Search

Search papers and lessons

Program Synthesis

Level 3 · 12 min read

Program synthesis builds a program automatically from a description of what it should do, such as a few input-output examples, by searching a space of programs for one that passes a check.

On this page

  • Colour = topic mix
  • Algorithms
  • Discrete math
  • Calculus
  • Probability
  • Losses & regularization
  • Pre-training
  • ReadReady to readNot yet

TL;DR

Program synthesis is the task of building a program automatically from a description of what it should do. The description can be a few input-output examples, a formal specification or a request in plain language. The system searches a space of candidate programs and returns one that passes a check against the description. It matters because writing correct code by hand is slow, and a search that is checked against the same tests the user cares about can produce code that is correct by construction for those tests.

Builds on: Abstract Syntax Tree, Tree Search, Language Model · Leads to: Code as Policies

Where it's used

Spreadsheet formulas. Flash Fill, a feature of Microsoft Excel from 2013, watches a few cells the user has filled in by hand. Typing "Lovelace, A." next to "Ada Lovelace" is enough for it to fill the rest of the column with the same pattern. The program behind the fill is synthesised from those examples, and it is only accepted if it reproduces every example the user gave.

Code assistants and programming contests. A large language model proposes many candidate functions for a task, and a filter runs each one against example tests and keeps the ones that pass. DeepMind's AlphaCode (2022) used this generate-then-filter pattern on competitive programming problems. The Codex paper (2021) measured a model trained on public code by running its generated functions against unit tests, not by reading them.

Robot control. In Code as Policies (2022), a language model is prompted with a few examples and writes short Python programs that call perception and motion functions. A spoken command such as "stack the blocks" becomes a program that the robot then runs. The synthesised program is the robot's policy, and it can be read, edited and re-run.

How it works

Take a tiny task. The specification is two examples: input 1 must give output 2, and input 3 must give output 6. The search space is every expression built from the variable xx, the constants 1 and 2, and the operators ++ and ×\times.

  1. Write the specification. The examples are the spec: f(1)=2f(1) = 2 and f(3)=6f(3) = 6. Check: a candidate is correct only if it matches both pairs.
  2. Define the space of programs. A program is a leaf (xx, 1 or 2) or an operator with two sub-programs. Check: x+xx + x and 2×x2 \times x are in the space. x+5x + 5 is not, because 5 is not a leaf.
  3. Enumerate by size. The size of a program is its number of nodes. List all programs of size 1, then size 3, then size 5, and so on. Check: the size-1 programs are xx, 11 and 22.
  4. Run each candidate on the examples. At input 1, the leaf xx gives 1, not 2. The leaf 1 gives 1. The leaf 2 gives 2 at input 1, but gives 2 at input 3, not 6. All three fail. Check: nothing of size 1 passes, so the search moves on.
  5. Keep the first match. At size 3, x+xx + x gives 2 at input 1 and 6 at input 3, so it passes both examples and the search stops. Check: 2×x2 \times x also passes both examples. It is the same function as x+xx + x (both give 2x2x everywhere), so the choice between them does not change the behaviour, but the examples alone cannot tell the two programs apart from the function they compute.
flowchart TD
  S[Examples as the spec] --> E[Enumerate programs of size n]
  E --> T{Does a program match every example?}
  T -- yes --> R[Return it]
  T -- no --> N[Try the next program]
  N --> E2{Any programs left at size n?}
  E2 -- yes --> E
  E2 -- no --> G[Grow to size n plus 2]
  G --> E

The loop is a Tree Search in which each program is a node. The search is only feasible because the programs are small and the test is cheap.

The math

Definition: Program synthesis problem
Given a grammar GG that defines a set of programs L(G)\mathcal{L}(G), and a specification made of input-output examples (x1,y1),…,(xm,ym)(x_1, y_1), \dots, (x_m, y_m), find a program p∈L(G)p \in \mathcal{L}(G) such that p(xi)=yip(x_i) = y_i for every example ii. Here p(x)p(x) means the output of the program pp when it is run on the input xx.

Step 1 in symbols: the specification as a test

Define the check sat(p)\mathrm{sat}(p) to be 1 when p(xi)=yip(x_i) = y_i for all ii, and 0 otherwise. A program satisfies the specification exactly when sat(p)=1\mathrm{sat}(p) = 1. Equivalently, sat(p)\mathrm{sat}(p) is the product over the examples of the indicator that each example matches:

sat(p)=∏i=1m1[p(xi)=yi]\mathrm{sat}(p) = \prod_{i=1}^{m} \mathbf{1}\big[p(x_i) = y_i\big]

Step 2 in symbols: the grammar

Take the grammar E::=x∣1∣2∣E+E∣E×EE ::= x \mid 1 \mid 2 \mid E + E \mid E \times E. Every binary operator adds one node for itself, so a program with an operator at the root and two children has size 1+n1+n21 + n_1 + n_2, where n1n_1 and n2n_2 are the sizes of the children. The sizes of programs are therefore 1,3,5,…1, 3, 5, \dots.

Step 3 in symbols: enumeration by size

Let Ln\mathcal{L}_n be the set of programs of size nn. Then L1={x,1,2}\mathcal{L}_1 = \{x, 1, 2\}, which has 3 elements. For size 3, a program is an operator applied to two leaves, so ∣L3∣=2×3×3=18|\mathcal{L}_3| = 2 \times 3 \times 3 = 18, from 2 operators, 3 choices for the left leaf and 3 for the right.

Step 4 and 5 in symbols: the search rule

The search returns the first program in the enumeration order that satisfies the check:

p∗=the first p in L1,L3,L5,… with sat(p)=1p^\ast = \text{the first } p \text{ in } \mathcal{L}_1, \mathcal{L}_3, \mathcal{L}_5, \dots \text{ with } \mathrm{sat}(p) = 1

Evaluating sat(p)\mathrm{sat}(p) can stop at the first failed example, because one mismatch already makes the product 0. The number of programs of size nn grows roughly exponentially in nn, so this search is practical only for small programs. Pruning, which discards whole groups of programs that cannot match, is what makes larger searches possible.

Worked examples

Example
1. A constant function, tiny and by hand

Specification: f(0)=2f(0) = 2 and f(1)=2f(1) = 2.

  1. Size 1, leaf xx: f(0)=0f(0) = 0, which is not 2. Reject.
  2. Size 1, leaf 11: f(0)=1f(0) = 1, which is not 2. Reject.
  3. Size 1, leaf 22: f(0)=2f(0) = 2 and f(1)=2f(1) = 2. Both match.
  4. The search returns the program 22.
  5. Interpretation: the search tested three programs, and the answer is a constant. The examples only ask for a constant, so the smallest program is enough.
Example
2. Squares, the standard case

Specification: f(1)=1f(1) = 1, f(2)=4f(2) = 4 and f(3)=9f(3) = 9.

  1. Size 1: xx gives f(2)=2f(2) = 2, not 4. Reject. The leaves 11 and 22 give constants, which fail at input 1 or input 2. Reject.
  2. Size 3: the search tests the 18 programs in turn. The sums such as x+xx + x give f(1)=2f(1) = 2, which is not 1. Reject.
  3. Continue through the products and sums. For example x×2x \times 2 gives f(1)=2f(1) = 2. Reject.
  4. The program x×xx \times x gives f(1)=1×1=1f(1) = 1 \times 1 = 1, f(2)=2×2=4f(2) = 2 \times 2 = 4 and f(3)=3×3=9f(3) = 3 \times 3 = 9. All three match.
  5. Interpretation: the search found the square with 3 nodes, and it is the only program of size 3 with these outputs. The check did all the work, and nothing in the search needed to know that the answer is a square.
Example
3. A name reformatter, realistic

Real string tools use a richer space, with operators such as "take the last word" and "take the first letter". Here is one such program.

Specification: "Ada Lovelace" becomes "Lovelace, A." and "Alan Turing" becomes "Turing, A.".

  1. Split the input on spaces. "Ada Lovelace" gives the words "Ada" and "Lovelace".
  2. Take the last word, "Lovelace".
  3. Take the first letter of the first word, "A".
  4. Join the pieces in order: the last word, then ", ", then the letter, then ".". The result is "Lovelace, A.".
  5. Check the second example in the same way. "Alan Turing" gives "Turing" and "A", so the output is "Turing, A.", which matches.
  6. Interpretation: the program is correct on both examples and reads like the rule a person would state. It also generalises to other names with the same shape.

Try it: apply the same program to "Grace Hopper". Answer: "Hopper, G.". The last word is "Hopper", the first letter of "Grace" is "G", and the joined result is "Hopper, G.".

Common mistakes and tradeoffs

It is tempting to think that a program which matches the examples is correct. In fact the examples only test the program on the inputs given. A program can fit f(1)=2f(1) = 2 and f(3)=6f(3) = 6 and still be wrong at x=5x = 5, for instance a program that returns 2x2x on those two inputs and something else elsewhere. Good synthesis keeps a separate set of held-out tests, or asks for more examples when several programs fit with different behaviour.

It is tempting to think that a large language model writes correct code, so no search is needed. In fact the model is a source of candidate programs. Its output is only trusted after a check, which is why the code-assistant pipeline runs tests on every candidate. The check is what turns a plausible guess into a verified answer.

It is tempting to think that a bigger search space always gives better programs. In fact the number of programs grows exponentially with size, so a larger grammar makes the search slower and more likely to return a long, odd program that fits the examples by accident.

When to use it. Use program synthesis when the specification can be checked cheaply, such as examples, tests or a formal property, and when the program is short enough for the search to reach. Enumerative search is exact and easy to explain. Genetic programming trades that exactness for a different way of exploring the space. Neural models trained on code, and In-Context Learning from a few examples in the prompt, handle vague descriptions well but need sampling and filtering to be reliable.

When not to use it. When the specification is hard to write down, synthesis has no check to rely on. Then the cost of finding a program is not the bottleneck, and the cost of agreeing on what the program should do is.

Alternatives. Formal Verification proves that a given program meets a property, rather than searching for one. Type checking catches a class of errors without running the program.

History

In 1971, Zohar Manna and Richard Waldinger proposed deriving a program from a proof that its specification can be met, one of the first serious attempts at automatic programming. In the mid-1970s, Phillip Summers showed that small LISP programs could be built from examples of their input and output. The field was slow for decades, because the search space grew faster than the computers of the time could cover.

In 2011, Sumit Gulwani published a method for synthesising string-transforming programs from examples, which became the basis of Flash Fill in Excel. It worked because the search space was small and designed around the operations people actually use on text. In 2013, Alur and colleagues proposed syntax-guided synthesis, which states the grammar and the correctness condition explicitly, so that a solver can be reused across problems.

Large language models changed the picture from 2021. Codex was measured by running generated functions against unit tests, and AlphaCode (2022) generated many candidate solutions and filtered them with example tests. Code as Policies (2022) applied the same idea to robot control, where the generated program is run on the robot.

Recap

  • A program synthesis problem has three parts: a space of programs defined by a grammar, a specification such as examples, and a check that the program meets it.
  • The simplest search enumerates programs in order of size and returns the first one that passes the check, as a Tree Search over programs.
  • The examples do not force a unique program, and the number of programs grows exponentially, so practical systems prune the space and add held-out tests.
  • Language models make the candidate generation broad and vague descriptions possible, but the check still decides what is correct.

Read next: Code as Policies applies synthesis to a robot, and Symbolic Regression uses the same search to find equations from data.

Check yourself

QuestionName the three parts of a program synthesis problem.Show answer
A program space defined by a grammar, a specification (for example input-output examples), and a check that a candidate meets the specification. The search runs over the first part and uses the second and third to decide what to return.
QuestionA grammar has leaves x and 1, and binary operators + and ×. How many programs have size 3?Show answer
There are 2 operators. The left and right children are each one of the 2 leaves, so there are 2 × 2 × 2 = 8 programs of size 3.
QuestionWhy can two examples fail to determine the correct program, even when a program passes both?Show answer
Two programs can agree on every input in the examples and disagree elsewhere. A program that returns 2x2x on inputs 1 and 3 but something else at x=5x = 5 fits the same two examples as 2x2x does. The examples test only the inputs given, so held-out tests are needed to rule out programs that fit by accident.
QuestionA team asks a language model for a function. It passes the five example tests they wrote, then fails on a hidden test. Which step of the pipeline failed, and what should change?Show answer
The check was too weak, because the five tests did not cover the case the hidden test uses. The model's output was treated as a candidate, which is correct, but the specification was not complete. The fix is to add tests that cover more cases, and to keep some tests hidden from the generator so it cannot fit them by accident.

Sources