Skip to content

[distributed] Sequence parallel module, with Ulysses - #50493

Open
3outeille wants to merge 17 commits into
mainfrom
cp-1-implementations
Open

3outeille wants to merge 17 commits into
mainfrom
cp-1-implementations

Conversation

@3outeille

@3outeille 3outeille commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

TODO: tiled MLP

This is the first PR in a sequence-parallelism stack: this PR → #50496 → #50796 → #50511 → #50514 → #50521 → #50522.

It adds the sequence-parallel module and a Ulysses attention style. Nothing is wired into DistributedConfig yet: the sp mesh axis and config plans come in #50496.

Sequence parallelism splits a sequence across ranks so each decoder layer works on fewer tokens. Attention still needs tokens held by other ranks. This PR provides three styles:

  • sp_model prepares inputs and combines partial losses
  • sp_split_sequence gives each decoder layer its local tokens
  • sp_ulysses exchanges sequence slices for head slices so attention can run over the full sequence.

For example, split an eight-token sequence across two ranks:

image

@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 added this pull request to stack #50502 November 9, 2026 11:03
@3outeille
3outeille removed this pull request from stack #50502 November 9, 2026 14:29
@3outeille
3outeille added this pull request to stack #50518 November 9, 2026 14:30
@3outeille
3outeille removed this pull request from stack #50518 November 9, 2026 14:36
@3outeille
3outeille added this pull request to stack #50520 November 9, 2026 14:37
@3outeille
3outeille removed this pull request from stack #50520 November 10, 2026 02:50
@3outeille
3outeille force-pushed the cp-1-implementations branch from ba95ec6 to a36d4f7 Compare November 10, 2026 02:50
@3outeille
3outeille added this pull request to stack #50546 November 10, 2026 02:51
@3outeille
3outeille force-pushed the cp-1-implementations branch 2 times, most recently from d0e004f to 16affa7 Compare November 10, 2026 05:44
@3outeille
3outeille force-pushed the cp-1-implementations branch 3 times, most recently from 6b06ac3 to 4d31656 Compare November 12, 2026 08:01
@3outeille 3outeille changed the title [distributed] Context parallel implementations, with Ulysses [distributed] Context parallel module, with Ulysses Nov 12, 2026
@stas00

stas00 commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Thank you for working on this integration, @3outeille

I'd recommend to stick to sp in the naming because ulysses is completely different from cp rsa (not a variation of it) and sp is already used for Ulysses in HF Trainer and Accelerate.

footnote: also rsa can be composed with ulysses => Unified Sequence Parallelism (USP)

@3outeille 3outeille changed the title [distributed] Context parallel module, with Ulysses [distributed] Sequence parallel module, with Ulysses Nov 20, 2026
@3outeille
3outeille removed this pull request from stack #50797 November 20, 2026 08:49
@3outeille
3outeille added this pull request to stack #51004 November 20, 2026 08:50
@3outeille
3outeille force-pushed the cp-1-implementations branch from 2deaaf4 to 4c1f526 Compare November 30, 2026 05:29
@3outeille
3outeille removed this pull request from stack #51004 November 30, 2026 05:31
@3outeille
3outeille added this pull request to stack #51606 December 2, 2026 05:05
@3outeille
3outeille force-pushed the cp-1-implementations branch 3 times, most recently from 5b4f074 to 3667b13 Compare December 3, 2026 06:59
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.
@3outeille
3outeille force-pushed the cp-1-implementations branch from 3667b13 to 5eeaf73 Compare December 3, 2026 07:38
@qgallouedec

Copy link
Copy Markdown
Member

Hey, nice stack! I gave it a try with TRL and our SFT and DPO trainers crash on the first step with sp_size=2 (Qwen3-0.6B, 2 GPUs):

IndexError: The shape of the mask [4, 1023] at index 1 does not match the shape of the indexed tensor [4, 511, 1024] at index 1

The reason: we patch model.forward after loading to fuse the LM head with the loss, check here https://github.com/huggingface/trl/blob/7059eff8bf2ca8d4be515e9ba1fa7190a0c5438e/trl/trainer/utils.py#L1847
and sp_model also works by replacing module.forward

def install_forward(self, module: nn.Module, sp_mesh: DeviceMesh, **options):
original_forward = module.forward
@wraps(original_forward)
def sp_forward(*args, **kwargs):
args, kwargs = self.transform_inputs_pre_forward(module, args, kwargs, sp_mesh, **options)
with self.context_around_forward(module, sp_mesh):
output = original_forward(*args, **kwargs)
return self.transform_output_post_forward(module, output, sp_mesh)
module.forward = sp_forward
return module

So our forward just overwrites yours and the padding, label split and loss reduction never run.

I tried installing sp_model with hooks instead, and it just works, no change needed on our side. TRL SFT then matches the single-GPU run to ~1e-6 over 8 steps (fp32), and your SP tests give the same result as before (45 passed, 5 skipped):

    def install_forward(self, module: nn.Module, sp_mesh: DeviceMesh):
        module.register_forward_pre_hook(
            lambda module, args, kwargs: self.transform_inputs_pre_forward(module, args, kwargs, sp_mesh),
            with_kwargs=True,
        )
        module.register_forward_hook(
            lambda module, args, kwargs, output: self.transform_output_post_forward(module, output, sp_mesh),
            with_kwargs=True,
        )
        return module

Would you be ok adding it to ModelSequenceParallel? I think any lib that patches forward would hit the same thing.

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants