Phi-3 is a family of language models that greatly improves the performance of small models by raising the quality of the training data while keeping almost the same architecture as Llama 2. Microsoft introduced it in 2024 in "Phi-3 Technical Report: A Highly Capable Language Model Locally on Your Phone". The flagship model is the 3.8-billion-parameter phi-3-mini, alongside the 7-billion-parameter phi-3-small and the 14-billion-parameter phi-3-medium.
Large language models have grown according to "scaling laws": the larger the model and the data, the better the performance. However, these laws assume that the quality of the training data is fixed. Since phi-1, the Phi family has consistently explored ways to break this assumption.
Filter web data with language models: keep only data of high educational value.
Have language models write synthetic data: create data that teaches reasoning and various skills.
According to the report, the previous model, phi-2 (2.7B), matched models 25 times larger with this approach. phi-3-mini, trained on 3.3 trillion tokens of a larger and more advanced version of phi-2's data, reaches 68.8% on MMLU and 8.38 on the chat benchmark MT-bench, close to Mixtral 8x7B and GPT-3.5.
At the same time, phi-3-mini quantized to 4 bits takes only about 1.8 GB and can generate more than 12 tokens per second offline on an iPhone 14 (A16 Bionic). Achieving performance close to large models at a size that runs on a local device is the goal of Phi-3.
Architecture: changes from Llama 2
phi-3-mini is a decoder-only Transformer built by stacking blocks with the same structure as Llama 2. It also uses the same tokenizer as Llama 2 (vocabulary of 32,064). The report explains that this lets "all the packages developed for Llama 2" be used as they are. In the figure at the top of the article, the left side shows the overall flow and the top right shows the inside of one decoder layer.
Each block consists of three components inherited from LLaMA (confirmed in the reference implementation, Phi-3 in Hugging Face transformers).
RMSNorm on the input side: normalize before attention and before the feed-forward, and add the input unchanged through the residual path.
SwiGLU feed-forward: a gate passed through SiLU scales the other branch's output element by element. The intermediate size is 8192.
Positions via RoPE: rotate the attention queries and keys according to their positions.
The three model sizes are as follows (Chapter 2 of the report).
Model
Parameters
Layers
Hidden size d
Heads
Tokenizer (vocabulary)
Context length
Training tokens
phi-3-mini
3.8B
32
3072
32
Same as Llama 2 (32,064)
4K (a 128K version also exists)
3.3T
phi-3-small
7B
32
4096
32
tiktoken (100,352)
8192
4.8T
phi-3-medium
14B
40
5120
40
Same as Llama 2 (32,064)
4K
4.8T
Only phi-3-small modifies the architecture in several ways.
GEGLU activation: SwiGLU with the gate replaced by GELU.
Grouped-query attention (GQA): four query heads share one key and value, reducing what must be stored during inference (the KV cache).
Block-sparse attention: the context is split into blocks, and each head attends only to a different combination of blocks. While ensuring every token is attended to by some head, this greatly reduces the KV cache. These layers alternate with dense attention layers that attend to everything (a form of sparse attention).
Hyperparameters set with muP: through a careful parameterization, the learning rate and other settings tuned on a small proxy model transfer directly to the 7B model.
phi-3-mini-128K, which extends phi-3-mini's context to 128K, uses LongRoPE, which extends the context by adjusting the rotation speeds of RoPE.
Training: the data-optimal approach
The key to Phi-3 lies in the training data, which is split into pretraining and post-training. The bottom right of the figure at the top of the article shows this pipeline.
Pretraining runs two stages with different content in sequence (Chapter 2 of the report).
Stage 1: mainly web data, teaching general knowledge and language understanding. The data is publicly available web data heavily filtered by "educational level".
Stage 2: an even more heavily filtered subset of the stage-1 data mixed with synthetic data generated by language models, teaching logical reasoning and various niche skills.
The report calls its filtering philosophy "data optimal". Chinchilla sought the compute-optimal model size and token count, and LLaMA trained small models for longer. Phi-3 asks what data is most useful for a model of a given size.
For example, the result of a Premier League match on a particular day might be good training data for a huge model. But for a small model, the report argues, it is better to remove such detailed knowledge and devote the capacity to "reasoning ability" rather than to memorizing it. So the web data is filtered to keep more pages that contain "the right level of knowledge" and are likely to improve reasoning ability.
Figure 3 of the report plots the log of the MMLU error rate against the log of model size, comparing the series phi-1.5, phi-2, phi-3-mini, and phi-3-small with four sizes of Llama 2 trained on the same data. The Phi series lies at lower error rates than Llama 2 models of the same size.
Post-training turns the model into a chat model in two stages.
SFT (supervised fine-tuning): fine-tune on high-quality data covering a wide range of areas, including math, code, reasoning, conversation, model identity, and safety. Initially only English data is used.
DPO (direct preference optimization): give undesirable responses as "rejected responses" to steer the model away from them. The data covers chat format, reasoning, and responsible AI.
Post-training improves math, code, reasoning, robustness, and safety, turning the model into an AI assistant users can interact with safely. phi-3-mini is released as a chat model that has completed this post-training.
Why a small model can approach large ones
The central idea of Phi-3 is to decide, through data, what the model's capacity is used for.
A language model's performance has two broad components.
Factual knowledge: names, events, figures, and so on, determined by how much is memorized. Models with larger capacity have the advantage.
Reasoning ability: the ability to derive answers step by step from given information. It is learned from "worked examples of thinking" in the data.
A small model cannot memorize much factual knowledge. But if it is trained on high-quality data rich in examples of reasoning, its reasoning ability can approach that of a large model. Phi-3 reduces fine-grained facts in the web data and increases textbook-like, logically coherent text and synthetic data, concentrating its limited capacity on reasoning ability.
As a study analogy: with limited time, mastering how to solve problems from a good workbook prepares you for more exam questions than trying to memorize an encyclopedia.
The trade-off is that Phi-3 is at a disadvantage on tasks that test factual knowledge. Indeed, on TriviaQA (trivia question answering) in the next section, phi-3-mini scores lower than other models of similar size.
The report notes that on some benchmarks the gain from phi-3-small (7B) to phi-3-medium (14B) is smaller than the gain from mini to small. The current data mixture may not yet be "data optimal" for a 14B model, so making the model bigger does not necessarily improve performance proportionally.
Experimental results
The report evaluates all models with the same evaluation pipeline (few-shot, temperature 0). As a result, the numbers may differ from those reported in other papers.
Main benchmarks (excerpt from the tables in Chapter 3 of the report. MT-bench is out of 10; the others are %)
phi-3-mini beats Mistral 7B and Gemma 7B, both more than twice its size, by about 10 points on the 19-benchmark average, and also beats the mixture-of-experts Mixtral 8x7B on average. The gains are especially large on math word problems (GSM-8K) and code (HumanEval, MBPP), matching the aim of devoting capacity to reasoning.
On the other hand, on TriviaQA, which tests factual knowledge, phi-3-mini (64.0) falls below Mistral 7B (75.2) and Gemma 7B (72.3). The report attributes this to the small model's limited ability to memorize factual knowledge.
The Phi-3.5 family
The revised version of the report (v4) adds the Phi-3.5 family, strengthened for multilingual use and long contexts.
phi-3.5-mini: phi-3-mini further trained with multilingual and long-document data, with its context extended to 128K using LongRoPE.
phi-3.5-MoE: a mixture-of-experts model that splits the feed-forward into 16 experts (each a GLU network) and uses only the top 2 per token. It has 42 billion parameters in total, 6.6 billion active per token, and scores 78.9% on MMLU (Table 3 of the report).
phi-3.5-Vision: a 4.2-billion-parameter multimodal model that encodes images with the ViT-L/14 of CLIP and feeds them into phi-3.5-mini.
Caveats in practice
Keep the following points in mind when using Phi-3 (Chapter 6 of the report).
Limited factual knowledge: Because of its small capacity, it is weak on questions about detailed facts. The report recommends augmenting it with a search engine (Figure 6 shows an example where, given search results, it answers correctly and specifically).
Mainly English: phi-3-mini is trained mainly on English data. For other languages, consider phi-3-small or the phi-3.5 family, which add multilingual data.
Scores depend on the evaluation pipeline: The report measures all models under the same conditions with Microsoft's internal evaluation pipeline. Its numbers may not be directly comparable with those in other papers.
Long-context performance: In the phi-3.5 family, performance on a long-context understanding task (RULER) dropped sharply at 128K. The report attributes this to a lack of high-quality long-context data during training.
Even with safety post-training and red-teaming, problems such as hallucinations (plausible but wrong answers), reproduction of biases, and generation of inappropriate content remain. The report also calls for evaluation and safety review for each use case.
Comparison with other models
Comparing Phi-3 with small language models from the same period along the same axes gives the following (MMLU values are from the tables in Chapter 3 of the Phi-3 report, measured with the same evaluation pipeline).
Model
Parameters
Architectural features
Training data approach
MMLU
phi-3-mini
3.8B
Same blocks as Llama 2
Heavily filtered web + synthetic data (data optimal)
Parameter counts and architectural features of Mistral 7B and Mixtral are from their respective papers, and those of Gemma from the Gemma report.
Rough guidelines for choosing a model:
To run on a local device such as a smartphone or laptop: phi-3-mini fits in about 1.8 GB at 4 bits and outperforms models of the same size on reasoning, math, and code.
For use cases that ask about a broad range of facts: The amount of knowledge depends on model size, so use a larger model or combine with search.
To understand how data quality affects performance: Comparing it with phi-1, which tested the same idea on code generation, makes the Phi family's philosophy easier to grasp.
When long contexts or multilingual support are needed: phi-3-mini-128K, extended to 128K with LongRoPE, and the phi-3.5 family, strengthened for multilingual use, are candidates.
PyTorch example
▶Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
A small implementation of the phi-3-mini decoder layer, following Chapter 2 of the technical report and the reference implementation (Phi-3 in Hugging Face transformers)
- Same structure as Llama 2: input-side RMSNorm, RoPE on Q and K, SwiGLU feed-forward, no biases
- As in the reference implementation, Q, K, V are computed by one linear layer (qkv_proj), and gate and up by one linear layer (gate_up_proj)
- phi-3-mini: d = 3072, 32 heads, intermediate 8192, 32 layers, vocabulary 32,064
No dropout is used (set to 0), so model.train() and model.eval() compute the same thing
"""
class RMSNorm(nn.Module):
def __init__(self, dim, eps=1e-5):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim))
def forward(self, x):
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * self.weight
def rope_angles(head_dim, max_len, theta=10000.0):
freqs = 1.0 / (theta ** (torch.arange(0, head_dim, 2).float() / head_dim))
angles = torch.outer(torch.arange(max_len).float(), freqs)
angles = torch.cat((angles, angles), dim=-1) # [max_len, head_dim]
return torch.cos(angles), torch.sin(angles)
def apply_rope(x, cos, sin):
# Rotate the first and second halves as pairs (rotate_half style)
x1, x2 = x.chunk(2, dim=-1)
return x * cos + torch.cat((-x2, x1), dim=-1) * sin
class Phi3DecoderLayer(nn.Module):
def __init__(self, dim=3072, n_heads=32, hidden=8192):
super().__init__()
self.n_heads, self.head_dim = n_heads, dim // n_heads
self.input_norm = RMSNorm(dim)
self.qkv_proj = nn.Linear(dim, 3 * dim, bias=False)
self.o_proj = nn.Linear(dim, dim, bias=False)
self.post_attn_norm = RMSNorm(dim)
self.gate_up_proj = nn.Linear(dim, 2 * hidden, bias=False)
self.down_proj = nn.Linear(hidden, dim, bias=False)
def attention(self, h, cos, sin):
b, n, _ = h.shape
q, k, v = self.qkv_proj(h).view(b, n, 3, self.n_heads, self.head_dim).permute(2, 0, 3, 1, 4)
q, k = apply_rope(q, cos[:n], sin[:n]), apply_rope(k, cos[:n], sin[:n])
out = F.scaled_dot_product_attention(q, k, v, is_causal=True) # causal mask
return self.o_proj(out.transpose(1, 2).reshape(b, n, -1))
def ffn(self, h):
gate, up = self.gate_up_proj(h).chunk(2, dim=-1)
return self.down_proj(up * F.silu(gate)) # SwiGLU
def forward(self, x, cos, sin):
x = x + self.attention(self.input_norm(x), cos, sin)
return x + self.ffn(self.post_attn_norm(x))
class TinyPhi3(nn.Module):
def __init__(self, vocab=32064, dim=3072, n_layers=32, n_heads=32, hidden=8192, max_len=4096):
super().__init__()
self.embed = nn.Embedding(vocab, dim)
self.layers = nn.ModuleList(Phi3DecoderLayer(dim, n_heads, hidden) for _ in range(n_layers))
self.norm = RMSNorm(dim)
self.lm_head = nn.Linear(dim, vocab, bias=False) # weights not tied to the embedding
cos, sin = rope_angles(dim // n_heads, max_len)
self.register_buffer("cos", cos, persistent=False)
self.register_buffer("sin", sin, persistent=False)
def forward(self, tokens):
x = self.embed(tokens)
for layer in self.layers:
x = layer(x, self.cos, self.sin)
return self.lm_head(self.norm(x))
# Sanity check (small configuration)
model = TinyPhi3(vocab=1000, dim=128, n_layers=2, n_heads=4, hidden=256, max_len=64).eval()
with torch.no_grad():
print(model(torch.randint(0, 1000, (2, 16))).shape) # torch.Size([2, 16, 1000])
FAQ
Q. How does Phi-3 differ from Llama 2?
A.
The architecture and tokenizer of phi-3-mini are almost the same as Llama 2. The difference is the training data: web data heavily filtered by educational level and synthetic data generated by language models. As a result, with 3.8 billion parameters, it beats 7B-class models more than twice its size on many benchmarks.
Q. Does phi-3-mini really run on a smartphone?
A.
In the report, phi-3-mini quantized to 4 bits (about 1.8 GB) runs offline on an iPhone 14 (A16 Bionic) and generates more than 12 tokens per second. Note, however, that quantization can slightly reduce accuracy, so verify it for your use case.
Q. What is Phi-3 bad at?
A.
Tasks that test factual knowledge. Because the model is small and cannot memorize many detailed facts, it scores lower than other models of similar size on benchmarks such as TriviaQA. The report recommends augmenting it with a search engine.