Skip to content

[distributed] Sequence parallelism with FSDP2 - #51003

Closed
3outeille wants to merge 22 commits into
cp-4-tester-mixinfrom
cp-4b-fsdp-x-cp
Closed

3outeille wants to merge 22 commits into
cp-4-tester-mixinfrom
cp-4b-fsdp-x-cp

Conversation

@3outeille

@3outeille 3outeille commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

Stack: #50493 → #50496 → #50796 → this PR → #50511 → #50514 → #50521 → #50522

Sequence parallelism now composes with FSDP2: DistributedConfig(fsdp_size=N, sp_size=M).

model = AutoModelForCausalLM.from_pretrained(
    "Qwen/Qwen3-8B",
    attn_implementation="flash_attention_2",
    distributed_config=DistributedConfig(fsdp_size=4, sp_size=2),
)
  • The ranks of an sp group hold the same batch, so FSDP2 shards the parameters and reduces the gradients over fsdp and sp together. That needs one mesh dim covering both: fsdp_sp.
  • HSDP also slices ("dp_replicate", "fsdp_sp"). Slicing a flattened dim from the root mesh is deprecated since torch 2.10, so fsdp_sp is a dim of the root mesh (pp, dp_replicate, fsdp_sp, tp), and the five dense dims are an _unflatten view of it. Both views share one root, which is also what FSDP2 needs to compose with tp later in the stack.
  • DeviceMesh._unflatten needs torch>=2.10. DistributedConfig refuses fsdp_size > 1 with sp_size > 1 on older torch. sp_size alone keeps the plain mesh, FSDP2 shards over sp, and it needs torch>=2.9.
  • pp_size, tp_size and ep_size with sp_size are still refused.

Tests

tests/sequence_parallel, CPU (gloo). Loss, logits slice and every gradient match an unsharded run:

setup ranks
fsdp=2 × sp=2 4

The test skips on torch<2.10.

Each rank of a `cp` device mesh holds a contiguous slice of every sequence. The plan pairs
two kinds of styles: `cp_split_sequence` cuts the layer inputs to that slice, and an attention
style, `cp_ulysses`, runs the attention call of the attention modules over the whole sequence,
with the mask and the keyword arguments the model built before the sequence was cut. Ulysses
is two all-to-all exchanges around the model's own attention function; another algorithm is a
`ContextParallelAttention` subclass registered in `ALL_PARALLEL_STYLES`. The styles share
`ContextParallelLayer`, with the `install_forward` contract of the TP and EP styles.

`apply_context_parallelism` installs a resolved plan on a model, and `ModelContextParallel`
on the model itself: the model checks, a forward without a cache, and the loss of the whole
sequences, which every rank reports.

Not wired into `DistributedConfig` yet: nothing changes for users.
The all-to-all and its backward, Ulysses against plain sdpa on the whole sequence given the
whole mask (unpacked, packed, sliding window, with and without GQA), the split style on a
stand-in layer, the routing of the attention call, the Ulysses and model checks, the loss
against the full-sequence loss, and a tiny Llama with the plan installed by hand against the
same weights on the full sequences. The multi-rank tests use two CPU ranks through
`run_distributed`, and carry `is_fsdp_test` so that the sharded CI jobs own them.
The context parallel styles live in their own registry, `ALL_CP_STYLES`, like `ALL_FSDP_STYLES`,
instead of `ALL_PARALLEL_STYLES` plus a filter on their class. `apply_context_parallelism` reads
it, and another attention algorithm is added to it under its own name. The layer types that
`ModelContextParallel.check` accepts are inlined in the check.
…ks in `apply_context_parallelism`, pad the sequences

- `context_parallel_loss` is a module-level function that `apply_context_parallelism` sets as
  `model.loss_function`, the seam transformers has for a model's loss; `ModelContextParallel` is
  about the forward only.
- The model checks open `apply_context_parallelism` instead of a `check` method.
- A sequence length that `cp_size` does not divide is padded at its end to a multiple of it, in
  `ModelContextParallel.transform_inputs_pre_forward`, before the model builds its masks:
  `input_ids` get `pad_token_id` (or 0), `inputs_embeds` zeros, `attention_mask` zeros, `labels`
  and `shift_labels` -100, and `position_ids` continue those of the last document. The logits are
  this rank's slice of the padded sequence; the loss counts the real tokens only. Was #50515.
…he two transforms of a style

`ContextParallelLayer` gains `transform_output_post_forward`, so a style can rewrite the output of the
forward it wraps, as the tensor parallel styles do. `ModelContextParallel` uses both: its inputs lose
the cache, are padded to a multiple of `cp_size`, and carry this rank's slice of the shifted labels with
the token count of the whole sequences, which the model's own loss function takes as kwargs; its output
reports the loss of the whole sequences on every rank, with the gradient of this rank's slice scaled
by `cp_size` for FSDP2's average. `context_parallel_loss` and the replacement of `model.loss_function`
are gone.
`ALL_CP_STYLES` lists everything context parallelism installs, the model's own style included, and
`apply_context_parallelism` installs the root through the same loop as the plan, under the name
`named_modules` gives it.
`apply_context_parallelism` installs the plan it is given, the model itself included under the
name `named_modules` gives it, `""`. The tests write it in their plans.
…on install

Restores the branch to its pre-merge scope: the tester mixin, CI job and test fetcher changes belong to #50796.
`sp_size` splits every sequence across the ranks of an `sp` mesh, which get the same batch and
keep a contiguous slice each. The plan follows the other parallelisms: a `base_model_sp_plan`
default in `PreTrainedConfig`, an `sp_plan` override merged and expanded like `tp_plan`, and
`apply_sequence_parallelism` installing the plan's styles after TP/EP and before FSDP2.

The model keeps taking whole sequences: the first decoder layer cuts `hidden_states`, every
layer cuts the rotary embeddings, the model-built mask and positions stay whole, and the loss is
the one of the whole sequences. FSDP2 shards over `sp`, and `dp_size` counts the sp ranks.
`fsdp_size`, `tp_size`, `pp_size` and `ep_size` are refused with it for now, and so is the
`Trainer`, whose dataloader would split the batch across an sp group.
A model sharded with `DistributedConfig(sp_size=N)` reproduces, step by step, the run of the same
weights on the full sequences: same loss, same logits on this rank's slice, same gradients. The
tests cover the plan, the refusals, packing, padding, `inputs_embeds`, sliding windows, a
registered attention style, saving, and HSDP composed with `sp_size`.
…the sequence parallel tests

`RUN_SEQUENCE_PARALLEL_TESTS` gates them like the tensor and expert parallel ones, `sequence_parallel_ci` runs
them on 6 workers, and the regular jobs deselect them.
…e model

`SequenceParallelTesterMixin` joins the bases of `CausalLMModelTest`, next to the FSDP and tensor
parallel mixins: every causal language model test class loads its tester's tiny config with
`sp_size=2` on 2 CPU ranks, and compares the logits of this rank's slice, the loss and every
gradient with the same weights on the whole sequences, plain, packed (`position_ids` restart
mid-sequence) and padded (a 2D `attention_mask`, and a length the ranks cannot split evenly).

A tester config is only changed when the sequence parallel checks refuse it and the change is
harmless: the auxiliary load-balancing loss of the MoE models is turned off. A model the checks
still refuse is loaded with `sp_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; set
`SEQUENCE_PARALLEL_TEST_MODEL_TYPES = None` to run every causal language model.

`_deterministic_init_model_dir` and `_distributed_tmpdir` move from the FSDP mixin to
`distributed_testing_utils`, and take the model class to build.
`DistributedConfig(fsdp_size=N, sp_size=M)` is no longer refused. FSDP2 shards over `fsdp` and
`sp` together: the ranks of an sp group hold the same batch, so their gradients are reduced
together and their parameters can be sharded together. That axis, `fsdp_sp`, is a dim of the
dense root mesh `(pp, dp_replicate, fsdp_sp, tp)`, and the five dense axes are an `_unflatten`
view of it, so that HSDP can slice `("dp_replicate", "fsdp_sp")` without slicing a flattened dim
from the root mesh, which torch deprecates. Requires `torch>=2.10`, refused in `DistributedConfig`;
`sp_size` alone keeps the plain mesh and shards over `sp`.
`fsdp_size=2 x sp_size=2` on four ranks against the same weights on the full sequences: same
loss, same logits on this rank's slice, same gradients.
@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.

@3outeille
3outeille removed this pull request from stack #51004 November 30, 2026 05:31
@3outeille

Copy link
Copy Markdown
Member Author

Folded into #50496.

@3outeille 3outeille closed this Nov 30, 2026
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