Skip to content

fix: correct DistributedAttention output shape and pad uneven sequence lengths (#7842) - #7868

Draft
harshang03 wants to merge 1 commit into
deepspeedai:masterfrom
harshang03:fix/7842-dist-attn-uneven-seq
Draft

harshang03 wants to merge 1 commit into
deepspeedai:masterfrom
harshang03:fix/7842-dist-attn-uneven-seq

Conversation

@harshang03

Copy link
Copy Markdown

What this PR does / why we need it

DistributedAttention produced numerically incorrect results whenever the global sequence length was not evenly divisible by the sequence-parallel world size. Two bugs were found and fixed:

Bug 1 – Wrong output shape formula (silent corruption even with divisible lengths)

In _generate_layout_params, the post_all2all_res_shape for the batch_dim_idx=1, scatter_idx < 2 path (seq-first layout, output all-to-all) was computed as [bs, seq_world_size * global_seq_len, num_local_head // seq_world_size, head_dim]. After the permute, the tensor is [S/P, B, P, H/P, D]; collapsing the two head dimensions must yield [S/P, B, H, D], not the formula above. This caused the returned tensor to have the right number of elements but the wrong shape, silently misinterpreting data.

Bug 2 – Unequal local sequence lengths crash dist.all_to_all_single

When S % P != 0 different ranks hold different numbers of tokens (ceil(S/P) vs floor(S/P)). dist.all_to_all_single with implicit equal splits then silently reads/writes beyond allocated buffers, producing garbage outputs with no exception raised.

Fix

  • deepspeed/sequence/layer.py: correct post_all2all_res_shape for the batch_dim_idx=1, scatter_idx<2 case; add DistributedAttention._pad_to_seq_world_size(); in forward(), call _get_max_local_seq_len() to align all ranks to the same local sequence length, pad Q/K/V before the all-to-all, and slice the output back to the original length. F.pad is differentiable so gradients flow correctly without extra ctx bookkeeping.
  • deepspeed/utils/groups.py: add _get_max_local_seq_len(local_seq_len, group) — a single allreduce(MAX) so that all ranks can agree on the padded sequence length without multiple round trips.
  • deepspeed/sequence/fpdt_layer.py: replace the hard assert global_seq_len % sp_size == 0 in FPDT_InputConstruct.__init__ with graceful zero-padding of tokens/labels/loss_mask/position_ids to the nearest multiple of sp_size.
  • deepspeed/sequence/__init__.py: export DistributedAttention and _SeqAllToAll for easier downstream imports.

Fixes #7842

…e lengths

Two related bugs caused numerically incorrect results in DistributedAttention
when the global sequence length is not evenly divisible by the sequence-parallel
world size (scatter_idx < 2, batch_dim_idx == 1 path):

1. Wrong post_all2all_res_shape for seq-first layout (batch_dim_idx=1,
   scatter_idx < 2).  After the all-to-all + permute the tensor is
   [S/P, B, P, H/P, D]; collapsing the two head dims must give
   [S/P, B, H, D] not [B, P*S, H/P^2, D] as previously computed.
   This caused silent data corruption even for evenly-divisible sequences.

2. Unequal local sequence lengths across ranks (S % P != 0) mean that
   dist.all_to_all_single with implicit equal splits silently reads/writes
   out of bounds, producing garbage values without raising an exception.

Fix:
- Correct post_all2all_res_shape in _generate_layout_params for the
  batch_dim_idx=1, scatter_idx<2 case (layer.py).
- Add _get_max_local_seq_len() to groups.py: a single allreduce(MAX) that
  lets every rank agree on the largest local sequence length.
- In DistributedAttention.forward, call _get_max_local_seq_len() and pad
  Q/K/V on the sequence dimension to max_local_seq_len before the all-to-all.
  Slice the output back to the original local_seq_len after the output
  all-to-all.  F.pad is differentiable, so backward gradients are handled
  correctly without explicit ctx bookkeeping (layer.py).
- In FPDT_InputConstruct.__init__, pad global_seq_len to the nearest
  multiple of sp_size before computing chunk sizes, replacing the hard
  assert with a graceful pad (fpdt_layer.py).
- Export DistributedAttention and _SeqAllToAll from the sequence package
  __init__.py for easier import by downstream users.

Fixes deepspeedai#7842
@PKUWZP
PKUWZP self-requested a review February 22, 2026 18:10

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

@harshang03 Thanks so much for fixing the bugs. Here are my comments:

I understand that this PR tries to fix two bugs: 1. Fix the tensor shape; 2. Padding the uneven sequences.

Bug 1 — Shape Fix (Correct)

I think the fix at layer.py:46-49 is correct. Tracing the tensor shapes:

  • Input: [global_seq_len, bs, num_local_head, head_dim]
  • After all-to-all + permute (1,2,0,3,4): [global_seq_len//P, bs, P, num_local_head, head_dim]
  • Collapse last two head dims → [global_seq_len//P, bs, P * num_local_head, head_dim]

The old formula [bs, P * global_seq_len, num_local_head // P, head_dim] was incorrect in every dimension. The fix correctly changes this to
[global_seq_len // P, bs, P * num_local_head, head_dim].

@sfc-gh-truwase @tohtana feel free to chime in and confirm. I think it's from the FPDT paper in MLSys (https://arxiv.org/pdf/2408.16978)?


Bug 2 — Uneven Sequence Padding, I feel for this bug, the fix has some issues

The current fix provides an allreduce MAX which finds the largest local sequence length across ranks; Q/K/V are zero-padded to that length before the all-to-all;
the output is sliced back afterward. @harshang03 feel free to chime in if my understanding is incorrect.

A coupe of potential Issues:

  1. Zero-padding corrupts attention for real tokens. After the first all-to-all, each rank sees the full (padded) sequence. During local attention, padding tokens participate as keys/values:
    - Zero keys → dot(q, 0) = 0 → exp(0) = 1 in softmax → non-trivial attention weight
    - Zero values → contribute zero to the weighted sum, which might inflate softmax normalization denominator. This could cause the outputs for real (non-padded) tokens numerically different from a non-SP baseline.
I suggest a few things:
   - Pass an attention mask through to the local attention to mask out padded positions, or
   - Document this as a known approximation that becomes negligible for long sequences
  1. Allreduce every forward pass (_get_max_local_seq_len). This introduces a global synchronization point on every forward call. In practice, local sequence lengths are typically constant across a training run. Consider caching or allowing users to pass the max length directly to avoid this overhead.
  2. Backward pass correctness. The output slicing output[:, :local_seq_len] (or output[:local_seq_len]) creates a view, so gradients flow back correctly through the slice. However, the zero-padded positions receive gradients from the attention computation, meaning F.pad's backward will produce gradients that reflect the (incorrect) attention over padding tokens. This may cause minor training instabilities. @harshang03 Not sure if I understand it correctly.

FPDT Padding (Has Issues)

  1. attention_mask is not padded (fpdt_layer.py). tokens, labels, loss_mask, and position_ids are all padded, but attention_mask is left unchanged. If attention_mask has a sequence-length dimension (which it often does), this will cause a shape mismatch downstream.
  2. Second assert may still cause problems. After padding, global_seq_len % sp_size == 0 is satisfied, but the next assertion global_seq_len % args.ds_sequence_parallel_fpdt_chunk_size == 0 could still fail if the padded length isn't divisible by chunk_size. The PR only addresses the first divisibility constraint.
  3. raw_global_seq_len stored but never used. self.raw_global_seq_len is set but never referenced — the generate() method doesn't trim back to the original length, so padded positions will flow through training including into the loss (mitigated only if loss_mask zeros them out).

Other Issues

  1. Unused imports in fpdt_layer.py. Both DistributedAttention and _get_max_local_seq_len are imported but never used in the FPDT changes:
    from .layer import single_all_to_all, apply_rotary_pos_emb, DistributedAttention # DistributedAttention unused from deepspeed.utils.groups import _get_max_local_seq_len # unused
  2. Exporting a private symbol. _SeqAllToAll (prefixed with _) is exported from __init__.py, effectively promoting it to a public API. If downstream users aren't expected to use it directly, it shouldn't be exported.
  3. No tests. This is a draft PR, but the fix is non-trivial and touches a correctness-critical code path. Tests should cover:
    - The shape fix (Bug 1) with batch_dim_idx=1, scatter_idx < 2
    - Uneven sequence lengths (S % P != 0) producing correct outputs
    - Round-trip correctness: verify SP output matches non-SP baseline

I suggest we separate this PR into two PRs. The first one covers the fix on tensor shape fix (which is straightforward); the second one fixes uneven sequence padding bugs.

@tohtana

tohtana commented Aug 28, 2026

Copy link
Copy Markdown
Collaborator

Hi @harshang03,
We merged another PR that includes part of your fix. Sorry, I should have been more careful in coordinating the two PRs.

As I mentioned in #8317, I think this PR is still worth merging since it contains several other fixes. Please feel free to pick this PR back up if you'd like. I'm happy to help move it forward. (Please tag me so I don't miss any updates)

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]>

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

3 participants