Skip to content

[TPU][Scan remat] 3/3: Save regions in the last N scanned layers, as fenced scan segments - #222

Draft
jack8558 wants to merge 23 commits into
jackoh/remat-2-offloadfrom
jackoh/remat-3-segments
Draft

jack8558 wants to merge 23 commits into
jackoh/remat-2-offloadfrom
jackoh/remat-3-segments

Conversation

@jack8558

@jack8558 jack8558 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #154 (and #153). Review only this PR's own commits: aabae6c...d53dffe

Part of #29. Third of 3 PRs:

PR What it does Depends on
#153 Region tags + a SAC policy decide what the scan body saves; no PyTorch patches main, PyTorch nightly 2.16.0.dev20261120+
#154 Scan host offload picked by name (compile.scan_offload); attention save works with offload #153
PR 3 (this) compile.save_last_n_layers under scan, as fenced scan segments #154

Requires PyTorch nightly ≥ 2.16.0.dev20261120 (through #153): pytorch/pytorch#203334 (012eb2b6a70) and pytorch/pytorch#203534 (4378929563f).

Goal

Let a recipe save attention in only the last N layers under scan, to trade memory for speed in finer steps than all-or-nothing.

This PR

Change: compile.save_last_n_layers works with --compile.use-scan-layers:

--compile.memory_policy=tpu_selective_and_offload \
--compile.save_last_n_layers attention.inner_attention 12

One scan body has one partition, so the layers run as consecutive scans over slices of the same stacks, each with its own save regions:

94 layers, last 12:  scan(layers 0..81, recompute) -> scan(layers 82..93, save attention)

fence_scan_segments puts an optimization barrier between consecutive scans in the same direction. Without it the next loop's weight gathers overlap the previous loop's reduce-scatters and both sets of buffers are live (4 real Qwen3-235B layers, 8 v6e chips, last 2 saved: 37.4 GiB unfenced (compile OOM), 17.7 GiB fenced, 19.8 GiB as one scan).

  • No last-N setting: same program as main.
  • N >= n_layers: one scan that saves the region in every layer, the same segments as save_regions (unit test).
Lines Files
Code +251 / −28 5
Tests +236 / −30 4

Validation

64 v7x chips (128 ranks), this PR alone against main: tree = this PR at f3c0b6cdd (jackoh/remat-3-segments-1119), not the top of the stack. Main = a83bff731. Both arms on the same image, which must have PyTorch with pytorch/pytorch#203334 + #203534 (nightly 2.16.0.dev20261120 or later) and torch_tpu main. Step time = median of the steps after warmup, without the profiled step.

64-chip runs on f3c0b6cdd; since then: merges of #154 and main, and the review fixes (8e2d4efa9e: config checks, a per-segment offload check, the fence's no-pair check), and the #153/#154 review edits (comments, a docstring, tests, a constant, the PyTorch-fix check and the no-grad path). On the current head d53dffe891, 8 chips: default step HLO identical to main, and the last-8 step HLO identical to before the fixes.

Arm Model Loss + grad norm match Step time Compiled peak memory Job Image
main Qwen3-235B, 15 steps — 24.84 s 77.77 GiB nw-mn235-rs64 native-ab-e10d1a346-nw1119f60 (torch 2.16.0.dev20261112 + pytorch#203334, #203534)
this PR Qwen3-235B, 15 steps 15/15 24.84 s 77.77 GiB nw-a3235-rs64 native-ab-e10d1a346-nw1119f60 (torch 2.16.0.dev20261112 + pytorch#203334, #203534)
main Llama 3 405B, b3 seq 8192, 10 steps — 101.37 s 94.72 GiB nw-mn405-rs64 native-ab-e10d1a346-nw1119f60 (torch 2.16.0.dev20261112 + pytorch#203334, #203534)
this PR Llama 3 405B, b3 seq 8192, 10 steps 10/10 100.07 s (−1.28%) 94.72 GiB nw-a3405-rs64 (window r-875a2) native-ab-e10d1a346-nw1119f60 (torch 2.16.0.dev20261112 + pytorch#203334, #203534)

Tests (proxy torch = 2.16.0.dev20261112 + the merged pytorch#203334 and #203534 commits, torch_tpu main e10d1a346, 8 v6e; stock nightly 2.16.0.dev20261120 (image native-ab-e10d1a346-nw1120tn): 8/8 test modules pass at head d53dffe891):

  • CPU (test_scan_remat_policy, test_layer_stack, test_tpu_memory_policy, test_tpu_graph_trainer_config, test_tpu_host_offload, test_fence_scan_segments): all pass.
  • TPU, 8 chips: test_layer_stack_distributed 11/11, test_tpu_host_offload_distributed 3/3.
  • 8 chips vs main, proxy torch: 8B default and Qwen3 MoE proxy loss + grad norm 15/15, same step program (8B: 0 HLO lines differ; MoE: instruction numbering only), same step time and XLA peak; MoE scan off 0 lines. Attention saved, runtime memory: at step 15: all layers 27.73 GiB, last 8 layers 25.41 GiB, last 8 layers with offload 21.11 GiB (loss + grad norm 15/15 equal to last 8 without offload).

Results, 8 v6e chips, image native-ab-22d846b, libtpu 0.0.51, 30 steps, vs main on the same torch (11/05-11/06, older base; proxy-torch re-run above; stock nightly, this PR's head: attention in the last 8 layers trains 15 steps, 2.880 s, XLA peak 12.03 GiB):

Arm Loss + grad norm Step HLO Step time Memory
llama3_8b_scan seq 8192 b2, default same 30/30 0 of 5,762 lines differ 2.90 s (main 2.88) 7.74 GiB both
same, attention saved in all 32 layers same as main's default 30/30 = #154's attention arm 2.67 s (−7.3%) 13.21 GiB
same, attention in the last 16 same as main's default 30/30 2 segments, fenced 2.775 s (−3.6%) 11.23 GiB
Qwen3 MoE debug model on scan (debugmodel_moe, global aux loss), default same 30/30 0 of 22,252 lines (after renumbering) 2.575 s (main 2.58) 4.47 GiB both
  • Default: same program as main, so the 0.7% gap is noise.
  • MoE row: the expert counts are still saved. The step has one f32[8,64] counts all-reduce (8 layers x 64 experts), which XLA moves out of the forward loop; the backward loop has none. Same as main.
  • Last 16: fence_scan_segments: fenced 2 scan boundaries (one per direction). The host stack bf16[32,16384,4096] becomes two bf16[16,16384,4096].

64 v7x chips (128 ranks), qwen3_moe_235b_scan b16, 15 steps, vs main. tok/s/rank = median of steps 3–15 without the profiled step 13. Run on an older head; the expert-count label has since moved into moe.py (metadata only).

Arm Loss + grad norm Step HLO tok/s/rank Memory (xprof peak)
main — — 2,611 49.81 GiB (83.69 GB)
this stack, default same 15/15 0 of 42,274 lines (after renumbering) 2,611.5 49.81 GiB (83.69 GB)
attention in the last 4 step 1 same, then drifts (step 15: 8.206 vs 7.905) 2 segments, fenced 2,613 (+0.08%) 57.91 GiB (92.45 GB)
attention in all 94 — — compile-time OOM: 128.20 G needed, 94.74 G HBM —

Segment gradients: each segment's weight gradient is f32 and covers only its rows, so backward pads both to [n_layers, ...] and adds them. Measured not at the memory peak: 8B last 8, 0 of 6 pad/add fusions in the XLA peak live set; 235B last 4 (64 chips, job jackoh-nw-sg235-0920), 0 of 10, live for about 5 instructions at the end of backward (at most 8.95 GiB live) against a 43.11 GiB peak, which sits in the last-4 backward where the saved attention stack is live.

Verdict: keep it opt-in. +3.6% at 8B for half the layers; at 235B, last 4 is flat on speed for +8 GiB, and all layers does not compile.

The scan body now runs under torch.utils.checkpoint with a selective
checkpoint policy that reads each op's remat_region: save the MoE expert
counts and compile.save_regions, recompute everything else, the FSDP
gather included. This replaces the hook that tagged the body's joint graph.

It needs a torch whose checkpoint tags nodes while scan traces its body,
even under the graph trainer's non-strict make_fx (PyTorch (a) + b').
scan_with_remat_policy raises on a torch without it.

The scan offload no longer finds the saved layer input by a layer_input
tag, which a SAC policy cannot set on a placeholder. It matches the body
output clone(carry placeholder) instead.
compile.save_last_n_layers now works with --compile.use-scan-layers. The
layers run as consecutive scans over slices of the same stacks, each with
its own save regions. fence_scan_segments puts an optimization barrier
between consecutive scans in the same direction, so one loop's weight
gathers do not overlap the previous loop's reduce-scatters. With no last-N
setting, or N >= n_layers, it is one scan, as before.
Conflicts with #153/#154's r2 fixes, resolved to this branch's SAC design:
- scan_remat_policy.py: keep scan_with_remat_policy; the r2 joint-graph
  tagger is gone with the window it ran in.
- tpu_host_offload.py: keep matching clone(carry); take r2's forward-scan
  count, its two error messages (reworded: no tag now) and the output-reader fix.
- tests: RealScanTest and the offload distributed test find the saved carry
  as clone(carry) instead of by the layer_input tag; r2's tagger-only tests
  and helpers are dropped. r2's unmatched-save-region check comes next.
Carries #153's r2 check ("Raise on an unmatched scan save region") over to
the SAC policy: the policy records each region it saves, and
scan_with_remat_policy raises after scan if a requested one never came up,
e.g. attention.inner_attention with SDPA instead of Splash.

Also ports r2's two gather tests: a gather inside a save region, and the real
spmd_types gather_slice, are both recomputed while the region around them is
saved.
Both are torch's job now:
- activation_memory_budget defaults to 1.0, where min-cut honours every tag.
  Upstream torchtitan never pins it; only MemoryBudgetAC sets it, from a user
  flag.
- pytorch#203534's HopGraphMinCutPartitioner enters preserve_node_meta()
  around the joint-graph trace, so the policy sees each op's region.

test_the_budget_is_restored becomes test_the_policy_holds_at_the_default_budget.
Every test in the file, including the non-strict make_fx one, passes without
either context.
Conflicts with #153's r2 fixes:
- config.py: keep this branch's message (save_last_n_layers is allowed).
- test_tpu_graph_trainer_config.py: keep r2's unknown-region case; drop
  r2's case that refuses save_last_n_layers under scan (this branch adds it).
- layer_stack.py: r2's has_moe wording plus this branch's last-N field.
# Conflicts:
#	torchtitan/experiments/tpu/graph_trainer/layer_stack.py
#	torchtitan/experiments/tpu/graph_trainer/scan_remat_policy.py
#	torchtitan/experiments/tpu/graph_trainer/tests/test_scan_remat_policy.py
#	torchtitan/experiments/tpu/graph_trainer/tests/test_tpu_graph_trainer_config.py
#	torchtitan/experiments/tpu/graph_trainer/tests/test_tpu_host_offload.py
The last-N gradient test becomes a second case of the scan-vs-loop
gradient test, the three _segments tests one table test, and the last-N
config test a case of the parametrized save_regions config test.
… segment

- config: `save_last_n_layers` under scan raises with `graph_split.enabled`,
  because the split program skips `fence_scan_segments`. A `scan_offload`
  name saved only in `save_last_n_layers` gets its own message. The scan
  model gets `save_last_n_layers` only under the policies that allow it,
  like `save_regions`.
- fence_scan_segments: when last-N splits the layers and the graph has
  scans, finding no pair to fence raises instead of running unfenced.
  Graphs with no scan (optimizer, grad norm) stay silent.
- scan offload: the saved-carry check runs per forward scan and names it;
  with last-N there is one forward scan per segment.
- Nits: log the last-N clause only when set; `frozenset()` in the
  `_segments` docstring; one assert for the fence's first value; drop the
  N=0 segments case the config already rejects.
…ts-1119

# Conflicts:
#	torchtitan/experiments/tpu/graph_trainer/config.py
#	torchtitan/experiments/tpu/graph_trainer/layer_stack.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant