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