Skip to content

[BUG] Checkpoint export still loses dense tensor dtypes and copies transformed CPU runtime operands #4466

Closed

Description

@devin-ai-integration

Describe the bug

At 0b94d79c67, the cases below violate the stated supported contract. The validation scope for each case is explicit; source/dispatch proofs are not device numerical qualification.

Mixed-dtype dense Parameters still narrow during load/re-save after the buffer-only dtype repairs

Severity: P2

Contract and impact

Absent an explicit conversion request, re-save must preserve each checkpoint-owned tensor storage dtype and payload, including dense Parameters, not just buffers.

Silent precision loss in norms, embeddings, unquantized heads/projections and other mixed-dtype dense Parameters. Demonstrated fp16-to-bf16 rounding; no measured generation impact claimed.

To reproduce / evidence

A supported quantized checkpoint stores a dense Parameter at fp16 while config/export-shell dtype is bf16. The tensor value 1.0009765625 is finite and exactly representable at fp16 but not bf16.

From the pinned checkout, run the following with PYTHONPATH=. and the repository requirements installed. It reuses the shipped tiny source/tokenizer/calibration fixture; no model download.
import sys,tempfile,torch
from pathlib import Path
from safetensors.torch import save_file,load_file
sys.path.insert(0,'tests')
from test_resave_preserves_checkpoint_dtypes_4379 import _tiny_source,CALIBRATION
from gptqmodel import GPTQModel,QuantizeConfig,BACKEND
torch.set_num_threads(2)
with tempfile.TemporaryDirectory() as d:
 p=Path(d); source=_tiny_source(p/'source'); q=p/'quantized'; out=p/'resaved'
 m=GPTQModel.load(str(source),quantize_config=QuantizeConfig(bits=4,group_size=32,desc_act=False,device='cpu'),backend=BACKEND.TORCH)
 m.quantize(CALIBRATION,batch_size=1,backend=BACKEND.GPTQ_TORCH,calibration_data_min_length=1)
 m.save(str(q)); del m
 key='model.norm.weight'; expected=torch.full((32,),1.001,dtype=torch.float16)
 for f in q.glob('*.safetensors'):
  sd=load_file(f)
  if key in sd:
   sd[key]=expected; save_file(sd,f,metadata={'format':'pt'})
 m=GPTQModel.load(str(q),backend=BACKEND.TORCH,device='cpu'); m.save(str(out))
 actual=next(load_file(f)[key] for f in out.glob('*.safetensors') if key in load_file(f))
 print(key,'expected',expected.dtype,expected[0].item(),'actual',actual.dtype,actual[0].item())
 Independently executed python reproduce.py from pinned checkout. Scratch path is a command record, not a parent-accessible artifact.

Observed and expected behavior

Real GPT-QModel tiny Llama quantize→save→modify one valid dense tensor dtype→GPTQModel.load→save: model.norm.weight expected fp16 1.0009765625, actual bf16 1.0. Independent direct shipped-helper control: a same-valued fp16 buffer remains fp16 1.0009765625 while a dense Parameter becomes bf16 1.0. Expected both source payloads unchanged. Independent probe additionally observed model.norm.weight already bf16 1.0 immediately after load; export shell rereads checkpoint but narrows it again.

Public source and history

ensure_qwen_drive_registered(model_id_or_path)
config = AutoConfig.from_pretrained(
model_id_or_path,
trust_remote_code=self.trust_remote_code,
)
normalize_hf_config_compat(config, trust_remote_code=self.trust_remote_code)
model_dtype = get_hf_config_dtype(config)
with model_load_lock(), suspend_hf_weight_init():
model = self.loader.from_config(
config, dtype=model_dtype
)
rebuilds at config model_dtype;
load_checkpoint_in_model_then_tie_weights(
model,
# Do not cast the export shell. Each quantized module
# allocates its buffers in the checkpoint's storage dtype
# (packed FP8 weight, FP16 GPTQ scales, FP32 QQQ
# ``s_channel``), and accelerate's ``dtype=None`` path copies a
# checkpoint tensor into that existing dtype. Passing the model
# dtype narrowed every packed/scale buffer to bf16/fp16, so an
# FP8 re-save was no longer loadable and GPTQ/QQQ re-saves were
# lossy (issue #4303).
dtype=None,
checkpoint=self.checkpoint_file_name,
# The shell allocates non-quantized buffers (for example a
# quantized module's bias) in the model dtype. When a legacy
# checkpoint stores one at another dtype, restore the
# checkpoint value instead of republishing the narrowed shell
# slot (issue #4379).
restore_checkpoint_buffer_dtypes=True,
# Load each tensor exactly once. With ``device_map=None``
# accelerate 1.15 calls ``set_model_state_dict`` once per
# checkpoint file, so the whole module ``load_state_dict``
# runs for every shard and a partial shard is completed from
# the module's own buffers.
device_map={"": "cpu"},
loads with dtype=None and restore_checkpoint_buffer_dtypes=True.
if restore_checkpoint_buffer_dtypes:
# The export shell allocates its buffers in the model dtype. A
# legacy checkpoint may store some of them (biases, EXL3 sign
# vectors, ...) at a different dtype, and accelerate's dtype=None
# copy narrows them to the shell slot. Restore every such buffer
# from the checkpoint at its stored dtype so a re-save publishes
# exactly what it read.
checkpoint_dtypes = _checkpoint_tensor_dtypes(
kwargs.get("checkpoint", checkpoint)
)
for name, checkpoint_dtype in checkpoint_dtypes.items():
if name in restore_dtypes:
continue
module_name, _, buffer_name = name.rpartition(".")
module = model.get_submodule(module_name) if module_name else model
current = module._buffers.get(buffer_name)
if (
isinstance(current, torch.Tensor)
and current.is_floating_point()
and current.dtype != checkpoint_dtype
):
restore_dtypes[name] = None
if restore_dtypes:
examines only module._buffers, not _parameters.
if offload_root:
state_dict = _collect_state_dict_with_offload(
model,
offload_root,
include_prefixes=include_prefixes,
include_names=include_names,
)
else:
emits current Parameter dtype. Real Accelerate 1.15.0 copies into the bf16 shell slot; the repair rereads an otherwise identical buffer exactly but never the Parameter.

Pre-existing export-shell casting; earliest original narrowing commit not fully traced. 3f79bdb / #3997 changes forced fp16 to config dtype, not each source dtype. 3d90873 / #4334 and 2daaae4 / #4417 narrow the correction to allocated packed/scale buffers and then floating buffers. Do not call #4417 a newly introducing regression.

Existing reports

Related closed #3976, #4303 and #4379. Public open+closed re-save search did not locate the exact dense-Parameter extension. #4379 explicitly calls its buffer examples incomplete cases rather than regression; this is a further uncovered representation. The final live refresh also checked #4458 (QQQ scale buffers on initial load) and #4455 (dense export target dtype); those are adjacent tensor-schema gaps, not this dense-Parameter save/load/save case.

Software / device info and validation limits

Final reproduction imports the complete real package and executes public CPU quantize/load/save APIs and real safetensors/Accelerate; no mocked loader or AST extraction in that final run. Earlier selected-function AST probe corroborates only control flow and is superseded as primary evidence. No GPU, kernel-arithmetic oracle or PPL claim.

Public hf_repack_layer copies CPU int4pack runtime operands as checkpoint tensors after inference

Severity: P2

Contract and impact

A repack source must expose canonical packed checkpoint tensors or an explicit compatible runtime ABI; state must remain available after a successful forward.

A public repack that succeeds before inference fails after one valid CPU forward. The canonical snapshot already exists but is bypassed.

To reproduce / evidence

Pack/eval/forward a TorchAtenLinear, then hf_repack_layer(module,BACKEND.GPTQ_TORCH,device="cpu").

Actual execution: PYTHONPATH=. python reproduce.py. For an independent rerun, place this script outside the pinned repository and use an interpreter with the versions recorded in limitations, with PYTHONPATH pointing at the pinned checkout. No model download or kernel mock is needed.

import json
import torch
from gptqmodel.nn_modules.qlinear.torch_aten_kernel import TorchAtenLinear
from gptqmodel.utils.packing import hf_pack_layer, hf_repack_layer
from gptqmodel.utils.backend import BACKEND
from gptqmodel.quantization import FORMAT

torch.set_num_threads(1)
results = {}
for after in (False, True):
    try:
        m = TorchAtenLinear(bits=4,group_size=32,sym=True,desc_act=False,
            in_features=128,out_features=64,bias=False,format=FORMAT.GPTQ_V2)
        dense = torch.nn.Linear(128,64,bias=False)
        with torch.no_grad():
            dense.weight.fill_(1)
        hf_pack_layer(m,dense,torch.ones(64,4),checkpoint_format=FORMAT.GPTQ_V2,post_init=True)
        m.eval()
        x = torch.ones(1,128,dtype=torch.bfloat16)
        if after:
            with torch.inference_mode():
                y = m(x)
            results['source_output'] = float(y[0,0])
        results[str(after)+'_shape'] = list(m.qweight.shape)
        t = hf_repack_layer(m,BACKEND.GPTQ_TORCH,device='cpu').eval()
        with torch.inference_mode():
            y = t(x)
        results[str(after)] = {'output':float(y[0,0]),'correct':bool((y == 128).all())}
    except Exception as e:
        results[str(after)] = type(e).__name__+': '+str(e)
print('CPU_REPACK_HISTORY',json.dumps(results))

Observed and expected behavior

Before forward repack succeeds (qweight shape [16,64]); forward outputs 128 for all-ones input/weights (independent dense result 128), runtime qweight becomes [64,64] uint8 and qzeros [4,64] BF16. After forward RuntimeError: size of tensor a (16) must match size of tensor b (64) at dimension 0. Expected canonical snapshot repack with identical output, or explicit private-ABI refusal.

Public source and history

_ABI_TRANSFORMING_QUANT_TYPES = frozenset({
"marlin",
"awq_marlin",
"machete",
"awq_machete",
"swordfish",
"awq_swordfish",
"gptq_bitblas",
"awq_bitblas",
})
def _normalize_enum(value, enum_cls, field: str):
if isinstance(value, enum_cls):
return value
static ABI blacklist omits CPU int4pack;
def _copy_packed_state(source: BaseQuantLinear, target: BaseQuantLinear) -> None:
source_tensors: Dict[str, torch.Tensor] = {}
source_tensors.update(dict(source.named_parameters()))
source_tensors.update(dict(source.named_buffers()))
target_tensors: Dict[str, torch.Tensor] = {}
target_tensors.update(dict(target.named_parameters()))
target_tensors.update(dict(target.named_buffers()))
if not any(key in source_tensors for key in ("qweight", "qzeros")):
raise ValueError(
f"hf_repack_layer: `{type(source).__name__}` has no packed tensors; "
"pack the layer before repacking."
)
missing = [
key
for key in _PACKED_STATE_KEYS
if key in source_tensors and key not in target_tensors
]
if missing:
raise NotImplementedError(
f"hf_repack_layer: `{type(target).__name__}` does not expose the packed buffers "
f"{missing} required to copy a `{type(source).__name__}` layout."
)
shared = {key: value for key, value in source_tensors.items() if key in target_tensors}
_preserve_checkpoint_buffer_dtypes(target, shared)
with torch.no_grad():
for key, value in shared.items():
target_tensors[key].copy_(value)
if hasattr(source, "_checkpoint_format_on_disk"):
target._checkpoint_format_on_disk = source._checkpoint_format_on_disk
source_qzero_format = getattr(source, "qzero_format", None)
target_qzero_format = getattr(target, "qzero_format", None)
if callable(source_qzero_format) and callable(target_qzero_format):
target_qzero_format(format=source_qzero_format())
def _preserve_checkpoint_buffer_dtypes(
target: BaseQuantLinear, shared: Dict[str, torch.Tensor]
) -> None:
"""Keep floating checkpoint buffers at the source storage width.
copies live named buffers;
def transform_cpu(self, dtype: torch.dtype | None = None):
if self._cpu_transformed:
return
# ATen int4pack requires the activation and scales/zero-points to have
# the same dtype. Choose that dtype from the first fused activation so
# an FP16 checkpoint loaded into a BF16 model does not silently fall
# back to dense dequantization on every token.
target_dtype = dtype if dtype in (torch.float16, torch.bfloat16) else self.scales.dtype
if target_dtype not in (torch.float16, torch.bfloat16, torch.float32):
target_dtype = torch.bfloat16
zero_codes = torch.bitwise_right_shift(
torch.unsqueeze(self.qzeros, 2).expand(-1, -1, self.pack_factor),
self.wf_unsqueeze_zero,
).to(torch.uint8)
zero_codes = torch.bitwise_and(zero_codes, self.maxq).reshape(self.scales.shape)
compute_dtype = _cpu_int4pack_scale_dtype(self.scales, zero_codes, self.bits, target_dtype)
# Convert for the packed runtime layout only: ``self.scales`` keeps the
# checkpoint dtype so a later forward or save cannot persist a narrowed
# scale (the same defect class as issue #4178).
compute_scales = self.scales.to(compute_dtype).contiguous()
weight = torch.bitwise_and(
torch.bitwise_right_shift(
torch.unsqueeze(self.qweight, 1).expand(-1, self.pack_factor, -1),
self.wf_unsqueeze_neg_one,
).to(torch.uint8),
self.maxq,
)
ret_idx = self._build_ret_idx()
weight = weight.reshape(weight.shape[0] * weight.shape[1], weight.shape[2])
if not self._ret_idx_is_identity():
weight = weight.index_select(0, ret_idx)
weight = weight.t().contiguous()
self.qweight = torch.ops.aten._convert_weight_to_int4pack_for_cpu(weight.int(), 1).contiguous()
self.qzeros = _cpu_int4pack_zero_offsets(zero_codes, compute_scales, self.bits).to(compute_dtype).contiguous()
self.scales_and_zeros = pack_scales_and_zeros(compute_scales, self.qzeros)
self._cpu_transform_dtype = target_dtype
self._cpu_transformed = True
replaces qweight with uint8 int4pack and qzeros with BF16 affine offsets;
def capture_fused_train_state(module: nn.Module, *, names=None) -> None:
"""Retain packed checkpoint tensors before an inference-only transform.
The clone deliberately escapes the caller's ``inference_mode``. Caches are
captured from inside an inference forward, but the snapshot is later
restored as the checkpoint tensor: ``load_state_dict`` copies into it in
place outside ``inference_mode``, which Torch rejects for inference tensors.
"""
if getattr(module, "_fused_train_state", None) is not None:
return
if names is None:
names = getattr(module, "_FUSED_TRAIN_STATE_NAMES", _STATE_NAMES)
snapshot = {}
with torch.inference_mode(False):
for name in names:
tensor = getattr(module, name, None)
if isinstance(tensor, torch.Tensor):
buffer_name = f"{_STATE_BUFFER_PREFIX}{name}"
module.register_buffer(
buffer_name,
tensor.detach().clone(),
persistent=False,
)
snapshot[name] = buffer_name
module._fused_train_state = snapshot
module._fused_train_state_exportable = True
canonical snapshots are retained.

Original introduction not localized. c73793c / #4096 changes the copy mechanism but does not introduce this exact failure: actual parent and commit probes both fail after forward while succeeding before it. The snapshot serialization fixes also do not establish an effective earlier public-repack fix. Treat as PARALLEL_CONTRACT_GAP.

Existing reports

All-state searches "repack CPU transformed", "repack int4pack", and "hf_repack_layer" "runtime" located related #3822, #4095 and #4125. These concern dtype, qzero-copy or writer boundaries; no exact post-forward CPU public-repack duplicate located.

Software / device info and validation limits

Ubuntu Linux x86-64, 8-vCPU Intel Xeon CPU model 94 with AVX2 but without AVX512-BF16; Python 3.14.6 free-threaded, Torch 2.15.0+cpu, Transformers 5.23.0, bitsandbytes 0.50.2. No CUDA/ROCm GPU. Actual shipped Python modules were imported, not extracted ASTs or mocked arithmetic. Tiny deterministic CPU tensors only; no model download or benchmark. Actual CPU first forward and public repack executed. Related backend-specific dequantize_weight()/dequantize_model() also raise rshift_cpu not implemented for BFloat16 after forward, but top-level GPTQModel dequantization uses a separate path; keeping that helper observation out of the public repack impact claim. Independently repeated at c73793c immediate parent 498e980, exact c73793c and PIN: pre-forward repack returns 128 in each; post-forward repack fails in each. This establishes a current canonical-state caller gap, not the original introducing commit.

Model / datasets

The evidence uses tiny synthetic tensors or local fixtures derived from the public tests; no private model or dataset is required. Device execution that remains untested is stated above.

Activity

  1. added
    bug
    on Nov 16, 2026
  2. Qubitium commented on Nov 16, 2026

    @Qubitium
    Collaborator

    Claimed by an AI agent. Will preserve dense Parameter storage dtypes on load/re-save and stop copying transformed CPU runtime operands into the export shell.

  3. Qubitium commented on Nov 17, 2026

    @Qubitium
    Collaborator

    Taking this. I'll investigate against current main, add a targeted regression test, and open a PR. Will report back here if the claim turns out to be invalid or already fixed.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions