Repository navigation
Conversation
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
force-pushed
the
jackoh/remat-1-regions
branch
from
November 5, 2026 14:14
04ad66d to
3fa4759
Compare
This was referenced 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.
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.
jack8558
marked this pull request as ready for review
November 24, 2026 13:07
jack8558
requested review from
alexanderb14,
jerryx99,
tanvibajpai,
vlasenkoalexey and
wconstab
November 24, 2026 13:08
…s-1119 # Conflicts: # torchtitan/experiments/tpu/graph_trainer/layer_stack.py
tanvibajpai
approved these changes
Nov 25, 2026
| self.assertIs(partitioners.min_cut_rematerialization_partition, partition) | ||
| self._check_same_grads(got, want) | ||
|
|
||
| def test_the_expert_parallel_count_exchange_is_recomputed(self): |
Contributor
There was a problem hiding this comment.
FYI: according to my agent, this exchange will need saving for EP under scan, and moe.routing needs the router top-k annotated.
Contributor
Author
There was a problem hiding this comment.
Agreed; it comes with scan + EP. #153 still rejects EP under scan.
tanvibajpai
reviewed
Nov 25, 2026
| if saved is not None: | ||
| saved.add(region) | ||
| return CheckpointPolicy.MUST_SAVE | ||
| return CheckpointPolicy.MUST_RECOMPUTE |
Contributor
There was a problem hiding this comment.
Suggestion from agent: match the non-scan policy in memory_policy.py:190 and return MUST_SAVE for torch.Tag.nondeterministic_seeded ops.
Contributor
Author
There was a problem hiding this comment.
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.
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
added a commit
that referenced
this pull request
Nov 26, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #27. Part of #29. Stacked on
main. First of 3 PRs:compile.scan_offload); attention save works with offloadcompile.save_last_n_layersunder scanRequires 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
scansplits 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:
So main works around them in
scan_remat_policy.py. During thescancall it forcesactivation_memory_budget=0.0(recompute everything) and swaps PyTorch'smin_cut_rematerialization_partitionfor a wrapper. The wrapper finds the MoE expert counts by op patterns and saves them.compile.memory_policy=tpu_selectiveis 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.checkpointwith a SAC policy that reads each op's region label: save the expert counts and any region listed incompile.save_regions, recompute everything else. No PyTorch internals are patched.MUST_RECOMPUTEwhen the body has counts)moe.expert_counts)attention.inner_attentiontpu_selectiveis refused under scan)compile.save_regions(opt-in)_all_reduce_expert_countsinmodels/common/moe.pywithannotate_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.Validation
64 v7x chips (128 ranks), this PR alone against main. PR arm =
cf63115522(this branch on 11/23, with main5a8b0e842cmerged in); main arm =5a8b0e842c. Both arms use one image: stock PyTorch nightly 2.16.0.dev20261120 (has pytorch/pytorch#203334 + #203534), torch_tpu maine10d1a346, libtpu 0.0.51. Step time = median of the steps after warmup, without the profiled step. Aftercf63115522, the PR changed only metadata, comments, a log message and tests (the expert-count label moved intomoe.py; test docstrings; new tests), added a clear error on PyTorch without the two fixes and a plain-scan path underno_grad(validation), and main34a0d8b49ewas merged in. At the current head4d1cd11b05, the 8-chip step HLO is identical to main34a0d8b49e(Status table).nw-mn235-rm64nw-a1235-rm64nw-mn405-rm64nw-a1405-rm64Status
4d1cd11b054d1cd11b05vs main34a0d8b49e, stock nightly