This document is relevant for: Trn2, Trn3
torch.compile backend reference#
This topic provides reference material for the Neuron torch.compile backend.
Use this page to look up the support status of the torch.compile parameters
and the torch.compiler APIs, the backend’s environment variables, the public
helper API, and caching configuration.
Applies to#
torch.compile(model, backend="neuron")withtorch-neuronx(TorchNeuron) on Trn2, Trn3.
torch.compile API and parameter support#
These tables give the support status of each torch.compile parameter and each torch.compiler API on the Neuron backend. Status values come from end-to-end runs on a Neuron device.
torch.compile parameters#
Parameter |
Status |
Notes |
|---|---|---|
|
Supported |
Module or callable. |
|
Supported |
|
|
Unsupported |
|
|
Supported |
|
|
Unsupported (default only) |
Only |
|
Partial |
Accepts a |
|
Unsupported |
Accepted without an error, but the name is not propagated to compilation artifacts. |
|
Supported |
|
|
Supported |
With |
|
Supported |
Compiles and runs. Independent-tracking behavior is not stress-tested. |
|
Unsupported |
A static shape spec runs without an error, but a dynamic one fails for the same reason as |
torch.compiler APIs#
API |
Status |
|---|---|
|
Supported |
|
Supported |
|
Supported |
|
Supported |
|
Supported |
|
Supported |
|
Supported |
|
Supported |
|
Supported |
|
Supported |
|
Supported |
|
Unsupported |
|
Supported |
|
Supported |
|
Supported |
|
Supported |
|
Supported |
|
Supported |
|
Supported |
|
Supported |
|
Supported |
|
Unsupported |
|
Supported |
|
Supported |
|
Supported |
|
Supported |
Graph breaks#
A graph break splits a function into graphs that compile separately. When TorchDynamo
traces an operation that the Neuron backend cannot compile, the backend forces a graph
break at that call. The operation runs in eager mode, and the rest of the function still
compiles. This applies to the function form (for example, torch.sort(x)) and to the
tensor method form (x.sort()).
A graph break occurs only with fullgraph=False, which is the default. With
fullgraph=True, the same operation raises torch._dynamo.exc.Unsupported. The
diagnostic has the type Op not supported by the Neuron backend and gives the
operation name and the reason.
The Neuron backend forces a graph break for these operations:
Operation |
When it breaks |
|---|---|
|
When the sorted dimension has more than 16,384 elements. |
|
When |
|
Always. |
Operations with no Neuron lowering |
Always. See the paragraph that follows this table. |
There is no fixed list of operations with no Neuron lowering. When you import
torch_neuronx, the backend builds this list from the installed versions of PyTorch,
torch-mlir, and the Neuron decompositions. The list can change when you upgrade
torch-neuronx or PyTorch. To find the graph breaks in your model, compile with
fullgraph=True during development, so that each break raises an error.
Backend behavior environment variables#
These variables control compilation behavior, artifact output, and fallback for
backend="neuron". Boolean variables accept 1/true/yes for true.
Variable |
Type |
Default |
Effect |
|---|---|---|---|
|
bool |
|
When true (the default), disables fallback to eager execution on a
compilation or execution failure, so the backend re-raises the error
instead of silently running the original graph. Set to |
|
str |
|
Directory where compilation artifacts (FX graphs, StableHLO IR, NEFF files) are written. |
|
bool |
|
When true, keeps the compilation-artifacts directory after execution completes. Useful for inspecting the IR. |
|
bool |
|
Build the NEFF without executing on device; a runtime-init failure is
non-fatal. Also set by |
|
bool |
|
When true, raises an error if CPU tensors are passed as inputs instead of auto-copying them to the Neuron device. |
|
bool |
|
When true, outputs retain their original device placement instead of the Neuron device. |
|
str |
(query live instance) |
Target platform (for example, |
|
str |
|
Extra flags passed to the |
|
bool |
|
Decompose |
Caching environment variables#
Compiled NEFFs and lowered HLO are cached on disk so that repeated compilations across runs and instances avoid recompilation. The NEFF cache is content-addressed; an entry from one run is reused by another as long as the inputs (HLO bytes, compiler configuration, compiler version) are unchanged.
Variable |
Type |
Default |
Effect |
|---|---|---|---|
|
path |
|
Directory for the persistent NEFF cache. Point at a shared mount (for example, Amazon FSx) to reuse compiled NEFFs across runs and instances. |
|
path |
|
Directory for the persistent HLO cache, shared by the eager and
|
|
bool |
|
When true, disables the persistent NEFF cache entirely; every compile runs fresh. |
|
path |
|
Local directory for file locks and scratch. Must stay on a local POSIX filesystem — NFS and Lustre lock semantics are unreliable. |
|
int |
|
Seconds to wait for the per-key compile lock before giving up. |
|
bool |
|
When true, enables the PyTorch Dynamo precompile cache (MegaCache). For the
Neuron backend the StableHLO result is cached, saved under
|
Metrics environment variables#
Variable |
Type |
Default |
Effect |
|---|---|---|---|
|
str |
|
Comma-separated metric tables to emit as CSV. The compilation table is
|
|
str |
|
Output directory for metric CSV files. |
Backend helper API#
All symbols below are importable from torch_neuronx.neuron_dynamo_backend.
(src: __init__.py, config.py, metrics.py, exceptions.py)
Note
Signatures, parameters, and field descriptions are transcribed from the
torch-neuronx source and should be confirmed against the release you are
running.
Symbol |
Description |
|---|---|
Set the model name used for artifact and graph naming. |
|
Get the current model name. |
|
Current distributed rank, or the Neuron device ID when not distributed. |
|
Retrieve per-graph compilation metrics. |
|
Reset recorded compilation metrics and counters. |
|
Raised when NEFF compilation fails. |
|
Raised when NEFF execution fails. |
Model naming#
Distributed#
- get_rank() int
Return the current process rank. Returns
torch.distributed.get_rank()whentorch.distributedis initialized; otherwise returns the current Neuron device ID (torch.neuron.current_device()).- Returns:
Process rank, or the Neuron device ID when not running under
torch.distributed.- Return type:
Compilation metrics#
- get_dynamo_metrics() list[NeuronCompilationMetrics]
Return per-graph compilation metrics collected during
torch.compile. Callstorch_neuronx.synchronize()first so that asynchronous compile timings are populated before the metrics are returned.- Returns:
One
NeuronCompilationMetricsrecord per compiled graph.- Return type:
list[NeuronCompilationMetrics]
Each record contains the following fields:
Field
Type
Description
graph_idstr
Unique identifier (cache key) for the compiled graph.
graph_namestr
Human-readable name,
{model_name}_{aot_id}_{graph_type}_{nth}.model_namestr
User-provided or auto-generated model name.
has_collectivesbool
Whether the graph contains collective operations (for example, all-reduce).
graph_node_countint
Number of nodes in the FX graph before lowering.
timestampstr
Compilation timestamp / segment ID used for ordering.
torch_neuronx_fx_passes_usint
Time for FX graph-level passes, in microseconds.
torch_neuronx_lower_usint
Time to lower to StableHLO (torch-mlir), in microseconds.
torch_neuronx_compile_usint
Time to compile StableHLO to NEFF, in microseconds (populated lazily on read).
- reset_dynamo_metrics() None
Clear all recorded compilation metrics and counters. Call this between test runs or when starting a new profiling session.
- Return type:
None
import torch
from torch_neuronx.neuron_dynamo_backend import get_dynamo_metrics, reset_dynamo_metrics
reset_dynamo_metrics()
compiled = torch.compile(model, backend="neuron")
compiled(*example_inputs) # first call triggers compilation
for m in get_dynamo_metrics():
print(m.graph_name, m.graph_node_count, m.torch_neuronx_compile_us)
Exceptions#
- exception NEFFCompilationError
Raised when NEFF compilation fails. Subclass of
Exception.
- exception NEFFExecutionError
Raised when NEFF execution fails. Subclass of
Exception.
Caching configuration#
The backend caches at three layers: the content-addressed persistent NEFF cache
(TORCH_NEURONX_NEFF_CACHE_DIR), the HLO cache (TORCH_NEURONX_HLO_CACHE_DIR),
and the optional Dynamo precompile cache (TORCH_CACHING_PRECOMPILE). To reuse
compiled NEFFs across runs and across instances, point TORCH_NEURONX_NEFF_CACHE_DIR
at a shared mount such as Amazon FSx, and keep TORCH_NEURONX_NEFF_LOCAL_CACHE_DIR
on a local POSIX filesystem for lock files.
Because the backend forces dynamic=False, each input shape produces a separate
cache entry. Pad or bucket inputs to a fixed set of shapes to maximize reuse. Pin
the torch-neuronx and compiler versions in production, since the NEFF cache key
includes the compiler version and a version change invalidates prior entries. For
the caching mechanics, see How torch.compile works on Neuron.
Learn more#
How torch.compile works on Neuron - How torch.compile works on Neuron
How to optimize a model with torch.compile - Optimize a model with
torch.compile
This document is relevant for: Trn2, Trn3