Skip to content

fix(mlx): translate transformers-5 rope_parameters into the keys mlx-lm reads (#4607) - #4617

Merged
Qubitium merged 1 commit into
mainfrom
fix/issue-4607-mlx-rope-parameters
Nov 17, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/issue-4607-mlx-rope-parameters

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #4607

TL;DR

transformers 5 saves RoPE as rope_parameters and omits the flat rope_theta / rope_scaling pair that most mlx-lm architectures read, so every Llama/Qwen2/Gemma export or in-process MLX load silently ran with rope_theta=10000 and no scaling. A new pure-Python translation (gptqmodel/utils/mlx_rope.py) is applied at both MLX config-construction sites, and it refuses or warns instead of silently defaulting. Net: +110 in the new module, +12/−5 in utils/mlx.py, 11 tests, one docs section.

1. Root cause

_packed_mlx_weights built mlx_config = deepcopy(config) and the requant path passed config straight to _get_classes / quantize_model. auto.py:1255 then writes that dict as the exported config.json. transformers 5 to_dict() produces:

{"rope_parameters": {"rope_type": "llama3", "factor": 32.0, ..., "rope_theta": 500000.0}}

with no top-level rope_theta / rope_scaling. mlx-lm's llama, qwen2, gemma2, gemma3_text, phi3, olmo2 and granite args only read the flat pair, so the key is dropped and their rope_theta=10000.0 default applies.

Old mechanism Replacement
mlx_config = deepcopy(config) (utils/mlx.py) mlx_config = _mlx_model_config(config) — deep copy + translation
Requant path passed config to _get_classes / quantize_model Same translated mlx_config
Nested rope_parameters forwarded untouched rope_theta and non-default scaling copied to the flat keys; the nested dict is kept
Per-layer-type dicts Collapsed when every layer type agrees; ValueError otherwise
rope_parameters without rope_theta Explicit warning naming the config, instead of accepting mlx-lm's 10000

qwen3 is left untouched because its mlx-lm ModelArgs reads the nested form directly.

2. Mapping

Source (rope_parameters) Emitted
rope_theta top-level rope_theta
rope_type != default, plus factor, high_freq_factor, low_freq_factor, original_max_position_embeddings, partial_rotary_factor top-level rope_scaling
rope_type: default no rope_scaling
per-layer-type dicts (full_attention / sliding_attention) collapsed when uniform, ValueError when they differ
rope_parameters kept

Nested text_config (Gemma3 VL wrappers) is normalized too.

3. Before / after (behavioral)

The test file models mlx-lm's ModelArgs.from_dict contract — unknown keys filtered, rope_theta default 10000, rope_scaling default None:

raw transformers-5 config     -> rope_theta 10000.0, rope_scaling None      # the silent fallback
translated config             -> rope_theta 500000.0, rope_scaling {'rope_type': 'llama3', 'factor': 32.0, ...}

4. Tests

tests/test_mlx_rope_parameters_4607.py (Linux, no MLX needed — the translation is pure config manipulation):

Test Invariant
test_llama3_rope_theta_and_scaling_reach_the_flat_mlx_keys theta 500000 + full llama3 scaling; 10000 absent; source config not mutated; nested form kept
test_qwen2_keeps_its_non_default_theta 1000000 preserved, no scaling invented
test_gemma2_theta_is_the_configured_value_not_a_fallback 10000 is the source value and no scaling marker is emitted
test_gemma3_text_config_is_normalized_too nested text_config handled
test_uniform_per_layer_rope_parameters_collapse / test_conflicting_..._are_rejected uniform collapses; conflicting raises
test_missing_theta_warns_instead_of_silently_defaulting explicit warning
test_qwen3_keeps_the_native_nested_form untouched
test_normalization_is_idempotent_and_serializable stable + JSON-safe
test_mlx_lm_consumes_the_translated_config consumer-level: raw config falls back to 10000/None, translated config gives 500000 + scaling
test_both_mlx_config_builders_use_the_translation export and runtime paths both call the builder

5. Validation

pytest tests/test_mlx_rope_parameters_4607.py -q
-> 11 passed

pytest tests/test_mlx_rope_parameters_4607.py tests/test_mlx_nf12.py \
  tests/test_mlx_nf12_row_dispatch_4478.py -q
-> 12 passed, 1 skipped

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

What was NOT executed: no MLX/Metal runtime or Apple hardware here (mlx/mlx_lm are not installed), so mlx_lm.load(...) and m.args.rope_theta were not run, and no exported model was executed. The tests pin the config translation and the consumer contract; they do not prove MLX numerics.

Detection evidence, stated plainly: with the new module absent the test file cannot be collected, which is not valid red evidence. With only utils/mlx.py reverted (module present, call sites not wired) test_both_mlx_config_builders_use_the_translation fails — that is wiring evidence, not behavioral. The behavioral defect is demonstrated by the raw-config assertion in test_mlx_lm_consumes_the_translated_config (raw transformers-5 config → 10000/None), which holds before and after by design.

6. Apple-device verification

On an Apple Silicon host:

python -m venv .venv && source .venv/bin/activate
pip install -U mlx mlx-lm transformers torch
python - <<'PY'
import json
from gptqmodel import GPTQModel
from mlx_lm import load

src = "ModelCloud/Llama-3.2-1B-Instruct-AWQ-bit4-g128-symFasle-descFalse"  # transformers-5 saved
GPTQModel.export(src, "out", "mlx")
cfg = json.load(open("out/config.json"))
print("config:", cfg.get("rope_theta"), cfg.get("rope_scaling"))
model, _ = load("out")
print("mlx args:", model.args.rope_theta, model.args.rope_scaling)
PY

Expected: config: 500000.0 {'rope_type': 'llama3', 'factor': 32.0, ...} and mlx args: 500000.0 {...}. Before this fix the same script printed 10000.0 None. Repeat for a Qwen2 checkpoint (theta 1000000) and a Gemma2/Gemma3 checkpoint (its configured theta, no scaling).

7. Reviewer notes

  • Limitations: no MLX execution, so accuracy/logit improvement is not measured here. The issue's logits comparison (max|diff| 1.73 → 0.097) is the reference expectation, not a result of this PR.
  • The translation only adds flat keys; it never removes rope_parameters, so architectures that read the nested form keep working. qwen3 is skipped entirely to avoid double-applying scaling.
  • A non-uniform per-layer-type RoPE config now raises at export/load time instead of exporting a config that mlx-lm would silently ignore; this is a deliberate behavior change for that case only.
  • gptqmodel/utils/mlx.py still cannot be imported without MLX (it uses mx.float16 at module scope, unrelated to this change), which is why the translation lives in its own module and is tested without MLX.

@Qubitium
Qubitium merged commit bb36e7f into main Nov 17, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/issue-4607-mlx-rope-parameters branch November 17, 2026 02:46
Qubitium added a commit that referenced this pull request Nov 17, 2026
) (#4684)

#4617 translated transformers-5 `rope_parameters` into the flat
`rope_theta`/`rope_scaling` pair, but refused any per-layer-type split because
that pair cannot express one. Every Gemma 3 checkpoint is exactly that layout
(`sliding_attention` theta 10000, `full_attention` theta 1000000), so
`GPTQModel.export(..., "mlx")` and `backend=MLX` loading raised before writing
a single weight.

mlx-lm does represent the split, just not through `rope_parameters`:
`gemma3_text.ModelArgs` builds the global layers from `rope_theta` plus
`rope_scaling` and the sliding layers from `rope_local_base_freq`. Add an
explicit per-architecture table and map onto those keys, so the 4B+ models also
keep their `full_attention` linear factor 8 instead of silently dropping it.

Two neighbouring gaps in the same translation:

- `gemma4_text` also emits per-layer-type `rope_parameters` in transformers 5
  and was refused for the same reason. Its mlx-lm `ModelArgs` selects
  `rope_parameters[layer_key]` itself, so it joins the native-passthrough set.
- The refusal stays where a mapping cannot represent the config: a
  sliding-attention scaling entry (mlx-lm builds those layers from a bare base)
  and layer-type keys a mapping does not cover.

Tests (tests/test_mlx_rope_parameters_4607.py):
- the `gemma3_text` fixture that pinned the rejection now pins the mapping, with
  Gemma 3 1B (no scaling) and 4B+ (global linear factor 8) cases;
- `gemma3n` text_config and `gemma4_text` passthrough cases;
- both refusal paths;
- consumer-level assertions, including against the real
  `mlx_lm.models.gemma3_text.ModelArgs` when mlx-lm is installed.

Red evidence with the pre-fix module restored: 8 failed, 11 passed. Green after
the fix: 19 passed; with the export-contract and method-selection suites 46
passed, 1 skipped.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant