Search

Search papers and lessons

Competition-Level Code Generation with AlphaCode

Yujia Li, David Choi, Junyoung Chung et al. · 2022

AlphaCode writes competitive-programming solutions by sampling up to a million programs per problem, keeping those that pass the example tests, and submitting one from each behaviour cluster, ten at most.

On this page

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

TL;DR

AlphaCode is a system that writes solutions to competitive-programming problems: long natural-language statements that need an algorithm, not just a snippet of code. It samples a very large number of candidate programs for each problem, keeps only the ones that pass the example tests in the statement, groups the rest by how they behave, and submits at most ten, one from each group. Simulated on ten recent Codeforces contests, it ranked in the top 54.3% on average, which means about 54% of human participants did better.

Builds on: Encoder-Decoder Architecture, Multi-Query Attention, Masked Language Modeling, Softmax Temperature, Pass@k · Leads to: later code-generation systems evaluated on competitive programming

Why it mattered

Before this work, transformer models could write short functions that solve simple, well-specified tasks, and the Codex paper showed that clearly. Competitive programming is far harder. The statement is a few paragraphs of story, a precise input and output format, and one or two examples. The solution needs a real algorithm, and the code can run to over a hundred lines with edge cases the statement does not mention. The authors describe it as the first time an AI system performed competitively in programming contests.

The result also shifted how the field measures progress. The authors found that the test cases in existing competitive-programming datasets were so thin that 30% or more of programs marked correct were not. They released CodeContests, a dataset that adds generated tests and cuts that false-positive rate to about 4%, and a strict time split so that no evaluation problem appeared in training data. Those choices are part of why the numbers can be trusted.

The problem

Three things make code generation for competitions hard. The search space is huge and the reward is sparse: a single wrong character can change the behaviour of a program that still runs, and a near-miss gets no partial credit from the judge. The problems are new for every contest, so a model cannot rely on memorised answers, and the hidden tests check edge cases and speed as well as the main result. And, as the paper notes, contests penalise incorrect submissions, so the system is limited to 10 submissions per problem, however many programs it samples.

The paper's metric follows the contest rules. The measure n@k is the percentage of problems solved when the system draws k samples per problem and is allowed to submit n of them. The headline setting is 10@k: ten submissions from k samples. A second metric, pass@k, assumes every sample can be submitted, which is the setting used by the earlier Codex work.

How it works

The pipeline runs from left to right. We follow one toy problem through it. The statement describes a task; the model writes eight candidate programs; three of them pass the example tests in the statement. We trace the eight through the stages that matter.

flowchart LR
  A[Problem statement as text] --> B[Encoder reads the statement]
  B --> C[Decoder writes a program token by token]
  C --> D[Sample a very large number of programs]
  D --> E[Filter: keep those passing the example tests]
  E --> F[Cluster by behaviour on generated inputs]
  F --> G[Submit at most 10, one per cluster]
  1. Read the statement as one sequence. The encoder takes the whole description as a sequence of subword tokens. The paper allows up to 1,536 input tokens for the encoder and 768 for the decoder. Check: the input is one text sequence, and the description is at most 1,536 tokens long.

  2. Pre-train on code, then fine-tune on contests. The model is first trained on 715.1 GB of open-source code from GitHub, then fine-tuned on CodeContests. The pre-training gives it a good sense of how programs look, and the fine-tuning adapts it to the difficult, unfamiliar style of competitive problems. Check: the paper's ablation shows that dropping pre-training lowers the solve rate, so both stages matter.

  3. Generate a large number of samples. The decoder writes a program one token at a time until an end-of-code token. In the toy problem the model writes eight programs. In the real system it writes up to millions per problem, which is possible because sampling parallelises well and multi-query attention keeps it cheap. Check: eight samples here, and each sample is a complete program.

  4. Filter with the example tests. Each program is run on the example inputs from the statement, and only those that produce the expected output survive. Filtering removes about 99% of the samples. In the toy problem three of the eight pass. Check: three programs survive; the other five are dropped.

  5. Make new test inputs and cluster. A separate model writes new inputs for the problem. Each surviving program is run on them, and programs that give the same outputs form one cluster. Suppose two of the three survivors give the same outputs on the new inputs, so one cluster has two members, and the third program forms a cluster of one. Check: the three survivors fall into two clusters, sizes two and one.

  6. Submit one per cluster, largest first. The rule takes one program from each cluster, starting with the largest, because correct programs tend to behave the same and so form large clusters, while wrong ones scatter. Here that gives two submissions: one from the cluster of two, then one from the cluster of one. Check: two submissions, both allowed under the ten-submission limit.

The math

Step 1 in symbols: the model

The encoder reads the statement XX and the decoder writes the program YY. The model is an encoder-decoder Autoregressive Model, so the probability of a program is the chain of next-token probabilities:

p(Y∣X)=∏t=1Tp(yt∣y<t,X),p(Y \mid X) = \prod_{t=1}^{T} p\left(y_t \mid y_{\lt t}, X\right),

where yty_t is the token at position tt and y<ty_{\lt t} is the program so far. Sampling draws each token from this distribution in turn.

Step 3 in symbols: sampling with a temperature

Before the softmax, the logits zjz_j are divided by a temperature TT. The probability of token jj becomes

pj=exp⁡(zj/T)∑kexp⁡(zk/T).p_j = \frac{\exp(z_j / T)}{\sum_k \exp(z_k / T)}.

A temperature below 1 sharpens the distribution toward the top choice, and a temperature above 1 flattens it. The paper trains with T=0.2T = 0.2 to reduce overfitting to the small fine-tuning set, and samples with a different, tuned temperature. This is the Softmax Temperature idea applied to training as well as sampling.

Step 4 in symbols: the metric

For a problem, let nn be the number of submissions allowed and kk the number of samples drawn. The metric n@kn@k is the fraction of problems for which at least one of nn submitted programs passes all hidden tests. The paper reports expected values over bootstrapped subsets, so the estimate does not depend on one lucky draw. The pass rate pass@k\text{pass}@k is the same quantity with n=kn = k, so it is an upper bound for any filtering method.

Step 6 in symbols: how solve rate scales

The paper finds that the solve rate rises approximately linearly with log⁡k\log k, which is written as

solve rate(k)≈a+blog⁡k,\text{solve rate}(k) \approx a + b \log k,

with aa and bb fitted constants. A larger bb means a better model needs fewer samples to reach a given rate. The authors use this to argue that improving the model is the efficient way to get more solved problems.

Results

The paper's numbers are below. The first table has the simulated Codeforces contests, and the others come from the CodeContests dataset.

Simulated contests. On ten Codeforces contests from December 2021, each with more than 5,000 participants, the system placed in the top 54.3% on average. The best contest was 48.4% and the worst 77.2%. The percentage is the share of participants who did better, so 54.3% means a little over half the field outranked it. With its estimated rating of 1238, the paper places it within the top 28% of users who entered a contest in the last six months. The paper also notes that the system solved problems mostly from the easier end of each contest, and it solved one problem rated 1800.

Submissions. With at most 10 submissions per problem, the system used 2.4 submissions on average for each problem it solved. Allowing more than 10 submissions, which does not follow contest rules, moved the average placement to the top 48.8%.

CodeContests solve rates (single 41B model with clustering):

MetricValidationTest
10@1k21.0%16.4%
10@10k26.2%25.4%
10@100k31.8%29.6%
10@1M34.2%not reported

The test set contains problems published after the training data, so no test problem appeared in training. The 41B model consistently outperforms the 9B model, and clustering consistently improves the results at every budget shown.

Pre-training and data. Starting from no pre-training and using the same fine-tuning, the 1B model reaches 10.5% at 10@100K. Pre-training on the full GitHub dataset reaches 21.5%. Pre-training on Python alone reaches 15.5%, and pre-training on MassiveText, a generic text corpus with some GitHub, reaches 21.2%. So the breadth of languages in pre-training mattered.

Architecture. The paper's comparison shows that the encoder-decoder model with multi-query attention improves sampling speed while keeping sample quality at the level of the more expensive alternatives. Faster sampling matters because drawing more samples is what drives the result.

Limits. The contest evaluation simulates participation rather than running live, and its entrants are a self-selected group. The paper says about 10% of problems have no program that passes the example tests, so filtering cannot even start for them. The solve rate depends on sampling millions of programs, which is far from cheap. And the authors note that validation loss is a poor guide to solve rate, so the metric you optimise has to be the one you care about.

Reading guide

The paper runs in six parts. Each part depends on the lessons listed here.

Check yourself

QuestionWhy does AlphaCode submit at most 10 programs per problem, even though it samples up to a million?Show answer

Contests penalise incorrect submissions, and the paper's metric caps submissions at 10 to match. Sampling many programs is useful because filtering and clustering can pick out the few likely-correct ones, but the final choice is limited to 10 submissions. This is the 10@k setting.

QuestionOn the test set, the 41B model with clustering moves from 16.4% at 10@1k to 29.6% at 10@100k. What is the gain in percentage points, and how many times more samples does that take?Show answer

The gain is 29.6 − 16.4 = 13.2 percentage points. Going from 1,000 samples to 100,000 is 100 times more samples. This is the log-linear trade-off the paper describes: each extra factor of ten in samples buys a roughly fixed gain, so the cost rises much faster than the benefit.

QuestionWhy does the paper filter with the example tests and then cluster, instead of picking submissions at random from the programs that pass the examples?Show answer

Many programs pass the examples but are wrong on hidden tests, and many are different code for the same behaviour. Random picks waste the 10-submission budget on near-duplicates. Clustering on outputs for generated inputs groups programs that behave the same, so each submission covers a different behaviour. Choosing from the largest clusters first works because correct programs tend to agree with one another.

QuestionA team reports a model solves 40% of its benchmark at 10@100k. Why is that not enough to say it would win a live contest?Show answer

The benchmark measures the solve rate on problems the team chose, under the team's test set and metric. The live contest uses hidden tests, a time limit, a penalty for wrong submissions, and a different difficulty mix. A solve rate on a benchmark is not a contest placement. The paper's 29.6% on the CodeContests test set is measured under its own filtering and submission rules, and its contest placement of 54.3% is a different measure, taken on simulated live contests. A benchmark number needs the same protocol, and the same kind of comparison, to mean anything.

Sources

Read the full paper

Yujia Li, David Choi, Junyoung Chung et al., 2022. arXiv:2203.07814