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/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/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/ci/tests_fetcher.py b/ci/tests_fetcher.py index e586c14f4ea7..d866299b6c43 100644 --- a/ci/tests_fetcher.py +++ b/ci/tests_fetcher.py @@ -189,6 +189,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 14c94c5ca3f4..d9b6926fc992 100644 --- a/csrc/adam/cpu_adam.cpp +++ b/csrc/adam/cpu_adam.cpp @@ -4,6 +4,7 @@ // DeepSpeed Team #include "cpu_adam.h" +#include PYBIND11_MODULE(TORCH_EXTENSION_NAME, 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..f6e60fc5b492 --- /dev/null +++ b/csrc/adam/reflow_cpu_adam_bindings.cpp @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: Apache-2.0 +// DeepSpeed Team + +#include +#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 +} + +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++)", + 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, + pybind11::call_guard(), + "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, + 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, + pybind11::call_guard(), + "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, + pybind11::arg("maximize") = 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, + pybind11::call_guard(), + "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..e0f984a917f7 --- /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; + 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); + }); + } + } +} + +// 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, + 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(); + 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); + 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) { + dispatch(c10::Half{}, c10::Half{}); + } else if (store_type == grad_type && grad_type == torch::kBFloat16 && + state_type == torch::kFloat32) { + dispatch(c10::BFloat16{}, float{}); + } else if (store_type == grad_type && grad_type == torch::kBFloat16 && + state_type == torch::kBFloat16) { + dispatch(c10::BFloat16{}, c10::BFloat16{}); + } else +#endif + { + throw std::runtime_error( + "reflow_ds_adam_step_params_halfgrad: unsupported combination of store/grad/state " + "dtypes"); + } + 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, + 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); + 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_cpu_adam.h b/csrc/includes/reflow_cpu_adam.h new file mode 100644 index 000000000000..285f230a93fc --- /dev/null +++ b/csrc/includes/reflow_cpu_adam.h @@ -0,0 +1,425 @@ +// 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_ready.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. + */ + 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; } + + // 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 (!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); + }; + 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. + // A negative scale folds maximizing into the existing gradient multiply, before weight decay. + 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); } + + 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); } + 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 constexpr (store_half_params) { + // Param generation leaves the FP32 master and the state to the later commit. + 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 + +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, + bool maximize = false, + ReflowReadyWork* work = nullptr, + size_t destination_offset = 0); + +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, + bool maximize = 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..a2e145d25f6c --- /dev/null +++ b/csrc/includes/reflow_cpu_lion.h @@ -0,0 +1,365 @@ +// 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_ready.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. + */ + 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; } + +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 sign_mask_4; + sign_mask_4.data = SIMD_SET(-0.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); + + 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, 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); + } 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 sign_mask_4; + sign_mask_4.data = SIMD_SET(-0.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 (!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); + }; + 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. + 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); } + 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, 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); + } else { + simd_add(param_4, param_4, tmp_4); + } + reflow_simd_store_ready(half_params + i, param_4, stream_output); + }); + + *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, + 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, + 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_ready.h b/csrc/includes/reflow_ready.h new file mode 100644 index 000000000000..76b95926dd24 --- /dev/null +++ b/csrc/includes/reflow_ready.h @@ -0,0 +1,225 @@ +// 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.dim() == 1); + auto prepare_tensor = [size](const at::Tensor& tensor) { + TORCH_CHECK(tensor.device().is_cpu() && tensor.is_contiguous() && + static_cast(tensor.numel()) == size); +#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 + }; + 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_)); + 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; + const auto& range = work->ranges_[chunk.range]; + 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. + // 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) {} + + // 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_; + 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 new file mode 100644 index 000000000000..72b16f4428d1 --- /dev/null +++ b/csrc/includes/reflow_simd.h @@ -0,0 +1,110 @@ +// SPDX-License-Identifier: Apache-2.0 +// DeepSpeed Team + +#pragma once + +#include "simd.h" + +#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) +#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) +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 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 + __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)); + return _mm_blendv_epi8(non_nan_res, _mm_set1_epi16((short)0x7fc0), nan_mask16); +} + +// 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__) +template +inline bool reflow_stream_ready_output(T* dst) +{ + // 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 void reflow_simd_store_ready(T* dst, AVX_Data* src, bool stream_output) +{ +#pragma unroll + for (size_t i = 0; i < span; ++i) { + INTV packed; + if constexpr (std::is_same_v) { + packed = pack_f32_as_bf16_nearest(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 void reflow_simd_store(T* dst, AVX_Data* src) +{ + simd_store(dst, src); +} + +template +inline void reflow_simd_load(AVX_Data* dst, T* src) +{ + simd_load(dst, src); +} +#endif 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/cpu_lion.cpp b/csrc/lion/cpu_lion.cpp index c5cf3e9e9235..acf7815d19fb 100644 --- a/csrc/lion/cpu_lion.cpp +++ b/csrc/lion/cpu_lion.cpp @@ -4,6 +4,7 @@ // DeepSpeed Team #include "cpu_lion.h" +#include PYBIND11_MODULE(TORCH_EXTENSION_NAME, 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..b322f01c70c1 --- /dev/null +++ b/csrc/lion/reflow_cpu_lion_bindings.cpp @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: Apache-2.0 +// DeepSpeed Team + +#include +#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 +} + +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++)", + 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, + pybind11::call_guard(), + "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, + pybind11::arg("ready_work") = nullptr, + pybind11::arg("destination_offset") = 0); + m.def("reflow_lion_update_state_halfgrad", + &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"), + 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..6cae2706a166 --- /dev/null +++ b/csrc/lion/reflow_cpu_lion_impl.cpp @@ -0,0 +1,458 @@ +// 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; + 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); + }); + } + } +} + +// 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, + 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(); + 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); + 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) { + dispatch(c10::Half{}, c10::Half{}); + } else if (store_type == grad_type && grad_type == torch::kBFloat16 && + state_type == torch::kFloat32) { + dispatch(c10::BFloat16{}, float{}); + } else if (store_type == grad_type && grad_type == torch::kBFloat16 && + state_type == torch::kBFloat16) { + dispatch(c10::BFloat16{}, c10::BFloat16{}); + } else +#endif + { + throw std::runtime_error( + "reflow_ds_lion_step_params_halfgrad: unsupported combination of store/grad/state " + "dtypes"); + } + 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 b27a61c9c160..db63b07de6b1 100755 --- a/deepspeed/runtime/config.py +++ b/deepspeed/runtime/config.py @@ -698,6 +698,27 @@ 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 reflow_enabled: + 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; " + "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/engine.py b/deepspeed/runtime/engine.py index dd3e5a021e94..bf8f3e166eb9 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 @@ -647,7 +648,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]) @@ -2469,8 +2471,12 @@ 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. + if reflow_engine.reflow_enabled(self): + basic_optimizer = reflow_engine.maybe_remap_client_optimizer(self, basic_optimizer) self._check_for_duplicates(basic_optimizer) @@ -2507,7 +2513,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: @@ -2521,6 +2531,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: @@ -2628,7 +2640,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) @@ -2870,8 +2885,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..e23c891d2be4 --- /dev/null +++ b/deepspeed/runtime/reflow/README.md @@ -0,0 +1,331 @@ +# 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. + +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. + +**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. + +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 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 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 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 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 +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 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) +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`. 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. + +--- + +## 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 `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, 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 +`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. + +--- + +## 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": 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) + } + // 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"`). 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 +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. 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` | `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` | `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. | + +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 +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 +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 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). +- **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. 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. + +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 + +- **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` + (`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. 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. + +--- + +## 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** — 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). +- **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..b80f3341ac8d --- /dev/null +++ b/deepspeed/runtime/reflow/engine.py @@ -0,0 +1,119 @@ +# 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 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 + + +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 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): + # 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", "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]) + 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), + maximize=defaults.get("maximize", False), + adamw_mode=bool(adamw_mode), + num_threads=reflow_num_threads(engine)) diff --git a/deepspeed/runtime/reflow/ready_batch.py b/deepspeed/runtime/reflow/ready_batch.py new file mode 100644 index 000000000000..62efee5e5776 --- /dev/null +++ b/deepspeed/runtime/reflow/ready_batch.py @@ -0,0 +1,102 @@ +# 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_eligible(self): + # Native writers can take a successor early only when both of its inputs are ready. + with self.lock: + if not self.pending: + return None + item = self.pending[0] + 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 + 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 run(self): + stream = self.optimizer._bucketwise_h2d_stream + started = False + try: + while 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: + 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 new file mode 100644 index 000000000000..1cadacdfca2e --- /dev/null +++ b/deepspeed/runtime/reflow/reflow_config.py @@ -0,0 +1,49 @@ +# 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. + 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" + """Count main-thread reservations as logical CPUs or physical cores including their SMT siblings.""" + + 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"] = "thread" + """Choose a CPU mask per bucketwise task, or reuse a fixed bucketwise mask on each pool thread.""" + + 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.""" + + 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..438568a52fd0 --- /dev/null +++ b/deepspeed/runtime/reflow/reflow_cpu_adam.py @@ -0,0 +1,202 @@ +# 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 +``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. +""" + +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.cpu.reflow_cpu_adam import ReflowCPUAdamBuilder +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, + 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. + """ + 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. + default_args = dict(lr=lr, + betas=betas, + eps=eps, + weight_decay=weight_decay, + bias_correction=bias_correction, + amsgrad=amsgrad, + maximize=maximize) + 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 = 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) + + 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 + 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 = ReflowCPUAdamBuilder().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, + maximize=hyperparams.get("maximize", False)) diff --git a/deepspeed/runtime/reflow/reflow_cpu_lion.py b/deepspeed/runtime/reflow/reflow_cpu_lion.py new file mode 100644 index 000000000000..a5e3ba32459c --- /dev/null +++ b/deepspeed/runtime/reflow/reflow_cpu_lion.py @@ -0,0 +1,165 @@ +# 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 +``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. +""" + +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.cpu.reflow_cpu_lion import ReflowCPULionBuilder +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`, 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. + 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 = 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) + + 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). + 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..74e81703d69c --- /dev/null +++ b/deepspeed/runtime/reflow/reflow_stage3.py @@ -0,0 +1,2081 @@ +# Copyright (c) DeepSpeed Team. +# SPDX-License-Identifier: Apache-2.0 + +# DeepSpeed Team + +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 +import torch + +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.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.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_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. +_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. + + 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): + # zero.Init models bypass the engine's parameter cast, so validate their actual dtype too. + 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 + # 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 + self._reflow_window_grad_ids = set() + self._reflow_boundary_grad_ids = set() + 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 + 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) + 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 + # 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_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. + 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 _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: + 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 + + 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_optimizer_workers(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._reflow_config.pin_main_thread) + self._worker_node_groups = node_worker_groups + + self._worker_cpu_affinity_mask = set(worker_cores) + 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) + # 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: + 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: + 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._setup_bucketwise_executors() + + def _setup_bucketwise_executors(self): + cores_per_worker = self.bucketwise_cores_per_worker + + try: + 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] + + 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) + 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"{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 + 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_optimizer", + initializer=initializer) + + def _submit_bucketwise_task(fn, *args, **kwargs): + 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) + + 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._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 = {} + # 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._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 + # 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_enqueue_lock = threading.Lock() + 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 + 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_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 + self._last_enqueue_future = 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"): + executor = getattr(self, attr, None) + if executor is not None: + try: + executor.shutdown(wait=True) + except Exception: + pass + 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 + # ------------------------------------------------------------------ # + 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 _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): + # 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: + 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, 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: + 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) + 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(): + 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.""" + 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 _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._bucketwise_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") + + # ------------------------------------------------------------------ # + # 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): + 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; + # 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 + # ------------------------------------------------------------------ # + 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 = [] + + # Cache loop-invariant values (avoid repeated getattr/property/C++ binding calls). + is_boundary = self.is_gradient_accumulation_boundary() + 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) + 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 + + 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 + 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: + # 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 + 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)) + + grad_numel = grad_buffer.numel() + + if not first_grad: + # Both slices must remain unchanged until the previous worker consumes them. + self._wait_for_accum_gradient(param_id) + + 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. + 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) + + with get_accelerator().stream(copy_grad_stream): + pending_slice.copy_(converted_grad.view(pending_slice.shape), non_blocking=True) + 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: + 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 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): + 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 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) + # 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() + 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) + 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): + _copy_event.synchronize() + ReflowCPUAdam.bf16_accumulate(_dst_slice.view(-1), _src_slice.view(-1)) + + future = accumulate_submit(_accumulate_worker) + self._bucketwise_accumulation_futures[param_id] = 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._pending_grad_ready = True + if boundary_grad: + self._reflow_boundary_grad_ids.add(param_id) + 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: + 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._reflow_window_grad_ids.clear() + self._reflow_boundary_grad_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._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_last_copy_event_by_group.clear() + if self._bucketwise_inflight_futures is not None: + self._bucketwise_inflight_futures.clear() + 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() + for sub_group_id in self._published_ready_groups: + self._restore_fp16_params_from_master(sub_group_id) + 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() + self._bucketwise_worker_error = worker_error + 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: + 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 _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 + + # 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: + 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._pin_current_thread(original_cpus) + + try: + tail = self._bucketwise_update_executor.submit(commit_all) + except Exception as error: + tail = Future() + tail.set_exception(error) + + if earlier: + + 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 + # 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: + # One pool job owns every resident subgroup in this step. + 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, 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): + 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 _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, 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 + 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): + # 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) + 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 + + 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 self._pending_grad_ready: + if flush_pending: + 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 + + # ------------------------------------------------------------------ # + # 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. + """ + # 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, stage_checkpoint) + return + try: + 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_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.""" + # 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.""" + 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 _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): + """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"] + ranges = work_item["ranges"] + grad_buffer_index = work_item["grad_buffer_index"] + combined_scale = work_item["combined_scale"] + last_copy_event = work_item["last_copy_event"] + target_step = work_item["target_step"] + + 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 != self._bucketwise_cancel_version: + return None + + # 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) + + fp32_param = self.fp32_partitioned_groups_flat[sub_group_id] + # 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] + # 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: + 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)") + + state = self.optimizer.state[fp32_param] + + 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) + momentum = state['exp_avg'].view(-1) + 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: + 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): + 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: + 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: + 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"]: + return self._copy_ready_ranges(fp16_flat, output, ranges, prepare=prepare_range) + + 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, 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 + # so step() can abort deterministically on all ranks instead of silently advancing. + 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}") + return None + + def _copy_ready_ranges(self, fp16_flat, output, ranges, prepare=None): + accelerator = get_accelerator() + stream = self._bucketwise_h2d_stream + if stream is None: + stream = accelerator.current_stream() + dst, src = fp16_flat.detach().view(-1), output.detach().view(-1) + 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: + 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) + 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) + if clipped_range is None: + return + dest_offset, num_elements = clipped_range + + with self._bucketwise_enqueue_lock: + if stage_checkpoint: + self._pending_checkpoint_groups.add(sub_group_id) + if copy_event is not None: + 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 + 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, + 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, 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 + ranges = self._bucketwise_pending_ranges_by_group[sub_group_id] + if not ranges: + return None + merged_ranges = reflow_utils.merge_contiguous_ranges(ranges) + 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 + + last_copy_event = self._bucketwise_last_copy_event_by_group.pop(sub_group_id, 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 + 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": 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, 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, + use_pending_buffer=use_pending_buffer, + combined_scale=combined_scale) + + def _bucketwise_cancel_inflight_updates(self): + # 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: + batch = self._ready_batches.get(f) + if batch is not None: + batch.discard() + 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 _ensure_bucketwise_group_step(self, sub_group_id): + """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) + 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 + # synchronized later via CUDA events. + + 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: + 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() + + 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, + 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]) + 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, + # 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._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): + # 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() + + 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) + 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 + 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 + 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, 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. + self._state_commit_overlaps_forward = False + super().backward_prologue() + + def _state_commit_cpu_affinity_mask(self): + 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() + + 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 = [ + 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) + # 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. + self._all_reduce_norm_entries_by_group(total_norms, partition_groups) + 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) + + 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 + # ------------------------------------------------------------------ # + @instrument_w_nvtx + def step(self, closure=None): + """ + Not supporting closure. + """ + self._wait_for_accum_gradient() + self._wait_for_pending_state_updates() + self._pre_step() + self._partition_all_parameters() + # 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: + 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.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() + return + + global_grad_norm = scaled_global_grad_norm / self.loss_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 + # 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) + else: + if not flushed_before_norm: + 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() + 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(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: + 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 + 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: + # 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() + 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 + # 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: + 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) + + 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 _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 + 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 + self._reassign_or_swap_out_partitioned_parameters(sub_group_id) + + # ------------------------------------------------------------------ # + # gradient access + # ------------------------------------------------------------------ # + + def get_fp32_grad_for_param(self, param) -> Tensor: + 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_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) + numel = param.partition_numel() + device = get_accelerator().current_device_name() + 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() + 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) + numel = param.partition_numel() + assert value.numel() == numel, f"Number of elements do not match: {value.numel()} != {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._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() + + 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: + 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: + 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) + self.norm_for_param_grads[param_id] = norm + + def _refresh_edited_gradient_overflow(self): + 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: + 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) + 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. + 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_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_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 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, + 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() + if self._bucketwise_worker_error is not None: + 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 new file mode 100644 index 000000000000..6f1974c66fc4 --- /dev/null +++ b/deepspeed/runtime/reflow/reflow_utils.py @@ -0,0 +1,476 @@ +# 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 socket + +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): + """Assign whole physical cores, sharing only when there are fewer cores than ranks.""" + groups = physical_cpu_groups(cpus) + if len(groups) < ranks: + return list(groups[position % len(groups)]) + 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": + 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)) + 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]) + 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: + 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. + base, remainder = divmod(len(node), ranks_per_node) + start = pos * base + min(pos, remainder) + count = base + (pos < remainder) + return node[start:start + count] + # 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.") + return [node[pos % len(node)]] + + +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] + local = { + "host": socket.gethostname(), + "cpus": sorted(rank_cores), + "units": units, + "pin": pin_main_thread, + } + 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) + 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"] + + 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. 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. + 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: + base, remainder = divmod(len(node_cores), n_on_node) + start = my_pos * base + min(my_pos, remainder) + count = base + (my_pos < remainder) + 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: + rank_cores = heuristic_rank_cores(numa_nodes, local_rank, local_world_size, physical=physical) + + if not rank_cores: + if affinity: + rank_cores = affinity + 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_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. + 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) + 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 + + +def merge_contiguous_ranges(ranges): + # 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 = max(cur_sz, off + sz - cur_off) + else: + merged.append((cur_off, cur_sz)) + cur_off, cur_sz = off, sz + merged.append((cur_off, cur_sz)) + 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. + + 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 diff --git a/deepspeed/runtime/zero/config.py b/deepspeed/runtime/zero/config.py index 72791ecc6ba9..82cf697f2625 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. @@ -189,6 +190,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 @@ -416,3 +425,24 @@ 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 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: + raise ValueError("Reflow is not compatible with super_offload; enable only one of them.") + return self 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/deepspeed/runtime/zero/partitioned_param_coordinator.py b/deepspeed/runtime/zero/partitioned_param_coordinator.py index dd6d6a64c441..f5a278f56815 100644 --- a/deepspeed/runtime/zero/partitioned_param_coordinator.py +++ b/deepspeed/runtime/zero/partitioned_param_coordinator.py @@ -162,6 +162,20 @@ def __init__( # and the modules and parameters it references, alive for the life of the process. self.__params_to_release = functools.lru_cache(maxsize=None)(self.__params_to_release) + 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/stage3.py b/deepspeed/runtime/zero/stage3.py index ab59dd56ef2a..33de25bcca22 100644 --- a/deepspeed/runtime/zero/stage3.py +++ b/deepspeed/runtime/zero/stage3.py @@ -799,7 +799,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) @@ -837,8 +837,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) @@ -1138,7 +1139,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 @@ -1217,13 +1218,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 \ @@ -1373,26 +1377,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 @@ -1801,7 +1805,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: @@ -1861,6 +1865,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: @@ -2195,18 +2202,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/deepspeed/runtime/zero/utils.py b/deepspeed/runtime/zero/utils.py index b8ef662c9c8f..d9c27f064c14 100755 --- a/deepspeed/runtime/zero/utils.py +++ b/deepspeed/runtime/zero/utils.py @@ -55,6 +55,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/timer.py b/deepspeed/utils/timer.py index 2e07f00f1fa7..0fe5e5514a05 100644 --- a/deepspeed/utils/timer.py +++ b/deepspeed/utils/timer.py @@ -205,7 +205,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 @@ -224,6 +231,10 @@ 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 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: raise ImportError("Unable to import 'psutils', please install package") @@ -235,6 +246,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 @@ -242,7 +259,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): @@ -260,7 +277,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 e608757040f6..d6b3f6a0aa58 100644 --- a/docs/_pages/config-json.md +++ b/docs/_pages/config-json.md @@ -717,6 +717,91 @@ 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 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`) 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, + "enable_cpu_affinity": false, + "main_thread_cores": 3, + "main_thread_core_type": "logical", + "pin_main_thread": true, + "worker_core_type": "logical", + "bucketwise_worker_affinity": "thread", + "bucketwise_cores_per_worker": null, + "h2d_chunk_size_mib": 16, + "state_update_cores": null, + "state_update_backward_cores": null + } +``` +***num_threads***: [integer or null] + +| Description | Default | +| ----------- | ------- | +| 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 | +| ----------- | ------- | +| 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 | +| ----------- | ------- | +| 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] + +| 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. | `true` | + +***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 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 or null] + +| Description | Default | +| ----------- | ------- | +| 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] + +| Description | Default | +| ----------- | ------- | +| 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] + +| 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 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..a628e0cc8e94 --- /dev/null +++ b/docs/_tutorials/reflow.md @@ -0,0 +1,88 @@ +--- +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 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. + +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 + +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 + } + }, + "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. 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: + +```bash +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 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 + +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 + +- 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. +- 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. +- 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 4c3eb8c3f7ca..d71f81e285a6 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/__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/reflow.py b/op_builder/cpu/reflow.py new file mode 100644 index 000000000000..ac3217f293d0 --- /dev/null +++ b/op_builder/cpu/reflow.py @@ -0,0 +1,60 @@ +# SPDX-License-Identifier: Apache-2.0 +# DeepSpeed Team + +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): + _, flags = _cpu_info() + return flags + + 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/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 new file mode 100644 index 000000000000..702bce92cf84 --- /dev/null +++ b/tests/unit/v1/ops/test_reflow_cpu_optimizers.py @@ -0,0 +1,564 @@ +# 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. +""" + +from functools import lru_cache + +import pytest +import torch +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 +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" + +# 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") + + +@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__"): + 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, 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") + _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 + + +@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. + 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") + reflow_builder = get_accelerator().create_op_builder(reflow.__name__) + assert reflow_builder is not None + normal_module = normal().load() + reflow_module = reflow_builder.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 + + 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)], + 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(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) + 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 = 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. + 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__.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"]) +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(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 = 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, + 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(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() + 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 = 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, + 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)... + 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) + + +@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 + 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 = 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() + 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__.get(ReflowCPUAdamBuilder.NAME, False): + pytest.skip("ReflowCPUAdamBuilder is not compatible") + _skip_without_avx(ReflowCPUAdamBuilder) + _skip_amd_fp16(dtype) + module = ReflowCPUAdamBuilder().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) + + +@pytest.mark.parametrize('adamw_mode', [False, True], ids=['adam', 'adamw']) +@pytest.mark.parametrize('model_size', [7, 129, 4099]) +@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__.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] + 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) + + +@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 new file mode 100644 index 000000000000..8bf216cbb44d --- /dev/null +++ b/tests/unit/v1/zero/test_reflow.py @@ -0,0 +1,2755 @@ +# 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 concurrent.futures import Future, ThreadPoolExecutor +from contextlib import ExitStack +from unittest.mock import Mock, patch +from types import SimpleNamespace + +import pytest +import torch +from torch.utils.checkpoint import checkpoint + +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 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 +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.utils import combine_grad_norm_groups +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_update_full_grad_vectorized) +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, "bf16": {"enabled": True}, "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 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 + + 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})) + + +@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", + "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 + 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"})) + 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 + + +@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() + 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(): + # 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)) + + +@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} + 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) + + +@pytest.mark.parametrize("precision_config, error", [ + ({ + "bf16": { + "enabled": False + } + }, "requires FP16 or BF16 model parameters"), + ({ + "torch_autocast": { + "enabled": True, + "dtype": "bfloat16" + } + }, "requires FP16 or 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) + + +@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): + # 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"] + 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)] + 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. +# 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(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 = [] + 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 == "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, state_keys=()): + 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()) + 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() + + +@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, precision): + skip_if_reflow_training_unsupported(variant) + hidden_dim = 16 + 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) + 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) + 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) + + # 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"] + 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 TestReflowSmallLossScaleMatchesZeroOffload(DistributedTest): + world_size = [1, 2] + + def test_fp16_training_matches_zero_offload(self, optimizer_kind): + 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) + + 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): + 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(optimizer_kind) + + 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" + + +@needs_gpu_accelerator +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 + # 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 +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", + "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, **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, **kwargs) + + 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) + + +@pytest.mark.parametrize( + "rank_affinity", ["shared", "launcher", "partial", "insufficient", "small_shared", "one_cpu", "oversubscribed"]) +@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]) + 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 + 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 == "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, + 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() + 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 == 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() + dist.all_gather_object(placements, (main_cpus, rank_cpus)) + 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: + 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 + + 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, 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") + 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 + + @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("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(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": + 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]) + @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 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) + + +@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 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] + 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) + + +@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() + + +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 TestReflowGradientStorage(DistributedTest): + world_size = 1 + + @pytest.mark.parametrize("pin_memory", [False, True]) + def test_no_discarded_model_sized_gradient(self, pin_memory): + skip_if_reflow_training_unsupported() + 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 + + # 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 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 + + with patch.object(torch, "zeros", track_zeros): + engine, optimizer, _, _ = deepspeed.initialize(model=model, + model_parameters=model.parameters(), + config=config) + 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 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 +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() + + +@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() + + +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 + 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): + 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 = { + "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), (2, False), (3, False), (4, False), + (8, 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}" + + +@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 + + +@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): + 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_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)] + + 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, 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": + 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 + config["gradient_clipping"] = clip + 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=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((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))): + 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): + world_size = 1 + + @pytest.mark.parametrize("optimizer_kind", ["adam", "lion"]) + @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") + # 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) + 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"][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) + 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) + 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()] + # 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() + + 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}" + + @pytest.mark.parametrize("optimizer_kind", ["adam", "lion"]) + @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") + 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() + 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()] + 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 + 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) + + +@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, pin_memory, offload_param): + skip_if_reflow_training_unsupported() + 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 + # 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} + 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()] + 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) + 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() 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):