Skip to content

fix(models): restore native remote-code RoPE and repair load/generate paths (#4093) - #4108

Merged
Qubitium merged 2 commits into
mainfrom
fix/issue-4093-remotecode
Nov 15, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/issue-4093-remotecode

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator

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, .bin conversion normalizes legacy tied keys and stops swallowing the real error, legacy unscaled RoPE keeps its None contract (MiniCPM/MobileLLM, generalized from the Nanbeige special case), native loads restore the rotary buffers transformers 5 leaves uninitialized (the 36x PPL bug), ChatGLM generate() works on native and quantized models, and Klear imports again. Net: 13 files, +999/-111; the docs page docs/transformers-5-compat.md gains section J with the same diagrams and tables.

1. The problem

Item Root cause (on main before this PR) Fix
7 modeling_spark.py:244 reads self.mlp.gate_proj.weight.dtype; AutoNF12HookedLinear (gptqmodel/utils/auto_dtype_cast.py:270) stores nf12_packed/nf12_escapes and has no .weight. Legacy Llama-shaped families also read q_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 in state_dict().
8 LazyTurtle._convert_checkpoint_source_to_safetensors (structure.py:1198) calls save_pretrained without _normalize_legacy_tied_weights_keys, so a list _tied_weights_keys raises AttributeError: '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". Normalize before save (structure.py:1337), and raise a path-qualified RuntimeError chained to the original cause (structure.py:1215).
9 hf.py:1689-1696 nulls rope_scaling; transformers 5 aliases it to rope_parameters and the later backfill (hf.py:1775) refills a default dict; legacy _init_rope indexes ["type"]. Only Nanbeige was special-cased (hf.py:1512). Class-declared policy: _declares_legacy_rope_field() (hf.py:1540) + unscaled check in _normalize_rope_parameters_config_compat (hf.py:1572).
10 Native eval (models/loader.py:1714, plain from_pretrained) never restored constructor-owned non-persistent buffers. transformers 5 materializes them with torch.empty_like in PreTrainedModel._move_missing_keys_from_meta_to_device, and its default _init_weights re-derives rotary buffers only when original_inv_freq exists. Legacy remote classes override _init_weights, so inv_freq (and DeciLM's cos/sin caches) stayed uninitialized. restore_init_owned_rotary_buffers() (structure.py:917), called from BaseQModel.__init__ (models/base.py:745) for every load path.
11 hf.py:1446 puts max_length in attribute_map; transformers 5 _prepare_generation_config then treats it as a modified generation parameter and raises. After that, DynamicCache is not subscriptable by ChatGLM's get_masks, and the remote update hook indexes an all-ones mask transformers 5 replaced with None. Filter max_length from _get_generation_parameters (hf.py:1453), alias num_hidden_layers, and install ChatGLMQModel._patch_generation_compat (definitions/chatglm.py:39).
12 hf.py:982 shims check_model_inputs but not OutputRecorder; modeling_klear.py imports both from transformers.utils.generic. Re-export the real OutputRecorder from transformers.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;
Loading

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;
Loading
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;
Loading
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;
Loading
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;
Loading
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"]
Loading

3. Failure and ambiguity contract

Situation Before After
Native remote rotary buffer uninitialized memory, silent bad PPL restored from constructor template
Meta lazy shell n/a skipped; LazyTurtle restores on materialization
Legacy unscaled RoPE default dict -> KeyError: 'type' both aliases None -> default path
Legacy scaled RoPE dict kept dict kept + legacy type key
Modern/native RoPE dict filled unchanged (class declares rope_parameters)
.bin conversion failure misleading "can't open model path" RuntimeError naming the path, original cause chained
ChatGLM generate() ValueError: max_length, then DynamicCache not subscriptable works without a KV cache
AUTO_NF12 remote .weight read AttributeError dtype/shape/device view, no dense weight

4. 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 4090 GPU-d458708b-c760-bbf1-08fb-8b8803a2157d and AMD R9700 (HIP_VISIBLE_DEVICES=2). Wikitext-2 test split, 40 non-overlapping windows of 512 tokens, bf16, native GPTQModel.load(quantize_config=None).

Item 10 (headline): native remote-code RoPE

Checkpoint Before After Issue's table
amd/Instella-3B-Instruct 704.70 23.06 692 -> 19.3
LGAI-EXAONE/EXAONE-3.0-7.8B-Instruct 366.47 10.19 243 -> 9.0
Deci/DeciLM-7B 1304.01 7.54 574 -> 5.48

ROCm spot check: Instella-3B-Instruct native PPL 23.02 after the fix. Nanbeige4.2-3B native PPL is 28.4428 on both origin/main and 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_nf12

Before (real checkpoint):

AttributeError: 'AutoNF12HookedLinear' object has no attribute 'weight'
  modeling_spark.py:244 -> forward_executor.py:431

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.1204613149 vs off 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 cause AttributeError: 'list' object has no attribute 'keys', swallowed). After: QUANTIZE OK on CUDA and ROCm.

Item 9: MiniCPM-2B / MobileLLM load

Before: KeyError: 'type' for openbmb/MiniCPM-2B-dpo-bf16. After: LOAD OK MiniCPMForCausalLM; MobileLLM-1B LOAD OK MobileLLMForCausalLM (CUDA and ROCm).

Item 11: ChatGLM generate()

Before (native chatglm3-6b and the tiny from-config model, both gm.generate and model.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 quantized chatglm3-6b saved and reloaded also returns (1, 7) through both gm.generate and model.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

Area File Purpose
AUTO_NF12 gptqmodel/utils/auto_dtype_cast.py source weight contract on the hooked linear
Loader/checkpoint gptqmodel/utils/structure.py tied-key normalization, surfaced conversion error, shared template builder, rotary restore
Model base gptqmodel/models/base.py call the rotary restore after after_model_load
Config compat gptqmodel/utils/hf.py generalized legacy RoPE policy, ChatGLM aliases, OutputRecorder shim
ChatGLM gptqmodel/models/definitions/chatglm.py transformers-5 generation compat
Docs docs/transformers-5-compat.md, README.md section J with flows/tables, linked from README
Tests tests/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.py regression coverage per item

6. Tests

New/updated tests. Each item has at least one test that fails on origin/main before the fix; the two guard tests are marked (guard).

Test Invariant
tests/test_remote_code_rotary_restore.py (6) fp64 oracle for legacy inv_freq/cos/sin, meta-shell skip, native-style skip, idempotence, clean state_dict
tests/test_hf_config_compat.py::test_normalize_hf_config_compat_clears_unscaled_legacy_rope MiniCPM/MobileLLM/Nanbeige unscaled RoPE stays None (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) modern remote configs keep rope_parameters
tests/test_hf_config_compat.py::test_normalize_chatglm_config_exposes_aliases_without_generation_leak aliases available, filtered from _get_generation_parameters
tests/test_hf_config_compat.py::test_patch_transformers_remote_code_compat_shims_output_recorder generic.OutputRecorder is the real class
tests/test_lazy_turtle_conversion_mapping.py::test_bin_conversion_normalizes_legacy_tied_weights_keys normalization happens before save_pretrained
tests/test_lazy_turtle_conversion_mapping.py::test_maybe_create_surfaces_construction_error path-qualified RuntimeError with chained cause
tests/test_spark2_5_support.py::test_auto_nf12_hooked_linear_exposes_source_weight_contract dtype/shape/device view, 1-element storage, absent from state_dict
tests/models/test_chatglm.py::test_chatglm_generate_after_config_compat tiny from-config generate()
tests/models/test_chatglm.py::test_chatglm_native_generate real native generate()
tests/models/test_instella.py::test_instella_native_rotary_inv_freq native inv_freq equals the fp64 oracle

Commands and results (CUDA venv, CUDA_VISIBLE_DEVICES=GPU-d458708b-c760-bbf1-08fb-8b8803a2157d):

PYTHONPATH=$PWD /opt/venvs/cu130t/bin/python -m pytest \
  tests/test_remote_code_rotary_restore.py tests/test_hf_config_compat.py \
  tests/test_nested_rope_config_compat.py tests/test_lazy_turtle_conversion_mapping.py \
  tests/test_spark2_5_support.py tests/test_auto_nf12_excluded_layers.py \
  tests/test_auto_module_decoder.py -q
-> 176 passed, 2 failed, 3 skipped
   the 2 failures are pre-existing on origin/main (110136fff):
   test_normalize_hf_config_compat_restores_legacy_cache_length_helpers
   test_resolve_trust_remote_code_overrides_when_native_support_exists
cd tests/models && PYTHONPATH=$PWD/.. /opt/venvs/cu130t/bin/python -m pytest \
  test_chatglm.py test_instella.py -k 'generate_after_config_compat or native_rotary' -q
-> 2 passed

ROCm (HIP_VISIBLE_DEVICES=2):

/opt/venvs/rocm101t/bin/python -m pytest tests/test_remote_code_rotary_restore.py \
  tests/test_nested_rope_config_compat.py tests/test_lazy_turtle_conversion_mapping.py \
  tests/test_spark2_5_support.py tests/test_hf_config_compat.py -q
-> 118 passed, 2 failed (same two pre-existing failures), 1 skipped

Issue snippets:

Spark-X2.5-4B GPTQ auto_nf12   -> QUANTIZE OK (CUDA, ROCm)
MiniCPM-2B-128k GPTQ 4-bit    -> QUANTIZE OK (CUDA, ROCm)
MiniCPM-2B-dpo / MobileLLM-1B -> LOAD OK (CUDA, ROCm)
chatglm3-6b native/4-bit      -> generate (1, 6) / (1, 7) (CUDA); (1, 6) (ROCm)
Klear remote modeling import  -> KLEAR IMPORT OK

ruff check gptqmodel docs/eora tests setup.py -> All checks passed! (after merging origin/main).

7. Limitations / reviewer notes

  • ChatGLM generate() runs without a KV cache (use_cache=False on generation_config); decode re-prefills each step. This is the only way to keep the legacy tuple-cache remote forward working without reimplementing its cache.
  • The native rotary restore rebuilds buffers from the module constructor; a remote rotary module whose constructor arguments are not stored as attributes is left to LazyTurtle's materialization-time restore.
  • Item 10's regression test pins the numerics (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_freq runs in the model zoo and fails on origin/main.
  • Pre-existing, unrelated failures observed in this environment (also fail on 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.py device-map cases need a single GPU visible (CUDA_VISIBLE_DEVICES pin) because the shared host exposes an RTX 5090 next to the 4090s.

… 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.
@Qubitium
Qubitium merged commit cd0ba61 into main Nov 15, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/issue-4093-remotecode branch November 15, 2026 09:04
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.
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