Skip to content

Fix replicated K/V all-reduce to run once per accumulation window - #9064

Draft
VenusTZZ wants to merge 6 commits into
deepspeedai:masterfrom
VenusTZZ:fix-gptbigcode-autotp-defer-kv
Draft

VenusTZZ wants to merge 6 commits into
deepspeedai:masterfrom
VenusTZZ:fix-gptbigcode-autotp-defer-kv

Conversation

@VenusTZZ

Copy link
Copy Markdown
Contributor

Stacked on #8962 (GPTBigCode AutoTP correctness fixes), which should be merged first. Only the last two commits are new. Child-only diff: VenusTZZ/DeepSpeed@1a19b1a...218cbf2. This PR stays Draft until #8962 merges; it will then be rebased onto master and marked ready.

Summary

AutoTP multi-query GPTBigCode keeps a full copy of the key/value (K/V) block on every tensor-parallel (TP) rank, so its gradient needs a TP all-reduce on every micro-batch. With gradient accumulation this repeats the same small collective for every micro-batch, gradient_accumulation_steps times per optimizer step. For ZeRO 0/1 the full window stays in param.grad, so the K/V rows can be all-reduced once at the accumulation boundary instead. This is a performance optimization follow-up to #8962, split out at the reviewer's request; #8962 keeps the correctness fixes only.

Motivation

The per-micro-batch reduce was introduced as a correctness fix in #8962. It is necessary for ZeRO 2/3 and for configurations that move earlier micro-batches out of param.grad, but for ZeRO 0/1 with gradient accumulation it adds 2 × layers all-reduces per micro-batch for a few hundred rows. Measured on a GPTBigCode multi-query attention (MQA) model (24 layers, hidden=2048, 268.8M parameters), TP=4, bf16, ZeRO-1, seq=1024, micro-batch=1. In the table, "accumulation steps" is the number of micro-batches per optimizer step (gradient_accumulation_steps):

Platform Accumulation steps Baseline: per micro-batch Deferred to boundary Step Tokens/s
4×910B4 8 1,467 ms / 5,585 tok/s 1,271 ms / 6,443 tok/s −13.3% +15.4%
4×910B4 32 5,408 ms / 6,060 tok/s 4,508 ms / 7,269 tok/s −16.6% +20.0%
4×A100-SXM4-80GB 8 750.2 ms / 10,920 tok/s 676.1 ms / 12,117 tok/s −9.9% +11.0%
4×A100-SXM4-80GB 32 3,302.5 ms / 9,922 tok/s 2,939.3 ms / 11,148 tok/s −11.0% +12.4%

K/V all-reduce calls per optimizer step drop from 1,536 to 48 at 32 accumulation steps, and from 384 to 48 at 8. The gain is workload-dependent: 4 layers/hidden=4096 was within noise on NPU, and a single accumulation step has no gain by construction.

Design

  • _ReplicatedKvGradReducer keeps its existing tensor hook and post-accumulate fallback. When the engine allows deferral, both hooks leave the local K/V partial in place; at the boundary the post-accumulate hook all-reduces the rows accumulated during the window.
  • DeepSpeedEngine._backward_prologue() publishes the accumulation state to the reducers. Deferral is allowed only when the whole window stays in param.grad: ZeRO 0 (non-BF16 optimizer, no CPU offload) or ZeRO-1 with DeepSpeedZeroOptimizer and no separate gradient-accumulation buffer, more than one accumulation step (gradient_accumulation_steps() > 1), managed gradient accumulation, not inside no_sync/coalesced reduction, and not pipeline parallel. Every other configuration keeps the per-micro-batch path.
  • The state is stored per reducer, so two engines in one process do not overwrite each other.
  • The decision is latched per accumulation window. Deciding per backward would let one window mix the two paths when no_sync covers only the non-boundary micro-batches, and the boundary's whole-window reduce would count already-reduced micro-batches again.
  • A reentrant checkpoint may run the boundary hook more than once; later calls reduce only the rows added since the previous call.

The fallback and the deferral share reducer state, so this branch depends on the reducer added in #8962. It is stacked and should be retargeted after #8962 lands.

Files changed

File Why it changes Diff
deepspeed/module_inject/layers.py Deferral state on the K/V reducer and a delta-based boundary reduce. +54/-11
deepspeed/runtime/engine.py Publish the per-window accumulation state from the backward prologue. +42/-1
tests/unit/v1/autotp/test_autotp_training.py Reducer unit tests and two-micro-batch accumulation parity tests for ZeRO 0/1/2/3, low precision, and no_sync. +236/-1

Testing

Environment

  • NPU: 4×Ascend 910B4, CANN 8.5.1, torch 2.10.0+cpu, torch_npu 2.10.0.post7, transformers 5.19.0
  • CUDA: 4×A100-SXM4-80GB, CUDA 12.6, torch 2.14.1+cu126, transformers 5.20.2

NPU

cd tests/unit
PYTHONPATH=$(git rev-parse --show-toplevel) HCCL_NPU_SOCKET_PORT_RANGE=auto \
python -m pytest -q --forked \
  v1/autotp/test_autotp_training.py::TestGPTBigCodeMultiQueryTraining \
  v1/autotp/test_autotp_training.py::TestGPTBigCodeMultiQueryAccumulation \
  v1/autotp/test_autotp_training.py::test_replicated_kv_gradient_defers_to_accumulation_boundary \
  v1/autotp/test_autotp_training.py::test_replicated_kv_gradient_deferred_boundary_reduces_new_rows

Result: 15 passed in 358.76 s. Coverage:

  • TestGPTBigCodeMultiQueryAccumulation: ZeRO 0/1/2/3 with and without the canonical distributed data parallel (DDP) no_sync pattern, plus fp16/bf16 with fp32 gradient accumulation on ZeRO-1. The test asserts both loss parity against the unsharded reference and the per-step K/V all-reduce count (2/2 per step for deferred windows, 4/4 for fallback windows), so it fails if the feature silently falls back or if the two paths mix.
  • Reducer unit tests: deferral to the boundary, the reentrant boundary delta, and both hook paths.
  • TestGPTBigCodeMultiQueryTraining: single-micro-batch regression (no gradient accumulation), 5 passed.

The tree is unchanged from the implementation before the split (218cbf242^{tree} equals the pre-split e02f9f3c0^{tree}), so the earlier NPU and A100 performance validation still applies.

CUDA

cd tests/unit
CUDA_VISIBLE_DEVICES=3,4,5,7 \
PYTHONPATH=$(git rev-parse --show-toplevel) \
python -m pytest -q --forked \
  v1/autotp/test_autotp_training.py::TestGPTBigCodeMultiQueryTraining \
  v1/autotp/test_autotp_training.py::TestGPTBigCodeMultiQueryAccumulation \
  v1/autotp/test_autotp_training.py::test_replicated_kv_gradient_defers_to_accumulation_boundary \
  v1/autotp/test_autotp_training.py::test_replicated_kv_gradient_deferred_boundary_reduces_new_rows

Result: 15 passed, 1 warning in 186.35 s (0:03:06) at split tip 218cbf242. Same 15-test set as NPU, including the loss-parity and per-step all-reduce-count assertions. This closes the previous CUDA test gap; the split only rewrote history, so the A100 performance numbers measured pre-split apply to this branch.

Not tested

  • Full CUDA AutoTP suite: only the targeted GPTBigCode training/accumulation tests above were rerun after the split.
  • ZeRO-2/3 deferral: they keep the per-micro-batch path by design.
  • torch.compile, pipeline parallelism, and windows that use coalesce_grad_reduction: these take the fallback path and are not benchmarked.
  • NVMe offload: excluded from deferral by the gate; not run.

Dependencies

Notes for review

  • No new config flag; the optimization is automatic for the safe cases and falls back otherwise.
  • The K/V access pattern and the collective shape are unchanged; only the number of calls changes.
  • AI assistance: the change was drafted with Claude Code; the author reviewed the diff and ran the NPU and CUDA validation above.

Checklist

  • NPU validation (4×910B4)
  • CUDA validation after split (4×A100)
  • Performance measurement (NPU + A100)
  • pre-commit (implementation before the split; the split only rewrote history)

GPTBigCode's fused c_attn stores the query rows followed by the whole shared K/V block. transformers 5.x exposes num_key_value_heads=1 for multi-query models, so AutoTP split the fused attention by one head and left every other rank with an empty query shard.

Use the query-head count for replicated-KV layouts, keep the K/V head attributes whole, recompute num_key_value_groups from the local shard, and reject TP widths larger than the query-head count from the shared AutoTP path. Reject an explicit partition_config for MQA until the heuristic attributes can follow an arbitrary shard.

Make the K/V gradient reduction backend-safe: stage a contiguous copy when the view is non-contiguous, then write the reduction back. Register the hook through register_grad_hook so it runs in ZeRO's post-accumulate phase on torch_npu, and accept the two-argument AccumulateGrad signature used before torch 2.1.

Signed-off-by: Venus-Tzz <[email protected]>
Add TP=2/TP=4 parity with ZeRO 0/1/2/3, shard-shape and checkpoint metadata checks, inference logits, TP-width rejection, unit coverage for the replicated-KV attributes and explicit-config guard, and the legacy AccumulateGrad hook signature.

Signed-off-by: Venus-Tzz <[email protected]>
Route the shard unit, K/V row span, and group count through
fusedqkv_utils helpers so the engine warning, init path, width
validation, and update_mp_params share one derivation.

Split the config, module, and sharded K/V attribute lists, and assert
the subset relations so later edits cannot silently diverge.

Signed-off-by: Venus-Tzz <[email protected]>
Keep the pre-accumulate tensor hook for the normal path and add a post-accumulate fallback for backends that skip it. The fallback reduces only the K/V rows added since its previous call, so gradient accumulation does not repeatedly scale earlier micro-batches.

Add a regression test covering both hook paths.

Signed-off-by: Venus-Tzz <[email protected]>
ZeRO 0/1 keep the full gradient local until the accumulation boundary, so GPTBigCode's replicated K/V rows can be all-reduced once per accumulation window instead of once per micro-batch. ZeRO 2/3 consume or partition the gradient during each micro-batch and keep the existing path.

Deferral is allowed only when the whole window stays in param.grad: ZeRO-1 with a separate gradient accumulation buffer, BF16_Optimizer, CPU/NVMe offload, and zenflow keep the per-micro-batch path. The accumulation state is tracked per reducer so two engines in one process do not overwrite each other, and a reentrant boundary reduces only the rows added since the previous boundary.

Add reducer unit tests and a GAS=2 parity test covering ZeRO 0/1/2/3, including fp16/bf16 with fp32 gradient accumulation on ZeRO-1.

Signed-off-by: Venus-Tzz <[email protected]>
A per-backward decision let one window mix the deferred and per-micro-batch paths when no_sync covered only the non-boundary backwards. The boundary's whole-window reduce then counted the micro-batches that had already been reduced before accumulation again.

Latch the decision for the whole window and keep the boundary on the same path. Add the canonical DDP no_sync pattern to the GAS=2 parity test for ZeRO 0/1.

Signed-off-by: Venus-Tzz <[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
@delock
delock self-requested a review November 21, 2026 07:09
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 21, 2026
Fixes deepspeedai#8961.

## Scope

This PR fixes the empty attention shard, the non-contiguous K/V
gradient, and the post-accumulate hook rescaling earlier micro-batches
under gradient accumulation in AutoTP multi-query GPTBigCode at TP > 1.
Parity tests use `gradient_clipping: 0.0`; the default clipping path is
a separate pre-existing issue.

The branch now contains only the four correctness commits (head
`1a19b1aab`). The deferred-reduce optimization discussed in review was
split into follow-up PR deepspeedai#9064 (branch `fix-gptbigcode-autotp-defer-kv`,
2 commits, stacked on this one); this PR is correctness-only and should
merge first.

## Background

GPTBigCode's fused `c_attn` stores the query rows followed by the whole
shared K/V block. With transformers 5.x, `num_key_value_heads=1` makes
AutoTP create empty query shards at TP > 1; some backends also return a
non-contiguous K/V gradient, and torch_npu skipped the plain hook under
ZeRO 1/2. A post-accumulate fallback is needed there, but it must not
reduce the already accumulated K/V gradient again on the next
micro-batch.

## Change

- Detect replicated-K/V layouts and shard the fused attention by query
heads; keep the K/V head attributes whole and recompute
`num_key_value_groups` from the local shard.
- Reject `tp > query heads` from the shared AutoTP path, and reject an
explicit `partition_config` / HF `tp_plan` for this layout until
attribute sharding can follow the actual shard.
- Reduce a contiguous copy when the K/V gradient view is non-contiguous,
then write it back; skip empty K/V blocks on every rank.
- Keep the pre-accumulate tensor hook for the normal path and add a
post-accumulate fallback (including the pre-2.1 `AccumulateGrad`
signature). The fallback reduces only the K/V rows added since its
previous call, so a second backward under gradient accumulation does not
all-reduce and rescale the first micro-batch again.
- Keep the non-replicated warning in `engine.py`; the replicated-KV
rejection lives in AutoTP.

## Files changed

| File | Why it changes | Diff |
|---|---|---|
| `deepspeed/module_inject/auto_tp.py` | Detect replicated-K/V layouts
and shard by query heads; reject illegal TP widths and explicit
partition configs for this layout. | +59/-11 |
| `deepspeed/module_inject/fusedqkv_utils.py` | Recognize the fused QKV
layout and expose the replicated-KV metadata used by sharding and
checkpoint conversion. | +68/-3 |
| `deepspeed/module_inject/layers.py` | Reduce the replicated K/V rows
exactly once per micro-batch; stage a non-contiguous gradient through a
contiguous copy. | +89/-11 |
| `deepspeed/module_inject/tp_shard.py` | Account for the replicated-KV
layout when deriving shard sizes. | +20/-2 |
| `deepspeed/runtime/engine.py` | Reject `tp > query heads` for this
layout; keep the non-replicated warning. | +9/-6 |
| `tests/unit/v1/autotp/test_autotp_custom_patterns.py` | Cover
replicated-KV attribute handling, width checks, and explicit partition
configs. | +130/-1 |
| `tests/unit/v1/autotp/test_autotp_inference.py` | GPTBigCode MQA
inference parity at TP=2. | +59/-0 |
| `tests/unit/v1/autotp/test_autotp_training.py` | Training parity,
shard/checkpoint assertions, K/V hook and accumulation regression tests.
| +135/-19 |

## Test

Run from `tests/unit`:

```bash
python -m pytest -q --forked v1/autotp/test_autotp_training.py::TestGPTBigCodeMultiQueryTraining
python -m pytest -q --forked v1/autotp/test_autotp_inference.py
python -m pytest -q --forked v1/autotp/test_autotp_custom_patterns.py
python -m pytest -q --forked \
  v1/autotp/test_autotp_training.py::test_replicated_kv_gradient_hook_and_staging \
  v1/autotp/test_autotp_training.py::test_replicated_kv_gradient_reduces_each_micro_batch_once
```

- `TestGPTBigCodeMultiQueryTraining` (TP=2): runs ZeRO 0/1/2/3 with DP=2
(`world_size=4`); each case checks four-step loss parity and the K/V
hook, while stage 0 also checks shard shapes, checkpoint metadata, and
identical K/V rows.
- `TestGPTBigCodeMultiQueryTraining` (TP=4): runs stage 0 and checks the
four-way query split.
- `TestGPTBigCodeMultiQueryInference`: compares TP=2 logits with the
unsharded model; illegal-TP rejection is covered by the shared
width-check unit test.
- Unit tests cover replicated-KV attributes, non-MQA explicit configs,
width checks, non-contiguous staging, the pre-2.1 hook signature, and
the two-accumulated-backward delta check for both hook paths.
- Parity tests use `gradient_clipping: 0.0`.

## Results

NPU: 4×Ascend 910B4 (32 GB each), CANN 8.5.1, torch 2.10.0, torch_npu
2.10.0.post7, transformers 5.19.0. At the split tip `1a19b1aab`:

- `test_autotp_custom_patterns.py` + `test_autotp_inference.py`: 45
passed in 417.04 s.
- `TestGPTBigCodeMultiQueryTraining` plus the three gradient-reducer
unit cases: 8 passed in 133.07 s.
- Inference max |Δlogit| = 1.2e-7.
- `pre-commit` passes on all changed files.

CUDA: 4×A100-SXM4-80GB, driver 580.126.16, torch 2.14.1+cu126, NCCL
2.29.3.

- At the split tip, the follow-up PR deepspeedai#9064's branch run (`218cbf242`,
which contains this branch) passed 15 tests: 5 training, 8 accumulation,
and 2 reducer unit tests. The full target suite (custom patterns +
inference + training) has not been rerun on A100 after the split.
- Earlier transformer-version runs: 5.20.2 master fails in SDPA while
this branch passes training, inference, and ZeRO 1/2/3; 4.44.2 master
passes and this branch's staging path is a no-op; 4.57.6 this branch
passes while master hangs at the empty-shard warning.
- The plain tensor hook also fires under ZeRO 1/2 on A100, so the
skipped-hook case is backend-specific.

## Validation matrix

| Axis | Validated |
|---|---|
| ZeRO | stages 0, 1, 2, 3 |
| Offload | none |
| Precision | fp32 |
| Parallelism | AutoTP TP=2/TP=4; ZeRO test TP=2 + DP=2 |
| Gradient accumulation | Unit regression covers two accumulated
backwards; the committed two-micro-batch end-to-end parity test is in
follow-up PR deepspeedai#9064 |
| Accelerators | 4×910B4 (HCCL), 4×A100 (NCCL) |
| Transformers | 4.44.2, 4.57.6, 5.19.0, 5.20.2 |
| Inference | TP=2 logits; illegal-TP rejection via shared unit test |
| Custom / HF partition | rejected for replicated-KV MQA |
| Gradient clipping | disabled in parity tests |

## Not covered

- **Gradient clipping.** The parity tests disable clipping. The norm
path counts replicated K/V rows once per TP rank: at TP=2 the `c_attn`
slice is 1.414×, the full-model norm is 1.0027× in the tiny model, and a
proper clipped-vs-clipped 4-step run differs by 4.72e-4. A
clipped-vs-unclipped run is not a valid parity check. Tracked in deepspeedai#9024.
- **Committed accumulation parity test.** This PR keeps the unit
regression covering two accumulated backwards; the committed
two-micro-batch end-to-end parity test lives in follow-up PR deepspeedai#9064.
- **Precision.** bf16, fp16, and autocast are follow-up; this PR
validates fp32 only.
- **Non-contiguous path on CUDA.** It runs end-to-end on NPU; CUDA uses
the contiguous branch, so it is covered by a synthetic unit test only.
- **Non-MQA GPTBigCode.** `multi_query=False` is unchanged; its forward
failure under AutoTP is pre-existing and noted in deepspeedai#8927.
- **Mixed replicated-KV layouts.** The `tp_meta` adjustment assumes one
replicated-KV layout per model.
- **Inference.** `generate` and a past-KV-cache run are not covered.
- **Performance.** No throughput or peak-memory benchmark; the K/V
all-reduce shape is unchanged.

## CI

`engine.py` is a shared runtime file, so `ci/tests_fetcher.py` selects
the full suite. GPU workflows run in the merge queue; the on-device
results above are the validation for this change.

## AI assistance

AI assistance was used to reproduce the failure, implement the change,
and run the tests; the human submitter reviewed every changed line and
is responsible for the change.

## Related

- deepspeedai#8927: AutoTP multi-query GPTBigCode diverges from single-device
training at TP > 1.
- deepspeedai#8928: K/V gradient all-reduce.
- Follow-up: deepspeedai#9064 (deferred K/V reduce; draft, stacked on this PR;
merge this PR first).

---------

Signed-off-by: Venus-Tzz <[email protected]>
Co-authored-by: Ma, Guokai <[email protected]>
@delock

delock commented Nov 22, 2026

Copy link
Copy Markdown
Collaborator

@VenusTZZ this PR looks good to me, ping me when its ready for review. Thanks!

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

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