Skip to content

Keep invalid group-norm sentinels from becoming a finite 1.0 step - #8638

Merged
sfc-gh-truwase merged 3 commits into
masterfrom
fix/invalid-grad-norm-sentinel
Oct 6, 2026
Merged

sfc-gh-truwase merged 3 commits into
masterfrom
fix/invalid-grad-norm-sentinel

Conversation

@sfc-gh-truwase

@sfc-gh-truwase sfc-gh-truwase commented Sep 23, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • DeepSpeed encodes inf/NaN group norms as -1. Combining those with vector_norm squares the sentinel to 1.0, so clipping and Adam treat a failed group as healthy and apply an unclipped step.
  • Treat non-finite or negative group norms as overflow (inf), skip the optimizer step, reset overflow each step, and advance the loss scaler once (including ZeRO-3 / SuperOffload / ZenFlow / FP16 fused+unfused / BF16).
  • Direct unscale_and_clip_grads callers map the sentinel to inf so they still zero gradients instead of using clip_coef=1.

This is split out of the ZeRO-2 oversized-gradient / stream-lifetime work so the sentinel contract can land independently.

Test plan

  • CPU, rebased onto current master (75eb961d1, includes Give rollout cache fakes the per-layer config Transformers now reads #8730): 17 passed in tests/unit/v1/zero/test_invalid_grad_norm.py (combine_grad_norm_groups / get_global_norm / CheckOverflow, ZeRO-1 clip, CPU-offload combine, ZeRO-3 / BF16 / SuperOffload overflow paths)
  • GPU (2× H200, prior run): TestZeROBFloat16Stage3InvalidNormRecovery. Skipped on the rebase machine (2 GPUs required, 1 available)
  • CI unit tests for the touched runtime files, started by the rebase push

@PKUWZP
PKUWZP self-requested a review October 2, 2026 16:17
sfc-gh-truwase and others added 3 commits October 3, 2026 01:01
L2-combining the -1 inf/NaN sentinel with vector_norm squares it to 1.0, so clipping and Adam treat a failed group as healthy. Preserve overflow, skip the step, and update the loss scale once.

Signed-off-by: tunji-ruwase_snow <tunji.ruwase@snowflake.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Keep new coverage on the v1 path instead of extending the legacy runtime test files.

Signed-off-by: tunji-ruwase_snow <tunji.ruwase@snowflake.com>
Stage 3 orthogonalizes before the norm, and the BF16 step reads _uses_muon.

Signed-off-by: tunji-ruwase_snow <tunji.ruwase@snowflake.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
@sfc-gh-truwase
sfc-gh-truwase force-pushed the fix/invalid-grad-norm-sentinel branch from 29d4d98 to 75eb961 Compare October 3, 2026 01:02
@sfc-gh-truwase
sfc-gh-truwase added this pull request to the merge queue Oct 3, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Oct 3, 2026
@sfc-gh-truwase
sfc-gh-truwase added this pull request to the merge queue Oct 5, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Oct 5, 2026
@sfc-gh-truwase
sfc-gh-truwase added this pull request to the merge queue Oct 6, 2026
Merged via the queue into master with commit 991ccf0 Oct 6, 2026
13 checks passed
@sfc-gh-truwase
sfc-gh-truwase deleted the fix/invalid-grad-norm-sentinel branch October 6, 2026 19:03
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Oct 16, 2026
## What

Adds the `world_size` axis to CI, which the current suite does not
cover:

| File | Purpose |
|---|---|
| `.github/workflows/cpu-torch-multi-latest.yml` | Nightly + manual
dispatch: runs the multi-rank CPU tests on a 4-vCPU runner |
| `.github/workflows/cpu-multi-triage.yml` | Routes its outcome through
the existing `ci/nightly_classify.sh` / `ci/nightly_report.sh` protocol
|
| `tests/conftest.py` | The `DS_MULTIRANK_ONLY` collection hook the
workflow selects with (required) |
| `.github/workflows/TEST_SELECTION.md` | Registration of the new
nightly |

## Why

`cpu-torch-latest` advertises a single device, so the per-device gate in
`tests/unit/common.py` skips **every `world_size > 1` test** on that
runner. The
multi-rank path is therefore only exercised on GPU machines, and issues
that show up
there only in a multi-rank configuration go unnoticed.

A recent example: PR deepspeedai#8638 changed the overflow semantics so that
non-finite
group norms force an optimizer step to be skipped, bypassing
`bf16.check_grad_overflow: False`.
`TestZeROBFloat16::test_ignore_grad_overflow` is
`world_size = 2`, so it is collected and *skipped* by the CPU CI and by
any run with
one device; it fails as soon as two ranks execute. Reported as issue
deepspeedai#8805.

## Why a nightly rather than a pre-merge check

The selection is cheap to state and expensive to run (measured in deepspeedai#8381,
4-vCPU
runner):

| Run | Wall time |
|---|---|
| This suite: non-v1 multi-rank half | 68-89 min |
| This suite: `sequential`-marked phase | 13-16 min |
| Longest current pre-merge job (`cpu-torch-latest`) | 39-43 min |
| Longest merge-queue job (`modal-torch-latest`) | 64-71 min |

Putting it in the pre-merge path would roughly triple the critical path
of every PR,
and a single wedged rank would block the merge queue (the suite's known
hang — the
shm op segfaulting on hosts without AVX512 — is fixed by deepspeedai#8701, but the
suite is the
most expensive one to re-run).

## What it runs

- `LOCAL_SIZE=4` so the gate admits `world_size <= 4`;
`DS_MULTIRANK_ONLY=1` deselects
  the single-rank tests that `cpu-torch-latest` already guards.
- Non-v1 half, `timeout 120m`, plus a `sequential`-marked phase,
`timeout 25m` (the
parallel phase deselects those by default, so they would otherwise never
run here).
- Same preset/install/HF-predownload steps as `cpu-torch-latest`, so
both runs agree on
  the environment.
- On failure the last step prints `DS_CI_FAILURE_CLASS=timeout|test` for
triage; a run
that dies before that step is reported as unclassified rather than
guessed.

Triage is a separate workflow with its own issue titles and its own
`nightly-cpu-multi-last-green` tag, so `nightly-last-green` keeps
meaning "the last
revision the full GPU suite verified" and the modal issue dedupe is
untouched.

## Validation

- Workflow YAML parses; `pre-commit` clean.
- Timings above come from the real runs of this configuration in deepspeedai#8381.
- Not yet run as `cpu-torch-multi-latest`: GitHub only exposes
`workflow_dispatch` for
workflows present on the default branch, so the first manual dispatch
has to happen
after this merges. Happy to run it then and follow up with the numbers.

---------

Signed-off-by: Guokai Ma <guokai.ma@intel.com>
Signed-off-by: Ma, Guokai <guokai.ma@intel.com>
@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
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 23, 2026
…p_comm (deepspeedai#9031)

## Problem

With `overlap_comm=true`, ZeRO-1/2 enqueues gradient reduction on
`reduction_stream` and returns without synchronizing. Parameters larger
than `reduce_bucket_size` skip the contiguous IPG buffer and keep their
own gradient storage (`extra_large_param_to_reduce`). After
`average_tensor()` queues the reduction, ranks that do not own such a
parameter release it immediately:

```python
if not self.is_param_in_current_partition[param_id]:
    if self.overlap_comm and self.contiguous_gradients is False:
        self.previous_reduced_grads[comm_dtype].append(param)
    else:
        self.clear_grad_attribute(param)   # param.grad = None
```

Regular parameters are safe here: their `grad.data` was rebound to the
persistent IPG bucket buffer, so clearing `param.grad` only drops a
reference. Oversized gradients never get that rebinding, so their
storage goes back to the caching allocator while the reduction stream
may still be reading it. The allocator can then reuse it for a tensor
allocated on the compute stream (in our case an activation recomputed by
gradient checkpointing), corrupting the gradient. In our 8-GPU run on
0.19.1 the weights turn NaN at step 3; on master the reduced gradient
holds values up to 3.4e38 (bf16 max) and the update is skipped.

Whether a block is exposed depends on how the gradient reaches the
collective. In the attached reproducer, a gradient that lies inside one
partition is passed to the collective as is, and its block is still
`active_pending_free` after `reduce_ipg_grads()` returns (checked with
`torch.cuda.memory_snapshot()`), so the compute stream cannot get it. A
weight cut by a partition boundary whose lower slice is smaller than
`reduce_bucket_size` behaves differently: `allreduce_and_scatter()`
batches the two slices, `flatten()` copies them on the reduction stream,
and nothing records that stream on the source. This is the case that
gets corrupted in the reproducer. It needs at least 3 ranks, because
with 2 a straddling weight is owned by both and never released.

Environment observed on:

- Model: Qwen2.5-7B-class backbone (hidden_size 3584, intermediate_size
18944, 28 layers), the affected `gate_proj` gradient is 67,895,296
elements, 5.29x `reduce_bucket_size`.
- Hardware: 8 GPUs, PCIe attached, no NVLink, bf16.
- DeepSpeed 0.19.1, PyTorch 2.13 nightly, NCCL 2.30.4, fused AdamW,
gradient checkpointing on, grad clip 1.0.
- ZeRO-2 with `overlap_comm=true`, `contiguous_gradients=true`,
`reduce_scatter=true`, `reduce_bucket_size=auto` (= 12,845,056), no
optimizer/parameter offload.
- The code path is unchanged on master (`b43c383f`), where
`_offload_gradient_safety_enabled` is `False` for this config.

## Still broken on master: NaN becomes a silently frozen run

On master (`b43c383f`, 0.19.10) the race is unchanged. What changed is
the symptom: deepspeedai#8035 (bf16 `check_grad_overflow` on by default) and deepspeedai#8638
(non-finite group norm is treated as overflow) detect the corrupted
gradient and skip the update, so the weights stay finite but the model
stops learning.

Same 8-GPU run, same data order, 40 optimizer steps, only `overlap_comm`
differs:

| | `overlap_comm=false` | `overlap_comm=true` |
|---|---|---|
| skipped updates | 0 / 40 | 39 / 40 (every step after the first) |
| reduced gradients | finite, max abs 0.10 to 0.38 | 380 to 3.0k
non-finite per step after step 1, max finite 3.4e38, `grad_norm=inf` |
| probe weight (`layers.19.mlp.gate_proj`) abs sum | changes on 35 of 39
steps | identical on all 39 later steps |
| mean loss, first 5 / last 5 steps | 1.022 / 0.765 | 1.023 / 1.003 |

The skip discards the update; it does not repair the gradient.

## Why the existing fixes don't cover this

- deepspeedai#7965 records the reduction stream on the reduction result and copy
destination buffers. It does not touch `extra_large_param_to_reduce`,
whose storage is the caller's `param.grad`.
- deepspeedai#8632 clones and `record_stream`s oversized gradients, but only when
`cpu_offload` is enabled (`_offload_gradient_safety_enabled`);
non-offloaded paths are explicitly unchanged.
- deepspeedai#8061 orders the multiple producers of the contiguous IPG bucket,
which oversized gradients bypass.

## Fix

Record the reduction stream on the oversized gradient storage before
handing it to `average_tensor()`:

```diff
@@ -2247,6 +2247,11 @@
                     extra_large_grad_reduc.data = extra_large_grad_reduc_for_average.data.view_as(extra_large_grad_reduc) if (not self.zenflow or self.extra_large_param_to_reduce[comm_dtype].dim() == 1) \
                         else extra_large_grad_reduc_for_average.data.view_as(extra_large_grad_reduc.transpose(0, 1))
 
+                    # Oversized gradients bypass the contiguous IPG buffer, so the
+                    # reduction reads the parameter's own storage, which non-owner
+                    # ranks release right after the reduction is enqueued.
+                    if self.overlap_comm and not get_accelerator().resolves_data_dependency():
+                        extra_large_grad_reduc_for_average.record_stream(self.reduction_stream)
                     self.average_tensor(extra_large_grad_reduc_for_average, comm_dtype)
                     del self.extra_large_param_to_reduce[comm_dtype]
                 else:
```

`extra_large_grad_reduc_for_average` shares storage with `param.grad`,
so the mark lands on the block that `clear_grad_attribute()` later
releases. The guards follow the existing `record_stream` call sites in
this file.

## Cost

One `record_stream` per oversized parameter per step: the block stays
alive until the reduction stream drains instead of being recycled
immediately. Measured on 8 GPUs (bf16, fused AdamW, gradient
checkpointing, 12 steps, `record_stream` applied to the oversized
`param.grad`, same storage as in the diff), against the same run without
it: mean step time 3.542 s to 3.565 s (+0.6%), peak allocated 37.35 GB
in both, peak reserved 45.0 to 46.6 GB per rank without and 45.3 to 45.6
GB with. NaN at step 3 is gone for 3 runs x 30 steps.

## Test plan

A standalone reproducer is attached
([repro_oversized_grad_race.py](https://github.com/user-attachments/files/34519304/repro_oversized_grad_race.py),
3 ranks, `torchrun`). It runs ZeRO-2 with `overlap_comm=true`,
`contiguous_gradients=true`, oversized weights and gradient
checkpointing, and shifts the partition boundary so one weight has a
lower slice below `reduce_bucket_size` (the header prints the slices
DeepSpeed produced). To make the race deterministic it delays the
reduction stream with `torch.cuda._sleep` before the collective, and
`--reuse emulate` makes the compute stream allocate the freed block and
overwrite it, standing in for the recomputed activation. With `--reuse
natural` the allocator is left alone, and this small model stays clean
on unpatched code, so the script shows the missing protection rather
than a natural occurrence.

```
DeepSpeed 0.19.1           : [result] WEIGHTS_NAN, step 1 (reused=2, grad_max_abs 3.3e29)
DeepSpeed 0.19.1 + this fix: [result] CLEAN, 6 steps (reused=0)
master b43c383f (0.19.10)  : [result] GRADIENTS_CORRUPTED, 6/6 updates skipped (grad_norm=inf, loss flat)
```

Signed-off-by: miaTian99 <1194695379@qq.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
Co-authored-by: pengdurice <pengduhit@gmail.com>
Co-authored-by: Hongwei Chen <33092912+hwchen2017@users.noreply.github.com>
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.

3 participants