diff --git a/csrc/adam/cpu_adam.cpp b/csrc/adam/cpu_adam.cpp index 72b7b2a97473..14c94c5ca3f4 100644 --- a/csrc/adam/cpu_adam.cpp +++ b/csrc/adam/cpu_adam.cpp @@ -9,6 +9,23 @@ 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_grad_scale_supported", + &ds_adam_grad_scale_supported, + "whether adam_update_scaled 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 d5912272376d..e6390cfabd83 100644 --- a/csrc/adam/cpu_adam_impl.cpp +++ b/csrc/adam/cpu_adam_impl.cpp @@ -54,6 +54,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; @@ -62,6 +63,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]; @@ -79,6 +81,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; } @@ -276,6 +279,134 @@ 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 and RVV kernels do 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; +#elif defined(__RVV__) && defined(__riscv_v_intrinsic) && __riscv_v_intrinsic >= 12000 + return false; +#else + return true; +#endif +} + +bool ds_adam_grad_scale_supported() +{ + // Step_RVV does not apply _grad_scale. +#if defined(__RVV__) && defined(__riscv_v_intrinsic) && __riscv_v_intrinsic >= 12000 + 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) +{ + TORCH_CHECK(ds_adam_grad_scale_supported(), + "adam_update_scaled: the RVV kernel does not apply 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 abab3ecda999..ca6f15555a9a 100644 --- a/csrc/includes/cpu_adam.h +++ b/csrc/includes/cpu_adam.h @@ -102,6 +102,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; @@ -127,6 +152,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; @@ -169,6 +198,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); @@ -186,6 +221,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); @@ -216,6 +252,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); } @@ -249,7 +286,8 @@ void Adam_Optimizer::Step_SVE(size_t* rounded_size, _alpha, _weight_decay, _adamw_mode, - parallel); + parallel, + _grad_scale); *rounded_size = _param_size; } } @@ -308,6 +346,41 @@ 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(); + +bool ds_adam_grad_scale_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 134262ce044d..60c599c56f3b 100644 --- a/deepspeed/ops/adam/cpu_adam.py +++ b/deepspeed/ops/adam/cpu_adam.py @@ -114,7 +114,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, bf16_copy=None): """Update the model parameters. .. note:: @@ -126,10 +126,28 @@ 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. + bf16_copy (tuple, optional): ``(piece_numel, before_piece, after_piece)`` + to also write a bfloat16 copy of the updated float32 parameters in + the same kernel pass. Each parameter is updated in pieces of + ``aligned_piece_numel(piece_numel)`` elements: ``out = + before_piece(param, start, count)`` returns a contiguous bfloat16 + CPU tensor of ``count`` elements, the kernel updates the piece and + writes it into ``out`` rounded to nearest even (as ``out.copy_`` + would), then ``after_piece(param, start, count, out)`` is called. + Parameters and moments are bitwise equal to a call without it. + Needs ``copy_supported()``. Defaults to ``None``. Returns: loss: if ``closure`` is provided. Otherwise ``None``. """ + if bf16_copy is not None: + assert self.copy_supported(), "bf16_copy needs AVX512, NEON or the scalar CPU Adam kernel" + if grad_scale != 1.0: + assert self.grad_scale_supported(), "grad_scale is not supported by this CPU Adam build (RVV)" loss = None if closure is not None: @@ -167,11 +185,51 @@ 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 bf16_copy is not None: + self._step_in_pieces_with_copy(p, state, group, grad_scale, *bf16_copy) + elif 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(bf16_copy=...) 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 grad_scale_supported(self): + """Whether step(grad_scale=...) is available (every kernel but RVV).""" + return bool(self.ds_opt_adam.adam_grad_scale_supported()) + + def aligned_piece_numel(self, piece_numel): + """The piece size step(bf16_copy=...) 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 call on the whole parameter.""" + block = int(self.ds_opt_adam.adam_block_numel()) + return max(block, piece_numel - piece_numel % block) + + def _step_in_pieces_with_copy(self, p, state, group, grad_scale, piece_numel, before_piece, after_piece): + assert p.dtype == torch.float32, f"bf16_copy needs float32 parameters, got {p.dtype}" + piece_numel = self.aligned_piece_numel(piece_numel) + 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 6c8f7ca4dc14..979876159fb4 100644 --- a/deepspeed/runtime/zero/stage3.py +++ b/deepspeed/runtime/zero/stage3.py @@ -250,6 +250,17 @@ def __init__( self.offload_optimizer = False self.offload_optimizer_pin_memory = False + # Fused CPU Adam copy-back (_cpu_adam_step_and_copy_back): two pinned bfloat16 buffers of this many elements, so + # the kernel writes one piece while the previous one is copied to the device. A power of two, so the pinned + # allocator does not round the buffers up. + self._cpu_adam_copy_piece_numel = 2**26 + self._cpu_adam_copy_buffers = None + # A fused CPU Adam step applies the gradient scale while loading each gradient and leaves the offloaded fp32 + # gradients unscaled: sub_group_id -> that factor, until _apply_deferred_grad_scale multiplies the gradients + # that were not overwritten since then. + self._deferred_grad_scale = {} + # ds_ids whose offloaded fp32 gradient was overwritten since the last step() + self._offload_grad_written_ids = set() self.offload_optimizer_fast_init = False self.offload_param = False self.offload_param_pin_memory = False @@ -563,6 +574,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, '_cpu_adam_copy_buffers', None) or []: + accelerator.unpin_memory(buffer) unpin_offloaded_optimizer_states(self.optimizer) if self.offload_optimizer_pin_memory: for sub_group_id, fp32_partition in enumerate(self.fp32_partitioned_groups_flat): @@ -1243,7 +1256,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, which DeepSpeedCPUAdam applies to each gradient as it + loads it (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] @@ -1261,7 +1276,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 None: + step_with_gradscaler(self.optimizer) + else: + self.optimizer.step(grad_scale=grad_scale) self.optimizer.param_groups[param_group_id]['params'] = [] else: self.backup_optimizer.param_groups[param_group_id]['params'] = [fp32_param] @@ -1468,6 +1486,7 @@ def _offload_grad_partition_at_boundary(self, param, grad_buffer, offload_fp32_g else: fp32_grad_tensor = self.fp32_partitioned_groups_flat[i].grad.narrow(0, dest_offset, grad_buffer.numel()) fp32_grad_tensor.copy_(grad_buffer.to(dtype=self.master_weights_and_grads_dtype), non_blocking=True) + self._offload_grad_written_ids.add(param.ds_id) def _swap_out_offload_fp32_gradients(self, offload_fp32_gradients, offload_fp32_offsets): if not (self.offload_optimizer and self.swap_optimizer): @@ -2556,6 +2575,10 @@ def reset_cpu_buffers(self): def _pre_step(self): self.micro_step_id = 0 self._offload_boundary_param_ids = set() + # Before the overflow check, so that a skipped step also leaves the gradients as the in-place scaling would; it + # reads which gradients the window ending here overwrote. + self._apply_all_deferred_grad_scales() + self._offload_grad_written_ids = set() # Also reset the epilogue flag so the next iteration starts fresh. # Without this, the flag from the last backward before step() would cause # an increment in the next forward(), which is wrong. @@ -2886,6 +2909,60 @@ def _copy_pinned_master_to_device(self, dst, src): event.record() 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 (asked only when _grad_scale_for_cpu_adam returned a factor): the device partition is + bfloat16, offload_optimizer.pin_memory is set, and the CPU Adam build can write the bfloat16 copy.""" + dst = self.fp16_partitioned_groups_flat[sub_group_id] + if dst is None or not self.offload_optimizer_pin_memory: + return False + if dst.dtype != torch.bfloat16 or dst.device.type == "cpu": + return False + return self.optimizer.copy_supported() + + @instrument_w_nvtx + def _cpu_adam_step_and_copy_back(self, sub_group_id, grad_scale): + """CPU Adam on this sub-group in pieces: for each piece the kernel updates the fp32 parameters and writes them in + bfloat16 into one of two pinned buffers, which is copied to the device partition while the next piece is + updated. Replaces _optimizer_step followed by _copy_pinned_master_to_device, which reads the fp32 master again + and copies twice the bytes to a float32 device temporary of the whole sub-group; 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) + piece_numel = self._cpu_adam_copy_piece_numel + if self._cpu_adam_copy_buffers is None: + self._cpu_adam_copy_buffers = [ + get_accelerator().pin_empty(piece_numel, dtype=torch.bfloat16) for _ in range(2) + ] + buffers = self._cpu_adam_copy_buffers + copy_events = [None, None] + piece_id = 0 + + def before_piece(param, start, count): + event = copy_events[piece_id % 2] + if event is not None: + # The copy out of this buffer, two pieces ago, must finish before the kernel writes it again. + event.synchronize() + return buffers[piece_id % 2][:count] + + def after_piece(param, start, count, out): + nonlocal piece_id + dst[start:start + count].copy_(out, non_blocking=True) + event = get_accelerator().Event() + event.record() + copy_events[piece_id % 2] = event + piece_id += 1 + + self.optimizer.param_groups[param_group_id]['params'] = [fp32_param] + self.optimizer.step(grad_scale=grad_scale, bf16_copy=(piece_numel, before_piece, after_piece)) + self.optimizer.param_groups[param_group_id]['params'] = [] + # As _copy_pinned_master_to_device: the partition must be on the device when this returns (the next forward's + # parameter all-gathers run on a stream that does not wait for this one). + last_event = copy_events[(piece_id - 1) % 2] if piece_id > 0 else None + if last_event is not None: + 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: @@ -2954,14 +3031,25 @@ 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) + elif grad_scale != 1.0: + self._deferred_grad_scale[sub_group_id] = grad_scale - #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 + if grad_scale is None: + self._optimizer_step(sub_group_id) + else: + 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) @@ -3015,8 +3103,7 @@ def dump_post_step_gradients(self): norm_list = [param_norm, ds_norm] + unflat_norm 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.: @@ -3024,9 +3111,53 @@ 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 + @instrument_w_nvtx + 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. The gradients themselves are multiplied later, and only where the next + accumulation window did not overwrite them (_apply_deferred_grad_scale). Only for float32 gradients and master + weights on the CPU, without a GradScaler, ZenFlow, NVMe swapping or Muon. + """ + if not self.deepspeed_adam_offload or 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 + if not self.optimizer.grad_scale_supported(): + return None + return float(1. / self._combined_grad_scale(total_norm)) + + def _apply_deferred_grad_scale(self, sub_group_id): + """Multiply the gradients that a fused CPU Adam step left unscaled by its factor, except the ones overwritten + since then. A parameter that is not reduced in a window keeps its older gradient, and the next step reads it + again; the in-place path has multiplied it by every step's factor, so it must hold the same value here.""" + factor = self._deferred_grad_scale.pop(sub_group_id, None) + if factor is None: + return + fp32_grad = self.fp32_partitioned_groups_flat[sub_group_id].grad + for param in self.fp16_groups[sub_group_id]: + if param.ds_id in self._offload_grad_written_ids: + continue + _, dest_offset, num_elements = self.grad_position[self.get_param_id(param)] + fp32_grad.narrow(0, dest_offset, num_elements).mul_(factor) + + def _apply_all_deferred_grad_scales(self): + for sub_group_id in list(self._deferred_grad_scale): + self._apply_deferred_grad_scale(sub_group_id) + def _check_overflow(self, partition_gradients=True): self.overflow = self.has_overflow(partition_gradients) @@ -3115,6 +3246,7 @@ def get_fp32_grad_partitions(self) -> Dict[int, Dict[int, Tensor]]: self.reduce_and_partition_stream.synchronize() grad_dict = collections.defaultdict(dict) if self.offload_optimizer: + self._apply_all_deferred_grad_scales() for group in self.fp16_groups: for param_idx, param in enumerate(group): group_idx, dest_offset, num_elements = self.grad_position[self.get_param_id(param)] @@ -3148,6 +3280,7 @@ def _get_fp32_grad_state_partition(self, param, release_swap_buffers): if self._swappable_optimizer_subgroup(group_idx): self._optimizer_states_and_gradient_swap_in(group_idx) + self._apply_deferred_grad_scale(group_idx) fp32_grad = self.fp32_partitioned_groups_flat[group_idx].grad.narrow(0, dest_offset, num_elements) if self._swappable_optimizer_subgroup(group_idx) and release_swap_buffers: @@ -3325,6 +3458,7 @@ def update_fp32_grad_for_param_vectorized(self, update_func, param_list): for group_idx, group_params in subgroups.items(): if self._swappable_optimizer_subgroup(group_idx): self._optimizer_states_and_gradient_swap_in(group_idx) + self._apply_deferred_grad_scale(group_idx) for param, dest_offset, num_elements in group_params: if self.offload_optimizer: diff --git a/tests/unit/ops/adam/test_cpu_adam.py b/tests/unit/ops/adam/test_cpu_adam.py index f487fc2759f0..82cf2a98511d 100644 --- a/tests/unit/ops/adam/test_cpu_adam.py +++ b/tests/unit/ops/adam/test_cpu_adam.py @@ -7,6 +7,7 @@ import math import os import sys +import warnings import torch import numpy as np import pytest @@ -114,6 +115,111 @@ 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) + if grad_scale != 1.0 and not fused.grad_scale_supported(): + pytest.skip("this CPU Adam build cannot apply grad_scale (RVV)") + + 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_bf16_copy_matches_step(model_size, piece_numel, grad_scale): + """step(bf16_copy=...) 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(grad_scale=grad_scale, bf16_copy=(piece_numel, before_piece, after_piece)) + 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_bf16_copy_runs_step_hooks(): + """step(bf16_copy=...) is still torch's wrapped Optimizer.step: step hooks run, and a learning-rate scheduler on + the optimizer sees the step (no "lr_scheduler.step() before optimizer.step()" warning).""" + from deepspeed.ops.adam import DeepSpeedCPUAdam + + param = torch.nn.Parameter(torch.ones(256)) + optimizer = DeepSpeedCPUAdam([param], lr=1e-3) + if not optimizer.copy_supported(): + pytest.skip("this CPU Adam build cannot write the bfloat16 copy") + scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1) + calls = [] + optimizer.register_step_pre_hook(lambda opt, args, kwargs: calls.append("pre")) + optimizer.register_step_post_hook(lambda opt, args, kwargs: calls.append("post")) + param.grad = torch.full((256, ), 0.5) + copy = torch.empty(256, dtype=torch.bfloat16) + optimizer.step(grad_scale=0.5, bf16_copy=(256, lambda p, start, count: copy[start:start + count], lambda *a: None)) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + scheduler.step() + + assert calls == ["pre", "post"] + assert not [w for w in caught if "optimizer.step()" in str(w.message)] + assert torch.equal(copy, 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 6c86154fb2d0..00859e35d1d5 100644 --- a/tests/unit/v1/zero/test_zero.py +++ b/tests/unit/v1/zero/test_zero.py @@ -1965,6 +1965,8 @@ def counting_copy(dst, src): copy_pinned_master(dst, src) optimizer._copy_pinned_master_to_device = counting_copy + # This test covers the copy above; the bf16 copy written by DeepSpeedCPUAdam is TestZero3CpuAdamCopyBack's. + optimizer._can_copy_back_from_cpu_adam = lambda sub_group_id: False torch.manual_seed(1) data_loader = random_dataloader(model=model, total_samples=6, @@ -2090,6 +2092,222 @@ def test(self): torch.testing.assert_close(safe_get_full_fp32_param(param), reference_param, rtol=1e-5, atol=1e-6) +class _SometimesUsedLayerModel(Module): + """SimpleModel's loss over a few layers, plus one layer that runs only while ``use_extra`` is set.""" + + def __init__(self, hidden_dim): + super().__init__() + self.linears = ModuleList([Linear(hidden_dim, hidden_dim) for _ in range(3)]) + self.extra = Linear(hidden_dim, hidden_dim) + self.use_extra = True + self.cross_entropy_loss = torch.nn.CrossEntropyLoss() + + def forward(self, x, y): + for layer in self.linears: + x = layer(x) + if self.use_extra: + x = self.extra(x) + return self.cross_entropy_loss(x, y) + + +def _train_zero3_cpu_offload(ratio, + clip, + pin_memory=True, + dtype="bf16", + piece_numel=None, + patch=None, + sometimes_used_layer=False, + overflow_first_step=False): + """3 steps of ZeRO-3 with the optimizer offloaded to the CPU (sub-groups much smaller than the model); + ``patch(optimizer)`` runs after initialization. With ``sometimes_used_layer``, one layer runs only in the first step. + With ``overflow_first_step``, the first loss is multiplied by inf. Returns (parameters after training, their + gradients as safe_get_full_grad reads them after the last step, engine).""" + hidden_dim = 256 + config_dict = { + "train_micro_batch_size_per_gpu": 2, + "gradient_clipping": clip, + "optimizer": { + "type": "Adam", + "params": { + "lr": 1e-3 + } + }, + "zero_optimization": { + "stage": 3, + "sub_group_size": 20000, + "offload_optimizer": { + "device": "cpu", + "pin_memory": pin_memory, + "ratio": ratio + } + }, + } + if dtype == "bf16": + config_dict["bf16"] = {"enabled": True} + else: + config_dict["fp16"] = {"enabled": True, "initial_scale_power": 8, "hysteresis": 1} + torch.manual_seed(0) + model = _SometimesUsedLayerModel(hidden_dim) if sometimes_used_layer else SimpleModel(hidden_dim, nlayers=4) + model, _, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config_dict) + if piece_numel is not None: + model.optimizer._cpu_adam_copy_piece_numel = piece_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 if dtype == "bf16" else torch.half) + for step, batch in enumerate(data_loader): + if sometimes_used_layer: + model.module.use_extra = step == 0 + loss = model(batch[0], batch[1]) + if overflow_first_step and step == 0: + loss = loss * float("inf") + model.backward(loss) + model.step() + params = [] + for p in model.module.parameters(): + with deepspeed.zero.GatheredParameters([p]): + params.append(p.detach().clone().cpu()) + grads = [safe_get_full_grad(p).detach().clone().cpu() for p in model.module.parameters()] + return params, grads, model + + +def _scale_gradients_in_place(optimizer): + """The reference: every sub-group's gradients are scaled in place before a plain CPU Adam step.""" + optimizer._grad_scale_for_cpu_adam = lambda sub_group_id, total_norm: None + + +def _record_grad_scales(factors): + + def patch(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 + + return patch + + +@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]) +@pytest.mark.parametrize("pin_memory", [True, False]) +class TestZero3CpuAdamGradScale(DistributedTest): + """For CPU sub-groups, ZeRO-3 passes the clipping factor to DeepSpeedCPUAdam, 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, and the gradients read after the last step, 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, pin_memory): + factors = [] + separate, separate_grads, _ = _train_zero3_cpu_offload(ratio, + clip, + pin_memory=pin_memory, + patch=_scale_gradients_in_place) + fused, fused_grads, _ = _train_zero3_cpu_offload(ratio, + clip, + pin_memory=pin_memory, + patch=_record_grad_scales(factors)) + 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 + separate_grads, fused + fused_grads): + 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 updates the fp32 parameters and writes their + bfloat16 copy into two pinned buffers that are copied to the device piece by piece, instead of an Adam pass followed + by copying the fp32 master to the device and casting it there. The parameters after training must be bitwise equal + to the separate passes. Pieces much smaller than a sub-group reuse both buffers many times per step.""" + world_size = 2 + + def test(self, ratio): + if get_accelerator().device_name() == "cpu": + pytest.skip("on the CPU accelerator the partitions never leave the host, so there is nothing to copy back") + calls = [] + + 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, piece_numel=1000, patch=_scale_gradients_in_place) + fused, _, _ = _train_zero3_cpu_offload(ratio, 1e-3, piece_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.skipif(not get_accelerator().is_bf16_supported(), reason="bf16 is not supported on this accelerator") +@pytest.mark.parametrize("pin_memory", [True, False]) +class TestZero3CpuAdamUnusedLayer(DistributedTest): + """A layer used only in the first step: its offloaded gradient is not overwritten afterwards, the optimizer reads + it again in every later step, and the in-place path multiplies it by every step's factor. With every sub-group on + the fused path, the parameters after training, and the gradients read after the last step, must be bitwise equal + to the in-place path.""" + world_size = 2 + + def test(self, pin_memory): + factors = [] + separate, separate_grads, _ = _train_zero3_cpu_offload(1.0, + 1e-3, + pin_memory=pin_memory, + patch=_scale_gradients_in_place, + sometimes_used_layer=True) + fused, fused_grads, _ = _train_zero3_cpu_offload(1.0, + 1e-3, + pin_memory=pin_memory, + patch=_record_grad_scales(factors), + sometimes_used_layer=True) + assert factors and all(f is not None for f in factors), "a sub-group did not take the fused path" + assert len(separate) == len(fused) + for a, b in zip(separate + separate_grads, fused + fused_grads): + assert torch.equal(a, b) + + +@pytest.mark.skipif(not get_accelerator().is_fp16_supported(), reason="fp16 is not supported on this accelerator") +class TestZero3CpuAdamFp16Overflow(DistributedTest): + """fp16 with a dynamic loss scale and an overflow in the first step: the step is skipped and the loss scale lowered + on both paths, and the later fused steps (the factor includes the loss scale) match the in-place path bitwise.""" + world_size = 2 + + def test(self): + factors = [] + separate, _, separate_engine = _train_zero3_cpu_offload(1.0, + 1.0, + dtype="fp16", + patch=_scale_gradients_in_place, + overflow_first_step=True) + fused, _, fused_engine = _train_zero3_cpu_offload(1.0, + 1.0, + dtype="fp16", + patch=_record_grad_scales(factors), + overflow_first_step=True) + assert any(f is not None for f in factors), "no sub-group took the fused path" + assert fused_engine.skipped_steps == separate_engine.skipped_steps == 1 + assert fused_engine.optimizer.loss_scale == separate_engine.optimizer.loss_scale + assert fused_engine.optimizer.loss_scale < 2**8 + for a, b in zip(separate, fused): + assert torch.equal(a, b) + + @pytest.mark.parametrize("training", [True, False]) class TestZeroPartitionCache(DistributedTest): world_size = 1