From 70e40e38fed43fb5e933adfbff01f521055425c4 Mon Sep 17 00:00:00 2001 From: Kenya Nara Date: Tue, 24 Nov 2026 17:52:11 +0900 Subject: [PATCH 1/3] feat(inkling2): load Inkling 2 checkpoints saved by mlx-vlm mlx-vlm's inkling2 model (inkling2 and inkling2_loop) saves checkpoints under its own module names with split tensors, for example orcarouter/Inkling-2-Mini-abliterated-MLX, and the Inkling 2 loader only mapped the published layout, so they failed with "parameters not in model". Undo mlx-vlm's sanitize in the loader: fuse the attention projections along their rows (quantizing the unquantized sink and dynamic conv rows to the fused spec), re-interleave gate/up into w13, convert weight_scale_2 back to global_scale, and map message queries and vision names. Rewrite the per-module quantization keys onto the runtime paths in load_config so nn.quantize builds matching modules. Published-layout checkpoints and oQ outputs keep their paths. Co-Authored-By: Claude Opus 5.5 --- omlx/patches/inkling2/loader.py | 282 ++++++++++++++++++++++++++ omlx/utils/model_loading.py | 29 +++ tests/test_inkling2_mlx_vlm_layout.py | 278 +++++++++++++++++++++++++ 3 files changed, 589 insertions(+) create mode 100644 tests/test_inkling2_mlx_vlm_layout.py diff --git a/omlx/patches/inkling2/loader.py b/omlx/patches/inkling2/loader.py index f4e7803f22..bd1004a932 100644 --- a/omlx/patches/inkling2/loader.py +++ b/omlx/patches/inkling2/loader.py @@ -81,6 +81,10 @@ def _loop_message_queries(queries: dict, core: range, out: dict) -> None: def sanitize_weights(model, weights: dict) -> tuple[dict, dict]: """Returns the mapped weights and the routed-expert format per layer.""" + if is_mlx_vlm_layout(weights): + # Expert carriers come from the per-path ``quantization`` that + # ``mlx_vlm_quantization`` rewrote, so no per-layer formats here. + return sanitize_mlx_vlm_weights(model, weights), {} if not is_original_layout(weights): return weights, {} args = model.args.text @@ -186,3 +190,281 @@ def sanitize_weights(model, weights: dict) -> tuple[dict, dict]: if loop_queries: _loop_message_queries(loop_queries, args.loop_core, out) return out, formats + + +# mlx-vlm layout ----------------------------------------------------------- +# +# mlx-vlm's ``inkling2`` model renames the published checkpoint and splits its +# fused tensors (``Model.sanitize`` in mlx_vlm/models/inkling2/inkling2.py). +# Quantized builds made with mlx-vlm, such as orcarouter's abliterated MLX +# release, ship in that layout. The maps below undo mlx-vlm's sanitize so the +# same files load on this runtime, with their quantized codes left as they are. + +_VLM_TEXT = "language_model." +_VLM_LAYER = "language_model.model.layers." +_VLM_VISION = "vision_tower." +# (mlx-vlm, runtime) substrings of the vision tower names; the runtime keeps +# the published names under ``backbone``. +_VLM_VISION_RENAMES = ( + ("pre_layernorm.", "ln_pre."), + (".layernorm_before.", ".ln_1."), + (".layernorm_after.", ".ln_2."), + (".lambda_1.", ".ls_1.gamma."), + (".lambda_2.", ".ls_2.gamma."), + (".mlp.fc1.", ".mlp.c_fc."), + (".mlp.fc2.", ".mlp.c_proj."), +) +_VLM_SLIDING_IN_PROJ = ( + "q_proj", + "k_proj", + "v_proj", + "r_proj", + "gate_proj", + "sink_proj", +) +_VLM_GLOBAL_Q_PROJ = ("q_proj", "r_proj", "gate_proj", "sink_proj") +_QUANT_SUFFIXES = ("weight", "scales", "biases") + + +def is_mlx_vlm_layout(weights: dict) -> bool: + return any(k.startswith(_VLM_LAYER) for k in weights) + + +def is_mlx_vlm_quantization(quantization: dict) -> bool: + """Whether ``quantization`` still names mlx-vlm's modules. + + Only mlx-vlm names layer modules ``self_attn`` and ``switch_mlp``; the + ``language_model.``-prefixed variants of runtime paths that + ``expand_per_layer_quant_keys`` adds do not, so a rewritten config is + left alone. + """ + return any( + k.startswith(_VLM_LAYER) and (".self_attn." in k or ".mlp.switch_mlp." in k) + for k, v in quantization.items() + if isinstance(v, dict) + ) + + +def _vlm_vision_name(name: str) -> str: + """mlx-vlm ``vision_tower.*`` key or module path -> runtime name.""" + sub = name[len(_VLM_VISION) :] + "." + for old, new in _VLM_VISION_RENAMES: + sub = sub.replace(old, new) + sub = sub[:-1] + if not sub.startswith(("proj_in", "proj_out")): + sub = "backbone." + sub + return _VLM_VISION + sub + + +def _vlm_module_path(path: str, args) -> str | None: + """Runtime module that an mlx-vlm module's rows end up in.""" + if path.startswith(_VLM_VISION): + return _vlm_vision_name(path) + if path == "language_model.lm_head": + return "lm_head" + if path == "language_model.model.embed_tokens": + return "model.embed" + if not path.startswith(_VLM_LAYER): + return None + idx, rest = path[len(_VLM_LAYER) :].split(".", 1) + pre = f"model.layers.{idx}." + if rest == "mlp.switch_mlp.down_proj": + return pre + "mlp.experts.w2" + if rest in ("mlp.switch_mlp.gate_proj", "mlp.switch_mlp.up_proj"): + return pre + "mlp.experts.w13" + if not rest.startswith("self_attn."): + return None + name = rest[len("self_attn.") :] + if name == "o_proj": + return pre + "attn.o_proj" + if args.is_sliding(int(idx)): + return pre + "attn.in_proj" if name in _VLM_SLIDING_IN_PROJ else None + if name in _VLM_GLOBAL_Q_PROJ: + return pre + "attn.q_proj" + for n in ("k", "v"): + if name in (f"{n}_proj", f"{n}_sconv.weight_proj"): + return pre + f"attn.{n}_proj" + return None + + +def mlx_vlm_quantization(quantization: dict, args) -> dict: + """Rewrite mlx-vlm per-module quantization onto runtime module paths. + + Modules the runtime fuses must agree on their spec; the unquantized rows + of a fused module (the attention sink, the dynamic conv projections) are + quantized to that spec by ``sanitize_mlx_vlm_weights``. + """ + out = {k: v for k, v in quantization.items() if not isinstance(v, dict)} + for path, spec in quantization.items(): + if not isinstance(spec, dict): + continue + target = _vlm_module_path(path, args) + if target is None: + raise ValueError(f"Unmapped quantized Inkling 2 module: {path}") + if target in out and out[target] != spec: + raise ValueError( + f"Inkling 2 {target} fuses modules with different quantization: " + f"{out[target]} and {spec}" + ) + out[target] = dict(spec) + return out + + +def _pop_linear(d: dict, name: str) -> dict: + return {s: d.pop(f"{name}.{s}") for s in _QUANT_SUFFIXES if f"{name}.{s}" in d} + + +def _fuse_rows(parts: list, spec, path: str, out: dict) -> None: + """Concatenate Linear weights along their output rows. + + Quantized codes are row-local, so quantized parts keep their codes; any + unquantized part is quantized to the fused module's spec first. + """ + if not any("scales" in p for p in parts): + out[path + ".weight"] = mx.concatenate([p["weight"] for p in parts], axis=0) + return + if not isinstance(spec, dict): + raise ValueError(f"Inkling 2 {path} is quantized but has no quantization spec") + columns: dict = {} + for part in parts: + if "scales" not in part: + q = mx.quantize( + part["weight"], + group_size=spec["group_size"], + bits=spec["bits"], + mode=spec.get("mode", "affine"), + ) + part = dict(zip(_QUANT_SUFFIXES, q)) + for suffix, value in part.items(): + columns.setdefault(suffix, []).append(value) + if len({len(v) for v in columns.values()}) != 1: + raise ValueError(f"Inkling 2 {path} fuses different quantized carriers") + for suffix, values in columns.items(): + out[f"{path}.{suffix}"] = mx.concatenate(values, axis=0) + + +def _vlm_experts(d: dict, out: dict, pre: str) -> None: + """``switch_mlp.{gate,up,down}_proj`` -> runtime ``w13`` and ``w2``. + + mlx-vlm de-interleaves the published ``w13`` rows into gate (even rows) + and up (odd rows), and stores the NVFP4 outer scale as + ``amax / denominator``; the runtime keeps ``amax`` in MLX's convention. + """ + names = ("gate_proj", "up_proj", "down_proj") + gate, up, down = (_pop_linear(d, "mlp.switch_mlp." + n) for n in names) + scale2 = {n: d.pop(f"mlp.switch_mlp.{n}.weight_scale_2", None) for n in names} + w13 = pre + "mlp.experts.w13." + for suffix in gate: + g, u = gate[suffix], up[suffix] + out[w13 + suffix] = mx.stack([g, u], axis=-2).reshape( + *g.shape[:-2], 2 * g.shape[-2], g.shape[-1] + ) + if scale2["gate_proj"] is not None: + if not mx.array_equal(scale2["gate_proj"], scale2["up_proj"]): + raise ValueError(f"Inkling 2 {pre}gate and up outer scales differ") + out[w13 + "global_scale"] = ( + scale2["gate_proj"].astype(mx.float32) * _NVFP4_DENOMINATOR + ) + w2 = pre + "mlp.experts.w2." + for suffix, value in down.items(): + out[w2 + suffix] = value + if scale2["down_proj"] is not None: + out[w2 + "global_scale"] = ( + scale2["down_proj"].astype(mx.float32) * _NVFP4_DENOMINATOR + ) + + +def _vlm_layer(d: dict, idx: int, args, quant: dict, out: dict) -> None: + pre = f"model.layers.{idx}." + a = "self_attn." + hidden, k = args.hidden_size, args.sconv_kernel_size + if args.is_sliding(idx): + parts = [_pop_linear(d, a + n) for n in _VLM_SLIDING_IN_PROJ] + _fuse_rows(parts, quant.get(pre + "attn.in_proj"), pre + "attn.in_proj", out) + out[pre + "attn.k_conv"] = d.pop(a + "k_sconv.conv.weight").reshape(-1, k) + out[pre + "attn.v_conv"] = d.pop(a + "v_sconv.conv.weight").reshape(-1, k) + out[pre + "attn_norm.weight"] = d.pop("input_layernorm.weight") + else: + parts = [_pop_linear(d, a + n) for n in _VLM_GLOBAL_Q_PROJ] + _fuse_rows(parts, quant.get(pre + "attn.q_proj"), pre + "attn.q_proj", out) + for n in ("k", "v"): + parts = [ + _pop_linear(d, a + f"{n}_proj"), + _pop_linear(d, a + f"{n}_sconv.weight_proj"), + ] + path = pre + f"attn.{n}_proj" + _fuse_rows(parts, quant.get(path), path, out) + out[pre + f"attn.{n}_static"] = d.pop(a + f"{n}_sconv.static_weight") + for n in ("q", "k", "v"): + out[pre + f"{n}_input_norm.weight"] = d.pop(f"{n}_input_layernorm.weight") + for suffix, value in _pop_linear(d, a + "o_proj").items(): + out[pre + "attn.o_proj." + suffix] = value + out[pre + "attn.q_scale"] = d.pop(a + "q_scale") + out[pre + "attn.r_scale"] = d.pop(a + "rel_scale") + out[pre + "attn.rel_proj"] = d.pop(a + "rel_proj") + out[pre + "attn_conv"] = d.pop("attn_sconv.conv.weight").reshape(hidden, k) + out[pre + "mlp_conv"] = d.pop("mlp_sconv.conv.weight").reshape(hidden, k) + out[pre + "mlp_norm.weight"] = d.pop("post_attention_layernorm.weight") + out[pre + "mlp.router_weight"] = d.pop("mlp.gate_weight").astype(mx.float32) + out[pre + "mlp.router_bias"] = d.pop("mlp.e_score_correction_bias").astype( + mx.float32 + ) + for src, dst in (("attention_input", "attn_input"), ("mlp_input", "mlp_input")): + if f"{src}.query" in d: + out[pre + f"{dst}.query"] = ( + d.pop(f"{src}.query").reshape(-1, hidden).astype(mx.float32) + ) + _vlm_experts(d, out, pre) + if "controllers.attn.down_weight" in d: + _loop_controllers(d, out, pre) + if d: + raise ValueError(f"Unmapped Inkling 2 tensors in layer {idx}: {sorted(d)}") + + +def sanitize_mlx_vlm_weights(model, weights: dict) -> dict: + """Map an mlx-vlm-layout Inkling 2 checkpoint to the runtime layout.""" + args = model.args.text + quant = model.args.quantization or {} + has_vision = getattr(model, "vision_tower", None) is not None + hidden = args.hidden_size + out: dict = {} + per_layer: dict[int, dict] = {} + for key, value in weights.items(): + if key.startswith(_VLM_VISION): + if has_vision: + out[_vlm_vision_name(key)] = value + continue + if key.startswith(_VLM_LAYER): + idx, rest = key[len(_VLM_LAYER) :].split(".", 1) + per_layer.setdefault(int(idx), {})[rest] = value + continue + if not key.startswith(_VLM_TEXT): + raise ValueError(f"Unmapped Inkling 2 tensor: {key}") + name = key[len(_VLM_TEXT) :] + if name.startswith("lm_head.") or name in ( + "model.embed_norm.weight", + "model.norm.weight", + ): + out[name] = value + elif name.startswith("model.embed_tokens."): + out["model.embed." + name.rsplit(".", 1)[1]] = value + elif name == "model.final_input.query": + out[name] = value.reshape(-1, hidden).astype(mx.float32) + elif name == "model.message_queries": + # mlx-vlm already stacks each core layer's rows in the runtime's + # (attn, k, v, mlp) order. + core = args.loop_core + if value.shape[0] != len(core): + raise ValueError( + f"Inkling 2 message_queries has {value.shape[0]} rows " + f"for {len(core)} loop layers" + ) + for i, idx in enumerate(core): + out[f"model.layers.{idx}.loop_message.query"] = value[i].astype( + mx.float32 + ) + else: + raise ValueError(f"Unmapped Inkling 2 tensor: {key}") + for idx, d in per_layer.items(): + _vlm_layer(d, idx, args, quant, out) + return out diff --git a/omlx/utils/model_loading.py b/omlx/utils/model_loading.py index 0fd68fd6e2..526cc679e2 100644 --- a/omlx/utils/model_loading.py +++ b/omlx/utils/model_loading.py @@ -463,6 +463,33 @@ def normalize_inkling2_modelopt_quant(cfg: dict) -> dict: return cfg +def normalize_inkling2_mlx_vlm_quant(cfg: dict) -> dict: + """Move an mlx-vlm-layout Inkling 2 quantization onto runtime paths. + + Checkpoints quantized through mlx-vlm key ``quantization`` by mlx-vlm's + module names (``language_model.model.layers.N.self_attn.q_proj``). The + runtime fuses some of those modules, and mlx-lm applies the per-path specs + to the runtime module tree, so the keys are rewritten before it does. + """ + if cfg.get("model_type") not in INKLING2_MODEL_TYPES: + return cfg + from ..patches.inkling2.loader import ( + is_mlx_vlm_quantization, + mlx_vlm_quantization, + ) + + quant = cfg.get("quantization") + if not isinstance(quant, dict) or not is_mlx_vlm_quantization(quant): + return cfg + from ..patches.inkling2.model import TextArgs + + text = TextArgs.from_dict(cfg.get("text_config") or {}) + cfg["quantization"] = mlx_vlm_quantization(quant, text) + if isinstance(cfg.get("quantization_config"), dict): + cfg["quantization_config"] = cfg["quantization"] + return cfg + + def _patch_mlx_lm_load_config() -> None: """Wrap ``mlx_lm.utils.load_config`` to expand per-layer quant keys.""" global _MLX_LM_LOAD_CONFIG_PATCHED @@ -482,6 +509,8 @@ def _patched(model_path, *args, **kwargs): normalize_hy_v3_rope_config(cfg) # Cluster ranks load MiniMax through mlx-lm, not the patched mlx-vlm. adopt_expert_global_scales(cfg) + # Before the key variants below, which it would otherwise misread. + normalize_inkling2_mlx_vlm_quant(cfg) expand_per_layer_quant_keys(cfg) expand_glm_moe_dsa_fused_quant_keys(cfg) normalize_laguna_compressed_quant(cfg) diff --git a/tests/test_inkling2_mlx_vlm_layout.py b/tests/test_inkling2_mlx_vlm_layout.py new file mode 100644 index 0000000000..293a1d9c76 --- /dev/null +++ b/tests/test_inkling2_mlx_vlm_layout.py @@ -0,0 +1,278 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Inkling 2 checkpoints in mlx-vlm's layout load like the published layout.""" + +from __future__ import annotations + +import copy +import json +import shutil + +import mlx.core as mx +import mlx.nn as nn +import mlx_lm.utils as mlx_lm_utils +import pytest +from mlx.utils import tree_flatten + +from omlx.patches.inkling2.model import TextArgs +from omlx.utils import model_loading +from tests.test_oq import _INK2_LAYERS, _inkling2_model, _inkling2_source + +_NVFP4 = {"group_size": 16, "bits": 4, "mode": "nvfp4"} +_MXFP8 = {"group_size": 32, "bits": 8, "mode": "mxfp8"} +_Q8 = {"group_size": 64, "bits": 8, "mode": "affine"} +_ATTN_PROJ = { + "wq_du": "q_proj", + "wk_dv": "k_proj", + "wv_dv": "v_proj", + "wr_du": "r_proj", + "wo_ud": "o_proj", + "gate_attn": "gate_proj", + "attn_sink_proj": "sink_proj", +} +_NORMS = { + "attn_norm": "input_layernorm", + "mlp_norm": "post_attention_layernorm", + "q_input_norm": "q_input_layernorm", + "k_input_norm": "k_input_layernorm", + "v_input_norm": "v_input_layernorm", +} +_VISION = ( + ("ln_pre.", "pre_layernorm."), + (".ln_1.", ".layernorm_before."), + (".ln_2.", ".layernorm_after."), + (".ls_1.gamma", ".lambda_1"), + (".ls_2.gamma", ".lambda_2"), + (".mlp.c_fc.", ".mlp.fc1."), + (".mlp.c_proj.", ".mlp.fc2."), +) + + +def _split_gate_up(v): + *lead, rows, cols = v.shape + w = v.reshape(*lead, rows // 2, 2, cols) + return mx.contiguous(w[..., 0, :]), mx.contiguous(w[..., 1, :]) + + +def _to_mlx_conv(v): + return v if v.ndim == 3 and v.shape[-1] == 1 else v.transpose(0, 2, 1) + + +def _mlx_vlm_tensors(source: dict, hidden: int) -> tuple[dict, dict]: + """The tensors and expert specs mlx-vlm's ``Model.sanitize`` produces. + + Mirrors mlx_vlm/models/inkling2/inkling2.py at Blaizzy/mlx-vlm d998a62, + the commit community MLX builds (orcarouter) were made with. + """ + out, experts, specs = {}, {}, {} + for key, value in source.items(): + if key.startswith("model.llm.layers."): + layer, sub = key[len("model.llm.layers.") :].split(".", 1) + base = f"language_model.model.layers.{layer}." + if sub.startswith("mlp.experts."): + experts.setdefault(layer, {})[sub[len("mlp.experts.") :]] = value + continue + if sub.startswith("attn."): + name, _, leaf = sub[len("attn.") :].partition(".") + sub = _ATTN_PROJ.get(name, name) + ("." + leaf if leaf else "") + sub = { + "q_l2_clip.scale": "q_scale", + "rel_l2_clip.scale": "rel_scale", + "rel_logits_proj.proj": "rel_proj", + }.get(sub, sub) + for conv in ("k_sconv", "v_sconv"): + if sub == conv + ".weight": + sub, value = conv + ".conv.weight", _to_mlx_conv(value) + elif sub == conv + ".static_w": + sub = conv + ".static_weight" + elif sub == conv + ".weight_proj": + sub += ".weight" + sub = "self_attn." + sub + elif sub in ("attn_sconv.weight", "mlp_sconv.weight"): + sub, value = sub.replace(".weight", ".conv.weight"), _to_mlx_conv(value) + elif sub in ("mlp.gate.weight", "mlp.gate.bias"): + sub = ( + "mlp.gate_weight" + if sub.endswith("weight") + else "mlp.e_score_correction_bias" + ) + else: + name, _, leaf = sub.partition(".") + sub = _NORMS.get(name, name) + "." + leaf + out[base + sub] = value + elif key.startswith("model.llm.attn_res."): + sub = key[len("model.llm.attn_res.") :] + if sub == "output_query": + target = "final_input.query" + else: + kind, index = sub.split(".") + layer = int(index) + (kind == "attn_queries") + name = "attention_input" if kind == "attn_queries" else "mlp_input" + target = f"layers.{layer}.{name}.query" + out["language_model.model." + target] = value + elif key.startswith("model.llm."): + sub = key[len("model.llm.") :] + out[ + ( + "language_model.lm_head.weight" + if sub == "unembed.weight" + else "language_model.model." + + sub.replace("embed.weight", "embed_tokens.weight") + ) + ] = value + elif key.startswith("model.visual."): + sub = key[len("model.visual.") :].removeprefix("backbone.") + for old, new in _VISION: + sub = sub.replace(old, new) + out["vision_tower." + sub] = value + for layer, tensors in experts.items(): + base = f"language_model.model.layers.{layer}.mlp.switch_mlp." + for name, projections in ( + ("w13_weight", ("gate_proj", "up_proj")), + ("w2_weight", ("down_proj",)), + ): + values = { + "weight": tensors[name].view(mx.uint32), + "scales": tensors[name + "_scale"], + } + if name + "_amax" in tensors: + values["weight_scale_2"] = ( + tensors[name + "_amax"] / tensors[name + "_outer_scale_denominator"] + ) + for suffix, v in values.items(): + parts = ( + _split_gate_up(v) + if len(projections) == 2 and suffix != "weight_scale_2" + else (v,) * len(projections) + ) + for projection, part in zip(projections, parts): + out[base + projection + "." + suffix] = part + for projection in projections: + specs[base + projection] = ( + _NVFP4 if "weight_scale_2" in values else _MXFP8 + ) + base = "language_model.model." + if base + "middle_cycle_cross_pass_queries" in out: + attn_mlp = out.pop(base + "middle_cycle_cross_pass_queries").reshape( + -1, 2, hidden + ) + kv = out.pop(base + "middle_cycle_cross_pass_kv_queries").reshape(-1, 2, hidden) + out[base + "message_queries"] = mx.concatenate( + [attn_mlp[:, :1], kv, attn_mlp[:, 1:]], axis=1 + ) + return out, specs + + +def _mlx_vlm_checkpoint(source_dir, dest, *, quantize_attention=False): + """Write ``source_dir`` the way an mlx-vlm quantized build ships it.""" + shutil.copytree( + source_dir, + dest, + ignore=shutil.ignore_patterns("*.safetensors", "hf_quant_config.json"), + ) + shutil.copy(source_dir / "mtp.safetensors", dest / "mtp.safetensors") + config = json.loads((source_dir / "config.json").read_text()) + tensors, specs = _mlx_vlm_tensors( + mx.load(str(source_dir / "model.safetensors")), + config["text_config"]["hidden_size"], + ) + quant = dict(_NVFP4, **specs) + if quantize_attention: + for layer in range(_INK2_LAYERS): + for proj in ("q_proj", "k_proj", "v_proj", "r_proj", "gate_proj", "o_proj"): + path = f"language_model.model.layers.{layer}.self_attn.{proj}" + w, s, b = mx.quantize( + tensors.pop(path + ".weight"), group_size=64, bits=8 + ) + tensors.update( + {path + ".weight": w, path + ".scales": s, path + ".biases": b} + ) + quant[path] = dict(_Q8) + config["quantization"] = config["quantization_config"] = quant + (dest / "config.json").write_text(json.dumps(config)) + mx.save_safetensors(str(dest / "model.safetensors"), tensors, {"format": "mlx"}) + return dest + + +@pytest.fixture +def patched_load_config(monkeypatch): + monkeypatch.setattr(model_loading, "_MLX_LM_LOAD_CONFIG_PATCHED", False) + monkeypatch.setattr(mlx_lm_utils, "load_config", mlx_lm_utils.load_config) + model_loading._patch_mlx_lm_load_config() + + +@pytest.mark.parametrize("looped", [False, True], ids=["plain", "looped"]) +def test_mlx_vlm_layout_loads_like_published_layout( + tmp_path, looped, patched_load_config +): + source = tmp_path / "source" + _inkling2_source(source, looped=looped) + vlm = _mlx_vlm_checkpoint(source, tmp_path / "mlx_vlm") + + expected = dict(tree_flatten(_inkling2_model(source).parameters())) + loaded = dict(tree_flatten(_inkling2_model(vlm).parameters())) + + assert loaded.keys() == expected.keys() + for key, value in expected.items(): + assert loaded[key].dtype == value.dtype, key + if key.endswith(".global_scale"): + # mlx-vlm stores amax / denominator; the runtime keeps amax. + assert mx.allclose(loaded[key], value, rtol=1e-6).item(), key + else: + assert mx.array_equal(loaded[key], value, equal_nan=True).item(), key + + +def test_quantized_attention_keeps_its_codes(tmp_path, patched_load_config): + source = tmp_path / "source" + _inkling2_source(source, looped=True) + vlm = _mlx_vlm_checkpoint(source, tmp_path / "mlx_vlm", quantize_attention=True) + + expected = _inkling2_model(source) + loaded = _inkling2_model(vlm) + + # Affine codes are local to a row, so the fused projections, including the + # unquantized sink and dynamic-conv rows, match quantizing the fused BF16 + # weight in one go. + for layer, (ref, got) in enumerate(zip(expected.model.layers, loaded.model.layers)): + names = ["o_proj"] + ( + ["in_proj"] if ref.attn.sliding else ["q_proj", "k_proj", "v_proj"] + ) + for name in names: + module = getattr(got.attn, name) + assert isinstance(module, nn.QuantizedLinear), f"layer {layer} {name}" + w, s, b = mx.quantize(getattr(ref.attn, name).weight, group_size=64, bits=8) + for want, have in ( + (w, module.weight), + (s, module.scales), + (b, module.biases), + ): + assert mx.array_equal(want, have).item(), f"layer {layer} {name}" + + +def test_fused_modules_must_share_a_spec(): + from omlx.patches.inkling2.loader import mlx_vlm_quantization + + args = TextArgs.from_dict( + {"num_hidden_layers": 2, "local_layer_ids": [0], "hidden_size": 64} + ) + base = "language_model.model.layers.0.self_attn." + with pytest.raises(ValueError, match="different quantization"): + mlx_vlm_quantization( + {base + "q_proj": _Q8, base + "k_proj": dict(_Q8, bits=4)}, args + ) + + +def test_rewritten_quantization_is_left_alone(tmp_path): + # load_config may run the normalizers again on a rewritten config, which by + # then also carries the language_model.-prefixed variants of its keys. + source = tmp_path / "source" + _inkling2_source(source, looped=True) + vlm = _mlx_vlm_checkpoint(source, tmp_path / "mlx_vlm", quantize_attention=True) + cfg = json.loads((vlm / "config.json").read_text()) + + model_loading.normalize_inkling2_mlx_vlm_quant(cfg) + model_loading.expand_per_layer_quant_keys(cfg) + once = copy.deepcopy(cfg["quantization"]) + assert "model.layers.0.attn.in_proj" in once + model_loading.normalize_inkling2_mlx_vlm_quant(cfg) + + assert cfg["quantization"] == once From 222c9febde2449c5dfb9503b474f232b5cc42168 Mon Sep 17 00:00:00 2001 From: Kenya Nara Date: Tue, 24 Nov 2026 19:04:36 +0900 Subject: [PATCH 2/3] feat(inkling2): widen narrower affine rows of fused modules Mixed-precision mlx-vlm builds can quantize the rows that the runtime fuses at different affine bits; the orcarouter 12GB build has 2-bit gate and 3-bit up in 10 layers. Let a fused module take the widest affine spec among its rows when they share a group size, and re-pack narrower codes at that width with their scales and biases unchanged, which keeps the weights exactly. Other mixes still raise. Co-Authored-By: Claude Opus 5.5 --- omlx/patches/inkling2/loader.py | 90 ++++++++++++++++++++++----- tests/test_inkling2_mlx_vlm_layout.py | 82 +++++++++++++++++++++--- 2 files changed, 151 insertions(+), 21 deletions(-) diff --git a/omlx/patches/inkling2/loader.py b/omlx/patches/inkling2/loader.py index bd1004a932..f1bd0e9b09 100644 --- a/omlx/patches/inkling2/loader.py +++ b/omlx/patches/inkling2/loader.py @@ -198,7 +198,9 @@ def sanitize_weights(model, weights: dict) -> tuple[dict, dict]: # fused tensors (``Model.sanitize`` in mlx_vlm/models/inkling2/inkling2.py). # Quantized builds made with mlx-vlm, such as orcarouter's abliterated MLX # release, ship in that layout. The maps below undo mlx-vlm's sanitize so the -# same files load on this runtime, with their quantized codes left as they are. +# same files load on this runtime with the same quantized weights: codes are +# kept, or re-packed at a wider bit width where the runtime fuses rows that +# were quantized at different widths. _VLM_TEXT = "language_model." _VLM_LAYER = "language_model.model.layers." @@ -290,9 +292,10 @@ def _vlm_module_path(path: str, args) -> str | None: def mlx_vlm_quantization(quantization: dict, args) -> dict: """Rewrite mlx-vlm per-module quantization onto runtime module paths. - Modules the runtime fuses must agree on their spec; the unquantized rows - of a fused module (the attention sink, the dynamic conv projections) are - quantized to that spec by ``sanitize_mlx_vlm_weights``. + A fused module takes the widest of its modules' affine specs when they + share a group size; ``sanitize_mlx_vlm_weights`` re-encodes the narrower + rows losslessly and quantizes the unquantized rows (the attention sink, the + dynamic conv projections) to that spec. Other mixes raise. """ out = {k: v for k, v in quantization.items() if not isinstance(v, dict)} for path, spec in quantization.items(): @@ -301,15 +304,67 @@ def mlx_vlm_quantization(quantization: dict, args) -> dict: target = _vlm_module_path(path, args) if target is None: raise ValueError(f"Unmapped quantized Inkling 2 module: {path}") - if target in out and out[target] != spec: - raise ValueError( - f"Inkling 2 {target} fuses modules with different quantization: " - f"{out[target]} and {spec}" - ) - out[target] = dict(spec) + out[target] = _merge_spec(target, out.get(target), dict(spec)) return out +def _merge_spec(target: str, old: dict | None, new: dict) -> dict: + if old is None or old == new: + return new + if ( + old.get("mode", "affine") == new.get("mode", "affine") == "affine" + and old["group_size"] == new["group_size"] + ): + return max(old, new, key=lambda spec: spec["bits"]) + raise ValueError( + f"Inkling 2 {target} fuses modules with different quantization: " + f"{old} and {new}" + ) + + +def _pack_codes(codes: mx.array, bits: int) -> mx.array: + """Pack unsigned codes the way MLX does: a little-endian bit stream per row.""" + *lead, n = codes.shape + q = codes.reshape(*lead, n // 32, 32) + words = [mx.zeros(q.shape[:-1], dtype=mx.uint32) for _ in range(bits)] + for j in range(32): + word, shift = divmod(j * bits, 32) + code = q[..., j].astype(mx.uint32) + words[word] = words[word] | (code << shift) + if shift + bits > 32: + words[word + 1] = words[word + 1] | (code >> (32 - shift)) + return mx.stack(words, axis=-1).reshape(*lead, n * bits // 32) + + +def _widen(part: dict, spec: dict) -> dict: + """Re-encode a narrower affine Linear at ``spec``'s bits, losslessly. + + An affine code ``q`` stands for ``scale * q + bias``. The same scales and + biases with ``q`` stored in more bits give the same weights. + """ + if "biases" not in part or spec.get("mode", "affine") != "affine": + return part + group_size, bits = spec["group_size"], spec["bits"] + in_dims = part["scales"].shape[-1] * group_size + have = part["weight"].shape[-1] * 32 // in_dims + if have == bits: + return part + if have > bits: + raise ValueError(f"Cannot narrow Inkling 2 {have}-bit rows to {bits} bits") + scales = part["scales"] + codes = mx.dequantize( + part["weight"], + mx.ones_like(scales), + mx.zeros_like(scales), + group_size=group_size, + bits=have, + ).astype(mx.uint8) + weight = _pack_codes(codes, bits) + # Bound the transient codes to one projection at a time. + mx.eval(weight) + return {**part, "weight": weight} + + def _pop_linear(d: dict, name: str) -> dict: return {s: d.pop(f"{name}.{s}") for s in _QUANT_SUFFIXES if f"{name}.{s}" in d} @@ -317,8 +372,9 @@ def _pop_linear(d: dict, name: str) -> dict: def _fuse_rows(parts: list, spec, path: str, out: dict) -> None: """Concatenate Linear weights along their output rows. - Quantized codes are row-local, so quantized parts keep their codes; any - unquantized part is quantized to the fused module's spec first. + Quantized codes are row-local, so quantized parts keep their codes, + widened to the fused module's bits if narrower; any unquantized part is + quantized to the fused module's spec first. """ if not any("scales" in p for p in parts): out[path + ".weight"] = mx.concatenate([p["weight"] for p in parts], axis=0) @@ -335,6 +391,8 @@ def _fuse_rows(parts: list, spec, path: str, out: dict) -> None: mode=spec.get("mode", "affine"), ) part = dict(zip(_QUANT_SUFFIXES, q)) + else: + part = _widen(part, spec) for suffix, value in part.items(): columns.setdefault(suffix, []).append(value) if len({len(v) for v in columns.values()}) != 1: @@ -343,15 +401,19 @@ def _fuse_rows(parts: list, spec, path: str, out: dict) -> None: out[f"{path}.{suffix}"] = mx.concatenate(values, axis=0) -def _vlm_experts(d: dict, out: dict, pre: str) -> None: +def _vlm_experts(d: dict, out: dict, pre: str, spec) -> None: """``switch_mlp.{gate,up,down}_proj`` -> runtime ``w13`` and ``w2``. mlx-vlm de-interleaves the published ``w13`` rows into gate (even rows) and up (odd rows), and stores the NVFP4 outer scale as ``amax / denominator``; the runtime keeps ``amax`` in MLX's convention. + Builds that quantize gate and up at different affine bits get the + narrower one widened to ``spec``, the fused ``w13`` spec. """ names = ("gate_proj", "up_proj", "down_proj") gate, up, down = (_pop_linear(d, "mlp.switch_mlp." + n) for n in names) + if isinstance(spec, dict): + gate, up = _widen(gate, spec), _widen(up, spec) scale2 = {n: d.pop(f"mlp.switch_mlp.{n}.weight_scale_2", None) for n in names} w13 = pre + "mlp.experts.w13." for suffix in gate: @@ -414,7 +476,7 @@ def _vlm_layer(d: dict, idx: int, args, quant: dict, out: dict) -> None: out[pre + f"{dst}.query"] = ( d.pop(f"{src}.query").reshape(-1, hidden).astype(mx.float32) ) - _vlm_experts(d, out, pre) + _vlm_experts(d, out, pre, quant.get(pre + "mlp.experts.w13")) if "controllers.attn.down_weight" in d: _loop_controllers(d, out, pre) if d: diff --git a/tests/test_inkling2_mlx_vlm_layout.py b/tests/test_inkling2_mlx_vlm_layout.py index 293a1d9c76..beb00cf645 100644 --- a/tests/test_inkling2_mlx_vlm_layout.py +++ b/tests/test_inkling2_mlx_vlm_layout.py @@ -162,8 +162,14 @@ def _mlx_vlm_tensors(source: dict, hidden: int) -> tuple[dict, dict]: return out, specs -def _mlx_vlm_checkpoint(source_dir, dest, *, quantize_attention=False): - """Write ``source_dir`` the way an mlx-vlm quantized build ships it.""" +def _mlx_vlm_checkpoint( + source_dir, dest, *, quantize_attention=False, expert_bits=None +): + """Write ``source_dir`` the way an mlx-vlm quantized build ships it. + + ``expert_bits`` maps gate/up/down to affine bits, replacing the source's + NVFP4/MXFP8 experts the way mixed-precision builds quantize them. + """ shutil.copytree( source_dir, dest, @@ -187,6 +193,24 @@ def _mlx_vlm_checkpoint(source_dir, dest, *, quantize_attention=False): {path + ".weight": w, path + ".scales": s, path + ".biases": b} ) quant[path] = dict(_Q8) + if expert_bits: + rng = mx.random.key(0) + for layer in range(_INK2_LAYERS): + base = f"language_model.model.layers.{layer}.mlp.switch_mlp." + for proj, bits in expert_bits.items(): + path = base + f"{proj}_proj" + text = config["text_config"] + in_dims = text["intermediate_size" if proj == "down" else "hidden_size"] + shape = tensors[path + ".weight"].shape[:-1] + (in_dims,) + rng, key = mx.random.split(rng) + w = (mx.random.normal(shape, key=key) * 0.05).astype(mx.bfloat16) + q, sc, b = mx.quantize(w, group_size=32, bits=bits) + for suffix in ("weight", "scales", "weight_scale_2"): + tensors.pop(f"{path}.{suffix}", None) + tensors.update( + {path + ".weight": q, path + ".scales": sc, path + ".biases": b} + ) + quant[path] = {"group_size": 32, "bits": bits, "mode": "affine"} config["quantization"] = config["quantization_config"] = quant (dest / "config.json").write_text(json.dumps(config)) mx.save_safetensors(str(dest / "model.safetensors"), tensors, {"format": "mlx"}) @@ -248,17 +272,61 @@ def test_quantized_attention_keeps_its_codes(tmp_path, patched_load_config): assert mx.array_equal(want, have).item(), f"layer {layer} {name}" -def test_fused_modules_must_share_a_spec(): +@pytest.mark.parametrize("bits", [(2, 3, 4), (4, 2, 8), (3, 6, 3)], ids=str) +def test_mixed_bit_experts_widen_losslessly(tmp_path, bits, patched_load_config): + # Mixed-precision builds can quantize gate and up at different bits; the + # runtime fuses them into w13, so the narrower rows are widened. + source = tmp_path / "source" + _inkling2_source(source, looped=True) + gate, up, down = bits + vlm = _mlx_vlm_checkpoint( + source, + tmp_path / "mlx_vlm", + expert_bits={"gate": gate, "up": up, "down": down}, + ) + tensors = mx.load(str(vlm / "model.safetensors")) + loaded = _inkling2_model(vlm) + + def dequant(path, b): + return mx.dequantize( + tensors[path + ".weight"], + tensors[path + ".scales"], + tensors[path + ".biases"], + group_size=32, + bits=b, + ) + + for layer, block in enumerate(loaded.model.layers): + experts = block.mlp.experts + base = f"language_model.model.layers.{layer}.mlp.switch_mlp." + g, u = dequant(base + "gate_proj", gate), dequant(base + "up_proj", up) + w13 = mx.stack([g, u], axis=-2).reshape(*g.shape[:-2], -1, g.shape[-1]) + assert experts.w13.bits == max(gate, up) + for proj, want in ( + (experts.w13, w13), + (experts.w2, dequant(base + "down_proj", down)), + ): + got = mx.dequantize( + proj.weight, proj.scales, proj.biases, group_size=32, bits=proj.bits + ) + assert mx.array_equal(got, want).item(), f"layer {layer}" + + +def test_fused_specs_take_the_widest_affine_bits(): from omlx.patches.inkling2.loader import mlx_vlm_quantization args = TextArgs.from_dict( {"num_hidden_layers": 2, "local_layer_ids": [0], "hidden_size": 64} ) base = "language_model.model.layers.0.self_attn." - with pytest.raises(ValueError, match="different quantization"): - mlx_vlm_quantization( - {base + "q_proj": _Q8, base + "k_proj": dict(_Q8, bits=4)}, args - ) + quant = mlx_vlm_quantization( + {base + "q_proj": dict(_Q8, bits=4), base + "k_proj": _Q8}, args + ) + assert quant["model.layers.0.attn.in_proj"] == _Q8 + # Rows with another group size or mode cannot be re-encoded losslessly. + for other in (dict(_Q8, group_size=32), _NVFP4): + with pytest.raises(ValueError, match="different quantization"): + mlx_vlm_quantization({base + "q_proj": _Q8, base + "k_proj": other}, args) def test_rewritten_quantization_is_left_alone(tmp_path): From f2f136b45da22238c5311370d6d02b24d0cdaac9 Mon Sep 17 00:00:00 2001 From: jundot Date: Wed, 25 Nov 2026 09:41:40 +0100 Subject: [PATCH 3/3] refactor(inkling2): trim the mlx-vlm layout loader and its tests --- omlx/patches/inkling2/loader.py | 45 +--- omlx/utils/model_loading.py | 12 +- tests/test_inkling2_mlx_vlm_layout.py | 346 -------------------------- tests/test_oq.py | 135 ++++++++++ 4 files changed, 138 insertions(+), 400 deletions(-) delete mode 100644 tests/test_inkling2_mlx_vlm_layout.py diff --git a/omlx/patches/inkling2/loader.py b/omlx/patches/inkling2/loader.py index f1bd0e9b09..516df5015d 100644 --- a/omlx/patches/inkling2/loader.py +++ b/omlx/patches/inkling2/loader.py @@ -82,8 +82,6 @@ def _loop_message_queries(queries: dict, core: range, out: dict) -> None: def sanitize_weights(model, weights: dict) -> tuple[dict, dict]: """Returns the mapped weights and the routed-expert format per layer.""" if is_mlx_vlm_layout(weights): - # Expert carriers come from the per-path ``quantization`` that - # ``mlx_vlm_quantization`` rewrote, so no per-layer formats here. return sanitize_mlx_vlm_weights(model, weights), {} if not is_original_layout(weights): return weights, {} @@ -192,21 +190,9 @@ def sanitize_weights(model, weights: dict) -> tuple[dict, dict]: return out, formats -# mlx-vlm layout ----------------------------------------------------------- -# -# mlx-vlm's ``inkling2`` model renames the published checkpoint and splits its -# fused tensors (``Model.sanitize`` in mlx_vlm/models/inkling2/inkling2.py). -# Quantized builds made with mlx-vlm, such as orcarouter's abliterated MLX -# release, ship in that layout. The maps below undo mlx-vlm's sanitize so the -# same files load on this runtime with the same quantized weights: codes are -# kept, or re-packed at a wider bit width where the runtime fuses rows that -# were quantized at different widths. - _VLM_TEXT = "language_model." _VLM_LAYER = "language_model.model.layers." _VLM_VISION = "vision_tower." -# (mlx-vlm, runtime) substrings of the vision tower names; the runtime keeps -# the published names under ``backbone``. _VLM_VISION_RENAMES = ( ("pre_layernorm.", "ln_pre."), (".layernorm_before.", ".ln_1."), @@ -248,7 +234,6 @@ def is_mlx_vlm_quantization(quantization: dict) -> bool: def _vlm_vision_name(name: str) -> str: - """mlx-vlm ``vision_tower.*`` key or module path -> runtime name.""" sub = name[len(_VLM_VISION) :] + "." for old, new in _VLM_VISION_RENAMES: sub = sub.replace(old, new) @@ -259,7 +244,6 @@ def _vlm_vision_name(name: str) -> str: def _vlm_module_path(path: str, args) -> str | None: - """Runtime module that an mlx-vlm module's rows end up in.""" if path.startswith(_VLM_VISION): return _vlm_vision_name(path) if path == "language_model.lm_head": @@ -323,7 +307,6 @@ def _merge_spec(target: str, old: dict | None, new: dict) -> dict: def _pack_codes(codes: mx.array, bits: int) -> mx.array: - """Pack unsigned codes the way MLX does: a little-endian bit stream per row.""" *lead, n = codes.shape q = codes.reshape(*lead, n // 32, 32) words = [mx.zeros(q.shape[:-1], dtype=mx.uint32) for _ in range(bits)] @@ -337,11 +320,6 @@ def _pack_codes(codes: mx.array, bits: int) -> mx.array: def _widen(part: dict, spec: dict) -> dict: - """Re-encode a narrower affine Linear at ``spec``'s bits, losslessly. - - An affine code ``q`` stands for ``scale * q + bias``. The same scales and - biases with ``q`` stored in more bits give the same weights. - """ if "biases" not in part or spec.get("mode", "affine") != "affine": return part group_size, bits = spec["group_size"], spec["bits"] @@ -360,7 +338,6 @@ def _widen(part: dict, spec: dict) -> dict: bits=have, ).astype(mx.uint8) weight = _pack_codes(codes, bits) - # Bound the transient codes to one projection at a time. mx.eval(weight) return {**part, "weight": weight} @@ -370,12 +347,6 @@ def _pop_linear(d: dict, name: str) -> dict: def _fuse_rows(parts: list, spec, path: str, out: dict) -> None: - """Concatenate Linear weights along their output rows. - - Quantized codes are row-local, so quantized parts keep their codes, - widened to the fused module's bits if narrower; any unquantized part is - quantized to the fused module's spec first. - """ if not any("scales" in p for p in parts): out[path + ".weight"] = mx.concatenate([p["weight"] for p in parts], axis=0) return @@ -395,21 +366,11 @@ def _fuse_rows(parts: list, spec, path: str, out: dict) -> None: part = _widen(part, spec) for suffix, value in part.items(): columns.setdefault(suffix, []).append(value) - if len({len(v) for v in columns.values()}) != 1: - raise ValueError(f"Inkling 2 {path} fuses different quantized carriers") for suffix, values in columns.items(): out[f"{path}.{suffix}"] = mx.concatenate(values, axis=0) def _vlm_experts(d: dict, out: dict, pre: str, spec) -> None: - """``switch_mlp.{gate,up,down}_proj`` -> runtime ``w13`` and ``w2``. - - mlx-vlm de-interleaves the published ``w13`` rows into gate (even rows) - and up (odd rows), and stores the NVFP4 outer scale as - ``amax / denominator``; the runtime keeps ``amax`` in MLX's convention. - Builds that quantize gate and up at different affine bits get the - narrower one widened to ``spec``, the fused ``w13`` spec. - """ names = ("gate_proj", "up_proj", "down_proj") gate, up, down = (_pop_linear(d, "mlp.switch_mlp." + n) for n in names) if isinstance(spec, dict): @@ -500,9 +461,7 @@ def sanitize_mlx_vlm_weights(model, weights: dict) -> dict: idx, rest = key[len(_VLM_LAYER) :].split(".", 1) per_layer.setdefault(int(idx), {})[rest] = value continue - if not key.startswith(_VLM_TEXT): - raise ValueError(f"Unmapped Inkling 2 tensor: {key}") - name = key[len(_VLM_TEXT) :] + name = key.removeprefix(_VLM_TEXT) if name.startswith("lm_head.") or name in ( "model.embed_norm.weight", "model.norm.weight", @@ -513,8 +472,6 @@ def sanitize_mlx_vlm_weights(model, weights: dict) -> dict: elif name == "model.final_input.query": out[name] = value.reshape(-1, hidden).astype(mx.float32) elif name == "model.message_queries": - # mlx-vlm already stacks each core layer's rows in the runtime's - # (attn, k, v, mlp) order. core = args.loop_core if value.shape[0] != len(core): raise ValueError( diff --git a/omlx/utils/model_loading.py b/omlx/utils/model_loading.py index a47305e10f..84935123fc 100644 --- a/omlx/utils/model_loading.py +++ b/omlx/utils/model_loading.py @@ -14,7 +14,9 @@ from ..patches.arrays_cache_metadata import apply_arrays_cache_metadata_patch from ..patches.inkling2 import INKLING2_MODEL_TYPES +from ..patches.inkling2.loader import is_mlx_vlm_quantization, mlx_vlm_quantization from ..patches.inkling2.loopcd import apply_loopcd +from ..patches.inkling2.model import TextArgs from ..patches.mlx_vlm_minimax_m3_compat import adopt_expert_global_scales from ..patches.qwen35_yarn import apply_qwen35_yarn_patch, set_context_window from ..patches.raon1_mini import normalize_raon1_mini_model_file @@ -474,20 +476,11 @@ def normalize_inkling2_mlx_vlm_quant(cfg: dict) -> dict: """ if cfg.get("model_type") not in INKLING2_MODEL_TYPES: return cfg - from ..patches.inkling2.loader import ( - is_mlx_vlm_quantization, - mlx_vlm_quantization, - ) - quant = cfg.get("quantization") if not isinstance(quant, dict) or not is_mlx_vlm_quantization(quant): return cfg - from ..patches.inkling2.model import TextArgs - text = TextArgs.from_dict(cfg.get("text_config") or {}) cfg["quantization"] = mlx_vlm_quantization(quant, text) - if isinstance(cfg.get("quantization_config"), dict): - cfg["quantization_config"] = cfg["quantization"] return cfg @@ -510,7 +503,6 @@ def _patched(model_path, *args, **kwargs): normalize_hy_v3_rope_config(cfg) # Cluster ranks load MiniMax through mlx-lm, not the patched mlx-vlm. adopt_expert_global_scales(cfg) - # Before the key variants below, which it would otherwise misread. normalize_inkling2_mlx_vlm_quant(cfg) expand_per_layer_quant_keys(cfg) expand_glm_moe_dsa_fused_quant_keys(cfg) diff --git a/tests/test_inkling2_mlx_vlm_layout.py b/tests/test_inkling2_mlx_vlm_layout.py deleted file mode 100644 index beb00cf645..0000000000 --- a/tests/test_inkling2_mlx_vlm_layout.py +++ /dev/null @@ -1,346 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -"""Inkling 2 checkpoints in mlx-vlm's layout load like the published layout.""" - -from __future__ import annotations - -import copy -import json -import shutil - -import mlx.core as mx -import mlx.nn as nn -import mlx_lm.utils as mlx_lm_utils -import pytest -from mlx.utils import tree_flatten - -from omlx.patches.inkling2.model import TextArgs -from omlx.utils import model_loading -from tests.test_oq import _INK2_LAYERS, _inkling2_model, _inkling2_source - -_NVFP4 = {"group_size": 16, "bits": 4, "mode": "nvfp4"} -_MXFP8 = {"group_size": 32, "bits": 8, "mode": "mxfp8"} -_Q8 = {"group_size": 64, "bits": 8, "mode": "affine"} -_ATTN_PROJ = { - "wq_du": "q_proj", - "wk_dv": "k_proj", - "wv_dv": "v_proj", - "wr_du": "r_proj", - "wo_ud": "o_proj", - "gate_attn": "gate_proj", - "attn_sink_proj": "sink_proj", -} -_NORMS = { - "attn_norm": "input_layernorm", - "mlp_norm": "post_attention_layernorm", - "q_input_norm": "q_input_layernorm", - "k_input_norm": "k_input_layernorm", - "v_input_norm": "v_input_layernorm", -} -_VISION = ( - ("ln_pre.", "pre_layernorm."), - (".ln_1.", ".layernorm_before."), - (".ln_2.", ".layernorm_after."), - (".ls_1.gamma", ".lambda_1"), - (".ls_2.gamma", ".lambda_2"), - (".mlp.c_fc.", ".mlp.fc1."), - (".mlp.c_proj.", ".mlp.fc2."), -) - - -def _split_gate_up(v): - *lead, rows, cols = v.shape - w = v.reshape(*lead, rows // 2, 2, cols) - return mx.contiguous(w[..., 0, :]), mx.contiguous(w[..., 1, :]) - - -def _to_mlx_conv(v): - return v if v.ndim == 3 and v.shape[-1] == 1 else v.transpose(0, 2, 1) - - -def _mlx_vlm_tensors(source: dict, hidden: int) -> tuple[dict, dict]: - """The tensors and expert specs mlx-vlm's ``Model.sanitize`` produces. - - Mirrors mlx_vlm/models/inkling2/inkling2.py at Blaizzy/mlx-vlm d998a62, - the commit community MLX builds (orcarouter) were made with. - """ - out, experts, specs = {}, {}, {} - for key, value in source.items(): - if key.startswith("model.llm.layers."): - layer, sub = key[len("model.llm.layers.") :].split(".", 1) - base = f"language_model.model.layers.{layer}." - if sub.startswith("mlp.experts."): - experts.setdefault(layer, {})[sub[len("mlp.experts.") :]] = value - continue - if sub.startswith("attn."): - name, _, leaf = sub[len("attn.") :].partition(".") - sub = _ATTN_PROJ.get(name, name) + ("." + leaf if leaf else "") - sub = { - "q_l2_clip.scale": "q_scale", - "rel_l2_clip.scale": "rel_scale", - "rel_logits_proj.proj": "rel_proj", - }.get(sub, sub) - for conv in ("k_sconv", "v_sconv"): - if sub == conv + ".weight": - sub, value = conv + ".conv.weight", _to_mlx_conv(value) - elif sub == conv + ".static_w": - sub = conv + ".static_weight" - elif sub == conv + ".weight_proj": - sub += ".weight" - sub = "self_attn." + sub - elif sub in ("attn_sconv.weight", "mlp_sconv.weight"): - sub, value = sub.replace(".weight", ".conv.weight"), _to_mlx_conv(value) - elif sub in ("mlp.gate.weight", "mlp.gate.bias"): - sub = ( - "mlp.gate_weight" - if sub.endswith("weight") - else "mlp.e_score_correction_bias" - ) - else: - name, _, leaf = sub.partition(".") - sub = _NORMS.get(name, name) + "." + leaf - out[base + sub] = value - elif key.startswith("model.llm.attn_res."): - sub = key[len("model.llm.attn_res.") :] - if sub == "output_query": - target = "final_input.query" - else: - kind, index = sub.split(".") - layer = int(index) + (kind == "attn_queries") - name = "attention_input" if kind == "attn_queries" else "mlp_input" - target = f"layers.{layer}.{name}.query" - out["language_model.model." + target] = value - elif key.startswith("model.llm."): - sub = key[len("model.llm.") :] - out[ - ( - "language_model.lm_head.weight" - if sub == "unembed.weight" - else "language_model.model." - + sub.replace("embed.weight", "embed_tokens.weight") - ) - ] = value - elif key.startswith("model.visual."): - sub = key[len("model.visual.") :].removeprefix("backbone.") - for old, new in _VISION: - sub = sub.replace(old, new) - out["vision_tower." + sub] = value - for layer, tensors in experts.items(): - base = f"language_model.model.layers.{layer}.mlp.switch_mlp." - for name, projections in ( - ("w13_weight", ("gate_proj", "up_proj")), - ("w2_weight", ("down_proj",)), - ): - values = { - "weight": tensors[name].view(mx.uint32), - "scales": tensors[name + "_scale"], - } - if name + "_amax" in tensors: - values["weight_scale_2"] = ( - tensors[name + "_amax"] / tensors[name + "_outer_scale_denominator"] - ) - for suffix, v in values.items(): - parts = ( - _split_gate_up(v) - if len(projections) == 2 and suffix != "weight_scale_2" - else (v,) * len(projections) - ) - for projection, part in zip(projections, parts): - out[base + projection + "." + suffix] = part - for projection in projections: - specs[base + projection] = ( - _NVFP4 if "weight_scale_2" in values else _MXFP8 - ) - base = "language_model.model." - if base + "middle_cycle_cross_pass_queries" in out: - attn_mlp = out.pop(base + "middle_cycle_cross_pass_queries").reshape( - -1, 2, hidden - ) - kv = out.pop(base + "middle_cycle_cross_pass_kv_queries").reshape(-1, 2, hidden) - out[base + "message_queries"] = mx.concatenate( - [attn_mlp[:, :1], kv, attn_mlp[:, 1:]], axis=1 - ) - return out, specs - - -def _mlx_vlm_checkpoint( - source_dir, dest, *, quantize_attention=False, expert_bits=None -): - """Write ``source_dir`` the way an mlx-vlm quantized build ships it. - - ``expert_bits`` maps gate/up/down to affine bits, replacing the source's - NVFP4/MXFP8 experts the way mixed-precision builds quantize them. - """ - shutil.copytree( - source_dir, - dest, - ignore=shutil.ignore_patterns("*.safetensors", "hf_quant_config.json"), - ) - shutil.copy(source_dir / "mtp.safetensors", dest / "mtp.safetensors") - config = json.loads((source_dir / "config.json").read_text()) - tensors, specs = _mlx_vlm_tensors( - mx.load(str(source_dir / "model.safetensors")), - config["text_config"]["hidden_size"], - ) - quant = dict(_NVFP4, **specs) - if quantize_attention: - for layer in range(_INK2_LAYERS): - for proj in ("q_proj", "k_proj", "v_proj", "r_proj", "gate_proj", "o_proj"): - path = f"language_model.model.layers.{layer}.self_attn.{proj}" - w, s, b = mx.quantize( - tensors.pop(path + ".weight"), group_size=64, bits=8 - ) - tensors.update( - {path + ".weight": w, path + ".scales": s, path + ".biases": b} - ) - quant[path] = dict(_Q8) - if expert_bits: - rng = mx.random.key(0) - for layer in range(_INK2_LAYERS): - base = f"language_model.model.layers.{layer}.mlp.switch_mlp." - for proj, bits in expert_bits.items(): - path = base + f"{proj}_proj" - text = config["text_config"] - in_dims = text["intermediate_size" if proj == "down" else "hidden_size"] - shape = tensors[path + ".weight"].shape[:-1] + (in_dims,) - rng, key = mx.random.split(rng) - w = (mx.random.normal(shape, key=key) * 0.05).astype(mx.bfloat16) - q, sc, b = mx.quantize(w, group_size=32, bits=bits) - for suffix in ("weight", "scales", "weight_scale_2"): - tensors.pop(f"{path}.{suffix}", None) - tensors.update( - {path + ".weight": q, path + ".scales": sc, path + ".biases": b} - ) - quant[path] = {"group_size": 32, "bits": bits, "mode": "affine"} - config["quantization"] = config["quantization_config"] = quant - (dest / "config.json").write_text(json.dumps(config)) - mx.save_safetensors(str(dest / "model.safetensors"), tensors, {"format": "mlx"}) - return dest - - -@pytest.fixture -def patched_load_config(monkeypatch): - monkeypatch.setattr(model_loading, "_MLX_LM_LOAD_CONFIG_PATCHED", False) - monkeypatch.setattr(mlx_lm_utils, "load_config", mlx_lm_utils.load_config) - model_loading._patch_mlx_lm_load_config() - - -@pytest.mark.parametrize("looped", [False, True], ids=["plain", "looped"]) -def test_mlx_vlm_layout_loads_like_published_layout( - tmp_path, looped, patched_load_config -): - source = tmp_path / "source" - _inkling2_source(source, looped=looped) - vlm = _mlx_vlm_checkpoint(source, tmp_path / "mlx_vlm") - - expected = dict(tree_flatten(_inkling2_model(source).parameters())) - loaded = dict(tree_flatten(_inkling2_model(vlm).parameters())) - - assert loaded.keys() == expected.keys() - for key, value in expected.items(): - assert loaded[key].dtype == value.dtype, key - if key.endswith(".global_scale"): - # mlx-vlm stores amax / denominator; the runtime keeps amax. - assert mx.allclose(loaded[key], value, rtol=1e-6).item(), key - else: - assert mx.array_equal(loaded[key], value, equal_nan=True).item(), key - - -def test_quantized_attention_keeps_its_codes(tmp_path, patched_load_config): - source = tmp_path / "source" - _inkling2_source(source, looped=True) - vlm = _mlx_vlm_checkpoint(source, tmp_path / "mlx_vlm", quantize_attention=True) - - expected = _inkling2_model(source) - loaded = _inkling2_model(vlm) - - # Affine codes are local to a row, so the fused projections, including the - # unquantized sink and dynamic-conv rows, match quantizing the fused BF16 - # weight in one go. - for layer, (ref, got) in enumerate(zip(expected.model.layers, loaded.model.layers)): - names = ["o_proj"] + ( - ["in_proj"] if ref.attn.sliding else ["q_proj", "k_proj", "v_proj"] - ) - for name in names: - module = getattr(got.attn, name) - assert isinstance(module, nn.QuantizedLinear), f"layer {layer} {name}" - w, s, b = mx.quantize(getattr(ref.attn, name).weight, group_size=64, bits=8) - for want, have in ( - (w, module.weight), - (s, module.scales), - (b, module.biases), - ): - assert mx.array_equal(want, have).item(), f"layer {layer} {name}" - - -@pytest.mark.parametrize("bits", [(2, 3, 4), (4, 2, 8), (3, 6, 3)], ids=str) -def test_mixed_bit_experts_widen_losslessly(tmp_path, bits, patched_load_config): - # Mixed-precision builds can quantize gate and up at different bits; the - # runtime fuses them into w13, so the narrower rows are widened. - source = tmp_path / "source" - _inkling2_source(source, looped=True) - gate, up, down = bits - vlm = _mlx_vlm_checkpoint( - source, - tmp_path / "mlx_vlm", - expert_bits={"gate": gate, "up": up, "down": down}, - ) - tensors = mx.load(str(vlm / "model.safetensors")) - loaded = _inkling2_model(vlm) - - def dequant(path, b): - return mx.dequantize( - tensors[path + ".weight"], - tensors[path + ".scales"], - tensors[path + ".biases"], - group_size=32, - bits=b, - ) - - for layer, block in enumerate(loaded.model.layers): - experts = block.mlp.experts - base = f"language_model.model.layers.{layer}.mlp.switch_mlp." - g, u = dequant(base + "gate_proj", gate), dequant(base + "up_proj", up) - w13 = mx.stack([g, u], axis=-2).reshape(*g.shape[:-2], -1, g.shape[-1]) - assert experts.w13.bits == max(gate, up) - for proj, want in ( - (experts.w13, w13), - (experts.w2, dequant(base + "down_proj", down)), - ): - got = mx.dequantize( - proj.weight, proj.scales, proj.biases, group_size=32, bits=proj.bits - ) - assert mx.array_equal(got, want).item(), f"layer {layer}" - - -def test_fused_specs_take_the_widest_affine_bits(): - from omlx.patches.inkling2.loader import mlx_vlm_quantization - - args = TextArgs.from_dict( - {"num_hidden_layers": 2, "local_layer_ids": [0], "hidden_size": 64} - ) - base = "language_model.model.layers.0.self_attn." - quant = mlx_vlm_quantization( - {base + "q_proj": dict(_Q8, bits=4), base + "k_proj": _Q8}, args - ) - assert quant["model.layers.0.attn.in_proj"] == _Q8 - # Rows with another group size or mode cannot be re-encoded losslessly. - for other in (dict(_Q8, group_size=32), _NVFP4): - with pytest.raises(ValueError, match="different quantization"): - mlx_vlm_quantization({base + "q_proj": _Q8, base + "k_proj": other}, args) - - -def test_rewritten_quantization_is_left_alone(tmp_path): - # load_config may run the normalizers again on a rewritten config, which by - # then also carries the language_model.-prefixed variants of its keys. - source = tmp_path / "source" - _inkling2_source(source, looped=True) - vlm = _mlx_vlm_checkpoint(source, tmp_path / "mlx_vlm", quantize_attention=True) - cfg = json.loads((vlm / "config.json").read_text()) - - model_loading.normalize_inkling2_mlx_vlm_quant(cfg) - model_loading.expand_per_layer_quant_keys(cfg) - once = copy.deepcopy(cfg["quantization"]) - assert "model.layers.0.attn.in_proj" in once - model_loading.normalize_inkling2_mlx_vlm_quant(cfg) - - assert cfg["quantization"] == once diff --git a/tests/test_oq.py b/tests/test_oq.py index 9af967d1f8..4b13849faa 100644 --- a/tests/test_oq.py +++ b/tests/test_oq.py @@ -3,9 +3,11 @@ import json import os +import shutil import sys import threading from pathlib import Path +from types import SimpleNamespace from unittest.mock import MagicMock, patch import numpy as np @@ -10101,6 +10103,139 @@ def test_converted_checkpoint_loads_and_runs(self, inkling2_source, tmp_path): assert mx.array_equal(model.encode_image(pixels, grid), features).item() +@pytest.fixture +def patched_load_config(monkeypatch): + monkeypatch.setattr(model_loading, "_MLX_LM_LOAD_CONFIG_PATCHED", False) + monkeypatch.setattr(mlx_lm_utils, "load_config", mlx_lm_utils.load_config) + model_loading._patch_mlx_lm_load_config() + + +def _store_affine(tensors, quant, path, weight, group_size, bits): + q, scales, biases = mx.quantize(weight, group_size=group_size, bits=bits) + tensors.update( + {f"{path}.weight": q, f"{path}.scales": scales, f"{path}.biases": biases} + ) + quant[path] = {"group_size": group_size, "bits": bits, "mode": "affine"} + + +def _mlx_vlm_inkling2(source, dest, *, attention_bits=None, expert_bits=()): + inkling2 = pytest.importorskip("mlx_vlm.models.inkling2.inkling2") + shutil.copytree(source, dest, ignore=shutil.ignore_patterns("model.safetensors")) + config = json.loads((source / "config.json").read_text()) + text = config["text_config"] + owner = SimpleNamespace(config=SimpleNamespace(text_config=SimpleNamespace(**text))) + tensors = inkling2.Model.sanitize(owner, mx.load(str(source / "model.safetensors"))) + quant = dict(TestInkling2OQ.NVFP4) + for key in [k for k in tensors if ".switch_mlp." in k and k.endswith(".weight")]: + path = key.removesuffix(".weight") + nvfp4 = f"{path}.weight_scale_2" in tensors + quant[path] = TestInkling2OQ.NVFP4 if nvfp4 else TestInkling2OQ.MXFP8 + for layer in range(_INK2_LAYERS): + base = f"language_model.model.layers.{layer}." + for name in ("q", "k", "v", "r", "gate", "o") if attention_bits else (): + path = f"{base}self_attn.{name}_proj" + weight = tensors.pop(f"{path}.weight") + _store_affine(tensors, quant, path, weight, 64, attention_bits) + for name, bits in expert_bits: + path = f"{base}mlp.switch_mlp.{name}_proj" + for suffix in ("scales", "weight_scale_2"): + tensors.pop(f"{path}.{suffix}", None) + in_dims = text["intermediate_size" if name == "down" else "hidden_size"] + shape = tensors.pop(f"{path}.weight").shape[:-1] + (in_dims,) + weight = mx.random.normal(shape, key=mx.random.key(layer)) * 0.05 + _store_affine(tensors, quant, path, weight.astype(mx.bfloat16), 32, bits) + config["quantization"] = config["quantization_config"] = quant + (dest / "config.json").write_text(json.dumps(config)) + mx.save_safetensors(str(dest / "model.safetensors"), tensors, {"format": "mlx"}) + return dest + + +@pytest.mark.skipif(not HAS_MLX, reason="MLX not available") +@pytest.mark.parametrize("looped", [False, True], ids=["plain", "looped"]) +def test_inkling2_mlx_vlm_layout_loads_like_published_layout( + request, tmp_path, looped, patched_load_config +): + source = request.getfixturevalue( + "inkling2_loop_source" if looped else "inkling2_source" + ) + vlm = _mlx_vlm_inkling2(source, tmp_path / "mlx_vlm") + + expected = dict(tree_flatten(_inkling2_model(source).parameters())) + loaded = dict(tree_flatten(_inkling2_model(vlm).parameters())) + + assert loaded.keys() == expected.keys() + for key, value in expected.items(): + assert loaded[key].dtype == value.dtype, key + if key.endswith(".global_scale"): + assert mx.allclose(loaded[key], value, rtol=1e-6).item(), key + else: + assert mx.array_equal(loaded[key], value, equal_nan=True).item(), key + + +@pytest.mark.skipif(not HAS_MLX, reason="MLX not available") +def test_inkling2_mlx_vlm_quantized_build_keeps_its_codes( + inkling2_loop_source, tmp_path, patched_load_config +): + gate, up, down = 2, 3, 4 + vlm = _mlx_vlm_inkling2( + inkling2_loop_source, + tmp_path / "mlx_vlm", + attention_bits=8, + expert_bits=(("gate", gate), ("up", up), ("down", down)), + ) + tensors = mx.load(str(vlm / "model.safetensors")) + reference = _inkling2_model(inkling2_loop_source) + loaded = _inkling2_model(vlm) + + def dequantize(path, bits): + return mx.dequantize( + tensors[f"{path}.weight"], + tensors[f"{path}.scales"], + tensors[f"{path}.biases"], + group_size=32, + bits=bits, + ) + + for layer, (ref, got) in enumerate( + zip(reference.model.layers, loaded.model.layers) + ): + fused = ["in_proj"] if ref.attn.sliding else ["q_proj", "k_proj", "v_proj"] + for name in ["o_proj", *fused]: + module = getattr(got.attn, name) + want = mx.quantize(getattr(ref.attn, name).weight, group_size=64, bits=8) + have = (module.weight, module.scales, module.biases) + for w, h in zip(want, have): + assert mx.array_equal(w, h).item(), f"layer {layer} {name}" + base = f"language_model.model.layers.{layer}.mlp.switch_mlp." + g, u = dequantize(base + "gate_proj", gate), dequantize(base + "up_proj", up) + w13 = mx.stack([g, u], axis=-2).reshape(*g.shape[:-2], -1, g.shape[-1]) + w2 = dequantize(base + "down_proj", down) + experts = got.mlp.experts + assert experts.w13.bits == max(gate, up) + for proj, want in ((experts.w13, w13), (experts.w2, w2)): + have = mx.dequantize( + proj.weight, proj.scales, proj.biases, group_size=32, bits=proj.bits + ) + assert mx.array_equal(have, want).item(), f"layer {layer}" + + +@pytest.mark.skipif(not HAS_MLX, reason="MLX not available") +def test_inkling2_mlx_vlm_quantization_is_rewritten_once( + inkling2_loop_source, tmp_path +): + vlm = _mlx_vlm_inkling2( + inkling2_loop_source, tmp_path / "mlx_vlm", attention_bits=8 + ) + cfg = json.loads((vlm / "config.json").read_text()) + model_loading.normalize_inkling2_mlx_vlm_quant(cfg) + model_loading.expand_per_layer_quant_keys(cfg) + once = json.loads(json.dumps(cfg["quantization"])) + assert "model.layers.0.attn.in_proj" in once + model_loading.normalize_inkling2_mlx_vlm_quant(cfg) + + assert cfg["quantization"] == once + + class TestGemma4AudioConfigSanitize: """Gemma 4 E2B/E4B sanitize reads audio_config.subsampling_conv_channels.