diff --git a/mlx_lm/models/inkling2/checkpoint.py b/mlx_lm/models/inkling2/checkpoint.py index b2a9dd3dd..6438b0c29 100644 --- a/mlx_lm/models/inkling2/checkpoint.py +++ b/mlx_lm/models/inkling2/checkpoint.py @@ -28,6 +28,11 @@ (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."), @@ -65,6 +70,7 @@ def _rename(key: str) -> str: 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.")): @@ -73,7 +79,16 @@ def sanitize(model, weights: dict[str, mx.array]) -> dict[str, mx.array]: v = v.swapaxes(1, 2) if k.startswith("model.vision_tower.") and model.args.vision is None: continue - if k.endswith(".mlp.gate.weight"): + 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() @@ -89,6 +104,14 @@ def sanitize(model, weights: dict[str, mx.array]) -> dict[str, mx.array]: 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 diff --git a/mlx_lm/models/inkling2/config.py b/mlx_lm/models/inkling2/config.py index 847906827..a82e69fe8 100644 --- a/mlx_lm/models/inkling2/config.py +++ b/mlx_lm/models/inkling2/config.py @@ -41,6 +41,11 @@ class TextArgs(BaseModelArgs): 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 diff --git a/mlx_lm/models/inkling2/layers.py b/mlx_lm/models/inkling2/layers.py index 3eeab0755..2b0220356 100644 --- a/mlx_lm/models/inkling2/layers.py +++ b/mlx_lm/models/inkling2/layers.py @@ -23,6 +23,8 @@ "FullAttention", "FullDecoderLayer", "L2Clip", + "MessageGate", + "MessageInput", "RelativeLogits", "ScaledL2Clip", "ShortConvolution", @@ -99,12 +101,11 @@ def _conv_input( 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) + conv_state = mx.zeros(shape, hidden_states.dtype) return mx.concatenate([conv_state, hidden_states], axis=1) @@ -373,6 +374,8 @@ def __init__(self, args: TextArgs): def __call__( self, hidden_states: mx.array, + key_hidden_states: mx.array, + value_hidden_states: mx.array, *, cache: Any | None, conv_states: list, @@ -380,10 +383,10 @@ def __call__( ) -> mx.array: kv_cache = cache[0] if cache is not None else None key_states, conv_states[0] = self.k_sconv( - self.k_proj(hidden_states), conv_states[0], conv_mask + self.k_proj(key_hidden_states), conv_states[0], conv_mask ) value_states, conv_states[1] = self.v_sconv( - self.v_proj(hidden_states), conv_states[1], conv_mask + self.v_proj(value_hidden_states), conv_states[1], conv_mask ) return self._attend( hidden_states, @@ -541,16 +544,51 @@ def __call__( self, block_states: mx.array, partial_block_states: mx.array ) -> mx.array: dims = partial_block_states.shape[-1] - query = self.query.reshape(-1, dims).astype(mx.float32) - scale = dims**-0.5 - if _use_kernels(): - return depth_attention( - block_states, partial_block_states, query, scale=scale - ) - stacked_states = mx.concatenate([block_states, partial_block_states[None]]) - stacked_states = mx.moveaxis(stacked_states, 0, -2) - weights = mx.softmax((stacked_states @ query.T) * scale, axis=-2, precise=True) - return weights.swapaxes(-1, -2) @ stacked_states + 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): @@ -567,6 +605,20 @@ def __init__(self, args: TextArgs, layer_idx: int, *, num_queries: int): 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, @@ -575,6 +627,7 @@ def __call__( *, 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 @@ -586,7 +639,7 @@ def __call__( if self.attention_input is not None: attention_inputs = self.attention_input(block_states, normed_residual) hidden_states = self._self_attention( - hidden_states, attention_inputs, cache, conv_states, conv_mask + hidden_states, attention_inputs, cache, conv_states, conv_mask, messages ) hidden_states, conv_states[2] = self.post_attention_convolution( hidden_states, conv_states[2], conv_mask @@ -604,6 +657,8 @@ def __call__( 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) ) @@ -627,13 +682,18 @@ def __init__(self, args: TextArgs, layer_idx: int): 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 + 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( - self.input_layernorm(hidden_states).astype(dtype), + *states, cache=cache, conv_states=conv_states, conv_mask=conv_mask, @@ -650,7 +710,7 @@ def __init__(self, args: TextArgs, layer_idx: int): self.v_input_layernorm = nn.RMSNorm(args.hidden_size, eps=eps) def _self_attention( - self, hidden_states, attention_inputs, cache, conv_states, conv_mask + self, hidden_states, attention_inputs, cache, conv_states, conv_mask, messages ): dtype = hidden_states.dtype if attention_inputs is None: @@ -659,6 +719,10 @@ def _self_attention( 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), diff --git a/mlx_lm/models/inkling2/model.py b/mlx_lm/models/inkling2/model.py index 10a4b4a8c..f860c2c8c 100644 --- a/mlx_lm/models/inkling2/model.py +++ b/mlx_lm/models/inkling2/model.py @@ -15,6 +15,7 @@ BlockAttentionResidual, DecoderLayer, FullDecoderLayer, + MessageInput, ShortConvolution, SlidingDecoderLayer, unweighted_rms_norm, @@ -46,10 +47,61 @@ def __init__(self, args: TextArgs): ] 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): + core = self.args.loop_core + caches = iter(cache) + + def run(layers, hidden_states, block_states, bank=None): + for i, layer in enumerate(layers): + 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, @@ -63,7 +115,7 @@ def __call__( layers = self.pipeline_layers if cache is None: - cache = [None] * len(layers) + 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]) @@ -76,9 +128,14 @@ def __call__( states = mx.distributed.recv_like(states, rank + 1) hidden_states, block_states = states[0].astype(dtype), states[1:] - for layer, c in zip(layers, cache): - hidden_states, block_states = layer( - hidden_states, block_states, cache=c, conv_mask=conv_mask + if self.args.loop_config is None: + for layer, c in zip(layers, cache): + 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 ) if rank != 0: @@ -240,7 +297,9 @@ def part(w: mx.array, axis: int) -> mx.array: def quant_predicate(self) -> Callable[[str, nn.Module], bool]: def predicate(path: str, module: nn.Module) -> bool: - return not path.startswith("model.vision_tower.") + return not path.startswith("model.vision_tower.") and ( + "_message_gate." not in path + ) return predicate @@ -249,7 +308,13 @@ 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") + ( + ".query", + ".mlp.gate.weight", + ".mlp.gate.e_score_correction_bias", + ".forget_gate_proj.weight", + ".message_gate_proj.weight", + ) ) return predicate @@ -269,5 +334,5 @@ def make_cache(self) -> list[CacheList]: ), ArraysCache(4), ) - for layer in self.layers + for layer in self.model.language_model.layer_visits ] diff --git a/mlx_lm/utils.py b/mlx_lm/utils.py index 17c97a5ca..f540db0bb 100644 --- a/mlx_lm/utils.py +++ b/mlx_lm/utils.py @@ -62,6 +62,7 @@ "qwen3_5_moe": "qwen3_5", "qwen3_vl_moe": "qwen3_vl", "solar_open": "glm4_moe", + "inkling2_loop": "inkling2", # Package names cannot have hyphens. "lfm2-vl": "lfm2_vl", "lille-130m": "lille_130m", diff --git a/tests/model_parallel_tests.py b/tests/model_parallel_tests.py index 59c29f174..31d5542e6 100644 --- a/tests/model_parallel_tests.py +++ b/tests/model_parallel_tests.py @@ -299,12 +299,20 @@ def run(): self.assertTrue(mx.allclose(e, out, rtol=1e-3, atol=1e-3)) def test_inkling2(self): - from models.test_inkling2 import UNPADDED_VOCAB, create_model, quantize_experts + from models.test_inkling2 import ( + CONFIG, + LOOP_CONFIG, + UNPADDED_VOCAB, + create_model, + quantize_experts, + ) - for parallel in ("tensor", "pipeline"): + cases = [(CONFIG, "tensor"), (CONFIG, "pipeline"), (LOOP_CONFIG, "tensor")] + for config, parallel in cases: for quantized in (False, True): - with self.subTest(parallel=parallel, quantized=quantized): - model = create_model() + loop = config is LOOP_CONFIG + with self.subTest(parallel=parallel, quantized=quantized, loop=loop): + model = create_model(config=config) if quantized: quantize_experts(model) x = mx.random.randint(0, UNPADDED_VOCAB, shape=(2, 13)) @@ -324,6 +332,10 @@ def run(): for e, out in zip(expected, run()): self.assertTrue(mx.allclose(e, out, rtol=1e-3, atol=1e-3)) + model = create_model(config=LOOP_CONFIG) + with self.assertRaisesRegex(ValueError, "Pipeline parallel"): + model.model.pipeline(mx.distributed.init()) + def test_pipeline_layer_assignment(self): def assignment(num_layers, size, split=None): blocks = [] diff --git a/tests/models/test_inkling2.py b/tests/models/test_inkling2.py index 158badd76..7bfbf38dd 100644 --- a/tests/models/test_inkling2.py +++ b/tests/models/test_inkling2.py @@ -61,12 +61,27 @@ "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) -> inkling2.Model: +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 + 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()): @@ -106,6 +121,11 @@ def predicate(path, module): (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"), @@ -133,6 +153,11 @@ def checkpoint(model: inkling2.Model) -> dict: 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.") @@ -242,6 +267,27 @@ def test_load_checkpoint(self): 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) diff --git a/tests/test_kernels.py b/tests/test_kernels.py index eaa8faf59..2977e1d2a 100644 --- a/tests/test_kernels.py +++ b/tests/test_kernels.py @@ -204,7 +204,7 @@ def test_relative_attention(self): def test_depth_attention(self): mx.random.seed(4) - for num_blocks, num_queries in ((1, 1), (4, 3), (8, 1)): + for num_blocks, num_queries in ((1, 1), (1, 4), (4, 3), (8, 1)): blocks = mx.random.normal((num_blocks, 2, 3, 1000)) partial = mx.random.normal((2, 3, 1000)) queries = 0.1 * mx.random.normal((num_queries, 1000))