|
| 1 | +from dataclasses import dataclass |
| 2 | +from typing import Dict, Optional, Tuple, Union |
| 3 | + |
| 4 | +import mlx.core as mx |
| 5 | +import mlx.nn as nn |
| 6 | +import numpy as np |
| 7 | + |
| 8 | +from .base import BaseModelArgs |
| 9 | + |
| 10 | + |
| 11 | +@dataclass |
| 12 | +class ModelArgs(BaseModelArgs): |
| 13 | + model_type: str |
| 14 | + vocab_size: int |
| 15 | + d_model: int |
| 16 | + ffn_config: dict |
| 17 | + attn_config: dict |
| 18 | + n_layers: int |
| 19 | + n_heads: int |
| 20 | + |
| 21 | + |
| 22 | +class Attention(nn.Module): |
| 23 | + def __init__(self, args: ModelArgs): |
| 24 | + super().__init__() |
| 25 | + self.num_heads = args.n_heads |
| 26 | + self.d_model = args.d_model |
| 27 | + self.head_dim = args.d_model // args.n_heads |
| 28 | + self.num_key_value_heads = args.attn_config["kv_n_heads"] |
| 29 | + self.clip_qkv = args.attn_config["clip_qkv"] |
| 30 | + self.rope_theta = args.attn_config["rope_theta"] |
| 31 | + |
| 32 | + self.scale = self.head_dim**-0.5 |
| 33 | + |
| 34 | + self.Wqkv = nn.Linear( |
| 35 | + args.d_model, |
| 36 | + (self.num_key_value_heads * 2 + self.num_heads) * self.head_dim, |
| 37 | + bias=False, |
| 38 | + ) |
| 39 | + self.out_proj = nn.Linear(args.d_model, args.d_model, bias=False) |
| 40 | + self.rope = nn.RoPE( |
| 41 | + self.head_dim, |
| 42 | + traditional=False, |
| 43 | + base=self.rope_theta, |
| 44 | + ) |
| 45 | + |
| 46 | + def __call__( |
| 47 | + self, |
| 48 | + x: mx.array, |
| 49 | + mask: Optional[mx.array] = None, |
| 50 | + cache: Optional[Tuple[mx.array, mx.array]] = None, |
| 51 | + ) -> mx.array: |
| 52 | + |
| 53 | + qkv = self.Wqkv(x) |
| 54 | + qkv = mx.clip(qkv, a_min=-self.clip_qkv, a_max=self.clip_qkv) |
| 55 | + splits = [self.d_model, self.d_model + self.head_dim * self.num_key_value_heads] |
| 56 | + queries, keys, values = mx.split(qkv, splits, axis=-1) |
| 57 | + |
| 58 | + B, L, D = x.shape |
| 59 | + |
| 60 | + # Prepare the queries, keys and values for the attention computation |
| 61 | + queries = queries.reshape(B, L, self.num_heads, -1).transpose(0, 2, 1, 3) |
| 62 | + keys = keys.reshape(B, L, self.num_key_value_heads, -1).transpose(0, 2, 1, 3) |
| 63 | + values = values.reshape(B, L, self.num_key_value_heads, -1).transpose( |
| 64 | + 0, 2, 1, 3 |
| 65 | + ) |
| 66 | + |
| 67 | + if cache is not None: |
| 68 | + key_cache, value_cache = cache |
| 69 | + queries = self.rope(queries, offset=key_cache.shape[2]) |
| 70 | + keys = self.rope(keys, offset=key_cache.shape[2]) |
| 71 | + keys = mx.concatenate([key_cache, keys], axis=2) |
| 72 | + values = mx.concatenate([value_cache, values], axis=2) |
| 73 | + else: |
| 74 | + queries = self.rope(queries) |
| 75 | + keys = self.rope(keys) |
| 76 | + |
| 77 | + output = mx.fast.scaled_dot_product_attention( |
| 78 | + queries, keys, values, scale=self.scale, mask=mask |
| 79 | + ) |
| 80 | + output = output.transpose(0, 2, 1, 3).reshape(B, L, -1) |
| 81 | + return self.out_proj(output), (keys, values) |
| 82 | + |
| 83 | + |
| 84 | +class NormAttnNorm(nn.Module): |
| 85 | + def __init__(self, args: ModelArgs): |
| 86 | + super().__init__() |
| 87 | + self.norm_1 = nn.LayerNorm(args.d_model, bias=False) |
| 88 | + self.norm_2 = nn.LayerNorm(args.d_model, bias=False) |
| 89 | + self.attn = Attention(args) |
| 90 | + |
| 91 | + def __call__( |
| 92 | + self, |
| 93 | + x: mx.array, |
| 94 | + mask: Optional[mx.array] = None, |
| 95 | + cache: Optional[Tuple[mx.array, mx.array]] = None, |
| 96 | + ) -> mx.array: |
| 97 | + h, cache = self.attn(self.norm_1(x), mask=mask, cache=cache) |
| 98 | + x = h + x |
| 99 | + return x, self.norm_2(x), cache |
| 100 | + |
| 101 | + |
| 102 | +class MLP(nn.Module): |
| 103 | + def __init__(self, d_model: int, ffn_dim: int): |
| 104 | + super().__init__() |
| 105 | + self.v1 = nn.Linear(d_model, ffn_dim, bias=False) |
| 106 | + self.w1 = nn.Linear(d_model, ffn_dim, bias=False) |
| 107 | + self.w2 = nn.Linear(ffn_dim, d_model, bias=False) |
| 108 | + self.act_fn = nn.silu |
| 109 | + |
| 110 | + def __call__(self, x: mx.array) -> mx.array: |
| 111 | + current_hidden_states = self.act_fn(self.w1(x)) * self.v1(x) |
| 112 | + current_hidden_states = self.w2(current_hidden_states) |
| 113 | + return current_hidden_states |
| 114 | + |
| 115 | + |
| 116 | +class Router(nn.Module): |
| 117 | + def __init__(self, d_model: int, num_experts: int): |
| 118 | + super().__init__() |
| 119 | + self.layer = nn.Linear(d_model, num_experts, bias=False) |
| 120 | + |
| 121 | + def __call__(self, x: mx.array): |
| 122 | + return self.layer(x) |
| 123 | + |
| 124 | + |
| 125 | +class SparseMoeBlock(nn.Module): |
| 126 | + def __init__(self, args: ModelArgs): |
| 127 | + super().__init__() |
| 128 | + self.d_model = args.d_model |
| 129 | + self.ffn_dim = args.ffn_config["ffn_hidden_size"] |
| 130 | + self.num_experts = args.ffn_config["moe_num_experts"] |
| 131 | + self.num_experts_per_tok = args.ffn_config["moe_top_k"] |
| 132 | + |
| 133 | + self.router = Router(self.d_model, self.num_experts) |
| 134 | + self.experts = [ |
| 135 | + MLP(self.d_model, self.ffn_dim) for _ in range(self.num_experts) |
| 136 | + ] |
| 137 | + |
| 138 | + def __call__(self, x: mx.array) -> mx.array: |
| 139 | + ne = self.num_experts_per_tok |
| 140 | + orig_shape = x.shape |
| 141 | + x = x.reshape(-1, x.shape[-1]) |
| 142 | + |
| 143 | + gates = self.router(x) |
| 144 | + gates = mx.softmax(gates.astype(mx.float32), axis=-1) |
| 145 | + |
| 146 | + inds = mx.stop_gradient(mx.argpartition(-gates, kth=ne, axis=-1)[:, :ne]) |
| 147 | + scores = mx.take_along_axis(gates, inds, axis=-1) |
| 148 | + scores = scores / mx.linalg.norm(scores, ord=1, axis=-1, keepdims=True) |
| 149 | + scores = scores.astype(x.dtype) |
| 150 | + |
| 151 | + if self.training: |
| 152 | + inds = np.array(inds) |
| 153 | + y = mx.zeros((x.shape[0], ne, x.shape[-1]), x.dtype) |
| 154 | + for e, expert in enumerate(self.experts): |
| 155 | + idx1, idx2 = map(mx.array, np.where(inds == e)) |
| 156 | + if idx1.size == 0: |
| 157 | + continue |
| 158 | + y[idx1, idx2] = expert(x[idx1]) |
| 159 | + |
| 160 | + y = (y * scores[:, :, None]).sum(axis=1) |
| 161 | + else: |
| 162 | + y = [] |
| 163 | + for xt, st, it in zip(x, scores, inds.tolist()): |
| 164 | + yt = mx.stack([self.experts[e](xt) for e in it], axis=-1) |
| 165 | + yt = (yt * st).sum(axis=-1) |
| 166 | + y.append(yt) |
| 167 | + y = mx.stack(y, axis=0) |
| 168 | + |
| 169 | + return y.reshape(orig_shape) |
| 170 | + |
| 171 | + |
| 172 | +class DecoderLayer(nn.Module): |
| 173 | + def __init__(self, args: ModelArgs): |
| 174 | + super().__init__() |
| 175 | + self.ffn = SparseMoeBlock(args) |
| 176 | + self.norm_attn_norm = NormAttnNorm(args) |
| 177 | + |
| 178 | + def __call__( |
| 179 | + self, |
| 180 | + x: mx.array, |
| 181 | + mask: Optional[mx.array] = None, |
| 182 | + cache: Optional[Tuple[mx.array, mx.array]] = None, |
| 183 | + ) -> mx.array: |
| 184 | + r, h, cache = self.norm_attn_norm(x, mask, cache) |
| 185 | + out = self.ffn(h) + r |
| 186 | + return out, cache |
| 187 | + |
| 188 | + |
| 189 | +class DBRX(nn.Module): |
| 190 | + def __init__(self, args: ModelArgs): |
| 191 | + super().__init__() |
| 192 | + self.vocab_size = args.vocab_size |
| 193 | + self.wte = nn.Embedding(args.vocab_size, args.d_model) |
| 194 | + self.blocks = [DecoderLayer(args=args) for _ in range(args.n_layers)] |
| 195 | + self.norm_f = nn.LayerNorm(args.d_model, bias=False) |
| 196 | + |
| 197 | + def __call__( |
| 198 | + self, |
| 199 | + inputs: mx.array, |
| 200 | + cache=None, |
| 201 | + ): |
| 202 | + h = self.wte(inputs) |
| 203 | + |
| 204 | + mask = None |
| 205 | + T = h.shape[1] |
| 206 | + if T > 1: |
| 207 | + mask = nn.MultiHeadAttention.create_additive_causal_mask(T) |
| 208 | + mask = mask.astype(h.dtype) |
| 209 | + |
| 210 | + if cache is None: |
| 211 | + cache = [None] * len(self.blocks) |
| 212 | + |
| 213 | + for e, layer in enumerate(self.blocks): |
| 214 | + h, cache[e] = layer(h, mask, cache[e]) |
| 215 | + |
| 216 | + return self.norm_f(h), cache |
| 217 | + |
| 218 | + |
| 219 | +class Model(nn.Module): |
| 220 | + def __init__(self, args: ModelArgs): |
| 221 | + super().__init__() |
| 222 | + self.model_type = args.model_type |
| 223 | + self.transformer = DBRX(args) |
| 224 | + self.lm_head = nn.Linear(args.d_model, args.vocab_size, bias=False) |
| 225 | + self.args = args |
| 226 | + |
| 227 | + def __call__( |
| 228 | + self, |
| 229 | + inputs: mx.array, |
| 230 | + cache=None, |
| 231 | + ): |
| 232 | + out, cache = self.transformer(inputs, cache) |
| 233 | + return self.lm_head(out), cache |
| 234 | + |
| 235 | + @property |
| 236 | + def layers(self): |
| 237 | + return self.transformer.blocks |
| 238 | + |
| 239 | + def sanitize(self, weights): |
| 240 | + # Split experts into sub matrices |
| 241 | + num_experts = self.args.ffn_config["moe_num_experts"] |
| 242 | + dim = self.args.ffn_config["ffn_hidden_size"] |
| 243 | + |
| 244 | + pattern = "experts.mlp" |
| 245 | + new_weights = {k: v for k, v in weights.items() if pattern not in k} |
| 246 | + for k, v in weights.items(): |
| 247 | + if pattern in k: |
| 248 | + experts = [ |
| 249 | + (k.replace(".mlp", f".{e}") + ".weight", sv) |
| 250 | + for e, sv in enumerate(mx.split(v, num_experts, axis=0)) |
| 251 | + ] |
| 252 | + if k.endswith("w2"): |
| 253 | + experts = [(s, sv.T) for s, sv in experts] |
| 254 | + new_weights.update(experts) |
| 255 | + return new_weights |
0 commit comments