"""Qwen3.5 text backbone used by Clairic and Clairic-flash. The layer math follows the Hugging Face Qwen3.5 implementation: RMSNorm is (1 + weight), full-attention layers have an output gate, and linear-attention layers are a gated delta net. Recurrence matches the reference PyTorch loop (state layout [batch, heads, key_dim, value_dim]). """ from __future__ import annotations from dataclasses import dataclass, field from typing import Any import mlx.core as mx import mlx.nn as nn from clairic_mlx.nnutil import ( apply_rope, as_f32, causal_depthwise_conv, gated_rms, l2norm_fla, rms_qwen, ) @dataclass class TextConfig: hidden_size: int = 4096 intermediate_size: int = 12288 num_hidden_layers: int = 32 num_attention_heads: int = 16 num_key_value_heads: int = 4 head_dim: int = 256 rms_norm_eps: float = 1e-6 vocab_size: int = 248320 max_position_embeddings: int = 262144 attention_bias: bool = False hidden_act: str = "silu" linear_conv_kernel_dim: int = 4 linear_key_head_dim: int = 128 linear_num_key_heads: int = 16 linear_num_value_heads: int = 32 linear_value_head_dim: int = 128 rope_theta: float = 10_000_000.0 partial_rotary_factor: float = 0.25 mrope_section: tuple[int, int, int] = (11, 11, 10) layer_types: list[str] = field(default_factory=list) tie_word_embeddings: bool = False def __post_init__(self) -> None: if not self.layer_types: self.layer_types = [ "linear_attention" if (i + 1) % 4 else "full_attention" for i in range(self.num_hidden_layers) ] if len(self.layer_types) != self.num_hidden_layers: raise ValueError("layer_types must match num_hidden_layers") @classmethod def from_dict(cls, text: dict[str, Any]) -> TextConfig: rope = text.get("rope_parameters") or {} section = rope.get("mrope_section") or [11, 11, 10] return cls( hidden_size=int(text["hidden_size"]), intermediate_size=int(text["intermediate_size"]), num_hidden_layers=int(text["num_hidden_layers"]), num_attention_heads=int(text["num_attention_heads"]), num_key_value_heads=int(text["num_key_value_heads"]), head_dim=int(text.get("head_dim") or text["hidden_size"] // text["num_attention_heads"]), rms_norm_eps=float(text.get("rms_norm_eps", 1e-6)), vocab_size=int(text["vocab_size"]), max_position_embeddings=int(text.get("max_position_embeddings", 262144)), attention_bias=bool(text.get("attention_bias", False)), hidden_act=str(text.get("hidden_act", "silu")), linear_conv_kernel_dim=int(text.get("linear_conv_kernel_dim", 4)), linear_key_head_dim=int(text.get("linear_key_head_dim", 128)), linear_num_key_heads=int(text.get("linear_num_key_heads", 16)), linear_num_value_heads=int(text.get("linear_num_value_heads", 32)), linear_value_head_dim=int(text.get("linear_value_head_dim", 128)), rope_theta=float(rope.get("rope_theta", 10_000_000.0)), partial_rotary_factor=float(rope.get("partial_rotary_factor", 0.25)), mrope_section=(int(section[0]), int(section[1]), int(section[2])), layer_types=list(text.get("layer_types") or []), tie_word_embeddings=bool(text.get("tie_word_embeddings", False)), ) class MLP(nn.Module): def __init__(self, hidden: int, intermediate: int) -> None: super().__init__() self.gate_proj = nn.Linear(hidden, intermediate, bias=False) self.up_proj = nn.Linear(hidden, intermediate, bias=False) self.down_proj = nn.Linear(intermediate, hidden, bias=False) def __call__(self, x: mx.array) -> mx.array: gate = nn.silu(as_f32(self.gate_proj(x))) up = as_f32(self.up_proj(x)) return self.down_proj((gate * up).astype(x.dtype)) def _append_kv(cache: dict, key: mx.array, value: mx.array) -> tuple[mx.array, mx.array]: """Grow the KV cache by doubling so decode copies stay amortized. key/value are [B, H, T, D]. The stored buffers may be longer than the filled prefix; ``length`` is the number of valid positions. """ incoming = key.shape[2] if "k" not in cache: capacity = incoming if incoming > 1 else max(256, incoming) buf_k = mx.zeros((key.shape[0], key.shape[1], capacity, key.shape[3]), dtype=key.dtype) buf_v = mx.zeros((value.shape[0], value.shape[1], capacity, value.shape[3]), dtype=value.dtype) cache["k"] = mx.slice_update(buf_k, key, mx.array([0]), (2,)) cache["v"] = mx.slice_update(buf_v, value, mx.array([0]), (2,)) cache["length"] = incoming return cache["k"][:, :, :incoming], cache["v"][:, :, :incoming] filled = int(cache["length"]) capacity = cache["k"].shape[2] if filled + incoming > capacity: capacity = max(capacity * 2, filled + incoming) grown_k = mx.zeros((key.shape[0], key.shape[1], capacity, key.shape[3]), dtype=key.dtype) grown_v = mx.zeros((value.shape[0], value.shape[1], capacity, value.shape[3]), dtype=value.dtype) cache["k"] = mx.slice_update(grown_k, cache["k"][:, :, :filled], mx.array([0]), (2,)) cache["v"] = mx.slice_update(grown_v, cache["v"][:, :, :filled], mx.array([0]), (2,)) cache["k"] = mx.slice_update(cache["k"], key, mx.array([filled]), (2,)) cache["v"] = mx.slice_update(cache["v"], value, mx.array([filled]), (2,)) cache["length"] = filled + incoming return cache["k"][:, :, : cache["length"]], cache["v"][:, :, : cache["length"]] class Attention(nn.Module): def __init__(self, config: TextConfig) -> None: super().__init__() self.num_heads = config.num_attention_heads self.num_kv_heads = config.num_key_value_heads self.head_dim = config.head_dim self.scale = self.head_dim**-0.5 self.eps = config.rms_norm_eps bias = config.attention_bias self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.head_dim * 2, bias=bias) self.k_proj = nn.Linear(config.hidden_size, self.num_kv_heads * self.head_dim, bias=bias) self.v_proj = nn.Linear(config.hidden_size, self.num_kv_heads * self.head_dim, bias=bias) self.o_proj = nn.Linear(self.num_heads * self.head_dim, config.hidden_size, bias=bias) self.q_norm_weight = mx.zeros((self.head_dim,)) self.k_norm_weight = mx.zeros((self.head_dim,)) def __call__( self, x: mx.array, cos: mx.array, sin: mx.array, cache: dict[str, mx.array] | None = None, ) -> mx.array: batch, length, _ = x.shape query, gate = mx.split( self.q_proj(x).reshape(batch, length, self.num_heads, self.head_dim * 2), 2, axis=-1, ) gate = gate.reshape(batch, length, -1) query = rms_qwen(query, self.q_norm_weight, self.eps).transpose(0, 2, 1, 3) key = self.k_proj(x).reshape(batch, length, self.num_kv_heads, self.head_dim) key = rms_qwen(key, self.k_norm_weight, self.eps).transpose(0, 2, 1, 3) value = self.v_proj(x).reshape(batch, length, self.num_kv_heads, self.head_dim) value = value.transpose(0, 2, 1, 3) query, key = apply_rope(query, key, cos, sin) if cache is not None: key, value = _append_kv(cache, key, value) # Fused attention. GQA keys stay untiled. "causal" is lower-right aligned, # so a single new query attends to the whole cache. out = mx.fast.scaled_dot_product_attention( query, key, value, scale=self.scale, mask="causal" ) out = out.transpose(0, 2, 1, 3).reshape(batch, length, -1) out = out * mx.sigmoid(gate.astype(out.dtype)) return self.o_proj(out.astype(x.dtype)) class GatedDeltaNet(nn.Module): def __init__(self, config: TextConfig) -> None: super().__init__() self.num_k_heads = config.linear_num_key_heads self.num_v_heads = config.linear_num_value_heads self.head_k_dim = config.linear_key_head_dim self.head_v_dim = config.linear_value_head_dim self.key_dim = self.head_k_dim * self.num_k_heads self.value_dim = self.head_v_dim * self.num_v_heads self.conv_dim = self.key_dim * 2 + self.value_dim self.kernel = config.linear_conv_kernel_dim self.eps = config.rms_norm_eps hidden = config.hidden_size self.in_proj_qkv = nn.Linear(hidden, self.conv_dim, bias=False) self.in_proj_z = nn.Linear(hidden, self.value_dim, bias=False) self.in_proj_b = nn.Linear(hidden, self.num_v_heads, bias=False) self.in_proj_a = nn.Linear(hidden, self.num_v_heads, bias=False) self.conv1d_weight = mx.zeros((self.conv_dim, 1, self.kernel)) self.dt_bias = mx.ones((self.num_v_heads,)) self.A_log = mx.zeros((self.num_v_heads,)) self.norm_weight = mx.ones((self.head_v_dim,)) self.out_proj = nn.Linear(self.value_dim, hidden, bias=False) def _split(self, mixed: mx.array) -> tuple[mx.array, mx.array, mx.array]: batch, _, length = mixed.shape seq = mixed.transpose(0, 2, 1) query, key, value = mx.split(seq, [self.key_dim, 2 * self.key_dim], axis=-1) query = query.reshape(batch, length, self.num_k_heads, self.head_k_dim) key = key.reshape(batch, length, self.num_k_heads, self.head_k_dim) value = value.reshape(batch, length, self.num_v_heads, self.head_v_dim) query = l2norm_fla(as_f32(query)) * (self.head_k_dim**-0.5) key = l2norm_fla(as_f32(key)) return query.astype(mx.float32), key.astype(mx.float32), as_f32(value) def __call__( self, x: mx.array, cache: dict[str, mx.array] | None = None, ) -> mx.array: batch, length, _ = x.shape pre = as_f32(self.in_proj_qkv(x)).transpose(0, 2, 1) z = self.in_proj_z(x).reshape(batch, length, self.num_v_heads, self.head_v_dim) beta = mx.sigmoid(as_f32(self.in_proj_b(x))) a = as_f32(self.in_proj_a(x)) g = -mx.exp(as_f32(self.A_log)) * nn.softplus(a + as_f32(self.dt_bias)) left = None if cache is None else cache.get("conv") mixed = nn.silu(causal_depthwise_conv(pre, self.conv1d_weight, left)) if cache is not None: history = pre if left is None else mx.concatenate([left, pre], axis=-1) cache["conv"] = history[:, :, -(self.kernel - 1) :] query, key, value = self._split(mixed) state = None if cache is None else cache.get("state") # gamma is the decay multiplier, exp(g). The fused kernel's state is # [B, Hv, Dv, Dk], the transpose of the explicit recurrence. if state is not None: state = state.transpose(0, 1, 3, 2) out, state = mx.fast.gated_delta_update( query, key, value, gamma=mx.exp(g), beta=beta, initial_state=state ) state = state.transpose(0, 1, 3, 2) if cache is not None: cache["state"] = state out = gated_rms( out.reshape(-1, self.head_v_dim), self.norm_weight, as_f32(z).reshape(-1, self.head_v_dim), self.eps, ) out = out.reshape(batch, length, -1) return self.out_proj(out.astype(x.dtype)) def recurrent_delta( query: mx.array, key: mx.array, value: mx.array, g: mx.array, beta: mx.array, state: mx.array | None, ) -> tuple[mx.array, mx.array]: """Token-wise gated delta rule. query/key: [B, T, H, Dk], value: [B, T, H, Dv], g/beta: [B, T, H]. state: [B, H, Dk, Dv]. """ batch, length, heads, key_dim = key.shape value_dim = value.shape[-1] if state is None: state = mx.zeros((batch, heads, key_dim, value_dim), dtype=mx.float32) outs = [] for t in range(length): q_t = query[:, t].transpose(0, 1, 2) k_t = key[:, t].transpose(0, 1, 2) v_t = value[:, t].transpose(0, 1, 2) g_t = mx.exp(g[:, t])[:, :, None, None] beta_t = beta[:, t][:, :, None] state = state * g_t kv = mx.sum(state * k_t[:, :, :, None], axis=-2) delta = (v_t - kv) * beta_t state = state + k_t[:, :, :, None] * delta[:, :, None, :] y = mx.sum(state * q_t[:, :, :, None], axis=-2) outs.append(y) return mx.stack(outs, axis=1), state class DecoderLayer(nn.Module): def __init__(self, config: TextConfig, layer_idx: int) -> None: super().__init__() self.layer_type = config.layer_types[layer_idx] self.is_linear = self.layer_type == "linear_attention" if self.is_linear: self.linear_attn = GatedDeltaNet(config) else: self.self_attn = Attention(config) self.mlp = MLP(config.hidden_size, config.intermediate_size) self.input_layernorm_weight = mx.zeros((config.hidden_size,)) self.post_attention_layernorm_weight = mx.zeros((config.hidden_size,)) self.eps = config.rms_norm_eps def __call__( self, x: mx.array, cos: mx.array, sin: mx.array, cache: dict[str, mx.array] | None = None, ) -> mx.array: residual = x normed = rms_qwen(x, self.input_layernorm_weight, self.eps) if self.is_linear: mixed = self.linear_attn(normed, cache) else: mixed = self.self_attn(normed, cos, sin, cache) hidden = (as_f32(residual) + as_f32(mixed)).astype(x.dtype) residual = hidden mixed = self.mlp(rms_qwen(hidden, self.post_attention_layernorm_weight, self.eps)) return (as_f32(residual) + as_f32(mixed)).astype(x.dtype) class TextModel(nn.Module): def __init__(self, config: TextConfig) -> None: super().__init__() self.config = config self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size) self.layers = [DecoderLayer(config, i) for i in range(config.num_hidden_layers)] self.norm_weight = mx.zeros((config.hidden_size,)) rotary = int(config.head_dim * config.partial_rotary_factor) inv = 1.0 / ( config.rope_theta ** (mx.arange(0, rotary, 2, dtype=mx.float32) / float(rotary)) ) self._inv_freq = inv self._rotary = rotary self._mrope = config.mrope_section def rope(self, position_ids: mx.array) -> tuple[mx.array, mx.array]: """position_ids: [T], [B, T], or [3, B, T]. Returns cos/sin [B, T, rotary].""" if position_ids.ndim == 1: position_ids = mx.expand_dims(position_ids, 0) if position_ids.ndim == 2: position_ids = mx.stack([position_ids, position_ids, position_ids], axis=0) # freqs: [3, B, T, rotary/2] pos = position_ids.astype(mx.float32)[..., None] freqs = pos * self._inv_freq.reshape(1, 1, 1, -1) freqs = interleaved_mrope(freqs, self._mrope) emb = mx.concatenate([freqs, freqs], axis=-1) return mx.cos(emb), mx.sin(emb) def __call__( self, input_ids: mx.array | None = None, inputs_embeds: mx.array | None = None, cache: list[dict[str, mx.array] | None] | None = None, position_ids: mx.array | None = None, ) -> mx.array: if (input_ids is None) == (inputs_embeds is None): raise ValueError("Pass exactly one of input_ids or inputs_embeds") hidden = self.embed_tokens(input_ids) if inputs_embeds is None else inputs_embeds batch, length, _ = hidden.shape offset = 0 if cache is not None: for layer_cache in cache: if layer_cache is not None and "length" in layer_cache: offset = int(layer_cache["length"]) break if position_ids is None: position_ids = mx.arange(offset, offset + length) cos, sin = self.rope(position_ids) if cos.shape[0] == 1 and batch > 1: cos = mx.broadcast_to(cos, (batch, cos.shape[1], cos.shape[2])) sin = mx.broadcast_to(sin, (batch, sin.shape[1], sin.shape[2])) if cache is None: cache = [None] * len(self.layers) for layer, layer_cache in zip(self.layers, cache): hidden = layer(hidden, cos, sin, layer_cache) return rms_qwen(hidden, self.norm_weight, self.layers[0].eps) def make_cache(self) -> list[dict[str, mx.array]]: return [{} for _ in self.layers] def interleaved_mrope(freqs: mx.array, sections: tuple[int, int, int]) -> mx.array: """freqs [3, B, T, half] -> [B, T, half], interleaved over H and W.""" out = freqs[0] half = out.shape[-1] for dim, offset in ((1, 1), (2, 2)): length = min(sections[dim] * 3, half) indices = list(range(offset, length, 3)) if not indices: continue idx = mx.array(indices) piece = mx.take(freqs[dim], idx, axis=-1) parts = [] cursor = 0 for slot, value_index in enumerate(indices): if value_index > cursor: parts.append(out[..., cursor:value_index]) parts.append(piece[..., slot : slot + 1]) cursor = value_index + 1 if cursor < half: parts.append(out[..., cursor:]) out = mx.concatenate(parts, axis=-1) return out class CausalLM(nn.Module): def __init__(self, config: TextConfig) -> None: super().__init__() self.config = config self.model = TextModel(config) self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) def __call__( self, input_ids: mx.array | None = None, inputs_embeds: mx.array | None = None, cache: list[dict[str, mx.array] | None] | None = None, position_ids: mx.array | None = None, ) -> mx.array: hidden = self.model( input_ids=input_ids, inputs_embeds=inputs_embeds, cache=cache, position_ids=position_ids, ) return self.lm_head(hidden) def hidden_states( self, input_ids: mx.array | None = None, inputs_embeds: mx.array | None = None, position_ids: mx.array | None = None, ) -> mx.array: return self.model( input_ids=input_ids, inputs_embeds=inputs_embeds, position_ids=position_ids, )