Repository navigation
fix(models): restore native remote-code RoPE and repair load/generate paths (#4093) - #4108
Merged
Merged
Conversation
… paths (#4093) Items 7-12 of #4093: - AUTO_NF12: AutoNF12HookedLinear exposes a one-element zero-stride view of the source weight (dtype, shape, device) so Spark-X2.5's `gate_proj.weight.dtype` read and the legacy `q_proj.weight.dtype` casts work during quantization. The view stays out of state_dict(). - LazyTurtle: normalize legacy list `_tied_weights_keys` before the .bin -> safetensors save, and surface the construction error instead of the misleading "can't open model path ... for offload_to_disk". - RoPE: generalize the Nanbeige special case to any legacy remote config that declares `rope_scaling` (MiniCPM-2B, MobileLLM): unscaled RoPE keeps both aliases None so `_init_rope` takes the default path. - Native loads: restore constructor-owned non-persistent rotary buffers that transformers 5 materialized with empty_like. Wikitext-2 PPL (40x512, bf16): Instella-3B-Instruct 704.7 -> 23.1, EXAONE-3.0-7.8B 366.5 -> 10.2, DeciLM-7B 1304.0 -> 7.5. - ChatGLM: keep max_length/num_hidden_layers as attribute_map aliases but filter max_length from `_get_generation_parameters`, and install a transformers-5 generation compat hook (no DynamicCache, mask/position updates) so native and quantized `generate()` work. - Klear: re-export `OutputRecorder` into transformers.utils.generic next to the existing check_model_inputs shim. Docs: docs/transformers-5-compat.md section J with flows, before/after table, and the measured PPL table; linked from README.md.
This was referenced Nov 15, 2026
Qubitium
added a commit
that referenced
this pull request
Nov 15, 2026
…cy generate adapter (#4121) (#4132) 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 #4093 (items 7-12)
TL;DR
Six remote-code failures (items 7-12) are fixed in one branch: the AUTO_NF12 packed linear now exposes the source-weight contract remote forwards read,
.binconversion normalizes legacy tied keys and stops swallowing the real error, legacy unscaled RoPE keeps itsNonecontract (MiniCPM/MobileLLM, generalized from the Nanbeige special case), native loads restore the rotary buffers transformers 5 leaves uninitialized (the 36x PPL bug), ChatGLMgenerate()works on native and quantized models, and Klear imports again. Net: 13 files, +999/-111; the docs pagedocs/transformers-5-compat.mdgains section J with the same diagrams and tables.1. The problem
mainbefore this PR)modeling_spark.py:244readsself.mlp.gate_proj.weight.dtype;AutoNF12HookedLinear(gptqmodel/utils/auto_dtype_cast.py:270) storesnf12_packed/nf12_escapesand has no.weight. Legacy Llama-shaped families also readq_proj.weight.dtype._source_weight_contract()(auto_dtype_cast.py:270) returns a one-element zero-stride view with the source dtype/shape/device; assigned at:311. Not instate_dict().LazyTurtle._convert_checkpoint_source_to_safetensors(structure.py:1198) callssave_pretrainedwithout_normalize_legacy_tied_weights_keys, so a list_tied_weights_keysraisesAttributeError: 'list' object has no attribute 'keys'.maybe_create(structure.py:1082) swallowed it and the loader reported only "can't open model path ... for offload_to_disk".structure.py:1337), and raise a path-qualifiedRuntimeErrorchained to the original cause (structure.py:1215).hf.py:1689-1696nullsrope_scaling; transformers 5 aliases it torope_parametersand the later backfill (hf.py:1775) refills a default dict; legacy_init_ropeindexes["type"]. Only Nanbeige was special-cased (hf.py:1512)._declares_legacy_rope_field()(hf.py:1540) + unscaled check in_normalize_rope_parameters_config_compat(hf.py:1572).models/loader.py:1714, plainfrom_pretrained) never restored constructor-owned non-persistent buffers. transformers 5 materializes them withtorch.empty_likeinPreTrainedModel._move_missing_keys_from_meta_to_device, and its default_init_weightsre-derives rotary buffers only whenoriginal_inv_freqexists. Legacy remote classes override_init_weights, soinv_freq(and DeciLM's cos/sin caches) stayed uninitialized.restore_init_owned_rotary_buffers()(structure.py:917), called fromBaseQModel.__init__(models/base.py:745) for every load path.hf.py:1446putsmax_lengthinattribute_map; transformers 5_prepare_generation_configthen treats it as a modified generation parameter and raises. After that,DynamicCacheis not subscriptable by ChatGLM'sget_masks, and the remote update hook indexes an all-ones mask transformers 5 replaced withNone.max_lengthfrom_get_generation_parameters(hf.py:1453), aliasnum_hidden_layers, and installChatGLMQModel._patch_generation_compat(definitions/chatglm.py:39).hf.py:982shimscheck_model_inputsbut notOutputRecorder;modeling_klear.pyimports both fromtransformers.utils.generic.OutputRecorderfromtransformers.utils.output_capturing(hf.py:996).Old flow that produced the silent PPL bug:
flowchart TD A["native GPTQModel.load(quantize_config=None)"] --> B["HF from_pretrained"] B --> C["meta init + empty_like non-persistent buffers"] C --> D{"remote class overrides _init_weights?"} D -- Yes --> E["inv_freq keeps uninitialized memory"] D -- No --> F["default _init_weights restores it"] E --> G["evaluate native baseline:<br/>PPL 692 issue / 704.7 measured"] classDef failure fill:#ffe8e8,stroke:#b30000,color:#111; class E,G failure;2. The new flow
flowchart TD A["from_pretrained or LazyTurtle shell"] --> B["transformers 5 meta init"] B --> C["_move_missing_keys_from_meta_to_device"] C --> D["BaseQModel.__init__"] D --> E["restore_init_owned_rotary_buffers"] E --> F{"inv_freq buffer and not handled<br/>by default _init_weights?"} F -- No --> G["leave untouched"] F -- Yes --> H["_build_module_init_template"] H --> I["register_buffer inv_freq, cos_cached, sin_cached"] I --> J["native eval, quantization, quantized reload"] G --> J classDef failure fill:#ffe8e8,stroke:#b30000,color:#111; X["meta shell: LazyTurtle restores on materialization"] -.-> F class X failure;flowchart TD A["normalize_hf_config_compat"] --> B{"class __init__ declares rope_scaling<br/>and not rope_parameters?"} B -- No --> C["fill default rope_parameters"] B -- Yes --> D{"per-layer dict or scaled rope?"} D -- Yes --> E["keep dict and add legacy type key"] D -- No --> F["rope_scaling = None<br/>rope_parameters = None"] F --> G["remote _init_rope default path"] C --> H["RotaryEmbedding reads rope_type"] X["KeyError type or ValueError Unknown RoPE scaling type"] -.-> F classDef failure fill:#ffe8e8,stroke:#b30000,color:#111; class X failure;flowchart TD A["ChatGLMQModel.after_model_load"] --> B["_patch_generation_compat"] B --> C["generation_config.use_cache = False"] B --> D["replace _update_model_kwargs_for_generation"] C --> E["generate skips DynamicCache"] D --> F["None mask stays None, position_ids advance"] E --> G["remote forward: past_key_values None"] F --> G G --> H["tokens returned"] I["attribute_map max_length and num_hidden_layers"] --> J["remote __init__ reads config.max_length"] I --> K["_get_generation_parameters drops max_length"] X["ValueError max_length or DynamicCache not subscriptable"] -.-> G classDef failure fill:#ffe8e8,stroke:#b30000,color:#111; class X failure;flowchart TD A["LazyTurtle.maybe_create"] --> B{"safetensors weight map?"} B -- Yes --> G["lazy checkpoint source"] B -- No --> C["_convert_checkpoint_source_to_safetensors"] C --> D["from_pretrained full CPU load"] D --> E["_normalize_legacy_tied_weights_keys"] E --> F["save_pretrained safe_serialization"] F --> G C --> X["construction error"] X --> Y["RuntimeError with path and chained cause"] classDef failure fill:#ffe8e8,stroke:#b30000,color:#111; class Y failure;flowchart TD A["AutoNF12HookedLinear.from_linear"] --> B["pack_original: nf12_packed and nf12_escapes"] B --> C["_source_weight_contract"] C --> D["zeros 1 element as_strided with zero strides"] D --> E["layer.weight: dtype, shape, device"] E --> F["modeling_spark.py:244 reads weight.dtype"] E --> G["1 element storage, absent from state_dict"]3. Failure and ambiguity contract
KeyError: 'type'None-> default pathtypekeyrope_parameters).binconversion failureRuntimeErrornaming the path, original cause chainedgenerate()ValueError: max_length, thenDynamicCachenot subscriptable.weightreadAttributeError4. Measured before/after
All numbers are from this branch; "before" is the same command on
origin/main(718256fd7), or the same build with the new restore disabled where noted. Hardware: RTX 4090GPU-d458708b-c760-bbf1-08fb-8b8803a2157dand AMD R9700 (HIP_VISIBLE_DEVICES=2). Wikitext-2 test split, 40 non-overlapping windows of 512 tokens, bf16, nativeGPTQModel.load(quantize_config=None).Item 10 (headline): native remote-code RoPE
amd/Instella-3B-InstructLGAI-EXAONE/EXAONE-3.0-7.8B-InstructDeci/DeciLM-7BROCm spot check: Instella-3B-Instruct native PPL
23.02after the fix.Nanbeige4.2-3Bnative PPL is28.4428on bothorigin/mainand this branch (the generalized policy reproduces the old Nanbeige branch exactly).Item 7: Spark-X2.5-4B GPTQ under the default
auto_dtype_cast=auto_nf12Before (real checkpoint):
After:
QUANTIZE OK auto_nf12(CUDA and ROCm). Accuracy on the real checkpoint (64 calibration docs, 4-bit g128, saved and reloaded, logits vs bf16 reference on 8 tokens):auto_nf12 gptq_err=0.1204613149vsoff gptq_err=0.1204613149— identical, so the NF12 cast is lossless. Independent per-group RTN baseline on the tiny Spark fixture:0.1784.Item 8: MiniCPM-2B-128k (
.bin-only, list_tied_weights_keys)Before:
RuntimeError: Loader: can't open model path ... for offload_to_disk(real causeAttributeError: 'list' object has no attribute 'keys', swallowed). After:QUANTIZE OKon CUDA and ROCm.Item 9: MiniCPM-2B / MobileLLM load
Before:
KeyError: 'type'foropenbmb/MiniCPM-2B-dpo-bf16. After:LOAD OK MiniCPMForCausalLM; MobileLLM-1BLOAD OK MobileLLMForCausalLM(CUDA and ROCm).Item 11: ChatGLM
generate()Before (native
chatglm3-6band the tiny from-config model, bothgm.generateandmodel.generate):ValueError: You have modified the pretrained model configuration ... {'max_length': 8192}(tiny:{'max_length': 64}).After: native
chatglm3-6b(1, 6); a 4-bit quantizedchatglm3-6bsaved and reloaded also returns(1, 7)through bothgm.generateandmodel.generate. ROCm native returns(1, 6).Item 12: Klear import
Before:
ImportError: cannot import name 'OutputRecorder' from 'transformers.utils.generic'. After:KLEAR IMPORT OK KlearMoeForCausalLM.5. Change inventory
gptqmodel/utils/auto_dtype_cast.pygptqmodel/utils/structure.pygptqmodel/models/base.pyafter_model_loadgptqmodel/utils/hf.pygptqmodel/models/definitions/chatglm.pydocs/transformers-5-compat.md,README.mdtests/test_remote_code_rotary_restore.py(new),tests/test_hf_config_compat.py,tests/test_lazy_turtle_conversion_mapping.py,tests/test_spark2_5_support.py,tests/models/test_chatglm.py,tests/models/test_instella.py6. Tests
New/updated tests. Each item has at least one test that fails on
origin/mainbefore the fix; the two guard tests are marked (guard).tests/test_remote_code_rotary_restore.py(6)inv_freq/cos/sin, meta-shell skip, native-style skip, idempotence, cleanstate_dicttests/test_hf_config_compat.py::test_normalize_hf_config_compat_clears_unscaled_legacy_ropeNone(the Nanbeige parameter already passed via the old special case)tests/test_hf_config_compat.py::test_normalize_hf_config_compat_keeps_modern_remote_rope_parameters(guard)rope_parameterstests/test_hf_config_compat.py::test_normalize_chatglm_config_exposes_aliases_without_generation_leak_get_generation_parameterstests/test_hf_config_compat.py::test_patch_transformers_remote_code_compat_shims_output_recordergeneric.OutputRecorderis the real classtests/test_lazy_turtle_conversion_mapping.py::test_bin_conversion_normalizes_legacy_tied_weights_keyssave_pretrainedtests/test_lazy_turtle_conversion_mapping.py::test_maybe_create_surfaces_construction_errorRuntimeErrorwith chained causetests/test_spark2_5_support.py::test_auto_nf12_hooked_linear_exposes_source_weight_contractstate_dicttests/models/test_chatglm.py::test_chatglm_generate_after_config_compatgenerate()tests/models/test_chatglm.py::test_chatglm_native_generategenerate()tests/models/test_instella.py::test_instella_native_rotary_inv_freqinv_freqequals the fp64 oracleCommands and results (CUDA venv,
CUDA_VISIBLE_DEVICES=GPU-d458708b-c760-bbf1-08fb-8b8803a2157d):ROCm (
HIP_VISIBLE_DEVICES=2):Issue snippets:
ruff check gptqmodel docs/eora tests setup.py->All checks passed!(after mergingorigin/main).7. Limitations / reviewer notes
generate()runs without a KV cache (use_cache=Falseongeneration_config); decode re-prefills each step. This is the only way to keep the legacy tuple-cache remote forward working without reimplementing its cache.inv_freq/cos/sin against an fp64 oracle) rather than a PPL threshold; the full PPL table above is the acceptance evidence.tests/models/test_instella.py::test_instella_native_rotary_inv_freqruns in the model zoo and fails onorigin/main.origin/main):tests/test_hf_config_compat.py::test_normalize_hf_config_compat_restores_legacy_cache_length_helpers,tests/test_hf_config_compat.py::test_resolve_trust_remote_code_overrides_when_native_support_exists.tests/test_auto_nf12_excluded_layers.pydevice-map cases need a single GPU visible (CUDA_VISIBLE_DEVICESpin) because the shared host exposes an RTX 5090 next to the 4090s.