Show a model its past attempts with their scores and it proposes a better one. On the same budget of tries that beats blind guessing, and the same loop found a new 512-point cap set.
Pick a partner, then press Ask for one more try and watch where each one looks next. Then we build, piece by piece, the loop underneath: prompts, text gradients, scored histories, programs that evolve, and the checks that make a discovery count.
You need a little Python and the idea of a score (one number that says how good an answer is). We build the rest from zero.
Based on Lecture 3 of MIT MAS.S62 How to AI an AI for (Almost) Anything (Fall 2026, MIT Multisensory Intelligence group), taught by Paul Liang, MIT Media Lab and EECS, and its six readings. Lecture slides. Every idea is re-taught here in our own words and devices.
The proposer here is a stand-in rule, not a language model: after three random starts it copies one of its three best tries with a small nudge, and one try in seven it jumps to a fresh spot. A real LLM optimizer reads the same list of tries and scores as text. The terrain is three smooth bumps, made up. The four terrains you can step through are picked because the gap is clear; the averages in the read-out are over all 400 made-up terrains, and are the honest number.
Chapter 0
See why a language model that reads its own scored attempts can search where the usual maths cannot
Picture a baker who wants the perfect loaf. She can change three things: the oven heat, the baking time and the amount of water. Each loaf takes three hours. When it comes out she tastes it and gives it a number from 0 to 10.
That number is all she gets. No formula says how the taste changes if she adds one more spoon of water. She cannot ask the oven for a slope. She can only try, taste and try again.
Engineers meet this shape of problem all the time. The thing you tune might be a prompt, a program, a robot controller or a research idea. You can run it and measure it. You cannot write down how the measurement changes when you nudge the input.
The number the baker gives each loaf is the score. The thing that computes it is the scorer, or evaluator. The rule that says how to get the score from a choice is the objective function. To optimize is to find the choice with the best score.
Most of machine learning optimizes with the gradient: the slope of the score, which says which way is up. Training a neural network works because the gradient is cheap to compute. If you know the slope you take a step uphill.
When there is no slope, the problem is a black box. You can feed it a choice and read the score. You cannot look inside. Black-box search is old. This lecture asks what changes when the searcher is a large language model (LLM, a program that reads text and writes the next words). An LLM can read a whole history of tries in plain language and reason about what to try next.
Try it on a toy hill. You start at the left. Each move takes one step and costs one try. First climb with the slope hidden: you only learn which way is up after you step. Then switch the slope on and climb again.
The curve is the score at each position. Press a step button to move one step and read the new score. Reach the top in as few moves as you can, then press the slope toggle and do it again.
Illustrative: a made-up curve with two hills, a small one near the start and a tall one at the right. A step is 0.04 of the way along. The slope arrow is the exact slope of the curve at your position.
With the slope hidden you spend moves just to learn which way is up, and a small hill can trick you into stopping early. With the slope shown the arrow tells you. A black-box optimizer has no arrow. It must get its direction from the pattern in its past tries.
This is Lecture 3 of How to AI an AI for (Almost) Anything, MIT MAS.S62 AI4AI, from the MIT Multisensory Intelligence group. It met on 23 September 2026 as Week 3, “Context evolution 2”, and Paul Liang taught it. Logistics are short: for-credit enrollment is capped at 20 to 30, listeners may join if they are dedicated, and a project preference form follows. The lecture plan has five parts, with its own timings: a recap of prompt optimization (5 minutes), a TextGrad deep dive (10), LLMs for discovery (20), a FunSearch breakdown (15) and open challenges (3).
The lecture is about context: everything the model reads before it writes. Week 2 showed that you can improve a model by changing its context. Week 3 asks the next question. Can a model do that improving by itself, in a loop, and can the loop go as far as new science?
Chapter 1
Recap what a prompt does, then watch a model write prompts and keep a playbook of what worked
You text a friend, “cheese”. Nothing else. She has no idea what you want. Now you text three lines first: “sea otter, loutre de mer. peppermint, menthe poivrée. cheese,” and she answers “fromage” at once. The last word did not change. The text before it did.
A language model lives in that situation all the time. The lecture opens with a recap of Week 2 and names the idea precisely. Context is everything the model reads before it writes the next token (a token is one piece of text, roughly a word). A prompt is what you give the model to guide its answer. So a prompt is the part of the context that you wrote on purpose.
The slide sorts context by who supplies it. The developer supplies a system prompt (standing instructions), task instructions, tool definitions (descriptions of the functions the model may call), examples and memory. The user supplies a message. The environment supplies files, search results and tool output. And the model itself adds its own thoughts and actions as it works. All of it sits in one stream of text that the model reads.
The slide also lists five jobs that context does. Keep these five words, because the rest of the lecture rewrites context for exactly these jobs.
| Job | What the context carries | Example |
|---|---|---|
| Inform | new information | a search result the model never saw in training |
| Steer | instructions, role, format | “Answer as JSON with two keys” |
| Demonstrate | examples | three word pairs, English to French |
| Compute | thinking step by step | the model writes its working before the answer |
| Correct | feedback from the last attempt | “Your last answer failed this test” |
The next slide gives a picture. Before it reads any context, the model could be doing almost any task: answering a question, translating, writing a poem. Its guess about the task is spread thin across all of them. A distribution is such a spread: a list of probabilities that add up to 1.
Context squeezes that spread. The slide writes the squeeze as p(z) becoming p(z | c): the chance of each task z, before and after the model reads context c. After the three French examples, almost all of the probability sits on translation. Add pieces of context below and watch the spread collapse.
Seven tasks start with equal odds. Switch pieces of context on and off. Each piece makes some tasks more likely and others less, and the bars show the result.
Illustrative numbers, not measured from a model. Each piece multiplies the odds of the matching task by 8 and the others by values between 0.1 and 0.7, then the seven odds are rescaled to add up to 100% (Bayes’ rule, done exactly). The slide draws the same squeeze as two curves.
Two things to notice. One example already moves a lot of the probability. Three examples make the choice almost certain. And a piece of context for a different task (the capital of France) pulls the mass elsewhere. Context is a steering wheel, and every piece you add turns it.
If context is so powerful, who should write it? The slide’s next point is that LLMs can write high-quality prompts through iterative attempts. The example is the Automatic Prompt Engineer (APE) of Zhou and colleagues, ICLR 2023. It runs a simple loop.
The slide’s chart compares prompts across 24 tasks using the interquartile mean (a robust average that ignores the extreme highs and lows). The bars for APE sit above the dashed line for a human prompt engineer. Notice the shape of the loop: propose, score, keep. It is the same shape as every system in this lecture. Only the thing the model proposes changes.
A prompt tuned once stays frozen. The slide’s last point asks for more: build an agentic system that updates useful context every time it solves a problem. Zhang and colleagues call theirs Agentic Context Engineering (ACE, ICLR 2026). Three roles share the work.
A Generator runs the task and produces a trajectory: the record of what it tried and what happened. A Reflector reads that record and writes insights, small lessons about what worked and what failed. A Curator turns the insights into delta context items, tiny additions, and merges them into a context playbook. The playbook goes back into the Generator’s context for the next task, and the loop turns again.
The slide shows a real generated playbook for a test environment called AppWorld. It is a list of short entries under headings such as strategies and hard rules, useful code snippets and templates, and troubleshooting and pitfalls. Each entry has an id. One warns, for example, that when authentication fails you should check credentials from the supervisor app before you retry. Each lesson is small, specific and checkable, and the playbook grows by adding entries, not by rewriting the whole text.
Here is the data flow in miniature. The shapes are ours and illustrative: the playbook is a list of dictionaries, and the prompt is built from it each time.
pythondef solve_with_playbook(task, playbook, llm): # the playbook is a list of {"id", "section", "text"} entries, rendered into the prompt context = "\n".join(f"[{e['id']}] {e['text']}" for e in playbook) trajectory = llm.run(system=context, user=task) # Generator insights = llm.reflect(trajectory) # Reflector: what worked, what failed delta = llm.curate(insights, playbook) # Curator: new entries only return playbook + delta # grow, never rewrite the whole text
If you want these two systems in full, our Week 2 style lessons cover them: the ACE Veanor, GEPA, reflective prompt evolution and prompt engineering from zero. Here we only need their shape: a record of tries, a way to judge them, and a rewrite of the context. The next chapters make that loop sharper.
Chapter 2
Copy the four moves of neural-network training, but pass sentences backward instead of numbers
A coach watches you shoot free throws. You miss. She does not hand you a number. She says, “Your elbow flares out. Tuck it in.” You adjust and shoot again. That sentence did the job of a slope: it told you which way to change and by how much to care.
The lecture’s TextGrad deep dive says language can play the same role in training. TextGrad is built to look just like the neural-network training you may already know. So first we need that training loop, in four moves.
A parameter is a number the model can change, like the weight w below. Take the smallest model there is: output = w × input. The input is 3, the weight starts at 2, and we want the output to be 10.
Real networks have millions of parameters and many layers, so the backward pass uses the chain rule, layer by layer, in reverse. That reverse sweep is backpropagation, and the software that does it for you is called automatic differentiation.
Many modern AI systems are not one network. They are chains of LLM calls, tools and search, each a black box. You cannot differentiate through a call to a hosted model. TextGrad’s idea is to keep the four moves and swap each number for text. The slide lines the two worlds up in a table: input, model, loss and optimizer, in maths, in PyTorch and in TextGrad.
| Piece | PyTorch (numbers) | TextGrad (words) |
|---|---|---|
| Input | a tensor, such as an image | tg.Variable(article): a piece of text |
| Model | ResNet50() | tg.BlackboxLLM(“You are a summarizer.”) |
| Loss | CrossEntropyLoss(): a number | tg.TextLoss(“Rate this summary.”): a written critique |
| Optimizer | torch.optim.SGD(parameters) | tg.TGD(parameters): textual gradient descent |
Even the code reads the same: loss = loss_fn(model(input)), then loss.backward(), then optimizer.step(). The names come from the slide. What happens inside each line is new.
In the forward pass the LLM runs on the variable and writes an output. The loss is another LLM call, a judge, that reads the output and writes a critique in plain language. The backward pass asks an LLM, for each variable that fed the output: “Given this critique, how should this variable change?” The answer is the textual gradient. It flows backward through the chain, so feedback on the last output becomes feedback on earlier variables. The step hands the variable and its textual gradient to an LLM, which rewrites the variable.
Step through one full turn. The left side is the numbers example from above. The right side is the same turn with sentences.
Press Next move to go forward, loss, backward, step. The strip shows the current move. The first box is the numeric turn. The second is the text turn with a summarizing prompt as the thing being trained.
The numbers are exact. The article, the summaries and the critiques are a scripted example written by us, not output from a real model, so that every step is visible. In TextGrad the critique and the rewrite come from real LLM calls.
Look at move three. The number −24 says how much and which way. The sentence says what is wrong and names the variable that caused it. A sentence carries more information than a single number. It also carries more risk, because nothing forces it to be right.
There is no magic in the backward pass. It is one prompt to an LLM, built from three parts: the variable, the output it helped produce, and the critique. Here is the shape.
pythondef textual_gradient(llm, variable, output, critique): # one call per variable that fed the output; the reply IS the gradient prompt = ("Here is a variable, the output it helped make, and feedback on that output.\n" f"VARIABLE: {variable}\nOUTPUT: {output}\nFEEDBACK: {critique}\n" "Say how the variable should change to improve the output.") return llm(prompt) # a few sentences of advice def step(llm, variable, gradients): prompt = f"Rewrite this variable.\nVARIABLE: {variable}\nADVICE: {' '.join(gradients)}" return llm(prompt) # the updated text
The failure mode is easy to name. Symptom: the prompt grows longer each turn, advice contradicts earlier advice and the answers get worse. Measurement: run each new version on a held-out set of examples and compare scores; an update that wins on one example can lose on the rest. Fix: keep an update only if the held-out score does not drop. That safeguard is our advice, in the spirit of the lecture: a text gradient is a suggestion, and the scorer has the last word.
The lecture ends this section with a question on a single slide. We have used LLMs to optimize prompts. Can we use the same propose, evaluate and refine loop to optimize something else? The next chapter shows the loop in its barest form, and then in its most general form.
Chapter 3
Compare a model that critiques itself with one that reads a list of tries and the numbers they earned
Two students write the same essay. The first rereads her draft, notices a weak paragraph and fixes it. The second hands drafts to a teacher who returns a grade each time, and he keeps the grades in a list on his desk. After ten drafts he can see which changes raised the grade. Both loops improve the essay. They use different feedback.
The lecture names two ways to let an LLM optimize without training it. The first is self-refine. The second is optimization with feedback from a scorer, which is the idea in the paper Large Language Models as Optimizers (Yang and colleagues, Google DeepMind, ICLR 2024). Its method is called OPRO, short for Optimization by PROmpting.
Self-Refine (Madaan and colleagues, NeurIPS 2023) uses one model, M, for everything. M writes an output. Then M is asked to give feedback on its own output. Then M is asked to refine the output, given that feedback. The loop can repeat. The loop needs no scorer and no training.
The slide shows two examples. In the first, a user says, “I am interested in playing table tennis,” and the first reply is a flat “I’m sure it’s a great way to socialize, stay active.” The model’s feedback is that the reply gives no information about table tennis and lacks understanding of what the user needs. The refined reply is warmer and asks a question: have you played before, or are you looking to learn?
In the second example the task is code: add the numbers from 1 to N. The first answer is a loop. The feedback says the code is slow because it uses brute force, and that a formula is better. The refined code returns (n * (n + 1)) // 2. The loop runs in n steps. The formula takes the same few steps for any n.
Self-refine works when the model can recognize a flaw it did not avoid. Its limit is that the critic and the writer share the same blind spots. If the model does not know a fact, its feedback will not supply it.
OPRO brings in an outside judge. The slide draws the loop. An objective function evaluator turns each generated solution into a score. The LLM, acting as the optimizer, reads a meta-prompt and writes new solutions. The loop stops after some tries and returns the top solutions.
The meta-prompt has two parts. One is the task description, in plain language. The other is a list of solution and score pairs: earlier tries, each with the number the scorer gave it. The LLM reads the list, spots what the high scorers share, and writes a new try. The scorer then scores it, and the new pair joins the list.
The model never sees a gradient. It sees a table of past results, which is exactly what a person tuning by hand would look at. The paper’s demonstrations are linear regression and the traveling salesman problem (visit every city once and return home, as short a trip as possible). Its main application is prompt optimization: find the instruction that maximizes accuracy on a task. The abstract reports that the best prompts OPRO found beat human-designed prompts by up to 8% on the GSM8K maths set and up to 50% on Big-Bench Hard tasks.
The slide’s meta-prompt for a traveling-salesman example lists points with coordinates, then several previous routes (“traces”) with their lengths, arranged in descending order of length so the best sit last. It ends with an instruction to give a new route that is different from all those above and shorter. Build one yourself below. You are the optimizer. Click cities in the order you want to visit them, press Score my tour, and watch the prompt grow.
Click cities A to G in the order of your tour. Score it, or let the stand-in propose a change to the best tour. The box shows exactly what an LLM would read. Slide the number of pairs kept and watch the prompt shrink.
Seven made-up cities on a grid. Every length is exact straight-line distance. The shortest possible tour was found by checking all 720 orders that start at A. The stand-in is a seeded random reversal of part of the best tour, not a language model. Prompt size is estimated as one token per 4 characters.
Three details of the prompt matter, and each is a design choice you can see in the box. First, the pairs are sorted, worst first and best last, because a model weighs recent text heavily. Second, only the best few are kept. A long history costs money and buries the signal, so OPRO-style systems keep a top slice. Third, the closing instruction says different from all of the above, or the model may simply copy its best try.
Symptom: the proposals stop changing, or the same try appears again and again. Measurement: count how many proposals in the last ten tries are duplicates of earlier ones, and plot the best score against the number of scorer calls. Fix: keep the “different from all above” instruction, show a wider slice of the history, or ask for several proposals per step and score them all. Each fix changes the prompt, not the model.
Where the scorer is trustworthy, OPRO-style loops are strong. Where the scorer is another model’s opinion, the loop learns to please that opinion, and that is a different risk, which Chapter 8 returns to. We also have a related lesson on LLM optimizers for a different problem, tuning parallel programs: LLM Optimizers for Parallel Programs. It is a different paper from OPRO, but it uses the same propose, score, keep loop with profiler feedback.
Chapter 4
See stories, agent code, charts, images and video all fit the same propose, make and judge loop
A carpenter, a chef and a gardener use different tools. Watch them work and the same pattern shows: try something, look at the result, adjust, try again. The tool changes. The pattern stays.
The lecture now makes that point with five quick examples. Each is a published system, and each improves something that is not a prompt: a story, the code around an agent, a chart, a picture and a video. Slides 18 to 22 are a tour, and the tour has one lesson. If you can make a thing and judge the result, an LLM can propose the next version.
Writing. Re3 (Yang and colleagues, EMNLP 2022) writes long stories. It begins with a premise, one or two sentences. Then it plans: it prompts a language model for a setting, characters and an outline. It drafts: it writes story continuations from the plan and the story so far. It rewrites: it ranks several candidate continuations for plot coherence and relevance to the premise. It edits: it changes the chosen continuation so facts stay consistent over a long story. The loop returns to drafting until the story ends.
Agent harness. A harness is the code around a model that decides what goes into its context, which tools it may call and how its memory works. Meta-Harness (Lee and colleagues, 2026) treats that code as the thing to optimize. A proposer reads a filesystem holding all earlier experience, then proposes new harness code. The harness plus an LLM runs on tasks and is evaluated. Everything is stored back in the filesystem: the proposed code, the reasoning traces and the score. The next proposal reads all of it. Next week’s lecture is about harnesses; our lesson on Meta-Harness goes deeper.
Data visualization. MatPlotAgent (Yang and colleagues, Findings of ACL 2024) writes plotting code for scientific charts. Its key move is visual feedback: the code runs, the chart is rendered as an image, and a model that can read images says what looks wrong. The slide shows the same chart requests with and without that feedback, next to the ground truth. With feedback the charts sit closer to the target.
Images. Idea2Img (Yang and colleagues, ECCV 2024) turns a rough idea into a polished picture. An image model makes pictures from text, GPT-4V looks at them, and the loop rewrites the text prompt, round after round. The slide compares the first output from the idea alone with later rounds on tasks such as object counts, scene text and style transfer.
Video. VISTA (Do and colleagues, 2025) is a test-time self-improving video-generation agent. The slide shows two prompts: a forehead creasing with worry at bad news, and a spaceship entering hyperdrive with stars streaking past. The direct prompt gives a plain result. The agent’s result is closer to the words. “Test-time” means all of this happens while generating, with no retraining.
Put the five side by side and three slots appear. The proposer writes the next version of the thing. The maker turns that text into a result you can inspect: it runs code, draws the chart or generates the image. The judge reads the result and returns feedback. The slots hold different things in each system. Pick a system below and see the loop re-label itself.
Choose a system. The loop shows what the proposer writes, what the maker produces and what the judge returns. The dot shows the order of one round.
The labels summarize what each slide shows, in our words. Whether the judge returns a number or a written critique differs by system and is marked on the judge box. Prompt (APE) is Chapter 1’s example, kept as the baseline.
The judge slot is where systems differ most. APE and the harness loop get a number from running the thing on tasks. A chart or an image has no exact formula for “looks right”, so a second model reads the picture and returns written feedback. A number is cheap and hard to argue with. Written feedback can say why, but it can be wrong.
All five systems reduce to a few lines. The details sit inside the three functions you pass in.
pythondef optimize(seed, propose, make, judge, rounds=10): history = [] # (candidate, result, feedback): the memory best = (seed, None, -1e9) cand = seed for _ in range(rounds): result = make(cand) # run the code, render the chart, generate the image score, feedback = judge(result) # a number, a critique, or both history.append((cand, result, feedback)) if score > best[2]: best = (cand, result, score) cand = propose(history, best) # an LLM reads the history and writes the next candidate return best
Failure mode. The symptom is a score that keeps rising while the outputs look worse to people. This happens when the judge is a model and the proposer learns what it likes. To measure it, collect 20 results, rate them yourself and compare your ratings with the judge’s. If they disagree, the loop is climbing the wrong hill. The fix is to anchor the judge with something exact where you can (a test that must pass, a size limit, a unit check) and to use a different model for judging than for proposing.
That brings the lecture to its turn. Everything so far improves a thing that a person could also improve. What about problems no person has solved? The next slide asks it in one line: what about scientific discovery?
Chapter 5
Meet two open problems, learn why the answer is a short program, and test candidate programs yourself
Ask a chatbot to solve an open problem in mathematics and it will write a confident answer. You cannot tell whether it is right without a lot of work. Now ask it for a short program that builds an answer. You run the program. A checker measures the result. You do not need to trust the model at all.
That switch is the heart of FunSearch, a method from DeepMind (Romera-Paredes and colleagues, Nature, December 2023). Slide 24 states what it achieved with LLM-driven search. It found new constructions for the cap set problem in eight dimensions, lifting the record from 496 to 512. And it found bin-packing heuristics that beat standard baselines on the tested benchmarks. We start with the two problems.
Take the numbers 0, 1 and 2. In n dimensions, a point is a list of n of them. In 8 dimensions one point is (0,2,1,0,1,2,2,0), and there are 38 = 6,561 points. A line is three different points that sum to zero in every coordinate, when you count modulo 3 (so 2 + 2 = 4 becomes 1). A cap set is a set of points with no three on a line. The question: how many points can a cap set hold?
Work it out in two dimensions, with 9 points. The points (0,0), (1,1) and (2,2) sum to (3,3), which is (0,0) modulo 3, so they are on a line. The points (0,0), (0,1) and (1,0) sum to (1,1), so they are not. Click points and see the rule at work.
Each button is a point (a, b). Pick as many as you can with no three on a line. Red points and lines show a broken rule.
Exact. The page checks every triple of your points. The largest cap set in two dimensions has 4 points; the page found that by testing all 512 subsets of the 9 points. The FunSearch paper draws a size-4 cap set in its Figure 3.
At n = 2 the answer is 4 and a computer checks it in a blink. At n = 8 there are 6,561 points and an astronomical number of subsets. The best known set before FunSearch had 496 points. FunSearch found one with 512. The paper notes that the earlier record relied on a complex combination of smaller cap sets, while FunSearch found its set from scratch.
The second problem is everyday. Pack items of different sizes into the fewest bins without going over any bin’s capacity. The slide’s example: capacity 10 and items 6, 5, 3, 2, 2, 2. One valid packing uses 3 bins: [6,3], [5,2,2], [2]. A better packing exists: [6,2,2] and [5,3,2] use only 2 bins. Finding it needs you to see all the items at once.
In online bin packing the items arrive one at a time and each must be placed at once. You cannot reorder. So you need a heuristic: a rule of thumb that picks a bin for each item. Two classic rules are first fit (the first bin with room) and best fit (the bin that will have the least room left over).
Slide 27 states both problems in one line. We want the best input to a function, but we can only ask the function for its value at points we choose, and every question costs time.
The optimizer sees only the history of pairs, and from it chooses the next x. This is exactly the setting of Chapter 3. What FunSearch adds is a clever choice of X.
Slide 28 defines it. A search space is the set of candidates an optimizer can explore. FunSearch searches over Python functions with a fixed input and output format. For cap sets the function is priority(element, n): it scores each point, and a fixed loop adds the highest-priority point that does not break the rule (the paper describes this loop as the algorithm skeleton). For bin packing it is heuristic(item, bins): it scores each bin, and the item goes to the best one. The evaluator runs the tests and returns a score: the size of the cap set, or the number of bins used. The output is a reusable program.
Why programs? A cap set of 512 points is a long, opaque list. The program that builds it is short, and people can read it. The paper reports that reading the program taught the authors something about the structure of the set. A program is also cheap to test: run it, count, done.
Now write a few programs yourself. Below are four heuristic functions for online bin packing. Choose one, slide the number of items, and watch the bins fill. Three are classic. The fourth is ours: it takes a very tight fit if it can, and otherwise picks the bin with the most room.
Items are made up: sizes drawn uniformly between 0.1 and 0.5 of a bin, from a fixed seed. The evaluator is exact. “Extra bins” compares with the lower bound, the total size rounded up. “Tight or roomy” is our own invention in the spirit of what the paper reports about FunSearch’s best heuristics (take the bin only if the fit is very tight); it was not evolved and is not the paper’s code.
The paper’s own result on this problem: its best heuristics beat first fit and best fit on every benchmark it tried, and on Weibull-distributed instances of 100,000 items they came within 0.03% of the lower bound. They also noticed a common strategy, close to our fourth program: assign to the fullest bin only if the fit is very tight, and otherwise leave more room.
Failure mode. The symptom is a program that scores well on your test items and badly in production. The measurement is to score it on a second set of instances it never saw. The fix is to score every candidate on a mix of instances, as the paper does, and report the average.
Chapter 6
Follow one FunSearch round from the pool to the prompt and back, and see why it runs on separate islands
A seed company wants a better tomato. Each season it grows a field, tastes the fruit, saves seeds from the best plants and plants those next year, with a few lucky changes. After many seasons the tomato is much better. Nobody designed it. The company only chose, varied and measured.
Slide 30 names this recipe: an evolutionary algorithm improves a population (a group of candidates) by repeated selection, variation and evaluation. The slide’s pseudocode is short.
pythonpopulation = initialize_programs() for generation in range(budget): parents = select(population) # choose promising parents children = vary(parents) # mutation, crossover evaluate(children) # measure quality population = retain(population, children) # survivor selection
| Operation | Purpose | In FunSearch |
|---|---|---|
| Selection | choose promising parents | pick an island, then pick programs, favouring high scores and short code |
| Mutation and crossover | make variations | the LLM writes a new program after reading two parents |
| Evaluation | measure quality | run the program on test inputs and score it |
| Survivor selection | decide what to keep | add correct programs to the pool; wipe the worst islands now and then |
Classic evolution varies a candidate by flipping a bit or swapping a number. On source code that almost always breaks the program. FunSearch (slide 31) lets an LLM do the varying instead. It reads real programs and writes a new one that makes sense.
The trick is the prompt. The paper calls it best-shot prompting. It samples k = 2 programs from one island, sorts them by score, and names them priority_v0 (the lower score) and priority_v1 (the higher). It then ends the prompt with the header of a third function, priority_v2. The LLM only has to finish the function. Because it sees two programs, it can spot patterns across them and generalize.
promptdef priority_v0(element, n): """Returns the priority with which we want to add `element` to the cap set.""" return 0.0 # the lower-scoring parent def priority_v1(element, n): """Improved version of `priority_v0`.""" # ... the higher-scoring parent, with its real body ... def priority_v2(element, n): """Improved version of `priority_v1`.""" # the model writes everything after this line
The data flow is plain text in, plain text out. The prompt goes to a pretrained model with no fine-tuning (the paper used Codey, built on PaLM 2). The reply is Python source. The evaluator runs it, and a crash, a timeout or an invalid result just discards it.
Which programs should be parents? Always the best one is greedy: it finds small gains fast and gets stuck. A uniform pick wastes tries on poor programs. Slide 31 shows the usual middle path, a softmax: each program is picked with a chance that grows with its score.
The slide labels the ends: small T exploits (the best program almost always wins) and large T explores (everyone gets a chance). A worked example with three programs scoring 0.6, 0.5 and 0.2. At T = 0.1 the weights are e6 = 403.4, e5 = 148.4 and e2 = 7.4, which sum to 559.2. The chances are 72.1%, 26.5% and 1.3%. At T = 1 the weights are 1.82, 1.65 and 1.22, which sum to 4.69. The chances become 38.8%, 35.1% and 26.0%. One knob moved the pick from near-certain to nearly even.
Slides 32 and 33 add the main protection against getting stuck. FunSearch does not keep one pool. It keeps several, called islands, and each evolves on its own. The paper says that preserving diversity is crucial to avoid local optima.
Run it below. The stand-in model improves a parent by a small random amount, and about one child in eight crashes and is thrown away. This device shows the machinery. It makes no claim about how much islands help; the paper’s argument for them is about diversity.
Each column is an island. Each dot is a program, higher is a better score. Press Run 1 iteration to sample two parents (teal rings) and add a child (green ring). Change the temperature. Press Reset the worst half to see islands refill.
Illustrative. Scores run from 0 to 1 and all programs start at the seed score of 0.30. A stand-in rule, not an LLM, makes each child: the better parent’s score plus a random change with a small upward lean. The pick chances are the exact softmax from the equation above.
Failure mode. The symptom is every island ending up with near-copies of one program, so the search stalls. The measurement is the number of distinct clusters per island and the gap between the islands’ best scores. The fix is more islands, a longer time between resets, or a higher temperature. Each costs something. More islands spend more evaluations on weak ones, and a high T wastes tries on weak parents.
Chapter 7
Widen the search from one function to a whole codebase, then give an agent a fixed budget and a ratchet
FunSearch changed one function and left a fixed skeleton around it. That was a smart limit, and also a cage. A real engineer fixing a slow system changes several files, tunes settings and cares about speed, memory and correctness at once. The lecture next shows two systems that open the cage in two different ways.
AlphaEvolve (DeepMind, white paper 2025) is the successor to FunSearch. Slide 34 lists what changed as four pairs, old on the left and new on the right.
| Axis | FunSearch | AlphaEvolve |
|---|---|---|
| Search scope | a single function | evolution of a full program |
| Edit mode | the model writes the whole function | SEARCH/REPLACE diffs |
| Models | one pretrained code model | stronger LLMs, with richer context and feedback |
| Objectives | one metric | several metrics together (multi-objective) |
Take the edit mode first. A full-program edit could mean the model rewrites thousands of lines to change three. A diff says only what changes. In a SEARCH/REPLACE diff, the model quotes a block that exists in the current program, then gives the block that replaces it. A small program applies it with plain string matching.
diff the model writes<<<<<<< SEARCH best = min(candidates, key=cost) ======= best = min(candidates, key=lambda c: cost(c) + 0.1 * c.size) >>>>>>> REPLACE pythondef apply_diff(source, search, replace): if source.count(search) != 1: # the quote must match exactly once raise ValueError("diff does not apply") # a bad diff is just a failed try return source.replace(search, replace)
Diffs have two wins. They save tokens, so each round is cheaper. And they keep the unchanged parts byte for byte, so a long program is less likely to be damaged by an edit. The price is that a quote that misses is a wasted try, which the code above treats as a plain failure.
The objective axis matters as much. Real engineering has several goals: faster, smaller, still correct. AlphaEvolve lets the evaluator return several scores and uses them together. The white paper’s abstract reports four results. It found a more efficient scheduling algorithm for data centers. It simplified a hardware accelerator circuit without changing what it does. It sped up the training of the LLM behind AlphaEvolve itself. And it found a way to multiply two 4×4 complex matrices with 48 scalar multiplications, the first improvement over Strassen’s algorithm in that setting after 56 years. We cover the system in full in the AlphaEvolve Veanor and the method behind it in our FunSearch lesson.
The other system on the slides is smaller and easier to run at home. Autoresearch is a public repository by Andrej Karpathy. An AI agent follows a plain-text instruction file, program.md, to propose ideas, edit code and run experiments that improve language-model pretraining. The rule is a fixed compute budget: 5 minutes per experiment, so about 100 experiments in one night.
The instruction file is a loop. The agent looks at the git state (git is the tool that records versions of code). It edits train.py with one idea and commits the change. It runs the training and reads the final line of the log, val_bpb: validation bits per byte, how many bits the model needs for each byte of held-out text, where lower is better. If the line is missing, the run crashed and the agent reads the trace. It records the result in a table. If the number improved, it keeps the commit. If the number is equal or worse, it runs git reset and the change vanishes.
That last step is the ratchet. A ratchet turns one way only. The best result so far can only get better, because every worse experiment is erased. The fixed 5 minutes is the other half of the design: it makes every experiment comparable, so a lower number means a better idea and not a longer run. Run a night below. Then switch the ratchet off and keep every change.
Illustrative toy, not a real training run. Each experiment changes the score by a random amount: on average slightly worse (+0.003) with a spread of 0.02, because most random edits to a tuned program hurt. The score starts at 1.200. Both rules see the same sequence of changes. The 8-hour night and the 5-minute default follow the slide.
Read the picture the way the agent’s own graph reads: a staircase that only goes down. Without the reset the line wanders. The agent still tried exactly the same ideas, but it kept the ones that hurt.
Slide 36 asks that question and slide 37 answers with a benchmark. EdgeBench (Zhu and colleagues, 2026) collects 134 real-world, day-long tasks in six families. There are 39 tasks in scientific problems and machine learning, 36 in systems and software engineering, 19 in combinatorial optimization, 19 in professional knowledge work, 13 in formal maths and theorem proving, and 8 in interactive games and simulators. Each task gives real feedback the agent can use to improve.
Slide 38 previews homework 1, which uses OpenEvolve, an open-source system in the AlphaEvolve family, in a notebook. We do not reproduce the assignment. The three ideas it needs are all above: a program to evolve, an evaluator that returns scores and a loop that keeps what wins.
Failure mode. The symptom is an agent that reports a better score you cannot reproduce. The measurement is to rerun the kept change from a clean checkout with a different random seed. The fix is to make the evaluator hard to cheat: fixed data, fixed budget, no edits to the scoring code. If the agent may edit the scorer, it will eventually do so.
Chapter 8
Find out how to judge research ideas when no program can score them, and step through a system that writes whole papers
Imagine you are on the review committee for a research conference. Two anonymous one-page ideas land on your desk. Neither has results. Both are interesting. Which is more novel? No test script answers that. You read, you compare with what you know and you give a number from 1 to 10.
That is the problem on slide 39. Everything in Chapters 5 to 7 had a numerical grader: the size of a cap set, the bins used, a validation score. Most great discoveries had none when they were made. The slide lists seven: CRISPR gene editing in biology, general relativity in physics, the discovery of penicillin in chemistry, dark matter in astronomy, plate tectonics in geology, mRNA vaccines in medicine and backpropagation in computer science. Nobody could run a function to score any of them in advance.
So the lecture turns to two questions. Can an LLM come up with research ideas that experts rate as novel? And can an AI system carry a whole project from idea to paper?
Si and colleagues (ICLR 2025) ran a careful experiment to find out. The hard part is not asking the model. It is making the comparison fair. People and models write ideas in different styles, and a reviewer may guess who wrote what. So the study controls the confounders, which are the things other than “human or AI” that could explain a difference.
The slide shows the design. There were 7 topics in natural language processing: bias, coding, safety, multilingual, factuality, maths and uncertainty. Over 100 NLP researchers took part, some writing ideas and some reviewing. Three conditions were compared, each with 49 ideas. Condition 1 was ideas written by human experts. Condition 2 was ideas from an LLM ideation agent. Condition 3 was the AI ideas again, but with a human choosing the best ones, a “human rerank”. A group of experts (79 of them on the slide) reviewed every idea blind, which means they did not know who wrote it.
| Condition | Ideas | Novelty score |
|---|---|---|
| 1. Human experts | 49 | 4.84 |
| 2. AI ideas | 49 | 5.64 |
| 3. AI ideas, human reranked | 49 | 5.81 |
The abstract draws the careful conclusion. The AI ideas were judged more novel, and the gap is statistically significant (p < 0.05). They were judged slightly weaker on feasibility. The paper also found two open problems in building research agents: self-evaluation fails, so the LLM cannot reliably pick its own best ideas, and the agent’s generation lacks diversity. That is why condition 3 uses a human to rerank. The authors also admit that human judgements of novelty are hard even for experts, and they propose a follow-up in which researchers execute the ideas, so that the final outcome, not just the opinion, can be measured.
Do not read “more novel” as “better science”. A novelty score is a reviewer’s opinion of an idea on paper. Whether the idea works is a different question, and the one the follow-up aims to answer.
The next slides show a system that tries the whole path. The AI Scientist (first paper: Lu and colleagues, 2024; a Nature article, Towards End-to-End Automation of AI Research, in 2026) builds a research project in three phases, drawn on the slide as three lanes. Step through them below. The device follows the slide’s boxes.
Press Next stage. The lit box is the current stage. Stage 8 loops back to stage 5 two times before the paper is written, as the loop in the slide shows.
The stages and their order follow the lecture slide, which is the Nature paper’s overview figure. The number of experiment rounds (3) is our choice for the demo; a real run decides for itself. The artifact lines are our own plain-words descriptions, not output from the system.
Two details deserve a close look. In stage 2 the system searches the literature with Semantic Scholar and drops an idea that already exists. The AI Scientist therefore uses an outside source for novelty and does not trust the model’s memory. And stage 12 is an LLM paper reviewer: the system grades its own paper with a model that plays a conference reviewer.
What did it achieve? The first paper reported that each idea becomes a full paper for under $15 and that its automated reviewer gets near-human scores. The 2026 abstract goes further. It describes the strongest demonstration so far of automating the whole process: a manuscript made by the system passed the first round of peer review at a major machine-learning conference workshop, one with a 70% acceptance rate. It tested two modes. The focused mode starts from human-provided code templates for a specific topic. The open-ended mode needs no template and uses agentic search. The authors also warn of risks: such systems could tax overwhelmed review systems and add noise to the scientific literature.
For the earlier systems in more depth, see our AI Scientist Veanor and the AI Scientist v2 Veanor.
Failure mode. The symptom is a polished paper whose claim does not hold. The measurement is to rerun its code from the saved scripts and compare the numbers in the text with the numbers the run prints. The fix is to keep every artifact (the scripts, the logs and the plots) so that anyone can repeat the check. Without a grader, the audit trail is the only grader.
Chapter 9
Watch what a checker does to a long chain of steps, then read the three open challenges the lecture ends on
In 1993 Andrew Wiles stood in front of a room and announced a proof of Fermat’s Last Theorem, a claim that had resisted every mathematician for 350 years. Two months into the check, a reviewer asked a question that exposed a gap. Wiles needed another year to repair it. Even a great proof can hide one broken link, and finding the link took months of expert reading.
That story, told in Anthropic’s report on the topic, is the point of slides 43 to 46: verification is important for discovery. A system that makes claims faster than people can check them is only as good as its checker.
A proof assistant is a program such as Lean in which a proof is written in a strict formal language, and the program checks every step. If Lean accepts the proof, the theorem is proved relative to the basic axioms. There is no “probably right”. The difficulty is that formal proofs must spell out every step a human would skip.
Slide 43 shows how DeepSeek-Prover-V2 (Ren and colleagues, 2025) works with Lean. Two models take two jobs. DeepSeek-V3, a general model, decomposes a hard theorem into smaller subgoals, with placeholders for the proofs still missing. DeepSeek-Prover-V2-7B then attempts to prove each subgoal in Lean. Lean checks every attempt. The loop is the one you know: propose, check, keep. The score is binary and exact. The paper’s abstract reports that its largest model reaches an 88.9% pass ratio on the MiniF2F-test benchmark and solves 49 of 658 problems from PutnamBench.
Slide 45 points to Anthropic’s post Formalizing Fermat’s Last Theorem (4 September 2026). It reports the first complete computer-checked proof of the theorem. Claude worked largely autonomously for 11 days to write it in Lean. The numbers from the post: about 13 million lines of Lean, proofs of 30,300 theorems along the way and 29,500 of them used in the final proof. Dozens of Claude agents shared the work.
Two details teach more than the totals. First, early attempts failed. The agents quickly lost track of the project’s state and stopped working together effectively. The effort succeeded after the team switched to Prove2Me, a collaborative platform that keeps a directed acyclic graph of theorem statements, so each agent can see what to prove next. Memory, in other words, was part of the harness. Second, the finished proof was checked by Lean and uses only Lean’s three standard axioms. A separate comparison confirmed that the statement proved matches the one in Mathlib, the community’s library of formalized mathematics. The checker, not the author, gave the proof its authority.
The last clip on the slides is titled Multi-agent = parallel test-time compute. Dozens of agents working at once is a way to spend more computation while answering, and the Fermat project did that at scale.
A proof is a chain. If one link breaks, everything after it is in doubt. Suppose a model writes each step wrongly 1 time in 100. A checker looks at each step. If the checker misses a wrong step with probability q, then each step hides an undetected error with probability 0.01 × q. For a chain of n steps, the chance that at least one error survives is 1 − (1 − 0.01 × q)n.
A worked case: n = 29,500 steps and a strong judge that misses 1% of wrong steps. Then 0.01 × 0.01 = 0.0001 per step, and the chance of at least one hidden error is 1 − 0.999929,500, about 94.8%. About three wrong steps are expected to slip through. With an exact checker, q = 0, and the chance is exactly 0. Try it.
Illustrative model: every step is wrong with probability 1%, a made-up rate, and the miss rates of the two judges are also made up. The formula is exact. 29,500 is the number of theorems the final Fermat proof used, from Anthropic’s report. A real checker would not be this simple, but Lean’s exact check is the case q = 0.
Look at the 100-step case. Even a weak judge leaves only about a 10% chance of a hidden error, and many people would accept that. At 29,500 steps the same judge hides about 30 wrong steps and the proof is certainly broken. This is why long discoveries need exact checkers, and why the lecture insists on them.
Failure mode. The symptom is a long output that looks fine at every spot you read. The measurement is the number of steps times the miss rate, as above. The fix is to push as much of the check as possible into an exact program: tests, a type checker, Lean. Use a model judge only for what no program can check, and then audit a sample by hand.
Slide 47 closes the technical part with three questions, each tied to something you met in this lesson.
The final slides turn the page. The next topic is from memory to harness. A slide sorts memory into short-term (sensory and working memory) and long-term (implicit and explicit, the latter holding facts and events). Then the course moves on to evolving the harness around a model. The practical notes were short. Enrollment status follows during the week. For-credit enrollment is capped at 20 to 30, and dedicated listeners are welcome as space allows. A project preference form, with tentative teammates and directions, is coming.
Chapter 10
Keep the numbers, the terms, a checklist and the core loop in code, and find where to go next
One loop ran through the whole lecture: propose, make, score, remember. A prompt, a program, a harness or an idea fills the first slot. A test, a judge, a benchmark or a Lean proof fills the third. The model never changes. The record of tries, passed back into its context, is what learns. How far the loop goes depends on how honest the scorer is.
| Number | What it is | Where it comes from |
|---|---|---|
| 496 → 512 | size of the best cap set in 8 dimensions, before and after FunSearch | slide 24 and the FunSearch paper |
| 6,561 | points in {0,1,2}8, which is 38 | slide 26 |
| 4 | largest cap set in 2 dimensions | FunSearch paper, Figure 3 |
| 3 and 2 | bins in the slide’s packing of 6, 5, 3, 2, 2, 2 (capacity 10), and in a better packing | slide 26, our check |
| k = 2 | programs in a FunSearch prompt, sorted by score | FunSearch paper, Methods |
| 0.03% | gap to the lower bound for 100,000 Weibull items | FunSearch paper |
| 8% and 50% | best OPRO prompts over human prompts, on GSM8K and Big-Bench Hard (up to) | OPRO abstract |
| 48 and 56 | scalar multiplications for 4×4 complex matrices, and years since Strassen | AlphaEvolve abstract |
| 5 min, ~100 | minutes per experiment, experiments per night in autoresearch | slide 35 |
| 134 | day-long tasks in 6 families in EdgeBench | slide 37 |
| 4.84, 5.64, 5.81 | novelty of human, AI and reranked-AI ideas, 49 ideas each | slide 40, Si et al. |
| < $15, 70% | cost per paper (2024), and the workshop acceptance rate its 2026 paper passed | the two AI Scientist abstracts |
| 11 days | time for Claude to formalize Fermat’s Last Theorem in Lean (13 million lines, 29,500 theorems used) | Anthropic, 4 September 2026 |
| 88.9%, 49 of 658 | DeepSeek-Prover-V2 on MiniF2F-test and PutnamBench | its abstract |
| Term | Meaning in one line |
|---|---|
| Context, prompt | everything the model reads before it writes; the part you wrote on purpose |
| Black box | a function you can run for a score but cannot differentiate |
| Textual gradient | advice in words, from an LLM, on how to change a variable |
| Meta-prompt | the optimizer’s prompt: the task plus scored earlier tries |
| Search space | the set of candidates the optimizer may try, for FunSearch, programs |
| Island | one separate pool of programs, kept apart to preserve diversity |
| Best-shot prompting | show the best sampled programs, sorted, and ask for an improved one |
| Ratchet | keep a change only if the score improves; reset the rest |
| Verification | an exact program checks the claim, such as a test or a Lean proof |
This is a runnable sketch of the FunSearch shape: islands, a scorer, best-shot prompts and resets. Pass in any function that turns a prompt into Python source.
pythonimport math, random SEED = "def heuristic(item, bins):\n return -(bins - item)\n" # best fit as the first program def evaluate(src, streams): # the scorer: run the program on test inputs; None means crash or invalid try: scope = {}; exec(src, {"np": __import__("numpy")}, scope) # use a real sandbox with limits return -sum(bins_used(scope["heuristic"], s) for s in streams) / len(streams) except Exception: return None def pick_two(island, T): # softmax on the scores: small T exploits, large T explores top = max(s for _, s in island) w = [math.exp((s - top) / T) for _, s in island] return random.choices(island, weights=w, k=2) def best_shot_prompt(parents): parents = sorted(parents, key=lambda p: p[1]) # worst first, best last text = "" for i, (src, _) in enumerate(parents): text += src.replace("def heuristic", f"def heuristic_v{i}") + "\n" return text + f"def heuristic_v{len(parents)}(item, bins):\n \"\"\"Improved version of heuristic_v{len(parents)-1}.\"\"\"\n" def evolve(llm, streams, n_islands=10, iters=1000, T=0.1, reset_every=200): islands = [[(SEED, evaluate(SEED, streams))] for _ in range(n_islands)] for t in range(1, iters + 1): isl = random.choice(islands) # an island at random src = llm(best_shot_prompt(pick_two(isl, T))) # text in, Python source out score = evaluate(src, streams) if score is not None: isl.append((src, score)) # correct programs join the same island if t % reset_every == 0: # wipe the worst half, clone a winner into each islands.sort(key=lambda I: max(s for _, s in I), reverse=True) half = n_islands // 2 for j in range(n_islands - half, n_islands): islands[j] = [max(islands[j - (n_islands - half)], key=lambda p: p[1])] return max((p for I in islands for p in I), key=lambda p: p[1])
The function bins_used runs the heuristic over one stream of items and counts the bins. It is the same few lines as our device in Chapter 5. Everything the paper adds at scale (a distributed database, many samplers, clusters by signature, sandboxes) is engineering around this skeleton.
Week 2 improved context by hand and by rule. This week made the improving itself an LLM’s job and pushed it to real discovery. The thread continues with the harness, the code that builds the context. Our GEPA and harness optimization lessons, and self-improving harnesses, pick it up. For the Stanford view on the same ideas see CS 329Z, the optimization lecture.
This lesson follows Lecture 3 of MIT MAS.S62 How to AI an AI for (Almost) Anything (Fall 2026), from the MIT Multisensory Intelligence group, taught by Paul Liang of the MIT Media Lab and EECS. The lecture slides are the course’s own. We re-teach each idea in our own words and devices, and we add the numbers and details from the papers and posts linked above. Errors are ours.
Now press Present or Teach and explain one full turn of the loop out loud, from memory: what the model reads, what it writes, who scores it and what is kept. Then go back to the hidden terrain at the top, set the tries to 5 and to 40, and explain why reading a scored history helps more as the tries grow.