Skip to content

[TPU][Scan remat] 1/3: Pick the scan body's saved values by region, with a standard SAC policy - #153

Open
jack8558 wants to merge 16 commits into
mainfrom
jackoh/remat-1-regions
Open

jack8558 wants to merge 16 commits into
mainfrom
jackoh/remat-1-regions

Conversation

@jack8558

@jack8558 jack8558 commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #27. Part of #29. Stacked on main. First of 3 PRs:

PR What it does Depends on
#153 (this) 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
#222 (draft) compile.save_last_n_layers under scan #154

Requires PyTorch nightly ≥ 2.16.0.dev20261120, which has pytorch/pytorch#203334 (012eb2b6a70) and pytorch/pytorch#203534 (4378929563f). Not in PyTorch 2.15. There is no runtime version check: on an older torch, the scan body saves every layer's gathered weight.

Goal

Remove the scan remat workaround (the swapped min-cut partitioner and the op-pattern matching) and choose what the scan body saves with a standard SAC policy.

Background and problem

scan splits each layer into forward and backward while it traces, before GraphTrainer's memory policy runs, so that policy never sees the body's ops. Left alone, scan's min-cut saves the body's FSDP-gathered weight, which keeps every layer's full weight alive and erases scan's memory win.

A SAC policy on the body should fix this, but two PyTorch bugs blocked it:

  1. scan re-traces its body several times and dropped the node labels a policy reads (fixed by [HOP] Keep node meta when scan re-traces its body for autograd pytorch/pytorch#203334);
  2. under the graph trainer's non-strict tracing, SAC took its eager path and lost its tags (fixed by [HOP] Let SAC tag recompute nodes in a scan body under non-strict tracing pytorch/pytorch#203534).

So main works around them in scan_remat_policy.py. During the scan call it forces activation_memory_budget=0.0 (recompute everything) and swaps PyTorch's min_cut_rematerialization_partition for a wrapper. The wrapper finds the MoE expert counts by op patterns and saves them. compile.memory_policy=tpu_selective is refused under scan, so attention cannot be saved.

Proposal

Both fixes are in the nightly, so drop the workaround. Each scan step runs the body under torch.utils.checkpoint with a SAC policy that reads each op's region label: save the expert counts and any region listed in compile.save_regions, recompute everything else. No PyTorch internals are patched.

Value in the scan body main this PR
FSDP gather, untagged ops recomputed (budget 0, or MUST_RECOMPUTE when the body has counts) recomputed (policy)
MoE expert counts (moe.expert_counts) saved (op-pattern match) saved (policy)
attention.inner_attention cannot be saved (tpu_selective is refused under scan) saved if listed in compile.save_regions (opt-in)
policy = scan_body_policy(save_regions)          # MUST_SAVE for counts + save_regions, else MUST_RECOMPUTE
scan(lambda *a: checkpoint(body, *a, use_reentrant=False, context_fn=SAC(policy)), init, xs)
  • No PyTorch internals are patched. PyTorch #203334 keeps the labels through scan's re-traces. #203534 makes SAC tag the body under the graph trainer's non-strict tracing. Min-cut follows the tags at its default budget.
  • A requested save region that matches no op raises (e.g. SDPA instead of Splash).
  • The expert-count label is set on _all_reduce_expert_counts in models/common/moe.py with annotate_fn (an import, a two-line comment and the decorator: 4 lines). It is metadata only and changes nothing that runs, on TPU or elsewhere.
  • Docs: the TPU README (Option A) and the optimization guide say scan needs the nightly.
Lines Files
Code +206 / −292 8
Docs +6 / −2 2
Tests +215 / −153 4

Validation

64 v7x chips (128 ranks), this PR alone against main. PR arm = cf63115522 (this branch on 11/23, with main 5a8b0e842c merged in); main arm = 5a8b0e842c. Both arms use one image: stock PyTorch nightly 2.16.0.dev20261120 (has pytorch/pytorch#203334 + #203534), torch_tpu main e10d1a346, libtpu 0.0.51. Step time = median of the steps after warmup, without the profiled step. After cf63115522, the PR changed only metadata, comments, a log message and tests (the expert-count label moved into moe.py; test docstrings; new tests), added a clear error on PyTorch without the two fixes and a plain-scan path under no_grad (validation), and main 34a0d8b49e was merged in. At the current head 4d1cd11b05, the 8-chip step HLO is identical to main 34a0d8b49e (Status table).

Arm Model Loss + grad norm match Step time Compiled peak memory Job Image
main Qwen3-235B, 15 steps — 24.82 s 77.77 GiB nw-mn235-rm64 native-ab-e10d1a346-nw1124rm (torch 2.16.0.dev20261120)
this PR Qwen3-235B, 15 steps 15/15 24.83 s (+0.04%) 77.77 GiB nw-a1235-rm64 native-ab-e10d1a346-nw1124rm (torch 2.16.0.dev20261120)
main Llama 3 405B, b3 seq 8192, 10 steps — 100.87 s 94.72 GiB nw-mn405-rm64 native-ab-e10d1a346-nw1124rm (torch 2.16.0.dev20261120)
this PR Llama 3 405B, b3 seq 8192, 10 steps 10/10 100.26 s (−0.60%) 94.72 GiB nw-a1405-rm64 native-ab-e10d1a346-nw1124rm (torch 2.16.0.dev20261120)

Status

Check Result
CPU tests (layer stack, scan remat policy, config, host offload, memory policy), stock nightly 2.16.0.dev20261120, head 4d1cd11b05 255 pass in 5 modules, 0 failures
Llama 3 8B, 8 v6e, default recipe, 15 steps, head 4d1cd11b05 vs main 34a0d8b49e, stock nightly loss + grad norm 15/15; step HLO 0 of 5,731 lines differ; 7 all-gathers per backward body both; 2.930 s both; XLA peak 16.35 GiB both
Opt-in attention save, 8B (full stack, 11/19) 2.76 s vs 2.93 s main default (−5.8%); XLA peak 19.56 vs 16.35 GiB; trains 15 steps

The scan body is partitioned inside scan's autograd, so GraphTrainer's
memory policies never see it. Tag its joint graph from remat_region
annotations instead: the FSDP gather and everything unannotated is
recomputed, the MoE expert counts and selected save regions are saved.

- Keep node meta through scan's two body re-traces (runtime patch of
  create_bw_fn and functionalize in the partitioner, until torch does it).
- Annotate the in-body gather (fsdp.gather) and both splash forwards
  (attention.inner_attention). Wrap the expert-count all-reduce as
  moe.expert_counts from TPU code at setup, so models/common/moe.py is
  untouched.
- Replace the op-pattern count matching and the budget-0 window.
- Allow tpu_selective with attention.inner_attention on the scan lane.
@jack8558
jack8558 force-pushed the jackoh/remat-1-regions branch from 04ad66d to 3fa4759 Compare November 5, 2026 14:14
@jack8558 jack8558 changed the title Pick the scan body's saved values by region [TPU][Scan remat] 1/4: Pick the scan body's saved values by region Nov 5, 2026
Conflicts:
- graph_trainer/scan_fsdp.py: keep main's spmd_types gather body as
  _gather_slice; gather_slice still wraps it in the fsdp.gather region.
- kernels/tokamax_splash_attention.py: take main's imports (jaxtyping
  workaround removed); add the remat_regions import at the top.

remat_regions moved to components/ on main; point our imports there.
- A save_regions entry that tags no forward node in the scan body now
  raises, naming the region, as the non-scan policy does.
- fsdp.gather nodes are always MUST_RECOMPUTE, whatever tag they came
  with. Other pre-existing save tags raise; recompute tags are kept.
- Scan validation message names save_last_n_layers; dense models' log
  line no longer mentions MoE counts.
- Tests: unmatched region, gather inside a save region, pre-tagged
  nodes, and two scan config errors.
gather_slice now gathers through spmd_types (main #152). The test runs the
real gather_slice inside a save region in a scan body and checks that its
forward collectives carry fsdp.gather, are tagged recompute, and that the
backward re-gathers.
jack8558 added a commit that referenced this pull request Nov 13, 2026
Brings in origin/main and #153's review fixes.

Conflicts (same resolution as the #153 fix needed before):
- graph_trainer/config.py: the scan error message names both
  tpu_selective policies and save_last_n_layers.
- graph_trainer/scan_remat_policy.py: docstring keeps the layer_input
  paragraph and the fsdp.gather paragraph.
- graph_trainer/tpu_memory_policy.py, tests/test_scan_remat_policy.py:
  keep both imports, at main's components/remat_regions path.

Also point tpu_host_offload and its tests at components/remat_regions.
…ches

The scan body now runs under torch.utils.checkpoint with a selective
checkpoint policy keyed on each op's remat_region: save the MoE expert
counts and compile.save_regions, recompute everything else (the FSDP
gather included). This replaces the joint-graph tag pass and the window
that swapped min-cut, create_bw_fn and torch.func.functionalize.

It needs pytorch/pytorch#203334 (scan keeps node meta in its re-traces)
and #203534 (SAC tags a scan body under non-strict tracing). On an older
torch the first trace raises with the PyTorch PRs and the found version.

Docs: the TPU README notes that scan layers need the nightly (Option B)
until PyTorch 2.16; the optimization guide no longer says the body is
fully recomputed.

Tests: merge the default-budget test into the save-region test, drop the
toy gather test (the real gather test catches all it catches), and make
the unknown-region test match its own error.
@jack8558 jack8558 changed the title [TPU][Scan remat] 1/4: Pick the scan body's saved values by region [TPU][Scan remat] 1/3: Pick the scan body's saved values by region, with a standard SAC policy Nov 23, 2026
The scan remat policy recomputes every op that is not in a save region,
so the label only mattered for a gather run inside a save region.
Production never does that: gather_slice runs in the scan body before
the layer, and the Splash regions wrap only the kernel call. Remove the
FSDP_GATHER constant, the wrapper in gather_slice, and the test for
that case.
…t at runtime

The TPU scan remat policy saves the region "moe.expert_counts". It was set by
replacing moe._all_reduce_expert_counts at setup from TPU code. Put the label
on the function itself with annotate_fn: metadata only, no runtime swap.
…s-1119

# Conflicts:
#	torchtitan/experiments/tpu/graph_trainer/layer_stack.py
self.assertIs(partitioners.min_cut_rematerialization_partition, partition)
self._check_same_grads(got, want)

def test_the_expert_parallel_count_exchange_is_recomputed(self):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI: according to my agent, this exchange will need saving for EP under scan, and moe.routing needs the router top-k annotated.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed; it comes with scan + EP. #153 still rejects EP under scan.

if saved is not None:
saved.add(region)
return CheckpointPolicy.MUST_SAVE
return CheckpointPolicy.MUST_RECOMPUTE

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion from agent: match the non-scan policy in memory_policy.py:190 and return MUST_SAVE for torch.Tag.nondeterministic_seeded ops.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not needed: scan's partitioner already saves RNG ops (_mark_rng_ops_as_must_save, pytorch#203334). A dropout test shows exact grads, with no bernoulli in backward.

- scan_remat_policy.py: say the mutation flag covers the whole body, and
  why that is safe (scan functionalizes the body to build its backward).
- layer_stack.py: the scan log says expert counts are saved only if
  all-reduced.
- test_tpu_memory_policy.py: test that tpu_selective tags the outer graph
  like `full` under scan. It fails if that branch is removed.
@jack8558 jack8558 added the pull ready Signals Copybara to import this PR into Google3 label Nov 26, 2026
scan_with_remat_policy raises a clear error when PyTorch lacks
pytorch/pytorch#203334 and #203534, instead of silently keeping every
layer's gathered weights. Under no_grad (validation) it runs plain scan:
checkpoint skips the policy without grad, so the save-region check would
raise "matched no op".
jack8558 added a commit that referenced this pull request Nov 26, 2026
@jack8558 jack8558 added pull ready Signals Copybara to import this PR into Google3 and removed pull ready Signals Copybara to import this PR into Google3 labels Nov 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pull ready Signals Copybara to import this PR into Google3

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Scan body ignores activation-checkpoint tag

2 participants