Skip to content

[NPU] Fix the fused LAMB step and inference int4/int8 dequantization on Ascend - #9043

Merged
delock merged 4 commits into
deepspeedai:masterfrom
VenusTZZ:fix-npu-lamb-and-intx-quant
Nov 10, 2026
Merged

delock merged 4 commits into
deepspeedai:masterfrom
VenusTZZ:fix-npu-lamb-and-intx-quant

Conversation

@VenusTZZ

@VenusTZZ VenusTZZ commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This fixes two runtime defects in the Ascend NPU op builders added by #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:

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:

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)

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:

@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)

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:

Exact command
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]'

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:

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)

  • Duplicate work: checked as described above; this is a bug fix for code introduced in Implement FusedLion, FusedLamb, and Quantizer ops for NPU accelerator #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.

The Ascend fused LAMB implementation mirrors 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, so PyTorch rejects the in-place
operation and every fp16 LAMB step fails with

  RuntimeError: a leaf Variable that requires grad is being used in an
  in-place operation.

The copy only propagates the fp32 update into the fp16 parameter and
must not be recorded by autograd, so run it under torch.no_grad().

Verified on 910B4: TestLambFP16::test__basic, TestLambFP16::test_empty_grad,
TestFP16OptimizerForMoE::test_lamb_gradnorm[True],
TestUnfused::test_some_overflow, TestUnfused::test_no_overflow, and
TestOtherOptimizerCheckpoint::test_checkpoint_unfused_optimizer all pass
(6 passed).

Signed-off-by: Venus-Tzz <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-09T12:54:26.224052Z 47d9668 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

DeQuantizer.dequantize takes a fused fast path for fp16 weights whose
groups lie on the last dimension. The Ascend quantizer builder left both
entry points unimplemented, so every inference int4/int8 weight
dequantization raised NotImplementedError.

Implement dequantize_int4_to_half_experimental and
dequantize_int8_to_half_experimental in pure torch, following the
asymmetric per-group scale/minimum math of the generic path. The int4
helper unpacks two unsigned nibbles per byte without widening to int64,
so the temporary stays one byte per element.

The int4/int8 fast paths are bitwise identical to the generic dequantize
path across group sizes 32/64 and model-shaped tensors. The int8
TestQuantizedInt cases pass on 910B4; int4 end-to-end runs on this host
are blocked earlier by CANN 8.5.1 lacking aclnnLeftShifts in the shared
int4 packer, which is outside this change.

Signed-off-by: Venus-Tzz <[email protected]>
@VenusTZZ
VenusTZZ marked this pull request as draft November 9, 2026 09:45
@VenusTZZ
VenusTZZ force-pushed the fix-npu-lamb-and-intx-quant branch from 322fb7a to 41a7a28 Compare November 9, 2026 10:09
The inference int4 path packs with the shared uint8 left shift, which
CANN provides as aclnnLeftShifts from 9.0.0. The NPU dequantizers do not
use that operator, so they are version-independent; on older CANN the
failure happens during quantization, before they run.

Record the requirement in the NPUQuantizer docstring, including the
torch_npu version APIs that can query it. No runtime gate is added: the
failing step is in shared inference code, which this NPU-only change
leaves untouched.

Signed-off-by: Venus-Tzz <[email protected]>
The int4 inference path needs aclnnLeftShifts, which CANN provides from
9.0.0. Add a version guard to the Ascend int4 dequantizer so an
unsupported environment gets an actionable error instead of a generic
missing-operator failure.

The guard caches the version check, uses torch_npu's version API when
available, and falls back to parsing get_cann_version(). It fails open
when the version cannot be determined, leaving the normal error path.

Verified on CANN 9.0.1: the six int4 cases pass, and a simulated
pre-9.0 version raises the new RuntimeError.

Signed-off-by: Venus-Tzz <[email protected]>
@VenusTZZ
VenusTZZ marked this pull request as ready for review November 9, 2026 12:50
@VenusTZZ

VenusTZZ commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 47d9668263

ℹ️ 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".

@delock
delock enabled auto-merge November 10, 2026 08:57
@delock
delock added this pull request to the merge queue Nov 10, 2026
Merged via the queue into deepspeedai:master with commit f7a7177 Nov 10, 2026
23 checks passed
@VenusTZZ
VenusTZZ deleted the fix-npu-lamb-and-intx-quant branch November 10, 2026 11:08
@auto-pr-labeler-with-jev auto-pr-labeler-with-jev Bot added the skip-gpu-test Requires positive evidence that every changed behavior can be validated without a GPU. label Nov 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

skip-gpu-test Requires positive evidence that every changed behavior can be validated without a GPU.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants