"""MLX-LM architecture for the published WebBrain LingLoop checkpoint. The base decoder and checkpoint transforms come from MLX-LM's Bailing V3. The loop follows the publisher's LoopedBailingMoeV3ForCausalLM implementation at https://huggingface.co/webbrain-one/WebBrain-LingLoop-8B-A1.3B/blob/6cd99926f92814c991585f48254dbd172cd8d162/looped_ling3.py. This module is self-contained so it can accompany a converted checkpoint. """ import math from dataclasses import dataclass import mlx.core as mx import mlx.nn as nn from mlx_lm.models import bailing_moe_v3 from mlx_lm.models.base import create_attention_mask, create_ssm_mask from mlx_lm.models.cache import ArraysCache, KVCache @dataclass class ModelArgs(bailing_moe_v3.ModelArgs): loop_core_start: int = 4 loop_core_end: int = 20 loop_num_passes: int = 2 loop_gate_rank: int = 64 def _rms_norm_fp32(x): x = x.astype(mx.float32) return x * mx.rsqrt(mx.mean(mx.square(x), axis=-1, keepdims=True) + 1e-6) class DepthAttentionReader(nn.Module): def __init__(self, hidden_size): super().__init__() self.q = mx.zeros((hidden_size,), dtype=mx.float32) self.scale = 1.0 / math.sqrt(hidden_size) def __call__(self, previous_states, dtype): scores = mx.sum(_rms_norm_fp32(previous_states) * self.q, axis=-1) * self.scale weights = mx.softmax(scores, axis=-1) message = mx.sum(weights[..., None] * previous_states.astype(mx.float32), axis=-2) return message.astype(dtype) class CrossPassGate(nn.Module): def __init__(self, hidden_size, rank): super().__init__() self.w_down = nn.Linear(hidden_size * 2, rank, bias=False) self.w_forget = nn.Linear(rank, hidden_size, bias=False) self.w_gain = nn.Linear(rank, hidden_size, bias=False) self.w_forget.weight = mx.zeros((hidden_size, rank), dtype=mx.float32) self.w_gain.weight = mx.zeros((hidden_size, rank), dtype=mx.float32) def __call__(self, x, message): inputs = mx.concatenate((_rms_norm_fp32(x), _rms_norm_fp32(message)), axis=-1) state = self.w_down(inputs) forget = mx.tanh(self.w_forget(state)) gain = mx.tanh(self.w_gain(state)) delta = -forget * x.astype(mx.float32) + gain * message.astype(mx.float32) return x + delta.astype(x.dtype) class LoopAdapter(nn.Module): def __init__(self, num_layers, hidden_size, rank): super().__init__() self.attn_readers = [DepthAttentionReader(hidden_size) for _ in range(num_layers)] self.attn_gates = [CrossPassGate(hidden_size, rank) for _ in range(num_layers)] self.mlp_readers = [DepthAttentionReader(hidden_size) for _ in range(num_layers)] self.mlp_gates = [CrossPassGate(hidden_size, rank) for _ in range(num_layers)] def run_layer(self, index, layer, hidden, previous_states, mask, cache): # Each gate changes the sublayer input. The residual retains the ungated hidden state. message = self.attn_readers[index](previous_states, hidden.dtype) inputs = self.attn_gates[index](hidden, message) hidden = hidden + layer.attention(layer.input_layernorm(inputs), mask, cache) message = self.mlp_readers[index](previous_states, hidden.dtype) inputs = self.mlp_gates[index](hidden, message) return hidden + layer.mlp(layer.post_attention_layernorm(inputs)) class Model(bailing_moe_v3.Model): """Reuse each physical core layer across passes, with separate state slots.""" def __init__(self, args): if not 0 <= args.loop_core_start < args.loop_core_end <= args.num_hidden_layers: raise ValueError("Invalid LingLoop core layer range") if args.loop_num_passes < 1 or args.loop_gate_rank < 1: raise ValueError("LingLoop pass count and gate rank must be positive") super().__init__(args) self._core_layers = range(args.loop_core_start, args.loop_core_end) self._num_slots = len(self.layers) + (args.loop_num_passes - 1) * len(self._core_layers) self.loop_adapter = LoopAdapter(len(self._core_layers), args.hidden_size, args.loop_gate_rank) def make_cache(self): cache = super().make_cache() for _ in range(1, self.args.loop_num_passes): for index in self._core_layers: cache.append(ArraysCache(size=4) if self.layers[index].is_linear else KVCache()) return cache @property def quant_predicate(self): base_predicate = super().quant_predicate def predicate(path, module): return not path.startswith("loop_adapter.") and base_predicate(path, module) return predicate def __call__(self, tokens, cache=None): physical = self.layers if cache is None: cache = [None] * self._num_slots elif len(cache) != self._num_slots: raise ValueError(f"LingLoop requires {self._num_slots} cache slots, got {len(cache)}") model = self.model hidden = model.word_embeddings(tokens) # All passes see the same token positions. Compute masks before updating slots. attention_mask = None linear_mask = None if model.attention_index is not None: attention_mask = create_attention_mask(hidden, cache[model.attention_index], return_array=True) if model.linear_index is not None: linear_mask = create_ssm_mask(hidden, cache[model.linear_index]) for index in range(self._core_layers.start): layer = physical[index] mask = linear_mask if layer.is_linear else attention_mask hidden = layer(hidden, mask, cache[index]) prelude = hidden previous_states = None for pass_index in range(self.args.loop_num_passes): hidden = prelude states = [] for core_index, index in enumerate(self._core_layers): layer = physical[index] mask = linear_mask if layer.is_linear else attention_mask if pass_index == 0: hidden = layer(hidden, mask, cache[index]) else: slot = len(physical) + (pass_index - 1) * len(self._core_layers) + core_index hidden = self.loop_adapter.run_layer(core_index, layer, hidden, previous_states, mask, cache[slot]) if pass_index + 1 < self.args.loop_num_passes: states.append(hidden) if states: previous_states = mx.stack(states, axis=-2) for index in range(self._core_layers.stop, len(physical)): layer = physical[index] mask = linear_mask if layer.is_linear else attention_mask hidden = layer(hidden, mask, cache[index]) hidden = model.norm(hidden) if self.lm_head is None: return model.word_embeddings.as_linear(hidden) return self.lm_head(hidden)