DeepSpeed
83df08a5 - Honor explicit dtype in ZeRO tensor constructors (#8959)

Commit
2 days ago
Honor explicit dtype in ZeRO tensor constructors (#8959) ## Summary Fixes #8948. Honor an explicit tensor-constructor `dtype` inside `deepspeed.zero.Init`, instead of unconditionally converting floating-point results to the context's dtype. Previously, unconditional conversion rounded an explicitly fp32 `torch.arange` to bf16 before a model computed RoPE inverse frequencies. Converting the resulting buffer back to fp32 could not recover the lost precision. ## Changes - Preserve a non-`None` explicit `dtype` in both the wrapped torch factory functions (`zero_wrapper_for_fp_tensor_constructor`) and the `torch.Tensor.__new__` hook (`get_new_tensor_fn_for_dtype`), while keeping the existing context-dtype conversion when `dtype` is omitted or `None`. Device override and parameter-partitioning behavior are unchanged. - Cast floating-point parameters to the Init dtype in `_post_init_method` before partitioning so explicitly typed `nn.Parameter` tensors still match the ZeRO-3 flattened partition dtype. - Record `_ds_zero_init_dtype` on newly registered floating-point non-ZeRO parameters inside `Init(dtype=...)` (for example, when a parent constructor replaces or adds a parameter on an already-partitioned child) and honor it in both `Init(module=...)` and `convert_to_zero_parameters` during `deepspeed.initialize()`. Uses `register_module_parameter_registration_hook` on PyTorch >= 2.5 and falls back to wrapping/restoring `Module.register_parameter` on older PyTorch versions. - Update `deepspeed/runtime/keep_in_fp32.py` to set `_ds_zero_init_dtype = torch.float32` on matching tensors so a replaced child weight in `keep_in_fp32_modules` is not downcast to bf16 during deferred conversion. - Document constructor dtype precedence and marked-parameter behavior in the `zero.Init` docstring. - Add regressions in `tests/unit/runtime/zero/test_zero_context.py` covering explicit fp32 RoPE-style frequencies, explicit fp32 `torch.Tensor` vs implicit bf16 defaults, explicit fp32 parameter training under bf16 ZeRO-3, replaced child weights, added child biases (both with and without `Init(module=model)`), the PyTorch < 2.5 registration fallback, and `keep_in_fp32_modules` precision preservation. This intentionally changes dtype precedence for explicitly typed constructor calls. Such tensors may use more initialization memory than before when their requested dtype is wider than the context dtype. This does not change the engine's subsequent model/buffer conversion policy. ## Validation Validated head: `6452a2947` (and `7cdf75be0` for the full `test_keep_in_fp32_modules.py` + `test_zero_linear_direct_init.py` suites). - **GPU hardware & software**: 4x NVIDIA H20 (driver `580.178.04`), Python 3.12.3, PyTorch `2.13.0+cu129`. - **Commands & results**: ```bash # On 6452a2947 (H20, CUDA): CUDA_VISIBLE_DEVICES=0,1 python -m pytest -v tests/unit/runtime/zero/test_zero_context.py # 19 passed, 0 failed, 0 skipped # On 7cdf75be0 (H20, CUDA): CUDA_VISIBLE_DEVICES=0,1,2,3 python -m pytest -v tests/unit/runtime/zero/test_zero_context.py tests/unit/runtime/zero/test_zero_linear_direct_init.py # 22 passed, 0 failed, 0 skipped CUDA_VISIBLE_DEVICES=4,5,6,7 python -m pytest -q tests/unit/v1/half_precision/test_keep_in_fp32_modules.py # 57 passed, 0 failed, 0 skipped (including 4-GPU hpZ and quantized tests) ``` - **GPU RoPE precision check** (`cuda:0`, `dim=256`, `theta=1e7`, `deepspeed.zero.Init(dtype=torch.bfloat16)`): `dtype=torch.float32`, `max_rel_err=7.99e-08`, `pos=65536 max_angle_err=0.0029 rad`. - **Before/after regression checks**: - `test_explicit_tensor_dtype_is_preserved`: fails on `origin/master`, passes with fix. - `test_added_child_bias_trains_without_registration_hook`: failed on `7cdf75be0` when `register_module_parameter_registration_hook` was absent (`RuntimeError: self and mat2 must have the same dtype, but got Float and BFloat16`), passes on `6452a2947`. - `test_replaced_child_weight_in_keep_in_fp32_preserves_fp32_precision`: fails without the `keep_in_fp32.py` marker update (`dtype=torch.bfloat16`, `1.0001234` rounded to `1.0`), passes with it. - **Pre-commit**: All configured hooks (`yapf`, `flake8`, `check-torchdist`, `check-torchcuda`, `check-license`, `codespell`, etc.) passed on commit `6452a2947`. ## Compatibility and remaining validation | Area | Coverage | |---|---| | ZeRO-3 `zero.Init`, bf16 context, explicit fp32 and implicit constructor dtypes | Passed on NVIDIA H20 GPU & CPU | | Existing ZeRO context/sharding/gather & direct-init tests | 22/22 passed on NVIDIA H20 (1- and 2-rank) | | `keep_in_fp32_modules` (stages 0–3, 4-GPU hpZ, quantized, replaced child precision) | 57/57 + new precision test passed on NVIDIA H20 | | PyTorch < 2.5 registration fallback | Verified via monkeypatch regression test on NVIDIA H20 | | fp16/fp32 context targets for the new regressions | Not separately exercised | | Non-CUDA accelerators (XPU/HPU/ROCm/MPS) | Not run locally | | CPU/NVMe offload and tensor/pipeline/sequence/expert parallel combinations | Not specifically validated | | Full Transformers end-to-end training convergence & throughput/peak memory | Not run; no performance or convergence claim | ## Sibling-path check - Checked both ZeRO-3 constructor hooks (`zero_wrapper_for_fp_tensor_constructor` and `get_new_tensor_fn_for_dtype`) and `_post_init_method`. - ZeRO-1/2 optimizer paths and fp16/bf16 optimizer wrappers do not define tensor-constructor hooks (they operate on already-constructed parameters). - The independent `deepspeed.OnDevice` constructor wrappers retain their existing conversion policy and are outside this PR's `zero.Init` scope. ## Duplicate check Checked issue #8948 and open PR searches for `8948 in:body` and `zero.Init explicit dtype`. No other PR addresses this constructor-dtype fix. Related #8843 preserves model-listed fp32 parameters and does not prevent precision loss during explicitly typed tensor construction. ## AI assistance The implementation, regression tests, and this description were prepared with AI assistance. --------- Signed-off-by: Jin, Youzhi <youzhi.jin@intel.com> Signed-off-by: Masahiro Tanaka <tanaka.masahiro@gmail.com> Signed-off-by: iLeGend <824040212@qq.com> Co-authored-by: pengdurice <pengduhit@gmail.com> Co-authored-by: Masahiro Tanaka <tanaka.masahiro@gmail.com>
Author
Parents
Loading