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).
Item
Value
Vector length d
4096
Number of layers
32
Head dimension
128
Feed-forward hidden dimension
14336
Number of query heads
32
Number of key-value heads
8
Window size W
4096
Context length
8192
Vocabulary
32,000
The changes from LLaMA are the following three, all around attention (Sections 1 and 2 of the paper).
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.
Sliding window attention (SWA): Each token looks only at the preceding W tokens, including itself, in the previous layer (Figure 1 of the paper; the same idea as Longformer and sparse attention).
Rolling buffer cache: Since only the preceding W tokens are looked at, the storage for keys and values (the KV cache) is fixed at W entries, and the oldest entries are overwritten.
The sliding window in step 2 can be expressed with masking. When the token at position i attends to the token at position j, the following Mijβ is added to the score before the softmax.
Mijβ={0βββ(iβW<jβ€i)(otherwise)β
Ordinary causal attention only requires jβ€i, but SWA additionally hides everything more than W tokens back. Since each token computes at most W scores, the attention cost becomes O(nW) rather than O(n2) in the sequence length n.
In the rolling buffer of step 3, the keys and values at position i are written to slot imodW of the cache. Once the position exceeds W, 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 W 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 W tokens. Even so, stacking layers lets information from outside the window arrive indirectly.
The output of layer k at position i looks at positions iβW+1 through i of layer kβ1. Each of those positions in layer kβ1 in turn looks at the W positions before it. So after passing through k layers, information from roughly kΓW tokens back in the original input can arrive. The bottom right of the figure at the top shows, for W=3, how the reachable range widens to the left with each additional layer.
In Mistral 7B, with W=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=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, %).
Model
MMLU
HellaSwag
WinoGrande
ARC-c
TriviaQA
HumanEval
MBPP
MATH
GSM8K
Llama 2 7B
44.4
77.1
69.5
43.2
63.8
11.6
26.1
3.9
16.0
Llama 2 13B
55.6
80.7
72.9
48.8
69.6
18.9
35.4
6.0
34.3
Code-Llama 7B
36.9
62.9
62.3
34.5
34.9
31.1
52.5
5.2
20.8
Mistral 7B
60.1
81.3
75.3
55.5
69.9
30.5
47.5
13.1
52.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 W 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:
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 k layers, information from roughly kΓW tokens back is included. In Mistral 7B (32 layers, W=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 W entries, so memory does not grow even as the generated text gets longer. The mechanism is simple: the keys and values at position i are written to slot imodW, 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.