Skip to content

[distributed] Context parallelism: padding masks, sliding windows and chunked attention with sdpa - #50512

Closed
3outeille wants to merge 25 commits into
mainfrom
cp-8-masks
Closed

3outeille wants to merge 25 commits into
mainfrom
cp-8-masks

Conversation

@3outeille

@3outeille 3outeille commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

Stack: #50493 → #50496 → #50497 → #50508 → this PR

After the all-to-all, attention sees the whole sequence, so the mask of the whole sequence can be rebuilt there. This PR rebuilds it with the masking_utils mask functions, so it matches what the model builds on an unsharded run. That lifts three refusals:

  • Padded batches: a 2D attention_mask is kept for the full sequence. sdpa gets the full mask. Flash kernels get the 2D mask and unpad, as on an unsharded run. 4D masks are still refused.
  • Sliding windows with sdpa: each layer's window comes from the sliding_window the model passes to the attention call, else module.sliding_window, else the config for layers that layer_types marks as sliding.
  • Chunked attention (llama4) with sdpa. It is still refused with flash kernels.

With sdpa, the whole-sequence mask takes batch × seq × seq booleans, so the docs recommend a flash kernel for long sequences.

Tests

tests/context_parallel, CPU (gloo). Loss, logits slice and every gradient match an unsharded run for: right and left padding, a sliding window with sdpa (unpacked and packed), a gemma3-style layer_types mix, chunked attention, and padding combined with the automatic padding to a multiple of cp_size.

CP test from #50499 on every causal LM, with the tester configs unchanged:

result classes
pass (plain and packed) 60, now including the sliding-window models (gemma3, mistral, cohere2, ministral, olmo3, exaone4, mellum, gemma4_unified, ...)
fail afmoe packed and hrm_text (both fail on an unsharded or FSDP-only run too, see #50499), gemma4_text (float32 rounding of the embedding gradient; passes at atol=1e-4)

On 2× H100 (Qwen3-0.6B, bf16), CP gives the same loss and logits as an unsharded run for batches with left and right padding (sdpa and the FA3 hub kernel), and for alternating sliding-window layers with sdpa, unpacked and packed.

`cp_size` splits every sequence across the ranks of a cp group, and `cp_implementation`
names how attention sees the whole sequence. FSDP2 now shards over `dp_size`
(`dp_replicate_size * fsdp_size * cp_size`) because the ranks of a cp group hold partial
sums of the same batch gradients.
… fsdp x cp

The dense mesh gains a `cp` axis, and its `fsdp` and `cp` axes are also exposed as one
`fsdp_cp` mesh: the ranks of a cp group hold parts of the same batch, so FSDP2 shards
parameters and reduces gradients over both.
…would break

Layers that mix tokens outside softmax attention would run on the local slice only, and
heads whose loss is not the causal-LM loss would be computed from shifted labels while
the logits stay sharded. Both are refused before the model is sharded.
…runs

`apply_context_parallelism` registers the implementation on the model's attention and hooks
the top-level forward: the pre-hook slices every sequence, label and position down to this
rank's contiguous part, and the post-hook replaces the loss by the loss of the full
sequences, which every rank reports with the gradient of the whole batch once FSDP2 averages
over the cp ranks.
`Trainer` would give a different batch to the ranks of a cp group, which expect the same one.
Use a plain training loop until its dataloader shards the sequences instead.
…ll sequences

Every rank loads a reference copy without `distributed_config` and a sharded copy, runs the
same batch and compares the loss, the logits and every gradient: plain cp, cp x fsdp,
cp x hsdp, packed sequences and ignored labels. Also covers a caller's
`num_items_in_batch`, custom and unknown implementations, the input refusals, and both
checkpoint paths.
… model

`ContextParallelTesterMixin` joins the bases of `CausalLMModelTest`, next to the FSDP and
tensor parallel mixins, so every causal language model test class runs its tester's tiny
config on 2 ranks: `cp_size=2` over the whole batch, with the loss, this rank's slice of the
logits and every gradient compared against the unsharded run. The packed variant restarts
`position_ids` mid-sequence, which the mask of every model then has to rebuild.

A tester config is only changed when the context parallel checks refuse it and the change is
harmless: the sliding-window layers, whose mask `sdpa` cannot rebuild for the whole sequence.
The change is verified by building the model from the config a checkpoint reloads, which is
the config the workers get, and a config class that validates its own fields can refuse it. A
model the checks still refuse is loaded with `cp_size=2` on both ranks and has to raise
`ValueError`; the test then skips with the reason.

The allow-list starts with 7 model types that run today. Set
`CONTEXT_PARALLEL_TEST_MODEL_TYPES = None` to run every model.
@HuggingFaceDocBuilderDev

Copy link
Copy Markdown

The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

Pages changed in this PR:

@3outeille
3outeille added this pull request to stack #50502 November 9, 2026 14:10
FSDP2 composes the mesh it shards a parameter over with the mesh the parameter is already sharded on, and torch only composes meshes built from the same root mesh. With context parallelism the sharding axis is fsdp x cp, so it is one axis of the dense root mesh and fsdp and cp are its unflattened view: the ranks, their order and the groups are unchanged, and a tp or ep mesh now composes with it.
The tp plan keeps num_heads / tp_size heads on each rank and Ulysses splits those across the cp group, so the heads and key/value heads must be divisible by cp_size * tp_size. Only pipeline and expert parallelism are still refused with context parallelism.
tp_size x cp_size on the tiny Llama: loss, this rank slice of the logits and every gradient match the unsharded run, with and without FSDP, packed and unpacked, and the gathered save reloads the reference weights. The workers now also drop the DTensor dispatch cache between tests: it is keyed by mesh, and a mesh rebuilt from the same ranks compares equal to the destroyed one.
Under cp the ranks of an ep group hold the slices of several batches, which token dispatch already handles: each rank sends the tokens of its own slice. The expert gradient divides by dp_size, which includes cp_size, so the reduced expert gradient is still the gradient of the full-sequence loss.
A tiny Qwen3 MoE against the same weights on full sequences: loss, this rank's logits slice and every gradient, with token dispatch (cp2 x ep2, cp2 x fsdp2 x ep4, cp2 x fsdp2 x ep2, cp2 x tp2 x ep4, cp2 x hsdp2 x ep2) and with the all-reduce plan (tp2 x cp2 x ep2).
Each rank has to hold the same number of positions, so the pre-hook pads the full sequences at their end: input_ids with the padding token, inputs_embeds with zeros, position_ids continuing after the last one of each row (the padding joins the last document) and labels with -100. num_items_in_batch keeps counting the real tokens.
…Ulysses context parallelism

The all-to-all gathers the sequence before every attention call, so the mask of the whole sequence can be built there
from transformers' own mask primitives: causal, packed documents, padding, sliding window and chunked attention.

- `_shard_inputs` keeps the full 2D padding mask on the implementation and passes `attention_mask=None` to the model.
- `UlyssesCP.attention` rebuilds the `sdpa` mask for the whole sequence, or returns `None` when it is plain causal so
  that the kernel relies on `is_causal`.
- flash kernels get the full 2D mask, which unpads and rebuilds the sequence boundaries.
- `UlyssesCP.check` only refuses sliding-window layers whose window is not visible at the attention call, and
  `chunked_attention` layers with a flash kernel.
…h context parallelism

- the mask rebuilt over the whole sequence is compared with the one the model builds on an unsharded run, for causal,
  packed, padded, sliding-window and chunked attention;
- right and left padding batches, a sliding-window model, a mix of sliding and full layers, and a chunked model are
  compared with the same weights on full sequences (loss, this rank's logits, every gradient);
- the flash padding test runs on 2 GPUs with `require_flash_attn`;
- the checks now accept sliding windows and chunked attention with `sdpa`, and refuse what they cannot rebuild.
Base automatically changed from cp-7-auto-pad to main November 9, 2026 14:25
@3outeille

Copy link
Copy Markdown
Member Author

Restacked after the docs moved to the end of the stack: replaced by a new PR with base cp-7-auto-pad (GitHub does not allow changing the base of this one).

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants