Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
9 changes: 9 additions & 0 deletions mlx_lm/models/aion_instruct/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Copyright © 2026 Apple Inc.

from mlx_lm.models.aion_instruct.config import ModelArgs
from mlx_lm.models.aion_instruct.model import Model

__all__ = [
"Model",
"ModelArgs",
]
49 changes: 49 additions & 0 deletions mlx_lm/models/aion_instruct/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Copyright © 2026 Apple Inc.

from dataclasses import dataclass
from typing import Any, Dict, List, Optional

from mlx_lm.models.base import BaseModelArgs

__all__ = [
"ModelArgs",
]


@dataclass
class ModelArgs(BaseModelArgs):
model_type: str
hidden_size: int
num_hidden_layers: int
intermediate_size: int
num_attention_heads: int
rms_norm_eps: float
vocab_size: int
sliding_window: int
layer_types: List[str]
rope_parameters: Dict[str, Dict[str, Any]]
num_key_value_heads: Optional[int] = None
head_dim: Optional[int] = None
max_position_embeddings: Optional[int] = None
attention_bias: bool = False
tie_word_embeddings: bool = True

def __post_init__(self):
if self.num_key_value_heads is None:
self.num_key_value_heads = self.num_attention_heads
if self.head_dim is None:
self.head_dim = self.hidden_size // self.num_attention_heads

if len(self.layer_types) != self.num_hidden_layers:
raise ValueError(
"layer_types length must match num_hidden_layers: "
f"{len(self.layer_types)} != {self.num_hidden_layers}"
)
unsupported = set(self.layer_types) - {"sliding_attention", "full_attention"}
if unsupported:
raise ValueError(f"Unsupported layer types: {sorted(unsupported)}")
missing_rope = set(self.layer_types) - set(self.rope_parameters)
if missing_rope:
raise ValueError(
f"Missing RoPE parameters for layer types: {sorted(missing_rope)}"
)
111 changes: 111 additions & 0 deletions mlx_lm/models/aion_instruct/layers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
# Copyright © 2026 Apple Inc.

from typing import Any, Optional

import mlx.core as mx
import mlx.nn as nn

from mlx_lm.layers.attention import scaled_dot_product_attention
from mlx_lm.layers.common import swiglu
from mlx_lm.layers.rope import initialize_rope
from mlx_lm.models.aion_instruct.config import ModelArgs

__all__ = [
"Attention",
"DecoderLayer",
"MLP",
]


class Attention(nn.Module):
def __init__(self, args: ModelArgs, layer_idx: int):
super().__init__()
self.n_heads = args.num_attention_heads
self.n_kv_heads = args.num_key_value_heads
head_dim = args.head_dim
self.scale = head_dim**-0.5
bias = args.attention_bias

self.q_proj = nn.Linear(args.hidden_size, self.n_heads * head_dim, bias=bias)
self.k_proj = nn.Linear(args.hidden_size, self.n_kv_heads * head_dim, bias=bias)
self.v_proj = nn.Linear(args.hidden_size, self.n_kv_heads * head_dim, bias=bias)
self.o_proj = nn.Linear(self.n_heads * head_dim, args.hidden_size, bias=bias)

# The norm is applied to each head, not to the full projection.
self.q_norm = nn.RMSNorm(head_dim, eps=args.rms_norm_eps)
self.k_norm = nn.RMSNorm(head_dim, eps=args.rms_norm_eps)

layer_type = args.layer_types[layer_idx]
self.is_sliding = layer_type == "sliding_attention"
params = args.rope_parameters[layer_type]
self.rope = initialize_rope(
head_dim,
base=params.get("rope_theta", 10000.0),
traditional=False,
scaling_config=params,
max_position_embeddings=args.max_position_embeddings,
)

def __call__(
self,
x: mx.array,
mask: Optional[mx.array] = None,
cache: Optional[Any] = None,
) -> mx.array:
B, L, _ = x.shape
queries = self.q_proj(x).reshape(B, L, self.n_heads, -1)
keys = self.k_proj(x).reshape(B, L, self.n_kv_heads, -1)
values = self.v_proj(x).reshape(B, L, self.n_kv_heads, -1)

queries = self.q_norm(queries).transpose(0, 2, 1, 3)
keys = self.k_norm(keys).transpose(0, 2, 1, 3)
values = values.transpose(0, 2, 1, 3)

if cache is not None:
queries = self.rope(queries, offset=cache.offset)
keys = self.rope(keys, offset=cache.offset)
keys, values = cache.update_and_fetch(keys, values)
else:
queries = self.rope(queries)
keys = self.rope(keys)

output = scaled_dot_product_attention(
queries, keys, values, cache=cache, scale=self.scale, mask=mask
)
output = output.transpose(0, 2, 1, 3).reshape(B, L, -1)
return self.o_proj(output)


class MLP(nn.Module):
def __init__(self, args: ModelArgs):
super().__init__()
self.gate_proj = nn.Linear(args.hidden_size, args.intermediate_size, bias=False)
self.up_proj = nn.Linear(args.hidden_size, args.intermediate_size, bias=False)
self.down_proj = nn.Linear(args.intermediate_size, args.hidden_size, bias=False)

def __call__(self, x: mx.array) -> mx.array:
return self.down_proj(swiglu(self.gate_proj(x), self.up_proj(x)))


class DecoderLayer(nn.Module):
def __init__(self, args: ModelArgs, layer_idx: int):
super().__init__()
self.self_attn = Attention(args, layer_idx)
self.mlp = MLP(args)
self.input_layernorm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps)
self.post_attention_layernorm = nn.RMSNorm(
args.hidden_size, eps=args.rms_norm_eps
)

@property
def is_sliding(self) -> bool:
return self.self_attn.is_sliding

def __call__(
self,
x: mx.array,
mask: Optional[mx.array] = None,
cache: Optional[Any] = None,
) -> mx.array:
h = x + self.self_attn(self.input_layernorm(x), mask, cache)
return h + self.mlp(self.post_attention_layernorm(h))
105 changes: 105 additions & 0 deletions mlx_lm/models/aion_instruct/model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
# Copyright © 2026 Apple Inc.

from typing import Any, Optional

import mlx.core as mx
import mlx.nn as nn

from mlx_lm.layers.attention import create_attention_mask
from mlx_lm.models.aion_instruct.config import ModelArgs
from mlx_lm.models.aion_instruct.layers import DecoderLayer
from mlx_lm.models.cache import KVCache, RotatingKVCache

__all__ = [
"AionInstructModel",
"Model",
]


class AionInstructModel(nn.Module):
def __init__(self, args: ModelArgs):
super().__init__()
self.sliding_window = args.sliding_window
self.layer_types = args.layer_types

self.embed_tokens = nn.Embedding(args.vocab_size, args.hidden_size)
self.layers = [
DecoderLayer(args, layer_idx=i) for i in range(args.num_hidden_layers)
]
self.norm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps)

# A config can have only one of the two layer types.
self.swa_idx = (
args.layer_types.index("sliding_attention")
if "sliding_attention" in args.layer_types
else None
)
self.ga_idx = (
args.layer_types.index("full_attention")
if "full_attention" in args.layer_types
else None
)

def __call__(
self,
inputs: mx.array,
cache: Optional[Any] = None,
) -> mx.array:
h = self.embed_tokens(inputs)

if cache is None:
cache = [None] * len(self.layers)

full_mask = None
sliding_window_mask = None
if self.ga_idx is not None:
full_mask = create_attention_mask(h, cache[self.ga_idx])
if self.swa_idx is not None:
sliding_window_mask = create_attention_mask(
h, cache[self.swa_idx], window_size=self.sliding_window
)

for layer, c in zip(self.layers, cache):
mask = sliding_window_mask if layer.is_sliding else full_mask
h = layer(h, mask, cache=c)

return self.norm(h)


class Model(nn.Module):
def __init__(self, args: ModelArgs):
super().__init__()
self.args = args
self.model_type = args.model_type
self.model = AionInstructModel(args)
if not args.tie_word_embeddings:
self.lm_head = nn.Linear(args.hidden_size, args.vocab_size, bias=False)

def __call__(
self,
inputs: mx.array,
cache: Optional[Any] = None,
) -> mx.array:
out = self.model(inputs, cache)
if self.args.tie_word_embeddings:
return self.model.embed_tokens.as_linear(out)
return self.lm_head(out)

def sanitize(self, weights):
if self.args.tie_word_embeddings:
weights.pop("lm_head.weight", None)
return weights

@property
def layers(self):
return self.model.layers

def make_cache(self):
return [
(
RotatingKVCache(max_size=self.args.sliding_window)
if layer.is_sliding
else KVCache()
)
for layer in self.layers
]
Loading