Skip to content

Commit 0c4c991

Browse files
jundotpcuenca
andcommitted
Add Inkling 2 Mini
Inkling 2 Mini is a looped Inkling 2 model. Co-authored-by: Pedro Cuenca <pedro@huggingface.co>
1 parent f00f079 commit 0c4c991

8 files changed

Lines changed: 248 additions & 31 deletions

File tree

‎mlx_lm/models/inkling2/checkpoint.py‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,11 @@
2828
(r"\.attn\.wo_ud\.", ".self_attn.o_proj."),
2929
(r"\.attn\.gate_attn\.", ".self_attn.gate_proj."),
3030
(r"\.attn\.attn_sink_proj\.", ".self_attn.sink_proj."),
31+
(r"\.controllers\.attn\.", ".q_message_gate."),
32+
(r"\.controllers\.(k|v|mlp)\.", r".\1_message_gate."),
33+
(r"_message_gate\.down_weight$", "_message_gate.down_proj.weight"),
34+
(r"_message_gate\.forget_weight$", "_message_gate.forget_gate_proj.weight"),
35+
(r"_message_gate\.gain_weight$", "_message_gate.message_gate_proj.weight"),
3136
(r"\.attn\.", ".self_attn."),
3237
(r"\.attn_sconv\.", ".post_attention_convolution."),
3338
(r"\.mlp_sconv\.", ".post_mlp_convolution."),
@@ -65,6 +70,7 @@ def _rename(key: str) -> str:
6570
def sanitize(model, weights: dict[str, mx.array]) -> dict[str, mx.array]:
6671
experts = re.compile(r"^(.+\.mlp\.experts)\.(w13|w2)_weight(\w*)$")
6772
amax, denominator = {}, {}
73+
message_queries = {}
6874
sanitized = {}
6975
for k, v in weights.items():
7076
if k.startswith(("model.llm.", "model.visual.")):
@@ -73,7 +79,16 @@ def sanitize(model, weights: dict[str, mx.array]) -> dict[str, mx.array]:
7379
v = v.swapaxes(1, 2)
7480
if k.startswith("model.vision_tower.") and model.args.vision is None:
7581
continue
76-
if k.endswith(".mlp.gate.weight"):
82+
if k.endswith(("cross_pass_queries", "cross_pass_kv_queries")):
83+
message_queries["kv" if "_kv_" in k else "q"] = v
84+
continue
85+
if k.endswith(
86+
(
87+
".mlp.gate.weight",
88+
".forget_gate_proj.weight",
89+
".message_gate_proj.weight",
90+
)
91+
):
7792
v = v.astype(mx.float32)
7893
elif m := experts.match(k):
7994
prefix, which, suffix = m.groups()
@@ -89,6 +104,14 @@ def sanitize(model, weights: dict[str, mx.array]) -> dict[str, mx.array]:
89104
continue
90105
sanitized[k] = v
91106

107+
if message_queries:
108+
# The checkpoint has [query, mlp] and [key, value] rows per looped layer.
109+
dims = message_queries["q"].shape[-1]
110+
q = message_queries["q"].reshape(-1, 2, dims)
111+
kv = message_queries["kv"].reshape(-1, 2, dims)
112+
query = mx.concatenate([q[:, :1], kv, q[:, 1:]], axis=1)
113+
sanitized["model.language_model.message_input.query"] = query
114+
92115
# Pipeline stages can miss the files of the other layers.
93116
for name in amax.keys() & denominator.keys():
94117
scale = _NVFP4_E2M1_MAX * _NVFP4_E4M3_MAX

‎mlx_lm/models/inkling2/config.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,11 @@ class TextArgs(BaseModelArgs):
4141
mlp_up_softcap: float
4242
route_scale: float
4343
final_logit_softcapping: float
44+
loop_config: dict | None = None
45+
46+
def __post_init__(self):
47+
loop = self.loop_config or {}
48+
self.loop_core = range(loop.get("core_start", 0), loop.get("core_end", 0))
4449

4550

4651
@dataclass

‎mlx_lm/models/inkling2/layers.py‎

Lines changed: 81 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@
2323
"FullAttention",
2424
"FullDecoderLayer",
2525
"L2Clip",
26+
"MessageGate",
27+
"MessageInput",
2628
"RelativeLogits",
2729
"ScaledL2Clip",
2830
"ShortConvolution",
@@ -373,17 +375,19 @@ def __init__(self, args: TextArgs):
373375
def __call__(
374376
self,
375377
hidden_states: mx.array,
378+
key_hidden_states: mx.array,
379+
value_hidden_states: mx.array,
376380
*,
377381
cache: Any | None,
378382
conv_states: list,
379383
conv_mask: mx.array | None,
380384
) -> mx.array:
381385
kv_cache = cache[0] if cache is not None else None
382386
key_states, conv_states[0] = self.k_sconv(
383-
self.k_proj(hidden_states), conv_states[0], conv_mask
387+
self.k_proj(key_hidden_states), conv_states[0], conv_mask
384388
)
385389
value_states, conv_states[1] = self.v_sconv(
386-
self.v_proj(hidden_states), conv_states[1], conv_mask
390+
self.v_proj(value_hidden_states), conv_states[1], conv_mask
387391
)
388392
return self._attend(
389393
hidden_states,
@@ -541,16 +545,51 @@ def __call__(
541545
self, block_states: mx.array, partial_block_states: mx.array
542546
) -> mx.array:
543547
dims = partial_block_states.shape[-1]
544-
query = self.query.reshape(-1, dims).astype(mx.float32)
545-
scale = dims**-0.5
546-
if _use_kernels():
547-
return depth_attention(
548-
block_states, partial_block_states, query, scale=scale
549-
)
550-
stacked_states = mx.concatenate([block_states, partial_block_states[None]])
551-
stacked_states = mx.moveaxis(stacked_states, 0, -2)
552-
weights = mx.softmax((stacked_states @ query.T) * scale, axis=-2, precise=True)
553-
return weights.swapaxes(-1, -2) @ stacked_states
548+
return _depth_attention(
549+
block_states, partial_block_states, self.query.reshape(-1, dims)
550+
)
551+
552+
553+
def _depth_attention(
554+
block_states: mx.array, partial_block_states: mx.array, query: mx.array
555+
) -> mx.array:
556+
query = query.astype(mx.float32)
557+
scale = partial_block_states.shape[-1] ** -0.5
558+
if _use_kernels():
559+
return depth_attention(block_states, partial_block_states, query, scale=scale)
560+
stacked_states = mx.concatenate([block_states, partial_block_states[None]])
561+
stacked_states = mx.moveaxis(stacked_states, 0, -2)
562+
weights = mx.softmax((stacked_states @ query.T) * scale, axis=-2, precise=True)
563+
return weights.swapaxes(-1, -2) @ stacked_states
564+
565+
566+
class MessageGate(nn.Module):
567+
def __init__(self, dims: int, rank: int):
568+
super().__init__()
569+
self.down_proj = nn.Linear(2 * dims, rank, bias=False)
570+
self.forget_gate_proj = nn.Linear(rank, dims, bias=False)
571+
self.message_gate_proj = nn.Linear(rank, dims, bias=False)
572+
573+
def __call__(self, hidden_states: mx.array, message: mx.array) -> mx.array:
574+
states = mx.concatenate(
575+
[unweighted_rms_norm(hidden_states), unweighted_rms_norm(message)],
576+
axis=-1,
577+
)
578+
states = self.down_proj(states.astype(self.down_proj.weight.dtype))
579+
states = states.astype(mx.float32)
580+
forget_gate = mx.tanh(self.forget_gate_proj(states))
581+
message_gate = mx.tanh(self.message_gate_proj(states))
582+
return (1 - forget_gate) * hidden_states + message_gate * message
583+
584+
585+
class MessageInput(nn.Module):
586+
def __init__(self, dims: int, num_looped_layers: int):
587+
super().__init__()
588+
# The query, key, value and mlp queries of each looped layer.
589+
self.query = mx.zeros((num_looped_layers, 4, dims), mx.float32)
590+
591+
def __call__(self, bank: tuple, loop_layer_idx: int) -> mx.array:
592+
return _depth_attention(*bank, self.query[loop_layer_idx])
554593

555594

556595
class DecoderLayer(nn.Module):
@@ -567,6 +606,20 @@ def __init__(self, args: TextArgs, layer_idx: int, *, num_queries: int):
567606
kernel_size = args.sconv_kernel_size
568607
self.post_attention_convolution = ShortConvolution(dims, kernel_size)
569608
self.post_mlp_convolution = ShortConvolution(dims, kernel_size)
609+
if layer_idx in args.loop_core:
610+
rank = args.loop_config["gate_rank"]
611+
self.q_message_gate = MessageGate(dims, rank)
612+
self.k_message_gate = MessageGate(dims, rank)
613+
self.v_message_gate = MessageGate(dims, rank)
614+
self.mlp_message_gate = MessageGate(dims, rank)
615+
616+
def _mix_messages(self, states: tuple, messages: mx.array) -> tuple:
617+
q_states, k_states, v_states = states
618+
return (
619+
self.q_message_gate(q_states, messages[..., 0, :]),
620+
self.k_message_gate(k_states, messages[..., 1, :]),
621+
self.v_message_gate(v_states, messages[..., 2, :]),
622+
)
570623

571624
def __call__(
572625
self,
@@ -575,6 +628,7 @@ def __call__(
575628
*,
576629
cache: Any | None = None,
577630
conv_mask: mx.array | None = None,
631+
messages: mx.array | None = None,
578632
) -> tuple[mx.array, mx.array]:
579633
dtype = hidden_states.dtype
580634
conv = cache[1] if cache is not None else None
@@ -586,7 +640,7 @@ def __call__(
586640
if self.attention_input is not None:
587641
attention_inputs = self.attention_input(block_states, normed_residual)
588642
hidden_states = self._self_attention(
589-
hidden_states, attention_inputs, cache, conv_states, conv_mask
643+
hidden_states, attention_inputs, cache, conv_states, conv_mask, messages
590644
)
591645
hidden_states, conv_states[2] = self.post_attention_convolution(
592646
hidden_states, conv_states[2], conv_mask
@@ -604,6 +658,8 @@ def __call__(
604658

605659
normed_states = unweighted_rms_norm(hidden_states)
606660
hidden_states = self.mlp_input(block_states, normed_states)[..., 0, :]
661+
if messages is not None:
662+
hidden_states = self.mlp_message_gate(hidden_states, messages[..., 3, :])
607663
hidden_states = self.mlp(
608664
self.post_attention_layernorm(hidden_states).astype(dtype)
609665
)
@@ -627,13 +683,18 @@ def __init__(self, args: TextArgs, layer_idx: int):
627683
self.input_layernorm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps)
628684

629685
def _self_attention(
630-
self, hidden_states, attention_inputs, cache, conv_states, conv_mask
686+
self, hidden_states, attention_inputs, cache, conv_states, conv_mask, messages
631687
):
632688
dtype = hidden_states.dtype
633689
if attention_inputs is not None:
634690
hidden_states = attention_inputs[..., 0, :]
691+
if messages is None:
692+
states = (self.input_layernorm(hidden_states).astype(dtype),) * 3
693+
else:
694+
states = self._mix_messages((hidden_states,) * 3, messages)
695+
states = [self.input_layernorm(s).astype(dtype) for s in states]
635696
return self.self_attn(
636-
self.input_layernorm(hidden_states).astype(dtype),
697+
*states,
637698
cache=cache,
638699
conv_states=conv_states,
639700
conv_mask=conv_mask,
@@ -650,7 +711,7 @@ def __init__(self, args: TextArgs, layer_idx: int):
650711
self.v_input_layernorm = nn.RMSNorm(args.hidden_size, eps=eps)
651712

652713
def _self_attention(
653-
self, hidden_states, attention_inputs, cache, conv_states, conv_mask
714+
self, hidden_states, attention_inputs, cache, conv_states, conv_mask, messages
654715
):
655716
dtype = hidden_states.dtype
656717
if attention_inputs is None:
@@ -659,6 +720,10 @@ def _self_attention(
659720
query_states, key_states, value_states = (
660721
attention_inputs[..., i, :] for i in range(3)
661722
)
723+
if messages is not None:
724+
query_states, key_states, value_states = self._mix_messages(
725+
(query_states, key_states, value_states), messages
726+
)
662727
return self.self_attn(
663728
self.q_input_layernorm(query_states).astype(dtype),
664729
self.k_input_layernorm(key_states).astype(dtype),

‎mlx_lm/models/inkling2/model.py‎

Lines changed: 72 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
BlockAttentionResidual,
1616
DecoderLayer,
1717
FullDecoderLayer,
18+
MessageInput,
1819
ShortConvolution,
1920
SlidingDecoderLayer,
2021
unweighted_rms_norm,
@@ -46,10 +47,61 @@ def __init__(self, args: TextArgs):
4647
]
4748
self.final_input = BlockAttentionResidual(args.hidden_size)
4849
self.norm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps)
50+
if args.loop_config is not None:
51+
self.message_input = MessageInput(args.hidden_size, len(args.loop_core))
4952

5053
def embed(self, inputs: mx.array) -> mx.array:
5154
return self.embed_norm(self.embed_tokens(inputs))
5255

56+
@property
57+
def layer_visits(self) -> list[DecoderLayer]:
58+
if self.args.loop_config is None:
59+
return self.pipeline_layers
60+
core = self.args.loop_core
61+
passes = self.args.loop_config["num_passes"]
62+
layers = self.layers
63+
return (
64+
layers[: core.start]
65+
+ layers[core.start : core.stop] * passes
66+
+ layers[core.stop :]
67+
)
68+
69+
def pipeline(self, group, split=None) -> None:
70+
if self.args.loop_config is not None:
71+
raise ValueError("Pipeline parallel does not support looped models.")
72+
super().pipeline(group, split)
73+
74+
def _run_loop(self, hidden_states, cache, conv_mask):
75+
core = self.args.loop_core
76+
caches = iter(cache)
77+
78+
def run(layers, hidden_states, block_states, bank=None):
79+
for i, layer in enumerate(layers):
80+
messages = None if bank is None else self.message_input(bank, i)
81+
hidden_states, block_states = layer(
82+
hidden_states,
83+
block_states,
84+
cache=next(caches),
85+
conv_mask=conv_mask,
86+
messages=messages,
87+
)
88+
return hidden_states, block_states
89+
90+
prelude = run(self.layers[: core.start], hidden_states, None)
91+
hidden_states, block_states = prelude
92+
for loop_pass in range(self.args.loop_config["num_passes"]):
93+
bank = None
94+
if loop_pass > 0:
95+
bank = (
96+
block_states[prelude[1].shape[0] + 1 :],
97+
unweighted_rms_norm(hidden_states.astype(mx.float32)),
98+
)
99+
hidden_states, block_states = prelude
100+
hidden_states, block_states = run(
101+
self.layers[core.start : core.stop], hidden_states, block_states, bank
102+
)
103+
return run(self.layers[core.stop :], hidden_states, block_states)
104+
53105
def __call__(
54106
self,
55107
inputs: mx.array,
@@ -63,7 +115,7 @@ def __call__(
63115

64116
layers = self.pipeline_layers
65117
if cache is None:
66-
cache = [None] * len(layers)
118+
cache = [None] * len(self.layer_visits)
67119
conv_mask = None
68120
if cache[0] is not None:
69121
conv_mask = cache[0][1].make_mask(hidden_states.shape[1])
@@ -76,9 +128,14 @@ def __call__(
76128
states = mx.distributed.recv_like(states, rank + 1)
77129
hidden_states, block_states = states[0].astype(dtype), states[1:]
78130

79-
for layer, c in zip(layers, cache):
80-
hidden_states, block_states = layer(
81-
hidden_states, block_states, cache=c, conv_mask=conv_mask
131+
if self.args.loop_config is None:
132+
for layer, c in zip(layers, cache):
133+
hidden_states, block_states = layer(
134+
hidden_states, block_states, cache=c, conv_mask=conv_mask
135+
)
136+
else:
137+
hidden_states, block_states = self._run_loop(
138+
hidden_states, cache, conv_mask
82139
)
83140

84141
if rank != 0:
@@ -240,7 +297,9 @@ def part(w: mx.array, axis: int) -> mx.array:
240297
def quant_predicate(self) -> Callable[[str, nn.Module], bool]:
241298

242299
def predicate(path: str, module: nn.Module) -> bool:
243-
return not path.startswith("model.vision_tower.")
300+
return not path.startswith("model.vision_tower.") and (
301+
"_message_gate." not in path
302+
)
244303

245304
return predicate
246305

@@ -249,7 +308,13 @@ def cast_predicate(self) -> Callable[[str], bool]:
249308

250309
def predicate(k: str) -> bool:
251310
return not k.endswith(
252-
(".query", ".mlp.gate.weight", ".mlp.gate.e_score_correction_bias")
311+
(
312+
".query",
313+
".mlp.gate.weight",
314+
".mlp.gate.e_score_correction_bias",
315+
".forget_gate_proj.weight",
316+
".message_gate_proj.weight",
317+
)
253318
)
254319

255320
return predicate
@@ -269,5 +334,5 @@ def make_cache(self) -> list[CacheList]:
269334
),
270335
ArraysCache(4),
271336
)
272-
for layer in self.layers
337+
for layer in self.model.language_model.layer_visits
273338
]

‎mlx_lm/utils.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@
6262
"qwen3_5_moe": "qwen3_5",
6363
"qwen3_vl_moe": "qwen3_vl",
6464
"solar_open": "glm4_moe",
65+
"inkling2_loop": "inkling2",
6566
# Package names cannot have hyphens.
6667
"lfm2-vl": "lfm2_vl",
6768
"lille-130m": "lille_130m",

0 commit comments

Comments
 (0)