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
Prev Previous commit
Next Next commit
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 <noreply@anthropic.com>
  • Loading branch information
Kenya Nara and claude committed Nov 24, 2026
commit 222c9febde2449c5dfb9503b474f232b5cc42168
90 changes: 76 additions & 14 deletions omlx/patches/inkling2/loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."
Expand Down Expand Up @@ -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():
Expand All @@ -301,24 +304,77 @@ 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}


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)
Expand All @@ -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:
Expand All @@ -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:
Expand Down Expand Up @@ -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:
Expand Down
82 changes: 75 additions & 7 deletions tests/test_inkling2_mlx_vlm_layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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"})
Expand Down Expand Up @@ -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):
Expand Down