Repository navigation
[NPU] Fix the fused LAMB step and inference int4/int8 dequantization on Ascend - #9043
Merged
Merged
Conversation
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]>
VenusTZZ
requested review from
hwchen2017,
loadams,
tjruwase and
tohtana
as code owners
November 9, 2026 09:41
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. |
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
marked this pull request as draft
November 9, 2026 09:45
VenusTZZ
force-pushed
the
fix-npu-lamb-and-intx-quant
branch
from
November 9, 2026 10:09
322fb7a to
41a7a28
Compare
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
marked this pull request as ready for review
November 9, 2026 12:50
Contributor
Author
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep them coming! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
sfc-gh-truwase
approved these changes
Nov 9, 2026
delock
enabled auto-merge
November 10, 2026 08:57
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
This fixes two runtime defects in the Ascend NPU op builders added by #8627:
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 withp_copy.copy_(p.data);p_copyis a leaf parameter that requires grad.NotImplementedError: experimental fp_quantizer path is not needed for hpZ.DeQuantizer.dequantizetakes 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:
p_copyisout_p, an fp16 parameter taken fromself.fp16_groups. It is a leaf tensor withrequires_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 == 0num_bitsis 4 or 8torch.float16All of them hold for fp16 inference weights on Ascend, so the dispatcher calls
get_quantizer_module().dequantize_int4_to_half_experimental(...)ordequantize_int8_to_half_experimental(...). Both Ascend entry points were stubs:The fp32 cases in the same suite pass because
dtype == torch.float16is false; they fall through to the generic_decompress_uint4_to_uint8+_dequantize_int8path. 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=1QuantizedLinearcases, 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_uint4uses a uint8 left shift, which CANN provides asaclnnLeftShiftsfrom 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-ops9.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
aclnnLeftShiftsis provided by CANN 9.0.0 and later. Both environments satisfy this: local validation runs CANN 9.0.1, and CI uses the floatingswr.cn-southwest-2.myhuaweicloud.com/base_image/ascend-ci/cann:latestimage, whose 2026-11-09ds_reportoutput reportsascend_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:
No runtime gate is added:
torch.bitwise_left_shiftis the interface and dispatches toaclnnLeftShiftsdirectly, 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/UINT64inputs, a scalarshiftBits, non-contiguous tensors, and support on Atlas A2/A3/350 products. The 910B4 is an Atlas A2 device; the packer's input isuint8in[0, 15]and the shift amount is the scalar4, within the documented precision guarantee (shiftBitsbelow 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.npu_convert_weight_to_int4pack[-8, 7], low nibble first, 8 values perint32torch_npu.npu_quantize(..., dtype=torch.quint4x2)int32outputtorch_npu.npu_anti_quantDeepSpeed inference stores unsigned
[0, 15]values, high nibble first, two peruint8. Reusing the torch_npu APIs would require nibble swapping and a-8offset, 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)Only the copy is wrapped; the rest of the update stays outside
no_grad. The other in-place operations inlamb()(onexp_avg,exp_avg_sq, andp.data) were checked: the state tensors do not require grad, andp.data.copy_already bypasses autograd.Inference dequantizers (
op_builder/npu/quantizer.py)Both entry points now implement the asymmetric inference formula
value / scale + minin pure torch: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 inuint8while unpacking and only then converts to fp16, so the temporary is one byte per element rather than the eight bytes anint64unpack 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 usestorch_npu.npu.utils._is_gte_cann_version("9.0.0", module="CANN")when available and falls back to parsingtorch_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 aRuntimeErrorwith 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
op_builder/supa/fused_lamb.py:62) has the samep_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.NotImplementedError.deepspeed/inference/quantization/utils.pyis unchanged; the int4 packer limitation is documented above rather than patched here.Compatibility, numerics, and memory
no_gradcontext around one copy.CI impact
The failing cases are part of the existing unit-test shards, not new tests:
runtimeTestLambFP16::test__basic,TestLambFP16::test_empty_grad,TestFP16OptimizerForMoE::test_lamb_gradnorm[True],TestUnfused::test_no_overflow,TestUnfused::test_some_overflowmiscTestOtherOptimizerCheckpoint::test_checkpoint_unfused_optimizerTestQuantizedIntcasesNotImplementedErrorfailure point is fixed; all 12 pass locally on CANN 9.0.1; CI runs CANN 9.0.0, which providesaclnnLeftShifts.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-ops9.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 usepytest --forkedandworld_size=2.CI environment: the three Ascend workflows (
deepspeed-upstream-ci.yml,deepspeed-upstream-ci-all.yml,deepspeed-compile.yml) use the floatingswr.cn-southwest-2.myhuaweicloud.com/base_image/ascend-ci/cann:latestimage. The 2026-11-09 image reportsascend_cann version 9.0.0inds_report(torch 2.10.0, torch_npu 2.10.0.post7), soaclnnLeftShiftsis available. None of the workflows asserts the CANN version.The model-based tests load
facebook/opt-125mfrom the local Hugging Face cache. The runs below setHF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1; without offline mode the hub check dominates the runtime.1. Fused LAMB — 6 passed (132.72 s)
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
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
TestQuantizedIntsuite — 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_offloadandtest_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_int8path. 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.pypasses every hook except flake8, which aborts in this environment before linting withAttributeError: 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
ghis not installed in this environment) on 2026-11-09 found no open PR or issue for either defect:dequantize_int4_to_half_experimental/dequantize_int8_to_half_experimentalon Ascend.Follow-ups (out of scope)
torch.no_grad()guard to the SUPA pure-torch fused LAMB fallback once SUPA hardware is available to validate it.Compliance with the repo AI-contribution policy (
AGENTS.md)