| 1 | import inspect |
| 2 | import math |
| 3 | from dataclasses import dataclass |
| 4 | from types import SimpleNamespace |
| 5 | from typing import Dict, Optional, Tuple, Union |
| 6 | |
| 7 | import mlx.core as mx |
| 8 | import mlx.nn as nn |
| 9 | import numpy as np |
| 10 | |
| 11 | from ..base import KVCache, LanguageModelOutput, create_attention_mask |
| 12 | from .language import LanguageModel, TextConfig |
| 13 | from .su_rope import Phi3SuScaledRotaryEmbedding |
| 14 | from .vision import VisionConfig, VisionModel |
| 15 | |
| 16 | |
| 17 | @dataclass |
| 18 | class ModelConfig: |
| 19 | text_config: TextConfig |
| 20 | vision_config: VisionConfig |
| 21 | model_type: str |
| 22 | vocab_size: int |
| 23 | |
| 24 | num_hidden_layers: int |
| 25 | intermediate_size: int |
| 26 | num_attention_heads: int |
| 27 | rms_norm_eps: float |
| 28 | |
| 29 | ignore_index: int = -100 |
| 30 | image_token_index: int = 257152 |
| 31 | hidden_size: int = 2048 |
| 32 | pad_token_id: int = 0 |
| 33 | |
| 34 | num_key_value_heads: int = None |
| 35 | rope_theta: float = 10000 |
| 36 | rope_traditional: bool = False |
| 37 | rope_scaling: Optional[Dict[str, Union[float, str]]] = None |
| 38 | max_position_embeddings: int = 131072 |
| 39 | original_max_position_embeddings: int = 4096 |
| 40 | |
| 41 | @classmethod |
| 42 | def from_dict(cls, params): |
| 43 | return cls( |
| 44 | **{ |
| 45 | k: v |
| 46 | for k, v in params.items() |
| 47 | if k in inspect.signature(cls).parameters |
| 48 | } |
| 49 | ) |
| 50 | |
| 51 | |
| 52 | class Attention(nn.Module): |
| 53 | def __init__(self, config: TextConfig): |
| 54 | super().__init__() |
| 55 | |
| 56 | dim = config.hidden_size |
| 57 | self.n_heads = n_heads = config.num_attention_heads |
| 58 | self.n_kv_heads = n_kv_heads = config.num_key_value_heads |
| 59 | self.num_hidden_layers = config.num_hidden_layers |
| 60 | |
| 61 | self.head_dim = head_dim = config.hidden_size // n_heads |
| 62 | self.scale = head_dim**-0.5 |
| 63 | |
| 64 | op_size = n_heads * head_dim + 2 * (n_kv_heads * head_dim) |
| 65 | self.qkv_proj = nn.Linear(dim, op_size, bias=False) |
| 66 | self.o_proj = nn.Linear(n_heads * head_dim, dim, bias=False) |
| 67 | |
| 68 | rope_scale = 1.0 |
| 69 | if config.rope_scaling and config.rope_scaling["type"] == "su": |
| 70 | self.rope = Phi3SuScaledRotaryEmbedding( |
| 71 | head_dim, |
| 72 | traditional=False, |
| 73 | base=config.rope_theta, |
| 74 | scale=rope_scale, |
| 75 | max_position_embeddings=config.max_position_embeddings, |
| 76 | original_max_position_embeddings=config.original_max_position_embeddings, |
| 77 | short_factor=config.rope_scaling["short_factor"], |
| 78 | long_factor=config.rope_scaling["long_factor"], |
| 79 | ) |
| 80 | else: |
| 81 | if config.rope_scaling and config.rope_scaling["type"] == "linear": |
| 82 | rope_scale = 1 / config.rope_scaling["factor"] |
| 83 | self.rope = nn.RoPE( |
| 84 | head_dim, |
| 85 | traditional=config.rope_traditional, |
| 86 | base=config.rope_theta, |
| 87 | scale=rope_scale, |
| 88 | ) |
| 89 | |
| 90 | def __call__( |
| 91 | self, |
| 92 | x: mx.array, |
| 93 | mask: Optional[mx.array] = None, |
| 94 | cache: Optional[KVCache] = None, |
| 95 | ) -> mx.array: |
| 96 | B, L, D = x.shape |
| 97 | |
| 98 | qkv = self.qkv_proj(x) |
| 99 | query_pos = self.n_heads * self.head_dim |
| 100 | queries, keys, values = mx.split( |
| 101 | qkv, [query_pos, query_pos + self.n_kv_heads * self.head_dim], axis=-1 |
| 102 | ) |
| 103 | |
| 104 | queries = queries.reshape(B, L, self.n_heads, -1).transpose(0, 2, 1, 3) |
| 105 | keys = keys.reshape(B, L, self.n_kv_heads, -1).transpose(0, 2, 1, 3) |
| 106 | values = values.reshape(B, L, self.n_kv_heads, -1).transpose(0, 2, 1, 3) |
| 107 | |
| 108 | if cache is not None: |
| 109 | queries = self.rope(queries, offset=cache.offset) |
| 110 | keys = self.rope(keys, offset=cache.offset) |
| 111 | keys, values = cache.update_and_fetch(keys, values) |
| 112 | else: |
| 113 | queries = self.rope(queries) |
| 114 | keys = self.rope(keys) |
| 115 | |
| 116 | output = mx.fast.scaled_dot_product_attention( |
| 117 | queries, keys, values, scale=self.scale, mask=mask |
| 118 | ) |
| 119 | output = output.transpose(0, 2, 1, 3).reshape(B, L, -1) |
| 120 | return self.o_proj(output) |
| 121 | |
| 122 | |
| 123 | class MLP(nn.Module): |
| 124 | def __init__(self, dim, hidden_dim): |
| 125 | super().__init__() |
| 126 | self.gate_up_proj = nn.Linear(dim, 2 * hidden_dim, bias=False) |
| 127 | self.down_proj = nn.Linear(hidden_dim, dim, bias=False) |
| 128 | |
| 129 | def __call__(self, x) -> mx.array: |
| 130 | x = self.gate_up_proj(x) |
| 131 | gate, x = mx.split(x, 2, axis=-1) |
| 132 | return self.down_proj(nn.silu(gate) * x) |
| 133 | |
| 134 | |
| 135 | class TransformerBlock(nn.Module): |
| 136 | def __init__(self, config: TextConfig): |
| 137 | super().__init__() |
| 138 | self.num_attention_heads = config.num_attention_heads |
| 139 | self.hidden_size = config.hidden_size |
| 140 | self.self_attn = Attention(config) |
| 141 | self.mlp = MLP(config.hidden_size, config.intermediate_size) |
| 142 | self.input_layernorm = nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps) |
| 143 | self.post_attention_layernorm = nn.RMSNorm( |
| 144 | config.hidden_size, eps=config.rms_norm_eps |
| 145 | ) |
| 146 | self.config = config |
| 147 | |
| 148 | def __call__( |
| 149 | self, |
| 150 | x: mx.array, |
| 151 | mask: Optional[mx.array] = None, |
| 152 | cache: Optional[KVCache] = None, |
| 153 | ) -> mx.array: |
| 154 | r = self.self_attn(self.input_layernorm(x), mask, cache) |
| 155 | h = x + r |
| 156 | r = self.mlp(self.post_attention_layernorm(h)) |
| 157 | out = h + r |
| 158 | return out |
| 159 | |
| 160 | |
| 161 | class Phi3V(nn.Module): |
| 162 | def __init__(self, config: TextConfig): |
| 163 | super().__init__() |
| 164 | self.config = config |
| 165 | self.vocab_size = config.vocab_size |
| 166 | self.num_hidden_layers = config.num_hidden_layers |
| 167 | self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size) |
| 168 | self.vision_embed_tokens = VisionModel(config) |
| 169 | self.layers = [ |
| 170 | TransformerBlock(config=config) for _ in range(config.num_hidden_layers) |
| 171 | ] |
| 172 | self.norm = nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps) |
| 173 | |
| 174 | def __call__( |
| 175 | self, |
| 176 | inputs: mx.array, |
| 177 | pixel_values=None, |
| 178 | image_sizes=None, |
| 179 | cache=None, |
| 180 | ): |
| 181 | h = self.embed_tokens(inputs) |
| 182 | p = np.argwhere(inputs < 0).tolist() |
| 183 | |
| 184 | if pixel_values is not None: |
| 185 | h = self.vision_embed_tokens(pixel_values, h, image_sizes, p) |
| 186 | |
| 187 | mask = create_attention_mask(h) |
| 188 | |
| 189 | if cache is None: |
| 190 | cache = [None] * len(self.layers) |
| 191 | |
| 192 | for layer, c in zip(self.layers, cache): |
| 193 | h = layer(h, mask, c) |
| 194 | |
| 195 | return self.norm(h) |
| 196 | |
| 197 | |
| 198 | class Model(nn.Module): |
| 199 | def __init__(self, config: TextConfig): |
| 200 | super().__init__() |
| 201 | self.model_type = config.model_type |
| 202 | self.model = Phi3V(config) |
| 203 | self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) |
| 204 | self.config = config |
| 205 | |
| 206 | def __call__( |
| 207 | self, |
| 208 | inputs: mx.array, |
| 209 | pixel_values=None, |
| 210 | mask=None, |
| 211 | cache=None, |
| 212 | image_sizes=None, |
| 213 | **kwargs, |
| 214 | ): |
| 215 | out = self.model(inputs, pixel_values, image_sizes, cache) |
| 216 | logits = self.lm_head(out).astype(self.lm_head.weight.dtype) |
| 217 | return LanguageModelOutput(logits=logits) |
| 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 |
| 230 | |
| 231 | @property |
| 232 | def language_model(self): |
| 233 | return self |
| 234 | |
| 235 | @property |
| 236 | def vision_model(self): |
| 237 | return self.model.vision_embed_tokens |