Skip to content
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Add Inkling 2 Mini
Inkling 2 Mini is a looped Inkling 2 model.

Co-authored-by: Pedro Cuenca <pedro@huggingface.co>
  • Loading branch information
jundot and pcuenca committed Nov 22, 2026
commit baf42e4067ce8593c6f1944fd1bb023b1951870f
25 changes: 24 additions & 1 deletion mlx_lm/models/inkling2/checkpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,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."),
Expand Down Expand Up @@ -62,6 +67,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.")):
Expand All @@ -70,7 +76,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()
Expand All @@ -86,6 +101,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
Expand Down
5 changes: 5 additions & 0 deletions mlx_lm/models/inkling2/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
97 changes: 81 additions & 16 deletions mlx_lm/models/inkling2/layers.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
"FullAttention",
"FullDecoderLayer",
"L2Clip",
"MessageGate",
"MessageInput",
"RelativeLogits",
"ScaledL2Clip",
"ShortConvolution",
Expand Down Expand Up @@ -373,17 +375,19 @@ 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,
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(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,
Expand Down Expand Up @@ -541,16 +545,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):
Expand All @@ -567,6 +606,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,
Expand All @@ -575,6 +628,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
Expand All @@ -586,7 +640,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
Expand All @@ -604,6 +658,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)
)
Expand All @@ -627,13 +683,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,
Expand All @@ -650,7 +711,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:
Expand All @@ -659,6 +720,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),
Expand Down
79 changes: 72 additions & 7 deletions mlx_lm/models/inkling2/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
BlockAttentionResidual,
DecoderLayer,
FullDecoderLayer,
MessageInput,
ShortConvolution,
SlidingDecoderLayer,
unweighted_rms_norm,
Expand Down Expand Up @@ -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,
Expand All @@ -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])
Expand All @@ -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:
Expand Down Expand Up @@ -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

Expand All @@ -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
Expand All @@ -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
]
1 change: 1 addition & 0 deletions mlx_lm/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Loading