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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
pinned: false
|
8 |
---
|
9 |
|
10 |
+
![Logo](logo_full.png)
|
11 |
+
|
12 |
+
<!--- BADGES: START --->
|
13 |
+
[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/zou-group/TextGrad/blob/main/examples/notebooks/Prompt-Optimization.ipynb)
|
14 |
+
[![GitHub license](https://img.shields.io/badge/License-MIT-blue.svg)][#license-gh-package]
|
15 |
+
[![Arxiv](https://img.shields.io/badge/arXiv-2406.07496-B31B1B.svg)][#arxiv-paper-package]
|
16 |
+
[![Documentation Status](https://readthedocs.org/projects/textgrad/badge/?version=latest)][#docs-package]
|
17 |
+
[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/textgrad)][#pypi-package]
|
18 |
+
[![PyPI](https://img.shields.io/pypi/v/textgrad)][#pypi-package]
|
19 |
+
[![Conda - Platform](https://img.shields.io/conda/pn/conda-forge/textgrad?logo=anaconda&style=flat)][#conda-forge-package]
|
20 |
+
[![Conda (channel only)](https://img.shields.io/conda/vn/conda-forge/textgrad?logo=anaconda&style=flat&color=orange)][#conda-forge-package]
|
21 |
+
|
22 |
+
[#license-gh-package]: https://lbesson.mit-license.org/
|
23 |
+
[#arxiv-paper-package]: https://arxiv.org/abs/2406.07496
|
24 |
+
[#docs-package]: https://textgrad.readthedocs.io/en/latest/?badge=latest
|
25 |
+
[#pypi-package]: https://pypi.org/project/textgrad/
|
26 |
+
[#conda-forge-package]: https://anaconda.org/conda-forge/textgrad
|
27 |
+
<!--- BADGES: END --->
|
28 |
+
|
29 |
+
## TextGrad: Automatic ''Differentiation'' via Text
|
30 |
+
|
31 |
+
An autograd engine -- for textual gradients!
|
32 |
+
|
33 |
+
TextGrad is a powerful framework building automatic ``differentiation'' via text.
|
34 |
+
TextGrad implements backpropagation through text feedback provided by LLMs, strongly building on the gradient metaphor
|
35 |
+
|
36 |
+
We provide a simple and intuitive API that allows you to define your own loss functions and optimize them using text feedback.
|
37 |
+
This API is similar to the Pytorch API, making it simple to adapt to your usecases.
|
38 |
+
|
39 |
+
![Analogy with Torch](analogy.png)
|
40 |
+
|
41 |
+
## QuickStart
|
42 |
+
If you know PyTorch, you know 80% of TextGrad.
|
43 |
+
Let's walk through the key components with a simple example. Say we want to use GPT-4o to solve a simple
|
44 |
+
reasoning problem.
|
45 |
+
|
46 |
+
The question is *If it takes 1 hour to dry 25 shirts under the sun, how long will it take to dry 30 shirts under the sun? Reason step by step.* (Thanks, [Reddit User](https://www.reddit.com/r/OpenAI/comments/18q479x/comment/kf444es/))
|
47 |
+
|
48 |
+
```python
|
49 |
+
import textgrad as tg
|
50 |
+
|
51 |
+
tg.set_backward_engine("gpt-4o", override=True)
|
52 |
+
|
53 |
+
# Step 1: Get an initial response from an LLM.
|
54 |
+
model = tg.BlackboxLLM("gpt-4o")
|
55 |
+
question_string = ("If it takes 1 hour to dry 25 shirts under the sun, "
|
56 |
+
"how long will it take to dry 30 shirts under the sun? "
|
57 |
+
"Reason step by step")
|
58 |
+
|
59 |
+
question = tg.Variable(question_string,
|
60 |
+
role_description="question to the LLM",
|
61 |
+
requires_grad=False)
|
62 |
+
|
63 |
+
answer = model(question)
|
64 |
+
```
|
65 |
+
|
66 |
+
> :warning: **answer: To determine how long it will take to dry 30 shirts under the sun,**
|
67 |
+
> **we can use a proportional relationship based on the given information.**
|
68 |
+
> **Here’s the step-by-step reasoning: [.....]**
|
69 |
+
> **So, it will take 1.2 hours (or 1 hour and 12 minutes) to dry 30 shirts under the sun.**
|
70 |
+
|
71 |
+
|
72 |
+
As you can see, **the model's answer is incorrect.** We can optimize the answer using TextGrad to get the correct answer.
|
73 |
+
|
74 |
+
```python
|
75 |
+
|
76 |
+
answer.set_role_description("concise and accurate answer to the question")
|
77 |
+
|
78 |
+
# Step 2: Define the loss function and the optimizer, just like in PyTorch!
|
79 |
+
# Here, we don't have SGD, but we have TGD (Textual Gradient Descent)
|
80 |
+
# that works with "textual gradients".
|
81 |
+
optimizer = tg.TGD(parameters=[answer])
|
82 |
+
evaluation_instruction = (f"Here's a question: {question_string}. "
|
83 |
+
"Evaluate any given answer to this question, "
|
84 |
+
"be smart, logical, and very critical. "
|
85 |
+
"Just provide concise feedback.")
|
86 |
+
|
87 |
+
|
88 |
+
# TextLoss is a natural-language specified loss function that describes
|
89 |
+
# how we want to evaluate the reasoning.
|
90 |
+
loss_fn = tg.TextLoss(evaluation_instruction)
|
91 |
+
```
|
92 |
+
> :brain: **loss: [...] Your step-by-step reasoning is clear and logical,**
|
93 |
+
> **but it contains a critical flaw in the assumption that drying time is**
|
94 |
+
> **directly proportional to the number of shirts. [...]**
|
95 |
+
|
96 |
+
```python
|
97 |
+
# Step 3: Do the loss computation, backward pass, and update the punchline.
|
98 |
+
# Exact same syntax as PyTorch!
|
99 |
+
loss = loss_fn(answer)
|
100 |
+
loss.backward()
|
101 |
+
optimizer.step()
|
102 |
+
answer
|
103 |
+
```
|
104 |
+
|
105 |
+
> :white_check_mark: **answer: It will still take 1 hour to dry 30 shirts under the sun,**
|
106 |
+
> **assuming they are all laid out properly to receive equal sunlight.**
|
107 |
+
|
108 |
+
|
109 |
+
|
110 |
+
|
111 |
+
We have many more examples around how TextGrad can optimize all kinds of variables -- code, solutions to problems, molecules, prompts, and all that!
|
112 |
+
|
113 |
+
### Tutorials
|
114 |
+
|
115 |
+
We have prepared a couple of tutorials to get you started with TextGrad. The order of this
|
116 |
+
tutorial is what we would recommend to follow for a beginner. You can run them directly in Google Colab by clicking on the links below (but
|
117 |
+
you need an OpenAI/Anthropic key to run the LLMs).
|
118 |
+
|
119 |
+
<div align="center">
|
120 |
+
|
121 |
+
| Tutorial | Difficulty | Colab Link |
|
122 |
+
|----------------------------------------------------|-----------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
123 |
+
| 1. Introduction to TextGrad Primitives | ![](https://img.shields.io/badge/Level-Beginner-green.svg) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/zou-group/TextGrad/blob/main/examples/notebooks/Tutorial-Primitives.ipynb) |
|
124 |
+
| 2. Solution Optimization | ![](https://img.shields.io/badge/Level-Beginner-green.svg) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/zou-group/TextGrad/blob/main/examples/notebooks/Tutorial-Solution-Optimization.ipynb) |
|
125 |
+
| 3. Optimizing a Code Snippet and Define a New Loss | ![](https://img.shields.io/badge/Level-Beginner-green.svg) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/zou-group/textgrad/blob/main/examples/notebooks/Tutorial-Test-Time-Loss-for-Code.ipynb) |
|
126 |
+
| 4. Prompt Optimization | ![](https://img.shields.io/badge/Level-Intermediate-yellow.svg) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/zou-group/TextGrad/blob/main/examples/notebooks/Tutorial-Prompt-Optimization.ipynb) |
|
127 |
+
| 5. MultiModal Optimization | ![](https://img.shields.io/badge/Level-Beginner-green.svg) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/zou-group/TextGrad/blob/main/examples/notebooks/Tutorial-MultiModal.ipynb) |
|
128 |
+
|
129 |
+
</div>
|
130 |
+
|
131 |
+
### Installation
|
132 |
+
|
133 |
+
You can install TextGrad using any of the following methods.
|
134 |
+
|
135 |
+
**With `pip`**:
|
136 |
+
|
137 |
+
```bash
|
138 |
+
pip install textgrad
|
139 |
+
```
|
140 |
+
|
141 |
+
**With `conda`**:
|
142 |
+
|
143 |
+
```sh
|
144 |
+
conda install -c conda-forge textgrad
|
145 |
+
```
|
146 |
+
|
147 |
+
> :bulb: The conda-forge package for `textgrad` is maintained [here](https://github.com/conda-forge/textgrad-feedstock).
|
148 |
+
|
149 |
+
**Bleeding edge installation with `pip`**:
|
150 |
+
|
151 |
+
```sh
|
152 |
+
pip install git+https://github.com/zou-group/textgrad.git
|
153 |
+
```
|
154 |
+
|
155 |
+
See [here](https://pip.pypa.io/en/stable/cli/pip_install/) for more details on various methods of pip installation.
|
156 |
+
|
157 |
+
## More detailed examples
|
158 |
+
|
159 |
+
### Minimal Instance Optimization Example
|
160 |
+
|
161 |
+
TextGrad can optimize unstructured variables, such as text. Let us have an initial solution to a math problem that we want to improve. Here's how to do it with TextGrad, using GPT-4o:
|
162 |
+
|
163 |
+
```python
|
164 |
+
tg.set_backward_engine("gpt-4o")
|
165 |
+
|
166 |
+
initial_solution = """To solve the equation 3x^2 - 7x + 2 = 0, we use the quadratic formula:
|
167 |
+
x = (-b ± √(b^2 - 4ac)) / 2a
|
168 |
+
a = 3, b = -7, c = 2
|
169 |
+
x = (7 ± √((-7)^2 - 4 * 3(2))) / 6
|
170 |
+
x = (7 ± √(7^3) / 6
|
171 |
+
The solutions are:
|
172 |
+
x1 = (7 + √73)
|
173 |
+
x2 = (7 - √73)"""
|
174 |
+
|
175 |
+
# Define the variable to optimize, let requires_grad=True to enable gradient computation
|
176 |
+
solution = tg.Variable(initial_solution,
|
177 |
+
requires_grad=True,
|
178 |
+
role_description="solution to the math question")
|
179 |
+
|
180 |
+
# Define the optimizer, let the optimizer know which variables to optimize, and run the loss function
|
181 |
+
|
182 |
+
loss_fn = tg.TextLoss("You will evaluate a solution to a math question. Do not attempt to solve it yourself, do not give a solution, only identify errors. Be super concise.")
|
183 |
+
|
184 |
+
optimizer = tg.TGD(parameters=[solution])
|
185 |
+
loss = loss_fn(solution)
|
186 |
+
```
|
187 |
+
|
188 |
+
Output:
|
189 |
+
> Variable(value=Errors:
|
190 |
+
> 1. Incorrect sign in the discriminant calculation: it should be b^2 - 4ac, not b^2 + 4ac.
|
191 |
+
> 2. Incorrect simplification of the quadratic formula: the denominator should be 2a, not 6.
|
192 |
+
> 3. Final solutions are missing the division by 2a., role=response from the language model, grads=)
|
193 |
+
|
194 |
+
```python
|
195 |
+
loss.backward()
|
196 |
+
optimizer.step()
|
197 |
+
print(solution.value)
|
198 |
+
```
|
199 |
+
|
200 |
+
Output:
|
201 |
+
> To solve the equation 3x^2 - 7x + 2 = 0, we use the quadratic formula:
|
202 |
+
> x = (-b ± √(b^2 - 4ac)) / 2a
|
203 |
+
>
|
204 |
+
> Given:
|
205 |
+
> a = 3, b = -7, c = 2
|
206 |
+
>
|
207 |
+
> Substitute the values into the formula:
|
208 |
+
> x = (7 ± √((-7)^2 - 4(3)(2))) / 6
|
209 |
+
> x = (7 ± √(49 - 24)) / 6
|
210 |
+
> x = (7 ± √25) / 6
|
211 |
+
> x = (7 ± 5) / 6
|
212 |
+
>
|
213 |
+
> The solutions are:
|
214 |
+
> x1 = (7 + 5) / 6 = 12 / 6 = 2
|
215 |
+
> x2 = (7 - 5) / 6 = 2 / 6 = 1/3
|
216 |
+
|
217 |
+
### Minimal Prompt Optimization Example
|
218 |
+
TextGrad can also optimize prompts in PyTorch style! Here's how to do it with TextGrad, using GPT-4o for feedback, and optimizing a prompt for gpt-3.5-turbo:
|
219 |
+
```python
|
220 |
+
import textgrad as tg
|
221 |
+
llm_engine = tg.get_engine("gpt-3.5-turbo")
|
222 |
+
tg.set_backward_engine("gpt-4o")
|
223 |
+
|
224 |
+
_, val_set, _, eval_fn = load_task("BBH_object_counting", llm_engine)
|
225 |
+
question_str, answer_str = val_set[0]
|
226 |
+
question = tg.Variable(question_str, role_description="question to the LLM", requires_grad=False)
|
227 |
+
answer = tg.Variable(answer_str, role_description="answer to the question", requires_grad=False)
|
228 |
+
```
|
229 |
+
|
230 |
+
Question:
|
231 |
+
> I have two stalks of celery, two garlics, a potato, three heads of broccoli, a carrot, and a yam. How many vegetables do I have?
|
232 |
+
|
233 |
+
Ground Truth Answer:
|
234 |
+
> 10
|
235 |
+
|
236 |
+
```python
|
237 |
+
system_prompt = tg.Variable("You are a concise LLM. Think step by step.",
|
238 |
+
requires_grad=True,
|
239 |
+
role_description="system prompt to guide the LLM's reasoning strategy for accurate responses")
|
240 |
+
|
241 |
+
model = tg.BlackboxLLM(llm_engine, system_prompt=system_prompt)
|
242 |
+
optimizer = tg.TGD(parameters=list(model.parameters()))
|
243 |
+
|
244 |
+
prediction = model(question)
|
245 |
+
```
|
246 |
+
|
247 |
+
Prediction:
|
248 |
+
> You have a total of seven vegetables: two stalks of celery, two garlics, one potato, three heads of broccoli, one carrot, and one yam.
|
249 |
+
|
250 |
+
```python
|
251 |
+
loss = eval_fn(inputs=dict(prediction=prediction, ground_truth_answer=answer))
|
252 |
+
```
|
253 |
+
|
254 |
+
Loss denoting accuracy:
|
255 |
+
> Variable(value=0, grads=)
|
256 |
+
|
257 |
+
```python
|
258 |
+
loss.backward()
|
259 |
+
```
|
260 |
+
|
261 |
+
System prompt gradients:
|
262 |
+
> ... 2. **Encourage Explicit Summation**: - The prompt should encourage the model to explicitly state the summation process. This can help in verifying the accuracy of the count. For example, "Explain your calculations clearly and verify the total."....
|
263 |
+
|
264 |
+
```python
|
265 |
+
optimizer.step()
|
266 |
+
```
|
267 |
+
|
268 |
+
New system prompt value:
|
269 |
+
> You are a concise LLM. Think step by step. Prioritize accuracy in your calculations. Identify and count each item individually. Explain your calculations clearly and verify the total. After calculating, review your steps to ensure the total is correct. If you notice a discrepancy in your count, re-evaluate the list and correct any mistakes.
|
270 |
+
|
271 |
+
```python
|
272 |
+
prediction = model(question)
|
273 |
+
```
|
274 |
+
|
275 |
+
New prediction:
|
276 |
+
> Let's count the number of each vegetable:
|
277 |
+
> 1. Celery stalks: 2
|
278 |
+
> 2. Garlics: 2
|
279 |
+
> 3. Potato: 1
|
280 |
+
> 4. Broccoli heads: 3
|
281 |
+
> 5. Carrot: 1
|
282 |
+
> 6. Yam: 1
|
283 |
+
>
|
284 |
+
> Now, let's add up the total number of vegetables:
|
285 |
+
> 2 + 2 + 1 + 3 + 1 + 1 = 10
|
286 |
+
>
|
287 |
+
> You have a total of 10 vegetables.
|
288 |
+
|
289 |
+
|
290 |
+
|
291 |
+
### Citation
|
292 |
+
```bibtex
|
293 |
+
@article{yuksekgonul2024textgrad,
|
294 |
+
title={TextGrad: Automatic "Differentiation" via Text},
|
295 |
+
author={Mert Yuksekgonul and Federico Bianchi and Joseph Boen and Sheng Liu and Zhi Huang and Carlos Guestrin and James Zou},
|
296 |
+
year={2024},
|
297 |
+
eprint={2406.07496},
|
298 |
+
archivePrefix={arXiv}
|
299 |
+
}
|
300 |
+
```
|