Skip to content

fix(mlx): accept generate() inputs and honor dynamic on export (#4076) - #4083

Merged
Qubitium merged 2 commits into
mainfrom
fix/issue-4076-mlx
Nov 15, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/issue-4076-mlx

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #4076

TL;DR

Three MLX defects are fixed in utils/mlx.py plus the validation plumbing:
the runtime adapter now consumes the prompts= / input_ids= contract that
BaseQModel.generate() emits and maps max_new_tokens, EOS, stop, seed and
do_sample; export/convert uses the exact numpy repack on any OS instead of
requantizing; and the requantization fallback now applies dynamic through a
quant_predicate. The runtime Metal gate stays where it belongs
(validate_once), not on the host-side repack.

Reference page: docs/mlx-runtime.md (linked from
README.md).

Root cause

1. generate() inputs and options (utils/mlx.py, models/base.py)

BaseQModel._generate_with_runtime (models/base.py:2841-2848) normalizes
inputs to prompts= for strings/lists and input_ids= for tensors. The MLX
adapter only read prompt (utils/mlx.py:498) and raised
MLX requires prompts to be provided; max_tokens defaulted from
kwargs.pop("max_tokens", 256) (utils/mlx.py:506) and ignored
max_new_tokens; eos_token_id, stop, seed and do_sample were dropped.

2. Export ignores dynamic and always requantizes off macOS

_convert_gptq_to_mlx_weights called quantize_model(...) without a
quant_predicate (utils/mlx.py:487), so -: exclusions were quantized and
+: overrides lost their bits/group. The exact packed transfer was gated by
_MlxLinearContract.validate_once() (Darwin + arm64 + Metal) through
source_compatible/validate (nn_modules/qlinear/mlx.py:53, :87), even
though pack_source/repack_gptq are pure numpy.

3. KeyError: 'bits' for a valid override

utils/mlx.py:405-410 read config["bits"] for every non-empty override and
printed the dynamic dict from library code.

The new flow

Generation:

flowchart TD
    A["BaseQModel.generate(inputs, kwargs)"] --> B{"_runtime_generate set?"}
    B -- no --> C["Transformers model.generate"]
    B -- yes --> D["_generate_with_runtime(runtime_generate, inputs, kwargs)"]
    D --> E{"inputs type"}
    E -- "str or list[str]" --> F["kwargs.prompts = inputs"]
    E -- "mapping" --> G["merge mapping into kwargs"]
    E -- "tensor or None" --> H["kwargs.input_ids = inputs"]
    F --> I["mlx_generate(model, tokenizer, kwargs)"]
    G --> I
    H --> I
    I --> J{"prompt / prompts / input_ids present?"}
    J -- no --> K["ValueError: MLX requires prompts or input_ids"]
    J -- yes --> L["_mlx_prompt_list -> list of str or token lists"]
    L --> M["map max_new_tokens or max_tokens"]
    M --> N["map seed, eos_token_id, stop, do_sample, sampler"]
    N --> O["mlx_lm.generate per prompt"]
    O --> P{"one prompt?"}
    P -- yes --> Q["return str"]
    P -- no --> R["return list[str]"]
Loading

Export/convert:

flowchart TD
    A["GPTQModel.export(path, target, 'mlx')"] --> B["convert_gptq_to_mlx_weights"]
    B --> C{"dynamic override valid?"}
    C -- "bits unsupported" --> D["ValueError"]
    C -- ok --> E["_packed_mlx_weights(model, config, lm_head_name)"]
    E --> F{"all packed source layers transferable?"}
    F -- yes --> G["repack_gptq / repack_awq / repack_gguf in numpy"]
    G --> H["mlx_config.quantization carries per-layer bits/group"]
    H --> I["_gptqmodel_custom_mlx_runtime or _gptqmodel_group16_runtime"]
    F -- no --> J["quantize_model(..., quant_predicate=_mlx_quant_predicate)"]
    J --> K{"dynamic_get(path)"}
    K -- "False (-: exclusion)" --> L["return False: layer stays float16"]
    K -- "None (no rule)" --> M["return True: default bits/group"]
    K -- "override dict" --> N["return bits/group override"]
    L --> O["MLX-LM checkpoint"]
    M --> O
    N --> O
    I --> O
Loading

Before/after mechanisms:

Mechanism Before After
Runtime prompt key mlx_generate popped only prompt (utils/mlx.py:498) accepts prompt, prompts, input_ids; tensors become token lists
Token budget max_tokens = kwargs.pop("max_tokens", 256) (:506) max_new_tokens wins, legacy max_tokens still works
Sampling options eos_token_id, stop, seed, do_sample dropped mapped to EOS ids, stop trimming, mx.random.seed, greedy/temperature sampler
Repack platform gate source_compatible called validate -> validate_once Darwin/Metal (nn_modules/qlinear/mlx.py:53, :87) _validate_source skips the runtime platform gate; pack_source stays numpy
dynamic in requantization no quant_predicate (utils/mlx.py:487) _mlx_quant_predicate maps -:/+: rules
Override without bits config["bits"] (utils/mlx.py:405-410) config.get("bits", gptq_config["bits"]); debug print removed

Fail-before / pass-after

All commands were run with PYTHONPATH=$PWD from the clone root and
CUDA_VISIBLE_DEVICES=""; MLX runtime used mlx-cpu 0.32.4 +
mlx-lm 0.32.2 on Linux.

Item 1

Before (main @ 39b62765e):

generate('Hello')                          -> ValueError: MLX requires prompts to be provided
generate(input_ids=tensor)                 -> ValueError: MLX requires prompts to be provided
generate(prompts=['Hello'])                -> ValueError: MLX requires prompts to be provided
generate(prompt='Hello', max_new_tokens=5) -> mlx_lm max_tokens=256
generate(prompt='Hello', max_tokens=5)     -> mlx_lm max_tokens=5

After:

generate('Hello')                          -> 'ok'; prompt='Hello'
generate(input_ids=tensor)                 -> 'ok'; prompt=[1, 2, 3]
generate(prompts=['Hello'])                -> 'ok'; prompt='Hello'
generate(prompt='Hello', max_new_tokens=5) -> 'ok'; max_tokens=5
generate(prompt='Hello', max_tokens=5)     -> 'ok'; max_tokens=5

Real mlx-cpu run through BaseQModel.generate on a tiny Qwen2 model:
STREAM_TOKENS 5 for max_new_tokens=5, and
generate(input_ids=torch.tensor([[3, 4]])) -> 'b'.

Item 2

Before (Qwen2.5-0.5B-Instruct RTN 4-bit g128,
dynamic={"-:.*mlp\\.down_proj": {}, "+:.*self_attn\\.o_proj": {"bits": 8, "group_size": 32}}):

EXPORTED_QUANTIZATION {"bits": 4, "group_size": 128, "mode": "affine"}
model.layers.0.self_attn.o_proj: 4-bit g128 rel_err_vs_dense=0.1104
model.layers.0.mlp.down_proj:    4-bit g128 rel_err_vs_dense=0.1089

After:

INFO  MLX: transferred source weights without requantization
LAYER0_CFG {"model.layers.0.self_attn.o_proj": {"bits": 8, "group_size": 32, "mode": "affine"}}
model.layers.0.self_attn.o_proj keys ['linear.biases', 'linear.scales', 'linear.weight']
model.layers.0.self_attn.o_proj: 8-bit g32 rel_err_vs_dense=0.0051
model.layers.0.mlp.down_proj keys ['weight']
model.layers.0.mlp.down_proj: fp16 rel_err_vs_dense=0.0000

The exported affine words are decoded independently in numpy and match the
source layer's own quantized weight (tiny-model test: 0.0053 exported vs 0.0054
source; excluded module equals the source fp16 weight).

Item 3

Before: convert(dynamic without bits) -> KeyError: 'bits' (plus the stray
print(gptq_config["dynamic"])). After:

ITEM3_OK {"bits": 4, "group_size": 128, "mode": "affine", "model.layers.0.self_attn.o_proj": {"bits": 4, "group_size": 32, "mode": "affine"}}

Tests

New regression tests in tests/test_mlx_packing.py (all fail on main, pass
after):

  • test_mlx_generate_through_base_generate_maps_inputs
  • test_mlx_generate_maps_seed_do_sample_eos_and_stop
  • test_mlx_quant_predicate_honors_dynamic
  • test_mlx_export_transfers_packed_dynamic_layout_without_requantization
  • test_mlx_requantization_honors_dynamic
CUDA_VISIBLE_DEVICES="" PYTHONPATH=$PWD /opt/venvs/mlx/bin/python -m pytest \
  tests/test_mlx_packing.py -k "quant_predicate or packed_dynamic or requantization_honors or through_base_generate or seed_do_sample" -q
-> 5 passed, 228 deselected

Full tests/test_mlx_packing.py on this Linux host (no Metal):

-> 148 passed, 82 failed, 3 skipped

The 82 failures are all RuntimeError: [metal_kernel] No Metal back-end
custom group-16 kernels. Baseline on main: 57 passed, 168 failed, 3 skipped;
no test that passes on main fails after this change (86 previously failing
layout tests now pass on Linux).

Related MLX files (test_mlx_rtn_quantization.py, test_mlx_fp8_native.py,
test_mlx_gguf.py, test_mlx_awq_variants.py, test_mlx_paro.py,
test_mlx_dense_methods.py): 98 passed, 127 failed, 81 skipped; baseline
35 passed, 190 failed, 81 skipped; no regressions, remaining failures are
Metal/bf16-on-CPU environment limits.

Related non-MLX validation tests:
tests/test_format_conversion_flow.py tests/test_inmemory_qzero_format.py tests/test_finalize_module_lookup.py tests/kernels/test_awq_cpu_fused_post_init.py
-> 16 passed, 3 errors (the 3 errors need a CUDA device: RuntimeError: No CUDA GPUs are available).

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

Hardware / environment

CPU only: Linux x86_64, Python 3.13, mlx-cpu 0.32.4, mlx-lm 0.32.2,
torch 2.15.0+cu132 (no GPU used; CUDA_VISIBLE_DEVICES=""). The MLX Metal
custom-kernel paths were not run here; the runtime contract was exercised
through mlx_lm.generate on the CPU stream.

Limitations

  • stop trims the returned text after generation, matching the OpenAI
    server's existing _strip_stop; it does not stop the token loop early.
  • Batched prompts are generated sequentially and returned as list[str].
    num_return_sequences is not mapped (pre-existing, out of scope).
  • The custom-runtime checkpoint layout emitted by the exact transfer is
    unchanged; the issue's "plausible, not verified" stock-mlx_lm.load note is
    out of scope.

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