Elffuss BraidHub

kikocis/mlx-vlm public

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