PyTorch 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.
, , , , , ,
torch.profiler.profiler.
schedule
(
*
wait
warmup
active
repeat=0
skip_first=0
skip_first_wait=0
)
Returns a callable that can be used as profiler schedule argument. 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.
The skip_first_wait parameter controls whether the first wait stage should be skipped.
This can be useful if a user wants to wait longer than skip_first between cycles, but not
for the first profile. For example, if skip_first is 10 and wait is 20, the first cycle will
wait 10 + 20 = 30 steps before warmup if skip_first_wait is zero, but will wait only 10
steps if skip_first_wait is non-zero. All subsequent cycles will then wait 20 steps between the
last active and warmup.
Return type:
Callable
torch.profiler.profiler.supported_activities()
Returns a set of supported profiler tracing activities.
Note: profiler uses CUPTI library to trace on-device CUDA kernels.
In case when CUDA is enabled but CUPTI is not available, passing
ProfilerActivity.CUDA to profiler results in using the legacy CUDA
profiling code (same as in the legacy torch.autograd.profiler).
This, in turn, results in including CUDA time in the profiler table output,
but not in the JSON trace.
Outputs tracing files to directory of dir_name, then that directory can be
directly delivered to tensorboard as logdir.
worker_name should be unique for each worker in distributed scenario,
it will be set to ‘[hostname]_[pid]’ by default.
list of activity groups (CPU, CUDA) to use in profiling, supported values:
torch.profiler.ProfilerActivity.CPU, torch.profiler.ProfilerActivity.CUDA,
torch.profiler.ProfilerActivity.XPU.
Default value: ProfilerActivity.CPU and (when available) ProfilerActivity.CUDA
or (when available) ProfilerActivity.XPU.
Each item can be a ProfilerActivity enum (collects all default
activity types for that group) or a dict mapping a ProfilerActivity
to a list of individual activity type names to collect, e.g.
{ProfilerActivity.CUDA:.
An empty list (e.g. ) means collect
nothing for that group.
The same activity group must not appear more than once.
See for the valid
activity type names and device-specific behavior.
classtorch.profiler.ProfilerAction(value)
Profiler actions that can be taken at the specified intervals.
NONE, WARMUP, RECORD, and RECORD_AND_SAVE are user-facing values that may
be returned from a user-provided schedule. DEVICE_STOPPED is set
internally by the profiler when device collection stops early due to
errors; it must not be returned from a user-provided schedule.
classtorch.profiler.ProfilerActivity
Device kinds that the profiler supports.
Members:
CPU : CPU events (operators, runtime, …).
XPU : Intel XPU device activity. In a fine-grained activity dict ({ProfilerActivity.XPU:[...]}), names that are not XPU activity types are interpreted as Intel XPU hardware metric names and enable the per-kernel scope profiler, e.g. {ProfilerActivity.XPU:["GpuTime","GpuCoreClocks"]}. The metric values are attached to each kernel as Perfetto counters. Hardware metric collection requires ZET_ENABLE_METRICS=1 and access to the GPU performance counters (perf_stream_paranoid/observation_paranoid set to ). Metric names are device-specific and defined by the driver, not by PyTorch. Because a dict entry collects exactly what it lists, requesting only metrics (e.g. ) does not also collect the default XPU activities; list the desired activity type names alongside the metrics to keep tracing them, e.g. .
Intel Instrumentation and Tracing Technology APIs
torch.profiler.itt.is_available()
Check if ITT feature is available or not
torch.profiler.itt.mark(msg)
Describe an instantaneous event that occurred at some point.
Parameters:
msg (str) – ASCII message to associate with the event.
torch.profiler.itt.range_push(msg)
Pushes a range onto a stack of nested range span. Returns zero-based
depth of the range that is started.
Pops a range off of a stack of nested range spans. Returns the
zero-based depth of the range that is ended.
torch.profiler.itt.range(msg, *args, **kwargs)
Context manager / decorator that pushes an ITT range at the beginning
of its scope, and pops it at the end. If extra arguments are given,
they are passed as arguments to msg.format().
schedule (Callable) – callable that takes step (int) as a single parameter and returns
ProfilerAction value that specifies the profiler action to perform at each step.
on_trace_ready (Callable) – callable invoked at the end of each profiling cycle
(when schedule returns ProfilerAction.RECORD_AND_SAVE). Receives the
profile instance as its only argument, typically used to export the
trace (e.g. via export_chrome_trace()) or print a summary.
record_shapes (bool) – save information about operator’s input shapes.
record module hierarchy (including function names)
corresponding to the callstack of the op. e.g. If module A’s forward call’s
module B’s forward which contains an aten::add op,
then aten::add’s module hierarchy is A.B
experimental_config (_ExperimentalConfig) – A set of experimental options
used for Kineto library features. Note, backward compatibility is not guaranteed.
execution_trace_observer (ExecutionTraceObserver) – A PyTorch Execution Trace Observer object.
PyTorch Execution Traces offer a graph based
representation of AI/ML workloads and enable replay benchmarks, simulators, and emulators.
When this argument is included the observer start() and stop() will be called for the
same time window as PyTorch profiler. See the examples section below for a code sample.
acc_events (bool) – Enable the accumulation of FunctionEvents across multiple profiling cycles
post_processing_timeout_s (float) – Optional timeout in seconds for post-processing profiler
results. If specified, event parsing will stop after this duration and return partial
results. Useful for handling large traces that may take too long to process.
custom_trace_id_callback (Callable[[], str], optional) – User-supplied trace ID generator,
invoked once per profiling cycle. Defaults to a random UUID; retrieve via
get_trace_id().
Using the profiler’s schedule, on_trace_ready and step functions:
# Non-default profiler schedule allows user to turn profiler on and off# on different iterations of the training loop;# trace_handler is called every time a new trace becomes availabledeftrace_handler(prof):print(prof.key_averages().table(sort_by="self_cuda_time_total",row_limit=-1))# prof.export_chrome_trace("/tmp/test_trace_" + str(prof.step_num) + ".json")withtorch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CPU,torch.profiler.ProfilerActivity.CUDA,],# In this example with wait=1, warmup=1, active=2, repeat=1,# profiler will skip the first step/iteration,# start warming up on the second, record# the third and the fourth iterations,# after which the trace will become available# and on_trace_ready (when set) is called;# the cycle repeats starting with the next stepschedule=torch.profiler.schedule(wait=1,warmup=1,active=2,repeat=1),on_trace_ready=trace_handler,# on_trace_ready=torch.profiler.tensorboard_trace_handler('./log')# used when outputting for tensorboard)asp:foriterinrange(N):code_iteration_to_profile(iter)# send a signal to the profiler that the next iteration has startedp.step()
The following sample shows how to setup up an Execution Trace Observer (execution_trace_observer)
You can also refer to test_execution_trace_with_kineto() in tests/profiler/test_profiler.py.
Note: One can also pass any object satisfying the _ITraceObserver interface.
add_metadata(key, value)
Adds a user defined metadata with a string key and a string value
into the trace file
add_metadata_json(key, value)
Adds a user defined metadata with a string key and a valid json value
into the trace file
events()
Return the list of unaggregated FunctionEvent
objects, for use in the trace callback or after profiling has finished.
Exports the collected trace in Chrome JSON format. If kineto is enabled, only
last cycle in schedule is exported.
export_memory_timeline(path, device=None)
Export memory event information from the profiler collected
tree for a given device, and export a timeline plot. There are 3
exportable files using export_memory_timeline, each controlled by the
path’s suffix.
For an HTML compatible plot, use the suffix .html, and a memory timeline
plot will be embedded as a PNG file in the HTML file.
For plot points consisting of [times,[sizesbycategory]], where
times are timestamps and sizes are memory usage for each category.
The memory timeline plot will be saved a JSON (.json) or gzipped JSON
(.json.gz) depending on the suffix.
For raw memory points, use the suffix .raw.json.gz. Each raw memory
event will consist of (timestamp,action,numbytes,category), where
action is one of [PREEXISTING,CREATE,INCREMENT_VERSION,DESTROY],
and category is one of the enums from
torch.profiler._memory_profiler.Category.
Output: Memory timeline written as gzipped JSON, JSON, or HTML.
Preset a user defined metadata when the profiler is not started
and added into the trace file later.
Metadata is in the format of a string key and a valid json value
set_custom_trace_id_callback(callback)
Set the trace ID generator. Called at the start of each cycle, so updating
it between cycles yields distinct IDs per cycle.
step()
Signals the profiler that the next profiling step has started.
take_pending_cupti_export()
Detach this cycle’s cupti_monitor ProfilerObserver (with its unwritten window) so
the deferred export can be finalized OFF the training thread (call
obs.join(force=False) on a worker). None for non-cupti backends.
Toggle collection of activities on/off at any point of collection. Currently supports toggling Torch Ops
(CPU) and CUDA activity supported in Kineto
Parameters:
activities (iterable) – list of activity groups to use in profiling, supported values:
torch.profiler.ProfilerActivity.CPU, torch.profiler.ProfilerActivity.CUDA
Block until every deferred cupti_monitor export is written, then unregister.
No-op unless the cupti_monitor backend is active. Call on the training thread when
you need the file(s) on disk; the finalize force-flushes CUPTI (safe here).