From 6cb78d0d7af132051649753f50937b267ae41e75 Mon Sep 17 00:00:00 2001 From: st-bang97 Date: Tue, 29 Sep 2026 02:22:39 +0000 Subject: [PATCH 01/19] Add ReFlow asynchronous CPU-offloaded optimizers for ZeRO-3 This commit introduces ReFlow, an asynchronous CPU-offloaded optimizer path for DeepSpeed ZeRO-3. ReFlow reduces CPU optimizer overhead and overlaps bucket-wise CPU optimizer execution with GPU backward computation. Highlights: - ReFlow Adam/AdamW and Lion CPU optimizers. - BF16 gradient offload with SIMD-local FP32 promotion and CPU-side gradient accumulation. - Register-resident AVX/SIMD optimizer kernels. - Ready/Persist scheduling for overlapping CPU optimizer execution without FP32 optimizer-state rollback. - ReFlow configuration, unit/training tests, CI coverage, documentation, and tutorial. Signed-off-by: st-bang97 --- ci/tests_fetcher.py | 6 + csrc/adam/cpu_adam.cpp | 4 + csrc/adam/reflow_cpu_adam_bindings.cpp | 145 ++ csrc/adam/reflow_cpu_adam_impl.cpp | 609 ++++++ csrc/includes/reflow_bindings.h | 9 + csrc/includes/reflow_cpu_adam.h | 422 ++++ csrc/includes/reflow_cpu_affinity.h | 42 + csrc/includes/reflow_cpu_lion.h | 366 ++++ csrc/includes/reflow_simd.h | 194 ++ csrc/lion/cpu_lion.cpp | 4 + csrc/lion/reflow_cpu_lion_bindings.cpp | 114 ++ csrc/lion/reflow_cpu_lion_impl.cpp | 459 +++++ deepspeed/runtime/config.py | 10 + deepspeed/runtime/engine.py | 28 +- deepspeed/runtime/reflow/README.md | 304 +++ deepspeed/runtime/reflow/__init__.py | 10 + deepspeed/runtime/reflow/engine.py | 106 + deepspeed/runtime/reflow/reflow_config.py | 47 + deepspeed/runtime/reflow/reflow_cpu_adam.py | 182 ++ deepspeed/runtime/reflow/reflow_cpu_lion.py | 157 ++ deepspeed/runtime/reflow/reflow_stage3.py | 1697 +++++++++++++++++ deepspeed/runtime/reflow/reflow_utils.py | 425 +++++ deepspeed/runtime/zero/config.py | 28 + .../zero/partitioned_param_coordinator.py | 14 + deepspeed/runtime/zero/utils.py | 9 + deepspeed/utils/numa.py | 38 +- deepspeed/utils/timer.py | 22 +- docs/_data/navigation.yml | 2 + docs/_pages/config-json.md | 43 + docs/_tutorials/reflow.md | 84 + docs/code-docs/source/optimizers.rst | 8 + docs/code-docs/source/zero3.rst | 5 +- op_builder/cpu/cpu_adam.py | 5 +- op_builder/cpu_adam.py | 5 +- op_builder/cpu_lion.py | 5 +- op_builder/hpu/cpu_adam.py | 5 +- op_builder/mlu/cpu_adam.py | 5 +- op_builder/mps/cpu_adam.py | 5 +- op_builder/npu/cpu_adam.py | 5 +- op_builder/npu/cpu_lion.py | 5 +- op_builder/sdaa/cpu_adam.py | 5 +- op_builder/supa/cpu_adam.py | 5 +- op_builder/supa/cpu_lion.py | 5 +- op_builder/xpu/cpu_adam.py | 5 +- tests/unit/launcher/test_ds_arguments.py | 64 +- .../unit/v1/ops/test_reflow_cpu_optimizers.py | 300 +++ tests/unit/v1/zero/test_reflow.py | 720 +++++++ 47 files changed, 6714 insertions(+), 23 deletions(-) create mode 100644 csrc/adam/reflow_cpu_adam_bindings.cpp create mode 100644 csrc/adam/reflow_cpu_adam_impl.cpp create mode 100644 csrc/includes/reflow_bindings.h create mode 100644 csrc/includes/reflow_cpu_adam.h create mode 100644 csrc/includes/reflow_cpu_affinity.h create mode 100644 csrc/includes/reflow_cpu_lion.h create mode 100644 csrc/includes/reflow_simd.h create mode 100644 csrc/lion/reflow_cpu_lion_bindings.cpp create mode 100644 csrc/lion/reflow_cpu_lion_impl.cpp create mode 100644 deepspeed/runtime/reflow/README.md create mode 100644 deepspeed/runtime/reflow/__init__.py create mode 100644 deepspeed/runtime/reflow/engine.py create mode 100644 deepspeed/runtime/reflow/reflow_config.py create mode 100644 deepspeed/runtime/reflow/reflow_cpu_adam.py create mode 100644 deepspeed/runtime/reflow/reflow_cpu_lion.py create mode 100644 deepspeed/runtime/reflow/reflow_stage3.py create mode 100644 deepspeed/runtime/reflow/reflow_utils.py create mode 100644 docs/_tutorials/reflow.md create mode 100644 tests/unit/v1/ops/test_reflow_cpu_optimizers.py create mode 100644 tests/unit/v1/zero/test_reflow.py diff --git a/ci/tests_fetcher.py b/ci/tests_fetcher.py index 27debbc26915..728b87fd8d84 100644 --- a/ci/tests_fetcher.py +++ b/ci/tests_fetcher.py @@ -178,6 +178,12 @@ class TestSelector: # module_inject is applied at deepspeed.initialize() time (replace_module / # replace_transformer_layer); the tests it affects don't import it directly. "deepspeed/module_inject/**": ("tests/unit/v1/moe/**", ), + # Reflow's ZeRO-3 optimizer is chosen inside deepspeed.initialize(); its tests reach it + # through the engine rather than by importing it. + "deepspeed/runtime/reflow/**": ( + "tests/unit/v1/zero/test_reflow.py", + "tests/unit/v1/ops/test_reflow_cpu_optimizers.py", + ), } def __init__(self, repo_root: Path | str, config: WorkflowConfig): diff --git a/csrc/adam/cpu_adam.cpp b/csrc/adam/cpu_adam.cpp index 72b7b2a97473..6245c8e0c7d3 100644 --- a/csrc/adam/cpu_adam.cpp +++ b/csrc/adam/cpu_adam.cpp @@ -4,6 +4,8 @@ // DeepSpeed Team #include "cpu_adam.h" +#include +#include "reflow_bindings.h" PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { @@ -48,4 +50,6 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) "ZenFlowAdam cross-process exit (C++)", pybind11::call_guard()); #endif + + bind_reflow_adam(m); } diff --git a/csrc/adam/reflow_cpu_adam_bindings.cpp b/csrc/adam/reflow_cpu_adam_bindings.cpp new file mode 100644 index 000000000000..0c8cc1d01c1e --- /dev/null +++ b/csrc/adam/reflow_cpu_adam_bindings.cpp @@ -0,0 +1,145 @@ +// SPDX-License-Identifier: Apache-2.0 +// DeepSpeed Team + +#include "reflow_bindings.h" +#include "reflow_cpu_adam.h" + +// Memory fence to enforce store ordering after non-temporal (streaming) stores. +static void reflow_adam_memory_fence() +{ +#if defined(__AVX512__) or defined(__AVX256__) + _mm_mfence(); +#endif +} + +static inline int reflow_ds_adam_step_params_halfgrad_gilfree(int optimizer_id, + size_t step, + float lr, + float beta1, + float beta2, + float epsilon, + float weight_decay, + bool bias_correction, + torch::Tensor& params_fp32, + torch::Tensor& grads, + torch::Tensor& exp_avg, + torch::Tensor& exp_avg_sq, + torch::Tensor& half_params, + float combined_scale, + bool skip_increment_step = false) +{ + pybind11::gil_scoped_release release; + return reflow_ds_adam_step_params_halfgrad(optimizer_id, + step, + lr, + beta1, + beta2, + epsilon, + weight_decay, + bias_correction, + params_fp32, + grads, + exp_avg, + exp_avg_sq, + half_params, + combined_scale, + skip_increment_step); +} + +static inline int reflow_ds_adam_state_step_halfgrad_gilfree(int optimizer_id, + size_t step, + float lr, + float beta1, + float beta2, + float epsilon, + float weight_decay, + bool bias_correction, + torch::Tensor& params_fp32, + torch::Tensor& grads, + torch::Tensor& exp_avg, + torch::Tensor& exp_avg_sq, + float combined_scale, + bool skip_increment_step = false) +{ + pybind11::gil_scoped_release release; + return reflow_ds_adam_state_step_halfgrad(optimizer_id, + step, + lr, + beta1, + beta2, + epsilon, + weight_decay, + bias_correction, + params_fp32, + grads, + exp_avg, + exp_avg_sq, + combined_scale, + skip_increment_step); +} + +static inline int reflow_ds_bf16_accumulate_gilfree(torch::Tensor& dst, torch::Tensor& src) +{ + pybind11::gil_scoped_release release; + return reflow_ds_bf16_accumulate(dst, src); +} + +void bind_reflow_adam(pybind11::module_& m) +{ + m.def("reflow_create_adam", + &reflow_create_adam_optimizer, + "Reflow CPU Adam create (C++)", + pybind11::arg("optimizer_id"), + pybind11::arg("alpha") = 1e-3, + pybind11::arg("betta1") = 0.9, + pybind11::arg("betta2") = 0.999, + pybind11::arg("eps") = 1e-8, + pybind11::arg("weight_decay") = 0, + pybind11::arg("adamw_mode") = true, + pybind11::arg("should_log") = false, + pybind11::arg("num_threads") = -1); + m.def("reflow_destroy_adam", &reflow_destroy_adam_optimizer, "Reflow CPU Adam destroy (C++)"); + m.def("reflow_adam_update_params_halfgrad", + &reflow_ds_adam_step_params_halfgrad_gilfree, + "Reflow CPU Adam update FP16 with half gradients, GIL-released (C++)", + pybind11::arg("optimizer_id"), + pybind11::arg("step"), + pybind11::arg("lr"), + pybind11::arg("beta1"), + pybind11::arg("beta2"), + pybind11::arg("epsilon"), + pybind11::arg("weight_decay"), + pybind11::arg("bias_correction"), + pybind11::arg("params_fp32"), + pybind11::arg("grads"), + pybind11::arg("exp_avg"), + pybind11::arg("exp_avg_sq"), + pybind11::arg("half_params"), + pybind11::arg("combined_scale"), + pybind11::arg("skip_increment_step") = false); + m.def("reflow_adam_update_state_halfgrad", + &reflow_ds_adam_state_step_halfgrad_gilfree, + "Reflow CPU Adam update state stream with half gradients, GIL-released (C++)", + pybind11::arg("optimizer_id"), + pybind11::arg("step"), + pybind11::arg("lr"), + pybind11::arg("beta1"), + pybind11::arg("beta2"), + pybind11::arg("epsilon"), + pybind11::arg("weight_decay"), + pybind11::arg("bias_correction"), + pybind11::arg("params_fp32"), + pybind11::arg("grads"), + pybind11::arg("exp_avg"), + pybind11::arg("exp_avg_sq"), + pybind11::arg("combined_scale"), + pybind11::arg("skip_increment_step") = false); + m.def("reflow_adam_memory_fence", + &reflow_adam_memory_fence, + "Reflow CPU Adam memory fence (C++)"); + m.def("reflow_bf16_accumulate", + &reflow_ds_bf16_accumulate_gilfree, + "Reflow CPU BF16/FP16 gradient accumulate using AVX, GIL-released (C++)", + pybind11::arg("dst"), + pybind11::arg("src")); +} diff --git a/csrc/adam/reflow_cpu_adam_impl.cpp b/csrc/adam/reflow_cpu_adam_impl.cpp new file mode 100644 index 000000000000..f6a0b9cb88e5 --- /dev/null +++ b/csrc/adam/reflow_cpu_adam_impl.cpp @@ -0,0 +1,609 @@ +// Copyright (c) Microsoft Corporation. +// SPDX-License-Identifier: Apache-2.0 + +// DeepSpeed Team + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "reflow_cpu_adam.h" + +#ifdef __linux__ +#include +#include +#endif + +using namespace std::string_literals; + +// Independent step counters for param vs. async-state updates. +struct ReflowOptimizerPair { + std::shared_ptr param_opt; + std::shared_ptr state_opt; + // Bucket workers share the optimizer scalars; keep their updates serialized. + std::shared_ptr param_opt_mutex; +}; +static std::unordered_map s_reflow_optimizers; + +// Affinity-aware available-core count (falls back to omp_get_num_procs()). +static unsigned int reflow_get_available_cpu_count() +{ +#ifdef __linux__ + cpu_set_t cpuset; + CPU_ZERO(&cpuset); + + if (sched_getaffinity(0, sizeof(cpu_set_t), &cpuset) == 0) { + unsigned int count = 0; + for (int i = 0; i < CPU_SETSIZE; i++) { + if (CPU_ISSET(i, &cpuset)) { count++; } + } + if (count > 0) { return count; } + } +#endif + return omp_get_num_procs(); +} + +// Non-positive thread counts use all cores available to this worker. +static unsigned int reflow_resolve_omp_threads(int num_threads, unsigned int available) +{ + if (num_threads > 0) { return std::min(static_cast(num_threads), available); } + return available; +} + +int reflow_create_adam_optimizer(int optimizer_id, + float alpha, + float betta1, + float betta2, + float eps, + float weight_decay, + bool adamw_mode, + bool should_log, + int num_threads) +{ + // The Reflow half-grad kernels exist only for AVX2/AVX-512; fail here instead of at the first + // step. +#if !(defined(__AVX512__) or defined(__AVX256__)) + throw std::runtime_error("Reflow Adam requires a CPU build with AVX2 or AVX-512 support"); +#endif + auto parameter_opt = std::make_shared( + alpha, betta1, betta2, eps, weight_decay, adamw_mode); + auto state_opt = std::make_shared( + alpha, betta1, betta2, eps, weight_decay, adamw_mode); + parameter_opt->set_num_threads(num_threads); + state_opt->set_num_threads(num_threads); + s_reflow_optimizers[optimizer_id] = + ReflowOptimizerPair{parameter_opt, state_opt, std::make_shared()}; + + if (should_log) { + std::string avx_type = ""; +#if defined(__AVX512__) + avx_type = "AVX512"; +#else + avx_type = "AVX2"; +#endif + + printf("Reflow Adam Optimizer #%d is created with %s arithmetic capability.\n", + optimizer_id, + avx_type.c_str()); + printf("Config: alpha=%f, betas=(%f, %f), weight_decay=%f, adam_w=%d\n", + alpha, + betta1, + betta2, + weight_decay, + (int)adamw_mode); + } + + return 0; +} + +// Half/BFloat16 gradient + FP16/BF16-store path (params only, skips state). +template +void Reflow_Adam_Optimizer::Step_8_FP16_HalfGrad(float* _params_fp32, + ds_grad_precision_t* grads_half, + ds_state_precision_t* _exp_avg, + ds_state_precision_t* _exp_avg_sq, + size_t _param_size, + ds_store_precision_t* half_params, + float combined_scale) +{ + size_t rounded_size = 0; +#if defined(__AVX512__) or defined(__AVX256__) + Step_AVX_HalfGrad<8, ds_grad_precision_t, ds_state_precision_t, ds_store_precision_t, true>( + &rounded_size, + _params_fp32, + grads_half, + _exp_avg, + _exp_avg_sq, + _param_size, + half_params, + combined_scale); + // Narrow the SIMD span before handling the remaining scalar tail. + if (_param_size > rounded_size) { + size_t tail_rounded_size = 0; + Step_AVX_HalfGrad<4, ds_grad_precision_t, ds_state_precision_t, ds_store_precision_t, true>( + &tail_rounded_size, + _params_fp32 + rounded_size, + grads_half + rounded_size, + _exp_avg + rounded_size, + _exp_avg_sq + rounded_size, + _param_size - rounded_size, + half_params + rounded_size, + combined_scale); + rounded_size += tail_rounded_size; + } + if (_param_size > rounded_size) { + size_t tail_rounded_size = 0; + Step_AVX_HalfGrad<1, ds_grad_precision_t, ds_state_precision_t, ds_store_precision_t, true>( + &tail_rounded_size, + _params_fp32 + rounded_size, + grads_half + rounded_size, + _exp_avg + rounded_size, + _exp_avg_sq + rounded_size, + _param_size - rounded_size, + half_params + rounded_size, + combined_scale); + rounded_size += tail_rounded_size; + } +#endif + if (_param_size > rounded_size) { + float betta1_minus1 = 1 - _betta1; + float betta2_minus1 = 1 - _betta2; + + float step_size = -1 * _alpha / _bias_correction1; + float w_decay = -1 * _alpha * _weight_decay; + float unscale_factor = 1.0f / combined_scale; + + for (size_t t = rounded_size; t < _param_size; t += TILE) { + size_t copy_size = TILE; + if ((t + TILE) > _param_size) copy_size = _param_size - t; + size_t offset = copy_size + t; + ReflowCPUAffinity affinity; +#pragma omp parallel + { + affinity.apply(); +#pragma omp for schedule(static) nowait + for (size_t k = t; k < offset; k++) { + float grad = static_cast(grads_half[k]) * unscale_factor; + float param = _params_fp32[k]; + float momentum = static_cast(_exp_avg[k]); + float variance = static_cast(_exp_avg_sq[k]); + + if (_weight_decay > 0 && !_adamw_mode) { grad = param * _weight_decay + grad; } + momentum = momentum * _betta1; + momentum = grad * betta1_minus1 + momentum; + + variance = variance * _betta2; + grad = grad * grad; + variance = grad * betta2_minus1 + variance; + + grad = sqrt(variance); + grad = grad * _bias_correction2 + _eps; + grad = momentum / grad; + if (_weight_decay > 0 && _adamw_mode) { param += w_decay * param; } + param = grad * step_size + param; + + // Store param to FP16/BF16 buffer only; state is skipped. + half_params[k] = ds_store_precision_t(param); + } + } + } + } +} + +// Half/BFloat16 gradient state-only update path. +template +void Reflow_Adam_Optimizer::Step_8_State_HalfGrad(float* _params_fp32, + ds_grad_precision_t* grads_half, + ds_state_precision_t* _exp_avg, + ds_state_precision_t* _exp_avg_sq, + size_t _param_size, + float combined_scale) +{ + size_t rounded_size = 0; +#if defined(__AVX512__) or defined(__AVX256__) + Step_AVX_HalfGrad<8, ds_grad_precision_t, ds_state_precision_t, float, false>( + &rounded_size, + _params_fp32, + grads_half, + _exp_avg, + _exp_avg_sq, + _param_size, + static_cast(nullptr), + combined_scale); + // Narrow the SIMD span before handling the remaining scalar tail. + if (_param_size > rounded_size) { + size_t tail_rounded_size = 0; + Step_AVX_HalfGrad<4, ds_grad_precision_t, ds_state_precision_t, float, false>( + &tail_rounded_size, + _params_fp32 + rounded_size, + grads_half + rounded_size, + _exp_avg + rounded_size, + _exp_avg_sq + rounded_size, + _param_size - rounded_size, + static_cast(nullptr), + combined_scale); + rounded_size += tail_rounded_size; + } + if (_param_size > rounded_size) { + size_t tail_rounded_size = 0; + Step_AVX_HalfGrad<1, ds_grad_precision_t, ds_state_precision_t, float, false>( + &tail_rounded_size, + _params_fp32 + rounded_size, + grads_half + rounded_size, + _exp_avg + rounded_size, + _exp_avg_sq + rounded_size, + _param_size - rounded_size, + static_cast(nullptr), + combined_scale); + rounded_size += tail_rounded_size; + } +#endif + if (_param_size > rounded_size) { + float betta1_minus1 = 1 - _betta1; + float betta2_minus1 = 1 - _betta2; + float unscale_factor = 1.0f / combined_scale; + float step_size = -1.0f * _alpha / _bias_correction1; + float w_decay = -1.0f * _alpha * _weight_decay; + + for (size_t t = rounded_size; t < _param_size; t += TILE) { + size_t copy_size = TILE; + if ((t + TILE) > _param_size) copy_size = _param_size - t; + size_t offset = copy_size + t; + ReflowCPUAffinity affinity; +#pragma omp parallel + { + affinity.apply(); +#pragma omp for schedule(static) nowait + for (size_t k = t; k < offset; k++) { + float grad = static_cast(grads_half[k]) * unscale_factor; + float param = _params_fp32[k]; + float momentum = static_cast(_exp_avg[k]); + float variance = static_cast(_exp_avg_sq[k]); + + if (_weight_decay > 0 && !_adamw_mode) { grad = param * _weight_decay + grad; } + momentum = momentum * _betta1; + momentum = grad * betta1_minus1 + momentum; + + variance = variance * _betta2; + grad = grad * grad; + variance = grad * betta2_minus1 + variance; + + grad = sqrt(variance); + grad = grad * _bias_correction2 + _eps; + grad = momentum / grad; + if (_weight_decay > 0 && _adamw_mode) { param += w_decay * param; } + param = grad * step_size + param; + + _params_fp32[k] = param; + _exp_avg[k] = static_cast(momentum); + _exp_avg_sq[k] = static_cast(variance); + } + } + } + } +} + +/* Half/BFloat16 gradient FP16-store path (params only, state skipped). + * params_fp32 stays FP32; the half_params buffer receives FP16/BF16. + */ +int reflow_ds_adam_step_params_halfgrad(int optimizer_id, + size_t step, + float lr, + float beta1, + float beta2, + float epsilon, + float weight_decay, + bool bias_correction, + torch::Tensor& params_fp32, + torch::Tensor& grads, + torch::Tensor& exp_avg, + torch::Tensor& exp_avg_sq, + torch::Tensor& half_params, + float combined_scale, + bool skip_increment_step) +{ + auto params_c = params_fp32.contiguous(); + auto grads_c = grads.contiguous(); + auto exp_avg_c = exp_avg.contiguous(); + auto exp_avg_sq_c = exp_avg_sq.contiguous(); + auto half_params_c = half_params.contiguous(); + + const size_t param_size = params_c.numel(); + if (param_size == 0) { return 0; } + + c10::ScalarType param_type = at::typeMetaToScalarType(params_c.options().dtype()); + c10::ScalarType grad_type = at::typeMetaToScalarType(grads_c.options().dtype()); + c10::ScalarType state_type = at::typeMetaToScalarType(exp_avg_c.options().dtype()); + c10::ScalarType store_type = at::typeMetaToScalarType(half_params_c.options().dtype()); + + if (param_type != torch::kFloat32) { + throw std::runtime_error("reflow_ds_adam_step_params_halfgrad expects FP32 params tensor"); + } + if (grad_type != torch::kFloat16 && grad_type != torch::kBFloat16) { + throw std::runtime_error( + "reflow_ds_adam_step_params_halfgrad expects FP16 or BF16 gradient tensor"); + } + if (store_type != torch::kFloat16 && store_type != torch::kBFloat16) { + throw std::runtime_error( + "reflow_ds_adam_step_params_halfgrad expects FP16 or BF16 half_params tensor"); + } + + ReflowOptimizerPair& pair = s_reflow_optimizers[optimizer_id]; + std::shared_ptr opt = pair.param_opt; + Reflow_Adam_Optimizer worker_opt; + // Snapshot this range's scalars under the lock so another group cannot change them + // while its SIMD kernel runs. The disjoint parameter buffers still run in parallel. + // Keep the mutex alive even if its registry entry is replaced. + std::shared_ptr opt_mutex = pair.param_opt_mutex; + { + std::lock_guard opt_lock(*opt_mutex); + opt->IncrementStep(step, beta1, beta2); + opt->update_state(lr, epsilon, weight_decay, bias_correction); + worker_opt = *opt; + } + // Honor the worker's CPU affinity to avoid oversubscribing its pinned cores. + unsigned int reflow_total_cpus = reflow_get_available_cpu_count(); + unsigned int reflow_max_omp_threads = + reflow_resolve_omp_threads(worker_opt.get_num_threads(), reflow_total_cpus); + int reflow_original_omp_threads = omp_get_max_threads(); + omp_set_num_threads(reflow_max_omp_threads); +#if defined(__AVX512__) or defined(__AVX256__) + if (store_type == torch::kFloat16 && grad_type == torch::kFloat16 && + state_type == torch::kFloat32) { + worker_opt.Step_8_FP16_HalfGrad( + params_c.data_ptr(), + grads_c.data_ptr(), + exp_avg_c.data_ptr(), + exp_avg_sq_c.data_ptr(), + param_size, + half_params_c.data_ptr(), + combined_scale); + } else if (store_type == torch::kFloat16 && grad_type == torch::kFloat16 && + state_type == torch::kFloat16) { + worker_opt.Step_8_FP16_HalfGrad( + params_c.data_ptr(), + grads_c.data_ptr(), + exp_avg_c.data_ptr(), + exp_avg_sq_c.data_ptr(), + param_size, + half_params_c.data_ptr(), + combined_scale); +#if defined(__AVX512__) or defined(__AVX256__) + } else if (store_type == torch::kBFloat16 && grad_type == torch::kBFloat16 && + state_type == torch::kFloat32) { + worker_opt.Step_8_FP16_HalfGrad( + params_c.data_ptr(), + grads_c.data_ptr(), + exp_avg_c.data_ptr(), + exp_avg_sq_c.data_ptr(), + param_size, + half_params_c.data_ptr(), + combined_scale); + } else if (store_type == torch::kBFloat16 && grad_type == torch::kBFloat16 && + state_type == torch::kBFloat16) { + worker_opt.Step_8_FP16_HalfGrad( + params_c.data_ptr(), + grads_c.data_ptr(), + exp_avg_c.data_ptr(), + exp_avg_sq_c.data_ptr(), + param_size, + half_params_c.data_ptr(), + combined_scale); +#endif + } else +#endif + { + omp_set_num_threads(reflow_original_omp_threads); + throw std::runtime_error( + "reflow_ds_adam_step_params_halfgrad: unsupported combination of store/grad/state " + "dtypes"); + } + omp_set_num_threads(reflow_original_omp_threads); + return 0; +} + +// Commit the FP32 master and optimizer state from half-precision gradients. +int reflow_ds_adam_state_step_halfgrad(int optimizer_id, + size_t step, + float lr, + float beta1, + float beta2, + float epsilon, + float weight_decay, + bool bias_correction, + torch::Tensor& params_fp32, + torch::Tensor& grads, + torch::Tensor& exp_avg, + torch::Tensor& exp_avg_sq, + float combined_scale, + bool skip_increment_step) +{ + unsigned int total_cpus = reflow_get_available_cpu_count(); + int configured_num_threads = s_reflow_optimizers[optimizer_id].state_opt->get_num_threads(); + unsigned int max_omp_threads = reflow_resolve_omp_threads(configured_num_threads, total_cpus); + int original_num_threads = omp_get_max_threads(); + omp_set_num_threads(max_omp_threads); + + auto params_c = params_fp32.contiguous(); + auto grads_c = grads.contiguous(); + auto exp_avg_c = exp_avg.contiguous(); + auto exp_avg_sq_c = exp_avg_sq.contiguous(); + + const size_t param_size = params_c.numel(); + if (param_size == 0) { + omp_set_num_threads(original_num_threads); + return 0; + } + + c10::ScalarType param_type = at::typeMetaToScalarType(params_c.options().dtype()); + c10::ScalarType grad_type = at::typeMetaToScalarType(grads_c.options().dtype()); + c10::ScalarType state_type = at::typeMetaToScalarType(exp_avg_c.options().dtype()); + + if (param_type != torch::kFloat32) { + omp_set_num_threads(original_num_threads); + throw std::runtime_error("reflow_ds_adam_state_step_halfgrad expects FP32 params tensor"); + } + if (grad_type != torch::kFloat16 && grad_type != torch::kBFloat16) { + omp_set_num_threads(original_num_threads); + throw std::runtime_error( + "reflow_ds_adam_state_step_halfgrad expects FP16 or BF16 gradient tensor"); + } + + std::shared_ptr opt = s_reflow_optimizers[optimizer_id].state_opt; + if (!skip_increment_step) { + opt->IncrementStep(step, beta1, beta2); + opt->update_state(lr, epsilon, weight_decay, bias_correction); + } +#if defined(__AVX512__) or defined(__AVX256__) + if (grad_type == torch::kFloat16 && state_type == torch::kFloat32) { + opt->Step_8_State_HalfGrad(params_c.data_ptr(), + grads_c.data_ptr(), + exp_avg_c.data_ptr(), + exp_avg_sq_c.data_ptr(), + param_size, + combined_scale); + } else if (grad_type == torch::kFloat16 && state_type == torch::kFloat16) { + opt->Step_8_State_HalfGrad(params_c.data_ptr(), + grads_c.data_ptr(), + exp_avg_c.data_ptr(), + exp_avg_sq_c.data_ptr(), + param_size, + combined_scale); +#if defined(__AVX512__) or defined(__AVX256__) + } else if (grad_type == torch::kBFloat16 && state_type == torch::kFloat32) { + opt->Step_8_State_HalfGrad(params_c.data_ptr(), + grads_c.data_ptr(), + exp_avg_c.data_ptr(), + exp_avg_sq_c.data_ptr(), + param_size, + combined_scale); + } else if (grad_type == torch::kBFloat16 && state_type == torch::kBFloat16) { + opt->Step_8_State_HalfGrad( + params_c.data_ptr(), + grads_c.data_ptr(), + exp_avg_c.data_ptr(), + exp_avg_sq_c.data_ptr(), + param_size, + combined_scale); +#endif + } else +#endif + { + omp_set_num_threads(original_num_threads); + throw std::runtime_error( + "reflow_ds_adam_state_step_halfgrad: unsupported combination of grad/state dtypes"); + } + omp_set_num_threads(original_num_threads); + return 0; +} + +int reflow_destroy_adam_optimizer(int optimizer_id) +{ + s_reflow_optimizers.erase(optimizer_id); + + return 0; +} + +/* BF16/FP16 gradient accumulation using AVX: dst[i] += src[i]. + * Both tensors must be contiguous BF16/FP16 tensors on CPU. + */ +int reflow_ds_bf16_accumulate(torch::Tensor& dst, torch::Tensor& src) +{ + auto dst_c = dst.contiguous(); + auto src_c = src.contiguous(); + + const size_t param_size = dst_c.numel(); + if (param_size == 0) { return 0; } + + if (src_c.numel() != static_cast(param_size)) { + throw std::runtime_error("reflow_ds_bf16_accumulate: src and dst must have same numel"); + } + + c10::ScalarType dst_type = at::typeMetaToScalarType(dst_c.options().dtype()); + c10::ScalarType src_type = at::typeMetaToScalarType(src_c.options().dtype()); + + if (dst_type != src_type) { + throw std::runtime_error("reflow_ds_bf16_accumulate: dst and src must have same dtype"); + } + +#if defined(__AVX512__) or defined(__AVX256__) + // Accumulation runs in bucket workers too; do not oversubscribe their smaller CPU masks. + unsigned int num_threads = std::min(static_cast(omp_get_max_threads()), + reflow_get_available_cpu_count()); + if (dst_type == torch::kBFloat16) { + c10::BFloat16* dst_ptr = dst_c.data_ptr(); + c10::BFloat16* src_ptr = src_c.data_ptr(); + + // AVX512 BF16 accumulation: load as FP32, add, store as BF16. + constexpr int span = 8; + size_t rounded_size = ROUND_DOWN(param_size, SIMD_WIDTH * span); + + ReflowCPUAffinity affinity; +#pragma omp parallel num_threads(num_threads) + { + affinity.apply(); +#pragma omp for schedule(static) nowait + for (size_t i = 0; i < rounded_size; i += SIMD_WIDTH * span) { + AVX_Data dst_4[span]; + AVX_Data src_4[span]; + reflow_simd_load(dst_4, dst_ptr + i); + reflow_simd_load(src_4, src_ptr + i); + simd_add(dst_4, dst_4, src_4); + reflow_simd_store(dst_ptr + i, dst_4); + } + } + + for (size_t i = rounded_size; i < param_size; ++i) { + float dst_val = static_cast(dst_ptr[i]); + float src_val = static_cast(src_ptr[i]); + dst_ptr[i] = static_cast(dst_val + src_val); + } + return 0; + } +#endif + +#if defined(__AVX512__) or defined(__AVX256__) + if (dst_type == torch::kFloat16) { + c10::Half* dst_ptr = dst_c.data_ptr(); + c10::Half* src_ptr = src_c.data_ptr(); + + // AVX FP16 accumulation: load as FP32, add, store as FP16. + constexpr int span = 8; + size_t rounded_size = ROUND_DOWN(param_size, SIMD_WIDTH * span); + + ReflowCPUAffinity affinity; +#pragma omp parallel num_threads(num_threads) + { + affinity.apply(); +#pragma omp for schedule(static) nowait + for (size_t i = 0; i < rounded_size; i += SIMD_WIDTH * span) { + AVX_Data dst_4[span]; + AVX_Data src_4[span]; + reflow_simd_load(dst_4, dst_ptr + i); + reflow_simd_load(src_4, src_ptr + i); + simd_add(dst_4, dst_4, src_4); + reflow_simd_store(dst_ptr + i, dst_4); + } + } + + for (size_t i = rounded_size; i < param_size; ++i) { + float dst_val = static_cast(dst_ptr[i]); + float src_val = static_cast(src_ptr[i]); + dst_ptr[i] = static_cast(dst_val + src_val); + } + return 0; + } +#endif + + throw std::runtime_error( + "reflow_ds_bf16_accumulate: only BF16 and FP16 (with AVX2/AVX512) are supported"); +} diff --git a/csrc/includes/reflow_bindings.h b/csrc/includes/reflow_bindings.h new file mode 100644 index 000000000000..9d28f7adbcc6 --- /dev/null +++ b/csrc/includes/reflow_bindings.h @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: Apache-2.0 +// DeepSpeed Team + +#pragma once + +#include + +void bind_reflow_adam(pybind11::module_& m); +void bind_reflow_lion(pybind11::module_& m); diff --git a/csrc/includes/reflow_cpu_adam.h b/csrc/includes/reflow_cpu_adam.h new file mode 100644 index 000000000000..9542d0870855 --- /dev/null +++ b/csrc/includes/reflow_cpu_adam.h @@ -0,0 +1,422 @@ +// Copyright (c) Microsoft Corporation. +// SPDX-License-Identifier: Apache-2.0 + +// DeepSpeed Team + +#pragma once + +#define NOMINMAX // Windows idiosyncrasy + // https://stackoverflow.com/questions/4913922/possible-problems-with-nominmax-on-visual-c + +#if defined(_OPENMP) +#include +#else +/* Builds without OpenMP (e.g. Apple clang without libomp) run the kernels on one thread. */ +inline int omp_get_max_threads() { return 1; } +inline int omp_get_num_procs() { return 1; } +inline void omp_set_num_threads(int) {} +#endif +#include +#include +#include +#include +#include "reflow_cpu_affinity.h" +#include "reflow_simd.h" + +/* Enable madvise(MADV_HUGEPAGE) hints in the streaming kernels (Linux only). + * Transparent huge pages reduce TLB pressure for the large, sequentially + * streamed param/grad/state buffers. + */ +#define USE_HUGE_PAGE 1 +#ifdef __linux__ +#include +#endif + +class Reflow_Adam_Optimizer { +public: + Reflow_Adam_Optimizer(float alpha = 1e-3, + float betta1 = 0.9, + float betta2 = 0.999, + float eps = 1e-8, + float weight_decay = 0, + bool adamw_mode = true) + : _alpha(alpha), + _betta1(betta1), + _betta2(betta2), + _eps(eps), + _weight_decay(weight_decay), + _betta1_t(1.0), + _betta2_t(1.0), + _step(0), + _bias_correction1(1.0), + _bias_correction2(1.0), + _adamw_mode(adamw_mode), + _num_threads(-1) + { + } + ~Reflow_Adam_Optimizer() {} + +#if defined(__AVX512__) or defined(__AVX256__) + // Adam over the SIMD-aligned prefix of a half-precision gradient. With store_half_params it + // writes only the new FP16/BF16 params to half_params (param generation); otherwise it commits + // the FP32 master and the state. + template + void Step_AVX_HalfGrad(size_t* rounded_size, + float* _params_fp32, + ds_grad_precision_t* grads_half, + ds_state_precision_t* _exp_avg, + ds_state_precision_t* _exp_avg_sq, + size_t param_size, + ds_store_precision_t* half_params, + float combined_scale); + + template + void Step_AVX_HalfGrad_Loop(size_t rounded_size, + float* _params_fp32, + ds_grad_precision_t* grads_half, + ds_state_precision_t* _exp_avg, + ds_state_precision_t* _exp_avg_sq, + ds_store_precision_t* half_params, + float combined_scale); + +#endif + inline void IncrementStep(size_t step, float beta1, float beta2) + { + if (beta1 != _betta1 || beta2 != _betta2) { + _step = step; + _betta1 = beta1; + _betta2 = beta2; + _betta1_t = std::pow(_betta1, step); + _betta2_t = std::pow(_betta2, step); + } else { + if (step == _step + 1) { // first optimizer step increase + _step++; + _betta1_t *= _betta1; + _betta2_t *= _betta2; + } else if (step == + _step) { // no need to update step; beta1_t and beta2_t already updated + return; + } else { // support step increase not equal to 1 + _betta1_t = std::pow(_betta1, step); + _betta2_t = std::pow(_betta2, step); + _step = step; + } + } + } + inline void update_state(float lr, float epsilon, float weight_decay, bool bias_correction) + { + _alpha = lr; + _eps = epsilon; + _weight_decay = weight_decay; + + _bias_correction1 = 1.0f; + _bias_correction2 = 1.0f; + if (bias_correction == 1) { + _bias_correction1 = 1 - _betta1_t; + _bias_correction2 = 1 / sqrt(1 - _betta2_t); + } + } + + /* -1 (the default) means "use all available cores"; a positive value caps the + * OpenMP thread count for the CPU-Adam state update. + */ + inline void set_num_threads(int num_threads) { _num_threads = num_threads; } + inline int get_num_threads() const { return _num_threads; } + + // Half/BFloat16 gradient wrapper, params-only FP16/BF16 store. + template + void Step_8_FP16_HalfGrad(float* _params_fp32, + ds_grad_precision_t* grads_half, + ds_state_precision_t* _exp_avg, + ds_state_precision_t* _exp_avg_sq, + size_t _param_size, + ds_store_precision_t* half_params, + float combined_scale); + + // Half/BFloat16 gradient wrapper, state-only update. + template + void Step_8_State_HalfGrad(float* _params_fp32, + ds_grad_precision_t* grads_half, + ds_state_precision_t* _exp_avg, + ds_state_precision_t* _exp_avg_sq, + size_t _param_size, + float combined_scale = 1.0f); + +private: + float _alpha; + float _betta1; + float _betta2; + float _eps; + float _weight_decay; + + float _betta1_t; + float _betta2_t; + size_t _step; + + float _bias_correction1; + float _bias_correction2; + + bool _adamw_mode; + + // OpenMP thread cap for the CPU-Adam state update; -1 means all available cores. + int _num_threads; +}; + +#if defined(__AVX512__) or defined(__AVX256__) + +/* Half/BFloat16 gradient path: params stay FP32, grads are Half/BFloat16, + * arithmetic is FP32, results stored to FP32 params and state. + */ +template +void Reflow_Adam_Optimizer::Step_AVX_HalfGrad(size_t* rounded_size, + float* _params_fp32, + ds_grad_precision_t* grads_half, + ds_state_precision_t* _exp_avg, + ds_state_precision_t* _exp_avg_sq, + size_t _param_size, + ds_store_precision_t* half_params, + float combined_scale) +{ + size_t new_rounded_size = ROUND_DOWN(_param_size, SIMD_WIDTH * span); + +#if defined(__linux__) && USE_HUGE_PAGE + if (new_rounded_size > 0) { + size_t page_size = 4096; + auto madvise_bytes = [&](size_t elem_size) { + return (_param_size * elem_size + page_size - 1) & ~(page_size - 1); + }; + size_t params_bytes = madvise_bytes(sizeof(float)); + size_t grad_bytes = madvise_bytes(sizeof(ds_grad_precision_t)); + size_t state_bytes = madvise_bytes(sizeof(ds_state_precision_t)); + void* params_aligned = (void*)((uintptr_t)_params_fp32 & ~(page_size - 1)); + madvise(params_aligned, params_bytes, MADV_HUGEPAGE); + madvise((void*)((uintptr_t)grads_half & ~(page_size - 1)), grad_bytes, MADV_HUGEPAGE); + madvise((void*)((uintptr_t)_exp_avg & ~(page_size - 1)), state_bytes, MADV_HUGEPAGE); + madvise((void*)((uintptr_t)_exp_avg_sq & ~(page_size - 1)), state_bytes, MADV_HUGEPAGE); + if (store_half_params) { + size_t store_bytes = madvise_bytes(sizeof(ds_store_precision_t)); + madvise((void*)((uintptr_t)half_params & ~(page_size - 1)), store_bytes, MADV_HUGEPAGE); + } + } +#endif + + // Pick the loop specialized for this step's flags, so no per-element branch remains. + bool unscale_grads = (combined_scale > 1.0f); + bool decay_grad = (_weight_decay > 0 && !_adamw_mode); + bool decay_param = (_weight_decay > 0 && _adamw_mode); + using G = ds_grad_precision_t; + using S = ds_state_precision_t; + using H = ds_store_precision_t; + if (unscale_grads && decay_grad) { + Step_AVX_HalfGrad_Loop( + new_rounded_size, + _params_fp32, + grads_half, + _exp_avg, + _exp_avg_sq, + half_params, + combined_scale); + } else if (unscale_grads && decay_param) { + Step_AVX_HalfGrad_Loop( + new_rounded_size, + _params_fp32, + grads_half, + _exp_avg, + _exp_avg_sq, + half_params, + combined_scale); + } else if (unscale_grads) { + Step_AVX_HalfGrad_Loop( + new_rounded_size, + _params_fp32, + grads_half, + _exp_avg, + _exp_avg_sq, + half_params, + combined_scale); + } else if (decay_grad) { + Step_AVX_HalfGrad_Loop( + new_rounded_size, + _params_fp32, + grads_half, + _exp_avg, + _exp_avg_sq, + half_params, + combined_scale); + } else if (decay_param) { + Step_AVX_HalfGrad_Loop( + new_rounded_size, + _params_fp32, + grads_half, + _exp_avg, + _exp_avg_sq, + half_params, + combined_scale); + } else { + Step_AVX_HalfGrad_Loop( + new_rounded_size, + _params_fp32, + grads_half, + _exp_avg, + _exp_avg_sq, + half_params, + combined_scale); + } + + *rounded_size = new_rounded_size; +} + +// Template flags eliminate per-element branches from each specialized loop. +template +void Reflow_Adam_Optimizer::Step_AVX_HalfGrad_Loop(size_t rounded_size, + float* _params_fp32, + ds_grad_precision_t* grads_half, + ds_state_precision_t* _exp_avg, + ds_state_precision_t* _exp_avg_sq, + ds_store_precision_t* half_params, + float combined_scale) +{ + AVX_Data betta1_4; + betta1_4.data = SIMD_SET(_betta1); + AVX_Data betta2_4; + betta2_4.data = SIMD_SET(_betta2); + + float betta1_minus1 = 1 - _betta1; + float betta2_minus1 = 1 - _betta2; + AVX_Data betta1_minus1_4; + betta1_minus1_4.data = SIMD_SET(betta1_minus1); + AVX_Data betta2_minus1_4; + betta2_minus1_4.data = SIMD_SET(betta2_minus1); + + AVX_Data bias2_sqrt; + bias2_sqrt.data = SIMD_SET(_bias_correction2); + + AVX_Data eps_4; + eps_4.data = SIMD_SET(_eps); + + float step_size = -1 * _alpha / _bias_correction1; + AVX_Data step_size_4; + step_size_4.data = SIMD_SET(step_size); + + // Adam folds the decay into the gradient; AdamW decays the parameter by lr * weight_decay. + float w_decay = -1 * _alpha * _weight_decay; + AVX_Data weight_decay4; + if (decay_grad) { weight_decay4.data = SIMD_SET(_weight_decay); } + if (decay_param) { weight_decay4.data = SIMD_SET(w_decay); } + + AVX_Data unscale_factor; + if (unscale_grads) { unscale_factor.data = SIMD_SET(1.0f / combined_scale); } + + ReflowCPUAffinity affinity; +#pragma omp parallel + { + affinity.apply(); +#pragma omp for schedule(static) nowait + for (size_t i = 0; i < rounded_size; i += SIMD_WIDTH * span) { + AVX_Data grad_4[span]; + reflow_simd_load(grad_4, grads_half + i); + if (unscale_grads) { simd_mul(grad_4, grad_4, unscale_factor); } + AVX_Data momentum_4[span]; + reflow_simd_load(momentum_4, _exp_avg + i); + AVX_Data variance_4[span]; + reflow_simd_load(variance_4, _exp_avg_sq + i); + AVX_Data param_4[span]; + reflow_simd_load(param_4, _params_fp32 + i); + + if (decay_grad) { simd_fma(grad_4, param_4, weight_decay4, grad_4); } + simd_mul(momentum_4, momentum_4, betta1_4); + simd_fma(momentum_4, grad_4, betta1_minus1_4, momentum_4); + simd_mul(variance_4, variance_4, betta2_4); + simd_mul(grad_4, grad_4, grad_4); + simd_fma(variance_4, grad_4, betta2_minus1_4, variance_4); + simd_sqrt(grad_4, variance_4); + simd_fma(grad_4, grad_4, bias2_sqrt, eps_4); + simd_div(grad_4, momentum_4, grad_4); + if (decay_param) { simd_fma(param_4, param_4, weight_decay4, param_4); } + simd_fma(param_4, grad_4, step_size_4, param_4); + + if (store_half_params) { + // Param generation leaves the FP32 master and the state to the later commit. + reflow_simd_store_stream(half_params + i, param_4); + } else { + reflow_simd_store(_params_fp32 + i, param_4); + reflow_simd_store(_exp_avg + i, momentum_4); + reflow_simd_store(_exp_avg_sq + i, variance_4); + } + } + } +} + +#endif + +int reflow_create_adam_optimizer(int optimizer_id, + float alpha = 1e-3, + float betta1 = 0.9, + float betta2 = 0.999, + float eps = 1e-8, + float weight_decay = 0, + bool adamw_mode = true, + bool should_log = false, + int num_threads = -1); + +int reflow_ds_adam_step_params_halfgrad(int optimizer_id, + size_t step, + float lr, + float beta1, + float beta2, + float epsilon, + float weight_decay, + bool bias_correction, + torch::Tensor& params_fp32, + torch::Tensor& grads, + torch::Tensor& exp_avg, + torch::Tensor& exp_avg_sq, + torch::Tensor& half_params, + float combined_scale = 1.0f, + bool skip_increment_step = false); + +int reflow_ds_adam_state_step_halfgrad(int optimizer_id, + size_t step, + float lr, + float beta1, + float beta2, + float epsilon, + float weight_decay, + bool bias_correction, + torch::Tensor& params_fp32, + torch::Tensor& grads, + torch::Tensor& exp_avg, + torch::Tensor& exp_avg_sq, + float combined_scale = 1.0f, + bool skip_increment_step = false); + +int reflow_destroy_adam_optimizer(int optimizer_id); + +/* BF16/FP16 gradient accumulation using AVX (CPU-side gradient accumulation): + * dst[i] += src[i]. Returns 0 on success. + */ +int reflow_ds_bf16_accumulate(torch::Tensor& dst, torch::Tensor& src); diff --git a/csrc/includes/reflow_cpu_affinity.h b/csrc/includes/reflow_cpu_affinity.h new file mode 100644 index 000000000000..c983077b32fe --- /dev/null +++ b/csrc/includes/reflow_cpu_affinity.h @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: Apache-2.0 +// DeepSpeed Team + +#pragma once + +#if defined(__linux__) && defined(_OPENMP) +#include +#include +#endif + +// OpenMP retains its helper threads when the calling worker changes CPU masks. +// Apply the caller's current mask inside the existing team, before it does any work. +class ReflowCPUAffinity { +public: + ReflowCPUAffinity() + { +#if defined(__linux__) && defined(_OPENMP) + CPU_ZERO(&_mask); + _valid = sched_getaffinity(0, sizeof(_mask), &_mask) == 0; +#endif + } + + void apply() const + { +#if defined(__linux__) && defined(_OPENMP) + if (_valid && omp_get_thread_num() != 0) { + cpu_set_t current; + // Most kernels reuse the same team and mask; avoid the scheduler update in that case. + if (sched_getaffinity(0, sizeof(current), ¤t) != 0 || + !CPU_EQUAL(¤t, &_mask)) { + sched_setaffinity(0, sizeof(_mask), &_mask); + } + } +#endif + } + +private: +#if defined(__linux__) && defined(_OPENMP) + cpu_set_t _mask; + bool _valid; +#endif +}; diff --git a/csrc/includes/reflow_cpu_lion.h b/csrc/includes/reflow_cpu_lion.h new file mode 100644 index 000000000000..6d6f2a4db518 --- /dev/null +++ b/csrc/includes/reflow_cpu_lion.h @@ -0,0 +1,366 @@ +// Copyright (c) Microsoft Corporation. +// SPDX-License-Identifier: Apache-2.0 + +// DeepSpeed Team + +/* Lion keeps a single momentum buffer (exp_avg); there is no second moment, no + * eps, and no bias correction. The update is: + * c_t = beta1*m_old + (1-beta1)*g (update direction) + * p_new = p*(1 - lr*wd) - lr*sign(c_t) (decoupled decay + sign step) + * m_new = beta2*m_old + (1-beta2)*g (momentum EMA) + * Both c_t and m_new read the OLD momentum, so c_t must be formed before the + * momentum register is overwritten with m_new. + */ + +#pragma once + +#define NOMINMAX // Windows idiosyncrasy + // https://stackoverflow.com/questions/4913922/possible-problems-with-nominmax-on-visual-c + +#if defined(_OPENMP) +#include +#else +/* Builds without OpenMP (e.g. Apple clang without libomp) run the kernels on one thread. */ +inline int omp_get_max_threads() { return 1; } +inline int omp_get_num_procs() { return 1; } +inline void omp_set_num_threads(int) {} +#endif +#include +#include +#include +#include +#include "reflow_cpu_affinity.h" +#include "reflow_simd.h" + +/* Enable madvise(MADV_HUGEPAGE) hints in the streaming kernels (Linux only). + * Transparent huge pages reduce TLB pressure for the large, sequentially + * streamed param/grad/state buffers. + */ +#define USE_HUGE_PAGE 1 +#ifdef __linux__ +#include +#endif + +class Reflow_Lion_Optimizer { +public: + Reflow_Lion_Optimizer(float alpha = 1e-3, + float betta1 = 0.9, + float betta2 = 0.999, + float weight_decay = 0) + : _alpha(alpha), + _betta1(betta1), + _betta2(betta2), + _weight_decay(weight_decay), + _step(0), + _num_threads(-1) + { + } + ~Reflow_Lion_Optimizer() {} + +#if defined(__AVX512__) or defined(__AVX256__) + // Half/BFloat16 gradient path that updates params (FP32 master) + state. + template + void Step_AVX_HalfGrad(size_t* rounded_size, + float* _params_fp32, + ds_grad_precision_t* grads_half, + ds_state_precision_t* _exp_avg, + size_t param_size, + float combined_scale = 1.0f); + // Half/BFloat16 gradient path that updates params only, stored to FP16/BF16. + template + void Step_AVX_FP16_HalfGrad(size_t* rounded_size, + float* _params_fp32, + ds_grad_precision_t* grads_half, + ds_state_precision_t* _exp_avg, + size_t param_size, + ds_store_precision_t* half_params, + float combined_scale); +#endif + + // Half/BFloat16 gradient wrapper, params-only FP16/BF16 store. + template + void Step_8_FP16_HalfGrad(float* _params_fp32, + ds_grad_precision_t* grads_half, + ds_state_precision_t* _exp_avg, + size_t _param_size, + ds_store_precision_t* half_params, + float combined_scale); + + // Half/BFloat16 gradient wrapper, params (FP32 master) + state update. + template + void Step_8_State_HalfGrad(float* _params_fp32, + ds_grad_precision_t* grads_half, + ds_state_precision_t* _exp_avg, + size_t _param_size, + float combined_scale = 1.0f); + + inline void IncrementStep(size_t step, float beta1, float beta2) + { + _step++; + if (_step != step || beta1 != _betta1 || beta2 != _betta2) { + _step = step; + _betta1 = beta1; + _betta2 = beta2; + } + } + inline void update_state(float lr, float weight_decay) + { + _alpha = lr; + _weight_decay = weight_decay; + } + + /* -1 (the default) means "use all available cores"; a positive value caps the + * OpenMP thread count for the CPU-Lion state update. + */ + inline void set_num_threads(int num_threads) { _num_threads = num_threads; } + inline int get_num_threads() const { return _num_threads; } + +private: + float _alpha; + float _betta1; + float _betta2; + float _weight_decay; + size_t _step; + + // OpenMP thread cap for the CPU-Lion state update; -1 means all available cores. + int _num_threads; +}; + +#if defined(__AVX512__) or defined(__AVX256__) + +/* Half/BFloat16 gradient path: params stay FP32, grads are Half/BFloat16, + * arithmetic is FP32, and the deferred commit writes the FP32 master and momentum. + */ +template +void Reflow_Lion_Optimizer::Step_AVX_HalfGrad(size_t* rounded_size, + float* _params_fp32, + ds_grad_precision_t* grads_half, + ds_state_precision_t* _exp_avg, + size_t _param_size, + float combined_scale) +{ + size_t new_rounded_size = 0; + + AVX_Data neg1_4; + neg1_4.data = SIMD_SET(-1.0f); + + AVX_Data betta1_4; + betta1_4.data = SIMD_SET(_betta1); + AVX_Data betta2_4; + betta2_4.data = SIMD_SET(_betta2); + + float betta1_minus1 = 1 - _betta1; + float betta2_minus1 = 1 - _betta2; + AVX_Data betta1_minus1_4; + betta1_minus1_4.data = SIMD_SET(betta1_minus1); + AVX_Data betta2_minus1_4; + betta2_minus1_4.data = SIMD_SET(betta2_minus1); + + float step_size = -_alpha; + AVX_Data step_size_4; + step_size_4.data = SIMD_SET(step_size); + + float after_decay = 1.0f - _alpha * _weight_decay; + AVX_Data after_decay_4; + if (_weight_decay > 0) after_decay_4.data = SIMD_SET(after_decay); + bool use_weight_decay = (_weight_decay > 0); + + // Unscale (after FP32 promotion) only when combined_scale > 1. + bool need_unscale = (combined_scale > 1.0f); + AVX_Data unscale_factor; + if (need_unscale) { unscale_factor.data = SIMD_SET(1.0f / combined_scale); } + + new_rounded_size = ROUND_DOWN(_param_size, SIMD_WIDTH * span); + +#if defined(__linux__) && USE_HUGE_PAGE + if (new_rounded_size > 0) { + size_t page_size = 4096; + auto madvise_bytes = [&](size_t elem_size) { + return (_param_size * elem_size + page_size - 1) & ~(page_size - 1); + }; + size_t params_bytes = madvise_bytes(sizeof(float)); + size_t grad_bytes = madvise_bytes(sizeof(ds_grad_precision_t)); + size_t state_bytes = madvise_bytes(sizeof(ds_state_precision_t)); + void* params_aligned = (void*)((uintptr_t)_params_fp32 & ~(page_size - 1)); + madvise(params_aligned, params_bytes, MADV_HUGEPAGE); + madvise((void*)((uintptr_t)grads_half & ~(page_size - 1)), grad_bytes, MADV_HUGEPAGE); + madvise((void*)((uintptr_t)_exp_avg & ~(page_size - 1)), state_bytes, MADV_HUGEPAGE); + } +#endif + + ReflowCPUAffinity affinity; +#pragma omp parallel + { + affinity.apply(); +#pragma omp for schedule(static) nowait + for (size_t i = 0; i < new_rounded_size; i += SIMD_WIDTH * span) { + AVX_Data grad_4[span]; + reflow_simd_load(grad_4, grads_half + i); + if (need_unscale) { simd_mul(grad_4, grad_4, unscale_factor); } + AVX_Data momentum_4[span]; + reflow_simd_load(momentum_4, _exp_avg + i); + AVX_Data param_4[span]; + reflow_simd_load(param_4, _params_fp32 + i); + + AVX_Data tmp_4[span]; + simd_mul(tmp_4, momentum_4, betta1_4); + simd_fma(tmp_4, grad_4, betta1_minus1_4, tmp_4); + simd_and(tmp_4, tmp_4, neg1_4); + simd_xor(tmp_4, tmp_4, step_size_4); + if (use_weight_decay) { + simd_fma(param_4, param_4, after_decay_4, tmp_4); + } else { + simd_add(param_4, param_4, tmp_4); + } + + simd_mul(momentum_4, momentum_4, betta2_4); + simd_fma(momentum_4, grad_4, betta2_minus1_4, momentum_4); + + reflow_simd_store(_params_fp32 + i, param_4); + reflow_simd_store(_exp_avg + i, momentum_4); + } + } + + *rounded_size = new_rounded_size; +} + +// Step_AVX_FP16_HalfGrad: update params only, store to FP16/BF16 buffer (skips +// the FP32 master and state). This is the foreground Phase-1 BF16 producer. +template +void Reflow_Lion_Optimizer::Step_AVX_FP16_HalfGrad(size_t* rounded_size, + float* _params_fp32, + ds_grad_precision_t* grads_half, + ds_state_precision_t* _exp_avg, + size_t _param_size, + ds_store_precision_t* half_params, + float combined_scale) +{ + size_t new_rounded_size = 0; + + AVX_Data neg1_4; + neg1_4.data = SIMD_SET(-1.0f); + + AVX_Data betta1_4; + betta1_4.data = SIMD_SET(_betta1); + + float betta1_minus1 = 1 - _betta1; + AVX_Data betta1_minus1_4; + betta1_minus1_4.data = SIMD_SET(betta1_minus1); + + float step_size = -_alpha; + AVX_Data step_size_4; + step_size_4.data = SIMD_SET(step_size); + + float after_decay = 1.0f - _alpha * _weight_decay; + AVX_Data after_decay_4; + if (_weight_decay > 0) after_decay_4.data = SIMD_SET(after_decay); + bool use_weight_decay = (_weight_decay > 0); + + bool need_unscale = (combined_scale > 1.0f); + AVX_Data unscale_factor; + if (need_unscale) { unscale_factor.data = SIMD_SET(1.0f / combined_scale); } + + new_rounded_size = ROUND_DOWN(_param_size, SIMD_WIDTH * span); + +#if defined(__linux__) && USE_HUGE_PAGE + if (new_rounded_size > 0) { + size_t page_size = 4096; + auto madvise_bytes = [&](size_t elem_size) { + return (_param_size * elem_size + page_size - 1) & ~(page_size - 1); + }; + size_t params_bytes = madvise_bytes(sizeof(float)); + size_t grad_bytes = madvise_bytes(sizeof(ds_grad_precision_t)); + size_t state_bytes = madvise_bytes(sizeof(ds_state_precision_t)); + size_t store_bytes = madvise_bytes(sizeof(ds_store_precision_t)); + void* params_aligned = (void*)((uintptr_t)_params_fp32 & ~(page_size - 1)); + madvise(params_aligned, params_bytes, MADV_HUGEPAGE); + madvise((void*)((uintptr_t)grads_half & ~(page_size - 1)), grad_bytes, MADV_HUGEPAGE); + madvise((void*)((uintptr_t)_exp_avg & ~(page_size - 1)), state_bytes, MADV_HUGEPAGE); + madvise((void*)((uintptr_t)half_params & ~(page_size - 1)), store_bytes, MADV_HUGEPAGE); + } +#endif + + // Phase-1 reads the OLD momentum but never overwrites it, so the momentum EMA + // (m_new) is intentionally not computed here -- it is committed in Phase-2. + ReflowCPUAffinity affinity; +#pragma omp parallel + { + affinity.apply(); +#pragma omp for schedule(static) nowait + for (size_t i = 0; i < new_rounded_size; i += SIMD_WIDTH * span) { + AVX_Data grad_4[span]; + reflow_simd_load(grad_4, grads_half + i); + if (need_unscale) { simd_mul(grad_4, grad_4, unscale_factor); } + AVX_Data momentum_4[span]; + reflow_simd_load(momentum_4, _exp_avg + i); + AVX_Data param_4[span]; + reflow_simd_load(param_4, _params_fp32 + i); + + AVX_Data tmp_4[span]; + simd_mul(tmp_4, momentum_4, betta1_4); + simd_fma(tmp_4, grad_4, betta1_minus1_4, tmp_4); + simd_and(tmp_4, tmp_4, neg1_4); + simd_xor(tmp_4, tmp_4, step_size_4); + if (use_weight_decay) { + simd_fma(param_4, param_4, after_decay_4, tmp_4); + } else { + simd_add(param_4, param_4, tmp_4); + } + reflow_simd_store_stream(half_params + i, param_4); + } + } + + *rounded_size = new_rounded_size; +} + +#endif + +/* Reflow CPU-Lion entry points (own registry, isolated from any base CPU-Lion). + * The param/state split mirrors the Adam path: the params-halfgrad producer runs + * during backward and writes only the BF16/FP16 weights; the state-step commit + * runs on a background worker and writes the FP32 master + exp_avg. + */ +int reflow_create_lion_optimizer(int optimizer_id, + float alpha = 1e-3, + float betta1 = 0.9, + float betta2 = 0.999, + float weight_decay = 0, + bool should_log = false, + int num_threads = -1); + +// Half/BFloat16 gradient FP16/BF16-store path (params only, state skipped). +int reflow_ds_lion_step_params_halfgrad(int optimizer_id, + size_t step, + float lr, + float beta1, + float beta2, + float weight_decay, + torch::Tensor& params_fp32, + torch::Tensor& grads, + torch::Tensor& exp_avg, + torch::Tensor& half_params, + float combined_scale, + bool skip_increment_step = false); + +// Half/BFloat16 gradient params (FP32 master) + state commit. +int reflow_ds_lion_state_step_halfgrad(int optimizer_id, + size_t step, + float lr, + float beta1, + float beta2, + float weight_decay, + torch::Tensor& params_fp32, + torch::Tensor& grads, + torch::Tensor& exp_avg, + float combined_scale, + bool skip_increment_step = false); + +int reflow_destroy_lion_optimizer(int optimizer_id); diff --git a/csrc/includes/reflow_simd.h b/csrc/includes/reflow_simd.h new file mode 100644 index 000000000000..baf931a541e9 --- /dev/null +++ b/csrc/includes/reflow_simd.h @@ -0,0 +1,194 @@ +// SPDX-License-Identifier: Apache-2.0 +// DeepSpeed Team + +#pragma once + +#include "simd.h" + +#if defined(__AVX512__) +#define SIMD_STREAM_STORE(a, d) _mm512_stream_ps(a, d) +// Reflow BF16 aliases (the stock AVX-512 BF16 conversion works as-is). +#define SIMD_LOAD_BF16_REFLOW(x) load_16_bf16_as_f32(x) +#define SIMD_STORE_BF16_REFLOW(x, d) store_16_f32_as_bf16_nearest(d, x) + +static void stream_store_16_f32_as_bf16_nearest(__m512 v, void* data) +{ + __m512i u32 = readAs<__m512i>(&v); + + __m512i b = _mm512_srli_epi32(u32, 16); + __m512i lsb_mask = _mm512_set1_epi32(0x00000001); + __m512i c = _mm512_and_si512(b, lsb_mask); + __m512i bias_constant = _mm512_set1_epi32(0x00007fff); + __m512i rounding_bias = _mm512_add_epi32(c, bias_constant); + + __m512i d = _mm512_add_epi32(u32, rounding_bias); + __m512i e = _mm512_srli_epi32(d, 16); + __m256i non_nan_res = _mm512_cvtusepi32_epi16(e); + + __m512i mask_out_sign = _mm512_set1_epi32(0x7fffffff); + __m512i non_sign_bits = _mm512_and_si512(u32, mask_out_sign); + __m512i nan_threshold = _mm512_set1_epi32(0x7f800000); + __mmask16 nan_mask = _mm512_cmp_epi32_mask(non_sign_bits, nan_threshold, _MM_CMPINT_GT); + + __m256i nans = _mm256_set1_epi16(0x7fc0); + __m256i res = _mm256_mask_mov_epi16(non_nan_res, nan_mask, nans); + + _mm256_storeu_si256((__m256i*)data, res); +} +#define SIMD_STREAM_STORE_BF16(x, d) stream_store_16_f32_as_bf16_nearest(d, x) + +#define SIMD_STREAM_STORE_FP16(x, d) \ + _mm256_storeu_ps(x, _mm256_castsi256_ps(_mm512_cvtps_ph(d, _MM_FROUND_TO_NEAREST_INT))) + +#elif defined(__AVX256__) +#define SIMD_STREAM_STORE(a, d) _mm256_stream_ps(a, d) +static __m256 reflow_load_8_bf16_as_f32(const void* data) +{ + __m128i a = readAs<__m128i>(data); // 8 x uint16 (bf16) + __m256i b = _mm256_cvtepu16_epi32(a); // zero-extend to 8 x uint32 + __m256i c = _mm256_slli_epi32(b, 16); // bf16 -> fp32 bits (bf16 is the high 16 bits of fp32) + return readAs<__m256>(&c); +} + +/* Pack 8 uint32 (each already holding a value in its low 16 bits) down to 8 uint16. AVX2 lacks a + * direct 32->16 narrowing like AVX-512's _mm512_cvtusepi32_epi16, so use packus (which works + * per-128-bit lane) plus a 64-bit permute to gather the 8 results into the low 128 bits. + */ +static inline __m128i reflow_pack_low16_x8(__m256i x) +{ + __m256i p = _mm256_packus_epi32(x, x); + p = _mm256_permute4x64_epi64(p, 0xD8); + return _mm256_castsi256_si128(p); +} + +static void reflow_store_8_f32_as_bf16_nearest(__m256 v, void* data) +{ + __m256i u32 = readAs<__m256i>(&v); + // round to nearest, ties to even: rounding_bias = ((u32 >> 16) & 1) + 0x7fff + __m256i b = _mm256_srli_epi32(u32, 16); + __m256i lsb = _mm256_and_si256(b, _mm256_set1_epi32(0x00000001)); + __m256i rounding_bias = _mm256_add_epi32(lsb, _mm256_set1_epi32(0x00007fff)); + __m256i e = _mm256_srli_epi32(_mm256_add_epi32(u32, rounding_bias), 16); + __m128i non_nan_res = reflow_pack_low16_x8(e); + // NaN (exp all 1s, mantissa != 0): (u32 & 0x7fffffff) > 0x7f800000 -> emit a quiet NaN 0x7fc0 + __m256i non_sign = _mm256_and_si256(u32, _mm256_set1_epi32(0x7fffffff)); + __m256i nan_mask = _mm256_cmpgt_epi32(non_sign, _mm256_set1_epi32(0x7f800000)); + __m128i nan_mask16 = reflow_pack_low16_x8(_mm256_srli_epi32(nan_mask, 16)); + __m128i res = _mm_blendv_epi8(non_nan_res, _mm_set1_epi16((short)0x7fc0), nan_mask16); + writeAs(data, res); +} + +static void reflow_stream_store_8_f32_as_bf16_nearest(__m256 v, void* data) +{ + __m256i u32 = readAs<__m256i>(&v); + __m256i b = _mm256_srli_epi32(u32, 16); + __m256i lsb = _mm256_and_si256(b, _mm256_set1_epi32(0x00000001)); + __m256i rounding_bias = _mm256_add_epi32(lsb, _mm256_set1_epi32(0x00007fff)); + __m256i e = _mm256_srli_epi32(_mm256_add_epi32(u32, rounding_bias), 16); + __m128i non_nan_res = reflow_pack_low16_x8(e); + __m256i non_sign = _mm256_and_si256(u32, _mm256_set1_epi32(0x7fffffff)); + __m256i nan_mask = _mm256_cmpgt_epi32(non_sign, _mm256_set1_epi32(0x7f800000)); + __m128i nan_mask16 = reflow_pack_low16_x8(_mm256_srli_epi32(nan_mask, 16)); + __m128i res = _mm_blendv_epi8(non_nan_res, _mm_set1_epi16((short)0x7fc0), nan_mask16); + /* Match the AVX-512 BF16 path (stream_store_16_f32_as_bf16_nearest), which uses a regular + * store: a non-temporal _mm_stream_si128 here is weakly ordered and not fenced before the + * OMP workers' half_params writes are read, yielding non-deterministic output. + */ + _mm_storeu_si128((__m128i*)data, res); +} + +// Reflow-specific AVX-256 BF16 support (the stock SIMD_*_BF16 above are AVX-512-only). +#define SIMD_LOAD_BF16_REFLOW(x) reflow_load_8_bf16_as_f32(x) +#define SIMD_STORE_BF16_REFLOW(x, d) reflow_store_8_f32_as_bf16_nearest(d, x) +#define SIMD_STREAM_STORE_BF16(x, d) reflow_stream_store_8_f32_as_bf16_nearest(d, x) +#define SIMD_STREAM_STORE_FP16(x, d) \ + _mm_storeu_ps(x, _mm_castsi128_ps(_mm256_cvtps_ph(d, _MM_FROUND_TO_NEAREST_INT))) +#endif + +// Streaming stores and BF16 helpers are available only in the AVX builds. +#if defined(__AVX512__) or defined(__AVX256__) +// Non-temporal (streaming) store per dtype. +template +inline typename std::enable_if_t, void> reflow_simd_store_stream( + T* dst, + AVX_Data* src) +{ + size_t width = SIMD_WIDTH; +#pragma unroll + for (size_t i = 0; i < span; ++i) { SIMD_STREAM_STORE(dst + width * i, src[i].data); } +} + +template +inline typename std::enable_if_t, void> reflow_simd_store_stream( + T* dst, + AVX_Data* src) +{ + size_t width = SIMD_WIDTH; +#pragma unroll + for (size_t i = 0; i < span; ++i) { + SIMD_STREAM_STORE_FP16((float*)(dst + width * i), src[i].data); + } +} + +template +inline typename std::enable_if_t, void> reflow_simd_store_stream( + T* dst, + AVX_Data* src) +{ + size_t width = SIMD_WIDTH; +#pragma unroll + for (size_t i = 0; i < span; ++i) { + SIMD_STREAM_STORE_BF16((float*)(dst + width * i), src[i].data); + } +} + +template +inline typename std::enable_if_t && !std::is_same_v && + !std::is_same_v, + void> +reflow_simd_store_stream(T* dst, AVX_Data* src) +{ + simd_store(dst, src); +} +#endif + +#if defined(__AVX512__) or defined(__AVX256__) +// Reflow load/store: BF16 uses the Reflow BF16 path (incl. AVX-256); other dtypes delegate +// to the stock simd_load/simd_store so the standard DeepSpeedCPUAdam path is untouched. +template +inline typename std::enable_if_t, void> reflow_simd_store( + T* dst, + AVX_Data* src) +{ + size_t width = SIMD_WIDTH; +#pragma unroll + for (size_t i = 0; i < span; ++i) { + SIMD_STORE_BF16_REFLOW((float*)(dst + width * i), src[i].data); + } +} +template +inline typename std::enable_if_t, void> reflow_simd_store( + T* dst, + AVX_Data* src) +{ + simd_store(dst, src); +} +template +inline typename std::enable_if_t, void> reflow_simd_load( + AVX_Data* dst, + T* src) +{ + size_t width = SIMD_WIDTH; +#pragma unroll + for (size_t i = 0; i < span; ++i) { + dst[i].data = SIMD_LOAD_BF16_REFLOW((float*)(src + width * i)); + } +} +template +inline typename std::enable_if_t, void> reflow_simd_load( + AVX_Data* dst, + T* src) +{ + simd_load(dst, src); +} +#endif diff --git a/csrc/lion/cpu_lion.cpp b/csrc/lion/cpu_lion.cpp index c5cf3e9e9235..d34f790dcda2 100644 --- a/csrc/lion/cpu_lion.cpp +++ b/csrc/lion/cpu_lion.cpp @@ -4,10 +4,14 @@ // DeepSpeed Team #include "cpu_lion.h" +#include +#include "reflow_bindings.h" PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("lion_update", &ds_lion_step, "DeepSpeed CPU Lion update (C++)"); m.def("create_lion", &create_lion_optimizer, "DeepSpeed CPU Lion (C++)"); m.def("destroy_lion", &destroy_lion_optimizer, "DeepSpeed CPU Lion destroy (C++)"); + + bind_reflow_lion(m); } diff --git a/csrc/lion/reflow_cpu_lion_bindings.cpp b/csrc/lion/reflow_cpu_lion_bindings.cpp new file mode 100644 index 000000000000..bfe59da73e19 --- /dev/null +++ b/csrc/lion/reflow_cpu_lion_bindings.cpp @@ -0,0 +1,114 @@ +// SPDX-License-Identifier: Apache-2.0 +// DeepSpeed Team + +#include "reflow_bindings.h" +#include "reflow_cpu_lion.h" + +// Memory fence to enforce store ordering after non-temporal (streaming) stores. +static void reflow_lion_memory_fence() +{ +#if defined(__AVX512__) or defined(__AVX256__) + _mm_mfence(); +#endif +} + +static inline int reflow_ds_lion_step_params_halfgrad_gilfree(int optimizer_id, + size_t step, + float lr, + float beta1, + float beta2, + float weight_decay, + torch::Tensor& params_fp32, + torch::Tensor& grads, + torch::Tensor& exp_avg, + torch::Tensor& half_params, + float combined_scale, + bool skip_increment_step = false) +{ + pybind11::gil_scoped_release release; + return reflow_ds_lion_step_params_halfgrad(optimizer_id, + step, + lr, + beta1, + beta2, + weight_decay, + params_fp32, + grads, + exp_avg, + half_params, + combined_scale, + skip_increment_step); +} + +static inline int reflow_ds_lion_state_step_halfgrad_gilfree(int optimizer_id, + size_t step, + float lr, + float beta1, + float beta2, + float weight_decay, + torch::Tensor& params_fp32, + torch::Tensor& grads, + torch::Tensor& exp_avg, + float combined_scale, + bool skip_increment_step = false) +{ + pybind11::gil_scoped_release release; + return reflow_ds_lion_state_step_halfgrad(optimizer_id, + step, + lr, + beta1, + beta2, + weight_decay, + params_fp32, + grads, + exp_avg, + combined_scale, + skip_increment_step); +} + +void bind_reflow_lion(pybind11::module_& m) +{ + m.def("reflow_create_lion", + &reflow_create_lion_optimizer, + "Reflow CPU Lion create (C++)", + pybind11::arg("optimizer_id"), + pybind11::arg("alpha") = 1e-3, + pybind11::arg("betta1") = 0.9, + pybind11::arg("betta2") = 0.999, + pybind11::arg("weight_decay") = 0, + pybind11::arg("should_log") = false, + pybind11::arg("num_threads") = -1); + m.def("reflow_destroy_lion", &reflow_destroy_lion_optimizer, "Reflow CPU Lion destroy (C++)"); + m.def("reflow_lion_update_params_halfgrad", + &reflow_ds_lion_step_params_halfgrad_gilfree, + "Reflow CPU Lion update FP16 with half gradients, GIL-released (C++)", + pybind11::arg("optimizer_id"), + pybind11::arg("step"), + pybind11::arg("lr"), + pybind11::arg("beta1"), + pybind11::arg("beta2"), + pybind11::arg("weight_decay"), + pybind11::arg("params_fp32"), + pybind11::arg("grads"), + pybind11::arg("exp_avg"), + pybind11::arg("half_params"), + pybind11::arg("combined_scale"), + pybind11::arg("skip_increment_step") = false); + m.def("reflow_lion_update_state_halfgrad", + &reflow_ds_lion_state_step_halfgrad_gilfree, + "Reflow CPU Lion update state stream with half gradients, GIL-released (C++)", + pybind11::arg("optimizer_id"), + pybind11::arg("step"), + pybind11::arg("lr"), + pybind11::arg("beta1"), + pybind11::arg("beta2"), + pybind11::arg("weight_decay"), + pybind11::arg("params_fp32"), + pybind11::arg("grads"), + pybind11::arg("exp_avg"), + pybind11::arg("combined_scale"), + pybind11::arg("skip_increment_step") = false); + m.def("reflow_lion_memory_fence", + &reflow_lion_memory_fence, + "Reflow CPU Lion memory fence (C++)"); +} diff --git a/csrc/lion/reflow_cpu_lion_impl.cpp b/csrc/lion/reflow_cpu_lion_impl.cpp new file mode 100644 index 000000000000..c50f94a678a7 --- /dev/null +++ b/csrc/lion/reflow_cpu_lion_impl.cpp @@ -0,0 +1,459 @@ +// Copyright (c) Microsoft Corporation. +// SPDX-License-Identifier: Apache-2.0 + +// DeepSpeed Team + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "reflow_cpu_lion.h" + +#ifdef __linux__ +#include +#include +#endif + +using namespace std::string_literals; + +// Independent step counters for param vs. async-state updates. +struct ReflowLionOptimizerPair { + std::shared_ptr param_opt; + std::shared_ptr state_opt; + // Bucket workers share the optimizer scalars; keep their updates serialized. + std::shared_ptr param_opt_mutex; +}; +static std::unordered_map s_reflow_lion_optimizers; + +// Affinity-aware available-core count (falls back to omp_get_num_procs()). +static unsigned int reflow_lion_get_available_cpu_count() +{ +#ifdef __linux__ + cpu_set_t cpuset; + CPU_ZERO(&cpuset); + + if (sched_getaffinity(0, sizeof(cpu_set_t), &cpuset) == 0) { + unsigned int count = 0; + for (int i = 0; i < CPU_SETSIZE; i++) { + if (CPU_ISSET(i, &cpuset)) { count++; } + } + if (count > 0) { return count; } + } +#endif + return omp_get_num_procs(); +} + +// Non-positive thread counts use all cores available to this worker. +static unsigned int reflow_lion_resolve_omp_threads(int num_threads, unsigned int available) +{ + if (num_threads > 0) { return std::min(static_cast(num_threads), available); } + return available; +} + +// Half/BFloat16 gradient FP16/BF16-store path (params only, skips state). +template +void Reflow_Lion_Optimizer::Step_8_FP16_HalfGrad(float* _params_fp32, + ds_grad_precision_t* grads_half, + ds_state_precision_t* _exp_avg, + size_t _param_size, + ds_store_precision_t* half_params, + float combined_scale) +{ + size_t rounded_size = 0; +#if defined(__AVX512__) or defined(__AVX256__) + Step_AVX_FP16_HalfGrad<8, ds_store_precision_t, ds_grad_precision_t, ds_state_precision_t>( + &rounded_size, + _params_fp32, + grads_half, + _exp_avg, + _param_size, + half_params, + combined_scale); + // Narrow the SIMD span before handling the remaining scalar tail. + if (_param_size > rounded_size) { + size_t tail_rounded_size = 0; + Step_AVX_FP16_HalfGrad<4, ds_store_precision_t, ds_grad_precision_t, ds_state_precision_t>( + &tail_rounded_size, + _params_fp32 + rounded_size, + grads_half + rounded_size, + _exp_avg + rounded_size, + _param_size - rounded_size, + half_params + rounded_size, + combined_scale); + rounded_size += tail_rounded_size; + } + if (_param_size > rounded_size) { + size_t tail_rounded_size = 0; + Step_AVX_FP16_HalfGrad<1, ds_store_precision_t, ds_grad_precision_t, ds_state_precision_t>( + &tail_rounded_size, + _params_fp32 + rounded_size, + grads_half + rounded_size, + _exp_avg + rounded_size, + _param_size - rounded_size, + half_params + rounded_size, + combined_scale); + rounded_size += tail_rounded_size; + } +#endif + if (_param_size > rounded_size) { + float betta1_minus1 = 1 - _betta1; + float alpha = _alpha; + float after_decay = 1 - alpha * _weight_decay; + float unscale_factor = 1.0f / combined_scale; + + for (size_t t = rounded_size; t < _param_size; t += TILE) { + size_t copy_size = TILE; + if ((t + TILE) > _param_size) copy_size = _param_size - t; + size_t offset = copy_size + t; + ReflowCPUAffinity affinity; +#pragma omp parallel + { + affinity.apply(); +#pragma omp for schedule(static) nowait + for (size_t k = t; k < offset; k++) { + float grad = static_cast(grads_half[k]) * unscale_factor; + float param = _params_fp32[k]; + float momentum = static_cast(_exp_avg[k]); + float tmp = momentum * _betta1; + tmp = grad * betta1_minus1 + tmp; + tmp = -std::copysignf(alpha, tmp); + if (_weight_decay > 0) { + param = param * after_decay + tmp; + } else { + param = param + tmp; + } + // Store param to FP16/BF16 buffer only; the FP32 master and state are skipped. + half_params[k] = ds_store_precision_t(param); + } + } + } + } +} + +// Half/BFloat16 gradient params (FP32 master) + state commit. +template +void Reflow_Lion_Optimizer::Step_8_State_HalfGrad(float* _params_fp32, + ds_grad_precision_t* grads_half, + ds_state_precision_t* _exp_avg, + size_t _param_size, + float combined_scale) +{ + size_t rounded_size = 0; +#if defined(__AVX512__) or defined(__AVX256__) + Step_AVX_HalfGrad<8, ds_grad_precision_t, ds_state_precision_t>( + &rounded_size, _params_fp32, grads_half, _exp_avg, _param_size, combined_scale); + if (_param_size > rounded_size) { + size_t tail_rounded_size = 0; + Step_AVX_HalfGrad<4, ds_grad_precision_t, ds_state_precision_t>(&tail_rounded_size, + _params_fp32 + rounded_size, + grads_half + rounded_size, + _exp_avg + rounded_size, + _param_size - rounded_size, + combined_scale); + rounded_size += tail_rounded_size; + } + if (_param_size > rounded_size) { + size_t tail_rounded_size = 0; + Step_AVX_HalfGrad<1, ds_grad_precision_t, ds_state_precision_t>(&tail_rounded_size, + _params_fp32 + rounded_size, + grads_half + rounded_size, + _exp_avg + rounded_size, + _param_size - rounded_size, + combined_scale); + rounded_size += tail_rounded_size; + } +#endif + if (_param_size > rounded_size) { + float betta1_minus1 = 1 - _betta1; + float betta2_minus1 = 1 - _betta2; + float alpha = _alpha; + float after_decay = 1 - alpha * _weight_decay; + float unscale_factor = 1.0f / combined_scale; + + for (size_t t = rounded_size; t < _param_size; t += TILE) { + size_t copy_size = TILE; + if ((t + TILE) > _param_size) copy_size = _param_size - t; + size_t offset = copy_size + t; + ReflowCPUAffinity affinity; +#pragma omp parallel + { + affinity.apply(); +#pragma omp for schedule(static) nowait + for (size_t k = t; k < offset; k++) { + float grad = static_cast(grads_half[k]) * unscale_factor; + float param = _params_fp32[k]; + float momentum = static_cast(_exp_avg[k]); + float tmp = momentum * _betta1; + tmp = grad * betta1_minus1 + tmp; + tmp = -std::copysignf(alpha, tmp); + if (_weight_decay > 0) { + param = param * after_decay + tmp; + } else { + param = param + tmp; + } + momentum = momentum * _betta2; + momentum = grad * betta2_minus1 + momentum; + + _params_fp32[k] = param; + _exp_avg[k] = static_cast(momentum); + } + } + } + } +} + +int reflow_create_lion_optimizer(int optimizer_id, + float alpha, + float betta1, + float betta2, + float weight_decay, + bool should_log, + int num_threads) +{ + // The Reflow half-grad kernels exist only for AVX2/AVX-512; fail here instead of at the first + // step. +#if !(defined(__AVX512__) or defined(__AVX256__)) + throw std::runtime_error("Reflow Lion requires a CPU build with AVX2 or AVX-512 support"); +#endif + auto parameter_opt = + std::make_shared(alpha, betta1, betta2, weight_decay); + auto state_opt = std::make_shared(alpha, betta1, betta2, weight_decay); + parameter_opt->set_num_threads(num_threads); + state_opt->set_num_threads(num_threads); + s_reflow_lion_optimizers[optimizer_id] = + ReflowLionOptimizerPair{parameter_opt, state_opt, std::make_shared()}; + + if (should_log) { + std::string avx_type = ""; +#if defined(__AVX512__) + avx_type = "AVX512"; +#else + avx_type = "AVX2"; +#endif + + printf("Reflow Lion Optimizer #%d is created with %s arithmetic capability.\n", + optimizer_id, + avx_type.c_str()); + printf("Config: alpha=%f, betas=(%f, %f), weight_decay=%f\n", + alpha, + betta1, + betta2, + weight_decay); + } + + return 0; +} + +/* Half/BFloat16 gradient FP16-store path (params only, state skipped). + * params_fp32 stays FP32; the half_params buffer receives FP16/BF16. + */ +int reflow_ds_lion_step_params_halfgrad(int optimizer_id, + size_t step, + float lr, + float beta1, + float beta2, + float weight_decay, + torch::Tensor& params_fp32, + torch::Tensor& grads, + torch::Tensor& exp_avg, + torch::Tensor& half_params, + float combined_scale, + bool skip_increment_step) +{ + auto params_c = params_fp32.contiguous(); + auto grads_c = grads.contiguous(); + auto exp_avg_c = exp_avg.contiguous(); + auto half_params_c = half_params.contiguous(); + + const size_t param_size = params_c.numel(); + if (param_size == 0) { return 0; } + + c10::ScalarType param_type = at::typeMetaToScalarType(params_c.options().dtype()); + c10::ScalarType grad_type = at::typeMetaToScalarType(grads_c.options().dtype()); + c10::ScalarType state_type = at::typeMetaToScalarType(exp_avg_c.options().dtype()); + c10::ScalarType store_type = at::typeMetaToScalarType(half_params_c.options().dtype()); + + if (param_type != torch::kFloat32) { + throw std::runtime_error("reflow_ds_lion_step_params_halfgrad expects FP32 params tensor"); + } + if (grad_type != torch::kFloat16 && grad_type != torch::kBFloat16) { + throw std::runtime_error( + "reflow_ds_lion_step_params_halfgrad expects FP16 or BF16 gradient tensor"); + } + if (store_type != torch::kFloat16 && store_type != torch::kBFloat16) { + throw std::runtime_error( + "reflow_ds_lion_step_params_halfgrad expects FP16 or BF16 half_params tensor"); + } + + ReflowLionOptimizerPair& pair = s_reflow_lion_optimizers[optimizer_id]; + std::shared_ptr opt = pair.param_opt; + Reflow_Lion_Optimizer worker_opt; + // Snapshot this range's scalars under the lock so another group cannot change them + // while its SIMD kernel runs. The disjoint parameter buffers still run in parallel. + // Keep the mutex alive even if its registry entry is replaced. + std::shared_ptr opt_mutex = pair.param_opt_mutex; + { + std::lock_guard opt_lock(*opt_mutex); + opt->IncrementStep(step, beta1, beta2); + opt->update_state(lr, weight_decay); + worker_opt = *opt; + } + // Honor the worker's CPU affinity to avoid oversubscribing its pinned cores. + unsigned int reflow_total_cpus = reflow_lion_get_available_cpu_count(); + unsigned int reflow_max_omp_threads = + reflow_lion_resolve_omp_threads(worker_opt.get_num_threads(), reflow_total_cpus); + int reflow_original_omp_threads = omp_get_max_threads(); + omp_set_num_threads(reflow_max_omp_threads); +#if defined(__AVX512__) or defined(__AVX256__) + if (store_type == torch::kFloat16 && grad_type == torch::kFloat16 && + state_type == torch::kFloat32) { + worker_opt.Step_8_FP16_HalfGrad( + params_c.data_ptr(), + grads_c.data_ptr(), + exp_avg_c.data_ptr(), + param_size, + half_params_c.data_ptr(), + combined_scale); + } else if (store_type == torch::kFloat16 && grad_type == torch::kFloat16 && + state_type == torch::kFloat16) { + worker_opt.Step_8_FP16_HalfGrad( + params_c.data_ptr(), + grads_c.data_ptr(), + exp_avg_c.data_ptr(), + param_size, + half_params_c.data_ptr(), + combined_scale); + } else if (store_type == torch::kBFloat16 && grad_type == torch::kBFloat16 && + state_type == torch::kFloat32) { + worker_opt.Step_8_FP16_HalfGrad( + params_c.data_ptr(), + grads_c.data_ptr(), + exp_avg_c.data_ptr(), + param_size, + half_params_c.data_ptr(), + combined_scale); + } else if (store_type == torch::kBFloat16 && grad_type == torch::kBFloat16 && + state_type == torch::kBFloat16) { + worker_opt.Step_8_FP16_HalfGrad( + params_c.data_ptr(), + grads_c.data_ptr(), + exp_avg_c.data_ptr(), + param_size, + half_params_c.data_ptr(), + combined_scale); + } else +#endif + { + omp_set_num_threads(reflow_original_omp_threads); + throw std::runtime_error( + "reflow_ds_lion_step_params_halfgrad: unsupported combination of store/grad/state " + "dtypes"); + } + omp_set_num_threads(reflow_original_omp_threads); + return 0; +} + +// Half/BFloat16 gradient params (FP32 master) + state commit. +int reflow_ds_lion_state_step_halfgrad(int optimizer_id, + size_t step, + float lr, + float beta1, + float beta2, + float weight_decay, + torch::Tensor& params_fp32, + torch::Tensor& grads, + torch::Tensor& exp_avg, + float combined_scale, + bool skip_increment_step) +{ + unsigned int total_cpus = reflow_lion_get_available_cpu_count(); + int configured_num_threads = + s_reflow_lion_optimizers[optimizer_id].state_opt->get_num_threads(); + unsigned int max_omp_threads = + reflow_lion_resolve_omp_threads(configured_num_threads, total_cpus); + int original_num_threads = omp_get_max_threads(); + omp_set_num_threads(max_omp_threads); + + auto params_c = params_fp32.contiguous(); + auto grads_c = grads.contiguous(); + auto exp_avg_c = exp_avg.contiguous(); + + const size_t param_size = params_c.numel(); + if (param_size == 0) { + omp_set_num_threads(original_num_threads); + return 0; + } + + c10::ScalarType param_type = at::typeMetaToScalarType(params_c.options().dtype()); + c10::ScalarType grad_type = at::typeMetaToScalarType(grads_c.options().dtype()); + c10::ScalarType state_type = at::typeMetaToScalarType(exp_avg_c.options().dtype()); + + if (param_type != torch::kFloat32) { + omp_set_num_threads(original_num_threads); + throw std::runtime_error("reflow_ds_lion_state_step_halfgrad expects FP32 params tensor"); + } + if (grad_type != torch::kFloat16 && grad_type != torch::kBFloat16) { + omp_set_num_threads(original_num_threads); + throw std::runtime_error( + "reflow_ds_lion_state_step_halfgrad expects FP16 or BF16 gradient tensor"); + } + + std::shared_ptr opt = s_reflow_lion_optimizers[optimizer_id].state_opt; + if (!skip_increment_step) { + opt->IncrementStep(step, beta1, beta2); + opt->update_state(lr, weight_decay); + } + // state_opt keeps its default skip-store flags (false, false) -> commits master + momentum. +#if defined(__AVX512__) or defined(__AVX256__) + if (grad_type == torch::kFloat16 && state_type == torch::kFloat32) { + opt->Step_8_State_HalfGrad(params_c.data_ptr(), + grads_c.data_ptr(), + exp_avg_c.data_ptr(), + param_size, + combined_scale); + } else if (grad_type == torch::kFloat16 && state_type == torch::kFloat16) { + opt->Step_8_State_HalfGrad(params_c.data_ptr(), + grads_c.data_ptr(), + exp_avg_c.data_ptr(), + param_size, + combined_scale); + } else if (grad_type == torch::kBFloat16 && state_type == torch::kFloat32) { + opt->Step_8_State_HalfGrad(params_c.data_ptr(), + grads_c.data_ptr(), + exp_avg_c.data_ptr(), + param_size, + combined_scale); + } else if (grad_type == torch::kBFloat16 && state_type == torch::kBFloat16) { + opt->Step_8_State_HalfGrad( + params_c.data_ptr(), + grads_c.data_ptr(), + exp_avg_c.data_ptr(), + param_size, + combined_scale); + } else +#endif + { + omp_set_num_threads(original_num_threads); + throw std::runtime_error( + "reflow_ds_lion_state_step_halfgrad: unsupported combination of grad/state dtypes"); + } + omp_set_num_threads(original_num_threads); + return 0; +} + +int reflow_destroy_lion_optimizer(int optimizer_id) +{ + s_reflow_lion_optimizers.erase(optimizer_id); + + return 0; +} diff --git a/deepspeed/runtime/config.py b/deepspeed/runtime/config.py index 390a0be5c559..ecc0d12af104 100755 --- a/deepspeed/runtime/config.py +++ b/deepspeed/runtime/config.py @@ -692,6 +692,16 @@ def _do_error_check(self): raise ValueError(f"{GRADIENT_ALLREDUCE_OP}='sum' is not supported with ZenFlow") 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") + reflow_enabled = self.zero_config.reflow is not None + if reflow_enabled and self.compile_config.deepcompile: + # DeepCompile's ZeRO-3 backward reduces grads without partition_grads, which is where Reflow + # launches its bucketwise CPU optimizer, so the optimizer would never see those grads. + raise ValueError("Reflow optimizer offload is not supported with DeepCompile") + if reflow_enabled and self.optimizer_name == MUON_OPTIMIZER: + # Reflow's CPU step runs its Adam/Lion kernels on every subgroup, so Muon's orthogonalized update would + # be silently replaced by Adam. Supporting Muon in Reflow is future work. + raise ValueError("Reflow does not support the Muon optimizer yet; remove the 'reflow' block from " + "zero_optimization to use Muon with ZeRO-Offload") if self.float16_config.fp16_master_weights_and_grads: assert self.zero_enabled and self.zero_optimization_stage in ( diff --git a/deepspeed/runtime/engine.py b/deepspeed/runtime/engine.py index 3e230e061367..c3dd3f53d748 100644 --- a/deepspeed/runtime/engine.py +++ b/deepspeed/runtime/engine.py @@ -39,6 +39,7 @@ from deepspeed.runtime.zero.config import ZERO_OPTIMIZATION from deepspeed.runtime.zenflow.engine import (configure_zenflow, zenflow_step, is_zenflow_update_boundary, sync_zenflow_optimizer_lr) +from deepspeed.runtime.reflow import engine as reflow_engine from deepspeed.runtime.fp16.fused_optimizer import FP16_Optimizer from deepspeed.runtime.fp16.loss_scaler import LossScaleConfig, LossScaleProfile @@ -637,7 +638,8 @@ def __init__(self, self.tput_timer = ThroughputTimer(self._config.timers_config, batch_size=self.train_batch_size(), steps_per_output=self.steps_per_print(), - monitor_memory=False) + monitor_memory=False, + sync_current_stream=reflow_engine.reflow_enabled(self)) log_dist(f"DeepSpeed Flops Profiler Enabled: {self.flops_profiler_enabled()}", ranks=[0]) @@ -2326,6 +2328,9 @@ def _configure_optimizer(self, client_optimizer, model_parameters): basic_optimizer.param_groups[:] = [pg for pg in basic_optimizer.param_groups if len(pg["params"]) != 0] log_dist("Removing param_group that has no 'params' in the basic Optimizer", ranks=[0]) + # A client optimizer has to become the matching Reflow CPU optimizer; the config-built one already is one. + if reflow_engine.reflow_enabled(self): + basic_optimizer = reflow_engine.maybe_remap_client_optimizer(self, basic_optimizer) self._check_for_duplicates(basic_optimizer) @@ -2362,7 +2367,11 @@ def get_optimizer_configuration(self, optimizer_parameters, adam_w_mode, allow_l if self.zero_use_cpu_optimizer(): from deepspeed.ops.adam import DeepSpeedCPUAdam, ZenFlowCPUAdam - CPUAdam = ZenFlowCPUAdam if self.zenflow else DeepSpeedCPUAdam + use_reflow = reflow_engine.reflow_enabled(self) + if use_reflow: + CPUAdam = reflow_engine.cpu_adam_class() + else: + CPUAdam = ZenFlowCPUAdam if self.zenflow else DeepSpeedCPUAdam if self.bf16_optimizer_states(): if user_fp32_optimizer_states: @@ -2376,6 +2385,8 @@ def get_optimizer_configuration(self, optimizer_parameters, adam_w_mode, allow_l optimizer_kwargs = {'adamw_mode': adam_w_mode, 'fp32_optimizer_states': fp32_optimizer_states} if self.zenflow: optimizer_kwargs['overlap_step'] = self.overlap_step + if use_reflow: + optimizer_kwargs['num_threads'] = reflow_engine.reflow_num_threads(self) return CPUAdam, optimizer_kwargs try: @@ -2484,7 +2495,10 @@ def _configure_basic_optimizer(self, model_parameters): elif self.optimizer_name() == LION_OPTIMIZER: if self.zero_use_cpu_optimizer(): from deepspeed.ops.lion import DeepSpeedCPULion - optimizer = DeepSpeedCPULion(model_parameters, **optimizer_parameters) + if reflow_engine.reflow_enabled(self): + optimizer = reflow_engine.build_cpu_lion(self, model_parameters, optimizer_parameters) + else: + optimizer = DeepSpeedCPULion(model_parameters, **optimizer_parameters) else: from deepspeed.ops.lion import FusedLion optimizer = FusedLion(model_parameters, **optimizer_parameters) @@ -2721,8 +2735,12 @@ def _configure_zero_optimizer(self, optimizer): log_dist(f'Creating {model_dtype} ZeRO stage {zero_stage} optimizer', ranks=[0]) from deepspeed.runtime.zero.stage3 import DeepSpeedZeroOptimizer_Stage3 from deepspeed.runtime.superoffload.superoffload_stage3 import SuperOffloadOptimizer_Stage3 - Stage3ZeroOptimizer = DeepSpeedZeroOptimizer_Stage3 if not self.super_offload( - ) else SuperOffloadOptimizer_Stage3 + if self.super_offload(): + Stage3ZeroOptimizer = SuperOffloadOptimizer_Stage3 + elif reflow_engine.reflow_enabled(self): + Stage3ZeroOptimizer = reflow_engine.stage3_optimizer_class(self) + else: + Stage3ZeroOptimizer = DeepSpeedZeroOptimizer_Stage3 optimizer = Stage3ZeroOptimizer( self.module, optimizer, diff --git a/deepspeed/runtime/reflow/README.md b/deepspeed/runtime/reflow/README.md new file mode 100644 index 000000000000..cd2aeeb86551 --- /dev/null +++ b/deepspeed/runtime/reflow/README.md @@ -0,0 +1,304 @@ +# Reflow — asynchronous CPU-offload optimizer for ZeRO-3 + +Reflow is an asynchronous CPU-offload optimizer for ZeRO Stage 3, driven by `ReflowCPUAdam` (and +`ReflowCPULion`). Like ZeRO-Offload it keeps the optimizer state (Adam's `exp_avg`/`exp_avg_sq`, or +Lion's single `exp_avg`) and the FP32 master weights on the CPU, but instead of running the CPU +optimizer as a separate serial phase *after* backward, it hides almost all of that cost *inside* the +backward pass. The result is ZeRO-3 CPU offloading where the CPU optimizer is largely overlapped with +GPU compute and the inter-GPU gradient reduction. + +**Optimizer support:** Adam/AdamW (`ReflowCPUAdam`) and Lion (`ReflowCPULion`). Lion keeps a single +momentum tensor (`exp_avg`) — no second moment, no `eps`, no bias correction — so its offloaded state +is half of Adam's; everything else in the pipeline below is identical. + +This directory is the implementation. A fine-tuning example is planned for +[DeepSpeedExamples](https://github.com/deepspeedai/DeepSpeedExamples); until it lands, the tutorial +(`docs/_tutorials/reflow.md`) shows the configuration a training script needs. + +**Maintainer:** [@st-bang97](https://github.com/st-bang97) — please tag me on issues or questions about Reflow. + +--- + +## What Reflow adds to ZeRO-3 (the `reflow` block) + +A `reflow` block in `zero_optimization` turns on three cooperating behaviors: + +1. **`cpu_bucketwise` — per-bucket optimizer during backward.** + As each gradient bucket becomes ready during backward, the CPU-Adam update for that bucket is + submitted to a background worker immediately, rather than waiting for the whole backward to + finish. The CPU optimizer therefore overlaps the remaining backward compute and the inter-GPU + reduce-scatter. + +2. **`cpu_conversion` — half-precision gradient transfer.** + Gradients are copied to the CPU in their native FP16/BF16 precision and promoted to FP32 *inside* + the AVX CPU-Adam kernel. This halves the GPU→CPU traffic with no extra host-side cast, and removes + the CPU-side FP32 gradient buffer entirely — only the half-precision (BF16/FP16) gradient is kept + on the CPU — so CPU memory usage drops. + +3. **`async_state` — asynchronous state update.** + The foreground step only generates the new BF16/FP16 parameters (produced just in time for the + next step); updating the FP32 master parameters and the optimizer state (Adam's + `exp_avg`/`exp_avg_sq`, or Lion's `exp_avg`) is split off to a background CPU worker. That state + update runs after the gradient-clipping and FP16-overflow checks, so it can overlap the *next* + iteration's forward. + +A **NUMA-aware core binding** underlies all three: worker threads are pinned to the CPU cores local +to each GPU's NUMA node for higher CPU↔GPU bandwidth. + +--- + +## Per-iteration pipeline + +``` +backward: reduce bucket ──► D2H grad copy (half precision, copy_grad_stream) + └► submit per-bucket CPU-Adam to a worker + ├► worker: FP32-promote + generate updated FP16/BF16 params + └► worker: H2D copy updated FP16/BF16 weights (bucketwise_h2d_stream) +step(): drain bucket workers ─► FP16-overflow check ─► grad-norm / gradient clipping + └► submit the deferred FP32-master + exp_avg/exp_avg_sq update to the + async-state worker (the param generation already ran during + backward, so this is a thin tail) +next fwd: the async-state worker runs concurrently with the forward; the param all-gather reads the + already-updated GPU weights (with overlap_comm it waits on the bucketwise H2D writes, + wait_for_external_allgather_dependencies) +``` + +Streams: `copy_grad_stream` (D2H grads), `_bucketwise_h2d_stream` (H2D updated weights, least +priority so it never preempts compute), and the standard ZeRO-3 `reduce_and_partition_stream` / +`__allgather_stream`. The CPU side uses a `ThreadPoolExecutor` of bucketwise workers (each pinned to +a disjoint NUMA-local core slice) plus a single chained async-state worker. + +--- + +## Components + +| File | Responsibility | +|---|---| +| `reflow_stage3.py` | `ReflowOptimizer_Stage3` (ZeRO-3 subclass): the bucketwise pipeline, the grad-copy / H2D streams, the split `step()`, the worker pools, and the affinity wiring. | +| `reflow_cpu_adam.py` | `ReflowCPUAdam` (extends `DeepSpeedCPUAdam`): the half-grad / state-only / per-range Adam variants. Registers its native optimizer in a **separate** Reflow C++ registry with its own `opt_id` space, isolating it from any plain `DeepSpeedCPUAdam` in the process. | +| `reflow_cpu_lion.py` | `ReflowCPULion` (extends `DeepSpeedCPULion`): the same half-grad / state-only / per-range variants for Lion's single-momentum update. Its own Reflow C++ registry in the `cpu_lion` extension. | +| `reflow_utils.py` | `plan_cpu_core_layout()` — NUMA-aware affinity planning (reads each GPU's PCIe→NUMA node) — plus contiguous-range helpers for the bucketwise pipeline. Pure helpers, no optimizer state. | +| `csrc/adam/reflow_cpu_adam_impl.cpp`, `csrc/includes/reflow_cpu_adam.h` | The AVX CPU-Adam kernels and the `reflow_*` C++ entry points (half-grad param generation, half-grad state commit, and half-precision gradient accumulation). | +| `csrc/lion/reflow_cpu_lion_impl.cpp`, `csrc/includes/reflow_cpu_lion.h` | The matching AVX CPU-Lion kernels and `reflow_lion_*` C++ entry points (single-momentum, sign-based update). | +| `csrc/includes/reflow_cpu_affinity.h` | Applies each worker CPU mask to its retained OpenMP helper threads when the worker moves or the state commit widens for backward. | +| `csrc/includes/reflow_simd.h` | Reflow-only SIMD conversions and streaming stores, layered on the shared `simd.h`. | +| `csrc/adam/reflow_cpu_adam_bindings.cpp`, `csrc/lion/reflow_cpu_lion_bindings.cpp` | Reflow Python bindings and GIL-released worker wrappers, registered through `csrc/includes/reflow_bindings.h` in the existing CPU optimizer modules. | + +A client that passes a plain `DeepSpeedCPUAdam` / `DeepSpeedCPULion` is auto-remapped to +`ReflowCPUAdam` / `ReflowCPULion` when the `reflow` block is set (see +`engine._maybe_remap_to_reflow_cpu_optimizer`). PyTorch `Adam` and `AdamW` are also remapped. +Pass client LR schedulers as factories or configure them in DeepSpeed; a scheduler already bound +to the original optimizer cannot follow the remapping and is rejected. + +--- + +## Configuration + +```jsonc +"zero_optimization": { + "stage": 3, + "overlap_comm": true, // recommended: overlaps the grad reduce with backward + "reduce_bucket_size": 5e8, + "sub_group_size": 1e9, + "offload_optimizer": { + "device": "cpu", + "pin_memory": true + }, + // The block enables Reflow; {} runs with the defaults. Its options are NUMA / affinity tuning + // (recommended for best throughput): + "reflow": { + "enable_cpu_affinity": true, // restrict the main process to NUMA-local cores; workers are always pinned + "main_thread_cores": 2, // cores reserved for the forward/backward (main) thread + "bucketwise_cores_per_worker": 7, // cores per bucketwise CPU-Adam worker; worker count = + // (rank worker cores) / this value + "state_update_cores": 2 // cores for the background optimizer-state commit while it + // overlaps the next forward (default 2) + // "num_threads": // CPU-Adam threads (default: all available cores) + } + // optional: also offload PARAMETERS to CPU (orthogonal to Reflow; frees the per-rank param + // shard of training memory). See "Parameter offload" below. + // "offload_param": { "device": "cpu", "pin_memory": true } +} +``` + +Reflow keeps the optimizer state in CPU RAM (`offload_optimizer.device: "cpu"`). It is mutually +exclusive with `super_offload` and `zenflow` (the config validator raises a clear error otherwise; +see `config.reflow_compat_check`), and with DeepCompile, whose ZeRO-3 backward reduces gradients +without `partition_grads`, where Reflow launches its workers (rejected in `DeepSpeedConfig`). The +Muon optimizer is rejected too, from the config or as a client `MuonWithAuxAdam`: Reflow's CPU step +runs Adam/Lion kernels on every subgroup and would drop Muon's orthogonalized update. Muon support +needs to be implemented in the future. The +Reflow kernels need a CPU Adam/Lion build with AVX2 or AVX-512; other builds raise an error when the +optimizer is created. To fall back to plain ZeRO-Offload, drop the `reflow` block. + +Per-parameter ZeRO-3 partition groups (e.g. AutoEP expert parallelism) run, and the grad-norm +reduction follows each subgroup's partition and expert-parallel groups like the base optimizer, but +this combination is not validated and may produce wrong results; Reflow logs a warning when it sees +such parameters. + +Pick the core split for your CPU: with `C` cores visible per rank, reserve a few for the main thread +and give the rest to the workers (e.g. on a 9-core-per-rank box, `main_thread_cores: 2` + +`bucketwise_cores_per_worker: 7`). Launch with `deepspeed --bind_cores_to_rank` so each rank is +pinned to the cores physically attached to its GPU. + +By default, counts refer to logical CPUs in the rank's affinity mask. `main_thread_cores` excludes +that many CPU IDs from workers; SMT siblings remain available and the main thread is not pinned +to the reservation. The following options allow other placements without machine-specific CPU IDs: + +| Option | Default | Behavior | +|---|---|---| +| `main_thread_core_type` | `"logical"` | `"physical"` counts physical cores and reserves all their available SMT siblings. | +| `pin_main_thread` | `false` | Pins the initializing thread to the reserved main CPUs; `engine.destroy()` restores its original affinity. | +| `worker_core_type` | `"logical"` | `"physical"` uses one logical CPU per remaining physical core. | +| `bucketwise_cores_per_worker` | `8` | Maximum logical CPUs per bucketwise worker; the last mask within a NUMA node may be smaller. | +| `bucketwise_worker_affinity` | `"task"` | `"task"` assigns CPU masks round-robin; `"thread"` fixes each pool thread to a mask at startup, reducing migrations and preserving its OpenMP team placement. | +| `state_update_backward_cores` | `null` | Caps the number of worker CPU IDs used by the state commit during backward; `null` uses all worker CPUs. `state_update_cores` still controls its forward mask. | + +For example, this reserves one physical main core, uses its SMT siblings for the main thread, +and keeps optimizer pool threads on fixed CPU masks: + +```json +"reflow": { + "main_thread_cores": 1, + "main_thread_core_type": "physical", + "pin_main_thread": true, + "worker_core_type": "logical", + "bucketwise_cores_per_worker": 4, + "bucketwise_worker_affinity": "thread", + "state_update_cores": 4 +} +``` + +Physical placement requires readable Linux CPU topology. Automatic rank assignment keeps SMT +siblings together; an existing taskset/launcher affinity remains authoritative. Main reservations +are capped to leave a worker core, and physical main reservation raises an error if a rank has fewer +than two physical cores. Counts for worker masks and state commits remain logical CPU counts, even +when main reservations count physical cores. Tune these values for the workload and CPU topology. + +Reflow applies each worker's CPU mask to its retained OpenMP helpers, changing their affinity only +when their current mask differs. Its uniform SIMD loops use contiguous `schedule(static)` work +sharing, keeping the parallel-region join without an extra loop barrier. Gradient accumulation +also caps its team size to the worker mask and the caller's OpenMP thread limit. OpenMP waiting behavior +can be tuned before launching the process with `OMP_WAIT_POLICY=ACTIVE` or `PASSIVE`; Reflow does +not change the application's environment. `OMP_SCHEDULE` affects only `schedule(runtime)` loops, +so it does not override Reflow's static loops. See the [OpenMP scheduling specification](https://openmp.org/spec-html/5.0/openmpse49.html) +and [waiting policy](https://openmp.org/spec-html/5.0/openmpse55.html). + +--- + +## Parameter offload (`offload_param`) + +Reflow composes with ZeRO-3 parameter offload (`"offload_param": {"device": "cpu"}`) — the two are +orthogonal and no Reflow code change is needed. Reflow offloads the *optimizer*; `offload_param` +additionally keeps the *parameter* partitions on CPU, fetched per layer by the ZeRO-3 coordinator. +With it on, `fp16_partitioned_groups_flat` lives on CPU, so Reflow's post-step weight writeback (a +CPU→CPU copy into that very buffer) lands exactly where the coordinator H2D-gathers from. + +Measured against standard ZeRO-3 + `offload_param` (the baseline) on OPT-30B, steady-state training +GPU memory **matches the baseline** and drops by the per-rank parameter shard — ~7 GB/rank on 8 GPUs, +~27 GB on 2 GPUs, and ~55 GB on 1 GPU (where the whole model would otherwise stay resident). + +The saving is in the steady-state training footprint; the one-time full-parameter materialization +spike at init is unchanged (orthogonal to Reflow — use `zero.Init()` to avoid that). + +--- + +## Gradient buffers (double by default; single is not fully implemented) + +Each subgroup keeps a **double** half-precision grad buffer on the CPU: an active slot the next +backward writes into, and a pending slot the previous step's async state commit is still reading. +`step()` flips the two, so the background commit never sees gradients from a later iteration. This is +the default and the only fully supported path. + +`REFLOW_SINGLE_GRAD_BUFFER=1` enables a **single** grad buffer prototype that is not fully implemented +yet. With `offload_param: cpu`, one slot only duplicates the CPU parameter source, so the prototype +writes the updated FP16/BF16 params straight into that source and saves ~2 bytes/param. It has been +checked only with `offload_param: cpu` and `gradient_accumulation_steps: 1`; any other run (gradient +accumulation, params on GPU, NVMe offload) logs a warning and falls back to the double buffer. + +--- + +## Performance characteristics + +- **The optimizer is hidden in the backward.** On a saturated multi-GPU run the DeepSpeed `step` + timer is a few ms — the per-rank optimizer shard drains within the backward window. The backward + wall-clock is also shorter than plain ZeRO-Offload because the grad D2H offload overlaps it. +- **The forward parameter all-gather is the inherent ZeRO-3 cost**, not a Reflow cost. The forward + blocks gathering the partitioned parameters across GPUs (interconnect-bound); a plain ZeRO-Offload + run, and even a no-offload ZeRO-3 run, show the same forward fetch wait. Reflow does not add to it + and cannot remove it — it is the ZeRO-3 structural floor (and the first forward layers' weights are + finalized last, since backward runs in reverse, so there is no boundary window to prime them into). +- **Single-GPU is the stress case.** With one GPU the optimizer is the *full* (unpartitioned) model + and must hide inside a single backward, so the bucketwise CPU-Adam workers must run truly in + parallel across the NUMA-local cores (see the mutex note under Correctness). +- **The state commit narrows its cores while it overlaps the forward.** The previous step's + optimizer-state commit overlaps the forward, which is launch-bound on the main thread. Every busy + core lowers the turbo frequency the CPU allows, so a commit spread over all worker cores slowed the + forward (OPT-350m: ~25%, main core ~3.6 GHz vs ~4.2 GHz). The commit therefore runs in slices on + `state_update_cores` cores (default 2) until the next backward starts, then on every worker core, + so a large model's commit still finishes before the next `step()` waits on it. +- **Gradient clipping re-runs the update inside `step()`.** The bucketwise workers apply the update + during backward, before the global grad norm is known. When a step needs clipping + (`gradient_clipping > 0` and the grad norm exceeds it), the in-flight work is cancelled and every + range is recomputed with the clipped scale in `step()`, so that step pays the full optimizer cost. + DeepSpeed defaults `gradient_clipping` to `1.0`; set `"gradient_clipping": 0.0` when clipping is not + wanted. On OPT-350m with one RTX 5080, `step` took ~58 ms unclipped vs ~139 ms with every step clipped. + +Illustrative (opt-30B, B200): 8-GPU step ~5 ms with the optimizer hidden; 1-GPU optimizer-step tail +fell from ~1700 ms to ~120 ms once the bucketwise workers ran concurrently. + +--- + +## Correctness + +- **FP16 dynamic loss scaling**: an overflowing step is detected with an on-GPU `isfinite` scan over + the offloaded grads and discarded exactly like the standard optimizer — the FP32 master is + untouched and the GPU weights are regenerated from it. +- **Async grad-copy aliveness**: the D2H grad-copy source is recorded against `copy_grad_stream` + (`record_stream`) so the caching allocator cannot recycle it before the async copy runs (this was a + NaN source on large models). +- **Shared-scalar guard**: concurrent bucketwise workers share one `param_opt` per `opt_id`. + Each worker updates and copies its step and group hyperparameters under a short mutex, then runs + the SIMD kernel against that private snapshot. Disjoint parameter buffers still run concurrently, + even when optimizer groups use different learning rates or weight decay. +- **overlap_comm ordering**: with `overlap_comm: true` the next forward's all-gather runs on a + separate stream, so the all-gather stream is made to wait on the bucketwise H2D weight-copy events + (`wait_for_external_allgather_dependencies`), ordering the param reads after the H2D writes. +- **Checkpoints see the committed state**: a step's FP32 master and optimizer state are committed in + the background after `step()` returns, so `state_dict` / `load_state_dict` and the `safe_get_*` / + `safe_set_*` hp-param APIs wait for that commit first. Only these entry points wait; the training + step is unchanged. + +--- + +## Diagnostics / debug environment variables + +| Env var | Effect | +|---|---| +| `REFLOW_SINGLE_GRAD_BUFFER=1` | Use the single grad buffer prototype (not fully implemented; see "Gradient buffers"). Unsupported runs fall back to the double buffer with a warning. Default off (double buffer). | +| `DS_REFLOW_SYNC_H2D_BEFORE_FORWARD=0` | Skip the host sync on the bucketwise H2D weight copies in `step()`. The sync keeps the next forward's parameter all-gather from reading a partition before its write-back lands, so leave it on except for measurement. Default on. | + +--- + +## Design history (by theme) + +The implementation was built and hardened across many commits; the major themes: + +- **Bucketwise overlap** — run the CPU-Adam per gradient bucket during backward; decouple the + per-shard size from `reduce_bucket_size` (a ~50M-element cap) so subgroups flush to the worker + mid-backward instead of waiting for the whole reduce bucket. +- **Half-precision transfer & async state** — send grads to CPU in FP16/BF16 (promote in-kernel, so + there is no CPU-side FP32 grad buffer); the foreground only generates the new FP16/BF16 params + while the FP32-master + optimizer-state update runs on a background worker after the + clipping/overflow checks. +- **NUMA affinity** — bind the main thread and per-NUMA-node worker groups to GPU-local cores; pin + the main process to the full NUMA-local slice (not only the reserved main cores) so it does not + throttle the launch-bound forward. +- **Stream scheduling** — least-priority H2D stream (so weight copies never preempt compute); move + the top-of-step device sync after the CPU step setup; allow more in-flight reduce events; order + overlap_comm all-gathers after the H2D weight writes. +- **Concurrency** — narrow the param CPU-Adam mutex to the scalar update so the bucketwise workers + run concurrently across the rank's cores (the key to hiding the optimizer when the per-rank shard + is large, e.g. single-GPU). +- **Correctness & robustness** — FP16-overflow detect-and-discard; async grad-copy aliveness; + auto-remap a client `DeepSpeedCPUAdam` to `ReflowCPUAdam`; isolated C++ `opt_id` registry. diff --git a/deepspeed/runtime/reflow/__init__.py b/deepspeed/runtime/reflow/__init__.py new file mode 100644 index 000000000000..5f6ba651efb5 --- /dev/null +++ b/deepspeed/runtime/reflow/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) DeepSpeed Team. +# SPDX-License-Identifier: Apache-2.0 + +# DeepSpeed Team +"""Reflow: an asynchronous CPU-offload optimizer for ZeRO stage 3. + +See README.md in this directory for the design, and docs/_tutorials/reflow.md for how to enable it. + +Maintainer: @st-bang97 +""" diff --git a/deepspeed/runtime/reflow/engine.py b/deepspeed/runtime/reflow/engine.py new file mode 100644 index 000000000000..82596f03ad61 --- /dev/null +++ b/deepspeed/runtime/reflow/engine.py @@ -0,0 +1,106 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team +""" +Engine-side wiring for Reflow, kept out of deepspeed/runtime/engine.py. + +Each function takes the engine, so the engine only carries one call per decision point. +""" + +import functools +from typing import TYPE_CHECKING + +import torch + +from deepspeed.runtime.zero.utils import ZeRORuntimeException +from deepspeed.utils import log_dist + +if TYPE_CHECKING: + from deepspeed.runtime.engine import DeepSpeedEngine + + +def reflow_enabled(engine: "DeepSpeedEngine") -> bool: + """Whether this run uses Reflow: the `reflow` config block is set and ZenFlow is not.""" + if engine._config.zero_config.reflow is None: + return False + # The throughput timer is built before _configure_zenflow runs, so read the flag defensively. + return not getattr(engine, "zenflow", False) + + +def reflow_num_threads(engine: "DeepSpeedEngine"): + return engine._config.zero_config.reflow.num_threads + + +def stage3_optimizer_class(engine: "DeepSpeedEngine"): + """Reflow's ZeRO-3 subclass with its config bound, so the engine's Stage-3 call is the shared one.""" + from deepspeed.runtime.reflow.reflow_stage3 import ReflowOptimizer_Stage3 + return functools.partial(ReflowOptimizer_Stage3, reflow_config=engine._config.zero_config.reflow) + + +def cpu_adam_class(): + """Reflow's CPU-Adam subclass, with the async / cpu_conversion / bucketwise step kernels.""" + from deepspeed.runtime.reflow.reflow_cpu_adam import ReflowCPUAdam + return ReflowCPUAdam + + +def build_cpu_lion(engine: "DeepSpeedEngine", model_parameters, optimizer_parameters: dict): + """Reflow's CPU-Lion subclass, built over the client's Lion parameters.""" + from deepspeed.runtime.reflow.reflow_cpu_lion import ReflowCPULion + return ReflowCPULion(model_parameters, **optimizer_parameters, num_threads=reflow_num_threads(engine)) + + +def maybe_remap_client_optimizer(engine: "DeepSpeedEngine", optimizer): + """Reflow's ZeRO-3 optimizer requires a Reflow CPU optimizer subclass (ReflowCPUAdam or + ReflowCPULion). If a client passed a plain DeepSpeedCPUAdam / torch Adam(W) or a + DeepSpeedCPULion (the usual ZeRO-Offload pattern) instead, rebuild an equivalent Reflow + optimizer over the same param groups and hyperparameters so existing scripts work unchanged. + Returns the optimizer unchanged if it is already a Reflow CPU optimizer.""" + from deepspeed.runtime.reflow.reflow_cpu_adam import ReflowCPUAdam + from deepspeed.runtime.reflow.reflow_cpu_lion import ReflowCPULion + from deepspeed.ops.adam import DeepSpeedCPUAdam + from deepspeed.ops.lion import DeepSpeedCPULion + from deepspeed.runtime.zero.muon.muon_optimizer import MuonWithAuxAdam + if isinstance(optimizer, (ReflowCPUAdam, ReflowCPULion)): + return optimizer + if isinstance(optimizer, MuonWithAuxAdam): + # Its class name contains "Adam", so the remap below would rebuild it as ReflowCPUAdam and silently train + # every parameter with Adam. Supporting Muon in Reflow is future work. + raise ZeRORuntimeException("Reflow does not support the Muon optimizer yet; remove the 'reflow' block " + "from zero_optimization to use Muon with ZeRO-Offload") + optimizer_type = type(optimizer) + name = optimizer_type.__name__ + defaults = getattr(optimizer, "defaults", {}) + is_lion = optimizer_type is DeepSpeedCPULion + if optimizer_type not in (DeepSpeedCPUAdam, DeepSpeedCPULion, torch.optim.Adam, torch.optim.AdamW): + raise ZeRORuntimeException( + f"Reflow cannot remap the client optimizer {name} without changing its update rule. " + "Pass a DeepSpeedCPUAdam / torch AdamW / DeepSpeedCPULion, or set the optimizer in the " + "DeepSpeed config.") + scheduler = engine.client_lr_scheduler + if scheduler is not None and getattr(scheduler, "optimizer", None) is optimizer: + raise ZeRORuntimeException("Reflow cannot remap a client optimizer already bound to an LR scheduler. " + "Pass a scheduler factory or set the scheduler in the DeepSpeed config.") + if is_lion: + keep = ("lr", "betas", "weight_decay") + else: + keep = ("lr", "betas", "eps", "weight_decay", "bias_correction", "amsgrad") + param_groups = [{"params": g["params"], **{k: g[k] for k in keep if k in g}} for g in optimizer.param_groups] + if is_lion: + log_dist(f"Reflow enabled: remapping client optimizer {name} to ReflowCPULion", ranks=[0]) + return ReflowCPULion(param_groups, + lr=defaults.get("lr", 1e-3), + betas=defaults.get("betas", (0.9, 0.999)), + weight_decay=defaults.get("weight_decay", 0.0), + num_threads=reflow_num_threads(engine)) + adamw_mode = getattr(optimizer, "adam_w_mode", None) + if adamw_mode is None: + adamw_mode = optimizer_type is torch.optim.AdamW + log_dist(f"Reflow enabled: remapping client optimizer {name} to ReflowCPUAdam", ranks=[0]) + return ReflowCPUAdam(param_groups, + lr=defaults.get("lr", 1e-3), + betas=defaults.get("betas", (0.9, 0.999)), + eps=defaults.get("eps", 1e-8), + weight_decay=defaults.get("weight_decay", 0.0), + bias_correction=defaults.get("bias_correction", True), + amsgrad=defaults.get("amsgrad", False), + adamw_mode=bool(adamw_mode), + num_threads=reflow_num_threads(engine)) diff --git a/deepspeed/runtime/reflow/reflow_config.py b/deepspeed/runtime/reflow/reflow_config.py new file mode 100644 index 000000000000..bce76dbae5c1 --- /dev/null +++ b/deepspeed/runtime/reflow/reflow_config.py @@ -0,0 +1,47 @@ +# Copyright (c) DeepSpeed Team. +# SPDX-License-Identifier: Apache-2.0 + +# DeepSpeed Team + +from pydantic import Field +from typing import Literal, Optional + +from deepspeed.runtime.config_utils import DeepSpeedConfigModel + + +class ReflowConfig(DeepSpeedConfigModel): + """Configuration options for the Reflow asynchronous CPU-offload optimizer (ZeRO stage 3).""" + + num_threads: Optional[int] = Field(None, ge=1) + """Threads for the CPU optimizer update. ``None`` uses every core available to the rank.""" + + enable_cpu_affinity: bool = False + """Restrict the main process to its NUMA-local cores. Optimizer workers are always pinned.""" + + main_thread_cores: int = Field(3, ge=1) + """Cores reserved for the main thread; the rest go to the optimizer workers. + Worker placement uses this even when ``enable_cpu_affinity`` is false.""" + + main_thread_core_type: Literal["logical", "physical"] = "logical" + """Count main-thread reservations as logical CPUs or physical cores including their SMT siblings.""" + + pin_main_thread: bool = False + """Pin the initializing thread to the reserved main CPUs and restore its affinity on destroy.""" + + worker_core_type: Literal["logical", "physical"] = "logical" + """Use all worker CPU IDs, or one logical CPU per worker physical core.""" + + bucketwise_worker_affinity: Literal["task", "thread"] = "task" + """Choose a CPU mask for each task, or keep each pool thread on its initial mask.""" + + bucketwise_cores_per_worker: int = Field(8, ge=1) + """Cores per bucketwise optimizer worker. The worker count follows from the cores available + to the rank divided by this value.""" + + state_update_cores: int = Field(2, ge=1) + """Worker cores the background optimizer-state commit may use while it overlaps the next + forward. Every busy core lowers the turbo frequency the CPU allows, which slows the + launch-bound forward; once backward starts the commit uses every worker core.""" + + state_update_backward_cores: Optional[int] = Field(None, ge=1) + """Limit the state commit's backward CPU mask; ``None`` uses all worker CPUs.""" diff --git a/deepspeed/runtime/reflow/reflow_cpu_adam.py b/deepspeed/runtime/reflow/reflow_cpu_adam.py new file mode 100644 index 000000000000..58a2ca5d7c0c --- /dev/null +++ b/deepspeed/runtime/reflow/reflow_cpu_adam.py @@ -0,0 +1,182 @@ +# Copyright (c) DeepSpeed Team. +# SPDX-License-Identifier: Apache-2.0 + +# DeepSpeed Team +""" +Reflow CPU-Adam optimizer. + +ReflowCPUAdam extends :class:`DeepSpeedCPUAdam` with the additional CPU-Adam step +variants required by the Reflow async CPU-offload optimizer: + +* cpu_conversion: gradients arrive on CPU in half precision and are promoted to + FP32 inside the AVX kernel (the half-grad step methods). +* async_state: the parameter update and the optimizer-state (exp_avg/exp_avg_sq) + update are split into separate calls so the state update can run on a background + worker (``step_state_halfgrad``). +* cpu_bucketwise: per-element-range partial updates (the reflow_adam_update_params_halfgrad C++ + entry point) so the + optimizer can run on gradient buckets as they arrive during backward. + +It registers its native optimizer instance in a separate Reflow registry inside the +``cpu_adam`` C++ extension (the ``reflow_*`` entry points), with its own opt_id space. +This keeps its C++ state isolated from any :class:`DeepSpeedCPUAdam` instances running +in the same process. +""" + +import torch +from cpuinfo import get_cpu_info + +from deepspeed.utils import logger +from deepspeed.utils.logging import should_log_le +from deepspeed.ops.op_builder import CPUAdamBuilder +from deepspeed.ops.adam.cpu_adam import DeepSpeedCPUAdam + +_CPU_DEVICE = torch.device('cpu') + + +class ReflowCPUAdam(DeepSpeedCPUAdam): + optimizer_id = 0 + + def __init__(self, + model_params, + lr=1e-3, + bias_correction=True, + betas=(0.9, 0.999), + eps=1e-8, + weight_decay=0, + amsgrad=False, + adamw_mode=True, + fp32_optimizer_states=True, + num_threads=None): + """Reflow CPU Adam(W). + + Same arguments as :class:`DeepSpeedCPUAdam` plus: + + Arguments: + num_threads (int): number of CPU threads for the Adam update. ``None`` uses + all available cores. + """ + # Initialize torch.optim.Optimizer directly (rather than via DeepSpeedCPUAdam.__init__) + # and register a Reflow C++ optimizer in its own registry. This avoids registering a + # standard cpu_adam optimizer instance and keeps the native state isolated. + default_args = dict(lr=lr, + betas=betas, + eps=eps, + weight_decay=weight_decay, + bias_correction=bias_correction, + amsgrad=amsgrad) + super(DeepSpeedCPUAdam, self).__init__(model_params, default_args) + + cpu_info = get_cpu_info() + self.cpu_vendor = cpu_info["vendor_id_raw"].lower() if "vendor_id_raw" in cpu_info else "unknown" + if "amd" in self.cpu_vendor: + for group in self.param_groups: + for p in group['params']: + if p.dtype == torch.half: + logger.warning("FP16 params for ReflowCPUAdam may not work on AMD CPUs") + break + else: + continue + break + + self.opt_id = ReflowCPUAdam.optimizer_id + ReflowCPUAdam.optimizer_id = ReflowCPUAdam.optimizer_id + 1 + self.adam_w_mode = adamw_mode + self.fp32_optimizer_states = fp32_optimizer_states + # None means "use all available cores"; converted to -1 at call time. + self.num_threads = num_threads + + self.ds_opt_adam = CPUAdamBuilder().load() + num_threads = int(self.num_threads) if self.num_threads is not None else -1 + self.ds_opt_adam.reflow_create_adam(self.opt_id, lr, betas[0], betas[1], eps, weight_decay, adamw_mode, + should_log_le("info"), num_threads) + + def memory_fence(self): + """Flush the non-temporal (streaming) stores so updated params/state are globally visible + before a worker future completes. Called by the Reflow ZeRO-3 async-state worker, which + dispatches through this method to stay optimizer-agnostic (Adam vs Lion).""" + self.ds_opt_adam.reflow_adam_memory_fence() + + @classmethod + def bf16_accumulate(cls, dst, src): + """Accumulate half-precision gradients using AVX: ``dst += src``. + + Uses AVX512 for BF16 and AVX256/512 for FP16. Both tensors must be contiguous + and share the same dtype (BF16 or FP16). Used to accumulate gradients across micro-steps. + """ + if not hasattr(cls, '_cpu_adam_module'): + cls._cpu_adam_module = CPUAdamBuilder().load() + cls._cpu_adam_module.reflow_bf16_accumulate(dst, src) + + def __del__(self): + # Destroy the C++ object explicitly to avoid a leak when deepspeed.initialize + # is used multiple times in the same process (notebook or pytest worker). + module = getattr(self, 'ds_opt_adam', None) + opt_id = getattr(self, 'opt_id', None) + if module is not None and opt_id is not None: + try: + module.reflow_destroy_adam(opt_id) + except Exception: + pass + + def _ensure_param_state(self, p): + """Lazily create the optimizer state (step, exp_avg, exp_avg_sq) for a CPU param.""" + state = self.state[p] + if 'exp_avg' not in state or 'exp_avg_sq' not in state: + state.setdefault('step', 0) + state_dtype = torch.float if self.fp32_optimizer_states else p.dtype + if 'exp_avg' not in state: + state['exp_avg'] = torch.zeros_like(p.data, dtype=state_dtype, device=_CPU_DEVICE) + if 'exp_avg_sq' not in state: + state['exp_avg_sq'] = torch.zeros_like(p.data, dtype=state_dtype, device=_CPU_DEVICE) + return state + + @torch.no_grad() + def step_state_halfgrad(self, half_grad_buffers, combined_scale=1.0, element_range=None, group_hyperparams=None): + """Optimizer-state-only Adam step from half-precision gradients: update exp_avg/exp_avg_sq and + skip the param store. Runs on a background worker so it overlaps with the next param update. + + The param update runs first and has already advanced ``state['step']``; the state + optimizer must use the same step for bias correction, so we pass ``state['step']``. + + ``half_grad_buffers`` is indexed by param-group id. Only the group being committed has a buffer; the + other entries are ``None`` and those groups are skipped. + + ``element_range=(start, numel)`` commits only that slice of each flat param, so the caller can + change the worker's cores between slices. The kernel is element-wise, so slicing does not change + the result. + + ``group_hyperparams`` maps a param-group index to the hyperparameters captured when the step was + submitted. The commit runs after step() returns, when an LR scheduler may already have changed the + live group, so the captured values keep it on the step's own lr/betas/weight_decay. + """ + for group_id, group in enumerate(self.param_groups): + grad_buffer = half_grad_buffers[group_id] + if grad_buffer is None: + continue + hyperparams = group_hyperparams.get(group_id, group) if group_hyperparams else group + for p in group['params']: + assert p.device == _CPU_DEVICE, ( + f"CPUAdam param is on {p.device} and must be 'cpu', " + f"make sure you enabled 'offload_optimizer': 'cpu' in your ZeRO config.") + # The param update already advanced state['step']; the state optimizer reuses it + # for bias correction. + state = self._ensure_param_state(p) + + params = p.data + grad = grad_buffer + exp_avg = state['exp_avg'] + exp_avg_sq = state['exp_avg_sq'] + if element_range is not None: + start, numel = element_range + params = params.narrow(0, start, numel) + grad = grad.narrow(0, start, numel) + exp_avg = exp_avg.narrow(0, start, numel) + exp_avg_sq = exp_avg_sq.narrow(0, start, numel) + + beta1, beta2 = hyperparams['betas'] + self.ds_opt_adam.reflow_adam_update_state_halfgrad(self.opt_id, state['step'], hyperparams['lr'], + beta1, beta2, hyperparams['eps'], + hyperparams['weight_decay'], + hyperparams['bias_correction'], params, grad, + exp_avg, exp_avg_sq, combined_scale) diff --git a/deepspeed/runtime/reflow/reflow_cpu_lion.py b/deepspeed/runtime/reflow/reflow_cpu_lion.py new file mode 100644 index 000000000000..3e81a905d9b7 --- /dev/null +++ b/deepspeed/runtime/reflow/reflow_cpu_lion.py @@ -0,0 +1,157 @@ +# Copyright (c) DeepSpeed Team. +# SPDX-License-Identifier: Apache-2.0 + +# DeepSpeed Team +""" +Reflow CPU-Lion optimizer. + +ReflowCPULion extends :class:`DeepSpeedCPULion` with the additional CPU-Lion step +variants required by the Reflow async CPU-offload optimizer, mirroring +:class:`~deepspeed.runtime.reflow.reflow_cpu_adam.ReflowCPUAdam`: + +* cpu_conversion: gradients arrive on CPU in half precision and are promoted to + FP32 inside the AVX kernel (the half-grad step methods). +* async_state: the parameter update and the optimizer-state (exp_avg) update are + split into separate calls so the state update can run on a background worker + (``step_state_halfgrad``). +* cpu_bucketwise: per-element-range partial updates (the reflow_lion_update_params_halfgrad C++ + entry point) so the optimizer can run on gradient buckets as they arrive during backward. + +Lion keeps a single momentum tensor (``exp_avg``); there is no second moment, no +eps, and no bias correction, so the optimizer state is half the size of Adam's. + +It registers its native optimizer instance in a separate Reflow registry inside the +``cpu_lion`` C++ extension (the ``reflow_*`` entry points), with its own opt_id space. +This keeps its C++ state isolated from any :class:`DeepSpeedCPULion` instances running +in the same process. +""" + +import torch +from cpuinfo import get_cpu_info + +from deepspeed.utils import logger +from deepspeed.utils.logging import should_log_le +from deepspeed.ops.op_builder import CPULionBuilder +from deepspeed.ops.lion.cpu_lion import DeepSpeedCPULion + +_CPU_DEVICE = torch.device('cpu') + + +class ReflowCPULion(DeepSpeedCPULion): + optimizer_id = 0 + + def __init__(self, + model_params, + lr=1e-3, + betas=(0.9, 0.999), + weight_decay=0, + fp32_optimizer_states=True, + num_threads=None): + """Reflow CPU Lion. + + Same arguments as :class:`DeepSpeedCPULion` plus: + + Arguments: + num_threads (int): number of CPU threads for the Lion update. ``None`` uses + all available cores. + """ + # Initialize torch.optim.Optimizer directly (rather than via DeepSpeedCPULion.__init__) + # and register a Reflow C++ optimizer in its own registry. This avoids registering a + # standard cpu_lion optimizer instance and keeps the native state isolated. + default_args = dict(lr=lr, betas=betas, weight_decay=weight_decay) + super(DeepSpeedCPULion, self).__init__(model_params, default_args) + + cpu_info = get_cpu_info() + self.cpu_vendor = cpu_info["vendor_id_raw"].lower() if "vendor_id_raw" in cpu_info else "unknown" + if "amd" in self.cpu_vendor: + for group in self.param_groups: + for p in group['params']: + if p.dtype == torch.half: + logger.warning("FP16 params for ReflowCPULion may not work on AMD CPUs") + break + else: + continue + break + + self.opt_id = ReflowCPULion.optimizer_id + ReflowCPULion.optimizer_id = ReflowCPULion.optimizer_id + 1 + self.fp32_optimizer_states = fp32_optimizer_states + # None means "use all available cores"; converted to -1 at call time. + self.num_threads = num_threads + + self.ds_opt_lion = CPULionBuilder().load() + num_threads = int(self.num_threads) if self.num_threads is not None else -1 + self.ds_opt_lion.reflow_create_lion(self.opt_id, lr, betas[0], betas[1], weight_decay, should_log_le("info"), + num_threads) + + def __del__(self): + # Destroy the C++ object explicitly to avoid a leak when deepspeed.initialize + # is used multiple times in the same process (notebook or pytest worker). + module = getattr(self, 'ds_opt_lion', None) + opt_id = getattr(self, 'opt_id', None) + if module is not None and opt_id is not None: + try: + module.reflow_destroy_lion(opt_id) + except Exception: + pass + + def _ensure_param_state(self, p): + """Lazily create the optimizer state (step, exp_avg) for a CPU param. Lion keeps a single + momentum tensor -- there is no exp_avg_sq.""" + state = self.state[p] + if 'exp_avg' not in state: + state.setdefault('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=_CPU_DEVICE) + return state + + def memory_fence(self): + """Flush the non-temporal (streaming) stores so updated params/state are globally visible + before a worker future completes. Called by the Reflow ZeRO-3 async-state worker, which + dispatches through this method to stay optimizer-agnostic (Adam vs Lion).""" + self.ds_opt_lion.reflow_lion_memory_fence() + + @torch.no_grad() + def step_state_halfgrad(self, half_grad_buffers, combined_scale=1.0, element_range=None, group_hyperparams=None): + """Optimizer-state-only Lion step from half-precision gradients: commit the FP32 master + + exp_avg. Runs on a background worker so it overlaps with the next param update. + + The param update runs first and has already advanced ``state['step']``; the state update + reuses it for the shared step counter. + + ``half_grad_buffers`` is indexed by param-group id. Only the group being committed has a buffer; the + other entries are ``None`` and those groups are skipped. + + ``element_range=(start, numel)`` commits only that slice of each flat param, so the caller can + change the worker's cores between slices. The kernel is element-wise, so slicing does not change + the result. + + ``group_hyperparams`` maps a param-group index to the hyperparameters captured when the step was + submitted. The commit runs after step() returns, when an LR scheduler may already have changed the + live group, so the captured values keep it on the step's own lr/betas/weight_decay. + """ + for group_id, group in enumerate(self.param_groups): + grad_buffer = half_grad_buffers[group_id] + if grad_buffer is None: + continue + hyperparams = group_hyperparams.get(group_id, group) if group_hyperparams else group + for p in group['params']: + assert p.device == _CPU_DEVICE, ( + f"CPULion param is on {p.device} and must be 'cpu', " + f"make sure you enabled 'offload_optimizer': 'cpu' in your ZeRO config.") + # The param update already advanced state['step']; the state update reuses it. + state = self._ensure_param_state(p) + + params = p.data + grad = grad_buffer + exp_avg = state['exp_avg'] + if element_range is not None: + start, numel = element_range + params = params.narrow(0, start, numel) + grad = grad.narrow(0, start, numel) + exp_avg = exp_avg.narrow(0, start, numel) + + beta1, beta2 = hyperparams['betas'] + self.ds_opt_lion.reflow_lion_update_state_halfgrad(self.opt_id, state['step'], hyperparams['lr'], + beta1, beta2, hyperparams['weight_decay'], params, + grad, exp_avg, combined_scale) diff --git a/deepspeed/runtime/reflow/reflow_stage3.py b/deepspeed/runtime/reflow/reflow_stage3.py new file mode 100644 index 000000000000..6b2edd652fdf --- /dev/null +++ b/deepspeed/runtime/reflow/reflow_stage3.py @@ -0,0 +1,1697 @@ +# Copyright (c) DeepSpeed Team. +# SPDX-License-Identifier: Apache-2.0 + +# DeepSpeed Team + +import gc +import os +import threading +from concurrent.futures import ThreadPoolExecutor +from typing import Container, List + +import psutil +import torch + +import deepspeed.comm as dist +from deepspeed.accelerator import get_accelerator +from deepspeed.runtime.reflow.reflow_cpu_adam import ReflowCPUAdam +from deepspeed.runtime.reflow import reflow_utils +from deepspeed.runtime.swap_tensor.partitioned_param_swapper import PartitionedParamStatus +from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum, OffloadStateTypeEnum +from deepspeed.runtime.zero.partition_parameters import Parameter, Tensor +from deepspeed.runtime.zero.stage3 import DeepSpeedZeroOptimizer_Stage3, INIT_OPTIMIZER_TIMER +from deepspeed.runtime.utils import has_inf_or_nan, is_model_parallel_parameter, mask_nan_or_inf_with_val_inplace +from deepspeed.utils import logger +from deepspeed.utils.nvtx import instrument_w_nvtx + +_REFLOW_FLAT_GRAD_FREED_MSG = ("Reflow frees the flat grad buffer; {api} is not supported under reflow.") +_DEFAULT_BUCKETWISE_SHARD_ELEMS = 50000000 +_DEFAULT_BUCKETWISE_MIN_SUBMIT_ELEMS = 262144 +# A power of two, so every full slice is a whole number of SIMD blocks and the kernel's scalar tail is the same +# elements as in an unsliced call; the sliced commit stays bit-exact. +_STATE_COMMIT_SLICE_ELEMS = 1 << 25 + + +class ReflowOptimizer_Stage3(DeepSpeedZeroOptimizer_Stage3): + """ZeRO-3 optimizer subclass adding the Reflow async CPU-offload feature. + + Adds three behaviors to ZeRO-3 stage-3 offloading, driven by a + ``ReflowCPUAdam`` optimizer: + - async_state: split the parameter update from the optimizer-state update so the + state update runs on a background CPU worker thread. + - cpu_conversion: send FP16/BF16 grads to the CPU optimizer, which promotes them to + FP32 internally, avoiding an extra host-side cast. + - cpu_bucketwise: run the optimizer per gradient bucket as soon as it is ready + during backward, instead of once after backward completes. + + Half-precision (FP16/BF16) gradients are promoted to FP32 inside the + CPU-conversion kernel path, where they must be FP32 before the Adam update. + """ + + def __init__(self, module, init_optimizer, param_names, timers, ds_config, reflow_config, **kwargs): + self._reflow_config = reflow_config + # These attributes must exist before super().__init__ runs: the parent constructor + # calls _setup_for_real_optimizer / initialize_optimizer_states, which are overridden + # here and read these fields. + self._cpu_grad_double_buffers = [] + self._active_grad_buffer_idx = 0 + self._pending_grad_ready = False + self._last_state_update_future = None + self._pending_state_updates_by_subgroup = {} + self._state_commit_overlaps_forward = False + self._main_thread_affinity = None + # Prototype, not fully implemented; the double grad buffer is the default. With offload_param='cpu' one + # grad slot only duplicates fp16_partitioned_groups_flat, so this writes the FP16 params there and saves + # ~2 bytes/param. Read before super().__init__, whose initialize_optimizer_states sizes the buffers. + # Unsupported runs fall back with a warning (see _resolve_single_grad_buffer_eligibility). + self._single_grad_buffer = os.getenv("REFLOW_SINGLE_GRAD_BUFFER", "0") == "1" + + super().__init__(module, init_optimizer, param_names, timers, ds_config, **kwargs) + self._warn_per_param_partition_groups() + # FP16/BF16 grads go straight to the CPU optimizer, which promotes them to FP32 + # internally, so the accumulation dtype stays half here. + self.gradient_accumulation_dtype = self.dtype + # The CPU optimizer is submitted per bucket during backward, so blocking after the base default of two + # in-flight reduce events stalls the main thread that dispatches it. + self.max_param_reduce_events = max(self.max_param_reduce_events, 4) + # Dedicated GPU->CPU copy stream so grad copies overlap with reduction; on synchronized + # devices (no async streams) this is just the default stream. + self.copy_grad_stream = get_accelerator().Stream() if get_accelerator().is_synchronized_device() is False \ + else get_accelerator().default_stream() + + self._setup_async_state_executor() + # The stream-level waits in step() do not keep the next forward's all-gather from reading a partition + # before its H2D write-back lands; without this host sync OPT-30B showed loss spikes. Leave it on except + # for measurement. + self._sync_bucketwise_h2d_before_forward = os.getenv("DS_REFLOW_SYNC_H2D_BEFORE_FORWARD", + "1") not in ("0", "false", "off") + # Pending-range bookkeeping is sized to the number of fp16 groups, which only exist + # after super().__init__, so initialize it here. + num_groups = len(self.fp16_groups) + self._bucketwise_pending_ranges_by_group = [[] for _ in range(num_groups)] + self._bucketwise_pending_elems_by_group = [0] * num_groups + + @property + def _pending_grad_buffer_idx(self): + # Single-buffer mode keeps grads (and reads) in the lone slot 0; otherwise the pending + # double-buffer index is the complement of the active one. + if self._single_grad_buffer: + return 0 + return 1 - self._active_grad_buffer_idx + + # ------------------------------------------------------------------ # + # __init__ helpers + # ------------------------------------------------------------------ # + def _warn_per_param_partition_groups(self): + # The grad-norm reduction follows the base per-subgroup process groups, but the rest of the Reflow pipeline + # has only been validated with every subgroup partitioned over the data-parallel group. + for sub_group in self.fp16_groups: + for param in sub_group: + is_autoep_expert = getattr(param, "ds_zero_placement_family", None) == "autoep_expert" + has_own_partition_group = getattr(param, "ds_zero_partition_process_group", None) is not None + if is_autoep_expert or has_own_partition_group: + if dist.get_rank() == 0: + logger.warning("Reflow with per-parameter ZeRO-3 partition groups (e.g. AutoEP expert " + "parallelism) is not validated and may produce wrong results.") + return + + def _setup_async_state_executor(self): + self._reset_bucketwise_handles() + self._worker_cpu_affinity_mask = None + self._state_update_cpu_affinity_mask = None + + main_thread_cores = self.main_thread_cores + enable_cpu_affinity = self.enable_cpu_affinity + # Automatically find NUMA-local cores for this rank, then split them into a main-thread set + # and per-NUMA-node optimizer-worker groups (so workers never straddle a NUMA boundary). + total_cpus, available_cores, node_worker_groups, main_cores, worker_cores = \ + reflow_utils.plan_cpu_core_layout(main_thread_cores, self._reflow_config.main_thread_core_type, + self._reflow_config.worker_core_type) + self._worker_node_groups = node_worker_groups + + self._worker_cpu_affinity_mask = set(worker_cores) + # While the state commit overlaps the next forward it stays on a few worker cores, away from the + # main-thread cores at the front of the list: every busy core lowers the turbo frequency the CPU + # allows, which slows the launch-bound forward. See _state_commit_cpu_affinity_mask. + state_update_core_count = min(max(1, int(self.state_update_cores)), len(worker_cores)) + self._state_update_cpu_affinity_mask = set(worker_cores[-state_update_core_count:]) if worker_cores else None + backward_count = self._reflow_config.state_update_backward_cores + backward_cores = worker_cores[-backward_count:] if backward_count is not None else worker_cores + self._state_backward_cpu_affinity_mask = set(backward_cores) + + original_affinity = None + if self._reflow_config.pin_main_thread: + if not hasattr(os, 'sched_getaffinity') or not hasattr(os, 'sched_setaffinity'): + raise ValueError("Reflow pin_main_thread requires OS thread-affinity support") + original_affinity = (threading.get_native_id(), os.sched_getaffinity(0)) + + if enable_cpu_affinity and available_cores: + try: + # Keep the main process on the whole NUMA-local slice, not only main_thread_cores: the ZeRO-3 forward + # is bound by kernel launches from this thread. The workers still pin themselves to worker_cores. + psutil.Process().cpu_affinity(available_cores) + if dist.get_rank() == 0: + logger.info(f"CPU affinity: main process on {len(available_cores)} NUMA-local cores, " + f"{len(main_cores)} reserved from workers {sorted(main_cores)}") + except (AttributeError, OSError, psutil.AccessDenied) as e: + if dist.get_rank() == 0: + logger.warning(f"Failed to set main process CPU affinity: {e}") + + if original_affinity is not None: + os.sched_setaffinity(0, main_cores) + self._main_thread_affinity = original_affinity + + if dist.get_rank() == 0: + logger.info(f"Reflow NUMA-aware CPU allocation: {total_cpus} rank cores across " + f"{len(node_worker_groups)} NUMA worker group(s); " + f"{len(main_cores)} main-thread cores {sorted(main_cores)}, " + f"{len(worker_cores)} optimizer-worker cores {sorted(worker_cores)}" + f"{', affinity isolation ENABLED' if enable_cpu_affinity else ''}") + + self._state_update_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="reflow_state_update") + + self._setup_bucketwise_executors() + + def _setup_bucketwise_executors(self): + bucketwise_cores_per_worker = max(1, int(self.bucketwise_cores_per_worker)) + + try: + # Build one affinity mask per worker by chunking EACH NUMA node's worker cores + # separately, so a worker's cores never span two NUMA nodes. + node_groups = getattr(self, "_worker_node_groups", None) + if not node_groups: + fallback_cores = sorted(list( + self._worker_cpu_affinity_mask)) or reflow_utils.resolve_available_cores()[1] + node_groups = [fallback_cores] + + self._bucketwise_worker_cpu_affinity_masks = [] + for node_cores in node_groups: + for start_idx in range(0, len(node_cores), bucketwise_cores_per_worker): + chunk = node_cores[start_idx:start_idx + bucketwise_cores_per_worker] + if chunk: + self._bucketwise_worker_cpu_affinity_masks.append(set(chunk)) + if not self._bucketwise_worker_cpu_affinity_masks: + self._bucketwise_worker_cpu_affinity_masks = [set(sorted(self._worker_cpu_affinity_mask) or [0])] + + max_bucketwise_workers = len(self._bucketwise_worker_cpu_affinity_masks) + total_worker_cores = sum(len(node) for node in node_groups) + if dist.get_rank() == 0: + logger.info(f"Bucketwise worker configuration (NUMA-aware): {max_bucketwise_workers} workers " + f"across {len(node_groups)} NUMA node group(s), " + f"{bucketwise_cores_per_worker} cores per worker, " + f"total {total_worker_cores} worker cores") + except Exception as e: + max_bucketwise_workers = 1 + fallback_mask = self._worker_cpu_affinity_mask if self._worker_cpu_affinity_mask else {0} + self._bucketwise_worker_cpu_affinity_masks = [fallback_mask] + if dist.get_rank() == 0: + logger.warning(f"Failed to configure bucketwise worker cores, using default: {e}") + + initializer = None + if self._reflow_config.bucketwise_worker_affinity == "thread": + masks = iter(self._bucketwise_worker_cpu_affinity_masks) + initializer_lock = threading.Lock() + + def initializer(): + with initializer_lock: + mask = next(masks) + self._pin_current_thread(mask) + + self._bucketwise_update_executor = ThreadPoolExecutor(max_workers=max_bucketwise_workers, + thread_name_prefix="reflow_bucketwise_update", + initializer=initializer) + + def _submit_bucketwise_task(fn, *args, **kwargs): + if initializer is not None: + return self._bucketwise_update_executor.submit(fn, *args, **kwargs) + + # Select the mask only here: selecting again in a caller would skip masks in an even-sized pool. + worker_idx = self._bucketwise_worker_idx + self._bucketwise_worker_idx = (self._bucketwise_worker_idx + 1) % len( + self._bucketwise_worker_cpu_affinity_masks) + affinity_mask = self._bucketwise_worker_cpu_affinity_masks[worker_idx] + + def wrapped_fn(*a, **kw): + self._pin_current_thread(affinity_mask) + return fn(*a, **kw) + + return self._bucketwise_update_executor.submit(wrapped_fn, *args, **kwargs) + + self._bucketwise_update_submit = _submit_bucketwise_task + self._bucketwise_update_futures = [] + self._bucketwise_inflight_futures = [] + self._bucketwise_accumulation_futures = {} + # Use the default (lowest) stream priority so H2D weight copies never preempt compute. CUDA priorities + # are inverted: a negative priority would outrank the compute stream. + if get_accelerator().is_synchronized_device(): + self._bucketwise_h2d_stream = None + else: + self._bucketwise_h2d_stream = get_accelerator().Stream() + + # Run enqueue/merge/flush off the main thread. + self._bucketwise_enq_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="reflow_bucketwise_enq") + self._bucketwise_enq_submit = self._bucketwise_enq_executor.submit + + self._bucketwise_group_step_incremented = set() + self._bucketwise_group_target_step = {} + self._bucketwise_inflight_h2d_events = [] + self._bucketwise_cancel_version = 0 + # Cap the per-shard size at _DEFAULT_BUCKETWISE_SHARD_ELEMS (also the fallback when + # reduce_bucket_size is unset) so each subgroup flushes to the CPU-Adam worker partway through + # backward, overlapping the CPU optimizer, instead of waiting for the whole reduce bucket. + self._bucketwise_element_shard_size = min(getattr(self, 'reduce_bucket_size', _DEFAULT_BUCKETWISE_SHARD_ELEMS), + _DEFAULT_BUCKETWISE_SHARD_ELEMS) + self._bucketwise_min_submit_range_elems = _DEFAULT_BUCKETWISE_MIN_SUBMIT_ELEMS + self._bucketwise_enqueue_lock = threading.Lock() + self._bucketwise_pending_events = {} + # First real (non-cancel) error raised by a bucketwise worker this iteration; step() + # all-reduces a flag derived from it and re-raises so the step aborts on every rank. + self._bucketwise_worker_error = None + self._bucketwise_error_flag = None # preallocated device flag for the per-step error all-reduce + + def _reset_bucketwise_handles(self): + self._bucketwise_update_executor = None + self._bucketwise_update_submit = None + self._bucketwise_update_futures = None + self._bucketwise_inflight_futures = None + self._bucketwise_worker_cpu_affinity_masks = None + self._worker_node_groups = None + self._bucketwise_worker_idx = 0 + self._bucketwise_h2d_stream = None + self._bucketwise_enq_executor = None + self._bucketwise_enq_submit = None + + def destroy(self): + """ + Drain any background work before shutting the pools down. An undrained bucketwise/state + worker can otherwise race ReflowCPUAdam.__del__ -> reflow_destroy_adam (use-after-free) + on an explicit mid-process engine.destroy(). Cancel inflight work first so drains return + quickly, then wait on the existing drain helpers. This must run before super().destroy(), + which unpins the offloaded optimizer states the workers are still writing. + """ + self._bucketwise_cancel_version = getattr(self, '_bucketwise_cancel_version', 0) + 1 + for drain in (self._wait_for_accum_gradient, self._wait_for_pending_state_updates, + self._bucketwise_wait_inflight_updates): + try: + drain() + except Exception: + pass + for attr in ("_bucketwise_enq_executor", "_bucketwise_update_executor", "_state_update_executor"): + executor = getattr(self, attr, None) + if executor is not None: + try: + executor.shutdown(wait=True) + except Exception: + pass + # The base _unpin_offload_buffers does not know Reflow's half-precision grad buffers; under the native + # pinning backend they would otherwise stay page-locked after destroy. Safe now that no worker uses them. + # The native unpin frees the memory, so drop the references too. + for grad_buffers in getattr(self, "_cpu_grad_double_buffers", None) or []: + for grad_buffer in grad_buffers or []: + if grad_buffer is not None and grad_buffer.device.type == 'cpu': + get_accelerator().unpin_memory(grad_buffer) + self._cpu_grad_double_buffers = [] + try: + super().destroy() + finally: + if self._main_thread_affinity is not None: + thread_id, cpus = self._main_thread_affinity + self._main_thread_affinity = None + os.sched_setaffinity(thread_id, cpus) + + # ------------------------------------------------------------------ # + # offload / partition setup + # ------------------------------------------------------------------ # + def _configure_offloading(self, offload_optimizer_config, offload_param_config): + super()._configure_offloading(offload_optimizer_config, offload_param_config) + assert self.offload_optimizer, "Reflow requires optimizer offload (offload_optimizer device='cpu' or 'nvme')" + # With NVMe optimizer offload, each subgroup's state is swapped around its CPU step in step() on one + # thread, because the partitioned optimizer swapper is not thread-safe. Gradients stay in CPU memory. + self.bucketwise_cores_per_worker = self._reflow_config.bucketwise_cores_per_worker + self.enable_cpu_affinity = self._reflow_config.enable_cpu_affinity + self.main_thread_cores = self._reflow_config.main_thread_cores + self.state_update_cores = self._reflow_config.state_update_cores + + def _setup_for_real_optimizer(self): + # cpu_bucketwise stores gradients exclusively in _cpu_grad_double_buffers, so the + # large flat grad buffer (grad_partitions_flat_buffer) is wasted memory here. The + # parent setup unconditionally allocates it, so free it (and its pinned backing) to + # reclaim ~2 bytes/param of CPU memory in the bucketwise case. + super()._setup_for_real_optimizer() + self.grad_partitions_flat_buffer = None + # GPU-side inf/nan accumulator for the offloaded grads, since the flat buffer that the base + # has_overflow scans is freed above (lazily created on the grad device in partition_grads). + self._reflow_grad_overflow = None + # Clear the name-mangled __param_id_to_grad_partition dict so the narrow() views into + # the buffer freed above are dropped and its storage can actually be reclaimed. + self._DeepSpeedZeroOptimizer_Stage3__param_id_to_grad_partition = {} + # The parent pins grad_partitions_flat_buffer, so dropping the references above only returns + # the block to torch's pinned-host caching allocator, which keeps the physical memory resident + # (the one large block is never reused by the smaller per-subgroup bucketwise buffers). Empty + # the host cache so the ~2 bytes/param of pinned memory is actually returned to the OS. + gc.collect() + if hasattr(torch._C, "_host_emptyCache"): + torch._C._host_emptyCache() + + def _pin_current_thread(self, cpu_affinity_mask): + if cpu_affinity_mask is None: + return + try: + if hasattr(os, 'sched_setaffinity'): + os.sched_setaffinity(0, cpu_affinity_mask) + except (OSError, AttributeError): + pass + + def _drain_update_futures_collecting_h2d_events(self, futures): + for f in futures: + try: + ev = f.result() + if ev is not None: + self._bucketwise_inflight_h2d_events.append(ev) + except Exception: + pass + + def _coalesce_bucketwise_h2d_events(self): + """Return one event covering all pending bucketwise H2D copies.""" + events = [ev for ev in self._bucketwise_inflight_h2d_events if ev is not None] + self._bucketwise_inflight_h2d_events.clear() + if len(events) <= 1 or get_accelerator().is_synchronized_device(): + return events + + stream = getattr(self, "_bucketwise_h2d_stream", None) + if stream is None: + return events + + with get_accelerator().stream(stream): + barrier = get_accelerator().Event() + barrier.record(stream) + return [barrier] + + def _get_enqueue_lock(self): + return self._bucketwise_enqueue_lock + + def _record_bucketwise_worker_error(self, exc): + # Record the first real (non-cancel) bucketwise worker failure under the shared enqueue + # lock; step() reads it to abort deterministically. Keep only the first so the original + # cause survives later cascading failures. + with self._get_enqueue_lock(): + if self._bucketwise_worker_error is None: + self._bucketwise_worker_error = exc + + def _check_bucketwise_worker_error(self): + # Abort the step deterministically on every rank if any rank's bucketwise worker hit a real + # error. A kernel/OOM failure may occur on only some ranks, so all-reduce a flag (MAX) and + # raise everywhere; a rank that saw the actual exception re-raises it, the rest raise a + # generic RuntimeError. This is a no-op (flag stays 0) on the happy path. + local_error = self._bucketwise_worker_error + # With one rank there is no remote worker error to collect, so avoid a device sync. + if dist.get_world_size() == 1: + if local_error is not None: + raise local_error + return + # Reuse a preallocated 1-element flag instead of allocating a new device tensor every step + # on this foreground collective path. + error_flag = self._bucketwise_error_flag + if error_flag is None: + error_flag = get_accelerator().ByteTensor([0]) + self._bucketwise_error_flag = error_flag + error_flag.fill_(1 if local_error is not None else 0) + dist.all_reduce(error_flag, op=dist.ReduceOp.MAX, group=self.dp_process_group) + self._model_parallel_all_reduce(tensor=error_flag, op=dist.ReduceOp.MAX) + if error_flag[0].item() == 0: + return + if local_error is not None: + raise local_error + raise RuntimeError("Reflow bucketwise worker failed on another rank; aborting step on all ranks") + + # ------------------------------------------------------------------ # + # partitioned param swap-out / CPU fp16 buffer sync + # ------------------------------------------------------------------ # + def _partitioned_params_swap_out(self, i, use_updated_weights=False): + offset = 0 + fp32_param = self.fp32_partitioned_groups_flat[i] + assert fp32_param is not None, f'fp32 parameters of sub_group {i} is None' + # Post-step, the CPU half_params buffer holds the freshly updated FP16/BF16 weights, so swap + # those out directly (a byte copy into the FP16 swap pool, avoiding an FP32->FP16 re-cast). + # At init the buffer is still torch.zeros, so callers there pass use_updated_weights=False to + # swap the pretrained FP32 master instead (cast to FP16 in the pool, like the base optimizer). + half_param_src = None + if use_updated_weights: + try: + if i < len(self._cpu_grad_double_buffers) and self._cpu_grad_double_buffers[i] is not None: + half_param_src = self._cpu_grad_double_buffers[i][self._pending_grad_buffer_idx] + except Exception: + half_param_src = None + + swap_fp16_params = [] + swap_fp32_params = [] + for param, partitioned_param in zip(self.fp16_groups[i], self.fp16_partitioned_groups[i]): + if half_param_src is not None: + src = half_param_src.narrow(0, offset, partitioned_param.ds_numel) + else: + src = fp32_param.narrow(0, offset, partitioned_param.ds_numel) + if partitioned_param.status == PartitionedParamStatus.AVAILABLE: + partitioned_param.data.copy_(src.data) + else: + swap_fp32_params.append(src) + swap_fp16_params.append(param) + offset += partitioned_param.ds_numel + + if len(swap_fp16_params): + swap_fp16_params[0].nvme_swapper.swap_out_partitioned_params(dst_fp16_params=swap_fp16_params, + src_fp32_params=swap_fp32_params) + + # ------------------------------------------------------------------ # + # optimizer state init (double-buffered CPU grad buffers) + # ------------------------------------------------------------------ # + def _resolve_single_grad_buffer_eligibility(self): + """When REFLOW_SINGLE_GRAD_BUFFER=1 is set, keep the single-slot optimization only on runs it can + serve correctly; otherwise fall back to the default double-buffer path (disable it) with a one-time + warning instead of failing. The single slot folds the FP16 param output into the CPU param source + (fp16_partitioned_groups_flat), so it is valid only with: CPU-offloaded params (fp16_flat is a + real CPU tensor the CPU kernel writes), no NVMe-swapped subgroup (those keep the 2-slot path), and + gradient_accumulation_steps == 1 (TODO: the accumulation path still needs the second slot as a + per-chunk scratch).""" + reason = None + gradient_accumulation_steps = self.gradient_accumulation_steps + if callable(gradient_accumulation_steps): + gradient_accumulation_steps = gradient_accumulation_steps() + if gradient_accumulation_steps != 1: + reason = f"gradient_accumulation_steps={gradient_accumulation_steps} != 1 (TODO: not supported yet)" + elif not self.offload_param: + reason = "offload_param is not enabled (the FP16 param source is on GPU, not a CPU flat buffer)" + else: + for sub_group_id in range(len(self.fp16_groups)): + fp16_flat = self.fp16_partitioned_groups_flat[sub_group_id] + if self._swappable_optimizer_subgroup(sub_group_id): + reason = f"subgroup {sub_group_id} uses NVMe optimizer offload" + elif fp16_flat is None: + reason = f"subgroup {sub_group_id} has no CPU param flat buffer (NVMe-swapped params)" + elif fp16_flat.device.type != 'cpu': + reason = f"subgroup {sub_group_id} param flat buffer is on {fp16_flat.device}, not CPU" + elif self.subgroup_to_device[sub_group_id] != 'cpu': + reason = (f"subgroup {sub_group_id} grad buffer maps to " + f"{self.subgroup_to_device[sub_group_id]}, not CPU") + if reason is not None: + break + if reason is not None: + if dist.get_rank() == 0: + logger.warning(f"REFLOW_SINGLE_GRAD_BUFFER=1 ignored ({reason}); using the default " + f"double-buffer path.") + self._single_grad_buffer = False + + def initialize_optimizer_states(self): + timer_names = set() + + is_adagrad = isinstance(self.optimizer, torch.optim.Adagrad) + + if self.swap_optimizer: + self.optimizer_swapper.init_timers() + + timer_names.add(INIT_OPTIMIZER_TIMER) + self.timers(INIT_OPTIMIZER_TIMER).start() + + self._cpu_grad_double_buffers = [] + self._pending_grad_ready = False + + if self._single_grad_buffer: + self._resolve_single_grad_buffer_eligibility() + + for i, group in enumerate(self.fp16_groups): + swappable_optimizer_subgroup = self._swappable_optimizer_subgroup(i) + swappable_param_subgroup = self.fp16_partitioned_groups_flat[i] is None + + num_elements = int(self.fp16_partitioned_groups_flat_numel[i]) + + if swappable_optimizer_subgroup: + self._optimizer_states_and_gradient_swap_in(i, timer_names) + # Bootstrap the lazy exp_avg/exp_avg_sq (zeros) NOW, before the init swap-out below + # registers this subgroup's state in the swap pool. Otherwise the first bucketwise + # flush creates them outside the pool, the swap-out cannot capture them, and the next + # swap-in reads uninitialized state -> the CPU-Adam produces NaN weights. + self.optimizer._ensure_param_state(self.fp32_partitioned_groups_flat[i]) + if self.use_muon and self.sub_groups_using_muon[i] and not self.save_muon_momentum_buffer_in_memory: + if "momentum_buffer" not in self.optimizer.state.get(self.fp32_partitioned_groups_flat[i], {}): + self._create_momentum_buffer(num_elements, i, self.fp32_partitioned_groups_flat[i].ds_id) + # Store grads in half precision for the bucketwise CPU-Adam (the kernel promotes to FP32). + # NVMe-optimizer subgroups use the same CPU half buffer for the reduced grad -- only the + # optimizer STATE is swapped to disk, never the gradient, so they need this buffer too. + grad_dtype = self.dtype + grad_buffers = [] + # Single-buffer mode allocates one slot (kept as a length-1 list so [0] indexing works); + # the param output is written into fp16_flat instead of a second slot. + num_grad_slots = 1 if self._single_grad_buffer else 2 + for _ in range(num_grad_slots): + subgroup_gradient_buffer = torch.zeros(num_elements, + dtype=grad_dtype, + device=self.subgroup_to_device[i]) + if self.offload_optimizer_pin_memory and self.subgroup_to_device[i] == 'cpu': + subgroup_gradient_buffer = get_accelerator().pin_memory(subgroup_gradient_buffer) + grad_buffers.append(subgroup_gradient_buffer) + self._cpu_grad_double_buffers.append(grad_buffers) + # The half-precision grad dtype differs from the FP32 param, so leave .grad unset; + # the kernels read the grad double-buffer directly. + self.fp32_partitioned_groups_flat[i].grad = None + + if swappable_param_subgroup: + self._partitioned_params_swap_out(i) + + if swappable_optimizer_subgroup: + self._optimizer_states_and_gradient_swap_out(i, timer_names) + + if is_adagrad: + self.optimizer = torch.optim.Adagrad(self.fp32_partitioned_groups_flat, **self.optimizer.defaults) + + self.timers(INIT_OPTIMIZER_TIMER).stop() + self.timers.log(timer_names) + + if self.swap_optimizer: + self.optimizer_swapper.log_timers() + + return + + # ------------------------------------------------------------------ # + # gradient partitioning + # ------------------------------------------------------------------ # + @instrument_w_nvtx + def partition_grads(self, params_to_release: List[Parameter], grad_partitions: List[Tensor]) -> None: + buffers = [] + + # Cache loop-invariant values (avoid repeated getattr/property/C++ binding calls). + is_boundary = self.is_gradient_accumulation_boundary() + micro_step_id = self.micro_step_id + copy_grad_stream = self.copy_grad_stream + current_stream = get_accelerator().current_stream() + stream_needs_sync = copy_grad_stream != current_stream + is_sync_device = get_accelerator().is_synchronized_device() + accumulate_submit = getattr(self, "_bucketwise_update_submit", None) + accum_futures_dict = self._bucketwise_accumulation_futures + + for param, grad_partition in zip(params_to_release, grad_partitions): + copy_event = None + + contains_real_data = param.partition_numel() * self._get_param_partition_rank(param) < param.ds_numel + if not contains_real_data: + param.grad = None + continue + + # No flat grad buffer is allocated in bucketwise mode; use grad_partition directly. + grad_buffer = grad_partition + buffers.append(grad_buffer) + + param_id = self.get_param_id(param) + grad_position_entry = self.grad_position[param_id] + sub_group_id, dest_offset, _ = grad_position_entry + + if grad_partition.dtype != self.gradient_accumulation_dtype: + converted_grad = grad_partition.to(self.gradient_accumulation_dtype) + else: + converted_grad = grad_partition + # The base flat grad buffer that has_overflow normally scans is freed on this path, so + # accumulate any inf/nan in the offloaded grads on the GPU here (no host sync); the flag + # is folded into has_overflow to drive FP16 dynamic-loss-scaling. + if self.dtype == torch.float16: + if self._reflow_grad_overflow is None: + self._reflow_grad_overflow = torch.zeros((), dtype=torch.uint8, device=converted_grad.device) + self._reflow_grad_overflow.logical_or_(has_inf_or_nan(converted_grad)) + + grad_numel = grad_buffer.numel() + + if micro_step_id == 0: # don't accumulate, first micro step + if self._single_grad_buffer: + # Slot 0 is also what the previous step's state commit reads, so wait for that commit before + # overwriting it. Usually a no-op: the commit finishes during the forward. + self._wait_for_pending_state_updates(sub_group_id=sub_group_id) + pending_buffer = self._get_cpu_grad_buffer(sub_group_id, pending=True) + pending_slice = pending_buffer.narrow(0, dest_offset, grad_numel) + + if stream_needs_sync: + copy_grad_stream.wait_stream(current_stream) + with get_accelerator().stream(copy_grad_stream): + pending_slice.copy_(converted_grad.view(pending_slice.shape), non_blocking=True) + copy_event = get_accelerator().Event() + copy_event.record(copy_grad_stream) + # No gradient accumulation: this micro-step is also the boundary, so use the GPU + # grad tensor directly for the norm/enqueue below. + if is_boundary: + grad_buffer = converted_grad + grad_numel = grad_buffer.numel() + else: + if is_boundary: + pending_buffer = self._get_cpu_grad_buffer(sub_group_id, pending=True) + dst_slice = pending_buffer.narrow(0, dest_offset, grad_numel) + if stream_needs_sync: + copy_grad_stream.wait_stream(current_stream) + with get_accelerator().stream(copy_grad_stream): + accum_gpu = dst_slice.to(converted_grad.device, non_blocking=True) + accum_gpu.add_(converted_grad.view(accum_gpu.shape)) + accum_event = get_accelerator().Event() + accum_event.record(copy_grad_stream) + dst_slice.copy_(accum_gpu, non_blocking=True) + copy_event = get_accelerator().Event() + copy_event.record(copy_grad_stream) + if stream_needs_sync: + current_stream.wait_event(accum_event) + # accum_gpu is allocated on copy_grad_stream but read by the grad-norm on + # current_stream below; the wait_event orders that read but does not keep the + # block alive, so record it against current_stream too or the allocator can + # recycle it (into copy_grad_stream's free list) before the norm read runs. + accum_gpu.record_stream(current_stream) + grad_buffer = accum_gpu + grad_numel = grad_buffer.numel() + else: + # The active slot written below as accumulation scratch still holds the previous step's grads, + # which that step's async state commit reads. Wait for that commit first; it is usually done + # by now, and the wait is a no-op once the future has been collected. + self._wait_for_pending_state_updates(sub_group_id=sub_group_id) + # CPU-side BF16 accumulation using AVX (avoid CPU->GPU->CPU round-trip). + active_buffer = self._get_cpu_grad_buffer(sub_group_id, pending=False) + src_slice = active_buffer.narrow(0, dest_offset, grad_numel) + pending_buffer = self._get_cpu_grad_buffer(sub_group_id, pending=True) + dst_slice = pending_buffer.narrow(0, dest_offset, grad_numel) + if stream_needs_sync: + copy_grad_stream.wait_stream(current_stream) + with get_accelerator().stream(copy_grad_stream): + src_slice.copy_(converted_grad.view(src_slice.shape), non_blocking=True) + copy_event = get_accelerator().Event() + copy_event.record(copy_grad_stream) + if accumulate_submit is not None: + # Capture values eagerly via default args (avoid late-binding closure bug). + def _accumulate_worker(_copy_event=copy_event, _dst_slice=dst_slice, _src_slice=src_slice): + _copy_event.synchronize() + ReflowCPUAdam.bf16_accumulate(_dst_slice.view(-1), _src_slice.view(-1)) + + future = accumulate_submit(_accumulate_worker) + if accum_futures_dict is not None: + accum_futures_dict.setdefault(sub_group_id, []).append(future) + grad_buffer = dst_slice + else: + copy_event.synchronize() + ReflowCPUAdam.bf16_accumulate(dst_slice.view(-1), src_slice.view(-1)) + grad_buffer = dst_slice + grad_numel = grad_buffer.numel() + + if is_boundary: + self.norm_for_param_grads[param_id] = self._constant_buffered_norm2(grad_buffer) + # NVMe subgroups have no resident optimizer state during backward, so their CPU step waits for + # step(); only mark the buffer ready. Other subgroups run the range during backward. + self._pending_grad_ready = True + if not self._swappable_optimizer_subgroup(sub_group_id): + self._bucketwise_schedule_enqueue_range(sub_group_id, + dest_offset, + grad_numel, + copy_event=copy_event) + + if not is_sync_device: + if param.grad is not None: + param.grad.record_stream(current_stream) + # The copy runs later on copy_grad_stream; record the source against it so the caching allocator does + # not hand that memory to the next bucket before the copy reads it. + if stream_needs_sync: + converted_grad.record_stream(copy_grad_stream) + param.grad = None + + return buffers + + def reset_cpu_buffers(self): + super().reset_cpu_buffers() + self._pending_grad_ready = False + + # Reset per-iteration pending/inflight state. + self._bucketwise_group_step_incremented.clear() + self._bucketwise_group_target_step.clear() + for sub_group_id in range(len(self._bucketwise_pending_ranges_by_group)): + self._bucketwise_pending_ranges_by_group[sub_group_id].clear() + self._bucketwise_pending_elems_by_group[sub_group_id] = 0 + self._bucketwise_inflight_h2d_events.clear() + self._bucketwise_pending_events.clear() + if getattr(self, "_bucketwise_update_futures", None) is not None: + self._bucketwise_update_futures.clear() + if self._bucketwise_inflight_futures is not None: + self._bucketwise_inflight_futures.clear() + self._bucketwise_cancel_version = 0 + self._bucketwise_worker_error = None + + # ------------------------------------------------------------------ # + # async state update workers + # ------------------------------------------------------------------ # + def _maybe_update_async_state(self, sub_group_id, combined_scale=None): + if combined_scale is None: + combined_scale = getattr(self, '_current_combined_scale', self.loss_scale) + + param_group_id = self.sub_group_to_group_id[sub_group_id] + # The commit runs after step() returns, and the engine steps the LR scheduler right after step(), so capture + # this step's hyperparameters now instead of letting the worker read the live param group later. + live_group = self.optimizer.param_groups[param_group_id] + group_hyperparams = {param_group_id: {key: value for key, value in live_group.items() if key != 'params'}} + + def _state_worker(pin_to_worker_cores=False, half_grad_buffer=None, combined_scale=None): + if pin_to_worker_cores: + self._pin_current_thread(self._state_commit_cpu_affinity_mask()) + + original = self.optimizer.param_groups[param_group_id]['params'] + try: + self.optimizer.param_groups[param_group_id]['params'] = \ + [self.fp32_partitioned_groups_flat[sub_group_id]] + # Align the buffer to param_groups by index, so a param group other than group 0 + # (e.g. the no-decay group of a decay/no-decay split) is updated with its buffer + # and every other group is skipped (None). + buffers = [None] * len(self.optimizer.param_groups) + buffers[param_group_id] = half_grad_buffer + numel = self.fp32_partitioned_groups_flat[sub_group_id].numel() + for start in range(0, numel, _STATE_COMMIT_SLICE_ELEMS): + # Re-pick the cores for every slice so the commit widens as soon as backward starts. + if pin_to_worker_cores: + self._pin_current_thread(self._state_commit_cpu_affinity_mask()) + slice_numel = min(_STATE_COMMIT_SLICE_ELEMS, numel - start) + self.optimizer.step_state_halfgrad(half_grad_buffers=buffers, + combined_scale=combined_scale, + element_range=(start, slice_numel), + group_hyperparams=group_hyperparams) + # Flush the non-temporal (streaming) optimizer-state stores so the updated state + # is globally visible before this worker's future completes, matching the fence the + # foreground param path issues; otherwise a later read can see partial/stale state. + self.optimizer.memory_fence() + finally: + self.optimizer.param_groups[param_group_id]['params'] = original + + # initialize_optimizer_states gives every subgroup a CPU half-precision grad buffer. + half_grad_buffer = self._cpu_grad_double_buffers[sub_group_id][self._active_grad_buffer_idx] + + executor = getattr(self, '_state_update_executor', None) + if executor is not None: + previous_future = self._last_state_update_future + + def chained_worker(): + # Wait for the previous future so workers complete in submission order. + if previous_future is not None: + previous_future.result() + _state_worker(True, half_grad_buffer, combined_scale) + + try: + future = executor.submit(chained_worker) + except Exception as e: + # submit() can fail (e.g. executor shut down); surface it through the all-reduced + # bucketwise flag so every rank aborts together at the next _check, not this one alone. + logger.warning(f"Reflow async state-update submit failed (rank {dist.get_rank()}): {e}") + self._record_state_update_error(e) + return + self._last_state_update_future = future + self._pending_state_updates_by_subgroup[sub_group_id] = future + else: + # Synchronous fallback (no async-state executor). Surface a failure through the same + # all-reduced flag so every rank aborts together at the next _check, rather than this rank + # raising alone and hanging its peers at the following collective. + try: + _state_worker(False, half_grad_buffer, combined_scale) + except Exception as e: + self._record_state_update_error(e) + + def _record_state_update_error(self, error): + # Surface a state-update worker failure through the same all-reduced flag the bucketwise + # workers use, so a failure on only some ranks aborts the step on ALL ranks together (the next + # _check_bucketwise_worker_error all-reduces it) instead of this rank raising alone and hanging + # its peers at the following collective. + if self._bucketwise_worker_error is None: + self._bucketwise_worker_error = error + + def _wait_for_pending_state_updates(self, sub_group_id=None): + """Wait for pending state-update workers (one subgroup, or all if sub_group_id is None).""" + if sub_group_id is not None: + future = self._pending_state_updates_by_subgroup.get(sub_group_id, None) + if future is None: + return + try: + future.result() + except Exception as e: + if dist.get_rank() == 0: + logger.warning(f"Error waiting for state update worker (subgroup {sub_group_id}): {e}") + self._record_state_update_error(e) + finally: + self._pending_state_updates_by_subgroup.pop(sub_group_id, None) + else: + future = getattr(self, '_last_state_update_future', None) + if future is None: + return + try: + # The last future chains all previous ones, so waiting for it drains them all. + future.result() + except Exception as e: + if dist.get_rank() == 0: + logger.warning(f"Error waiting for state update workers: {e}") + self._record_state_update_error(e) + finally: + self._last_state_update_future = None + + def _wait_for_accum_gradient(self, sub_group_id=None): + """Wait for pending gradient-accumulation workers (one subgroup, or all).""" + if sub_group_id is not None: + for f in self._bucketwise_accumulation_futures.get(sub_group_id, []): + try: + f.result() + except Exception as e: + self._record_bucketwise_worker_error(e) + self._bucketwise_accumulation_futures[sub_group_id] = [] + else: + for _sg_id, futures in list(self._bucketwise_accumulation_futures.items()): + for f in futures: + try: + f.result() + except Exception as e: + self._record_bucketwise_worker_error(e) + self._bucketwise_accumulation_futures.clear() + + def _get_cpu_grad_buffer(self, sub_group_id, pending=False): + if sub_group_id >= len(self._cpu_grad_double_buffers): + return self.fp32_partitioned_groups_flat[sub_group_id].grad + buffers = self._cpu_grad_double_buffers[sub_group_id] + if buffers is None: + return self.fp32_partitioned_groups_flat[sub_group_id].grad + index = self._pending_grad_buffer_idx if pending else self._active_grad_buffer_idx + return buffers[index] + + def _activate_pending_cpu_grads_if_ready(self): + if not self._pending_grad_ready: + return False + # Gradient buffers are written directly by the bucketwise workers; drain them and flip + # the active/pending double buffer. + self._bucketwise_drain_enq_executor() + self._bucketwise_wait_inflight_updates() + # Single-buffer mode has only slot 0: keep the active index pinned there (no flip). The + # workers already wrote the params into fp16_flat, and Phase-2 reads the grads from slot 0. + if not self._single_grad_buffer: + self._active_grad_buffer_idx = 1 - self._active_grad_buffer_idx + self._pending_grad_ready = False + return True + + # ------------------------------------------------------------------ # + # cpu_bucketwise pipeline + # ------------------------------------------------------------------ # + def _bucketwise_drain_enq_executor(self): + """Block until all async enqueue work has been reflected in the pending ranges. + + ``_bucketwise_schedule_enqueue_range`` submits enqueue work asynchronously; before + flushing we must ensure every gradient range has landed in the pending structures, + otherwise a range is dropped and the parameter update is silently skipped. + """ + enq_executor = getattr(self, "_bucketwise_enq_executor", None) + if enq_executor is None: + return + try: + sentinel = enq_executor.submit(lambda: None) + sentinel.result(timeout=30.0) + except Exception as e: + self._record_bucketwise_worker_error(e) + + def _bucketwise_schedule_enqueue_range(self, sub_group_id, dest_offset, num_elements, copy_event=None): + """Schedule a range enqueue off the main thread (falls back to sync if no executor).""" + if not self.is_gradient_accumulation_boundary(): + return + + enq_submit = getattr(self, "_bucketwise_enq_submit", None) + if enq_submit is None: + self._bucketwise_enqueue_range(sub_group_id, dest_offset, num_elements, copy_event) + return + try: + enq_submit(self._bucketwise_enqueue_range, sub_group_id, dest_offset, num_elements, copy_event) + except Exception: + self._bucketwise_enqueue_range(sub_group_id, dest_offset, num_elements, copy_event) + + def _bucketwise_get_valid_partition_element_count(self, sub_group_id: int) -> int: + """Return the number of real (non-padding) elements this rank must update.""" + partition_element_count = int(self.fp16_partitioned_groups_flat_numel[sub_group_id]) + padding_element_count = 0 + if sub_group_id < len(self.groups_padding): + padding_element_count = sum(self.groups_padding[sub_group_id]) + valid_partition_element_count = partition_element_count - padding_element_count + return max(valid_partition_element_count, 0) + + def _bucketwise_clip_range_to_valid_partition(self, sub_group_id: int, dest_offset: int, num_elements: int): + """Clamp a range to the valid partition; return None if it is entirely padding.""" + valid_partition_element_count = self._bucketwise_get_valid_partition_element_count(sub_group_id) + return reflow_utils.clip_range_to_valid_partition(valid_partition_element_count, dest_offset, num_elements) + + def _bucketwise_chunk_update_worker(self, work_item): + # Worker: run the partial Adam update, then async-copy only the updated ranges to GPU. + try: + sub_group_id = work_item["sub_group_id"] + ranges = work_item["ranges"] + grad_buffer_index = work_item["grad_buffer_index"] + combined_scale = work_item["combined_scale"] + copy_events = work_item.get("copy_events", []) + cancel_version = work_item.get("cancel_version", 0) + increment_step = work_item.get("increment_step", False) + target_step = work_item.get("target_step", None) + + if cancel_version != getattr(self, "_bucketwise_cancel_version", 0): + return None + + # Wait for the GPU->CPU grad copy (only the last event, the stream is sequential). + last_copy_event = copy_events[-1] if copy_events else None + if last_copy_event is not None: + last_copy_event.synchronize() + + if cancel_version != getattr(self, "_bucketwise_cancel_version", 0): + return None + + # Ensure all gradient accumulations for this subgroup completed. + self._wait_for_accum_gradient(sub_group_id) + + # Make sure the previous state update for this subgroup finished. + self._wait_for_pending_state_updates(sub_group_id=sub_group_id) + + fp32_param = self.fp32_partitioned_groups_flat[sub_group_id] + # The kernel call below uses explicit param/grad/state slices and never reads + # param_groups, so the worker does not touch self.optimizer.param_groups here: + # mutating it would be a dead store that races concurrent bucketwise workers, + # _prepare_state_and_params, and the async _state_worker. + + # grad_buffer_index holds the grads (slot 0 in single-buffer mode). + half_grad_buffer = self._cpu_grad_double_buffers[sub_group_id][grad_buffer_index] + if self._single_grad_buffer: + # Single-buffer mode has no opposite slot, so the kernel writes the params straight into fp16_flat, + # which that slot would only have duplicated. Grads are still read from slot 0. + half_params_buffer = self.fp16_partitioned_groups_flat[sub_group_id] + else: + # Cross-buffer: FP16 param output goes to the slot opposite the grads. + fp16_output_buffer_index = 1 - grad_buffer_index + half_params_buffer = self._cpu_grad_double_buffers[sub_group_id][fp16_output_buffer_index] + + use_lion = hasattr(self.optimizer, "ds_opt_lion") + if not use_lion and not hasattr(self.optimizer, "ds_opt_adam"): + raise RuntimeError("cpu_bucketwise requires a Reflow CPU optimizer (ReflowCPUAdam or ReflowCPULion)") + + p = fp32_param + state = self.optimizer.state[p] + + lr = work_item.get("lr") + beta1 = work_item.get("beta1") + beta2 = work_item.get("beta2") + eps = work_item.get("eps") + weight_decay = work_item.get("weight_decay") + bias_correction = work_item.get("bias_correction", True) + # increment_step controls the per-range skip flag only; the Python state['step'] + # is committed once at the end of step(). + if target_step is None: + target_step = int(state.get('step', 0)) + 1 + + # Lion has no second moment, epsilon, or bias correction. + if use_lion: + for range_idx, (offset, size) in enumerate(ranges): + range_increment_step = increment_step and (range_idx == 0) + + param_slice = p.data.view(-1).narrow(0, offset, size) + grad_slice = half_grad_buffer.view(-1).narrow(0, offset, size) + exp_avg_slice = state['exp_avg'].view(-1).narrow(0, offset, size) + half_params_slice = half_params_buffer.view(-1).narrow(0, offset, size) + + self.optimizer.ds_opt_lion.reflow_lion_update_params_halfgrad( + self.optimizer.opt_id, + target_step, + lr, + beta1, + beta2, + weight_decay, + param_slice, + grad_slice, + exp_avg_slice, + half_params_slice, + combined_scale, + not range_increment_step, + ) + + self.optimizer.ds_opt_lion.reflow_lion_memory_fence() + else: + for range_idx, (offset, size) in enumerate(ranges): + range_increment_step = increment_step and (range_idx == 0) + + param_slice = p.data.view(-1).narrow(0, offset, size) + grad_slice = half_grad_buffer.view(-1).narrow(0, offset, size) + exp_avg_slice = state['exp_avg'].view(-1).narrow(0, offset, size) + exp_avg_sq_slice = state['exp_avg_sq'].view(-1).narrow(0, offset, size) + half_params_slice = half_params_buffer.view(-1).narrow(0, offset, size) + + self.optimizer.ds_opt_adam.reflow_adam_update_params_halfgrad( + self.optimizer.opt_id, + target_step, + lr, + beta1, + beta2, + eps, + weight_decay, + bias_correction, + param_slice, + grad_slice, + exp_avg_slice, + exp_avg_sq_slice, + half_params_slice, + combined_scale, + not range_increment_step, + ) + + self.optimizer.ds_opt_adam.reflow_adam_memory_fence() + + if cancel_version != getattr(self, "_bucketwise_cancel_version", 0): + return None + + if self._single_grad_buffer: + # Single-buffer mode already wrote the params into fp16_flat. No H2D event is needed: they are + # CPU-resident, and step() joins this worker before the next forward reads them. + return None + + fp16_flat = self.fp16_partitioned_groups_flat[sub_group_id] + if fp16_flat is None: + return None + + src = half_params_buffer.data.view(-1) + dst = fp16_flat.data.view(-1) + + merged_ranges = reflow_utils.merge_contiguous_ranges(ranges) + stream = getattr(self, "_bucketwise_h2d_stream", None) + if stream is None: + stream = get_accelerator().current_stream() + + with get_accelerator().stream(stream): + for off, sz in merged_ranges: + dst.narrow(0, off, sz).copy_(src.narrow(0, off, sz), non_blocking=True) + if not get_accelerator().is_synchronized_device(): + h2d_event = get_accelerator().Event() + h2d_event.record(stream) + else: + h2d_event = None + + return h2d_event + except Exception as e: + # A cooperative cancel (version bump) can race the kernel and surface as a transient + # error; if this work item has been cancelled, treat it as a clean no-op like the + # explicit cancel returns above. Otherwise this is a real kernel/OOM failure: record it + # so step() can abort deterministically on all ranks instead of silently advancing. + if work_item.get("cancel_version", 0) != getattr(self, "_bucketwise_cancel_version", 0): + return None + self._record_bucketwise_worker_error(e) + logger.warning(f"Reflow bucketwise worker error (rank {dist.get_rank()}): {e}") + return None + + def _bucketwise_enqueue_range(self, sub_group_id, dest_offset, num_elements, copy_event=None): + # Accumulate a scheduled grad range; flush once the shard threshold is reached. + try: + clipped_range = self._bucketwise_clip_range_to_valid_partition(sub_group_id, dest_offset, num_elements) + if clipped_range is None: + return + dest_offset, num_elements = clipped_range + + lock = self._get_enqueue_lock() + + with lock: + if sub_group_id >= len(self._bucketwise_pending_ranges_by_group): + while len(self._bucketwise_pending_ranges_by_group) <= sub_group_id: + self._bucketwise_pending_ranges_by_group.append([]) + self._bucketwise_pending_elems_by_group.append(0) + + if copy_event is not None: + self._bucketwise_pending_events.setdefault(sub_group_id, []).append(copy_event) + + self._bucketwise_pending_ranges_by_group[sub_group_id].append((dest_offset, num_elements)) + self._bucketwise_pending_elems_by_group[sub_group_id] += num_elements + pending_elem_count = self._bucketwise_pending_elems_by_group[sub_group_id] + + if pending_elem_count >= self._bucketwise_element_shard_size: + self._bucketwise_flush_group(sub_group_id, + force=True, + use_pending_buffer=True, + combined_scale=self.loss_scale, + already_locked=True) + except Exception as e: + self._record_bucketwise_worker_error(e) + + def _bucketwise_flush_group(self, + sub_group_id, + force=False, + use_pending_buffer=True, + combined_scale=None, + already_locked=False): + # Submit accumulated ranges as a single work item. Returns the future (or None). + if self._bucketwise_update_submit is None: + return None + if sub_group_id >= len(self._bucketwise_pending_ranges_by_group): + return None + ranges = self._bucketwise_pending_ranges_by_group[sub_group_id] + if not ranges: + return None + if not force and self._bucketwise_pending_elems_by_group[sub_group_id] < self._bucketwise_element_shard_size: + return None + + merged_ranges = reflow_utils.merge_contiguous_ranges(ranges) + + # force=False: submit merged ranges >= min_submit_range_elems, keep the rest pending. + min_submit_range_elems = getattr(self, "_bucketwise_min_submit_range_elems", + _DEFAULT_BUCKETWISE_MIN_SUBMIT_ELEMS) + if not force: + submit_ranges, pending_merged, pending_elems = \ + reflow_utils.split_ranges_by_min_size(merged_ranges, min_submit_range_elems) + self._bucketwise_pending_ranges_by_group[sub_group_id] = pending_merged + self._bucketwise_pending_elems_by_group[sub_group_id] = pending_elems + if not submit_ranges: + return None + else: + submit_ranges = merged_ranges + self._bucketwise_pending_ranges_by_group[sub_group_id].clear() + self._bucketwise_pending_elems_by_group[sub_group_id] = 0 + + # Final clamp/filter so submitted ranges never exceed the valid partition. + valid_partition_element_count = self._bucketwise_get_valid_partition_element_count(sub_group_id) + if valid_partition_element_count <= 0: + return None + submit_ranges = reflow_utils.clip_ranges_to_valid_partition(submit_ranges, valid_partition_element_count) + if not submit_ranges: + return None + + grad_buffer_index = self._pending_grad_buffer_idx if use_pending_buffer else self._active_grad_buffer_idx + + copy_events_snapshot = self._bucketwise_pending_events.get(sub_group_id, []) + self._bucketwise_pending_events[sub_group_id] = [] + + lock = self._get_enqueue_lock() + + def _prepare_state_and_params(): + increment_step = (sub_group_id not in self._bucketwise_group_step_incremented) + if increment_step: + self._bucketwise_group_step_incremented.add(sub_group_id) + + param_group_id = self.sub_group_to_group_id[sub_group_id] + group = self.optimizer.param_groups[param_group_id] + # The previous step's async state worker may still be iterating group['params']. + # Keep its list intact while preparing the next bucket update. + p = self.fp32_partitioned_groups_flat[sub_group_id] + if p is None: + return None + + # Reflow fp32 master params live on CPU, so _ensure_param_state (device=cpu) builds + # the same lazy step/exp_avg/exp_avg_sq buffers the inline init did. + state = self.optimizer._ensure_param_state(p) + # Pass a fixed per-iteration target_step to the kernel; commit state['step'] once + # at the end of step() instead of mutating it in the worker. + current_step = int(state.get('step', 0)) + target_step = self._bucketwise_group_target_step.get(sub_group_id, None) + if target_step is None: + target_step = current_step + 1 + self._bucketwise_group_target_step[sub_group_id] = target_step + + beta1, beta2 = group['betas'] + lr = group['lr'] + # Lion param groups carry no 'eps'/'bias_correction'; the optimizer ignores both. + eps = group.get('eps', 0.0) + weight_decay = group['weight_decay'] + bias_correction = group.get('bias_correction', True) + + return increment_step, target_step, lr, beta1, beta2, eps, weight_decay, bias_correction + + if already_locked: + result = _prepare_state_and_params() + if result is None: + return None + increment_step, target_step, lr, beta1, beta2, eps, weight_decay, bias_correction = result + else: + with lock: + result = _prepare_state_and_params() + if result is None: + return None + increment_step, target_step, lr, beta1, beta2, eps, weight_decay, bias_correction = result + + work_item = { + "sub_group_id": sub_group_id, + "ranges": submit_ranges, + "grad_buffer_index": grad_buffer_index, + "combined_scale": combined_scale, + "copy_events": copy_events_snapshot, + "cancel_version": getattr(self, "_bucketwise_cancel_version", 0), + "increment_step": increment_step, + "target_step": target_step, + "lr": lr, + "beta1": beta1, + "beta2": beta2, + "eps": eps, + "weight_decay": weight_decay, + "bias_correction": bias_correction, + } + + future = self._bucketwise_update_submit(self._bucketwise_chunk_update_worker, work_item) + if getattr(self, "_bucketwise_update_futures", None) is not None: + self._bucketwise_update_futures.append(future) + self._bucketwise_inflight_futures.append(future) + return future + + def _bucketwise_flush_all_pending(self, force=False, use_pending_buffer=True, combined_scale=None): + for sub_group_id in range(len(self._bucketwise_pending_ranges_by_group)): + self._bucketwise_flush_group(sub_group_id, + force=force, + use_pending_buffer=use_pending_buffer, + combined_scale=combined_scale) + + def _bucketwise_cancel_inflight_updates(self): + # Best-effort cancel of inflight workers when clipping is needed. + self._bucketwise_cancel_version += 1 + for f in list(getattr(self, "_bucketwise_inflight_futures", [])): + try: + f.cancel() + except Exception: + pass + + def _bucketwise_commit_group_steps(self): + target_steps = getattr(self, "_bucketwise_group_target_step", None) + if not target_steps: + return + for sub_group_id, target_step in list(target_steps.items()): + if sub_group_id >= len(self.fp32_partitioned_groups_flat): + continue + p = self.fp32_partitioned_groups_flat[sub_group_id] + if p is None: + continue + state = self.optimizer.state[p] + current_step = int(state.get('step', 0)) + if current_step < target_step: + state['step'] = target_step + + def _bucketwise_wait_inflight_updates(self): + # Wait for submitted bucketwise work (optimizer + H2D submit). H2D completion itself is + # synchronized later via CUDA events. + + futures = list(getattr(self, "_bucketwise_update_futures", []) or []) + if not futures: + futures = list(getattr(self, "_bucketwise_inflight_futures", []) or []) + + self._drain_update_futures_collecting_h2d_events(futures) + + if getattr(self, "_bucketwise_update_futures", None) is not None: + self._bucketwise_update_futures.clear() + self._bucketwise_inflight_futures.clear() + + def _nvme_optimizer_step_subgroups(self, combined_scale, timer_names): + """NVMe optimizer offload: a swappable-optimizer subgroup's state (fp32 master + the optimizer + moments) lives on disk, so its CPU optimizer could not run during backward. Here -- after the + cpu subgroups drained -- swap each subgroup's state in from nvme, run its full-partition + CPU optimizer (param + state) reading the reduced grad from the active CPU half buffer, then + swap the updated state back out. Serialized on the main thread: the partitioned optimizer swapper + is single-threaded and not thread-safe, so subgroups are processed one at a time.""" + for sub_group_id in range(len(self.fp16_groups)): + if not self._swappable_optimizer_subgroup(sub_group_id): + continue + self._optimizer_states_and_gradient_swap_in(sub_group_id, timer_names) + full_ranges = [] + for param in self.fp16_groups[sub_group_id]: + if not param.requires_grad: + continue + pos = self.grad_position.get(self.get_param_id(param), None) + if pos is None: + continue + dest_offset, num_elems = pos[1], pos[2] + if num_elems > 0: + full_ranges.append((dest_offset, num_elems)) + if full_ranges: + self._bucketwise_pending_ranges_by_group[sub_group_id] = sorted(full_ranges, key=lambda x: x[0]) + self._bucketwise_pending_elems_by_group[sub_group_id] = sum(sz for _, sz in full_ranges) + future = self._bucketwise_flush_group(sub_group_id, + force=True, + use_pending_buffer=False, + combined_scale=combined_scale) + if future is not None: + # Join the param-update worker AND collect its H2D event, so the next forward's + # all-gather waits for this subgroup's updated GPU param (written on the h2d + # stream) -- otherwise the forward races the in-flight copy and reads stale params. + self._drain_update_futures_collecting_h2d_events([future]) + # Commit the step counter into optimizer.state BEFORE the state update. step_state_halfgrad + # reads state['step'] for bias correction and assumes the param update already advanced it + # (in CPU mode the commit precedes the async-state loop). Without committing first, + # state['step']=0 -> bias_correction 1-beta**0 = 0 -> divide-by-zero -> NaN weights. + self._bucketwise_commit_group_steps() + # Optimizer-state (momentum) update; then join both the param-update worker and the + # state worker before swapping the now-final state out to nvme. + self._maybe_update_async_state(sub_group_id, combined_scale) + self._wait_for_pending_state_updates(sub_group_id=sub_group_id) + self._optimizer_states_and_gradient_swap_out(sub_group_id, timer_names) + + def _bucketwise_run_full_partition_updates(self, combined_scale): + # Clipping path: re-shard and re-run each group's full range, then transfer. + + full_update_futures = [] + for sub_group_id in range(len(self.fp16_groups)): + if self._swappable_optimizer_subgroup(sub_group_id): + continue # nvme optimizer subgroups are handled in _nvme_optimizer_step_subgroups + full_ranges = [] + for param in self.fp16_groups[sub_group_id]: + if not param.requires_grad: + continue + param_id = self.get_param_id(param) + pos = self.grad_position.get(param_id, None) + if pos is None: + continue + dest_offset, num_elems = pos[1], pos[2] + if num_elems > 0: + full_ranges.append((dest_offset, num_elems)) + + if not full_ranges: + continue + + shard_ranges = [] + shard_elems = 0 + for off, sz in sorted(full_ranges, key=lambda x: x[0]): + shard_ranges.append((off, sz)) + shard_elems += sz + if shard_elems >= self._bucketwise_element_shard_size: + self._bucketwise_pending_ranges_by_group[sub_group_id] = shard_ranges + self._bucketwise_pending_elems_by_group[sub_group_id] = shard_elems + future = self._bucketwise_flush_group(sub_group_id, + force=True, + use_pending_buffer=False, + combined_scale=combined_scale) + if future is not None: + full_update_futures.append(future) + shard_ranges = [] + shard_elems = 0 + + if shard_ranges: + self._bucketwise_pending_ranges_by_group[sub_group_id] = shard_ranges + self._bucketwise_pending_elems_by_group[sub_group_id] = shard_elems + future = self._bucketwise_flush_group(sub_group_id, + force=True, + use_pending_buffer=False, + combined_scale=combined_scale) + if future is not None: + full_update_futures.append(future) + + self._drain_update_futures_collecting_h2d_events(full_update_futures) + + def backward_prologue(self): + # The pending state commit no longer overlaps a forward, so let it use every worker core. + self._state_commit_overlaps_forward = False + super().backward_prologue() + + def _state_commit_cpu_affinity_mask(self): + # A few busy cores keep the forward's core at a high turbo frequency; after the forward the commit gets every + # worker core so a large model's commit still finishes before the next step() waits on it. + if self._state_commit_overlaps_forward: + return self._state_update_cpu_affinity_mask + return self._state_backward_cpu_affinity_mask + + @staticmethod + def _all_reduce_norm_entries_by_group(total_norms, process_groups): + # Sum each entry over its process group (None: skip). Groups are visited in subgroup order, so every rank + # issues the same collectives in the same order. + indices_by_group = {} + for index, process_group in enumerate(process_groups): + if process_group is None: + continue + if id(process_group) not in indices_by_group: + indices_by_group[id(process_group)] = (process_group, []) + indices_by_group[id(process_group)][1].append(index) + for process_group, indices in indices_by_group.values(): + if len(indices) == len(process_groups): + dist.all_reduce(total_norms, op=dist.ReduceOp.SUM, group=process_group) + continue + index_tensor = torch.tensor(indices, device=total_norms.device) + entries = total_norms.index_select(0, index_tensor) + dist.all_reduce(entries, op=dist.ReduceOp.SUM, group=process_group) + total_norms.index_copy_(0, index_tensor, entries) + + def _get_norm_groups(self): + # Reduce every subgroup's sum of squares in one pair of collectives instead of one pair per subgroup like + # the base; with Reflow's many small subgroups the per-subgroup latency dominates the norm. + if not self.offload_optimizer: + return super()._get_norm_groups() + + local_sq = [] + for group in self.fp16_groups: + group_sq = 0.0 + for p in group: + if is_model_parallel_parameter(p) or (self.model_parallel_rank == 0): + param_id = self.get_param_id(p) + if param_id in self.norm_for_param_grads: + group_sq += self.norm_for_param_grads[param_id]**2 + local_sq.append(float(group_sq)) + + total_norms = get_accelerator().FloatTensor(local_sq) + # Match complete_grad_norm_calculation_for_cpu_offload: each subgroup sums over its own partition group, + # then the model-parallel group, then (AutoEP expert subgroups only) the expert-parallel group. Subgroups + # sharing a group are reduced together, so the usual single-group case stays one all-reduce. + partition_groups = [self._get_sub_group_process_group(i) for i in range(len(self.fp16_groups))] + self._all_reduce_norm_entries_by_group(total_norms, partition_groups) + self._model_parallel_all_reduce(tensor=total_norms, op=dist.ReduceOp.SUM) + expert_groups = [self._autoep_expert_parallel_group(group) for group in self.fp16_groups] + self._all_reduce_norm_entries_by_group(total_norms, expert_groups) + + norm_groups = [] + for i in range(len(self.fp16_groups)): + total_norm = total_norms[i]**0.5 + mask_nan_or_inf_with_val_inplace(total_norm, device=total_norm.device) + norm_groups.append(total_norm.cpu()) + return norm_groups + + # ------------------------------------------------------------------ # + # step + # ------------------------------------------------------------------ # + @instrument_w_nvtx + def step(self, closure=None): + """ + Not supporting closure. + """ + self._wait_for_accum_gradient() + self._wait_for_pending_state_updates() + # This setup only touches param handles and the FP32 master, so run it before the device sync to overlap + # the GPU drain from backward. Everything below that reads GPU results still follows the sync. + self._pre_step() + self._partition_all_parameters() + get_accelerator().synchronize() + bucketwise_drained = self._activate_pending_cpu_grads_if_ready() + # Activation already joined the backward workers when it flipped the buffers. Otherwise + # join them before overflow cleanup discards their handles. + if not bucketwise_drained: + self._bucketwise_drain_enq_executor() + self._bucketwise_wait_inflight_updates() + # Workers swallow their own exceptions (a cancel and a real error both return None), so + # surface any real kernel/OOM failure here and abort deterministically on all ranks before + # the overflow check advances the loss scale / optimizer state. + self._check_bucketwise_worker_error() + + if self._overflow_check_and_loss_scale_update(): + if self.swap_optimizer: + self.optimizer_swapper.log_timers() + # Discard the step like the base optimizer. The workers already wrote new FP16/BF16 params to the GPU + # during backward, so restore them from the untouched FP32 master. + self._bucketwise_cancel_version += 1 + if not get_accelerator().is_synchronized_device(): + get_accelerator().synchronize() + for sub_group_id in range(len(self.fp16_groups)): + self._restore_fp16_params_from_master(sub_group_id) + return + + norm_groups = self._get_norm_groups() + scaled_global_grad_norm = torch.linalg.vector_norm(torch.stack(norm_groups)) + + self._global_grad_norm = scaled_global_grad_norm / self.loss_scale + + combined_scale = self.loss_scale + needs_clipping = False + if self.clip_grad > 0.: + # norm is in fact norm*scale, so unscale. + clip = ((scaled_global_grad_norm / self.loss_scale) + 1e-6) / self.clip_grad + # Re-run the update exactly when the clip factor changes the scale, like the base optimizer. A plain + # norm > clip_grad test misses norms just below the threshold, which the base still clips, and would + # commit the clipped state under params that were computed unclipped during backward. + needs_clipping = clip > 1.0 + clip = max(clip, 1.0) + combined_scale = clip * self.loss_scale + self._current_combined_scale = combined_scale + + self._bucketwise_flush_all_pending(force=True, use_pending_buffer=False, combined_scale=self.loss_scale) + if needs_clipping: + # cancel() does not wait. Join the cancelled workers first so their unclipped H2D writes are enqueued + # before the clipped re-run's and cannot land last. + self._bucketwise_cancel_inflight_updates() + self._bucketwise_wait_inflight_updates() + self._bucketwise_run_full_partition_updates(combined_scale=combined_scale) + + timer_names = set() + # Param updates already ran bucketwise during backward; here we only commit per-group + # step counters and submit the deferred async state updates. + self._bucketwise_wait_inflight_updates() + # NVMe optimizer subgroups deferred their CPU-Adam (state not resident during backward); run + # it now with the state swapped in around it, before committing step counters / the async loop. + if self.swap_optimizer: + self._nvme_optimizer_step_subgroups(combined_scale, timer_names) + self._bucketwise_commit_group_steps() + # The commits submitted below overlap the next forward until its backward starts. + self._state_commit_overlaps_forward = True + for sub_group_id in reversed(range(len(self.fp16_groups))): + if self._swappable_optimizer_subgroup(sub_group_id): + continue # nvme: already updated above with its state swapped in + self._maybe_update_async_state(sub_group_id, combined_scale) + if self._bucketwise_inflight_h2d_events: + # Instead of blocking on the workers' H2D copies, make every stream that reads the params wait on them. + # With overlap_comm the all-gather has its own stream, so a compute-stream wait alone is not enough. + h2d_events = self._coalesce_bucketwise_h2d_events() + compute_stream = get_accelerator().current_stream() + for h2d_event in h2d_events: + if h2d_event is not None: + if self._sync_bucketwise_h2d_before_forward: + h2d_event.synchronize() + compute_stream.wait_event(h2d_event) + self.copy_grad_stream.wait_event(h2d_event) + self._get_param_coordinator().wait_for_external_allgather_dependencies(h2d_events) + # NVMe param offload: the bucketwise workers leave the updated FP16/BF16 weights in the CPU + # half buffer (an nvme subgroup has no GPU param to H2D into), so swap them out to nvme here, + # on the main thread -- the partitioned param swapper holds single shared mutable state and is + # not thread-safe. Confined to nvme subgroups (fp16 flat is None); cpu/gpu paths are untouched. + for sub_group_id in range(len(self.fp16_groups)): + if self.fp16_partitioned_groups_flat[sub_group_id] is None: + self._partitioned_params_swap_out(sub_group_id, use_updated_weights=True) + + self._post_step(timer_names) + + memory_stats = get_accelerator().memory_stats() + alloc_retries = memory_stats.get("num_alloc_retries") + if alloc_retries is None: + alloc_retries = 0 + if alloc_retries > self.n_caching_allocator_flushes: + if dist.get_rank() == 0: + logger.warning( + "%d pytorch allocator cache flushes since last step. this happens " + "when there is high memory pressure and is detrimental to " + "performance. if this is happening frequently consider adjusting " + "settings to reduce memory consumption. If you are unable to " + "make the cache flushes go away consider adding " + "get_accelerator().empty_cache() calls in your training loop to ensure " + "that all ranks flush their caches at the same time", + alloc_retries - self.n_caching_allocator_flushes) + self.n_caching_allocator_flushes = alloc_retries + + # ------------------------------------------------------------------ # + # overflow + # ------------------------------------------------------------------ # + def _restore_fp16_params_from_master(self, sub_group_id): + """Undo a discarded (overflow) step: re-cast the FP32 master weights to FP16/BF16 and + scatter them back onto the GPU params, overwriting any FP16 preview the bucketwise workers + wrote during backward (the FP32 master itself is the unchanged pre-step weight).""" + if sub_group_id >= len(self.fp16_partitioned_groups_flat): + return + fp16_flat = self.fp16_partitioned_groups_flat[sub_group_id] + fp32_flat = self.fp32_partitioned_groups_flat[sub_group_id] + if fp32_flat is None: + return + if fp16_flat is None: + # nvme subgroup: no GPU fp16 flat to restore -- re-swap the unchanged FP32 master so the + # on-disk weights stay the pre-step values after a discarded (overflow) step. + self._partitioned_params_swap_out(sub_group_id) + return + if self._swappable_optimizer_subgroup(sub_group_id): + # nvme optimizer subgroup: its CPU-Adam is deferred to step() (skipped entirely on + # overflow), so the GPU param was never updated during backward and already holds the + # pre-step weight. The FP32 master lives on nvme (swapped out), so there is nothing to + # copy from here -- the discarded step leaves both the param and the state untouched. + return + fp16_flat.data.copy_(fp32_flat.data) + self._unflatten_partitioned_parameters(sub_group_id) + + @instrument_w_nvtx + def has_overflow(self, partition_gradients=True): + if partition_gradients: + with get_accelerator().stream(self.reduce_and_partition_stream): + if self.grad_partitions_flat_buffer is None: + # No flat grad buffer is allocated in bucketwise mode, so there is nothing to + # scan for inf/nan here. + pass + elif hasattr(self.inf_or_nan_tracker, "logical_or_"): + self.inf_or_nan_tracker.logical_or_(torch.isinf(self.grad_partitions_flat_buffer).any()) + self.inf_or_nan_tracker.logical_or_(torch.isnan(self.grad_partitions_flat_buffer).any()) + else: + # logical_or_ not available in older versions of pytorch + self.inf_or_nan_tracker += torch.isinf(self.grad_partitions_flat_buffer).any() + self.inf_or_nan_tracker += torch.isnan(self.grad_partitions_flat_buffer).any() + self.inf_or_nan_tracker = self.inf_or_nan_tracker > 0 + + overflow_gpu = self.inf_or_nan_tracker.clone().to(get_accelerator().current_device_name()).to( + torch.uint8) + self.inf_or_nan_tracker.zero_() + # Fold in the inf/nan seen while offloading grads in partition_grads (this path + # freed the flat buffer the branch above would otherwise scan). + if self._reflow_grad_overflow is not None: + overflow_gpu.logical_or_(self._reflow_grad_overflow.to(overflow_gpu.device)) + self._reflow_grad_overflow.zero_() + + if not get_accelerator().resolves_data_dependency(): + get_accelerator().default_stream().wait_stream(self.reduce_and_partition_stream) + dist.all_reduce(overflow_gpu, op=dist.ReduceOp.MAX, group=self.dp_process_group) + + else: + params = [] + for group in self.fp16_groups: + for param in group: + params.append(param) + + overflow = self.has_overflow_serial(params, is_grad_list=partition_gradients) + overflow_gpu = get_accelerator().ByteTensor([overflow]) + # Since each model parallel GPU carries only part of the model, + # make sure overflow flag is synced across all the model parallel GPUs + self._model_parallel_all_reduce(tensor=overflow_gpu, op=dist.ReduceOp.MAX) + + overflow = overflow_gpu[0].item() + return bool(overflow) + + # ------------------------------------------------------------------ # + # auxiliary APIs unsupported under reflow + # ------------------------------------------------------------------ # + # Reflow frees the flat grad buffer and leaves the FP32 .grad unset, so these APIs would fail with an + # opaque AttributeError; raise a clear NotImplementedError instead. + + def get_fp32_grad_for_param(self, param) -> Tensor: + raise NotImplementedError(_REFLOW_FLAT_GRAD_FREED_MSG.format(api="get_fp32_grad_for_param")) + + def set_fp32_grad_for_param(self, value, param): + raise NotImplementedError(_REFLOW_FLAT_GRAD_FREED_MSG.format(api="set_fp32_grad_for_param")) + + def offload_states(self, + include: Container[OffloadStateTypeEnum] = None, + device: OffloadDeviceEnum = OffloadDeviceEnum.cpu, + pin_memory: bool = True, + non_blocking: bool = False): + raise NotImplementedError(_REFLOW_FLAT_GRAD_FREED_MSG.format(api="offload_states")) + + def finalize_gradient_accumulation_boundary(self): + # Unmanaged gradient accumulation marks the boundary only after backward, but Reflow submits its CPU + # optimizer work during backward when it sees the boundary, so the update would silently never run. + raise NotImplementedError("Reflow requires managed gradient accumulation; set " + "'managed_gradient_accumulation' to true or disable reflow.") + + # ------------------------------------------------------------------ # + # checkpoint and hp-param access + # ------------------------------------------------------------------ # + # step() returns while background workers still commit the FP32 master and optimizer state, so + # checkpoints and the safe_get/set_* APIs wait for that commit; the training loop does not. + + def state_dict(self): + self._wait_for_pending_state_updates() + return super().state_dict() + + def load_state_dict(self, + state_dict_list, + load_optimizer_states=True, + load_from_fp32_weights=False, + checkpoint_folder=None, + load_serial=None, + param_shapes=None): + # A commit that lands after the load would overwrite the loaded state. + self._wait_for_pending_state_updates() + return super().load_state_dict(state_dict_list, + load_optimizer_states=load_optimizer_states, + load_from_fp32_weights=load_from_fp32_weights, + checkpoint_folder=checkpoint_folder, + load_serial=load_serial, + param_shapes=param_shapes) + + def get_lean_optimizer_state(self): + self._wait_for_pending_state_updates() + return super().get_lean_optimizer_state() + + def _get_fp32_opt_state_partition(self, param, release_swap_buffers, optim_state_key=None): + # Every get/set hp-param API goes through here. + self._wait_for_pending_state_updates() + return super()._get_fp32_opt_state_partition(param, release_swap_buffers, optim_state_key=optim_state_key) diff --git a/deepspeed/runtime/reflow/reflow_utils.py b/deepspeed/runtime/reflow/reflow_utils.py new file mode 100644 index 000000000000..f15513598f33 --- /dev/null +++ b/deepspeed/runtime/reflow/reflow_utils.py @@ -0,0 +1,425 @@ +# Copyright (c) DeepSpeed Team. +# SPDX-License-Identifier: Apache-2.0 + +# DeepSpeed Team +""" +Reflow utilities: NUMA-aware CPU-core/affinity planning for the optimizer worker threads, +plus small contiguous-range helpers for the bucketwise pipeline. These are pure +helpers that hold no optimizer state, so they live in a separate module from the +optimizer itself. +""" + +import os + +import psutil + +import deepspeed.comm as dist +from deepspeed.accelerator import get_accelerator +from deepspeed.utils import logger + + +def resolve_available_cores(): + """Return (total_cpus, available_cores) honoring an existing process affinity.""" + try: + current_process = psutil.Process() + current_affinity = current_process.cpu_affinity() + if current_affinity: + # Process is already pinned (taskset/numactl) - only use those cores. + return len(current_affinity), sorted(current_affinity) + total_cpus = psutil.cpu_count(logical=False) + return total_cpus, list(range(total_cpus)) + except (AttributeError, psutil.AccessDenied): + total_cpus = psutil.cpu_count(logical=False) if hasattr(psutil, 'cpu_count') else 1 + total_cpus = total_cpus if total_cpus and total_cpus > 0 else 1 + return total_cpus, list(range(total_cpus)) + + +def numa_cores_by_id(): + """Return {numa_node_id: [cores]} for non-empty nodes. The key is the real system NUMA node + id (so a GPU's NUMA node maps directly into this dict); empty/HBM nodes are dropped.""" + try: + from deepspeed.utils.numa import get_numa_cores + raw = get_numa_cores() or [] + except Exception: + return {} + return {nid: sorted(int(c) for c in cores) for nid, cores in enumerate(raw) if cores} + + +def gpu_input_count(): + """Number of local GPUs/processes the job was launched with (the 'GPU input'), matching the + num_local_procs DeepSpeed uses for --bind_cores_to_rank core binding. The DeepSpeed launcher + exports it as LOCAL_SIZE; torchrun exports LOCAL_WORLD_SIZE; otherwise fall back to the world + size or the visible device count. This drives the per-rank core split.""" + for var in ("LOCAL_SIZE", "LOCAL_WORLD_SIZE"): + value = os.environ.get(var) + if value is not None: + try: + count = int(value) + if count > 0: + return count + except ValueError: + pass + try: + if dist.is_initialized(): + return max(1, dist.get_world_size()) + except Exception: + pass + try: + return max(1, get_accelerator().device_count()) + except Exception: + return 1 + + +def gpu_numa_node_for_device(device_index): + """Return the NUMA node id that a CUDA device's PCIe link is physically attached to, or -1 + if unknown. Reads the device's PCI address numa_node from sysfs, with an NVML memory-affinity + fallback, so each rank binds to its GPU's real node instead of a positional guess.""" + bdf = None + try: + import torch + p = torch.cuda.get_device_properties(device_index) #ignore-cuda + bdf = f"{p.pci_domain_id:04x}:{p.pci_bus_id:02x}:{p.pci_device_id:02x}.0" + with open(f"/sys/bus/pci/devices/{bdf}/numa_node") as fh: + node = int(fh.read().strip()) + if node >= 0: + return node + except Exception: + pass + try: + import pynvml + pynvml.nvmlInit() + handle = pynvml.nvmlDeviceGetHandleByPciBusId(bdf) if bdf \ + else pynvml.nvmlDeviceGetHandleByIndex(device_index) + affinity = pynvml.nvmlDeviceGetMemoryAffinity(handle, 8, 0) + bits = 0 + for word, value in enumerate(affinity): + bits |= (int(value) << (64 * word)) + for node in range(256): + if bits & (1 << node): + return node + except Exception: + pass + return -1 + + +def gpu_pci_id(device_index): + """Return a unique integer key for a CUDA device's real PCI address (domain/bus/device), used + to order GPUs deterministically across ranks; -1 if unavailable.""" + try: + import torch + p = torch.cuda.get_device_properties(device_index) #ignore-cuda + return (int(p.pci_domain_id) << 24) | (int(p.pci_bus_id) << 16) | (int(p.pci_device_id) << 8) + except Exception: + return -1 + + +def resolve_gpu_numa_assignment(local_rank, local_world_size): + """Return (my_numa_node, num_gpus_sharing_node, my_position_on_node) from the real GPU + PCIe-NUMA topology, considering only the GPUs this job actually uses. + + Preferred path: when distributed is initialized, every participating rank exchanges + (host, gpu-pci-id, gpu-numa-node), so a node's cores are divided only among the job's GPUs on + the same host - correct for any number of physical GPUs and any CUDA_VISIBLE_DEVICES layout. + Fallbacks: locally-visible devices, then the whole node, then (None, ...) when the GPU node + cannot be read. Returns the device count from the job's ranks, never the physical GPU count. + """ + # Distributed gate: globally consistent on every rank (same dist state, same world size), so all + # ranks take the same branch here. + try: + distributed = dist.is_initialized() and dist.get_world_size() > 1 + except Exception: + distributed = False + + if distributed: + # Every rank must reach the collective, even when its topology is unreadable. + # Use a sentinel for missing topology and choose the fallback after the exchange. + import socket + import zlib + import torch + try: + host_id = zlib.crc32(socket.gethostname().encode()) & 0x7fffffff + except Exception: + host_id = -1 + try: + my_dev = get_accelerator().current_device() + except Exception: + my_dev = local_rank if local_rank is not None and local_rank >= 0 else 0 + my_node = gpu_numa_node_for_device(my_dev) + my_pci = gpu_pci_id(my_dev) + row = [int(host_id), int(my_pci), int(my_node)] + local_t = torch.tensor(row, dtype=torch.long, device=get_accelerator().current_device_name()) + gathered = [torch.zeros_like(local_t) for _ in range(dist.get_world_size())] + dist.all_gather(gathered, local_t) + rows = [g.detach().cpu().tolist() for g in gathered] + if my_node < 0 or my_pci < 0: + return None, None, None + # Only this host's GPUs on my NUMA node, ordered by PCI id for a stable split. + same = sorted(pci for h, pci, node in rows if h == host_id and node == my_node and pci >= 0) + if my_pci in same: + return my_node, len(same), same.index(my_pci) + return my_node, None, None + # Single-process (non-distributed) fallback: no collective here, so an early return is safe. + # Derive co-location from the locally-visible job GPUs. + try: + if not get_accelerator().is_available(): + return None, None, None + try: + my_dev = get_accelerator().current_device() + except Exception: + my_dev = local_rank if local_rank is not None and local_rank >= 0 else 0 + my_node = gpu_numa_node_for_device(my_dev) + if my_node < 0: + return None, None, None + visible = get_accelerator().device_count() + count = local_world_size if (local_world_size and local_world_size > 0) else visible + count = min(count, visible) + if count > 0 and local_rank is not None and local_rank >= 0 and local_rank < count: + rank_to_node = {r: gpu_numa_node_for_device(r) for r in range(count)} + if all(node_id >= 0 for node_id in rank_to_node.values()): + co_located = sorted(r for r, node_id in rank_to_node.items() if node_id == my_node) + if local_rank in co_located: + return my_node, len(co_located), co_located.index(local_rank) + return my_node, None, None + except Exception: + return None, None, None + + +def physical_cpu_groups(cpus): + """Group available CPU IDs by the Linux package/core topology, without adding unavailable siblings.""" + groups = {} + for cpu in sorted(cpus): + topology = f"/sys/devices/system/cpu/cpu{cpu}/topology" + try: + with open(f"{topology}/physical_package_id") as handle: + package = int(handle.read()) + with open(f"{topology}/core_id") as handle: + core = int(handle.read()) + except (OSError, ValueError) as error: + raise ValueError("Reflow physical CPU placement requires readable Linux CPU topology") from error + groups.setdefault((package, core), []).append(cpu) + return list(groups.values()) + + +def partition_physical_cpus(cpus, ranks, position): + """Give each local rank whole physical cores so its SMT siblings cannot belong to another rank.""" + groups = physical_cpu_groups(cpus) + if len(groups) < ranks: + raise ValueError("Reflow physical CPU placement requires at least one physical core per local rank") + base, remainder = divmod(len(groups), ranks) + start = position * base + min(position, remainder) + count = base + (position < remainder) + return [cpu for group in groups[start:start + count] for cpu in group] + + +def split_cpu_worker_cores(rank_cores, + node_groups, + main_thread_cores, + main_thread_core_type="logical", + worker_core_type="logical"): + """Reserve main CPUs and keep worker masks within the rank's CPU and NUMA boundaries.""" + physical_groups = None + if main_thread_core_type == "physical" or worker_core_type == "physical": + physical_groups = physical_cpu_groups(rank_cores) + if main_thread_core_type == "physical": + if len(physical_groups) < 2: + raise ValueError("Reflow physical main-thread reservation requires at least two physical cores per rank") + count = min(main_thread_cores, len(physical_groups) - 1) + main_cores = [cpu for group in physical_groups[:count] for cpu in group] + else: + count = min(max(1, int(main_thread_cores)), max(1, len(rank_cores) - 1)) + main_cores = rank_cores[:count] + main_set = set(main_cores) + worker_set = set(rank_cores) - main_set + if worker_core_type == "physical": + worker_set = set() + for group in physical_groups: + available = [cpu for cpu in group if cpu not in main_set] + if available: + worker_set.add(available[0]) + node_worker_groups = [[cpu for cpu in group if cpu in worker_set] for group in node_groups] + node_worker_groups = [group for group in node_worker_groups if group] + if not node_worker_groups: + node_worker_groups = [rank_cores] + worker_cores = [cpu for group in node_worker_groups for cpu in group] + return main_cores, node_worker_groups, worker_cores + + +def heuristic_rank_cores(numa_nodes, local_rank, local_world_size, physical=False): + """Positional NUMA assignment used only when the real GPU->NUMA topology is unavailable.""" + if not numa_nodes: + total = psutil.cpu_count(logical=False) or 1 + return list(range(total)) + n_nodes = len(numa_nodes) + if local_rank < 0: + return sorted(c for node in numa_nodes for c in node) + if local_world_size <= n_nodes: + nodes_per_rank = max(1, n_nodes // max(1, local_world_size)) + start = (local_rank * nodes_per_rank) % n_nodes + chosen = [numa_nodes[(start + k) % n_nodes] for k in range(nodes_per_rank)] + return sorted(c for node in chosen for c in node) + node_index = local_rank % n_nodes + node = numa_nodes[node_index] + ranks_per_node = len(range(node_index, local_world_size, n_nodes)) + pos = local_rank // n_nodes + if physical: + return partition_physical_cpus(node, ranks_per_node, pos) + if ranks_per_node <= len(node): + # Common case: enough cores to give each co-located rank a contiguous chunk. + chunk = max(1, len(node) // ranks_per_node) + start = pos * chunk + return node[start:start + chunk] if start < len(node) else node + # Extreme oversubscription (more co-located ranks than cores): split the node's cores into + # disjoint slices via a base size + remainder so co-located ranks never share a core. Ranks + # past the core count fall back to a degenerate (<1 core/rank) split, so warn once on rank 0. + if local_rank == 0: + logger.warning(f"Reflow NUMA affinity hint: {ranks_per_node} co-located ranks but only " + f"{len(node)} cores on this NUMA node; cores cannot be split disjointly.") + base = len(node) // ranks_per_node + remainder = len(node) % ranks_per_node + start = pos * base + min(pos, remainder) + size = base + (1 if pos < remainder else 0) + return node[start:start + size] + + +def plan_cpu_core_layout(main_thread_cores, main_thread_core_type="logical", worker_core_type="logical"): + """Automatically find NUMA-aware cores for this rank. + + Priority: + 1. If the process is already pinned (numactl/taskset), respect exactly those cores. + 2. Otherwise bind to the NUMA node this rank's GPU is physically attached to (read from the + PCIe topology via sysfs/NVML), splitting that node's cores among the GPUs that share it, + so the CPU optimizer runs on the cores local to the GPU's memory controller. + 3. If the GPU->NUMA topology cannot be read, fall back to a positional NUMA guess. + 4. If no NUMA topology is available at all, fall back to all physical cores. + + Returns (total_cpus, rank_cores, node_worker_groups, main_cores, worker_cores). The worker + cores are grouped per NUMA node so a single worker is never split across two nodes. + """ + node_cores_by_id = numa_cores_by_id() + physical = main_thread_core_type == "physical" or worker_core_type == "physical" + numa_nodes = [node_cores_by_id[nid] for nid in sorted(node_cores_by_id)] + try: + affinity = sorted(psutil.Process().cpu_affinity()) + except (AttributeError, psutil.AccessDenied): + affinity = None + # psutil returns ALL cores when the process is not actually pinned; only treat affinity as an + # explicit pin when it is a strict subset of the machine's cores. + all_cores = set(c for cores in node_cores_by_id.values() for c in cores) + total_visible = len(all_cores) if all_cores else (psutil.cpu_count() or 0) + is_pinned = bool(affinity) and total_visible > 0 and len(affinity) < total_visible + + local_rank = int(os.environ.get("LOCAL_RANK", -1)) + # The GPU input count (DeepSpeed num_local_procs) drives the per-rank core split, matching + # the DeepSpeed --bind_cores_to_rank convention. + local_world_size = gpu_input_count() + # Exchange topology before branching on local affinity so pinned and unpinned ranks + # participate in the same collective. Pinned ranks can ignore the result. + gpu_node, gpu_n_on_node, gpu_pos = resolve_gpu_numa_assignment(local_rank, local_world_size) + + rank_cores = None + if is_pinned: + # Already pinned (e.g. launcher numactl --cpunodebind) - honor it. + rank_cores = affinity + elif node_cores_by_id: + # Bind to the NUMA node this rank's GPU is physically attached to (read from the PCIe + # topology), and split that node's cores evenly among the GPUs that share it. Fall back + # to a positional guess only when the GPU->NUMA topology cannot be read. + my_node, n_on_node, my_pos = gpu_node, gpu_n_on_node, gpu_pos + if my_node is not None and my_node in node_cores_by_id: + node_cores = node_cores_by_id[my_node] + if n_on_node and n_on_node > 1 and my_pos is not None: + if physical: + rank_cores = partition_physical_cpus(node_cores, n_on_node, my_pos) + else: + chunk = max(1, len(node_cores) // n_on_node) + start = my_pos * chunk + rank_cores = node_cores[start:start + chunk] if start < len(node_cores) else node_cores + else: + rank_cores = node_cores + else: + rank_cores = heuristic_rank_cores(numa_nodes, local_rank, local_world_size, physical=physical) + + if not rank_cores: + if physical and affinity: + rank_cores = affinity + else: + total = psutil.cpu_count(logical=False) or 1 + rank_cores = list(range(total)) + rank_cores = sorted(rank_cores) + total_cpus = len(rank_cores) + + # Group this rank's cores by NUMA node so worker masks stay within a single node. + rank_set = set(rank_cores) + node_groups = [] + for node in numa_nodes: + cores_on_node = [c for c in node if c in rank_set] + if cores_on_node: + node_groups.append(cores_on_node) + accounted = set(c for node_group in node_groups for c in node_group) + leftover = [c for c in rank_cores if c not in accounted] + if leftover: + node_groups.append(sorted(leftover)) + if not node_groups: + node_groups = [rank_cores] + main_cores, node_worker_groups, worker_cores = split_cpu_worker_cores(rank_cores, node_groups, main_thread_cores, + main_thread_core_type, worker_core_type) + return total_cpus, rank_cores, node_worker_groups, main_cores, worker_cores + + +def merge_contiguous_ranges(ranges): + # Merge contiguous (offset, size) tuples to reduce copy call overhead. + if not ranges: + return [] + ranges_sorted = sorted(ranges, key=lambda x: x[0]) + merged = [] + cur_off, cur_sz = ranges_sorted[0] + for off, sz in ranges_sorted[1:]: + if off == cur_off + cur_sz: + cur_sz += sz + else: + merged.append((cur_off, cur_sz)) + cur_off, cur_sz = off, sz + merged.append((cur_off, cur_sz)) + return merged + + +def clip_range_to_valid_partition(valid_partition_element_count, dest_offset, num_elements): + """Clamp a single (dest_offset, num_elements) range to the valid partition. + + Returns (offset, size) clamped so it never extends past valid_partition_element_count, + or None if the range starts at or beyond the valid region (i.e. it is entirely padding). + """ + if dest_offset >= valid_partition_element_count: + return None + clipped_num_elements = min(int(num_elements), valid_partition_element_count - int(dest_offset)) + if clipped_num_elements <= 0: + return None + return (int(dest_offset), int(clipped_num_elements)) + + +def clip_ranges_to_valid_partition(ranges, valid_partition_element_count): + """Clamp a list of (offset, size) ranges to the valid partition, dropping empties.""" + clipped = [] + for off, sz in ranges: + clipped_range = clip_range_to_valid_partition(valid_partition_element_count, off, sz) + if clipped_range is not None: + clipped.append(clipped_range) + return clipped + + +def split_ranges_by_min_size(merged_ranges, min_range_elems): + """Partition merged ranges into (submit, pending) by a minimum element threshold. + + Ranges whose size is >= min_range_elems are returned in ``submit``; smaller ranges are + returned in ``pending`` and their total element count is returned as ``pending_elems``. + """ + submit = [] + pending = [] + pending_elems = 0 + for off, sz in merged_ranges: + if sz >= min_range_elems: + submit.append((off, sz)) + else: + pending.append((off, sz)) + pending_elems += sz + return submit, pending, pending_elems diff --git a/deepspeed/runtime/zero/config.py b/deepspeed/runtime/zero/config.py index 427b5507306c..db6ba629611c 100644 --- a/deepspeed/runtime/zero/config.py +++ b/deepspeed/runtime/zero/config.py @@ -11,6 +11,7 @@ from deepspeed.utils import logger from .offload_config import DeepSpeedZeroOffloadParamConfig, DeepSpeedZeroOffloadOptimizerConfig, OffloadDeviceEnum from deepspeed.runtime.zenflow.zenflow_config import ZenFlowConfig +from deepspeed.runtime.reflow.reflow_config import ReflowConfig from .leaf_module_config import DeepSpeedZeroLeafModuleConfig # ZeRO optimization. By default, this optimization is not enabled. @@ -179,6 +180,14 @@ class DeepSpeedZeroConfig(DeepSpeedConfigModel): zenflow: Optional[ZenFlowConfig] = None """Enable ZenFlow""" + reflow: Optional[ReflowConfig] = None + """ + Enable Reflow, the asynchronous CPU-offload optimizer for ZeRO stage 3: the CPU optimizer runs + per gradient bucket during backward and commits its state in the background, overlapping GPU + compute instead of running as a phase after backward. Requires optimizer offload to CPU. + Expects a dictionary containing values for :any:`ReflowConfig`. + """ + sub_group_size: int = Field(pp_int(1e9), ge=0) """ Tile size for parameter processing to fit massive models (with trillions of @@ -406,3 +415,22 @@ def elastic_checkpoint_deprecated(self): "ZeRO-3 elastic checkpointing is deprecated and no longer supported. Use Universal Checkpointing instead." ) return self + + @model_validator(mode="after") + def reflow_compat_check(self): + # Reflow is its own ZeRO-3 optimizer path; reject what it cannot wrap here, so the user gets a + # clear config error instead of a downstream failure at optimizer build time. + if self.reflow is None: + return self + if self.stage != ZeroStageEnum.weights: + raise ValueError(f"Reflow requires ZeRO stage 3, got stage {int(self.stage)}.") + offload_config = self.offload_optimizer + if offload_config is None or offload_config.device not in (OffloadDeviceEnum.cpu, OffloadDeviceEnum.nvme): + # Reflow runs the optimizer on CPU. device='cpu' keeps its state in CPU memory; device='nvme' + # additionally swaps that state per subgroup around the CPU step. + raise ValueError("Reflow requires optimizer offload with device 'cpu' or 'nvme'.") + if self.zenflow is not None: + raise ValueError("Reflow is not compatible with ZenFlow; enable only one of them.") + if offload_config.super_offload: + raise ValueError("Reflow is not compatible with super_offload; enable only one of them.") + return self diff --git a/deepspeed/runtime/zero/partitioned_param_coordinator.py b/deepspeed/runtime/zero/partitioned_param_coordinator.py index 2ca8cc4c038d..f22b326a8ecc 100644 --- a/deepspeed/runtime/zero/partitioned_param_coordinator.py +++ b/deepspeed/runtime/zero/partitioned_param_coordinator.py @@ -159,6 +159,20 @@ def __init__( # remove a specific module, since multi-tensor z3-leaf hooks fire out of reverse order. self.__active_backward_submodules: Dict[int, Module] = {} + def wait_for_external_allgather_dependencies(self, events) -> None: + """Make future param all-gathers wait for external GPU writes. + + Reflow writes updated fp16/bf16 parameter partitions on its own H2D stream. With overlap_comm + the all-gather runs on its own stream, so a compute-stream wait alone would not order those + reads after the H2D writes. + """ + if not events or get_accelerator().is_synchronized_device(): + return + with get_accelerator().stream(self.__allgather_stream): + for event in events: + if event is not None: + self.__allgather_stream.wait_event(event) + """Tracing and Tracking TODO. consider performing trace before initializing PartitionedParameterCoordinator and passing trace results into constructor. This way all the code in here can diff --git a/deepspeed/runtime/zero/utils.py b/deepspeed/runtime/zero/utils.py index 689fe77df75f..c47bceba409c 100755 --- a/deepspeed/runtime/zero/utils.py +++ b/deepspeed/runtime/zero/utils.py @@ -62,6 +62,15 @@ class ZeRORuntimeException(Exception): except ImportError: pass +# Add ReflowCPUAdam / ReflowCPULion (Reflow async CPU-offload optimizer) to supported list +try: + from deepspeed.runtime.reflow.reflow_cpu_adam import ReflowCPUAdam + from deepspeed.runtime.reflow.reflow_cpu_lion import ReflowCPULion + ZERO_SUPPORTED_OPTIMIZERS.append(ReflowCPUAdam) + ZERO_SUPPORTED_OPTIMIZERS.append(ReflowCPULion) +except ImportError: + pass + def get_norm_dtype(): """Gradient norms accumulate in fp64 for accuracy, except on devices without fp64 (e.g. MPS).""" diff --git a/deepspeed/utils/numa.py b/deepspeed/utils/numa.py index 8232547210b3..6c3d4e269a98 100644 --- a/deepspeed/utils/numa.py +++ b/deepspeed/utils/numa.py @@ -14,6 +14,8 @@ import shutil import subprocess +from .logging import logger + # return a list of list for cores to numa mapping # [ @@ -62,6 +64,22 @@ def check_for_numactl_pkg(): return found +def numactl_cmd_error(numactl_cmd): + """Dry-run numactl with a no-op program. Returns None on success, else the error message.""" + try: + result = subprocess.run(numactl_cmd + ["true"], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) + except OSError as e: + return str(e) + if result.returncode == 0: + return None + return result.stderr.decode("utf-8").strip().replace("\n", "; ") + + +def _numactl_permission_error(error): + message = error.lower() + return "operation not permitted" in message or "permission denied" in message + + def parse_range(rng): try: value = int(rng) @@ -202,4 +220,22 @@ def get_numactl_cmd(bind_core_list, num_local_procs, local_rank): if first_core != last_core: core_list_str = f"{core_list_str}-{last_core}" numactl_cmd.append(f"{core_list_str}") - return cores_per_rank, numactl_cmd + + # Containers without CAP_SYS_NICE reject NUMA memory policies (-m/-p) with "Operation not + # permitted", which would kill every rank at spawn. Degrade gracefully instead of failing. + error = numactl_cmd_error(numactl_cmd) + if error is None: + return cores_per_rank, numactl_cmd + if not _numactl_permission_error(error): + raise RuntimeError(f"'{' '.join(numactl_cmd)}' failed: {error}") + cpu_only_cmd = ["numactl", "-C", core_list_str] + cpu_only_error = numactl_cmd_error(cpu_only_cmd) + if cpu_only_error is None: + logger.warning(f"'{' '.join(numactl_cmd)}' failed ({error}). " + f"Falling back to CPU binding without NUMA memory binding: '{' '.join(cpu_only_cmd)}'") + return cores_per_rank, cpu_only_cmd + if not _numactl_permission_error(cpu_only_error): + raise RuntimeError(f"'{' '.join(cpu_only_cmd)}' failed: {cpu_only_error}") + logger.warning(f"'{' '.join(cpu_only_cmd)}' failed ({cpu_only_error}). " + "Launching without numactl core/memory binding.") + return cores_per_rank, [] diff --git a/deepspeed/utils/timer.py b/deepspeed/utils/timer.py index 65506cb6df7b..c4553a2abaf8 100644 --- a/deepspeed/utils/timer.py +++ b/deepspeed/utils/timer.py @@ -198,7 +198,14 @@ def get_mean(self, names, normalizer=1.0, reset=True): class ThroughputTimer: - def __init__(self, config, batch_size, start_step=2, steps_per_output=None, monitor_memory=False, logging_fn=None): + def __init__(self, + config, + batch_size, + start_step=2, + steps_per_output=None, + monitor_memory=False, + logging_fn=None, + sync_current_stream=False): from deepspeed.utils import logger self.config = config self.start_time = 0 @@ -217,6 +224,9 @@ def __init__(self, config, batch_size, start_step=2, steps_per_output=None, moni if self.logging is None: self.logging = logger.info self.initialized = False + # Reflow auto-enables this: with CPU-offload side streams, sync only the current + # stream so the timer does not serialize them. Default preserves the full device sync. + self.sync_current_stream = sync_current_stream if self.monitor_memory and not PSUTILS_INSTALLED: raise ImportError("Unable to import 'psutils', please install package") @@ -228,6 +238,12 @@ def update_epoch_count(self): def _init_timer(self): self.initialized = True + def _synchronize(self): + if self.sync_current_stream: + get_accelerator().current_stream().synchronize() + else: + get_accelerator().synchronize() + def start(self): if not self.config.enabled: return @@ -235,7 +251,7 @@ def start(self): self.started = True if self.global_step_count >= self.start_step: if self.config.synchronized: - get_accelerator().synchronize() + self._synchronize() self.start_time = time.time() def _is_report_boundary(self): @@ -253,7 +269,7 @@ def stop(self, global_step=False, report_speed=True): if self.start_time > 0: if self.config.synchronized: - get_accelerator().synchronize() + self._synchronize() self.end_time = time.time() duration = self.end_time - self.start_time self.total_elapsed_time += duration diff --git a/docs/_data/navigation.yml b/docs/_data/navigation.yml index 47f992f3f5ca..2d6b530856d7 100755 --- a/docs/_data/navigation.yml +++ b/docs/_data/navigation.yml @@ -101,6 +101,8 @@ lnav: url: /tutorials/one-cycle/ - title: 'Pipeline Parallelism' url: /tutorials/pipeline/ + - title: 'Reflow' + url: /tutorials/reflow/ - title: 'Transformer Kernel' url: /tutorials/transformer_kernel/ - title: 'Arctic Long Sequence Training (ALST) for HF Transformers integration' diff --git a/docs/_pages/config-json.md b/docs/_pages/config-json.md index b78b0dd44310..b59da1ed3f00 100644 --- a/docs/_pages/config-json.md +++ b/docs/_pages/config-json.md @@ -687,6 +687,49 @@ Note that if the value of "device" is not specified or not supported, an asserti | ------------------------------------------------------------- | ------- | | Enable fast optimizer initialization when offloading to NVMe. | `false` | +### Reflow +[Reflow](/tutorials/reflow/) is an asynchronous CPU-offload optimizer for ZeRO stage 3. The CPU optimizer runs per gradient bucket during backward, gradients move to CPU in half precision, and the FP32 master weights and optimizer state are committed in the background while the next forward runs. + +The `reflow` block enables it, so an empty block is enough to run with the defaults. Reflow requires `"stage": 3` with `offload_optimizer` on `cpu` (or `nvme`), and a CPU Adam build with AVX2 or AVX-512. It uses `ReflowCPUAdam`/`ReflowCPULion`; a client `DeepSpeedCPUAdam`/`DeepSpeedCPULion` is remapped automatically. It is not compatible with `super_offload`, ZenFlow, DeepCompile, the Muon optimizer (support to be implemented), or `managed_gradient_accumulation: false`. +```json + "reflow": { + "num_threads": null, + "enable_cpu_affinity": false, + "main_thread_cores": 3, + "bucketwise_cores_per_worker": 1, + "state_update_cores": 2 + } +``` +***num_threads***: [integer] + +| Description | Default | +| ----------- | ------- | +| Threads for the CPU optimizer kernels. When unset, all cores available to the rank are used. | `null` | + +***enable_cpu_affinity***: [boolean] + +| Description | Default | +| ----------- | ------- | +| Pin the main (forward/backward) thread and the optimizer workers to separate NUMA-local CPU cores. | `false` | + +***main_thread_cores***: [integer] + +| Description | Default | +| ----------- | ------- | +| CPU cores reserved for the main thread when `enable_cpu_affinity` is true; the remaining cores go to the optimizer workers. | `3` | + +***bucketwise_cores_per_worker***: [integer] + +| Description | Default | +| ----------- | ------- | +| CPU cores per bucketwise optimizer worker; the worker count is the rank's worker cores divided by this value. | `1` | + +***state_update_cores***: [integer] + +| Description | Default | +| ----------- | ------- | +| Worker cores the background optimizer-state commit uses while it overlaps the next forward. Fewer busy cores keep the CPU at a higher turbo frequency for the forward; once backward starts, the commit uses every worker core. | `2` | + ### Asynchronous I/O Configuring the asynchronous I/O module for offloading parameter and optimizer states to persistent (NVMe) storage. This module uses Linux native asynchronous I/O (libaio). diff --git a/docs/_tutorials/reflow.md b/docs/_tutorials/reflow.md new file mode 100644 index 000000000000..01c6e8b46f82 --- /dev/null +++ b/docs/_tutorials/reflow.md @@ -0,0 +1,84 @@ +--- +title: "Reflow" +tags: training IO large-model +--- +Reflow is an asynchronous CPU-offload optimizer for ZeRO stage 3. Like [ZeRO-Offload](/tutorials/zero-offload/), it keeps the FP32 master weights and the optimizer state on the CPU and runs the optimizer there. The difference is *when* that CPU work runs: instead of a serial optimizer phase after backward, Reflow overlaps it with GPU compute, so the iteration spends less time waiting on the CPU. + +We recommend that you read the tutorials on [ZeRO](/tutorials/zero/) and [ZeRO-Offload](/tutorials/zero-offload/) before this one. + +## How Reflow works + +Adding a `reflow` block to `zero_optimization` turns on three cooperating behaviors: + +1. **Per-bucket optimizer during backward.** As each gradient bucket is reduced, its CPU optimizer update is submitted to a background worker, so the optimizer overlaps the rest of backward and the gradient reduce-scatter. +2. **Half-precision gradient transfer.** Gradients are copied to CPU in FP16/BF16 and promoted to FP32 inside the AVX kernel. This halves the GPU-to-CPU traffic and removes the CPU-side FP32 gradient buffer. +3. **Asynchronous state commit.** The foreground only produces the new FP16/BF16 parameters. The FP32 master weights and optimizer state are committed by a background worker after the gradient clipping and overflow checks, overlapping the next forward. + +Checkpoint APIs (`state_dict`, `load_state_dict`, and the `safe_get_*`/`safe_set_*` helpers) wait for that background commit, so they always see the fully applied step. + +## Configuration + +Reflow needs no model code changes. Enable it in the DeepSpeed configuration: + +```json +{ + "zero_optimization": { + "stage": 3, + "overlap_comm": true, + "offload_optimizer": { + "device": "cpu", + "pin_memory": true + }, + "reflow": { + "enable_cpu_affinity": true, + "main_thread_cores": 2, + "bucketwise_cores_per_worker": 8, + "state_update_cores": 2 + } + }, + "optimizer": { + "type": "AdamW", + "params": { + "lr": 1e-5 + } + } +} +``` + +DeepSpeed builds `ReflowCPUAdam` (or `ReflowCPULion` for Lion) for this configuration. A client `DeepSpeedCPUAdam`/`DeepSpeedCPULion` or PyTorch `Adam`/`AdamW` passed to `deepspeed.initialize` is remapped automatically. If you pass a client optimizer and an LR scheduler, pass a scheduler factory that accepts the remapped optimizer, or configure the scheduler in the DeepSpeed config. A scheduler already bound to the original optimizer is rejected. An empty `"reflow": {}` runs with the defaults; see the [configuration reference](/docs/config-json/#reflow) for every option. + +Launch with `--bind_cores_to_rank` so each rank runs on the CPU cores local to its GPU: + +```bash +deepspeed --bind_cores_to_rank train.py --deepspeed_config ds_config.json +``` + +Reflow always pins optimizer workers to NUMA-local cores and reserves `main_thread_cores` from those workers. `enable_cpu_affinity` additionally restricts the main process to its NUMA-local core slice. The remaining cores are split into workers of `bucketwise_cores_per_worker` cores. While the state commit overlaps the forward it uses only `state_update_cores` cores: every busy core lowers the CPU's turbo frequency, which would slow the launch-bound forward. + +## Gradient clipping + +The bucketwise workers apply the update before the global gradient norm is known. When a step actually needs clipping, Reflow recomputes that step's update with the clipped scale inside `step()`, so the step pays the full optimizer cost. DeepSpeed's `gradient_clipping` defaults to `1.0`; set it to `0.0` when you do not want clipping. With or without clipping, the loss matches ZeRO-Offload bit for bit in the unit tests. + +## Performance + +OPT-350m fine-tuning on one NVIDIA RTX 5080 with an Intel Xeon w7-3445 (batch 4, sequence length 2048, bf16, activation checkpointing, Alpaca 10%, `gradient_clipping: 0.0`). These measurements use the Reflow example's `finetune_zero3.py`, `--bind_cores_to_rank`, and `overlap_comm: false`. Times are the mean of steps 11–60 after 10 warmup steps (September 2026): + +| | ZeRO-Offload (ZeRO-3 + CPU optimizer offload) | Reflow | +| --- | --- | --- | +| Optimizer step | 268 ms | 57 ms | +| Iteration | 796 ms | 523 ms | + +With `gradient_clipping: 1.0` in the same setup, Reflow's optimizer step averaged 138 ms and the iteration 606 ms because clipping recomputes the update as described above. + +## Limitations + +- ZeRO stage 3 with `offload_optimizer.device` set to `cpu`; any other stage or device is rejected when the configuration is parsed. NVMe optimizer offload is accepted but is not covered by tests. +- The CPU Adam/Lion extension must be built with AVX2 or AVX-512; Reflow raises an error when it creates the optimizer on other builds. +- Not supported with `super_offload`, ZenFlow, DeepCompile, the Muon optimizer, or `managed_gradient_accumulation: false`. The first four are rejected at initialization. +- Muon support needs to be implemented in the future. Reflow's CPU step applies its Adam/Lion kernels to every subgroup, so Muon's orthogonalized update needs its own path through the two-phase step. +- Per-parameter ZeRO-3 partition groups (for example AutoEP expert parallelism) run, but this combination is not validated and may produce wrong results. Reflow logs a warning when it sees such parameters. +- Each subgroup keeps a double half-precision gradient buffer on the CPU by default. A single-buffer mode (`REFLOW_SINGLE_GRAD_BUFFER=1`) exists but is not fully implemented yet; runs it does not support fall back to the double buffer with a warning. + +## Questions and maintenance + +Reflow is maintained by [@st-bang97](https://github.com/st-bang97). Please tag me on GitHub issues about it. diff --git a/docs/code-docs/source/optimizers.rst b/docs/code-docs/source/optimizers.rst index 9a58cd523f25..3dbf77d4e5e3 100755 --- a/docs/code-docs/source/optimizers.rst +++ b/docs/code-docs/source/optimizers.rst @@ -7,6 +7,14 @@ Adam (CPU) ---------------------------- .. autoclass:: deepspeed.ops.adam.DeepSpeedCPUAdam +Reflow Adam (CPU, ZeRO-3 asynchronous offload) +---------------------------------------------- +.. autoclass:: deepspeed.runtime.reflow.reflow_cpu_adam.ReflowCPUAdam + +Reflow Lion (CPU, ZeRO-3 asynchronous offload) +---------------------------------------------- +.. autoclass:: deepspeed.runtime.reflow.reflow_cpu_lion.ReflowCPULion + FusedAdam (GPU) ---------------------------- .. autoclass:: deepspeed.ops.adam.FusedAdam diff --git a/docs/code-docs/source/zero3.rst b/docs/code-docs/source/zero3.rst index bf13227153f2..f987f02706a8 100644 --- a/docs/code-docs/source/zero3.rst +++ b/docs/code-docs/source/zero3.rst @@ -59,7 +59,7 @@ The dictionary provided under the ``zero_optimization`` entry of the main DeepSpeed configuration dict will be parsed and validated with this class. Sub-configurations for parameter offload and optimizer offload settings are parsed by `DeepSpeedZeroOffloadParamConfig`_ and -`DeepSpeedZeroOffloadOptimizerConfig`_. +`DeepSpeedZeroOffloadOptimizerConfig`_, and the Reflow settings by `ReflowConfig`_. .. _DeepSpeedZeroConfig: .. autopydantic_model:: deepspeed.runtime.zero.config.DeepSpeedZeroConfig @@ -70,6 +70,9 @@ parsed by `DeepSpeedZeroOffloadParamConfig`_ and .. _DeepSpeedZeroOffloadOptimizerConfig: .. autopydantic_model:: deepspeed.runtime.zero.config.DeepSpeedZeroOffloadOptimizerConfig +.. _ReflowConfig: +.. autopydantic_model:: deepspeed.runtime.reflow.reflow_config.ReflowConfig + Example ZeRO-3 Configurations ============================= diff --git a/op_builder/cpu/cpu_adam.py b/op_builder/cpu/cpu_adam.py index 0c8438aea40d..e3237e874605 100644 --- a/op_builder/cpu/cpu_adam.py +++ b/op_builder/cpu/cpu_adam.py @@ -17,7 +17,10 @@ def absolute_name(self): return f'deepspeed.ops.adam.{self.NAME}_op' def sources(self): - return ['csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp'] + return [ + 'csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp', 'csrc/adam/reflow_cpu_adam_impl.cpp', + 'csrc/adam/reflow_cpu_adam_bindings.cpp' + ] def libraries_args(self): args = super().libraries_args() diff --git a/op_builder/cpu_adam.py b/op_builder/cpu_adam.py index 7f4c0847a8c4..982c295bf610 100644 --- a/op_builder/cpu_adam.py +++ b/op_builder/cpu_adam.py @@ -17,7 +17,10 @@ def absolute_name(self): return f'deepspeed.ops.adam.{self.NAME}_op' def sources(self): - return ['csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp'] + return [ + 'csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp', 'csrc/adam/reflow_cpu_adam_impl.cpp', + 'csrc/adam/reflow_cpu_adam_bindings.cpp' + ] def libraries_args(self): args = super().libraries_args() diff --git a/op_builder/cpu_lion.py b/op_builder/cpu_lion.py index 9a60d99773b3..72683a3ab925 100644 --- a/op_builder/cpu_lion.py +++ b/op_builder/cpu_lion.py @@ -17,7 +17,10 @@ def absolute_name(self): return f'deepspeed.ops.lion.{self.NAME}_op' def sources(self): - return ['csrc/lion/cpu_lion.cpp', 'csrc/lion/cpu_lion_impl.cpp'] + return [ + 'csrc/lion/cpu_lion.cpp', 'csrc/lion/cpu_lion_impl.cpp', 'csrc/lion/reflow_cpu_lion_impl.cpp', + 'csrc/lion/reflow_cpu_lion_bindings.cpp' + ] def libraries_args(self): args = super().libraries_args() diff --git a/op_builder/hpu/cpu_adam.py b/op_builder/hpu/cpu_adam.py index 58eea2698ebb..6b98589ffb30 100644 --- a/op_builder/hpu/cpu_adam.py +++ b/op_builder/hpu/cpu_adam.py @@ -18,7 +18,10 @@ def absolute_name(self): return f'deepspeed.ops.adam.{self.NAME}_op' def sources(self): - return ['csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp'] + return [ + 'csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp', 'csrc/adam/reflow_cpu_adam_impl.cpp', + 'csrc/adam/reflow_cpu_adam_bindings.cpp' + ] def libraries_args(self): args = super().libraries_args() diff --git a/op_builder/mlu/cpu_adam.py b/op_builder/mlu/cpu_adam.py index b3c8e476bf39..4d7141217221 100644 --- a/op_builder/mlu/cpu_adam.py +++ b/op_builder/mlu/cpu_adam.py @@ -18,7 +18,10 @@ def absolute_name(self): return f'deepspeed.ops.adam.{self.NAME}_op' def sources(self): - return ['csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp'] + return [ + 'csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp', 'csrc/adam/reflow_cpu_adam_impl.cpp', + 'csrc/adam/reflow_cpu_adam_bindings.cpp' + ] def libraries_args(self): args = super().libraries_args() diff --git a/op_builder/mps/cpu_adam.py b/op_builder/mps/cpu_adam.py index 6d5f57c50bad..cc4a87f30c74 100644 --- a/op_builder/mps/cpu_adam.py +++ b/op_builder/mps/cpu_adam.py @@ -24,7 +24,10 @@ def absolute_name(self): return f'deepspeed.ops.adam.{self.NAME}_op' def sources(self): - return ['csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp'] + return [ + 'csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp', 'csrc/adam/reflow_cpu_adam_impl.cpp', + 'csrc/adam/reflow_cpu_adam_bindings.cpp' + ] def include_paths(self): return ['csrc/includes'] diff --git a/op_builder/npu/cpu_adam.py b/op_builder/npu/cpu_adam.py index a4e9569c0f33..4e45194cb916 100644 --- a/op_builder/npu/cpu_adam.py +++ b/op_builder/npu/cpu_adam.py @@ -17,7 +17,10 @@ def absolute_name(self): return f'deepspeed.ops.adam.{self.NAME}_op' def sources(self): - return ['csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp'] + return [ + 'csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp', 'csrc/adam/reflow_cpu_adam_impl.cpp', + 'csrc/adam/reflow_cpu_adam_bindings.cpp' + ] def include_paths(self): args = super().include_paths() diff --git a/op_builder/npu/cpu_lion.py b/op_builder/npu/cpu_lion.py index 6917e0fd03d0..c8113bc13e33 100644 --- a/op_builder/npu/cpu_lion.py +++ b/op_builder/npu/cpu_lion.py @@ -17,7 +17,10 @@ def absolute_name(self): return f'deepspeed.ops.lion.{self.NAME}_op' def sources(self): - return ['csrc/lion/cpu_lion.cpp', 'csrc/lion/cpu_lion_impl.cpp'] + return [ + 'csrc/lion/cpu_lion.cpp', 'csrc/lion/cpu_lion_impl.cpp', 'csrc/lion/reflow_cpu_lion_impl.cpp', + 'csrc/lion/reflow_cpu_lion_bindings.cpp' + ] def include_paths(self): args = super().include_paths() diff --git a/op_builder/sdaa/cpu_adam.py b/op_builder/sdaa/cpu_adam.py index b38a71a6275d..3848c2a67dde 100755 --- a/op_builder/sdaa/cpu_adam.py +++ b/op_builder/sdaa/cpu_adam.py @@ -43,7 +43,10 @@ def absolute_name(self): return f'deepspeed.ops.adam.{self.NAME}_op' def sources(self): - return ['csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp'] + return [ + 'csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp', 'csrc/adam/reflow_cpu_adam_impl.cpp', + 'csrc/adam/reflow_cpu_adam_bindings.cpp' + ] def libraries_args(self): args = super().libraries_args() diff --git a/op_builder/supa/cpu_adam.py b/op_builder/supa/cpu_adam.py index 66f64079531a..4a1093fe4b71 100644 --- a/op_builder/supa/cpu_adam.py +++ b/op_builder/supa/cpu_adam.py @@ -15,7 +15,10 @@ def absolute_name(self): return f'deepspeed.ops.adam.{self.NAME}_op' def sources(self): - return ['csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp'] + return [ + 'csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp', 'csrc/adam/reflow_cpu_adam_impl.cpp', + 'csrc/adam/reflow_cpu_adam_bindings.cpp' + ] def include_paths(self): args = super().include_paths() diff --git a/op_builder/supa/cpu_lion.py b/op_builder/supa/cpu_lion.py index 8d77ce275c42..522da669561f 100644 --- a/op_builder/supa/cpu_lion.py +++ b/op_builder/supa/cpu_lion.py @@ -15,7 +15,10 @@ def absolute_name(self): return f'deepspeed.ops.lion.{self.NAME}_op' def sources(self): - return ['csrc/lion/cpu_lion.cpp', 'csrc/lion/cpu_lion_impl.cpp'] + return [ + 'csrc/lion/cpu_lion.cpp', 'csrc/lion/cpu_lion_impl.cpp', 'csrc/lion/reflow_cpu_lion_impl.cpp', + 'csrc/lion/reflow_cpu_lion_bindings.cpp' + ] def include_paths(self): args = super().include_paths() diff --git a/op_builder/xpu/cpu_adam.py b/op_builder/xpu/cpu_adam.py index 9d5fdcd3e8ab..614e7215ef0b 100644 --- a/op_builder/xpu/cpu_adam.py +++ b/op_builder/xpu/cpu_adam.py @@ -17,7 +17,10 @@ def absolute_name(self): return f'deepspeed.ops.adam.{self.NAME}_op' def sources(self): - return ['csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp'] + return [ + 'csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp', 'csrc/adam/reflow_cpu_adam_impl.cpp', + 'csrc/adam/reflow_cpu_adam_bindings.cpp' + ] def libraries_args(self): args = super().libraries_args() diff --git a/tests/unit/launcher/test_ds_arguments.py b/tests/unit/launcher/test_ds_arguments.py index ee6d4ce6b7be..c3fdb8248256 100644 --- a/tests/unit/launcher/test_ds_arguments.py +++ b/tests/unit/launcher/test_ds_arguments.py @@ -4,9 +4,10 @@ # DeepSpeed Team import argparse +import os import pytest import deepspeed -from deepspeed.utils.numa import parse_range_list +from deepspeed.utils.numa import get_numactl_cmd, parse_range_list def basic_parser(): @@ -131,3 +132,64 @@ def test_core_binding_arguments(): else: # invalid core list must fail assert False + + +FAKE_NUMACTL = """#!/bin/sh +# Stand-in for numactl: reports one 8-core NUMA node and rejects the options listed in +# FAKE_NUMACTL_DENIED, the way a container without CAP_SYS_NICE rejects memory policies. +if [ "$1" = "--hardware" ]; then + echo "available: 1 nodes (0)" + echo "node 0 cpus: 0 1 2 3 4 5 6 7" + exit 0 +fi +if [ "$1" = "-C" ] && [ -n "$FAKE_NUMACTL_CPU_ERROR" ]; then + echo "$FAKE_NUMACTL_CPU_ERROR" >&2 + exit 1 +fi +for arg in "$@"; do + case " $FAKE_NUMACTL_DENIED " in + *" $arg "*) + echo "${FAKE_NUMACTL_ERROR:-set_mempolicy: Operation not permitted}" >&2 + exit 1 + ;; + esac +done +exit 0 +""" + + +@pytest.mark.parametrize("denied_options, expected_cmd", [ + ("", ["numactl", "-m", "0", "-C", "0-3"]), + ("-m", ["numactl", "-C", "0-3"]), + ("-m -C", []), +]) +def test_numactl_cmd_fallback(tmp_path, monkeypatch, denied_options, expected_cmd): + # Launching a rank must not fail just because numactl rejects some binding options. + fake_numactl = tmp_path / "numactl" + fake_numactl.write_text(FAKE_NUMACTL) + fake_numactl.chmod(0o755) + monkeypatch.setenv("PATH", f"{tmp_path}{os.pathsep}{os.environ['PATH']}") + monkeypatch.setenv("FAKE_NUMACTL_DENIED", denied_options) + monkeypatch.delenv("KMP_AFFINITY", raising=False) + + cores_per_rank, numactl_cmd = get_numactl_cmd("0-7", 2, 0) + assert cores_per_rank == 4 + assert numactl_cmd == expected_cmd + + +def test_numactl_cmd_rejects_invalid_binding(tmp_path, monkeypatch): + fake_numactl = tmp_path / "numactl" + fake_numactl.write_text(FAKE_NUMACTL) + fake_numactl.chmod(0o755) + monkeypatch.setenv("PATH", f"{tmp_path}{os.pathsep}{os.environ['PATH']}") + monkeypatch.setenv("FAKE_NUMACTL_DENIED", "-m") + monkeypatch.setenv("FAKE_NUMACTL_ERROR", "numactl: invalid NUMA node") + monkeypatch.delenv("KMP_AFFINITY", raising=False) + + with pytest.raises(RuntimeError, match="invalid NUMA node"): + get_numactl_cmd("0-7", 2, 0) + + monkeypatch.setenv("FAKE_NUMACTL_ERROR", "set_mempolicy: Operation not permitted") + monkeypatch.setenv("FAKE_NUMACTL_CPU_ERROR", "numactl: invalid CPU list") + with pytest.raises(RuntimeError, match="invalid CPU list"): + get_numactl_cmd("0-7", 2, 0) diff --git a/tests/unit/v1/ops/test_reflow_cpu_optimizers.py b/tests/unit/v1/ops/test_reflow_cpu_optimizers.py new file mode 100644 index 000000000000..405c68011fa8 --- /dev/null +++ b/tests/unit/v1/ops/test_reflow_cpu_optimizers.py @@ -0,0 +1,300 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team +""" +Drop-in equivalence tests for the Reflow CPU-Adam and CPU-Lion kernels (the async CPU-offload path). + +Reflow splits one optimizer step into two passes over the same tensors: + * Phase-1 (``reflow_*_update_params_halfgrad``): from the FP32 master, the half-precision grad and the + optimizer state, produce ONLY the new BF16/FP16 weights into a separate buffer. The FP32 master and + the state are left untouched (deferred). + * Phase-2 (``reflow_*_update_state_halfgrad``): commit the FP32 master and the state. + +The reference is the base ``DeepSpeedCPUAdam`` / ``DeepSpeedCPULion`` step, so these prove the Reflow +kernels are a faithful drop-in. They run purely on CPU; no GPU/distributed env is required. +""" + +import pytest +import torch +from cpuinfo import get_cpu_info + +import deepspeed +from deepspeed.ops.op_builder import CPUAdamBuilder, CPULionBuilder + +pytest.cpu_vendor = get_cpu_info()["vendor_id_raw"].lower() if "vendor_id_raw" in get_cpu_info() else "unknown" + +# One shared opt_id counter so each parametrized case uses an isolated native reflow optimizer. +_opt_id = 0 + + +def _next_opt_id(): + global _opt_id + _opt_id += 1 + return _opt_id + + +def _skip_amd_fp16(grad_dtype): + if ("amd" in pytest.cpu_vendor) and (grad_dtype == torch.half): + pytest.skip("cpu optimizers with half precision not supported on AMD CPUs") + + +def _skip_without_avx(builder): + # The Reflow kernels exist only for AVX2/AVX-512; on other builds creating the optimizer raises. + if builder().simd_width() not in ("-D__AVX512__", "-D__AVX256__"): + pytest.skip("the CPU optimizer extension is not built with AVX2 or AVX-512") + + +def test_every_builder_of_the_shared_bindings_compiles_the_reflow_kernels(): + """The Reflow entry points are bound in the shared cpu_adam.cpp / cpu_lion.cpp, so a builder that compiles those + without the Reflow implementation produces an extension that fails to import with an undefined reflow_* symbol. + The accelerator-specific builders import accelerator packages, so read their source lists instead of loading them. + """ + import ast + import pathlib + + import op_builder + + bindings = { + "csrc/adam/cpu_adam.cpp": "csrc/adam/reflow_cpu_adam_impl.cpp", + "csrc/lion/cpu_lion.cpp": "csrc/lion/reflow_cpu_lion_impl.cpp", + } + missing = [] + checked = 0 + for path in sorted(pathlib.Path(op_builder.__file__).parent.rglob("*.py")): + sources = [] + for node in ast.walk(ast.parse(path.read_text())): + if isinstance(node, ast.FunctionDef) and node.name == "sources": + sources += [ + sub.value for sub in ast.walk(node) + if isinstance(sub, ast.Constant) and isinstance(sub.value, str) + ] + for binding, reflow_impl in bindings.items(): + if binding in sources: + checked += 1 + reflow_bindings = reflow_impl.replace("_impl.cpp", "_bindings.cpp") + for required in (reflow_impl, reflow_bindings): + if required not in sources: + missing.append(f"{path.name} compiles {binding} without {required}") + assert checked > 0, "no builder compiles the shared bindings; the paths above are stale" + assert not missing, missing + + +@pytest.mark.skipif(not deepspeed.ops.__compatible_ops__[CPUAdamBuilder.NAME], + reason="CPUAdamBuilder is not compatible on this system.") +@pytest.mark.parametrize('model_size', [22, 128, 1000, 1024, 4096]) +@pytest.mark.parametrize('grad_dtype', [torch.bfloat16, torch.half], ids=["bf16grad", "fp16grad"]) +@pytest.mark.parametrize('adamw_mode, weight_decay', [(True, 0.0), (True, 0.01), (False, 0.01)], + ids=["adamw_wd0", "adamw_wd0.01", "adam_wd0.01"]) +class TestReflowCPUAdamDropIn: + + LR, BETA1, BETA2, EPS = 1e-3, 0.9, 0.999, 1e-8 + STEPS = 3 + + def test_two_phase_step_matches_base(self, model_size, grad_dtype, adamw_mode, weight_decay): + from deepspeed.ops.adam import DeepSpeedCPUAdam + _skip_amd_fp16(grad_dtype) + _skip_without_avx(CPUAdamBuilder) + lr, b1, b2, eps = self.LR, self.BETA1, self.BETA2, self.EPS + torch.manual_seed(1234 + model_size) + param_fp32 = torch.randn(model_size, dtype=torch.float) + exp_avg = torch.zeros(model_size, dtype=torch.float) + exp_avg_sq = torch.zeros(model_size, dtype=torch.float) + half_params = torch.zeros(model_size, dtype=grad_dtype) + + base_param = torch.nn.Parameter(param_fp32.clone()) + base_opt = DeepSpeedCPUAdam([base_param], + lr=lr, + betas=(b1, b2), + eps=eps, + weight_decay=weight_decay, + adamw_mode=adamw_mode) + + module = CPUAdamBuilder().load() + opt_id = _next_opt_id() + module.reflow_create_adam(opt_id, lr, b1, b2, eps, weight_decay, adamw_mode, False, -1) + # Several steps, so bias correction and non-zero moments are exercised. + for step in range(1, self.STEPS + 1): + grad_half = torch.randn(model_size, dtype=torch.float).to(grad_dtype) + # The reflow kernel promotes the half grad to FP32 exactly, so the base step gets the promoted grad. + base_param.grad = grad_half.float() + base_opt.step() + base_state = base_opt.state[base_param] + + param_before = param_fp32.clone() + module.reflow_adam_update_params_halfgrad(opt_id, step, lr, b1, b2, eps, weight_decay, True, param_fp32, + grad_half, exp_avg, exp_avg_sq, half_params, 1.0, False) + module.reflow_adam_memory_fence() + # Phase-1 emits the base optimizer's new weights in half precision and defers the FP32 master. + assert torch.equal(half_params, base_param.data.to(grad_dtype)), f"half params differ at step {step}" + assert torch.equal(param_fp32, param_before), f"Phase-1 changed the FP32 master at step {step}" + + module.reflow_adam_update_state_halfgrad(opt_id, step, lr, b1, b2, eps, weight_decay, True, param_fp32, + grad_half, exp_avg, exp_avg_sq, 1.0, False) + module.reflow_adam_memory_fence() + assert torch.equal(param_fp32, base_param.data), f"FP32 master differs at step {step}" + assert torch.equal(exp_avg, base_state['exp_avg']), f"exp_avg differs at step {step}" + assert torch.equal(exp_avg_sq, base_state['exp_avg_sq']), f"exp_avg_sq differs at step {step}" + module.reflow_destroy_adam(opt_id) + + +def _base_lion_step(param_fp32, exp_avg, grad_fp32, lr, beta1, beta2, weight_decay): + """One step of the base DeepSpeedCPULion, seeded with the given momentum, as the reference.""" + from deepspeed.ops.lion import DeepSpeedCPULion + p = torch.nn.Parameter(param_fp32.clone()) + opt = DeepSpeedCPULion([p], lr=lr, betas=(beta1, beta2), weight_decay=weight_decay) + # Seed a non-zero starting momentum (skips the lazy zero-init in step()) so the update direction + # c_t is exercised, not just the gradient. + state = opt.state[p] + state['step'] = 0 + state['exp_avg'] = exp_avg.clone() + p.grad = grad_fp32.clone() + opt.step() + return p.data.detach().clone(), opt.state[p]['exp_avg'].detach().clone() + + +@pytest.mark.skipif(not deepspeed.ops.__compatible_ops__[CPULionBuilder.NAME], + reason="CPULionBuilder is not compatible on this system.") +@pytest.mark.parametrize('model_size', [22, 128, 1000, 1024, 4096]) +@pytest.mark.parametrize('grad_dtype', [torch.bfloat16, torch.half], ids=["bf16grad", "fp16grad"]) +@pytest.mark.parametrize('weight_decay', [0.0, 0.01], ids=["wd0", "wd0.01"]) +class TestReflowCPULionDropIn: + + LR, BETA1, BETA2 = 1e-3, 0.9, 0.99 + + def _inputs(self, model_size, grad_dtype): + torch.manual_seed(1234 + model_size) + param_fp32 = torch.randn(model_size, dtype=torch.float) + exp_avg = torch.randn(model_size, dtype=torch.float) + grad_half = torch.randn(model_size, dtype=torch.float).to(grad_dtype) + return param_fp32, exp_avg, grad_half + + def test_phase2_halfgrad_matches_base(self, model_size, grad_dtype, weight_decay): + _skip_amd_fp16(grad_dtype) + _skip_without_avx(CPULionBuilder) + lr, b1, b2 = self.LR, self.BETA1, self.BETA2 + param_fp32, exp_avg, grad_half = self._inputs(model_size, grad_dtype) + # The reflow kernel promotes the half grad to FP32 exactly, so the base reference gets the same + # promoted gradient. + param_ref, exp_avg_ref = _base_lion_step(param_fp32, exp_avg, grad_half.float(), lr, b1, b2, weight_decay) + + module = CPULionBuilder().load() + opt_id = _next_opt_id() + module.reflow_create_lion(opt_id, lr, b1, b2, weight_decay, False, -1) + module.reflow_lion_update_state_halfgrad(opt_id, 1, lr, b1, b2, weight_decay, param_fp32, grad_half, exp_avg, + 1.0, False) + module.reflow_lion_memory_fence() + module.reflow_destroy_lion(opt_id) + + torch.testing.assert_close(param_fp32, param_ref, atol=1e-4, rtol=1e-4) + torch.testing.assert_close(exp_avg, exp_avg_ref, atol=1e-4, rtol=1e-4) + + def test_phase1_produces_bf16_and_defers(self, model_size, grad_dtype, weight_decay): + _skip_amd_fp16(grad_dtype) + _skip_without_avx(CPULionBuilder) + lr, b1, b2 = self.LR, self.BETA1, self.BETA2 + param_fp32, exp_avg, grad_half = self._inputs(model_size, grad_dtype) + param_before = param_fp32.clone() + exp_avg_before = exp_avg.clone() + + param_ref, _ = _base_lion_step(param_fp32, exp_avg, grad_half.float(), lr, b1, b2, weight_decay) + half_params = torch.zeros(model_size, dtype=grad_dtype) + + module = CPULionBuilder().load() + opt_id = _next_opt_id() + module.reflow_create_lion(opt_id, lr, b1, b2, weight_decay, False, -1) + module.reflow_lion_update_params_halfgrad(opt_id, 1, lr, b1, b2, weight_decay, param_fp32, grad_half, exp_avg, + half_params, 1.0, False) + module.reflow_lion_memory_fence() + module.reflow_destroy_lion(opt_id) + + # Phase-1 emits the base optimizer's new weights into the half buffer (BF16/FP16 rounding)... + torch.testing.assert_close(half_params.float(), param_ref, atol=2e-2, rtol=2e-2) + # ...and leaves the FP32 master and momentum untouched (the deferred writeback). + torch.testing.assert_close(param_fp32, param_before, atol=0, rtol=0) + torch.testing.assert_close(exp_avg, exp_avg_before, atol=0, rtol=0) + + +@pytest.mark.parametrize("optimizer_kind", ["adam", "lion"]) +def test_reused_kernel_threads_follow_the_worker_cpu_mask(optimizer_kind): + import os + from concurrent.futures import ThreadPoolExecutor + from pathlib import Path + + if not hasattr(os, "sched_getaffinity") or not Path("/proc/self/task").exists(): + pytest.skip("requires Linux thread affinity") + cpus = sorted(os.sched_getaffinity(0)) + if len(cpus) < 4: + pytest.skip("requires four available CPUs") + builder = CPUAdamBuilder if optimizer_kind == "adam" else CPULionBuilder + if not deepspeed.ops.__compatible_ops__[builder.NAME]: + pytest.skip("CPU optimizer builder is not compatible") + _skip_without_avx(builder) + module = builder().load() + opt_id = _next_opt_id() + param = torch.zeros(4096) + grad = torch.ones(4096, dtype=torch.bfloat16) + momentum = torch.zeros_like(param) + variance = torch.zeros_like(param) + half_param = torch.zeros_like(grad) + common = [opt_id, 1, 1e-3, 0.9, 0.99] + if optimizer_kind == "adam": + module.reflow_create_adam(opt_id, 1e-3, 0.9, 0.99, 1e-8, 0.0, True, False, -1) + else: + module.reflow_create_lion(opt_id, 1e-3, 0.9, 0.99, 0.0, False, -1) + helpers = set() + + def run(mask, phase): + os.sched_setaffinity(0, mask) + before = {int(path.name) for path in Path("/proc/self/task").iterdir()} + if optimizer_kind == "adam": + args = common + [1e-8, 0.0, True, param, grad, momentum, variance] + update = getattr(module, f"reflow_adam_update_{phase}_halfgrad") + else: + args = common + [0.0, param, grad, momentum] + update = getattr(module, f"reflow_lion_update_{phase}_halfgrad") + if phase == "params": + args.append(half_param) + update(*args, 1.0, False) + after = {int(path.name) for path in Path("/proc/self/task").iterdir()} + helpers.update(after - before) + # Pin the fixed regression: retained OpenMP helpers used to keep the previous task's + # CPU mask when this same worker moved. Observe their OS affinity after kernel completion. + for tid in helpers & after: + assert set(os.sched_getaffinity(tid)) <= set(mask) + + try: + with ThreadPoolExecutor(max_workers=1) as executor: + for phase, mask in [("params", cpus[:2]), ("state", cpus[2:4]), ("params", cpus[:2]), + ("state", cpus[2:4])]: + executor.submit(run, mask, phase).result() + finally: + destroy = getattr(module, f"reflow_destroy_{optimizer_kind}") + destroy(opt_id) + + +@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.half], ids=["bf16", "fp16"]) +@pytest.mark.parametrize("size", [22, 4099]) +def test_accumulation_matches_addition_on_restricted_worker_cpus(dtype, size): + import os + from concurrent.futures import ThreadPoolExecutor + + if not hasattr(os, "sched_getaffinity"): + pytest.skip("requires Linux thread affinity") + if not deepspeed.ops.__compatible_ops__[CPUAdamBuilder.NAME]: + pytest.skip("CPUAdamBuilder is not compatible") + _skip_without_avx(CPUAdamBuilder) + _skip_amd_fp16(dtype) + module = CPUAdamBuilder().load() + cpus = sorted(os.sched_getaffinity(0)) + generator = torch.Generator().manual_seed(1234) + dst = torch.randn(size, generator=generator).to(dtype) + src = torch.randn(size, generator=generator).to(dtype) + expected = (dst.float() + src.float()).to(dtype) + + def accumulate(): + os.sched_setaffinity(0, cpus[:1]) + module.reflow_bf16_accumulate(dst, src) + + with ThreadPoolExecutor(max_workers=1) as executor: + executor.submit(accumulate).result() + # A restricted OpenMP team must still finish every SIMD chunk and the non-vectorized tail. + assert torch.equal(dst, expected) diff --git a/tests/unit/v1/zero/test_reflow.py b/tests/unit/v1/zero/test_reflow.py new file mode 100644 index 000000000000..b9124ca5976f --- /dev/null +++ b/tests/unit/v1/zero/test_reflow.py @@ -0,0 +1,720 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team +""" +Contract tests for Reflow, the asynchronous CPU-offload optimizer for ZeRO-3. + +Reflow is meant to be a bit-exact drop-in for ZeRO-Offload (ZeRO-3 + CPU optimizer offload), so every training +test runs the same model and batches through plain ZeRO-Offload as the oracle and compares exactly. +""" + +import copy +import os +import threading +from unittest.mock import patch + +import pytest +import torch + +import deepspeed +import deepspeed.comm as dist +from deepspeed.accelerator import get_accelerator +from deepspeed.checkpoint.constants import FP32_FLAT_GROUPS +from deepspeed.ops.adam import DeepSpeedCPUAdam +from deepspeed.ops.lion import DeepSpeedCPULion +from deepspeed.ops.op_builder import CPUAdamBuilder, CPULionBuilder +from deepspeed.runtime.config import DeepSpeedConfig +from deepspeed.runtime.reflow.reflow_cpu_adam import ReflowCPUAdam +from deepspeed.runtime.reflow.reflow_cpu_lion import ReflowCPULion +from deepspeed.runtime.reflow import reflow_utils +from deepspeed.runtime.zero.muon.muon_optimizer import MuonWithAuxAdam +from deepspeed.runtime.zero.utils import ZeRORuntimeException +from deepspeed.utils import safe_get_full_fp32_param, safe_get_full_optimizer_state +from deepspeed.utils.numa import parse_range_list +from unit.common import DistributedTest +from unit.simple_model import SimpleModel + + +def minimal_reflow_config(reflow=None, **zero_overrides): + """The smallest config that enables Reflow, for the checks that run when the config is parsed.""" + zero_optimization = {"stage": 3, "offload_optimizer": {"device": "cpu"}, "reflow": reflow or {}} + zero_optimization.update(zero_overrides) + return {"train_batch_size": 1, "zero_optimization": zero_optimization} + + +def test_reflow_block_configures_the_optimizer(): + config = DeepSpeedConfig(minimal_reflow_config({"state_update_cores": 4})) + assert config.zero_config.reflow.state_update_cores == 4 + assert config.zero_config.reflow.bucketwise_cores_per_worker == 8 + + for cores in (1, 4, 8): + config = DeepSpeedConfig(minimal_reflow_config({"bucketwise_cores_per_worker": cores})) + assert config.zero_config.reflow.bucketwise_cores_per_worker == cores + + with pytest.raises(ValueError): + DeepSpeedConfig(minimal_reflow_config({"state_update_cores": 0})) + + +def test_cpu_placement_options_are_validated(): + options = { + "main_thread_core_type": "physical", + "worker_core_type": "physical", + "pin_main_thread": True, + "bucketwise_worker_affinity": "thread", + "state_update_backward_cores": 3, + } + config = DeepSpeedConfig(minimal_reflow_config(options)).zero_config.reflow + for key, value in options.items(): + assert getattr(config, key) == value + for key in ("main_thread_core_type", "worker_core_type", "bucketwise_worker_affinity"): + with pytest.raises(ValueError): + DeepSpeedConfig(minimal_reflow_config({key: "unsupported"})) + with pytest.raises(ValueError): + DeepSpeedConfig(minimal_reflow_config({"state_update_backward_cores": 0})) + + +def cpu_siblings(cpu): + # Use the kernel's sibling list as an oracle independent of the planner's package/core IDs. + try: + with open(f"/sys/devices/system/cpu/cpu{cpu}/topology/thread_siblings_list") as handle: + return frozenset(parse_range_list(handle.read().strip())) + except OSError: + pytest.skip("requires readable Linux CPU topology") + + +def available_physical_cpus(): + if not hasattr(os, "sched_getaffinity"): + pytest.skip("requires Linux CPU affinity") + cpus = sorted(os.sched_getaffinity(0)) + groups = {} + for cpu in cpus: + groups.setdefault(cpu_siblings(cpu), []).append(cpu) + return cpus, list(groups.values()) + + +@pytest.mark.parametrize("main_type", ["logical", "physical"]) +@pytest.mark.parametrize("worker_type", ["logical", "physical"]) +def test_cpu_split_respects_rank_and_numa_boundaries(main_type, worker_type): + cpus, groups = available_physical_cpus() + if len(groups) < 2: + pytest.skip("requires two physical cores") + midpoint = len(groups) // 2 + nodes = [[cpu for group in groups[:midpoint] for cpu in group], + [cpu for group in groups[midpoint:] for cpu in group]] + main, worker_nodes, workers = reflow_utils.split_cpu_worker_cores(cpus, nodes, 1, main_type, worker_type) + assert set(main) <= set(cpus) + assert set(workers) <= set(cpus) - set(main) + assert workers + for worker_node in worker_nodes: + assert any(set(worker_node) <= set(node) for node in nodes) + if main_type == "physical": + main_keys = {cpu_siblings(cpu) for cpu in main} + assert len(main_keys) == 1 + assert all(cpu_siblings(cpu) not in main_keys for cpu in workers) + if worker_type == "physical": + assert len(workers) == len({cpu_siblings(cpu) for cpu in workers}) + + +def test_physical_rank_partition_preserves_siblings_and_remainders(): + cpus, groups = available_physical_cpus() + if len(groups) < 3: + pytest.skip("requires three physical cores") + assignments = [reflow_utils.partition_physical_cpus(cpus, 3, rank) for rank in range(3)] + assert set().union(*map(set, assignments)) == set(cpus) + physical_assignments = [{cpu_siblings(cpu) for cpu in assignment} for assignment in assignments] + for rank, physical in enumerate(physical_assignments): + for other in physical_assignments[rank + 1:]: + assert physical.isdisjoint(other) + counts = [len(physical) for physical in physical_assignments] + assert max(counts) - min(counts) <= 1 + + +def test_physical_main_reservation_keeps_a_worker_core(): + _, groups = available_physical_cpus() + with pytest.raises(ValueError): + reflow_utils.split_cpu_worker_cores(groups[0], [groups[0]], 1, "physical", "logical") + + +def test_requires_stage3_and_cpu_optimizer_offload(): + # Reflow only extends the stage-3 CPU-offload path; anything else would silently train without it. + with pytest.raises(ValueError, match="Reflow requires ZeRO stage 3"): + DeepSpeedConfig(minimal_reflow_config(stage=2)) + + with pytest.raises(ValueError, match="Reflow requires optimizer offload"): + DeepSpeedConfig(minimal_reflow_config(offload_optimizer=None)) + + +def test_rejects_deepcompile(): + config = minimal_reflow_config() + config["compile"] = {"deepcompile": True} + with pytest.raises(ValueError, match="not supported with DeepCompile"): + DeepSpeedConfig(config) + + +def test_rejects_muon_config(): + # Reflow's CPU step would replace Muon's orthogonalized update with Adam, so the combination must fail loudly. + config = minimal_reflow_config() + config["optimizer"] = {"type": "Muon", "params": {"lr": 1e-3}} + with pytest.raises(ValueError, match="does not support the Muon optimizer"): + DeepSpeedConfig(config) + + +def test_heuristic_numa_split_with_uneven_rank_count(): + nodes = [list(range(8)), list(range(8, 16))] + assigned = [set(reflow_utils.heuristic_rank_cores(nodes, rank, 3)) for rank in range(3)] + assert assigned == [set(range(4)), set(range(8, 16)), set(range(4, 8))] + + +# The oracle runs are bf16 ZeRO-3 on a GPU accelerator; Reflow is not validated on the CPU accelerator. +# Skipping here, rather than inside the test, keeps a CPU-only run from starting the distributed workers. +needs_gpu_accelerator = pytest.mark.skipif(get_accelerator().device_name() == "cpu", + reason="Reflow training tests need a GPU accelerator.") + + +def skip_if_reflow_training_unsupported(): + if not deepspeed.ops.__compatible_ops__[CPUAdamBuilder.NAME]: + pytest.skip("CPUAdamBuilder is not compatible on this system.") + if not get_accelerator().is_bf16_supported(): + pytest.skip("bf16 is not supported on this accelerator.") + + +def make_batches(hidden_dim, count, dtype=torch.bfloat16): + device = get_accelerator().current_device_name() + batches = [] + for _ in range(count): + inputs = torch.randn(2, hidden_dim, device=device, dtype=dtype) + labels = torch.randint(0, hidden_dim, (2, ), device=device) + batches.append((inputs, labels)) + return batches + + +def get_offload_clip_config(reflow, gradient_clipping, sub_group_size=None): + offload_optimizer = {"device": "cpu", "pin_memory": True} + config = { + "train_micro_batch_size_per_gpu": 2, + "bf16": { + "enabled": True + }, + "optimizer": { + "type": "AdamW", + "params": { + "lr": 0.1 + } + }, + "zero_optimization": { + "stage": 3, + "offload_optimizer": offload_optimizer, + }, + "gradient_clipping": gradient_clipping, + } + if sub_group_size is not None: + config["zero_optimization"]["sub_group_size"] = sub_group_size + if reflow: + config["zero_optimization"]["reflow"] = {} + return config + + +def train_with_offload(model, config, batches): + engine, _, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) + losses = [] + grad_norms = [] + for inputs, labels in batches: + loss = engine(inputs, labels) + # Shrink the grads so the 1e-6 term in the clip factor (norm + 1e-6) / clip is not negligible and + # per-element grads sit near Adam's eps, where the update size depends on the grad scale. + engine.backward(loss * 1e-7) + engine.step() + losses.append(loss.detach().clone()) + grad_norms.append(float(engine.get_global_grad_norm())) + engine.destroy() + return losses, grad_norms + + +def assert_same_training(expected, actual): + expected_losses, expected_norms = expected + actual_losses, actual_norms = actual + assert actual_norms == expected_norms + for step, (want, got) in enumerate(zip(expected_losses, actual_losses)): + assert torch.equal(got, want), f"loss differs at step {step}: {got} vs {want}" + + +@pytest.mark.parametrize("clip_ratio", [0.5, 1.0, 100.0]) +@needs_gpu_accelerator +class TestReflowGradClipMatchesZeroOffload(DistributedTest): + world_size = [1, 2] + + def test_losses_and_grad_norms_match(self, clip_ratio): + # A clip threshold equal to the grad norm is the boundary case: ZeRO-Offload still clips there + # because it clips whenever (norm + 1e-6) / clip > 1. + skip_if_reflow_training_unsupported() + + hidden_dim = 16 + torch.manual_seed(1234) + initial_model = SimpleModel(hidden_dim=hidden_dim, nlayers=2) + batches = make_batches(hidden_dim, count=4) + + # The first step's grad norm does not depend on the clip threshold, so measure it unclipped. + _, unclipped_norms = train_with_offload(copy.deepcopy(initial_model), + get_offload_clip_config(reflow=False, gradient_clipping=0.0), + batches[:1]) + gradient_clipping = unclipped_norms[0] * clip_ratio + + expected = train_with_offload(copy.deepcopy(initial_model), + get_offload_clip_config(reflow=False, gradient_clipping=gradient_clipping), + batches) + actual = train_with_offload(copy.deepcopy(initial_model), + get_offload_clip_config(reflow=True, gradient_clipping=gradient_clipping), batches) + assert_same_training(expected, actual) + + +@needs_gpu_accelerator +class TestReflowGradNormWithPerParamPartitionGroups(DistributedTest): + world_size = [1, 2] + + def test_losses_and_grad_norms_match(self): + # Some params partition over a process group of their own (as AutoEP expert params do), so the grad norm + # must be reduced per subgroup group. The groups have the same members here, which keeps plain ZeRO-Offload a + # valid oracle while still exercising the per-group reduction. + skip_if_reflow_training_unsupported() + + hidden_dim = 16 + torch.manual_seed(1234) + initial_model = SimpleModel(hidden_dim=hidden_dim, nlayers=2) + batches = make_batches(hidden_dim, count=4) + + def model_with_own_partition_group(): + model = copy.deepcopy(initial_model) + own_group = dist.new_group(ranks=list(range(dist.get_world_size()))) + for param in model.linears[0].parameters(): + param.ds_zero_partition_process_group = own_group + return model + + # One param per subgroup, so no subgroup mixes partition groups. + _, unclipped_norms = train_with_offload( + model_with_own_partition_group(), + get_offload_clip_config(reflow=False, gradient_clipping=0.0, sub_group_size=1), batches[:1]) + gradient_clipping = unclipped_norms[0] * 0.5 + + expected = train_with_offload( + model_with_own_partition_group(), + get_offload_clip_config(reflow=False, gradient_clipping=gradient_clipping, sub_group_size=1), batches) + actual = train_with_offload( + model_with_own_partition_group(), + get_offload_clip_config(reflow=True, gradient_clipping=gradient_clipping, sub_group_size=1), batches) + assert_same_training(expected, actual) + + +def get_variant_config(reflow, variant): + offload_optimizer = {"device": "cpu", "pin_memory": True} + config = { + "train_micro_batch_size_per_gpu": 2, + "gradient_clipping": 0.0, + "bf16": { + "enabled": True + }, + "optimizer": { + "type": "AdamW", + "params": { + "lr": 1e-3 + } + }, + "zero_optimization": { + "stage": 3, + "offload_optimizer": offload_optimizer, + }, + } + if variant == "lion": + config["optimizer"] = {"type": "Lion", "params": {"lr": 1e-4}} + elif variant == "offload_param": + config["zero_optimization"]["offload_param"] = {"device": "cpu", "pin_memory": True} + elif variant == "fp16_overflow": + del config["bf16"] + # With this tiny model a 2**16 loss scale overflows the first two of eight steps (2**24 overflows all eight). + # Reflow must skip exactly the same steps as ZeRO-Offload and then train identically. + config["fp16"] = {"enabled": True, "initial_scale_power": 16, "hysteresis": 1} + elif variant == "client_optimizer": + # The client passes a DeepSpeedCPUAdam instead, which Reflow remaps to ReflowCPUAdam. + del config["optimizer"] + if reflow: + config["zero_optimization"]["reflow"] = {} + return config + + +def train_and_collect(model, config, batches, client_optimizer=None, on_initialize=None): + engine, _, _, _ = deepspeed.initialize(model=model, + model_parameters=model.parameters(), + optimizer=client_optimizer, + config=config) + try: + if on_initialize is not None: + on_initialize(engine) + losses = [] + for inputs, labels in batches: + loss = engine(inputs, labels) + engine.backward(loss) + engine.step() + losses.append(loss.detach().clone()) + return { + "losses": losses, + "fp32_params": [safe_get_full_fp32_param(param).clone() for param in engine.module.parameters()], + "skipped_steps": engine.skipped_steps, + "cpu_optimizer": type(engine.optimizer.optimizer), + } + finally: + engine.destroy() + + +@pytest.mark.parametrize("variant", ["lion", "offload_param", "fp16_overflow", "client_optimizer"]) +@needs_gpu_accelerator +class TestReflowVariantsMatchZeroOffload(DistributedTest): + world_size = [1, 2] + + def test_matches_zero_offload(self, variant): + skip_if_reflow_training_unsupported() + if variant == "fp16_overflow" and not get_accelerator().is_fp16_supported(): + pytest.skip("fp16 is not supported on this accelerator.") + + hidden_dim = 16 + dtype = torch.bfloat16 + num_steps = 4 + if variant == "fp16_overflow": + dtype = torch.half + num_steps = 8 + torch.manual_seed(1234) + initial_model = SimpleModel(hidden_dim=hidden_dim, nlayers=2) + batches = make_batches(hidden_dim, count=num_steps, dtype=dtype) + + def run(reflow): + model = copy.deepcopy(initial_model) + client_optimizer = None + if variant == "client_optimizer": + client_optimizer = DeepSpeedCPUAdam(model.parameters(), lr=1e-3) + return train_and_collect(model, get_variant_config(reflow, variant), batches, client_optimizer) + + expected = run(reflow=False) + actual = run(reflow=True) + + # Without this check, a run that silently fell back to plain ZeRO-Offload would pass every comparison below. + expected_cpu_optimizer = ReflowCPULion if variant == "lion" else ReflowCPUAdam + assert issubclass(actual["cpu_optimizer"], expected_cpu_optimizer) + assert actual["skipped_steps"] == expected["skipped_steps"] + if variant == "fp16_overflow": + assert 0 < actual["skipped_steps"] < num_steps, "the loss scale should overflow some steps, not all" + for step, (want, got) in enumerate(zip(expected["losses"], actual["losses"])): + assert torch.equal(got, want), f"loss differs at step {step}: {got} vs {want}" + for index, (want, got) in enumerate(zip(expected["fp32_params"], actual["fp32_params"])): + assert torch.equal(got, want), f"fp32 param {index} differs" + + +@pytest.mark.parametrize("optimizer_kind", ["adam", "lion"]) +@needs_gpu_accelerator +class TestReflowMultipleOptimizerGroupsMatchZeroOffload(DistributedTest): + world_size = 1 + + def test_group_hyperparameters_stay_isolated(self, optimizer_kind): + # Large groups keep bucket workers active long enough to overlap across optimizer groups. + skip_if_reflow_training_unsupported() + if optimizer_kind == "lion" and not deepspeed.ops.__compatible_ops__[CPULionBuilder.NAME]: + pytest.skip("CPULionBuilder is not compatible on this system.") + + hidden_dim = 2049 + torch.manual_seed(1234) + initial_model = SimpleModel(hidden_dim=hidden_dim, nlayers=4) + batches = make_batches(hidden_dim, count=4) + + def run(reflow): + model = copy.deepcopy(initial_model) + first_group = list(model.linears[0].parameters()) + list(model.linears[1].parameters()) + second_group = list(model.linears[2].parameters()) + list(model.linears[3].parameters()) + groups = [{ + "params": first_group, + "lr": 1e-3, + "weight_decay": 0.1 + }, { + "params": second_group, + "lr": 0.1, + "weight_decay": 0.0 + }] + if optimizer_kind == "adam": + optimizer = DeepSpeedCPUAdam(groups, adamw_mode=True) + else: + optimizer = DeepSpeedCPULion(groups) + config = get_variant_config(reflow, "client_optimizer") + if reflow: + config["zero_optimization"]["reflow"]["bucketwise_cores_per_worker"] = 1 + return train_and_collect(model, config, batches, optimizer) + + expected = run(reflow=False) + actual = run(reflow=True) + expected_cpu_optimizer = ReflowCPUAdam if optimizer_kind == "adam" else ReflowCPULion + assert issubclass(actual["cpu_optimizer"], expected_cpu_optimizer) + for step, (want, got) in enumerate(zip(expected["losses"], actual["losses"])): + assert torch.equal(got, want), f"loss differs at step {step}: {got} vs {want}" + for index, (want, got) in enumerate(zip(expected["fp32_params"], actual["fp32_params"])): + assert torch.equal(got, want), f"fp32 param {index} differs" + + +@pytest.mark.parametrize("worker_affinity", ["task", "thread"]) +@pytest.mark.parametrize("worker_type", ["logical", "physical"]) +@needs_gpu_accelerator +class TestReflowCPUPlacementMatchesZeroOffload(DistributedTest): + world_size = [1, 2] + + def test_training_and_cpu_placement(self, worker_affinity, worker_type): + # Catch skipped masks from double round-robin selection, changing masks in thread mode, + # SMT overlap with the pinned main core, and leaked affinity after engine.destroy(). + skip_if_reflow_training_unsupported() + original_cpus, groups = available_physical_cpus() + if len(groups) < 2 * dist.get_world_size(): + pytest.skip("requires a main and a worker physical core per rank") + torch.manual_seed(1234) + initial_model = SimpleModel(hidden_dim=1024, nlayers=4) + batches = make_batches(1024, count=8) + expected = train_and_collect(copy.deepcopy(initial_model), get_variant_config(False, "adam"), batches) + config = get_variant_config(True, "adam") + config["zero_optimization"]["sub_group_size"] = 1_000_000 + config["zero_optimization"]["reflow"] = { + "main_thread_cores": 1, + "main_thread_core_type": "physical", + "pin_main_thread": True, + "worker_core_type": worker_type, + "bucketwise_cores_per_worker": 4, + "bucketwise_worker_affinity": worker_affinity, + "state_update_cores": 2, + "state_update_backward_cores": 3, + } + param_masks = {} + state_masks = set() + pinned_cpus = set() + originals = {} + native = None + + def observe(engine): + nonlocal native + pinned_cpus.update(os.sched_getaffinity(0)) + native = engine.optimizer.optimizer.ds_opt_adam + for phase in ("params", "state"): + name = f"reflow_adam_update_{phase}_halfgrad" + original = getattr(native, name) + originals[name] = original + + def recorded(*args, _phase=phase, _original=original): + mask = frozenset(os.sched_getaffinity(0)) + if _phase == "params": + param_masks.setdefault(threading.get_native_id(), set()).add(mask) + else: + state_masks.add(mask) + return _original(*args) + + setattr(native, name, recorded) + + try: + actual = train_and_collect(copy.deepcopy(initial_model), config, batches, on_initialize=observe) + finally: + if native is not None: + for name, original in originals.items(): + setattr(native, name, original) + assert set(os.sched_getaffinity(0)) == set(original_cpus) + main_keys = {cpu_siblings(cpu) for cpu in pinned_cpus} + assert len(main_keys) == 1 + assert pinned_cpus == set().union(*main_keys) & set(original_cpus) + all_masks = set().union(*param_masks.values()) + used_cpus = set().union(*all_masks) + assert used_cpus <= set(original_cpus) - pinned_cpus + for mask in all_masks | state_masks: + assert {cpu_siblings(cpu) for cpu in mask}.isdisjoint(main_keys) + if worker_type == "physical": + assert len(mask) == len({cpu_siblings(cpu) for cpu in mask}) + assert state_masks + assert all(len(mask) <= 3 for mask in state_masks) + if worker_affinity == "thread": + assert all(len(masks) == 1 for masks in param_masks.values()) + placements = [None] * dist.get_world_size() + dist.all_gather_object(placements, (pinned_cpus, used_cpus)) + all_main = set().union(*(main for main, _ in placements)) + all_used = set().union(*(used for _, used in placements)) + assert {cpu_siblings(cpu) for cpu in all_main}.isdisjoint({cpu_siblings(cpu) for cpu in all_used}) + if worker_affinity == "task": + remaining = set(original_cpus) - all_main + if worker_type == "physical": + remaining = {min(set(group) & remaining) for group in groups if set(group) & remaining} + assert all_used == remaining + for want, got in zip(expected["losses"], actual["losses"]): + assert torch.equal(got, want) + for want, got in zip(expected["fp32_params"], actual["fp32_params"]): + assert torch.equal(got, want) + + +@needs_gpu_accelerator +class TestReflowRejectsUnsupportedClientOptimizer(DistributedTest): + world_size = 1 + + def test_raises_instead_of_training_with_adam(self): + # MuonWithAuxAdam's class name contains "Adam", so it used to be rebuilt as ReflowCPUAdam and silently train + # every parameter with Adam. + skip_if_reflow_training_unsupported() + model = SimpleModel(hidden_dim=16, nlayers=2) + muon_params = [param for param in model.parameters() if param.ndim >= 2] + adam_params = [param for param in model.parameters() if param.ndim < 2] + for param in muon_params: + param.use_muon = True + for param in adam_params: + param.use_muon = False + client_optimizer = MuonWithAuxAdam([ + dict(params=muon_params, use_muon=True, lr=1e-3), + dict(params=adam_params, use_muon=False, lr=1e-3), + ]) + config = get_variant_config(reflow=True, variant="client_optimizer") + # Without this, ZeRO-Offload rejects every non-DeepSpeed CPU optimizer before Reflow sees it. + config["zero_force_ds_cpu_optimizer"] = False + with pytest.raises(ZeRORuntimeException, match="does not support the Muon optimizer"): + deepspeed.initialize(model=model, optimizer=client_optimizer, config=config) + + def test_rejects_radam_instead_of_training_with_adam(self): + skip_if_reflow_training_unsupported() + model = SimpleModel(hidden_dim=16, nlayers=2) + client_optimizer = torch.optim.RAdam(model.parameters(), lr=1e-3) + config = get_variant_config(reflow=True, variant="client_optimizer") + config["zero_force_ds_cpu_optimizer"] = False + with pytest.raises(ZeRORuntimeException, match="cannot remap the client optimizer RAdam"): + deepspeed.initialize(model=model, optimizer=client_optimizer, config=config) + + def test_rejects_scheduler_bound_to_replaced_optimizer(self): + skip_if_reflow_training_unsupported() + model = SimpleModel(hidden_dim=16, nlayers=2) + client_optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3) + scheduler = torch.optim.lr_scheduler.StepLR(client_optimizer, step_size=1) + config = get_variant_config(reflow=True, variant="client_optimizer") + config["zero_force_ds_cpu_optimizer"] = False + with pytest.raises(ZeRORuntimeException, match="already bound to an LR scheduler"): + deepspeed.initialize(model=model, optimizer=client_optimizer, lr_scheduler=scheduler, config=config) + + +@pytest.mark.parametrize("failure_source", ["accumulate", "enqueue"]) +@needs_gpu_accelerator +class TestReflowAsyncWorkerFailures(DistributedTest): + world_size = [1, 2] + non_daemonic_procs = True + + def test_step_reports_worker_error(self, failure_source): + # A failed CPU accumulation or enqueue must abort the public step on every rank. + skip_if_reflow_training_unsupported() + message = f"injected {failure_source} failure" + + def fail(*args): + raise RuntimeError(message) + + if failure_source == "accumulate": + failure_patch = patch.object(ReflowCPUAdam, "bf16_accumulate", classmethod(fail)) + else: + failure_patch = patch.object(reflow_utils, "clip_range_to_valid_partition", fail) + + model = SimpleModel(hidden_dim=16, nlayers=2) + config = get_offload_clip_config(reflow=True, gradient_clipping=0.0) + # Three micro-steps exercise the CPU accumulation worker between the first and boundary steps. + config["gradient_accumulation_steps"] = 3 + batches = make_batches(16, count=3) + engine, _, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) + try: + with failure_patch: + for step, (inputs, labels) in enumerate(batches): + loss = engine(inputs, labels) + engine.backward(loss) + if step < 2: + engine.step() + else: + with pytest.raises(RuntimeError, match=message): + engine.step() + finally: + engine.destroy() + + +def get_state_read_config(reflow, gradient_accumulation_steps, warmup_lr): + offload_optimizer = {"device": "cpu", "pin_memory": True} + config = { + "train_micro_batch_size_per_gpu": 2, + "gradient_accumulation_steps": gradient_accumulation_steps, + "gradient_clipping": 0.0, + "bf16": { + "enabled": True + }, + "optimizer": { + "type": "AdamW", + "params": { + "lr": 1e-3 + } + }, + "zero_optimization": { + "stage": 3, + # Split every weight into its own subgroup, so the chained async commits keep running after step() + # returns and overlap the next micro-steps and the LR scheduler step. + "sub_group_size": 2_000_000, + "offload_optimizer": offload_optimizer, + }, + } + if warmup_lr: + # The LR changes after every optimizer step, so a commit that reads it late would use the next step's LR. + config["scheduler"] = { + "type": "WarmupLR", + "params": { + "warmup_min_lr": 0.0, + "warmup_max_lr": 1e-3, + "warmup_num_steps": 10 + } + } + if reflow: + config["zero_optimization"]["reflow"] = {} + return config + + +def read_state_right_after_each_step(model, config, batches): + # Read as soon as an optimizer step returns, which is when a training script would save a checkpoint. + engine, optimizer, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) + snapshots = [] + for inputs, labels in batches: + loss = engine(inputs, labels) + engine.backward(loss) + at_boundary = engine.is_gradient_accumulation_boundary() + engine.step() + if not at_boundary: + continue + flat_groups = [group.clone() for group in optimizer.state_dict()[FP32_FLAT_GROUPS]] + fp32_params = [safe_get_full_fp32_param(lp).clone() for lp in engine.module.parameters()] + exp_avgs = [safe_get_full_optimizer_state(lp, "exp_avg").clone() for lp in engine.module.parameters()] + snapshots.append((flat_groups, fp32_params, exp_avgs)) + engine.destroy() + return snapshots + + +@pytest.mark.parametrize("gradient_accumulation_steps, warmup_lr", [(1, False), (3, False), (1, True)]) +@needs_gpu_accelerator +class TestReflowStateReadAfterStep(DistributedTest): + world_size = [1, 2] + + def test_matches_zero_offload(self, gradient_accumulation_steps, warmup_lr): + # Reflow commits the FP32 master and optimizer state in background workers after step() returns, while the + # next micro-steps run. Checkpoints and safe_get_* reads right after step() must see the committed values, and + # the commit must not be disturbed by the next micro-steps' grads or by an LR scheduler step. The model is + # large enough that the commit outlasts the read. + skip_if_reflow_training_unsupported() + + hidden_dim = 2048 + torch.manual_seed(1234) + batches = make_batches(hidden_dim, count=2 * gradient_accumulation_steps) + + expected = read_state_right_after_each_step( + SimpleModel(hidden_dim=hidden_dim, nlayers=4), + get_state_read_config(reflow=False, + gradient_accumulation_steps=gradient_accumulation_steps, + warmup_lr=warmup_lr), batches) + torch.manual_seed(1234) + actual = read_state_right_after_each_step( + SimpleModel(hidden_dim=hidden_dim, nlayers=4), + get_state_read_config(reflow=True, + gradient_accumulation_steps=gradient_accumulation_steps, + warmup_lr=warmup_lr), batches) + + for step, (expected_step, actual_step) in enumerate(zip(expected, actual)): + for name, expected_tensors, actual_tensors in zip(("state_dict fp32 groups", "fp32 params", "exp_avg"), + expected_step, actual_step): + for index, (want, got) in enumerate(zip(expected_tensors, actual_tensors)): + assert torch.equal(got, want), f"{name}[{index}] differs after step {step}" From fdf7baded986c4443ecea5c2a08c316161c6f5d2 Mon Sep 17 00:00:00 2001 From: st-bang97 Date: Fri, 2 Oct 2026 04:41:41 +0000 Subject: [PATCH 02/19] Validate ReFlow precision and optimizer usage Signed-off-by: st-bang97 --- deepspeed/runtime/config.py | 8 ++ deepspeed/runtime/reflow/README.md | 23 +++-- deepspeed/runtime/reflow/engine.py | 3 + deepspeed/runtime/reflow/reflow_cpu_adam.py | 10 +- deepspeed/runtime/reflow/reflow_cpu_lion.py | 10 +- deepspeed/runtime/reflow/reflow_stage3.py | 4 + docs/_pages/config-json.md | 55 +++++++++-- docs/_tutorials/reflow.md | 6 +- .../unit/v1/ops/test_reflow_cpu_optimizers.py | 24 +++++ tests/unit/v1/zero/test_reflow.py | 96 ++++++++++++++++--- 10 files changed, 201 insertions(+), 38 deletions(-) diff --git a/deepspeed/runtime/config.py b/deepspeed/runtime/config.py index ecc0d12af104..75a525c02335 100755 --- a/deepspeed/runtime/config.py +++ b/deepspeed/runtime/config.py @@ -702,6 +702,14 @@ def _do_error_check(self): # be silently replaced by Adam. Supporting Muon in Reflow is future work. raise ValueError("Reflow does not support the Muon optimizer yet; remove the 'reflow' block from " "zero_optimization to use Muon with ZeRO-Offload") + if reflow_enabled: + if not self.bfloat16_config.enabled or self.float16_config.enabled or self.torch_autocast_enabled: + raise ValueError("Reflow requires BF16 model parameters with 'bf16.enabled': true; " + "FP16, FP32 model parameters and torch_autocast are not supported.") + if (self.float16_config.fp16_master_weights_and_grads or self.bfloat16_config.bf16_master_weights_and_grads + or self.bfloat16_config.bf16_optimizer_states): + raise ValueError("Reflow requires FP32 master weights and optimizer states; " + "low-precision master weights and optimizer states are not supported.") if self.float16_config.fp16_master_weights_and_grads: assert self.zero_enabled and self.zero_optimization_stage in ( diff --git a/deepspeed/runtime/reflow/README.md b/deepspeed/runtime/reflow/README.md index cd2aeeb86551..1716808dfc40 100644 --- a/deepspeed/runtime/reflow/README.md +++ b/deepspeed/runtime/reflow/README.md @@ -11,6 +11,11 @@ GPU compute and the inter-GPU gradient reduction. momentum tensor (`exp_avg`) — no second moment, no `eps`, no bias correction — so its offloaded state is half of Adam's; everything else in the pipeline below is identical. +**Precision support:** BF16 model parameters and gradients with FP32 master weights and optimizer +states. FP16/FP32 model parameters, `torch_autocast`, low-precision master weights/states, and +`fp32_optimizer_states=False` are rejected at initialization. Use `engine.step()` after +`deepspeed.initialize()`; direct `ReflowCPUAdam.step()` and `ReflowCPULion.step()` calls are rejected. + This directory is the implementation. A fine-tuning example is planned for [DeepSpeedExamples](https://github.com/deepspeedai/DeepSpeedExamples); until it lands, the tutorial (`docs/_tutorials/reflow.md`) shows the configuration a training script needs. @@ -30,16 +35,16 @@ A `reflow` block in `zero_optimization` turns on three cooperating behaviors: reduce-scatter. 2. **`cpu_conversion` — half-precision gradient transfer.** - Gradients are copied to the CPU in their native FP16/BF16 precision and promoted to FP32 *inside* + Gradients are copied to the CPU in their native BF16 precision and promoted to FP32 *inside* the AVX CPU-Adam kernel. This halves the GPU→CPU traffic with no extra host-side cast, and removes - the CPU-side FP32 gradient buffer entirely — only the half-precision (BF16/FP16) gradient is kept + the CPU-side FP32 gradient buffer entirely — only the half-precision BF16 gradient is kept on the CPU — so CPU memory usage drops. 3. **`async_state` — asynchronous state update.** - The foreground step only generates the new BF16/FP16 parameters (produced just in time for the + The foreground step only generates the new BF16 parameters (produced just in time for the next step); updating the FP32 master parameters and the optimizer state (Adam's `exp_avg`/`exp_avg_sq`, or Lion's `exp_avg`) is split off to a background CPU worker. That state - update runs after the gradient-clipping and FP16-overflow checks, so it can overlap the *next* + update runs after the gradient-clipping and non-finite gradient checks, so it can overlap the *next* iteration's forward. A **NUMA-aware core binding** underlies all three: worker threads are pinned to the CPU cores local @@ -52,9 +57,9 @@ to each GPU's NUMA node for higher CPU↔GPU bandwidth. ``` backward: reduce bucket ──► D2H grad copy (half precision, copy_grad_stream) └► submit per-bucket CPU-Adam to a worker - ├► worker: FP32-promote + generate updated FP16/BF16 params - └► worker: H2D copy updated FP16/BF16 weights (bucketwise_h2d_stream) -step(): drain bucket workers ─► FP16-overflow check ─► grad-norm / gradient clipping + ├► worker: FP32-promote + generate updated BF16 params + └► worker: H2D copy updated BF16 weights (bucketwise_h2d_stream) +step(): drain bucket workers ─► non-finite gradient check ─► grad-norm / gradient clipping └► submit the deferred FP32-master + exp_avg/exp_avg_sq update to the async-state worker (the param generation already ran during backward, so this is a thin tail) @@ -212,7 +217,7 @@ the default and the only fully supported path. `REFLOW_SINGLE_GRAD_BUFFER=1` enables a **single** grad buffer prototype that is not fully implemented yet. With `offload_param: cpu`, one slot only duplicates the CPU parameter source, so the prototype -writes the updated FP16/BF16 params straight into that source and saves ~2 bytes/param. It has been +writes the updated BF16 params straight into that source and saves ~2 bytes/param. It has been checked only with `offload_param: cpu` and `gradient_accumulation_steps: 1`; any other run (gradient accumulation, params on GPU, NVMe offload) logs a warning and falls back to the double buffer. @@ -251,7 +256,7 @@ fell from ~1700 ms to ~120 ms once the bucketwise workers ran concurrently. ## Correctness -- **FP16 dynamic loss scaling**: an overflowing step is detected with an on-GPU `isfinite` scan over +- **Non-finite gradients**: a step with non-finite gradients is detected with an on-GPU `isfinite` scan over the offloaded grads and discarded exactly like the standard optimizer — the FP32 master is untouched and the GPU weights are regenerated from it. - **Async grad-copy aliveness**: the D2H grad-copy source is recorded against `copy_grad_stream` diff --git a/deepspeed/runtime/reflow/engine.py b/deepspeed/runtime/reflow/engine.py index 82596f03ad61..afa218363089 100644 --- a/deepspeed/runtime/reflow/engine.py +++ b/deepspeed/runtime/reflow/engine.py @@ -59,6 +59,9 @@ def maybe_remap_client_optimizer(engine: "DeepSpeedEngine", optimizer): from deepspeed.ops.adam import DeepSpeedCPUAdam from deepspeed.ops.lion import DeepSpeedCPULion from deepspeed.runtime.zero.muon.muon_optimizer import MuonWithAuxAdam + if not getattr(optimizer, "fp32_optimizer_states", True): + raise ZeRORuntimeException("Reflow requires FP32 optimizer states; fp32_optimizer_states=False " + "is not supported.") if isinstance(optimizer, (ReflowCPUAdam, ReflowCPULion)): return optimizer if isinstance(optimizer, MuonWithAuxAdam): diff --git a/deepspeed/runtime/reflow/reflow_cpu_adam.py b/deepspeed/runtime/reflow/reflow_cpu_adam.py index 58a2ca5d7c0c..bf41b77c0728 100644 --- a/deepspeed/runtime/reflow/reflow_cpu_adam.py +++ b/deepspeed/runtime/reflow/reflow_cpu_adam.py @@ -50,12 +50,15 @@ def __init__(self, num_threads=None): """Reflow CPU Adam(W). - Same arguments as :class:`DeepSpeedCPUAdam` plus: + Same arguments as :class:`DeepSpeedCPUAdam`, requiring ``fp32_optimizer_states=True``, plus: Arguments: num_threads (int): number of CPU threads for the Adam update. ``None`` uses all available cores. """ + if not fp32_optimizer_states: + raise ValueError("ReflowCPUAdam requires FP32 optimizer states; fp32_optimizer_states=False " + "is not supported.") # Initialize torch.optim.Optimizer directly (rather than via DeepSpeedCPUAdam.__init__) # and register a Reflow C++ optimizer in its own registry. This avoids registering a # standard cpu_adam optimizer instance and keeps the native state isolated. @@ -91,6 +94,11 @@ def __init__(self, self.ds_opt_adam.reflow_create_adam(self.opt_id, lr, betas[0], betas[1], eps, weight_decay, adamw_mode, should_log_le("info"), num_threads) + def step(self, closure=None): + """Direct steps cannot use the separate Reflow native registry.""" + raise NotImplementedError("ReflowCPUAdam.step() is not supported; initialize Reflow with " + "deepspeed.initialize() and use engine.step().") + def memory_fence(self): """Flush the non-temporal (streaming) stores so updated params/state are globally visible before a worker future completes. Called by the Reflow ZeRO-3 async-state worker, which diff --git a/deepspeed/runtime/reflow/reflow_cpu_lion.py b/deepspeed/runtime/reflow/reflow_cpu_lion.py index 3e81a905d9b7..5d29676de7bb 100644 --- a/deepspeed/runtime/reflow/reflow_cpu_lion.py +++ b/deepspeed/runtime/reflow/reflow_cpu_lion.py @@ -49,12 +49,15 @@ def __init__(self, num_threads=None): """Reflow CPU Lion. - Same arguments as :class:`DeepSpeedCPULion` plus: + Same arguments as :class:`DeepSpeedCPULion`, requiring ``fp32_optimizer_states=True``, plus: Arguments: num_threads (int): number of CPU threads for the Lion update. ``None`` uses all available cores. """ + if not fp32_optimizer_states: + raise ValueError("ReflowCPULion requires FP32 optimizer states; fp32_optimizer_states=False " + "is not supported.") # Initialize torch.optim.Optimizer directly (rather than via DeepSpeedCPULion.__init__) # and register a Reflow C++ optimizer in its own registry. This avoids registering a # standard cpu_lion optimizer instance and keeps the native state isolated. @@ -84,6 +87,11 @@ def __init__(self, self.ds_opt_lion.reflow_create_lion(self.opt_id, lr, betas[0], betas[1], weight_decay, should_log_le("info"), num_threads) + def step(self, closure=None): + """Direct steps cannot use the separate Reflow native registry.""" + raise NotImplementedError("ReflowCPULion.step() is not supported; initialize Reflow with " + "deepspeed.initialize() and use engine.step().") + def __del__(self): # Destroy the C++ object explicitly to avoid a leak when deepspeed.initialize # is used multiple times in the same process (notebook or pytest worker). diff --git a/deepspeed/runtime/reflow/reflow_stage3.py b/deepspeed/runtime/reflow/reflow_stage3.py index 6b2edd652fdf..e2d053bfe54f 100644 --- a/deepspeed/runtime/reflow/reflow_stage3.py +++ b/deepspeed/runtime/reflow/reflow_stage3.py @@ -49,6 +49,10 @@ class ReflowOptimizer_Stage3(DeepSpeedZeroOptimizer_Stage3): """ def __init__(self, module, init_optimizer, param_names, timers, ds_config, reflow_config, **kwargs): + # zero.Init models bypass the engine's parameter cast, so validate their actual dtype too. + if any(param.is_floating_point() and param.dtype != torch.bfloat16 for param in module.parameters()): + raise ValueError("Reflow requires BF16 model parameters; FP16 and FP32 model parameters " + "are not supported.") self._reflow_config = reflow_config # These attributes must exist before super().__init__ runs: the parent constructor # calls _setup_for_real_optimizer / initialize_optimizer_states, which are overridden diff --git a/docs/_pages/config-json.md b/docs/_pages/config-json.md index b59da1ed3f00..af2d69dc12d7 100644 --- a/docs/_pages/config-json.md +++ b/docs/_pages/config-json.md @@ -688,47 +688,82 @@ Note that if the value of "device" is not specified or not supported, an asserti | Enable fast optimizer initialization when offloading to NVMe. | `false` | ### Reflow -[Reflow](/tutorials/reflow/) is an asynchronous CPU-offload optimizer for ZeRO stage 3. The CPU optimizer runs per gradient bucket during backward, gradients move to CPU in half precision, and the FP32 master weights and optimizer state are committed in the background while the next forward runs. +[Reflow](/tutorials/reflow/) is an asynchronous CPU-offload optimizer for ZeRO stage 3. The CPU optimizer runs per gradient bucket during backward, gradients move to CPU in BF16, and the FP32 master weights and optimizer state are committed in the background while the next forward runs. -The `reflow` block enables it, so an empty block is enough to run with the defaults. Reflow requires `"stage": 3` with `offload_optimizer` on `cpu` (or `nvme`), and a CPU Adam build with AVX2 or AVX-512. It uses `ReflowCPUAdam`/`ReflowCPULion`; a client `DeepSpeedCPUAdam`/`DeepSpeedCPULion` is remapped automatically. It is not compatible with `super_offload`, ZenFlow, DeepCompile, the Muon optimizer (support to be implemented), or `managed_gradient_accumulation: false`. +The `reflow` block enables it, so an empty block is enough to run with the defaults. Reflow requires `"stage": 3`, `"bf16": {"enabled": true}`, `offload_optimizer` on `cpu` (or `nvme`), and CPU Adam/Lion kernels built with AVX2 or AVX-512. Model parameters and offloaded gradients must be BF16; master weights and optimizer states must be FP32. FP16 or FP32 model parameters, `torch_autocast`, low-precision master weights/states, and `fp32_optimizer_states: false` are rejected. It uses `ReflowCPUAdam`/`ReflowCPULion`; a client `DeepSpeedCPUAdam`/`DeepSpeedCPULion` is remapped automatically. Call `engine.step()`; direct `ReflowCPUAdam.step()` and `ReflowCPULion.step()` calls are rejected. It is not compatible with `super_offload`, ZenFlow, DeepCompile, the Muon optimizer (support to be implemented), or `managed_gradient_accumulation: false`. ```json "reflow": { "num_threads": null, "enable_cpu_affinity": false, "main_thread_cores": 3, - "bucketwise_cores_per_worker": 1, - "state_update_cores": 2 + "main_thread_core_type": "logical", + "pin_main_thread": false, + "worker_core_type": "logical", + "bucketwise_worker_affinity": "task", + "bucketwise_cores_per_worker": 8, + "state_update_cores": 2, + "state_update_backward_cores": null } ``` -***num_threads***: [integer] +***num_threads***: [integer or null] | Description | Default | | ----------- | ------- | -| Threads for the CPU optimizer kernels. When unset, all cores available to the rank are used. | `null` | +| CPU optimizer kernel thread limit. When unset, each kernel uses the CPUs available under its worker's affinity. | `null` | ***enable_cpu_affinity***: [boolean] | Description | Default | | ----------- | ------- | -| Pin the main (forward/backward) thread and the optimizer workers to separate NUMA-local CPU cores. | `false` | +| Restrict the main process to the rank's NUMA-local CPU slice. Optimizer workers are pinned regardless of this setting. Use `pin_main_thread` to restrict the initializing thread to the reserved main CPUs. | `false` | ***main_thread_cores***: [integer] | Description | Default | | ----------- | ------- | -| CPU cores reserved for the main thread when `enable_cpu_affinity` is true; the remaining cores go to the optimizer workers. | `3` | +| CPUs or physical cores reserved from the optimizer workers, according to `main_thread_core_type`. Worker placement uses this reservation even when `enable_cpu_affinity` is false. | `3` | + +***main_thread_core_type***: [string] + +| Description | Default | +| ----------- | ------- | +| Count the main reservation as logical CPUs (`logical`) or physical cores with all available SMT siblings (`physical`). | `"logical"` | + +***pin_main_thread***: [boolean] + +| Description | Default | +| ----------- | ------- | +| Pin the initializing thread to the reserved main CPUs. Its original affinity is restored on engine destruction. Requires OS thread-affinity support. | `false` | + +***worker_core_type***: [string] + +| Description | Default | +| ----------- | ------- | +| Use all available worker CPU IDs (`logical`) or one logical CPU per worker physical core (`physical`). | `"logical"` | + +***bucketwise_worker_affinity***: [string] + +| Description | Default | +| ----------- | ------- | +| Assign a CPU mask per submitted task (`task`) or pin each pool thread to its initial mask (`thread`). | `"task"` | ***bucketwise_cores_per_worker***: [integer] | Description | Default | | ----------- | ------- | -| CPU cores per bucketwise optimizer worker; the worker count is the rank's worker cores divided by this value. | `1` | +| Maximum worker CPU IDs per bucketwise worker. Each NUMA group is split into chunks of this size; the final chunk may be smaller. One pool thread is created per chunk. | `8` | ***state_update_cores***: [integer] | Description | Default | | ----------- | ------- | -| Worker cores the background optimizer-state commit uses while it overlaps the next forward. Fewer busy cores keep the CPU at a higher turbo frequency for the forward; once backward starts, the commit uses every worker core. | `2` | +| Worker CPU IDs available to the background optimizer-state commit while it overlaps the next forward. Once backward starts, the commit uses the mask selected by `state_update_backward_cores`. | `2` | + +***state_update_backward_cores***: [integer or null] + +| Description | Default | +| ----------- | ------- | +| Limit the background state commit's worker CPU IDs during backward. When unset, all worker CPUs are available. Affinity changes take effect between commit slices. | `null` | ### Asynchronous I/O diff --git a/docs/_tutorials/reflow.md b/docs/_tutorials/reflow.md index 01c6e8b46f82..ffb3ff49e5d2 100644 --- a/docs/_tutorials/reflow.md +++ b/docs/_tutorials/reflow.md @@ -11,8 +11,8 @@ We recommend that you read the tutorials on [ZeRO](/tutorials/zero/) and [ZeRO-O Adding a `reflow` block to `zero_optimization` turns on three cooperating behaviors: 1. **Per-bucket optimizer during backward.** As each gradient bucket is reduced, its CPU optimizer update is submitted to a background worker, so the optimizer overlaps the rest of backward and the gradient reduce-scatter. -2. **Half-precision gradient transfer.** Gradients are copied to CPU in FP16/BF16 and promoted to FP32 inside the AVX kernel. This halves the GPU-to-CPU traffic and removes the CPU-side FP32 gradient buffer. -3. **Asynchronous state commit.** The foreground only produces the new FP16/BF16 parameters. The FP32 master weights and optimizer state are committed by a background worker after the gradient clipping and overflow checks, overlapping the next forward. +2. **Half-precision gradient transfer.** Gradients are copied to CPU in BF16 and promoted to FP32 inside the AVX kernel. This halves the GPU-to-CPU traffic and removes the CPU-side FP32 gradient buffer. +3. **Asynchronous state commit.** The foreground only produces the new BF16 parameters. The FP32 master weights and optimizer state are committed by a background worker after the gradient clipping and overflow checks, overlapping the next forward. Checkpoint APIs (`state_dict`, `load_state_dict`, and the `safe_get_*`/`safe_set_*` helpers) wait for that background commit, so they always see the fully applied step. @@ -72,6 +72,8 @@ With `gradient_clipping: 1.0` in the same setup, Reflow's optimizer step average ## Limitations +- Reflow requires BF16 model parameters and gradients with FP32 master weights and optimizer states. Enable `bf16.enabled`; FP16/FP32 model parameters, `torch_autocast`, low-precision master weights/states, and `fp32_optimizer_states: false` are rejected. +- Use `engine.step()` after `deepspeed.initialize()`. Direct `ReflowCPUAdam.step()` and `ReflowCPULion.step()` calls are rejected. - ZeRO stage 3 with `offload_optimizer.device` set to `cpu`; any other stage or device is rejected when the configuration is parsed. NVMe optimizer offload is accepted but is not covered by tests. - The CPU Adam/Lion extension must be built with AVX2 or AVX-512; Reflow raises an error when it creates the optimizer on other builds. - Not supported with `super_offload`, ZenFlow, DeepCompile, the Muon optimizer, or `managed_gradient_accumulation: false`. The first four are rejected at initialization. diff --git a/tests/unit/v1/ops/test_reflow_cpu_optimizers.py b/tests/unit/v1/ops/test_reflow_cpu_optimizers.py index 405c68011fa8..188eace65f9e 100644 --- a/tests/unit/v1/ops/test_reflow_cpu_optimizers.py +++ b/tests/unit/v1/ops/test_reflow_cpu_optimizers.py @@ -19,6 +19,8 @@ import deepspeed from deepspeed.ops.op_builder import CPUAdamBuilder, CPULionBuilder +from deepspeed.runtime.reflow.reflow_cpu_adam import ReflowCPUAdam +from deepspeed.runtime.reflow.reflow_cpu_lion import ReflowCPULion pytest.cpu_vendor = get_cpu_info()["vendor_id_raw"].lower() if "vendor_id_raw" in get_cpu_info() else "unknown" @@ -43,6 +45,28 @@ def _skip_without_avx(builder): pytest.skip("the CPU optimizer extension is not built with AVX2 or AVX-512") +@pytest.mark.parametrize("optimizer_type", [ReflowCPUAdam, ReflowCPULion]) +def test_reflow_optimizer_rejects_low_precision_states(optimizer_type): + param = torch.nn.Parameter(torch.ones(22, dtype=torch.bfloat16)) + with pytest.raises(ValueError, match="requires FP32 optimizer states"): + optimizer_type([param], fp32_optimizer_states=False) + + +@pytest.mark.parametrize("optimizer_type, builder", [(ReflowCPUAdam, CPUAdamBuilder), (ReflowCPULion, CPULionBuilder)]) +def test_reflow_optimizer_rejects_direct_step(optimizer_type, builder): + if not deepspeed.ops.__compatible_ops__.get(builder.NAME, False): + pytest.skip("the CPU optimizer builder is not supported on this accelerator") + _skip_without_avx(builder) + param = torch.nn.Parameter(torch.ones(22, dtype=torch.bfloat16)) + param.grad = torch.ones_like(param) + optimizer = optimizer_type([param], num_threads=1) + original = param.detach().clone() + with pytest.raises(NotImplementedError, match="use engine.step"): + optimizer.step() + assert torch.equal(param, original) + assert not optimizer.state + + def test_every_builder_of_the_shared_bindings_compiles_the_reflow_kernels(): """The Reflow entry points are bound in the shared cpu_adam.cpp / cpu_lion.cpp, so a builder that compiles those without the Reflow implementation produces an extension that fails to import with an undefined reflow_* symbol. diff --git a/tests/unit/v1/zero/test_reflow.py b/tests/unit/v1/zero/test_reflow.py index b9124ca5976f..191a11cdb316 100644 --- a/tests/unit/v1/zero/test_reflow.py +++ b/tests/unit/v1/zero/test_reflow.py @@ -38,7 +38,7 @@ def minimal_reflow_config(reflow=None, **zero_overrides): """The smallest config that enables Reflow, for the checks that run when the config is parsed.""" zero_optimization = {"stage": 3, "offload_optimizer": {"device": "cpu"}, "reflow": reflow or {}} zero_optimization.update(zero_overrides) - return {"train_batch_size": 1, "zero_optimization": zero_optimization} + return {"train_batch_size": 1, "bf16": {"enabled": True}, "zero_optimization": zero_optimization} def test_reflow_block_configures_the_optimizer(): @@ -158,6 +158,61 @@ def test_rejects_muon_config(): DeepSpeedConfig(config) +@pytest.mark.parametrize("precision_config, error", [ + ({ + "bf16": { + "enabled": False + } + }, "requires BF16 model parameters"), + ({ + "bf16": { + "enabled": False + }, + "fp16": { + "enabled": True + } + }, "requires BF16 model parameters"), + ({ + "torch_autocast": { + "enabled": True, + "dtype": "bfloat16" + } + }, "requires BF16 model parameters"), + ({ + "bf16": { + "enabled": True, + "bf16_master_weights_and_grads": True + } + }, "requires FP32 master weights"), + ({ + "bf16": { + "enabled": True, + "bf16_optimizer_states": True + } + }, "requires FP32 master weights"), + ({ + "fp16": { + "fp16_master_weights_and_grads": True + } + }, "requires FP32 master weights"), +]) +def test_rejects_unsupported_precision(precision_config, error): + # These combinations must fail before any worker or native optimizer is created. + config = minimal_reflow_config() + config.update(precision_config) + with pytest.raises(ValueError, match=error): + DeepSpeedConfig(config) + + +def test_precision_restrictions_do_not_apply_without_reflow(): + config = minimal_reflow_config() + del config["zero_optimization"]["reflow"] + config["bf16"] = {"enabled": False} + assert not DeepSpeedConfig(config).bfloat16_config.enabled + config["bf16"] = {"enabled": True, "bf16_master_weights_and_grads": True} + assert DeepSpeedConfig(config).bfloat16_config.bf16_master_weights_and_grads + + def test_heuristic_numa_split_with_uneven_rank_count(): nodes = [list(range(8)), list(range(8, 16))] assigned = [set(reflow_utils.heuristic_rank_cores(nodes, rank, 3)) for rank in range(3)] @@ -326,11 +381,6 @@ def get_variant_config(reflow, variant): config["optimizer"] = {"type": "Lion", "params": {"lr": 1e-4}} elif variant == "offload_param": config["zero_optimization"]["offload_param"] = {"device": "cpu", "pin_memory": True} - elif variant == "fp16_overflow": - del config["bf16"] - # With this tiny model a 2**16 loss scale overflows the first two of eight steps (2**24 overflows all eight). - # Reflow must skip exactly the same steps as ZeRO-Offload and then train identically. - config["fp16"] = {"enabled": True, "initial_scale_power": 16, "hysteresis": 1} elif variant == "client_optimizer": # The client passes a DeepSpeedCPUAdam instead, which Reflow remaps to ReflowCPUAdam. del config["optimizer"] @@ -363,22 +413,16 @@ def train_and_collect(model, config, batches, client_optimizer=None, on_initiali engine.destroy() -@pytest.mark.parametrize("variant", ["lion", "offload_param", "fp16_overflow", "client_optimizer"]) +@pytest.mark.parametrize("variant", ["lion", "offload_param", "client_optimizer"]) @needs_gpu_accelerator class TestReflowVariantsMatchZeroOffload(DistributedTest): world_size = [1, 2] def test_matches_zero_offload(self, variant): skip_if_reflow_training_unsupported() - if variant == "fp16_overflow" and not get_accelerator().is_fp16_supported(): - pytest.skip("fp16 is not supported on this accelerator.") - hidden_dim = 16 dtype = torch.bfloat16 num_steps = 4 - if variant == "fp16_overflow": - dtype = torch.half - num_steps = 8 torch.manual_seed(1234) initial_model = SimpleModel(hidden_dim=hidden_dim, nlayers=2) batches = make_batches(hidden_dim, count=num_steps, dtype=dtype) @@ -397,8 +441,6 @@ def run(reflow): expected_cpu_optimizer = ReflowCPULion if variant == "lion" else ReflowCPUAdam assert issubclass(actual["cpu_optimizer"], expected_cpu_optimizer) assert actual["skipped_steps"] == expected["skipped_steps"] - if variant == "fp16_overflow": - assert 0 < actual["skipped_steps"] < num_steps, "the loss scale should overflow some steps, not all" for step, (want, got) in enumerate(zip(expected["losses"], actual["losses"])): assert torch.equal(got, want), f"loss differs at step {step}: {got} vs {want}" for index, (want, got) in enumerate(zip(expected["fp32_params"], actual["fp32_params"])): @@ -544,6 +586,30 @@ def recorded(*args, _phase=phase, _original=original): assert torch.equal(got, want) +class TestReflowPrecisionValidation(DistributedTest): + world_size = 1 + + @pytest.mark.parametrize("optimizer_type", [DeepSpeedCPUAdam, DeepSpeedCPULion]) + def test_rejects_low_precision_client_states(self, optimizer_type): + builder = CPULionBuilder if optimizer_type is DeepSpeedCPULion else CPUAdamBuilder + if not deepspeed.ops.__compatible_ops__.get(builder.NAME, False): + pytest.skip("the CPU optimizer builder is not supported on this accelerator") + model = SimpleModel(hidden_dim=16, nlayers=2) + optimizer = optimizer_type(model.parameters(), fp32_optimizer_states=False) + config = get_variant_config(reflow=True, variant="client_optimizer") + with pytest.raises(ZeRORuntimeException, match="requires FP32 optimizer states"): + deepspeed.initialize(model=model, optimizer=optimizer, config=config) + + @pytest.mark.parametrize("dtype", [torch.float32, torch.float16]) + def test_rejects_zero_init_model_with_unsupported_dtype(self, dtype): + # zero.Init bypasses the engine's model cast; the config's BF16 flag alone cannot guarantee BF16 weights. + config = get_variant_config(reflow=True, variant="offload_param") + with deepspeed.zero.Init(config_dict_or_path=config, dtype=dtype): + model = SimpleModel(hidden_dim=16, nlayers=2) + with pytest.raises(ValueError, match="requires BF16 model parameters"): + deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) + + @needs_gpu_accelerator class TestReflowRejectsUnsupportedClientOptimizer(DistributedTest): world_size = 1 From 7e180988b012dc157e24253c3a085b3d26d08176 Mon Sep 17 00:00:00 2001 From: st-bang97 Date: Fri, 2 Oct 2026 05:05:48 +0000 Subject: [PATCH 03/19] Abort ReFlow checkpoints on asynchronous optimizer failures Signed-off-by: st-bang97 --- deepspeed/runtime/reflow/README.md | 5 ++- deepspeed/runtime/reflow/reflow_stage3.py | 22 ++++++++++ docs/_tutorials/reflow.md | 2 +- tests/unit/v1/zero/test_reflow.py | 52 +++++++++++++++++++++++ 4 files changed, 79 insertions(+), 2 deletions(-) diff --git a/deepspeed/runtime/reflow/README.md b/deepspeed/runtime/reflow/README.md index 1716808dfc40..ab0375360c8e 100644 --- a/deepspeed/runtime/reflow/README.md +++ b/deepspeed/runtime/reflow/README.md @@ -272,7 +272,10 @@ fell from ~1700 ms to ~120 ms once the bucketwise workers ran concurrently. - **Checkpoints see the committed state**: a step's FP32 master and optimizer state are committed in the background after `step()` returns, so `state_dict` / `load_state_dict` and the `safe_get_*` / `safe_set_*` hp-param APIs wait for that commit first. Only these entry points wait; the training - step is unchanged. + step is unchanged. Before writing checkpoint files, the checkpoint prologue shares one reused + error flag across all ranks and aborts everywhere if a worker failed. Single-rank checkpoints + need no error collective. Direct `state_dict` and `get_lean_optimizer_state` calls propagate + local worker errors without adding communication. --- diff --git a/deepspeed/runtime/reflow/reflow_stage3.py b/deepspeed/runtime/reflow/reflow_stage3.py index e2d053bfe54f..b786cfa3cb40 100644 --- a/deepspeed/runtime/reflow/reflow_stage3.py +++ b/deepspeed/runtime/reflow/reflow_stage3.py @@ -1671,8 +1671,28 @@ def finalize_gradient_accumulation_boundary(self): # step() returns while background workers still commit the FP32 master and optimizer state, so # checkpoints and the safe_get/set_* APIs wait for that commit; the training loop does not. + def checkpoint_event_prologue(self): + self._wait_for_pending_state_updates() + local_error = self._bucketwise_worker_error + if dist.get_world_size() > 1: + # Checkpoints involve every rank, including ranks outside this optimizer's DP group. + # Reuse the training error flag, but coordinate once globally before any checkpoint file is written. + error_flag = self._bucketwise_error_flag + if error_flag is None: + error_flag = get_accelerator().ByteTensor([0]) + self._bucketwise_error_flag = error_flag + error_flag.fill_(1 if local_error is not None else 0) + dist.all_reduce(error_flag, op=dist.ReduceOp.MAX) + if error_flag[0].item() != 0 and local_error is None: + raise RuntimeError("Reflow asynchronous optimizer update failed on another rank; aborting checkpoint") + if local_error is not None: + raise local_error + super().checkpoint_event_prologue() + def state_dict(self): self._wait_for_pending_state_updates() + if self._bucketwise_worker_error is not None: + raise self._bucketwise_worker_error return super().state_dict() def load_state_dict(self, @@ -1693,6 +1713,8 @@ def load_state_dict(self, def get_lean_optimizer_state(self): self._wait_for_pending_state_updates() + if self._bucketwise_worker_error is not None: + raise self._bucketwise_worker_error return super().get_lean_optimizer_state() def _get_fp32_opt_state_partition(self, param, release_swap_buffers, optim_state_key=None): diff --git a/docs/_tutorials/reflow.md b/docs/_tutorials/reflow.md index ffb3ff49e5d2..0814e352c08b 100644 --- a/docs/_tutorials/reflow.md +++ b/docs/_tutorials/reflow.md @@ -14,7 +14,7 @@ Adding a `reflow` block to `zero_optimization` turns on three cooperating behavi 2. **Half-precision gradient transfer.** Gradients are copied to CPU in BF16 and promoted to FP32 inside the AVX kernel. This halves the GPU-to-CPU traffic and removes the CPU-side FP32 gradient buffer. 3. **Asynchronous state commit.** The foreground only produces the new BF16 parameters. The FP32 master weights and optimizer state are committed by a background worker after the gradient clipping and overflow checks, overlapping the next forward. -Checkpoint APIs (`state_dict`, `load_state_dict`, and the `safe_get_*`/`safe_set_*` helpers) wait for that background commit, so they always see the fully applied step. +Checkpoint APIs (`state_dict`, `load_state_dict`, and the `safe_get_*`/`safe_set_*` helpers) wait for that background commit. If a worker fails, `engine.save_checkpoint()` aborts on every rank before writing checkpoint files. Direct `state_dict()` and `get_lean_optimizer_state()` calls raise any recorded local worker error. Checkpoint preparation shares one error flag across ranks; this adds no collectives to the training or direct state-read paths. ## Configuration diff --git a/tests/unit/v1/zero/test_reflow.py b/tests/unit/v1/zero/test_reflow.py index 191a11cdb316..8243f278b879 100644 --- a/tests/unit/v1/zero/test_reflow.py +++ b/tests/unit/v1/zero/test_reflow.py @@ -10,6 +10,7 @@ import copy import os import threading +from concurrent.futures import ThreadPoolExecutor from unittest.mock import patch import pytest @@ -694,6 +695,57 @@ def fail(*args): engine.destroy() +@pytest.mark.parametrize("worker_fails, read_before_save", [(True, False), (True, True), (False, True)]) +class TestReflowCheckpointWorkerFailures(DistributedTest): + world_size = [1, 2] if get_accelerator().device_count() > 1 else 1 + non_daemonic_procs = True + + def test_checkpoint_reports_worker_failure(self, worker_fails, read_before_save, tmpdir): + skip_if_reflow_training_unsupported() + model = SimpleModel(hidden_dim=16, nlayers=2) + config = get_offload_clip_config(reflow=True, gradient_clipping=0.0) + engine, optimizer, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) + save_dir = tmpdir / f"checkpoint_{dist.get_world_size()}" + message = "injected asynchronous state commit failure" + failing_rank = worker_fails and dist.get_rank() == 0 + + def commit(): + if failing_rank: + raise RuntimeError(message) + + try: + with ThreadPoolExecutor(max_workers=1) as executor: + # Inject the real Future at the async commit boundary to reproduce the checkpoint bug; + # CPU-only execution cannot run Reflow's GPU backward/copy path. + optimizer._last_state_update_future = executor.submit(commit) + read_error = None + if read_before_save and dist.get_rank() == 0: + try: + optimizer.state_dict() + except RuntimeError as error: + read_error = error + + if worker_fails: + with pytest.raises(RuntimeError) as save_error: + engine.save_checkpoint(str(save_dir), tag="test") + if failing_rank: + assert str(save_error.value) == message + assert not save_dir.exists() + if read_before_save and failing_rank: + assert str(read_error) == message + if failing_rank: + # A consumed future must not hide its failure from a later serialization attempt. + for read in (optimizer.state_dict, optimizer.get_lean_optimizer_state): + with pytest.raises(RuntimeError, match=message): + read() + else: + assert read_error is None + assert engine.save_checkpoint(str(save_dir), tag="test") + assert (save_dir / "latest").read_text(encoding="utf-8") == "test" + finally: + engine.destroy() + + def get_state_read_config(reflow, gradient_accumulation_steps, warmup_lr): offload_optimizer = {"device": "cpu", "pin_memory": True} config = { From 255aa7caefe577f58c66b1e9b3178ea34766b652 Mon Sep 17 00:00:00 2001 From: st-bang97 Date: Fri, 2 Oct 2026 05:20:53 +0000 Subject: [PATCH 04/19] Fix Intel MPI NUMA binding checks on target hosts Signed-off-by: st-bang97 --- deepspeed/launcher/multinode_runner.py | 17 ++- deepspeed/utils/numa.py | 41 ++++- docs/_tutorials/reflow.md | 2 + tests/unit/launcher/test_multinode_runner.py | 148 +++++++++++++++++++ 4 files changed, 200 insertions(+), 8 deletions(-) diff --git a/deepspeed/launcher/multinode_runner.py b/deepspeed/launcher/multinode_runner.py index 82a6773ae530..941ca9c99ed7 100644 --- a/deepspeed/launcher/multinode_runner.py +++ b/deepspeed/launcher/multinode_runner.py @@ -12,7 +12,7 @@ from shlex import split from abc import ABC, abstractmethod from deepspeed.accelerator import get_accelerator -from ..utils import logger, get_numactl_cmd +from ..utils import logger, numa from .constants import PDSH_MAX_FAN_OUT, MVAPICH_TMP_HOSTFILE @@ -303,10 +303,6 @@ def get_cmd(self, environment, active_resources): for k, v in self.exports.items(): export_cmd += ['-genv', f'{k}', f'{v}'] - if self.args.bind_cores_to_rank: - cores_per_rank, _ = get_numactl_cmd(self.args.bind_core_list, process_per_node, 0) - export_cmd += ['-genv', 'OMP_NUM_THREADS', str(cores_per_rank)] - export_cmd += ['-genv', 'MASTER_ADDR', str(self.args.master_addr)] export_cmd += ['-genv', 'MASTER_PORT', str(self.args.master_port)] export_cmd += ['-genv', 'WORLD_SIZE', str(total_process_count)] @@ -330,8 +326,15 @@ def get_cmd(self, environment, active_resources): local_rank = i % process_per_node python_exec = [] if self.args.bind_cores_to_rank: - _, numactl_cmd = get_numactl_cmd(self.args.bind_core_list, process_per_node, local_rank) - python_exec += numactl_cmd + # NUMA topology and permissions belong to the target host, not the launcher. + python_exec = [ + sys.executable, "-u", numa.__file__, "--num_local_procs", + str(process_per_node), "--local_rank", + str(local_rank) + ] + if self.args.bind_core_list is not None: + python_exec += ["--bind_core_list", self.args.bind_core_list] + python_exec.append("--") if not self.args.no_python: python_exec += [sys.executable, "-u"] diff --git a/deepspeed/utils/numa.py b/deepspeed/utils/numa.py index 6c3d4e269a98..b73d3fc0b364 100644 --- a/deepspeed/utils/numa.py +++ b/deepspeed/utils/numa.py @@ -10,11 +10,23 @@ # ] import os + +if __name__ == "__main__": + import sys + # Sibling types.py and logging.py must not shadow the standard library in the rank wrapper. + if sys.path and sys.path[0] == os.path.dirname(os.path.abspath(__file__)): + sys.path.pop(0) + import psutil import shutil import subprocess -from .logging import logger +# Running this file directly avoids importing DeepSpeed/PyTorch in the short-lived rank wrapper. +if __name__ == "__main__": + import logging + logger = logging.getLogger("DeepSpeed") +else: + from .logging import logger # return a list of list for cores to numa mapping @@ -239,3 +251,30 @@ def get_numactl_cmd(bind_core_list, num_local_procs, local_rank): logger.warning(f"'{' '.join(cpu_only_cmd)}' failed ({cpu_only_error}). " "Launching without numactl core/memory binding.") return cores_per_rank, [] + + +def main(args=None): + import argparse + + parser = argparse.ArgumentParser(description="Bind and exec a command using this host's NUMA permissions.") + parser.add_argument("--bind_core_list", default=None) + parser.add_argument("--num_local_procs", type=int, required=True) + parser.add_argument("--local_rank", type=int, required=True) + parser.add_argument("command", nargs=argparse.REMAINDER) + args = parser.parse_args(args) + command = args.command + if command and command[0] == "--": + command = command[1:] + if not command: + parser.error("a command to launch is required") + + cores_per_rank, numactl_cmd = get_numactl_cmd(args.bind_core_list, args.num_local_procs, args.local_rank) + env = os.environ.copy() + env["OMP_NUM_THREADS"] = str(cores_per_rank) + command = numactl_cmd + command + # Keep the MPI rank's PID and signal/exit handling without a resident wrapper process. + os.execvpe(command[0], command, env) + + +if __name__ == "__main__": + main() diff --git a/docs/_tutorials/reflow.md b/docs/_tutorials/reflow.md index 0814e352c08b..602452700a00 100644 --- a/docs/_tutorials/reflow.md +++ b/docs/_tutorials/reflow.md @@ -53,6 +53,8 @@ Launch with `--bind_cores_to_rank` so each rank runs on the CPU cores local to i deepspeed --bind_cores_to_rank train.py --deepspeed_config ds_config.json ``` +With Intel MPI, core selection and NUMA permission checks run on each target host at rank startup. If a container denies NUMA memory binding, the launcher retains CPU binding when permitted; if CPU binding is also denied, it launches without `numactl` binding. Invalid CPU or NUMA selections still fail. These checks add no work to training steps, but losing memory locality can affect throughput on hosts with multiple NUMA nodes. + Reflow always pins optimizer workers to NUMA-local cores and reserves `main_thread_cores` from those workers. `enable_cpu_affinity` additionally restricts the main process to its NUMA-local core slice. The remaining cores are split into workers of `bucketwise_cores_per_worker` cores. While the state commit overlaps the forward it uses only `state_update_cores` cores: every busy core lowers the CPU's turbo frequency, which would slow the launch-bound forward. ## Gradient clipping diff --git a/tests/unit/launcher/test_multinode_runner.py b/tests/unit/launcher/test_multinode_runner.py index 6bca5b605620..6faaaca4430c 100644 --- a/tests/unit/launcher/test_multinode_runner.py +++ b/tests/unit/launcher/test_multinode_runner.py @@ -9,6 +9,10 @@ from deepspeed.launcher.runner import (encode_world_info, parse_args, parse_inclusion_exclusion, apply_num_nodes_and_gpus) import os +import sys +import json +import subprocess +from pathlib import Path import pytest @@ -153,3 +157,147 @@ def test_mvapich_runner(runner_info): runner = mnrunner.MVAPICHRunner(args, world_info, resource_pool) cmd = runner.get_cmd(env, resource_pool) assert cmd[0] == 'mpirun' + + +@pytest.fixture +def target_numactl(tmp_path, monkeypatch): + # Model the numactl CLI, including exec and host-specific topology/permissions. + fake_numactl = tmp_path / 'numactl' + fake_numactl.write_text(f'''#!{sys.executable} +import json +import os +import sys +with open(os.environ['NUMACTL_LOG'], 'a') as log: + log.write(json.dumps(sys.argv[1:]) + '\\n') +if sys.argv[1:] == ['--hardware']: + node = int(os.environ.get('NUMACTL_NODE', '0')) + print('available: 2 nodes (0-1)') + for i in range(2): + start = 0 if i == node else 8 + print('node %d cpus: %s' % (i, ' '.join(str(c) for c in range(start, start + 8)))) + sys.exit(0) +args = sys.argv[1:] +while args and args[0] in ('-m', '-p', '-C'): + option = args[0] + if option in os.environ.get('NUMACTL_DENIED', '').split(): + error = os.environ.get('NUMACTL_CPU_ERROR') if option == '-C' else None + print(error or os.environ.get('NUMACTL_ERROR', 'Operation not permitted'), file=sys.stderr) + sys.exit(1) + args = args[2:] +os.environ['NUMACTL_BINDING'] = json.dumps(sys.argv[1:len(sys.argv) - len(args)]) +os.execvp(args[0], args) +''') + fake_numactl.chmod(0o755) + monkeypatch.setenv('PATH', f"{tmp_path}:{os.environ['PATH']}") + repo_root = Path(mnrunner.__file__).resolve().parents[2] + monkeypatch.setenv('PYTHONPATH', f"{repo_root}:{os.environ.get('PYTHONPATH', '')}") + monkeypatch.setenv('NUMACTL_LOG', str(tmp_path / 'launcher-numactl.log')) + monkeypatch.setenv('NUMACTL_DENIED', '-m') + monkeypatch.setenv('NUMACTL_ERROR', 'invalid NUMA node') + return tmp_path + + +@pytest.mark.parametrize('launch_mode', [[], ['--module'], ['--no_python']]) +@pytest.mark.parametrize('denied_options', ['', '-m', '-m -C']) +def test_impi_binding_uses_target_host(runner_info, target_numactl, launch_mode, denied_options): + env, resource_pool, world_info, _ = runner_info + script = target_numactl / 'rank_payload.py' + script.write_text(f'''#!{sys.executable} +import json +import os +import sys +with open(sys.argv[1], 'w') as output: + json.dump(dict(pid=os.getpid(), rank=os.environ['RANK'], local_rank=os.environ['LOCAL_RANK'], + threads=os.environ['OMP_NUM_THREADS'], arguments=sys.argv[2:], + binding=json.loads(os.environ.get('NUMACTL_BINDING', '[]'))), output) +sys.exit(17) +''') + script.chmod(0o755) + user_script = 'rank_payload' if '--module' in launch_mode else str(script) + output = target_numactl / 'rank.json' + args = parse_args(['--bind_cores_to_rank', '--bind_core_list', '0-7'] + launch_mode + + [user_script, str(output), 'argument with spaces']) + runner = mnrunner.IMPIRunner(args, world_info, resource_pool) + cmd = runner.get_cmd(env, resource_pool) + # Command construction must neither probe nor depend on the launcher's permissions. + assert not (target_numactl / 'launcher-numactl.log').exists() + groups = [] + group = [] + for arg in cmd[cmd.index('-n'):]: + if arg == ':': + groups.append(group) + group = [] + else: + group.append(arg) + groups.append(group) + + # Execute the MPI rank commands with different target-host environments. + for rank, node, denied in [(1, '0', ''), (5, '1', denied_options)]: + rank_env = os.environ.copy() + rank_env.update(RANK=str(rank), + LOCAL_RANK='1', + LOCAL_SIZE='4', + NUMACTL_NODE=node, + NUMACTL_DENIED=denied, + NUMACTL_ERROR='Operation not permitted', + NUMACTL_LOG=str(target_numactl / f'target-{rank}.log')) + proc = subprocess.Popen(groups[rank][8:], + env=rank_env, + cwd=target_numactl, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + _, stderr = proc.communicate(timeout=30) + assert proc.returncode == 17, stderr.decode() + result = json.loads(output.read_text()) + if '-C' in denied: + binding = [] + elif '-m' in denied: + binding = ['-C', '2-3'] + else: + binding = ['-m', node, '-C', '2-3'] + assert result == dict(pid=proc.pid, + rank=str(rank), + local_rank='1', + threads='2', + arguments=['argument with spaces'], + binding=binding) + + +@pytest.mark.parametrize('error', ['invalid NUMA node', 'invalid CPU list']) +def test_impi_helper_rejects_invalid_binding(target_numactl, error): + output = target_numactl / 'must-not-launch' + helper = Path(mnrunner.numa.__file__) + env = os.environ.copy() + env.update(RANK='0', LOCAL_RANK='0', LOCAL_SIZE='2', NUMACTL_DENIED='-m -C') + if error == 'invalid CPU list': + env.update(NUMACTL_ERROR='Operation not permitted', NUMACTL_CPU_ERROR=error) + else: + env['NUMACTL_ERROR'] = error + result = subprocess.run([ + sys.executable, + str(helper), '--num_local_procs', '2', '--local_rank', '0', '--bind_core_list', '0-7', '--', 'touch', + str(output) + ], + env=env, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + timeout=30) + assert result.returncode != 0 + assert error in result.stderr.decode() + assert not output.exists() + + +@pytest.mark.parametrize('launch_mode', [[], ['--module'], ['--no_python']]) +def test_impi_without_binding_skips_numa_wrapper(runner_info, launch_mode): + env, resource_pool, world_info, _ = runner_info + args = parse_args(launch_mode + ['training_script', '--training-arg']) + runner = mnrunner.IMPIRunner(args, world_info, resource_pool) + cmd = runner.get_cmd(env, resource_pool) + expected = [] + if not args.no_python: + expected = [sys.executable, '-u'] + if args.module: + expected.append('-m') + expected += ['training_script', '--training-arg'] + first_rank_command = cmd.index('-n') + 8 + assert cmd[first_rank_command:first_rank_command + len(expected)] == expected From 0ae955c830064ac927cbd33bb82b4d0e875c8703 Mon Sep 17 00:00:00 2001 From: st-bang97 Date: Fri, 2 Oct 2026 06:01:49 +0000 Subject: [PATCH 05/19] Support per-group maximize semantics in ReFlow Adam Signed-off-by: st-bang97 --- csrc/adam/reflow_cpu_adam_bindings.cpp | 18 +++-- csrc/adam/reflow_cpu_adam_impl.cpp | 10 ++- csrc/includes/reflow_cpu_adam.h | 9 ++- deepspeed/runtime/reflow/README.md | 6 +- deepspeed/runtime/reflow/engine.py | 3 +- deepspeed/runtime/reflow/reflow_cpu_adam.py | 24 ++++-- deepspeed/runtime/reflow/reflow_stage3.py | 10 ++- docs/_pages/config-json.md | 2 +- .../unit/v1/ops/test_reflow_cpu_optimizers.py | 76 +++++++++++++++++++ tests/unit/v1/zero/test_reflow.py | 59 ++++++++++++++ 10 files changed, 194 insertions(+), 23 deletions(-) diff --git a/csrc/adam/reflow_cpu_adam_bindings.cpp b/csrc/adam/reflow_cpu_adam_bindings.cpp index 0c8cc1d01c1e..d01aaf24ff37 100644 --- a/csrc/adam/reflow_cpu_adam_bindings.cpp +++ b/csrc/adam/reflow_cpu_adam_bindings.cpp @@ -26,7 +26,8 @@ static inline int reflow_ds_adam_step_params_halfgrad_gilfree(int optimizer_id, torch::Tensor& exp_avg_sq, torch::Tensor& half_params, float combined_scale, - bool skip_increment_step = false) + bool skip_increment_step = false, + bool maximize = false) { pybind11::gil_scoped_release release; return reflow_ds_adam_step_params_halfgrad(optimizer_id, @@ -43,7 +44,8 @@ static inline int reflow_ds_adam_step_params_halfgrad_gilfree(int optimizer_id, exp_avg_sq, half_params, combined_scale, - skip_increment_step); + skip_increment_step, + maximize); } static inline int reflow_ds_adam_state_step_halfgrad_gilfree(int optimizer_id, @@ -59,7 +61,8 @@ static inline int reflow_ds_adam_state_step_halfgrad_gilfree(int optimizer_id, torch::Tensor& exp_avg, torch::Tensor& exp_avg_sq, float combined_scale, - bool skip_increment_step = false) + bool skip_increment_step = false, + bool maximize = false) { pybind11::gil_scoped_release release; return reflow_ds_adam_state_step_halfgrad(optimizer_id, @@ -75,7 +78,8 @@ static inline int reflow_ds_adam_state_step_halfgrad_gilfree(int optimizer_id, exp_avg, exp_avg_sq, combined_scale, - skip_increment_step); + skip_increment_step, + maximize); } static inline int reflow_ds_bf16_accumulate_gilfree(torch::Tensor& dst, torch::Tensor& src) @@ -116,7 +120,8 @@ void bind_reflow_adam(pybind11::module_& m) pybind11::arg("exp_avg_sq"), pybind11::arg("half_params"), pybind11::arg("combined_scale"), - pybind11::arg("skip_increment_step") = false); + pybind11::arg("skip_increment_step") = false, + pybind11::arg("maximize") = false); m.def("reflow_adam_update_state_halfgrad", &reflow_ds_adam_state_step_halfgrad_gilfree, "Reflow CPU Adam update state stream with half gradients, GIL-released (C++)", @@ -133,7 +138,8 @@ void bind_reflow_adam(pybind11::module_& m) pybind11::arg("exp_avg"), pybind11::arg("exp_avg_sq"), pybind11::arg("combined_scale"), - pybind11::arg("skip_increment_step") = false); + pybind11::arg("skip_increment_step") = false, + pybind11::arg("maximize") = false); m.def("reflow_adam_memory_fence", &reflow_adam_memory_fence, "Reflow CPU Adam memory fence (C++)"); diff --git a/csrc/adam/reflow_cpu_adam_impl.cpp b/csrc/adam/reflow_cpu_adam_impl.cpp index f6a0b9cb88e5..2a99d4253b88 100644 --- a/csrc/adam/reflow_cpu_adam_impl.cpp +++ b/csrc/adam/reflow_cpu_adam_impl.cpp @@ -309,8 +309,11 @@ int reflow_ds_adam_step_params_halfgrad(int optimizer_id, torch::Tensor& exp_avg_sq, torch::Tensor& half_params, float combined_scale, - bool skip_increment_step) + bool skip_increment_step, + bool maximize) { + // Encode direction in the scale so SIMD and scalar tails share the same gradient transform. + if (maximize) { combined_scale = -combined_scale; } auto params_c = params_fp32.contiguous(); auto grads_c = grads.contiguous(); auto exp_avg_c = exp_avg.contiguous(); @@ -425,8 +428,11 @@ int reflow_ds_adam_state_step_halfgrad(int optimizer_id, torch::Tensor& exp_avg, torch::Tensor& exp_avg_sq, float combined_scale, - bool skip_increment_step) + bool skip_increment_step, + bool maximize) { + // Encode direction in the scale so SIMD and scalar tails share the same gradient transform. + if (maximize) { combined_scale = -combined_scale; } unsigned int total_cpus = reflow_get_available_cpu_count(); int configured_num_threads = s_reflow_optimizers[optimizer_id].state_opt->get_num_threads(); unsigned int max_omp_threads = reflow_resolve_omp_threads(configured_num_threads, total_cpus); diff --git a/csrc/includes/reflow_cpu_adam.h b/csrc/includes/reflow_cpu_adam.h index 9542d0870855..10f3eed68a7d 100644 --- a/csrc/includes/reflow_cpu_adam.h +++ b/csrc/includes/reflow_cpu_adam.h @@ -218,7 +218,8 @@ void Reflow_Adam_Optimizer::Step_AVX_HalfGrad(size_t* rounded_size, #endif // Pick the loop specialized for this step's flags, so no per-element branch remains. - bool unscale_grads = (combined_scale > 1.0f); + // A negative scale folds maximizing into the existing gradient multiply, before weight decay. + bool unscale_grads = (combined_scale > 1.0f || combined_scale < 0.0f); bool decay_grad = (_weight_decay > 0 && !_adamw_mode); bool decay_param = (_weight_decay > 0 && _adamw_mode); using G = ds_grad_precision_t; @@ -397,7 +398,8 @@ int reflow_ds_adam_step_params_halfgrad(int optimizer_id, torch::Tensor& exp_avg_sq, torch::Tensor& half_params, float combined_scale = 1.0f, - bool skip_increment_step = false); + bool skip_increment_step = false, + bool maximize = false); int reflow_ds_adam_state_step_halfgrad(int optimizer_id, size_t step, @@ -412,7 +414,8 @@ int reflow_ds_adam_state_step_halfgrad(int optimizer_id, torch::Tensor& exp_avg, torch::Tensor& exp_avg_sq, float combined_scale = 1.0f, - bool skip_increment_step = false); + bool skip_increment_step = false, + bool maximize = false); int reflow_destroy_adam_optimizer(int optimizer_id); diff --git a/deepspeed/runtime/reflow/README.md b/deepspeed/runtime/reflow/README.md index ab0375360c8e..d587150c05dc 100644 --- a/deepspeed/runtime/reflow/README.md +++ b/deepspeed/runtime/reflow/README.md @@ -91,7 +91,11 @@ a disjoint NUMA-local core slice) plus a single chained async-state worker. A client that passes a plain `DeepSpeedCPUAdam` / `DeepSpeedCPULion` is auto-remapped to `ReflowCPUAdam` / `ReflowCPULion` when the `reflow` block is set (see -`engine._maybe_remap_to_reflow_cpu_optimizer`). PyTorch `Adam` and `AdamW` are also remapped. +`engine._maybe_remap_to_reflow_cpu_optimizer`). PyTorch `Adam` and `AdamW` are also remapped, preserving each group's `maximize` option. +`ReflowCPUAdam` also accepts `maximize=True` directly or per parameter group. Both parameter generation +and the deferred state commit negate the objective gradient before Adam weight decay; AdamW +weight decay keeps its usual direction. The sign is combined with gradient unscaling inside the CPU +kernel, without an extra gradient buffer or pass. Pass client LR schedulers as factories or configure them in DeepSpeed; a scheduler already bound to the original optimizer cannot follow the remapping and is rejected. diff --git a/deepspeed/runtime/reflow/engine.py b/deepspeed/runtime/reflow/engine.py index afa218363089..23366b4de10f 100644 --- a/deepspeed/runtime/reflow/engine.py +++ b/deepspeed/runtime/reflow/engine.py @@ -85,7 +85,7 @@ def maybe_remap_client_optimizer(engine: "DeepSpeedEngine", optimizer): if is_lion: keep = ("lr", "betas", "weight_decay") else: - keep = ("lr", "betas", "eps", "weight_decay", "bias_correction", "amsgrad") + keep = ("lr", "betas", "eps", "weight_decay", "bias_correction", "amsgrad", "maximize") param_groups = [{"params": g["params"], **{k: g[k] for k in keep if k in g}} for g in optimizer.param_groups] if is_lion: log_dist(f"Reflow enabled: remapping client optimizer {name} to ReflowCPULion", ranks=[0]) @@ -105,5 +105,6 @@ def maybe_remap_client_optimizer(engine: "DeepSpeedEngine", optimizer): weight_decay=defaults.get("weight_decay", 0.0), bias_correction=defaults.get("bias_correction", True), amsgrad=defaults.get("amsgrad", False), + maximize=defaults.get("maximize", False), adamw_mode=bool(adamw_mode), num_threads=reflow_num_threads(engine)) diff --git a/deepspeed/runtime/reflow/reflow_cpu_adam.py b/deepspeed/runtime/reflow/reflow_cpu_adam.py index bf41b77c0728..0677bc69c0b2 100644 --- a/deepspeed/runtime/reflow/reflow_cpu_adam.py +++ b/deepspeed/runtime/reflow/reflow_cpu_adam.py @@ -47,12 +47,14 @@ def __init__(self, amsgrad=False, adamw_mode=True, fp32_optimizer_states=True, - num_threads=None): + num_threads=None, + maximize=False): """Reflow CPU Adam(W). Same arguments as :class:`DeepSpeedCPUAdam`, requiring ``fp32_optimizer_states=True``, plus: Arguments: + maximize (bool): maximize the objective instead of minimizing it; may be overridden per group. num_threads (int): number of CPU threads for the Adam update. ``None`` uses all available cores. """ @@ -67,7 +69,8 @@ def __init__(self, eps=eps, weight_decay=weight_decay, bias_correction=bias_correction, - amsgrad=amsgrad) + amsgrad=amsgrad, + maximize=maximize) super(DeepSpeedCPUAdam, self).__init__(model_params, default_args) cpu_info = get_cpu_info() @@ -183,8 +186,17 @@ def step_state_halfgrad(self, half_grad_buffers, combined_scale=1.0, element_ran exp_avg_sq = exp_avg_sq.narrow(0, start, numel) beta1, beta2 = hyperparams['betas'] - self.ds_opt_adam.reflow_adam_update_state_halfgrad(self.opt_id, state['step'], hyperparams['lr'], - beta1, beta2, hyperparams['eps'], + self.ds_opt_adam.reflow_adam_update_state_halfgrad(self.opt_id, + state['step'], + hyperparams['lr'], + beta1, + beta2, + hyperparams['eps'], hyperparams['weight_decay'], - hyperparams['bias_correction'], params, grad, - exp_avg, exp_avg_sq, combined_scale) + hyperparams['bias_correction'], + params, + grad, + exp_avg, + exp_avg_sq, + combined_scale, + maximize=hyperparams.get("maximize", False)) diff --git a/deepspeed/runtime/reflow/reflow_stage3.py b/deepspeed/runtime/reflow/reflow_stage3.py index b786cfa3cb40..904dac411586 100644 --- a/deepspeed/runtime/reflow/reflow_stage3.py +++ b/deepspeed/runtime/reflow/reflow_stage3.py @@ -994,6 +994,7 @@ def _bucketwise_chunk_update_worker(self, work_item): eps = work_item.get("eps") weight_decay = work_item.get("weight_decay") bias_correction = work_item.get("bias_correction", True) + maximize = work_item.get("maximize", False) # increment_step controls the per-range skip flag only; the Python state['step'] # is committed once at the end of step(). if target_step is None: @@ -1051,6 +1052,7 @@ def _bucketwise_chunk_update_worker(self, work_item): half_params_slice, combined_scale, not range_increment_step, + maximize, ) self.optimizer.ds_opt_adam.reflow_adam_memory_fence() @@ -1207,20 +1209,21 @@ def _prepare_state_and_params(): eps = group.get('eps', 0.0) weight_decay = group['weight_decay'] bias_correction = group.get('bias_correction', True) + maximize = group.get('maximize', False) - return increment_step, target_step, lr, beta1, beta2, eps, weight_decay, bias_correction + return increment_step, target_step, lr, beta1, beta2, eps, weight_decay, bias_correction, maximize if already_locked: result = _prepare_state_and_params() if result is None: return None - increment_step, target_step, lr, beta1, beta2, eps, weight_decay, bias_correction = result + increment_step, target_step, lr, beta1, beta2, eps, weight_decay, bias_correction, maximize = result else: with lock: result = _prepare_state_and_params() if result is None: return None - increment_step, target_step, lr, beta1, beta2, eps, weight_decay, bias_correction = result + increment_step, target_step, lr, beta1, beta2, eps, weight_decay, bias_correction, maximize = result work_item = { "sub_group_id": sub_group_id, @@ -1237,6 +1240,7 @@ def _prepare_state_and_params(): "eps": eps, "weight_decay": weight_decay, "bias_correction": bias_correction, + "maximize": maximize, } future = self._bucketwise_update_submit(self._bucketwise_chunk_update_worker, work_item) diff --git a/docs/_pages/config-json.md b/docs/_pages/config-json.md index af2d69dc12d7..847460277f41 100644 --- a/docs/_pages/config-json.md +++ b/docs/_pages/config-json.md @@ -690,7 +690,7 @@ Note that if the value of "device" is not specified or not supported, an asserti ### Reflow [Reflow](/tutorials/reflow/) is an asynchronous CPU-offload optimizer for ZeRO stage 3. The CPU optimizer runs per gradient bucket during backward, gradients move to CPU in BF16, and the FP32 master weights and optimizer state are committed in the background while the next forward runs. -The `reflow` block enables it, so an empty block is enough to run with the defaults. Reflow requires `"stage": 3`, `"bf16": {"enabled": true}`, `offload_optimizer` on `cpu` (or `nvme`), and CPU Adam/Lion kernels built with AVX2 or AVX-512. Model parameters and offloaded gradients must be BF16; master weights and optimizer states must be FP32. FP16 or FP32 model parameters, `torch_autocast`, low-precision master weights/states, and `fp32_optimizer_states: false` are rejected. It uses `ReflowCPUAdam`/`ReflowCPULion`; a client `DeepSpeedCPUAdam`/`DeepSpeedCPULion` is remapped automatically. Call `engine.step()`; direct `ReflowCPUAdam.step()` and `ReflowCPULion.step()` calls are rejected. It is not compatible with `super_offload`, ZenFlow, DeepCompile, the Muon optimizer (support to be implemented), or `managed_gradient_accumulation: false`. +The `reflow` block enables it, so an empty block is enough to run with the defaults. Reflow requires `"stage": 3`, `"bf16": {"enabled": true}`, `offload_optimizer` on `cpu` (or `nvme`), and CPU Adam/Lion kernels built with AVX2 or AVX-512. Model parameters and offloaded gradients must be BF16; master weights and optimizer states must be FP32. FP16 or FP32 model parameters, `torch_autocast`, low-precision master weights/states, and `fp32_optimizer_states: false` are rejected. It uses `ReflowCPUAdam`/`ReflowCPULion`; a client `DeepSpeedCPUAdam`/`DeepSpeedCPULion` is remapped automatically. Adam/AdamW support `maximize`, including per-group settings preserved when remapping a PyTorch optimizer; the default is `false`. Call `engine.step()`; direct `ReflowCPUAdam.step()` and `ReflowCPULion.step()` calls are rejected. It is not compatible with `super_offload`, ZenFlow, DeepCompile, the Muon optimizer (support to be implemented), or `managed_gradient_accumulation: false`. ```json "reflow": { "num_threads": null, diff --git a/tests/unit/v1/ops/test_reflow_cpu_optimizers.py b/tests/unit/v1/ops/test_reflow_cpu_optimizers.py index 188eace65f9e..f5c67c6394c5 100644 --- a/tests/unit/v1/ops/test_reflow_cpu_optimizers.py +++ b/tests/unit/v1/ops/test_reflow_cpu_optimizers.py @@ -322,3 +322,79 @@ def accumulate(): executor.submit(accumulate).result() # A restricted OpenMP team must still finish every SIMD chunk and the non-vectorized tail. assert torch.equal(dst, expected) + + +@pytest.mark.parametrize('adamw_mode', [False, True], ids=['adam', 'adamw']) +@pytest.mark.parametrize('model_size', [7, 129, 4099]) +@pytest.mark.parametrize('combined_scale', [1.0, 8.0]) +def test_adam_maximize_groups_match_pytorch(adamw_mode, model_size, combined_scale): + # Catch dropped per-group directions, incorrect decay, scalar-tail omissions, and a + # deferred commit that reads changed live flags instead of the submitted step's snapshot. + if not deepspeed.ops.__compatible_ops__[CPUAdamBuilder.NAME]: + pytest.skip('CPUAdamBuilder is not compatible') + _skip_without_avx(CPUAdamBuilder) + generator = torch.Generator().manual_seed(4321) + params = [torch.nn.Parameter(torch.randn(model_size, generator=generator)) for _ in range(2)] + references = [torch.nn.Parameter(p.detach().clone()) for p in params] + groups = [{'params': [params[0]]}, {'params': [params[1]], 'maximize': False}] + reference_groups = [{'params': [references[0]]}, {'params': [references[1]], 'maximize': False}] + kwargs = dict(lr=0.05, betas=(0.8, 0.95), eps=1e-5, weight_decay=0.1, maximize=True) + optimizer = ReflowCPUAdam(groups, adamw_mode=adamw_mode, num_threads=1, **kwargs) + reference_type = torch.optim.AdamW if adamw_mode else torch.optim.Adam + reference = reference_type(reference_groups, foreach=False, **kwargs) + module = optimizer.ds_opt_adam + for p in params: + optimizer.state[p].update(step=0, exp_avg=torch.zeros_like(p), exp_avg_sq=torch.zeros_like(p)) + + for step in range(1, 6): + grads = [torch.randn(model_size, generator=generator).bfloat16() for _ in params] + for p, grad in zip(references, grads): + p.grad = grad.float() / combined_scale + reference.step() + snapshots = { + i: { + k: v + for k, v in group.items() if k != 'params' + } + for i, group in enumerate(optimizer.param_groups) + } + for i, p in enumerate(params): + state = optimizer.state[p] + half_params = torch.empty(model_size, dtype=torch.bfloat16) + before = p.detach().clone() + before_momentum = state['exp_avg'].clone() + before_variance = state['exp_avg_sq'].clone() + group = snapshots[i] + module.reflow_adam_update_params_halfgrad(optimizer.opt_id, + step, + group['lr'], + *group['betas'], + group['eps'], + group['weight_decay'], + group['bias_correction'], + p, + grads[i], + state['exp_avg'], + state['exp_avg_sq'], + half_params, + combined_scale, + maximize=group['maximize']) + optimizer.memory_fence() + torch.testing.assert_close(half_params.float(), + references[i].detach().bfloat16().float(), + rtol=0.008, + atol=1e-5) + assert torch.equal(p, before) + assert torch.equal(state['exp_avg'], before_momentum) + assert torch.equal(state['exp_avg_sq'], before_variance) + state['step'] = step + optimizer.param_groups[i]['maximize'] = not group['maximize'] + optimizer.step_state_halfgrad(grads, combined_scale=combined_scale, group_hyperparams=snapshots) + optimizer.memory_fence() + for i, p in enumerate(params): + optimizer.param_groups[i]['maximize'] = snapshots[i]['maximize'] + state = optimizer.state[p] + expected = reference.state[references[i]] + torch.testing.assert_close(p, references[i], rtol=2e-6, atol=2e-7) + torch.testing.assert_close(state['exp_avg'], expected['exp_avg'], rtol=2e-6, atol=2e-7) + torch.testing.assert_close(state['exp_avg_sq'], expected['exp_avg_sq'], rtol=2e-6, atol=2e-7) diff --git a/tests/unit/v1/zero/test_reflow.py b/tests/unit/v1/zero/test_reflow.py index 8243f278b879..c5c7100eb312 100644 --- a/tests/unit/v1/zero/test_reflow.py +++ b/tests/unit/v1/zero/test_reflow.py @@ -836,3 +836,62 @@ def test_matches_zero_offload(self, gradient_accumulation_steps, warmup_lr): expected_step, actual_step): for index, (want, got) in enumerate(zip(expected_tensors, actual_tensors)): assert torch.equal(got, want), f"{name}[{index}] differs after step {step}" + + +class TestReflowMaximizeClientInitialization(DistributedTest): + world_size = 1 + non_daemonic_procs = True + + @pytest.mark.parametrize('optimizer_type', [torch.optim.Adam, torch.optim.AdamW]) + def test_preserves_group_directions(self, optimizer_type): + skip_if_reflow_training_unsupported() + model = SimpleModel(hidden_dim=16, nlayers=2) + params = list(model.parameters()) + optimizer = optimizer_type([{'params': params[:2]}, {'params': params[2:], 'maximize': False}], maximize=True) + config = get_variant_config(reflow=True, variant='client_optimizer') + config['zero_force_ds_cpu_optimizer'] = False + engine, _, _, _ = deepspeed.initialize(model=model, optimizer=optimizer, config=config) + try: + actual = engine.optimizer.optimizer + assert isinstance(actual, ReflowCPUAdam) + assert [group['maximize'] for group in actual.param_groups] == [True, False] + finally: + engine.destroy() + + +@needs_gpu_accelerator +class TestReflowMaximizeTraining(DistributedTest): + world_size = [1, 2] + + @pytest.mark.parametrize('adamw_mode', [False, True]) + def test_matches_minimizing_negative_loss(self, adamw_mode): + # Negating the loss supplies an independent ascent oracle using the existing descent optimizer. + skip_if_reflow_training_unsupported() + torch.manual_seed(1234) + initial = SimpleModel(hidden_dim=16, nlayers=2) + batches = make_batches(16, count=5) + results = [] + for reflow in (False, True): + model = copy.deepcopy(initial) + config = get_variant_config(reflow, 'client_optimizer') + config['zero_force_ds_cpu_optimizer'] = False + if reflow: + optimizer_type = torch.optim.AdamW if adamw_mode else torch.optim.Adam + optimizer = optimizer_type(model.parameters(), lr=0.01, weight_decay=0.1, maximize=True) + else: + optimizer = DeepSpeedCPUAdam(model.parameters(), lr=0.01, weight_decay=0.1, adamw_mode=adamw_mode) + engine, _, _, _ = deepspeed.initialize(model=model, optimizer=optimizer, config=config) + try: + losses = [] + for inputs, labels in batches: + loss = engine(inputs, labels) + engine.backward(loss if reflow else -loss) + engine.step() + losses.append(loss.detach().clone()) + results.append((losses, [safe_get_full_fp32_param(p).clone() for p in engine.module.parameters()])) + finally: + engine.destroy() + for expected, actual in zip(results[0][0], results[1][0]): + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + for expected, actual in zip(results[0][1], results[1][1]): + torch.testing.assert_close(actual, expected, rtol=0, atol=0) From d7d20f3792cc5c015ca9b3314b919bd1c590f4ff Mon Sep 17 00:00:00 2001 From: st-bang97 Date: Fri, 2 Oct 2026 07:20:27 +0000 Subject: [PATCH 06/19] Allow FP16 parameters in Reflow Signed-off-by: st-bang97 --- deepspeed/runtime/config.py | 6 +-- deepspeed/runtime/reflow/README.md | 4 +- deepspeed/runtime/reflow/reflow_stage3.py | 5 +- docs/_pages/config-json.md | 2 +- docs/_tutorials/reflow.md | 4 +- tests/unit/v1/zero/test_reflow.py | 62 +++++++++++++++++------ 6 files changed, 57 insertions(+), 26 deletions(-) diff --git a/deepspeed/runtime/config.py b/deepspeed/runtime/config.py index 75a525c02335..01f9ae0ff73c 100755 --- a/deepspeed/runtime/config.py +++ b/deepspeed/runtime/config.py @@ -703,9 +703,9 @@ def _do_error_check(self): raise ValueError("Reflow does not support the Muon optimizer yet; remove the 'reflow' block from " "zero_optimization to use Muon with ZeRO-Offload") if reflow_enabled: - if not self.bfloat16_config.enabled or self.float16_config.enabled or self.torch_autocast_enabled: - raise ValueError("Reflow requires BF16 model parameters with 'bf16.enabled': true; " - "FP16, FP32 model parameters and torch_autocast are not supported.") + if not (self.bfloat16_config.enabled or self.float16_config.enabled) or self.torch_autocast_enabled: + raise ValueError("Reflow requires FP16 or BF16 model parameters; enable 'fp16.enabled' " + "or 'bf16.enabled'. FP32 model parameters and torch_autocast are not supported.") if (self.float16_config.fp16_master_weights_and_grads or self.bfloat16_config.bf16_master_weights_and_grads or self.bfloat16_config.bf16_optimizer_states): raise ValueError("Reflow requires FP32 master weights and optimizer states; " diff --git a/deepspeed/runtime/reflow/README.md b/deepspeed/runtime/reflow/README.md index d587150c05dc..2b311d02e5bc 100644 --- a/deepspeed/runtime/reflow/README.md +++ b/deepspeed/runtime/reflow/README.md @@ -11,8 +11,8 @@ GPU compute and the inter-GPU gradient reduction. momentum tensor (`exp_avg`) — no second moment, no `eps`, no bias correction — so its offloaded state is half of Adam's; everything else in the pipeline below is identical. -**Precision support:** BF16 model parameters and gradients with FP32 master weights and optimizer -states. FP16/FP32 model parameters, `torch_autocast`, low-precision master weights/states, and +**Precision support:** FP16/BF16 model parameters and gradients with FP32 master weights and optimizer +states. FP32 model parameters, `torch_autocast`, low-precision master weights/states, and `fp32_optimizer_states=False` are rejected at initialization. Use `engine.step()` after `deepspeed.initialize()`; direct `ReflowCPUAdam.step()` and `ReflowCPULion.step()` calls are rejected. diff --git a/deepspeed/runtime/reflow/reflow_stage3.py b/deepspeed/runtime/reflow/reflow_stage3.py index 904dac411586..2ee0aecbc016 100644 --- a/deepspeed/runtime/reflow/reflow_stage3.py +++ b/deepspeed/runtime/reflow/reflow_stage3.py @@ -50,8 +50,9 @@ class ReflowOptimizer_Stage3(DeepSpeedZeroOptimizer_Stage3): def __init__(self, module, init_optimizer, param_names, timers, ds_config, reflow_config, **kwargs): # zero.Init models bypass the engine's parameter cast, so validate their actual dtype too. - if any(param.is_floating_point() and param.dtype != torch.bfloat16 for param in module.parameters()): - raise ValueError("Reflow requires BF16 model parameters; FP16 and FP32 model parameters " + if any(param.is_floating_point() and param.dtype not in (torch.float16, torch.bfloat16) + for param in module.parameters()): + raise ValueError("Reflow requires FP16 or BF16 model parameters; FP32 model parameters " "are not supported.") self._reflow_config = reflow_config # These attributes must exist before super().__init__ runs: the parent constructor diff --git a/docs/_pages/config-json.md b/docs/_pages/config-json.md index 847460277f41..ed2b3a934f79 100644 --- a/docs/_pages/config-json.md +++ b/docs/_pages/config-json.md @@ -690,7 +690,7 @@ Note that if the value of "device" is not specified or not supported, an asserti ### Reflow [Reflow](/tutorials/reflow/) is an asynchronous CPU-offload optimizer for ZeRO stage 3. The CPU optimizer runs per gradient bucket during backward, gradients move to CPU in BF16, and the FP32 master weights and optimizer state are committed in the background while the next forward runs. -The `reflow` block enables it, so an empty block is enough to run with the defaults. Reflow requires `"stage": 3`, `"bf16": {"enabled": true}`, `offload_optimizer` on `cpu` (or `nvme`), and CPU Adam/Lion kernels built with AVX2 or AVX-512. Model parameters and offloaded gradients must be BF16; master weights and optimizer states must be FP32. FP16 or FP32 model parameters, `torch_autocast`, low-precision master weights/states, and `fp32_optimizer_states: false` are rejected. It uses `ReflowCPUAdam`/`ReflowCPULion`; a client `DeepSpeedCPUAdam`/`DeepSpeedCPULion` is remapped automatically. Adam/AdamW support `maximize`, including per-group settings preserved when remapping a PyTorch optimizer; the default is `false`. Call `engine.step()`; direct `ReflowCPUAdam.step()` and `ReflowCPULion.step()` calls are rejected. It is not compatible with `super_offload`, ZenFlow, DeepCompile, the Muon optimizer (support to be implemented), or `managed_gradient_accumulation: false`. +The `reflow` block enables it, so an empty block is enough to run with the defaults. Reflow requires `"stage": 3`, `"fp16": {"enabled": true}` or `"bf16": {"enabled": true}`, `offload_optimizer` on `cpu` (or `nvme`), and CPU Adam/Lion kernels built with AVX2 or AVX-512. Model parameters and offloaded gradients must be FP16/BF16; master weights and optimizer states must be FP32. FP32 model parameters, `torch_autocast`, low-precision master weights/states, and `fp32_optimizer_states: false` are rejected. It uses `ReflowCPUAdam`/`ReflowCPULion`; a client `DeepSpeedCPUAdam`/`DeepSpeedCPULion` is remapped automatically. Adam/AdamW support `maximize`, including per-group settings preserved when remapping a PyTorch optimizer; the default is `false`. Call `engine.step()`; direct `ReflowCPUAdam.step()` and `ReflowCPULion.step()` calls are rejected. It is not compatible with `super_offload`, ZenFlow, DeepCompile, the Muon optimizer (support to be implemented), or `managed_gradient_accumulation: false`. ```json "reflow": { "num_threads": null, diff --git a/docs/_tutorials/reflow.md b/docs/_tutorials/reflow.md index 602452700a00..a6ab5389ed1f 100644 --- a/docs/_tutorials/reflow.md +++ b/docs/_tutorials/reflow.md @@ -74,9 +74,9 @@ With `gradient_clipping: 1.0` in the same setup, Reflow's optimizer step average ## Limitations -- Reflow requires BF16 model parameters and gradients with FP32 master weights and optimizer states. Enable `bf16.enabled`; FP16/FP32 model parameters, `torch_autocast`, low-precision master weights/states, and `fp32_optimizer_states: false` are rejected. +- Reflow uses FP16/BF16 model parameters and gradients with FP32 master weights and optimizer states. Enable `fp16.enabled` or `bf16.enabled`; FP32 model parameters, `torch_autocast`, low-precision master weights/states, and `fp32_optimizer_states: false` are rejected. - Use `engine.step()` after `deepspeed.initialize()`. Direct `ReflowCPUAdam.step()` and `ReflowCPULion.step()` calls are rejected. -- ZeRO stage 3 with `offload_optimizer.device` set to `cpu`; any other stage or device is rejected when the configuration is parsed. NVMe optimizer offload is accepted but is not covered by tests. +- Reflow requires ZeRO stage 3 with optimizer offload; unsupported stages and offload devices are rejected when the configuration is parsed. - The CPU Adam/Lion extension must be built with AVX2 or AVX-512; Reflow raises an error when it creates the optimizer on other builds. - Not supported with `super_offload`, ZenFlow, DeepCompile, the Muon optimizer, or `managed_gradient_accumulation: false`. The first four are rejected at initialization. - Muon support needs to be implemented in the future. Reflow's CPU step applies its Adam/Lion kernels to every subgroup, so Muon's orthogonalized update needs its own path through the two-phase step. diff --git a/tests/unit/v1/zero/test_reflow.py b/tests/unit/v1/zero/test_reflow.py index c5c7100eb312..9624e131b042 100644 --- a/tests/unit/v1/zero/test_reflow.py +++ b/tests/unit/v1/zero/test_reflow.py @@ -164,21 +164,13 @@ def test_rejects_muon_config(): "bf16": { "enabled": False } - }, "requires BF16 model parameters"), - ({ - "bf16": { - "enabled": False - }, - "fp16": { - "enabled": True - } - }, "requires BF16 model parameters"), + }, "requires FP16 or BF16 model parameters"), ({ "torch_autocast": { "enabled": True, "dtype": "bfloat16" } - }, "requires BF16 model parameters"), + }, "requires FP16 or BF16 model parameters"), ({ "bf16": { "enabled": True, @@ -205,6 +197,19 @@ def test_rejects_unsupported_precision(precision_config, error): DeepSpeedConfig(config) +@pytest.mark.parametrize("precision", ["fp16", "bf16"]) +@pytest.mark.parametrize("device", ["cpu", "nvme"]) +def test_accepts_half_precision_and_supported_optimizer_offload(precision, device): + # FP32 masters/states must not accidentally exclude FP16 compute or NVMe state swapping. + config = minimal_reflow_config(offload_optimizer={"device": device}) + config["bf16"] = {"enabled": precision == "bf16"} + config["fp16"] = {"enabled": precision == "fp16"} + parsed = DeepSpeedConfig(config) + assert parsed.zero_config.offload_optimizer.device == device + precision_config = parsed.float16_config if precision == "fp16" else parsed.bfloat16_config + assert precision_config.enabled + + def test_precision_restrictions_do_not_apply_without_reflow(): config = minimal_reflow_config() del config["zero_optimization"]["reflow"] @@ -415,14 +420,15 @@ def train_and_collect(model, config, batches, client_optimizer=None, on_initiali @pytest.mark.parametrize("variant", ["lion", "offload_param", "client_optimizer"]) +@pytest.mark.parametrize("precision", ["bf16", "fp16"]) @needs_gpu_accelerator class TestReflowVariantsMatchZeroOffload(DistributedTest): world_size = [1, 2] - def test_matches_zero_offload(self, variant): + def test_matches_zero_offload(self, variant, precision): skip_if_reflow_training_unsupported() hidden_dim = 16 - dtype = torch.bfloat16 + dtype = torch.float16 if precision == "fp16" else torch.bfloat16 num_steps = 4 torch.manual_seed(1234) initial_model = SimpleModel(hidden_dim=hidden_dim, nlayers=2) @@ -433,7 +439,11 @@ def run(reflow): client_optimizer = None if variant == "client_optimizer": client_optimizer = DeepSpeedCPUAdam(model.parameters(), lr=1e-3) - return train_and_collect(model, get_variant_config(reflow, variant), batches, client_optimizer) + config = get_variant_config(reflow, variant) + if precision == "fp16": + config["bf16"] = {"enabled": False} + config["fp16"] = {"enabled": True, "loss_scale": 128} + return train_and_collect(model, config, batches, client_optimizer) expected = run(reflow=False) actual = run(reflow=True) @@ -589,6 +599,7 @@ def recorded(*args, _phase=phase, _original=original): class TestReflowPrecisionValidation(DistributedTest): world_size = 1 + non_daemonic_procs = True @pytest.mark.parametrize("optimizer_type", [DeepSpeedCPUAdam, DeepSpeedCPULion]) def test_rejects_low_precision_client_states(self, optimizer_type): @@ -601,13 +612,32 @@ def test_rejects_low_precision_client_states(self, optimizer_type): with pytest.raises(ZeRORuntimeException, match="requires FP32 optimizer states"): deepspeed.initialize(model=model, optimizer=optimizer, config=config) - @pytest.mark.parametrize("dtype", [torch.float32, torch.float16]) + @pytest.mark.parametrize("precision", ["bf16", "fp16"]) + def test_initializes_half_precision_zero_init_model(self, precision): + if not deepspeed.ops.__compatible_ops__.get(CPUAdamBuilder.NAME, False): + pytest.skip("the CPU optimizer builder is not supported on this accelerator") + config = get_variant_config(reflow=True, variant="offload_param") + dtype = torch.float16 if precision == "fp16" else torch.bfloat16 + if precision == "fp16": + config["bf16"] = {"enabled": False} + config["fp16"] = {"enabled": True, "loss_scale": 128} + with deepspeed.zero.Init(config_dict_or_path=config, dtype=dtype): + model = SimpleModel(hidden_dim=16, nlayers=2) + engine, optimizer, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) + try: + assert all(param.dtype == dtype for param in engine.module.parameters()) + assert isinstance(optimizer.optimizer, ReflowCPUAdam) + assert optimizer.optimizer.fp32_optimizer_states + finally: + engine.destroy() + + @pytest.mark.parametrize("dtype", [torch.float32]) def test_rejects_zero_init_model_with_unsupported_dtype(self, dtype): - # zero.Init bypasses the engine's model cast; the config's BF16 flag alone cannot guarantee BF16 weights. + # zero.Init bypasses the engine's model cast, so its actual parameters must still be half precision. config = get_variant_config(reflow=True, variant="offload_param") with deepspeed.zero.Init(config_dict_or_path=config, dtype=dtype): model = SimpleModel(hidden_dim=16, nlayers=2) - with pytest.raises(ValueError, match="requires BF16 model parameters"): + with pytest.raises(ValueError, match="requires FP16 or BF16 model parameters"): deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) From 30354441d24c9b2d4d95d74e61e9fcab788a44c7 Mon Sep 17 00:00:00 2001 From: st-bang97 Date: Thu, 29 Oct 2026 07:20:02 +0000 Subject: [PATCH 07/19] Validate ReFlow optimizer and offload compatibility Signed-off-by: st-bang97 --- deepspeed/runtime/config.py | 3 ++ deepspeed/runtime/engine.py | 1 + deepspeed/runtime/reflow/README.md | 4 ++- deepspeed/runtime/reflow/engine.py | 9 +++++ deepspeed/runtime/zero/config.py | 2 ++ deepspeed/utils/timer.py | 5 +-- docs/_pages/config-json.md | 2 +- docs/_tutorials/reflow.md | 4 +-- tests/unit/v1/zero/test_reflow.py | 55 ++++++++++++++++++++++++++++++ 9 files changed, 78 insertions(+), 7 deletions(-) diff --git a/deepspeed/runtime/config.py b/deepspeed/runtime/config.py index fb5ceeedfe7f..8a6772ae1b04 100755 --- a/deepspeed/runtime/config.py +++ b/deepspeed/runtime/config.py @@ -712,6 +712,9 @@ def _do_error_check(self): if not (self.bfloat16_config.enabled or self.float16_config.enabled) or self.torch_autocast_enabled: raise ValueError("Reflow requires FP16 or BF16 model parameters; enable 'fp16.enabled' " "or 'bf16.enabled'. FP32 model parameters and torch_autocast are not supported.") + model_dtype = torch.bfloat16 if self.bfloat16_config.enabled else torch.float16 + if self.grad_accum_dtype is not None and DtypeEnum(self.grad_accum_dtype).value != model_dtype: + raise ValueError("Reflow requires data_types.grad_accum_dtype to match the FP16 or BF16 model dtype.") if (self.float16_config.fp16_master_weights_and_grads or self.bfloat16_config.bf16_master_weights_and_grads or self.bfloat16_config.bf16_optimizer_states): raise ValueError("Reflow requires FP32 master weights and optimizer states; " diff --git a/deepspeed/runtime/engine.py b/deepspeed/runtime/engine.py index 3f8310fffced..99c809c6ed1d 100644 --- a/deepspeed/runtime/engine.py +++ b/deepspeed/runtime/engine.py @@ -2346,6 +2346,7 @@ def _configure_optimizer(self, client_optimizer, model_parameters): msg = f'You are using ZeRO-Offload with a client provided optimizer ({type(basic_optimizer)}) which in most cases will yield poor performance. Please either use deepspeed.ops.adam.DeepSpeedCPUAdam or set an optimizer in your ds-config (https://www.deepspeed.ai/docs/config-json/#optimizer-parameters). If you really want to use a custom optimizer w. ZeRO-Offload and understand the performance impacts you can also set <"zero_force_ds_cpu_optimizer": false> in your configuration file.' raise ZeRORuntimeException(msg) + reflow_engine.reject_optimizer_without_reflow(self, basic_optimizer) basic_optimizer.param_groups[:] = [pg for pg in basic_optimizer.param_groups if len(pg["params"]) != 0] log_dist("Removing param_group that has no 'params' in the basic Optimizer", ranks=[0]) # A client optimizer has to become the matching Reflow CPU optimizer; the config-built one already is one. diff --git a/deepspeed/runtime/reflow/README.md b/deepspeed/runtime/reflow/README.md index 2b311d02e5bc..8c692d2d487b 100644 --- a/deepspeed/runtime/reflow/README.md +++ b/deepspeed/runtime/reflow/README.md @@ -130,7 +130,9 @@ to the original optimizer cannot follow the remapping and is rejected. } ``` -Reflow keeps the optimizer state in CPU RAM (`offload_optimizer.device: "cpu"`). It is mutually +Reflow keeps the optimizer state in CPU RAM (`offload_optimizer.device: "cpu"`). Partial optimizer +offload (`offload_optimizer.ratio < 1.0`) is not supported. If `data_types.grad_accum_dtype` is set, +it must match the FP16 or BF16 model dtype. It is mutually exclusive with `super_offload` and `zenflow` (the config validator raises a clear error otherwise; see `config.reflow_compat_check`), and with DeepCompile, whose ZeRO-3 backward reduces gradients without `partition_grads`, where Reflow launches its workers (rejected in `DeepSpeedConfig`). The diff --git a/deepspeed/runtime/reflow/engine.py b/deepspeed/runtime/reflow/engine.py index 23366b4de10f..b80f3341ac8d 100644 --- a/deepspeed/runtime/reflow/engine.py +++ b/deepspeed/runtime/reflow/engine.py @@ -26,6 +26,15 @@ def reflow_enabled(engine: "DeepSpeedEngine") -> bool: return not getattr(engine, "zenflow", False) +def reject_optimizer_without_reflow(engine: "DeepSpeedEngine", optimizer): + if reflow_enabled(engine): + return + from deepspeed.runtime.reflow.reflow_cpu_adam import ReflowCPUAdam + from deepspeed.runtime.reflow.reflow_cpu_lion import ReflowCPULion + if isinstance(optimizer, (ReflowCPUAdam, ReflowCPULion)): + raise ZeRORuntimeException("ReflowCPUAdam and ReflowCPULion require zero_optimization.reflow.") + + def reflow_num_threads(engine: "DeepSpeedEngine"): return engine._config.zero_config.reflow.num_threads diff --git a/deepspeed/runtime/zero/config.py b/deepspeed/runtime/zero/config.py index 00ed2a741195..c99a22d77d64 100644 --- a/deepspeed/runtime/zero/config.py +++ b/deepspeed/runtime/zero/config.py @@ -429,6 +429,8 @@ def reflow_compat_check(self): # Reflow runs the optimizer on CPU. device='cpu' keeps its state in CPU memory; device='nvme' # additionally swaps that state per subgroup around the CPU step. raise ValueError("Reflow requires optimizer offload with device 'cpu' or 'nvme'.") + if offload_config.ratio != 1.0: + raise ValueError("Reflow does not support partial optimizer offload; offload_optimizer.ratio must be 1.0.") if self.zenflow is not None: raise ValueError("Reflow is not compatible with ZenFlow; enable only one of them.") if offload_config.super_offload: diff --git a/deepspeed/utils/timer.py b/deepspeed/utils/timer.py index 221b8702b34d..0fe5e5514a05 100644 --- a/deepspeed/utils/timer.py +++ b/deepspeed/utils/timer.py @@ -231,8 +231,9 @@ def __init__(self, if self.logging is None: self.logging = logger.info self.initialized = False - # Reflow auto-enables this: with CPU-offload side streams, sync only the current - # stream so the timer does not serialize them. Default preserves the full device sync. + # Reflow avoids a device-wide timer sync: waiting for its H2D side stream would delay + # the next GPU compute launch and reduce overlap with the CPU optimizer workers. + # Other runs keep the original full-device synchronization. self.sync_current_stream = sync_current_stream if self.monitor_memory and importlib.util.find_spec("psutil") is None: diff --git a/docs/_pages/config-json.md b/docs/_pages/config-json.md index 825a19097b3b..ce3a8f23fa49 100644 --- a/docs/_pages/config-json.md +++ b/docs/_pages/config-json.md @@ -706,7 +706,7 @@ Note that if the value of "device" is not specified or not supported, an asserti ### Reflow [Reflow](/tutorials/reflow/) is an asynchronous CPU-offload optimizer for ZeRO stage 3. The CPU optimizer runs per gradient bucket during backward, gradients move to CPU in BF16, and the FP32 master weights and optimizer state are committed in the background while the next forward runs. -The `reflow` block enables it, so an empty block is enough to run with the defaults. Reflow requires `"stage": 3`, `"fp16": {"enabled": true}` or `"bf16": {"enabled": true}`, `offload_optimizer` on `cpu` (or `nvme`), and CPU Adam/Lion kernels built with AVX2 or AVX-512. Model parameters and offloaded gradients must be FP16/BF16; master weights and optimizer states must be FP32. FP32 model parameters, `torch_autocast`, low-precision master weights/states, and `fp32_optimizer_states: false` are rejected. It uses `ReflowCPUAdam`/`ReflowCPULion`; a client `DeepSpeedCPUAdam`/`DeepSpeedCPULion` is remapped automatically. Adam/AdamW support `maximize`, including per-group settings preserved when remapping a PyTorch optimizer; the default is `false`. Call `engine.step()`; direct `ReflowCPUAdam.step()` and `ReflowCPULion.step()` calls are rejected. It is not compatible with `super_offload`, ZenFlow, DeepCompile, the Muon optimizer (support to be implemented), or `managed_gradient_accumulation: false`. +The `reflow` block enables it, so an empty block is enough to run with the defaults. Reflow requires `"stage": 3`, `"fp16": {"enabled": true}` or `"bf16": {"enabled": true}`, `offload_optimizer` on `cpu` (or `nvme`) with `"ratio": 1.0`, and CPU Adam/Lion kernels built with AVX2 or AVX-512. Model parameters and offloaded gradients must be FP16/BF16; master weights and optimizer states must be FP32. If `data_types.grad_accum_dtype` is set, it must match the model dtype. FP32 model parameters, `torch_autocast`, low-precision master weights/states, and `fp32_optimizer_states: false` are rejected. It uses `ReflowCPUAdam`/`ReflowCPULion`; a client `DeepSpeedCPUAdam`/`DeepSpeedCPULion` is remapped automatically. These Reflow optimizers require the `reflow` block even when passed directly. Adam/AdamW support `maximize`, including per-group settings preserved when remapping a PyTorch optimizer; the default is `false`. Call `engine.step()`; direct `ReflowCPUAdam.step()` and `ReflowCPULion.step()` calls are rejected. It is not compatible with partial optimizer offload, `super_offload`, ZenFlow, DeepCompile, the Muon optimizer (support to be implemented), or `managed_gradient_accumulation: false`. ```json "reflow": { "num_threads": null, diff --git a/docs/_tutorials/reflow.md b/docs/_tutorials/reflow.md index a6ab5389ed1f..7a5622067e06 100644 --- a/docs/_tutorials/reflow.md +++ b/docs/_tutorials/reflow.md @@ -45,7 +45,7 @@ Reflow needs no model code changes. Enable it in the DeepSpeed configuration: } ``` -DeepSpeed builds `ReflowCPUAdam` (or `ReflowCPULion` for Lion) for this configuration. A client `DeepSpeedCPUAdam`/`DeepSpeedCPULion` or PyTorch `Adam`/`AdamW` passed to `deepspeed.initialize` is remapped automatically. If you pass a client optimizer and an LR scheduler, pass a scheduler factory that accepts the remapped optimizer, or configure the scheduler in the DeepSpeed config. A scheduler already bound to the original optimizer is rejected. An empty `"reflow": {}` runs with the defaults; see the [configuration reference](/docs/config-json/#reflow) for every option. +DeepSpeed builds `ReflowCPUAdam` (or `ReflowCPULion` for Lion) for this configuration. A client `DeepSpeedCPUAdam`/`DeepSpeedCPULion` or PyTorch `Adam`/`AdamW` passed to `deepspeed.initialize` is remapped automatically. PyTorch optimizers require `"zero_force_ds_cpu_optimizer": false`. If you pass a client optimizer and an LR scheduler, pass a scheduler factory that accepts the remapped optimizer, or configure the scheduler in the DeepSpeed config. A scheduler already bound to the original optimizer is rejected. Passing a `ReflowCPUAdam` or `ReflowCPULion` without the `reflow` block is rejected. An empty `"reflow": {}` runs with the defaults; see the [configuration reference](/docs/config-json/#reflow) for every option. Partial optimizer offload (`offload_optimizer.ratio` below `1.0`) and a `data_types.grad_accum_dtype` different from the model dtype are not supported. Launch with `--bind_cores_to_rank` so each rank runs on the CPU cores local to its GPU: @@ -53,8 +53,6 @@ Launch with `--bind_cores_to_rank` so each rank runs on the CPU cores local to i deepspeed --bind_cores_to_rank train.py --deepspeed_config ds_config.json ``` -With Intel MPI, core selection and NUMA permission checks run on each target host at rank startup. If a container denies NUMA memory binding, the launcher retains CPU binding when permitted; if CPU binding is also denied, it launches without `numactl` binding. Invalid CPU or NUMA selections still fail. These checks add no work to training steps, but losing memory locality can affect throughput on hosts with multiple NUMA nodes. - Reflow always pins optimizer workers to NUMA-local cores and reserves `main_thread_cores` from those workers. `enable_cpu_affinity` additionally restricts the main process to its NUMA-local core slice. The remaining cores are split into workers of `bucketwise_cores_per_worker` cores. While the state commit overlaps the forward it uses only `state_update_cores` cores: every busy core lowers the CPU's turbo frequency, which would slow the launch-bound forward. ## Gradient clipping diff --git a/tests/unit/v1/zero/test_reflow.py b/tests/unit/v1/zero/test_reflow.py index 9624e131b042..e881cdcd4970 100644 --- a/tests/unit/v1/zero/test_reflow.py +++ b/tests/unit/v1/zero/test_reflow.py @@ -144,6 +144,16 @@ def test_requires_stage3_and_cpu_optimizer_offload(): DeepSpeedConfig(minimal_reflow_config(offload_optimizer=None)) +@pytest.mark.parametrize("ratio", [0.0, 0.5]) +def test_rejects_partial_optimizer_offload(ratio): + config = minimal_reflow_config(offload_optimizer={"device": "cpu", "ratio": ratio}) + with pytest.raises(ValueError, match="offload_optimizer.ratio must be 1.0"): + DeepSpeedConfig(config) + + del config["zero_optimization"]["reflow"] + assert DeepSpeedConfig(config).zero_config.offload_optimizer.ratio == ratio + + def test_rejects_deepcompile(): config = minimal_reflow_config() config["compile"] = {"deepcompile": True} @@ -197,6 +207,23 @@ def test_rejects_unsupported_precision(precision_config, error): DeepSpeedConfig(config) +@pytest.mark.parametrize("model_dtype, grad_dtype", [("bf16", "fp32"), ("bf16", "fp16"), ("fp16", "fp32")]) +def test_rejects_mismatched_gradient_accumulation_dtype(model_dtype, grad_dtype): + config = minimal_reflow_config() + config["bf16"]["enabled"] = model_dtype == "bf16" + config["fp16"] = {"enabled": model_dtype == "fp16"} + config["data_types"] = {"grad_accum_dtype": grad_dtype} + with pytest.raises(ValueError, match="data_types.grad_accum_dtype to match"): + DeepSpeedConfig(config) + + config["data_types"]["grad_accum_dtype"] = model_dtype + assert DeepSpeedConfig(config).grad_accum_dtype == model_dtype + + del config["zero_optimization"]["reflow"] + config["data_types"]["grad_accum_dtype"] = grad_dtype + assert DeepSpeedConfig(config).grad_accum_dtype == grad_dtype + + @pytest.mark.parametrize("precision", ["fp16", "bf16"]) @pytest.mark.parametrize("device", ["cpu", "nvme"]) def test_accepts_half_precision_and_supported_optimizer_offload(precision, device): @@ -597,6 +624,34 @@ def recorded(*args, _phase=phase, _original=original): assert torch.equal(got, want) +class TestReflowOptimizerRequiresOptIn(DistributedTest): + world_size = 1 + non_daemonic_procs = True + + def test_regular_optimizer_without_reflow_config(self): + model = SimpleModel(hidden_dim=16, nlayers=2) + optimizer = torch.optim.Adam(model.parameters()) + config = {"train_micro_batch_size_per_gpu": 1, "zero_optimization": {"stage": 0}} + engine, _, _, _ = deepspeed.initialize(model=model, optimizer=optimizer, config=config) + try: + assert engine.basic_optimizer is optimizer + finally: + engine.destroy() + + @pytest.mark.parametrize("optimizer_type, builder", [(ReflowCPUAdam, CPUAdamBuilder), + (ReflowCPULion, CPULionBuilder)]) + def test_rejects_reflow_optimizer_without_reflow_config(self, optimizer_type, builder): + if not deepspeed.ops.__compatible_ops__.get(builder.NAME, False): + pytest.skip("the CPU optimizer builder is not supported on this accelerator") + if builder().simd_width() not in ("-D__AVX512__", "-D__AVX256__"): + pytest.skip("the Reflow CPU optimizer requires AVX2 or AVX-512") + model = SimpleModel(hidden_dim=16, nlayers=2) + optimizer = optimizer_type(model.parameters()) + config = {"train_micro_batch_size_per_gpu": 1, "zero_optimization": {"stage": 0}} + with pytest.raises(ZeRORuntimeException, match="require zero_optimization.reflow"): + deepspeed.initialize(model=model, optimizer=optimizer, config=config) + + class TestReflowPrecisionValidation(DistributedTest): world_size = 1 non_daemonic_procs = True From c4b6660cb5faa58884da39033ab1632c9267602b Mon Sep 17 00:00:00 2001 From: st-bang97 Date: Tue, 10 Nov 2026 05:18:29 +0000 Subject: [PATCH 08/19] Fix ReFlow gradient handling and CPU affinity Signed-off-by: st-bang97 --- csrc/includes/reflow_cpu_lion.h | 12 +- deepspeed/runtime/reflow/README.md | 28 ++- deepspeed/runtime/reflow/reflow_config.py | 10 +- deepspeed/runtime/reflow/reflow_stage3.py | 96 +++++---- deepspeed/runtime/reflow/reflow_utils.py | 93 ++++++++- docs/_pages/config-json.md | 16 +- docs/_tutorials/reflow.md | 5 +- .../unit/v1/ops/test_reflow_cpu_optimizers.py | 2 +- tests/unit/v1/zero/test_reflow.py | 188 +++++++++++++++++- 9 files changed, 356 insertions(+), 94 deletions(-) diff --git a/csrc/includes/reflow_cpu_lion.h b/csrc/includes/reflow_cpu_lion.h index 6d6f2a4db518..c3b5d8482bcf 100644 --- a/csrc/includes/reflow_cpu_lion.h +++ b/csrc/includes/reflow_cpu_lion.h @@ -146,8 +146,8 @@ void Reflow_Lion_Optimizer::Step_AVX_HalfGrad(size_t* rounded_size, { size_t new_rounded_size = 0; - AVX_Data neg1_4; - neg1_4.data = SIMD_SET(-1.0f); + AVX_Data sign_mask_4; + sign_mask_4.data = SIMD_SET(-0.0f); AVX_Data betta1_4; betta1_4.data = SIMD_SET(_betta1); @@ -210,7 +210,7 @@ void Reflow_Lion_Optimizer::Step_AVX_HalfGrad(size_t* rounded_size, AVX_Data tmp_4[span]; simd_mul(tmp_4, momentum_4, betta1_4); simd_fma(tmp_4, grad_4, betta1_minus1_4, tmp_4); - simd_and(tmp_4, tmp_4, neg1_4); + simd_and(tmp_4, tmp_4, sign_mask_4); simd_xor(tmp_4, tmp_4, step_size_4); if (use_weight_decay) { simd_fma(param_4, param_4, after_decay_4, tmp_4); @@ -245,8 +245,8 @@ void Reflow_Lion_Optimizer::Step_AVX_FP16_HalfGrad(size_t* rounded_size, { size_t new_rounded_size = 0; - AVX_Data neg1_4; - neg1_4.data = SIMD_SET(-1.0f); + AVX_Data sign_mask_4; + sign_mask_4.data = SIMD_SET(-0.0f); AVX_Data betta1_4; betta1_4.data = SIMD_SET(_betta1); @@ -307,7 +307,7 @@ void Reflow_Lion_Optimizer::Step_AVX_FP16_HalfGrad(size_t* rounded_size, AVX_Data tmp_4[span]; simd_mul(tmp_4, momentum_4, betta1_4); simd_fma(tmp_4, grad_4, betta1_minus1_4, tmp_4); - simd_and(tmp_4, tmp_4, neg1_4); + simd_and(tmp_4, tmp_4, sign_mask_4); simd_xor(tmp_4, tmp_4, step_size_4); if (use_weight_decay) { simd_fma(param_4, param_4, after_decay_4, tmp_4); diff --git a/deepspeed/runtime/reflow/README.md b/deepspeed/runtime/reflow/README.md index 8c692d2d487b..fc3dafcfad29 100644 --- a/deepspeed/runtime/reflow/README.md +++ b/deepspeed/runtime/reflow/README.md @@ -120,8 +120,8 @@ to the original optimizer cannot follow the remapping and is rejected. "main_thread_cores": 2, // cores reserved for the forward/backward (main) thread "bucketwise_cores_per_worker": 7, // cores per bucketwise CPU-Adam worker; worker count = // (rank worker cores) / this value - "state_update_cores": 2 // cores for the background optimizer-state commit while it - // overlaps the next forward (default 2) + "state_update_cores": 2 // optional forward limit for the background state commit + // (default: all worker CPUs) // "num_threads": // CPU-Adam threads (default: all available cores) } // optional: also offload PARAMETERS to CPU (orthogonal to Reflow; frees the per-rank param @@ -152,17 +152,19 @@ and give the rest to the workers (e.g. on a 9-core-per-rank box, `main_thread_co `bucketwise_cores_per_worker: 7`). Launch with `deepspeed --bind_cores_to_rank` so each rank is pinned to the cores physically attached to its GPU. -By default, counts refer to logical CPUs in the rank's affinity mask. `main_thread_cores` excludes -that many CPU IDs from workers; SMT siblings remain available and the main thread is not pinned -to the reservation. The following options allow other placements without machine-specific CPU IDs: +By default, counts refer to logical CPUs in the rank's affinity mask. The initializing thread is pinned +to `main_thread_cores` CPU IDs and workers use the remaining IDs; SMT siblings may still be shared. +Local ranks with the same CPU affinity share it disjointly. Partially overlapping rank affinities are +rejected when main-thread pinning is enabled. The following options allow other placements: | Option | Default | Behavior | |---|---|---| | `main_thread_core_type` | `"logical"` | `"physical"` counts physical cores and reserves all their available SMT siblings. | -| `pin_main_thread` | `false` | Pins the initializing thread to the reserved main CPUs; `engine.destroy()` restores its original affinity. | +| `pin_main_thread` | `true` | Pins the initializing thread to the reserved main CPUs; `engine.destroy()` restores its original affinity. | | `worker_core_type` | `"logical"` | `"physical"` uses one logical CPU per remaining physical core. | | `bucketwise_cores_per_worker` | `8` | Maximum logical CPUs per bucketwise worker; the last mask within a NUMA node may be smaller. | -| `bucketwise_worker_affinity` | `"task"` | `"task"` assigns CPU masks round-robin; `"thread"` fixes each pool thread to a mask at startup, reducing migrations and preserving its OpenMP team placement. | +| `bucketwise_worker_affinity` | `"thread"` | `"task"` assigns CPU masks round-robin; `"thread"` fixes each pool thread to a mask at startup, reducing migrations and preserving its OpenMP team placement. | +| `state_update_cores` | `null` | Caps the worker CPU IDs used by the state commit during forward; `null` uses all worker CPUs. | | `state_update_backward_cores` | `null` | Caps the number of worker CPU IDs used by the state commit during backward; `null` uses all worker CPUs. `state_update_cores` still controls its forward mask. | For example, this reserves one physical main core, uses its SMT siblings for the main thread, @@ -182,8 +184,7 @@ and keeps optimizer pool threads on fixed CPU masks: Physical placement requires readable Linux CPU topology. Automatic rank assignment keeps SMT siblings together; an existing taskset/launcher affinity remains authoritative. Main reservations -are capped to leave a worker core, and physical main reservation raises an error if a rank has fewer -than two physical cores. Counts for worker masks and state commits remain logical CPU counts, even +must leave at least one worker CPU; initialization raises an error if the rank's CPU set is too small. Counts for worker masks and state commits remain logical CPU counts, even when main reservations count physical cores. Tune these values for the workload and CPU topology. Reflow applies each worker's CPU mask to its retained OpenMP helpers, changing their affinity only @@ -242,12 +243,9 @@ accumulation, params on GPU, NVMe offload) logs a warning and falls back to the - **Single-GPU is the stress case.** With one GPU the optimizer is the *full* (unpartitioned) model and must hide inside a single backward, so the bucketwise CPU-Adam workers must run truly in parallel across the NUMA-local cores (see the mutex note under Correctness). -- **The state commit narrows its cores while it overlaps the forward.** The previous step's - optimizer-state commit overlaps the forward, which is launch-bound on the main thread. Every busy - core lowers the turbo frequency the CPU allows, so a commit spread over all worker cores slowed the - forward (OPT-350m: ~25%, main core ~3.6 GHz vs ~4.2 GHz). The commit therefore runs in slices on - `state_update_cores` cores (default 2) until the next backward starts, then on every worker core, - so a large model's commit still finishes before the next `step()` waits on it. +- **The state commit can overlap the forward.** By default it can use all worker CPUs in both forward + and backward. Set `state_update_cores` or `state_update_backward_cores` to limit its affinity during + either phase; changes take effect between commit slices. - **Gradient clipping re-runs the update inside `step()`.** The bucketwise workers apply the update during backward, before the global grad norm is known. When a step needs clipping (`gradient_clipping > 0` and the grad norm exceeds it), the in-flight work is cancelled and every diff --git a/deepspeed/runtime/reflow/reflow_config.py b/deepspeed/runtime/reflow/reflow_config.py index bce76dbae5c1..394530bdb423 100644 --- a/deepspeed/runtime/reflow/reflow_config.py +++ b/deepspeed/runtime/reflow/reflow_config.py @@ -25,23 +25,21 @@ class ReflowConfig(DeepSpeedConfigModel): main_thread_core_type: Literal["logical", "physical"] = "logical" """Count main-thread reservations as logical CPUs or physical cores including their SMT siblings.""" - pin_main_thread: bool = False + pin_main_thread: bool = True """Pin the initializing thread to the reserved main CPUs and restore its affinity on destroy.""" worker_core_type: Literal["logical", "physical"] = "logical" """Use all worker CPU IDs, or one logical CPU per worker physical core.""" - bucketwise_worker_affinity: Literal["task", "thread"] = "task" + bucketwise_worker_affinity: Literal["task", "thread"] = "thread" """Choose a CPU mask for each task, or keep each pool thread on its initial mask.""" bucketwise_cores_per_worker: int = Field(8, ge=1) """Cores per bucketwise optimizer worker. The worker count follows from the cores available to the rank divided by this value.""" - state_update_cores: int = Field(2, ge=1) - """Worker cores the background optimizer-state commit may use while it overlaps the next - forward. Every busy core lowers the turbo frequency the CPU allows, which slows the - launch-bound forward; once backward starts the commit uses every worker core.""" + state_update_cores: Optional[int] = Field(None, ge=1) + """Limit worker CPUs used by the background state commit during forward; ``None`` uses all worker CPUs.""" state_update_backward_cores: Optional[int] = Field(None, ge=1) """Limit the state commit's backward CPU mask; ``None`` uses all worker CPUs.""" diff --git a/deepspeed/runtime/reflow/reflow_stage3.py b/deepspeed/runtime/reflow/reflow_stage3.py index 2ee0aecbc016..6fab28aec8ad 100644 --- a/deepspeed/runtime/reflow/reflow_stage3.py +++ b/deepspeed/runtime/reflow/reflow_stage3.py @@ -13,6 +13,7 @@ import torch import deepspeed.comm as dist +from deepspeed.comm import pg_utils from deepspeed.accelerator import get_accelerator from deepspeed.runtime.reflow.reflow_cpu_adam import ReflowCPUAdam from deepspeed.runtime.reflow import reflow_utils @@ -20,7 +21,8 @@ from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum, OffloadStateTypeEnum from deepspeed.runtime.zero.partition_parameters import Parameter, Tensor from deepspeed.runtime.zero.stage3 import DeepSpeedZeroOptimizer_Stage3, INIT_OPTIMIZER_TIMER -from deepspeed.runtime.utils import has_inf_or_nan, is_model_parallel_parameter, mask_nan_or_inf_with_val_inplace +from deepspeed.runtime.utils import (combine_grad_norm_groups, has_inf_or_nan, is_invalid_grad_norm, + is_model_parallel_parameter, mask_nan_or_inf_with_val_inplace) from deepspeed.utils import logger from deepspeed.utils.nvtx import instrument_w_nvtx @@ -131,15 +133,17 @@ def _setup_async_state_executor(self): # and per-NUMA-node optimizer-worker groups (so workers never straddle a NUMA boundary). total_cpus, available_cores, node_worker_groups, main_cores, worker_cores = \ reflow_utils.plan_cpu_core_layout(main_thread_cores, self._reflow_config.main_thread_core_type, - self._reflow_config.worker_core_type) + self._reflow_config.worker_core_type, + self._reflow_config.pin_main_thread) self._worker_node_groups = node_worker_groups self._worker_cpu_affinity_mask = set(worker_cores) - # While the state commit overlaps the next forward it stays on a few worker cores, away from the - # main-thread cores at the front of the list: every busy core lowers the turbo frequency the CPU - # allows, which slows the launch-bound forward. See _state_commit_cpu_affinity_mask. - state_update_core_count = min(max(1, int(self.state_update_cores)), len(worker_cores)) - self._state_update_cpu_affinity_mask = set(worker_cores[-state_update_core_count:]) if worker_cores else None + state_update_core_count = self.state_update_cores + if state_update_core_count is None: + state_update_cores = worker_cores + else: + state_update_cores = worker_cores[-state_update_core_count:] + self._state_update_cpu_affinity_mask = set(state_update_cores) if state_update_cores else None backward_count = self._reflow_config.state_update_backward_cores backward_cores = worker_cores[-backward_count:] if backward_count is not None else worker_cores self._state_backward_cpu_affinity_mask = set(backward_cores) @@ -152,8 +156,6 @@ def _setup_async_state_executor(self): if enable_cpu_affinity and available_cores: try: - # Keep the main process on the whole NUMA-local slice, not only main_thread_cores: the ZeRO-3 forward - # is bound by kernel launches from this thread. The workers still pin themselves to worker_cores. psutil.Process().cpu_affinity(available_cores) if dist.get_rank() == 0: logger.info(f"CPU affinity: main process on {len(available_cores)} NUMA-local cores, " @@ -245,6 +247,7 @@ def wrapped_fn(*a, **kw): self._bucketwise_update_submit = _submit_bucketwise_task self._bucketwise_update_futures = [] self._bucketwise_inflight_futures = [] + # Backward and step own this registry; executor workers never access it. self._bucketwise_accumulation_futures = {} # Use the default (lowest) stream priority so H2D weight copies never preempt compute. CUDA priorities # are inverted: a negative priority would outrank the compute stream. @@ -590,7 +593,6 @@ def partition_grads(self, params_to_release: List[Parameter], grad_partitions: L stream_needs_sync = copy_grad_stream != current_stream is_sync_device = get_accelerator().is_synchronized_device() accumulate_submit = getattr(self, "_bucketwise_update_submit", None) - accum_futures_dict = self._bucketwise_accumulation_futures for param, grad_partition in zip(params_to_release, grad_partitions): copy_event = None @@ -622,6 +624,10 @@ def partition_grads(self, params_to_release: List[Parameter], grad_partitions: L grad_numel = grad_buffer.numel() + if micro_step_id > 0: + # Both slices must remain unchanged until the previous worker consumes them. + self._wait_for_accum_gradient(param_id) + if micro_step_id == 0: # don't accumulate, first micro step if self._single_grad_buffer: # Slot 0 is also what the previous step's state commit reads, so wait for that commit before @@ -687,8 +693,7 @@ def _accumulate_worker(_copy_event=copy_event, _dst_slice=dst_slice, _src_slice= ReflowCPUAdam.bf16_accumulate(_dst_slice.view(-1), _src_slice.view(-1)) future = accumulate_submit(_accumulate_worker) - if accum_futures_dict is not None: - accum_futures_dict.setdefault(sub_group_id, []).append(future) + self._bucketwise_accumulation_futures[param_id] = future grad_buffer = dst_slice else: copy_event.synchronize() @@ -848,23 +853,21 @@ def _wait_for_pending_state_updates(self, sub_group_id=None): finally: self._last_state_update_future = None - def _wait_for_accum_gradient(self, sub_group_id=None): - """Wait for pending gradient-accumulation workers (one subgroup, or all).""" - if sub_group_id is not None: - for f in self._bucketwise_accumulation_futures.get(sub_group_id, []): - try: - f.result() - except Exception as e: - self._record_bucketwise_worker_error(e) - self._bucketwise_accumulation_futures[sub_group_id] = [] - else: - for _sg_id, futures in list(self._bucketwise_accumulation_futures.items()): - for f in futures: - try: - f.result() - except Exception as e: - self._record_bucketwise_worker_error(e) + def _wait_for_accum_gradient(self, param_id=None): + """Wait until the requested gradient buffers are no longer used by accumulation workers.""" + if param_id is None: + futures = list(self._bucketwise_accumulation_futures.values()) self._bucketwise_accumulation_futures.clear() + else: + future = self._bucketwise_accumulation_futures.pop(param_id, None) + if future is None: + return + futures = (future, ) + for future in futures: + try: + future.result() + except Exception as e: + self._record_bucketwise_worker_error(e) def _get_cpu_grad_buffer(self, sub_group_id, pending=False): if sub_group_id >= len(self._cpu_grad_double_buffers): @@ -959,9 +962,7 @@ def _bucketwise_chunk_update_worker(self, work_item): if cancel_version != getattr(self, "_bucketwise_cancel_version", 0): return None - # Ensure all gradient accumulations for this subgroup completed. - self._wait_for_accum_gradient(sub_group_id) - + # Boundary ranges are enqueued after their accumulation completes; step() drains the rest before reruns. # Make sure the previous state update for this subgroup finished. self._wait_for_pending_state_updates(sub_group_id=sub_group_id) @@ -1396,8 +1397,6 @@ def backward_prologue(self): super().backward_prologue() def _state_commit_cpu_affinity_mask(self): - # A few busy cores keep the forward's core at a high turbo frequency; after the forward the commit gets every - # worker core so a large model's commit still finishes before the next step() waits on it. if self._state_commit_overlaps_forward: return self._state_update_cpu_affinity_mask return self._state_backward_cpu_affinity_mask @@ -1428,11 +1427,19 @@ def _get_norm_groups(self): if not self.offload_optimizer: return super()._get_norm_groups() + partition_groups = [self._get_sub_group_process_group(i) for i in range(len(self.fp16_groups))] + if self.model_parallel_group is None: + counts_every_rank = [False] * len(self.fp16_groups) + else: + counts_every_rank = [ + self._grad_norm_counts_every_rank(group, process_group) + for group, process_group in zip(self.fp16_groups, partition_groups) + ] local_sq = [] - for group in self.fp16_groups: + for group, count_every_rank in zip(self.fp16_groups, counts_every_rank): group_sq = 0.0 for p in group: - if is_model_parallel_parameter(p) or (self.model_parallel_rank == 0): + if count_every_rank or is_model_parallel_parameter(p) or (self.model_parallel_rank == 0): param_id = self.get_param_id(p) if param_id in self.norm_for_param_grads: group_sq += self.norm_for_param_grads[param_id]**2 @@ -1442,10 +1449,12 @@ def _get_norm_groups(self): # Match complete_grad_norm_calculation_for_cpu_offload: each subgroup sums over its own partition group, # then the model-parallel group, then (AutoEP expert subgroups only) the expert-parallel group. Subgroups # sharing a group are reduced together, so the usual single-group case stays one all-reduce. - partition_groups = [self._get_sub_group_process_group(i) for i in range(len(self.fp16_groups))] self._all_reduce_norm_entries_by_group(total_norms, partition_groups) - self._model_parallel_all_reduce(tensor=total_norms, op=dist.ReduceOp.SUM) + if pg_utils.is_parallel(self.model_parallel_group): + model_groups = [self.model_parallel_group if not count else None for count in counts_every_rank] + self._all_reduce_norm_entries_by_group(total_norms, model_groups) expert_groups = [self._autoep_expert_parallel_group(group) for group in self.fp16_groups] + expert_groups = [group if pg_utils.is_parallel(group) else None for group in expert_groups] self._all_reduce_norm_entries_by_group(total_norms, expert_groups) norm_groups = [] @@ -1481,7 +1490,15 @@ def step(self, closure=None): # the overflow check advances the loss scale / optimizer state. self._check_bucketwise_worker_error() - if self._overflow_check_and_loss_scale_update(): + self._overflow_check_and_loss_scale_update(update_scale=False) + scaled_global_grad_norm = None + if not self.overflow: + norm_groups = self._get_norm_groups() + scaled_global_grad_norm = combine_grad_norm_groups(norm_groups) + if is_invalid_grad_norm(scaled_global_grad_norm): + self.overflow = True + + if self._loss_scale_update_and_overflow_cleanup(): if self.swap_optimizer: self.optimizer_swapper.log_timers() # Discard the step like the base optimizer. The workers already wrote new FP16/BF16 params to the GPU @@ -1493,9 +1510,6 @@ def step(self, closure=None): self._restore_fp16_params_from_master(sub_group_id) return - norm_groups = self._get_norm_groups() - scaled_global_grad_norm = torch.linalg.vector_norm(torch.stack(norm_groups)) - self._global_grad_norm = scaled_global_grad_norm / self.loss_scale combined_scale = self.loss_scale diff --git a/deepspeed/runtime/reflow/reflow_utils.py b/deepspeed/runtime/reflow/reflow_utils.py index f15513598f33..0bc8f172f755 100644 --- a/deepspeed/runtime/reflow/reflow_utils.py +++ b/deepspeed/runtime/reflow/reflow_utils.py @@ -10,6 +10,7 @@ """ import os +import socket import psutil @@ -265,9 +266,10 @@ def heuristic_rank_cores(numa_nodes, local_rank, local_world_size, physical=Fals return partition_physical_cpus(node, ranks_per_node, pos) if ranks_per_node <= len(node): # Common case: enough cores to give each co-located rank a contiguous chunk. - chunk = max(1, len(node) // ranks_per_node) - start = pos * chunk - return node[start:start + chunk] if start < len(node) else node + base, remainder = divmod(len(node), ranks_per_node) + start = pos * base + min(pos, remainder) + count = base + (pos < remainder) + return node[start:start + count] # Extreme oversubscription (more co-located ranks than cores): split the node's cores into # disjoint slices via a base size + remainder so co-located ranks never share a core. Ranks # past the core count fall back to a degenerate (<1 core/rank) split, so warn once on rank 0. @@ -281,11 +283,80 @@ def heuristic_rank_cores(numa_nodes, local_rank, local_world_size, physical=Fals return node[start:start + size] -def plan_cpu_core_layout(main_thread_cores, main_thread_core_type="logical", worker_core_type="logical"): +def _isolate_rank_cpu_sets(rank_cores, main_thread_cores, main_thread_core_type, worker_core_type, pin_main_thread): + """Split shared rank CPU sets and reject ambiguous overlaps before pinning any thread.""" + physical = main_thread_core_type == "physical" or worker_core_type == "physical" + units = physical_cpu_groups(rank_cores) if physical else [[cpu] for cpu in rank_cores] + local = { + "host": socket.gethostname(), + "cpus": sorted(rank_cores), + "units": units, + "pin": pin_main_thread, + "main_count": main_thread_cores, + "main_type": main_thread_core_type, + } + if dist.is_initialized() and dist.get_world_size() > 1: + layouts = [None] * dist.get_world_size() + dist.all_gather_object(layouts, local) + rank = dist.get_rank() + else: + layouts = [local] + rank = 0 + + cpu_sets = [set(layout["cpus"]) for layout in layouts] + for index, layout in enumerate(layouts): + for other in range(index + 1, len(layouts)): + peer = layouts[other] + if layout["host"] != peer["host"] or not (layout["pin"] or peer["pin"]): + continue + if cpu_sets[index] & cpu_sets[other] and cpu_sets[index] != cpu_sets[other]: + raise ValueError("Reflow cannot reserve exclusive main CPUs for partially overlapping rank CPU " + "affinities; assign disjoint CPU sets or the same shared CPU set to local ranks.") + + assignments = [None] * len(layouts) + for index, layout in enumerate(layouts): + if assignments[index] is not None: + continue + peers = [ + peer for peer in range(index, len(layouts)) + if layouts[peer]["host"] == layout["host"] and cpu_sets[peer] == cpu_sets[index] + ] + if len(peers) > 1 and any(layouts[peer]["pin"] for peer in peers): + shared_units = layout["units"] + if any(layouts[peer]["units"] != shared_units for peer in peers): + raise ValueError("Reflow ranks sharing CPU affinity must use the same CPU placement type.") + base, remainder = divmod(len(shared_units), len(peers)) + for position, peer in enumerate(peers): + start = position * base + min(position, remainder) + count = base + (position < remainder) + assignments[peer] = [cpu for unit in shared_units[start:start + count] for cpu in unit] + else: + for peer in peers: + assignments[peer] = layouts[peer]["cpus"] + + for index, layout in enumerate(layouts): + if not layout["pin"]: + continue + assigned = set(assignments[index]) + if layout["main_type"] == "physical": + available = sum(bool(assigned.intersection(unit)) for unit in layout["units"]) + else: + available = len(assigned) + if available <= layout["main_count"]: + raise ValueError("Reflow needs enough CPUs per rank for the requested main_thread_cores and at least " + "one worker CPU.") + return sorted(assignments[rank]) + + +def plan_cpu_core_layout(main_thread_cores, + main_thread_core_type="logical", + worker_core_type="logical", + pin_main_thread=False): """Automatically find NUMA-aware cores for this rank. Priority: - 1. If the process is already pinned (numactl/taskset), respect exactly those cores. + 1. Honor the process affinity assigned by the launcher (numactl/taskset). + Identical rank affinities are divided when main-thread pinning is enabled. 2. Otherwise bind to the NUMA node this rank's GPU is physically attached to (read from the PCIe topology via sysfs/NVML), splitting that node's cores among the GPUs that share it, so the CPU optimizer runs on the cores local to the GPU's memory controller. @@ -331,21 +402,23 @@ def plan_cpu_core_layout(main_thread_cores, main_thread_core_type="logical", wor if physical: rank_cores = partition_physical_cpus(node_cores, n_on_node, my_pos) else: - chunk = max(1, len(node_cores) // n_on_node) - start = my_pos * chunk - rank_cores = node_cores[start:start + chunk] if start < len(node_cores) else node_cores + base, remainder = divmod(len(node_cores), n_on_node) + start = my_pos * base + min(my_pos, remainder) + count = base + (my_pos < remainder) + rank_cores = node_cores[start:start + count] else: rank_cores = node_cores else: rank_cores = heuristic_rank_cores(numa_nodes, local_rank, local_world_size, physical=physical) if not rank_cores: - if physical and affinity: + if affinity: rank_cores = affinity else: total = psutil.cpu_count(logical=False) or 1 rank_cores = list(range(total)) - rank_cores = sorted(rank_cores) + rank_cores = _isolate_rank_cpu_sets(sorted(rank_cores), main_thread_cores, main_thread_core_type, worker_core_type, + pin_main_thread) total_cpus = len(rank_cores) # Group this rank's cores by NUMA node so worker masks stay within a single node. diff --git a/docs/_pages/config-json.md b/docs/_pages/config-json.md index 6a3ca2f99640..009264e32da7 100644 --- a/docs/_pages/config-json.md +++ b/docs/_pages/config-json.md @@ -727,11 +727,11 @@ The `reflow` block enables it, so an empty block is enough to run with the defau "enable_cpu_affinity": false, "main_thread_cores": 3, "main_thread_core_type": "logical", - "pin_main_thread": false, + "pin_main_thread": true, "worker_core_type": "logical", - "bucketwise_worker_affinity": "task", + "bucketwise_worker_affinity": "thread", "bucketwise_cores_per_worker": 8, - "state_update_cores": 2, + "state_update_cores": null, "state_update_backward_cores": null } ``` @@ -751,7 +751,7 @@ The `reflow` block enables it, so an empty block is enough to run with the defau | Description | Default | | ----------- | ------- | -| CPUs or physical cores reserved from the optimizer workers, according to `main_thread_core_type`. Worker placement uses this reservation even when `enable_cpu_affinity` is false. | `3` | +| CPUs or physical cores reserved for the initializing thread, according to `main_thread_core_type`. Ranks sharing a CPU set divide it before reserving their main CPUs. Partially overlapping rank affinities are rejected when pinning is enabled. | `3` | ***main_thread_core_type***: [string] @@ -763,7 +763,7 @@ The `reflow` block enables it, so an empty block is enough to run with the defau | Description | Default | | ----------- | ------- | -| Pin the initializing thread to the reserved main CPUs. Its original affinity is restored on engine destruction. Requires OS thread-affinity support. | `false` | +| Pin the initializing thread to the reserved main CPUs. Its original affinity is restored on engine destruction. Requires OS thread-affinity support. | `true` | ***worker_core_type***: [string] @@ -775,7 +775,7 @@ The `reflow` block enables it, so an empty block is enough to run with the defau | Description | Default | | ----------- | ------- | -| Assign a CPU mask per submitted task (`task`) or pin each pool thread to its initial mask (`thread`). | `"task"` | +| Assign a CPU mask per submitted task (`task`) or pin each pool thread to its initial mask (`thread`). | `"thread"` | ***bucketwise_cores_per_worker***: [integer] @@ -783,11 +783,11 @@ The `reflow` block enables it, so an empty block is enough to run with the defau | ----------- | ------- | | Maximum worker CPU IDs per bucketwise worker. Each NUMA group is split into chunks of this size; the final chunk may be smaller. One pool thread is created per chunk. | `8` | -***state_update_cores***: [integer] +***state_update_cores***: [integer or null] | Description | Default | | ----------- | ------- | -| Worker CPU IDs available to the background optimizer-state commit while it overlaps the next forward. Once backward starts, the commit uses the mask selected by `state_update_backward_cores`. | `2` | +| Limit worker CPU IDs available to the background optimizer-state commit during forward. When unset, all worker CPUs are available. | `null` | ***state_update_backward_cores***: [integer or null] diff --git a/docs/_tutorials/reflow.md b/docs/_tutorials/reflow.md index 7a5622067e06..995c8830c7fc 100644 --- a/docs/_tutorials/reflow.md +++ b/docs/_tutorials/reflow.md @@ -32,8 +32,7 @@ Reflow needs no model code changes. Enable it in the DeepSpeed configuration: "reflow": { "enable_cpu_affinity": true, "main_thread_cores": 2, - "bucketwise_cores_per_worker": 8, - "state_update_cores": 2 + "bucketwise_cores_per_worker": 8 } }, "optimizer": { @@ -53,7 +52,7 @@ Launch with `--bind_cores_to_rank` so each rank runs on the CPU cores local to i deepspeed --bind_cores_to_rank train.py --deepspeed_config ds_config.json ``` -Reflow always pins optimizer workers to NUMA-local cores and reserves `main_thread_cores` from those workers. `enable_cpu_affinity` additionally restricts the main process to its NUMA-local core slice. The remaining cores are split into workers of `bucketwise_cores_per_worker` cores. While the state commit overlaps the forward it uses only `state_update_cores` cores: every busy core lowers the CPU's turbo frequency, which would slow the launch-bound forward. +By default Reflow pins the initializing thread to `main_thread_cores` CPU IDs and divides the remaining CPUs among optimizer workers. Local ranks sharing a CPU set divide it before reserving their main CPUs; partially overlapping rank affinities are rejected. The state commit may use all worker CPUs unless `state_update_cores` or `state_update_backward_cores` sets a limit. `enable_cpu_affinity` additionally restricts the main process to its NUMA-local CPU slice. ## Gradient clipping diff --git a/tests/unit/v1/ops/test_reflow_cpu_optimizers.py b/tests/unit/v1/ops/test_reflow_cpu_optimizers.py index f5c67c6394c5..1049011291e5 100644 --- a/tests/unit/v1/ops/test_reflow_cpu_optimizers.py +++ b/tests/unit/v1/ops/test_reflow_cpu_optimizers.py @@ -231,7 +231,7 @@ def test_phase1_produces_bf16_and_defers(self, model_size, grad_dtype, weight_de module.reflow_destroy_lion(opt_id) # Phase-1 emits the base optimizer's new weights into the half buffer (BF16/FP16 rounding)... - torch.testing.assert_close(half_params.float(), param_ref, atol=2e-2, rtol=2e-2) + assert torch.equal(half_params, param_ref.to(grad_dtype)) # ...and leaves the FP32 master and momentum untouched (the deferred writeback). torch.testing.assert_close(param_fp32, param_before, atol=0, rtol=0) torch.testing.assert_close(exp_avg, exp_avg_before, atol=0, rtol=0) diff --git a/tests/unit/v1/zero/test_reflow.py b/tests/unit/v1/zero/test_reflow.py index e881cdcd4970..4518178e4f66 100644 --- a/tests/unit/v1/zero/test_reflow.py +++ b/tests/unit/v1/zero/test_reflow.py @@ -46,6 +46,9 @@ def test_reflow_block_configures_the_optimizer(): config = DeepSpeedConfig(minimal_reflow_config({"state_update_cores": 4})) assert config.zero_config.reflow.state_update_cores == 4 assert config.zero_config.reflow.bucketwise_cores_per_worker == 8 + assert config.zero_config.reflow.bucketwise_worker_affinity == "thread" + assert config.zero_config.reflow.pin_main_thread is True + assert DeepSpeedConfig(minimal_reflow_config()).zero_config.reflow.state_update_cores is None for cores in (1, 4, 8): config = DeepSpeedConfig(minimal_reflow_config({"bucketwise_cores_per_worker": cores})) @@ -66,6 +69,12 @@ def test_cpu_placement_options_are_validated(): config = DeepSpeedConfig(minimal_reflow_config(options)).zero_config.reflow for key, value in options.items(): assert getattr(config, key) == value + config = DeepSpeedConfig(minimal_reflow_config({ + "bucketwise_worker_affinity": "task", + "pin_main_thread": False + })).zero_config.reflow + assert config.bucketwise_worker_affinity == "task" + assert config.pin_main_thread is False for key in ("main_thread_core_type", "worker_core_type", "bucketwise_worker_affinity"): with pytest.raises(ValueError): DeepSpeedConfig(minimal_reflow_config({key: "unsupported"})) @@ -250,6 +259,8 @@ def test_heuristic_numa_split_with_uneven_rank_count(): nodes = [list(range(8)), list(range(8, 16))] assigned = [set(reflow_utils.heuristic_rank_cores(nodes, rank, 3)) for rank in range(3)] assert assigned == [set(range(4)), set(range(8, 16)), set(range(4, 8))] + assigned = [set(reflow_utils.heuristic_rank_cores([list(range(11))], rank, 3)) for rank in range(3)] + assert assigned == [set(range(4)), set(range(4, 8)), set(range(8, 11))] # The oracle runs are bf16 ZeRO-3 on a GPU accelerator; Reflow is not validated on the CPU accelerator. @@ -555,7 +566,6 @@ def test_training_and_cpu_placement(self, worker_affinity, worker_type): config["zero_optimization"]["reflow"] = { "main_thread_cores": 1, "main_thread_core_type": "physical", - "pin_main_thread": True, "worker_core_type": worker_type, "bucketwise_cores_per_worker": 4, "bucketwise_worker_affinity": worker_affinity, @@ -577,13 +587,13 @@ def observe(engine): original = getattr(native, name) originals[name] = original - def recorded(*args, _phase=phase, _original=original): + def recorded(*args, _phase=phase, _original=original, **kwargs): mask = frozenset(os.sched_getaffinity(0)) if _phase == "params": param_masks.setdefault(threading.get_native_id(), set()).add(mask) else: state_masks.add(mask) - return _original(*args) + return _original(*args, **kwargs) setattr(native, name, recorded) @@ -624,6 +634,96 @@ def recorded(*args, _phase=phase, _original=original): assert torch.equal(got, want) +@pytest.mark.parametrize("rank_affinity", ["shared", "launcher", "partial", "insufficient"]) +@needs_gpu_accelerator +class TestReflowRankCoreBinding(DistributedTest): + world_size = 2 + + def test_rank_main_and_worker_cpus_are_disjoint(self, rank_affinity): + # A shared container cpuset must be split, while launcher-assigned rank cpus must be retained. + skip_if_reflow_training_unsupported() + if not hasattr(os, "sched_getaffinity"): + pytest.skip("requires Linux CPU affinity") + original = set(os.sched_getaffinity(0)) + available = [None] * dist.get_world_size() + dist.all_gather_object(available, sorted(original)) + shared = sorted(set.intersection(*(set(cpus) for cpus in available))) + if len(shared) < 16: + pytest.skip("requires at least 16 CPUs available to both ranks") + shared = shared[:16] + rank = dist.get_rank() + rank_cpus = set(shared[rank * 8:(rank + 1) * 8]) + if rank_affinity == "shared": + input_cpus = set(shared) + elif rank_affinity == "partial": + input_cpus = set(shared[:12] if rank == 0 else shared[4:]) + elif rank_affinity == "insufficient": + input_cpus = set(shared[rank * 3:(rank + 1) * 3]) + else: + input_cpus = rank_cpus + engine = None + native = None + originals = {} + worker_masks = [] + state_masks = [] + try: + os.sched_setaffinity(0, input_cpus) + torch.manual_seed(1234) + model = SimpleModel(hidden_dim=16, nlayers=2) + config = get_variant_config(reflow=True, variant="adam") + config["zero_optimization"]["reduce_bucket_size"] = 1_000_000 + if rank_affinity in ("partial", "insufficient"): + message = ("partially overlapping rank CPU affinities" + if rank_affinity == "partial" else "main_thread_cores and at least one worker CPU") + with pytest.raises(ValueError, match=message): + deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) + return + engine, optimizer, _, _ = deepspeed.initialize(model=model, + model_parameters=model.parameters(), + config=config) + main_cpus = set(os.sched_getaffinity(0)) + native = optimizer.optimizer.ds_opt_adam + for phase in ("params", "state"): + name = f"reflow_adam_update_{phase}_halfgrad" + originals[name] = getattr(native, name) + + def recorded(*args, _phase=phase, _original=originals[name], **kwargs): + mask = set(os.sched_getaffinity(0)) + if _phase == "params": + worker_masks.append(mask) + else: + state_masks.append(mask) + return _original(*args, **kwargs) + + setattr(native, name, recorded) + batches = make_batches(16, count=2) + for inputs, labels in batches: + loss = engine(inputs, labels) + engine.backward(loss) + engine.step() + optimizer.state_dict() + assert len(main_cpus) == 3 + assert main_cpus == set(sorted(rank_cpus)[:3]) + assert worker_masks + assert all(mask <= rank_cpus - main_cpus for mask in worker_masks) + assert state_masks + assert all(mask == rank_cpus - main_cpus for mask in state_masks) + placements = [None] * dist.get_world_size() + dist.all_gather_object(placements, (main_cpus, rank_cpus)) + assert placements[0][1].isdisjoint(placements[1][1]) + assert all(main <= cpus for main, cpus in placements) + finally: + if native is not None: + for name, original_fn in originals.items(): + setattr(native, name, original_fn) + if engine is not None: + engine.destroy() + restored_cpus = set(os.sched_getaffinity(0)) + os.sched_setaffinity(0, original) + if engine is not None: + assert restored_cpus == input_cpus + + class TestReflowOptimizerRequiresOptIn(DistributedTest): world_size = 1 non_daemonic_procs = True @@ -888,7 +988,8 @@ def read_state_right_after_each_step(model, config, batches): return snapshots -@pytest.mark.parametrize("gradient_accumulation_steps, warmup_lr", [(1, False), (3, False), (1, True)]) +@pytest.mark.parametrize("gradient_accumulation_steps, warmup_lr", [(1, False), (2, False), (3, False), (4, False), + (8, False), (1, True)]) @needs_gpu_accelerator class TestReflowStateReadAfterStep(DistributedTest): world_size = [1, 2] @@ -923,6 +1024,45 @@ def test_matches_zero_offload(self, gradient_accumulation_steps, warmup_lr): assert torch.equal(got, want), f"{name}[{index}] differs after step {step}" +@pytest.mark.parametrize("gradient_accumulation_steps", [4, 8]) +@pytest.mark.parametrize("precision", ["bf16", "fp16"]) +@needs_gpu_accelerator +class TestReflowAccumulationBufferReuse(DistributedTest): + world_size = 1 + + def test_matches_zero_offload(self, gradient_accumulation_steps, precision): + # Repeated updates with many parameters in one subgroup catch scratch buffers reused before CPU reads finish. + skip_if_reflow_training_unsupported() + hidden_dim = 128 + torch.manual_seed(1234) + dtype = torch.float16 if precision == "fp16" else torch.bfloat16 + batches = make_batches(hidden_dim, count=4 * gradient_accumulation_steps, dtype=dtype) + + def config_for(reflow): + config = get_state_read_config(reflow=reflow, + gradient_accumulation_steps=gradient_accumulation_steps, + warmup_lr=False) + config["zero_optimization"]["reduce_bucket_size"] = 1_000_000 + if precision == "fp16": + config["bf16"] = {"enabled": False} + config["fp16"] = {"enabled": True, "loss_scale": 128} + return config + + expected = read_state_right_after_each_step(SimpleModel(hidden_dim=hidden_dim, nlayers=8), config_for(False), + batches) + torch.manual_seed(1234) + actual = read_state_right_after_each_step(SimpleModel(hidden_dim=hidden_dim, nlayers=8), config_for(True), + batches) + for expected_step, actual_step in zip(expected, actual): + for expected_tensors, actual_tensors in zip(expected_step, actual_step): + for want, got in zip(expected_tensors, actual_tensors): + assert torch.equal(got, want) + + +class TestReflowAccumulationBufferReuseDistributed(TestReflowAccumulationBufferReuse): + world_size = 2 + + class TestReflowMaximizeClientInitialization(DistributedTest): world_size = 1 non_daemonic_procs = True @@ -980,3 +1120,43 @@ def test_matches_minimizing_negative_loss(self, adamw_mode): torch.testing.assert_close(actual, expected, rtol=0, atol=0) for expected, actual in zip(results[0][1], results[1][1]): torch.testing.assert_close(actual, expected, rtol=0, atol=0) + + +@pytest.mark.parametrize("precision", ["bf16", "fp16"]) +@pytest.mark.parametrize("invalid_value", [float("nan"), float("inf")]) +@needs_gpu_accelerator +class TestReflowInvalidGradient(DistributedTest): + world_size = [1, 2] + + def test_invalid_step_preserves_parameters_and_state(self, precision, invalid_value): + skip_if_reflow_training_unsupported() + torch.manual_seed(1234) + config = get_variant_config(reflow=True, variant="adam") + config["zero_optimization"]["reduce_bucket_size"] = 1_000_000 + if precision == "fp16": + config["bf16"] = {"enabled": False} + config["fp16"] = {"enabled": True, "loss_scale": 128} + dtype = torch.float16 if precision == "fp16" else torch.bfloat16 + batches = make_batches(16, count=2, dtype=dtype) + model = SimpleModel(hidden_dim=16, nlayers=2) + engine, optimizer, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) + try: + loss = engine(*batches[0]) + engine.backward(loss) + engine.step() + before_params = [safe_get_full_fp32_param(p).clone() for p in engine.module.parameters()] + before_states = [safe_get_full_optimizer_state(p, "exp_avg").clone() for p in engine.module.parameters()] + before_steps = [int(state["step"]) for state in optimizer.optimizer.state.values()] + skipped_steps = engine.skipped_steps + loss = engine(*batches[1]) + if dist.get_rank() == 0: + loss = loss * invalid_value + engine.backward(loss) + engine.step() + assert engine.skipped_steps == skipped_steps + 1 + assert [int(state["step"]) for state in optimizer.optimizer.state.values()] == before_steps + for param, before_param, before_state in zip(engine.module.parameters(), before_params, before_states): + assert torch.equal(safe_get_full_fp32_param(param), before_param) + assert torch.equal(safe_get_full_optimizer_state(param, "exp_avg"), before_state) + finally: + engine.destroy() From 958fdc982a1b92fad86b683721f6cac8a486096f Mon Sep 17 00:00:00 2001 From: st-bang97 Date: Wed, 18 Nov 2026 22:24:14 +0900 Subject: [PATCH 09/19] Separate ReFlow CPU builders and fix loss scaling Signed-off-by: st-bang97 --- accelerator/cpu_accelerator.py | 8 +- csrc/adam/cpu_adam.cpp | 3 - csrc/adam/reflow_cpu_adam_bindings.cpp | 4 +- csrc/includes/reflow_bindings.h | 9 - csrc/includes/reflow_cpu_adam.h | 2 +- csrc/includes/reflow_cpu_lion.h | 5 +- csrc/lion/cpu_lion.cpp | 3 - csrc/lion/reflow_cpu_lion_bindings.cpp | 4 +- deepspeed/runtime/reflow/README.md | 9 +- deepspeed/runtime/reflow/reflow_cpu_adam.py | 8 +- deepspeed/runtime/reflow/reflow_cpu_lion.py | 6 +- .../runtime/zero/partition_parameters.py | 4 +- op_builder/cpu/__init__.py | 2 + op_builder/cpu/cpu_adam.py | 5 +- op_builder/cpu/cpu_lion.py | 5 +- op_builder/cpu/reflow.py | 58 +++++ op_builder/cpu/reflow_cpu_adam.py | 18 ++ op_builder/cpu/reflow_cpu_lion.py | 18 ++ op_builder/hpu/cpu_adam.py | 5 +- op_builder/klxpu/cpu_adam.py | 5 +- op_builder/klxpu/cpu_lion.py | 5 +- op_builder/mlu/cpu_adam.py | 5 +- op_builder/mps/cpu_adam.py | 5 +- op_builder/npu/cpu_adam.py | 5 +- op_builder/npu/cpu_lion.py | 5 +- op_builder/reflow_cpu_adam.py | 4 + op_builder/reflow_cpu_lion.py | 4 + op_builder/sdaa/cpu_adam.py | 5 +- op_builder/supa/cpu_adam.py | 5 +- op_builder/supa/cpu_lion.py | 5 +- op_builder/xpu/cpu_adam.py | 5 +- .../v1/ops/muon/test_muon_partial_training.py | 3 + .../unit/v1/ops/test_reflow_cpu_optimizers.py | 207 +++++++++++++----- tests/unit/v1/zero/test_reflow.py | 70 +++++- 34 files changed, 366 insertions(+), 148 deletions(-) delete mode 100644 csrc/includes/reflow_bindings.h create mode 100644 op_builder/cpu/reflow.py create mode 100644 op_builder/cpu/reflow_cpu_adam.py create mode 100644 op_builder/cpu/reflow_cpu_lion.py create mode 100644 op_builder/reflow_cpu_adam.py create mode 100644 op_builder/reflow_cpu_lion.py diff --git a/accelerator/cpu_accelerator.py b/accelerator/cpu_accelerator.py index 1290523a6c6f..1737218f31c1 100644 --- a/accelerator/cpu_accelerator.py +++ b/accelerator/cpu_accelerator.py @@ -475,9 +475,9 @@ def get_op_builder(self, class_name): # is op_builder from deepspeed or a 3p version? this should only succeed if it's deepspeed # if successful this also means we're doing a local install and not JIT compile path from op_builder import __deepspeed__ # noqa: F401 # type: ignore - from op_builder.cpu import AsyncIOBuilder, CCLCommBuilder, ShareMemCommBuilder, FusedAdamBuilder, CPUAdamBuilder, CPUAdagradBuilder, CPULionBuilder, PinMemoryBuilder, NotImplementedBuilder + from op_builder.cpu import AsyncIOBuilder, CCLCommBuilder, ShareMemCommBuilder, FusedAdamBuilder, CPUAdamBuilder, CPUAdagradBuilder, CPULionBuilder, ReflowCPUAdamBuilder, ReflowCPULionBuilder, PinMemoryBuilder, NotImplementedBuilder except ImportError: - from deepspeed.ops.op_builder.cpu import AsyncIOBuilder, CCLCommBuilder, ShareMemCommBuilder, FusedAdamBuilder, CPUAdamBuilder, CPUAdagradBuilder, CPULionBuilder, PinMemoryBuilder, NotImplementedBuilder + from deepspeed.ops.op_builder.cpu import AsyncIOBuilder, CCLCommBuilder, ShareMemCommBuilder, FusedAdamBuilder, CPUAdamBuilder, CPUAdagradBuilder, CPULionBuilder, ReflowCPUAdamBuilder, ReflowCPULionBuilder, PinMemoryBuilder, NotImplementedBuilder if class_name == "CCLCommBuilder": return CCLCommBuilder @@ -491,6 +491,10 @@ def get_op_builder(self, class_name): return CPUAdagradBuilder elif class_name == "CPULionBuilder": return CPULionBuilder + elif class_name == "ReflowCPUAdamBuilder": + return ReflowCPUAdamBuilder + elif class_name == "ReflowCPULionBuilder": + return ReflowCPULionBuilder elif class_name == "AsyncIOBuilder": return AsyncIOBuilder elif class_name == "PinMemoryBuilder": diff --git a/csrc/adam/cpu_adam.cpp b/csrc/adam/cpu_adam.cpp index 305ac8797835..d9b6926fc992 100644 --- a/csrc/adam/cpu_adam.cpp +++ b/csrc/adam/cpu_adam.cpp @@ -5,7 +5,6 @@ #include "cpu_adam.h" #include -#include "reflow_bindings.h" PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { @@ -67,6 +66,4 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) "ZenFlowAdam cross-process exit (C++)", pybind11::call_guard()); #endif - - bind_reflow_adam(m); } diff --git a/csrc/adam/reflow_cpu_adam_bindings.cpp b/csrc/adam/reflow_cpu_adam_bindings.cpp index d01aaf24ff37..843d2f705ebc 100644 --- a/csrc/adam/reflow_cpu_adam_bindings.cpp +++ b/csrc/adam/reflow_cpu_adam_bindings.cpp @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // DeepSpeed Team -#include "reflow_bindings.h" +#include #include "reflow_cpu_adam.h" // Memory fence to enforce store ordering after non-temporal (streaming) stores. @@ -88,7 +88,7 @@ static inline int reflow_ds_bf16_accumulate_gilfree(torch::Tensor& dst, torch::T return reflow_ds_bf16_accumulate(dst, src); } -void bind_reflow_adam(pybind11::module_& m) +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("reflow_create_adam", &reflow_create_adam_optimizer, diff --git a/csrc/includes/reflow_bindings.h b/csrc/includes/reflow_bindings.h deleted file mode 100644 index 9d28f7adbcc6..000000000000 --- a/csrc/includes/reflow_bindings.h +++ /dev/null @@ -1,9 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// DeepSpeed Team - -#pragma once - -#include - -void bind_reflow_adam(pybind11::module_& m); -void bind_reflow_lion(pybind11::module_& m); diff --git a/csrc/includes/reflow_cpu_adam.h b/csrc/includes/reflow_cpu_adam.h index 10f3eed68a7d..b6920a01e2d2 100644 --- a/csrc/includes/reflow_cpu_adam.h +++ b/csrc/includes/reflow_cpu_adam.h @@ -219,7 +219,7 @@ void Reflow_Adam_Optimizer::Step_AVX_HalfGrad(size_t* rounded_size, // Pick the loop specialized for this step's flags, so no per-element branch remains. // A negative scale folds maximizing into the existing gradient multiply, before weight decay. - bool unscale_grads = (combined_scale > 1.0f || combined_scale < 0.0f); + bool unscale_grads = (combined_scale != 1.0f); bool decay_grad = (_weight_decay > 0 && !_adamw_mode); bool decay_param = (_weight_decay > 0 && _adamw_mode); using G = ds_grad_precision_t; diff --git a/csrc/includes/reflow_cpu_lion.h b/csrc/includes/reflow_cpu_lion.h index c3b5d8482bcf..75787d680aaf 100644 --- a/csrc/includes/reflow_cpu_lion.h +++ b/csrc/includes/reflow_cpu_lion.h @@ -170,8 +170,7 @@ void Reflow_Lion_Optimizer::Step_AVX_HalfGrad(size_t* rounded_size, if (_weight_decay > 0) after_decay_4.data = SIMD_SET(after_decay); bool use_weight_decay = (_weight_decay > 0); - // Unscale (after FP32 promotion) only when combined_scale > 1. - bool need_unscale = (combined_scale > 1.0f); + bool need_unscale = (combined_scale != 1.0f); AVX_Data unscale_factor; if (need_unscale) { unscale_factor.data = SIMD_SET(1.0f / combined_scale); } @@ -264,7 +263,7 @@ void Reflow_Lion_Optimizer::Step_AVX_FP16_HalfGrad(size_t* rounded_size, if (_weight_decay > 0) after_decay_4.data = SIMD_SET(after_decay); bool use_weight_decay = (_weight_decay > 0); - bool need_unscale = (combined_scale > 1.0f); + bool need_unscale = (combined_scale != 1.0f); AVX_Data unscale_factor; if (need_unscale) { unscale_factor.data = SIMD_SET(1.0f / combined_scale); } diff --git a/csrc/lion/cpu_lion.cpp b/csrc/lion/cpu_lion.cpp index d34f790dcda2..acf7815d19fb 100644 --- a/csrc/lion/cpu_lion.cpp +++ b/csrc/lion/cpu_lion.cpp @@ -5,13 +5,10 @@ #include "cpu_lion.h" #include -#include "reflow_bindings.h" PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("lion_update", &ds_lion_step, "DeepSpeed CPU Lion update (C++)"); m.def("create_lion", &create_lion_optimizer, "DeepSpeed CPU Lion (C++)"); m.def("destroy_lion", &destroy_lion_optimizer, "DeepSpeed CPU Lion destroy (C++)"); - - bind_reflow_lion(m); } diff --git a/csrc/lion/reflow_cpu_lion_bindings.cpp b/csrc/lion/reflow_cpu_lion_bindings.cpp index bfe59da73e19..518efd0537df 100644 --- a/csrc/lion/reflow_cpu_lion_bindings.cpp +++ b/csrc/lion/reflow_cpu_lion_bindings.cpp @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // DeepSpeed Team -#include "reflow_bindings.h" +#include #include "reflow_cpu_lion.h" // Memory fence to enforce store ordering after non-temporal (streaming) stores. @@ -66,7 +66,7 @@ static inline int reflow_ds_lion_state_step_halfgrad_gilfree(int optimizer_id, skip_increment_step); } -void bind_reflow_lion(pybind11::module_& m) +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("reflow_create_lion", &reflow_create_lion_optimizer, diff --git a/deepspeed/runtime/reflow/README.md b/deepspeed/runtime/reflow/README.md index fc3dafcfad29..06eaeb7cc9d6 100644 --- a/deepspeed/runtime/reflow/README.md +++ b/deepspeed/runtime/reflow/README.md @@ -81,13 +81,18 @@ a disjoint NUMA-local core slice) plus a single chained async-state worker. |---|---| | `reflow_stage3.py` | `ReflowOptimizer_Stage3` (ZeRO-3 subclass): the bucketwise pipeline, the grad-copy / H2D streams, the split `step()`, the worker pools, and the affinity wiring. | | `reflow_cpu_adam.py` | `ReflowCPUAdam` (extends `DeepSpeedCPUAdam`): the half-grad / state-only / per-range Adam variants. Registers its native optimizer in a **separate** Reflow C++ registry with its own `opt_id` space, isolating it from any plain `DeepSpeedCPUAdam` in the process. | -| `reflow_cpu_lion.py` | `ReflowCPULion` (extends `DeepSpeedCPULion`): the same half-grad / state-only / per-range variants for Lion's single-momentum update. Its own Reflow C++ registry in the `cpu_lion` extension. | +| `reflow_cpu_lion.py` | `ReflowCPULion` (extends `DeepSpeedCPULion`): the same half-grad / state-only / per-range variants for Lion's single-momentum update. Its own Reflow C++ registry in the `reflow_cpu_lion` extension. | | `reflow_utils.py` | `plan_cpu_core_layout()` — NUMA-aware affinity planning (reads each GPU's PCIe→NUMA node) — plus contiguous-range helpers for the bucketwise pipeline. Pure helpers, no optimizer state. | | `csrc/adam/reflow_cpu_adam_impl.cpp`, `csrc/includes/reflow_cpu_adam.h` | The AVX CPU-Adam kernels and the `reflow_*` C++ entry points (half-grad param generation, half-grad state commit, and half-precision gradient accumulation). | | `csrc/lion/reflow_cpu_lion_impl.cpp`, `csrc/includes/reflow_cpu_lion.h` | The matching AVX CPU-Lion kernels and `reflow_lion_*` C++ entry points (single-momentum, sign-based update). | | `csrc/includes/reflow_cpu_affinity.h` | Applies each worker CPU mask to its retained OpenMP helper threads when the worker moves or the state commit widens for backward. | | `csrc/includes/reflow_simd.h` | Reflow-only SIMD conversions and streaming stores, layered on the shared `simd.h`. | -| `csrc/adam/reflow_cpu_adam_bindings.cpp`, `csrc/lion/reflow_cpu_lion_bindings.cpp` | Reflow Python bindings and GIL-released worker wrappers, registered through `csrc/includes/reflow_bindings.h` in the existing CPU optimizer modules. | +| `csrc/adam/reflow_cpu_adam_bindings.cpp`, `csrc/lion/reflow_cpu_lion_bindings.cpp` | Reflow Python bindings and GIL-released worker wrappers, built as independent ReFlow CPU optimizer modules. | + +ReFlow builds its CPU Adam and Lion kernels independently from the standard CPU optimizer extensions. +The ReFlow builders require an x86 CPU with AVX2 or AVX-512 and currently support CPU and CUDA +accelerator configurations. They build on first use by default; set `DS_BUILD_REFLOW_CPU_ADAM=1` +or `DS_BUILD_REFLOW_CPU_LION=1` to pre-build the corresponding extension. A client that passes a plain `DeepSpeedCPUAdam` / `DeepSpeedCPULion` is auto-remapped to `ReflowCPUAdam` / `ReflowCPULion` when the `reflow` block is set (see diff --git a/deepspeed/runtime/reflow/reflow_cpu_adam.py b/deepspeed/runtime/reflow/reflow_cpu_adam.py index 0677bc69c0b2..438568a52fd0 100644 --- a/deepspeed/runtime/reflow/reflow_cpu_adam.py +++ b/deepspeed/runtime/reflow/reflow_cpu_adam.py @@ -18,7 +18,7 @@ optimizer can run on gradient buckets as they arrive during backward. It registers its native optimizer instance in a separate Reflow registry inside the -``cpu_adam`` C++ extension (the ``reflow_*`` entry points), with its own opt_id space. +``reflow_cpu_adam`` C++ extension (the ``reflow_*`` entry points), with its own opt_id space. This keeps its C++ state isolated from any :class:`DeepSpeedCPUAdam` instances running in the same process. """ @@ -28,7 +28,7 @@ from deepspeed.utils import logger from deepspeed.utils.logging import should_log_le -from deepspeed.ops.op_builder import CPUAdamBuilder +from deepspeed.ops.op_builder.cpu.reflow_cpu_adam import ReflowCPUAdamBuilder from deepspeed.ops.adam.cpu_adam import DeepSpeedCPUAdam _CPU_DEVICE = torch.device('cpu') @@ -92,7 +92,7 @@ def __init__(self, # None means "use all available cores"; converted to -1 at call time. self.num_threads = num_threads - self.ds_opt_adam = CPUAdamBuilder().load() + self.ds_opt_adam = ReflowCPUAdamBuilder().load() num_threads = int(self.num_threads) if self.num_threads is not None else -1 self.ds_opt_adam.reflow_create_adam(self.opt_id, lr, betas[0], betas[1], eps, weight_decay, adamw_mode, should_log_le("info"), num_threads) @@ -116,7 +116,7 @@ def bf16_accumulate(cls, dst, src): and share the same dtype (BF16 or FP16). Used to accumulate gradients across micro-steps. """ if not hasattr(cls, '_cpu_adam_module'): - cls._cpu_adam_module = CPUAdamBuilder().load() + cls._cpu_adam_module = ReflowCPUAdamBuilder().load() cls._cpu_adam_module.reflow_bf16_accumulate(dst, src) def __del__(self): diff --git a/deepspeed/runtime/reflow/reflow_cpu_lion.py b/deepspeed/runtime/reflow/reflow_cpu_lion.py index 5d29676de7bb..a5e3ba32459c 100644 --- a/deepspeed/runtime/reflow/reflow_cpu_lion.py +++ b/deepspeed/runtime/reflow/reflow_cpu_lion.py @@ -21,7 +21,7 @@ eps, and no bias correction, so the optimizer state is half the size of Adam's. It registers its native optimizer instance in a separate Reflow registry inside the -``cpu_lion`` C++ extension (the ``reflow_*`` entry points), with its own opt_id space. +``reflow_cpu_lion`` C++ extension (the ``reflow_*`` entry points), with its own opt_id space. This keeps its C++ state isolated from any :class:`DeepSpeedCPULion` instances running in the same process. """ @@ -31,7 +31,7 @@ from deepspeed.utils import logger from deepspeed.utils.logging import should_log_le -from deepspeed.ops.op_builder import CPULionBuilder +from deepspeed.ops.op_builder.cpu.reflow_cpu_lion import ReflowCPULionBuilder from deepspeed.ops.lion.cpu_lion import DeepSpeedCPULion _CPU_DEVICE = torch.device('cpu') @@ -82,7 +82,7 @@ def __init__(self, # None means "use all available cores"; converted to -1 at call time. self.num_threads = num_threads - self.ds_opt_lion = CPULionBuilder().load() + self.ds_opt_lion = ReflowCPULionBuilder().load() num_threads = int(self.num_threads) if self.num_threads is not None else -1 self.ds_opt_lion.reflow_create_lion(self.opt_id, lr, betas[0], betas[1], weight_decay, should_log_le("info"), num_threads) diff --git a/deepspeed/runtime/zero/partition_parameters.py b/deepspeed/runtime/zero/partition_parameters.py index 06e07f58525b..80f9a1009dc4 100644 --- a/deepspeed/runtime/zero/partition_parameters.py +++ b/deepspeed/runtime/zero/partition_parameters.py @@ -401,8 +401,8 @@ def _set_dtype(self, ds_config, dtype): else: self.dtype = torch.float else: - self.dtype = dtype or torch.float16 if get_accelerator().is_fp16_supported( - ) else torch.bfloat16 if get_accelerator().is_bf16_supported else torch.float32 + self.dtype = dtype or (torch.float16 if get_accelerator().is_fp16_supported() else + torch.bfloat16 if get_accelerator().is_bf16_supported() else torch.float32) def _enable_mem_efficient_linear(self): print_rank_0( diff --git a/op_builder/cpu/__init__.py b/op_builder/cpu/__init__.py index 84a15b088b6c..e7f5fc34c84e 100644 --- a/op_builder/cpu/__init__.py +++ b/op_builder/cpu/__init__.py @@ -9,6 +9,8 @@ from .cpu_adam import CPUAdamBuilder from .cpu_adagrad import CPUAdagradBuilder from .cpu_lion import CPULionBuilder +from .reflow_cpu_adam import ReflowCPUAdamBuilder +from .reflow_cpu_lion import ReflowCPULionBuilder from .no_impl import NotImplementedBuilder from .async_io import AsyncIOBuilder from .pin_memory import PinMemoryBuilder diff --git a/op_builder/cpu/cpu_adam.py b/op_builder/cpu/cpu_adam.py index e3237e874605..0c8438aea40d 100644 --- a/op_builder/cpu/cpu_adam.py +++ b/op_builder/cpu/cpu_adam.py @@ -17,10 +17,7 @@ def absolute_name(self): return f'deepspeed.ops.adam.{self.NAME}_op' def sources(self): - return [ - 'csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp', 'csrc/adam/reflow_cpu_adam_impl.cpp', - 'csrc/adam/reflow_cpu_adam_bindings.cpp' - ] + return ['csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp'] def libraries_args(self): args = super().libraries_args() diff --git a/op_builder/cpu/cpu_lion.py b/op_builder/cpu/cpu_lion.py index 86f302a57db2..4a748934296e 100644 --- a/op_builder/cpu/cpu_lion.py +++ b/op_builder/cpu/cpu_lion.py @@ -17,10 +17,7 @@ def absolute_name(self): return f'deepspeed.ops.lion.{self.NAME}_op' def sources(self): - return [ - 'csrc/lion/cpu_lion.cpp', 'csrc/lion/cpu_lion_impl.cpp', 'csrc/lion/reflow_cpu_lion_impl.cpp', - 'csrc/lion/reflow_cpu_lion_bindings.cpp' - ] + return ['csrc/lion/cpu_lion.cpp', 'csrc/lion/cpu_lion_impl.cpp'] def libraries_args(self): args = super().libraries_args() diff --git a/op_builder/cpu/reflow.py b/op_builder/cpu/reflow.py new file mode 100644 index 000000000000..e83bd4ce42fb --- /dev/null +++ b/op_builder/cpu/reflow.py @@ -0,0 +1,58 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team + +from .builder import CPUOpBuilder + + +class ReflowCPUOp(CPUOpBuilder): + """Host kernels are currently validated only on x86 CPU and CUDA configurations.""" + + def _cpu_flags(self): + try: + from cpuinfo import get_cpu_info + cpu_info = get_cpu_info() + except Exception: + cpu_info = self._backup_cpuinfo() + return set(cpu_info.get('flags', [])) if cpu_info else set() + + def simd_width(self): + width = super().simd_width() + if width == '-D__AVX512__': + flags = self._cpu_flags() + required = {'avx512f', 'avx512bw', 'avx512dq', 'avx512vl'} + if not required.issubset(flags): + return '-D__AVX256__' if {'avx2', 'fma', 'f16c'}.issubset(flags) else '-D__SCALAR__' + return width + + def is_compatible(self, verbose=False): + try: + import torch + except ImportError: + return False + try: + from accelerator import get_accelerator + except ImportError: + from deepspeed.accelerator import get_accelerator + + accelerator_name = get_accelerator()._name + if accelerator_name not in ('cpu', 'cuda') or (accelerator_name == 'cuda' and torch.version.hip is not None): + if verbose: + self.warning(f'{self.name} supports only CPU and CUDA accelerator configurations') + return False + simd_width = self.simd_width() + if simd_width not in ('-D__AVX256__', '-D__AVX512__'): + if verbose: + self.warning(f'{self.name} requires an x86 CPU with AVX2 or AVX-512') + return False + flags = self._cpu_flags() + required_flags = {'avx2', 'fma', 'f16c'} + if simd_width == '-D__AVX512__': + required_flags.update(('avx512f', 'avx512bw', 'avx512dq', 'avx512vl')) + if not required_flags.issubset(flags): + if verbose: + self.warning(f'{self.name} requires CPU flags {sorted(required_flags)}') + return False + return super().is_compatible(verbose) + + def include_paths(self): + return ['csrc/includes'] diff --git a/op_builder/cpu/reflow_cpu_adam.py b/op_builder/cpu/reflow_cpu_adam.py new file mode 100644 index 000000000000..5b408cb73345 --- /dev/null +++ b/op_builder/cpu/reflow_cpu_adam.py @@ -0,0 +1,18 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team + +from .reflow import ReflowCPUOp + + +class ReflowCPUAdamBuilder(ReflowCPUOp): + BUILD_VAR = 'DS_BUILD_REFLOW_CPU_ADAM' + NAME = 'reflow_cpu_adam' + + def __init__(self): + super().__init__(name=self.NAME) + + def absolute_name(self): + return f'deepspeed.ops.adam.{self.NAME}_op' + + def sources(self): + return ['csrc/adam/reflow_cpu_adam_bindings.cpp', 'csrc/adam/reflow_cpu_adam_impl.cpp'] diff --git a/op_builder/cpu/reflow_cpu_lion.py b/op_builder/cpu/reflow_cpu_lion.py new file mode 100644 index 000000000000..addd1c23cb7e --- /dev/null +++ b/op_builder/cpu/reflow_cpu_lion.py @@ -0,0 +1,18 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team + +from .reflow import ReflowCPUOp + + +class ReflowCPULionBuilder(ReflowCPUOp): + BUILD_VAR = 'DS_BUILD_REFLOW_CPU_LION' + NAME = 'reflow_cpu_lion' + + def __init__(self): + super().__init__(name=self.NAME) + + def absolute_name(self): + return f'deepspeed.ops.lion.{self.NAME}_op' + + def sources(self): + return ['csrc/lion/reflow_cpu_lion_bindings.cpp', 'csrc/lion/reflow_cpu_lion_impl.cpp'] diff --git a/op_builder/hpu/cpu_adam.py b/op_builder/hpu/cpu_adam.py index 6b98589ffb30..58eea2698ebb 100644 --- a/op_builder/hpu/cpu_adam.py +++ b/op_builder/hpu/cpu_adam.py @@ -18,10 +18,7 @@ def absolute_name(self): return f'deepspeed.ops.adam.{self.NAME}_op' def sources(self): - return [ - 'csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp', 'csrc/adam/reflow_cpu_adam_impl.cpp', - 'csrc/adam/reflow_cpu_adam_bindings.cpp' - ] + return ['csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp'] def libraries_args(self): args = super().libraries_args() diff --git a/op_builder/klxpu/cpu_adam.py b/op_builder/klxpu/cpu_adam.py index 671089248c0c..21fb89498e4a 100644 --- a/op_builder/klxpu/cpu_adam.py +++ b/op_builder/klxpu/cpu_adam.py @@ -15,10 +15,7 @@ def absolute_name(self): return f'deepspeed.ops.adam.{self.NAME}_op' def sources(self): - return [ - 'csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp', 'csrc/adam/reflow_cpu_adam_impl.cpp', - 'csrc/adam/reflow_cpu_adam_bindings.cpp' - ] + return ['csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp'] def include_paths(self): args = super().include_paths() diff --git a/op_builder/klxpu/cpu_lion.py b/op_builder/klxpu/cpu_lion.py index 03a40e11a99c..76ad43401b2d 100644 --- a/op_builder/klxpu/cpu_lion.py +++ b/op_builder/klxpu/cpu_lion.py @@ -15,10 +15,7 @@ def absolute_name(self): return f'deepspeed.ops.lion.{self.NAME}_op' def sources(self): - return [ - 'csrc/lion/cpu_lion.cpp', 'csrc/lion/cpu_lion_impl.cpp', 'csrc/lion/reflow_cpu_lion_impl.cpp', - 'csrc/lion/reflow_cpu_lion_bindings.cpp' - ] + return ['csrc/lion/cpu_lion.cpp', 'csrc/lion/cpu_lion_impl.cpp'] def include_paths(self): args = super().include_paths() diff --git a/op_builder/mlu/cpu_adam.py b/op_builder/mlu/cpu_adam.py index 4d7141217221..b3c8e476bf39 100644 --- a/op_builder/mlu/cpu_adam.py +++ b/op_builder/mlu/cpu_adam.py @@ -18,10 +18,7 @@ def absolute_name(self): return f'deepspeed.ops.adam.{self.NAME}_op' def sources(self): - return [ - 'csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp', 'csrc/adam/reflow_cpu_adam_impl.cpp', - 'csrc/adam/reflow_cpu_adam_bindings.cpp' - ] + return ['csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp'] def libraries_args(self): args = super().libraries_args() diff --git a/op_builder/mps/cpu_adam.py b/op_builder/mps/cpu_adam.py index cc4a87f30c74..6d5f57c50bad 100644 --- a/op_builder/mps/cpu_adam.py +++ b/op_builder/mps/cpu_adam.py @@ -24,10 +24,7 @@ def absolute_name(self): return f'deepspeed.ops.adam.{self.NAME}_op' def sources(self): - return [ - 'csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp', 'csrc/adam/reflow_cpu_adam_impl.cpp', - 'csrc/adam/reflow_cpu_adam_bindings.cpp' - ] + return ['csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp'] def include_paths(self): return ['csrc/includes'] diff --git a/op_builder/npu/cpu_adam.py b/op_builder/npu/cpu_adam.py index 4e45194cb916..a4e9569c0f33 100644 --- a/op_builder/npu/cpu_adam.py +++ b/op_builder/npu/cpu_adam.py @@ -17,10 +17,7 @@ def absolute_name(self): return f'deepspeed.ops.adam.{self.NAME}_op' def sources(self): - return [ - 'csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp', 'csrc/adam/reflow_cpu_adam_impl.cpp', - 'csrc/adam/reflow_cpu_adam_bindings.cpp' - ] + return ['csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp'] def include_paths(self): args = super().include_paths() diff --git a/op_builder/npu/cpu_lion.py b/op_builder/npu/cpu_lion.py index c8113bc13e33..6917e0fd03d0 100644 --- a/op_builder/npu/cpu_lion.py +++ b/op_builder/npu/cpu_lion.py @@ -17,10 +17,7 @@ def absolute_name(self): return f'deepspeed.ops.lion.{self.NAME}_op' def sources(self): - return [ - 'csrc/lion/cpu_lion.cpp', 'csrc/lion/cpu_lion_impl.cpp', 'csrc/lion/reflow_cpu_lion_impl.cpp', - 'csrc/lion/reflow_cpu_lion_bindings.cpp' - ] + return ['csrc/lion/cpu_lion.cpp', 'csrc/lion/cpu_lion_impl.cpp'] def include_paths(self): args = super().include_paths() diff --git a/op_builder/reflow_cpu_adam.py b/op_builder/reflow_cpu_adam.py new file mode 100644 index 000000000000..4f93e888f765 --- /dev/null +++ b/op_builder/reflow_cpu_adam.py @@ -0,0 +1,4 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team + +from .cpu.reflow_cpu_adam import ReflowCPUAdamBuilder # noqa: F401 diff --git a/op_builder/reflow_cpu_lion.py b/op_builder/reflow_cpu_lion.py new file mode 100644 index 000000000000..72a12fe148cb --- /dev/null +++ b/op_builder/reflow_cpu_lion.py @@ -0,0 +1,4 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team + +from .cpu.reflow_cpu_lion import ReflowCPULionBuilder # noqa: F401 diff --git a/op_builder/sdaa/cpu_adam.py b/op_builder/sdaa/cpu_adam.py index 3848c2a67dde..b38a71a6275d 100755 --- a/op_builder/sdaa/cpu_adam.py +++ b/op_builder/sdaa/cpu_adam.py @@ -43,10 +43,7 @@ def absolute_name(self): return f'deepspeed.ops.adam.{self.NAME}_op' def sources(self): - return [ - 'csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp', 'csrc/adam/reflow_cpu_adam_impl.cpp', - 'csrc/adam/reflow_cpu_adam_bindings.cpp' - ] + return ['csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp'] def libraries_args(self): args = super().libraries_args() diff --git a/op_builder/supa/cpu_adam.py b/op_builder/supa/cpu_adam.py index 4a1093fe4b71..66f64079531a 100644 --- a/op_builder/supa/cpu_adam.py +++ b/op_builder/supa/cpu_adam.py @@ -15,10 +15,7 @@ def absolute_name(self): return f'deepspeed.ops.adam.{self.NAME}_op' def sources(self): - return [ - 'csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp', 'csrc/adam/reflow_cpu_adam_impl.cpp', - 'csrc/adam/reflow_cpu_adam_bindings.cpp' - ] + return ['csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp'] def include_paths(self): args = super().include_paths() diff --git a/op_builder/supa/cpu_lion.py b/op_builder/supa/cpu_lion.py index 522da669561f..8d77ce275c42 100644 --- a/op_builder/supa/cpu_lion.py +++ b/op_builder/supa/cpu_lion.py @@ -15,10 +15,7 @@ def absolute_name(self): return f'deepspeed.ops.lion.{self.NAME}_op' def sources(self): - return [ - 'csrc/lion/cpu_lion.cpp', 'csrc/lion/cpu_lion_impl.cpp', 'csrc/lion/reflow_cpu_lion_impl.cpp', - 'csrc/lion/reflow_cpu_lion_bindings.cpp' - ] + return ['csrc/lion/cpu_lion.cpp', 'csrc/lion/cpu_lion_impl.cpp'] def include_paths(self): args = super().include_paths() diff --git a/op_builder/xpu/cpu_adam.py b/op_builder/xpu/cpu_adam.py index 614e7215ef0b..9d5fdcd3e8ab 100644 --- a/op_builder/xpu/cpu_adam.py +++ b/op_builder/xpu/cpu_adam.py @@ -17,10 +17,7 @@ def absolute_name(self): return f'deepspeed.ops.adam.{self.NAME}_op' def sources(self): - return [ - 'csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp', 'csrc/adam/reflow_cpu_adam_impl.cpp', - 'csrc/adam/reflow_cpu_adam_bindings.cpp' - ] + return ['csrc/adam/cpu_adam.cpp', 'csrc/adam/cpu_adam_impl.cpp'] def libraries_args(self): args = super().libraries_args() diff --git a/tests/unit/v1/ops/muon/test_muon_partial_training.py b/tests/unit/v1/ops/muon/test_muon_partial_training.py index 9a9d44412c2f..c41407d744c2 100644 --- a/tests/unit/v1/ops/muon/test_muon_partial_training.py +++ b/tests/unit/v1/ops/muon/test_muon_partial_training.py @@ -20,6 +20,8 @@ ensuring empty parameter groups are properly handled. """ +from types import SimpleNamespace + import torch import torch.nn as nn import deepspeed @@ -388,6 +390,7 @@ def __init__(self, cpu_offload=False, bf16_states=False, zenflow=False): self.bf16_states = bf16_states self.zenflow = zenflow self.overlap_step = True + self._config = SimpleNamespace(zero_config=SimpleNamespace(reflow=None)) def zero_use_cpu_optimizer(self): return self.cpu_offload diff --git a/tests/unit/v1/ops/test_reflow_cpu_optimizers.py b/tests/unit/v1/ops/test_reflow_cpu_optimizers.py index 1049011291e5..f29c5183ab8c 100644 --- a/tests/unit/v1/ops/test_reflow_cpu_optimizers.py +++ b/tests/unit/v1/ops/test_reflow_cpu_optimizers.py @@ -13,12 +13,16 @@ kernels are a faithful drop-in. They run purely on CPU; no GPU/distributed env is required. """ +from functools import lru_cache + import pytest import torch from cpuinfo import get_cpu_info import deepspeed from deepspeed.ops.op_builder import CPUAdamBuilder, CPULionBuilder +from deepspeed.ops.op_builder.cpu.reflow_cpu_adam import ReflowCPUAdamBuilder +from deepspeed.ops.op_builder.cpu.reflow_cpu_lion import ReflowCPULionBuilder from deepspeed.runtime.reflow.reflow_cpu_adam import ReflowCPUAdam from deepspeed.runtime.reflow.reflow_cpu_lion import ReflowCPULion @@ -39,6 +43,7 @@ def _skip_amd_fp16(grad_dtype): pytest.skip("cpu optimizers with half precision not supported on AMD CPUs") +@lru_cache(maxsize=None) def _skip_without_avx(builder): # The Reflow kernels exist only for AVX2/AVX-512; on other builds creating the optimizer raises. if builder().simd_width() not in ("-D__AVX512__", "-D__AVX256__"): @@ -52,7 +57,8 @@ def test_reflow_optimizer_rejects_low_precision_states(optimizer_type): optimizer_type([param], fp32_optimizer_states=False) -@pytest.mark.parametrize("optimizer_type, builder", [(ReflowCPUAdam, CPUAdamBuilder), (ReflowCPULion, CPULionBuilder)]) +@pytest.mark.parametrize("optimizer_type, builder", [(ReflowCPUAdam, ReflowCPUAdamBuilder), + (ReflowCPULion, ReflowCPULionBuilder)]) def test_reflow_optimizer_rejects_direct_step(optimizer_type, builder): if not deepspeed.ops.__compatible_ops__.get(builder.NAME, False): pytest.skip("the CPU optimizer builder is not supported on this accelerator") @@ -67,43 +73,73 @@ def test_reflow_optimizer_rejects_direct_step(optimizer_type, builder): assert not optimizer.state -def test_every_builder_of_the_shared_bindings_compiles_the_reflow_kernels(): - """The Reflow entry points are bound in the shared cpu_adam.cpp / cpu_lion.cpp, so a builder that compiles those - without the Reflow implementation produces an extension that fails to import with an undefined reflow_* symbol. - The accelerator-specific builders import accelerator packages, so read their source lists instead of loading them. - """ +@pytest.mark.parametrize("builder", [ReflowCPUAdamBuilder, ReflowCPULionBuilder]) +def test_reflow_builder_rejects_non_avx_cpu(builder, monkeypatch): + # A compatible normal CPU optimizer must not imply that Reflow works on non-x86 hosts. + monkeypatch.setattr(builder, "simd_width", lambda self: "-D__SCALAR__") + assert not builder().is_compatible() + + +@pytest.mark.parametrize("builder", [ReflowCPUAdamBuilder, ReflowCPULionBuilder]) +def test_reflow_builder_falls_back_to_avx2_when_avx512_is_incomplete(builder, monkeypatch): + from deepspeed.ops.op_builder.cpu.builder import CPUOpBuilder + + monkeypatch.setattr(CPUOpBuilder, "simd_width", lambda self: "-D__AVX512__") + monkeypatch.setattr(builder, "_cpu_flags", lambda self: {"avx2", "fma", "f16c", "avx512f"}) + assert builder().simd_width() == "-D__AVX256__" + assert builder().is_compatible() + + +@pytest.mark.parametrize("builder", [ReflowCPUAdamBuilder, ReflowCPULionBuilder]) +def test_reflow_builder_rejects_missing_fma(builder, monkeypatch): + from deepspeed.ops.op_builder.cpu.builder import CPUOpBuilder + + monkeypatch.setattr(CPUOpBuilder, "simd_width", lambda self: "-D__AVX256__") + monkeypatch.setattr(builder, "_cpu_flags", lambda self: {"avx2", "f16c"}) + assert not builder().is_compatible() + + +@pytest.mark.parametrize("builder", [ReflowCPUAdamBuilder, ReflowCPULionBuilder]) +def test_reflow_builder_rejects_unvalidated_accelerator(builder, monkeypatch): + from types import SimpleNamespace + import accelerator + + monkeypatch.setattr(accelerator, "get_accelerator", lambda: SimpleNamespace(_name="npu")) + assert not builder().is_compatible() + + +@pytest.mark.parametrize("normal, reflow, symbol", [ + (CPUAdamBuilder, ReflowCPUAdamBuilder, "reflow_create_adam"), + (CPULionBuilder, ReflowCPULionBuilder, "reflow_create_lion"), +]) +def test_reflow_extension_is_independent(normal, reflow, symbol): + if not reflow().is_compatible() or not normal().is_compatible(): + pytest.skip("requires compatible CPU optimizers") + normal_module = normal().load() + reflow_module = reflow().load() + assert not hasattr(normal_module, symbol) + assert hasattr(reflow_module, symbol) + assert normal_module is not reflow_module + + +def test_standard_cpu_optimizer_builders_do_not_include_reflow(): import ast import pathlib - import op_builder - bindings = { - "csrc/adam/cpu_adam.cpp": "csrc/adam/reflow_cpu_adam_impl.cpp", - "csrc/lion/cpu_lion.cpp": "csrc/lion/reflow_cpu_lion_impl.cpp", - } - missing = [] - checked = 0 - for path in sorted(pathlib.Path(op_builder.__file__).parent.rglob("*.py")): - sources = [] - for node in ast.walk(ast.parse(path.read_text())): - if isinstance(node, ast.FunctionDef) and node.name == "sources": - sources += [ - sub.value for sub in ast.walk(node) - if isinstance(sub, ast.Constant) and isinstance(sub.value, str) - ] - for binding, reflow_impl in bindings.items(): - if binding in sources: - checked += 1 - reflow_bindings = reflow_impl.replace("_impl.cpp", "_bindings.cpp") - for required in (reflow_impl, reflow_bindings): - if required not in sources: - missing.append(f"{path.name} compiles {binding} without {required}") - assert checked > 0, "no builder compiles the shared bindings; the paths above are stale" - assert not missing, missing - - -@pytest.mark.skipif(not deepspeed.ops.__compatible_ops__[CPUAdamBuilder.NAME], - reason="CPUAdamBuilder is not compatible on this system.") + for path in pathlib.Path(op_builder.__file__).parent.rglob("*.py"): + if path.name not in ("cpu_adam.py", "cpu_lion.py"): + continue + source = ast.parse(path.read_text()) + reflow_sources = [ + node.value for node in ast.walk(source) if isinstance(node, ast.Constant) and isinstance(node.value, str) + and "csrc/" in node.value and "reflow_" in node.value + ] + assert not reflow_sources, f"{path} includes Reflow: {reflow_sources}" + + +@pytest.mark.skipif(not deepspeed.ops.__compatible_ops__.get(ReflowCPUAdamBuilder.NAME, False), + reason="ReflowCPUAdamBuilder is not compatible on this system.") @pytest.mark.parametrize('model_size', [22, 128, 1000, 1024, 4096]) @pytest.mark.parametrize('grad_dtype', [torch.bfloat16, torch.half], ids=["bf16grad", "fp16grad"]) @pytest.mark.parametrize('adamw_mode, weight_decay', [(True, 0.0), (True, 0.01), (False, 0.01)], @@ -116,7 +152,7 @@ class TestReflowCPUAdamDropIn: def test_two_phase_step_matches_base(self, model_size, grad_dtype, adamw_mode, weight_decay): from deepspeed.ops.adam import DeepSpeedCPUAdam _skip_amd_fp16(grad_dtype) - _skip_without_avx(CPUAdamBuilder) + _skip_without_avx(ReflowCPUAdamBuilder) lr, b1, b2, eps = self.LR, self.BETA1, self.BETA2, self.EPS torch.manual_seed(1234 + model_size) param_fp32 = torch.randn(model_size, dtype=torch.float) @@ -132,7 +168,7 @@ def test_two_phase_step_matches_base(self, model_size, grad_dtype, adamw_mode, w weight_decay=weight_decay, adamw_mode=adamw_mode) - module = CPUAdamBuilder().load() + module = ReflowCPUAdamBuilder().load() opt_id = _next_opt_id() module.reflow_create_adam(opt_id, lr, b1, b2, eps, weight_decay, adamw_mode, False, -1) # Several steps, so bias correction and non-zero moments are exercised. @@ -175,8 +211,8 @@ def _base_lion_step(param_fp32, exp_avg, grad_fp32, lr, beta1, beta2, weight_dec return p.data.detach().clone(), opt.state[p]['exp_avg'].detach().clone() -@pytest.mark.skipif(not deepspeed.ops.__compatible_ops__[CPULionBuilder.NAME], - reason="CPULionBuilder is not compatible on this system.") +@pytest.mark.skipif(not deepspeed.ops.__compatible_ops__.get(ReflowCPULionBuilder.NAME, False), + reason="ReflowCPULionBuilder is not compatible on this system.") @pytest.mark.parametrize('model_size', [22, 128, 1000, 1024, 4096]) @pytest.mark.parametrize('grad_dtype', [torch.bfloat16, torch.half], ids=["bf16grad", "fp16grad"]) @pytest.mark.parametrize('weight_decay', [0.0, 0.01], ids=["wd0", "wd0.01"]) @@ -193,14 +229,14 @@ def _inputs(self, model_size, grad_dtype): def test_phase2_halfgrad_matches_base(self, model_size, grad_dtype, weight_decay): _skip_amd_fp16(grad_dtype) - _skip_without_avx(CPULionBuilder) + _skip_without_avx(ReflowCPULionBuilder) lr, b1, b2 = self.LR, self.BETA1, self.BETA2 param_fp32, exp_avg, grad_half = self._inputs(model_size, grad_dtype) # The reflow kernel promotes the half grad to FP32 exactly, so the base reference gets the same # promoted gradient. param_ref, exp_avg_ref = _base_lion_step(param_fp32, exp_avg, grad_half.float(), lr, b1, b2, weight_decay) - module = CPULionBuilder().load() + module = ReflowCPULionBuilder().load() opt_id = _next_opt_id() module.reflow_create_lion(opt_id, lr, b1, b2, weight_decay, False, -1) module.reflow_lion_update_state_halfgrad(opt_id, 1, lr, b1, b2, weight_decay, param_fp32, grad_half, exp_avg, @@ -213,7 +249,7 @@ def test_phase2_halfgrad_matches_base(self, model_size, grad_dtype, weight_decay def test_phase1_produces_bf16_and_defers(self, model_size, grad_dtype, weight_decay): _skip_amd_fp16(grad_dtype) - _skip_without_avx(CPULionBuilder) + _skip_without_avx(ReflowCPULionBuilder) lr, b1, b2 = self.LR, self.BETA1, self.BETA2 param_fp32, exp_avg, grad_half = self._inputs(model_size, grad_dtype) param_before = param_fp32.clone() @@ -222,7 +258,7 @@ def test_phase1_produces_bf16_and_defers(self, model_size, grad_dtype, weight_de param_ref, _ = _base_lion_step(param_fp32, exp_avg, grad_half.float(), lr, b1, b2, weight_decay) half_params = torch.zeros(model_size, dtype=grad_dtype) - module = CPULionBuilder().load() + module = ReflowCPULionBuilder().load() opt_id = _next_opt_id() module.reflow_create_lion(opt_id, lr, b1, b2, weight_decay, False, -1) module.reflow_lion_update_params_halfgrad(opt_id, 1, lr, b1, b2, weight_decay, param_fp32, grad_half, exp_avg, @@ -248,8 +284,8 @@ def test_reused_kernel_threads_follow_the_worker_cpu_mask(optimizer_kind): cpus = sorted(os.sched_getaffinity(0)) if len(cpus) < 4: pytest.skip("requires four available CPUs") - builder = CPUAdamBuilder if optimizer_kind == "adam" else CPULionBuilder - if not deepspeed.ops.__compatible_ops__[builder.NAME]: + builder = ReflowCPUAdamBuilder if optimizer_kind == "adam" else ReflowCPULionBuilder + if not deepspeed.ops.__compatible_ops__.get(builder.NAME, False): pytest.skip("CPU optimizer builder is not compatible") _skip_without_avx(builder) module = builder().load() @@ -303,11 +339,11 @@ def test_accumulation_matches_addition_on_restricted_worker_cpus(dtype, size): if not hasattr(os, "sched_getaffinity"): pytest.skip("requires Linux thread affinity") - if not deepspeed.ops.__compatible_ops__[CPUAdamBuilder.NAME]: - pytest.skip("CPUAdamBuilder is not compatible") - _skip_without_avx(CPUAdamBuilder) + if not deepspeed.ops.__compatible_ops__.get(ReflowCPUAdamBuilder.NAME, False): + pytest.skip("ReflowCPUAdamBuilder is not compatible") + _skip_without_avx(ReflowCPUAdamBuilder) _skip_amd_fp16(dtype) - module = CPUAdamBuilder().load() + module = ReflowCPUAdamBuilder().load() cpus = sorted(os.sched_getaffinity(0)) generator = torch.Generator().manual_seed(1234) dst = torch.randn(size, generator=generator).to(dtype) @@ -326,13 +362,13 @@ def accumulate(): @pytest.mark.parametrize('adamw_mode', [False, True], ids=['adam', 'adamw']) @pytest.mark.parametrize('model_size', [7, 129, 4099]) -@pytest.mark.parametrize('combined_scale', [1.0, 8.0]) +@pytest.mark.parametrize('combined_scale', [0.5, 1.0, 2.0, 8.0]) def test_adam_maximize_groups_match_pytorch(adamw_mode, model_size, combined_scale): # Catch dropped per-group directions, incorrect decay, scalar-tail omissions, and a # deferred commit that reads changed live flags instead of the submitted step's snapshot. - if not deepspeed.ops.__compatible_ops__[CPUAdamBuilder.NAME]: - pytest.skip('CPUAdamBuilder is not compatible') - _skip_without_avx(CPUAdamBuilder) + if not deepspeed.ops.__compatible_ops__.get(ReflowCPUAdamBuilder.NAME, False): + pytest.skip('ReflowCPUAdamBuilder is not compatible') + _skip_without_avx(ReflowCPUAdamBuilder) generator = torch.Generator().manual_seed(4321) params = [torch.nn.Parameter(torch.randn(model_size, generator=generator)) for _ in range(2)] references = [torch.nn.Parameter(p.detach().clone()) for p in params] @@ -398,3 +434,70 @@ def test_adam_maximize_groups_match_pytorch(adamw_mode, model_size, combined_sca torch.testing.assert_close(p, references[i], rtol=2e-6, atol=2e-7) torch.testing.assert_close(state['exp_avg'], expected['exp_avg'], rtol=2e-6, atol=2e-7) torch.testing.assert_close(state['exp_avg_sq'], expected['exp_avg_sq'], rtol=2e-6, atol=2e-7) + + +@pytest.mark.parametrize("optimizer_kind", ["adam", "lion"]) +@pytest.mark.parametrize("gradient_dtype", [torch.float16, torch.bfloat16], ids=["fp16", "bf16"]) +@pytest.mark.parametrize("combined_scale", [0.5, 1.0, 2.0]) +@pytest.mark.parametrize("model_size", [7, 129]) +def test_two_phase_updates_unscale_below_and_above_one(optimizer_kind, gradient_dtype, combined_scale, model_size): + """The vector prefix and scalar tail must apply the same loss scale in both phases.""" + _skip_amd_fp16(gradient_dtype) + builder = ReflowCPUAdamBuilder if optimizer_kind == "adam" else ReflowCPULionBuilder + if not builder().is_compatible(): + pytest.skip("Reflow CPU optimizer is not compatible") + from deepspeed.ops.adam import DeepSpeedCPUAdam + from deepspeed.ops.lion import DeepSpeedCPULion + + lr, beta1, beta2, weight_decay = 0.01, 0.5, 0.9, 0.01 + master = torch.linspace(-0.5, 0.5, model_size) + momentum = torch.full_like(master, -0.3) + gradient = torch.full((model_size, ), 0.25, dtype=gradient_dtype) + original_master = master.clone() + original_momentum = momentum.clone() + reference_param = torch.nn.Parameter(master.clone()) + if optimizer_kind == "adam": + reference = DeepSpeedCPUAdam([reference_param], + lr=lr, + betas=(beta1, beta2), + eps=1e-8, + weight_decay=weight_decay, + adamw_mode=True) + variance = torch.full_like(master, 0.2) + original_variance = variance.clone() + reference.state[reference_param].update(step=0, exp_avg=momentum.clone(), exp_avg_sq=variance.clone()) + else: + reference = DeepSpeedCPULion([reference_param], lr=lr, betas=(beta1, beta2), weight_decay=weight_decay) + reference.state[reference_param].update(step=0, exp_avg=momentum.clone()) + reference_param.grad = gradient.float() / combined_scale + reference.step() + reference_state = reference.state[reference_param] + + module = builder().load() + optimizer_id = _next_opt_id() + output = torch.empty(model_size, dtype=gradient_dtype) + if optimizer_kind == "adam": + module.reflow_create_adam(optimizer_id, lr, beta1, beta2, 1e-8, weight_decay, True, False, 1) + common = [optimizer_id, 1, lr, beta1, beta2, 1e-8, weight_decay, True, master, gradient, momentum, variance] + else: + module.reflow_create_lion(optimizer_id, lr, beta1, beta2, weight_decay, False, 1) + common = [optimizer_id, 1, lr, beta1, beta2, weight_decay, master, gradient, momentum] + try: + ready = getattr(module, f"reflow_{optimizer_kind}_update_params_halfgrad") + persist = getattr(module, f"reflow_{optimizer_kind}_update_state_halfgrad") + ready(*common, output, combined_scale, False) + module_fence = getattr(module, f"reflow_{optimizer_kind}_memory_fence") + module_fence() + assert torch.equal(output, reference_param.detach().to(gradient_dtype)) + assert torch.equal(master, original_master) + assert torch.equal(momentum, original_momentum) + if optimizer_kind == "adam": + assert torch.equal(variance, original_variance) + persist(*common, combined_scale, False) + module_fence() + torch.testing.assert_close(master, reference_param.detach(), rtol=1e-6, atol=1e-7) + torch.testing.assert_close(momentum, reference_state["exp_avg"], rtol=1e-6, atol=1e-7) + if optimizer_kind == "adam": + torch.testing.assert_close(variance, reference_state["exp_avg_sq"], rtol=1e-6, atol=1e-7) + finally: + getattr(module, f"reflow_destroy_{optimizer_kind}")(optimizer_id) diff --git a/tests/unit/v1/zero/test_reflow.py b/tests/unit/v1/zero/test_reflow.py index 4518178e4f66..d61cf7157d91 100644 --- a/tests/unit/v1/zero/test_reflow.py +++ b/tests/unit/v1/zero/test_reflow.py @@ -23,6 +23,8 @@ from deepspeed.ops.adam import DeepSpeedCPUAdam from deepspeed.ops.lion import DeepSpeedCPULion from deepspeed.ops.op_builder import CPUAdamBuilder, CPULionBuilder +from deepspeed.ops.op_builder.cpu.reflow_cpu_adam import ReflowCPUAdamBuilder +from deepspeed.ops.op_builder.cpu.reflow_cpu_lion import ReflowCPULionBuilder from deepspeed.runtime.config import DeepSpeedConfig from deepspeed.runtime.reflow.reflow_cpu_adam import ReflowCPUAdam from deepspeed.runtime.reflow.reflow_cpu_lion import ReflowCPULion @@ -270,8 +272,8 @@ def test_heuristic_numa_split_with_uneven_rank_count(): def skip_if_reflow_training_unsupported(): - if not deepspeed.ops.__compatible_ops__[CPUAdamBuilder.NAME]: - pytest.skip("CPUAdamBuilder is not compatible on this system.") + if not deepspeed.ops.__compatible_ops__.get(ReflowCPUAdamBuilder.NAME, False): + pytest.skip("ReflowCPUAdamBuilder is not compatible on this system.") if not get_accelerator().is_bf16_supported(): pytest.skip("bf16 is not supported on this accelerator.") @@ -496,6 +498,53 @@ def run(reflow): assert torch.equal(got, want), f"fp32 param {index} differs" +@pytest.mark.parametrize("optimizer_kind", ["adam", "lion"]) +@needs_gpu_accelerator +class TestReflowSmallLossScaleMatchesZeroOffload(DistributedTest): + world_size = [1, 2] + + def test_fp16_training_matches_zero_offload(self, optimizer_kind): + skip_if_reflow_training_unsupported() + torch.manual_seed(1234) + initial_model = SimpleModel(hidden_dim=16, nlayers=2) + batches = make_batches(16, count=4, dtype=torch.float16) + + def run(reflow): + model = copy.deepcopy(initial_model) + config = get_variant_config(reflow, optimizer_kind) + config["bf16"] = {"enabled": False} + config["fp16"] = {"enabled": True, "loss_scale": 0.5} + engine, optimizer, _, _ = deepspeed.initialize(model=model, + model_parameters=model.parameters(), + config=config) + try: + assert optimizer.loss_scale == 0.5 + losses = [] + for batch in batches: + loss = engine(*batch) + engine.backward(loss) + engine.step() + losses.append(loss.detach().clone()) + params = [safe_get_full_fp32_param(param).clone() for param in engine.module.parameters()] + moments = [ + safe_get_full_optimizer_state(param, "exp_avg").clone() for param in engine.module.parameters() + ] + variances = ([ + safe_get_full_optimizer_state(param, "exp_avg_sq").clone() for param in engine.module.parameters() + ] if optimizer_kind == "adam" else []) + return losses, params, moments, variances, engine.skipped_steps, type(optimizer.optimizer) + finally: + engine.destroy() + + expected = run(False) + actual = run(True) + assert issubclass(actual[-1], ReflowCPUAdam if optimizer_kind == "adam" else ReflowCPULion) + assert expected[-2] == actual[-2] == 0 + for expected_group, actual_group in zip(expected[:4], actual[:4]): + for want, got in zip(expected_group, actual_group): + assert torch.equal(got, want) + + @pytest.mark.parametrize("optimizer_kind", ["adam", "lion"]) @needs_gpu_accelerator class TestReflowMultipleOptimizerGroupsMatchZeroOffload(DistributedTest): @@ -504,7 +553,7 @@ class TestReflowMultipleOptimizerGroupsMatchZeroOffload(DistributedTest): def test_group_hyperparameters_stay_isolated(self, optimizer_kind): # Large groups keep bucket workers active long enough to overlap across optimizer groups. skip_if_reflow_training_unsupported() - if optimizer_kind == "lion" and not deepspeed.ops.__compatible_ops__[CPULionBuilder.NAME]: + if optimizer_kind == "lion" and not deepspeed.ops.__compatible_ops__.get(ReflowCPULionBuilder.NAME, False): pytest.skip("CPULionBuilder is not compatible on this system.") hidden_dim = 2049 @@ -738,8 +787,8 @@ def test_regular_optimizer_without_reflow_config(self): finally: engine.destroy() - @pytest.mark.parametrize("optimizer_type, builder", [(ReflowCPUAdam, CPUAdamBuilder), - (ReflowCPULion, CPULionBuilder)]) + @pytest.mark.parametrize("optimizer_type, builder", [(ReflowCPUAdam, ReflowCPUAdamBuilder), + (ReflowCPULion, ReflowCPULionBuilder)]) def test_rejects_reflow_optimizer_without_reflow_config(self, optimizer_type, builder): if not deepspeed.ops.__compatible_ops__.get(builder.NAME, False): pytest.skip("the CPU optimizer builder is not supported on this accelerator") @@ -769,6 +818,8 @@ def test_rejects_low_precision_client_states(self, optimizer_type): @pytest.mark.parametrize("precision", ["bf16", "fp16"]) def test_initializes_half_precision_zero_init_model(self, precision): + if precision == "fp16" and not get_accelerator().is_fp16_supported(): + pytest.skip("the accelerator does not support FP16") if not deepspeed.ops.__compatible_ops__.get(CPUAdamBuilder.NAME, False): pytest.skip("the CPU optimizer builder is not supported on this accelerator") config = get_variant_config(reflow=True, variant="offload_param") @@ -787,11 +838,14 @@ def test_initializes_half_precision_zero_init_model(self, precision): engine.destroy() @pytest.mark.parametrize("dtype", [torch.float32]) - def test_rejects_zero_init_model_with_unsupported_dtype(self, dtype): + @pytest.mark.parametrize("fp16_supported", [False, True]) + def test_rejects_zero_init_model_with_unsupported_dtype(self, dtype, fp16_supported): # zero.Init bypasses the engine's model cast, so its actual parameters must still be half precision. config = get_variant_config(reflow=True, variant="offload_param") - with deepspeed.zero.Init(config_dict_or_path=config, dtype=dtype): - model = SimpleModel(hidden_dim=16, nlayers=2) + with patch.object(get_accelerator(), "is_fp16_supported", return_value=fp16_supported): + with deepspeed.zero.Init(config_dict_or_path=config, dtype=dtype): + model = SimpleModel(hidden_dim=16, nlayers=2) + assert all(param.dtype == dtype for param in model.parameters()) with pytest.raises(ValueError, match="requires FP16 or BF16 model parameters"): deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) From 96cb85f14ae71a22aac05b5d7010f8699f86ab98 Mon Sep 17 00:00:00 2001 From: st-bang97 Date: Thu, 19 Nov 2026 13:38:53 +0900 Subject: [PATCH 10/19] Fix ReFlow CPU compatibility checks Signed-off-by: st-bang97 --- op_builder/cpu/reflow.py | 14 +++++----- .../unit/v1/ops/test_reflow_cpu_optimizers.py | 20 ++++++++++++++ tests/unit/v1/zero/test_reflow.py | 27 ++++++++++++------- 3 files changed, 45 insertions(+), 16 deletions(-) diff --git a/op_builder/cpu/reflow.py b/op_builder/cpu/reflow.py index e83bd4ce42fb..ac3217f293d0 100644 --- a/op_builder/cpu/reflow.py +++ b/op_builder/cpu/reflow.py @@ -3,17 +3,19 @@ from .builder import CPUOpBuilder +try: + from op_builder import __deepspeed__ # noqa: F401 # type: ignore + from op_builder.builder import _cpu_info +except ImportError: + from deepspeed.ops.op_builder.builder import _cpu_info + class ReflowCPUOp(CPUOpBuilder): """Host kernels are currently validated only on x86 CPU and CUDA configurations.""" def _cpu_flags(self): - try: - from cpuinfo import get_cpu_info - cpu_info = get_cpu_info() - except Exception: - cpu_info = self._backup_cpuinfo() - return set(cpu_info.get('flags', [])) if cpu_info else set() + _, flags = _cpu_info() + return flags def simd_width(self): width = super().simd_width() diff --git a/tests/unit/v1/ops/test_reflow_cpu_optimizers.py b/tests/unit/v1/ops/test_reflow_cpu_optimizers.py index f29c5183ab8c..eb0d78d5ae01 100644 --- a/tests/unit/v1/ops/test_reflow_cpu_optimizers.py +++ b/tests/unit/v1/ops/test_reflow_cpu_optimizers.py @@ -73,6 +73,26 @@ def test_reflow_optimizer_rejects_direct_step(optimizer_type, builder): assert not optimizer.state +@pytest.mark.parametrize("builder", [ReflowCPUAdamBuilder, ReflowCPULionBuilder]) +def test_reflow_builder_uses_shared_cpu_info_fallback(builder, monkeypatch): + import importlib + import cpuinfo + from deepspeed.ops.op_builder.cpu import reflow + + cpu_info_module = importlib.import_module(reflow._cpu_info.__module__) + + def unavailable_cpuinfo(): + raise RuntimeError("CPU information unavailable") + + monkeypatch.setattr(cpuinfo, "get_cpu_info", unavailable_cpuinfo) + monkeypatch.setattr(cpu_info_module, "_lscpu_cpu_info", lambda: ("X86_64", frozenset({"avx2", "fma", "f16c"}))) + reflow._cpu_info.cache_clear() + try: + assert builder()._cpu_flags() == {"avx2", "fma", "f16c"} + finally: + reflow._cpu_info.cache_clear() + + @pytest.mark.parametrize("builder", [ReflowCPUAdamBuilder, ReflowCPULionBuilder]) def test_reflow_builder_rejects_non_avx_cpu(builder, monkeypatch): # A compatible normal CPU optimizer must not imply that Reflow works on non-x86 hosts. diff --git a/tests/unit/v1/zero/test_reflow.py b/tests/unit/v1/zero/test_reflow.py index d61cf7157d91..92580c3c15ab 100644 --- a/tests/unit/v1/zero/test_reflow.py +++ b/tests/unit/v1/zero/test_reflow.py @@ -271,13 +271,22 @@ def test_heuristic_numa_split_with_uneven_rank_count(): reason="Reflow training tests need a GPU accelerator.") -def skip_if_reflow_training_unsupported(): - if not deepspeed.ops.__compatible_ops__.get(ReflowCPUAdamBuilder.NAME, False): - pytest.skip("ReflowCPUAdamBuilder is not compatible on this system.") +def skip_if_reflow_training_unsupported(optimizer_kind="adam"): + builder = ReflowCPULionBuilder if optimizer_kind == "lion" else ReflowCPUAdamBuilder + if not deepspeed.ops.__compatible_ops__.get(builder.NAME, False): + pytest.skip(f"{builder.__name__} is not compatible on this system.") if not get_accelerator().is_bf16_supported(): pytest.skip("bf16 is not supported on this accelerator.") +@pytest.mark.parametrize("optimizer_kind", ["adam", "lion"]) +def test_training_compatibility_checks_selected_reflow_builder(optimizer_kind, monkeypatch): + monkeypatch.setitem(deepspeed.ops.__compatible_ops__, ReflowCPUAdamBuilder.NAME, optimizer_kind == "lion") + monkeypatch.setitem(deepspeed.ops.__compatible_ops__, ReflowCPULionBuilder.NAME, optimizer_kind == "adam") + with pytest.raises(pytest.skip.Exception): + skip_if_reflow_training_unsupported(optimizer_kind) + + def make_batches(hidden_dim, count, dtype=torch.bfloat16): device = get_accelerator().current_device_name() batches = [] @@ -466,7 +475,7 @@ class TestReflowVariantsMatchZeroOffload(DistributedTest): world_size = [1, 2] def test_matches_zero_offload(self, variant, precision): - skip_if_reflow_training_unsupported() + skip_if_reflow_training_unsupported(variant) hidden_dim = 16 dtype = torch.float16 if precision == "fp16" else torch.bfloat16 num_steps = 4 @@ -504,7 +513,7 @@ class TestReflowSmallLossScaleMatchesZeroOffload(DistributedTest): world_size = [1, 2] def test_fp16_training_matches_zero_offload(self, optimizer_kind): - skip_if_reflow_training_unsupported() + skip_if_reflow_training_unsupported(optimizer_kind) torch.manual_seed(1234) initial_model = SimpleModel(hidden_dim=16, nlayers=2) batches = make_batches(16, count=4, dtype=torch.float16) @@ -552,9 +561,7 @@ class TestReflowMultipleOptimizerGroupsMatchZeroOffload(DistributedTest): def test_group_hyperparameters_stay_isolated(self, optimizer_kind): # Large groups keep bucket workers active long enough to overlap across optimizer groups. - skip_if_reflow_training_unsupported() - if optimizer_kind == "lion" and not deepspeed.ops.__compatible_ops__.get(ReflowCPULionBuilder.NAME, False): - pytest.skip("CPULionBuilder is not compatible on this system.") + skip_if_reflow_training_unsupported(optimizer_kind) hidden_dim = 2049 torch.manual_seed(1234) @@ -820,8 +827,8 @@ def test_rejects_low_precision_client_states(self, optimizer_type): def test_initializes_half_precision_zero_init_model(self, precision): if precision == "fp16" and not get_accelerator().is_fp16_supported(): pytest.skip("the accelerator does not support FP16") - if not deepspeed.ops.__compatible_ops__.get(CPUAdamBuilder.NAME, False): - pytest.skip("the CPU optimizer builder is not supported on this accelerator") + if not deepspeed.ops.__compatible_ops__.get(ReflowCPUAdamBuilder.NAME, False): + pytest.skip("the ReFlow CPU Adam builder is not supported on this accelerator") config = get_variant_config(reflow=True, variant="offload_param") dtype = torch.float16 if precision == "fp16" else torch.bfloat16 if precision == "fp16": From 392e3ee1d98833879999945e8d2a2cfced1a2e26 Mon Sep 17 00:00:00 2001 From: st-bang97 Date: Fri, 20 Nov 2026 12:43:26 +0900 Subject: [PATCH 11/19] Fix ReFlow gradient buffer cleanup and overflow restore Signed-off-by: st-bang97 --- deepspeed/runtime/reflow/reflow_stage3.py | 18 +++- tests/unit/v1/zero/test_reflow.py | 111 +++++++++++++++++++++- 2 files changed, 123 insertions(+), 6 deletions(-) diff --git a/deepspeed/runtime/reflow/reflow_stage3.py b/deepspeed/runtime/reflow/reflow_stage3.py index 6fab28aec8ad..5645d3a5b088 100644 --- a/deepspeed/runtime/reflow/reflow_stage3.py +++ b/deepspeed/runtime/reflow/reflow_stage3.py @@ -346,6 +346,8 @@ def _setup_for_real_optimizer(self): # parent setup unconditionally allocates it, so free it (and its pinned backing) to # reclaim ~2 bytes/param of CPU memory in the bucketwise case. super()._setup_for_real_optimizer() + grad_buffers = self.grad_partitions_flat_buffers + self.grad_partitions_flat_buffers = {} self.grad_partitions_flat_buffer = None # GPU-side inf/nan accumulator for the offloaded grads, since the flat buffer that the base # has_overflow scans is freed above (lazily created on the grad device in partition_grads). @@ -353,7 +355,14 @@ def _setup_for_real_optimizer(self): # Clear the name-mangled __param_id_to_grad_partition dict so the narrow() views into # the buffer freed above are dropped and its storage can actually be reclaimed. self._DeepSpeedZeroOptimizer_Stage3__param_id_to_grad_partition = {} - # The parent pins grad_partitions_flat_buffer, so dropping the references above only returns + # Native pinning requires an explicit release; remove the parent's references first so + # its destroy path cannot release these allocations a second time. + while grad_buffers: + _, grad_buffer = grad_buffers.popitem() + if self.offload_optimizer_pin_memory: + get_accelerator().unpin_memory(grad_buffer) + del grad_buffer + # When the parent pins these buffers, dropping the references above only returns # the block to torch's pinned-host caching allocator, which keeps the physical memory resident # (the one large block is never reused by the smaller per-subgroup bucketwise buffers). Empty # the host cache so the ~2 bytes/param of pinned memory is actually returned to the OS. @@ -1611,7 +1620,12 @@ def _restore_fp16_params_from_master(self, sub_group_id): # pre-step weight. The FP32 master lives on nvme (swapped out), so there is nothing to # copy from here -- the discarded step leaves both the param and the state untouched. return - fp16_flat.data.copy_(fp32_flat.data) + dst = fp16_flat.data + src = fp32_flat.data + if dst.device.type != "cpu" and self._master_pinned_at_construction(sub_group_id): + self._copy_pinned_master_to_device(dst, src) + else: + dst.copy_(src) self._unflatten_partitioned_parameters(sub_group_id) @instrument_w_nvtx diff --git a/tests/unit/v1/zero/test_reflow.py b/tests/unit/v1/zero/test_reflow.py index 92580c3c15ab..c508394c9635 100644 --- a/tests/unit/v1/zero/test_reflow.py +++ b/tests/unit/v1/zero/test_reflow.py @@ -10,8 +10,10 @@ import copy import os import threading +import weakref from concurrent.futures import ThreadPoolExecutor -from unittest.mock import patch +from unittest.mock import Mock, patch +from types import SimpleNamespace import pytest import torch @@ -28,7 +30,9 @@ from deepspeed.runtime.config import DeepSpeedConfig from deepspeed.runtime.reflow.reflow_cpu_adam import ReflowCPUAdam from deepspeed.runtime.reflow.reflow_cpu_lion import ReflowCPULion +from deepspeed.runtime.reflow.reflow_stage3 import ReflowOptimizer_Stage3 from deepspeed.runtime.reflow import reflow_utils +from deepspeed.runtime.zero.stage3 import DeepSpeedZeroOptimizer_Stage3 from deepspeed.runtime.zero.muon.muon_optimizer import MuonWithAuxAdam from deepspeed.runtime.zero.utils import ZeRORuntimeException from deepspeed.utils import safe_get_full_fp32_param, safe_get_full_optimizer_state @@ -857,6 +861,93 @@ def test_rejects_zero_init_model_with_unsupported_dtype(self, dtype, fp16_suppor deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) +def test_reflow_releases_every_parent_gradient_dtype(): + optimizer = object.__new__(ReflowOptimizer_Stage3) + optimizer.offload_optimizer_pin_memory = True + references = [] + released = [] + + def create_parent_buffers(parent): + buffers = {dtype: torch.zeros(4, dtype=dtype) for dtype in (torch.float16, torch.float32)} + references.extend(weakref.ref(buffer) for buffer in buffers.values()) + parent.grad_partitions_flat_buffers = buffers + parent.grad_partitions_flat_buffer = buffers[torch.float16] + parent._DeepSpeedZeroOptimizer_Stage3__param_id_to_grad_partition = { + i: buffer.narrow(0, 0, 2) + for i, buffer in enumerate(buffers.values()) + } + + accelerator = SimpleNamespace(unpin_memory=lambda buffer: released.append(id(buffer))) + with patch.object(DeepSpeedZeroOptimizer_Stage3, "_setup_for_real_optimizer", create_parent_buffers), \ + patch("deepspeed.runtime.reflow.reflow_stage3.get_accelerator", return_value=accelerator): + optimizer._setup_for_real_optimizer() + assert len(released) == len(set(released)) == 2 + assert all(reference() is None for reference in references) + assert not optimizer.grad_partitions_flat_buffers + assert optimizer.grad_partitions_flat_buffer is None + assert not optimizer._DeepSpeedZeroOptimizer_Stage3__param_id_to_grad_partition + + +@pytest.mark.parametrize("nvme_parameter", [False, True]) +def test_reflow_overflow_keeps_nvme_restore_paths(nvme_parameter): + # NVMe parameters must be re-swapped from the unchanged master; swapped optimizer + # subgroups never published a preview and must not attempt a master copy. + optimizer = SimpleNamespace(fp16_partitioned_groups_flat=[None if nvme_parameter else torch.zeros(4)], + fp32_partitioned_groups_flat=[torch.ones(4)], + _partitioned_params_swap_out=Mock(), + _swappable_optimizer_subgroup=Mock(return_value=not nvme_parameter), + _copy_pinned_master_to_device=Mock(), + _unflatten_partitioned_parameters=Mock()) + ReflowOptimizer_Stage3._restore_fp16_params_from_master(optimizer, 0) + if nvme_parameter: + optimizer._partitioned_params_swap_out.assert_called_once_with(0) + else: + optimizer._partitioned_params_swap_out.assert_not_called() + optimizer._copy_pinned_master_to_device.assert_not_called() + optimizer._unflatten_partitioned_parameters.assert_not_called() + + +@needs_gpu_accelerator +class TestReflowReleasesParentGradientBuffers(DistributedTest): + world_size = 1 + + @pytest.mark.parametrize("pin_memory", [False, True]) + def test_releases_all_parent_gradient_buffers(self, pin_memory): + skip_if_reflow_training_unsupported() + original_setup = DeepSpeedZeroOptimizer_Stage3._setup_for_real_optimizer + accelerator = get_accelerator() + original_unpin = accelerator.unpin_memory + parent_buffers = [] + unpinned = [] + + def capture_parent_buffers(optimizer): + original_setup(optimizer) + parent_buffers.extend(weakref.ref(buffer) for buffer in optimizer.grad_partitions_flat_buffers.values()) + + def record_unpin(buffer): + if any(reference() is buffer for reference in parent_buffers): + unpinned.append(id(buffer)) + return original_unpin(buffer) + + config = get_variant_config(reflow=True, variant="adam") + config["zero_optimization"]["offload_optimizer"]["pin_memory"] = pin_memory + model = SimpleModel(hidden_dim=16, nlayers=2) + with patch.object(DeepSpeedZeroOptimizer_Stage3, "_setup_for_real_optimizer", capture_parent_buffers), \ + patch.object(accelerator, "unpin_memory", record_unpin): + engine, optimizer, _, _ = deepspeed.initialize(model=model, + model_parameters=model.parameters(), + config=config) + try: + assert parent_buffers + assert all(reference() is None for reference in parent_buffers) + assert not optimizer.grad_partitions_flat_buffers + assert optimizer.grad_partitions_flat_buffer is None + finally: + engine.destroy() + assert len(unpinned) == (len(parent_buffers) if pin_memory else 0) + assert len(set(unpinned)) == len(unpinned) + + @needs_gpu_accelerator class TestReflowRejectsUnsupportedClientOptimizer(DistributedTest): world_size = 1 @@ -1185,14 +1276,17 @@ def test_matches_minimizing_negative_loss(self, adamw_mode): @pytest.mark.parametrize("precision", ["bf16", "fp16"]) @pytest.mark.parametrize("invalid_value", [float("nan"), float("inf")]) +@pytest.mark.parametrize("pin_memory", [False, True]) +@pytest.mark.parametrize("offload_param", [False, True]) @needs_gpu_accelerator class TestReflowInvalidGradient(DistributedTest): world_size = [1, 2] - def test_invalid_step_preserves_parameters_and_state(self, precision, invalid_value): + def test_invalid_step_preserves_parameters_and_state(self, precision, invalid_value, pin_memory, offload_param): skip_if_reflow_training_unsupported() torch.manual_seed(1234) - config = get_variant_config(reflow=True, variant="adam") + config = get_variant_config(reflow=True, variant="offload_param" if offload_param else "adam") + config["zero_optimization"]["offload_optimizer"]["pin_memory"] = pin_memory config["zero_optimization"]["reduce_bucket_size"] = 1_000_000 if precision == "fp16": config["bf16"] = {"enabled": False} @@ -1208,16 +1302,25 @@ def test_invalid_step_preserves_parameters_and_state(self, precision, invalid_va before_params = [safe_get_full_fp32_param(p).clone() for p in engine.module.parameters()] before_states = [safe_get_full_optimizer_state(p, "exp_avg").clone() for p in engine.module.parameters()] before_steps = [int(state["step"]) for state in optimizer.optimizer.state.values()] + with deepspeed.zero.GatheredParameters(list(engine.module.parameters())): + before_low_precision = [p.detach().clone() for p in engine.module.parameters()] skipped_steps = engine.skipped_steps loss = engine(*batches[1]) if dist.get_rank() == 0: loss = loss * invalid_value engine.backward(loss) - engine.step() + with patch.object(optimizer, + "_copy_pinned_master_to_device", + wraps=optimizer._copy_pinned_master_to_device) as pinned_copy: + engine.step() + assert bool(pinned_copy.call_count) == (pin_memory and not offload_param) assert engine.skipped_steps == skipped_steps + 1 assert [int(state["step"]) for state in optimizer.optimizer.state.values()] == before_steps for param, before_param, before_state in zip(engine.module.parameters(), before_params, before_states): assert torch.equal(safe_get_full_fp32_param(param), before_param) assert torch.equal(safe_get_full_optimizer_state(param, "exp_avg"), before_state) + with deepspeed.zero.GatheredParameters(list(engine.module.parameters())): + for param, before_param in zip(engine.module.parameters(), before_low_precision): + assert torch.equal(param, before_param) finally: engine.destroy() From fd0e8655b0762b2372efd9b2bbccd645e4af4046 Mon Sep 17 00:00:00 2001 From: st-bang97 Date: Fri, 20 Nov 2026 12:44:08 +0900 Subject: [PATCH 12/19] Fix ReFlow gradient accumulation and norm handling Signed-off-by: st-bang97 --- csrc/includes/reflow_simd.h | 12 +- deepspeed/runtime/reflow/reflow_stage3.py | 190 ++++++++++++++-- tests/unit/v1/zero/test_reflow.py | 255 +++++++++++++++++++++- 3 files changed, 430 insertions(+), 27 deletions(-) diff --git a/csrc/includes/reflow_simd.h b/csrc/includes/reflow_simd.h index 6a88ae3158fd..baf931a541e9 100644 --- a/csrc/includes/reflow_simd.h +++ b/csrc/includes/reflow_simd.h @@ -147,7 +147,9 @@ inline typename std::enable_if_t && !std::is_same_v, void> reflow_simd_store_stream(T* dst, AVX_Data* src) -{ simd_store(dst, src); } +{ + simd_store(dst, src); +} #endif #if defined(__AVX512__) or defined(__AVX256__) @@ -168,7 +170,9 @@ template inline typename std::enable_if_t, void> reflow_simd_store( T* dst, AVX_Data* src) -{ simd_store(dst, src); } +{ + simd_store(dst, src); +} template inline typename std::enable_if_t, void> reflow_simd_load( AVX_Data* dst, @@ -184,5 +188,7 @@ template inline typename std::enable_if_t, void> reflow_simd_load( AVX_Data* dst, T* src) -{ simd_load(dst, src); } +{ + simd_load(dst, src); +} #endif diff --git a/deepspeed/runtime/reflow/reflow_stage3.py b/deepspeed/runtime/reflow/reflow_stage3.py index 5645d3a5b088..cb84f0e0a6ee 100644 --- a/deepspeed/runtime/reflow/reflow_stage3.py +++ b/deepspeed/runtime/reflow/reflow_stage3.py @@ -20,10 +20,11 @@ from deepspeed.runtime.swap_tensor.partitioned_param_swapper import PartitionedParamStatus from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum, OffloadStateTypeEnum from deepspeed.runtime.zero.partition_parameters import Parameter, Tensor +from deepspeed.runtime.zero.partitioned_param_coordinator import iter_params from deepspeed.runtime.zero.stage3 import DeepSpeedZeroOptimizer_Stage3, INIT_OPTIMIZER_TIMER from deepspeed.runtime.utils import (combine_grad_norm_groups, has_inf_or_nan, is_invalid_grad_norm, is_model_parallel_parameter, mask_nan_or_inf_with_val_inplace) -from deepspeed.utils import logger +from deepspeed.utils import logger, z3_leaf_module from deepspeed.utils.nvtx import instrument_w_nvtx _REFLOW_FLAT_GRAD_FREED_MSG = ("Reflow frees the flat grad buffer; {api} is not supported under reflow.") @@ -63,6 +64,10 @@ def __init__(self, module, init_optimizer, param_names, timers, ds_config, reflo self._cpu_grad_double_buffers = [] self._active_grad_buffer_idx = 0 self._pending_grad_ready = False + self._reflow_window_grad_ids = set() + self._reflow_boundary_grad_ids = set() + self._reflow_gradient_partitions = None + self._reflow_checkpoint_param_ids = set() self._last_state_update_future = None self._pending_state_updates_by_subgroup = {} self._state_commit_overlaps_forward = False @@ -74,6 +79,7 @@ def __init__(self, module, init_optimizer, param_names, timers, ds_config, reflo self._single_grad_buffer = os.getenv("REFLOW_SINGLE_GRAD_BUFFER", "0") == "1" super().__init__(module, init_optimizer, param_names, timers, ds_config, **kwargs) + self._track_checkpointed_parameters() self._warn_per_param_partition_groups() # FP16/BF16 grads go straight to the CPU optimizer, which promotes them to FP32 # internally, so the accumulation dtype stays half here. @@ -109,6 +115,22 @@ def _pending_grad_buffer_idx(self): # ------------------------------------------------------------------ # # __init__ helpers # ------------------------------------------------------------------ # + def _track_checkpointed_parameters(self): + # Reentrant checkpoint forwards run with gradients disabled. A later + # recomputation must read the original weights, even if an earlier + # checkpoint segment has already produced a gradient for the same param. + original_forward = self.parameter_offload.pre_sub_module_forward_function + self._reflow_original_pre_sub_module_forward = original_forward + + def track_forward(sub_module): + if not torch.is_grad_enabled(): + for param in iter_params(sub_module, recurse=z3_leaf_module(sub_module)): + if hasattr(param, "ds_id") and param.requires_grad: + self._reflow_checkpoint_param_ids.add(self.get_param_id(param)) + return original_forward(sub_module) + + self.parameter_offload.pre_sub_module_forward_function = track_forward + def _warn_per_param_partition_groups(self): # The grad-norm reduction follows the base per-subgroup process groups, but the rest of the Reflow pipeline # has only been validated with every subgroup partitioned over the data-parallel group. @@ -319,6 +341,10 @@ def destroy(self): if grad_buffer is not None and grad_buffer.device.type == 'cpu': get_accelerator().unpin_memory(grad_buffer) self._cpu_grad_double_buffers = [] + original_forward = getattr(self, "_reflow_original_pre_sub_module_forward", None) + if original_forward is not None: + self.parameter_offload.pre_sub_module_forward_function = original_forward + self._reflow_original_pre_sub_module_forward = None try: super().destroy() finally: @@ -596,7 +622,6 @@ def partition_grads(self, params_to_release: List[Parameter], grad_partitions: L # Cache loop-invariant values (avoid repeated getattr/property/C++ binding calls). is_boundary = self.is_gradient_accumulation_boundary() - micro_step_id = self.micro_step_id copy_grad_stream = self.copy_grad_stream current_stream = get_accelerator().current_stream() stream_needs_sync = copy_grad_stream != current_stream @@ -618,11 +643,31 @@ def partition_grads(self, params_to_release: List[Parameter], grad_partitions: L param_id = self.get_param_id(param) grad_position_entry = self.grad_position[param_id] sub_group_id, dest_offset, _ = grad_position_entry + first_grad = param_id not in self._reflow_window_grad_ids + self._reflow_window_grad_ids.add(param_id) + if is_boundary and param_id in self._reflow_boundary_grad_ids: + # A reentrant backward can submit a second gradient after Ready has + # started reading this range. Finish that use before replacing it. + self._bucketwise_drain_enq_executor() + clipped_range = self._bucketwise_clip_range_to_valid_partition(sub_group_id, dest_offset, + grad_partition.numel()) + pending_ranges = self._bucketwise_pending_ranges_by_group[sub_group_id] + if clipped_range in pending_ranges: + pending_ranges.remove(clipped_range) + self._bucketwise_pending_elems_by_group[sub_group_id] -= clipped_range[1] + else: + self._bucketwise_wait_inflight_updates() + for event in self._bucketwise_inflight_h2d_events: + if event is not None: + event.synchronize() if grad_partition.dtype != self.gradient_accumulation_dtype: converted_grad = grad_partition.to(self.gradient_accumulation_dtype) else: converted_grad = grad_partition + if self._reflow_checkpoint_param_ids and stream_needs_sync: + # Reentrant reductions can reuse their GPU source before the async copy finishes. + converted_grad = converted_grad.clone() # The base flat grad buffer that has_overflow normally scans is freed on this path, so # accumulate any inf/nan in the offloaded grads on the GPU here (no host sync); the flag # is folded into has_overflow to drive FP16 dynamic-loss-scaling. @@ -633,11 +678,11 @@ def partition_grads(self, params_to_release: List[Parameter], grad_partitions: L grad_numel = grad_buffer.numel() - if micro_step_id > 0: + if not first_grad: # Both slices must remain unchanged until the previous worker consumes them. self._wait_for_accum_gradient(param_id) - if micro_step_id == 0: # don't accumulate, first micro step + if first_grad: if self._single_grad_buffer: # Slot 0 is also what the previous step's state commit reads, so wait for that commit before # overwriting it. Usually a no-op: the commit finishes during the forward. @@ -715,7 +760,10 @@ def _accumulate_worker(_copy_event=copy_event, _dst_slice=dst_slice, _src_slice= # NVMe subgroups have no resident optimizer state during backward, so their CPU step waits for # step(); only mark the buffer ready. Other subgroups run the range during backward. self._pending_grad_ready = True - if not self._swappable_optimizer_subgroup(sub_group_id): + if param_id not in self._reflow_checkpoint_param_ids: + self._reflow_boundary_grad_ids.add(param_id) + if (param_id not in self._reflow_checkpoint_param_ids + and not self._swappable_optimizer_subgroup(sub_group_id)): self._bucketwise_schedule_enqueue_range(sub_group_id, dest_offset, grad_numel, @@ -734,6 +782,9 @@ def _accumulate_worker(_copy_event=copy_event, _dst_slice=dst_slice, _src_slice= def reset_cpu_buffers(self): super().reset_cpu_buffers() + self._reflow_window_grad_ids.clear() + self._reflow_boundary_grad_ids.clear() + self._reflow_checkpoint_param_ids.clear() self._pending_grad_ready = False # Reset per-iteration pending/inflight state. @@ -751,6 +802,39 @@ def reset_cpu_buffers(self): self._bucketwise_cancel_version = 0 self._bucketwise_worker_error = None + def zero_grad(self, set_to_none=True): + # An explicit zero_grad may discard a window after Ready has published a + # preview. Drain only on this uncommon path, then restore those weights. + window_ids = getattr(self, "_reflow_window_grad_ids", None) + if window_ids and not getattr(self, "_reflow_in_overflow_cleanup", False): + self._wait_for_accum_gradient() + self._wait_for_pending_state_updates() + self._bucketwise_drain_enq_executor() + self._bucketwise_cancel_inflight_updates() + self._bucketwise_wait_inflight_updates() + for event in self._bucketwise_inflight_h2d_events: + if event is not None: + event.synchronize() + self.copy_grad_stream.synchronize() + touched_groups = {self.grad_position[param_id][0] for param_id in self._reflow_boundary_grad_ids} + for sub_group_id in touched_groups: + self._restore_fp16_params_from_master(sub_group_id) + if self._reflow_grad_overflow is not None: + self._reflow_grad_overflow.zero_() + checkpoint_params = set(self._reflow_checkpoint_param_ids) + worker_error = self._bucketwise_worker_error + self.reset_cpu_buffers() + self._bucketwise_worker_error = worker_error + self._reflow_checkpoint_param_ids.update(checkpoint_params) + return super().zero_grad(set_to_none=set_to_none) + + def _overflow_clean_up(self, prev_scale): + self._reflow_in_overflow_cleanup = True + try: + return super()._overflow_clean_up(prev_scale) + finally: + self._reflow_in_overflow_cleanup = False + # ------------------------------------------------------------------ # # async state update workers # ------------------------------------------------------------------ # @@ -887,12 +971,50 @@ def _get_cpu_grad_buffer(self, sub_group_id, pending=False): index = self._pending_grad_buffer_idx if pending else self._active_grad_buffer_idx return buffers[index] - def _activate_pending_cpu_grads_if_ready(self): + def _complete_pending_gradient_window(self): + # The parent ZeRO-3 fills these partitions with zeros or copies their earlier + # micro-step gradients at the boundary. ReFlow owns the CPU buffers instead. + if self._reflow_gradient_partitions is None: + self._reflow_gradient_partitions = [] + for sub_group_id, group in enumerate(self.fp16_groups): + for param in group: + if not param.requires_grad: + continue + if param.partition_numel() * self._get_param_partition_rank(param) >= param.ds_numel: + continue + param_id = self.get_param_id(param) + position = self.grad_position.get(param_id) + if position is not None and position[2] > 0: + self._reflow_gradient_partitions.append((param_id, sub_group_id, position[1], position[2])) + if len(self._reflow_boundary_grad_ids) == len(self._reflow_gradient_partitions): + return False + for param_id, sub_group_id, offset, numel in self._reflow_gradient_partitions: + if param_id in self._reflow_boundary_grad_ids: + continue + grad_buffer = self._get_cpu_grad_buffer(sub_group_id, pending=True).narrow(0, offset, numel) + if param_id not in self._reflow_window_grad_ids: + if self._single_grad_buffer: + self._wait_for_pending_state_updates(sub_group_id=sub_group_id) + grad_buffer.zero_() + self.norm_for_param_grads[param_id] = 0.0 + else: + self._wait_for_accum_gradient(param_id) + grad_for_norm = grad_buffer.to(get_accelerator().current_device_name(), non_blocking=True) + self.norm_for_param_grads[param_id] = self._constant_buffered_norm2(grad_for_norm) + self._pending_grad_ready = True + if not self._swappable_optimizer_subgroup(sub_group_id): + self._bucketwise_schedule_enqueue_range(sub_group_id, offset, numel) + return True + + def _activate_pending_cpu_grads_if_ready(self, flush_completed_window=False): if not self._pending_grad_ready: return False # Gradient buffers are written directly by the bucketwise workers; drain them and flip # the active/pending double buffer. self._bucketwise_drain_enq_executor() + if flush_completed_window: + # Start Ready while the GPU computes norms for earlier-micro-step gradients. + self._bucketwise_flush_all_pending(force=True, use_pending_buffer=True, combined_scale=self.loss_scale) self._bucketwise_wait_inflight_updates() # Single-buffer mode has only slot 0: keep the active index pinned there (no flip). The # workers already wrote the params into fp16_flat, and Phase-2 reads the grads from slot 0. @@ -935,13 +1057,10 @@ def _bucketwise_schedule_enqueue_range(self, sub_group_id, dest_offset, num_elem self._bucketwise_enqueue_range(sub_group_id, dest_offset, num_elements, copy_event) def _bucketwise_get_valid_partition_element_count(self, sub_group_id: int) -> int: - """Return the number of real (non-padding) elements this rank must update.""" - partition_element_count = int(self.fp16_partitioned_groups_flat_numel[sub_group_id]) - padding_element_count = 0 - if sub_group_id < len(self.groups_padding): - padding_element_count = sum(self.groups_padding[sub_group_id]) - valid_partition_element_count = partition_element_count - padding_element_count - return max(valid_partition_element_count, 0) + """Return the flat-buffer bound, including padding between parameters.""" + # Per-parameter padding is interspersed in the flat subgroup, so subtracting + # its sum as if it were all at the end drops real elements near the end. + return int(self.fp16_partitioned_groups_flat_numel[sub_group_id]) def _bucketwise_clip_range_to_valid_partition(self, sub_group_id: int, dest_offset: int, num_elements: int): """Clamp a range to the valid partition; return None if it is entirely padding.""" @@ -1291,6 +1410,17 @@ def _bucketwise_commit_group_steps(self): if current_step < target_step: state['step'] = target_step + def _ensure_bucketwise_group_step(self, sub_group_id): + # A rank can own only padding for a subgroup, so no Ready range was + # submitted even though the optimizer must advance its step counter. + if sub_group_id in self._bucketwise_group_target_step: + return + param = self.fp32_partitioned_groups_flat[sub_group_id] + if param is None: + return + state = self.optimizer._ensure_param_state(param) + self._bucketwise_group_target_step[sub_group_id] = int(state.get('step', 0)) + 1 + def _bucketwise_wait_inflight_updates(self): # Wait for submitted bucketwise work (optimizer + H2D submit). H2D completion itself is # synchronized later via CUDA events. @@ -1338,6 +1468,7 @@ def _nvme_optimizer_step_subgroups(self, combined_scale, timer_names): # all-gather waits for this subgroup's updated GPU param (written on the h2d # stream) -- otherwise the forward races the in-flight copy and reads stale params. self._drain_update_futures_collecting_h2d_events([future]) + self._ensure_bucketwise_group_step(sub_group_id) # Commit the step counter into optimizer.state BEFORE the state update. step_state_halfgrad # reads state['step'] for bias correction and assumes the param update already advanced it # (in CPU mode the commit precedes the async-state loop). Without committing first, @@ -1452,9 +1583,20 @@ def _get_norm_groups(self): param_id = self.get_param_id(p) if param_id in self.norm_for_param_grads: group_sq += self.norm_for_param_grads[param_id]**2 - local_sq.append(float(group_sq)) - - total_norms = get_accelerator().FloatTensor(local_sq) + local_sq.append(group_sq) + + device = get_accelerator().current_device_name() + zero = torch.zeros((), device=device) + # Keep subgroup sums in their original precision until the existing FP32 collective boundary. + norm_entries = [] + for value in local_sq: + if torch.is_tensor(value): + norm_entries.append(value) + elif value == 0.0: + norm_entries.append(zero) + else: + norm_entries.append(torch.tensor(value, device=device)) + total_norms = torch.stack(norm_entries).float() # Match complete_grad_norm_calculation_for_cpu_offload: each subgroup sums over its own partition group, # then the model-parallel group, then (AutoEP expert subgroups only) the expert-parallel group. Subgroups # sharing a group are reduced together, so the usual single-group case stays one all-reduce. @@ -1466,12 +1608,9 @@ def _get_norm_groups(self): expert_groups = [group if pg_utils.is_parallel(group) else None for group in expert_groups] self._all_reduce_norm_entries_by_group(total_norms, expert_groups) - norm_groups = [] - for i in range(len(self.fp16_groups)): - total_norm = total_norms[i]**0.5 - mask_nan_or_inf_with_val_inplace(total_norm, device=total_norm.device) - norm_groups.append(total_norm.cpu()) - return norm_groups + total_norms = total_norms.sqrt() + mask_nan_or_inf_with_val_inplace(total_norms, device=total_norms.device) + return list(total_norms.cpu().unbind()) # ------------------------------------------------------------------ # # step @@ -1488,7 +1627,8 @@ def step(self, closure=None): self._pre_step() self._partition_all_parameters() get_accelerator().synchronize() - bucketwise_drained = self._activate_pending_cpu_grads_if_ready() + completed_window = self._complete_pending_gradient_window() + bucketwise_drained = self._activate_pending_cpu_grads_if_ready(flush_completed_window=completed_window) # Activation already joined the backward workers when it flipped the buffers. Otherwise # join them before overflow cleanup discards their handles. if not bucketwise_drained: @@ -1550,6 +1690,10 @@ def step(self, closure=None): # it now with the state swapped in around it, before committing step counters / the async loop. if self.swap_optimizer: self._nvme_optimizer_step_subgroups(combined_scale, timer_names) + if len(self._bucketwise_group_target_step) < len(self.fp16_groups): + for sub_group_id in range(len(self.fp16_groups)): + if not self._swappable_optimizer_subgroup(sub_group_id): + self._ensure_bucketwise_group_step(sub_group_id) self._bucketwise_commit_group_steps() # The commits submitted below overlap the next forward until its backward starts. self._state_commit_overlaps_forward = True diff --git a/tests/unit/v1/zero/test_reflow.py b/tests/unit/v1/zero/test_reflow.py index c508394c9635..5b67fd850daf 100644 --- a/tests/unit/v1/zero/test_reflow.py +++ b/tests/unit/v1/zero/test_reflow.py @@ -17,6 +17,7 @@ import pytest import torch +from torch.utils.checkpoint import checkpoint import deepspeed import deepspeed.comm as dist @@ -24,7 +25,7 @@ from deepspeed.checkpoint.constants import FP32_FLAT_GROUPS from deepspeed.ops.adam import DeepSpeedCPUAdam from deepspeed.ops.lion import DeepSpeedCPULion -from deepspeed.ops.op_builder import CPUAdamBuilder, CPULionBuilder +from deepspeed.ops.op_builder import AsyncIOBuilder, CPUAdamBuilder, CPULionBuilder from deepspeed.ops.op_builder.cpu.reflow_cpu_adam import ReflowCPUAdamBuilder from deepspeed.ops.op_builder.cpu.reflow_cpu_lion import ReflowCPULionBuilder from deepspeed.runtime.config import DeepSpeedConfig @@ -1215,6 +1216,258 @@ class TestReflowAccumulationBufferReuseDistributed(TestReflowAccumulationBufferR world_size = 2 +class ConditionalGradientModel(torch.nn.Module): + + def __init__(self, width=16): + super().__init__() + self.scale = torch.nn.Parameter(torch.ones(1)) + self.always = torch.nn.Linear(width, width) + self.optional = torch.nn.Linear(width, width) + + def forward(self, inputs, use_optional): + result = self.always(inputs) + if use_optional: + result = result + self.optional(inputs) + return self.scale.float() * result.float().square().mean() + + +@needs_gpu_accelerator +class TestReflowConditionalGradients(DistributedTest): + world_size = [1, 2] + + @pytest.mark.parametrize("optimizer_kind", ["adam", "lion"]) + @pytest.mark.parametrize("accumulation_steps", [2, 4]) + def test_matches_zero_offload_across_accumulation_windows(self, optimizer_kind, accumulation_steps): + skip_if_reflow_training_unsupported(optimizer_kind) + if accumulation_steps == 2: + schedule = [(True, True), (True, False), (False, False), (False, True), (True, True)] + else: + schedule = [(True, True, True, False), (False, False, False, False), (False, False, True, True), + (True, True, True, True)] + + def run(reflow): + torch.manual_seed(1234) + model = ConditionalGradientModel() + config = get_variant_config(reflow, optimizer_kind) + config["data_types"] = {"grad_accum_dtype": "bf16"} + config["gradient_accumulation_steps"] = accumulation_steps + config["zero_optimization"]["reduce_bucket_size"] = 1000 + config["zero_optimization"]["sub_group_size"] = 1 + engine, optimizer, _, _ = deepspeed.initialize(model=model, + model_parameters=model.parameters(), + config=config) + snapshots = [] + try: + for step, uses in enumerate(schedule): + for micro_step, use_optional in enumerate(uses): + torch.manual_seed(900 + step * accumulation_steps + micro_step) + inputs = torch.randn(2, 16, device=engine.device, dtype=torch.bfloat16) + engine.backward(engine(inputs, use_optional)) + engine.step() + params = [safe_get_full_fp32_param(p).clone() for p in engine.module.parameters()] + states = [safe_get_full_optimizer_state(p, "exp_avg").clone() for p in engine.module.parameters()] + steps = [int(optimizer.optimizer.state[p]["step"]) for p in optimizer.fp32_partitioned_groups_flat] + snapshots.append((params, states, steps)) + return snapshots + finally: + engine.destroy() + + expected = run(False) + actual = run(True) + for step, (reference, result) in enumerate(zip(expected, actual)): + assert reference[2] == result[2], (f"optimizer steps differ at step {step} rank {dist.get_rank()}: " + f"expected {reference[2]}, got {result[2]}") + for expected_group, actual_group in zip(reference[:2], result[:2]): + for want, got in zip(expected_group, actual_group): + assert torch.equal(got, want), f"parameter or optimizer state differs at step {step}" + + def test_skipped_step_does_not_reuse_invalid_gradient(self): + skip_if_reflow_training_unsupported() + schedule = [(True, False), (True, True), (False, False), (False, True)] + + def run(reflow): + torch.manual_seed(1234) + model = ConditionalGradientModel() + config = get_variant_config(reflow, "adam") + config["bf16"] = {"enabled": False} + config["fp16"] = {"enabled": True, "loss_scale": 128} + config["data_types"] = {"grad_accum_dtype": "fp16"} + config["gradient_accumulation_steps"] = 2 + config["zero_optimization"]["sub_group_size"] = 256 + engine, optimizer, _, _ = deepspeed.initialize(model=model, + model_parameters=model.parameters(), + config=config) + snapshots = [] + try: + for step, uses in enumerate(schedule): + for micro_step, use_optional in enumerate(uses): + torch.manual_seed(900 + step * 2 + micro_step) + inputs = torch.randn(2, 16, device=engine.device, dtype=torch.float16) + loss = engine(inputs, use_optional) + if step == 1 and micro_step == 0 and dist.get_rank() == 0: + loss = loss * float("inf") + engine.backward(loss) + engine.step() + params = [safe_get_full_fp32_param(p).clone() for p in engine.module.parameters()] + states = [safe_get_full_optimizer_state(p, "exp_avg").clone() for p in engine.module.parameters()] + steps = [int(optimizer.optimizer.state[p]["step"]) for p in optimizer.fp32_partitioned_groups_flat] + with deepspeed.zero.GatheredParameters(list(engine.module.parameters())): + low_params = [p.detach().clone() for p in engine.module.parameters()] + snapshots.append((params, states, steps, engine.skipped_steps, low_params)) + return snapshots + finally: + engine.destroy() + + for step, (expected, actual) in enumerate(zip(run(False), run(True))): + assert expected[2:4] == actual[2:4], f"step counters differ at step {step}" + for kind, (expected_group, + actual_group) in enumerate(zip((expected[4], *expected[:2]), (actual[4], *actual[:2]))): + for index, (want, got) in enumerate(zip(expected_group, actual_group)): + if not torch.equal(got, want): + max_index = (got - want).abs().argmax().item() + raise AssertionError( + f"kind {kind} index {index} differs at step {step} rank {dist.get_rank()}: " + f"low={want.flatten()[max_index].item()},{got.flatten()[max_index].item()} " + f"master={expected[0][index].flatten()[max_index].item()}," + f"{actual[0][index].flatten()[max_index].item()}") + + def test_zero_grad_discards_pending_invalid_gradient(self): + skip_if_reflow_training_unsupported() + + def run(reflow): + torch.manual_seed(1234) + model = ConditionalGradientModel() + config = get_variant_config(reflow, "adam") + config["bf16"] = {"enabled": False} + config["fp16"] = {"enabled": True, "loss_scale": 128} + config["data_types"] = {"grad_accum_dtype": "fp16"} + config["zero_optimization"]["reduce_bucket_size"] = 256 + engine, optimizer, _, _ = deepspeed.initialize(model=model, + model_parameters=model.parameters(), + config=config) + try: + torch.manual_seed(900) + inputs = torch.randn(2, 16, device=engine.device, dtype=torch.float16) + engine.backward(engine(inputs, True) * float("inf")) + optimizer.zero_grad() + engine.backward(engine(inputs, False)) + engine.step() + params = [safe_get_full_fp32_param(p).clone() for p in engine.module.parameters()] + states = [safe_get_full_optimizer_state(p, "exp_avg").clone() for p in engine.module.parameters()] + return params, states, engine.skipped_steps + finally: + engine.destroy() + + expected, actual = run(False), run(True) + assert expected[2] == actual[2] == 0 + for expected_group, actual_group in zip(expected[:2], actual[:2]): + for want, got in zip(expected_group, actual_group): + assert torch.equal(got, want) + + +class ReentrantGradientModel(torch.nn.Module): + + def __init__(self): + super().__init__() + self.input = torch.nn.Linear(16, 16) + self.shared = torch.nn.Linear(16, 16) + self.output = torch.nn.Linear(16, 1) + + def forward(self, inputs): + hidden = self.input(inputs).tanh() + for _ in range(2): + hidden = checkpoint(self.shared, hidden, use_reentrant=True).tanh() + return self.output(hidden).float().square().mean() + + +@needs_gpu_accelerator +class TestReflowReentrantGradients(DistributedTest): + world_size = [1, 2] + + @pytest.mark.parametrize("optimizer_kind", ["adam", "lion"]) + @pytest.mark.parametrize("gradient_accumulation_steps", [1, 2]) + def test_matches_zero_offload(self, optimizer_kind, gradient_accumulation_steps): + skip_if_reflow_training_unsupported(optimizer_kind) + + def run(reflow): + torch.manual_seed(1234) + model = ReentrantGradientModel() + config = get_variant_config(reflow, optimizer_kind) + config["data_types"] = {"grad_accum_dtype": "bf16"} + config["gradient_accumulation_steps"] = gradient_accumulation_steps + if gradient_accumulation_steps > 1: + config["gradient_clipping"] = 0.1 + config["zero_optimization"]["reduce_bucket_size"] = 256 + engine, _, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) + snapshots = [] + try: + for step in range(3): + for micro_step in range(gradient_accumulation_steps): + torch.manual_seed(900 + step * gradient_accumulation_steps + micro_step) + inputs = torch.randn(2, 16, device=engine.device, dtype=torch.bfloat16) + engine.backward(engine(inputs)) + engine.step() + params = [safe_get_full_fp32_param(p).clone() for p in engine.module.parameters()] + states = [safe_get_full_optimizer_state(p, "exp_avg").clone() for p in engine.module.parameters()] + snapshots.append((params, states)) + return snapshots + finally: + engine.destroy() + + for step, (expected, actual) in enumerate(zip(run(False), run(True))): + for expected_group, actual_group in zip(expected, actual): + for want, got in zip(expected_group, actual_group): + assert torch.equal(got, want), (f"parameter or optimizer state differs at step {step}: " + f"max diff {(got - want).abs().max().item()}") + + +@needs_gpu_accelerator +class TestReflowNVMeConditionalGradients(DistributedTest): + world_size = 1 + + @pytest.mark.parametrize("optimizer_kind", ["adam", "lion"]) + def test_matches_zero_offload(self, tmpdir, optimizer_kind): + skip_if_reflow_training_unsupported(optimizer_kind) + if not deepspeed.ops.__compatible_ops__.get(AsyncIOBuilder.NAME, False): + pytest.skip("NVMe offload requires the async_io extension") + width = 384 + + def run(reflow): + torch.manual_seed(1234) + model = ConditionalGradientModel(width) + config = get_variant_config(reflow, optimizer_kind) + config["data_types"] = {"grad_accum_dtype": "bf16"} + config["gradient_accumulation_steps"] = 2 + config["zero_optimization"]["reduce_bucket_size"] = 1_000_000 + config["zero_optimization"]["offload_optimizer"] = { + "device": "nvme", + "nvme_path": str(tmpdir.join("reflow" if reflow else "zero")) + } + engine, optimizer, _, _ = deepspeed.initialize(model=model, + model_parameters=model.parameters(), + config=config) + assert any(optimizer._swappable_optimizer_subgroup(i) for i in range(len(optimizer.fp16_groups))) + snapshots = [] + try: + for step, uses in enumerate(((True, True), (True, False), (False, False), (False, True))): + for micro_step, use_optional in enumerate(uses): + torch.manual_seed(900 + step * 2 + micro_step) + inputs = torch.randn(2, width, device=engine.device, dtype=torch.bfloat16) + engine.backward(engine(inputs, use_optional)) + engine.step() + params = [safe_get_full_fp32_param(p).clone() for p in engine.module.parameters()] + states = [safe_get_full_optimizer_state(p, "exp_avg").clone() for p in engine.module.parameters()] + snapshots.append((params, states)) + return snapshots + finally: + engine.destroy() + + for step, (expected, actual) in enumerate(zip(run(False), run(True))): + for expected_group, actual_group in zip(expected, actual): + for want, got in zip(expected_group, actual_group): + assert torch.equal(got, want), f"NVMe parameter or optimizer state differs at step {step}" + + class TestReflowMaximizeClientInitialization(DistributedTest): world_size = 1 non_daemonic_procs = True From 06a1416182166059eecb7a416df8e01f88d0cb8c Mon Sep 17 00:00:00 2001 From: st-bang97 Date: Fri, 20 Nov 2026 12:44:12 +0900 Subject: [PATCH 13/19] Fix ReFlow local gradient access and CPU placement Signed-off-by: st-bang97 --- deepspeed/runtime/reflow/reflow_config.py | 1 + deepspeed/runtime/reflow/reflow_stage3.py | 96 +++++- deepspeed/runtime/reflow/reflow_utils.py | 51 ++- docs/_pages/config-json.md | 2 +- docs/_tutorials/reflow.md | 4 +- tests/unit/v1/zero/test_reflow.py | 365 +++++++++++++++++++++- 6 files changed, 468 insertions(+), 51 deletions(-) diff --git a/deepspeed/runtime/reflow/reflow_config.py b/deepspeed/runtime/reflow/reflow_config.py index 394530bdb423..e34ea36d2eb0 100644 --- a/deepspeed/runtime/reflow/reflow_config.py +++ b/deepspeed/runtime/reflow/reflow_config.py @@ -20,6 +20,7 @@ class ReflowConfig(DeepSpeedConfigModel): main_thread_cores: int = Field(3, ge=1) """Cores reserved for the main thread; the rest go to the optimizer workers. + The reservation shrinks if needed to leave a worker core; a single available core is shared. Worker placement uses this even when ``enable_cpu_affinity`` is false.""" main_thread_core_type: Literal["logical", "physical"] = "logical" diff --git a/deepspeed/runtime/reflow/reflow_stage3.py b/deepspeed/runtime/reflow/reflow_stage3.py index cb84f0e0a6ee..43e3ce3f1fdb 100644 --- a/deepspeed/runtime/reflow/reflow_stage3.py +++ b/deepspeed/runtime/reflow/reflow_stage3.py @@ -68,6 +68,7 @@ def __init__(self, module, init_optimizer, param_names, timers, ds_config, reflo self._reflow_boundary_grad_ids = set() self._reflow_gradient_partitions = None self._reflow_checkpoint_param_ids = set() + self._reflow_modified_gradient_ids = set() self._last_state_update_future = None self._pending_state_updates_by_subgroup = {} self._state_commit_overlaps_forward = False @@ -785,6 +786,7 @@ def reset_cpu_buffers(self): self._reflow_window_grad_ids.clear() self._reflow_boundary_grad_ids.clear() self._reflow_checkpoint_param_ids.clear() + self._reflow_modified_gradient_ids.clear() self._pending_grad_ready = False # Reset per-iteration pending/inflight state. @@ -1480,8 +1482,8 @@ def _nvme_optimizer_step_subgroups(self, combined_scale, timer_names): self._wait_for_pending_state_updates(sub_group_id=sub_group_id) self._optimizer_states_and_gradient_swap_out(sub_group_id, timer_names) - def _bucketwise_run_full_partition_updates(self, combined_scale): - # Clipping path: re-shard and re-run each group's full range, then transfer. + def _bucketwise_run_full_partition_updates(self, combined_scale, param_ids=None): + # Re-shard full groups for clipping, or only changed gradients for local API updates. full_update_futures = [] for sub_group_id in range(len(self.fp16_groups)): @@ -1492,6 +1494,8 @@ def _bucketwise_run_full_partition_updates(self, combined_scale): if not param.requires_grad: continue param_id = self.get_param_id(param) + if param_ids is not None and param_id not in param_ids: + continue pos = self.grad_position.get(param_id, None) if pos is None: continue @@ -1681,6 +1685,11 @@ def step(self, closure=None): self._bucketwise_cancel_inflight_updates() self._bucketwise_wait_inflight_updates() self._bucketwise_run_full_partition_updates(combined_scale=combined_scale) + elif self._reflow_modified_gradient_ids: + # Unchanged ranges still need their original Ready work to finish. + self._bucketwise_wait_inflight_updates() + self._bucketwise_run_full_partition_updates(combined_scale=combined_scale, + param_ids=self._reflow_modified_gradient_ids) timer_names = set() # Param updates already ran bucketwise during backward; here we only commit per-group @@ -1829,6 +1838,69 @@ def get_fp32_grad_for_param(self, param) -> Tensor: def set_fp32_grad_for_param(self, value, param): raise NotImplementedError(_REFLOW_FLAT_GRAD_FREED_MSG.format(api="set_fp32_grad_for_param")) + def get_local_fp32_grad_for_param(self, param) -> Tensor: + if not param.requires_grad: + return None + param_id = self.get_param_id(param) + sub_group_id, offset, numel = self.grad_position[param_id] + device = get_accelerator().current_device_name() + has_partition = param.partition_numel() * self._get_param_partition_rank(param) < param.ds_numel + if param_id not in self._reflow_window_grad_ids or not has_partition: + return torch.zeros(numel, dtype=torch.float32, device=device) + self._wait_for_accum_gradient(param_id) + if self._bucketwise_worker_error is not None: + raise self._bucketwise_worker_error + self.copy_grad_stream.synchronize() + gradient = self._get_cpu_grad_buffer(sub_group_id, pending=True).narrow(0, offset, numel) + return gradient.to(device=device, dtype=torch.float32) + + def set_local_grad_for_param(self, value, param): + if not param.requires_grad: + return + param_id = self.get_param_id(param) + sub_group_id, offset, numel = self.grad_position[param_id] + assert value.numel() == numel, f"Number of elements do not match: {value.numel()} != {numel}" + if param.partition_numel() * self._get_param_partition_rank(param) >= param.ds_numel: + return + + # Ready may already be reading this gradient. Join it before changing the buffer; + # the step will regenerate previews after the final clipping scale is known. + if self.dtype == torch.float16: + self._wait_for_accum_gradient() + else: + self._wait_for_accum_gradient(param_id) + self._bucketwise_drain_enq_executor() + self._bucketwise_wait_inflight_updates() + self.copy_grad_stream.synchronize() + if self._single_grad_buffer: + self._wait_for_pending_state_updates(sub_group_id=sub_group_id) + if self._bucketwise_worker_error is not None: + raise self._bucketwise_worker_error + gradient = self._get_cpu_grad_buffer(sub_group_id, pending=True).narrow(0, offset, numel) + gradient.copy_(value.detach().reshape(-1), non_blocking=False) + self._reflow_window_grad_ids.add(param_id) + self._pending_grad_ready = True + self._reflow_modified_gradient_ids.add(param_id) + gradient_on_device = gradient.to(get_accelerator().current_device_name(), non_blocking=True) + self.norm_for_param_grads[param_id] = self._constant_buffered_norm2(gradient_on_device) + + if self.dtype == torch.float16: + # A replacement can remove an earlier overflow, so rebuild the flag from + # this window's stored gradients rather than keeping a stale sticky bit. + invalid = False + for active_id in self._reflow_window_grad_ids: + group, start, length = self.grad_position[active_id] + active_gradient = self._get_cpu_grad_buffer(group, pending=True).narrow(0, start, length) + if not torch.isfinite(active_gradient).all(): + invalid = True + break + if self._reflow_grad_overflow is None: + self._reflow_grad_overflow = torch.zeros((), dtype=torch.uint8, device=gradient_on_device.device) + self._reflow_grad_overflow.fill_(invalid) + + def get_fp32_grad_partitions(self): + raise NotImplementedError(_REFLOW_FLAT_GRAD_FREED_MSG.format(api="get_fp32_grad_partitions")) + def offload_states(self, include: Container[OffloadStateTypeEnum] = None, device: OffloadDeviceEnum = OffloadDeviceEnum.cpu, @@ -1894,7 +1966,27 @@ def get_lean_optimizer_state(self): raise self._bucketwise_worker_error return super().get_lean_optimizer_state() + def get_full_hp_param(self, param, optim_state_key=None) -> Tensor: + if not param.requires_grad: + return None + # The inherited full-parameter getter is collective; report a failure on all + # participating ranks before any one of them exits the following all-gather. + self._wait_for_pending_state_updates() + local_error = self._bucketwise_worker_error + process_group = self._get_param_partition_group(param) + if dist.get_world_size(group=process_group) > 1: + error_flag = get_accelerator().ByteTensor([1 if local_error is not None else 0]) + dist.all_reduce(error_flag, op=dist.ReduceOp.MAX, group=process_group) + if error_flag[0].item() and local_error is None: + raise RuntimeError( + "Reflow asynchronous optimizer update failed on another rank; aborting state access") + if local_error is not None: + raise local_error + return super().get_full_hp_param(param, optim_state_key=optim_state_key) + def _get_fp32_opt_state_partition(self, param, release_swap_buffers, optim_state_key=None): # Every get/set hp-param API goes through here. self._wait_for_pending_state_updates() + if self._bucketwise_worker_error is not None: + raise self._bucketwise_worker_error return super()._get_fp32_opt_state_partition(param, release_swap_buffers, optim_state_key=optim_state_key) diff --git a/deepspeed/runtime/reflow/reflow_utils.py b/deepspeed/runtime/reflow/reflow_utils.py index 0bc8f172f755..c8b05f41b927 100644 --- a/deepspeed/runtime/reflow/reflow_utils.py +++ b/deepspeed/runtime/reflow/reflow_utils.py @@ -202,10 +202,10 @@ def physical_cpu_groups(cpus): def partition_physical_cpus(cpus, ranks, position): - """Give each local rank whole physical cores so its SMT siblings cannot belong to another rank.""" + """Assign whole physical cores, sharing only when there are fewer cores than ranks.""" groups = physical_cpu_groups(cpus) if len(groups) < ranks: - raise ValueError("Reflow physical CPU placement requires at least one physical core per local rank") + return list(groups[position % len(groups)]) base, remainder = divmod(len(groups), ranks) start = position * base + min(position, remainder) count = base + (position < remainder) @@ -222,9 +222,7 @@ def split_cpu_worker_cores(rank_cores, if main_thread_core_type == "physical" or worker_core_type == "physical": physical_groups = physical_cpu_groups(rank_cores) if main_thread_core_type == "physical": - if len(physical_groups) < 2: - raise ValueError("Reflow physical main-thread reservation requires at least two physical cores per rank") - count = min(main_thread_cores, len(physical_groups) - 1) + count = min(main_thread_cores, max(1, len(physical_groups) - 1)) main_cores = [cpu for group in physical_groups[:count] for cpu in group] else: count = min(max(1, int(main_thread_cores)), max(1, len(rank_cores) - 1)) @@ -237,6 +235,8 @@ def split_cpu_worker_cores(rank_cores, available = [cpu for cpu in group if cpu not in main_set] if available: worker_set.add(available[0]) + if not worker_set: + worker_set.add(physical_groups[0][0]) node_worker_groups = [[cpu for cpu in group if cpu in worker_set] for group in node_groups] node_worker_groups = [group for group in node_worker_groups if group] if not node_worker_groups: @@ -270,20 +270,14 @@ def heuristic_rank_cores(numa_nodes, local_rank, local_world_size, physical=Fals start = pos * base + min(pos, remainder) count = base + (pos < remainder) return node[start:start + count] - # Extreme oversubscription (more co-located ranks than cores): split the node's cores into - # disjoint slices via a base size + remainder so co-located ranks never share a core. Ranks - # past the core count fall back to a degenerate (<1 core/rank) split, so warn once on rank 0. + # More ranks than cores requires sharing at least one CPU between ranks. if local_rank == 0: logger.warning(f"Reflow NUMA affinity hint: {ranks_per_node} co-located ranks but only " f"{len(node)} cores on this NUMA node; cores cannot be split disjointly.") - base = len(node) // ranks_per_node - remainder = len(node) % ranks_per_node - start = pos * base + min(pos, remainder) - size = base + (1 if pos < remainder else 0) - return node[start:start + size] + return [node[pos % len(node)]] -def _isolate_rank_cpu_sets(rank_cores, main_thread_cores, main_thread_core_type, worker_core_type, pin_main_thread): +def _isolate_rank_cpu_sets(rank_cores, main_thread_core_type, worker_core_type, pin_main_thread): """Split shared rank CPU sets and reject ambiguous overlaps before pinning any thread.""" physical = main_thread_core_type == "physical" or worker_core_type == "physical" units = physical_cpu_groups(rank_cores) if physical else [[cpu] for cpu in rank_cores] @@ -292,8 +286,6 @@ def _isolate_rank_cpu_sets(rank_cores, main_thread_cores, main_thread_core_type, "cpus": sorted(rank_cores), "units": units, "pin": pin_main_thread, - "main_count": main_thread_cores, - "main_type": main_thread_core_type, } if dist.is_initialized() and dist.get_world_size() > 1: layouts = [None] * dist.get_world_size() @@ -329,22 +321,14 @@ def _isolate_rank_cpu_sets(rank_cores, main_thread_cores, main_thread_core_type, for position, peer in enumerate(peers): start = position * base + min(position, remainder) count = base + (position < remainder) - assignments[peer] = [cpu for unit in shared_units[start:start + count] for cpu in unit] + if count == 0: + assignments[peer] = list(shared_units[position % len(shared_units)]) + else: + assignments[peer] = [cpu for unit in shared_units[start:start + count] for cpu in unit] else: for peer in peers: assignments[peer] = layouts[peer]["cpus"] - for index, layout in enumerate(layouts): - if not layout["pin"]: - continue - assigned = set(assignments[index]) - if layout["main_type"] == "physical": - available = sum(bool(assigned.intersection(unit)) for unit in layout["units"]) - else: - available = len(assigned) - if available <= layout["main_count"]: - raise ValueError("Reflow needs enough CPUs per rank for the requested main_thread_cores and at least " - "one worker CPU.") return sorted(assignments[rank]) @@ -405,7 +389,10 @@ def plan_cpu_core_layout(main_thread_cores, base, remainder = divmod(len(node_cores), n_on_node) start = my_pos * base + min(my_pos, remainder) count = base + (my_pos < remainder) - rank_cores = node_cores[start:start + count] + if count: + rank_cores = node_cores[start:start + count] + else: + rank_cores = [node_cores[my_pos % len(node_cores)]] else: rank_cores = node_cores else: @@ -417,8 +404,7 @@ def plan_cpu_core_layout(main_thread_cores, else: total = psutil.cpu_count(logical=False) or 1 rank_cores = list(range(total)) - rank_cores = _isolate_rank_cpu_sets(sorted(rank_cores), main_thread_cores, main_thread_core_type, worker_core_type, - pin_main_thread) + rank_cores = _isolate_rank_cpu_sets(sorted(rank_cores), main_thread_core_type, worker_core_type, pin_main_thread) total_cpus = len(rank_cores) # Group this rank's cores by NUMA node so worker masks stay within a single node. @@ -436,6 +422,9 @@ def plan_cpu_core_layout(main_thread_cores, node_groups = [rank_cores] main_cores, node_worker_groups, worker_cores = split_cpu_worker_cores(rank_cores, node_groups, main_thread_cores, main_thread_core_type, worker_core_type) + if pin_main_thread and set(main_cores).intersection(worker_cores): + logger.warning("Reflow has too few CPUs to isolate the main thread; main and optimizer workers will share " + "at least one CPU.") return total_cpus, rank_cores, node_worker_groups, main_cores, worker_cores diff --git a/docs/_pages/config-json.md b/docs/_pages/config-json.md index 30ee5fdc8b81..62fc66f9c03a 100644 --- a/docs/_pages/config-json.md +++ b/docs/_pages/config-json.md @@ -751,7 +751,7 @@ The `reflow` block enables it, so an empty block is enough to run with the defau | Description | Default | | ----------- | ------- | -| CPUs or physical cores reserved for the initializing thread, according to `main_thread_core_type`. Ranks sharing a CPU set divide it before reserving their main CPUs. Partially overlapping rank affinities are rejected when pinning is enabled. | `3` | +| CPUs or physical cores reserved for the initializing thread, according to `main_thread_core_type`. Ranks sharing a CPU set divide it before reserving their main CPUs. The reservation shrinks to leave a worker CPU when possible; a single CPU is shared by main and worker. Ranks also share CPUs if there are fewer CPUs than ranks. Partially overlapping rank affinities are rejected when pinning is enabled. | `3` | ***main_thread_core_type***: [string] diff --git a/docs/_tutorials/reflow.md b/docs/_tutorials/reflow.md index 995c8830c7fc..acb49b53e505 100644 --- a/docs/_tutorials/reflow.md +++ b/docs/_tutorials/reflow.md @@ -14,7 +14,7 @@ Adding a `reflow` block to `zero_optimization` turns on three cooperating behavi 2. **Half-precision gradient transfer.** Gradients are copied to CPU in BF16 and promoted to FP32 inside the AVX kernel. This halves the GPU-to-CPU traffic and removes the CPU-side FP32 gradient buffer. 3. **Asynchronous state commit.** The foreground only produces the new BF16 parameters. The FP32 master weights and optimizer state are committed by a background worker after the gradient clipping and overflow checks, overlapping the next forward. -Checkpoint APIs (`state_dict`, `load_state_dict`, and the `safe_get_*`/`safe_set_*` helpers) wait for that background commit. If a worker fails, `engine.save_checkpoint()` aborts on every rank before writing checkpoint files. Direct `state_dict()` and `get_lean_optimizer_state()` calls raise any recorded local worker error. Checkpoint preparation shares one error flag across ranks; this adds no collectives to the training or direct state-read paths. +Checkpoint and FP32 parameter/state access APIs wait for that background commit. If a worker fails, `engine.save_checkpoint()` aborts on every rank before writing checkpoint files, and direct state reads report the failure. A full FP32 parameter or optimizer-state read uses an additional collective over the parameter partition group so all participating ranks see a failed commit; the training path adds no collective. Local gradient inspection and modification before `step()` use Reflow’s CPU buffers for the current accumulation window. Reads return FP32 values; writes are stored in the model’s FP16/BF16 gradient dtype and rounded accordingly. Changing a gradient requires Ready to regenerate the affected update. Full gradient helpers remain unsupported because Reflow releases the standard FP32 gradient buffer. ## Configuration @@ -52,7 +52,7 @@ Launch with `--bind_cores_to_rank` so each rank runs on the CPU cores local to i deepspeed --bind_cores_to_rank train.py --deepspeed_config ds_config.json ``` -By default Reflow pins the initializing thread to `main_thread_cores` CPU IDs and divides the remaining CPUs among optimizer workers. Local ranks sharing a CPU set divide it before reserving their main CPUs; partially overlapping rank affinities are rejected. The state commit may use all worker CPUs unless `state_update_cores` or `state_update_backward_cores` sets a limit. `enable_cpu_affinity` additionally restricts the main process to its NUMA-local CPU slice. +By default Reflow pins the initializing thread to `main_thread_cores` CPU IDs and divides the remaining CPUs among optimizer workers. Local ranks sharing a CPU set divide it before reserving their main CPUs; partially overlapping rank affinities are rejected. If the requested reservation leaves no worker CPU, Reflow reduces it to leave at least one CPU each for the main thread and workers. If only one CPU is available, they share it; ranks also share CPUs when there are fewer CPUs than ranks. The state commit may use all worker CPUs unless `state_update_cores` or `state_update_backward_cores` sets a limit. `enable_cpu_affinity` additionally restricts the main process to its NUMA-local CPU slice. ## Gradient clipping diff --git a/tests/unit/v1/zero/test_reflow.py b/tests/unit/v1/zero/test_reflow.py index 5b67fd850daf..33df59ef794a 100644 --- a/tests/unit/v1/zero/test_reflow.py +++ b/tests/unit/v1/zero/test_reflow.py @@ -11,7 +11,7 @@ import os import threading import weakref -from concurrent.futures import ThreadPoolExecutor +from concurrent.futures import Future, ThreadPoolExecutor from unittest.mock import Mock, patch from types import SimpleNamespace @@ -36,7 +36,8 @@ from deepspeed.runtime.zero.stage3 import DeepSpeedZeroOptimizer_Stage3 from deepspeed.runtime.zero.muon.muon_optimizer import MuonWithAuxAdam from deepspeed.runtime.zero.utils import ZeRORuntimeException -from deepspeed.utils import safe_get_full_fp32_param, safe_get_full_optimizer_state +from deepspeed.utils import (safe_get_full_fp32_param, safe_get_full_optimizer_state, safe_get_local_grad, + safe_set_local_grad) from deepspeed.utils.numa import parse_range_list from unit.common import DistributedTest from unit.simple_model import SimpleModel @@ -145,10 +146,38 @@ def test_physical_rank_partition_preserves_siblings_and_remainders(): assert max(counts) - min(counts) <= 1 -def test_physical_main_reservation_keeps_a_worker_core(): +@pytest.mark.parametrize("count", [1, 2, 3, 4, 5]) +def test_cpu_split_keeps_a_worker_when_main_reservation_is_too_large(count): + cpus, _ = available_physical_cpus() + if len(cpus) < count: + pytest.skip("requires enough available CPUs") + rank_cpus = cpus[:count] + main, _, workers = reflow_utils.split_cpu_worker_cores(rank_cpus, [rank_cpus], 3) + assert main and workers + assert len(main) == min(3, max(1, count - 1)) + if count == 1: + assert main == workers == rank_cpus + else: + assert set(main).isdisjoint(workers) + assert set(main) | set(workers) == set(rank_cpus) + + +def test_oversubscribed_ranks_share_only_available_cpus(): + cpus, groups = available_physical_cpus() + if len(groups) < 2: + pytest.skip("requires two physical cores") + node = [groups[0][0], groups[1][0]] + assigned = [reflow_utils.heuristic_rank_cores([node], rank, 4) for rank in range(4)] + assert assigned == [[node[0]], [node[1]], [node[0]], [node[1]]] + physical_cpus = groups[0] + groups[1] + assigned = [reflow_utils.partition_physical_cpus(physical_cpus, 4, rank) for rank in range(4)] + assert assigned == [groups[0], groups[1], groups[0], groups[1]] + + +def test_physical_main_reservation_shares_a_single_core(): _, groups = available_physical_cpus() - with pytest.raises(ValueError): - reflow_utils.split_cpu_worker_cores(groups[0], [groups[0]], 1, "physical", "logical") + main, _, workers = reflow_utils.split_cpu_worker_cores(groups[0], [groups[0]], 3, "physical", "logical") + assert set(main) == set(workers) == set(groups[0]) def test_requires_stage3_and_cpu_optimizer_offload(): @@ -695,7 +724,8 @@ def recorded(*args, _phase=phase, _original=original, **kwargs): assert torch.equal(got, want) -@pytest.mark.parametrize("rank_affinity", ["shared", "launcher", "partial", "insufficient"]) +@pytest.mark.parametrize( + "rank_affinity", ["shared", "launcher", "partial", "insufficient", "small_shared", "one_cpu", "oversubscribed"]) @needs_gpu_accelerator class TestReflowRankCoreBinding(DistributedTest): world_size = 2 @@ -720,6 +750,16 @@ def test_rank_main_and_worker_cpus_are_disjoint(self, rank_affinity): input_cpus = set(shared[:12] if rank == 0 else shared[4:]) elif rank_affinity == "insufficient": input_cpus = set(shared[rank * 3:(rank + 1) * 3]) + rank_cpus = input_cpus + elif rank_affinity == "small_shared": + input_cpus = set(shared[:4]) + rank_cpus = set(shared[rank * 2:(rank + 1) * 2]) + elif rank_affinity == "one_cpu": + input_cpus = {shared[rank]} + rank_cpus = input_cpus + elif rank_affinity == "oversubscribed": + input_cpus = {shared[0]} + rank_cpus = input_cpus else: input_cpus = rank_cpus engine = None @@ -733,10 +773,8 @@ def test_rank_main_and_worker_cpus_are_disjoint(self, rank_affinity): model = SimpleModel(hidden_dim=16, nlayers=2) config = get_variant_config(reflow=True, variant="adam") config["zero_optimization"]["reduce_bucket_size"] = 1_000_000 - if rank_affinity in ("partial", "insufficient"): - message = ("partially overlapping rank CPU affinities" - if rank_affinity == "partial" else "main_thread_cores and at least one worker CPU") - with pytest.raises(ValueError, match=message): + if rank_affinity == "partial": + with pytest.raises(ValueError, match="partially overlapping rank CPU affinities"): deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) return engine, optimizer, _, _ = deepspeed.initialize(model=model, @@ -763,15 +801,19 @@ def recorded(*args, _phase=phase, _original=originals[name], **kwargs): engine.backward(loss) engine.step() optimizer.state_dict() - assert len(main_cpus) == 3 - assert main_cpus == set(sorted(rank_cpus)[:3]) + expected_main = set(sorted(rank_cpus)[:min(3, max(1, len(rank_cpus) - 1))]) + expected_workers = rank_cpus - expected_main or rank_cpus + assert main_cpus == expected_main assert worker_masks - assert all(mask <= rank_cpus - main_cpus for mask in worker_masks) + assert all(mask <= expected_workers for mask in worker_masks) assert state_masks - assert all(mask == rank_cpus - main_cpus for mask in state_masks) + assert all(mask == expected_workers for mask in state_masks) placements = [None] * dist.get_world_size() dist.all_gather_object(placements, (main_cpus, rank_cpus)) - assert placements[0][1].isdisjoint(placements[1][1]) + if rank_affinity == "oversubscribed": + assert placements[0][1] == placements[1][1] + else: + assert placements[0][1].isdisjoint(placements[1][1]) assert all(main <= cpus for main, cpus in placements) finally: if native is not None: @@ -862,6 +904,177 @@ def test_rejects_zero_init_model_with_unsupported_dtype(self, dtype, fp16_suppor deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) +@needs_gpu_accelerator +class TestReflowUnsupportedGradientAccess(DistributedTest): + world_size = 1 + + @pytest.mark.parametrize("precision", ["bf16", "fp16"]) + def test_rejects_mixed_fp32_and_half_parameters(self, precision): + skip_if_reflow_training_unsupported() + model = SimpleModel(hidden_dim=16, nlayers=2) + config = get_variant_config(True, "adam") + if precision == "fp16": + config["bf16"] = {"enabled": False} + config["fp16"] = {"enabled": True, "loss_scale": 128} + config["data_types"] = {"keep_in_fp32_modules": ["linears.0"]} + with pytest.raises(ValueError, match="requires FP16 or BF16 model parameters"): + deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) + + +@needs_gpu_accelerator +class TestReflowLocalGradientAccess(DistributedTest): + world_size = [1, 2] + non_daemonic_procs = True + + @pytest.mark.parametrize("precision", ["bf16", "fp16"]) + @pytest.mark.parametrize("optimizer_kind", ["adam", "lion"]) + @pytest.mark.parametrize("accumulation_steps", [1, 2]) + @pytest.mark.parametrize("clip", [0.0, 0.1]) + def test_local_gradients_and_updates_match_zero(self, precision, optimizer_kind, accumulation_steps, clip): + skip_if_reflow_training_unsupported(optimizer_kind) + dtype = torch.bfloat16 if precision == "bf16" else torch.float16 + torch.manual_seed(1234) + initial_model = SimpleModel(hidden_dim=16, nlayers=2) + batches = make_batches(16, count=2 * accumulation_steps, dtype=dtype) + + def run(reflow): + model = copy.deepcopy(initial_model) + config = get_variant_config(reflow, optimizer_kind) + config["data_types"] = {"grad_accum_dtype": precision} + config["gradient_accumulation_steps"] = accumulation_steps + config["gradient_clipping"] = clip + config["zero_optimization"]["reduce_bucket_size"] = 128 + if precision == "fp16": + config["bf16"] = {"enabled": False} + config["fp16"] = {"enabled": True, "loss_scale": 128} + engine, _, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) + snapshots = [] + try: + for step in range(2): + for micro in range(accumulation_steps): + inputs, labels = batches[step * accumulation_steps + micro] + engine.backward(engine(inputs, labels)) + if micro == accumulation_steps - 1: + param = next(engine.module.parameters()) + gradient = safe_get_local_grad(param).clone() + safe_set_local_grad(param, (-gradient * 0.5).to(dtype)) + updated_gradient = safe_get_local_grad(param).clone() + engine.step() + params = [safe_get_full_fp32_param(p).clone() for p in engine.module.parameters()] + states = [safe_get_full_optimizer_state(p, "exp_avg").clone() for p in engine.module.parameters()] + variances = ( + [safe_get_full_optimizer_state(p, "exp_avg_sq").clone() + for p in engine.module.parameters()] if optimizer_kind == "adam" else []) + steps = [int(state["step"]) for state in engine.optimizer.optimizer.state.values()] + snapshots.append( + (gradient, updated_gradient, params, states, variances, steps, engine.get_global_grad_norm())) + return snapshots + finally: + engine.destroy() + + expected = run(False) + actual = run(True) + for want, got in zip(expected, actual): + assert torch.equal(want[0], got[0]) + assert torch.equal(want[1], got[1]) + assert want[5:] == got[5:] + for expected_group, actual_group in zip(want[2:5], got[2:5]): + for expected_tensor, actual_tensor in zip(expected_group, actual_group): + assert torch.equal(expected_tensor, actual_tensor) + + @pytest.mark.parametrize("precision", ["bf16", "fp16"]) + def test_modification_between_microsteps_accumulates(self, precision): + # The reference zeros this parameter's first gradient in autograd, before ZeRO sees it. + skip_if_reflow_training_unsupported() + dtype = torch.bfloat16 if precision == "bf16" else torch.float16 + torch.manual_seed(1234) + initial_model = SimpleModel(hidden_dim=16, nlayers=2) + batches = make_batches(16, count=2, dtype=dtype) + + def run(reflow): + model = copy.deepcopy(initial_model) + phase = [0] + if not reflow: + model.linears[0].weight.register_hook(lambda grad: torch.zeros_like(grad) if phase[0] == 0 else grad) + config = get_variant_config(reflow, "adam") + config["data_types"] = {"grad_accum_dtype": precision} + config["gradient_accumulation_steps"] = 2 + if precision == "fp16": + config["bf16"] = {"enabled": False} + config["fp16"] = {"enabled": True, "loss_scale": 128} + engine, _, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) + try: + for micro_step, (inputs, labels) in enumerate(batches): + phase[0] = micro_step + engine.backward(engine(inputs, labels)) + if reflow and micro_step == 0: + param = engine.module.linears[0].weight + local_grad = safe_get_local_grad(param) + safe_set_local_grad(param, torch.zeros_like(local_grad, dtype=dtype)) + assert torch.count_nonzero(safe_get_local_grad(param)) == 0 + engine.step() + params = [safe_get_full_fp32_param(p).clone() for p in engine.module.parameters()] + states = [safe_get_full_optimizer_state(p, "exp_avg").clone() for p in engine.module.parameters()] + return params, states + finally: + engine.destroy() + + expected = run(False) + actual = run(True) + for expected_group, actual_group in zip(expected, actual): + for want, got in zip(expected_group, actual_group): + assert torch.equal(want, got) + + +@needs_gpu_accelerator +class TestReflowLocalGradientInvalid(DistributedTest): + world_size = [1, 2] + non_daemonic_procs = True + + @pytest.mark.parametrize("precision", ["bf16", "fp16"]) + @pytest.mark.parametrize("restore", [False, True]) + def test_replaced_invalid_gradient_matches_zero(self, precision, restore): + skip_if_reflow_training_unsupported() + dtype = torch.bfloat16 if precision == "bf16" else torch.float16 + torch.manual_seed(1234) + initial_model = SimpleModel(hidden_dim=16, nlayers=2) + inputs, labels = make_batches(16, count=1, dtype=dtype)[0] + + def run(reflow): + model = copy.deepcopy(initial_model) + config = get_variant_config(reflow, "adam") + config["data_types"] = {"grad_accum_dtype": precision} + if precision == "fp16": + config["bf16"] = {"enabled": False} + config["fp16"] = {"enabled": True, "loss_scale": 128} + engine, optimizer, _, _ = deepspeed.initialize(model=model, + model_parameters=model.parameters(), + config=config) + try: + engine.backward(engine(inputs, labels)) + engine.step() + engine.backward(engine(inputs, labels)) + param = next(engine.module.parameters()) + if dist.get_rank() == 0: + original = safe_get_local_grad(param).to(dtype) + safe_set_local_grad(param, torch.full_like(original, float("inf"))) + if restore: + safe_set_local_grad(param, original) + engine.step() + params = [safe_get_full_fp32_param(p).clone() for p in engine.module.parameters()] + states = [safe_get_full_optimizer_state(p, "exp_avg").clone() for p in engine.module.parameters()] + return engine.skipped_steps, params, states + finally: + engine.destroy() + + expected = run(False) + actual = run(True) + assert actual[0] == expected[0] == (0 if restore else 1) + for expected_group, actual_group in zip(expected[1:], actual[1:]): + for want, got in zip(expected_group, actual_group): + assert torch.equal(want, got) + + def test_reflow_releases_every_parent_gradient_dtype(): optimizer = object.__new__(ReflowOptimizer_Stage3) optimizer.offload_optimizer_pin_memory = True @@ -1084,6 +1297,85 @@ def commit(): engine.destroy() +class TestReflowFailedCommitStateAccess(DistributedTest): + world_size = [1, 2] + non_daemonic_procs = True + + def test_parameter_and_state_access_report_failed_commit(self): + skip_if_reflow_training_unsupported() + model = SimpleModel(hidden_dim=16, nlayers=2) + engine, optimizer, _, _ = deepspeed.initialize(model=model, + model_parameters=model.parameters(), + config=get_variant_config(True, "adam")) + try: + if dist.get_rank() == 0: + failed_commit = Future() + failed_commit.set_exception(RuntimeError("injected asynchronous state commit failure")) + optimizer._last_state_update_future = failed_commit + param = next(engine.module.parameters()) + for read in (lambda: safe_get_full_fp32_param(param), + lambda: safe_get_full_optimizer_state(param, "exp_avg")): + with pytest.raises(RuntimeError, match="asynchronous"): + read() + finally: + engine.destroy() + + +@needs_gpu_accelerator +class TestReflowCheckpointResume(DistributedTest): + world_size = [1, 2] + non_daemonic_procs = True + + def test_resume_matches_uninterrupted_training(self, tmpdir): + # A checkpoint immediately after step must include the outstanding Persist update. + skip_if_reflow_training_unsupported() + torch.manual_seed(1234) + model = SimpleModel(hidden_dim=16, nlayers=2) + batches = make_batches(16, count=3) + config = get_variant_config(True, "adam") + config["gradient_clipping"] = 0.1 + save_dir = str(tmpdir / "resume") + engine, _, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) + + def continue_training(current_engine): + snapshots = [] + for inputs, labels in batches[1:]: + loss = current_engine(inputs, labels) + current_engine.backward(loss) + current_engine.step() + params = [safe_get_full_fp32_param(param).clone() for param in current_engine.module.parameters()] + moments = [ + safe_get_full_optimizer_state(param, "exp_avg").clone() + for param in current_engine.module.parameters() + ] + snapshots.append((loss.detach().clone(), params, moments)) + return snapshots + + try: + inputs, labels = batches[0] + engine.backward(engine(inputs, labels)) + engine.step() + assert engine.save_checkpoint(save_dir, tag="first") + expected = continue_training(engine) + finally: + engine.destroy() + + model = SimpleModel(hidden_dim=16, nlayers=2) + engine, _, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) + try: + loaded_path, _ = engine.load_checkpoint(save_dir, tag="first") + assert loaded_path is not None + actual = continue_training(engine) + finally: + engine.destroy() + + for expected_step, actual_step in zip(expected, actual): + assert torch.equal(expected_step[0], actual_step[0]) + for expected_group, actual_group in zip(expected_step[1:], actual_step[1:]): + for want, got in zip(expected_group, actual_group): + assert torch.equal(want, got) + + def get_state_read_config(reflow, gradient_accumulation_steps, warmup_lr): offload_optimizer = {"device": "cpu", "pin_memory": True} config = { @@ -1467,6 +1759,49 @@ def run(reflow): for want, got in zip(expected_group, actual_group): assert torch.equal(got, want), f"NVMe parameter or optimizer state differs at step {step}" + @pytest.mark.parametrize("optimizer_kind", ["adam", "lion"]) + def test_local_gradient_access_matches_zero(self, tmpdir, optimizer_kind): + skip_if_reflow_training_unsupported(optimizer_kind) + if not deepspeed.ops.__compatible_ops__.get(AsyncIOBuilder.NAME, False): + pytest.skip("NVMe offload requires the async_io extension") + width = 384 + + def run(reflow): + torch.manual_seed(1234) + model = ConditionalGradientModel(width) + config = get_variant_config(reflow, optimizer_kind) + config["data_types"] = {"grad_accum_dtype": "bf16"} + config["gradient_clipping"] = 0.1 + config["zero_optimization"]["offload_optimizer"] = { + "device": "nvme", + "nvme_path": str(tmpdir.join("local_reflow" if reflow else "local_zero")) + } + engine, optimizer, _, _ = deepspeed.initialize(model=model, + model_parameters=model.parameters(), + config=config) + try: + param = engine.module.always.weight + group = optimizer.grad_position[optimizer.get_param_id(param)][0] + assert optimizer._swappable_optimizer_subgroup(group) + torch.manual_seed(900) + inputs = torch.randn(2, width, device=engine.device, dtype=torch.bfloat16) + engine.backward(engine(inputs, True)) + gradient = safe_get_local_grad(param).clone() + safe_set_local_grad(param, (-0.5 * gradient).to(torch.bfloat16)) + engine.step() + params = [safe_get_full_fp32_param(p).clone() for p in engine.module.parameters()] + states = [safe_get_full_optimizer_state(p, "exp_avg").clone() for p in engine.module.parameters()] + return gradient, params, states + finally: + engine.destroy() + + expected = run(False) + actual = run(True) + assert torch.equal(expected[0], actual[0]) + for expected_group, actual_group in zip(expected[1:], actual[1:]): + for want, got in zip(expected_group, actual_group): + assert torch.equal(want, got) + class TestReflowMaximizeClientInitialization(DistributedTest): world_size = 1 From 3b4716727890e82d59a03c7991a29ee59c2ee2b4 Mon Sep 17 00:00:00 2001 From: st-bang97 Date: Fri, 20 Nov 2026 12:44:16 +0900 Subject: [PATCH 14/19] Overlap ReFlow Ready updates with backward on a shared optimizer pool Run Ready and Persist on one CPU worker pool while preserving subgroup dependencies and worker affinity. Let gradient norm checks overlap Ready work and propagate worker failures before committing optimizer state. For unclipped, fixed-scale reentrant checkpoints, stage low-precision weights in the existing CPU buffer until recomputation and overflow checks finish. Publish disjoint shards as their workers complete and wait for the accumulated gradient before running Ready on shared weights. Cover checkpoint recomputation, local gradient edits, invalid steps and asynchronous publication against standard ZeRO-3. Signed-off-by: st-bang97 --- deepspeed/runtime/reflow/README.md | 33 +- deepspeed/runtime/reflow/reflow_config.py | 2 +- deepspeed/runtime/reflow/reflow_stage3.py | 634 ++++++++++++---------- deepspeed/runtime/reflow/reflow_utils.py | 6 +- docs/_pages/config-json.md | 2 +- tests/unit/v1/zero/test_reflow.py | 380 ++++++++++++- 6 files changed, 754 insertions(+), 303 deletions(-) diff --git a/deepspeed/runtime/reflow/README.md b/deepspeed/runtime/reflow/README.md index 06eaeb7cc9d6..0f9d705d5444 100644 --- a/deepspeed/runtime/reflow/README.md +++ b/deepspeed/runtime/reflow/README.md @@ -70,8 +70,9 @@ next fwd: the async-state worker runs concurrently with the forward; the param Streams: `copy_grad_stream` (D2H grads), `_bucketwise_h2d_stream` (H2D updated weights, least priority so it never preempts compute), and the standard ZeRO-3 `reduce_and_partition_stream` / -`__allgather_stream`. The CPU side uses a `ThreadPoolExecutor` of bucketwise workers (each pinned to -a disjoint NUMA-local core slice) plus a single chained async-state worker. +`__allgather_stream`. Ready, gradient accumulation and Persist use the same CPU worker pool. +A separate enqueue thread merges ranges and submits work. Each bucketwise team uses its +NUMA-local CPU mask, and a worker restores that mask after running Persist. --- @@ -168,7 +169,7 @@ rejected when main-thread pinning is enabled. The following options allow other | `pin_main_thread` | `true` | Pins the initializing thread to the reserved main CPUs; `engine.destroy()` restores its original affinity. | | `worker_core_type` | `"logical"` | `"physical"` uses one logical CPU per remaining physical core. | | `bucketwise_cores_per_worker` | `8` | Maximum logical CPUs per bucketwise worker; the last mask within a NUMA node may be smaller. | -| `bucketwise_worker_affinity` | `"thread"` | `"task"` assigns CPU masks round-robin; `"thread"` fixes each pool thread to a mask at startup, reducing migrations and preserving its OpenMP team placement. | +| `bucketwise_worker_affinity` | `"thread"` | `"task"` assigns CPU masks round-robin; `"thread"` reuses a fixed mask per thread for bucketwise work. Persist temporarily uses its phase-specific mask. | | `state_update_cores` | `null` | Caps the worker CPU IDs used by the state commit during forward; `null` uses all worker CPUs. | | `state_update_backward_cores` | `null` | Caps the number of worker CPU IDs used by the state commit during backward; `null` uses all worker CPUs. `state_update_cores` still controls its forward mask. | @@ -248,13 +249,22 @@ accumulation, params on GPU, NVMe offload) logs a warning and falls back to the - **Single-GPU is the stress case.** With one GPU the optimizer is the *full* (unpartitioned) model and must hide inside a single backward, so the bucketwise CPU-Adam workers must run truly in parallel across the NUMA-local cores (see the mutex note under Correctness). -- **The state commit can overlap the forward.** By default it can use all worker CPUs in both forward - and backward. Set `state_update_cores` or `state_update_backward_cores` to limit its affinity during - either phase; changes take effect between commit slices. +- **Ready and Persist share one optimizer worker pool.** A pool worker commits resident subgroups in + order during the next forward. Set `state_update_cores` or `state_update_backward_cores` to cap + its CPU team in each phase. A Ready team with disjoint CPUs can start once its subgroup is + committed. Teams whose CPUs overlap either commit mask resume after the batch finishes. + GPU backward and gradient transfers can continue during the commit. - **Gradient clipping re-runs the update inside `step()`.** The bucketwise workers apply the update - during backward, before the global grad norm is known. When a step needs clipping - (`gradient_clipping > 0` and the grad norm exceeds it), the in-flight work is cancelled and every - range is recomputed with the clipped scale in `step()`, so that step pays the full optimizer cost. + during backward, before the global grad norm is known. On a clipped step, `step()` waits for + preview copies to finish before reusing their output buffers. It generates every range with the + clipped scale, including pending ranges that have yet to run Ready. With a fixed loss scale, + checkpointed ranges that first become safe in `step()` can use the final scale on their first + pass. Their boundary norms are already available from backward. + With clipping disabled and a fixed loss scale, Ready can compute checkpointed ranges during + backward when optimizer state is resident and parameters are on the GPU. It writes the existing + CPU output slot. After recomputation and the overflow check, `step()` copies accepted weights + to the GPU as their Ready jobs finish. A weight used by multiple checkpoint segments in the + same micro-step runs Ready once its contributions have accumulated. DeepSpeed defaults `gradient_clipping` to `1.0`; set `"gradient_clipping": 0.0` when clipping is not wanted. On OPT-350m with one RTX 5080, `step` took ~58 ms unclipped vs ~139 ms with every step clipped. @@ -311,9 +321,8 @@ The implementation was built and hardened across many commits; the major themes: - **NUMA affinity** — bind the main thread and per-NUMA-node worker groups to GPU-local cores; pin the main process to the full NUMA-local slice (not only the reserved main cores) so it does not throttle the launch-bound forward. -- **Stream scheduling** — least-priority H2D stream (so weight copies never preempt compute); move - the top-of-step device sync after the CPU step setup; allow more in-flight reduce events; order - overlap_comm all-gathers after the H2D weight writes. +- **Stream scheduling** — allow multiple in-flight reduce events and wait for the gradient-copy stream + after CPU step setup. The least-priority H2D stream publishes the weights before `overlap_comm` all-gathers. - **Concurrency** — narrow the param CPU-Adam mutex to the scalar update so the bucketwise workers run concurrently across the rank's cores (the key to hiding the optimizer when the per-rank shard is large, e.g. single-GPU). diff --git a/deepspeed/runtime/reflow/reflow_config.py b/deepspeed/runtime/reflow/reflow_config.py index e34ea36d2eb0..c3bffcc4a969 100644 --- a/deepspeed/runtime/reflow/reflow_config.py +++ b/deepspeed/runtime/reflow/reflow_config.py @@ -33,7 +33,7 @@ class ReflowConfig(DeepSpeedConfigModel): """Use all worker CPU IDs, or one logical CPU per worker physical core.""" bucketwise_worker_affinity: Literal["task", "thread"] = "thread" - """Choose a CPU mask for each task, or keep each pool thread on its initial mask.""" + """Choose a CPU mask per bucketwise task, or reuse a fixed bucketwise mask on each pool thread.""" bucketwise_cores_per_worker: int = Field(8, ge=1) """Cores per bucketwise optimizer worker. The worker count follows from the cores available diff --git a/deepspeed/runtime/reflow/reflow_stage3.py b/deepspeed/runtime/reflow/reflow_stage3.py index 43e3ce3f1fdb..3c4f32dd0d33 100644 --- a/deepspeed/runtime/reflow/reflow_stage3.py +++ b/deepspeed/runtime/reflow/reflow_stage3.py @@ -6,8 +6,8 @@ import gc import os import threading -from concurrent.futures import ThreadPoolExecutor -from typing import Container, List +from concurrent.futures import CancelledError, Future, ThreadPoolExecutor, as_completed +from typing import Container, List, NamedTuple import psutil import torch @@ -35,6 +35,11 @@ _STATE_COMMIT_SLICE_ELEMS = 1 << 25 +class _StagedReady(NamedTuple): + sub_group_id: int + ranges: list + + class ReflowOptimizer_Stage3(DeepSpeedZeroOptimizer_Stage3): """ZeRO-3 optimizer subclass adding the Reflow async CPU-offload feature. @@ -67,7 +72,7 @@ def __init__(self, module, init_optimizer, param_names, timers, ds_config, reflo self._reflow_window_grad_ids = set() self._reflow_boundary_grad_ids = set() self._reflow_gradient_partitions = None - self._reflow_checkpoint_param_ids = set() + self._reflow_checkpoint_visits = {} self._reflow_modified_gradient_ids = set() self._last_state_update_future = None self._pending_state_updates_by_subgroup = {} @@ -93,7 +98,7 @@ def __init__(self, module, init_optimizer, param_names, timers, ds_config, reflo self.copy_grad_stream = get_accelerator().Stream() if get_accelerator().is_synchronized_device() is False \ else get_accelerator().default_stream() - self._setup_async_state_executor() + self._setup_optimizer_workers() # The stream-level waits in step() do not keep the next forward's all-gather from reading a partition # before its H2D write-back lands; without this host sync OPT-30B showed loss spikes. Leave it on except # for measurement. @@ -127,7 +132,10 @@ def track_forward(sub_module): if not torch.is_grad_enabled(): for param in iter_params(sub_module, recurse=z3_leaf_module(sub_module)): if hasattr(param, "ds_id") and param.requires_grad: - self._reflow_checkpoint_param_ids.add(self.get_param_id(param)) + param_id = self.get_param_id(param) + last_step, _ = self._reflow_checkpoint_visits.get(param_id, (None, False)) + self._reflow_checkpoint_visits[param_id] = (self.micro_step_id, + last_step == self.micro_step_id) return original_forward(sub_module) self.parameter_offload.pre_sub_module_forward_function = track_forward @@ -145,7 +153,7 @@ def _warn_per_param_partition_groups(self): "parallelism) is not validated and may produce wrong results.") return - def _setup_async_state_executor(self): + def _setup_optimizer_workers(self): self._reset_bucketwise_handles() self._worker_cpu_affinity_mask = None self._state_update_cpu_affinity_mask = None @@ -170,6 +178,8 @@ def _setup_async_state_executor(self): backward_count = self._reflow_config.state_update_backward_cores backward_cores = worker_cores[-backward_count:] if backward_count is not None else worker_cores self._state_backward_cpu_affinity_mask = set(backward_cores) + # A running Persist slice may still use its forward mask when backward starts. + self._state_commit_reserved_cpus = set(state_update_cores).union(backward_cores) original_affinity = None if self._reflow_config.pin_main_thread: @@ -198,8 +208,6 @@ def _setup_async_state_executor(self): f"{len(worker_cores)} optimizer-worker cores {sorted(worker_cores)}" f"{', affinity isolation ENABLED' if enable_cpu_affinity else ''}") - self._state_update_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="reflow_state_update") - self._setup_bucketwise_executors() def _setup_bucketwise_executors(self): @@ -248,27 +256,40 @@ def initializer(): self._pin_current_thread(mask) self._bucketwise_update_executor = ThreadPoolExecutor(max_workers=max_bucketwise_workers, - thread_name_prefix="reflow_bucketwise_update", + thread_name_prefix="reflow_optimizer", initializer=initializer) def _submit_bucketwise_task(fn, *args, **kwargs): - if initializer is not None: + commit = self._last_state_update_future + if commit is not None and commit.done(): + commit = None + if initializer is not None and commit is None: return self._bucketwise_update_executor.submit(fn, *args, **kwargs) - # Select the mask only here: selecting again in a caller would skip masks in an even-sized pool. - worker_idx = self._bucketwise_worker_idx - self._bucketwise_worker_idx = (self._bucketwise_worker_idx + 1) % len( - self._bucketwise_worker_cpu_affinity_masks) - affinity_mask = self._bucketwise_worker_cpu_affinity_masks[worker_idx] - - def wrapped_fn(*a, **kw): - self._pin_current_thread(affinity_mask) - return fn(*a, **kw) - - return self._bucketwise_update_executor.submit(wrapped_fn, *args, **kwargs) + mask = None + if initializer is None: + worker_idx = self._bucketwise_worker_idx + masks = self._bucketwise_worker_cpu_affinity_masks + mask = masks[worker_idx] + self._bucketwise_worker_idx = (worker_idx + 1) % len(masks) + + def run(): + if mask is not None: + self._pin_current_thread(mask) + if commit is not None and not commit.done(): + # The entire older commit is already running or queued first. It never waits + # on new work from this pool. Disjoint teams can proceed independently. + try: + cpus = os.sched_getaffinity(0) + except (AttributeError, OSError): + cpus = None + if cpus is None or not self._state_commit_reserved_cpus.isdisjoint(cpus): + commit.result() + return fn(*args, **kwargs) + + return self._bucketwise_update_executor.submit(run) self._bucketwise_update_submit = _submit_bucketwise_task - self._bucketwise_update_futures = [] self._bucketwise_inflight_futures = [] # Backward and step own this registry; executor workers never access it. self._bucketwise_accumulation_futures = {} @@ -283,7 +304,10 @@ def wrapped_fn(*a, **kw): self._bucketwise_enq_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="reflow_bucketwise_enq") self._bucketwise_enq_submit = self._bucketwise_enq_executor.submit - self._bucketwise_group_step_incremented = set() + self._published_ready_groups = set() + self._pending_checkpoint_groups = set() + # An early join retains completed ranges here until their replacements finish. + self._staged_ready_ranges = {} self._bucketwise_group_target_step = {} self._bucketwise_inflight_h2d_events = [] self._bucketwise_cancel_version = 0 @@ -294,7 +318,7 @@ def wrapped_fn(*a, **kw): _DEFAULT_BUCKETWISE_SHARD_ELEMS) self._bucketwise_min_submit_range_elems = _DEFAULT_BUCKETWISE_MIN_SUBMIT_ELEMS self._bucketwise_enqueue_lock = threading.Lock() - self._bucketwise_pending_events = {} + self._bucketwise_last_copy_event_by_group = {} # First real (non-cancel) error raised by a bucketwise worker this iteration; step() # all-reduces a flag derived from it and re-raises so the step aborts on every rank. self._bucketwise_worker_error = None @@ -303,7 +327,6 @@ def wrapped_fn(*a, **kw): def _reset_bucketwise_handles(self): self._bucketwise_update_executor = None self._bucketwise_update_submit = None - self._bucketwise_update_futures = None self._bucketwise_inflight_futures = None self._bucketwise_worker_cpu_affinity_masks = None self._worker_node_groups = None @@ -311,6 +334,7 @@ def _reset_bucketwise_handles(self): self._bucketwise_h2d_stream = None self._bucketwise_enq_executor = None self._bucketwise_enq_submit = None + self._last_enqueue_future = None def destroy(self): """ @@ -327,7 +351,7 @@ def destroy(self): drain() except Exception: pass - for attr in ("_bucketwise_enq_executor", "_bucketwise_update_executor", "_state_update_executor"): + for attr in ("_bucketwise_enq_executor", "_bucketwise_update_executor"): executor = getattr(self, attr, None) if executor is not None: try: @@ -406,14 +430,34 @@ def _pin_current_thread(self, cpu_affinity_mask): except (OSError, AttributeError): pass - def _drain_update_futures_collecting_h2d_events(self, futures): - for f in futures: + def _drain_update_futures_collecting_h2d_events(self, futures, publish_staged=False): + # A drain for a reentrant gradient or a local edit can leave overlapping old + # previews. Join their replacements before copying that output slot. Otherwise + # disjoint shards can start H2D as soon as their own native writer finishes. + publish_each = publish_staged and not any(self._staged_ready_ranges.values()) + if publish_each and self._staged_ready_ranges and len(futures) > 1: + futures = as_completed(futures) + for future in futures: try: - ev = f.result() - if ev is not None: - self._bucketwise_inflight_h2d_events.append(ev) - except Exception: - pass + result = future.result() + if isinstance(result, _StagedReady): + if not publish_each: + self._staged_ready_ranges[result.sub_group_id].extend(result.ranges) + elif self._bucketwise_worker_error is None: + self._publish_staged_ready(result.sub_group_id, result.ranges) + elif result is not None: + self._bucketwise_inflight_h2d_events.append(result) + except CancelledError: + continue + except Exception as error: + self._record_bucketwise_worker_error(error) + if publish_staged and not publish_each and self._bucketwise_worker_error is None: + try: + for group, ranges in self._staged_ready_ranges.items(): + if ranges: + self._publish_staged_ready(group, reflow_utils.merge_contiguous_ranges(ranges)) + except Exception as error: + self._record_bucketwise_worker_error(error) def _coalesce_bucketwise_h2d_events(self): """Return one event covering all pending bucketwise H2D copies.""" @@ -628,6 +672,8 @@ def partition_grads(self, params_to_release: List[Parameter], grad_partitions: L stream_needs_sync = copy_grad_stream != current_stream is_sync_device = get_accelerator().is_synchronized_device() accumulate_submit = getattr(self, "_bucketwise_update_submit", None) + # This output slot is separate from the GPU weights read by checkpoint recomputation. + stage_checkpoints = self.clip_grad <= 0. and not self.dynamic_loss_scale and not self.offload_param for param, grad_partition in zip(params_to_release, grad_partitions): copy_event = None @@ -644,6 +690,14 @@ def partition_grads(self, params_to_release: List[Parameter], grad_partitions: L param_id = self.get_param_id(param) grad_position_entry = self.grad_position[param_id] sub_group_id, dest_offset, _ = grad_position_entry + checkpoint_step, shared = self._reflow_checkpoint_visits.get(param_id, (None, False)) + checkpointed = checkpoint_step is not None + # A shared checkpoint weight can receive multiple reductions in this micro-step. + # Leave its Ready until step() so it only runs on the complete gradient. + enqueue_ready = (is_boundary and (not checkpointed or (stage_checkpoints and not shared)) + and not self._swappable_optimizer_subgroup(sub_group_id)) + stage_checkpoint = enqueue_ready and checkpointed + boundary_grad = is_boundary and (not checkpointed or stage_checkpoint) first_grad = param_id not in self._reflow_window_grad_ids self._reflow_window_grad_ids.add(param_id) if is_boundary and param_id in self._reflow_boundary_grad_ids: @@ -666,7 +720,7 @@ def partition_grads(self, params_to_release: List[Parameter], grad_partitions: L converted_grad = grad_partition.to(self.gradient_accumulation_dtype) else: converted_grad = grad_partition - if self._reflow_checkpoint_param_ids and stream_needs_sync: + if self._reflow_checkpoint_visits and stream_needs_sync: # Reentrant reductions can reuse their GPU source before the async copy finishes. converted_grad = converted_grad.clone() # The base flat grad buffer that has_overflow normally scans is freed on this path, so @@ -695,8 +749,9 @@ def partition_grads(self, params_to_release: List[Parameter], grad_partitions: L copy_grad_stream.wait_stream(current_stream) with get_accelerator().stream(copy_grad_stream): pending_slice.copy_(converted_grad.view(pending_slice.shape), non_blocking=True) - copy_event = get_accelerator().Event() - copy_event.record(copy_grad_stream) + if enqueue_ready: + copy_event = get_accelerator().Event() + copy_event.record(copy_grad_stream) # No gradient accumulation: this micro-step is also the boundary, so use the GPU # grad tensor directly for the norm/enqueue below. if is_boundary: @@ -711,11 +766,13 @@ def partition_grads(self, params_to_release: List[Parameter], grad_partitions: L with get_accelerator().stream(copy_grad_stream): accum_gpu = dst_slice.to(converted_grad.device, non_blocking=True) accum_gpu.add_(converted_grad.view(accum_gpu.shape)) - accum_event = get_accelerator().Event() - accum_event.record(copy_grad_stream) + if stream_needs_sync: + accum_event = get_accelerator().Event() + accum_event.record(copy_grad_stream) dst_slice.copy_(accum_gpu, non_blocking=True) - copy_event = get_accelerator().Event() - copy_event.record(copy_grad_stream) + if enqueue_ready: + copy_event = get_accelerator().Event() + copy_event.record(copy_grad_stream) if stream_needs_sync: current_stream.wait_event(accum_event) # accum_gpu is allocated on copy_grad_stream but read by the grad-norm on @@ -757,18 +814,13 @@ def _accumulate_worker(_copy_event=copy_event, _dst_slice=dst_slice, _src_slice= grad_numel = grad_buffer.numel() if is_boundary: - self.norm_for_param_grads[param_id] = self._constant_buffered_norm2(grad_buffer) - # NVMe subgroups have no resident optimizer state during backward, so their CPU step waits for - # step(); only mark the buffer ready. Other subgroups run the range during backward. self._pending_grad_ready = True - if param_id not in self._reflow_checkpoint_param_ids: + if boundary_grad: self._reflow_boundary_grad_ids.add(param_id) - if (param_id not in self._reflow_checkpoint_param_ids - and not self._swappable_optimizer_subgroup(sub_group_id)): - self._bucketwise_schedule_enqueue_range(sub_group_id, - dest_offset, - grad_numel, - copy_event=copy_event) + if enqueue_ready: + self._bucketwise_schedule_enqueue_range(sub_group_id, dest_offset, grad_numel, copy_event, + stage_checkpoint) + self.norm_for_param_grads[param_id] = self._constant_buffered_norm2(grad_buffer) if not is_sync_device: if param.grad is not None: @@ -785,20 +837,20 @@ def reset_cpu_buffers(self): super().reset_cpu_buffers() self._reflow_window_grad_ids.clear() self._reflow_boundary_grad_ids.clear() - self._reflow_checkpoint_param_ids.clear() + self._reflow_checkpoint_visits.clear() self._reflow_modified_gradient_ids.clear() self._pending_grad_ready = False # Reset per-iteration pending/inflight state. - self._bucketwise_group_step_incremented.clear() + self._published_ready_groups.clear() + self._pending_checkpoint_groups.clear() + self._staged_ready_ranges.clear() self._bucketwise_group_target_step.clear() for sub_group_id in range(len(self._bucketwise_pending_ranges_by_group)): self._bucketwise_pending_ranges_by_group[sub_group_id].clear() self._bucketwise_pending_elems_by_group[sub_group_id] = 0 self._bucketwise_inflight_h2d_events.clear() - self._bucketwise_pending_events.clear() - if getattr(self, "_bucketwise_update_futures", None) is not None: - self._bucketwise_update_futures.clear() + self._bucketwise_last_copy_event_by_group.clear() if self._bucketwise_inflight_futures is not None: self._bucketwise_inflight_futures.clear() self._bucketwise_cancel_version = 0 @@ -818,99 +870,106 @@ def zero_grad(self, set_to_none=True): if event is not None: event.synchronize() self.copy_grad_stream.synchronize() - touched_groups = {self.grad_position[param_id][0] for param_id in self._reflow_boundary_grad_ids} - for sub_group_id in touched_groups: + for sub_group_id in self._published_ready_groups: self._restore_fp16_params_from_master(sub_group_id) if self._reflow_grad_overflow is not None: self._reflow_grad_overflow.zero_() - checkpoint_params = set(self._reflow_checkpoint_param_ids) + checkpoint_visits = self._reflow_checkpoint_visits.copy() worker_error = self._bucketwise_worker_error self.reset_cpu_buffers() self._bucketwise_worker_error = worker_error - self._reflow_checkpoint_param_ids.update(checkpoint_params) + self._reflow_checkpoint_visits.update(checkpoint_visits) return super().zero_grad(set_to_none=set_to_none) def _overflow_clean_up(self, prev_scale): + # A staged CPU result has not changed the GPU weight. Restore resident groups + # that could have published a preview, as well as NVMe parameter partitions. + restore_groups = [ + i for i, flat in enumerate(self.fp16_partitioned_groups_flat) + if flat is None or i in self._published_ready_groups + ] self._reflow_in_overflow_cleanup = True try: - return super()._overflow_clean_up(prev_scale) + super()._overflow_clean_up(prev_scale) finally: self._reflow_in_overflow_cleanup = False + if restore_groups: + if self._bucketwise_h2d_stream is not None: + self._bucketwise_h2d_stream.synchronize() + for sub_group_id in restore_groups: + self._restore_fp16_params_from_master(sub_group_id) # ------------------------------------------------------------------ # # async state update workers # ------------------------------------------------------------------ # - def _maybe_update_async_state(self, sub_group_id, combined_scale=None): - if combined_scale is None: - combined_scale = getattr(self, '_current_combined_scale', self.loss_scale) - - param_group_id = self.sub_group_to_group_id[sub_group_id] - # The commit runs after step() returns, and the engine steps the LR scheduler right after step(), so capture - # this step's hyperparameters now instead of letting the worker read the live param group later. - live_group = self.optimizer.param_groups[param_group_id] - group_hyperparams = {param_group_id: {key: value for key, value in live_group.items() if key != 'params'}} - - def _state_worker(pin_to_worker_cores=False, half_grad_buffer=None, combined_scale=None): - if pin_to_worker_cores: - self._pin_current_thread(self._state_commit_cpu_affinity_mask()) + def _submit_state_updates(self, sub_group_ids, combined_scale): + # Capture the gradient slot and LR scheduler values before step() returns. One pool + # job commits subgroups in order because they temporarily share group['params']. + # Per-subgroup completion still releases readers as soon as their master is ready. + commits = [] + for sub_group_id in sub_group_ids: + group_id = self.sub_group_to_group_id[sub_group_id] + group = self.optimizer.param_groups[group_id] + hyperparams = {key: value for key, value in group.items() if key != 'params'} + grad = self._cpu_grad_double_buffers[sub_group_id][self._active_grad_buffer_idx] + commits.append((sub_group_id, group_id, {group_id: hyperparams}, grad)) + if not commits: + return - original = self.optimizer.param_groups[param_group_id]['params'] + # The executor's own Future covers the last (often only) subgroup. + earlier = {entry[0]: Future() for entry in commits[:-1]} + + def commit_all(): + original_cpus = os.sched_getaffinity(0) if hasattr(os, "sched_getaffinity") else None try: - self.optimizer.param_groups[param_group_id]['params'] = \ - [self.fp32_partitioned_groups_flat[sub_group_id]] - # Align the buffer to param_groups by index, so a param group other than group 0 - # (e.g. the no-decay group of a decay/no-decay split) is updated with its buffer - # and every other group is skipped (None). - buffers = [None] * len(self.optimizer.param_groups) - buffers[param_group_id] = half_grad_buffer - numel = self.fp32_partitioned_groups_flat[sub_group_id].numel() - for start in range(0, numel, _STATE_COMMIT_SLICE_ELEMS): - # Re-pick the cores for every slice so the commit widens as soon as backward starts. - if pin_to_worker_cores: - self._pin_current_thread(self._state_commit_cpu_affinity_mask()) - slice_numel = min(_STATE_COMMIT_SLICE_ELEMS, numel - start) - self.optimizer.step_state_halfgrad(half_grad_buffers=buffers, - combined_scale=combined_scale, - element_range=(start, slice_numel), - group_hyperparams=group_hyperparams) - # Flush the non-temporal (streaming) optimizer-state stores so the updated state - # is globally visible before this worker's future completes, matching the fence the - # foreground param path issues; otherwise a later read can see partial/stale state. - self.optimizer.memory_fence() + for sub_group_id, group_id, hyperparams, grad in commits: + self._commit_subgroup_state(sub_group_id, group_id, hyperparams, grad, combined_scale) + if sub_group_id in earlier: + earlier[sub_group_id].set_result(None) finally: - self.optimizer.param_groups[param_group_id]['params'] = original - - # initialize_optimizer_states gives every subgroup a CPU half-precision grad buffer. - half_grad_buffer = self._cpu_grad_double_buffers[sub_group_id][self._active_grad_buffer_idx] + self._pin_current_thread(original_cpus) - executor = getattr(self, '_state_update_executor', None) - if executor is not None: - previous_future = self._last_state_update_future + try: + tail = self._bucketwise_update_executor.submit(commit_all) + except Exception as error: + tail = Future() + tail.set_exception(error) - def chained_worker(): - # Wait for the previous future so workers complete in submission order. - if previous_future is not None: - previous_future.result() - _state_worker(True, half_grad_buffer, combined_scale) + if earlier: - try: - future = executor.submit(chained_worker) - except Exception as e: - # submit() can fail (e.g. executor shut down); surface it through the all-reduced - # bucketwise flag so every rank aborts together at the next _check, not this one alone. - logger.warning(f"Reflow async state-update submit failed (rank {dist.get_rank()}): {e}") - self._record_state_update_error(e) - return - self._last_state_update_future = future - self._pending_state_updates_by_subgroup[sub_group_id] = future - else: - # Synchronous fallback (no async-state executor). Surface a failure through the same - # all-reduced flag so every rank aborts together at the next _check, rather than this rank - # raising alone and hanging its peers at the following collective. - try: - _state_worker(False, half_grad_buffer, combined_scale) - except Exception as e: - self._record_state_update_error(e) + def release_readers_on_failure(done): + try: + done.result() + except BaseException as error: + # Also release readers if the executor failed before commit_all could start. + for completed in earlier.values(): + if not completed.done(): + completed.set_exception(error) + + tail.add_done_callback(release_readers_on_failure) + self._pending_state_updates_by_subgroup.update(earlier) + self._pending_state_updates_by_subgroup[commits[-1][0]] = tail + self._last_state_update_future = tail + + def _commit_subgroup_state(self, sub_group_id, group_id, hyperparams, grad, combined_scale): + group = self.optimizer.param_groups[group_id] + original_params = group['params'] + param = self.fp32_partitioned_groups_flat[sub_group_id] + group['params'] = [param] + try: + buffers = [None] * len(self.optimizer.param_groups) + buffers[group_id] = grad + numel = param.numel() + for start in range(0, numel, _STATE_COMMIT_SLICE_ELEMS): + self._pin_current_thread(self._state_commit_cpu_affinity_mask()) + slice_numel = min(_STATE_COMMIT_SLICE_ELEMS, numel - start) + self.optimizer.step_state_halfgrad(half_grad_buffers=buffers, + combined_scale=combined_scale, + element_range=(start, slice_numel), + group_hyperparams=hyperparams) + self.optimizer.memory_fence() + finally: + group['params'] = original_params def _record_state_update_error(self, error): # Surface a state-update worker failure through the same all-reduced flag the bucketwise @@ -939,7 +998,7 @@ def _wait_for_pending_state_updates(self, sub_group_id=None): if future is None: return try: - # The last future chains all previous ones, so waiting for it drains them all. + # One pool job owns every resident subgroup in this step. future.result() except Exception as e: if dist.get_rank() == 0: @@ -989,41 +1048,46 @@ def _complete_pending_gradient_window(self): if position is not None and position[2] > 0: self._reflow_gradient_partitions.append((param_id, sub_group_id, position[1], position[2])) if len(self._reflow_boundary_grad_ids) == len(self._reflow_gradient_partitions): - return False + return False, self._reflow_modified_gradient_ids + ready_after_norm = self._reflow_modified_gradient_ids.copy() + enqueued_ready = False for param_id, sub_group_id, offset, numel in self._reflow_gradient_partitions: if param_id in self._reflow_boundary_grad_ids: continue grad_buffer = self._get_cpu_grad_buffer(sub_group_id, pending=True).narrow(0, offset, numel) + has_boundary_norm = (param_id in self.norm_for_param_grads + and param_id not in self._reflow_modified_gradient_ids) if param_id not in self._reflow_window_grad_ids: if self._single_grad_buffer: self._wait_for_pending_state_updates(sub_group_id=sub_group_id) grad_buffer.zero_() self.norm_for_param_grads[param_id] = 0.0 - else: + elif not has_boundary_norm: + # A local gradient setter can leave a norm from an earlier micro-step. self._wait_for_accum_gradient(param_id) grad_for_norm = grad_buffer.to(get_accelerator().current_device_name(), non_blocking=True) self.norm_for_param_grads[param_id] = self._constant_buffered_norm2(grad_for_norm) self._pending_grad_ready = True if not self._swappable_optimizer_subgroup(sub_group_id): - self._bucketwise_schedule_enqueue_range(sub_group_id, offset, numel) - return True - - def _activate_pending_cpu_grads_if_ready(self, flush_completed_window=False): - if not self._pending_grad_ready: - return False - # Gradient buffers are written directly by the bucketwise workers; drain them and flip - # the active/pending double buffer. + # Checkpointed gradients with a final norm have no backward or norm computation left + # to overlap here. Use the final scale for their first Ready if clipping is enabled. + if has_boundary_norm and self.clip_grad > 0.: + ready_after_norm.add(param_id) + else: + self._bucketwise_schedule_enqueue_range(sub_group_id, offset, numel) + enqueued_ready = True + return enqueued_ready, ready_after_norm + + def _activate_pending_cpu_grads_if_ready(self, flush_pending): + # The enqueue thread chooses the gradient slot at submission. Once it drains, every + # running Ready owns its slot and can finish while the host decides clipping/overflow. self._bucketwise_drain_enq_executor() - if flush_completed_window: - # Start Ready while the GPU computes norms for earlier-micro-step gradients. - self._bucketwise_flush_all_pending(force=True, use_pending_buffer=True, combined_scale=self.loss_scale) - self._bucketwise_wait_inflight_updates() - # Single-buffer mode has only slot 0: keep the active index pinned there (no flip). The - # workers already wrote the params into fp16_flat, and Phase-2 reads the grads from slot 0. - if not self._single_grad_buffer: - self._active_grad_buffer_idx = 1 - self._active_grad_buffer_idx - self._pending_grad_ready = False - return True + if self._pending_grad_ready: + if flush_pending: + self._bucketwise_flush_all_pending(force=True, use_pending_buffer=True, combined_scale=self.loss_scale) + if not self._single_grad_buffer: + self._active_grad_buffer_idx = self._pending_grad_buffer_idx + self._pending_grad_ready = False # ------------------------------------------------------------------ # # cpu_bucketwise pipeline @@ -1035,28 +1099,36 @@ def _bucketwise_drain_enq_executor(self): flushing we must ensure every gradient range has landed in the pending structures, otherwise a range is dropped and the parameter update is silently skipped. """ - enq_executor = getattr(self, "_bucketwise_enq_executor", None) - if enq_executor is None: - return - try: - sentinel = enq_executor.submit(lambda: None) - sentinel.result(timeout=30.0) - except Exception as e: - self._record_bucketwise_worker_error(e) - - def _bucketwise_schedule_enqueue_range(self, sub_group_id, dest_offset, num_elements, copy_event=None): + # A single FIFO worker makes the last real job a fence for all earlier enqueues. + future = self._last_enqueue_future + if future is not None: + try: + future.result(timeout=30.0) + except Exception as e: + self._record_bucketwise_worker_error(e) + else: + self._last_enqueue_future = None + + def _bucketwise_schedule_enqueue_range(self, + sub_group_id, + dest_offset, + num_elements, + copy_event=None, + stage_checkpoint=False): """Schedule a range enqueue off the main thread (falls back to sync if no executor).""" if not self.is_gradient_accumulation_boundary(): return enq_submit = getattr(self, "_bucketwise_enq_submit", None) if enq_submit is None: - self._bucketwise_enqueue_range(sub_group_id, dest_offset, num_elements, copy_event) + self._bucketwise_enqueue_range(sub_group_id, dest_offset, num_elements, copy_event, stage_checkpoint) return try: - enq_submit(self._bucketwise_enqueue_range, sub_group_id, dest_offset, num_elements, copy_event) + self._last_enqueue_future = enq_submit(self._bucketwise_enqueue_range, sub_group_id, dest_offset, + num_elements, copy_event, stage_checkpoint) except Exception: - self._bucketwise_enqueue_range(sub_group_id, dest_offset, num_elements, copy_event) + self._bucketwise_drain_enq_executor() + self._bucketwise_enqueue_range(sub_group_id, dest_offset, num_elements, copy_event, stage_checkpoint) def _bucketwise_get_valid_partition_element_count(self, sub_group_id: int) -> int: """Return the flat-buffer bound, including padding between parameters.""" @@ -1076,7 +1148,7 @@ def _bucketwise_chunk_update_worker(self, work_item): ranges = work_item["ranges"] grad_buffer_index = work_item["grad_buffer_index"] combined_scale = work_item["combined_scale"] - copy_events = work_item.get("copy_events", []) + last_copy_event = work_item["last_copy_event"] cancel_version = work_item.get("cancel_version", 0) increment_step = work_item.get("increment_step", False) target_step = work_item.get("target_step", None) @@ -1085,7 +1157,6 @@ def _bucketwise_chunk_update_worker(self, work_item): return None # Wait for the GPU->CPU grad copy (only the last event, the stream is sequential). - last_copy_event = copy_events[-1] if copy_events else None if last_copy_event is not None: last_copy_event.synchronize() @@ -1201,24 +1272,9 @@ def _bucketwise_chunk_update_worker(self, work_item): if fp16_flat is None: return None - src = half_params_buffer.data.view(-1) - dst = fp16_flat.data.view(-1) - - merged_ranges = reflow_utils.merge_contiguous_ranges(ranges) - stream = getattr(self, "_bucketwise_h2d_stream", None) - if stream is None: - stream = get_accelerator().current_stream() - - with get_accelerator().stream(stream): - for off, sz in merged_ranges: - dst.narrow(0, off, sz).copy_(src.narrow(0, off, sz), non_blocking=True) - if not get_accelerator().is_synchronized_device(): - h2d_event = get_accelerator().Event() - h2d_event.record(stream) - else: - h2d_event = None - - return h2d_event + if work_item["stage_copy"]: + return _StagedReady(sub_group_id, ranges) + return self._copy_ready_ranges(fp16_flat, half_params_buffer, ranges) except Exception as e: # A cooperative cancel (version bump) can race the kernel and surface as a transient # error; if this work item has been cancelled, treat it as a clean no-op like the @@ -1230,7 +1286,32 @@ def _bucketwise_chunk_update_worker(self, work_item): logger.warning(f"Reflow bucketwise worker error (rank {dist.get_rank()}): {e}") return None - def _bucketwise_enqueue_range(self, sub_group_id, dest_offset, num_elements, copy_event=None): + def _copy_ready_ranges(self, fp16_flat, output, ranges): + stream = self._bucketwise_h2d_stream + if stream is None: + stream = get_accelerator().current_stream() + dst, src = fp16_flat.detach().view(-1), output.detach().view(-1) + with get_accelerator().stream(stream): + for offset, size in ranges: + dst.narrow(0, offset, size).copy_(src.narrow(0, offset, size), non_blocking=True) + if not get_accelerator().is_synchronized_device(): + event = get_accelerator().Event() + event.record(stream) + return event + + def _publish_staged_ready(self, sub_group_id, ranges): + self._published_ready_groups.add(sub_group_id) + output = self._cpu_grad_double_buffers[sub_group_id][1 - self._active_grad_buffer_idx] + event = self._copy_ready_ranges(self.fp16_partitioned_groups_flat[sub_group_id], output, ranges) + if event is not None: + self._bucketwise_inflight_h2d_events.append(event) + + def _bucketwise_enqueue_range(self, + sub_group_id, + dest_offset, + num_elements, + copy_event=None, + stage_checkpoint=False): # Accumulate a scheduled grad range; flush once the shard threshold is reached. try: clipped_range = self._bucketwise_clip_range_to_valid_partition(sub_group_id, dest_offset, num_elements) @@ -1246,8 +1327,10 @@ def _bucketwise_enqueue_range(self, sub_group_id, dest_offset, num_elements, cop self._bucketwise_pending_ranges_by_group.append([]) self._bucketwise_pending_elems_by_group.append(0) + if stage_checkpoint: + self._pending_checkpoint_groups.add(sub_group_id) if copy_event is not None: - self._bucketwise_pending_events.setdefault(sub_group_id, []).append(copy_event) + self._bucketwise_last_copy_event_by_group[sub_group_id] = copy_event self._bucketwise_pending_ranges_by_group[sub_group_id].append((dest_offset, num_elements)) self._bucketwise_pending_elems_by_group[sub_group_id] += num_elements @@ -1306,16 +1389,11 @@ def _bucketwise_flush_group(self, grad_buffer_index = self._pending_grad_buffer_idx if use_pending_buffer else self._active_grad_buffer_idx - copy_events_snapshot = self._bucketwise_pending_events.get(sub_group_id, []) - self._bucketwise_pending_events[sub_group_id] = [] + last_copy_event = self._bucketwise_last_copy_event_by_group.pop(sub_group_id, None) lock = self._get_enqueue_lock() def _prepare_state_and_params(): - increment_step = (sub_group_id not in self._bucketwise_group_step_incremented) - if increment_step: - self._bucketwise_group_step_incremented.add(sub_group_id) - param_group_id = self.sub_group_to_group_id[sub_group_id] group = self.optimizer.param_groups[param_group_id] # The previous step's async state worker may still be iterating group['params']. @@ -1331,7 +1409,8 @@ def _prepare_state_and_params(): # at the end of step() instead of mutating it in the worker. current_step = int(state.get('step', 0)) target_step = self._bucketwise_group_target_step.get(sub_group_id, None) - if target_step is None: + increment_step = target_step is None + if increment_step: target_step = current_step + 1 self._bucketwise_group_target_step[sub_group_id] = target_step @@ -1357,12 +1436,23 @@ def _prepare_state_and_params(): return None increment_step, target_step, lr, beta1, beta2, eps, weight_decay, bias_correction, maximize = result + # A mixed shard can include weights a checkpoint will gather again. A rerun + # after a local edit can also overwrite staged output in this subgroup. + stage_copy = sub_group_id in self._pending_checkpoint_groups or (not use_pending_buffer + and sub_group_id in self._staged_ready_ranges) + if not self._bucketwise_pending_ranges_by_group[sub_group_id]: + self._pending_checkpoint_groups.discard(sub_group_id) + if stage_copy: + self._staged_ready_ranges.setdefault(sub_group_id, []) + else: + self._published_ready_groups.add(sub_group_id) work_item = { + "stage_copy": stage_copy, "sub_group_id": sub_group_id, "ranges": submit_ranges, "grad_buffer_index": grad_buffer_index, "combined_scale": combined_scale, - "copy_events": copy_events_snapshot, + "last_copy_event": last_copy_event, "cancel_version": getattr(self, "_bucketwise_cancel_version", 0), "increment_step": increment_step, "target_step": target_step, @@ -1376,8 +1466,6 @@ def _prepare_state_and_params(): } future = self._bucketwise_update_submit(self._bucketwise_chunk_update_worker, work_item) - if getattr(self, "_bucketwise_update_futures", None) is not None: - self._bucketwise_update_futures.append(future) self._bucketwise_inflight_futures.append(future) return future @@ -1389,7 +1477,7 @@ def _bucketwise_flush_all_pending(self, force=False, use_pending_buffer=True, co combined_scale=combined_scale) def _bucketwise_cancel_inflight_updates(self): - # Best-effort cancel of inflight workers when clipping is needed. + # An explicit zero_grad also discards previews that are already running. self._bucketwise_cancel_version += 1 for f in list(getattr(self, "_bucketwise_inflight_futures", [])): try: @@ -1423,19 +1511,18 @@ def _ensure_bucketwise_group_step(self, sub_group_id): state = self.optimizer._ensure_param_state(param) self._bucketwise_group_target_step[sub_group_id] = int(state.get('step', 0)) + 1 - def _bucketwise_wait_inflight_updates(self): + def _bucketwise_wait_inflight_updates(self, discard_queued=False, publish_staged=False): # Wait for submitted bucketwise work (optimizer + H2D submit). H2D completion itself is # synchronized later via CUDA events. - futures = list(getattr(self, "_bucketwise_update_futures", []) or []) - if not futures: - futures = list(getattr(self, "_bucketwise_inflight_futures", []) or []) - - self._drain_update_futures_collecting_h2d_events(futures) - - if getattr(self, "_bucketwise_update_futures", None) is not None: - self._bucketwise_update_futures.clear() - self._bucketwise_inflight_futures.clear() + futures = self._bucketwise_inflight_futures + if not futures and not (publish_staged and self._staged_ready_ranges): + return + if discard_queued: + for future in futures: + future.cancel() + self._drain_update_futures_collecting_h2d_events(futures, publish_staged=publish_staged) + futures.clear() def _nvme_optimizer_step_subgroups(self, combined_scale, timer_names): """NVMe optimizer offload: a swappable-optimizer subgroup's state (fp32 master + the optimizer @@ -1478,14 +1565,16 @@ def _nvme_optimizer_step_subgroups(self, combined_scale, timer_names): self._bucketwise_commit_group_steps() # Optimizer-state (momentum) update; then join both the param-update worker and the # state worker before swapping the now-final state out to nvme. - self._maybe_update_async_state(sub_group_id, combined_scale) + self._submit_state_updates([sub_group_id], combined_scale) self._wait_for_pending_state_updates(sub_group_id=sub_group_id) self._optimizer_states_and_gradient_swap_out(sub_group_id, timer_names) def _bucketwise_run_full_partition_updates(self, combined_scale, param_ids=None): - # Re-shard full groups for clipping, or only changed gradients for local API updates. + # An earlier H2D can still read the pinned output that the new Ready kernels will overwrite. + if param_ids is None or self._reflow_modified_gradient_ids: + for event in self._coalesce_bucketwise_h2d_events(): + event.synchronize() - full_update_futures = [] for sub_group_id in range(len(self.fp16_groups)): if self._swappable_optimizer_subgroup(sub_group_id): continue # nvme optimizer subgroups are handled in _nvme_optimizer_step_subgroups @@ -1514,26 +1603,20 @@ def _bucketwise_run_full_partition_updates(self, combined_scale, param_ids=None) if shard_elems >= self._bucketwise_element_shard_size: self._bucketwise_pending_ranges_by_group[sub_group_id] = shard_ranges self._bucketwise_pending_elems_by_group[sub_group_id] = shard_elems - future = self._bucketwise_flush_group(sub_group_id, - force=True, - use_pending_buffer=False, - combined_scale=combined_scale) - if future is not None: - full_update_futures.append(future) + self._bucketwise_flush_group(sub_group_id, + force=True, + use_pending_buffer=False, + combined_scale=combined_scale) shard_ranges = [] shard_elems = 0 if shard_ranges: self._bucketwise_pending_ranges_by_group[sub_group_id] = shard_ranges self._bucketwise_pending_elems_by_group[sub_group_id] = shard_elems - future = self._bucketwise_flush_group(sub_group_id, - force=True, - use_pending_buffer=False, - combined_scale=combined_scale) - if future is not None: - full_update_futures.append(future) - - self._drain_update_futures_collecting_h2d_events(full_update_futures) + self._bucketwise_flush_group(sub_group_id, + force=True, + use_pending_buffer=False, + combined_scale=combined_scale) def backward_prologue(self): # The pending state commit no longer overlaps a forward, so let it use every worker core. @@ -1626,23 +1709,17 @@ def step(self, closure=None): """ self._wait_for_accum_gradient() self._wait_for_pending_state_updates() - # This setup only touches param handles and the FP32 master, so run it before the device sync to overlap - # the GPU drain from backward. Everything below that reads GPU results still follows the sync. self._pre_step() self._partition_all_parameters() - get_accelerator().synchronize() - completed_window = self._complete_pending_gradient_window() - bucketwise_drained = self._activate_pending_cpu_grads_if_ready(flush_completed_window=completed_window) - # Activation already joined the backward workers when it flipped the buffers. Otherwise - # join them before overflow cleanup discards their handles. - if not bucketwise_drained: - self._bucketwise_drain_enq_executor() - self._bucketwise_wait_inflight_updates() - # Workers swallow their own exceptions (a cancel and a real error both return None), so - # surface any real kernel/OOM failure here and abort deterministically on all ranks before - # the overflow check advances the loss scale / optimizer state. - self._check_bucketwise_worker_error() - + # The backward epilogue orders the reductions. Missing gradients and NVMe subgroups + # can read the host buffers without a Ready event, so finish their D2H writes. + if self.copy_grad_stream is not None: + self.copy_grad_stream.synchronize() + enqueued_ready, ready_after_norm = self._complete_pending_gradient_window() + # With a fixed unclipped scale, even a below-threshold tail already knows its + # Ready transform. Publish from the captured slot while the GPU finishes the norm. + flushed_before_norm = enqueued_ready or (self.clip_grad <= 0. and not self.dynamic_loss_scale) + self._activate_pending_cpu_grads_if_ready(flush_pending=flushed_before_norm) self._overflow_check_and_loss_scale_update(update_scale=False) scaled_global_grad_norm = None if not self.overflow: @@ -1651,50 +1728,55 @@ def step(self, closure=None): if is_invalid_grad_norm(scaled_global_grad_norm): self.overflow = True + if self.overflow: + # Cleanup drops the work handles, so collect real failures before restoring weights. + self._bucketwise_wait_inflight_updates(discard_queued=True) + self._check_bucketwise_worker_error() + preview_scale = self.loss_scale + # ZeRO uses the updated scale for a successful step. Keep the scaler's counters + # as well as its scale recoverable until the final Ready succeeds on every rank. + scaler_state = vars(self.loss_scaler).copy() if self.dynamic_loss_scale and not self.overflow else None if self._loss_scale_update_and_overflow_cleanup(): if self.swap_optimizer: self.optimizer_swapper.log_timers() - # Discard the step like the base optimizer. The workers already wrote new FP16/BF16 params to the GPU - # during backward, so restore them from the untouched FP32 master. - self._bucketwise_cancel_version += 1 - if not get_accelerator().is_synchronized_device(): - get_accelerator().synchronize() - for sub_group_id in range(len(self.fp16_groups)): - self._restore_fp16_params_from_master(sub_group_id) return - self._global_grad_norm = scaled_global_grad_norm / self.loss_scale + global_grad_norm = scaled_global_grad_norm / self.loss_scale combined_scale = self.loss_scale - needs_clipping = False if self.clip_grad > 0.: # norm is in fact norm*scale, so unscale. - clip = ((scaled_global_grad_norm / self.loss_scale) + 1e-6) / self.clip_grad - # Re-run the update exactly when the clip factor changes the scale, like the base optimizer. A plain - # norm > clip_grad test misses norms just below the threshold, which the base still clips, and would - # commit the clipped state under params that were computed unclipped during backward. - needs_clipping = clip > 1.0 - clip = max(clip, 1.0) - combined_scale = clip * self.loss_scale + clip = (global_grad_norm + 1e-6) / self.clip_grad + if clip > 1.0: + combined_scale = clip * self.loss_scale self._current_combined_scale = combined_scale - self._bucketwise_flush_all_pending(force=True, use_pending_buffer=False, combined_scale=self.loss_scale) - if needs_clipping: - # cancel() does not wait. Join the cancelled workers first so their unclipped H2D writes are enqueued - # before the clipped re-run's and cannot land last. - self._bucketwise_cancel_inflight_updates() - self._bucketwise_wait_inflight_updates() + if combined_scale != preview_scale: + # Clipping and dynamic scale growth both invalidate old-scale previews. Join + # started work before the final pass fences H2D and reuses its pinned output. + self._bucketwise_wait_inflight_updates(discard_queued=True) self._bucketwise_run_full_partition_updates(combined_scale=combined_scale) - elif self._reflow_modified_gradient_ids: - # Unchanged ranges still need their original Ready work to finish. - self._bucketwise_wait_inflight_updates() - self._bucketwise_run_full_partition_updates(combined_scale=combined_scale, - param_ids=self._reflow_modified_gradient_ids) + else: + if not flushed_before_norm: + self._bucketwise_flush_all_pending(force=True, + use_pending_buffer=False, + combined_scale=self.loss_scale) + if ready_after_norm: + if self._reflow_modified_gradient_ids: + self._bucketwise_wait_inflight_updates() + self._bucketwise_run_full_partition_updates(combined_scale=combined_scale, param_ids=ready_after_norm) timer_names = set() # Param updates already ran bucketwise during backward; here we only commit per-group # step counters and submit the deferred async state updates. - self._bucketwise_wait_inflight_updates() + self._bucketwise_wait_inflight_updates(publish_staged=True) + try: + self._check_bucketwise_worker_error() + except Exception: + if scaler_state is not None: + vars(self.loss_scaler).update(scaler_state) + raise + self._global_grad_norm = global_grad_norm # NVMe optimizer subgroups deferred their CPU-Adam (state not resident during backward); run # it now with the state swapped in around it, before committing step counters / the async loop. if self.swap_optimizer: @@ -1706,22 +1788,22 @@ def step(self, closure=None): self._bucketwise_commit_group_steps() # The commits submitted below overlap the next forward until its backward starts. self._state_commit_overlaps_forward = True - for sub_group_id in reversed(range(len(self.fp16_groups))): - if self._swappable_optimizer_subgroup(sub_group_id): - continue # nvme: already updated above with its state swapped in - self._maybe_update_async_state(sub_group_id, combined_scale) + resident_groups = (i for i in reversed(range(len(self.fp16_groups))) + if not self._swappable_optimizer_subgroup(i)) + self._submit_state_updates(resident_groups, combined_scale) if self._bucketwise_inflight_h2d_events: - # Instead of blocking on the workers' H2D copies, make every stream that reads the params wait on them. - # With overlap_comm the all-gather has its own stream, so a compute-stream wait alone is not enough. + # Host completion covers every reader. In asynchronous mode the next forward's + # compute and all-gather and the next gradient-slot reuse each need a stream edge. h2d_events = self._coalesce_bucketwise_h2d_events() - compute_stream = get_accelerator().current_stream() - for h2d_event in h2d_events: - if h2d_event is not None: - if self._sync_bucketwise_h2d_before_forward: - h2d_event.synchronize() - compute_stream.wait_event(h2d_event) - self.copy_grad_stream.wait_event(h2d_event) - self._get_param_coordinator().wait_for_external_allgather_dependencies(h2d_events) + if self._sync_bucketwise_h2d_before_forward: + for event in h2d_events: + event.synchronize() + else: + compute_stream = get_accelerator().current_stream() + for event in h2d_events: + compute_stream.wait_event(event) + self.copy_grad_stream.wait_event(event) + self._get_param_coordinator().wait_for_external_allgather_dependencies(h2d_events) # NVMe param offload: the bucketwise workers leave the updated FP16/BF16 weights in the CPU # half buffer (an nvme subgroup has no GPU param to H2D into), so swap them out to nvme here, # on the main thread -- the partitioned param swapper holds single shared mutable state and is diff --git a/deepspeed/runtime/reflow/reflow_utils.py b/deepspeed/runtime/reflow/reflow_utils.py index c8b05f41b927..8b4d4af5c478 100644 --- a/deepspeed/runtime/reflow/reflow_utils.py +++ b/deepspeed/runtime/reflow/reflow_utils.py @@ -429,15 +429,15 @@ def plan_cpu_core_layout(main_thread_cores, def merge_contiguous_ranges(ranges): - # Merge contiguous (offset, size) tuples to reduce copy call overhead. + # Repeated gradients can replace part of a staged range in the same output slot. if not ranges: return [] ranges_sorted = sorted(ranges, key=lambda x: x[0]) merged = [] cur_off, cur_sz = ranges_sorted[0] for off, sz in ranges_sorted[1:]: - if off == cur_off + cur_sz: - cur_sz += sz + if off <= cur_off + cur_sz: + cur_sz = max(cur_sz, off + sz - cur_off) else: merged.append((cur_off, cur_sz)) cur_off, cur_sz = off, sz diff --git a/docs/_pages/config-json.md b/docs/_pages/config-json.md index 62fc66f9c03a..677283573939 100644 --- a/docs/_pages/config-json.md +++ b/docs/_pages/config-json.md @@ -775,7 +775,7 @@ The `reflow` block enables it, so an empty block is enough to run with the defau | Description | Default | | ----------- | ------- | -| Assign a CPU mask per submitted task (`task`) or pin each pool thread to its initial mask (`thread`). | `"thread"` | +| Assign a CPU mask per bucketwise task (`task`) or reuse a fixed bucketwise mask on each pool thread (`thread`). A thread running a state commit temporarily uses the commit mask. | `"thread"` | ***bucketwise_cores_per_worker***: [integer] diff --git a/tests/unit/v1/zero/test_reflow.py b/tests/unit/v1/zero/test_reflow.py index 33df59ef794a..8ff8d7d44f5d 100644 --- a/tests/unit/v1/zero/test_reflow.py +++ b/tests/unit/v1/zero/test_reflow.py @@ -12,6 +12,7 @@ import threading import weakref from concurrent.futures import Future, ThreadPoolExecutor +from contextlib import ExitStack from unittest.mock import Mock, patch from types import SimpleNamespace @@ -33,6 +34,7 @@ from deepspeed.runtime.reflow.reflow_cpu_lion import ReflowCPULion from deepspeed.runtime.reflow.reflow_stage3 import ReflowOptimizer_Stage3 from deepspeed.runtime.reflow import reflow_utils +from deepspeed.runtime.utils import combine_grad_norm_groups from deepspeed.runtime.zero.stage3 import DeepSpeedZeroOptimizer_Stage3 from deepspeed.runtime.zero.muon.muon_optimizer import MuonWithAuxAdam from deepspeed.runtime.zero.utils import ZeRORuntimeException @@ -634,6 +636,149 @@ def run(reflow): assert torch.equal(got, want), f"fp32 param {index} differs" +@needs_gpu_accelerator +class TestReflowSharedOptimizerWorker(DistributedTest): + world_size = 1 + + @pytest.mark.parametrize("invalid", [False, True]) + def test_norm_progresses_while_ready_is_running(self, invalid): + # A running preview must allow the clipping/overflow decision to proceed, yet its + # late weight publication must never overwrite the clipped or restored weights. + skip_if_reflow_training_unsupported() + torch.manual_seed(1234) + model = SimpleModel(hidden_dim=16, nlayers=4) + batches = make_batches(16, count=3) + + def run(reflow): + config = get_offload_clip_config(reflow, gradient_clipping=0.01, sub_group_size=512) + config["zero_optimization"]["reduce_bucket_size"] = 128 + net = copy.deepcopy(model) + engine, opt, _, _ = deepspeed.initialize(model=net, model_parameters=net.parameters(), config=config) + snapshots = [] + try: + for index, (inputs, labels) in enumerate(batches): + loss = engine(inputs, labels) + if index == 1 and invalid: + loss = loss * float("inf") + if reflow and index == 1: + native = opt.optimizer.ds_opt_adam + ready = native.reflow_adam_update_params_halfgrad + started, norm_finished = threading.Event(), threading.Event() + + def delayed_ready(*args): + started.set() + if not norm_finished.wait(10): + norm_finished.set() + raise RuntimeError("gradient norm waited for a running Ready") + return ready(*args) + + def observe_norm(*args): + norm = combine_grad_norm_groups(*args) + norm_finished.set() + return norm + + with patch.object(native, "reflow_adam_update_params_halfgrad", delayed_ready), \ + patch("deepspeed.runtime.reflow.reflow_stage3.combine_grad_norm_groups", observe_norm): + engine.backward(loss) + assert started.wait(10) + engine.step() + else: + engine.backward(loss) + engine.step() + for param in net.parameters(): + snapshots.extend([ + param.ds_tensor.detach().clone(), + safe_get_full_fp32_param(param).clone(), + safe_get_full_optimizer_state(param, "exp_avg").clone(), + safe_get_full_optimizer_state(param, "exp_avg_sq").clone(), + ]) + steps = [int(opt.optimizer.state[p]["step"]) for p in opt.fp32_partitioned_groups_flat] + return snapshots, steps, engine.skipped_steps + finally: + engine.destroy() + + expected, expected_steps, expected_skips = run(False) + actual, steps, skips = run(True) + assert steps == expected_steps and skips == expected_skips == int(invalid) + for want, got in zip(expected, actual): + torch.testing.assert_close(got, want, rtol=0, atol=0) + + @pytest.mark.parametrize("disjoint_teams", [False, True]) + def test_delayed_commit(self, disjoint_teams): + # Same-core Ready must wait for Persist. A Ready on disjoint CPUs with a + # committed master must be able to finish while a later subgroup is stalled. + skip_if_reflow_training_unsupported() + torch.manual_seed(1234) + model = SimpleModel(hidden_dim=512, nlayers=3) + batches = make_batches(512, count=3) + config = get_variant_config(False, "adam") + config["zero_optimization"].update(sub_group_size=262144, reduce_bucket_size=262144) + expected = train_and_collect(copy.deepcopy(model), config, batches) + cpus, _ = available_physical_cpus() + if disjoint_teams and len(cpus) < 4: + pytest.skip("requires a main CPU and three optimizer CPU teams") + config["zero_optimization"]["reflow"] = { + "main_thread_cores": 1, + "bucketwise_cores_per_worker": 1, + "state_update_cores": 1, + "state_update_backward_cores": 1, + } + last_commit_cpus, conflicting_cpus = set(), set() + started, disjoint_ready, release = threading.Event(), threading.Event(), threading.Event() + workers = {"params": set(), "state": set()} + engine = None + try: + os.sched_setaffinity(0, sorted(cpus)[:4 if disjoint_teams else 1]) + engine, optimizer, _, _ = deepspeed.initialize(model=model, + model_parameters=model.parameters(), + config=config) + native = optimizer.optimizer.ds_opt_adam + ready, persist = native.reflow_adam_update_params_halfgrad, native.reflow_adam_update_state_halfgrad + last_master = optimizer.fp32_partitioned_groups_flat[0].data_ptr() + + def record_ready(*args, **kwargs): + workers["params"].add(threading.get_native_id()) + if started.is_set() and not release.is_set(): + mask = os.sched_getaffinity(0) + conflicting_cpus.update(mask & last_commit_cpus) + if mask.isdisjoint(last_commit_cpus): + disjoint_ready.set() + return ready(*args, **kwargs) + + def delay_last_commit(*args, **kwargs): + workers["state"].add(threading.get_native_id()) + if args[8].data_ptr() == last_master and not started.is_set(): + last_commit_cpus.update(os.sched_getaffinity(0)) + started.set() + assert release.wait(30), "next backward did not finish with Persist outstanding" + return persist(*args, **kwargs) + + with patch.object(native, "reflow_adam_update_params_halfgrad", record_ready), \ + patch.object(native, "reflow_adam_update_state_halfgrad", delay_last_commit): + for step, batch in enumerate(batches): + if step == 1: + assert started.wait(30) + loss = engine(*batch) + engine.backward(loss) + if step == 1: + if disjoint_teams: + assert disjoint_ready.wait(20), "independent Ready was blocked by the later subgroup" + release.set() + engine.step() + assert torch.equal(loss.detach(), expected["losses"][step]) + for param, want in zip(model.parameters(), expected["fp32_params"]): + assert torch.equal(safe_get_full_fp32_param(param), want) + assert not conflicting_cpus + if not disjoint_teams: + assert workers["params"] == workers["state"] + assert len(workers["state"]) == 1 + finally: + release.set() + if engine is not None: + engine.destroy() + os.sched_setaffinity(0, cpus) + + @pytest.mark.parametrize("worker_affinity", ["task", "thread"]) @pytest.mark.parametrize("worker_type", ["logical", "physical"]) @needs_gpu_accelerator @@ -1320,6 +1465,37 @@ def test_parameter_and_state_access_report_failed_commit(self): finally: engine.destroy() + @needs_gpu_accelerator + def test_failed_native_commit_aborts_next_step(self): + # Fail partway through a shared Persist batch. Readers on every rank, including + # readers of a later subgroup, must be released and the next step must abort. + skip_if_reflow_training_unsupported() + torch.manual_seed(1234) + model = SimpleModel(hidden_dim=768, nlayers=3) + config = get_offload_clip_config(True, gradient_clipping=0., sub_group_size=262144) + config["zero_optimization"]["reduce_bucket_size"] = 262144 + engine, optimizer, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) + try: + native = optimizer.optimizer.ds_opt_adam + persist = native.reflow_adam_update_state_halfgrad + target = optimizer.fp32_partitioned_groups_flat[1].data_ptr() + + def commit(*args, **kwargs): + if dist.get_rank() == 0 and args[8].data_ptr() == target: + raise RuntimeError("injected subgroup commit failure") + return persist(*args, **kwargs) + + first, second = make_batches(768, count=2) + with patch.object(native, "reflow_adam_update_state_halfgrad", commit): + engine.backward(engine(*first)) + engine.step() + engine.backward(engine(*second)) + with pytest.raises(RuntimeError, + match="injected subgroup commit failure|worker failed on another rank"): + engine.step() + finally: + engine.destroy() + @needs_gpu_accelerator class TestReflowCheckpointResume(DistributedTest): @@ -1573,6 +1749,38 @@ def run(reflow): for want, got in zip(expected_group, actual_group): assert torch.equal(got, want), f"parameter or optimizer state differs at step {step}" + def test_norm_after_replacing_an_earlier_microstep_gradient(self): + skip_if_reflow_training_unsupported() + + def run(reflow): + torch.manual_seed(1234) + model = ConditionalGradientModel() + weight = model.optional.weight + # Zero the same first contribution in the reference before ZeRO partitions it. + if not reflow: + weight.register_hook(lambda grad: torch.zeros_like(grad) if micro_step == 0 else grad) + config = get_variant_config(reflow, "adam") + config["data_types"] = {"grad_accum_dtype": "bf16"} + config["gradient_accumulation_steps"] = 3 + config["gradient_clipping"] = 0.01 + engine, _, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) + try: + for micro_step, use_optional in enumerate((True, True, False)): + torch.manual_seed(900 + micro_step) + inputs = torch.randn(2, 16, device=engine.device, dtype=torch.bfloat16) + engine.backward(engine(inputs, use_optional)) + if reflow and micro_step == 0: + safe_set_local_grad(weight, torch.zeros_like(safe_get_local_grad(weight))) + engine.step() + return engine.get_global_grad_norm(), safe_get_full_optimizer_state(weight, "exp_avg").clone() + finally: + engine.destroy() + + expected_norm, expected_moment = run(False) + actual_norm, actual_moment = run(True) + assert actual_norm == expected_norm + assert torch.equal(actual_moment, expected_moment) + def test_skipped_step_does_not_reuse_invalid_gradient(self): skip_if_reflow_training_unsupported() schedule = [(True, False), (True, True), (False, False), (False, True)] @@ -1677,18 +1885,24 @@ class TestReflowReentrantGradients(DistributedTest): world_size = [1, 2] @pytest.mark.parametrize("optimizer_kind", ["adam", "lion"]) - @pytest.mark.parametrize("gradient_accumulation_steps", [1, 2]) - def test_matches_zero_offload(self, optimizer_kind, gradient_accumulation_steps): + @pytest.mark.parametrize("gradient_accumulation_steps, clip, precision", [(1, 0., "bf16"), (1, 1000., "bf16"), + (2, 0.1, "bf16"), (1, 0.0001, "fp16"), + (1, 0., "fp16")]) + def test_matches_zero_offload(self, optimizer_kind, gradient_accumulation_steps, clip, precision): skip_if_reflow_training_unsupported(optimizer_kind) def run(reflow): torch.manual_seed(1234) model = ReentrantGradientModel() config = get_variant_config(reflow, optimizer_kind) - config["data_types"] = {"grad_accum_dtype": "bf16"} + config["data_types"] = {"grad_accum_dtype": precision} + dtype = torch.bfloat16 + if precision == "fp16": + dtype = torch.float16 + config["bf16"] = {"enabled": False} + config["fp16"] = {"enabled": True, "initial_scale_power": 3, "loss_scale_window": 1, "hysteresis": 1} config["gradient_accumulation_steps"] = gradient_accumulation_steps - if gradient_accumulation_steps > 1: - config["gradient_clipping"] = 0.1 + config["gradient_clipping"] = clip config["zero_optimization"]["reduce_bucket_size"] = 256 engine, _, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) snapshots = [] @@ -1696,22 +1910,167 @@ def run(reflow): for step in range(3): for micro_step in range(gradient_accumulation_steps): torch.manual_seed(900 + step * gradient_accumulation_steps + micro_step) - inputs = torch.randn(2, 16, device=engine.device, dtype=torch.bfloat16) - engine.backward(engine(inputs)) + inputs = torch.randn(2, 16, device=engine.device, dtype=dtype) + loss = engine(inputs) + if precision == "fp16" and step == 1 and dist.get_rank() == 0: + loss = loss * float("inf") + engine.backward(loss) engine.step() + with deepspeed.zero.GatheredParameters(list(engine.module.parameters())): + published = [p.detach().clone() for p in engine.module.parameters()] params = [safe_get_full_fp32_param(p).clone() for p in engine.module.parameters()] states = [safe_get_full_optimizer_state(p, "exp_avg").clone() for p in engine.module.parameters()] - snapshots.append((params, states)) + snapshots.append((published, params, states, engine.get_global_grad_norm(), + engine.optimizer.loss_scale, engine.skipped_steps)) return snapshots finally: engine.destroy() for step, (expected, actual) in enumerate(zip(run(False), run(True))): - for expected_group, actual_group in zip(expected, actual): + assert actual[3:] == expected[3:], f"gradient norm, loss scale or skipped steps differ at step {step}" + for expected_group, actual_group in zip(expected[:3], actual[:3]): for want, got in zip(expected_group, actual_group): assert torch.equal(got, want), (f"parameter or optimizer state differs at step {step}: " f"max diff {(got - want).abs().max().item()}") + @pytest.mark.parametrize("precision", ["bf16", "fp16"]) + def test_unclipped_checkpoint_ready_preserves_forward_weights(self, precision): + # Ready may finish in backward, but recomputation still owns the published weights. + skip_if_reflow_training_unsupported() + + class CheckpointedLayers(torch.nn.Sequential): + + def forward(self, inputs): + inputs = checkpoint(self[0], inputs, use_reentrant=True).tanh() + inputs = checkpoint(self[1], inputs, use_reentrant=True).tanh() + return checkpoint(self[0], inputs, use_reentrant=True).float().square().mean() + + def run(reflow): + torch.manual_seed(731) + model = CheckpointedLayers(torch.nn.Linear(16, 16, bias=False), torch.nn.Linear(16, 16, bias=False)) + config = get_offload_clip_config(reflow, gradient_clipping=0., sub_group_size=1) + dtype = torch.bfloat16 + if precision == "fp16": + dtype = torch.float16 + config["bf16"] = {"enabled": False} + config["fp16"] = {"enabled": True, "loss_scale": 0.5} + config["zero_optimization"]["reduce_bucket_size"] = 32 + engine, opt, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) + snapshots = [] + try: + for step in range(3): + inputs = torch.randn(2, 16, dtype=dtype, device=engine.device, requires_grad=True) + loss = engine(inputs) + if step == 1 and dist.get_rank() == 0: + loss = loss * float("inf") + with ExitStack() as patches: + if reflow: + weights = [param.ds_tensor.clone() for param in model.parameters()] + native = opt.optimizer.ds_opt_adam + ready = native.reflow_adam_update_params_halfgrad + ready_finished = threading.Event() + processed = [] + + def observe_ready(*args): + result = ready(*args) + processed.append(args[8].numel()) + ready_finished.set() + return result + + patches.enter_context( + patch.object(native, "reflow_adam_update_params_halfgrad", observe_ready)) + engine.backward(loss) + if reflow: + assert ready_finished.wait(10), "checkpoint Ready was held until step()" + if step == 2: + # Replace the gradient of the weight that already has a staged Ready. + weight = model[1].weight + safe_set_local_grad(weight, torch.full_like(safe_get_local_grad(weight), 0.125)) + if reflow: + # The local setter joins outstanding previews. A premature copy + # is now visible regardless of worker ordering. + get_accelerator().synchronize() + for param, original in zip(model.parameters(), weights): + assert torch.equal(param.ds_tensor, original) + engine.step() + if reflow and step == 0: + # The tied weight receives two gradients but needs only one Ready. + assert sum(processed) == sum(weight.numel() for weight in weights) + for param in model.parameters(): + snapshots.extend([ + param.ds_tensor.clone(), + safe_get_full_fp32_param(param).clone(), + safe_get_full_optimizer_state(param, "exp_avg").clone(), + safe_get_full_optimizer_state(param, "exp_avg_sq").clone() + ]) + steps = [int(opt.optimizer.state[p]["step"]) for p in opt.fp32_partitioned_groups_flat] + return snapshots, steps, engine.skipped_steps + finally: + engine.destroy() + + expected, expected_steps, expected_skips = run(False) + actual, steps, skips = run(True) + assert steps == expected_steps and skips == expected_skips == 1 + for want, got in zip(expected, actual): + torch.testing.assert_close(got, want, rtol=0, atol=0) + + @pytest.mark.parametrize("dynamic, failure", [(False, "kernel"), (True, "kernel"), (True, "executor")]) + def test_deferred_ready_failure_aborts_before_persist(self, dynamic, failure): + # A rank-local error published after the norm decision must abort all ranks + # before any state, master weight or optimizer step counter is committed. + skip_if_reflow_training_unsupported() + torch.manual_seed(1234) + model = ReentrantGradientModel() + config = get_offload_clip_config(True, gradient_clipping=0.0001) + if dynamic: + config["bf16"] = {"enabled": False} + config["fp16"] = {"enabled": True, "initial_scale_power": 3, "loss_scale_window": 1} + # Keep repeated uses in separate reduction buckets, as in the ZeRO-3 oracle above. + config["zero_optimization"]["reduce_bucket_size"] = 256 + engine, optimizer, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) + try: + dtype = torch.float16 if dynamic else torch.bfloat16 + inputs = torch.randn(2, 16, device=engine.device, dtype=dtype) + engine.backward(engine(inputs)) + engine.step() + optimizer.state_dict() + masters = optimizer.fp32_partitioned_groups_flat + snapshots = [(p.detach().clone(), copy.deepcopy(optimizer.optimizer.state[p])) for p in masters] + engine.backward(engine(inputs)) + native = optimizer.optimizer.ds_opt_adam + ready = native.reflow_adam_update_params_halfgrad + + scale_before = optimizer.loss_scale + if dynamic: + iteration_before = optimizer.loss_scaler.cur_iter + + def fail_on_one_rank(*args, **kwargs): + if dist.get_rank() == 0 and float(args[13]) > optimizer.loss_scale: + raise RuntimeError("injected final Ready failure") + return ready(*args, **kwargs) + + if failure == "executor" and dist.get_rank() == 0: + # An executor can fail a Future before the Ready kernel gets a chance to report it. + failed = Future() + failed.set_exception(RuntimeError("injected final Ready failure")) + failure_patch = patch.object(optimizer._bucketwise_update_executor, "submit", return_value=failed) + else: + failure_patch = patch.object(native, "reflow_adam_update_params_halfgrad", fail_on_one_rank) + with failure_patch: + with pytest.raises(RuntimeError, match="injected final Ready failure|worker failed on another rank"): + engine.step() + assert optimizer.loss_scale == scale_before + if dynamic: + assert optimizer.loss_scaler.cur_iter == iteration_before + for param, (master, state) in zip(masters, snapshots): + assert torch.equal(param, master) + now = optimizer.optimizer.state[param] + assert now["step"] == state["step"] + for key in ("exp_avg", "exp_avg_sq"): + assert torch.equal(now[key], state[key]) + finally: + engine.destroy() + @needs_gpu_accelerator class TestReflowNVMeConditionalGradients(DistributedTest): @@ -1875,7 +2234,8 @@ def test_invalid_step_preserves_parameters_and_state(self, precision, invalid_va torch.manual_seed(1234) config = get_variant_config(reflow=True, variant="offload_param" if offload_param else "adam") config["zero_optimization"]["offload_optimizer"]["pin_memory"] = pin_memory - config["zero_optimization"]["reduce_bucket_size"] = 1_000_000 + # Submit Ready during backward so overflow must restore an actual parameter preview. + config["zero_optimization"]["reduce_bucket_size"] = 128 if precision == "fp16": config["bf16"] = {"enabled": False} config["fp16"] = {"enabled": True, "loss_scale": 128} From 843e377a6f1649605ed72c9182dba14ad8d4a3cb Mon Sep 17 00:00:00 2001 From: st-bang97 Date: Fri, 20 Nov 2026 12:44:20 +0900 Subject: [PATCH 15/19] Batch ReFlow Ready work and stream parameter transfers Use one optimizer worker per rank by default and share its OpenMP team across ready ranges. Publish each transfer chunk after its writers fence their streaming stores. Keep checkpointed ranges staged until publication is safe and make the H2D chunk size configurable. Signed-off-by: st-bang97 --- csrc/adam/reflow_cpu_adam_bindings.cpp | 13 +- csrc/adam/reflow_cpu_adam_impl.cpp | 142 +++++------ csrc/includes/reflow_cpu_adam.h | 24 +- csrc/includes/reflow_cpu_lion.h | 22 +- csrc/includes/reflow_ready.h | 221 ++++++++++++++++ csrc/includes/reflow_simd.h | 99 ++----- csrc/lion/reflow_cpu_lion_bindings.cpp | 13 +- csrc/lion/reflow_cpu_lion_impl.cpp | 117 +++++---- deepspeed/runtime/reflow/README.md | 5 +- deepspeed/runtime/reflow/ready_batch.py | 106 ++++++++ deepspeed/runtime/reflow/reflow_config.py | 9 +- deepspeed/runtime/reflow/reflow_stage3.py | 241 +++++++++++------- deepspeed/runtime/reflow/reflow_utils.py | 7 + docs/_pages/config-json.md | 13 +- docs/_tutorials/reflow.md | 7 +- .../unit/v1/ops/test_reflow_cpu_optimizers.py | 38 +++ tests/unit/v1/zero/test_reflow.py | 206 ++++++++++++++- 17 files changed, 931 insertions(+), 352 deletions(-) create mode 100644 csrc/includes/reflow_ready.h create mode 100644 deepspeed/runtime/reflow/ready_batch.py diff --git a/csrc/adam/reflow_cpu_adam_bindings.cpp b/csrc/adam/reflow_cpu_adam_bindings.cpp index 843d2f705ebc..12484c58ee7e 100644 --- a/csrc/adam/reflow_cpu_adam_bindings.cpp +++ b/csrc/adam/reflow_cpu_adam_bindings.cpp @@ -27,7 +27,9 @@ static inline int reflow_ds_adam_step_params_halfgrad_gilfree(int optimizer_id, torch::Tensor& half_params, float combined_scale, bool skip_increment_step = false, - bool maximize = false) + bool maximize = false, + ReflowReadyWork* work = nullptr, + size_t destination_offset = 0) { pybind11::gil_scoped_release release; return reflow_ds_adam_step_params_halfgrad(optimizer_id, @@ -45,7 +47,9 @@ static inline int reflow_ds_adam_step_params_halfgrad_gilfree(int optimizer_id, half_params, combined_scale, skip_increment_step, - maximize); + maximize, + work, + destination_offset); } static inline int reflow_ds_adam_state_step_halfgrad_gilfree(int optimizer_id, @@ -90,6 +94,7 @@ static inline int reflow_ds_bf16_accumulate_gilfree(torch::Tensor& dst, torch::T PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + bind_reflow_ready_work(m); m.def("reflow_create_adam", &reflow_create_adam_optimizer, "Reflow CPU Adam create (C++)", @@ -121,7 +126,9 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) pybind11::arg("half_params"), pybind11::arg("combined_scale"), pybind11::arg("skip_increment_step") = false, - pybind11::arg("maximize") = false); + pybind11::arg("maximize") = false, + pybind11::arg("ready_work") = nullptr, + pybind11::arg("destination_offset") = 0); m.def("reflow_adam_update_state_halfgrad", &reflow_ds_adam_state_step_halfgrad_gilfree, "Reflow CPU Adam update state stream with half gradients, GIL-released (C++)", diff --git a/csrc/adam/reflow_cpu_adam_impl.cpp b/csrc/adam/reflow_cpu_adam_impl.cpp index 2a99d4253b88..e0f984a917f7 100644 --- a/csrc/adam/reflow_cpu_adam_impl.cpp +++ b/csrc/adam/reflow_cpu_adam_impl.cpp @@ -166,35 +166,30 @@ void Reflow_Adam_Optimizer::Step_8_FP16_HalfGrad(float* _params_fp32, size_t copy_size = TILE; if ((t + TILE) > _param_size) copy_size = _param_size - t; size_t offset = copy_size + t; - ReflowCPUAffinity affinity; -#pragma omp parallel - { - affinity.apply(); -#pragma omp for schedule(static) nowait - for (size_t k = t; k < offset; k++) { - float grad = static_cast(grads_half[k]) * unscale_factor; - float param = _params_fp32[k]; - float momentum = static_cast(_exp_avg[k]); - float variance = static_cast(_exp_avg_sq[k]); - - if (_weight_decay > 0 && !_adamw_mode) { grad = param * _weight_decay + grad; } - momentum = momentum * _betta1; - momentum = grad * betta1_minus1 + momentum; - - variance = variance * _betta2; - grad = grad * grad; - variance = grad * betta2_minus1 + variance; - - grad = sqrt(variance); - grad = grad * _bias_correction2 + _eps; - grad = momentum / grad; - if (_weight_decay > 0 && _adamw_mode) { param += w_decay * param; } - param = grad * step_size + param; - - // Store param to FP16/BF16 buffer only; state is skipped. - half_params[k] = ds_store_precision_t(param); - } - } + reflow_ready_loop(offset - t, 1, single_ready_writer, false, [&](size_t index) { + const size_t k = t + index; + float grad = static_cast(grads_half[k]) * unscale_factor; + float param = _params_fp32[k]; + float momentum = static_cast(_exp_avg[k]); + float variance = static_cast(_exp_avg_sq[k]); + + if (_weight_decay > 0 && !_adamw_mode) { grad = param * _weight_decay + grad; } + momentum = momentum * _betta1; + momentum = grad * betta1_minus1 + momentum; + + variance = variance * _betta2; + grad = grad * grad; + variance = grad * betta2_minus1 + variance; + + grad = sqrt(variance); + grad = grad * _bias_correction2 + _eps; + grad = momentum / grad; + if (_weight_decay > 0 && _adamw_mode) { param += w_decay * param; } + param = grad * step_size + param; + + // Store param to FP16/BF16 buffer only; state is skipped. + half_params[k] = ds_store_precision_t(param); + }); } } } @@ -310,10 +305,13 @@ int reflow_ds_adam_step_params_halfgrad(int optimizer_id, torch::Tensor& half_params, float combined_scale, bool skip_increment_step, - bool maximize) + bool maximize, + ReflowReadyWork* work, + size_t destination_offset) { // Encode direction in the scale so SIMD and scalar tails share the same gradient transform. if (maximize) { combined_scale = -combined_scale; } + TORCH_CHECK(!work || half_params.is_contiguous(), "Deferred Ready requires contiguous output"); auto params_c = params_fp32.contiguous(); auto grads_c = grads.contiguous(); auto exp_avg_c = exp_avg.contiguous(); @@ -357,60 +355,56 @@ int reflow_ds_adam_step_params_halfgrad(int optimizer_id, unsigned int reflow_total_cpus = reflow_get_available_cpu_count(); unsigned int reflow_max_omp_threads = reflow_resolve_omp_threads(worker_opt.get_num_threads(), reflow_total_cpus); - int reflow_original_omp_threads = omp_get_max_threads(); - omp_set_num_threads(reflow_max_omp_threads); -#if defined(__AVX512__) or defined(__AVX256__) - if (store_type == torch::kFloat16 && grad_type == torch::kFloat16 && - state_type == torch::kFloat32) { - worker_opt.Step_8_FP16_HalfGrad( - params_c.data_ptr(), - grads_c.data_ptr(), - exp_avg_c.data_ptr(), - exp_avg_sq_c.data_ptr(), - param_size, - half_params_c.data_ptr(), - combined_scale); - } else if (store_type == torch::kFloat16 && grad_type == torch::kFloat16 && + auto dispatch = [&](auto half, auto state) { + using Half = decltype(half); + using State = decltype(state); + auto* params = params_c.data_ptr(); + auto* grad = grads_c.data_ptr(); + auto* momentum = exp_avg_c.data_ptr(); + auto* variance = exp_avg_sq_c.data_ptr(); + auto* output = half_params_c.data_ptr(); + worker_opt.single_ready_writer = work != nullptr; + auto kernel = [=](size_t start, size_t size) mutable { + worker_opt.Step_8_FP16_HalfGrad(params + start, + grad + start, + momentum + start, + variance + start, + size, + output + start, + combined_scale); + }; + if (work) { + work->add(destination_offset, + reflow_max_omp_threads, + half_params_c, + {params_c, grads_c, exp_avg_c, exp_avg_sq_c}, + std::move(kernel)); + } else { + const int previous_threads = omp_get_max_threads(); + omp_set_num_threads(reflow_max_omp_threads); + kernel(0, param_size); + omp_set_num_threads(previous_threads); + } + }; +#if defined(__AVX512__) || defined(__AVX256__) + if (store_type == grad_type && grad_type == torch::kFloat16 && state_type == torch::kFloat32) { + dispatch(c10::Half{}, float{}); + } else if (store_type == grad_type && grad_type == torch::kFloat16 && state_type == torch::kFloat16) { - worker_opt.Step_8_FP16_HalfGrad( - params_c.data_ptr(), - grads_c.data_ptr(), - exp_avg_c.data_ptr(), - exp_avg_sq_c.data_ptr(), - param_size, - half_params_c.data_ptr(), - combined_scale); -#if defined(__AVX512__) or defined(__AVX256__) - } else if (store_type == torch::kBFloat16 && grad_type == torch::kBFloat16 && + dispatch(c10::Half{}, c10::Half{}); + } else if (store_type == grad_type && grad_type == torch::kBFloat16 && state_type == torch::kFloat32) { - worker_opt.Step_8_FP16_HalfGrad( - params_c.data_ptr(), - grads_c.data_ptr(), - exp_avg_c.data_ptr(), - exp_avg_sq_c.data_ptr(), - param_size, - half_params_c.data_ptr(), - combined_scale); - } else if (store_type == torch::kBFloat16 && grad_type == torch::kBFloat16 && + dispatch(c10::BFloat16{}, float{}); + } else if (store_type == grad_type && grad_type == torch::kBFloat16 && state_type == torch::kBFloat16) { - worker_opt.Step_8_FP16_HalfGrad( - params_c.data_ptr(), - grads_c.data_ptr(), - exp_avg_c.data_ptr(), - exp_avg_sq_c.data_ptr(), - param_size, - half_params_c.data_ptr(), - combined_scale); -#endif + dispatch(c10::BFloat16{}, c10::BFloat16{}); } else #endif { - omp_set_num_threads(reflow_original_omp_threads); throw std::runtime_error( "reflow_ds_adam_step_params_halfgrad: unsupported combination of store/grad/state " "dtypes"); } - omp_set_num_threads(reflow_original_omp_threads); return 0; } diff --git a/csrc/includes/reflow_cpu_adam.h b/csrc/includes/reflow_cpu_adam.h index b6920a01e2d2..285f230a93fc 100644 --- a/csrc/includes/reflow_cpu_adam.h +++ b/csrc/includes/reflow_cpu_adam.h @@ -21,6 +21,7 @@ inline void omp_set_num_threads(int) {} #include #include #include "reflow_cpu_affinity.h" +#include "reflow_ready.h" #include "reflow_simd.h" /* Enable madvise(MADV_HUGEPAGE) hints in the streaming kernels (Linux only). @@ -131,6 +132,7 @@ class Reflow_Adam_Optimizer { /* -1 (the default) means "use all available cores"; a positive value caps the * OpenMP thread count for the CPU-Adam state update. */ + bool single_ready_writer = false; inline void set_num_threads(int num_threads) { _num_threads = num_threads; } inline int get_num_threads() const { return _num_threads; } @@ -197,7 +199,7 @@ void Reflow_Adam_Optimizer::Step_AVX_HalfGrad(size_t* rounded_size, size_t new_rounded_size = ROUND_DOWN(_param_size, SIMD_WIDTH * span); #if defined(__linux__) && USE_HUGE_PAGE - if (new_rounded_size > 0) { + if (!single_ready_writer && new_rounded_size > 0) { size_t page_size = 4096; auto madvise_bytes = [&](size_t elem_size) { return (_param_size * elem_size + page_size - 1) & ~(page_size - 1); @@ -332,12 +334,9 @@ void Reflow_Adam_Optimizer::Step_AVX_HalfGrad_Loop(size_t rounded_size, AVX_Data unscale_factor; if (unscale_grads) { unscale_factor.data = SIMD_SET(1.0f / combined_scale); } - ReflowCPUAffinity affinity; -#pragma omp parallel - { - affinity.apply(); -#pragma omp for schedule(static) nowait - for (size_t i = 0; i < rounded_size; i += SIMD_WIDTH * span) { + const bool stream_output = store_half_params && reflow_stream_ready_output(half_params); + reflow_ready_loop( + rounded_size, SIMD_WIDTH * span, single_ready_writer, stream_output, [&](size_t i) { AVX_Data grad_4[span]; reflow_simd_load(grad_4, grads_half + i); if (unscale_grads) { simd_mul(grad_4, grad_4, unscale_factor); } @@ -360,16 +359,15 @@ void Reflow_Adam_Optimizer::Step_AVX_HalfGrad_Loop(size_t rounded_size, if (decay_param) { simd_fma(param_4, param_4, weight_decay4, param_4); } simd_fma(param_4, grad_4, step_size_4, param_4); - if (store_half_params) { + if constexpr (store_half_params) { // Param generation leaves the FP32 master and the state to the later commit. - reflow_simd_store_stream(half_params + i, param_4); + reflow_simd_store_ready(half_params + i, param_4, stream_output); } else { reflow_simd_store(_params_fp32 + i, param_4); reflow_simd_store(_exp_avg + i, momentum_4); reflow_simd_store(_exp_avg_sq + i, variance_4); } - } - } + }); } #endif @@ -399,7 +397,9 @@ int reflow_ds_adam_step_params_halfgrad(int optimizer_id, torch::Tensor& half_params, float combined_scale = 1.0f, bool skip_increment_step = false, - bool maximize = false); + bool maximize = false, + ReflowReadyWork* work = nullptr, + size_t destination_offset = 0); int reflow_ds_adam_state_step_halfgrad(int optimizer_id, size_t step, diff --git a/csrc/includes/reflow_cpu_lion.h b/csrc/includes/reflow_cpu_lion.h index 75787d680aaf..a2e145d25f6c 100644 --- a/csrc/includes/reflow_cpu_lion.h +++ b/csrc/includes/reflow_cpu_lion.h @@ -30,6 +30,7 @@ inline void omp_set_num_threads(int) {} #include #include #include "reflow_cpu_affinity.h" +#include "reflow_ready.h" #include "reflow_simd.h" /* Enable madvise(MADV_HUGEPAGE) hints in the streaming kernels (Linux only). @@ -117,6 +118,7 @@ class Reflow_Lion_Optimizer { /* -1 (the default) means "use all available cores"; a positive value caps the * OpenMP thread count for the CPU-Lion state update. */ + bool single_ready_writer = false; inline void set_num_threads(int num_threads) { _num_threads = num_threads; } inline int get_num_threads() const { return _num_threads; } @@ -270,7 +272,7 @@ void Reflow_Lion_Optimizer::Step_AVX_FP16_HalfGrad(size_t* rounded_size, new_rounded_size = ROUND_DOWN(_param_size, SIMD_WIDTH * span); #if defined(__linux__) && USE_HUGE_PAGE - if (new_rounded_size > 0) { + if (!single_ready_writer && new_rounded_size > 0) { size_t page_size = 4096; auto madvise_bytes = [&](size_t elem_size) { return (_param_size * elem_size + page_size - 1) & ~(page_size - 1); @@ -289,12 +291,9 @@ void Reflow_Lion_Optimizer::Step_AVX_FP16_HalfGrad(size_t* rounded_size, // Phase-1 reads the OLD momentum but never overwrites it, so the momentum EMA // (m_new) is intentionally not computed here -- it is committed in Phase-2. - ReflowCPUAffinity affinity; -#pragma omp parallel - { - affinity.apply(); -#pragma omp for schedule(static) nowait - for (size_t i = 0; i < new_rounded_size; i += SIMD_WIDTH * span) { + const bool stream_output = reflow_stream_ready_output(half_params); + reflow_ready_loop( + new_rounded_size, SIMD_WIDTH * span, single_ready_writer, stream_output, [&](size_t i) { AVX_Data grad_4[span]; reflow_simd_load(grad_4, grads_half + i); if (need_unscale) { simd_mul(grad_4, grad_4, unscale_factor); } @@ -313,9 +312,8 @@ void Reflow_Lion_Optimizer::Step_AVX_FP16_HalfGrad(size_t* rounded_size, } else { simd_add(param_4, param_4, tmp_4); } - reflow_simd_store_stream(half_params + i, param_4); - } - } + reflow_simd_store_ready(half_params + i, param_4, stream_output); + }); *rounded_size = new_rounded_size; } @@ -347,7 +345,9 @@ int reflow_ds_lion_step_params_halfgrad(int optimizer_id, torch::Tensor& exp_avg, torch::Tensor& half_params, float combined_scale, - bool skip_increment_step = false); + bool skip_increment_step = false, + ReflowReadyWork* work = nullptr, + size_t destination_offset = 0); // Half/BFloat16 gradient params (FP32 master) + state commit. int reflow_ds_lion_state_step_halfgrad(int optimizer_id, diff --git a/csrc/includes/reflow_ready.h b/csrc/includes/reflow_ready.h new file mode 100644 index 000000000000..5f44fc3b187f --- /dev/null +++ b/csrc/includes/reflow_ready.h @@ -0,0 +1,221 @@ +// SPDX-License-Identifier: Apache-2.0 +// DeepSpeed Team + +#pragma once + +#include +#include +#include +#include +#ifdef _OPENMP +#include +#endif +#if defined(__AVX512__) || defined(__AVX256__) +#include +#endif +#include +#include +#include +#include +#include "reflow_cpu_affinity.h" +#if defined(__linux__) +#include +#endif + +// A single optimizer worker lends its OpenMP team to consecutive independent Ready ranges. +// Each writer can enter the next chunk once it has fenced its own stores in this one. +class ReflowReadyWork { +public: + using Work = std::shared_ptr; + using Kernel = std::function; + + ReflowReadyWork(at::Tensor destination, c10::Stream stream, int64_t chunk_elems) + : destination_(destination.detach()), stream_(stream), chunk_elems_(chunk_elems) + { + TORCH_CHECK(chunk_elems > 0 && destination_.dim() == 1 && destination_.is_contiguous() && + destination_.device() == stream.device()); + } + + void add(size_t offset, + int threads, + at::Tensor output, + std::vector inputs, + Kernel kernel) + { + std::lock_guard lock(setup_mutex_); + TORCH_CHECK(!sealed_, "Ready work has already started"); + const size_t size = output.numel(); + TORCH_CHECK(offset <= static_cast(destination_.numel()) && + size <= static_cast(destination_.numel()) - offset && + destination_.scalar_type() == output.scalar_type()); + TORCH_CHECK(output.device().is_cpu() && output.dim() == 1 && output.is_contiguous()); + inputs.push_back(output); + for (const auto& tensor : inputs) { + TORCH_CHECK(tensor.device().is_cpu() && tensor.is_contiguous() && + tensor.numel() == output.numel()); +#if defined(__linux__) + // Advise once per range, before splitting it among writers. + constexpr uintptr_t page_size = 4096; + const auto addr = reinterpret_cast(tensor.data_ptr()); + const auto page = addr & ~(page_size - 1); + madvise(reinterpret_cast(page), addr - page + tensor.nbytes(), MADV_HUGEPAGE); +#endif + } + inputs.pop_back(); // The output view is owned separately below. + threads_ = threads; + for (size_t start = 0; start < size; start += chunk_elems_) + chunks_.emplace_back(ranges_.size(), start, std::min(size - start, chunk_elems_)); + ranges_.push_back({offset, std::move(output), std::move(inputs), std::move(kernel)}); + } + + void cancel() { cancelled_.store(true, std::memory_order_release); } + + void run(const std::function& take_next) + { + seal(); + std::exception_ptr failure; + std::mutex failure_mutex; + auto fail = [&] { + std::lock_guard lock(failure_mutex); + if (!failure) failure = std::current_exception(); + cancel(); + }; + const ReflowCPUAffinity affinity; +#pragma omp parallel num_threads(threads_) + { + affinity.apply(); +#ifdef _OPENMP + const size_t writer = omp_get_thread_num(), team = omp_get_num_threads(); +#else + const size_t writer = 0, team = 1; +#endif + try { + c10::OptionalStreamGuard copy_stream; + ReflowReadyWork* work = this; + while (work && !cancelled_.load(std::memory_order_acquire)) { + auto prepare_next = [&] { + if (cancelled_.load(std::memory_order_acquire)) return; + try { + auto next = take_next(); + if (next) { + TORCH_CHECK(next->stream_ == stream_, + "Ready jobs must use the same copy stream"); + next->seal(); + work->next_ = std::move(next); + } + } catch (...) { + // A failed admission must not consume another successor. + fail(); + } + }; + for (auto& chunk : work->chunks_) { + if (cancelled_.load(std::memory_order_acquire)) break; + // Preserve the same SIMD and scalar tails as the unsplit Ready kernel. + constexpr size_t block = 128; + const size_t blocks = std::max(1, chunk.size / block); + const size_t writers = std::min(team, blocks); + if (writer >= writers) continue; + const size_t begin = (blocks * writer / writers) * block; + const size_t end = writer + 1 == writers + ? chunk.size + : (blocks * (writer + 1) / writers) * block; + const auto& range = work->ranges_[chunk.range]; + range.kernel(chunk.start + begin, end - begin); + // The kernel fences on the issuing thread. The last arrival acquires + // all earlier writers' releases before handing the pinned range to DMA. + if (chunk.finished.fetch_add(1, std::memory_order_acq_rel) + 1 == writers && + !cancelled_.load(std::memory_order_acquire)) { + if (!copy_stream.current_stream()) + copy_stream.reset_stream(work->stream_); + work->destination_.narrow(0, range.offset + chunk.start, chunk.size) + .copy_(range.output.narrow(0, chunk.start, chunk.size), true); + // Prepare one independent successor during the remaining CPU work. + if (&chunk == &work->chunks_.front() && work->chunks_.size() > 1) + std::call_once(work->prefetch_, prepare_next); + } + } + std::call_once(work->admit_, [&] { + // A leading writer can reach the boundary before the first DMA. + // Close or join the early lookup before inspecting its result. + std::call_once(work->prefetch_, [] {}); + if (!work->next_) prepare_next(); + }); + work = work->next_.get(); + } + } catch (...) { + fail(); + } + } + if (failure) std::rethrow_exception(failure); + } + +private: + void seal() + { + std::lock_guard lock(setup_mutex_); + TORCH_CHECK(!sealed_ && !chunks_.empty(), "Ready work must contain fresh ranges"); + sealed_ = true; + } + std::mutex setup_mutex_; + bool sealed_ = false; + struct Range { + size_t offset; + at::Tensor output; + std::vector inputs; // Own the storage used by the deferred native kernel. + Kernel kernel; + }; + struct Chunk { + size_t range, start, size; + std::atomic finished{0}; + Chunk(size_t range, size_t start, size_t size) : range(range), start(start), size(size) {} + }; + at::Tensor destination_; + c10::Stream stream_; + size_t chunk_elems_; + int threads_ = 1; + std::vector ranges_; + std::deque chunks_; + std::atomic cancelled_{false}; + std::once_flag prefetch_, admit_; + Work next_; +}; + +inline void bind_reflow_ready_work(pybind11::module_& module) +{ + pybind11::class_( + module, "ReadyWork", pybind11::module_local()) + .def(pybind11::init()) + .def("cancel", &ReflowReadyWork::cancel) + .def("run", &ReflowReadyWork::run, pybind11::call_guard()); +} + +template +inline void reflow_ready_loop(size_t size, + size_t stride, + bool single_writer, + bool streaming, + F update) +{ + if (!size) return; + if (single_writer) { + for (size_t i = 0; i < size; i += stride) update(i); +#if defined(__AVX512__) || defined(__AVX256__) + if (streaming) _mm_sfence(); +#endif + return; + } + ReflowCPUAffinity affinity; +#pragma omp parallel + { + affinity.apply(); + bool wrote = false; +#pragma omp for schedule(static) nowait + for (size_t i = 0; i < size; i += stride) { + update(i); + wrote = true; + } +#if defined(__AVX512__) || defined(__AVX256__) + if (wrote && streaming) _mm_sfence(); +#endif + } +} diff --git a/csrc/includes/reflow_simd.h b/csrc/includes/reflow_simd.h index baf931a541e9..9dc24a6f3cbf 100644 --- a/csrc/includes/reflow_simd.h +++ b/csrc/includes/reflow_simd.h @@ -6,12 +6,13 @@ #include "simd.h" #if defined(__AVX512__) -#define SIMD_STREAM_STORE(a, d) _mm512_stream_ps(a, d) +#define REFLOW_STREAM_PACKED(dst, value) _mm256_stream_si256(dst, value) +#define REFLOW_PACK_FP16(value) _mm512_cvtps_ph(value, _MM_FROUND_TO_NEAREST_INT) // Reflow BF16 aliases (the stock AVX-512 BF16 conversion works as-is). #define SIMD_LOAD_BF16_REFLOW(x) load_16_bf16_as_f32(x) #define SIMD_STORE_BF16_REFLOW(x, d) store_16_f32_as_bf16_nearest(d, x) -static void stream_store_16_f32_as_bf16_nearest(__m512 v, void* data) +static inline __m256i reflow_pack_bf16(__m512 v) { __m512i u32 = readAs<__m512i>(&v); @@ -31,17 +32,12 @@ static void stream_store_16_f32_as_bf16_nearest(__m512 v, void* data) __mmask16 nan_mask = _mm512_cmp_epi32_mask(non_sign_bits, nan_threshold, _MM_CMPINT_GT); __m256i nans = _mm256_set1_epi16(0x7fc0); - __m256i res = _mm256_mask_mov_epi16(non_nan_res, nan_mask, nans); - - _mm256_storeu_si256((__m256i*)data, res); + return _mm256_mask_mov_epi16(non_nan_res, nan_mask, nans); } -#define SIMD_STREAM_STORE_BF16(x, d) stream_store_16_f32_as_bf16_nearest(d, x) - -#define SIMD_STREAM_STORE_FP16(x, d) \ - _mm256_storeu_ps(x, _mm256_castsi256_ps(_mm512_cvtps_ph(d, _MM_FROUND_TO_NEAREST_INT))) #elif defined(__AVX256__) -#define SIMD_STREAM_STORE(a, d) _mm256_stream_ps(a, d) +#define REFLOW_STREAM_PACKED(dst, value) _mm_stream_si128(dst, value) +#define REFLOW_PACK_FP16(value) _mm256_cvtps_ph(value, _MM_FROUND_TO_NEAREST_INT) static __m256 reflow_load_8_bf16_as_f32(const void* data) { __m128i a = readAs<__m128i>(data); // 8 x uint16 (bf16) @@ -61,7 +57,7 @@ static inline __m128i reflow_pack_low16_x8(__m256i x) return _mm256_castsi256_si128(p); } -static void reflow_store_8_f32_as_bf16_nearest(__m256 v, void* data) +static inline __m128i reflow_pack_bf16(__m256 v) { __m256i u32 = readAs<__m256i>(&v); // round to nearest, ties to even: rounding_bias = ((u32 >> 16) & 1) + 0x7fff @@ -74,85 +70,44 @@ static void reflow_store_8_f32_as_bf16_nearest(__m256 v, void* data) __m256i non_sign = _mm256_and_si256(u32, _mm256_set1_epi32(0x7fffffff)); __m256i nan_mask = _mm256_cmpgt_epi32(non_sign, _mm256_set1_epi32(0x7f800000)); __m128i nan_mask16 = reflow_pack_low16_x8(_mm256_srli_epi32(nan_mask, 16)); - __m128i res = _mm_blendv_epi8(non_nan_res, _mm_set1_epi16((short)0x7fc0), nan_mask16); - writeAs(data, res); -} - -static void reflow_stream_store_8_f32_as_bf16_nearest(__m256 v, void* data) -{ - __m256i u32 = readAs<__m256i>(&v); - __m256i b = _mm256_srli_epi32(u32, 16); - __m256i lsb = _mm256_and_si256(b, _mm256_set1_epi32(0x00000001)); - __m256i rounding_bias = _mm256_add_epi32(lsb, _mm256_set1_epi32(0x00007fff)); - __m256i e = _mm256_srli_epi32(_mm256_add_epi32(u32, rounding_bias), 16); - __m128i non_nan_res = reflow_pack_low16_x8(e); - __m256i non_sign = _mm256_and_si256(u32, _mm256_set1_epi32(0x7fffffff)); - __m256i nan_mask = _mm256_cmpgt_epi32(non_sign, _mm256_set1_epi32(0x7f800000)); - __m128i nan_mask16 = reflow_pack_low16_x8(_mm256_srli_epi32(nan_mask, 16)); - __m128i res = _mm_blendv_epi8(non_nan_res, _mm_set1_epi16((short)0x7fc0), nan_mask16); - /* Match the AVX-512 BF16 path (stream_store_16_f32_as_bf16_nearest), which uses a regular - * store: a non-temporal _mm_stream_si128 here is weakly ordered and not fenced before the - * OMP workers' half_params writes are read, yielding non-deterministic output. - */ - _mm_storeu_si128((__m128i*)data, res); + return _mm_blendv_epi8(non_nan_res, _mm_set1_epi16((short)0x7fc0), nan_mask16); } // Reflow-specific AVX-256 BF16 support (the stock SIMD_*_BF16 above are AVX-512-only). #define SIMD_LOAD_BF16_REFLOW(x) reflow_load_8_bf16_as_f32(x) -#define SIMD_STORE_BF16_REFLOW(x, d) reflow_store_8_f32_as_bf16_nearest(d, x) -#define SIMD_STREAM_STORE_BF16(x, d) reflow_stream_store_8_f32_as_bf16_nearest(d, x) -#define SIMD_STREAM_STORE_FP16(x, d) \ - _mm_storeu_ps(x, _mm_castsi128_ps(_mm256_cvtps_ph(d, _MM_FROUND_TO_NEAREST_INT))) +#define SIMD_STORE_BF16_REFLOW(x, d) writeAs(x, reflow_pack_bf16(d)) #endif -// Streaming stores and BF16 helpers are available only in the AVX builds. #if defined(__AVX512__) or defined(__AVX256__) -// Non-temporal (streaming) store per dtype. template -inline typename std::enable_if_t, void> reflow_simd_store_stream( - T* dst, - AVX_Data* src) +inline bool reflow_stream_ready_output(T* dst) { - size_t width = SIMD_WIDTH; -#pragma unroll - for (size_t i = 0; i < span; ++i) { SIMD_STREAM_STORE(dst + width * i, src[i].data); } + // The eight-vector loop writes the bulk. Short vector tails and misaligned views use cached + // stores. + return span == 8 && reinterpret_cast(dst) % sizeof(INTV) == 0; } template -inline typename std::enable_if_t, void> reflow_simd_store_stream( - T* dst, - AVX_Data* src) -{ - size_t width = SIMD_WIDTH; -#pragma unroll - for (size_t i = 0; i < span; ++i) { - SIMD_STREAM_STORE_FP16((float*)(dst + width * i), src[i].data); - } -} - -template -inline typename std::enable_if_t, void> reflow_simd_store_stream( - T* dst, - AVX_Data* src) +inline void reflow_simd_store_ready(T* dst, AVX_Data* src, bool stream_output) { - size_t width = SIMD_WIDTH; #pragma unroll for (size_t i = 0; i < span; ++i) { - SIMD_STREAM_STORE_BF16((float*)(dst + width * i), src[i].data); + INTV packed; + if constexpr (std::is_same_v) { + packed = reflow_pack_bf16(src[i].data); + } else { + static_assert(std::is_same_v); + packed = REFLOW_PACK_FP16(src[i].data); + } + T* output = dst + SIMD_WIDTH * i; + if (stream_output) { + REFLOW_STREAM_PACKED(reinterpret_cast(output), packed); + } else { + writeAs(output, packed); + } } } -template -inline typename std::enable_if_t && !std::is_same_v && - !std::is_same_v, - void> -reflow_simd_store_stream(T* dst, AVX_Data* src) -{ - simd_store(dst, src); -} -#endif - -#if defined(__AVX512__) or defined(__AVX256__) // Reflow load/store: BF16 uses the Reflow BF16 path (incl. AVX-256); other dtypes delegate // to the stock simd_load/simd_store so the standard DeepSpeedCPUAdam path is untouched. template diff --git a/csrc/lion/reflow_cpu_lion_bindings.cpp b/csrc/lion/reflow_cpu_lion_bindings.cpp index 518efd0537df..edd9b8a8eeae 100644 --- a/csrc/lion/reflow_cpu_lion_bindings.cpp +++ b/csrc/lion/reflow_cpu_lion_bindings.cpp @@ -23,7 +23,9 @@ static inline int reflow_ds_lion_step_params_halfgrad_gilfree(int optimizer_id, torch::Tensor& exp_avg, torch::Tensor& half_params, float combined_scale, - bool skip_increment_step = false) + bool skip_increment_step = false, + ReflowReadyWork* work = nullptr, + size_t destination_offset = 0) { pybind11::gil_scoped_release release; return reflow_ds_lion_step_params_halfgrad(optimizer_id, @@ -37,7 +39,9 @@ static inline int reflow_ds_lion_step_params_halfgrad_gilfree(int optimizer_id, exp_avg, half_params, combined_scale, - skip_increment_step); + skip_increment_step, + work, + destination_offset); } static inline int reflow_ds_lion_state_step_halfgrad_gilfree(int optimizer_id, @@ -68,6 +72,7 @@ static inline int reflow_ds_lion_state_step_halfgrad_gilfree(int optimizer_id, PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + bind_reflow_ready_work(m); m.def("reflow_create_lion", &reflow_create_lion_optimizer, "Reflow CPU Lion create (C++)", @@ -93,7 +98,9 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) pybind11::arg("exp_avg"), pybind11::arg("half_params"), pybind11::arg("combined_scale"), - pybind11::arg("skip_increment_step") = false); + pybind11::arg("skip_increment_step") = false, + pybind11::arg("ready_work") = nullptr, + pybind11::arg("destination_offset") = 0); m.def("reflow_lion_update_state_halfgrad", &reflow_ds_lion_state_step_halfgrad_gilfree, "Reflow CPU Lion update state stream with half gradients, GIL-released (C++)", diff --git a/csrc/lion/reflow_cpu_lion_impl.cpp b/csrc/lion/reflow_cpu_lion_impl.cpp index c50f94a678a7..6cae2706a166 100644 --- a/csrc/lion/reflow_cpu_lion_impl.cpp +++ b/csrc/lion/reflow_cpu_lion_impl.cpp @@ -115,27 +115,22 @@ void Reflow_Lion_Optimizer::Step_8_FP16_HalfGrad(float* _params_fp32, size_t copy_size = TILE; if ((t + TILE) > _param_size) copy_size = _param_size - t; size_t offset = copy_size + t; - ReflowCPUAffinity affinity; -#pragma omp parallel - { - affinity.apply(); -#pragma omp for schedule(static) nowait - for (size_t k = t; k < offset; k++) { - float grad = static_cast(grads_half[k]) * unscale_factor; - float param = _params_fp32[k]; - float momentum = static_cast(_exp_avg[k]); - float tmp = momentum * _betta1; - tmp = grad * betta1_minus1 + tmp; - tmp = -std::copysignf(alpha, tmp); - if (_weight_decay > 0) { - param = param * after_decay + tmp; - } else { - param = param + tmp; - } - // Store param to FP16/BF16 buffer only; the FP32 master and state are skipped. - half_params[k] = ds_store_precision_t(param); + reflow_ready_loop(offset - t, 1, single_ready_writer, false, [&](size_t index) { + const size_t k = t + index; + float grad = static_cast(grads_half[k]) * unscale_factor; + float param = _params_fp32[k]; + float momentum = static_cast(_exp_avg[k]); + float tmp = momentum * _betta1; + tmp = grad * betta1_minus1 + tmp; + tmp = -std::copysignf(alpha, tmp); + if (_weight_decay > 0) { + param = param * after_decay + tmp; + } else { + param = param + tmp; } - } + // Store param to FP16/BF16 buffer only; the FP32 master and state are skipped. + half_params[k] = ds_store_precision_t(param); + }); } } } @@ -268,8 +263,11 @@ int reflow_ds_lion_step_params_halfgrad(int optimizer_id, torch::Tensor& exp_avg, torch::Tensor& half_params, float combined_scale, - bool skip_increment_step) + bool skip_increment_step, + ReflowReadyWork* work, + size_t destination_offset) { + TORCH_CHECK(!work || half_params.is_contiguous(), "Deferred Ready requires contiguous output"); auto params_c = params_fp32.contiguous(); auto grads_c = grads.contiguous(); auto exp_avg_c = exp_avg.contiguous(); @@ -312,54 +310,55 @@ int reflow_ds_lion_step_params_halfgrad(int optimizer_id, unsigned int reflow_total_cpus = reflow_lion_get_available_cpu_count(); unsigned int reflow_max_omp_threads = reflow_lion_resolve_omp_threads(worker_opt.get_num_threads(), reflow_total_cpus); - int reflow_original_omp_threads = omp_get_max_threads(); - omp_set_num_threads(reflow_max_omp_threads); -#if defined(__AVX512__) or defined(__AVX256__) - if (store_type == torch::kFloat16 && grad_type == torch::kFloat16 && - state_type == torch::kFloat32) { - worker_opt.Step_8_FP16_HalfGrad( - params_c.data_ptr(), - grads_c.data_ptr(), - exp_avg_c.data_ptr(), - param_size, - half_params_c.data_ptr(), - combined_scale); - } else if (store_type == torch::kFloat16 && grad_type == torch::kFloat16 && + auto dispatch = [&](auto half, auto state) { + using Half = decltype(half); + using State = decltype(state); + auto* params = params_c.data_ptr(); + auto* grad = grads_c.data_ptr(); + auto* momentum = exp_avg_c.data_ptr(); + + auto* output = half_params_c.data_ptr(); + worker_opt.single_ready_writer = work != nullptr; + auto kernel = [=](size_t start, size_t size) mutable { + worker_opt.Step_8_FP16_HalfGrad(params + start, + grad + start, + momentum + start, + size, + output + start, + combined_scale); + }; + if (work) { + work->add(destination_offset, + reflow_max_omp_threads, + half_params_c, + {params_c, grads_c, exp_avg_c}, + std::move(kernel)); + } else { + const int previous_threads = omp_get_max_threads(); + omp_set_num_threads(reflow_max_omp_threads); + kernel(0, param_size); + omp_set_num_threads(previous_threads); + } + }; +#if defined(__AVX512__) || defined(__AVX256__) + if (store_type == grad_type && grad_type == torch::kFloat16 && state_type == torch::kFloat32) { + dispatch(c10::Half{}, float{}); + } else if (store_type == grad_type && grad_type == torch::kFloat16 && state_type == torch::kFloat16) { - worker_opt.Step_8_FP16_HalfGrad( - params_c.data_ptr(), - grads_c.data_ptr(), - exp_avg_c.data_ptr(), - param_size, - half_params_c.data_ptr(), - combined_scale); - } else if (store_type == torch::kBFloat16 && grad_type == torch::kBFloat16 && + dispatch(c10::Half{}, c10::Half{}); + } else if (store_type == grad_type && grad_type == torch::kBFloat16 && state_type == torch::kFloat32) { - worker_opt.Step_8_FP16_HalfGrad( - params_c.data_ptr(), - grads_c.data_ptr(), - exp_avg_c.data_ptr(), - param_size, - half_params_c.data_ptr(), - combined_scale); - } else if (store_type == torch::kBFloat16 && grad_type == torch::kBFloat16 && + dispatch(c10::BFloat16{}, float{}); + } else if (store_type == grad_type && grad_type == torch::kBFloat16 && state_type == torch::kBFloat16) { - worker_opt.Step_8_FP16_HalfGrad( - params_c.data_ptr(), - grads_c.data_ptr(), - exp_avg_c.data_ptr(), - param_size, - half_params_c.data_ptr(), - combined_scale); + dispatch(c10::BFloat16{}, c10::BFloat16{}); } else #endif { - omp_set_num_threads(reflow_original_omp_threads); throw std::runtime_error( "reflow_ds_lion_step_params_halfgrad: unsupported combination of store/grad/state " "dtypes"); } - omp_set_num_threads(reflow_original_omp_threads); return 0; } diff --git a/deepspeed/runtime/reflow/README.md b/deepspeed/runtime/reflow/README.md index 0f9d705d5444..31889fb47eb0 100644 --- a/deepspeed/runtime/reflow/README.md +++ b/deepspeed/runtime/reflow/README.md @@ -124,8 +124,7 @@ to the original optimizer cannot follow the remapping and is rejected. "reflow": { "enable_cpu_affinity": true, // restrict the main process to NUMA-local cores; workers are always pinned "main_thread_cores": 2, // cores reserved for the forward/backward (main) thread - "bucketwise_cores_per_worker": 7, // cores per bucketwise CPU-Adam worker; worker count = - // (rank worker cores) / this value + "bucketwise_cores_per_worker": null, // one optimizer worker for this rank's remaining CPUs "state_update_cores": 2 // optional forward limit for the background state commit // (default: all worker CPUs) // "num_threads": // CPU-Adam threads (default: all available cores) @@ -168,7 +167,7 @@ rejected when main-thread pinning is enabled. The following options allow other | `main_thread_core_type` | `"logical"` | `"physical"` counts physical cores and reserves all their available SMT siblings. | | `pin_main_thread` | `true` | Pins the initializing thread to the reserved main CPUs; `engine.destroy()` restores its original affinity. | | `worker_core_type` | `"logical"` | `"physical"` uses one logical CPU per remaining physical core. | -| `bucketwise_cores_per_worker` | `8` | Maximum logical CPUs per bucketwise worker; the last mask within a NUMA node may be smaller. | +| `bucketwise_cores_per_worker` | `null` | One optimizer worker uses the rank's worker CPUs by default. A positive limit splits each NUMA-local CPU set into groups of at most that size. | | `bucketwise_worker_affinity` | `"thread"` | `"task"` assigns CPU masks round-robin; `"thread"` reuses a fixed mask per thread for bucketwise work. Persist temporarily uses its phase-specific mask. | | `state_update_cores` | `null` | Caps the worker CPU IDs used by the state commit during forward; `null` uses all worker CPUs. | | `state_update_backward_cores` | `null` | Caps the number of worker CPU IDs used by the state commit during backward; `null` uses all worker CPUs. `state_update_cores` still controls its forward mask. | diff --git a/deepspeed/runtime/reflow/ready_batch.py b/deepspeed/runtime/reflow/ready_batch.py new file mode 100644 index 000000000000..ef69974cb2b6 --- /dev/null +++ b/deepspeed/runtime/reflow/ready_batch.py @@ -0,0 +1,106 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team + +import threading +from collections import deque + +from deepspeed.accelerator import get_accelerator + + +class ReadyBatch: + """Consecutive independent Ready jobs owned by one shared optimizer executor future.""" + + def __init__(self, optimizer, item): + self.optimizer = optimizer + self.lock = threading.Lock() + self.pending = deque() + self.bounds = {} + self.window = (item["grad_buffer_index"], item["cancel_version"], item["target_step"]) + self.closed = False + self.active = None + self.future = None + self.append(item) + + def append(self, item): + window = (item["grad_buffer_index"], item["cancel_version"], item["target_step"]) + group = item["sub_group_id"] + ranges = item["ranges"] + first = ranges[0][0] + last_offset, last_size = ranges[-1] + last = last_offset + last_size + with self.lock: + if self.closed or window != self.window: + return False + previous = self.bounds.get(group) + if previous is not None: + # Reentrant edits and clipping can regenerate a range. An intersecting + # span stays in FIFO order behind this batch, even if it contains gaps. + if first < previous[1] and last > previous[0]: + return False + first, last = min(first, previous[0]), max(last, previous[1]) + self.bounds[group] = (first, last) + self.pending.append(item) + return True + + def discard(self): + with self.lock: + self.closed = True + self.pending.clear() + if self.active is not None: + self.active.cancel() + + def _take(self, wait): + with self.lock: + if not self.pending: + if wait: + self.closed = True + return None + item = self.pending[0] + if not wait: + event = item["last_copy_event"] + commit = self.optimizer._pending_state_updates_by_subgroup.get(item["sub_group_id"]) + if commit is not None and not commit.done(): + return None + if event is not None: + if not event.query(): + return None + # This job owns its event reference. A successful query already + # observed the D2H completion required by the CPU kernel. + item["last_copy_event"] = None + self.pending.popleft() + return self.optimizer._bucketwise_chunk_update_worker(item, defer=True) + + def _take_eligible(self): + return self._take(wait=False) + + def run(self): + stream = self.optimizer._bucketwise_h2d_stream + started = False + try: + while True: + work = self._take(wait=True) + if work is None: + with self.lock: + if self.closed: + break + continue + with self.lock: + if self.closed: + break + self.active = work + started = True + work.run(self._take_eligible) + if started: + # All helpers have returned from copy submission, including any prefix + # of a cancelled job. One stream event protects all their pinned slots. + event = get_accelerator().Event() + event.record(stream) + return event + except BaseException: + stream.synchronize() + raise + finally: + with self.lock: + self.closed = True + self.active = None + self.pending.clear() diff --git a/deepspeed/runtime/reflow/reflow_config.py b/deepspeed/runtime/reflow/reflow_config.py index c3bffcc4a969..1cadacdfca2e 100644 --- a/deepspeed/runtime/reflow/reflow_config.py +++ b/deepspeed/runtime/reflow/reflow_config.py @@ -35,9 +35,12 @@ class ReflowConfig(DeepSpeedConfigModel): bucketwise_worker_affinity: Literal["task", "thread"] = "thread" """Choose a CPU mask per bucketwise task, or reuse a fixed bucketwise mask on each pool thread.""" - bucketwise_cores_per_worker: int = Field(8, ge=1) - """Cores per bucketwise optimizer worker. The worker count follows from the cores available - to the rank divided by this value.""" + bucketwise_cores_per_worker: Optional[int] = Field(None, ge=1) + """By default one optimizer worker uses the rank's worker CPUs. Set a limit to split + each NUMA-local CPU set among multiple workers.""" + + h2d_chunk_size_mib: int = Field(16, ge=1) + """Maximum MiB per host-to-device transfer of Ready parameters.""" state_update_cores: Optional[int] = Field(None, ge=1) """Limit worker CPUs used by the background state commit during forward; ``None`` uses all worker CPUs.""" diff --git a/deepspeed/runtime/reflow/reflow_stage3.py b/deepspeed/runtime/reflow/reflow_stage3.py index 3c4f32dd0d33..2bced427ae9c 100644 --- a/deepspeed/runtime/reflow/reflow_stage3.py +++ b/deepspeed/runtime/reflow/reflow_stage3.py @@ -15,6 +15,7 @@ import deepspeed.comm as dist from deepspeed.comm import pg_utils from deepspeed.accelerator import get_accelerator +from deepspeed.runtime.reflow.ready_batch import ReadyBatch from deepspeed.runtime.reflow.reflow_cpu_adam import ReflowCPUAdam from deepspeed.runtime.reflow import reflow_utils from deepspeed.runtime.swap_tensor.partitioned_param_swapper import PartitionedParamStatus @@ -211,24 +212,24 @@ def _setup_optimizer_workers(self): self._setup_bucketwise_executors() def _setup_bucketwise_executors(self): - bucketwise_cores_per_worker = max(1, int(self.bucketwise_cores_per_worker)) + cores_per_worker = self.bucketwise_cores_per_worker try: - # Build one affinity mask per worker by chunking EACH NUMA node's worker cores - # separately, so a worker's cores never span two NUMA nodes. node_groups = getattr(self, "_worker_node_groups", None) if not node_groups: fallback_cores = sorted(list( self._worker_cpu_affinity_mask)) or reflow_utils.resolve_available_cores()[1] node_groups = [fallback_cores] - self._bucketwise_worker_cpu_affinity_masks = [] - for node_cores in node_groups: - for start_idx in range(0, len(node_cores), bucketwise_cores_per_worker): - chunk = node_cores[start_idx:start_idx + bucketwise_cores_per_worker] - if chunk: - self._bucketwise_worker_cpu_affinity_masks.append(set(chunk)) - if not self._bucketwise_worker_cpu_affinity_masks: + if cores_per_worker is None: + self._bucketwise_worker_cpu_affinity_masks = [set().union(*node_groups)] + else: + self._bucketwise_worker_cpu_affinity_masks = [] + for node_cores in node_groups: + for start in range(0, len(node_cores), cores_per_worker): + self._bucketwise_worker_cpu_affinity_masks.append( + set(node_cores[start:start + cores_per_worker])) + if not any(self._bucketwise_worker_cpu_affinity_masks): self._bucketwise_worker_cpu_affinity_masks = [set(sorted(self._worker_cpu_affinity_mask) or [0])] max_bucketwise_workers = len(self._bucketwise_worker_cpu_affinity_masks) @@ -236,7 +237,7 @@ def _setup_bucketwise_executors(self): if dist.get_rank() == 0: logger.info(f"Bucketwise worker configuration (NUMA-aware): {max_bucketwise_workers} workers " f"across {len(node_groups)} NUMA node group(s), " - f"{bucketwise_cores_per_worker} cores per worker, " + f"{cores_per_worker or total_worker_cores} cores per worker, " f"total {total_worker_cores} worker cores") except Exception as e: max_bucketwise_workers = 1 @@ -289,7 +290,29 @@ def run(): return self._bucketwise_update_executor.submit(run) + self._ready_batches = {} self._bucketwise_update_submit = _submit_bucketwise_task + if max_bucketwise_workers == 1 and len(self._bucketwise_worker_cpu_affinity_masks[0]) > 1 and \ + self._reflow_config.num_threads != 1: + submit_lock = threading.Lock() + tail = None + + def submit(fn, *args, **kwargs): + nonlocal tail + with submit_lock: + if fn == self._bucketwise_chunk_update_worker and self._can_batch_ready(args[0]): + item = args[0] + if tail is not None and not tail.future.done() and tail.append(item): + return tail.future + tail = ReadyBatch(self, item) + tail.future = _submit_bucketwise_task(tail.run) + self._ready_batches[tail.future] = tail + return tail.future + # Never take work from beyond an accumulation, Persist, or staged Ready. + tail = None + return _submit_bucketwise_task(fn, *args, **kwargs) + + self._bucketwise_update_submit = submit self._bucketwise_inflight_futures = [] # Backward and step own this registry; executor workers never access it. self._bucketwise_accumulation_futures = {} @@ -358,6 +381,10 @@ def destroy(self): executor.shutdown(wait=True) except Exception: pass + # A finished or cancelled Ready may still have DMA reading its pinned output. + h2d_stream = getattr(self, "_bucketwise_h2d_stream", None) + if h2d_stream is not None: + h2d_stream.synchronize() # The base _unpin_offload_buffers does not know Reflow's half-precision grad buffers; under the native # pinning backend they would otherwise stay page-locked after destroy. Safe now that no worker uses them. # The native unpin frees the memory, so drop the references too. @@ -451,6 +478,8 @@ def _drain_update_futures_collecting_h2d_events(self, futures, publish_staged=Fa continue except Exception as error: self._record_bucketwise_worker_error(error) + finally: + self._ready_batches.pop(future, None) if publish_staged and not publish_each and self._bucketwise_worker_error is None: try: for group, ranges in self._staged_ready_ranges.items(): @@ -630,11 +659,11 @@ def initialize_optimizer_states(self): # the param output is written into fp16_flat instead of a second slot. num_grad_slots = 1 if self._single_grad_buffer else 2 for _ in range(num_grad_slots): - subgroup_gradient_buffer = torch.zeros(num_elements, - dtype=grad_dtype, - device=self.subgroup_to_device[i]) - if self.offload_optimizer_pin_memory and self.subgroup_to_device[i] == 'cpu': - subgroup_gradient_buffer = get_accelerator().pin_memory(subgroup_gradient_buffer) + device = self.subgroup_to_device[i] + if self.offload_optimizer_pin_memory and device == 'cpu': + subgroup_gradient_buffer = get_accelerator().pin_empty(num_elements, dtype=grad_dtype).zero_() + else: + subgroup_gradient_buffer = torch.zeros(num_elements, dtype=grad_dtype, device=device) grad_buffers.append(subgroup_gradient_buffer) self._cpu_grad_double_buffers.append(grad_buffers) # The half-precision grad dtype differs from the FP32 param, so leave .grad unset; @@ -1141,8 +1170,18 @@ def _bucketwise_clip_range_to_valid_partition(self, sub_group_id: int, dest_offs valid_partition_element_count = self._bucketwise_get_valid_partition_element_count(sub_group_id) return reflow_utils.clip_range_to_valid_partition(valid_partition_element_count, dest_offset, num_elements) - def _bucketwise_chunk_update_worker(self, work_item): + def _can_batch_ready(self, item): + if item["stage_copy"] or self.swap_optimizer or not self.offload_optimizer_pin_memory: + return False + dst = self.fp16_partitioned_groups_flat[item["sub_group_id"]] + if dst is None or dst.device.type != "cuda" or self._bucketwise_h2d_stream is None: + return False + chunk_elems = (self._reflow_config.h2d_chunk_size_mib << 20) // dst.element_size() + return any(size >= chunk_elems for _, size in item["ranges"]) + + def _bucketwise_chunk_update_worker(self, work_item, defer=False): # Worker: run the partial Adam update, then async-copy only the updated ranges to GPU. + direct_cpu_output = False try: sub_group_id = work_item["sub_group_id"] ranges = work_item["ranges"] @@ -1175,21 +1214,22 @@ def _bucketwise_chunk_update_worker(self, work_item): # grad_buffer_index holds the grads (slot 0 in single-buffer mode). half_grad_buffer = self._cpu_grad_double_buffers[sub_group_id][grad_buffer_index] - if self._single_grad_buffer: - # Single-buffer mode has no opposite slot, so the kernel writes the params straight into fp16_flat, - # which that slot would only have duplicated. Grads are still read from slot 0. - half_params_buffer = self.fp16_partitioned_groups_flat[sub_group_id] + fp16_flat = self.fp16_partitioned_groups_flat[sub_group_id] + # Keep staged previews private until step() publishes them. NVMe can still need + # the opposite slot as its swap source. Resident CPU params already own the output. + direct_cpu_output = (fp16_flat is not None and fp16_flat.device.type == "cpu" + and not work_item["stage_copy"] and not self.swap_optimizer + and not self.params_in_nvme_and_cpu) + if self._single_grad_buffer or direct_cpu_output: + half_params_buffer = fp16_flat else: - # Cross-buffer: FP16 param output goes to the slot opposite the grads. - fp16_output_buffer_index = 1 - grad_buffer_index - half_params_buffer = self._cpu_grad_double_buffers[sub_group_id][fp16_output_buffer_index] + half_params_buffer = self._cpu_grad_double_buffers[sub_group_id][1 - grad_buffer_index] use_lion = hasattr(self.optimizer, "ds_opt_lion") if not use_lion and not hasattr(self.optimizer, "ds_opt_adam"): raise RuntimeError("cpu_bucketwise requires a Reflow CPU optimizer (ReflowCPUAdam or ReflowCPULion)") - p = fp32_param - state = self.optimizer.state[p] + state = self.optimizer.state[fp32_param] lr = work_item.get("lr") beta1 = work_item.get("beta1") @@ -1203,79 +1243,60 @@ def _bucketwise_chunk_update_worker(self, work_item): if target_step is None: target_step = int(state.get('step', 0)) + 1 - # Lion has no second moment, epsilon, or bias correction. - if use_lion: - for range_idx, (offset, size) in enumerate(ranges): - range_increment_step = increment_step and (range_idx == 0) - - param_slice = p.data.view(-1).narrow(0, offset, size) - grad_slice = half_grad_buffer.view(-1).narrow(0, offset, size) - exp_avg_slice = state['exp_avg'].view(-1).narrow(0, offset, size) - half_params_slice = half_params_buffer.view(-1).narrow(0, offset, size) - + master = fp32_param.detach().view(-1) + grads = half_grad_buffer.view(-1) + momentum = state['exp_avg'].view(-1) + variance = None if use_lion else state['exp_avg_sq'].view(-1) + output = half_params_buffer.view(-1) + + work = None + if defer: + native = self.optimizer.ds_opt_lion if use_lion else self.optimizer.ds_opt_adam + chunk_elems = (self._reflow_config.h2d_chunk_size_mib << 20) // fp16_flat.element_size() + work = native.ReadyWork(fp16_flat, self._bucketwise_h2d_stream, chunk_elems) + + def prepare_range(offset, size, output_slice): + nonlocal increment_step + if cancel_version != self._bucketwise_cancel_version: + return False + param_slice = master.narrow(0, offset, size) + grad_slice = grads.narrow(0, offset, size) + momentum_slice = momentum.narrow(0, offset, size) + deferred = (work, offset) if defer else () + if use_lion: self.optimizer.ds_opt_lion.reflow_lion_update_params_halfgrad( - self.optimizer.opt_id, - target_step, - lr, - beta1, - beta2, - weight_decay, - param_slice, - grad_slice, - exp_avg_slice, - half_params_slice, - combined_scale, - not range_increment_step, - ) - - self.optimizer.ds_opt_lion.reflow_lion_memory_fence() - else: - for range_idx, (offset, size) in enumerate(ranges): - range_increment_step = increment_step and (range_idx == 0) - - param_slice = p.data.view(-1).narrow(0, offset, size) - grad_slice = half_grad_buffer.view(-1).narrow(0, offset, size) - exp_avg_slice = state['exp_avg'].view(-1).narrow(0, offset, size) - exp_avg_sq_slice = state['exp_avg_sq'].view(-1).narrow(0, offset, size) - half_params_slice = half_params_buffer.view(-1).narrow(0, offset, size) - + self.optimizer.opt_id, target_step, lr, beta1, beta2, weight_decay, param_slice, grad_slice, + momentum_slice, output_slice, combined_scale, not increment_step, *deferred) + else: self.optimizer.ds_opt_adam.reflow_adam_update_params_halfgrad( - self.optimizer.opt_id, - target_step, - lr, - beta1, - beta2, - eps, - weight_decay, - bias_correction, - param_slice, - grad_slice, - exp_avg_slice, - exp_avg_sq_slice, - half_params_slice, - combined_scale, - not range_increment_step, - maximize, - ) - - self.optimizer.ds_opt_adam.reflow_adam_memory_fence() + self.optimizer.opt_id, target_step, lr, beta1, beta2, eps, + weight_decay, bias_correction, param_slice, grad_slice, momentum_slice, + variance.narrow(0, offset, + size), output_slice, combined_scale, not increment_step, maximize, *deferred) + increment_step = False + return cancel_version == self._bucketwise_cancel_version - if cancel_version != getattr(self, "_bucketwise_cancel_version", 0): - return None - - if self._single_grad_buffer: - # Single-buffer mode already wrote the params into fp16_flat. No H2D event is needed: they are - # CPU-resident, and step() joins this worker before the next forward reads them. - return None + if not defer and fp16_flat is not None and fp16_flat.device.type != "cpu" and not work_item["stage_copy"]: + return self._copy_ready_ranges(fp16_flat, output, ranges, prepare=prepare_range) - fp16_flat = self.fp16_partitioned_groups_flat[sub_group_id] - if fp16_flat is None: + for offset, size in ranges: + if not prepare_range(offset, size, output.narrow(0, offset, size)): + return None + if defer: + return work + if fp16_flat is None or half_params_buffer is fp16_flat: return None - if work_item["stage_copy"]: return _StagedReady(sub_group_id, ranges) - return self._copy_ready_ranges(fp16_flat, half_params_buffer, ranges) + return self._copy_ready_ranges(fp16_flat, output, ranges) except Exception as e: + if direct_cpu_output: + # A failed kernel may already have written part of the public CPU partition. + # This work owns these disjoint ranges, and Persist has not committed this step. + source = fp32_param.detach().view(-1) + destination = fp16_flat.detach().view(-1) + for offset, size in ranges: + destination.narrow(0, offset, size).copy_(source.narrow(0, offset, size)) # A cooperative cancel (version bump) can race the kernel and surface as a transient # error; if this work item has been cancelled, treat it as a clean no-op like the # explicit cancel returns above. Otherwise this is a real kernel/OOM failure: record it @@ -1286,18 +1307,35 @@ def _bucketwise_chunk_update_worker(self, work_item): logger.warning(f"Reflow bucketwise worker error (rank {dist.get_rank()}): {e}") return None - def _copy_ready_ranges(self, fp16_flat, output, ranges): + def _copy_ready_ranges(self, fp16_flat, output, ranges, prepare=None): + accelerator = get_accelerator() stream = self._bucketwise_h2d_stream if stream is None: - stream = get_accelerator().current_stream() + stream = accelerator.current_stream() dst, src = fp16_flat.detach().view(-1), output.detach().view(-1) - with get_accelerator().stream(stream): + if dst.device.type != "cpu": + chunk_elems = (self._reflow_config.h2d_chunk_size_mib << 20) // dst.element_size() + ranges = reflow_utils.iter_range_chunks(ranges, chunk_elems) + submitted = False + try: for offset, size in ranges: - dst.narrow(0, offset, size).copy_(src.narrow(0, offset, size), non_blocking=True) - if not get_accelerator().is_synchronized_device(): - event = get_accelerator().Event() + src_slice = src.narrow(0, offset, size) + if prepare is not None and not prepare(offset, size, src_slice): + break + with accelerator.stream(stream): + dst.narrow(0, offset, size).copy_(src_slice, non_blocking=True) + submitted = True + # A cancelled Ready can already have submitted a prefix. Its one event protects + # that pinned slot until replay, cleanup or the following backward can reuse it. + if submitted and not accelerator.is_synchronized_device(): + event = accelerator.Event() event.record(stream) return event + except Exception: + # No event will reach the caller if a kernel or copy fails after an earlier DMA. + if stream is not None: + stream.synchronize() + raise def _publish_staged_ready(self, sub_group_id, ranges): self._published_ready_groups.add(sub_group_id) @@ -1466,7 +1504,8 @@ def _prepare_state_and_params(): } future = self._bucketwise_update_submit(self._bucketwise_chunk_update_worker, work_item) - self._bucketwise_inflight_futures.append(future) + if not self._bucketwise_inflight_futures or self._bucketwise_inflight_futures[-1] is not future: + self._bucketwise_inflight_futures.append(future) return future def _bucketwise_flush_all_pending(self, force=False, use_pending_buffer=True, combined_scale=None): @@ -1481,6 +1520,9 @@ def _bucketwise_cancel_inflight_updates(self): self._bucketwise_cancel_version += 1 for f in list(getattr(self, "_bucketwise_inflight_futures", [])): try: + batch = self._ready_batches.get(f) + if batch is not None: + batch.discard() f.cancel() except Exception: pass @@ -1520,6 +1562,9 @@ def _bucketwise_wait_inflight_updates(self, discard_queued=False, publish_staged return if discard_queued: for future in futures: + batch = self._ready_batches.get(future) + if batch is not None: + batch.discard() future.cancel() self._drain_update_futures_collecting_h2d_events(futures, publish_staged=publish_staged) futures.clear() diff --git a/deepspeed/runtime/reflow/reflow_utils.py b/deepspeed/runtime/reflow/reflow_utils.py index 8b4d4af5c478..2cfc715d0a95 100644 --- a/deepspeed/runtime/reflow/reflow_utils.py +++ b/deepspeed/runtime/reflow/reflow_utils.py @@ -445,6 +445,13 @@ def merge_contiguous_ranges(ranges): return merged +def iter_range_chunks(ranges, chunk_elems): + """Split each contiguous range independently so DMA never crosses a gap between Ready weights.""" + for offset, size in ranges: + for start in range(0, size, chunk_elems): + yield offset + start, min(chunk_elems, size - start) + + def clip_range_to_valid_partition(valid_partition_element_count, dest_offset, num_elements): """Clamp a single (dest_offset, num_elements) range to the valid partition. diff --git a/docs/_pages/config-json.md b/docs/_pages/config-json.md index 677283573939..fdba129cbbc8 100644 --- a/docs/_pages/config-json.md +++ b/docs/_pages/config-json.md @@ -730,7 +730,8 @@ The `reflow` block enables it, so an empty block is enough to run with the defau "pin_main_thread": true, "worker_core_type": "logical", "bucketwise_worker_affinity": "thread", - "bucketwise_cores_per_worker": 8, + "bucketwise_cores_per_worker": null, + "h2d_chunk_size_mib": 16, "state_update_cores": null, "state_update_backward_cores": null } @@ -777,11 +778,17 @@ The `reflow` block enables it, so an empty block is enough to run with the defau | ----------- | ------- | | Assign a CPU mask per bucketwise task (`task`) or reuse a fixed bucketwise mask on each pool thread (`thread`). A thread running a state commit temporarily uses the commit mask. | `"thread"` | -***bucketwise_cores_per_worker***: [integer] +***bucketwise_cores_per_worker***: [integer or null] | Description | Default | | ----------- | ------- | -| Maximum worker CPU IDs per bucketwise worker. Each NUMA group is split into chunks of this size; the final chunk may be smaller. One pool thread is created per chunk. | `8` | +| By default one optimizer worker uses the CPUs assigned to the rank after the main-thread reservation. A positive integer splits each NUMA-local group into workers with at most that many CPU IDs. | `null` | + +***h2d_chunk_size_mib*** (positive integer) + +| Description | Default | +| ----------- | ------- | +| Maximum size in MiB (1,048,576 bytes) of a Ready parameter copy from CPU to the accelerator. Each completed chunk can transfer while the CPU computes the next one. Checkpointed ranges wait until they are safe to publish. | `16` | ***state_update_cores***: [integer or null] diff --git a/docs/_tutorials/reflow.md b/docs/_tutorials/reflow.md index acb49b53e505..4cbf233d0c5a 100644 --- a/docs/_tutorials/reflow.md +++ b/docs/_tutorials/reflow.md @@ -31,8 +31,7 @@ Reflow needs no model code changes. Enable it in the DeepSpeed configuration: }, "reflow": { "enable_cpu_affinity": true, - "main_thread_cores": 2, - "bucketwise_cores_per_worker": 8 + "main_thread_cores": 2 } }, "optimizer": { @@ -52,7 +51,9 @@ Launch with `--bind_cores_to_rank` so each rank runs on the CPU cores local to i deepspeed --bind_cores_to_rank train.py --deepspeed_config ds_config.json ``` -By default Reflow pins the initializing thread to `main_thread_cores` CPU IDs and divides the remaining CPUs among optimizer workers. Local ranks sharing a CPU set divide it before reserving their main CPUs; partially overlapping rank affinities are rejected. If the requested reservation leaves no worker CPU, Reflow reduces it to leave at least one CPU each for the main thread and workers. If only one CPU is available, they share it; ranks also share CPUs when there are fewer CPUs than ranks. The state commit may use all worker CPUs unless `state_update_cores` or `state_update_backward_cores` sets a limit. `enable_cpu_affinity` additionally restricts the main process to its NUMA-local CPU slice. +By default Reflow pins the initializing thread to `main_thread_cores` CPU IDs and gives the remaining CPUs assigned to the rank to one optimizer worker. Set `bucketwise_cores_per_worker` to split each NUMA-local group among multiple workers. Local ranks sharing a CPU set divide it before reserving their main CPUs; partially overlapping rank affinities are rejected. If the requested reservation leaves no worker CPU, Reflow reduces it to leave at least one CPU each for the main thread and workers. If only one CPU is available, they share it; ranks also share CPUs when there are fewer CPUs than ranks. The state commit may use all worker CPUs unless `state_update_cores` or `state_update_backward_cores` sets a limit. `enable_cpu_affinity` additionally restricts the main process to its NUMA-local CPU slice. + +Reflow copies each contiguous range of Ready weights to the accelerator in chunks of at most 16 MiB. Set `zero_optimization.reflow.h2d_chunk_size_mib` to a positive integer to change this limit. CPU computation can overlap the transfer of an earlier chunk. Weights needed by checkpoint recomputation wait for their normal publication point. With one optimizer worker using multiple CPU threads and pinned gradients, large direct CUDA transfers share an OpenMP team. Each writer can start its portion of the next independent chunk after fencing its own stores. The last writer submits the completed chunk to the copy stream. ## Gradient clipping diff --git a/tests/unit/v1/ops/test_reflow_cpu_optimizers.py b/tests/unit/v1/ops/test_reflow_cpu_optimizers.py index eb0d78d5ae01..3e9ddecf5e02 100644 --- a/tests/unit/v1/ops/test_reflow_cpu_optimizers.py +++ b/tests/unit/v1/ops/test_reflow_cpu_optimizers.py @@ -293,6 +293,44 @@ def test_phase1_produces_bf16_and_defers(self, model_size, grad_dtype, weight_de torch.testing.assert_close(exp_avg, exp_avg_before, atol=0, rtol=0) +@pytest.mark.parametrize("optimizer_kind", ["adam", "lion"]) +@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16]) +@pytest.mark.parametrize("offset", [0, 1, 8, 16]) +def test_ready_writers_publish_aligned_and_unaligned_output(optimizer_kind, dtype, offset): + builder = ReflowCPUAdamBuilder if optimizer_kind == "adam" else ReflowCPULionBuilder + if not deepspeed.ops.__compatible_ops__.get(builder.NAME, False): + pytest.skip("Reflow optimizer builder unavailable") + _skip_amd_fp16(dtype) + module = builder().load() + opt_id = _next_opt_id() + size = 65539 + master = torch.linspace(-2, 2, size) + # Include FP32 ties for both low precisions, infinities and a NaN in the vector prefix. + special = [1 + 2**-8, 1 + 3 * 2**-8, 1 + 2**-11, 1 + 3 * 2**-11, float("inf"), -float("inf"), float("nan")] + grad = torch.ones(size, dtype=dtype) + momentum = torch.zeros_like(master) + start = 32 + offset + storage = torch.full((start + size + 32, ), -123, dtype=dtype) + output = storage.narrow(0, start, size) + if optimizer_kind == "adam": + module.reflow_create_adam(opt_id, 0., 0.9, 0.99, 1e-8, 0., True, False, 4) + args = [opt_id, 1, 0., 0.9, 0.99, 1e-8, 0., True, master, grad, momentum, torch.zeros_like(master)] + else: + module.reflow_create_lion(opt_id, 0., 0.9, 0.99, 0., False, 4) + args = [opt_id, 1, 0., 0.9, 0.99, 0., master, grad, momentum] + try: + for _ in range(3): + master.neg_() + master[:len(special)] = torch.tensor(special) + output.fill_(-123) + getattr(module, f"reflow_{optimizer_kind}_update_params_halfgrad")(*args, output, 1., False) + # The return from Ready itself publishes every writer's output, including its scalar tail. + torch.testing.assert_close(output, master.to(dtype), rtol=0, atol=0, equal_nan=True) + assert (storage[:start] == -123).all() and (storage[start + size:] == -123).all() + finally: + getattr(module, f"reflow_destroy_{optimizer_kind}")(opt_id) + + @pytest.mark.parametrize("optimizer_kind", ["adam", "lion"]) def test_reused_kernel_threads_follow_the_worker_cpu_mask(optimizer_kind): import os diff --git a/tests/unit/v1/zero/test_reflow.py b/tests/unit/v1/zero/test_reflow.py index 8ff8d7d44f5d..a9594365f807 100644 --- a/tests/unit/v1/zero/test_reflow.py +++ b/tests/unit/v1/zero/test_reflow.py @@ -55,7 +55,8 @@ def minimal_reflow_config(reflow=None, **zero_overrides): def test_reflow_block_configures_the_optimizer(): config = DeepSpeedConfig(minimal_reflow_config({"state_update_cores": 4})) assert config.zero_config.reflow.state_update_cores == 4 - assert config.zero_config.reflow.bucketwise_cores_per_worker == 8 + assert config.zero_config.reflow.bucketwise_cores_per_worker is None + assert config.zero_config.reflow.h2d_chunk_size_mib == 16 assert config.zero_config.reflow.bucketwise_worker_affinity == "thread" assert config.zero_config.reflow.pin_main_thread is True assert DeepSpeedConfig(minimal_reflow_config()).zero_config.reflow.state_update_cores is None @@ -68,6 +69,12 @@ def test_reflow_block_configures_the_optimizer(): DeepSpeedConfig(minimal_reflow_config({"state_update_cores": 0})) +@pytest.mark.parametrize("size", [0, -1]) +def test_reflow_rejects_nonpositive_h2d_chunks(size): + with pytest.raises(ValueError, match="h2d_chunk_size_mib"): + DeepSpeedConfig(minimal_reflow_config({"h2d_chunk_size_mib": size})) + + def test_cpu_placement_options_are_validated(): options = { "main_thread_core_type": "physical", @@ -480,7 +487,7 @@ def get_variant_config(reflow, variant): return config -def train_and_collect(model, config, batches, client_optimizer=None, on_initialize=None): +def train_and_collect(model, config, batches, client_optimizer=None, on_initialize=None, state_keys=()): engine, _, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), optimizer=client_optimizer, @@ -494,12 +501,15 @@ def train_and_collect(model, config, batches, client_optimizer=None, on_initiali engine.backward(loss) engine.step() losses.append(loss.detach().clone()) - return { + result = { "losses": losses, "fp32_params": [safe_get_full_fp32_param(param).clone() for param in engine.module.parameters()], "skipped_steps": engine.skipped_steps, "cpu_optimizer": type(engine.optimizer.optimizer), } + for key in state_keys: + result[key] = [safe_get_full_optimizer_state(param, key).clone() for param in engine.module.parameters()] + return result finally: engine.destroy() @@ -640,6 +650,182 @@ def run(reflow): class TestReflowSharedOptimizerWorker(DistributedTest): world_size = 1 + @pytest.mark.parametrize("optimizer_kind, dtype, clip", [("adam", torch.bfloat16, 0.01), + ("lion", torch.float16, 0.)]) + def test_training_across_h2d_chunk_boundaries(self, optimizer_kind, dtype, clip): + skip_if_reflow_training_unsupported(optimizer_kind) + torch.manual_seed(1234) + # A single weight is larger than one 1 MiB transfer. Later forwards consume both pieces. + model = SimpleModel(hidden_dim=768, nlayers=2) + batches = make_batches(768, count=4, dtype=dtype) + + state_keys = ("exp_avg", "exp_avg_sq") if optimizer_kind == "adam" else ("exp_avg", ) + + def run(reflow): + config = get_variant_config(reflow, optimizer_kind) + config["gradient_clipping"] = clip + if dtype == torch.float16: + config["bf16"]["enabled"] = False + config["fp16"] = {"enabled": True, "loss_scale": 16} + if reflow: + config["zero_optimization"]["reflow"]["h2d_chunk_size_mib"] = 1 + return train_and_collect(copy.deepcopy(model), config, batches, state_keys=state_keys) + + expected, actual = run(False), run(True) + assert expected["skipped_steps"] == actual["skipped_steps"] == 0 + for key in ("losses", "fp32_params", *state_keys): + for want, got in zip(expected[key], actual[key]): + assert torch.equal(want, got) + + def test_failed_ready_restores_cpu_partition(self): + skip_if_reflow_training_unsupported() + torch.manual_seed(1234) + model = torch.nn.Linear(16, 16, bias=False) + config = get_variant_config(True, "offload_param") + config["gradient_clipping"] = 0. + config["optimizer"]["params"]["lr"] = 0.25 + engine, optimizer, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) + try: + partition = model.weight.ds_tensor + expected = partition.clone() + inputs = torch.randn(2, 16, dtype=torch.bfloat16, device=engine.device) + native = optimizer.optimizer.ds_opt_adam + ready = native.reflow_adam_update_params_halfgrad + + def fail_after_write(*args): + ready(*args) + raise RuntimeError("injected failure after CPU Ready store") + + with patch.object(native, "reflow_adam_update_params_halfgrad", fail_after_write): + engine.backward(engine(inputs).sum()) + with pytest.raises(RuntimeError, match="injected failure after CPU Ready store"): + engine.step() + assert torch.equal(partition, expected) + finally: + engine.destroy() + + @pytest.mark.parametrize("optimizer_kind,dtype", [("adam", torch.bfloat16), ("lion", torch.float16)]) + @pytest.mark.parametrize("outcome", ["complete", "cancel", "failure"]) + def test_team_publishes_only_finished_ranges(self, optimizer_kind, dtype, outcome): + # The next Ready can have different scalars and an unrelated destination. Each DMA + # must see every writer's data and leave gaps and a cancelled successor untouched. + skip_if_reflow_training_unsupported(optimizer_kind) + accelerator = get_accelerator() + if accelerator.device_name() != "cuda": + pytest.skip("requires CUDA Ready transfers") + torch.manual_seed(8719) + model = SimpleModel(hidden_dim=16) + config = get_variant_config(True, optimizer_kind) + engine, opt, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) + try: + cpu_opt = opt.optimizer + native = cpu_opt.ds_opt_adam if optimizer_kind == "adam" else cpu_opt.ds_opt_lion + update = getattr(native, f"reflow_{optimizer_kind}_update_params_halfgrad") + stream = accelerator.Stream() + size, chunk = 262151, 65536 + master = torch.randn(size) + grad, momentum = torch.randn(size, dtype=dtype), torch.randn(size) + variance = torch.rand(size) + jobs, destinations, expected = [], [], [] + for step, start in enumerate((0, 5, 16), 1): + dst = torch.full((size + 32, ), -77, device=engine.device, dtype=dtype) + source = torch.empty(size + 32, dtype=dtype, pin_memory=True)[start:start + size] + reference = torch.empty_like(source, pin_memory=False) + job = native.ReadyWork(dst, stream, chunk) + args = [cpu_opt.opt_id, step, 0.1 / step, 0.8, 0.99] + if optimizer_kind == "adam": + args.extend((1e-8, 0.01, True, master, grad, momentum, variance)) + else: + args.extend((0.01, master, grad, momentum)) + flags = [0.5 * step, False] + if optimizer_kind == "adam": + flags.append(step == 2) + update(*args, reference, *flags) + update(*args, source, *flags, job, start) + want = torch.full((size + 32, ), -77, dtype=dtype) + want[start:start + size].copy_(reference) + jobs.append(job) + destinations.append(dst) + expected.append(want) + + stream.wait_stream(accelerator.current_stream()) + + def next_job(): + nonlocal admissions + admissions += 1 + if admissions == 1: + return jobs[1] + if outcome == "failure": + raise RuntimeError("injected Ready admission failure") + if outcome == "cancel": + jobs[0].cancel() + return jobs[2] + return None + + admissions = 0 + if outcome == "failure": + with pytest.raises(RuntimeError, match="injected Ready admission failure"): + jobs[0].run(next_job) + else: + jobs[0].run(next_job) + if outcome == "failure": + assert admissions == 2 # A failed admission must be propagated exactly once. + stream.synchronize() + for dst, want, start in zip(destinations[:2], expected[:2], (0, 5)): + got = dst.cpu() + if outcome == "complete": + assert torch.equal(got, want) + else: + assert (got[:start] == -77).all() and (got[start + size:] == -77).all() + for offset in range(start, start + size, chunk): + end = min(offset + chunk, start + size) + actual = got[offset:end] + assert torch.equal(actual, want[offset:end]) or (actual == -77).all() + assert (destinations[2].cpu() == -77).all() + finally: + engine.destroy() + + def test_cancelled_chunk_keeps_prior_h2d_and_range_gaps(self): + # Cancellation can happen after a prefix has reached the copy stream but before + # the rest is ready. The returned event must still protect that prefix's source. + skip_if_reflow_training_unsupported() + config = get_variant_config(True, "adam") + config["zero_optimization"]["reflow"]["h2d_chunk_size_mib"] = 1 + model = SimpleModel(hidden_dim=16) + engine, opt, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) + event = None + try: + chunk = (1 << 20) // 2 + ranges = [(3, chunk + 11), (chunk + 32, chunk + 7)] + host = torch.zeros(2 * chunk + 64, dtype=torch.bfloat16, pin_memory=True) + device = torch.full_like(host, -1, device=engine.device) + opt._bucketwise_h2d_stream.wait_stream(get_accelerator().current_stream()) + prepared = [] + + def prepare(offset, size, source): + prepared.append((offset, size)) + source.fill_(len(prepared)) + return len(prepared) < 4 + + event = opt._copy_ready_ranges(device, host, ranges, prepare=prepare) + assert event is not None + assert prepared == [(3, chunk), (3 + chunk, 11), (chunk + 32, chunk), (2 * chunk + 32, 7)] + expected = torch.full_like(host, -1) + expected[3:chunk + 3] = 1 + expected[chunk + 3:chunk + 14] = 2 + expected[chunk + 32:2 * chunk + 32] = 3 + finally: + unpin = get_accelerator().unpin_memory + + def unpin_after_copy(buffer): + if event is not None: + assert event.query(), "teardown released pinned memory before the last Ready copy completed" + return unpin(buffer) + + with patch.object(get_accelerator(), "unpin_memory", unpin_after_copy): + engine.destroy() + assert torch.equal(device.cpu(), expected) + @pytest.mark.parametrize("invalid", [False, True]) def test_norm_progresses_while_ready_is_running(self, invalid): # A running preview must allow the clipping/overflow decision to proceed, yet its @@ -950,7 +1136,7 @@ def recorded(*args, _phase=phase, _original=originals[name], **kwargs): expected_workers = rank_cpus - expected_main or rank_cpus assert main_cpus == expected_main assert worker_masks - assert all(mask <= expected_workers for mask in worker_masks) + assert all(mask == expected_workers for mask in worker_masks) assert state_masks assert all(mask == expected_workers for mask in state_masks) placements = [None] * dist.get_world_size() @@ -1885,16 +2071,20 @@ class TestReflowReentrantGradients(DistributedTest): world_size = [1, 2] @pytest.mark.parametrize("optimizer_kind", ["adam", "lion"]) - @pytest.mark.parametrize("gradient_accumulation_steps, clip, precision", [(1, 0., "bf16"), (1, 1000., "bf16"), - (2, 0.1, "bf16"), (1, 0.0001, "fp16"), - (1, 0., "fp16")]) - def test_matches_zero_offload(self, optimizer_kind, gradient_accumulation_steps, clip, precision): + @pytest.mark.parametrize("gradient_accumulation_steps, clip, precision, offload_params", + [(1, 0., "bf16", False), (1, 1000., "bf16", False), (2, 0.1, "bf16", False), + (1, 0.0001, "fp16", False), (1, 0., "fp16", False), + pytest.param(2, 0.1, "bf16", True, id="cpu-partitions-bf16"), + pytest.param(1, 0., "fp16", True, id="cpu-partitions-fp16")]) + def test_matches_zero_offload(self, optimizer_kind, gradient_accumulation_steps, clip, precision, offload_params): skip_if_reflow_training_unsupported(optimizer_kind) def run(reflow): torch.manual_seed(1234) model = ReentrantGradientModel() config = get_variant_config(reflow, optimizer_kind) + if offload_params: + config["zero_optimization"]["offload_param"] = {"device": "cpu", "pin_memory": True} config["data_types"] = {"grad_accum_dtype": precision} dtype = torch.bfloat16 if precision == "fp16": From c72796229f3a2df98f554fff2f930daa244d368c Mon Sep 17 00:00:00 2001 From: st-bang97 Date: Fri, 20 Nov 2026 12:44:23 +0900 Subject: [PATCH 16/19] Apply full-gradient edits to ReFlow accumulation buffers Gather low-precision shards within each parameter's partition group for the FP32 callback. Write the result to the CPU buffer used by Ready and Persist, refresh gradient norms and overflow, and coordinate callback failures before writing a shard. Signed-off-by: st-bang97 --- deepspeed/runtime/reflow/reflow_stage3.py | 114 +++++++++++--- docs/_tutorials/reflow.md | 4 +- tests/unit/v1/zero/test_reflow.py | 183 +++++++++++++++++++++- 3 files changed, 278 insertions(+), 23 deletions(-) diff --git a/deepspeed/runtime/reflow/reflow_stage3.py b/deepspeed/runtime/reflow/reflow_stage3.py index 2bced427ae9c..46ce8017d06b 100644 --- a/deepspeed/runtime/reflow/reflow_stage3.py +++ b/deepspeed/runtime/reflow/reflow_stage3.py @@ -1102,7 +1102,7 @@ def _complete_pending_gradient_window(self): # to overlap here. Use the final scale for their first Ready if clipping is enabled. if has_boundary_norm and self.clip_grad > 0.: ready_after_norm.add(param_id) - else: + elif param_id not in ready_after_norm: self._bucketwise_schedule_enqueue_range(sub_group_id, offset, numel) enqueued_ready = True return enqueued_ready, ready_after_norm @@ -1954,10 +1954,8 @@ def has_overflow(self, partition_gradients=True): return bool(overflow) # ------------------------------------------------------------------ # - # auxiliary APIs unsupported under reflow + # gradient access # ------------------------------------------------------------------ # - # Reflow frees the flat grad buffer and leaves the FP32 .grad unset, so these APIs would fail with an - # opaque AttributeError; raise a clear NotImplementedError instead. def get_fp32_grad_for_param(self, param) -> Tensor: raise NotImplementedError(_REFLOW_FLAT_GRAD_FREED_MSG.format(api="get_fp32_grad_for_param")) @@ -1990,30 +1988,42 @@ def set_local_grad_for_param(self, value, param): if param.partition_numel() * self._get_param_partition_rank(param) >= param.ds_numel: return - # Ready may already be reading this gradient. Join it before changing the buffer; - # the step will regenerate previews after the final clipping scale is known. + self._wait_for_gradient_edits([param_id]) + if self._bucketwise_worker_error is not None: + raise self._bucketwise_worker_error + gradient = self._get_cpu_grad_buffer(sub_group_id, pending=True).narrow(0, offset, numel) + rounded = value.detach().reshape(-1).to(dtype=gradient.dtype) + self._write_gradient_partition(param_id, gradient, rounded) + self._refresh_edited_gradient_overflow() + + def _wait_for_gradient_edits(self, param_ids): + # Join readers once per API call. In FP16 the overflow rescan also reads unedited partitions. if self.dtype == torch.float16: self._wait_for_accum_gradient() else: - self._wait_for_accum_gradient(param_id) + for param_id in param_ids: + self._wait_for_accum_gradient(param_id) self._bucketwise_drain_enq_executor() self._bucketwise_wait_inflight_updates() self.copy_grad_stream.synchronize() if self._single_grad_buffer: - self._wait_for_pending_state_updates(sub_group_id=sub_group_id) - if self._bucketwise_worker_error is not None: - raise self._bucketwise_worker_error - gradient = self._get_cpu_grad_buffer(sub_group_id, pending=True).narrow(0, offset, numel) - gradient.copy_(value.detach().reshape(-1), non_blocking=False) + for group in {self.grad_position[param_id][0] for param_id in param_ids}: + self._wait_for_pending_state_updates(sub_group_id=group) + + def _write_gradient_partition(self, param_id, gradient, rounded): + # Compute the norm from the rounded values that Ready and Persist will actually read. + norm = self._constant_buffered_norm2(rounded.to(get_accelerator().current_device_name())) + gradient[:rounded.numel()].copy_(rounded) + if rounded.numel() < gradient.numel(): + gradient[rounded.numel():].zero_() self._reflow_window_grad_ids.add(param_id) self._pending_grad_ready = True self._reflow_modified_gradient_ids.add(param_id) - gradient_on_device = gradient.to(get_accelerator().current_device_name(), non_blocking=True) - self.norm_for_param_grads[param_id] = self._constant_buffered_norm2(gradient_on_device) + self.norm_for_param_grads[param_id] = norm + def _refresh_edited_gradient_overflow(self): if self.dtype == torch.float16: - # A replacement can remove an earlier overflow, so rebuild the flag from - # this window's stored gradients rather than keeping a stale sticky bit. + # A replacement can remove an earlier overflow. Scan the window once after all edits. invalid = False for active_id in self._reflow_window_grad_ids: group, start, length = self.grad_position[active_id] @@ -2021,9 +2031,75 @@ def set_local_grad_for_param(self, value, param): if not torch.isfinite(active_gradient).all(): invalid = True break - if self._reflow_grad_overflow is None: - self._reflow_grad_overflow = torch.zeros((), dtype=torch.uint8, device=gradient_on_device.device) - self._reflow_grad_overflow.fill_(invalid) + # partition_grads and has_overflow both access this flag on the reduction stream. + with get_accelerator().stream(self.reduce_and_partition_stream): + if self._reflow_grad_overflow is None: + self._reflow_grad_overflow = get_accelerator().ByteTensor([0]) + self._reflow_grad_overflow.fill_(invalid) + + def _full_gradient_edit_error(self, error, group): + if dist.get_world_size(group=group) > 1: + flag = get_accelerator().ByteTensor([int(error is not None)]) + dist.all_reduce(flag, op=dist.ReduceOp.MAX, group=group) + if flag.item() and error is None: + return RuntimeError("Reflow full gradient update failed on another rank") + return error + + def _update_full_gradient_partition(self, param, group, update_func): + param_id = self.get_param_id(param) + subgroup, offset, numel = self.grad_position[param_id] + gradient = self._get_cpu_grad_buffer(subgroup, pending=True).narrow(0, offset, numel) + ranks = dist.get_world_size(group=group) + start = self._get_param_partition_rank(param) * numel + # Gather the stored halves directly into rank order. Only the callback needs an FP32 tensor. + gathered = torch.empty(ranks * numel, dtype=gradient.dtype, device=param.device) + partition = gathered.narrow(0, start, numel) + if param_id in self._reflow_window_grad_ids: + partition.copy_(gradient, non_blocking=True) + else: + partition.zero_() + if ranks > 1: + dist.all_gather_into_tensor(gathered, partition, group=group) + full_grad = gathered[:param.ds_numel].view(param.ds_shape).float() + del gathered, partition + + error = None + try: + value = update_func(full_grad, param) + if value.numel() != param.ds_numel: + raise ValueError(f"Expected {param.ds_numel} gradient elements, got {value.numel()}") + # A callback can return a non-contiguous tensor. Select only the real elements on this rank. + shard = value.detach().reshape(-1)[start:start + numel].to(dtype=gradient.dtype) + except Exception as exc: + error = exc + # A rank-local callback failure must leave this parameter intact on every owner. Vote before + # writing its shards, so a caller can fix the callback and retry without repeating backward. + error = self._full_gradient_edit_error(error, group) + if error is None and start < param.ds_numel: + self._write_gradient_partition(param_id, gradient, shard) + elif error is not None and ranks == 1 and not get_accelerator().is_synchronized_device(): + # With no distributed vote or write-back, the H2D may still own the pinned input. + get_accelerator().current_stream().synchronize() + return error + + def update_fp32_grad_for_param_vectorized(self, update_func, param_list): + params = [p for p in param_list if p.requires_grad] + if not params: + return + self._wait_for_gradient_edits([self.get_param_id(p) for p in params]) + # A caller may own expert parameters in a different group. Finish each group's collectives + # even if another group failed, and never require ranks outside the parameter's group. + group_errors = {} + for param in params: + group = self._get_param_partition_group(param) + if group not in group_errors: + group_errors[group] = self._full_gradient_edit_error(self._bucketwise_worker_error, group) + if group_errors[group] is None: + group_errors[group] = self._update_full_gradient_partition(param, group, update_func) + self._refresh_edited_gradient_overflow() + for error in group_errors.values(): + if error is not None: + raise error def get_fp32_grad_partitions(self): raise NotImplementedError(_REFLOW_FLAT_GRAD_FREED_MSG.format(api="get_fp32_grad_partitions")) diff --git a/docs/_tutorials/reflow.md b/docs/_tutorials/reflow.md index 4cbf233d0c5a..a628e0cc8e94 100644 --- a/docs/_tutorials/reflow.md +++ b/docs/_tutorials/reflow.md @@ -14,7 +14,9 @@ Adding a `reflow` block to `zero_optimization` turns on three cooperating behavi 2. **Half-precision gradient transfer.** Gradients are copied to CPU in BF16 and promoted to FP32 inside the AVX kernel. This halves the GPU-to-CPU traffic and removes the CPU-side FP32 gradient buffer. 3. **Asynchronous state commit.** The foreground only produces the new BF16 parameters. The FP32 master weights and optimizer state are committed by a background worker after the gradient clipping and overflow checks, overlapping the next forward. -Checkpoint and FP32 parameter/state access APIs wait for that background commit. If a worker fails, `engine.save_checkpoint()` aborts on every rank before writing checkpoint files, and direct state reads report the failure. A full FP32 parameter or optimizer-state read uses an additional collective over the parameter partition group so all participating ranks see a failed commit; the training path adds no collective. Local gradient inspection and modification before `step()` use Reflow’s CPU buffers for the current accumulation window. Reads return FP32 values; writes are stored in the model’s FP16/BF16 gradient dtype and rounded accordingly. Changing a gradient requires Ready to regenerate the affected update. Full gradient helpers remain unsupported because Reflow releases the standard FP32 gradient buffer. +Checkpoint and FP32 parameter/state access APIs wait for that background commit. If a worker fails, `engine.save_checkpoint()` aborts on every rank before writing checkpoint files, and direct state reads report the failure. A full FP32 parameter or optimizer-state read uses an additional collective over the parameter partition group so all participating ranks see a failed commit; the training path adds no collective. Local gradient inspection and modification before `step()` use Reflow’s CPU buffers for the current accumulation window. Reads return FP32 values; writes are stored in the model’s FP16/BF16 gradient dtype and rounded accordingly. Changing a gradient requires Ready to regenerate the affected update. + +After backward and before `engine.step()`, all ranks in a parameter’s partition group can call `safe_update_full_grad_vectorized(params, update_func)` in the same order. The callback receives the full accumulated gradient in FP32, in the parameter’s original shape and at the current loss scale. Each rank writes its slice of the result into the FP16/BF16 gradient buffer used by Ready and Persist. If a callback fails on one rank, its parameter keeps its previous gradient on every owner. Earlier successful edits are retained. Individual full-gradient reads and writes through `safe_get_full_grad` and `safe_set_full_grad` remain unsupported. ## Configuration diff --git a/tests/unit/v1/zero/test_reflow.py b/tests/unit/v1/zero/test_reflow.py index a9594365f807..c01333c6668e 100644 --- a/tests/unit/v1/zero/test_reflow.py +++ b/tests/unit/v1/zero/test_reflow.py @@ -39,7 +39,7 @@ from deepspeed.runtime.zero.muon.muon_optimizer import MuonWithAuxAdam from deepspeed.runtime.zero.utils import ZeRORuntimeException from deepspeed.utils import (safe_get_full_fp32_param, safe_get_full_optimizer_state, safe_get_local_grad, - safe_set_local_grad) + safe_set_local_grad, safe_update_full_grad_vectorized) from deepspeed.utils.numa import parse_range_list from unit.common import DistributedTest from unit.simple_model import SimpleModel @@ -1357,6 +1357,179 @@ def run(reflow): assert torch.equal(want, got) +@needs_gpu_accelerator +class TestReflowFullGradientUpdate(DistributedTest): + world_size = [1, 2] + non_daemonic_procs = True + + @pytest.mark.parametrize("optimizer_kind,precision,clip", [("adam", "bf16", 0.0), ("lion", "fp16", 0.1)]) + def test_edits_drive_ready_persist_and_overflow(self, optimizer_kind, precision, clip): + skip_if_reflow_training_unsupported(optimizer_kind) + dtype = torch.bfloat16 if precision == "bf16" else torch.float16 + torch.manual_seed(8719) + initial_model = SimpleModel(hidden_dim=16, nlayers=2) + batches = make_batches(16, count=8, dtype=dtype) + + def run(reflow): + model = copy.deepcopy(initial_model) + config = get_variant_config(reflow, optimizer_kind) + config["gradient_accumulation_steps"] = 2 + config["gradient_clipping"] = clip + config["zero_optimization"]["reduce_bucket_size"] = 128 + if precision == "fp16": + config["bf16"] = {"enabled": False} + config["fp16"] = {"enabled": True, "loss_scale": 128} + engine, opt, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) + params = list(engine.module.parameters()) + results = [] + try: + for step in range(4): + for micro in range(2): + inputs, labels = batches[2 * step + micro] + loss = engine(inputs, labels) + engine.backward(loss) + if micro == 1: + + def edit(grad, param): + assert grad.shape == param.ds_shape and grad.dtype == torch.float32 + if step in (1, 2) and param is params[0]: + return grad.fill_(float("inf")) + # Reverse across rank boundaries and return values that need rounding. + value = grad.flip((0, )).add_(0.0137) + return value if reflow else value.to(dtype) + + safe_update_full_grad_vectorized(params, edit) + if step == 1: + safe_update_full_grad_vectorized([params[0]], lambda g, p: torch.zeros_like(g)) + results.extend(safe_get_local_grad(p).clone() for p in params) + engine.step() + results.extend([loss.detach(), engine.get_global_grad_norm(), engine.skipped_steps]) + results.extend(int(opt.optimizer.state[p]["step"]) for p in opt.fp32_partitioned_groups_flat) + for param in params: + results.append(safe_get_full_fp32_param(param).clone()) + results.append(safe_get_full_optimizer_state(param, "exp_avg").clone()) + if optimizer_kind == "adam": + results.append(safe_get_full_optimizer_state(param, "exp_avg_sq").clone()) + assert engine.skipped_steps == 1 + return results + finally: + engine.destroy() + + torch.testing.assert_close(run(True), run(False), rtol=0, atol=0) + + def test_padded_and_unused_gradients_between_microsteps(self): + skip_if_reflow_training_unsupported() + + class Model(torch.nn.Module): + + def __init__(self): + super().__init__() + self.weight = torch.nn.Parameter(torch.arange(9, dtype=torch.float32).reshape(3, 3)) + self.bias = torch.nn.Parameter(torch.ones(1)) + + def forward(self, inputs, bias_scale): + loss = (self.weight * inputs).sum() + return loss if bias_scale is None else loss + self.bias.sum() * bias_scale + + def run(reflow): + model = Model() + config = get_variant_config(reflow, "adam") + config["gradient_accumulation_steps"] = 2 + engine, _, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) + params = list(engine.module.parameters()) + try: + inputs = torch.arange(9, device=engine.device, dtype=torch.bfloat16).reshape(3, 3) + for step in range(2): + for micro in range(2): + editing = step == 1 and micro == 0 + # The ZeRO reference obtains the edited gradients directly from its loss. + data = inputs.t() if editing and not reflow else inputs + bias_scale = 4 if step == 0 else (1 if editing and not reflow else None) + engine.backward(engine(data, bias_scale)) + if editing and reflow: + + def edit(grad, param): + if param is engine.module.bias: + assert grad.shape == (1, ) and grad.item() == 0 + return grad.fill_(0.5) + torch.testing.assert_close(grad, inputs.float() / 2, rtol=0, atol=0) + return grad.t().cpu() + + safe_update_full_grad_vectorized(params, edit) + engine.step() + return ([safe_get_full_fp32_param(p).clone() + for p in params], [safe_get_full_optimizer_state(p, "exp_avg").clone() + for p in params], engine.get_global_grad_norm()) + finally: + engine.destroy() + + torch.testing.assert_close(run(True), run(False), rtol=0, atol=0) + + @pytest.mark.world_size(2) + def test_update_on_owning_partition_group(self): + # Only rank zero edits its expert shard. A world collective in the API would hang its peer. + skip_if_reflow_training_unsupported() + rank = dist.get_rank() + singleton_groups = [dist.new_group(ranks=[r]) for r in range(dist.get_world_size())] + torch.manual_seed(8719) + initial_model = SimpleModel(hidden_dim=16, nlayers=2) + inputs, labels = make_batches(16, 1)[0] + + def run(reflow): + model = copy.deepcopy(initial_model) + weight = model.linears[0].weight + weight.ds_zero_partition_process_group = singleton_groups[rank] + config = get_variant_config(reflow, "adam") + config["zero_optimization"]["sub_group_size"] = 1 + engine, _, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) + try: + engine.backward(engine(inputs, labels)) + if rank == 0: + safe_update_full_grad_vectorized([weight], lambda g, p: g.flip((0, ))) + engine.step() + master = safe_get_full_fp32_param(weight).clone() + momentum = safe_get_full_optimizer_state(weight, "exp_avg").clone() + return master, momentum + finally: + engine.destroy() + + torch.testing.assert_close(run(True), run(False), rtol=0, atol=0) + + def test_rank_local_callback_failure_can_retry_without_backward(self): + skip_if_reflow_training_unsupported() + torch.manual_seed(8719) + initial_model = SimpleModel(hidden_dim=16, nlayers=2) + inputs, labels = make_batches(16, 1)[0] + + def run(reflow): + model = copy.deepcopy(initial_model) + config = get_variant_config(reflow, "adam") + config["zero_optimization"]["reduce_bucket_size"] = 128 + engine, _, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) + params = list(engine.module.parameters()) + try: + engine.backward(engine(inputs, labels)) + if reflow: + + def edit(grad, param): + if param is params[1] and dist.get_rank() == 0: + raise ValueError("invalid gradient edit") + return grad.neg_() + + with pytest.raises((ValueError, RuntimeError)): + safe_update_full_grad_vectorized(params, edit) + safe_update_full_grad_vectorized(params[1:], lambda g, p: g.neg_()) + else: + safe_update_full_grad_vectorized(params, lambda g, p: g.neg_()) + engine.step() + return ([safe_get_full_fp32_param(p).clone() + for p in params], [safe_get_full_optimizer_state(p, "exp_avg").clone() for p in params]) + finally: + engine.destroy() + + torch.testing.assert_close(run(True), run(False), rtol=0, atol=0) + + @needs_gpu_accelerator class TestReflowLocalGradientInvalid(DistributedTest): world_size = [1, 2] @@ -2309,7 +2482,8 @@ def run(reflow): assert torch.equal(got, want), f"NVMe parameter or optimizer state differs at step {step}" @pytest.mark.parametrize("optimizer_kind", ["adam", "lion"]) - def test_local_gradient_access_matches_zero(self, tmpdir, optimizer_kind): + @pytest.mark.parametrize("vectorized", [False, True], ids=["local", "full"]) + def test_local_gradient_access_matches_zero(self, tmpdir, optimizer_kind, vectorized): skip_if_reflow_training_unsupported(optimizer_kind) if not deepspeed.ops.__compatible_ops__.get(AsyncIOBuilder.NAME, False): pytest.skip("NVMe offload requires the async_io extension") @@ -2336,7 +2510,10 @@ def run(reflow): inputs = torch.randn(2, width, device=engine.device, dtype=torch.bfloat16) engine.backward(engine(inputs, True)) gradient = safe_get_local_grad(param).clone() - safe_set_local_grad(param, (-0.5 * gradient).to(torch.bfloat16)) + if vectorized: + safe_update_full_grad_vectorized([param], lambda g, p: (-0.5 * g).to(torch.bfloat16)) + else: + safe_set_local_grad(param, (-0.5 * gradient).to(torch.bfloat16)) engine.step() params = [safe_get_full_fp32_param(p).clone() for p in engine.module.parameters()] states = [safe_get_full_optimizer_state(p, "exp_avg").clone() for p in engine.module.parameters()] From e2549fc26ddcbf24dd536f3707486d51dc916166 Mon Sep 17 00:00:00 2001 From: st-bang97 Date: Fri, 20 Nov 2026 20:30:15 +0900 Subject: [PATCH 17/19] Reuse ZeRO-3 helpers and simplify ReFlow Ready work Share the local squared norm, clipping scale, overflow reduction and parameter restore paths with ZeRO-3. Let NVMe swap-out take the low-precision weights produced by Ready. Simplify Ready submissions and native bindings. Reuse the AVX-512 BF16 conversion for cached and streaming stores. Exercise both parameter and optimizer NVMe offload against standard ZeRO-3. Signed-off-by: st-bang97 --- csrc/adam/reflow_cpu_adam_bindings.cpp | 89 +---- csrc/includes/reflow_ready.h | 60 +-- csrc/includes/reflow_simd.h | 85 ++--- csrc/includes/simd.h | 9 +- csrc/lion/reflow_cpu_lion_bindings.cpp | 64 +--- deepspeed/runtime/reflow/ready_batch.py | 36 +- deepspeed/runtime/reflow/reflow_stage3.py | 430 ++++++---------------- deepspeed/runtime/reflow/reflow_utils.py | 18 - deepspeed/runtime/zero/stage3.py | 35 +- tests/unit/v1/zero/test_reflow.py | 26 +- 10 files changed, 238 insertions(+), 614 deletions(-) diff --git a/csrc/adam/reflow_cpu_adam_bindings.cpp b/csrc/adam/reflow_cpu_adam_bindings.cpp index 12484c58ee7e..f6e60fc5b492 100644 --- a/csrc/adam/reflow_cpu_adam_bindings.cpp +++ b/csrc/adam/reflow_cpu_adam_bindings.cpp @@ -12,86 +12,6 @@ static void reflow_adam_memory_fence() #endif } -static inline int reflow_ds_adam_step_params_halfgrad_gilfree(int optimizer_id, - size_t step, - float lr, - float beta1, - float beta2, - float epsilon, - float weight_decay, - bool bias_correction, - torch::Tensor& params_fp32, - torch::Tensor& grads, - torch::Tensor& exp_avg, - torch::Tensor& exp_avg_sq, - torch::Tensor& half_params, - float combined_scale, - bool skip_increment_step = false, - bool maximize = false, - ReflowReadyWork* work = nullptr, - size_t destination_offset = 0) -{ - pybind11::gil_scoped_release release; - return reflow_ds_adam_step_params_halfgrad(optimizer_id, - step, - lr, - beta1, - beta2, - epsilon, - weight_decay, - bias_correction, - params_fp32, - grads, - exp_avg, - exp_avg_sq, - half_params, - combined_scale, - skip_increment_step, - maximize, - work, - destination_offset); -} - -static inline int reflow_ds_adam_state_step_halfgrad_gilfree(int optimizer_id, - size_t step, - float lr, - float beta1, - float beta2, - float epsilon, - float weight_decay, - bool bias_correction, - torch::Tensor& params_fp32, - torch::Tensor& grads, - torch::Tensor& exp_avg, - torch::Tensor& exp_avg_sq, - float combined_scale, - bool skip_increment_step = false, - bool maximize = false) -{ - pybind11::gil_scoped_release release; - return reflow_ds_adam_state_step_halfgrad(optimizer_id, - step, - lr, - beta1, - beta2, - epsilon, - weight_decay, - bias_correction, - params_fp32, - grads, - exp_avg, - exp_avg_sq, - combined_scale, - skip_increment_step, - maximize); -} - -static inline int reflow_ds_bf16_accumulate_gilfree(torch::Tensor& dst, torch::Tensor& src) -{ - pybind11::gil_scoped_release release; - return reflow_ds_bf16_accumulate(dst, src); -} - PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { bind_reflow_ready_work(m); @@ -109,7 +29,8 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) pybind11::arg("num_threads") = -1); m.def("reflow_destroy_adam", &reflow_destroy_adam_optimizer, "Reflow CPU Adam destroy (C++)"); m.def("reflow_adam_update_params_halfgrad", - &reflow_ds_adam_step_params_halfgrad_gilfree, + &reflow_ds_adam_step_params_halfgrad, + pybind11::call_guard(), "Reflow CPU Adam update FP16 with half gradients, GIL-released (C++)", pybind11::arg("optimizer_id"), pybind11::arg("step"), @@ -130,7 +51,8 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) pybind11::arg("ready_work") = nullptr, pybind11::arg("destination_offset") = 0); m.def("reflow_adam_update_state_halfgrad", - &reflow_ds_adam_state_step_halfgrad_gilfree, + &reflow_ds_adam_state_step_halfgrad, + pybind11::call_guard(), "Reflow CPU Adam update state stream with half gradients, GIL-released (C++)", pybind11::arg("optimizer_id"), pybind11::arg("step"), @@ -151,7 +73,8 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) &reflow_adam_memory_fence, "Reflow CPU Adam memory fence (C++)"); m.def("reflow_bf16_accumulate", - &reflow_ds_bf16_accumulate_gilfree, + &reflow_ds_bf16_accumulate, + pybind11::call_guard(), "Reflow CPU BF16/FP16 gradient accumulate using AVX, GIL-released (C++)", pybind11::arg("dst"), pybind11::arg("src")); diff --git a/csrc/includes/reflow_ready.h b/csrc/includes/reflow_ready.h index 5f44fc3b187f..76b95926dd24 100644 --- a/csrc/includes/reflow_ready.h +++ b/csrc/includes/reflow_ready.h @@ -48,11 +48,10 @@ class ReflowReadyWork { TORCH_CHECK(offset <= static_cast(destination_.numel()) && size <= static_cast(destination_.numel()) - offset && destination_.scalar_type() == output.scalar_type()); - TORCH_CHECK(output.device().is_cpu() && output.dim() == 1 && output.is_contiguous()); - inputs.push_back(output); - for (const auto& tensor : inputs) { + TORCH_CHECK(output.dim() == 1); + auto prepare_tensor = [size](const at::Tensor& tensor) { TORCH_CHECK(tensor.device().is_cpu() && tensor.is_contiguous() && - tensor.numel() == output.numel()); + static_cast(tensor.numel()) == size); #if defined(__linux__) // Advise once per range, before splitting it among writers. constexpr uintptr_t page_size = 4096; @@ -60,8 +59,9 @@ class ReflowReadyWork { const auto page = addr & ~(page_size - 1); madvise(reinterpret_cast(page), addr - page + tensor.nbytes(), MADV_HUGEPAGE); #endif - } - inputs.pop_back(); // The output view is owned separately below. + }; + prepare_tensor(output); + for (const auto& input : inputs) prepare_tensor(input); threads_ = threads; for (size_t start = 0; start < size; start += chunk_elems_) chunks_.emplace_back(ranges_.size(), start, std::min(size - start, chunk_elems_)); @@ -110,29 +110,17 @@ class ReflowReadyWork { }; for (auto& chunk : work->chunks_) { if (cancelled_.load(std::memory_order_acquire)) break; - // Preserve the same SIMD and scalar tails as the unsplit Ready kernel. - constexpr size_t block = 128; - const size_t blocks = std::max(1, chunk.size / block); - const size_t writers = std::min(team, blocks); - if (writer >= writers) continue; - const size_t begin = (blocks * writer / writers) * block; - const size_t end = writer + 1 == writers - ? chunk.size - : (blocks * (writer + 1) / writers) * block; const auto& range = work->ranges_[chunk.range]; - range.kernel(chunk.start + begin, end - begin); - // The kernel fences on the issuing thread. The last arrival acquires - // all earlier writers' releases before handing the pinned range to DMA. - if (chunk.finished.fetch_add(1, std::memory_order_acq_rel) + 1 == writers && - !cancelled_.load(std::memory_order_acquire)) { - if (!copy_stream.current_stream()) - copy_stream.reset_stream(work->stream_); - work->destination_.narrow(0, range.offset + chunk.start, chunk.size) - .copy_(range.output.narrow(0, chunk.start, chunk.size), true); - // Prepare one independent successor during the remaining CPU work. - if (&chunk == &work->chunks_.front() && work->chunks_.size() > 1) - std::call_once(work->prefetch_, prepare_next); - } + if (!chunk.write_partition(range.kernel, writer, team) || + cancelled_.load(std::memory_order_acquire)) + continue; + + if (!copy_stream.current_stream()) copy_stream.reset_stream(work->stream_); + work->destination_.narrow(0, range.offset + chunk.start, chunk.size) + .copy_(range.output.narrow(0, chunk.start, chunk.size), true); + // Prepare one independent successor during the remaining CPU work. + if (&chunk == &work->chunks_.front() && work->chunks_.size() > 1) + std::call_once(work->prefetch_, prepare_next); } std::call_once(work->admit_, [&] { // A leading writer can reach the boundary before the first DMA. @@ -168,6 +156,22 @@ class ReflowReadyWork { size_t range, start, size; std::atomic finished{0}; Chunk(size_t range, size_t start, size_t size) : range(range), start(start), size(size) {} + + // Only the last writer may submit this chunk to DMA. + bool write_partition(const Kernel& kernel, size_t writer, size_t team) + { + // Whole SIMD blocks keep the scalar tail identical to the unsplit kernel. + constexpr size_t block = 128; + const size_t blocks = std::max(1, size / block); + const size_t writers = std::min(team, blocks); + if (writer >= writers) return false; + const size_t begin = (blocks * writer / writers) * block; + const size_t end = writer + 1 == writers ? size + : (blocks * (writer + 1) / writers) * block; + kernel(start + begin, end - begin); + // Each kernel fences its own stores. The last arrival acquires all those releases. + return finished.fetch_add(1, std::memory_order_acq_rel) + 1 == writers; + } }; at::Tensor destination_; c10::Stream stream_; diff --git a/csrc/includes/reflow_simd.h b/csrc/includes/reflow_simd.h index 9dc24a6f3cbf..72b16f4428d1 100644 --- a/csrc/includes/reflow_simd.h +++ b/csrc/includes/reflow_simd.h @@ -8,33 +8,6 @@ #if defined(__AVX512__) #define REFLOW_STREAM_PACKED(dst, value) _mm256_stream_si256(dst, value) #define REFLOW_PACK_FP16(value) _mm512_cvtps_ph(value, _MM_FROUND_TO_NEAREST_INT) -// Reflow BF16 aliases (the stock AVX-512 BF16 conversion works as-is). -#define SIMD_LOAD_BF16_REFLOW(x) load_16_bf16_as_f32(x) -#define SIMD_STORE_BF16_REFLOW(x, d) store_16_f32_as_bf16_nearest(d, x) - -static inline __m256i reflow_pack_bf16(__m512 v) -{ - __m512i u32 = readAs<__m512i>(&v); - - __m512i b = _mm512_srli_epi32(u32, 16); - __m512i lsb_mask = _mm512_set1_epi32(0x00000001); - __m512i c = _mm512_and_si512(b, lsb_mask); - __m512i bias_constant = _mm512_set1_epi32(0x00007fff); - __m512i rounding_bias = _mm512_add_epi32(c, bias_constant); - - __m512i d = _mm512_add_epi32(u32, rounding_bias); - __m512i e = _mm512_srli_epi32(d, 16); - __m256i non_nan_res = _mm512_cvtusepi32_epi16(e); - - __m512i mask_out_sign = _mm512_set1_epi32(0x7fffffff); - __m512i non_sign_bits = _mm512_and_si512(u32, mask_out_sign); - __m512i nan_threshold = _mm512_set1_epi32(0x7f800000); - __mmask16 nan_mask = _mm512_cmp_epi32_mask(non_sign_bits, nan_threshold, _MM_CMPINT_GT); - - __m256i nans = _mm256_set1_epi16(0x7fc0); - return _mm256_mask_mov_epi16(non_nan_res, nan_mask, nans); -} - #elif defined(__AVX256__) #define REFLOW_STREAM_PACKED(dst, value) _mm_stream_si128(dst, value) #define REFLOW_PACK_FP16(value) _mm256_cvtps_ph(value, _MM_FROUND_TO_NEAREST_INT) @@ -57,7 +30,7 @@ static inline __m128i reflow_pack_low16_x8(__m256i x) return _mm256_castsi256_si128(p); } -static inline __m128i reflow_pack_bf16(__m256 v) +static inline __m128i pack_f32_as_bf16_nearest(__m256 v) { __m256i u32 = readAs<__m256i>(&v); // round to nearest, ties to even: rounding_bias = ((u32 >> 16) & 1) + 0x7fff @@ -73,9 +46,24 @@ static inline __m128i reflow_pack_bf16(__m256 v) return _mm_blendv_epi8(non_nan_res, _mm_set1_epi16((short)0x7fc0), nan_mask16); } -// Reflow-specific AVX-256 BF16 support (the stock SIMD_*_BF16 above are AVX-512-only). -#define SIMD_LOAD_BF16_REFLOW(x) reflow_load_8_bf16_as_f32(x) -#define SIMD_STORE_BF16_REFLOW(x, d) writeAs(x, reflow_pack_bf16(d)) +// The stock AVX2 helpers support FP16 and FP32. ReFlow also transfers and accumulates BF16. +template +inline void reflow_simd_store(c10::BFloat16* dst, AVX_Data* src) +{ +#pragma unroll + for (size_t i = 0; i < span; ++i) { + writeAs(dst + SIMD_WIDTH * i, pack_f32_as_bf16_nearest(src[i].data)); + } +} + +template +inline void reflow_simd_load(AVX_Data* dst, c10::BFloat16* src) +{ +#pragma unroll + for (size_t i = 0; i < span; ++i) { + dst[i].data = reflow_load_8_bf16_as_f32(src + SIMD_WIDTH * i); + } +} #endif #if defined(__AVX512__) or defined(__AVX256__) @@ -94,7 +82,7 @@ inline void reflow_simd_store_ready(T* dst, AVX_Data* src, bool stream_output) for (size_t i = 0; i < span; ++i) { INTV packed; if constexpr (std::is_same_v) { - packed = reflow_pack_bf16(src[i].data); + packed = pack_f32_as_bf16_nearest(src[i].data); } else { static_assert(std::is_same_v); packed = REFLOW_PACK_FP16(src[i].data); @@ -108,41 +96,14 @@ inline void reflow_simd_store_ready(T* dst, AVX_Data* src, bool stream_output) } } -// Reflow load/store: BF16 uses the Reflow BF16 path (incl. AVX-256); other dtypes delegate -// to the stock simd_load/simd_store so the standard DeepSpeedCPUAdam path is untouched. -template -inline typename std::enable_if_t, void> reflow_simd_store( - T* dst, - AVX_Data* src) -{ - size_t width = SIMD_WIDTH; -#pragma unroll - for (size_t i = 0; i < span; ++i) { - SIMD_STORE_BF16_REFLOW((float*)(dst + width * i), src[i].data); - } -} template -inline typename std::enable_if_t, void> reflow_simd_store( - T* dst, - AVX_Data* src) +inline void reflow_simd_store(T* dst, AVX_Data* src) { simd_store(dst, src); } + template -inline typename std::enable_if_t, void> reflow_simd_load( - AVX_Data* dst, - T* src) -{ - size_t width = SIMD_WIDTH; -#pragma unroll - for (size_t i = 0; i < span; ++i) { - dst[i].data = SIMD_LOAD_BF16_REFLOW((float*)(src + width * i)); - } -} -template -inline typename std::enable_if_t, void> reflow_simd_load( - AVX_Data* dst, - T* src) +inline void reflow_simd_load(AVX_Data* dst, T* src) { simd_load(dst, src); } diff --git a/csrc/includes/simd.h b/csrc/includes/simd.h index 6016bd38c39b..462470b8cf62 100644 --- a/csrc/includes/simd.h +++ b/csrc/includes/simd.h @@ -57,7 +57,7 @@ static __m512 load_16_bf16_as_f32(const void* data) return readAs<__m512>(&c); // use memcpy to avoid aliasing } -static void store_16_f32_as_bf16_nearest(__m512 v, void* data) +static inline __m256i pack_f32_as_bf16_nearest(__m512 v) { __m512i u32 = readAs<__m512i>(&v); @@ -84,9 +84,12 @@ static void store_16_f32_as_bf16_nearest(__m512 v, void* data) // mix in results with nans as needed __m256i nans = _mm256_set1_epi16(0x7fc0); - __m256i res = _mm256_mask_mov_epi16(non_nan_res, nan_mask, nans); + return _mm256_mask_mov_epi16(non_nan_res, nan_mask, nans); +} - writeAs(data, res); +static void store_16_f32_as_bf16_nearest(__m512 v, void* data) +{ + writeAs(data, pack_f32_as_bf16_nearest(v)); } #define SIMD_LOAD_BF16(x) load_16_bf16_as_f32(x) #define SIMD_STORE_BF16(x, d) store_16_f32_as_bf16_nearest(d, x) diff --git a/csrc/lion/reflow_cpu_lion_bindings.cpp b/csrc/lion/reflow_cpu_lion_bindings.cpp index edd9b8a8eeae..b322f01c70c1 100644 --- a/csrc/lion/reflow_cpu_lion_bindings.cpp +++ b/csrc/lion/reflow_cpu_lion_bindings.cpp @@ -12,64 +12,6 @@ static void reflow_lion_memory_fence() #endif } -static inline int reflow_ds_lion_step_params_halfgrad_gilfree(int optimizer_id, - size_t step, - float lr, - float beta1, - float beta2, - float weight_decay, - torch::Tensor& params_fp32, - torch::Tensor& grads, - torch::Tensor& exp_avg, - torch::Tensor& half_params, - float combined_scale, - bool skip_increment_step = false, - ReflowReadyWork* work = nullptr, - size_t destination_offset = 0) -{ - pybind11::gil_scoped_release release; - return reflow_ds_lion_step_params_halfgrad(optimizer_id, - step, - lr, - beta1, - beta2, - weight_decay, - params_fp32, - grads, - exp_avg, - half_params, - combined_scale, - skip_increment_step, - work, - destination_offset); -} - -static inline int reflow_ds_lion_state_step_halfgrad_gilfree(int optimizer_id, - size_t step, - float lr, - float beta1, - float beta2, - float weight_decay, - torch::Tensor& params_fp32, - torch::Tensor& grads, - torch::Tensor& exp_avg, - float combined_scale, - bool skip_increment_step = false) -{ - pybind11::gil_scoped_release release; - return reflow_ds_lion_state_step_halfgrad(optimizer_id, - step, - lr, - beta1, - beta2, - weight_decay, - params_fp32, - grads, - exp_avg, - combined_scale, - skip_increment_step); -} - PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { bind_reflow_ready_work(m); @@ -85,7 +27,8 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) pybind11::arg("num_threads") = -1); m.def("reflow_destroy_lion", &reflow_destroy_lion_optimizer, "Reflow CPU Lion destroy (C++)"); m.def("reflow_lion_update_params_halfgrad", - &reflow_ds_lion_step_params_halfgrad_gilfree, + &reflow_ds_lion_step_params_halfgrad, + pybind11::call_guard(), "Reflow CPU Lion update FP16 with half gradients, GIL-released (C++)", pybind11::arg("optimizer_id"), pybind11::arg("step"), @@ -102,7 +45,8 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) pybind11::arg("ready_work") = nullptr, pybind11::arg("destination_offset") = 0); m.def("reflow_lion_update_state_halfgrad", - &reflow_ds_lion_state_step_halfgrad_gilfree, + &reflow_ds_lion_state_step_halfgrad, + pybind11::call_guard(), "Reflow CPU Lion update state stream with half gradients, GIL-released (C++)", pybind11::arg("optimizer_id"), pybind11::arg("step"), diff --git a/deepspeed/runtime/reflow/ready_batch.py b/deepspeed/runtime/reflow/ready_batch.py index ef69974cb2b6..62efee5e5776 100644 --- a/deepspeed/runtime/reflow/ready_batch.py +++ b/deepspeed/runtime/reflow/ready_batch.py @@ -49,40 +49,36 @@ def discard(self): if self.active is not None: self.active.cancel() - def _take(self, wait): + def _take_eligible(self): + # Native writers can take a successor early only when both of its inputs are ready. with self.lock: if not self.pending: - if wait: - self.closed = True return None item = self.pending[0] - if not wait: - event = item["last_copy_event"] - commit = self.optimizer._pending_state_updates_by_subgroup.get(item["sub_group_id"]) - if commit is not None and not commit.done(): + commit = self.optimizer._pending_state_updates_by_subgroup.get(item["sub_group_id"]) + event = item["last_copy_event"] + if commit is not None and not commit.done(): + return None + if event is not None: + if not event.query(): return None - if event is not None: - if not event.query(): - return None - # This job owns its event reference. A successful query already - # observed the D2H completion required by the CPU kernel. - item["last_copy_event"] = None + item["last_copy_event"] = None # The worker no longer needs to wait for this copy. self.pending.popleft() return self.optimizer._bucketwise_chunk_update_worker(item, defer=True) - def _take_eligible(self): - return self._take(wait=False) - def run(self): stream = self.optimizer._bucketwise_h2d_stream started = False try: while True: - work = self._take(wait=True) + with self.lock: + if not self.pending: + # Close before releasing the lock so no submission can join an empty batch. + self.closed = True + break + item = self.pending.popleft() + work = self.optimizer._bucketwise_chunk_update_worker(item, defer=True) if work is None: - with self.lock: - if self.closed: - break continue with self.lock: if self.closed: diff --git a/deepspeed/runtime/reflow/reflow_stage3.py b/deepspeed/runtime/reflow/reflow_stage3.py index 46ce8017d06b..da83207c64b1 100644 --- a/deepspeed/runtime/reflow/reflow_stage3.py +++ b/deepspeed/runtime/reflow/reflow_stage3.py @@ -7,6 +7,7 @@ import os import threading from concurrent.futures import CancelledError, Future, ThreadPoolExecutor, as_completed +from contextlib import nullcontext from typing import Container, List, NamedTuple import psutil @@ -18,19 +19,17 @@ from deepspeed.runtime.reflow.ready_batch import ReadyBatch from deepspeed.runtime.reflow.reflow_cpu_adam import ReflowCPUAdam from deepspeed.runtime.reflow import reflow_utils -from deepspeed.runtime.swap_tensor.partitioned_param_swapper import PartitionedParamStatus from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum, OffloadStateTypeEnum from deepspeed.runtime.zero.partition_parameters import Parameter, Tensor from deepspeed.runtime.zero.partitioned_param_coordinator import iter_params from deepspeed.runtime.zero.stage3 import DeepSpeedZeroOptimizer_Stage3, INIT_OPTIMIZER_TIMER from deepspeed.runtime.utils import (combine_grad_norm_groups, has_inf_or_nan, is_invalid_grad_norm, - is_model_parallel_parameter, mask_nan_or_inf_with_val_inplace) + mask_nan_or_inf_with_val_inplace) from deepspeed.utils import logger, z3_leaf_module from deepspeed.utils.nvtx import instrument_w_nvtx _REFLOW_FLAT_GRAD_FREED_MSG = ("Reflow frees the flat grad buffer; {api} is not supported under reflow.") _DEFAULT_BUCKETWISE_SHARD_ELEMS = 50000000 -_DEFAULT_BUCKETWISE_MIN_SUBMIT_ELEMS = 262144 # A power of two, so every full slice is a whole number of SIMD blocks and the kernel's scalar tail is the same # elements as in an unsliced call; the sliced commit stays bit-exact. _STATE_COMMIT_SLICE_ELEMS = 1 << 25 @@ -86,6 +85,12 @@ def __init__(self, module, init_optimizer, param_names, timers, ds_config, reflo self._single_grad_buffer = os.getenv("REFLOW_SINGLE_GRAD_BUFFER", "0") == "1" super().__init__(module, init_optimizer, param_names, timers, ds_config, **kwargs) + if self.dtype == torch.float16: + # Accumulate overflow before D2H. ZeRO-3 reduces and clears this flag in has_overflow(). + with get_accelerator().stream(self.reduce_and_partition_stream): + self.inf_or_nan_tracker = torch.zeros(1, + dtype=torch.uint8, + device=get_accelerator().current_device_name()) self._track_checkpointed_parameters() self._warn_per_param_partition_groups() # FP16/BF16 grads go straight to the CPU optimizer, which promotes them to FP32 @@ -339,7 +344,6 @@ def submit(fn, *args, **kwargs): # backward, overlapping the CPU optimizer, instead of waiting for the whole reduce bucket. self._bucketwise_element_shard_size = min(getattr(self, 'reduce_bucket_size', _DEFAULT_BUCKETWISE_SHARD_ELEMS), _DEFAULT_BUCKETWISE_SHARD_ELEMS) - self._bucketwise_min_submit_range_elems = _DEFAULT_BUCKETWISE_MIN_SUBMIT_ELEMS self._bucketwise_enqueue_lock = threading.Lock() self._bucketwise_last_copy_event_by_group = {} # First real (non-cancel) error raised by a bucketwise worker this iteration; step() @@ -427,9 +431,6 @@ def _setup_for_real_optimizer(self): grad_buffers = self.grad_partitions_flat_buffers self.grad_partitions_flat_buffers = {} self.grad_partitions_flat_buffer = None - # GPU-side inf/nan accumulator for the offloaded grads, since the flat buffer that the base - # has_overflow scans is freed above (lazily created on the grad device in partition_grads). - self._reflow_grad_overflow = None # Clear the name-mangled __param_id_to_grad_partition dict so the narrow() views into # the buffer freed above are dropped and its storage can actually be reclaimed. self._DeepSpeedZeroOptimizer_Stage3__param_id_to_grad_partition = {} @@ -504,14 +505,11 @@ def _coalesce_bucketwise_h2d_events(self): barrier.record(stream) return [barrier] - def _get_enqueue_lock(self): - return self._bucketwise_enqueue_lock - def _record_bucketwise_worker_error(self, exc): # Record the first real (non-cancel) bucketwise worker failure under the shared enqueue # lock; step() reads it to abort deterministically. Keep only the first so the original # cause survives later cascading failures. - with self._get_enqueue_lock(): + with self._bucketwise_enqueue_lock: if self._bucketwise_worker_error is None: self._bucketwise_worker_error = exc @@ -541,43 +539,6 @@ def _check_bucketwise_worker_error(self): raise local_error raise RuntimeError("Reflow bucketwise worker failed on another rank; aborting step on all ranks") - # ------------------------------------------------------------------ # - # partitioned param swap-out / CPU fp16 buffer sync - # ------------------------------------------------------------------ # - def _partitioned_params_swap_out(self, i, use_updated_weights=False): - offset = 0 - fp32_param = self.fp32_partitioned_groups_flat[i] - assert fp32_param is not None, f'fp32 parameters of sub_group {i} is None' - # Post-step, the CPU half_params buffer holds the freshly updated FP16/BF16 weights, so swap - # those out directly (a byte copy into the FP16 swap pool, avoiding an FP32->FP16 re-cast). - # At init the buffer is still torch.zeros, so callers there pass use_updated_weights=False to - # swap the pretrained FP32 master instead (cast to FP16 in the pool, like the base optimizer). - half_param_src = None - if use_updated_weights: - try: - if i < len(self._cpu_grad_double_buffers) and self._cpu_grad_double_buffers[i] is not None: - half_param_src = self._cpu_grad_double_buffers[i][self._pending_grad_buffer_idx] - except Exception: - half_param_src = None - - swap_fp16_params = [] - swap_fp32_params = [] - for param, partitioned_param in zip(self.fp16_groups[i], self.fp16_partitioned_groups[i]): - if half_param_src is not None: - src = half_param_src.narrow(0, offset, partitioned_param.ds_numel) - else: - src = fp32_param.narrow(0, offset, partitioned_param.ds_numel) - if partitioned_param.status == PartitionedParamStatus.AVAILABLE: - partitioned_param.data.copy_(src.data) - else: - swap_fp32_params.append(src) - swap_fp16_params.append(param) - offset += partitioned_param.ds_numel - - if len(swap_fp16_params): - swap_fp16_params[0].nvme_swapper.swap_out_partitioned_params(dst_fp16_params=swap_fp16_params, - src_fp32_params=swap_fp32_params) - # ------------------------------------------------------------------ # # optimizer state init (double-buffered CPU grad buffers) # ------------------------------------------------------------------ # @@ -752,13 +713,8 @@ def partition_grads(self, params_to_release: List[Parameter], grad_partitions: L if self._reflow_checkpoint_visits and stream_needs_sync: # Reentrant reductions can reuse their GPU source before the async copy finishes. converted_grad = converted_grad.clone() - # The base flat grad buffer that has_overflow normally scans is freed on this path, so - # accumulate any inf/nan in the offloaded grads on the GPU here (no host sync); the flag - # is folded into has_overflow to drive FP16 dynamic-loss-scaling. if self.dtype == torch.float16: - if self._reflow_grad_overflow is None: - self._reflow_grad_overflow = torch.zeros((), dtype=torch.uint8, device=converted_grad.device) - self._reflow_grad_overflow.logical_or_(has_inf_or_nan(converted_grad)) + self.inf_or_nan_tracker.logical_or_(has_inf_or_nan(converted_grad)) grad_numel = grad_buffer.numel() @@ -901,8 +857,9 @@ def zero_grad(self, set_to_none=True): self.copy_grad_stream.synchronize() for sub_group_id in self._published_ready_groups: self._restore_fp16_params_from_master(sub_group_id) - if self._reflow_grad_overflow is not None: - self._reflow_grad_overflow.zero_() + if self.dtype == torch.float16: + with get_accelerator().stream(self.reduce_and_partition_stream): + self.inf_or_nan_tracker.zero_() checkpoint_visits = self._reflow_checkpoint_visits.copy() worker_error = self._bucketwise_worker_error self.reset_cpu_buffers() @@ -1113,7 +1070,7 @@ def _activate_pending_cpu_grads_if_ready(self, flush_pending): self._bucketwise_drain_enq_executor() if self._pending_grad_ready: if flush_pending: - self._bucketwise_flush_all_pending(force=True, use_pending_buffer=True, combined_scale=self.loss_scale) + self._bucketwise_flush_all_pending(use_pending_buffer=True, combined_scale=self.loss_scale) if not self._single_grad_buffer: self._active_grad_buffer_idx = self._pending_grad_buffer_idx self._pending_grad_ready = False @@ -1180,7 +1137,8 @@ def _can_batch_ready(self, item): return any(size >= chunk_elems for _, size in item["ranges"]) def _bucketwise_chunk_update_worker(self, work_item, defer=False): - # Worker: run the partial Adam update, then async-copy only the updated ranges to GPU. + """Generate low-precision weights for these ranges. Persist owns the master and moment updates.""" + cancel_version = work_item["cancel_version"] direct_cpu_output = False try: sub_group_id = work_item["sub_group_id"] @@ -1188,18 +1146,16 @@ def _bucketwise_chunk_update_worker(self, work_item, defer=False): grad_buffer_index = work_item["grad_buffer_index"] combined_scale = work_item["combined_scale"] last_copy_event = work_item["last_copy_event"] - cancel_version = work_item.get("cancel_version", 0) - increment_step = work_item.get("increment_step", False) - target_step = work_item.get("target_step", None) + target_step = work_item["target_step"] - if cancel_version != getattr(self, "_bucketwise_cancel_version", 0): + if cancel_version != self._bucketwise_cancel_version: return None # Wait for the GPU->CPU grad copy (only the last event, the stream is sequential). if last_copy_event is not None: last_copy_event.synchronize() - if cancel_version != getattr(self, "_bucketwise_cancel_version", 0): + if cancel_version != self._bucketwise_cancel_version: return None # Boundary ranges are enqueued after their accumulation completes; step() drains the rest before reruns. @@ -1207,11 +1163,6 @@ def _bucketwise_chunk_update_worker(self, work_item, defer=False): self._wait_for_pending_state_updates(sub_group_id=sub_group_id) fp32_param = self.fp32_partitioned_groups_flat[sub_group_id] - # The kernel call below uses explicit param/grad/state slices and never reads - # param_groups, so the worker does not touch self.optimizer.param_groups here: - # mutating it would be a dead store that races concurrent bucketwise workers, - # _prepare_state_and_params, and the async _state_worker. - # grad_buffer_index holds the grads (slot 0 in single-buffer mode). half_grad_buffer = self._cpu_grad_double_buffers[sub_group_id][grad_buffer_index] fp16_flat = self.fp16_partitioned_groups_flat[sub_group_id] @@ -1231,17 +1182,9 @@ def _bucketwise_chunk_update_worker(self, work_item, defer=False): state = self.optimizer.state[fp32_param] - lr = work_item.get("lr") - beta1 = work_item.get("beta1") - beta2 = work_item.get("beta2") - eps = work_item.get("eps") - weight_decay = work_item.get("weight_decay") - bias_correction = work_item.get("bias_correction", True) - maximize = work_item.get("maximize", False) - # increment_step controls the per-range skip flag only; the Python state['step'] - # is committed once at the end of step(). - if target_step is None: - target_step = int(state.get('step', 0)) + 1 + lr = work_item["lr"] + beta1, beta2 = work_item["betas"] + weight_decay = work_item["weight_decay"] master = fp32_param.detach().view(-1) grads = half_grad_buffer.view(-1) @@ -1249,31 +1192,31 @@ def _bucketwise_chunk_update_worker(self, work_item, defer=False): variance = None if use_lion else state['exp_avg_sq'].view(-1) output = half_params_buffer.view(-1) + native = self.optimizer.ds_opt_lion if use_lion else self.optimizer.ds_opt_adam work = None if defer: - native = self.optimizer.ds_opt_lion if use_lion else self.optimizer.ds_opt_adam chunk_elems = (self._reflow_config.h2d_chunk_size_mib << 20) // fp16_flat.element_size() work = native.ReadyWork(fp16_flat, self._bucketwise_h2d_stream, chunk_elems) def prepare_range(offset, size, output_slice): - nonlocal increment_step if cancel_version != self._bucketwise_cancel_version: return False param_slice = master.narrow(0, offset, size) grad_slice = grads.narrow(0, offset, size) momentum_slice = momentum.narrow(0, offset, size) deferred = (work, offset) if defer else () + # Ready kernels use the absolute target_step for every range. if use_lion: - self.optimizer.ds_opt_lion.reflow_lion_update_params_halfgrad( - self.optimizer.opt_id, target_step, lr, beta1, beta2, weight_decay, param_slice, grad_slice, - momentum_slice, output_slice, combined_scale, not increment_step, *deferred) + native.reflow_lion_update_params_halfgrad(self.optimizer.opt_id, target_step, lr, beta1, beta2, + weight_decay, param_slice, grad_slice, momentum_slice, + output_slice, combined_scale, False, *deferred) else: - self.optimizer.ds_opt_adam.reflow_adam_update_params_halfgrad( - self.optimizer.opt_id, target_step, lr, beta1, beta2, eps, - weight_decay, bias_correction, param_slice, grad_slice, momentum_slice, - variance.narrow(0, offset, - size), output_slice, combined_scale, not increment_step, maximize, *deferred) - increment_step = False + variance_slice = variance.narrow(0, offset, size) + native.reflow_adam_update_params_halfgrad(self.optimizer.opt_id, target_step, lr, beta1, beta2, + work_item["eps"], weight_decay, + work_item["bias_correction"], param_slice, grad_slice, + momentum_slice, variance_slice, output_slice, + combined_scale, False, work_item["maximize"], *deferred) return cancel_version == self._bucketwise_cancel_version if not defer and fp16_flat is not None and fp16_flat.device.type != "cpu" and not work_item["stage_copy"]: @@ -1301,7 +1244,7 @@ def prepare_range(offset, size, output_slice): # error; if this work item has been cancelled, treat it as a clean no-op like the # explicit cancel returns above. Otherwise this is a real kernel/OOM failure: record it # so step() can abort deterministically on all ranks instead of silently advancing. - if work_item.get("cancel_version", 0) != getattr(self, "_bucketwise_cancel_version", 0): + if cancel_version != self._bucketwise_cancel_version: return None self._record_bucketwise_worker_error(e) logger.warning(f"Reflow bucketwise worker error (rank {dist.get_rank()}): {e}") @@ -1357,14 +1300,7 @@ def _bucketwise_enqueue_range(self, return dest_offset, num_elements = clipped_range - lock = self._get_enqueue_lock() - - with lock: - if sub_group_id >= len(self._bucketwise_pending_ranges_by_group): - while len(self._bucketwise_pending_ranges_by_group) <= sub_group_id: - self._bucketwise_pending_ranges_by_group.append([]) - self._bucketwise_pending_elems_by_group.append(0) - + with self._bucketwise_enqueue_lock: if stage_checkpoint: self._pending_checkpoint_groups.add(sub_group_id) if copy_event is not None: @@ -1376,142 +1312,70 @@ def _bucketwise_enqueue_range(self, if pending_elem_count >= self._bucketwise_element_shard_size: self._bucketwise_flush_group(sub_group_id, - force=True, use_pending_buffer=True, combined_scale=self.loss_scale, already_locked=True) except Exception as e: self._record_bucketwise_worker_error(e) - def _bucketwise_flush_group(self, - sub_group_id, - force=False, - use_pending_buffer=True, - combined_scale=None, - already_locked=False): - # Submit accumulated ranges as a single work item. Returns the future (or None). + def _bucketwise_flush_group(self, sub_group_id, use_pending_buffer, combined_scale, already_locked=False): + """Submit all pending ranges for one subgroup with its optimizer settings at enqueue time.""" if self._bucketwise_update_submit is None: return None - if sub_group_id >= len(self._bucketwise_pending_ranges_by_group): - return None ranges = self._bucketwise_pending_ranges_by_group[sub_group_id] if not ranges: return None - if not force and self._bucketwise_pending_elems_by_group[sub_group_id] < self._bucketwise_element_shard_size: - return None - merged_ranges = reflow_utils.merge_contiguous_ranges(ranges) - - # force=False: submit merged ranges >= min_submit_range_elems, keep the rest pending. - min_submit_range_elems = getattr(self, "_bucketwise_min_submit_range_elems", - _DEFAULT_BUCKETWISE_MIN_SUBMIT_ELEMS) - if not force: - submit_ranges, pending_merged, pending_elems = \ - reflow_utils.split_ranges_by_min_size(merged_ranges, min_submit_range_elems) - self._bucketwise_pending_ranges_by_group[sub_group_id] = pending_merged - self._bucketwise_pending_elems_by_group[sub_group_id] = pending_elems - if not submit_ranges: - return None - else: - submit_ranges = merged_ranges - self._bucketwise_pending_ranges_by_group[sub_group_id].clear() - self._bucketwise_pending_elems_by_group[sub_group_id] = 0 - - # Final clamp/filter so submitted ranges never exceed the valid partition. - valid_partition_element_count = self._bucketwise_get_valid_partition_element_count(sub_group_id) - if valid_partition_element_count <= 0: - return None - submit_ranges = reflow_utils.clip_ranges_to_valid_partition(submit_ranges, valid_partition_element_count) + ranges.clear() + self._bucketwise_pending_elems_by_group[sub_group_id] = 0 + limit = self._bucketwise_get_valid_partition_element_count(sub_group_id) + submit_ranges = reflow_utils.clip_ranges_to_valid_partition(merged_ranges, limit) if not submit_ranges: return None - grad_buffer_index = self._pending_grad_buffer_idx if use_pending_buffer else self._active_grad_buffer_idx - last_copy_event = self._bucketwise_last_copy_event_by_group.pop(sub_group_id, None) - - lock = self._get_enqueue_lock() - - def _prepare_state_and_params(): - param_group_id = self.sub_group_to_group_id[sub_group_id] - group = self.optimizer.param_groups[param_group_id] - # The previous step's async state worker may still be iterating group['params']. - # Keep its list intact while preparing the next bucket update. - p = self.fp32_partitioned_groups_flat[sub_group_id] - if p is None: - return None - - # Reflow fp32 master params live on CPU, so _ensure_param_state (device=cpu) builds - # the same lazy step/exp_avg/exp_avg_sq buffers the inline init did. - state = self.optimizer._ensure_param_state(p) - # Pass a fixed per-iteration target_step to the kernel; commit state['step'] once - # at the end of step() instead of mutating it in the worker. - current_step = int(state.get('step', 0)) - target_step = self._bucketwise_group_target_step.get(sub_group_id, None) - increment_step = target_step is None - if increment_step: - target_step = current_step + 1 - self._bucketwise_group_target_step[sub_group_id] = target_step - - beta1, beta2 = group['betas'] - lr = group['lr'] - # Lion param groups carry no 'eps'/'bias_correction'; the optimizer ignores both. - eps = group.get('eps', 0.0) - weight_decay = group['weight_decay'] - bias_correction = group.get('bias_correction', True) - maximize = group.get('maximize', False) - - return increment_step, target_step, lr, beta1, beta2, eps, weight_decay, bias_correction, maximize - - if already_locked: - result = _prepare_state_and_params() - if result is None: + # A threshold flush already holds the enqueue lock. The step thread takes it here. + lock = nullcontext() if already_locked else self._bucketwise_enqueue_lock + with lock: + target_step = self._ensure_bucketwise_group_step(sub_group_id) + if target_step is None: return None - increment_step, target_step, lr, beta1, beta2, eps, weight_decay, bias_correction, maximize = result - else: - with lock: - result = _prepare_state_and_params() - if result is None: - return None - increment_step, target_step, lr, beta1, beta2, eps, weight_decay, bias_correction, maximize = result - - # A mixed shard can include weights a checkpoint will gather again. A rerun - # after a local edit can also overwrite staged output in this subgroup. - stage_copy = sub_group_id in self._pending_checkpoint_groups or (not use_pending_buffer - and sub_group_id in self._staged_ready_ranges) - if not self._bucketwise_pending_ranges_by_group[sub_group_id]: + group = self.optimizer.param_groups[self.sub_group_to_group_id[sub_group_id]] + beta1, beta2 = group["betas"] + grad_buffer_index = self._pending_grad_buffer_idx if use_pending_buffer else self._active_grad_buffer_idx + # A checkpoint or a replay of an edited gradient can still own unpublished weights. + stage_copy = (sub_group_id in self._pending_checkpoint_groups + or (not use_pending_buffer and sub_group_id in self._staged_ready_ranges)) self._pending_checkpoint_groups.discard(sub_group_id) - if stage_copy: - self._staged_ready_ranges.setdefault(sub_group_id, []) - else: - self._published_ready_groups.add(sub_group_id) - work_item = { - "stage_copy": stage_copy, - "sub_group_id": sub_group_id, - "ranges": submit_ranges, - "grad_buffer_index": grad_buffer_index, - "combined_scale": combined_scale, - "last_copy_event": last_copy_event, - "cancel_version": getattr(self, "_bucketwise_cancel_version", 0), - "increment_step": increment_step, - "target_step": target_step, - "lr": lr, - "beta1": beta1, - "beta2": beta2, - "eps": eps, - "weight_decay": weight_decay, - "bias_correction": bias_correction, - "maximize": maximize, - } + if stage_copy: + self._staged_ready_ranges.setdefault(sub_group_id, []) + else: + self._published_ready_groups.add(sub_group_id) + work_item = { + "stage_copy": stage_copy, + "sub_group_id": sub_group_id, + "ranges": submit_ranges, + "grad_buffer_index": grad_buffer_index, + "combined_scale": combined_scale, + "last_copy_event": last_copy_event, + "cancel_version": self._bucketwise_cancel_version, + "target_step": target_step, + "lr": group["lr"], + "betas": (beta1, beta2), + "weight_decay": group["weight_decay"], + "eps": group.get("eps", 0.0), + "bias_correction": group.get("bias_correction", True), + "maximize": group.get("maximize", False), + } future = self._bucketwise_update_submit(self._bucketwise_chunk_update_worker, work_item) if not self._bucketwise_inflight_futures or self._bucketwise_inflight_futures[-1] is not future: self._bucketwise_inflight_futures.append(future) return future - def _bucketwise_flush_all_pending(self, force=False, use_pending_buffer=True, combined_scale=None): + def _bucketwise_flush_all_pending(self, use_pending_buffer, combined_scale): for sub_group_id in range(len(self._bucketwise_pending_ranges_by_group)): self._bucketwise_flush_group(sub_group_id, - force=force, use_pending_buffer=use_pending_buffer, combined_scale=combined_scale) @@ -1543,15 +1407,17 @@ def _bucketwise_commit_group_steps(self): state['step'] = target_step def _ensure_bucketwise_group_step(self, sub_group_id): - # A rank can own only padding for a subgroup, so no Ready range was - # submitted even though the optimizer must advance its step counter. - if sub_group_id in self._bucketwise_group_target_step: - return + """Reserve one step per subgroup, including ranks with only padding and no Ready ranges.""" + target_step = self._bucketwise_group_target_step.get(sub_group_id) + if target_step is not None: + return target_step param = self.fp32_partitioned_groups_flat[sub_group_id] if param is None: return state = self.optimizer._ensure_param_state(param) - self._bucketwise_group_target_step[sub_group_id] = int(state.get('step', 0)) + 1 + target_step = int(state.get("step", 0)) + 1 + self._bucketwise_group_target_step[sub_group_id] = target_step + return target_step def _bucketwise_wait_inflight_updates(self, discard_queued=False, publish_staged=False): # Wait for submitted bucketwise work (optimizer + H2D submit). H2D completion itself is @@ -1594,7 +1460,6 @@ def _nvme_optimizer_step_subgroups(self, combined_scale, timer_names): self._bucketwise_pending_ranges_by_group[sub_group_id] = sorted(full_ranges, key=lambda x: x[0]) self._bucketwise_pending_elems_by_group[sub_group_id] = sum(sz for _, sz in full_ranges) future = self._bucketwise_flush_group(sub_group_id, - force=True, use_pending_buffer=False, combined_scale=combined_scale) if future is not None: @@ -1648,20 +1513,14 @@ def _bucketwise_run_full_partition_updates(self, combined_scale, param_ids=None) if shard_elems >= self._bucketwise_element_shard_size: self._bucketwise_pending_ranges_by_group[sub_group_id] = shard_ranges self._bucketwise_pending_elems_by_group[sub_group_id] = shard_elems - self._bucketwise_flush_group(sub_group_id, - force=True, - use_pending_buffer=False, - combined_scale=combined_scale) + self._bucketwise_flush_group(sub_group_id, use_pending_buffer=False, combined_scale=combined_scale) shard_ranges = [] shard_elems = 0 if shard_ranges: self._bucketwise_pending_ranges_by_group[sub_group_id] = shard_ranges self._bucketwise_pending_elems_by_group[sub_group_id] = shard_elems - self._bucketwise_flush_group(sub_group_id, - force=True, - use_pending_buffer=False, - combined_scale=combined_scale) + self._bucketwise_flush_group(sub_group_id, use_pending_buffer=False, combined_scale=combined_scale) def backward_prologue(self): # The pending state commit no longer overlaps a forward, so let it use every worker core. @@ -1707,15 +1566,10 @@ def _get_norm_groups(self): self._grad_norm_counts_every_rank(group, process_group) for group, process_group in zip(self.fp16_groups, partition_groups) ] - local_sq = [] - for group, count_every_rank in zip(self.fp16_groups, counts_every_rank): - group_sq = 0.0 - for p in group: - if count_every_rank or is_model_parallel_parameter(p) or (self.model_parallel_rank == 0): - param_id = self.get_param_id(p) - if param_id in self.norm_for_param_grads: - group_sq += self.norm_for_param_grads[param_id]**2 - local_sq.append(group_sq) + local_sq = [ + self._local_grad_norm_squared(group, count_every_rank) + for group, count_every_rank in zip(self.fp16_groups, counts_every_rank) + ] device = get_accelerator().current_device_name() zero = torch.zeros((), device=device) @@ -1787,14 +1641,7 @@ def step(self, closure=None): return global_grad_norm = scaled_global_grad_norm / self.loss_scale - - combined_scale = self.loss_scale - if self.clip_grad > 0.: - # norm is in fact norm*scale, so unscale. - clip = (global_grad_norm + 1e-6) / self.clip_grad - if clip > 1.0: - combined_scale = clip * self.loss_scale - self._current_combined_scale = combined_scale + combined_scale = float(self._combined_grad_scale(scaled_global_grad_norm)) if combined_scale != preview_scale: # Clipping and dynamic scale growth both invalidate old-scale previews. Join @@ -1803,9 +1650,7 @@ def step(self, closure=None): self._bucketwise_run_full_partition_updates(combined_scale=combined_scale) else: if not flushed_before_norm: - self._bucketwise_flush_all_pending(force=True, - use_pending_buffer=False, - combined_scale=self.loss_scale) + self._bucketwise_flush_all_pending(use_pending_buffer=False, combined_scale=self.loss_scale) if ready_after_norm: if self._reflow_modified_gradient_ids: self._bucketwise_wait_inflight_updates() @@ -1855,7 +1700,8 @@ def step(self, closure=None): # not thread-safe. Confined to nvme subgroups (fp16 flat is None); cpu/gpu paths are untouched. for sub_group_id in range(len(self.fp16_groups)): if self.fp16_partitioned_groups_flat[sub_group_id] is None: - self._partitioned_params_swap_out(sub_group_id, use_updated_weights=True) + ready_weights = self._cpu_grad_double_buffers[sub_group_id][self._pending_grad_buffer_idx] + self._partitioned_params_swap_out(sub_group_id, source=ready_weights) self._post_step(timer_names) @@ -1900,58 +1746,7 @@ def _restore_fp16_params_from_master(self, sub_group_id): # pre-step weight. The FP32 master lives on nvme (swapped out), so there is nothing to # copy from here -- the discarded step leaves both the param and the state untouched. return - dst = fp16_flat.data - src = fp32_flat.data - if dst.device.type != "cpu" and self._master_pinned_at_construction(sub_group_id): - self._copy_pinned_master_to_device(dst, src) - else: - dst.copy_(src) - self._unflatten_partitioned_parameters(sub_group_id) - - @instrument_w_nvtx - def has_overflow(self, partition_gradients=True): - if partition_gradients: - with get_accelerator().stream(self.reduce_and_partition_stream): - if self.grad_partitions_flat_buffer is None: - # No flat grad buffer is allocated in bucketwise mode, so there is nothing to - # scan for inf/nan here. - pass - elif hasattr(self.inf_or_nan_tracker, "logical_or_"): - self.inf_or_nan_tracker.logical_or_(torch.isinf(self.grad_partitions_flat_buffer).any()) - self.inf_or_nan_tracker.logical_or_(torch.isnan(self.grad_partitions_flat_buffer).any()) - else: - # logical_or_ not available in older versions of pytorch - self.inf_or_nan_tracker += torch.isinf(self.grad_partitions_flat_buffer).any() - self.inf_or_nan_tracker += torch.isnan(self.grad_partitions_flat_buffer).any() - self.inf_or_nan_tracker = self.inf_or_nan_tracker > 0 - - overflow_gpu = self.inf_or_nan_tracker.clone().to(get_accelerator().current_device_name()).to( - torch.uint8) - self.inf_or_nan_tracker.zero_() - # Fold in the inf/nan seen while offloading grads in partition_grads (this path - # freed the flat buffer the branch above would otherwise scan). - if self._reflow_grad_overflow is not None: - overflow_gpu.logical_or_(self._reflow_grad_overflow.to(overflow_gpu.device)) - self._reflow_grad_overflow.zero_() - - if not get_accelerator().resolves_data_dependency(): - get_accelerator().default_stream().wait_stream(self.reduce_and_partition_stream) - dist.all_reduce(overflow_gpu, op=dist.ReduceOp.MAX, group=self.dp_process_group) - - else: - params = [] - for group in self.fp16_groups: - for param in group: - params.append(param) - - overflow = self.has_overflow_serial(params, is_grad_list=partition_gradients) - overflow_gpu = get_accelerator().ByteTensor([overflow]) - # Since each model parallel GPU carries only part of the model, - # make sure overflow flag is synced across all the model parallel GPUs - self._model_parallel_all_reduce(tensor=overflow_gpu, op=dist.ReduceOp.MAX) - - overflow = overflow_gpu[0].item() - return bool(overflow) + self._reassign_or_swap_out_partitioned_parameters(sub_group_id) # ------------------------------------------------------------------ # # gradient access @@ -1963,35 +1758,38 @@ def get_fp32_grad_for_param(self, param) -> Tensor: def set_fp32_grad_for_param(self, value, param): raise NotImplementedError(_REFLOW_FLAT_GRAD_FREED_MSG.format(api="set_fp32_grad_for_param")) + def _pending_gradient_partition(self, param_id): + subgroup, offset, length = self.grad_position[param_id] + return self._get_cpu_grad_buffer(subgroup, pending=True).narrow(0, offset, length) + def get_local_fp32_grad_for_param(self, param) -> Tensor: if not param.requires_grad: return None param_id = self.get_param_id(param) - sub_group_id, offset, numel = self.grad_position[param_id] + numel = param.partition_numel() device = get_accelerator().current_device_name() - has_partition = param.partition_numel() * self._get_param_partition_rank(param) < param.ds_numel + has_partition = numel * self._get_param_partition_rank(param) < param.ds_numel if param_id not in self._reflow_window_grad_ids or not has_partition: return torch.zeros(numel, dtype=torch.float32, device=device) self._wait_for_accum_gradient(param_id) if self._bucketwise_worker_error is not None: raise self._bucketwise_worker_error self.copy_grad_stream.synchronize() - gradient = self._get_cpu_grad_buffer(sub_group_id, pending=True).narrow(0, offset, numel) - return gradient.to(device=device, dtype=torch.float32) + return self._pending_gradient_partition(param_id).to(device=device, dtype=torch.float32) def set_local_grad_for_param(self, value, param): if not param.requires_grad: return param_id = self.get_param_id(param) - sub_group_id, offset, numel = self.grad_position[param_id] + numel = param.partition_numel() assert value.numel() == numel, f"Number of elements do not match: {value.numel()} != {numel}" - if param.partition_numel() * self._get_param_partition_rank(param) >= param.ds_numel: + if numel * self._get_param_partition_rank(param) >= param.ds_numel: return self._wait_for_gradient_edits([param_id]) if self._bucketwise_worker_error is not None: raise self._bucketwise_worker_error - gradient = self._get_cpu_grad_buffer(sub_group_id, pending=True).narrow(0, offset, numel) + gradient = self._pending_gradient_partition(param_id) rounded = value.detach().reshape(-1).to(dtype=gradient.dtype) self._write_gradient_partition(param_id, gradient, rounded) self._refresh_edited_gradient_overflow() @@ -2022,20 +1820,14 @@ def _write_gradient_partition(self, param_id, gradient, rounded): self.norm_for_param_grads[param_id] = norm def _refresh_edited_gradient_overflow(self): - if self.dtype == torch.float16: - # A replacement can remove an earlier overflow. Scan the window once after all edits. - invalid = False - for active_id in self._reflow_window_grad_ids: - group, start, length = self.grad_position[active_id] - active_gradient = self._get_cpu_grad_buffer(group, pending=True).narrow(0, start, length) - if not torch.isfinite(active_gradient).all(): - invalid = True - break - # partition_grads and has_overflow both access this flag on the reduction stream. - with get_accelerator().stream(self.reduce_and_partition_stream): - if self._reflow_grad_overflow is None: - self._reflow_grad_overflow = get_accelerator().ByteTensor([0]) - self._reflow_grad_overflow.fill_(invalid) + if self.dtype != torch.float16: + return + # A replacement can remove an earlier overflow. Check only gradients in this window. + invalid = any( + has_inf_or_nan(self._pending_gradient_partition(param_id)) for param_id in self._reflow_window_grad_ids) + # partition_grads and has_overflow both access this flag on the reduction stream. + with get_accelerator().stream(self.reduce_and_partition_stream): + self.inf_or_nan_tracker.fill_(invalid) def _full_gradient_edit_error(self, error, group): if dist.get_world_size(group=group) > 1: @@ -2047,8 +1839,8 @@ def _full_gradient_edit_error(self, error, group): def _update_full_gradient_partition(self, param, group, update_func): param_id = self.get_param_id(param) - subgroup, offset, numel = self.grad_position[param_id] - gradient = self._get_cpu_grad_buffer(subgroup, pending=True).narrow(0, offset, numel) + gradient = self._pending_gradient_partition(param_id) + numel = gradient.numel() ranks = dist.get_world_size(group=group) start = self._get_param_partition_rank(param) * numel # Gather the stored halves directly into rank order. Only the callback needs an FP32 tensor. diff --git a/deepspeed/runtime/reflow/reflow_utils.py b/deepspeed/runtime/reflow/reflow_utils.py index 2cfc715d0a95..6f1974c66fc4 100644 --- a/deepspeed/runtime/reflow/reflow_utils.py +++ b/deepspeed/runtime/reflow/reflow_utils.py @@ -474,21 +474,3 @@ def clip_ranges_to_valid_partition(ranges, valid_partition_element_count): if clipped_range is not None: clipped.append(clipped_range) return clipped - - -def split_ranges_by_min_size(merged_ranges, min_range_elems): - """Partition merged ranges into (submit, pending) by a minimum element threshold. - - Ranges whose size is >= min_range_elems are returned in ``submit``; smaller ranges are - returned in ``pending`` and their total element count is returned as ``pending_elems``. - """ - submit = [] - pending = [] - pending_elems = 0 - for off, sz in merged_ranges: - if sz >= min_range_elems: - submit.append((off, sz)) - else: - pending.append((off, sz)) - pending_elems += sz - return submit, pending, pending_elems diff --git a/deepspeed/runtime/zero/stage3.py b/deepspeed/runtime/zero/stage3.py index 8885d04166fe..2bf56ee1177d 100644 --- a/deepspeed/runtime/zero/stage3.py +++ b/deepspeed/runtime/zero/stage3.py @@ -1341,26 +1341,26 @@ def _swappable_optimizer_subgroup(self, sub_group_id): return self.optimizer_swapper.is_swappable_tensor(None, numel=self.fp16_partitioned_groups_flat_numel[sub_group_id]) - def _partitioned_params_swap_out(self, i): - offset = 0 - fp32_param = self.fp32_partitioned_groups_flat[i] - assert fp32_param is not None, \ - f'fp32 parameters of sub_group {i} is None' + def _partitioned_params_swap_out(self, i, source=None): + if source is None: + source = self.fp32_partitioned_groups_flat[i] + assert source is not None, f'fp32 parameters of sub_group {i} is None' + offset = 0 swap_fp16_params = [] - swap_fp32_params = [] + swap_sources = [] for param, partitioned_param in zip(self.fp16_groups[i], self.fp16_partitioned_groups[i]): - src = fp32_param.narrow(0, offset, partitioned_param.ds_numel) + src = source.narrow(0, offset, partitioned_param.ds_numel) if partitioned_param.status == PartitionedParamStatus.AVAILABLE: partitioned_param.data.copy_(src.data) else: - swap_fp32_params.append(src) + swap_sources.append(src) swap_fp16_params.append(param) offset += partitioned_param.ds_numel if len(swap_fp16_params): swap_fp16_params[0].nvme_swapper.swap_out_partitioned_params(dst_fp16_params=swap_fp16_params, - src_fp32_params=swap_fp32_params) + src_fp32_params=swap_sources) def _set_fp16_partitioned_groups_flat(self): # setup flat buffers per subgroup, these are each just sections of the @@ -2159,18 +2159,21 @@ def set_norm_for_param_grad_in_gpu(self, param): #Using a more memory efficient version self.norm_for_param_grads[param_id] = self._constant_buffered_norm2(param.grad) + def _local_grad_norm_squared(self, params, counts_every_rank): + total = 0.0 + for param in params: + if counts_every_rank or is_model_parallel_parameter(param) or self.model_parallel_rank == 0: + param_id = self.get_param_id(param) + if param_id in self.norm_for_param_grads: + total += self.norm_for_param_grads[param_id]**2 + return total + def complete_grad_norm_calculation_for_cpu_offload(self, params): self._assert_same_partition_group(params) process_group = self._get_param_partition_group(params[0]) counts_every_rank = self._grad_norm_counts_every_rank(params, process_group) - total_norm = 0.0 + total_norm = self._local_grad_norm_squared(params, counts_every_rank) norm_type = 2.0 - for p in params: - if counts_every_rank or is_model_parallel_parameter(p) or (self.model_parallel_rank == 0): - param_id = self.get_param_id(p) - if param_id in self.norm_for_param_grads.keys(): - param_norm = self.norm_for_param_grads[param_id] - total_norm += param_norm**2 # Sum across all model parallel GPUs. total_norm_cuda = get_accelerator().FloatTensor([float(total_norm)]) diff --git a/tests/unit/v1/zero/test_reflow.py b/tests/unit/v1/zero/test_reflow.py index c01333c6668e..f231fccd39ca 100644 --- a/tests/unit/v1/zero/test_reflow.py +++ b/tests/unit/v1/zero/test_reflow.py @@ -2440,11 +2440,13 @@ class TestReflowNVMeConditionalGradients(DistributedTest): world_size = 1 @pytest.mark.parametrize("optimizer_kind", ["adam", "lion"]) - def test_matches_zero_offload(self, tmpdir, optimizer_kind): + @pytest.mark.parametrize("nvme_target", ["offload_optimizer", "offload_param"]) + def test_matches_zero_offload(self, tmpdir, optimizer_kind, nvme_target): skip_if_reflow_training_unsupported(optimizer_kind) if not deepspeed.ops.__compatible_ops__.get(AsyncIOBuilder.NAME, False): pytest.skip("NVMe offload requires the async_io extension") - width = 384 + # Parameter I/O requires at least 1 MiB per BF16 weight. Optimizer I/O uses the FP32 subgroup. + width = 768 if nvme_target == "offload_param" else 384 def run(reflow): torch.manual_seed(1234) @@ -2453,16 +2455,25 @@ def run(reflow): config["data_types"] = {"grad_accum_dtype": "bf16"} config["gradient_accumulation_steps"] = 2 config["zero_optimization"]["reduce_bucket_size"] = 1_000_000 - config["zero_optimization"]["offload_optimizer"] = { + config["zero_optimization"][nvme_target] = { "device": "nvme", "nvme_path": str(tmpdir.join("reflow" if reflow else "zero")) } + if nvme_target == "offload_param": + # One large weight per subgroup keeps the pinned swap pools small for both runs. + zero_config = config["zero_optimization"] + zero_config["sub_group_size"] = width * width + zero_config[nvme_target].update(max_in_cpu=0, buffer_size=width * width, buffer_count=2) + zero_config["offload_optimizer"]["pin_memory"] = False engine, optimizer, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) - assert any(optimizer._swappable_optimizer_subgroup(i) for i in range(len(optimizer.fp16_groups))) snapshots = [] try: + if nvme_target == "offload_param": + assert any(p.ds_tensor.final_location == "nvme" for p in engine.module.parameters()) + else: + assert any(optimizer._swappable_optimizer_subgroup(i) for i in range(len(optimizer.fp16_groups))) for step, uses in enumerate(((True, True), (True, False), (False, False), (False, True))): for micro_step, use_optional in enumerate(uses): torch.manual_seed(900 + step * 2 + micro_step) @@ -2471,7 +2482,12 @@ def run(reflow): engine.step() params = [safe_get_full_fp32_param(p).clone() for p in engine.module.parameters()] states = [safe_get_full_optimizer_state(p, "exp_avg").clone() for p in engine.module.parameters()] - snapshots.append((params, states)) + # Reading through the public gather also checks the weights Ready published to the swap file. + weights = [] + for param in engine.module.parameters(): + with deepspeed.zero.GatheredParameters([param]): + weights.append(param.detach().cpu().clone()) + snapshots.append((params, states, weights)) return snapshots finally: engine.destroy() From 1c1016e74545815a3cccb63ec0650113e0045fd6 Mon Sep 17 00:00:00 2001 From: st-bang97 Date: Fri, 20 Nov 2026 20:30:33 +0900 Subject: [PATCH 18/19] Reuse ReFlow gradient storage and bound master restore copies Allocate ReFlow's CPU gradient slots directly and reuse idle reduction bucket storage for accumulation, norms and parameter restoration. Track copies that borrow a bucket and retain their buffers through teardown. Keep the standard ZeRO-3 allocation and copy paths intact. Exercise delayed bucket reuse and pinned master restoration in regression tests. Signed-off-by: st-bang97 --- deepspeed/runtime/reflow/reflow_stage3.py | 216 ++++++++++++++++------ deepspeed/runtime/zero/stage3.py | 31 ++-- tests/unit/v1/zero/test_reflow.py | 210 +++++++++++++++------ tests/unit/v1/zero/test_zero.py | 12 ++ 4 files changed, 340 insertions(+), 129 deletions(-) diff --git a/deepspeed/runtime/reflow/reflow_stage3.py b/deepspeed/runtime/reflow/reflow_stage3.py index da83207c64b1..74e81703d69c 100644 --- a/deepspeed/runtime/reflow/reflow_stage3.py +++ b/deepspeed/runtime/reflow/reflow_stage3.py @@ -3,7 +3,6 @@ # DeepSpeed Team -import gc import os import threading from concurrent.futures import CancelledError, Future, ThreadPoolExecutor, as_completed @@ -23,12 +22,13 @@ from deepspeed.runtime.zero.partition_parameters import Parameter, Tensor from deepspeed.runtime.zero.partitioned_param_coordinator import iter_params from deepspeed.runtime.zero.stage3 import DeepSpeedZeroOptimizer_Stage3, INIT_OPTIMIZER_TIMER +from deepspeed.runtime.zero.utils import get_norm_dtype from deepspeed.runtime.utils import (combine_grad_norm_groups, has_inf_or_nan, is_invalid_grad_norm, mask_nan_or_inf_with_val_inplace) from deepspeed.utils import logger, z3_leaf_module from deepspeed.utils.nvtx import instrument_w_nvtx -_REFLOW_FLAT_GRAD_FREED_MSG = ("Reflow frees the flat grad buffer; {api} is not supported under reflow.") +_REFLOW_FLAT_GRAD_MSG = "Reflow uses its own gradient buffers; {api} is not supported under reflow." _DEFAULT_BUCKETWISE_SHARD_ELEMS = 50000000 # A power of two, so every full slice is a whole number of SIMD blocks and the kernel's scalar tail is the same # elements as in an unsliced call; the sliced commit stays bit-exact. @@ -64,8 +64,7 @@ def __init__(self, module, init_optimizer, param_names, timers, ds_config, reflo "are not supported.") self._reflow_config = reflow_config # These attributes must exist before super().__init__ runs: the parent constructor - # calls _setup_for_real_optimizer / initialize_optimizer_states, which are overridden - # here and read these fields. + # calls initialize_optimizer_states, which sizes the Reflow gradient slots. self._cpu_grad_double_buffers = [] self._active_grad_buffer_idx = 0 self._pending_grad_ready = False @@ -74,6 +73,7 @@ def __init__(self, module, init_optimizer, param_names, timers, ds_config, reflo self._reflow_gradient_partitions = None self._reflow_checkpoint_visits = {} self._reflow_modified_gradient_ids = set() + self._ipg_read_events = {} self._last_state_update_future = None self._pending_state_updates_by_subgroup = {} self._state_commit_overlaps_forward = False @@ -385,30 +385,36 @@ def destroy(self): executor.shutdown(wait=True) except Exception: pass - # A finished or cancelled Ready may still have DMA reading its pinned output. - h2d_stream = getattr(self, "_bucketwise_h2d_stream", None) - if h2d_stream is not None: - h2d_stream.synchronize() - # The base _unpin_offload_buffers does not know Reflow's half-precision grad buffers; under the native - # pinning backend they would otherwise stay page-locked after destroy. Safe now that no worker uses them. - # The native unpin frees the memory, so drop the references too. - for grad_buffers in getattr(self, "_cpu_grad_double_buffers", None) or []: - for grad_buffer in grad_buffers or []: - if grad_buffer is not None and grad_buffer.device.type == 'cpu': - get_accelerator().unpin_memory(grad_buffer) - self._cpu_grad_double_buffers = [] original_forward = getattr(self, "_reflow_original_pre_sub_module_forward", None) if original_forward is not None: self.parameter_offload.pre_sub_module_forward_function = original_forward self._reflow_original_pre_sub_module_forward = None + # ZeRO clears its bucket mapping before its existing device synchronization. Keep the borrowed + # storage alive through that synchronization, including copies unassociated with a worker future. + ipg_buckets = self.ipg_buckets.copy() try: super().destroy() + self._ipg_read_events.clear() + except BaseException: + # Synchronization may have failed after ZeRO cleared the mapping. Retain ownership for a retry. + self.ipg_buckets.update(ipg_buckets) + raise finally: if self._main_thread_affinity is not None: thread_id, cpus = self._main_thread_affinity self._main_thread_affinity = None os.sched_setaffinity(thread_id, cpus) + def _unpin_offload_buffers(self): + # The parent finishes device copies before calling this hook, including D2H for a first micro-step + # with no accumulation worker and H2D from a cancelled Ready. Native unpin frees the underlying memory. + for group in self._cpu_grad_double_buffers: + for buffer in group or (): + if buffer is not None and buffer.device.type == 'cpu': + get_accelerator().unpin_memory(buffer) + self._cpu_grad_double_buffers = [] + super()._unpin_offload_buffers() + # ------------------------------------------------------------------ # # offload / partition setup # ------------------------------------------------------------------ # @@ -422,32 +428,20 @@ def _configure_offloading(self, offload_optimizer_config, offload_param_config): self.main_thread_cores = self._reflow_config.main_thread_cores self.state_update_cores = self._reflow_config.state_update_cores + def _create_fp32_partitions(self): + super()._create_fp32_partitions(create_offloaded_master=self._create_offloaded_master) + + def _create_offloaded_master(self, partition, device): + dtype = self.master_weights_and_grads_dtype + if self.offload_optimizer_pin_memory and device == 'cpu': + master = get_accelerator().pin_empty_like(partition, dtype=dtype) + master.copy_(partition.detach()) + return master + return partition.detach().to(device=device, dtype=dtype, copy=True) + def _setup_for_real_optimizer(self): - # cpu_bucketwise stores gradients exclusively in _cpu_grad_double_buffers, so the - # large flat grad buffer (grad_partitions_flat_buffer) is wasted memory here. The - # parent setup unconditionally allocates it, so free it (and its pinned backing) to - # reclaim ~2 bytes/param of CPU memory in the bucketwise case. - super()._setup_for_real_optimizer() - grad_buffers = self.grad_partitions_flat_buffers - self.grad_partitions_flat_buffers = {} - self.grad_partitions_flat_buffer = None - # Clear the name-mangled __param_id_to_grad_partition dict so the narrow() views into - # the buffer freed above are dropped and its storage can actually be reclaimed. - self._DeepSpeedZeroOptimizer_Stage3__param_id_to_grad_partition = {} - # Native pinning requires an explicit release; remove the parent's references first so - # its destroy path cannot release these allocations a second time. - while grad_buffers: - _, grad_buffer = grad_buffers.popitem() - if self.offload_optimizer_pin_memory: - get_accelerator().unpin_memory(grad_buffer) - del grad_buffer - # When the parent pins these buffers, dropping the references above only returns - # the block to torch's pinned-host caching allocator, which keeps the physical memory resident - # (the one large block is never reused by the smaller per-subgroup bucketwise buffers). Empty - # the host cache so the ~2 bytes/param of pinned memory is actually returned to the OS. - gc.collect() - if hasattr(torch._C, "_host_emptyCache"): - torch._C._host_emptyCache() + # initialize_optimizer_states already creates the CPU slots used for accumulation and Ready output. + super()._setup_for_real_optimizer(allocate_grad_partitions=False) def _pin_current_thread(self, cpu_affinity_mask): if cpu_affinity_mask is None: @@ -651,6 +645,31 @@ def initialize_optimizer_states(self): # ------------------------------------------------------------------ # # gradient partitioning # ------------------------------------------------------------------ # + def _add_grad_to_ipg_bucket(self, param): + # Only a write into this bucket can overwrite a still-pending copy. Oversized gradients bypass it. + if self._ipg_read_events: + dtype = self.get_param_comm_dtype(param) + event = self._ipg_read_events.get(dtype) + if event is not None: + bucket = self.ipg_buckets[dtype] + if bucket.elements + param.grad.numel() <= self._ipg_bucket_capacity(bucket): + self.reduce_and_partition_stream.wait_event(event) + del self._ipg_read_events[dtype] + super()._add_grad_to_ipg_bucket(param) + + @staticmethod + def _unused_ipg_buffer(bucket, dtype): + buffer = bucket.buffer + if buffer is None: + return None + # Keep scratch outside all live gradient views and aligned for vectorized reductions. + start = (bucket.elements * buffer.element_size() + 255) // 256 * 256 + element_size = torch.finfo(dtype).bits // 8 + end = buffer.numel() * buffer.element_size() // element_size * element_size + if start >= end: + return None + return buffer.view(torch.uint8)[start:end].view(dtype) + @instrument_w_nvtx def partition_grads(self, params_to_release: List[Parameter], grad_partitions: List[Tensor]) -> None: buffers = [] @@ -662,6 +681,18 @@ def partition_grads(self, params_to_release: List[Parameter], grad_partitions: L stream_needs_sync = copy_grad_stream != current_stream is_sync_device = get_accelerator().is_synchronized_device() accumulate_submit = getattr(self, "_bucketwise_update_submit", None) + if not params_to_release: + return buffers + comm_dtype = self.get_param_comm_dtype(params_to_release[0]) + bucket = self.ipg_buckets[comm_dtype] + norm_staging = self._unused_ipg_buffer(bucket, get_norm_dtype()) if is_boundary else None + accum_staging = None + ipg_storage = None + if stream_needs_sync and bucket.buffer is not None: + ipg_storage = bucket.buffer.untyped_storage().data_ptr() + wait_for_reduction = stream_needs_sync + checkpoint_grads = bool(self._reflow_checkpoint_visits) + check_source = stream_needs_sync and (ipg_storage is not None or checkpoint_grads) # This output slot is separate from the GPU weights read by checkpoint recomputation. stage_checkpoints = self.clip_grad <= 0. and not self.dynamic_loss_scale and not self.offload_param @@ -710,9 +741,18 @@ def partition_grads(self, params_to_release: List[Parameter], grad_partitions: L converted_grad = grad_partition.to(self.gradient_accumulation_dtype) else: converted_grad = grad_partition - if self._reflow_checkpoint_visits and stream_needs_sync: - # Reentrant reductions can reuse their GPU source before the async copy finishes. - converted_grad = converted_grad.clone() + reads_ipg = False + if check_source and converted_grad is grad_partition: + storage = converted_grad.untyped_storage().data_ptr() + reads_ipg = storage == ipg_storage + if (checkpoint_grads and not reads_ipg and param.grad is not None + and storage == param.grad.untyped_storage().data_ptr()): + # Autograd can reuse an unbucketed checkpoint gradient during recomputation. + converted_grad = converted_grad.clone() + # One handoff covers the reduced bucket. Only a new producer-side cast or clone needs another. + if wait_for_reduction or (stream_needs_sync and converted_grad is not grad_partition): + copy_grad_stream.wait_stream(current_stream) + wait_for_reduction = False if self.dtype == torch.float16: self.inf_or_nan_tracker.logical_or_(has_inf_or_nan(converted_grad)) @@ -730,13 +770,13 @@ def partition_grads(self, params_to_release: List[Parameter], grad_partitions: L pending_buffer = self._get_cpu_grad_buffer(sub_group_id, pending=True) pending_slice = pending_buffer.narrow(0, dest_offset, grad_numel) - if stream_needs_sync: - copy_grad_stream.wait_stream(current_stream) with get_accelerator().stream(copy_grad_stream): pending_slice.copy_(converted_grad.view(pending_slice.shape), non_blocking=True) - if enqueue_ready: + if enqueue_ready or reads_ipg: copy_event = get_accelerator().Event() copy_event.record(copy_grad_stream) + if reads_ipg: + self._ipg_read_events[comm_dtype] = copy_event # No gradient accumulation: this micro-step is also the boundary, so use the GPU # grad tensor directly for the norm/enqueue below. if is_boundary: @@ -746,24 +786,35 @@ def partition_grads(self, params_to_release: List[Parameter], grad_partitions: L if is_boundary: pending_buffer = self._get_cpu_grad_buffer(sub_group_id, pending=True) dst_slice = pending_buffer.narrow(0, dest_offset, grad_numel) - if stream_needs_sync: - copy_grad_stream.wait_stream(current_stream) + if accum_staging is None and norm_staging is not None: + # Norms on the reduction stream reuse the prefix. Give each simultaneous copy-stream + # accumulation its own slice beyond the largest norm, so neither stream waits for reuse. + largest_partition = max(part.numel() for part in grad_partitions) + accum_staging = norm_staging[largest_partition:].view(converted_grad.dtype) + norm_staging = norm_staging[:largest_partition] + use_bucket_staging = accum_staging is not None and grad_numel <= accum_staging.numel() + # The norm only needs the sum. The next bucket write must also wait for its D2H copy. + staging_read_needs_event = use_bucket_staging and stream_needs_sync with get_accelerator().stream(copy_grad_stream): - accum_gpu = dst_slice.to(converted_grad.device, non_blocking=True) + if use_bucket_staging: + accum_gpu = accum_staging[:grad_numel] + accum_staging = accum_staging[grad_numel:] + accum_gpu.copy_(dst_slice, non_blocking=True) + else: + accum_gpu = dst_slice.to(converted_grad.device, non_blocking=True) accum_gpu.add_(converted_grad.view(accum_gpu.shape)) if stream_needs_sync: accum_event = get_accelerator().Event() accum_event.record(copy_grad_stream) dst_slice.copy_(accum_gpu, non_blocking=True) - if enqueue_ready: + if enqueue_ready or staging_read_needs_event: copy_event = get_accelerator().Event() copy_event.record(copy_grad_stream) + if staging_read_needs_event: + self._ipg_read_events[comm_dtype] = copy_event if stream_needs_sync: current_stream.wait_event(accum_event) - # accum_gpu is allocated on copy_grad_stream but read by the grad-norm on - # current_stream below; the wait_event orders that read but does not keep the - # block alive, so record it against current_stream too or the allocator can - # recycle it (into copy_grad_stream's free list) before the norm read runs. + # A temporary allocated on the copy stream must also stay live through the norm read. accum_gpu.record_stream(current_stream) grad_buffer = accum_gpu grad_numel = grad_buffer.numel() @@ -777,12 +828,12 @@ def partition_grads(self, params_to_release: List[Parameter], grad_partitions: L src_slice = active_buffer.narrow(0, dest_offset, grad_numel) pending_buffer = self._get_cpu_grad_buffer(sub_group_id, pending=True) dst_slice = pending_buffer.narrow(0, dest_offset, grad_numel) - if stream_needs_sync: - copy_grad_stream.wait_stream(current_stream) with get_accelerator().stream(copy_grad_stream): src_slice.copy_(converted_grad.view(src_slice.shape), non_blocking=True) copy_event = get_accelerator().Event() copy_event.record(copy_grad_stream) + if reads_ipg: + self._ipg_read_events[comm_dtype] = copy_event if accumulate_submit is not None: # Capture values eagerly via default args (avoid late-binding closure bug). def _accumulate_worker(_copy_event=copy_event, _dst_slice=dst_slice, _src_slice=src_slice): @@ -805,6 +856,11 @@ def _accumulate_worker(_copy_event=copy_event, _dst_slice=dst_slice, _src_slice= if enqueue_ready: self._bucketwise_schedule_enqueue_range(sub_group_id, dest_offset, grad_numel, copy_event, stage_checkpoint) + if norm_staging is not None and grad_numel <= norm_staging.numel(): + # The copy and the norm both run on the bucket's producer stream before its next write. + norm_input = norm_staging[:grad_numel] + norm_input.copy_(grad_buffer.view(-1)) + grad_buffer = norm_input self.norm_for_param_grads[param_id] = self._constant_buffered_norm2(grad_buffer) if not is_sync_device: @@ -1725,6 +1781,44 @@ def step(self, closure=None): # ------------------------------------------------------------------ # # overflow # ------------------------------------------------------------------ # + def _copy_pinned_master_to_device(self, dst, src): + if src.numel() == 0: + return super()._copy_pinned_master_to_device(dst, src) + chunk_elems = min(src.numel(), (self._reflow_config.h2d_chunk_size_mib << 20) // src.element_size()) + for comm_dtype, bucket in self.ipg_buckets.items(): + if bucket.elements: + continue + staging = self._unused_ipg_buffer(bucket, src.dtype) + if staging is None or staging.device != dst.device or staging.numel() < chunk_elems: + continue + # A logically empty bucket can still have a reduction or a D2H read in flight. + stream = get_accelerator().current_stream() + if self.reduce_and_partition_stream is not None and self.reduce_and_partition_stream != stream: + stream.wait_stream(self.reduce_and_partition_stream) + event = self._ipg_read_events.get(comm_dtype) + if event is not None: + stream.wait_event(event) + del self._ipg_read_events[comm_dtype] + break + else: + if src.numel() == chunk_elems: + return super()._copy_pinned_master_to_device(dst, src) + staging = dst.new_empty((chunk_elems, ), dtype=src.dtype) + + copies_done = get_accelerator().Event() + try: + for offset in range(0, src.numel(), chunk_elems): + count = min(chunk_elems, src.numel() - offset) + chunk = staging[:count] + chunk.copy_(src.narrow(0, offset, count), non_blocking=True) + dst.narrow(0, offset, count).copy_(chunk) + copies_done.record() + except BaseException: + # A later chunk may fail after an earlier copy started using the borrowed storage. + get_accelerator().current_stream().synchronize() + raise + copies_done.synchronize() + def _restore_fp16_params_from_master(self, sub_group_id): """Undo a discarded (overflow) step: re-cast the FP32 master weights to FP16/BF16 and scatter them back onto the GPU params, overwriting any FP16 preview the bucketwise workers @@ -1753,10 +1847,10 @@ def _restore_fp16_params_from_master(self, sub_group_id): # ------------------------------------------------------------------ # def get_fp32_grad_for_param(self, param) -> Tensor: - raise NotImplementedError(_REFLOW_FLAT_GRAD_FREED_MSG.format(api="get_fp32_grad_for_param")) + raise NotImplementedError(_REFLOW_FLAT_GRAD_MSG.format(api="get_fp32_grad_for_param")) def set_fp32_grad_for_param(self, value, param): - raise NotImplementedError(_REFLOW_FLAT_GRAD_FREED_MSG.format(api="set_fp32_grad_for_param")) + raise NotImplementedError(_REFLOW_FLAT_GRAD_MSG.format(api="set_fp32_grad_for_param")) def _pending_gradient_partition(self, param_id): subgroup, offset, length = self.grad_position[param_id] @@ -1894,14 +1988,14 @@ def update_fp32_grad_for_param_vectorized(self, update_func, param_list): raise error def get_fp32_grad_partitions(self): - raise NotImplementedError(_REFLOW_FLAT_GRAD_FREED_MSG.format(api="get_fp32_grad_partitions")) + raise NotImplementedError(_REFLOW_FLAT_GRAD_MSG.format(api="get_fp32_grad_partitions")) def offload_states(self, include: Container[OffloadStateTypeEnum] = None, device: OffloadDeviceEnum = OffloadDeviceEnum.cpu, pin_memory: bool = True, non_blocking: bool = False): - raise NotImplementedError(_REFLOW_FLAT_GRAD_FREED_MSG.format(api="offload_states")) + raise NotImplementedError(_REFLOW_FLAT_GRAD_MSG.format(api="offload_states")) def finalize_gradient_accumulation_boundary(self): # Unmanaged gradient accumulation marks the boundary only after backward, but Reflow submits its CPU diff --git a/deepspeed/runtime/zero/stage3.py b/deepspeed/runtime/zero/stage3.py index 2bf56ee1177d..ab6be1895975 100644 --- a/deepspeed/runtime/zero/stage3.py +++ b/deepspeed/runtime/zero/stage3.py @@ -788,7 +788,7 @@ def invalidate_secondary_tensor(self): if param.ds_secondary_tensor is not None: param.ds_secondary_tensor = None - def _setup_for_real_optimizer(self): + def _setup_for_real_optimizer(self, *, allocate_grad_partitions=True): see_memory_usage("Before creating fp32 partitions", force=False) self._create_fp32_partitions() see_memory_usage("After creating fp32 partitions", force=False) @@ -826,8 +826,9 @@ def _setup_for_real_optimizer(self): # One flat gradient buffer per accumulation dtype: parameters kept in fp32 accumulate in fp32. params_by_grad_dtype = collections.defaultdict(list) - for param in all_params: - params_by_grad_dtype[self._grad_accumulation_dtype(param)].append(param) + if allocate_grad_partitions: + for param in all_params: + params_by_grad_dtype[self._grad_accumulation_dtype(param)].append(param) self.grad_partitions_flat_buffers: Dict[torch.dtype, Tensor] = {} for dtype, params in params_by_grad_dtype.items(): flat_buffer = torch.zeros(sum(p.partition_numel() for p in params), dtype=dtype, device=self.device) @@ -1127,7 +1128,7 @@ def _create_momentum_buffer(self, num_elements, i, ds_id): self.optimizer.state[ self.fp32_partitioned_groups_flat[i]]["momentum_buffer"] = unpinned_fp32_buffer_momentum - def _create_fp32_partitions(self): + def _create_fp32_partitions(self, *, create_offloaded_master=None): cpu_memory_usage = 0 cpu_memory_sub_groups = 0 nvme_memory_usage = 0 @@ -1206,13 +1207,16 @@ def _create_fp32_partitions(self): self.fp32_partitioned_groups_flat.append(unpinned_fp32_buffer) self._create_momentum_buffer(num_elements, i, ds_id) elif self.offload_optimizer: - converted = self.fp16_partitioned_groups_flat[i].to(self.subgroup_to_device[i], - dtype=self.master_weights_and_grads_dtype) - master = converted.clone().detach() - if self.offload_optimizer_pin_memory and master.device.type == "cpu": - # As ZeRO-1/2 does: the master is copied to the device after every step, which is fast only - # from pinned memory (_copy_pinned_master_to_device). - master = get_accelerator().pin_memory(master) + if create_offloaded_master is None: + converted = self.fp16_partitioned_groups_flat[i].to(self.subgroup_to_device[i], + dtype=self.master_weights_and_grads_dtype) + master = converted.clone().detach() + if self.offload_optimizer_pin_memory and master.device.type == "cpu": + # As ZeRO-1/2 does: the master is copied to the device after every step, which is fast only + # from pinned memory (_copy_pinned_master_to_device). + master = get_accelerator().pin_memory(master) + else: + master = create_offloaded_master(tensor, self.subgroup_to_device[i]) self.fp32_partitioned_groups_flat.append(master) self._create_momentum_buffer(num_elements, i, ds_id) elif self.fp16_partitioned_groups_flat[i].dtype == self.master_weights_and_grads_dtype and \ @@ -1765,7 +1769,7 @@ def reduce_independent_p_g_buckets_and_remove_grads(self, param): # deal with a use-case of transient grads that will be generated in a loop for the same computation involving some model params - e.g. when performing a tiled memory calculation that shards the normal single sub-module call into a loop over a shards. if getattr(param, "ds_grad_is_ready", True): self._apply_autoep_folding_tp_correction(param) - self.__add_grad_to_ipg_bucket(param) + self._add_grad_to_ipg_bucket(param) def configure_autoep_folding_tp_gradient_reduction(self, folding_spec): if folding_spec is None or folding_spec.tp_size <= 1: @@ -1825,6 +1829,9 @@ def __add_grad_to_ipg_bucket(self, param: Parameter) -> None: bucket.process_group = self._get_param_partition_group(param) bucket.elements += param.grad.numel() + # Subclasses can guard writes here. The standard writer keeps its original NVTX range. + _add_grad_to_ipg_bucket = __add_grad_to_ipg_bucket + @instrument_w_nvtx @torch.no_grad() def __reduce_and_partition_ipg_grads(self, communication_data_type: torch.dtype) -> None: diff --git a/tests/unit/v1/zero/test_reflow.py b/tests/unit/v1/zero/test_reflow.py index f231fccd39ca..8bf216cbb44d 100644 --- a/tests/unit/v1/zero/test_reflow.py +++ b/tests/unit/v1/zero/test_reflow.py @@ -10,7 +10,6 @@ import copy import os import threading -import weakref from concurrent.futures import Future, ThreadPoolExecutor from contextlib import ExitStack from unittest.mock import Mock, patch @@ -35,7 +34,6 @@ from deepspeed.runtime.reflow.reflow_stage3 import ReflowOptimizer_Stage3 from deepspeed.runtime.reflow import reflow_utils from deepspeed.runtime.utils import combine_grad_norm_groups -from deepspeed.runtime.zero.stage3 import DeepSpeedZeroOptimizer_Stage3 from deepspeed.runtime.zero.muon.muon_optimizer import MuonWithAuxAdam from deepspeed.runtime.zero.utils import ZeRORuntimeException from deepspeed.utils import (safe_get_full_fp32_param, safe_get_full_optimizer_state, safe_get_local_grad, @@ -1579,33 +1577,6 @@ def run(reflow): assert torch.equal(want, got) -def test_reflow_releases_every_parent_gradient_dtype(): - optimizer = object.__new__(ReflowOptimizer_Stage3) - optimizer.offload_optimizer_pin_memory = True - references = [] - released = [] - - def create_parent_buffers(parent): - buffers = {dtype: torch.zeros(4, dtype=dtype) for dtype in (torch.float16, torch.float32)} - references.extend(weakref.ref(buffer) for buffer in buffers.values()) - parent.grad_partitions_flat_buffers = buffers - parent.grad_partitions_flat_buffer = buffers[torch.float16] - parent._DeepSpeedZeroOptimizer_Stage3__param_id_to_grad_partition = { - i: buffer.narrow(0, 0, 2) - for i, buffer in enumerate(buffers.values()) - } - - accelerator = SimpleNamespace(unpin_memory=lambda buffer: released.append(id(buffer))) - with patch.object(DeepSpeedZeroOptimizer_Stage3, "_setup_for_real_optimizer", create_parent_buffers), \ - patch("deepspeed.runtime.reflow.reflow_stage3.get_accelerator", return_value=accelerator): - optimizer._setup_for_real_optimizer() - assert len(released) == len(set(released)) == 2 - assert all(reference() is None for reference in references) - assert not optimizer.grad_partitions_flat_buffers - assert optimizer.grad_partitions_flat_buffer is None - assert not optimizer._DeepSpeedZeroOptimizer_Stage3__param_id_to_grad_partition - - @pytest.mark.parametrize("nvme_parameter", [False, True]) def test_reflow_overflow_keeps_nvme_restore_paths(nvme_parameter): # NVMe parameters must be re-swapped from the unchanged master; swapped optimizer @@ -1625,45 +1596,112 @@ def test_reflow_overflow_keeps_nvme_restore_paths(nvme_parameter): optimizer._unflatten_partitioned_parameters.assert_not_called() +def delay_reflow_gradient_copies(engine, cycles=200_000_000): + copy_tensor = torch.Tensor.copy_ + + def delayed_offload_copy(dst, src, *args, **kwargs): + if (dst.device.type == "cpu" and isinstance(src, torch.Tensor) and src.device == engine.device + and get_accelerator().current_stream() == engine.optimizer.copy_grad_stream): + # Delay the actual DMA, including a boundary copy submitted after the GPU accumulation event. + torch.cuda._sleep(cycles) #ignore-cuda + return copy_tensor(dst, src, *args, **kwargs) + + return patch.object(torch.Tensor, "copy_", delayed_offload_copy) + + @needs_gpu_accelerator -class TestReflowReleasesParentGradientBuffers(DistributedTest): +class TestReflowGradientStorage(DistributedTest): world_size = 1 @pytest.mark.parametrize("pin_memory", [False, True]) - def test_releases_all_parent_gradient_buffers(self, pin_memory): + def test_no_discarded_model_sized_gradient(self, pin_memory): skip_if_reflow_training_unsupported() - original_setup = DeepSpeedZeroOptimizer_Stage3._setup_for_real_optimizer - accelerator = get_accelerator() - original_unpin = accelerator.unpin_memory - parent_buffers = [] - unpinned = [] + model = SimpleModel(hidden_dim=16, nlayers=2) + numel = sum(param.numel() for param in model.parameters()) + config = get_variant_config(reflow=True, variant="adam") + config["zero_optimization"]["offload_optimizer"]["pin_memory"] = pin_memory + config["zero_optimization"]["sub_group_size"] = 128 - def capture_parent_buffers(optimizer): - original_setup(optimizer) - parent_buffers.extend(weakref.ref(buffer) for buffer in optimizer.grad_partitions_flat_buffers.values()) + # The parent's per-dtype zero allocation used to live only until the subclass returned from setup. + # A whole-model allocation is fine if the optimizer actually uses that storage for its gradient slots. + flat_allocations = set() + zeros = torch.zeros - def record_unpin(buffer): - if any(reference() is buffer for reference in parent_buffers): - unpinned.append(id(buffer)) - return original_unpin(buffer) + def track_zeros(*args, **kwargs): + tensor = zeros(*args, **kwargs) + if tensor.device.type == "cpu" and tensor.dtype == torch.bfloat16 and tensor.numel() == numel: + flat_allocations.add(tensor.untyped_storage().data_ptr()) + return tensor - config = get_variant_config(reflow=True, variant="adam") - config["zero_optimization"]["offload_optimizer"]["pin_memory"] = pin_memory - model = SimpleModel(hidden_dim=16, nlayers=2) - with patch.object(DeepSpeedZeroOptimizer_Stage3, "_setup_for_real_optimizer", capture_parent_buffers), \ - patch.object(accelerator, "unpin_memory", record_unpin): + with patch.object(torch, "zeros", track_zeros): engine, optimizer, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) - try: - assert parent_buffers - assert all(reference() is None for reference in parent_buffers) - assert not optimizer.grad_partitions_flat_buffers - assert optimizer.grad_partitions_flat_buffer is None - finally: + try: + slots = [t for group in optimizer._cpu_grad_double_buffers for t in group] + assert all(get_accelerator().is_pinned(t) == pin_memory for t in slots) + assert flat_allocations.issubset({t.untyped_storage().data_ptr() for t in slots}) + finally: + engine.destroy() + + def test_destroy_finishes_gradient_copy_before_unpinning(self): + skip_if_reflow_training_unsupported() + accelerator = get_accelerator() + if accelerator.device_name() != "cuda": + pytest.skip("Requires a CUDA copy stream for the delayed DMA") + model = torch.nn.Linear(32, 1, bias=False) + config = get_variant_config(True, "adam") + config["gradient_accumulation_steps"] = 2 + config["zero_optimization"]["reduce_bucket_size"] = 32 + engine, optimizer, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) + copies_done = accelerator.Event() + slots = {buf.data_ptr() for group in optimizer._cpu_grad_double_buffers for buf in group} + unpin = accelerator.unpin_memory + completed_at_release = [] + + def check_release(buffer): + if buffer.data_ptr() in slots: + completed_at_release.append(copies_done.query()) + # Keep the native allocator safe even when testing a regressed release order. + copies_done.synchronize() + return unpin(buffer) + + try: + loss = engine(torch.ones((1, 32), device=engine.device, dtype=torch.bfloat16)).float().sum() + with delay_reflow_gradient_copies(engine, cycles=600_000_000): + engine.backward(loss) + finally: + copies_done.record(optimizer.copy_grad_stream) + with patch.object(accelerator, "unpin_memory", check_release): engine.destroy() - assert len(unpinned) == (len(parent_buffers) if pin_memory else 0) - assert len(set(unpinned)) == len(unpinned) + assert completed_at_release and all(completed_at_release) + + @pytest.mark.parametrize("contiguous_gradients", [True, False]) + def test_pinned_restore_bounds_device_scratch(self, contiguous_gradients): + skip_if_reflow_training_unsupported() + torch.manual_seed(8719) + model = torch.nn.Linear(1025, 1024, bias=False) + config = get_variant_config(True, "adam") + config["zero_optimization"].update(contiguous_gradients=contiguous_gradients, reduce_bucket_size=(1 << 20) + 1) + config["zero_optimization"]["reflow"]["h2d_chunk_size_mib"] = 1 + engine, optimizer, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) + try: + master = optimizer.fp32_partitioned_groups_flat[0].detach() + dst = optimizer.fp16_partitioned_groups_flat[0] + expected = master.to(dst.device).to(dst.dtype) + dst.zero_() + accelerator = get_accelerator() + accelerator.synchronize() + accelerator.reset_peak_memory_stats() + baseline = accelerator.memory_allocated() + # Isolate the restore from the rest of a skipped step. A subgroup is larger than the + # configured transfer size and its final chunk is short. + optimizer._restore_fp16_params_from_master(0) + peak = accelerator.max_memory_allocated() - baseline + assert torch.equal(dst, expected) + assert peak <= (0 if contiguous_gradients else 1 << 20) + finally: + engine.destroy() @needs_gpu_accelerator @@ -2043,6 +2081,66 @@ class TestReflowAccumulationBufferReuseDistributed(TestReflowAccumulationBufferR world_size = 2 +@needs_gpu_accelerator +class TestReflowReductionBucketReuse(DistributedTest): + world_size = [1, 2] + + @pytest.mark.parametrize("precision, reduce_scatter, accumulation_steps, mixed_sizes", [("bf16", True, 1, False), + ("fp16", True, 4, False), + ("bf16", False, 1, False), + ("bf16", True, 4, True)]) + def test_slow_gradient_copy_keeps_its_source(self, precision, reduce_scatter, accumulation_steps, mixed_sizes): + skip_if_reflow_training_unsupported() + if get_accelerator().device_name() != "cuda": + pytest.skip("Requires a CUDA copy stream for the delayed DMA") + width = 32768 + # Backward reduces the two small weights before the large one rewrites the bucket, including its tail. + widths = [8 * width, width, width] if mixed_sizes else [width] * 4 + + class WeightedSum(torch.nn.ModuleList): + + def forward(self, inputs): + return sum(layer(inputs[:, :layer.in_features]).float().sum() * 2**i for i, layer in enumerate(self)) + + torch.manual_seed(8719) + model = WeightedSum([torch.nn.Linear(n, 1, bias=False) for n in widths]) + config = get_variant_config(True, "adam") + config["gradient_accumulation_steps"] = accumulation_steps + config["optimizer"]["params"]["betas"] = [0.5, 0.75] + config["zero_optimization"].update(contiguous_gradients=True, + reduce_scatter=reduce_scatter, + overlap_comm=True, + reduce_bucket_size=8 * width if mixed_sizes else width) + config["zero_optimization"]["offload_optimizer"]["pin_memory"] = True + if precision == "fp16": + config.pop("bf16") + config["fp16"] = {"enabled": True, "loss_scale": 1} + dtype = torch.float16 if precision == "fp16" else torch.bfloat16 + engine, _, _, _ = deepspeed.initialize(model=model, model_parameters=model.parameters(), config=config) + try: + inputs = torch.ones((1, max(widths)), dtype=dtype, device=engine.device) + for step in range(2): + for micro_step in range(accumulation_steps): + loss = engine(inputs) + if step == 1 and micro_step in (0, accumulation_steps - 1): + with delay_reflow_gradient_copies(engine): + engine.backward(loss) + else: + engine.backward(loss) + if step == 1 and micro_step == accumulation_steps - 1: + for i, param in enumerate(model.parameters()): + grad = safe_get_local_grad(param) + assert torch.equal(grad, torch.full_like(grad, 2**i)) + engine.step() + expected_norm = sum(n * 4**i for i, n in enumerate(widths))**0.5 + assert float(engine.get_global_grad_norm()) == pytest.approx(expected_norm, rel=1e-7) + for i, param in enumerate(model.parameters()): + moment = safe_get_full_optimizer_state(param, "exp_avg") + assert torch.equal(moment, torch.full_like(moment, 0.75 * 2**i)) + finally: + engine.destroy() + + class ConditionalGradientModel(torch.nn.Module): def __init__(self, width=16): diff --git a/tests/unit/v1/zero/test_zero.py b/tests/unit/v1/zero/test_zero.py index 155fc4e84724..3a5da905b3e9 100644 --- a/tests/unit/v1/zero/test_zero.py +++ b/tests/unit/v1/zero/test_zero.py @@ -1923,6 +1923,18 @@ def test(self, force_ds_optim): model, _, _, _ = deepspeed.initialize(model=model, optimizer=optimizer, config=config_dict) +def test_zero3_failed_master_copy_preserves_original_error(monkeypatch): + from deepspeed.runtime.zero.stage3 import DeepSpeedZeroOptimizer_Stage3 + + # Under memory pressure, creating a completion event can itself fail and hide the original copy error. + def unavailable_event(self): + raise MemoryError("cannot allocate completion event") + + monkeypatch.setattr(type(get_accelerator()), "Event", unavailable_event) + with pytest.raises(RuntimeError): + DeepSpeedZeroOptimizer_Stage3._copy_pinned_master_to_device(None, torch.empty(2), torch.ones(3)) + + @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): From ef7da9c3253a1d760fe88743020aa1f1a4f70bed Mon Sep 17 00:00:00 2001 From: st-bang97 Date: Sun, 22 Nov 2026 16:16:37 +0900 Subject: [PATCH 19/19] Register ReFlow CPU builders with the CUDA accelerator Use the shared CPU builder list for Adam and Lion, remove their top-level re-exports, and test lookup through the accelerator. Link the ASPLOS 2027 ReFlow paper in the project and runtime READMEs. Signed-off-by: st-bang97 --- README.md | 1 + README.zh.md | 1 + accelerator/cuda_accelerator.py | 9 ++++++++- deepspeed/runtime/reflow/README.md | 2 ++ op_builder/reflow_cpu_adam.py | 4 ---- op_builder/reflow_cpu_lion.py | 4 ---- tests/unit/v1/ops/test_reflow_cpu_optimizers.py | 5 ++++- 7 files changed, 16 insertions(+), 10 deletions(-) delete mode 100644 op_builder/reflow_cpu_adam.py delete mode 100644 op_builder/reflow_cpu_lion.py diff --git a/README.md b/README.md index ff8ffc391c8e..19b4a47ad5e2 100755 --- a/README.md +++ b/README.md @@ -261,6 +261,7 @@ Conduct](https://opensource.microsoft.com/codeofconduct/). For more information 35. Tingfeng Lan, Yusen Wu, Bin Ma, Zhaoyuan Su, Rui Yang, Tekin Bicer, Masahiro Tanaka, Olatunji Ruwase, Dong Li, Yue Cheng. (2025) ZenFlow: Enabling Stall-Free Offloading Training via Asynchronous Updates [arXiv:2505.12242](https://arxiv.org/abs/2505.12242) 36. Kayhan Behdin, Ata Fatahibaarzi, Qingquan Song, Yun Dai, Aman Gupta, Zhipeng Wang, Hejian Sang, Shao Tang, Gregory Dexter, Sirou Zhu, Siyu Zhu, Tejas Dharamsi, Vignesh Kothapalli, Zhoutong Fu, Yihan Cao, Pin-Lun Hsu, Fedor Borisyuk, Natesh S. Pillai, Luke Simon, Rahul Mazumder.(2025) Scaling Down, Serving Fast: Compressing and Deploying Efficient LLMs for Recommendation Systems [EMNLP 2025](https://aclanthology.org/2025.emnlp-industry.119/) 37. Xinyu Lian, Masahiro Tanaka, Olatunji Ruwase, Minjia Zhang. (2026) SuperOffload: Unleashing the Power of Large-Scale LLM Training on Superchips [arxiv](https://arxiv.org/abs/2509.21271), [ASPLOS 2026](https://www.asplos-conference.org/asplos2026) +38. Seongtae Bang, Gyeongseo Park, Ki-Dong Kang, Hyunkyun Shin, Sungju Kim, Daehoon Kim. (2027) ReFlow: Exposing Parallelism in CPU-Offloaded LLM Training via Register-Resident SIMD Fusion and Decoupled Update Scheduling [ACM](https://dl.acm.org/doi/10.1145/3845814.3850051), [ASPLOS 2027](https://www.asplos-conference.org/asplos2027/) # Videos 1. DeepSpeed KDD 2020 Tutorial diff --git a/README.zh.md b/README.zh.md index 3ab03e7708ab..224b4c40deb5 100644 --- a/README.zh.md +++ b/README.zh.md @@ -243,6 +243,7 @@ DCO 针对每次 Git Commit 生效,因此每个提交都需要附加签署声 35. Tingfeng Lan, Yusen Wu, Bin Ma, Zhaoyuan Su, Rui Yang, Tekin Bicer, Masahiro Tanaka, Olatunji Ruwase, Dong Li, Yue Cheng. (2025) ZenFlow: Enabling Stall-Free Offloading Training via Asynchronous Updates [arXiv:2505.12242](https://arxiv.org/abs/2505.12242) 36. Kayhan Behdin, Ata Fatahibaarzi, Qingquan Song, Yun Dai, Aman Gupta, Zhipeng Wang, Hejian Sang, Shao Tang, Gregory Dexter, Sirou Zhu, Siyu Zhu, Tejas Dharamsi, Vignesh Kothapalli, Zhoutong Fu, Yihan Cao, Pin-Lun Hsu, Fedor Borisyuk, Natesh S. Pillai, Luke Simon, Rahul Mazumder.(2025) Scaling Down, Serving Fast: Compressing and Deploying Efficient LLMs for Recommendation Systems [EMNLP 2025](https://aclanthology.org/2025.emnlp-industry.119/) 37. Xinyu Lian, Masahiro Tanaka, Olatunji Ruwase, Minjia Zhang. (2026) SuperOffload: Unleashing the Power of Large-Scale LLM Training on Superchips [arxiv](https://arxiv.org/abs/2509.21271), [ASPLOS 2026](https://www.asplos-conference.org/asplos2026) +38. Seongtae Bang, Gyeongseo Park, Ki-Dong Kang, Hyunkyun Shin, Sungju Kim, Daehoon Kim. (2027) ReFlow: Exposing Parallelism in CPU-Offloaded LLM Training via Register-Resident SIMD Fusion and Decoupled Update Scheduling [ACM](https://dl.acm.org/doi/10.1145/3845814.3850051), [ASPLOS 2027](https://www.asplos-conference.org/asplos2027/) # 视频讲座与教程 1. DeepSpeed KDD 2020 专题教程 diff --git a/accelerator/cuda_accelerator.py b/accelerator/cuda_accelerator.py index 482e64fb30e9..7a3174847e98 100644 --- a/accelerator/cuda_accelerator.py +++ b/accelerator/cuda_accelerator.py @@ -389,7 +389,14 @@ def _lazy_init_class_dict(self): # Host-side ops (the CPU optimizers, and async I/O, which stages device tensors through # host memory) need no CUDA to build, so they share their builders with the CPU accelerator. cpu_op_builder_module = importlib.import_module("{}.cpu".format(op_builder_dir)) - for member_name in ["CPUAdamBuilder", "CPUAdagradBuilder", "CPULionBuilder", "AsyncIOBuilder"]: + for member_name in [ + "CPUAdamBuilder", + "CPUAdagradBuilder", + "CPULionBuilder", + "ReflowCPUAdamBuilder", + "ReflowCPULionBuilder", + "AsyncIOBuilder", + ]: self.class_dict[member_name] = getattr(cpu_op_builder_module, member_name) # end initialize for create_op_builder() diff --git a/deepspeed/runtime/reflow/README.md b/deepspeed/runtime/reflow/README.md index 31889fb47eb0..e23c891d2be4 100644 --- a/deepspeed/runtime/reflow/README.md +++ b/deepspeed/runtime/reflow/README.md @@ -7,6 +7,8 @@ optimizer as a separate serial phase *after* backward, it hides almost all of th backward pass. The result is ZeRO-3 CPU offloading where the CPU optimizer is largely overlapped with GPU compute and the inter-GPU gradient reduction. +For the design and evaluation, see the [ASPLOS 2027 paper](https://dl.acm.org/doi/10.1145/3845814.3850051). + **Optimizer support:** Adam/AdamW (`ReflowCPUAdam`) and Lion (`ReflowCPULion`). Lion keeps a single momentum tensor (`exp_avg`) — no second moment, no `eps`, no bias correction — so its offloaded state is half of Adam's; everything else in the pipeline below is identical. diff --git a/op_builder/reflow_cpu_adam.py b/op_builder/reflow_cpu_adam.py deleted file mode 100644 index 4f93e888f765..000000000000 --- a/op_builder/reflow_cpu_adam.py +++ /dev/null @@ -1,4 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# DeepSpeed Team - -from .cpu.reflow_cpu_adam import ReflowCPUAdamBuilder # noqa: F401 diff --git a/op_builder/reflow_cpu_lion.py b/op_builder/reflow_cpu_lion.py deleted file mode 100644 index 72a12fe148cb..000000000000 --- a/op_builder/reflow_cpu_lion.py +++ /dev/null @@ -1,4 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# DeepSpeed Team - -from .cpu.reflow_cpu_lion import ReflowCPULionBuilder # noqa: F401 diff --git a/tests/unit/v1/ops/test_reflow_cpu_optimizers.py b/tests/unit/v1/ops/test_reflow_cpu_optimizers.py index 3e9ddecf5e02..702bce92cf84 100644 --- a/tests/unit/v1/ops/test_reflow_cpu_optimizers.py +++ b/tests/unit/v1/ops/test_reflow_cpu_optimizers.py @@ -20,6 +20,7 @@ from cpuinfo import get_cpu_info import deepspeed +from deepspeed.accelerator import get_accelerator from deepspeed.ops.op_builder import CPUAdamBuilder, CPULionBuilder from deepspeed.ops.op_builder.cpu.reflow_cpu_adam import ReflowCPUAdamBuilder from deepspeed.ops.op_builder.cpu.reflow_cpu_lion import ReflowCPULionBuilder @@ -135,8 +136,10 @@ def test_reflow_builder_rejects_unvalidated_accelerator(builder, monkeypatch): def test_reflow_extension_is_independent(normal, reflow, symbol): if not reflow().is_compatible() or not normal().is_compatible(): pytest.skip("requires compatible CPU optimizers") + reflow_builder = get_accelerator().create_op_builder(reflow.__name__) + assert reflow_builder is not None normal_module = normal().load() - reflow_module = reflow().load() + reflow_module = reflow_builder.load() assert not hasattr(normal_module, symbol) assert hasattr(reflow_module, symbol) assert normal_module is not reflow_module