Repository navigation
[BUG] loader: GPTQModel.load(<dir without tokenizer files>) silently accepts the empty 1-token tokenizer that transformers 5 builds: quantize() fails with a misleading "samples shorter than min_length" error, generate() crashes with a reshape error, and the documented quantize(tokenizer=...) override saves pad_token="!" / pad_token_id=0 #6361
Description
Summary
A very common fine-tuning flow writes only the model: peft_model.merge_and_unload().save_pretrained(out_dir), or trainer.save_model() without a tokenizer. The resulting directory has config.json, generation_config.json and safetensors shards, but no tokenizer.json, tokenizer_config.json or vocab.json. The same happens with quantized repos that publish weights only.
Under transformers 5, AutoTokenizer.from_pretrained(out_dir) no longer raises. It returns a Qwen2Tokenizer with one token ({'<|endoftext|>': 0}) that encodes every string to []. GPTQModel.load (load_hf_tokenizer -> Tokenicer) accepts this tokenizer without checking it against the model (vocab_size=151936). Three things follow:
model.quantize(CalibrationConfig(dataset=texts))tokenizes all 64 c4 rows to[]and then raisesValueError: Calibration dataset is empty after CalibrationConfig.prepare_dataset removed all samples (for example, every input_ids was shorter than CalibrationConfig.min_length). Lower CalibrationConfig.min_length or provide longer calibration samples.That message sends the user after their data, not the missing tokenizer.- On a quantized checkpoint without tokenizer files,
model.generate("The capital of France is")crashes withRuntimeError: cannot reshape tensor of 0 elements into shape [1, 0, -1, 64]. - During load, the empty tokenizer's pad id (0) is written into the model:
config.pad_token_id = 0andgeneration_config.pad_token_id = 0. Token 0 is"!"in the real Qwen2.5 vocab. The fix the docs describe for a wrong or missing tokenizer isquantize(..., tokenizer=AutoTokenizer.from_pretrained(base))(docs/calibration-config.md: "tokenizer=... replaces the model's tokenizer ... but is also whatsave()writes"). When it is applied, Tokenicer re-derives the pad token from the already-mutatedmodel_config.pad_token_id=0. The saved checkpoint then haspad_token: "!"intokenizer_config.jsonandpad_token_id: 0in bothconfig.jsonandgeneration_config.json. With the tokenizer files present, the same model savespad_token: "<|endoftext|>"/pad_token_id: 151643.
Introduced by
Pre-existing since the Transformers 5 port (d2dfb93, #4620). Under transformers 4.x (checked with 4.44.2), AutoTokenizer.from_pretrained raised OSError: Can't load tokenizer for ... for a directory without tokenizer files. Under transformers 5 it builds an empty tokenizer, and the GPT-QModel loader does not validate it. Still present at be14824.
Location
gptqmodel/models/loader.py:2935-2944:tokenizer = load_hf_tokenizer(model_local_path, model_config=config, ...)with no vocabulary or usability checkgptqmodel/utils/hf.py:1047load_hf_tokenizer(...): passes the empty tokenizer toTokenicer.load(..., model_config=...), which alignsmodel_config.pad_token_idwith itgptqmodel/models/base.py:3490-3500quantize(tokenizer=...):Tokenicer.load(tokenizer, model_config=self.model.config)reuses the mutatedpad_token_id=0
Reproduction (ran it, be14824, transformers 5.23, Qwen2.5-0.5B-Instruct)
import json, torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from gptqmodel import GPTQModel
from gptqmodel.quantization import GPTQConfig, CalibrationConfig
# fine-tune/merge output saved without the tokenizer
m = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct", dtype=torch.bfloat16)
m.save_pretrained("notok", max_shard_size="200MB") # config.json, generation_config.json, 5 shards, index
texts = [...] # 64 c4 rows, 259-672 tokens each
q = GPTQModel.load("notok", quantize_config=GPTQConfig(bits=4, group_size=128))
tok = q.tokenizer.tokenizer
print(type(tok).__name__, len(tok), tok.get_vocab(), tok("The capital of France is Paris.")["input_ids"])
print(q.model.config.pad_token_id, q.model.generation_config.pad_token_id)
q.quantize(CalibrationConfig(dataset=texts))Output:
Qwen2Tokenizer 1 {'<|endoftext|>': 0} []
0 0
WARN Quantize: 64 calibration items were removed because every row was empty, all-padding, or <= 10 non-padding tokens. ...
ValueError: Calibration dataset is empty after CalibrationConfig.prepare_dataset removed all samples (for example, every input_ids was shorter than CalibrationConfig.min_length). Lower CalibrationConfig.min_length or provide longer calibration samples.
Documented override:
q = GPTQModel.load("notok", quantize_config=GPTQConfig(bits=4, group_size=128))
q.quantize(CalibrationConfig(dataset=texts), tokenizer=AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct"))
q.save("notok_q")notok_q compared with the same model quantized from a directory that has tokenizer files:
tokenizer_config.json pad_token: "!" vs "<|endoftext|>"
generation_config.json pad_token_id: 0 vs 151643
config.json pad_token_id: 0 vs 151643
Quantized checkpoint without tokenizer files (weights, config, generation_config and quantize_config copied from a good GPTQ save):
tokenizer Qwen2Tokenizer len 1 model vocab 151936
generate raised RuntimeError cannot reshape tensor of 0 elements into shape [1, 0, -1, 64] because the unspecified dimension size -1 can be any value and is ambiguous
Expected vs actual
- Expected: when the model directory has no usable tokenizer,
GPTQModel.load(orquantize/generate) raises a clear error, for example "no tokenizer files in ; passtokenizer=or save the tokenizer next to the model". Passingtokenizer=toquantize()then produces the same checkpoint as a directory with tokenizer files. - Actual: the load succeeds with a 1-token tokenizer that encodes everything to
[]. quantize fails with an error that blames calibration sample length, and generate fails with a reshape error. The documentedtokenizer=override savespad_token="!"/pad_token_id=0into all three config files because the empty tokenizer had already rewrittenconfig.pad_token_id.
Suggested fix
- In
load_hf_tokenizer(or right after it in the loader), reject a text tokenizer whose vocabulary is far smaller thanmodel_config.vocab_size(e.g.len(tokenizer) <= 1, or notokenizer*.json/vocab*files and an empty vocab). Raise an actionable error, or fall back totokenizer=Noneand letquantize()requiretokenizer=. - Do not write a pad id from such a tokenizer into
model.config/generation_config. Whenquantize(tokenizer=...)replaces the tokenizer, derive the pad token from the new tokenizer's ownpad_token, not from amodel_config.pad_token_idthat the previous tokenizer set.
Activity
fix(loader): reject tokenizer-less checkpoints instead of loading an …
fix(models): stop rewriting a checkpoint's generation pad id on load (#…
fix(loader): keep a checkpoint's generation pad id when quantize_conf…