Skip to content

feat(nf12): add automatic source dtype casting - #3853

Merged
Qubitium merged 14 commits into
mainfrom
auto-nf12-dtype-cast
Nov 14, 2026
Merged

Qubitium merged 14 commits into
mainfrom
auto-nf12-dtype-cast

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

TL;DR

Add BaseQuantizeConfig.auto_dtype_cast, defaulting to AUTO_NF12, so eligible BF16-compatible source matrices use lossless NF12 storage during calibration forwards. Restore the exact original dtype and bits before GPTQ/AWQ/RTN consumes the source. The change also adds native row-major embedding storage and kernels on CUDA and ROCm, short-M linear dispatch tuning, and the corresponding flow documentation and tests.

The net change is 5,022 insertions and 293 deletions across 61 files. The core consequence is that the source can be packed during calibration without changing the bytes seen by the quantizer or retaining a dense source beside the packed representation.

1. Problem and old flow

Previously, every quantizable source matrix stayed dense during calibration. For BF16 source models this left the original weight resident while calibration forwards ran, even though NF12 can represent every BF16 bit exactly.

The old lifecycle was:

flowchart TD
    A["dense source module"] --> B["calibration forward"]
    B --> C["quantizer process"]
    C --> D["packed output"]
Loading

The feature must preserve the quantizer handoff while changing the storage used by calibration. The main risk is that a packed forward could leave GPTQ/AWQ with a decoded or altered source instead of the exact input matrix.

2. New flow

flowchart TD
    A["dense source module"] --> B{"auto_dtype_cast"}
    B -- "OFF" --> C["dense source"]
    B -- "AUTO_NF12" --> D{"native floatx path validated?"}
    D -- "yes" --> C
    D -- "no" --> E{"eligible matrix and device?"}
    E -- "no" --> C
    E -- "yes" --> F["cast_source_module"]
    F --> G["packed NF12 forward"]
    G --> H["quantization task metadata retained"]
    H --> I["restore_source_module"]
    I --> J["exact source dtype and bits"]
    J --> K["GPTQ / AWQ / RTN process"]
    C --> K
Loading

The source policy is selected by config, never by an environment variable. Native FP8/FP4/MXFP4/MXFP8 execution takes precedence. A decoded floatx view is eligible for NF12. BF16 is eligible when the matrix shape and device are supported. FP16 is eligible only when FP16 -> BF16 -> FP16 preserves every bit, including signed zero.

3. Storage and reduction contracts

  • NF12 matrix modules retain canonical 16-row super-atoms.
  • nf12.decode_fp32 and nf12_hip.decode_fp32 widen to FP32 in the decode store, so FP32 consumers never materialize a BF16 matrix.
  • Embedding modules persist the lookup-oriented row-major layout on supported CUDA and ROCm devices.
  • Norm vectors and biases remain dense.
  • The quantizer receives the original source dtype and exact bits before processing.
  • No dense or dequantized inference weight cache is retained between forwards.
  • SM89 and RDNA4 use measured pairwise reduction association; SM120 retains rank order because pairwise association measured worse there.
  • HookedLinear and AutoNF12HookedLinear share prepare_hooked_linear_input; W4A replay and online Hadamard run exactly once before the packed GEMM and calibration hook capture.
  • restore_source_module rebuilds hooked sources as HookedLinear and shares the registered-hook registries plus online-rotation and W4A replay state, so RemovableHandle.remove() affects source, packed, and restored modules consistently.

The storage and fallback flow is documented in Automatic NF12 source storage. Row-major embedding is documented in NF12 row-major embedding storage, HIP embedding dispatch in NF12 HIP embedding dispatch, reduction behavior in NF12 linear reduction association, and the M sweep in NF12 short-M dispatch.

4. Measured results

Lossless storage and numerical scope

NF12 storage and decoding are bit exact for BF16. Matrix multiplication is not generally bitwise identical because the NF12 kernels can associate FP32 partial sums differently from dense BF16 GEMM.

On RTX 4090, all 113/113 aligned projection weights restored bit exactly across 1,235,746,816 elements. Representative projection results were:

Projection Max absolute difference Mean absolute difference Bit exact
model.layers.0.self_attn.q_proj 0.0009765625 1.7003549146465957e-07 No
model.layers.0.mlp.down_proj 0.03125 1.4519027899950743e-05 No
lm_head 0.0 0.0 Yes

The full model retained identical next-token IDs, with maximum logits difference 0.21875 and mean absolute difference 0.023402199131775.

The Llama embedding table decoded bit exactly, and 512/512 sampled lookup rows matched dense BF16 exactly. Its row-major packed representation occupied 394,365,297 bytes instead of 525,336,576 bytes, a 24.93% reduction.

Quantization memory and warm timing

The model was unsloth/Llama-3.2-1B-Instruct, loaded as BF16. GPTQ calibration cast 112 projection matrices. Their dense BF16 source occupied 1,856.0 MiB; the NF12 representation occupied 1,394.532 MiB.

The current RTX 4090 comparison used GPTQ 4-bit, group size 128, 8 WikiText windows of 512 tokens (4,096 calibration tokens), the same BF16 source, and the same held-out 4,096-token evaluation split. Model load and checkpoint save were excluded from the quantization timer.

Metric AUTO_NF12 OFF
Cast projection modules 112 0
Resident allocation after module preparation 626.139 MiB 771.844 MiB
Calibration-forward phase peak 912.420 MiB 920.391 MiB
End-to-end peak allocation 1,458.342 MiB 1,458.342 MiB
Final allocated memory 254.1294 MiB 254.1294 MiB
Warm median quantization time 5.318339 s 5.500630 s

Resident allocation after preparation was 18.88% lower with AUTO_NF12. The end-to-end peak was equal because the cached 4K activation inputs and GPTQ workspace dominate it. Allocation history attributes the peak to a 512 MiB inverse factor, two 256 MiB damping/inverse temporaries, 64 MiB permutation storage, and additional quantization/activation buffers. With one 512-token block, the calibration-forward peak was 444.420 MiB with AUTO_NF12 and 681.783 MiB with OFF.

The first implementation copied each GPU weight to CPU, copied it back for native encoding, then copied the packed result to CPU and back to the GPU. It also allocated full zero NF12 buffers before overwriting them. That made 112 warm encodes take about 1.8 seconds and made AUTO_NF12 slower.

The encoder now consumes the accelerator-resident BF16 source and installs the native result on that device. Warm encoding took 0.118522 seconds for all 112 modules, or 0.079967 seconds after excluding the first seven shape specializations. Median warm encoding was 0.478 ms per module. Warm median end-to-end quantization was 5.318339 s with AUTO_NF12 versus 5.500630 s with OFF, 3.43% faster. Against the prior implementation, absolute warm quantization time fell 9.47% for AUTO_NF12 and 10.22% for OFF. The 10–15% AUTO_NF12-versus-OFF target was not reached: remaining time is dominated by GPTQ processing and its dense Hessian/inverse workspace, while all 112 native NF12 encodes now total about 0.12 seconds.

All six final checkpoints, three per policy, contained 482 state tensors, and every corresponding tensor was bit identical. Both policies scored NLL 3.1000067591667175 and perplexity 22.198101321602206 on the held-out split.

The quantization path now also offloads completed layers through pinned CPU storage on CUDA/HIP; other accelerators keep the ordinary CPU move. Large D2H copies are queued in 64 MiB chunks on the existing device stream and synchronized once at the module boundary; small tensors stay pageable. Direct checkpoint-to-device loading was measured slower for large Llama tensors, and CPU-parallel NF12 encoding was not adopted because native encoding is already only about 0.12 seconds total.

SM89 M=512 calibration sweep

The four RTX 4090 sweep used serial verification to avoid PCIe and allocator contention. All selected schedules are bit-identical to the previous arithmetic:

Projection (N, K) Previous NF12 Tuned NF12 Improvement
2048x2048 30.010 us 27.583 us 8.80%
512x2048 16.988 us 15.183 us 11.88%
2048x8192 91.065 us 86.317 us 5.50%

The 8192x2048 gate/up and 128256x2048 vocabulary projections already used their fastest tested schedules.

Full-model logits and short-M linear dispatch

Device Max logits drift Mean absolute drift
RTX 4090 0.218750 0.0234022
RTX 5090 0.2734375 0.0255472
R9700 0.187500 0.0176995

Token IDs matched dense on all devices. RTX 5090 retains rank-order reduction because its pairwise experiment increased both maximum and mean drift.

The paired M=1/4/8/16 benchmark uses resident inputs, seven warmed trials of 200 calls, and one synchronization after each trial. Selected results:

Device Shape M Speedup vs dense
RTX 4090 8192x2048 16 1.171x
RTX 4090 2048x8192 16 2.474x
RTX 5090 8192x2048 16 1.001x
RTX 5090 2048x8192 16 2.926x
R9700 2048x8192 16 1.380x
R9700 128256x2048 16 1.145x

The R9700 long-K M16 split improved 2048x8192 from approximately 45.29 us to 23.17 us during tuning. Remaining slower cases are explicit in the short-M reference page, including RTX 4090 narrow shapes and R9700 8192x2048 M4 and 4096x4096 M4/M8.

NF12 to FP32 conversion

FP32 consumers used to decode BF16 and widen the dense matrix: 9.5 bytes moved per element and a BF16 copy that existed only to be cast. nf12.decode_fp32 and nf12_hip.decode_fp32 now widen in the decode store, so FP32 traffic is 5.5 bytes per element and no BF16 matrix is materialized. The widening is an exponent-preserving bit shift, so the output is bit-identical to decode().float(), including signed zero, subnormals, infinities and NaN payloads.

Measured on an RTX 4090, median of seven trials with resident inputs:

Shape (N, K) Decode then widen decode_fp32 Speedup
2048x2048 15.23 us 12.45 us 1.22x
512x2048 10.59 us 6.49 us 1.63x
8192x2048 175.31 us 109.21 us 1.61x
2048x8192 175.50 us 109.75 us 1.60x

Across the 112 Llama 3.2 1B projections the FP32 conversion falls from 9.08 ms to 5.77 ms, a 1.57x improvement and 3.30 ms saved. On an R9700 the same shapes measure 1.37x to 2.41x. The AUTO_NF12 checkpoint pair remains 482/482 tensors bit-identical after the change.

The GPTQ path keeps its BF16 module weight, because W4A replay and the saved checkpoint need that tensor; decoding FP32 from NF12 instead of widening the resident BF16 copy would add a packed buffer beside both dense tensors rather than remove one. The fused store targets FP32-only consumers.

Fused EoRA weight diff

EoRA consumes the FP32 difference between the source weight and GPTQ's reconstructed weight. The diff used to be built as module.weight.data.float() - wq, which materializes a second full FP32 source matrix beside wq and the result. nf12::sub_fp32 and nf12_hip.sub_fp32 decode each super-atom and subtract wq in the same widening store, so the FP32 source is never written.

GPTQ returns its reconstruction in the source dtype, so _w_wq_diff converts a copy to FP32 before calling the fused op; the original BF16/FP16 wq stays untouched for replay and packing. A real GPTQProcessor.process regression covers the BF16 reconstruction path.

The packed source is retained only when GPTQ and EoRA both run, and is released immediately after the diff is built. The EoRA stage forwards the quantized layer already in the model tree instead of re-packing the restored dense source, and the layer inventory keeps the NamedModule so EoRA's per-module state survives.

Mechanism Dense diff Fused diff
Source read 2 B/element 1.5 B/element (packed)
FP32 source copy 4 B/element none
wq read 4 B/element 4 B/element
Result write 4 B/element 4 B/element
Peak for the diff step 8 B/element 4 B/element

Measured on an RTX 4090 with resident inputs, median of 30 trials:

Shape (N, K) Dense diff Fused diff Speedup Peak saved
512x2048 15.97 us 18.24 us 0.88x 4 MiB
2048x2048 25.86 us 27.65 us 0.94x 16 MiB
8192x2048 325.58 us 184.22 us 1.77x 64 MiB
2048x8192 324.66 us 184.22 us 1.76x 64 MiB
128256x2048 5,027.84 us 2,712.77 us 1.85x 1,002 MiB

Across the 112 Llama 3.2 1B projections plus the vocabulary projection the diff falls from 21.98 ms to 13.02 ms (1.69x), and 4,714 MiB of FP32 source traffic is never materialized.

End-to-end GPTQ + EoRA on Llama 3.2 1B produced 482/482 bit-identical model tensors and 224/224 bit-identical adapter tensors between AUTO_NF12 and OFF. Both policies peaked at 4,042.4 MiB: the packed source stays resident through GPTQ's Hessian/inverse workspace, but the fused store removes the FP32 source copy, so the diff step no longer adds to the workspace-dominated peak.

The FP32 conversion ABI is the nf12 / nf12_hip torch namespace. The separate gptqmodel_floatx ABI exposes only dequantize_fp8_cpu and dequantize_fp4_cpu, and its target dtype codes cover BF16 and FP16 only, so NF12 to FP32 was not added there.

Embedding performance

The production embedding storage uses 96 packed bytes per 64-column row block plus the BF16 output write. Dense BF16 reads 128 bytes and writes 128 bytes; row-major NF12 reads 96 and writes 128, giving an ideal ceiling of 256 / 224 = 1.143x before decode and launch overhead.

Device/table IDs Row-major NF12 vs dense
RTX 4090 [512,5120] 64 1.100x
RTX 5090 [512,5120] 64 1.085x
R9700 [512,5120] 64 1.057x
R9700 [128256,2048] 64 1.047x
R9700 [128256,2048] 256 2.627x

One-ID lookup remains launch and binding limited and is slower than dense, approximately 0.85-0.91x depending on device and wrapper. Multi-token lookup meets the 1.0x gate; the 1.2x target is above the row-major traffic ceiling for a one-ID lookup.

5. Batched-request semantics

For four one-token requests represented as input_ids=[4,1], embedding receives four IDs and the flattened projection sees M=4. Four prefill requests of length L produce M=4L. Ragged requests without padding see the sum of their processed token lengths. Padding tokens count unless the caller removes them.

6. Change inventory

Area Main files Purpose
Config and lifecycle gptqmodel/quantization/config.py, gptqmodel/models/base.py, gptqmodel/looper/module_looper.py, gptqmodel/looper/stage_subset.py, gptqmodel/utils/auto_dtype_cast.py, gptqmodel/nn_modules/hooked_linear.py, gptqmodel/nn_modules/qlinear/nf12.py Pack eligible sources, preserve task and hooked-forward metadata, restore exact source before quantization
Decode width gptqmodel_ext/nf12/csrc/codec/tile.cuh, codec/decode.cu, api.cu, gptqmodel_ext/nf12_hip/nf12_format_hip.cuh, nf12_decode.hip, nf12_torch.cpp, gptqmodel_nf12/api.py Fused NF12 to FP32 widening store
CUDA embedding gptqmodel_ext/nf12/csrc/torch/rowmajor_embedding.cu, gptqmodel_ext/nf12/csrc/torch/ops.cpp, gptqmodel_nf12/api.py Row-major packing and exact lookup
ROCm embedding and linear gptqmodel_ext/nf12_hip/nf12_embedding.hip, nf12_rowmajor_embedding.hip, nf12_torch.cpp, nf12_wmma.hip, gptqmodel/utils/nf12_hip.py Canonical and row-major embedding, cached dispatch, M16 split-K
Tests and docs tests/test_auto_dtype_cast.py, tests/test_nf12_hip_embedding.py, shared embedding cases, docs under docs/ Numerical, lifecycle, device-family, GIL=0, and performance coverage

7. Failure and ambiguity contract

  • Unsupported device, shape, dtype, or module stays dense.
  • Non-exact FP16 stays dense.
  • Native floatx execution is left untouched.
  • Native floatx fallback decoded to BF16 can use NF12.
  • Embedding IDs outside [0,N) produce +0.0 rows, matching the existing CUDA contract.
  • Empty ID tensors return an empty output without launching a kernel.
  • Unsupported packed layouts, mismatched devices, invalid dtypes, invalid exponent bases, and invalid escape indices fail closed.
  • The row-major path retains only packed data, escapes, and scalar metadata between calls.

8. Validation

  • CUDA AutoDtypeCast: 34 passed
  • CUDA NF12 codec, NF12 API, config dispatch, and weight-only config: 202 passed, 10 skipped
  • CUDA AutoDtypeCast + codec + NF12 API after the review fixes: 186 passed, 10 skipped
  • ROCm AutoDtypeCast, embedding, HIP review, and kernel contracts: 562 passed, 3 skipped
  • ROCm NF12 codec: 53 passed, 2 skipped
  • Applicable W4A replay stream tests: 51 passed, 2 skipped
  • End-to-end GPTQ without EoRA: 482/482 model tensors bit-identical, equal 1,458.342 MiB peak
  • End-to-end GPTQ with EoRA: 482/482 model tensors and 224/224 adapter tensors bit-identical
  • New sub_fp32 regressions cover exact equality with decode_fp32 - wq, the fused path without a source materialization, the dense fallback, packed-storage release, and the EoRA forward skip
  • New decode regressions cover adversarial bit patterns (signed zero, subnormals, Inf, NaN), exact equality with decode().float(), and a check that FP32 dequantize never calls the BF16 decode.
  • New lifecycle regressions cover transformed operands, one-application rotation, both W4A replay modes, restored metadata, removable hooks, packed-storage release for linear/hooked/embedding sources, native GPU encoding staying on its source device, pinned layer offload preserving bits, and the three tuned SM89 M=512 schedules matching the BF16 twin exactly.
  • CUDA two-GPU PYTHON_GIL=0 probe: PASS
  • ROCm two-GPU PYTHON_GIL=0 probe: PASS
  • Scoped ruff check, git diff --check, and Mermaid fence validation: passed

9. Reviewer notes and remaining limits

  • R9700 one-ID embedding remains slower than dense; multi-token is the useful speedup.
  • End-to-end peak quantization memory remains governed by GPTQ Hessian/inverse workspace; NF12 reduces calibration resident state rather than that workspace. With EoRA the fused diff keeps the peak equal to OFF (4,042.4 MiB) while saving 4 B/element at the diff step.
  • RTX 5090 has higher full-model drift under its retained reduction order; pairwise association was measured and rejected.
  • The short-M benchmark is a paired kernel benchmark, not an end-to-end serving benchmark.
  • No persistent dense/dequantized inference cache was added.
  • The current implementation covers aligned nn.Linear, calibration HookedLinear, and nn.Embedding; norm vectors and biases stay dense.

The draft PR contains commits 01739ce88, f77e4104d, ac5463f0e, review-fix commits 95040b7c6 and c7321933d, measured-evidence documentation commit 11fb0204f, memory/encode performance fix 1e6af2d31, SM89 calibration/offload performance commit dc03172b5, the FP32 widening-store commit c68d71271, the fused EoRA diff commit e0f318fea, the fused-diff wiring fix 68c661fce, and the review fixes 26b3efe7e.

Comment thread gptqmodel/utils/nf12_hip.py Fixed
Comment thread gptqmodel/utils/nf12_hip.py Fixed
Comment thread gptqmodel/utils/nf12_hip.py Fixed

Copy link
Copy Markdown
Collaborator Author

Reviewed head f77e4104d8650b07411ea29eff6fb0841bb624a7. I found two correctness regressions in rotated calibration that should be fixed before merging.

  1. [P1] Capture the transformed operand in AutoNF12HookedLinear.forward. Lines 263–270 call NF12Linear.forward(input), which applies the online Hadamard internally, then pass the original input to the calibration hook. Existing HookedLinear.forward passes the transformed input. Thus a rotated down projection computes with one operand while GPTQ collects its Hessian from another. CPU reproduction with a BF16 64→16 HookedLinear, online_full_had=True, and input [1,0,…,0]: the source hook receives [0.125,…,0.125]; the packed hook receives [1,0,…,0]. Preserve the source forward's operand transformation before both GEMM and capture, without applying rotation twice. The copied W4A replay fields also need their corresponding forward semantics preserved; copying the attributes alone does not execute the original replay logic.

  2. [P1] Preserve forward behavior when restoring a hooked source. Lines 311–316 restore every linear kind as a bare nn.Linear, discarding online rotation and W4A replay metadata/behavior. shell_module_materialize(role="quant_source") installs this object in the live model, so subsequent layer/subset replay uses an unrotated activation with a rotated weight. This is separate from the capture mismatch above: fixing the hook still leaves replay wrong. In the same reproduction, the restored object has no online_full_had flag and its forward differs from the source despite exact weight restoration. Restore a behavior-preserving source module (including rotation/replay metadata), and cover forwards both before packing and after restoration.

Minimal reproducer for both, using the CPU codec to isolate lifecycle semantics:

import torch
from torch import nn
import gptqmodel.quantization.nf12 as codec
from gptqmodel.nn_modules.hooked_linear import HookedLinear
from gptqmodel.utils.auto_dtype_cast import (
    AutoNF12HookedLinear, SourceModuleSpec, restore_source_module,
)

codec._native_encode_runtime = lambda *args: (None, None)
source = HookedLinear.from_linear(
    nn.Linear(64, 16, bias=False, dtype=torch.bfloat16)
)
source.online_full_had = True
seen = []
source.forward_hook = lambda m, args, out: seen.append(args[0].clone())
packed = AutoNF12HookedLinear.from_linear(source)
x = torch.zeros(1, 64, dtype=torch.bfloat16)
x[0, 0] = 1
source(x)
packed(x)
print(seen[0][0, :8], seen[1][0, :8])
restored = restore_source_module(
    packed, SourceModuleSpec("hooked_linear", torch.bfloat16, (16, 64)),
    device="cpu",
)
print(getattr(restored, "online_full_had", None))
print((source(x) - restored(x)).abs().max())

Validation: tests/test_auto_dtype_cast.py: 14 passed; tests/test_gptqmodel_nf12_api.py: 95 passed, 3 skipped. The reproduction above exposes behavior absent from those tests. Local runtime: Python 3.14t, Torch 2.15.0.dev20260928+cu130, Transformers 5.20.2, NVIDIA SM80. ROCm and the SM89/SM120 tuning paths were not executed in this review.

Copy link
Copy Markdown
Collaborator Author

Fixed in 95040b7c6.

The dense and packed hooked paths now share prepare_hooked_linear_input, so W4A replay and online Hadamard run exactly once before the GEMM and the calibration hook receives that transformed operand. AutoNF12HookedLinear calls NF12Linear._forward_impl(..., apply_rotation=False) after preparation.

restore_source_module now restores hooked sources as HookedLinear, copies registered hooks plus the online-rotation and W4A replay state, and preserves the restored forward behavior. Regression coverage includes transformed hook operands, both W4A replay modes, one-application rotation, metadata restoration, registered hooks, and source-versus-restored forward equality.

Validation on this commit:

  • tests/test_auto_dtype_cast.py: 19 passed on CUDA; 18 passed, 1 skipped on ROCm
  • tests/test_gptqmodel_nf12_api.py: 97 passed, 1 skipped
  • ROCm embedding/review/kernel contracts: 531 passed
  • Applicable W4A replay stream tests: 51 passed, 2 skipped
  • GIL=0 probes: CUDA NF12 ops PASS; ROCm NF12 embedding PASS
  • ruff check and git diff --check: passed

Copy link
Copy Markdown
Collaborator Author

Re-reviewed head 95040b7c6028b5542e5b36ead4511186762ca24b, including both commits since the previous review.

The two earlier P1 rotation findings are fixed. Re-running the original non-mocked Hadamard reproducer now captures [0.125, …, 0.125] in both source and packed hooks; restoration retains online_full_had=True, and source-versus-restored forward maximum difference is 0.0.

One remaining finding:

[P2] Preserve hook removal when transferring registered hooks. In copy_hooked_linear_runtime, lines 83–87, value.copy() creates new hook dictionaries for the packed and restored modules. A PyTorch RemovableHandle still refers to the original dictionary, so handle.remove() only removes the source hook; both replacements keep executing it. This affects temporary activation transforms and capture hooks when their owner removes them after source replacement, and can retain their captured state. The existing new registered-hook test checks that the hook fires after restoration, but not that it can subsequently be removed.

Confirmed CPU reproduction: after removal, source/packed/restored pre-hook counts are 0 / 1 / 1 and their outputs are 0 / 32 / 32. The remaining hook, not NF12 arithmetic, produces the difference:

import torch
from torch import nn
import gptqmodel.quantization.nf12 as codec
from gptqmodel.nn_modules.hooked_linear import HookedLinear
from gptqmodel.utils.auto_dtype_cast import (
    AutoNF12HookedLinear, SourceModuleSpec, restore_source_module,
)

# Isolate lifecycle behavior using the CPU codec.
codec._native_encode_runtime = lambda *args: (None, None)
source = HookedLinear.from_linear(
    nn.Linear(64, 16, bias=False, dtype=torch.bfloat16)
)
with torch.no_grad():
    source.weight.fill_(0.5)
handle = source.register_forward_pre_hook(lambda m, args: (args[0] + 1,))
packed = AutoNF12HookedLinear.from_linear(source)
restored = restore_source_module(
    packed, SourceModuleSpec("hooked_linear", torch.bfloat16, (16, 64)),
    device="cpu",
)
handle.remove()
modules = (source, packed, restored)
x = torch.zeros(1, 64, dtype=torch.bfloat16)
print([len(m._forward_pre_hooks) for m in modules])  # [0, 1, 1]
print([m(x)[0, 0].item() for m in modules])         # [0, 32, 32]

Preserve the registration/removal relationship across replacement, or explicitly transfer/rebind the handles owned by the hook lifecycle. Cover removal of both forward and pre-forward hooks after casting and restoration, including the companion kwargs/always-call metadata dictionaries.

Validation on this head:

  • tests/test_auto_dtype_cast.py + tests/test_gptqmodel_nf12_api.py: 114 passed, 3 skipped.
  • tests/models/test_w4a_replay_stream.py: 51 passed, 3 skipped.
  • Original rotation reproducer: both previous failures resolved.
  • New hook-removal reproducer: failure above confirmed.
  • git diff --check: passed; checkout unchanged.

Runtime: Python 3.14t with GIL disabled, Torch 2.15.0.dev20260928+cu130, Transformers 5.20.2, NVIDIA SM80. No new ROCm, SM89/SM120, or full-model quality validation is claimed.

@Qubitium
Qubitium marked this pull request as ready for review November 13, 2026 14:25

Copy link
Copy Markdown
Collaborator Author

Fixed in c7321933d.

copy_hooked_linear_runtime now shares the source hook registries with packed and restored modules instead of copying them. This preserves PyTorch's RemovableHandle relationship, so removing a pre-hook or forward hook removes it from the source, packed, and restored views, including the companion kwargs and always-call metadata dictionaries.

Added test_registered_hook_removal_survives_cast_and_restore, which covers:

  • forward pre-hook removal after casting and restoration;
  • forward hook removal with with_kwargs=True and always_call=True;
  • shared identity of all hook and metadata registries;
  • empty registries and unchanged forward outputs after removal.

Validation on c7321933d:

  • tests/test_auto_dtype_cast.py + tests/test_gptqmodel_nf12_api.py: 117 passed, 1 skipped on CUDA
  • tests/test_auto_dtype_cast.py: 19 passed, 1 skipped on ROCm
  • Relevant W4A hooked-linear tests: 11 passed
  • ruff check and git diff --check: passed

@Qubitium
Qubitium marked this pull request as draft November 13, 2026 14:35

Copy link
Copy Markdown
Collaborator Author

Verification completed on 11fb0204f.

  • NF12 projection storage: 113/113 aligned Llama projection weights restored bit exactly across 1,235,746,816 elements. Projection arithmetic is close but not bitwise identical because FP32 reduction association differs (q_proj max abs 0.0009765625; down_proj max abs 0.03125; lm_head exact). Full-model token IDs matched.
  • NF12 embedding: table decode and 512/512 sampled lookup rows were bit exact. Packed storage was 394,365,297 bytes versus 525,336,576 dense, a 24.93% reduction.
  • End-to-end GPTQ: 4K WikiText calibration, GPTQ 4-bit/group 128, RTX 4090. All 482 tensors were bit identical across four AUTO_NF12 and three OFF checkpoints. Held-out NLL and PPL were exactly equal (3.1071042120456696, 22.35621172659059). Peak memory was 7.974 MiB / 0.527% lower with AUTO_NF12; warm median quantization time was 1.904% higher (30.131874 s versus 29.568869 s), so this run does not demonstrate a quantization-time reduction.

The removable-hook review issue is fixed and covered by test_registered_hook_removal_survives_cast_and_restore; all CodeQL inline threads are resolved.

Validation on the pushed branch:

  • CUDA AutoDtypeCast + NF12 API: 117 passed, 1 skipped
  • ROCm AutoDtypeCast + embedding + review + kernel contracts: 550 passed, 1 skipped
  • CUDA and ROCm GIL=0 probes: PASS
  • Scoped Ruff and git diff --check: PASS
  • CI for c7321933d: all checks passed

Copy link
Copy Markdown
Collaborator Author

Investigated the warm per-layer slowdown and fixed two encode-path bugs in 1e6af2d31.

Cause

  • quantize_nf12_weight copied each GPU weight to CPU, then copied it back to the GPU for native encoding.
  • NF12Linear/AutoNF12HookedLinear allocated full zero NF12 buffers on CPU before immediately overwriting them, requiring another device copy.
  • Warm NF12 encoding of 112 modules took about 1.8 s before these fixes. Native encoding itself is about 0.08–0.18 ms per representative matrix.

Fix

  • Native GPU input now remains on its source device through encode and packed-result installation.
  • Source casting creates the NF12 module without placeholder buffers, so the first installed buffers are the actual native results.
  • The quantizer source restores exact BF16, installs the dense module, then releases stale packed buffers.

Warm RTX 4090 production A/B

  • AUTO_NF12: 5.874719 s median
  • OFF: 6.126948 s median
  • AUTO_NF12: 4.12% faster
  • Peak allocation: 1,458.342 MiB for both
  • Three checkpoints per policy: 482/482 tensors bit identical
  • Held-out PPL: 22.198101321602206 for both

Warm encoding after the fix is 0.118522 s for all 112 modules, or 0.079967 s after excluding the first seven shape specializations. Resident allocation after module preparation is 18.88% lower, but end-to-end peak remains governed by GPTQ's inverse/damping workspace and cached calibration inputs.

Validation: CUDA 165 passed / 8 skipped; ROCm 554 passed / 1 skipped; both GIL=0 probes pass; scoped Ruff and git diff --check pass.

@Qubitium

Copy link
Copy Markdown
Collaborator Author

Updated in dc03172b5.

Four-4090 M=512 sweep
The tuning sweep ran across all four RTX 4090s, followed by serial verification to remove PCIe and allocator contention. The production SM89 overrides are bit-identical to the previous arithmetic:

Projection (N,K) Previous Tuned NF12 improvement
2048x2048 30.010 us 27.583 us 8.80%
512x2048 16.988 us 15.183 us 11.88%
2048x8192 91.065 us 86.317 us 5.50%

8192x2048 and 128256x2048 already selected their fastest measured schedules and were left unchanged.

End-to-end
Five-run alternating warm A/B on RTX 4090 with 4,096 WikiText calibration tokens:

  • AUTO_NF12: 5.318339 s
  • OFF: 5.500630 s
  • AUTO_NF12 vs OFF: 3.43% faster
  • Absolute improvement versus the previous implementation: 9.47% for AUTO_NF12, 10.22% for OFF

The 10-15% AUTO_NF12-versus-OFF target was not reached. GPTQ processing and its dense Hessian/inverse workspace now dominate; all 112 NF12 encodes total about 0.12 seconds.

The production A/B checkpoint pair remains 482/482 tensors bit-identical.

Transfer changes
Completed layers now use pinned CPU storage for large D2H copies, queued in 64 MiB chunks and synchronized once per module stream. Direct safe_open(..., device="cuda") and pinned H2D staging were measured and rejected because both were slower in the real Llama path.

Validation

  • CUDA AutoDtypeCast, codec, decoder, and config suites: 156 passed, 9 skipped
  • Full CUDA NF12 API, including six new SM89 schedule/twin-oracle cases: 103 passed, 1 skipped
  • ROCm AutoDtypeCast, embedding, review, and kernel contracts: 555 passed, 1 skipped
  • CUDA and ROCm PYTHON_GIL=0 probes: PASS
  • Scoped Ruff and git diff --check: PASS

`NF12Linear.dequantize_weight(dtype=torch.float32)` decoded to BF16 and then
widened the dense matrix, so FP32 consumers moved 9.5 bytes per element
(1.5 read + 2 write + 2 read + 4 write) and held a BF16 copy that existed only
to be cast.

Add a widening store to both decoders:

* CUDA `store_row_tile_fp32` writes the same elements as `store_row_tile` as
  two `float4` chunks, widening each BF16 pair with an exponent-preserving bit
  shift. `decode_rows`, `decode_kernel`, `launch_decode` and `decode_impl` are
  templated on the output type; `nf12_decode_fp32` and the `nf12::decode_fp32`
  torch op expose it.
* HIP mirrors it with `store_row_tile_fp32`, a templated `decode_rows`,
  `decode_nf12_matrix` shared by `nf12_decode` and `nf12_decode_fp32`, and a
  `nf12_hip::decode_fp32` torch op.

Widening is exact, so the result is bit-identical to decoding BF16 and casting,
including signed zero, subnormals, infinities and NaN payloads. FP32 traffic
drops from 9.5 to 5.5 bytes per element.

Measured on an RTX 4090 (median of seven trials):

  2048x2048   15.23 us -> 12.45 us   1.22x
  512x2048    10.59 us ->  6.49 us   1.63x
  8192x2048  175.31 us -> 109.21 us  1.61x
  2048x8192  175.50 us -> 109.75 us  1.60x

Across the 112 Llama 3.2 1B projections the FP32 conversion falls from 9.08 ms
to 5.77 ms (1.57x, 3.30 ms saved). On an R9700 the same shapes measure 1.37x to
2.41x. The AUTO_NF12 GPTQ checkpoint pair remains 482/482 tensors
bit-identical.

The GPTQ path keeps its BF16 module weight: that tensor is what W4A replay and
the saved checkpoint require, so decoding FP32 from NF12 in place of widening
the resident BF16 copy would add a packed buffer beside both dense tensors
rather than remove one. The fused store targets FP32-only consumers.
@Qubitium

Copy link
Copy Markdown
Collaborator Author

Added in c68d71271: NF12 now decodes straight to FP32.

What was there
NF12Linear.dequantize_weight(dtype=torch.float32) decoded BF16 and then widened the dense matrix. That moved 9.5 bytes per element (1.5 read + 2 write + 2 read + 4 write) and held a BF16 copy that existed only to be cast. There was no standalone NF12 to FP32 decode on either backend; the only FP32 path was the fused linear_fp32 router kernel, which decodes in registers and never materializes weights.

What changed

  • CUDA: store_row_tile_fp32 in codec/tile.cuh writes the same elements as store_row_tile as two float4 chunks, widening each BF16 pair with an exponent-preserving bit shift. decode_rows, decode_kernel, launch_decode and decode_impl are templated on the output type; nf12_decode_fp32 and nf12::decode_fp32 expose it.
  • HIP: store_row_tile_fp32, a templated decode_rows, and decode_nf12_matrix shared by nf12_decode and nf12_decode_fp32, plus the nf12_hip::decode_fp32 torch op.
  • Python: gptqmodel_nf12.decode_fp32, NF12Weight.decode_fp32, gptqmodel.utils.nf12.decode_fp32, gptqmodel.utils.nf12_hip.decode_fp32, and NF12Linear.dequantize_weight selects the widening store when dtype is torch.float32. An older already-loaded runtime falls back to decode-then-cast.

Widening is exact, so the output is bit-identical to decode().float() for signed zero, subnormals, infinities and NaN payloads. FP32 traffic drops from 9.5 to 5.5 bytes per element.

Measured, RTX 4090, median of seven trials, resident inputs

Shape (N, K) Decode then widen decode_fp32 Speedup
2048x2048 15.23 us 12.45 us 1.22x
512x2048 10.59 us 6.49 us 1.63x
8192x2048 175.31 us 109.21 us 1.61x
2048x8192 175.50 us 109.75 us 1.60x

Across the 112 Llama 3.2 1B projections: 9.08 ms to 5.77 ms, 1.57x, 3.30 ms saved. R9700: 1.37x to 2.41x.

Scope
The GPTQ path keeps its BF16 module weight. GPTQ.clone_module reads the restored dense source, and W4A replay and the saved checkpoint need that same BF16 tensor, so decoding FP32 from NF12 instead of widening the resident BF16 copy would add a packed buffer beside both dense tensors rather than remove one. The fused store targets FP32-only consumers: dequantize_weight(dtype=torch.float32), FP32 oracles, and future FP32 paths. The embedding row-major layout still restores through its BF16 lookup kernel; that FP32 widening store is not in this change.

Validation

  • CUDA NF12 API + codec + AutoDtypeCast: 176 passed, 9 skipped
  • ROCm NF12 codec + AutoDtypeCast + HIP review + HIP embedding: 192 passed, 1 skipped
  • ROCm kernel contracts: 416 passed
  • GIL=0 probes: gptqmodel_nf12.ops PASS, gptqmodel_nf12_hip.embedding PASS (both now cover decode_fp32; ledger updated)
  • AUTO_NF12 GPTQ checkpoint vs OFF: 482/482 tensors bit-identical, 0 mismatches
  • End-to-end quantization unchanged: 5.435 s, peak 1,458.342 MiB
  • Ruff and git diff --check: pass

EoRA needs w - wq in FP32. Decoding the packed source and subtracting wq in
the same widening store avoids materializing an FP32 copy of the source:

  nf12::sub_fp32 / nf12_hip.sub_fp32: out = widen(decode(W)) - wq

The fused store is bit-identical to decode_fp32 - wq and peaks at 4 B/element
instead of 8 B/element. Across the 112 Llama 3.2 1B projections plus the
vocabulary projection the diff drops from 21.98 ms to 13.02 ms (1.69x) and
4,714 MiB of FP32 source traffic is never materialized.

GPTQ keeps the packed source alive only when EoRA will consume the diff, and
releases it immediately after. The EoRA stage forwards the quantized layer in
the model tree instead of re-packing the restored dense source, and the layer
inventory keeps the NamedModule so EoRA state survives. End-to-end GPTQ + EoRA
on Llama 3.2 1B is 482/482 bit-identical model tensors and 224/224
bit-identical adapter tensors between AUTO_NF12 and OFF.
@Qubitium

Qubitium commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator Author

Fused EoRA weight diff (e0f318fea, wiring fix 68c661fce)

EoRA now gets w - wq from a fused NF12 widening store instead of materializing an FP32 source:

  • nf12::sub_fp32 / nf12_hip.sub_fp32: out = widen(decode(W)) - wq
  • Bit-identical to decode_fp32 - wq, including signed zero, subnormals, Inf, and NaN payloads.
  • Peak for the diff step drops from 8 B/element to 4 B/element.

RTX 4090, resident inputs, median of 30 trials:

Shape (N, K) Dense diff Fused diff Speedup Peak saved
512x2048 15.97 us 18.24 us 0.88x 4 MiB
2048x2048 25.86 us 27.65 us 0.94x 16 MiB
8192x2048 325.58 us 184.22 us 1.77x 64 MiB
2048x8192 324.66 us 184.22 us 1.76x 64 MiB
128256x2048 5,027.84 us 2,712.77 us 1.85x 1,002 MiB

Across the 112 Llama 3.2 1B projections plus the vocabulary projection: 21.98 ms -> 13.02 ms (1.69x), 4,714 MiB of FP32 source traffic avoided.

End-to-end GPTQ + EoRA on Llama 3.2 1B (rank 4, 4,096 WikiText tokens):

  • 482/482 model tensors bit-identical between AUTO_NF12 and OFF
  • 224/224 adapter tensors bit-identical
  • Both policies peak at 4,042.4 MiB: the fused store removes the FP32 source copy, so it does not add to the workspace-dominated peak

The EoRA stage no longer re-packs the restored dense source: it forwards the quantized layer in the model tree, and the layer inventory keeps the NamedModule so EoRA's w_wq_diff/wq state survives.

Validation

  • CUDA test_auto_dtype_cast.py: 31 passed
  • CUDA codec + NF12 API + config + weight-only: 202 passed, 10 skipped
  • ROCm AutoDtypeCast + embedding + review + contracts: 559 passed, 3 skipped
  • ROCm codec: 53 passed, 2 skipped
  • CUDA and ROCm PYTHON_GIL=0 probes: PASS
  • ruff check, git diff --check, Mermaid fences: PASS

The gptqmodel_floatx ABI exposes only dequantize_fp8_cpu and dequantize_fp4_cpu with BF16/FP16 target codes; NF12 to FP32 stays in the nf12 / nf12_hip namespace.

Copy link
Copy Markdown
Collaborator Author

Reviewed all 10 commits through e0f318feaa020782889a80550bc0640feed5479d. The earlier rotation and removable-hook fixes pass their regression tests. Two remaining findings:

  1. [P1] Preserve CPU offload for non-CUDA accelerators. move_module_to_cpu_pinned, lines 333–335 returns every non-cuda tensor unchanged. BaseQModel.post_quantize now calls this helper unconditionally for ordinary quantization, replacing move_to(module, device=CPU). Consequently, completed layers on XPU, MPS, NPU, or XLA remain on the accelerator as subsequent layers are processed, defeating layer-by-layer offload and potentially exhausting device memory. This also affects auto_dtype_cast="off". Keep pinned transfers for the CUDA/HIP runtime, but preserve the ordinary CPU move for other real devices. A FakeTensor device-routing reproduction with registered buffers returns xpu:0 → xpu:0 and mps → mps:0, rather than CPU; this is a routing check, not a claim of hardware execution on those backends.

  2. [P2] Connect the fused EoRA diff to the production call site, including its dtype contract. The new GPTQProcessor._w_wq_diff has no production caller: process still uses the original dense subtraction at line 823. Thus GPTQ+EoRA pays for retaining the packed source without obtaining the fused diff or its immediate release; cleanup occurs later in finalization. Simply calling the helper with the existing wq is insufficient: GPTQ casts its result back to the source dtype, while fused_w_minus_wq rejects non-FP32 operands. Wire the actual process path through the helper and prepare the FP32 reconstructed operand there, preserving the BF16/FP16 weight used for replay/packing. Add a regression that invokes GPTQProcessor.process, rather than only testing the helper directly.

For finding 2, invoking the real process method with a stub quantization task returning a BF16 reconstruction and a real CUDA NF12 source produced:

process helper calls: 0
packed source remains: True
packed bytes remaining: 1537
wq dtype: torch.bfloat16
fused helper accepts actual dtype: False
fused helper accepts FP32: True

Validation on this head:

  • test_auto_dtype_cast.py, test_nf12_codec.py, and test_gptqmodel_nf12_api.py: 175 passed, 18 skipped.
  • tests/models/test_w4a_replay_stream.py and test_nf12_rowmajor_experimental.py: 55 passed, 3 skipped.
  • Native FP32 decode/subtraction tests and the registered-hook-removal regression passed.
  • git diff --check: passed; repository files unchanged.

Runtime: Python 3.14.7t with GIL disabled, Torch 2.15.0.dev20260928+cu130, Transformers 5.20.2, NVIDIA SM80. ROCm, SM89/SM120 tuning, and full-model quality/performance were not executed in this review.

The processor defined _w_wq_diff but process() still built the diff with the
dense expression, so the fused NF12 store was never used. Route process()
through the helper and add a source-contract regression.

With the fused path active, GPTQ + EoRA on Llama 3.2 1B is still 482/482
bit-identical model tensors and 224/224 bit-identical adapter tensors, and
both policies now peak at 4,042.4 MiB instead of AUTO_NF12 adding the
retained packed source on top of the dense FP32 temporary.
- move_module_to_cpu_pinned now moves XPU/MPS/NPU/XLA tensors to CPU instead
  of returning them unchanged, restoring layer offload for non-CUDA
  accelerators. Meta tensors stay in place because they have no storage.
- _w_wq_diff converts GPTQ's BF16/FP16 reconstruction to FP32 before calling
  the fused NF12 subtraction. The original wq stays untouched for replay and
  packing. Previously the helper rejected the source dtype and silently fell
  back to the dense expression.
- Add a real GPTQProcessor.process regression with a BF16 reconstruction and a
  packed NF12 source, plus a FakeTensor offload-routing regression.

Verified: 112/112 EoRA diffs use the fused FP32 path; GPTQ + EoRA on Llama
3.2 1B is 482/482 model and 224/224 adapter tensors bit-identical, with both
policies peaking at 4,042.4 MiB.
@Qubitium

Copy link
Copy Markdown
Collaborator Author

Both findings are fixed in 26b3efe7e.

P1 — non-CUDA offload. move_module_to_cpu_pinned now calls tensor.to(device=CPU) for every non-cuda device (XPU, MPS, NPU, XLA, and already-CPU), and only leaves meta in place because it has no storage. Pinned chunked staging is still CUDA/HIP-only. Added test_pinned_cpu_offload_moves_non_cuda_accelerators_to_cpu, which uses FakeTensorMode and asserts xpu:0 -> cpu, mps -> cpu, cpu -> cpu, meta -> meta. This applies to auto_dtype_cast="off" as well, since the helper is policy-independent.

P2 — fused diff wiring and dtype. GPTQProcessor.process now calls self._w_wq_diff(module, wq), and _w_wq_diff converts GPTQ's BF16/FP16 reconstruction to FP32 before calling fused_w_minus_wq:

wq_fp32 = wq if wq.dtype == torch.float32 else wq.to(dtype=torch.float32)
fused = fused_w_minus_wq(packed_source, wq_fp32)

The original wq tensor is untouched, so replay/packing still see the BF16/FP16 value. The packed source is released immediately after the diff, including on the dense fallback.

Added test_gptq_process_uses_the_fused_diff_with_a_bf16_reconstruction, which invokes the real GPTQProcessor.process with a stub task returning a BF16 reconstruction and a real CUDA NF12 source. It asserts the helper receives FP32, returns a non-None result, the diff equals w.float() - wq.float() bit for bit, and the packed source is released.

Production check on Llama 3.2 1B with a call counter:

fused_calls: 112, fp32_operand: 112, fused_used: 112

End-to-end GPTQ + EoRA (4,096 WikiText tokens):

  • 482/482 model tensors bit-identical between AUTO_NF12 and OFF
  • 224/224 adapter tensors bit-identical
  • peak 4,042.4 MiB for both policies

Validation on 26b3efe7e:

  • CUDA test_auto_dtype_cast.py + codec + NF12 API: 186 passed, 10 skipped
  • ROCm AutoDtypeCast + embedding + review + contracts: 562 passed, 3 skipped
  • CUDA and ROCm PYTHON_GIL=0 probes: PASS
  • ruff check, git diff --check: PASS

Copy link
Copy Markdown
Collaborator Author

Follow-up review of 5542d27ca1326f3088d39046fe0a287755333244, focused on the serial GPTQ → EoRA lifecycle.

The two findings in my earlier review are addressed: non-CUDA offload again routes to CPU, and the real GPTQ processing path now invokes the fused residual helper with an FP32 reconstruction operand while preserving the BF16/FP16 reconstruction used for replay and packing. I found no additional blocking correctness issue in this focused pass. The lifecycle changes below are a concrete enhancement proposal, not functionality already implemented by this PR.

Make the producer/consumer contract part of the lifecycle

The ordered processor stages already provide the right execution model. Keep GPTQ and EoRA serial, and make their per-module dependency explicit.

Today that dependency spans model flags _has_eora / _needs_w_wq_diff, wrapper-retention branches, auto_dtype_cast_forward_disabled, and loose state["wq"] / state["w_wq_diff"] entries. See run setup, wrapper retention, and EoRA setup. This makes storage lifetime and forward-weight identity depend on knowledge of EoRA in several layers.

I recommend extending the existing ProcessorLifecycleConfig with declared produced/required artifacts and a forward-weight role, resolved once by QuantizationRunPlan. This does not need a new general scheduler.

A proposed typed, transient EoraHandoff on the stable NamedModule would own:

  • An independent CPU snapshot of the uncorrected reconstruction.
  • The residual plus shape/dtype/source metadata and consumption status.
  • Explicit operations to publish the input, consume the residual once, and take the reconstruction for packing.

The planner should reject an EoRA stage without a compatible producer. A missing or already-consumed module handoff should produce a descriptive lifecycle error. Preserve producer-specific residual arithmetic: GPTQ uses FP32 here, while some other producers intentionally subtract in FP16. This contract should also accommodate the dequantization → EoRA adapter-generation path.

Give each tensor and forward a defined owner

Boundary Required behavior
Original calibration → GPTQ Restore exact source bits; retain the packed source only if the planned residual producer can use it.
GPTQ → EoRA Publish the reconstruction and residual atomically after successful processing. Release the packed source immediately after residual construction, including failure cleanup.
EoRA calibration Use the reconstruction already installed in the module tree. Explicitly bypass original-checkpoint rematerialization and source NF12 packing for this forward role.
EoRA processing → replay Consume the residual once; install the adapter-corrected live weight for downstream replay while retaining the independent uncorrected snapshot.
Final packing Pack the uncorrected reconstruction; export the adapter separately; then release the snapshot. Packing the corrected replay weight would apply the adapter twice at inference.

The current GPTQ residual helper, EoRA consumer, and GPTQ finalizer already implement important pieces of this contract. The enhancement is to express and validate those pieces centrally, replacing scattered stage-specific flags. Handoff storage should remain temporary quantization state; it should not become a persistent dense inference cache.

Enforce finalization dependencies per module

stage_layer.py collects finalizers in reverse processor order, then submits them individually to the pool. Reverse submission alone does not guarantee completion order with multiple workers.

For the proposed contract, run one ordered finalization chain per module: EoRA adapter finalization → producer packing → cleanup/offload. Different modules can still finalize concurrently. This is a dependency requirement for the refactor, not a demonstrated corruption bug in today's finalizers.

Proposed lifecycle; not implemented by this PR:

flowchart TD
    A["QuantizationRunPlan validates producer and consumer"] --> B["GPTQProcessor.process: exact source to reconstruction"]
    B --> C["Publish EoraHandoff; release packed source"]
    C --> D["EoraProcessor: capture using reconstructed weights"]
    D --> E["Consume residual; compute adapter"]
    E --> F["Replay corrected live weights"]
    F --> G["EoRA finalizes adapter"]
    G --> H["GPTQ packs uncorrected reconstruction"]
    H --> I["Release snapshot and offload"]
    B -. "failure" .-> X["Abort module and release transient ownership"]
    C -. "missing or invalid handoff" .-> X
    E -. "failure" .-> X
Loading

Implementation should include lifecycle tests for native/fallback residual paths and BF16/exact-FP16 sources; snapshot independence and original-checkpoint reload prevention; dynamic skips and failure cleanup; delayed consumer finalization proving that producer packing waits; and checkpoint continuation plus multi-device placement.

Validation performed

  • 54 passed across test_auto_dtype_cast.py, test_eora_weight_lifecycle.py, test_specialized_eora_lifecycle.py, and test_quantization_lifecycle_contracts.py at 719b08d4. The only subsequent change through reviewed head 5542d27c is the documentation correction to diff memory accounting.
  • A real GPTQProcessor.process() smoke test with a stub quantization result and a native CUDA NF12 source observed a successful FP32 fused residual call, packed-source release, and preservation of the BF16 reconstruction.
  • A serial smoke test then ran real EoRA processing/eigendecomposition/SVD with synthetic identity covariance. It consumed the residual, preserved the uncorrected CPU snapshot bit exactly, and verified that the GPTQ finalizer restored that snapshot at the packing boundary.
  • Environment: free-threaded Python 3.14.7, PyTorch 2.15 development build with CUDA 13.0, NVIDIA SM80. These smoke tests do not establish full-model quality, actual final packed output equivalence, or ROCm/SM89/SM120 coverage.

Recommendation: the immediate fixes are validated; make the next lifecycle change a declared producer/consumer handoff with explicit forward roles and per-module finalization dependencies.

@Qubitium
Qubitium marked this pull request as ready for review November 14, 2026 03:22
@Qubitium
Qubitium merged commit 6548073 into main Nov 14, 2026
6 checks passed
@Qubitium
Qubitium deleted the auto-nf12-dtype-cast branch November 14, 2026 03:22
Qubitium added a commit that referenced this pull request Nov 14, 2026
Upstream added the NF12 embedding and row-major operators (#3853), which
touch the same HIP binding as the stable-ABI migration.

The resolution keeps every new op and re-applies the stable-ABI
conversion on top: the host TU includes only torch_stable_compat.h,
allocates with the stable empty() instead of at::native::empty_cuda,
uses std::vector instead of c10::SmallVector, and registers through
STABLE_TORCH_LIBRARY with TORCH_BOX. at::cumsum/select/zero_ were added
to the compat layer for the row-major pack path.

Verified on ROCm 10.1 (R9700): nf12 HIP suites 196 passed, 4 skipped;
row-major pack and embedding match the dense oracle; the built object
has no unstable torch C++ symbols.
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.

1 participant