Skip to content

Assert the scattered sequence length is divisible by the SP size - #8351

Closed
adarshsm wants to merge 1 commit into
deepspeedai:masterfrom
adarshsm:fix/7384-guard-sequence-divisibility
Closed

adarshsm wants to merge 1 commit into
deepspeedai:masterfrom
adarshsm:fix/7384-guard-sequence-divisibility

Conversation

@adarshsm

Copy link
Copy Markdown

Refs #7384. @stas00 — this is the "original implementation" half of your reply, plus the
answer to what you asked.

The new implementation does already check

UlyssesSPDataLoaderAdapter.refill() validates it before sharding
(deepspeed/runtime/sequence_parallel/ulysses_sp.py):

if seq_length % self.sp_world_size != 0:
    raise ValueError(f"batch's seqlen={seq_length} isn't divisible by sp-size={self.sp_world_size}")

So the new path is fine. deepspeed/sequence/layer.py has no equivalent.

What this changes

_generate_layout_params asserts the head count divides evenly in both branches that
scatter heads:

assert num_total_head % seq_world_size == 0, f"Number of heads ({num_total_head}) must be divisible by the sequence parallel size ({seq_world_size})!"

The two branches that scatter the sequence had no equivalent — they just computed
global_seq_len // seq_world_size, so a length that is not a multiple of the SP size was
silently truncated and the all2all buffers then disagreed. This adds the matching
assertion, so it now fails the same way a head mismatch already does:

AssertionError: Sequence length (9) must be divisible by the sequence parallel size (2)!

What it does not cover, and why

This does not fully close #7384, which is why the commit says Refs rather than
Fixes.

The reporter pre-shards with torch.tensor_split(t, world_size, dim=2)[rank] and passes
scatter_idx=1, gather_idx=2. With a global length of 9 over 2 ranks that hands rank 0 a
size-5 shard and rank 1 a size-4 shard, so the ranks disagree on the gather dimension.
No rank can detect that locally — each one's own shard looks perfectly valid — and the
mismatch only surfaces inside all_to_all_single, where gloo aborts the process group with
no Python traceback at all.

Catching that case needs a cross-rank check, e.g. an all_gather of the local shape
compared across ranks before the all2all. That is a collective on every all2all call, so it
is a performance trade I did not want to make on your behalf. Happy to add it behind a flag,
or only under a debug/validation mode, if you want it.

Verification

Two ranks over gloo on CPU:

case before after
seq 8, world 2, full sequence at the scattered dim works, matches single-device attention unchanged
seq 9, world 2, full sequence at the scattered dim process group aborts, no message AssertionError naming both numbers
seq 9, world 2, pre-sharded unevenly (the report) aborts still aborts — see above

The divisible case was checked against single-device scaled_dot_product_attention on the
same input to confirm the harness itself is sound before trusting the failing case.

yapf --style .style.yapf reports no diff; the two new lines are the same shape and length
as the head assertions directly below them.

I could not run tests/unit/sequence_parallelism/ here — no NVIDIA GPU on this machine — so
that is worth a look in CI.

_generate_layout_params asserts that the head count divides evenly by the
sequence parallel size, but the two branches that scatter the sequence
had no equivalent check: they just computed global_seq_len //
seq_world_size, so a sequence length that is not a multiple of the SP
size was silently truncated. The all2all buffers then disagreed and the
process group aborted with no usable message.

Add the matching assertion so this fails with the same kind of error the
head mismatch already produces.

Refs deepspeedai#7384

Signed-off-by: adarshsm <[email protected]>
@adarshsm
adarshsm force-pushed the fix/7384-guard-sequence-divisibility branch from e09ff10 to 25493c7 Compare August 29, 2026 13:31

@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: e09ff10b0a

ℹ️ 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 batch_dim_idx == 0:
if scatter_idx < 2:
bs, global_seq_len, num_local_head, head_dim = input.shape
assert global_seq_len % seq_world_size == 0, f"Sequence length ({global_seq_len}) must be divisible by the sequence parallel size ({seq_world_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 Add the required sign-off trailer

Because this is a non-merge commit and its message contains no Signed-off-by trailer, it does not satisfy the repository's mandatory commit/CI requirement and may be rejected by DCO enforcement; recreate the commit using git commit --signoff with the configured author identity.

AGENTS.md reference: AGENTS.md:L6-L10

Useful? React with 👍 / 👎.

@stas00

stas00 commented Aug 29, 2026 •

Copy link
Copy Markdown
Collaborator

I don't know if it's worthwhile investing into an outdated implementation. Perhaps it should be deprecated in favor of the new version that has no such bugs?

But in any case if you are fixing the old implementation please tag the original authors. Perhaps they can also decide what to do with it.

@adarshsm

Copy link
Copy Markdown
Author

You're right, and I should have reached that conclusion myself before opening this.

Your first reply already contained the answer — you suspected the new implementation handled it, and my own investigation confirmed it does (UlyssesSPDataLoaderAdapter.refill() raises before sharding). At that point the honest read was that the remaining gap is in a path you would rather retire, not one worth hardening. I had the disqualifying evidence and opened the PR anyway, which puts a review burden on you for marginal value. Compounding it, the guard does not even close #7384: the reported failure is ranks disagreeing on the gather dimension after an uneven pre-shard, which no local assertion can detect.

Closing this. If you do want the deprecation route instead — a warning on deepspeed.sequence.DistributedAttention pointing at runtime/sequence_parallel, plus a docs note — I am happy to write that, and it would make the old path's status explicit for the frameworks still on it. Just say the word and I will open it against whatever removal timeline you want.

Thanks for the straight answer rather than letting it sit.

@adarshsm adarshsm closed this Aug 31, 2026
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 14, 2026
…edai#9059)

## Problem


[`DistributedAttention`](https://github.com/jschneider-canva/DeepSpeed/blob/5a8b4a67b4a93aeec42a1b403da18647a7b04ebe/deepspeed/sequence/layer.py)
assumes equal sequence lengths across sequence-parallel ranks. Unequal
shards can hang, abort, or silently corrupt results, depending on
backend and version
([deepspeedai#7384](deepspeedai#7384),
[deepspeedai#8351](deepspeedai#8351)). A two-GPU
reproduction hangs without a mask or fails with a callback shape error
when masked.

Separately,
[`FPDT_InputConstruct`](https://github.com/jschneider-canva/DeepSpeed/blob/5a8b4a67b4a93aeec42a1b403da18647a7b04ebe/deepspeed/sequence/fpdt_layer.py)
rejects sequence lengths that do not fill its global chunks, requiring
callers to pad manually.

[deepspeedai#7868](deepspeedai#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`](https://github.com/jschneider-canva/DeepSpeed/blob/5a8b4a67b4a93aeec42a1b403da18647a7b04ebe/deepspeed/sequence/__init__.py);
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.

<details>
<summary>PKUWZP’s review items on deepspeedai#7868</summary>

| # | 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;
[deepspeedai#8317](deepspeedai#8317) already
covers the shape fix. |

</details>

## Testing

**137 passed, zero skips** across the [FPDT
constructor](https://github.com/jschneider-canva/DeepSpeed/blob/5a8b4a67b4a93aeec42a1b403da18647a7b04ebe/tests/unit/v1/sequence_parallelism/test_fpdt_inputs.py),
[Ulysses](https://github.com/jschneider-canva/DeepSpeed/blob/5a8b4a67b4a93aeec42a1b403da18647a7b04ebe/tests/unit/v1/sequence_parallelism/test_ulysses.py),
and
[ALST](https://github.com/jschneider-canva/DeepSpeed/blob/5a8b4a67b4a93aeec42a1b403da18647a7b04ebe/tests/unit/ulysses_alst/test_ulysses_sp_hf.py)
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.

<details>
<summary>Test commands</summary>

```bash
# 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
```

</details>

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

## Duplicate Work

Addresses [deepspeedai#7384](deepspeedai#7384)
and picks up the remaining work from
[deepspeedai#7868](deepspeedai#7868).

[deepspeedai#8351](deepspeedai#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](https://github.com/harshang03)’s proposal and
[@PKUWZP](https://github.com/PKUWZP)’s review of
[deepspeedai#7868](deepspeedai#7868).

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

---------

Signed-off-by: Jacob Schneider-Martin <[email protected]>
@auto-pr-labeler-with-jev auto-pr-labeler-with-jev Bot added the skip-gpu-test Requires positive evidence that every changed behavior can be validated without a GPU. label Nov 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

skip-gpu-test Requires positive evidence that every changed behavior can be validated without a GPU.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] Ulysses DistributedAttention silently produces incorrect output when #GPUs does not divide global sequence length

2 participants