快捷方式

torch.profiler

概述

PyTorch Profiler 是一款工具,用于在训练和推理期间收集性能指标。Profiler 的上下文管理器 API 可用于更好地理解哪些模型算子开销最大,检查其输入形状和堆栈跟踪,研究设备内核活动并可视化执行轨迹。

注意

torch.autograd 模块中较早版本的 API 被认为是遗留 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.CPUtorch.profiler.ProfilerActivity.CUDAtorch.profiler.ProfilerActivity.XPU。默认值:ProfilerActivity.CPU 以及(如果可用)ProfilerActivity.CUDA 或(如果可用)ProfilerActivity.XPU。

  • record_shapes (bool) – 保存有关算子输入形状的信息。

  • profile_memory (bool) – 跟踪张量内存分配/释放(有关更多详细信息,请参阅 export_memory_timeline)。

  • with_stack (bool) – 记录算子的源信息(文件和行号)。

  • with_flops (bool) – 使用公式估算特定算子(矩阵乘法和二维卷积)的 FLOPS。

  • with_modules (bool) – 记录与算子调用栈对应的模块层次结构(包括函数名)。例如,如果模块 A 的 forward 调用了模块 B 的 forward,而模块 B 包含一个 aten::add 算子,那么 aten::add 的模块层次结构是 A.B。请注意,目前此支持仅适用于 TorchScript 模型,而不适用于 Eager Mode 模型。

  • experimental_config (_ExperimentalConfig) – 性能分析库(如 Kineto)使用的一组实验性选项。请注意,不保证向后兼容性。

  • execution_trace_observer (ExecutionTraceObserver) – 一个 PyTorch 执行轨迹观察器对象。PyTorch 执行轨迹提供了 AI/ML 工作负载的基于图的表示,并支持回放基准测试、模拟器和仿真器。包含此参数时,观察器的 start() 和 stop() 方法将在与 PyTorch profiler 相同的时间窗口内被调用。

  • acc_events (bool) – 在多个性能分析周期中启用 FunctionEvents 的累积

注意

此 API 是实验性的,未来可能会更改。

启用形状和堆栈跟踪会带来额外的开销。指定 record_shapes=True 时,性能分析器会暂时持有张量的引用;这可能会进一步阻止依赖引用计数的某些优化,并引入额外的张量复制。

add_metadata(key, value)[source][source]

将具有字符串键和字符串值的用户定义元数据添加到跟踪文件中

add_metadata_json(key, value)[source][source]

将具有字符串键和有效 json 值的用户定义元数据添加到跟踪文件中

events()[source][source]

返回未聚合的性能分析事件列表,可在跟踪回调或性能分析完成后使用

export_chrome_trace(path)[source][source]

以 Chrome JSON 格式导出收集到的跟踪。如果 Kineto 已启用,则仅导出调度中的最后一个周期。

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] 之一,categorytorch.profiler._memory_profiler.Category 中的枚举之一。

输出:以 gzipped JSON、JSON 或 HTML 格式写入的内存时间线。

export_stacks(path, metric='self_cpu_time_total')[source][source]

将堆栈跟踪保存到文件

参数
  • path (str) – 将堆栈文件保存到此位置;

  • metric (str) – 要使用的指标:“self_cpu_time_total” 或 “self_cuda_time_total”

key_averages(group_by_input_shape=False, group_by_stack_n=0, group_by_overload_name=False)[source][source]

对事件进行平均,按算子名称以及(可选)输入形状、堆栈和重载名称进行分组。

注意

要使用形状/堆栈功能,请确保在创建性能分析器上下文管理器时设置 record_shapes/with_stack。

preset_metadata_json(key, value)[source][source]

在性能分析器未启动时预设用户定义的元数据,稍后将其添加到跟踪文件中。元数据的格式为字符串键和有效的 json 值

toggle_collection_dynamic(enable, activities)[source][source]

在收集过程中的任何时候切换活动收集的开启/关闭。目前支持切换 Torch 算子 (CPU) 和 Kineto 中支持的 CUDA 活动

参数

activities (iterable) – 要用于性能分析的活动组列表,支持的值:torch.profiler.ProfilerActivity.CPUtorch.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.CPUtorch.profiler.ProfilerActivity.CUDAtorch.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) – 使用公式估算特定算子(矩阵乘法和二维卷积)的 FLOPs(浮点运算)。

  • with_modules (bool) – 记录与算子调用栈对应的模块层次结构(包括函数名)。例如,如果模块 A 的 forward 调用了模块 B 的 forward,而模块 B 包含一个 aten::add 算子,那么 aten::add 的模块层次结构是 A.B。请注意,目前此支持仅适用于 TorchScript 模型,而不适用于 Eager Mode 模型。

  • experimental_config (_ExperimentalConfig) – 用于 Kineto 库功能的一组实验性选项。请注意,不保证向后兼容性。

  • execution_trace_observer (ExecutionTraceObserver) – 一个 PyTorch 执行轨迹观察器对象。PyTorch 执行轨迹提供了 AI/ML 工作负载的基于图的表示,并支持回放基准测试、模拟器和仿真器。包含此参数时,观察器的 start() 和 stop() 方法将在与 PyTorch profiler 相同的时间窗口内被调用。有关代码示例,请参阅下面的示例部分。

  • acc_events (bool) – 在多个性能分析周期中启用 FunctionEvents 的累积

  • use_cuda (bool) –

    自 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 接口的任何对象。

get_trace_id()[source][source]

返回当前的跟踪 ID。

set_custom_trace_id_callback(callback)[source][source]

设置一个回调函数,用于在新跟踪 ID 生成时被调用。

step()[source][source]

通知性能分析器下一个性能分析步骤已开始。

class torch.profiler.ProfilerAction(value)[source][source]

可在指定间隔执行的性能分析器操作

class torch.profiler.ProfilerActivity

成员

CPU

XPU

MTIA

CUDA

HPU

PrivateUse1

property name
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 步。所有后续周期则在上次 activity 和 warmup 之间等待 20 步。

返回类型

Callable

torch.profiler.tensorboard_trace_handler(dir_name, worker_name=None, use_gzip=False)[source][source]

将跟踪文件输出到 dir_name 目录,然后该目录可以直接作为 logdir 提供给 tensorboard。在分布式场景中,worker_name 应对于每个 worker 都是唯一的,默认情况下它将被设置为 ‘[hostname]_[pid]’。

Intel Instrumentation and Tracing Technology API

torch.profiler.itt.is_available()[source][source]

检查 ITT 功能是否可用

torch.profiler.itt.mark(msg)[source][source]

描述在某个时间点发生的瞬时事件。

参数

msg (str) – 与事件关联的 ASCII 消息。

torch.profiler.itt.range_push(msg)[source][source]

将一个范围推入嵌套范围跨度堆栈中。返回新启动范围的基于零的深度。

参数

msg (str) – 与范围关联的 ASCII 消息

torch.profiler.itt.range_pop()[source][source]

从嵌套范围跨度堆栈中弹出一个范围。返回结束范围的基于零的深度。

文档

查阅 PyTorch 的完整开发者文档

查看文档

教程

获取适合初学者和高级开发者的深度教程

查看教程

资源

查找开发资源并获得问题解答

查看资源