| 1 | import inspect |
| 2 | from dataclasses import dataclass |
| 3 | from typing import Any, Dict, List, 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 = "molmo" |
| 14 | max_position_embeddings: int = 4096 |
| 15 | d_model: int = 3584 |
| 16 | n_heads: int = 28 |
| 17 | n_kv_heads: int = 4 |
| 18 | n_layers: int = 28 |
| 19 | mlp_ratio: int = 4 |
| 20 | max_sequence_length: int = 1024 |
| 21 | act_output_multiplier: int = 0.5 |
| 22 | mlp_hidden_size: int = 37888 |
| 23 | vocab_size: int = 152064 |
| 24 | embedding_size: Optional[int] = 152064 |
| 25 | additional_vocab_size: Optional[int] = None |
| 26 | attention_dropout: float = 0.1 |
| 27 | residual_dropout: float = 0.1 |
| 28 | embedding_dropout: float = 0.1 |
| 29 | layer_norm_eps: float = 1e-5 |
| 30 | initializer_range: float = 0.02 |
| 31 | pad_token_id: int = -1 |
| 32 | rope: bool = True |
| 33 | rope_theta: float = 1000000.0 |
| 34 | weight_tying: bool = False |
| 35 | rope_full_precision: bool = True |
| 36 | rope_impl: str = "interleave" |
| 37 | additional_vocab_size: Optional[int] = 128 |
| 38 | |
| 39 | @classmethod |
| 40 | def from_dict(cls, params): |
| 41 | return cls( |
| 42 | **{ |
| 43 | k: v |
| 44 | for k, v in params.items() |
| 45 | if k in inspect.signature(cls).parameters |
| 46 | } |
| 47 | ) |
| 48 | |
| 49 | |
| 50 | class SwiGLU(nn.Module): |
| 51 | def __call__(self, x: mx.array) -> mx.array: |
| 52 | x, gate = mx.split(x, 2, axis=-1) |
| 53 | return nn.silu(gate) * x |
| 54 | |
| 55 | |
| 56 | class MolmoBlock(nn.Module): |
| 57 | def __init__(self, config: TextConfig): |
| 58 | super().__init__() |
| 59 | self.attn_out = nn.Linear(config.d_model, config.d_model, bias=False) |
| 60 | self.ff_out = nn.Linear( |
| 61 | int(config.act_output_multiplier * config.mlp_hidden_size), |
| 62 | config.d_model, |
| 63 | bias=False, |
| 64 | ) |
| 65 | self.attn_norm = nn.RMSNorm(config.d_model, eps=config.layer_norm_eps) |
| 66 | self.ff_norm = nn.RMSNorm(config.d_model, eps=config.layer_norm_eps) |
| 67 | self.ff_proj = nn.Linear(config.d_model, config.mlp_hidden_size, bias=False) |
| 68 | head_dim = config.d_model // config.n_heads |
| 69 | self.rotary_emb = nn.RoPE(head_dim, base=config.rope_theta) |
| 70 | self.scale = head_dim**-0.5 |
| 71 | self.n_heads = config.n_heads |
| 72 | self.n_kv_heads = config.n_kv_heads |
| 73 | self.fused_dims = ( |
| 74 | config.d_model, |
| 75 | config.n_kv_heads * head_dim, |
| 76 | config.n_kv_heads * head_dim, |
| 77 | ) |
| 78 | self.att_proj = nn.Linear(config.d_model, sum(self.fused_dims), bias=True) |
| 79 | self.act = SwiGLU() |
| 80 | |
| 81 | def __call__(self, x, mask=None, cache=None): |
| 82 | batch_size, seq_len, D = x.shape |
| 83 | attn_in = self.attn_norm(x) |
| 84 | |
| 85 | qkv = self.att_proj(attn_in) |
| 86 | |
| 87 | q, k, v = mx.split( |
| 88 | qkv, [self.fused_dims[0], self.fused_dims[0] + self.fused_dims[1]], axis=-1 |
| 89 | ) |
| 90 | |
| 91 | q = q.reshape(batch_size, seq_len, self.n_heads, D // self.n_heads).transpose( |
| 92 | 0, 2, 1, 3 |
| 93 | ) |
| 94 | k = k.reshape( |
| 95 | batch_size, seq_len, self.n_kv_heads, D // self.n_heads |
| 96 | ).transpose(0, 2, 1, 3) |
| 97 | v = v.reshape( |
| 98 | batch_size, seq_len, self.n_kv_heads, D // self.n_heads |
| 99 | ).transpose(0, 2, 1, 3) |
| 100 | |
| 101 | if cache is not None: |
| 102 | q = self.rotary_emb(q, offset=cache.offset) |
| 103 | k = self.rotary_emb(k, offset=cache.offset) |
| 104 | k, v = cache.update_and_fetch(k, v) |
| 105 | else: |
| 106 | q = self.rotary_emb(q) |
| 107 | k = self.rotary_emb(k) |
| 108 | |
| 109 | # Perform attention |
| 110 | att = mx.fast.scaled_dot_product_attention(q, k, v, scale=self.scale, mask=mask) |
| 111 | att = att.transpose(0, 2, 1, 3).reshape(batch_size, seq_len, D) |
| 112 | att = self.attn_out(att) |
| 113 | |
| 114 | # Add attention scores |
| 115 | # shape: (batch_size, seq_len, d_model) |
| 116 | x = x + att |
| 117 | |
| 118 | # Feed-forward layer |
| 119 | og_x = x |
| 120 | x = self.ff_norm(x) |
| 121 | x = self.ff_proj(x) |
| 122 | x = self.act(x) |
| 123 | x = self.ff_out(x) |
| 124 | x = og_x + x |
| 125 | |
| 126 | return x |
| 127 | |
| 128 | |
| 129 | class Embedding(nn.Module): |
| 130 | def __init__( |
| 131 | self, |
| 132 | num_embeddings: int, |
| 133 | num_new_embeddings: int, |
| 134 | features: int, |
| 135 | initializer_range: float = 0.02, |
| 136 | new_embed_initializer_range: float = 0.02, |
| 137 | ): |
| 138 | super().__init__() |
| 139 | self.initializer_range = initializer_range |
| 140 | self.new_embed_initializer_range = new_embed_initializer_range |
| 141 | |
| 142 | # Initialize embeddings |
| 143 | self.embedding = mx.random.normal( |
| 144 | (num_embeddings, features), scale=self.initializer_range |
| 145 | ) |
| 146 | self.new_embedding = mx.random.normal( |
| 147 | (num_new_embeddings, features), scale=self.new_embed_initializer_range |
| 148 | ) |
| 149 | |
| 150 | def __call__(self, x: mx.array) -> mx.array: |
| 151 | return mx.concat([self.embedding, self.new_embedding], axis=0)[x] |
| 152 | |
| 153 | |
| 154 | class Molmo(nn.Module): |
| 155 | def __init__(self, config: TextConfig): |
| 156 | super().__init__() |
| 157 | self.config = config |
| 158 | |
| 159 | self.wte = Embedding( |
| 160 | config.embedding_size, config.additional_vocab_size, config.d_model |
| 161 | ) |
| 162 | |
| 163 | self.blocks = [MolmoBlock(config) for _ in range(config.n_layers)] |
| 164 | |
| 165 | self.ln_f = nn.RMSNorm(config.d_model, eps=config.layer_norm_eps) |
| 166 | |
| 167 | if not config.weight_tying: |
| 168 | self.ff_out = nn.Linear(config.d_model, config.vocab_size, bias=False) |
| 169 | |
| 170 | def __call__( |
| 171 | self, |
| 172 | input_ids: mx.array, |
| 173 | inputs_embeds: Optional[mx.array] = None, |
| 174 | mask: Optional[mx.array] = None, |
| 175 | cache: Optional[KVCache] = None, |
| 176 | ) -> LanguageModelOutput: |
| 177 | |
| 178 | if inputs_embeds is None: |
| 179 | h = self.wte(input_ids) |
| 180 | else: |
| 181 | h = inputs_embeds |
| 182 | |
| 183 | if cache is None: |
| 184 | cache = [None] * self.config.n_layers |
| 185 | |
| 186 | if mask is None: |
| 187 | mask = create_attention_mask(h) |
| 188 | |
| 189 | for block, c in zip(self.blocks, cache): |
| 190 | h = block(h, mask, c) |
| 191 | |
| 192 | h = self.ln_f(h) |
| 193 | |
| 194 | if self.config.weight_tying: |
| 195 | logits = mx.matmul(h, self.wte.weight.T) |
| 196 | else: |
| 197 | logits = self.ff_out(h) |
| 198 | |
| 199 | return LanguageModelOutput(logits=logits) |
| 200 | |
| 201 | |
| 202 | class LanguageModel(nn.Module): |
| 203 | def __init__(self, config: TextConfig): |
| 204 | super().__init__() |
| 205 | self.config = config |
| 206 | self.model_type = config.model_type |
| 207 | if self.model_type != "molmo": |
| 208 | raise ValueError( |
| 209 | f"Model type {self.model_type} not supported. Currently only 'molmo' is supported" |
| 210 | ) |
| 211 | self.model = Molmo(config) |
| 212 | |
| 213 | def __call__( |
| 214 | self, |
| 215 | input_ids: mx.array, |
| 216 | inputs_embeds: Optional[mx.array] = None, |
| 217 | mask: Optional[mx.array] = None, |
| 218 | cache: Optional[KVCache] = None, |
| 219 | ) -> LanguageModelOutput: |
| 220 | outputs = self.model(input_ids, inputs_embeds, mask, cache) |
| 221 | return outputs |
| 222 | |
| 223 | @staticmethod |
| 224 | def sanitize(weights): |
| 225 | # Remove unused precomputed rotary freqs |
| 226 | return {k: v for k, v in weights.items() if "rotary_emb.inv_freq" not in k} |
| 227 | |
| 228 | @property |
| 229 | def layers(self): |
| 230 | return self.model.blocks |
| 231 | |
| 232 | @property |
| 233 | def head_dim(self): |
| 234 | return self.config.d_model // self.config.n_heads |
| 235 | |
| 236 | @property |
| 237 | def n_kv_heads(self): |
| 238 | return self.config.n_kv_heads |