Skip to content

[BUG] Calibration rows with both messages and input_ids are still re-tokenized from messages (#4638 incomplete): chat-template truncation to 256 silently becomes 3033 tokens #4670

Closed

Description

@Qubitium

Found on main @ 12c1273 (CPU-only path, reproduced on Linux with transformers 5.22 / datasets).

What is wrong

#4638 (fix for #4635) made explicit input_ids take precedence over a text column. The messages column has the same problem and was left out. gptqmodel/utils/calibration.py:621-633 (prepare_calibration_dataset) still checks messages first, so a row that has both messages and input_ids is re-rendered through the chat template and re-tokenized from the full conversation. The caller's input_ids / attention_mask are thrown away without a message, along with their truncation, max_length, and special-token choices.

These rows come from the standard chat pre-tokenization recipe:
ds.map(lambda r: tok.apply_chat_template(r["messages"], tokenize=True, return_dict=True, truncation=True, max_length=N))
keeps the messages column next to the new input_ids/attention_mask. ds[:] and list(ds) keep it as well. This is exactly the situation #4638's comment describes for text ("the normal output of Dataset.map(tokenizer, truncation=True, ...)"). The VLM prepare_dataset overrides now route through the same helper (#4648), so they inherit the same behavior.

Repro

from types import SimpleNamespace
from datasets import Dataset
from transformers import AutoTokenizer
from gptqmodel.utils.calibration import prepare_calibration_dataset

tok = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")
long = "The quick brown fox jumps over the lazy dog. " * 300
ds = Dataset.from_list([{"messages": [{"role": "user", "content": long}, {"role": "assistant", "content": "ok"}]}] * 4)
ds = ds.map(lambda r: tok.apply_chat_template(r["messages"], tokenize=True, return_dict=True, truncation=True, max_length=256))
print("columns:", ds.column_names, "provided input_ids len:", len(ds[0]["input_ids"]))
qm = SimpleNamespace(tokenizer=tok, support_batch_quantize=True,
                     model=SimpleNamespace(config=SimpleNamespace(max_position_embeddings=32768)))
for name, data in (("Dataset", ds), ("ds[:] columnar", ds[:]), ("list(ds)", list(ds))):
    out = prepare_calibration_dataset(qm, data, batch_size=1)
    print(f"{name}: calibration lengths -> {[int(b['input_ids'].shape[-1]) for b in out]}")
out = prepare_calibration_dataset(qm, ds.remove_columns("messages"), batch_size=1)
print(f"same rows without messages column -> {[int(b['input_ids'].shape[-1]) for b in out]}")

Output:

columns: ['messages', 'input_ids', 'attention_mask'] provided input_ids len: 256
Dataset: calibration lengths -> [3033, 3033, 3033, 3033]
ds[:] columnar: calibration lengths -> [3033, 3033, 3033, 3033]
list(ds): calibration lengths -> [3033, 3033, 3033, 3033]
same rows without messages column -> [256, 256, 256, 256]

The user capped every sample at 256 tokens, but calibration runs on 3033 tokens per sample: 12x the activation and Hessian capture work and memory. Removing the unrelated messages column changes the result.

Suggested fix

Apply #4638's rule to every source column. When a row has non-None input_ids, use them (with attention_mask) before messages or text. Move the input_ids check above the messages branch at calibration.py:621. Optionally log once at debug level when a source column is ignored for that reason.

Test that should have caught it

tests/test_calibration_text_and_ids_precedence_4635.py covers only text + input_ids. Add the messages + input_ids case for per-row mappings, Dataset and the columnar ds[:] form.

Severity

Medium. Calibration silently ignores the caller's truncation for chat datasets, so the quantization is not the one requested, and capture memory and time grow with the uncapped length (up to max_position_embeddings).

🤖 Generated with Claude Code

Activity

  1. Qubitium commented on Nov 17, 2026

    @Qubitium
    CollaboratorAuthor

    Taking this. It is the messages half of #4638, which I merged: explicit input_ids will win over messages (and text) in every source branch of the shared calibration helper, with the Dataset.map(apply_chat_template, truncation=True) shape covered for per-row, Dataset and columnar ds[:] inputs.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions