From 25c8b4322c5dad4bca0887a6d878d0ffa2655928 Mon Sep 17 00:00:00 2001 From: jundot Date: Fri, 13 Nov 2026 12:58:42 +0100 Subject: [PATCH 1/5] Add Inkling 2 model Text and image input, with Metal kernels for the prefill attention and the attention residuals. The published checkpoint loads as is, and tensor and pipeline parallel work. --- mlx_lm/kernels/__init__.py | 4 + mlx_lm/kernels/depth_attention.py | 107 +++ mlx_lm/kernels/relative_attention.py | 214 +++++ mlx_lm/models/inkling2.py | 1278 ++++++++++++++++++++++++++ mlx_lm/processors/__init__.py | 7 +- mlx_lm/processors/inkling2.py | 63 ++ tests/model_parallel_tests.py | 26 + tests/models/test_inkling2.py | 282 ++++++ tests/test_kernels.py | 49 + 9 files changed, 2028 insertions(+), 2 deletions(-) create mode 100644 mlx_lm/kernels/depth_attention.py create mode 100644 mlx_lm/kernels/relative_attention.py create mode 100644 mlx_lm/models/inkling2.py create mode 100644 mlx_lm/processors/inkling2.py create mode 100644 tests/models/test_inkling2.py diff --git a/mlx_lm/kernels/__init__.py b/mlx_lm/kernels/__init__.py index 98a488aa8..79b92a59c 100644 --- a/mlx_lm/kernels/__init__.py +++ b/mlx_lm/kernels/__init__.py @@ -2,21 +2,25 @@ """Fused Metal kernels, one kernel per file.""" +from .depth_attention import depth_attention from .expert_routing import expert_routing from .norm_add_norm import norm_add_norm, pre_norm from .post_expert_norm_combine import post_expert_norm_combine from .qk_norm import qk_norm from .qk_norm_rope import qk_norm_rope +from .relative_attention import relative_attention from .rms_norm_sigmoid_gate import rms_norm_sigmoid_gate from .sparse_mla import sparse_mla_attention __all__ = [ + "depth_attention", "expert_routing", "norm_add_norm", "post_expert_norm_combine", "pre_norm", "qk_norm", "qk_norm_rope", + "relative_attention", "rms_norm_sigmoid_gate", "sparse_mla_attention", ] diff --git a/mlx_lm/kernels/depth_attention.py b/mlx_lm/kernels/depth_attention.py new file mode 100644 index 000000000..d816ba068 --- /dev/null +++ b/mlx_lm/kernels/depth_attention.py @@ -0,0 +1,107 @@ +# Copyright © 2026 Apple Inc. + +"""Attention of learned queries over the depth sources of each token, in one +kernel.""" + +import mlx.core as mx + +from ._common import row_threads, scalar + +_SOURCE = """ + constexpr int N = K + 1; + uint row = threadgroup_position_in_grid.x; + uint rows = threadgroups_per_grid.x; + uint tid = thread_position_in_threadgroup.x; + uint lane = thread_index_in_simdgroup; + uint sg = simdgroup_index_in_threadgroup; + + float acc[N * Q]; + for (int i = 0; i < N * Q; i++) { + acc[i] = 0.0f; + } + for (int d = tid; d < D; d += TG) { + float x[N]; + for (int i = 0; i < K; i++) { + x[i] = blocks[(size_t(i) * rows + row) * D + d]; + } + x[K] = partial[size_t(row) * D + d]; + for (int j = 0; j < Q; j++) { + float qv = queries[j * D + d]; + for (int i = 0; i < N; i++) { + acc[i * Q + j] += x[i] * qv; + } + } + } + + threadgroup float buf[N * Q][TG / 32]; + for (int i = 0; i < N * Q; i++) { + float v = simd_sum(acc[i]); + if (lane == 0) { + buf[i][sg] = v; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + float w[N * Q]; + for (int i = 0; i < N * Q; i++) { + float t = 0.0f; + for (int s = 0; s < TG / 32; s++) { + t += buf[i][s]; + } + w[i] = t * scale; + } + for (int j = 0; j < Q; j++) { + float m = -INFINITY; + for (int i = 0; i < N; i++) { + m = max(m, w[i * Q + j]); + } + float z = 0.0f; + for (int i = 0; i < N; i++) { + w[i * Q + j] = metal::exp(w[i * Q + j] - m); + z += w[i * Q + j]; + } + for (int i = 0; i < N; i++) { + w[i * Q + j] /= z; + } + } + + for (int d = tid; d < D; d += TG) { + float x[N]; + for (int i = 0; i < K; i++) { + x[i] = blocks[(size_t(i) * rows + row) * D + d]; + } + x[K] = partial[size_t(row) * D + d]; + for (int j = 0; j < Q; j++) { + float o = 0.0f; + for (int i = 0; i < N; i++) { + o += w[i * Q + j] * x[i]; + } + out[(size_t(row) * Q + j) * D + d] = o; + } + } +""" + +_kernel = mx.fast.metal_kernel( + name="depth_attention", + input_names=["blocks", "partial", "queries", "scale"], + output_names=["out"], + source=_SOURCE, +) + + +def depth_attention( + blocks: mx.array, partial: mx.array, queries: mx.array, *, scale: float +) -> mx.array: + """blocks: (K, ..., D) and partial: (..., D), float32, also the values. + queries: float32 (Q, D). Returns (..., Q, D).""" + D = partial.shape[-1] + Q = queries.shape[0] + TG = row_threads(D) + return _kernel( + inputs=[blocks, partial, queries, scalar(scale)], + template=[("K", blocks.shape[0]), ("D", D), ("Q", Q), ("TG", TG)], + grid=(partial.size // D * TG, 1, 1), + threadgroup=(TG, 1, 1), + output_shapes=[partial.shape[:-1] + (Q, D)], + output_dtypes=[mx.float32], + )[0] diff --git a/mlx_lm/kernels/relative_attention.py b/mlx_lm/kernels/relative_attention.py new file mode 100644 index 000000000..e2e6afecd --- /dev/null +++ b/mlx_lm/kernels/relative_attention.py @@ -0,0 +1,214 @@ +# Copyright © 2026 Apple Inc. + +"""Causal flash attention with a relative position bias and a sink logit per +query.""" + +import mlx.core as mx + +from ._common import scalar + +# Queries per threadgroup, 8 for each of its 4 simdgroups. +_BQ = 32 +_TG = 128 + +# The online softmax of each row starts from its sink logit, so the zero-value +# sink needs no key. +_SOURCE = """ + constexpr float LOG2E = 1.4426950408889634f; + constexpr int BK = 16; + constexpr int LDK = BK + 8; + constexpr int LDV = D + 8; + const int L = sizes[0]; + const int S = sizes[1]; + const uint tid = thread_position_in_threadgroup.x; + const uint sg = simdgroup_index_in_threadgroup; + const uint lane = thread_index_in_simdgroup; + const int batch = threadgroup_position_in_grid.z; + const int head = threadgroup_position_in_grid.y; + const int kv_head = head / (HQ / HKV); + const int q0 = threadgroup_position_in_grid.x * BQ; + const int start = key_start[batch]; + const float qscale = scale * LOG2E; + + // The lane holds row fm and columns fn, fn + 1 of each 8x8 fragment. + const short fm = ((lane / 4) & 4) + (lane / 2) % 4; + const short fn = ((lane / 4) & 2) * 2 + (lane % 2) * 2; + const int row = q0 + int(sg) * 8 + fm; + const bool row_ok = row < L; + const int diag = S - L + row; + + // q and k are clipped and v has unit RMS, so half holds them. + threadgroup half Ks[D * LDK]; + threadgroup half Vs[BK * LDV]; + + simdgroup_half8x8 q_frag[D / 8]; + for (int db = 0; db < D / 8; ++db) { + half2 qv = half2(0.0h); + if (row_ok) { + const device T* qp = q + batch * q_strides[0] + head * q_strides[1] + + row * q_strides[2] + db * 8 + fn; + qv = half2(float(qp[0]), float(qp[1])); + } + q_frag[db].thread_elements()[0] = qv.x; + q_frag[db].thread_elements()[1] = qv.y; + } + simdgroup_float8x8 acc[D / 8]; + for (int db = 0; db < D / 8; ++db) { + acc[db] = make_filled_simdgroup_matrix(0.0f); + } + float row_max = row_ok ? float(sinks[(batch * L + row) * HQ + head]) * LOG2E : 0.0f; + float row_sum = 1.0f; + const int bias_row = batch * L + (row_ok ? row : 0); + const device T* bias = rel + (size_t(bias_row) * HQ + head) * R; + + const int first_diag = S - L + q0; + const int last_diag = S - L + min(q0 + BQ, L) - 1; + int first_key = WINDOW > 0 ? max(0, first_diag - WINDOW + 1) : 0; + first_key = max(first_key, start); + const device T* k_head = k + batch * k_strides[0] + kv_head * k_strides[1]; + const device T* v_head = v + batch * v_strides[0] + kv_head * v_strides[1]; + + for (int k0 = first_key / BK * BK; k0 <= last_diag; k0 += BK) { + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int c = tid; c < BK * D / 8; c += TG) { + const int r = c / (D / 8); + const int col = (c % (D / 8)) * 8; + const int key = k0 + r; + vec kv[2] = {vec(0), vec(0)}; + vec vv[2] = {vec(0), vec(0)}; + if (key < S) { + auto kp = (const device vec*)(k_head + key * k_strides[2] + col); + auto vp = (const device vec*)(v_head + key * v_strides[2] + col); + kv[0] = kp[0]; + kv[1] = kp[1]; + vv[0] = vp[0]; + vv[1] = vp[1]; + } + for (int j = 0; j < 8; ++j) { + Ks[(col + j) * LDK + r] = half(float(kv[j / 4][j % 4])); + Vs[r * LDV + col + j] = half(float(vv[j / 4][j % 4])); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (q0 + int(sg) * 8 >= L) { + continue; + } + + simdgroup_float8x8 scores[BK / 8]; + for (int kb = 0; kb < BK / 8; ++kb) { + scores[kb] = make_filled_simdgroup_matrix(0.0f); + for (int db = 0; db < D / 8; ++db) { + simdgroup_half8x8 k_frag; + simdgroup_load(k_frag, Ks + db * 8 * LDK + kb * 8, LDK); + simdgroup_multiply_accumulate(scores[kb], q_frag[db], k_frag, scores[kb]); + } + } + + float tile_max = -INFINITY; + for (int kb = 0; kb < BK / 8; ++kb) { + for (int e = 0; e < 2; ++e) { + const int key = k0 + kb * 8 + fn + e; + const int d = diag - key; + const bool visible = row_ok && d >= 0 && key >= start + && (WINDOW == 0 || d < WINDOW); + float s = -INFINITY; + if (visible) { + s = scores[kb].thread_elements()[e] * qscale; + if (d < R) { + s += float(bias[d]) * LOG2E; + } + } + scores[kb].thread_elements()[e] = s; + tile_max = max(tile_max, s); + } + } + // The 4 lanes of a row are lane ^ 1 and lane ^ 8 apart. + tile_max = max(tile_max, simd_shuffle_xor(tile_max, 1)); + tile_max = max(tile_max, simd_shuffle_xor(tile_max, 8)); + const float new_max = max(row_max, tile_max); + const float factor = fast::exp2(row_max - new_max); + float tile_sum = 0.0f; + simdgroup_half8x8 probs[BK / 8]; + for (int kb = 0; kb < BK / 8; ++kb) { + for (int e = 0; e < 2; ++e) { + const float p = fast::exp2(scores[kb].thread_elements()[e] - new_max); + probs[kb].thread_elements()[e] = half(p); + tile_sum += p; + } + } + tile_sum += simd_shuffle_xor(tile_sum, 1); + tile_sum += simd_shuffle_xor(tile_sum, 8); + row_sum = row_sum * factor + tile_sum; + row_max = new_max; + for (int db = 0; db < D / 8; ++db) { + acc[db].thread_elements()[0] *= factor; + acc[db].thread_elements()[1] *= factor; + for (int kb = 0; kb < BK / 8; ++kb) { + simdgroup_half8x8 v_frag; + simdgroup_load(v_frag, Vs + kb * 8 * LDV + db * 8, LDV); + simdgroup_multiply_accumulate(acc[db], probs[kb], v_frag, acc[db]); + } + } + } + + if (row_ok) { + device T* op = out + (size_t(batch * L + row) * HQ + head) * D; + for (int db = 0; db < D / 8; ++db) { + op[db * 8 + fn] = T(acc[db].thread_elements()[0] / row_sum); + op[db * 8 + fn + 1] = T(acc[db].thread_elements()[1] / row_sum); + } + } +""" + +_kernel = mx.fast.metal_kernel( + name="relative_attention", + input_names=["q", "k", "v", "rel", "sinks", "key_start", "sizes", "scale"], + output_names=["out"], + source=_SOURCE, + ensure_row_contiguous=False, +) + + +def relative_attention( + q: mx.array, + k: mx.array, + v: mx.array, + rel: mx.array, + sinks: mx.array, + *, + scale: float, + window: int, + key_start: mx.array, +) -> mx.array: + """q: (B, Hq, L, D), k and v: (B, Hkv, S, D), all bfloat16, with the queries + at the last L keys. rel: (B, L, Hq, R), the bias at distances below R. + sinks: (B, L, Hq). key_start: (B,), the first key of each row. Returns + (B, L, Hq, D).""" + B, Hq, L, D = q.shape + Hkv, S = k.shape[1], k.shape[2] + return _kernel( + inputs=[ + q, + k, + v, + mx.contiguous(rel), + mx.contiguous(sinks.astype(mx.float32)), + mx.contiguous(key_start.astype(mx.int32)), + mx.array([L, S], dtype=mx.int32), + scalar(scale), + ], + template=[ + ("T", q.dtype), + ("D", D), + ("HQ", Hq), + ("HKV", Hkv), + ("R", rel.shape[-1]), + ("WINDOW", window), + ("BQ", _BQ), + ("TG", _TG), + ], + grid=((L + _BQ - 1) // _BQ * _TG, Hq, B), + threadgroup=(_TG, 1, 1), + output_shapes=[(B, L, Hq, D)], + output_dtypes=[q.dtype], + )[0] diff --git a/mlx_lm/models/inkling2.py b/mlx_lm/models/inkling2.py new file mode 100644 index 000000000..c216bbbd1 --- /dev/null +++ b/mlx_lm/models/inkling2.py @@ -0,0 +1,1278 @@ +# Copyright © 2026 Apple Inc. + +"""Inkling 2. + +https://huggingface.co/thinkingmachines/Inkling-2-Small +""" + +import math +import re +from dataclasses import dataclass +from functools import partial +from typing import Any, Callable + +import mlx.core as mx +from mlx import nn +from mlx.nn.layers.distributed import shard_linear, sum_gradients +from mlx.utils import tree_unflatten + +from ..kernels import depth_attention, expert_routing, relative_attention +from .base import BaseModelArgs, gather_last_axis +from .cache import ( + ArraysCache, + BatchRotatingKVCache, + CacheList, + KVCache, + RotatingKVCache, +) +from .muse_spark import shard_experts_inplace +from .pipeline import PipelineMixin +from .switch_layers import SwitchLinear, _gather_sort, _scatter_unsort + +_ROUTER_SCORE_EPS = 1e-20 + +_NVFP4_E2M1_MAX = 6.0 +_NVFP4_E4M3_MAX = 448.0 + + +_RENAMES = [ + (r"^model\.llm\.unembed\.", "lm_head."), + (r"^model\.llm\.embed\.", "model.language_model.embed_tokens."), + (r"^model\.llm\.", "model.language_model."), + (r"\.attn_res\.mlp_queries\.(\d+)$", r".layers.\1.mlp_input.query"), + (r"\.attn_res\.output_query$", ".final_input.query"), + (r"\.attn\.wq_du\.", ".self_attn.q_proj."), + (r"\.attn\.wk_dv\.", ".self_attn.k_proj."), + (r"\.attn\.wv_dv\.", ".self_attn.v_proj."), + (r"\.attn\.wr_du\.", ".self_attn.r_proj."), + (r"\.attn\.wo_ud\.", ".self_attn.o_proj."), + (r"\.attn\.gate_attn\.", ".self_attn.gate_proj."), + (r"\.attn\.attn_sink_proj\.", ".self_attn.sink_proj."), + (r"\.attn\.", ".self_attn."), + (r"\.attn_sconv\.", ".post_attention_convolution."), + (r"\.mlp_sconv\.", ".post_mlp_convolution."), + (r"sconv\.weight$", "sconv.conv1d.weight"), + (r"convolution\.weight$", "convolution.conv1d.weight"), + (r"sconv\.static_w$", "sconv.static_weight"), + (r"sconv\.weight_proj$", "sconv.weight_proj.weight"), + (r"\.mlp_norm\.", ".post_attention_layernorm."), + (r"\.attn_norm\.", ".input_layernorm."), + (r"\.(q|k|v)_input_norm\.", r".\1_input_layernorm."), + (r"\.mlp\.gate\.bias$", ".mlp.gate.e_score_correction_bias"), + (r"^model\.visual\.backbone\.ln_pre\.", "model.vision_tower.pre_layernorm."), + (r"^model\.visual\.backbone\.", "model.vision_tower."), + (r"^model\.visual\.proj_in\.", "model.vision_tower.merger.linear_1."), + (r"^model\.visual\.proj_out\.", "model.vision_tower.merger.linear_2."), + (r"embeddings\.position_embedding$", "embeddings.position_embedding.weight"), + (r"(vision_tower\.layers\.\d+)\.ln_1\.", r"\1.layernorm_before."), + (r"(vision_tower\.layers\.\d+)\.ln_2\.", r"\1.layernorm_after."), + (r"(vision_tower\.layers\.\d+)\.mlp\.c_fc\.", r"\1.mlp.fc1."), + (r"(vision_tower\.layers\.\d+)\.mlp\.c_proj\.", r"\1.mlp.fc2."), + (r"(vision_tower\.layers\.\d+)\.ls_(\d)\.gamma$", r"\1.lambda_\2"), +] + + +def _rename(key: str) -> str: + if m := re.match(r"model\.llm\.attn_res\.attn_queries\.(\d+)$", key): + # Layer 0 has no attention input, so query i is for layer i + 1. + layer = int(m.group(1)) + 1 + return f"model.language_model.layers.{layer}.attention_input.query" + for pattern, replacement in _RENAMES: + key = re.sub(pattern, replacement, key) + return key + + +@dataclass +class TextArgs(BaseModelArgs): + hidden_size: int + num_hidden_layers: int + vocab_size: int + unpadded_vocab_size: int + num_attention_heads: int + num_key_value_heads: int + head_dim: int + swa_num_attention_heads: int + swa_num_key_value_heads: int + swa_head_dim: int + sliding_window_size: int + local_layer_ids: list[int] + d_rel: int + rel_extent: int + log_scaling_n_floor: int + log_scaling_alpha: float + rms_norm_eps: float + qk_l2_clip_threshold: float + rel_l2_clip_threshold: float + sconv_kernel_size: int + n_layers_per_attn_res_block: int + n_routed_experts: int + num_experts_per_tok: int + intermediate_size: int + mlp_gate_softcap: float + mlp_up_softcap: float + route_scale: float + final_logit_softcapping: float + + +@dataclass +class VisionArgs(BaseModelArgs): + hidden_size: int = 1024 + num_hidden_layers: int = 23 + num_attention_heads: int = 16 + num_channels: int = 3 + native_patch_size: int = 20 + adapter_merge_size: int = 2 + posemb_grid_size: int = 32 + projection_hidden_dim: int = 4096 + projector_bias: bool = False + mlp_ratio: float = 4.0 + layer_norm_eps: float = 1e-5 + rope_theta: float = 10000.0 + + def __post_init__(self): + self.head_dim = self.hidden_size // self.num_attention_heads + self.intermediate_size = int(self.hidden_size * self.mlp_ratio) + + +@dataclass +class ModelArgs(BaseModelArgs): + model_type: str + text_config: dict + vision_config: dict | None = None + image_token_id: int = 200054 + + def __post_init__(self): + self.text = TextArgs.from_dict(self.text_config) + self.vision = None + if self.vision_config: + self.vision = VisionArgs.from_dict(self.vision_config) + + +def _use_kernels() -> bool: + return mx.default_device() == mx.gpu and mx.metal.is_available() + + +def _unweighted_rms_norm(x: mx.array, eps: float = 1e-6) -> mx.array: + return mx.fast.rms_norm(x, None, eps) + + +def _precise_gelu(x: mx.array) -> mx.array: + return nn.gelu(x.astype(mx.float32)).astype(x.dtype) + + +@partial(mx.compile, shapeless=True) +def _l2_clip(hidden_states: mx.array, scale: mx.array, threshold: float) -> mx.array: + states = hidden_states.astype(mx.float32) * scale + norm = mx.sqrt((states * states).sum(axis=-1, keepdims=True)) + scaled = states * mx.minimum(threshold / (norm + 1e-6), 1.0) + return scaled.astype(hidden_states.dtype) + + +@partial(mx.compile, shapeless=True) +def _softcapped_swiglu( + gate: mx.array, up: mx.array, gate_softcap: float, up_softcap: float +) -> mx.array: + input_dtype = gate.dtype + gate, up = gate.astype(mx.float32), up.astype(mx.float32) + gate_capped = mx.tanh(gate / gate_softcap) * gate_softcap + up_capped = mx.tanh(up / up_softcap) * up_softcap + return (gate_capped * mx.sigmoid(gate) * up_capped).astype(input_dtype) + + +class L2Clip(nn.Module): + def __init__(self, threshold: float): + super().__init__() + self.threshold = threshold + + def __call__(self, hidden_states: mx.array) -> mx.array: + return _l2_clip(hidden_states, 1.0, self.threshold) + + +class ScaledL2Clip(nn.Module): + def __init__(self, num_heads: int, head_dim: int, threshold: float): + super().__init__() + self.threshold = threshold + self.scale = mx.ones((num_heads, head_dim)) + + def __call__(self, hidden_states: mx.array) -> mx.array: + return _l2_clip(hidden_states, self.scale, self.threshold) + + +class RelativeLogits(nn.Module): + def __init__(self, d_rel: int, rel_extent: int): + super().__init__() + self.proj = mx.zeros((d_rel, rel_extent)) + + def __call__(self, relative_states: mx.array) -> mx.array: + return relative_states @ self.proj.astype(relative_states.dtype) + + +def _conv_input( + hidden_states: mx.array, + conv_state: mx.array | None, + conv_mask: mx.array | None, + kernel_size: int, +) -> mx.array: + hidden_states = hidden_states.astype(mx.float32) + if conv_mask is not None: + hidden_states = mx.where(conv_mask[..., None], hidden_states, 0) + if conv_state is None: + shape = (hidden_states.shape[0], kernel_size - 1, hidden_states.shape[-1]) + conv_state = mx.zeros(shape, mx.float32) + return mx.concatenate([conv_state, hidden_states], axis=1) + + +def _conv_state(window: mx.array, lengths: mx.array | None, n: int) -> mx.array: + if lengths is None: + pos = mx.arange(window.shape[1] - n, window.shape[1])[None, :, None] + else: + ends = mx.clip(lengths, 0, window.shape[1] - n) + pos = (ends[:, None] + mx.arange(n))[..., None] + # A gather copies, so the state does not keep the input in memory. + return mx.take_along_axis(window, pos, axis=1) + + +class ShortConvolution(nn.Module): + def __init__(self, dims: int, kernel_size: int): + super().__init__() + self.kernel_size = kernel_size + self.conv1d = nn.Conv1d(dims, dims, kernel_size, groups=dims, bias=False) + + def __call__( + self, + hidden_states: mx.array, + conv_state: mx.array | None, + conv_mask: mx.array | None, + ) -> tuple[mx.array, mx.array]: + K = self.kernel_size + residual = hidden_states.astype(mx.float32) + window = _conv_input(hidden_states, conv_state, conv_mask, K) + # As the reference, the conv runs in the weight dtype. + out = self.conv1d(window.astype(self.conv1d.weight.dtype)) + out = (out.astype(mx.float32) + residual) / math.sqrt(K + 1) + return out.astype(hidden_states.dtype), window + + +class DynamicShortConvolution(nn.Module): + def __init__(self, dims: int, input_dims: int, num_heads: int, kernel_size: int): + super().__init__() + self.kernel_size = kernel_size + self.num_heads = num_heads + self.static_weight = mx.zeros((kernel_size, dims)) + self.weight_proj = nn.Linear(input_dims, num_heads * kernel_size, bias=False) + + def __call__( + self, + hidden_states: mx.array, + dynamic_input: mx.array, + conv_state: mx.array | None, + conv_mask: mx.array | None, + ) -> tuple[mx.array, mx.array]: + B, L, C = hidden_states.shape + K, H = self.kernel_size, self.num_heads + dynamic_weights = self.weight_proj(dynamic_input).astype(mx.float32) + dynamic_weights = dynamic_weights.reshape(B, L, H, 1, K) + static_weights = self.static_weight.astype(mx.float32).T.reshape(H, -1, K) + weights = static_weights + dynamic_weights + + window = _conv_input(hidden_states, conv_state, conv_mask, K) + windows = mx.stack( + [window[:, K - 1 - lag : K - 1 - lag + L] for lag in range(K)], axis=-1 + ) + windows = windows.reshape(B, L, H, -1, K) + out = (windows * weights).sum(axis=-1).reshape(B, L, C) + out = (out + hidden_states.astype(mx.float32)) / math.sqrt(2 * K + 1) + return out.astype(hidden_states.dtype), window + + +def _positions(offset, length: int) -> mx.array: + pos = mx.arange(length) + if isinstance(offset, mx.array): + return offset[:, None] + pos + return pos + offset + + +def _key_positions(cache: Any, num_keys: int, num_queries: int, end) -> mx.array: + k = mx.arange(num_keys) + if num_queries == 1 and isinstance(cache, (RotatingKVCache, BatchRotatingKVCache)): + # A decode step writes in place, so the keys can be rotated. + k = (k - cache._idx) % num_keys + if isinstance(end, mx.array): + return (end - num_keys)[:, None] + k + return k + (end - num_keys) + + +def _attention_reference( + query: mx.array, + key: mx.array, + value: mx.array, + position_bias: mx.array, + sinks: mx.array, + *, + scale: float, + window: int, + query_positions: mx.array, + key_positions: mx.array, +) -> mx.array: + B, Hq, L, D = query.shape + Hkv, S = key.shape[1], key.shape[2] + R = position_bias.shape[-1] + distance = query_positions[..., :, None] - key_positions[..., None, :] + visible = (distance >= 0) & (key_positions[..., None, :] >= 0) + if window: + visible = visible & (distance < window) + if distance.ndim == 3: + distance, visible = distance[:, None], visible[:, None] + bias = mx.take_along_axis( + position_bias.transpose(0, 2, 1, 3), + mx.broadcast_to(mx.clip(distance, 0, R - 1), (B, Hq, L, S)), + axis=-1, + ) + bias = mx.where(distance < R, bias.astype(mx.float32), 0.0) + attention_mask = mx.where(visible, bias, -mx.inf).reshape(B, Hkv, -1, L, S) + + query = query.astype(mx.float32).reshape(B, Hkv, -1, L, D) + key = key.astype(mx.float32)[:, :, None] + attn_weights = (query @ key.swapaxes(-1, -2)) * scale + attention_mask + sinks = sinks.astype(mx.float32).transpose(0, 2, 1).reshape(B, Hkv, -1, L, 1) + combined_logits = mx.concatenate([attn_weights, sinks], axis=-1) + attn_weights = mx.softmax(combined_logits, axis=-1)[..., :S] + attn_output = attn_weights.astype(value.dtype) @ value[:, :, None] + return attn_output.reshape(B, Hq, L, D).transpose(0, 2, 1, 3) + + +class Attention(nn.Module): + def __init__(self, args: TextArgs, *, sliding: bool): + super().__init__() + if sliding: + self.num_heads = args.swa_num_attention_heads + self.num_key_value_heads = args.swa_num_key_value_heads + self.head_dim = args.swa_head_dim + self.sliding_window = args.sliding_window_size + rel_extent = args.sliding_window_size + else: + self.num_heads = args.num_attention_heads + self.num_key_value_heads = args.num_key_value_heads + self.head_dim = args.head_dim + self.sliding_window = 0 + rel_extent = args.rel_extent + self.scaling = self.head_dim**-0.5 + + dim = args.hidden_size + q_dim = self.num_heads * self.head_dim + kv_dim = self.num_key_value_heads * self.head_dim + self.q_proj = nn.Linear(dim, q_dim, bias=False) + self.k_proj = nn.Linear(dim, kv_dim, bias=False) + self.v_proj = nn.Linear(dim, kv_dim, bias=False) + self.r_proj = nn.Linear(dim, self.num_heads * args.d_rel, bias=False) + self.o_proj = nn.Linear(q_dim, dim, bias=False) + self.gate_proj = nn.Linear(dim, q_dim, bias=False) + self.sink_proj = nn.Linear(dim, self.num_heads, bias=False) + self.rel_logits_proj = RelativeLogits(args.d_rel, rel_extent) + self.q_l2_clip = ScaledL2Clip( + self.num_heads, self.head_dim, args.qk_l2_clip_threshold + ) + self.k_l2_clip = L2Clip(args.qk_l2_clip_threshold) + self.rel_l2_clip = ScaledL2Clip( + self.num_heads, args.d_rel, args.rel_l2_clip_threshold + ) + self.eps = args.rms_norm_eps + + def _attend( + self, + hidden_states: mx.array, + query_states: mx.array, + key_states: mx.array, + value_states: mx.array, + relative_states: mx.array, + cache: Any | None, + tau: mx.array | None = None, + ) -> mx.array: + B, L, _ = hidden_states.shape + gate = self.gate_proj(hidden_states) + sinks = self.sink_proj(hidden_states) + + query_states = query_states.reshape(B, L, self.num_heads, -1) + key_states = key_states.reshape(B, L, self.num_key_value_heads, -1) + value_states = value_states.reshape(B, L, self.num_key_value_heads, -1) + relative_states = relative_states.reshape(B, L, self.num_heads, -1) + query_states = self.q_l2_clip(query_states) + key_states = self.k_l2_clip(key_states) + value_states = _unweighted_rms_norm( + value_states.astype(mx.float32), self.eps + ).astype(value_states.dtype) + relative_states = self.rel_l2_clip(relative_states) + if tau is not None: + query_states = (query_states.astype(mx.float32) * tau).astype( + query_states.dtype + ) + relative_states = (relative_states.astype(mx.float32) * tau).astype( + relative_states.dtype + ) + position_bias = self.rel_logits_proj(relative_states) + + query_states = query_states.transpose(0, 2, 1, 3) + key_states = key_states.transpose(0, 2, 1, 3) + value_states = value_states.transpose(0, 2, 1, 3) + if cache is not None: + key_states, value_states = cache.update_and_fetch(key_states, value_states) + attn_output = self._attention( + query_states, key_states, value_states, position_bias, sinks, cache + ) + + attn_output = attn_output.reshape(B, L, -1).astype(mx.float32) + attn_output = attn_output * mx.sigmoid(gate.astype(mx.float32)) + return self.o_proj(attn_output.astype(gate.dtype)) + + def _attention(self, query, key, value, position_bias, sinks, cache) -> mx.array: + B, _, L, _ = query.shape + S = key.shape[2] + end = cache.offset if cache is not None else L + bf16 = query.dtype == key.dtype == value.dtype == mx.bfloat16 + if L > 1 and _use_kernels() and bf16: + key_start = mx.broadcast_to(S - end, (B,)) + return relative_attention( + query, + key, + value, + position_bias, + sinks, + scale=self.scaling, + window=self.sliding_window, + key_start=key_start, + ) + + query_positions = _positions(end - L, L) + key_positions = _key_positions(cache, S, L, end) + if L == 1 and B == 1: + # The fused attention takes the sinks of one row. + distance = query_positions.reshape(1) - key_positions.reshape(S) + R = position_bias.shape[-1] + bias = mx.take(position_bias[0, 0], mx.clip(distance, 0, R - 1), axis=-1) + bias = mx.where(distance < R, bias, mx.zeros_like(bias)) + visible = (distance >= 0) & (key_positions.reshape(S) >= 0) + if self.sliding_window: + visible = visible & (distance < self.sliding_window) + mask = mx.where(visible, bias, -mx.inf).astype(query.dtype) + attn_output = mx.fast.scaled_dot_product_attention( + query, + key, + value, + scale=self.scaling, + mask=mask[None, :, None, :], + sinks=sinks[0, 0].astype(query.dtype), + ) + return attn_output.transpose(0, 2, 1, 3) + + return _attention_reference( + query, + key, + value, + position_bias, + sinks, + scale=self.scaling, + window=self.sliding_window, + query_positions=query_positions, + key_positions=key_positions, + ) + + +class SlidingAttention(Attention): + def __init__(self, args: TextArgs): + super().__init__(args, sliding=True) + dims = self.num_key_value_heads * self.head_dim + self.k_sconv = ShortConvolution(dims, args.sconv_kernel_size) + self.v_sconv = ShortConvolution(dims, args.sconv_kernel_size) + + def __call__( + self, + hidden_states: mx.array, + *, + cache: Any | None, + conv_states: list, + conv_mask: mx.array | None, + ) -> mx.array: + kv_cache = cache[0] if cache is not None else None + key_states, conv_states[0] = self.k_sconv( + self.k_proj(hidden_states), conv_states[0], conv_mask + ) + value_states, conv_states[1] = self.v_sconv( + self.v_proj(hidden_states), conv_states[1], conv_mask + ) + return self._attend( + hidden_states, + self.q_proj(hidden_states), + key_states, + value_states, + self.r_proj(hidden_states), + kv_cache, + ) + + +class FullAttention(Attention): + def __init__(self, args: TextArgs): + super().__init__(args, sliding=False) + dims = self.num_key_value_heads * self.head_dim + conv_args = (args.hidden_size, self.num_key_value_heads, args.sconv_kernel_size) + self.k_sconv = DynamicShortConvolution(dims, *conv_args) + self.v_sconv = DynamicShortConvolution(dims, *conv_args) + self.log_scaling_n_floor = args.log_scaling_n_floor + self.log_scaling_alpha = args.log_scaling_alpha + + def __call__( + self, + hidden_states: mx.array, + key_hidden_states: mx.array, + value_hidden_states: mx.array, + *, + cache: Any | None, + conv_states: list, + conv_mask: mx.array | None, + ) -> mx.array: + kv_cache = cache[0] if cache is not None else None + key_states, conv_states[0] = self.k_sconv( + self.k_proj(key_hidden_states), + key_hidden_states, + conv_states[0], + conv_mask, + ) + value_states, conv_states[1] = self.v_sconv( + self.v_proj(value_hidden_states), + value_hidden_states, + conv_states[1], + conv_mask, + ) + + offset = kv_cache.offset if kv_cache is not None else 0 + position_ids = _positions(offset, hidden_states.shape[1]).astype(mx.float32) + tau = 1.0 + self.log_scaling_alpha * mx.log( + mx.maximum((position_ids + 1) / self.log_scaling_n_floor, 1.0) + ) + return self._attend( + hidden_states, + self.q_proj(hidden_states), + key_states, + value_states, + self.r_proj(hidden_states), + kv_cache, + tau=tau[..., None, None], + ) + + +class SoftcappedSwiGLU(nn.Module): + def __init__(self, args: TextArgs): + super().__init__() + self.gate_softcap = args.mlp_gate_softcap + self.up_softcap = args.mlp_up_softcap + + def __call__(self, gate: mx.array, up: mx.array) -> mx.array: + return _softcapped_swiglu(gate, up, self.gate_softcap, self.up_softcap) + + +class Experts(nn.Module): + def __init__(self, args: TextArgs): + super().__init__() + dims, hidden = args.hidden_size, args.intermediate_size + num_experts = args.n_routed_experts + # The rows alternate between gate and up, as in the checkpoint. + self.gate_up_proj = SwitchLinear(dims, 2 * hidden, num_experts, bias=False) + self.down_proj = SwitchLinear(hidden, dims, num_experts, bias=False) + self.act_fn = SoftcappedSwiGLU(args) + + def __call__(self, x: mx.array, indices: mx.array) -> mx.array: + x = mx.expand_dims(x, (-2, -3)) + indices = mx.stop_gradient(indices) + do_sort = indices.size >= 64 + idx, inv_order = indices, None + if do_sort: + x, idx, inv_order = _gather_sort(x, indices) + gate_up = self.gate_up_proj(x, idx, sorted_indices=do_sort) + x = self.act_fn(gate_up[..., 0::2], gate_up[..., 1::2]) + x = self.down_proj(x, idx, sorted_indices=do_sort) + if do_sort: + x = _scatter_unsort(x, inv_order, indices.shape) + return x.squeeze(-2) + + +class TopKRouter(nn.Module): + def __init__(self, args: TextArgs): + super().__init__() + self.top_k = args.num_experts_per_tok + self.routed_scaling_factor = args.route_scale + num_experts, dims = args.n_routed_experts, args.hidden_size + self.weight = mx.zeros((num_experts, dims), dtype=mx.float32) + self.e_score_correction_bias = mx.zeros((num_experts,), dtype=mx.float32) + + def __call__(self, hidden_states: mx.array) -> tuple[mx.array, mx.array]: + logits = hidden_states.astype(mx.float32) @ self.weight.T + if _use_kernels(): + return expert_routing( + logits, + self.e_score_correction_bias, + top_k=self.top_k, + multiplier=1.0, + score_eps=_ROUTER_SCORE_EPS, + route_scale=self.routed_scaling_factor, + ) + scores = mx.sigmoid(logits) + biased = scores + self.e_score_correction_bias + k = self.top_k + indices = mx.argpartition(-biased, kth=k - 1, axis=-1)[..., :k] + weights = mx.take_along_axis(scores, indices, axis=-1) + weights = weights / (weights.sum(axis=-1, keepdims=True) + _ROUTER_SCORE_EPS) + return indices, weights * self.routed_scaling_factor + + +class SparseMoeBlock(nn.Module): + def __init__(self, args: TextArgs): + super().__init__() + self.gate = TopKRouter(args) + self.experts = Experts(args) + self.sharding_group = None + + def __call__(self, hidden_states: mx.array) -> mx.array: + group = self.sharding_group + if group is not None: + hidden_states = sum_gradients(group)(hidden_states) + selected_experts, routing_weights = self.gate(hidden_states) + expert_states = self.experts(hidden_states, selected_experts) + expert_states = expert_states.astype(mx.float32) * routing_weights[..., None] + final_hidden_states = expert_states.sum(axis=-2) + if group is not None: + final_hidden_states = mx.distributed.all_sum( + final_hidden_states, group=group + ) + return final_hidden_states.astype(hidden_states.dtype) + + +class BlockAttentionResidual(nn.Module): + def __init__(self, dims: int, num_queries: int = 1): + super().__init__() + shape = (dims,) if num_queries == 1 else (num_queries, dims) + self.query = mx.zeros(shape, dtype=mx.float32) + + def __call__( + self, block_states: mx.array, partial_block_states: mx.array + ) -> mx.array: + dims = partial_block_states.shape[-1] + query = self.query.reshape(-1, dims).astype(mx.float32) + scale = dims**-0.5 + if _use_kernels(): + return depth_attention( + block_states, partial_block_states, query, scale=scale + ) + stacked_states = mx.concatenate([block_states, partial_block_states[None]]) + stacked_states = mx.moveaxis(stacked_states, 0, -2) + weights = mx.softmax((stacked_states @ query.T) * scale, axis=-2, precise=True) + return weights.swapaxes(-1, -2) @ stacked_states + + +class DecoderLayer(nn.Module): + def __init__(self, args: TextArgs, layer_idx: int, *, num_queries: int): + super().__init__() + dims = args.hidden_size + self.is_block_boundary = layer_idx % args.n_layers_per_attn_res_block == 0 + self.attention_input = ( + BlockAttentionResidual(dims, num_queries) if layer_idx > 0 else None + ) + self.mlp_input = BlockAttentionResidual(dims) + self.mlp = SparseMoeBlock(args) + self.post_attention_layernorm = nn.RMSNorm(dims, eps=args.rms_norm_eps) + kernel_size = args.sconv_kernel_size + self.post_attention_convolution = ShortConvolution(dims, kernel_size) + self.post_mlp_convolution = ShortConvolution(dims, kernel_size) + + def __call__( + self, + hidden_states: mx.array, + block_states: mx.array | None, + *, + cache: Any | None = None, + conv_mask: mx.array | None = None, + ) -> tuple[mx.array, mx.array]: + dtype = hidden_states.dtype + conv = cache[1] if cache is not None else None + conv_states = list(conv.cache) if conv is not None else [None] * 4 + block_residual = hidden_states + normed_residual = _unweighted_rms_norm(block_residual.astype(mx.float32)) + + attention_inputs = None + if self.attention_input is not None: + attention_inputs = self.attention_input(block_states, normed_residual) + hidden_states = self._self_attention( + hidden_states, attention_inputs, cache, conv_states, conv_mask + ) + hidden_states, conv_states[2] = self.post_attention_convolution( + hidden_states, conv_states[2], conv_mask + ) + + residual = hidden_states = hidden_states.astype(mx.float32) + if self.is_block_boundary: + block = normed_residual[None] + if block_states is None: + block_states = block + else: + block_states = mx.concatenate([block_states, block]) + else: + residual = hidden_states = block_residual.astype(mx.float32) + hidden_states + + normed_states = _unweighted_rms_norm(hidden_states) + hidden_states = self.mlp_input(block_states, normed_states)[..., 0, :] + hidden_states = self.mlp( + self.post_attention_layernorm(hidden_states).astype(dtype) + ) + hidden_states, conv_states[3] = self.post_mlp_convolution( + hidden_states, conv_states[3], conv_mask + ) + + if conv is not None: + n = self.post_mlp_convolution.kernel_size - 1 + for i, window in enumerate(conv_states): + conv[i] = _conv_state(window, conv.lengths, n) + conv.advance(block_residual.shape[1]) + hidden_states = residual + hidden_states.astype(mx.float32) + return hidden_states.astype(dtype), block_states + + +class SlidingDecoderLayer(DecoderLayer): + def __init__(self, args: TextArgs, layer_idx: int): + super().__init__(args, layer_idx, num_queries=1) + self.self_attn = SlidingAttention(args) + self.input_layernorm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps) + + def _self_attention( + self, hidden_states, attention_inputs, cache, conv_states, conv_mask + ): + dtype = hidden_states.dtype + if attention_inputs is not None: + hidden_states = attention_inputs[..., 0, :] + return self.self_attn( + self.input_layernorm(hidden_states).astype(dtype), + cache=cache, + conv_states=conv_states, + conv_mask=conv_mask, + ) + + +class FullDecoderLayer(DecoderLayer): + def __init__(self, args: TextArgs, layer_idx: int): + super().__init__(args, layer_idx, num_queries=3) + self.self_attn = FullAttention(args) + eps = args.rms_norm_eps + self.q_input_layernorm = nn.RMSNorm(args.hidden_size, eps=eps) + self.k_input_layernorm = nn.RMSNorm(args.hidden_size, eps=eps) + self.v_input_layernorm = nn.RMSNorm(args.hidden_size, eps=eps) + + def _self_attention( + self, hidden_states, attention_inputs, cache, conv_states, conv_mask + ): + dtype = hidden_states.dtype + if attention_inputs is None: + query_states = key_states = value_states = hidden_states + else: + query_states, key_states, value_states = ( + attention_inputs[..., i, :] for i in range(3) + ) + return self.self_attn( + self.q_input_layernorm(query_states).astype(dtype), + self.k_input_layernorm(key_states).astype(dtype), + self.v_input_layernorm(value_states).astype(dtype), + cache=cache, + conv_states=conv_states, + conv_mask=conv_mask, + ) + + +class TextModel(PipelineMixin, nn.Module): + def __init__(self, args: TextArgs): + super().__init__() + self.args = args + self.embed_tokens = nn.Embedding(args.vocab_size, args.hidden_size) + # Not in embed_tokens as in transformers, so that it can be quantized. + self.embed_norm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps) + self.layers = [ + ( + SlidingDecoderLayer(args, i) + if i in args.local_layer_ids + else FullDecoderLayer(args, i) + ) + for i in range(args.num_hidden_layers) + ] + self.final_input = BlockAttentionResidual(args.hidden_size) + self.norm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps) + + def embed(self, inputs: mx.array) -> mx.array: + return self.embed_norm(self.embed_tokens(inputs)) + + def __call__( + self, + inputs: mx.array, + cache: list[Any] | None = None, + input_embeddings: mx.array | None = None, + ) -> mx.array: + if input_embeddings is None: + input_embeddings = self.embed(inputs) + hidden_states = input_embeddings + dtype = hidden_states.dtype + + layers = self.pipeline_layers + if cache is None: + cache = [None] * len(layers) + conv_mask = None + if cache[0] is not None: + conv_mask = cache[0][1].make_mask(hidden_states.shape[1]) + + rank, size = self.pipeline_rank, self.pipeline_size + block_states = None + if rank < size - 1: + num_blocks = -(-self.start_idx // self.args.n_layers_per_attn_res_block) + states = mx.zeros((num_blocks + 1, *hidden_states.shape), mx.float32) + states = mx.distributed.recv_like(states, rank + 1) + hidden_states, block_states = states[0].astype(dtype), states[1:] + + for layer, c in zip(layers, cache): + hidden_states, block_states = layer( + hidden_states, block_states, cache=c, conv_mask=conv_mask + ) + + if rank != 0: + states = mx.concatenate( + [hidden_states.astype(mx.float32)[None], block_states] + ) + states = mx.distributed.send(states, (rank - 1) % size) + if cache[-1] is not None: + kv_cache = cache[-1][0] + kv_cache.keys = mx.depends(kv_cache.keys, states) + # Only the output of rank 0 is used. + hidden_states = states[0].astype(dtype) + else: + normed_states = _unweighted_rms_norm(hidden_states.astype(mx.float32)) + hidden_states = self.final_input(block_states, normed_states)[..., 0, :] + hidden_states = self.norm(hidden_states).astype(dtype) + + if size > 1: + batch = hidden_states.shape[0] + hidden_states = mx.distributed.all_gather(hidden_states)[:batch] + return hidden_states + + +def _grid_positions(grid_h: int, grid_w: int, merge: int) -> tuple[mx.array, mx.array]: + i = mx.arange(grid_h * grid_w) + blocks_w = grid_w // merge + row = i // (merge * merge * blocks_w) * merge + i // merge % merge + col = i // (merge * merge) % blocks_w * merge + i % merge + return row, col + + +def _bilinear_taps(index: mx.array, size: int, side: int) -> tuple[mx.array, mx.array]: + src = (index.astype(mx.float32) + 0.5) * side / size - 0.5 + taps = mx.floor(src)[:, None] + mx.arange(2) + weights = mx.maximum(1.0 - mx.abs(src[:, None] - taps), 0.0) + return mx.clip(taps, 0, side - 1).astype(mx.int32), weights + + +class VisionEmbeddings(nn.Module): + def __init__(self, args: VisionArgs): + super().__init__() + self.merge_size = args.adapter_merge_size + self.grid_size = args.posemb_grid_size + patch_dims = args.num_channels * args.native_patch_size**2 + self.patch_embedding = nn.Linear(patch_dims, args.hidden_size, bias=False) + self.position_embedding = nn.Embedding( + args.posemb_grid_size**2, args.hidden_size + ) + self.class_embedding = mx.zeros((args.hidden_size,)) + self.cls_position_embedding = mx.zeros((args.hidden_size,)) + + def __call__(self, pixel_values: mx.array, grid_h: int, grid_w: int) -> mx.array: + patch_embeddings = self.patch_embedding(pixel_values) + + side = self.grid_size + row, col = _grid_positions(grid_h, grid_w, self.merge_size) + row_taps, row_weights = _bilinear_taps(row, grid_h, side) + col_taps, col_weights = _bilinear_taps(col, grid_w, side) + interp_indices = row_taps[:, :, None] * side + col_taps[:, None, :] + interp_weights = row_weights[:, :, None] * col_weights[:, None, :] + position_embeddings = self.position_embedding(interp_indices.reshape(-1, 4)) + position_embeddings = position_embeddings.astype(mx.float32) + position_embeddings = position_embeddings * interp_weights.reshape(-1, 4, 1) + patch_embeddings = patch_embeddings + position_embeddings.sum(axis=1).astype( + patch_embeddings.dtype + ) + + cls_embedding = self.class_embedding + self.cls_position_embedding + cls_embedding = cls_embedding.astype(patch_embeddings.dtype) + return mx.concatenate([cls_embedding[None], patch_embeddings]) + + +class VisionRotaryEmbedding(nn.Module): + def __init__(self, args: VisionArgs): + super().__init__() + dims = args.head_dim // 2 + self._inv_freq = 1.0 / ( + args.rope_theta ** (mx.arange(0, dims, 2, dtype=mx.float32) / dims) + ) + + def __call__(self, row: mx.array, col: mx.array) -> tuple[mx.array, mx.array]: + freqs_h = row[:, None].astype(mx.float32) * self._inv_freq + freqs_w = col[:, None].astype(mx.float32) * self._inv_freq + freqs = mx.repeat(mx.concatenate([freqs_w, freqs_h], axis=-1), 2, axis=-1) + return mx.cos(freqs), mx.sin(freqs) + + +def _apply_rotary_pos_emb_vision( + hidden_states: mx.array, cos: mx.array, sin: mx.array +) -> mx.array: + states = hidden_states.astype(mx.float32) + pairs = states.reshape(*states.shape[:-1], -1, 2) + rotated = mx.stack([-pairs[..., 1], pairs[..., 0]], axis=-1).reshape(states.shape) + return (states * cos + rotated * sin).astype(hidden_states.dtype) + + +class VisionAttention(nn.Module): + def __init__(self, args: VisionArgs): + super().__init__() + dims = args.hidden_size + self.num_heads = args.num_attention_heads + self.scaling = args.head_dim**-0.5 + self.q_proj = nn.Linear(dims, dims) + self.k_proj = nn.Linear(dims, dims) + self.v_proj = nn.Linear(dims, dims) + self.out_proj = nn.Linear(dims, dims) + + def __call__( + self, hidden_states: mx.array, cos: mx.array, sin: mx.array + ) -> mx.array: + N = hidden_states.shape[0] + shape = (N, self.num_heads, -1) + cos, sin = cos[:, None], sin[:, None] + query_states = self.q_proj(hidden_states).reshape(shape) + key_states = self.k_proj(hidden_states).reshape(shape) + value_states = self.v_proj(hidden_states).reshape(shape) + query_states = _apply_rotary_pos_emb_vision(query_states, cos, sin) + key_states = _apply_rotary_pos_emb_vision(key_states, cos, sin) + query_states, key_states, value_states = ( + states.transpose(1, 0, 2)[None] + for states in (query_states, key_states, value_states) + ) + attn_output = mx.fast.scaled_dot_product_attention( + query_states, key_states, value_states, scale=self.scaling + ) + attn_output = attn_output[0].transpose(1, 0, 2).reshape(N, -1) + return self.out_proj(attn_output) + + +class VisionMLP(nn.Module): + def __init__(self, args: VisionArgs): + super().__init__() + self.fc1 = nn.Linear(args.hidden_size, args.intermediate_size) + self.fc2 = nn.Linear(args.intermediate_size, args.hidden_size) + + def __call__(self, hidden_states: mx.array) -> mx.array: + return self.fc2(_precise_gelu(self.fc1(hidden_states))) + + +class VisionEncoderLayer(nn.Module): + def __init__(self, args: VisionArgs): + super().__init__() + dims, eps = args.hidden_size, args.layer_norm_eps + self.self_attn = VisionAttention(args) + self.mlp = VisionMLP(args) + self.layernorm_before = nn.LayerNorm(dims, eps=eps) + self.layernorm_after = nn.LayerNorm(dims, eps=eps) + self.lambda_1 = mx.ones((dims,)) + self.lambda_2 = mx.ones((dims,)) + + def __call__( + self, hidden_states: mx.array, cos: mx.array, sin: mx.array + ) -> mx.array: + residual = hidden_states + hidden_states = self.self_attn(self.layernorm_before(hidden_states), cos, sin) + hidden_states = residual + self.lambda_1 * hidden_states + residual = hidden_states + hidden_states = self.mlp(self.layernorm_after(hidden_states)) + return residual + self.lambda_2 * hidden_states + + +class VisionMerger(nn.Module): + def __init__(self, args: VisionArgs, text_hidden_size: int): + super().__init__() + dims = args.adapter_merge_size**2 * args.hidden_size + hidden, bias = args.projection_hidden_dim, args.projector_bias + self.linear_1 = nn.Linear(dims, hidden, bias=bias) + self.linear_2 = nn.Linear(hidden, text_hidden_size, bias=bias) + + def __call__(self, image_features: mx.array) -> mx.array: + return self.linear_2(_precise_gelu(self.linear_1(image_features))) + + +class VisionModel(nn.Module): + def __init__(self, args: VisionArgs, text_hidden_size: int): + super().__init__() + self.args = args + self.embeddings = VisionEmbeddings(args) + self.pre_layernorm = nn.LayerNorm(args.hidden_size, eps=args.layer_norm_eps) + self.rotary_emb = VisionRotaryEmbedding(args) + self.layers = [VisionEncoderLayer(args) for _ in range(args.num_hidden_layers)] + self.merger = VisionMerger(args, text_hidden_size) + + def __call__(self, pixel_values: mx.array) -> mx.array: + C, H, W = pixel_values.shape + p, m = self.args.native_patch_size, self.args.adapter_merge_size + if H % (p * m) or W % (p * m): + raise ValueError(f"Image size {H}x{W} is not a multiple of {p * m}.") + rows, cols = H // (p * m), W // (p * m) + patches = pixel_values.transpose(1, 2, 0).reshape(rows, m, p, cols, m, p, C) + # The merge blocks in raster order, then the patches of each block. + patches = patches.transpose(0, 3, 1, 4, 2, 5, 6).reshape(-1, p * p * C) + dtype = self.embeddings.patch_embedding.weight.dtype + hidden_states = self.embeddings(patches.astype(dtype), rows * m, cols * m) + hidden_states = self.pre_layernorm(hidden_states) + + row, col = _grid_positions(rows * m, cols * m, m) + zero = mx.zeros((1,), dtype=row.dtype) + cos, sin = self.rotary_emb( + mx.concatenate([zero, row + 1]), mx.concatenate([zero, col + 1]) + ) + for layer in self.layers: + hidden_states = layer(hidden_states, cos, sin) + patch_states = hidden_states[1:].reshape(rows * cols, -1) + return self.merger(patch_states) + + +def _splice_image_features( + inputs_embeds: mx.array, + input_ids: mx.array, + image_features: mx.array, + image_token_id: int, +) -> mx.array: + if image_features.shape[0] == 0: + return inputs_embeds + special_image_mask = input_ids == image_token_id + idx = mx.cumsum(special_image_mask.flatten()).reshape(special_image_mask.shape) - 1 + idx = mx.clip(idx, 0, image_features.shape[0] - 1) + rows = image_features[idx].astype(inputs_embeds.dtype) + return mx.where(special_image_mask[..., None], rows, inputs_embeds) + + +class Inkling2Model(nn.Module): + def __init__(self, args: ModelArgs): + super().__init__() + self.language_model = TextModel(args.text) + if args.vision is not None: + self.vision_tower = VisionModel(args.vision, args.text.hidden_size) + + # mlx_lm.utils pipelines model.model with these. + @property + def layers(self) -> list[DecoderLayer | None]: + return self.language_model.layers + + @property + def start_idx(self) -> int: + return self.language_model.start_idx + + @property + def end_idx(self) -> int | None: + return self.language_model.end_idx + + def pipeline(self, group, split=None) -> None: + self.language_model.pipeline(group, split) + + +class Model(nn.Module): + def __init__(self, args: ModelArgs): + super().__init__() + self.args = args + self.model_type = args.model_type + self.model = Inkling2Model(args) + text = args.text + self.lm_head = nn.Linear(text.hidden_size, text.vocab_size, bias=False) + self.sharding_group = None + + def encode_image(self, pixel_values: mx.array | list[mx.array]) -> mx.array: + """pixel_values: one image (num_channels, H, W) or a list of images of + any size. Returns the rows of the image tokens of all images.""" + if isinstance(pixel_values, mx.array) and pixel_values.ndim == 3: + pixel_values = [pixel_values] + assert len(pixel_values), "No images." + return mx.concatenate([self.model.vision_tower(p) for p in pixel_values]) + + def embed_inputs( + self, + inputs: mx.array, + *, + pixel_values: mx.array | list[mx.array] | None = None, + ) -> mx.array: + inputs_embeds = self.model.language_model.embed(inputs) + if pixel_values is not None: + image_features = self.encode_image(pixel_values) + inputs_embeds = _splice_image_features( + inputs_embeds, inputs, image_features, self.args.image_token_id + ) + return inputs_embeds + + def __call__( + self, + inputs: mx.array, + cache: list[Any] | None = None, + input_embeddings: mx.array | None = None, + pixel_values: mx.array | list[mx.array] | None = None, + ) -> mx.array: + if pixel_values is not None: + assert input_embeddings is None, "Pass pixel_values or input_embeddings." + input_embeddings = self.embed_inputs(inputs, pixel_values=pixel_values) + hidden_states = self.model.language_model( + inputs, cache=cache, input_embeddings=input_embeddings + ) + logits = self.lm_head(hidden_states) + if self.sharding_group is not None: + logits = gather_last_axis(logits, self.sharding_group) + text = self.args.text + softcap = text.final_logit_softcapping + logits = logits.astype(mx.float32) + logits = mx.tanh(logits / softcap) * softcap + return logits[..., : text.unpadded_vocab_size] + + def sanitize(self, weights: dict[str, mx.array]) -> dict[str, mx.array]: + experts = re.compile(r"^(.+\.mlp\.experts)\.(w13|w2)_weight(\w*)$") + amax, denominator = {}, {} + sanitized = {} + for k, v in weights.items(): + if k.startswith(("model.llm.", "model.visual.")): + k = _rename(k) + if k.endswith("conv1d.weight"): + v = v.swapaxes(1, 2) + if k.startswith("model.vision_tower.") and self.args.vision is None: + continue + if k.endswith(".mlp.gate.weight"): + v = v.astype(mx.float32) + elif m := experts.match(k): + prefix, which, suffix = m.groups() + name = f"{prefix}.{'gate_up_proj' if which == 'w13' else 'down_proj'}" + if suffix == "_amax": + amax[name] = v + elif suffix == "_outer_scale_denominator": + denominator[name] = v + elif suffix == "_scale": + sanitized[f"{name}.scales"] = v + else: + sanitized[f"{name}.weight"] = v.view(mx.uint32) + continue + sanitized[k] = v + + # Pipeline stages can miss the files of the other layers. + for name in amax.keys() & denominator.keys(): + scale = _NVFP4_E2M1_MAX * _NVFP4_E4M3_MAX + scale = scale / denominator[name].astype(mx.float32) + sanitized[f"{name}.global_scale"] = amax[name].astype(mx.float32) * scale + + # mlx-lm does not read this quantization config, so set the experts here. + modes = {(4, 16): "nvfp4", (4, 32): "mxfp4", (8, 32): "mxfp8"} + quantized = [] + for path, module in self.named_modules(): + scales = sanitized.get(f"{path}.scales") + if not isinstance(module, SwitchLinear) or scales is None: + continue + if scales.dtype != mx.uint8: + continue + in_dims = module.weight.shape[-1] + group_size = in_dims // scales.shape[-1] + bits = sanitized[f"{path}.weight"].shape[-1] * 32 // in_dims + if (bits, group_size) not in modes: + continue + ql = module.to_quantized( + group_size, + bits, + mode=modes[bits, group_size], + global_scale=f"{path}.global_scale" in sanitized, + ) + quantized.append((path, ql)) + if quantized: + self.update_modules(tree_unflatten(quantized)) + return sanitized + + def shard(self, group: mx.distributed.Group | None = None) -> None: + group = group or mx.distributed.init() + N, r = group.size(), group.rank() + text = self.args.text + for n_kv_heads in (text.num_key_value_heads, text.swa_num_key_value_heads): + assert ( + n_kv_heads % N == 0 + ), f"group size {N} must divide num_key_value_heads {n_kv_heads}" + assert ( + text.vocab_size % N == 0 + ), f"group size {N} must divide vocab_size {text.vocab_size}" + + def part(w: mx.array, axis: int) -> mx.array: + return mx.contiguous(mx.split(w, N, axis=axis)[r]) + + self.lm_head = shard_linear(self.lm_head, "all-to-sharded", group=group) + self.sharding_group = group + for layer in self.layers: + attn = layer.self_attn + for name in ( + "q_proj", + "k_proj", + "v_proj", + "r_proj", + "gate_proj", + "sink_proj", + ): + proj = shard_linear(getattr(attn, name), "all-to-sharded", group=group) + setattr(attn, name, proj) + attn.o_proj = shard_linear(attn.o_proj, "sharded-to-all", group=group) + attn.q_l2_clip.scale = part(attn.q_l2_clip.scale, 0) + attn.rel_l2_clip.scale = part(attn.rel_l2_clip.scale, 0) + for conv in (attn.k_sconv, attn.v_sconv): + if isinstance(conv, ShortConvolution): + conv.conv1d.weight = part(conv.conv1d.weight, 0) + conv.conv1d.groups //= N + else: + conv.static_weight = part(conv.static_weight, 1) + conv.weight_proj = shard_linear( + conv.weight_proj, "all-to-sharded", group=group + ) + conv.num_heads //= N + attn.num_heads //= N + attn.num_key_value_heads //= N + + layer.mlp.sharding_group = group + experts = layer.mlp.experts + shard_experts_inplace(experts.gate_up_proj, "all-to-sharded", group) + shard_experts_inplace(experts.down_proj, "sharded-to-all", group) + + @property + def quant_predicate(self) -> Callable[[str, nn.Module], bool]: + + def predicate(path: str, module: nn.Module) -> bool: + return not path.startswith("model.vision_tower.") + + return predicate + + @property + def cast_predicate(self) -> Callable[[str], bool]: + + def predicate(k: str) -> bool: + return not k.endswith( + (".query", ".mlp.gate.weight", ".mlp.gate.e_score_correction_bias") + ) + + return predicate + + @property + def layers(self) -> list[DecoderLayer]: + return self.model.language_model.pipeline_layers + + def make_cache(self) -> list[CacheList]: + window = self.args.text.sliding_window_size + return [ + CacheList( + ( + RotatingKVCache(max_size=window) + if isinstance(layer, SlidingDecoderLayer) + else KVCache() + ), + ArraysCache(4), + ) + for layer in self.layers + ] diff --git a/mlx_lm/processors/__init__.py b/mlx_lm/processors/__init__.py index 9790bba33..3c630ed55 100644 --- a/mlx_lm/processors/__init__.py +++ b/mlx_lm/processors/__init__.py @@ -4,15 +4,18 @@ from mlx import nn -from . import muse_spark +from . import inkling2, muse_spark # The processor of each model module. PROCESSORS = { + "inkling2": inkling2.Processor, "muse_spark": muse_spark.Processor, } -def load_processor(model: nn.Module, config: dict) -> muse_spark.Processor | None: +def load_processor( + model: nn.Module, config: dict +) -> inkling2.Processor | muse_spark.Processor | None: """The processor of a model, or None.""" if not config.get("vision_config"): return None diff --git a/mlx_lm/processors/inkling2.py b/mlx_lm/processors/inkling2.py new file mode 100644 index 000000000..7615508c8 --- /dev/null +++ b/mlx_lm/processors/inkling2.py @@ -0,0 +1,63 @@ +# Copyright © 2026 Apple Inc. + +"""Image processor of Inkling 2.""" + +import math +from dataclasses import dataclass +from typing import ClassVar, Sequence + +import mlx.core as mx +import numpy as np + +IMAGE_TOKEN = "<|unused_200054|>" + + +@dataclass(frozen=True) +class Processor: + image_token: ClassVar[str] = IMAGE_TOKEN + + block_size: int = 40 + image_mean: tuple[float, float, float] = (0.5, 0.5, 0.5) + image_std: tuple[float, float, float] = (0.5, 0.5, 0.5) + + @classmethod + def from_config(cls, config: dict) -> "Processor": + vision = config.get("vision_config") + if not vision: + raise ValueError("The model config has no vision_config.") + patch_size = vision.get("native_patch_size", 20) + merge_size = vision.get("adapter_merge_size", 2) + return cls(block_size=patch_size * merge_size) + + def preprocess_image(self, image: np.ndarray) -> tuple[mx.array, int]: + assert image.ndim == 3 and image.shape[-1] == 3, "Images must be (H, W, 3)." + assert image.dtype == np.uint8, "Images must be uint8." + height, width, _ = image.shape + rows = math.ceil(height / self.block_size) + cols = math.ceil(width / self.block_size) + # As the reference, the padding is -1 on the 0-255 scale. + x = np.full( + (rows * self.block_size, cols * self.block_size, 3), -1.0, np.float32 + ) + x[:height, :width] = image + mean = np.array(self.image_mean, dtype=np.float32) + std = np.array(self.image_std, dtype=np.float32) + x = (x * np.float32(1 / 255) - mean) / std + return mx.array(x.transpose(2, 0, 1)), rows * cols + + def __call__( + self, text: str, *, images: Sequence[np.ndarray] + ) -> tuple[str, list[mx.array]]: + parts = text.split(IMAGE_TOKEN) + if len(parts) - 1 != len(images): + raise ValueError( + f"The text has {len(parts) - 1} {IMAGE_TOKEN} " + f"for {len(images)} images." + ) + pixel_values = [] + expanded = [parts[0]] + for image, part in zip(images, parts[1:], strict=True): + pixels, num_tokens = self.preprocess_image(image) + expanded += [IMAGE_TOKEN * num_tokens, part] + pixel_values.append(pixels) + return "".join(expanded), pixel_values diff --git a/tests/model_parallel_tests.py b/tests/model_parallel_tests.py index 87bdcf757..7f5acbcf9 100644 --- a/tests/model_parallel_tests.py +++ b/tests/model_parallel_tests.py @@ -298,6 +298,32 @@ def run(): for e, out in zip(expected, run()): self.assertTrue(mx.allclose(e, out, rtol=1e-3, atol=1e-3)) + def test_inkling2(self): + from models.test_inkling2 import UNPADDED_VOCAB, create_model, quantize_experts + + for parallel in ("tensor", "pipeline"): + for quantized in (False, True): + with self.subTest(parallel=parallel, quantized=quantized): + model = create_model() + if quantized: + quantize_experts(model) + x = mx.random.randint(0, UNPADDED_VOCAB, shape=(2, 13)) + + def run(): + cache = model.make_cache() + outputs = [model(x[:, :10], cache=cache)] + for i in range(10, 13): + outputs.append(model(x[:, i : i + 1], cache=cache)) + return outputs + + expected = run() + if parallel == "tensor": + model.shard() + else: + model.model.pipeline(mx.distributed.init()) + for e, out in zip(expected, run()): + self.assertTrue(mx.allclose(e, out, rtol=1e-3, atol=1e-3)) + def test_pipeline_layer_assignment(self): def assignment(num_layers, size, split=None): blocks = [] diff --git a/tests/models/test_inkling2.py b/tests/models/test_inkling2.py new file mode 100644 index 000000000..c18fa0adc --- /dev/null +++ b/tests/models/test_inkling2.py @@ -0,0 +1,282 @@ +# Copyright © 2026 Apple Inc. + +import json +import re +import tempfile +import unittest +from pathlib import Path + +import mlx.core as mx +import numpy as np +from mlx.utils import tree_flatten, tree_unflatten + +from mlx_lm.generate import BatchGenerator, generate_step +from mlx_lm.models import inkling2 +from mlx_lm.processors import inkling2 as inkling2_processor +from mlx_lm.processors import load_processor +from mlx_lm.utils import load_model, quantize_model + +CONFIG = { + "model_type": "inkling2", + "image_token_id": 127, + "text_config": { + "hidden_size": 64, + "num_hidden_layers": 8, + "vocab_size": 128, + "unpadded_vocab_size": 120, + "num_attention_heads": 4, + "num_key_value_heads": 2, + "head_dim": 16, + "swa_num_attention_heads": 4, + "swa_num_key_value_heads": 2, + "swa_head_dim": 16, + "sliding_window_size": 8, + "local_layer_ids": [0, 1, 2, 3, 4, 6], + "d_rel": 4, + "rel_extent": 8, + "log_scaling_n_floor": 4, + "log_scaling_alpha": 0.1, + "rms_norm_eps": 1e-6, + "qk_l2_clip_threshold": 3.0, + "rel_l2_clip_threshold": 2.0, + "sconv_kernel_size": 4, + "n_layers_per_attn_res_block": 3, + "n_routed_experts": 4, + "num_experts_per_tok": 2, + "intermediate_size": 64, + "mlp_gate_softcap": 4.0, + "mlp_up_softcap": 25.0, + "route_scale": 2.0, + "final_logit_softcapping": 30.0, + }, +} + +VISION_CONFIG = { + "hidden_size": 32, + "num_hidden_layers": 2, + "num_attention_heads": 2, + "native_patch_size": 2, + "adapter_merge_size": 2, + "posemb_grid_size": 4, + "projection_hidden_dim": 48, +} + +UNPADDED_VOCAB = CONFIG["text_config"]["unpadded_vocab_size"] + + +def create_model(vision: bool = False) -> inkling2.Model: + mx.random.seed(0) + config = {**CONFIG, "vision_config": VISION_CONFIG} if vision else CONFIG + model = inkling2.Model(inkling2.ModelArgs.from_dict(config)) + weights = [] + for k, v in tree_flatten(model.parameters()): + if k.endswith(("norm.weight", "l2_clip.scale", "lambda_1", "lambda_2")): + v = 1 + 0.1 * mx.random.normal(v.shape) + else: + fan_in = v.shape[-1] if v.ndim > 1 else 16 + v = mx.random.normal(v.shape) * fan_in**-0.5 + weights.append((k, v)) + model.update(tree_unflatten(weights)) + mx.eval(model.parameters()) + return model + + +def quantize_experts(model: inkling2.Model) -> None: + def predicate(path, module): + if ".mlp.experts." not in path: + return False + if ".layers.7." in path: + return {"group_size": 32, "bits": 8, "mode": "mxfp8"} + return {"group_size": 16, "bits": 4, "mode": "nvfp4", "global_scale": True} + + quantize_model(model, {}, None, None, quant_predicate=predicate) + + +_CHECKPOINT_NAMES = [ + (r"^lm_head\.", "model.llm.unembed."), + (r"^model\.language_model\.embed_tokens\.", "model.llm.embed."), + (r"^model\.language_model\.", "model.llm."), + (r"\.final_input\.query$", ".attn_res.output_query"), + (r"\.layers\.(\d+)\.mlp_input\.query$", r".attn_res.mlp_queries.\1"), + (r"\.self_attn\.q_proj\.", ".attn.wq_du."), + (r"\.self_attn\.k_proj\.", ".attn.wk_dv."), + (r"\.self_attn\.v_proj\.", ".attn.wv_dv."), + (r"\.self_attn\.r_proj\.", ".attn.wr_du."), + (r"\.self_attn\.o_proj\.", ".attn.wo_ud."), + (r"\.self_attn\.gate_proj\.", ".attn.gate_attn."), + (r"\.self_attn\.sink_proj\.", ".attn.attn_sink_proj."), + (r"\.self_attn\.", ".attn."), + (r"\.post_attention_convolution\.", ".attn_sconv."), + (r"\.post_mlp_convolution\.", ".mlp_sconv."), + (r"\.conv1d\.weight$", ".weight"), + (r"sconv\.static_weight$", "sconv.static_w"), + (r"sconv\.weight_proj\.weight$", "sconv.weight_proj"), + (r"\.post_attention_layernorm\.", ".mlp_norm."), + (r"\.input_layernorm\.", ".attn_norm."), + (r"\.(q|k|v)_input_layernorm\.", r".\1_input_norm."), + (r"\.mlp\.gate\.e_score_correction_bias$", ".mlp.gate.bias"), + (r"^model\.vision_tower\.pre_layernorm\.", "model.visual.backbone.ln_pre."), + (r"^model\.vision_tower\.merger\.linear_1\.", "model.visual.proj_in."), + (r"^model\.vision_tower\.merger\.linear_2\.", "model.visual.proj_out."), + (r"^model\.vision_tower\.", "model.visual.backbone."), + (r"position_embedding\.weight$", "position_embedding"), + (r"\.layernorm_before\.", ".ln_1."), + (r"\.layernorm_after\.", ".ln_2."), + (r"\.mlp\.fc1\.", ".mlp.c_fc."), + (r"\.mlp\.fc2\.", ".mlp.c_proj."), + (r"\.lambda_(\d)$", r".ls_\1.gamma"), +] + + +def checkpoint(model: inkling2.Model) -> dict: + weights = dict(tree_flatten(model.parameters())) + ckpt = {} + denominator = mx.array([7.5]) + for k, v in weights.items(): + if m := re.match(r"(.+\.mlp\.experts)\.(gate_up|down)_proj\.(\w+)$", k): + prefix, name, param = m.groups() + prefix = prefix.replace("model.language_model.", "model.llm.") + w = f"{prefix}.{'w13' if name == 'gate_up' else 'w2'}_weight" + if param == "weight": + ckpt[w] = v.view(mx.uint8) + elif param == "scales": + ckpt[f"{w}_scale"] = v + else: + ckpt[f"{w}_amax"] = v * denominator / 2688.0 + ckpt[f"{w}_outer_scale_denominator"] = denominator + continue + if m := re.match(r".+\.layers\.(\d+)\.attention_input\.query$", k): + ckpt[f"model.llm.attn_res.attn_queries.{int(m.group(1)) - 1}"] = v + continue + for pattern, replacement in _CHECKPOINT_NAMES: + k = re.sub(pattern, replacement, k) + if k.endswith("sconv.weight"): + v = v.swapaxes(1, 2) + ckpt[k] = v + return ckpt + + +def image_prompt(model: inkling2.Model, *, h: int, w: int): + vision = model.args.vision + side = vision.native_patch_size * vision.adapter_merge_size + rows = (h // side) * (w // side) + image = mx.random.uniform(-1, 1, shape=(3, h, w)) + inputs = mx.array([1, 2] + [model.args.image_token_id] * rows + [3, 4]) + return image, inputs + + +class TestInkling2(unittest.TestCase): + def test_forward(self): + model = create_model() + for dtype in (mx.float32, mx.bfloat16): + model.update( + tree_unflatten( + [(k, v.astype(dtype)) for k, v in tree_flatten(model.parameters())] + ) + ) + outputs = model(mx.array([[0, 1]])) + self.assertEqual(outputs.shape, (1, 2, UNPADDED_VOCAB)) + self.assertEqual(outputs.dtype, mx.float32) + + def test_cached_matches_forward(self): + model = create_model() + tokens = mx.random.randint(0, UNPADDED_VOCAB, (2, 20)) + full = model(tokens) + + cache = model.make_cache() + steps = [model(tokens[:, :6], cache=cache), model(tokens[:, 6:12], cache=cache)] + steps += [model(tokens[:, i : i + 1], cache=cache) for i in range(12, 20)] + self.assertTrue( + mx.allclose(mx.concatenate(steps, axis=1), full, rtol=1e-4, atol=1e-4) + ) + + def test_batch_matches_single(self): + model = create_model() + prompts = [[1, 2, 3], list(range(5, 30)), list(range(40, 52))] + max_tokens = 10 + + expected = [] + for p in prompts: + steps = generate_step(mx.array(p), model, max_tokens=max_tokens) + expected.append([(int(t), lp) for t, lp in steps]) + + gen = BatchGenerator(model, max_tokens=max_tokens, prefill_step_size=7) + uids = gen.insert(prompts) + got = {uid: [] for uid in uids} + while any(len(g) < max_tokens for g in got.values()): + for r in gen.next_generated(): + got[r.uid].append((r.token, r.logprobs)) + gen.close() + + for uid, want in zip(uids, expected): + self.assertEqual([t for t, _ in got[uid]], [t for t, _ in want]) + for (_, a), (_, b) in zip(got[uid], want): + self.assertTrue(mx.allclose(a, b, atol=1e-4)) + + def test_sanitize_checkpoint(self): + model = create_model(vision=True) + quantize_experts(model) + weights = dict(tree_flatten(model.parameters())) + sanitized = model.sanitize(checkpoint(model)) + self.assertEqual(sanitized.keys(), weights.keys()) + for k, v in weights.items(): + self.assertTrue(mx.allclose(sanitized[k], v), k) + + sanitized = model.sanitize(dict(weights)) + for k, v in weights.items(): + self.assertTrue(mx.array_equal(sanitized[k], v), k) + + def test_load_checkpoint(self): + model = create_model(vision=True) + quantize_experts(model) + tokens = mx.array([[5, 6, 7, 8]]) + expected = model(tokens) + + with tempfile.TemporaryDirectory() as path: + path = Path(path) + mx.save_safetensors(str(path / "model.safetensors"), checkpoint(model)) + config = {**CONFIG, "vision_config": VISION_CONFIG} + (path / "config.json").write_text(json.dumps(config)) + quant = {"quant_method": "inkling2"} + (path / "hf_quant_config.json").write_text(json.dumps(quant)) + loaded, _ = load_model(path) + self.assertTrue(mx.allclose(loaded(tokens), expected, rtol=1e-4, atol=1e-4)) + + def test_embed_inputs(self): + model = create_model(vision=True) + image, inputs = image_prompt(model, h=8, w=12) + rows = model.encode_image(image) + self.assertEqual(rows.shape, (6, CONFIG["text_config"]["hidden_size"])) + h = model.embed_inputs(inputs, pixel_values=[image]) + text = model.model.language_model.embed(inputs) + self.assertTrue(mx.array_equal(h[2:8], rows)) + self.assertTrue(mx.array_equal(h[:2], text[:2])) + self.assertTrue(mx.array_equal(h[8:], text[8:])) + + out = model(inputs[None], pixel_values=[image]) + self.assertTrue(mx.allclose(out, model(inputs[None], input_embeddings=h[None]))) + + def test_processor(self): + processor = inkling2_processor.Processor(block_size=4) + image = np.full((5, 8, 3), 255, dtype=np.uint8) + pixels, num_tokens = processor.preprocess_image(image) + self.assertEqual(pixels.shape, (3, 8, 8)) + self.assertEqual(num_tokens, 4) + self.assertTrue(mx.all(pixels[:, :5] == 1.0).item()) + self.assertTrue(mx.allclose(pixels[:, 5:], mx.array((-1 / 255 - 0.5) / 0.5))) + + token = inkling2_processor.IMAGE_TOKEN + text, pixel_values = processor(f"A {token} B", images=[image]) + self.assertEqual(text, f"A {token * 4} B") + self.assertEqual(len(pixel_values), 1) + with self.assertRaisesRegex(ValueError, "for 2 images"): + processor(f"A {token}", images=[image, image]) + + config = {**CONFIG, "vision_config": VISION_CONFIG} + processor = load_processor(create_model(vision=True), config) + self.assertIsInstance(processor, inkling2_processor.Processor) + self.assertEqual(processor.block_size, 4) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_kernels.py b/tests/test_kernels.py index 3efa91a7b..ad4f769ca 100644 --- a/tests/test_kernels.py +++ b/tests/test_kernels.py @@ -7,16 +7,19 @@ import mlx.nn as nn from mlx_lm.kernels import ( + depth_attention, expert_routing, norm_add_norm, post_expert_norm_combine, pre_norm, qk_norm, qk_norm_rope, + relative_attention, rms_norm_sigmoid_gate, sparse_mla, sparse_mla_attention, ) +from mlx_lm.models.inkling2 import _attention_reference TOL = {mx.float32: 1e-5, mx.bfloat16: 1e-2} @@ -165,6 +168,52 @@ def test_expert_routing(self): self.assertTrue(mx.array_equal(inds, ref_inds)) self._assert_close(weights, ref_weights, TOL[mx.float32]) + def test_relative_attention(self): + mx.random.seed(3) + # B, Hq, Hkv, L, S, D, R, window, the first key of each row + cases = [ + (1, 4, 2, 40, 40, 16, 8, 0, [0]), + (1, 4, 2, 40, 40, 16, 8, 8, [0]), + (2, 6, 2, 33, 70, 128, 32, 32, [5, -10]), + ] + for B, Hq, Hkv, L, S, D, R, window, key_start in cases: + q = (0.5 * mx.random.normal((B, Hq, L, D))).astype(mx.bfloat16) + k = (0.5 * mx.random.normal((B, Hkv, S, D))).astype(mx.bfloat16) + v = mx.random.normal((B, Hkv, S, D)).astype(mx.bfloat16) + rel = mx.random.normal((B, L, Hq, R)).astype(mx.bfloat16) + sinks = mx.random.normal((B, L, Hq)).astype(mx.bfloat16) + key_start = mx.array(key_start) + out = relative_attention( + q, k, v, rel, sinks, scale=D**-0.5, window=window, key_start=key_start + ) + end = S - key_start + q_pos = (end - L)[:, None] + mx.arange(L) + ref = _attention_reference( + q, + k, + v, + rel, + sinks, + scale=D**-0.5, + window=window, + query_positions=q_pos, + key_positions=(end - S)[:, None] + mx.arange(S), + ) + # Queries at negative positions are padding. + ref = mx.where((q_pos >= 0)[..., None, None], ref, out) + self._assert_close(out, ref, TOL[mx.bfloat16]) + + def test_depth_attention(self): + mx.random.seed(4) + for num_blocks, num_queries in ((1, 1), (4, 3), (8, 1)): + blocks = mx.random.normal((num_blocks, 2, 3, 1000)) + partial = mx.random.normal((2, 3, 1000)) + queries = 0.1 * mx.random.normal((num_queries, 1000)) + out = depth_attention(blocks, partial, queries, scale=1000**-0.5) + x = mx.moveaxis(mx.concatenate([blocks, partial[None]]), 0, -2) + weights = mx.softmax((x @ queries.T) * 1000**-0.5, axis=-2, precise=True) + self._assert_close(out, weights.swapaxes(-1, -2) @ x, TOL[mx.float32]) + def test_post_expert_norm_combine(self): # fp32 only: in bf16 the kernel rounds after each expert. mx.random.seed(3) From fcb4e47889fd687ea0916ede7251fa2f97126aa7 Mon Sep 17 00:00:00 2001 From: Pedro Cuenca Date: Wed, 18 Nov 2026 15:42:02 +0100 Subject: [PATCH 2/5] Handle transparent images (Inkling 2) --- mlx_lm/generate.py | 7 ++----- mlx_lm/processors/__init__.py | 15 +++++++++++++++ mlx_lm/processors/inkling2.py | 22 +++++++++++++++++++++- mlx_lm/server.py | 10 ++++------ 4 files changed, 42 insertions(+), 12 deletions(-) diff --git a/mlx_lm/generate.py b/mlx_lm/generate.py index 96ee5b095..fabe8a2c1 100644 --- a/mlx_lm/generate.py +++ b/mlx_lm/generate.py @@ -24,7 +24,6 @@ import mlx.core as mx import mlx.nn as nn -import numpy as np from mlx.utils import tree_reduce from transformers import PreTrainedTokenizer @@ -37,7 +36,7 @@ make_prompt_cache, trim_prompt_cache, ) -from .processors import load_processor +from .processors import load_image, load_processor from .sample_utils import LogitsProcessor, Sampler, greedy_sampler, make_sampler from .tokenizer_utils import TokenizerWrapper from .utils import ( @@ -2176,9 +2175,7 @@ def main(): processor = load_processor(model, config) if processor is None: raise ValueError(f"The model {model_path} does not take images.") - from PIL import Image - - images = [np.asarray(Image.open(f).convert("RGB")) for f in args.image] + images = [load_image(processor, f) for f in args.image] prompt, pixel_values = processor(prompt, images=images) else: pixel_values = None diff --git a/mlx_lm/processors/__init__.py b/mlx_lm/processors/__init__.py index 3c630ed55..ddab11c18 100644 --- a/mlx_lm/processors/__init__.py +++ b/mlx_lm/processors/__init__.py @@ -2,6 +2,9 @@ """Image processors of multimodal models, one module per model.""" +from typing import BinaryIO + +import numpy as np from mlx import nn from . import inkling2, muse_spark @@ -23,3 +26,15 @@ def load_processor( name = config.get("processor_type", model_module) processor = PROCESSORS.get(name) return processor.from_config(config) if processor else None + + +def load_image( + processor: inkling2.Processor | muse_spark.Processor, fp: str | BinaryIO +) -> np.ndarray: + """A uint8 (H, W, 3) image for the processor.""" + if hasattr(processor, "load_image"): + return processor.load_image(fp) + from PIL import Image + + with Image.open(fp) as image: + return np.asarray(image.convert("RGB")) diff --git a/mlx_lm/processors/inkling2.py b/mlx_lm/processors/inkling2.py index 7615508c8..f1f970548 100644 --- a/mlx_lm/processors/inkling2.py +++ b/mlx_lm/processors/inkling2.py @@ -4,7 +4,7 @@ import math from dataclasses import dataclass -from typing import ClassVar, Sequence +from typing import BinaryIO, ClassVar, Sequence import mlx.core as mx import numpy as np @@ -12,6 +12,15 @@ IMAGE_TOKEN = "<|unused_200054|>" +def _composite_alpha(rgba: np.ndarray) -> np.ndarray: + height, width, _ = rgba.shape + y, x = np.ogrid[:height, :width] + background = np.where((x // 8 + y // 8) % 2 == 0, 204, 153)[..., None] + rgb, alpha = rgba[..., :3].astype(np.int32), rgba[..., 3:].astype(np.int32) + blended = (rgb * alpha + background * (255 - alpha) + 127) // 255 + return blended.astype(np.uint8) + + @dataclass(frozen=True) class Processor: image_token: ClassVar[str] = IMAGE_TOKEN @@ -29,6 +38,17 @@ def from_config(cls, config: dict) -> "Processor": merge_size = vision.get("adapter_merge_size", 2) return cls(block_size=patch_size * merge_size) + def load_image(self, fp: str | BinaryIO) -> np.ndarray: + """A uint8 (H, W, 3) image. As the reference, transparent pixels are + put on a gray checkerboard.""" + from PIL import Image + + with Image.open(fp) as image: + if not image.has_transparency_data: + return np.asarray(image.convert("RGB")) + rgba = np.asarray(image.convert("RGBA")) + return _composite_alpha(rgba) + def preprocess_image(self, image: np.ndarray) -> tuple[mx.array, int]: assert image.ndim == 3 and image.shape[-1] == 3, "Images must be (H, W, 3)." assert image.dtype == np.uint8, "Images must be uint8." diff --git a/mlx_lm/server.py b/mlx_lm/server.py index a6a9a6dcd..0404cb300 100644 --- a/mlx_lm/server.py +++ b/mlx_lm/server.py @@ -45,7 +45,7 @@ stream_generate, ) from .models.cache import LRUPromptCache, make_prompt_cache -from .processors import load_processor +from .processors import load_image, load_processor from .sample_utils import make_logits_processors, make_sampler from .utils import ( _parse_size, @@ -168,14 +168,12 @@ def _inline_image_urls(messages: List[Dict[str, Any]]) -> None: part.update(type="image_url", image_url={"url": f"data:{mime};base64,{data}"}) -def _decode_image(url: str) -> np.ndarray: +def _decode_image(processor: Any, url: str) -> np.ndarray: """An RGB uint8 image from a data URL.""" - from PIL import Image - if not url.startswith("data:"): raise ValueError("Images must be data URLs or http(s) URLs.") data = base64.b64decode(url.partition(",")[2]) - return np.asarray(Image.open(io.BytesIO(data)).convert("RGB")) + return load_image(processor, io.BytesIO(data)) @dataclass @@ -678,7 +676,7 @@ def _tokenize(self, tokenizer, request, args): **{**template_kwargs, "tokenize": False}, ) text, pixel_values = processor( - text, images=[_decode_image(u) for u in urls] + text, images=[_decode_image(processor, u) for u in urls] ) prompt = tokenizer.encode(text, add_special_tokens=False) vision = _make_vision( From 18c4ab73667613d940d81fc4974646b5eaeb00a7 Mon Sep 17 00:00:00 2001 From: jundot Date: Thu, 19 Nov 2026 09:31:02 +0100 Subject: [PATCH 3/5] Test the checkerboard for transparent Inkling 2 images --- tests/models/test_inkling2.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tests/models/test_inkling2.py b/tests/models/test_inkling2.py index c18fa0adc..417aec7aa 100644 --- a/tests/models/test_inkling2.py +++ b/tests/models/test_inkling2.py @@ -265,6 +265,13 @@ def test_processor(self): self.assertTrue(mx.all(pixels[:, :5] == 1.0).item()) self.assertTrue(mx.allclose(pixels[:, 5:], mx.array((-1 / 255 - 0.5) / 0.5))) + rgba = np.zeros((16, 16, 4), dtype=np.uint8) + rgba[:, 8:, 3] = 255 + rgb = inkling2_processor._composite_alpha(rgba) + self.assertEqual(rgb[0, 0].tolist(), [204] * 3) + self.assertEqual(rgb[8, 0].tolist(), [153] * 3) + self.assertEqual(rgb[0, 8].tolist(), [0] * 3) + token = inkling2_processor.IMAGE_TOKEN text, pixel_values = processor(f"A {token} B", images=[image]) self.assertEqual(text, f"A {token * 4} B") From f00f0798ab5c4b0298a14d719ac26b185ceeff73 Mon Sep 17 00:00:00 2001 From: jundot Date: Fri, 20 Nov 2026 06:00:28 +0100 Subject: [PATCH 4/5] Move Inkling 2 to the new models layout Split the model file into config, layers, vision, checkpoint and model modules, and move the processor and the two kernels into the package. The processor now returns a dict of inputs, as load_processor expects, and the image rows use the shared splice. The model code is otherwise unchanged. --- mlx_lm/kernels/depth_attention.py | 107 -- mlx_lm/models/inkling2.py | 1278 ----------------- mlx_lm/models/inkling2/__init__.py | 14 + mlx_lm/models/inkling2/checkpoint.py | 121 ++ mlx_lm/models/inkling2/config.py | 77 + .../inkling2/kernels.py} | 124 +- mlx_lm/models/inkling2/layers.py | 669 +++++++++ mlx_lm/models/inkling2/model.py | 273 ++++ .../inkling2/processor.py} | 9 +- mlx_lm/models/inkling2/vision.py | 204 +++ tests/models/test_inkling2.py | 8 +- tests/test_kernels.py | 5 +- 12 files changed, 1487 insertions(+), 1402 deletions(-) delete mode 100644 mlx_lm/kernels/depth_attention.py delete mode 100644 mlx_lm/models/inkling2.py create mode 100644 mlx_lm/models/inkling2/__init__.py create mode 100644 mlx_lm/models/inkling2/checkpoint.py create mode 100644 mlx_lm/models/inkling2/config.py rename mlx_lm/{kernels/relative_attention.py => models/inkling2/kernels.py} (69%) create mode 100644 mlx_lm/models/inkling2/layers.py create mode 100644 mlx_lm/models/inkling2/model.py rename mlx_lm/{processors/inkling2.py => models/inkling2/processor.py} (94%) create mode 100644 mlx_lm/models/inkling2/vision.py diff --git a/mlx_lm/kernels/depth_attention.py b/mlx_lm/kernels/depth_attention.py deleted file mode 100644 index d816ba068..000000000 --- a/mlx_lm/kernels/depth_attention.py +++ /dev/null @@ -1,107 +0,0 @@ -# Copyright © 2026 Apple Inc. - -"""Attention of learned queries over the depth sources of each token, in one -kernel.""" - -import mlx.core as mx - -from ._common import row_threads, scalar - -_SOURCE = """ - constexpr int N = K + 1; - uint row = threadgroup_position_in_grid.x; - uint rows = threadgroups_per_grid.x; - uint tid = thread_position_in_threadgroup.x; - uint lane = thread_index_in_simdgroup; - uint sg = simdgroup_index_in_threadgroup; - - float acc[N * Q]; - for (int i = 0; i < N * Q; i++) { - acc[i] = 0.0f; - } - for (int d = tid; d < D; d += TG) { - float x[N]; - for (int i = 0; i < K; i++) { - x[i] = blocks[(size_t(i) * rows + row) * D + d]; - } - x[K] = partial[size_t(row) * D + d]; - for (int j = 0; j < Q; j++) { - float qv = queries[j * D + d]; - for (int i = 0; i < N; i++) { - acc[i * Q + j] += x[i] * qv; - } - } - } - - threadgroup float buf[N * Q][TG / 32]; - for (int i = 0; i < N * Q; i++) { - float v = simd_sum(acc[i]); - if (lane == 0) { - buf[i][sg] = v; - } - } - threadgroup_barrier(mem_flags::mem_threadgroup); - - float w[N * Q]; - for (int i = 0; i < N * Q; i++) { - float t = 0.0f; - for (int s = 0; s < TG / 32; s++) { - t += buf[i][s]; - } - w[i] = t * scale; - } - for (int j = 0; j < Q; j++) { - float m = -INFINITY; - for (int i = 0; i < N; i++) { - m = max(m, w[i * Q + j]); - } - float z = 0.0f; - for (int i = 0; i < N; i++) { - w[i * Q + j] = metal::exp(w[i * Q + j] - m); - z += w[i * Q + j]; - } - for (int i = 0; i < N; i++) { - w[i * Q + j] /= z; - } - } - - for (int d = tid; d < D; d += TG) { - float x[N]; - for (int i = 0; i < K; i++) { - x[i] = blocks[(size_t(i) * rows + row) * D + d]; - } - x[K] = partial[size_t(row) * D + d]; - for (int j = 0; j < Q; j++) { - float o = 0.0f; - for (int i = 0; i < N; i++) { - o += w[i * Q + j] * x[i]; - } - out[(size_t(row) * Q + j) * D + d] = o; - } - } -""" - -_kernel = mx.fast.metal_kernel( - name="depth_attention", - input_names=["blocks", "partial", "queries", "scale"], - output_names=["out"], - source=_SOURCE, -) - - -def depth_attention( - blocks: mx.array, partial: mx.array, queries: mx.array, *, scale: float -) -> mx.array: - """blocks: (K, ..., D) and partial: (..., D), float32, also the values. - queries: float32 (Q, D). Returns (..., Q, D).""" - D = partial.shape[-1] - Q = queries.shape[0] - TG = row_threads(D) - return _kernel( - inputs=[blocks, partial, queries, scalar(scale)], - template=[("K", blocks.shape[0]), ("D", D), ("Q", Q), ("TG", TG)], - grid=(partial.size // D * TG, 1, 1), - threadgroup=(TG, 1, 1), - output_shapes=[partial.shape[:-1] + (Q, D)], - output_dtypes=[mx.float32], - )[0] diff --git a/mlx_lm/models/inkling2.py b/mlx_lm/models/inkling2.py deleted file mode 100644 index c216bbbd1..000000000 --- a/mlx_lm/models/inkling2.py +++ /dev/null @@ -1,1278 +0,0 @@ -# Copyright © 2026 Apple Inc. - -"""Inkling 2. - -https://huggingface.co/thinkingmachines/Inkling-2-Small -""" - -import math -import re -from dataclasses import dataclass -from functools import partial -from typing import Any, Callable - -import mlx.core as mx -from mlx import nn -from mlx.nn.layers.distributed import shard_linear, sum_gradients -from mlx.utils import tree_unflatten - -from ..kernels import depth_attention, expert_routing, relative_attention -from .base import BaseModelArgs, gather_last_axis -from .cache import ( - ArraysCache, - BatchRotatingKVCache, - CacheList, - KVCache, - RotatingKVCache, -) -from .muse_spark import shard_experts_inplace -from .pipeline import PipelineMixin -from .switch_layers import SwitchLinear, _gather_sort, _scatter_unsort - -_ROUTER_SCORE_EPS = 1e-20 - -_NVFP4_E2M1_MAX = 6.0 -_NVFP4_E4M3_MAX = 448.0 - - -_RENAMES = [ - (r"^model\.llm\.unembed\.", "lm_head."), - (r"^model\.llm\.embed\.", "model.language_model.embed_tokens."), - (r"^model\.llm\.", "model.language_model."), - (r"\.attn_res\.mlp_queries\.(\d+)$", r".layers.\1.mlp_input.query"), - (r"\.attn_res\.output_query$", ".final_input.query"), - (r"\.attn\.wq_du\.", ".self_attn.q_proj."), - (r"\.attn\.wk_dv\.", ".self_attn.k_proj."), - (r"\.attn\.wv_dv\.", ".self_attn.v_proj."), - (r"\.attn\.wr_du\.", ".self_attn.r_proj."), - (r"\.attn\.wo_ud\.", ".self_attn.o_proj."), - (r"\.attn\.gate_attn\.", ".self_attn.gate_proj."), - (r"\.attn\.attn_sink_proj\.", ".self_attn.sink_proj."), - (r"\.attn\.", ".self_attn."), - (r"\.attn_sconv\.", ".post_attention_convolution."), - (r"\.mlp_sconv\.", ".post_mlp_convolution."), - (r"sconv\.weight$", "sconv.conv1d.weight"), - (r"convolution\.weight$", "convolution.conv1d.weight"), - (r"sconv\.static_w$", "sconv.static_weight"), - (r"sconv\.weight_proj$", "sconv.weight_proj.weight"), - (r"\.mlp_norm\.", ".post_attention_layernorm."), - (r"\.attn_norm\.", ".input_layernorm."), - (r"\.(q|k|v)_input_norm\.", r".\1_input_layernorm."), - (r"\.mlp\.gate\.bias$", ".mlp.gate.e_score_correction_bias"), - (r"^model\.visual\.backbone\.ln_pre\.", "model.vision_tower.pre_layernorm."), - (r"^model\.visual\.backbone\.", "model.vision_tower."), - (r"^model\.visual\.proj_in\.", "model.vision_tower.merger.linear_1."), - (r"^model\.visual\.proj_out\.", "model.vision_tower.merger.linear_2."), - (r"embeddings\.position_embedding$", "embeddings.position_embedding.weight"), - (r"(vision_tower\.layers\.\d+)\.ln_1\.", r"\1.layernorm_before."), - (r"(vision_tower\.layers\.\d+)\.ln_2\.", r"\1.layernorm_after."), - (r"(vision_tower\.layers\.\d+)\.mlp\.c_fc\.", r"\1.mlp.fc1."), - (r"(vision_tower\.layers\.\d+)\.mlp\.c_proj\.", r"\1.mlp.fc2."), - (r"(vision_tower\.layers\.\d+)\.ls_(\d)\.gamma$", r"\1.lambda_\2"), -] - - -def _rename(key: str) -> str: - if m := re.match(r"model\.llm\.attn_res\.attn_queries\.(\d+)$", key): - # Layer 0 has no attention input, so query i is for layer i + 1. - layer = int(m.group(1)) + 1 - return f"model.language_model.layers.{layer}.attention_input.query" - for pattern, replacement in _RENAMES: - key = re.sub(pattern, replacement, key) - return key - - -@dataclass -class TextArgs(BaseModelArgs): - hidden_size: int - num_hidden_layers: int - vocab_size: int - unpadded_vocab_size: int - num_attention_heads: int - num_key_value_heads: int - head_dim: int - swa_num_attention_heads: int - swa_num_key_value_heads: int - swa_head_dim: int - sliding_window_size: int - local_layer_ids: list[int] - d_rel: int - rel_extent: int - log_scaling_n_floor: int - log_scaling_alpha: float - rms_norm_eps: float - qk_l2_clip_threshold: float - rel_l2_clip_threshold: float - sconv_kernel_size: int - n_layers_per_attn_res_block: int - n_routed_experts: int - num_experts_per_tok: int - intermediate_size: int - mlp_gate_softcap: float - mlp_up_softcap: float - route_scale: float - final_logit_softcapping: float - - -@dataclass -class VisionArgs(BaseModelArgs): - hidden_size: int = 1024 - num_hidden_layers: int = 23 - num_attention_heads: int = 16 - num_channels: int = 3 - native_patch_size: int = 20 - adapter_merge_size: int = 2 - posemb_grid_size: int = 32 - projection_hidden_dim: int = 4096 - projector_bias: bool = False - mlp_ratio: float = 4.0 - layer_norm_eps: float = 1e-5 - rope_theta: float = 10000.0 - - def __post_init__(self): - self.head_dim = self.hidden_size // self.num_attention_heads - self.intermediate_size = int(self.hidden_size * self.mlp_ratio) - - -@dataclass -class ModelArgs(BaseModelArgs): - model_type: str - text_config: dict - vision_config: dict | None = None - image_token_id: int = 200054 - - def __post_init__(self): - self.text = TextArgs.from_dict(self.text_config) - self.vision = None - if self.vision_config: - self.vision = VisionArgs.from_dict(self.vision_config) - - -def _use_kernels() -> bool: - return mx.default_device() == mx.gpu and mx.metal.is_available() - - -def _unweighted_rms_norm(x: mx.array, eps: float = 1e-6) -> mx.array: - return mx.fast.rms_norm(x, None, eps) - - -def _precise_gelu(x: mx.array) -> mx.array: - return nn.gelu(x.astype(mx.float32)).astype(x.dtype) - - -@partial(mx.compile, shapeless=True) -def _l2_clip(hidden_states: mx.array, scale: mx.array, threshold: float) -> mx.array: - states = hidden_states.astype(mx.float32) * scale - norm = mx.sqrt((states * states).sum(axis=-1, keepdims=True)) - scaled = states * mx.minimum(threshold / (norm + 1e-6), 1.0) - return scaled.astype(hidden_states.dtype) - - -@partial(mx.compile, shapeless=True) -def _softcapped_swiglu( - gate: mx.array, up: mx.array, gate_softcap: float, up_softcap: float -) -> mx.array: - input_dtype = gate.dtype - gate, up = gate.astype(mx.float32), up.astype(mx.float32) - gate_capped = mx.tanh(gate / gate_softcap) * gate_softcap - up_capped = mx.tanh(up / up_softcap) * up_softcap - return (gate_capped * mx.sigmoid(gate) * up_capped).astype(input_dtype) - - -class L2Clip(nn.Module): - def __init__(self, threshold: float): - super().__init__() - self.threshold = threshold - - def __call__(self, hidden_states: mx.array) -> mx.array: - return _l2_clip(hidden_states, 1.0, self.threshold) - - -class ScaledL2Clip(nn.Module): - def __init__(self, num_heads: int, head_dim: int, threshold: float): - super().__init__() - self.threshold = threshold - self.scale = mx.ones((num_heads, head_dim)) - - def __call__(self, hidden_states: mx.array) -> mx.array: - return _l2_clip(hidden_states, self.scale, self.threshold) - - -class RelativeLogits(nn.Module): - def __init__(self, d_rel: int, rel_extent: int): - super().__init__() - self.proj = mx.zeros((d_rel, rel_extent)) - - def __call__(self, relative_states: mx.array) -> mx.array: - return relative_states @ self.proj.astype(relative_states.dtype) - - -def _conv_input( - hidden_states: mx.array, - conv_state: mx.array | None, - conv_mask: mx.array | None, - kernel_size: int, -) -> mx.array: - hidden_states = hidden_states.astype(mx.float32) - if conv_mask is not None: - hidden_states = mx.where(conv_mask[..., None], hidden_states, 0) - if conv_state is None: - shape = (hidden_states.shape[0], kernel_size - 1, hidden_states.shape[-1]) - conv_state = mx.zeros(shape, mx.float32) - return mx.concatenate([conv_state, hidden_states], axis=1) - - -def _conv_state(window: mx.array, lengths: mx.array | None, n: int) -> mx.array: - if lengths is None: - pos = mx.arange(window.shape[1] - n, window.shape[1])[None, :, None] - else: - ends = mx.clip(lengths, 0, window.shape[1] - n) - pos = (ends[:, None] + mx.arange(n))[..., None] - # A gather copies, so the state does not keep the input in memory. - return mx.take_along_axis(window, pos, axis=1) - - -class ShortConvolution(nn.Module): - def __init__(self, dims: int, kernel_size: int): - super().__init__() - self.kernel_size = kernel_size - self.conv1d = nn.Conv1d(dims, dims, kernel_size, groups=dims, bias=False) - - def __call__( - self, - hidden_states: mx.array, - conv_state: mx.array | None, - conv_mask: mx.array | None, - ) -> tuple[mx.array, mx.array]: - K = self.kernel_size - residual = hidden_states.astype(mx.float32) - window = _conv_input(hidden_states, conv_state, conv_mask, K) - # As the reference, the conv runs in the weight dtype. - out = self.conv1d(window.astype(self.conv1d.weight.dtype)) - out = (out.astype(mx.float32) + residual) / math.sqrt(K + 1) - return out.astype(hidden_states.dtype), window - - -class DynamicShortConvolution(nn.Module): - def __init__(self, dims: int, input_dims: int, num_heads: int, kernel_size: int): - super().__init__() - self.kernel_size = kernel_size - self.num_heads = num_heads - self.static_weight = mx.zeros((kernel_size, dims)) - self.weight_proj = nn.Linear(input_dims, num_heads * kernel_size, bias=False) - - def __call__( - self, - hidden_states: mx.array, - dynamic_input: mx.array, - conv_state: mx.array | None, - conv_mask: mx.array | None, - ) -> tuple[mx.array, mx.array]: - B, L, C = hidden_states.shape - K, H = self.kernel_size, self.num_heads - dynamic_weights = self.weight_proj(dynamic_input).astype(mx.float32) - dynamic_weights = dynamic_weights.reshape(B, L, H, 1, K) - static_weights = self.static_weight.astype(mx.float32).T.reshape(H, -1, K) - weights = static_weights + dynamic_weights - - window = _conv_input(hidden_states, conv_state, conv_mask, K) - windows = mx.stack( - [window[:, K - 1 - lag : K - 1 - lag + L] for lag in range(K)], axis=-1 - ) - windows = windows.reshape(B, L, H, -1, K) - out = (windows * weights).sum(axis=-1).reshape(B, L, C) - out = (out + hidden_states.astype(mx.float32)) / math.sqrt(2 * K + 1) - return out.astype(hidden_states.dtype), window - - -def _positions(offset, length: int) -> mx.array: - pos = mx.arange(length) - if isinstance(offset, mx.array): - return offset[:, None] + pos - return pos + offset - - -def _key_positions(cache: Any, num_keys: int, num_queries: int, end) -> mx.array: - k = mx.arange(num_keys) - if num_queries == 1 and isinstance(cache, (RotatingKVCache, BatchRotatingKVCache)): - # A decode step writes in place, so the keys can be rotated. - k = (k - cache._idx) % num_keys - if isinstance(end, mx.array): - return (end - num_keys)[:, None] + k - return k + (end - num_keys) - - -def _attention_reference( - query: mx.array, - key: mx.array, - value: mx.array, - position_bias: mx.array, - sinks: mx.array, - *, - scale: float, - window: int, - query_positions: mx.array, - key_positions: mx.array, -) -> mx.array: - B, Hq, L, D = query.shape - Hkv, S = key.shape[1], key.shape[2] - R = position_bias.shape[-1] - distance = query_positions[..., :, None] - key_positions[..., None, :] - visible = (distance >= 0) & (key_positions[..., None, :] >= 0) - if window: - visible = visible & (distance < window) - if distance.ndim == 3: - distance, visible = distance[:, None], visible[:, None] - bias = mx.take_along_axis( - position_bias.transpose(0, 2, 1, 3), - mx.broadcast_to(mx.clip(distance, 0, R - 1), (B, Hq, L, S)), - axis=-1, - ) - bias = mx.where(distance < R, bias.astype(mx.float32), 0.0) - attention_mask = mx.where(visible, bias, -mx.inf).reshape(B, Hkv, -1, L, S) - - query = query.astype(mx.float32).reshape(B, Hkv, -1, L, D) - key = key.astype(mx.float32)[:, :, None] - attn_weights = (query @ key.swapaxes(-1, -2)) * scale + attention_mask - sinks = sinks.astype(mx.float32).transpose(0, 2, 1).reshape(B, Hkv, -1, L, 1) - combined_logits = mx.concatenate([attn_weights, sinks], axis=-1) - attn_weights = mx.softmax(combined_logits, axis=-1)[..., :S] - attn_output = attn_weights.astype(value.dtype) @ value[:, :, None] - return attn_output.reshape(B, Hq, L, D).transpose(0, 2, 1, 3) - - -class Attention(nn.Module): - def __init__(self, args: TextArgs, *, sliding: bool): - super().__init__() - if sliding: - self.num_heads = args.swa_num_attention_heads - self.num_key_value_heads = args.swa_num_key_value_heads - self.head_dim = args.swa_head_dim - self.sliding_window = args.sliding_window_size - rel_extent = args.sliding_window_size - else: - self.num_heads = args.num_attention_heads - self.num_key_value_heads = args.num_key_value_heads - self.head_dim = args.head_dim - self.sliding_window = 0 - rel_extent = args.rel_extent - self.scaling = self.head_dim**-0.5 - - dim = args.hidden_size - q_dim = self.num_heads * self.head_dim - kv_dim = self.num_key_value_heads * self.head_dim - self.q_proj = nn.Linear(dim, q_dim, bias=False) - self.k_proj = nn.Linear(dim, kv_dim, bias=False) - self.v_proj = nn.Linear(dim, kv_dim, bias=False) - self.r_proj = nn.Linear(dim, self.num_heads * args.d_rel, bias=False) - self.o_proj = nn.Linear(q_dim, dim, bias=False) - self.gate_proj = nn.Linear(dim, q_dim, bias=False) - self.sink_proj = nn.Linear(dim, self.num_heads, bias=False) - self.rel_logits_proj = RelativeLogits(args.d_rel, rel_extent) - self.q_l2_clip = ScaledL2Clip( - self.num_heads, self.head_dim, args.qk_l2_clip_threshold - ) - self.k_l2_clip = L2Clip(args.qk_l2_clip_threshold) - self.rel_l2_clip = ScaledL2Clip( - self.num_heads, args.d_rel, args.rel_l2_clip_threshold - ) - self.eps = args.rms_norm_eps - - def _attend( - self, - hidden_states: mx.array, - query_states: mx.array, - key_states: mx.array, - value_states: mx.array, - relative_states: mx.array, - cache: Any | None, - tau: mx.array | None = None, - ) -> mx.array: - B, L, _ = hidden_states.shape - gate = self.gate_proj(hidden_states) - sinks = self.sink_proj(hidden_states) - - query_states = query_states.reshape(B, L, self.num_heads, -1) - key_states = key_states.reshape(B, L, self.num_key_value_heads, -1) - value_states = value_states.reshape(B, L, self.num_key_value_heads, -1) - relative_states = relative_states.reshape(B, L, self.num_heads, -1) - query_states = self.q_l2_clip(query_states) - key_states = self.k_l2_clip(key_states) - value_states = _unweighted_rms_norm( - value_states.astype(mx.float32), self.eps - ).astype(value_states.dtype) - relative_states = self.rel_l2_clip(relative_states) - if tau is not None: - query_states = (query_states.astype(mx.float32) * tau).astype( - query_states.dtype - ) - relative_states = (relative_states.astype(mx.float32) * tau).astype( - relative_states.dtype - ) - position_bias = self.rel_logits_proj(relative_states) - - query_states = query_states.transpose(0, 2, 1, 3) - key_states = key_states.transpose(0, 2, 1, 3) - value_states = value_states.transpose(0, 2, 1, 3) - if cache is not None: - key_states, value_states = cache.update_and_fetch(key_states, value_states) - attn_output = self._attention( - query_states, key_states, value_states, position_bias, sinks, cache - ) - - attn_output = attn_output.reshape(B, L, -1).astype(mx.float32) - attn_output = attn_output * mx.sigmoid(gate.astype(mx.float32)) - return self.o_proj(attn_output.astype(gate.dtype)) - - def _attention(self, query, key, value, position_bias, sinks, cache) -> mx.array: - B, _, L, _ = query.shape - S = key.shape[2] - end = cache.offset if cache is not None else L - bf16 = query.dtype == key.dtype == value.dtype == mx.bfloat16 - if L > 1 and _use_kernels() and bf16: - key_start = mx.broadcast_to(S - end, (B,)) - return relative_attention( - query, - key, - value, - position_bias, - sinks, - scale=self.scaling, - window=self.sliding_window, - key_start=key_start, - ) - - query_positions = _positions(end - L, L) - key_positions = _key_positions(cache, S, L, end) - if L == 1 and B == 1: - # The fused attention takes the sinks of one row. - distance = query_positions.reshape(1) - key_positions.reshape(S) - R = position_bias.shape[-1] - bias = mx.take(position_bias[0, 0], mx.clip(distance, 0, R - 1), axis=-1) - bias = mx.where(distance < R, bias, mx.zeros_like(bias)) - visible = (distance >= 0) & (key_positions.reshape(S) >= 0) - if self.sliding_window: - visible = visible & (distance < self.sliding_window) - mask = mx.where(visible, bias, -mx.inf).astype(query.dtype) - attn_output = mx.fast.scaled_dot_product_attention( - query, - key, - value, - scale=self.scaling, - mask=mask[None, :, None, :], - sinks=sinks[0, 0].astype(query.dtype), - ) - return attn_output.transpose(0, 2, 1, 3) - - return _attention_reference( - query, - key, - value, - position_bias, - sinks, - scale=self.scaling, - window=self.sliding_window, - query_positions=query_positions, - key_positions=key_positions, - ) - - -class SlidingAttention(Attention): - def __init__(self, args: TextArgs): - super().__init__(args, sliding=True) - dims = self.num_key_value_heads * self.head_dim - self.k_sconv = ShortConvolution(dims, args.sconv_kernel_size) - self.v_sconv = ShortConvolution(dims, args.sconv_kernel_size) - - def __call__( - self, - hidden_states: mx.array, - *, - cache: Any | None, - conv_states: list, - conv_mask: mx.array | None, - ) -> mx.array: - kv_cache = cache[0] if cache is not None else None - key_states, conv_states[0] = self.k_sconv( - self.k_proj(hidden_states), conv_states[0], conv_mask - ) - value_states, conv_states[1] = self.v_sconv( - self.v_proj(hidden_states), conv_states[1], conv_mask - ) - return self._attend( - hidden_states, - self.q_proj(hidden_states), - key_states, - value_states, - self.r_proj(hidden_states), - kv_cache, - ) - - -class FullAttention(Attention): - def __init__(self, args: TextArgs): - super().__init__(args, sliding=False) - dims = self.num_key_value_heads * self.head_dim - conv_args = (args.hidden_size, self.num_key_value_heads, args.sconv_kernel_size) - self.k_sconv = DynamicShortConvolution(dims, *conv_args) - self.v_sconv = DynamicShortConvolution(dims, *conv_args) - self.log_scaling_n_floor = args.log_scaling_n_floor - self.log_scaling_alpha = args.log_scaling_alpha - - def __call__( - self, - hidden_states: mx.array, - key_hidden_states: mx.array, - value_hidden_states: mx.array, - *, - cache: Any | None, - conv_states: list, - conv_mask: mx.array | None, - ) -> mx.array: - kv_cache = cache[0] if cache is not None else None - key_states, conv_states[0] = self.k_sconv( - self.k_proj(key_hidden_states), - key_hidden_states, - conv_states[0], - conv_mask, - ) - value_states, conv_states[1] = self.v_sconv( - self.v_proj(value_hidden_states), - value_hidden_states, - conv_states[1], - conv_mask, - ) - - offset = kv_cache.offset if kv_cache is not None else 0 - position_ids = _positions(offset, hidden_states.shape[1]).astype(mx.float32) - tau = 1.0 + self.log_scaling_alpha * mx.log( - mx.maximum((position_ids + 1) / self.log_scaling_n_floor, 1.0) - ) - return self._attend( - hidden_states, - self.q_proj(hidden_states), - key_states, - value_states, - self.r_proj(hidden_states), - kv_cache, - tau=tau[..., None, None], - ) - - -class SoftcappedSwiGLU(nn.Module): - def __init__(self, args: TextArgs): - super().__init__() - self.gate_softcap = args.mlp_gate_softcap - self.up_softcap = args.mlp_up_softcap - - def __call__(self, gate: mx.array, up: mx.array) -> mx.array: - return _softcapped_swiglu(gate, up, self.gate_softcap, self.up_softcap) - - -class Experts(nn.Module): - def __init__(self, args: TextArgs): - super().__init__() - dims, hidden = args.hidden_size, args.intermediate_size - num_experts = args.n_routed_experts - # The rows alternate between gate and up, as in the checkpoint. - self.gate_up_proj = SwitchLinear(dims, 2 * hidden, num_experts, bias=False) - self.down_proj = SwitchLinear(hidden, dims, num_experts, bias=False) - self.act_fn = SoftcappedSwiGLU(args) - - def __call__(self, x: mx.array, indices: mx.array) -> mx.array: - x = mx.expand_dims(x, (-2, -3)) - indices = mx.stop_gradient(indices) - do_sort = indices.size >= 64 - idx, inv_order = indices, None - if do_sort: - x, idx, inv_order = _gather_sort(x, indices) - gate_up = self.gate_up_proj(x, idx, sorted_indices=do_sort) - x = self.act_fn(gate_up[..., 0::2], gate_up[..., 1::2]) - x = self.down_proj(x, idx, sorted_indices=do_sort) - if do_sort: - x = _scatter_unsort(x, inv_order, indices.shape) - return x.squeeze(-2) - - -class TopKRouter(nn.Module): - def __init__(self, args: TextArgs): - super().__init__() - self.top_k = args.num_experts_per_tok - self.routed_scaling_factor = args.route_scale - num_experts, dims = args.n_routed_experts, args.hidden_size - self.weight = mx.zeros((num_experts, dims), dtype=mx.float32) - self.e_score_correction_bias = mx.zeros((num_experts,), dtype=mx.float32) - - def __call__(self, hidden_states: mx.array) -> tuple[mx.array, mx.array]: - logits = hidden_states.astype(mx.float32) @ self.weight.T - if _use_kernels(): - return expert_routing( - logits, - self.e_score_correction_bias, - top_k=self.top_k, - multiplier=1.0, - score_eps=_ROUTER_SCORE_EPS, - route_scale=self.routed_scaling_factor, - ) - scores = mx.sigmoid(logits) - biased = scores + self.e_score_correction_bias - k = self.top_k - indices = mx.argpartition(-biased, kth=k - 1, axis=-1)[..., :k] - weights = mx.take_along_axis(scores, indices, axis=-1) - weights = weights / (weights.sum(axis=-1, keepdims=True) + _ROUTER_SCORE_EPS) - return indices, weights * self.routed_scaling_factor - - -class SparseMoeBlock(nn.Module): - def __init__(self, args: TextArgs): - super().__init__() - self.gate = TopKRouter(args) - self.experts = Experts(args) - self.sharding_group = None - - def __call__(self, hidden_states: mx.array) -> mx.array: - group = self.sharding_group - if group is not None: - hidden_states = sum_gradients(group)(hidden_states) - selected_experts, routing_weights = self.gate(hidden_states) - expert_states = self.experts(hidden_states, selected_experts) - expert_states = expert_states.astype(mx.float32) * routing_weights[..., None] - final_hidden_states = expert_states.sum(axis=-2) - if group is not None: - final_hidden_states = mx.distributed.all_sum( - final_hidden_states, group=group - ) - return final_hidden_states.astype(hidden_states.dtype) - - -class BlockAttentionResidual(nn.Module): - def __init__(self, dims: int, num_queries: int = 1): - super().__init__() - shape = (dims,) if num_queries == 1 else (num_queries, dims) - self.query = mx.zeros(shape, dtype=mx.float32) - - def __call__( - self, block_states: mx.array, partial_block_states: mx.array - ) -> mx.array: - dims = partial_block_states.shape[-1] - query = self.query.reshape(-1, dims).astype(mx.float32) - scale = dims**-0.5 - if _use_kernels(): - return depth_attention( - block_states, partial_block_states, query, scale=scale - ) - stacked_states = mx.concatenate([block_states, partial_block_states[None]]) - stacked_states = mx.moveaxis(stacked_states, 0, -2) - weights = mx.softmax((stacked_states @ query.T) * scale, axis=-2, precise=True) - return weights.swapaxes(-1, -2) @ stacked_states - - -class DecoderLayer(nn.Module): - def __init__(self, args: TextArgs, layer_idx: int, *, num_queries: int): - super().__init__() - dims = args.hidden_size - self.is_block_boundary = layer_idx % args.n_layers_per_attn_res_block == 0 - self.attention_input = ( - BlockAttentionResidual(dims, num_queries) if layer_idx > 0 else None - ) - self.mlp_input = BlockAttentionResidual(dims) - self.mlp = SparseMoeBlock(args) - self.post_attention_layernorm = nn.RMSNorm(dims, eps=args.rms_norm_eps) - kernel_size = args.sconv_kernel_size - self.post_attention_convolution = ShortConvolution(dims, kernel_size) - self.post_mlp_convolution = ShortConvolution(dims, kernel_size) - - def __call__( - self, - hidden_states: mx.array, - block_states: mx.array | None, - *, - cache: Any | None = None, - conv_mask: mx.array | None = None, - ) -> tuple[mx.array, mx.array]: - dtype = hidden_states.dtype - conv = cache[1] if cache is not None else None - conv_states = list(conv.cache) if conv is not None else [None] * 4 - block_residual = hidden_states - normed_residual = _unweighted_rms_norm(block_residual.astype(mx.float32)) - - attention_inputs = None - if self.attention_input is not None: - attention_inputs = self.attention_input(block_states, normed_residual) - hidden_states = self._self_attention( - hidden_states, attention_inputs, cache, conv_states, conv_mask - ) - hidden_states, conv_states[2] = self.post_attention_convolution( - hidden_states, conv_states[2], conv_mask - ) - - residual = hidden_states = hidden_states.astype(mx.float32) - if self.is_block_boundary: - block = normed_residual[None] - if block_states is None: - block_states = block - else: - block_states = mx.concatenate([block_states, block]) - else: - residual = hidden_states = block_residual.astype(mx.float32) + hidden_states - - normed_states = _unweighted_rms_norm(hidden_states) - hidden_states = self.mlp_input(block_states, normed_states)[..., 0, :] - hidden_states = self.mlp( - self.post_attention_layernorm(hidden_states).astype(dtype) - ) - hidden_states, conv_states[3] = self.post_mlp_convolution( - hidden_states, conv_states[3], conv_mask - ) - - if conv is not None: - n = self.post_mlp_convolution.kernel_size - 1 - for i, window in enumerate(conv_states): - conv[i] = _conv_state(window, conv.lengths, n) - conv.advance(block_residual.shape[1]) - hidden_states = residual + hidden_states.astype(mx.float32) - return hidden_states.astype(dtype), block_states - - -class SlidingDecoderLayer(DecoderLayer): - def __init__(self, args: TextArgs, layer_idx: int): - super().__init__(args, layer_idx, num_queries=1) - self.self_attn = SlidingAttention(args) - self.input_layernorm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps) - - def _self_attention( - self, hidden_states, attention_inputs, cache, conv_states, conv_mask - ): - dtype = hidden_states.dtype - if attention_inputs is not None: - hidden_states = attention_inputs[..., 0, :] - return self.self_attn( - self.input_layernorm(hidden_states).astype(dtype), - cache=cache, - conv_states=conv_states, - conv_mask=conv_mask, - ) - - -class FullDecoderLayer(DecoderLayer): - def __init__(self, args: TextArgs, layer_idx: int): - super().__init__(args, layer_idx, num_queries=3) - self.self_attn = FullAttention(args) - eps = args.rms_norm_eps - self.q_input_layernorm = nn.RMSNorm(args.hidden_size, eps=eps) - self.k_input_layernorm = nn.RMSNorm(args.hidden_size, eps=eps) - self.v_input_layernorm = nn.RMSNorm(args.hidden_size, eps=eps) - - def _self_attention( - self, hidden_states, attention_inputs, cache, conv_states, conv_mask - ): - dtype = hidden_states.dtype - if attention_inputs is None: - query_states = key_states = value_states = hidden_states - else: - query_states, key_states, value_states = ( - attention_inputs[..., i, :] for i in range(3) - ) - return self.self_attn( - self.q_input_layernorm(query_states).astype(dtype), - self.k_input_layernorm(key_states).astype(dtype), - self.v_input_layernorm(value_states).astype(dtype), - cache=cache, - conv_states=conv_states, - conv_mask=conv_mask, - ) - - -class TextModel(PipelineMixin, nn.Module): - def __init__(self, args: TextArgs): - super().__init__() - self.args = args - self.embed_tokens = nn.Embedding(args.vocab_size, args.hidden_size) - # Not in embed_tokens as in transformers, so that it can be quantized. - self.embed_norm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps) - self.layers = [ - ( - SlidingDecoderLayer(args, i) - if i in args.local_layer_ids - else FullDecoderLayer(args, i) - ) - for i in range(args.num_hidden_layers) - ] - self.final_input = BlockAttentionResidual(args.hidden_size) - self.norm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps) - - def embed(self, inputs: mx.array) -> mx.array: - return self.embed_norm(self.embed_tokens(inputs)) - - def __call__( - self, - inputs: mx.array, - cache: list[Any] | None = None, - input_embeddings: mx.array | None = None, - ) -> mx.array: - if input_embeddings is None: - input_embeddings = self.embed(inputs) - hidden_states = input_embeddings - dtype = hidden_states.dtype - - layers = self.pipeline_layers - if cache is None: - cache = [None] * len(layers) - conv_mask = None - if cache[0] is not None: - conv_mask = cache[0][1].make_mask(hidden_states.shape[1]) - - rank, size = self.pipeline_rank, self.pipeline_size - block_states = None - if rank < size - 1: - num_blocks = -(-self.start_idx // self.args.n_layers_per_attn_res_block) - states = mx.zeros((num_blocks + 1, *hidden_states.shape), mx.float32) - states = mx.distributed.recv_like(states, rank + 1) - hidden_states, block_states = states[0].astype(dtype), states[1:] - - for layer, c in zip(layers, cache): - hidden_states, block_states = layer( - hidden_states, block_states, cache=c, conv_mask=conv_mask - ) - - if rank != 0: - states = mx.concatenate( - [hidden_states.astype(mx.float32)[None], block_states] - ) - states = mx.distributed.send(states, (rank - 1) % size) - if cache[-1] is not None: - kv_cache = cache[-1][0] - kv_cache.keys = mx.depends(kv_cache.keys, states) - # Only the output of rank 0 is used. - hidden_states = states[0].astype(dtype) - else: - normed_states = _unweighted_rms_norm(hidden_states.astype(mx.float32)) - hidden_states = self.final_input(block_states, normed_states)[..., 0, :] - hidden_states = self.norm(hidden_states).astype(dtype) - - if size > 1: - batch = hidden_states.shape[0] - hidden_states = mx.distributed.all_gather(hidden_states)[:batch] - return hidden_states - - -def _grid_positions(grid_h: int, grid_w: int, merge: int) -> tuple[mx.array, mx.array]: - i = mx.arange(grid_h * grid_w) - blocks_w = grid_w // merge - row = i // (merge * merge * blocks_w) * merge + i // merge % merge - col = i // (merge * merge) % blocks_w * merge + i % merge - return row, col - - -def _bilinear_taps(index: mx.array, size: int, side: int) -> tuple[mx.array, mx.array]: - src = (index.astype(mx.float32) + 0.5) * side / size - 0.5 - taps = mx.floor(src)[:, None] + mx.arange(2) - weights = mx.maximum(1.0 - mx.abs(src[:, None] - taps), 0.0) - return mx.clip(taps, 0, side - 1).astype(mx.int32), weights - - -class VisionEmbeddings(nn.Module): - def __init__(self, args: VisionArgs): - super().__init__() - self.merge_size = args.adapter_merge_size - self.grid_size = args.posemb_grid_size - patch_dims = args.num_channels * args.native_patch_size**2 - self.patch_embedding = nn.Linear(patch_dims, args.hidden_size, bias=False) - self.position_embedding = nn.Embedding( - args.posemb_grid_size**2, args.hidden_size - ) - self.class_embedding = mx.zeros((args.hidden_size,)) - self.cls_position_embedding = mx.zeros((args.hidden_size,)) - - def __call__(self, pixel_values: mx.array, grid_h: int, grid_w: int) -> mx.array: - patch_embeddings = self.patch_embedding(pixel_values) - - side = self.grid_size - row, col = _grid_positions(grid_h, grid_w, self.merge_size) - row_taps, row_weights = _bilinear_taps(row, grid_h, side) - col_taps, col_weights = _bilinear_taps(col, grid_w, side) - interp_indices = row_taps[:, :, None] * side + col_taps[:, None, :] - interp_weights = row_weights[:, :, None] * col_weights[:, None, :] - position_embeddings = self.position_embedding(interp_indices.reshape(-1, 4)) - position_embeddings = position_embeddings.astype(mx.float32) - position_embeddings = position_embeddings * interp_weights.reshape(-1, 4, 1) - patch_embeddings = patch_embeddings + position_embeddings.sum(axis=1).astype( - patch_embeddings.dtype - ) - - cls_embedding = self.class_embedding + self.cls_position_embedding - cls_embedding = cls_embedding.astype(patch_embeddings.dtype) - return mx.concatenate([cls_embedding[None], patch_embeddings]) - - -class VisionRotaryEmbedding(nn.Module): - def __init__(self, args: VisionArgs): - super().__init__() - dims = args.head_dim // 2 - self._inv_freq = 1.0 / ( - args.rope_theta ** (mx.arange(0, dims, 2, dtype=mx.float32) / dims) - ) - - def __call__(self, row: mx.array, col: mx.array) -> tuple[mx.array, mx.array]: - freqs_h = row[:, None].astype(mx.float32) * self._inv_freq - freqs_w = col[:, None].astype(mx.float32) * self._inv_freq - freqs = mx.repeat(mx.concatenate([freqs_w, freqs_h], axis=-1), 2, axis=-1) - return mx.cos(freqs), mx.sin(freqs) - - -def _apply_rotary_pos_emb_vision( - hidden_states: mx.array, cos: mx.array, sin: mx.array -) -> mx.array: - states = hidden_states.astype(mx.float32) - pairs = states.reshape(*states.shape[:-1], -1, 2) - rotated = mx.stack([-pairs[..., 1], pairs[..., 0]], axis=-1).reshape(states.shape) - return (states * cos + rotated * sin).astype(hidden_states.dtype) - - -class VisionAttention(nn.Module): - def __init__(self, args: VisionArgs): - super().__init__() - dims = args.hidden_size - self.num_heads = args.num_attention_heads - self.scaling = args.head_dim**-0.5 - self.q_proj = nn.Linear(dims, dims) - self.k_proj = nn.Linear(dims, dims) - self.v_proj = nn.Linear(dims, dims) - self.out_proj = nn.Linear(dims, dims) - - def __call__( - self, hidden_states: mx.array, cos: mx.array, sin: mx.array - ) -> mx.array: - N = hidden_states.shape[0] - shape = (N, self.num_heads, -1) - cos, sin = cos[:, None], sin[:, None] - query_states = self.q_proj(hidden_states).reshape(shape) - key_states = self.k_proj(hidden_states).reshape(shape) - value_states = self.v_proj(hidden_states).reshape(shape) - query_states = _apply_rotary_pos_emb_vision(query_states, cos, sin) - key_states = _apply_rotary_pos_emb_vision(key_states, cos, sin) - query_states, key_states, value_states = ( - states.transpose(1, 0, 2)[None] - for states in (query_states, key_states, value_states) - ) - attn_output = mx.fast.scaled_dot_product_attention( - query_states, key_states, value_states, scale=self.scaling - ) - attn_output = attn_output[0].transpose(1, 0, 2).reshape(N, -1) - return self.out_proj(attn_output) - - -class VisionMLP(nn.Module): - def __init__(self, args: VisionArgs): - super().__init__() - self.fc1 = nn.Linear(args.hidden_size, args.intermediate_size) - self.fc2 = nn.Linear(args.intermediate_size, args.hidden_size) - - def __call__(self, hidden_states: mx.array) -> mx.array: - return self.fc2(_precise_gelu(self.fc1(hidden_states))) - - -class VisionEncoderLayer(nn.Module): - def __init__(self, args: VisionArgs): - super().__init__() - dims, eps = args.hidden_size, args.layer_norm_eps - self.self_attn = VisionAttention(args) - self.mlp = VisionMLP(args) - self.layernorm_before = nn.LayerNorm(dims, eps=eps) - self.layernorm_after = nn.LayerNorm(dims, eps=eps) - self.lambda_1 = mx.ones((dims,)) - self.lambda_2 = mx.ones((dims,)) - - def __call__( - self, hidden_states: mx.array, cos: mx.array, sin: mx.array - ) -> mx.array: - residual = hidden_states - hidden_states = self.self_attn(self.layernorm_before(hidden_states), cos, sin) - hidden_states = residual + self.lambda_1 * hidden_states - residual = hidden_states - hidden_states = self.mlp(self.layernorm_after(hidden_states)) - return residual + self.lambda_2 * hidden_states - - -class VisionMerger(nn.Module): - def __init__(self, args: VisionArgs, text_hidden_size: int): - super().__init__() - dims = args.adapter_merge_size**2 * args.hidden_size - hidden, bias = args.projection_hidden_dim, args.projector_bias - self.linear_1 = nn.Linear(dims, hidden, bias=bias) - self.linear_2 = nn.Linear(hidden, text_hidden_size, bias=bias) - - def __call__(self, image_features: mx.array) -> mx.array: - return self.linear_2(_precise_gelu(self.linear_1(image_features))) - - -class VisionModel(nn.Module): - def __init__(self, args: VisionArgs, text_hidden_size: int): - super().__init__() - self.args = args - self.embeddings = VisionEmbeddings(args) - self.pre_layernorm = nn.LayerNorm(args.hidden_size, eps=args.layer_norm_eps) - self.rotary_emb = VisionRotaryEmbedding(args) - self.layers = [VisionEncoderLayer(args) for _ in range(args.num_hidden_layers)] - self.merger = VisionMerger(args, text_hidden_size) - - def __call__(self, pixel_values: mx.array) -> mx.array: - C, H, W = pixel_values.shape - p, m = self.args.native_patch_size, self.args.adapter_merge_size - if H % (p * m) or W % (p * m): - raise ValueError(f"Image size {H}x{W} is not a multiple of {p * m}.") - rows, cols = H // (p * m), W // (p * m) - patches = pixel_values.transpose(1, 2, 0).reshape(rows, m, p, cols, m, p, C) - # The merge blocks in raster order, then the patches of each block. - patches = patches.transpose(0, 3, 1, 4, 2, 5, 6).reshape(-1, p * p * C) - dtype = self.embeddings.patch_embedding.weight.dtype - hidden_states = self.embeddings(patches.astype(dtype), rows * m, cols * m) - hidden_states = self.pre_layernorm(hidden_states) - - row, col = _grid_positions(rows * m, cols * m, m) - zero = mx.zeros((1,), dtype=row.dtype) - cos, sin = self.rotary_emb( - mx.concatenate([zero, row + 1]), mx.concatenate([zero, col + 1]) - ) - for layer in self.layers: - hidden_states = layer(hidden_states, cos, sin) - patch_states = hidden_states[1:].reshape(rows * cols, -1) - return self.merger(patch_states) - - -def _splice_image_features( - inputs_embeds: mx.array, - input_ids: mx.array, - image_features: mx.array, - image_token_id: int, -) -> mx.array: - if image_features.shape[0] == 0: - return inputs_embeds - special_image_mask = input_ids == image_token_id - idx = mx.cumsum(special_image_mask.flatten()).reshape(special_image_mask.shape) - 1 - idx = mx.clip(idx, 0, image_features.shape[0] - 1) - rows = image_features[idx].astype(inputs_embeds.dtype) - return mx.where(special_image_mask[..., None], rows, inputs_embeds) - - -class Inkling2Model(nn.Module): - def __init__(self, args: ModelArgs): - super().__init__() - self.language_model = TextModel(args.text) - if args.vision is not None: - self.vision_tower = VisionModel(args.vision, args.text.hidden_size) - - # mlx_lm.utils pipelines model.model with these. - @property - def layers(self) -> list[DecoderLayer | None]: - return self.language_model.layers - - @property - def start_idx(self) -> int: - return self.language_model.start_idx - - @property - def end_idx(self) -> int | None: - return self.language_model.end_idx - - def pipeline(self, group, split=None) -> None: - self.language_model.pipeline(group, split) - - -class Model(nn.Module): - def __init__(self, args: ModelArgs): - super().__init__() - self.args = args - self.model_type = args.model_type - self.model = Inkling2Model(args) - text = args.text - self.lm_head = nn.Linear(text.hidden_size, text.vocab_size, bias=False) - self.sharding_group = None - - def encode_image(self, pixel_values: mx.array | list[mx.array]) -> mx.array: - """pixel_values: one image (num_channels, H, W) or a list of images of - any size. Returns the rows of the image tokens of all images.""" - if isinstance(pixel_values, mx.array) and pixel_values.ndim == 3: - pixel_values = [pixel_values] - assert len(pixel_values), "No images." - return mx.concatenate([self.model.vision_tower(p) for p in pixel_values]) - - def embed_inputs( - self, - inputs: mx.array, - *, - pixel_values: mx.array | list[mx.array] | None = None, - ) -> mx.array: - inputs_embeds = self.model.language_model.embed(inputs) - if pixel_values is not None: - image_features = self.encode_image(pixel_values) - inputs_embeds = _splice_image_features( - inputs_embeds, inputs, image_features, self.args.image_token_id - ) - return inputs_embeds - - def __call__( - self, - inputs: mx.array, - cache: list[Any] | None = None, - input_embeddings: mx.array | None = None, - pixel_values: mx.array | list[mx.array] | None = None, - ) -> mx.array: - if pixel_values is not None: - assert input_embeddings is None, "Pass pixel_values or input_embeddings." - input_embeddings = self.embed_inputs(inputs, pixel_values=pixel_values) - hidden_states = self.model.language_model( - inputs, cache=cache, input_embeddings=input_embeddings - ) - logits = self.lm_head(hidden_states) - if self.sharding_group is not None: - logits = gather_last_axis(logits, self.sharding_group) - text = self.args.text - softcap = text.final_logit_softcapping - logits = logits.astype(mx.float32) - logits = mx.tanh(logits / softcap) * softcap - return logits[..., : text.unpadded_vocab_size] - - def sanitize(self, weights: dict[str, mx.array]) -> dict[str, mx.array]: - experts = re.compile(r"^(.+\.mlp\.experts)\.(w13|w2)_weight(\w*)$") - amax, denominator = {}, {} - sanitized = {} - for k, v in weights.items(): - if k.startswith(("model.llm.", "model.visual.")): - k = _rename(k) - if k.endswith("conv1d.weight"): - v = v.swapaxes(1, 2) - if k.startswith("model.vision_tower.") and self.args.vision is None: - continue - if k.endswith(".mlp.gate.weight"): - v = v.astype(mx.float32) - elif m := experts.match(k): - prefix, which, suffix = m.groups() - name = f"{prefix}.{'gate_up_proj' if which == 'w13' else 'down_proj'}" - if suffix == "_amax": - amax[name] = v - elif suffix == "_outer_scale_denominator": - denominator[name] = v - elif suffix == "_scale": - sanitized[f"{name}.scales"] = v - else: - sanitized[f"{name}.weight"] = v.view(mx.uint32) - continue - sanitized[k] = v - - # Pipeline stages can miss the files of the other layers. - for name in amax.keys() & denominator.keys(): - scale = _NVFP4_E2M1_MAX * _NVFP4_E4M3_MAX - scale = scale / denominator[name].astype(mx.float32) - sanitized[f"{name}.global_scale"] = amax[name].astype(mx.float32) * scale - - # mlx-lm does not read this quantization config, so set the experts here. - modes = {(4, 16): "nvfp4", (4, 32): "mxfp4", (8, 32): "mxfp8"} - quantized = [] - for path, module in self.named_modules(): - scales = sanitized.get(f"{path}.scales") - if not isinstance(module, SwitchLinear) or scales is None: - continue - if scales.dtype != mx.uint8: - continue - in_dims = module.weight.shape[-1] - group_size = in_dims // scales.shape[-1] - bits = sanitized[f"{path}.weight"].shape[-1] * 32 // in_dims - if (bits, group_size) not in modes: - continue - ql = module.to_quantized( - group_size, - bits, - mode=modes[bits, group_size], - global_scale=f"{path}.global_scale" in sanitized, - ) - quantized.append((path, ql)) - if quantized: - self.update_modules(tree_unflatten(quantized)) - return sanitized - - def shard(self, group: mx.distributed.Group | None = None) -> None: - group = group or mx.distributed.init() - N, r = group.size(), group.rank() - text = self.args.text - for n_kv_heads in (text.num_key_value_heads, text.swa_num_key_value_heads): - assert ( - n_kv_heads % N == 0 - ), f"group size {N} must divide num_key_value_heads {n_kv_heads}" - assert ( - text.vocab_size % N == 0 - ), f"group size {N} must divide vocab_size {text.vocab_size}" - - def part(w: mx.array, axis: int) -> mx.array: - return mx.contiguous(mx.split(w, N, axis=axis)[r]) - - self.lm_head = shard_linear(self.lm_head, "all-to-sharded", group=group) - self.sharding_group = group - for layer in self.layers: - attn = layer.self_attn - for name in ( - "q_proj", - "k_proj", - "v_proj", - "r_proj", - "gate_proj", - "sink_proj", - ): - proj = shard_linear(getattr(attn, name), "all-to-sharded", group=group) - setattr(attn, name, proj) - attn.o_proj = shard_linear(attn.o_proj, "sharded-to-all", group=group) - attn.q_l2_clip.scale = part(attn.q_l2_clip.scale, 0) - attn.rel_l2_clip.scale = part(attn.rel_l2_clip.scale, 0) - for conv in (attn.k_sconv, attn.v_sconv): - if isinstance(conv, ShortConvolution): - conv.conv1d.weight = part(conv.conv1d.weight, 0) - conv.conv1d.groups //= N - else: - conv.static_weight = part(conv.static_weight, 1) - conv.weight_proj = shard_linear( - conv.weight_proj, "all-to-sharded", group=group - ) - conv.num_heads //= N - attn.num_heads //= N - attn.num_key_value_heads //= N - - layer.mlp.sharding_group = group - experts = layer.mlp.experts - shard_experts_inplace(experts.gate_up_proj, "all-to-sharded", group) - shard_experts_inplace(experts.down_proj, "sharded-to-all", group) - - @property - def quant_predicate(self) -> Callable[[str, nn.Module], bool]: - - def predicate(path: str, module: nn.Module) -> bool: - return not path.startswith("model.vision_tower.") - - return predicate - - @property - def cast_predicate(self) -> Callable[[str], bool]: - - def predicate(k: str) -> bool: - return not k.endswith( - (".query", ".mlp.gate.weight", ".mlp.gate.e_score_correction_bias") - ) - - return predicate - - @property - def layers(self) -> list[DecoderLayer]: - return self.model.language_model.pipeline_layers - - def make_cache(self) -> list[CacheList]: - window = self.args.text.sliding_window_size - return [ - CacheList( - ( - RotatingKVCache(max_size=window) - if isinstance(layer, SlidingDecoderLayer) - else KVCache() - ), - ArraysCache(4), - ) - for layer in self.layers - ] diff --git a/mlx_lm/models/inkling2/__init__.py b/mlx_lm/models/inkling2/__init__.py new file mode 100644 index 000000000..2fdcd1673 --- /dev/null +++ b/mlx_lm/models/inkling2/__init__.py @@ -0,0 +1,14 @@ +# Copyright © 2026 Apple Inc. + +"""Inkling 2. + +https://huggingface.co/thinkingmachines/Inkling-2-Small +""" + +from mlx_lm.models.inkling2.config import ModelArgs +from mlx_lm.models.inkling2.model import Model + +__all__ = [ + "Model", + "ModelArgs", +] diff --git a/mlx_lm/models/inkling2/checkpoint.py b/mlx_lm/models/inkling2/checkpoint.py new file mode 100644 index 000000000..b2a9dd3dd --- /dev/null +++ b/mlx_lm/models/inkling2/checkpoint.py @@ -0,0 +1,121 @@ +# Copyright © 2026 Apple Inc. + +import re + +import mlx.core as mx +from mlx.utils import tree_unflatten + +from mlx_lm.layers.moe import SwitchLinear + +__all__ = [ + "sanitize", +] + + +_NVFP4_E2M1_MAX = 6.0 +_NVFP4_E4M3_MAX = 448.0 + +_RENAMES = [ + (r"^model\.llm\.unembed\.", "lm_head."), + (r"^model\.llm\.embed\.", "model.language_model.embed_tokens."), + (r"^model\.llm\.", "model.language_model."), + (r"\.attn_res\.mlp_queries\.(\d+)$", r".layers.\1.mlp_input.query"), + (r"\.attn_res\.output_query$", ".final_input.query"), + (r"\.attn\.wq_du\.", ".self_attn.q_proj."), + (r"\.attn\.wk_dv\.", ".self_attn.k_proj."), + (r"\.attn\.wv_dv\.", ".self_attn.v_proj."), + (r"\.attn\.wr_du\.", ".self_attn.r_proj."), + (r"\.attn\.wo_ud\.", ".self_attn.o_proj."), + (r"\.attn\.gate_attn\.", ".self_attn.gate_proj."), + (r"\.attn\.attn_sink_proj\.", ".self_attn.sink_proj."), + (r"\.attn\.", ".self_attn."), + (r"\.attn_sconv\.", ".post_attention_convolution."), + (r"\.mlp_sconv\.", ".post_mlp_convolution."), + (r"sconv\.weight$", "sconv.conv1d.weight"), + (r"convolution\.weight$", "convolution.conv1d.weight"), + (r"sconv\.static_w$", "sconv.static_weight"), + (r"sconv\.weight_proj$", "sconv.weight_proj.weight"), + (r"\.mlp_norm\.", ".post_attention_layernorm."), + (r"\.attn_norm\.", ".input_layernorm."), + (r"\.(q|k|v)_input_norm\.", r".\1_input_layernorm."), + (r"\.mlp\.gate\.bias$", ".mlp.gate.e_score_correction_bias"), + (r"^model\.visual\.backbone\.ln_pre\.", "model.vision_tower.pre_layernorm."), + (r"^model\.visual\.backbone\.", "model.vision_tower."), + (r"^model\.visual\.proj_in\.", "model.vision_tower.merger.linear_1."), + (r"^model\.visual\.proj_out\.", "model.vision_tower.merger.linear_2."), + (r"embeddings\.position_embedding$", "embeddings.position_embedding.weight"), + (r"(vision_tower\.layers\.\d+)\.ln_1\.", r"\1.layernorm_before."), + (r"(vision_tower\.layers\.\d+)\.ln_2\.", r"\1.layernorm_after."), + (r"(vision_tower\.layers\.\d+)\.mlp\.c_fc\.", r"\1.mlp.fc1."), + (r"(vision_tower\.layers\.\d+)\.mlp\.c_proj\.", r"\1.mlp.fc2."), + (r"(vision_tower\.layers\.\d+)\.ls_(\d)\.gamma$", r"\1.lambda_\2"), +] + + +def _rename(key: str) -> str: + if m := re.match(r"model\.llm\.attn_res\.attn_queries\.(\d+)$", key): + # Layer 0 has no attention input, so query i is for layer i + 1. + layer = int(m.group(1)) + 1 + return f"model.language_model.layers.{layer}.attention_input.query" + for pattern, replacement in _RENAMES: + key = re.sub(pattern, replacement, key) + return key + + +def sanitize(model, weights: dict[str, mx.array]) -> dict[str, mx.array]: + experts = re.compile(r"^(.+\.mlp\.experts)\.(w13|w2)_weight(\w*)$") + amax, denominator = {}, {} + sanitized = {} + for k, v in weights.items(): + if k.startswith(("model.llm.", "model.visual.")): + k = _rename(k) + if k.endswith("conv1d.weight"): + v = v.swapaxes(1, 2) + if k.startswith("model.vision_tower.") and model.args.vision is None: + continue + if k.endswith(".mlp.gate.weight"): + v = v.astype(mx.float32) + elif m := experts.match(k): + prefix, which, suffix = m.groups() + name = f"{prefix}.{'gate_up_proj' if which == 'w13' else 'down_proj'}" + if suffix == "_amax": + amax[name] = v + elif suffix == "_outer_scale_denominator": + denominator[name] = v + elif suffix == "_scale": + sanitized[f"{name}.scales"] = v + else: + sanitized[f"{name}.weight"] = v.view(mx.uint32) + continue + sanitized[k] = v + + # Pipeline stages can miss the files of the other layers. + for name in amax.keys() & denominator.keys(): + scale = _NVFP4_E2M1_MAX * _NVFP4_E4M3_MAX + scale = scale / denominator[name].astype(mx.float32) + sanitized[f"{name}.global_scale"] = amax[name].astype(mx.float32) * scale + + # mlx-lm does not read this quantization config, so set the experts here. + modes = {(4, 16): "nvfp4", (4, 32): "mxfp4", (8, 32): "mxfp8"} + quantized = [] + for path, module in model.named_modules(): + scales = sanitized.get(f"{path}.scales") + if not isinstance(module, SwitchLinear) or scales is None: + continue + if scales.dtype != mx.uint8: + continue + in_dims = module.weight.shape[-1] + group_size = in_dims // scales.shape[-1] + bits = sanitized[f"{path}.weight"].shape[-1] * 32 // in_dims + if (bits, group_size) not in modes: + continue + ql = module.to_quantized( + group_size, + bits, + mode=modes[bits, group_size], + global_scale=f"{path}.global_scale" in sanitized, + ) + quantized.append((path, ql)) + if quantized: + model.update_modules(tree_unflatten(quantized)) + return sanitized diff --git a/mlx_lm/models/inkling2/config.py b/mlx_lm/models/inkling2/config.py new file mode 100644 index 000000000..847906827 --- /dev/null +++ b/mlx_lm/models/inkling2/config.py @@ -0,0 +1,77 @@ +# Copyright © 2026 Apple Inc. + +from dataclasses import dataclass + +from mlx_lm.models.base import BaseModelArgs + +__all__ = [ + "ModelArgs", + "TextArgs", + "VisionArgs", +] + + +@dataclass +class TextArgs(BaseModelArgs): + hidden_size: int + num_hidden_layers: int + vocab_size: int + unpadded_vocab_size: int + num_attention_heads: int + num_key_value_heads: int + head_dim: int + swa_num_attention_heads: int + swa_num_key_value_heads: int + swa_head_dim: int + sliding_window_size: int + local_layer_ids: list[int] + d_rel: int + rel_extent: int + log_scaling_n_floor: int + log_scaling_alpha: float + rms_norm_eps: float + qk_l2_clip_threshold: float + rel_l2_clip_threshold: float + sconv_kernel_size: int + n_layers_per_attn_res_block: int + n_routed_experts: int + num_experts_per_tok: int + intermediate_size: int + mlp_gate_softcap: float + mlp_up_softcap: float + route_scale: float + final_logit_softcapping: float + + +@dataclass +class VisionArgs(BaseModelArgs): + hidden_size: int = 1024 + num_hidden_layers: int = 23 + num_attention_heads: int = 16 + num_channels: int = 3 + native_patch_size: int = 20 + adapter_merge_size: int = 2 + posemb_grid_size: int = 32 + projection_hidden_dim: int = 4096 + projector_bias: bool = False + mlp_ratio: float = 4.0 + layer_norm_eps: float = 1e-5 + rope_theta: float = 10000.0 + + def __post_init__(self): + self.head_dim = self.hidden_size // self.num_attention_heads + self.intermediate_size = int(self.hidden_size * self.mlp_ratio) + + +@dataclass +class ModelArgs(BaseModelArgs): + model_type: str + text_config: dict + vision_config: dict | None = None + image_token_id: int = 200054 + + def __post_init__(self): + self.text = TextArgs.from_dict(self.text_config) + self.vision = None + if self.vision_config: + self.vision = VisionArgs.from_dict(self.vision_config) diff --git a/mlx_lm/kernels/relative_attention.py b/mlx_lm/models/inkling2/kernels.py similarity index 69% rename from mlx_lm/kernels/relative_attention.py rename to mlx_lm/models/inkling2/kernels.py index e2e6afecd..6279769ae 100644 --- a/mlx_lm/kernels/relative_attention.py +++ b/mlx_lm/models/inkling2/kernels.py @@ -1,19 +1,127 @@ # Copyright © 2026 Apple Inc. -"""Causal flash attention with a relative position bias and a sink logit per -query.""" - import mlx.core as mx -from ._common import scalar +from mlx_lm.kernels.common import row_threads, scalar + +__all__ = [ + "depth_attention", + "relative_attention", +] + + +# Attention of learned queries over the depth sources of each token, in one +# kernel. +_DEPTH_ATTENTION_SOURCE = """ + constexpr int N = K + 1; + uint row = threadgroup_position_in_grid.x; + uint rows = threadgroups_per_grid.x; + uint tid = thread_position_in_threadgroup.x; + uint lane = thread_index_in_simdgroup; + uint sg = simdgroup_index_in_threadgroup; + + float acc[N * Q]; + for (int i = 0; i < N * Q; i++) { + acc[i] = 0.0f; + } + for (int d = tid; d < D; d += TG) { + float x[N]; + for (int i = 0; i < K; i++) { + x[i] = blocks[(size_t(i) * rows + row) * D + d]; + } + x[K] = partial[size_t(row) * D + d]; + for (int j = 0; j < Q; j++) { + float qv = queries[j * D + d]; + for (int i = 0; i < N; i++) { + acc[i * Q + j] += x[i] * qv; + } + } + } + + threadgroup float buf[N * Q][TG / 32]; + for (int i = 0; i < N * Q; i++) { + float v = simd_sum(acc[i]); + if (lane == 0) { + buf[i][sg] = v; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + float w[N * Q]; + for (int i = 0; i < N * Q; i++) { + float t = 0.0f; + for (int s = 0; s < TG / 32; s++) { + t += buf[i][s]; + } + w[i] = t * scale; + } + for (int j = 0; j < Q; j++) { + float m = -INFINITY; + for (int i = 0; i < N; i++) { + m = max(m, w[i * Q + j]); + } + float z = 0.0f; + for (int i = 0; i < N; i++) { + w[i * Q + j] = metal::exp(w[i * Q + j] - m); + z += w[i * Q + j]; + } + for (int i = 0; i < N; i++) { + w[i * Q + j] /= z; + } + } + + for (int d = tid; d < D; d += TG) { + float x[N]; + for (int i = 0; i < K; i++) { + x[i] = blocks[(size_t(i) * rows + row) * D + d]; + } + x[K] = partial[size_t(row) * D + d]; + for (int j = 0; j < Q; j++) { + float o = 0.0f; + for (int i = 0; i < N; i++) { + o += w[i * Q + j] * x[i]; + } + out[(size_t(row) * Q + j) * D + d] = o; + } + } +""" + +_depth_attention_kernel = mx.fast.metal_kernel( + name="depth_attention", + input_names=["blocks", "partial", "queries", "scale"], + output_names=["out"], + source=_DEPTH_ATTENTION_SOURCE, +) + + +def depth_attention( + blocks: mx.array, partial: mx.array, queries: mx.array, *, scale: float +) -> mx.array: + """blocks: (K, ..., D) and partial: (..., D), float32, also the values. + queries: float32 (Q, D). Returns (..., Q, D).""" + D = partial.shape[-1] + Q = queries.shape[0] + TG = row_threads(D) + return _depth_attention_kernel( + inputs=[blocks, partial, queries, scalar(scale)], + template=[("K", blocks.shape[0]), ("D", D), ("Q", Q), ("TG", TG)], + grid=(partial.size // D * TG, 1, 1), + threadgroup=(TG, 1, 1), + output_shapes=[partial.shape[:-1] + (Q, D)], + output_dtypes=[mx.float32], + )[0] + + +# Causal flash attention with a relative position bias and a sink logit per +# query. # Queries per threadgroup, 8 for each of its 4 simdgroups. _BQ = 32 + _TG = 128 # The online softmax of each row starts from its sink logit, so the zero-value # sink needs no key. -_SOURCE = """ +_RELATIVE_ATTENTION_SOURCE = """ constexpr float LOG2E = 1.4426950408889634f; constexpr int BK = 16; constexpr int LDK = BK + 8; @@ -160,11 +268,11 @@ } """ -_kernel = mx.fast.metal_kernel( +_relative_attention_kernel = mx.fast.metal_kernel( name="relative_attention", input_names=["q", "k", "v", "rel", "sinks", "key_start", "sizes", "scale"], output_names=["out"], - source=_SOURCE, + source=_RELATIVE_ATTENTION_SOURCE, ensure_row_contiguous=False, ) @@ -186,7 +294,7 @@ def relative_attention( (B, L, Hq, D).""" B, Hq, L, D = q.shape Hkv, S = k.shape[1], k.shape[2] - return _kernel( + return _relative_attention_kernel( inputs=[ q, k, diff --git a/mlx_lm/models/inkling2/layers.py b/mlx_lm/models/inkling2/layers.py new file mode 100644 index 000000000..3eeab0755 --- /dev/null +++ b/mlx_lm/models/inkling2/layers.py @@ -0,0 +1,669 @@ +# Copyright © 2026 Apple Inc. + +import math +from functools import partial +from typing import Any + +import mlx.core as mx +from mlx import nn +from mlx.nn.layers.distributed import sum_gradients + +from mlx_lm.kernels.expert_routing import expert_routing +from mlx_lm.layers.moe import SwitchLinear, _gather_sort, _scatter_unsort +from mlx_lm.models.cache import BatchRotatingKVCache, RotatingKVCache +from mlx_lm.models.inkling2.config import TextArgs +from mlx_lm.models.inkling2.kernels import depth_attention, relative_attention + +__all__ = [ + "Attention", + "BlockAttentionResidual", + "DecoderLayer", + "DynamicShortConvolution", + "Experts", + "FullAttention", + "FullDecoderLayer", + "L2Clip", + "RelativeLogits", + "ScaledL2Clip", + "ShortConvolution", + "SlidingAttention", + "SlidingDecoderLayer", + "SoftcappedSwiGLU", + "SparseMoeBlock", + "TopKRouter", + "unweighted_rms_norm", +] + + +_ROUTER_SCORE_EPS = 1e-20 + + +def _use_kernels() -> bool: + return mx.default_device() == mx.gpu and mx.metal.is_available() + + +def unweighted_rms_norm(x: mx.array, eps: float = 1e-6) -> mx.array: + return mx.fast.rms_norm(x, None, eps) + + +@partial(mx.compile, shapeless=True) +def _l2_clip(hidden_states: mx.array, scale: mx.array, threshold: float) -> mx.array: + states = hidden_states.astype(mx.float32) * scale + norm = mx.sqrt((states * states).sum(axis=-1, keepdims=True)) + scaled = states * mx.minimum(threshold / (norm + 1e-6), 1.0) + return scaled.astype(hidden_states.dtype) + + +@partial(mx.compile, shapeless=True) +def _softcapped_swiglu( + gate: mx.array, up: mx.array, gate_softcap: float, up_softcap: float +) -> mx.array: + input_dtype = gate.dtype + gate, up = gate.astype(mx.float32), up.astype(mx.float32) + gate_capped = mx.tanh(gate / gate_softcap) * gate_softcap + up_capped = mx.tanh(up / up_softcap) * up_softcap + return (gate_capped * mx.sigmoid(gate) * up_capped).astype(input_dtype) + + +class L2Clip(nn.Module): + def __init__(self, threshold: float): + super().__init__() + self.threshold = threshold + + def __call__(self, hidden_states: mx.array) -> mx.array: + return _l2_clip(hidden_states, 1.0, self.threshold) + + +class ScaledL2Clip(nn.Module): + def __init__(self, num_heads: int, head_dim: int, threshold: float): + super().__init__() + self.threshold = threshold + self.scale = mx.ones((num_heads, head_dim)) + + def __call__(self, hidden_states: mx.array) -> mx.array: + return _l2_clip(hidden_states, self.scale, self.threshold) + + +class RelativeLogits(nn.Module): + def __init__(self, d_rel: int, rel_extent: int): + super().__init__() + self.proj = mx.zeros((d_rel, rel_extent)) + + def __call__(self, relative_states: mx.array) -> mx.array: + return relative_states @ self.proj.astype(relative_states.dtype) + + +def _conv_input( + hidden_states: mx.array, + conv_state: mx.array | None, + conv_mask: mx.array | None, + kernel_size: int, +) -> mx.array: + hidden_states = hidden_states.astype(mx.float32) + if conv_mask is not None: + hidden_states = mx.where(conv_mask[..., None], hidden_states, 0) + if conv_state is None: + shape = (hidden_states.shape[0], kernel_size - 1, hidden_states.shape[-1]) + conv_state = mx.zeros(shape, mx.float32) + return mx.concatenate([conv_state, hidden_states], axis=1) + + +def _conv_state(window: mx.array, lengths: mx.array | None, n: int) -> mx.array: + if lengths is None: + pos = mx.arange(window.shape[1] - n, window.shape[1])[None, :, None] + else: + ends = mx.clip(lengths, 0, window.shape[1] - n) + pos = (ends[:, None] + mx.arange(n))[..., None] + # A gather copies, so the state does not keep the input in memory. + return mx.take_along_axis(window, pos, axis=1) + + +class ShortConvolution(nn.Module): + def __init__(self, dims: int, kernel_size: int): + super().__init__() + self.kernel_size = kernel_size + self.conv1d = nn.Conv1d(dims, dims, kernel_size, groups=dims, bias=False) + + def __call__( + self, + hidden_states: mx.array, + conv_state: mx.array | None, + conv_mask: mx.array | None, + ) -> tuple[mx.array, mx.array]: + K = self.kernel_size + residual = hidden_states.astype(mx.float32) + window = _conv_input(hidden_states, conv_state, conv_mask, K) + # As the reference, the conv runs in the weight dtype. + out = self.conv1d(window.astype(self.conv1d.weight.dtype)) + out = (out.astype(mx.float32) + residual) / math.sqrt(K + 1) + return out.astype(hidden_states.dtype), window + + +class DynamicShortConvolution(nn.Module): + def __init__(self, dims: int, input_dims: int, num_heads: int, kernel_size: int): + super().__init__() + self.kernel_size = kernel_size + self.num_heads = num_heads + self.static_weight = mx.zeros((kernel_size, dims)) + self.weight_proj = nn.Linear(input_dims, num_heads * kernel_size, bias=False) + + def __call__( + self, + hidden_states: mx.array, + dynamic_input: mx.array, + conv_state: mx.array | None, + conv_mask: mx.array | None, + ) -> tuple[mx.array, mx.array]: + B, L, C = hidden_states.shape + K, H = self.kernel_size, self.num_heads + dynamic_weights = self.weight_proj(dynamic_input).astype(mx.float32) + dynamic_weights = dynamic_weights.reshape(B, L, H, 1, K) + static_weights = self.static_weight.astype(mx.float32).T.reshape(H, -1, K) + weights = static_weights + dynamic_weights + + window = _conv_input(hidden_states, conv_state, conv_mask, K) + windows = mx.stack( + [window[:, K - 1 - lag : K - 1 - lag + L] for lag in range(K)], axis=-1 + ) + windows = windows.reshape(B, L, H, -1, K) + out = (windows * weights).sum(axis=-1).reshape(B, L, C) + out = (out + hidden_states.astype(mx.float32)) / math.sqrt(2 * K + 1) + return out.astype(hidden_states.dtype), window + + +def _positions(offset, length: int) -> mx.array: + pos = mx.arange(length) + if isinstance(offset, mx.array): + return offset[:, None] + pos + return pos + offset + + +def _key_positions(cache: Any, num_keys: int, num_queries: int, end) -> mx.array: + k = mx.arange(num_keys) + if num_queries == 1 and isinstance(cache, (RotatingKVCache, BatchRotatingKVCache)): + # A decode step writes in place, so the keys can be rotated. + k = (k - cache._idx) % num_keys + if isinstance(end, mx.array): + return (end - num_keys)[:, None] + k + return k + (end - num_keys) + + +def _attention_reference( + query: mx.array, + key: mx.array, + value: mx.array, + position_bias: mx.array, + sinks: mx.array, + *, + scale: float, + window: int, + query_positions: mx.array, + key_positions: mx.array, +) -> mx.array: + B, Hq, L, D = query.shape + Hkv, S = key.shape[1], key.shape[2] + R = position_bias.shape[-1] + distance = query_positions[..., :, None] - key_positions[..., None, :] + visible = (distance >= 0) & (key_positions[..., None, :] >= 0) + if window: + visible = visible & (distance < window) + if distance.ndim == 3: + distance, visible = distance[:, None], visible[:, None] + bias = mx.take_along_axis( + position_bias.transpose(0, 2, 1, 3), + mx.broadcast_to(mx.clip(distance, 0, R - 1), (B, Hq, L, S)), + axis=-1, + ) + bias = mx.where(distance < R, bias.astype(mx.float32), 0.0) + attention_mask = mx.where(visible, bias, -mx.inf).reshape(B, Hkv, -1, L, S) + + query = query.astype(mx.float32).reshape(B, Hkv, -1, L, D) + key = key.astype(mx.float32)[:, :, None] + attn_weights = (query @ key.swapaxes(-1, -2)) * scale + attention_mask + sinks = sinks.astype(mx.float32).transpose(0, 2, 1).reshape(B, Hkv, -1, L, 1) + combined_logits = mx.concatenate([attn_weights, sinks], axis=-1) + attn_weights = mx.softmax(combined_logits, axis=-1)[..., :S] + attn_output = attn_weights.astype(value.dtype) @ value[:, :, None] + return attn_output.reshape(B, Hq, L, D).transpose(0, 2, 1, 3) + + +class Attention(nn.Module): + def __init__(self, args: TextArgs, *, sliding: bool): + super().__init__() + if sliding: + self.num_heads = args.swa_num_attention_heads + self.num_key_value_heads = args.swa_num_key_value_heads + self.head_dim = args.swa_head_dim + self.sliding_window = args.sliding_window_size + rel_extent = args.sliding_window_size + else: + self.num_heads = args.num_attention_heads + self.num_key_value_heads = args.num_key_value_heads + self.head_dim = args.head_dim + self.sliding_window = 0 + rel_extent = args.rel_extent + self.scaling = self.head_dim**-0.5 + + dim = args.hidden_size + q_dim = self.num_heads * self.head_dim + kv_dim = self.num_key_value_heads * self.head_dim + self.q_proj = nn.Linear(dim, q_dim, bias=False) + self.k_proj = nn.Linear(dim, kv_dim, bias=False) + self.v_proj = nn.Linear(dim, kv_dim, bias=False) + self.r_proj = nn.Linear(dim, self.num_heads * args.d_rel, bias=False) + self.o_proj = nn.Linear(q_dim, dim, bias=False) + self.gate_proj = nn.Linear(dim, q_dim, bias=False) + self.sink_proj = nn.Linear(dim, self.num_heads, bias=False) + self.rel_logits_proj = RelativeLogits(args.d_rel, rel_extent) + self.q_l2_clip = ScaledL2Clip( + self.num_heads, self.head_dim, args.qk_l2_clip_threshold + ) + self.k_l2_clip = L2Clip(args.qk_l2_clip_threshold) + self.rel_l2_clip = ScaledL2Clip( + self.num_heads, args.d_rel, args.rel_l2_clip_threshold + ) + self.eps = args.rms_norm_eps + + def _attend( + self, + hidden_states: mx.array, + query_states: mx.array, + key_states: mx.array, + value_states: mx.array, + relative_states: mx.array, + cache: Any | None, + tau: mx.array | None = None, + ) -> mx.array: + B, L, _ = hidden_states.shape + gate = self.gate_proj(hidden_states) + sinks = self.sink_proj(hidden_states) + + query_states = query_states.reshape(B, L, self.num_heads, -1) + key_states = key_states.reshape(B, L, self.num_key_value_heads, -1) + value_states = value_states.reshape(B, L, self.num_key_value_heads, -1) + relative_states = relative_states.reshape(B, L, self.num_heads, -1) + query_states = self.q_l2_clip(query_states) + key_states = self.k_l2_clip(key_states) + value_states = unweighted_rms_norm( + value_states.astype(mx.float32), self.eps + ).astype(value_states.dtype) + relative_states = self.rel_l2_clip(relative_states) + if tau is not None: + query_states = (query_states.astype(mx.float32) * tau).astype( + query_states.dtype + ) + relative_states = (relative_states.astype(mx.float32) * tau).astype( + relative_states.dtype + ) + position_bias = self.rel_logits_proj(relative_states) + + query_states = query_states.transpose(0, 2, 1, 3) + key_states = key_states.transpose(0, 2, 1, 3) + value_states = value_states.transpose(0, 2, 1, 3) + if cache is not None: + key_states, value_states = cache.update_and_fetch(key_states, value_states) + attn_output = self._attention( + query_states, key_states, value_states, position_bias, sinks, cache + ) + + attn_output = attn_output.reshape(B, L, -1).astype(mx.float32) + attn_output = attn_output * mx.sigmoid(gate.astype(mx.float32)) + return self.o_proj(attn_output.astype(gate.dtype)) + + def _attention(self, query, key, value, position_bias, sinks, cache) -> mx.array: + B, _, L, _ = query.shape + S = key.shape[2] + end = cache.offset if cache is not None else L + bf16 = query.dtype == key.dtype == value.dtype == mx.bfloat16 + if L > 1 and _use_kernels() and bf16: + key_start = mx.broadcast_to(S - end, (B,)) + return relative_attention( + query, + key, + value, + position_bias, + sinks, + scale=self.scaling, + window=self.sliding_window, + key_start=key_start, + ) + + query_positions = _positions(end - L, L) + key_positions = _key_positions(cache, S, L, end) + if L == 1 and B == 1: + # The fused attention takes the sinks of one row. + distance = query_positions.reshape(1) - key_positions.reshape(S) + R = position_bias.shape[-1] + bias = mx.take(position_bias[0, 0], mx.clip(distance, 0, R - 1), axis=-1) + bias = mx.where(distance < R, bias, mx.zeros_like(bias)) + visible = (distance >= 0) & (key_positions.reshape(S) >= 0) + if self.sliding_window: + visible = visible & (distance < self.sliding_window) + mask = mx.where(visible, bias, -mx.inf).astype(query.dtype) + attn_output = mx.fast.scaled_dot_product_attention( + query, + key, + value, + scale=self.scaling, + mask=mask[None, :, None, :], + sinks=sinks[0, 0].astype(query.dtype), + ) + return attn_output.transpose(0, 2, 1, 3) + + return _attention_reference( + query, + key, + value, + position_bias, + sinks, + scale=self.scaling, + window=self.sliding_window, + query_positions=query_positions, + key_positions=key_positions, + ) + + +class SlidingAttention(Attention): + def __init__(self, args: TextArgs): + super().__init__(args, sliding=True) + dims = self.num_key_value_heads * self.head_dim + self.k_sconv = ShortConvolution(dims, args.sconv_kernel_size) + self.v_sconv = ShortConvolution(dims, args.sconv_kernel_size) + + def __call__( + self, + hidden_states: mx.array, + *, + cache: Any | None, + conv_states: list, + conv_mask: mx.array | None, + ) -> mx.array: + kv_cache = cache[0] if cache is not None else None + key_states, conv_states[0] = self.k_sconv( + self.k_proj(hidden_states), conv_states[0], conv_mask + ) + value_states, conv_states[1] = self.v_sconv( + self.v_proj(hidden_states), conv_states[1], conv_mask + ) + return self._attend( + hidden_states, + self.q_proj(hidden_states), + key_states, + value_states, + self.r_proj(hidden_states), + kv_cache, + ) + + +class FullAttention(Attention): + def __init__(self, args: TextArgs): + super().__init__(args, sliding=False) + dims = self.num_key_value_heads * self.head_dim + conv_args = (args.hidden_size, self.num_key_value_heads, args.sconv_kernel_size) + self.k_sconv = DynamicShortConvolution(dims, *conv_args) + self.v_sconv = DynamicShortConvolution(dims, *conv_args) + self.log_scaling_n_floor = args.log_scaling_n_floor + self.log_scaling_alpha = args.log_scaling_alpha + + def __call__( + self, + hidden_states: mx.array, + key_hidden_states: mx.array, + value_hidden_states: mx.array, + *, + cache: Any | None, + conv_states: list, + conv_mask: mx.array | None, + ) -> mx.array: + kv_cache = cache[0] if cache is not None else None + key_states, conv_states[0] = self.k_sconv( + self.k_proj(key_hidden_states), + key_hidden_states, + conv_states[0], + conv_mask, + ) + value_states, conv_states[1] = self.v_sconv( + self.v_proj(value_hidden_states), + value_hidden_states, + conv_states[1], + conv_mask, + ) + + offset = kv_cache.offset if kv_cache is not None else 0 + position_ids = _positions(offset, hidden_states.shape[1]).astype(mx.float32) + tau = 1.0 + self.log_scaling_alpha * mx.log( + mx.maximum((position_ids + 1) / self.log_scaling_n_floor, 1.0) + ) + return self._attend( + hidden_states, + self.q_proj(hidden_states), + key_states, + value_states, + self.r_proj(hidden_states), + kv_cache, + tau=tau[..., None, None], + ) + + +class SoftcappedSwiGLU(nn.Module): + def __init__(self, args: TextArgs): + super().__init__() + self.gate_softcap = args.mlp_gate_softcap + self.up_softcap = args.mlp_up_softcap + + def __call__(self, gate: mx.array, up: mx.array) -> mx.array: + return _softcapped_swiglu(gate, up, self.gate_softcap, self.up_softcap) + + +class Experts(nn.Module): + def __init__(self, args: TextArgs): + super().__init__() + dims, hidden = args.hidden_size, args.intermediate_size + num_experts = args.n_routed_experts + # The rows alternate between gate and up, as in the checkpoint. + self.gate_up_proj = SwitchLinear(dims, 2 * hidden, num_experts, bias=False) + self.down_proj = SwitchLinear(hidden, dims, num_experts, bias=False) + self.act_fn = SoftcappedSwiGLU(args) + + def __call__(self, x: mx.array, indices: mx.array) -> mx.array: + x = mx.expand_dims(x, (-2, -3)) + indices = mx.stop_gradient(indices) + do_sort = indices.size >= 64 + idx, inv_order = indices, None + if do_sort: + x, idx, inv_order = _gather_sort(x, indices) + gate_up = self.gate_up_proj(x, idx, sorted_indices=do_sort) + x = self.act_fn(gate_up[..., 0::2], gate_up[..., 1::2]) + x = self.down_proj(x, idx, sorted_indices=do_sort) + if do_sort: + x = _scatter_unsort(x, inv_order, indices.shape) + return x.squeeze(-2) + + +class TopKRouter(nn.Module): + def __init__(self, args: TextArgs): + super().__init__() + self.top_k = args.num_experts_per_tok + self.routed_scaling_factor = args.route_scale + num_experts, dims = args.n_routed_experts, args.hidden_size + self.weight = mx.zeros((num_experts, dims), dtype=mx.float32) + self.e_score_correction_bias = mx.zeros((num_experts,), dtype=mx.float32) + + def __call__(self, hidden_states: mx.array) -> tuple[mx.array, mx.array]: + logits = hidden_states.astype(mx.float32) @ self.weight.T + if _use_kernels(): + return expert_routing( + logits, + self.e_score_correction_bias, + top_k=self.top_k, + multiplier=1.0, + score_eps=_ROUTER_SCORE_EPS, + route_scale=self.routed_scaling_factor, + ) + scores = mx.sigmoid(logits) + biased = scores + self.e_score_correction_bias + k = self.top_k + indices = mx.argpartition(-biased, kth=k - 1, axis=-1)[..., :k] + weights = mx.take_along_axis(scores, indices, axis=-1) + weights = weights / (weights.sum(axis=-1, keepdims=True) + _ROUTER_SCORE_EPS) + return indices, weights * self.routed_scaling_factor + + +class SparseMoeBlock(nn.Module): + def __init__(self, args: TextArgs): + super().__init__() + self.gate = TopKRouter(args) + self.experts = Experts(args) + self.sharding_group = None + + def __call__(self, hidden_states: mx.array) -> mx.array: + group = self.sharding_group + if group is not None: + hidden_states = sum_gradients(group)(hidden_states) + selected_experts, routing_weights = self.gate(hidden_states) + expert_states = self.experts(hidden_states, selected_experts) + expert_states = expert_states.astype(mx.float32) * routing_weights[..., None] + final_hidden_states = expert_states.sum(axis=-2) + if group is not None: + final_hidden_states = mx.distributed.all_sum( + final_hidden_states, group=group + ) + return final_hidden_states.astype(hidden_states.dtype) + + +class BlockAttentionResidual(nn.Module): + def __init__(self, dims: int, num_queries: int = 1): + super().__init__() + shape = (dims,) if num_queries == 1 else (num_queries, dims) + self.query = mx.zeros(shape, dtype=mx.float32) + + def __call__( + self, block_states: mx.array, partial_block_states: mx.array + ) -> mx.array: + dims = partial_block_states.shape[-1] + query = self.query.reshape(-1, dims).astype(mx.float32) + scale = dims**-0.5 + if _use_kernels(): + return depth_attention( + block_states, partial_block_states, query, scale=scale + ) + stacked_states = mx.concatenate([block_states, partial_block_states[None]]) + stacked_states = mx.moveaxis(stacked_states, 0, -2) + weights = mx.softmax((stacked_states @ query.T) * scale, axis=-2, precise=True) + return weights.swapaxes(-1, -2) @ stacked_states + + +class DecoderLayer(nn.Module): + def __init__(self, args: TextArgs, layer_idx: int, *, num_queries: int): + super().__init__() + dims = args.hidden_size + self.is_block_boundary = layer_idx % args.n_layers_per_attn_res_block == 0 + self.attention_input = ( + BlockAttentionResidual(dims, num_queries) if layer_idx > 0 else None + ) + self.mlp_input = BlockAttentionResidual(dims) + self.mlp = SparseMoeBlock(args) + self.post_attention_layernorm = nn.RMSNorm(dims, eps=args.rms_norm_eps) + kernel_size = args.sconv_kernel_size + self.post_attention_convolution = ShortConvolution(dims, kernel_size) + self.post_mlp_convolution = ShortConvolution(dims, kernel_size) + + def __call__( + self, + hidden_states: mx.array, + block_states: mx.array | None, + *, + cache: Any | None = None, + conv_mask: mx.array | None = None, + ) -> tuple[mx.array, mx.array]: + dtype = hidden_states.dtype + conv = cache[1] if cache is not None else None + conv_states = list(conv.cache) if conv is not None else [None] * 4 + block_residual = hidden_states + normed_residual = unweighted_rms_norm(block_residual.astype(mx.float32)) + + attention_inputs = None + if self.attention_input is not None: + attention_inputs = self.attention_input(block_states, normed_residual) + hidden_states = self._self_attention( + hidden_states, attention_inputs, cache, conv_states, conv_mask + ) + hidden_states, conv_states[2] = self.post_attention_convolution( + hidden_states, conv_states[2], conv_mask + ) + + residual = hidden_states = hidden_states.astype(mx.float32) + if self.is_block_boundary: + block = normed_residual[None] + if block_states is None: + block_states = block + else: + block_states = mx.concatenate([block_states, block]) + else: + residual = hidden_states = block_residual.astype(mx.float32) + hidden_states + + normed_states = unweighted_rms_norm(hidden_states) + hidden_states = self.mlp_input(block_states, normed_states)[..., 0, :] + hidden_states = self.mlp( + self.post_attention_layernorm(hidden_states).astype(dtype) + ) + hidden_states, conv_states[3] = self.post_mlp_convolution( + hidden_states, conv_states[3], conv_mask + ) + + if conv is not None: + n = self.post_mlp_convolution.kernel_size - 1 + for i, window in enumerate(conv_states): + conv[i] = _conv_state(window, conv.lengths, n) + conv.advance(block_residual.shape[1]) + hidden_states = residual + hidden_states.astype(mx.float32) + return hidden_states.astype(dtype), block_states + + +class SlidingDecoderLayer(DecoderLayer): + def __init__(self, args: TextArgs, layer_idx: int): + super().__init__(args, layer_idx, num_queries=1) + self.self_attn = SlidingAttention(args) + self.input_layernorm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps) + + def _self_attention( + self, hidden_states, attention_inputs, cache, conv_states, conv_mask + ): + dtype = hidden_states.dtype + if attention_inputs is not None: + hidden_states = attention_inputs[..., 0, :] + return self.self_attn( + self.input_layernorm(hidden_states).astype(dtype), + cache=cache, + conv_states=conv_states, + conv_mask=conv_mask, + ) + + +class FullDecoderLayer(DecoderLayer): + def __init__(self, args: TextArgs, layer_idx: int): + super().__init__(args, layer_idx, num_queries=3) + self.self_attn = FullAttention(args) + eps = args.rms_norm_eps + self.q_input_layernorm = nn.RMSNorm(args.hidden_size, eps=eps) + self.k_input_layernorm = nn.RMSNorm(args.hidden_size, eps=eps) + self.v_input_layernorm = nn.RMSNorm(args.hidden_size, eps=eps) + + def _self_attention( + self, hidden_states, attention_inputs, cache, conv_states, conv_mask + ): + dtype = hidden_states.dtype + if attention_inputs is None: + query_states = key_states = value_states = hidden_states + else: + query_states, key_states, value_states = ( + attention_inputs[..., i, :] for i in range(3) + ) + return self.self_attn( + self.q_input_layernorm(query_states).astype(dtype), + self.k_input_layernorm(key_states).astype(dtype), + self.v_input_layernorm(value_states).astype(dtype), + cache=cache, + conv_states=conv_states, + conv_mask=conv_mask, + ) diff --git a/mlx_lm/models/inkling2/model.py b/mlx_lm/models/inkling2/model.py new file mode 100644 index 000000000..10a4b4a8c --- /dev/null +++ b/mlx_lm/models/inkling2/model.py @@ -0,0 +1,273 @@ +# Copyright © 2026 Apple Inc. + +from typing import Any, Callable + +import mlx.core as mx +from mlx import nn +from mlx.nn.layers.distributed import shard_linear + +from mlx_lm.layers.common import splice +from mlx_lm.layers.distributed import PipelineMixin, gather_last_axis +from mlx_lm.models.cache import ArraysCache, CacheList, KVCache, RotatingKVCache +from mlx_lm.models.inkling2 import checkpoint +from mlx_lm.models.inkling2.config import ModelArgs, TextArgs +from mlx_lm.models.inkling2.layers import ( + BlockAttentionResidual, + DecoderLayer, + FullDecoderLayer, + ShortConvolution, + SlidingDecoderLayer, + unweighted_rms_norm, +) +from mlx_lm.models.inkling2.vision import VisionModel +from mlx_lm.models.muse_spark.model import shard_experts_inplace + +__all__ = [ + "Inkling2Model", + "Model", + "TextModel", +] + + +class TextModel(PipelineMixin, nn.Module): + def __init__(self, args: TextArgs): + super().__init__() + self.args = args + self.embed_tokens = nn.Embedding(args.vocab_size, args.hidden_size) + # Not in embed_tokens as in transformers, so that it can be quantized. + self.embed_norm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps) + self.layers = [ + ( + SlidingDecoderLayer(args, i) + if i in args.local_layer_ids + else FullDecoderLayer(args, i) + ) + for i in range(args.num_hidden_layers) + ] + self.final_input = BlockAttentionResidual(args.hidden_size) + self.norm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps) + + def embed(self, inputs: mx.array) -> mx.array: + return self.embed_norm(self.embed_tokens(inputs)) + + def __call__( + self, + inputs: mx.array, + cache: list[Any] | None = None, + input_embeddings: mx.array | None = None, + ) -> mx.array: + if input_embeddings is None: + input_embeddings = self.embed(inputs) + hidden_states = input_embeddings + dtype = hidden_states.dtype + + layers = self.pipeline_layers + if cache is None: + cache = [None] * len(layers) + conv_mask = None + if cache[0] is not None: + conv_mask = cache[0][1].make_mask(hidden_states.shape[1]) + + rank, size = self.pipeline_rank, self.pipeline_size + block_states = None + if rank < size - 1: + num_blocks = -(-self.start_idx // self.args.n_layers_per_attn_res_block) + states = mx.zeros((num_blocks + 1, *hidden_states.shape), mx.float32) + states = mx.distributed.recv_like(states, rank + 1) + hidden_states, block_states = states[0].astype(dtype), states[1:] + + for layer, c in zip(layers, cache): + hidden_states, block_states = layer( + hidden_states, block_states, cache=c, conv_mask=conv_mask + ) + + if rank != 0: + states = mx.concatenate( + [hidden_states.astype(mx.float32)[None], block_states] + ) + states = mx.distributed.send(states, (rank - 1) % size) + if cache[-1] is not None: + kv_cache = cache[-1][0] + kv_cache.keys = mx.depends(kv_cache.keys, states) + # Only the output of rank 0 is used. + hidden_states = states[0].astype(dtype) + else: + normed_states = unweighted_rms_norm(hidden_states.astype(mx.float32)) + hidden_states = self.final_input(block_states, normed_states)[..., 0, :] + hidden_states = self.norm(hidden_states).astype(dtype) + + if size > 1: + batch = hidden_states.shape[0] + hidden_states = mx.distributed.all_gather(hidden_states)[:batch] + return hidden_states + + +class Inkling2Model(nn.Module): + def __init__(self, args: ModelArgs): + super().__init__() + self.language_model = TextModel(args.text) + if args.vision is not None: + self.vision_tower = VisionModel(args.vision, args.text.hidden_size) + + # mlx_lm.utils pipelines model.model with these. + @property + def layers(self) -> list[DecoderLayer | None]: + return self.language_model.layers + + @property + def start_idx(self) -> int: + return self.language_model.start_idx + + @property + def end_idx(self) -> int | None: + return self.language_model.end_idx + + def pipeline(self, group, split=None) -> None: + self.language_model.pipeline(group, split) + + +class Model(nn.Module): + def __init__(self, args: ModelArgs): + super().__init__() + self.args = args + self.model_type = args.model_type + self.model = Inkling2Model(args) + text = args.text + self.lm_head = nn.Linear(text.hidden_size, text.vocab_size, bias=False) + self.sharding_group = None + + def encode_image(self, pixel_values: mx.array | list[mx.array]) -> mx.array: + """pixel_values: one image (num_channels, H, W) or a list of images of + any size. Returns the rows of the image tokens of all images.""" + if isinstance(pixel_values, mx.array) and pixel_values.ndim == 3: + pixel_values = [pixel_values] + assert len(pixel_values), "No images." + return mx.concatenate([self.model.vision_tower(p) for p in pixel_values]) + + def embed_inputs( + self, + inputs: mx.array, + *, + pixel_values: mx.array | list[mx.array] | None = None, + ) -> mx.array: + inputs_embeds = self.model.language_model.embed(inputs) + if pixel_values is not None: + image_features = self.encode_image(pixel_values) + inputs_embeds = splice( + inputs_embeds, + inputs, + rows=image_features, + token_id=self.args.image_token_id, + ) + return inputs_embeds + + def __call__( + self, + inputs: mx.array, + cache: list[Any] | None = None, + input_embeddings: mx.array | None = None, + pixel_values: mx.array | list[mx.array] | None = None, + ) -> mx.array: + if pixel_values is not None: + assert input_embeddings is None, "Pass pixel_values or input_embeddings." + input_embeddings = self.embed_inputs(inputs, pixel_values=pixel_values) + hidden_states = self.model.language_model( + inputs, cache=cache, input_embeddings=input_embeddings + ) + logits = self.lm_head(hidden_states) + if self.sharding_group is not None: + logits = gather_last_axis(logits, self.sharding_group) + text = self.args.text + softcap = text.final_logit_softcapping + logits = logits.astype(mx.float32) + logits = mx.tanh(logits / softcap) * softcap + return logits[..., : text.unpadded_vocab_size] + + def sanitize(self, weights: dict[str, mx.array]) -> dict[str, mx.array]: + return checkpoint.sanitize(self, weights) + + def shard(self, group: mx.distributed.Group | None = None) -> None: + group = group or mx.distributed.init() + N, r = group.size(), group.rank() + text = self.args.text + for n_kv_heads in (text.num_key_value_heads, text.swa_num_key_value_heads): + assert ( + n_kv_heads % N == 0 + ), f"group size {N} must divide num_key_value_heads {n_kv_heads}" + assert ( + text.vocab_size % N == 0 + ), f"group size {N} must divide vocab_size {text.vocab_size}" + + def part(w: mx.array, axis: int) -> mx.array: + return mx.contiguous(mx.split(w, N, axis=axis)[r]) + + self.lm_head = shard_linear(self.lm_head, "all-to-sharded", group=group) + self.sharding_group = group + for layer in self.layers: + attn = layer.self_attn + for name in ( + "q_proj", + "k_proj", + "v_proj", + "r_proj", + "gate_proj", + "sink_proj", + ): + proj = shard_linear(getattr(attn, name), "all-to-sharded", group=group) + setattr(attn, name, proj) + attn.o_proj = shard_linear(attn.o_proj, "sharded-to-all", group=group) + attn.q_l2_clip.scale = part(attn.q_l2_clip.scale, 0) + attn.rel_l2_clip.scale = part(attn.rel_l2_clip.scale, 0) + for conv in (attn.k_sconv, attn.v_sconv): + if isinstance(conv, ShortConvolution): + conv.conv1d.weight = part(conv.conv1d.weight, 0) + conv.conv1d.groups //= N + else: + conv.static_weight = part(conv.static_weight, 1) + conv.weight_proj = shard_linear( + conv.weight_proj, "all-to-sharded", group=group + ) + conv.num_heads //= N + attn.num_heads //= N + attn.num_key_value_heads //= N + + layer.mlp.sharding_group = group + experts = layer.mlp.experts + shard_experts_inplace(experts.gate_up_proj, "all-to-sharded", group) + shard_experts_inplace(experts.down_proj, "sharded-to-all", group) + + @property + def quant_predicate(self) -> Callable[[str, nn.Module], bool]: + + def predicate(path: str, module: nn.Module) -> bool: + return not path.startswith("model.vision_tower.") + + return predicate + + @property + def cast_predicate(self) -> Callable[[str], bool]: + + def predicate(k: str) -> bool: + return not k.endswith( + (".query", ".mlp.gate.weight", ".mlp.gate.e_score_correction_bias") + ) + + return predicate + + @property + def layers(self) -> list[DecoderLayer]: + return self.model.language_model.pipeline_layers + + def make_cache(self) -> list[CacheList]: + window = self.args.text.sliding_window_size + return [ + CacheList( + ( + RotatingKVCache(max_size=window) + if isinstance(layer, SlidingDecoderLayer) + else KVCache() + ), + ArraysCache(4), + ) + for layer in self.layers + ] diff --git a/mlx_lm/processors/inkling2.py b/mlx_lm/models/inkling2/processor.py similarity index 94% rename from mlx_lm/processors/inkling2.py rename to mlx_lm/models/inkling2/processor.py index f1f970548..b3db194ca 100644 --- a/mlx_lm/processors/inkling2.py +++ b/mlx_lm/models/inkling2/processor.py @@ -9,6 +9,11 @@ import mlx.core as mx import numpy as np +__all__ = [ + "IMAGE_TOKEN", + "Processor", +] + IMAGE_TOKEN = "<|unused_200054|>" @@ -67,7 +72,7 @@ def preprocess_image(self, image: np.ndarray) -> tuple[mx.array, int]: def __call__( self, text: str, *, images: Sequence[np.ndarray] - ) -> tuple[str, list[mx.array]]: + ) -> tuple[str, dict[str, list[mx.array]]]: parts = text.split(IMAGE_TOKEN) if len(parts) - 1 != len(images): raise ValueError( @@ -80,4 +85,4 @@ def __call__( pixels, num_tokens = self.preprocess_image(image) expanded += [IMAGE_TOKEN * num_tokens, part] pixel_values.append(pixels) - return "".join(expanded), pixel_values + return "".join(expanded), {"pixel_values": pixel_values} diff --git a/mlx_lm/models/inkling2/vision.py b/mlx_lm/models/inkling2/vision.py new file mode 100644 index 000000000..a4b4617a7 --- /dev/null +++ b/mlx_lm/models/inkling2/vision.py @@ -0,0 +1,204 @@ +# Copyright © 2026 Apple Inc. + +import mlx.core as mx +from mlx import nn + +from mlx_lm.models.inkling2.config import VisionArgs + +__all__ = [ + "VisionAttention", + "VisionEmbeddings", + "VisionEncoderLayer", + "VisionMLP", + "VisionMerger", + "VisionModel", + "VisionRotaryEmbedding", +] + + +def _precise_gelu(x: mx.array) -> mx.array: + return nn.gelu(x.astype(mx.float32)).astype(x.dtype) + + +def _grid_positions(grid_h: int, grid_w: int, merge: int) -> tuple[mx.array, mx.array]: + i = mx.arange(grid_h * grid_w) + blocks_w = grid_w // merge + row = i // (merge * merge * blocks_w) * merge + i // merge % merge + col = i // (merge * merge) % blocks_w * merge + i % merge + return row, col + + +def _bilinear_taps(index: mx.array, size: int, side: int) -> tuple[mx.array, mx.array]: + src = (index.astype(mx.float32) + 0.5) * side / size - 0.5 + taps = mx.floor(src)[:, None] + mx.arange(2) + weights = mx.maximum(1.0 - mx.abs(src[:, None] - taps), 0.0) + return mx.clip(taps, 0, side - 1).astype(mx.int32), weights + + +class VisionEmbeddings(nn.Module): + def __init__(self, args: VisionArgs): + super().__init__() + self.merge_size = args.adapter_merge_size + self.grid_size = args.posemb_grid_size + patch_dims = args.num_channels * args.native_patch_size**2 + self.patch_embedding = nn.Linear(patch_dims, args.hidden_size, bias=False) + self.position_embedding = nn.Embedding( + args.posemb_grid_size**2, args.hidden_size + ) + self.class_embedding = mx.zeros((args.hidden_size,)) + self.cls_position_embedding = mx.zeros((args.hidden_size,)) + + def __call__(self, pixel_values: mx.array, grid_h: int, grid_w: int) -> mx.array: + patch_embeddings = self.patch_embedding(pixel_values) + + side = self.grid_size + row, col = _grid_positions(grid_h, grid_w, self.merge_size) + row_taps, row_weights = _bilinear_taps(row, grid_h, side) + col_taps, col_weights = _bilinear_taps(col, grid_w, side) + interp_indices = row_taps[:, :, None] * side + col_taps[:, None, :] + interp_weights = row_weights[:, :, None] * col_weights[:, None, :] + position_embeddings = self.position_embedding(interp_indices.reshape(-1, 4)) + position_embeddings = position_embeddings.astype(mx.float32) + position_embeddings = position_embeddings * interp_weights.reshape(-1, 4, 1) + patch_embeddings = patch_embeddings + position_embeddings.sum(axis=1).astype( + patch_embeddings.dtype + ) + + cls_embedding = self.class_embedding + self.cls_position_embedding + cls_embedding = cls_embedding.astype(patch_embeddings.dtype) + return mx.concatenate([cls_embedding[None], patch_embeddings]) + + +class VisionRotaryEmbedding(nn.Module): + def __init__(self, args: VisionArgs): + super().__init__() + dims = args.head_dim // 2 + self._inv_freq = 1.0 / ( + args.rope_theta ** (mx.arange(0, dims, 2, dtype=mx.float32) / dims) + ) + + def __call__(self, row: mx.array, col: mx.array) -> tuple[mx.array, mx.array]: + freqs_h = row[:, None].astype(mx.float32) * self._inv_freq + freqs_w = col[:, None].astype(mx.float32) * self._inv_freq + freqs = mx.repeat(mx.concatenate([freqs_w, freqs_h], axis=-1), 2, axis=-1) + return mx.cos(freqs), mx.sin(freqs) + + +def _apply_rotary_pos_emb_vision( + hidden_states: mx.array, cos: mx.array, sin: mx.array +) -> mx.array: + states = hidden_states.astype(mx.float32) + pairs = states.reshape(*states.shape[:-1], -1, 2) + rotated = mx.stack([-pairs[..., 1], pairs[..., 0]], axis=-1).reshape(states.shape) + return (states * cos + rotated * sin).astype(hidden_states.dtype) + + +class VisionAttention(nn.Module): + def __init__(self, args: VisionArgs): + super().__init__() + dims = args.hidden_size + self.num_heads = args.num_attention_heads + self.scaling = args.head_dim**-0.5 + self.q_proj = nn.Linear(dims, dims) + self.k_proj = nn.Linear(dims, dims) + self.v_proj = nn.Linear(dims, dims) + self.out_proj = nn.Linear(dims, dims) + + def __call__( + self, hidden_states: mx.array, cos: mx.array, sin: mx.array + ) -> mx.array: + N = hidden_states.shape[0] + shape = (N, self.num_heads, -1) + cos, sin = cos[:, None], sin[:, None] + query_states = self.q_proj(hidden_states).reshape(shape) + key_states = self.k_proj(hidden_states).reshape(shape) + value_states = self.v_proj(hidden_states).reshape(shape) + query_states = _apply_rotary_pos_emb_vision(query_states, cos, sin) + key_states = _apply_rotary_pos_emb_vision(key_states, cos, sin) + query_states, key_states, value_states = ( + states.transpose(1, 0, 2)[None] + for states in (query_states, key_states, value_states) + ) + attn_output = mx.fast.scaled_dot_product_attention( + query_states, key_states, value_states, scale=self.scaling + ) + attn_output = attn_output[0].transpose(1, 0, 2).reshape(N, -1) + return self.out_proj(attn_output) + + +class VisionMLP(nn.Module): + def __init__(self, args: VisionArgs): + super().__init__() + self.fc1 = nn.Linear(args.hidden_size, args.intermediate_size) + self.fc2 = nn.Linear(args.intermediate_size, args.hidden_size) + + def __call__(self, hidden_states: mx.array) -> mx.array: + return self.fc2(_precise_gelu(self.fc1(hidden_states))) + + +class VisionEncoderLayer(nn.Module): + def __init__(self, args: VisionArgs): + super().__init__() + dims, eps = args.hidden_size, args.layer_norm_eps + self.self_attn = VisionAttention(args) + self.mlp = VisionMLP(args) + self.layernorm_before = nn.LayerNorm(dims, eps=eps) + self.layernorm_after = nn.LayerNorm(dims, eps=eps) + self.lambda_1 = mx.ones((dims,)) + self.lambda_2 = mx.ones((dims,)) + + def __call__( + self, hidden_states: mx.array, cos: mx.array, sin: mx.array + ) -> mx.array: + residual = hidden_states + hidden_states = self.self_attn(self.layernorm_before(hidden_states), cos, sin) + hidden_states = residual + self.lambda_1 * hidden_states + residual = hidden_states + hidden_states = self.mlp(self.layernorm_after(hidden_states)) + return residual + self.lambda_2 * hidden_states + + +class VisionMerger(nn.Module): + def __init__(self, args: VisionArgs, text_hidden_size: int): + super().__init__() + dims = args.adapter_merge_size**2 * args.hidden_size + hidden, bias = args.projection_hidden_dim, args.projector_bias + self.linear_1 = nn.Linear(dims, hidden, bias=bias) + self.linear_2 = nn.Linear(hidden, text_hidden_size, bias=bias) + + def __call__(self, image_features: mx.array) -> mx.array: + return self.linear_2(_precise_gelu(self.linear_1(image_features))) + + +class VisionModel(nn.Module): + def __init__(self, args: VisionArgs, text_hidden_size: int): + super().__init__() + self.args = args + self.embeddings = VisionEmbeddings(args) + self.pre_layernorm = nn.LayerNorm(args.hidden_size, eps=args.layer_norm_eps) + self.rotary_emb = VisionRotaryEmbedding(args) + self.layers = [VisionEncoderLayer(args) for _ in range(args.num_hidden_layers)] + self.merger = VisionMerger(args, text_hidden_size) + + def __call__(self, pixel_values: mx.array) -> mx.array: + C, H, W = pixel_values.shape + p, m = self.args.native_patch_size, self.args.adapter_merge_size + if H % (p * m) or W % (p * m): + raise ValueError(f"Image size {H}x{W} is not a multiple of {p * m}.") + rows, cols = H // (p * m), W // (p * m) + patches = pixel_values.transpose(1, 2, 0).reshape(rows, m, p, cols, m, p, C) + # The merge blocks in raster order, then the patches of each block. + patches = patches.transpose(0, 3, 1, 4, 2, 5, 6).reshape(-1, p * p * C) + dtype = self.embeddings.patch_embedding.weight.dtype + hidden_states = self.embeddings(patches.astype(dtype), rows * m, cols * m) + hidden_states = self.pre_layernorm(hidden_states) + + row, col = _grid_positions(rows * m, cols * m, m) + zero = mx.zeros((1,), dtype=row.dtype) + cos, sin = self.rotary_emb( + mx.concatenate([zero, row + 1]), mx.concatenate([zero, col + 1]) + ) + for layer in self.layers: + hidden_states = layer(hidden_states, cos, sin) + patch_states = hidden_states[1:].reshape(rows * cols, -1) + return self.merger(patch_states) diff --git a/tests/models/test_inkling2.py b/tests/models/test_inkling2.py index 417aec7aa..158badd76 100644 --- a/tests/models/test_inkling2.py +++ b/tests/models/test_inkling2.py @@ -12,7 +12,7 @@ from mlx_lm.generate import BatchGenerator, generate_step from mlx_lm.models import inkling2 -from mlx_lm.processors import inkling2 as inkling2_processor +from mlx_lm.models.inkling2 import processor as inkling2_processor from mlx_lm.processors import load_processor from mlx_lm.utils import load_model, quantize_model @@ -273,14 +273,14 @@ def test_processor(self): self.assertEqual(rgb[0, 8].tolist(), [0] * 3) token = inkling2_processor.IMAGE_TOKEN - text, pixel_values = processor(f"A {token} B", images=[image]) + text, media_inputs = processor(f"A {token} B", images=[image]) self.assertEqual(text, f"A {token * 4} B") - self.assertEqual(len(pixel_values), 1) + self.assertEqual(len(media_inputs["pixel_values"]), 1) with self.assertRaisesRegex(ValueError, "for 2 images"): processor(f"A {token}", images=[image, image]) config = {**CONFIG, "vision_config": VISION_CONFIG} - processor = load_processor(create_model(vision=True), config) + processor = load_processor(config) self.assertIsInstance(processor, inkling2_processor.Processor) self.assertEqual(processor.block_size, 4) diff --git a/tests/test_kernels.py b/tests/test_kernels.py index e07414889..eaa8faf59 100644 --- a/tests/test_kernels.py +++ b/tests/test_kernels.py @@ -7,10 +7,10 @@ import mlx.nn as nn from mlx_lm.kernels import sparse_mla -from mlx_lm.kernels.depth_attention import depth_attention from mlx_lm.kernels.expert_routing import expert_routing -from mlx_lm.kernels.relative_attention import relative_attention from mlx_lm.kernels.sparse_mla import sparse_mla_attention +from mlx_lm.models.inkling2.kernels import depth_attention, relative_attention +from mlx_lm.models.inkling2.layers import _attention_reference from mlx_lm.models.muse_spark.kernels import ( norm_add_norm, post_expert_norm_combine, @@ -19,7 +19,6 @@ qk_norm_rope, rms_norm_sigmoid_gate, ) -from mlx_lm.models.inkling2 import _attention_reference TOL = {mx.float32: 1e-5, mx.bfloat16: 1e-2} From bbb12c95c8db40ef58cd46356890c7af8b08f6bb Mon Sep 17 00:00:00 2001 From: jundot Date: Sun, 22 Nov 2026 13:28:00 +0100 Subject: [PATCH 5/5] Use the standard loader for Inkling 2 experts The public checkpoints declare their quantization, so load_model sets up the experts and sanitize only maps the tensors. load_model also reads fp8 with 1x32 ue8m0 blocks as mxfp8, as in Inkling-2-Small-MXFP8. --- mlx_lm/models/inkling2/checkpoint.py | 26 ------------------ mlx_lm/utils.py | 7 +++-- tests/models/test_inkling2.py | 41 ++++++++++++++++++---------- 3 files changed, 30 insertions(+), 44 deletions(-) diff --git a/mlx_lm/models/inkling2/checkpoint.py b/mlx_lm/models/inkling2/checkpoint.py index b2a9dd3dd..976b6f7cc 100644 --- a/mlx_lm/models/inkling2/checkpoint.py +++ b/mlx_lm/models/inkling2/checkpoint.py @@ -3,9 +3,6 @@ import re import mlx.core as mx -from mlx.utils import tree_unflatten - -from mlx_lm.layers.moe import SwitchLinear __all__ = [ "sanitize", @@ -95,27 +92,4 @@ def sanitize(model, weights: dict[str, mx.array]) -> dict[str, mx.array]: scale = scale / denominator[name].astype(mx.float32) sanitized[f"{name}.global_scale"] = amax[name].astype(mx.float32) * scale - # mlx-lm does not read this quantization config, so set the experts here. - modes = {(4, 16): "nvfp4", (4, 32): "mxfp4", (8, 32): "mxfp8"} - quantized = [] - for path, module in model.named_modules(): - scales = sanitized.get(f"{path}.scales") - if not isinstance(module, SwitchLinear) or scales is None: - continue - if scales.dtype != mx.uint8: - continue - in_dims = module.weight.shape[-1] - group_size = in_dims // scales.shape[-1] - bits = sanitized[f"{path}.weight"].shape[-1] * 32 // in_dims - if (bits, group_size) not in modes: - continue - ql = module.to_quantized( - group_size, - bits, - mode=modes[bits, group_size], - global_scale=f"{path}.global_scale" in sanitized, - ) - quantized.append((path, ql)) - if quantized: - model.update_modules(tree_unflatten(quantized)) return sanitized diff --git a/mlx_lm/utils.py b/mlx_lm/utils.py index 17c97a5ca..209dc49ab 100644 --- a/mlx_lm/utils.py +++ b/mlx_lm/utils.py @@ -551,10 +551,11 @@ def class_predicate(p, m): elif ( quant_method == "fp8" and quantization_config.get("scale_fmt") == "ue8m0" - and list(quantization_config.get("weight_block_size", ())) == [32, 32] + and list(quantization_config.get("weight_block_size", ())) + in ([32, 32], [1, 32]) ): - # Power-of-two scales over 32x32 blocks are mxfp8, so the weights - # stay packed. Other fp8 checkpoints dequantize in their sanitize. + # Power-of-two scales over 32x32 or 1x32 blocks are mxfp8, so the + # weights stay packed. Other fp8 checkpoints dequantize in sanitize. quantization = {"group_size": 32, "bits": 8, "mode": "mxfp8"} config["quantization"] = quantization config["quantization_config"] = quantization diff --git a/tests/models/test_inkling2.py b/tests/models/test_inkling2.py index 158badd76..35d0cb6bd 100644 --- a/tests/models/test_inkling2.py +++ b/tests/models/test_inkling2.py @@ -81,11 +81,19 @@ def create_model(vision: bool = False) -> inkling2.Model: return model -def quantize_experts(model: inkling2.Model) -> None: +NVFP4_RELEASE = {"quant_method": "modelopt", "quant_algo": "NVFP4"} +MXFP8_RELEASE = { + "quant_method": "fp8", + "weight_block_size": [1, 32], + "scale_fmt": "ue8m0", +} + + +def quantize_experts(model: inkling2.Model, mxfp8_only: bool = False) -> None: def predicate(path, module): if ".mlp.experts." not in path: return False - if ".layers.7." in path: + if mxfp8_only or ".layers.7." in path: return {"group_size": 32, "bits": 8, "mode": "mxfp8"} return {"group_size": 16, "bits": 4, "mode": "nvfp4", "global_scale": True} @@ -227,20 +235,23 @@ def test_sanitize_checkpoint(self): self.assertTrue(mx.array_equal(sanitized[k], v), k) def test_load_checkpoint(self): - model = create_model(vision=True) - quantize_experts(model) tokens = mx.array([[5, 6, 7, 8]]) - expected = model(tokens) - - with tempfile.TemporaryDirectory() as path: - path = Path(path) - mx.save_safetensors(str(path / "model.safetensors"), checkpoint(model)) - config = {**CONFIG, "vision_config": VISION_CONFIG} - (path / "config.json").write_text(json.dumps(config)) - quant = {"quant_method": "inkling2"} - (path / "hf_quant_config.json").write_text(json.dumps(quant)) - loaded, _ = load_model(path) - self.assertTrue(mx.allclose(loaded(tokens), expected, rtol=1e-4, atol=1e-4)) + for release, mxfp8_only in ((NVFP4_RELEASE, False), (MXFP8_RELEASE, True)): + with self.subTest(release["quant_method"]): + model = create_model(vision=True) + quantize_experts(model, mxfp8_only) + expected = model(tokens) + with tempfile.TemporaryDirectory() as path: + path = Path(path) + weights = checkpoint(model) + mx.save_safetensors(str(path / "model.safetensors"), weights) + config = {**CONFIG, "vision_config": VISION_CONFIG} + config["quantization_config"] = release + (path / "config.json").write_text(json.dumps(config)) + loaded, _ = load_model(path) + self.assertTrue( + mx.allclose(loaded(tokens), expected, rtol=1e-4, atol=1e-4) + ) def test_embed_inputs(self): model = create_model(vision=True)