diff --git a/omlx/patches/inkling2/loader.py b/omlx/patches/inkling2/loader.py index f4e7803f22..516df5015d 100644 --- a/omlx/patches/inkling2/loader.py +++ b/omlx/patches/inkling2/loader.py @@ -81,6 +81,8 @@ 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): + return sanitize_mlx_vlm_weights(model, weights), {} if not is_original_layout(weights): return weights, {} args = model.args.text @@ -186,3 +188,302 @@ def sanitize_weights(model, weights: dict) -> tuple[dict, dict]: if loop_queries: _loop_message_queries(loop_queries, args.loop_core, out) return out, formats + + +_VLM_TEXT = "language_model." +_VLM_LAYER = "language_model.model.layers." +_VLM_VISION = "vision_tower." +_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: + 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: + 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. + + 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(): + 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}") + 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: + *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: + 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) + 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} + + +def _fuse_rows(parts: list, spec, path: str, out: dict) -> None: + 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)) + else: + part = _widen(part, spec) + for suffix, value in part.items(): + columns.setdefault(suffix, []).append(value) + 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: + 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: + 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, quant.get(pre + "mlp.experts.w13")) + 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 + name = key.removeprefix(_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": + 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 afe1e06b20..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 @@ -464,6 +466,24 @@ 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 + quant = cfg.get("quantization") + if not isinstance(quant, dict) or not is_mlx_vlm_quantization(quant): + return cfg + text = TextArgs.from_dict(cfg.get("text_config") or {}) + cfg["quantization"] = mlx_vlm_quantization(quant, text) + 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 @@ -483,6 +503,7 @@ 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) + 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_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.