MIPROv2

Picture a helper that answers a hard question in two steps: it writes a search query, then it writes the answer. Only the final answer is ever graded. MIPRO still rewrites the instructions and picks the worked examples for both steps. On one test, HotPotQA Conditional, it lifts the score from 6% to 23.3%.

Press a button to choose what the optimizer may change. Seven test programs change score, and the thin mark on each bar shows the score before tuning. Then we build, piece by piece, how a search can tune prompts it cannot grade one by one.

You need what a prompt is and what a language model does with one. We build the rest from zero.

Optimize the prompts

Ready

Every bar is a test score (higher is better), averaged over 5 runs and copied from Table 2 of the paper. Each task has its own metric, which Chapter 9 explains. The model that runs each program is Llama 3 8B. On HotPotQA, MIPRO, Bootstrap RS and Bayesian Bootstrap tie by the paper’s significance tests. Paper: arXiv:2406.11695, by Krista Opsahl-Ong, Michael J Ryan, Josh Purtell, David Broman, Christopher Potts, Matei Zaharia and Omar Khattab. Read as a Stanford CS 329Z Lecture 9 reading.

Chapter 0

Tuning a Pipeline You Cannot See Inside

See why one final score cannot tell you which prompt to fix, and what a prompt optimizer must do about it

Suppose you build a small helper that answers hard questions. One example: “Who directed the film whose success, with An American Tail and The Land Before Time, led Steven Spielberg to start his own animation studio?” One search is not enough. You must first find the film, then find its director.

So the helper works in two steps. Step one reads the question and writes a search query. A search engine returns a few passages. Step two reads the passages and the question, then writes the answer. Each step is one call to a language model, and each call has its own prompt: the text we send to the model.

We call this helper a language model program, or LM program. It is ordinary code that calls a language model several times. Each call is a module. Our program has two modules: the query writer and the answerer.

You grade only the final answer. The answer is right if it matches the known correct one exactly. Averaged over many questions, that gives one number, the metric. Say the program scores 21%. The paper’s Figure 1 starts from exactly this kind of program, a two-step multi-hop question answerer at 21% quality.

Now you want 40%. You open the prompt of step one and rewrite its instruction. The score moves to 24%. Was that your edit, or luck in which questions were drawn? And did step two gain anything? The only signal you have is the last number.

Two parts of a prompt you can change

The paper tunes two parts of every module’s prompt. The first is the instruction: the sentence that tells the model what to do, such as “Given the question, write a search query.” The second is a set of demonstrations, or demos: worked examples of an input and the output the module should give. A prompt with demos is called a few-shot prompt. A prompt with only an instruction is 0-shot.

Everything else stays fixed. The model’s weights never change. The optimizer only rewrites words.

Why this is harder than it sounds

If every module had its own answer key, this would be simple. You would grade the query writer on its queries, and the answerer on its answers. But nobody wrote the “correct” search query for each question. We call such a key a module-level label, and a program like ours has none. We have the correct final answer, and that is all.

We also cannot use gradients. A gradient is the slope that tells a neural network which way to nudge each weight. Hosted models give us text in and text out, with no weights and no slopes. The paper makes this a rule: it assumes no access to weights, no log-probabilities and no handwritten labels for the middle steps. It needs only the program, a metric and a training set of inputs.

Try the problem in a toy version. Each module has a weak prompt and a good prompt. You flip switches and see only the final score, as a real optimizer would.

Fix the prompts, see one number

Each module starts with a weak prompt. Flip a prompt to good, watch the final score, then flip the other one. Then press Peek to see what the real optimizer never sees.

Illustrative toy, not the paper's data. A weak query prompt finds the right passage 35% of the time and a good one 80%. A weak answer prompt is right 30% of the time given the right passage and a good one 85%. With no right passage, the answerer guesses right 5% of the time.

Flip the query prompt first, with the answer prompt still weak: the score rises by about 11 points. Reset, fix the answer prompt first, then fix the query prompt: now the same flip adds 36.0 points. Same edit, two very different payoffs. The size of a gain depends on the other module. That one fact is why this problem needs a careful optimizer.

Why earlier prompt optimizers fall short

People have already built prompt optimizers: algorithms that search over strings for a prompt that scores well. The paper names three, APE, OPRO and EvoPrompt. OPRO is the one to remember. It shows a language model a list of past instructions with their scores, and asks for a better one. Chapter 2 builds on it.

These methods mostly assume one prompt with its own score. A multi-stage program breaks that assumption. The score belongs to the whole pipeline. If the answerer ignores a good query, a great query writer earns no credit, and the optimizer may throw it away.

DSPy’s earlier optimizers did handle multi-stage programs. But they only bootstrapped demonstrations, and they could not tune the instructions of a pipeline with several prompts. This paper adds that missing piece. It also asks a practical question: when do instructions matter, and when do demonstrations matter more?

The authors’ answer comes in three parts, which later chapters test. Optimizing bootstrapped demonstrations is often essential for the biggest gains. Optimizing instructions matters most for tasks with conditional rules. Doing both together usually works best.

What the optimizer must do

The paper names two challenges. The proposal challenge: the number of possible prompts is huge, and it grows with every module, so we need a way to propose a few good ones. The credit assignment challenge: many prompts change at once, so we must work out which choice earned which part of the score.

The paper’s answer is a family of optimizers. The headline one is MIPRO, the Multi-prompt Instruction PRoposal Optimizer. On seven tasks, with Llama 3 8B running every program, it wins on five and gains as much as 13% accuracy. The authors released it in DSPy, the library for building LM programs. This lesson uses the paper’s name, MIPRO, and builds it piece by piece.

Look back at the hero at the top. Its four buttons are the four ways the paper lets an optimizer change a program: change nothing, change instructions only, change demonstrations only, change both. Chapters 3 and 4 explain the second and third. Chapters 5 to 8 explain how MIPRO searches over both together.

The road

  1. A program made of prompts: the exact problem, and why brute force fails.
  2. The optimizer loop: Initialize, Propose, Update, Extract.
  3. Bootstrapping demonstrations: let the program write its own examples.
  4. Grounded instruction proposals: show a proposer the data, the code and the scores.
  5. Credit assignment: greedy, history-based, and surrogate.
  6. A surrogate that learns: a Bayesian search over the menu of prompts.
  7. MIPRO, assembled: mini-batches and a fixed budget.
  8. Learning how to propose: MIPRO++ and the importance scores.
  9. The benchmark and the main results: seven tasks, Table 2.
  10. What the ablations teach: five lessons and one failure mode.
  11. Limits and field guide: numbers, code, and what comes next.
Why can an optimizer not train each module’s prompt against that module’s own answer key?

Chapter 1

A Program Made of Prompts

Write the problem down exactly, and count why a brute-force search cannot solve it

Look at one module of the two-step helper from Chapter 0. Its prompt is not one fixed block of text. It is a template: a text with open slots that code fills in each time. The query module’s template has a slot for the instruction, slots for demonstrations, and slots for the inputs, which are the question and the passages found so far.

Each open slot is a variable. Fill every variable with a string and you get a real prompt. Fill them with different strings and you get a different prompt. The paper’s job is to choose the best strings for all variables of all modules at once.

The paper’s example program, in code

Here is the multi-hop question answerer the paper calls HotPotQA, written in DSPy (the library from Chapter 0). It is the paper’s Listing 4.

class MultiHop(dspy.Module):
    def __init__(self):
        self.retrieve = dspy.Retrieve(k=3)                      # search engine: 3 passages
        self.generate_query  = dspy.ChainOfThought("context, question -> search_query")
        self.generate_answer = dspy.ChainOfThought("context, question -> answer")

    def forward(self, question):
        context = []
        for hop in range(2):                                    # two search hops
            query = self.generate_query(context, question).search_query
            context += self.retrieve(query).passages
        return self.generate_answer(context, question).answer

Follow the data. A question arrives as one string. Hop one: the query module reads an empty context and the question, and writes a query string. The search engine returns 3 passages. Hop two: the same query module reads those 3 passages and the question, and writes a second query. Now the context holds 6 passages. Last, the answer module reads all 6 and writes the answer string.

So the program has 2 modules but makes 3 LM calls, because the query module runs twice. This matches Table 1 of the paper. Every value that moves between steps is plain text. There are no tensors and no gradients, only strings in and strings out.

The signature "context, question -> search_query" is the weakest possible prompt. DSPy expands it into the sentence “Given the fields context and question, produce the fields search_query.” The paper’s Table 6 lists this as the baseline instruction. Optimization starts from sentences this plain.

One prompt, filled in

To make “template” concrete, here is the second query call of one question, with every slot filled. The instruction is a real proposal from the paper’s Table 6. The demonstration and the passages are invented for illustration.

[instruction]  Given the fields `context` and `question`, generate a search
               query for identifying relevant information related to the question.
[demo 1]       context: [ ... ]   question: Who wrote the novel that the film Jaws is based on?
               search_query: author of the novel Jaws
[inputs]       context: [3 passages from hop one]
               question: Who directed the film whose success, with An American Tail ...
[output slot]  search_query:

The language model sees all of this as one long string and continues it after search_query:. The text it writes becomes the next query. Nothing else is learned. If the instruction and demo are better, the continuation is better.

A demonstration is a full input and output pair for one module, not for the whole program. That matters. A demo for the query module shows a context, a question and a good query. We have no gold queries, so Chapter 3 shows how to make such demos from the program’s own good runs. The paper gives each module K demo variables, so a module can show the model K worked examples.

The problem, written exactly

Let the program be Φ with m modules. Each module i has a prompt template with open variables. Let V be the set of all variables in all templates. An assignment maps every variable to a string. We write Φ run under an assignment as ΦV→S. The goal is the assignment that gives the best average score on the training set D.

Φ*
The best program: the same code as Φ, with the best strings filled in.
arg maxV→S
Try every way of giving each variable a string, and keep the way that makes the sum below largest.
1/|D|
One divided by the number of training examples. It turns the sum into an average.
∑(x, x′)∈D
Add up over every training example. The input is x. The extra information is x′, such as the correct final answer. It may be empty.
μ(ΦV→S(x), x′)
The metric. It scores the program’s final output for input x against x′. A right answer might score 1 and a wrong answer 0.

This is the paper’s Equation 2. In this paper each module i has one variable for its instruction and K variables for demonstrations. Everything else in the program stays constant.

Five reasons it is hard

The paper lists five obstacles. Read them as a checklist of what MIPRO must handle.

  1. Strings are unbounded. Each variable can hold any text, so the space of assignments has no end.
  2. The metric is global. It scores only the final output, so every variable is latent: its effect is hidden inside one number.
  3. No gradients or embeddings. This rules out reinforcement learning and prompt-tuning methods that need access to model internals.
  4. Small data. Designers usually have hundreds of examples, not millions.
  5. Small budgets. Each test of a prompt means running the whole program on many examples, and every run costs model calls.

Obstacle five hides a trap. Suppose we cap each variable at N good candidates. Even then, the number of combinations explodes. Move the sliders to see how fast.

Count the combinations

Each module has a menu of instructions (blue) and a menu of demonstration sets (purple). Drag the sliders. The bar shows combinations on a log scale, next to a 50-trial budget.

2
30

The count is (N × N)m: N instruction choices times N demo-set choices for each of m modules. The default, m = 2 and N = 30, matches the paper's HotPotQA setup (Table 4 lists N = 30 for MIPRO). The 50-trial budget is the paper's full-evaluation budget for HotPotQA (Appendix B.2). The paper does not state this count itself. It is our arithmetic.

At the default, 2 modules and 30 candidates per menu, there are (30 × 30)2 = 810,000 combinations. The paper spends about 50 full trials. A full trial runs the program on all 500 training examples, so 50 trials is 25,000 program runs. That is why the x-axis of the paper’s optimization plots stops at 25,000 evaluation calls.

The lesson: a search cannot try everything. It must learn from each trial which regions look promising. The rest of the paper is about doing exactly that.

A program has 3 modules. Each module has 10 candidate instructions and 10 candidate demonstration sets. How many combinations are there?

Chapter 2

The Optimizer Loop

Step through the four methods every optimizer in the paper must fill in, and meet the two hard parts

Imagine you tune prompts by hand, but you are disciplined. You keep a notebook. Each line holds one version of the prompts and the score it earned on a small batch of questions. To pick the next version, you read the notebook. When you are done, you circle the best line.

That routine has four moves: set up the notebook, propose a version, write down its score, and circle the winner. The paper turns these four moves into a frame that every optimizer in it must fill in. The frame is its Algorithm 1.

The four methods

An optimizer M is an object with four methods and some internal memory. Think of the memory as the notebook.

  1. Initialize reads the training data D and the proposal settings θ, and prepares the notebook.
  2. Propose returns an assignment: a string for each variable it wants to set. Call it V→Sk on round k.
  3. Update receives that assignment and its score, and writes them into memory.
  4. ExtractOptimizedSets reads memory at the end and returns the best assignment it knows.

The framework then runs a fixed loop. For each of I rounds it calls Propose. Then it draws a batch of B random training examples and runs the program under the proposed prompts. Last, it averages the metric and calls Update with the result. Here is the averaging step as an equation.

σ
The score of this round: the average metric over the batch.
1/B
One over the batch size. It turns the sum into an average.
∑(x, x′)∈Dk
Add up over the B random training examples drawn for round k.
μ(ΦV→Sk(x), x′)
The metric on one example: run the program with this round’s prompts on input x, then compare its output with x′.

A tiny worked case. Take B = 4 and an exact-match metric. The program gets examples one, three and four right and example two wrong. The scores are 1, 0, 1, 1, so σ = (1 + 0 + 1 + 1) / 4 = 0.75. Update stores that 0.75 next to the prompts that produced it.

The same loop as code. This is our own Python rendering of Algorithm 1, not code from the paper.

def optimize(M, program, metric, data, iters, B, theta):
    M.initialize(data, theta)                     # prepare the notebook
    for k in range(iters):
        assignment = M.propose(theta)             # strings for the variables
        batch = random.sample(data, B)            # B examples, not all of them
        sigma = mean(metric(program.run(assignment, x), y) for x, y in batch)
        M.update(assignment, sigma)               # write the score down
    return M.extract_optimized_sets()             # circle the winner

Only one line of this loop is expensive: the line that runs the program. Every pass over a batch means B runs, and each run makes several LM calls. The paper says its goal is to minimize how often the program runs, and as a result how often we must propose. So a good optimizer proposes carefully, and it also scores cheaply.

Run the loop, one line at a time

The program has two modules, each with three candidate instructions. Press Step to run one line of the loop, or Run to do a whole round. Watch the notebook fill, and how the winner changes.

Illustrative toy. The true accuracy of the pair (a, b) is 25% plus 0, 8 or 16 points for the first module’s instruction and 0, 20 or 10 points for the second. Each batch has B = 50 examples drawn with a fixed random seed. The proposer here picks pairs at random, standing in for any real Propose.

Run ten rounds and compare the notebook with the hidden truth in the read-out. The best line in the notebook is not always the truly best pair. A batch of 50 examples is a noisy ruler. For a pair with true accuracy 50%, the average over 50 examples typically misses by about √(0.5 × 0.5 / 50) = 0.071, or 7.1 points. Two pairs that differ by 8 points can swap places on one unlucky batch. Chapter 7 returns to this noise, because MIPRO chooses it on purpose.

Module-Level OPRO, the first full optimizer

Now fill in the four methods for real. OPRO, from the paper’s related work, keeps a notebook inside a prompt. The notebook is a list of past instructions with their scores, shown to a proposer: a second language model whose only job is to write new instructions. The paper’s Module-Level OPRO extends it to a program with m modules.

Look at the Update step. All m instructions receive the same number. The paper states the assumption openly: it treats the program score as a good enough proxy for each module’s instruction. Chapter 5 shows where that breaks. Chapter 0’s toy already hinted at it, since a flip was worth 11 points in one setting and 36 in another.

Step back and see what the frame leaves open. It does not say how Propose finds good candidates among endless strings. That is the proposal challenge. It also does not say how Update should split one score among many variables. That is the credit assignment challenge. Chapters 3 and 4 answer the first. Chapters 5 and 6 answer the second.

In one round of the framework, what does Update receive?

Chapter 3

Bootstrapping Demonstrations

Let the program grade itself, keep the runs that ended well, and reuse their middle steps as worked examples

A teacher has no answer key for the middle steps of a hard homework, only for the final answers. So she tries something clever. She lets a student solve twenty problems. She keeps only the solutions whose final answer is right. Then she shows those worked solutions, steps and all, to the next student.

The paper’s first tool for the proposal problem works the same way. It makes demonstrations without ever writing one by hand. It is called bootstrapping, and it comes from earlier DSPy work by Khattab and colleagues.

A trace, then a filter

Run the program on one training input x. As it runs, record every module call: the inputs the module saw and the output it wrote. That full record is a trace, written τ. For our two-step helper, one trace holds three entries: the hop-one query, the hop-two query and the final answer.

Now check the final answer with the metric. If it is good enough, we trust the whole trace. Each entry becomes a candidate demonstration for the module that produced it. If the final answer is bad, we throw the trace away. This is rejection sampling: draw many samples and keep only those that pass a test.

keep τ
Add every entry of the trace to the pool of candidate demonstrations, one entry for each module that ran.
μ(Φ(x), x′)
The metric score of the program’s final output on input x, compared with the label x′.
λ
The threshold for good enough. For an exact-match metric that scores 0 or 1, any λ above 0 means “exactly right”.

This is the paper’s Section 3.1. The logic is a bet: if the final answer is right, the middle steps were probably sensible. The bet is not perfect. A program can reach the right answer through a poor query. Even so, the bet gives us worked examples for every module, from only a final-answer metric. That is exactly the supervision we have.

From a pool to a few-shot prompt

After the filter, every module owns a pool of candidate demos. The remaining question is which few to show. Here the problem has shrunk. We no longer invent text. We choose a small subset from a pool, for each module, and that is something a search can handle.

The paper’s Bootstrap Random Search (its Figure 2) does this in the simplest way. It has two settings: K, the number of demos each module shows, and N, the number of sets to try. The four methods of Chapter 2 fill in like this.

Here is the idea as code. It is our own sketch, shaped after the paper’s description.

def bootstrap(program, metric, data, lam, n_sets, k):
    pool = {m: [] for m in program.modules}
    for x, y in data:
        out, trace = program.run_with_trace(x)      # trace: [(module, inputs, output), ...]
        if metric(out, y) >= lam:                   # final answer good enough
            for module, inputs, output in trace:
                pool[module].append((inputs, output))
    return [{m: random.sample(pool[m], k) for m in pool} for _ in range(n_sets)]

A worked count shows the pool’s shape. The unoptimized HotPotQA program scores 35.4% on the paper’s training set (Table 2). Run 20 training questions. About 7 will end in a right answer. Each right run contributes the query module twice, since it ran for two hops, and the answer module once. So 7 good runs give 14 candidate demos for the query module and 7 for the answer module. If K = 3, the answer module has 7 choose 3, or 35, possible sets.

Bootstrap a demonstration pool

Each tile is one training question. Run all 20. Right answers (green) are kept and their traces fill the two pools. Wrong ones are rejected (red). Then draw one set of K demos.

36%
3

Illustrative toy. Each question is right with the chosen probability, drawn with a seeded random generator. The default, 36%, is close to the unoptimized HotPotQA program’s test score in Table 2 (36.1%). The query module counts twice per kept run because the HotPotQA program calls it for two hops.

Slide the accuracy down to 15% and run again. On average only 3 of 20 runs survive, so the query pool holds about 6 chips and the answer pool about 3. With K = 3, the answer module then has almost no choice of set. A weak program bootstraps weak variety. That is why the paper uses a stronger teacher model on its two hardest tasks, ScoNe and HoVer. GPT-4o makes the traces, and Llama 3 8B reads them as demos. For the other tasks, Llama 3 8B is its own teacher.

Why this simple method matters

The paper treats Bootstrap Random Search as a strong baseline, and Table 2 shows why. Bootstrap alone lifts Heart Disease from 26.8% to 79.2%, and Iris from 40.9% to 94.1%, on the test sets. The authors also saw high variation between different demo sets, so the choice of examples matters a great deal. They read this as strong demos carrying information about successful reasoning, more than just teaching the output format.

Random search treats all N sets alike. It does not learn that some demos help more than others. Chapter 6 replaces the random draw with a learner.

Why does bootstrapping keep a trace only when the final score passes the threshold?

Chapter 4

Grounded Instruction Proposals

Show a proposer model the data, the code, the examples and the past scores, then ask it for a better instruction

Ask a colleague to “write a good instruction for this task” and give them nothing else. You will get something bland. Now give them a sample of the data, the code of the whole pipeline, a few solved examples, and a list of instructions you already tried with their scores. The new instruction will be much better. It is informed.

That is the paper’s second tool for the proposal problem. It calls the idea grounding: give the model that writes instructions the context it needs to write good ones.

Two models, two jobs

The paper uses two different language models. The task model runs inside the program. Here it is Llama 3 8B. The proposer writes candidate instructions. It is usually GPT-3.5, run at temperature 0.7, and GPT-4 for ScoNe, HoVer and Iris. Temperature is the setting that controls how random a model’s word choices are. A higher value gives more varied output.

Keeping the two apart is a design choice. The proposer only needs to be good at writing about tasks. The task model only needs to follow the instruction. A strong proposer can therefore help a small task model.

What the proposer sees

The paper builds the proposer’s input from four pieces of context, plus one small hint. Each answers a question the proposer would otherwise have to guess.

  1. A dataset summary. What kind of inputs and answers does this task have?
  2. A program summary. What does the whole pipeline do, and where does this module sit in it?
  3. Bootstrapped demos. What do successful runs of this module look like?
  4. Previous instructions with scores. What did we already try, and how did it do?
  5. A tip. A short nudge in a different direction, such as “Keep the instruction clear and concise.”

The dataset summary comes from a loop. The proposer reads a batch of training examples and writes observations. It sees the observations it already has, and adds new ones. When it has nothing to add, it replies COMPLETE. After five COMPLETE replies, the loop stops and a final call squeezes the observations into two or three sentences. For HotPotQA the result begins: “The dataset contains trivia-style questions from a wide range of topics like music, film, history, and literature.”

The program summary is simpler. The DSPy code goes straight into a summarizer, which must state what task the program solves and how it appears to work. The paper reflexively includes the code as written.

The tips come from a fixed list of six. They are none, creative, simple, description, high stakes and persona. The paper says their purpose is to encourage diversity of features across the candidates. A high-stakes tip asks for a scenario in which the model must solve the task. A persona tip asks for a role such as “You are a …”.

A real before and after

The paper’s Table 6 lists what the search found for HotPotQA. The seed instruction for the query module is “Given the fields context, question, produce the fields search_query.” An early proposal, at trial 10, reads “Given the fields context and question, generate a search query for identifying relevant information related to the question.” The answer module goes from “produce the fields answer” to “Given the context passages and a question, generate the correct answer.”

These edits are small. They say what the field is for. For a task whose seed already holds rules, the proposer keeps the rules and adds a frame. On HotPotQA Conditional it wrote “Given the urgency of a live trivia competition where every answer counts, ensure your response follows the specific formatting rules,” and then repeated the rules. Chapter 10 returns to such proposals, because some of them do not help at all.

The proposal program

The paper writes the proposer itself as a small DSPy program. Its signature, in the paper’s Listing 1, shows the inputs and the one output. Every field is a string.

class GenerateSingleModuleInstruction(dspy.Signature):
    """Use the information below to learn about a task that we are trying to
    solve using calls to an LM, then generate a new instruction that will be
    used to prompt a Language Model to better solve the task."""
    dataset_description  = dspy.InputField()   # the dataset summary
    program_code         = dspy.InputField()   # the DSPy program
    program_description  = dspy.InputField()   # the program summary
    module               = dspy.InputField()   # which module to write for
    task_demos           = dspy.InputField()   # bootstrapped input/output examples
    previous_instructions= dspy.InputField()   # earlier tries and their scores
    basic_instruction    = dspy.InputField()   # the seed instruction
    tip                  = dspy.InputField()   # one of the six tips
    proposed_instruction = dspy.OutputField()  # the new instruction

Eight strings go in, one string comes out. The call is repeated for every module, once per candidate. Table 4 shows how many: MIPRO uses N = 30 candidates per module on HotPotQA. All of them are written once, before the search starts.

Toggle the ingredients below and watch the proposer’s input grow.

Assemble the proposer’s input

Each block is one ingredient for the query module of the HotPotQA program. Switch ingredients on and off, and pick a tip. The text below shows what the proposer would read.

The task text, the dataset summary (shortened), the seed instruction, the baseline score of 35.4 and the six tip texts are quoted from the paper (Listing 1, Listing 2, Appendix C.4, Table 2 and Table 6). The token sizes are illustrative estimates, not measurements.

Switch everything off and the proposer sees only the seed instruction. That is the setting the paper calls Module-Level OPRO without grounding, or OPRO −G. With everything on, the input is several times longer. Chapter 10 compares the two on real tasks. The result is mixed: grounding helps a lot on HotPotQA and HoVer and hurts on ScoNe.

Why would context ever hurt? The authors suggest an answer. A dataset summary may be vital for a logic task, yet distract a small proposer on a familiar task like factoid question answering. So the best ingredients vary by task. Chapter 8 shows how MIPRO++ learns that mix.

What does “grounding” mean in the paper’s instruction proposals?

Chapter 5

Credit Assignment

Decide which module deserves the praise or the blame, and see why giving every module equal credit fails

Two runners share a relay. You see only the team’s total time. One day the first runner swaps her shoes and the total improves by two seconds. Was it the shoes? Or did the second runner have a good day? A single number for the team cannot say.

An LM program has the same trouble. The score belongs to the whole pipeline, but the choices belong to individual modules. Working out which choice earned which part of the score is the credit assignment challenge. The paper tries three answers: greedy, history-based and surrogate.

Greedy: change one thing at a time

The cleanest idea is to change one module, keep everything else fixed, and see what happens. If the score moves, that module caused it. This limits blame for errors in other stages.

The paper names two costs. First, changes must be applied one at a time, which is slow. Second, a change to one stage may not move the program score until another stage improves first. A better query writer earns nothing if the answerer ignores the passages. The authors found greedy no more effective than other methods in preliminary work, with much worse time complexity.

The paper also builds a greedy variant of OPRO called CA-OPRO, for coordinate ascent. It loops over the modules. For each one it proposes N instructions, scores each with all other prompts frozen, keeps the best, and moves on. It repeats the whole sweep D times. The authors report that its performance did not justify its inefficiency.

History-based: let the proposer figure it out

The second idea is to trust a strong language model. Put the history of past attempts inside the proposer’s prompt, and let it learn what works. This is OPRO’s idea, and it needs no separate learner. Chapter 2 showed the Module-Level OPRO version. In code, its bookkeeping is very short.

# Module-Level OPRO: every module in a round gets the SAME score
for module in modules:
    history[module].append((new_instruction[module], program_score))

# the proposer for module i later reads history[module_i] and writes a better instruction

The paper states the assumption out loud: the program score is a good enough proxy for each instruction. There is also a Program-Level OPRO. Its proposer sees whole multi-stage trajectories and must assign credit by itself. That asks a lot of one prompt. The paper warns that information in long histories is likely to be lost as they grow. It did not give extra gains, so the experiments use the module-level version.

Why equal credit goes wrong

Take the two-step helper again, with three candidate instructions for each module. Use the toy rule from Chapter 0: the program is right when the query finds the right passage and the answerer reads it. The numbers below are illustrative.

Suppose the optimizer first tries (A3, B1): the best query prompt with the worst answer prompt. The score is 0.80 × 0.30 + 0.20 × 0.05 = 25.0%. Next it tries (A1, B2): the worst query prompt with the best answer prompt. The score is 0.35 × 0.85 + 0.65 × 0.05 = 33.0%.

Under equal credit, A3 receives 25.0 and A1 receives 33.0. The history says A1 is better than A3. That is backwards. A3 was punished for a bad partner, and A1 was rewarded for a good one. The proposer reads this and writes new instructions in the style of A1. Try it.

Watch equal credit mislead

Rows are query prompts, columns are answer prompts. Tap a cell to run that pair, or try random pairs. The bars on the right are what an equal-credit history records for each prompt.

Illustrative toy, not the paper’s data. The paper does not report these numbers. It states the equal-credit assumption of Module-Level OPRO and warns that a poor module can ruin the whole program. Scores here have no noise, to keep the misattribution clear.

Now run more pairs. The bars drift toward the truth, since each prompt meets many partners. But the drift is slow, and the budget is small. A real search with 50 trials over 810,000 combinations never gets to average out its luck. We need a learner that models partners explicitly.

Surrogate: learn the score function

The third idea is a surrogate model: a cheap model that predicts the program score for any combination of choices. It learns from every past trial. Since the surrogate sees the choices and the score together, it can discover that A3 does poorly only when paired with B1. The paper uses Bayesian learning for this, because Bayesian methods are known for optimizing functions with many hidden variables efficiently.

The surrogate has one limit that the paper states: it picks from a fixed menu of proposals. What it learns cannot improve the proposals themselves. That limit is why the paper later adds MIPRO++ (Chapter 8). First, Chapter 6 builds the surrogate.

Why does Module-Level OPRO risk ranking a good instruction below a poor one?

Chapter 6

A Surrogate That Learns Which Combinations Win

Run a Bayesian search over the menu of instructions and demonstrations, and watch it concentrate on winners

You are a food critic with a budget of 50 tastings. Each meal has several courses, and each course has 30 dishes on the menu. You cannot taste every combination. So after each meal you keep a score. Soon you notice that some dishes show up again and again in the good meals, and others only in the bad ones. You start betting on the good dishes, and you still try an unknown dish now and then.

That habit is the heart of the surrogate in MIPRO. The menu is the list of N instructions and N demonstration sets that Chapters 3 and 4 prepared for each module. A meal is one program run. The score is the metric on a mini-batch.

What the search chooses

After Initialize, every module has N candidate instructions and N candidate demo sets, all written in advance. The search no longer invents text. It picks indices. For m modules, that makes 2m categorical variables: variables that take one of N named values, with no order between them. The paper starts each one with a uniform prior, which means every choice is equally likely until trials say otherwise.

The paper uses Bayesian optimization, a family of methods that learn a cheap model of an expensive function and use it to pick the next point to test. The cheap model here is the surrogate. It predicts how good a combination of choices is, using only the scores seen so far. The paper names the specific method: the Tree-structured Parzen Estimator, or TPE, in the implementation from the library Optuna.

How TPE decides, with numbers

This part is background from the TPE paper by Bergstra and colleagues, not a contribution of MIPRO. We explain it because MIPRO’s Propose step is exactly one TPE sampling step.

TPE does not model score given choice. It flips the question. It splits the past trials into two groups at a cutoff: the best fraction γ are “good”, the rest are “bad”. Then it learns two distributions over choices. The first, l(x), describes choices seen in good trials. The second, g(x), describes choices seen in bad trials. The next choice to try should be common among good trials and rare among bad ones.

EI(x)
Expected improvement: how much better than the cutoff we expect the next score to be if we try choice x.
γ, l(x), g(x)
γ is the fraction of trials called good. l(x) is the share of good trials that used x. g(x) is the share of bad trials that used x.
arg max l(x)/g(x)
The expected improvement rises as g/l falls. So the best next choice is the one with the largest ratio l over g.

A worked example for one variable with four instructions, a, b, c and d. Eight trials ran, with scores a 31, b 44, c 29, b 47, d 35, a 33, b 41, c 30. Take γ = 0.25, so the top two trials count as good: b with 47 and b with 44. Give every choice one pseudo-count, a stand-in for the uniform prior.

Choice b wins by a wide margin. Notice two things. A choice never tried in a good trial can still be tried later, since the pseudo-count keeps its l above zero. And the paper uses a multivariate TPE, which models the variables together rather than one at a time, so it can learn that A3 works only with B2. This toy keeps them separate for clarity.

Why does TPE suit this job? Our choices are discrete, so there are no slopes to follow. The paper also needs an estimator that works without labels for single modules, and TPE needs only the final score. Finally, TPE draws its next choice at random from l(x) and then ranks the draws. That keeps a little exploration alive, so one lucky early trial cannot lock the search onto a weak prompt.

Here is how you would wire it, as our own sketch with Optuna’s real interface.

import optuna

def objective(trial):                             # one trial = one program run on a mini-batch
    assign = {}
    for m in modules:
        i = trial.suggest_categorical(f"ins_{m}",  list(range(N)))    # which instruction
        d = trial.suggest_categorical(f"demo_{m}", list(range(N)))    # which demo set
        assign[m] = (instructions[m][i], demos[m][d])
    return minibatch_score(program, assign, B)    # the score TPE learns from

study = optuna.create_study(direction="maximize",
                            sampler=optuna.samplers.TPESampler(multivariate=True))
study.optimize(objective, n_trials=300)

Watch the surrogate concentrate

A toy program has 6 instructions and 6 demo sets, so 36 combinations. The bars show the ratio l over g that TPE has learned for each choice. The lines compare the true quality of the best trial found by TPE and by random search.

Illustrative toy, not the paper’s data. True accuracy is 30% plus a bonus for each instruction and each demo set. Every trial scores a mini-batch of 40 examples, so scores are noisy. TPE uses γ = 0.25, one pseudo-count per choice, and 6 random warm-up trials. This toy models each variable on its own. The paper uses Optuna’s multivariate TPE.

Run 40 trials, then look at the lines. TPE usually finds a better pair sooner, because later trials concentrate on choices that keep showing up in good mini-batches. Random search wastes trials on choices that already looked poor. With a noisy score, either line can wobble. That wobble is why MIPRO uses mini-batches wisely, which is Chapter 7.

In TPE, which choice should the search try next?

Chapter 7

MIPRO, Assembled

Put proposal, bootstrapping and search together, and spend a fixed budget on mini-batches instead of full passes

A factory makes thousands of parts a day. Inspecting every part is too slow. So an inspector pulls a small sample from each batch, and rejects the batch when the sample looks bad. Once in a while, she does a full inspection of the finalists to be sure.

MIPRO works the same way. It cannot afford to run a program on all 500 training examples for each candidate. So it scores most candidates on a small random sample, and runs a full check only now and then.

The four methods, filled in

Here is MIPRO in the frame of Chapter 2. It uses everything built so far.

  1. Initialize. For every module, bootstrap N demo sets (Chapter 3) and write N grounded instructions (Chapter 4). Create the surrogate with a uniform prior over each choice.
  2. Propose. Draw one instruction index and one demo-set index for every module, using the TPE sampling rule (Chapter 6).
  3. Update. Run the program on a random mini-batch of B examples. Tell the surrogate the score σ.
  4. ExtractOptimizedSets. Every S steps, take the candidate with the highest mean score over its trials and evaluate it on the full training set. At the end, return the best fully evaluated candidate.

The paper stresses one design point. Because instructions and demos are made upfront, the proposer only has to propose. The surrogate does the credit assignment afterwards. In the paper’s words, this separates credit assignment from prompt proposal. Module-Level OPRO needed one model to do both jobs.

A concrete count

On HotPotQA, Table 4 gives N = 30 for MIPRO. There are 2 modules. The proposer therefore writes 2 × 30 = 60 instructions, and bootstrapping builds 2 × 30 = 60 demo sets. The surrogate searches over 4 categorical variables, each with 30 values. The data flow of one trial: four integers go in, one prompt string is assembled for each module, the program runs on B examples, and one number σ comes out.

The paper gives a rule of thumb for N: keep N below T / v, where T is the trial budget and v is the number of variables. With the 300 mini-batch trials of HotPotQA and 4 variables, T / v is 75, so N = 30 fits with room to spare. That 75 is our arithmetic. The paper says only that N was chosen by intuition from past runs, not by extensive sweeps.

Why mini-batches

Bayesian optimization is known for its robustness to noise. The paper uses that. Instead of one precise score per trial, MIPRO takes many cheap, noisy ones. The noise of an accuracy measured on B examples, when the true accuracy is p, is about the following.

sd
The typical error of one measured accuracy, in fractions of 1. Multiply by 100 for points.
p, B
p is the true accuracy of the program under these prompts. B is the number of examples in the mini-batch. A bigger B shrinks the error, slowly: four times the examples halves it.

Take p = 0.40. At B = 25 the error is √(0.24 / 25) = 0.098, about 10 points. At B = 100 it is 0.049, about 5 points. At the full 500 examples it is 0.022, about 2 points. Since the surrogate looks at many trials, it can average out noise that a single trial hides.

Now the budget. The paper’s HotPotQA budget is 50 full evaluation trials, and it says that equals about 300 mini-batch trials. A full trial uses all 500 training examples, so the budget is 50 × 500 = 25,000 program runs. Mini-batches and the periodic full checks share that pool. Let D be the size of the training set. Spend B runs per trial, and D runs on a full check every S trials. Then T trials cost the following.

T
How many mini-batch trials fit in the budget.
budget
Total program runs allowed. For HotPotQA: 50 × 500 = 25,000.
B + D/S
The average cost per trial: its own B runs, plus its share of a full check that costs D runs and happens once every S trials.

This formula is our own derivation. The paper does not state B or S for each task, but you can see the trade-off. Try it below.

Split the budget

The budget is 25,000 program runs. Drag the mini-batch size B and the full-check interval S. Dots are trials. Tall ticks are full checks.

83
25

Our arithmetic with the paper’s HotPotQA numbers: a training set of 500 (Table 3) and a budget of 50 full trials (Appendix B.2). B = 83 is the mini-batch size that would spend the whole budget on about 300 trials, which is our inference. The paper does not report B or S. Noise assumes a true accuracy of 40%.

At the defaults you get about 242 trials and 9 full checks. A mini-batch score is off by about 5 points, and a full check by about 2. Push B down to 20 and trials more than double, to 625, but each score is off by 11 points. Push B to 250 and the scores sharpen, but only about 92 trials remain, so the surrogate has little to learn from. There is a sweet spot, and it depends on the task.

Here is MIPRO as code. It is our sketch of the paper’s algorithm.

def mipro(program, metric, train, N, trials, B, S):
    ins  = {m: propose_instructions(m, N) for m in modules}      # Chapter 4, grounded
    demo = {m: bootstrap_demo_sets(m, N)  for m in modules}      # Chapter 3
    study = tpe_study()                                          # uniform prior over indices
    best_full = None
    for t in range(1, trials + 1):
        idx = study.ask()                                        # one index per variable
        assign = materialize(idx, ins, demo)
        sigma = score(program, assign, random.sample(train, B))  # mini-batch score
        study.tell(idx, sigma)
        if t % S == 0:
            cand = study.best_by_mean_score()                    # highest mean over its trials
            full = score(program, materialize(cand, ins, demo), train)   # all of D
            if best_full is None or full > best_full[1]:
                best_full = (cand, full)
    return materialize(best_full[0], ins, demo)

Cousins of MIPRO

The paper defines three simpler variants by cutting parts away. 0-Shot MIPRO optimizes instructions only, which suits tight cost or context limits. Bayesian Bootstrap optimizes demos only, which suits tasks where examples matter most or a good instruction already exists. MIPRO++ tunes how the proposer works, which is the next chapter.

Why does MIPRO evaluate its best candidate on the full training set every S steps?

Chapter 8

Learning How to Propose

Tune the proposer itself with the same Bayesian trick, and read which proposal ingredients mattered for each task

A writer has a favorite way to start every draft: read the notes first, set a mood, pick a style. After a year she notices that on some projects the notes help and on others they get in the way. So she decides to treat her own habits as things to test.

That is the paper’s third proposal strategy, learning to propose. Chapter 4 gave the proposer a fixed recipe: summarize the data, summarize the program, show demos, show past scores, add a tip. The paper points out that the best recipe depends on the task, the program and the proposer. A dataset summary may be vital for a logic puzzle, and a distraction for a small proposer on trivia questions it already knows.

The settings of a proposal

The paper makes the recipe itself a set of hyperparameters: settings chosen before a run, rather than learned inside it. For instruction-only tuning, 0-Shot MIPRO++ treats five of them as variables.

Chapter 6’s Bayesian search now runs over these settings, not over prompts. Each trial samples one setting. The proposer writes one new instruction under that setting. The program with the new instruction scores a mini-batch. The surrogate learns which settings tend to give higher scores. As before, the best fully evaluated program is returned.

def mipro_pp_trial(study, program, proposer, train, B):
    cfg = study.ask()      # use_dataset_summary: bool, program_aware: bool,
                           # temperature: float, tip: category, demos: category
    instruction = proposer.write(cfg)                           # a NEW instruction each trial
    sigma = score(program.with_instruction(instruction), random.sample(train, B))
    study.tell(cfg, sigma)                                      # learn which settings pay off

Walk through one trial on ScoNe, with invented settings for illustration. The surrogate samples: dataset summary on, program summary off, temperature 0.9, tip “persona”, and demo set 12 out of the 70 that Table 4 lists for this task. The proposer receives the summary of logic puzzles with nested negation, no program code, the persona tip, and demo set 12. At temperature 0.9 it writes one instruction. The program runs on a mini-batch and scores, say, 0.74. The surrogate records that this setting earned 0.74, and the next trial leans toward settings that look like it.

Compare this with MIPRO. MIPRO writes N instructions up front and only chooses among them. MIPRO++ writes a new instruction on every trial, so each trial costs one proposer call. In return, what the surrogate learns improves the proposals themselves. That is the limit Chapter 5 said a plain surrogate has, and MIPRO++ removes it.

What the surrogate learned

A pleasant side effect is a readout. Since the Bayesian model tracks how each setting relates to score, it can report how much each one mattered. The paper shows this for three tasks, in its Figures 5 to 7. Pick a task below.

Read the learned importances

Each bar is how much one proposal setting mattered on that task, as learned by the Bayesian model. Switch the task and watch which bars grow or shrink.

Values are read from the paper’s Figures 5, 6 and 7 (Appendix D) and rounded as printed. Each task’s bars add up to about 1. Program summary is below 0.01 on HotPotQA and HoVer. Demos for module 1 means the demos shown to the proposer for the first module, counting as the figures do. The paper does not give a formula for the importance score.

Three patterns stand out, and the paper names them. First, the choice of demos shown to the proposer and the tip score high on every task. Second, the picture changes with the task. The dataset summary carries 0.30 on ScoNe and only 0.01 on HotPotQA and 0.04 on HoVer. Third, temperature is the top setting on HoVer, at 0.26, and a minor one elsewhere, at 0.05.

These importances also explain the grounding results you will see in Chapter 10. The OPRO −G ablation showed grounding hurt ScoNe. MIPRO++ can learn which parts of grounding to use, and in what mix, for each task. The paper reports that it recovers the lost score there: 0-Shot MIPRO++ reaches 75.7 on the ScoNe test set, against 71.5 for 0-Shot MIPRO and 73.5 for Module-Level OPRO.

The paper is careful about what it has not shown. Results across the three instruction-only methods are mixed. 0-Shot MIPRO++ beats 0-Shot MIPRO on ScoNe and HotPotQA and is about equal on HoVer. The authors guess that 0-Shot MIPRO could win at very low budgets, because its mini-batches let it explore many options. They also guess that MIPRO++ could shine when budget is no problem, because learning proposal dynamics takes many trials. They leave both for future work.

One more design reason is worth saying. The settings are few: five, plus one demo choice per module. A search over a handful of settings needs far fewer trials to learn something useful than a search over 810,000 prompt combinations. So MIPRO++ trades a larger menu for a smaller, smarter space, and it pays for that with one proposer call per trial.

What does MIPRO++ apply its Bayesian model to?

Chapter 9

The Benchmark and the Main Results

Read Table 2 task by task, and learn exactly what each program, metric and budget was

Imagine seven exams, each built to catch a different kind of student. One tests multi-step lookup. One tests whether you follow formatting rules. One tests a tiny, nearly solved problem. A good tutor would run every study method against all seven, and report where each one helps and where it fails.

That is what the paper does. It builds a benchmark of seven tasks. Each task is a dataset, a metric and an LM program. It then runs every optimizer five times on every task.

The seven tasks

TaskProgramModulesLM callsMetric
HotPotQAMulti-hop retrieval23Exact match
HotPotQA ConditionalMulti-hop retrieval23Custom format check
IrisChain of thought11Accuracy
Iris-TypoChain of thought11Accuracy
Heart DiseaseAnswer ensemble24Accuracy
ScoNeChain of thought11Exact match
HoVerMulti-hop retrieval44Recall@21

This is the paper’s Table 1. Each task has a purpose.

How the runs were set up

Most tasks use 500 training examples, 500 development examples and up to 2,000 test examples. The small tasks use less: Iris has 75 train and 75 test examples, Heart Disease 120 and 183. Each method runs 5 times per task. A Wilcoxon signed-rank test compares two methods across the test examples, and the paper marks a winner in bold only when the difference is significant at p < .05.

The task model is Llama 3 8B at temperature 0.7. The proposer is GPT-3.5, or GPT-4 on ScoNe, HoVer and Iris. Demos come from Llama 3 8B itself, except on ScoNe and HoVer where GPT-4o makes them. Budgets are 50 full trials on HotPotQA and ScoNe, 30 on Iris, Heart Disease and HotPotQA Conditional, and 20 on HoVer, the most expensive program.

The paper compares seven optimizers in three groups. Instructions only: Module-Level OPRO without grounding, Module-Level OPRO, 0-Shot MIPRO and 0-Shot MIPRO++. Demonstrations only: Bootstrap Random Search and Bayesian Bootstrap. Both: MIPRO. The unoptimized program is the baseline, written N/A in the table. A result counts as a real difference when a paired test gives p < .05: a gap this big would appear by chance less than one time in twenty.

Read Table 2, one task at a time

Pick a task and a split. Bars are averages over 5 runs. A star marks the winner or winners in bold in the paper’s table. Rows with no bar were not run on that task.

All values are copied from the paper’s Table 2. Test sets are 2,000 examples or fewer, as Table 3 lists. The paper does not run every method on every task, so some rows are empty. Stars mark the paper’s own bold entries for the test split.

Reading the table

Start with ScoNe, test split. The unoptimized program scores 69.1. Bootstrap Random Search reaches 75.4 and MIPRO reaches 79.4, a gain of 10.3 points. Module-Level OPRO without grounding, a pure instruction method, gets 76.1. Now switch to Iris. Bootstrap Random Search gets 94.1 and MIPRO only 88.6. The jointly searching method is not always the best.

The paper counts MIPRO as the winner on five of seven tasks. By Table 2’s bold marks that is ScoNe, HotPotQA, HoVer, HotPotQA Conditional and Iris-Typo, with HotPotQA a three-way tie. Counting only clear wins gives four. Iris and Heart Disease go to Bootstrap Random Search. The abstract says MIPRO gains “as much as 13%” accuracy over baselines. The paper does not spell out which comparison that is. Against the unoptimized program, the gains in Table 2 are much larger on some tasks, such as Iris, at 47.7 points.

Compare train and test columns. MIPRO on Iris scores 98.4 on train and 88.6 on test. The gap may mean the search overfit a small training set, since Iris has only 75 training examples. The paper does not test this.

On Iris (test), which method scores highest in Table 2, and what does that show?

Chapter 10

What the Ablations Teach

Compare demonstrations with instructions, test grounding, and meet the failure the authors saw in the prompts

After a long experiment, a good scientist writes down what she would tell a friend in one breath. The paper does this too. From the seven tasks it draws five lessons for people who tune LM programs. We take the first four, test each against the numbers in Table 2, and then look at a failure the authors saw in the prompts themselves.

Five lessons

  1. Demonstrations are key. Optimizing bootstrapped demos alone often beats optimizing instructions alone. The paper says even simple Bootstrap Random Search beats the best instruction-only method in all but one task, HotPotQA Conditional.
  2. Doing both usually wins. MIPRO is best overall. The exceptions are HotPotQA, where it ties, Heart Disease and Iris.
  3. Instructions matter most for hidden rules. Conditional rules that are not obvious, and that a few examples cannot show, need instructions.
  4. Grounding helps overall, but the best proposal strategy varies. It is essential on HotPotQA and HoVer and it seems to hurt on ScoNe.
  5. There is more to learn. Results across the instruction-only methods are mixed, and budgets were fixed.

The device below turns each of the first four into a picture. For every task it draws one difference between two Table 2 numbers, as bars that go right when the first method wins.

Test a lesson on the numbers

Pick a lesson. Each bar is a difference in test score, in points, computed from Table 2. A bar to the right means the first method named in the lesson wins on that task.

Differences are our arithmetic on the paper’s Table 2 test averages. Lesson 1 compares Bootstrap RS with the best instruction-only method (on tasks where only 0-Shot MIPRO ran, with 0-Shot MIPRO). Lesson 2 compares MIPRO with the best of all other methods. Lesson 3 compares 0-Shot MIPRO with Bootstrap RS. Lesson 4 compares Module-Level OPRO with OPRO without grounding, which the paper ran on three tasks.

Reading the bars

Lesson 1. By the averages, Bootstrap RS beats the best instruction-only method by 6.5 points on HotPotQA, 4.1 on HoVer and 57.7 on Iris. It trails by 4.2 on HotPotQA Conditional, as the paper says. It also trails by 0.7 on ScoNe. That one is a close call in the averages, so the paper’s claim rests on its statistical test over per-example scores, which Table 2 does not show.

Lesson 2. MIPRO leads the best other method by 8.7 points on HotPotQA Conditional and 10.0 on Iris-Typo, but only by 0.2 on HotPotQA. It trails by 5.5 on Iris and 5.0 on Heart Disease. The authors guess why for Heart Disease. They seeded every optimizer with a simple instruction that gives no classification criteria, and current instruction optimizers have limited power to infer them. On HotPotQA they note that the final module is a plain question answering step, which many models already handle well.

Lesson 3. Only on HotPotQA Conditional does the instruction-only method beat demos, by 4.2 points. That is the task where the rules are the whole difficulty. Iris-Typo is a near tie, at −2.0 points. There, instruction optimization helped by repairing a mistake in the seed prompt, and the baseline of 32.0 rises to 56.7. The authors add a caution. These optimizers cannot yet infer all task rules, so you must give them a seed prompt that states the rules you know.

Lesson 4. Module-Level OPRO with grounding beats the same method without it by 3.0 points on HotPotQA and 6.8 on HoVer, and loses 2.6 on ScoNe. This is the case for MIPRO++, which learns the recipe per task.

The paper tests significance with a paired non-parametric test. The two methods are scored on the same test examples, and the test asks whether one is consistently higher. Here is how you would run it.

from scipy.stats import wilcoxon

# a, b: per-example scores of two methods on the SAME test examples
# (each averaged over the 5 runs)
stat, p = wilcoxon(a, b)           # paired, makes no assumption about the score distribution
significant = p < 0.05            # the paper's threshold for bold in Table 2

A failure the authors saw

The paper’s Appendix H lists the prompts discovered over trials of one 0-Shot MIPRO run for each task. It notes a failure mode. The proposers tend to overfit instructions to the few-shot examples in the meta-prompt.

Here is a real case from HotPotQA, at trial 330. The query instruction asks to “generate the search query to find the director of the film whose success, along with An American Tail and The Land Before Time, prompted Steven Spielberg to establish his own animation studio.” The answer instruction says to “determine the answer by identifying the Finnish former boxer who shares a nickname with a Ugandan political leader and military officer.” Both are specific training questions pasted into instructions that should be general.

On ScoNe the best proposed instruction describes a detective, a suspect wearing gloves, and a weapon with no fingerprints. And on Iris-Typo, the best proposed instruction is about saving a rare iris from extinction. These are scenes, not rules.

Yet such instructions sometimes end up in the best programs. The authors give two guesses. One: removing them would need more explicit credit assignment. Two: they act as extra few-shot examples that still help the task model. The paper leaves the question open. A reader who deploys an optimized prompt should read it first.

On which kind of task does the paper find instruction optimization most valuable?

Chapter 11

Limits and Field Guide

Collect the numbers, the core code and the open questions, and see where MIPRO sits in the field

Here is the whole paper in one paragraph. A multi-stage LM program has prompts in every module, and only the final answer has a label. The paper writes this as a search over strings, and splits the difficulty into two challenges: proposing good prompts, and assigning credit among modules. It meets the first with bootstrapped demonstrations and grounded instruction proposals. It meets the second with a Bayesian surrogate that learns from mini-batch scores. MIPRO puts the pieces together. On seven tasks with Llama 3 8B, it wins on five by the paper’s count, and shows that demonstrations carry most of the gain, except where rules are hidden.

What the paper does not claim

The Limitations section is short and plain. We list it, then add what the earlier chapters showed.

Use the device below as a reading aid. It maps three common situations to the nearest task in the benchmark, and shows what Table 2 says there. It is our own summary, not advice from the paper, and a different model or budget could change the picture.

Find your nearest task

Pick the situation that sounds most like yours. The bars show the four ways to optimize on the benchmark task that is closest to it.

Scores are test averages from the paper’s Table 2. Hidden rules maps to HotPotQA Conditional. Hard criteria maps to Heart Disease, where the seed instruction gave no classification criteria. Ordinary pipeline maps to HoVer. The mapping is our own reading aid.

The numbers to remember

MeasurementValueSource
Tasks where MIPRO beats the baselines5 of 7, by up to 13% accuracy, with Llama 3 8BAbstract
Example program, before and after optimization21% → 40%Figure 1
HotPotQA, unoptimized → MIPRO (test)36.1 → 46.4Table 2
HoVer, unoptimized → MIPRO (test)25.3 → 39.0Table 2
HotPotQA Conditional, unoptimized → MIPRO (test)6.0 → 23.3Table 2
Iris-Typo, unoptimized → MIPRO (test)32.0 → 68.7Table 2
Heart Disease, Bootstrap RS vs MIPRO (test)79.2 vs 74.2Table 2
Budget on HotPotQA and ScoNe50 full trials, about 300 mini-batch trialsAppendix B.2
Candidates per module on HotPotQA (MIPRO)N = 30Table 4
Runs per method, significance level5 runs, p < .05 (Wilcoxon)Section 5.2
Most important proposal setting on HotPotQADemos for module 2, 0.59Figure 6

Terms

TermPlain meaning
LM program, moduleCode that calls a language model several times. Each call is a module with its own prompt.
Instruction, demonstrationThe sentence that says what to do. A worked input and output example inside the prompt.
BootstrappingKeep the traces of runs with a good final score. Reuse their middle steps as demonstrations.
Proposer, groundingThe model that writes candidate instructions. The context it is given first.
Credit assignmentWorking out which module’s choice earned which part of the score.
Surrogate, TPEA cheap learned model of the score. A method that favors choices common in good trials and rare in bad ones.
Mini-batchA small random sample of training examples, used for a quick, noisy score.
0-Shot MIPRO, Bayesian Bootstrap, MIPRO++MIPRO with instructions only. MIPRO with demos only. MIPRO that searches over proposal settings.

The core, as code

The number-crunching heart of MIPRO is one small function. It turns the trial history of one variable into a choice. This is our sketch of the TPE rule from Chapter 6.

from math import ceil

def tpe_pick(history, n_choices, gamma=0.25, prior=1.0):
    """history: list of (choice, score). Returns the next choice to try."""
    ranked = sorted(history, key=lambda t: t[1], reverse=True)
    n_good = max(1, ceil(gamma * len(ranked)))
    good, bad = ranked[:n_good], ranked[n_good:]
    def share(group, c):                        # smoothed share of the group that used choice c
        return (sum(1 for ch, _ in group if ch == c) + prior) / (len(group) + prior * n_choices)
    return max(range(n_choices), key=lambda c: share(good, c) / share(bad, c))   # max l(c) / g(c)

Where MIPRO sits, and where to go next

MIPRO belongs to a line of work that treats prompts as the thing to optimize. APE, OPRO and EvoPrompt search over strings for one prompt. Gradient-guided and reinforcement learning methods need model access. Sordoni and colleagues optimize two stacked LLM calls with variational inference, but they need log-probabilities, which hosted models often hide. MIPRO uses text in and text out only, and works for any number of modules. Soylu and colleagues, cited by the paper, optimize prompts, model weights, or both together.

Questions we would ask next

These are our own questions, not claims of the paper. Would the ranking of Table 2 hold with a different task model, or a stronger proposer? Is there a budget at which 0-Shot MIPRO overtakes MIPRO++, as the authors guess? Could the proposer see the surrogate’s learned importances, so it learns from past failures and stops copying training questions? And how would any of this change if the program could also train the weights of its modules?

Credit and source

This lesson teaches the paper Optimizing Instructions and Demonstrations for Multi-Stage Language Model Programs. The authors are Krista Opsahl-Ong, Michael J Ryan, Josh Purtell, David Broman, Christopher Potts, Matei Zaharia and Omar Khattab. They work at Stanford University, Basis, KTH Royal Institute of Technology and UC Berkeley. The paper is arXiv:2406.11695, and it is a reading for Stanford CS 329Z, Lecture 9. All results, figures and tables are the authors’. Toy numbers on this page are labeled illustrative. Read the original at arxiv.org/abs/2406.11695. The authors released the optimizers and benchmark in DSPy at dspy.ai.

The idea in one line: search over words, and let the final score do the grading. No module has a label, no model gives gradients, and the budget is small. MIPRO bootstraps examples from the program’s own good runs, asks a grounded proposer for instructions, and lets a Bayesian surrogate find which combination wins. Demonstrations carry most of the gain, and instructions matter when the rules are hidden.
Go back to the hero and run all four optimizers again. Now you can say which chapter explains each bar: Chapter 3 for the examples, Chapter 4 for the instructions, Chapter 6 for the search that picks among them, and Chapter 9 for the numbers.
Which statement matches the paper’s own limitations?
MIPROv2
Krista Opsahl-Ong, Michael J Ryan, Josh Purtell, David Broman, Christopher Potts, Matei Zaharia and Omar Khattab, arXiv:2406.11695 · Read the paper · Back to Veanors