Optimization
A system can be changed at three levels: the text it is sent, the weights it runs on, and the computation it spends per request. Each produces a different artifact, costs a different amount, and fails in a different way.
7.1The optimization landscape: three levers
An agent that works but works badly presents a choice about where to spend effort. The system has parameters at three distinct levels, and each level has its own cost structure, its own failure modes, and its own operational consequences. The first level is the text sent to the model: instructions, few-shot demonstrations, tool descriptions, output schemas, and the assembly logic that decides what goes into a context window on any given call. The second level is the model weights themselves, changed by supervised fine-tuning, by parameter-efficient adaptation, or by preference-based training. The third level is how much computation the system spends per request at inference: how many candidate solutions it samples, how deep it searches, how many times it revises before committing to an answer.
These three levels are not interchangeable ways of doing the same thing. Each produces a different artifact with a different lifetime. Prompt optimization produces text, which lives in a repository, diffs cleanly against its predecessor, and can be reverted by a git revert. Weight optimization produces a checkpoint or an adapter file, which lives in a model registry, cannot be meaningfully diffed, and requires a redeployment to change. Inference-compute optimization usually produces a configuration value plus some orchestration code, which changes the per-request cost of every subsequent call for as long as the setting stays in place. When a team says it is going to fine-tune, it is committing to a build artifact and a serving path, not merely to an experiment.
| LEVER | ARTIFACT PRODUCED | COST PROFILE | REVERSIBILITY | HUMAN-LEGIBLE |
|---|---|---|---|---|
| Prompts | Text in version control | Hundreds to thousands of calls, once | Git revert | Yes, readable diff |
| Weights | Checkpoint or adapter file | GPU-hours, once, plus storage | Redeploy previous checkpoint | No, only via eval |
| Inference compute | Config value plus orchestration | Multiplied on every request, forever | Config change, but quality regresses | Partially, cost is visible |
Cost asymmetry between the levers is large enough to drive the ordering of any sensible workflow. A prompt optimization run over a few hundred labeled examples costs some number of model calls, typically in the hundreds to low thousands, and finishes in minutes to hours. A LoRA fine-tune on a seven-billion-parameter base costs GPU-hours and produces an artifact someone must store, version, evaluate, and eventually deprecate. Full-parameter fine-tuning of anything large costs enough that most teams building agents will never do it. Inference-compute scaling has the inverted cost profile: it is nearly free to turn on and expensive forever, because the cost is paid on every request in production rather than once at build time. A best-of-16 sampling strategy multiplies the generation bill by sixteen and adds latency to every user interaction, permanently.
Reversibility differs in the same direction. Reverting a prompt change is a text edit. Reverting a fine-tune means keeping the previous checkpoint around and swapping the serving path back, which is straightforward if the team has that discipline and painful if it does not. Reverting an inference-compute increase is easy mechanically but hard organizationally, since by the time quality has come to depend on best-of-N, removing it visibly regresses the product. There is also a subtler asymmetry: a prompt change is legible to a human reviewer, who can read the new instruction and form an opinion about whether it will generalize. A weight change is legible only through evaluation. Nobody reads a delta of adapter matrices and notices that the model has learned to overfit a labeling quirk.
The ordering argument follows from these asymmetries rather than from any claim that prompts are more powerful than weights. Start at the cheapest and most reversible lever, measure what it achieves, and move rightward only when the measurement shows the current lever exhausted. The word measured is doing real work in that sentence. Teams routinely conclude that prompting has been exhausted after a few hours of manual iteration by one engineer, which is an entirely different claim from concluding it after an automated search over the instruction and demonstration space with a scored objective. Chapter 3 covered the machinery for doing that search inside a DSPy program; the point here is that the search must actually have been run before the conclusion that prompts are insufficient carries any weight.
Rightward movement is also not exclusive. Fine-tuning does not retire the prompt; the fine-tuned model still receives instructions, and those instructions can themselves be re-optimized against the new weights. Test-time compute scaling composes with both, since sampling sixteen candidates from a fine-tuned model with an optimized prompt is a coherent configuration. Section 7.5 returns to composition with a specific empirical result about the interaction between prompt and weight optimization. For now the practical shape of the workflow is: characterize the failure, optimize the prompt with a real optimizer, measure the residual, and only then decide whether the residual is the kind of gap that weights or inference compute can close.
One useful diagnostic separates the cases. If the model demonstrably knows how to do the task but does it inconsistently, or misunderstands the output contract, or forgets a constraint stated once in a long instruction, the deficit is in the specification and the prompt lever applies. If the model does not know something the training data never contained, such as an internal schema, a domain vocabulary, or a house style with a thousand small conventions, no instruction of reasonable length conveys it and the weight lever applies. If the model can find the right answer but only sometimes, and there is a way to check which of several attempts is correct, the deficit is in search rather than knowledge and the inference lever applies. These three diagnoses map onto the three levers well enough to be a first-pass triage, though real systems usually present a mixture and require the trace-level analysis described in Section 7.5.
7.2Prompt optimization beyond hand-tuning
Manual prompt engineering has a shape familiar to anyone who has done it. An engineer reads a handful of failures, forms a hypothesis, edits an instruction, reruns a small set of examples, and keeps the version that seems better. The procedure is a hill-climbing search with a human in the inner loop, a sample size of maybe twenty examples, and an objective function contaminated by the engineer's memory of which examples were hard. It works well enough to get a demo running and poorly enough that the resulting prompt rarely survives a model upgrade. Automated prompt optimization replaces the human in that inner loop with a scored search over a defined space of candidate prompts, which makes the objective explicit and the comparison honest.
OPRO, introduced by Yang and colleagues in 2023, takes the most direct approach: use a language model as the optimizer itself. The setup constructs a meta-prompt that contains the optimization problem stated in natural language, a description of the task, and, importantly, a trajectory of previously generated solutions each paired with the score it achieved. The optimizer model reads this trajectory and generates new candidate solutions. Those candidates are evaluated on a training set, scored, appended to the trajectory, and the loop repeats. No gradients are involved anywhere. The mechanism by which the search improves is the optimizer model's in-context pattern recognition over the score-annotated history: having seen that instructions emphasizing step-by-step decomposition scored 71 and instructions emphasizing brevity scored 58, the model proposes something more like the former.
The trajectory ordering matters to how OPRO behaves. Solutions are presented in ascending score order, so the highest-scoring candidates appear closest to the generation point, where in-context influence is strongest. The trajectory is also truncated to a fixed number of the best solutions seen, which turns the meta-prompt into a form of population memory analogous to the elite set in an evolutionary algorithm. On GSM8K, OPRO-discovered instructions exceeded human-written prompts by up to 8 percentage points, and on Big-Bench Hard tasks the margin reached up to 50 points on individual tasks. The wide spread across tasks is itself informative: the tasks where a discovered instruction gains fifty points are ones where the default human phrasing was badly mismatched to the task, and the gain reflects the size of that initial mismatch more than any general property of the method.
TextGrad, from Yuksekgonul and colleagues, formulates the problem differently. Instead of treating the prompt as an opaque string to be resampled, it treats a compound system of LLM calls as a computation graph and propagates natural-language feedback backward through it. A forward pass runs the system and produces an output. A loss is computed, but the loss is a textual critique produced by an LLM rather than a scalar. That critique is then propagated to upstream variables through the graph, with each backward step asking a model: given that the downstream consumer of this variable produced this criticism, what specifically was wrong with this variable? The resulting textual feedback plays the role of a gradient, and an update step asks a model to revise the variable in the direction the feedback indicates. The API deliberately mirrors PyTorch, with variables carrying a gradient field and an optimizer exposing a step method.
This autodiff analogy is precise in its structure and loose in its semantics, and the distinction is worth stating carefully because the framing invites over-extension. What genuinely carries over is the graph decomposition and the credit assignment topology. In reverse-mode autodiff, the chain rule lets a single backward pass attribute a scalar loss to every upstream parameter, and TextGrad's backward pass performs the same attribution structurally, walking the graph in reverse and producing a per-variable critique. What does not carry over is everything that makes gradients mathematically well-behaved. A real gradient is a local linear approximation with a defined magnitude and direction, it composes by multiplication, and identical inputs produce identical outputs. Textual feedback has no magnitude, so there is no learning rate that means anything; it does not compose by any associative operation, so the feedback at layer one is a summary of a summary rather than a product; and it is generated by a stochastic model, so the same backward pass run twice yields different critiques. There is no guarantee that following textual feedback decreases the loss, no convergence result, and no notion of a stationary point. TextGrad is a structured heuristic that borrows autodiff's decomposition of credit assignment, not an implementation of differentiation over text.
import textgrad as tg
system_prompt = tg.Variable("Answer the question.",
requires_grad=True, role_description="system prompt")
model = tg.BlackboxLLM("gpt-4o", system_prompt)
optimizer = tg.TGD(parameters=[system_prompt])
response = model(tg.Variable(question, requires_grad=False,
role_description="question"))
loss = tg.TextLoss("Critique correctness and completeness.")(response)
loss.backward() # writes textual critiques into .gradients
optimizer.step() # LM rewrites system_prompt given its critiqueThe empirical results are modest in absolute terms and instructive about where the method applies. TextGrad raised GPT-4o's zero-shot accuracy on Google-Proof QA from 51 percent to 55 percent, and improved LeetCode-Hard solution rates by roughly 20 percent relative. It has also been applied to variables that are not prompts at all, including molecular structures optimized for binding affinity and radiotherapy treatment plans, which is the framework's real distinguishing claim: the optimized variable can be any text-representable object sitting in the graph, not just an instruction string.
MIPROv2, from Opsahl-Ong and colleagues, targets the harder problem of optimizing a multi-stage program where intermediate modules have no labels. In a pipeline with a query rewriter feeding a retriever feeding a synthesizer, only the final output is scored, and there is no supervision saying which module produced the bad rewrite. MIPROv2 factorizes the search into two coupled subproblems, instructions and demonstrations, for every module, and runs three stages. First it bootstraps demonstrations by executing the current program over training inputs and keeping the full input-output traces from runs whose final answer scored well, which yields per-module demonstrations without per-module labels because a trace that ended correctly is evidence that each intermediate step was at least serviceable. Second, a grounded proposer writes candidate instructions using context beyond the task name: a summary of the dataset, a summary of the program's control flow, the bootstrapped demonstrations, and a history of previously tried instructions with their scores. Third, it searches the joint space of instruction and demonstration assignments across all modules using a Bayesian surrogate model, evaluating candidates on stochastic minibatches rather than the full training set so that a single evaluation is cheap enough to afford many of them.
The Bayesian stage is what makes the joint search tractable. With several modules, several instruction candidates each, and several demonstration sets each, the combinatorial space is far too large for exhaustive evaluation, and the modules interact so that per-module greedy optimization gives up real quality. A Tree-structured Parzen Estimator fitted to the observed minibatch scores predicts which unevaluated configurations are promising, and the search spends its remaining budget there. MIPROv2 outperformed baseline optimizers on five of seven multi-stage programs, with gains reaching 13 percent accuracy on Llama-3-8B. The paper's broader finding, that grounding the instruction proposer in program and data context contributes more to final quality than the raw number of candidates it produces, is the practical lesson: an optimizer that proposes fifty uninformed instructions loses to one that proposes ten informed ones.
GEPA, covered in depth in Chapter 3, occupies the same design space with a different search strategy: reflective evolution over a Pareto frontier of prompts, using natural-language diagnosis of execution traces as the mutation operator. Its comparative results position it against both alternatives discussed here and against reinforcement learning, outperforming GRPO by 6 percent on average and up to 20 percent while using as much as 35 times fewer rollouts, and exceeding MIPROv2 by more than 10 percent, including a 12-point gain on AIME-2025. Readers should treat Chapter 3 as the reference for GEPA's mechanism and this section as the surrounding comparison: OPRO searches by resampling from a score-annotated history, TextGrad searches by propagating structured critique through a graph, MIPROv2 searches by Bayesian optimization over a factorized joint space, and GEPA searches by reflective mutation with Pareto-based candidate selection.
| METHOD | SEARCH OPERATOR | SIGNAL USED | HANDLES MULTI-STAGE CREDIT ASSIGNMENT |
|---|---|---|---|
| OPRO | Resample from score-sorted trajectory | Scalar scores in meta-prompt | Not directly |
| TextGrad | Backward critique through call graph | Textual feedback per variable | Yes, via graph topology |
| MIPROv2 | Bayesian search over instructions x demos | Minibatch scores, grounded context | Yes, via joint factorized search |
| GEPA (Ch. 3) | Reflective mutation, Pareto selection | Trace reflection plus per-instance scores | Yes, via module-level reflection |
A shared property of all four deserves emphasis because it constrains when any of them can be used. Every one requires a scoring function over outputs and a set of examples to score against. The optimizer's quality ceiling is set by the metric, and a metric that correlates weakly with what the product actually needs will produce prompts that score well and behave badly. Teams that cannot articulate a metric are not ready to run an optimizer, and the effort that would have gone into the optimization run is better spent building an evaluation set. This constraint applies with equal force to every technique in the remaining sections.
7.3Test-time compute scaling
Every technique so far changes the system before deployment and leaves per-request cost unchanged. Test-time compute scaling does the opposite: it holds the model and prompt fixed and spends more computation per request. The premise is that a model's single greedy sample understates what the model is capable of producing, because the distribution over its outputs contains correct answers that greedy decoding does not select. Scaling test-time compute means drawing more from that distribution, or searching it more carefully, and then selecting from what comes back.
Best-of-N sampling is the simplest instance. Draw N independent samples at nonzero temperature, score each with some verifier, and return the highest-scoring one. Performance improves roughly logarithmically in N over a useful range, then saturates and in some regimes degrades, since a sufficiently large N eventually surfaces a candidate that fools the verifier rather than one that is correct. Self-consistency, or majority voting, replaces the verifier with agreement: sample N chains of thought, extract the final answer from each, and return the modal answer. This works when answers are comparable, which means tasks with short canonical outputs like a number or a label, and works poorly for free-form generation where no two samples are ever identical. Self-consistency requires no verifier at all, which is why it remains the default for math and multiple-choice benchmarks.
Search over reasoning steps generalizes both by treating the solution as a sequence of steps rather than an atomic sample. Beam search over reasoning maintains a set of partial solutions, expands each by sampling continuations of the next step, scores the resulting partial solutions with a verifier that can evaluate incomplete reasoning, and keeps the top candidates by score. Lookahead search extends this by rolling out several steps ahead from each candidate before scoring, spending additional compute to get a less myopic estimate of a partial solution's value. Both require a verifier capable of scoring an unfinished prefix, which is a strictly stronger requirement than scoring a complete answer.
That requirement is what separates process reward models from outcome reward models. An outcome reward model, or ORM, is trained on complete solutions labeled by final-answer correctness, and scores a finished candidate. It is cheap to build, since final-answer labels come from the dataset, but it provides no signal until the solution is complete, which restricts it to reranking rather than guiding search. A process reward model, or PRM, is trained to score each intermediate step, and provides signal at every position in a partial solution, which is what makes step-level beam and lookahead search possible. PRMs require per-step supervision, historically obtained by human annotation of step correctness and more recently by automated methods that estimate a step's value by rolling out completions from it and measuring how often they reach a correct final answer. PRMs also carry a failure mode ORMs do not: a step that is locally plausible and globally useless scores well, so search guided by a PRM can drift into elaborate reasoning that never converges.
| MECHANISM | NEEDS VERIFIER | VERIFIER TYPE | BEST REGIME |
|---|---|---|---|
| Self-consistency / majority vote | No | Answer equality only | Short canonical answers |
| Best-of-N reranking | Yes | ORM or test suite | Complete-answer scoring available |
| Sequential revision | Weak | Self-critique or ORM | Easier prompts, near-correct first draft |
| Beam search over steps | Yes | PRM (scores prefixes) | Harder prompts, structured reasoning |
| Lookahead search | Yes | PRM plus rollouts | Harder prompts, high per-request budget |
Snell and colleagues studied how to allocate a fixed test-time compute budget across these mechanisms, and their central finding is that the right allocation depends on the difficulty of the specific prompt rather than being a global property of the method. They analyzed two families of mechanism: searching against a process-based verifier, and adaptively revising the model's own response distribution at test time by having it iteratively revise its answers. Neither family dominates. On easier problems, where the model's initial samples are frequently near-correct, sequential revision outperforms parallel search, because the model can productively refine a nearly-right answer and the search space does not need broad exploration. On harder problems, where initial samples are usually wrong in structurally different ways, parallel search against a verifier outperforms revision, because refinement of a wrong answer tends to preserve the wrongness while independent samples explore genuinely different approaches.
This difficulty dependence motivates a compute-optimal strategy: estimate the difficulty of an incoming prompt and select the scaling mechanism and budget accordingly, rather than applying a single fixed strategy to all inputs. Applying that adaptive allocation, the paper reports improving the efficiency of test-time compute scaling by more than 4x compared to a best-of-N baseline, meaning the adaptive strategy reaches the same accuracy as best-of-N with roughly a quarter of the compute. The difficulty estimate can come from the model's own pass rate on the prompt, or from a learned difficulty predictor, and the paper shows the adaptive gains survive using an estimated rather than oracle difficulty label.
A second finding bears directly on the choice between levers. Comparing test-time compute against pretraining compute in a FLOPs-matched setting, the paper finds that on problems where a smaller base model already achieves a nontrivial success rate, spending the additional FLOPs at test time on the smaller model outperforms using those FLOPs to run a model 14x larger. The qualification is essential and easy to drop when the result gets summarized. The advantage holds on easier and intermediate problems, where the smaller model's distribution contains correct answers often enough that additional sampling and verification can find them. On the hardest problems, where the smaller model essentially never produces a correct answer, no amount of test-time search recovers what is not in the distribution, and additional pretraining, meaning the larger model, wins. Test-time compute and pretraining compute are not freely exchangeable; the exchange rate depends on whether the capability is present but unreliable, or absent.
The dependence on a verifier is the practical constraint that determines whether any of this applies to a given agent. Every mechanism in this section is a select-among-candidates procedure, and its benefit is bounded by the quality of the selection. If the verifier is perfect, best-of-N accuracy approaches the probability that at least one of N samples is correct, which rises quickly. If the verifier is uninformative, best-of-N accuracy equals single-sample accuracy and the extra compute buys nothing. Real verifiers sit between these poles, and the gap between the oracle and actual curves is a direct measure of how much of the available headroom the verifier captures. Reporting both curves during evaluation is worth the small extra cost, because it tells a team whether to invest in more samples or in a better verifier.
Agent tasks vary widely in how good a verifier is available. Code generation has strong verifiers in the form of test suites, and best-of-N against passing tests is close to the oracle case, which is why sampling-based approaches have been so effective on programming benchmarks. Math with a checkable final answer has a good verifier during evaluation, though at deployment the answer is unknown and only a learned PRM or ORM is available. Retrieval-augmented question answering over private documents has a weak verifier at best. Open-ended writing, summarization, and most conversational tasks have no verifier, and applying best-of-N there means paying N times the cost for a selection made by an LLM judge whose agreement with human preference may be too low to rank close candidates reliably. A team considering test-time scaling should first ask what will rank the candidates and how well that ranker has been measured, because a weak ranker converts the entire compute increase into pure cost.
7.4Weight-level optimization
Weight optimization becomes the appropriate lever when the model needs to know something that cannot be economically stated in a prompt. The clearest cases involve volume and consistency: a house style with hundreds of small conventions, an internal API surface with dozens of endpoints and their idiosyncrasies, a classification taxonomy with fine distinctions that a domain expert learned over years. These can sometimes be written down, but the written form runs to tens of thousands of tokens, must be sent on every call, and still gets applied inconsistently because attention over a long instruction is imperfect. Fine-tuning moves that knowledge into the weights, where it costs nothing per call and is applied more uniformly.
Full-parameter fine-tuning updates every weight, which requires optimizer state proportional to the parameter count. With Adam, the standard accounting is roughly two bytes per parameter for the model in half precision plus twelve bytes per parameter for the fp32 master weights and the two moment estimates, so a seven-billion-parameter model needs on the order of a hundred gigabytes before activations, and a sixty-five-billion-parameter model is far beyond a single device. LoRA, introduced by Hu and colleagues, avoids this by freezing the base weights entirely and learning a low-rank update. For a frozen weight matrix W of shape d by k, LoRA parameterizes the update as the product of two matrices B of shape d by r and A of shape r by k, with r much smaller than either dimension, and computes the adapted forward pass as Wx plus BAx scaled by alpha over r. Only A and B receive gradients. A is initialized from a small random distribution and B is initialized to zero, so the adapted model at step zero is exactly the base model and training begins from an unperturbed starting point.
The parameter savings follow from the rank. A 4096 by 4096 attention projection has about 16.8 million parameters; the corresponding LoRA pair at rank 8 has 2 times 8 times 4096, or about 65,000, a reduction of roughly 250x for that matrix. Applied across a model, the original paper reports reducing trainable parameters by up to 10,000x relative to full fine-tuning of GPT-3 175B and cutting GPU memory by 3x, while matching or exceeding full fine-tuning quality on the models evaluated. The choice of which matrices to adapt was originally the attention projections, with the paper finding that adapting the query and value projections gave the best quality per parameter; current practice usually adapts all attention projections and often the MLP projections as well, since the additional parameters are cheap relative to the base model.
Why a low-rank update suffices is a question with a partial answer. The stated hypothesis is that the weight change induced by adapting a pretrained model to a downstream task has low intrinsic rank, even though the weights themselves do not. Pretraining has already installed general capability, and adaptation is a comparatively small reorientation, which a low-rank perturbation can express. This is consistent with the empirical observation that quality is often flat across a wide range of r, with r equal to 8 or 16 performing comparably to much larger ranks on many tasks, and it is also consistent with the observed failure mode: tasks requiring genuinely new capability rather than reorientation of existing capability benefit from larger r or do not respond well to LoRA at all. The hypothesis is descriptive rather than a theorem, and the practical procedure remains to sweep r over a small grid.
QLoRA, from Dettmers and colleagues, attacks the remaining memory cost, which after LoRA is dominated by the frozen base model itself. It combines three techniques. The base model is quantized to 4-bit NormalFloat, a data type whose quantization levels are chosen so that each level receives an equal share of probability mass under a normal distribution, which is information-theoretically optimal for normally distributed data and matches the empirical distribution of pretrained weights better than uniform 4-bit quantization does. Double quantization then quantizes the quantization constants themselves, since block-wise quantization stores one scaling constant per block and those constants are numerous enough to matter, saving roughly 0.37 bits per parameter. Paged optimizers use unified memory to page optimizer state to CPU when gradient checkpointing produces a memory spike, preventing the out-of-memory failures that otherwise interrupt long runs. The LoRA adapters remain in 16-bit and receive gradients, which flow through the dequantized 4-bit base weights without ever updating them.
from transformers import BitsAndBytesConfig
from peft import LoraConfig, get_peft_model
bnb = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4", # NormalFloat, not uniform int4
bnb_4bit_use_double_quant=True, # quantize the quant constants
bnb_4bit_compute_dtype="bfloat16") # dequantize for matmul
lora = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05,
target_modules=["q_proj","k_proj","v_proj","o_proj"],
task_type="CAUSAL_LM")
model = get_peft_model(load_base(quantization_config=bnb), lora)The resulting numbers restructured who can fine-tune large models. QLoRA finetunes a 65B-parameter model on a single 48GB GPU while preserving full 16-bit finetuning task performance, a workload that previously required a multi-GPU cluster. The Guanaco model family produced this way reached 99.3 percent of ChatGPT's performance level on the Vicuna benchmark, with the best model requiring 24 hours of finetuning on a single GPU. The practical consequence for agent engineering is that the weight lever is no longer gated on infrastructure access, which shifts the deciding constraint from hardware to data: the binding question becomes whether the team has a few thousand well-labeled examples, not whether it has a GPU cluster.
Distillation transfers behavior from a capable teacher model to a smaller student. The mechanism in the agent setting is usually simpler than the classical soft-label formulation, since API access to a strong teacher typically provides only text. The standard recipe runs the teacher over a corpus of inputs, keeps the outputs that pass a quality filter, and supervised-fine-tunes the student on those input-output pairs. When the teacher is an entire agent pipeline rather than a single call, the distillation target is often the pipeline's final behavior, and the student learns to produce in one call what the teacher produced through several, collapsing a multi-step chain into a single forward pass. This is where distillation and test-time compute interact directly: an expensive best-of-N or search-based configuration can serve as the teacher, and its outputs become training data for a student that produces comparable answers at single-sample cost. The distilled student inherits the teacher's ceiling and its biases, so a teacher pipeline that fails systematically on some input class produces a student that fails the same way with more confidence and no visible reasoning.
Supervised fine-tuning, whether full, LoRA, or distillation-driven, optimizes the likelihood of a target output given an input. It cannot express preferences over outputs where no single target is correct, which covers most questions of tone, helpfulness, verbosity, refusal behavior, and format preference. RLHF addresses this by learning from comparisons. The pipeline has three stages. A supervised fine-tune establishes a reasonable starting policy. Then human annotators compare pairs of model outputs for the same prompt and indicate which they prefer, and a reward model, typically the language model with a scalar head, is trained on these comparisons under a Bradley-Terry objective so that it assigns higher scores to preferred outputs. Finally the policy is optimized against the reward model using PPO, with a KL-divergence penalty against the supervised reference policy to prevent the optimizer from drifting into degenerate regions where the reward model is badly calibrated and assigns high scores to text humans would reject.
The pipeline works and is operationally demanding. It maintains four models in memory during training, the policy, the reference, the reward model, and the value function; it samples from the policy inside the training loop, which is slow; and its stability depends on hyperparameters including the KL coefficient and PPO's clipping range that require careful tuning. Reward hacking is the characteristic failure: the policy discovers inputs on which the reward model is wrong and exploits them, producing outputs that score highly and are worse by any human judgment.
DPO, from Rafailov and colleagues, removes most of this machinery through a reparameterization. The observation is that the KL-constrained reward maximization problem has a known closed-form optimal policy, an exponentially-tilted version of the reference policy weighted by the reward. That relationship can be inverted to express the reward as a function of the optimal policy and the reference policy, specifically as beta times the log-ratio of their probabilities plus a partition term. Substituting this expression into the Bradley-Terry preference likelihood causes the partition term to cancel, because it depends only on the prompt and appears in both branches of the comparison. What remains is a loss over preference pairs written entirely in terms of the policy and the frozen reference, with no reward model and no sampling. The language model is its own implicit reward model, and training reduces to a binary classification-style objective on a static preference dataset.
The practical difference is substantial: DPO holds two models rather than four, does no generation during training, and has essentially one hyperparameter of consequence in beta, which controls how far the policy may move from the reference. The original paper reports that DPO matches or exceeds PPO-based RLHF on sentiment control, summarization, and single-turn dialogue while being markedly simpler to implement and train. It is not strictly superior. Because DPO trains on a fixed preference dataset, it never sees its own current outputs, so it cannot correct errors that only emerge after the policy has moved, which is precisely what on-policy sampling in PPO provides. The commonly reported consequence is that DPO can over-optimize toward the preferred responses in its dataset and reduce output diversity. For most teams building agents the tradeoff favors DPO, and in many cases the honest recommendation is neither: preference optimization is worth reaching for when the failure is a matter of taste that comparisons capture and instructions do not, which is a narrower set of problems than its prominence in the literature suggests.
Serving considerations should influence the choice of weight-optimization method as much as training cost does. A LoRA adapter is a small file, typically tens to hundreds of megabytes, containing only the A and B matrices. Modern inference servers can hold one copy of the base model in memory and serve many adapters concurrently, routing each request to its adapter and batching across them, so per-tenant or per-task adaptation costs a small marginal memory allocation rather than a full model instance. Adapters can be hot-swapped without restarting the server, and can be merged into the base weights at deployment when the deployment is dedicated, which eliminates the small runtime overhead of the extra matrix multiplications and yields the paper's claim of no additional inference latency. A full fine-tune has none of these properties: it produces a complete model that occupies its own memory, cannot share a base with anything, and requires a separate serving instance per variant. A team expecting to maintain several task-specific or customer-specific variants should treat adapter-based methods as close to mandatory, independent of any quality comparison.
| METHOD | TRAINABLE PARAMS | MEMORY DRIVER | SERVING STORY | USE WHEN |
|---|---|---|---|---|
| Full fine-tune | 100% | ~14 bytes/param with Adam | One full model per variant | Large domain shift, one variant only |
| LoRA | <1% | Frozen base in 16-bit | Swappable adapter, mergeable | Style, format, schema adaptation |
| QLoRA | <1% | Frozen base in NF4 4-bit | Same as LoRA | Same as LoRA, on constrained hardware |
| Distillation | Student's params | Student-sized training | Smaller model, cheaper serving | Collapsing an expensive pipeline |
| RLHF (PPO) | 100% of policy | Four models resident | Full model per variant | Preferences, large annotation budget |
| DPO | 100% or LoRA-wrapped | Two models resident | Depends on wrapping | Preferences, static comparison data |
7.5Choosing a lever and knowing when to stop
The decision framework begins before any optimizer runs, with an error analysis on execution traces rather than an aggregate score. Sample fifty to a hundred failing trajectories, read them individually, and label where in the trajectory the run first went wrong. This is tedious and it is the step that determines whether everything after it is aimed correctly. An aggregate accuracy number says a system fails a third of the time; it does not say whether the failures come from a retrieval step returning irrelevant passages, a planning step choosing an unworkable decomposition, a tool call with malformed arguments, or a final synthesis that ignores evidence it was given. Those four failures have four different remedies, and only one of them is addressed by any given optimization run.
Categories that emerge from this reading map onto levers with reasonable directness. Failures where the model had the necessary information and used it incorrectly, or ignored a stated constraint, or emitted a shape the downstream parser rejected, are specification failures and belong to prompt optimization. Failures where the model produced fluent output that was wrong in a way indicating it never knew the relevant fact are knowledge failures, and they belong either to retrieval, if the fact is lookup-able, or to fine-tuning, if the deficit is a large body of tacit convention. Failures where repeated sampling shows the model sometimes gets it right are search failures and belong to test-time compute, conditional on a verifier existing. Failures where the trajectory went wrong because a tool returned something unexpected are not optimization problems at all; they are engineering problems in the tool layer, and no amount of prompt search fixes a tool that returns stale data.
| TRACE FAILURE CATEGORY | LEVER | FIRST ACTION |
|---|---|---|
| Constraint ignored, format wrong, instruction misapplied | Prompt | Run an optimizer with a metric that scores the constraint |
| Fact absent, tacit convention violated at volume | Retrieval, then weights | Check retrievability first; fine-tune only if not lookup-able |
| Correct sometimes across resamples | Test-time compute | Build or measure a verifier before adding samples |
| Tool returned unexpected or stale data | Neither | Fix the tool contract; optimization cannot repair it |
| Evaluation label disputed on review | Neither | Repair the eval set; the measured gap is not real |
Ordering across the levers follows the cost and reversibility argument of Section 7.1, with one refinement drawn from the interaction between them. Soylu, Potts, and Khattab studied whether prompt optimization and weight optimization should be treated as alternatives and found that they compose: alternating between optimizing prompts and fine-tuning weights outperformed doing either alone, with gains reported up to 60 percent over weight optimization by itself and up to 6 percent over prompt optimization by itself, averaged across their benchmarks. The asymmetry in those two numbers is worth reading carefully, because it says the alternation rescues a weights-only workflow far more than it improves a prompts-only workflow, which is consistent with the ordering advice: a team that fine-tunes without optimizing prompts is leaving the larger share on the table.
The mechanism behind composition is that the two levers address different deficits. Fine-tuning shifts what the model tends to produce; prompt optimization shifts what it is asked for. A prompt tuned against the base model is not necessarily the best prompt for the tuned model, since the tuned model may no longer need an instruction that was compensating for a behavior fine-tuning has now corrected, and may benefit from an instruction that would have been unusable before. The practical procedure is to optimize the prompt, fine-tune with that prompt in place so the training distribution matches deployment, then re-run prompt optimization against the new weights, and stop when a round produces no held-out improvement.
Certain configurations should be ruled out before any measurement. Fine-tuning on a dataset that has not been read is the most common, and it fails in a predictable way: the model learns the annotation artifacts, and evaluation on data with the same artifacts confirms success. Optimizing against a metric nobody has validated against human judgment is the second, and Chapter 10 gives the validation procedure. Running any optimizer on fewer than roughly a hundred examples produces a result whose confidence interval is wide enough to contain zero, so the measured improvement is not distinguishable from selection noise. Adding test-time compute without a verifier multiplies cost and moves accuracy by approximately nothing. Each of these consumes real effort and returns a number that looks like progress.
Knowing when to stop is a question about diminishing returns relative to alternative uses of the same effort. The straightforward signals are a plateau in held-out score across successive optimizer runs, and a widening gap between training and held-out performance, which indicates the search has begun fitting the training set rather than the task. A subtler and more common signal appears when a team reviews the remaining failures and finds that a meaningful share are cases where the evaluation label is itself disputable. At that point the measured error is dominated by label noise, further optimization is fitting the annotation rather than the task, and the effort belongs in the evaluation set instead. Chapter 09 covers how to establish that ceiling; the operational rule is that a system cannot be optimized past the reliability of the labels it is scored against.
Optimization also has a maintenance cost that accrues after the run finishes. An optimized prompt is tuned to a specific model version, and a provider-side model update can degrade it without warning, which argues for storing the optimizer configuration and training set alongside the prompt so the search can be re-run rather than reconstructed. A fine-tuned checkpoint pins the team to a base model that will eventually be deprecated, and the migration cost is a fresh training run plus a fresh evaluation. Test-time compute settings pin an ongoing spend that shows up in the monthly bill rather than in any code review. None of these is an argument against optimizing. They are an argument for recording what was optimized, against which metric, on which data, and at which model version, because the artifact alone does not carry that information and the person who runs the next migration will need it.
Beat your own prompt with a search
Take a stage you hand-tuned. Run an automated optimiser against a held-out metric. Report the gain, the search cost, and — most importantly — whether the winning prompt reveals something your evaluation was failing to penalise.