Accelerate documentation
プロファイラー
プロファイラー
Profilerは、学習および推論中にパフォーマンス指標を収集できるツールです。ProfilerのコンテキストマネージャーAPIを使用することで、どのモデル演算子が最もコストが高いかを理解し、その入力形状やスタックトレースを調べ、デバイスのカーネルアクティビティを分析し、実行トレースを可視化できます。モデルのパフォーマンスに関する洞察を提供し、最適化と改善を可能にします。
このガイドでは、PyTorch Profiler を使用してモデルの演算子の時間とメモリ消費量を測定する方法、および Accelerate との統合方法について説明します。さまざまなユースケースを取り上げ、それぞれに例を示します。
プロファイラーを使用して実行時間を分析する
Profilerを使用すると、プロファイラコンテキストマネージャでラップされたコード範囲の実行中にどのオペレーターが呼び出されたかをチェックできます。
プロファイラーを使用して実行時間を分析する方法を見てみましょう:
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))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 で実行することを必要とします):
print(prof.key_averages(group_by_input_shape=True).table(sort_by="cpu_time_total", row_limit=10))プロファイラーを使用してメモリ消費量を分析する
Profiler は、モデルの演算子の実行中に割り当てられた(または解放された)メモリ量(モデルのテンソルによって使用されるもの)も表示できます。メモリプロファイリング機能を有効にするには、profile_memory=True を渡します。
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))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実験の追跡のために、完全なオペレーターテーブルではなく1つか2つの集計値が必要な場合は、プロファイラーとPyTorchが公開するランタイムメモリ統計を組み合わせます。これにより、実行ごとのピークメモリ使用量をログに記録するには通常十分です。
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トレースのエクスポート
Chrome trace viewer(chrome://tracing)で、プロファイルされたオペレーターとCUDAカーネルのシーケンスを確認できます。
# 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")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 directoryProfilerを使用して長時間実行されるジョブを分析する
Profilerには、長時間実行されるジョブ(トレーニングループなど)を処理するための追加のAPIが用意されています。実行全体をトレースすると遅くなる場合があり、非常に大きなトレースファイルが生成される可能性があります。これを避けるために、任意の引数を使用します:
schedule_option: スケジューリングオプションにより、プロファイリングが有効になるタイミングを制御できます。これは、長時間実行されるジョブにおいて、データ収集量が多すぎることになるのを避けるために役立ちます。利用可能なキーはwait、warmup、active、repeat、skip_firstです。プロファイラーは最初のskip_firstステップをスキップし、次にwaitステップ待機し、次のwarmupステップでウォームアップを行い、次のactiveステップでアクティブな記録を行い、その後waitステップからサイクルを繰り返します。サイクルの任意の回数はrepeatパラメータで指定され、ゼロの値は、プロファイリングが完了するまでサイクルが継続されることを意味します。on_trace_ready: プロファイラーへの参照を入力として受け取り、新しいトレースが準備できたたびにプロファイラーによって呼び出される関数を指定します。
APIの動作を説明するために、以下の例を検討してください。
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()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
数式を使用して、特定のオペレーター(行列積および2D畳み込み)のFLOPs(浮動小数点演算)を推定します。
浮動小数点演算(FLOPS)を測定するには:
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))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のドキュメントを参照してください。
Update on GitHub