Repository navigation
Description
Summary
requantize(embed_quant_mode=QuantizeEmbed.OUTPUT/BOTH) on a quantized checkpoint loaded on CUDA leaves every
quantized decoder linear whose kernel only has buffers (e.g. TritonV2Linear) on CPU, while the kernel stays the
CUDA-only Triton kernel. The first in-session generate()/forward after requantize() then fails with
ValueError: Expected a cuda device, but got: cpu. Save -> reload still works, so only the in-session model is broken,
which is exactly what #5116 / #5156 was supposed to fix.
Root cause: _requantize_embeddings() snapshots the pre-run placement with _snapshot_module_placement(), which uses
get_device(module). get_device() returns the device of the first parameter, else the first buffer. Every
BaseQuantLinear registers the persistent qzeros_format marker as its first buffer; it is created on CPU in
__init__ and is not part of the saved checkpoint (the writer drops it). With the default
GPTQModel.load(path) (no device/device_map; verified with one visible GPU) the loader builds a layer-wise map
(Loader: Built map across 1 GPU(s), 34 entries); simple_dispatch_model() then takes the single-resident-device
shortcut (gptqmodel/utils/model.py:2064-2073), which skips the hooks and only moves non-persistent buffers
(_place_non_persistent_buffers). qzeros_format is persistent but never in the checkpoint, so it stays on CPU while
qweight/qzeros/scales/g_idx are on cuda:0.
(With device="cuda:0" or device_map={"": "cuda:0"} the single-root shortcut calls model.to(), the marker moves
too and requantize works; tests/test_requant_embed_lm_head_e2e.py loads with device_map={"": "cuda:0"} and does not
generate in-session, so it does not cover this path.) The snapshot therefore records cpu for those modules. After the loop
moves the layers to CPU (post_quantize), _rehome_requantized_endpoints() compares get_device(module) (cpu) with
the recorded placement (cpu) and does not move them back.
Debug trace for model.layers.0.self_attn.q_proj (TritonV2Linear) on HEAD:
BEFORE buffers: qzeros_format=cpu, qweight=cuda:0, qzeros=cuda:0, scales=cuda:0, g_idx=cuda:0
PLACEMENT recorded device for q_proj: cpu
AFTER LOOP all buffers cpu
AFTER REHOME all buffers cpu <- not restored
Kernels whose packed tensors are parameters (e.g. MarlinLinear) are restored correctly, because get_device() sees a
parameter first. Model-wide after requantize: buffers {'cpu': 1260, 'cuda:0': 99}.
Second symptom, two visible GPUs. With CUDA_VISIBLE_DEVICES=0,1 the same default GPTQModel.load(path) dispatches
the layers across both GPUs with GPTQModelAlignDevicesHooks (model.embed_tokens -> cuda:0, layers alternating),
and requantize() itself crashes in input capture:
File "gptqmodel/looper/stage_inputs_capture.py", line 536, in cache_inputs
...
File "accelerate/hooks.py", line 185, in new_forward
File "torch/nn/functional.py", line 2621, in embedding
RuntimeError: Expected all tensors to be on the same device, but got index is on cuda:0, different from other tensors on cpu
StageInputsCapture.cache_inputs() starts with cur_layer_device = CPU and calls
shell_module_materialize(target_submodule=<base module>, device=cur_layer_device) for every base module
(stage_inputs_capture.py:406-424), so the embedding weight is moved to CPU, while the accelerate hook still on the
embedding moves input_ids to its execution_device (cuda:0). Debug print right before capture:
embed_tokens.weight=cuda:0, hook=GPTQModelAlignDevicesHook(execution_device=cuda:0); the forward then sees a CPU weight.
Introduced by
Single-GPU symptom: combination of 6f9ad69e6 / #4134 (adds the CPU-resident qzeros_format buffer as the first
buffer of every quantized linear), 1ba670307/cc7a10e3f (single-device dispatch shortcut that keeps checkpoint
tensors in place and only moves non-persistent buffers, gptqmodel/utils/model.py:2064-2073; qzeros_format is
persistent but never in the checkpoint) and ed6ad92a3 / #5156 (placement snapshot/restore keyed on
get_device(module)). Two-GPU symptom: the requantize path through StageInputsCapture does not account for
accelerate dispatch hooks. All still present at HEAD d81ad345e (no later commit on main touches these files).
Location
gptqmodel/models/base.py:3807 (HEAD d81ad345e):
placement[name] = get_device(module)gptqmodel/models/base.py:3843 (restore):
if get_device(module) != device:
safe_module_to(module, device)gptqmodel/utils/device.py:26-37:
params = list(obj.parameters())
buffers = list(obj.buffers())
if len(params) > 0:
return params[0].device
elif len(buffers) > 0:
return buffers[0].devicegptqmodel/nn_modules/qlinear/__init__.py:1491-1495: self.register_buffer(QZEROS_FORMAT_BUFFER, t.ones((), dtype=t.int64), persistent=True) (created on CPU, first buffer).
Reproduction
Ran on 1x A100 at HEAD d81ad345e (transformers 5.23, torch 2.15). The checkpoint is SmolLM2-135M quantized with
the README quick start (GPTQConfig(bits=4, group_size=128), saved with model.save()).
import sys, collections
from datasets import load_dataset
from gptqmodel import CalibrationConfig, GPTQModel, QuantizeEmbed
model = GPTQModel.load("SmolLM2-135M-gptq-4bit") # default load, as in the README
print(model.generate("The capital of France is", max_new_tokens=8, do_sample=False)[0].shape) # works
texts = [t for t in load_dataset("Salesforce/wikitext", "wikitext-2-raw-v1", split="train")["text"] if len(t) > 200][:8]
model.requantize(CalibrationConfig(dataset=texts), embed_quant_mode=QuantizeEmbed.OUTPUT)
q = model.model.model.layers[0].self_attn.q_proj
print(type(q).__name__, {n: str(b.device) for n, b in q.named_buffers()})
model.generate("The capital of France is", max_new_tokens=8, do_sample=False) # crashesOutput:
TritonV2Linear {'qzeros_format': 'cpu', 'qweight': 'cpu', 'qzeros': 'cpu', 'scales': 'cpu', 'g_idx': 'cpu', 'wf_unsqueeze_zero': 'cpu'}
...
File "gptqmodel/nn_modules/triton_utils/dequant.py", line 332, in dequant
with torch.xpu.device(qweight.device) if HAS_XPU else torch.cuda.device(qweight.device):
ValueError: Expected a cuda device, but got: cpu
QuantizeEmbed.BOTH fails the same way. model.save() followed by GPTQModel.load() of the result generates fine.
Same script with GPTQModel.load(path, device="cuda:0") or device_map={"": "cuda:0"}: all 1359 buffers on cuda:0, generate works.
Same script with CUDA_VISIBLE_DEVICES=0,1 (default load): requantize() raises the index_select device error above.
Expected vs actual
Expected: requantize() works on a checkpoint loaded with the default GPTQModel.load(path) and the in-session model
runs on the device(s) it was loaded on (the #5116 contract, "Layers the loop returned to CPU are also moved back to
where they were").
Actual: on 1 GPU, buffer-only quantized linears stay on CPU behind a CUDA-only kernel, so the first forward raises; on
2 GPUs, requantize() itself raises a device-mismatch error during input capture.
Suggested fix
Do not use get_device() (first tensor) for the placement snapshot/compare. Record the device from the module's
real payload, e.g. ignore the qzeros_format marker (or any 0-dim CPU marker buffers) or take the most common
non-CPU device among module.parameters(recurse=False) + module.buffers(recurse=False), and compare all tensors when
restoring. Moving qzeros_format to the module device on load (or excluding it from get_device) would also fix the
other get_device(quant_module) callers that currently see cpu for a CUDA-resident quantized module. For the
multi-GPU case, either remove the dispatch hooks before the requantize capture (and re-dispatch afterwards) or
materialize base modules on the hook's execution device instead of CPU. A regression test should requantize a real
checkpoint loaded with the default GPTQModel.load(path) (1 and 2 GPUs) and call generate() in-session.
Activity