Skip to content

Fix the seq-first Ulysses all2all output layout - #8317

Merged
tohtana merged 1 commit into
deepspeedai:masterfrom
vineethsaivs:fix/ulysses-seq-first-all2all-layout
Aug 28, 2026
Merged

tohtana merged 1 commit into
deepspeedai:masterfrom
vineethsaivs:fix/ulysses-seq-first-all2all-layout

Conversation

@vineethsaivs

Copy link
Copy Markdown
Contributor

Symptom

_generate_layout_params (deepspeed/sequence/layer.py) builds the reshape target for every all2all in DistributedAttention. For the seq-first layout (batch_dim_idx=1, (s, b, n, h)) with scatter_idx < 2 it returns

post_all2all_res_shape = [bs, seq_world_size * global_seq_len, num_local_head // seq_world_size, head_dim]

That is the batch_dim_idx=0 / scatter_idx >= 2 shape: batch first, sequence multiplied, heads divided. This direction does the opposite, it scatters the sequence and gathers the heads, so the result should be [global_seq_len // seq_world_size, bs, seq_world_size * num_local_head, head_dim].

The element count still matches whenever num_local_head is divisible by seq_world_size, so the reshape succeeds and silently returns a transposed, mis-strided tensor. When it is not divisible the floor division makes a dimension 0 and the reshape raises shape '[...]' is invalid for input of size ....

Root cause

A copy of the wrong sibling branch during a refactor. Before #6750 extracted this function, post_all2all computed the shape inline and this case read:

        else:
            # s, b, n, h
            if scatter_idx < 2:
                output = input.permute(1, 2, 0, 3, 4).contiguous()
                output = output.reshape(seq_len // seq_world_size, bs, seq_world_size * num_head,
                                        head_dim).contiguous()

The permute survived the refactor unchanged; only the reshape target was replaced, with the shape from the batch_dim_idx=0/scatter_idx >= 2 branch.

Reachability

DistributedAttention.__init__ defaults to gather_idx=0, and the output-projection all2all swaps the two indices:

output = _SeqAllToAll.apply(self.spg, context_layer, self.gather_idx, self.scatter_idx, batch_dim_idx, ...)

so it runs with scatter_idx=0. _SeqAllToAll.backward swaps them too, so the backward of the q/k/v all2alls takes the same path. Both are the seq-first (s, b, n, h) layout used by Megatron-DeepSpeed.

Why the existing tests miss it

  • TestUlyssesAll2All only runs batch_dim_idx = 0.
  • TestUlyssesAll2All_odd does cover batch_dim_idx = 1, but its first call has num_heads % seq_world_size != 0, which calls set_num_kv_heads(...). From then on get_num_kv_heads() is not None routes every later call to uneven_heads_all2all, so _generate_layout_params is never reached.
  • Both are DistributedTest classes behind skip_on_arch(min_arch=8), so neither runs in the CPU CI.

Fix

One line, restoring the pre-#6750 shape, plus a two-line comment naming the direction.

Test

_generate_layout_params, pre_all2all_fun and post_all2all are pure, so TestUlyssesAll2AllLayout drives them with an emulated all_to_all_single (rank i sends chunk j of dim 0 to rank j) and checks that both directions land the right (sequence, head) shard of a known tensor. No process group, no accelerator, so it runs in the CPU CI, where this branch currently has no coverage at all.

# before, tests/
$ pytest unit/sequence_parallelism/test_ulysses.py -k Layout
FAILED TestUlyssesAll2AllLayout::test_head_to_seq_parallel[2-1] - AssertionError: rank 0 got torch.Size([2, 12, 1, 4]), expected torch.Size([3, 2, 4, 4])
FAILED TestUlyssesAll2AllLayout::test_head_to_seq_parallel[4-1] - RuntimeError: shape '[2, 48, 0, 4]' is invalid for input of size 192
2 failed, 6 passed

# after
8 passed

# whole file, after
8 passed, 43 skipped        (the 43 are the DistributedTest classes, no GPU here)

yapf --style .style.yapf and flake8 are clean on both files.

_generate_layout_params builds the reshape target for every all2all in
DistributedAttention. For batch_dim_idx=1 (s, b, n, h) with scatter_idx < 2 it
returns [bs, seq_world_size * global_seq_len, num_local_head // seq_world_size,
head_dim], which is the batch_dim_idx=0 / scatter_idx >= 2 shape: it puts the
batch first, multiplies the sequence and divides the heads, when this direction
scatters the sequence and gathers the heads.

Before deepspeedai#6750 extracted this function, post_all2all computed
[seq_len // seq_world_size, bs, seq_world_size * num_head, head_dim] for that
case, so the refactor copied the wrong sibling branch. Restore that shape.

The element count still matches whenever num_local_head is divisible by
seq_world_size, so the reshape succeeds and silently returns a transposed,
mis-strided tensor; when it is not divisible, the floor division makes a
dimension 0 and the reshape raises. Both are reachable from
DistributedAttention, whose default gather_idx is 0: the output projection
all2all and the backward of the q/k/v all2alls both run scatter_idx < 2.

The existing coverage misses it. TestUlyssesAll2All only runs batch_dim_idx=0,
and TestUlyssesAll2All_odd sets num_kv_heads on its first call so every later
call takes uneven_heads_all2all instead of _generate_layout_params.

_generate_layout_params is pure, so add TestUlyssesAll2AllLayout, which drives
it with an emulated all_to_all_single and checks that both directions land the
right (sequence, head) shard of a known tensor. It needs no process group and
no accelerator, so it runs in the CPU CI. Against the current code the two
batch_dim_idx=1 head-to-sequence cases fail (2 failed, 6 passed: one shape
assertion, one reshape RuntimeError) and all 8 pass with the fix.

Signed-off-by: Vineeth Sai <[email protected]>
@vineethsaivs
vineethsaivs force-pushed the fix/ulysses-seq-first-all2all-layout branch from 021970c to 2caa549 Compare August 25, 2026 18:40
@vineethsaivs

Copy link
Copy Markdown
Contributor Author

Flagging some prior art I only found today: #7868 proposes the same one-line change to post_all2all_res_shape, as part of a larger draft that also pads uneven sequence lengths and touches fpdt_layer.py, sequence/__init__.py and utils/groups.py. That draft has been conflicting and unchanged since 2026-02-22, and the issue it was filed against (#7842) was closed out by its reporter after the mismatch turned out to be their baseline rather than DeepSpeed.

I did not know about it when I opened this. Since the shape bug is real independently of the padding work, this PR keeps to just that one line plus a CPU regression test that fails on master (2 failed, 6 passed) and passes with the fix (8 passed). Happy to close this in favour of #7868 if a maintainer would rather revive the larger change.

@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 @vineethsaivs,
This is a very high-impact fix! And the fix looks correct to me.
I really appreciate you submitting this PR.

@tohtana
tohtana enabled auto-merge August 28, 2026 21:59
@tohtana
tohtana added this pull request to the merge queue Aug 28, 2026
Merged via the queue into deepspeedai:master with commit cd5206a Aug 28, 2026
13 checks passed
@tohtana

tohtana commented Aug 28, 2026

Copy link
Copy Markdown
Collaborator

Thank you @vineethsaivs for your comments about the prior PR (#7868). I have missed it.
I think #7868 is still worth merging, even without the shape fix from this PR, since it includes several other fixes.

Sorry, @harshang03, I should have been more careful about the overlap. Please feel free to revive #7868 and continue working on the remaining issues.

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.

2 participants