Repository navigation
fix(models): run the pre-load hook on native loads and share one legacy generate adapter (#4121) - #4132
Merged
Conversation
…cy generate adapter (#4121) Item 2: the native (quantize_config=None) branch of models/loader.py never called before_model_load, so the mask-helper shims that OuroQModel/Spark2_5QModel install there were missing for native generate() (TypeError: create_causal_mask() got an unexpected keyword argument 'input_embeds'). All three load paths now go through _call_before_model_load. Item 3: #4108 fixed transformers-5 generate() for ChatGLM only. DeciLM/Baichuan2 index the cache as a tuple, MiniCPM-2B-dpo reads seen_tokens, EXAONE-3 reads cache_position.shape, Nanbeige4.2 calls get_max_length() on an empty cache, and PanGu-alpha's config has no num_hidden_layers. install_legacy_generation_compat installs one adapter for every remote-code class: an empty cache is passed as None, cache_position is synthesized from next_sequence_length, DynamicCache regains tuple indexing and seen_tokens, get_usable_length treats -1 as unbounded, and any num_layers/n_layer/n_layers config gets the num_hidden_layers alias.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Part of #4121 (items 2, 3)
TL;DR
Two defects, one theme: a remote-code family was only wired into the load path (or the generate path) that #4108 happened to test. Native loads now run
before_model_loadon all three branches, and transformers-5generate()gets one shared legacy-cache adapter instead of a ChatGLM-only patch. 15 files, +680/−10;docs/transformers-5-compat.mdgains section K with the same diagrams.1. Item 2 — the native load branch skipped
before_model_loadmodels/loader.pycalls the definition hook in the quantize branch and the quantized-reload branch, but thequantize_config is None(native evaluation) branch went straight tofrom_pretrained:flowchart TD A["GPTQModel.load(path, quantize_config=None)"] --> B{"native branch<br/>models/loader.py:1823"} B --> C["_call_before_model_load(cls, load_quantized_model=False)"] C --> D["cls.before_model_load(cls, ...)"] D --> E["definition patches the remote module:<br/>create_causal_mask keyword names"] E --> F["_hf_loader_from_pretrained_with_dynamic_module_retry"] F --> G["BaseQModel.__init__<br/>install_legacy_generation_compat"] G --> H["generate() / forward()"] B -.->|"before this change"| X["hook skipped:<br/>mask helper unchanged"] X -.-> Y["TypeError: input_embeds"] style X fill:#fdd,stroke:#c00 style Y fill:#fdd,stroke:#c00OuroQModel.before_model_load(gptqmodel/models/definitions/ouro.py:44) andSpark2_5QModel.before_model_load(spark2_5.py:42) adaptinput_embeds/cache_positionfor the transformers mask helper. Because the native branch skipped them, an unquantized model could not run a single forward. The same hook does config or remote-class work foragnes,brumby,dots3_note,ernie4_5_vl_moe,minicpm_o,minicpmv(code read only, not run).All three call sites now share one helper (
models/loader.py:886), so a definition cannot be wired into one path and forgotten in another:flowchart LR A["from_pretrained native<br/>loader.py:1823"] --> H["_call_before_model_load"] B["from_pretrained quantize<br/>loader.py:1911"] --> H C["from_quantized reload<br/>loader.py:2504"] --> H H --> D["cls.before_model_load(cls, load_quantized_model=...)"] D --> E["definition patches guard themselves,<br/>so repeated loads are idempotent"]Fail-before / pass-after
Ouro-1.4B,
GPTQModel.load(path, quantize_config=None, trust_remote_code=True, device="cuda:0"), thengm.generate(**tok("The capital of France is"), max_new_tokens=12, do_sample=False):Spark-X2.5-4B, same call:
The new regression test reproduces the issue text exactly on
origin/main@a8c7675:ROCm (
HIP_VISIBLE_DEVICES=2): OuroGENERATE OK: 'The capital of France is Paris...'.2. Item 3 — the ChatGLM-only generate fix became one shared adapter
#4108 fixed transformers-5
generate()for ChatGLM by disabling its KV cache (gptqmodel/models/definitions/chatglm.py:39). Every other legacy family hits the same boundary from a different call site, because transformers 5 handsprepare_inputs_for_generationaDynamicCacheon the very first step while transformers 4 passedNone, and the old tuple/attribute interface is gone:mainTypeError: 'DynamicCache' object is not subscriptablepast_key_values[0][0].shape[2]transformers_v4_35_2__modeling_llama.py:1084modeling_baichuan.pyAttributeError: 'DynamicCache' object has no attribute 'seen_tokens'past_key_values.seen_tokensmodeling_minicpm.py:1248AttributeError: 'NoneType' object has no attribute 'shape'cache_positionis a tensormodeling_exaone.py:1465ValueError: max() iterable argument is emptyget_max_length()isNonebefore prefilltransformers/cache_utils.py:1708AttributeError: 'GPTPanguConfig' object has no attribute 'num_hidden_layers'transformers/integrations/heterogeneity/configuration_utils.py:216The fix is one adapter installed from
BaseQModel.__init__(models/base.py:774), plus cache-side surface in_patch_transformers_remote_code_compat(utils/hf.py:858). No family name appears in it:flowchart TD A["BaseQModel.__init__"] --> B["install_legacy_generation_compat(model)<br/>gptqmodel/utils/hf.py"] B --> C{"class module starts with<br/>transformers_modules.?"} C -- No --> Z["leave native transformers classes alone"] C -- Yes --> D{"class defines its own<br/>prepare_inputs_for_generation?"} D -- No --> Z D -- Yes --> E["wrap prepare_inputs_for_generation"] E --> F{"cache sequence length == 0?"} F -- Yes --> G["pass past_key_values=None"] F -- No --> H["pass the Cache:<br/>tuple indexing and seen_tokens work"] G --> I["synthesize cache_position<br/>from next_sequence_length"] H --> I I --> J["remote legacy prepare_inputs_for_generation"] style Z fill:#eef,stroke:#446Cache-side surface, installed once per process:
DynamicCache.__getitem__utils/hf.py:1118cache[0][0].shape[2]; an unwritten layer raisesIndexErrorinstead of returning fake stateCache.seen_tokensutils/hf.py:1098get_seq_length()Cache.get_usable_lengthutils/hf.py:1061-1sentinel as unbounded; previously returned-1 - new_seq_lengthand producedkv_seq_len = -1The layer-count alias is generic (
utils/hf.py:1703): any remote config declaringnum_layers/n_layer/n_layersbut notnum_hidden_layersgets anattribute_mapentry, so the serialized checkpoint keeps its own field name. ChatGLM's alias now calls the same helper instead of its own copy (utils/hf.py:1495).Fail-before / pass-after (native
GPTQModel.load(..., quantize_config=None)+ greedy generate)Quantized path (DeciLM-7B-instruct, 4-bit g128, 32 calibration samples, saved and reloaded with
BACKEND.TORCH):PanGu-alpha, config path used by the loader (
prepare_remote_code_compat+AutoModelForCausalLM), because its local snapshot has notokenizer_config.jsonand this venv has nosentencepiece:ROCm (
HIP_VISIBLE_DEVICES=2): NanbeigeGENERATE OK: 'The capital of France is Paris...'.3. Test coverage: ARC alone hid this
quantize_and_evaluate()never calledgenerate(), so every one of these families could quantize, score ARC, and still be unable to produce one token.ModelTestnow has anASSERT_INFERENCEopt-in that runsassertInferencebefore the model is released (tests/models/model_test.py:2097), andassertInferenceresolves its prompt from the instance so a family can override it (tests/models/model_test.py:809).Opted in:
test_ouro.py,test_spark2_5.py,test_deci.py,test_exaone.py,test_nanbeige42.py,test_minicpm.py,test_baichuan.py,test_pangu_alpha.py.test_ouro.pyandtest_spark2_5.pyalso gain the native-load generate test from item 2, andtest_minicpm.pygainsTestMiniCpmDpofor the checkpoint that actually readsseen_tokens.tests/test_legacy_generation_compat.pypins the adapter contract without a GPU or a large checkpoint: empty cache becomesNone,cache_positioncomes fromnext_sequence_length,cache[0][0]/seen_tokens/get_usable_length, the layer-count alias, idempotence, and a tiny real Ouro checkpoint loaded through the native branch.4. Validation
The 2 failures are pre-existing on
origin/main@a8c7675(verified in a clean worktree):test_normalize_hf_config_compat_restores_legacy_cache_length_helpersfails with'DummyCache' object has no attribute 'get_max_length'on both trees, andtest_resolve_trust_remote_code_overrides_when_native_support_existsfails identically.tests/models/test_chatglm.pycannot run in this venv at all (ImportError: ... sentencepiece), identically on base and branch.Hardware: NVIDIA RTX 4090
GPU-d458708b-c760-bbf1-08fb-8b8803a2157d; AMD R9700 viaHIP_VISIBLE_DEVICES=2only. The RTX 5090 was never used.5. Change inventory
gptqmodel/models/loader.py_call_before_model_load; native branch now runs the hookgptqmodel/utils/hf.pyinstall_legacy_generation_compat, cache legacy surface, generic layer-count aliasgptqmodel/models/base.pytests/test_legacy_generation_compat.pytests/models/model_test.pyASSERT_INFERENCEopt-in; instance-resolved prompttests/models/test_{ouro,spark2_5,deci,exaone,nanbeige42,minicpm,baichuan,pangu_alpha}.pydocs/transformers-5-compat.md,README.md6. Limits
sentencepiece, so its remote modeling module cannot import (tests/models/test_baichuan.pyalready skips for that reason). Itspast_key_values[0][0]pattern is the same one DeciLM exercises.sentencepiecereason (pre-existing, identical on base). Its alias path is covered by a unit test intests/test_legacy_generation_compat.py.tokenizer_config.json, soAutoTokenizerreturnsNonebefore any model code runs; item 3's config fix is demonstrated through the loader's ownprepare_remote_code_compatpath instead.IndexErrorrather than returning zero tensors.