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