9.4 Prompting, ICL, and Prompt Optimization
Prompting and SFT can both adapt task behavior, but they modify different artifacts. SFT changes model or adapter parameters. A prompt changes the conditioning context of a forward pass. The useful comparison is operational: which intervention yields the required behavior at an acceptable optimization, serving, and maintenance cost?
In-context learning can exploit demonstrations without updating stored weights. That does not make a prompted frontier Transformer literally equivalent to running gradient-based SFT on those demonstrations.
1. The Gradient-Descent Analogy Has Assumptions
Dai et al. and von Oswald et al. study connections between attention and optimization [1] [2]. Their constructions and experiments illuminate mechanisms under specified settings; they do not establish one universal implementation for every nonlinear attention model or every task.
For a concrete linear-regression illustration, let be an input, its target, an initial predictor, demonstration count, and a step size. One gradient step on mean squared error gives
Applied to query , this yields
The right-hand side resembles linear associative attention with residual-valued updates. The construction explains a possible relation to optimization. It does not show that arbitrary value vectors are gradients or that a pretrained model’s persistent parameters changed. Demonstration order, formatting, relevance, and task distribution still affect behavior.
2. Reasoning Tokens Add Work, Not Guaranteed Depth
A generated reasoning token becomes context for another model step. This can support decomposition, checking, and revision; it can also produce repetition or rationalization. Multiplying layer count by output tokens measures repeated forward-pass work, not the number of valid logical deductions. A fixed-depth model does not automatically fail every task whose written solution contains more steps than layers.
Use Chapter 15.3 to allocate inference budgets and Chapter 15.5 to distinguish learned reasoning from test-time prompting. Evaluate delivered correctness, verification, stopping, total tokens, and latency together.
3. Prompt Compilation as an Optimization Workflow
DSPy separates signatures and program modules from the instructions and demonstrations selected by an optimizer [3]. This makes prompt assets easier to version and compare. It does not guarantee optimal prompts, eliminate human review, or ensure portability to another model. Recompilation is a search procedure with a finite budget and a chosen metric.
DSPy Prompt Compiler Simulation
Illustrative stages with synthetic scores; no model calls or optimization run here.
class MultiHopQA(dspy.Signature):
"""Answer complex questions by leveraging retrieved context."""
context = dspy.InputField(desc="Retrieved factual snippets")
question = dspy.InputField()
reasoning = dspy.OutputField(desc="Step-by-step logical deduction")
answer = dspy.OutputField(desc="Short factual answer")Research snapshot as of 2026-10-13. GEPA proposes reflection over execution traces to evolve prompts and retain useful candidates. Its reported comparisons with RL are conditional on the evaluated tasks and optimization budgets [4]. Treat textual feedback as a source of candidate changes, not evidence that the candidate generalizes. Adaptive search can overfit an exposed development set just as weight training can.
4. A Reproducible Prompt-Optimization Contract
The following workflow is conceptual, not a runnable DSPy script. Library names and optimizer signatures change; pin the exact release and use its documentation when implementing.
| Stage | Artifact and decision |
|---|---|
| Baseline | Model/provider revision, tokenizer-native template, system prompt, tools, retrieval revision, decoding and reasoning settings |
| Search data | Provenance, licensed examples, semantic-cluster splits, sample IDs, and evaluation quarantine |
| Objective | Executable correctness where possible, calibrated rubric otherwise, critical safety and format constraints |
| Search budget | Candidate/attempt limits, demonstration count, input/output cap, reflection calls, total tokens/cost, seed, and timeout |
| Development | Record every candidate, trace, metric, failure, rejection reason, and parent lineage |
| Final evaluation | Sealed holdout untouched by reflection or candidate selection, paired against the baseline |
| Promotion | Versioned prompt/program bundle, bounded canary, owner and rollback thresholds |
Verify train/serve formatting parity for demonstrations: native roles, BOS/EOS, add_generation_prompt, truncation and padding. For a later SFT distillation of the optimized program, use explicit assistant-span loss masks, exclude tool outputs and padding, prevent cross-sample packed attention, and pin the base/reference identity and response-length policy. Prompt compilation itself does not perform those weight updates.
Prompt search uses inference resources even when it avoids backpropagation. Budget prefill, decode, reflection/verifier calls, tool/sandbox work, temporary state, parallel candidates, evaluation, and persisted artifacts separately. For later SFT, additionally account for parameters, gradients, optimizer states, activations, precision, sharding, and recomputation under Chapter 9.1’s contract.
5. Evaluation, Recovery, and Release
Measure quality by domain and difficulty, demonstration sensitivity, prompt-injection behavior, format/tool errors, output length, cost, p50/p95 latency, and provider errors. Retain reconstructable candidate and batch IDs. If distilling into weights, add token-normalized training/validation loss, nonfinite/overflow counts, gradient/activation norms, throughput, MFU, data wait, collectives/stragglers, and full training checkpoints.
Stop search at its predeclared budget, repeated invalid tool effects, evaluator disagreement, or no held-out improvement inside uncertainty bounds. Save resumable optimizer/search state, candidate ancestry, RNG, data cursor, and model/template/data/config hashes. SFT checkpoints additionally contain sharded model/optimizer, scheduler, scaler/FP8 state, step/tokens, and sampler state. Publish artifacts atomically with checksums; define retention, replication, restore tests, and changed-world-size limits where distributed training applies.
Release only when domain quality, base retention, safety, format/tool use, latency, cost, and error gates pass with paired uncertainty or justified sample sizes. Rollback must restore the whole prompt/program/model/tool bundle. Rehearse the switch and keep an owner and observation window. A development-set score increase is insufficient.
Quizzes
Quiz 1: Which artifact changes during ordinary in-context learning?
The conditioning context and transient activations change. Stored model weights are not updated by a standard inference call.
Quiz 2: When can a linear attention-like update represent a gradient step?
Under a specified construction where update values encode prediction residuals and scaling matches the chosen objective. Arbitrary learned value vectors do not automatically satisfy those assumptions.
Quiz 3: Why must reflective prompt search have a sealed final holdout?
Reflection and candidate selection adapt to exposed feedback. Reusing that feedback set for release evaluation produces selection bias and can hide overfitting.
Quiz 4: Why is recompiling a prompt after a model upgrade insufficient on its own?
Compilation optimizes a finite metric under a budget. The new system still needs template/tool compatibility, quality and safety gates, cost/latency checks, and rollback.
References
- Dai, D., et al. (2023). Why Can GPT Learn In-Context? Language Models Secretly Perform Gradient Descent as Meta-Optimizers. arXiv:2212.10559.
- von Oswald, J., et al. (2023). Transformers learn in-context by gradient descent. arXiv:2212.07677.
- Khattab, O., et al. (2024). DSPy: Compiling Declarative Language Model Calls into Self-Improving Pipelines. arXiv:2310.03714.
- Agrawal, L. A., et al. (2025). GEPA: Reflective Prompt Evolution Can Outperform Reinforcement Learning. arXiv:2507.19457.