Large Language Models as Optimizers

A language model can search for the best instruction by reading a scoreboard of its own past tries. Within six steps it found “Let’s do the math!”, which beats the famous “step by step” on GSM8K.

Tap the six instructions one by one and read how many of the 1,319 test questions each one answers right. Two of them were written by a language model that never saw a gradient. Then we build the method, piece by piece: the loop, the meta-prompt, the tests, the knobs and the limits.

You need a feel for what a prompt is (the text you give a model) and a little Python for the code. We build the rest from zero.

Paper: Chengrun Yang, Xuezhi Wang, Yifeng Lu, Hanxiao Liu, Quoc V. Le, Denny Zhou and Xinyun Chen (Google DeepMind), “Large Language Models as Optimizers”, arXiv 2309.03409; code. This is the reading for MIT MAS.S62 AI4AI, Lecture 3: LLMs as Optimizers. Every idea is re-taught here in our own words and devices.

Score an instruction

Numbers are the paper’s test accuracies on the 1,319 GSM8K test questions, with pre-trained PaLM 2-L answering and the instruction placed at the start of its answer (Table 1, Table 4 and Section 5.2.3 for 49.4; the 60.8 and 76.3 come from the one-step comparison in Section 5.3). The count of questions right is accuracy times 1,319, rounded.

Chapter 0

Searching When You Cannot Take a Slope

See why some problems give you only a score, and why a language model might still climb them

Picture a hiker on a foggy hill. She wants the highest point, but she cannot see more than a step away. So she does what hikers do: she feels the slope under her boots and walks uphill. The slope tells her which way to go, and how steep it is.

Now change the rules. A friend on the radio can tell her the height of any spot she names. But she cannot feel the ground. She can only say a spot and hear a number. How does she find the top?

The slope has a name: the gradient

The gradient is the slope, written as numbers. It points uphill and says how steep the climb is. Gradient descent is the hiker’s walk, run downhill on a loss (a number you want small). Almost all of deep learning runs on it.

Gradient descent needs three things. The knobs must be numbers, so that a tiny nudge means something. The score must be a smooth formula, so that a slope exists. And you must see inside the machine, so that the slope can be computed. The objective function is the name for the score you want to push up or down.

Three ways a prompt breaks those rules

Take the task of this paper: find the best instruction to put in front of a math question, such as “Let’s think step by step.” The score is the share of questions the model then answers right.

First, the knobs are words, not numbers. There is no tiny nudge from “step by step” to a slightly different instruction. Second, the score is a count. You run the model on 262 questions and count the right ones. No formula links the words to that count. Third, the model often sits behind an API. Text goes in. Text comes out. You cannot look inside.

So there is no gradient. Problems like this are called black-box or derivative-free optimization: you may ask for the score at a point, and nothing more. The old tools are random search, hill climbing and evolutionary algorithms (keep the best guesses, mutate them, repeat). Each one needs a hand-built rule for how to move, and the rule changes with every new problem.

The idea of OPRO

The paper by Yang and colleagues at Google DeepMind has a short answer. Let a language model be the move-maker. Write the problem in plain English. Paste in the past guesses with their scores. Ask for a new guess that scores higher. Score it, add it to the list, and ask again. The authors call this Optimization by PROmpting, or OPRO.

As a trade, in the form this site uses: OPRO finds instructions that score up to 8% higher than human-written ones on GSM8K, and up to 50% higher on Big-Bench Hard tasks, because the model reads a scoreboard of earlier tries and writes the next one in plain language. Both numbers come from the paper’s abstract.

Feel the difficulty first. In the device below, a hidden hill sits behind the fog. You may probe eight spots. Each probe returns one number. Try to end on the highest one.

Climb in the fog

Drag the teal line to a spot, then press Probe here. You see only the score, not the curve. After eight probes the hill is revealed.

50

Illustrative: a made-up curve with one tall peak and one lower decoy peak, the same on every visit. The scores are not from the paper. It only shows the situation: a score for a point, and no slope.

Most people probe the middle, then walk toward whichever side looked better. That is hill climbing, and it works until a decoy peak fools it. Notice what you did: you read the past probes and chose the next spot from them. OPRO asks a language model to do exactly that reading, with text.

One more point matters. OPRO never trains the language model. Its weights stay frozen. Only the text in the prompt changes from step to step. The “learning” lives in the list of past tries.

The road

The paper has a clean order, and this lesson follows it. First the method, then a toy test, then the real target, then the knobs and the limits.

  1. The loop: one OPRO step, from prompt to optimizer to scorer and back.
  2. The meta-prompt: the three parts of the one prompt that holds everything.
  3. Warm-up: fitting a line with a language model, and why eight guesses per step.
  4. Prompt optimization: the scorer, the optimizer and the three places an instruction can go.
  5. Results: GSM8K, Big-Bench Hard, and the strange prompts that won.
  6. The knobs: order, scores, examples, batch size, temperature, starting point.
  7. Where it breaks: travelling-salesman tours, failure cases, overfitting.
  8. Field guide: numbers, terms, a checklist and the core code.
Why can gradient descent not be used directly to find the best instruction for a model behind an API?

Chapter 1

The Loop: Propose, Score, Remember

Follow one OPRO step from the prompt, through the optimizer and the scorer, and back into the prompt

Imagine a baking contest that runs all week. Each morning you read a board on the wall. It lists earlier cakes and the score the judge gave each, lowest at the top and best at the bottom. You bake eight new cakes. The judge scores them. You pin them on the board and go home.

Nobody tells you the recipe for a good cake. You read the board, notice what the best cakes share, and bake something a little better. That is OPRO in one picture. The baker is a language model. The board is part of its prompt.

Four named parts

The optimizer LLM is the baker: the model that writes new candidate solutions. The scorer (the paper also says evaluator) is the judge: code or a model that returns the objective value for one candidate. A solution-score pair is one candidate plus its number.

The meta-prompt is the prompt sent to the optimizer. It holds the problem in words and the board of pairs. The board is called the optimization trajectory: the path of past tries. Figure 2 of the paper draws these four parts in a ring, and so does the device below.

One step, in five moves

  1. Build the meta-prompt. Write the task in words. Add the best solution-score pairs so far, lowest score first. For prompt tuning, add three example questions too.
  2. Propose. Send the meta-prompt to the optimizer LLM. Do it 8 times at temperature 1.0 (the paper’s default). Temperature is a dial on randomness: at 0 the model always picks its likeliest next word, and at 1.0 it samples more freely, so eight replies differ. Each reply is one new candidate.
  3. Score. Run each of the 8 candidates through the objective. For a prompt, that means asking the scorer model the training questions and counting the right answers.
  4. Remember. Add the 8 new pairs to the trajectory. Keep only the best 20, because the prompt must fit the model’s context window (its input limit).
  5. Repeat, until the optimizer cannot find a better solution or a step limit is reached. For prompts the paper’s default is 200 steps.

Look at the data flow. In: one long text, the meta-prompt, built fresh every step. Out: eight short strings. The score for each string comes from a different place than the optimizer. This split matters. The optimizer never judges its own work. A number from the real objective does.

Walk the ring

Press Next stage. A dot travels along the arrow that is active. Watch the count of pairs on the board: it grows by 8 per loop until it hits 20.

The 5 starting pairs match the paper’s linear regression set-up (Section 3.1); 8 new solutions per step and the best 20 kept match Section 5.1. Everything else here is a picture of the data flow, not a run.

A worked count

Follow the board over three loops of the line-fit problem. It starts with 5 pairs. Loop 1 adds 8 scored pairs: 13 on the board, all shown. Loop 2 adds 8 more: 21 pairs exist, but the prompt keeps only the best 20, so the single worst pair drops out. Loop 3 adds 8 and drops 8: still 20 on the board. From loop 3 on, every step replaces the 8 weakest rows with the 8 new ones, if the new ones are better. This is why the board slowly fills with similar good rows, and why the later steps feel like refinement.

The run ends when the optimizer cannot find a better solution, or when the step limit is reached. A flat board is a signal. Either the search has converged, or it has stalled, and only the score curve can tell you which.

What one step costs

A step has two bills. The optimizer bill is 8 calls with one long prompt. The scorer bill is larger. For GSM8K the paper scores each instruction on 3.5% of the 7,473 training questions, about 262 of them. So one step is about 8 × 262 = 2,096 scorer calls, and a 200-step run is about 419,000. This is our arithmetic from the paper’s settings, not a number the paper prints.

That cost shapes every design choice later. Few steps matter more than long prompts. A small training slice is enough. And the scorer should be cheap.

When the loop stalls

Symptom: the best score stays flat for twenty steps. Measurement: the same candidates, or near copies, keep coming back, and the curve of per-step averages does not move. Fix: raise the temperature or ask for more candidates per step. Chapter 6 tests both. The paper also notes that the optimizer sometimes repeats an old solution even when told to give a new one (Appendix A), so a real implementation checks for repeats before it spends scorer calls.

In one OPRO step with the paper’s defaults, what does the optimizer receive and what does it return?

Chapter 2

The Meta-Prompt Is the Whole Algorithm

Open the one prompt that carries the scoreboard, the task and the instructions to the optimizer

You hire a coach by letter. The letter must do three jobs. It must show past training plans with the results they got. It must say what a plan looks like and what you want. And it must say how to write the reply. Leave one out and you get a useless answer.

The meta-prompt is that letter. In OPRO it is the entire algorithm. There is no update rule, no learning rate and no search code that picks the next point. The optimizer LLM reads the letter, and what it writes is the next step.

Three parts, three jobs

Section 2.2 of the paper names two essential parts. Section 4.2 adds a third for prompt tuning. We colour them the same way in every device on this page.

The optimization trajectory. Past candidates with their scores, sorted lowest first, so the best sits at the bottom. This is the memory of the search.

The problem description. What is being optimized, in words. For prompt tuning it also holds a few exemplars: real training questions with the right answer. The paper uses three, picked at random each step. An exemplar shows the task, and it shows where the new instruction will be placed.

The meta-instructions. Orders to the optimizer: write a new text, different from the old ones, with a score as high as possible, inside square brackets. They can add a taste, such as “the instruction should be concise and generally applicable.” The paper calls this an informal regulariser (a gentle push toward the kind of answer you want).

Choose a part below. The text is the paper’s own Figure 3 for GSM8K, shortened where the paper itself shortens it.

Open the letter

Pick a part to light it up and dim the rest. Then read what that part does for the optimizer.

Text from Figure 3 of the paper (PaLM 2-L-IT optimizer, GSM8K). The two instructions with scores 61 and 63 are the paper’s; the rows it elides are marked the same way it marks them. Scores in the board are whole numbers, a choice tested in Chapter 6.

The same thing as a formula

Write it down once, so every symbol has a name. Let s be a candidate solution and f(s) its score. After t steps the history is every pair so far. The meta-prompt keeps the best 20, sorted, and glues on the other two parts.

Mt
The meta-prompt at step t, a single block of text.
d
The problem description in words. It stays the same every step.
sort↑(top20(Ht))
Ht is every (s, f(s)) pair tried so far. Keep the 20 best, then sort them from the lowest score to the highest.
Et
The exemplars: 3 training questions with answers, drawn again each step.
m
The meta-instructions: write something new, score as high as possible, use square brackets.
s ~ LLMτ(Mt)
One new candidate, drawn by the optimizer at temperature τ (1.0 by default). Draw it 8 times per step.

Illustrative worked step (board rows from the paper’s Figure 3 example): board = {61: “Let’s figure it out!”, 63: “Let’s solve the problem.”} → the optimizer writes [Let’s think carefully about the problem and solve it together.] → the scorer returns 63.2 → the board shows 63.

The proposed instruction and its 63.2 are the paper’s own step-2 leap in the GSM8K run. The paper does not say that this exact board produced it, so read the step as a picture of the mechanism. The board rounds 63.2 to 63, so it ties the old best. The next meta-prompt contains it, and the optimizer now has three wordings to compare.

Why each choice is there

Lowest first, because language models lean on the end of a prompt. The paper ties this to recency bias, the habit of copying whatever sits nearest the answer. Putting the best candidates last makes the model build on them. Scores are in the prompt because the model needs to see how much better one wording is. Exemplars are in because they show the task and the slot where the instruction lands. Chapter 6 measures all three.

Square brackets are plain engineering. The reply is free text, and the code must cut the candidate out of it. A fixed marker makes the cut easy. Symptom of a missing marker: the parser returns half a sentence of chatter. Measurement: count how many of the 8 replies parse. Fix: say the format in the meta-instructions and ask again.

The meta-prompt shows past instructions sorted from lowest to highest score. What reason does the paper give?

Chapter 3

Warm-Up: Fitting a Line by Asking

Watch the loop fit two numbers, and learn why each step asks for eight guesses and not one

Before it tunes prompts, the paper tests the loop on a problem where we know the answer. A shop owner has 50 days of sales and wants the straight line that fits them best. The line has two numbers to find. Can a language model find them just by reading earlier guesses?

The problem in plain words

Linear regression fits a line y = w x + b through points. The slope w says how fast y climbs as x grows. The intercept b says where the line starts. A pair (w, b) is one candidate line. The objective value is how far the points sit from that line; think of it as the average squared miss. Smaller is better, and the best pair is the global optimum.

The set-up (Section 3.1): hidden true values wtrue and btrue; 50 points with x from 1 to 50 and standard Gaussian noise added to y; five random starting pairs, each number between 10 and 20. The meta-prompt shows the best 20 pairs with their values, and asks for a new pair with a lower value.

One choice is easy to miss. The formula of the objective is not in the prompt. This is on purpose. The paper notes that a model can often compute the answer straight from the formula, which would hide what is being tested. So the optimizer sees only pairs and numbers, exactly as it would for a prompt. That is black-box optimization.

What the model does with the board

The paper gives a clean example. Suppose the board shows (8, 7), (8, 6), (8, 5) with values going down. The best model, gpt-4, is the most likely to propose (8, 4). It saw a trend and continued it. Nobody wrote a rule for that. It read the pattern in text.

A second thing is more subtle. Not every guess is good, and a bad row in the prompt can mislead the next answer. In-context learning (learning from examples inside the prompt) is sensitive to what the prompt holds. So the paper asks for several guesses per step. It uses 8. One bad draw then does less harm, and the model can try several directions at once. The authors compare this to a mini-batch in stochastic gradient descent, which averages out noise.

Play with it. The device below is a stand-in, not a language model. It follows the trend between the two best rows, adds noise that grows with temperature, and sometimes copies the best row or ignores the board. Turn the temperature and watch how the batch of 8 behaves.

Propose eight lines

Each dot is one (w, b) pair that was scored. The blue star is the true line. The dashed box is where the five starting pairs begin. Press Step to ask for 8 new pairs.

1.0

Illustrative: the proposer is a few lines of code written for this page, not a language model, and it only imitates the behaviours the paper reports (follow the trend, repeat at low temperature, wander at high temperature). The data are 50 points with true slope 25, true intercept 23 and noise of 1, the same on every visit. “Reached” means the loss is within 6 of the best-fit line’s loss.

What Table 2 shows

The paper ran text-bison, gpt-3.5-turbo and gpt-4 as the optimizer, five runs each, at temperature 1.0, on seven choices of the true pair. Two facts stand out. First, the models need far fewer probes than trying every pair. They do real black-box optimization. Second, the further the true pair sits from the start box, the more they struggle. With the true pair inside the start region (15, 14), the three models need about 4 to 8 steps. With it far outside, (36, −1), they need about 36 to 50.

In the first case gpt-4 explored 17.2 distinct pairs on average. The other two explored 36.0 and 40.0. Across all seven rows gpt-4 explored the fewest. It is the best at proposing a sensible next step from the history.

When it gets stuck

Symptom: the run stops improving at a point that is neither the global nor a local best. Measurement: look at the top rows of the board. In Appendix A the paper finds two causes. All the best pairs share one w, so the model keeps changing only b. Or the best pairs sit on opposite sides of the answer, for example all slopes too small and all intercepts too big, so any single-number change looks worse. Fix: show more past pairs, and draw more guesses per step so some of them explore.

Why does each OPRO step draw 8 candidates rather than one?

Chapter 4

The Real Target: Optimizing a Prompt

Turn an instruction into a score, and split the work between an optimizer and a scorer

Two people share a job. A writer drafts a sentence of advice for a maths exam. A student sits the exam with that sentence printed at the top. The writer never sits the exam. The student never writes advice. The writer only learns how the advice did, as a mark.

That is prompt optimization in OPRO. The writer is the optimizer LLM. The student is the scorer LLM. The advice is the instruction, a short text placed with each question. The mark is the share of questions the student gets right.

What is being searched

The search space is all possible sentences. That is huge and discrete. The objective is the scorer’s training accuracy on a small set of questions with known answers. The method needs a training set, but not a big one. For GSM8K the paper uses a random 3.5% of the 7,473 training questions (about 262), the same ones at every step. For Big-Bench Hard it uses 20% of each task’s examples. After the search ends, the best instructions are scored on the full test set: 1,319 questions for GSM8K. That number is test accuracy, and it is the one we trust.

Two benchmarks matter here. GSM8K is a set of grade-school maths word problems. Big-Bench Hard (BBH) is 23 hard tasks that range from sorting words to judging a movie recommendation. A zero-shot instruction means the scorer gets the instruction and the question, with no worked examples.

Where the instruction goes

Where you put the sentence changes what the scorer does with it. The paper tests three places, and the one you can use depends on the scorer.

PositionWhere the instruction goesUsed with
Q_beginBefore the questiontext-bison (already instruction-tuned)
Q_endAfter the questiontext-bison
A_beginAt the start of the answerPre-trained PaLM 2-L, which only continues Q/A text

A pre-trained model has only learned to continue text. It has not been tuned to follow orders. So the prompt looks like a page of questions and answers, and the instruction becomes the first words of the answer, as if the answer had started that way. An instruction-tuned model can take the sentence as an order. Try each position on the paper’s own test question.

Build the scorer prompt

Pick a position and an instruction. The box shows the text the scorer receives. The instruction is highlighted in teal.

The formats follow Figures 14 to 16 of the paper, using its GSM8K test question about Janet’s ducks. For instruction-tuned scorers the paper drops the Q/A pattern (Figures 17 and 18); we keep it here so the three positions are easy to compare. Word counts are computed live.

Why is a slice of 262 questions enough? The goal is not to learn the questions. It is to rank candidates, and a ranking needs only a steady ruler. A fixed random slice gives the same ruler to every candidate. The final test on all 1,319 questions then checks that the ranking carried over.

The data flow of one candidate

Follow one instruction through the scorer. In: the instruction plus one training question, glued by the position rule. Out: the scorer’s answer text. The scorer runs at temperature 0, so it always picks its most likely next word and the same prompt gives the same answer. Compare the final number with the known answer: right is 1, wrong is 0. Do it for all ~262 questions and average. Multiply by 100 and round: that integer is the score on the board.

Why temperature 0 here, and 1.0 for the optimizer? The scorer must be a steady ruler. The optimizer must be creative. The two jobs want opposite settings, which is a good reason to keep them as two roles.

A worked score

Say the instruction is “Let’s do the math!” and the slice has 262 questions. The scorer writes an answer for each at temperature 0. A small script pulls the last number out of each answer and compares it with the gold answer. Suppose 191 match. Then 191 / 262 = 0.729, so the accuracy is 72.9, and the board line reads 73. (The numbers are illustrative; the paper does not list per-question counts.) The 8 candidates of one step each get such a number.

Notice what the optimizer never sees: which questions were missed. It sees 73 and nothing else. The paper tried feeding wrong answers back into the meta-prompt, and the results were similar, so a bare number is what the loop runs on.

The mark is noisy

Symptom: two runs of the same instruction on different question slices give marks a few points apart. Measurement: if the true accuracy is 70% and you score 262 questions, the standard error is about √(0.7 × 0.3 / 262) = 2.8 points. This is our arithmetic, not a figure from the paper. Fix: the paper scores every candidate on the same fixed slice, so candidates are compared on equal ground. It also reads a leap of a couple of points on the curve with care.

Why does the paper put the instruction at A_begin when the scorer is pre-trained PaLM 2-L?

Chapter 5

What the Search Found

Read the GSM8K curve, the Big-Bench Hard bars and the odd prompts that came out of the loop

You watch a student improve over a term. Early on she scores 60%. A few weeks later she scores 78%. Then she creeps up for months. The shape tells a story: a quick climb, then a slow, flat crawl. The first figure in the paper has exactly that shape, and it is worth reading closely.

One run, step by step

This is Figure 1(a). The scorer is pre-trained PaLM 2-L. The optimizer is PaLM 2-L-IT (the instruction-tuned version). The start is “Let’s solve the problem.”, which scores 60.5 on the training slice. The paper lists the leaps in the text. We show them below as dots. The curve between the dots is not given, so we do not draw it.

Replay the search

Drag to move along the real leaps from the paper’s GSM8K run. The step axis is stretched near the start, because most leaps come early.

0

Step numbers, instructions and training accuracies are the ones the paper lists in Section 5.2.1 for Figure 1(a). Training accuracy is on the 3.5% training slice. The dashed teal line is the 71.8 test accuracy of “Let’s think step by step.”, drawn for scale: it is a test number set beside training numbers.

Why does the curve move in leaps? The paper gives a careful reason. A leap does not always mean one better instruction was found. After a much better one appears, the board slowly drops weaker rows, and the optimizer starts to write copies of the good one. Several steps later, all eight candidates are good. That is when the average jumps.

What Table 1 shows

Table 1 is the headline. Every row is an instruction and its test accuracy on GSM8K, with pre-trained PaLM 2-L answering. All four optimizers beat the human baseline:

SourceInstructionTest accuracy
Kojima et al. (human)Let’s think step by step.71.8
Zhou et al. (APE)Let’s work this out in a step by step way to be sure we have the right answer.58.8
No instruction(empty string)34.0
OPRO, PaLM 2-L-ITTake a deep breath and work on this problem step-by-step.80.2
OPRO, PaLM 2-LBreak this down.79.9
OPRO, gpt-3.5-turboA little bit of arithmetic and a logical approach will help us quickly arrive at the solution to this problem.78.5
OPRO, gpt-4Let’s combine our numerical command and clear thinking to quickly and accurately decipher the answer.74.5

Three readings. First, the gap to the empty string is large: 34.0 to 80.2. The instruction matters a great deal. Second, the best OPRO instruction is 8.4 points above the best human one. Third, the optimizers write in very different styles. PaLM 2-L-IT and PaLM 2-L write short lines. The GPT models write long, detailed ones. Most winning prompts do not even contain “step by step”.

One caution of ours. The test set has 1,319 questions. At 80% accuracy the standard error is about 1.1 points. So 80.2 against 79.9 is a tie. Only the larger gaps tell a story.

Figure 5 shows this as 23 bars per panel, one per BBH task. Each bar is the OPRO instruction’s accuracy minus a baseline’s. A bar above zero is a win. Read the panels in pairs: one against “Let’s think step by step.”, one against the empty string. A task that wins in both panels is a safe win. Per-task accuracies are in Table 7 of the paper, split as training, test and overall, because each task is cut 20% for search and 80% for testing.

A second run: ruin_names

The paper traces one BBH task, ruin_names, in which the model must pick the funniest edit of an artist or movie name. The scorer is text-bison, the optimizer PaLM 2-L-IT, and the start is the empty string at 64.0 training accuracy. At step 1 the optimizer writes “Consider the following when editing artist or movie names humorously:” and it scores 72.0. At step 18 it writes that you can change letters or add similar-sounding words: 80.0. At step 38 it adds worked examples, such as The Police becoming The Polite: 82.0. The same story as GSM8K, in a task with no maths: first a plain frame, then a method, then examples. The paper adds that all three are semantically close, yet each paraphrase gives a real gain.

Big-Bench Hard, and one oddity

On the 23 BBH tasks the paper starts from the empty string and optimizes each task alone. With the PaLM 2-L scorer, OPRO beats “Let’s think step by step.” by over 5 points on 19 of 23 tasks. With text-bison it does so on 15 of 23. Against the empty start it wins by over 5 points on 20 of 23 and 15 of 23. The abstract’s “up to 50%” refers to the largest gain among these tasks.

Now the oddity. In Section 5.2.3, “Let’s think step by step.” scores 71.8. “Let’s solve the problem together.” scores 60.5. Their merge, “Let’s work together to solve this problem step by step.”, scores 49.4. Merging two good prompts made a bad one. Symptom: a wording that reads fine to a human scores far lower. Measurement: score it. Fix: never trust meaning; score every candidate. This is the reason the loop asks for eight guesses and measures all of them.

Last, transfer. Instructions found on GSM8K were also tried on two other maths sets, MultiArith and AQuA. They beat the baselines there too (Table 6). The wording learned something about maths problems in general, not only about the 262 training questions.

Why is the combined prompt “Let’s work together to solve this problem step by step.” (49.4) a warning for the method?

Chapter 6

The Knobs, Tested One at a Time

Change the order, the scores, the batch and the temperature, and see which choices carry the method

A sound engineer has a mixing desk with six dials. She wants to know which dials matter. So she turns one at a time and listens. If the sound barely changes, the dial is not important. If it falls apart, that dial is carrying the mix.

Section 5.3 of the paper does this for OPRO. It uses text-bison as the scorer and PaLM 2-L as the optimizer, and it tests on two tasks: GSM8K (maths) and BBH sports_understanding (not maths). Every curve is the average of 3 repeated runs. Here is each dial, with the result.

DialOptions testedDefaultWhat the paper found
Order of past instructionslow to high, high to low, randomlow to highDefault converged faster and ended higher. Likely recency bias.
Scores shown100 buckets, 20 buckets, none100 buckets (whole numbers)Scores help the optimizer see quality gaps.
Exemplars3, 10, none3Needed. More than a few do not help and can distract.
Instructions per step1, 2, 4, 8, 1688 was best at a fixed budget of evaluated instructions.
Optimizer temperature0, 0.5, 1.0, 1.5, 2.01.01.0 was best. Low was flat. High was unsteady.
Starting instructionempty, short phrases, “step by step”empty or “Let’s solve the problem.”Little effect with text-bison. Large effect with pre-trained PaLM 2-L.

How to read these curves

Each curve in Figures 7 to 10 is the average of 3 optimization runs, drawn as dots with a shaded band for the spread. Two curves are different only if their bands separate. A curve that rises fast and ends high is good. A flat curve means the search is stuck. A curve that bounces means the search forgets what it learned.

The starting point is the dial most tied to the model. With the instruction-tuned text-bison as scorer, the empty string, “Solve the following problem.” and a pair of phrases all reached about the same accuracy, with similar wording. With pre-trained PaLM 2-L the start mattered a lot. Starting from “Let’s think step by step.” beat both other starts all through the run. Starting from the empty string needed more steps, because the board held weak rows that took time to push out. The authors list faster convergence from weak starts as future work.

The exemplar dial deserves one more line. With no exemplars, the optimizer does not know the task or where the instruction lands. With 10, the examples dominate the prompt and crowd out the board. Three is enough to say what the task looks like and still leave room for the history.

Two dials that pull against each other

Temperature and batch size are the best-explained pair, because both manage the same tension: exploitation (stay near what works) against exploration (try something new). Temperature is the sharper dial.

Recall that temperature rescales the model’s word probabilities before it draws a word. Low temperature makes the likeliest word win nearly every time. So at 0 and 0.5 the paper saw the optimizer “stuck at the same instruction for tens of steps”: flat curves. At 1.5 and 2.0 it did the opposite. It ignored the board and wandered, so the curve had no steady climb. Temperature 1.0 sat between.

Batch size trades quality for cost. Many guesses per step steady the search. But with a fixed budget of scorer calls, more guesses per step means fewer steps, and fewer chances to learn from the board. The paper found 8 balanced these.

The device below runs the stand-in optimizer from Chapter 3 on the line-fit problem, 40 times per setting. It is not a language model, but it reproduces the same two pressures. Choose a dial.

Turn one dial

Choose a dial. Each bar is the median number of steps to reach the optimum over 40 runs. A red mark means some runs never got there in 60 steps.

Illustrative: the stand-in proposer of Chapter 3 on the 50-point line fit (true slope 25, intercept 23), 40 seeded runs per setting, capped at 60 steps. It is a toy, so its numbers are not the paper’s. In particular the paper compares batch sizes at an equal budget of evaluated instructions, which this simple count does not do.

The comparison that justifies the loop

The most important ablation asks: does the loop matter, or would a single big batch do? The authors made the optimizer write 50 instructions in one step, with only the task examples and the start instruction in the prompt, no trajectory. On GSM8K the best of the 50 was still the start, “Let’s solve the problem”: 64.4 training and 60.8 test. OPRO’s loop found “Let’s do the math!” at step 5 (the appendix says the 5th step; the main text says step 6) (the main text says step 6, the appendix says 5th step): 78.2 training and 76.3 test, with only 8 candidates per step. On sports_understanding the best of 50 got 84.0 train and 80.0 test. OPRO at step 4 got 88.0 and 84.5.

So the history is the engine. Take away the board and fifty guesses do worse than a few dozen guided ones.

Against its neighbours

EvoPrompt (Guo et al.) is a contemporary method that asks the model to cross over and mutate two prompts. Figure 12 compares. On GSM8K, with simple starts, both EvoPrompt versions got worse while OPRO kept climbing. The paper’s explanation: EvoPrompt sees no exemplars, so it does not know the task. When both start from task-specific prompts on sports_understanding, the gap shrinks. Two lessons follow. The trajectory with scores gives more information than a pair of parents. And the exemplars matter.

With the optimizer at temperature 0 the paper saw flat curves. What is the cause?

Chapter 7

Where It Breaks

Find the size, the landscape and the habits at which an LLM optimizer stops being useful

A courier must visit ten towns once each and drive home. Which order gives the shortest drive? With ten towns there are millions of orders. With fifty there are more than anyone can check. This is the Traveling Salesman Problem (TSP), the classic test for combinatorial optimization. The paper uses it as its second warm-up, and it is where OPRO’s limits show most clearly.

The set-up

Each problem has n towns with random coordinates in [−100, 100]. OPRO starts from 5 random tours and writes 8 new tours per step. The meta-prompt lists tours with their lengths, shortest last. To judge a result, the authors use the Gurobi solver (a commercial exact solver) as the oracle. The optimality gap is how much longer a tour is than the oracle’s: (tour − oracle) / oracle.

Two classic hand-made heuristics are the baseline. Nearest Neighbor (NN) always drives to the closest unvisited town. It is fast, but it ignores the long drive home at the end. Farthest Insertion (FI) grows a tour by adding the town whose cheapest insertion is the most expensive, so the far-out towns go in first. FI is much better than NN.

Choose a size. The bars are the paper’s Table 3, with five problems per size.

Grow the tour

Pick the number of towns. A shorter bar is a better tour. Bar lengths use a square-root scale, because the gaps run from 0 to 220.

All values are Table 3 of the paper: mean optimality gap in percent over 5 problems per size. Steps to reach the optimum are quoted from the same table for the runs that succeeded.

What the table says

At 10 towns, every LLM found the optimum on all five problems, and gpt-4 needed about 4 times fewer steps than the others (9.6 against 40.4 and 46.8 on average). At 15 and 20 towns gpt-4 stays close to optimal, with gaps of 0.2% and 1.4%. At 50 towns it breaks down: text-bison reaches a gap of 219.8% and gpt-3.5-turbo 133.0%. Only gpt-4 stays comparable to farthest insertion, with 11.0% against 9.8%. No model found the exact optimum for any 50-town problem.

The authors say plainly what this is and is not. OPRO is not trying to beat gradient-based methods or a specialised solver. The point is that an LLM can optimise different objectives by prompting alone, and match a heuristic on a small problem. The result is a proof of concept, and the line between small and large is sharp.

Four ways it fails

Appendix A lists failure cases, and each one teaches a design rule.

  1. It invents numbers. Symptom: the model writes “the function value at (5, 3) is 15” when the true value is different. Measurement: recompute it. Fix: never let the model score its own work; use code or a tool.
  2. It repeats old answers. Even when told “give a pair different from all above”, it sometimes returns one already on the board, often while saying it won’t. Fix: filter repeats before scoring. The paper notes that a model that explicitly compares its new pair with the old ones almost never repeats.
  3. It stalls on a bad row set. Covered in Chapter 3: all best rows share one value, or point in opposite directions. More past rows and more guesses per step help.
  4. It gets lost in a bumpy landscape. On the Rosenbrock function with a = 20, whose best point is (20, 400) at the end of a narrow curved valley, runs often stop near (0, 0). From there the model sees only a value of 400 that is lower than before, and it cannot follow the narrow valley uphill. Classic optimizers have the same trouble on this function.

Limits for prompt optimization

The conclusion names two. The optimizer does not use error cases well: the authors put wrongly answered training questions into the meta-prompt, and results stayed similar. A bare accuracy number tells the model that it lost, not why. And the method needs a training set, at least tens of examples, so that the prompt does not fit them too closely.

Overfitting means the prompt does better on the training questions than on new ones. It is real here: training accuracy is often 5 to 20 points above test accuracy (Tables 7 and 10). The paper's check (Figure 11) is hopeful. With a held-out validation set of equal size, validation accuracy rises and falls with training accuracy, so picking the highest training score still picks a good prompt. Symptom: a large train-test gap. Measurement: hold out data and compare. Fix: a larger training slice and early stopping.

On 50-town TSP problems, which statement matches Table 3?

Chapter 8

Field Guide

Keep the numbers, the terms, the checklist and the core code on one page

You can now explain the paper from memory. OPRO turns a language model into the move-maker of a search. It needs a score for each guess, and it needs the guesses to be text. Everything else is the care taken in the meta-prompt and the settings around it.

The one-paragraph summary

Optimization by PROmpting repeats one step. Build a meta-prompt from the task in words, the best 20 solution-score pairs sorted lowest first, and (for prompt tuning) three random examples. Ask the optimizer LLM for 8 new solutions at temperature 1.0. Score each with the real objective, which for a prompt means a scorer model answering about 262 training questions at temperature 0. Add the pairs to the board and repeat for up to 200 steps. The model is never trained. On GSM8K it found an instruction that scores 80.2% on the test set, against 71.8% for the best human-written one. On Big-Bench Hard it beat “Let’s think step by step.” by over 5 points on 19 of 23 tasks. It fails when the problem grows (50-town tours), when the landscape is bumpy, and when the training slice is too small.

The numbers that matter

WhatNumberWhy it matters
Candidates per step8 (1, 2, 4, 8, 16 tested)Steadies the search
Pairs kept in the meta-promptbest 20; 3 exemplarsFits the context window
Optimizer temperature1.0 default; scorer 0Explore, but measure steadily
Steps200 default; 6 reached 78.2 trainMost gain comes early
GSM8K training slice3.5% of 7,473 (about 262)Cheap scoring is enough
GSM8K test, best human71.8 (“Let’s think step by step.”)The bar to beat
GSM8K test, OPRO best80.2 (“Take a deep breath…”)+8.4 points
GSM8K test, empty string34.0Instructions matter
Merged human prompts71.8 and 60.5 merge into 49.4Always score candidates
One-step baseline (50 at once)60.8 test against 76.3 for the loopThe history is the engine
BBH wins over “step by step” (>5 pts)19 of 23 (PaLM 2-L); 15 of 23 (text-bison)Not only maths
TSP, 50 towns, gapgpt-4 11.0%; FI 9.8%; text-bison 219.8%Scale limit
Train over test accuracyoften 5 to 20 pointsOverfitting is real

The terms

TermMeaning
Optimizer LLMThe model that writes new candidates from the meta-prompt.
Scorer LLMThe model whose accuracy is the score; it answers questions with the candidate instruction in place.
Meta-promptThe optimizer’s input: task, scored trajectory, exemplars, orders.
TrajectoryThe sorted list of past solutions with scores.
ExemplarA training question with its answer, shown in the meta-prompt.
Q_begin, Q_end, A_beginWhere the instruction sits: before the question, after it, or at the start of the answer.
Black-box optimizationSearch where you can read a score but not a slope.
Optimality gapHow much longer a tour is than the best possible, as a fraction of the best.
Exploration, exploitationTrying something new, against refining what works.

Will it fit your problem?

These are our rules of thumb, built from the paper’s limits. Toggle each one that is true for your task.

Check the fit

Each button is a condition. Press it when it holds for your task.

A teaching aid, not a test from the paper. The five conditions come from Sections 3 to 5 and Appendix A: it needs a score, a text-sized candidate, a cheap scorer, a training set of at least tens, and a problem within the model’s reach.

The core as code

This is a sketch of the whole method. optimizer and llm stand for whatever model API you use, and describe returns the task text with 3 fresh training examples. It follows the settings above.

pythonimport re

def make_scorer(llm, train):                       # train = [(question, gold_answer), ...] about 262 of them
    def score(instruction):
        right = 0
        for q, gold in train:
            out = llm(f"Q: {q}\nA: {instruction}", temperature=0)   # A_begin; greedy, so the ruler is steady
            right += last_number(out) == gold
        return 100 * right / len(train)
    return score

def opro(score, describe, optimizer, start, steps=200, n_new=8, keep=20, temp=1.0):
    board = {s: round(score(s)) for s in start}      # solution -> whole-number score
    for step in range(steps):
        top = sorted(board.items(), key=lambda kv: kv[1])[-keep:]      # best 20, lowest score first
        rows = "\n\n".join(f"text:\n{s}\nscore:\n{v}" for s, v in top)
        meta = ("I have some texts along with their corresponding scores. The texts are arranged in "
                "ascending order based on their scores, where higher scores indicate better quality.\n\n"
                f"{rows}\n\n{describe()}\n\n"                          # task + 3 random exemplars
                "Write your new text that is different from the old ones and has a score as high as "
                "possible. Write the text in square brackets.")
        for _ in range(n_new):                                  # 8 draws at temperature 1.0
            m = re.search(r"\[(.+?)\]", optimizer(meta, temperature=temp), re.S)
            if m and m.group(1) not in board:                # skip repeats before paying for a score
                board[m.group(1)] = round(score(m.group(1)))
    return sorted(board.items(), key=lambda kv: kv[1])[-5:]   # then check the best on held-out data

Read it once, naming the chapter behind each line. The scorer is the greedy ruler of Chapter 4. The board keeps whole numbers and the best 20, lowest first, as Chapter 2 explains. The loop draws 8 candidates at temperature 1.0 (Chapters 3 and 6). The repeat check answers a failure case from Chapter 7. The last comment is the fix for overfitting.

Where this sits

The paper places itself among earlier work. Soft prompt tuning learns continuous vectors, but needs access to the model’s insides. Gradient-guided and reinforcement-learning searches over words need that access too, and so do not work with an API alone. Edit-based methods change one prompt at a time: APE asks for paraphrases of the best instruction, and APO asks the model for feedback on one old instruction. OPRO instead shows the model the whole scored history. It also sits near evolutionary prompting such as EvoPrompt, and near OptFormer, which trains a transformer on optimization histories, where OPRO trains nothing.

The paper's own closing question is the open one: richer feedback than a single accuracy number, so the optimizer can learn why a candidate failed.

Keep going

Credit

This lesson re-teaches “Large Language Models as Optimizers” by Chengrun Yang, Xuezhi Wang, Yifeng Lu, Hanxiao Liu, Quoc V. Le, Denny Zhou and Xinyun Chen, Google DeepMind (the first and last authors contributed equally). Read the original at arXiv 2309.03409; the authors’ code is at github.com/google-deepmind/opro. All numbers here come from the paper unless marked illustrative. The devices on the line fit and the sweep use a stand-in, written for this page, not the authors’ models.

The takeaway. A search does not need a gradient if it has a scoreboard and a model that can read it. OPRO puts the best past tries in front of a language model, in order, with their numbers, and asks for a better one. The method works because the board is honest (real scores from code), the batch is wide (8 guesses), the temperature is warm (1.0) and the history is visible. It stops working when the problem outgrows the prompt.
You want to improve a customer-support prompt. You have 200 labelled tickets, a script that counts correct replies, and a model API only. Which plan follows the paper?

Now press Teach and explain one OPRO step out loud, from memory: what is in the meta-prompt, what comes back, who gives the score, and what could go wrong. Then go back to the six instructions at the top, and say why the best one is not the longest or the cleverest.

Large Language Models as Optimizers (OPRO)
Read the paper · Code · Lecture 3 · Back to Gleams