Extending the stack: custom kernels, compiler passes, out-of-tree plugins and agent workflows¶
Related chapters
Section 6.1 is chapter 12 (with the guide Write a Pallas kernel). Sections 6.2 to 6.4.2 are chapter 25, which builds on chapter 14 for TorchTitan, chapters 18 and 19 for the serving engines and chapter 20 for the llm-d router. Section 6.4.3 is chapter 26. The repository pages (torch_tpu, vLLM-TorchTPU, SGLang-TorchTPU, TorchTitan, tpu-agent-suite) list the entry points.
This page covers how to design, write, verify and ship new hardware kernels (Pallas, Kiln C++ Mosaic kernels, Helion, Tokamax), C++ ATen/StableHLO lowerings and MLIR passes, c10d windows (WindowTpu), serving-engine plugins and patches (vLLM-TorchTPU, SGLang-TorchTPU), whole-decoder Pallas megakernels, distributed training sharding and graph passes (TorchTitan), llm-d EndpointPicker plugins, and multi-harness agent skills (tpu-agent-suite).
The page in one picture: each band is one section, ordered as the stack is, with the layers that run on torch_tpu above it and the kernels it calls below. Each box is something the section shows you how to extend; the two tags mark kernel options outside the supported public path: Helion is experimental and Kiln is internal to torch_tpu.
6.1 Writing custom TPU kernels (Pallas, Kiln, Helion and Tokamax)¶
In one sentence: Unlike GPU SIMT threads where each thread computes a scalar element and relies on hardware L1/L2 caches, a TPU kernel is a single-threaded tile program per TensorCore (or SparseCore) that explicitly orchestrates asynchronous DMA transfers (HBM \(\leftrightarrow\) VMEM/SMEM) via semaphores while keeping the MXU systolic arrays (\(128 \times 128\) on v5e and v5p, \(256 \times 256\) on v6e and v7x) and the \(8 \times 128\) VPU vector lanes fed.
How it works: memory hierarchy, tiling and the double-buffered DMA pipeline¶
Both scratchpads are inside the TensorCore, and a Pallas kernel moves every operand into them itself: blocks travel between HBM and VMEM by asynchronous DMA, which the scalar unit issues, and small metadata is prefetched into SMEM. The compute units load from and store to these scratchpads only.
Read one column: during step t the body computes on block t while the DMA engines fetch block t + 1 into the other slot and write back the output of step t − 1. Every input and output BlockSpec gets two VMEM buffers, one in use by the body while the other is filled or drained, which is why the VMEM budget counts every block twice.
Note
VMEM capacity differs by generation: 64 MiB per TensorCore on v7x (chapter 1); elsewhere ask the hardware with pltpu.get_tpu_info().vmem_capacity_bytes (chapter 12). A kernel's usable budget is the scoped VMEM limit, not the physical size. HBM per chip is 16 GiB on v5e, 95 GiB on v5p, 32 GiB on v6e and 192 GiB on v7x, at 819, 2,765, 1,638 and 7,380 GB/s (hardware reference). SMEM is 1 MiB per core on v7x (smem_capacity_bytes in JAX's tpu_info.py). A kernel moves blocks between HBM and VMEM with pltpu.async_copy and waits on SemaphoreType.DMA semaphores.
6.1.1 Writing a Pallas TPU kernel and calling it from PyTorch¶
Danger
JAX must not run on the TPU in a process where TorchTPU owns it. torch.tpu.pallas.jax_op uses JAX only to trace and export: on the first call with a new signature it turns each tensor's shape and dtype into a jax.ShapeDtypeStruct, traces the jax.jit-wrapped function, and exports it with jax.export for the tpu platform (abstract compile-only devices from _mock_device.py). The serialized StableHLO module, with the Pallas kernel carried as a Mosaic payload, is registered with TorchTPU's runtime; no tensor is ever converted to a jax.Array. The verifier's VerificationMode.FULL does create JAX devices, which initializes JAX's other backends including the TPU, so in a TorchTPU process use VerificationMode.STATIC (chapter 12).
Note
cpu_export_jax_op is SGLang-TorchTPU's (sglang_tpu/pallas_jax_op.py); vLLM-TorchTPU calls jax_op directly (vllm-torchtpu Coding Guidance, section 2).
Worked example: block-scaled matmul with an epilogue, scalar prefetch and custom autograd¶
# 1. PURE JAX / PALLAS KERNEL MODULE (e.g., my_kernels/scaled_linear.py)
# NOTE: In vllm-torchtpu, files under src/vllm_torchtpu/kernels/ MUST NOT import torch.
import functools
import jax
import jax.numpy as jnp
from jax.experimental import pallas as pl
from jax.experimental.pallas import tpu as pltpu
def _scaled_linear_fwd_kernel(
# Scalar prefetch refs (SMEM) come FIRST in the kernel signature
m_bound_sref, # SMEM [1] int32: dynamic active token count
# HBM/VMEM input refs bridged by BlockSpec
x_ref, # VMEM [bm, bk] bfloat16
w_ref, # VMEM [bk, bn] float8_e4m3fn
scale_ref, # VMEM [1, bn] float32 (broadcastable along sublanes)
# Output refs (VMEM)
out_ref, # VMEM [bm, bn] bfloat16
# Scratch refs (VMEM accumulator across K loop)
acc_scratch_ref, # VMEM [bm, bn] float32
*,
num_k_steps: int,
):
m_tile = pl.program_id(0)
k_step = pl.program_id(2)
# Zero accumulator on first K step
@pl.when(k_step == 0)
def _init_acc():
acc_scratch_ref[...] = jnp.zeros_like(acc_scratch_ref)
# Skip compute if the entire M-tile is beyond active tokens (dynamic early-exit)
bm = x_ref.shape[0]
active_m = m_bound_sref[0]
@pl.when(m_tile * bm < active_m)
def _compute():
lhs = x_ref[...] # [bm, bk] bf16
rhs = w_ref[...] # [bk, bn] fp8_e4m3fn
# MXU hardware contraction accumulating in FP32
partial = jnp.dot(lhs, rhs, preferred_element_type=jnp.float32)
acc_scratch_ref[...] += partial
# Write scaled BF16 output on final K step
@pl.when(k_step == num_k_steps - 1)
def _epilogue():
scaled = acc_scratch_ref[...] * scale_ref[...] # VPU broadcast multiply
out_ref[...] = scaled.astype(out_ref.dtype)
def scaled_linear_pallas(
x: jax.Array, # [M, K] bf16 (M divisible by bm=128, K divisible by bk=128)
w: jax.Array, # [K, N] fp8_e4m3fn (N divisible by bn=128)
scale: jax.Array, # [1, N] f32
m_bound: jax.Array, # [1] i32
bm: int = 128,
bn: int = 128,
bk: int = 128,
) -> jax.Array:
m, k = x.shape
_, n = w.shape
num_m, num_n, num_k = m // bm, n // bn, k // bk
grid_spec = pltpu.PrefetchScalarGridSpec(
num_scalar_prefetch=1,
# Dimension semantics: 'parallel' allows compiler to reorder; 'arbitrary' enforces K reduction order
grid=(num_m, num_n, num_k),
in_specs=[
pl.BlockSpec((bm, bk), lambda i, j, p, _: (i, p)),
pl.BlockSpec((bk, bn), lambda i, j, p, _: (p, j)),
pl.BlockSpec((1, bn), lambda i, j, p, _: (0, j)),
],
out_specs=pl.BlockSpec((bm, bn), lambda i, j, p, _: (i, j)),
scratch_shapes=[pltpu.VMEM((bm, bn), jnp.float32)],
)
return pl.pallas_call(
functools.partial(_scaled_linear_fwd_kernel, num_k_steps=num_k),
out_shape=jax.ShapeDtypeStruct((m, n), jnp.bfloat16),
grid_spec=grid_spec,
compiler_params=pltpu.CompilerParams(
dimension_semantics=("parallel", "parallel", "arbitrary"),
vmem_limit_bytes=32 * 1024 * 1024,
),
)(m_bound, x, w, scale)
Test before use
The kernel above is an illustrative example, not a kernel from a repository. Two things to check before you rely on it: a jnp.dot of a bf16 tile with a float8_e4m3fn tile may need an explicit cast, depending on the JAX version; and the early exit leaves the accumulator of a skipped tile at zero, so the rows past m_bound are written as zeros. Test it in the strict interpreter (interpret=pltpu.InterpretParams()) against a PyTorch reference first, as chapter 12 does.
# 2. PYTORCH BRIDGE (e.g., my_ops/scaled_linear_op.py)
import torch
from my_kernels.scaled_linear import scaled_linear_pallas
# jax_op(name, fn=None, /, *, donate_argnums=None, mesh=None,
# input_partition_specs=None, output_partition_specs=None)
# The name comes first and needs exactly one "::". Every parameter of the JAX
# function must be annotated; non-tensor parameters (bm, bn, bk) become static
# arguments, inferred from the annotations and part of the cache key.
# jax_op returns a torch.library CustomOpDef and registers a fake (meta) kernel.
scaled_linear = torch.tpu.pallas.jax_op("my_ns::scaled_linear", scaled_linear_pallas)
# A jax_op has no gradient of its own: register one on the returned op.
def _setup_context(ctx, inputs, output):
x, w, scale, m_bound, bm, bn, bk = inputs
ctx.save_for_backward(x, w, scale)
def _backward(ctx, grad_out: torch.Tensor):
x, w, scale = ctx.saved_tensors
# ATen fallback; a training kernel would register a second jax_op here.
grad_x = (grad_out.float() * scale) @ w.to(torch.float32).T
return grad_x.to(x.dtype), None, None, None, None, None, None
scaled_linear.register_autograd(_backward, setup_context=_setup_context)
Note
In the 0.2.0 source (pallas.py) the signature is jax_op(name, fn=None, /, *, donate_argnums, mesh, input_partition_specs, output_partition_specs). Static arguments are inferred, and jax_op itself registers the custom op and its fake kernel, so no second torch.library.custom_op wrapper is needed. The source decorates jax_op as experimental, while the custom-kernel guide calls the Pallas path "Production Ready"; pin your TorchTPU version. Bounded dynamic shapes are not supported for jax_op kernels (chapter 12).
6.1.2 jax_op, SGLang's cpu_export_jax_op and build-time embedded MLIR compared¶
| Bridge Mechanism | Source Location | How It Lowers & Caches | Primary Use Case |
|---|---|---|---|
torch.tpu.pallas.jax_op |
src/torch_tpu/_internal/pallas/pallas.py |
Traces the jax.jit-wrapped function on ShapeDtypeStruct placeholders, exports it with jax.export for the tpu platform, strips debug locations, fingerprints the module (BLAKE2) and registers it with the C++ runtime under that fingerprint; registers a torch.library custom op and a fake kernel. Keyword options: donate_argnums, mesh, input_partition_specs, output_partition_specs (with get_pallas_mesh for kernels that run across chips). |
User custom kernels and Pallas ops in all three serving and training repositories. vLLM-TorchTPU calls it directly from its layers/adapter/custom_ops/*_op.py bridges. |
cpu_export_jax_op (SGLang-TorchTPU) |
sglang_tpu/pallas_jax_op.py |
Reuses jax_op's internal signature checks and static-argument inference, builds its own jax.jit (with output shardings from the partition specs), and registers a torch.library.custom_op; imports tpu_info_for_cpu_export from sglang_tpu/pallas_export.py for CPU-side export. |
SGLang-TorchTPU kernels. It is not on TorchTPU's public API list. |
| Build-Time Embedded MLIR | scaled_mm_generate.pyscaled_grouped_mm_generate.py |
"Generate blockwise scaled mm Pallas kernel MLIR module embedded C++ files" (the generator's docstring): the Bazel macro define_scaled_mm_kernel in csrc/ops/scaled_mm/kernels/defs.bzl runs it at build time and compiles the StableHLO artifacts into C++ data arrays used by the operator's lowering. |
Built-in scaled matmul ops such as torch._scaled_mm and torch._scaled_grouped_mm (chapter 12). |
Note
cpu_export_jax_op lives in SGLang-TorchTPU. The build-time kernels are generated under csrc/ops/scaled_mm/kernels/; Kiln's SpliceStablehlo is a different mechanism that splices StableHLO into a Kiln kernel body.
6.1.3 Production kernels across the repositories¶
The production kernels in torch_tpu, vllm-torchtpu, sglang-torchtpu and torchtitan fall into eight families:
| Kernel Family | Canonical Source Files | Core Hardware & Algorithmic Pattern | Key Env Vars / Tunables |
|---|---|---|---|
1. Ragged Paged Attention v3 (ragged_paged_attention_v3) |
• vllm_torchtpu/kernels/ragged_paged_attention/v3/kernel.py• vllm_torchtpu/kernels/ragged_paged_attention/v3/kernel_hd64.py• vllm_torchtpu/kernels/experimental/batched_rpa/kernel.py• sglang_tpu/attention/ |
• 5D Dual-Tiled KV Page Layout: [num_blocks, page_size // packing, kv_heads * 2, packing, head_dim] (interleaved K/V per head so one DMA fetches both K and V).• 3-Zone Request Distribution ( distribution[3] = [n_decode, n_prefill, n_mixed]): Prefetched into SMEM; dynamically selects specialized decode (\(q\_len=1\)), prefill, or mixed loop bounds without recompiling.• In-Kernel KV Cache Update + Manual Async DMA Ring: Updates new KV tokens in-place while triple-buffering page DMAs via custom pltpu.BufferedRef (bref_override.py). |
USE_RPA_PIPELINED_DMA_STAGING=1 |
2. Multi-Head Latent Attention (mla_v2, sparse_mla, masked_dense) |
• vllm_torchtpu/kernels/mla/v2/kernel.py• vllm_torchtpu/kernels/mla/sparse/kernel.py• vllm_torchtpu/kernels/mla/masked_dense/kernel.py• vllm_torchtpu/kernels/deepseek_v4/streamindex_topk/streamindex_topk.py |
• Absorbed Latent Cache: Packs compressed latent \(c_{KV} \in \mathbb{R}^{512}\) (NoPE, often FP8 quantized with UE8M0 scales) + \(k_{RoPE} \in \mathbb{R}^{64}\) (BF16) into a single aligned page row (576 or 640 bytes).• Sparse MLA / DSA (DeepSeek-V4 & GLM-5.2): Runs streamindex_topk + sparsecore_topk (32 SparseCore subcores) to select top-\(k\) candidate tokens, gathers NoPE/RoPE rows on SparseCore (dsa_gather.py / csa_gather.py), or converts top-\(k\) indices into a dense bitmask (csa_mask.py) for masked_dense when token density crosses cost_model.py. |
VLLM_TPU_INDEXER_KV_CACHE_MODE ("sal", "has", "xla")TPU_SPARSE_MLA_CHUNK_TOKENSTPU_STREAMIDX_CHUNK_TOKENSTPU_DSV4_ATTN_INTRA_CHIP_TP |
3. Gated DeltaNet (gdn/v3) & Kimi Delta Attention (mega_kda) |
• vllm_torchtpu/kernels/gdn/v3/wrapper.py• vllm_torchtpu/kernels/gdn/v3/compute_gdn.py• vllm_torchtpu/kernels/experimental/gdn_pcp_fused/pcp_wrapper.py• vllm_torchtpu/kernels/kimi_k3/mega_kda/kernel.py |
• Fused Causal Conv1D + Chunkwise WY Recurrence: Fuses depthwise causal conv1d state update, SiLU, L2 norm, triangular matrix inversion \((I + L)^{-1}\) via Neumann series/block substitution, and recurrent state \(S_t \in \mathbb{R}^{H \times D_K \times D_V}\) update in VMEM.• Speculative State Checkpointing: Maintains recurrent_window = 1 + max_verify_tokens state slots per sequence so rejected draft tokens roll back in \(O(1)\) pointer update.• PCP-Fused GDN: Overlaps Prefill Context Parallelism state propagation across ranks with chunk recurrence. |
KDA_OVERLAP_H0_DMA=1KDA_OVERLAP_HT_DMA=1KDA_PACK_HEAD_INV=1KDA_FWD_MB |
4. Fused Expert-Parallel MoE (fused_moe/v2) & MegaBlocks GMM (gmm_v2) |
• vllm_torchtpu/kernels/fused_moe/v2/kernel.py• vllm_torchtpu/kernels/megablox/gmm_v2.py• sglang_tpu/moe/pallas/gmm_v2.py• torch_tpu/_internal/ops/scaled_grouped_mm/kernels/rowwise_scaled_grouped_mm_kernel.py |
• gmm_v2 (Grouped Matrix Multiply v2): Builds a static (group_ids, m_tile_ids) visit schedule in SMEM from cumulative group_offsets; supports BF16, FP8 (e4m3fn), INT4 (W4A16 / vmem-fp8), MXFP4, and NVFP4 (W4A16 / W4A8) with fused gate+up activation (silu, gelu, swiglu_oai, situ).• fused_ep_moe_v2 & adaptive_fused_moe: Single SPMD Pallas program executing router top-\(k\), cross-rank remote DMA token dispatch, both expert GEMMs (with HEIGHT_RUNGS ladder to skip padding rows), and remote DMA combine. |
USE_MOE_FUSED_EP_KERNEL=1MOE_FUSED_EP_KERNEL_IMPL ("v2", "adaptive")MOE_FUSED_EP_ENABLE_W4A8=1SGLANG_TPU_INT4_MOE_MODE |
5. SparseCore Ragged Gather & Scatter-Reduce (sparse_core/) |
• vllm_torchtpu/kernels/sparse_core/ragged_gather_v2.py• vllm_torchtpu/kernels/sparse_core/ragged_gather_reduce_v2/kernel.py• vllm_torchtpu/kernels/sparse_core/ragged_scatter.py |
• Subcore-Parallel Gather/Reduce: Uses pl.kernel(..., mesh=pltpu.create_tensorcore_mesh(..., core_type=pltpu.CoreType.SC_VECTOR_SUBCORE)) across all 32 SparseCore vector subcores on v5p/v6e/v7x.• Offloads MoE token permutation ( x[token_indices]) and top-\(k\) weighted unpermutation (sum_k w_{t,k} y_{t,k}) from TensorCore VPU/HBM channels. |
SGLANG_TPU_FUSED_MOE_SC_GATHER=1MOE_FUSED_EP_SORTED_GATHER=1SC_ALLREDUCE_ALLGATHER_OFFLOAD_MIN_BYTES |
| 6. Splash Attention & Diffusion FlashAttention | • torch_tpu/_internal/ops/splash_attention.py• vllm_torchtpu/kernels/diffusion_attention/kernel.py• vllm_torchtpu/kernels/diffusion_attention/block_sizes.py |
• Training (splash_sdpa): Precomputes sparse block-mask metadata (MaskInfo) on CPU NumPy (_make_numpy_splash_mask_infos) so only non-masked tiles are visited on MXU; bridges forward & backward via _SplashAttentionFn.• Diffusion ( flash_attention_bshd): Uses Fixed-\(M\) Softmax (use_fixed_m=True, precomputing rigorous row-norm upper bounds \(m_h = \|Q_h\|_{\infty,2} \|K_h\|_{\infty,2}\)) to eliminate the online softmax rescaling dependency inside the inner KV loop. |
autotune_block_sizes(..., kernel_mode="fixedm") |
7. Fused Linear Softmax Cross-Entropy (linear_softmax_cross_entropy_loss) |
• torchtitan/experiments/tpu/kernels/linear_softmax_cross_entropy_loss.py |
• Vocabulary-Tiled Online LogSumExp: Tiles hidden states \([B \cdot S, H]\) (b_block_size=1024) and vocabulary weights \([H, V]\) (v_block_size=2048) in VMEM, accumulating running \((m_i, \ell_i)\) online without materializing the full \([B \cdot S, V]\) FP32 logit tensor in HBM. |
b_block_size=1024h_block_size=512v_block_size=2048 |
8. Pipelined Collectives (all_gather_matmul & matmul_reduce_scatter) |
• vllm_torchtpu/kernels/collectives/all_gather_matmul.py• sglang_tpu/fp8_moe_fused_rs.py• vllm_torchtpu/kernels/kimi_k3/collectives.py |
• Bidirectional ICI Ring + MXU Overlap: Splits local shard into ring chunks; at step \(s\), computes MXU matmul on chunk \(s\) while simultaneously pushing chunk \(s\) to left_neighbor and right_neighbor via pltpu.make_async_remote_copy and synchronizing with local_barrier (SemaphoreType.GLOBAL). |
None in the env files |
Note
Every file path in this table is in the public repositories, and every environment variable in the last column is declared in src/vllm_torchtpu/envs.py, sglang_tpu/envs.py or SGLang's environ.py. The third column summarises each kernel; read the kernel code for exact page layouts and byte counts. The cross-entropy block sizes (1024, 512, 2048) are the function defaults in the TorchTitan kernel.
Note
The diffusion autotuner's fixed-m mode is kernel_mode="fixedm" (_FIXED_M_KERNEL_MODES in block_sizes.py). SGLang-TorchTPU's attention code is under sglang_tpu/attention/, and TorchTitan's fused cross-entropy kernel is experiments/tpu/kernels/linear_softmax_cross_entropy_loss.py.
Worked example: a bidirectional ICI ring all_gather_matmul inside one Pallas kernel¶
A simplified sketch of the pattern in vllm_torchtpu/kernels/collectives/all_gather_matmul.py, which overlaps inter-chip DMA with MXU work:
from jax import lax
from jax.experimental import pallas as pl
from jax.experimental.pallas import tpu as pltpu
from vllm_torchtpu.kernels.collectives.util import local_barrier
def _ring_ag_matmul_step(
x_hbm_ref, # Local shard [M_local, K] in HBM
w_vmem_ref, # Weight tile [K, bn] already prefetched in VMEM
out_vmem_ref, # Output tile [M_global, bn] in VMEM
scratch_hbm_ref, # Ping-pong ring buffers [2, M_local, K] in HBM
send_sems, # SemaphoreType.DMA((2,))
recv_sems, # SemaphoreType.DMA((2,))
axis_name: str,
tp_size: int,
):
my_id = lax.axis_index(axis_name)
left_peer = (my_id - 1) % tp_size
right_peer = (my_id + 1) % tp_size
# 1. Global barrier across neighbors before issuing remote DMAs (prevents race on recv_sems)
local_barrier(left_peer, right_peer, double_barrier=True)
# 2. Launch async remote DMA of local shard to right_peer's scratch_hbm_ref[0]
remote_copy = pltpu.make_async_remote_copy(
src_ref=x_hbm_ref,
dst_ref=scratch_hbm_ref.at[0],
send_sem=send_sems.at[0],
recv_sem=recv_sems.at[0],
device_id={axis_name: right_peer},
)
remote_copy.start()
# 3. Overlap: Compute local matmul slice WHILE remote ICI DMA is in flight.
# ... MXU dot(x_local_vmem, w_vmem_ref) -> out_vmem_ref[my_id * M_local : (my_id+1) * M_local] ...
# 4. Wait for remote DMA completion before advancing to next ring hop
remote_copy.wait()
A sketch
This is a one-direction sketch: the real kernel issues left and right remote copies (left_remote_copy_op, right_remote_copy_op, both pltpu.make_async_remote_copy) over a full ring loop. local_barrier(left_neighbor, right_neighbor, double_barrier=True) matches the signature in collectives/util.py. Read the file before you copy the sketch.
6.1.4 C++ Mosaic kernels with Kiln (csrc/internal/mosaic/kiln/)¶
In one sentence: Kiln (csrc/internal/mosaic/kiln/kiln.h) is, in its header's words, "a small, Pallas-shaped kernel language for authoring Mosaic TPU kernels in C++", used inside torch_tpu's own operator lowerings; a kernel is wrapped in a StableHLO custom call by CreateKilnCustomCallOp (kiln_custom_call.h).
The header's own example and its mapping onto Pallas:
// From the header comment in csrc/internal/mosaic/kiln/kiln.h
auto kernel = CreateKernel(
GridSpec{.name = "add", .grid = {m / tm}},
InSpec{f32(tm, n), row_map},
InSpec{f32(tm, n), row_map},
OutSpec{f32(tm, n), row_map},
[](VmemRef x, VmemRef y, VmemRef out) {
Store(out, Load(x) + Load(y));
});
Kiln concept (kiln.h) |
Pallas TPU equivalent |
|---|---|
GridSpec / InSpec / OutSpec / ScratchSpec |
pallas_call specs |
std::optional<InSpec / OutSpec> |
An optional operand, received as std::optional<VmemRef> |
ProgramId / NumPrograms |
pl.program_id / pl.num_programs |
VmemRef / SmemRef / HbmRef (TypedRef<MemorySpace>), Ref |
Refs typed by memory space (pltpu.VMEM / SMEM / ANY); Ref when the space is known only at run time |
ref(0, 0), ref(0, Slice(c, kChunk), all) |
Ref slicing; emits tpu::MemRefSlice / Squeeze |
Load(ref) / Store(ref, value) |
ref[...] / ref[...] = value (a Tile for VMEM, a Scalar for SMEM) |
Tile, Scalar |
A jax.Array value inside the kernel; scalar (SMEM or grid index) values |
If / For / RunScoped |
pl.when / lax.fori_loop / pl.run_scoped |
AsyncCopy / MakeAsyncCopy, SyncCopy |
pltpu.async_copy / pltpu.make_async_copy, pltpu.sync_copy |
AsyncRemoteCopy / MakeAsyncRemoteCopy, DeviceId |
pltpu.async_remote_copy / pltpu.make_async_remote_copy, tpu.device_id |
Semaphore / SemaphoreArray |
pltpu.SemaphoreType / tpu.sem_alloc |
kDynamic / ref.Dim(axis) / MultipleOf |
Dynamic memref dimensions and divisibility assumptions (pl.multiple_of) |
Two helpers sit next to the core: EmitPipeline in lib/pipeline.h streams HBM operands through VMEM blocks, and SpliceStablehlo(mlir_text, ...) in mlir/stablehlo_splice.h inlines a StableHLO module string into a kernel body as a Tile. The end-to-end tests are in kiln_e2e_test.cc.
Note
The header creates kernels with CreateKernel(GridSpec{...}, InSpec{...}, OutSpec{...}, body), uses free functions Load(ref) and Store(ref, value), and the custom-call builder is CreateKilnCustomCallOp. Kiln lives under csrc/internal/ and is not on TorchTPU's public API list; chapter 12 mentions it only as an internal C++ language.
6.1.5 Tokamax kernels and portable kernels with Helion¶
TorchTPU's custom-kernel guide lists three ways to get a kernel, in order of preference:
| Option | Status (guide) | Use it for |
|---|---|---|
| Tokamax | Production Ready | Drop-in kernels for common LLM and MoE building blocks without writing kernel code: grouped matmul, token gathers and scatters; paged attention, Gated DeltaNet, Kimi Delta Attention, MLA; TopK. Authored in JAX/Pallas with autotuning; "Under the hood, Tokamax uses torch.tpu.pallas.jax_op" and exposes native PyTorch APIs |
Pallas with jax_op |
Production Ready (guide); experimental decorator in the 0.2.0 source | A bespoke operation not covered by PyTorch or Tokamax (6.1.1) |
| Helion | Experimental | Kernels portable across accelerators, written in a PyTorch-native DSL; "For production workloads, use Tokamax or torch.tpu.pallas.jax_op" |
The guide's Helion example:
import helion
import helion.language as hl
import torch
# 1. Define the kernel in Helion
@helion.kernel
def add_vectors(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
# Standard PyTorch host-side setup
x, y = torch.broadcast_tensors(x, y)
out = torch.empty_like(x)
# Device execution loop over automatically partitioned tiles
for tile in hl.tile(out.size()):
out[tile] = x[tile] + y[tile]
return out
# 2. Call it like a standard PyTorch function
x = torch.tensor([1.0, 2.0, 3.0], device="tpu")
y = torch.tensor([4.0, 5.0, 6.0], device="tpu")
z = add_vectors(x, y)
Note
Tokamax calls jax_op for you. Splash attention is TorchTPU's own torch.tpu.ops.splash_sdpa (chapter 12).
6.1.6 Pallas Kernel Verification (torch.tpu.pallas.verifier)¶
In one sentence: torch.tpu.pallas.verifier.verify(target, args, kwargs=None, *, mode=..., options=None) (documented in the verifier README) "finds concurrency, memory-safety, and integration bugs in Pallas TPU kernels and in the PyTorch programs that call them through @jax_op", and "Everything runs on CPU: no TPU is needed". It is experimental.
Target passed to verify |
Checks (README) |
|---|---|
A @jax_op |
Op-contract, TPU-lowering, model-checking, autograd-parity and CPU-interpret checks |
A raw JAX function (called with jax.Array or jax.ShapeDtypeStruct arguments) |
Model-checking and CPU-interpret checks |
Any other callable, such as an nn.Module |
Traced into an FX graph whose buffer donation and aliasing are checked; every @jax_op call in the graph is then verified for the shapes and dtypes it is called with |
- Modes (
VerificationMode):FULL, the default, adds "dynamic checks that run the kernels on CPU in TPU interpret mode (schedule sweeps and autograd parity)", and creating the JAX CPU devices initializes the other JAX backends, the TPU included.STATICruns "only checks that never execute the kernels: contracts, TPU lowering, FX graph analysis, and model checking"; it needs no JAX devices and suits a process that uses the TPU through TorchTPU. VerificationReport(a frozen dataclass):findings,checked_phases,passed("True if and only if the report contains no errors"),findings_by_severity(severity),findings_by_category(category),summary(),raise_for_errors()(raisesVerificationError, a subclass ofAssertionErrorwith areportproperty).VerificationFinding:category,severity,phase,message,op_name,source_location,format().SeverityhasERROR,WARNING,INFO; onlyERRORfails a report.FindingCategoryhas one member,VERIFICATION_INCOMPLETE.verifyis forbidden inside a compiled region (forbid_in_torch_compile).
import torch
from torch.tpu.pallas import verifier
# A jax_op with example arguments, like torch.library.opcheck. In a process that
# owns the TPU through TorchTPU, use STATIC; run FULL in its own process with
# JAX_PLATFORMS=cpu.
report = verifier.verify(scaled_linear, (x_sample, w_sample, scale_sample, m_bound_sample),
mode=verifier.VerificationMode.STATIC)
print(report.summary()) # lists the phases that actually ran
report.raise_for_errors() # VerificationError if any ERROR finding
# A PyTorch program that calls jax_op kernels
assert verifier.verify(my_transformer_block, (hidden_states, kv_cache)).passed
Note
The Phase enum and VerificationOptions class define no public members, and passed depends only on ERROR findings. Read what a report covered from report.checked_phases (chapter 12).
6.2 Extending torch_tpu: ATen lowerings, MLIR passes, c10d windows, multi-ABI builds and developer policies¶
In one sentence: When an operator is part of standard PyTorch (aten::*), needs a StableHLO optimization pass, or introduces a new public torch.tpu.* API, extend torch_tpu in C++ and Python: an ATen lowering in its own directory under csrc/ops/ registered in csrc/eager/tpu_aten_kernels.cc, a pass in csrc/mlir/passes/, and the API rules and lifecycle policy in docs/developers/ (chapter 25).
A registered kernel only checks its arguments and queues a deferred op that carries the op's StableHLO builder; a background worker later builds the StableHLO, runs the optimization passes and the PjRt compile, and executes it, one op at a time in the default strict eager mode or as a fused block with TORCH_TPU_DEFER_AND_FUSE=1. An op with no kernel reaches the fallback, which by default raises instead of running on the CPU.
Note
The registration block is in csrc/eager/tpu_aten_kernels.cc, each kernel has its own directory csrc/ops/<op>/, the optimization passes run as the torch-tpu-optimization-pipeline (csrc/mlir/pipeline.cc), and the PJRT client is csrc/pjrt/pjrt_client.cc. The glue libraries (6.2.4) are a build-time packaging layer, not a step in dispatch. An op with no kernel reaches TpuMissingOpFallback, which raises NotImplementedError unless an internal knob turns on the CPU fallback: unsupported ops do not silently fall back to the CPU (chapter 25, "When no kernel is registered").
6.2.1 Recipe 1: adding a C++ ATen operator lowering (csrc/ops/<op>/)¶
Each ATen op has a StableHLO builder and a kernel in csrc/ops/<op>/<op>_aten_kernels.{h,cc}, and one ImplStable line in the registration block. From csrc/ops/hardswish/hardswish_aten_kernels.cc, trimmed as in chapter 25:
absl::StatusOr<mlir::MlirOp> BuildHardswishShlo(mlir::MlirOp input_op) {
auto type = GetTensorTypeOrDie(input_op);
TT_ASSIGN_OR_RETURN(auto element_type,
ConvertTo<mlir::ElementType>(type.getElementType()));
mlir::MlirOp three = MakeConstantLike(input_op, 3.0, element_type);
mlir::MlirOp six = MakeConstantLike(input_op, 6.0, element_type);
mlir::MlirOp zero = MakeConstantLike(input_op, 0.0, element_type);
mlir::MlirOp x_plus_3 = mlir::stablehlo::Add(input_op, three);
mlir::MlirOp relu6 = mlir::stablehlo::Clamp(zero, x_plus_3, six);
mlir::MlirOp num = mlir::stablehlo::Mul(input_op, relu6);
return mlir::stablehlo::Div(num, six);
}
at::Tensor AtenHardswish(const at::Tensor& self) {
TT_KERNEL(OpName::kHardswish, _, (self), {
TT_CHECK_THROW(self.is_floating_point(), error::kInvalidArgument)
<< "expected the input dtype to be floating point, got "
<< ToString(self.scalar_type());
TT_ASSIGN_OR_THROW(
at::Tensor result,
UnaryOp(self, BuildHardswishShlo,
{.op_param_cache_keys = OpParamCacheKeys::Empty()}));
return result;
});
}
// csrc/eager/tpu_aten_kernels.cc
TORCH_LIBRARY_IMPL(aten, PrivateUse1, m) {
...
ImplStable<OpName::kHardswish>(m, AtenHardswish);
...
}
A standard ATen op always uses ImplStable (a template defined at the top of tpu_aten_kernels.cc); ImplInternal, ImplExperimental and ImplDeprecated are for TPU custom ops. A lowering must build StableHLO itself: calling another ATen op inside TT_KERNEL trips a fatal composite-op check. Then remove the op from UNREGISTERED_OPS in tests/native_functions_data.py, add CPU-comparison tests to tests/ops_unit_test.py, and confirm CI runs them (chapter 25, "Adding an ATen lowering").
6.2.2 Recipe 2: writing an mlir::stablehlo optimization pass (csrc/mlir/passes/)¶
TorchTPU's own passes live in csrc/mlir/passes/ and run from csrc/mlir/pipeline.cc, registered as the torch-tpu-optimization-pipeline. The pass IR can be dumped with the internal variable TORCH_TPU_INTERNAL_DUMP_MLIR_PASSES_TO ("print" or a directory path, per env_vars.h).
- Passes in
csrc/mlir/passes/(the order ispipeline.cc's): guard_zero_operand_custom_calls.cc: guards zero-operand custom calls around a CSE pass, then unguards them.reassociate_norm_weights.cc: reassociates normalization weights; on by default, turned off withTORCH_TPU_INTERNAL_ENABLE_REASSOCIATE_NORM_WEIGHTS=0.lower_separable_gather_to_dot.cc: lowers separable gathers to dots.fold_concat_softmax.cc: a concat and softmax fold, after StableHLO's target-independent optimization pass.dummy_pass.cc: a template.- Kiln's own pass
fold_memref_slice.ccfolds chainedtpu.memref_sliceandtpu.memref_squeezeops inside Kiln kernels.
// A generic MLIR rewrite pattern, shown for its shape only (not from torch_tpu).
// Copy an existing pass such as fold_concat_softmax.cc, and add it in pipeline.cc.
struct FoldRedundantConvertPattern
: public mlir::OpRewritePattern<mlir::stablehlo::ConvertOp> {
using OpRewritePattern::OpRewritePattern;
mlir::LogicalResult matchAndRewrite(
mlir::stablehlo::ConvertOp op,
mlir::PatternRewriter& rewriter) const override {
if (op.getOperand().getType() == op.getType()) {
rewriter.replaceOp(op, op.getOperand());
return mlir::success();
}
return mlir::failure();
}
};
Note
The list above is the directory's contents in pipeline.cc's order. Matmul precision is TorchTPU's torch.tpu.precision and torch.set_float32_matmul_precision (chapter 6), not a pass you edit. TORCH_TPU_INTERNAL_* variables are internal, not public API.
6.2.3 Recipe 3: c10d windows with WindowTpu¶
In one sentence: WindowTpu implements PyTorch's native c10d::Window interface for TPUs (built for PyTorch 2.14 and later): a process group creates one with new_window(tensor), and put, signal and wait_signal move data one-sidedly. In the current source, host-device transfers are true one-sided DMA, but peer transfers between chips are emulated with two-sided send and receive, as the header explains.
Method (c10d::Window override) |
Semantics (header comments) |
|---|---|
ProcessGroupTpu::new_window(tensor) |
supportsWindow() is true; returns a WindowTpu over the registered tensor |
tensor_register(tensor, owning) / tensor_deregister() |
Collective buffer registration with low-level hardware memory hooks |
put(tensor, dstRank, targetOffsetNelems, asyncOp, opts) |
"One-sided zero-copy DMA write (Put) into destination rank at an element offset". Three paths: device-to-host DMA, host-to-device DMA, and peer P2P; peer P2P does not support a non-zero targetOffsetNelems and throws if asked |
signal(peerRank, ...), wait_signal(peerRank, ...) |
Point-to-point synchronization; for peer transfers the receiver's wait_signal() is where the data is actually received |
map_remote_tensor(rank), get_attr(peerRank) |
A tensor view of a rank's registered window; window attributes |
torch.tpu.distributed.window_num_stripes, window_stripe_chunk_mb |
Experimental public properties: "the maximum number of concurrent DMA stripes" and "the minimum payload size (in MB) per DMA stripe" for peer-to-peer transfers (TorchTPU API Reference) |
# Pattern from tests/distributed/window_tpu_test.py (a ring push between ranks).
import torch
import torch.distributed as dist
rank, world = dist.get_rank(), dist.get_world_size()
tpu_tensor = torch.full((1024 * 32,), float(rank * 10 + 1),
dtype=torch.float32, device="tpu:0")
win = dist._new_window(tpu_tensor) # private PyTorch entry point
send_work = recv_work = None
if rank < world - 1:
send_work = win.put(tpu_tensor, dst_rank=rank + 1,
target_offset_nelems=0, async_op=True)
if rank > 0:
recv_work = win.wait_signal(peer_rank=rank - 1, async_op=True)
local_tensor = win.map_remote_tensor(rank) # what rank - 1 wrote
for work in (recv_work, send_work):
if work is not None:
work.wait()
win.tensor_deregister()
del win
dist.barrier()
Peer transfers
Per the header, peer transfers are emulated through ProcessGroup send and receive, with receiver CPU involvement, a c10d::Store rendezvous and a deadlock risk if calls are not sequenced; a TODO plans true one-sided ICI DMA once the PJRT C API exposes it. The example above follows the repository's own test; dist._new_window is a private PyTorch name, so expect it to change.
6.2.4 Multi-ABI Bazel build, glue libraries and shims/¶
In one sentence: A single torch_tpu wheel supports several PyTorch releases by shipping "one thin extension glue per version in WHEEL_TORCH_VERSIONS" (bazel/pytorch_versions.bzl); at run time torch_tpu/_versioned_so_loader.py serves each install "from the newest glue at or below its version". At the time of writing the list is 2.11.0 (the default) plus 2.12.0, 2.13.0 and 2.14.0, and Python 3.11, 3.12, 3.13, 3.14 and free-threaded 3.14t are supported (python_support_policy.md, MODULE.bazel).
| Build / Shim Component | File Path | Architectural Role |
|---|---|---|
pytorch_versions.bzl |
bazel/pytorch_versions.bzl |
Data-only "single source of truth for the PyTorch versions the multi-ABI wheel targets": DEFAULT_TORCH_VERSION, EXTRA_PYTORCH_VERSIONS, WHEEL_TORCH_VERSIONS; also parsed by requirements/lock_environments.sh |
versioned_glue_library |
bazel/glue.bzl |
"Per-version wheel pywrap_library for one PyTorch version": each glue in its own package glue_<suffix>, generated into @torch_tpu_glues |
pywrap_mapper.bzl & wheel_mapper.py |
ci/wheel/pywrap_mapper.bzl, ci/wheel/wheel_mapper.py |
Wheel packaging; the wheel mapper keys glue libraries on their basename (glue.bzl docstring) |
shims/torch/ |
shims/torch/BUILD.bazel, shims/build_files/torch_version.bzl |
Bazel shims for the PyTorch dependency; torch_version.bzl loads pytorch_versions.bzl |
shims/jax/ & shims/libtpu/ |
shims/jax/BUILD.bazel, shims/libtpu/BUILD.bazel |
Bazel shims for JAX and libtpu, two of the many under shims/ |
noxfile.py Multi-ABI Test Matrix |
noxfile.py |
Sessions include wheel_test, intermediate_patch_abi (when a release in INTERMEDIATE_PATCH_VERSIONS fails it, that release "broke ABI and must move into" the wheel list), tpu_smoke_all_versions and cpu_smoke_all_versions |
Note
The version dispatch is _versioned_so_loader.py; _loader.py handles TORCH_DEVICE_BACKEND_AUTOLOAD. The supported version list changes with every release, so read pytorch_versions.bzl for yours.
6.2.5 torch_tpu API design, the four-stage lifecycle policy, Python support and CI tooling¶
Every change to torch_tpu is governed by the policy documents in docs/developers/ and by Contributing to TorchTPU:
1. Public API design rules (TorchTPU API Design Guidelines)¶
| Design Dimension | Rule in torch_tpu |
Rationale & Enforcement |
|---|---|---|
| Reuse PyTorch first | "Prefer reusing an existing PyTorch API"; prefer torch.accelerator over torch.tpu. |
Lowers user migration cost. The legacy torch.tpu.{device_count, current_device, set_device, synchronize, ...} duplicates are Internal and raise RuntimeError from user code unless TORCH_TPU_ALLOW_LEGACY_DEVICE_APIS=1 (API matrix). |
| One canonical path | Public APIs live under torch.tpu.*, not torch_tpu or torch.backends.tpu; "Each TorchTPU module, class, and function should have at most one public module-level path that isn't deprecated." |
Every public path is an API; tt_apis_test checks the public surface, and TorchTPU Public APIs is generated from the stage annotations ("a test fails when it's out of date"). |
| Global vs. local knobs | Global knobs always have a Python API (torch.tpu.allow_excess_precision = True), optionally with an environment variable for the default; local knobs are context managers (with torch.tpu.precision(...)), and a local knob overrides the global one. |
Read a flag once with ReadFlagOnce(), an environment variable once with GetEnvOnce(). C++ command-line flags are only for Google-internal knobs and start with torch_tpu_internal_; do not use Python flags.DEFINE_*. A TorchTPU variable starts with TORCH_TPU_INTERNAL_ until it is meant for users. |
| Custom op naming | Register the op in C++ as torch.ops.tpu._foo and re-export it as torch.tpu.ops.foo. |
Gives the op one public path. |
| Private instance attributes | "Instance attributes of public classes must start with _"; expose state through properties. "Dataclass fields are exempt." |
The API scanner cannot discover instance attributes; tt_apis_test enforces the rule. |
Note
The guide uses the absl flag library when a command-line flag is justified, and restricts flags to internal knobs; its knob examples are allow_excess_precision and precision. VerificationReport is a dataclass, whose fields are exempt from the private-attribute rule.
2. Four-stage API lifecycle and annotations (api_policy.md)¶
Only removing a stable API is slow: it must first be marked deprecated and kept for at least two minor releases. An experimental API can be hidden again or abandoned at any time, and no API has to move forward at all.
| Surface | How to mark it (policy) | Behavior When Invoked by User Code |
|---|---|---|
| Python functions and classes | Internal: a name starting with _. Otherwise @annotations.experimental(reason), @annotations.stable(reason) or @annotations.deprecated(version, reason) from torch_tpu._internal.utils.annotations; @annotations.internal_or_experimental(...) for an API that becomes internal once a replacement exists |
Experimental and Deprecated warn once. An API marked internal this way raises RuntimeError on every call from user code when strict=True, or warns once when strict=False |
| Python attributes and enum constants | An entry in __tt_api_stages__ on the module or class |
Checked with the other annotations |
TPU custom ops in torch.ops.tpu |
ImplInternal, ImplExperimental, ImplStable or ImplDeprecated (defined in csrc/eager/tpu_aten_kernels.cc) |
Stage warnings on the dispatcher binding |
| Environment variables | Internal: name it TORCH_TPU_INTERNAL_*. Otherwise add it to kEnvVarToStage in csrc/common/env_vars.h as SymbolStage::Experimental(), Stable() or Deprecated() |
GetEnvOnce<kVar>() memoizes the value; SafeSetEnv() crashes if GetEnvOnce() has already memoized that variable (env_vars.h) |
Note
The annotations module has experimental, stable, deprecated, internal_or_experimental and forbid_in_torch_compile; the Impl* templates are defined in tpu_aten_kernels.cc (symbol_stage.h defines the SymbolStage type that env_vars.h uses).
3. Python version support, CI test discovery and contribution workflow¶
- Python Support Policy (
python_support_policy.md): "TorchTPU currently supports Python 3.11, 3.12, 3.13, and 3.14 (including free-threaded 3.14t)." - Inspecting CI Test Execution (
list_ci_tests_guide.md):ci/tools/list_ci_tests.pyevaluates the CI jobs' tag filters without running tests. The guide's examples:ci/tools/list_ci_tests.py --list_jobs # each job, machine type, tag filters (no bazel query) ci/tools/list_ci_tests.py --format=count # one line per job ci/tools/list_ci_tests.py --jobs=ci_tpu_v7_presubmit # targets one job runs ci/tools/list_ci_tests.py --test=//csrc/ops/macros:kernel_test # which jobs run one target ci/tools/list_ci_tests.py --tests='ops_test*' # restrict to matching targets - Contribution and Copybara review workflow (Contributing to TorchTPU):
- Sign the Google CLA; open an issue before anything "more complicated than trivial fixes". On AI assistance, "AI assistants should not be considered co-authors on any commits"; you may add an
Assisted-by:tag. - Review runs through Google's Copybara: an oncall triages the PR and adds a domain expert; the domain expert approves and adds a quality champion (one of
cbasile-g,LeeHowes,vladbelousandzhanyong-wan) as reviewer and assignee; the champion approves and applies thepull readylabel, which makes the Copybara bot create an internal change (CL) with the champion as its reviewer; once the champion approves it, the CL submits, the commit lands onmainseparately and the PR is closed, so it never shows as merged. If the author updates the PR afterwards, the champion re-approves the import by voting Code-Review+2 on theimport/copybarasafe-review page (the CL needs approvals from two Googlers) (chapter 25).
The pull ready label hands the PR to Copybara, which turns it into an internal change that the quality champion approves. The commit then lands on main separately and the PR is closed, so it never shows as merged.
6.3 Extending vLLM-TorchTPU and SGLang-TorchTPU (patch registry, coding guidance, type checking, megakernels and Raiden)¶
In one sentence: Because both
vllm-torchtpuandsglang-torchtpuoperate as out-of-tree (OOT) hardware plugins on top of upstream engines, extending them cleanly means using the engines' own extension points first, then staged runtime patches (patch_registry.py/ SGLang'sHookRegistryentries insglang_tpu/hooks/), the coding and type-checking gates (R-1.1..R-8.10,PR-x/P-x/Q-x,pyreflydual baselines), whole-decoder Pallas megakernels for low-batch decode, and geometry-aware KV cache resharding (Raiden) for disaggregated prefill and decode pools (chapter 25).
6.3.1 How it works: staged out-of-tree patching and whole-decoder megakernels¶
Read a column to see at which stages a patch registered with that tuple is applied; Model patches is the tuple ("platform_activation", "model_load") of the model-specific recipe. _ACTIVE lists worker_init as well as platform_activation because platform activation in the parent does not cover a spawned worker, and _ENGINE adds engine_core for code that the engine-core process runs.
The stages are entry points in different processes, "not a sequence that every process necessarily executes" (developer guide, quoted in chapter 25); the figure shows, for each stage, which stage tuples include it.
6.3.2 The vLLM-TorchTPU five-stage patch registry (src/vllm_torchtpu/patch_registry.py)¶
Before writing a patch, use vLLM's own extension points: R-3.5 lists "vLLM's plugin hooks, register_oot registration, AttentionBackendEnum registration". The plugin enters through the vllm.platform_plugins and vllm.general_plugins entry points in its pyproject.toml. When none of those reaches the code that must change, the change is one entry in the ordered tuple PATCHES in src/vllm_torchtpu/patch_registry.py, installed by apply(stage, model_config=...) (developer guide TPU patch mechanism; tests in tests/platforms/test_patch_registry.py).
The five patch stages and stage tuples¶
| Stage | Called from | Use |
|---|---|---|
import |
env_override.py, after early environment setup |
Import-time prerequisites; keep it light: it must not load TorchTPU or resolve vLLM's platform |
platform_activation |
TpuPlatform.check_and_update_config |
Shared TPU patches, and model patches with vllm_config.model_config |
engine_core |
_run_engine_core_with_tpu_patches |
Scheduler, KV-cache, offloading and multimodal patches in the engine-core process |
worker_init |
TPUWorker.__init__, before WorkerBase.__init__ |
Shared patches in each worker, including spawned workers |
model_load |
TPUWorker.load_model, before the runner loads the model |
Model-specific patches with self.model_config |
_ACTIVE |
("platform_activation", "worker_init") |
"Parent platform activation alone does not cover a spawned worker" |
_ENGINE |
(*_ACTIVE, "engine_core"), that is ("platform_activation", "worker_init", "engine_core") |
Patches the scheduler process also reads |
The Patch dataclass and the apply(stage, model_config=...) contract¶
@dataclass(frozen=True)
class Patch:
target: str # "module:callable", or a bare module imported for side effects
stages: tuple[Stage, ...] # where the entry is eligible
model_config: bool = False # pass model_config=... (possibly None) to the callback
refresh: str | None = None # lazy target called on later eligible stages once complete
- Tuple order is application order within a stage.
- Completion is keyed by the target string and kept for the process. Only the literal
Falseleaves an entry eligible for a later attempt;None, including "this model is not mine", marks it complete. - An exception propagates and stops that stage's pass; earlier completions stay recorded and nothing is rolled back.
- Refresh handles late bindings: a module that did
from upstream import fnkeeps its own reference; arefreshtarget runs on every later eligibleapply, so it must be idempotent. - Processes: spawned processes start with an empty registry; forked ones inherit it. One
RLockserializes application, and re-entering a stage already being applied returns at once. - The log line is not evidence:
Completed TPU patch callbacks at <stage>: ..."includes permanent no-ops".
A model-specific patch follows the guide's recipe: a callback in src/vllm_torchtpu/models/vllm/<model_name>_patch.py that returns False when model_config is None or does not match, applies the patch and returns None when it does, and an entry under # Model-specific patches with ("platform_activation", "model_load") and model_config=True. The Qwen2 patch, from qwen2_patch.py:
# src/vllm_torchtpu/models/vllm/qwen2_patch.py
def maybe_patch_qwen2(model_config: Optional["ModelConfig"] = None) -> bool | None:
if model_config is None or "Qwen2ForCausalLM" not in (
getattr(model_config, "architectures", None) or []
):
return False
import vllm.model_executor.models.qwen2 as qwen2_mod
from vllm_torchtpu.models.vllm.qwen2 import TPUTPPaddedQwen2Attention
qwen2_mod.Qwen2Attention = TPUTPPaddedQwen2Attention
logger.info("Applied TPU patch: Qwen2 GQA query-head padding attention.")
return None
Note
The stage entry points are env_override.py, check_and_update_config, _run_engine_core_with_tpu_patches, TPUWorker.__init__ and TPUWorker.load_model. The registry takes module:callable (or a bare module), a single refresh target, and string completion keys (chapter 25, "Patching a serving engine").
6.3.3 vLLM-TorchTPU coding guidance (R-1.1..R-8.10), dual-baseline pyrefly type checking and contribution workflow¶
The coding guidance is "normative" for human authors and coding agents; reviewers cite its rule IDs. Two meta-principles organize it:
- Reuse upstream. "vLLM upstream is the first place to look for any functionality. This repo exists to add TPU behavior to vLLM, not to re-implement vLLM."
- Derive, don't declare. "Any value recoverable from tensor shapes, dtypes, hardware APIs, sharding specs, or cost models is derived at the point of use", never duplicated into a knob, environment variable, magic number or member variable.
Table 6.3a: vLLM-TorchTPU coding rules (R-1.1 to R-8.10), paraphrased¶
| Section | Rule IDs | Representative rules (guide) |
|---|---|---|
| 1. Python style | R-1.1 to R-1.8 |
Google Python Style Guide for what tooling does not decide (R-1.1); ruff formats and sorts imports through pre-commit (R-1.2), wrapping at 88 columns (R-1.3); PEP 604 unions and builtin generics, pyrefly at the default preset (R-1.5); the full Apache 2.0 header and no SPDX-License-Identifier tag, tools/check_license_headers.py --fix (R-1.6); no print, log with vllm_torchtpu.logger.init_logger (R-1.7); minimize comments (R-1.8) |
| 2. Architecture ground rules | R-2.1 to R-2.7 |
Directory responsibilities: kernels/ has no vLLM imports and no torch, layers/core/ is jax-first, layers/adapter/ is the vLLM- and torch-facing layer, platforms/, runner/, worker/, executors/ are thin translation (R-2.1); interface files stay thin (R-2.2); kernels are self-contained, with no envs/os.environ reads inside (R-2.3); name kernels by function, not by model (R-2.4); write against the pinned versions (R-2.5); environment and startup mutation only in env_override.py (R-2.6); read the governing section before touching a gated area (R-2.7) |
| 3. Reuse upstream first | R-3.1 to R-3.5 |
Search order "vLLM upstream, then vllm-torchtpu, then JAX/Pallas utilities, then write it" (R-3.1); no per-model forks of shared layers (R-3.2); fix upstream defects upstream (R-3.4); use framework extension points, not private APIs (R-3.5) |
| 4. Derive, don't declare | R-4.1 to R-4.7 |
No string-based or attribute-probing dispatch (R-4.1); derive from argument shapes (R-4.2); no env reads inside jitted or compiled functions (R-4.3); no hard-coded hardware constants (R-4.4); no magic mesh-axis strings (R-4.5); config flows through vLLM's typed config (R-4.6); typed containers over dicts and sentinels (R-4.7) |
| 5. Fail fast | R-5.1 to R-5.6 |
No defensive or bare except (R-5.1); assert untested assumptions (R-5.2); raise NotImplementedError with a TODO for incomplete features (R-5.3); error messages that tell the user the fix (R-5.4); do not hide a dtype mismatch with a cast (R-5.5); guard recompilation with official APIs (R-5.6) |
| 6. Minimize surface area | R-6.1 to R-6.6 |
Question every new argument, flag and env var (R-6.1); add an env var only in one of three cases (R-6.2); one sharding formulation (R-6.4); generalize from the mechanism (R-6.5) |
| 7. Diff discipline | R-7.1 to R-7.12 |
Small, single-purpose PRs (R-7.1); refactor first, feature second (R-7.2); rebase, never merge (R-7.6); a human reviews every changed line (R-7.7); fail closed (R-7.10); no internal-only references in anything that lands publicly (R-7.12) |
| 8. Tests | R-8.1 to R-8.10 |
A unit test for every production change (R-8.1); a regression test must fail without the fix (R-8.2); verify tests are wired into CI (R-8.4); run evals proactively for model-affecting changes (R-8.10) |
Note
The table follows the guide's section and rule titles. Logging uses vllm_torchtpu.logger.init_logger. The 500-line limit is in the contributing guide: "exceeding 500 lines of core logic" needs an RFC issue first, and such PRs "may be labeled rfc-required".
Dual-baseline pyrefly type-checking gate (type checking)¶
The pre-commit environment has no torch, jax or vllm, while CI's full check runs against them, so vllm-torchtpu keeps two pyrefly baselines, both checked through tools/check_pyrefly_baseline.py:
| Check Tier | Baseline File | How to Run Locally | What It Catches |
|---|---|---|---|
| 1. Pre-commit check (no third-party packages) | .pyrefly-baseline.json |
pre-commit run --all-files |
Errors within the repository; imports of torch, jax and vLLM are Any |
| 2. Full-environment check (Buildkite "Type Check - Full Environment") | .pyrefly-baseline-full.json |
bash tools/typecheck_full.sh (Docker, no TPU) |
Type errors against the real torch, jax and vllm signatures |
- Ratchet rule: when a PR fixes existing errors, regenerate the baselines (
uvx pyrefly@1.3.0 check --update-baselineandbash tools/typecheck_full.sh --update-baseline); a change may only delete baseline entries: "An added entry means your change introduced that error; fix it instead."
Developer setup and contribution workflow (contributing, testing)¶
# Every commit carries a DCO sign-off
git commit -s
# Install for development (uv): CPU torch, vLLM from source
export UV_TORCH_BACKEND=cpu
VLLM_TARGET_DEVICE="empty" uv pip install -e . --group vllm
uv pip install --prerelease=allow -e . --group vllm --group test # test dependencies
# Hooks: ruff, pyrefly (no third-party packages), env-read and kernel checks
pre-commit install --hook-type pre-commit --hook-type commit-msg
pre-commit run --all-files
# Full-environment type check against real torch, jax and vllm (Docker, no TPU)
bash tools/typecheck_full.sh
# CPU unit tests, exactly as CI runs them
JAX_PLATFORMS=cpu pytest tests/ -m "not tpu_test and not multichip and not nightly"
- Buildkite CI labels: a maintainer applies the
readylabel to run TPU CI; on a PR from a fork every push removes it again. A PR that fixes a broken main or nightly build can takeoncall-fix, which runs its TPU jobs ahead of every other build. vLLM-TorchTPU asks you to disclose AI help in the PR description and to addCo-authored-by:trailers for the tools, a different policy from torch_tpu's.
Table 6.3b: performance rules (PR-1 to PR-4, P-1 to P-17) and quantization rules (Q-1 to Q-7)¶
The rules live in the vLLM-TorchTPU optimization best practices. The Diagnosis and evaluation page carries the full catalog (section 4.3, table 2.A), paraphrased from that guide as chapter 11 cites it: for example P-1 "xprof traces are the unit of evidence", P-5 "shard via jit signatures", P-13 "optimization barriers hide in innocuous constructs", P-16 "block sizes live in tuned tables inside the kernel directory", Q-3 "numeric verification is non-negotiable".
Note
The environment variables that tune these paths (FUSED_MOE_DECODE_KERNEL, TPU_PARALLEL_PRECOMPILE, TPU_KERNEL_ITER_MODE, VLLM_TPU_FUSED_DRAFT_LOOP and others) are declared in src/vllm_torchtpu/envs.py; the environment variable reference lists the ones the book explains.
6.3.4 SGLang-TorchTPU platform modes, HookRegistry and debt-ratchet tooling¶
sglang-torchtpu is migrating TPU code out of its SGLang fork (python/) into the plugin sglang_tpu/ ("All new TPU code goes here"); the plugin is discovered through the sglang.srt.platforms entry point tpu_oot = "sglang_tpu:activate". Two platform modes (sglang_tpu/__init__.py, sglang_tpu/platform.py):
SGLANG_PLATFORM=tpu,TpuSRTPlatform(sglang_tpu/tpu_platform.py,PlatformEnum.TPU): the in-tree TPU platform. DSA and sparse attention (the DeepSeek V3.2 family) are served only in this mode.SGLANG_PLATFORM=tpu_oot,TpuOOTPlatform(PlatformEnum.OOT;is_tpu()still returnsTrueso coreis_tpu()sites keep working):activate()returns the platform class only when selected by name, andinit_backend()is deferred until the worker bootstrap sets its marker variable.
Order of choices for a core change the TPU needs (contributing guide): an existing SRTPlatform method or capability flag; a registry filled from init_backend(); subclass-and-override through a factory; and only then an upstream seam PR, carried meanwhile as a sglang_tpu/hooks/ entry. Hooks go through SGLang's HookRegistry (BEFORE, AFTER, AROUND, REPLACE); sglang_tpu/hooks/__init__.py collects them in HOOKS and register() registers them only when current_platform.is_tpu().
# SGLang-TorchTPU migration-debt and support checks
python tools/plugin/check_tpu_branches.py # pre-commit: rejects a PR that raises a per-file count of is_tpu branches
python tools/plugin/gate_audit.py # checks the is_out_of_tree() gates for the out-of-tree mode
python tools/plugin/inventory.py # lists every hook and runtime patch ("only go down")
python tools/plugin/scoreboard.py # the full set of counts
python3 scripts/ci/tpu/support_matrix.py --strict --check SUPPORT_MATRIX.md # matrix generated from register_tpu_ci markers
Note
Select SGLANG_PLATFORM=tpu explicitly for sparse attention: SGLANG_PLATFORM defaults to the empty string in environ.py. The out-of-tree mode's marker is _WORKER_BOOTSTRAP_MARKER (chapter 25, "Extending SGLang-TorchTPU").
6.3.5 KV cache resharding across TP sizes with Raiden (sglang_tpu/disaggregation/raiden/)¶
When prefill and decode run with different attention TP degrees, a decode rank's KV-head slice spans several prefill ranks, and which bytes land where depends on the number of KV heads. reshard_schedule.py computes "strided KV resharding schedules" as pure byte math (no torch), mirroring SGLang's compute_head_slice_params:
from sglang_tpu.disaggregation.raiden.reshard_schedule import (
ReshardGeometry, head_slice_params, reshard_ratio, source_ranks_for,
)
# Prefill attention TP=8 -> decode attention TP=4, 8 KV heads, bf16 head_dim 128
ratio = reshard_ratio(8, 4) # 2 prefill ranks feed each decode rank
source_ranks_for(1, ratio) # [2, 3]: decode rank 1's writers, in order
head_slice_params(8, 4, 3, 1, 8) # (0, 1, 1, 1, 2): src_head_start, num_heads,
# dst_head_start, src/dst heads per rank
geom = ReshardGeometry(src_tp=8, dst_tp=4, hp_bytes=512, total_kv_heads=8)
geom.entry_bytes(3, 1) # (0, 512, 512, 512, 1024): per-token src_offset,
# size, src_stride, dst_offset, dst_stride
The values in the comments are what these calls return for the arguments shown. build_sender_request(pb2, *, uuid, req_id, peer, prefill_rank, decode_rank, geom, src_block_ids, dst_block_ids, live_tokens) and build_receiver_request(...) turn the geometry into Raiden StartTransferRequest push schedules. ReshardGeometry requires native 32-bit packing (kv_packing * element_size == 4).
Note
This resharding module is SGLang-TorchTPU's; vLLM-TorchTPU has its own Raiden connector, TPURaidenConnector.
6.3.6 Whole-decoder Pallas megakernels (vllm-torchtpu and sglang-torchtpu)¶
At small decode batch sizes, launching each layer's ops separately costs dispatch and HBM round trips; a whole-decoder megakernel runs the decoder's layers inside one Pallas launch and keeps state on chip between them.
Megakernel code in the repositories¶
| Megakernel Engine | Source Location | Target Models | Execution Model & Key Abstractions |
|---|---|---|---|
1. Composable megakernel library (vllm-torchtpu) |
src/vllm_torchtpu/megakernel/ |
Models described by a ModelSpec |
"Config-driven composable TPU Pallas megakernel library": ModelSpec(name, config, layer_type, cache_backend) in spec.py, a LayerType(name, slots) of Modules and SwitchSlots, Module subclasses that register under a name and carry Tunables, ExecSpec and Tiles in exec_spec.py, and planner.plan(model_spec, ex) -> Plan, documented as a "Pure function of model_spec and ex" |
2. Kimi-K3 stack megakernel (sglang-torchtpu) |
sglang_tpu/k3_megakernel/ |
Kimi-K3 | StackKernel (kernel/stack.py) and K3MegakernelRuntime (ops.py); stages KdaStage, MlaStage, DenseMlpStage, MoeStage, GreedyHead under kernel/stages/, an Arena, and collectives including PairExchange. Enabled with SGLANG_TPU_ENABLE_K3_DECODE_MEGAKERNEL=1; tuned with SGLANG_TPU_OPT_K3_MEGAKERNEL_RELAX, SGLANG_TPU_K3_MEGAKERNEL_KERNEL_OPTS |
3. GLM-5.3-Flash megakernel (sglang-torchtpu) |
sglang_tpu/glm_flash_megakernel/ |
GLM-5.3-Flash | GlmFlashMegakernel (ops.py) and make_decode (kernel/runner.py); weights packed K-major (SlabIndex, pack_kmajor). SGLANG_TPU_GLM_FLASH_MEGAKERNEL=1 |
4. Muse megakernel (sglang-torchtpu) |
sglang_tpu/muse_megakernel/ |
MuseSparkForConditionalGeneration (plugin README) |
MuseMegakernel (torch.nn.Module in ops.py) over the whole-decoder kernel in kernel.py. SGLANG_TPU_MUSE_MEGAKERNEL=1 |
Note
The Muse class is MuseMegakernel. The composable library's module is spec.py, and ModelSpec takes name, config, layer_type and cache_backend.
6.4 Extending TorchTitan, the llm-d EPP and tpu-agent-suite¶
In one sentence: At the cluster and agent layer, extending the stack means declaring module sharding with
ShardingConfigand writing FX graph passes in TorchTitan, writing request-scheduling plugins for the llm-d Endpoint Picker (EPP), and adding skills and specialist agents to the tpu-agent-suite package (0.7.0).
6.4.1 Extending TorchTitan: declarative ShardingConfig and FX graph passes¶
TorchTitan's TPU lane is torchtitan/experiments/tpu/; its Graph Trainer (tpu_graph_trainer.py) traces the training step and runs graph passes over it (chapter 14).
- Declarative
ShardingConfig(protocols/sharding.py): "Declarative sharding for a Module's states and activations." Fields:state_shardings,in_src_shardings,in_dst_shardings,out_src_shardings,out_dst_shardings,local_map. Placements areSpmdTypes keyed by mesh axis name and resolved against the mesh atparallelize()time; "every sharding_config must explicitly declare a placement for every mesh axis it will be applied against". Row-wise tensor parallelism frommodels/common/decoder_sharding.py:A model fillsdef rowwise_config(*, output_sp: bool = False) -> ShardingConfig: """ RowwiseParallel: weight S(1), bias R (no-op if bias absent). Output redistributes to S(1) (reduce-scatter) if SP on, else I (all-reduce). """ out_dst = ( dense_sequence_parallel_placement() if output_sp else dense_activation_placement(tp=spmd.I, cp=spmd.S(0)) ) return ShardingConfig( state_shardings={ "weight": dense_param_placement(tp=spmd.S(1)), "bias": dense_param_placement(tp=spmd.R), }, out_src_shardings=dense_activation_placement(tp=spmd.P, cp=spmd.S(0)), out_dst_shardings=out_dst, )sharding_configon its sub-configs (for Llama 3,set_llama3_sharding_config(config, enable_sp=...)inmodels/llama3/sharding.py). - FX graph passes for the Graph Trainer live in
graph_trainer/passes/: for exampleapply_combine_barrier_pass(insertstpu::_optimization_barrieraround the MoE padded combine) andapply_selected_reduce_scatter_allreduce_pass(lowers selected FSDP reduce-scatters through all-reduce plus a local slice, which "changes collective reduction order, so BF16 recipes must validate the resulting numerical trajectory"). Copy one of these, with its tests ingraph_trainer/tests/. The public barrier op istorch.tpu.ops.optimization_barrier(inputs), which takes a sequence of tensors and returns a list (remat_schedule.pycalls it astorch.tpu.ops.optimization_barrier(list(values))).
To add a model to the TPU lane (wrap vs port, registration, the reference-parity test on BaseAcceleratorDeviceTest, CI shard rules), follow chapter 25, "Adding a model to TorchTitan's TPU lane".
Note
ShardingConfig uses SpmdTypes keyed by axis name; the example above is the source's. For graph passes, start from the real passes the pointers above name.
6.4.2 Extending the llm-d Endpoint Picker (EPP): filter, scorer and picker plugins¶
The EPP is configured by an EndpointPickerConfig (apiVersion: llm-d.ai/v1), which "is not a Kubernetes CRD": the binary reads it once at startup from --config-file or --config-text. Inside each scheduling profile the scheduler runs filters, then weighted scorers, then a picker; a ProfileHandler decides which profiles run and merges their results (chapter 20, llm-d API reference). ProfileHandler.Pick is called again with the results of the profiles that ran until it picks none, then ProcessResults merges them into one SchedulingResult.
The profile handler both opens and closes the cycle: Pick chooses which profiles to run, possibly again after seeing their results, and ProcessResults merges the results of every profile that ran into one scheduling result.
Built-in EPP plugins (llm-d 1.0 scheduling docs)¶
| Extension point | Built-in type names |
Responsibility |
|---|---|---|
| 1. Profile handler | single-profile-handler, disagg-profile-handler (data-parallel-profile-handler is deprecated) |
Chooses the profiles to run; for P/D, disagg-profile-handler runs a prefill and a decode profile, returns the decode endpoint as the destination and injects the prefill endpoint as a header (x-llm-d-prefiller-host-port) |
| 2. Filter | label-selector-filter, prefill-filter, decode-filter, encode-filter, prefix-cache-affinity-filter, slo-headroom-tier-filter |
Removes endpoints that cannot or should not serve the request (roles come from the llm-d.ai/role label) |
| 3. Scorer | prefix-cache-scorer, kv-cache-utilization-scorer, queue-scorer, running-requests-size-scorer, token-load-scorer, lora-affinity-scorer, session-affinity-scorer, no-hit-lru-scorer, latency-scorer, active-request-scorer |
"Assigns a score between 0.0 and 1.0 to each filtered endpoint"; the profile sums weight × score |
| 4. Picker | max-score-picker (default, injected into a profile with no picker), random-picker, weighted-random-picker |
Selects the endpoint |
| Data producers | precise-prefix-cache-producer, approx-prefix-cache-producer, predicted-latency-producer, inflight-load-producer |
Publish per-endpoint data that scorers and filters read |
| Flow control & request handling | global-strict-fairness-policy, round-robin-fairness-policy, fcfs-ordering-policy, edf-ordering-policy, slo-deadline-ordering-policy; utilization-detector, concurrency-detector; parsers openai-parser, anthropic-parser, vllmhttp-parser, vllmgrpc-parser, passthrough-parser |
Priority bands, fairness and ordering, saturation detection, request parsing |
Built-in plugins live in the llm-d-router repository under pkg/epp/framework/plugins/ at tag v1.0.0. A scorer of your own is a Go plugin in that tree; read the Go interface and the registration call from a built-in scorer at the tag you build against. Once the binary knows your type, wiring it in is configuration only (chapter 25, "Writing an llm-d EPP scorer"):
apiVersion: llm-d.ai/v1
kind: EndpointPickerConfig
plugins:
- type: prefix-cache-scorer
- type: queue-scorer
- name: tpu-shape-fit # your instance name
type: my-tpu-shape-scorer # the type your plugin registers (hypothetical)
parameters:
maxCompiledTokens: 8192 # whatever your plugin parses
schedulingProfiles:
- name: default
plugins:
- pluginRef: prefix-cache-scorer
weight: 2
- pluginRef: queue-scorer
weight: 1
- pluginRef: tpu-shape-fit
weight: 1
To see that the scorer does something, watch llm_d_epp_plugin_duration_seconds (labels extension_point, plugin_type, plugin_name) and where requests land in llm_d_epp_scheduler_attempts_total.
Note
The documented names are disagg-profile-handler, label-selector-filter, and precise-prefix-cache-producer feeding prefix-cache-scorer; the prefill header is x-llm-d-prefiller-host-port. The configuration above is chapter 25's.
6.4.3 tpu-agent-suite (0.7.0): compiler, skills, specialist agents, compute backends and the trajectory/Harbor pipeline¶
In one sentence: tpu-agent-suite (version 0.7.0 in package/package.release.json, in preview) is one canonical package (package/) compiled into a native distribution per agent harness and backed at run time by a Python runtime that validates every request and result against a schema and runs every TPU job through one compute CLI. The README lists Claude Code and Antigravity, with Codex and Cursor "coming soon". The suite's video describes three pillars, grounded, bounded and checked (chapter 26).
One package becomes one bundle per agent harness. make build writes all four folders, but the README supports only Claude Code and Antigravity so far.
1. Skills (package/skills/)¶
The release build ships two skills; the experimental manifest (package.experimental.json) adds eleven. "Delegates" is each SKILL.md's delegates frontmatter.
| Build | Skill | Delegates | What it does (SKILL.md description, condensed) |
|---|---|---|---|
| Release | tpu-agent |
tpu-model-onboarding, tpu-kernel-development, tpu-diagnostics, tpu-knowledge-base |
The entry point: onboarding, optimization, profiling and benchmarking PyTorch models on Cloud TPU |
tpu-agent-export-trajectory |
None | Saves the session's trajectory (the tpu-agent work and every agent it delegated to) to the destination the user chose |
|
| Experimental | accuracy-check |
None | Measures a model's accuracy on real hardware against a recorded baseline |
change-preflight |
tpu-diagnostics |
Establishes on real hardware that a code change does what it claims before a long benchmark | |
close-gaps |
tpu-diagnostics |
An optimization loop for one served job: microbenchmark, rank gaps with decompose-optimization, work the list |
|
code-reference |
None | Fetches the upstream kernel repositories (jax-ml/jax, openxla/tokamax) into a gitignored code-reference/ directory |
|
critical-review |
tpu-diagnostics |
Adversarially reviews a claim, document or A/B result by recomputing every number from the raw source | |
decompose-optimization |
tpu-diagnostics |
Turns a benchmark job with an XProf capture into a ranked list of optimization candidates with root causes | |
exit-review |
tpu-diagnostics |
Adversarially reviews a decision to stop ("this cannot be made faster") | |
roofline-analysis |
None | Models an LLM's analytic roofline on TPU: per-op FLOPs, HBM bytes, collective volume and the bound | |
sharding-strategy |
None | Enumerates TP/DP/EP/PCP/DCP/PP partitions on a slice before a benchmark is spent | |
workload-microbenchmark |
tpu-diagnostics |
Turns a finished serving job into representative per-rank microbenchmark configs for a small slice | |
write-tpu-kernels |
tpu-diagnostics |
Designs, proves, builds, probes and optimizes custom Pallas/Mosaic kernels for a block of model compute |
2. Specialist agents (package/agents/)¶
| Agent | Delegates | Role (agent frontmatter, condensed) |
|---|---|---|
tpu-model-onboarding |
tpu-unwiring, tpu-knowledge-base |
Orchestrates PyTorch model onboarding, inference and benchmarking on the torch_tpu backend |
tpu-unwiring |
None | Replaces CUDA-locked code in a Hugging Face model with native PyTorch, emitting a patches module proven to load and run a forward pass on TPU |
tpu-diagnostics |
None | The entry point for XProf profiling: captures a profile when there is none, reads one with the profiler's tools, reports what they measured and could not see |
tpu-kernel-development |
kernel-worker, tpu-diagnostics, tpu-knowledge-base |
Only when asked by name: drives the kernel self-refinement loop from JAX or PyTorch to a Pallas kernel |
kernel-worker |
analyze-cuda-reference |
One full iteration of kernel optimization |
analyze-cuda-reference |
None | Reads a CUDA kernel supplied as a reference and writes a structural brief |
tpu-performance-optimization |
None | Only when asked by name or for a study: advances one bounded round of a long-running optimization study |
tpu-performance-optimization-researcher |
None | Pairs XProf/HLO attribution with source and knowledge-base analysis to generate and rank hypotheses |
tpu-performance-optimization-executor |
None | Executes one candidate optimization arm: implements it, microbenchmarks it, verifies numerics |
tpu-sharding |
tpu-sharding-optimizer, tpu-sharding-executor, tpu-sharding-memory-contributor, tpu-diagnostics, tpu-knowledge-base |
Orchestrator of the sharding hill-climbing lifecycle |
tpu-sharding-researcher |
None | Broad search and deep telemetry analysis |
tpu-sharding-optimizer |
tpu-sharding-memory-contributor, tpu-sharding-researcher |
Proposes configuration changes, forms hypotheses, evaluates results |
tpu-sharding-executor |
tpu-sharding-memory-contributor |
Runs jobs on the backend, extracts metrics, tails logs |
tpu-sharding-memory-contributor |
None | Formats, deduplicates and ingests empirical takeaways into the optimization memory |
tpu-roofline |
None | Models the analytic roofline of an op, a block of code or a whole LLM from shapes and hardware limits |
tpu-knowledge-base |
None | Looks keywords up in the TPU knowledge catalog and returns the pages |
tpu-hello-world |
None | Dispatches one PyTorch op onto a TPU node of the configured GKE cluster and checks it against the CPU |
Note
The release router tpu-agent delegates to four agents. "Bounded" means the kernel loop stops at max_iterations (default 5), and the kernel-request schema has no time budget. The knowledge-base index ships under package/data/tpu-knowledge-base/. Both tables above follow the SKILL.md frontmatter (chapter 26).
3. Template tokens, compute backends and trajectory/Harbor isolation¶
- Template tokens (
framework/compiler.py): package files reference other package files with tokens such as{{agent:...}},{{script:...}},{{schema:...}},{{reference:...}},{{skill:...}}and{{runtime}}, which the compiler resolves per harness; a literalscripts/...orreferences/...path in prose failsverify. - Compute backends (
framework/compute/drivers/):local(LocalDriver),gce_tpu_vm(GceTpuVmDriver),gke_pod(GkePodDriver),gke_job(GkeJobDriver) andgke_xpk(GkeXpkDriver). Ongke_job,--inputfiles that fit in the Job's ConfigMap with the script (900 KiB in all) travel in it and--outputfiles come back in the pod's log (1 MiB in all); larger files go throughstaging_bucketon V4 signed URLs (compute README). - Run leases (
framework/compute/lease.py): a killed session never firesSessionEnd, so its batch jobs would keep their chips. Each run is leased to the harness process that started it; once that process is gone, a detached watcher reaps the jobs afterLEASE_GRACE_SECONDS(a constant, 120), or the next session's sweep does. - Trajectory export (
framework/trajectory/):resolvers.pyfinds aCutwhere the bundle starts (basesskill-tool-use,slash-command,skill-file-read,user-consented-all,none);bundle.pyslices the session records from there. - Harbor evaluation (
eval/): in each trial container the agent runs as an ordinary user, while the cluster credentials and the realkubectlcan only be read or run by a separate system user,kube-gate;/usr/local/bin/kubectlcallskubectl_wrapper.pythroughsudo, and the wrapper labels everything a trial creates witheval-trial-idand limits the trial to its own objects.
Note
The build writes dist/<harness>/tpu-agent-suite. In eval/adapter/, sitecustomize.py stages declared mounts into the GKE pod.
6.5 Blueprints for new kernels, compiler passes and plugins¶
In one sentence: Use these four blueprints as an end-to-end checklist when you design a new Pallas kernel, a
torch_tpuop or pass, avllm-torchtpu/sglang-torchtpuchange, or atpu-agent-suiteskill. Each step names a check the chapters explain; parity comes before performance (chapter 25, "Designing an extension").
Blueprint 1: designing, verifying and autotuning a new Pallas TPU kernel (jax_op)¶
Correctness comes first: the kernel matches a PyTorch reference on the CPU and passes static verification before it runs on a TPU, and it is timed only after its TPU outputs match.
- Size blocks from the roofline. Compute the arithmetic intensity I = FLOPs / HBM bytes and compare it with the bf16 ridge (about 166 FLOPs/B on v5p, 560 on v6e, 313 on v7x; peak FLOP/s over HBM bandwidth). Choose block shapes whose last two dims are multiples of 8 and 128 (or the full dims); chapter 12 plans bf16 rows in multiples of 16 for packing. Keep
2 x (input blocks + output blocks) + scratchunder the scoped VMEM limit (pltpu.CompilerParams(vmem_limit_bytes=...), or a fraction ofpltpu.get_tpu_info().vmem_capacity_bytes), and keep scalar metadata in SMEM viaPrefetchScalarGridSpec(num_scalar_prefetch=K). - Write the kernel in JAX and Pallas. Write the body with
jax.experimental.pallas(pl) andpallas.tpu(pltpu); in vLLM-TorchTPU,kernels/has no torch, no vLLM and no env reads (R-2.1, R-2.3). Accumulate injnp.float32and cast to bf16 only on the final store. Donate buffers you update in place (donate_argnumsonjax_op). - Check parity in the strict interpreter. Run the kernel with
interpret=pltpu.InterpretParams()against a PyTorch reference in float32 and bf16, over several grid sizes. - Register it with
jax_op. SGLang-TorchTPU code uses its owncpu_export_jax_op; addop.register_autograd(...)for training. - Verify it statically with
VerificationMode.STATIC, in the TorchTPU process. - Compare on the TPU. Compare eager and
torch.compile(backend="tpu", dynamic=False)outputs with the reference at the dtype's tolerance, then time the kernel against the compiled reference.
Steps 4 and 5 in code:
op = torch.tpu.pallas.jax_op("ns::name", fn)
report = torch.tpu.pallas.verifier.verify(
op, sample_args,
mode=torch.tpu.pallas.verifier.VerificationMode.STATIC,
) # in the TorchTPU process
report.raise_for_errors()
Blueprint 2: adding a torch_tpu ATen lowering, TPU custom op or optimization pass¶
Where the code goes depends on what you add; every change then goes through the same checks: CPU-comparison tests for ops, the API scanner, and a CI job that actually runs the new test.
Where the change goes:
- ATen op: builder and kernel in
csrc/ops/<op>/<op>_aten_kernels.{h,cc}(copyhardswish/orxlogy/),ImplStable<OpName::kFoo>(m, AtenFoo)incsrc/eager/tpu_aten_kernels.cc, and remove the op fromUNREGISTERED_OPSintests/native_functions_data.py. - TPU custom op: register
torch.ops.tpu._foowithImplInternalorImplExperimental, and re-export it astorch.tpu.ops.foo. - Graph rewrite: a pass in
csrc/mlir/passes/, added tocsrc/mlir/pipeline.cc; inspect it withTORCH_TPU_INTERNAL_DUMP_MLIR_PASSES_TO="print"(an internal variable). - Environment variable: register
kMyEnvVarinkEnvVarToStage(csrc/common/env_vars.h) and read it withGetEnvOnce.
Then pass these checks:
- CPU comparison: write the tests in
tests/ops_unit_test.py(assert_close_tpu_vs_cpu) and run them on a TPU VM. - API scanner: new names start Internal (a leading underscore), or Experimental (
@annotations.experimental) undertorch.tpu.*when users are meant to call them, and the API scanner test passes. - CI jobs: check which CI jobs run your test.
bazel test //tests:ops_unit_test --test_filter=<test name> # on a TPU VM
bazel test //tests/api:tt_apis_test
python ci/tools/list_ci_tests.py --test=//tests:ops_unit_test
Blueprint 3: integrating a model optimization or patch in vllm-torchtpu / sglang-torchtpu¶
Both engines follow the same order: use an extension point the upstream engine already has, and fall back to the repository's own patch or hook mechanism only when none reaches the code. Each repository then has its own gates.
- Prefer vLLM's plugin hooks,
register_ootregistration orAttentionBackendEnumregistration (R-3.5) over a patch. - Pallas math goes in
kernels/, thejax_opbridge inlayers/adapter/custom_ops/, and the vLLM binding inlayers/adapter/. - Add an environment variable only if R-6.2 allows it, and declare it in
src/vllm_torchtpu/envs.py(orTpuEnvsinsglang_tpu/envs.py). - Otherwise the change is one
Patchentry inPATCHES(src/vllm_torchtpu/patch_registry.py), or a hook insglang_tpu/hooks/for an SGLang core change with an upstream seam PR.
Gates in vllm-torchtpu:
pre-commit run --all-files
bash tools/typecheck_full.sh
pytest -q tests/platforms/test_patch_registry.py
JAX_PLATFORMS=cpu pytest tests/ -m "not tpu_test and not multichip and not nightly"
Gates in sglang-torchtpu:
python tools/plugin/check_tpu_branches.py && python tools/plugin/gate_audit.py
python3 scripts/ci/tpu/support_matrix.py --strict --check SUPPORT_MATRIX.md
Blueprint 4: writing, compiling and evaluating a tpu-agent-suite skill¶
Everything up to step 4 is editing files in package/; steps 5 and 6 are the build pipeline drawn in section 6.4.3, and the skill is finished only when Harbor compares it with a control arm.
- Create
package/skills/<skill-name>/SKILL.md(frontmatter perframework/schemas/skill-frontmatter.schema.json) and list the skill in a manifest (package.release.jsonorpackage.experimental.json). - Reference a specialist in
package/agents/<agent-name>.mdwith{{agent:<agent-name>}}; use tokens ({{script:...}},{{schema:...}},{{runtime}}) instead of literal paths. - Define each hand-off with a request and result schema in
package/schemas/. make verify(ormake verify-experimental) checks the manifest, graph, schemas, content and knowledge base;make build-experimentalwrites one distribution per harness underdist/<harness>/.- Install the built distribution, then evaluate with Harbor against a control arm.
make verify # or: make verify-experimental
make build-experimental
python3 <dist>/framework/installer.py install --destination /path/to/project
./eval/run.py --config claude-code/agent-suite claude-code/baseline --dataset tpu-hello-world
Note
With the hardware reference's peaks and bandwidths, the v5p, v6e and v7x ridges are about 166, 560 and 313 FLOPs/B. Blueprint 3's type check runs through pre-commit, which calls pyrefly. Two of the four agent harnesses are "coming soon".












