Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
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 <noreply@anthropic.com>
  • Loading branch information
Kenya Nara and claude committed Nov 24, 2026
commit 70e40e38fed43fb5e933adfbff01f521055425c4
282 changes: 282 additions & 0 deletions omlx/patches/inkling2/loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
29 changes: 29 additions & 0 deletions omlx/utils/model_loading.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down
Loading