Skip to content

[CP] Add sliding-window varlen selective gather - #5746

Draft
fegin wants to merge 1 commit into
fegin/stack/42from
fegin/stack/6
Draft

fegin wants to merge 1 commit into
fegin/stack/42from
fegin/stack/6

Conversation

@fegin

@fegin fegin commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Stacked PRs:


[CP] Add sliding-window varlen selective gather

Summary (human-written)

Selective gather -- only gathering the required blocks instead of doing allgather.

Integrate selective gather CP for sliding window VarlenAttn. This PR depends on
meta-pytorch/attention-gym#651.

This version assumes CP is within the same nvlink domain. A cross-nvlink domain version require the next attention-gym PR.

Why

K/V all-gather copies tokens that sliding-window attention cannot use. Keep local K/V and gather only remote window blocks through attention-gym's copy-engine exchange. The measured gain is step time (5.7% under full remat and 7.4% under inner remat, Performance); peak memory does not drop, as explained below.

Example: CP8, 128K tokens per rank, window 4096, block size 256:

All-gather K/V:         1024K tokens
Compact K/V:       at most 136K tokens
Saved remote K/V:  at most   8K tokens with full remat

These are buffer-size bounds. They exclude shared transport buffers and other activations. With full remat, all-gather also releases gathered K/V but fetches it again during backward. Selective gather retains halos to avoid that fetch. Model peak memory must be measured for each policy. In the benchmark below, peak allocated memory is 0.151 GiB higher with selective gather: model peak is set by other activations, and the shared transport buffers add a little.

What changed

  • Use attention-gym's public builder for fixed contiguous or head-tail routing. Reuse exchanges across matching layers. Packed document offsets can change during CUDA Graph replay.
  • Save remote K/V under full remat. During backward, rebuild compact K/V from local K/V and saved halos without fetching remote K/V again.
  • Check compact K/V SPMD types and load-balancer compatibility. Support no balancer and head-tail; reject PTRR.
  • Config validation checks that each CP chunk holds whole gather_block_size blocks (num_tokens_per_microbatch_per_dp_rank divisible by CP chunks x block size), so a bad size fails before the first forward.
  • Keep the generic Muse Glimmer integration on all-gather. The H100 recipe selects selective sliding attention through the same setup, with full remat and real process groups.
  • The copy-engine exchange cache lives next to its only caller in cp_attention.py. A layer checks only its CP group and head-tail flag; attention-gym checks the K/V shapes and dtype on every exchange.
  • Mechanical: share varlen chunk helpers with all-gather.

User-facing changes

Attention Backend
Sliding varlen Opt into SelectiveGatherKVSlidingWindowVarlenInnerAttention with contiguous or head-tail CP in one NVLink domain.
Full varlen Keep AllGatherKVVarlenInnerAttention.

Numerics

Loss and grad_norm match bit-for-bit across all 20 steps, both backends, and both remat policies . Seed 42, deterministic mode, BF16, FA4, and CUDA Graphs. All 64 rank records (4 runs x 16 ranks) and TensorBoard files agree.

Performance

Full 52-layer Muse Glimmer, CP16 on 16 GB300s in one NVLink domain, head-tail sharding, 256K packed tokens across 17 documents capped at 16K, and 2048-token sliding windows. Full layers use all-gather in both variants. The benchmark uses this PR's public-layout code with the attention-gym code of meta-pytorch/attention-gym#651 and PyTorch 087ceb5.

Remat Sliding backend Step (ms) Peak allocated (GiB) Peak reserved (GiB)
Full All-gather 2866.2 43.393 57.793
Full Copy engine 2701.7 43.545 57.867
Inner attention All-gather 2404.6 141.706 159.648
Inner attention Copy engine 2227.7 141.857 159.139
  • Copy engine reduces step time by 5.74% under full remat and 7.36% under inner remat. Peak allocated memory increases by 0.151 GiB in each pair.
  • Inner remat uses save_regions=[""] and recompute_regions=["attention.inner_attention"]. Projection math runs once; inner attention runs twice. Bare operations outside saved regions can replay.
  • One run per case on one allocation. Timing averages the slowest rank at each of 17 graph replays. Memory peaks include build, warmup, capture, and training; symmetric-memory buffers can be outside the allocator.

Testing

  • Pass each rank's cp_query_ranges to the attention-gym plan builder of Add selective K/V block exchange plan and copy-engine backend meta-pytorch/attention-gym#651. All layout and plan fields match the benchmark builder across 12,496 rank-specific cases, including the full CP16 benchmark shape. GPU checks and performance results use the same attention-gym PR.
  • 75 TorchTitan CPU tests pass. They cover varlen attention, exchange sharing, fixed-layout rejection, remat regions, and saved K/V lifetime. Two shipped-recipe tests are excluded. Routing tests live upstream; all 39 host plan tests pass.
  • The four-H100 numerical suite passes all eight combinations of contiguous/head-tail, remat off/on, and window sizes 1/4. It checks outputs, gradients, shared exchanges, changed documents, and CUDA Graph replay. The one-token window works with zero remote blocks.
  • Both Muse Glimmer recipes validate.
  • Production validation, CP attention, and context-parallel helpers pass targeted Pyrefly with one PyTorch source path. All non-typechecking pre-commit hooks pass.

Known issues

  • Depends on Add selective K/V block exchange plan and copy-engine backend meta-pytorch/attention-gym#651 (selective gather); the attention-gym pin bump lands separately. Until then, the pinned release lacks attn_gym.distributed.selective_gather.
  • torchtitan does not check that CP ranks share one NVLink domain. One domain can span hosts (GB300 NVL72), so a same-host check would reject valid layouts. The attention-gym symmetric-memory setup is where a bad layout fails.

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 2, 2026
fegin added a commit that referenced this pull request Nov 2, 2026
## Summary (human-written)
Selective gather -- only gathering the required blocks instead of doing allgather.

Integrate selective gather CP for sliding window VarlenAttn. This PR depends on
meta-pytorch/attention-gym#651.

This version assumes CP is within the same nvlink domain. A cross-nvlink domain version require the next attention-gym PR.

## Why
K/V all-gather copies tokens that sliding-window attention cannot use. Keep local K/V and gather only remote window blocks through attention-gym's copy-engine exchange.

Example: CP8, 128K tokens per rank, window 4096, block size 256:

```
All-gather K/V:         1024K tokens
Compact K/V:       at most 136K tokens
Saved remote K/V:  at most   8K tokens with full remat
```

These are buffer-size bounds. They exclude shared transport buffers and other activations. With full remat, all-gather also releases gathered K/V but fetches it again during backward. Selective gather retains halos to avoid that fetch. Model peak memory must be measured for each policy.

## What changed
- Use attention-gym's public builder for fixed contiguous or head-tail routing. Reuse exchanges across matching layers. Packed document offsets can change during CUDA Graph replay.
- Save remote K/V under full remat. During backward, rebuild compact K/V from local K/V and saved halos without fetching remote K/V again.
- Check compact K/V SPMD types and load-balancer compatibility. Support no balancer and head-tail; reject PTRR. Attention-gym validates actual token-range alignment.
- Keep the generic Muse Glimmer integration on all-gather. The H100 recipe selects selective sliding attention through the same setup, with full remat and real process groups.
- Mechanical: share varlen chunk helpers with all-gather.

## User-facing changes
| Attention | Backend |
| --- | --- |
| Sliding varlen | Opt into `SelectiveGatherKVSlidingWindowVarlenInnerAttention` with contiguous or head-tail CP in one NVLink domain. |
| Full varlen | Keep `AllGatherKVVarlenInnerAttention`. |

## Numerics
Loss and grad_norm match bit-for-bit across all 20 steps, both backends, and both remat policies on job 2276942. Seed 42, deterministic mode, BF16, FA4, and CUDA Graphs. All 64 rank records and TensorBoard files agree.

## Performance
Full 52-layer Muse Glimmer, CP16 on 16 GB300s in one NVLink domain, head-tail sharding, 256K packed tokens across 17 documents capped at 16K, and 2048-token sliding windows. Full layers use all-gather in both variants. The benchmark uses this PR's public-layout code with attention-gym 38cd874 and PyTorch 087ceb5.

| Remat | Sliding backend | Step (ms) | Peak allocated (GiB) | Peak reserved (GiB) |
| --- | --- | ---: | ---: | ---: |
| Full | All-gather | 2866.2 | 43.393 | 57.793 |
| Full | Copy engine | 2701.7 | 43.545 | 57.867 |
| Inner attention | All-gather | 2404.6 | 141.706 | 159.648 |
| Inner attention | Copy engine | 2227.7 | 141.857 | 159.139 |

- Copy engine reduces step time by 5.74% under full remat and 7.36% under inner remat. Peak allocated memory increases by 0.151 GiB in each pair.
- Inner remat uses save_regions=["*"] and recompute_regions=["attention.inner_attention*"]. Projection math runs once; inner attention runs twice. Bare operations outside saved regions can replay.
- One run per case on one allocation. Timing averages the slowest rank at each of 17 graph replays. Memory peaks include build, warmup, capture, and training; symmetric-memory buffers can be outside the allocator.

## Testing
- Pass each rank's `cp_query_ranges` to attention-gym `4bc108c`. All layout and plan fields match the benchmark builder across 12,496 rank-specific cases, including the full CP16 benchmark shape. Copy-engine source is unchanged. GPU checks and performance results use attention-gym `38cd874`.
- 75 TorchTitan CPU tests pass. They cover varlen attention, exchange sharing, fixed-layout rejection, remat regions, and saved K/V lifetime. Two shipped-recipe tests are excluded. Routing tests live upstream; all 39 host plan tests pass.
- The four-H100 numerical suite passes all eight combinations of contiguous/head-tail, remat off/on, and window sizes 1/4. It checks outputs, gradients, shared exchanges, changed documents, and CUDA Graph replay. The one-token window works with zero remote blocks.
- Both Muse Glimmer recipes validate. The H100 recipe was checked in isolation because the full module import fails on the torchvision issue below.
- Production validation, CP attention, and context-parallel helpers pass targeted Pyrefly with one PyTorch source path. All non-typechecking pre-commit hooks pass. Whole-worktree Pyrefly reports 195 dependency and scratch-file errors.

## Known issues
- The attention-gym release pin still lacks block exchange. Testing uses its local checkout.
- Whole-worktree typechecking reports scratch-file and dependency errors. The generic integration file has ten errors in untouched code.
- The full H100 suite cannot import torchvision locally because torchvision::nms is missing. Its existing Qwen3.5 import triggers the failure.

stack-info: PR: #5746, branch: fegin/stack/6
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 2, 2026
@fegin
fegin changed the base branch from fegin/stack/5 to main November 2, 2026 20:44
fegin added a commit that referenced this pull request Nov 2, 2026
## Summary (human-written)
Selective gather -- only gathering the required blocks instead of doing allgather.

Integrate selective gather CP for sliding window VarlenAttn. This PR depends on
meta-pytorch/attention-gym#651.

This version assumes CP is within the same nvlink domain. A cross-nvlink domain version require the next attention-gym PR.

## Why
K/V all-gather copies tokens that sliding-window attention cannot use. Keep local K/V and gather only remote window blocks through attention-gym's copy-engine exchange.

Example: CP8, 128K tokens per rank, window 4096, block size 256:

```
All-gather K/V:         1024K tokens
Compact K/V:       at most 136K tokens
Saved remote K/V:  at most   8K tokens with full remat
```

These are buffer-size bounds. They exclude shared transport buffers and other activations. With full remat, all-gather also releases gathered K/V but fetches it again during backward. Selective gather retains halos to avoid that fetch. Model peak memory must be measured for each policy.

## What changed
- Use attention-gym's public builder for fixed contiguous or head-tail routing. Reuse exchanges across matching layers. Packed document offsets can change during CUDA Graph replay.
- Save remote K/V under full remat. During backward, rebuild compact K/V from local K/V and saved halos without fetching remote K/V again.
- Check compact K/V SPMD types and load-balancer compatibility. Support no balancer and head-tail; reject PTRR. Attention-gym validates actual token-range alignment.
- Keep the generic Muse Glimmer integration on all-gather. The H100 recipe selects selective sliding attention through the same setup, with full remat and real process groups.
- Mechanical: share varlen chunk helpers with all-gather.

## User-facing changes
| Attention | Backend |
| --- | --- |
| Sliding varlen | Opt into `SelectiveGatherKVSlidingWindowVarlenInnerAttention` with contiguous or head-tail CP in one NVLink domain. |
| Full varlen | Keep `AllGatherKVVarlenInnerAttention`. |

## Numerics
Loss and grad_norm match bit-for-bit across all 20 steps, both backends, and both remat policies on job 2276942. Seed 42, deterministic mode, BF16, FA4, and CUDA Graphs. All 64 rank records and TensorBoard files agree.

## Performance
Full 52-layer Muse Glimmer, CP16 on 16 GB300s in one NVLink domain, head-tail sharding, 256K packed tokens across 17 documents capped at 16K, and 2048-token sliding windows. Full layers use all-gather in both variants. The benchmark uses this PR's public-layout code with attention-gym 38cd874 and PyTorch 087ceb5.

| Remat | Sliding backend | Step (ms) | Peak allocated (GiB) | Peak reserved (GiB) |
| --- | --- | ---: | ---: | ---: |
| Full | All-gather | 2866.2 | 43.393 | 57.793 |
| Full | Copy engine | 2701.7 | 43.545 | 57.867 |
| Inner attention | All-gather | 2404.6 | 141.706 | 159.648 |
| Inner attention | Copy engine | 2227.7 | 141.857 | 159.139 |

- Copy engine reduces step time by 5.74% under full remat and 7.36% under inner remat. Peak allocated memory increases by 0.151 GiB in each pair.
- Inner remat uses save_regions=["*"] and recompute_regions=["attention.inner_attention*"]. Projection math runs once; inner attention runs twice. Bare operations outside saved regions can replay.
- One run per case on one allocation. Timing averages the slowest rank at each of 17 graph replays. Memory peaks include build, warmup, capture, and training; symmetric-memory buffers can be outside the allocator.

## Testing
- Pass each rank's `cp_query_ranges` to attention-gym `4bc108c`. All layout and plan fields match the benchmark builder across 12,496 rank-specific cases, including the full CP16 benchmark shape. Copy-engine source is unchanged. GPU checks and performance results use attention-gym `38cd874`.
- 75 TorchTitan CPU tests pass. They cover varlen attention, exchange sharing, fixed-layout rejection, remat regions, and saved K/V lifetime. Two shipped-recipe tests are excluded. Routing tests live upstream; all 39 host plan tests pass.
- The four-H100 numerical suite passes all eight combinations of contiguous/head-tail, remat off/on, and window sizes 1/4. It checks outputs, gradients, shared exchanges, changed documents, and CUDA Graph replay. The one-token window works with zero remote blocks.
- Both Muse Glimmer recipes validate. The H100 recipe was checked in isolation because the full module import fails on the torchvision issue below.
- Production validation, CP attention, and context-parallel helpers pass targeted Pyrefly with one PyTorch source path. All non-typechecking pre-commit hooks pass. Whole-worktree Pyrefly reports 195 dependency and scratch-file errors.

## Known issues
- The attention-gym release pin still lacks block exchange. Testing uses its local checkout.
- Whole-worktree typechecking reports scratch-file and dependency errors. The generic integration file has ten errors in untouched code.
- The full H100 suite cannot import torchvision locally because torchvision::nms is missing. Its existing Qwen3.5 import triggers the failure.

stack-info: PR: #5746, branch: fegin/stack/6
@fegin
fegin changed the base branch from main to fegin/stack/5 November 2, 2026 20:45
@fegin
fegin changed the base branch from fegin/stack/5 to fegin/stack/4 November 2, 2026 21:38
fegin added a commit that referenced this pull request Nov 2, 2026
## Summary (human-written)
Selective gather -- only gathering the required blocks instead of doing allgather.

Integrate selective gather CP for sliding window VarlenAttn. This PR depends on
meta-pytorch/attention-gym#651.

This version assumes CP is within the same nvlink domain. A cross-nvlink domain version require the next attention-gym PR.

## Why
K/V all-gather copies tokens that sliding-window attention cannot use. Keep local K/V and gather only remote window blocks through attention-gym's copy-engine exchange.

Example: CP8, 128K tokens per rank, window 4096, block size 256:

```
All-gather K/V:         1024K tokens
Compact K/V:       at most 136K tokens
Saved remote K/V:  at most   8K tokens with full remat
```

These are buffer-size bounds. They exclude shared transport buffers and other activations. With full remat, all-gather also releases gathered K/V but fetches it again during backward. Selective gather retains halos to avoid that fetch. Model peak memory must be measured for each policy.

## What changed
- Use attention-gym's public builder for fixed contiguous or head-tail routing. Reuse exchanges across matching layers. Packed document offsets can change during CUDA Graph replay.
- Save remote K/V under full remat. During backward, rebuild compact K/V from local K/V and saved halos without fetching remote K/V again.
- Check compact K/V SPMD types and load-balancer compatibility. Support no balancer and head-tail; reject PTRR. Attention-gym validates actual token-range alignment.
- Keep the generic Muse Glimmer integration on all-gather. The H100 recipe selects selective sliding attention through the same setup, with full remat and real process groups.
- Mechanical: share varlen chunk helpers with all-gather.

## User-facing changes
| Attention | Backend |
| --- | --- |
| Sliding varlen | Opt into `SelectiveGatherKVSlidingWindowVarlenInnerAttention` with contiguous or head-tail CP in one NVLink domain. |
| Full varlen | Keep `AllGatherKVVarlenInnerAttention`. |

## Numerics
Loss and grad_norm match bit-for-bit across all 20 steps, both backends, and both remat policies on job 2276942. Seed 42, deterministic mode, BF16, FA4, and CUDA Graphs. All 64 rank records and TensorBoard files agree.

## Performance
Full 52-layer Muse Glimmer, CP16 on 16 GB300s in one NVLink domain, head-tail sharding, 256K packed tokens across 17 documents capped at 16K, and 2048-token sliding windows. Full layers use all-gather in both variants. The benchmark uses this PR's public-layout code with attention-gym 38cd874 and PyTorch 087ceb5.

| Remat | Sliding backend | Step (ms) | Peak allocated (GiB) | Peak reserved (GiB) |
| --- | --- | ---: | ---: | ---: |
| Full | All-gather | 2866.2 | 43.393 | 57.793 |
| Full | Copy engine | 2701.7 | 43.545 | 57.867 |
| Inner attention | All-gather | 2404.6 | 141.706 | 159.648 |
| Inner attention | Copy engine | 2227.7 | 141.857 | 159.139 |

- Copy engine reduces step time by 5.74% under full remat and 7.36% under inner remat. Peak allocated memory increases by 0.151 GiB in each pair.
- Inner remat uses save_regions=["*"] and recompute_regions=["attention.inner_attention*"]. Projection math runs once; inner attention runs twice. Bare operations outside saved regions can replay.
- One run per case on one allocation. Timing averages the slowest rank at each of 17 graph replays. Memory peaks include build, warmup, capture, and training; symmetric-memory buffers can be outside the allocator.

## Testing
- Pass each rank's `cp_query_ranges` to attention-gym `4bc108c`. All layout and plan fields match the benchmark builder across 12,496 rank-specific cases, including the full CP16 benchmark shape. Copy-engine source is unchanged. GPU checks and performance results use attention-gym `38cd874`.
- 75 TorchTitan CPU tests pass. They cover varlen attention, exchange sharing, fixed-layout rejection, remat regions, and saved K/V lifetime. Two shipped-recipe tests are excluded. Routing tests live upstream; all 39 host plan tests pass.
- The four-H100 numerical suite passes all eight combinations of contiguous/head-tail, remat off/on, and window sizes 1/4. It checks outputs, gradients, shared exchanges, changed documents, and CUDA Graph replay. The one-token window works with zero remote blocks.
- Both Muse Glimmer recipes validate. The H100 recipe was checked in isolation because the full module import fails on the torchvision issue below.
- Production validation, CP attention, and context-parallel helpers pass targeted Pyrefly with one PyTorch source path. All non-typechecking pre-commit hooks pass. Whole-worktree Pyrefly reports 195 dependency and scratch-file errors.

## Known issues
- The attention-gym release pin still lacks block exchange. Testing uses its local checkout.
- Whole-worktree typechecking reports scratch-file and dependency errors. The generic integration file has ten errors in untouched code.
- The full H100 suite cannot import torchvision locally because torchvision::nms is missing. Its existing Qwen3.5 import triggers the failure.

stack-info: PR: #5746, branch: fegin/stack/6
@fegin
fegin changed the base branch from fegin/stack/4 to fegin/stack/5 November 2, 2026 21:38
STATUS=0
if [[ "${GPU_ARCH_TYPE}" != "rocm" ]]; then
if ! NCCL_NVLS_ENABLE=0 python -m pytest \
tests/unit_tests/gpu/models/common/test_varlen_selective_gather.py -v; then

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.

why adding this to CI integration tests?

return input_dict


def cp_query_ranges(

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.

can we unify get_token_fragments and this function?

] = WeakValueDictionary()


def get_copy_engine_block_exchange(

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.

I wonder whether you should define this in attn_gym? similar to linear attention

fegin added a commit that referenced this pull request Nov 3, 2026
Stacked PRs:
 * #5746
 * #5745
 * #5744
 * #5743
 * __->__#5742


--- --- ---

[docs] Clarify PyTorch library ownership

## Summary (human-written)
Agents are confused by what "PyTorch libraries" means. They may treat
meta-pytorch repos as non-pytorch repo and request changes if we
use repos in the core parallelisms, which violates one of the core
principal.

## Why
The dependency rule does not define PyTorch libraries. This can
incorrectly exclude libraries such as meta-pytorch/attention-gym.

## What changed
- Count pytorch/pytorch and meta-pytorch repos as PyTorch libraries.
- Keep complex techniques upstream, in pytorch/pytorch or a suitable
meta-pytorch repo.

## Testing
Documentation only. `pre-commit run --files .claude/CLAUDE.md` passes.
fegin added a commit that referenced this pull request Nov 3, 2026
Stacked PRs:
 * #5746
 * #5745
 * #5744
 * __->__#5743
 * #5742


--- --- ---

[tools] Fix CUDA Graph dependency arrows

## Summary (human-written)
Fix a bug of cudagraph dependency arrow. The AI summary shows an example
that can cause errors. This PR fixes the issue.

## Why
The trace compactor matches GPU dependency arrows to kernel start times.
An arrow's source is at the source kernel's end. This can attach the
arrow to the next kernel or make compaction fail.

```text
Kernel A: [10, 12]
Kernel B: [12, 14]
At time 12, an arrow source belongs to A and a destination belongs to B.
```

## What changed
- Match GPU arrow sources to slice ends and destinations to slice
starts.
- Accept one adjacent floating-point value when matching a source
timestamp. This handles rounding in timestamp + duration.
- Keep errors for endpoints that cannot be matched.

## Numerics / performance
This tool processes saved profiler traces. Kernel timestamps and
durations are preserved. Training code is outside the change.

## Testing
- Six tests pass: `python -m unittest discover -s
.claude/skills/cuda_graph_trace_compaction/scripts -p
test_compact_cuda_graph_trace.py`.
- The regression test checks adjacent kernels, a rounded source
timestamp, and preservation of the arrow timestamp.
- Saved Muse Glimmer trace validation maps all 4228 and 3372 GPU flow
endpoints.
@fegin
fegin changed the base branch from fegin/stack/5 to main November 3, 2026 08:07
fegin added a commit that referenced this pull request Nov 3, 2026
## Summary (human-written)
Selective gather -- only gathering the required blocks instead of doing allgather.

Integrate selective gather CP for sliding window VarlenAttn. This PR depends on
meta-pytorch/attention-gym#651.

This version assumes CP is within the same nvlink domain. A cross-nvlink domain version require the next attention-gym PR.

## Why
K/V all-gather copies tokens that sliding-window attention cannot use. Keep local K/V and gather only remote window blocks through attention-gym's copy-engine exchange.

Example: CP8, 128K tokens per rank, window 4096, block size 256:

```
All-gather K/V:         1024K tokens
Compact K/V:       at most 136K tokens
Saved remote K/V:  at most   8K tokens with full remat
```

These are buffer-size bounds. They exclude shared transport buffers and other activations. With full remat, all-gather also releases gathered K/V but fetches it again during backward. Selective gather retains halos to avoid that fetch. Model peak memory must be measured for each policy.

## What changed
- Use attention-gym's public builder for fixed contiguous or head-tail routing. Reuse exchanges across matching layers. Packed document offsets can change during CUDA Graph replay.
- Save remote K/V under full remat. During backward, rebuild compact K/V from local K/V and saved halos without fetching remote K/V again.
- Check compact K/V SPMD types and load-balancer compatibility. Support no balancer and head-tail; reject PTRR. Attention-gym validates actual token-range alignment.
- Keep the generic Muse Glimmer integration on all-gather. The H100 recipe selects selective sliding attention through the same setup, with full remat and real process groups.
- Mechanical: share varlen chunk helpers with all-gather.

## User-facing changes
| Attention | Backend |
| --- | --- |
| Sliding varlen | Opt into `SelectiveGatherKVSlidingWindowVarlenInnerAttention` with contiguous or head-tail CP in one NVLink domain. |
| Full varlen | Keep `AllGatherKVVarlenInnerAttention`. |

## Numerics
Loss and grad_norm match bit-for-bit across all 20 steps, both backends, and both remat policies on job 2276942. Seed 42, deterministic mode, BF16, FA4, and CUDA Graphs. All 64 rank records and TensorBoard files agree.

## Performance
Full 52-layer Muse Glimmer, CP16 on 16 GB300s in one NVLink domain, head-tail sharding, 256K packed tokens across 17 documents capped at 16K, and 2048-token sliding windows. Full layers use all-gather in both variants. The benchmark uses this PR's public-layout code with attention-gym 38cd874 and PyTorch 087ceb5.

| Remat | Sliding backend | Step (ms) | Peak allocated (GiB) | Peak reserved (GiB) |
| --- | --- | ---: | ---: | ---: |
| Full | All-gather | 2866.2 | 43.393 | 57.793 |
| Full | Copy engine | 2701.7 | 43.545 | 57.867 |
| Inner attention | All-gather | 2404.6 | 141.706 | 159.648 |
| Inner attention | Copy engine | 2227.7 | 141.857 | 159.139 |

- Copy engine reduces step time by 5.74% under full remat and 7.36% under inner remat. Peak allocated memory increases by 0.151 GiB in each pair.
- Inner remat uses save_regions=["*"] and recompute_regions=["attention.inner_attention*"]. Projection math runs once; inner attention runs twice. Bare operations outside saved regions can replay.
- One run per case on one allocation. Timing averages the slowest rank at each of 17 graph replays. Memory peaks include build, warmup, capture, and training; symmetric-memory buffers can be outside the allocator.

## Testing
- Pass each rank's `cp_query_ranges` to attention-gym `4bc108c`. All layout and plan fields match the benchmark builder across 12,496 rank-specific cases, including the full CP16 benchmark shape. Copy-engine source is unchanged. GPU checks and performance results use attention-gym `38cd874`.
- 75 TorchTitan CPU tests pass. They cover varlen attention, exchange sharing, fixed-layout rejection, remat regions, and saved K/V lifetime. Two shipped-recipe tests are excluded. Routing tests live upstream; all 39 host plan tests pass.
- The four-H100 numerical suite passes all eight combinations of contiguous/head-tail, remat off/on, and window sizes 1/4. It checks outputs, gradients, shared exchanges, changed documents, and CUDA Graph replay. The one-token window works with zero remote blocks.
- Both Muse Glimmer recipes validate. The H100 recipe was checked in isolation because the full module import fails on the torchvision issue below.
- Production validation, CP attention, and context-parallel helpers pass targeted Pyrefly with one PyTorch source path. All non-typechecking pre-commit hooks pass. Whole-worktree Pyrefly reports 195 dependency and scratch-file errors.

## Known issues
- The attention-gym release pin still lacks block exchange. Testing uses its local checkout.
- Whole-worktree typechecking reports scratch-file and dependency errors. The generic integration file has ten errors in untouched code.
- The full H100 suite cannot import torchvision locally because torchvision::nms is missing. Its existing Qwen3.5 import triggers the failure.

stack-info: PR: #5746, branch: fegin/stack/6
fegin added a commit that referenced this pull request Nov 3, 2026
## Summary (human-written)
Selective gather -- only gathering the required blocks instead of doing allgather.

Integrate selective gather CP for sliding window VarlenAttn. This PR depends on
meta-pytorch/attention-gym#651.

This version assumes CP is within the same nvlink domain. A cross-nvlink domain version require the next attention-gym PR.

## Why
K/V all-gather copies tokens that sliding-window attention cannot use. Keep local K/V and gather only remote window blocks through attention-gym's copy-engine exchange.

Example: CP8, 128K tokens per rank, window 4096, block size 256:

```
All-gather K/V:         1024K tokens
Compact K/V:       at most 136K tokens
Saved remote K/V:  at most   8K tokens with full remat
```

These are buffer-size bounds. They exclude shared transport buffers and other activations. With full remat, all-gather also releases gathered K/V but fetches it again during backward. Selective gather retains halos to avoid that fetch. Model peak memory must be measured for each policy.

## What changed
- Use attention-gym's public builder for fixed contiguous or head-tail routing. Reuse exchanges across matching layers. Packed document offsets can change during CUDA Graph replay.
- Save remote K/V under full remat. During backward, rebuild compact K/V from local K/V and saved halos without fetching remote K/V again.
- Check compact K/V SPMD types and load-balancer compatibility. Support no balancer and head-tail; reject PTRR. Attention-gym validates actual token-range alignment.
- Keep the generic Muse Glimmer integration on all-gather. The H100 recipe selects selective sliding attention through the same setup, with full remat and real process groups.
- Mechanical: share varlen chunk helpers with all-gather.

## User-facing changes
| Attention | Backend |
| --- | --- |
| Sliding varlen | Opt into `SelectiveGatherKVSlidingWindowVarlenInnerAttention` with contiguous or head-tail CP in one NVLink domain. |
| Full varlen | Keep `AllGatherKVVarlenInnerAttention`. |

## Numerics
Loss and grad_norm match bit-for-bit across all 20 steps, both backends, and both remat policies on job 2276942. Seed 42, deterministic mode, BF16, FA4, and CUDA Graphs. All 64 rank records and TensorBoard files agree.

## Performance
Full 52-layer Muse Glimmer, CP16 on 16 GB300s in one NVLink domain, head-tail sharding, 256K packed tokens across 17 documents capped at 16K, and 2048-token sliding windows. Full layers use all-gather in both variants. The benchmark uses this PR's public-layout code with attention-gym 38cd874 and PyTorch 087ceb5.

| Remat | Sliding backend | Step (ms) | Peak allocated (GiB) | Peak reserved (GiB) |
| --- | --- | ---: | ---: | ---: |
| Full | All-gather | 2866.2 | 43.393 | 57.793 |
| Full | Copy engine | 2701.7 | 43.545 | 57.867 |
| Inner attention | All-gather | 2404.6 | 141.706 | 159.648 |
| Inner attention | Copy engine | 2227.7 | 141.857 | 159.139 |

- Copy engine reduces step time by 5.74% under full remat and 7.36% under inner remat. Peak allocated memory increases by 0.151 GiB in each pair.
- Inner remat uses save_regions=["*"] and recompute_regions=["attention.inner_attention*"]. Projection math runs once; inner attention runs twice. Bare operations outside saved regions can replay.
- One run per case on one allocation. Timing averages the slowest rank at each of 17 graph replays. Memory peaks include build, warmup, capture, and training; symmetric-memory buffers can be outside the allocator.

## Testing
- Pass each rank's `cp_query_ranges` to attention-gym `4bc108c`. All layout and plan fields match the benchmark builder across 12,496 rank-specific cases, including the full CP16 benchmark shape. Copy-engine source is unchanged. GPU checks and performance results use attention-gym `38cd874`.
- 75 TorchTitan CPU tests pass. They cover varlen attention, exchange sharing, fixed-layout rejection, remat regions, and saved K/V lifetime. Two shipped-recipe tests are excluded. Routing tests live upstream; all 39 host plan tests pass.
- The four-H100 numerical suite passes all eight combinations of contiguous/head-tail, remat off/on, and window sizes 1/4. It checks outputs, gradients, shared exchanges, changed documents, and CUDA Graph replay. The one-token window works with zero remote blocks.
- Both Muse Glimmer recipes validate. The H100 recipe was checked in isolation because the full module import fails on the torchvision issue below.
- Production validation, CP attention, and context-parallel helpers pass targeted Pyrefly with one PyTorch source path. All non-typechecking pre-commit hooks pass. Whole-worktree Pyrefly reports 195 dependency and scratch-file errors.

## Known issues
- The attention-gym release pin still lacks block exchange. Testing uses its local checkout.
- Whole-worktree typechecking reports scratch-file and dependency errors. The generic integration file has ten errors in untouched code.
- The full H100 suite cannot import torchvision locally because torchvision::nms is missing. Its existing Qwen3.5 import triggers the failure.

stack-info: PR: #5746, branch: fegin/stack/6
@fegin
fegin changed the base branch from main to fegin/stack/5 November 3, 2026 08:08
fegin added a commit that referenced this pull request Nov 3, 2026
Stacked PRs:
 * #5746
 * #5745
 * #5744
 * __->__#5771


--- --- ---

[tools] Fix CUDA Graph dependency arrows

Reland #5743, accidentally
land #5743 to an incorrect branch.

## Summary (human-written)
Fix a bug of cudagraph dependency arrow. The AI summary shows an example
that can cause errors. This PR fixes the issue.

## Why
The trace compactor matches GPU dependency arrows to kernel start times.
An arrow's source is at the source kernel's end. This can attach the
arrow to the next kernel or make compaction fail.

```text
Kernel A: [10, 12]
Kernel B: [12, 14]
At time 12, an arrow source belongs to A and a destination belongs to B.
```

## What changed
- Match GPU arrow sources to slice ends and destinations to slice
starts.
- Accept one adjacent floating-point value when matching a source
timestamp. This handles rounding in timestamp + duration.
- Keep errors for endpoints that cannot be matched.

## Numerics / performance
This tool processes saved profiler traces. Kernel timestamps and
durations are preserved. Training code is outside the change.

## Testing
- Six tests pass: `python -m unittest discover -s
.claude/skills/cuda_graph_trace_compaction/scripts -p
test_compact_cuda_graph_trace.py`.
- The regression test checks adjacent kernels, a rounded source
timestamp, and preservation of the arrow timestamp.
- Saved Muse Glimmer trace validation maps all 4228 and 3372 GPU flow
endpoints.
@fegin
fegin changed the base branch from fegin/stack/5 to main November 3, 2026 17:30
fegin added a commit that referenced this pull request Nov 3, 2026
## Summary (human-written)
Selective gather -- only gathering the required blocks instead of doing allgather.

Integrate selective gather CP for sliding window VarlenAttn. This PR depends on
meta-pytorch/attention-gym#651.

This version assumes CP is within the same nvlink domain. A cross-nvlink domain version require the next attention-gym PR.

## Why
K/V all-gather copies tokens that sliding-window attention cannot use. Keep local K/V and gather only remote window blocks through attention-gym's copy-engine exchange.

Example: CP8, 128K tokens per rank, window 4096, block size 256:

```
All-gather K/V:         1024K tokens
Compact K/V:       at most 136K tokens
Saved remote K/V:  at most   8K tokens with full remat
```

These are buffer-size bounds. They exclude shared transport buffers and other activations. With full remat, all-gather also releases gathered K/V but fetches it again during backward. Selective gather retains halos to avoid that fetch. Model peak memory must be measured for each policy.

## What changed
- Use attention-gym's public builder for fixed contiguous or head-tail routing. Reuse exchanges across matching layers. Packed document offsets can change during CUDA Graph replay.
- Save remote K/V under full remat. During backward, rebuild compact K/V from local K/V and saved halos without fetching remote K/V again.
- Check compact K/V SPMD types and load-balancer compatibility. Support no balancer and head-tail; reject PTRR. Attention-gym validates actual token-range alignment.
- Keep the generic Muse Glimmer integration on all-gather. The H100 recipe selects selective sliding attention through the same setup, with full remat and real process groups.
- Mechanical: share varlen chunk helpers with all-gather.

## User-facing changes
| Attention | Backend |
| --- | --- |
| Sliding varlen | Opt into `SelectiveGatherKVSlidingWindowVarlenInnerAttention` with contiguous or head-tail CP in one NVLink domain. |
| Full varlen | Keep `AllGatherKVVarlenInnerAttention`. |

## Numerics
Loss and grad_norm match bit-for-bit across all 20 steps, both backends, and both remat policies on job 2276942. Seed 42, deterministic mode, BF16, FA4, and CUDA Graphs. All 64 rank records and TensorBoard files agree.

## Performance
Full 52-layer Muse Glimmer, CP16 on 16 GB300s in one NVLink domain, head-tail sharding, 256K packed tokens across 17 documents capped at 16K, and 2048-token sliding windows. Full layers use all-gather in both variants. The benchmark uses this PR's public-layout code with attention-gym 38cd874 and PyTorch 087ceb5.

| Remat | Sliding backend | Step (ms) | Peak allocated (GiB) | Peak reserved (GiB) |
| --- | --- | ---: | ---: | ---: |
| Full | All-gather | 2866.2 | 43.393 | 57.793 |
| Full | Copy engine | 2701.7 | 43.545 | 57.867 |
| Inner attention | All-gather | 2404.6 | 141.706 | 159.648 |
| Inner attention | Copy engine | 2227.7 | 141.857 | 159.139 |

- Copy engine reduces step time by 5.74% under full remat and 7.36% under inner remat. Peak allocated memory increases by 0.151 GiB in each pair.
- Inner remat uses save_regions=["*"] and recompute_regions=["attention.inner_attention*"]. Projection math runs once; inner attention runs twice. Bare operations outside saved regions can replay.
- One run per case on one allocation. Timing averages the slowest rank at each of 17 graph replays. Memory peaks include build, warmup, capture, and training; symmetric-memory buffers can be outside the allocator.

## Testing
- Pass each rank's `cp_query_ranges` to attention-gym `4bc108c`. All layout and plan fields match the benchmark builder across 12,496 rank-specific cases, including the full CP16 benchmark shape. Copy-engine source is unchanged. GPU checks and performance results use attention-gym `38cd874`.
- 75 TorchTitan CPU tests pass. They cover varlen attention, exchange sharing, fixed-layout rejection, remat regions, and saved K/V lifetime. Two shipped-recipe tests are excluded. Routing tests live upstream; all 39 host plan tests pass.
- The four-H100 numerical suite passes all eight combinations of contiguous/head-tail, remat off/on, and window sizes 1/4. It checks outputs, gradients, shared exchanges, changed documents, and CUDA Graph replay. The one-token window works with zero remote blocks.
- Both Muse Glimmer recipes validate. The H100 recipe was checked in isolation because the full module import fails on the torchvision issue below.
- Production validation, CP attention, and context-parallel helpers pass targeted Pyrefly with one PyTorch source path. All non-typechecking pre-commit hooks pass. Whole-worktree Pyrefly reports 195 dependency and scratch-file errors.

## Known issues
- The attention-gym release pin still lacks block exchange. Testing uses its local checkout.
- Whole-worktree typechecking reports scratch-file and dependency errors. The generic integration file has ten errors in untouched code.
- The full H100 suite cannot import torchvision locally because torchvision::nms is missing. Its existing Qwen3.5 import triggers the failure.

stack-info: PR: #5746, branch: fegin/stack/6
@fegin
fegin changed the base branch from main to fegin/stack/43 November 20, 2026 18:02
@fegin
fegin changed the base branch from fegin/stack/43 to main November 23, 2026 08:13
@fegin
fegin changed the base branch from main to fegin/stack/43 November 23, 2026 08:14
@fegin
fegin changed the base branch from fegin/stack/43 to main November 23, 2026 08:42
@fegin
fegin changed the base branch from main to fegin/stack/42 November 23, 2026 08:43
fegin added a commit that referenced this pull request Nov 23, 2026
Stacked PRs:
 * #6252
 * #5746
 * #6135
 * #6134
 * #6133
 * #6132
 * #5882
 * __->__#5881


--- --- ---

### [optim] Keep Adam moments in pinned host memory (zero-copy)


## Summary (human-written)
This PR implements CPU offloading for fused Adam/AdamW. We keep the
moments in
pinned memory and never allocate GPU memory for them. Instead, we feed
the pinned
memory data pointer to the CUDA tensor. So the fused op will directly
use the tensor assuming the tensor data is on GPU memory.

So the CPU <-> GPU reads and writes and the computation are all
initiated through one
single kernel. And the overlapping comes from the kernel pipeline
itself.

Compared to PR #5749, this approach requires less GPU memory and the
performance is better. See the **Alternatives** below.

We now use `preserve_state_dtype_on_load` in TorchTitan. This preserves
the dtype, so we don't need to install a hook for bf16 moments. The hook
also made a temporary fp32 copy of every moment in GPU memory during
load.

## Why
Adam moments can be the last thing that does not fit on the GPU. Muse
Spark 816B with DP8/CP8/EP64 and 32K sequence length runs out of memory
in the first `optimizer.step()` with device moments. The check uses a
fake process group (fake PG): one GB300 GPU runs rank 0 of a 64-GPU
layout. Step 1 forward and backward finish, then Adam fails to allocate
`exp_avg` (tried to allocate 512 MiB with 155 MiB free of 276.6 GiB). PR
#5749 offloads the moments, but it streams them through two GPU slots
with side-stream copies and needs a custom state_dict/load_state_dict.

This change keeps `exp_avg` and `exp_avg_sq` of a chosen share of the
parameters in pinned CPU memory and exposes them to CUDA as tensors that
alias that memory. The unchanged fused kernel reads and writes them in
place over the host link.

**Example.**

```python
# Before: moments live on the GPU. The 64-GPU Muse Spark run OOMs in optimizer.step().
# After:
optimizers = config.optim.optimizer.optimizers
optimizers[0] = replace(optimizers[0], moment_cpu_offload_fraction=1.0)
# Launch with: PYTORCH_ALLOC_CONF="expandable_segments:True,pinned_max_round_threshold_mb:1" ./run_train.sh ...
# Moments use no GPU memory. The step stays one fused kernel launch on fixed addresses.
# A fraction such as 0.5 offloads only part of the moments and costs less step time.
```

## What changed
**Config**
- Adam and AdamW get `moment_cpu_offload_fraction: float` (default
`0.0`). 0.0 keeps all moments on the device, 1.0 offloads all, and a
value in between offloads that share of the local moment bytes.
- The unit is a whole parameter. Parameters are taken in optimizer order
until the offloaded moment bytes reach the fraction of all local moment
bytes. FSDP shards evenly and experts have equal sizes, so ranks usually
pick the same parameters.
- Offloaded and device moments share one param group and one fused AdamW
call.
- Add `pinned_max_round_threshold_mb:1` to `PYTORCH_ALLOC_CONF` when
offloading moments (Moment allocation).
- `TrainingEngine` applies NUMA binding before any pinned allocation, so
no launcher flag is needed.

**Moment allocation**
- The moments and `step` of offloaded parameters are created at
optimizer construction. The moments are `torch.zeros(...,
pin_memory=True)` CPU tensors; `step` stays a device tensor. The other
parameters get device moments lazily, as before.
- There are no chunks, slots, side streams, or events. The step stays
one kernel launch on fixed addresses and is CUDA-graph capturable.
- DTensor params get DTensor moments with the same mesh and placements,
so DCP saves and reshards them like device moments.
- Empty shards are never offloaded. They need no memory.
- By default, PyTorch's caching host allocator rounds each allocation up
to a power of two, using up to 2x host memory.
`pinned_max_round_threshold_mb` (pytorch/pytorch#171662) turns that off
above the threshold. With `pinned_max_round_threshold_mb:1`, allocations
above 1 MB are pinned at their exact size. After allocating, the
optimizer compares the pinned bytes in `torch.cuda.host_memory_stats()`
with the requested bytes. If rounding wasted more than 1 GiB, it raises
`ValueError` that names the setting to add
(`pinned_max_round_threshold_mb:1` in `PYTORCH_ALLOC_CONF`).
- The offloading code lives in a new
`torchtitan/components/optim/offloading.py`. `optimizer.py` only
validates the config and calls `init_cpu_offloaded_moments`.
- New `as_dtensor_like` in `torchtitan/distributed/utils.py` wraps a
local shard as a DTensor with a parameter's mesh, placements, and shape.
The offloaded moments use it, and so does `EMA._materialize_dtensor`,
which had the same code. EMA behavior is unchanged (mechanical). The
CUDA view of pinned memory still uses `__cuda_array_interface__`,
because PyTorch has no API for it.

**State dict**
- `optimizer.state_dict()` returns each moment as the CPU tensor over
its pinned memory (a DTensor with the parameter's mesh and placements,
built without a copy). `OptimizersContainer.state_dict()` goes through
it, so every checkpointer sees CPU tensors and copies the moments on the
CPU. On one Grace socket, a CPU copy runs at 362 GB/s with 32 threads; a
CUDA copy between two host buffers is synchronous and runs at 45-47
GB/s. With torch_checkpointing async saves on the 64-GPU fake-PG run,
the CUDA copies made the step after each save 1.5 s slower.
- A load pre-hook swaps the CPU tensors back to the CUDA moments, so
`Optimizer.load_state_dict` keeps them and does not move them to the
GPU. Loaded values that are other tensors are first copied into the CUDA
moments on the stream, after any pending optimizer step. DCP and
torch_checkpointing load in place into the CPU tensors, so no copy
happens there.
- Device moments keep the default state dict and load behavior.
- Checkpointers copy CPU tensors on the host, outside stream order. So
`state_dict()` first waits for the current stream, and the copy starts
only after the queued optimizer step has written the moments. This
covers every checkpointer (DCP sync, async, and async_with_pinned_mem,
and torch_checkpointing) and costs one device sync per save.

**Checkpoint load**
- DCP loads into the pinned buffers, so load makes no temporary device
copy.
- `load_flat_optim_state_dict` calls `Optimizer.load_state_dict` under
`torch.optim.preserve_state_dtype_on_load()` (pytorch/pytorch#201779).
Without it, `load_state_dict` casts bf16 moments to new fp32 tensors in
GPU memory.
- Buffer addresses never change, so a captured optimizer graph stays
valid.
- Checkpoints are interchangeable between any two fractions.
- The bf16 moment load post-hook (`restore_moment_dtype`) is removed.
Under `preserve_state_dtype_on_load()`, DCP loads into the bf16 moments
and they keep their dtype, so the hook did nothing; before, load cast
each bf16 device moment to a new fp32 GPU tensor and the hook cast it
back. `BF16_OPTIMIZER_STATES.md` describes the load without it.

**Lifetime**
- When the last tensor that uses a pinned buffer is freed, a device
synchronize runs first, so in-flight kernels finish before the caching
host allocator can reuse the memory.
- The synchronize is skipped at interpreter exit.

**Rejected with ValueError**
- A fraction outside [0, 1] (config time).
- A fraction above 0 with `fused=False` (config time).
- A fraction above 0 on an accelerator other than CUDA, including ROCm
(config time). A host without an accelerator can still build the config,
so CPU recipe tests work.
- Offloaded params not on CUDA, such as `fsdp_enable_cpu_offloading` and
`create_seed_checkpoint` runs (construction).
- Non-contiguous local shards of offloaded params (construction). The
error names the parameter.
- Pinned memory rounded up by more than 1 GiB (construction).
- TorchFT with a fraction above 0 (config time, in
`torchtitan/experiments/torchft/optimizer.py`). Replica recovery loads a
peer's state by assignment, which would replace the pinned moments with
device tensors.

**Docs**
- `torchtitan/components/optim/CPU_OFFLOADED_MOMENTS.md`: usage, how to
choose the fraction, the allocator setting and its check, cost formula,
NUMA binding, and requirements. The benchmark tables stay in this
description.

## Alternatives considered
- PR #5749 streams the moments through two GPU slots with side-stream
copies. This change keeps them in place, so it needs no slot memory, no
stream or event bookkeeping, and no custom state_dict/load_state_dict.
It also uses 2 GiB less peak memory and gets +2.5% tps (table below).
- Managed (pageable) host memory instead of pinned. In a GB300 copy
microbenchmark (not a training run) it matched pinned. Pinned memory
needs no ATS or page-migration support, so it does not depend on the
host's paging behavior.

## Numerics / performance
Cost on a run that fits both ways (Muse Spark 816B,
`muse_spark_816b_a42b_dist_moe_bf16_spmd_256_fake`, 256-GPU fake PG,
DP16/TP4/CP4/EP64, 96K, one GB300 GPU runs rank 0, NUMA-bound, steps
4-10):

| | device | all offloaded |
|---|---|---|
| peak reserved memory | 253.06 GiB | 228.84 GiB (-24.2 GiB) |
| tps | 3,301 | 3,273 (-0.85%) |
| AdamW per step (mean of steps 4-9) | 26.2 ms | 166.5 ms (about 1.1% of
a 15 s step) |

Losses follow the same curve (2.644 vs 2.641 at step 10).

Vs PR #5749 on a run that only fits with offload (Muse Spark 816B,
64-GPU fake PG, DP8/CP8/EP64, 32K, one GB300 GPU runs rank 0,
NUMA-bound):

| | no offload | PR #5749 | this change |
|---|---|---|---|
| peak memory | OOM in optimizer.step() | 257.12 GiB | 255.12 GiB |
| tps (steps 4-10) | - | 2,906 | 2,979 |
| optimizer span (trace) | - | 932 ms | 656 ms |

Host link traffic:
- Each step moves about 16 bytes per local parameter over the host link
for fp32 moments.
- On the 64-GPU run on one GB300 GPU, AdamW moves 2 x 104 GB. AdamW
alone takes 0.63 s (about 330 GB/s), 5.8% of the step (one synchronized
measurement). This is close to the host link limit.
- NUMA binding matters when copies run in both directions. On GB300 with
four GPUs busy and no NUMA binding, copies in both directions at once
dropped about 2-2.5x, from 86-111 GB/s to 44 GB/s. Host-to-device copies
alone dropped 1.0-1.8x.
- With both GPUs of a Grace socket running the step at the same time,
AdamW takes about 2x longer, because they share the socket's host
bandwidth. The training step was only about 6% slower in that run.

Numerics: pinned host moments match device moments bitwise, for full and
partial offload (Testing).

## Testing
- GPU unit test
`tests/unit_tests/gpu/components/optim/test_adam_cpu_offloaded_moments.py`
(2 GPUs, FSDP2, fp32 and bf16 moments). It catches: loss of bitwise
parity with device moments for fractions 0.25 and 1.0, moments that use
device memory, a broken empty shard, and a fraction that pins the wrong
parameters (0.25 must pin exactly the first weight). It catches pinned
memory silently rounded up to a power of two. It also checks DCP async
save of mixed pinned and device moments with the checkpointer's stager
options, and load into all-pinned and all-device moments. `state_dict()`
must return CPU tensors over the pinned memory for offloaded moments.
Load must keep the same buffers, restore values exactly, allocate no
temporary device copy, copy other loaded tensors into the same buffers,
keep the moment dtype, and continue training bitwise identically.
- CPU unit test `test_moment_options_checked_at_config_time`. It catches
bf16 or pinned host moments silently using a non-fused kernel, a
fraction outside [0, 1], and pinned host moments on ROCm or another
non-CUDA accelerator.
- bf16 device-moment resume on 2xH100 is bitwise equal to the
uninterrupted run.
- Integration test: `pp_dp_tp` (FSDP2+TP2+PP2, save then resume) saves
device moments and resumes with fraction 0.5, so half the moments go to
pinned host memory, and skips ROCm. No existing CUDA-only integration
test does save and resume, so this drops ROCm coverage of this PP+DP+TP
save/resume test. `full_checkpoint` and `optional_checkpoint` keep
device moments and still run save/resume on ROCm. `pp_dp_tp` needs 8
GPUs and was not run here. The 4-GPU bitwise resume checks below
(FSDP2+TP2, PP2+FSDP2) cover the same paths.
- Resume check with the trainer, on a 4-GPU host: llama3 debug model
with flex attention, 10 steps, async_with_pinned_mem checkpoint at step
5, seed 42, deterministic, NCCL_ALGO=Ring NCCL_NVLS_ENABLE=0. Resuming
from step 5 gives bitwise identical loss and grad_norm (TensorBoard) to
the uninterrupted run. Pinned host moments match device moments bitwise.
Checked for FSDP2, FSDP2+TP2, PP2+FSDP2, FSDP2 with bf16 moments, and
FSDP2 with the optimizer CUDA graph. These runs and the performance
numbers above used full offload with `cudaHostRegister` allocation;
partial offload and the `pin_memory` allocation were checked only by the
unit tests.

## Known issues / follow-ups
- Varlen attention and NVLS were not run-to-run deterministic in our
runs, even with device moments. The resume checks use flex attention and
NVLS off for that reason.
- Needs a PyTorch nightly from 2026-10-30 or later for
`torch.optim.preserve_state_dtype_on_load` (pytorch/pytorch#201779).
Every optimizer checkpoint load calls it, also with
`moment_cpu_offload_fraction=0`. Older PyTorch raises `AttributeError`
on resume. The release-validation jobs pin torch 2.15.0, so a torchtitan
release with this change must validate against a newer torch.
- Two TODOs mark private or undocumented PyTorch behavior (the
`DTensor(local, spec)` constructor and `__cuda_array_interface__` over
pinned host memory); their upstream issues are not filed yet.
@fegin
fegin changed the base branch from fegin/stack/42 to main November 23, 2026 17:34
@fegin
fegin changed the base branch from main to fegin/stack/42 November 23, 2026 17:34
@fegin
fegin changed the base branch from fegin/stack/42 to main November 30, 2026 22:53
@fegin
fegin changed the base branch from main to fegin/stack/42 November 30, 2026 22:54
@fegin
fegin marked this pull request as ready for review November 30, 2026 22:55
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 30, 2026
@fegin
fegin marked this pull request as draft November 30, 2026 23:07
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 30, 2026
## Summary (human-written)
Selective gather -- only gathering the required blocks instead of doing allgather.

Integrate selective gather CP for sliding window VarlenAttn. This PR depends on
meta-pytorch/attention-gym#651.

This version assumes CP is within the same nvlink domain. A cross-nvlink domain version require the next attention-gym PR.

## Why
K/V all-gather copies tokens that sliding-window attention cannot use. Keep local K/V and gather only remote window blocks through attention-gym's copy-engine exchange. The measured gain is step time (5.7% under full remat and 7.4% under inner remat, Performance); peak memory does not drop, as explained below.

Example: CP8, 128K tokens per rank, window 4096, block size 256:

```
All-gather K/V:         1024K tokens
Compact K/V:       at most 136K tokens
Saved remote K/V:  at most   8K tokens with full remat
```

These are buffer-size bounds. They exclude shared transport buffers and other activations. With full remat, all-gather also releases gathered K/V but fetches it again during backward. Selective gather retains halos to avoid that fetch. Model peak memory must be measured for each policy. In the benchmark below, peak allocated memory is 0.151 GiB higher with selective gather: model peak is set by other activations, and the shared transport buffers add a little.

## What changed
- Use attention-gym's public builder for fixed contiguous or head-tail routing. Reuse exchanges across matching layers. Packed document offsets can change during CUDA Graph replay.
- Save remote K/V under full remat. During backward, rebuild compact K/V from local K/V and saved halos without fetching remote K/V again.
- Check compact K/V SPMD types and load-balancer compatibility. Support no balancer and head-tail; reject PTRR.
- Config validation checks that each CP chunk holds whole `gather_block_size` blocks (`num_tokens_per_microbatch_per_dp_rank` divisible by CP chunks x block size), so a bad size fails before the first forward.
- Keep the generic Muse Glimmer integration on all-gather. The H100 recipe selects selective sliding attention through the same setup, with full remat and real process groups.
- The copy-engine exchange cache lives next to its only caller in `cp_attention.py`. A layer checks only its CP group and head-tail flag; attention-gym checks the K/V shapes and dtype on every exchange.
- Mechanical: share varlen chunk helpers with all-gather.

## User-facing changes
| Attention | Backend |
| --- | --- |
| Sliding varlen | Opt into `SelectiveGatherKVSlidingWindowVarlenInnerAttention` with contiguous or head-tail CP in one NVLink domain. |
| Full varlen | Keep `AllGatherKVVarlenInnerAttention`. |

## Numerics
Loss and grad_norm match bit-for-bit across all 20 steps, both backends, and both remat policies . Seed 42, deterministic mode, BF16, FA4, and CUDA Graphs. All 64 rank records (4 runs x 16 ranks) and TensorBoard files agree.

## Performance
Full 52-layer Muse Glimmer, CP16 on 16 GB300s in one NVLink domain, head-tail sharding, 256K packed tokens across 17 documents capped at 16K, and 2048-token sliding windows. Full layers use all-gather in both variants. The benchmark uses this PR's public-layout code with the attention-gym code of meta-pytorch/attention-gym#651 and PyTorch 087ceb5.

| Remat | Sliding backend | Step (ms) | Peak allocated (GiB) | Peak reserved (GiB) |
| --- | --- | ---: | ---: | ---: |
| Full | All-gather | 2866.2 | 43.393 | 57.793 |
| Full | Copy engine | 2701.7 | 43.545 | 57.867 |
| Inner attention | All-gather | 2404.6 | 141.706 | 159.648 |
| Inner attention | Copy engine | 2227.7 | 141.857 | 159.139 |

- Copy engine reduces step time by 5.74% under full remat and 7.36% under inner remat. Peak allocated memory increases by 0.151 GiB in each pair.
- Inner remat uses save_regions=["*"] and recompute_regions=["attention.inner_attention*"]. Projection math runs once; inner attention runs twice. Bare operations outside saved regions can replay.
- One run per case on one allocation. Timing averages the slowest rank at each of 17 graph replays. Memory peaks include build, warmup, capture, and training; symmetric-memory buffers can be outside the allocator.

## Testing
- Pass each rank's `cp_query_ranges` to the attention-gym plan builder of meta-pytorch/attention-gym#651. All layout and plan fields match the benchmark builder across 12,496 rank-specific cases, including the full CP16 benchmark shape. GPU checks and performance results use the same attention-gym PR.
- 75 TorchTitan CPU tests pass. They cover varlen attention, exchange sharing, fixed-layout rejection, remat regions, and saved K/V lifetime. Two shipped-recipe tests are excluded. Routing tests live upstream; all 39 host plan tests pass.
- The four-H100 numerical suite passes all eight combinations of contiguous/head-tail, remat off/on, and window sizes 1/4. It checks outputs, gradients, shared exchanges, changed documents, and CUDA Graph replay. The one-token window works with zero remote blocks.
- Both Muse Glimmer recipes validate.
- Production validation, CP attention, and context-parallel helpers pass targeted Pyrefly with one PyTorch source path. All non-typechecking pre-commit hooks pass.

## Known issues
- Depends on meta-pytorch/attention-gym#651 (selective gather); the attention-gym pin bump lands separately. Until then, the pinned release lacks `attn_gym.distributed.selective_gather`.
- torchtitan does not check that CP ranks share one NVLink domain. One domain can span hosts (GB300 NVL72), so a same-host check would reject valid layouts. The attention-gym symmetric-memory setup is where a bad layout fails.

stack-info: PR: #5746, branch: fegin/stack/6

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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