MCPcopy Create free account
hub / github.com/OpenSparseLLMs/MoM / pytorch_profiler

Function pytorch_profiler

benchmarks/ops/benchmark.py:202–255  ·  view source on GitHub ↗

Wrap benchmark functions in Pytorch profiler to see CUDA information.

(
    fn,
    *inputs,
    trace_filename=None,
    backward=False,
    amp=False,
    amp_dtype=torch.float16,
    cpu=False,
    verbose=True,
    **kwinputs,
)

Source from the content-addressed store, hash-verified

200
201
202def pytorch_profiler(
203 fn,
204 *inputs,
205 trace_filename=None,
206 backward=False,
207 amp=False,
208 amp_dtype=torch.float16,
209 cpu=False,
210 verbose=True,
211 **kwinputs,
212):
213 """Wrap benchmark functions in Pytorch profiler to see CUDA information."""
214 if backward:
215 with torch.autocast(device_type="cuda", dtype=amp_dtype, enabled=amp):
216 out = fn(*inputs, **kwinputs)
217 if type(out) is tuple:
218 out = out[0]
219 g = torch.randn_like(out)
220 for _ in range(30): # Warm up
221 if backward:
222 for x in inputs:
223 if isinstance(x, torch.Tensor):
224 x.grad = None
225 with torch.autocast(device_type="cuda", dtype=amp_dtype, enabled=amp):
226 out = fn(*inputs, **kwinputs)
227 if type(out) is tuple:
228 out = out[0]
229 # Backward should be done outside autocast
230 if backward:
231 out.backward(g, retain_graph=True)
232 activities = ([torch.profiler.ProfilerActivity.CPU] if cpu else []) + [
233 torch.profiler.ProfilerActivity.CUDA
234 ]
235 with torch.profiler.profile(
236 activities=activities,
237 record_shapes=True,
238 # profile_memory=True,
239 with_stack=True,
240 ) as prof:
241 if backward:
242 for x in inputs:
243 if isinstance(x, torch.Tensor):
244 x.grad = None
245 with torch.autocast(device_type="cuda", dtype=amp_dtype, enabled=amp):
246 out = fn(*inputs, **kwinputs)
247 if type(out) is tuple:
248 out = out[0]
249 if backward:
250 out.backward(g, retain_graph=True)
251 if verbose:
252 # print(prof.key_averages().table(sort_by="self_cuda_time_total", row_limit=50))
253 print(prof.key_averages().table(row_limit=50))
254 if trace_filename is not None:
255 prof.export_chrome_trace(trace_filename)
256
257
258def benchmark_memory(fn, *inputs, desc="", verbose=True, **kwinputs):

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected