Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions deepspeed/runtime/bf16_optimizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -509,18 +509,24 @@ def _update_hp_grad(self, lp, group_idx, param_idx, clear_lp_grads):
if lp.grad is None:
return

grad = lp.grad
if self.autoep_folding_tp_group is not None and getattr(lp, "ds_grad_is_ready", True):
if self.grad_acc_dtype == torch.float32:
grad = grad.float()
apply_folding_correction_to_grad_buffer(self.autoep_folding_spec,
lp,
lp.grad,
grad,
tp_group=self.autoep_folding_tp_group,
param_name=self.param_names.get(lp))
# Retained LP gradients must still agree with their correction marker.
if grad is not lp.grad:
lp.grad.copy_(grad)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The copy-back is unconditional. It's wasted in two common cases. Under immediate_grad_update, accumulate_hp_grads_and_remove_lp sets lp.grad = None right after this call. For parameters whose folding strategy is SKIP, grad holds the unchanged value. apply_folding_correction_to_grad_buffer returns the strategy, so the copy could be skipped there, and also when the caller is about to drop lp.grad.


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_(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

Expand Down
153 changes: 152 additions & 1 deletion tests/unit/v1/moe/test_autoep_autotp_bf16_folding_parity.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
import torch
from torch.utils.checkpoint import checkpoint

from deepspeed.module_inject.auto_ep_folding import is_autoep_folding_gradient_corrected
from deepspeed.accelerator import get_accelerator
from deepspeed.module_inject.auto_ep_folding import (is_autoep_folding_gradient_corrected,
mark_autoep_folding_partial_router_parameter)
from deepspeed.runtime import bf16_optimizer as bf16_mod
from deepspeed.runtime.bf16_optimizer import BF16_Optimizer
from deepspeed.utils import groups, safe_get_full_fp32_param, safe_get_full_grad
Expand All @@ -29,6 +31,7 @@ def _bf16_optimizer_stub(lp, hp_grad):
optimizer.param_names = {lp: "model.layers.0.mlp.router.gate.weight"}
optimizer.fp32_groups_gradients = [[hp_grad]]
optimizer.fp32_groups_has_gradients = [[False]]
optimizer.grad_acc_dtype = hp_grad.dtype
return optimizer


Expand Down Expand Up @@ -92,6 +95,154 @@ def test_bf16_immediate_grad_update_corrects_every_consumed_gradient(monkeypatch
optimizer.fp32_groups_has_gradients[0][0] = False


class TestBF16FoldingReductionPrecision(DistributedTest):
world_size = 2

@pytest.mark.parametrize("partial_router", [False, True])
@pytest.mark.parametrize("clear_lp_grads", [False, True])
def test_hp_buffer_keeps_fp32_reduction(self, partial_router, clear_lp_grads):
if not get_accelerator().is_bf16_supported():
pytest.skip("requires bfloat16 support")
device = get_accelerator().current_device_name()
lp = torch.nn.Parameter(torch.ones(2, dtype=torch.bfloat16, device=device))
local_values = [1.0, 1.0078125] if dist.get_rank() == 0 else [1.0078125, 1.0]
lp.grad = torch.tensor(local_values, dtype=torch.bfloat16, device=device)
hp_grad = torch.zeros(2, dtype=torch.float32, device=device)
optimizer = _bf16_optimizer_stub(lp, hp_grad)
optimizer.autoep_folding_tp_group = dist.get_world_group()
if partial_router:
mark_autoep_folding_partial_router_parameter(lp)

# Both inputs are exact BF16 values, but their FP32 sum and mean are BF16 midpoints.
expected = torch.full_like(hp_grad, 2.0078125 if partial_router else 1.00390625)
optimizer._update_hp_grad(lp, group_idx=0, param_idx=0, clear_lp_grads=clear_lp_grads)
torch.testing.assert_close(hp_grad, expected, rtol=0, atol=0)
assert is_autoep_folding_gradient_corrected(lp)
expected_lp = torch.zeros_like(lp) if clear_lp_grads else expected.to(torch.bfloat16)
torch.testing.assert_close(lp.grad, expected_lp, rtol=0, atol=0)

# Pin the marker contract: a retained LP gradient is already corrected when consumed again.
optimizer._update_hp_grad(lp, group_idx=0, param_idx=0, clear_lp_grads=clear_lp_grads)
torch.testing.assert_close(hp_grad, expected + expected_lp.float(), rtol=0, atol=0)


class _FoldingPrecisionModel(torch.nn.Module):

def __init__(self):
super().__init__()
self.router = torch.nn.Parameter(torch.ones(2))
self.sharded = torch.nn.Parameter(torch.ones(2))
# Each TP rank owns this auxiliary shard, keeping its norm input nonempty.
self.sharded.model_parallel = True

def forward(self, router_input, sharded_input):
return (self.router * router_input).float().sum() + (self.sharded * sharded_input).float().sum()


class TestBF16FoldingPrecisionTraining(DistributedTest):
world_size = 2
reuse_dist_env = False

@pytest.mark.parametrize("immediate_grad_update", [False, True])
@pytest.mark.parametrize("micro_batches", [1, 2])
def test_fp32_gradients_and_clipped_updates(self, immediate_grad_update, micro_batches):
if not get_accelerator().is_bf16_supported():
pytest.skip("requires bfloat16 support")
groups._init_tp_mesh_device(tensor_model_parallel_size=2)
config = {
"train_micro_batch_size_per_gpu": 1,
"gradient_accumulation_steps": micro_batches,
"gradient_clipping": 0.5,
# Keep the later DP reduction from imposing a separate BF16 rounding boundary.
"communication_data_type": "fp32",
"optimizer": {
"type": "SGD",
"params": {
"lr": 0.1
}
},
"zero_allow_untested_optimizer": True,
"zero_optimization": {
"stage": 1
},
"bf16": {
"enabled": True,
"immediate_grad_update": immediate_grad_update
},
"data_types": {
"grad_accum_dtype": "fp32"
},
}
engine, _, _, _ = deepspeed.initialize(model=_FoldingPrecisionModel(), config=config, mpu=groups)
try:
assert isinstance(engine.optimizer, BF16_Optimizer)
assert dist.get_world_size(groups.get_tensor_model_parallel_group()) == 2
assert dist.get_world_size(groups.get_data_parallel_group()) == 1
folding_spec = SimpleNamespace(tp_size=2, mp_mode="tp")
engine._autoep_folding_spec = folding_spec
engine.optimizer.configure_autoep_folding_tp_gradient_reduction(folding_spec)
rank = dist.get_rank()
sharded_inputs = [[0.25, 0.5], [0.75, 1.0]]
expected_master = {
name: safe_get_full_fp32_param(param).detach().clone()
for name, param in engine.module.named_parameters()
}
for step in range(2):
expected_router = torch.zeros(2, device=engine.device)
expected_sharded = torch.zeros(2, device=engine.device)
for micro_batch in range(micro_batches):
if micro_batch == 0:
router_values = [1.0, 1.0078125] if rank == 0 else [1.0078125, 1.0]
router_mean = 1.00390625
else:
# Non-immediate GAS>1 already retains its marker until the boundary.
# Equal later inputs isolate precision from that separate lifecycle limitation.
router_values = [1.5, 1.5]
router_mean = 1.5
router_input = torch.tensor(router_values, dtype=torch.bfloat16, device=engine.device)
sharded_input = torch.tensor(sharded_inputs[rank], dtype=torch.bfloat16, device=engine.device)
engine.backward(engine(router_input, sharded_input))
expected_router.add_(router_mean / micro_batches)
expected_sharded.add_(sharded_input.float() / micro_batches)
for name, expected in [("router", expected_router), ("sharded", expected_sharded)]:
param = getattr(engine.module, name)
actual = safe_get_full_grad(param)
assert actual is not None and actual.dtype == torch.float32
torch.testing.assert_close(actual,
expected,
rtol=0,
atol=0,
msg=f"{name} gradient at step {step}, micro-batch {micro_batch}")
if immediate_grad_update:
assert param.grad is None
engine.step()

# A replicated router contributes once; both independent auxiliary shards contribute.
sharded_squared_norm = sum(value**2 for values in sharded_inputs for value in values)
expected_norm = (expected_router.square().sum() + sharded_squared_norm).sqrt()
torch.testing.assert_close(engine.get_global_grad_norm(),
expected_norm,
rtol=1e-6,
atol=1e-7,
msg=f"gradient norm at step {step}")
clip_coefficient = config["gradient_clipping"] / (expected_norm + 1e-6)
for name, gradient in [("router", expected_router), ("sharded", expected_sharded)]:
expected_master[name].add_(gradient * clip_coefficient, alpha=-0.1)
param = getattr(engine.module, name)
torch.testing.assert_close(safe_get_full_fp32_param(param),
expected_master[name],
rtol=0,
atol=1e-7,
msg=f"{name} master update at step {step}")
torch.testing.assert_close(param,
expected_master[name].to(torch.bfloat16),
rtol=0,
atol=0,
msg=f"{name} BF16 update at step {step}")
finally:
engine.destroy()


class _FoldedGradientLifecycleModel(torch.nn.Module):

def __init__(self, expert_scale, reentrant_checkpointing):
Expand Down
Loading