diff --git a/mlx_lm/generate.py b/mlx_lm/generate.py index 47b632dc4..d278ce78f 100644 --- a/mlx_lm/generate.py +++ b/mlx_lm/generate.py @@ -1415,6 +1415,141 @@ def _append_pair(hs, ts, h, t): mx.eval([c.state for c in cache]) +def _has_dspark(model: nn.Module) -> bool: + return "dspark" in model and hasattr(model, "forward_features") + + +def dspark_generate_step( + prompt: mx.array, + model: nn.Module, + *, + num_draft_tokens: Optional[int] = None, + adaptive: bool = True, + max_tokens: int = 256, + sampler: Optional[Sampler] = None, + prompt_cache: Optional[Any] = None, + prefill_step_size: int = 2048, + prompt_progress_callback: Optional[Callable[[int, int], None]] = None, + stream: mx.Stream | mx.ThreadLocalStream = generation_stream, +) -> Generator[Tuple[int, mx.array, bool], None, None]: + """Speculative decoding with the model's DSpark draft (Inkling 2). + + The draft proposes up to ``block_size - 1`` tokens in one pass (``adaptive``: + as many as DraftLength expects to be fastest); the model runs once over + ``[last token, drafts...]``, samples its own token at every position and + accepts the longest prefix of drafts equal to those samples, then emits + its sample right after it. Every emitted token is the model's own sample: + the output is plain decoding's, with any sampler. The rejected tokens are + rolled back exactly (rollback_speculative_cache). + + The draft's context holds the model's features of every committed + position of this call (a reused prompt cache's prefix is not in it: the + drafts are then worse, the output the same). + + Single sequence only; no logits processors, KV quantization or input + embeddings (stream_generate falls back to plain decoding for those). + + Yields: + Tuple[int, mx.array, bool]: (token, log-probabilities, from_draft). + """ + if prompt.ndim != 1: + raise ValueError("dspark_generate_step supports a single sequence only.") + sampler = sampler or greedy_sampler + max_drafts = model.dspark.block_size - 1 + if num_draft_tokens is not None: + max_drafts = max(0, min(max_drafts, num_draft_tokens)) + cache = prompt_cache if prompt_cache is not None else make_prompt_cache(model) + draft_cache = model.dspark.make_cache() + if prompt_progress_callback is None: + prompt_progress_callback = lambda *_: None + + def _sample(logits): + logprobs = logits - mx.logsumexp(logits, axis=-1, keepdims=True) + if logprobs.shape[0] == 1 or sampler is greedy_sampler: + return sampler(logprobs), logprobs + rows = [sampler(logprobs[i : i + 1]) for i in range(logprobs.shape[0])] + return mx.concatenate(rows), logprobs + + total = len(prompt) + position = _cache_offset(cache) + with mx.stream(stream): + done = 0 + prompt_progress_callback(0, total) + while done < total: + n = min(prefill_step_size, total - done) + logits, features = model.forward_features( + prompt[done : done + n][None], cache + ) + model.dspark.add_context(features, position + done, draft_cache) + mx.eval([c.state for c in cache] + [c.state for c in draft_cache]) + done += n + prompt_progress_callback(done, total) + mx.clear_cache() + tok, logprobs = _sample(logits[:, -1]) + last = features[:, -1] + position += total + mx.eval(tok, logprobs, last) + + # On exit the cache holds exactly prompt + every token yielded so far, as + # plain generate_step leaves it: the last yielded token is fed, or the + # accepted drafts after the stop are rolled back. + fixup = ("feed", tok) + n_out = 1 + try: + yield tok.item(), logprobs.squeeze(0), False + limit = max_tokens if max_tokens >= 0 else float("inf") + lengths = DraftLength(max_drafts) if adaptive else None + while n_out < limit: + k = lengths.choose() if lengths else max_drafts + k = int(min(k, limit - n_out)) + started = time.perf_counter() + fixup = None # mid-iteration: cache state not well defined + with mx.stream(stream): + if k > 0: + drafts = model.draft(tok, position, last, draft_cache, k) + block = mx.concatenate([tok.reshape(1, 1), drafts], axis=1) + else: + drafts = mx.array([[]], mx.uint32) + block = tok.reshape(1, 1) + model.record_conv_windows(cache, True) + logits, features = model.forward_features(block, cache, all_logits=True) + model.record_conv_windows(cache, False) + toks, lps = _sample(logits[0]) + mx.eval(toks, lps, drafts, features) + toks_l, draft_l = toks.tolist(), drafts[0].tolist() + n_acc = 0 + while n_acc < k and draft_l[n_acc] == toks_l[n_acc]: + n_acc += 1 + if lengths: + lengths.update(k, n_acc, time.perf_counter() - started) + with mx.stream(stream): + model.rollback_speculative_cache(cache, n_acc + 1, k + 1) + model.dspark.add_context( + features[:, : n_acc + 1], position, draft_cache + ) + last = features[:, n_acc] + position += n_acc + 1 + tok = toks[n_acc] + for i in range(n_acc): + # Stopping here keeps the anchor and the first i + 1 drafts. + fixup = ("keep", i + 2, n_acc + 1) + yield draft_l[i], lps[i], True + n_out += 1 + if n_out >= limit: + return + fixup = ("feed", tok) + yield toks_l[n_acc], lps[n_acc], False + n_out += 1 + finally: + if fixup is not None: + with mx.stream(stream): + if fixup[0] == "keep": + model.rollback_speculative_cache(cache, fixup[1], fixup[2]) + else: + model(fixup[1].reshape(1, 1), cache=cache) + mx.eval([c.state for c in cache]) + + def _is_gemma4_assistant(draft_model: Optional[nn.Module]) -> bool: return getattr(draft_model, "model_type", None) == "gemma4_assistant" @@ -1736,8 +1871,19 @@ def stream_generate( # docstring for why rollback needs no quantization-aware branch). # A Qwen3.5 MTP head: any sampler (the drafts are checked against # the backbone's own samples). + # An Inkling 2 DSpark draft: any sampler, as the MTP head. + use_dspark = ( + _has_dspark(model) + and num_head_drafts != 0 + and prompt.ndim == 1 + and not kwargs.get("logits_processors") + and kwargs.get("max_kv_size") is None + and kwargs.get("input_embeddings") is None + and kwargs.get("kv_bits") is None + ) use_head = ( - _mtp_language_model(model) is not None + not use_dspark + and _mtp_language_model(model) is not None and num_head_drafts != 0 and prompt.ndim == 1 and not kwargs.get("logits_processors") @@ -1753,7 +1899,19 @@ def stream_generate( and kwargs.get("max_kv_size") is None and kwargs.get("input_embeddings") is None ) - if use_head: + if use_dspark: + token_generator = dspark_generate_step( + prompt, + model, + num_draft_tokens=num_head_drafts, + max_tokens=kwargs["max_tokens"], + sampler=kwargs.get("sampler"), + prompt_cache=kwargs.get("prompt_cache"), + prefill_step_size=kwargs.get("prefill_step_size", 2048), + prompt_progress_callback=kwargs.get("prompt_progress_callback"), + stream=stream, + ) + elif use_head: token_generator = mtp_generate_step( prompt, model, diff --git a/mlx_lm/kernels/bitlinear.py b/mlx_lm/kernels/bitlinear.py new file mode 100644 index 000000000..a3c3cad83 --- /dev/null +++ b/mlx_lm/kernels/bitlinear.py @@ -0,0 +1,106 @@ +# Copyright © 2025 Apple Inc. + +"""BitNet's ternary matmul Metal kernel.""" + +import mlx.core as mx + +__all__ = [ + "bitlinear_matmul", + "make_bitlinear_kernel", +] + + +def make_bitlinear_kernel(): + """ + Custom Metal kernel that performs matrix multiplication directly on + packed weights and scales the output. This eliminates the need to + store unpacked weights in memory. + """ + source = """ + constexpr int M = 4; + constexpr int BLOCK = 32; + + uint tid = thread_position_in_grid.y; + uint in_offset = thread_position_in_grid.x; + + uint batch_idx = tid / (out_features / 4); + uint row_idx = tid % (out_features / 4); + + float sum[4] = {0.0}; + + for (uint i = in_offset * M; i < in_features; i += BLOCK * M) { + float v[M]; + for (int j=0; j> 2) & 3) - 1); + sum[2] += v[j] * (((w >> 4) & 3) - 1); + sum[3] += v[j] * (((w >> 6) & 3) - 1); + } + } + + for (int j=0; j<4; j++) { + sum[j] = simd_sum(sum[j]); + } + + // Apply weight scaling by diving them or multiplying them + if (in_offset == 0) { + float scale = invert_weight_scales ? 1 / weight_scale[0] : weight_scale[0]; + for (int i=0; i<4; i++) { + out[batch_idx * out_features + row_idx + i * (out_features/4)] = static_cast(sum[i] * scale); + } + } + """ + + return mx.fast.metal_kernel( + name="bitlinear_matmul", + input_names=["x", "packed_weights", "weight_scale"], + output_names=["out"], + source=source, + ) + + +_bitlinear_kernel = make_bitlinear_kernel() + + +def bitlinear_matmul( + x: mx.array, + packed_weights: mx.array, + weight_scale: mx.array, + *, + out_features: int, + invert_weight_scales: bool, +) -> mx.array: + """x times the ternary weights, packed four to a byte.""" + original_shape = x.shape + if len(original_shape) > 2: + x = x.reshape(-1, original_shape[-1]) + total_batch_elements, in_features = x.shape + + dtype = weight_scale.dtype + assert x.dtype == dtype, "Wrong type for input." + out = _bitlinear_kernel( + inputs=[ + x, + packed_weights, + weight_scale, + ], + template=[ + ("T", dtype), + ("invert_weight_scales", invert_weight_scales), + ("in_features", in_features), + ("out_features", out_features), + ], + grid=(32, total_batch_elements * out_features // 4, 1), + threadgroup=(32, 1, 1), # SIMD width is 32 threads + output_shapes=[(total_batch_elements, out_features)], + output_dtypes=[dtype], + )[0] + + if len(original_shape) > 2: + out = out.reshape(*original_shape[:-1], out_features) + return out diff --git a/mlx_lm/layers/__init__.py b/mlx_lm/layers/__init__.py new file mode 100644 index 000000000..d16c77519 --- /dev/null +++ b/mlx_lm/layers/__init__.py @@ -0,0 +1 @@ +# Copyright © 2026 Apple Inc. diff --git a/mlx_lm/layers/common.py b/mlx_lm/layers/common.py new file mode 100644 index 000000000..ac9666ff6 --- /dev/null +++ b/mlx_lm/layers/common.py @@ -0,0 +1,205 @@ +# Copyright © 2025 Apple Inc. + +from functools import partial + +import mlx.core as mx +import mlx.nn as nn +from mlx.utils import tree_flatten, tree_unflatten + +from mlx_lm.kernels.bitlinear import bitlinear_matmul + +__all__ = [ + "BitLinear", + "SwiGLU", + "SwigluOAI", + "XieLU", + "ZeroCenteredRMSNorm", + "bitnet_quantize", + "precise_swiglu", + "splice", + "swiglu", + "swiglu_oai", + "xielu", +] + + +@partial(mx.compile, shapeless=True) +def swiglu(gate, x): + return nn.silu(gate) * x + + +@partial(mx.compile, shapeless=True) +def precise_swiglu(h, gate, x): + gate = nn.silu(gate.astype(mx.float32)) + x = x.astype(mx.float32) + return (gate * x).astype(h.dtype) + + +@partial(mx.compile, shapeless=True) +def swiglu_oai( + gate: mx.array, x: mx.array, alpha: float = 1.702, limit: float = 7.0 +) -> mx.array: + # GPT-OSS variant: clip the gate from above only, and add 1 to the linear part. + gate = mx.minimum(gate, limit) + x = mx.clip(x, -limit, limit) + return (x + 1.0) * (gate * mx.sigmoid(alpha * gate)) + + +class SwigluOAI(nn.Module): + def __init__(self, alpha: float = 1.702, limit: float = 7.0): + super().__init__() + self._alpha = alpha + self._limit = limit + + def __call__(self, x: mx.array, gate: mx.array) -> mx.array: + return swiglu_oai(gate, x, alpha=self._alpha, limit=self._limit) + + +@partial(mx.compile, shapeless=True) +def xielu(x, alpha_p, alpha_n, beta, eps): + alpha_p = nn.softplus(alpha_p) + alpha_n = beta + nn.softplus(alpha_n) + return mx.where( + x > 0, + alpha_p * mx.square(x) + beta * x, + (mx.expm1(mx.minimum(x, eps)) - x) * alpha_n + beta * x, + ) + + +class XieLU(nn.Module): + def __init__( + self, + alpha_p_init=0.8, + alpha_n_init=0.8, + beta=0.5, + eps=-1e-6, + ): + super().__init__() + alpha_p_tensor = mx.array(alpha_p_init) + alpha_n_tensor = mx.array(alpha_n_init - beta) + self.alpha_p = mx.log(mx.exp(alpha_p_tensor) - 1) + self.alpha_n = mx.log(mx.exp(alpha_n_tensor) - 1) + + self.beta = mx.array(beta) + self.eps = mx.array(eps) + + def __call__(self, x: mx.array) -> mx.array: + return xielu(x, self.alpha_p, self.alpha_n, self.beta, self.eps) + + +class SwiGLU(nn.Module): + def __init__(self): + super().__init__() + + def __call__(self, x, gate): + return swiglu(gate, x) + + +class ZeroCenteredRMSNorm(nn.Module): + """RMSNorm with a zero-centred weight: it scales by ``1 + weight``. + + The weight starts at zero, so a new norm is a plain RMSNorm. Only the + weight is centred, not the input; centring the input is LayerNorm. + """ + + def __init__(self, dims: int, *, eps: float): + super().__init__() + self.weight = mx.zeros((dims,)) + self.eps = eps + + def _extra_repr(self) -> str: + return f"{self.weight.shape[0]}, eps={self.eps}" + + def __call__(self, x: mx.array) -> mx.array: + return mx.fast.rms_norm(x, 1.0 + self.weight, self.eps) + + +def bitnet_quantize(model, quantization_config: dict): + quantize_layers = [] + modules_to_not_convert = quantization_config.get("modules_to_not_convert", []) + invert_weight_scales = ( + quantization_config.get("linear_class", "") != "autobitlinear" + ) + + for name, module in tree_flatten(model.leaf_modules(), is_leaf=nn.Module.is_module): + + # Replace nn.Linear layers, but skip any layer from the `modules_to_not_convert` list + if name not in modules_to_not_convert and isinstance(module, nn.Linear): + old_weight = module.weight + out_features, in_features = old_weight.shape + bias = "bias" in module + new_layer = BitLinear( + in_features, + out_features, + bias=bias, + invert_weight_scales=invert_weight_scales, + ) + quantize_layers.append((name, new_layer)) + if len(quantize_layers) > 0: + model.update_modules(tree_unflatten(quantize_layers)) + return model + + +class BitLinear(nn.Module): + """ + BitLinear module with memory-efficient weight handling. + """ + + def __init__( + self, + in_features, + out_features, + bias=True, + invert_weight_scales=False, + ): + super().__init__() + self.in_features = in_features + self.out_features = out_features + # Calculate packed dimensions - the first dimension gets packed 4:1 + # The weights are ternary so can be represented with 2 bits, and they + # are packed in uint8 tensors, hence the number of values per item is 4 + packed_out_features = (out_features + 3) // 4 + self.weight = mx.zeros((packed_out_features, in_features), dtype=mx.uint8) + + self.invert_weight_scales = invert_weight_scales + self.weight_scale = mx.array([1.0]) + + if bias: + self.bias = mx.zeros((out_features,)) + else: + self.bias = None + + def execute_matmul_kernel(self, x, packed_weights): + return bitlinear_matmul( + x, + packed_weights, + self.weight_scale, + out_features=self.out_features, + invert_weight_scales=self.invert_weight_scales, + ) + + def __call__(self, x): + y = self.execute_matmul_kernel(x, self.weight) + + if self.bias is not None: + y = mx.add(y, self.bias) + return y + + +def splice( + embeddings: mx.array, + inputs: mx.array, + *, + rows: mx.array, + token_id: int, +) -> mx.array: + """The embeddings with the rows, in order, at the token_id positions of inputs.""" + # A shape check only, so no host sync. + if rows.shape[0] == 0: + return embeddings + mask = inputs == token_id + # The row of each masked token: the number of masked tokens before it. + idx = mx.cumsum(mask.flatten()).reshape(mask.shape) - 1 + idx = mx.clip(idx, 0, rows.shape[0] - 1) + selected = rows[idx].astype(embeddings.dtype) + return mx.where(mask[..., None], selected, embeddings) diff --git a/mlx_lm/layers/distributed.py b/mlx_lm/layers/distributed.py new file mode 100644 index 000000000..b981c2c03 --- /dev/null +++ b/mlx_lm/layers/distributed.py @@ -0,0 +1,54 @@ +# Copyright © 2025 Apple Inc. + +import mlx.core as mx + +__all__ = [ + "PipelineMixin", + "gather_last_axis", +] + + +def gather_last_axis(x: mx.array, group: mx.distributed.Group) -> mx.array: + """Gather the last axis of ``x``, which is split across ``group``.""" + n, size = group.size(), x.shape[-1] + parts = mx.distributed.all_gather(x.reshape(-1, size), group=group) + # (ranks * rows, size) to (rows, ranks * size), in rank order. + parts = parts.reshape(n, -1, size).transpose(1, 0, 2) + return parts.reshape(*x.shape[:-1], n * size) + + +class PipelineMixin: + def __init__(self): + super().__init__() + self.pipeline_rank = 0 + self.pipeline_size = 1 + self.start_idx = 0 + self.end_idx = None + + @property + def pipeline_layers(self): + return self.layers[self.start_idx : self.end_idx] + + def pipeline(self, group, split=None): + # Split layers in reverse so rank=0 gets the last layers and + # rank=pipeline_size-1 gets the first + self.pipeline_rank = group.rank() + self.pipeline_size = group.size() + if split is None: + # Even split; the low ranks get the extra layers. + base, extra = divmod(len(self.layers), self.pipeline_size) + split = [base + (1 if r < extra else 0) for r in range(self.pipeline_size)] + if len(split) != self.pipeline_size: + raise ValueError( + f"split has {len(split)} entries for group size {self.pipeline_size}" + ) + if any(s <= 0 for s in split) or sum(split) != len(self.layers): + raise ValueError( + f"split {split} must be positive and sum to {len(self.layers)} layers" + ) + # Rank r runs the layers after the layers of ranks r+1 ... size-1. + self.start_idx = sum(split[self.pipeline_rank + 1 :]) + self.end_idx = self.start_idx + split[self.pipeline_rank] + self.layers = self.layers[: self.end_idx] + # Keep the layer numbers the same for model loading + self.layers[: self.start_idx] = [None] * self.start_idx diff --git a/mlx_lm/layers/moe.py b/mlx_lm/layers/moe.py new file mode 100644 index 000000000..00055050e --- /dev/null +++ b/mlx_lm/layers/moe.py @@ -0,0 +1,255 @@ +# Copyright © 2023 Apple Inc. + +import math + +import mlx.core as mx +import mlx.nn as nn + +from mlx_lm.layers.common import SwiGLU + +__all__ = [ + "QuantizedSwitchLinear", + "SwitchGLU", + "SwitchLinear", + "SwitchMLP", +] + + +def _gather_sort(x, indices): + *_, M = indices.shape + indices = indices.flatten() + order = mx.argsort(indices) + inv_order = mx.argsort(order) + return x.flatten(0, -3)[order // M], indices[order], inv_order + + +def _scatter_unsort(x, inv_order, shape=None): + x = x[inv_order] + if shape is not None: + x = mx.unflatten(x, 0, shape) + return x + + +def _quantize_experts(w, *, group_size, bits, mode): + """Quantize each expert with its own nvfp4 tensor scale.""" + if mode != "nvfp4": + raise ValueError(f"A global scale needs 'nvfp4' mode, got '{mode}'.") + gs = mx.max(mx.abs(w), axis=(-2, -1)).astype(mx.float32) + qs = [ + mx.quantize(w[e], group_size, bits, mode=mode, global_scale=gs[e]) + for e in range(w.shape[0]) + ] + return mx.stack([q for q, _ in qs]), mx.stack([s for _, s in qs]), gs + + +class QuantizedSwitchLinear(nn.Module): + def __init__( + self, + input_dims: int, + output_dims: int, + num_experts: int, + bias: bool = True, + group_size: int = 64, + bits: int = 4, + mode: str = "affine", + global_scale: bool = False, + ): + super().__init__() + + self.group_size = group_size + self.bits = bits + self.mode = mode + + scale = math.sqrt(1 / input_dims) + weight = mx.random.uniform( + low=-scale, + high=scale, + shape=(num_experts, output_dims, input_dims), + ) + self._quantize(weight, global_scale) + if bias: + self.bias = mx.zeros((num_experts, output_dims)) + # Freeze this model's parameters + self.freeze() + + def _quantize(self, weight, global_scale=False): + if global_scale: + self.weight, self.scales, self.global_scale = _quantize_experts( + weight, group_size=self.group_size, bits=self.bits, mode=self.mode + ) + self.biases = None + else: + self.weight, self.scales, *biases = mx.quantize( + weight, self.group_size, self.bits, mode=self.mode + ) + self.biases = biases[0] if biases else None + self.global_scale = None + + @property + def input_dims(self): + return self.scales.shape[2] * self.group_size + + @property + def output_dims(self): + return self.weight.shape[1] + + @property + def num_experts(self): + return self.weight.shape[0] + + def __call__(self, x, indices, sorted_indices=False): + x = mx.gather_qmm( + x, + self["weight"], + self["scales"], + self.get("biases"), + rhs_indices=indices, + transpose=True, + group_size=self.group_size, + bits=self.bits, + mode=self.mode, + global_scale=self.global_scale, + sorted_indices=sorted_indices, + ) + if "bias" in self: + x = x + mx.expand_dims(self["bias"][indices], -2) + return x + + +class SwitchLinear(nn.Module): + def __init__( + self, input_dims: int, output_dims: int, num_experts: int, bias: bool = True + ): + super().__init__() + scale = math.sqrt(1 / input_dims) + self.weight = mx.random.uniform( + low=-scale, + high=scale, + shape=(num_experts, output_dims, input_dims), + ) + + if bias: + self.bias = mx.zeros((num_experts, output_dims)) + + @property + def input_dims(self): + return self.weight.shape[2] + + @property + def output_dims(self): + return self.weight.shape[1] + + @property + def num_experts(self): + return self.weight.shape[0] + + def __call__(self, x, indices, sorted_indices=False): + x = mx.gather_mm( + x, + self["weight"].swapaxes(-1, -2), + rhs_indices=indices, + sorted_indices=sorted_indices, + ) + if "bias" in self: + x = x + mx.expand_dims(self["bias"][indices], -2) + return x + + def to_quantized( + self, + group_size: int = 64, + bits: int = 4, + mode: str = "affine", + global_scale: bool = False, + ): + num_experts, output_dims, input_dims = self.weight.shape + ql = QuantizedSwitchLinear( + input_dims, + output_dims, + num_experts, + False, + group_size, + bits, + mode=mode, + ) + ql._quantize(self.weight, global_scale) + + if "bias" in self: + ql.bias = self.bias + return ql + + +class SwitchGLU(nn.Module): + def __init__( + self, + input_dims: int, + hidden_dims: int, + num_experts: int, + activation=SwiGLU(), + bias: bool = False, + ): + super().__init__() + + self.gate_proj = SwitchLinear(input_dims, hidden_dims, num_experts, bias=bias) + self.up_proj = SwitchLinear(input_dims, hidden_dims, num_experts, bias=bias) + self.down_proj = SwitchLinear(hidden_dims, input_dims, num_experts, bias=bias) + self.activation = activation + + def __call__(self, x, indices) -> mx.array: + x = mx.expand_dims(x, (-2, -3)) + + # When we have many tokens, then sort them to make sure that the access + # of different experts is in order. + indices = mx.stop_gradient(indices) + do_sort = indices.size >= 64 + idx = indices + inv_order = None + if do_sort: + x, idx, inv_order = _gather_sort(x, indices) + x_up = self.up_proj(x, idx, sorted_indices=do_sort) + x_gate = self.gate_proj(x, idx, sorted_indices=do_sort) + x = self.down_proj( + self.activation(x_up, x_gate), + idx, + sorted_indices=do_sort, + ) + + if do_sort: + x = _scatter_unsort(x, inv_order, indices.shape) + + return x.squeeze(-2) + + +class SwitchMLP(nn.Module): + def __init__( + self, + input_dims: int, + hidden_dims: int, + num_experts: int, + activation=nn.GELU(approx="precise"), + bias: bool = False, + ): + super().__init__() + + self.fc1 = SwitchLinear(input_dims, hidden_dims, num_experts, bias=bias) + self.fc2 = SwitchLinear(hidden_dims, input_dims, num_experts, bias=bias) + self.activation = activation + + def __call__(self, x, indices) -> mx.array: + x = mx.expand_dims(x, (-2, -3)) + + # When we have many tokens, then sort them to make sure that the access + # of different experts is in order. + indices = mx.stop_gradient(indices) + do_sort = indices.size >= 64 + idx = indices + inv_order = None + if do_sort: + x, idx, inv_order = _gather_sort(x, indices) + x = self.fc1(x, idx, sorted_indices=do_sort) + x = self.activation(x) + x = self.fc2(x, idx, sorted_indices=do_sort) + + if do_sort: + x = _scatter_unsort(x, inv_order, indices.shape) + + return x.squeeze(-2) 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..e65237157 --- /dev/null +++ b/mlx_lm/models/inkling2/checkpoint.py @@ -0,0 +1,147 @@ +# 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"\.controllers\.attn\.", ".q_message_gate."), + (r"\.controllers\.(k|v|mlp)\.", r".\1_message_gate."), + (r"_message_gate\.down_weight$", "_message_gate.down_proj.weight"), + (r"_message_gate\.forget_weight$", "_message_gate.forget_gate_proj.weight"), + (r"_message_gate\.gain_weight$", "_message_gate.message_gate_proj.weight"), + (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 = {}, {} + message_queries = {} + 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(("cross_pass_queries", "cross_pass_kv_queries")): + message_queries["kv" if "_kv_" in k else "q"] = v + continue + if k.endswith( + ( + ".mlp.gate.weight", + ".forget_gate_proj.weight", + ".message_gate_proj.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 + elif v.dtype == mx.uint8: + sanitized[f"{name}.weight"] = v.view(mx.uint32) + else: + # Unquantized experts. + sanitized[f"{name}.weight"] = v + continue + sanitized[k] = v + + if message_queries: + # The checkpoint has [query, mlp] and [key, value] rows per looped layer. + dims = message_queries["q"].shape[-1] + q = message_queries["q"].reshape(-1, 2, dims) + kv = message_queries["kv"].reshape(-1, 2, dims) + query = mx.concatenate([q[:, :1], kv, q[:, 1:]], axis=1) + sanitized["model.language_model.message_input.query"] = query + + # 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..08058b760 --- /dev/null +++ b/mlx_lm/models/inkling2/config.py @@ -0,0 +1,83 @@ +# 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 + loop_config: dict | None = None + + def __post_init__(self): + loop = self.loop_config or {} + self.loop_core = range(loop.get("core_start", 0), loop.get("core_end", 0)) + + +@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 + mtp_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/models/inkling2/dspark.py b/mlx_lm/models/inkling2/dspark.py new file mode 100644 index 000000000..94027ed2f --- /dev/null +++ b/mlx_lm/models/inkling2/dspark.py @@ -0,0 +1,234 @@ +# Copyright © 2026 IPSupport LLC + +"""The DSpark draft of Inkling 2 (``mtp.safetensors``). + +A block of an anchor (the last sampled token) and ``block_size - 1`` mask +embeddings runs through a small dense transformer. Its keys and values are +the block's own plus a context: per draft layer, a learned mix of the +target's hidden states at ``target_layer_ids`` for every committed +position. A recurrent Markov head then corrects the logits of the mask +positions one after the other, from the token drafted before. As vLLM's +``vllm/models/inkling2/nvidia/dspark.py``. +""" + +from dataclasses import dataclass + +import mlx.core as mx +import mlx.nn as nn + +from mlx_lm.models.base import BaseModelArgs +from mlx_lm.models.cache import KVCache + +__all__ = ["DSpark", "DSparkArgs"] + + +@dataclass +class DSparkArgs(BaseModelArgs): + hidden_size: int + num_hidden_layers: int + num_attention_heads: int + num_key_value_heads: int + head_dim: int + intermediate_size: int + rms_norm_eps: float + rope_theta: float + local_layer_ids: list[int] + sliding_window_size: int + block_size: int + markov_rank: int + target_layer_ids: list[int] + markov_head_type: str = "rnn_hidden" + + +def _mix(features: mx.array, alpha: mx.array, norm: nn.RMSNorm) -> mx.array: + """RMSNorm of the alpha-weighted sum of the target features (..., taps, hidden).""" + mixed = (features.astype(mx.float32) * alpha[:, None]).sum(axis=-2) + return mx.fast.rms_norm(mixed, norm.weight.astype(mx.float32), norm.eps) + + +class _Context: + """Context keys and values of one draft layer, committed positions only: + the last ``window`` of them for a local layer.""" + + def __init__(self, window: int): + self.window = window + self.cache = None if window else KVCache() + self.keys = self.values = None + + def append(self, keys: mx.array, values: mx.array): + if self.cache is not None: + self.keys, self.values = self.cache.update_and_fetch(keys, values) + return + if self.keys is not None: + keys = mx.concatenate([self.keys, keys], axis=2) + values = mx.concatenate([self.values, values], axis=2) + self.keys = keys[..., -self.window :, :] + self.values = values[..., -self.window :, :] + + @property + def state(self): + return [a for a in (self.keys, self.values) if a is not None] + + +class Attention(nn.Module): + def __init__(self, args: DSparkArgs): + super().__init__() + dims, self.head_dim = args.hidden_size, args.head_dim + self.num_heads = args.num_attention_heads + self.num_kv_heads = args.num_key_value_heads + q_dims = self.num_heads * self.head_dim + kv_dims = self.num_kv_heads * self.head_dim + self.q_proj = nn.Linear(dims, q_dims, bias=False) + self.k_proj = nn.Linear(dims, kv_dims, bias=False) + self.v_proj = nn.Linear(dims, kv_dims, bias=False) + self.o_proj = nn.Linear(q_dims, dims, bias=False) + self.k_proj_ctx = nn.Linear(dims, kv_dims, bias=False) + self.v_proj_ctx = nn.Linear(dims, kv_dims, bias=False) + self.q_norm = nn.RMSNorm(self.head_dim, eps=args.rms_norm_eps) + self.k_norm = nn.RMSNorm(self.head_dim, eps=args.rms_norm_eps) + self.k_norm_ctx = nn.RMSNorm(self.head_dim, eps=args.rms_norm_eps) + self.rope = nn.RoPE(self.head_dim, traditional=False, base=args.rope_theta) + + def _heads(self, x: mx.array, n: int) -> mx.array: + B, L, _ = x.shape + return x.reshape(B, L, n, self.head_dim) + + def context(self, x: mx.array, position: int) -> tuple[mx.array, mx.array]: + keys = self.k_norm_ctx(self._heads(self.k_proj_ctx(x), self.num_kv_heads)) + keys = self.rope(keys.transpose(0, 2, 1, 3), offset=position) + values = self._heads(self.v_proj_ctx(x), self.num_kv_heads) + return keys, values.transpose(0, 2, 1, 3) + + def __call__(self, x: mx.array, position: int, context: _Context) -> mx.array: + B, L, _ = x.shape + queries = self.q_norm(self._heads(self.q_proj(x), self.num_heads)) + keys = self.k_norm(self._heads(self.k_proj(x), self.num_kv_heads)) + values = self._heads(self.v_proj(x), self.num_kv_heads) + queries = self.rope(queries.transpose(0, 2, 1, 3), offset=position) + keys = self.rope(keys.transpose(0, 2, 1, 3), offset=position) + values = values.transpose(0, 2, 1, 3) + if context.keys is not None: + keys = mx.concatenate([context.keys, keys], axis=2) + values = mx.concatenate([context.values, values], axis=2) + # The block attends to all of itself and its context: no mask. + out = mx.fast.scaled_dot_product_attention( + queries, keys, values, scale=self.head_dim**-0.5 + ) + return self.o_proj(out.transpose(0, 2, 1, 3).reshape(B, L, -1)) + + +class MLP(nn.Module): + def __init__(self, dims: int, hidden: int): + super().__init__() + self.gate_proj = nn.Linear(dims, hidden, bias=False) + self.up_proj = nn.Linear(dims, hidden, bias=False) + self.down_proj = nn.Linear(hidden, dims, bias=False) + + def __call__(self, x: mx.array) -> mx.array: + return self.down_proj(nn.silu(self.gate_proj(x)) * self.up_proj(x)) + + +class Layer(nn.Module): + def __init__(self, args: DSparkArgs): + super().__init__() + eps = args.rms_norm_eps + self.input_layernorm = nn.RMSNorm(args.hidden_size, eps=eps) + self.post_attention_layernorm = nn.RMSNorm(args.hidden_size, eps=eps) + self.dflare_norm = nn.RMSNorm(args.hidden_size, eps=eps) + self.self_attn = Attention(args) + self.mlp = MLP(args.hidden_size, args.intermediate_size) + + def __call__(self, x: mx.array, position: int, context: _Context) -> mx.array: + x = x + self.self_attn(self.input_layernorm(x), position, context) + return x + self.mlp(self.post_attention_layernorm(x)) + + +class MarkovHead(nn.Module): + def __init__(self, args: DSparkArgs, vocab_size: int): + super().__init__() + rank, dims = args.markov_rank, args.hidden_size + self.markov_rank = rank + self.markov_w1 = nn.Embedding(vocab_size, rank) + self.rnn_proj = nn.Linear(2 * rank + 2 * dims, 3 * rank) + self.hidden_out = nn.Linear(rank, dims) + self.dflare_norm = nn.RMSNorm(dims, eps=args.rms_norm_eps) + + def step(self, state, prev, hidden, f_rnn): + """One recurrence step: the new state and the correction of the + hidden state (the LM head turns it into the logits' bias).""" + R = self.markov_rank + joint = mx.concatenate( + [state, self.markov_w1(prev).astype(mx.float32), hidden, f_rnn], axis=-1 + ) + raw = self.rnn_proj(joint.astype(self.rnn_proj.weight.dtype)) + raw = raw.astype(mx.float32) + gate = mx.sigmoid(raw[..., :R]) + state = gate * state + (1 - gate) * mx.tanh(raw[..., R : 2 * R]) + latent = mx.tanh(raw[..., 2 * R :]) + return state, self.hidden_out(latent.astype(self.hidden_out.weight.dtype)) + + +class DSpark(nn.Module): + def __init__(self, args: DSparkArgs, vocab_size: int): + super().__init__() + self.args = args + self.layers = [Layer(args) for _ in range(args.num_hidden_layers)] + self.norm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps) + self.markov_head = MarkovHead(args, vocab_size) + taps = len(args.target_layer_ids) + self.fuse_weight = mx.zeros((args.num_hidden_layers + 1, taps)) + self.mask_embed = mx.zeros((args.hidden_size,)) + + @property + def block_size(self) -> int: + return self.args.block_size + + def make_cache(self) -> list[_Context]: + window = self.args.sliding_window_size + return [ + _Context(window if i in self.args.local_layer_ids else 0) + for i in range(len(self.layers)) + ] + + def _alpha(self) -> mx.array: + return mx.softmax(self.fuse_weight.astype(mx.float32), axis=-1) + + def add_context(self, features: mx.array, position: int, cache: list[_Context]): + """Commit the target features (B, L, taps, hidden) of positions + position .. position + L - 1.""" + alpha = self._alpha() + dtype = self.mask_embed.dtype + for i, (layer, context) in enumerate(zip(self.layers, cache)): + x = _mix(features, alpha[i], layer.dflare_norm).astype(dtype) + context.append(*layer.self_attn.context(x, position)) + + def __call__(self, anchor: mx.array, position: int, cache: list[_Context]): + """Final hidden states of the block [anchor, masks...] at positions + position .. position + block_size - 1; anchor: (B, 1, hidden).""" + B = anchor.shape[0] + masks = mx.broadcast_to( + self.mask_embed.astype(anchor.dtype), + (B, self.block_size - 1, anchor.shape[-1]), + ) + x = mx.concatenate([anchor, masks], axis=1) + for layer, context in zip(self.layers, cache): + x = layer(x, position, context) + return self.norm(x) + + def draft(self, anchor_token, anchor, position, last_features, cache, head, k): + """k greedy draft tokens after anchor_token. last_features: the target + features (B, taps, hidden) of the position before the anchor; head + maps hidden states to final logits.""" + hidden = self(anchor, position, cache) + f_rnn = _mix(last_features, self._alpha()[-1], self.markov_head.dflare_norm) + B = anchor.shape[0] + state = mx.zeros((B, self.markov_head.markov_rank), mx.float32) + prev, drafts = anchor_token.reshape(B), [] + for i in range(k): + h = hidden[:, i + 1] + state, correction = self.markov_head.step( + state, prev, h.astype(mx.float32), f_rnn + ) + prev = mx.argmax(head(h + correction.astype(h.dtype)), axis=-1) + drafts.append(prev) + return mx.stack(drafts, axis=-1) diff --git a/mlx_lm/models/inkling2/kernels.py b/mlx_lm/models/inkling2/kernels.py new file mode 100644 index 000000000..8f83e0462 --- /dev/null +++ b/mlx_lm/models/inkling2/kernels.py @@ -0,0 +1,322 @@ +# Copyright © 2026 Apple Inc. + +import mlx.core as mx + +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. +_RELATIVE_ATTENTION_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); + } + } +""" + +_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=_RELATIVE_ATTENTION_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 _relative_attention_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/layers.py b/mlx_lm/models/inkling2/layers.py new file mode 100644 index 000000000..05810825f --- /dev/null +++ b/mlx_lm/models/inkling2/layers.py @@ -0,0 +1,738 @@ +# 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", + "MessageGate", + "MessageInput", + "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, + 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), conv_states[0], conv_mask + ) + value_states, conv_states[1] = self.v_sconv( + self.v_proj(value_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] + return _depth_attention( + block_states, partial_block_states, self.query.reshape(-1, dims) + ) + + +def _depth_attention( + block_states: mx.array, partial_block_states: mx.array, query: mx.array +) -> mx.array: + query = query.astype(mx.float32) + scale = partial_block_states.shape[-1] ** -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 MessageGate(nn.Module): + def __init__(self, dims: int, rank: int): + super().__init__() + self.down_proj = nn.Linear(2 * dims, rank, bias=False) + self.forget_gate_proj = nn.Linear(rank, dims, bias=False) + self.message_gate_proj = nn.Linear(rank, dims, bias=False) + + def __call__(self, hidden_states: mx.array, message: mx.array) -> mx.array: + states = mx.concatenate( + [unweighted_rms_norm(hidden_states), unweighted_rms_norm(message)], + axis=-1, + ) + states = self.down_proj(states.astype(self.down_proj.weight.dtype)) + states = states.astype(mx.float32) + forget_gate = mx.tanh(self.forget_gate_proj(states)) + message_gate = mx.tanh(self.message_gate_proj(states)) + return (1 - forget_gate) * hidden_states + message_gate * message + + +class MessageInput(nn.Module): + def __init__(self, dims: int, num_looped_layers: int): + super().__init__() + # The query, key, value and mlp queries of each looped layer. + self.query = mx.zeros((num_looped_layers, 4, dims), mx.float32) + + def __call__(self, bank: tuple, loop_layer_idx: int) -> mx.array: + return _depth_attention(*bank, self.query[loop_layer_idx]) + + +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) + if layer_idx in args.loop_core: + rank = args.loop_config["gate_rank"] + self.q_message_gate = MessageGate(dims, rank) + self.k_message_gate = MessageGate(dims, rank) + self.v_message_gate = MessageGate(dims, rank) + self.mlp_message_gate = MessageGate(dims, rank) + + def _mix_messages(self, states: tuple, messages: mx.array) -> tuple: + q_states, k_states, v_states = states + return ( + self.q_message_gate(q_states, messages[..., 0, :]), + self.k_message_gate(k_states, messages[..., 1, :]), + self.v_message_gate(v_states, messages[..., 2, :]), + ) + + def __call__( + self, + hidden_states: mx.array, + block_states: mx.array | None, + *, + cache: Any | None = None, + conv_mask: mx.array | None = None, + messages: 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, messages + ) + 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, :] + if messages is not None: + hidden_states = self.mlp_message_gate(hidden_states, messages[..., 3, :]) + 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 + if getattr(conv, "record_windows", False): + # A speculative verify keeps the windows: the rollback sets the + # states to the last accepted token. + conv.windows = list(conv_states) + 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, messages + ): + dtype = hidden_states.dtype + if attention_inputs is not None: + hidden_states = attention_inputs[..., 0, :] + if messages is None: + states = (self.input_layernorm(hidden_states).astype(dtype),) * 3 + else: + states = self._mix_messages((hidden_states,) * 3, messages) + states = [self.input_layernorm(s).astype(dtype) for s in states] + return self.self_attn( + *states, + 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, messages + ): + 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) + ) + if messages is not None: + query_states, key_states, value_states = self._mix_messages( + (query_states, key_states, value_states), messages + ) + 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..ed8f5d8ee --- /dev/null +++ b/mlx_lm/models/inkling2/model.py @@ -0,0 +1,417 @@ +# 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.dspark import DSpark, DSparkArgs +from mlx_lm.models.inkling2.layers import ( + BlockAttentionResidual, + DecoderLayer, + FullDecoderLayer, + MessageInput, + ShortConvolution, + SlidingDecoderLayer, + unweighted_rms_norm, +) +from mlx_lm.models.inkling2.vision import VisionModel +from mlx_lm.models.muse_spark 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) + if args.loop_config is not None: + self.message_input = MessageInput(args.hidden_size, len(args.loop_core)) + + def embed(self, inputs: mx.array) -> mx.array: + return self.embed_norm(self.embed_tokens(inputs)) + + @property + def layer_visits(self) -> list[DecoderLayer]: + if self.args.loop_config is None: + return self.pipeline_layers + core = self.args.loop_core + passes = self.args.loop_config["num_passes"] + layers = self.layers + return ( + layers[: core.start] + + layers[core.start : core.stop] * passes + + layers[core.stop :] + ) + + def pipeline(self, group, split=None) -> None: + if self.args.loop_config is not None: + raise ValueError("Pipeline parallel does not support looped models.") + super().pipeline(group, split) + + def _run_loop(self, hidden_states, cache, conv_mask, tap): + core = self.args.loop_core + caches = iter(cache) + + def run(layers, hidden_states, block_states, bank=None): + for i, layer in enumerate(layers): + tap(hidden_states) + messages = None if bank is None else self.message_input(bank, i) + hidden_states, block_states = layer( + hidden_states, + block_states, + cache=next(caches), + conv_mask=conv_mask, + messages=messages, + ) + return hidden_states, block_states + + prelude = run(self.layers[: core.start], hidden_states, None) + hidden_states, block_states = prelude + for loop_pass in range(self.args.loop_config["num_passes"]): + bank = None + if loop_pass > 0: + bank = ( + block_states[prelude[1].shape[0] + 1 :], + unweighted_rms_norm(hidden_states.astype(mx.float32)), + ) + hidden_states, block_states = prelude + hidden_states, block_states = run( + self.layers[core.start : core.stop], hidden_states, block_states, bank + ) + return run(self.layers[core.stop :], hidden_states, block_states) + + def __call__( + self, + inputs: mx.array, + cache: list[Any] | None = None, + input_embeddings: mx.array | None = None, + capture: list[int] | None = None, + ) -> mx.array | tuple[mx.array, list[mx.array]]: + """capture: layer visits (the loop's passes counted) whose input + hidden states are returned too; the number of visits is the output.""" + taps, visit = [], [0] + + def tap(hidden_states): + if capture is not None and visit[0] in capture: + taps.append(hidden_states) + visit[0] += 1 + + 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(self.layer_visits) + 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:] + + if self.args.loop_config is None: + for layer, c in zip(layers, cache): + tap(hidden_states) + hidden_states, block_states = layer( + hidden_states, block_states, cache=c, conv_mask=conv_mask + ) + else: + hidden_states, block_states = self._run_loop( + hidden_states, cache, conv_mask, tap + ) + + 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] + if capture is None: + return hidden_states + tap(hidden_states) + return hidden_states, taps + + +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 + # The DSpark draft (mtp.safetensors); sanitize drops it without weights. + if args.mtp_config and args.mtp_config.get("markov_head_type") == "rnn_hidden": + self.dspark = DSpark(DSparkArgs.from_dict(args.mtp_config), text.vocab_size) + + 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 + ) + return self.logits(hidden_states) + + def logits(self, hidden_states: mx.array) -> mx.array: + 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 forward_features( + self, inputs: mx.array, cache: list[Any], *, all_logits: bool = False + ) -> tuple[mx.array, mx.array]: + """Logits (of the last position only unless all_logits) and the DSpark + target features (B, L, taps, hidden) of every position.""" + hidden, taps = self.model.language_model( + inputs, cache=cache, capture=self.dspark.args.target_layer_ids + ) + if not all_logits: + hidden = hidden[:, -1:] + return self.logits(hidden), mx.stack(taps, axis=2) + + def draft(self, token, position, last_features, draft_cache, k: int): + """k DSpark draft tokens after `token` at `position`.""" + lm = self.model.language_model + anchor = lm.embed(token.reshape(1, 1)) + return self.dspark.draft( + token, anchor, position, last_features, draft_cache, self.logits, k + ) + + @staticmethod + def record_conv_windows(cache: list[Any], on: bool): + """On: the next forward keeps its convolution windows (until the + next forward recorded) for rollback_speculative_cache.""" + for c in cache: + c[1].record_windows = on + + @staticmethod + def rollback_speculative_cache(cache: list[Any], keep: int, held: int): + """Of the tokens of the last recorded forward, the cache holds the + first `held`: keep the first `keep`. The key/value caches lose the + rest (exact also past the sliding window: the multi-token forward + left the rotating buffer in temporal order), the convolution states + are taken from the recorded windows.""" + from mlx_lm.generate import _gemma4_trim_cache + + drop = held - keep + if drop <= 0: + return + _gemma4_trim_cache([c[0] for c in cache], drop) + for c in cache: + conv = c[1] + n = conv[0].shape[1] + for i, window in enumerate(conv.windows): + conv[i] = mx.contiguous(window[:, keep : keep + n]) + + def sanitize(self, weights: dict[str, mx.array]) -> dict[str, mx.array]: + # The draft: mtp.* as published, dspark.* once converted. + draft = {k: v for k, v in weights.items() if k.startswith(("mtp.", "dspark."))} + weights = {k: v for k, v in weights.items() if k not in draft} + if not draft and "dspark" in self: + del self["dspark"] + weights = checkpoint.sanitize(self, weights) + if "dspark" in self: + for k, v in draft.items(): + weights["dspark." + k.split(".", 1)[1]] = v + return 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: + # The draft's recurrence stays float, as the reference's fp32 path. + return not path.startswith("model.vision_tower.") and not ( + "_message_gate." in path + or path.endswith(("rnn_proj", "markov_head.hidden_out")) + ) + + 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", + ".forget_gate_proj.weight", + ".message_gate_proj.weight", + ) + ) + + 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.model.language_model.layer_visits + ] diff --git a/mlx_lm/models/inkling2/processor.py b/mlx_lm/models/inkling2/processor.py new file mode 100644 index 000000000..b3db194ca --- /dev/null +++ b/mlx_lm/models/inkling2/processor.py @@ -0,0 +1,88 @@ +# Copyright © 2026 Apple Inc. + +"""Image processor of Inkling 2.""" + +import math +from dataclasses import dataclass +from typing import BinaryIO, ClassVar, Sequence + +import mlx.core as mx +import numpy as np + +__all__ = [ + "IMAGE_TOKEN", + "Processor", +] + +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 + + 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 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." + 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, dict[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": 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/mlx_lm/processors/__init__.py b/mlx_lm/processors/__init__.py index 9790bba33..84e0d7012 100644 --- a/mlx_lm/processors/__init__.py +++ b/mlx_lm/processors/__init__.py @@ -2,21 +2,22 @@ """Image processors of multimodal models, one module per model.""" -from mlx import nn +from mlx_lm.models.inkling2 import processor as inkling2 +from mlx_lm.utils import model_package from . import muse_spark -# The processor of each model module. +# The processor of each model package. PROCESSORS = { + "inkling2": inkling2.Processor, "muse_spark": muse_spark.Processor, } -def load_processor(model: nn.Module, config: dict) -> muse_spark.Processor | None: +def load_processor(config: dict): """The processor of a model, or None.""" if not config.get("vision_config"): return None - model_module = type(model).__module__.rsplit(".", 1)[-1] - name = config.get("processor_type", model_module) + name = config.get("processor_type", model_package(config)) processor = PROCESSORS.get(name) return processor.from_config(config) if processor else None diff --git a/mlx_lm/utils.py b/mlx_lm/utils.py index 43dfc3c6b..3ef3d618e 100644 --- a/mlx_lm/utils.py +++ b/mlx_lm/utils.py @@ -64,6 +64,7 @@ "qwen3_5_text": "qwen3_5", "qwen3_5_moe_text": "qwen3_5_moe", "nemotron_h_puzzle": "nemotron_h", + "inkling2_loop": "inkling2", } MODEL_ARCHITECTURE_REMAPPING = { @@ -366,6 +367,19 @@ def _transform_compressed_tensors_int4_weights( return new_weights, {"group_size": group_size, "bits": bits, "mode": "affine"} +def model_package(config: dict) -> str: + """The package in ``mlx_lm.models`` of the model of a configuration.""" + model_type = config["model_type"] + architectures = config.get("architectures") or () + if isinstance(architectures, str): + architectures = (architectures,) + for architecture in architectures: + remapped = MODEL_ARCHITECTURE_REMAPPING.get((model_type, architecture)) + if remapped is not None: + return remapped + return MODEL_REMAPPING.get(model_type, model_type) + + def _get_classes(config: dict): """ Retrieve the model and model args classes based on the configuration. @@ -1644,6 +1658,8 @@ def save_config( "lfm2_vl", "lfm2-vl", "muse_spark", + "inkling2", + "inkling2_loop", ): config.pop("vision_config", None) if "quantization" in config: diff --git a/setup.py b/setup.py index 83b9bf1c5..ee6d5b1c0 100644 --- a/setup.py +++ b/setup.py @@ -3,7 +3,7 @@ import sys from pathlib import Path -from setuptools import setup +from setuptools import find_packages, setup package_dir = Path(__file__).parent / "mlx_lm" sys.path.append(str(package_dir)) @@ -35,14 +35,8 @@ # uses HF's PIL-backed Gemma 4 image processor; no torch needed). "pillow", ], - packages=[ - "mlx_lm", - "mlx_lm.models", - "mlx_lm.quant", - "mlx_lm.tuner", - "mlx_lm.tool_parsers", - "mlx_lm.chat_templates", - ], + # Every subpackage; mlx_lm.quant has no __init__.py. + packages=sorted({*find_packages(include=["mlx_lm", "mlx_lm.*"]), "mlx_lm.quant"}), python_requires=">=3.8", extras_require={ "test": ["datasets", "lm-eval"], diff --git a/tests/models/test_inkling2.py b/tests/models/test_inkling2.py new file mode 100644 index 000000000..7bfbf38dd --- /dev/null +++ b/tests/models/test_inkling2.py @@ -0,0 +1,335 @@ +# 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.models.inkling2 import processor 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, +} + +LOOP_CONFIG = { + **CONFIG, + "model_type": "inkling2_loop", + "text_config": { + **CONFIG["text_config"], + "loop_config": { + "core_start": 3, + "core_end": 6, + "num_passes": 3, + "gate_rank": 8, + "is_varloop": False, + }, + }, +} + +UNPADDED_VOCAB = CONFIG["text_config"]["unpadded_vocab_size"] + + +def create_model(vision: bool = False, config: dict = CONFIG) -> 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"\.q_message_gate\.", ".controllers.attn."), + (r"\.(k|v|mlp)_message_gate\.", r".controllers.\1."), + (r"(\.controllers\.\w+)\.down_proj\.weight$", r"\1.down_weight"), + (r"(\.controllers\.\w+)\.forget_gate_proj\.weight$", r"\1.forget_weight"), + (r"(\.controllers\.\w+)\.message_gate_proj\.weight$", r"\1.gain_weight"), + (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 k.endswith(".message_input.query"): + q, kv = mx.concatenate([v[:, :1], v[:, 3:]], axis=1), v[:, 1:3] + ckpt["model.llm.middle_cycle_cross_pass_queries"] = q.flatten(0, 1) + ckpt["model.llm.middle_cycle_cross_pass_kv_queries"] = kv.flatten(0, 1) + continue + 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_loop(self): + model = create_model(config=LOOP_CONFIG) + quantize_experts(model) + tokens = mx.random.randint(0, UNPADDED_VOCAB, (2, 20)) + full = model(tokens) + + cache = model.make_cache() + self.assertEqual(len(cache), 14) + 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) + ) + + with tempfile.TemporaryDirectory() as path: + path = Path(path) + mx.save_safetensors(str(path / "model.safetensors"), checkpoint(model)) + (path / "config.json").write_text(json.dumps(LOOP_CONFIG)) + loaded, _ = load_model(path) + self.assertTrue(mx.allclose(loaded(tokens), full, 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))) + + 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, media_inputs = processor(f"A {token} B", images=[image]) + self.assertEqual(text, f"A {token * 4} B") + 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(config) + self.assertIsInstance(processor, inkling2_processor.Processor) + self.assertEqual(processor.block_size, 4) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/models/test_inkling2_dspark.py b/tests/models/test_inkling2_dspark.py new file mode 100644 index 000000000..1147fd744 --- /dev/null +++ b/tests/models/test_inkling2_dspark.py @@ -0,0 +1,132 @@ +# Copyright © 2026 IPSupport LLC + +import unittest + +import mlx.core as mx +from mlx.utils import tree_flatten + +from mlx_lm.generate import dspark_generate_step, generate_step +from mlx_lm.models.cache import make_prompt_cache + +from .test_inkling2 import LOOP_CONFIG, create_model + +# 8 layers, layers 3-5 looped 3 times: 14 layer visits, 14 is the output. +MTP_CONFIG = { + "hidden_size": 64, + "num_hidden_layers": 3, + "num_attention_heads": 4, + "num_key_value_heads": 2, + "head_dim": 16, + "intermediate_size": 96, + "rms_norm_eps": 1e-6, + "rope_theta": 10000.0, + "local_layer_ids": [0, 2], + "sliding_window_size": 8, + "block_size": 5, + "markov_rank": 8, + "markov_head_type": "rnn_hidden", + "target_layer_ids": [2, 6, 11, 14], +} +CONFIG = {**LOOP_CONFIG, "mtp_config": MTP_CONFIG} + + +def plain(model, prompt, n): + out = [] + for tok, _ in generate_step(prompt, model, max_tokens=n): + out.append(tok) + return out + + +class TestInkling2DSpark(unittest.TestCase): + def setUp(self): + self.model = create_model(config=CONFIG) + self.prompt = mx.random.randint(0, 120, (20,), key=mx.random.key(1)) + + def test_features(self): + cache = make_prompt_cache(self.model) + logits, features = self.model.forward_features(self.prompt[None], cache) + self.assertEqual(features.shape, (1, 20, 4, 64)) + hidden = self.model.model.language_model(self.prompt[None]) + self.assertTrue(mx.allclose(features[:, :, -1], hidden, atol=1e-5)) + self.assertTrue( + mx.allclose(logits[0, -1], self.model(self.prompt[None])[0, -1], atol=1e-4) + ) + + def test_greedy_matches_plain(self): + want = plain(self.model, self.prompt, 30) + got = [ + t + for t, _, _ in dspark_generate_step( + self.prompt, self.model, max_tokens=30, adaptive=False + ) + ] + self.assertEqual(got, want) + + def test_partial_acceptance(self): + want = plain(self.model, self.prompt, 40) + calls = [] + + def oracle(token, position, last_features, draft_cache, k): + # The true continuation, wrong from a varying position on. + start = position - len(self.prompt) + 1 + drafts = want[start : start + k] + [0] * k + drafts = drafts[:k] + wrong = len(calls) % (k + 1) + if wrong < k: + drafts[wrong] = (drafts[wrong] + 1) % 120 + calls.append(wrong) + return mx.array([drafts]) + + self.model.draft = oracle + got, from_draft = [], 0 + for t, _, d in dspark_generate_step( + self.prompt, self.model, max_tokens=40, adaptive=False + ): + got.append(t) + from_draft += d + self.assertEqual(got, want) + self.assertGreater(from_draft, 10) + + def test_cache_after_early_stop(self): + want = plain(self.model, self.prompt, 40) + + def oracle(token, position, last_features, draft_cache, k): + start = position - len(self.prompt) + 1 + return mx.array([(want[start : start + k] + [0] * k)[:k]]) + + self.model.draft = oracle + for n in (5, 9, 14): + cache = make_prompt_cache(self.model) + got = [ + t + for t, _, _ in dspark_generate_step( + self.prompt, + self.model, + max_tokens=n, + prompt_cache=cache, + adaptive=False, + ) + ] + self.assertEqual(got, want[:n]) + # The cache holds prompt + yielded tokens: the next step is plain's. + nxt = self.model(mx.array([[want[n]]]), cache=cache) + full = mx.concatenate([self.prompt, mx.array(want[: n + 1])]) + self.assertTrue( + mx.allclose(nxt[0, -1], self.model(full[None])[0, -1], atol=1e-3), + f"stop after {n}", + ) + + def test_sanitize_drops_or_keeps_draft(self): + weights = dict(tree_flatten(self.model.parameters())) + draft = {k: v for k, v in weights.items() if k.startswith("dspark.")} + raw = {"mtp." + k.split(".", 1)[1]: v for k, v in draft.items()} + model = create_model(config=CONFIG) + out = model.sanitize(raw) + self.assertEqual(set(out), set(draft)) + model = create_model(config=CONFIG) + model.sanitize({}) + self.assertNotIn("dspark", model) + + +if __name__ == "__main__": + unittest.main()