From cfc822f92e8c3cb560f8734aaf6638a278ec7c10 Mon Sep 17 00:00:00 2001 From: Sean Bell <1844189+seanbell@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:44:55 +0000 Subject: [PATCH 1/4] bf16: opt-in stochastic rounding of the bf16 parameters from fp32 masters ZeRO-1/2 and BF16_Optimizer copy each rank's fp32 master partition into its bf16 parameters with round-to-nearest after every optimizer step. A master update smaller than half a bf16 spacing does not change the bf16 parameter, so at small learning rates the parameters used by the forward pass and saved in weights-only exports trail the masters by many steps. Add bf16.stochastic_round_params (default false). When set, that copy rounds each element to the bf16 neighbour away from zero with probability equal to its fractional position between its two bf16 neighbours, so the bf16 parameters equal the masters in expectation. The rounding happens before the existing all-gather, so it adds no communication. Draws are seeded from the torch seed and the data-parallel rank, so tensor-parallel replicas of a parameter round identically. The engine refuses the key for optimizers that do not apply it (ZeRO-3, ZenFlow, FP16_Optimizer), and the config refuses it with bf16_master_weights_and_grads. Test: two CPU ranks, eight Adam steps on a constant gradient that move every master less than half a spacing. With the key off, the bf16 parameters stay at round-to-nearest of the masters (unchanged); with it on, they are unbiased within 5 standard errors, for BF16_Optimizer and ZeRO-2 with and without CPU offload. Co-Authored-By: Claude Opus 5.5 --- deepspeed/runtime/bf16_optimizer.py | 6 +- deepspeed/runtime/engine.py | 10 ++ deepspeed/runtime/precision_config.py | 14 +++ deepspeed/runtime/stochastic_rounding.py | 52 +++++++++ deepspeed/runtime/zero/stage_1_and_2.py | 11 +- docs/_pages/config-json.md | 6 + tests/unit/v1/half_precision/test_bf16.py | 131 ++++++++++++++++++++++ 7 files changed, 226 insertions(+), 4 deletions(-) create mode 100644 deepspeed/runtime/stochastic_rounding.py diff --git a/deepspeed/runtime/bf16_optimizer.py b/deepspeed/runtime/bf16_optimizer.py index 5ff7626e5d92..da513ef4259e 100644 --- a/deepspeed/runtime/bf16_optimizer.py +++ b/deepspeed/runtime/bf16_optimizer.py @@ -10,6 +10,7 @@ from deepspeed import comm as dist from deepspeed.runtime.constants import PIPE_REPLICATED from deepspeed.runtime.base_optimizer import ZeROOptimizer +from deepspeed.runtime.stochastic_rounding import StochasticRoundingCopy from packaging import version as pkg_version from deepspeed.git_version_info import version from deepspeed.runtime.utils import (get_global_norm_of_tensors, clip_tensors_by_global_norm, DummyOptim, @@ -88,6 +89,9 @@ def __init__(self, self.allgather_bucket_size = int(allgather_bucket_size) self.dp_process_group = dp_process_group self.dp_rank = dist.get_rank(group=self.dp_process_group) + self._copy_to_lp = torch.Tensor.copy_ + if bfloat16_config.stochastic_round_params: + self._copy_to_lp = StochasticRoundingCopy(self.dp_rank) self.has_moe_layers = has_moe_layers self.non_expert_gradients = [] self.real_dp_process_group = [dp_process_group for i in range(len(self.optimizer.param_groups))] @@ -599,7 +603,7 @@ def update_lp_params(self): for i, (bf16_partitions, fp32_partition) in enumerate(zip(self.bf16_partitioned_groups, self.fp32_groups_flat_partition)): partition_id = dist.get_rank(group=self.real_dp_process_group[i]) - bf16_partitions[partition_id].data.copy_(fp32_partition.data) + self._copy_to_lp(bf16_partitions[partition_id].data, fp32_partition.data) all_gather_dp_groups(groups_flat=self.bf16_groups_flat, partitioned_param_groups=self.bf16_partitioned_groups, diff --git a/deepspeed/runtime/engine.py b/deepspeed/runtime/engine.py index 3beb985491f7..87d04b4a40d6 100644 --- a/deepspeed/runtime/engine.py +++ b/deepspeed/runtime/engine.py @@ -1723,6 +1723,9 @@ def bf16_master_weights_and_gradients(self): def bf16_optimizer_states(self): return self._config.bfloat16_config.bf16_optimizer_states + def bf16_stochastic_round_params(self): + return self.bfloat16_enabled() and self._config.bfloat16_config.stochastic_round_params + def torch_autocast_enabled(self) -> bool: return self._config.torch_autocast_enabled @@ -2443,6 +2446,12 @@ def _configure_optimizer(self, client_optimizer, model_parameters): else: self.optimizer = basic_optimizer + # Subclasses such as ZenFlow's override the step that applies the rounding, so match exact types. + if self.bf16_stochastic_round_params() and type( + self.optimizer) not in (BF16_Optimizer, DeepSpeedZeroOptimizer): + raise ValueError("bf16.stochastic_round_params supports BF16_Optimizer and ZeRO stage 1/2 " + f"(DeepSpeedZeroOptimizer); this engine uses {type(self.optimizer).__name__}") + self._configure_autoep_folding_optimizer_gradient_reduction() log_dist("DeepSpeed Final Optimizer = {}".format(self.optimizer.__class__.__name__), ranks=[0]) @@ -2777,6 +2786,7 @@ def _configure_zero_optimizer(self, optimizer): fp16_master_weights_and_gradients=self.fp16_master_weights_and_gradients(), bf16_master_weights_and_gradients=self.bf16_master_weights_and_gradients(), bf16_optimizer_states=self.bf16_optimizer_states(), + bf16_stochastic_round_params=self.bf16_stochastic_round_params(), gradient_accumulation_dtype=gradient_accumulation_dtype, communication_data_type=self.communication_data_type, elastic_checkpoint=self.zero_elastic_checkpoint(), diff --git a/deepspeed/runtime/precision_config.py b/deepspeed/runtime/precision_config.py index 775f2c4a1e6b..9d9fe995fbf0 100644 --- a/deepspeed/runtime/precision_config.py +++ b/deepspeed/runtime/precision_config.py @@ -70,6 +70,20 @@ class DeepSpeedBF16Config(DeepSpeedConfigModel): Keep optimizer states in bf16 (only valid when bf16_master_weights_and_grads is enabled). """ + stochastic_round_params: bool = False + """ + Round the bf16 parameters from their fp32 master weights stochastically instead of to nearest (after each optimizer + step and after a universal-checkpoint load), so updates smaller than half a bf16 spacing still reach the + parameters in expectation. Supported by ZeRO stages 1 and 2 and by BF16_Optimizer; requires fp32 master weights. + """ + + @model_validator(mode="after") + def _validate_stochastic_round_params(self): + if self.stochastic_round_params and self.bf16_master_weights_and_grads: + raise ValueError("bf16.stochastic_round_params rounds from fp32 master weights and cannot be combined " + "with bf16.bf16_master_weights_and_grads") + return self + ######################################### # FP16 support diff --git a/deepspeed/runtime/stochastic_rounding.py b/deepspeed/runtime/stochastic_rounding.py new file mode 100644 index 000000000000..065bf2f273ae --- /dev/null +++ b/deepspeed/runtime/stochastic_rounding.py @@ -0,0 +1,52 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team + +import torch + +# Bounds the temporaries of one rounding pass, however large a partition is. +_CHUNK_NUMEL = 1 << 24 + + +def stochastic_round_to_bf16_(dst, src, generator): + """Copy fp32 ``src`` into bf16 ``dst``, rounding each element to one of its two bf16 neighbours at random. + + An element rounds away from zero with probability equal to its distance from the neighbour toward zero, as a + fraction of the spacing between the two, so ``E[dst] == src``. An fp32 master update smaller than half a bf16 + spacing therefore still reaches ``dst`` in expectation, where round-to-nearest would leave ``dst`` unchanged. + Non-finite values round to nearest; finite values beyond the bf16 range can round to infinity. + """ + src = src.view(-1) + dst = dst.view(-1) + for start in range(0, src.numel(), _CHUNK_NUMEL): + numel = min(_CHUNK_NUMEL, src.numel() - start) + chunk = src.narrow(0, start, numel) + # Adding 16 random bits below bf16's last mantissa bit and truncating them rounds the magnitude up with the + # probability of the dropped fraction; fp32 is sign-magnitude, so this holds for either sign. + noise = torch.randint(0, 1 << 16, (numel, ), dtype=torch.int32, device=chunk.device, generator=generator) + truncated = noise.add_(chunk.view(torch.int32)).bitwise_and_(-(1 << 16)).view(torch.float32) + rounded = torch.where(torch.isfinite(chunk), truncated, chunk) + dst.narrow(0, start, numel).copy_(rounded) + + +class StochasticRoundingCopy: + """``copy_(dst, src)`` replacement for the fp32-master to bf16-parameter copy (``bf16.stochastic_round_params``). + + Draws come from one generator per device, seeded from ``torch.initial_seed()`` and the data-parallel rank, so + tensor-parallel ranks holding a replicated parameter at the same offsets round it identically. Draws are not + checkpointed. Destinations that are not bf16 (parameters kept in fp32) are copied exactly. + """ + + def __init__(self, dp_rank): + self.seed = (torch.initial_seed() + dp_rank) % (1 << 64) + self.generators = {} + + def __call__(self, dst, src): + if dst.dtype != torch.bfloat16: + dst.copy_(src) + return + generator = self.generators.get(src.device) + if generator is None: + generator = torch.Generator(device=src.device) + generator.manual_seed(self.seed) + self.generators[src.device] = generator + stochastic_round_to_bf16_(dst, src, generator) diff --git a/deepspeed/runtime/zero/stage_1_and_2.py b/deepspeed/runtime/zero/stage_1_and_2.py index 2da2ce686ba9..95083f3af91f 100644 --- a/deepspeed/runtime/zero/stage_1_and_2.py +++ b/deepspeed/runtime/zero/stage_1_and_2.py @@ -21,6 +21,7 @@ unpin_offloaded_optimizer_states) from deepspeed.runtime.base_optimizer import ZeROOptimizer from deepspeed.runtime.fp16.loss_scaler import CreateLossScaler +from deepspeed.runtime.stochastic_rounding import StochasticRoundingCopy from deepspeed.runtime.torch_autocast import get_autocast_dtype, get_all_comm_dtypes, is_autocast_initialized, sort_dtypes from deepspeed.runtime.utils import (empty_cache, see_memory_usage, has_inf_or_nan, inf, is_model_parallel_parameter, align_dense_tensors, all_gather_dp_groups, mask_nan_or_inf_with_val_inplace, @@ -203,6 +204,7 @@ def __init__(self, fp16_master_weights_and_gradients=False, bf16_master_weights_and_gradients=False, bf16_optimizer_states=False, + bf16_stochastic_round_params=False, elastic_checkpoint=False, check_grad_overflow=True, compute_grad_norm=True, @@ -248,6 +250,9 @@ def __init__(self, self.elastic_checkpoint = elastic_checkpoint self.parameter_alignment = parameter_alignment + self._copy_to_bit16 = torch.Tensor.copy_ + if bf16_stochastic_round_params: + self._copy_to_bit16 = StochasticRoundingCopy(dist.get_rank(group=dp_process_group)) self.check_grad_overflow = check_grad_overflow self.compute_grad_norm = compute_grad_norm self.param_names = param_names @@ -3209,7 +3214,7 @@ def step(self, closure=None): bit16_partitions = self.parallel_partitioned_bit16_groups[i] fp32_partition = self.single_partition_of_fp32_groups[i] bit16_partition_buffer = self.param_buffer_of_bit16_for_cpu_offload_groups[i] - bit16_partition_buffer.data.copy_(fp32_partition.data) + self._copy_to_bit16(bit16_partition_buffer.data, fp32_partition.data) bit16_partitions[partition_id].data.copy_(bit16_partition_buffer.data, non_blocking=True) self._release_preflattened_grad_buffers(i) self.averaged_gradients[i] = None @@ -3259,7 +3264,7 @@ def step(self, closure=None): del single_grad_partition bit16_partitions = self.parallel_partitioned_bit16_groups[i] fp32_partition = self.single_partition_of_fp32_groups[i] - bit16_partitions[partition_id].data.copy_(fp32_partition.data) + self._copy_to_bit16(bit16_partitions[partition_id].data, fp32_partition.data) self.timers(OPTIMIZER_STEP_TIMER).stop() see_memory_usage('After optimizer before all-gather') @@ -3290,7 +3295,7 @@ def update_lp_params(self): for i, (bit16_partitions, fp32_partition) in enumerate( zip(self.parallel_partitioned_bit16_groups, self.single_partition_of_fp32_groups)): partition_id = dist.get_rank(group=self.real_dp_process_group[i]) - bit16_partitions[partition_id].data.copy_(fp32_partition.data) + self._copy_to_bit16(bit16_partitions[partition_id].data, fp32_partition.data) all_gather_dp_groups(groups_flat=self.bit16_groups_flat, partitioned_param_groups=self.parallel_partitioned_bit16_groups, diff --git a/docs/_pages/config-json.md b/docs/_pages/config-json.md index ed5f42684c10..68032f2a755d 100644 --- a/docs/_pages/config-json.md +++ b/docs/_pages/config-json.md @@ -360,6 +360,12 @@ Example of **scheduler** | ----------- | ------- | | Keep optimizer states in bf16 as well. Requires `bf16_master_weights_and_grads=true`. Offload is optional: without `offload_optimizer` the bf16 states stay on the GPU; with `offload_optimizer` (`DeepSpeedCPUAdam`) they are offloaded to CPU memory in bf16. The offloaded state (bf16 master weights plus the two bf16 Adam moments) is then ~6 bytes/param, versus ~10 bytes/param when the moments are kept in fp32. | `false` | +**bf16:stochastic_round_params**: [boolean] + +| Description | Default | +| ----------- | ------- | +| Copy the fp32 master weights into the bf16 parameters with stochastic rounding instead of round-to-nearest, after each optimizer step and after a universal-checkpoint load: each element rounds to the bf16 neighbour away from zero with probability equal to its fractional position between its two bf16 neighbours, so the bf16 parameters equal the fp32 masters in expectation. With round-to-nearest, a master update smaller than half a bf16 spacing (about \|w\|/256) leaves the bf16 parameter unchanged, so at small learning rates the parameters used for the forward pass and saved in weights-only exports can trail the fp32 masters by many steps. Supported by ZeRO stages 1 and 2 (with or without optimizer offload) and by `BF16_Optimizer`; requires fp32 master weights (`bf16_master_weights_and_grads=false`). Adds no communication, but one 16-bit random draw and a few elementwise operations per master element per step, on the device that holds the master partition. With CPU optimizer offload that is the host, where the draw is serial: about 8 ns per element on a 64-thread Xeon (about 8 s per step for 10^9 elements per rank), versus 0.02 ns for the round-to-nearest copy. Draws are seeded from the torch seed and the data-parallel rank, so tensor-parallel ranks with the same torch seed round a replicated parameter identically; parameters tied across pipeline stages may round differently. | `false` | + **Support matrix (bf16 master weights/gradients)** | ZeRO stage | bf16_optimizer_states=False | bf16_optimizer_states=True | diff --git a/tests/unit/v1/half_precision/test_bf16.py b/tests/unit/v1/half_precision/test_bf16.py index aea974a442a1..332694e2e3d0 100644 --- a/tests/unit/v1/half_precision/test_bf16.py +++ b/tests/unit/v1/half_precision/test_bf16.py @@ -14,6 +14,7 @@ from deepspeed import comm as dist from deepspeed.accelerator import get_accelerator from deepspeed.runtime.bf16_optimizer import BF16_Optimizer +from deepspeed.runtime.zero.stage_1_and_2 import DeepSpeedZeroOptimizer from deepspeed.utils import safe_get_full_fp32_param, safe_get_full_grad from unit.v1.zero.test_zero_user_backward import (initialize_distributed, create_ddp_model, collect_ddp_gradients, collect_gradients_safe, compare_gradients) @@ -669,3 +670,133 @@ def test_split_and_unsplit_gradients_match_the_global_reference(self, zero_stage msg=f"{name} at step {step}") before[name] = after.clone() engine.destroy() + + +_SR_NUMEL = (1 << 16) + 1 # odd, so the last rank's partition ends in padding +_SR_STEPS = 8 +_SR_LR = 1e-4 # 8 steps move a master by 8e-4, less than half the bf16 spacing of any |w| in [0.3, 1) + + +class _ConstantGradientModel(torch.nn.Module): + """Every element's gradient is 1, so each Adam step moves every fp32 master by exactly -lr.""" + + def __init__(self): + super().__init__() + generator = torch.Generator().manual_seed(0) + magnitude = torch.rand(_SR_NUMEL, generator=generator) * 0.7 + 0.3 + sign = torch.randint(0, 2, (_SR_NUMEL, ), generator=generator) * 2 - 1 + self.weight = torch.nn.Parameter((sign * magnitude).to(torch.bfloat16).float()) + + def forward(self): + return self.weight.float().sum() + + +def _bf16_neighbours(master): + """The bf16 values just below and just above each fp32 ``master`` (equal when it is a bf16 value).""" + nearest = master.to(torch.bfloat16) + up = torch.nextafter(nearest, torch.full_like(nearest, float("inf"))) + down = torch.nextafter(nearest, torch.full_like(nearest, float("-inf"))) + master = master.double() + low = torch.where(nearest.double() <= master, nearest, down).double() + high = torch.where(nearest.double() >= master, nearest, up).double() + return low, high + + +@pytest.mark.parametrize("stochastic", [False, True]) +@pytest.mark.parametrize("zero_stage, offload, grad_accum_dtype, optimizer_type", [ + (1, False, "fp32", BF16_Optimizer), + (2, False, "bf16", DeepSpeedZeroOptimizer), + (2, True, "bf16", DeepSpeedZeroOptimizer), +]) +class TestBF16StochasticRoundParams(DistributedTest): + world_size = 2 + + def test_bf16_params_track_fp32_masters(self, stochastic, zero_stage, offload, grad_accum_dtype, optimizer_type): + if not bf16_required_version_check(): + pytest.skip( + " DeepSpeed BFloat16 tests need torch >= 1.10, NCCL >= 2.10.3, CUDA > =11.0 and HW support for BFloat16 to run correctly" + ) + zero_config = {"stage": zero_stage} + if offload: + zero_config["offload_optimizer"] = {"device": "cpu"} + config_dict = { + "train_micro_batch_size_per_gpu": 1, + "bf16": { + "enabled": True, + "stochastic_round_params": stochastic + }, + "data_types": { + "grad_accum_dtype": grad_accum_dtype + }, + "zero_optimization": zero_config, + "zero_force_ds_cpu_optimizer": False, + } + model = _ConstantGradientModel() + optimizer = torch.optim.Adam(model.parameters(), lr=_SR_LR) + engine, _, _, _ = deepspeed.initialize(config=config_dict, model=model, optimizer=optimizer) + assert type(engine.optimizer) is optimizer_type + assert getattr(engine.optimizer, "cpu_offload", False) == offload + + weight = engine.module.weight + initial = weight.detach().cpu().clone() + for _ in range(_SR_STEPS): + engine.backward(engine()) + engine.step() + served = weight.detach().cpu() + master = safe_get_full_fp32_param(weight).detach().cpu() + + gathered = [torch.empty(_SR_NUMEL, device=weight.device) for _ in range(dist.get_world_size())] + dist.all_gather(gathered, weight.detach().float()) + assert all(torch.equal(g, gathered[0]) for g in gathered) + expected_master = initial.double() - _SR_STEPS * _SR_LR + torch.testing.assert_close(master.double(), expected_master, rtol=0, atol=1e-6) + + if not stochastic: + # Round-to-nearest: no master moved half a bf16 spacing, so no bf16 parameter moved. + assert torch.equal(served, master.to(torch.bfloat16)) + assert torch.equal(served, initial) + else: + low, high = _bf16_neighbours(master) + served = served.double() + assert ((served == low) | (served == high)).all() + between = high > low + spacing = (high - low)[between] + fraction = (master.double() - low)[between] / spacing + # Unbiased: the summed error is within 5 standard errors of 0. Round-to-nearest misses by ~200. + error = ((served - master.double())[between] / spacing).sum() + standard_error = (fraction * (1 - fraction)).sum().sqrt() + assert error.abs() < 5 * standard_error, (error, standard_error) + engine.destroy() + + +@pytest.mark.parametrize("zero_config, bf16_config", [ + ({ + "stage": 3 + }, {}), + ({ + "stage": 2 + }, { + "bf16_master_weights_and_grads": True + }), +]) +class TestBF16StochasticRoundParamsUnsupported(DistributedTest): + world_size = 1 + + def test_refused(self, zero_config, bf16_config): + if not bf16_required_version_check(): + pytest.skip( + " DeepSpeed BFloat16 tests need torch >= 1.10, NCCL >= 2.10.3, CUDA > =11.0 and HW support for BFloat16 to run correctly" + ) + config_dict = { + "train_micro_batch_size_per_gpu": 1, + "bf16": { + "enabled": True, + "stochastic_round_params": True, + **bf16_config + }, + "zero_optimization": zero_config, + } + model = _ConstantGradientModel() + optimizer = torch.optim.Adam(model.parameters(), lr=_SR_LR) + with pytest.raises(ValueError, match="stochastic_round_params"): + deepspeed.initialize(config=config_dict, model=model, optimizer=optimizer) From 1fadc115c405a351da80fba634935c0b41fce15a Mon Sep 17 00:00:00 2001 From: Sean Bell <1844189+seanbell@users.noreply.github.com> Date: Sun, 22 Nov 2026 04:26:07 +0000 Subject: [PATCH 2/4] bf16 stochastic rounding: round on the accelerator under CPU offload; test the kernel With CPU optimizer offload, the ZeRO-1/2 step rounded the fp32 master into the host bf16 staging buffer, so the random draw ran on the host, where torch draws serially (about 7 ns per element on 64 threads, against 0.04 ns for the round-to-nearest copy). The rounding now runs on the bf16 parameter's device: each master chunk is copied there in fp32 and rounded in place, and the round-to-nearest default keeps its staging buffer. Add a kernel test: unbiased for either sign and for subnormals (tolerance 5 binomial standard errors at 2^16 draws), exact on bf16 values, nearest on non-finite values including NaNs whose payload would carry into the sign bit, and repeatable under a seeded generator. Co-Authored-By: Claude Opus 5.5 --- deepspeed/runtime/stochastic_rounding.py | 11 ++++--- deepspeed/runtime/zero/stage_1_and_2.py | 10 +++++-- docs/_pages/config-json.md | 2 +- tests/unit/v1/half_precision/test_bf16.py | 35 ++++++++++++++++++++++- 4 files changed, 47 insertions(+), 11 deletions(-) diff --git a/deepspeed/runtime/stochastic_rounding.py b/deepspeed/runtime/stochastic_rounding.py index 065bf2f273ae..80a804e87e9e 100644 --- a/deepspeed/runtime/stochastic_rounding.py +++ b/deepspeed/runtime/stochastic_rounding.py @@ -13,13 +13,14 @@ def stochastic_round_to_bf16_(dst, src, generator): An element rounds away from zero with probability equal to its distance from the neighbour toward zero, as a fraction of the spacing between the two, so ``E[dst] == src``. An fp32 master update smaller than half a bf16 spacing therefore still reaches ``dst`` in expectation, where round-to-nearest would leave ``dst`` unchanged. - Non-finite values round to nearest; finite values beyond the bf16 range can round to infinity. + Non-finite values round to nearest; finite values beyond the bf16 range can round to infinity. The rounding runs + on ``dst``'s device, where ``generator`` lives, so an offloaded master is copied there in fp32. """ src = src.view(-1) dst = dst.view(-1) for start in range(0, src.numel(), _CHUNK_NUMEL): numel = min(_CHUNK_NUMEL, src.numel() - start) - chunk = src.narrow(0, start, numel) + chunk = src.narrow(0, start, numel).to(dst.device) # Adding 16 random bits below bf16's last mantissa bit and truncating them rounds the magnitude up with the # probability of the dropped fraction; fp32 is sign-magnitude, so this holds for either sign. noise = torch.randint(0, 1 << 16, (numel, ), dtype=torch.int32, device=chunk.device, generator=generator) @@ -44,9 +45,7 @@ def __call__(self, dst, src): if dst.dtype != torch.bfloat16: dst.copy_(src) return - generator = self.generators.get(src.device) + generator = self.generators.get(dst.device) if generator is None: - generator = torch.Generator(device=src.device) - generator.manual_seed(self.seed) - self.generators[src.device] = generator + generator = self.generators[dst.device] = torch.Generator(device=dst.device).manual_seed(self.seed) stochastic_round_to_bf16_(dst, src, generator) diff --git a/deepspeed/runtime/zero/stage_1_and_2.py b/deepspeed/runtime/zero/stage_1_and_2.py index 870ce4206c62..175ee0776c86 100644 --- a/deepspeed/runtime/zero/stage_1_and_2.py +++ b/deepspeed/runtime/zero/stage_1_and_2.py @@ -3217,9 +3217,13 @@ def step(self, closure=None): # bit16_partitions[partition_id].data.copy_(fp32_partition.data) bit16_partitions = self.parallel_partitioned_bit16_groups[i] fp32_partition = self.single_partition_of_fp32_groups[i] - bit16_partition_buffer = self.param_buffer_of_bit16_for_cpu_offload_groups[i] - self._copy_to_bit16(bit16_partition_buffer.data, fp32_partition.data) - bit16_partitions[partition_id].data.copy_(bit16_partition_buffer.data, non_blocking=True) + if isinstance(self._copy_to_bit16, StochasticRoundingCopy): + # Round on the accelerator: on the host the random draw is serial, about 5 ns per element. + self._copy_to_bit16(bit16_partitions[partition_id].data, fp32_partition.data) + else: + bit16_partition_buffer = self.param_buffer_of_bit16_for_cpu_offload_groups[i] + bit16_partition_buffer.data.copy_(fp32_partition.data) + bit16_partitions[partition_id].data.copy_(bit16_partition_buffer.data, non_blocking=True) self._release_preflattened_grad_buffers(i) self.averaged_gradients[i] = None diff --git a/docs/_pages/config-json.md b/docs/_pages/config-json.md index c4bcf8231518..f050b6a8b0c3 100644 --- a/docs/_pages/config-json.md +++ b/docs/_pages/config-json.md @@ -364,7 +364,7 @@ Example of **scheduler** | Description | Default | | ----------- | ------- | -| Copy the fp32 master weights into the bf16 parameters with stochastic rounding instead of round-to-nearest, after each optimizer step and after a universal-checkpoint load: each element rounds to the bf16 neighbour away from zero with probability equal to its fractional position between its two bf16 neighbours, so the bf16 parameters equal the fp32 masters in expectation. With round-to-nearest, a master update smaller than half a bf16 spacing (about \|w\|/256) leaves the bf16 parameter unchanged, so at small learning rates the parameters used for the forward pass and saved in weights-only exports can trail the fp32 masters by many steps. Supported by ZeRO stages 1 and 2 (with or without optimizer offload) and by `BF16_Optimizer`; requires fp32 master weights (`bf16_master_weights_and_grads=false`). Adds no communication, but one 16-bit random draw and a few elementwise operations per master element per step, on the device that holds the master partition. With CPU optimizer offload that is the host, where the draw is serial: about 8 ns per element on a 64-thread Xeon (about 8 s per step for 10^9 elements per rank), versus 0.02 ns for the round-to-nearest copy. Draws are seeded from the torch seed and the data-parallel rank, so tensor-parallel ranks with the same torch seed round a replicated parameter identically; parameters tied across pipeline stages may round differently. | `false` | +| Copy the fp32 master weights into the bf16 parameters with stochastic rounding instead of round-to-nearest, after each optimizer step and after a universal-checkpoint load: each element rounds to the bf16 neighbour away from zero with probability equal to its fractional position between its two bf16 neighbours, so the bf16 parameters equal the fp32 masters in expectation. With round-to-nearest, a master update smaller than half a bf16 spacing (about \|w\|/256) leaves the bf16 parameter unchanged, so at small learning rates the parameters used for the forward pass and saved in weights-only exports can trail the fp32 masters by many steps. Supported by ZeRO stages 1 and 2 (with or without optimizer offload) and by `BF16_Optimizer`; requires fp32 master weights (`bf16_master_weights_and_grads=false`). Adds no communication, but one 16-bit random draw and a few elementwise operations per master element per step, on the accelerator. With CPU optimizer offload, the master partition is copied to the accelerator in fp32 for this (4 bytes per element instead of the 2 of the bf16 copy). Draws are seeded from the torch seed and the data-parallel rank, so tensor-parallel ranks with the same torch seed round a replicated parameter identically when it sits at the same offset of their partitions; parameters tied across pipeline stages may round differently. | `false` | **Support matrix (bf16 master weights/gradients)** diff --git a/tests/unit/v1/half_precision/test_bf16.py b/tests/unit/v1/half_precision/test_bf16.py index 332694e2e3d0..1c6ac9901599 100644 --- a/tests/unit/v1/half_precision/test_bf16.py +++ b/tests/unit/v1/half_precision/test_bf16.py @@ -14,6 +14,7 @@ from deepspeed import comm as dist from deepspeed.accelerator import get_accelerator from deepspeed.runtime.bf16_optimizer import BF16_Optimizer +from deepspeed.runtime.stochastic_rounding import stochastic_round_to_bf16_ from deepspeed.runtime.zero.stage_1_and_2 import DeepSpeedZeroOptimizer from deepspeed.utils import safe_get_full_fp32_param, safe_get_full_grad from unit.v1.zero.test_zero_user_backward import (initialize_distributed, create_ddp_model, collect_ddp_gradients, @@ -702,6 +703,38 @@ def _bf16_neighbours(master): return low, high +def test_stochastic_round_to_bf16_kernel(): + tiny = 2.0**-133 # the smallest bf16 subnormal + values = torch.tensor([1 + 2.0**-9, -(1 + 3 * 2.0**-9), 0.3, 2.5 * tiny, -1.25 * tiny]) + draws = 1 << 16 + src = values.repeat_interleave(draws) + dst = torch.empty_like(src, dtype=torch.bfloat16) + stochastic_round_to_bf16_(dst, src, torch.Generator().manual_seed(0)) + # Unbiased for either sign and for subnormals: each value rounds to its upper neighbour with probability equal + # to its position between the two. + low, high = _bf16_neighbours(values) + fraction = (values.double() - low) / (high - low) + rounded = dst.double().view(len(values), draws) + assert ((rounded == low[:, None]) | (rounded == high[:, None])).all() + rounded_up = (rounded == high[:, None]).double().mean(dim=1) + assert ((rounded_up - fraction).abs() < 5 * (fraction * (1 - fraction) / draws).sqrt()).all(), rounded_up + + # The same seed repeats the draw; another seed does not. + again = torch.empty_like(dst) + stochastic_round_to_bf16_(again, src, torch.Generator().manual_seed(0)) + assert torch.equal(again, dst) + stochastic_round_to_bf16_(again, src, torch.Generator().manual_seed(1)) + assert not torch.equal(again, dst) + + # bf16 values are kept exactly. Non-finite values round to nearest, including NaNs whose low bits would carry. + exact = torch.tensor([0.0, -0.0, 1.0, -0.5, tiny, -tiny, torch.finfo(torch.bfloat16).max]) + non_finite = torch.tensor([0x7F800000, -0x00800000, 0x7FFFFFFF, -1], dtype=torch.int32).view(torch.float32) + src = torch.cat([exact, non_finite]).repeat(1000) + out = torch.empty_like(src, dtype=torch.bfloat16) + stochastic_round_to_bf16_(out, src, torch.Generator().manual_seed(2)) + assert torch.equal(out.view(torch.int16), src.to(torch.bfloat16).view(torch.int16)) + + @pytest.mark.parametrize("stochastic", [False, True]) @pytest.mark.parametrize("zero_stage, offload, grad_accum_dtype, optimizer_type", [ (1, False, "fp32", BF16_Optimizer), @@ -762,7 +795,7 @@ def test_bf16_params_track_fp32_masters(self, stochastic, zero_stage, offload, g between = high > low spacing = (high - low)[between] fraction = (master.double() - low)[between] / spacing - # Unbiased: the summed error is within 5 standard errors of 0. Round-to-nearest misses by ~200. + # Unbiased: the summed error is within 5 standard errors of 0. Round-to-nearest misses by about 150. error = ((served - master.double())[between] / spacing).sum() standard_error = (fraction * (1 - fraction)).sum().sqrt() assert error.abs() < 5 * standard_error, (error, standard_error) From 4774c1b10faf0993967aed94e46237145ba70a25 Mon Sep 17 00:00:00 2001 From: Sean Bell <1844189+seanbell@users.noreply.github.com> Date: Sun, 22 Nov 2026 04:59:15 +0000 Subject: [PATCH 3/4] bf16 stochastic rounding: skip the unused offload staging buffer; tighten tests and docs - With CPU offload and the key on, the host bf16 staging buffer (2 bytes per element, pinned with pin_memory) was allocated but never used; it is no longer allocated, and its presence selects the default two-stage copy, so optimizers built without __init__ in unit tests keep working. - Keep the new DeepSpeedZeroOptimizer argument last, so positional callers are unaffected. - Write the finite-value selection into the truncated buffer instead of a new 64 MB result per chunk. - Kernel test: add a value below a binade boundary. Engine test: the off case omits the key; the master tolerance is one fp32 epsilon per step. - Test the bf16-master refusal on a configuration DeepSpeed otherwise accepts (ZeRO-2 with CPU offload), at config level; the ZeRO-3 refusal test fails with an assertion instead of hanging when the refusal is missing. - Docs: unbiased within the finite bf16 range; replicas round alike only with matching seeds, partition layouts and copy order. Co-Authored-By: Claude Opus 5.5 --- deepspeed/runtime/precision_config.py | 6 +-- deepspeed/runtime/stochastic_rounding.py | 11 ++-- deepspeed/runtime/zero/stage_1_and_2.py | 18 +++---- docs/_pages/config-json.md | 2 +- tests/unit/v1/half_precision/test_bf16.py | 65 +++++++++++++++-------- 5 files changed, 60 insertions(+), 42 deletions(-) diff --git a/deepspeed/runtime/precision_config.py b/deepspeed/runtime/precision_config.py index 9d9fe995fbf0..ceef23701cc1 100644 --- a/deepspeed/runtime/precision_config.py +++ b/deepspeed/runtime/precision_config.py @@ -72,9 +72,9 @@ class DeepSpeedBF16Config(DeepSpeedConfigModel): stochastic_round_params: bool = False """ - Round the bf16 parameters from their fp32 master weights stochastically instead of to nearest (after each optimizer - step and after a universal-checkpoint load), so updates smaller than half a bf16 spacing still reach the - parameters in expectation. Supported by ZeRO stages 1 and 2 and by BF16_Optimizer; requires fp32 master weights. + Stochastically round fp32 master weights into the bf16 parameters after each optimizer step and universal-checkpoint + load. The expected result equals the master within the finite bf16 range. Supported by ZeRO stages 1 and 2 and + BF16_Optimizer; requires fp32 master weights. """ @model_validator(mode="after") diff --git a/deepspeed/runtime/stochastic_rounding.py b/deepspeed/runtime/stochastic_rounding.py index 80a804e87e9e..00934dd755a1 100644 --- a/deepspeed/runtime/stochastic_rounding.py +++ b/deepspeed/runtime/stochastic_rounding.py @@ -11,8 +11,7 @@ def stochastic_round_to_bf16_(dst, src, generator): """Copy fp32 ``src`` into bf16 ``dst``, rounding each element to one of its two bf16 neighbours at random. An element rounds away from zero with probability equal to its distance from the neighbour toward zero, as a - fraction of the spacing between the two, so ``E[dst] == src``. An fp32 master update smaller than half a bf16 - spacing therefore still reaches ``dst`` in expectation, where round-to-nearest would leave ``dst`` unchanged. + fraction of the spacing between the two, so ``E[dst] == src`` for values within the finite bf16 range. Non-finite values round to nearest; finite values beyond the bf16 range can round to infinity. The rounding runs on ``dst``'s device, where ``generator`` lives, so an offloaded master is copied there in fp32. """ @@ -25,15 +24,15 @@ def stochastic_round_to_bf16_(dst, src, generator): # probability of the dropped fraction; fp32 is sign-magnitude, so this holds for either sign. noise = torch.randint(0, 1 << 16, (numel, ), dtype=torch.int32, device=chunk.device, generator=generator) truncated = noise.add_(chunk.view(torch.int32)).bitwise_and_(-(1 << 16)).view(torch.float32) - rounded = torch.where(torch.isfinite(chunk), truncated, chunk) - dst.narrow(0, start, numel).copy_(rounded) + torch.where(torch.isfinite(chunk), truncated, chunk, out=truncated) + dst.narrow(0, start, numel).copy_(truncated) class StochasticRoundingCopy: """``copy_(dst, src)`` replacement for the fp32-master to bf16-parameter copy (``bf16.stochastic_round_params``). - Draws come from one generator per device, seeded from ``torch.initial_seed()`` and the data-parallel rank, so - tensor-parallel ranks holding a replicated parameter at the same offsets round it identically. Draws are not + Each device's generator is seeded from ``torch.initial_seed()`` and the data-parallel rank. On like devices, + replicas with the same seed, partition layout and copy order use the same draws. Generator state is not checkpointed. Destinations that are not bf16 (parameters kept in fp32) are copied exactly. """ diff --git a/deepspeed/runtime/zero/stage_1_and_2.py b/deepspeed/runtime/zero/stage_1_and_2.py index 175ee0776c86..097df852518d 100644 --- a/deepspeed/runtime/zero/stage_1_and_2.py +++ b/deepspeed/runtime/zero/stage_1_and_2.py @@ -204,11 +204,11 @@ def __init__(self, fp16_master_weights_and_gradients=False, bf16_master_weights_and_gradients=False, bf16_optimizer_states=False, - bf16_stochastic_round_params=False, elastic_checkpoint=False, check_grad_overflow=True, compute_grad_norm=True, - retain_gpu_grad_partition_until_step=False): + retain_gpu_grad_partition_until_step=False, + bf16_stochastic_round_params=False): super().__init__() @@ -567,9 +567,9 @@ def _enforce_cpu_offload(): weights_partition = self.parallel_partitioned_bit16_groups[i][partition_id].detach().clone().to( device=self.device, dtype=self.master_weights_and_grads_dtype) - if self.cpu_offload: - if self.cpu_offload_pin_memory: - weights_partition = get_accelerator().pin_memory(weights_partition) + if self.cpu_offload_pin_memory: + weights_partition = get_accelerator().pin_memory(weights_partition) + if self.cpu_offload and not bf16_stochastic_round_params: temp_dtype = self.parallel_partitioned_bit16_groups[i][partition_id].dtype temp_buffer_bit16 = torch.full(weights_partition.shape, fill_value=0.0, @@ -3217,13 +3217,13 @@ def step(self, closure=None): # bit16_partitions[partition_id].data.copy_(fp32_partition.data) bit16_partitions = self.parallel_partitioned_bit16_groups[i] fp32_partition = self.single_partition_of_fp32_groups[i] - if isinstance(self._copy_to_bit16, StochasticRoundingCopy): - # Round on the accelerator: on the host the random draw is serial, about 5 ns per element. - self._copy_to_bit16(bit16_partitions[partition_id].data, fp32_partition.data) - else: + if self.param_buffer_of_bit16_for_cpu_offload_groups: bit16_partition_buffer = self.param_buffer_of_bit16_for_cpu_offload_groups[i] bit16_partition_buffer.data.copy_(fp32_partition.data) bit16_partitions[partition_id].data.copy_(bit16_partition_buffer.data, non_blocking=True) + else: + # No staging buffer: stochastic rounding runs on the accelerator, as the host draws serially. + self._copy_to_bit16(bit16_partitions[partition_id].data, fp32_partition.data) self._release_preflattened_grad_buffers(i) self.averaged_gradients[i] = None diff --git a/docs/_pages/config-json.md b/docs/_pages/config-json.md index f050b6a8b0c3..1e3a147645f8 100644 --- a/docs/_pages/config-json.md +++ b/docs/_pages/config-json.md @@ -364,7 +364,7 @@ Example of **scheduler** | Description | Default | | ----------- | ------- | -| Copy the fp32 master weights into the bf16 parameters with stochastic rounding instead of round-to-nearest, after each optimizer step and after a universal-checkpoint load: each element rounds to the bf16 neighbour away from zero with probability equal to its fractional position between its two bf16 neighbours, so the bf16 parameters equal the fp32 masters in expectation. With round-to-nearest, a master update smaller than half a bf16 spacing (about \|w\|/256) leaves the bf16 parameter unchanged, so at small learning rates the parameters used for the forward pass and saved in weights-only exports can trail the fp32 masters by many steps. Supported by ZeRO stages 1 and 2 (with or without optimizer offload) and by `BF16_Optimizer`; requires fp32 master weights (`bf16_master_weights_and_grads=false`). Adds no communication, but one 16-bit random draw and a few elementwise operations per master element per step, on the accelerator. With CPU optimizer offload, the master partition is copied to the accelerator in fp32 for this (4 bytes per element instead of the 2 of the bf16 copy). Draws are seeded from the torch seed and the data-parallel rank, so tensor-parallel ranks with the same torch seed round a replicated parameter identically when it sits at the same offset of their partitions; parameters tied across pipeline stages may round differently. | `false` | +| After each optimizer step and universal-checkpoint load, stochastically round the fp32 master weights into the bf16 parameters. Within the finite bf16 range, rounding chooses between adjacent bf16 values with probabilities that preserve the master value in expectation. This lets updates smaller than half a bf16 spacing reach the parameters used in forward passes and weights-only exports. Finite values outside that range can round to infinity. Supported by ZeRO stages 1 and 2 (including CPU optimizer offload) and by `BF16_Optimizer`; requires fp32 master weights (`bf16_master_weights_and_grads=false`). Each rank makes one random draw per bf16 element on the destination device before the existing all-gather. CPU offload transfers 4 bytes per bf16 parameter to the accelerator for rounding, versus 2 with the default copy. The torch seed and data-parallel rank seed the per-device generator. Replicas on like devices use the same draws when their seeds, partition layouts and copy order match. Parameters tied across pipeline stages sit at different offsets and can round differently. Generator state is not checkpointed. | `false` | **Support matrix (bf16 master weights/gradients)** diff --git a/tests/unit/v1/half_precision/test_bf16.py b/tests/unit/v1/half_precision/test_bf16.py index 1c6ac9901599..c51c7c17a629 100644 --- a/tests/unit/v1/half_precision/test_bf16.py +++ b/tests/unit/v1/half_precision/test_bf16.py @@ -14,6 +14,7 @@ from deepspeed import comm as dist from deepspeed.accelerator import get_accelerator from deepspeed.runtime.bf16_optimizer import BF16_Optimizer +from deepspeed.runtime.config import DeepSpeedConfig from deepspeed.runtime.stochastic_rounding import stochastic_round_to_bf16_ from deepspeed.runtime.zero.stage_1_and_2 import DeepSpeedZeroOptimizer from deepspeed.utils import safe_get_full_fp32_param, safe_get_full_grad @@ -675,11 +676,11 @@ def test_split_and_unsplit_gradients_match_the_global_reference(self, zero_stage _SR_NUMEL = (1 << 16) + 1 # odd, so the last rank's partition ends in padding _SR_STEPS = 8 -_SR_LR = 1e-4 # 8 steps move a master by 8e-4, less than half the bf16 spacing of any |w| in [0.3, 1) +_SR_LR = 1e-4 # 8 steps move a master by 8e-4, less than half the bf16 spacing of any |w| in [0.3, 1] class _ConstantGradientModel(torch.nn.Module): - """Every element's gradient is 1, so each Adam step moves every fp32 master by exactly -lr.""" + """Every element's gradient is 1, so each Adam step moves every fp32 master by approximately -lr.""" def __init__(self): super().__init__() @@ -705,7 +706,7 @@ def _bf16_neighbours(master): def test_stochastic_round_to_bf16_kernel(): tiny = 2.0**-133 # the smallest bf16 subnormal - values = torch.tensor([1 + 2.0**-9, -(1 + 3 * 2.0**-9), 0.3, 2.5 * tiny, -1.25 * tiny]) + values = torch.tensor([1 + 2.0**-9, -(1 + 3 * 2.0**-9), 0.3, 2 - 2.0**-9, 2.5 * tiny, -1.25 * tiny]) draws = 1 << 16 src = values.repeat_interleave(draws) dst = torch.empty_like(src, dtype=torch.bfloat16) @@ -755,8 +756,7 @@ def test_bf16_params_track_fp32_masters(self, stochastic, zero_stage, offload, g config_dict = { "train_micro_batch_size_per_gpu": 1, "bf16": { - "enabled": True, - "stochastic_round_params": stochastic + "enabled": True }, "data_types": { "grad_accum_dtype": grad_accum_dtype @@ -764,6 +764,8 @@ def test_bf16_params_track_fp32_masters(self, stochastic, zero_stage, offload, g "zero_optimization": zero_config, "zero_force_ds_cpu_optimizer": False, } + if stochastic: + config_dict["bf16"]["stochastic_round_params"] = True model = _ConstantGradientModel() optimizer = torch.optim.Adam(model.parameters(), lr=_SR_LR) engine, _, _, _ = deepspeed.initialize(config=config_dict, model=model, optimizer=optimizer) @@ -782,7 +784,9 @@ def test_bf16_params_track_fp32_masters(self, stochastic, zero_stage, offload, g dist.all_gather(gathered, weight.detach().float()) assert all(torch.equal(g, gathered[0]) for g in gathered) expected_master = initial.double() - _SR_STEPS * _SR_LR - torch.testing.assert_close(master.double(), expected_master, rtol=0, atol=1e-6) + # Allow one fp32 epsilon per step for the update near unit magnitude. + master_atol = _SR_STEPS * torch.finfo(torch.float32).eps + torch.testing.assert_close(master.double(), expected_master, rtol=0, atol=master_atol) if not stochastic: # Round-to-nearest: no master moved half a bf16 spacing, so no bf16 parameter moved. @@ -795,41 +799,56 @@ def test_bf16_params_track_fp32_masters(self, stochastic, zero_stage, offload, g between = high > low spacing = (high - low)[between] fraction = (master.double() - low)[between] / spacing - # Unbiased: the summed error is within 5 standard errors of 0. Round-to-nearest misses by about 150. + # Unbiased: the summed error is within 5 standard errors of 0. error = ((served - master.double())[between] / spacing).sum() standard_error = (fraction * (1 - fraction)).sum().sqrt() assert error.abs() < 5 * standard_error, (error, standard_error) engine.destroy() -@pytest.mark.parametrize("zero_config, bf16_config", [ - ({ - "stage": 3 - }, {}), - ({ - "stage": 2 - }, { - "bf16_master_weights_and_grads": True - }), -]) +def test_bf16_stochastic_round_params_refuses_bf16_masters(): + config = { + "train_micro_batch_size_per_gpu": 1, + "bf16": { + "enabled": True, + "stochastic_round_params": True, + "bf16_master_weights_and_grads": True + }, + "zero_optimization": { + "stage": 2, + "offload_optimizer": { + "device": "cpu" + } + }, + } + with pytest.raises(ValueError, match="stochastic_round_params"): + DeepSpeedConfig(config) + + class TestBF16StochasticRoundParamsUnsupported(DistributedTest): world_size = 1 - def test_refused(self, zero_config, bf16_config): + def test_zero3_refused(self): if not bf16_required_version_check(): pytest.skip( " DeepSpeed BFloat16 tests need torch >= 1.10, NCCL >= 2.10.3, CUDA > =11.0 and HW support for BFloat16 to run correctly" ) config_dict = { + "zero_optimization": { + "stage": 3 + }, "train_micro_batch_size_per_gpu": 1, "bf16": { "enabled": True, - "stochastic_round_params": True, - **bf16_config + "stochastic_round_params": True }, - "zero_optimization": zero_config, } model = _ConstantGradientModel() optimizer = torch.optim.Adam(model.parameters(), lr=_SR_LR) - with pytest.raises(ValueError, match="stochastic_round_params"): - deepspeed.initialize(config=config_dict, model=model, optimizer=optimizer) + try: + engine, _, _, _ = deepspeed.initialize(config=config_dict, model=model, optimizer=optimizer) + except ValueError as error: + assert "stochastic_round_params" in str(error) + return + engine.destroy() + raise AssertionError("Unsupported stochastic rounding configuration was accepted") From 8aae0f946f641e7dc7be08d96954bc1df516417a Mon Sep 17 00:00:00 2001 From: Sean Bell <1844189+seanbell@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:24:51 +0000 Subject: [PATCH 4/4] bf16 stochastic rounding: keep tied pipeline weights equal; refuse tensor parallelism and low-precision masters Each pipeline stage rounds its own copy of a tied weight at a different offset of its rounding stream, so tied copies diverged after a step and after a universal-checkpoint warm start; broadcast the tied weights after rounding at both places, as initialization already does. Tensor-parallel ranks hold replicated weights at different partition offsets (and AutoTP replicates KV heads inside sharded QKV tensors), so independent draws make replicas differ; refuse tensor parallelism at initialization. Ulysses sequence parallelism, which aliases its sequence group as the model-parallel group, stays supported. The optimizer check moves ahead of optimizer construction, and fp16 masters are refused with bf16 masters at config load. The rounding helper rounds one chunk per call and keeps NaNs on the device cast (infinities have no low bits to carry). Tests enter through deepspeed.initialize: the master-to-bf16 refresh on controlled masters, a two-stage pipeline train_batch plus universal warm start, tensor-parallel refusal and Ulysses training. Co-Authored-By: Claude Opus 5.5 --- deepspeed/runtime/config.py | 4 + deepspeed/runtime/engine.py | 20 +- deepspeed/runtime/pipe/engine.py | 3 + deepspeed/runtime/precision_config.py | 9 +- deepspeed/runtime/stochastic_rounding.py | 41 ++-- docs/_pages/config-json.md | 2 +- tests/unit/v1/half_precision/test_bf16.py | 231 ++++++++++++++-------- 7 files changed, 182 insertions(+), 128 deletions(-) diff --git a/deepspeed/runtime/config.py b/deepspeed/runtime/config.py index b27a61c9c160..cc2d806b5623 100755 --- a/deepspeed/runtime/config.py +++ b/deepspeed/runtime/config.py @@ -699,6 +699,10 @@ def _do_error_check(self): if self.gradient_allreduce_op == GRADIENT_ALLREDUCE_OP_SUM and self.compile_config.deepcompile: raise ValueError(f"{GRADIENT_ALLREDUCE_OP}='sum' is not supported with DeepCompile") + if self.bfloat16_config.enabled and self.bfloat16_config.stochastic_round_params and ( + self.float16_config.fp16_master_weights_and_grads + or self.bfloat16_config.bf16_master_weights_and_grads): + raise ValueError("bf16.stochastic_round_params requires fp32 master weights") if self.float16_config.fp16_master_weights_and_grads: assert self.zero_enabled and self.zero_optimization_stage in ( ZeroStageEnum.optimizer_states, ZeroStageEnum.gradients, diff --git a/deepspeed/runtime/engine.py b/deepspeed/runtime/engine.py index fd8f904a6557..a4c6d0a3efdf 100644 --- a/deepspeed/runtime/engine.py +++ b/deepspeed/runtime/engine.py @@ -2458,6 +2458,18 @@ def _configure_optimizer(self, client_optimizer, model_parameters): optimizer_wrapper = self._do_optimizer_sanity_check(basic_optimizer) + if self.bf16_stochastic_round_params(): + from deepspeed.runtime.sequence_parallel import parallel_state_sp + from deepspeed.utils.bwc import bwc_tensor_model_parallel_world_size + + # Ulysses aliases its sequence group to the legacy model-parallel group. + if self.mpu is not parallel_state_sp and bwc_tensor_model_parallel_world_size(self.mpu) > 1: + raise ValueError("bf16.stochastic_round_params cannot preserve replicated tensor-parallel weights") + if optimizer_wrapper != BFLOAT16 and not (optimizer_wrapper == ZERO_OPTIMIZATION + and self.zero_optimization_stage() <= ZeroStageEnum.gradients + and not self.zenflow): + raise ValueError("bf16.stochastic_round_params supports BF16_Optimizer and ordinary ZeRO stages 1/2") + if optimizer_wrapper == ZERO_OPTIMIZATION: self.optimizer = self._configure_zero_optimizer(basic_optimizer) elif optimizer_wrapper in [FP16, DDP_BFLOAT16]: @@ -2468,12 +2480,6 @@ def _configure_optimizer(self, client_optimizer, model_parameters): else: self.optimizer = basic_optimizer - # Subclasses such as ZenFlow's override the step that applies the rounding, so match exact types. - if self.bf16_stochastic_round_params() and type( - self.optimizer) not in (BF16_Optimizer, DeepSpeedZeroOptimizer): - raise ValueError("bf16.stochastic_round_params supports BF16_Optimizer and ZeRO stage 1/2 " - f"(DeepSpeedZeroOptimizer); this engine uses {type(self.optimizer).__name__}") - self._configure_autoep_folding_optimizer_gradient_reduction() log_dist("DeepSpeed Final Optimizer = {}".format(self.optimizer.__class__.__name__), ranks=[0]) @@ -4621,6 +4627,8 @@ def load_checkpoint(self, if load_zero_checkpoint and universal and not zero3: self.optimizer.update_lp_params() + if self.pipeline_parallelism and self.bf16_stochastic_round_params(): + self.module._synchronize_tied_weights() if load_module_only: self.optimizer.refresh_fp32_params() diff --git a/deepspeed/runtime/pipe/engine.py b/deepspeed/runtime/pipe/engine.py index 5620d4be3710..7b49050415d0 100644 --- a/deepspeed/runtime/pipe/engine.py +++ b/deepspeed/runtime/pipe/engine.py @@ -1216,6 +1216,9 @@ def _exec_optimizer_step(self, lr_kwargs=None): self._force_grad_boundary = True self._take_model_step(lr_kwargs) + if self.module.tied_comms and self.bf16_stochastic_round_params(): + # The same tied weight can occupy different offsets in each stage's rounding stream. + self.module._synchronize_tied_weights() self._force_grad_boundary = False if self.global_rank == 0 and self.monitor.enabled: diff --git a/deepspeed/runtime/precision_config.py b/deepspeed/runtime/precision_config.py index ceef23701cc1..cdca8bd11a51 100644 --- a/deepspeed/runtime/precision_config.py +++ b/deepspeed/runtime/precision_config.py @@ -74,16 +74,9 @@ class DeepSpeedBF16Config(DeepSpeedConfigModel): """ Stochastically round fp32 master weights into the bf16 parameters after each optimizer step and universal-checkpoint load. The expected result equals the master within the finite bf16 range. Supported by ZeRO stages 1 and 2 and - BF16_Optimizer; requires fp32 master weights. + BF16_Optimizer with fp32 master weights and without tensor parallelism. """ - @model_validator(mode="after") - def _validate_stochastic_round_params(self): - if self.stochastic_round_params and self.bf16_master_weights_and_grads: - raise ValueError("bf16.stochastic_round_params rounds from fp32 master weights and cannot be combined " - "with bf16.bf16_master_weights_and_grads") - return self - ######################################### # FP16 support diff --git a/deepspeed/runtime/stochastic_rounding.py b/deepspeed/runtime/stochastic_rounding.py index 00934dd755a1..a5faf135b585 100644 --- a/deepspeed/runtime/stochastic_rounding.py +++ b/deepspeed/runtime/stochastic_rounding.py @@ -7,34 +7,8 @@ _CHUNK_NUMEL = 1 << 24 -def stochastic_round_to_bf16_(dst, src, generator): - """Copy fp32 ``src`` into bf16 ``dst``, rounding each element to one of its two bf16 neighbours at random. - - An element rounds away from zero with probability equal to its distance from the neighbour toward zero, as a - fraction of the spacing between the two, so ``E[dst] == src`` for values within the finite bf16 range. - Non-finite values round to nearest; finite values beyond the bf16 range can round to infinity. The rounding runs - on ``dst``'s device, where ``generator`` lives, so an offloaded master is copied there in fp32. - """ - src = src.view(-1) - dst = dst.view(-1) - for start in range(0, src.numel(), _CHUNK_NUMEL): - numel = min(_CHUNK_NUMEL, src.numel() - start) - chunk = src.narrow(0, start, numel).to(dst.device) - # Adding 16 random bits below bf16's last mantissa bit and truncating them rounds the magnitude up with the - # probability of the dropped fraction; fp32 is sign-magnitude, so this holds for either sign. - noise = torch.randint(0, 1 << 16, (numel, ), dtype=torch.int32, device=chunk.device, generator=generator) - truncated = noise.add_(chunk.view(torch.int32)).bitwise_and_(-(1 << 16)).view(torch.float32) - torch.where(torch.isfinite(chunk), truncated, chunk, out=truncated) - dst.narrow(0, start, numel).copy_(truncated) - - class StochasticRoundingCopy: - """``copy_(dst, src)`` replacement for the fp32-master to bf16-parameter copy (``bf16.stochastic_round_params``). - - Each device's generator is seeded from ``torch.initial_seed()`` and the data-parallel rank. On like devices, - replicas with the same seed, partition layout and copy order use the same draws. Generator state is not - checkpointed. Destinations that are not bf16 (parameters kept in fp32) are copied exactly. - """ + """Copy an optimizer partition, rounding fp32 masters to bf16 on the parameter device.""" def __init__(self, dp_rank): self.seed = (torch.initial_seed() + dp_rank) % (1 << 64) @@ -47,4 +21,15 @@ def __call__(self, dst, src): generator = self.generators.get(dst.device) if generator is None: generator = self.generators[dst.device] = torch.Generator(device=dst.device).manual_seed(self.seed) - stochastic_round_to_bf16_(dst, src, generator) + for start in range(0, src.numel(), _CHUNK_NUMEL): + _round_chunk(dst[start:start + _CHUNK_NUMEL], src[start:start + _CHUNK_NUMEL], generator) + + +def _round_chunk(dst, src, generator): + src = src.to(dst.device) + noise = torch.randint(1 << 16, src.shape, dtype=torch.int32, device=dst.device, generator=generator) + # Carry into the retained magnitude with probability equal to the discarded fraction, for either sign. + rounded = noise.add_(src.view(torch.int32)).bitwise_and_(-(1 << 16)).view(torch.float32) + # A NaN payload can carry into infinity or wrap into zero. Infinity already has zero low bits. + torch.where(src.isnan(), src, rounded, out=rounded) + dst.copy_(rounded) diff --git a/docs/_pages/config-json.md b/docs/_pages/config-json.md index 9d5fc64d86a3..9ab116807f0b 100644 --- a/docs/_pages/config-json.md +++ b/docs/_pages/config-json.md @@ -364,7 +364,7 @@ Example of **scheduler** | Description | Default | | ----------- | ------- | -| After each optimizer step and universal-checkpoint load, stochastically round the fp32 master weights into the bf16 parameters. Within the finite bf16 range, rounding chooses between adjacent bf16 values with probabilities that preserve the master value in expectation. This lets updates smaller than half a bf16 spacing reach the parameters used in forward passes and weights-only exports. Finite values outside that range can round to infinity. Supported by ZeRO stages 1 and 2 (including CPU optimizer offload) and by `BF16_Optimizer`; requires fp32 master weights (`bf16_master_weights_and_grads=false`). Each rank makes one random draw per bf16 element on the destination device before the existing all-gather. CPU offload transfers 4 bytes per bf16 parameter to the accelerator for rounding, versus 2 with the default copy. The torch seed and data-parallel rank seed the per-device generator. Replicas on like devices use the same draws when their seeds, partition layouts and copy order match. Parameters tied across pipeline stages sit at different offsets and can round differently. Generator state is not checkpointed. | `false` | +| Stochastically round fp32 masters into bf16 parameters after each optimizer step and universal-checkpoint refresh. For finite masters in the bf16 range, each fresh draw chooses adjacent bf16 values with the master as its expected value. Values outside this range can round to infinity. Supports ordinary ZeRO stages 1 and 2 (including CPU optimizer offload) and `BF16_Optimizer` with fp32 masters. Tensor parallelism is unsupported because replicas can occupy different partition offsets. Each data-parallel owner rounds its partition before the existing all-gather. Pipeline stages broadcast their tied weights after rounding. CPU offload transfers four bytes per bf16 parameter to the accelerator. The torch seed and data-parallel rank seed a dedicated generator. Restarting with the same seed replays its stream from the beginning. | `false` | **Support matrix (bf16 master weights/gradients)** diff --git a/tests/unit/v1/half_precision/test_bf16.py b/tests/unit/v1/half_precision/test_bf16.py index c51c7c17a629..241eed6719b9 100644 --- a/tests/unit/v1/half_precision/test_bf16.py +++ b/tests/unit/v1/half_precision/test_bf16.py @@ -15,9 +15,8 @@ from deepspeed.accelerator import get_accelerator from deepspeed.runtime.bf16_optimizer import BF16_Optimizer from deepspeed.runtime.config import DeepSpeedConfig -from deepspeed.runtime.stochastic_rounding import stochastic_round_to_bf16_ from deepspeed.runtime.zero.stage_1_and_2 import DeepSpeedZeroOptimizer -from deepspeed.utils import safe_get_full_fp32_param, safe_get_full_grad +from deepspeed.utils import safe_get_full_fp32_param, safe_get_full_grad, safe_set_full_fp32_param from unit.v1.zero.test_zero_user_backward import (initialize_distributed, create_ddp_model, collect_ddp_gradients, collect_gradients_safe, compare_gradients) @@ -704,36 +703,52 @@ def _bf16_neighbours(master): return low, high -def test_stochastic_round_to_bf16_kernel(): - tiny = 2.0**-133 # the smallest bf16 subnormal - values = torch.tensor([1 + 2.0**-9, -(1 + 3 * 2.0**-9), 0.3, 2 - 2.0**-9, 2.5 * tiny, -1.25 * tiny]) - draws = 1 << 16 - src = values.repeat_interleave(draws) - dst = torch.empty_like(src, dtype=torch.bfloat16) - stochastic_round_to_bf16_(dst, src, torch.Generator().manual_seed(0)) - # Unbiased for either sign and for subnormals: each value rounds to its upper neighbour with probability equal - # to its position between the two. - low, high = _bf16_neighbours(values) - fraction = (values.double() - low) / (high - low) - rounded = dst.double().view(len(values), draws) - assert ((rounded == low[:, None]) | (rounded == high[:, None])).all() - rounded_up = (rounded == high[:, None]).double().mean(dim=1) - assert ((rounded_up - fraction).abs() < 5 * (fraction * (1 - fraction) / draws).sqrt()).all(), rounded_up - - # The same seed repeats the draw; another seed does not. - again = torch.empty_like(dst) - stochastic_round_to_bf16_(again, src, torch.Generator().manual_seed(0)) - assert torch.equal(again, dst) - stochastic_round_to_bf16_(again, src, torch.Generator().manual_seed(1)) - assert not torch.equal(again, dst) - - # bf16 values are kept exactly. Non-finite values round to nearest, including NaNs whose low bits would carry. - exact = torch.tensor([0.0, -0.0, 1.0, -0.5, tiny, -tiny, torch.finfo(torch.bfloat16).max]) - non_finite = torch.tensor([0x7F800000, -0x00800000, 0x7FFFFFFF, -1], dtype=torch.int32).view(torch.float32) - src = torch.cat([exact, non_finite]).repeat(1000) - out = torch.empty_like(src, dtype=torch.bfloat16) - stochastic_round_to_bf16_(out, src, torch.Generator().manual_seed(2)) - assert torch.equal(out.view(torch.int16), src.to(torch.bfloat16).view(torch.int16)) +def _rounding_config(stage): + return dict(train_micro_batch_size_per_gpu=1, + bf16=dict(enabled=True, stochastic_round_params=True), + zero_optimization=dict(stage=stage)) + + +class TestBF16StochasticRoundRefresh(DistributedTest): + world_size = 1 + + def test_master_neighbours(self): + if not bf16_required_version_check(): + pytest.skip("bf16 is required") + tiny = 2.0**-133 + values = torch.tensor([1 + 2.0**-9, -(1 + 3 * 2.0**-9), 0.3, 2 - 2.0**-9, 2.5 * tiny, -1.25 * tiny]) + exact = torch.tensor([0.0, -0.0, 1.0, -0.5, tiny, -tiny, torch.finfo(torch.bfloat16).max]) + specials = torch.tensor([0x7F800000, -0x00800000, 0x7FFFFFFF, -1], dtype=torch.int32).view(torch.float32) + draws = 1 << 16 + fixed = torch.cat([exact, specials]).repeat(64) + master = torch.cat([values.repeat_interleave(draws), fixed]) + + def round_with_seed(seed): + torch.manual_seed(seed) + model = torch.nn.Linear(master.numel(), 1, bias=False) + config = _rounding_config(1) + config["data_types"] = dict(grad_accum_dtype="fp32") + engine, _, _, _ = deepspeed.initialize(model=model, + optimizer=torch.optim.Adam(model.parameters()), + config=config) + weight = engine.module.weight + safe_set_full_fp32_param(weight, master.to(weight.device).view_as(weight)) + engine.optimizer.update_lp_params() + result = weight.detach().flatten().cpu().clone() + engine.destroy() + return result + + rounded = round_with_seed(0) + assert torch.equal(rounded.view(torch.int16), round_with_seed(0).view(torch.int16)) + assert not torch.equal(rounded[:draws], round_with_seed(1)[:draws]) + low, high = _bf16_neighbours(values) + fraction = (values.double() - low) / (high - low) + samples = rounded[:values.numel() * draws].double().view(-1, draws) + assert ((samples == low[:, None]) | (samples == high[:, None])).all() + rounded_up = (samples == high[:, None]).double().mean(dim=1) + assert ((rounded_up - fraction).abs() < 5 * (fraction * (1 - fraction) / draws).sqrt()).all() + nearest = fixed.to(get_accelerator().current_device_name()).to(torch.bfloat16).cpu() + assert torch.equal(rounded[-fixed.numel():].view(torch.int16), nearest.view(torch.int16)) @pytest.mark.parametrize("stochastic", [False, True]) @@ -747,25 +762,15 @@ class TestBF16StochasticRoundParams(DistributedTest): def test_bf16_params_track_fp32_masters(self, stochastic, zero_stage, offload, grad_accum_dtype, optimizer_type): if not bf16_required_version_check(): - pytest.skip( - " DeepSpeed BFloat16 tests need torch >= 1.10, NCCL >= 2.10.3, CUDA > =11.0 and HW support for BFloat16 to run correctly" - ) - zero_config = {"stage": zero_stage} + pytest.skip("bf16 is required") + torch.manual_seed(0) + config_dict = _rounding_config(zero_stage) + config_dict["data_types"] = dict(grad_accum_dtype=grad_accum_dtype) if offload: - zero_config["offload_optimizer"] = {"device": "cpu"} - config_dict = { - "train_micro_batch_size_per_gpu": 1, - "bf16": { - "enabled": True - }, - "data_types": { - "grad_accum_dtype": grad_accum_dtype - }, - "zero_optimization": zero_config, - "zero_force_ds_cpu_optimizer": False, - } - if stochastic: - config_dict["bf16"]["stochastic_round_params"] = True + config_dict["zero_optimization"]["offload_optimizer"] = dict(device="cpu") + config_dict["zero_force_ds_cpu_optimizer"] = False + if not stochastic: + del config_dict["bf16"]["stochastic_round_params"] model = _ConstantGradientModel() optimizer = torch.optim.Adam(model.parameters(), lr=_SR_LR) engine, _, _, _ = deepspeed.initialize(config=config_dict, model=model, optimizer=optimizer) @@ -806,22 +811,12 @@ def test_bf16_params_track_fp32_masters(self, stochastic, zero_stage, offload, g engine.destroy() -def test_bf16_stochastic_round_params_refuses_bf16_masters(): - config = { - "train_micro_batch_size_per_gpu": 1, - "bf16": { - "enabled": True, - "stochastic_round_params": True, - "bf16_master_weights_and_grads": True - }, - "zero_optimization": { - "stage": 2, - "offload_optimizer": { - "device": "cpu" - } - }, - } - with pytest.raises(ValueError, match="stochastic_round_params"): +@pytest.mark.parametrize("precision", ["fp16", "bf16"]) +def test_stochastic_round_requires_fp32_masters(precision): + config = _rounding_config(2) + config["zero_optimization"]["offload_optimizer"] = dict(device="cpu") + config.setdefault(precision, {})[f"{precision}_master_weights_and_grads"] = True + with pytest.raises(ValueError, match="requires fp32 master weights"): DeepSpeedConfig(config) @@ -830,25 +825,91 @@ class TestBF16StochasticRoundParamsUnsupported(DistributedTest): def test_zero3_refused(self): if not bf16_required_version_check(): - pytest.skip( - " DeepSpeed BFloat16 tests need torch >= 1.10, NCCL >= 2.10.3, CUDA > =11.0 and HW support for BFloat16 to run correctly" - ) - config_dict = { - "zero_optimization": { - "stage": 3 - }, - "train_micro_batch_size_per_gpu": 1, - "bf16": { - "enabled": True, - "stochastic_round_params": True - }, - } + pytest.skip("bf16 is required") + model = _ConstantGradientModel() + with pytest.raises(ValueError, match="supports BF16_Optimizer"): + engine, _, _, _ = deepspeed.initialize(config=_rounding_config(3), + model=model, + optimizer=torch.optim.Adam(model.parameters())) + engine.destroy() + raise AssertionError("ZeRO-3 accepted stochastic rounding") + + +class TestStochasticRoundParallelism(DistributedTest): + world_size = 2 + + @pytest.mark.parametrize("tensor_parallel", [False, True]) + def test_replicated_weights(self, tensor_parallel): + from deepspeed.runtime.pipe.topology import PipelineParallelGrid, PipeModelDataParallelTopology + from deepspeed.runtime.sequence_parallel import parallel_state_sp + + if not bf16_required_version_check(): + pytest.skip("bf16 is required") + initialize_distributed() + config = _rounding_config(2) model = _ConstantGradientModel() optimizer = torch.optim.Adam(model.parameters(), lr=_SR_LR) - try: - engine, _, _, _ = deepspeed.initialize(config=config_dict, model=model, optimizer=optimizer) - except ValueError as error: - assert "stochastic_round_params" in str(error) - return + if tensor_parallel: + mpu = PipelineParallelGrid(PipeModelDataParallelTopology(num_pp=1, num_mp=2, num_dp=1)) + with pytest.raises(ValueError, match="replicated tensor-parallel weights"): + engine, _, _, _ = deepspeed.initialize(model=model, optimizer=optimizer, config=config, mpu=mpu) + engine.destroy() + raise AssertionError("TP accepted independent rounding of replicas") + else: + parallel_state_sp.initialize_sequence_parallel(2) + config["sequence_parallel_size"] = 2 + engine, _, _, _ = deepspeed.initialize(model=model, + optimizer=optimizer, + config=config, + mpu=parallel_state_sp) + before = model.weight.detach().clone() + engine.backward(engine()) + engine.step() + assert (model.weight != before).any() + engine.destroy() + + +class TestPipelineTiedStochasticRound(DistributedTest): + world_size = 2 + + def test_step_and_universal_warm_start_keep_copies_equal(self, tmpdir): + from deepspeed.checkpoint.constants import PIPELINE_REPLICATED_PARAMETER_PATTERNS, UNIVERSAL_CHECKPOINT_INFO + from unit.checkpoint.test_autotp_uc_checkpoint import _convert_to_universal + from deepspeed.pipe import PipelineModule, TiedLayerSpec + + if not bf16_required_version_check(): + pytest.skip("bf16 is required") + initialize_distributed() + torch.manual_seed(42) + tied = TiedLayerSpec("shared", torch.nn.Linear, 32, 32, bias=False) + layers = [tied, torch.nn.Identity(), torch.nn.Linear(32, 32, bias=False), tied] + model = PipelineModule(layers, num_stages=2, partition_method="uniform", loss_fn=lambda x, y: x.float().mean()) + for param in model.parameters(): + param.data.fill_(1.0) + # The second stage's extra matrix precedes the tied weight in its optimizer partition. + optimizer = torch.optim.Adam(reversed(list(model.parameters())), lr=0.001) + config = _rounding_config(1) + config["checkpoint"] = dict(load_universal=True) + config["data_types"] = dict(grad_accum_dtype="fp32") + engine, _, _, _ = deepspeed.initialize(model=model, optimizer=optimizer, config=config) + batch = (torch.ones(1, 32, dtype=torch.bfloat16), torch.zeros(1)) + engine.train_batch(data_iter=iter([batch])) + weight = model.tied_modules["shared"].weight + + def check_tied(): + copies = [torch.empty_like(weight) for _ in range(2)] + dist.all_gather(copies, weight.detach()) + assert weight.ne(1).any() + assert torch.equal(*copies) + + check_tied() + info = {PIPELINE_REPLICATED_PARAMETER_PATTERNS: [r"^tied_modules\.shared\.weight$"]} + engine.save_checkpoint(str(tmpdir), tag="native", client_state={UNIVERSAL_CHECKPOINT_INFO: info}) + if dist.get_rank() == 0: + _convert_to_universal(str(tmpdir / "native"), str(tmpdir / "universal")) + dist.barrier() + path, _ = engine.load_checkpoint(str(tmpdir), tag="universal", load_module_only=True) + assert path + check_tied() + assert torch.equal(safe_get_full_fp32_param(weight), weight.float()) engine.destroy() - raise AssertionError("Unsupported stochastic rounding configuration was accepted")