Elffuss BraidHub

kikocis/mlx-vlm public

main · 5.7 KiBRawPermalink
1import inspect
2import re
3from dataclasses import dataclass
4from typing import Dict, Optional, Tuple, Union
5
6import mlx.core as mx
7import mlx.nn as nn
8
9from ..base import KVCache, LanguageModelOutput, create_attention_mask
10
11
12@dataclass
13class TextConfig:
14 model_type: str
15 hidden_size: int
16 num_hidden_layers: int
17 intermediate_size: int
18 num_attention_heads: int
19 rms_norm_eps: float
20 vocab_size: int
21 num_key_value_heads: int
22 rope_theta: float = 1000000.0
23 rope_traditional: bool = False
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
41class Attention(nn.Module):
42 def __init__(self, config: TextConfig):
43 super().__init__()
44
45 dim = config.hidden_size
46 self.n_heads = n_heads = config.num_attention_heads
47 self.n_kv_heads = n_kv_heads = config.num_key_value_heads
48
49 head_dim = config.hidden_size // n_heads
50 self.scale = head_dim**-0.5
51
52 self.q_proj = nn.Linear(dim, n_heads * head_dim, bias=False)
53 self.k_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=False)
54 self.v_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=False)
55 self.o_proj = nn.Linear(n_heads * head_dim, dim, bias=False)
56
57 self.rope = nn.RoPE(
58 head_dim,
59 traditional=config.rope_traditional,
60 base=config.rope_theta,
61 )
62
63 def __call__(
64 self,
65 x: mx.array,
66 mask: Optional[mx.array] = None,
67 cache: Optional[KVCache] = None,
68 ) -> mx.array:
69 B, L, D = x.shape
70
71 queries, keys, values = self.q_proj(x), self.k_proj(x), self.v_proj(x)
72
73 # Prepare the queries, keys and values for the attention computation
74 queries = queries.reshape(B, L, self.n_heads, -1).transpose(0, 2, 1, 3)
75 keys = keys.reshape(B, L, self.n_kv_heads, -1).transpose(0, 2, 1, 3)
76 values = values.reshape(B, L, self.n_kv_heads, -1).transpose(0, 2, 1, 3)
77
78 if cache is not None:
79 queries = self.rope(queries, offset=cache.offset)
80 keys = self.rope(keys, offset=cache.offset)
81 keys, values = cache.update_and_fetch(keys, values)
82 else:
83 queries = self.rope(queries)
84 keys = self.rope(keys)
85
86 output = mx.fast.scaled_dot_product_attention(
87 queries, keys, values, scale=self.scale, mask=mask
88 )
89 output = output.transpose(0, 2, 1, 3).reshape(B, L, -1)
90 return self.o_proj(output)
91
92
93class MLP(nn.Module):
94 def __init__(self, dim, hidden_dim):
95 super().__init__()
96 self.gate_proj = nn.Linear(dim, hidden_dim, bias=False)
97 self.down_proj = nn.Linear(hidden_dim, dim, bias=False)
98 self.up_proj = nn.Linear(dim, hidden_dim, bias=False)
99
100 def __call__(self, x) -> mx.array:
101 return self.down_proj(nn.silu(self.gate_proj(x)) * self.up_proj(x))
102
103
104class TransformerBlock(nn.Module):
105 def __init__(self, config: TextConfig):
106 super().__init__()
107 self.num_attention_heads = config.num_attention_heads
108 self.hidden_size = config.hidden_size
109 self.self_attn = Attention(config)
110 self.mlp = MLP(config.hidden_size, config.intermediate_size)
111 self.input_layernorm = nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
112 self.post_attention_layernorm = nn.RMSNorm(
113 config.hidden_size, eps=config.rms_norm_eps
114 )
115 self.config = config
116
117 def __call__(
118 self,
119 x: mx.array,
120 mask: Optional[mx.array] = None,
121 cache: Optional[KVCache] = None,
122 ) -> mx.array:
123 r = self.self_attn(self.input_layernorm(x), mask, cache)
124 h = x + r
125 r = self.mlp(self.post_attention_layernorm(h))
126 out = h + r
127 return out
128
129
130class LanguageModel(nn.Module):
131 def __init__(self, config: TextConfig):
132 super().__init__()
133 self.config = config
134 self.model_type = config.model_type
135 self.vocab_size = config.vocab_size
136 self.num_hidden_layers = config.num_hidden_layers
137 assert self.vocab_size > 0
138 self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
139 self.layers = [
140 TransformerBlock(config=config) for _ in range(config.num_hidden_layers)
141 ]
142 self.norm = nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
143 self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
144
145 def __call__(
146 self,
147 inputs: mx.array,
148 cache=None,
149 inputs_embeds=None,
150 mask: Optional[mx.array] = None,
151 ):
152 # for passing merged input embeddings
153 if inputs_embeds is None:
154 h = self.embed_tokens(inputs)
155 else:
156 h = inputs_embeds
157
158 mask = create_attention_mask(h)
159
160 if cache is None:
161 cache = [None] * len(self.layers)
162
163 for layer, c in zip(self.layers, cache):
164 h = layer(h, mask, c)
165
166 logits = self.lm_head(self.norm(h))
167 return LanguageModelOutput(logits=logits)
168
169 def sanitize(self, weights):
170 # Remove unused precomputed rotary freqs
171 return {
172 k: v for k, v in weights.items() if "self_attn.rotary_emb.inv_freq" not in k
173 }
174
175 @property
176 def layers(self):
177 return self.model.layers
178
179 @property
180 def head_dim(self):
181 return self.config.hidden_size // self.config.num_attention_heads
182
183 @property
184 def n_kv_heads(self):
185 return self.config.num_key_value_heads