Search

Search papers and lessons

Code Llama: Open Foundation Models for Code

Baptiste Rozière, Jonas Gehring, Fabian Gloeckle et al. · 2023

Code Llama continues training Llama 2 on code, adds gap filling, stretches its context to 100,000 tokens and tunes an instruction version, giving strong open models for programming.

On this page

  • Colour = topic mix
  • Probability
  • Reinforcement learning
  • Discrete math
  • Calculus
  • Linear algebra
  • Neural network basics
  • ReadReady to readNot yet

TL;DR

Code Llama is a family of language models for writing code, built by continuing the training of Llama 2, a general text model. It is trained on about 500 billion more tokens, mostly code, and then specialised further. It can fill a gap in the middle of a file, read contexts of up to 100,000 tokens, and follow instructions. The family comes in 7, 13, 34 and 70 billion parameter sizes, and the paper's abstract reports scores of up to 67 percent on HumanEval and 65 percent on MBPP, which it describes as state of the art among open models at release. The weights are released under a licence that allows research and commercial use.

Builds on: Llama 2: Open Foundation and Fine-Tuned Chat Models, Fill-in-the-Middle, Rotary Position Embedding, Instruction Tuning, Pass@k · Leads to: open code assistants that complete code inside editors

Why it mattered

Code is one of the most common things people ask language models to produce, and a model that works inside an editor needs more than a chat interface. It has to complete code at the cursor, using the lines above and below it, and it has to see a whole repository's worth of context. Most of the strong code models at the time were trained on code alone. The paper's central claim is that an open model, starting from a general base and then specialised, can match or beat the code-only open models of its size.

The release also matters as a recipe. The paper shows, step by step, what each stage buys: code training, Python specialisation, infilling, long-context tuning and instruction tuning. A reader who wants to adapt a general model to a narrow domain can see which steps moved which scores, and what they cost on other tasks.

The problem

A general language model is trained on text, and most of its knowledge of code is incidental. Code has its own structure: a function body depends on a signature that may be hundreds of lines away, and a useful completion often sits in the middle of a file rather than at the end. Three things break in a plain next-token model. It cannot see text that comes after the cursor. Its context window, 4,096 tokens for Llama 2, is shorter than a large file or a project. And it follows instructions poorly unless it is tuned to do so.

The paper's answer is a cascade. Start from a strong general model, so the knowledge of language carries over. Train it on a large code mix. Add an objective that lets it infill. Stretch the context in a short final stage. Then tune an instruction version. Each step is cheap compared to the base training, which is why the paper frames the whole project as specialisation rather than a new model from scratch.

How it works

The pipeline runs in a fixed order, and each stage starts from the weights the stage before produced. The figure in the paper annotates each stage with the tokens seen. Here is the path, with the numbers the paper gives:

flowchart LR
  A["Llama 2 base, 2T tokens of general text"] --> B["code training, 500B tokens, mostly code"]
  B --> C["Python specialisation, 100B tokens"]
  B --> D["infilling objective, mixed in during training"]
  D --> E["long-context fine-tuning, 16k-token sequences"]
  E --> F["instruction tuning, about 5B tokens"]

The flow is not a single line for every model. The paper releases several variants from the same cascade, and the 34B base model was trained without the infilling objective.

  1. Start from Llama 2. The base model has seen 2 trillion tokens of general text, with only about 80 billion of code. The paper's ablation in Section 3.4.1 compares this start with training the same architecture from scratch on the same code mix, and the start from Llama 2 reaches a given loss sooner.
  2. Train on code. The code stage uses 500 billion tokens. Of these, 85 percent are code, 8 percent natural language related to code, such as discussions and snippets in questions and answers, and 7 percent general natural language. The natural language share keeps the model's language skills from fading. The 70B model was trained on 1 trillion tokens instead.
  3. Specialise on Python. Code Llama - Python takes 100 billion more tokens, of which 75 percent are Python. The gain is between 4.3 and 8.3 percentage points on HumanEval pass@1, the paper says.
  4. Add infilling. The 7B, 13B and 70B models are trained with a mixed objective. For a training document, the cut points are chosen at random, the text is rearranged so the suffix comes before the gap, and the model predicts the gap left to right. The paper applies this with probability 0.9, and only to documents that fit within a single context. Half the splits use one ordering of the three pieces and half use the other.
  5. Extend the context. Long-context fine-tuning uses sequences of 16,384 tokens, up from 4,096, and changes the rotary position base from 10,000 to 1,000,000. The change is what lets the model handle positions far beyond those it trained on. The paper reports that perplexity keeps falling up to 100,000 tokens.
  6. Tune for instructions. Code Llama - Instruct is trained on three mixes: Llama 2's proprietary instruction data, a self-generated set of coding problems with unit tests, and a small rehearsal share of code and natural language, 6 and 2 percent, that keeps general coding ability from slipping.

Here is the infilling step traced on a small function. The document is

def add(a, b): return a + b

and the cut points are chosen so that the prefix is def add(a, b): return, the middle is a +, and the suffix is b. Check: concatenating the three pieces gives back the original text, def add(a, b): return a + b. In the prefix-suffix-middle order, the model reads the prefix, then the suffix, then a marker that says the middle comes next. It then writes the middle left to right, so during training the model learns that the answer to "what fills this gap" is the next thing it writes. Check: the middle is predicted one token at a time, as in any language model, so no special decoder is needed.

The self-instruct step also has a concrete recipe. The paper prompts Llama 2 70B for 62,000 interview-style programming questions, removes exact duplicates to get about 52,000, and then for each question generates unit tests and ten Python solutions with the 7B model. The first solution that passes its tests is kept with its question. That gives about 14,000 question, test and solution triples. The unit tests act as the filter, so no human writes the answers.

The math

The two mathematical ideas in the paper are the position encoding that makes long contexts possible and the infilling objective. Both are small.

Step 3 in symbols: rotary position embedding

Llama 2 uses rotary position embeddings, which rotate each query and key vector by an angle that depends on its position. For a vector xn\mathbf{x}_n at position nn in an embedding of dimension dd, the paper writes the transformation as RΘ,ndxn\mathbf{R}^{d}_{\Theta,n}\mathbf{x}_n, where RΘ,nd\mathbf{R}^{d}_{\Theta,n} is block diagonal. Each block is a two-by-two rotation,

(cos⁡nθi−sin⁡nθisin⁡nθicos⁡nθi)\begin{pmatrix}\cos n\theta_i & -\sin n\theta_i\\ \sin n\theta_i & \cos n\theta_i\end{pmatrix}

and the frequency of block ii is θi=θ−2i/d\theta_i = \theta^{-2i/d}. The base θ\theta sets how fast the frequencies fall off across blocks. The paper raises θ\theta from 10,000 to 1,000,000 for the long-context stage.

Here is one number pushed through. Take a toy embedding with d=4d = 4, which has two blocks, i=0i = 0 and i=1i = 1. The first block has θ0=θ0=1\theta_0 = \theta^{0} = 1 whatever the base. The second block has θ1=θ−2/4=θ−1/2\theta_1 = \theta^{-2/4} = \theta^{-1/2}. For the old base, θ=10,000\theta = 10{,}000, this gives θ1=1/100=0.01\theta_1 = 1/100 = 0.01. At position n=1000n = 1000 the second block rotates by 1000×0.01=101000 \times 0.01 = 10 radians. For the new base, θ=1,000,000\theta = 1{,}000{,}000, we get θ1=1/1000=0.001\theta_1 = 1/1000 = 0.001 and a rotation of 1000×0.001=11000 \times 0.001 = 1 radian. Check: the slow block turns ten times less over the same distance, so positions far apart look less like the wrap-around they looked like when the model had only seen short sequences.

Step 4 in symbols: the infilling objective

Write a document as a sequence of characters x1,…,xTx_1, \dots, x_T. Choose two cut points a<ba < b uniformly at random. The prefix is x1…xax_1 \dots x_a, the middle is xa+1…xbx_{a+1} \dots x_b, and the suffix is xb+1…xTx_{b+1} \dots x_T. The reordered training sequence places the prefix and suffix first, then the middle, and the training loss is the usual next-token cross-entropy on that sequence. Restricting attention to the tokens the model must produce, the middle, the objective reads

L=−∑klog⁡pθ ⁣(midk∣pre,suf,mid<k)\mathcal{L} = -\sum_{k} \log p_\theta\!\left(\mathrm{mid}_k \mid \mathrm{pre}, \mathrm{suf}, \mathrm{mid}_{<k}\right)

where midk\mathrm{mid}_k is the kk-th token of the middle and mid<k\mathrm{mid}_{<k} are the middle tokens before it. The paper's infilling loss is the same cross-entropy as the autoregressive objective. Only the order of the text changes. This is why an infilling model can share all its weights with the ordinary model. The paper finds the cost is small: about 0.6 percentage points on average across HumanEval and MBPP pass@1, pass@10 and pass@100 for the 7B model, and 1.1 points for 13B.

Step 6 in symbols: how the scores are estimated

The pass@k numbers use an estimator defined by Pass@k. The paper reports pass@1 with greedy decoding, and pass@10 and pass@100 with nucleus sampling at top-p 0.95 and temperature 0.8. The choice of sampler matters for the larger k, which is why the paper states it.

Results

The main code benchmarks are HumanEval and MBPP, which score whether generated Python passes hidden unit tests. Pass@1 is the fraction of problems solved by one greedy attempt, as reported in Table 2 of the paper.

ModelSizeHumanEval pass@1MBPP pass@1
Llama 270B30.5%45.4%
Code Llama7B33.5%41.4%
Code Llama13B36.0%47.0%
Code Llama34B48.8%55.0%
Code Llama70B53.0%62.4%
Code Llama - Python7B38.4%47.6%
Code Llama - Python70B57.3%65.6%
Code Llama - Instruct70B67.8%62.2%
GPT-3.5 (ChatGPT)not stated48.1%52.2%
GPT-4not stated67.0%not reported

Three points stand out. The 7B Python model beats Llama 2 70B on both benchmarks, which is the paper's clearest case for specialisation. Scaling from 7B to 70B adds points at each step, and the paper notes that it gained 5.6 points on MBPP from 7B to 13B. The abstract's 67 and 65 percent come from two different 70B models: Code Llama - Instruct on HumanEval (67.8) and Code Llama - Python on MBPP (65.6). Instruct 70B edges past GPT-4's 67.0 on HumanEval, but the base 70B model does not, and the paper's claim is about open models, not the closed frontier.

On multilingual HumanEval, the paper's Table 4 averages Pass@1 over C++, Java, PHP, TypeScript, C#, and Bash. The 70B Code Llama model averages 45.3 percent and Llama 2 70B averages 24.4 percent, and the 7B Code Llama model is ahead of Llama 2 70B as well. The paper also notes that the Python and Bash scores correlate strongly across models.

For infilling, the paper's Table 6 gives exact-match scores on single-line infilling in Python. Code Llama 13B reaches 68.3 percent in prefix-suffix-middle order and 74.5 percent in suffix-prefix-middle order, and StarCoder's reported SPM figure is 62 percent. The paper notes a further gain when prompts use the SPM order.

The long-context results are measured by perplexity, a synthetic key-retrieval task and single-line completion. Perplexity keeps falling beyond the 16,384-token training length, out to 100,000 tokens. On a key-retrieval task, the models recall a function's return value placed in a prompt of about 16,000 tokens, which is the length they were trained on, and performance drops for sequences beyond that. On the balanced long-completion benchmark, the long-context models score higher than their pre-fine-tuning versions on every metric.

The paper is open about the costs. Long-context fine-tuning lowers HumanEval pass@1 by about 0.5 points and MBPP pass@1 by about 1.9 points, and the authors judge that cost worth paying for the gains on long inputs. Infilling training costs a small amount on HumanEval and MBPP. The paper also reports that Code Llama - Instruct improves on truthfulness, toxicity and bias benchmarks at moderate cost to code scores, but the safety results are a separate section, and this lesson does not go through them.

Reading guide

The paper is long, and the appendices carry most of the evidence. Read the main text first, then return to the tables you need.

  1. Section 1, Introduction. The four contributions: code training from a foundation model, infilling, long inputs and instruction tuning. Needs Llama 2: Open Foundation and Fine-Tuned Chat Models and Fill-in-the-Middle.
  2. Section 2.1, Model family. Which sizes get infilling and which are Python-specialised. Read this before the training sections, because it sets which model each later table refers to.
  3. Section 2.2 and Table 1, Dataset. The token mix behind the 500 billion tokens, with the sampling shares.
  4. Section 2.3, Infilling. The cut-point procedure and the PSM and SPM formats. Needs Fill-in-the-Middle.
  5. Section 2.4, Long-context fine-tuning. The rotary base change, with the formula for RΘ,nd\mathbf{R}^{d}_{\Theta,n}. Needs Rotary Position Embedding and RoPE. Appendix G has the long-context ablations and the key-retrieval details.
  6. Section 2.5, Instruction fine-tuning. The three data sources and the self-instruct recipe. Needs Instruction Tuning and Self-Instruct: Aligning Language Models with Self-Generated Instructions.
  7. Section 2.6, Training details. Optimiser, learning rates and batch sizes. The hyperparameters are a practical reference for anyone repeating the cascade.
  8. Section 3, Results. Tables 2 to 7 give the main numbers. Read Table 2 with Pass@k in hand.
  9. Section 3.4, Ablations. Training from Llama 2 against training from scratch, and the effect of self-instruct data.
  10. Sections 4 and 5, Responsible AI and related work. The safety evaluation and the comparison with other code models. StarCoder and HumanEval are the main reference points.

Check yourself

QuestionWhy does the paper change the rotary base from 10,000 to 1,000,000 instead of training on longer sequences from the start?Show answer

Training on 16,384-token sequences from the start would be far more expensive, because the cost of attention grows quickly with length. The paper limits long sequences to a short fine-tuning stage. Changing the base slows the low-frequency rotations, which the paper says reduces the bias toward short-distance attention and lets the model handle much larger sequences. In the toy calculation, the slow block rotates 1 radian at position 1,000 with the new base, against 10 radians with the old one.

QuestionCompute the rotation angle at position 500 for the second block of a toy embedding with d equal to 4, first with base 10,000 and then with base 1,000,000.Show answer

For d=4d = 4 and block i=1i = 1, the frequency is θ1=θ−2/4=θ−1/2\theta_1 = \theta^{-2/4} = \theta^{-1/2}. With base 10,000 this is 1/100=0.011/100 = 0.01, so the angle is 500×0.01=5500 \times 0.01 = 5 radians. With base 1,000,000 it is 1/1000=0.0011/1000 = 0.001, so the angle is 500×0.001=0.5500 \times 0.001 = 0.5 radians. Check: the new base gives an angle ten times smaller at the same position, matching the factor of ten between the two frequencies.

QuestionA team wants a code model that can fill a gap in the middle of a file, but it has already trained an ordinary left-to-right model. What does the paper's infilling step change, and what does it keep?Show answer

It changes the order of the training text: each document is cut into prefix, middle and suffix, and rearranged so the suffix comes before the middle, with markers for each piece. It keeps the loss and the architecture. The model is still trained with next-token cross-entropy, so the same weights handle both ordinary and infilling prompts. The paper reports a small cost on HumanEval and MBPP, about 0.6 points for the 7B model.

QuestionWhy does the self-instruct recipe use unit tests rather than human-written answers, and what does it keep from each generated solution?Show answer

Human annotation of coding answers is expensive because it needs professional developers. The unit tests provide an automatic signal of correctness. The paper generates ten Python solutions per question and keeps only the first that passes the tests, with its question and tests. That gives about 14,000 verified triples from about 52,000 de-duplicated questions. The filter trades coverage for correctness, since questions whose solutions never pass are dropped.

Sources

Read the full paper

Baptiste Rozière, Jonas Gehring, Fabian Gloeckle et al., 2023. arXiv:2308.12950