From dbfc252252ae4816dab9d6a0eac8941986ae0c45 Mon Sep 17 00:00:00 2001 From: Siddhant Rajhans <51508945+siddhant-rajhans@users.noreply.github.com> Date: Mon, 2 Nov 2026 23:04:15 +0000 Subject: [PATCH] Fix BF16 AutoEP folding: avoid BF16 round-trip in FP32 accumulation _update_hp_grad applies AutoEP folding correction to lp.grad (BF16), which internally promotes to FP32 for the TP all-reduce but copies the result back to the BF16 grad buffer. The wrapper then casts this rounded BF16 value to FP32 for accumulation, introducing an unnecessary precision loss between the FP32 reduction and FP32 accumulation. Promote the gradient to FP32 before the folding correction so the TP reduction result feeds directly into the high-precision accumulation buffer without a BF16 round-trip. Fixes #8913 Signed-off-by: Siddhant Rajhans <51508945+siddhant-rajhans@users.noreply.github.com> --- deepspeed/runtime/bf16_optimizer.py | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/deepspeed/runtime/bf16_optimizer.py b/deepspeed/runtime/bf16_optimizer.py index 2753c9fed0f7..9b002af1b6ad 100644 --- a/deepspeed/runtime/bf16_optimizer.py +++ b/deepspeed/runtime/bf16_optimizer.py @@ -509,18 +509,22 @@ def _update_hp_grad(self, lp, group_idx, param_idx, clear_lp_grads): if lp.grad is None: return + hp_grad = self.fp32_groups_gradients[group_idx][param_idx] + assert hp_grad is not None, \ + f'high precision param has no gradient, lp param_id = {id(lp)} group_info = [{group_idx}][{param_idx}]' + if self.autoep_folding_tp_group is not None and getattr(lp, "ds_grad_is_ready", True): + # Promote to FP32 before folding so the TP reduction result is + # accumulated directly without a BF16 round-trip (#8913). + fp32_grad = lp.grad.float() apply_folding_correction_to_grad_buffer(self.autoep_folding_spec, lp, - lp.grad, + fp32_grad, tp_group=self.autoep_folding_tp_group, param_name=self.param_names.get(lp)) - - hp_grad = self.fp32_groups_gradients[group_idx][param_idx] - assert hp_grad is not None, \ - f'high precision param has no gradient, lp param_id = {id(lp)} group_info = [{group_idx}][{param_idx}]' - - hp_grad.data.add_(lp.grad.data.to(hp_grad.dtype).view(hp_grad.shape)) + hp_grad.data.add_(fp32_grad.data.view(hp_grad.shape)) + else: + hp_grad.data.add_(lp.grad.data.to(hp_grad.dtype).view(hp_grad.shape)) lp._hp_grad = hp_grad self.fp32_groups_has_gradients[group_idx][param_idx] = True