Repository navigation
Sum GPTBigCode's shared key/value gradient across tensor-parallel ranks - #8928
Conversation
With multi-query attention every rank holds the whole key/value block of the fused c_attn but attends with only its own query heads, so its gradient for those rows is partial. Nothing summed them, so the ranks applied different updates to rows that must stay identical and training departed from the unsharded model. All-reduce the gradient of those rows in c_attn's weight and bias across the tensor-parallel group. Fixes deepspeedai#8927 Signed-off-by: Achyuthan Sivasankar <[email protected]>
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.
An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0bdd7b73ac
ℹ️ 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".
|
|
||
| def sum_kv_rows(grad): | ||
| grad = grad.clone() | ||
| dist.all_reduce(grad.narrow(0, kv_start, grad.shape[0] - kv_start), group=group) |
There was a problem hiding this comment.
Count replicated K/V rows once during clipping
With the default positive gradient_clipping (1.0), this new all-reduce leaves the full summed K/V gradient in every TP copy. config_tp_params marks the entire fused weight and bias as model-parallel, so clip_grad_norm_ and the ZeRO 1/2/3 norm routines include each local tensor and then sum norms across the model-parallel group; consequently the logical K/V squared norm is counted tp_world_size times while the sharded query rows are counted once. Whenever clipping activates, the coefficient is therefore too small and AutoTP updates no longer match the unsharded model; the added test explicitly sets clipping to 0.0, so it cannot detect this default-path numerical regression. The replicated segment needs to be excluded on all but one TP rank (without excluding each rank's query segment) when computing the norm.
AGENTS.md reference: AGENTS.md:L37-L38
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Good point, verified. With the default clipping at TP 2, the global norm now counts the replicated K/V rows on every rank: 1.5416 against the true 1.5382 at step 0 on the repro model, so when clipping activates the coefficient is slightly too small. With clipping on, the loss gap against single-device training is 3.3e-5 with this PR versus 5.3e-4 on master, so the default path is much closer but not exact. On master the norm wasn't exact for these rows either: it summed each rank's partial-gradient norm instead of taking the norm of their sum.
Counting rows that are replicated inside a sharded parameter once needs the TP grad-norm code to know about them. That check (is_model_parallel_parameter(p) or mp_rank == 0) is decided per parameter in runtime/utils.py, both ZeRO stages, bf16_optimizer.py and fp16/fused_optimizer.py, so I'd rather do it as a follow-up than widen this fix into the core optimizer paths. I've noted the limitation in the description.
9148ab2
Stage the upstream-targeted NPU workflow in Ascend-CI first, so it can be exercised before being submitted to deepspeedai/DeepSpeed. Triggers are manual-only for now, with a suite input to run either the PR smoke subset or the nightly full set. - PR smoke (non-blocking, 60 min): accelerator, utils, ds_config_model, zero_config, data - Nightly full (360 min): the xpu-max1100 test list plus autotuning, autotp, monitor, pipe and zero variants - Filter TestGPTBigCodeMultiQueryTraining until the NPU teardown hang introduced by deepspeedai/DeepSpeed#8928 is fixed
Stage the upstream-targeted NPU workflow in Ascend-CI first, so it can be exercised before being submitted to deepspeedai/DeepSpeed. Triggers are manual-only for now, with a suite input to run either the PR smoke subset or the nightly full set. - PR smoke (non-blocking, 60 min): accelerator, utils, ds_config_model, zero_config, data - Nightly full (360 min): the xpu-max1100 test list plus autotuning, autotp, monitor, pipe and zero variants - Filter TestGPTBigCodeMultiQueryTraining until the NPU teardown hang introduced by deepspeedai/DeepSpeed#8928 is fixed
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]>
Fixes #8927.
With AutoTP training, multi-query GPTBigCode's fused
c_attngives every rank its slice of the query rows plus the whole key/value block (_bigcode_type_transpose). Each rank attends with only its own query heads, so the gradient it computes for the shared key/value rows covers those heads alone. Nothing summed those partial gradients. Each rank therefore applied a different update to rows that must stay identical, and training departed from the unsharded model.Change
fused_LinearLayernow registers a gradient hook onc_attn's weight and bias for thebigcodetypelayout. The hook all-reduces (sums) the key/value rows across the tensor-parallel group.Test
TestGPTBigCodeMultiQueryTrainingintests/unit/v1/autotp/test_autotp_training.py(world sizes 2 and 4) trains a tiny multi-query GPTBigCode with AutoTP and with plain PyTorch on the same data. It checks three things:c_attn(weight and bias) on every rank equal the single-device ones.atol=1e-5).On
master, the first check fails: 471 of 512 key/value-weight gradient elements differ, by up to 1.4e-2.The test uses plain SGD with
gradient_clipping: 0.0to keep the comparison clean. DeepSpeed clips gradients to norm 1.0 by default and the reference does not, and Adam turns floating-point noise on gradients that are zero in the unsharded model into visible updates.Results
The script from #8927 with
gradient_clipping: 0.0and SGD (lr 0.5), 6 steps, compared with single-device training:mastermasterValidation
macOS 26.5 (arm64, CPU), Python 3.9.6, torch 2.8.0, transformers 4.44.2,
DS_ACCELERATOR=cpu LOCAL_SIZE=4.master.test_autotp_training.py,test_autotp_custom_patterns.py,test_affine_shard_map.pyandtest_autotp_uc_checkpoint.py: 146 passed, 42 failed, 2 skipped.master: 145 passed and the same 42 failures.KeyError: 'flags'from building the CPU Adam op on macOS arm64.yapf0.43.0 is clean.flake8is clean on the changed lines; the 3F824warnings inlayers.pyare onmastertoo and come from a newer pyflakes than the pinned 5.0.4.Not covered here
c_attnis marked as sharded. The clipping coefficient is therefore slightly too small. On the repro model at TP 2 with clipping on, the loss gap against single-device training is 3.3e-5 with this PR and 5.3e-4 onmaster. Counting replicated rows once needs the norm code inruntime/utils.py, both ZeRO stages,bf16_optimizer.pyandfp16/fused_optimizer.pyto know about them, which I'd rather do as a follow-up.multi_query=FalseGPTBigCode still fails in the forward pass under AutoTP (the "Related" note in [BUG] AutoTP training of multi-query GPTBigCode diverges from single-device training at TP > 1 #8927). That is a separate change.torch.compile.