From c2b85b64bcac92539ecc96b7b1b98e6452987a10 Mon Sep 17 00:00:00 2001 From: pengdurice Date: Thu, 15 Oct 2026 19:31:05 +0000 Subject: [PATCH 1/2] ZeRO-3: copy offloaded master weights back to the device through pinned buffers Signed-off-by: pengdurice --- deepspeed/runtime/zero/stage3.py | 51 ++++++++++++++++++++++++- tests/unit/v1/zero/test_zero.py | 64 ++++++++++++++++++++++++++++++++ 2 files changed, 113 insertions(+), 2 deletions(-) diff --git a/deepspeed/runtime/zero/stage3.py b/deepspeed/runtime/zero/stage3.py index 215eee472980..e4410d6172df 100644 --- a/deepspeed/runtime/zero/stage3.py +++ b/deepspeed/runtime/zero/stage3.py @@ -251,6 +251,11 @@ def __init__( self.offload_optimizer = False self.offload_optimizer_pin_memory = False + # Pinned buffers for copying CPU master partitions back to the device (_copy_through_pinned_staging). The + # element count is a power of two, so the pinned allocator does not round the buffers up. + self._staging_numel = 2**26 + self._staging_buffers = None + self._staging_events = None self.offload_optimizer_fast_init = False self.offload_param = False self.offload_param_pin_memory = False @@ -562,6 +567,8 @@ def _unpin_offload_buffers(self): accelerator.unpin_memory(buffer) for buffer in getattr(self, 'hp_params_pin_buffers', []): accelerator.unpin_memory(buffer) + for buffer in getattr(self, '_staging_buffers', None) or []: + accelerator.unpin_memory(buffer) unpin_offloaded_optimizer_states(self.optimizer) if self.offload_optimizer_pin_memory: for fp32_partition in self.fp32_partitioned_groups_flat: @@ -2849,13 +2856,53 @@ def _post_step(self, timer_names): see_memory_usage('After zero_optimizer step', force=False) print_rank_0("------------------Finishing Step-----------------------") + @instrument_w_nvtx + def _copy_through_pinned_staging(self, dst, src): + """Copy the pageable CPU master partition ``src`` into the device partition ``dst`` through two small pinned + buffers: each piece is cast on the CPU into one buffer while the previous piece is copied from the other. + + Copies from pageable memory run at a few GB/s. Pinning the master partitions themselves, as ZeRO-1/2 does, + would also need a pinned low-precision buffer of each partition's size, so pinned host memory would grow with + the model; these two buffers have a fixed size.""" + numel = src.numel() + chunk = self._staging_numel + if self._staging_buffers is None or self._staging_buffers[0].dtype != dst.dtype: + self._staging_buffers = [get_accelerator().pin_empty(chunk, dtype=dst.dtype) for _ in range(2)] + self._staging_events = [None, None] + src = src.view(-1) + dst = dst.view(-1) + last_event = None + for index, start in enumerate(range(0, numel, chunk)): + buf = index % 2 + if self._staging_events[buf] is not None: + # The previous copy out of this buffer must finish before the buffer is refilled. + self._staging_events[buf].synchronize() + count = min(chunk, numel - start) + staging = self._staging_buffers[buf][:count] + staging.copy_(src[start:start + count]) + dst[start:start + count].copy_(staging, non_blocking=True) + event = get_accelerator().Event() + event.record() + self._staging_events[buf] = event + last_event = event + # Callers expect the partition on the device when this returns: the parameter all-gathers of the next forward + # run on a stream that does not wait for this one. + if last_event is not None: + last_event.synchronize() + @instrument_w_nvtx def _reassign_or_swap_out_partitioned_parameters(self, sub_group_id): if self.fp16_partitioned_groups_flat[sub_group_id] is not None: # When torch autocast is enabled, groups in fp16_partitioned_groups are in fp32 already and those in # fp32_partitioned_groups are aliases. Calling tensor.data.copy_ will not trigger any copy in that case. - self.fp16_partitioned_groups_flat[sub_group_id].data.copy_( - self.fp32_partitioned_groups_flat[sub_group_id].data) + dst = self.fp16_partitioned_groups_flat[sub_group_id].data + src = self.fp32_partitioned_groups_flat[sub_group_id].data + accelerator = get_accelerator() + src_is_pageable = src.device.type == "cpu" and not accelerator.is_pinned(src) + if self.offload_optimizer_pin_memory and src_is_pageable and dst.device.type != "cpu": + self._copy_through_pinned_staging(dst, src) + else: + dst.copy_(src) #unflatten fp16 parameter subgroup self._unflatten_partitioned_parameters(sub_group_id) diff --git a/tests/unit/v1/zero/test_zero.py b/tests/unit/v1/zero/test_zero.py index 0475dc0b2250..2de08f06ca1a 100644 --- a/tests/unit/v1/zero/test_zero.py +++ b/tests/unit/v1/zero/test_zero.py @@ -1919,6 +1919,70 @@ def test(self, force_ds_optim): model, _, _, _ = deepspeed.initialize(model=model, optimizer=optimizer, config=config_dict) +@pytest.mark.skipif(not get_accelerator().is_bf16_supported(), reason="bf16 is not supported on this accelerator") +@pytest.mark.parametrize("ratio", [1.0, 0.5]) +class TestZero3OffloadPinnedCopyBack(DistributedTest): + """With pin_memory, the updated CPU master partitions must reach the device with the same values as the direct + copy from pageable memory (pin_memory False): the parameters after training are compared bitwise. The pinned run + must actually go through the staging buffers, or the test would compare the direct copy with itself.""" + world_size = 2 + + def _train(self, pin_memory, ratio): + hidden_dim = 256 + config_dict = { + "train_micro_batch_size_per_gpu": 2, + "optimizer": { + "type": "Adam", + "params": { + "lr": 1e-3 + } + }, + "bf16": { + "enabled": True + }, + "zero_optimization": { + "stage": 3, + "sub_group_size": 20000, + "offload_optimizer": { + "device": "cpu", + "pin_memory": pin_memory, + "ratio": ratio + } + }, + } + torch.manual_seed(0) + model = SimpleModel(hidden_dim, nlayers=4) + model, _, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config_dict) + # Pieces much smaller than a sub-group, so the copy refills both staging buffers many times per step: a buffer + # refilled before its previous copy finished would change the values. + model.optimizer._staging_numel = 1000 + torch.manual_seed(1) + data_loader = random_dataloader(model=model, + total_samples=6, + hidden_dim=hidden_dim, + device=model.device, + dtype=torch.bfloat16) + for batch in data_loader: + loss = model(batch[0], batch[1]) + model.backward(loss) + model.step() + params = [] + for p in model.module.parameters(): + with deepspeed.zero.GatheredParameters([p]): + params.append(p.detach().clone().cpu()) + used_staging = model.optimizer._staging_buffers is not None + return params, used_staging + + def test(self, ratio): + direct, direct_used_staging = self._train(pin_memory=False, ratio=ratio) + staged, staged_used_staging = self._train(pin_memory=True, ratio=ratio) + assert not direct_used_staging + assert staged_used_staging + assert len(direct) == len(staged) + for a, b in zip(direct, staged): + assert torch.equal(a, b) + + @pytest.mark.parametrize("training", [True, False]) class TestZeroPartitionCache(DistributedTest): world_size = 1 From 5f663c08e5ad46d0088e379c55a8b900633e6360 Mon Sep 17 00:00:00 2001 From: pengdurice Date: Thu, 15 Oct 2026 19:31:12 +0000 Subject: [PATCH 2/2] ZeRO-3 CPU offload: apply the clip factor and write the bf16 copy inside the CPU Adam pass Signed-off-by: pengdurice --- csrc/adam/cpu_adam.cpp | 14 ++++ csrc/adam/cpu_adam_impl.cpp | 117 ++++++++++++++++++++++++++ csrc/includes/cpu_adam.h | 73 ++++++++++++++++- csrc/includes/sve.h | 5 +- deepspeed/ops/adam/cpu_adam.py | 70 +++++++++++++++- deepspeed/runtime/zero/stage3.py | 105 ++++++++++++++++++++++-- tests/unit/ops/adam/test_cpu_adam.py | 78 ++++++++++++++++++ tests/unit/v1/zero/test_zero.py | 118 +++++++++++++++++++++++++++ 8 files changed, 565 insertions(+), 15 deletions(-) diff --git a/csrc/adam/cpu_adam.cpp b/csrc/adam/cpu_adam.cpp index 72b7b2a97473..27a5f77b0d93 100644 --- a/csrc/adam/cpu_adam.cpp +++ b/csrc/adam/cpu_adam.cpp @@ -9,6 +9,20 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { using namespace pybind11::literals; m.def("adam_update", &ds_adam_step, "DeepSpeed CPU Adam update (C++)"); + m.def("adam_update_scaled", + &ds_adam_step_scaled, + "DeepSpeed CPU Adam update with every gradient multiplied by grad_scale first (C++)"); + m.def("adam_update_scaled_copy", + &ds_adam_step_scaled_copy, + "adam_update_scaled that also writes the updated parameters in bfloat16 to params_copy " + "(C++)"); + m.def("adam_block_numel", + &ds_adam_block_numel, + "pieces starting at multiples of this element count are updated exactly as one call on " + "the whole tensor"); + m.def("adam_copy_supported", + &ds_adam_copy_supported, + "whether adam_update_scaled_copy is available in this build (C++)"); m.def("adam_rollback", &ds_adam_rollback, "DeepSpeed CPU Adam rollback (C++)"); m.def("create_adam", &create_adam_optimizer, "DeepSpeed CPU Adam (C++)"); m.def("destroy_adam", &destroy_adam_optimizer, "DeepSpeed CPU Adam destroy (C++)"); diff --git a/csrc/adam/cpu_adam_impl.cpp b/csrc/adam/cpu_adam_impl.cpp index 6c81f301ef5e..dba587947bf7 100644 --- a/csrc/adam/cpu_adam_impl.cpp +++ b/csrc/adam/cpu_adam_impl.cpp @@ -52,6 +52,7 @@ void Adam_Optimizer::Step_1(ds_params_precision_t* _params, float step_size = -1 * _alpha / _bias_correction1; float w_decay = -1 * _alpha * _weight_decay; + c10::BFloat16* params_copy = params_copy_for(_params); for (size_t t = rounded_size; t < _param_size; t += TILE) { size_t copy_size = TILE; @@ -60,6 +61,7 @@ void Adam_Optimizer::Step_1(ds_params_precision_t* _params, #pragma omp parallel for if (parallel) for (size_t k = t; k < offset; k++) { float grad = (float)grads[k]; + if (_grad_scale != 1.0f) { grad = grad * _grad_scale; } float param = (float)_params[k]; float momentum = _exp_avg[k]; float variance = _exp_avg_sq[k]; @@ -77,6 +79,7 @@ void Adam_Optimizer::Step_1(ds_params_precision_t* _params, if (_weight_decay > 0 && _adamw_mode) { param += w_decay * param; } param = grad * step_size + param; _params[k] = param; + if (params_copy != nullptr) { params_copy[k] = c10::BFloat16(param); } _exp_avg[k] = momentum; _exp_avg_sq[k] = variance; } @@ -268,6 +271,120 @@ int ds_adam_step(int optimizer_id, return 0; } +bool ds_adam_copy_supported() +{ + // The vectorized loop needs a bfloat16 store (AVX512 or NEON); the SVE kernel does not write + // the copy. +#if defined(__AVX512__) or defined(__NEON__) + return true; +#elif defined(__AVX256__) + return false; +#elif defined(__SVE__) && defined(__ARM_FEATURE_SVE) + return false; +#else + return true; +#endif +} + +size_t ds_adam_block_numel() +{ + // Step_8 updates the first ROUND_DOWN(n, SIMD_WIDTH * 8) elements with the widest vector loop + // and the rest with narrower loops and finally scalar code, whose float rounding can differ + // (fused multiply-add or not). A call on a piece that starts at a multiple of this count sends + // every element through the same code as one call on the whole tensor. +#if defined(__AVX512__) or defined(__AVX256__) or defined(__NEON__) + return SIMD_WIDTH * 8; +#else + return 1; +#endif +} + +int ds_adam_step_scaled_copy(int optimizer_id, + size_t step, + float lr, + float beta1, + float beta2, + float epsilon, + float weight_decay, + bool bias_correction, + torch::Tensor& params, + torch::Tensor& grads, + torch::Tensor& exp_avg, + torch::Tensor& exp_avg_sq, + float grad_scale, + torch::Tensor& params_copy) +{ + TORCH_CHECK(ds_adam_copy_supported(), + "adam_update_scaled_copy needs AVX512, NEON or the scalar kernel"); + TORCH_CHECK(params.scalar_type() == torch::kFloat32 && params.is_contiguous(), + "adam_update_scaled_copy: params must be contiguous float32"); + TORCH_CHECK( + params_copy.scalar_type() == torch::kBFloat16 && params_copy.is_contiguous() && + params_copy.numel() == params.numel(), + "adam_update_scaled_copy: params_copy must be contiguous bfloat16 with params' numel"); + std::shared_ptr opt = + std::static_pointer_cast(s_optimizers[optimizer_id]); + opt->set_params_copy(params.data_ptr(), params_copy.data_ptr()); + try { + ds_adam_step_scaled(optimizer_id, + step, + lr, + beta1, + beta2, + epsilon, + weight_decay, + bias_correction, + params, + grads, + exp_avg, + exp_avg_sq, + grad_scale); + } catch (...) { + opt->set_params_copy(nullptr, nullptr); + throw; + } + opt->set_params_copy(nullptr, nullptr); + return 0; +} + +int ds_adam_step_scaled(int optimizer_id, + size_t step, + float lr, + float beta1, + float beta2, + float epsilon, + float weight_decay, + bool bias_correction, + torch::Tensor& params, + torch::Tensor& grads, + torch::Tensor& exp_avg, + torch::Tensor& exp_avg_sq, + float grad_scale) +{ + std::shared_ptr opt = + std::static_pointer_cast(s_optimizers[optimizer_id]); + opt->set_grad_scale(grad_scale); + try { + ds_adam_step(optimizer_id, + step, + lr, + beta1, + beta2, + epsilon, + weight_decay, + bias_correction, + params, + grads, + exp_avg, + exp_avg_sq); + } catch (...) { + opt->set_grad_scale(1.0f); + throw; + } + opt->set_grad_scale(1.0f); + return 0; +} + void adamw_rollback_inplace(float* params, const float* grads, float* momentum, diff --git a/csrc/includes/cpu_adam.h b/csrc/includes/cpu_adam.h index a2e884ead2ea..b66c3811e936 100644 --- a/csrc/includes/cpu_adam.h +++ b/csrc/includes/cpu_adam.h @@ -91,6 +91,31 @@ class Adam_Optimizer { } } } + // Multiplies every gradient as it is loaded, before weight decay and the moment updates: the + // same float multiply as scaling the gradients in place first, without a separate pass over + // them. + inline void set_grad_scale(float grad_scale) { _grad_scale = grad_scale; } + + // While set, the updated float32 parameters are also written in bfloat16 to params_copy: + // element j of the parameter tensor that starts at param_base goes to params_copy[j]. Rounds to + // nearest even, as torch's cast. + inline void set_params_copy(const float* param_base, c10::BFloat16* params_copy) + { + _copy_param_base = param_base; + _params_copy = params_copy; + } + + // Where the bfloat16 copy of _params[0] goes, or nullptr. _params may point past param_base + // (the remainder after the vectorized blocks is updated by a second call on offset pointers). + template + inline c10::BFloat16* params_copy_for(const ds_params_precision_t* _params) const + { + if constexpr (std::is_same_v) { + if (_params_copy != nullptr) { return _params_copy + (_params - _copy_param_base); } + } + return nullptr; + } + inline void update_state(float lr, float epsilon, float weight_decay, bool bias_correction) { _alpha = lr; @@ -116,6 +141,10 @@ class Adam_Optimizer { float _betta2_t; size_t _step; + float _grad_scale = 1.0f; + const float* _copy_param_base = nullptr; + c10::BFloat16* _params_copy = nullptr; + float _bias_correction1; float _bias_correction2; @@ -158,6 +187,12 @@ void Adam_Optimizer::Step_AVX(size_t* rounded_size, AVX_Data eps_4; eps_4.data = SIMD_SET(_eps); + const bool scale_grads = _grad_scale != 1.0f; + AVX_Data grad_scale_4; + grad_scale_4.data = SIMD_SET(_grad_scale); + + c10::BFloat16* params_copy = params_copy_for(_params); + float step_size = -1 * _alpha / _bias_correction1; AVX_Data step_size_4; step_size_4.data = SIMD_SET(step_size); @@ -175,6 +210,7 @@ void Adam_Optimizer::Step_AVX(size_t* rounded_size, for (size_t i = t; i < offset; i += SIMD_WIDTH * span) { AVX_Data grad_4[span]; simd_load(grad_4, grads + i); + if (scale_grads) { simd_mul(grad_4, grad_4, grad_scale_4); } AVX_Data momentum_4[span]; simd_load(momentum_4, _exp_avg + i); @@ -205,6 +241,7 @@ void Adam_Optimizer::Step_AVX(size_t* rounded_size, simd_fma(param_4, grad_4, step_size_4, param_4); simd_store(_params + i, param_4); + if (params_copy != nullptr) { simd_store(params_copy + i, param_4); } simd_store(_exp_avg + i, momentum_4); simd_store(_exp_avg_sq + i, variance_4); } @@ -238,7 +275,8 @@ void Adam_Optimizer::Step_SVE(size_t* rounded_size, _alpha, _weight_decay, _adamw_mode, - parallel); + parallel, + _grad_scale); *rounded_size = _param_size; } } @@ -266,6 +304,39 @@ int ds_adam_step(int optimizer_id, torch::Tensor& exp_avg, torch::Tensor& exp_avg_sq); +int ds_adam_step_scaled(int optimizer_id, + size_t step, + float lr, + float beta1, + float beta2, + float epsilon, + float weight_decay, + bool bias_correction, + torch::Tensor& params, + torch::Tensor& grads, + torch::Tensor& exp_avg, + torch::Tensor& exp_avg_sq, + float grad_scale); + +int ds_adam_step_scaled_copy(int optimizer_id, + size_t step, + float lr, + float beta1, + float beta2, + float epsilon, + float weight_decay, + bool bias_correction, + torch::Tensor& params, + torch::Tensor& grads, + torch::Tensor& exp_avg, + torch::Tensor& exp_avg_sq, + float grad_scale, + torch::Tensor& params_copy); + +bool ds_adam_copy_supported(); + +size_t ds_adam_block_numel(); + int ds_adam_rollback(int optimizer_id, size_t step, float lr, diff --git a/csrc/includes/sve.h b/csrc/includes/sve.h index 87ceb1e07d9f..8c01ed58bfe7 100644 --- a/csrc/includes/sve.h +++ b/csrc/includes/sve.h @@ -23,7 +23,8 @@ inline void sve_adam_update(float* params, float learning_rate, float weight_decay, bool adamw_mode, - bool parallel) + bool parallel, + float grad_scale = 1.0f) { constexpr size_t tile_size = 128ULL * 1024 * 1024; const size_t vector_width = svcntw(); @@ -45,6 +46,7 @@ inline void sve_adam_update(float* params, const svfloat32_t epsilon_vec = svdup_n_f32(epsilon); const svfloat32_t step_size_vec = svdup_n_f32(-learning_rate / bias_correction1); const svfloat32_t weight_decay_vec = svdup_n_f32(decay); + const svfloat32_t grad_scale_vec = svdup_n_f32(grad_scale); #pragma omp for for (size_t i = tile_start; i < tile_end; i += block_width) { @@ -56,6 +58,7 @@ inline void sve_adam_update(float* params, const svbool_t predicate = svwhilelt_b32(offset, tile_end); svfloat32_t param = svldnt1_f32(predicate, params + offset); svfloat32_t grad = svldnt1_f32(predicate, grads + offset); + if (grad_scale != 1.0f) { grad = svmul_f32_x(predicate, grad, grad_scale_vec); } svfloat32_t momentum = svldnt1_f32(predicate, exp_avg + offset); svfloat32_t variance = svldnt1_f32(predicate, exp_avg_sq + offset); diff --git a/deepspeed/ops/adam/cpu_adam.py b/deepspeed/ops/adam/cpu_adam.py index 33d9287f0cbd..aaf714b22b9a 100644 --- a/deepspeed/ops/adam/cpu_adam.py +++ b/deepspeed/ops/adam/cpu_adam.py @@ -110,7 +110,7 @@ def __setstate__(self, state): group.setdefault('amsgrad', False) @torch.no_grad() - def step(self, closure=None): + def step(self, closure=None, grad_scale=1.0): """Update the model parameters. .. note:: @@ -122,6 +122,10 @@ def step(self, closure=None): Args: closure (callable, optional): closure to compute the loss. Defaults to ``None``. + grad_scale (float, optional): every gradient is multiplied by this + factor as the kernel loads it, the same float multiply as + ``grad.mul_(grad_scale)`` before the step but without a separate + pass over the gradients (which are left unchanged). Defaults to 1. Returns: loss: if ``closure`` is provided. Otherwise ``None``. @@ -163,11 +167,69 @@ def step(self, closure=None): state['step'] += 1 beta1, beta2 = group['betas'] - self.ds_opt_adam.adam_update(self.opt_id, state['step'], group['lr'], beta1, beta2, group['eps'], - group['weight_decay'], group['bias_correction'], p.data, p.grad.data, - state['exp_avg'], state['exp_avg_sq']) + if grad_scale != 1.0: + self.ds_opt_adam.adam_update_scaled(self.opt_id, state['step'], group['lr'], beta1, beta2, + group['eps'], group['weight_decay'], group['bias_correction'], + p.data, p.grad.data, state['exp_avg'], state['exp_avg_sq'], + grad_scale) + else: + self.ds_opt_adam.adam_update(self.opt_id, state['step'], group['lr'], beta1, beta2, group['eps'], + group['weight_decay'], group['bias_correction'], p.data, p.grad.data, + state['exp_avg'], state['exp_avg_sq']) return loss + def copy_supported(self): + """Whether step_pieces can write a bfloat16 copy of the updated parameters (needs AVX512, NEON or the + scalar kernel).""" + return bool(self.ds_opt_adam.adam_copy_supported()) + + def aligned_piece_numel(self, piece_numel): + """The piece size step_pieces uses for ``piece_numel``: rounded down to a multiple of the kernel's widest + vector block (at least one block), so every element goes through the same code, with the same rounding, as in + one step() call on the whole parameter.""" + block = int(self.ds_opt_adam.adam_block_numel()) + return max(block, piece_numel - piece_numel % block) + + @torch.no_grad() + def step_pieces(self, piece_numel, before_piece, after_piece, grad_scale=1.0): + """step(grad_scale=...) for float32 parameters, done in pieces of ``piece_numel`` elements, with a bfloat16 + copy of each updated piece written by the same kernel pass. + + Pieces are ``aligned_piece_numel(piece_numel)`` elements (the last one may be shorter). + For each piece of each parameter: ``out = before_piece(param, start, count)`` returns a contiguous bfloat16 + CPU tensor of ``count`` elements; the kernel updates the piece and writes it, rounded to nearest even (as + ``out.copy_(param[start:start + count])`` would), into ``out``; then ``after_piece(param, start, count, out)``. + The parameters and moments are bitwise equal to step(grad_scale=...). + """ + assert self.copy_supported(), "step_pieces needs AVX512, NEON or the scalar CPU Adam kernel" + piece_numel = self.aligned_piece_numel(piece_numel) + device = torch.device('cpu') + for group in self.param_groups: + for p in group['params']: + if p.grad is None: + continue + assert p.device == device and p.dtype == torch.float32, \ + f"step_pieces needs float32 CPU parameters, got {p.dtype} on {p.device}" + state = self.state[p] + if len(state) == 0: + state['step'] = 0 + state_dtype = torch.float if self.fp32_optimizer_states else p.dtype + state['exp_avg'] = torch.zeros_like(p.data, dtype=state_dtype, device=device) + state['exp_avg_sq'] = torch.zeros_like(p.data, dtype=state_dtype, device=device) + state['step'] += 1 + beta1, beta2 = group['betas'] + param, grad = p.data.view(-1), p.grad.data.view(-1) + exp_avg, exp_avg_sq = state['exp_avg'].view(-1), state['exp_avg_sq'].view(-1) + for start in range(0, param.numel(), piece_numel): + count = min(piece_numel, param.numel() - start) + out = before_piece(p, start, count) + piece = slice(start, start + count) + self.ds_opt_adam.adam_update_scaled_copy(self.opt_id, state['step'], group['lr'], beta1, beta2, + group['eps'], group['weight_decay'], + group['bias_correction'], param[piece], grad[piece], + exp_avg[piece], exp_avg_sq[piece], grad_scale, out) + after_piece(p, start, count, out) + @torch.no_grad() def step_subgroup(self, subgroup_id: int, closure=None): """Update the model parameters in a single subgroup (by index).""" diff --git a/deepspeed/runtime/zero/stage3.py b/deepspeed/runtime/zero/stage3.py index e4410d6172df..4260a2d3ede2 100644 --- a/deepspeed/runtime/zero/stage3.py +++ b/deepspeed/runtime/zero/stage3.py @@ -255,6 +255,7 @@ def __init__( # element count is a power of two, so the pinned allocator does not round the buffers up. self._staging_numel = 2**26 self._staging_buffers = None + self._cpu_adam_copy_supported = None # DeepSpeedCPUAdam.copy_supported(), asked once self._staging_events = None self.offload_optimizer_fast_init = False self.offload_param = False @@ -1238,7 +1239,9 @@ def _create_fp16_sub_groups(self, params_group): return sub_groups - def _optimizer_step(self, sub_group_id): + def _optimizer_step(self, sub_group_id, grad_scale=None): + """grad_scale: the factor from _grad_scale_for_cpu_adam, applied by DeepSpeedCPUAdam to each gradient as it is + loaded (the sub-group's gradients were not scaled in place); None when they were.""" param_group_id = self.sub_group_to_group_id[sub_group_id] fp32_param = self.fp32_partitioned_groups_flat[sub_group_id] @@ -1256,7 +1259,10 @@ def step_with_gradscaler(optimizer): cur_device = self.subgroup_to_device[sub_group_id] if cur_device == 'cpu' or (self.use_muon and self.sub_groups_using_muon[sub_group_id]): self.optimizer.param_groups[param_group_id]['params'] = [fp32_param] - step_with_gradscaler(self.optimizer) + if grad_scale is not None: + self.optimizer.step(grad_scale=grad_scale) + else: + step_with_gradscaler(self.optimizer) self.optimizer.param_groups[param_group_id]['params'] = [] else: self.backup_optimizer.param_groups[param_group_id]['params'] = [fp32_param] @@ -2890,6 +2896,58 @@ def _copy_through_pinned_staging(self, dst, src): if last_event is not None: last_event.synchronize() + def _can_copy_back_from_cpu_adam(self, sub_group_id): + """Whether _cpu_adam_step_and_copy_back can replace _optimizer_step + _reassign_or_swap_out_partitioned_parameters + for this CPU sub-group (called only when _grad_scale_for_cpu_adam returned a factor): the device partition is + bfloat16 and would be copied through the pinned staging buffers, and the CPU Adam build can write the + bfloat16 copy.""" + if self.fp16_partitioned_groups_flat[sub_group_id] is None or not self.offload_optimizer_pin_memory: + return False + dst = self.fp16_partitioned_groups_flat[sub_group_id] + src = self.fp32_partitioned_groups_flat[sub_group_id] + if dst.dtype != torch.bfloat16 or dst.device.type == "cpu" or src.is_pinned(): + return False + if self._cpu_adam_copy_supported is None: + self._cpu_adam_copy_supported = self.optimizer.copy_supported() + return self._cpu_adam_copy_supported + + def _cpu_adam_step_and_copy_back(self, sub_group_id, grad_scale): + """CPU Adam on this sub-group in pieces of the pinned staging size: for each piece the kernel updates the + fp32 parameters and writes them in bfloat16 into one staging buffer, which is copied to the device partition + while the next piece is updated. Replaces _optimizer_step followed by _copy_through_pinned_staging (which + reads the fp32 parameters again to cast them); same values, same rounding.""" + param_group_id = self.sub_group_to_group_id[sub_group_id] + fp32_param = self.fp32_partitioned_groups_flat[sub_group_id] + dst = self.fp16_partitioned_groups_flat[sub_group_id].data.view(-1) + chunk = self._staging_numel + if self._staging_buffers is None or self._staging_buffers[0].dtype != dst.dtype: + self._staging_buffers = [get_accelerator().pin_empty(chunk, dtype=dst.dtype) for _ in range(2)] + self._staging_events = [None, None] + pieces = {"index": 0, "last_event": None} + + def before_piece(param, start, count): + buf = pieces["index"] % 2 + if self._staging_events[buf] is not None: + self._staging_events[buf].synchronize() # the previous copy out of this buffer has finished + return self._staging_buffers[buf][:count] + + def after_piece(param, start, count, out): + dst[start:start + count].copy_(out, non_blocking=True) + event = get_accelerator().Event() + event.record() + self._staging_events[pieces["index"] % 2] = event + pieces["last_event"] = event + pieces["index"] += 1 + + self.optimizer.param_groups[param_group_id]['params'] = [fp32_param] + self.optimizer.step_pieces(chunk, before_piece, after_piece, grad_scale=grad_scale) + self.optimizer.param_groups[param_group_id]['params'] = [] + # As _copy_through_pinned_staging: the data must be on the device before returning (the next forward's + # parameter all-gathers run on a stream that does not wait for this one). + if pieces["last_event"] is not None: + pieces["last_event"].synchronize() + self._unflatten_partitioned_parameters(sub_group_id) + @instrument_w_nvtx def _reassign_or_swap_out_partitioned_parameters(self, sub_group_id): if self.fp16_partitioned_groups_flat[sub_group_id] is not None: @@ -2960,14 +3018,20 @@ def step(self, closure=None): if self._muon_update_lacks_loss_scale(sub_group_id): self.fp32_partitioned_groups_flat[sub_group_id].grad.mul_(self.loss_scale) - #scale the fp32 gradients - self.unscale_and_clip_grads(sub_group_id, scaled_global_grad_norm) + #scale the fp32 gradients; DeepSpeedCPUAdam applies the factor as it loads each gradient instead + grad_scale = self._grad_scale_for_cpu_adam(sub_group_id, scaled_global_grad_norm) + if grad_scale is None: + self.unscale_and_clip_grads(sub_group_id, scaled_global_grad_norm) - #apply the optimizer step on the sub group and copy fp32 parameters to fp16 - self._optimizer_step(sub_group_id) + if grad_scale is not None and self._can_copy_back_from_cpu_adam(sub_group_id): + #one kernel pass updates the fp32 parameters and writes their bf16 copy, piece by piece + self._cpu_adam_step_and_copy_back(sub_group_id, grad_scale) + else: + #apply the optimizer step on the sub group and copy fp32 parameters to fp16 + self._optimizer_step(sub_group_id, grad_scale=grad_scale) - #put fp16 parameters in appropriate location - self._reassign_or_swap_out_partitioned_parameters(sub_group_id) + #put fp16 parameters in appropriate location + self._reassign_or_swap_out_partitioned_parameters(sub_group_id) #release memory or swap out optimizer states of fp32 parameters self._release_sub_group(sub_group_id, timer_names) @@ -3022,7 +3086,7 @@ def dump_post_step_gradients(self): print(f'Post-Step Norms {i} {param_id} = {norm_list}') @instrument_w_nvtx - def unscale_and_clip_grads(self, sub_group_id, total_norm): + def _combined_grad_scale(self, total_norm): # compute combined scale factor for this group combined_scale = self.loss_scale if self.clip_grad > 0.: @@ -3030,9 +3094,32 @@ def unscale_and_clip_grads(self, sub_group_id, total_norm): clip = ((total_norm / self.loss_scale) + 1e-6) / self.clip_grad clip = torch.clamp(clip, min=1.0) combined_scale = clip * self.loss_scale + return combined_scale + def unscale_and_clip_grads(self, sub_group_id, total_norm): + combined_scale = self._combined_grad_scale(total_norm) self.fp32_partitioned_groups_flat[sub_group_id].grad.mul_(1. / combined_scale) + def _grad_scale_for_cpu_adam(self, sub_group_id, total_norm): + """The factor unscale_and_clip_grads would multiply this sub-group's gradients by, when DeepSpeedCPUAdam can + apply it while loading each gradient instead; None otherwise. + + Scaling the CPU gradients in place is a separate pass over every offloaded gradient (read and write), done even + when the factor is 1. DeepSpeedCPUAdam.step(grad_scale=...) does the same float multiply on each loaded gradient, + so the update is unchanged. Only for float32 gradients and master weights (a bfloat16 gradient scaled in place + is rounded to bfloat16 before the step), without a GradScaler, ZenFlow, NVMe swapping or Muon. + """ + if not (self.offload_optimizer and type(self.optimizer) == DeepSpeedCPUAdam + and self.subgroup_to_device[sub_group_id] == 'cpu'): + return None + if self.torch_autocast_gradscaler or self.zenflow or self.swap_optimizer or self.use_muon: + return None + fp32_param = self.fp32_partitioned_groups_flat[sub_group_id] + grad = fp32_param.grad + if grad is None or grad.dtype != torch.float32 or fp32_param.dtype != torch.float32 or grad.device.type != 'cpu': + return None + return float(1. / self._combined_grad_scale(total_norm)) + def _check_overflow(self, partition_gradients=True): self.overflow = self.has_overflow(partition_gradients) diff --git a/tests/unit/ops/adam/test_cpu_adam.py b/tests/unit/ops/adam/test_cpu_adam.py index ef685e30af35..cc24f3533047 100644 --- a/tests/unit/ops/adam/test_cpu_adam.py +++ b/tests/unit/ops/adam/test_cpu_adam.py @@ -111,6 +111,84 @@ def test_cpu_adam_strict_state_updates(model_size, adamw_mode, weight_decay, bia torch.testing.assert_close(state['exp_avg_sq'], ref_exp_avg_sq, rtol=3e-5, atol=2e-6) +@pytest.mark.parametrize('model_size', [3, 17, 513, 524289]) +@pytest.mark.parametrize('adamw_mode,weight_decay', [(True, 0.0), (True, 0.07), (False, 0.07)]) +@pytest.mark.parametrize('grad_scale', [0.37, 1.0]) +def test_cpu_adam_grad_scale_matches_scaling_in_place(model_size, adamw_mode, weight_decay, grad_scale): + """step(grad_scale=s) multiplies each gradient by s as the kernel loads it: the parameters and moments must be + bitwise equal to grad.mul_(s) followed by step(), and the gradient itself must be left unchanged. Sizes cover the + vectorized blocks and the scalar remainder.""" + from deepspeed.ops.adam import DeepSpeedCPUAdam + + generator = torch.Generator().manual_seed(model_size) + initial = torch.rand(model_size, generator=generator).mul_(1.5).sub_(0.75) + fused_param = torch.nn.Parameter(initial.clone()) + in_place_param = torch.nn.Parameter(initial.clone()) + kwargs = dict(lr=7e-4, betas=(0.85, 0.97), eps=1e-7, weight_decay=weight_decay, adamw_mode=adamw_mode) + fused = DeepSpeedCPUAdam([fused_param], **kwargs) + in_place = DeepSpeedCPUAdam([in_place_param], **kwargs) + + for _ in range(4): + grad = torch.rand(model_size, generator=generator).mul_(3.0).sub_(1.5) + fused_param.grad = grad.clone() + fused.step(grad_scale=grad_scale) + assert torch.equal(fused_param.grad, grad) + in_place_param.grad = grad.clone().mul_(grad_scale) + in_place.step() + + assert torch.equal(fused_param, in_place_param) + assert torch.equal(fused.state[fused_param]['exp_avg'], in_place.state[in_place_param]['exp_avg']) + assert torch.equal(fused.state[fused_param]['exp_avg_sq'], in_place.state[in_place_param]['exp_avg_sq']) + + +@pytest.mark.parametrize('model_size', [3, 17, 513, 524289]) +@pytest.mark.parametrize('piece_numel', [1000, 1 << 20]) +@pytest.mark.parametrize('grad_scale', [0.37, 1.0]) +def test_cpu_adam_step_pieces_matches_step(model_size, piece_numel, grad_scale): + """step_pieces updates in pieces and writes a bfloat16 copy of each updated piece in the same kernel pass: the + parameters and moments must be bitwise equal to step(grad_scale=...), and the copy bitwise equal to casting the + updated parameters with torch. A requested piece size of 1000 is rounded down to a multiple of the kernel's + widest vector block (aligned_piece_numel); the last piece of 524289 elements still ends in the scalar loop.""" + from deepspeed.ops.adam import DeepSpeedCPUAdam + + generator = torch.Generator().manual_seed(model_size) + initial = torch.rand(model_size, generator=generator).mul_(1.5).sub_(0.75) + pieces_param = torch.nn.Parameter(initial.clone()) + step_param = torch.nn.Parameter(initial.clone()) + kwargs = dict(lr=7e-4, betas=(0.85, 0.97), eps=1e-7, weight_decay=0.07, adamw_mode=True) + pieces = DeepSpeedCPUAdam([pieces_param], **kwargs) + reference = DeepSpeedCPUAdam([step_param], **kwargs) + if not pieces.copy_supported(): + pytest.skip("this CPU Adam build cannot write the bfloat16 copy") + + for _ in range(3): + grad = torch.rand(model_size, generator=generator).mul_(3.0).sub_(1.5) + pieces_param.grad = grad.clone() + step_param.grad = grad.clone() + copy = torch.full((model_size, ), float('nan'), dtype=torch.bfloat16) + seen = [] + + def before_piece(param, start, count): + return torch.empty(count, dtype=torch.bfloat16) + + def after_piece(param, start, count, out): + assert param is pieces_param + seen.append((start, count)) + copy[start:start + count] = out + + pieces.step_pieces(piece_numel, before_piece, after_piece, grad_scale=grad_scale) + reference.step(grad_scale=grad_scale) + + piece = pieces.aligned_piece_numel(piece_numel) + assert piece <= piece_numel or piece == pieces.aligned_piece_numel(1) + assert seen == [(s, min(piece, model_size - s)) for s in range(0, model_size, piece)] + assert torch.equal(pieces_param.grad, grad) + assert torch.equal(pieces_param, step_param) + assert torch.equal(pieces.state[pieces_param]['exp_avg'], reference.state[step_param]['exp_avg']) + assert torch.equal(pieces.state[pieces_param]['exp_avg_sq'], reference.state[step_param]['exp_avg_sq']) + assert torch.equal(copy, step_param.detach().to(torch.bfloat16)) + + def test_cpu_adam_rejects_amsgrad(): from deepspeed.ops.adam import DeepSpeedCPUAdam diff --git a/tests/unit/v1/zero/test_zero.py b/tests/unit/v1/zero/test_zero.py index 2de08f06ca1a..75fa19df463a 100644 --- a/tests/unit/v1/zero/test_zero.py +++ b/tests/unit/v1/zero/test_zero.py @@ -1983,6 +1983,124 @@ def test(self, ratio): assert torch.equal(a, b) +def _train_zero3_cpu_offload(ratio, clip, staging_numel=None, patch=None): + """3 steps of ZeRO-3 with the optimizer offloaded to the CPU (pinned, sub-groups much smaller than the model); + ``patch(optimizer)`` runs after initialization. Returns the parameters after training.""" + hidden_dim = 256 + config_dict = { + "train_micro_batch_size_per_gpu": 2, + "gradient_clipping": clip, + "optimizer": { + "type": "Adam", + "params": { + "lr": 1e-3 + } + }, + "bf16": { + "enabled": True + }, + "zero_optimization": { + "stage": 3, + "sub_group_size": 20000, + "offload_optimizer": { + "device": "cpu", + "pin_memory": True, + "ratio": ratio + } + }, + } + torch.manual_seed(0) + model = SimpleModel(hidden_dim, nlayers=4) + model, _, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config_dict) + if staging_numel is not None: + model.optimizer._staging_numel = staging_numel + if patch is not None: + patch(model.optimizer) + torch.manual_seed(1) + data_loader = random_dataloader(model=model, + total_samples=6, + hidden_dim=hidden_dim, + device=model.device, + dtype=torch.bfloat16) + for batch in data_loader: + loss = model(batch[0], batch[1]) + model.backward(loss) + model.step() + params = [] + for p in model.module.parameters(): + with deepspeed.zero.GatheredParameters([p]): + params.append(p.detach().clone().cpu()) + return params + + +@pytest.mark.skipif(not get_accelerator().is_bf16_supported(), reason="bf16 is not supported on this accelerator") +@pytest.mark.parametrize("ratio", [1.0, 0.5]) +@pytest.mark.parametrize("clip", [1e-3, 1e6]) +class TestZero3CpuAdamGradScale(DistributedTest): + """For CPU sub-groups, ZeRO-3 passes the clipping factor to DeepSpeedCPUAdam (_grad_scale_for_cpu_adam), which + applies it while loading each gradient, instead of multiplying the CPU gradients in place first. The same float + multiply, so the parameters after training must be bitwise equal to the in-place path. Clip 1e-3 clips every step + (factor below 1); clip 1e6 never does (factor 1).""" + world_size = 2 + + def test(self, ratio, clip): + factors = [] + + def in_place(optimizer): + optimizer._grad_scale_for_cpu_adam = lambda sub_group_id, total_norm: None + + def record(optimizer): + original = optimizer._grad_scale_for_cpu_adam + + def wrapped(sub_group_id, total_norm): + factor = original(sub_group_id, total_norm) + factors.append(factor) + return factor + + optimizer._grad_scale_for_cpu_adam = wrapped + + separate = _train_zero3_cpu_offload(ratio, clip, patch=in_place) + fused = _train_zero3_cpu_offload(ratio, clip, patch=record) + used = [f for f in factors if f is not None] + assert used, "no sub-group took the fused path" + assert all(f < 1.0 for f in used) if clip < 1.0 else all(f == 1.0 for f in used) + assert len(separate) == len(fused) + for a, b in zip(separate, fused): + assert torch.equal(a, b) + + +@pytest.mark.skipif(not get_accelerator().is_bf16_supported(), reason="bf16 is not supported on this accelerator") +@pytest.mark.parametrize("ratio", [1.0, 0.5]) +class TestZero3CpuAdamCopyBack(DistributedTest): + """For CPU sub-groups with pinned memory, one DeepSpeedCPUAdam pass (step_pieces) updates the fp32 parameters and + writes their bfloat16 copy into the pinned staging buffers (_cpu_adam_step_and_copy_back), instead of an Adam pass + followed by a cast pass (_copy_through_pinned_staging). The parameters after training must be bitwise equal to + the separate passes. Pieces much smaller than a sub-group reuse both staging buffers many times per step.""" + world_size = 2 + + def test(self, ratio): + calls = [] + + def in_place(optimizer): + optimizer._grad_scale_for_cpu_adam = lambda sub_group_id, total_norm: None + + def record(optimizer): + original = optimizer._cpu_adam_step_and_copy_back + + def wrapped(sub_group_id, grad_scale): + calls.append(sub_group_id) + return original(sub_group_id, grad_scale) + + optimizer._cpu_adam_step_and_copy_back = wrapped + + separate = _train_zero3_cpu_offload(ratio, 1e-3, staging_numel=1000, patch=in_place) + fused = _train_zero3_cpu_offload(ratio, 1e-3, staging_numel=1000, patch=record) + assert calls, "no sub-group took the fused copy-back path" + assert len(separate) == len(fused) + for a, b in zip(separate, fused): + assert torch.equal(a, b) + + @pytest.mark.parametrize("training", [True, False]) class TestZeroPartitionCache(DistributedTest): world_size = 1