|
| 1 | +# Copyright © 2025 Apple Inc. |
| 2 | + |
| 3 | +from dataclasses import dataclass |
| 4 | +from typing import Any, Dict, Optional, Union |
| 5 | + |
| 6 | +import mlx.core as mx |
| 7 | +import mlx.nn as nn |
| 8 | + |
| 9 | +from .base import BaseModelArgs, create_attention_mask, scaled_dot_product_attention |
| 10 | +from .rope_utils import initialize_rope |
| 11 | + |
| 12 | + |
| 13 | +@dataclass |
| 14 | +class ModelArgs(BaseModelArgs): |
| 15 | + model_type: str |
| 16 | + hidden_size: int |
| 17 | + num_hidden_layers: int |
| 18 | + intermediate_size: int |
| 19 | + num_attention_heads: int |
| 20 | + rms_norm_eps: float |
| 21 | + vocab_size: int |
| 22 | + num_key_value_heads: int |
| 23 | + head_dim: int |
| 24 | + max_position_embeddings: Optional[int] = None |
| 25 | + attention_bias: bool = False |
| 26 | + attention_out_bias: bool = False |
| 27 | + mlp_bias: bool = False |
| 28 | + rope_theta: float = 10000 |
| 29 | + rope_traditional: bool = False |
| 30 | + rope_scaling: Optional[Dict[str, Union[float, str]]] = None |
| 31 | + tie_word_embeddings: bool = True |
| 32 | + |
| 33 | + |
| 34 | +class Attention(nn.Module): |
| 35 | + def __init__(self, args: ModelArgs): |
| 36 | + super().__init__() |
| 37 | + |
| 38 | + dim = args.hidden_size |
| 39 | + self.n_heads = n_heads = args.num_attention_heads |
| 40 | + self.n_kv_heads = n_kv_heads = args.num_key_value_heads |
| 41 | + self.head_dim = head_dim = args.head_dim |
| 42 | + |
| 43 | + self.scale = head_dim**-0.5 |
| 44 | + |
| 45 | + input_bias = args.attention_bias |
| 46 | + output_bias = args.attention_out_bias |
| 47 | + |
| 48 | + self.q_proj = nn.Linear(dim, n_heads * head_dim, bias=input_bias) |
| 49 | + self.k_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=input_bias) |
| 50 | + self.v_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=input_bias) |
| 51 | + self.o_proj = nn.Linear(n_heads * head_dim, dim, bias=output_bias) |
| 52 | + |
| 53 | + self.rope = initialize_rope( |
| 54 | + self.head_dim, |
| 55 | + args.rope_theta, |
| 56 | + args.rope_traditional, |
| 57 | + args.rope_scaling, |
| 58 | + args.max_position_embeddings, |
| 59 | + ) |
| 60 | + |
| 61 | + def __call__( |
| 62 | + self, |
| 63 | + x: mx.array, |
| 64 | + mask: Optional[mx.array] = None, |
| 65 | + cache: Optional[Any] = None, |
| 66 | + ) -> mx.array: |
| 67 | + B, L, D = x.shape |
| 68 | + |
| 69 | + queries, keys, values = self.q_proj(x), self.k_proj(x), self.v_proj(x) |
| 70 | + |
| 71 | + # Prepare the queries, keys and values for the attention computation |
| 72 | + queries = queries.reshape(B, L, self.n_heads, -1).transpose(0, 2, 1, 3) |
| 73 | + keys = keys.reshape(B, L, self.n_kv_heads, -1).transpose(0, 2, 1, 3) |
| 74 | + values = values.reshape(B, L, self.n_kv_heads, -1).transpose(0, 2, 1, 3) |
| 75 | + |
| 76 | + if cache is not None: |
| 77 | + queries = self.rope(queries, offset=cache.offset) |
| 78 | + keys = self.rope(keys, offset=cache.offset) |
| 79 | + keys, values = cache.update_and_fetch(keys, values) |
| 80 | + else: |
| 81 | + queries = self.rope(queries) |
| 82 | + keys = self.rope(keys) |
| 83 | + |
| 84 | + output = scaled_dot_product_attention( |
| 85 | + queries, keys, values, cache=cache, scale=self.scale, mask=mask |
| 86 | + ) |
| 87 | + output = output.transpose(0, 2, 1, 3).reshape(B, L, -1) |
| 88 | + return self.o_proj(output) |
| 89 | + |
| 90 | + |
| 91 | +class MLP(nn.Module): |
| 92 | + def __init__(self, dim, hidden_dim, bias=False): |
| 93 | + super().__init__() |
| 94 | + self.gate_proj = nn.Linear(dim, hidden_dim, bias=bias) |
| 95 | + self.down_proj = nn.Linear(hidden_dim, dim, bias=bias) |
| 96 | + self.up_proj = nn.Linear(dim, hidden_dim, bias=bias) |
| 97 | + |
| 98 | + def __call__(self, x) -> mx.array: |
| 99 | + return self.down_proj(nn.silu(self.gate_proj(x)) * self.up_proj(x)) |
| 100 | + |
| 101 | + |
| 102 | +class TransformerBlock(nn.Module): |
| 103 | + def __init__(self, args: ModelArgs): |
| 104 | + super().__init__() |
| 105 | + self.num_attention_heads = args.num_attention_heads |
| 106 | + self.hidden_size = args.hidden_size |
| 107 | + self.self_attn = Attention(args) |
| 108 | + self.mlp = MLP(args.hidden_size, args.intermediate_size, args.mlp_bias) |
| 109 | + self.input_layernorm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps) |
| 110 | + self.post_attention_layernorm = nn.RMSNorm( |
| 111 | + args.hidden_size, eps=args.rms_norm_eps |
| 112 | + ) |
| 113 | + |
| 114 | + def __call__( |
| 115 | + self, |
| 116 | + x: mx.array, |
| 117 | + mask: Optional[mx.array] = None, |
| 118 | + cache: Optional[Any] = None, |
| 119 | + ) -> mx.array: |
| 120 | + r = self.self_attn(self.input_layernorm(x), mask, cache) |
| 121 | + h = x + r |
| 122 | + r = self.mlp(self.post_attention_layernorm(h)) |
| 123 | + out = h + r |
| 124 | + return out |
| 125 | + |
| 126 | + |
| 127 | +class SeedModel(nn.Module): |
| 128 | + def __init__(self, args: ModelArgs): |
| 129 | + super().__init__() |
| 130 | + self.embed_tokens = nn.Embedding(args.vocab_size, args.hidden_size) |
| 131 | + self.layers = [ |
| 132 | + TransformerBlock(args=args) for _ in range(args.num_hidden_layers) |
| 133 | + ] |
| 134 | + self.norm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps) |
| 135 | + |
| 136 | + def __call__( |
| 137 | + self, |
| 138 | + inputs: mx.array, |
| 139 | + mask: mx.array = None, |
| 140 | + cache=None, |
| 141 | + ): |
| 142 | + h = self.embed_tokens(inputs) |
| 143 | + |
| 144 | + if mask is None: |
| 145 | + mask = create_attention_mask(h, cache) |
| 146 | + |
| 147 | + if cache is None: |
| 148 | + cache = [None] * len(self.layers) |
| 149 | + |
| 150 | + for layer, c in zip(self.layers, cache): |
| 151 | + h = layer(h, mask, cache=c) |
| 152 | + |
| 153 | + return self.norm(h) |
| 154 | + |
| 155 | + |
| 156 | +class Model(nn.Module): |
| 157 | + def __init__(self, args: ModelArgs): |
| 158 | + super().__init__() |
| 159 | + self.model = SeedModel(args) |
| 160 | + self.tie_word_embeddings = args.tie_word_embeddings |
| 161 | + if not args.tie_word_embeddings: |
| 162 | + self.lm_head = nn.Linear(args.hidden_size, args.vocab_size, bias=False) |
| 163 | + |
| 164 | + def __call__( |
| 165 | + self, |
| 166 | + inputs: mx.array, |
| 167 | + mask: mx.array = None, |
| 168 | + cache=None, |
| 169 | + ): |
| 170 | + h = self.model(inputs, mask=mask, cache=cache) |
| 171 | + if self.tie_word_embeddings: |
| 172 | + return h @ self.model.embed_tokens.weight.T |
| 173 | + else: |
| 174 | + return self.lm_head(h) |
| 175 | + |
| 176 | + def sanitize(self, weights): |
| 177 | + if self.tie_word_embeddings: |
| 178 | + weights.pop("lm_head.weight", None) |
| 179 | + |
| 180 | + return weights |
| 181 | + |
| 182 | + @property |
| 183 | + def layers(self): |
| 184 | + return self.model.layers |
0 commit comments