Skip to content

[BUG] After offloaded quantize(), unquantized Linear layers (MoE routers, dynamic '-:' exclusions) fail every in-session forward: 'Inference tensors do not track version counter' (#4498 incomplete) #4572

Closed

Description

@Qubitium

Found on main @ 4b65923, RTX 5090 (sm_120), torch 2.15 / transformers 5.22.

What is wrong

With the default offload_to_disk=True, any plain nn.Linear inside a decoder layer that is not quantized leaves the in-session model unusable after quantize() returns. Examples are a MoE router/gate, or a module excluded with a dynamic -: rule. model.generate(), a forward under torch.inference_mode()/no_grad() and a plain forward all raise:

RuntimeError: Inference tensors do not track version counter.

This breaks the #4498 (#4450) contract that the in-session model after an offloaded quantize equals the offload_to_disk=False model. Every MoE model is affected without any dynamic rule, because routers are never quantized.

Mechanism (verified step by step)

  1. BaseQModel.pre_quantize (gptqmodel/models/base.py:4254) materializes each meta layer from the lazy checkpoint source through shell_module_materialize, then materialize_submodule and _copy_checkpoint_tensors_into_submodule (gptqmodel/utils/structure.py:~3901-3905). This runs under torch.inference_mode() (structure.py:1816/1872), so the layer's dense parameters are inference tensors.
  2. BaseQModel.post_quantize (base.py:4378) calls move_module_to_cpu_pinned, which calls Module._apply, which assigns param.data = cpu_copy outside inference mode. The result is a Parameter with is_inference() == False and no version counter. This is the same broken state [BUG] Staged AWQ GSQ (AWQConfig(gsq_training=...)) crashes on every GPU after layer 0: linear.weight.data = weight across inference_mode makes post_quantize view() raise #4561 reaches through a different .data = site.
  3. At loop exit, fix(offload): leave a normal in-session model after disk-offloaded quantize (#4450) #4498's replace_inference_parameters (gptqmodel/utils/offload.py:328-341) is the only repair. It is applied only to base modules and to modules that were still on meta (weight_only_looper.py:945, offload.py:369), and it keys on param.is_inference(), which is False for these parameters. So they are never rebound.
  4. RMSNorm weights end up in the same state (48 of them on Qwen2.5-0.5B even with no dynamic rule) but only take part in elementwise ops, which still work. F.linear on an unquantized Linear in this state raises.

State of model.layers.0.input_layernorm.weight (the same thing happens to every unquantized layer parameter):

after pre_quantize after post_quantize after quantize()
offload_to_disk=True cuda, is_inference=True, no version cpu, is_inference=False, no version cpu, is_inference=False, no version
offload_to_disk=False cuda, is_inference=False, ok cpu, ok cpu, ok

Repro 1: dense model with a dynamic exclusion (RTN shown; GPTQ, FP8, GGUF and EXL3 fail the same way)

import torch
from gptqmodel import GPTQModel
from gptqmodel.quantization.config import RTNConfig

cfg = RTNConfig(bits=4, group_size=128, dynamic={r"-:.*\.layers\.1\.mlp\..*": {}})   # offload_to_disk=True default
m = GPTQModel.load("Qwen/Qwen2.5-0.5B-Instruct", cfg, dtype=torch.float16)
m.quantize(["hello world " * 50] * 4)
ids = m.tokenizer("The capital of France is", return_tensors="pt")
m.generate(**ids, max_new_tokens=4)
generate -> RuntimeError Inference tensors do not track version counter.
no_grad forward -> RuntimeError Inference tensors do not track version counter.
plain forward -> RuntimeError Inference tensors do not track version counter.
layers.0.input_layernorm.weight is_inference: False
layers.0.input_layernorm.weight._version -> Inference tensors do not track version counter.

The traceback ends in modeling_qwen2.py: self.gate_proj(x) → F.linear(input, self.weight, self.bias), on the excluded layers.1.mlp.

In my round-trip harness (16 C4 samples, rules -:layers.1.mlp plus +:layers.2 bits=8), the in-session failure reproduced for GPTQ (fp16 and bf16 asym), RTN, FP8, GGUF Q4_K_M and EXL3. The saved checkpoints were correct, and save → load → re-save → load was byte-identical. With offload_to_disk=False, the in-session model works.

Repro 2: MoE model, no dynamic rule

cfg = RTNConfig(bits=4, group_size=128)                       # offload_to_disk=True default
m = GPTQModel.load("microsoft/Phi-tiny-MoE-instruct", cfg, dtype=torch.bfloat16)
m.quantize(["hello world " * 50] * 4)
m.generate(**m.tokenizer("The capital of France is", return_tensors="pt"), max_new_tokens=3)
offload_to_disk params without version counter unquantized Linear owners generate()
True (default) 160 32 (model.layers.*.mlp.router) RuntimeError: Inference tensors do not track version counter.
False 0 0 The capital of France is Paris.

Suggested fix

In restore_disk_offloaded_modules / materialize_remaining_meta_modules, or one final pass at loop exit, rebind every non-quantized parameter and buffer whose version counter is unusable. The test for that is param.is_inference() or param._version raising, not just is_inference(). Rebind it as a fresh nn.Parameter(param.detach().clone()) (cloned outside inference mode), as replace_inference_parameters already does. Better still, avoid creating these parameters at all: either materialize the layer outside inference mode in pre_quantize, or make move_module_to_cpu_pinned replace parameters instead of assigning .data (for example with torch.__future__.set_swap_module_params_on_conversion(True) or explicit setattr). The same .data = mechanism is behind #4561.

Test that should have caught it

tests/test_offload_quantized_modules_restored_4450.py checks only fully-quantized dense layers and model.to(). Add an in-session generate() case with one dynamic -: exclusion and one MoE model (router left dense), plus an assertion that every parameter of the returned model has a usable version counter.

Severity

High for MoE users: with defaults, quantize-then-evaluate in the same process is broken on every MoE model. Medium for dense models that use dynamic exclusions. Saved checkpoints are not affected.

🤖 Generated with Claude Code

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions