Elffuss BraidHub

kikocis/mlx-vlm public

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