Skip to content

Environment variables

The variables that configure TorchTPU, vLLM-TorchTPU and SGLang-TorchTPU, with their defaults and what each does. Each section names the documentation it summarizes. Python APIs are on the API matrix.

Set them before import torch

TorchTPU's variables are locked when the backend initializes, usually at import torch or torch.device("tpu") (API reference). To switch eager mode inside a running process, use torch.tpu.set_eager_mode instead (chapter 4).

The TorchTPU tables follow TorchTPU's API reference and public API list, which gives each variable's stage (Stable or Experimental, at the end of each effect); defaults not given there come from the comments in csrc/common/env_vars.h, and the launch defaults from set_tpu_launch_env. "Not documented" means none of these gives a default.

TorchTPU: device visibility, runtime and launch

Name Default Effect
TPU_VISIBLE_DEVICES Not documented Comma-separated TPU chip indices visible to the process, like CUDA_VISIBLE_DEVICES. TorchTPU treats it as the source of truth and overwrites TPU_VISIBLE_CHIPS to match. Stable
RANK, LOCAL_RANK, WORLD_SIZE Set by the launcher Global rank, host-local rank and process count of a distributed job. Stable
NNODES, NODE_RANK Set by the launcher Host count and this host's rank in a multi-host job. Stable
MASTER_ADDR, MASTER_PORT Set by the launcher Rendezvous address and port of the rank-0 host for torch.distributed. Stable
TORCH_DEVICE_BACKEND_AUTOLOAD Unset (autoload on) "0" stops PyTorch autoloading the torch_tpu backend. Owned by PyTorch. Stable
TORCH_TPU_ALLOW_LEGACY_DEVICE_APIS false "1" or "true" turns the error from internal torch.tpu device calls into a one-time warning. A temporary fix, likely to be removed. Experimental
LIBTPU_INIT_ARGS Set by Google Cloud Space-separated flags for libtpu and PJRT, including TPU compiler flags --xla_tpu_*. Rejects generic XLA flags such as --xla_dump_to. Stable
TPU_PREMAPPED_BUFFER_SIZE Not documented Premapped host-to-device buffer size in bytes for the PJRT client. Stable
TMPDIR System default Temporary directory for the runtime and compiler. Stable

TorchTPU: topology and multi-host coordination

Usually set for you by torch.tpu.distributed.set_tpu_launch_env(), the python3 -m torch.tpu.distributed launcher or Google Cloud; set_tpu_launch_env never overwrites a variable that is already set (chapter 8, chapter 13).

Name Default Effect
TORCH_TPU_TOPOLOGY Set by TorchTPU launchers Physical topology of the slice, for example 2x2x1 or 2x2x4. Must agree with the GKE node selectors and chip request (chapter 8). Experimental
TORCH_TPU_SLICEBUILDER_ADDRESSES Derived by set_tpu_launch_env on multi-host jobs Comma-separated host:port slice-builder addresses, one per device: each host from TPU_WORKER_HOSTNAMES with ports from TORCH_TPU_BASE_PORT upward. Experimental
TORCH_TPU_DEVICES_PER_HOST nproc_per_node, else the attached device count, else 8 Devices per host when deriving slice-builder addresses. env_vars.h states 8; the Python launcher tries the first two first. Experimental
TORCH_TPU_BASE_PORT 8070 First port when deriving slice-builder addresses. Experimental
TORCH_TPU_SPMD_HANDSHAKE_STAGE OFF When ranks check that their collective graphs match so collectives can compile without splitting: OFF, COMPILE_STAGE or DISPATCH_STAGE (chapter 13). Experimental
TORCHCOMM_RANK Falls back to RANK, then LOCAL_RANK, then 0 Process rank for torchcomm; takes precedence over RANK. Experimental
TORCHCOMM_SIZE Falls back to WORLD_SIZE, then 1 World size for torchcomm; takes precedence over WORLD_SIZE. Experimental

TorchTPU: execution mode, compilation and caching

Name Default Effect
TORCH_TPU_DEFER_AND_FUSE Off (Strict mode) "1" or "true" makes EagerMode.DEFER_AND_FUSE the default eager mode (chapter 4). Experimental
TORCH_TPU_LAUNCH_BLOCKING Off "1" or "true" makes EagerMode.DEFER_NEVER_AND_LAUNCH_BLOCKING (Debug) the default, like CUDA_LAUNCH_BLOCKING (chapter 4). Experimental
TORCH_TPU_TIER2_COMPILATION_CACHE Off at world size 1; otherwise on, named default Name of the host-local cache directory under /dev/shm/torch_tpu_cache/, or "disabled" (chapter 3). Experimental
TORCH_TPU_TIER3_COMPILATION_CACHE_ROOT Unset (tier 3 off) Path or gs:// URI of the persistent cache shared across hosts and runs. Experimental
XLA_FLAGS Unset Generic XLA compiler and debug flags such as --xla_dump_hlo_as_text --xla_dump_to=DIR. Rejects TPU compiler flags --xla_tpu_*. Experimental

Which variable for which flag. The current repository API reference states this rule; the 0.2.0 documentation does not. An unknown flag in either variable stops the process at backend initialization:

Flag kind Example Set in If put in the other variable
Generic XLA compiler and debug flags --xla_dump_to, --xla_dump_hlo_as_text XLA_FLAGS LIBTPU_INIT_ARGS fails with Unknown command line flag 'xla_dump_to'
TPU compiler flags --xla_tpu_enable_async_collective_fusion LIBTPU_INIT_ARGS XLA_FLAGS fails with Unknown flag in XLA_FLAGS: --xla_tpu_...

TorchTPU: debugging, profiling and tracing

Name Default Effect
TORCH_SHOW_CPP_STACKTRACES Off "1" appends C++ backtraces to Python RuntimeErrors. Shared with PyTorch. Experimental
TORCH_TPU_ENABLE_DEBUG_CHECKS False "1" enables runtime debug and bounds checks, at a cost in speed. Debug eager mode turns them on by default; "0" overrides that. Experimental
TORCH_TPU_PROFILER_OUTPUT_DIR Unset Fallback directory for XProf traces when TpuProfilerConfig.run_dir is unset (chapter 10). Experimental
TORCH_TPU_XPROF_SESSION_ID Set by set_tpu_launch_env when unset XProf session ID shared by all workers of a job. Experimental
TORCH_TRACE Unset Output directory for structured compiler and dispatcher logs for tlparse. Experimental

TorchTPU: names that are not public

env_vars.h also defines variables whose names start with TORCH_TPU_INTERNAL_, and reads Google Cloud variables such as TPU_WORKER_HOSTNAMES, JOB_COMPLETION_INDEX and TPU_VISIBLE_CHIPS. None is on the public list, and TorchTPU calls any API outside that list undefined behaviour; do not build on them.

vLLM-TorchTPU

All variables are declared and validated in src/vllm_torchtpu/envs.py. Booleans accept 1, true, yes, on, 0, false, no, off (any case); an invalid value raises ValueError at startup. vLLM-TorchTPU's Environment Variables Reference gives every detail. Chapter 18 teaches the compilation and parallelism variables.

Platform, runtime and compilation cache

Name Default Effect
VLLM_XLA_CACHE_PATH ~/.cache/vllm/xla_cache Directory or gs:// URI for the persistent XLA/PJRT compilation cache
VLLM_XLA_CHECK_RECOMPILATION False Logs or raises when a graph recompiles after warmup
TPU_PARALLEL_PRECOMPILE False Compiles in parallel during warmup
TPU_PRECOMPILE_PEER_REPLAY False With parallel precompile, one rank per host compiles each range and the others replay it from the compile cache; fails with VLLM_DISABLE_COMPILE_CACHE=1
TPU_PRECOMPILE_PEER_WAIT_S 600 Seconds a rank waits for a range's owner before compiling it itself
TPU_PRECOMPILE_TRACE_FIRST False Traces every token-bucket group before compiling any; incompatible with VLLM_USE_MEGA_AOT_ARTIFACT=1
TPU_MULTIHOST_BACKEND "" (mp) Multi-host backend: unset for native multiprocessing, "ray" for RayDistributedExecutor
TORCH_TPU_BASE_PORT 8070 Base TCP port for torch_tpu slice-builder communication
TORCH_TPU_MP_RENDEZVOUS_PORT None Explicit TCP port for the multi-host mp TCPStore rendezvous
TPU_ACCELERATOR_TYPE None Accelerator type override (for example "tpu7x", "v6e-8") for offline compilation or CPU tests
TPU_LIBRARY_PATH None libtpu.so to load; a custom file takes precedence over the installed libtpu package and skips the minimum-version check

Parallelism, mesh and scheduling

Name Default Effect
DP_SCHED_ENABLED False TPU data-parallel request scheduling optimizations
VLLM_TPU_SRPT_MAX_CONSECUTIVE_HOLDS 8 Steps a prefill chunk may be held back in SrptPrefillScheduler before it moves ahead (0 disables hold-back)
VLLM_TPU_SRPT_ATTN_WORK_CAP 0 Cap on a step's attention work in SrptPrefillScheduler while decode runs (0 disables)
VLLM_TPU_SRPT_ATTN_TILE_TOKENS 32 A chunk shrunk by the work cap ends on a multiple of this many tokens
TPU_PP_DYNAMIC_CHUNKS True Sizes pipeline-parallel microbatch chunks dynamically
TPU_PP_CHUNK_SLACK 0.1 Slack ratio for dynamic pipeline-parallel chunk sizing
TPU_PP_HANDOFF wave Pipeline handoff: wave (one collective per forward) or ring (point to point; needs libtpu 0.0.50 or later with torch_tpu 0.2.0 or later)
TPU_PP_RING_DEPTH 2 With ring, forwards a stage may queue for sending; the buffers are reserved before the KV cache is sized
TPU_PCP_TOPOLOGY_AWARE_MESH True Orders prefill context-parallel ranks along ICI neighbours
TPU_DCP_MLA_TOPK_CAP 0 Caps top-k per decode context-parallel rank in sparse MLA (0 disables)
TPU_DCP_LSE_MERGE_A2A False All-to-all LSE merge for decode context parallelism below TPU_DCP_LSE_MERGE_A2A_MAX_TOKENS (64)
TPU_TOKEN_BUCKET_EXTRA [] Extra token padding buckets to precompile, comma-separated
TPU_TOKEN_BUCKET_LINEAR False Linearly spaced token buckets instead of exponential

Mixture of experts and quantization

Name Default Effect
USE_MOE_SPARSE_CORE True SparseCore offload for MoE permutation and ragged gather and reduce; validated on v5p, v6e, 7 and 7x, other chips fall back to TensorCore
ONEHOT_MOE_PERMUTE_THRESHOLD None Token threshold between one-hot matmul and SparseCore sort in MoE routing
USE_MOE_FUSED_EP_KERNEL False Fused expert-parallel Pallas MoE kernel
MOE_FUSED_EP_KERNEL_IMPL None Fused EP kernel implementation: "v1" or "v2"
MOE_FUSED_EP_ENABLE_W4A8 False 4-bit weight, 8-bit activation execution in the fused EP kernel
MOE_FUSED_EP_SORTED_GATHER False Keeps the fused EP mesh in EP-rank order and all-gathers activations outside the kernel
FUSED_MOE_DECODE_KERNEL False Fused MoE decode Pallas kernel for eligible layers up to the token cap
FUSED_MOE_DECODE_KERNEL_MAX_TOKENS 256 Token cap for the fused MoE decode kernel
USE_MOE_TP_DECODE_KERNEL False Fused tensor-parallel FP8 MoE decode kernel; requires TPU_MOE_SKIP_PADDED_TOKENS=1
TPU_MOE_HIERARCHICAL_EP False Two-level intra-chip and inter-chip expert parallelism on dual-core v7x hosts
TPU_MOE_SEQUENCE_PARALLEL False Sequence parallelism around MoE blocks
TPU_ATTN_MOE_OVERLAP False Overlaps Qwen3.5 MoE post-attention norm and router gate with TP collectives on large buckets
TPU_MOE_ROUTER_TOPK "rowmax" MoE router top-k kernel implementation
TPU_MOE_FP8_ALL_GATHER False MoE activation all-gather in fp8
ENABLE_QUANTIZED_MATMUL_KERNEL False Sends quantized linear layers to the Pallas quantized matmul kernel
QUANTIZE_ON_LOAD_PREFIXES [] Module prefixes to quantize to FP8 at load
REQUANTIZE_WEIGHT_DTYPE "float8_e4m3fn" Target dtype for load-time linear weight requantization
REQUANTIZE_BLOCK_SIZE None Subchannel block size for load-time linear requantization
TPU_FP8_LINEAR_W8A16_MAX_ROWS 0 Small FP8 dense-linear buckets up to this many rows keep bf16 activations (W8A16); measured on v7x
TPU_GDN_QKVZ_KERNEL_LAYOUT False Stores the GDN in_proj_qkvz weight in the matmul's layout to remove a per-step copy
MOE_REQUANTIZE_WEIGHT_DTYPE "float8_e4m3fn" Target dtype for load-time MoE expert requantization (for example "fp4")
MOE_REQUANTIZE_BLOCK_SIZE None Block size for load-time MoE expert requantization
VLLM_TPU_MXFP4_DEVICE_DEQUANT True Dequantizes MXFP4 weights on the TPU during load rather than on the CPU

Attention and KV cache layouts

Name Default Effect
VLLM_TPU_BLOCK_MAJOR_KV False Block-major KV cache layout for Ragged Paged Attention
TPU_VLLM_ENABLE_UNIFIED_BLOCK_POOL None One KV block pool shared across hybrid attention layers (GDN plus full attention, or MLA)
TPU_LATENT_PROJ_INTRA_CHIP_TP False Shards MLA latent projections across the 2 TensorCores of one v7x chip at TP=1
TPU_MLA_MASKED_DENSE_ENABLED False Masked-dense MLA attention for short KV lengths
TPU_SPARSE_MLA_NOPE_LAYOUT "sparsecore" Sparse MLA non-positional KV layout: "sparsecore" or "tc"
TPU_SPARSE_MLA_ROPE_LAYOUT "sparsecore" Sparse MLA RoPE KV layout: "sparsecore" or "tc"
TPU_SPARSE_MLA_CHUNK_TOKENS None (kernel default 64) Query-token chunk size for sparse MLA attention
USE_RPA_PIPELINED_DMA_STAGING False Pipelined DMA staging in Ragged Paged Attention

Disaggregated serving (Raiden and KV transfer)

Name Default Effect
TPU_USE_RAIDEN_KV_CACHE_MANAGER False Raiden KV cache manager for prefill and decode disaggregation
TPU_RAIDEN_CONTROLLER_ADDRESS "" host:port of the Raiden coordinator (run_raiden_controller.py)
TPU_RAIDEN_JOB_NAME "" Role registered with the controller: "prefill" or "decode"
TPU_RAIDEN_ENGINE_ID "0" Engine replica identifier
TPU_RAIDEN_TRANSFER_PARALLELISM 8 Parallel DMA streams in TPURaidenConnector (the class is TPURaidenConnector; the environment variable reference spells it TpuRaidenConnector)
TPU_RAIDEN_RESHARD_IMPL "controller" KV resharding when prefill and decode topologies differ: "controller" or "store" ("store" runs the reshard service inside each engine instead of a separate controller)
TPU_KV_RESHARD_TRANSPORT "zmq" Host-side resharding transport: "zmq" or "raiden"
TPU_KV_TRANSFER_PORT "9100" TPUConnector KV transfer port
TPU_SIDE_CHANNEL_PORT "9600" TPUConnector side-channel handshake port

Profiling and debugging

Name Default Effect
USE_PHASED_PROFILER False Separate XProf traces for prefill and decode in one run (chapter 10)
PYTHON_TRACER_LEVEL 1 Python host call-stack tracing: 0 off, 1 standard, 2 verbose
HOST_TRACER_LEVEL 2 XLA runtime host activity tracing level
DEVICE_TRACER_LEVEL 1 TensorCore and SparseCore execution tracing level
TPU_TRACE_MODE "TRACE_COMPUTE" SparseCore trace mode, for example "TRACE_COMPUTE_AND_DMA"
TPU_NUM_SPARSE_CORES_TO_TRACE 1 SparseCores traced when SparseCore tracing is on
TPU_KERNEL_ITER_MODE False Hot-reloads Pallas kernels without restarting the server (TPU_KERNEL_RELOAD_MODULES)

SGLang-TorchTPU

The variables chapter 19 uses, as defined in sglang_tpu/envs.py. That file defines many more; read it for the full set.

Name Default Effect
SGLANG_PLATFORM Not documented Selects the TPU plugin: tpu in the recipes (benchmark/tpu/common_env.sh), tpu_oot in the README's Docker command
SGLANG_TPU_CHECK_RECOMPILATION False Logs compiles that happen after warmup
SGLANG_TPU_CHECK_RECOMPILATION_SITES False Also attributes eager compiles to SGLang source lines, at about 9 µs per eager op
SGLANG_TPU_ENABLE_EXPERIMENTAL_SPEC_WORKER True Routes DFLASH and DSPARK to TpuBlockSpecWorker and MTP and EAGLE3 to TpuChainSpecWorker
SGLANG_TPU_FUSED_MOE_SC_GATHER True Offloads the MoE permute and unpermute gather to SparseCore
SGLANG_TPU_HICACHE_WRITE_BACK_COPY_AHEAD_TOKENS None (four chunked-prefill chunks) Tokens of the next eviction victims kept copied to host for HiCache on Raiden; 0 backs them up synchronously
SGLANG_TPU_USE_BLOCK_MAJOR_KV False Allocates RPA v3 KV so all layers of a page form one row, for single-DMA Raiden P/D transfers; both P/D servers must agree
SGLANG_TPU_USE_SEQ_ALONG_LANE_KV False Reads the KV cache with the token index on the lane axis; 256 instead of 512 bytes per token at one KV head and fp8

Other variables the book sets

Name Default Effect
TPU_VISIBLE_CHIPS Set by Ray per worker Ray isolates a worker's TPU device with it, as it sets CUDA_VISIBLE_DEVICES on GPUs (chapter 15). TorchTPU overwrites it to match TPU_VISIBLE_DEVICES
PYTHONHASHSEED Random Must be the same fixed value (the llm-d KV-cache offloading and P2P sharing examples use 0) on every engine that shares block hashes, or no hash matches across pods (chapter 20)

See also

These guides set the variables above in context, in the order a task needs them:

References