torch.profiler¶
概述¶
PyTorch Profiler 是一个工具,允许在训练和推理期间收集性能指标。Profiler 的上下文管理器 API 可用于更好地理解哪些模型运算符最耗时,检查它们的输入形状和堆栈跟踪,研究设备内核活动并可视化执行跟踪。
注意
在 torch.autograd
模块中早期版本的 API 被认为是过时的,并将被弃用。
API 参考¶
- class torch.profiler._KinetoProfile(*, activities=None, record_shapes=False, profile_memory=False, with_stack=False, with_flops=False, with_modules=False, experimental_config=None, execution_trace_observer=None, acc_events=False, custom_trace_id_callback=None)[source][source]¶
低级分析器包装 autograd 分析器
- 参数
activities (iterable) – 用于分析的活动组列表 (CPU, CUDA),支持的值:
torch.profiler.ProfilerActivity.CPU
,torch.profiler.ProfilerActivity.CUDA
,torch.profiler.ProfilerActivity.XPU
。默认值:ProfilerActivity.CPU 和 (可用时) ProfilerActivity.CUDA 或 (可用时) ProfilerActivity.XPU。record_shapes (bool) – 保存关于运算符输入形状的信息。
profile_memory (bool) – 跟踪张量内存分配/释放 (有关更多详细信息,请参阅
export_memory_timeline
)。with_stack (bool) – 记录运算符的源信息(文件和行号)。
with_flops (bool) – 使用公式估算特定运算符(矩阵乘法和 2D 卷积)的 FLOPS。
with_modules (bool) – 记录与运算符的调用堆栈相对应的模块层次结构(包括函数名称)。例如,如果模块 A 的前向调用模块 B 的前向,其中包含一个 aten::add 运算,则 aten::add 的模块层次结构为 A.B。请注意,目前此支持仅适用于 TorchScript 模型,而不适用于 eager 模式模型。
experimental_config (_ExperimentalConfig) – 由 Kineto 等分析器库使用的一组实验性选项。请注意,不保证向后兼容性。
execution_trace_observer (ExecutionTraceObserver) – PyTorch 执行跟踪观察器对象。PyTorch 执行跟踪提供 AI/ML 工作负载的基于图的表示,并支持重放基准测试、模拟器和仿真器。当包含此参数时,观察者的 start() 和 stop() 将在与 PyTorch 分析器相同的时间窗口内被调用。
acc_events (bool) – 启用跨多个分析周期的 FunctionEvents 累积
注意
此 API 是实验性的,将来可能会发生更改。
启用形状和堆栈跟踪会导致额外的开销。当指定 record_shapes=True 时,分析器将临时持有对张量的引用;这可能会进一步阻止某些依赖于引用计数的优化,并引入额外的张量副本。
- export_memory_timeline(path, device=None)[source][source]¶
从给定设备的分析器收集树导出内存事件信息,并导出时间线图。使用
export_memory_timeline
可以导出 3 个文件,每个文件都由path
的后缀控制。对于 HTML 兼容的绘图,请使用后缀
.html
,内存时间线图将作为 PNG 文件嵌入到 HTML 文件中。对于由
[times, [sizes by category]]
组成的绘图点,其中times
是时间戳,sizes
是每个类别的内存使用量。内存时间线图将保存为 JSON (.json
) 或 gzipped JSON (.json.gz
),具体取决于后缀。对于原始内存点,请使用后缀
.raw.json.gz
。每个原始内存事件将由(timestamp, action, numbytes, category)
组成,其中action
是[PREEXISTING, CREATE, INCREMENT_VERSION, DESTROY]
之一,category
是torch.profiler._memory_profiler.Category
中的枚举之一。
输出:内存时间线,以 gzipped JSON、JSON 或 HTML 格式写入。
- key_averages(group_by_input_shape=False, group_by_stack_n=0)[source][source]¶
平均事件,按运算符名称和(可选)输入形状和堆栈对它们进行分组。
注意
要使用形状/堆栈功能,请确保在创建分析器上下文管理器时设置 record_shapes/with_stack。
- preset_metadata_json(key, value)[source][source]¶
当分析器未启动时预设用户定义的元数据,并在稍后添加到跟踪文件中。元数据格式为字符串键和有效的 json 值
- toggle_collection_dynamic(enable, activities)[source][source]¶
在收集的任何点动态切换活动收集的开/关。目前支持切换 Torch Ops (CPU) 和 Kineto 中支持的 CUDA 活动
- 参数
activities (iterable) – 用于分析的活动组列表,支持的值:
torch.profiler.ProfilerActivity.CPU
,torch.profiler.ProfilerActivity.CUDA
示例
with torch.profiler.profile( activities=[ torch.profiler.ProfilerActivity.CPU, torch.profiler.ProfilerActivity.CUDA, ] ) as p: code_to_profile_0() // turn off collection of all CUDA activity p.toggle_collection_dynamic(False, [torch.profiler.ProfilerActivity.CUDA]) code_to_profile_1() // turn on collection of all CUDA activity p.toggle_collection_dynamic(True, [torch.profiler.ProfilerActivity.CUDA]) code_to_profile_2() print(p.key_averages().table( sort_by="self_cuda_time_total", row_limit=-1))
- class torch.profiler.profile(*, activities=None, schedule=None, on_trace_ready=None, record_shapes=False, profile_memory=False, with_stack=False, with_flops=False, with_modules=False, experimental_config=None, execution_trace_observer=None, acc_events=False, use_cuda=None, custom_trace_id_callback=None)[source][source]¶
分析器上下文管理器。
- 参数
activities (iterable) – 用于分析的活动组列表 (CPU, CUDA),支持的值:
torch.profiler.ProfilerActivity.CPU
,torch.profiler.ProfilerActivity.CUDA
,torch.profiler.ProfilerActivity.XPU
。默认值:ProfilerActivity.CPU 和 (可用时) ProfilerActivity.CUDA 或 (可用时) ProfilerActivity.XPU。schedule (Callable) – 可调用对象,它接受 step (int) 作为单个参数,并返回
ProfilerAction
值,该值指定在每个步骤执行的分析器操作。on_trace_ready (Callable) – 可调用对象,在
schedule
返回ProfilerAction.RECORD_AND_SAVE
时在每个步骤调用分析期间。record_shapes (bool) – 保存关于运算符输入形状的信息。
profile_memory (bool) – 跟踪张量内存分配/释放。
with_stack (bool) – 记录运算符的源信息(文件和行号)。
with_flops (bool) – 使用公式估算特定运算符(矩阵乘法和 2D 卷积)的 FLOPs(浮点运算)。
with_modules (bool) – 记录与运算符的调用堆栈相对应的模块层次结构(包括函数名称)。例如,如果模块 A 的前向调用模块 B 的前向,其中包含一个 aten::add 运算,则 aten::add 的模块层次结构为 A.B。请注意,目前此支持仅适用于 TorchScript 模型,而不适用于 eager 模式模型。
experimental_config (_ExperimentalConfig) – 用于 Kineto 库功能的一组实验性选项。请注意,不保证向后兼容性。
execution_trace_observer (ExecutionTraceObserver) – PyTorch 执行跟踪观察器对象。PyTorch 执行跟踪提供 AI/ML 工作负载的基于图的表示,并支持重放基准测试、模拟器和仿真器。当包含此参数时,观察者的 start() 和 stop() 将在与 PyTorch 分析器相同的时间窗口内被调用。有关代码示例,请参见下面的示例部分。
acc_events (bool) – 启用跨多个分析周期的 FunctionEvents 累积
use_cuda (bool) –
Deprecated since version 1.8.1: 使用
activities
代替。
注意
使用
schedule()
生成可调用计划。当分析长时间的训练作业时,非默认计划非常有用,并允许用户在训练过程的不同迭代中获得多个跟踪。默认计划只是在上下文管理器的持续时间内连续记录所有事件。注意
使用
tensorboard_trace_handler()
为 TensorBoard 生成结果文件on_trace_ready=torch.profiler.tensorboard_trace_handler(dir_name)
分析后,可以在指定目录中找到结果文件。使用命令
tensorboard --logdir dir_name
在 TensorBoard 中查看结果。有关更多信息,请参阅 PyTorch Profiler TensorBoard 插件
注意
启用形状和堆栈跟踪会导致额外的开销。当指定 record_shapes=True 时,分析器将临时持有对张量的引用;这可能会进一步阻止某些依赖于引用计数的优化,并引入额外的张量副本。
示例
with torch.profiler.profile( activities=[ torch.profiler.ProfilerActivity.CPU, torch.profiler.ProfilerActivity.CUDA, ] ) as p: code_to_profile() print(p.key_averages().table( sort_by="self_cuda_time_total", row_limit=-1))
使用分析器的
schedule
、on_trace_ready
和step
函数# Non-default profiler schedule allows user to turn profiler on and off # on different iterations of the training loop; # trace_handler is called every time a new trace becomes available def trace_handler(prof): print(prof.key_averages().table( sort_by="self_cuda_time_total", row_limit=-1)) # prof.export_chrome_trace("/tmp/test_trace_" + str(prof.step_num) + ".json") with torch.profiler.profile( activities=[ torch.profiler.ProfilerActivity.CPU, torch.profiler.ProfilerActivity.CUDA, ], # In this example with wait=1, warmup=1, active=2, repeat=1, # profiler will skip the first step/iteration, # start warming up on the second, record # the third and the forth iterations, # after which the trace will become available # and on_trace_ready (when set) is called; # the cycle repeats starting with the next step schedule=torch.profiler.schedule( wait=1, warmup=1, active=2, repeat=1), on_trace_ready=trace_handler # on_trace_ready=torch.profiler.tensorboard_trace_handler('./log') # used when outputting for tensorboard ) as p: for iter in range(N): code_iteration_to_profile(iter) # send a signal to the profiler that the next iteration has started p.step()
以下示例显示如何设置执行跟踪观察器 (execution_trace_observer)
with torch.profiler.profile( ... execution_trace_observer=( ExecutionTraceObserver().register_callback("./execution_trace.json") ), ) as p: for iter in range(N): code_iteration_to_profile(iter) p.step()
您还可以参考 tests/profiler/test_profiler.py 中的 test_execution_trace_with_kineto()。注意:也可以传递任何满足 _ITraceObserver 接口的对象。
- torch.profiler.schedule(*, wait, warmup, active, repeat=0, skip_first=0, skip_first_wait=0)[source][source]¶
返回一个可调用对象,可以用作分析器
schedule
参数。分析器将跳过前skip_first
步,然后等待wait
步,然后对接下来的warmup
步进行预热,然后对接下来的active
步进行活动记录,然后重复以wait
步开始的循环。可选的循环次数由repeat
参数指定,零值表示循环将持续到分析完成。skip_first_wait
参数控制是否应跳过第一个wait
阶段。如果用户希望在周期之间等待的时间长于skip_first
,但不是针对第一个配置文件,这将很有用。例如,如果skip_first
为 10,wait
为 20,则如果skip_first_wait
为零,则第一个周期将在预热前等待 10 + 20 = 30 步,但如果skip_first_wait
为非零值,则仅等待 10 步。然后,所有后续周期将在上一个活动和预热之间等待 20 步。- 返回类型