Repository navigation
Enable bf16 check_grad_overflow by default (matching fp16) - #8035
sfc-gh-truwase merged 1 commit into
Conversation
|
Thank you @yongzhe-wang, What is your thought? @sfc-gh-truwase |
|
Thanks @tohtana — good question. A few things that I think bound the sync-cost concern:
if self.bfloat16_enabled():
check_grad_overflow =
self._config.bfloat16_config.check_grad_overflow
elif self.fp16_enabled():
check_grad_overflow = True # fp16 always pays this
else:
check_grad_overflow = FalseThe work it gates — has_overflow(): an isfinite scan over the gradient partition, a scalar all_reduce(MAX), and one .item() — is the same code path fp16 has run by default for years. So this is a well-characterized production cost, not a new one; the PR just gives bf16 the same protection.
|
| Check for gradient overflows and underflows | ||
| check_grad_overflow: bool = True | ||
| """ | ||
| Detect gradient overflow/underflow before optimizer step and skip the step |
There was a problem hiding this comment.
Make this terse, and move the details to the PR. Okay to leave the issue and PR links here.
|
@yongzhe-wang, apologies for the delayed response. Thanks for this PR. Similar to @tohtana's point, performance concern was what prevented making this default. But, I think your arguments are solid: (1) parity with known production-cost of fp16, and (2) potentially reusing the current grad norm scans to reduce cost. I left one minor code cleanup comment. |
46dcf7b to
90c4c8b
Compare
|
@yongzhe-wang Let me know when you think this PR is ready to merge. |
Signed-off-by: Yongzhe Wang <[email protected]>
90c4c8b to
d6fc7d9
Compare
|
@sfc-gh-truwase Rebased onto latest master — branch is up to date, approved, and DCO green. The remaining required checks are waiting on maintainer workflow approval (fork PR). Could you approve the workflow runs and merge when green? Thanks! |
…ai#8035) ## Summary Flip `DeepSpeedBF16Config.check_grad_overflow` default from `False` to `True`, so bf16 users get the same gradient-overflow protection that fp16 users already get by default. ## Motivation The bf16 documentation states bf16 "does not require loss scaling" (deepspeed.ai/docs/config-json/), but this overstates the safety guarantee for the bf16 + ZeRO-2 (non-offload) partition-flat gradient accumulation path. We reproduced a deterministic catastrophic NaN under a small set of training conditions: - ZeRO-2 (non-offload) + bf16 - Mixture-of-Transformers (modality-specific transformer branches) - Heterogeneous per-sample loss masks (e.g. 50% action-invalid samples in robotics VLA training) Under these conditions, a single bf16 element in `engine.optimizer.averaged_gradients[i]` overflows to `+inf`. The downstream `Adam.step` then computes `inf / sqrt(inf) = NaN` in a fused kernel, which simultaneously corrupts the partition slice's `exp_avg`, `exp_avg_sq`, and fp32 master weights. The next forward pass propagates NaN through every layer; the training run is dead with no useful diagnostic. Reproduced consistently in DeepSpeed 0.16.9 - 0.17.1 at step ~22 with our internal repro. The infrastructure to detect and skip such steps was correctly added by deepspeedai#6976 (`check_grad_overflow` option, `DeepSpeedZeroOptimizer.check_overflow` method, and step-skip logic at `stage_1_and_2.step()` lines ~2128-2143). However the default was set to `False` for bf16, so users hitting this condition do not receive the protection. ## Change Single line: `check_grad_overflow: bool = False` -> `check_grad_overflow: bool = True` in `DeepSpeedBF16Config`. Updated docstring + bf16 example block accordingly. ## Backward compatibility Users who have benchmarked the check as too expensive AND have separately confirmed their bf16 path cannot overflow can opt out by setting: \`\`\`json "bf16": { "enabled": true, "check_grad_overflow": false } \`\`\` The runtime cost is one isfinite-style scan over the gradient partition per optimizer step (already implemented in `DeepSpeedZeroOptimizer.check_overflow`); typically under 1% of step wallclock. ## Related - Issue deepspeedai#5242 (open) - bf16+ZeRO-2 NaN on real training runs (Baichuan2-7B + 8x A800) - PR deepspeedai#6976 - introduced `check_grad_overflow` option and underlying skip logic ## Test plan - [x] Reproducer (private repo): with default `False`, run dies at step ~22; with `True`, training survives via DeepSpeed's existing skip-step path. - [x] Existing CI should pass unchanged; this PR only changes a default value in `precision_config.py`. Signed-off-by: Yongzhe Wang <[email protected]> Signed-off-by: nathon-lee <[email protected]>
…ai#8035) ## Summary Flip `DeepSpeedBF16Config.check_grad_overflow` default from `False` to `True`, so bf16 users get the same gradient-overflow protection that fp16 users already get by default. ## Motivation The bf16 documentation states bf16 "does not require loss scaling" (deepspeed.ai/docs/config-json/), but this overstates the safety guarantee for the bf16 + ZeRO-2 (non-offload) partition-flat gradient accumulation path. We reproduced a deterministic catastrophic NaN under a small set of training conditions: - ZeRO-2 (non-offload) + bf16 - Mixture-of-Transformers (modality-specific transformer branches) - Heterogeneous per-sample loss masks (e.g. 50% action-invalid samples in robotics VLA training) Under these conditions, a single bf16 element in `engine.optimizer.averaged_gradients[i]` overflows to `+inf`. The downstream `Adam.step` then computes `inf / sqrt(inf) = NaN` in a fused kernel, which simultaneously corrupts the partition slice's `exp_avg`, `exp_avg_sq`, and fp32 master weights. The next forward pass propagates NaN through every layer; the training run is dead with no useful diagnostic. Reproduced consistently in DeepSpeed 0.16.9 - 0.17.1 at step ~22 with our internal repro. The infrastructure to detect and skip such steps was correctly added by deepspeedai#6976 (`check_grad_overflow` option, `DeepSpeedZeroOptimizer.check_overflow` method, and step-skip logic at `stage_1_and_2.step()` lines ~2128-2143). However the default was set to `False` for bf16, so users hitting this condition do not receive the protection. ## Change Single line: `check_grad_overflow: bool = False` -> `check_grad_overflow: bool = True` in `DeepSpeedBF16Config`. Updated docstring + bf16 example block accordingly. ## Backward compatibility Users who have benchmarked the check as too expensive AND have separately confirmed their bf16 path cannot overflow can opt out by setting: \`\`\`json "bf16": { "enabled": true, "check_grad_overflow": false } \`\`\` The runtime cost is one isfinite-style scan over the gradient partition per optimizer step (already implemented in `DeepSpeedZeroOptimizer.check_overflow`); typically under 1% of step wallclock. ## Related - Issue deepspeedai#5242 (open) - bf16+ZeRO-2 NaN on real training runs (Baichuan2-7B + 8x A800) - PR deepspeedai#6976 - introduced `check_grad_overflow` option and underlying skip logic ## Test plan - [x] Reproducer (private repo): with default `False`, run dies at step ~22; with `True`, training survives via DeepSpeed's existing skip-step path. - [x] Existing CI should pass unchanged; this PR only changes a default value in `precision_config.py`. Signed-off-by: Yongzhe Wang <[email protected]>
…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 <[email protected]> Co-authored-by: Claude Code <[email protected]> Co-authored-by: pengdurice <[email protected]> Co-authored-by: Hongwei Chen <[email protected]>
Summary
Flip
DeepSpeedBF16Config.check_grad_overflowdefault fromFalsetoTrue, so bf16 users get the same gradient-overflow protection that fp16 users already get by default.Motivation
The bf16 documentation states bf16 "does not require loss scaling" (deepspeed.ai/docs/config-json/), but this overstates the safety guarantee for the bf16 + ZeRO-2 (non-offload) partition-flat gradient accumulation path. We reproduced a deterministic catastrophic NaN under a small set of training conditions:
Under these conditions, a single bf16 element in
engine.optimizer.averaged_gradients[i]overflows to+inf. The downstreamAdam.stepthen computesinf / sqrt(inf) = NaNin a fused kernel, which simultaneously corrupts the partition slice'sexp_avg,exp_avg_sq, and fp32 master weights. The next forward pass propagates NaN through every layer; the training run is dead with no useful diagnostic. Reproduced consistently in DeepSpeed 0.16.9 - 0.17.1 at step ~22 with our internal repro.The infrastructure to detect and skip such steps was correctly added by #6976 (
check_grad_overflowoption,DeepSpeedZeroOptimizer.check_overflowmethod, and step-skip logic atstage_1_and_2.step()lines ~2128-2143). However the default was set toFalsefor bf16, so users hitting this condition do not receive the protection.Change
Single line:
check_grad_overflow: bool = False->check_grad_overflow: bool = TrueinDeepSpeedBF16Config. Updated docstring + bf16 example block accordingly.Backward compatibility
Users who have benchmarked the check as too expensive AND have separately confirmed their bf16 path cannot overflow can opt out by setting:
```json
"bf16": {
"enabled": true,
"check_grad_overflow": false
}
```
The runtime cost is one isfinite-style scan over the gradient partition per optimizer step (already implemented in
DeepSpeedZeroOptimizer.check_overflow); typically under 1% of step wallclock.Related
check_grad_overflowoption and underlying skip logicTest plan
False, run dies at step ~22; withTrue, training survives via DeepSpeed's existing skip-step path.precision_config.py.