Skip to content

[Ulysses] Add opt-in uneven-shard rejection and FPDT padding - #9059

Merged
tohtana merged 4 commits into
deepspeedai:masterfrom
jschneider-canva:codex/ulysses-uneven-shards-7384
Nov 14, 2026
Merged

tohtana merged 4 commits into
deepspeedai:masterfrom
jschneider-canva:codex/ulysses-uneven-shards-7384

Conversation

@jschneider-canva

@jschneider-canva jschneider-canva commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Problem

DistributedAttention assumes equal sequence lengths across sequence-parallel ranks. Unequal shards can hang, abort, or silently corrupt results, depending on backend and version (#7384, #8351). A two-GPU reproduction hangs without a mask or fails with a callback shape error when masked.

Separately, FPDT_InputConstruct rejects sequence lengths that do not fill its global chunks, requiring callers to pad manually.

#7868 proposed zero-padding Q/K/V inside attention. In a five-token reproduction, that produced maximum absolute errors of 0.24 in outputs and 0.32 in Q gradients against an unpadded reference, and unmasked zero keys still receive softmax probability.

Approach

Report unequal shards as an error before generic attention data exchange and pad FPDT inputs under its causal contract.

  • Ulysses: add local sequence-scatter divisibility assertions and opt-in DistributedAttention(..., validate_shards=True). The enabled check gathers Q/K/V sequence lengths across the SP group and raises ValueError on every participating rank before attention data exchange. Q and K/V may differ from each other; each must agree across ranks. Validation defaults off.
  • FPDT: validate sequence/chunk/SP geometry and rank, then pad incomplete sequences to the global chunk size. Append zero inputs, label 0, zero loss weights, and continued position IDs. Padding requires loss_mask and attention_mask=None. The padding and normalization contract is documented in the FPDT tutorial and constructor docstring.
  • Export DistributedAttention from deepspeed.sequence; keep _SeqAllToAll private.

Outputs and gradients were verified against an unpadded reference within numerical tolerances.

Enable validation consistently across all SP ranks - this adds one metadata all-gather and host synchronization per forward. Generic-attention callers still own the padding and masks.

For FPDT, apply the returned loss mask and normalize by the SP-global sum of loss weights.

PKUWZP’s review items on #7868
# Item Resolution here
1 Padding changes attention normalization No internal generic-attention padding; FPDT uses causal tail padding.
2 Per-forward collective overhead No new default collective; validation adds one metadata all-gather when enabled.
3 Backward correctness Output, loss, input/QKV/head gradients and padding invariance tested.
4 Attention masks Reject non-None masks when padding is required; preserve aligned pass-through.
5 Chunk divisibility Pad to global chunk size; validate divisibility by SP size.
6 Original-length field and padded loss No unused field; require loss masking and zero padded loss weights.
7 Unused imports No extra attention/max-length imports; F401 checks passed.
8 Private export Export DistributedAttention only.
9 Regression coverage Add uneven rejection, valid/caller-padded attention, and CPU/GPU FPDT tests; #8317 already covers the shape fix.

Testing

137 passed, zero skips across the FPDT constructor, Ulysses, and ALST files on four H200s. The six affected rejection cases passed again on two H200s after test deduplication.

Coverage includes:

  • Unequal shards in both rank orders, both tensor layouts, valid equal shards, cross-attention, and independent SP subgroups.
  • 39 CPU constructor tests: geometry/errors, padding values, positions, ordering, reconstruction, optional fields, and input immutability.
  • FPDT at SP2: aligned length 24, odd length 19, and short length 3, with both offload requests. Comparisons exercise actual attention and loss backward, globally normalized loss, input/QKV/head gradients, caller padding, and padding perturbations.
  • Length 19 exercises both multi-chunk attention paths. Length 3 uses the existing one-chunk non-offloading fallback, including when offloading is requested.
  • Changed-file pre-commit and strict FPDT F401 checks passed.

Environment: Python 3.11.10, Torch 2.11.0+cu128, CUDA 12.8, FA2 2.8.3, pytest 8.3.5, NVIDIA driver 590.48.01.

New numerical coverage uses FP32 SDPA for Ulysses and FP16/SP2/zero dropout for FPDT.

Test commands
# CPU environment without FA2
CUDA_VISIBLE_DEVICES='' DS_ACCELERATOR=cpu PYTHONPATH="$PWD" \
  python -m pytest -q tests/unit/v1/sequence_parallelism/test_fpdt_inputs.py

# Full suite: four H200s
CUDA_VISIBLE_DEVICES=0,1,2,3 PYTHONPATH="$PWD" \
HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 \
  python -m pytest --forked -q -rs \
  tests/unit/v1/sequence_parallelism/test_fpdt_inputs.py \
  tests/unit/v1/sequence_parallelism/test_ulysses.py \
  tests/unit/ulysses_alst/test_ulysses_sp_hf.py --maxfail=1

The pre-existing softmax().log() instability is being addressed separately in #9068. This PR documents zeroing losses at zero-weight positions before weighting, avoiding inf * 0 = NaN for masked tokens.

Duplicate Work

Addresses #7384 and picks up the remaining work from #7868.

#8351 proposed the local divisibility assertion, this PR adds cross-rank validation and FPDT padding. The sibling ALST data-loader adapter already rejects non-divisible lengths and is unchanged. Our pre-submission search found no other open implementation of this approach.

Builds on @harshang03’s proposal and @PKUWZP’s review of #7868.

AI assistance was used for implementation, testing, review, and preparation of this PR.

@jschneider-canva
jschneider-canva marked this pull request as ready for review November 12, 2026 00:35
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-12T00:40:56.014894Z 5a8b4a6 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5a8b4a67b4

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

if global_chunk_size % sp_size != 0:
raise ValueError(f"FPDT chunk size must be divisible by the sequence parallel size {geometry}")

padding = (-global_seq_len) % global_chunk_size

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Document the FPDT padding and loss-mask contract

FPDT_InputConstruct now turns previously rejected lengths into padded batches, but the shipped FPDT tutorial (docs/_tutorials/ulysses-offload.md) still only describes fixed chunks and never states that callers must pass and use the returned loss mask, reject attention masks, or normalize by the SP-global weight sum. External Megatron users can therefore enable the new path yet include fake labels or mis-normalize ranks with no valid tokens; document this contract where FPDT is configured.

AGENTS.md reference: AGENTS.md:L71-L71

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Have now added the padding contract to the FPDT tutorial and constructor docstring in a170cbbc.

Comment on lines +114 to +115
labels = append_zeros(labels)
loss_mask = append_zeros(loss_mask)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep padded losses finite before zero-weighting

When an auto-padded position assigns class 0 a probability that underflows to zero (for example, its logit is roughly 104 or more below the maximum), FPDT_LogitsLoss.forward computes softmax(...).log() and returns +inf; the intended (losses * loss_mask).sum() then evaluates inf * 0 as NaN. Thus an otherwise finite model can report a NaN loss for an unaligned sequence even though padded gradients are masked; make the padded loss finite (for example via log_softmax or an honored ignore mask) rather than relying on a zero multiplier.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is true, but it seems the softmax().log() issue is pre-existing? Happy to include a fix here if the reviewers prefer, otherwise it could be added as a second PR. For now, I've just included it as a limitation in the PR.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are right, the instability of softmax().log() is a pre-existing issue. I opened #9068 to address it.
On the other hand, padding could cause the same issue when the padded positions return +inf. I think it would be good to show an example to zero loss values the padded positions (See the inline comment).

@jschneider-canva jschneider-canva Nov 12, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense, just added the safe-masking example. Have referenced #9068 in the PR body now too.

@jschneider-canva

Copy link
Copy Markdown
Contributor Author

@tohtana picking up #7868, this PR should cover the rest of @PKUWZP's review (shape fixed was merged in #8317).

@tohtana tohtana left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @jschneider-canva,
Thank you for your contribution! The code change looks good to me, but could we show an example to zero loss values at padded positions? I left a comment in the new tutorial section you added.

I also found we could improve the stability of logits loss by using log_softmax and opened #9068.

Comment thread docs/_tutorials/ulysses-offload.md Outdated

When padding is needed, supply a `loss_mask` and set `attention_mask=None`. Causal attention prevents real tokens from attending to the appended tail, so padding cannot affect their outputs. Aligned inputs retain their existing behavior.

Use the reordered loss mask returned by `FPDT_InputConstruct.generate()`, keeping it aligned with the loss layout. `FPDT_LogitsLoss` returns globally gathered losses in SP-rank order with shape `[sequence, batch]`; the returned mask already covers the global sequence in the same order with shape `[batch, sequence]`. Compute `(losses * loss_mask.t()).sum() / loss_mask.sum()`. This normalizes by the SP-global valid loss-weight sum even when one rank has no valid tokens; the returned mask needs no further all-reduce.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

losses * loss_mask.t()

If a padded token has an infinite loss, multiplying it by its zero weight gives NaN, and the mean loss becomes NaN as well. Could we add an example showing how to set the loss at masked positions to zero before multiplying by the weights?

# Losses are [sequence, batch]. The last position is padding for both samples.
losses = torch.tensor([[1., 2.],
                       [3., 4.],
                       [5., 6.],
                       [float("inf"), float("inf")]])

# FPDT returns the mask in [batch, sequence] order.
loss_mask = torch.tensor([[1., 1., 1., 0.],
                          [1., 1., 1., 0.]])

weights = loss_mask.t()
losses = losses.masked_fill(weights == 0, 0.0)
mean_loss = (losses * weights).sum() / weights.sum()

This gives 21 / 6 = 3.5, the mean over the six real tokens.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the review - I've added that example in f24d695d, zeroing out masked losses before applying the weights. Checked it on CPU with infinite padded losses and fractional weights, and verified the masked gradients are zero.

@tohtana tohtana added the needs-gpu-test GPU testing is recommended to validate the changes in this PR. label Nov 13, 2026

@tohtana tohtana left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for the update! Looks good to me.

@tohtana
tohtana enabled auto-merge November 13, 2026 23:31
@tohtana
tohtana added this pull request to the merge queue Nov 14, 2026
Merged via the queue into deepspeedai:master with commit 663de97 Nov 14, 2026
23 checks passed
@tohtana tohtana removed the needs-gpu-test GPU testing is recommended to validate the changes in this PR. label Nov 14, 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