Skip to content

Per-block remat policies - #6104

Merged
anijain2305 merged 1 commit into
mainfrom
remat-block-overrides
Nov 17, 2026
Merged

anijain2305 merged 1 commit into
mainfrom
remat-block-overrides

Conversation

@anijain2305

@anijain2305 anijain2305 commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

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.

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 [ac] Add block-scoped activation retention #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.


Stack created with GitHub Stacks CLI • Give Feedback 💬

@pytorch-bot pytorch-bot Bot added ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Nov 15, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 15, 2026
@anijain2305
anijain2305 marked this pull request as draft November 15, 2026 21:11
@anijain2305
anijain2305 added this pull request to stack #6105 November 15, 2026 21:11
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 15, 2026
@anijain2305
anijain2305 force-pushed the remat-block-overrides branch from cea7f28 to 0d9014e Compare November 16, 2026 07:33
@anijain2305 anijain2305 changed the title remat block overridesss Per-block remat policies Nov 16, 2026
@anijain2305
anijain2305 marked this pull request as ready for review November 16, 2026 07:51
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 16, 2026
@anijain2305
anijain2305 force-pushed the remat-block-overrides branch from 0d9014e to 8b18879 Compare November 16, 2026 07:56
Comment on lines +133 to +138
if not override.blocks:
raise ValueError("BlockRematOverride.blocks must not be empty.")
if override.save_regions is None and override.recompute_regions is None:
raise ValueError(
f"BlockRematOverride for {override.blocks} sets no field."
)

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.

these probably should go to post_init of BlockRematOverride itself

Comment on lines +53 to +54
save_regions: list[str] | None = None
recompute_regions: list[str] | None = None

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.

@anijain2305 anijain2305 Nov 17, 2026 •

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.

Yes, it is. Let me verify and add a comment.


def apply(
self,
model: Module,

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.

we probably should rename this back to module, as

  • it is not always root model, e.g. vision_encoder is a module that contains transformer blocks
  • be consistent with module_fqn below

)
overridden.add(block_fqn)

def block_policy(self, block_fqn: str) -> BlockRematPolicy:

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.

should this be a private field?

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.

nit: let's rename to ACTIVATION_REMAT.md to stay uniform

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 7s —— View job


Approve -- please address the items before merging (tianyu-l's open comments, plus deleting BlockRematPolicy/block_policy): review

@claude claude Bot left a comment

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.

Verdict: Approve -- please address the items below before merging. The feature is small and has a named consumer (the Kimi K3 recipe, #5793/#5686). What remains is local cleanup: tianyu-l's open comments and some code that can be deleted.

What this PR does. It adds ActivationRematConfig.block_overrides. Each BlockRematOverride names blocks by original FQN (layers.<id> or <encoder>.layers.<id>) and replaces save_regions and/or recompute_regions for those blocks. A field left None inherits the base value. apply gains module_fqn, so MultimodalModel encoders match vision_encoder.layers.N and not the decoder's layers.N. The fixed presets reject overrides.

Example.

ActivationRematConfig(
    save_regions=["*"], recompute_regions=["*routed_experts.w13.*"],
    block_overrides=[BlockRematOverride(blocks=["layers.82"],
                                        recompute_regions=["attention.inner_attention"])],
)
# before: impossible; recomputing inner_attention meant recomputing it in every block
# after:  only block 82 recomputes inner_attention (and saves w13, since recompute_regions
#         is replaced, not extended); every other block keeps the base policy, on any PP stage

Must fix

  1. tianyu-l's comments that are still open at HEAD:
    • activation_remat.py:133-138: move the empty-blocks and no-field checks into BlockRematOverride.__post_init__. The per-name regex check can go there too. Only the duplicate-name check needs the whole list, so it stays in ActivationRematConfig.__post_init__.
    • activation_remat.py:53-54: give the override fields docstrings that restate the precedence rule (see inline comment for the concrete pitfall).
    • activation_remat.py:185: rename apply(model, ...) to apply(module, ...), to match module_fqn and because the argument is an encoder, not always the root model. Update the Args: entry and the model.get_submodule use.
    • activation_remat.py:153: block_policy should not be public. See the inline comment: the method can be deleted outright.
    • REMAT.md: rename it to ACTIVATION_REMAT.md and update every reference: .claude/rules/direction.md:28, torchtitan/distributed/README.md:26, torchtitan/models/common/moe/README.md:117, README.md:139, and activation_remat.py:212.
  2. activation_remat.py:229-236: inline the override lookup into apply. This deletes BlockRematPolicy, block_policy, _override and _T (about -25 LoC) and removes the second scan of block_overrides (inline suggestion).

Should consider

  • activation_remat.py:224: override names that match no block are silently ignored. Extend the existing TODO to cover them.

Questions

  • Will #5793 be rebased onto this, and will #5686 be closed as superseded?

A maintainer still needs to review the core change in torchtitan/models/common/multimodal.py.

Not verified: PP (original layer ids kept across stages) and FSDP with overrides. The PR description also lists these as not run.

Comment on lines +229 to 236
base_fqn = f"layers.{layer_id}"
block_fqn = f"{module_fqn}.{base_fqn}" if module_fqn else base_fqn
policy = self.block_policy(block_fqn)
if any(block_fqn in override.blocks for override in self.block_overrides):
overridden.append(block_fqn)
transformer_block.configure_remat_regions(
self.save_regions, self.recompute_regions
policy.save_regions, policy.recompute_regions
)

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.

block_policy has one caller (here), and this loop then scans block_overrides a second time (L232) to find out whether an override matched. Resolve the override once inline instead. That lets you delete BlockRematPolicy (L57-62), block_policy (L153-167), _override (L306-307), _T, and the TypeVar import, about 25 lines. It also resolves tianyu-l's "should this be private?" comment, since the method goes away.

Suggested change
base_fqn = f"layers.{layer_id}"
block_fqn = f"{module_fqn}.{base_fqn}" if module_fqn else base_fqn
policy = self.block_policy(block_fqn)
if any(block_fqn in override.blocks for override in self.block_overrides):
overridden.append(block_fqn)
transformer_block.configure_remat_regions(
self.save_regions, self.recompute_regions
policy.save_regions, policy.recompute_regions
)
base_fqn = f"layers.{layer_id}"
block_fqn = f"{module_fqn}.{base_fqn}" if module_fqn else base_fqn
save_regions, recompute_regions = self.save_regions, self.recompute_regions
override = next(
(o for o in self.block_overrides if block_fqn in o.blocks), None
)
if override is not None:
overridden.append(block_fqn)
if override.save_regions is not None:
save_regions = override.save_regions
if override.recompute_regions is not None:
recompute_regions = override.recompute_regions
transformer_block.configure_remat_regions(save_regions, recompute_regions)

Comment on lines +53 to +54
save_regions: list[str] | None = None
recompute_regions: list[str] | None = None

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.

This expands on tianyu-l's comment here. The precedence rule does hold for the resolved policy, but these fields need docstrings that say so, because it changes what an override does. Example: with base save_regions=["*"], recompute_regions=["attention.*"], the override BlockRematOverride(blocks=["layers.91"], save_regions=["attention.inner_attention"]) inherits recompute_regions=["attention.*"], so inner_attention is still recomputed in block 91 and the override has no effect. Suggested docstrings: on save_regions, "Replaces the base save_regions for these blocks; None inherits it. A region that also matches the effective recompute_regions is still recomputed, so to retain a region the base recomputes, override recompute_regions too." On recompute_regions, "Replaces the base recompute_regions for these blocks; None inherits it."

Comment on lines 224 to 225
# TODO: Validate unmatched patterns once validation can account for save
# regions across all pipeline stages instead of only this model part.

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.

An override that names a block the model doesn't have, such as a typo like layers.910, is silently ignored. That is the same gap as unmatched region patterns and has the same cause: each PP stage holds only some blocks. The docs mention it, but the TODO should cover it too, so it gets fixed along with region validation.

Suggested change
# TODO: Validate unmatched patterns once validation can account for save
# regions across all pipeline stages instead of only this model part.
# TODO: Validate unmatched patterns and block_overrides names once
# validation can account for all pipeline stages instead of only this
# model part.

## 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.
- `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.
@anijain2305
anijain2305 force-pushed the remat-block-overrides branch from 11d7b12 to b1eb2e6 Compare November 17, 2026 18:39
@anijain2305
anijain2305 merged commit 5ac3354 into main Nov 17, 2026
anijain2305 added a commit that referenced this pull request Nov 18, 2026
## Summary (human-written)

This PR introduces activation offloading API. The design doc is in torchtitan/distributed/ACTIVATION_OFFLOAD.md.

tldr is
* activation offloadin works with and without remat. For both, we use the same pack/unpack hooks.
* users can choose among block inputs, tensors outputs in remat regions, and tensors saved for backward for offloading. This gives users many perf-memory tradeoff points.
* Both offload and reload have one layer full of compute to overlap with.
* For PP, there are natural actions that PP runtime IR can take to overlap the offload and reload with other microbatches on the same rank.

## Why

Remat is the only way to trade time for activation memory today. When a
model does not fit even with the remat policy you want (e.g. Muse Spark 816B
LoRA on 8 GB300: 253 GiB of 276 GiB), the only option is to recompute more.
Offloading what remat keeps to CPU DRAM is the other side of that trade.

**Example.** Offloading is part of the remat policy, which chooses, for each
region it retains, GPU or CPU:
```python
config.activation_remat = ActivationRematConfig(
    save_regions=["*"],               # retain every region: only cheap code is recomputed
    offload_block_input=True,         # each block's input goes to CPU
    offload_regions=["attention.*"],  # and what these regions retain
)
```

## What changed

- `ActivationRematConfig.offload_block_input` / `offload_regions` (default
  off): which retained tensors go to CPU. They are also `BlockRematOverride`
  fields (per-block policies, #6104), so offloading can differ per block; the
  fixed presets accept them, also in overrides that set nothing else.
  `offload_last_block` (default off) also offloads each model part's last
  block.
- `ActivationRematConfig.apply` checkpoints the blocks and, when the policy
  offloads anything, installs an `ActivationOffloader` on the model part
  (`get_activation_offloader(model_part)` returns it). There is no separate
  offload config. `apply` runs inside `parallelize`, before `fully_shard`;
  FSDP2's pre-forward is prepended, so it still runs before the offloader's.
- `apply`'s `saved_tensors_hooks` argument is removed: it existed for custom
  offloading, which this PR supersedes, and had no production caller.
- `torchtitan/distributed/activation_offload.py` (new): `ActivationOffloader`.
  Per transformer block it installs
  `torch_remat.saved_tensors_hooks`; `pack` copies selected storages D2H on a
  side stream, the GPU copies are freed at the end of the next block's
  forward, and a pre-hook on the autograd node of block i+1's output reloads
  block i on a reload stream (autograd runs it after FSDP2's pre-backward
  tensor hook, so the reload queues behind FSDP2's all-gather copy-out).
  Pinned host buffers come from a pool, so whole-step CUDA graphs work; it
  reuses buffers by power-of-two capacity, so saves whose size changes every
  step (tokens routed to an EP rank) do not grow pinned memory. Storages
  under 1 MiB stay on GPU. Autograd skips its in-place check for saves that
  hooks pack, so the offloader records each save's version and raises
  autograd's error at unpack if it changed. A tensor no reload trigger
  reloaded (its block's output got no gradient) raises at unpack.
  Under PP each stage has its own offloader; by default
  (`offload_last_block=False`) each stage's last block stays on GPU, which
  takes precedence over the offload fields (an override offloading it logs a
  warning). Encoder blocks cannot be offloaded: `apply` raises if the policy
  offloads one.
- GraphTrainer rejects a remat policy that offloads (its traced step does not
  run the eager hooks).
- Docs: `torchtitan/distributed/ACTIVATION_OFFLOAD.md`, timeline SVG, README links.

## Alternatives considered

- A hook inside FSDP2: offload must understand torch_remat (saved vs.
  recomputed, region names), which does not belong in pytorch/pytorch.
- Groups finer than a block: no backward savings under block remat, and the
  block input would be missed.
- Offload without remat: the closest setting is remat retaining every region
  and offloading some, which recomputes only the cheap code outside regions.
  Requiring remat makes the remat policy the one place that decides, per
  region, recompute, keep on GPU, or offload.

## Design notes

**Backward trigger: an autograd node pre-hook.** Group i is reloaded from a
pre-hook on the autograd node of block i+1's output, which fires before that
block's backward, one block ahead of the reload's consumer.
- Not a module backward pre-hook: it wraps the block's outputs in a custom
  autograd Function, so an in-place update of an output (`out += x`) raises,
  and it fires before FSDP2's pre-backward.
- Not a plain tensor hook: FSDP2's pre-backward is itself a tensor hook on
  the same output (`t.register_hook`), and tensor hooks fire in registration
  order, so the order would depend on whether offload was applied before or
  after `fully_shard`. Autograd runs every tensor hook of a node before any
  of its node pre-hooks, so the reload is always issued after FSDP2's
  pre-backward, whatever the registration order.
- Why the order matters: FSDP2's pre-backward runs the all-gather copy-out on
  the compute stream, and `split_with_sizes_copy` first copies a few KB of
  kernel metadata host-to-device. In #467 the reload was
  issued first and, on H100, that small copy queued behind the whole reload
  in the copy engine, stalling a block that does not read the reloaded
  activations (about -25% throughput). Issued after it, the reload waits on
  the compute stream (a GPU-side `wait_stream`), so it cannot start before
  that copy. GB300's copy engines do not serialize these copies (measured:
  0.07 ms with a 1 GiB copy in flight vs 0.04 ms idle), but the order holds
  on any hardware.

**FSDP2 CPU parameter offload.** It is the one FSDP2 traffic that shares the
CPU-GPU link with offloading (intra-node all-gather and reduce-scatter run
over NVLink; measured -1 to -2% with offload copies running). In block i's
backward, FSDP2 prefetches block i-1's parameter shards host-to-device while
the offloader reloads block i-1's activations, in the same direction, and
block i+1's gradient shards go device-to-host. The two host-to-device copies
are not ordered by default. When they do not fit in block i's backward,
parameters first would be better, since block i-1's parameters still need the
all-gather after their copy and its activations need nothing more. Under
`set_unshard_in_current_stream` or with a single rank, FSDP2 issues the
parameter copies on the compute stream, so reloads already follow them. A
follow-up makes the reload stream also wait on FSDP2's
`all_gather_copy_in_stream` (TODO in the code), which needs FSDP2 to expose
that stream.

**Pinned host memory.** Needed for the copies to be asynchronous at all, not
only for CUDA graphs. A `non_blocking` copy to or from pageable memory
returns only after the data has moved: on GB300, 1 GiB blocks the CPU for
5.3 ms pageable vs 0.16 ms pinned (bandwidth is the same, about 200 GB/s,
and the GPU still overlaps it with compute). At 15-23 GB offloaded per
forward that is 75-110 ms of blocked CPU per step, during which the CPU
cannot run ahead of the GPU, and CUDA graph capture rejects pageable copies.
The offloader's own buffer pool, rather than allocating per copy, is what
CUDA graphs need: the caching host allocator never reuses a block allocated
during capture.

**Two copy streams.** One per direction: the link is full duplex (one GPU:
about 143 GB/s each way concurrently vs 205 GB/s one way), so one
microbatch's offload and another's reload can run at once, and a reload
never queues behind a pending offload.

## Numerics

Offload moves tensors and copies them back unchanged. Loss and grad_norm are
bitwise equal with vs. without offload (seed 42, deterministic, flex attention,
10 steps, `scripts/loss_compare.py`):

| Model | Layouts |
| --- | --- |
| llama3 debugmodel | 1 GPU full / selective remat; PP2 1F1B, Interleaved1F1B, ZBV; CUDA graphs |
| DeepSeek-V3 debug + BF16 Dist-MoE | selective, full, EP 2, LoRA + EP 2, EP 4 |
| Muse Spark debug | TP/SP (dp2 x tp2 x ep2), LoRA selective / full, Dist-MoE, Dist-MoE + LoRA |

## Performance

llama3 8B, FSDP 4 x GB300, 8K tokens/rank, whole-step CUDA graph, NUMA-bound, 30 steps:

| Config | Peak mem | Offloaded / fwd | TPS (median) |
| --- | --- | --- | --- |
| selective remat | 60.82 GiB | - | 18,952 |
| + block input + attention.* | 52.43 GiB | 8.75 GiB | 18,977 |
| + block input + w13 | 45.62 GiB | 15.50 GiB | 17,265 |
| + all saved regions | 38.72 GiB | 22.3 GiB | 13,400 |

Muse Spark 816B SLAKE LoRA, 8 x GB300 (dp_shard 8 x EP 8, 4K), NUMA-bound:
no offload 252.84 GiB / 1,868 TPS; block input 245.44 GiB (-1.0%); block
input + attention.* 241.77 GiB (-1.8%); everything 238.57 GiB (-3.9%).
Dist-MoE's own activation buffers (28.95 GiB/rank) are not autograd saves and
are not reachable.

## Testing

`tests/unit_tests/gpu/distributed/test_activation_offload.py`: 20 tests, all
pass on GB300 (19 on 1 GPU, 1 FSDP CPU-offload test on 2 GPUs, with offload
installed before `fully_shard` as in `parallelize`). They check outputs and
grads equal to the same remat policy without offload; only the selected saves
move; per-block offload overrides, and the last block winning over them;
`offload_last_block`; one
transfer per storage across views; parameters never offloaded; forward frees
and backward releases the GPU copies; unpack without a reload raises; CUDA
graph replay equal to eager with shared host buffers; step-varying sizes
reuse host buffers; reloads queue after later-registered output hooks;
in-place updates of saves are detected; bitwise with FSDP2 CPU parameter
offload.
`test_activation_checkpoint.py`: offloading an encoder block raises.

## Known issues / follow-ups

- Schedule-driven offload of each stage's last block under PP: the offloader
  API is the next PR in this stack; the PyTorch schedule actions that call it
  come separately.
- Dist-MoE-side offload of its activation buffers.
- Loading FSDP2 CPU parameter offload's host-to-device shard copies before
  activation reloads in FSDP2's default mode (see Design notes): the reload
  stream also waits on FSDP2's `all_gather_copy_in_stream`, which needs FSDP2
  to expose it.
shuhuayu added a commit that referenced this pull request Nov 26, 2026
## Summary (human-written)

Part **14/n** of the Kimi K3 training stack. Independent PR on `main`:
the
pieces it composes are all on `main` now (SiTU-GLU Dist-MoE #5684, Kimi
K3
Dist-MoE pipeline stages #6049, per-block remat #6104).

## Why

TorchTitan has Kimi K3 debug recipes only. There is no recipe that runs
the
full 93-layer model with Dist-MoE, DistMuon and pipeline parallelism
together,
so the configuration used for full-scale throughput runs lives outside
the
repo.

## What changed

`torchtitan_recipes/models/kimi_k3.py` adds one text-only 4K MXFP8
recipe:

| Recipe | Hardware | PP / VPP / EP / FSDP | Microbatches / update |
Tokens / update |
| --- | --- | --- | ---: | ---: |
| `kimi_k3_dist_moe_mxfp8_gb200_512` | 512 GB200 | 8 / 1 / 64 / 64 | 64
| 16,777,216 |

- FP32 parameters, gradients and optimizer state with BF16 compute
views; only
routed-expert GEMMs use MXFP8 (Dist-MoE). Interleaved1F1B with one
explicit
  chunk per rank (seven 12-layer chunks and a final 9-layer chunk),
  CUDA-graph forward/backward, DistMuon, FSDP
  parameters kept unsharded across forward/backward.
- Expert routing uses core's `RoundRobinTokenChoiceTopKRouter`, so this
is a
**throughput recipe, not learned-router training**; gate scores and
their
  gradients stay learned. KDA uses core's default kernel selection.
- `torchtitan/models/kimi_k3/README.md`: a short "Full-Scale Recipe"
section
  with measured throughput for forced and learned routing.
- The K3 DistMuon optimizer builder moves from the K3 debug recipe to
`torchtitan_recipes.models.kimi_k3.dist_muon_optimizer` and is
simplified
(one layout helper, one table per layer type, one pass over layers); the
K3
and K3.1 debug recipes and the GPU test import it from there. The
full-scale
  recipe keeps its own private copy of the expert compute layout helper
  instead of importing it from the K2.7 debug recipe.
- CI: the B200 job, which installs Dist-MoE, also runs the recipe-build
test
(`test_full_recipe_selects_dist_moe_before_graph_validation`); it skips
  wherever Dist-MoE is not installed.

## Numerics

No change to existing recipes. The simplified optimizer builder produces
identical optimizer configs (Muon pattern, learning rates, ordered
buckets and
ordered per-FQN compute layouts) for the K3 debug, K3 debug MXFP8, K3.1
debug
and full-scale recipes, and for the debug model at EP=1 and EP=2.

## Testing

| Check | Result |
| --- | --- |
| `tests/unit_tests/cpu/recipes/test_kimi_dist_moe.py` (Dist-MoE
selection before graph validation) | pass |
| `tests/unit_tests/cpu/models/kimi_k3/` | pass |
| `tests/unit_tests/gpu/models/kimi_k3/test_kimi_k3.py -k dist_muon` (1
GPU) | pass |
| Kimi K2.5 / K3 / K3.1 debug recipes and the 512-GPU recipe build |
pass |

The README's forced-routing row (1,009.5 tokens/s/GPU, 651.44 model
TFLOP/s/GPU,
158.41 GiB maximum reserved, twelve updates on 512 GB200) was measured
with
this recipe. The learned-routing row (971 tokens/s/GPU, 626.52 model
TFLOP/s/GPU) used Kimi K3's default router with Dist-MoE scratch
capacity 2.0.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants