# Profiler

Profiler 是一款用于在训练和推理过程中收集性能指标的工具。Profiler 的上下文管理器 API 可用于深入了解哪些模型算子开销最大，检查它们的输入形状和堆栈跟踪，研究设备内核活动，并可视化执行跟踪。它提供了有关模型性能的见解，从而帮助你对其进行优化和改进。

本指南介绍如何使用 PyTorch Profiler 来测量模型算子的时间和内存消耗，以及如何将其与 Accelerate 集成。我们将涵盖各种使用场景，并为每个场景提供示例。

## 使用 profiler 分析执行时间

Profiler 允许检查在由 profiler 上下文管理器包裹的代码范围执行期间调用了哪些算子。

让我们看看如何使用 profiler 来分析执行时间：

```python
import torch
import torchvision.models as models
from torch.profiler import profile, record_function, ProfilerActivity

model = models.resnet18()
inputs = torch.randn(5, 3, 224, 224)

with profile(activities=[ProfilerActivity.CPU], record_shapes=True) as prof:
    model(inputs)

print(prof.key_averages().table(sort_by="cpu_time_total", row_limit=10))
```

```python
from accelerate import Accelerator, ProfileKwargs
import torch
import torchvision.models as models

model = models.resnet18()
inputs = torch.randn(5, 3, 224, 224)

profile_kwargs = ProfileKwargs(
    activities=["cpu"],
    record_shapes=True
)

accelerator = Accelerator(cpu=True, kwargs_handlers=[profile_kwargs])
model = accelerator.prepare(model)

with accelerator.profile() as prof:
    with torch.no_grad():
        model(inputs)

print(prof.key_averages().table(sort_by="cpu_time_total", row_limit=10))
```

生成的表格输出（省略了部分列）：

```
---------------------------------  ------------  ------------  ------------  ------------  
                             Name      Self CPU     CPU total  CPU time avg    # of Calls  
---------------------------------  ------------  ------------  ------------  ------------  
                     aten::conv2d     171.000us      52.260ms       2.613ms            20  
                aten::convolution     227.000us      52.089ms       2.604ms            20  
               aten::_convolution     270.000us      51.862ms       2.593ms            20  
         aten::mkldnn_convolution      51.273ms      51.592ms       2.580ms            20  
                 aten::batch_norm     118.000us       7.059ms     352.950us            20  
     aten::_batch_norm_impl_index     315.000us       6.941ms     347.050us            20  
          aten::native_batch_norm       6.305ms       6.599ms     329.950us            20  
                 aten::max_pool2d      40.000us       4.008ms       4.008ms             1  
    aten::max_pool2d_with_indices       3.968ms       3.968ms       3.968ms             1  
                       aten::add_     780.000us     780.000us      27.857us            28  
---------------------------------  ------------  ------------  ------------  ------------  
Self CPU time total: 67.016ms
```

要获得更细粒度的结果并包含算子输入形状，请传入 `group_by_input_shape=True`（注意：这要求使用 `record_shapes=True` 运行分析器）：

```python
print(prof.key_averages(group_by_input_shape=True).table(sort_by="cpu_time_total", row_limit=10))
```

## 使用 profiler 分析内存消耗

Profiler 还可以显示在执行模型算子期间分配（或释放）的内存量（由模型的张量使用）。要启用内存分析功能，请传入 `profile_memory=True`。

```python
model = models.resnet18()
inputs = torch.randn(5, 3, 224, 224)

with profile(activities=[ProfilerActivity.CPU],
        profile_memory=True, record_shapes=True) as prof:
    model(inputs)

print(prof.key_averages().table(sort_by="self_cpu_memory_usage", row_limit=10))
```

```python
model = models.resnet18()
inputs = torch.randn(5, 3, 224, 224)

profile_kwargs = ProfileKwargs(
    activities=["cpu"],
    profile_memory=True,
    record_shapes=True
)

accelerator = Accelerator(cpu=True, kwargs_handlers=[profile_kwargs])
model = accelerator.prepare(model)

with accelerator.profile() as prof:
    model(inputs)

print(prof.key_averages().table(sort_by="self_cpu_memory_usage", row_limit=10))
```

生成的表格输出（省略了部分列）：

```
---------------------------------  ------------  ------------  ------------  
                             Name       CPU Mem  Self CPU Mem    # of Calls  
---------------------------------  ------------  ------------  ------------  
                      aten::empty      94.85 Mb      94.85 Mb           205  
    aten::max_pool2d_with_indices      11.48 Mb      11.48 Mb             1  
                      aten::addmm      19.53 Kb      19.53 Kb             1  
                       aten::mean      10.00 Kb      10.00 Kb             1  
              aten::empty_strided         492 b         492 b             5  
                        aten::cat         240 b         240 b             6  
                        aten::abs         480 b         240 b             4  
              aten::masked_select         120 b         112 b             1  
                         aten::ne          61 b          53 b             3  
                         aten::eq          30 b          30 b             1  
---------------------------------  ------------  ------------  ------------  
Self CPU time total: 69.332ms
```

如果你只需要一两个用于实验跟踪的汇总数值，而不是完整的算子表格，可以将性能分析器与 PyTorch 暴露的运行时内存统计信息结合使用。这通常足以记录每次运行的峰值内存使用情况：

```python
import torch
from accelerate import Accelerator, PartialState, ProfileKwargs

# Resolve the device type/module (cuda, xpu, ...) instead of hardcoding CUDA
device_type = PartialState().device.type
device_module = getattr(torch, device_type)

def summarize_memory_stats():
    return {
        "peak_allocated_mb": device_module.max_memory_allocated() / 1024**2,
        "peak_reserved_mb": device_module.max_memory_reserved() / 1024**2,
    }

profile_kwargs = ProfileKwargs(
    activities=["cpu", device_type],
    profile_memory=True,
    record_shapes=True,
)

accelerator = Accelerator(kwargs_handlers=[profile_kwargs])

device_module.reset_peak_memory_stats()

with accelerator.profile() as prof:
    model(inputs)

print(prof.key_averages().table(sort_by=f"self_{device_type}_memory_usage", row_limit=10))
print(summarize_memory_stats())
```

这种模式在保留分析器输出以便调试的同时，还能生成紧凑的值，以便记录到实验跟踪器中。

## 导出 chrome trace

您可以在 Chrome 跟踪查看器（`chrome://tracing`）中查看已分析的操作和 CUDA 内核序列：

![profile_export](https://github.com/huggingface/accelerate/assets/100389977/5acb193f-6d11-4f7b-9873-c600c19e8172)

```python
# Pick the available accelerator (cuda, xpu, ...) instead of hardcoding CUDA
device = torch.accelerator.current_accelerator()
device_activity = getattr(ProfilerActivity, device.type.upper())

model = models.resnet18().to(device)
inputs = torch.randn(5, 3, 224, 224).to(device)

with profile(activities=[ProfilerActivity.CPU, device_activity]) as prof:
    model(inputs)

prof.export_chrome_trace("trace.json")
```

```python
model = models.resnet18()
profile_kwargs = ProfileKwargs(
    activities=["cpu", PartialState().device.type],
    output_trace_dir="trace"
)

accelerator = Accelerator(kwargs_handlers=[profile_kwargs])
model = accelerator.prepare(model)
inputs = torch.randn(5, 3, 224, 224).to(accelerator.device)

with accelerator.profile() as prof:
    model(inputs)

# The trace will be saved to the specified directory
```

## 使用 Profiler 分析长时间运行的任务

Profiler 提供了一个额外的 API 来处理长时间运行的任务（例如训练循环）。追踪所有执行过程可能会很慢，并生成非常大的 trace 文件。为避免这种情况，请使用可选参数：

- `schedule_option`：调度选项允许您控制性能分析何时处于激活状态。这对于长时间运行的任务非常有用，可以避免收集过多的数据。可用的键为 `wait`、`warmup`、`active`、`repeat` 和 `skip_first`。性能分析器将跳过前 `skip_first` 个步骤，然后等待 `wait` 个步骤，接着对接下来的 `warmup` 个步骤进行预热，再对接下来的 `active` 个步骤进行激活记录，然后从 `wait` 个步骤开始重复该循环。可选的循环次数由 `repeat` 参数指定，零值表示循环将持续进行，直到性能分析结束。
- `on_trace_ready`：指定一个函数，该函数以 profiler 的引用作为输入，并在每次新 trace 就绪时由 profiler 调用。

为了说明该 API 的工作方式，请考虑以下示例：

```python
from torch.profiler import schedule

my_schedule = schedule(
    skip_first=1,
    wait=5,
    warmup=1,
    active=3,
    repeat=2
)

def trace_handler(p):
    output = p.key_averages().table(sort_by=f"self_{device.type}_time_total", row_limit=10)
    print(output)
    p.export_chrome_trace("/tmp/trace_" + str(p.step_num) + ".json")

with profile(
    activities=[ProfilerActivity.CPU, device_activity],
    schedule=my_schedule,
    on_trace_ready=trace_handler
) as p:
    for idx in range(8):
        model(inputs)
        p.step()
```

```python
device_type = PartialState().device.type

def trace_handler(p):
    output = p.key_averages().table(sort_by=f"self_{device_type}_time_total", row_limit=10)
    print(output)
    p.export_chrome_trace("/tmp/trace_" + str(p.step_num) + ".json")

profile_kwargs = ProfileKwargs(
    activities=["cpu", device_type],
    schedule_option={"wait": 5, "warmup": 1, "active": 3, "repeat": 2, "skip_first": 1},
    on_trace_ready=trace_handler
)

accelerator = Accelerator(kwargs_handlers=[profile_kwargs])
model = accelerator.prepare(model)

with accelerator.profile() as prof:
    for idx in range(8):
        model(inputs)
        prof.step()
```

## FLOPS

使用公式来估算特定算子（矩阵乘法和二维卷积）的 FLOPs（浮点运算次数）。

要测量浮点运算（FLOPS）：

```python
with profile(
    activities=[ProfilerActivity.CPU, device_activity],
    with_flops=True
) as prof:
    model(inputs)

print(prof.key_averages().table(sort_by="flops", row_limit=10))
```

```python
profile_kwargs = ProfileKwargs(
    with_flops=True
)
accelerator = Accelerator(kwargs_handlers=[profile_kwargs])

with accelerator.profile() as prof:
    model(inputs)

print(prof.key_averages().table(sort_by="flops", row_limit=10))
```

生成的表格输出（省略了部分列）：

```
-------------------------------------------------------  ------------  ------------  ------------  
                                                   Name      Self CPU     Self CUDA    Total FLOPs  
-------------------------------------------------------  ------------  ------------  ------------  
                                           aten::conv2d     197.000us       0.000us  18135613440.000  
                                            aten::addmm     103.000us      17.000us     5120000.000  
                                              aten::mul      29.000us       2.000us          30.000  
                                      aten::convolution     409.000us       0.000us            --  
                                     aten::_convolution     253.000us       0.000us            --  
                                aten::cudnn_convolution       5.465ms       2.970ms            --  
                                        cudaEventRecord     138.000us       0.000us            --  
                                  cudaStreamIsCapturing      43.000us       0.000us            --  
                                  cudaStreamGetPriority      40.000us       0.000us            --  
                       cudaDeviceGetStreamPriorityRange      10.000us       0.000us            --  
-------------------------------------------------------  ------------  ------------  ------------  
Self CPU time total: 21.938ms
Self CUDA time total: 4.165ms
```

## 结论与更多信息

PyTorch Profiler 是一款用于分析模型性能的强有力工具。通过将其与 Accelerate 集成，你可以轻松地对模型进行性能分析，深入了解其性能表现，从而帮助优化和改进模型。

有关更详细的信息，请参阅 [PyTorch Profiler 文档](https://pytorch.org/docs/stable/profiler.html)。

