Skip to content

Fix quantized storage of nontrainable weights in ZeRO-3 - #8995

Open
VenusTZZ wants to merge 7 commits into
deepspeedai:masterfrom
VenusTZZ:fix-zero-quantized-nontrainable-weights
Open

VenusTZZ wants to merge 7 commits into
deepspeedai:masterfrom
VenusTZZ:fix-zero-quantized-nontrainable-weights

Conversation

@VenusTZZ

@VenusTZZ VenusTZZ commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #8990

Summary

The change has two parts:

  1. Fix three device-agnostic defects in the zero_quantized_nontrainable_weights path (int8 storage of frozen weights, used by LoRA + ZeRO-3).

    • Quantize the partition only after the real weights have been copied in. Previously the code quantized an uninitialized buffer and then overwrote it with a dtype-cast copy of fp16/bf16 weights, truncating values in (-1, 1) to zero in the int8 storage. The model silently output zeros and the loss never moved.
    • Assign the quantizer on the Init class so the no-gather handles used on single-rank runs can dequantize (AttributeError: type object 'Init' has no attribute 'quantizer_module').
    • In coalesced buckets whose params carry their own quantized storage, dequantize each param with its own scale and re-quantize the bucket uniformly. A flat dequantize with concatenated per-param scales computes a wrong elems_per_group whenever group counts differ (silent on CUDA, divisibility assertion on NPU). Also cast the fetched weights to param.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.
    • Reject direct coalesced fetches that mix quantized and non-quantized parameters instead of silently choosing one storage layout from the first parameter. The engine already splits such buckets before coalescing.
  2. Extend NPUQuantizer to the int4/asymmetric contract and round half to even, matching the CUDA kernel (__float2int_rn). quantize now packs int4 two per byte; dequantize accepts N-D packed inputs and asymmetric params; the reference test in tests/unit/ops/quantizer/test_quantize.py covers 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_weights is 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:

  • Frozen weights are all zeros in storage, with a scale derived from uninitialized memory. Training runs, the loss is 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 raises Tensor mat2 not implemented for DT_INT8.
  • Single-rank runs crash immediately.
  • Multi-parameter buckets either corrupt values or assert, depending on backend.

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

  • NPU: Ascend 910B4, CANN 8.5.1, torch 2.10.0, torch_npu 2.10.0.post7, transformers 4.57.6, peft 0.20.0.
  • GPU: 2x A100-SXM4-80GB (cards 4/5), driver 580.126.16, torch 2.14.1+cu126, CUDA 12.6 (nvcc 12.4), Python 3.10.22, transformers 4.57.6, peft 0.21.2.

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

  • Branch, NPU: pytest tests/unit/v1/zero/test_quantized_nontrainable.py -q --forked -> 2 passed (both world sizes; storage/repartition and mixed-storage rejection), 86.61s.
  • Branch, GPU: 2 passed (A100-SXM4-80GB, world sizes 1 and 2). This run used f568548b, whose tree is identical to the final squashed head f0305ff4c.
  • Branch, GPU, quantizer: 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.
  • The storage/repartition case fails on master with AssertionError: quantized storage is all zeros.
  • Coverage: init storage and dequantization inside the group-scale bound; forward output against a plain-torch reference; the coalesced-bucket fetch after backward; the ZeRO-3 state-dict load through 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.
  • It lives under tests/unit/v1, so the PR-level v1 workflow selects it. python ci/tests_fetcher.py --base origin/master returns mode all (because op_builder/npu/quantizer.py is a shared file) and selects tests/unit/v1, which includes the new test.

Unit tests

Test NPU GPU
tests/unit/v1/zero/test_quantized_nontrainable.py 2 passed (both world sizes; storage/repartition + mixed-storage guard) 2 passed (A100-SXM4-80GB; final tree)
tests/unit/checkpoint/test_zero_affine.py 27 passed 27 passed (4 GPUs; 2 GPUs skip 4 AutoTP cases)
tests/unit/ops/quantizer/test_quantize.py 242 passed (full matrix, 30.18s) 242 passed (previous revision); changed rounding cases [4]/[8] passed on the final tree
test_zeropp.py::TestZeroPPConfigSweep (hpZ, 4 ranks) 9 passed (4 cards) 9 passed
test_zero_autocast_mixed_dtype.py + test_zero_allreduce_fetch_params.py + non-sequential test_zeropp.py 8 passed 8 passed

Notes on test_quantize.py:

  • Every case is marked inference_ops, so pytest.ini deselects them when the command is run verbatim; use -m "inference_ops or not inference_ops".
  • The file is device-agnostic and collects on NPU. NPUQuantizer.quantize now covers int4 (two per byte) and asymmetric scale+zero point, so the full 242-case matrix runs on NPU as well as CUDA.
  • The new rounding cases use the accelerator-resolved QuantizerBuilder (quantize for int8, swizzle_quant for int4), so they run against CUDA or NPU without importing a platform module.
  • CUDA's reciprocal scale differs from the torch reference by 1-2 ULP. The test compares scales with a small tolerance and compares kernel codes with torch.round(x / scale), allowing only a one-code difference at an exact half-step boundary; truncation and non-boundary differences still fail.
  • CI note: the test_quantize.py cases carry inference_ops. nv-inference runs that marker, but its PR path filter does not include op_builder/npu/quantizer.py or tests/unit/ops/quantizer/**; the v1 PR workflow collects only tests/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-commit passes 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.

Check master this branch
Regression test (storage case) fails: quantized storage is all zeros passes
Qwen3-0.6B frozen storage 0% non-zero 98.8% non-zero
Single rank AttributeError: type object 'Init' has no attribute 'quantizer_module' passes
Multi-param coalesced bucket int8 cast error on NPU / wrong group sizes on CUDA passes

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.

Model Arm Init GPU / NPU (MiB/rank) Peak GPU / NPU (MiB/rank) Frozen storage (B/rank) Loss GPU Loss NPU
Qwen3-0.6B (596.0M frozen) quantized 1,251 / 1,308 3,468 / 3,579 298,273,412 12.418 -> 6.359 12.257 -> 6.044
fp16 control 1,557 / 1,603 3,774 / 3,871 596,049,920 12.422 -> 6.247 12.262 -> 5.880
Qwen3-1.7B (1,720.6M frozen) quantized 1,789 / 1,845 5,041 / 6,207 860,955,972 12.249 -> 0.042 12.230 -> 0.036
fp16 control 2,608 / 2,608 5,864 / 5,989 1,720,574,976 12.236 -> 0.027 12.246 -> 0.039
Qwen3-4B (4,022.5M frozen) quantized 2,921 / 2,951 7,091 / 8,534 2,012,639,940 12.881 -> 0.024 12.302 -> 0.010
fp16 control 4,839 / 4,840 9,047 / 9,102 4,022,468,096 12.871 -> 0.016 12.319 -> 0.009
  • All quantized runs: 310/310 int8 partitions on 0.6B and 1.7B, 398/398 on 4B, 98.8% non-zero on both devices.
  • Init-allocated savings (quantized vs control): GPU 306 / 819 / 1,918 MiB, NPU 295 / 763 / 1,889 MiB. The frozen storage itself halves at every size, and the byte counts are identical across devices.
  • Training peak is lower with quantization in every GPU run. On NPU the 1.7B peak is 218 MiB higher (6,207 vs 5,989) because peak includes the fp16 all-gather buffers and bucket re-quantize transients; treat peak as workload-dependent, and init-allocated/storage as the stable savings.
  • 0.6B checkpoint (8 steps): GPU replay 8.1402, NPU replay 8.1354 (step 7 repeats step 5); both ALL PASS. Frozen storage is zeroed before the load, so the continuation proves restoration.
  • The coalesced-bucket re-quantize path runs repeatedly (quantize counter +9 per step on 0.6B, +42 per step on 1.7B).

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

  • Pretrained weights on GPU: the GPU real-model runs use random-init weights. Storage and memory metrics match the NPU pretrained-weight runs; loss values are not comparable to a pretrained model.
  • bf16 and fp32 storage: not validated. stage3.quantize_nontrainable_params() still asserts fp16, so the post-init bf16 workflow remains out of scope.
  • Parameter offload behavior is unchanged by this PR; CPU/NVMe combinations are not covered.
  • Padding: the in-repo test does not construct partial or fully padded partitions; those audit fixes are validated by inspection and the end-to-end runs, not by a targeted regression case.
  • stage3.quantize_nontrainable_params() (the post-init re-quantize workflow) is not exercised by the in-repo test.
  • hpZ ds_secondary_tensor (_partition_param_sec) has no targeted quantization test; the hpZ suites cover the primary path.
  • Full save_checkpoint/load_checkpoint round trip is covered by the external Qwen3 script; the in-repo test uses load_module_state_dict(..., fetch_z3_params=True).
  • Cross-world-size checkpoint loading, TP/PP, and accelerators other than A100 and 910B4.

Compatibility and risk

  • No API signature, config, or checkpoint format change.
  • zero_quantized_nontrainable_weights users on CUDA get correct storage instead of zeros; single-rank and multi-param buckets start working.
  • hpZ (zero_quantized_weights), autocast communication and the general fetch path are unchanged when the flag is off; the regression suites above pass.
  • Parameter offload behavior is unchanged by this PR.
  • A direct coalesced fetch that mixes quantized and non-quantized parameters now raises RuntimeError; the engine splits such buckets before coalescing.
  • Existing quantized checkpoints: storage produced by the old code was all zeros and unusable, so no compatible checkpoint exists to preserve.

Notes for review

  • The three storage defects are described in [BUG] zero_quantized_nontrainable_weights corrupts frozen weights and crashes ZeRO-3 fetches #8990.
  • The chosen fix keeps the existing wire format and quantizer. The bucket path mirrors the on-the-fly hpZ bucket logic that is already exercised in production.
  • AI assistance was used to develop this change and its test harness. The human submitter reviewed every changed line and ran the GPU validation above.
  • Standalone reproducers and verification scripts can be provided on request; they live outside the repository (hardware-specific test harness).

Checklist

  • pre-commit on all changed files (passes in the NPU environment)
  • In-repo regression test (fails on master; 2 cases pass on NPU and A100 at world sizes 1 and 2)
  • Quantizer contract tests (int8/int4, symmetric/asymmetric) in tests/unit/ops/quantizer/test_quantize.py (NPU 242 passed; A100 rounding cases [4]/[8] passed on the final tree)
  • End-to-end validation of the storage fix on NPU (1 and 2 ranks) and CUDA (A100, 1 and 2 ranks)
  • Multi-rank LoRA + ZeRO-3 training on Qwen3-0.6B/1.7B/4B (pretrained weights on NPU, random-init weights on GPU)
  • CUDA hardware validation (A100: unit tests, Qwen3 real-model runs)

@VenusTZZ
VenusTZZ force-pushed the fix-zero-quantized-nontrainable-weights branch 2 times, most recently from 48fe936 to f0305ff Compare November 6, 2026 08:11
@VenusTZZ
VenusTZZ marked this pull request as ready for review November 6, 2026 08:25
@chatgpt-codex-connector

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

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-06T08:31:23.613913Z f0305ff 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.

@VenusTZZ

VenusTZZ commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@delock

delock commented Nov 10, 2026

Copy link
Copy Markdown
Collaborator

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!

@VenusTZZ
VenusTZZ force-pushed the fix-zero-quantized-nontrainable-weights branch from 7b25758 to fe8aaab Compare November 10, 2026 09:30
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>
@tohtana tohtana added the needs-gpu-test GPU testing is recommended to validate the changes in this PR. label Nov 10, 2026
@VenusTZZ

Copy link
Copy Markdown
Contributor Author

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!

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.

@delock

delock commented Nov 11, 2026

Copy link
Copy Markdown
Collaborator

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!

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.

@VenusTZZ

VenusTZZ commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor Author

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!

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>
@VenusTZZ
VenusTZZ force-pushed the fix-zero-quantized-nontrainable-weights branch from b6a5b28 to 63371e4 Compare November 12, 2026 12:55
@tohtana tohtana removed the needs-gpu-test GPU testing is recommended to validate the changes in this PR. label Nov 14, 2026
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>
@VenusTZZ
VenusTZZ force-pushed the fix-zero-quantized-nontrainable-weights branch from dd44f79 to 9d19c0f Compare November 17, 2026 02:50
@delock

delock commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator

Hi @VenusTZZ , here are the comments, can you take a look? Thanks!

1. One creation point, and a home for the quantizer adapter

get_quantizer() introduced a second creation point next to Init.quantizer_module = CUDAQuantizer() (partition_parameters.py:1165), and nine call sites still read self.quantizer_module. They all live in the same file, so please consolidate in this PR:

  • New deepspeed/runtime/zero/quantizer.py holding the adapter and get_quantizer(), with a module-level singleton instead of Init.quantizer_module. The module must not import partition_parameters, and must not load the op at import time.
  • Rename while moving: CUDAQuantizer → AcceleratorQuantizer, quantizer_cuda_module → backend_module, keeping CUDAQuantizer = AcceleratorQuantizer for import compatibility — tests/unit/runtime/zero/test_zeropp.py:16 imports the class and :69 monkeypatches the module attribute by name.
  • partition_parameters.py imports from the new module and re-exports both names; stage3.py:31 imports get_quantizer from the new module.
  • Delete Init.quantizer_module and the eager assignment; Init.__init__ just calls get_quantizer().
  • Replace the nine self.quantizer_module reads (:1166, :1435, :1450, :1503, :1505, :1511, :1524, :2113, :2173) with get_quantizer().

No behavior change is intended — it returns the same object.

2. Tests: return → pytest.skip

Four cases in tests/unit/v1/zero/test_quantized_nontrainable.py do if world_size < 2: return. With world_size = [1, 2] those runs report green at world size 1 without asserting anything. Please use pytest.skip("requires >= 2 ranks").

3. bf16: make the limitation visible

The init path silently casts bf16 to fp16 inside CUDAQuantizer.quantize, while quantize_nontrainable_params() asserts fp16 and fails with a bare assertion. Please:

  • add a line to docs/_tutorials/mixed_precision_zeropp.md saying the option requires an fp16 base model (bf16/fp32 are not supported), and
  • make the assertion in quantize_dstensor explain itself, e.g. zero_quantized_nontrainable_weights requires fp16 partitions, got {tensor.dtype}.

4. Document the config key

docs/_pages/config-json.md lists zero_quantized_weights, zero_quantized_gradients and zero_hpz_partition_size, but not zero_quantized_nontrainable_weights. Since this PR is what makes the option usable, please add it to the JSON snippet and to the parameter reference.

5. PR description: one new contract for direct callers

For direct calls to all_gather_coalesced, a bucket that mixes quantized and non-quantized parameters now raises, and a fully quantized bucket is forced through the quantized path (so quantize=False is not honored). Internal callers are unaffected. Please state this in the description.


6. Per-step timing (request, non-blocking)

_all_gather_coalesced now dequantizes every partition and re-quantizes the whole bucket on each fetch. That is the right call given per-parameter scales, but it is a new per-step cost (N dequantize + one bucket quantize per quantized bucket), and the PR reports memory but not time.

Please add a per-step timing comparison with zero_quantized_nontrainable_weights on and off — same model, same seed, same step count, averaged over a few steps. One model size is enough to establish the order of magnitude. This can land before merge or as a follow-up; I would not block on it.

Review based on code reading; I did not run the distributed tests locally.

@VenusTZZ

Copy link
Copy Markdown
Contributor Author

Hi @VenusTZZ , here are the comments, can you take a look? Thanks!

1. One creation point, and a home for the quantizer adapter

get_quantizer() introduced a second creation point next to Init.quantizer_module = CUDAQuantizer() (partition_parameters.py:1165), and nine call sites still read self.quantizer_module. They all live in the same file, so please consolidate in this PR:

  • New deepspeed/runtime/zero/quantizer.py holding the adapter and get_quantizer(), with a module-level singleton instead of Init.quantizer_module. The module must not import partition_parameters, and must not load the op at import time.
  • Rename while moving: CUDAQuantizer → AcceleratorQuantizer, quantizer_cuda_module → backend_module, keeping CUDAQuantizer = AcceleratorQuantizer for import compatibility — tests/unit/runtime/zero/test_zeropp.py:16 imports the class and :69 monkeypatches the module attribute by name.
  • partition_parameters.py imports from the new module and re-exports both names; stage3.py:31 imports get_quantizer from the new module.
  • Delete Init.quantizer_module and the eager assignment; Init.__init__ just calls get_quantizer().
  • Replace the nine self.quantizer_module reads (:1166, :1435, :1450, :1503, :1505, :1511, :1524, :2113, :2173) with get_quantizer().

No behavior change is intended — it returns the same object.

2. Tests: return → pytest.skip

Four cases in tests/unit/v1/zero/test_quantized_nontrainable.py do if world_size < 2: return. With world_size = [1, 2] those runs report green at world size 1 without asserting anything. Please use pytest.skip("requires >= 2 ranks").

3. bf16: make the limitation visible

The init path silently casts bf16 to fp16 inside CUDAQuantizer.quantize, while quantize_nontrainable_params() asserts fp16 and fails with a bare assertion. Please:

  • add a line to docs/_tutorials/mixed_precision_zeropp.md saying the option requires an fp16 base model (bf16/fp32 are not supported), and
  • make the assertion in quantize_dstensor explain itself, e.g. zero_quantized_nontrainable_weights requires fp16 partitions, got {tensor.dtype}.

4. Document the config key

docs/_pages/config-json.md lists zero_quantized_weights, zero_quantized_gradients and zero_hpz_partition_size, but not zero_quantized_nontrainable_weights. Since this PR is what makes the option usable, please add it to the JSON snippet and to the parameter reference.

5. PR description: one new contract for direct callers

For direct calls to all_gather_coalesced, a bucket that mixes quantized and non-quantized parameters now raises, and a fully quantized bucket is forced through the quantized path (so quantize=False is not honored). Internal callers are unaffected. Please state this in the description.

6. Per-step timing (request, non-blocking)

_all_gather_coalesced now dequantizes every partition and re-quantizes the whole bucket on each fetch. That is the right call given per-parameter scales, but it is a new per-step cost (N dequantize + one bucket quantize per quantized bucket), and the PR reports memory but not time.

Please add a per-step timing comparison with zero_quantized_nontrainable_weights on and off — same model, same seed, same step count, averaged over a few steps. One model size is enough to establish the order of magnitude. This can land before merge or as a follow-up; I would not block on it.

Review based on code reading; I did not run the distributed tests locally.

Thanks for the patient, detailed review, really appreciate you taking the time. I'll address these shortly.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] zero_quantized_nontrainable_weights corrupts frozen weights and crashes ZeRO-3 fetches

3 participants