Debian Codegraph @

docs/source/usage_guides/profiler.md

raw
1 <!--
2 Copyright 2024 The HuggingFace Team. All rights reserved.
3
4 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 the License. You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 specific language governing permissions and limitations under the License.
12
13 ⚠️ Note that this file is in Markdown but contains specific syntax for our doc-builder (similar to MDX) that may not be
14 rendered properly in your Markdown viewer.
15 -->
16
17 # Profiler
18
19 Profiler is a tool that allows the collection of performance metrics during training and inference. Profiler’s context manager API can be used to better understand what model operators are the most expensive, examine their input shapes and stack traces, study device kernel activity, and visualize the execution trace. It provides insights into the performance of your model, allowing you to optimize and improve it.
20
21 This guide explains how to use PyTorch Profiler to measure the time and memory consumption of the model’s operators and how to integrate this with Accelerate. We will cover various use cases and provide examples for each.
22
23 ## Using profiler to analyze execution time
24
25 Profiler allows one to check which operators were called during the execution of a code range wrapped with a profiler context manager.
26
27 Let’s see how we can use profiler to analyze the execution time:
28
29 <hfoptions id="cpu execution time">
30 <hfoption id="PyTorch">
31
32 ```python
33 import torch
34 import torchvision.models as models
35 from torch.profiler import profile, record_function, ProfilerActivity
36
37 model = models.resnet18()
38 inputs = torch.randn(5, 3, 224, 224)
39
40 with profile(activities=[ProfilerActivity.CPU], record_shapes=True) as prof:
41 model(inputs)
42
43 print(prof.key_averages().table(sort_by="cpu_time_total", row_limit=10))
44 ```
45
46 </hfoption>
47 <hfoption id="Accelerate">
48
49 ```python
50 from accelerate import Accelerator, ProfileKwargs
51 import torch
52 import torchvision.models as models
53
54 model = models.resnet18()
55 inputs = torch.randn(5, 3, 224, 224)
56
57 profile_kwargs = ProfileKwargs(
58 activities=["cpu"],
59 record_shapes=True
60 )
61
62 accelerator = Accelerator(cpu=True, kwargs_handlers=[profile_kwargs])
63 model = accelerator.prepare(model)
64
65 with accelerator.profile() as prof:
66 with torch.no_grad():
67 model(inputs)
68
69 print(prof.key_averages().table(sort_by="cpu_time_total", row_limit=10))
70 ```
71
72 </hfoption>
73 </hfoptions>
74
75 The resulting table output (omitting some columns):
76
77 ```
78 --------------------------------- ------------ ------------ ------------ ------------
79 Name Self CPU CPU total CPU time avg # of Calls
80 --------------------------------- ------------ ------------ ------------ ------------
81 aten::conv2d 171.000us 52.260ms 2.613ms 20
82 aten::convolution 227.000us 52.089ms 2.604ms 20
83 aten::_convolution 270.000us 51.862ms 2.593ms 20
84 aten::mkldnn_convolution 51.273ms 51.592ms 2.580ms 20
85 aten::batch_norm 118.000us 7.059ms 352.950us 20
86 aten::_batch_norm_impl_index 315.000us 6.941ms 347.050us 20
87 aten::native_batch_norm 6.305ms 6.599ms 329.950us 20
88 aten::max_pool2d 40.000us 4.008ms 4.008ms 1
89 aten::max_pool2d_with_indices 3.968ms 3.968ms 3.968ms 1
90 aten::add_ 780.000us 780.000us 27.857us 28
91 --------------------------------- ------------ ------------ ------------ ------------
92 Self CPU time total: 67.016ms
93 ```
94
95 To get a finer granularity of results and include operator input shapes, pass `group_by_input_shape=True` (note: this requires running the profiler with `record_shapes=True`):
96
97 ```python
98 print(prof.key_averages(group_by_input_shape=True).table(sort_by="cpu_time_total", row_limit=10))
99 ```
100
101 ## Using profiler to analyze memory consumption
102
103 Profiler can also show the amount of memory (used by the model’s tensors) that was allocated (or released) during the execution of the model’s operators. To enable memory profiling functionality pass `profile_memory=True`.
104
105 <hfoptions id="memory consumption">
106 <hfoption id="PyTorch">
107
108 ```python
109 model = models.resnet18()
110 inputs = torch.randn(5, 3, 224, 224)
111
112 with profile(activities=[ProfilerActivity.CPU],
113 profile_memory=True, record_shapes=True) as prof:
114 model(inputs)
115
116 print(prof.key_averages().table(sort_by="self_cpu_memory_usage", row_limit=10))
117 ```
118
119 </hfoption>
120 <hfoption id="Accelerate">
121
122 ```python
123 model = models.resnet18()
124 inputs = torch.randn(5, 3, 224, 224)
125
126 profile_kwargs = ProfileKwargs(
127 activities=["cpu"],
128 profile_memory=True,
129 record_shapes=True
130 )
131
132 accelerator = Accelerator(cpu=True, kwargs_handlers=[profile_kwargs])
133 model = accelerator.prepare(model)
134
135 with accelerator.profile() as prof:
136 model(inputs)
137
138 print(prof.key_averages().table(sort_by="self_cpu_memory_usage", row_limit=10))
139 ```
140
141 </hfoption>
142 </hfoptions>
143
144 The resulting table output (omitting some columns):
145
146 ```
147 --------------------------------- ------------ ------------ ------------
148 Name CPU Mem Self CPU Mem # of Calls
149 --------------------------------- ------------ ------------ ------------
150 aten::empty 94.85 Mb 94.85 Mb 205
151 aten::max_pool2d_with_indices 11.48 Mb 11.48 Mb 1
152 aten::addmm 19.53 Kb 19.53 Kb 1
153 aten::mean 10.00 Kb 10.00 Kb 1
154 aten::empty_strided 492 b 492 b 5
155 aten::cat 240 b 240 b 6
156 aten::abs 480 b 240 b 4
157 aten::masked_select 120 b 112 b 1
158 aten::ne 61 b 53 b 3
159 aten::eq 30 b 30 b 1
160 --------------------------------- ------------ ------------ ------------
161 Self CPU time total: 69.332ms
162 ```
163
164 If you need one or two aggregate numbers for experiment tracking instead of a full operator table, combine the profiler with the runtime memory stats exposed by PyTorch. This is often enough for logging peak memory usage per run:
165
166 ```python
167 import torch
168 from accelerate import Accelerator, ProfileKwargs
169
170
171 def summarize_memory_stats():
172 return {
173 "peak_allocated_mb": torch.cuda.max_memory_allocated() / 1024**2,
174 "peak_reserved_mb": torch.cuda.max_memory_reserved() / 1024**2,
175 }
176
177
178 profile_kwargs = ProfileKwargs(
179 activities=["cpu", "cuda"],
180 profile_memory=True,
181 record_shapes=True,
182 )
183
184 accelerator = Accelerator(kwargs_handlers=[profile_kwargs])
185
186 torch.cuda.reset_peak_memory_stats()
187
188 with accelerator.profile() as prof:
189 model(inputs)
190
191 print(prof.key_averages().table(sort_by="self_cuda_memory_usage", row_limit=10))
192 print(summarize_memory_stats())
193 ```
194
195 This pattern keeps the profiler output available for debugging while also producing compact values that can be logged to an experiment tracker.
196
197
198 ## Exporting chrome trace
199
200 You can examine the sequence of profiled operators and CUDA kernels in Chrome trace viewer (`chrome://tracing`):
201
202 ![profile_export](https://github.com/huggingface/accelerate/assets/100389977/5acb193f-6d11-4f7b-9873-c600c19e8172)
203
204 <hfoptions id="exporting chrome trace">
205 <hfoption id="PyTorch">
206
207 ```python
208 model = models.resnet18().cuda()
209 inputs = torch.randn(5, 3, 224, 224).cuda()
210
211 with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA]) as prof:
212 model(inputs)
213
214 prof.export_chrome_trace("trace.json")
215 ```
216
217 </hfoption>
218 <hfoption id="Accelerate">
219
220 ```python
221 model = models.resnet18()
222 inputs = torch.randn(5, 3, 224, 224).cuda()
223 profile_kwargs = ProfileKwargs(
224 activities=["cpu", "cuda"],
225 output_trace_dir="trace"
226 )
227
228 accelerator = Accelerator(kwargs_handlers=[profile_kwargs])
229 model = accelerator.prepare(model)
230
231 with accelerator.profile() as prof:
232 model(inputs)
233
234 # The trace will be saved to the specified directory
235 ```
236 For other hardware accelerators, e.g. XPU, you can change `cuda` to `xpu` in the above example code.
237
238 </hfoption>
239 </hfoptions>
240
241 ## Using Profiler to Analyze Long-Running Jobs
242
243 Profiler offers an additional API to handle long-running jobs (such as training loops). Tracing all of the execution can be slow and result in very large trace files. To avoid this, use optional arguments:
244
245 - `schedule_option`: Scheduling options allow you to control when profiling is active. This is useful for long-running jobs to avoid collecting too much data. Available keys are `wait`, `warmup`, `active`, `repeat` and `skip_first`. The profiler will skip the first `skip_first` steps, then wait for `wait` steps, then do the warmup for the next `warmup` steps, then do the active recording for the next `active` steps and then repeat the cycle starting with `wait` steps. The optional number of cycles is specified with the `repeat` parameter, the zero value means that the cycles will continue until the profiling is finished.
246 - `on_trace_ready`: specifies a function that takes a reference to the profiler as an input and is called by the profiler each time the new trace is ready.
247
248 To illustrate how the API works, consider the following example:
249
250 <hfoptions id="custom handler">
251 <hfoption id="PyTorch">
252
253 ```python
254 from torch.profiler import schedule
255
256 my_schedule = schedule(
257 skip_first=1,
258 wait=5,
259 warmup=1,
260 active=3,
261 repeat=2
262 )
263
264 def trace_handler(p):
265 output = p.key_averages().table(sort_by="self_cuda_time_total", row_limit=10)
266 print(output)
267 p.export_chrome_trace("/tmp/trace_" + str(p.step_num) + ".json")
268
269 with profile(
270 activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA],
271 schedule=my_schedule,
272 on_trace_ready=trace_handler
273 ) as p:
274 for idx in range(8):
275 model(inputs)
276 p.step()
277 ```
278
279 </hfoption>
280 <hfoption id="Accelerate">
281
282 ```python
283 def trace_handler(p):
284 output = p.key_averages().table(sort_by="self_cuda_time_total", row_limit=10)
285 print(output)
286 p.export_chrome_trace("/tmp/trace_" + str(p.step_num) + ".json")
287
288 profile_kwargs = ProfileKwargs(
289 activities=["cpu", "cuda"],
290 schedule_option={"wait": 5, "warmup": 1, "active": 3, "repeat": 2, "skip_first": 1},
291 on_trace_ready=trace_handler
292 )
293
294 accelerator = Accelerator(kwargs_handlers=[profile_kwargs])
295 model = accelerator.prepare(model)
296
297 with accelerator.profile() as prof:
298 for idx in range(8):
299 model(inputs)
300 prof.step()
301 ```
302
303 </hfoption>
304 </hfoptions>
305
306 ## FLOPS
307
308 Use formula to estimate the FLOPs (floating point operations) of specific operators (matrix multiplication and 2D convolution).
309
310 To measure floating-point operations (FLOPS):
311
312 <hfoptions id="FLOPS">
313 <hfoption id="PyTorch">
314
315 ```python
316 with profile(
317 activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA],
318 with_flops=True
319 ) as prof:
320 model(inputs)
321
322 print(prof.key_averages().table(sort_by="flops", row_limit=10))
323 ```
324
325 </hfoption>
326 <hfoption id="Accelerate">
327
328 ```python
329 profile_kwargs = ProfileKwargs(
330 with_flops=True
331 )
332 accelerator = Accelerator(kwargs_handlers=[profile_kwargs])
333
334 with accelerator.profile() as prof:
335 model(inputs)
336
337 print(prof.key_averages().table(sort_by="flops", row_limit=10))
338 ```
339
340 </hfoption>
341 </hfoptions>
342
343 The resulting table output (omitting some columns):
344
345 ```
346 ------------------------------------------------------- ------------ ------------ ------------
347 Name Self CPU Self CUDA Total FLOPs
348 ------------------------------------------------------- ------------ ------------ ------------
349 aten::conv2d 197.000us 0.000us 18135613440.000
350 aten::addmm 103.000us 17.000us 5120000.000
351 aten::mul 29.000us 2.000us 30.000
352 aten::convolution 409.000us 0.000us --
353 aten::_convolution 253.000us 0.000us --
354 aten::cudnn_convolution 5.465ms 2.970ms --
355 cudaEventRecord 138.000us 0.000us --
356 cudaStreamIsCapturing 43.000us 0.000us --
357 cudaStreamGetPriority 40.000us 0.000us --
358 cudaDeviceGetStreamPriorityRange 10.000us 0.000us --
359 ------------------------------------------------------- ------------ ------------ ------------
360 Self CPU time total: 21.938ms
361 Self CUDA time total: 4.165ms
362 ```
363
364
365
366 ## Conclusion and Further Information
367
368 PyTorch Profiler is a powerful tool for analyzing the performance of your models. By integrating it with Accelerate, you can easily profile your models and gain insights into their performance, helping you to optimize and improve them.
369
370 For more detailed information, refer to the [PyTorch Profiler documentation](https://pytorch.org/docs/stable/profiler.html).