tboen1 commited on
Commit
7135c50
1 Parent(s): a9545d7

Update README.md

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