Skip to content

[BUG] LLaVA / Gemma 3 VL: in-session generate() after quantize() crashes with the default offload_to_disk (vision-tower buffers and small modules left on CUDA) #6180

Done

Description

@Qubitium

Summary

With the default offload_to_disk=True, quantize() on a llava or multimodal gemma3 checkpoint leaves the model split between devices: almost everything ends up on CPU, but several tensors stay on cuda:0. The first in-session generate() (or forward) with an image then fails in the vision tower:

RuntimeError: Expected all tensors to be on the same device, but got index is on cuda:0, different from other tensors on cpu (when checking argument in method wrapper_CUDA__index_select)

The pre-quantize hooks added for these models move embed_tokens, norm, rotary_emb, vision_tower and multi_modal_projector to the quantize device. pre_quantize_generate_hook_end() then hands each of them to offload_to_disk(), which does not bring everything back:

  • Non-persistent buffers are not in state_dict(), so they are neither offloaded nor moved. Examples: the SigLIP/CLIP embeddings.position_ids, the rotary inv_freq / original_inv_freq, and Gemma's embed_scale. The vision tower's weights become disk-offloaded behind an Accelerate hook, while its position_ids stays on CUDA.
  • Modules under _SMALL_MODULE_OFFLOAD_BYTES (4 KB) are skipped entirely and stay on CUDA. For llava-interleave-qwen-0.5b this is model.language_model.norm.weight, which is 896 bf16 values.

Measured after quantize() (all parameters and buffers not on CPU):

  • llava-hf/llava-interleave-qwen-0.5b-hf: model.language_model.norm.weight, model.vision_tower.embeddings.position_ids, model.language_model.rotary_emb.inv_freq, ...original_inv_freq, all on cuda:0
  • unsloth/gemma-3-4b-it: model.vision_tower.embeddings.position_ids, model.language_model.embed_tokens.embed_scale, model.language_model.rotary_emb.{full,sliding}_attention_{,original_}inv_freq, all on cuda:0

With offload_to_disk=False the same llava run leaves nothing on CUDA, and in-session generation works. Qwen2-VL, whose hook does not materialize these modules, also generates correctly in session with the default offload. Saving and reloading is not affected: the reloaded llava and Gemma 3 checkpoints generate correctly both natively and through HF.

Introduced by

The pre_quantize_generate_hook_start / pre_quantize_generate_hook_end pairs added in 4ddd98a ([MODE] support llava quantization, #3411) and a5d5d73 (feat(gemma3): add Gemma 3 VL modality and image calibration support, #3307). The root cause is the generic offload_to_disk() behavior described above. I did not run the pre-#3307 Gemma 3 path.

Location (HEAD 8ebe255)

  • gptqmodel/models/definitions/llava.py, pre_quantize_generate_hook_end(): calls offload_to_disk(...) for embed_tokens, norm, rotary_emb, vision_tower and multi_modal_projector.
  • gptqmodel/models/definitions/gemma3.py:259, pre_quantize_generate_hook_end(): same pattern.
  • gptqmodel/utils/offload.py:1455-1460, the small-module skip:
    if not force:
        total_bytes = sum(
            _tensor_nbytes(tensor) for tensor in module.state_dict().values()
        )
        if total_bytes <= _SMALL_MODULE_OFFLOAD_BYTES:
            return

Non-persistent buffers are never visited because they are not in state_dict().

Reproduction (ran it, RTX 4090, transformers 5.23)

import torch
from PIL import Image
from gptqmodel import GPTQModel, QuantizeConfig, CalibrationConfig
from transformers import AutoProcessor

mid = "llava-hf/llava-interleave-qwen-0.5b-hf"   # same failure with unsloth/gemma-3-4b-it
img = Image.open("tests/models/ovis/10016.jpg").convert("RGB")
calib = [[{"role": "user", "content": [{"type": "image", "image": img}, {"type": "text", "text": f"Describe item {i}."}]},
          {"role": "assistant", "content": "A mountain."}] for i in range(4)]
m = GPTQModel.load(mid, QuantizeConfig(bits=4, group_size=128))
m.quantize(CalibrationConfig(dataset=calib, batch_size=1))

print({n: str(t.device) for n, t in [*m.model.named_parameters(), *m.model.named_buffers()] if t.device.type != "cpu"})

proc = AutoProcessor.from_pretrained(mid)
conv = [{"role": "user", "content": [{"type": "image", "image": img}, {"type": "text", "text": "Describe this image."}]}]
inp = proc.apply_chat_template(conv, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt")
m.generate(**inp, max_new_tokens=20, do_sample=False)

Output:

{'model.language_model.norm.weight': 'cuda:0', 'model.vision_tower.embeddings.position_ids': 'cuda:0', 'model.language_model.rotary_emb.inv_freq': 'cuda:0', 'model.language_model.rotary_emb.original_inv_freq': 'cuda:0'}
...
  File ".../siglip/modeling_siglip.py", line 187, in forward
    embeddings = embeddings + self.position_embedding(self.position_ids)
RuntimeError: Expected all tensors to be on the same device, but got index is on cuda:0, different from other tensors on cpu (when checking argument in method wrapper_CUDA__index_select)

With QuantizeConfig(..., offload_to_disk=False), the leftover-device dict is {} and generation returns 'The image captures a breathtaking view of a mountain range ...'.

Expected vs actual

  • Expected: after quantize(), the model is on one consistent device, all CPU as for Qwen2-VL, and generate() with an image works in session.
  • Actual: non-persistent buffers and sub-4 KB modules stay on CUDA, and the first image forward crashes.

Suggested fix

In offload_to_disk(), move whatever it does not offload to CPU: skipped small modules, and non-persistent buffers of an offloaded module. The hook pattern was "move everything back to CPU", and this would keep it. Alternatively, in these two hooks, move_to(module, CPU) after offload_to_disk() for modules that still have accelerator tensors.

Metadata

Metadata

Assignees

No one assigned

    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