TextGrad

TextGrad treats a pipeline of language model calls like a neural network: it backpropagates written criticism instead of numbers. It lifted GPT-4o on GPQA from 51% to 55%.

Learn how an AI system made of prompts, answers and tools can be tuned by the same loop that trains a neural network: forward pass, backward pass, update.

Switch between Numbers and Text, then press Next phase again and again. Watch the same loop run twice: once with a number as the gradient, once with a sentence. Then we build, piece by piece, every part of it, and the results the paper reports.

You need a feel for what a prompt and an LLM call are and a little Python. We build backpropagation, gradients and the rest from zero.

Based on “TextGrad: Automatic ‘Differentiation’ via Text” (arXiv 2406.07496) by Mert Yuksekgonul, Federico Bianchi, Joseph Boen, Sheng Liu, Zhi Huang, Carlos Guestrin and James Zou (Stanford, 2024). It is a reading for Lecture 2, Context Evolution of MIT MAS.S62, How to AI an AI for (Almost) Anything. Every idea is re-taught here in our own words and devices.

Run the loop

Numbers mode: a one-weight toy, y = w × 2, loss (y − 10)², learning rate 0.05, computed live. Text mode: the first prompt and the third prompt are the paper’s GSM8k prompts (Table 3: accuracy 72.9% before, 81.1% after 12 iterations, batch 3); this device compresses those 12 iterations into three. The question, the answers, the scores and every criticism are illustrative, written by us.

Chapter 0

Why Tune an AI System by Hand?

See why a pipeline of language model calls is hard to improve, and what a neural network has that the pipeline lacks

Picture a small assistant that answers questions about a company’s refund policy. It has three parts. A retriever finds the right paragraph. A drafter (a call to a language model) writes an answer from that paragraph. A checker (a second call) reads the draft and says whether it is safe to send.

One morning the assistant tells a customer the wrong refund window. The final score is bad. Now you must fix it. But which part is to blame? The retriever may have found the wrong paragraph. The drafter’s prompt may be vague. The checker may be too lenient. Each part has a prompt that you wrote by hand, and each prompt hides inside a black box.

The paper calls this kind of system a compound AI system: several components, such as language models, search tools and code, wired together. The authors note that many of the best results today come from systems like this, and that most of them are “hand-crafted by experts… and tweaked through heuristics”. An expert edits a prompt, runs the system, looks at the result, and edits again.

What a neural network has that the pipeline lacks

A neural network is also a chain of parts. It has layers, and each layer holds numbers called parameters (the knobs that training turns). Yet nobody tunes those knobs by hand. A procedure called backpropagation (backprop) tells every knob which way to turn and how much. Chapter 1 builds it from zero.

Backprop works because the parts are differentiable: you can ask a part how its output would change if its input changed a little, and get a number back. A language model call is not like that. You send text in and text comes out. You cannot ask for a derivative of “a refund window of 30 days” with respect to the word “vague”. So the old tool does not fit.

The paper’s bet is simple. A derivative is only a message that says how to change this input to improve the final score. A strong language model can write such a message in plain English. So let the message be a sentence, and pass it backward through the system, one component at a time. The authors call this TextGrad. They use “differentiation” and “gradient” as a metaphor, and the quotation marks in the title are on purpose.

Why not just try everything?

You could skip all this and search. Write five alternative prompts for each component and test every combination. That works when there is one component. It collapses as the system grows, because the number of combinations multiplies. Move the sliders and watch the two costs part ways.

Search every combination, or ask each part

Each bar is a cost on a log scale. Yellow: runs needed to test every combination of rewrites. Warm: extra language model calls for one backward pass. Drag both sliders.

4
5

Illustrative arithmetic, not a result from the paper. The grid size is mk for k components with m candidate rewrites each. The backward cost uses the paper’s bound: each iteration makes at most one extra language model call per edge of the computation graph (Section 2). A chain of k components has k edges once the final score is counted. A backward pass tells you where to edit; it does not replace running the system.

With four components and five rewrites each, a full search needs 625 runs. A backward pass needs at most four extra calls. At ten components the search needs almost ten million runs, and the backward pass needs ten. The comparison is not fair in every way, because one backward pass does not find the best prompt. It finds a direction. But a direction that costs a handful of calls is what lets you walk, instead of search.

What this lesson builds

Two things make TextGrad more than a clever prompt. First, it keeps the whole shape of backprop: a forward pass that runs the system, a backward pass that collects criticism for every variable, and an update that rewrites each variable using its criticism. Second, it ships as a library that copies PyTorch’s names, so a PyTorch user can read the code at once. The hero above ran that loop twice, once with a number and once with a sentence. Same loop, different message.

The paper reports gains in five very different places: hard coding problems, PhD-level science questions, prompts for reasoning, drug-like molecules and radiation treatment plans. We will meet each one. Be ready for a mixed verdict. The paper is an early, wide demonstration, and several of its claims come with honest limits that we flag as we go.

  1. Backpropagation in two minutes: the chain rule and one gradient step, with numbers.
  2. The textual gradient: what a criticism is, and the exact request that asks for it.
  3. The graph and the chain rule through text: variables, functions, and criticism collected from every use.
  4. The optimizer: textual gradient descent, momentum and constraints.
  5. The loop in practice: instance versus prompt optimization, batches and the validation check.
  6. What the tables show: LeetCode Hard, GPQA, MMLU, three reasoning tasks.
  7. Molecules and radiotherapy: a simulator’s numbers turned into criticism.
  8. The field guide: numbers, limits, the core code, and where to go next.
Why can you not run ordinary backpropagation through a pipeline of language model API calls?

Chapter 1

Backpropagation in Two Minutes

Learn how a number can tell every knob in a chain which way to turn, using one weight and the chain rule

You are baking bread, and the loaf comes out too dry. Two things changed since last time: the oven was hotter, and the dough rested a shorter time. You want to know how much each one hurt. A good baker runs a small thought experiment for each: “If I had rested the dough a little longer, how much better would the loaf be?” That question, asked of every knob at once, is the heart of training a neural network.

The question has a name. The gradient of a score with respect to a knob is the rate at which the score changes when you nudge the knob. If the gradient of the loss is −32, raising the knob lowers the loss, and fast. If it is +5, lowering the knob helps, slowly. The sign gives the direction. The size gives the urgency.

One knob, one chain

Take the smallest system we can: one weight w, one input x = 2, and one target t = 10. The system multiplies, then scores itself.

y = w · x
The forward pass: run the system from knob to output. With w = 1 and x = 2, y = 2.
L = (y − t)2
The loss: one number that says how wrong the output is. It is zero when y equals the target t. Here L = (2 − 10)2 = 64.

We want dL/dw, the rate at which the loss changes with the weight. But the weight does not touch the loss directly. It touches y, and y touches the loss. So we ask two smaller questions and multiply the answers. This is the chain rule: the rate of a chain is the product of the rates of its links.

∂L/∂w
The gradient we want: how the loss changes per unit change of the weight.
∂L/∂y
How the loss changes with the output. It is the gradient that arrives from downstream, from the score back to y.
∂y/∂w
How the output changes with the weight. It is a fact about this one link and nothing else.
2(y − t)
The derivative of the square. At y = 2 and t = 10 it is 2 × (−8) = −16.
x
The derivative of w · x with respect to w. It equals the input, 2.

∂L/∂w = (−16) × 2 = −32

Read the answer. A gradient of −32 means: raise w and the loss drops, by about 32 per unit. Notice the order of work. You first ran forward to get y and L. Then you started at the score and walked backward: first ∂L/∂y, then the local rate ∂y/∂w. That backward walk, reusing each link’s local rate, is backpropagation. The key trick is that each link only needs to know its own rule and the message arriving from downstream.

The update

With the gradient in hand, take a small step against it. This is gradient descent. The step size is the learning rate, written η (eta). Here η = 0.05.

wnew
The knob after the update.
w
The knob before the update.
η
The learning rate. Too large and you overshoot the best value. Too small and you crawl.
∂L/∂w
The gradient. It is subtracted, so a negative gradient raises w.

From w = 1: wnew = 1 − 0.05 × (−32) = 2.6. Then y = 5.2 and L drops from 64 to 23.04. Try it yourself below. The warm line is the tangent: its slope is the gradient.

Take a gradient step

The curve is the loss for every weight. The dot is where you are. The warm line is the tangent, so its slope is the gradient. Drag the weight, or press Take one step and watch the dot slide downhill.

1.00

A toy: x = 2, target t = 10, learning rate 0.05. The best weight is 5, where the loss is zero. Every number is computed live from the two formulas above. Nothing here comes from the paper; it is the background the paper builds on.

Near w = 5 the slope flattens and the steps shrink on their own, because the step is the gradient times a fixed η. Far away, the steps are big. That is why gradient descent settles without being told where the bottom is.

Add a second link to see the pattern repeat. Let h = w1 · x, then y = w2 · h, then the same loss. The message at y is still ∂L/∂y. It reaches h as ∂L/∂y × w2, because the rate of y with respect to h is w2. It reaches w1 as that result times x. Each link multiplies once, then hands the product to the link behind it. Nobody needs to see the whole chain.

The same loop, at scale

A real network has millions of weights, stored in tensors, for example a weight matrix of shape [d_in, d_out]. The gradient of a tensor has the same shape, one number per weight, so every knob gets its own signal. Frameworks such as PyTorch store the graph of operations during the forward pass, then apply the chain rule backward automatically. That automation is called automatic differentiation. The whole training step is three calls.

pythonloss = loss_fn(model(x))   # forward pass: run the chain, get one number
loss.backward()            # backward pass: chain rule, fills p.grad for every parameter
optimizer.step()           # update: p = p - lr * p.grad

Why not simply nudge each knob and measure the loss? Because a network with a million weights would need a million extra forward passes for one step. Backpropagation gets every gradient from one forward pass and one backward pass, because each link’s work is reused by every knob behind it. That economy is why the method won, and it is the property TextGrad tries to keep: a backward pass that visits each edge of the graph once.

Keep those three lines in mind. TextGrad keeps every one of them, and changes only what “gradient” means: a sentence that says how to change a variable to make the score better.

In the chain rule, why does each link in the chain only need its own local rate and the message arriving from downstream?

Chapter 2

The Textual Gradient

Turn a score into a written criticism that says how to change a variable, and see the exact request that asks for it

A teacher marks your essay. She does not write “−32” in the margin. She writes, “This paragraph never says why the refund window matters. Add one sentence.” You know at once what to change, and where. That note does the job of a gradient: it points from a bad score toward a better draft.

TextGrad makes this the definition. A textual gradient is natural language feedback that describes how a variable should change to improve the final objective. The paper’s own wording for what it looks like is “this response can be improved by…”. A variable is any piece of text the system can change: a prompt, an answer, a code snippet. A language model call that writes such feedback plays the role of the derivative.

Start with the smallest graph

The paper opens with a system of two calls. In its notation, + joins two strings.

Prediction = LLM(Prompt + Question)    Evaluation = LLM(Evaluation Instruction + Prediction)

The first call answers a question using a prompt. The second call grades that answer. The Prompt is the free parameter we want to improve. Backpropagation asks for the gradient of the Evaluation with respect to the Prompt. We get it in two hops, exactly as in Chapter 1.

∂Eval/∂Pred
The gradient on the prediction: feedback that says how the prediction should change to get a better evaluation. It is a piece of text.
∇LLM(Pred, Eval)
The gradient operator for an LLM call. It takes the variable and what lies downstream, and returns criticism. For the last link, the downstream thing is the evaluation itself.
∂Eval/∂Prompt
The gradient on the prompt: how the prompt should change. This is what we want.
∂Eval/∂Pred
The message that arrives from downstream, the same text we just computed. It is the first factor of the chain rule.
∂Pred/∂Prompt
The local link: the call that turned the prompt into the prediction. It cannot be written as a number. Its job is done by the operator instead.
∇LLM(Prompt, Pred, …)
The operator again. It now sees the prompt, the prediction the prompt produced, and the criticism of that prediction.

Compare with Chapter 1. There, the downstream gradient ∂L/∂y was multiplied by a local rate. Here, the downstream criticism is placed in front of a language model, together with the local context. The multiplication became a request.

The operator is a request

How is ∇LLM built? The paper’s Equation 6 shows the idea, and says the exact prompts differ “to ensure generality”. In short: “Here is a conversation with an LLM: {x | y}. Below are the criticisms on {y}: {∂L/∂y}. Explain how to improve {x}.” Three pieces go in: the conversation (the variable x and the output y it caused), the downstream criticism of y, and a plain request.

The appendix prints the real prompt for a system-prompt variable. It tells the model the variable’s role in a tag, shows the conversation inside tags (LM_SYSTEM_PROMPT, LM_INPUT, LM_OUTPUT), pastes the downstream criticism inside OBJECTIVE_FUNCTION tags, marks the variable in VARIABLE tags, and asks: “describe how the system prompt to a language model could be improved… Be very creative, critical, and intelligent.” The system part of the prompt also tells the critic to stay quiet when the variable already works. Build it below, piece by piece.

Assemble the backward request

Switch pieces on and off. The final request is built live below. Ask what the critic can and cannot know with each piece missing.

The text is the paper’s own example backward prompt (Appendix A, system prompt of a counting task), shortened with … where the paper’s text is long. The paper notes that the real prompts differ from its exposition so that one operator works for every application. Character counts are of the shortened text shown here, not of the full prompt.

With all four pieces, the critic sees which prompt produced which answer, what was wrong with that answer, and exactly which words to improve. Switch off the downstream criticism and the critic has no reason to say anything useful: it sees a conversation that looks fine. Switch off the variable and it does not know which span to rewrite. The request is cheap to build, because it is only string assembly plus one call.

What stays fixed, what changes

The paper stresses one point: once the operator for LLM calls is written, it stays fixed for every application. The same backward prompt serves code, science questions, molecules and treatment plans. Only the objective (the final score) changes. That is why the framework is general: nobody rewrites the gradient code when the domain changes.

Two details differ from numbers. First, a numeric gradient has the same shape as its variable, one number per entry. A textual gradient has no fixed shape: it is a piece of text, long or short, and the variable can be longer than its criticism or the reverse. Second, each backward step is a language model call that costs money and may be wrong. The criticism can be noisy. The optimizer in Chapter 4 is told this: “The feedback may be noisy, identify what is important and what is correct.”

When it goes wrong

The symptom: the gradient praises a bad answer, or gives generic advice such as “be more clear”. The measurement: print the gradient text for a failing example, and ask whether a person could act on it. The usual fix is to give the operator what the device above shows: the role of the variable, the full conversation, and a pointed downstream criticism. A vague objective produces vague gradients.

In TextGrad’s backward pass, what takes the place of multiplying the downstream gradient by a local derivative?

Chapter 3

The Graph and the Chain Rule Through Text

Wire variables and functions into a graph, then collect criticism from every place a variable was used

A cook writes one recipe card and uses it three nights in a row: soup on Monday, stew on Tuesday, curry on Wednesday. Each dinner gets a review. Monday: “Too salty.” Tuesday: “Meat was tough.” Wednesday: “Great.” Before the cook rewrites the card, she wants all three reviews in front of her. A change that fixes Tuesday should not ruin Wednesday.

That is the situation inside any system where one variable is used more than once. A single system prompt serves many questions. A single code snippet is tested on many inputs. Chapter 2 gave us the criticism for one use. This chapter shows how to gather criticism from all of them.

A system is a graph

TextGrad describes any system as a computation graph: a set of variables, joined by functions. A variable holds data, mostly text. A function consumes some variables and produces another. The paper writes this in one line.

v
A variable: a prompt, an answer, a code snippet, a molecule written as text.
fv
The function that produces v. It can be an LLM call, a code interpreter, a simulator or a numerical solver. It need not be differentiable.
PredecessorsOf(v)
The variables that go into fv to make v. In the cooking story: the recipe card and the ingredients.
v ∈ V
“For every v in the set V of all variables in the graph.”

The graph in the paper’s Chapter 2 example has three variables in a row: Prompt, Prediction, Evaluation. A larger system has branches and joins. A variable with no predecessors is an input. A variable with no successors is the objective, the final score that everything is trying to improve. The paper stresses that the objective may be any function, with text in and text out, such as a code interpreter that returns test results.

Gather the criticism from every use

Now the central equation. To find the gradient of the objective with respect to a variable v, look at every place v was used. Those places are the successors of v. For each one, run the Chapter 2 operator, with the criticism of that successor in hand. Then keep all the answers.

∂L/∂v
The gradient on v: a set of contexts and criticisms, one for each place v was used.
∪w ∈ SuccessorsOf(v)
“Collect over all successors w of v.” The paper’s word is collect, not add. Text does not add; it is gathered side by side.
∇f(v, w, ∂L/∂w)
The operator for the function f that turned v into w. It sees v, the result w, and the criticism of w that already arrived from downstream.

Compare with Chapter 1. In a numeric graph, gradients from two uses of a weight are added. In TextGrad they are concatenated: the optimizer will later read all the criticisms as one block of text. The paper says it this way: the final gradient variable “comprises a set of contexts and criticisms for any place a variable was used in.”

Work the order of operations. The recursion needs a successor’s gradient before the predecessor’s, so the backward pass walks the graph from the objective back toward the inputs, just as in Chapter 1. Each variable object stores its value, a short role description (for example “system prompt to the language model”), a flag that says whether it needs a gradient, and a list for the criticisms that arrive.

For this to work, the forward pass must keep a record. Each time a function makes a variable, TextGrad stores which variables went in and what the call was. Without that record, the backward pass could not build the request of Chapter 2, because it would not know which conversation produced the output. PyTorch keeps the same kind of record to run its chain rule. A variable also carries a flag, requires_grad. A question that needs no improvement is an input with the flag off, so no backward call is spent on it.

How many calls does it cost?

The paper gives a bound: for a graph with n edges, each iteration makes at most n extra language model calls to compute gradients, one per edge. An edge that leads away from every variable you want to improve needs no call at all. Build a batch of questions below and count.

Gather criticism from every use

One prompt is used on a batch of questions. Each answer gets a score, and the scores are summed. Choose the batch size, then press Run backward pass and watch the criticism flow from the sum to the prompt.

3

The structure follows the paper’s batch setup (Section 2, tg.sum, and Appendix A.3): the scores are joined by tg.sum, whose backward step hands the same feedback to every score. The 40 words per criticism are illustrative. The edge count is ours: 4 edges per question (question to answer, prompt to answer, answer to score, score to sum); the question is an input that needs no gradient, so only 3 per question lie on a path to the prompt.

With a batch of 3 the graph has 12 edges, and 9 of them lie on a path to the prompt. So one backward pass costs about 9 language model calls, and it hands the prompt 3 criticisms to read together. That is the cook’s three reviews on one table. The paper uses exactly this for prompt optimization, with a batch size of 3 (Chapter 5).

The sum is the quiet hero

The paper defines tg.sum to join many losses. Going forward, it joins them as one string, one per line. Going backward, it does the simplest possible thing: it passes the gradient on its output to each input. This mirrors numeric addition, where the gradient of a sum is the same for every term. It is why batching works with no new idea.

When it goes wrong

The symptom (our reading, not a result in the paper): with a large batch, the optimizer must read a long block of criticisms, some of which disagree. The measurement: count the words in the concatenated gradient, as the device above does. The fix: use a small batch, which is what the paper does, and rely on the optimizer prompt’s reminder that feedback may be noisy.

A prompt variable is used in 4 different calls in the graph. What does the backward pass give the optimizer for that prompt?

Chapter 4

The Optimizer: Textual Gradient Descent

Apply a pile of criticisms to a variable with one more language model call, then add momentum and rules

An editor receives your draft with a stack of margin notes. Her job is not to write a new essay. It is to read the notes, decide which ones matter, and hand back a revised draft. She also has house rules: “Always keep the headline format.” Some notes are wrong, and she ignores those. The revised draft is the update.

Chapter 2 gave us the notes. This chapter gives us the editor. In Chapter 1 the update was one line of arithmetic, w − η · gradient. For text there is no subtraction that makes sense, so the paper does the natural thing: the update is also a call to a language model.

xnew
The improved variable: the text that replaces x.
TGD.step
Textual Gradient Descent, one step. In the paper’s Equation 9 it is a request: “Below are the criticisms on {x}: {∂L/∂x}. Incorporate the criticisms, and produce a new variable.”
x
The current value of the variable, such as the old prompt.
∂L/∂x
All the criticisms collected in Chapter 3.
x − ∂L/∂x
What numeric gradient descent does. Text cannot be subtracted, so TGD does not do this.

As with the gradient operator, TGD does not depend on the application. The same optimizer edits prompts, code, solutions and molecules. Equation 12 states the general case: for any variable v in the graph, vnew = TGD.step(v, ∂L/∂v).

What the optimizer receives and returns

The appendix prints the real prompts. The system prompt of the optimizer says it is “part of an optimization system that improves text”, that “the feedback may be noisy, identify what is important and what is correct”, and that it “MUST” send the new text between <IMPROVED_VARIABLE> tags. The user message holds the variable’s role, its current text in <VARIABLE> tags, and a <CONTEXT> with the conversation and the <FEEDBACK>. The reply is a string. The code reads whatever sits between the tags and writes it into the variable. Those tags are the interface: a string in, a string out, a parse.

Notice what is missing: a step size. In numeric descent, η says how far to move. In TextGrad the optimizer decides how far, and the gradient can carry the size in words. In the paper’s radiotherapy example the criticism says to “slightly increase” two weights, a step size written in plain English (Chapter 7).

Work one step by hand with the paper’s example. Step 1. The variable is a short system prompt, “Think step by step” plus the answer format. Step 2. Two criticisms have been collected: state each quantity and the sum, and verify each intermediate step. Step 3. The optimizer request holds the role, the prompt, the conversation and both criticisms. Step 4. The reply sits between the tags and holds the prompt plus two new directives. Step 5. The code parses the tags and stores the new text. Every step is string handling around a single call.

Three knobs from classical optimization

The paper borrows three ideas from numeric optimization. Each one is a few extra lines in the optimizer’s request.

Momentum. In numeric momentum, the update remembers earlier gradients, which smooths out noise. In TextGrad, the optimizer “can optionally see the earlier iterations of the variable.” The code adds a block, <PAST_ITERATIONS>, with the earlier values. In code, momentum_window=3 keeps the last three. So the editor sees the earlier drafts, and avoids re-making a change that was already tried.

Constraints. The optimizer takes constraints, plain-language rules appended inside <CONSTRAINTS> tags. The paper’s example: “The last line of your response should be of the following format: ‘Answer: $LETTER’ where LETTER is one of ABCD.” The paper notes that instruction-tuned models follow simple constraints, and that reliability drops with too many.

In-context examples. The optimizer can be shown examples of good variables, inside an <EXAMPLES> block, so that it knows what an optimized variable looks like. Change the switches below to see how each addition changes the request.

Run one optimizer step

The prompt below is the variable. Two criticisms have arrived. Choose which ones the optimizer sees, then add momentum or a rule, and compare the new prompt and the request.

The two criticisms and their suggested sentences come from the paper’s example optimizer prompt (Appendix A.4, a counting task). The new prompt is our illustrative result of applying them; in the paper a language model writes it and may phrase it differently. The two past prompts shown under momentum are made up. The request is shortened, and the character count is of the text shown here. The failure shown when the constraint is off is an illustration of the risk the paper’s constraint feature addresses, not a measured result.

Try the cases. With both criticisms and the constraint on, the new prompt gains two directives and still ends with the answer format. Turn the constraint off and the device shows a plausible rewrite that drops the format line. A grader that looks for “Answer:” would then fail every response, even if the reasoning improved. That is the reason constraints exist.

When it goes wrong

The symptom: the score drops after an update, or the prompt grows long and contradictory. The measurement: compare the score before and after the step on held-out examples. The fix in the paper’s prompt-optimization recipe: keep the new prompt only if the validation score improved (Chapter 5). Momentum and constraints add stability, but a single noisy criticism can still push the text the wrong way.

What is one TextGrad optimizer step, in terms of data flow?

Chapter 5

The Loop in Practice

Run forward, backward and update as real code, in two modes, and learn why the prompt loop keeps a change only if validation improves

Two students prepare for an exam. The first has one practice question and a red pen. She writes an answer, reads her own critique, and rewrites the answer, three times. At the end, the answer is better, and the work is done. The second student has no single question. She is writing a one-page study guide that must help on every question the exam will ask. She tries the guide on a few questions, sees where it fails, and revises the guide.

These are the two modes the paper separates. In instance optimization, the variable is the solution: a code snippet, an answer, a molecule. The goal is a better solution for this one problem, now. In prompt optimization, the variable is a prompt that is shared across many questions. The goal is a prompt that generalizes. The loop is the same in both. The data differ.

Instance optimization in nine lines

The paper’s first code listing improves an answer to a hard science question at test time. The loss is self-supervised: it does not use the correct answer. A language model critiques the current answer, and the critique is the loss.

pythonsolution = zero_shot_llm(question)                      # a tg.Variable: the first attempt
optimizer = tg.TextualGradientDescent(parameters=[solution])
for iteration in range(max_iterations):
    optimizer.zero_grad()                                 # clear last round's criticisms
    loss = test_time_loss_fn(question, solution)          # an LLM critiques the answer
    loss.backward()                                       # criticism flows back to the solution
    optimizer.step()                                      # the solution is rewritten

Read it as PyTorch. zero_grad clears stored gradients, so old criticism does not pile up. The loss function’s prompt (the paper calls it the Solution Refinement Objective) asks the model to act as “a critical and creative scientist”, to go through the reasoning, and to think about whether alternative answers could be true. For code, the loss prompt also includes the local test results. In the coding runs, each iteration makes 3 calls to gpt-4o: one to evaluate, one to collect the gradient, one to update (Appendix C).

Prompt optimization in the same shape

The second listing optimizes a system prompt. Three things change. The variable is a tg.Variable marked requires_grad=True, with a role description. The model is a tg.BlackboxLLM that holds that prompt. And each iteration uses a small batch of training questions.

pythonsystem_prompt = tg.Variable("You are a helpful language model. Think step by step.",
                          requires_grad=True, role_description="system prompt to the language model")
model = tg.BlackboxLLM(system_prompt=system_prompt)
optimizer = tg.TextualGradientDescent(parameters=[system_prompt])
for iteration in range(max_iterations):
    batch_x, batch_y = next(train_loader)
    optimizer.zero_grad()
    responses = model(batch_x)                                    # forward: b answers
    losses = [loss_fn(r, y) for r, y in zip(responses, batch_y)]
    total_loss = tg.sum(losses)                                   # Chapter 3: join the scores
    total_loss.backward()                                         # b criticisms reach the prompt
    optimizer.step()                                              # the prompt is rewritten

The setup in the paper: the model that answers is the cheap gpt-3.5-turbo-0125. The model that writes gradients and updates the prompt is the stronger gpt-4o. The batch size is 3, with 12 iterations, so the cheap model sees 36 training examples, drawn at random with replacement. The authors note why this is useful: “by paying a fixed cost to optimize a prompt, the prompt-optimized weaker model can be used with cheaper inference costs”.

The validation check

Chapter 4 ended on a worry: one noisy criticism can make a prompt worse. The paper’s guard is simple. After each iteration, run the validation set (examples held out from training) and update the prompt only if the performance is better than before. Without such a check, the loop is a random walk with a push in the right direction. With it, the accuracy cannot fall. Run the toy below to see the difference.

Keep a rewrite only if it helps

Each iteration proposes a new prompt. Some rewrites help, some hurt. Choose whether the loop checks validation accuracy before it keeps a rewrite. Press Try another run to draw new proposals.

A toy simulation, not a result from the paper. The start, 72.9%, and the dashed line, 81.1%, are the paper’s GSM8k accuracies before and after 12 iterations (Table 3). Each proposal changes accuracy by a random amount (mean +0.7 points, spread 3 points) from a seeded generator. The paper states the keep-if-better rule for prompt optimization; it does not report a run without it.

The check has a visible price, and the paper’s numbers let us count it. For the two Big Bench Hard tasks the validation set has 100 examples. Twelve iterations of validation then cost 12 × 100 = 1,200 answers from the cheap model. Training itself needs only 12 × 3 = 36. So the guard costs more than 30 times the training forward calls, in cheap calls. This is our arithmetic from the paper’s setup, not a figure the paper reports.

With the check, every curve climbs or stays flat, because a bad proposal is thrown away and the previous prompt stays. Without it, some runs dip under their start. The paper does not report a call count for this task, so treat the estimate above as an order of magnitude.

What the paper compares, and what it does not

The paper has no table that removes one part of TextGrad at a time, so there is no true ablation of the method. It offers one related comparison instead. The baseline DSPy optimizer adds demonstrations to the prompt, while TextGrad rewrites the instruction. The two are complementary. On GSM8k, combining DSPy’s demonstrations with TextGrad’s instruction raised accuracy to 82.1%, up from 81.1% for either alone. That is one dataset and one run, so treat it as a hint.

What is the difference between instance optimization and prompt optimization in TextGrad?

Chapter 6

What the Tables Show

Read the three result tables as an engineer would: what was run, what was compared, and how large each gain really is

A friend tells you a new diet helped her lose four kilos. Before you copy it, you ask questions. Over how long? Compared with what? Was it one person or fifty? A result is a number plus the story of how it was made. This chapter reads TextGrad’s three tables with those questions in hand.

The tasks fall into the two modes of Chapter 5. Tables 1 and 2 are instance optimization: the variable is a solution, improved at test time. Table 3 is prompt optimization: the variable is a system prompt, improved on training questions and then tested on unseen ones.

Table 1: LeetCode Hard (code)

The task. LeetCode Hard is a set of hard programming problems (39 of them here). Success is the completion rate: the share of problems whose code passes every hidden test, which only the LeetCode site can check. The method. The code is the variable. The loss prompt holds the problem, the code, the local test results and an instruction to judge correctness and speed. Five iterations; no demonstrations. The baselines. A zero-shot gpt-4o, and Reflexion, a method where the model reflects on its failed tests and tries again (one demonstration, five iterations).

The numbers. Table 1 reports zero-shot 0.26, Reflexion 0.31 ± 0.012 and TextGrad 0.36 ± 0.018, averaged over 5 seeds. Two cautions. First, the text of the paper says zero-shot gpt-4o reached 23%, while the table prints 0.26; the two disagree, and we show the table. Second, the authors re-ran Reflexion and had to re-extract the dataset, so it is “likely” not identical to the one in the original Reflexion paper. With 39 problems, one problem is worth about 2.6 points. A gain of 5 points over Reflexion is about two problems.

Table 2: science questions

The task. GPQA is a multiple-choice benchmark of hard physics, biology and chemistry questions written by PhD-level experts. The paper reports experts at 81% and skilled non-experts at 22%. It also uses two MMLU subsets, Machine Learning and College Physics. The method. The solution is the variable, improved for 3 iterations with a self-critique loss, then a majority vote across the solutions. The baselines. Chain of thought at temperature 0 (51.0 on GPQA), and the figure OpenAI reported for gpt-4o (53.6).

The numbers. TextGrad scores 55.0 on GPQA, 88.4 against 85.7 on MMLU Machine Learning, and 95.1 against 91.2 on College Physics. The paper calls 55% the best known GPQA result at the time. Note that TextGrad spends more compute at test time: several critique and update calls per question, plus a vote. The authors say so: the gain comes from “spending more computation at test-time”. A fair reading is: more thinking time buys a few points. The table gives no spread, so we cannot judge how much of a 2 to 4 point gain is noise.

Table 3: prompts for reasoning

The task. Three reasoning sets: Object Counting and Word Sorting from Big Bench Hard (50 training, 100 validation, 100 test items each) and GSM8k grade-school math. The method. Optimize the system prompt of gpt-3.5-turbo with gpt-4o as the gradient engine: batch 3, 12 iterations, keep the prompt if validation improved. The baselines. Zero-shot chain of thought, and DSPy’s bootstrapped few-shot search with 8 demonstrations.

The numbers. Object Counting: 77.8, DSPy 84.9, TextGrad 91.9. Word Sorting: 76.7, DSPy 79.8, TextGrad 79.8. GSM8k: 72.9, DSPy 81.1, TextGrad 81.1. TextGrad wins on one task and ties on two. It does so with an instruction only and no demonstrations, which keeps the prompt short and inference cheap. Use the device to compare the methods on every task.

Compare the methods on each task

Pick a task. Each bar is one method’s score from the paper. The warm bar is TextGrad.

All scores are from the paper: Table 1 (completion rate in %, mean of 5 seeds, ± shown in the read-out), Table 2 (accuracy %, gpt-4o) and Table 3 (accuracy %, gpt-3.5-turbo-0125 with gpt-4o as the gradient engine). The text of the paper gives 23% for zero-shot gpt-4o on LeetCode Hard; Table 1 prints 0.26, which we show.

What the figures add

Figure 1 is a map, not a result. Panel (a) shows a neural network passing numbers forward and gradients back; (b) shows the same loop with an LLM, a search tool and a prompt; (c) shows the matching names: tg.BlackboxLLM for ResNet50(), tg.TextLoss for CrossEntropyLoss(), tg.TGD for SGD. Panels (d) to (g) preview the molecule, code, treatment plan and prompt cases. In (g) a counting prompt goes from 77.8% to 91.9%, the same Object Counting numbers as Table 3.

When to trust it

The symptom to watch for is a small gain on a small test. The measurement is the spread across seeds and the size of the test set. The fix is to re-run on your own task with your own metric. The pattern is clearest in Table 3, where the gradient engine is stronger than the model it improves. The paper does not test whether the method works when both are the same weak model, so we do not know.

The LeetCode Hard table has only 39 problems. What does that imply about the 5-point gain of TextGrad over Reflexion (36% against 31%)?

Chapter 7

Molecules and Radiotherapy: A Simulator Inside the Loop

Follow two science cases where a simulator scores the variable and a language model turns the score into advice

A chemist sketches a molecule and sends it to a docking program. The program replies with a number: how tightly the molecule would bind to a target protein. A number is not advice. The chemist needs a sentence such as “add a group that can form hydrogen bonds.” Now picture a language model sitting between the program and the chemist, turning each score into that sentence. That is the shape of the paper’s two science cases.

Both cases use instance optimization (Chapter 5). The variable is a single object, written as text. The function that scores it is not a language model but a numerical tool. This is the case the graph in Chapter 3 allowed for: any function can sit in the graph, as long as something turns its output into a criticism.

Case 1: designing a drug-like molecule

The variable. A molecule written as a SMILES string, a line of text such as c1ccccc1 (benzene) that spells out the atoms and bonds. The two scores. The Vina score from the AutoDock Vina docking tool estimates binding strength; more negative is better, in kcal/mol. The QED score from RDKit measures drug-likeness on a scale from 0 to 1, where 1 is best. The two pull against each other: docking rewards big molecules with many groups, drug-likeness rewards small, simple ones.

The loop. The paper starts from a small fragment, scores it, asks gpt-4o for a textual gradient on the SMILES string, and rewrites it. This runs for 10 iterations. The authors repeat it for 3 starting fragments on each of 58 protein targets from the DOCKSTRING benchmark, 29 of which have clinically approved drugs. The new SMILES is a variable like any other.

The numbers. Figure 2 follows one run on the target PPARA. The gradients in the first two steps read, in the paper’s words, “Introduce functional groups that can form hydrogen bonds or hydrophobic interactions” and “Add hydrophobic groups or aromatic rings to enhance interactions… while maintaining a balance of hydrophobic and hydrophilic properties.” The molecule moves from Vina −4.2 and QED 0.44, to −5.5 and 0.59, to −7.5 and 0.79.

Case 2: planning a radiation treatment

The setting. A radiotherapy plan must give the tumor region (the PTV, planning target volume) the prescribed dose, in grays (Gy), while sparing nearby healthy organs, the organs at risk, here the bladder and rectum. A numerical solver, matRad, computes the plan from a set of weights that say how much each region matters. Human planners tweak those weights by trial and error.

The two loops. The inner loop is matRad: given weights, it returns a plan. TextGrad runs the outer loop. The variable is a string of weights, “weight for PTV: […], weight for bladder: […], weight for rectum: […]…”. The plan is scored by a language model against the clinical goals, the criticism flows back to the weights, and the weights are rewritten. To help the optimizer see how weights shape plans, the update also receives earlier pairs of weights and plans, a use of the momentum idea from Chapter 4. Step through both cases below.

Step a simulator-in-the-loop run

Choose a case, then drag the iteration. The picture shows the simulator’s numbers. The text box shows the criticism the paper prints for that step.

1

Molecule case: the three (Vina, QED) points are printed in Figure 2a of the paper (target PPARA, one run); Figure 1 prints −4.3 for the first. Plan case: the doses are read off Figures 3b and 3c by eye and are accurate to about 1 Gy, not exact; the PTV mean dose goal is 70.20 Gy. The two gradients quoted for the plan are printed in Figure 3a; the paper shows no gradient text for other steps. The plan loop in the paper runs 5 iterations.

In the plan case, the first step overshoots. Raising the PTV weight pushes the dose to the bladder above its allowed maximum of 30 Gy (Figure 3c). The next gradient notices and says, in the paper’s words, to “slightly increase the importance weight for the bladder and rectum.” Over the following iterations the organ doses fall back. This is the kind of balancing act a human planner does by hand, written as a sequence of sentences you can read.

What the paper claims, and what it does not

For molecules, the paper reports that TextGrad improves binding and drug-likeness for all 58 targets, whatever the starting fragment, and that on the 29 targets with approved drugs the results are “highly competitive” with clinical molecules scored by the same loss. For plans, on five prostate cancer patients, Figure 3d reports the PTV mean dose as a deviation from the 70.20 Gy goal: +0.51 Gy (±0.09) for TextGrad against +1.97 Gy (±0.36) for the clinical plans, and the D95 deviation as +0.00 for TextGrad against −0.10 Gy (±0.15). Figure 3e shows lower mean organ doses: bladder 20.92 Gy against 22.39 Gy, rectum 17.18 Gy against 23.88 Gy.

Read these with care. All molecule results are in silico, meaning scored by programs, not tested in a lab. The paper says the real test “requires experimental and clinical assessments, which are outside of the scope of this paper.” The plan study has five patients. And the paper’s own prose says TextGrad achieves “a higher mean dose”, while the table shows it closer to the goal than the clinical plan; we follow the table.

The symptom to expect in a case like this is an optimizer that gets one score better by breaking another, as the first plan step did. The measurement is to track every objective at every step, as the device does. The fix in the paper is the objective itself: a loss that names all the goals, so the criticism has to balance them.

In the radiotherapy case, what is the variable that TextGrad rewrites, and what produces the plan that gets scored?

Chapter 8

Field Guide: TextGrad on One Page

Review the method, keep the numbers and terms at hand, read the core as code, and decide when to reach for it

You can now re-derive TextGrad from memory. The recipe has one sentence of idea and three calls of code. Describe your system as a graph of variables and functions. Run it forward to a score. Run a backward pass in which a language model turns the score into criticism for each variable, one edge at a time. Then let a second language model rewrite each variable using its criticisms, and keep the rewrite if validation agrees.

The numbers that matter

WhatNumberWhy it matters
Backward cost per iterationat most 1 extra call per edgeThe cost of a gradient grows with the graph, not with the number of prompt variants (Section 2)
LeetCode Hard, completion rate0.26 zero-shot, 0.31 Reflexion, 0.36 TextGrad (5 seeds, 39 problems)Code refined with test results and self-critique beats a reflection baseline (Table 1)
GPQA, gpt-4o51.0 CoT, 53.6 best reported, 55.0 TextGradThree test-time updates and a vote add a few points (Table 2)
MMLU subsets85.7 to 88.4 (ML); 91.2 to 95.1 (physics)The gain holds on a second benchmark family (Table 2)
Object Counting prompt77.8 CoT, 84.9 DSPy, 91.9 TextGradAn instruction alone can beat 8 demonstrations (Table 3)
Word Sorting, GSM8k79.8 and 81.1 for both DSPy and TextGradTwo ties: the method is not always better (Table 3)
DSPy demonstrations plus TextGrad instruction82.1 on GSM8kThe two approaches are complementary (Section 3.3)
Prompt optimization setupbatch 3, 12 iterations, 36 examples seenSmall data, small batch (Section 3.3)
Molecule study58 targets, 3 fragments each, 10 iterationsScored in silico only (Section 3.4)
Radiotherapy, 5 patientsorgan mean dose 20.92 and 17.18 Gy against 22.39 and 23.88 GyLower organ dose than the clinical plans in this small sample (Figure 3e)

The terms

TermMeaningWhere
VariableA piece of text that can be improved, with a role descriptionChapter 3
Textual gradientFeedback that says how a variable should change to improve the objectiveChapter 2
Gradient operatorThe language model call that writes that feedback for one edgeChapter 2
TGDTextual Gradient Descent: a language model call that rewrites a variable from its criticismsChapter 4
tg.sumJoins losses for a batch; its backward step hands the feedback to every inputChapter 3
Instance / prompt optimizationImprove one solution now, or one prompt that must generalizeChapter 5
Compound AI systemSeveral models and tools wired togetherChapter 0

The core as code

Here is the whole data flow in a sketch we wrote, not the paper’s code. It assumes a graph that is a chain, and a function llm(text) -> text. The real library handles general graphs, the exact prompts, momentum and constraints.

pythonclass Variable:
    def __init__(self, value, role, requires_grad=False, preds=(), ctx=""):
        self.value, self.role, self.requires_grad = value, role, requires_grad
        self.preds, self.ctx = list(preds), ctx          # who made me, and the call that did
        self.gradients = []                              # criticisms: one per use (Eq. 11)

def forward(llm, prompt, question):                    # Prompt + Question -> Answer
    answer = llm(prompt.value + "\n" + question)
    return Variable(answer, "answer", preds=[prompt], ctx=question)

def loss(strong, rubric, answer):                      # objective: an LLM judges the answer
    verdict = strong(rubric + "\n" + answer.value)
    out = Variable(verdict, "evaluation", preds=[answer])
    out.gradients = [verdict]                            # the verdict is the first criticism
    return out

def backward(strong, w):                               # Eq. 6: one call per edge v -> w
    for v in w.preds:
        ask = (f"Role of the variable: {v.role}\n"
               f"Conversation: INPUT {w.ctx} OUTPUT {w.value}\n"
               f"Criticism of the output: {' '.join(w.gradients)}\n"
               f"<VARIABLE>{v.value}</VARIABLE>\nHow could the variable be improved?")
        v.gradients.append(strong(ask))                  # collect, do not add (Eq. 11)
        backward(strong, v)

def step(strong, v):                                   # TGD.step (Eq. 9)
    ask = (f"Role: {v.role}\n<VARIABLE>{v.value}</VARIABLE>\n"
           f"<FEEDBACK>{chr(10).join(v.gradients)}</FEEDBACK>\n"
           "Improve the variable. Reply inside <IMPROVED_VARIABLE> tags.")
    reply = strong(ask)
    v.value = reply.split("<IMPROVED_VARIABLE>")[1].split("</IMPROVED_VARIABLE>")[0].strip()
    v.gradients = []                                     # zero_grad

Count the shapes. Every value is a string. The forward pass makes one call per node. The backward pass makes one call per edge toward a variable that needs improving. The step makes one call per variable. Nothing here needs a GPU or a gradient tensor. Read it line by line and name the chapter behind each choice.

Should you reach for it?

Use the four switches below. Each one is a condition the paper’s results lean on.

Check the fit

Switch on each condition that is true for your task. The lamps show how many the paper’s results lean on.

A rule of thumb we wrote from the paper’s setups, not a result in it. In Table 3 the gradient engine (gpt-4o) is stronger than the model it improves (gpt-3.5-turbo-0125); the paper does not test the case where both are the same weak model.

What it does not do

The paper names its limits. The applications are first steps: the molecule and plan results are in silico, and “the ultimate test requires experimental and clinical assessments”. The method relies on the assumption that today’s best models can reason about each component, and the constraints it uses work best with few rules. The authors list stability as an open problem: ideas such as variance reduction, adaptive gradients and self-verification are listed as future work. We add three things the paper does not measure. It does not report the dollar or time cost of a run. It does not report a run without the validation check. And criticism written by a language model can be wrong; the optimizer prompt says so, and a numeric gradient is not noisy in this way.

Where this sits

The paper credits two close relatives. ProTeGi defined textual gradients for prompt optimization. DSPy treats LLM systems as programs and optimizes them, and is the baseline in Table 3. TextGrad’s step beyond both is to optimize instances too: code, molecules, plans. It is the first reading of Lecture 2, Context Evolution, and the next lecture, LLMs as Optimizers, widens the same idea.

Keep going

The takeaway. A gradient is only a message that says how to change an input to improve a score. TextGrad shows that, for a system of language models and tools, that message can be a written sentence, passed backward one edge at a time. It buys generality, readable feedback and a PyTorch-like loop. It costs extra calls, and it leans on a model that criticizes well.
You have a pipeline of three LLM calls and a rubric that scores the final answer. Which set of steps follows TextGrad?

Now press Teach and explain one TextGrad step out loud, from memory: what the forward pass makes, what the backward request holds, what the optimizer returns, and why the prompt is kept only if validation improves. Then go back to the loop at the top and run it again.

TextGrad: Automatic “Differentiation” via Text
Read the paper · The code · Lecture 2, Context Evolution · Back to Gleams