phi-1 is a small 1.3-billion-parameter language model focused on writing Python functions from their descriptions (docstrings). It was introduced in 2023 by Gunasekar et al. at Microsoft Research in the paper "Textbooks Are All You Need".
At the time, language models were growing according to "scaling laws": the bigger the model and the training data, the better the performance. In code generation, training a 15-billion-parameter model on 1 trillion tokens was typical. The phi-1 paper explores a different direction: improving the quality of the data rather than the scale.
The paper's claims can be summarized in two points.
Ordinary code on the web often depends on other files or merely lists configuration settings, so it is poor material for learning the fundamentals of programming.
Just as people learn efficiently from a good textbook, a language model trained on data that is clear, self-contained, instructive, and balanced across topics can reach high performance with less data and a smaller model.
As a result, phi-1 was trained on fewer than 7 billion tokens of data (about 8 passes, a little over 50 billion tokens in total) for about 4 days on 8 A100 GPUs, and achieved 50.6% on the code generation benchmark HumanEval and 55.5% on MBPP (both pass@1). These scores beat many models with more than 10 times the parameters and more than 100 times the training data.
pass@1 is the fraction of problems for which a single piece of code written by the model passes all the provided tests. HumanEval consists of 164 problems that ask for a Python function, and MBPP is a collection of basic Python programming problems.
Architecture: changes from a GPT-style decoder
The architecture of phi-1 itself is, in the paper's words, "fairly standard". It is a Transformer made of stacked decoder layers with causal (masked) self-attention, as in GPT, and according to Section 2.3 of the paper the architectural choices follow the code generation model CodeGen. 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.
It differs from an ordinary GPT-style decoder in three ways.
Attention and MLP in parallel: An ordinary decoder layer passes the input through attention and then through the MLP (feed-forward). phi-1 feeds the same input into both at once and adds their outputs (the same arrangement as CodeGen, PaLM, and GPT-NeoX).
RoPE applied to only part of the dimensions: Position information is injected not by positional embeddings added to the input but by RoPE, which rotates the attention queries and keys. Only 32 of the 64 dimensions of each head are rotated.
Attention computed with FlashAttention: Multi-head attention is computed with the FlashAttention implementation, which reduces memory reads and writes. The result is unchanged, but computation is faster and uses less memory.
Written as a formula, the parallel form in point 1 makes one decoder layer compute the following (confirmed in the reference implementation, Phi in Hugging Face transformers).
h=LN(x),x←x+Attention(h)+MLP(h)
LN is Layer Normalization, and attention and the MLP share a single one. The MLP consists of two fully connected layers with GELU in between. The parallel arrangement lets the matrix multiplications of attention and the MLP proceed at the same time, which speeds up training and inference.
The paper trained two models of different sizes with the same procedure (Section 2.3 of the paper).
Model
Parameters
Layers
Hidden size d
MLP intermediate size
Heads × dimension
phi-1
1.3B
24
2048
8192
32 × 64
phi-1-small
350M
20
1024
4096
16 × 64
The tokenizer is the same as that of CodeGen's codegen-350M-mono, and the context length is 2048 tokens.
The paper states that it deliberately does not use techniques that could improve performance further, such as fill-in-the-middle training or multi-query attention. The architecture is kept standard to show that the difference comes from data quality alone.
Training data: building textbook-quality data
The core of phi-1 is how its training data is built. The paper prepares three datasets (Chapter 2 of the paper).
Data
Size (tokens)
How it is built
Stage
Filtered code
about 6B
A classifier selects Python code with high educational value from The Stack and StackOverflow
Pretraining
Synthetic textbooks
under 1B
GPT-3.5 writes Python textbooks that interleave explanatory text and code
Pretraining
CodeExercises
about 180M
GPT-3.5 writes function docstrings (problems) and their implementations (solutions)
Fine-tuning
The combination of the first two is called CodeTextbook. The model pretrained on it is phi-1-base, and the model obtained by fine-tuning it on CodeExercises is phi-1.
The filtered code is built as follows (Section 2.1 of the paper).
Collect the Python subset of The Stack (deduplicated version) and StackOverflow: more than 35 million files and more than 35 billion tokens in total.
Have GPT-4 judge about 100,000 of them for "educational value for a student learning the basics" and use the judgments as labels.
Convert the code into embedding vectors with a pretrained CodeGen model, and train a random forest classifier that predicts the labels from these features.
Run the classifier over the whole corpus and keep only the files judged to have high value.
GPT-4 is used only on a small amount of data, as a substitute for human labeling. The paper shows that even this has a large effect. A 350M-parameter model trained on unfiltered data plateaued at 12.19% on HumanEval even after about 200 billion tokens, whereas filtered data raised it to 17.68%, and adding the synthetic textbooks raised it to 20.12%.
The difficulty with the synthetic textbooks and exercises is making the content diverse. Simply asking a language model to "write a textbook" tends to produce similar content over and over. So the prompts inject different constraints every time: topics and target audiences for the textbooks, and function names for the exercises (the same idea as the story dataset TinyStories, where the words to use were chosen at random each time).
The paper does not disclose details such as the prompts used to generate the synthetic data, citing them as "proprietary". The same data cannot be reproduced; only the ideas behind the method can be used as a reference.
Training: pretraining and fine-tuning
Pretraining and fine-tuning use the same framework with different settings (Section 2.3 of the paper). In both, all the data is concatenated into one long sequence (with an end-of-text token between files), cut into chunks of 2048 tokens, and the model is trained to predict the next token.
Setting
Pretraining (phi-1-base)
Fine-tuning (phi-1)
Data
CodeTextbook (under 7B)
CodeExercises (about 180M)
Batch size
1024
256
Peak learning rate
1×10−3
1×10−4
Warmup
750 steps
50 steps
Weight Decay
0.1
0.01
Steps
Checkpoint at 24,000 of 36,000 steps (about 8 epochs, a little over 50B tokens)
6,000 (best of the checkpoints saved every 1,000)
Time (8 × A100)
under 4 days
7 hours
The settings shared by both are as follows.
Optimizer: AdamW. The learning rate rises linearly during warmup and then decreases linearly
Regularization: Dropout with probability 0.1 on the attention and residual paths. Weight Decay as in the table above
Computation: fp16 (16-bit floating point), trained on 8 GPUs with DeepSpeed
Why so little data works
The paper explains why phi-1 reaches high performance with little data in terms of the quality of the "signal" in the data.
When the authors inspected ordinary web code by hand, they found problems like these.
Not self-contained: The code depends on other modules or files, so its meaning is unclear from the code alone.
Little meaningful computation: Much of it is boilerplate, such as constant definitions or GUI configuration.
Algorithms are buried: Important logic is hidden inside long, undocumented functions.
Skewed topics: Code for certain uses dominates.
Teaching oneself programming from a pile of such code is hard for a person. The same goes for a language model: the cues for learning the correspondence between "a natural-language description" and "the code that implements it" are buried in noise. The paper argues that textbook-quality data makes this correspondence explicit, so the model can learn efficiently even from a small amount.
As a cooking analogy, reading one basic cookbook thoroughly several times makes you improve faster than reading tens of thousands of recipe scraps scattered across the internet.
Another finding is that fine-tuning on a small exercise dataset improves abilities not present in the exercises (Chapter 3 of the paper). CodeExercises contains only basic libraries, yet after fine-tuning, phi-1 writes code more correctly than phi-1-base even for problems that use external libraries such as Pygame and Tkinter, or that require following the logic of the instructions. The paper suggests that fine-tuning may reorganize the knowledge acquired during pretraining and make it easier to retrieve.
The result that "better data quality makes a small model sufficient" was obtained on a narrow task: writing simple Python functions. The paper itself notes that it is still unknown whether the same effect holds for tasks requiring broad knowledge.
Experimental results
HumanEval and MBPP (pass@1, %. Excerpt from Table 1 of the paper. Values self-reported in each model's paper)
Model
Parameters
Training data (tokens)
HumanEval
MBPP
Codex-12B
12B
100B
28.8
-
CodeGen-Mono-16.1B
16.1B
577B
29.3
35.3
PaLM-Coder
540B
780B
35.9
47.0
StarCoder
15.5B
1T
33.6
52.7
WizardCoder
16B
1T
57.3
51.8
GPT-3.5
175B
undisclosed
47
-
GPT-4
undisclosed
undisclosed
67
-
phi-1
1.3B
7B
50.6
55.5
phi-1 beats every model except GPT-4 on MBPP, and every model except WizardCoder on HumanEval. The effect of each training stage, from Figure 2.1 and the text of the paper, is as follows. For the 1.3B-parameter model, phi-1-base, pretrained only on CodeTextbook, scores 29%, and phi-1, fine-tuned on CodeExercises, scores 50.6%. Before phi-1, the smallest model scoring close to 30% was the 2.7B-parameter Replit-Finetuned (30.5%), trained on about 100 times as many tokens as phi-1.
New problems unlikely to appear in the training data (Chapter 4 of the paper, Table 2)
If problems similar to HumanEval leak into the synthetic data (data contamination), scores overstate true ability. So the paper had a separate team that had not seen the training data create 50 problems in the same format as HumanEval but "unlikely to appear in real code or exercises", and had GPT-4 grade the answers on a scale of 0 to 10.
Model
Parameters
Training data (tokens)
Score on new problems
HumanEval
CodeGen-Mono-16.1B
16.1B
577B
38%
29%
Replit
2.7B
525B
37%
22%
StarCoder
15.5B
1T
51%
34%
phi-1-base
1.3B
7B
37%
29%
phi-1-small
350M
7B
45%
45%
phi-1
1.3B
7B
52%
51%
On the new problems, the ranking of the models is almost the same as on HumanEval, and phi-1 beats StarCoder.
Retraining with similar problems removed (Chapter 5 of the paper, Table 3)
The authors also removed problems similar to HumanEval from CodeExercises (judged by embedding distance and syntax-tree edit distance) and retrained phi-1. Under the strictest setting, 354K of the 879.5K problems (more than 40%) were removed, yet the retrained phi-1 still scored 45.1% on HumanEval, above StarCoder-Prompted (41.5%).
Caveats in practice
Keep the following points in mind when using phi-1 (Chapter 6 and Appendix B of the paper).
Python only: The training data is almost entirely Python. The model is not suited to other programming languages.
Limited knowledge of specialized APIs: Compared with larger models, it struggles with code that uses specific libraries or uncommon packages.
Sensitive to variations in prompt wording: Because the synthetic data has a uniform style, performance drops sharply when the prompt is malformed, for example when it contains grammatical errors.
Narrow as a foundation model: The model is specialized for writing Python functions and is not meant for general conversation or knowledge-based tasks.
A high HumanEval score is a metric easily affected by "contamination", where synthetic data ends up resembling the evaluation problems. The paper checks this by retraining with similar problems removed, but before using the model for your own purpose, verify its performance on problems that do not overlap with the training data.
The paper suggests that generating the synthetic data with GPT-4 instead of GPT-3.5 might improve performance further. phi-1 performs well even though the data generated by GPT-3.5 contained many errors.
Comparison with other models
Comparing phi-1 with code generation models from the same period along the same axes gives the following (figures from Table 1 of the phi-1 paper).
Model
Parameters
Training data (tokens)
HumanEval (pass@1)
MBPP (pass@1)
Codex-12B
12B
100B
28.8%
-
StarCoder
15.5B
1T
33.6%
52.7%
WizardCoder
16B
1T
57.3%
51.8%
phi-1
1.3B
7B
50.6%
55.5%
phi-1 competes with models trained on massive data while being less than one tenth their size and using about one hundredth of the data. On the other hand, it mainly handles simple Python functions, and models trained on massive data are better at handling a wide range of languages and libraries.
Rough guidelines for choosing a model:
To study the effect of data quality on performance, or to do research with small models: phi-1 is cheap to train (about 4 days on 8 × A100) and a good starting point for studying how data construction matters.
To generate code in many languages and libraries: Larger models trained on large amounts of code are better suited.
To get a small model that handles language understanding and reasoning as well as code: The successor Phi-3, which extends the same "textbook-quality data" idea to general text, is better suited.
Other work in the direction of "changing how data is used rather than making the model bigger" includes Chinchilla (training on more tokens) and LLaMA (training small models for longer). phi-1 differs in changing the quality of the data, not its quantity.
PyTorch example
▶Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
A small implementation of the phi-1 decoder layer, following Section 2.3 of the paper and the reference implementation (Phi in Hugging Face transformers)
- The output of a single LayerNorm feeds attention and the MLP in parallel; both outputs are added to the input
- RoPE is applied to only 32 (rotary_dim) of the 64 dimensions of each head
- The MLP is 2048 -> 8192 -> 2048 with GELU activation (tanh approximation)
- Fully connected layers have biases
Because of Dropout (0.1 in the paper), model.train() and model.eval() compute differently
"""
def rope_angles(rotary_dim, max_len, theta=10000.0):
freqs = 1.0 / (theta ** (torch.arange(0, rotary_dim, 2).float() / rotary_dim))
angles = torch.outer(torch.arange(max_len).float(), freqs) # [max_len, rotary_dim/2]
return torch.cos(angles), torch.sin(angles)
def apply_partial_rope(x, cos, sin, rotary_dim):
# x: [batch, heads, n, head_dim]. Rotate only the first rotary_dim dimensions; leave the rest unchanged
x_rot, x_pass = x[..., :rotary_dim], x[..., rotary_dim:]
x1, x2 = x_rot[..., : rotary_dim // 2], x_rot[..., rotary_dim // 2 :]
rotated = torch.cat((x1 * cos - x2 * sin, x1 * sin + x2 * cos), dim=-1)
return torch.cat((rotated, x_pass), dim=-1)
class ParallelDecoderLayer(nn.Module):
def __init__(self, dim=2048, n_heads=32, mlp_dim=8192, rotary_dim=32, dropout=0.1):
super().__init__()
self.n_heads, self.head_dim, self.rotary_dim = n_heads, dim // n_heads, rotary_dim
self.ln = nn.LayerNorm(dim) # shared by attention and the MLP
self.qkv = nn.Linear(dim, 3 * dim)
self.out = nn.Linear(dim, dim)
self.fc1 = nn.Linear(dim, mlp_dim)
self.fc2 = nn.Linear(mlp_dim, dim)
self.attn_dropout = dropout
self.resid_dropout = nn.Dropout(dropout)
def attention(self, h, cos, sin):
b, n, _ = h.shape
q, k, v = self.qkv(h).view(b, n, 3, self.n_heads, self.head_dim).permute(2, 0, 3, 1, 4)
q = apply_partial_rope(q, cos[:n], sin[:n], self.rotary_dim)
k = apply_partial_rope(k, cos[:n], sin[:n], self.rotary_dim)
out = F.scaled_dot_product_attention(
q, k, v, is_causal=True, # causal mask
dropout_p=self.attn_dropout if self.training else 0.0)
return self.out(out.transpose(1, 2).reshape(b, n, -1))
def mlp(self, h):
return self.fc2(F.gelu(self.fc1(h), approximate="tanh"))
def forward(self, x, cos, sin):
h = self.ln(x)
# Instead of applying them in sequence, compute both from the same h and add
return x + self.resid_dropout(self.attention(h, cos, sin)) + self.resid_dropout(self.mlp(h))
class TinyPhi1(nn.Module):
def __init__(self, vocab=51200, dim=2048, n_layers=24, n_heads=32, max_len=2048):
super().__init__()
self.embed = nn.Embedding(vocab, dim) # no positional embedding (injected by RoPE)
self.layers = nn.ModuleList(ParallelDecoderLayer(dim, n_heads, 4 * dim) for _ in range(n_layers))
self.final_ln = nn.LayerNorm(dim)
self.lm_head = nn.Linear(dim, vocab)
cos, sin = rope_angles(32, max_len)
self.register_buffer("cos", cos, persistent=False)
self.register_buffer("sin", sin, persistent=False)
def forward(self, tokens): # tokens: [batch, n]
x = self.embed(tokens)
for layer in self.layers:
x = layer(x, self.cos, self.sin)
return self.lm_head(self.final_ln(x)) # next-token logits
# Sanity check (small configuration)
model = TinyPhi1(vocab=1000, dim=128, n_layers=2, n_heads=2, max_len=64)
tokens = torch.randint(0, 1000, (2, 16))
model.train()
logits = model(tokens)
loss = F.cross_entropy(logits[:, :-1].reshape(-1, 1000), tokens[:, 1:].reshape(-1))
model.eval()
with torch.no_grad():
print(model(tokens).shape) # torch.Size([2, 16, 1000])
FAQ
Q. What is the "textbook-quality data" used by phi-1?
A.
The paper means data that, like a good textbook, is "clear, self-contained, instructive, and balanced across topics". Concretely, it consists of Python code from the web selected for high educational value based on GPT-4 judgments (about 6 billion tokens), plus textbooks (under 1 billion tokens) and exercises (about 180 million tokens) written by GPT-3.5.
Q. Doesn't training on synthetic data let the model memorize the evaluation problems?
A.
The paper checks this. On 50 new problems created by a team that had not seen the training data, phi-1 still beat StarCoder. And after removing more than 40% of the exercises as similar to HumanEval and retraining, phi-1 scored 45.1% on HumanEval, above StarCoder-Prompted (41.5%). This does not completely rule out contamination, however, so it is safest to verify on problems from your own use case.
Q. How do phi-1 and Phi-3 differ?
A.
phi-1 is a 1.3-billion-parameter model specialized for Python code generation. Phi-3 is its successor, which extends the same idea of "training a small model on high-quality data" to general text; it handles a wide range of tasks including language understanding, reasoning, math, and code, and is tuned for chat.