|
| 1 | +"""Implementation for Mistral architecture.""" |
| 2 | +import dataclasses |
| 3 | + |
| 4 | +from tvm import tir |
| 5 | +from tvm.relax.frontend import nn |
| 6 | +from tvm.relax.frontend.nn import Tensor, op |
| 7 | + |
| 8 | +from mlc_chat import op as op_ext |
| 9 | +from mlc_chat.model.mistral.mistral_model import ( |
| 10 | + MistralAttention, |
| 11 | + MistralConfig, |
| 12 | + MistralForCasualLM, |
| 13 | + MistralModel, |
| 14 | + RotaryEmbedding, |
| 15 | +) |
| 16 | +from mlc_chat.nn.expert import MixtralExperts |
| 17 | +from mlc_chat.support import logging |
| 18 | +from mlc_chat.support import tensor_parallel as tp |
| 19 | + |
| 20 | +logger = logging.getLogger(__name__) |
| 21 | + |
| 22 | + |
| 23 | +@dataclasses.dataclass |
| 24 | +class MixtralConfig(MistralConfig): # pylint: disable=too-many-instance-attributes |
| 25 | + """Configuration of the Mixtral model.""" |
| 26 | + |
| 27 | + num_local_experts: int = 0 |
| 28 | + num_experts_per_tok: int = 0 |
| 29 | + |
| 30 | + |
| 31 | +# pylint: disable=invalid-name,missing-docstring,too-many-locals,fixme |
| 32 | + |
| 33 | + |
| 34 | +class MixtralMoE(nn.Module): |
| 35 | + """Mixture of experts""" |
| 36 | + |
| 37 | + def __init__(self, config: MixtralConfig): |
| 38 | + super().__init__() |
| 39 | + self.num_experts_per_tok = config.num_experts_per_tok |
| 40 | + self.num_local_experts = config.num_local_experts |
| 41 | + self.intermediate_size = config.intermediate_size // config.tensor_parallel_shards |
| 42 | + self.gate = nn.Linear( |
| 43 | + in_features=config.hidden_size, |
| 44 | + out_features=config.num_local_experts, |
| 45 | + bias=False, |
| 46 | + ) |
| 47 | + self.e1_e3 = MixtralExperts( |
| 48 | + self.num_local_experts, |
| 49 | + in_features=config.hidden_size, |
| 50 | + out_features=2 * self.intermediate_size, |
| 51 | + ) |
| 52 | + self.e2 = MixtralExperts( |
| 53 | + self.num_local_experts, |
| 54 | + in_features=self.intermediate_size, |
| 55 | + out_features=config.hidden_size, |
| 56 | + ) |
| 57 | + self.dtype = "float32" |
| 58 | + |
| 59 | + def forward(self, x: Tensor): |
| 60 | + def _expert_forward(x: Tensor, indptr: Tensor): |
| 61 | + x1_x3 = self.e1_e3(x, indptr) |
| 62 | + x1, x3 = op.split(x1_x3, indices_or_sections=2, axis=-1) |
| 63 | + x = self.e2(op.silu(x1) * x3, indptr) |
| 64 | + return x |
| 65 | + |
| 66 | + experts_per_tok = self.num_experts_per_tok # activated experts per token |
| 67 | + local_experts = self.num_local_experts # total number of experts |
| 68 | + batch_size, seq_len, hidden_size = x.shape |
| 69 | + num_tokens = batch_size * seq_len |
| 70 | + x = x.reshape(num_tokens, hidden_size) |
| 71 | + # gate: [num_tokens, local_experts] |
| 72 | + gate: Tensor = self.gate(x) |
| 73 | + # expert_weights: [num_tokens, experts_per_tok] |
| 74 | + # expert_indices: [num_tokens, experts_per_tok] |
| 75 | + expert_weights, expert_indices = op_ext.moe_misc.topk(gate, experts_per_tok) |
| 76 | + expert_weights = op.softmax(expert_weights.astype("float32"), axis=-1).astype(self.dtype) |
| 77 | + if num_tokens == 1: |
| 78 | + # x: [num_tokens * experts_per_tok, hidden_size] |
| 79 | + x = _expert_forward(x, expert_indices) |
| 80 | + else: |
| 81 | + # cumsum: [num_tokens * total_experts] |
| 82 | + cumsum = op_ext.moe_misc.moe_cumsum(expert_indices, local_experts) |
| 83 | + # indices: [num_tokens * experts_per_tok] |
| 84 | + indices = op_ext.moe_misc.get_indices(cumsum, expert_indices) |
| 85 | + # indptr: [num_local_experts + 1] |
| 86 | + indptr = op_ext.moe_misc.get_indptr(cumsum, local_experts) |
| 87 | + # x: [num_tokens * experts_per_tok, hidden_size] |
| 88 | + x = op.take(x, indices / experts_per_tok, axis=0) |
| 89 | + x = _expert_forward(x, indptr) |
| 90 | + x = op_ext.moe_misc.scatter_output(x, indices) |
| 91 | + # x: [num_tokens, experts_per_tok, hidden_size] |
| 92 | + x = x.reshape( # pylint: disable=too-many-function-args |
| 93 | + num_tokens, experts_per_tok, hidden_size |
| 94 | + ) * expert_weights.reshape( # pylint: disable=too-many-function-args |
| 95 | + num_tokens, experts_per_tok, 1 |
| 96 | + ) |
| 97 | + # x: [num_tokens, hidden_size] |
| 98 | + x = op_ext.moe_misc.moe_sum(x, dim=1) |
| 99 | + x = x.reshape(batch_size, seq_len, hidden_size) # pylint: disable=too-many-function-args |
| 100 | + return x |
| 101 | + |
| 102 | + |
| 103 | +class MixtralDecoderLayer(nn.Module): |
| 104 | + """Mixtral decoder layer""" |
| 105 | + |
| 106 | + def __init__(self, config: MixtralConfig, rotary_embedding: RotaryEmbedding): |
| 107 | + eps = config.rms_norm_eps |
| 108 | + self.self_attn = MistralAttention(config, rotary_embedding) |
| 109 | + self.moe = MixtralMoE(config) |
| 110 | + self.input_layernorm = nn.RMSNorm(config.hidden_size, -1, eps, bias=False) |
| 111 | + self.post_attention_layernorm = nn.RMSNorm(config.hidden_size, -1, eps, bias=False) |
| 112 | + |
| 113 | + def _set_tp(): |
| 114 | + def _set(layer, hint): |
| 115 | + layer.weight.attrs["shard_strategy"] = hint |
| 116 | + |
| 117 | + hd = config.head_dim |
| 118 | + q = self.self_attn.num_q_heads * hd |
| 119 | + k = self.self_attn.num_kv_heads * hd |
| 120 | + v = self.self_attn.num_kv_heads * hd |
| 121 | + i = self.moe.intermediate_size |
| 122 | + _set(self.self_attn.qkv_proj, tp.ShardSingleDim("_shard_qkv", segs=[q, k, v], dim=0)) |
| 123 | + _set(self.self_attn.o_proj, tp.ShardSingleDim("_shard_o", dim=1)) |
| 124 | + _set(self.moe.e1_e3, tp.ShardSingleDim("_shard_mlp_up", segs=[i, i], dim=1)) |
| 125 | + _set(self.moe.e2, tp.ShardSingleDim("_shard_mlp_down", dim=2)) |
| 126 | + |
| 127 | + self.tensor_parallel_shards = config.tensor_parallel_shards |
| 128 | + _set_tp() |
| 129 | + |
| 130 | + def forward( # pylint: disable=too-many-arguments |
| 131 | + self, |
| 132 | + hidden_states: Tensor, |
| 133 | + attention_mask: Tensor, |
| 134 | + rolling_cache_len: tir.Var, |
| 135 | + kv_seq_len: tir.Var, |
| 136 | + cache_offset: tir.Var, |
| 137 | + ): |
| 138 | + """Forward pass of a decoder layer; calculate attention, and add an residual connection.""" |
| 139 | + |
| 140 | + def _apply_residual(out, residual): |
| 141 | + if self.tensor_parallel_shards > 1: |
| 142 | + return op.ccl_allreduce(out + residual / self.tensor_parallel_shards, "sum") |
| 143 | + return out + residual |
| 144 | + |
| 145 | + out = self.self_attn( |
| 146 | + self.input_layernorm(hidden_states), |
| 147 | + attention_mask, |
| 148 | + rolling_cache_len, |
| 149 | + kv_seq_len, |
| 150 | + cache_offset, |
| 151 | + ) |
| 152 | + hidden_states = _apply_residual(out, residual=hidden_states) |
| 153 | + out = self.moe(self.post_attention_layernorm(hidden_states)) |
| 154 | + hidden_states = _apply_residual(out, residual=hidden_states) |
| 155 | + return hidden_states |
| 156 | + |
| 157 | + |
| 158 | +class MixtralModel(MistralModel): |
| 159 | + """Exact same as LlamaModel.""" |
| 160 | + |
| 161 | + def __init__(self, config: MixtralConfig): |
| 162 | + super().__init__(config) |
| 163 | + rotary_embedding = RotaryEmbedding(config) |
| 164 | + self.layers = nn.ModuleList( |
| 165 | + [MixtralDecoderLayer(config, rotary_embedding) for _ in range(config.num_hidden_layers)] |
| 166 | + ) |
| 167 | + |
| 168 | + |
| 169 | +class MixtralForCasualLM(MistralForCasualLM): |
| 170 | + """Same as LlamaForCausalLM, except for the use of sliding window attention.""" |
| 171 | + |
| 172 | + def __init__(self, config: MixtralConfig): |
| 173 | + super().__init__(config) |
| 174 | + self.model = MixtralModel(config) |
0 commit comments