This document is relevant for: Trn2, Trn3

torch.neuron and torch.accelerator reference#

This topic lists the functions of the torch.neuron device module and the torch.accelerator functions that TorchNeuron supports. Use it to look up a function’s signature, what it returns, and the Neuron-specific behavior behind it.

Applies to#

  • torch-neuronx (TorchNeuron) on Trn2 and Trn3 Trainium instances.

  • Eager mode and torch.compile(backend="neuron").

How the module is registered#

When torch_neuronx loads, it registers Trainium with PyTorch as the PrivateUse1 backend under the name neuron:

  • torch.neuron becomes the device module for the neuron device, with the functions listed on this page. It plays the role that torch.cuda plays for CUDA devices.

  • torch.accelerator resolves to the neuron device when no other accelerator is present, so code written against torch.accelerator selects Trainium without a change.

  • Tensors, modules, and storages get .neuron() and .is_neuron methods, generated by PyTorch from the backend name.

PyTorch loads torch_neuronx automatically when you import torch, so you do not need to import it yourself. An explicit import torch_neuronx is needed only when TORCH_DEVICE_BACKEND_AUTOLOAD=0 is set. If another PrivateUse1 backend was imported first, torch_neuronx leaves the device registration to that backend and torch.neuron is not created.

import torch

assert torch.neuron.is_available()
print(torch.neuron.device_count(), torch.accelerator.current_accelerator())

torch.accelerator support#

The torch.accelerator namespace is PyTorch’s device-agnostic API. Device, stream, and synchronization functions reach TorchNeuron through the device guard that torch-neuronx registers, and work the same way as their torch.neuron equivalents. The memory functions report the same Neuron caching allocator statistics as the torch.neuron memory functions listed below; the table notes the differences.

torch.accelerator function

Status

torch.neuron equivalent and notes

is_available()

Supported

torch.neuron.is_available()

current_accelerator(check_available=False)

Supported

Returns device(type='neuron').

device_count()

Supported

torch.neuron.device_count()

current_device_index()

Supported

torch.neuron.current_device(). current_device_idx() is the deprecated PyTorch alias.

set_device_index(device)

Supported

torch.neuron.set_device(device). set_device_idx() is the deprecated PyTorch alias.

device_index(index) (context manager)

Supported

torch.neuron.device(device_spec)

current_stream(device=None)

Supported

torch.neuron.current_stream(device)

set_stream(stream)

Supported

torch.neuron.set_stream(stream)

synchronize(device=None)

Supported

torch.neuron.synchronize(device)

get_device_capability(device=None)

Supported

Reports the dtypes the device supports: bool, uint8, int8, int16, int32, int64, float16, bfloat16, float32, float64. Complex dtypes are not reported. For how int64 and float64 execute, see What is TorchNeuron?.

memory_stats(), memory_allocated(), max_memory_allocated(), memory_reserved(), max_memory_reserved(), reset_peak_memory_stats(), reset_accumulated_memory_stats()

Supported

Same statistics and resets as the torch.neuron functions of the same name (see Memory), reported for the all pool only: large_pool and small_pool values are 0. requested_bytes equals active_bytes. Before the runtime starts, memory_stats() returns an empty dictionary and the byte functions return 0. These functions do not wait for queued device work; call torch.neuron.synchronize() first for an exact value.

empty_cache()

Supported

Same as torch.neuron.empty_cache(). Does nothing before the runtime starts.

get_memory_info(device=None)

Supported

torch.neuron.mem_get_info(device): (free, total) HBM bytes from the Neuron runtime. Starts the runtime when needed.

Graph

Not available

Accelerator graph capture is not supported on Neuron. Use torch.compile(backend="neuron") to reduce launch overhead; see torch.compile backend reference.

torch.neuron functions#

Every function below is available as torch.neuron.<name>. Where a function takes a device argument, it accepts an int index, a str such as "neuron:1", or a torch.device; None means the current Neuron device. set_device and get_device_name are the exceptions: they do not accept a str.

Device#

Function

Returns

Description

is_available()

bool

True when the device count is positive; False when it is zero or cannot be queried.

is_initialized()

bool

Whether the Neuron runtime is initialized. The runtime initializes lazily on first device use.

init()

None

Initializes the Neuron runtime and applies the pending device seed. Raises RuntimeError if initialization fails or the process was forked after initialization.

device_count()

int

Number of Neuron device indices exposed to PyTorch: the configured local world size when distributed state is initialized, otherwise the number of visible NeuronCores (virtual cores, as configured by logical NeuronCore configuration).

current_device()

int

Current device index: the thread-local selection, the process default, or 0. A host-side query; it does not synchronize device work.

set_device(device)

None

Selects the current device from an int index or a torch.device. None, or a torch.device with no index, keeps the current selection. A str such as "neuron:1" raises TypeError.

device(device_spec)

context manager

Selects a device for the duration of a with block and restores the previous device on exit. None uses the current device.

get_device_name(device=0)

str

"neuron:<index>" for an int, or the string form of a torch.device. Any other type, including str, raises ValueError.

get_device_properties(device=None)

properties object

name is the instance type; total_memory is the device HBM limit in bytes, or 0 when the runtime memory query fails.

get_amp_supported_dtype()

list[torch.dtype]

Dtypes supported for automatic mixed precision: float32, float16, bfloat16.

is_bf16_supported()

bool

Always True. Present so that code that checks torch.cuda.is_bf16_supported() also works with torch.neuron.

Random number generation#

Each Neuron device has its own generator. The generator state is a seed and a counter offset; the seed functions below reset the offset to zero. The set of accessible generators is fixed the first time it is queried, so a later change in device_count() is not reflected in it. For how the on-device RNG works, reproducibility guarantees, and which random operations run on the device, see Random number generation.

Function

Returns

Description

manual_seed(seed)

None

Sets the current device generator’s seed and resets its offset. When the runtime is initialized and NKI RNG is available, also queues a GpSimd RNG-state update on the current device.

manual_seed_all(seed)

None

Sets the seed of every accessible generator and resets each offset. Same NKI RNG update as manual_seed.

seed()

None

Assigns a nondeterministic seed to the current generator and resets its offset.

seed_all()

None

Draws one nondeterministic seed from the first generator and copies it to every accessible generator, resetting each offset.

initial_seed()

int

Initial seed of the current device generator.

get_rng_state(device=None)

torch.Tensor

A 16-element CPU uint8 tensor: the 8-byte seed followed by the 8-byte offset. The copy is synchronous.

set_rng_state(state, device=None)

None

Replaces the generator state from an 8-byte (seed only; offset reset to zero) or 16-byte (seed and offset) CPU uint8 tensor. Outside FakeTensorMode, a changed state also reseeds the CPU default generator with seed XOR offset and, when the runtime is initialized, the device RNG seed. Raises RuntimeError for any other length.

Streams and events#

Neuron execution is asynchronous: an operation returns to Python once it is enqueued on a stream. Use these functions to create streams, order work between them, and wait for completion. For a worked example that overlaps communication with compute, see Overlap communication with compute.

Function

Returns

Description

Stream(device=None, priority=0)

torch_neuronx.Stream

Creates a stream on device (None is the current device). Pass the arguments by keyword; torch.neuron.Stream forwards keyword arguments to torch_neuronx.Stream. priority is recorded in the stream identifier as metadata; it does not affect scheduling.

stream(stream)

context manager

Makes stream current for the with block and restores the previous streams on exit. None is a no-op context.

StreamContext(stream)

torch_neuronx.StreamContext

The context manager that stream(stream) returns, exposed under the same name as torch.cuda.StreamContext for code that builds the context directly. None is a no-op context.

current_stream(device=None)

torch_neuronx.Stream

The currently selected stream on a device.

default_stream(device=None)

torch_neuronx.Stream

The default stream of a device.

set_stream(stream)

None

Makes stream current. None leaves the selection unchanged. Selecting a stream on another device also makes that device current.

synchronize(device=None)

None

Blocks until all streams on the device have completed. Call it before you stop a timer or read a memory statistic.

wait_stream(stream)

None

Makes future work on the current stream wait for the work already submitted to stream.

wait_event(event)

None

Makes future work on the current stream wait for event. Raises RuntimeError if event is not a Neuron event.

record_event(event=None)

torch_neuronx.Event

Records an event after the work already submitted to the current stream. With None, creates and returns a new event.

query()

bool

True when all work submitted to the current stream has completed.

Event(enable_timing=False, blocking=False)

torch_neuronx.Event

Creates an event. With enable_timing=True, elapsed time between two events uses host steady-clock timestamps taken when queued work reaches each event, not a device hardware timer. blocking is stored but currently has no effect.

Memory#

These functions read the Neuron caching allocator. Because execution is asynchronous, call torch.neuron.synchronize() before you read a statistic. For how to interpret the numbers and reduce memory use, see How to profile memory usage in TorchNeuron and Guidelines for memory management.

Function

Returns

Description

memory_allocated(device=None)

int

Bytes occupied by allocated blocks (allocated_bytes.all.current).

max_memory_allocated(device=None)

int

Peak allocated bytes since the last reset (allocated_bytes.all.peak).

memory_reserved(device=None)

int

Bytes currently reserved by the caching allocator (reserved_bytes.all.current).

max_memory_reserved(device=None)

int

Peak reserved bytes since the last reset (reserved_bytes.all.peak).

memory_stats(device=None)

dict[str, Any]

Byte values by category, pool, and state; allocator, deferred-allocation, and scalar-cache counters; scalar cache size; and per-category runtime usage bytes when available. Per-pool values are measured only for current; for peak, allocated, and freed, large_pool repeats the all value and small_pool is zero. Allocator-cache and split/merge counters are not included.

memory_summary(device=None, abbreviated=False)

str

Human-readable table of allocated, reserved, and active bytes, plus allocation, free, out-of-memory, retry, and deferred-allocation counters. abbreviated currently has no effect.

peak_memory_stats(device=None)

dict[str, Any]

The allocator snapshot captured at the allocation peak: valid, a steady-clock timestamp_ns, allocated, reserved, and active byte dictionaries, internal fragmentation, and allocator counters. Updated at each new peak; survives reset_peak_memory_stats(); logged with TORCH_WARN on out-of-memory.

reset_peak_memory_stats(device=None)

None

Resets peak byte values to their current values. Does not clear the peak_memory_stats() snapshot.

reset_accumulated_memory_stats(device=None)

None

Resets event counters and the historical allocated and freed totals. Current and peak byte values are unchanged.

empty_cache()

None

Releases cached allocator blocks to the Neuron runtime. With lazy allocation, synchronizes every visible device first. Memory held by live tensors is not released.

mem_get_info(device=None)

tuple[int, int]

(free, total) HBM bytes of the device from the Neuron runtime. free also excludes runtime memory outside the caching allocator, for example loaded NEFFs. Starts the runtime when needed, so call it after the process group starts and after forking worker processes. Raises RuntimeError if the index is invalid or the runtime query fails.

segment_pool_analysis(device=None)

dict[str, Any]

Fragmentation and efficiency metrics for the segment pool: free_chunks, num_segments, byte fields for free space, HBM, fragmentation, address span, and allocator use, and the ratios fragmentation_index and memory_density. Before runtime initialization, total_hbm is 0 and fragmentation_index is None.

segment_pool_analysis_summary(device=None)

str

Formatted table of the segment_pool_analysis() values.

Compilation metrics#

These functions mirror the torch_neuronx.neuron_dynamo_backend helpers documented in get_dynamo_metrics().

Function

Returns

Description

get_dynamo_metrics()

list[NeuronCompilationMetrics]

Per-graph compilation metrics for the neuron torch.compile backend, with lazy NEFF compilation times resolved. Synchronizes the current device before resolving them.

reset_dynamo_metrics()

None

Clears the process-wide metrics records and the counters["neuron"] Dynamo counters.

Example#

import torch

torch.neuron.manual_seed(0)
dev = torch.device("neuron", torch.neuron.current_device())

x = torch.randn(4096, 4096, device=dev)
y = x @ x

torch.neuron.synchronize()
print(torch.neuron.memory_summary())