Skip to content

fix(models): run the pre-load hook on native loads and share one legacy generate adapter (#4121) - #4132

Merged
Qubitium merged 1 commit into
mainfrom
fix/issue-4121-native-load-generate
Nov 15, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/issue-4121-native-load-generate

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator

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_load on all three branches, and transformers-5 generate() gets one shared legacy-cache adapter instead of a ChatGLM-only patch. 15 files, +680/−10; docs/transformers-5-compat.md gains section K with the same diagrams.

1. Item 2 — the native load branch skipped before_model_load

models/loader.py calls the definition hook in the quantize branch and the quantized-reload branch, but the quantize_config is None (native evaluation) branch went straight to from_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:#c00
Loading

OuroQModel.before_model_load (gptqmodel/models/definitions/ouro.py:44) and Spark2_5QModel.before_model_load (spark2_5.py:42) adapt input_embeds/cache_position for 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 for agnes, 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"]
Loading

Fail-before / pass-after

Ouro-1.4B, GPTQModel.load(path, quantize_config=None, trust_remote_code=True, device="cuda:0"), then gm.generate(**tok("The capital of France is"), max_new_tokens=12, do_sample=False):

before: GENERATE FAIL: TypeError create_causal_mask() got an unexpected keyword argument 'input_embeds'. Did you mean 'inputs_embeds'?
after:  GENERATE OK: 'The capital of France is Paris.\n\nThe capital of France is Paris.\n'

Spark-X2.5-4B, same call:

before: GENERATE FAIL: TypeError create_causal_mask() got an unexpected keyword argument 'input_embeds'. Did you mean 'inputs_embeds'?
after:  GENERATE OK: 'The capital of France is Paris.\nující\n\n\n\n\n\n\n\n'

The new regression test reproduces the issue text exactly on origin/main @ a8c7675:

$ pytest tests/models/test_ouro.py::TestOuro::test_ouro_native_generate_runs_before_model_load_hook
base:   FAILED TypeError: create_causal_mask() got an unexpected keyword argument 'input_embeds'
        /root/.cache/huggingface/modules/transformers_modules/Ouro_hyphen_1_dot_4B/be7d84acc14fbbaa/modeling_ouro.py:577
branch: 1 passed

ROCm (HIP_VISIBLE_DEVICES=2): Ouro GENERATE 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 hands prepare_inputs_for_generation a DynamicCache on the very first step while transformers 4 passed None, and the old tuple/attribute interface is gone:

Family Failure on main transformers-4 expectation Root cause
DeciLM-7B-instruct TypeError: 'DynamicCache' object is not subscriptable past_key_values[0][0].shape[2] remote transformers_v4_35_2__modeling_llama.py:1084
Baichuan2-7B-Chat same (not exercised here, see limits) same remote modeling_baichuan.py
MiniCPM-2B-dpo AttributeError: 'DynamicCache' object has no attribute 'seen_tokens' past_key_values.seen_tokens remote modeling_minicpm.py:1248
EXAONE-3.0-7.8B AttributeError: 'NoneType' object has no attribute 'shape' cache_position is a tensor remote modeling_exaone.py:1465
Nanbeige4.2-3B ValueError: max() iterable argument is empty get_max_length() is None before prefill transformers/cache_utils.py:1708
PanGu-alpha-2.6B AttributeError: 'GPTPanguConfig' object has no attribute 'num_hidden_layers' layer-count alias transformers/integrations/heterogeneity/configuration_utils.py:216

The 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:#446
Loading

Cache-side surface, installed once per process:

Symbol Added at Why
DynamicCache.__getitem__ utils/hf.py:1118 cache[0][0].shape[2]; an unwritten layer raises IndexError instead of returning fake state
Cache.seen_tokens utils/hf.py:1098 property over get_seq_length()
Cache.get_usable_length utils/hf.py:1061 treats transformers 5's -1 sentinel as unbounded; previously returned -1 - new_seq_length and produced kv_seq_len = -1

The layer-count alias is generic (utils/hf.py:1703): any remote config declaring num_layers/n_layer/n_layers but not num_hidden_layers gets an attribute_map entry, 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)

DeciLM-7B-instruct  before: TypeError 'DynamicCache' object is not subscriptable
                    after:  'The capital of France is Paris.\n\nQuestion: What is the capital'
EXAONE-3.0-7.8B     before: AttributeError 'NoneType' object has no attribute 'shape'
                    after:  'The capital of France is Paris.\n\n10. **What is'
MiniCPM-2B-dpo-bf16 before: AttributeError 'DynamicCache' object has no attribute 'seen_tokens'
                    after:  'TheĠcapitalĠofĠFranceĠisĠParis,ĠwhichĠisĠtheĠ'
Nanbeige4.2-3B      before: ValueError max() iterable argument is empty
                    after:  'The capital of France is Paris.\n</think>\n\nHere are a few'

Quantized path (DeciLM-7B-instruct, 4-bit g128, 32 calibration samples, saved and reloaded with BACKEND.TORCH):

before: QUANTIZED GENERATE FAIL: TypeError 'DynamicCache' object is not subscriptable
after:  QUANTIZED GENERATE OK: 'The capital of France is Paris.\n bekan'

PanGu-alpha, config path used by the loader (prepare_remote_code_compat + AutoModelForCausalLM), because its local snapshot has no tokenizer_config.json and this venv has no sentencepiece:

before: GENERATE FAIL: AttributeError 'GPTPanguConfig' object has no attribute 'num_hidden_layers'
after:  num_hidden_layers: 32
        GENERATE OK (1, 8)

ROCm (HIP_VISIBLE_DEVICES=2): Nanbeige GENERATE OK: 'The capital of France is Paris...'.

3. Test coverage: ARC alone hid this

quantize_and_evaluate() never called generate(), so every one of these families could quantize, score ARC, and still be unable to produce one token. ModelTest now has an ASSERT_INFERENCE opt-in that runs assertInference before the model is released (tests/models/model_test.py:2097), and assertInference resolves 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.py and test_spark2_5.py also gain the native-load generate test from item 2, and test_minicpm.py gains TestMiniCpmDpo for the checkpoint that actually reads seen_tokens.

tests/test_legacy_generation_compat.py pins the adapter contract without a GPU or a large checkpoint: empty cache becomes None, cache_position comes from next_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

$ ruff check gptqmodel docs/eora tests setup.py
All checks passed!

$ pytest tests/test_legacy_generation_compat.py tests/test_hf_config_compat.py \
         tests/test_ouro_support.py tests/test_looped_decoder_capture.py \
         tests/test_spark2_5_support.py tests/test_pangu_alpha_replay.py
2 failed, 80 passed, 1 skipped

$ HIP_VISIBLE_DEVICES=2 pytest tests/test_legacy_generation_compat.py \
         tests/test_ouro_support.py tests/test_spark2_5_support.py tests/test_pangu_alpha_replay.py
27 passed

The 2 failures are pre-existing on origin/main @ a8c7675 (verified in a clean worktree): test_normalize_hf_config_compat_restores_legacy_cache_length_helpers fails with 'DummyCache' object has no attribute 'get_max_length' on both trees, and test_resolve_trust_remote_code_overrides_when_native_support_exists fails identically. tests/models/test_chatglm.py cannot 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 via HIP_VISIBLE_DEVICES=2 only. The RTX 5090 was never used.

5. Change inventory

File Purpose
gptqmodel/models/loader.py _call_before_model_load; native branch now runs the hook
gptqmodel/utils/hf.py install_legacy_generation_compat, cache legacy surface, generic layer-count alias
gptqmodel/models/base.py install the adapter on every load path
tests/test_legacy_generation_compat.py adapter contract + tiny real Ouro native load
tests/models/model_test.py ASSERT_INFERENCE opt-in; instance-resolved prompt
tests/models/test_{ouro,spark2_5,deci,exaone,nanbeige42,minicpm,baichuan,pangu_alpha}.py generate coverage
docs/transformers-5-compat.md, README.md section K + link

6. Limits

  • Baichuan2-7B-Chat was not exercised end to end: neither venv has sentencepiece, so its remote modeling module cannot import (tests/models/test_baichuan.py already skips for that reason). Its past_key_values[0][0] pattern is the same one DeciLM exercises.
  • ChatGLM's end-to-end tests cannot run here for the same sentencepiece reason (pre-existing, identical on base). Its alias path is covered by a unit test in tests/test_legacy_generation_compat.py.
  • PanGu-alpha's local snapshot lacks tokenizer_config.json, so AutoTokenizer returns None before any model code runs; item 3's config fix is demonstrated through the loader's own prepare_remote_code_compat path instead.
  • The adapter deliberately leaves native transformers classes untouched and does not fake cache state: an unwritten layer still raises IndexError rather than returning zero tensors.

…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant