Skip to content

fix(int8): keep checkpoint group scales in the CPU INT8 layout - #3804

Merged
Qubitium merged 3 commits into
mainfrom
fix/int8-group-scale
Nov 13, 2026
Merged

Qubitium merged 3 commits into
mainfrom
fix/int8-group-scale

Conversation

@ZX-ModelCloud

Copy link
Copy Markdown
Collaborator

TL;DR

TorchInt8Linear no longer re-quantizes a decoded GPTQ matrix to one symmetric
scale 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:

channel_scale[n] = max_k |W[k, n]| / 127
code[k, n]       = round(W[k, n] / channel_scale[n])

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
Loading
Removed mechanism Where Consequence
_requantize_to_int8 per-channel absmax gptqmodel/nn_modules/qlinear/torch_int8.py:40-54 (pre-PR) Second quantization of an already-quantized checkpoint
int8_channel_scale buffer torch_int8.py:24, :79-82 (pre-PR) One scale per output channel, no group structure
FP32 decode + requantize in transform_cpu torch_int8.py:320-324 (pre-PR) Materialized full-layer FP32 matrix during conversion

Reported reproduction (two groups 1024x apart inside one output channel): the
exact weight reference is 0.03125 for the small group's contribution and the
per-channel layout produced 0. Reproduced here as 32.03125 -> 32.0 on the
same 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 failure
Loading

Numerically, with c the checkpoint code (signed residual r = c - 128) and
s_g, z_g the checkpoint group scale and zero point:

W[k, n]  = s_g * (c - z_g)
         = s_g * r + s_g * (128 - z_g)

The first term is exactly what aten::_weight_int8pack_mm computes with the
checkpoint's own s_g; the second is a per-(group, output) additive offset that
is identically zero for symmetric GPTQ (not stored) and a small [G, N] term
otherwise. 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_idx order 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.

Mechanism Before After
Runtime numerics per-output-channel requantization checkpoint codes + checkpoint group scales
Weight buffer int8_weight_nk [N, K] int8_weight_gnk [G, N, W]
Scale buffer int8_channel_scale [N] int8_group_scale [G, N]
Zero points absorbed by the per-channel scale signed residual + optional int8_group_offset [G, N]
Activation order input order int8_input_perm [K]
Ragged last group unsupported padded, zero activation columns
Reduction one kernel call one call per group, FP32 accumulate, one rounding
Fusion axes [N, K] codes on axis 0 [G, N, W] codes and [G, N] metadata on axis 1

Fusion 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

  • Exactly one g_idx entry per input channel; otherwise NotImplementedError
    (never silently mis-index).
  • 8-bit sources only; the retire-lower-bit guard is unchanged.
  • Runtime storage stays 8-bit codes + group scales. No dense weight is retained
    after conversion or any forward; the FP32 conversion matrix is gone.

4. Tests / guarantees

Test Invariant
test_native_int8_group_layout_output_and_storage_oracle (-1,16,32,64,128 x 3 dtypes) codes, group scales, offset, and permutation match an independent oracle; dequantize_weight() is bit-exact; kernel stays inside the FP32-reduction bound
test_native_int8_layout_preserves_a_small_group_inside_a_large_channel the reported 1024x case: grouped output keeps the small group, per-channel collapses it
test_native_int8_ragged_last_group_keeps_exact_weights in_features=100, group=32 pads the last group without a phantom bias
test_cpu_int8_group_scale_range_spread, test_cpu_int8_zero_point_offset_is_applied scale spread and asymmetric offsets
test_native_int8_checkpoint_save_strict_reload_and_oracle save/reload round-trip keeps the checkpoint bytes and the runtime oracle
test_native_int8_runtime_refreshes_after_checkpoint_change, ..._inference_tensor_edit_requires_explicit_clear cache invalidation on load/mutate/move/clear
test_native_fusion_shapes_oracle_ownership_and_invalidation[...] fusion oracle, no dense weights, unfuse restores sources
test_native_int8_cold_refresh_builds_once_across_threads free-threaded cold rebuild is serialized

5. Validation

CPU, non-GPU host, free-threaded Python 3.14t / Torch 2.15.0+cu132:

Command Result
pytest tests/kernels/test_torch_int8.py tests/test_int8_bias_cancellation.py 52 passed
pytest tests/module_tree 1414 passed, 779 skipped
pytest tests/kernels/test_inference_numeric_range.py tests/test_quant_module_device.py 238 passed, 59 skipped
pytest tests/module_tree/test_fusion_kernel_backends.py 55 passed, 135 skipped
PYTHON_GIL=0 pytest tests/kernels/test_torch_int8.py tests/test_int8_bias_cancellation.py 52 passed
tests/kernels/test_torch_int8.py on unmodified afde8d7d2 50 passed - the suite encodes the old per-channel contract, so it cannot catch this
tests/kernels/test_gptq.py on unmodified afde8d7d2 24 errors, all No CUDA GPUs are available (pre-existing, unrelated)

Branch rebased onto afde8d7d2 (includes #3796's fusion lifecycle refactor); all
results 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, argmax equal; the old per-channel layout rel 3.0e-1,
argmax differs. Per-layer runtime output is bit-exact against the checkpoint
decode 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 int64
permutation); 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_gate true,
raw_relative 7.5e-5) where the per-channel layout misses (7.4e-3). Grouped
costs 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

  • Speed. One kernel launch per group instead of one per layer. It costs
    ~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.
  • Deliberate scope. No new C++ kernel: the fix is expressible with the
    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.
  • Ragged groups. in_features % group_size != 0 now works via padding; the
    old code silently trained on a truncated matrix.
  • Buffer renames. int8_weight_nk / int8_channel_scale are derived,
    non-persistent layout names; INT8_SCALE_BUFFER_NAME remains an alias so
    importers see the group scale. No checkpoint format changed.
  • Docs. docs/torch-int8-checkpoint-lifecycle.md carries the same diagrams,
    before/after table, measured storage, and contract limits; README.md and
    docs/fusion-planner.md were updated where they described the old layout.

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.
@ZX-ModelCloud

Copy link
Copy Markdown
Collaborator Author

Reviewed the group-preserving layout; the kernel math is sound, but two layout paths could silently corrupt weights. Pushed 9a32884ff to fix them:

  • Negative g_idx: pack_block resolves -1 to the last group, and _group_layout counted it there, but transform_cpu sorted the raw tensor, so those rows were counted in the last group and sorted into the first. The counts and int8_input_perm now share one normalized tensor (also used by the source decode).
  • Ragged/empty groups: _dequantize_group_layout truncated the flat [G*W, N] layout at sum(lengths), which is only correct for a ragged last group. It now gathers each group's exact rows, so dequantize_weight()/export matches the forward.

Added test_native_int8_negative_g_idx_matches_checkpoint_decode and test_native_int8_dequantize_layout_handles_empty_and_ragged_groups, and updated the lifecycle doc.

Validation: int8 kernel + bias tests 54 passed (also under PYTHON_GIL=0), numeric-range/device tests 344 passed, fusion backend tests 156 passed / 34 skipped. Real 8-bit Qwen2.5-0.5B checkpoint: per-layer dequantize_weight() bit-exact vs the checkpoint decode, fused vs unfused logits identical, int8 vs BACKEND.TORCH rel 2.6e-3 with equal argmax. No other blocking issues found.

@ZX-ModelCloud
ZX-ModelCloud marked this pull request as ready for review November 13, 2026 03:48

Copy link
Copy Markdown
Collaborator

Reviewed current head 9a32884ff597debffdb2f83154880c94a25f1fe6 against afde8d7d2, including the negative-g_idx and ragged-group fixes already discussed.

[P2] Apply asymmetric zero-point cancellation before the independent FP32 reductions. In Int8PackedModule.forward, lines 237–243, the residual dot products are accumulated first, and the zero-point correction is computed separately using flat.sum(-1) and addmm. Their rounding errors survive cancellation even when the checkpoint weights are exactly zero.

I reproduced this through TorchInt8Linear.load_state_dict() → post_init() → forward with K=512, N=32, group_size=128, sym=False, every code and zero point equal to 255, FP16 scales equal to 0.01, no bias, and g_idx=arange(512)//128. The decoded matrix and independent FP64 reference are identically zero. For torch.manual_seed(42); x=(torch.rand(3,512)*10000).to(dtype), the new path's maximum absolute errors are:

Activation dtype Current head Base implementation
FP16 0.3125 0
BF16 0.25 0
FP32 0.5 0

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: qweight=torch.full((128,32), -1, dtype=torch.int32), qzeros=torch.full((4,8), -1, dtype=torch.int32), and scales=torch.full((4,32), 0.01, dtype=torch.float16). This isolates the new execution arithmetic from packing.

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 2.15.0.dev20260928+cu130: existing INT8 kernel and bias tests 54 passed; focused native INT8 fusion tests 6 passed under PYTHON_GIL=0. The base comparison executed its original requantizer and packed executor against the same decoded-zero matrix. No real-model benchmark was rerun.

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.

Copy link
Copy Markdown
Collaborator Author

Confirmed the P2 and fixed it in 0fb26a074.

Root cause. Int8PackedModule.forward reduced scale * (code - 128) per group and then added scale * (128 - zero) with addmm. Both terms are large and independently rounded, so their cancellation leaves a residue even when the decoded matrix is exactly zero. Reproduced with the reported fixture (K=512, N=32, group=128, sym=False, codes/zeros 255, scales 0.01, g_idx=arange(512)//128): max abs error 0.3125 / 0.25 / 0.5 for FP16/BF16/FP32 at x*10000, and 0.00634765625 / 0.00390625 / 0.00537109375 at x*100.

Fix. Symmetric sources (int8_group_offset is None) keep the native aten::_weight_int8pack_mm path unchanged. Asymmetric sources now reconstruct the checkpoint's integer code - zero per element before reducing: each group decodes a bounded [tile, width] FP32 weight tile (_INT8_ASYMMETRIC_DECODE_TILE = 256 output channels), multiplies it by the group scale, reduces in FP32, and releases the tile. No decoded weight is stored on the module or retained after the forward; persistent storage stays 8-bit codes plus group metadata. On the same fixture the output is now exactly 0.0 for all three dtypes at both activation magnitudes.

Regressions added in tests/kernels/test_torch_int8.py:

  • test_native_int8_asymmetric_zero_weights_cancel_exactly — zero decoded weights at zero points 255/200/129, FP16/BF16/FP32, x*10000 and x*100, asserts exact zero.
  • test_native_int8_asymmetric_near_zero_weights_meet_oracle — code - zero in {-1, 0, 1} against an independent FP64 decode; also asserts dequantize_weight() matches exactly.

Validation on this host: tests/kernels/test_torch_int8.py + tests/test_int8_bias_cancellation.py 66 passed (also PYTHON_GIL=0); focused native INT8 fusion tests 6 passed; INT8 numeric-range tests 8 passed. docs/torch-int8-checkpoint-lifecycle.md now documents the symmetric/asymmetric split arithmetic.

Requesting a re-review of 0fb26a074.

@Qubitium
Qubitium merged commit 31c26c9 into main Nov 13, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/int8-group-scale branch November 13, 2026 06:27
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.

2 participants