Repository navigation
Conversation
48fe936 to
f0305ff
Compare
Codex Review SummaryThis 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. |
Quantize each partition after the real weights are copied in, dequantize existing quantized storage before repartitioning, and assign the quantizer on Init so single-rank no-gather fetches can dequantize. For coalesced fetches, dequantize each parameter with its own scale and re-quantize the bucket uniformly; materialize quantized buckets in the parameter dtype, reject mixed quantized/non-quantized buckets, and zero only uncovered secondary-partition padding. Add a ZeRO-3 regression covering storage, coalesced fetch, checkpoint repartition, single-rank fetch, and mixed-bucket rejection. Signed-off-by: Venus-Tzz <1601677496@qq.com>
Implement int4 packing, asymmetric scale/zero-point handling, and round-half-to-even matching the CUDA kernel. Update the quantizer tests to derive expected codes from the kernel scale and allow only boundary ULP differences. Signed-off-by: Venus-Tzz <1601677496@qq.com>
The quantizer rebinds ds_tensor to an accelerator tensor. NVMe partitions point into the swapper buffer, so swap-out would persist the original fp16 values while ds_quant_scale remains attached; the next swap-in would dequantize those bytes as int8. Keep NVMe partitions unquantized, matching the pre-change behavior. Signed-off-by: Venus-Tzz <1601677496@qq.com>
Detect quantized storage and choose the active partition through shared helpers, so the async coordinator, coalesced fetch, single-rank no-gather, checkpoint and stage3 paths cannot disagree about whether a parameter is quantized. Share the frozen-storage quantize/dequantize steps and the NVMe exception between the primary and secondary partition paths, and reuse the same exception in quantize_nontrainable_params(). Reject an all-quantized coalesced bucket when quantize=False instead of gathering int8 codes as weights. Cover the post-init LoRA entry point, the hpZ secondary partition and the NVMe policy in the regression tests. Signed-off-by: Venus-Tzz <1601677496@qq.com>
b6a5b28 to
63371e4
Compare
Route the dequantize/quantize calls in _partition_param through get_quantizer(), matching the no-gather and post-init LoRA paths, and add a regression test that exercises the NVMe skip from quantize_nontrainable_params(). Signed-off-by: Venus-Tzz <1601677496@qq.com>
When every parameter in a coalesced bucket holds quantized storage, a caller that does not pass quantize=True currently gets a RuntimeError. Select the quantized gather path in that case and dequantize when the handle completes, so default gathers return full-precision weights. Mixed buckets keep raising. Add a regression test for the default gather path. Signed-off-by: Venus-Tzz <1601677496@qq.com>
Signed-off-by: Venus-Tzz <1601677496@qq.com>
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. |
Fixes #8990
Summary
The change has two parts:
Fix three device-agnostic defects in the
zero_quantized_nontrainable_weightspath (int8 storage of frozen weights, used by LoRA + ZeRO-3).Initclass so the no-gather handles used on single-rank runs can dequantize (AttributeError: type object 'Init' has no attribute 'quantizer_module').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.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).Files changed
deepspeed/runtime/zero/partition_parameters.py(+73/-32)op_builder/npu/quantizer.py(+70/-58)tests/unit/ops/quantizer/test_quantize.py(+64)tests/unit/v1/zero/test_quantized_nontrainable.py(new, +155)Motivation
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
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, world sizes 1 and 2):pytest tests/unit/v1/zero/test_quantized_nontrainable.py -q --forked-> 2 passed (both world sizes; storage/repartition and mixed-storage rejection), 86.61s.f568548b, whose tree is identical to the final squashed headf0305ff4c.test_quantize_rounds_to_nearest[4]and[8]passed after the boundary-test change; the other 240 cases are unchanged from the previously green full matrix.AssertionError: quantized storage is all zeros.load_module_state_dict(..., fetch_z3_params=True)(the repartition path used when loading a checkpoint); the single-rank no-gather path; and rejection of a directly mixed quantized/non-quantized bucket. The test skips when the quantizer op is unavailable.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.Unit tests
tests/unit/v1/zero/test_quantized_nontrainable.pytests/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.pre-commitpasses on all changed files in the NPU environment.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 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.stage3.quantize_nontrainable_params()(the post-init re-quantize workflow) is not exercised by the in-repo test.ds_secondary_tensor(_partition_param_sec) has no targeted quantization test; the hpZ suites cover the primary path.save_checkpoint/load_checkpointround trip is covered by the external Qwen3 script; the in-repo test usesload_module_state_dict(..., fetch_z3_params=True).Compatibility and risk
zero_quantized_nontrainable_weightsusers on CUDA 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.Notes for review
Checklist
pre-commiton all changed files (passes in the NPU environment)tests/unit/ops/quantizer/test_quantize.py(NPU 242 passed; A100 rounding cases [4]/[8] passed on the final tree)