AI Logic

Architectures

Mistral 7B

Updated:

Architecture of Mistral 7B. Left: the overall flow (a token sequence with vocabulary 32,000 and context 8192, token embeddings, 32 decoder layers, a final RMSNorm, and next-token prediction), plus the attention range of a sliding window that sees only the preceding W tokens. Right: inside a decoder layer (self-attention with GQA and a sliding window and a SwiGLU feed-forward, each with RMSNorm on the input side), and how the range of input covered by the last token widens as layers are stacked

Background and Overview

Mistral 7B is a 7-billion-parameter language model that adds grouped-query attention (GQA) and sliding window attention (SWA) to a decoder of the same form as LLaMA, making inference faster and lighter. Jiang et al. at Mistral AI presented it in 2023 in the paper "Mistral 7B" and released it under the Apache 2.0 license.

Large language models improve as they grow, but so do the computational cost and latency of using them. The Mistral 7B paper aims to show that with good design, even a small model can combine high performance with fast inference.

As a result, Mistral 7B achieved the following (Section 3 of the paper).

  • It outperforms the best openly available 13B model at the time (Llama 2 13B) on every benchmark evaluated.
  • It outperforms a 34B model (LLaMA 34B) on mathematics, code, and reasoning.
  • Mistral 7B Instruct, tuned to follow instructions, outperforms Llama 2 13B Chat in both human and automated evaluations.

In its conclusion, the paper argues that model performance should be considered not only along the two axes of "training cost" and "performance" but along three axes that add "inference cost". This takes further the direction LLaMA set of "training small models for longer".

Architecture: Changes from LLaMA

Inside each layer, Mistral 7B, like LLaMA, uses RMSNorm on the input side, a SwiGLU feed-forward, and RoPE (not stated in the paper; confirmed in the official reference implementation). In the figure at the top of the article, the left side shows the overall flow and the range attention can see, and the right side shows the inside of a single decoder layer and how the visible range widens as layers are stacked.

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

ItemValue
Vector length dd4096
Number of layers32
Head dimension128
Feed-forward hidden dimension14336
Number of query heads32
Number of key-value heads8
Window size WW4096
Context length8192
Vocabulary32,000

The changes from LLaMA are the following three, all around attention (Sections 1 and 2 of the paper).

  1. Grouped-query attention (GQA): The 32 query heads are split into 8 groups, and each group of 4 shares one key head and one value head (grouped-query attention). The keys and values stored during generation shrink to a quarter, making inference faster and using less memory. This allows generation with larger batches.
  2. Sliding window attention (SWA): Each token looks only at the preceding WW tokens, including itself, in the previous layer (Figure 1 of the paper; the same idea as Longformer and sparse attention).
  3. Rolling buffer cache: Since only the preceding WW tokens are looked at, the storage for keys and values (the KV cache) is fixed at WW entries, and the oldest entries are overwritten.

The sliding window in step 2 can be expressed with masking. When the token at position ii attends to the token at position jj, the following MijM_{ij} is added to the score before the softmax.

Mij={0(iβˆ’W<j≀i)βˆ’βˆž(otherwise)M_{ij} = \begin{cases} 0 & (i - W < j \le i) \\ -\infty & (\text{otherwise}) \end{cases}

Ordinary causal attention only requires j≀ij \le i, but SWA additionally hides everything more than WW tokens back. Since each token computes at most WW scores, the attention cost becomes O(nW)O(nW) rather than O(n2)O(n^2) in the sequence length nn.

In the rolling buffer of step 3, the keys and values at position ii are written to slot iβ€Šmodβ€ŠWi \bmod W of the cache. Once the position exceeds WW, old values are overwritten and the cache grows no further. According to the paper, on a sequence of 32,000 tokens this cut cache memory by a factor of 8 without changing model quality.

A long prompt can be loaded into the KV cache all at once before generation starts (prefill). When the prompt is very long, splitting it into chunks of WW tokens and feeding them in order keeps memory down. Each chunk applies causal attention within itself and sliding window attention to the cache (Figure 3 of the paper).

Why Information Outside the Window Is Still Usable

With a sliding window, a single layer sees only the preceding WW tokens. Even so, stacking layers lets information from outside the window arrive indirectly.

The output of layer kk at position ii looks at positions iβˆ’W+1i-W+1 through ii of layer kβˆ’1k-1. Each of those positions in layer kβˆ’1k-1 in turn looks at the WW positions before it. So after passing through kk layers, information from roughly kΓ—Wk \times W tokens back in the original input can arrive. The bottom right of the figure at the top shows, for W=3W = 3, how the reachable range widens to the left with each additional layer.

In Mistral 7B, with W=4096W = 4096 and 32 layers, the last layer can in theory receive information from about 131,000 tokens back (Section 2 of the paper).

Think of a game of telephone: even if each person can directly hear only the 4096 people nearby, after 32 rounds of passing the message along, words from people much farther away can get through. However, the information is summarized at each hand-off, so the more distant the information, the more likely fine details are lost.

"131,000 tokens in theory" is the range information can reach; it does not mean the model handles a context that long correctly. Mistral 7B's context length is 8192 tokens (Table 1), and the paper does not evaluate performance with a 131,000-token context. When handling long documents, verify on your actual task.

Speed: At a sequence length of 16,000 tokens with W=4096W = 4096, modifications for sliding windows in FlashAttention and xFormers made it 2Γ— faster than vanilla attention (Section 2 of the paper).

Experimental Results

The paper re-evaluated all compared models with its own evaluation pipeline (Table 2 of the paper, %).

ModelMMLUHellaSwagWinoGrandeARC-cTriviaQAHumanEvalMBPPMATHGSM8K
Llama 2 7B44.477.169.543.263.811.626.13.916.0
Llama 2 13B55.680.772.948.869.618.935.46.034.3
Code-Llama 7B36.962.962.334.534.931.152.55.220.8
Mistral 7B60.181.375.355.569.930.547.513.152.2

(MMLU is 5-shot; HellaSwag, WinoGrande, and ARC are zero-shot; TriviaQA is 5-shot; HumanEval is zero-shot; MBPP is 3-shot; MATH is 4-shot with majority voting over 4; GSM8K is 8-shot with majority voting over 8.)

Mistral 7B outperforms Llama 2 13B, nearly twice its size, and on code it approaches Code-Llama 7B, which is specifically tuned for code.

Efficiency in terms of equivalent size: From the relationship between size and performance in Llama 2, the paper estimated what size of Llama 2 Mistral 7B is equivalent to. On reasoning, comprehension, and MMLU, it matched a Llama 2 more than 3Γ— its size, but on knowledge tasks only 1.9Γ—. The paper attributes this to the limited amount of knowledge a model with fewer parameters can store.

Instruction-following model (Table 3 of the paper): Mistral 7B Instruct, tuned only on instruction data publicly available on Hugging Face, scored 6.84 on MT-Bench, outperforming all 7B models (Llama 2 7B Chat scored 6.27) and on par with 13B chat models (Llama 2 13B Chat scored 6.65). In a human evaluation where people chose the better of two responses (llmboxing.com), Mistral 7B's responses were preferred 5,020 times versus 4,143 times for Llama 2 13B.

System prompt for safety (Section 5 of the paper): With the recommended system prompt, the model declined all 175 harmful questions. When Mistral 7B Instruct itself was used to classify whether user inputs or generated text are harmful (self-reflection), it achieved 99.4% precision and 95.6% recall.

Practical Considerations

Keep the following points in mind when using Mistral 7B.

  • The training data is not disclosed: The paper does not describe the content or token count of the pretraining data. Unlike LLaMA and Llama 2, you cannot check what data it was trained on, so you need to check for data bias and benchmark contamination yourself.
  • Knowledge-heavy tasks hit a size limit: The paper itself notes that gains are smaller on knowledge tasks. For uses that need many facts, combine it with methods such as providing documents through retrieval.
  • Information beyond the window tends to be weaker: Although it can reach the model through stacked layers, it is not seen directly, so fine details at distant positions are easily lost.
  • The base model has no safety tuning: Mistral 7B Instruct is a demonstration of simple fine-tuning, and the paper treats safety mechanisms (moderation) as something optionally added with the recommended system prompt. When deploying in a public service, safety measures suited to the use case are needed.

Sliding windows and the rolling buffer cache have no effect unless the inference library supports them. Implementations without support may treat the model as ordinary causal attention, so results can change for inputs longer than WW and memory may not decrease. Check the support status of libraries such as vLLM, which uses PagedAttention, before use.

Comparison with Other Models

Compared with LLaMA-family models from the same period:

ModelSizeContext lengthAttentionKV cache sizeLicense
LLaMA 7B7B2048Multi-head (32 heads)Proportional to context lengthFor researchers
Llama 2 7B, 13B7B, 13B4096Multi-headProportional to context lengthResearch and commercial (custom license)
Mistral 7B7B8192GQA (8 K/V heads) + sliding windowCapped at WW entriesApache 2.0
Mixtral 8x7B47B (13B used per token)32,768GQAProportional to context lengthApache 2.0

The Mixtral row is based on the Mixtral paper (Section 2.1 and Table 1). Mixtral is a successor to Mistral 7B that does not use a sliding window and replaces the feed-forward network with a mixture of experts.

Rough guidelines for choosing:

  • To run the best-performing model possible on a single GPU: Mistral 7B outperforms Llama 2 13B at 7B size, so better results can be expected on the same GPU.
  • To minimize license restrictions: Mistral 7B is released under Apache 2.0, which is easy to use even commercially.
  • If you need even higher performance and have memory to spare: Mixtral matches or exceeds Llama 2 70B while keeping the compute per token low.
  • If you want to know the training data and tuning methods in detail before use: Llama 2, whose training procedure is described in detail in its paper, is a better fit.

PyTorch example

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

"""
A small example of the attention-related ideas in Mistral 7B, following Section 2 of the paper
1. Causal sliding window mask: position i looks only at j with i-W < j <= i
2. GQA: repeat the K/V heads to match the number of query heads (32 / 8 = 4 times)
3. Rolling buffer cache: write the K/V of position i to slot i mod W of the cache
Finally, an example of using the pretrained model with Hugging Face transformers
"""

# --- 1. Sliding window mask ---
def sliding_window_mask(n, window):
  i = torch.arange(n).unsqueeze(1)
  j = torch.arange(n).unsqueeze(0)
  return (j <= i) & (j > i - window)          # attend only where True

print(sliding_window_mask(6, 3).int())         # same as the bottom left of the top figure (W = 3)


# --- 2. GQA with sliding window attention ---
def sliding_window_gqa(q, k, v, window):
  # q: [batch, 32, n, 128], k and v: [batch, 8, n, 128]
  rep = q.shape[1] // k.shape[1]               # number of query heads sharing one K/V (4)
  k = k.repeat_interleave(rep, dim=1)
  v = v.repeat_interleave(rep, dim=1)
  mask = sliding_window_mask(q.shape[2], window).to(q.device)
  return F.scaled_dot_product_attention(q, k, v, attn_mask=mask)

q = torch.randn(1, 32, 10, 128)
k, v = torch.randn(1, 8, 10, 128), torch.randn(1, 8, 10, 128)
print(sliding_window_gqa(q, k, v, window=4).shape)   # torch.Size([1, 32, 10, 128])


# --- 3. Rolling buffer cache ---
class RollingKVCache:
  def __init__(self, window, n_kv_heads=8, head_dim=128):
    self.window = window
    self.k = torch.zeros(window, n_kv_heads, head_dim)
    self.v = torch.zeros(window, n_kv_heads, head_dim)
    self.length = 0                            # number of tokens inserted so far

  def update(self, k_t, v_t):
    slot = self.length % self.window           # position i goes to slot i mod W (overwriting old values)
    self.k[slot], self.v[slot] = k_t, v_t
    self.length += 1

  def get(self):
    # Return in oldest-first order. The size is at most W and grows no further
    n = min(self.length, self.window)
    order = [(self.length - n + t) % self.window for t in range(n)]
    return self.k[order], self.v[order]

cache = RollingKVCache(window=4)
for t in range(6):
  cache.update(torch.full((8, 128), float(t)), torch.full((8, 128), float(t)))
k_cached, _ = cache.get()
print(k_cached[:, 0, 0])                       # tensor([2., 3., 4., 5.]): only the last 4 remain


# --- 4. Use the pretrained Mistral 7B ---
from transformers import AutoTokenizer, AutoModelForCausalLM

name = "mistralai/Mistral-7B-v0.1"             # the base model from the paper
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name, torch_dtype=torch.float16, device_map="auto")
model.eval()
print(model.config.sliding_window, model.config.num_key_value_heads)   # 4096 8
enc = tokenizer("Sliding window attention is", return_tensors="pt").to(model.device)
with torch.no_grad():
  out = model.generate(**enc, max_new_tokens=40)
print(tokenizer.decode(out[0], skip_special_tokens=True))

FAQ

Q. With a sliding window, can information before the window not be used?
A.

It is not visible directly within a single layer, but it arrives indirectly as layers are stacked. After kk layers, information from roughly kΓ—Wk \times W tokens back is included. In Mistral 7B (32 layers, W=4096W = 4096), it can in theory reach about 131,000 tokens back. However, the more distant the information, the more times it is summarized on the way, so fine details are easily lost.

Q. What is the benefit of the rolling buffer cache?
A.

The KV cache size is capped at WW entries, so memory does not grow even as the generated text gets longer. The mechanism is simple: the keys and values at position ii are written to slot iβ€Šmodβ€ŠWi \bmod W, overwriting old ones. In the paper, cache memory was reduced by a factor of 8 on a 32,000-token sequence.

Q. How does the architecture of Mistral 7B differ from Llama 2 7B?
A.

The components inside each layer (RMSNorm on the input side, SwiGLU, and RoPE) are the same; the difference is attention. Mistral 7B uses GQA with 8 key-value heads and a sliding window that sees only the preceding 4096 tokens. The feed-forward hidden dimension (14336) and the context length (8192) also differ.

References

  1. Jiang, A. Q., Sablayrolles, A., Mensch, A., et al. (2023). Mistral 7B. arXiv:2310.06825.
  2. Ainslie, J., Lee-Thorp, J., de Jong, M., Zemlyanskiy, Y., LebrΓ³n, F., & Sanghai, S. (2023). GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints. EMNLP 2023.
  3. Beltagy, I., Peters, M. E., & Cohan, A. (2020). Longformer: The Long-Document Transformer. arXiv:2004.05150.
  4. Child, R., Gray, S., Radford, A., & Sutskever, I. (2019). Generating Long Sequences with Sparse Transformers. arXiv:1904.10509.
  5. Touvron, H., Martin, L., Stone, K., et al. (2023). Llama 2: Open Foundation and Fine-Tuned Chat Models. arXiv:2307.09288.
  6. Mistral AI. mistral-inference (reference implementation) mistral/model.py.