Rate this Page

torch.profiler#

Created On: Dec 18, 2020 | Last Updated On: Jun 13, 2025

Overview#

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.

Note

An earlier version of the API intorch.autograd module is considered legacy and will be deprecated.

API Reference#

classtorch.profiler._KinetoProfile(*,activities=None,record_shapes=False,profile_memory=False,with_stack=False,with_flops=False,with_modules=False,experimental_config=None,execution_trace_observer=None,acc_events=False,custom_trace_id_callback=None)[source]#

Low-level profiler wrap the autograd profile

Parameters:
  • activities (iterable) – 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.CUDAor (when available) ProfilerActivity.XPU.

  • record_shapes (bool) – save information about operator’s input shapes.

  • profile_memory (bool) – track tensor memory allocation/deallocation (seeexport_memory_timelinefor more details).

  • with_stack (bool) – record source information (file and line number) for the ops.

  • with_flops (bool) – use formula to estimate the FLOPS of specific operators(matrix multiplication and 2D convolution).

  • with_modules (bool) – record module hierarchy (including function names)corresponding to the callstack of the op. e.g. If module A’s forward call’smodule B’s forward which contains an aten::add op,then aten::add’s module hierarchy is A.BNote that this support exist, at the moment, only for TorchScript modelsand not eager mode models.

  • experimental_config (_ExperimentalConfig) – A set of experimental optionsused by profiler libraries like Kineto. Note, backward compatibility is not guaranteed.

  • execution_trace_observer (ExecutionTraceObserver) – A PyTorch Execution Trace Observer object.PyTorch Execution Traces offer a graph basedrepresentation 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 thesame time window as PyTorch profiler.

  • acc_events (bool) – Enable the accumulation of FunctionEvents across multiple profiling cycles

Note

This API is experimental and subject to change in the future.

Enabling shape and stack tracing results in additional overhead.When record_shapes=True is specified, profiler will temporarily hold references to the tensors;that may further prevent certain optimizations that depend on the reference count and introduceextra tensor copies.

add_metadata(key,value)[source]#

Adds a user defined metadata with a string key and a string valueinto the trace file

add_metadata_json(key,value)[source]#

Adds a user defined metadata with a string key and a valid json valueinto the trace file

events()[source]#

Returns the list of unaggregated profiler events,to be used in the trace callback or after the profiling is finished

export_chrome_trace(path)[source]#

Exports the collected trace in Chrome JSON format. If kineto is enabled, onlylast cycle in schedule is exported.

export_memory_timeline(path,device=None)[source]#

Export memory event information from the profiler collectedtree for a given device, and export a timeline plot. There are 3exportable files usingexport_memory_timeline, each controlled by thepath’s suffix.

  • For an HTML compatible plot, use the suffix.html, and a memory timelineplot will be embedded as a PNG file in the HTML file.

  • For plot points consisting of[times,[sizesbycategory]], wheretimes are timestamps andsizes 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 memoryevent will consist of(timestamp,action,numbytes,category), whereaction is one of[PREEXISTING,CREATE,INCREMENT_VERSION,DESTROY],andcategory is one of the enums fromtorch.profiler._memory_profiler.Category.

Output: Memory timeline written as gzipped JSON, JSON, or HTML.

Deprecated since version ``export_memory_timeline``:is deprecated and will be removed in a future version.Please usetorch.cuda.memory._record_memory_history andtorch.cuda.memory._export_memory_snapshot instead.

export_stacks(path,metric='self_cpu_time_total')[source]#

Save stack traces to a file

Parameters:
  • path (str) – save stacks file to this location;

  • metric (str) – metric to use: “self_cpu_time_total” or “self_cuda_time_total”

key_averages(group_by_input_shape=False,group_by_stack_n=0,group_by_overload_name=False)[source]#

Averages events, grouping them by operator name and (optionally) input shapes, stackand overload name.

Note

To use shape/stack functionality make sure to set record_shapes/with_stackwhen creating profiler context manager.

preset_metadata_json(key,value)[source]#

Preset a user defined metadata when the profiler is not startedand added into the trace file later.Metadata is in the format of a string key and a valid json value

toggle_collection_dynamic(enable,activities)[source]#

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

Examples:

withtorch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CPU,torch.profiler.ProfilerActivity.CUDA,])asp:code_to_profile_0()//turnoffcollectionofallCUDAactivityp.toggle_collection_dynamic(False,[torch.profiler.ProfilerActivity.CUDA])code_to_profile_1()//turnoncollectionofallCUDAactivityp.toggle_collection_dynamic(True,[torch.profiler.ProfilerActivity.CUDA])code_to_profile_2()print(p.key_averages().table(sort_by="self_cuda_time_total",row_limit=-1))
classtorch.profiler.profile(*,activities=None,schedule=None,on_trace_ready=None,record_shapes=False,profile_memory=False,with_stack=False,with_flops=False,with_modules=False,experimental_config=None,execution_trace_observer=None,acc_events=False,use_cuda=None,custom_trace_id_callback=None)[source]#

Profiler context manager.

Parameters:
  • activities (iterable) – 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.CUDAor (when available) ProfilerActivity.XPU.

  • schedule (Callable) – callable that takes step (int) as a single parameter and returnsProfilerAction value that specifies the profiler action to perform at each step.

  • on_trace_ready (Callable) – callable that is called at each step whenschedulereturnsProfilerAction.RECORD_AND_SAVE during the profiling.

  • record_shapes (bool) – save information about operator’s input shapes.

  • profile_memory (bool) – track tensor memory allocation/deallocation.

  • with_stack (bool) – record source information (file and line number) for the ops.

  • with_flops (bool) – use formula to estimate the FLOPs (floating point operations) of specific operators(matrix multiplication and 2D convolution).

  • with_modules (bool) – record module hierarchy (including function names)corresponding to the callstack of the op. e.g. If module A’s forward call’smodule B’s forward which contains an aten::add op,then aten::add’s module hierarchy is A.BNote that this support exist, at the moment, only for TorchScript modelsand not eager mode models.

  • experimental_config (_ExperimentalConfig) – A set of experimental optionsused 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 basedrepresentation 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 thesame 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

  • use_cuda (bool) –

    Deprecated since version 1.8.1:useactivities instead.

Note

Useschedule() to generate the callable schedule.Non-default schedules are useful when profiling long training jobsand allow the user to obtain multiple traces at the different iterationsof the training process.The default schedule simply records all the events continuously for theduration of the context manager.

Note

Usetensorboard_trace_handler() to generate result files for TensorBoard:

on_trace_ready=torch.profiler.tensorboard_trace_handler(dir_name)

After profiling, result files can be found in the specified directory. Use the command:

tensorboard--logdirdir_name

to see the results in TensorBoard.For more information, seePyTorch Profiler TensorBoard Plugin

Note

Enabling shape and stack tracing results in additional overhead.When record_shapes=True is specified, profiler will temporarily hold references to the tensors;that may further prevent certain optimizations that depend on the reference count and introduceextra tensor copies.

Examples:

withtorch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CPU,torch.profiler.ProfilerActivity.CUDA,])asp:code_to_profile()print(p.key_averages().table(sort_by="self_cuda_time_total",row_limit=-1))

Using the profiler’sschedule,on_trace_ready andstep 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 forth 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)

withtorch.profiler.profile(...execution_trace_observer=(ExecutionTraceObserver().register_callback("./execution_trace.json")),)asp:foriterinrange(N):code_iteration_to_profile(iter)p.step()

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.

get_trace_id()[source]#

Returns the current trace ID.

set_custom_trace_id_callback(callback)[source]#

Sets a callback to be called when a new trace ID is generated.

step()[source]#

Signals the profiler that the next profiling step has started.

classtorch.profiler.ProfilerAction(value)[source]#

Profiler actions that can be taken at the specified intervals

classtorch.profiler.ProfilerActivity#

Members:

CPU

XPU

MTIA

CUDA

HPU

PrivateUse1

propertyname#
torch.profiler.schedule(*,wait,warmup,active,repeat=0,skip_first=0,skip_first_wait=0)[source]#

Returns a callable that can be used as profilerschedule argument. The profiler will skipthe firstskip_first steps, then wait forwait steps, then do the warmup for the nextwarmup steps,then do the active recording for the nextactive steps and then repeat the cycle starting withwait steps.The optional number of cycles is specified with therepeat parameter, the zero value means thatthe cycles will continue until the profiling is finished.

Theskip_first_wait parameter controls whether the firstwait stage should be skipped.This can be useful if a user wants to wait longer thanskip_first between cycles, but notfor the first profile. For example, ifskip_first is 10 andwait is 20, the first cycle willwait 10 + 20 = 30 steps before warmup ifskip_first_wait is zero, but will wait only 10steps ifskip_first_wait is non-zero. All subsequent cycles will then wait 20 steps between thelast active and warmup.

Return type:

Callable

torch.profiler.tensorboard_trace_handler(dir_name,worker_name=None,use_gzip=False)[source]#

Outputs tracing files to directory ofdir_name, then that directory can bedirectly 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.

Intel Instrumentation and Tracing Technology APIs#

torch.profiler.itt.is_available()[source]#

Check if ITT feature is available or not

torch.profiler.itt.mark(msg)[source]#

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)[source]#

Pushes a range onto a stack of nested range span. Returns zero-baseddepth of the range that is started.

Parameters:

msg (str) – ASCII message to associate with range

torch.profiler.itt.range_pop()[source]#

Pops a range off of a stack of nested range spans. Returns thezero-based depth of the range that is ended.