2024-08-16 15:28:39 -07:00
|
|
|
# Copyright © 2023-2024 Apple Inc.
|
|
|
|
|
2024-01-11 12:29:12 -08:00
|
|
|
from dataclasses import dataclass
|
2024-10-31 16:59:52 -07:00
|
|
|
from typing import Any, Dict, Optional, Union
|
2024-01-11 12:29:12 -08:00
|
|
|
|
|
|
|
import mlx.core as mx
|
|
|
|
import mlx.nn as nn
|
|
|
|
|
2024-10-31 16:59:52 -07:00
|
|
|
from .base import BaseModelArgs, create_attention_mask, scaled_dot_product_attention
|
2024-12-09 10:58:25 -05:00
|
|
|
from .rope_utils import initialize_rope
|
2024-01-11 12:29:12 -08:00
|
|
|
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
class ModelArgs(BaseModelArgs):
|
2024-02-12 10:51:02 -08:00
|
|
|
model_type: str
|
2024-01-11 12:29:12 -08:00
|
|
|
hidden_size: int
|
|
|
|
num_hidden_layers: int
|
|
|
|
intermediate_size: int
|
|
|
|
num_attention_heads: int
|
|
|
|
rms_norm_eps: float
|
|
|
|
vocab_size: int
|
2024-07-22 15:09:24 +02:00
|
|
|
head_dim: Optional[int] = None
|
2024-07-23 13:21:32 -07:00
|
|
|
max_position_embeddings: Optional[int] = None
|
2024-06-10 14:47:31 -07:00
|
|
|
num_key_value_heads: Optional[int] = None
|
2024-05-22 05:16:31 +02:00
|
|
|
attention_bias: bool = False
|
|
|
|
mlp_bias: bool = False
|
2024-01-11 12:29:12 -08:00
|
|
|
rope_theta: float = 10000
|
|
|
|
rope_traditional: bool = False
|
|
|
|
rope_scaling: Optional[Dict[str, Union[float, str]]] = None
|
2024-05-22 05:16:31 +02:00
|
|
|
tie_word_embeddings: bool = True
|
2024-01-11 12:29:12 -08:00
|
|
|
|
|
|
|
def __post_init__(self):
|
|
|
|
if self.num_key_value_heads is None:
|
|
|
|
self.num_key_value_heads = self.num_attention_heads
|
|
|
|
|
|
|
|
|
|
|
|
class Attention(nn.Module):
|
|
|
|
def __init__(self, args: ModelArgs):
|
|
|
|
super().__init__()
|
|
|
|
|
|
|
|
dim = args.hidden_size
|
|
|
|
self.n_heads = n_heads = args.num_attention_heads
|
|
|
|
self.n_kv_heads = n_kv_heads = args.num_key_value_heads
|
|
|
|
|
2024-07-22 15:09:24 +02:00
|
|
|
self.head_dim = head_dim = args.head_dim or args.hidden_size // n_heads
|
|
|
|
|
2024-01-11 12:29:12 -08:00
|
|
|
self.scale = head_dim**-0.5
|
2024-05-22 05:16:31 +02:00
|
|
|
if hasattr(args, "attention_bias"):
|
|
|
|
attention_bias = args.attention_bias
|
|
|
|
else:
|
|
|
|
attention_bias = False
|
2024-01-11 12:29:12 -08:00
|
|
|
|
2024-05-22 05:16:31 +02:00
|
|
|
self.q_proj = nn.Linear(dim, n_heads * head_dim, bias=attention_bias)
|
|
|
|
self.k_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=attention_bias)
|
|
|
|
self.v_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=attention_bias)
|
|
|
|
self.o_proj = nn.Linear(n_heads * head_dim, dim, bias=attention_bias)
|
2024-01-11 12:29:12 -08:00
|
|
|
|
2024-12-09 10:58:25 -05:00
|
|
|
self.rope = initialize_rope(
|
|
|
|
self.head_dim,
|
|
|
|
args.rope_theta,
|
|
|
|
args.rope_traditional,
|
|
|
|
args.rope_scaling,
|
|
|
|
args.max_position_embeddings,
|
|
|
|
)
|
2024-01-11 12:29:12 -08:00
|
|
|
|
|
|
|
def __call__(
|
|
|
|
self,
|
|
|
|
x: mx.array,
|
|
|
|
mask: Optional[mx.array] = None,
|
2024-10-07 20:45:51 -07:00
|
|
|
cache: Optional[Any] = None,
|
2024-01-11 12:29:12 -08:00
|
|
|
) -> mx.array:
|
|
|
|
B, L, D = x.shape
|
|
|
|
|
|
|
|
queries, keys, values = self.q_proj(x), self.k_proj(x), self.v_proj(x)
|
|
|
|
|
|
|
|
# Prepare the queries, keys and values for the attention computation
|
|
|
|
queries = queries.reshape(B, L, self.n_heads, -1).transpose(0, 2, 1, 3)
|
|
|
|
keys = keys.reshape(B, L, self.n_kv_heads, -1).transpose(0, 2, 1, 3)
|
|
|
|
values = values.reshape(B, L, self.n_kv_heads, -1).transpose(0, 2, 1, 3)
|
|
|
|
|
|
|
|
if cache is not None:
|
2024-05-08 08:18:13 -07:00
|
|
|
queries = self.rope(queries, offset=cache.offset)
|
|
|
|
keys = self.rope(keys, offset=cache.offset)
|
|
|
|
keys, values = cache.update_and_fetch(keys, values)
|
2024-01-11 12:29:12 -08:00
|
|
|
else:
|
|
|
|
queries = self.rope(queries)
|
|
|
|
keys = self.rope(keys)
|
|
|
|
|
2024-10-31 16:59:52 -07:00
|
|
|
output = scaled_dot_product_attention(
|
|
|
|
queries, keys, values, cache=cache, scale=self.scale, mask=mask
|
2024-03-07 17:41:23 -08:00
|
|
|
)
|
2024-10-31 16:59:52 -07:00
|
|
|
|
2024-03-07 17:41:23 -08:00
|
|
|
output = output.transpose(0, 2, 1, 3).reshape(B, L, -1)
|
2024-05-08 08:18:13 -07:00
|
|
|
return self.o_proj(output)
|
2024-01-11 12:29:12 -08:00
|
|
|
|
|
|
|
|
|
|
|
class MLP(nn.Module):
|
2024-05-22 05:16:31 +02:00
|
|
|
def __init__(self, args: ModelArgs):
|
2024-01-11 12:29:12 -08:00
|
|
|
super().__init__()
|
2024-05-22 05:16:31 +02:00
|
|
|
|
|
|
|
dim = args.hidden_size
|
|
|
|
hidden_dim = args.intermediate_size
|
|
|
|
if hasattr(args, "mlp_bias"):
|
|
|
|
mlp_bias = args.mlp_bias
|
|
|
|
else:
|
|
|
|
mlp_bias = False
|
|
|
|
|
|
|
|
self.gate_proj = nn.Linear(dim, hidden_dim, bias=mlp_bias)
|
|
|
|
self.down_proj = nn.Linear(hidden_dim, dim, bias=mlp_bias)
|
|
|
|
self.up_proj = nn.Linear(dim, hidden_dim, bias=mlp_bias)
|
2024-01-11 12:29:12 -08:00
|
|
|
|
|
|
|
def __call__(self, x) -> mx.array:
|
|
|
|
return self.down_proj(nn.silu(self.gate_proj(x)) * self.up_proj(x))
|
|
|
|
|
|
|
|
|
|
|
|
class TransformerBlock(nn.Module):
|
|
|
|
def __init__(self, args: ModelArgs):
|
|
|
|
super().__init__()
|
|
|
|
self.num_attention_heads = args.num_attention_heads
|
|
|
|
self.hidden_size = args.hidden_size
|
|
|
|
self.self_attn = Attention(args)
|
2024-05-22 05:16:31 +02:00
|
|
|
self.mlp = MLP(args)
|
2024-03-23 07:13:51 -07:00
|
|
|
self.input_layernorm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps)
|
|
|
|
self.post_attention_layernorm = nn.RMSNorm(
|
|
|
|
args.hidden_size, eps=args.rms_norm_eps
|
|
|
|
)
|
2024-01-11 12:29:12 -08:00
|
|
|
self.args = args
|
|
|
|
|
|
|
|
def __call__(
|
|
|
|
self,
|
|
|
|
x: mx.array,
|
|
|
|
mask: Optional[mx.array] = None,
|
2024-10-07 20:45:51 -07:00
|
|
|
cache: Optional[Any] = None,
|
2024-01-11 12:29:12 -08:00
|
|
|
) -> mx.array:
|
2024-05-08 08:18:13 -07:00
|
|
|
r = self.self_attn(self.input_layernorm(x), mask, cache)
|
2024-01-11 12:29:12 -08:00
|
|
|
h = x + r
|
|
|
|
r = self.mlp(self.post_attention_layernorm(h))
|
|
|
|
out = h + r
|
2024-05-08 08:18:13 -07:00
|
|
|
return out
|
2024-01-11 12:29:12 -08:00
|
|
|
|
|
|
|
|
|
|
|
class LlamaModel(nn.Module):
|
|
|
|
def __init__(self, args: ModelArgs):
|
|
|
|
super().__init__()
|
|
|
|
self.args = args
|
|
|
|
self.vocab_size = args.vocab_size
|
|
|
|
self.num_hidden_layers = args.num_hidden_layers
|
|
|
|
assert self.vocab_size > 0
|
|
|
|
self.embed_tokens = nn.Embedding(args.vocab_size, args.hidden_size)
|
|
|
|
self.layers = [
|
|
|
|
TransformerBlock(args=args) for _ in range(args.num_hidden_layers)
|
|
|
|
]
|
2024-03-23 07:13:51 -07:00
|
|
|
self.norm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps)
|
2024-01-11 12:29:12 -08:00
|
|
|
|
|
|
|
def __call__(
|
|
|
|
self,
|
|
|
|
inputs: mx.array,
|
2024-12-18 19:43:52 -08:00
|
|
|
mask: mx.array = None,
|
2024-01-11 12:29:12 -08:00
|
|
|
cache=None,
|
|
|
|
):
|
|
|
|
h = self.embed_tokens(inputs)
|
|
|
|
|
2024-12-18 19:43:52 -08:00
|
|
|
if mask is None:
|
|
|
|
mask = create_attention_mask(h, cache)
|
2024-01-11 12:29:12 -08:00
|
|
|
|
|
|
|
if cache is None:
|
|
|
|
cache = [None] * len(self.layers)
|
|
|
|
|
2024-05-08 08:18:13 -07:00
|
|
|
for layer, c in zip(self.layers, cache):
|
|
|
|
h = layer(h, mask, cache=c)
|
2024-01-11 12:29:12 -08:00
|
|
|
|
2024-05-08 08:18:13 -07:00
|
|
|
return self.norm(h)
|
2024-01-11 12:29:12 -08:00
|
|
|
|
|
|
|
|
|
|
|
class Model(nn.Module):
|
|
|
|
def __init__(self, args: ModelArgs):
|
|
|
|
super().__init__()
|
2024-05-22 05:16:31 +02:00
|
|
|
self.args = args
|
2024-02-12 10:51:02 -08:00
|
|
|
self.model_type = args.model_type
|
2024-01-11 12:29:12 -08:00
|
|
|
self.model = LlamaModel(args)
|
2024-05-22 05:16:31 +02:00
|
|
|
if not args.tie_word_embeddings:
|
|
|
|
self.lm_head = nn.Linear(args.hidden_size, args.vocab_size, bias=False)
|
2024-01-11 12:29:12 -08:00
|
|
|
|
|
|
|
def __call__(
|
|
|
|
self,
|
|
|
|
inputs: mx.array,
|
2024-12-18 19:43:52 -08:00
|
|
|
mask: mx.array = None,
|
2024-01-11 12:29:12 -08:00
|
|
|
cache=None,
|
|
|
|
):
|
2024-12-18 19:43:52 -08:00
|
|
|
out = self.model(inputs, mask, cache)
|
2024-05-22 05:16:31 +02:00
|
|
|
if self.args.tie_word_embeddings:
|
|
|
|
out = self.model.embed_tokens.as_linear(out)
|
|
|
|
else:
|
|
|
|
out = self.lm_head(out)
|
|
|
|
return out
|
2024-01-18 14:18:13 -08:00
|
|
|
|
2024-03-13 15:34:32 +11:00
|
|
|
def sanitize(self, weights):
|
2024-01-18 14:18:13 -08:00
|
|
|
# Remove unused precomputed rotary freqs
|
|
|
|
return {
|
|
|
|
k: v for k, v in weights.items() if "self_attn.rotary_emb.inv_freq" not in k
|
|
|
|
}
|
2024-02-19 20:37:15 -08:00
|
|
|
|
|
|
|
@property
|
|
|
|
def layers(self):
|
|
|
|
return self.model.layers
|