DEV Community

Cover image for TorchTitan on Cloud TPU: SimpleFSDP, Graph Trainer, Ray and GRPO
Omotayo Aina for Google Developer Experts

Posted on Edited on

TorchTitan on Cloud TPU: SimpleFSDP, Graph Trainer, Ray and GRPO

Whole-step graph training and RL post-training at pod scale, judged lever by lever with the case-study numbers.

Series: TorchTPU in Production: From First Tensor to Pod Scale. A five-part, hands-on series for PyTorch engineers moving real workloads onto Cloud TPU v6e (Trillium) and v7x (Ironwood) with TorchTPU. Part 1 builds the mental model (execution modes, memory, profiling, kernels). Part 2 runs Hugging Face Transformers v5 and Diffusers natively. Part 3 serves models in production with vLLM-TorchTPU, SGLang-TorchTPU and llm-d. Part 4 trains and post-trains at pod scale with TorchTitan, Ray and GRPO. Part 5 hands the whole workflow to the TPU Agent Suite. This is Part 4. Earlier: Part 1: TorchTPU Performance: Execution Modes, XProf and Pallas Kernels, Part 2: Hugging Face on TPU: Transformers v5, MoE Kernels and Diffusers, Part 3: vLLM and SGLang on TPU: Production Serving with llm-d 1.0. Next: Part 5: TPU Agent Suite: Onboard, Profile and Tune PyTorch on Cloud TPU.

You have a PyTorch training job that works. It runs on one 8-chip TPU host, the loss goes down, and the profile is mostly gaps. You add chips and the gaps do not close. You wrap your blocks in torch.compile and the trace now shows the compiled regions, plus a parade of copy ops around every FSDP all-gather. You try a 94-layer MoE and the compiler asks for more HBM than the chip has before step one. You switch to a 202k-token vocabulary and the logits alone take 15 GiB. Then someone asks for GRPO, and now a sampler and a trainer want the same HBM at the same time.

Each of those is a different bottleneck, and TorchTitan on TPU has a different lever for each one. The levers are cheap to flip (most are one config field) but expensive to flip in the wrong order, because each one changes what the next measurement means. This post is about judging which lever addresses which bottleneck, in which order, using the numbers Google and the TorchTitan maintainers published as evidence.

What you'll be able to do after reading:

  • Explain why SimpleFSDP's DTensor parametrization lets XLA overlap all-gathers with matmuls, and why FSDP2's hooks cannot.
  • Configure whole-step capture with TpuGraphTrainer, pick an optimizer compile mode and a memory policy, and know what each costs in HBM.
  • Compare scan over layers with the graph splitter for 100B+ models, and decide which one fits your model.
  • Diagnose when the fused soft-capped cross-entropy kernel pays and when it does not, from a peak-HBM number.
  • Compute MFU yourself and reproduce a published number to two decimal places.
  • Build a GRPO loop where a rollout worker and a trainer worker live on separate devices and sync weights through Ray.

Everything here has a runnable companion: code/sample_03_torchtitan_simple_fsdp_scan_and_ray_grpo.py in the series repo. Its --cpu-smoke mode runs every pure-PyTorch path on a laptop. --tpu runs the same objects on a TPU host. Part 5 reuses its compute_mfu() and sharding helpers.

The map: three costs, four steps

Before any code, fix the vocabulary. On TPU a training step loses time to three things.

  1. Dispatch. Every XLA program the host launches costs host time, and the TPU idles between launches. The TorchTitan TPU optimization guide (torchtitan/experiments/tpu/torch-tpu-optimization-guide.md) puts it bluntly: compile, or be dispatch-bound.
  2. Data movement. Copies, transposes, upcasts and layout changes that move HBM bytes without doing math. FSDP2's flat staging buffer is one. A torch.flip in scan's backward is another.
  3. Memory. Not time directly, but it caps batch size and forces recompute. Free HBM is what you spend on a bigger batch or on saving activations instead of recomputing them.

The TorchTitan TPU playbook orders the fixes in four steps, and the order matters because each step changes what the next one measures:

Step Goal Levers
1. Baseline correct, compiled, fits Graph Trainer + SimpleFSDP on a topology-aware mesh; full recompute (plus offload) so it fits; scan or graph splitter for 100B+
2. Kernels, overhead more FLOPs in dense kernels, less movement Splash attention, fused linear + CE, grouped MoE kernels, rewrite ops that lower to copies
3. Memory back to speed least aggressive policy that still fits save attention instead of recomputing, drop offload, grow the batch
4. XLA flags hide communication SparseCore offload, latency-hiding scheduler, scoped VMEM, p-state

Then profile in XProf and go back to whichever step owns the bottleneck you see. Keep that loop in mind. The rest of the post walks it.

Run the smoke test first so you have the numbers in front of you:

git clone https://github.com/ainaomotayo/torchtpu-sprint-26h4 && cd torchtpu-sprint-26h4
python code/sample_03_torchtitan_simple_fsdp_scan_and_ray_grpo.py --cpu-smoke
python -m pytest tests/test_sample_03.py -q    # 33 passed
Enter fullscreen mode Exit fullscreen mode

Part A: Why compiler-visible SimpleFSDP beats eager FSDP2 on TPU

What FSDP2 does that a compiler cannot see

FSDP2 (fully_shard) was built around the GPU execution model. It issues all-gathers and reduce-scatters from module pre-forward and post-backward hooks, and it gets overlap by putting those collectives on dedicated CUDA streams synchronized with events. Google's TorchTitan integration post names the consequence: none of that is visible to a compiler. The collectives sit outside the traced region, so on TPU a torch.compile region breaks at every FSDP hook and a whole-step graph cannot be captured at all. TorchTPU provides no-op stream and event objects only so FSDP2 runs. XLA has no use for them. It schedules from data dependencies.

There is a second, quieter cost. FSDP2 copies each parameter shard into a flat staging buffer before the all-gather and copies the gathered result back out into per-parameter tensors afterwards. On a GPU those copies are cheap and overlapped. On TPU they are HBM round trips on the critical path. In Google's FLUX.1 case study on a v6e-8, the eager trace "was dominated by FSDP2 copying parameter shards into a flat staging buffer before each all-gather and back out into per-parameter tensors afterwards." Replacing FSDP2 with SimpleFSDP removed the buffer and both copies and took the step from 9.95 s to 6.52 s, the single largest improvement on that ladder until compilation.

Animated timeline: the FSDP2 lane serializes orange copy blocks, purple all-gathers and blue matmuls on one TensorCore lane, while the SimpleFSDP lanes run all-gathers on an ICI and SparseCore lane one layer ahead of back-to-back matmuls on the TensorCore lane, finishing earlier
Schematic, not to scale: watch the orange staging copies disappear and the all-gathers move off the matmul lane once the collectives live inside the graph.

What SimpleFSDP does instead

SimpleFSDP stores each parameter as a sharded DTensor and installs a parametrization. Reading a module's weight runs DTensor.redistribute from Shard to Replicate: that is the all-gather. The autograd backward of that redistribute is the reduce-scatter. There are no hooks and no explicit collective calls, so both collectives are ordinary nodes in whatever graph is being traced, a per-block torch.compile region or the Graph Trainer's single make_fx step.

Mixed precision rides the same call. In ReplicateComputation.replicate_compute the redistribute is invoked with forward_dtype=self.param_dtype and backward_dtype=self.reduce_dtype, so the gather happens in bf16 and the gradient reduction in fp32. That is the setting every TPU recipe uses, and the optimization guide warns not to drop reduce_dtype to bf16 to save bandwidth: "that is a model-quality regression, not a perf lever."

Diagram inside one XLA program: a teal sharded weight feeds a purple all-gather in bf16, which feeds a blue matmul; the backward path runs from the matmul to a purple reduce-scatter in fp32 and ends at a green sharded gradient
Both collectives are nodes in the same program as the matmul, which is the only reason XLA can schedule the gather ahead of the math that needs it.

The sample reproduces that contract in about 30 lines, with functional collectives so you can trace it, test it and read it. From code/sample_03_torchtitan_simple_fsdp_scan_and_ray_grpo.py:

class _GatherInParamDtypeReduceInReduceDtype(torch.autograd.Function):

  @staticmethod
  def forward(shard, group, world_size, param_dtype, reduce_dtype):
    w = shard.to(param_dtype)
    if world_size > 1:
      w = funcol.wait_tensor(funcol.all_gather_single(w, gather_dim=0, group=group))
    return w

  @staticmethod
  def setup_context(ctx, inputs, output):
    shard, group, world_size, _param_dtype, reduce_dtype = inputs
    ctx.group, ctx.world_size = group, world_size
    ctx.reduce_dtype, ctx.shard_dtype = reduce_dtype, shard.dtype

  @staticmethod
  def backward(ctx, grad_full):
    g = grad_full.to(ctx.reduce_dtype)
    if ctx.world_size > 1:
      g = funcol.wait_tensor(
          funcol.reduce_scatter_single(g, "sum", scatter_dim=0, group=ctx.group)
      )
    return g.to(ctx.shard_dtype), None, None, None, None
Enter fullscreen mode Exit fullscreen mode

SimpleFSDPLinear keeps a fp32 row shard as its only parameter and calls that function on every weight read. On one CPU process the collectives are skipped and the layer is a plain nn.Linear with a bf16 matmul and an fp32 gradient. The same file also runs a two-process gloo check, run_gloo_parity().

Predict, then check. Rank 1 of 2 owns rows 4 to 7 of an 8 by 6 weight. Each rank computes the loss on its own half of a batch, divided by the global batch size. After backward(), should rank 1's weight_shard.grad equal rows 4 to 7 of the dense gradient computed on the full batch, or half of it? The smoke output answers:

2-process gloo parity (shard grads == dense grads): ['1 1 (4, 6)', '1 1 (4, 6)']
Enter fullscreen mode Exit fullscreen mode

Exactly equal, because SimpleFSDP reduces with Partial(reduce_op="sum"). That is also the most common migration bug: FSDP2 defaults to an AVG reduction, so the migration guide in torch_tpu/examples/fsdp/fsdp_to_simple_fsdp/fsdp_to_simple_fsdp.md tells you to scale the loss by 1 / world_size (or the learning rate) when you switch. The sample's ToyMuseGlimmer has a loss_scale field for exactly this.

The migration, and what it buys

The real migration is smaller than the sample. Before, per layer with manual prefetch tuning:

for layer in layers:
  layer.forward = functools.partial(checkpoint_utils.checkpoint, layer.forward, use_reentrant=False)
  fsdp.fully_shard(layer, mesh=mesh, mp_policy=mp_policy)
fsdp.fully_shard(model, mesh=mesh, mp_policy=mp_policy)
for i, layer in enumerate(layers):
  if i < len(layers) - 2:
    layer.set_modules_to_forward_prefetch([layers[i + 1], layers[i + 2]])
Enter fullscreen mode Exit fullscreen mode

After, one call, no prefetch lists:

model = simple_fsdp.data_parallel(model, device_mesh=mesh, mode="fully_shard", mp_policy=mp_policy)
compiled_model = torch.compile(model, backend="tpu")
Enter fullscreen mode Exit fullscreen mode

The tutorial's own comparison on 8 TPU cores, both compiled, same initial weights:

Step FSDPv2 loss FSDPv2 time SimpleFSDP loss SimpleFSDP time
2 0.952740 156.00 ms 0.952740 36.90 ms
3 0.952636 154.55 ms 0.952636 52.44 ms
4 0.952552 157.09 ms 0.952553 51.82 ms

Same losses, roughly 3x faster steady-state steps on a toy model. Do not extrapolate the 3x. Extrapolate the mechanism. In TorchTitan the switch is --parallelism.use_simple_fsdp, which every TPU recipe already sets.

Letting XLA hide the collectives: the flag bundles

Putting collectives in the graph makes overlap possible. libtpu flags decide how aggressively it happens. TorchTitan carries them on the config as named bundles in torchtitan/experiments/tpu/tpu_flags.py. The ones that matter for FSDP:

Bundle Flags What it does
SPARSECORE_LATENCY_HIDING_SCHEDULER xla_tpu_enable_sparse_core_collective_aggregator, xla_tpu_enable_latency_hiding_layer_scheduler lets the layer scheduler overlap FSDP collectives with compute (the two move together)
SPARSECORE_COLLECTIVE_OFFLOAD 2D/3D all-gather and reduce-scatter offload, offload queuing in LHS moves the collectives themselves off the TensorCore onto SparseCores
HIERARCHICAL_REDUCE_SCATTER ND reduce-scatter offload, hierarchical reduce-scatter, both SparseCores splits multi-dimensional reduce-scatters into stages (libtpu 0.0.47+)
ICI_AG_PIPELINING xla_tpu_enable_ici_ag_pipelining starts each layer's all-gather one scan iteration early, at an HBM cost
TPU7X_THROUGHPUT_P_STATE xla_tpu_dvfs_p_state=7 throughput operating point on v7x; does not change the graph

The Muse Glimmer 30B and Qwen3-8B/32B v7x 4x4x4 recipes use p-state 7, xla_tpu_scoped_vmem_limit_kib=65472, the SparseCore latency-hiding scheduler and hierarchical reduce-scatter. setup_torchtpu_distributed() exports exactly that set (it prints it in the smoke run), and like tpu_flags.py it lets anything already in your environment win.

One rule from the TorchTitan TPU README keeps flag sweeps honest: flags never change what the model computes, but some change how. A pure scheduling flag leaves the loss bit-identical. A flag that changes fusion or reduction order (hierarchical reduce-scatter is one) shifts rounding. Check the step-1 loss and gradient norm after every sweep. On the command line, --extra-libtpu-init-flags adds or overrides single flags, '!flag' drops one, and --libtpu-init-flags='' drops the recipe's whole set.

Distributed setup and the topology-aware mesh

TorchTPU runs one process per device and lowers collectives straight to StableHLO collective ops through the tpu_dist c10d backend. Two things differ from GPU, both covered in distributed_support.md: the slice topology must be known before the runtime starts, and every rank must agree on the slice-builder addresses. The sample's setup function follows that order:

def setup_torchtpu_distributed(mesh_shape=None, mesh_dim_names=("fsdp",), *,
                               libtpu_flags=None, xla_flags=None, fsdp_dim="fsdp") -> DistContext:
  # 1. LIBTPU_INIT_ARGS / XLA_FLAGS before any TPU op
  # 2. torch.tpu.distributed.set_tpu_launch_env()  (parent launcher; idempotent)
  # 3. dist.init_process_group(backend="tpu_dist")
  # 4. torch.tpu.distributed.topology_aware_mesh(mesh_shape)
  #    -> DeviceMesh("tpu", mesh=rank_tensor, mesh_dim_names=..., preserve_rank_order=True)
Enter fullscreen mode Exit fullscreen mode

Two details from the source are worth knowing. set_tpu_launch_env() only mutates os.environ, never overwrites a variable you set, and belongs in the parent process before spawning. In a torchrun worker the sample refuses to guess and tells you to run eval $(python3 -m torch.tpu.distributed | sed 's/^/export /') first, because per-rank guesses would disagree. And topology_aware_mesh takes the mesh shape ordered by increasing communication intensity, returns a rank tensor aligned to physical ICI rings, and detects multiple slices on its own. In TorchTitan the same mesh is one field: ParallelismConfig(enable_tpu_topo_mesh=True).

Past one slice: HSDP over DCN

A slice is a set of chips joined by ICI. A multi-slice job joins slices over the much slower data-center network. The layout that pays is HSDP: shard within a slice, replicate across slices, so the only DCN traffic is one gradient all-reduce per step that overlaps the backward pass.

Two blue dashed slice containers, Slice 0 and Slice 1, each running FSDP over ICI on a 4 by 4 grid of chips, connected by two-way arrows to one purple DCN all-reduce block underneath
All-gathers and reduce-scatters stay inside a slice. Only the replicated gradient crosses DCN.

The README for multi-slice runs is specific about three settings, and each one prevents a silent slowdown:

  • --parallelism.data_parallel_replicate_degree=$MEGASCALE_NUM_SLICES is required. With the default of 1, FSDP shard groups straddle slices and the job trains correctly at a fraction of the throughput. TorchTitan refuses to start rather than let that happen.
  • --parallelism.enable_min_cost_redistribute makes the planner reduce-scatter before the replicate-axis reduction, shrinking the DCN payload by the shard degree.
  • On v7x, MegaScale pins a host-memory pool per process, and TorchTPU runs one process per TensorCore (8 per VM), so the default reservation reaches 256 GiB per VM. --megascale_grpc_premap_memory_bytes=4294967296 with --megascale_use_numa_aware_block_allocator=false brings it to 32 GiB, which matters once activation offload also wants host RAM.

Part B: Capturing the whole step with TpuGraphTrainer

Why per-block compile leaves performance on the table

Per-block torch.compile turns each transformer block into one XLA program. It is the step that makes TorchTPU fast at all: on FLUX it took the step from 5.55 s to 3.02 s. But the optimization guide is clear about what remains: "the optimizer step, the loss, the embedding, and layout ops remain separate programs, and the host-side gaps between whatever is not inside a compiled region set a structural MFU ceiling." Compiling the transformer harder does not reduce the idle fraction, because the idle is not in the transformer.

TpuGraphTrainer (experiments/tpu/graph_trainer/tpu_graph_trainer.py) removes that surface. It traces forward, loss and backward with make_fx into one FX graph ahead of time, runs graph passes over it (including a memory policy that decides per tensor whether to save, recompute or offload), and compiles the result for TPU. With compile.optimizer_compile="in_graph" the AdamW update joins the same program through functional_adamw_step.

An amber Host CPU container holding a Python loop sends a single arrow into a blue dashed One XLA program container holding Forward, Loss, Backward, AdamW and Updated weights in a row
One arrow crosses the host boundary per step. Nothing runs on the host between the first forward op and the weight write-back.

That is the JAX model of training (the whole step is one jitted function) expressed in PyTorch. Google reports Qwen3-8B reaching 51% to 52% MFU on this path with the functional AdamW traced in.

torch.compile on the model GraphTrainer (aot_fx_trace)
Tracer Dynamo: guards, graph breaks make_fx: the whole step ahead of time
Covers model forward and backward forward, loss, backward, plus optimizer with in_graph
Activation memory checkpoint() inside the region a memory-policy pass: save, recompute or offload per tensor
FSDP SimpleFSDP SimpleFSDP collectives in the same graph, with prefetch passes

How to turn it on (and a correction)

You may have seen --tpu_config.use_graph_trainer, --tpu_config.use_scan_layers and --tpu_config.use_graph_split written as CLI switches. In the current TorchTitan source none of those fields exist. A recipe selects Graph Trainer by returning a TpuGraphTrainer.Config, and experiments/tpu/train.py dispatches on the config type. The scan and splitter switches live on the compile config as compile.use_scan_layers and compile.graph_split.enabled. From the optimization guide:

config = TpuGraphTrainer.Config.from_tpu_trainer_config(
    base_config, graph_trainer_model_registry  # e.g. graph_trainer.qwen3.model_registry
)
config.compile = TpuGraphTrainerCompileConfig(
    enable=True,
    components=["model"],
    memory_policy="default",       # replaces the eager activation_checkpoint config
    optimizer_compile="in_graph",  # optional: fold AdamW into the step graph
)
Enter fullscreen mode Exit fullscreen mode

Reference recipes: qwen3_8b() in experiments/tpu/qwen3/config_registry.py (in-graph optimizer) and muse_glimmer_30b_full_logits() in experiments/tpu/muse_glimmer/config_registry.py. Launch either with the standard entry point:

torchrun --nproc_per_node=8 -m torchtitan.experiments.tpu.train \
    --module=torchtitan.experiments.tpu.muse_glimmer \
    --config=muse_glimmer_30b_full_logits --training.steps=30
Enter fullscreen mode Exit fullscreen mode

Three costs come with whole-step capture, and the source states them plainly:

  • The whole step must trace. No graph breaks to fall back on, no data-dependent Python. The sample hit this itself: F.one_hot reads max(targets) on the host, so the fused loss builds its one-hot with scatter instead.
  • optimizer_compile="in_graph" costs HBM. Step inputs are not donated today, so the graph holds both the input and updated copies of parameters and optimizer state. (Some summaries describe this mode as using input-output buffer donation; the current guide says the opposite. Budget for the copy, or use separate_graph.)
  • GraphTrainer ignores the eager activation_checkpoint config. Activation memory is compile.memory_policy: default (selective recompute), full, tpu_selective (full recompute but keep named regions such as attention.inner_attention or feed_forward.w2), plus offload variants. Recipes on libtpu 0.0.48+ also set xla_enable_hlo_sharding_v3=False, because Shardy HLO sharding v3 segfaults on GraphTrainer.

The same idea in 40 lines: run_single_trace_training_step()

TorchTPU ships a standalone version of whole-step capture: torch.tpu.optimizers.SingleTraceTrainer, exported with torch.tpu.optimizers.AdamW in torch_tpu/src/torch_tpu/_internal/public_api.py and marked experimental. Its make_compiled_train_step() runs func.grad_and_value(loss) plus the optimizer under make_fx and hands the FX graph to a compile function. The sample's TPU branch:

trainer = torch.tpu.optimizers.SingleTraceTrainer(
    model,
    optimizer=torch.tpu.optimizers.AdamW(lr=lr, weight_decay=0.1, beta2=0.95),
    compile_fn=_tpu_compile_fn,  # torch.compile(gm, backend="tpu", dynamic=False)
    compute_loss_fn=lambda m, args, kwargs: m(*args, **kwargs),
)
step_fn = trainer.make_compiled_train_step((tokens, targets))
Enter fullscreen mode Exit fullscreen mode

When there is more than one rank, the sample also wraps model.forward with torch.tpu.distributed.spmd_safe. By default TorchTPU compiles each collective as its own "skinny" program for MPMD safety. @spmd_safe tells it this code is identical on every rank, so the collectives fuse into the step program and XLA can overlap them.

On CPU, CpuWholeStepTrainer does the same thing without the TPU compiler: one make_fx trace of forward, the fused loss, backward and an out-of-place functional_adamw(). Predict, then check: the toy model has 51 parameter tensors. How many aten.sqrt nodes will the traced step contain?

== 4. Whole-step trace: forward + fused CE + backward + AdamW in ONE graph
   graph: {'call_function_nodes': 2253, 'matmul_like': 108, 'adamw_sqrt': 52}
   losses: 6.2635 5.9571 5.6564 5.3510 5.0503 4.7955 4.5812
Enter fullscreen mode Exit fullscreen mode

Fifty-two: one sqrt(v) per parameter plus one bias-correction square root. Every matmul of forward and backward and every optimizer update sits in one graph of 2,253 ops. The test test_whole_step_trace_matches_eager_adamw checks that three traced steps match three eager steps with torch.optim.AdamW to 1e-5.

Measuring it: compute_mfu() reproduces the published number

MFU is the number every case study quotes, so compute it yourself. TorchTitan's convention (models/utils.py, get_nparams_and_active_nparams) is 6 x active parameters per token plus attention FLOPs, where active parameters exclude the embedding table but include the LM head, and attention adds 6 x heads x (2 x head_dim) x attended tokens per layer with no causal discount. The sample implements that for Muse Glimmer's exact shape (52 layers, dim 6,656, 32 query and 2 KV heads, an output-gate projection, and a repeating pattern of three 2,048-token sliding-window layers then one global layer):

def compute_mfu(tokens_per_sec, params, chips, peak_flops_per_chip, attention_flops_per_token=0.0):
  achieved = tokens_per_sec * (6.0 * params + attention_flops_per_token)
  return achieved / (chips * peak_flops_per_chip)
Enter fullscreen mode Exit fullscreen mode
== 7. MFU arithmetic vs published numbers
   Muse Glimmer 30B: active params=26.51B, flops/token=173.5 GFLOP
   5,848 tok/s/chip on 64 v7x chips -> MFU 43.97% (published: 43.98%)
   recipe README 3,245 tok/s/device x 128 devices -> MFU 48.80% (README: ~48.8%)
Enter fullscreen mode Exit fullscreen mode

The trap this catches: TorchTPU exposes a v7x chip as two devices. TorchTitan's get_peak_flops() returns 2,307 TFLOP/s divided by 2 per device, and Google's Muse Glimmer table reports TPS per chip as twice TPS per device. Mix per-device throughput with per-chip peak and your MFU is off by 2x. The sample keeps everything per chip (PEAK_BF16_FLOPS_PER_CHIP = {"v6e": 918e12, "v7x": 2307e12}).

The second line is also a useful surprise. The current recipe README reports about 48.8% MFU, higher than the 43.98% in the launch post. The README's own tables point at the save regions: the same recipe measured about 44.0% MFU under full recompute and 48.8% with the Splash and w2 outputs saved. More on that in Part C below.

Scaling compilation past 100B: scan or graph splitter

One unrolled step graph stops working as depth grows, and the guide lists three reasons. Compile time and compile-time memory grow with depth. With ZeRO-3 on one unrolled graph, XLA can merge the forward all-gathers with the recomputed ones and keep full parameters alive through backward, so the config rejects that combination unless you pick a structure. And each layer's saved input stays live until its backward. On Qwen3-235B (94 layers, 128 experts) the flat graph asks for more HBM than the chip has before a step can run.

Before you look at the animation, guess: if one decoder layer contributes five ops to the traced forward graph, how many ops does a 32-layer scan contribute?

Animated comparison: on the left a stack of blue layer bars grows from 1 to 32; in the middle a single loop body over a teal stacked-weight block stays fixed; on the right an orange line of traced op counts climbs linearly to 161 while a green scan line stays flat at 4
Counts are real: traced_forward_nodes() in the sample traces both versions with make_fx on CPU. Unrolled grows by 5 ops per layer. Scan stays at 4.

Scan over layers (compile.use_scan_layers=True) stores each kind of weight as one [n_layers, ...] tensor (graph_trainer/layer_stack.py, StackedLayers) and runs the decoder as a single torch._higher_order_ops.scan loop. The compiler sees one body. FSDP gathers one layer's shard per iteration, so the full stack of weights is never resident, and the body is fully recomputed in backward. The graph splitter (compile.graph_split.enabled=True) keeps layers unrolled and cuts the traced step into separately compiled forward and backward programs, optionally one per layer group.

Two panels: Scan, with teal Stacked weights feeding a blue Loop body that has a self-loop arrow; Graph splitter, with a blue Forward program feeding stacked Backward programs; both send an offload arrow down to an amber Host memory block in a Host CPU strip
Both structures fix compile time and ZeRO-3 parameter lifetime. Host offload fixes saved activations and works with either.

Scan (compile.use_scan_layers) Graph splitter (compile.graph_split.enabled)
Step runs as one program, layers as one loop many programs, one per layer group
Parameters stacked; per-layer names gone (checkpoints keep them, optimizer state does not) unchanged
Parallelism FSDP and HSDP tested; TP, CP, PP, EP rejected not restricted by config
Layers must be identical, body must not mutate state any mix of layer types
In-graph optimizer allowed, no recipe uses it rejected
Offload policy full_and_scan_offload full_and_offload, tpu_selective_and_offload
Recipes llama3_*_scan(), qwen3_moe_235b_scan() qwen3_moe_235b_fsdp_activation_offload_*()

On Qwen3-235B the two land within a few percent of each other, and Google reports 29%+ MFU on this path. So how do you choose? Scan is the XLA-native construct and the only one that compiles Llama 3 405B in its recipe. The splitter wins when your layers are not identical (hybrid attention, mixed MoE and dense), when you need TP, EP or CP, or when per-layer parameter names must survive (optimizer checkpoints do not move across a scan flip). One subtle cost of scan: its per-layer saves come out as one stacked [n_layers, batch, seq, dim] tensor that cannot be freed a row at a time, which is why the guide calls offload "close to mandatory" with scan.

scan_backward_patch: a copy you would never find without a profile

PyTorch's ScanAutogradImpl.call_backward reverses the loop by calling torch.flip on every saved activation stack, scanning forward over the flipped copies, and flipping the gradient stacks back. The docstring of experiments/tpu/scan_backward_patch.py explains why that hurts on TPU: the first flip copies every activation the forward saved, and on TPU it costs twice that again because a reversed tensor needs a new memory layout. At any size where saved stacks are the bulk of memory, that copy is what runs the chip out of HBM. The patch makes torch.flip a no-op for the duration of one call_backward and runs a reverse loop over an ascending index that reads each row with index_select, so the same rows arrive in the same order with no copy. It is a data-movement fix in the purest form. (Some summaries quote specific GB savings for Llama 3 8B and Qwen3-30B-A3B; I could not find those numbers in the TorchTitan source or docs, so I am not repeating them.)

Part C: Kernels, memory and the case studies as evidence

Splash attention and the fused loss

Two Pallas kernels do most of the work in step 2 of the playbook. Both are JAX functions turned into PyTorch custom ops by torch.tpu.pallas.jax_op, and both are a config switch tested against the plain PyTorch path they replace.

Splash attention (--splash_attention_kernel.use_splash_attention_kernel, kernels/splash_attention.py) never materializes the attention matrix and handles causal, sliding-window and packed-document masks through segment ids. Its nine block sizes (sa_block_q, sa_block_kv and friends) default to 512. Muse Glimmer's recipe uses 1,024 everywhere, and Google's post warns that values tuned on Trillium should not be expected to carry over to Ironwood. At short sequence lengths it is often a wash against TorchTPU's built-in flash SDPA, so measure.

Fused linear + cross-entropy (PallasCrossEntropyLoss, kernels/linear_softmax_cross_entropy_loss.py) computes the LM-head matmul, softmax and loss one vocabulary tile at a time, so the [tokens, vocab] logits never reach HBM. Its block sizes live in LossKernelConfig (loss_b_block_size=1024, loss_h_block_size=512, loss_v_block_size=2048), and one constraint bites silently: the flattened token count must be a multiple of loss_b_block_size or the kernel falls back to XLA without telling you. For Muse Glimmer the kernel was extended (kernels/linear_softmax_ce_softcap_kernel.py) to apply the soft-cap cap * tanh(z * alpha / cap) per tile, with cap=20.0 and alpha=0.19611613513 from the model config.

The sample's ChunkwiseFusedSoftcapCrossEntropyLoss is the pure-PyTorch version of the same idea, chunked over tokens instead of vocabulary. For each chunk it computes the logits, the loss, and the gradient analytically, using the same derivative the Pallas kernel applies:

u = hc @ w32.t()
t = torch.tanh(u * (alpha / cap))
z, dz_du = cap * t, alpha * (1.0 - t * t)       # soft-capped logits and their slope
lse = torch.logsumexp(z, dim=-1)
loss = loss + ((lse - picked) * vc).sum()
g = torch.softmax(z, dim=-1)
g = g - torch.zeros_like(g).scatter(-1, safe_t[:, None], 1.0)
g = g * vc[:, None].to(g.dtype) * dz_du          # dL/du for this chunk only
grad_h_chunks.append(g @ w32)
grad_w = grad_w + g.t() @ hc
Enter fullscreen mode Exit fullscreen mode

Only a [chunk, V] block is ever live. The Muse Glimmer standalone example takes the other route to the same place: it calls loss.backward() inside a torch.compiled chunk function, which recent PyTorch no longer treats as a graph break. The smoke test compares the chunked loss with a naive full-logits reference in float64:

== 2. Chunkwise soft-capped CE vs naive full-logits CE
   loss naive=7.1130580669 chunked=7.1130580669
   max|dh| diff=1.91e-17  max|dW| diff=5.20e-18
   Muse Glimmer [8, 5120, 202048] bf16 logits = 15.4 GiB; one 1024-token chunk = 395 MiB
Enter fullscreen mode Exit fullscreen mode

The pytest file sweeps chunk sizes 1, 7, 16, 96 and 500, with and without the cap and with ignored tokens, and checks forward and both gradients.

When the fused loss pays, and when it does not

Here is where Evaluate starts. The fused kernel's value is memory, and the TorchTitan maintainers measured exactly when that memory matters on Muse Glimmer 30B (from the docstring of muse_glimmer_30b_full_logits()):

Grouped bar chart of peak HBM per device: at 16,384 tokens per device, full logits 46.18 GiB and fused CE 46.12 GiB; at 2 x 16,384 tokens, full logits 87.62 GiB and fused CE 51.84 GiB
At one 16k sequence per device the fused loss saves 0.06 GiB. Double the tokens and it saves 35.78 GiB.

At 16,384 tokens per device the logits are not what sets peak HBM, so the fused kernel saves nothing, and XLA's plain LM-head matmul plus cross-entropy runs about 2% faster (2,913 vs 2,851 TPS, 43.8% vs 42.9% MFU). That is why the recipe named full_logits is the default. At 2 x 16,384 tokens the logits dominate: 87.62 GiB with full logits against 51.84 GiB fused. The regular (non-graph) trainer runs out of HBM at step 1 with full logits.

The lesson generalizes. A memory lever only pays when memory is the binding constraint. Turn it on when the profile says HBM-bound, and spend what it frees on batch, which is the single largest MFU lever at small scale according to the guide.

Trading memory back for speed: the memory policy

Step 3 of the playbook says "relax to the least aggressive policy that still fits." The Muse Glimmer recipe README measured four configurations on the same 64-chip slice:

Scatter plot of step time against peak HBM for four Muse Glimmer 30B configurations, with a dashed orange line at the 94.74 G per-device compile-time limit: fused CE full recompute at 5.72 s and 46.1 GiB, fused CE saving Splash and w2 at 5.19 s and 59.8 GiB, full logits saving Splash at 5.30 s and 76.1 GiB, full logits saving Splash and w2 at 5.05 s and 78.7 GiB
Down and to the right is faster but hungrier. The fastest point peaks at 78.7 GiB, close to the 94.74 G compile-time limit the README reports.

tpu_selective with two save regions (the Splash output and LSE, and the FFN w2 output that the post-FFN norm's backward reads) cut the fused-loss recipe from 5.72 s to 5.19 s, a 9.3% gain, for 13.65 GiB more HBM. The saves grow with tokens per microbatch: at 2 x 16,384 tokens the fused recipe with both saves runs out of HBM at compile time (96.29 GB of temporaries against 94.74 GB available). A middle setting saves Splash only in the last 26 layers, which backward reaches first, and recovers about half the speedup with no extra peak HBM.

The FLUX ladder: which lever fixed which cost

The FLUX.1 case study is the cleanest worked example of the playbook order, because each stage was measured on the same v6e-8 with batch 3 at 1024x1024:

Horizontal bar chart of FLUX.1 step time on TPU v6e-8: baseline eager FSDP2 with activation checkpointing 11.49 s, DeferAndFuse 9.95 s, SimpleFSDP 6.52 s, Splash attention 5.55 s, per-block torch.compile 3.02 s, graph fusion rewrites 2.78 s, a 4.13x total speedup
Two of the five steps are data-movement fixes and two are dispatch fixes. Read each bar as the cost it removed.

Analyze each step by the cost it removed:

Stage Step time Cost removed Evidence in the source
DeferAndFuse eager 11.49 to 9.95 s dispatch 28% fewer HLO module invocations
SimpleFSDP 9.95 to 6.52 s data movement flat staging buffer and both copies gone
Splash attention 6.52 to 5.55 s memory and padding packing with segment ids, no MXU cycles on padding
Per-block torch.compile 5.55 to 3.02 s dispatch large subgraphs, control flow out of Python
Graph fusion rewrites 3.02 to 2.78 s data movement split fused projection, plain-math RoPE, view instead of transpose

The final 2.78 s is about 99% of JAX MaxDiffusion's throughput on the same hardware. The last row is worth a second look: three small, local edits to the model code, each found in a profile, each removing a copy. That is what "profile, then go back to the lever" means in practice.

Scaling evidence: does it hold at pod size?

Weak scaling is the honest test of the distributed half: keep work per chip fixed, add chips, see what per-chip throughput does. Three models, three shapes of evidence (all from Google's TorchTitan post, all on v7x):

Two stacked panels for Muse Glimmer 30B from 8 to 128 v7x chips: tokens per second per chip falls from 6,096 to 5,768 and MFU from 45.84% to 43.36%
Muse Glimmer loses about 5% of per-chip throughput over a 16x increase in chips, on plain FSDP with no HSDP.

Two stacked panels for FLUX.1 from 8 to 1,024 v7x chips: step time moves from 2.53 s to 2.71 s and MFU from 20.76% to 19.35%
93% weak-scaling efficiency, but only after switching from pure FSDP to HSDP past one 4x4x4 cube.

Two stacked panels for Qwen3-235B-A22B from 64 to 8,192 v7x chips with the multi-slice region shaded: tokens per second per chip goes from 4,568 to 4,208 and MFU from 33.12% to 30.51%
The visible step down is at 4,096 chips, inside the multi-slice HSDP region. From 4,096 to 8,192 it is flat.

Three readings, from most to least obvious:

  1. The framework holds. Qwen3-235B keeps 92% of per-chip throughput across 128x more chips, with HSDP over DCN from 2,048 chips up and 1,024-chip slices as the sharding group. Llama 3 405B holds about 57% MFU from 128 to 1,024 chips.
  2. Small models need HSDP sooner. FLUX at 12B is compact enough that pure FSDP slows down past one 64-chip cube: there is too little work per gathered byte. HSDP fixes it by sharding within each 4x4x4 cube and replicating across cubes, using the topology-aware mesh to map onto the 8x8x16 torus. The guide's general rule: choose HSDP when the FSDP group would be wider than the collectives need, or when the replicate axis maps to a slow link.
  3. Weak scaling is not a training recommendation. Google's caveat is explicit: the 8,192-chip Qwen3 run grows the global batch with the chip count, past what anyone would train this model with. It proves the compiler and collectives hold at that scale, nothing more.

A decision table you can use on Monday

You see in XProf or the logs Lever Evidence What it costs
TPU idle between many small programs per-block torch.compile, then Graph Trainer FLUX 5.55 to 3.02 s; Qwen3-8B 51-52% MFU whole-step the block (then the step) must trace
copy ops around every all-gather SimpleFSDP (--parallelism.use_simple_fsdp) FLUX 9.95 to 6.52 s; tutorial ~3x scale loss by 1/world_size
exposed all-gathers and reduce-scatters SPARSECORE_LATENCY_HIDING_SCHEDULER, HIERARCHICAL_REDUCE_SCATTER Qwen3-235B: most collective time hidden behind compute reduction order may shift rounding
compile time or compile-time HBM grows with depth scan (identical layers) or graph splitter (anything else) Qwen3-235B and Llama 3 405B only compile this way scan: stacked names, no TP/EP; splitter: no in-graph optimizer
OOM at the LM head, large vocab fused (soft-capped) CE 87.62 to 51.84 GiB at 2 x 16k tokens about 2% slower when logits are small
HBM headroom left after it fits tpu_selective save regions, then bigger batch Muse 5.72 to 5.19 s more peak HBM, grows with tokens
per-chip throughput falls past one cube HSDP on a topology-aware mesh FLUX 93% to 1,024 chips memory goes up by the replicate degree

Part D: RL post-training with Ray, Miles and VeRL

Why RL is a heterogeneous-compute problem

GRPO alternates two workloads with opposite needs. Rollout is serving: a vLLM-TorchTPU or SGLang-TorchTPU engine with a paged KV cache, compiled per token-count bucket, as Part 3 covered. Training is everything in this post so far: weights, gradients, optimizer state, activations. Put both on the same chips and they fight over HBM. The README of TorchTitan's Ray experiment, experiments/tpu/rl_nc_ray, states the design choice directly: in a non-colocated setup the policy trainer and the vLLM generator run on separate TPU slices, so "the training weights/gradients and the KV cache do not compete for the same HBM."

That makes orchestration the hard part: who runs where, how the slice is reserved, and how fresh weights reach the sampler. That is Ray's job.

Ray on TPU, one device per worker

Anyscale and Google's announcement describes the model: Ray now runs one worker per TPU device, matching PyTorch's one-process-per-device model. A worker asks for resources={"TPU": 1} the way a GPU worker asks for num_gpus=1, Ray isolates the device through TPU_VISIBLE_CHIPS, and the only code changes from GPU are the device string and backend="tpu_dist". SlicePlacementGroup gang-schedules actors onto one slice over ICI. For training, Ray Train's TorchTrainer reserves the slice for you:

scaling_config = ScalingConfig(
    num_workers=16,
    use_tpu=True,
    topology="4x4",
    accelerator_type="TPU-V6E",
    resources_per_worker={"TPU": 1},
)
trainer = TorchTrainer(train_loop_per_worker=train_fn_per_worker, scaling_config=scaling_config)
Enter fullscreen mode Exit fullscreen mode

With use_tpu=True, TorchTrainer provisions a SlicePlacementGroup under the hood, sets RANK, WORLD_SIZE, MASTER_ADDR and the TorchTPU slice-builder variables, and initializes tpu_dist. I use the ScalingConfig path rather than constructing SlicePlacementGroup by hand because its constructor is not documented in the sources this post draws on.

The GRPO loop, piece by piece

A clockwise loop around an amber Ray controller: Rollout engine inside a Rollout chips container, Reward, Group advantage, TorchTitan trainer inside a Trainer chips container, and Weight sync back to the rollout engine
Rollout chips hold the KV cache. Trainer chips hold weights, gradients and optimizer state. Only weights cross between them.

The math is small. For each prompt, sample a group of G completions, score each one, and use the group itself as the baseline. TorchTitan's estimator (experiments/rl/rollout/advantage.py) is:

A_i = (r_i - mean(r)) / (pstdev(r) + 1e-6)     # GRPO, should_std_normalize=True
A_i =  r_i - mean(r)                           # Dr.GRPO mean baseline, the default
Enter fullscreen mode Exit fullscreen mode

Note the default: TorchTitan ships should_std_normalize=False, the Dr.GRPO variant. The loss (experiments/rl/losses/dapo.py, with GRPOLoss as DAPO with one symmetric clip) is the per-token clipped surrogate -min(ratio * A, clip(ratio, 1 - 0.2, 1 + 0.2) * A), averaged over valid response tokens.

Predict, then check. A group of four scores [1, 1, 1, 0]. Which sample gets the largest-magnitude advantage, and what sign? And what does a group that scores [0, 0, 0, 0] contribute?

== 6. GRPO: group-relative advantages and a short RL run
   rewards [[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 0.0]]
   GRPO adv [[1.0, -1.0, -1.0, 1.0], [0.0, 0.0, 0.0, 0.0], [0.577, 0.577, 0.577, -1.732]]
   Dr.GRPO  [[0.5, -0.5, -0.5, 0.5], [0.0, 0.0, 0.0, 0.0], [0.25, 0.25, 0.25, -0.75]]
Enter fullscreen mode Exit fullscreen mode

The lone failure gets -1.732: rare outcomes carry the strongest signal. The all-zero group contributes nothing, which is why group size and task difficulty matter so much: a group where every sample fails (or every sample succeeds) is wasted rollout compute. The sample's history logs groups_with_signal for that reason.

Animated GRPO loop: the active stage cycles through Rollout, Reward, Group advantage, Policy update and Weight sync; a side panel fills in eight sampled answers to 3 + 4, their rewards with one correct answer, and advantages of +2.65 for the correct sample and -0.38 for the rest, while a reward curve rises over 60 iterations
One correct answer in eight earns +2.65. The other seven share -0.38. The curve is the sample's toy policy on CPU, five-iteration average.

RayTpuGrpoPipeline wires the five stages together. Rollout and trainer are plain classes. With use_ray=True they become actors, each with {"TPU": 1} on TPU. From the sample:

def run(self, iterations: int | None = None) -> list[dict[str, float]]:
  self.sync_weights(0)
  for it in range(iterations or self.cfg.iterations):
    prompts, expected = self.sample_prompts()
    roll = self._call(self.rollout, "generate", prompts, self.cfg.group_size)
    answers = roll["answers"]
    rewards = (answers == expected[:, None]).float()  # math_reward, vectorized
    adv = group_relative_advantages(rewards, self.cfg.std_normalize)
    metrics = self._call(self.trainer, "train_step", prompts, answers,
                         roll["old_logprobs"], adv)
    if (it + 1) % self.cfg.sync_every == 0:
      self.sync_weights(it + 1)
Enter fullscreen mode Exit fullscreen mode

sync_weights() pulls the trainer's state dict, ray.puts it, and passes the ObjectRef wrapped in a list. That wrapper is borrowed from rl_nc_ray/grpo.py, whose comment explains it: passing the ref directly makes Ray resolve and deserialize it on the generator driver, which becomes a CPU and memory bottleneck. On CPU, 40 iterations of the toy task (answer a + b, group size 8) take the mean reward from 0.069 to 0.264. The test asserts the gain and that the rollout runs exactly one policy version behind the trainer.

What exists today, and how preview it is

Three stacks run this loop on TPU, at different maturity levels. Be precise about which is which.

  • TorchTitan rl_nc_ray. A Ray orchestrator (RayController) that subclasses TorchTitan's GPU RL controller, launches RayTPUPolicyTrainer and RayVLLMGenerator actors, and moves the state dict through Ray's object store. scripts/e2e_recipe_gke.sh submits python3 -m torchtitan.experiments.tpu.rl_nc_ray.grpo as a Ray job on a GKE KubeRay cluster with an 8-way tensor-parallel generator, for Qwen3-0.6B, 1.7B or 4B. The local smoke scripts put the trainer on CPU and the generator on TPU.
  • Miles with SGLang-TorchTPU (preview). RadixArk's RL framework, with SGLang-TorchTPU generating rollouts and TorchTitan training on them. On one v7x host with 4 chips, 2 for the trainer and 2 for rollouts, Qwen3-4B with GRPO on DAPO-Math-17k produced reward and response-length curves that match a 6x H200 baseline within seed-to-seed variation, with AIME-24 within eval noise. Multi-host training and larger models are listed as next steps.
  • VeRL (Preview). Google's PyTorch-on-TPU overview lists VeRL's examples/tpu/grpo as a preview integration that delegates parameter updates to TorchTitan and pushes updated weights to serving engines for rollouts. TorchTPU's own feature table lists VeRL under near-term focus. I could not inspect the recipe's contents from the sources available here, so this post does not describe its flags.

Weight sync: shared memory, disk, or ICI

Miles names three ways to move weights from trainer to engine:

Path Where it works Status
Host shared memory trainer and engine on one host what the Miles runs use today
Disk (full checkpoint, engine reloads) across hosts works, slowest
ICI, device to device within the interconnect planned; "about 50x faster than shared memory" in their test

You may see that 50x attached to TorchTPU's WindowTPU. The source says to be careful. WindowTpu in torch_tpu/csrc/distributed/window_tpu.h implements PyTorch's c10d::Window (Python: dist._new_window(tensor), then win.put(...) and win.wait_signal(...), as in tests/distributed/window_tpu_test.py). Host-to-device and device-to-host puts are true one-sided DMA. Peer transfers across chips are, in the header's words, "currently emulated via two-sided ProcessGroup send/recv rendezvous", and non-zero target offsets are not supported for peers. The sample includes window_weight_sync() as an experimental helper that follows the test's API exactly, but its default path is the Ray object store, as rl_nc_ray does.

Evaluating the RL design choices

Decision Choose A when Choose B when
Split chips on one host vs separate slices one host: the model is small, both halves fit on a few chips each, and sync can use host shared memory (Miles: 2 trainer + 2 rollout chips) separate slices: either side needs a slice of its own, or you want to scale them independently (rl_nc_ray)
Sync every step vs every few every step: on-policy, small model, shared-memory sync is cheap every few: sync is disk or cross-host and costs more than a step; accept off-policy staleness that the clipped ratio absorbs
GRPO vs Dr.GRPO advantage std-normalize when reward scales vary across prompts mean baseline (TorchTitan default) when you want unbiased length and difficulty weighting
Group size larger G when many groups score all-zero or all-one smaller G when rollout time dominates and most groups already have signal
TorchTrainer vs raw actors Ray Train for plain SFT or pre-training loops on a slice actors for multi-stage pipelines where rollout and train are different programs

Try it yourself

Each exercise uses the sample file and should take under an hour on a laptop.

  1. Break SimpleFSDP on purpose. In _gloo_parity_worker(), divide the loss by the local batch size instead of the global one. Predict what run_gloo_parity() reports, run it, and then fix it with loss_scale the way FSDP2 migrations must.
  2. Find the fused loss's break-even. Using logits_hbm_bytes(), compute the logits footprint for your own model's vocabulary at 1x, 2x and 4x tokens per device, and compare it with your measured peak HBM. At which point would you switch from full logits to the fused kernel?
  3. Make scan earn its keep. Extend traced_forward_nodes() to trace a stack of real MuseGlimmerDecoderLayers (stack their weight_shards along a new leading dimension). How many ops does one Muse layer add to the unrolled graph?
  4. Try Dr.GRPO. Run RayTpuGrpoPipeline(GrpoConfig(std_normalize=False)) and compare reward curves and groups_with_signal against the default. Then raise group_size to 16 and explain the change.
  5. Compute your own MFU. Feed your job's tokens per second, active parameter count and chip count into compute_mfu(). If your number disagrees with TorchTitan's logged MFU by 2x, check whether you mixed per-device and per-chip numbers.

If you build something with these pieces, post it with #TorchTPUSprint.

Summary

The levers in TorchTitan on TPU are building blocks, each behind one config field, and the case studies say what each is worth. SimpleFSDP puts sharding inside the graph so XLA can overlap it and the staging copies disappear (FLUX: 9.95 to 6.52 s). Graph Trainer makes the whole step one program (Qwen3-8B at 51-52% MFU), at the cost that the whole step must trace and the in-graph optimizer holds an extra copy of state. Scan or the graph splitter make 100B+ models compile at all, and host offload makes them fit. Fused kernels buy memory, which only pays when memory is the constraint (the Muse Glimmer recipe defaults to full logits for exactly that reason). And for RL, Ray gives each rollout and trainer worker its own TPU device, with weight sync as the cost that decides how often you can be on-policy.

Part 5 hands this workflow to the TPU Agent Suite, which reuses compute_mfu() and the sharding helpers from this post's sample to reason about rooflines and MFU before it touches a kernel.

References: Integrating TorchTPU into TorchTitan and Optimizing Models for TPU (Google, Oct 2026). TorchTitan TPU optimization guide. TorchTPU distributed support. FSDP best practices. Muse Glimmer 30B training case study. Announcing Ray support for PyTorch on Google TPUs. SGLang-TorchTPU and Miles RL.

Top comments (0)