AI Logic

Architectures

Mixtral

Updated:

Mixtral architecture. Left: the overall flow (a token sequence with a 32,000-token vocabulary and a 32,768-token context, token embedding, 32 decoder layers, a final RMSNorm, and next-token prediction) and the range covered by causal attention. Right: inside a decoder layer (GQA self-attention with pre-RMSNorm, and the MoE layer), and inside the MoE layer (an example where the router scores xΒ·Wg, keeps the top 2, turns them into weights with softmax, and sums the weighted outputs of the selected experts E1 and E5 out of 8)

Background and overview

Mixtral (Mixtral 8x7B) is a language model that uses the same decoder as Mistral 7B but replaces the feed-forward block in every layer with a mixture-of-experts (MoE) layer that "picks 2 of 8 experts". Jiang et al. at Mistral AI introduced it in 2024 in the paper "Mixtral of Experts" and released it under the Apache 2.0 license.

Language models tend to improve as they get more parameters, but the compute needed to process each token grows as well. Sparsely-Gated MoE prepares many "experts" (small networks) and uses only some of them for each input, so parameters can grow with almost no increase in compute. Mixtral applies this idea to Mistral 7B.

The key points of Mixtral are as follows (paper abstract and Section 1).

  • In every layer and for every token, a router picks 2 of 8 experts and sums their outputs with weights.
  • The model has 47 billion (47B) parameters in total, but uses only 13 billion (13B) to process each token.
  • The context is 32,768 tokens (32k), and the training data includes a larger share of multilingual text.
  • On every benchmark evaluated, it outperforms or matches Llama 2 70B and GPT-3.5. It beats Llama 2 70B by a wide margin in mathematics, code, and multilingual tasks.

Mixtral 8x7B Instruct, fine-tuned to follow instructions, outperformed GPT-3.5 Turbo, Claude-2.1, Gemini Pro, and Llama 2 70B Chat in human preference evaluations.

Architecture: MoE layers and the router

Apart from the feed-forward block, Mixtral has the same architecture as Mistral 7B. The left side of the figure at the top of this article shows the overall flow and the range attention can see; the right side shows the inside of one decoder layer and how the MoE layer processes a single token.

The main settings are as follows (Table 1 of the paper).

ItemValue
Vector size dd4096
Number of layers32
Query heads / key-value heads32 / 8 (GQA)
Expert hidden size14336
Number of experts nn8
Experts used per token KK2
Context length32,768
Vocabulary32,000

There are two changes from Mistral 7B (Section 2 of the paper).

  1. Attend to the full context: Mixtral drops Mistral 7B's sliding window and attends to the entire 32k-token context with ordinary causal attention.
  2. Turn the feed-forward block into an MoE layer: In every layer, the single feed-forward block is replaced by 8 experts and a router.

The MoE layer processes the vector xx of one token in the following order (Section 2.1 of the paper).

  1. Score with the router: A linear layer WgW_g produces a score (logit) xβ‹…Wgx \cdot W_g for each of the 8 experts.
  2. Keep only the top 2: All scores except the two highest are set to βˆ’βˆž-\infty.
  3. Convert to weights: A softmax is applied. Experts at βˆ’βˆž-\infty get weight 0, and the weights of the remaining two sum to 1.
  4. Compute only the 2 selected experts: Each expert is a SwiGLU feed-forward block, the same as in LLaMA and Mistral 7B.
  5. Sum with weights: The two outputs are multiplied by their weights and added to form the output of the MoE layer.

In equations, the output yy is:

y=βˆ‘i=0nβˆ’1Softmax(Top2(xβ‹…Wg))iβ‹…SwiGLUi(x)y = \sum_{i=0}^{n-1} \mathrm{Softmax}\bigl(\mathrm{Top2}(x \cdot W_g)\bigr)_i \cdot \mathrm{SwiGLU}_i(x) (TopK(β„“))i={β„“i(β„“iΒ isΒ amongΒ theΒ topΒ K)βˆ’βˆž(otherwise)\bigl(\mathrm{TopK}(\ell)\bigr)_i = \begin{cases} \ell_i & (\ell_i \text{ is among the top } K) \\ -\infty & (\text{otherwise}) \end{cases}

Experts with weight 0 do not need to be computed, so 6 of the 8 can be skipped. Which experts are selected changes from token to token and from layer to layer.

The paper notes that this design is close to GShard. The differences are that GShard makes only every other layer an MoE layer while Mixtral makes every layer one, and that GShard uses a more elaborate rule for choosing the second expert.

Why a large model's performance comes at a small model's compute

In an MoE model, the number of parameters and the number of parameters used per token are separate quantities. The paper distinguishes them as the "sparse parameter count" and the "active parameter count".

  • The sparse parameter count grows in proportion to the number of experts nn. It relates to how much knowledge the model can store.
  • The active parameter count grows in proportion to the number of selected experts KK (up to nn). It is directly proportional to the compute needed to process one token.

Keeping KK fixed at 2 and increasing nn adds parameters while keeping compute roughly constant. Mixtral has 47B parameters in total but uses 13B, so its compute is about that of an ordinary 13B model. Even so, it matches or exceeds Llama 2 70B, which uses 5 times as many active parameters.

Think of a hospital: there may be 8 specialists in internal medicine, surgery, ophthalmology, and so on, but each patient sees only the 2 chosen by the reception desk (the router). The hospital as a whole has broad knowledge, yet each patient costs only two doctors' time. As shown later, however, Mixtral's experts are not divided by topic into a "math expert" or a "biology expert".

Even though compute is about that of a 13B model, all 47B parameters must be loaded into memory, because it is not known in advance which tokens will use which experts. The paper also notes that comparing active parameter counts reflects only inference compute and ignores memory cost and hardware utilization. In addition, the router and the memory loads needed to run several experts on one device add overhead, so MoE suits workloads that process many inputs together (large batches).

Despite the name "8x7B", the total is 47B rather than 8 Γ— 7 = 56B. Only the feed-forward blocks are experts; attention, embeddings, and the rest are shared by all 8.

What the router bases its expert choice on

The paper examined whether the experts specialized by domain during training (Section 5 of the paper). For each domain of The Pile validation set, it compared the fraction of tokens routed to each expert at layers 0, 15, and 31 (Figure 7).

The result was that no clear differences by domain were found. Expert assignments were nearly identical for arXiv papers (LaTeX), biology (PubMed abstracts), and philosophy (PhilPapers). Only the synthetic mathematics data (DM Mathematics) showed a slight difference.

What did appear was routing that follows sentence structure (syntax) (Figure 8).

  • Python's self and the English word Question are often sent to the same expert even when split into multiple tokens.
  • Indentation tokens in code are always sent to the same expert, especially in the first and last layers.
  • Consecutive tokens tend to be sent to the same expert.

For the third point, the paper measured how often tokens ii and i+1i+1 share the same first-choice expert (Table 5). Random assignment would give 12.5%. At layer 0 the rate was 13.6–14.9%, close to random, but at layer 15 it rose sharply to 23.6–28.4%.

This tendency to pick the same expert for consecutive tokens can be exploited in implementations. It helps caching that reduces how often experts are reloaded from memory, but when experts are spread across several GPUs (expert parallelism), it can concentrate work on particular GPUs.

Experimental results

The paper re-evaluates every compared model with its own evaluation pipeline (Table 2 of the paper, %).

ModelActive parametersMMLUHellaSwagWinoGrandeARC-cNQTriviaQAHumanEvalMBPPMATHGSM8K
Llama 2 13B13B55.680.772.948.816.764.018.935.46.034.3
Llama 2 70B70B69.985.480.456.525.473.029.349.813.869.6
Mistral 7B7B62.581.074.254.923.262.526.250.212.750.0
Mixtral 8x7B13B70.684.477.259.730.671.540.260.728.474.4

(MMLU is 5-shot, commonsense reasoning is zero-shot, NQ and TriviaQA are 5-shot, HumanEval is zero-shot, MBPP is 3-shot, MATH is 4-shot with majority voting over 4, and GSM8K is 8-shot with majority voting over 8)

With 5 times fewer active parameters, Mixtral matches or beats Llama 2 70B on most items. It is far ahead on code (HumanEval, MBPP) and mathematics (MATH, GSM8K).

Comparison with GPT-3.5 (Table 3 of the paper; evaluation settings differ from the table above)

BenchmarkLlama 2 70BGPT-3.5Mixtral 8x7B
MMLU69.970.070.6
HellaSwag (10-shot)87.185.586.7
ARC Challenge (25-shot)85.185.285.8
WinoGrande (5-shot)83.281.681.2
MBPP (pass@1)49.852.260.7
GSM8K (5-shot)53.657.158.4
MT-Bench (instruction-tuned models)6.868.328.30

Multilingual (Table 4 of the paper): Mixtral was trained with a much larger share of multilingual data than Mistral 7B. It outperforms Llama 2 70B on ARC Challenge, HellaSwag, and MMLU in French, German, Spanish, and Italian. For example, French MMLU is 70.9% versus 64.3% for Llama 2 70B.

Long context (Section 3.2 of the paper): On a task that asks the model to retrieve a passkey hidden somewhere in a long input, it achieves 100% accuracy regardless of context length or passkey position. Also, perplexity on a dataset of mathematical proofs decreases monotonically as the context grows.

Instruction-following model (Section 4 of the paper): Mixtral 8x7B Instruct, trained with SFT followed by DPO (Direct Preference Optimization) on data indicating which of two responses is better, scores 8.30 on MT-Bench, the highest among open-weight models as of December 2023. In LMSys human evaluation (Arena Elo) it reaches 1121, above Claude-2.1 (1117), GPT-3.5-Turbo (up to 1117), Gemini Pro (1111), and Llama 2 70B Chat (1077).

Practical considerations

Keep the following points in mind when using Mixtral.

  • Memory for 47B is required: Compute is about that of 13B, but all experts must be kept loaded. The 16-bit weights alone take about 94 GB (47B Γ— 2 bytes), which does not fit on a single typical GPU. Consider quantization or splitting across multiple GPUs.
  • Small batches are not as fast as the compute suggests: The router and loading expert weights add overhead. The paper also notes that Mixtral suits workloads that process many inputs together. To run it efficiently, use an inference library that supports MoE-specific kernels (the paper integrated Megablocks CUDA kernels into vLLM).
  • Experts are not divided by domain: Uses such as "extract only the math expert" are not possible.
  • Detailed training settings are not published: The paper does not describe the contents or token count of the training data, or the training loss (for example, measures to balance expert usage).

When training MoE layers yourself, the router is known to tend to favor a few experts, leaving the rest barely trained (Sparsely-Gated MoE and Switch Transformer add an auxiliary loss to balance usage). The Mixtral paper does not describe how it handles this, so before further training, check your library's settings (whether an auxiliary loss is used and its strength).

Comparison with other models

Comparing Mixtral with its base model and contemporary models from the same angles gives the following.

ModelTotal parametersParameters used per tokenFeed-forwardContext lengthLicense
Mistral 7B7B7BOne SwiGLU8192 (sliding window)Apache 2.0
Llama 2 70B70B70BOne SwiGLU4096Research and commercial (custom license)
Mixtral 8x7B47B13B2 of 8 SwiGLU experts32,768Apache 2.0

As an MoE method, Mixtral does not propose a new router. It applies the same simple router as Sparsely-Gated MoE, a softmax over the top KK, to every layer. It differs in its selection rule from Switch Transformer, which picks a single expert, and from Expert Choice routing, where experts choose tokens.

A rough guide to choosing:

  • Plenty of GPU memory, and you want high performance at low compute: Mixtral matches or exceeds Llama 2 70B at roughly 13B-level compute.
  • You want to run on a single GPU, or memory is limited: Mistral 7B, with fewer total parameters, is easier to handle.
  • You need European languages other than English, or long context: Mixtral, trained with more multilingual data and a 32k context, is a good fit.
  • You want to learn how MoE works from the basics: Start with Sparsely-Gated MoE to understand the router and top-KK selection; Mixtral's architecture then becomes easy to follow.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F

"""
A minimal Mixtral MoE layer written directly from the equation in Section 2.1 of the paper
  y = Ξ£_i Softmax(Top2(x Β· W_g))_i Β· SwiGLU_i(x)
  - Router W_g: a linear layer from d to the number of experts (8)
  - Softmax is taken over the top 2 logits only (the rest are -∞, so their weight is 0)
  - Only the selected experts are computed
No dropout is used, so model.train() and model.eval() compute the same thing
"""

class SwiGLU(nn.Module):
  def __init__(self, dim, hidden):
    super().__init__()
    self.w1 = nn.Linear(dim, hidden, bias=False)
    self.w3 = nn.Linear(dim, hidden, bias=False)
    self.w2 = nn.Linear(hidden, dim, bias=False)

  def forward(self, x):
    return self.w2(F.silu(self.w1(x)) * self.w3(x))


class MoELayer(nn.Module):
  def __init__(self, dim=4096, hidden=14336, n_experts=8, top_k=2):
    super().__init__()
    self.gate = nn.Linear(dim, n_experts, bias=False)      # router W_g
    self.experts = nn.ModuleList(SwiGLU(dim, hidden) for _ in range(n_experts))
    self.top_k = top_k

  def forward(self, x):
    # x: [number of tokens, dim] (batch and sequence flattened together)
    logits = self.gate(x)                                   # [T, 8]
    top_logits, top_idx = logits.topk(self.top_k, dim=-1)   # top 2
    weights = F.softmax(top_logits, dim=-1)                 # softmax over the 2 only (sums to 1)
    y = torch.zeros_like(x)
    for e, expert in enumerate(self.experts):
      token, slot = (top_idx == e).nonzero(as_tuple=True)   # tokens that chose expert e
      if token.numel() == 0:
        continue                                            # skip if no token chose it
      y[token] += weights[token, slot, None] * expert(x[token])
    return y, top_idx


moe = MoELayer(dim=64, hidden=224)                          # try a small size
x = torch.randn(10, 64)
y, chosen = moe(x)
print(y.shape)                                              # torch.Size([10, 64])
print(chosen[:3])                                           # the 2 experts chosen by each token

# Total parameters and parameters used per token (expert part only)
per_expert = sum(p.numel() for p in moe.experts[0].parameters())
print("total:", per_expert * 8 + moe.gate.weight.numel(), " used per token:", per_expert * 2 + moe.gate.weight.numel())


# The pretrained model can be loaded with Hugging Face transformers
# Even in 16-bit it needs about 94 GB of memory, so use multiple GPUs or quantization
# from transformers import AutoTokenizer, AutoModelForCausalLM
# tokenizer = AutoTokenizer.from_pretrained("mistralai/Mixtral-8x7B-v0.1")
# model = AutoModelForCausalLM.from_pretrained("mistralai/Mixtral-8x7B-v0.1", torch_dtype=torch.float16, device_map="auto")

FAQ

Q. Why is the total 47B rather than 56B if the model is "8x7B"?
A.

Only the feed-forward blocks are experts; attention, embeddings, normalization, and the rest are shared by all 8 experts. It is easier to think of it not as 8 copies of Mistral 7B but as Mistral 7B with only the feed-forward part multiplied by 8.

Q. If only 13B is used per token, does it run in the same memory as a 13B model?
A.

No. The selected experts change from token to token and from layer to layer, so all 47B of weights must be kept in memory. What stays at about 13B is the compute per token.

Q. Are the experts divided by domain, such as mathematics or code?
A.

The paper's analysis found no clear division by domain. Instead, it found that the same expert tends to be chosen along lines of sentence structure, such as code indentation or particular words, and that consecutive tokens tend to be sent to the same expert.

References

  1. Jiang, A. Q., Sablayrolles, A., Roux, A., et al. (2024). Mixtral of Experts. arXiv:2401.04088.
  2. Jiang, A. Q., Sablayrolles, A., Mensch, A., et al. (2023). Mistral 7B. arXiv:2310.06825.
  3. Shazeer, N., Mirhoseini, A., Maziarz, K., Davis, A., Le, Q., Hinton, G., & Dean, J. (2017). Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer. ICLR 2017.
  4. Lepikhin, D., Lee, H., Xu, Y., et al. (2021). GShard: Scaling Giant Models with Conditional Computation and Automatic Sharding. ICLR 2021.
  5. Shazeer, N. (2020). GLU Variants Improve Transformer. arXiv:2002.05202.
  6. Rafailov, R., Sharma, A., Mitchell, E., Ermon, S., Manning, C. D., & Finn, C. (2023). Direct Preference Optimization: Your Language Model is Secretly a Reward Model. NeurIPS 2023.