Repository navigation
fix(mlx): accept generate() inputs and honor dynamic on export (#4076) - #4083
Merged
Merged
Conversation
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.
Fixes #4076
TL;DR
Three MLX defects are fixed in
utils/mlx.pyplus the validation plumbing:the runtime adapter now consumes the
prompts=/input_ids=contract thatBaseQModel.generate()emits and mapsmax_new_tokens, EOS, stop, seed anddo_sample; export/convert uses the exact numpy repack on any OS instead ofrequantizing; and the requantization fallback now applies
dynamicthrough aquant_predicate. The runtime Metal gate stays where it belongs(
validate_once), not on the host-side repack.Reference page:
docs/mlx-runtime.md(linked fromREADME.md).Root cause
1.
generate()inputs and options (utils/mlx.py,models/base.py)BaseQModel._generate_with_runtime(models/base.py:2841-2848) normalizesinputstoprompts=for strings/lists andinput_ids=for tensors. The MLXadapter only read
prompt(utils/mlx.py:498) and raisedMLX requires prompts to be provided;max_tokensdefaulted fromkwargs.pop("max_tokens", 256)(utils/mlx.py:506) and ignoredmax_new_tokens;eos_token_id,stop,seedanddo_samplewere dropped.2. Export ignores
dynamicand always requantizes off macOS_convert_gptq_to_mlx_weightscalledquantize_model(...)without aquant_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) throughsource_compatible/validate(nn_modules/qlinear/mlx.py:53,:87), eventhough
pack_source/repack_gptqare pure numpy.3.
KeyError: 'bits'for a valid overrideutils/mlx.py:405-410readconfig["bits"]for every non-empty override andprinted 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]"]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 --> OBefore/after mechanisms:
mlx_generatepopped onlyprompt(utils/mlx.py:498)prompt,prompts,input_ids; tensors become token listsmax_tokens = kwargs.pop("max_tokens", 256)(:506)max_new_tokenswins, legacymax_tokensstill workseos_token_id,stop,seed,do_sampledroppedmx.random.seed, greedy/temperature samplersource_compatiblecalledvalidate->validate_onceDarwin/Metal (nn_modules/qlinear/mlx.py:53,:87)_validate_sourceskips the runtime platform gate;pack_sourcestays numpydynamicin requantizationquant_predicate(utils/mlx.py:487)_mlx_quant_predicatemaps-:/+:rulesbitsconfig["bits"](utils/mlx.py:405-410)config.get("bits", gptq_config["bits"]); debug print removedFail-before / pass-after
All commands were run with
PYTHONPATH=$PWDfrom the clone root andCUDA_VISIBLE_DEVICES=""; MLX runtime usedmlx-cpu 0.32.4+mlx-lm 0.32.2on Linux.Item 1
Before (main @
39b62765e):After:
Real
mlx-cpurun throughBaseQModel.generateon a tiny Qwen2 model:STREAM_TOKENS 5formax_new_tokens=5, andgenerate(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}}):After:
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 strayprint(gptq_config["dynamic"])). After:Tests
New regression tests in
tests/test_mlx_packing.py(all fail on main, passafter):
test_mlx_generate_through_base_generate_maps_inputstest_mlx_generate_maps_seed_do_sample_eos_and_stoptest_mlx_quant_predicate_honors_dynamictest_mlx_export_transfers_packed_dynamic_layout_without_requantizationtest_mlx_requantization_honors_dynamicFull
tests/test_mlx_packing.pyon this Linux host (no Metal):The 82 failures are all
RuntimeError: [metal_kernel] No Metal back-endcustom 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; baseline35 passed, 190 failed, 81 skipped; no regressions, remaining failures areMetal/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).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 Metalcustom-kernel paths were not run here; the runtime contract was exercised
through
mlx_lm.generateon the CPU stream.Limitations
stoptrims the returned text after generation, matching the OpenAIserver's existing
_strip_stop; it does not stop the token loop early.list[str].num_return_sequencesis not mapped (pre-existing, out of scope).unchanged; the issue's "plausible, not verified" stock-
mlx_lm.loadnote isout of scope.