Skip to content

torch.tpu API matrix

Every public Python API that TorchTPU documents, grouped by what you use it for, with its stability stage and the chapter that teaches it. The CUDA name each one replaces is in the CUDA to TorchTPU table; the environment variables are in Environment variables.

The rows follow TorchTPU's API reference and its generated public API list. TorchTPU states that using any API not on the public list is undefined behaviour and unsupported, so this page lists nothing else.

Stages, as the public API list defines them:

Stage Promise
Stable Supported long term; incompatible changes go through deprecation
Experimental May change or disappear in any release; a one-time warning on first use
Deprecated Removed at least 2 minor releases after deprecation; a one-time warning on use
Internal Public name for PyTorch to call; calling it from your code raises an error
PyTorch A standard PyTorch call that takes the "tpu" device type or backend name

The 0.2.0 documentation and the current repository differ

The 0.2.0 API reference documents the 0.2.0 release; the current repository API reference is newer, and this page follows it. The differences you will notice: the 0.2.0 documentation calls the stream type TpuStream where the current one says torch.tpu.Stream; it describes LIBTPU_INIT_ARGS and XLA_FLAGS without the rule that each rejects the other's flags; and it has no "Which variable for which flag" section. The deprecations dated 0.2.1 below exist only in the current public list.

Names that differ between the API reference and the public list

Both versions of the API reference write torch.tpu.topology_aware_mesh, torch.tpu.window_num_stripes and torch.tpu.window_stripe_chunk_mb. The public list, and the source (_internal/distributed/_distributed_module.py), put all three under torch.tpu.distributed, and the public list marks torch.tpu.topology_aware_mesh deprecated since 0.2.0. This page uses the torch.tpu.distributed names.

Device queries

Use torch.accelerator wherever it has the call; the torch.accelerator rows need PyTorch 2.11 or later.

API Stage What it does Taught in
torch.device("tpu") PyTorch The TPU device; registered when import torch autoloads TorchTPU 3
torch.accelerator.current_accelerator() Stable Returns torch.device("tpu") when the TPU is the active accelerator 3
torch.accelerator.is_available() Stable Whether the TPU backend is available 3, 8
torch.accelerator.device_count() Stable Number of devices visible to the current process 3, 8
torch.accelerator.current_device_index() Stable The active TPU device index 3
torch.accelerator.set_device_index(i) Stable Sets the active device index for the process 3
torch.accelerator.device_index(i) Stable Context manager that sets the device index temporarily 3
torch.tpu.is_initialized() Experimental Whether TorchTPU's runtime state has been initialized None
torch.tpu.get_device_properties(device=None) Experimental Static properties: name, devices_per_chip, hbm_bytes_per_chip, hbm_bytes_per_device, bf16_flops_per_chip, bf16_flops_per_device, sparse_cores_per_device, sparse_core_simd_width, topology 1, 2, 3
torch.tpu.device_of(obj) Experimental Context manager that switches to the device of a tensor or storage; a no-op for objects not on a TPU (source docstring) None

Memory

All Stable. Each call exists both as torch.accelerator.memory.<name> and as torch.accelerator.<name>; TorchTPU fills them from PjRt's allocator.

API What it does Taught in
memory_allocated(), max_memory_allocated() Bytes allocated now, and the peak 3, 5
memory_reserved(), max_memory_reserved() Bytes reserved now, and the peak 5
memory_stats(), get_memory_info() Allocator statistics; free and total memory 5
reset_peak_memory_stats() Resets the peak counters, for measuring one action 5
empty_cache() Releases cached memory 3

Layout

API Stage What it does Taught in
torch.tpu.get_device_layout_if_materialized(t) Experimental Returns (minor_to_major, tiles, element_size_in_bits) of a tensor's device buffer, or None before it exists 5
torch.tpu.TpuLayout Experimental A layout: minor_to_major, tiles, element_size_in_bits 5
torch.tpu.LayoutContext(layout) Experimental Context manager that sets the layout hint for TPU tensors created inside it; eager host-to-device copies only, not allowed inside torch.compile 5

Random numbers

The torch.accelerator.random rows need PyTorch 2.13 or later.

API Stage What it does Taught in
torch.tpu.manual_seed(seed) Experimental Seeds the active device's generator 3, 14
torch.tpu.manual_seed_all(seed) Experimental Seeds all local TPU devices 3
torch.tpu.set_rng_state(new_state, device=...) Experimental Sets the RNG state of the process's active device None
torch.tpu.default_generators Experimental Lazily initialized tuple of default torch.Generators, one per local device None
torch.accelerator.random.initial_seed() Stable Initial seed of the current device 3
torch.accelerator.random.get_rng_state(), get_rng_state_all() Stable RNG state of the current device, or of all devices 3

Mixed precision and matmul precision

API Stage What it does Taught in
torch.amp.autocast("tpu", ...) PyTorch Automatic mixed precision; bfloat16 by default on TPU 3, 6
torch.tpu.get_amp_supported_dtype() Experimental Dtypes autocast supports on TPU 6
torch.tpu.Precision Experimental Enum for float32 matmul and convolution precision on the MXU: DEFAULT, HIGH, HIGHEST 6
torch.tpu.precision(level) Experimental Context manager that sets the Precision for matmuls and convolutions in the block 3, 6
torch.tpu.allow_excess_precision Experimental Gets or sets XLA's --xla_allow_excess_precision (keep float32 intermediates in fused code). Defaults to False and locks at the first compilation 6, 23

Execution modes and compilation

API Stage What it does Taught in
torch.tpu.EagerMode Experimental Enum: DEFER_NEVER (Strict, the default), DEFER_AND_FUSE, DEFER_NEVER_AND_LAUNCH_BLOCKING (Debug) 4
torch.tpu.eager_mode Experimental Gets or sets the active EagerMode globally 4, 11
torch.tpu.set_eager_mode(mode) Experimental Context manager that sets the EagerMode temporarily 4
torch.tpu.compiler.custom_compiler_options(options) Experimental Context manager that passes custom XLA compiler flags to eager operations materialized inside the block None
torch.compile(model, backend="tpu") PyTorch Compiles with XLA, not TorchInductor; TorchTPU defaults to dynamic=False 4, 7

Streams and events

A TensorCore runs one computation at a time, and the API reference says manual multi-stream management is not needed. The torch.accelerator rows need PyTorch 2.11 or later.

API Stage What it does Taught in
torch.accelerator.synchronize() Stable Waits for all pending work on the device, deferred ops included 3, 4
torch.accelerator.current_stream(), set_stream(s) Stable Gets or sets the active stream 3
torch.tpu.default_stream(device=None) Experimental The default torch.tpu.Stream for a device None
torch.tpu.stream(s) Experimental Context manager that selects a torch.tpu.Stream None
torch.tpu.Stream(device=None, priority=0, *, pinned=None) Experimental Subclass of torch.Stream: synchronize, record_event, wait_event, wait_stream, query, priority_range; core pinning with pinned="dense" or "sparse", read back with is_dense and is_sparse 3
torch.tpu.Event(enable_timing=False) Experimental Subclass of torch.Event: record, synchronize, query, wait, elapsed_time, ipc_handle, from_ipc_handle 3

Distributed

TorchTPU registers "tpu_dist", aliased "tpu", as the default torch.distributed backend for TPU devices.

API Stage What it does Taught in
dist.init_process_group(backend="tpu_dist") PyTorch Collectives compiled into the TPU program as StableHLO ops; no NCCL 13
torch.tpu.distributed.topology_aware_mesh(mesh_shape, ...) Experimental A rank layout of shape mesh_shape that follows the physical ICI torus, for DeviceMesh("tpu", mesh=...) 13, 14
torch.tpu.distributed.set_tpu_launch_env(...) Experimental Sets the topology and multi-host launch variables before workers spawn; never overwrites a variable already set 8, 13
torch.tpu.distributed.spmd_safe(func) Experimental Decorator declaring that all ranks run identical TPU operations in func, so collectives can be fused instead of run as skinny modules 13, 14
torch.tpu.distributed.window_num_stripes Experimental Gets or sets the maximum number of concurrent DMA stripes for peer-to-peer transfers None
torch.tpu.distributed.window_stripe_chunk_mb Experimental Gets or sets the minimum payload in MB per DMA stripe for peer-to-peer transfers None

Operators: torch.tpu.ops

API Stage What it does Taught in
max_pool{1,2,3}d(...) Stable 1D, 2D or 3D max pooling without materializing an index tensor 3
max_pool{1,2,3}d_backward(...) Stable Backward of the above, without an index tensor 3
optimization_barrier(inputs) Experimental Stops XLA moving, fusing or deduplicating computation across the barrier None
splash_sdpa(q, k, v, ...) Experimental Scaled dot-product attention on the Pallas Splash Attention kernel 3, 9, 12
ragged_dot(lhs, rhs, group_sizes, ...) Experimental Grouped matmul for mixture-of-experts layers 12
ragged_dot_weight_grad(lhs, grad_output, group_sizes) Experimental Weight gradient of ragged_dot None
align_jagged_to_multiple(nt, ...) Experimental Pads a torch.jagged NestedTensor buffer to a multiple for TPU alignment 7
strip_jagged_padding(nt, ...) Experimental Removes the padding added by align_jagged_to_multiple 7
all_gather_dim(input, dim, group=None) Experimental All-gathers across group and concatenates along dim None
reduce_scatter_dim(input, dim, group=None, ...) Experimental Reduces across group and scatters chunks along dim None
ragged_all_to_all(...) Experimental Exchanges variable-length slices across ranks 13
send(tensors, dst, tag), recv(tensors, src, tag) Experimental Point-to-point send and receive on the default TPU process group None

SparseCore operators

These need a TPU with SparseCores; get_device_properties().sparse_cores_per_device is 0 on TPUs without them. All are Experimental and none is taught in a chapter.

API What it does
sparse_dense_matmul(...) CSR embedding lookup and aggregation on SparseCore
sparse_dense_matmul_grad_with_sgd(...), _with_adagrad(...), _with_adam(...) Backward of sparse_dense_matmul with a fused in-place SGD, Adagrad or Adam table update
sparse_dense_matmul_activation_unstack(...) Splits stacked embedding activations into per-feature tensors
sparse_dense_matmul_gradient_stack(...) Stacks per-feature activation gradients into one tensor
sparse_gather(...) Gathers rows of a 2D tensor with CSR indices
sparse_gather_backward(...) Scatter-adds gradients for sparse_gather
sparse_iota(...) Within-row position indices for the non-zeros of a CSR matrix
sparse_map_row(...) Maps a custom MLIR row-wise computation over sparse CSR matrices

Custom kernels: torch.tpu.pallas

API Stage What it does Taught in
torch.tpu.pallas.jax_op(name, fn=None, ...) Experimental Registers a JAX or Pallas function as a traceable PyTorch custom op 12, 25
torch.tpu.pallas.get_pallas_mesh(axis_names, mesh_shape=None, process_group=None) Experimental A JAX mesh aligned with torch ranks, for Pallas kernels that communicate across devices 12, 13
torch.tpu.pallas.verifier.verify(target, args, ...) Experimental Checks a jax_op, a JAX function or a PyTorch program that calls Pallas kernels; returns a VerificationReport (passed, findings, raise_for_errors()) 12
verifier.VerificationMode (FULL, STATIC), VerificationOptions, Severity, Phase, FindingCategory, VerificationFinding, VerificationError Experimental Options and result types for verify 12

The public list also names the members of these types (for example VerificationReport.findings_by_severity, VerificationFinding.source_location, Severity.ERROR); they are not listed one per row here.

Fused training step: torch.tpu.optimizers

None of these is taught in a chapter; chapter 14 covers the TorchTitan Graph Trainer, which puts the optimizer in the traced step by a different route.

API Stage What it does
SingleTraceTrainer(model, optimizer=None, ...) Experimental Holds functional params and optimizer state (param_group) and compiles forward, loss, backward and optimizer step into one program with make_compiled_train_step(...)
Optimizer(lr=..., weight_decay=...) Experimental Base class for stateless functional optimizers: defaults, init_param_group, step
AdamW(...), Muon(...), Sgd(...) Experimental Traceable functional optimizers, each with a ParamGroup holding params, opt_steps and moment state (opt_state_m, plus opt_state_v for AdamW)

Profiling: torch.tpu.profiler

API Stage What it does Taught in
torch.tpu.profiler.TpuProfilerConfig(...) Experimental Passed as torch.profiler.profile(..., experimental_config=...) with ProfilerActivity.TPU to configure host, device and Python tracing for XProf 10

Deprecated

API Deprecated in Use instead
torch.tpu.get_device_name TorchTPU 0.2.1 torch.tpu.get_device_properties().name
get_device_properties().total_memory TorchTPU 0.2.1 hbm_bytes_per_device (or _per_chip)
get_device_properties().multi_processor_count TorchTPU 0.2.1 The TPU-specific fields
torch.tpu.topology_aware_mesh TorchTPU 0.2.0 torch.tpu.distributed.topology_aware_mesh
torch.accelerator.current_device_idx PyTorch torch.accelerator.current_device_index
torch.accelerator.set_device_idx PyTorch torch.accelerator.set_device_index

The public list names no replacement for the first three; their "use instead" entries are the properties that the API reference documents for torch.tpu.get_device_properties.

Internal: calling these raises an error

On PyTorch 2.11 or later (2.13 or later for the two RNG calls) these torch.tpu duplicates raise a RuntimeError from user code. TORCH_TPU_ALLOW_LEGACY_DEVICE_APIS=1 turns the error into a one-time warning while you migrate; the API reference says that variable will likely be removed.

Internal API Use instead
torch.tpu.is_available torch.accelerator.is_available
torch.tpu.device_count torch.accelerator.device_count
torch.tpu.current_device torch.accelerator.current_device_index
torch.tpu.set_device torch.accelerator.set_device_index
torch.tpu.device torch.accelerator.device_index
torch.tpu.synchronize torch.accelerator.synchronize
torch.tpu.current_stream torch.accelerator.current_stream
torch.tpu.set_stream torch.accelerator.set_stream
torch.tpu.get_rng_state torch.accelerator.random.get_rng_state
torch.tpu.initial_seed torch.accelerator.random.initial_seed

Not on the public list

Public documents around TorchTPU use some names that are not torch.tpu APIs:

See also

References