# Mixtral of Experts

The paper introduces Mixtral 8x7B, a Sparse Mixture of Experts (SMoE) language model, showcasing advancements in the field of AI language processing.&#x20;

{% embed url="<https://arxiv.org/abs/2401.04088>" %}
Mixtral of Experts
{% endembed %}

### <mark style="color:purple;">Mixtral 8x7B Overview</mark>

<mark style="color:green;">**Architecture**</mark><mark style="color:green;">:</mark> Mixtral 8x7B is built on the same architecture as Mistral 7B but includes a unique feature where each of its layers contains 8 feedforward blocks, known as experts.

<mark style="color:green;">**Expert Selection**</mark>: For every token in the input, a router network at each layer selects two experts to process the token and combine their outputs. This selective process allows the model to dynamically choose which parts of its network to use for each token.

<mark style="color:green;">**Parameter Efficiency**</mark><mark style="color:green;">:</mark> While the total parameter count for the model is 47 billion, any given token is processed using only 13 billion active parameters, enhancing the model's efficiency during inference.

<mark style="color:green;">**Training and Performance**</mark><mark style="color:green;">:</mark> Mixtral was trained with a large context size of 32,000 tokens and shows superior or comparable performance to Llama 2 70B and GPT-3.5 on various benchmarks, particularly excelling in mathematics, code generation, and multilingual tasks.

### <mark style="color:purple;">Analysis of how Mixture of Experts works</mark>

This excellent article from the famous Cameron Wolfe.  Please visit his website here:

{% embed url="<https://cameronrwolfe.me/>" %}
Cameron Wolfe is a generous AI researcher - bridging the gap between academia and practitioners
{% endembed %}

<mark style="color:green;">Here his full article on how Mixture of Experts works:</mark>

{% embed url="<https://substack.com/@cwolferesearch/note/c-51916763>" %}
Mixture of Experts
{% endembed %}

I have paraphrased his article below:

The paper delves into the <mark style="color:blue;">Sparse Mixture of Experts (MoE) layers</mark> in the context of decoder-only transformer architecture, commonly employed in autoregressive large language models (LLMs).&#x20;

It explains how *<mark style="color:yellow;">**MoEs enhance model capacity while maintaining computational efficiency**</mark>* by selectively activating a subset of parameters during the forward pass.

### <mark style="color:purple;">Key Aspects of MoE in LLMs</mark>

<mark style="color:green;">**Expert Architecture:**</mark> Each expert within an MoE layer is a feed-forward neural network with its unique set of parameters, mirroring the architecture of the standard feed-forward sub-layer in traditional transformer models.

<mark style="color:green;">**Routing Mechanism:**</mark> A router processes each token, producing a probability distribution that *<mark style="color:yellow;">**dictates which expert(s) will process the token.**</mark>*  This selective routing significantly increases model capacity without proportionally increasing computational demands.

<mark style="color:green;">**Sparse Activation:**</mark> In each MoE layer, *<mark style="color:yellow;">**only a few experts are activated for each token,**</mark>* reducing the computational cost compared to a model where all parameters are always active.

<mark style="color:green;">**Implementation in Decoder-only Architecture:**</mark> MoEs are integrated into the decoder-only transformer architecture, replacing the standard feed-forward sub-layers with MoE layers. This architecture is prevalent in autoregressive LLMs.

<mark style="color:green;">**Creating an MoE Layer:**</mark> An MoE layer consists of multiple experts, and the layer replaces the conventional feed-forward sub-layer in the transformer block. This setup allows for the model to scale up the number of experts without incurring the full computational cost typically associated with larger models.

<mark style="color:green;">**Routing Details:**</mark> Routing in MoEs usually employs a softmax gating function that converts the outputs of a linear layer into a probability distribution over experts, guiding the token through the most relevant experts based on the routing mechanism's decision.

<mark style="color:green;">**Popularity of MoEs in LLMs:**</mark> MoEs offer a path to scale model capacity - a crucial factor for improving LLM performance. They allow for significant parameter expansion without commensurate increases in computational requirements during training and inference, making large-scale LLMs more feasible and efficient.

<mark style="color:green;">**Example of MoE Implementation:**</mark> An instance is provided where a model named Grok incorporates eight experts per MoE layer, demonstrating how MoEs function in a practical LLM context. Despite having 314B parameters, Grok only activates 25% of these for any given token, illustrating the efficiency gains from sparse activation.

### <mark style="color:purple;">Definitions</mark>

<mark style="color:blue;">**Dense Feed-forward Layers**</mark><mark style="color:blue;">:</mark> These layers are standard components in neural networks where each input is connected to each output by a learned weight. In the context of transformer architectures, dense feed-forward layers are present within each transformer block and process the input sequentially, applying the same set of weights across the entire sequence.

<mark style="color:blue;">**Router**</mark><mark style="color:blue;">:</mark> In the context of a Mixture of Experts (MoE) layer, a router is a mechanism that determines how the input is distributed among the various experts. It takes each token or piece of input data, computes a probability distribution over the experts, and routes the input to the selected experts based on this distribution. The routing process is crucial for managing the computational load and ensuring that the most relevant experts handle each piece of input.

<mark style="color:blue;">**Decoder-only Architecture**</mark><mark style="color:blue;">:</mark> This architecture refers to transformer models that only use the decoder component, omitting the encoder. In autoregressive large language models (LLMs), the decoder-only architecture is prevalent, where each transformer block within the decoder contains layers for masked self-attention and feed-forward processing. The architecture is designed to generate output one token at a time, using previously generated tokens as context.

<mark style="color:blue;">**Sparse Activation**</mark><mark style="color:blue;">:</mark> This concept refers to the activation of only a small subset of the available experts in an MoE layer for any given input. Despite the MoE layer having a large number of experts, sparse activation ensures that only the most relevant experts (determined by the router) are utilized during the forward pass, thus optimizing computational efficiency.

<mark style="color:blue;">**Routing Mechanism**</mark><mark style="color:blue;">:</mark> The routing mechanism in MoE layers, typically a softmax gating function, is responsible for allocating input tokens to different experts. It involves passing the input through a linear layer to produce logits, applying a softmax function to generate a probability distribution, and then using this distribution to select and weigh the contribution of each expert in processing the input.

### <mark style="color:purple;">Summary of Wolfe Analysis</mark>

The incorporation of Sparse Mixture of Experts layers within LLMs enables a substantial increase in model capacity while managing computational expenses.

This methodology allows for the development of more powerful and nuanced language models, potentially unlocking new capabilities in natural language processing and understanding.

### <mark style="color:purple;">Back to Mixtral 8x7B–Instruct</mark>

<mark style="color:green;">**Fine-tuned Model**</mark><mark style="color:green;">:</mark> A variant of Mixtral, known as Mixtral 8x7B–Instruct, is fine-tuned to follow instructions better, demonstrating enhanced performance in human evaluation benchmarks compared to other leading models.

<mark style="color:green;">**Reduced Biases and Balanced Sentiment**</mark><mark style="color:green;">:</mark> The instruction-following version of Mixtral also shows improvements in reducing biases and achieving a more balanced sentiment in its outputs.

### <mark style="color:purple;">Mixtral's Architecture</mark>

<mark style="color:green;">**Transformer Basis**</mark><mark style="color:green;">:</mark> At its core, Mixtral is based on the transformer architecture, known for its efficiency and effectiveness in handling sequence data. Transformers consist of layers with two main sub-blocks: a self-attention mechanism and a feedforward neural network.

<mark style="color:green;">**Modifications**</mark><mark style="color:green;">:</mark> Unlike standard transformers, Mixtral replaces the feedforward blocks with Mixture-of-Expert (MoE) layers. This allows the model to dynamically select which parts of the network to use for processing each token, enhancing its adaptability and efficiency.

<mark style="color:green;">**Context Length**</mark><mark style="color:green;">:</mark> Mixtral is designed to handle a fully dense context length of up to 32,000 tokens, providing it with a substantial lookback capability, beneficial for understanding and generating long sequences of text.

### <mark style="color:purple;">Sparse Mixture of Experts (SMoE)</mark>

<mark style="color:green;">**Expert Networks**</mark><mark style="color:green;">:</mark> In an MoE layer, there are 'n' expert networks ($$E0​,E1​,...,En−1​$$). Each <mark style="color:yellow;">expert is a specialised feedforward network</mark> capable of handling specific types of information or patterns within the data.

<mark style="color:green;">**Gating Network**</mark><mark style="color:green;">:</mark> The gating network <mark style="color:yellow;">decides which experts to engage for processing each token</mark>. It outputs a gating vector $$G(x)$$ which is an n-dimensional vector indicating the relevance of each expert for the current input token $$x$$

<mark style="color:green;">**Output Computation**</mark><mark style="color:green;">:</mark> The output of the MoE layer for an input $$x$$ is a weighted sum of the outputs from the expert networks. Mathematically, it's represented as:

$$
y = \sum\_{i=0}^{n-1} G(x)\_i \cdot E\_i(x)
$$

where $$G(x)i​$$ is the i-th element of the gating vector, and $$Ei​(x)$$ is the output from the i-th expert network.

<mark style="color:green;">**Top-K Gating**</mark><mark style="color:green;">:</mark> The gating mechanism selects the top $$K$$ experts based on the gating vector's values. This selection is made using a <mark style="color:blue;">softmax function</mark> applied to the top-K logits of a linear layer. The mathematical expression for this gating function is:

$$
G(x) = \text{Softmax}(\text{TopK}(x \cdot W\_g))
$$

where $$Wg​$$ is the weight matrix for the gating network.

<mark style="color:green;">**Computational Efficiency**</mark>

By using only the top $$K$$ experts (with  being much smaller than $$n$$), the model reduces the computational load, making it efficient while still leveraging a large parameter space.

#### <mark style="color:green;">Execution and Parallelism</mark>

<mark style="color:blue;">**Efficiency on GPUs**</mark><mark style="color:blue;">:</mark> The MoE layers can be efficiently executed on GPUs, using specialized kernels like Megablocks for sparse matrix operations, enhancing execution speed.

<mark style="color:blue;">**Expert Parallelism**</mark><mark style="color:blue;">:</mark> To scale and distribute the workload, Mixtral employs <mark style="color:blue;">Expert Parallelism</mark>, where *<mark style="color:yellow;">**each expert is processed on a different GPU**</mark>*, allowing parallel processing and reducing computation time.

<mark style="color:blue;">**Load Balancing**</mark><mark style="color:blue;">:</mark> Ensuring an even distribution of workload across GPUs is crucial to prevent bottlenecks and maximize resource utilisation.

In summary, Mixtral's architecture, with its integration of the SMoE approach, represents a significant innovation in transformer-based models, offering a dynamic, efficient, and scalable solution for processing large-scale language data.

### <mark style="color:purple;">Conclusion</mark>

In this study, we unveiled Mixtral 8x7B, a pioneering mixture-of-experts network that achieves state-of-the-art performance among open-source models.&#x20;

Notably, the Mixtral 8x7B Instruct variant surpasses other leading models like Claude-2.1, Gemini Pro, and GPT-3.5 Turbo in human evaluation benchmarks.&#x20;

Remarkably, *<mark style="color:yellow;">**Mixtral achieves this superior performance while using only 13 billion active parameters per token, in stark contrast to its predecessor, Llama 2 70B, which uses 70 billion.**</mark>*&#x20;
