Skip to content

[distributed] Context parallelism: pad the sequences to a multiple of cp_size - #50515

Draft
3outeille wants to merge 2 commits into
cp-9-ep-x-cpfrom
cp-7-auto-pad
Draft

3outeille wants to merge 2 commits into
cp-9-ep-x-cpfrom
cp-7-auto-pad

Conversation

@3outeille

@3outeille 3outeille commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

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

With context parallelism, a sequence length that cp_size does not divide used to raise. Now ModelContextParallel, the style of the model itself (#50493), pads the full sequences at the end, before the model builds its masks:

  • input_ids get pad_token_id (or 0), and inputs_embeds get zeros. No real token attends to the padding, because it comes after them.
  • position_ids, if given, continue those of the last document.
  • A 2D attention_mask, if given, gets zeros.
  • labels and shift_labels get -100, so num_items_in_batch still counts the real tokens only.
  • outputs.logits is this rank's slice of the padded sequence.

Tests

tests/context_parallel, CPU (gloo):

  • length 7 with cp=2 (plain, packed, inputs_embeds, with a padding mask) and length 5 with cp=4;
  • the loss, every gradient, and the logits at the real positions match an unsharded run on the unpadded sequences;
  • a single-process test of what ModelContextParallel pads.

@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.

… cp_size

The root pre-hook pads every sequence-shaped input at its end instead of raising: `input_ids` with
the model's `pad_token_id` (0 without one), `inputs_embeds` with zeros, `position_ids` with the
positions that continue each row's last document, a 2D `attention_mask` with zeros, and `labels`
or a caller's `shift_labels` with -100. The padding happens before the model builds its mask and
its rotary embeddings, so nothing on the padding is attended to or trained on, and the loss
wrapper counts `num_items_in_batch` on the real tokens only.
…vide

A length of 7 over 2 ranks (plain, packed, `inputs_embeds` and through a 2D padding mask) and a
length of 5 over 4 ranks, compared on the real positions of the logits only, plus a single-process
test of the hook's padding of every input, of a positional `input_ids` and of a config without a
`pad_token_id`.

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.

2 participants