| 1 | import inspect |
| 2 | from dataclasses import dataclass |
| 3 | from typing import Dict, Optional, Tuple, Union |
| 4 | |
| 5 | import mlx.core as mx |
| 6 | import mlx.nn as nn |
| 7 | |
| 8 | from ..base import KVCache, LanguageModelOutput, create_attention_mask |
| 9 | |
| 10 | |
| 11 | @dataclass |
| 12 | class TextConfig: |
| 13 | model_type: str |
| 14 | hidden_size: int = 5120 |
| 15 | head_dim: int = 128 |
| 16 | num_hidden_layers: int = 40 |
| 17 | intermediate_size: int = 14336 |
| 18 | num_attention_heads: int = 32 |
| 19 | rms_norm_eps: float = 1e-06 |
| 20 | vocab_size: int = 131072 |
| 21 | num_key_value_heads: int = 8 |
| 22 | rope_theta: float = 1000000000.0 |
| 23 | rope_traditional: bool = False |
| 24 | rope_scaling: Optional[Dict[str, Union[float, str]]] = None |
| 25 | |
| 26 | @classmethod |
| 27 | def from_dict(cls, params): |
| 28 | return cls( |
| 29 | **{ |
| 30 | k: v |
| 31 | for k, v in params.items() |
| 32 | if k in inspect.signature(cls).parameters |
| 33 | } |
| 34 | ) |
| 35 | |
| 36 | def __post_init__(self): |
| 37 | if self.num_key_value_heads is None: |
| 38 | self.num_key_value_heads = self.num_attention_heads |
| 39 | |
| 40 | if self.rope_scaling: |
| 41 | required_keys = {"factor", "type"} |
| 42 | if not all(key in self.rope_scaling for key in required_keys): |
| 43 | raise ValueError(f"rope_scaling must contain keys {required_keys}") |
| 44 | |
| 45 | if self.rope_scaling["type"] != "linear": |
| 46 | raise ValueError("rope_scaling 'type' currently only supports 'linear'") |
| 47 | |
| 48 | |
| 49 | class Attention(nn.Module): |
| 50 | def __init__(self, config: TextConfig): |
| 51 | super().__init__() |
| 52 | |
| 53 | dim = config.hidden_size |
| 54 | self.n_heads = n_heads = config.num_attention_heads |
| 55 | self.n_kv_heads = n_kv_heads = config.num_key_value_heads |
| 56 | |
| 57 | head_dim = config.head_dim |
| 58 | self.scale = head_dim**-0.5 |
| 59 | |
| 60 | self.q_proj = nn.Linear(dim, n_heads * head_dim, bias=False) |
| 61 | self.k_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=False) |
| 62 | self.v_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=False) |
| 63 | self.o_proj = nn.Linear(n_heads * head_dim, dim, bias=False) |
| 64 | |
| 65 | rope_scale = ( |
| 66 | 1 / config.rope_scaling["factor"] |
| 67 | if config.rope_scaling is not None |
| 68 | and config.rope_scaling["type"] == "linear" |
| 69 | else 1 |
| 70 | ) |
| 71 | self.rope = nn.RoPE( |
| 72 | head_dim, |
| 73 | traditional=config.rope_traditional, |
| 74 | base=config.rope_theta, |
| 75 | scale=rope_scale, |
| 76 | ) |
| 77 | |
| 78 | def __call__( |
| 79 | self, |
| 80 | x: mx.array, |
| 81 | mask: Optional[mx.array] = None, |
| 82 | cache: Optional[KVCache] = None, |
| 83 | ) -> mx.array: |
| 84 | B, L, D = x.shape |
| 85 | |
| 86 | queries, keys, values = self.q_proj(x), self.k_proj(x), self.v_proj(x) |
| 87 | |
| 88 | # Prepare the queries, keys and values for the attention computation |
| 89 | queries = queries.reshape(B, L, self.n_heads, -1).transpose(0, 2, 1, 3) |
| 90 | keys = keys.reshape(B, L, self.n_kv_heads, -1).transpose(0, 2, 1, 3) |
| 91 | values = values.reshape(B, L, self.n_kv_heads, -1).transpose(0, 2, 1, 3) |
| 92 | |
| 93 | if cache is not None: |
| 94 | queries = self.rope(queries, offset=cache.offset) |
| 95 | keys = self.rope(keys, offset=cache.offset) |
| 96 | keys, values = cache.update_and_fetch(keys, values) |
| 97 | else: |
| 98 | queries = self.rope(queries) |
| 99 | keys = self.rope(keys) |
| 100 | |
| 101 | output = mx.fast.scaled_dot_product_attention( |
| 102 | queries, keys, values, scale=self.scale, mask=mask |
| 103 | ) |
| 104 | output = output.transpose(0, 2, 1, 3).reshape(B, L, -1) |
| 105 | return self.o_proj(output) |
| 106 | |
| 107 | |
| 108 | class MLP(nn.Module): |
| 109 | def __init__(self, dim, hidden_dim): |
| 110 | super().__init__() |
| 111 | self.gate_proj = nn.Linear(dim, hidden_dim, bias=False) |
| 112 | self.down_proj = nn.Linear(hidden_dim, dim, bias=False) |
| 113 | self.up_proj = nn.Linear(dim, hidden_dim, bias=False) |
| 114 | |
| 115 | def __call__(self, x) -> mx.array: |
| 116 | return self.down_proj(nn.silu(self.gate_proj(x)) * self.up_proj(x)) |
| 117 | |
| 118 | |
| 119 | class TransformerBlock(nn.Module): |
| 120 | def __init__(self, config: TextConfig): |
| 121 | super().__init__() |
| 122 | self.num_attention_heads = config.num_attention_heads |
| 123 | self.hidden_size = config.hidden_size |
| 124 | self.self_attn = Attention(config) |
| 125 | self.mlp = MLP(config.hidden_size, config.intermediate_size) |
| 126 | self.input_layernorm = nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps) |
| 127 | self.post_attention_layernorm = nn.RMSNorm( |
| 128 | config.hidden_size, eps=config.rms_norm_eps |
| 129 | ) |
| 130 | self.config = config |
| 131 | |
| 132 | def __call__( |
| 133 | self, |
| 134 | x: mx.array, |
| 135 | mask: Optional[mx.array] = None, |
| 136 | cache: Optional[KVCache] = None, |
| 137 | ) -> mx.array: |
| 138 | r = self.self_attn(self.input_layernorm(x), mask, cache) |
| 139 | h = x + r |
| 140 | r = self.mlp(self.post_attention_layernorm(h)) |
| 141 | out = h + r |
| 142 | return out |
| 143 | |
| 144 | |
| 145 | class Mistral(nn.Module): |
| 146 | def __init__(self, config: TextConfig): |
| 147 | super().__init__() |
| 148 | self.config = config |
| 149 | self.vocab_size = config.vocab_size |
| 150 | self.num_hidden_layers = config.num_hidden_layers |
| 151 | assert self.vocab_size > 0 |
| 152 | self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size) |
| 153 | self.layers = [ |
| 154 | TransformerBlock(config=config) for _ in range(config.num_hidden_layers) |
| 155 | ] |
| 156 | self.norm = nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps) |
| 157 | |
| 158 | def __call__( |
| 159 | self, |
| 160 | inputs: mx.array, |
| 161 | cache=None, |
| 162 | inputs_embeds=None, |
| 163 | ): |
| 164 | # for passing merged input embeddings |
| 165 | if inputs_embeds is None: |
| 166 | h = self.embed_tokens(inputs) |
| 167 | else: |
| 168 | h = inputs_embeds |
| 169 | |
| 170 | mask = create_attention_mask(h, cache) |
| 171 | |
| 172 | if cache is None: |
| 173 | cache = [None] * len(self.layers) |
| 174 | |
| 175 | for layer, c in zip(self.layers, cache): |
| 176 | h = layer(h, mask, c) |
| 177 | |
| 178 | return self.norm(h) |
| 179 | |
| 180 | |
| 181 | class LanguageModel(nn.Module): |
| 182 | def __init__(self, config: TextConfig): |
| 183 | super().__init__() |
| 184 | self.config = config |
| 185 | self.model_type = config.model_type |
| 186 | if self.model_type != "mistral": |
| 187 | raise ValueError( |
| 188 | f"Model type {self.model_type} not supported. Currently only 'mistral' is supported" |
| 189 | ) |
| 190 | self.model = Mistral(config) |
| 191 | self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) |
| 192 | |
| 193 | def __call__( |
| 194 | self, |
| 195 | inputs: mx.array, |
| 196 | cache=None, |
| 197 | inputs_embeds=None, |
| 198 | mask: Optional[mx.array] = None, |
| 199 | ): |
| 200 | out = self.model(inputs, cache, inputs_embeds) |
| 201 | logits = self.lm_head(out) |
| 202 | return LanguageModelOutput(logits=logits) |
| 203 | |
| 204 | @staticmethod |
| 205 | def sanitize(weights): |
| 206 | # Remove unused precomputed rotary freqs |
| 207 | return { |
| 208 | k: v for k, v in weights.items() if "self_attn.rotary_emb.inv_freq" not in k |
| 209 | } |
| 210 | |
| 211 | @property |
| 212 | def layers(self): |
| 213 | return self.model.layers |
| 214 | |
| 215 | @property |
| 216 | def head_dim(self): |
| 217 | return self.config.head_dim |
| 218 | |
| 219 | @property |
| 220 | def n_kv_heads(self): |
| 221 | return self.config.num_key_value_heads |