Accelerate 文件

效能分析器

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

效能分析器

效能分析器(Profiler)是一種在訓練和推理過程中收集效能指標的工具。Profiler 的上下文管理器 API 可以用於更好地理解哪些模型運算子最耗時,檢查它們的輸入形狀和堆疊跟蹤,研究裝置核心活動,並可視化執行軌跡。它提供了對模型效能的深入瞭解,使您能夠對其進行最佳化和改進。

本指南解釋瞭如何使用 PyTorch Profiler 來測量模型運算子的時間和記憶體消耗,以及如何將其與 Accelerate 整合。我們將涵蓋各種用例併為每個用例提供示例。

使用效能分析器分析執行時間

效能分析器允許檢查在使用效能分析器上下文管理器包裝的程式碼範圍內,執行期間呼叫了哪些運算子。

讓我們看看如何使用效能分析器來分析執行時間

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

生成的表格輸出(省略部分列)

---------------------------------  ------------  ------------  ------------  ------------  
                             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` 的情況下執行效能分析器)

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

使用效能分析器分析記憶體消耗

效能分析器還可以顯示在模型運算子執行期間分配(或釋放)的記憶體量(由模型的張量使用)。要啟用記憶體分析功能,請傳遞 `profile_memory=True`。

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

生成的表格輸出(省略部分列)

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

匯出 Chrome 跟蹤

您可以在 Chrome 跟蹤檢視器 (`chrome://tracing`) 中檢查分析的運算子和 CUDA 核心的序列。

profile_export

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

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

prof.export_chrome_trace("trace.json")

使用效能分析器分析長時間執行的作業

效能分析器提供了一個額外的 API 來處理長時間執行的作業(例如訓練迴圈)。跟蹤所有執行過程可能會很慢,並導致生成非常大的跟蹤檔案。為避免這種情況,請使用可選引數

  • `schedule_option`:排程選項允許您控制性能分析的活動時間。這對於長時間執行的作業很有用,可以避免收集過多的資料。可用的鍵是 `wait`、`warmup`、`active`、`repeat` 和 `skip_first`。效能分析器將跳過前 `skip_first` 步,然後等待 `wait` 步,接著為接下來的 `warmup` 步進行預熱,然後為接下來的 `active` 步進行活動記錄,最後從 `wait` 步開始重複這個週期。可選的週期數由 `repeat` 引數指定,值為零意味著週期將持續到效能分析結束。
  • `on_trace_ready`:指定一個函式,該函式接收效能分析器的引用作為輸入,並在每次新跟蹤準備就緒時由效能分析器呼叫。

為了說明 API 的工作原理,請看下面的示例

PyTorch
Accelerate
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="self_cuda_time_total", row_limit=10)
    print(output)
    p.export_chrome_trace("/tmp/trace_" + str(p.step_num) + ".json")

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

FLOPS

使用公式估算特定運算子(矩陣乘法和 2D 卷積)的 FLOPs(浮點運算次數)。

要測量浮點運算次數 (FLOPS)

PyTorch
Accelerate
with profile(
    activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA],
    with_flops=True
) 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 文件

< > 在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.