In Stanford's CS329Z, Michael Ryan compares context optimization and weight optimization for improving AI agents. With good data and evaluation, you can adapt a system to a particular task through prompts, examples, or model training. The approaches can also work together. The lecture covers GEPA for automatically improving prompts, GRPO for learning by comparing model responses, and on-policy distillation, where a teacher gives feedback on a student model's actions.
1. The Starting Point: Good Prompts Are Hard to Guess
Ryan begins by announcing a guest lecture on Terminal-Bench the following Monday. He then recalls having to convert existing research materials into slides for the class. Codex reverse-engineered how Keynote files are stored and wrote conversion code. He found it impressive enough to call it something like an AGI moment.
The lecture opens with a poll asking which prompt is most effective for solving math problems with Google's older PaLM 2L model. The options were:
"Let's think step by step."
"Take a deep breath and solve this problem step by step."
"Let's combine mathematical ability and clear thinking to find the answer quickly and accurately."
Students split about evenly across the options. In the experiment, the second phrase did best. Ryan says intuition alone can't easily explain why one phrase is better, and the result can depend on the model.
"You can't know in advance that one prompt will be better than another. Set up an evaluation, run the prompts, and see what works best."
This is the lecture's central idea of optimization. Instead of specifying every behavior individually, use data and evaluation to define what you want and improve the system based on measured performance.
The lecture goes from the prerequisites for optimization to context optimization, weight optimization, optimization by agents, and how to choose an approach in practice.
2. Three Things You Need to Start Optimizing
Ryan identifies three requirements.
- Data. Execution traces, good examples, human feedback, or similar input.
- A system. A language model and the workflow or agent around it.
- Evaluation metrics. Accuracy, exact match, language-model-based judging, cost, latency, and so on.
You need a system to improve, data to learn or test from, and a way to measure whether a change helped.
He asks whether prompt optimization remains necessary as models improve. Small prompt tricks, such as changing a single word, may matter less. Last-mile adaptation to a specific task will still be needed.
"Model companies will make models good at general tasks. When your system has a particular purpose, you still need a last step that fits it to exactly what you want."
That's why he prefers context optimization to "prompt optimization." It covers arranging instructions, examples, and other inputs for the job, beyond finding clever wording.
Take a system that extracts event dates and times from email. "Find the date and time" is simple, but the requirements may include outputting dates in an ISO format a calendar app can read and handling emails with several events. People may not enumerate every requirement up front. Examples and evaluations can surface requirements they left implicit.
"Sometimes the right evaluation captures your intent better than an explanation you wrote yourself."
Optimization can improve consistency and reliability, adapt a system to a domain, reduce cost and latency by using a smaller model, and help a system improve from experience. Good evaluation also lets you reoptimize when you switch models.
3. Few-Shot Examples: What to Include and in What Order
The first context optimization method is few-shot prompting. Include a few examples of the task in the prompt to demonstrate the desired behavior without changing the weights.
If you ask a model to translate English into French and show examples of translations, it can better infer how to respond to a new input.
The Order of Examples Affects Performance Too
The 2022 paper Fantastically Ordered Prompts and Where to Find Them showed that the order of the same few-shot examples can make a substantial difference. The researchers reordered examples for positive-or-negative movie review classification and examined the labels the model produced on separate probing data.
They didn't use the probing data's ground-truth labels directly. They examined the distribution of the labels the model predicted.
- Global entropy measures how varied the outputs are across the examples. A model that labels every review negative has low global entropy.
- Local entropy measures how close the probabilities for different choices are on an individual example. It is high when positive and negative are similarly likely and low when one is strongly favored.
Ryan says global entropy looked more useful for choosing the order. He compares it with an oracle that uses the right answers to pick the best order. A global-entropy-based choice beat random ordering and sometimes improved performance by around eight percentage points.
Today, relatively little research focuses on optimizing the order itself. The durable lesson is to test different prompt configurations and measure what they do.
4. Bootstrap Model-Generated Reasoning Examples
Labeled examples often give an answer without the reasoning that led to it. A movie review may be labeled negative without explaining why particular words imply that label.
Ryan describes STaR as a way to make reasoning examples. Give a model a question and have it generate reasoning and an answer. Keep correct results as training examples. For incorrect answers, supply the right answer as a hint and ask it to produce reasoning that leads there. The collected examples can be used to fine-tune the model.
The same idea works for context optimization without changing weights. DSPy's bootstrap random search is an example.
- Run inputs through the system to generate reasoning and answers.
- Keep well-scoring results and discard poor ones.
- Sample combinations of the saved examples to put in the prompt.
- Test each combination on development data and choose the best.
A student asks what it means to change a combination. If there are 30 good examples and six slots in the prompt, Ryan explains, randomly pick six to test, then try another six.
This can preserve reasoning traces as well as labeled answers. In the DSPy results presented, the approach using rejection sampling to discard incorrect results compared well with plain labeled examples and human-written reasoning examples.
5. OPRO: Show Past Scores and Ask for a Better Instruction
Ryan groups several papers under reflective optimization. Run the system, look at what worked and what could be better, and revise it based on that information.
The first example is Google DeepMind's OPRO. Give a language model the instructions tried so far and the score for each, then ask it to write an instruction that would score higher.
If "take a deep breath" got 80 and "think step by step" got 76, put those results and other candidates into a meta-prompt to generate the next one.
"Look at the previous instructions and their scores. Write a new instruction that can score higher."
The opening poll came from this work. In the paper, "think step by step" scored 71.8% accuracy. PaLM's proposed "take a deep breath" did better. A different phrase from GPT-4 also beat the baseline, but came in below the deep-breath phrase in that experiment.
Questions About Variability and Why It Works
A student asks how to control for nondeterminism, when the same input can produce different outputs. Ryan suggests running it several times and accounting for variability in practice.
Another asks why a model's prompts work better. Ryan's intuition about older models is that their wording may have resembled their training data more closely. He doesn't present that as an established result.
Today he sees greater value in finding missing task requirements than in subtle word choice. Feedback that a system failed because of a date format, for instance, can lead you to specify ISO dates explicitly.
6. MIPROv2: Search Over Instructions and Examples Together
MIPROv2, which Ryan helped develop, generates successful few-shot examples and instruction candidates separately, then searches for good combinations. It uses Bayesian search instead of the bootstrap random search discussed earlier.
Ryan illustrates it with classifying an iris species from four flower measurements. The model predicts a species from the measurements. Evaluation identifies the correct predictions, and successful traces are kept as examples.
The model proposing instructions receives several types of information.
- Program information. What the code is trying to do.
- Training data information. A summary of the inputs and labels.
- Successful traces. Reasoning and answers that produced good results.
- Prompt-writing tips. Hints that diversify candidates, such as assigning a role or making instructions explicit.
Ryan stresses that the development data is kept out of instruction generation. Putting evaluation information directly into candidate generation would undermine the evaluation.
One resulting instruction said that classifying iris species mattered for saving endangered plants. Such urgency could help with older models, he says, and may be less necessary with current ones.
MIPROv2 tests combinations of instructions and groups of examples, updating its estimates of which candidates will work based on the results. It evaluates minibatches and periodically runs a broader evaluation so chance results don't mislead it. Ryan mentions the tree-structured Parzen estimator available in Optuna.
The user ultimately gets the one highest-scoring combination of instructions and examples, rather than the entire probability distribution.
Questions from the Class
A student asks whether the answer can be right while the reasoning is wrong. Ryan says the example did not monitor reasoning separately. A language model could judge its validity as part of the metric, but optimizing a score can lead to reward hacking, where the system exploits gaps in the evaluation.
Ryan says MIPROv2 still gets used with new models and mentions other ways to take advantage of stronger ones. In theory, the search can also be seen as a multi-armed bandit, testing several options and giving promising ones more chances.
7. TextGrad: Pass Text Feedback to Earlier Stages
Ryan introduces TextGrad briefly to bridge to the next method. In a program made up of model calls and tool use, evaluate the output and ask a language model to explain in text what should change.
Feed the feedback back to an earlier stage. Show its input and output along with feedback from the next stage, then ask for a change that would produce a better result.
"Here's the output, here's the feedback from the next stage, and here's the input. What would you change to improve it?"
The name and explanation resemble a PyTorch loss function and backpropagation. Ryan stresses that no actual differentiation or numerical backpropagation through a network is happening. A model reads written feedback and proposes changes.
8. GEPA: Improve Prompts with Reflection and Evolution
GEPA starts with a base prompt, makes candidates, and uses evaluation results to evolve good ones. It's also the method Ryan used to optimize the earlier email event extraction example.
Keep Candidates That Do Well on Different Tasks
Development data contains different tasks. A prompt might solve the first task while another solves the second and third. GEPA keeps candidates on a Pareto frontier that reflects task-specific strengths, instead of retaining only the top average score.
In the lecture's example, P1 solves only task two and P2 solves tasks two and three, so P2 dominates P1. If P3 solves task one when the others can't, P3 is worth keeping as well.
Two Ways to Generate Candidates
The first is reflective prompt mutation. Sample a candidate, run it on a minibatch of training examples, inspect scores and actual outputs, and propose a revised prompt.
The second is system-aware merging. In a program with several modules, you could combine email extraction instructions from one candidate with emoji selection instructions from another.
If a new candidate improves on the minibatch, evaluate it more broadly and add it to the pool. Otherwise discard it and try again. Repeat until the optimization budget is spent.
"If you find something that looks better, add it to the pool. Then you can use it to make something better again."
In the discussion, Ryan explains that sampling comes from candidates filtered by the Pareto criterion. Starting with one instruction could get stuck in a local optimum, he agrees. Combining it with a method that makes several starting instructions might help. He doesn't know whether the original researchers tested that.
A Privacy Example and Results
A GEPA example is a privacy-preserving question-answering system. When a user's question contains sensitive information, a local model removes or transforms the personal information. An external API model answers the altered question. A final local step combines the original question with the external answer to produce a personalized result.
GEPA improves the privacy rewrite instruction and the final answer instruction. The original simple instructions became detailed directions for identifying personally identifiable information, analyzing the question's purpose, structuring the output, and explaining transformations. Ryan shows one branch where the privacy metric improved by about 8%.
In the paper results presented, GEPA achieved high accuracy on the tested benchmarks, especially GEPA with system-aware merging. Ryan describes it as a context optimization method still used frequently.
A student asks how many candidates are kept compared with genetic algorithms that commonly maintain large populations. Ryan says the Pareto frontier criterion and the mix of evaluation tasks constrain the pool. Changing the algorithm to preserve more diversity would be an interesting research direction.
9. Start Weight Optimization with Supervised Fine-Tuning
The lecture moves from prompts to changing the model weights. The first method is supervised fine-tuning, or SFT.
SFT trains a model to give the desired target tokens higher probabilities. It computes cross-entropy loss and updates weights through actual backpropagation. You might prepare questions and exemplary responses, then make those responses more likely under the model.
For an agent, a strong teacher model can generate how it did an entire task, and a smaller student model can learn to imitate it. The target is the whole execution trajectory, including tool calls, inspection of results, and subsequent decisions, as well as the final answer.
OpenThoughts-Agent
Ryan describes a terminal task to find files with a particular name, exclude specified subdirectories, and save both standard output and standard error. The teacher writes a command, reviews the terminal output, and checks that what was saved is right. The student learns from that process.
The pipeline gathers tasks from several sources, chooses tasks and teachers, generates and filters teacher traces, then fine-tunes the student. Some pipelines trust a sufficiently strong teacher without checking every answer. If a verifier is available, it can filter by correctness.
An important observation is that the strongest teacher isn't always the best teacher. A very small student can struggle to learn from a much more advanced model's elaborate solution.
"A trajectory from a teacher that's much better than the student may be hard for that student to learn."
Ryan shows performance improving with more training data across diverse tasks. Given a good teacher and data, he sees SFT as a useful baseline.
FireAct
FireAct used GPT-4 as a teacher to produce traces with reasoning, tool use, and reflection for several questions. It discarded incorrect traces and used the rest to train Llama 2.
In the results shown, FireAct-trained Llama 2 13B reached 34% accuracy, while GPT-3.5 with a ReAct prompt reached 31%. Fine-tuning GPT-3.5 itself could improve it further. This illustrates how SFT alone on teacher traces can raise agent performance.
10. PPO and GRPO: Learn from Rewards on Actual Runs
In reinforcement learning (RL), the student tries the task and earns a reward based on the result. Passing unit tests can be the reward on a coding task. A language model can judge tasks where correctness is hard to check automatically. The crucial ingredient is a reward signal that distinguishes good outcomes.
PPO Components and Overhead
Ryan's description of PPO includes these components.
- Policy model. Acts and learns.
- Reward model or external reward. Scores the outcome.
- Reference model. Provides a comparison so the policy doesn't move too far from the original model.
- Value model. Estimates how each point in a trajectory contributes to the final outcome.
These help estimate how much credit or blame to assign to individual tokens and update the policy. KL divergence measures the difference from the reference model to limit how far the policy shifts during training.
There is overhead in holding several models in memory, training both policy and value models, and performing token-level calculations. A separate reward model isn't always needed if the environment supplies the reward directly.
GRPO Compares Responses with One Another
GRPO uses comparisons among rewards for several policy responses to the same problem instead of a separate value model.
If repeated runs of a coding task pass 40% of tests on average and one run passes 70%, that run did better than its group. GRPO subtracts the group mean from each reward and divides by the standard deviation to compute a standardized score, or z-score, for the relative advantage.
The signal makes outputs that contribute to better outcomes more likely and worse outcomes less likely. Ryan says that the update clips a ratio to limit the size of policy changes and manages drift from the reference model.
"Even without a value model, comparing several results on the same problem tells you which ones did better than average."
In the setup described, GRPO is more efficient in memory and computation than PPO because it doesn't have to train a separate value model.
DeepSeek R1 and the Roles of SFT and RL
The DeepSeek R1 example starts from applying RL to the base model to make R1-Zero. Its reasoning examples feed into the subsequent SFT and additional RL stages. RL alone can elicit reasoning, Ryan says, though SFT and RL are often used together.
SFT helps the model learn initial behaviors that can solve the problem. RL lets the model act in different situations and improve from rewards. An advantage of RL is that it learns from the student's own trajectories instead of a path chosen by a teacher.
A student asks whether to keep using RL if it performs worse than SFT. It depends, Ryan says, but use the SFT that works better in most cases. SFT may be less practical when training a frontier model for which there is no stronger teacher.
11. On-Policy Distillation: Have a Teacher Evaluate the Student's Actions
To explain on-policy distillation, Ryan uses chess. A beginner could watch the world's best players. It may be more helpful to play and have a coach explain why the moves the beginner chose were good or bad.
"In one case you watch what top players do. In the other, you try new moves yourself and learn from the attempt."
He compares three training methods.
- SFT. The student follows the teacher's trajectory. It gets a signal for each token the teacher produced, but that trajectory may differ from what the student would do.
- Reinforcement learning. The student acts, but may get only a reward for the full outcome, making it hard to tell where it went wrong.
- On-policy distillation. The teacher evaluates the trajectory produced by the student, giving a more detailed learning signal at the token level.
Ryan says this requires access to the teacher's conditional probabilities or log probabilities for each student token. It takes more detailed access than receiving the teacher's final answer alone.
If a student ignores the order of operations at the start of a math solution, a final reward might only signal that it was wrong. Token-level evaluations can give more specific feedback about which choices were off.
Ryan also mentions a problem about ice cubes on a hot frying pan. If the student overlooks melting and keeps counting cubes, a teacher can assign a low score to a premise such as "none of the ice melted or was removed."
A Qwen Example and a Question
Ryan describes training a small model in the Qwen family through on-policy distillation from a larger teacher. In the experiment presented, SFT-style approaches reached about 55%, RL 67%, and on-policy distillation 74% accuracy. On-policy distillation also used fewer GPU hours. These were results from that experiment.
A student asks whether on-policy distillation and SFT eventually converge to the same model with enough compute. Ryan says he doesn't know the exact theory and intuitively thinks they could. He offers that as a conjecture, not a definitive result.
12. When the Agent Does the Optimization
The later part of the lecture looks at using an agent to perform optimization as well as optimizing the agent itself.
Darwin Gödel Machine
The premise of the Darwin Gödel Machine is that an agent modifies the code and tools it runs in, its harness. Attempts are recorded like commits. A previous version is selected, modifies itself, and the result is evaluated.
Selection considers benchmark performance and how many descendants have already been generated, encouraging exploration. That creates several branching histories of changes.
Examples of improvements found by the agent include compressing context as it approaches the limit, generating patches with earlier history in mind, and inspecting files more closely.
The two concepts are self-improvement and open-ended exploration. The selected agent edits its own code instead of having a separate meta-agent make all the changes. Exploration can start from several previous versions rather than always editing only the latest one. Ryan says both contributed to better performance in the study.
He also describes Meta-Harness, a similar idea in which an agent examines past attempts and improves the harness code. In the results shown, it outperformed other evolutionary strategies and scored highly on Terminal-Bench.
AutoResearch
Ryan describes AutoResearch, popularized by Andrej Karpathy. The agent reads repository context, proposes changes, modifies code, and runs experiments. It keeps changes that improve the metric and reverts those that don't, recording results in a log.
In the example, it tries changing batch size and late training settings, then eventually changes random seeds. Ryan's point is that agents can be quite capable optimizers when they can repeatedly suggest ideas, run experiments, and record the results.
"If the agent can experiment and record results, what you measure and how you evaluate become the most important things."
13. When to Choose Context or Weight Optimization
Ryan concludes that the two approaches can be combined. The Better Together study shows the value of optimizing a prompt, tuning the weights, then optimizing the prompt again, for example.
GEPA research also shows that in some experiments, prompt optimization improved more quickly than RL with fewer execution samples. Weight optimization can take more data but can build the target capability into the model with enough examples.
When Context Optimization Can Help
If an external API is the only access you have and you can't change weights, adjusting prompts and examples is practical. It's also useful when the system changes often enough to reoptimize almost daily, or when interactions with the environment are expensive and improvement needs to come from few runs.
When Weight Optimization Can Help
Prompt changes may be insufficient to bring a small model up to the desired performance. Distillation can help when you have a strong teacher and want to serve with a cheaper model. You can also train a capability into the weights when context optimization has accumulated so many instructions and examples that the prompt is too long.
There is no single winning technique for every case. Start with a goal you can evaluate and choose or combine methods based on the data, cost, access to the model, and how often you need to optimize again.
