使用 torch.profiler记录模型训练轨迹,并使用Tensorboard进行可视化分析,首先导入需要的库,准备模型和数据集,设置记录器,生成json格式的文件,最后通过Tensorboard可视化。
Steps
- Prepare the data and model
- Use profiler to record execution events
- Run the profiler
- Use TensorBoard to view results and analyze model performance
- Improve performance with the help of profiler
- Analyze performance with other advanced features
- Additional Practices: Profiling PyTorch on AMD GPUs
1. Prepare the data and model
导入需要的库:
1 | import torch |
准备数据集
1 | transform = T.Compose( |
模型定义
1 | device = torch.device("cuda:0") |
模型训练
1 | def train(data): |
2. 使用Profiler记录轨迹
some useful parameters are as follow:
schedule: 参数例如wait=1,warmup=1,active=3,repeat=1(profiler 会跳过第一个step/iteration,在第二个iter热身,记录三个iter。). In total, the cycle repeats once. Each cycle is called a “span” in TensorBoard plugin.
在wait阶段,profiler 不生效,在warmup 阶段,proliler 开始工作但不记录结果,是为了减少开销,proliling 的开始开销很大,会影响结果。
on_trace_ready : 在每个cylce结束时调用,例如使用torch.profiler.tensorboard_trace_handler来时生成Tensorboard使用的结果文件,在Profiling后,结果文件存储在./log/resnet18中。
record_shapes:是否记录输入张亮的形状
profile_memory: 追踪张量空间申请和释放。
with_stack:记录算子的代码信息,如果在vscode中集成TensorBoard, 单击可以跳转到特定行。
https://code.visualstudio.com/docs/datascience/pytorch-support#_tensorboard-integration
以上下文管理器启动/停止:
1 | with torch.profiler.profile( |
也可以以非上下文管理器启动/停止:
1 | prof = torch.profiler.profile( |
3. 运行profiler
4. 使用Tensorboard展示结果
安装Pytorch Profiler TensorBoard Plugin
1 | pip install torch_tb_profiler |
登录TensorBoard
1 | tensorboard --logdir=./log |
打开TensorBoard
1 | http://localhost:6006/#pytorch_profiler |