textgrad

textgrad

基于文本反馈的自动'微分'优化框架

TextGrad是一个基于大语言模型文本反馈实现自动'微分'的框架。它提供简洁API用于定义损失函数和基于文本反馈的优化。该框架与PyTorch接口相似,可优化文本、代码等非结构化变量,为自然语言处理和人工智能开发提供新思路。

TextGrad自动微分文本反馈优化梯度下降Github开源项目

Logo

<!--- BADGES: START --->

Open In Colab GitHub license Arxiv Documentation Status PyPI - Python Version PyPI Conda - Platform Conda (channel only)

<!--- BADGES: END --->

TextGrad: Automatic ''Differentiation'' via Text

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.

Analogy with Torch

QuickStart

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!

Tutorials

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">
TutorialDifficultyColab Link
1. Introduction to TextGrad PrimitivesOpen In Colab
2. Solution OptimizationOpen In Colab
3. Optimizing a Code Snippet and Define a New LossOpen In Colab
4. Prompt OptimizationOpen In Colab
5. MultiModal OptimizationOpen In Colab
</div>

Installation

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.

More detailed examples

Minimal Instance Optimization Example

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:

  1. Incorrect sign in the discriminant calculation: it should be b^2 - 4ac, not b^2 + 4ac.
  2. Incorrect simplification of the quadratic formula: the denominator should be 2a, not 6.
  3. 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

Minimal Prompt Optimization Example

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:

  1. Celery stalks: 2
  2. Garlics: 2
  3. Potato: 1
  4. Broccoli heads: 3
  5. Carrot: 1
  6. 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.

Resources

Inspiration

Many existing works greatly inspired this project! Here is a non-exhaustive list:

  • 📚 PyTorch The one and only. We owe a ton to PyTorch, hard to do justice here.
  • 📚 DSPy is a pioneer in writing LM-based programs in many different ways! Has been a huge inspiration for us.
  • 📚 Micrograd: A tiny autograd engine greatly inspired our simple design!
  • 📚 ProTeGi: We owe the term "Textual Gradients" to ProTeGi!
  • 📚 Reflexion: A self-reflection that showed us the power of text-based reflection!

Citation

@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} }

Contributors

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;"

编辑推荐精选

Vora

Vora

免费创建高清无水印Sora视频

Vora是一个免费创建高清无水印Sora视频的AI工具

Refly.AI

Refly.AI

最适合小白的AI自动化工作流平台

无需编码,轻松生成可复用、可变现的AI自动化工作流

酷表ChatExcel

酷表ChatExcel

大模型驱动的Excel数据处理工具

基于大模型交互的表格处理系统,允许用户通过对话方式完成数据整理和可视化分析。系统采用机器学习算法解析用户指令,自动执行排序、公式计算和数据透视等操作,支持多种文件格式导入导出。数据处理响应速度保持在0.8秒以内,支持超过100万行数据的即时分析。

AI工具酷表ChatExcelAI智能客服AI营销产品使用教程
TRAE编程

TRAE编程

AI辅助编程,代码自动修复

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
AIWritePaper论文写作

AIWritePaper论文写作

AI论文写作指导平台

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

AI辅助写作AI工具AI论文工具论文写作智能生成大纲数据安全AI助手热门
博思AIPPT

博思AIPPT

AI一键生成PPT,就用博思AIPPT!

博思AIPPT,新一代的AI生成PPT平台,支持智能生成PPT、AI美化PPT、文本&链接生成PPT、导入Word/PDF/Markdown文档生成PPT等,内置海量精美PPT模板,涵盖商务、教育、科技等不同风格,同时针对每个页面提供多种版式,一键自适应切换,完美适配各种办公场景。

AI办公办公工具AI工具博思AIPPTAI生成PPT智能排版海量精品模板AI创作热门
潮际好麦

潮际好麦

AI赋能电商视觉革命,一站式智能商拍平台

潮际好麦深耕服装行业,是国内AI试衣效果最好的软件。使用先进AIGC能力为电商卖家批量提供优质的、低成本的商拍图。合作品牌有Shein、Lazada、安踏、百丽等65个国内外头部品牌,以及国内10万+淘宝、天猫、京东等主流平台的品牌商家,为卖家节省将近85%的出图成本,提升约3倍出图效率,让品牌能够快速上架。

iTerms

iTerms

企业专属的AI法律顾问

iTerms是法大大集团旗下法律子品牌,基于最先进的大语言模型(LLM)、专业的法律知识库和强大的智能体架构,帮助企业扫清合规障碍,筑牢风控防线,成为您企业专属的AI法律顾问。

SimilarWeb流量提升

SimilarWeb流量提升

稳定高效的流量提升解决方案,助力品牌曝光

稳定高效的流量提升解决方案,助力品牌曝光

Sora2视频免费生成

Sora2视频免费生成

最新版Sora2模型免费使用,一键生成无水印视频

最新版Sora2模型免费使用,一键生成无水印视频

下拉加载更多