From 6b1d27a39f060e0a76628e1eda09d4c79b859f78 Mon Sep 17 00:00:00 2001 From: Prince Canuma Date: Tue, 20 Aug 2024 23:47:13 +0200 Subject: [PATCH 1/5] add phimoe --- llms/mlx_lm/models/phimoe.py | 257 +++++++++++++++++++++++++++++++++++ 1 file changed, 257 insertions(+) create mode 100644 llms/mlx_lm/models/phimoe.py diff --git a/llms/mlx_lm/models/phimoe.py b/llms/mlx_lm/models/phimoe.py new file mode 100644 index 000000000..b34d3bcd3 --- /dev/null +++ b/llms/mlx_lm/models/phimoe.py @@ -0,0 +1,257 @@ +import math +from dataclasses import dataclass +from typing import List, Optional, Tuple, Union + +import mlx.core as mx +import mlx.nn as nn + +from .base import BaseModelArgs, KVCache, create_attention_mask +from .su_rope import SuScaledRotaryEmbedding + + +@dataclass +class ModelArgs(BaseModelArgs): + model_type: str = "phimoe" + vocab_size: int = 30000 + hidden_size: int = 1024 + intermediate_size: int = 4096 + num_hidden_layers: int = 12 + num_attention_heads: int = 16 + num_key_value_heads: int = 16 + max_position_embeddings: int = 2048 + initializer_range: float = 0.02 + rms_norm_eps: float = 1e-6 + pad_token_id: Optional[int] = None + rope_traditional: bool = False + num_local_experts: int = 8 + num_experts_per_tok: int = 2 + attention_bias: bool = False + rope_theta: float = 10000.0 + + def __post_init__(self): + if self.num_key_value_heads is None: + self.num_key_value_heads = self.num_attention_heads + + if self.rope_scaling: + required_keys = {"long_factor", "type"} + if not all(key in self.rope_scaling for key in required_keys): + raise ValueError(f"rope_scaling must contain keys {required_keys}") + + if self.rope_scaling["type"] not in ["longrope", "su", "linear"]: + print( + "[WARNING] rope_scaling 'type' currently only supports 'linear', 'su', and 'longrope'; setting rope scaling to false." + ) + self.rope_scaling = None + + +class Attention(nn.Module): + def __init__(self, args: ModelArgs): + super().__init__() + + dim = args.hidden_size + self.n_heads = n_heads = args.num_attention_heads + assert args.num_key_value_heads is not None + self.n_kv_heads = n_kv_heads = args.num_key_value_heads + + head_dim = args.hidden_size // n_heads + self.scale = head_dim**-0.5 + + self.q_proj = nn.Linear(dim, n_heads * head_dim, bias=True) + self.k_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=True) + self.v_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=True) + self.o_proj = nn.Linear(n_heads * head_dim, dim, bias=False) + + rope_scale = 1.0 + if args.rope_scaling and args.rope_scaling["type"] in ["longrope", "su"]: + self.rope = SuScaledRotaryEmbedding( + head_dim, + traditional=False, + base=args.rope_theta, + scale=rope_scale, + max_position_embeddings=args.max_position_embeddings, + original_max_position_embeddings=args.original_max_position_embeddings, + short_factor=args.rope_scaling["short_factor"], + long_factor=args.rope_scaling["long_factor"], + ) + else: + if args.rope_scaling and args.rope_scaling["type"] == "linear": + assert isinstance(args.rope_scaling["factor"], float) + rope_scale = 1 / args.rope_scaling["factor"] + self.rope = nn.RoPE( + head_dim, + traditional=args.rope_traditional, + base=args.rope_theta, + scale=rope_scale, + ) + + def __call__( + self, + x: mx.array, + mask: Optional[mx.array] = None, + cache: Optional[KVCache] = None, + ) -> 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: + queries = self.rope(queries, offset=cache.offset) + keys = self.rope(keys, offset=cache.offset) + keys, values = cache.update_and_fetch(keys, values) + else: + queries = self.rope(queries) + keys = self.rope(keys) + + output = mx.fast.scaled_dot_product_attention( + queries, keys, values, scale=self.scale, mask=mask + ) + output = output.transpose(0, 2, 1, 3).reshape(B, L, -1) + return self.o_proj(output) + + +class PhiMoEBlockSparseTop2MLP(nn.Module): + def __init__(self, args: ModelArgs): + super().__init__() + self.ffn_dim = args.intermediate_size + self.hidden_dim = args.hidden_size + + self.w1 = nn.Linear(self.hidden_dim, self.ffn_dim, bias=False) + self.w2 = nn.Linear(self.ffn_dim, self.hidden_dim, bias=False) + self.w3 = nn.Linear(self.hidden_dim, self.ffn_dim, bias=False) + + self.act_fn = nn.GELU() + + def __call__(self, hidden_states): + current_hidden_states = self.act_fn(self.w1(hidden_states)) * self.w3( + hidden_states + ) + current_hidden_states = self.w2(current_hidden_states) + return current_hidden_states + + +class PhiMoESparseMoeBlock(nn.Module): + def __init__(self, args: ModelArgs): + super().__init__() + self.hidden_dim = args.hidden_size + self.ffn_dim = args.intermediate_size + self.num_experts = args.num_local_experts + self.top_k = args.num_experts_per_tok + + self.gate = nn.Linear(self.hidden_dim, self.num_experts, bias=False) + self.experts = [PhiMoEBlockSparseTop2MLP(args) for _ in range(self.num_experts)] + + def __call__(self, hidden_states): + batch_size, sequence_length, hidden_dim = hidden_states.shape + hidden_states = hidden_states.reshape(-1, hidden_dim) + + router_logits = self.gate(hidden_states) + routing_weights = mx.softmax(router_logits, axis=-1) + expert_indices = mx.argmax(routing_weights, axis=-1) + + final_hidden_states = mx.zeros((batch_size * sequence_length, hidden_dim)) + + for expert_idx in range(self.num_experts): + expert_layer = self.experts[expert_idx] + expert_mask = expert_indices == expert_idx + if mx.sum(expert_mask) > 0: + expert_input = hidden_states[expert_mask] + expert_output = expert_layer(expert_input) + final_hidden_states = mx.where( + expert_mask[:, None], expert_output, final_hidden_states + ) + + final_hidden_states = final_hidden_states.reshape( + batch_size, sequence_length, hidden_dim + ) + return final_hidden_states, router_logits + + +class PhiMoEDecoderLayer(nn.Module): + def __init__(self, args: ModelArgs): + super().__init__() + self.hidden_size = args.hidden_size + + self.self_attn = Attention(args) + self.block_sparse_moe = PhiMoESparseMoeBlock(args) + self.input_layernorm = nn.LayerNorm(args.hidden_size, eps=args.rms_norm_eps) + self.post_attention_layernorm = nn.LayerNorm( + args.hidden_size, eps=args.rms_norm_eps + ) + + def __call__(self, hidden_states, attention_mask=None, position_ids=None): + residual = hidden_states + hidden_states = self.input_layernorm(hidden_states) + + hidden_states = self.self_attn( + hidden_states=hidden_states, + attention_mask=attention_mask, + position_ids=position_ids, + ) + hidden_states = residual + hidden_states + + residual = hidden_states + hidden_states = self.post_attention_layernorm(hidden_states) + hidden_states, router_logits = self.block_sparse_moe(hidden_states) + hidden_states = residual + hidden_states + + return hidden_states, router_logits + + +class PhiMoEModel(nn.Module): + def __init__(self, args: ModelArgs): + super().__init__() + self.args = args + self.padding_idx = args.pad_token_id + self.vocab_size = args.vocab_size + + self.embed_tokens = nn.Embedding( + args.vocab_size, args.hidden_size, self.padding_idx + ) + self.layers = [PhiMoEDecoderLayer(args) for _ in range(args.num_hidden_layers)] + self.norm = nn.LayerNorm(args.hidden_size, eps=args.rms_norm_eps) + + def __call__(self, input_ids, attention_mask=None, position_ids=None): + hidden_states = self.embed_tokens(input_ids) + + for layer in self.layers: + hidden_states, _ = layer(hidden_states, attention_mask, position_ids) + + hidden_states = self.norm(hidden_states) + + return hidden_states + + +class Model(nn.Module): + def __init__(self, args: ModelArgs): + super().__init__() + self.args = args + self.model = PhiMoEModel(args) + self.lm_head = nn.Linear(args.hidden_size, args.vocab_size, bias=False) + + def __call__(self, input_ids, attention_mask=None, position_ids=None): + hidden_states = self.model(input_ids, attention_mask, position_ids) + logits = self.lm_head(hidden_states) + return logits + + @property + def layers(self): + return self.model.layers + + @property + def head_dim(self): + return self.args.hidden_size // self.args.num_attention_heads + + def sanitize(self, weights): + # Remove unused precomputed rotary freqs + return { + k: v for k, v in weights.items() if "self_attn.rotary_emb.inv_freq" not in k + } + + @property + def n_kv_heads(self): + return self.args.num_key_value_heads From 0b20d08d1b3d65f5a2bc48a2d74e1c2e3da9e74a Mon Sep 17 00:00:00 2001 From: Prince Canuma Date: Sat, 24 Aug 2024 08:47:11 +0200 Subject: [PATCH 2/5] add phimoe to tunner --- llms/mlx_lm/tuner/utils.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/llms/mlx_lm/tuner/utils.py b/llms/mlx_lm/tuner/utils.py index c6af97306..92afd97c7 100644 --- a/llms/mlx_lm/tuner/utils.py +++ b/llms/mlx_lm/tuner/utils.py @@ -96,6 +96,7 @@ def to_lora(layer): "stablelm", "qwen2", "qwen2_moe", + "phimoe", "gemma", "gemma2", "starcoder2", @@ -104,7 +105,7 @@ def to_lora(layer): "deepseek", ]: keys = set(["self_attn.q_proj", "self_attn.v_proj"]) - if model.model_type == "mixtral": + if model.model_type in ["mixtral", "phimoe"]: keys.add("block_sparse_moe.gate") if model.model_type == "qwen2_moe": keys.add("mlp.gate") From e3df32430e49f22ab672962cb4a008626c867c03 Mon Sep 17 00:00:00 2001 From: Prince Canuma Date: Sat, 24 Aug 2024 08:48:10 +0200 Subject: [PATCH 3/5] add switch_mlp --- llms/mlx_lm/models/phimoe.py | 165 +++++++++++++++++------------------ 1 file changed, 79 insertions(+), 86 deletions(-) diff --git a/llms/mlx_lm/models/phimoe.py b/llms/mlx_lm/models/phimoe.py index b34d3bcd3..185a5fb01 100644 --- a/llms/mlx_lm/models/phimoe.py +++ b/llms/mlx_lm/models/phimoe.py @@ -1,29 +1,32 @@ import math from dataclasses import dataclass -from typing import List, Optional, Tuple, Union +from typing import Dict, List, Optional, Tuple, Union import mlx.core as mx import mlx.nn as nn from .base import BaseModelArgs, KVCache, create_attention_mask from .su_rope import SuScaledRotaryEmbedding +from .switch_layers import SwitchGLU @dataclass class ModelArgs(BaseModelArgs): model_type: str = "phimoe" - vocab_size: int = 30000 - hidden_size: int = 1024 - intermediate_size: int = 4096 - num_hidden_layers: int = 12 - num_attention_heads: int = 16 - num_key_value_heads: int = 16 - max_position_embeddings: int = 2048 + vocab_size: int = 32064 + hidden_size: int = 4096 + intermediate_size: int = 6400 + num_hidden_layers: int = 32 + num_attention_heads: int = 32 + num_key_value_heads: int = 8 + max_position_embeddings: int = 131072 + original_max_position_embeddings: int = 4096 initializer_range: float = 0.02 rms_norm_eps: float = 1e-6 pad_token_id: Optional[int] = None rope_traditional: bool = False - num_local_experts: int = 8 + rope_scaling: Optional[Dict[str, Union[float, List[float]]]] = None + num_local_experts: int = 16 num_experts_per_tok: int = 2 attention_bias: bool = False rope_theta: float = 10000.0 @@ -59,7 +62,7 @@ def __init__(self, args: ModelArgs): self.q_proj = nn.Linear(dim, n_heads * head_dim, bias=True) self.k_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=True) self.v_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=True) - self.o_proj = nn.Linear(n_heads * head_dim, dim, bias=False) + self.o_proj = nn.Linear(n_heads * head_dim, dim, bias=True) rope_scale = 1.0 if args.rope_scaling and args.rope_scaling["type"] in ["longrope", "su"]: @@ -114,26 +117,6 @@ def __call__( return self.o_proj(output) -class PhiMoEBlockSparseTop2MLP(nn.Module): - def __init__(self, args: ModelArgs): - super().__init__() - self.ffn_dim = args.intermediate_size - self.hidden_dim = args.hidden_size - - self.w1 = nn.Linear(self.hidden_dim, self.ffn_dim, bias=False) - self.w2 = nn.Linear(self.ffn_dim, self.hidden_dim, bias=False) - self.w3 = nn.Linear(self.hidden_dim, self.ffn_dim, bias=False) - - self.act_fn = nn.GELU() - - def __call__(self, hidden_states): - current_hidden_states = self.act_fn(self.w1(hidden_states)) * self.w3( - hidden_states - ) - current_hidden_states = self.w2(current_hidden_states) - return current_hidden_states - - class PhiMoESparseMoeBlock(nn.Module): def __init__(self, args: ModelArgs): super().__init__() @@ -143,32 +126,20 @@ def __init__(self, args: ModelArgs): self.top_k = args.num_experts_per_tok self.gate = nn.Linear(self.hidden_dim, self.num_experts, bias=False) - self.experts = [PhiMoEBlockSparseTop2MLP(args) for _ in range(self.num_experts)] - - def __call__(self, hidden_states): - batch_size, sequence_length, hidden_dim = hidden_states.shape - hidden_states = hidden_states.reshape(-1, hidden_dim) - - router_logits = self.gate(hidden_states) - routing_weights = mx.softmax(router_logits, axis=-1) - expert_indices = mx.argmax(routing_weights, axis=-1) - - final_hidden_states = mx.zeros((batch_size * sequence_length, hidden_dim)) - - for expert_idx in range(self.num_experts): - expert_layer = self.experts[expert_idx] - expert_mask = expert_indices == expert_idx - if mx.sum(expert_mask) > 0: - expert_input = hidden_states[expert_mask] - expert_output = expert_layer(expert_input) - final_hidden_states = mx.where( - expert_mask[:, None], expert_output, final_hidden_states - ) + self.switch_mlp = SwitchGLU(self.hidden_dim, self.ffn_dim, self.num_experts) - final_hidden_states = final_hidden_states.reshape( - batch_size, sequence_length, hidden_dim - ) - return final_hidden_states, router_logits + def __call__(self, x: mx.array) -> mx.array: + gates = self.gate(x) + + k = self.top_k + inds = mx.stop_gradient(mx.argpartition(-gates, kth=k - 1, axis=-1)[..., :k]) + scores = mx.take_along_axis(gates, inds, axis=-1) + scores = mx.softmax(scores, axis=-1, precise=True) + + y = self.switch_mlp(x, inds) + y = (y * scores[..., None]).sum(axis=-2) + + return y class PhiMoEDecoderLayer(nn.Module): @@ -183,47 +154,52 @@ def __init__(self, args: ModelArgs): args.hidden_size, eps=args.rms_norm_eps ) - def __call__(self, hidden_states, attention_mask=None, position_ids=None): - residual = hidden_states - hidden_states = self.input_layernorm(hidden_states) + def __call__( + self, + x: mx.array, + mask: Optional[mx.array] = None, + cache: Optional[KVCache] = None, + ) -> mx.array: + residual = x + hidden_states = self.input_layernorm(x) - hidden_states = self.self_attn( - hidden_states=hidden_states, - attention_mask=attention_mask, - position_ids=position_ids, - ) + hidden_states = self.self_attn(x=hidden_states, mask=mask, cache=cache) hidden_states = residual + hidden_states residual = hidden_states hidden_states = self.post_attention_layernorm(hidden_states) - hidden_states, router_logits = self.block_sparse_moe(hidden_states) + hidden_states = self.block_sparse_moe(hidden_states) hidden_states = residual + hidden_states - return hidden_states, router_logits + return hidden_states class PhiMoEModel(nn.Module): def __init__(self, args: ModelArgs): super().__init__() self.args = args - self.padding_idx = args.pad_token_id self.vocab_size = args.vocab_size - self.embed_tokens = nn.Embedding( - args.vocab_size, args.hidden_size, self.padding_idx - ) + self.embed_tokens = nn.Embedding(args.vocab_size, args.hidden_size) self.layers = [PhiMoEDecoderLayer(args) for _ in range(args.num_hidden_layers)] self.norm = nn.LayerNorm(args.hidden_size, eps=args.rms_norm_eps) - def __call__(self, input_ids, attention_mask=None, position_ids=None): - hidden_states = self.embed_tokens(input_ids) + def __call__( + self, + inputs: mx.array, + cache=None, + ) -> mx.array: + h = self.embed_tokens(inputs) + + mask = create_attention_mask(h, cache) - for layer in self.layers: - hidden_states, _ = layer(hidden_states, attention_mask, position_ids) + if cache is None: + cache = [None] * len(self.layers) - hidden_states = self.norm(hidden_states) + for layer, c in zip(self.layers, cache): + h = layer(h, mask, c) - return hidden_states + return self.norm(h) class Model(nn.Module): @@ -231,12 +207,35 @@ def __init__(self, args: ModelArgs): super().__init__() self.args = args self.model = PhiMoEModel(args) - self.lm_head = nn.Linear(args.hidden_size, args.vocab_size, bias=False) + self.lm_head = nn.Linear(args.hidden_size, args.vocab_size, bias=True) - def __call__(self, input_ids, attention_mask=None, position_ids=None): - hidden_states = self.model(input_ids, attention_mask, position_ids) - logits = self.lm_head(hidden_states) - return logits + def __call__( + self, + inputs: mx.array, + cache=None, + ): + out = self.model(inputs, cache) + return self.lm_head(out) + + def sanitize(self, weights): + if "model.layers.0.block_sparse_moe.experts.0.w1.weight" not in weights: + return weights + for l in range(self.args.num_hidden_layers): + prefix = f"model.layers.{l}" + for n, m in [("w1", "gate_proj"), ("w2", "down_proj"), ("w3", "up_proj")]: + for k in ["weight", "scales", "biases"]: + if f"{prefix}.block_sparse_moe.experts.0.{n}.{k}" in weights: + to_join = [ + weights.pop( + f"{prefix}.block_sparse_moe.experts.{e}.{n}.{k}" + ) + for e in range(self.args.num_local_experts) + ] + weights[f"{prefix}.block_sparse_moe.switch_mlp.{m}.{k}"] = ( + mx.stack(to_join) + ) + + return weights @property def layers(self): @@ -246,12 +245,6 @@ def layers(self): def head_dim(self): return self.args.hidden_size // self.args.num_attention_heads - def sanitize(self, weights): - # Remove unused precomputed rotary freqs - return { - k: v for k, v in weights.items() if "self_attn.rotary_emb.inv_freq" not in k - } - @property def n_kv_heads(self): return self.args.num_key_value_heads From d76417197f98a38f468da81e294c5487b8f4102c Mon Sep 17 00:00:00 2001 From: Prince Canuma Date: Sat, 24 Aug 2024 09:13:03 +0200 Subject: [PATCH 4/5] fix SuScaled args --- llms/mlx_lm/models/phimoe.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/llms/mlx_lm/models/phimoe.py b/llms/mlx_lm/models/phimoe.py index 185a5fb01..82b5fa672 100644 --- a/llms/mlx_lm/models/phimoe.py +++ b/llms/mlx_lm/models/phimoe.py @@ -68,9 +68,7 @@ def __init__(self, args: ModelArgs): if args.rope_scaling and args.rope_scaling["type"] in ["longrope", "su"]: self.rope = SuScaledRotaryEmbedding( head_dim, - traditional=False, base=args.rope_theta, - scale=rope_scale, max_position_embeddings=args.max_position_embeddings, original_max_position_embeddings=args.original_max_position_embeddings, short_factor=args.rope_scaling["short_factor"], From 0e7f44a87526b65808005a599aa147a652c23966 Mon Sep 17 00:00:00 2001 From: Awni Hannun Date: Sat, 24 Aug 2024 06:45:20 -0700 Subject: [PATCH 5/5] nits --- llms/mlx_lm/models/phimoe.py | 64 ++++++++++------------------------- llms/mlx_lm/models/su_rope.py | 6 +++- 2 files changed, 22 insertions(+), 48 deletions(-) diff --git a/llms/mlx_lm/models/phimoe.py b/llms/mlx_lm/models/phimoe.py index 82b5fa672..db6bd4b55 100644 --- a/llms/mlx_lm/models/phimoe.py +++ b/llms/mlx_lm/models/phimoe.py @@ -1,11 +1,12 @@ +# Copyright © 2024 Apple Inc. import math from dataclasses import dataclass -from typing import Dict, List, Optional, Tuple, Union +from typing import Dict, List, Optional, Union import mlx.core as mx import mlx.nn as nn -from .base import BaseModelArgs, KVCache, create_attention_mask +from .base import BaseModelArgs, create_attention_mask from .su_rope import SuScaledRotaryEmbedding from .switch_layers import SwitchGLU @@ -21,31 +22,12 @@ class ModelArgs(BaseModelArgs): num_key_value_heads: int = 8 max_position_embeddings: int = 131072 original_max_position_embeddings: int = 4096 - initializer_range: float = 0.02 rms_norm_eps: float = 1e-6 - pad_token_id: Optional[int] = None - rope_traditional: bool = False - rope_scaling: Optional[Dict[str, Union[float, List[float]]]] = None + rope_scaling: Dict[str, Union[float, List[float]]] = None num_local_experts: int = 16 num_experts_per_tok: int = 2 - attention_bias: bool = False rope_theta: float = 10000.0 - def __post_init__(self): - if self.num_key_value_heads is None: - self.num_key_value_heads = self.num_attention_heads - - if self.rope_scaling: - required_keys = {"long_factor", "type"} - if not all(key in self.rope_scaling for key in required_keys): - raise ValueError(f"rope_scaling must contain keys {required_keys}") - - if self.rope_scaling["type"] not in ["longrope", "su", "linear"]: - print( - "[WARNING] rope_scaling 'type' currently only supports 'linear', 'su', and 'longrope'; setting rope scaling to false." - ) - self.rope_scaling = None - class Attention(nn.Module): def __init__(self, args: ModelArgs): @@ -53,7 +35,6 @@ def __init__(self, args: ModelArgs): dim = args.hidden_size self.n_heads = n_heads = args.num_attention_heads - assert args.num_key_value_heads is not None self.n_kv_heads = n_kv_heads = args.num_key_value_heads head_dim = args.hidden_size // n_heads @@ -64,32 +45,22 @@ def __init__(self, args: ModelArgs): self.v_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=True) self.o_proj = nn.Linear(n_heads * head_dim, dim, bias=True) - rope_scale = 1.0 - if args.rope_scaling and args.rope_scaling["type"] in ["longrope", "su"]: - self.rope = SuScaledRotaryEmbedding( - head_dim, - base=args.rope_theta, - max_position_embeddings=args.max_position_embeddings, - original_max_position_embeddings=args.original_max_position_embeddings, - short_factor=args.rope_scaling["short_factor"], - long_factor=args.rope_scaling["long_factor"], - ) - else: - if args.rope_scaling and args.rope_scaling["type"] == "linear": - assert isinstance(args.rope_scaling["factor"], float) - rope_scale = 1 / args.rope_scaling["factor"] - self.rope = nn.RoPE( - head_dim, - traditional=args.rope_traditional, - base=args.rope_theta, - scale=rope_scale, - ) + self.rope = SuScaledRotaryEmbedding( + head_dim, + base=args.rope_theta, + max_position_embeddings=args.max_position_embeddings, + original_max_position_embeddings=args.original_max_position_embeddings, + short_factor=args.rope_scaling["short_factor"], + long_factor=args.rope_scaling["long_factor"], + short_mscale=args.rope_scaling["short_mscale"], + long_mscale=args.rope_scaling["long_mscale"], + ) def __call__( self, x: mx.array, mask: Optional[mx.array] = None, - cache: Optional[KVCache] = None, + cache=None, ) -> mx.array: B, L, D = x.shape @@ -156,12 +127,11 @@ def __call__( self, x: mx.array, mask: Optional[mx.array] = None, - cache: Optional[KVCache] = None, + cache=None, ) -> mx.array: residual = x hidden_states = self.input_layernorm(x) - - hidden_states = self.self_attn(x=hidden_states, mask=mask, cache=cache) + hidden_states = self.self_attn(hidden_states, mask=mask, cache=cache) hidden_states = residual + hidden_states residual = hidden_states diff --git a/llms/mlx_lm/models/su_rope.py b/llms/mlx_lm/models/su_rope.py index f96b99574..9c414afda 100644 --- a/llms/mlx_lm/models/su_rope.py +++ b/llms/mlx_lm/models/su_rope.py @@ -16,6 +16,8 @@ def __init__( original_max_position_embeddings: int = 4096, short_factor: Union[List[float], float] = 1.0, long_factor: Union[List[float], float] = 1.0, + short_mscale: float = None, + long_mscale: float = None, ): """ Phi3Su Scaled Rotary Embedding layer for Phi-3 models. @@ -37,12 +39,14 @@ def __init__( long_factor (float or list[float], optional): List of scaling factors for sequences of length greater than ``original_max_position_embeddings``. Default: ``1.0``. + short_mscale (float, optional): Scale the input prior to embedding. + long_mscale (float, optional): Scale the input prior to embedding. """ super().__init__() freqs = base ** (mx.arange(0, dims, 2, dtype=mx.float32) / dims) self._freqs = mx.array(long_factor, dtype=mx.float32) * freqs self.original_max_position_embeddings = original_max_position_embeddings - self.scale = math.sqrt( + self.scale = long_mscale or math.sqrt( 1 + math.log(max_position_embeddings / original_max_position_embeddings) / math.log(original_max_position_embeddings)