Repository navigation
[CP] Support Ulysses CP when CP is larger than the number of KV heads - #6285
Conversation
67aa463 to
9be42c2
Compare
| k_THK = k_THK.repeat_interleave(num_copies, dim=_HEAD_DIM) | ||
| v_THV = v_THV.repeat_interleave(num_copies, dim=_HEAD_DIM) |
There was a problem hiding this comment.
Without specifying output_size, repeat_interleave causes d2h sync.
There was a problem hiding this comment.
seems it will not, as num_copies is already a python int on cpu.
There was a problem hiding this comment.
Yes, if this is an integer, not a tensor, it is not going to causes a d2h sync.
|
@claude review this PR |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The KV head copy is the smallest correct way to run Ulysses with fewer KV heads than CP ranks: the divisible case is unchanged, and the copy order matches GQA's h // group mapping. A maintainer still needs to review, since this touches models/common and config validation.
What this PR does. When a TP rank holds fewer KV heads than there are CP ranks, UlyssesInnerAttention repeats each local KV head cp / local_kv times, with the copies next to each other, before the token-to-head all-to-all. After the all-to-all, each CP rank holds one KV head, and it is the one its query heads use. Validation now accepts this case for full-attention Ulysses (n_kv_heads | tp*cp and tp | n_kv_heads). GDN, KDA, and MLA Ulysses keep the strict rule.
Example. Qwen3.5 9B shape, 16 Q heads, 4 KV heads, TP 1, CP 8:
main: ValueError n_kv_heads (4) must be divisible by ... (8)
PR: k (T/8, 4, K) -> repeat_interleave(2) -> [kv0 kv0 kv1 kv1 kv2 kv2 kv3 kv3]
a2a -> rank r: Q heads {2r, 2r+1}, KV copy r -> kv head r // 2
GQA group = 16/4 = 4 -> Q head 2r uses kv head 2r // 4 = r // 2 (match)
With TP 2 x CP 4 and the same heads: each TP rank has 8 Q heads and 2 KV heads, and gets 2 copies per KV head. CP rank r gets Q heads {2r, 2r+1}, which map to local KV head r // 2, the same head as copy r.
Must fix
cp_attention.py:523-- @tianyu-l's comment about a D2H sync fromrepeat_interleavehas no reply yet. I don't think the sync happens here.repeatsis a Python int, so this dispatches to the scalar overload (repeat_interleave.self_int). ATen implements that overload asunsqueeze -> expand -> clone -> flattenand never reads device memory. The sync, and the need foroutput_size, only arise with a tensorrepeats, as ingpt_oss/moe.py:66. Please reply on the thread. If the maintainer wants the absence of a sync to be obvious from the code,k_THK.unsqueeze(2).expand(-1, -1, num_copies, -1).flatten(1, 2)gives the same result.
Should consider
validation.py:317-321-- the error message points GDN, KDA, and MLA users to a relaxed rule they can't use, and uses different wording from then_headsmessage right above it (inline).
Details
- Gate. The problem is real on
main: Qwen3.5 9B with Ulysses at CP 8 is rejected. The PR measures K/V all-gather imbalance with packed documents (min-max flash kernel time 278-525 ms vs 352-369 ms with KV copies) and a 14% step-time gain. No overlapping open PR, and nothing indirection.mdmoves away from Ulysses. - Runtime guard.
num_kv_heads < cp_group.size()relies on validation guaranteeingcp % local_kv == 0.validate_context_parallelruns from the trainer config's__post_init__, so a runtime assert would only duplicate it. - Backward. The gradient of
repeat_interleavesums over the copies, so dK/dV come out correct. The extra all-to-all bytes on K/V arenum_copiesx, and the PR accounts for them (11-29 ms). - Tests. In the TP2 x CP2 integration config each TP rank has 1 local KV head, so tiled and adjacent copies are identical there. The CPU unit test (
(16,4,1,8),(16,4,2,4)) is what catches arepeatregression, so it earns its place. Replacing the CP2 entry with TP2 x CP2 keeps the plain-CP coverage and adds the harder case. n_kv_heads % tpclause. It is needed: the generic TP check only rejectsn_kv_heads % tp != 0for fusedqkv_linear. Separate K/V projections may shard head features instead, which would break the per-rank head count Ulysses assumes.
Not verified: the multimodal TP2 x CP2 integration config end to end (the PR says only the text dataset was run locally); the claim that the int-repeats repeat_interleave doesn't sync rests on the ATen source, and I did not run it here.
9be42c2 to
4878212
Compare
4878212 to
50fa448
Compare
## Summary (human-written)
Ulysses usually cannot work when the number of KV heads is smaller than the CP degree. However, in certain cases, Ulysses is still the best choice for full attention -- very long context on slower GPUs, which makes computation the dominant factor. In such a case, a slight imbalance can cause a dramatic slowdown.
This PR lets Ulysses support the case where the number of KV heads is smaller than the CP degree by replicating KV heads.
## Why
Ulysses CP all-to-alls Q/K/V from sequence-sharded to head-sharded, so every CP rank needs whole KV heads. Validation requires `n_kv_heads % (tp * cp) == 0`. GQA models with few KV heads cannot use Ulysses at the CP degree they need for long context. Qwen3.5 9B has 16 Q heads and 4 KV heads, so Ulysses with CP 8 is rejected. The only option left is K/V all-gather CP, whose head-tail balancing breaks once a row holds several packed documents (1.9x attention imbalance across ranks, measured below).
**Example.** 16 Q heads, 4 KV heads, TP 1, CP 8:
```
main: ValueError: n_kv_heads (4) must be divisible by ... (8)
PR: k (T/8, 4, K) -> repeat_interleave(2) -> (T/8, 8, K) = [kv0 kv0 kv1 kv1 kv2 kv2 kv3 kv3]
after the all-to-all, rank r holds Q heads [2r, 2r+1] and KV head r // 2
```
GQA maps Q head h to KV head h // 4, so each rank gets the KV head its Q heads use.
## What changed
- `UlyssesInnerAttention` repeats each local KV head `cp / n_kv_heads` times (adjacent copies) before the all-to-all. The divisible case takes no new code path.
- Config validation accepts full-attention Ulysses when `n_kv_heads` divides `tp * cp` and is divisible by `tp`. GDN, KDA, and MLA Ulysses keep the strict rule.
- The rule is documented in the `UlyssesInnerAttention` docstring; the Qwen3.5 README points to it.
## Alternatives considered
- K/V all-gather CP: works today, but attention work is uneven across ranks with packed documents.
- All-gather K/V within each group of ranks that share a KV head instead of copying: saves some all-to-all bytes, but adds code, and the all-to-all is only 11-29 ms per step.
## User-facing changes
| Before | After |
| --- | --- |
| Ulysses with `cp % n_kv_heads == 0`, `n_kv_heads < cp` raises `ValueError` | Runs, with KV head copies |
## Numerics
| Config | GPUs | Result |
| --- | --- | --- |
| Qwen3.5 debugmodel, Ulysses CP 2 (divisible case), seed 42, deterministic, 10 steps | 2 | loss and grad_norm bitwise identical to `b1c259cd3` |
| Qwen3.5 debugmodel, 4 Q / 2 KV heads, TP 2 x CP 2, Ulysses vs K/V all-gather | 4 | step 1 loss and grad_norm identical (12.94527 / 1.3714); later steps differ in the 4th-5th digit |
| Qwen3.5 debugmodel, 4 Q / 2 KV heads, CP 4, flex, Ulysses vs K/V all-gather | 4 | max diff 4.6e-5 loss, 3.6e-5 grad_norm over 10 steps |
Kernel check (document-masked, bf16, varlen and flex) at CP 4 and CP 8 against no-CP and an fp32 oracle: same output error as no-CP.
## Performance
8 H100, one CP 8 group, Qwen3.5 9B shape with 4 layers (2 GDN + 2 full attention), 256K tokens of packed documents, FA3, steps 6-15:
| CP method | step time | flash kernel time per rank (min-max) |
| --- | --- | --- |
| Ulysses + KV copies | 1.152 s | 352-369 ms |
| K/V all-gather, head-tail | 1.346 s | 278-525 ms |
| K/V all-gather, contiguous | 1.453 s | 143-613 ms |
## Testing
- CPU unit test: per-CP-rank GQA after the KV copy matches full GQA, with and without TP. It fails if the copy is tiled (`repeat`) instead of adjacent (`repeat_interleave`).
- Validation tests: the new rule accepts `cp=4, tp=2, n_heads=16, n_kv_heads=4`, and rejects 3 KV heads at CP 4 and KV heads not divisible by TP (on Qwen3.5 attention, which has no fused QKV, so the CP check is what fires).
- The Qwen3.5 Ulysses H100 integration test now runs TP 2 x CP 2 (1 TP-local KV head copied to 2 CP ranks). It uses 4 GPUs instead of 2.
## Known issues / follow-ups
- The integration config was verified locally on the text dataset; the multimodal dataset does not load in the local env (torchvision CUDA mismatch).
stack-info: PR: #6285, branch: fegin/stack/46
50fa448 to
193a7c5
Compare
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
this approach, and what you checked yourself. -->
Fix failing CI test.
## Agent details (AI-generated, to be reviewed by @acisseJZhong)
> AI-generated by an AI agent on behalf of @acisseJZhong.
>
> **Why.** [GPU Unit
Tests](https://github.com/pytorch/torchtitan/actions/workflows/unit_test_gpu.yaml?query=branch%3Amain)
has failed on main since 2026-11-23, in two multi-GPU tests:
>
> | Test | Failure | Cause |
> | --- | --- | --- |
> |
`TestDistMuonCpuOffload::test_accelerator_ns_device_matches_gpu_resident_run`
| `No backend type associated with device type cpu` |
pytorch/pytorch#205504 (nightlies from 2026-11-23) renamed the
`DTensorTestBase` backend hook from `backend` to `backend_str`. The
test's `backend` property is now ignored, so the PG is NCCL-only and the
CPU `all_gather` in `_validate_bucket_plans_across_ranks` fails. First
red run (#6285) has no DistMuon change. |
> | `TestAdamCPUOffloadedMoments::test_rounded_pinned_memory_raises`
(new in #5881) | 300 s timeout | The first `_build` result is dropped,
so its exact-size pinned blocks can go back to the host allocator cache
and get reused by the second build, which then sees no rounding and does
not raise. When this happens on one rank only (rank 0 locally:
`AssertionError: ValueError not raised`), the other rank waits in
`destroy_pg`'s barrier and the test hangs. |
>
> **What changed.** Test-only:
> - `test_dist_muon.py`: pass the backend through
`@with_comms(backend="cpu:gloo,cuda:nccl")`, which works with PyTorch
before and after #205504, instead of overriding the hook.
> - `test_adam_cpu_offloaded_moments.py`: keep the first build alive so
the second build has to allocate new, rounded blocks.
>
> **Testing** (torch 2.16.0.dev20261123+cu132, 2x H100):
> ```
> pytest
tests/unit_tests/gpu/components/optim/test_adam_cpu_offloaded_moments.py
\
>
"tests/unit_tests/gpu/distributed/flex_shard/test_dist_muon.py::TestDistMuonCpuOffload"
> ```
> Before: both tests fail (the Adam test hung in 3/3 runs). After: 4
passed in 5/5 runs.
> `pytest tests/unit_tests/gpu -m multi_gpu` on 8x H100: these two pass.
The 5 other local failures are unrelated: they need FA3
(`flash_attn_interface`), which is not installed locally and not
selected on the A10G CI runners.
>
> **Not changed.** Several CPU tests still override `backend` (returning
`"gloo"`). Those overrides are now dead code, but they don't change
behavior on CPU runners, so they are left for a separate cleanup.
Stacked PRs:
[CP] Support Ulysses CP when CP is larger than the number of KV heads
Summary (human-written)
Ulysses usually cannot work when the number of KV heads is smaller than the CP degree. However, in certain cases, Ulysses is still the best choice for full attention -- very long context on slower GPUs, which makes computation the dominant factor. In such a case, a slight imbalance can cause a dramatic slowdown.
This PR lets Ulysses support the case where the number of KV heads is smaller than the CP degree by replicating KV heads.
Why
Ulysses CP all-to-alls Q/K/V from sequence-sharded to head-sharded, so every CP rank needs whole KV heads. Validation requires
n_kv_heads % (tp * cp) == 0. GQA models with few KV heads cannot use Ulysses at the CP degree they need for long context. Qwen3.5 9B has 16 Q heads and 4 KV heads, so Ulysses with CP 8 is rejected. The only option left is K/V all-gather CP, whose head-tail balancing breaks once a row holds several packed documents (1.9x attention imbalance across ranks, measured below).Example. 16 Q heads, 4 KV heads, TP 1, CP 8:
GQA maps Q head h to KV head h // 4, so each rank gets the KV head its Q heads use.
What changed
UlyssesInnerAttentionrepeats each local KV headcp / n_kv_headstimes (adjacent copies) before the all-to-all. The divisible case takes no new code path.n_kv_headsdividestp * cpand is divisible bytp. GDN, KDA, and MLA Ulysses keep the strict rule.UlyssesInnerAttentiondocstring; the Qwen3.5 README points to it.Alternatives considered
User-facing changes
cp % n_kv_heads == 0,n_kv_heads < cpraisesValueErrorNumerics
b1c259cd3Performance
8 H100, one CP 8 group, Qwen3.5 9B shape with 4 layers (2 GDN + 2 full attention), 256K tokens of packed documents, FA3, steps 6-15:
Testing
repeat) instead of adjacent (repeat_interleave).cp=4, tp=2, n_heads=16, n_kv_heads=4, and rejects 3 KV heads at CP 4 and KV heads not divisible by TP (on Qwen3.5 attention, which has no fused QKV, so the CP check is what fires).Known issues / follow-ups