An autograd engine -- for textual gradients!
TextGrad is a powerful framework building automatic ``differentiation'' via text. TextGrad implements backpropagation through text feedback provided by LLMs, strongly building on the gradient metaphor
We provide a simple and intuitive API that allows you to define your own loss functions and optimize them using text feedback. This API is similar to the Pytorch API, making it simple to adapt to your usecases.
If you know PyTorch, you know 80% of TextGrad. Let's walk through the key components with a simple example. Say we want to use GPT-4o to solve a simple reasoning problem.
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)
import textgrad as tg tg.set_backward_engine("gpt-4o", override=True) # Step 1: Get an initial response from an LLM. model = tg.BlackboxLLM("gpt-4o") question_string = ("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") question = tg.Variable(question_string, role_description="question to the LLM", requires_grad=False) answer = model(question)
:warning: answer: To determine how long it will take to dry 30 shirts under the sun, we can use a proportional relationship based on the given information. Here’s the step-by-step reasoning: [.....] So, it will take 1.2 hours (or 1 hour and 12 minutes) to dry 30 shirts under the sun.
As you can see, the model's answer is incorrect. We can optimize the answer using TextGrad to get the correct answer.
answer.set_role_description("concise and accurate answer to the question") # Step 2: Define the loss function and the optimizer, just like in PyTorch! # Here, we don't have SGD, but we have TGD (Textual Gradient Descent) # that works with "textual gradients". optimizer = tg.TGD(parameters=[answer]) evaluation_instruction = (f"Here's a question: {question_string}. " "Evaluate any given answer to this question, " "be smart, logical, and very critical. " "Just provide concise feedback.") # TextLoss is a natural-language specified loss function that describes # how we want to evaluate the reasoning. loss_fn = tg.TextLoss(evaluation_instruction)
:brain: loss: [...] Your step-by-step reasoning is clear and logical, but it contains a critical flaw in the assumption that drying time is directly proportional to the number of shirts. [...]
# Step 3: Do the loss computation, backward pass, and update the punchline. # Exact same syntax as PyTorch! loss = loss_fn(answer) loss.backward() optimizer.step() answer
:white_check_mark: answer: It will still take 1 hour to dry 30 shirts under the sun, assuming they are all laid out properly to receive equal sunlight.
We have many more examples around how TextGrad can optimize all kinds of variables -- code, solutions to problems, molecules, prompts, and all that!
We have prepared a couple of tutorials to get you started with TextGrad. The order of this 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 you need an OpenAI/Anthropic key to run the LLMs).
<div align="center">Tutorial | Difficulty | Colab Link |
---|---|---|
1. Introduction to TextGrad Primitives | ||
2. Solution Optimization | ||
3. Optimizing a Code Snippet and Define a New Loss | ||
4. Prompt Optimization | ||
5. MultiModal Optimization |
You can install TextGrad using any of the following methods.
With pip
:
pip install textgrad
With conda
:
conda install -c conda-forge textgrad
:bulb: The conda-forge package for
textgrad
is maintained here.
Bleeding edge installation with pip
:
pip install git+https://github.com/zou-group/textgrad.git
Installing textgrad with vllm:
pip install textgrad[vllm]
See here for more details on various methods of pip installation.
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:
tg.set_backward_engine("gpt-4o") initial_solution = """To solve the equation 3x^2 - 7x + 2 = 0, we use the quadratic formula: x = (-b ± √(b^2 - 4ac)) / 2a a = 3, b = -7, c = 2 x = (7 ± √((-7)^2 - 4 * 3(2))) / 6 x = (7 ± √(7^3) / 6 The solutions are: x1 = (7 + √73) x2 = (7 - √73)""" # Define the variable to optimize, let requires_grad=True to enable gradient computation solution = tg.Variable(initial_solution, requires_grad=True, role_description="solution to the math question") # Define the optimizer, let the optimizer know which variables to optimize, and run the loss function 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.") optimizer = tg.TGD(parameters=[solution]) loss = loss_fn(solution)
Output:
Variable(value=Errors:
- Incorrect sign in the discriminant calculation: it should be b^2 - 4ac, not b^2 + 4ac.
- Incorrect simplification of the quadratic formula: the denominator should be 2a, not 6.
- Final solutions are missing the division by 2a., role=response from the language model, grads=)
loss.backward() optimizer.step() print(solution.value)
Output:
To solve the equation 3x^2 - 7x + 2 = 0, we use the quadratic formula: x = (-b ± √(b^2 - 4ac)) / 2a
Given: a = 3, b = -7, c = 2
Substitute the values into the formula: x = (7 ± √((-7)^2 - 4(3)(2))) / 6 x = (7 ± √(49 - 24)) / 6 x = (7 ± √25) / 6 x = (7 ± 5) / 6
The solutions are: x1 = (7 + 5) / 6 = 12 / 6 = 2 x2 = (7 - 5) / 6 = 2 / 6 = 1/3
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:
import textgrad as tg llm_engine = tg.get_engine("gpt-3.5-turbo") tg.set_backward_engine("gpt-4o") _, val_set, _, eval_fn = load_task("BBH_object_counting", llm_engine) question_str, answer_str = val_set[0] question = tg.Variable(question_str, role_description="question to the LLM", requires_grad=False) answer = tg.Variable(answer_str, role_description="answer to the question", requires_grad=False)
Question:
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?
Ground Truth Answer:
10
system_prompt = tg.Variable("You are a concise LLM. Think step by step.", requires_grad=True, role_description="system prompt to guide the LLM's reasoning strategy for accurate responses") model = tg.BlackboxLLM(llm_engine, system_prompt=system_prompt) optimizer = tg.TGD(parameters=list(model.parameters())) prediction = model(question)
Prediction:
You have a total of seven vegetables: two stalks of celery, two garlics, one potato, three heads of broccoli, one carrot, and one yam.
loss = eval_fn(inputs=dict(prediction=prediction, ground_truth_answer=answer))
Loss denoting accuracy:
Variable(value=0, grads=)
loss.backward()
System prompt gradients:
... 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."....
optimizer.step()
New system prompt value:
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.
prediction = model(question)
New prediction:
Let's count the number of each vegetable:
- Celery stalks: 2
- Garlics: 2
- Potato: 1
- Broccoli heads: 3
- Carrot: 1
- Yam: 1
Now, let's add up the total number of vegetables: 2 + 2 + 1 + 3 + 1 + 1 = 10
You have a total of 10 vegetables.
Many existing works greatly inspired this project! Here is a non-exhaustive list:
@article{yuksekgonul2024textgrad, title={TextGrad: Automatic "Differentiation" via Text}, author={Mert Yuksekgonul and Federico Bianchi and Joseph Boen and Sheng Liu and Zhi Huang and Carlos Guestrin and James Zou}, year={2024}, eprint={2406.07496}, archivePrefix={arXiv} }
We are grateful for all the help we got from our contributors!
<!-- readme: contributors -start --> <table> <tbody> <tr> <td align="center"> <a href="https://github.com/vinid"> <img src="https://avatars.githubusercontent.com/u/2234699?v=4" width="100;" alt="vinid"/> <br /> <sub><b>Federico Bianchi</b></sub> </a> </td> <td align="center"> <a href="https://github.com/mertyg"> <img src="https://avatars.githubusercontent.com/u/29640736?v=4" width="100;" alt="mertyg"/> <br /> <sub><b>Mert Yuksekgonul</b></sub> </a> </td> <td align="center"> <a href="https://github.com/nihalnayak"> <img src="https://avatars.githubusercontent.com/u/5679782?v=4" width="100;" alt="nihalnayak"/> <br /> <sub><b>Nihal Nayak</b></sub> </a> </td> <td align="center"> <a href="https://github.com/sugatoray"> <img src="https://avatars.githubusercontent.com/u/10201242?v=4" width="100;" alt="sugatoray"/> <br /> <sub><b>Sugato Ray</b></sub> </a> </td> <td align="center"> <a href="https://github.com/lupantech"> <img src="https://avatars.githubusercontent.com/u/17663606?v=4" width="100;" alt="lupantech"/> <br /> <sub><b>Pan Lu</b></sub> </a> </td> <td align="center"> <a href="https://github.com/ruanwz"> <img src="https://avatars.githubusercontent.com/u/4874?v=4" width="100;" alt="ruanwz"/> <br /> <sub><b>David Ruan</b></sub> </a> </td> </tr> <tr> <td align="center"> <a href="https://github.com/sanowl"> <img src="https://avatars.githubusercontent.com/u/99511815?v=4" width="100;"字节跳动发布的AI编程神器IDE
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。
AI小说写作助手,一站式润色、改写、扩写
蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。
全能AI智能助手,随时解答生活与工作的多样问题
问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。
实时语音翻译/同声传译工具
Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨 国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。
一键生成PPT和Word,让学习生活更轻松
讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。
深度推理能力全新升级,全面对标OpenAI o1
科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像 创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。
一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型
Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。
AI助力,做PPT更简单!
咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。
选题、配图、成文,一站式创作,让内容运营更高效
讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。
专业的AI公文写作平台,公文写作神器
AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。
最新AI工具、AI资讯
独家AI资源、AI项目落地
微信扫一扫关注公众号