Repository navigation
Conversation
48fe936 to
f0305ff
Compare
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f0305ff4c9
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if not param.requires_grad and self.quantized_nontrainable_weights: | ||
| with torch.no_grad(): | ||
| quantized_storage, scale = self.quantizer_module.quantize(param.ds_tensor.data) | ||
| param.ds_tensor.data = quantized_storage |
There was a problem hiding this comment.
Preserve NVMe swap-buffer storage while quantizing
On CUDA, when ZeRO-3 NVMe offload uses the param_swapper.get_buffer() branch for a frozen partition, param.ds_tensor points into the swapper's CPU buffer. CUDAQuantizer.quantize() returns a new accelerator tensor, so rebinding .data here disconnects the partition from that buffer; the subsequent swap-out writes the original fp16 values to disk while leaving ds_quant_scale attached. On the next swap-in, the gather path interprets those fp16 bytes as int8 codes, corrupting the frozen weights.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 7b25758. NVMe-backed partitions now stay unquantized, matching the pre-change behavior: ds_tensor aliases the swapper buffer, so rebinding .data would make swap-out persist the original fp16 bytes while ds_quant_scale remains attached. Quantized NVMe storage would require an int8 swapper buffer and is out of scope for this fix. NPU regression tests pass (2 passed); AsyncIO is unavailable in this environment, so the NVMe branch was validated by inspection rather than end to end.
|
Hi @VenusTZZ thanks for contributing this PR. I want to first understand the use case here. This PR is trying to enable LoRA finetuning when base weights are quantized. So are base weights also quantized when the finetuned model is inferenced? Asked so because I'm wondering if this optimization is only for the sake of training acceleration or also allows inference acclerated due to quantization of base weight, thanks! |
7b25758 to
fe8aaab
Compare
…on Ascend (deepspeedai#9043) ## Summary This fixes two runtime defects in the Ascend NPU op builders added by deepspeedai#8627: 1. **Every fp16 LAMB step fails** with `RuntimeError: a leaf Variable that requires grad is being used in an in-place operation.` The fused LAMB implementation copies the updated fp32 master weight into the fp16 model parameter with `p_copy.copy_(p.data)`; `p_copy` is a leaf parameter that requires grad. 2. **Every fp16 inference weight dequantization fails** with `NotImplementedError: experimental fp_quantizer path is not needed for hpZ`. `DeQuantizer.dequantize` takes its fp16 fast path for last-dimension groups, but the Ascend quantizer builder never implemented the two entry points it calls. Both failures are currently reported by CI: the affected cases belong to the existing unit-test shards, and this PR restores them by fixing the NPU implementations, not by skipping or disabling tests. **Design constraint:** all changes are confined to `op_builder/npu/`. No common runtime or inference code is modified. ## Problem ### 1. Fused LAMB: in-place copy of a leaf parameter Call chain: ``` tests/unit/... (DistributedTest, world_size=2) -> deepspeed/runtime/fp16/unfused_optimizer.py:169 step_fused_lamb self.optimizer.step(grads=..., output_params=self.fp16_groups, ...) -> deepspeed/ops/lamb/fused_lamb.py:165 FusedLamb.step self.fused_lamb_cuda.lamb(p.data, out_p, ...) -> op_builder/npu/fused_lamb.py:75 NPUFusedLamb.lamb p_copy.copy_(p.data) # <-- raises ``` `p_copy` is `out_p`, an fp16 parameter taken from `self.fp16_groups`. It is a leaf tensor with `requires_grad=True`, so PyTorch rejects the in-place copy. The copy only mirrors the fp32 update into the fp16 parameter; it is bookkeeping, not part of the autograd graph. Impact: **6 existing tests** covering FP16 + LAMB, empty gradients, MoE gradient norms, dynamic loss scale, and the unfused-optimizer checkpoint round-trip fail on Ascend. Any fp16 LAMB training run fails on its first step. ### 2. Inference int4/int8 dequantization: unimplemented entry points `DeQuantizer.dequantize` (`deepspeed/inference/quantization/utils.py:110`) enters the fused fast path when all of the following hold: - `group_size % 8 == 0` - `num_bits` is 4 or 8 - the quantization group is the last dimension - the parameter dtype is `torch.float16` - the runtime device matches the accelerator device All of them hold for fp16 inference weights on Ascend, so the dispatcher calls `get_quantizer_module().dequantize_int4_to_half_experimental(...)` or `dequantize_int8_to_half_experimental(...)`. Both Ascend entry points were stubs: ```python raise NotImplementedError("experimental fp_quantizer path is not needed for hpZ") ``` The fp32 cases in the same suite pass because `dtype == torch.float16` is false; they fall through to the generic `_decompress_uint4_to_uint8` + `_dequantize_int8` path. That is the numerical reference this fix matches. Impact: **12 existing tests** fail at this point in CI: the fp16 int4/int8 round-trips, the `group_dim=1` `QuantizedLinear` cases, and the ZeRO-3 post-init / quantized-initialization cases (including CPU offload). Inference weight quantization cannot be used on Ascend. ### Scope note: the shared int4 packer requires CANN 9.0.0 The shared `Quantizer._compress_uint8_to_uint4` uses a uint8 left shift, which CANN provides as `aclnnLeftShifts` from 9.0.0. The validation host originally used a manual CANN 8.5.1 installation and int4 failed there before dequantization; the conda toolkit was then reinstalled to **CANN 9.0.1** (`ascend-cann-toolkit` + `ascend-cann-910b-ops` 9.0.1), and the int4 cases now run end to end. CI uses CANN 9.0.0 (`cann:latest`), so it satisfies the same requirement. Fixing this on older CANN would require changing `deepspeed/inference/quantization/utils.py`, which is common inference code. This PR deliberately leaves it untouched; the requirement is documented instead (see the next section). ### CANN version note `aclnnLeftShifts` is provided by CANN 9.0.0 and later. Both environments satisfy this: local validation runs CANN 9.0.1, and CI uses the floating `swr.cn-southwest-2.myhuaweicloud.com/base_image/ascend-ci/cann:latest` image, whose 2026-11-09 `ds_report` output reports `ascend_cann version 9.0.0`. The image tag is not pinned and the workflows do not assert the version, but the current image has the operator. The version can be queried through torch_npu: ```python from torch_npu.utils import get_cann_version get_cann_version() # '9.0.1' locally, '9.0.0' in CI from torch_npu.npu.utils import _is_gte_cann_version _is_gte_cann_version('9.0.0', module='CANN') # True locally and in CI ``` No runtime gate is added: `torch.bitwise_left_shift` is the interface and dispatches to `aclnnLeftShifts` directly, which is exactly the call the shared packer already makes. The NPU dequantizers below are version-independent and are called directly by the existing fast path. The operator's support matrix covers this workload: the ACLNN documentation lists `INT8`/`INT16`/`INT32`/`INT64`/`UINT8`/`UINT16`/`UINT32`/`UINT64` inputs, a scalar `shiftBits`, non-contiguous tensors, and support on Atlas A2/A3/350 products. The 910B4 is an Atlas A2 device; the packer's input is `uint8` in `[0, 15]` and the shift amount is the scalar `4`, within the documented precision guarantee (`shiftBits` below the dtype width). torch_npu's own int4 packing APIs use a different wire format from DeepSpeed's inference format, so they are not drop-in substitutes: | torch_npu API | Layout | |---|---| | `torch_npu.npu_convert_weight_to_int4pack` | signed `[-8, 7]`, low nibble first, 8 values per `int32` | | `torch_npu.npu_quantize(..., dtype=torch.quint4x2)` | low nibble first, clamped to the signed int4 range, `int32` output | | `torch_npu.npu_anti_quant` | consumes int32-packed int4 (8 values per int32), same low-nibble-first layout | DeepSpeed inference stores unsigned `[0, 15]` values, high nibble first, two per `uint8`. Reusing the torch_npu APIs would require nibble swapping and a `-8` offset, and the result would still have to be called from the shared packer, so this PR leaves them unused. ## Fix ### Fused LAMB (`op_builder/npu/fused_lamb.py`) ```python p.data.copy_((p.float() - step_size * lamb_coeff * update).to(p.dtype)) if p_copy.numel() > 0: # p_copy is a leaf fp16 parameter and the copy only mirrors the # fp32 update into it, so it must not be recorded by autograd. with torch.no_grad(): p_copy.copy_(p.data) ``` Only the copy is wrapped; the rest of the update stays outside `no_grad`. The other in-place operations in `lamb()` (on `exp_avg`, `exp_avg_sq`, and `p.data`) were checked: the state tensors do not require grad, and `p.data.copy_` already bypasses autograd. ### Inference dequantizers (`op_builder/npu/quantizer.py`) Both entry points now implement the asymmetric inference formula `value / scale + min` in pure torch: ```python @staticmethod def _dequantize_inference_groups(values, scale_buffer, min_val_buffer, num_group, group_size): scale = scale_buffer.reshape(num_group, 1).to(torch.float16) min_val = min_val_buffer.reshape(num_group, 1).to(torch.float16) values = values.reshape(num_group, group_size).to(torch.float16) return values.div_(scale).add_(min_val) ``` The int4 entry point unpacks two unsigned nibbles per byte, **high nibble first** (even element in the high nibble, odd element in the low nibble), matching `Quantizer._compress_uint8_to_uint4`. It stays in `uint8` while unpacking and only then converts to fp16, so the temporary is one byte per element rather than the eight bytes an `int64` unpack would use. This is deliberately **not** reusing `NPUQuantizer._unpack_int4`: that helper belongs to the Zero++/hpZ wire format, which packs the even element in the low nibble and sign-extends each nibble. The inference format is high-nibble-first and unsigned (`0..15`); using the hpZ unpacker would swap elements and turn values above 7 into negatives. The implementation keeps the shared dispatcher unchanged and requires no new capability flag: the two entry points are exactly the contract the existing fast path calls. Their output is bitwise identical to the generic reference path (verified below), so no numerical branch is introduced. ### CANN version guard (`op_builder/npu/quantizer.py`) The int4 dequantizer calls `NPUQuantizer._check_int4_inference_support()` before unpacking. The check uses `torch_npu.npu.utils._is_gte_cann_version("9.0.0", module="CANN")` when available and falls back to parsing `torch_npu.utils.get_cann_version()`; it caches the result per process and fails open when the version cannot be determined. On CANN older than 9.0.0 (including 8.5.x) it raises a `RuntimeError` with the detected version and upgrade advice; on 9.0.0+ it returns and the normal path continues. Boundary: in the standard inference flow the shared packer runs before this entry point, so on CANN 8.5 the first error can still be the missing `aclnnLeftShifts`. The guard covers pre-packed weights and direct calls to the NPU entry point, and makes the version requirement explicit. Intercepting the shared packer itself would require a common-code hook, which this NPU-only change intentionally avoids. ## Sibling paths checked - **SUPA fused LAMB** (`op_builder/supa/fused_lamb.py:62`) has the same `p_copy.copy_(p.data)` pattern in its pure-PyTorch fallback. It is not changed here because no SUPA hardware was available to run it; it is listed under follow-ups. - **CUDA and other accelerated fused LAMB implementations** call compiled kernels and never execute this Python copy; they are unaffected. - **Quantizer builders:** CUDA and SUPA implement the two experimental entry points natively; only the Ascend builder raised `NotImplementedError`. - **Shared inference code:** `deepspeed/inference/quantization/utils.py` is unchanged; the int4 packer limitation is documented above rather than patched here. ## Compatibility, numerics, and memory - **Public API / config / checkpoints:** no changes. - **Numerics:** the LAMB copy has identical values; only autograd bookkeeping changes. The new dequantizers return bitwise-identical output to the existing generic path, so model outputs are unchanged. - **Memory:** the int4 fast path allocates one uint8 unpacking buffer (one byte per element) plus the fp16 output, the same order as the generic path. It does not widen to int64. - **Throughput:** no fused kernel is added; both dequantizers are plain torch, matching the generic path's cost. The LAMB change adds a `no_grad` context around one copy. - **Validated matrix cells:** fp16; int4/int8 dequantizer math; inference post-init quantization and quantized initialization; ZeRO-3; CPU parameter offload; world size 2; FP16 LAMB basic step, empty gradients, MoE gradient norm, dynamic loss scale, and checkpoint round-trip. - **Not validated here:** CUDA (no NVIDIA device in this environment), SUPA, NVMe parameter offload (skipped because async-io is not compatible on Ascend), tensor/pipeline parallelism, fp32 LAMB, and int4 on CANN < 9.0.0 (the operator is absent there). ## CI impact The failing cases are part of the existing unit-test shards, not new tests: | Shard | Cases | Status on this branch | |---|---|---| | `runtime` | 5 cases: `TestLambFP16::test__basic`, `TestLambFP16::test_empty_grad`, `TestFP16OptimizerForMoE::test_lamb_gradnorm[True]`, `TestUnfused::test_no_overflow`, `TestUnfused::test_some_overflow` | pass (verified) | | `misc` | 1 case: `TestOtherOptimizerCheckpoint::test_checkpoint_unfused_optimizer` | pass (verified) | | inference quantization | 12 `TestQuantizedInt` cases | the reported `NotImplementedError` failure point is fixed; all 12 pass locally on CANN 9.0.1; CI runs CANN 9.0.0, which provides `aclnnLeftShifts`. | No test is skipped or disabled to clear the jobs. On the base commit these cases fail on Ascend; with this branch the NPU code paths they exercise are implemented. ## Test plan **Local validation environment:** 2 × Ascend 910B4 per run (4 logical devices available); npu-smi 25.5.1 / CANN 9.0.1 (conda `ascend-cann-toolkit` + `ascend-cann-910b-ops` 9.0.1, enabled with `$CONDA_PREFIX/Ascend/cann/set_env.sh`); Python 3.10.21; torch 2.10.0+cpu; torch_npu 2.10.0.post7+git51c843b. Distributed tests use `pytest --forked` and `world_size=2`. **CI environment:** the three Ascend workflows (`deepspeed-upstream-ci.yml`, `deepspeed-upstream-ci-all.yml`, `deepspeed-compile.yml`) use the floating `swr.cn-southwest-2.myhuaweicloud.com/base_image/ascend-ci/cann:latest` image. The 2026-11-09 image reports `ascend_cann version 9.0.0` in `ds_report` (torch 2.10.0, torch_npu 2.10.0.post7), so `aclnnLeftShifts` is available. None of the workflows asserts the CANN version. The model-based tests load `facebook/opt-125m` from the local Hugging Face cache. The runs below set `HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1`; without offline mode the hub check dominates the runtime. ### 1. Fused LAMB — 6 passed (132.72 s) ```bash cd tests/unit ASCEND_RT_VISIBLE_DEVICES=0,1 python -m pytest -q --forked \ runtime/half_precision/test_fp16.py::TestLambFP16::test__basic \ runtime/half_precision/test_fp16.py::TestLambFP16::test_empty_grad \ 'runtime/half_precision/test_fp16.py::TestFP16OptimizerForMoE::test_lamb_gradnorm[True]' \ runtime/half_precision/test_dynamic_loss_scale.py::TestUnfused::test_no_overflow \ runtime/half_precision/test_dynamic_loss_scale.py::TestUnfused::test_some_overflow \ checkpoint/test_other_optimizer.py::TestOtherOptimizerCheckpoint::test_checkpoint_unfused_optimizer ``` Result: `6 passed, 1 warning`. ### 2. Quantizer cases on CANN 9.0.1 — 12 passed (405.90 s) Run with `ASCEND_RT_VISIBLE_DEVICES=2,3`, `HF_HUB_OFFLINE=1`, `TRANSFORMERS_OFFLINE=1`, `--forked`: <details> <summary>Exact command</summary> ```bash cd tests/unit HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 ASCEND_RT_VISIBLE_DEVICES=2,3 \ python -m pytest -q --tb=short --forked \ 'inference/quantization/test_intX_quantization.py::TestQuantizedInt::test_half_int4_quantization' \ 'inference/quantization/test_intX_quantization.py::TestQuantizedInt::test_half_int8_quantization' \ 'inference/quantization/test_intX_quantization.py::TestQuantizedInt::test_quantized_linear[4bits-1]' \ 'inference/quantization/test_intX_quantization.py::TestQuantizedInt::test_quantized_linear[8bits-1]' \ 'inference/quantization/test_intX_quantization.py::TestQuantizedInt::test_zero3_int4_post_init_quant[4bits]' \ 'inference/quantization/test_intX_quantization.py::TestQuantizedInt::test_zero3_int4_post_init_quant[8bits]' \ 'inference/quantization/test_intX_quantization.py::TestQuantizedInt::test_zero3_int4_post_init_quant_cpu_offload[4bits]' \ 'inference/quantization/test_intX_quantization.py::TestQuantizedInt::test_zero3_int4_post_init_quant_cpu_offload[8bits]' \ 'inference/quantization/test_intX_quantization.py::TestQuantizedInt::test_zero3_int4_quantized_initialization[4bits]' \ 'inference/quantization/test_intX_quantization.py::TestQuantizedInt::test_zero3_int4_quantized_initialization[8bits]' \ 'inference/quantization/test_intX_quantization.py::TestQuantizedInt::test_zero3_int4_quantized_initialization_cpu_offload[4bits]' \ 'inference/quantization/test_intX_quantization.py::TestQuantizedInt::test_zero3_int4_quantized_initialization_cpu_offload[8bits]' ``` </details> Result: **12 passed** (405.90 s) on CANN 9.0.1. Before the CANN upgrade, the six int4 cases stopped in the shared packer on 8.5.1; with 9.0.1 they run end to end. The six int8 cases pass in both environments. After adding the version guard, the six int4 cases were re-run on CANN 9.0.1: **6 passed** (205.64 s). With the cached check forced to unsupported, the entry point raises the new `RuntimeError`; the supported path returns the expected `(2, 8)` fp16 result for a small input. ### 3. Full `TestQuantizedInt` suite — 18 passed, 2 skipped (581.48 s) Same environment and command shape as above, with `-k TestQuantizedInt`. The two skipped cases are the NVMe variants (`test_zero3_int4_post_init_quant_nvme_offload` and `test_zero3_int4_quantized_initialization_nvme_offload`), skipped because async-io is not compatible on this NPU build. ### 4. Dequantizer numerical parity An ad-hoc NPU script compared each new fast path against the generic `_decompress_uint4_to_uint8` + `_dequantize_int8` path. For int4 and int8 at group sizes 32 and 64, on shapes `(768, 768)`, `(3072, 768)`, `(128, 128)`, and `(32768, 64)`, the two paths are **bitwise identical**; mean absolute error versus the original fp16 tensors is 0.0039–0.0758, below the suite's 0.15/0.5 thresholds. The int4 inputs for this check come from the same shared packer on CANN 9.0.1; no workaround or repository change is involved. ### 5. Lint `pre-commit run --files op_builder/npu/fused_lamb.py op_builder/npu/quantizer.py` passes every hook except flake8, which aborts in this environment before linting with `AttributeError: module 'ast' has no attribute 'Str'` on unmodified files as well. Running flake8 7.4.1 from the project environment directly on the two files reports no issues. ## Duplicate-work check GitHub issue/PR search (the GitHub issues search API, since `gh` is not installed in this environment) on 2026-11-09 found no open PR or issue for either defect: - No open PR/issue for the NPU fused LAMB in-place failure. - No open PR/issue for `dequantize_int4_to_half_experimental` / `dequantize_int8_to_half_experimental` on Ascend. - Related but not duplicate: deepspeedai#8995 fixes quantized storage of nontrainable weights in ZeRO-3 (a different code path); deepspeedai#8777 is a backend-pluggable low-precision training RFC; deepspeedai#8627 (closed) introduced the NPU FusedLamb/Quantizer builders that this PR repairs. ## Follow-ups (out of scope) - Supporting CANN builds older than 9.0.0 for int4 inference quantization would require a shared-packer fallback (common code) or a CANN upgrade; CI already runs 9.0.0, so this is not needed for the CI fix. This PR intentionally leaves common code untouched and only documents the requirement (see "CANN version note"). - Apply the same `torch.no_grad()` guard to the SUPA pure-torch fused LAMB fallback once SUPA hardware is available to validate it. - Re-run these suites on CUDA to confirm the NPU-only changes do not affect other accelerators (they are not imported there). - The two NVMe offload variants remain skipped until async-io is compatible on Ascend. ## Compliance with the repo AI-contribution policy ([`AGENTS.md`](https://github.com/deepspeedai/DeepSpeed/blob/master/AGENTS.md)) - **Duplicate work:** checked as described above; this is a bug fix for code introduced in deepspeedai#8627, not a new feature. - **On-device validation:** the LAMB and quantizer suites were executed on Ascend 910B4 with CANN 9.0.1; commands, hardware, software versions, and results are listed in the test plan. All 12 affected quantization cases pass locally; CI runs CANN 9.0.0. CUDA and SUPA could not be run here. - **Numerics / performance / memory:** the new dequantizers are bitwise identical to the generic reference path; no new kernel or persistent buffer is introduced. No common code is changed. - **Compatibility matrix:** validated cells and gaps are listed under "Compatibility, numerics, and memory". - **AI assistance:** this PR was prepared with the assistance of AI coding agents. The submitting human has reviewed every changed line and run the tests above. --------- Signed-off-by: Venus-Tzz <1601677496@qq.com>
Thanks for the question — happy to clarify. This PR fixes the existing MixZ++/qwZ training path: frozen LoRA base weights are quantized only in their ZeRO-3 partitions to reduce training memory and all-gather traffic, then dequantized back to fp16/bf16 before the normal GEMM. So the base weights are not kept quantized for inference, and this flag does not provide inference acceleration. That would need a separate weight-only quantization / quantized inference path. |
Thanks for clarification. Is this training path a production scenario you or your team aim to enhance? @sfc-gh-truwase for this potential use case. |
Thanks for the question. While reading experience-sharing posts, I noticed many customers in vertical industries have limited compute, but their current models cannot handle their specific business scenarios, so they plan to use SFT/LoRA to fine-tune a base model for those use cases and also want to build in-house LLM fine-tuning capability. Some of them go with DeepSpeed because it's a fully open-source framework. That led me to audit DeepSpeed's NPU support for this path and fix it here; the same defects reproduce on A100. |
b6a5b28 to
63371e4
Compare
dd44f79 to
9d19c0f
Compare
|
Hi @VenusTZZ , here are the comments, can you take a look? Thanks! 1. One creation point, and a home for the quantizer adapter
No behavior change is intended — it returns the same object. 2. Tests:
|
Thanks for the patient, detailed review, really appreciate you taking the time. I'll address these shortly. |
There was a problem hiding this comment.
🟡 Changes recommended
Quantized-weight handling defects break uneven-size gathers and checkpoint restore/export, while NPU asymmetric parameters are incompatible with CUDA.
3 open issues
What changed in this PR
This PR addresses #8990 by correcting quantized storage and retrieval of frozen weights in ZeRO-3, supporting LoRA fine-tuning with lower weight-storage memory.
Changes:
- Quantizes partitions after copying weights and updates single-rank and coalesced fetch handling.
- Centralizes quantization checks across primary and secondary partitions, including NVMe exclusions.
- Extends NPU quantization with int4/asymmetric support and half-to-even rounding, with regression tests.
| File | Description |
|---|---|
tests/unit/v1/zero/test_quantized_nontrainable.py |
Adds storage, fetch, repartition, post-init freezing, and secondary-partition tests. |
tests/unit/ops/quantizer/test_quantize.py |
Adds accelerator-independent int4/int8 rounding checks. |
op_builder/npu/quantizer.py |
Adds asymmetric quantization, packed int4 support, and half-to-even rounding. |
deepspeed/runtime/zero/utils.py |
Adds shared storage detection and quantization eligibility helpers. |
deepspeed/runtime/zero/stage3.py |
Reuses quantization helpers and skips NVMe-backed storage. |
deepspeed/runtime/zero/partitioned_param_coordinator.py |
Classifies fetch buckets by the active partition’s quantization status. |
deepspeed/runtime/zero/partition_parameters.py |
Updates quantization timing, padding, quantizer access, and fetch reconstruction. |
deepspeed/checkpoint/zero_affine.py |
Uses the shared quantized-storage check for affine-map rejection. |
Review effort: Balanced
| if all(quantized) and not quantize: | ||
| # Quantized storage cannot be gathered as full-precision weights; | ||
| # use the quantized path and dequantize when the handle completes. | ||
| quantize = True |
| tensor.data = quantized_storage | ||
| setattr(tensor, QUANT_SCALE_ATTR, scale) |
| offset = q_min - minv * scale | ||
| xg.mul_(scale).add_(offset).round_().clamp_(q_min, q_max) |
9d19c0f to
cf7fa4f
Compare
|
Hi @VenusTZZ , thanks for following up, let me know when this PR is ready for review again. Thanks! |
|
@codex review this pr |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ed9eb2ba98
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
1d6cb79 to
35cbbd7
Compare
- Quantize frozen partitions only after the real weights are copied in. - Share one quantizer adapter and keep CPU/NVMe-offloaded and non-int8-groupable partitions unquantized. - Handle all-quantized coalesced buckets and document the fp16 and offload boundaries. - Save dequantized frozen fragments in checkpoints and re-quantize them on load. - Add the ZeRO-3 regression and quantizer contract tests. Signed-off-by: Venus-Tzz <1601677496@qq.com>
35cbbd7 to
4da809a
Compare
Hi @delock, thanks for the patient review — this PR is ready for another review. Changes since your review:
Validation: tests/unit/v1/zero/test_quantized_nontrainable.py 9/9 on 2x A100-SXM4-80GB (103.70 s) and 9/9 on 2x Ascend |


Fixes #8990
Summary
Fix the
zero_quantized_nontrainable_weightspath (int8 storage of frozen weights, used by LoRA + ZeRO-3).deepspeed/runtime/zero/weight_quantizer.py.ZeROWeightQuantizeris a module-level singleton, so the no-gather handles used on single-rank runs and the post-init path share the same adapter (AttributeError: type object 'Init' has no attribute 'quantizer_module').Init.quantizer_moduleis removed;CUDAQuantizerremains as an import-compatible alias.elems_per_groupwhenever group counts differ (silent on CUDA, divisibility assertion on NPU). Also cast the fetched weights toparam.dtype, not the int8 storage dtype. The per-param dequantize stays in the fp16 wire dtype because a quantized bucket may mix parameter dtypes, and fully padded partitions are zeroed before the bucket re-quantize so uninitialized padding cannot feed the shared group scale.zero_to_fp32exports could not recover the frozen weights. Checkpoints written by the old code now raise a clear error instead of loading codes as weights.Extend
NPUQuantizerto the int4/asymmetric contract and round half to even, matching the CUDA kernel (__float2int_rn).quantizenow packs int4 two per byte;dequantizeaccepts N-D packed inputs and asymmetric params; the reference test intests/unit/ops/quantizer/test_quantize.pycovers int8/int4, symmetric/asymmetric. Production hpZ/qgZ continue to use symmetric int8. The half-to-even change is adapted from Round to nearest in NPUQuantizer, matching the CUDA quantizer #8764 (author: vineethsaivs).Review follow-up
deepspeed/runtime/zero/weight_quantizer.pywith a module-level singleton. The new module does not importpartition_parametersand does not load the op at import time.weight_quantizer.py,ZeROWeightQuantizer,get_weight_quantizer) so they are not confused with the training-quantization backends underdeepspeed/runtime/quantization/.CUDAQuantizertoZeROWeightQuantizerandquantizer_cuda_moduletobackend_module, keepingCUDAQuantizer = ZeROWeightQuantizerfor import compatibility.partition_parameters.pyto re-export the quantizer names andstage3.pyto importget_weight_quantizerfrom the new module.returns withpytest.skip, then moved the >=2-rank cases to@pytest.mark.world_size(2)so standard 2-rank runs execute them instead of stopping at ws=1.zero_quantized_nontrainable_weightsconfig key.Files changed
deepspeed/runtime/engine.pydeepspeed/runtime/zero/weight_quantizer.pyInit.quantizer_moduledeepspeed/runtime/zero/partition_parameters.pydeepspeed/runtime/zero/utils.pydeepspeed/runtime/zero/stage3.pyget_weight_quantizerfrom the new module; make the fp16 assertion self-explanatorydeepspeed/runtime/zero/partitioned_param_coordinator.pydeepspeed/checkpoint/zero_affine.pyop_builder/npu/quantizer.pytests/unit/ops/quantizer/test_quantize.pytests/unit/v1/zero/test_quantized_nontrainable.py@pytest.mark.world_size(2)tests/unit/runtime/zero/test_zeropp.pybackend_modulerename in the quantizer test doubledocs/_pages/config-json.mdzero_quantized_nontrainable_weightsin the JSON snippet and parameter referencedocs/_tutorials/mixed_precision_zeropp.mdMotivation
zero_quantized_nontrainable_weightsis the option that makes LoRA fine-tuning cheap in ZeRO-3: frozen base weights are stored as int8 and dequantized on fetch. On master the option is effectively unusable:mean(label**2), and gradients are zero -- no error is raised. On NPU the same path later fails even harder: a second fetch leaks int8 storage into matmul and raisesTensor mat2 not implemented for DT_INT8.The rounding change addresses a separate but related accuracy issue in the same quantizer: truncation biases int4 qgZ gradients low (sum ~0.85 of the exact value in a 2x2 CPU simulation), while the CUDA kernel rounds.
Testing
35cbbd70(the only change since then is a code comment): the full 9-case file passes (103.70 s), and the ZeRO++ and quantizer regressions pass.The NPU matrix below was collected on the functional revision, before the review-only refactor. The A100 suite was rerun on
35cbbd70, which includes the checkpoint fix and its test; the only later change is a code comment. The per-step timing was measured on the Qwen3-0.6B configuration before the review-only refactor (the guard/test changes do not affect the timed path).The end-to-end scripts live outside the repository. They are device-agnostic through
get_accelerator()and were run unchanged on both devices.In-repo regression test
tests/unit/v1/zero/test_quantized_nontrainable.py(new; 9 cases, world sizes 1 and 2 plus two single-device helper tests):@pytest.mark.world_size(2)and run directly at 2 ranks; the helper cases cover unsupported sizes, CPU-offloaded storage, and the NVMe skip predicate.world_size < 2skip caused theDistributedTestharness to end the class's world-size loop at ws=1 and report 4 passed + 3 skipped without reaching ws=2; the marker version removes that gap.AssertionError: quantized storage is all zeros. The checkpoint round-trip case fails without the save/load fix (_check_quantized_partitionbounds are exceeded after reload).load_module_state_dict(..., fetch_z3_params=True)(the repartition path used when loading a checkpoint); asave_checkpoint/load_checkpointround trip into a freshly seeded model, which checks both the restored weights and their new scales; the single-rank no-gather path; rejection of a directly mixed quantized/non-quantized bucket; and the CPU/NVMe/size skip predicates.tests/unit/v1, so the PR-level v1 workflow selects it.python ci/tests_fetcher.py --base origin/masterreturns modeall(becauseop_builder/npu/quantizer.pyis a shared file) and selectstests/unit/v1, which includes the new test.Review-follow-up validation
pytest tests/unit/runtime/zero/test_zeropp.py -k "zero_hpz_small_param_secondary_shard_without_overlap or zero_hpz_secondary_shard_padding_is_zeroed" -q --forked -n 4-> 2 passed.pytest tests/unit/runtime/zero/test_zeropp.py -k "not cuda_quantizer_round_trips_parameter_dtype" -q --forked -n 4-> 3 passed.py_compileon the changed Python files andcodespellpass. Theflake8pre-commit hook hits a pre-existing pyflakesast.Strenvironment bug; runningflake8directly reports only findings that already exist on master (F811inengine.py, twoF824inpartition_parameters.py).35cbbd70(the only change since then is a code comment): the >=2-rank cases use@pytest.mark.world_size(2), and the standard run reports 9 passed (103.70 s), including the checkpoint round trip and the CPU-offload/size helper test. NPU on the current head reports 9 passed (227.88 s).A100 validation on final HEAD
Environment: 2x NVIDIA A100-SXM4-80GB (GPUs 1 and 5), driver 580.126.16, CUDA 12.6, torch 2.14.1+cu126, Python 3.10.22. Tested head
35cbbd70; the current head differs only by a code comment.pytest tests/unit/v1/zero/test_quantized_nontrainable.py -v --forked(2 ranks)pytest tests/unit/runtime/zero/test_zeropp.py -v(no--forked; CUDA cannot re-initialize in a forked subprocess)pytest tests/unit/ops/quantizer/test_quantize.py -m inference_opsdeepspeed.runtime.zero.weight_quantizerCUDAQuantizer is ZeROWeightQuantizer,get_weight_quantizer()returns one process-wide instanceThe four cases that need at least two ranks use
@pytest.mark.world_size(2), so the standard 2-rank run executes them directly: mixed-bucket rejection, default gather dequantization, hpZ partitioning, and the checkpoint round trip. The earlier runtime-skip version reported 4 passed + 3 skipped because the harness ended the class's world-size loop at ws=1 without reaching ws=2.Fix verification on the same A100 host:
Parameter(10)initializes successfully and its partition stays unquantized, so the int8 grouping assertion is no longer reachable.offload_param.device=cpu, the frozenw1.ds_tensorremainscpu / float16 / pinnedwith nods_quant_scale, and trainable parameters stay on CPU; parameter offload semantics are preserved.Unit tests
tests/unit/v1/zero/test_quantized_nontrainable.py35cbbd70, 103.70 s; current head differs only by a comment)tests/unit/checkpoint/test_zero_affine.pytests/unit/ops/quantizer/test_quantize.pytest_zeropp.py::TestZeroPPConfigSweep(hpZ, 4 ranks)test_zero_autocast_mixed_dtype.py+test_zero_allreduce_fetch_params.py+ non-sequentialtest_zeropp.pyNotes on
test_quantize.py:inference_ops, sopytest.inideselects them when the command is run verbatim; use-m "inference_ops or not inference_ops".NPUQuantizer.quantizenow covers int4 (two per byte) and asymmetric scale+zero point, so the full 242-case matrix runs on NPU as well as CUDA.QuantizerBuilder(quantizefor int8,swizzle_quantfor int4), so they run against CUDA or NPU without importing a platform module.torch.round(x / scale), allowing only a one-code difference at an exact half-step boundary; truncation and non-boundary differences still fail.test_quantize.pycases carryinference_ops.nv-inferenceruns that marker, but its PR path filter does not includeop_builder/npu/quantizer.pyortests/unit/ops/quantizer/**; the v1 PR workflow collects onlytests/unit/v1. They therefore run manually/nightly, not in this PR's v1 job. The v1 regression test above is the PR-blocking one.Per-step timing
NPU 910B4 x2, Qwen3-0.6B (random init, seed 0), seq length 128, micro-batch 2, 20 steps per run, first 5 steps treated as warmup, 15 measured steps. Same model, data, and seed for both arms.
The new bucket dequantize/re-quantize path costs about 5% step time at this size (2.2666 vs 2.1577 s, -4.8% tok/s), while init-allocated memory drops by about 285 MiB/rank and training peak by about 281 MiB/rank. Step 1 of each run is much slower (~23 s) because it includes lazy compilation/initialization; it is excluded by the 5-step warmup.
Before / after on master
Observable failure modes on master versus this branch; each row maps to one defect.
quantized storage is all zerosAttributeError: type object 'Init' has no attribute 'quantizer_module'Real-model training, GPU vs NPU
Qwen3 models + PEFT LoRA (r=8 on q/k/v/o), 2 ranks, 20 steps on a fixed text batch. Both devices build the model from config only (
--random-init, seed 0), so no weights need to be downloaded; loss is comparable across devices but not to a pretrained model. The GPU real-model rows are from the functional revision; the final-HEAD A100 rerun covers unit tests and import checks.The NPU also ran the same three models with pretrained weights: init allocated 1,307 / 1,600, 1,845 / 2,608 and 2,952 / 4,840 MiB, identical frozen storage, and losses 0.932 -> 0.021 / 0.863 -> 0.001 / 0.718 -> 0.003 (control 0.934 -> 0.015 / 0.883 -> 0.000 / 0.705 -> 0.001). The storage and memory numbers agree with the random-init runs within 1-8 MiB.
Not tested
stage3.quantize_nontrainable_params()still asserts fp16, so the post-init bf16 workflow remains out of scope.ds_secondary_tensor(_partition_param_sec): the hpZ case asserts that the secondary storage is quantized, but does not check its values separately; the forward comparison covers the primary path.Compatibility and risk
zero_quantized_nontrainable_weightsusers on CUDA and NPU get correct storage instead of zeros; single-rank and multi-param buckets start working.zero_quantized_weights), autocast communication and the general fetch path are unchanged when the flag is off; the regression suites above pass.RuntimeError; the engine splits such buckets before coalescing.quantize=Falseis not honored for it. Internal engine callers are unaffected because they split buckets by quantization status before coalescing.zero_to_fp32and reloads see real weights and the load path re-quantizes them with scales recomputed from the saved values. Checkpoints written by the old code stored int8 codes without scales; loading one now raises a clear error instead of silently treating the codes as weights. This does not drop a usable artifact: under the old code the init path stored zeros, and the post-init path never persisted a scale.Notes for review
Checklist
pre-commiton all changed files (yapf/codespellpass; theflake8hook hits the pre-existing pyflakesast.Strenvironment bug, and directflake8reports only pre-existing findings)tests/unit/ops/quantizer/test_quantize.py