Repository navigation
Conversation
95844b8 to
ed9c993
Compare
b1e304f to
903a147
Compare
ed9c993 to
86e2944
Compare
903a147 to
e47afea
Compare
#5674) Part **1/n** of the Kimi K3 / Dist-MoE training stack. Based on `main`: the review diff contains only this feature. human notes: previously: `distributed/utils.py::init_distributed()` passes `CommConfig.init_timeout_seconds` to `torch.distributed.init_process_group()` so the world group has, say, 30 minutes timeout. now, that remains unchanged. Additionally, `TrainingEngine._initialize_distributed_runtime()` calls `set_pg_timeouts()` after `ParallelismContext.from_config()`, so the tracked mesh subgroups get the configured timeout before model/FSDP/optimizer initialization. this also covers the RL trainer. without this pr, independently created NCCL subgroups can still use the default 10-minute timeout even though we configured 30 minutes. the existing switch to `train_timeout_seconds` after the first step is unchanged. ## Why The world process group receives `comm.init_timeout_seconds`, but mesh subgroups created later do not inherit it. They can retain the backend-default startup timeout through model initialization and the first update. Example: with `CommConfig(init_timeout_seconds=1800)`, the world group uses 1,800 seconds but a later NCCL subgroup can use its 600-second default. This change applies the configured startup budget to the groups tracked by `ParallelismContext` before model/FSDP/optimizer initialization. ## What changed - Call the existing `set_pg_timeouts()` helper immediately after `ParallelismContext.from_config()` in the shared training engine. - Apply the same call in the TorchFT runtime override. - Preserve the unconditional post-first-step switch to `train_timeout_seconds`, including fake backends. - Add no helper, configuration field, or test. The deleted forwarding-only mock test is not coverage for the current code. ## User-facing changes | Configuration | Before | After | | --- | --- | --- | | `init_timeout_seconds=1800` | World: 1,800 s; tracked NCCL mesh groups may use 600 s during startup. | World and tracked mesh groups: 1,800 s during startup. | | Default `init_timeout_seconds=300` | World: 300 s; tracked NCCL mesh groups may use 600 s. | World and tracked mesh groups: 300 s during startup. | | After the first update | Existing switch to `train_timeout_seconds`. | Unchanged. | Groups created separately outside the context's tracked mesh map, including optimizer-specific communicators, are not covered by this call. ## Numerics No model math, parameter layout, gradient policy, or checkpoint mapping changes. The existing helper adds one startup barrier/device synchronization; there is no new per-update synchronization. ## Testing Rebased onto upstream `ad7a9937b5e57ccadebbb98b3eb14ff139ceb2b3`. The feature diff is unchanged: ten added lines in the shared engine and TorchFT override. ```bash CUDA_VISIBLE_DEVICES='' python -m pytest -q -p no:cacheprovider --tb=short \ tests/unit_tests/cpu/test_trainer.py \ tests/unit_tests/cpu/distributed/test_distributed_utils.py ``` Result: **76 passed**. These existing CPU tests do not directly verify real NCCL subgroup timeout values. ## Known issues / landing gates All non-type pre-commit checks passed in the preceding review. The three Pyrefly failures were independently reproduced on unchanged upstream: missing `torch_checkpointing.checkpoint_writer.CallbackArgs`, its callback signature mismatch, and optional `video.stream.time_base` multiplication. No unrelated source or dependency workaround is included. ## Stack Bottom of stack; based on `main`. Next: [#5675](#5675). <details> <summary>Full draft stack — review and land in this order</summary> | Position | Draft PR | | --- | --- | | 1/n | [#5674 — [distributed] 1/n Apply initialization timeouts to mesh process groups](#5674) | | 2/n | [#5675 — [fsdp] 2/n Expose explicit backward-prefetch policy](#5675) | | 3/n | [#5676 — [fsdp] 3/n Support layer-scoped CPU offload](#5676) | | 4/n | [#5677 — [optim] 4/n Bound optimizer memory ownership and allocation lifetimes](#5677) | | 5/n | [#5678 — [dist_muon] 5/n Support CP and TP storage-to-compute layouts](#5678) | | 6/n | [#5679 — [profiler] 6/n Preserve failure context and merge CUDA-graph streams](#5679) | | 7/n | [#5680 — [kda] 7/n Preserve graph metadata and expose chunk-kernel options](#5680) | | 8/n | [#5681 — [cp] 8/n Add configurable graph-friendly Ulysses transport](#5681) | | 9/n | [#5682 — [compile] 9/n Compile MLA assembly and router postprocessing](#5682) | | 10/n | [#5683 — [pp] 10/n Make cache release and FSDP chunk lifetimes explicit](#5683) | | 11/n | [#5684 — [dist_moe] 11/n Enable Kimi K3 SiTU-GLU training and pipeline lifecycle](#5684) | | 12/n | [#5685 — [moe] 12/n Add opt-in shared-expert CUDA stream overlap](#5685) | | 13/n | [#5686 — [ac] 13/n Add block-scoped activation retention](#5686) | </details> After the preceding PR lands, rebase the remaining suffix onto updated main and retarget its next bottom PR to main. Keep the rest stacked; no automatic landing is requested.
86e2944 to
5e73b43
Compare
e47afea to
bcdafc8
Compare
…tion (#5681) Part **8/n** of the Kimi K3 / Dist-MoE training stack. Based directly on `main`; this PR can land independently of the remaining stack. human notes: fix the nccl ulysses safeguard that uses `Ulysses.Config` instead of `UlyssesInnerAttention.Config`. ## Why The existing NCCL Ulysses safeguard detects `UlyssesInnerAttention.Config`. Compact MLA, Ulysses KDA, and Ulysses GDN instead inherit directly from `Ulysses.Config`, so these models miss the existing protection on affected NCCL versions. Example: `UlyssesMLAAttention.Config` does not inherit from `UlyssesInnerAttention.Config`. On NCCL 2.32.2 the old traversal leaves graph registration enabled; traversing the common base selects the existing safeguard. The NCCL fix and version boundary are unchanged: [NVIDIA/nccl#2362](NVIDIA/nccl#2362). ## What changed - Match the common `Ulysses.Config` base in the existing safeguard. - Add one isolated GDN regression for a subclass outside the old hierarchy. Full attention uses K/V all-gather in this test, so it cannot accidentally trigger the old safeguard. - Keep the existing version-boundary and unsupported-runtime tests rather than repeating them for each backend. There are only two production-line replacements. Native attention and communication paths are unchanged; no new option or dependency is introduced. ## User-facing changes | Before | After | | --- | --- | | The safeguard detects only full-attention Ulysses wrappers. | It also detects compact MLA and linear-attention Ulysses wrappers. | | NCCL >= 2.32.3, non-CUDA, and fake runtimes skip the safeguard. | Unchanged. | ## Numerics No tensor computation, collective implementation, parameter, or checkpoint layout changes. This extends an existing pre-initialization runtime policy. The CPU checks below do not claim fresh end-to-end training or throughput acceptance. ## Testing Fresh validation against upstream `73c4ebdac57de0d89bb20d5dfabed340449c8b0d`: - **91 CPU tests and 84 subtests passed**, with no deselection. - **Fresh negative control:** the retained GDN regression fails on untouched main because `NCCL_GRAPH_REGISTER` remains unset; it passes with this change. - All non-type-checking pre-commit hooks passed over all files. ```bash CUDA_VISIBLE_DEVICES='' python -m pytest -q -o addopts='' -p no:cacheprovider --tb=short \ tests/unit_tests/cpu/distributed/test_ulysses_nccl.py \ tests/unit_tests/cpu/models/common/test_cp_attention.py \ tests/unit_tests/cpu/config/test_context_parallel_validation.py ``` The type error at unchanged `torchtitan/components/data/multimodal/utils/video.py:114` independently reproduces on untouched upstream `73c4ebdac`. This PR does not change that file. Not verified: a fresh real multi-rank CP/CUDA-graph training run. ## Stack This PR is directly based on `main` and does not require 4/n-7/n. The other source branches are unchanged by this update. 1/n (#5674) is merged; 2/n (#5675) and 3/n (#5676) are closed. | Position | PR | | --- | --- | | 4/n | [#5677](#5677) | | 5/n | [#5678](#5678) | | 6/n | [#5679](#5679) | | 7/n | [#5680](#5680) | | 8/n | [#5681](#5681), independent on main | | 9/n | [#5682](#5682) | | 10/n | [#5683](#5683) | | 11/n | [#5684](#5684) | | 12/n | [#5685](#5685) | | 13/n | [#5686](#5686) | | 14/n | [#5793](#5793), full-scale MXFP8 recipes |
5e73b43 to
ea78b7b
Compare
bcdafc8 to
bded89c
Compare
ea78b7b to
b117ce9
Compare
28b4b25 to
82afd34
Compare
b117ce9 to
3157b3a
Compare
Part **4/n** of the Kimi K3 / Dist-MoE training stack. Based directly on `main`: the review diff contains only the optimizer-memory changes below. human notes: 1. release distmuon's gpu redistribution and compute scratch after each eager optimizer update by default. 1) in full eager training, later fwd/bwd can reuse the released memory. 2) if one rank has two eager optimizers (fwd/bwd can use cudagraph), like when vpp=2, their scratch allocations can reuse memory instead of remaining simultaneously resident. keep tensor metadata and cpu scratch, and release unused ns intermediates earlier without changing the math. 2. the flow is: reserve shapes/dtypes/device, and use allocate for setting real storage, and use resize_(0) to free the storage. 3. remove some ns step intermediate tensors without changing math. ## Why DistMuon retains exchange and compute scratch between updates, even when eager forward/backward or a second eager optimizer could reuse that memory. Dropping scratch allocated on the transfer stream does not let the caller stream reuse its cached blocks. Prepare the buffer capacities once, then regrow and release accelerator backing storage on the caller stream. Keep CPU backing storage allocated between updates to avoid repeated host allocations. Tensor objects, shapes, bucket plans, communication streams/events, parameters, and optimizer state remain alive. This is the default behavior; no new config knob is added. **Example.** ```python # Forward/backward may be eager or CUDA-graphed; optimizer updates are eager. chunk0_optimizer.step() # Regrow cached scratch, update, resize storage to zero. chunk1_optimizer.step() # Can reuse released caller-stream allocator blocks. # With one optimizer, later eager forward/backward can reuse those blocks too. # A separate forward/backward CUDA-graph pool cannot reuse normal-pool scratch. ``` ## What changed - Keep the four scratch tensor types and their metadata; prepare capacities at construction or checkpoint replanning, not before every update. - Regrow released backing storage with `untyped_storage().resize_(size)` on the current caller stream. Preserve the existing transfer/caller event ordering, then release accelerator storage with `resize_(0)` after a successful eager update. CPU storage stays allocated; `allocate()` already skips correctly sized storage. - Make storage release the default rather than introduce a persistence knob. Because every storage lifetime begins and ends on its caller stream, the old persistent-buffer caller-tracking set is unnecessary. - Release obsolete Newton-Schulz intermediate references after their last use. Arithmetic, compute dtype, and update ordering do not change. The net diff touches the runtime, DistMuon implementation, and one CPU runtime regression. Existing optimizer/checkpoint tests exercise the new default without new distributed CI variants. There are no trainer/container changes, synthetic all-to-all warmups, new dependencies, or communicator/CTA changes. ## User-facing behavior | Before | After | | --- | --- | | Accelerator scratch tensor objects and backing storage remain resident between updates | Tensor objects persist; accelerator backing storage is released after each eager update | | CPU scratch remains allocated between updates | Unchanged; the release loop skips CPU tensors | | Several eager optimizers each retain their scratch arena | Sequential eager updates can reuse caller-stream scratch allocations | | Forward/backward graph pools are separate from optimizer scratch | Unchanged; this PR does not implement graph-pool sharing | ## Numerics Compared with the `main` parent `22047b18a`: - GPU 0: FP32 and BF16 parameters each produced bitwise-identical loss, gradients, and updated weights for ten updates, with both eager and CUDA-graphed forward/backward. Each run reloaded an optimizer checkpoint after update five. - Real two-rank CPU/Gloo redistribution: owned, uneven mixed-block, and expert matrices produced bitwise-identical updated weights for ten updates and a checkpoint reload. The owned matrix also matched `torch.optim.Muon` exactly. Scratch tensor identities survived updates/reloading; CPU backing storage now stays allocated between updates, matching the host-buffer behavior on `main`. - A standalone one-rank optimizer-capture smoke test completed ten exact-parity replays. This is not multi-rank optimizer-graph validation; the Titan optimizer container still does not enable DistMuon capture. Fresh follow-up checks against the previous PR head `a4fada369` also produced exact FP32/BF16 eager and graphed loss/gradient/weight parity, and exact two-rank Gloo updates. An actual single-GPU FSDP2 `CPUOffloadPolicy` run with `ns_device=None` completed ten updates and a checkpoint reload: a 16-to-16-to-8 linear model (384 weights, eight input rows) kept its 1,024-byte host scratch allocated and reused its pointer between replans, with bitwise-identical loss, gradients, and weights. This is correctness/lifecycle evidence, not an offload throughput or host-allocation-cost measurement. Fresh multi-rank NCCL validation has not been rerun because only GPU 0 was available. ## Memory evidence The following accelerator-only measurements predate the CPU-retention correction; the correction does not change the accelerator release branch. This is a synthetic single-GPU GB300 allocator benchmark, not a Kimi K3 training run. BF16 forward/backward uses a bias-free 1024-to-8192 linear layer (8.39M weights) with 4096 input rows. Each eager DistMuon instance updates a separate 29.36M-parameter workload (14.68M local parameters on shape-only fake DP=2), with FP32 parameters/gradients/momentum, BF16 compute, and one Newton-Schulz iteration. The table covers ten updates after two eager warmups; graph cases additionally capture/replay forward/backward before measurement. Values are PyTorch allocator counters, not total device HBM. FakePG is used for shapes here, not distributed numerical evidence. | Forward/backward | Eager optimizers | Peak allocated: parent -> PR | Steady reserved: parent -> PR | | --- | ---: | ---: | ---: | | Eager | 1 | 672 -> 528 MiB | 722 -> 594 MiB | | Eager | 2 | 984 -> 696 MiB | 1058 -> 774 MiB | | CUDA graph | 1 | 424 -> 420 MiB | 788 -> 800 MiB | | CUDA graph | 2 | 736 -> 588 MiB | 1124 -> 980 MiB | Each optimizer retains 144 MiB of scratch capacity metadata but zero backing storage after an update, versus 144 MiB resident on the parent. All cases had zero allocator retries. The single-optimizer graph case does not show meaningful scratch-related peak savings; the two-optimizer case demonstrates normal-pool scratch reuse, not graph-pool sharing. A separate setup-call census over ten updates/two optimizers recorded zero `reserve_buffers` and `_reserve_tensor` calls in the new steady loop, versus 20 and 180 calls in the previous transient implementation. Storage allocation/free operations still occur. No full-scale HBM or throughput gain is claimed. ## Testing - **123 CPU tests passed** for redistribution, optimizer state/configuration, trainer, and accelerator graphs. The one added CPU regression checks all four scratch buffer roles for ten release/allocate cycles, verifying retained host capacity, pointers, and contents; it fails cleanly against the previous PR head. - The supplementary GPU-0, FSDP2 CPU-offload, and real Gloo probes above passed; no new multi-GPU CI variants were added. - All non-type-checking pre-commit hooks passed across the repository. Both changed production files and the CPU regression pass focused Pyrefly. - Full-project Pyrefly reports the same single optional-value error at `components/data/multimodal/utils/video.py:114` on both this patch and the independently checked `main` parent. No unrelated fix or suppression is included. ```bash CUDA_VISIBLE_DEVICES='' python -m pytest -q \ tests/unit_tests/cpu/distributed/flex_shard \ tests/unit_tests/cpu/components/optim/test_optimizer_param_groups.py \ tests/unit_tests/cpu/components/optim/test_optim.py \ tests/unit_tests/cpu/test_trainer.py \ tests/unit_tests/cpu/distributed/test_accelerator_graph.py SKIP=pyrefly-check pre-commit run --all-files pyrefly check torchtitan/distributed/flex_shard/_optimizer_reshard_runtime.py \ torchtitan/distributed/flex_shard/dist_muon.py \ tests/unit_tests/cpu/distributed/flex_shard/test_optimizer_reshard_runtime.py ``` ## Stack Based directly on `main`. Next: [#5678](#5678). <details> <summary>Draft stack — review and land in this order</summary> 1/n (#5674) and 8/n (#5681) are merged. 2/n (#5675) and 3/n (#5676) are closed because the chosen full-scale recipes use neither the prefetch-disable policy nor selected-layer CPU offload. They are no longer in the stack. | Position | Draft PR | | --- | --- | | 4/n | [#5677 — [distmuon] 4/n Release scratch storage between optimizer updates](#5677) | | 5/n | [#5678 — [dist_muon] 5/n Support CP and TP storage-to-compute layouts](#5678) | | 6/n | [#5679 — [profiler] 6/n Preserve active failures during shutdown](#5679) | | 7/n | [#5680 — [attention] 7/n Keep linear-attention graph metadata replayable](#5680) | | 8/n, merged | [#5681 — [cp] 8/n Apply the Ulysses NCCL safeguard to compact and linear attention](#5681) | | 9/n | [#5682 — [compile] 9/n Compile MLA assembly and router postprocessing](#5682) | | 10/n | [#5683 — [pp] 10/n Add once-only startup cache release](#5683) | | 11/n | [#5684 — [dist_moe] 11/n Enable Kimi K3 SiTU-GLU training and pipeline lifecycle](#5684) | | 12/n | [#5685 — [moe] 12/n Add opt-in shared-expert CUDA stream overlap](#5685) | | 13/n | [#5686 — [ac] 13/n Add block-scoped activation retention](#5686) | | 14/n | [#5793 — [recipes] 14/n Add full-scale Kimi K3 MXFP8 recipes](#5793) | </details> After this PR lands, rebase the remaining suffix onto updated main and retarget its next bottom PR to main. Keep the rest stacked; no automatic landing is requested.
82afd34 to
3cb136a
Compare
09b72fb to
f9d0d38
Compare
|
@claude review |
There was a problem hiding this comment.
Verdict: Request changes -- block keys are matched relative to whatever module apply gets, so on multimodal models the same layers.<id> key also adds saves to the encoder block with that index.
What this PR does. It adds ActivationRematConfig.block_save_regions: dict[str, list[str]]. Each key is an exact layers.<id> and each value is a list of region patterns, which apply appends to save_regions for that block only. recompute_regions still wins. The Full and Default presets reject the field. Keys keep their meaning under PP because split_module deletes entries from the ModuleDict without renumbering the rest. The consumer is the K3 recipe in draft #5793.
Example.
ActivationRematConfig(
save_regions=["feed_forward.shared_experts.*"],
block_save_regions={"layers.5": ["attention.inner_attention"]},
)
# Intended: decoder layers.5 also saves attention.inner_attention.
# Actual on qwen3_5 / kimi_k2_7 / muse_spark / kimi_k3 with a vision encoder:
# model.layers.5 -> extra save (intended)
# model.vision_encoder.layers.5 -> extra save too, if its block declares a
# matching region (not intended, not reported)Must fix
torchtitan/distributed/activation_remat.py:163-- block key lookup is relative to the module passed toapply, which also runs on encoders (kimi_k3/model.py:274,common/multimodal.py:94). This contradicts "original model FQN" in the docstring and REMAT.md. Fix: pass the module's FQN intoapply(encoder call sites pass their attribute name), or applyblock_save_regionsonly for the root model and document that. Details inline.
Should consider
torchtitan/distributed/activation_remat.py:46-- "every pipeline stage" should read "every block". This paragraph also repeats the field docstring.torchtitan/distributed/REMAT.md:91-- drop the Dist-MoE arena sentence (and its copy in the field docstring atactivation_remat.py:70). It is not specific to this feature.
Questions
- #5793, the consumer, still carries the earlier glob version of this code. Its
tests/unit_tests/cpu/distributed/test_activation_remat.pyuses"layers.8?"and"layers.*"keys, which the__post_init__added here rejects. Will #5793 be rebased onto this version so its activation-remat file and those tests are dropped?
Details
- Gate: there is a concrete consumer (#5793's
kimi_k3recipe, which saves the KDA core and projections in one late KDA layer per physical PP rank), and the change is small (+29 logic lines). It builds on the torch_remat path indirection.mdand is additive with global saves. An exact-key dict is the smallest form; a glob or per-block full-policy variant would add surface with no consumer. - PP: all in-repo models use
ModuleDictforlayers(common/decoder.py:252). TheModuleListbranch ofsplit_modulerenumbers indices, but no current model uses it. - The same relative-FQN ambiguity already exists in the
base_fqnpassed tosaved_tensors_hooksandremat.checkpoint(region_name=...). Fixing the lookup with a module FQN would fix those names too. - Tests: the new test folds into the existing GPU file, and the preset row extends an existing subTest. Both guard silent no-op and silent-acceptance regressions. No extra test is needed for the encoder fix beyond one assertion in the existing test, if the prefix approach is chosen.
Not verified: whether each multimodal encoder's blocks declare a region named exactly like the decoder pattern a recipe uses (e.g. attention.inner_attention). If none do, the collision only shows up for patterns that both share. A maintainer still needs to review.
| base_fqn = f"layers.{layer_id}" | ||
| transformer_block.configure_remat_regions( | ||
| self.save_regions, self.recompute_regions | ||
| [*self.save_regions, *self.block_save_regions.get(base_fqn, [])], | ||
| self.recompute_regions, | ||
| ) |
There was a problem hiding this comment.
base_fqn is relative to the module apply is called on, not the root model. The same policy object is also applied to encoders: activation_remat.apply(self.vision_encoder) in torchtitan/models/kimi_k3/model.py:274, and activation_remat.apply(encoder) for every multimodal encoder in torchtitan/models/common/multimodal.py:94 (qwen3_5, kimi_k2_7, muse_spark). Those encoders also key their blocks layers.<id>. So {"layers.5": ["attention.inner_attention"]} adds the save to decoder layer 5 and also to vision_encoder.layers.5 if that block has a matching region. Nothing reports this, and it spends memory the user didn't budget for. It also contradicts the docstring and REMAT.md, which say the keys are "original model FQNs".
Smallest fix: give apply the FQN of the module it is given, e.g. apply(model, *, module_fqn: str = "", ...), and build fqn = f"{module_fqn}.layers.{layer_id}" (or layers.{layer_id} at the root) for the lookup. The two encoder call sites pass their attribute name, and the __post_init__ regex accepts an optional <encoder>. prefix. If encoder blocks are out of scope, the other option is to apply block_save_regions only for the root model and say so in the docstring. Either way, the "original model FQN" wording then matches what the code does.
| Save-region names are relative to a transformer block. Use | ||
| ``block_save_regions`` to retain additional regions only in selected | ||
| blocks, for example to spend a small activation budget on an expensive | ||
| attention kernel without retaining it in every pipeline stage. |
There was a problem hiding this comment.
"without retaining it in every pipeline stage" is inaccurate: a global save applies to every block, and pipeline stages don't come into it. This also repeats the block_save_regions docstring a few lines below. Suggest keeping one sentence here:
| Save-region names are relative to a transformer block. Use | |
| ``block_save_regions`` to retain additional regions only in selected | |
| blocks, for example to spend a small activation budget on an expensive | |
| attention kernel without retaining it in every pipeline stage. | |
| Save-region names are relative to a transformer block and apply to every | |
| block; ``block_save_regions`` adds saves to selected blocks only. |
| stages. Retained tensors follow the block's saved-tensor hooks, described below. | ||
| By default they consume device memory independently of backend-owned expert | ||
| activation arenas; measure that cost before enabling extra saves. |
There was a problem hiding this comment.
This sentence brings the Dist-MoE arena into a generic remat doc, and "By default" has no stated alternative. Retained tensors costing device memory is true of every save region, not just block-scoped ones. The same goes for "independent of backend-owned activation arenas" in the field docstring (activation_remat.py:70). Suggest dropping both, and keeping only "Retained tensors follow the block's saved-tensor hooks, described below."
Allow selected block regions to retain activations under remat. Preserve global recompute precedence, original pipeline layer FQNs, fixed-preset validation, and saved-tensor-hook ownership.
f9d0d38 to
7430d8a
Compare
|
@claude review again |
There was a problem hiding this comment.
Verdict: Approve -- the encoder key collision from the last review is fixed: apply now takes module_fqn, and both encoder call sites pass it. A maintainer still needs to review, since this touches torchtitan/distributed/.
Example.
cfg = ActivationRematConfig(
save_regions=[],
block_save_regions={"layers.5": ["attention.inner_attention"]},
)
# Before: model.layers.5 and model.vision_encoder.layers.5 both gained the save.
# Now: only model.layers.5 does; the encoder block needs the key
# "vision_encoder.layers.5".Earlier review items
- Must fix, encoder blocks matched by decoder keys (
activation_remat.py:172): resolved.block_fqnis prefixed withmodule_fqn, andmultimodal.py:94andkimi_k3/model.py:274pass the encoder attribute name. That covers every encoderapplycall site in the repo (qwen3_5, kimi_k2_7, kimi_k3, muse_spark, muse_glimmer). Root-model callers (base/model.py:171, transformers backend, tests) keep"". The__post_init__regex accepts the optional single-segment<encoder>.prefix, which matches everymultimodal_encoder_fqnsentry in the repo. The new test checks that the encoder does not match the decoder key. - Class docstring "every pipeline stage" wording: resolved.
- Dist-MoE arena sentence in REMAT.md and the field docstring: resolved, removed from both.
- Question about #5793 carrying the glob version: answered in the description (#5793 will be rebased and drop its copy and tests).
Should consider
torchtitan/distributed/REMAT.md:83-- one line is left unwrapped. The suggested reflow is inline.
Details
- An encoder prefix with a typo (e.g.
visual_encoder.layers.3) passes the regex and matches nothing. This is the same class of mistake as a key naming a layer that doesn't exist, which the docs already say is not detected because each PP stage holds only some layers. No change needed. saved_tensors_hooksandremat.checkpoint(region_name=...)still receive the relativelayers.<id>name. The description says this is deliberate, and there is no current consumer that needs the prefixed name there.
Not verified: multi-rank PP/FSDP behavior at this head (needs GPUs; the description also lists it as not run).
| Block keys are exact names: `layers.<id>` for decoder blocks and | ||
| `<encoder>.layers.<id>` (e.g. `vision_encoder.layers.3`) for encoder blocks; | ||
| other key forms raise at config time. Region patterns remain relative to the block, and `recompute_regions` | ||
| still wins over policy-controlled saves. Pipeline partitioning preserves |
There was a problem hiding this comment.
Nit: line 83 runs well past the wrap width the rest of this paragraph uses (it was left unwrapped after the encoder sentence was added). Reflowed:
| Block keys are exact names: `layers.<id>` for decoder blocks and | |
| `<encoder>.layers.<id>` (e.g. `vision_encoder.layers.3`) for encoder blocks; | |
| other key forms raise at config time. Region patterns remain relative to the block, and `recompute_regions` | |
| still wins over policy-controlled saves. Pipeline partitioning preserves | |
| Block keys are exact names: `layers.<id>` for decoder blocks and | |
| `<encoder>.layers.<id>` (e.g. `vision_encoder.layers.3`) for encoder blocks; | |
| other key forms raise at config time. Region patterns remain relative to the | |
| block, and `recompute_regions` still wins over policy-controlled saves. | |
| Pipeline partitioning preserves |
|
Overall, I like this direction. And I think there is a simple way to understand the appeal of this direction. Let's take a model which was unable to fit in memory, and then you end up applying remat. Today, with remat, maybe the only way to fit in the memory budget was to recompute one expensive operation. However, since the policy is uniform: you end up recomputing that expensive operation in all the layers. But suppose recomputing that one operation for only 2 layers was enough to fit in memory. The current design does not allow this, and this PR makes us support that new performance-memory tradeoff. |
@anijain2305 agreed. i heard you and @tianyu-l had some offline discussions on a more unified approach, if you wanna changes on api, can you take over this pr by adding your own commits? i just need something similar to land the k3 recipe. |
## Summary (human-written) Support non-uniform remat policy. Introducing `block_overrides` which if specified takes over the default policy, and overrides the given save/recompute regions for the spcified blocks. Any overridden valye with None defaults to the original policy. Initial idea by Shuhua at #5686 ## Why The remat policy applies to every transformer block, so every block pays the same price. If recomputing one expensive region in two blocks is enough to fit the memory budget, the only uniform choice is to recompute it in all of them; likewise, retaining a region in a few blocks means retaining it everywhere. This supersedes #5686 (block-scoped save regions), generalizing it from adding saves to replacing either policy field, so a recipe can trade time for memory in both directions per block. **Example.** ```python ActivationRematConfig( save_regions=["*"], block_overrides=[ # Recompute the attention core only in the first two blocks. BlockRematOverride( blocks=["layers.0", "layers.1"], recompute_regions=["attention.inner_attention"], ), ], ) ``` #5686's Kimi K3 use (retain the KDA core only in layers 58/70/82/90) is an override with `save_regions=[*base, "attention.inner_attention"]` for those blocks. ## What changed - `BlockRematOverride(blocks, save_regions, recompute_regions)` and `ActivationRematConfig.block_overrides`. A field the override sets replaces the base value for its blocks; `None` inherits it. Within a block's result, `recompute_regions` still wins over `save_regions`. - Blocks are named by exact original FQNs (`layers.<id>`, `<encoder>.layers.<id>`), which pipeline splitting keeps. Malformed names, empty overrides and a block named by two overrides raise at config time. - `ActivationRematConfig.block_policy(fqn)` resolves one block's policy. `apply` takes `module_fqn`, passed by the encoder call sites (`MultimodalModel`, `KimiK3Model`), so decoder names never match encoder blocks (from #5686). Checkpoint region names and the saved-tensor hook FQN are unchanged. - The fixed presets (Full/Default) reject overrides. - `REMAT.md`: per-block policies. ## Numerics Overrides only choose, per block, which regions are retained or recomputed; loss and gradients are unchanged. ## Testing `tests/unit_tests/gpu/distributed/test_activation_checkpoint.py` (29 tests with `test_remat.py`, all pass on one GB300): - Overrides replace fields by original layer id (blocks 81/82/91; an override for `layers.1`, a block's position, matches nothing), checked with per-block forward counts. - An encoder override is matched with `module_fqn`; a decoder name does not match the encoder block of the same id. - Validation errors, and presets rejecting overrides. Not run: multi-rank PP/FSDP with overrides, or an end-to-end recipe.
## Summary (human-written) Support non-uniform remat policy. Introducing `block_overrides` which if specified takes over the default policy, and overrides the given save/recompute regions for the spcified blocks. Any overridden valye with None defaults to the original policy. Initial idea by Shuhua at #5686 ## Why The remat policy applies to every transformer block, so every block pays the same price. If recomputing one expensive region in two blocks is enough to fit the memory budget, the only uniform choice is to recompute it in all of them; likewise, retaining a region in a few blocks means retaining it everywhere. This supersedes #5686 (block-scoped save regions), generalizing it from adding saves to replacing either policy field, so a recipe can trade time for memory in both directions per block. **Example.** ```python ActivationRematConfig( save_regions=["*"], block_overrides=[ # Recompute the attention core only in the first two blocks. BlockRematOverride( blocks=["layers.0", "layers.1"], recompute_regions=["attention.inner_attention"], ), ], ) ``` #5686's Kimi K3 use (retain the KDA core only in layers 58/70/82/90) is an override with `save_regions=[*base, "attention.inner_attention"]` for those blocks. ## What changed - `BlockRematOverride(blocks, save_regions, recompute_regions)` and `ActivationRematConfig.block_overrides`. A field the override sets replaces the base value for its blocks; `None` inherits it. Within a block's result, `recompute_regions` still wins over `save_regions`. - Blocks are named by exact original FQNs (`layers.<id>`, `<encoder>.layers.<id>`), which pipeline splitting keeps. Malformed names, empty overrides and a block named by two overrides raise at config time. - `ActivationRematConfig.block_policy(fqn)` resolves one block's policy. `apply` takes `module_fqn`, passed by `MultimodalModel` for each encoder (Kimi K3's vision encoder included), so decoder names never match encoder blocks (from #5686). Checkpoint region names and the saved-tensor hook FQN are unchanged. - The fixed presets (Full/Default) reject overrides. - `REMAT.md`: per-block policies. ## Numerics Overrides only choose, per block, which regions are retained or recomputed; loss and gradients are unchanged. ## Testing `tests/unit_tests/gpu/distributed/test_activation_checkpoint.py` (29 tests with `test_remat.py`, all pass on one GB300): - Overrides replace fields by original layer id (blocks 81/82/91; an override for `layers.1`, a block's position, matches nothing), checked with per-block forward counts. - An encoder override is matched with `module_fqn`; a decoder name does not match the encoder block of the same id. - Validation errors, and presets rejecting overrides. Not run: multi-rank PP/FSDP with overrides, or an end-to-end recipe.
## Summary (human-written) Support non-uniform remat policy. Introducing `block_overrides` which if specified takes over the default policy, and overrides the given save/recompute regions for the spcified blocks. Any overridden valye with None defaults to the original policy. Initial idea by Shuhua at #5686 ## Why The remat policy applies to every transformer block, so every block pays the same price. If recomputing one expensive region in two blocks is enough to fit the memory budget, the only uniform choice is to recompute it in all of them; likewise, retaining a region in a few blocks means retaining it everywhere. This supersedes #5686 (block-scoped save regions), generalizing it from adding saves to replacing either policy field, so a recipe can trade time for memory in both directions per block. **Example.** ```python ActivationRematConfig( save_regions=["*"], block_overrides=[ # Recompute the attention core only in the first two blocks. BlockRematOverride( blocks=["layers.0", "layers.1"], recompute_regions=["attention.inner_attention"], ), ], ) ``` #5686's Kimi K3 use (retain the KDA core only in layers 58/70/82/90) is an override with `save_regions=[*base, "attention.inner_attention"]` for those blocks. ## What changed - `BlockRematOverride(blocks, save_regions, recompute_regions)` and `ActivationRematConfig.block_overrides`. A field the override sets replaces the base value for its blocks; `None` inherits it. Within a block's result, `recompute_regions` still wins over `save_regions`. - Blocks are named by exact original FQNs (`layers.<id>`, `<encoder>.layers.<id>`), which pipeline splitting keeps. Malformed names, empty overrides and a block named by two overrides raise at config time. - `ActivationRematConfig.block_policy(fqn)` resolves one block's policy. `apply` takes `module_fqn`, passed by `MultimodalModel` for each encoder (Kimi K3's vision encoder included), so decoder names never match encoder blocks (from #5686). Checkpoint region names and the saved-tensor hook FQN are unchanged. - The fixed presets (Full/Default) reject overrides. - `REMAT.md`: per-block policies. ## Numerics Overrides only choose, per block, which regions are retained or recomputed; loss and gradients are unchanged. ## Testing `tests/unit_tests/gpu/distributed/test_activation_checkpoint.py` (29 tests with `test_remat.py`, all pass on one GB300): - Overrides replace fields by original layer id (blocks 81/82/91; an override for `layers.1`, a block's position, matches nothing), checked with per-block forward counts. - An encoder override is matched with `module_fqn`; a decoder name does not match the encoder block of the same id. - Validation errors, and presets rejecting overrides. Not run: multi-rank PP/FSDP with overrides, or an end-to-end recipe. --- <sub>Stack created with <a href="https://github.com/github/gh-stack">GitHub Stacks CLI</a> • <a href="https://gh.io/stacks-feedback">Give Feedback 💬</a></sub>
## Summary (human-written) Support non-uniform remat policy. Introducing `block_overrides` which if specified takes over the default policy, and overrides the given save/recompute regions for the spcified blocks. Any overridden valye with None defaults to the original policy. Initial idea by Shuhua at pytorch/torchtitan#5686 ## Why The remat policy applies to every transformer block, so every block pays the same price. If recomputing one expensive region in two blocks is enough to fit the memory budget, the only uniform choice is to recompute it in all of them; likewise, retaining a region in a few blocks means retaining it everywhere. This supersedes #5686 (block-scoped save regions), generalizing it from adding saves to replacing either policy field, so a recipe can trade time for memory in both directions per block. **Example.** ```python ActivationRematConfig( save_regions=["*"], block_overrides=[ # Recompute the attention core only in the first two blocks. BlockRematOverride( blocks=["layers.0", "layers.1"], recompute_regions=["attention.inner_attention"], ), ], ) ``` #5686's Kimi K3 use (retain the KDA core only in layers 58/70/82/90) is an override with `save_regions=[*base, "attention.inner_attention"]` for those blocks. ## What changed - `BlockRematOverride(blocks, save_regions, recompute_regions)` and `ActivationRematConfig.block_overrides`. A field the override sets replaces the base value for its blocks; `None` inherits it. Within a block's result, `recompute_regions` still wins over `save_regions`. - Blocks are named by exact original FQNs (`layers.<id>`, `<encoder>.layers.<id>`), which pipeline splitting keeps. Malformed names, empty overrides and a block named by two overrides raise at config time. - `apply` resolves each block's override and takes `module_fqn`, passed by `MultimodalModel` for each encoder (Kimi K3's vision encoder included), so decoder names never match encoder blocks (from #5686). Checkpoint region names and the saved-tensor hook FQN are unchanged. - The fixed presets (Full/Default) reject overrides. - `REMAT.md` is renamed `ACTIVATION_REMAT.md`, matching `activation_remat.py` and `ACTIVATION_OFFLOAD.md`, and documents per-block policies. `apply`'s first argument is renamed `module` (it is the root model or an encoder). ## Numerics Overrides only choose, per block, which regions are retained or recomputed; loss and gradients are unchanged. ## Testing `tests/unit_tests/gpu/distributed/test_activation_checkpoint.py` (29 tests with `test_remat.py`, all pass on one GB300): - Overrides replace fields by original layer id (blocks 81/82/91; an override for `layers.1`, a block's position, matches nothing), checked with per-block forward counts. - An encoder override is matched with `module_fqn`; a decoder name does not match the encoder block of the same id. - Validation errors, and presets rejecting overrides. Not run: multi-rank PP/FSDP with overrides, or an end-to-end recipe.
Part **5/n** of the Kimi K3 / Dist-MoE training stack. Based on `main`. Replaces #4353. ## Summary human notes: add tp support for distmuon. ## Why DistMuon cannot be used with tensor parallelism on `main`. Muon must orthogonalize complete matrices, but with TP+FSDP a matrix is split across two mesh axes, and the FlexShard planner only supports transport along one axis with every other axis replicated. The Kimi recipes therefore reject `tensor_parallel_degree > 1` when DistMuon is configured (`TODO(#3353)`). **Example.** ```text storage mesh: (dp_shard=2, tp=2); one matrix stored as (Shard(0), Shard(1)) rank (dp, tp) holds the [rows of dp] x [cols of tp] fragment compute: {"dp_shard": Owned(), "tp": Owned()} # one rank updates the whole matrix main: NotImplementedError: multi-axis transport is not implemented this PR: the 4 ranks form one "dp_shard_tp" transport group; the owner receives the complete matrix, runs Newton-Schulz once, and every rank gets its original (Shard(0), Shard(1)) fragment back ``` The same applies to MLA head blocks stored as `(_StridedShard(0), Shard(0))` (TP and FSDP sharding the same dim) and to experts stored as `(Shard(0), Shard(1))`. CP already works with DistMuon on `main` (`dp_shard_cp` is one flattened axis); with this PR it also composes with TP (`dp_shard_cp` + `tp`). ## What changed **FlexShard planner** (`flex_shard/dist_muon.py`, `_optimizer_reshard_schedule.py`) -- the core of the PR: - A transition may span several storage mesh axes; `redistribution_storage_mesh_axis` becomes `redistribution_storage_mesh_axes`. - Storage is described as per-dimension index runs, so `_StridedShard`, uneven, and empty shards map to logical regions exactly; each rank's storage must be one contiguous region (true for TP + FSDP layouts), otherwise planning raises. `_StridedShard` storage whose dimension is not divisible by its split factor also raises: FSDP2 lays out that uneven case differently from DTensor's split-then-shard rule (TODO in the code). Non-transport axes keep their storage placement. - `Owned` compute requires every non-owned axis to be replicated; changing an axis outside the transport group raises `ValueError`. **Explicit transport meshes.** FlexShard never creates process groups. `BucketConfig.mesh` is removed: `DistMuon(..., transport_meshes=...)` takes a pool of caller-owned 1D meshes, and each bucket uses the pool mesh whose ranks equal the storage ranks of its transport axes (names are not used). Without a match, a single-axis transport reuses its storage group and a combined transport raises. - `ParallelismContext.build_optimizer_meshes(axes_list, backend=..., pg_options=...)` builds the pool. For each axes tuple it creates one group per slice of those axes over the whole world and returns this rank's 1D meshes, named by the joined axes (`dp_shard_tp`). Axes that cover the same ranks share one group and one mesh: with dp_shard=2, tp=2, ep=2, each rank's `edp_shard` slice equals its `dp_shard` slice, and two pool meshes with the same ranks would make the bucket's mesh ambiguous. Every rank creates every slice, so ranks on different PP stages (including an expert-free stage) create the same groups in the same order without an extra collective. The meshes are not registered on the root mesh, so DTensor never uses them. This replaces `build_alternative_fsdp_mesh`. - The TorchTitan `DistMuon` wrapper (`components/optim/optimizer.py`) requests `(dp_shard[, cp], tp)` when TP > 1. With `max_nccl_ctas_for_comms` it also requests `dp_shard[, cp]` and, with EP, `edp_shard`, all as NCCL communicators with that CTA cap (FSDP groups unchanged). `Optim` passes `parallelism_context` through `OptimizersContainer` to every optimizer build for this. **Compute buffer reuse** (`_optimizer_reshard_runtime.py`, `_optimizer_reshard_schedule.py`): the compute exchange buffer is reused in place for returned fragments, which is only safe when both directions pack each parameter identically. A replicated holder (e.g. a TP-replicated `Owned` matrix) gets its update back on every holder, so returned fragments could overwrite later parameters' unread input. The bucket plan records `compute_to_storage_offset`: `0` when the layouts match, otherwise returned fragments go after the received ones. This duplicates #5695, where the same bug reproduces on `main` with plain `Replicate` storage on a 1D mesh. #5695 lands first; this PR then rebases and keeps only its TP test. | | #5695 | this PR | | --- | --- | --- | | Plan field | `compute_to_storage_input_offset` | `compute_to_storage_offset` | | Offset rule | `0` if the compute -> storage input spans equal the storage -> compute output spans, else the received buffer size | same | | Runtime | buffer sized `offset + input_buffer_numel` (2 sites); returned fragments and the outgoing all-to-all use `buffer[offset:]` | same | | Test | 1D `dp_shard`, `Replicate` storage between `Shard(1)` params; shared bucket vs per-parameter buckets | DP x TP, TP-replicated `Owned` before TP-sharded params; vs unsharded `torch.optim.Muon` | **Kimi** (`models/kimi_k2_7/qk_clip.py`, recipes, README): - QK-Clip derives its per-head scale placements from the MAX all-reduce group (the `loss` mesh) instead of axis names: scales are `Replicate` on mesh axes inside that group and keep the weight's `Shard(0)` on axes that split heads (TP); anything else raises. - Recipe compute layouts declare the `tp` axis only when `tensor_parallel_degree > 1`; the TP guard is removed, so TP=1 layouts are unchanged. TP with DistMuon is verified on K3. - The recipes' `__post_init__` re-derives the dense layouts' `tp` axis (and, as before, the routed-expert layouts) from the final parallelism config, so a config that sets TP after building the recipe, like the b200 cell, still gets TP layouts. **Integration coverage:** the b200 `kimi_k3_debugmodel_fsdp2_tp2_ep2_pp2_vpp4` cell (FSDP 2, TP 2, EP 2, interleaved PP 2 x 4 stages, 8 GPUs, no golden file) now keeps the recipe's DistMuon with its CTA cap instead of AdamW, so CI runs the TP layouts, QK-Clip on TP-local heads, and transport group creation across stages on real NCCL. **Mechanical / skimmable:** FlexShard and Kimi README updates, integration-test comments, DeepSeek V4 guard message (its layouts do not declare `tp`), deletion of `build_alternative_fsdp_mesh` and its mocked tests, `parallelism_context` plumbing through `Optim`, `OptimizersContainer` and `TorchFTOptimizersContainer` and its test updates. ## Alternatives considered - Run Newton-Schulz on TP fragments independently: changes Muon's math. - Let FlexShard create the groups itself: hides process-group policy (CTA cap, NCCL options) inside the planner; the caller owns process groups instead. - Create groups lazily per bucket, with only their members (`use_local_synchronization=True`), or with `split_group` from the storage group (as `main` did for the CTA cap): every group creation advances a per-rank counter that names later groups, so when PP stages create different groups, later WORLD-wide group creation hangs. - `DeviceMesh._flatten` from a storage mesh: private, needs the storage mesh on every rank (fails for an expert-free stage), and registers the combined mesh on the world root, which changes how DTensor gathers other parameters on those axes. - Create the combined groups in `ParallelismContext.build_mesh` (as first proposed for option (a)): every TP run, AdamW included, would pay for the extra communicators, and `build_mesh` would need the DistMuon-only CTA cap. Instead the DistMuon wrapper calls `build_optimizer_meshes` once at construction, and FlexShard picks each bucket's mesh by ranks, so `BucketConfig.mesh` and the wrapper's bucket matching are no longer needed. - Create only the groups this rank's buckets need (query FlexShard for each bucket's transport axes, all-gather the rank lists across PP stages, create the union): needs a FlexShard query API and an extra collective; creating every slice of a few fixed axis combinations is simpler. - DP-only transport for TP-local head blocks (a dedicated `dp_shard` group, or pinning each head block to its TP shard inside the `(dp_shard, tp)` group): not needed for correctness, and not faster in the microbenchmark below. Head blocks use the same `(dp_shard, tp)` all-to-all as the other dense weights. `all_to_all_single` (bf16, uneven splits) on 4 GB300s, all NVLink, as dp_shard=2 x tp=2. Time per call after warmup, slowest rank. Each rank sends 2x "bytes/peer" in total in every column: - pinned: 4-rank group, the same-TP peer and self get "bytes/peer" each, cross-TP peers get 0 - spread: 4-rank group, the same total split evenly over all 4 ranks (cross-TP allowed) - dp_shard: dedicated 2-rank group, same bytes as pinned | bytes/peer | pinned | spread | dp_shard | | --- | --- | --- | --- | | **default CTAs** | | | | | 64 KiB | 70 us | 90 us | 68 us | | 1 MiB | 74 us | 78 us | 70 us | | 8 MiB | 72 us | 76 us | 67 us | | 32 MiB | 212 us | 124 us | 123 us | | 128 MiB | 758 us | 415 us | 407 us | | **8-CTA cap (`max_nccl_ctas_for_comms`)** | | | | | 64 KiB | 74 us | 80 us | 69 us | | 1 MiB | 70 us | 74 us | 67 us | | 8 MiB | 197 us | 104 us | 113 us | | 32 MiB | 746 us | 394 us | 390 us | | 128 MiB | 1536 us | 1406 us | 1157 us | Pinning is up to ~1.9x slower than spreading at 8 MiB/peer and above. Spreading is within ~10% of a dedicated group except at 128 MiB with the cap (1.2x). Single node only; cross-node behavior is unmeasured. ## User-facing changes | Before | After | | --- | --- | | Kimi recipes with DistMuon reject `tensor_parallel_degree > 1` | DP x TP supported (K3 also CP x TP) | | `max_nccl_ctas_for_comms` caps `split_group` children of `dp_shard`/`edp_shard` | caps the actual optimizer transport groups, incl. combined DP/TP | | `BucketConfig.mesh` overrides a bucket's groups with a storage-axis child mesh | removed; FlexShard `DistMuon(transport_meshes=...)` takes a pool of 1D meshes matched by ranks, including combined ones (`dp_shard_tp`); the TorchTitan wrapper builds it with `ParallelismContext.build_optimizer_meshes` | Mesh setup requires every rank to construct the same sequence of DistMuon optimizers (true for torchtitan PP schedules). Memory: a bucket that contains a replicated holder region (e.g. a TP-replicated `Owned` matrix) places returned fragments after the received ones, so its compute exchange buffer grows by the bucket's receive size, up to about 2x. Buckets whose receive and return layouts match are unchanged. ## Numerics Newton-Schulz arithmetic and the Muon update are unchanged; TP=1 layouts take the same paths as before. With TP, every block/matrix is orthogonalized whole, as without TP. | Check | Workers / backend | Result | | --- | --- | --- | | Whole, TP-replicated `Owned`, strided head-block and expert matrices, 2 real Muon steps, DP-only `(4,1)`, TP-only `(1,4)` and DP x TP `(2,2)` each vs. unsharded `torch.optim.Muon` | 4 / NCCL | whole matrices exact; batched head blocks and experts within 2e-2 of the lr-normalized update per step (batched vs per-matrix BF16 GEMMs) | | Same parameters, shared bucket vs one bucket per parameter | 4 / NCCL | exact | **Kimi K3 debug model, 50 steps**, rebased on `main` at `72e556678`, `scripts/loss_compare.py` from a shared seed checkpoint, dp_shard=2 + ep=2, TP=1 (2 GPUs) vs TP=2 + SP (4 GPUs), GB300. TP changes reduction order, so loss is not bitwise; the AdamW run shows the TP noise floor: | Step | DistMuon TP=2 - TP=1 | AdamW TP=2 - TP=1 | | --- | --- | --- | | 2 | +0.001 | -0.002 | | 5 | +0.008 | +0.000 | | 10 | -0.001 | +0.006 | | 25 | +0.009 | -0.009 | | 50 | -0.007 | +0.002 | | max \|diff\| over 50 steps | 0.017 | 0.021 | | mean \|diff\| over 50 steps | 0.006 | 0.006 | ## Testing ```bash CUDA_VISIBLE_DEVICES='' python -m pytest -q \ tests/unit_tests/cpu/distributed/flex_shard \ tests/unit_tests/cpu/distributed/test_distributed_utils.py \ tests/unit_tests/cpu/distributed/test_parallelism_context.py \ tests/unit_tests/cpu/components/optim \ tests/unit_tests/cpu/recipes \ torchtitan/experiments/torchft/tests python -m pytest -q \ tests/unit_tests/gpu/distributed/flex_shard/test_dist_muon.py \ tests/unit_tests/gpu/models/kimi_k2_7/test_qk_clip.py # 4 GPUs ``` CPU: 230 passed, 13 skipped (198 + 32 TorchFT; the skips are all in `test_fused_mla_override.py`, which needs CUDA). GPU: 19 passed on 4x GB300. Run with the attn-gym and torch_checkpointing commits pinned in `requirements.txt`. `pre-commit` passes except Pyrefly, which reports 8 errors, all in files this PR does not change. New tests and the regressions they catch: - GPU `test_dist_muon.py::TestDistMuonMatchesUnshardedMuon`: DP-only, TP-only and DP x TP storage each match unsharded `torch.optim.Muon` (whole matrices exactly; batched head blocks and experts within the 2e-2 tolerance the other DistMuon tests use), for a bucket where a TP-replicated `Owned` matrix sorts before TP-sharded, head-block and expert parameters. The shared bucket must also match per-parameter buckets exactly; the TP-only case fails that check without the buffer-reuse fix. Also checks that FlexShard never creates groups and that a combined transport without a matching transport mesh raises. - GPU `test_dist_muon.py::TestDistMuonTensorParallelCudaGraph`: TP routing stays exact under CUDA-graph replay. - GPU `test_qk_clip.py::QKClipTensorParallelTest`: QK-Clip scales TP-local heads when FSDP's shard splits a head, and raises when the reduction group does not match the weight's placements. - Group creation across PP stages: `TestBuildOptimizerMeshes` (next bullet) checks that every rank creates every stage's groups in the same order, and the b200 `kimi_k3_debugmodel_fsdp2_tp2_ep2_pp2_vpp4` cell runs DistMuon with the CTA cap under PP, TP and EP on 8 GPUs. - CPU `test_parallelism_context.py::TestBuildOptimizerMeshes`: with PP 2 on a fake PG, a stage-1 rank also creates stage 0's slices, in the same order as every other rank; `dp_shard` and `edp_shard` slices with equal ranks share one group and return one mesh; the meshes are not registered on the root mesh; an axis combination spanning the dense and sparse meshes raises. ## Known issues / follow-ups - Depends on #5695 landing first; this PR then drops its copy of the buffer-reuse fix. - The b200 `kimi_k3_debugmodel_fsdp2_tp2_ep2_pp2_vpp4` cell needs 8 GPUs, so only a 4-GPU variant (dp_shard=1, TP 2, EP 2, PP 2 x 4 stages) was run here: DistMuon builds for all 4 model parts, then the first forward fails in the attn-gym KDA kernel (`'tuple' object has no attribute 'atom'`), the same failure as the cell config with AdamW on `main` on this machine. The cell is therefore not verified end-to-end locally. - Kimi K3.1 shares the K3 DistMuon recipe, so it can now run DistMuon with TP. DistMuon construction under FSDP 2, TP 2, EP 2 succeeds (243 Muon parameters, including the indexer layouts), but training was not verified: the first forward fails in the attn-gym KDA kernel (`'tuple' object has no attribute 'atom'`), with AdamW on `main` as well. - Kimi `__post_init__` mutates a shared optimizer config under `dataclasses.replace`; pre-existing on main, separate fix. ## Stack | Position | PR | | --- | --- | | 5/n | [#5678 — Support TP storage-to-compute layouts](#5678) | | 7/n | [#5680 — Keep linear-attention graph metadata replayable](#5680) | | 11/n | [#5684 — Enable Kimi K3 SiTU-GLU training and pipeline lifecycle](#5684) | | 13/n | [#5686 — Add block-scoped activation retention](#5686) | | 14/n | [#5793 — Add full-scale Kimi K3 MXFP8 recipes](#5793) | Merged: 1/n (#5674), 4/n (#5677), 6/n (#5679), 8/n (#5681), 9/n (#5682). Closed: 2/n, 3/n, 10/n, 12/n.
Summary (human-written)
human notes: add a knob for remat, one can pick some blocks to remat when memory pressure is high to save every transformer block. some evidence from full k3 training is presented below.
Independent PR on
main. The consumer is the full-scale Kimi K3 256-GB300MXFP8 recipe, which saves the KDA core only in the last KDA layer of each
physical PP rank's second virtual chunk; that recipe is draft
#5793, which will be rebased
onto this PR (dropping its copy of the earlier glob version and its tests).
Why
The existing remat policy applies each save-region pattern to every transformer
block. Keeping an expensive attention core in one late Kimi layer therefore
requires retaining that core everywhere or changing model code. A block-qualified
save mapping lets a recipe spend a limited activation budget without changing
global expert recomputation or pipeline partitioning.
Example.
What changed
ActivationRematConfig.block_save_regions: exact original-model blockFQN keys (no globs) whose save-region patterns are added to
save_regionsfor that block only. Keys are
layers.<id>for the decoder and<encoder>.layers.<id>for an encoder (e.g.vision_encoder.layers.3).__post_init__raises on other key forms, so a typo such aslayer.91failsat config time instead of silently saving nothing. A key naming a layer the
model lacks is not detected, since each PP stage holds only some layers.
apply()takes a keyword-onlymodule_fqn(empty for the root model). Theencoder call sites (
KimiK3Model,MultimodalModel) pass the encoder'sattribute name, so a decoder key such as
layers.5no longer also matchesvision_encoder.layers.5. Checkpoint region names and saved-tensor hooknames are unchanged.
block overrides on fixed Full/default policies.
REMAT.md, and extend the existing remat tests intests/unit_tests/gpu/distributed/test_activation_checkpoint.py(no new testfile).
Alternatives considered
selects regions declared by the model.
User-facing changes
layers.<id>keys add saves only to those original blocks.The default mapping is empty. Extra retained tensors follow existing pack/unpack
hooks and do not resize Dist-MoE's own activation arena.
Numerics and testing
Retention only chooses which region outputs are saved instead of recomputed, so
loss and gradients are unchanged.
Fresh on this branch (rebased onto
mainat7e6c10618), on one GB300:27 passed. Test changes, both in
test_activation_checkpoint.py:test_block_save_regions_follow_original_layer_ids: blocks81/82/91with aglobal save plus
{"layers.82": [...], "layers.1": [...]}, asserting per-blockforward counts (
layers.1is block 82's position and must match nothing). Italso applies the policy to a toy encoder with
module_fqn="vision_encoder",checking that a decoder key
layers.82does not match the encoder's block 82while
vision_encoder.layers.82does, and that a malformed key such aslayer.91raises.block_save_regionsrow intest_preset_policies_are_fixed. It catches theFull/default presets silently accepting extra saves.
Checked by temporarily breaking the code: block rules replacing global saves,
block rules ignored, matching by position instead of original layer id, the
lookup ignoring
module_fqn, the key check removed, and the preset checkremoved each fail the tests.
End to end, 3 training steps on one GPU pass the encoder name through both call
sites: the Kimi K3 debug model (
KimiK3Model, vision encoder) and the Qwen3.5debug model (
MultimodalModel, run with accelerator graphs disabled, becausethat recipe fails CUDA-graph replay with a changed input shape on
maintoo). Recompute precedence and saved-tensor hooks areunchanged code paths, already covered by
test_recompute_regions_override_save_regionsandtest_saved_tensors_hooks_offload_block_input.pre-commitpasses.Evidence from full-scale runs
The consumer recipe is the accepted 256-GB300 PP4/VPP2 4K Kimi K3 run ("M3.4").
Its baseline, "M3.3", already saves the KDA core only in layers 58/70/82/90 via
this mechanism. M3.4 adds shared-expert saves in every block (global
save_regions, not this PR) plus KDA q/k/v/gate projection saves in those fourlayers (this PR):
Limits of this evidence:
same regions in every block; both runs above use block-scoped saves.
saves; the two are not separated.
Landing gates
The full-scale numbers above come from the
moonepbranch (197a425e2) thatproduced the accepted runs, not from this head. That branch had an earlier,
glob-matching version of this option; the accepted recipes used exact
layers.<id>keys, for which it selects the same blocks as this exact-keyversion. No full-scale run was repeated at this head. Not run at this head: multi-rank
PP/CP/FSDP and checkpoint resume. Complete CI and maintainer review are still
needed.