Repository navigation
fix(int8): keep checkpoint group scales in the CPU INT8 layout - #3804
Conversation
TorchInt8Linear re-quantized the decoded GPTQ matrix to one symmetric scale per output channel. A GPTQ checkpoint is group-quantized, so a per-channel scale must cover the largest group and every code in a smaller group truncates toward zero. With two groups 1024x apart the small group became exactly 0 and its contribution vanished (32.03125 -> 32.0 on the reported fixture). Keep the checkpoint's own numerics instead of quantizing a second time: - Decode the GPTQ codes and zero points directly and store them as [group, out_features, group_width] signed residuals `code - 128`, one row per quantization group. No FP32 weight matrix is materialized during transform_cpu any more. - Reuse the checkpoint's per-group `scales` rows. Symmetric checkpoints need no zero operand at all; asymmetric ones keep a per-(group, output) additive offset instead of a packed zero tensor. - Sort input channels into group order once and keep that permutation, so the executor still issues one kernel launch per group. `g_idx` order is arbitrary, so this is required for contiguity. - Pad and mask a ragged last group (in_features not divisible by group_size) with zero activation columns. - Accumulate the groups in FP32 and round once, after the optional bias. Fusion now concatenates the output axis of the group codes, group scales, and offsets. It requires every sibling to share the activation permutation and the offset presence, so hybrid symmetric/asymmetric groups are rejected instead of mis-bound. `_dequantize_group_layout` reconstructs the checkpoint matrix bit-exactly for export and for the oracle. Measured on an 8-bit Qwen2.5-0.5B GPTQ checkpoint: per-layer runtime output is bit-exact against the checkpoint decode, and the kernel's arithmetic error against that fp64 decode is 2.1e-4 -- the same as BACKEND.TORCH. The old per-channel layout was 7.9e-3 relative on the weights, 1.6e-3 on layer outputs per layer, and 3.0e-1 versus 8.5e-2 on full-model logits (with the greedy argmax preserved only by the group layout). Docs: docs/torch-int8-checkpoint-lifecycle.md now carries the before/after table, the new flow diagram, measured storage, and the contract limits.
- Resolve negative g_idx entries to the last group once, then use the normalized tensor for both the group counts and the channel permutation. Previously -1 was counted in the last group but sorted first, silently permuting the runtime weight rows. - Reconstruct dequantized rows per group instead of truncating the flat [G*W, N] layout, so empty and non-trailing ragged groups keep their exact bounds in dequantize_weight()/export. - Add regression coverage and document the normalization contract.
|
Reviewed the group-preserving layout; the kernel math is sound, but two layout paths could silently corrupt weights. Pushed
Added Validation: int8 kernel + bias tests 54 passed (also under |
|
Reviewed current head [P2] Apply asymmetric zero-point cancellation before the independent FP32 reductions. In I reproduced this through
These are arithmetic errors, not unavoidable low-precision output rounding: zero is exactly representable in all three dtypes. Even scaling the same random activations by 100 instead of 10000 gives maximum errors of 0.00634765625 / 0.00390625 / 0.00537109375 respectively, exceeding the repository's 0.002 absolute tolerance. The packed fixture can be constructed without a quantizer: Please use a numerically stable asymmetric path that applies the zero-point subtraction before reducing, or otherwise demonstrate a correction strategy that meets the decoded-weight oracle bound. A bounded temporary decode is one possible fallback; a retained dense cache is unnecessary. Add a cancellation regression with zero and near-zero decoded weights across FP16/BF16/FP32. Validation on CPU / Torch |
Int8PackedModule accumulated scale * (code - 128) per group and then added scale * (128 - zero). For an asymmetric checkpoint both terms are large and independently rounded, so their cancellation left a residue even when every decoded weight was exactly zero (FP16 0.3125, BF16 0.25, FP32 0.5 on the reported fixture). Symmetric sources keep the native INT8 op. Asymmetric sources now decode a bounded [tile, width] weight tile with the checkpoint's integer code - zero applied per element, reduce it in FP32, and release the tile. No dense weight is retained between forwards. Adds zero-weight and one-code-residual regressions across FP16/BF16/FP32 and documents the split arithmetic path.
|
Confirmed the P2 and fixed it in Root cause. Fix. Symmetric sources ( Regressions added in
Validation on this host: Requesting a re-review of |
TL;DR
TorchInt8Linearno longer re-quantizes a decoded GPTQ matrix to one symmetricscale per output channel. It keeps the checkpoint's own per-group scales and
zero points, so the runtime layout is a lossless repack: a group whose scale is
1024x smaller than a sibling's no longer rounds to zero. Net diff: 12 files,
+655/-178, concentrated in
gptqmodel/nn_modules/qlinear/torch_int8.py.1. The problem
The CPU INT8 kernel decoded the GPTQ checkpoint into an FP32 matrix and then ran
a second quantization:
GPTQ scatters channels across groups with independent scales, so one output
channel can mix a large group and a tiny one. The per-channel scale must cover
the largest group and every code in the smaller group truncates to zero.
flowchart TD A["GPTQ qweight, qzeros, scales, g_idx"] --> B["_dequantize_gptq_source_weight"] B --> C["FP32 matrix W[k, n]"] C --> D["channel_scale = per-output-channel absmax / 127"] D --> E{"small group representable at that scale?"} E -->|no| F["codes round to 0; group contribution lost"] E -->|yes| G["Int8PackedModule"] F --> G classDef failure fill:#ffe8e8,stroke:#b30000,color:#111 class F failure_requantize_to_int8per-channel absmaxgptqmodel/nn_modules/qlinear/torch_int8.py:40-54(pre-PR)int8_channel_scalebuffertorch_int8.py:24,:79-82(pre-PR)transform_cputorch_int8.py:320-324(pre-PR)Reported reproduction (two groups 1024x apart inside one output channel): the
exact weight reference is
0.03125for the small group's contribution and theper-channel layout produced
0. Reproduced here as32.03125 -> 32.0on thesame structure, with the small group's codes round to zero.
2. The new flow
flowchart TD A["GPTQ qweight, qzeros, scales, g_idx"] --> B["transform_cpu"] B --> E{"exactly one g_idx entry per input channel?"} E -->|no| X["NotImplementedError"] E -->|yes| F["decode codes and zeros directly; no FP32 matrix"] F --> P["_group_layout: _group_layout counts, stable argsort permutation"] P --> G["_write_group_buffers: residual code-128, checkpoint group scales, optional offset, permutation"] G --> H["_bind_int8_runtime: Int8PackedModule aliases buffers"] H --> I["_fused_op_forward"] I --> R["_refresh_int8_runtime"] R --> Q{"source signature matches?"} Q -->|yes| O["Int8PackedModule.forward: one launch per group, FP32 accumulate, one rounding, bias epilogue"] Q -->|no| B C["persistent GPTQ source buffers"] --> S["get_state_dict_for_save"] S --> V["serialize original GPTQ checkpoint"] M["source edit, load, device move, explicit clear"] --> I classDef failure fill:#ffe8e8,stroke:#b30000,color:#111 class X failureNumerically, with
cthe checkpoint code (signed residualr = c - 128) ands_g,z_gthe checkpoint group scale and zero point:The first term is exactly what
aten::_weight_int8pack_mmcomputes with thecheckpoint's own
s_g; the second is a per-(group, output) additive offset thatis identically zero for symmetric GPTQ (not stored) and a small
[G, N]termotherwise. Because the codes are the checkpoint's integers, no re-quantization
happens at all —
dequantize_weight()is bit-exact against the checkpoint.Channels are sorted into group order once (
int8_input_perm). This is required:g_idxorder is arbitrary in real checkpoints (measured:[1, 4, 5, 3, 5, 6, ...]on layer 0 of an 8-bit Qwen2.5 checkpoint), so a group's channels are not
contiguous in the checkpoint. Permuting activations is exact for an
integer-coded dot product.
int8_weight_nk[N, K]int8_weight_gnk[G, N, W]int8_channel_scale[N]int8_group_scale[G, N]int8_group_offset[G, N]int8_input_perm[K][N, K]codes on axis 0[G, N, W]codes and[G, N]metadata on axis 1Fusion additionally rejects siblings whose activation permutations or group
offset presence differ, since the executor permutes once and concatenates a
single offset operand.
3. Contract limits
g_idxentry per input channel; otherwiseNotImplementedError(never silently mis-index).
after conversion or any forward; the FP32 conversion matrix is gone.
4. Tests / guarantees
test_native_int8_group_layout_output_and_storage_oracle(-1,16,32,64,128x 3 dtypes)dequantize_weight()is bit-exact; kernel stays inside the FP32-reduction boundtest_native_int8_layout_preserves_a_small_group_inside_a_large_channeltest_native_int8_ragged_last_group_keeps_exact_weightsin_features=100, group=32pads the last group without a phantom biastest_cpu_int8_group_scale_range_spread,test_cpu_int8_zero_point_offset_is_appliedtest_native_int8_checkpoint_save_strict_reload_and_oracletest_native_int8_runtime_refreshes_after_checkpoint_change,..._inference_tensor_edit_requires_explicit_cleartest_native_fusion_shapes_oracle_ownership_and_invalidation[...]test_native_int8_cold_refresh_builds_once_across_threads5. Validation
CPU, non-GPU host, free-threaded Python 3.14t / Torch 2.15.0+cu132:
pytest tests/kernels/test_torch_int8.py tests/test_int8_bias_cancellation.pypytest tests/module_treepytest tests/kernels/test_inference_numeric_range.py tests/test_quant_module_device.pypytest tests/module_tree/test_fusion_kernel_backends.pyPYTHON_GIL=0 pytest tests/kernels/test_torch_int8.py tests/test_int8_bias_cancellation.pytests/kernels/test_torch_int8.pyon unmodifiedafde8d7d2tests/kernels/test_gptq.pyon unmodifiedafde8d7d2No CUDA GPUs are available(pre-existing, unrelated)Branch rebased onto
afde8d7d2(includes #3796's fusion lifecycle refactor); allresults above were re-measured on that rebase.
Real checkpoint (
viveksil/Qwen2.5-0.5B-Instruct-gptqmodel-8bit, group 128):full-model logits vs
BACKEND.TORCH, 4-token prompt, fusion disabled:grouped
rel 8.5e-2,argmaxequal; the old per-channel layoutrel 3.0e-1,argmaxdiffers. Per-layer runtime output is bit-exact against the checkpointdecode and the kernel's error against that fp64 decode is
2.1e-4.Measured storage, 512x64 fixture, group 128, no bias: checkpoint 35,584 B;
grouped runtime 37,888 B (codes unchanged;
+group scale rows and the int64permutation); previous per-channel 33,024 B; dense cache 0.
Benchmark (
tests/benchmark/benchmark_int8_storage_migration.py, 512x512,group 128): grouped matches the ATen int4 reference (
visible_gatetrue,raw_relative 7.5e-5) where the per-channel layout misses (7.4e-3). Groupedcosts 1.0-1.3x the single-call kernel; the old path was 4.5x faster only because
it measured the wrong numerics.
6. Reviewer notes
~1.2x at M=1 and ~1.0x at M>=64 on 4096x4096 with 128 groups (measured on this
host). Keeping the checkpoint semantics is the point of the change; the old
number was faster because it computed a different matrix.
existing ATen op plus per-(group, output) corrections, so it works on every
CPU build that already had this backend. A fused grouped-scale C++ kernel
would recover the small-M overhead and can follow separately.
in_features % group_size != 0now works via padding; theold code silently trained on a truncated matrix.
int8_weight_nk/int8_channel_scaleare derived,non-persistent layout names;
INT8_SCALE_BUFFER_NAMEremains an alias soimporters see the group scale. No checkpoint format changed.
docs/torch-int8-checkpoint-lifecycle.mdcarries the same diagrams,before/after table, measured storage, and contract limits;
README.mdanddocs/fusion-planner.mdwere updated where they described the old layout.