sharded_llama.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. from dataclasses import dataclass, field
  2. from typing import Dict, Optional, Tuple, Union
  3. import mlx.core as mx
  4. import mlx.nn as nn
  5. from mlx_lm.models.base import BaseModelArgs, create_additive_causal_mask
  6. from ...shard import Shard
  7. @dataclass
  8. class NormalModelArgs(BaseModelArgs):
  9. model_type: str
  10. hidden_size: int
  11. num_hidden_layers: int
  12. intermediate_size: int
  13. num_attention_heads: int
  14. rms_norm_eps: float
  15. vocab_size: int
  16. num_key_value_heads: int = None
  17. attention_bias: bool = False
  18. mlp_bias: bool = False
  19. rope_theta: float = 10000
  20. rope_traditional: bool = False
  21. rope_scaling: Optional[Dict[str, Union[float, str]]] = None
  22. tie_word_embeddings: bool = True
  23. def __post_init__(self):
  24. if self.num_key_value_heads is None:
  25. self.num_key_value_heads = self.num_attention_heads
  26. if self.rope_scaling:
  27. required_keys = {"factor", "type"}
  28. if not all(key in self.rope_scaling for key in required_keys):
  29. raise ValueError(f"rope_scaling must contain keys {required_keys}")
  30. if self.rope_scaling["type"] != "linear":
  31. raise ValueError("rope_scaling 'type' currently only supports 'linear'")
  32. @dataclass
  33. class ModelArgs(NormalModelArgs):
  34. shard: Shard = field(default_factory=lambda: Shard("", 0, 0, 0))
  35. def __post_init__(self):
  36. super().__post_init__() # Ensure parent initializations are respected
  37. if isinstance(self.shard, Shard):
  38. return
  39. if not isinstance(self.shard, dict):
  40. raise TypeError(f"Expected shard to be a Shard instance or a dict, got {type(self.shard)} instead")
  41. self.shard = Shard(**self.shard)
  42. class Attention(nn.Module):
  43. def __init__(self, args: ModelArgs):
  44. super().__init__()
  45. dim = args.hidden_size
  46. self.n_heads = n_heads = args.num_attention_heads
  47. self.n_kv_heads = n_kv_heads = args.num_key_value_heads
  48. head_dim = args.hidden_size // n_heads
  49. self.scale = head_dim**-0.5
  50. if hasattr(args, "attention_bias"):
  51. attention_bias = args.attention_bias
  52. else:
  53. attention_bias = False
  54. self.q_proj = nn.Linear(dim, n_heads * head_dim, bias=attention_bias)
  55. self.k_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=attention_bias)
  56. self.v_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=attention_bias)
  57. self.o_proj = nn.Linear(n_heads * head_dim, dim, bias=attention_bias)
  58. rope_scale = (
  59. 1 / args.rope_scaling["factor"]
  60. if args.rope_scaling is not None and args.rope_scaling["type"] == "linear"
  61. else 1
  62. )
  63. self.rope = nn.RoPE(
  64. head_dim,
  65. traditional=args.rope_traditional,
  66. base=args.rope_theta,
  67. scale=rope_scale,
  68. )
  69. def __call__(
  70. self,
  71. x: mx.array,
  72. mask: Optional[mx.array] = None,
  73. cache: Optional[Tuple[mx.array, mx.array]] = None,
  74. ) -> mx.array:
  75. B, L, D = x.shape
  76. queries, keys, values = self.q_proj(x), self.k_proj(x), self.v_proj(x)
  77. # Prepare the queries, keys and values for the attention computation
  78. queries = queries.reshape(B, L, self.n_heads, -1).transpose(0, 2, 1, 3)
  79. keys = keys.reshape(B, L, self.n_kv_heads, -1).transpose(0, 2, 1, 3)
  80. values = values.reshape(B, L, self.n_kv_heads, -1).transpose(0, 2, 1, 3)
  81. if cache is not None:
  82. queries = self.rope(queries, offset=cache.offset)
  83. keys = self.rope(keys, offset=cache.offset)
  84. keys, values = cache.update_and_fetch(keys, values)
  85. else:
  86. queries = self.rope(queries)
  87. keys = self.rope(keys)
  88. output = mx.fast.scaled_dot_product_attention(
  89. queries, keys, values, scale=self.scale, mask=mask
  90. )
  91. output = output.transpose(0, 2, 1, 3).reshape(B, L, -1)
  92. return self.o_proj(output)
  93. class MLP(nn.Module):
  94. def __init__(self, args: ModelArgs):
  95. super().__init__()
  96. dim = args.hidden_size
  97. hidden_dim = args.intermediate_size
  98. if hasattr(args, "mlp_bias"):
  99. mlp_bias = args.mlp_bias
  100. else:
  101. mlp_bias = False
  102. self.gate_proj = nn.Linear(dim, hidden_dim, bias=mlp_bias)
  103. self.down_proj = nn.Linear(hidden_dim, dim, bias=mlp_bias)
  104. self.up_proj = nn.Linear(dim, hidden_dim, bias=mlp_bias)
  105. def __call__(self, x) -> mx.array:
  106. return self.down_proj(nn.silu(self.gate_proj(x)) * self.up_proj(x))
  107. class TransformerBlock(nn.Module):
  108. def __init__(self, args: ModelArgs):
  109. super().__init__()
  110. self.num_attention_heads = args.num_attention_heads
  111. self.hidden_size = args.hidden_size
  112. self.self_attn = Attention(args)
  113. self.mlp = MLP(args)
  114. self.input_layernorm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps)
  115. self.post_attention_layernorm = nn.RMSNorm(
  116. args.hidden_size, eps=args.rms_norm_eps
  117. )
  118. self.args = args
  119. def __call__(
  120. self,
  121. x: mx.array,
  122. mask: Optional[mx.array] = None,
  123. cache: Optional[Tuple[mx.array, mx.array]] = None,
  124. ) -> mx.array:
  125. r = self.self_attn(self.input_layernorm(x), mask, cache)
  126. h = x + r
  127. r = self.mlp(self.post_attention_layernorm(h))
  128. out = h + r
  129. return out
  130. class LlamaModel(nn.Module):
  131. def __init__(self, args: ModelArgs):
  132. super().__init__()
  133. self.args = args
  134. self.vocab_size = args.vocab_size
  135. self.num_hidden_layers = args.num_hidden_layers
  136. assert self.vocab_size > 0
  137. self.embed_tokens = nn.Embedding(args.vocab_size, args.hidden_size)
  138. self.layers = [
  139. TransformerBlock(args=args) for _ in range(args.shard.n_layers)
  140. ]
  141. self.norm = nn.RMSNorm(args.hidden_size, eps=args.rms_norm_eps)
  142. def __call__(
  143. self,
  144. inputs: mx.array,
  145. cache=None,
  146. ):
  147. if self.args.shard.is_first_layer():
  148. h = self.embed_tokens(inputs)
  149. else:
  150. h = inputs
  151. mask = None
  152. if h.shape[1] > 1:
  153. mask = create_additive_causal_mask(
  154. h.shape[1], cache[0].offset if cache is not None else 0
  155. )
  156. mask = mask.astype(h.dtype)
  157. if cache is None:
  158. cache = [None] * len(self.layers)
  159. for layer, c in zip(self.layers, cache):
  160. h = layer(h, mask, cache=c)
  161. if self.args.shard.is_last_layer():
  162. return self.norm(h)
  163. else:
  164. return h
  165. class Model(nn.Module):
  166. def __init__(self, args: ModelArgs):
  167. super().__init__()
  168. self.args = args
  169. self.model_type = args.model_type
  170. self.model = LlamaModel(args)
  171. if not args.tie_word_embeddings:
  172. self.lm_head = nn.Linear(args.hidden_size, args.vocab_size, bias=False)
  173. def __call__(
  174. self,
  175. inputs: mx.array,
  176. cache=None,
  177. ):
  178. out = self.model(inputs, cache)
  179. if self.args.shard.is_last_layer():
  180. if self.args.tie_word_embeddings:
  181. out = self.model.embed_tokens.as_linear(out)
  182. else:
  183. out = self.lm_head(out)
  184. return out
  185. def sanitize(self, weights):
  186. # Remove unused precomputed rotary freqs
  187. return {
  188. k: v for k, v in weights.items() if "self_attn.rotary_emb.inv_freq" not in k
  189. }
  190. @property
  191. def layers(self):
  192. return self.model.layers
  193. @property
  194. def head_dim(self):
  195. return self.args.hidden_size // self.args.num_attention_heads
  196. @property
  197. def n_kv_heads(self):
  198. return self.args.num_key_value_heads