Repository navigation
Implement FusedLion, FusedLamb, and Quantizer ops for NPU accelerator - #8627
Merged
Merged
Conversation
delock
reviewed
Sep 27, 2026
| @@ -0,0 +1,97 @@ | |||
| # Copyright (c) Microsoft Corporation. | |||
Collaborator
There was a problem hiding this comment.
Remove Microsoft copyright line. Follow https://github.com/deepspeedai/DeepSpeed/blob/master/AGENTS.md for new file license head
delock
reviewed
Sep 27, 2026
| @@ -0,0 +1,271 @@ | |||
| # Copyright (c) Microsoft Corporation. | |||
Collaborator
There was a problem hiding this comment.
same, remove Microsoft license head
delock
reviewed
Sep 27, 2026
| @@ -0,0 +1,72 @@ | |||
| # Copyright (c) Microsoft Corporation. | |||
Collaborator
There was a problem hiding this comment.
Same, remove Microsoft copyright head
Signed-off-by: Zizhao Tang <1601677496@qq.com>
Follow torch_npu's NpuFusedLamb form: replace the explicit two-step arithmetic with chained in-place ops. ~17% faster per step on 910B4 (128 params, 162M elems), numerically agreeing with the previous form to 1 ulp, and bit-identical exp_avg/exp_avg_sq vs torch_npu's NpuFusedLamb under equivalent semantics. Signed-off-by: Zizhao Tang <1601677496@qq.com>
Follow the same chained in-place form as NPUFusedLamb: ~26% faster per step on 910B4 (128 params, 162M elems), bitwise-identical to the previous explicit two-step form. Signed-off-by: Zizhao Tang <1601677496@qq.com>
Replace the where() scale guard with a masked fill and run the per-group quantize/dequantize math in place: 24-26% faster quantize on 1-8M-element tensors (the hpZ bucket range) and 8% faster dequantize on 910B4, bitwise-identical to the previous form. Signed-off-by: Zizhao Tang <1601677496@qq.com>
Signed-off-by: Zizhao Tang <1601677496@qq.com>
VenusTZZ
force-pushed
the
npu-zero-quantized-comm
branch
from
September 28, 2026 01:22
1bc2378 to
e172311
Compare
delock
approved these changes
Sep 28, 2026
delock
enabled auto-merge
September 28, 2026 01:24
Signed-off-by: Zizhao Tang <1601677496@qq.com>
auto-merge was automatically disabled
September 28, 2026 01:32
Head branch was pushed to by a user without write access
delock
enabled auto-merge
September 28, 2026 01:34
Contributor
Author
|
Thanks for reviewing and merging! Much appreciated. |
banxingmjj
pushed a commit
to openanolis/DeepSpeed
that referenced
this pull request
Nov 10, 2026
…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>
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.
Fixes #8626
Ships the NPU counterparts of the three op builders that #8054 added for SUPA in op_builder/supa/.
Summary
Adds op_builder/npu/fused_lion.py (NPUFusedLion), op_builder/npu/fused_lamb.py (NPUFusedLamb), and op_builder/npu/quantizer.py (NPUQuantizer + QuantizerBuilder), registered in op_builder/npu/init.py. Previously the three names resolved to NotImplementedBuilder on NPU, so "optimizer": {"type": "Lion"|"Lamb"} and zero_quantized_weights / zero_quantized_gradients all crashed at engine initialization with ValueError: This op had not been implemented on NPU backend. — reproduced on hardware.
All three are pure-torch stateless modules with the same interface shape as the SUPA backend (Add Biren SUPA accelerator support #8054) and the same per-parameter op contract as the CUDA kernels; nothing to compile, no kernel code.
The quantizer matches the Zero++ wire format bit for bit (truncation toward zero, clamp to [-2**(b-1), 2**(b-1)-1], stored 1/scale per group) and includes the qgZ int4 swizzle_quant / quantized_reduction pair (signed two's-complement nibble packing, two-stage all-to-all layout).
Implementation notes
NPUFusedLion implements the sign update with the c==0 -> +lr branch and multiplicative weight decay. NPUFusedLamb implements the full per-parameter semantics (trust ratio clamped by max/min coefficients, bias correction, both eps modes, zero-norm fallbacks).
Both use chained in-place updates, following torch_npu's NpuFusedLamb form: on 910B4 this is ~26% (Lion) / ~17% (Lamb) faster per step than the equivalent explicit two-step arithmetic (128 params, 162M elems). Lion agrees with the explicit form bitwise; Lamb agrees to 1 ulp, and its exp_avg/exp_avg_sq are bit-identical to torch_npu.optim.NpuFusedLamb under equivalent semantics (an independent cross-check).
NPUQuantizer covers quantize / dequantize / dequantize_fp32 for the hpZ int8 path and swizzle_quant / quantized_reduction for the qgZ int4 path. The int8/int4 types only ever appear as communication payloads (quantize -> move bytes -> dequantize); training compute stays fp16/bf16.
Docstrings record the native-operator upgrade points: torch_npu's npu_quantize family rounds half-to-even and exposes no truncation mode today, so a native kernel can be swapped in later without changing the contract.
Performance (Ascend 910B4, median of 5 runs, chained in-place vs the original explicit two-step form)
The optimizers are called per parameter, matching the per-parameter op contract of the CUDA kernels; quantize/dequantize timings cover the hpZ bucket size range. At 64M elements the quantize path is bandwidth-bound and the forms are equivalent (1.01x).
Validation on Ascend 910B4 (CANN 8.5.0, torch 2.9.0+cpu, torch_npu 2.9.0.post7, 4x Ascend 910B4, aarch64)
Test plan
Known limitation
fp32/fp64 division on Ascend is approximate (1 ulp off on ~5% of values), so the stored quantizer scales can differ from a correctly rounded computation by 1 ulp. This is bounded and safe: every rank in a run computes the same value, the 1-ulp scale error (~1e-7 relative) is five orders below the quantization error (~1e-2), and the wire format is transient (checkpoints store unquantized weights).