Automatic Prompt Engineer

A language model reads a few examples, writes many candidate instructions, scores each one, and keeps the best. This search matched human prompts on 24 of 24 tasks.

Learn how a model can write, test and choose the instruction that steers another model, and why search beats a single guess.

Set the number of candidates to 1, then raise it. Watch the best score climb as the model tries more wordings. Then we build, piece by piece, every part of the method: the proposal, the score, the cheap filter and the loop.

You need a rough idea that a language model continues text and a little Python for the code. We build the rest from zero.

Based on “Large Language Models Are Human-Level Prompt Engineers” by Yongchao Zhou, Andrei Ioan Muresanu, Ziwen Han, Keiran Paster, Silviu Pitis, Harris Chan and Jimmy Ba (University of Toronto and Vector Institute), ICLR 2023. Read the paper on arXiv. A reading for MIT MAS.S62 How to AI an AI; it belongs to Lecture 2, Context Evolution. Every idea is re-taught here in our own words and devices.

Search for the instruction

5 demonstrations (input → output): prove → disprove, on → off, direct → indirect, and two more. The model must infer the rule.

1

Six of the twelve instructions and their scores are the paper’s own, from Figure 1(a): “write the antonym of the word” (−0.26), “give the antonym of the word provided” (−0.28), “reverse the input” (−0.86), “to reverse the order of the letters” (−1.08), “write the opposite of the word given” (−0.16) and “list antonyms for the given word” (−0.39). The other six, and the order in which they come up, are invented to show the idea. The score is the log probability of the right answer under the target model, closer to 0 is better.

Chapter 0

The Prompt Is a Program Nobody Can Read

See why the exact words of an instruction swing a model’s accuracy, and why people want a machine to search for them

You have a language model and five examples of a small task. Each example is a word and its opposite: prove and disprove, on and off, direct and indirect. You want the model to handle new words it has never seen.

So you type an instruction in front of each new word. “Write the opposite.” Does it work? Maybe. A colleague types “Give the antonym.” Another types “Reverse the input.” Only one of these wording choices is a good idea, and you cannot tell which by reading them.

The words you need

A language model is a program that reads text and continues it. A large language model (LLM) is a very big one. You talk to it with a prompt, the text it reads before it answers. Think of the prompt as the note you leave for a very capable temp worker who has never seen your office.

An instruction is the part of the prompt that says what to do. A demonstration is one worked example: an input and the output you want. Zero-shot means the model gets the instruction and a new input, with no worked examples. Few-shot means it also gets some demonstrations.

The paper treats the model as a black box: you can send text in and read text out, but you cannot see inside. That matches how most people use a model today, through an API. The instruction then acts like a program written in English, and the model is the computer that runs it.

Why the wording matters so much

A program with a typo does not run. A prompt with a clumsy word runs, but worse, and with no error message. The people who wrote this paper point out that the way a model reads a prompt may not match how a human reads it. So the quality of an instruction can only be measured one way: run it.

Here is real evidence. A well known finding says that adding “Let’s think step by step.” before the answer makes a model reason through arithmetic. On the MultiArith benchmark (grade school word problems), the same model, the same questions, and ten different trigger phrases give accuracies from 45.7% to 82.0%. Without any trigger the model scores 17.7%. Slide through the ranking below.

Rank ten wordings of one idea

Each bar is the accuracy of the same model on the same questions with a different phrase placed before its answer. Move the slider to pick a phrase.

2

The numbers are the paper’s Table 7: zero-shot chain of thought accuracy on MultiArith (Roy and Roth, 2016) with InstructGPT (text-davinci-002). Phrases 2 to 10 were written by people; phrase 1 was found by APE (Chapter 6). The first human phrase is the one from Kojima et al. (2022).

The best phrase beats the worst by 36.3 points. Nobody could have predicted that order by reading the phrases. “Let’s think like a detective step by step” sounds clever and scores 70.3%. “First,” sounds plain and scores 77.3%.

What people tried before

People have tried to automate this search in three ways. The first is plain trial and error by a human, called prompt engineering. It is slow, and you only learn what you thought to try.

The second uses gradients. A soft prompt is a set of extra numbers, not words, placed in front of the input and trained by gradient descent. It works, but it needs access to the model’s insides. It also gets costly as models grow. Most big models now sit behind an API that gives no gradients.

The third searches over words. Earlier systems used one special model to write prompts, another to score them, and a third to paraphrase them, and they leaned on human written templates. A closely related method from Honovich et al. (2022), which the paper calls Greedy, asks a model to guess the instruction once and takes whatever comes out. It has no search and no selection.

The paper’s claim is that one large language model can do the whole job. It writes the candidates, and the target model scores them. We call the method Automatic Prompt Engineer, or APE.

One request, followed all the way through

Take the antonym task and follow one request from your keyboard to the answer. You write the prompt as one string: the instruction, a blank line, then the new word. The model splits that string into tokens, the small pieces of text it counts. It reads them all and then writes the next tokens, one at a time. Those new tokens are the answer.

Nothing in that path tells you the instruction was a poor choice. If you wrote “reverse the input”, the model happily writes the word backwards. It did what you asked. The mistake was yours, and the only signal is that the answer is wrong. So you must check outputs against known answers, and you need known answers to check against. The five pairs play that role.

What a good solution must do

Look at the three hand methods again and you can list what a better method needs.

  1. It must work through an API. The model is a black box. You may send text and read text, and nothing else.
  2. It must use a number. Without a score, you cannot say that one instruction beats another.
  3. It must try many wordings. One guess gives one sample from a wide spread, as the ranking above shows.
  4. It must stay cheap. Every try is a paid call, so the method cannot score everything on everything.

The chapters that follow meet these needs one at a time: the score in Chapters 1 and 3, the many wordings in Chapter 2, the budget in Chapter 4. Chapters 5 to 8 then ask whether the finished machine is any good, and what it costs.

The road

Each chapter builds one part of the machine. The hero at the top is the whole machine in miniature: more candidates, better best score.

  1. Instruction as program: the problem as one equation, and what a score of 0 or 1 means.
  2. Propose: the template that makes a model write instructions from demonstrations.
  3. Score: execution accuracy and log probability, and which one wins.
  4. Filter: the cheap multi-round trick that avoids scoring everything fully.
  5. Results: 24 instruction induction tasks and 21 BIG-Bench tasks.
  6. Chain of thought and truth: two new jobs for the same search.
  7. Ablations: what really matters, including iteration and transfer.
  8. Cost and limits: tokens, money and where APE fails.
  9. Field guide: the numbers, a checklist, the code.
Why can nobody judge a good instruction just by reading it?

Chapter 1

An Instruction Is a Program, and the Score Is a Test

Turn “find a good prompt” into one equation, and learn what it means to run an instruction and grade it

Picture a small bakery. The owner leaves a note for a new helper: “Make the opposite of what I show you.” Then she shows five pairs of cakes. The helper reads the note and the pairs, and tries the next cake. Whether the note worked is only clear when the helper finishes the cake and the owner tastes it.

APE faces the same set-up. The note is the instruction. The pairs are the demonstrations. The helper is the target model. This chapter turns that picture into symbols, so that every later chapter can point at one part of it.

The data: demonstrations

The paper starts with a dataset Dtrain of input and output pairs, written (Q, A). Q is the question, the input the model will see. A is the answer, the output you want. The pairs come from some wider population X, so there are more pairs out there than the few you hold.

In the paper’s main experiments there are only five pairs per task. That is tiny. Five pairs are enough for a person to guess a rule, and the paper asks a model to guess it too.

The program: one instruction

The goal is a single instruction, written ρ, so that when the target model M reads the concatenation [ρ; Q] it produces the matching A. Concatenation just means joining two strings: the instruction first, then the question. Here is the actual text for one of our pairs.

Instruction: write the opposite of the word given.\n\nInput: prove\nOutput: → model continues with “disprove”

The model sees that string and writes the next words. Nothing else is passed in. In the paper’s zero-shot tests, those are the only inputs. The data flow is one string in, one string out.

The score: a test per example

To compare two instructions, we need a number. The paper writes it as f(ρ, Q, A): the score of instruction ρ on one pair. The simplest score is the 0-1 loss. It gives 1 if the model’s output matches A exactly and 0 if it does not. The paper calls this idea execution accuracy.

The score of an instruction is the average over pairs. That average is an expectation, a fancy word for the mean you would get if you tried infinitely many pairs from X. The goal then fits on one line.

ρ*
The best instruction we want to find. The star means “optimal”.
arg maxρ
Try every possible instruction and return the one with the highest value. It returns the instruction itself, not the score.
f(ρ)
The score of one instruction, averaged over all pairs.
E(Q,A)
The average over question and answer pairs drawn from the population.
f(ρ, Q, A)
The score on a single pair. With execution accuracy it is 1 if M([ρ; Q]) = A and 0 otherwise.

Try the equation on a tiny scale. Pick an instruction, and the device runs it on all five pairs and grades each output.

Run an instruction, grade it

Choose one of four candidate instructions. The box shows the model’s output for each input and whether it matches the true answer exactly.

Illustrative: the model outputs are written by hand to show the grading, not produced by a real model. The four instructions are “write the opposite of the word given”, “reverse the input”, “write a synonym for the word” and “put dis in front of the word”. Grading is the exact-match 0-1 loss from Section 3.2 of the paper.

Look at the first instruction. It does the right thing on four words. On “win” the model wrote “loss”, but the answer in the data is “lose”. The exact-match score gives that a 0, even though a person would nod at it. So f(ρ) = 4/5 = 0.8. That strictness is a feature: it makes the score cheap, automatic and fair between candidates.

Why this is hard to solve directly

If instructions were numbers, you could use calculus. They are strings. Suppose each instruction has 20 tokens (pieces of text) and the model knows 50,000 tokens. Then there are 50,00020, about 1094, strings to try. That number is only an example, but it shows why brute force cannot work.

You also cannot take a gradient. The score depends on what a frozen black-box model does with a string, and a string has no slope. The paper therefore treats the problem as black-box optimization: you may evaluate f for any candidate you choose, but you get nothing else back. The only way to do well is to guess smartly and test.

The paper names the whole task natural language program synthesis. Classical program synthesis searches for a program that fits input and output examples. Here the program is English, and the computer is a language model.

The plan, in two moves

APE uses a language model twice. In the first move, proposal, one model reads the demonstrations and writes a pool U of candidate instructions. In the second move, scoring, the target model runs each candidate and f grades it. Then you keep the highest. Chapters 2 and 3 take each move in turn.

A worked run, step by step

Follow pair five for the first instruction, to see every intermediate step. The string sent to the model is “Instruction: write the opposite of the word given.”, then a blank line, then “Input: win” and a new line “Output:”. The model continues with “loss”. The data says “lose”. The two strings differ, so f = 0. The other four pairs match, so f = 1 each. The mean is (1 + 1 + 1 + 1 + 0) / 5 = 0.8.

Now ask how much to trust 0.8. Five pairs is a small sample. A rough measure of the noise is the standard error, the square root of p(1 − p) / n. With p = 0.8 and n = 5 it is about 0.18. So a true accuracy anywhere from about 0.6 to 1.0 could easily give a score of 0.8 on five pairs. Two instructions that score 0.8 and 0.6 on the same five pairs may be equal in truth.

The failure mode: an instruction that only fits the five pairs

The symptom: an instruction scores 5 of 5 on the pairs you searched with, then does worse on new inputs. The measurement: score it again on pairs it never saw. The paper does exactly this. It picks the instruction using the training pairs and reports accuracy on a held-out test set Dtest, the expectation in Equation 1 taken over fresh pairs. The fix is to always report the test score, never the search score. A candidate that memorised the demonstrations, for example by copying one of them, looks perfect on the five pairs and falls apart on the rest.

There is a quieter version of the same trap. If you search for a long time on the same five pairs, the winner is partly the luckiest candidate. That is why the later chapters keep a separate test set and why the paper repeats its Instruction Induction runs with five random seeds.

An instruction is run on 5 pairs. The model matches the answer exactly on 3 of them. What is its execution accuracy, and what does arg max return?

Chapter 2

Propose: Ask a Model to Guess the Rule

Show a model the demonstrations, ask what the instruction must have been, and sample dozens of guesses

Imagine you find a worksheet with the teacher’s instruction torn off. Five solved lines remain: prove becomes disprove, on becomes off. You can still guess the missing line: “Write the opposite.” You work backward from the answers to the question that produced them.

That is the whole idea of the proposal step. Chapter 1 left us with a huge space of strings. Random strings are useless. But a language model has read a great deal of text, including worksheets, so it has a decent sense of which instructions would produce a given set of answers.

What we want to sample

The paper writes the target as P(ρ | Dtrain, f(ρ) is high). Read it aloud: the probability of an instruction, given the demonstrations and given that the instruction scores well. Sampling from exactly that is impossible, because we do not know which instructions score well until we test them.

So APE approximates it. It asks the LLM to “approximately infer the most likely instructions” behind the demonstrations. This inference model needs no training. It is the same off-the-shelf LLM, used in a new way: the instruction is the thing it writes.

Forward mode: write at the end

A language model writes left to right. So the easiest trick is to put the blank at the very end of a text and let the model fill it. The paper’s forward mode template, adopted from Honovich et al. (2022), is a short story.

“I gave a friend an instruction and five inputs. The friend read the instruction and wrote an output for every one of the inputs. Here are the input-output pairs:” Then the five pairs. Then the line “The instruction was” and the model continues. Whatever it writes is a candidate instruction.

Reverse mode: fill in the middle

Forward mode has a catch. In real prompts, the instruction sits at the start, not after the examples. The paper wants the instruction to be placeable anywhere in the text. A left-to-right model cannot write something that comes before text it has not seen.

The fix is reverse mode. It uses a model with infilling, the ability to fill a gap in the middle of a text. T5, GLM and InsertGPT are examples. The template starts “I instructed my friend to” followed by an INSERT marker, then the pairs. The model reads the pairs and fills the gap before them. In the paper this directly samples the target distribution, with the blank where the instruction will really sit.

Customised templates

The best meta prompt depends on the score. For TruthfulQA the authors start from a human written instruction idea: “Professor Smith was given the following instructions” followed by INSERT, then “Here are the Professor’s responses” and the questions and answers. Same trick, different story. Compare the three below.

Build the request to the proposer

Choose a template. The box shows the exact text sent to the proposing model, with the place where the model writes highlighted.

The three templates follow the paper’s Figure 2. The three antonym pairs are our own small example (the paper uses five pairs per task and, for TruthfulQA, six). The TruthfulQA question and answer are made up. The sample completions “to write the opposite of the word given.” and the “series of questions” instruction are quoted from the paper’s Tables 12 and 9.

In forward mode the model writes after “The instruction was”. In reverse mode it writes inside the first sentence. The words it adds are the candidate. Count the data flow: about a hundred words go in, and a short instruction, capped at 50 tokens in the paper’s cost study, comes out.

Draw many, not one

A single guess is the Greedy baseline of Honovich et al. It takes the most likely instruction once. APE instead samples many guesses, so it sees a spread of wordings. Each sample gives a different instruction because sampling picks words by probability, not always the top one.

The pool is called U. The paper’s default is 50 samples, based on a test in Chapter 7. The paper tuned two settings in Appendix F: how many proposals to draw per set of demonstrations, and how many demonstrations to show. The sketch below is ours, not the authors’ code.

def propose(llm, demos, m=50, k=5, mode="forward"):
    pool = []
    for _ in range(m):
        shown = random.sample(demos, k)          # k input/output pairs
        if mode == "forward":
            text = FORWARD.format(pairs=fmt(shown))   # ends with "The instruction was"
            pool.append(llm.complete(text, max_tokens=50))
        else:
            text = REVERSE.format(pairs=fmt(shown))   # has a hole after "my friend to"
            pool.append(llm.infill(text, max_tokens=50))
    return pool          # U = {rho_1, ..., rho_m}

Not every guess is good. The paper shows that on a hard task, half of the instructions from the best model are off-topic. That is fine. Proposal need only put a few good candidates in the pool, because Chapter 3 will find them.

A worked example of the data flow

Count what moves. The meta prompt for the antonym task holds the story sentence, five pairs and the cue “The instruction was”. In tokens that is roughly 100 to 150. It goes to the proposer as one string. The proposer returns up to 50 tokens. That string is one candidate. Repeat 50 times and the pool U holds 50 strings.

Many will be near copies. From the paper’s own examples you can see the spread: “write the antonym of the word”, “give the antonym of the word provided”, “write the opposite of the word given” and “list antonyms for the given word” all mean the same thing in different words. Others are wrong in an instructive way: “reverse the input” and “to reverse the order of the letters” fit the demonstrations only if you misread them. That mix is what you want. A pool of near copies wastes scoring calls, and a pool of nonsense wastes them too. A pool with several different readings of the data gives the score something real to choose between.

The failure mode: a pool with no good candidate

The symptom: after scoring, every candidate is poor. The measurement in the paper is the survival function of Chapter 7: on the hard task Start With, about half of the instructions from the best proposer were off-topic. The fix has two parts. Sample more candidates, because each draw is another chance. Or change the meta prompt, because the template shapes the whole pool. The paper tried a different story (the TruthfulQA template) on one task, Membership, and found good instructions that the original template never produced.

There is one more thing to watch in the output. The paper notes that one proposer, OPT, sometimes put in-context examples inside its instruction. Such a candidate is no longer zero-shot. It smuggles in examples, and its score hides what the instruction itself does.

Why does the paper add “reverse mode” when forward mode already works?

Chapter 3

Score: Two Ways to Grade an Instruction

Compare a hard pass-or-fail grade with a soft probability grade, and see why the paper chose the hard one

A teacher marks a maths test in two ways. She can count the questions you got exactly right. Or she can read each wrong answer and note how close you came. Two students with the same count of right answers can differ in how badly they missed the rest.

APE has the same choice. The pool U holds about 50 candidate instructions. We need one number per candidate, and the paper offers two.

Score 1: execution accuracy

Execution accuracy, written fexec, was proposed by Honovich et al. (2022). It runs the instruction and checks the output. For most tasks it is the 0-1 loss from Chapter 1: f(ρ, Q, A) = 1 if M([ρ; Q]) = A, and 0 otherwise.

Some tasks need a looser match. When the answer is a set of words, the order should not matter. Then the paper uses an order invariant set matching: the output counts as right if it has the same items as the answer in any order. The Honovich et al. appendix gives the details.

The data flow per pair is one model call. A string goes in and a string comes out. The model must write several tokens, so a call generates text and then compares it with A.

Score 2: log probability

The second score asks something softer: how likely did the model think the true answer was? It is the log probability of the desired answer given the instruction and question: log P(A | [ρ; Q]).

f(ρ, Q, A)
The score of instruction ρ on one pair. A value near 0 is good. A big negative value is bad.
PM
The probability the target model M assigns. A model gives every next token a probability, and the answer’s tokens multiply together.
A
The true answer from the dataset. We do not let the model write it; we ask how likely it was.
[ρ; Q]
The instruction joined to the question. This is the condition, the text the model has already read.

A logarithm turns a long product of small chances into a sum, so the number stays readable. A probability of 0.9 has a log of about −0.11. A probability of 0.01 has a log of about −4.6. One very unlikely answer drags the sum down hard.

Why add a second score? The authors hypothesise that a probability gives “a more fine-grained signal when searching over low-quality instruction candidates.” When all 50 candidates get an exact-match score of 0, execution accuracy cannot tell them apart. A probability can.

See them disagree

Below are four candidates for the antonym task, each tested on five pairs. For every pair the table gives the model’s probability for the true answer and whether its text output matched exactly. Switch the score and watch the winner change.

Rank by two different scores

Pick a score. Bars grow with the quality of each candidate; the top one is what APE would keep.

Illustrative: the probabilities and match flags are made up to show how the two scores can disagree. Mean log probability is the average of ln P(A) over the five pairs, in natural logarithms. Which score the paper keeps is shown in Figure 7 (Middle).

Candidate one matches four of five answers exactly, so fexec = 0.8. But on one pair it gave the true answer a chance of only 0.01. Its mean log probability is about −1.16. Candidate two matches only two of five, but it never gets a pair badly wrong, and its mean log probability is about −0.90. The execution score keeps candidate one. The probability score keeps candidate two.

Now look at candidates three and four. Both score 0 on execution, so execution accuracy calls it a tie. Their log probabilities are −3.33 and −5.39, so the soft score still ranks them.

Which one wins

The paper tests the question directly. For each of the 24 tasks it generates 250 instructions with InstructGPT (175B) in forward mode, and scores them with both metrics. Then it measures the Spearman correlation between each score and the real test accuracy. This number says whether two rankings agree: 1 means a perfect match, 0 means no link.

Execution accuracy matches test accuracy better across the tasks (Figure 7, Middle). So the paper makes it the default score. The log probability score stays as an option, and for TruthfulQA the paper uses other automatic metrics instead (Chapter 6).

Worked arithmetic for the probability score

A model writes an answer one token at a time. Suppose the true answer “disprove” takes two tokens. The model gives the first token a probability of 0.6, and then gives the second token, given the first, a probability of 0.9. The chance of the full answer is the product, 0.6 × 0.9 = 0.54. The log of that is ln(0.54) = −0.62. Adding the logs of the two parts gives the same number: ln(0.6) + ln(0.9) = −0.51 + (−0.11) = −0.62.

Where does the model get those numbers? From a single forward pass over the prompt plus the true answer. You feed it [ρ; Q] followed by A, and at each answer position you read off the probability it gave to the token that actually came next. No text is generated, so this score needs one pass per pair, with the answer supplied. Execution accuracy needs a generation, which is a different kind of call.

A looser match for set answers

Take the task Starting With. The input is a sentence and a letter, and the answer is the list of words that start with the letter. If the true answer is “man, me” and the model writes “me, man”, exact match gives 0 though the model is right. An order invariant set match compares the two as sets, so the order is ignored and the pair scores 1. This is the reason the paper says execution accuracy “takes into account invariants” on some tasks.

The failure mode: the score is too strict, or too easy to fool

The symptom: a good instruction gets a low score. In Chapter 1, “loss” against “lose” is a case. The measurement: read the failed pairs by eye. The fix: use an invariant match where order or format should not count, or use the log probability, which gives partial credit.

The opposite symptom is worse: a poor instruction gets a high score. Chapter 5 shows the Rhymes case, where instructions that echo or transform the input scored near 1.0 on a zero-shot test. A score is a measuring stick that the search will lean on as hard as it can. Check its top picks by reading them.

When would log probability separate two candidates that execution accuracy cannot?

Chapter 4

Filter: Spend Calls Where They Count

Score every candidate on a few pairs first, drop the weak ones early, and give the survivors the full test

A talent show has 50 acts. The judges cannot watch all 50 for an hour each. So they give every act two minutes, send home the clear misses, and let the rest perform longer. Nobody calls this unfair. It spends judge time where it matters.

APE has the same budget problem. Each candidate must be run on the training pairs, and every run is a call to the target model. A call costs money and time. This chapter shows how the paper avoids scoring all candidates on all pairs.

The cost of doing it the plain way

Say the pool has m = 50 instructions and the training set has n pairs. Scoring everything on everything takes m × n model calls. For n = 100 that is 5,000 calls. Most of those calls go to candidates that are plainly bad after a handful of tries.

The paper calls the fix efficient score estimation. The idea: a promising candidate should get more computation, a poor one less. The paper uses “a multi-stage computation strategy.”

The multi-stage filter, step by step

  1. Stage 1. Score all candidates on a small random subset of the training pairs.
  2. Filter. Keep only the candidates above a threshold. In Algorithm 1 this is the top k% by score.
  3. Next stage. Draw a new subset that does not overlap the old one. Score the survivors on it, and update each one’s moving average, the running mean over every subset seen so far.
  4. Repeat until a small set remains.
  5. Final. Score the last few on the whole training set. The one with the highest score becomes ρ*.

The paper says this scheme works by “keeping the exact computation costs for the high-quality samples and drastically reducing the computation costs for low-quality candidates.” It borrows the idea from earlier work on sampling by subsets (Li et al., 2022; Maclaurin and Adams, 2015).

Algorithm 1, line by line

U = propose(llm, D_train)                  # line 1: sample instruction proposals
while not converged:                      # line 2
    D_sub = random_subset(D_train)        # line 3: a fresh subset
    for rho in U:                         # line 4
        s[rho] = f(rho, D_sub)            # line 5: score on the subset
    U_k = top_k_percent(U, s)             # line 7: filter by score
    U = U_k  or  resample(U_k)            # line 8: keep, or ask the LLM for variants
best = argmax(U_k, key=lambda r: f(r, D_train))   # return the top on the full set

Line 8 gives two choices. You can simply keep the survivors. Or you can use the LLM to write new instructions that are similar to the survivors. That second choice is iterative Monte Carlo search, which Chapter 7 tests.

Try the filter

Below, 24 invented candidates are scored on a pool of 40 pairs in five rounds of 8 pairs each. Each dot is a candidate’s running mean. Drag the keep fraction and press the button for fresh luck.

Drop weak candidates early

Each line follows one candidate across the rounds. Grey lines were dropped. The green ring marks the truly best candidate; it turns red if the filter dropped it.

50%

A simulation with made-up candidates: their true accuracies are fixed numbers and each pair is scored right or wrong by seeded chance. The paper’s own scheme is the one in Section 3.2; its thresholds and subset sizes are not given here, so we use rounds of 8 pairs and a top-percent cut as in Algorithm 1.

At the default of 50%, the field halves each round: 24, 12, 6, 3, 2. The total is about 380 scored pairs where full scoring takes 960. That is a saving of roughly 60%. Press New luck a few times. Usually the best candidate survives, and when it does not, the winner is still a good one.

The failure mode

Slide the keep fraction down to 10%. The symptom: the green ring turns red, because the best candidate was dropped in round one. The measurement: with only eight pairs, a candidate with true accuracy 0.9 can still miss three of them by chance and look average. The fix: keep a more generous slice early, or use bigger first subsets. A cheap filter trades a little risk for a lot of savings, and the keep fraction sets the trade.

The loop

Resampling uses one small prompt (Figure 3): “Generate a variation of the following instruction while keeping the semantic meaning.” followed by Input: the instruction and Output: the blank. It asks the same LLM to paraphrase the survivors. Then the new variants go through the same filter. The paper treats this as optional, and Chapter 7 shows why it is off by default.

Worked numbers for the moving average

Follow one candidate through two stages. In stage one it gets 6 of 8 pairs right, a mean of 0.75. In stage two, on a fresh set of 8 pairs, it gets 4 of 8. The moving average is the mean over everything seen so far: (6 + 4) / 16 = 0.625. A candidate that scored only 2 of 8 in stage one has a mean of 0.25 and is probably cut at once.

The total cost follows from the pool sizes. Call the pool size at stage s ns and the subset size b. The pairs scored are the sum over stages of ns × b. With 24, 12, 6, 3 and 2 survivors and b = 8, that is 8 × (24 + 12 + 6 + 3 + 2) = 8 × 47 = 376. Full scoring is 24 × 40 = 960.

Why too small a subset is risky

Use the standard error again. A candidate with a true accuracy of 0.8, scored on 8 pairs, has a standard error of about the square root of 0.8 × 0.2 / 8, which is 0.14. A candidate with a true accuracy of 0.6 has about 0.17. Those bands overlap. After one stage, the better candidate can easily look worse than the weaker one. This is why a cut that keeps only a thin slice is dangerous early, when the numbers are noisy, and why the finalists must face the whole training set.

A sound design therefore cuts gently at first and harder later. In the paper this is the “certain threshold” of Section 3.2. The device above lets you see the same effect with the keep fraction.

What is the main reason for scoring candidates on small subsets before the full training set?

Chapter 5

What 24 Plus 21 Tasks Show

Read the paper’s main tables, task by task, and learn what “human-level” does and does not claim

A paper’s title makes a claim. Here it is “human-level prompt engineers.” To see what that means, you need three facts: which tasks, which baselines, and how success is graded. This chapter reads the main results the way a careful reviewer would.

The set-up for Instruction Induction

Instruction Induction is a benchmark by Honovich et al. (2022) with 24 small language tasks. They cover spelling (first letter, second letter), morphosyntax (pluralization, passivization), word meaning (antonyms, synonyms), translation, sentiment, numbers (sum, difference) and more. Each task comes with a human written gold instruction.

For each task the authors take five input and output pairs from the training data and run APE to pick an instruction. Then they run that instruction on the target model, InstructGPT (the text-davinci-002 model through the OpenAI API), on held-out test pairs. They repeat everything with five random seeds and report the mean and spread.

Two baselines compete. Human is the gold instruction, manually checked. Greedy is the one-shot model-written instruction of Honovich et al., with no search and no selection. This is the cleanest comparison: the only difference between Greedy and APE is the proposal pool and the scoring.

The headline numbers

APE beats Greedy on every task. APE equals or beats the human instruction on 24 of 24 tasks. To summarise across tasks the paper uses the interquartile mean (IQM): sort the 24 task scores, throw away the lowest quarter and the highest quarter, and average the middle half. It is less pushed around by a few outlier tasks than a plain mean. With InstructGPT, APE scores an IQM of 0.810 and humans score 0.749.

One honest note from the appendix. The extra visualisations come from an earlier version of APE that reached human level on only 19 of 24 tasks. After the authors tuned two settings, the number of proposals per demonstration and the number of demonstrations per random seed, they re-ran five tasks and got 24 of 24. On Second Letter the mean rose from 0.596 to 0.8, and on Membership from 0.126 to 0.612 (Table 17). So the final method includes some tuning on the benchmark.

Explore the results

The first view lists the instruction APE picked for each task and its zero-shot test accuracy (Table 12). The second view shows the BIG-Bench results described below. Slide through the rows.

Walk through the benchmark tasks

Choose a benchmark, then slide to a task. The highlighted row shows the instruction (left benchmark) or the human and APE scores (right benchmark).

1

Left benchmark: the best instruction by zero-shot test accuracy for each task, from the paper’s Table 12 (the Sentence Similarity and Word in Context instructions are shortened). Right benchmark: normalised zero-shot test performance, human against APE, from Table 6. The count of 17 is computed from those 21 rows.

Look at the failures as well as the wins. On Synonyms the best APE instruction reaches only 0.22 accuracy. On Common Concept the best instruction was literally “List things that”, followed by the inputs, and it scores 0.27. Some tasks stay hard because many answers could be right but only one counts under exact match.

BIG-Bench: harder tasks

Is the result special to easy tasks? The authors curated BIG-Bench Instruction Induction (BBII), 21 tasks from the BIG-Bench collection. They kept tasks with a clear human written instruction that applies to every example, and it includes all nine such problems from the BIG-Bench Hard subset. The tasks cover emotion, reading comprehension, summarisation, algorithms and several kinds of reasoning.

Here APE uses reverse mode with InstructGPT and ranks by execution accuracy. APE matches or beats the default human prompt on 17 of 21 tasks. The losses are logical fallacy detection, operators, presuppositions as NLI and ruin names. Some wins are large: object counting rises from 2.0 to 44.0.

Few-shot: does an instruction still help?

Now add worked examples, so the prompt holds both an instruction and demonstrations. The paper compares the plain few-shot prompt with an instruction placed in front of it. The instruction version is comparable or better on 21 of 24 tasks.

Three tasks went the wrong way: Rhymes, Large Animal and Second Letter. The authors suspect the instruction overfit to the zero-shot case. On Rhymes the picked instructions told the model to write a function that capitalises a word. Zero-shot, that scored near 1.0. With examples in the prompt it fell to between 0.03 and 0.39, because the instruction and the examples pulled in different directions. Scoring instructions with the few-shot metric reduced the drop.

Reading the evidence with care

Three checks help whenever you read a table like this. First, ask what the test data is. Here it is held-out pairs, never the five used to search. Second, ask about spread. The authors repeat the runs with five random seeds, and they report mean and standard deviation, so one lucky seed cannot carry the result. Third, ask what the baseline could have been. A human instruction written once is a fair but not a heroic baseline.

Look at the instructions themselves in Table 12. Many begin with a stray phrase such as “most likely” or “probably something like”. They are continuations of the cue “The instruction was”. Table 12 lists them as found. The search kept them because they scored well. Sentence Similarity shows the limit: the picked instruction trails off mid-sentence, and the score is 0.36. The method finds what works, not what reads well.

Some entries are impressive. First Letter, Pluralization, Passivization, Sum, Difference and Number to Word all reach 1.00. Some are modest. Synonyms is 0.22 and Common Concept is 0.27. Both tasks have many acceptable answers, and exact match accepts only one. The paper states that APE equals or beats the human instruction on all 24. It does not say every task is solved.

The failure mode: the score and the goal drift apart

The symptom: a result that looks too good. Rhymes reaches 1.00 zero-shot with an instruction about capitalising a word. The measurement: add examples to the prompt and the same instruction drops to between 0.03 and 0.39. The fix, in the paper, is to score the instructions with the few-shot metric when you plan to use few-shot prompts. The general rule: choose the score in the same setting where you will use the prompt.

What does an interquartile mean over 24 task scores do?

Chapter 6

Two New Jobs: Better Reasoning Prompts and Steered Honesty

Point the same search at a reasoning trigger and at a truthfulness goal, and see what the score really rewards

So far APE found an instruction that makes a model copy a rule from five pairs. But the search is general. It only needs a way to propose text and a score to rank it. Change the score and you change the job. This chapter shows two such changes.

Job 1: a better “think step by step”

Chain of thought means the model writes its reasoning steps before the answer. Kojima et al. (2022) found that you can trigger this with no examples: put “Let’s think step by step.” where the answer begins. This is called zero-shot chain of thought. It lifted InstructGPT on MultiArith from 17.7% to 78.7%, and on GSM8K (a harder maths set) from 10.4% to 40.7%.

Their phrase was the best of at least nine that people wrote (Table 7). Could a search do better? The authors follow a recipe inspired by STaR (Zelikman et al., 2022):

  1. Generate. Run InstructGPT on training questions with “Let’s think step by step.” and keep each question with the reasoning it wrote.
  2. Filter. Delete every item whose final answer was wrong. What is left is a set of good reasoning traces.
  3. Search. Use APE to find a phrase that starts with “Let’s” and makes those good traces most likely.

The template for step three is Q: [INPUT] A: Let’s INSERT. [OUTPUT]. The blank sits right after “Let’s”, so the proposer fills the middle of the phrase. The score is the likelihood of the correct reasoning, the log probability idea from Chapter 3. Execution accuracy does not fit here, because there is no short answer to match exactly.

The search returned: “Let’s work this out in a step by step way to be sure we have the right answer.” It improves MultiArith from 78.7 to 82.0 and GSM8K from 40.7 to 43.0. Table 7, the same table you saw in Chapter 0, ranks it above all nine human phrases.

The gain is real but modest, and the paper is careful on the wider picture. The same phrase was tried on 12 tasks from Kojima et al. It improved 6 of 12 and nearly matched humans on 4 of 12. The authors guess that Shuffled Objects and Last Letter are hard to improve with one general phrase. The lesson: APE can polish one part of a template you already use. That is a common job for a prompt engineer.

Job 2: steering toward truth

TruthfulQA (Lin et al., 2022) is a set of 817 questions that tempt a model to repeat common false beliefs. Two scores matter. % True is the share of answers a judge model rates as true. % Info is the share it rates as informative. A third number is the share that are both. The judges are fine-tuned models, GPT-judge and GPT-info, and they agree with human raters over 90% of the time.

The authors use 100 of the 817 questions as training pairs and keep 717 for testing. They draw 200 candidates from InstructGPT (175B) using a reverse-mode proposer and six random pairs, and take the top 10 by score. They stress that this is not “true few-shot learning” and the numbers are not comparable with the original benchmark. A single generic instruction must work across all 38 question categories, from health to law to fiction.

The result: APE finds instructions that reach over 40% both true and informative, against about 30% for the human “help” prompt from Lin et al. But there is a catch. The paper notes that its instructions can reach very high truthfulness with answers like “No comment,” which tell you nothing. The search found the two ends of the trade-off, not a free lunch.

Truthful or informative

Each dot is an instruction APE picked for TruthfulQA, plotted by how often its answers were true (across) and informative (up). Choose a dot to read its instruction.

The four points are rows of the paper’s Table 9 (selected by training % True, test numbers on 717 questions). The first two rows have identical numbers, so their dots sit on top of each other. The dashed arrow is our annotation of the trade-off the paper describes, not a fitted curve. The 40% and 30% figures in the text are the paper’s own, for the best instruction on the combined score.

All four dots sit in the same corner: very true, not very informative. That is what happens when you rank by % True alone. A model gets full marks for truth by declining to say anything. Real systems need both, and a score that ignores one of them will be gamed.

The failure mode: a general phrase that does not fit every task

The symptom: the new reasoning phrase helps on some tasks and not on others. The measurement: on 12 tasks it improved 6 and nearly matched humans on 4, so on the other two it fell short. The fix is to treat it as a default, not a law. If a task matters, run the search on that task. The authors suggest that Shuffled Objects and Last Letter need a more specific prompt than one general phrase can give.

In the chain of thought job, why does APE use the likelihood of correct reasoning traces as its score instead of exact match?

Chapter 7

Ablations: Which Part Earns Its Place

Remove or vary one part at a time to see what the proposer, the sample size, the loop and the target model each contribute

A recipe has many steps. A good cook asks which ones matter. Leave out the salt and the dish fails. Leave out the garnish and nobody notices. An ablation is that test for a method: change one part, keep the rest, and measure the damage. Section 5 of the paper runs four such tests.

Test 1: does the proposer’s size matter?

The authors use eight models from the OpenAI API: ada, babbage, curie, davinci, and the instruction-trained versions of each. Each model writes 250 instructions, and each instruction is run on 50 test points. The survival function shows, for each accuracy threshold, what share of instructions scored above it.

Bigger models write better pools, and so do models trained to follow human instructions. On the easy task Pluralization, every instruction from the best model, InstructGPT (175B), has reasonable accuracy. On the hard task Start With, half of its instructions are off-topic and score poorly. So the proposer is not magic. Its pool needs the next step.

Test 2: does selection fix a weak pool?

This is the heart of the method. If you sample more candidates, you are more likely to find a good one. The authors raise the sample size from 4 to 128 and track the test accuracy of the best pick. The line rises steadily with diminishing returns. Human-level performance arrives with 64 samples, and the default is 50.

Even small models help once you select. They write fewer good instructions, but some are good. Scoring finds them, and that is why APE beats the Greedy baseline across all eight models. Try it below: the first view shows how the best-of-N result climbs with more samples.

What more search buys

Choose what to increase. The curve shows the result; the marker follows the slider.

16

Illustrative: both curves come from a made-up pool, not from the paper’s data. The candidate curve averages 400 seeded trials of drawing N accuracies and keeping the best; we picked the pool and the dashed human level so that the crossing lands near 64, the number the paper reports in Figure 7 (Left). The round curves follow the shape the paper describes in Figure 6 (Right): the pool gets better for three rounds and then stabilises, while the single best stays about the same.

Test 3: which score?

Chapter 3 covered this. Execution accuracy correlates better than log probability with held-out test accuracy across the 24 tasks, using 250 forward-mode instructions per task and 10 test points. That is why it is the default.

Test 4: does the loop help?

Iterative Monte Carlo search (Chapter 4) asks the LLM to write variants of the survivors. On Passivization, the survival curve climbs each round, so the proposal pool does get better. But quality stabilises after about three rounds, and “the highest scoring instruction tends to remain the same.”

Across six tasks, iterating helps a little where APE was below humans and changes little elsewhere. That fits the authors’ guess: iteration matters most where a good first pool is hard to get. They conclude it gives only marginal gains and run plain APE by default.

More checks in the appendix

The failure mode: an instruction tied to one model

The symptom: you search with one model and deploy on another, and accuracy falls. The measurement is Figure 17: InstructGPT instructions steered GPT-3 badly. Strikingly, GPT-3’s own instructions steered GPT-3 “exceptionally well,” beating both the InstructGPT and the human instructions by a large margin, even though GPT-3 cannot follow human instructions well. Its prompts were odd. One antonym prompt reads as a rambling explanation of opposite pairs.

The fix is a rule: score on the model you will run. The paper’s conclusion is that “the alignment between the scoring model and execution model is crucial.” A prompt is not a universal object. It is a program written for one machine.

Derive why more samples help

Suppose a fraction g of the instructions a proposer writes are good, meaning they reach a score you would accept. Each sample is good with chance g. The chance that all N samples are bad is (1 − g)N, so the chance that at least one is good is 1 − (1 − g)N. This is the same coverage formula used for repeated sampling in general.

Try g = 0.05, a weak proposer. With N = 4 the chance of at least one good candidate is 1 − 0.954 = 18.5%. With N = 50 it is 1 − 0.9550 = 92.3%. With N = 64 it is 96.3%. The curve rises fast and then flattens, which matches the diminishing returns the paper reports. The default of 50 sits where the curve is already near its top. The numbers here are our arithmetic for one assumed g, not the paper’s data. The paper’s measured curve is Figure 7 (Left).

The formula also shows why a better proposer helps: a larger g shrinks (1 − g)N much faster, so fewer samples are needed. It shows why selection is essential too. Coverage only says a good candidate exists in the pool. The score must still find it.

Reading a survival function

A survival function answers: for each accuracy threshold x, what share of instructions scored above x? It starts at 1 for x = 0 and falls as x rises. A pool of mostly poor instructions drops fast. A good pool stays high for longer. In Figure 6 (Left) the larger and instruction-trained models keep their curves high. In Figure 6 (Right) the curve for each later round of iterative search sits above the previous one, which means the pool improved. That is how the paper shows both claims in one kind of plot.

Reading a rank correlation

Take five candidates. Their search scores rank them 1 to 5, and their test accuracies rank them 1 to 5. The Spearman correlation compares the two rank lists. If both lists are the same, it is 1. If one is the reverse of the other, it is −1. If they are unrelated, it is near 0. A score with a high correlation is a good guide to what will work on new data, and that is what the authors measured for the two scores.

A small model writes mostly poor instructions. Why can APE still beat Greedy with that small model?

Chapter 8

Cost and Limits: When the Search Pays Off

Count the tokens APE spends once and the tokens it saves on every later call, then list what it cannot do

A tailor spends a day measuring and cutting one suit. A shop sells a hundred off-the-rack suits that fit worse. The tailor is only worth it if you wear the suit often. APE is a tailor for prompts. This chapter asks how often you must use the prompt before the search pays for itself.

Where the money goes

Two kinds of calls cost tokens. First, the proposer writes instructions. Second, the target scores them. The paper measures both for the eight OpenAI models: it counts the tokens used for instruction generation, plus the tokens used to score 250 generated instructions on ten validation pairs with InstructGPT, then multiplies by the API rates of 1 September 2022. Those rates, per 1,000 tokens, were 0.0004 US dollars for ada, 0.0005 for babbage, 0.0020 for curie and 0.0200 for davinci.

You would expect the cheap small models to give the cheap search. The opposite happened. The paper’s word: “Counter-intuitively, smaller models are more expensive.” The biggest line item is scoring, and it grows with the length of each instruction. Small models that were not trained on human instructions write long ones, often hitting the 50-token cap. Larger, human-aligned models write short, tight instructions, so scoring them is cheap.

The symptom: your bill is high though you chose a cheap proposer. The measurement: the accuracy and cost frontier of Figure 11 and the accuracy and length frontier of Figure 12. The fix: use the larger, instruction-trained model as the proposer. The authors recommend that whenever possible.

Instructions as context condensers

Few-shot prompting puts several worked examples in front of every question. That is a lot of tokens on every call. A zero-shot instruction says the same thing in one line. The paper calls APE instructions context condensers: they squeeze what the examples teach into a short rule.

The search costs more up front than in-context learning, since you sample and score many candidates. But it is a one-time cost. The paper reports (Figure 13) that APE instructions cut prompt tokens by up to an order of magnitude, and that they can be up to five times more efficient than five in-context examples at similar accuracy. Move the slider to see the trade.

When does the search pay off

Two lines count the prompt tokens spent so far. The few-shot line rises steeply. The APE line starts high, because of the search, then rises slowly. Slide the number of queries.

1,000

Illustrative arithmetic, not the paper’s measurement: five demonstrations of 30 tokens each give 150 tokens per call, against a 30-token instruction (5 times fewer, the paper’s best case). The search scores 250 instructions on 10 pairs of 70 tokens each (175,000 tokens) and spends about 57,500 more on proposals. The price of 0.0200 dollars per 1,000 tokens is the paper’s davinci rate of September 2022.

With these toy numbers each call saves 120 prompt tokens, and the search costs about 232,500 tokens, so the break-even is near 1,940 queries. A prompt that serves a few dozen calls is not worth searching for. A prompt inside a product that serves millions is.

What APE cannot do

The paper is honest about its edges, and a few more follow from its numbers.

The definition of prompt engineering matters, too. The authors define it as optimising the language in a prompt. It does not cover chaining several calls or giving the model tools. APE solves a smaller problem than a whole agent system, and solves it well.

Worked cost arithmetic

Score 250 candidates on 10 pairs. Say each pair is 40 tokens of question and answer. With a 50-token instruction, each scoring call is about 90 tokens, so the total is 250 × 10 × 90 = 225,000 tokens. With a 15-token instruction, each call is about 55 tokens and the total is 137,500. A tighter instruction cuts the scoring bill by about 39%, and it does so for every candidate in the pool. These numbers are our illustration of the paper’s argument, not its measurements.

Now the price. At the September 2022 davinci rate of 0.0200 dollars per 1,000 tokens, 225,000 tokens cost 4.50 dollars. The ada rate is 0.0004, fifty times lower per token. Price per token is not the whole story. The paper found that smaller proposers cost more overall, because their longer instructions inflate the scoring bill. The expensive model in the loop is the target that does the scoring, so the proposer’s job is to keep its instructions short.

The failure mode: spending the search on a prompt that is rarely used

The symptom: the search cost is larger than the saving. The measurement: divide the one-time cost by the saving per call, as the device does. The fix: do not search for a prompt that will serve only dozens of calls. Search where the prompt sits inside something that runs thousands of times, or where accuracy matters more than the token bill.

Why were the smaller proposers more expensive in the paper’s cost analysis?

Chapter 9

Field Guide: APE on One Page

Keep the numbers, the terms, the code and a short checklist for deciding when to search for a prompt

Here is the whole method in one paragraph. You have a task shown by a few input and output pairs. A language model reads the pairs and writes dozens of candidate instructions (Chapter 2). The target model runs each one, and a score such as exact-match accuracy grades it (Chapter 3). A cheap multi-round filter drops weak candidates early (Chapter 4). The best instruction goes into your prompt. On 24 of 24 Instruction Induction tasks it matched or beat a human written one.

The numbers to remember

QuantityValueWhere in the paper
Pairs shown per task5Section 4.1
Default candidates sampled50; human level reached by 64Section 5.1, Figure 7 (Left)
Longest instruction in the cost study50 tokensAppendix D
Instruction Induction (24 tasks)APE ≥ human on 24; IQM 0.810 against 0.749Section 4.1, Figure 4
BIG-Bench Instruction Induction (21 tasks)APE ≥ human on 17Section 4.2, Table 6
Instruction plus examples against examples onlycomparable or better on 21 of 24Section 4.1, Figure 8
Zero-shot chain of thought, MultiArith78.7 to 82.0Section 4.3, Table 7
Zero-shot chain of thought, GSM8K40.7 to 43.0Section 4.3
TruthfulQA split100 train, 717 test, 38 categoriesSection 4.4
TruthfulQA both true and informativeover 40% against about 30% for the human promptSection 4.4, Figure 5
Rounds before iterative search stabilisesabout 3Section 5.3, Figure 6 (Right)
Prompt tokens saved against few-shotup to 5 times; up to an order of magnitudeAppendix D, Figure 13
Tasks at human level, early against tuned APE19 of 24 to 24 of 24Appendix F, Table 17

The terms

TermPlain meaning
ρOne instruction, the program being searched for.
Dtrain = {(Q, A)}The few input and output pairs that show the task.
[ρ; Q]The instruction joined to a question: the exact prompt the target model reads.
UThe pool of candidate instructions.
fexecExecution accuracy: 1 if the output matches the answer exactly, else 0.
log P(A | [ρ; Q])The log probability the model gives the true answer. Closer to 0 is better.
Forward modeThe blank is at the end of the meta prompt. Any left to right model works.
Reverse modeThe blank is inside the text. An infilling model is needed.
GreedyThe baseline: one model written instruction, no search.
IQMInterquartile mean: the average of the middle half of the task scores.

The core as code

This is our sketch of Algorithm 1 with the multi-stage filter. The authors’ own code is linked below.

import random, math

def f_exec(target, rho, pairs):
    """Execution accuracy: share of pairs the target gets exactly right."""
    hits = sum(target.complete(f"Instruction: {rho}\n\nInput: {q}\nOutput:").strip() == a
               for q, a in pairs)
    return hits / len(pairs)

def f_logp(target, rho, pairs):
    """Mean log P(A | [rho; Q]); the model scores the answer tokens, it does not write them."""
    return sum(target.logprob(prompt=f"Instruction: {rho}\n\nInput: {q}\nOutput:", completion=" " + a)
               for q, a in pairs) / len(pairs)

def ape(proposer, target, d_train, m=50, rounds=5, keep=0.5, f=f_exec):
    pool = propose(proposer, random.sample(d_train, 5), m=m)           # Chapter 2
    sums = {rho: 0.0 for rho in pool}; seen = 0
    chunks = split(d_train, rounds)                                     # disjoint subsets
    alive = list(pool)
    for chunk in chunks:                                                # Chapter 4
        for rho in alive:
            sums[rho] += f(target, rho, chunk) * len(chunk)
        seen += len(chunk)
        alive.sort(key=lambda r: sums[r], reverse=True)
        alive = alive[:max(2, math.ceil(len(alive) * keep))]            # top k percent
        # optional: alive += resample(proposer, alive)  (iterative Monte Carlo)
    return max(alive, key=lambda r: sums[r] / seen)                     # rho star

How to reproduce the method

  1. Collect the pairs. Gather 5 or more input and output pairs, and set aside held-out pairs for the final test.
  2. Choose a proposer and a template. Use a large, instruction-trained model. Start with forward mode unless you need the blank inside the text.
  3. Sample the pool. Draw about 50 candidates, each capped near 50 tokens.
  4. Pick the score. Use execution accuracy, with an invariant match where order does not matter. Use the log probability when answers are long text.
  5. Filter in stages. Score all candidates on a small subset, cut, and repeat on fresh subsets. Score the finalists on the full set.
  6. Test on held-out pairs. Read the winning instruction. Check it for tricks such as echoing the input.
  7. Search on the model you will run. Do not carry the instruction to a different model without searching again.

A checklist before you search

Mark the conditions that hold for your task. The read-out tells you how strong the case is.

Is a prompt search worth it?

Press each condition that is true for your task.

A rule of thumb built from Chapters 3 to 8, not a result from the paper.

Where it sits in the field

APE sits between hand-written prompts and gradient-tuned soft prompts. It searches discrete words with a black-box model, so it works through an API. The next lecture in this course covers LLMs as optimizers (Lecture 3), which takes the idea of searching over prompts further. The chain of thought result builds on Chain-of-Thought Prompting, and its reasoning data recipe echoes STaR.

Keep going

Credit and sources

“Large Language Models Are Human-Level Prompt Engineers” is by Yongchao Zhou, Andrei Ioan Muresanu, Ziwen Han, Keiran Paster, Silviu Pitis, Harris Chan and Jimmy Ba, of the University of Toronto and the Vector Institute. It appeared at ICLR 2023. Read the paper at arXiv 2211.01910. Their code is at github.com/keirp/automatic_prompt_engineer. The benchmark behind Chapter 5 is Instruction Induction by Honovich et al., and zero-shot chain of thought is Kojima et al. This lesson re-teaches the paper in our own words and devices. Any toy number is labelled as illustrative where it appears.

The takeaway. Treat the instruction as a program, let a model propose many versions, and let a score choose. Search turns an art of guessing into a measured choice.
Which sequence correctly lists APE’s main steps?

Now press Present or Teach and explain APE out loud, from memory: what the instruction is, how the proposer is asked, how the score is chosen, why the filter saves calls, and where the method breaks. Then go back to the search at the top, set the candidates to 1 and to 8, and explain why the best score moves.

Automatic Prompt Engineer
Read the paper · Back to Lecture 2, Context Evolution · Prompt engineering basics