Skip to content

fix(models): route every VLM prepare_dataset through the shared calibration helper (#4633) - #4648

Merged
Qubitium merged 2 commits into
mainfrom
fix/issue-4633-vlm-prepare-dataset
Nov 17, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/issue-4633-vlm-prepare-dataset

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #4633

TL;DR

Every vision-language prepare_dataset override now delegates to one shared
helper, prepare_vlm_calibration_dataset in
gptqmodel/models/definitions/_vlm_calibration.py. Twenty-three overrides that
had copied the conversation loop (and dropped the #4228/#4308 split) were
replaced; the eight that already used the shared helpers are unchanged. Net
+420/-215 across 25 definition files (the helper plus 24 definitions), one
96-node contract test, and a docs page.

1. The problem

Definitions added after #4228/#4308 copied batched_conversations directly:

flowchart TD
    A["definition.prepare_dataset"] --> B["batched_conversations"]
    B --> C["prepare_inputs_for_conversations"]
    C --> D["processor.apply_chat_template"]
    A --> E["del kwargs"]
    D -->|"pre-tokenized row"| F["empty prompt or literal 'input_ids'<br/>calibrates on boilerplate"]
    E -->|"concat / sort / min_length"| G["silently ignored"]
    C -->|"unequal lengths, no padding"| H["ValueError at batch_size > 1"]
Loading
Pre-fix location Bypass Symptom
cohere_compass.py:374 no split; del kwargs; no padding=True pre-tokenized -> empty prompt; bs=2 ValueError
inkling.py:132 no split; del kwargs; no padding=True bs=2 ValueError
hunyuan_vl.py:110 no split; del kwargs rows -> BOS only; columnar -> "input_ids"
muse_glimmer.py:83 no split; del kwargs rows -> system prompt only; columnar -> "input_ids"
ernie4_5_vl_moe.py:399 no split; options ignored AttributeError / KeyError content
minimax_m3_vl.py:114 no split; options ignored ValueError (int not subscriptable)
interns1.py:127 no split; no padding AttributeError; bs=2 ValueError
lfm3_vl.py:143, lfm3_omni.py:139 no split; no padding bs=2 ValueError
intern_s2_preview.py:187 no split; del kwargs options ignored
deepseek_vl.py:111 no split; del kwargs rows -> processor path
diffusion_gemma.py:344 no split; del kwargs rows -> processor path
apertus.py:130 no split; del kwargs rows -> processor path
deepseek_ocr2.py:124 no split; del kwargs rows -> processor path
deepseek_vl_v2.py:171 no split; del kwargs rows -> processor path
locateanything.py:98 no split; del kwargs rows -> processor path
openvla.py:180 no split; del kwargs rows -> processor path
ovis.py:129 no split; options ignored rows -> KeyError
ovis2_5.py:102 no split; options ignored rows -> processor path
unlimited_ocr.py:255 no split; del kwargs rows -> processor path
zdtaichu5.py:283 own conversation detector; options ignored options ignored

The silent cases are the bad ones: the caller passes
[{"input_ids": ids, "attention_mask": mask}] (or tokenizer(texts)) and
every calibration sample is replaced by a template rendered around a dict with
no content, or around the literal key names. GPTQ then calibrates on 1 to 9
tokens of boilerplate, the exact #4308 failure.

2. The new flow

BaseQModel.quantize still calls self.prepare_dataset(...); each definition
override is now a short delegation that supplies only its processor hook.

flowchart TD
    A["BaseQModel.quantize"] --> B["definition.prepare_dataset"]
    B --> C["prepare_vlm_calibration_dataset"]
    C --> D["split_calibration_dataset"]
    D -->|"pre-tokenized rows / columnar mapping"| E["prepare_calibration_dataset<br/>base text path"]
    D -->|"mixed ids + conversations"| F["ValueError: mixes pre-tokenized rows"]
    D -->|"multimodal columns in an input_ids row"| G["ValueError: non-text columns"]
    D -->|"chat conversations"| H["pop_conversation_calibration_options"]
    H -->|"calibration_concat_size set"| I["ValueError: concat not supported"]
    H --> J["batched_conversations<br/>preprocess_func"]
    J --> K["prepare_inputs_for_conversations<br/>or prepare_conversations callback"]
    K --> L["finalize_conversation_batches<br/>sort / min_length / shuffle"]
    E --> M["calibration batches"]
    L --> M
Loading

Two per-model hooks remain, and both delegate:

  • prepare_inputs_for_conversations(processor, conversations) prepares one
    processor batch. It is the default, and every definition whose processor call
    is a plain apply_chat_template supplies only this method.
  • prepare_conversations(rows) receives the raw non-chat rows and returns the
    prepared batches (OCR {"image", "text"} rows, Ovis
    {"conversations", "image"} rows, OpenVLA prompt rows).

Processors are resolved with self.processor first and load_processor() only
when none is loaded, so a pre-tokenized dataset never loads a multimodal
processor.

3. Audit: every VLM prepare_dataset override

Discovered with "prepare_dataset" in cls.__dict__ over
gptqmodel.models.definitions (31 exported classes). Status after this PR:

# Definition Status
1 Apertus1p5QModel delegates; new prepare_inputs_for_conversations
2 CohereCompassQModel delegates; padding=True
3 DeepSeekOCR2QModel delegates; _prepare_calibration_batches
4 DeepSeekVLQModel delegates
5 DeepSeekVLV2QModel delegates; _prepare_calibration_batches
6 DiffusionGemmaQModel delegates; new prepare_inputs_for_conversations
7 Ernie4_5_VLMoeQModel delegates; _prepare_calibration_batch
8 HunYuanVLQModel delegates; new prepare_inputs_for_conversations
9 InklingMMQModel delegates; padding=True
10 InternS1QModel delegates; _prepare_calibration_batch; padding=True
11 InternS2PreviewQModel delegates; new prepare_inputs_for_conversations
12 InternVLChatQModel already compliant (unchanged)
13 InternVLQModel already compliant (unchanged)
14 LFM2VLQModel already compliant (unchanged)
15 LFM3OmniQModel delegates; padding=True
16 LFM3VLQModel delegates; padding=True
17 LlavaQModel already compliant (unchanged)
18 LocateAnythingQModel delegates; _prepare_calibration_batches
19 MiniCPMOQModel already compliant (unchanged)
20 MiniCPMV4_6QModel already compliant (unchanged)
21 MiniCPMVQModel already compliant (unchanged)
22 MiniMaxM3VLGPTQ delegates; _prepare_calibration_batches
23 MuseGlimmerQModel delegates
24 OpenVLAQModel delegates; _prepare_calibration_batches
25 Ovis2_5QModel delegates; _prepare_calibration_batches
26 OvisQModel delegates; _prepare_calibration_batches
27 Qwen2AudioGPTQ delegates; _prepare_calibration_batch
28 Qwen3OmniMoeGPTQ delegates; _prepare_calibration_batches
29 SmolVLMQModel already compliant (unchanged)
30 UnlimitedOCRQModel delegates; _prepare_calibration_batches
31 ZDTaichu5QModel delegates for conversations; base path otherwise

Overrides that are not exported through the definitions package but already
share the helpers: BaseQwen2VLGPTQ (base_qwen2_vl.py:345),
BaseQwen2_5_OmniGPTQ (base_qwen2_5_omni.py:293),
Gemma3ForConditionalGenerationGPTQ (gemma3.py:299),
Ovis2QModel (ovis2.py:103).

Deliberate exceptions (documented in
docs/vlm-calibration-input-normalization.md):

4. Failure contract

Situation Before After
pre-tokenized row (list[int], input_ids mapping) processor path: empty prompt, "input_ids" text, or AttributeError base text path keeps the ids
columnar mapping (tokenizer(texts)) calibrated on key names unpacked into rows
mixed token ids and conversations silent corruption or late crash ValueError naming the mix
input_ids row plus pixel_values tensors silently dropped ValueError naming the columns
calibration_concat_size with conversations silently ignored ValueError
calibration_dataset_sort / calibration_data_min_length silently ignored applied
unequal conversations at batch_size > 1 ValueError from apply_chat_template padding=True on support_batch_quantize=True models

5. Tests

tests/test_vlm_prepare_dataset_contract_4633.py (96 nodes) discovers every
exported definition with its own prepare_dataset and pins:

Test Invariant
test_pretokenized_rows_never_reach_the_processor 40/45 ids and masks survive; load_processor never called
test_columnar_mapping_is_unpacked_not_rendered_as_key_names tokenizer(texts) mapping keeps its rows
test_conversation_path_rejects_concat_size ValueError names calibration_concat_size
test_batch_size_two_pads_unequal_conversations Cohere/Inkling bs=2 returns one (2, max_len) batch with padding=True
test_discovery_covers_the_models_named_in_the_issue Cohere/HunYuan/Muse/Inkling stay in the parametrization

Red evidence (origin/main @ 504769ea8, new test file copied in):

$ pytest tests/test_vlm_prepare_dataset_contract_4633.py -q
70 failed, 26 passed
  test_pretokenized_rows_never_reach_the_processor       22 failed
  test_columnar_mapping_is_unpacked...                   23 failed
  test_conversation_path_rejects_concat_size             23 failed
  test_batch_size_two_pads_unequal_conversations          2 failed

The pre-tokenized failures are the intended assertion
(AssertionError: Pre-tokenized calibration must not load the multimodal processor); the bs=2 failures are the intended ValueError
(Unable to create tensor ... padding=True).

Green evidence (this branch, after the fix):

$ PYTHONPATH=$PWD pytest tests/test_vlm_prepare_dataset_contract_4633.py -q
96 passed

$ pytest tests/test_vlm_prepare_dataset_contract_4633.py \
    tests/test_vlm_pretokenized_calibration.py \
    tests/test_vlm_mapping_calibration_4308.py \
    tests/test_vlm_multimodal_calibration_4371.py \
    tests/test_vlm_calibration_metadata_columns_4455.py \
    tests/test_calibration_text_and_ids_precedence_4635.py \
    tests/test_prepare_dataset.py -q
279 passed

$ pytest tests/test_multimodal_modality_calibration.py \
    tests/test_multimodal_calibration_replay.py \
    tests/test_hunyuan_ocr_support.py tests/test_apertus1p5_support.py \
    tests/test_qwen2_audio_support.py tests/test_zdtaichu5_support.py \
    tests/models/test_inkling_mm_model.py::test_inkling_calibration_uses_native_multimodal_chat_template \
    tests/models/test_intern_s2_preview.py::test_prepare_dataset_wraps_raw_text_as_chat_messages -q
50 passed, 1 error (pre-existing monkeypatch teardown on object.__new__; same on main)

ruff check gptqmodel docs/eora tests setup.py -> All checks passed.

Real-checkpoint repro (CPU, local HunYuanOCR processor):

main  @504769ea8   rows:     batches=1 tokens=1  ids_preserved=False  (decoded: BOS token only)
main  @504769ea8   columnar: batches=2 tokens=4  ids_preserved=False  (decoded: BOS + "input_ids" + role markers)
this PR            rows:     batches=1 tokens=40 ids_preserved=True
this PR            columnar: batches=1 tokens=40 ids_preserved=True

Known pre-existing failures (also on origin/main, not caused by this PR):
tests/models/test_inkling_mm_model.py 5 nodes (defuser/torchvision env),
TestInklingMMModel::test_inkling_mm_model,
TestInternS2Preview::test_intern_s2_preview (missing sentencepiece),
test_diffusion_gemma_post_quantize_syncs_encoder_layer, and the
object.__new__ monkeypatch teardown errors.

6. Validation env

  • CPU-only tests; no GPU was allocated or timed. OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=4 exported for every run.
  • /opt/venvs/rocm101t/bin/python for tests needing datasets;
    /opt/venvs/cu130t/bin/python for the CUDA-side run
    (test_vlm_prepare_dataset_contract_4633.py + pretokenized: 180 passed).
  • PYTHONPATH=$PWD from the clone root; no installs.

7. Limitations

  • The exact issue snippet needs torchvision for the Cohere Compass video
    processor and a loadable image processor for Muse-Glimmer / Inkling; neither
    venv has torchvision, and the local Muse/Inkling checkpoints do not expose an
    image processor to Transformers 5.22. Those two models are therefore covered
    by the stub-processor contract tests (including the bs=2 crash), not by the
    real checkpoints. HunYuanOCR is covered by both.
  • BaseQwen3VLGPTQ and the MTP replay overrides are documented exceptions; see
    section 3.
  • Model integration tests that download checkpoints were not run; no large
    downloads were made.

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

Labels

None yet

Projects

None yet

1 participant