目录

torch.profiler

概述

PyTorch Profiler 是一个工具,允许在训练和推理过程中收集性能指标。 Profiler 的上下文管理器 API 可用于更好地了解哪些模型操作最耗时, 检查它们的输入形状和堆栈跟踪,研究设备内核活动并可视化执行轨迹。

注意

早期版本的API在torch.autograd模块中被认为是旧版,并将被弃用。

API 参考

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, use_cuda=None)[source]

性能分析器上下文管理器。

Parameters
  • activities (iterable) – 用于分析的活动组(CPU、CUDA)列表,支持的值: torch.profiler.ProfilerActivity.CPU, torch.profiler.ProfilerActivity.CUDA. 默认值: ProfilerActivity.CPU 和(当可用时)ProfilerActivity.CUDA。

  • schedule (Callable) – 可调用对象,接受 step(整数)作为唯一参数,并返回 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 的前向调用中包含模块 B 的前向调用, 而模块 B 中有一个 aten::add 操作, 那么 aten::add 的模块层次结构为 A.B。 请注意,目前此功能仅支持 TorchScript 模型,而不支持即时模式模型。

  • 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 时,分析器会暂时持有张量的引用; 这可能会进一步阻止依赖于引用计数的某些优化,并引入额外的张量复制。

Examples:

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))

使用分析器的 scheduleon_trace_readystep 函数:

# 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,
    # 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),
    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()
add_metadata(key, value)[source]

将一个由用户定义的元数据(包含字符串键和字符串值)添加到跟踪文件中

add_metadata_json(key, value)[source]

添加一个用户定义的元数据,其中键为字符串,值为有效的 JSON 数据到跟踪文件中

events()[source]

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

export_chrome_trace(path)[source]

以 Chrome JSON 格式导出收集的跟踪信息。

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

将堆栈跟踪以适合可视化的格式保存到文件中。

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

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

注意

使用 FlameGraph 工具的示例:

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

按操作符名称和(可选)输入形状及堆栈对事件进行分组并求平均值。

注意

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

step()[source]

表示分析器下一个分析步骤已开始。

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

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

class torch.profiler.ProfilerActivity

Members:

CPU

CUDA

property name
torch.profiler.schedule(*, wait, warmup, active, repeat=0, skip_first=0)[source]

返回一个可调用对象,可用作分析器 schedule 参数。分析器将跳过前 skip_first 步,然后等待 wait 步,接着对接下来的 warmup 步进行预热, 然后对接下来的 active 步进行活动记录,之后从 wait 步开始重复该周期。可以通过 repeat 参数指定可选的周期数,零值表示周期将持续到分析完成为止。

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

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

文档

访问 PyTorch 的全面开发人员文档

查看文档

教程

获取面向初学者和高级开发人员的深入教程

查看教程

资源

查找开发资源并解答您的问题

查看资源