作者:Nathan Cooper
链接:https://www.answer.ai/posts/2024-10-15-how-to-synthesize-data.html
引言
合成数据已经成为大规模语言模型(LLM)领域中的重要话题。Meta最近在Llama 3模型的训练中使用LLM生成数据,突显了这一趋势。本文分享了我在生成合成数据方面的实验经验,同时介绍了我们新推出的库——fastdata,旨在简化合成数据的生成过程。
让我们从一个显而易见的问题开始:为什么现在大家都为合成数据疯狂?
想象一下,拥有一个巨大的、完美的训练数据供应库,适用于任何任务。这就是合成数据的承诺,LLM正将我们带向这个现实。这些模型能够以高度的精确度和控制力生成多样化、高质量的数据集。
合成数据的价值在于它的可控性和多样性,与噪声大、不规范的网络抓取数据形成鲜明对比。现代LLM在给予合适提示时展示出了强大的指令跟随能力。再加上它们从网络规模文本数据中训练而来的广泛知识,让我们可以合成任何主题的数据,无论多么小众,并将其调整以满足我们的需求。
然而,创建有效的合成数据往往充满挑战。本文将探讨使用合成数据的挑战和机遇。我将分享一些实用的见解,帮助您释放合成数据的潜力,并改变您处理数据驱动任务的方式。
为了为我们的合成数据冒险做铺垫,我将带您走进一个我使用合成数据的实验。
实验
灵感来源于TinyStories论文,该论文展示了小型模型在合成儿童故事上的训练可以优于大型模型。我由此开发了一个针对编码模型的类似想法,叫做TinyPrograms。TinyPrograms由大约1000个小型Python程序组成,这些程序是通过Anthropic的Haiku 3模型生成的。
https://arxiv.org/abs/2305.07759
第一次尝试:意外的挫折
我使用TinyPrograms尝试微调一个强大的LLM模型,看看是否可以提高其编码能力。我使用了Huggingface的出色模型SmolLM-360M。它很小,并且在编码任务上表现良好。原生状态下,SmolLM-360M在一个名为HumanEval的流行编码测试中得分为11.6%。HumanEval是一个流行的编码测试,它测量模型生成解决编码问题的能力。令人惊讶的是,我微调后的模型在HumanEval中的表现下降到了9.1%。但是,我并没有因此气馁,因为我知道生成合成数据是困难的。
第二次尝试:提高多样性和质量
合成数据面临的两个问题是质量和多样性。我使用了一篇论文中的技巧,论文名为《Scaling Synthetic Data Creation with 1,000,000,000 Personas》。它展示了如何通过让LLM模拟不同的角色来生成合成数据,从而改善在合成数据上训练的模型。这是他们数据集中一些有趣的角色:
["专门研究萨尔瓦多政治格局的政治分析师。", "理解不完整或不准确项目文档法律影响的法律顾问", "致力于提高对产后并发症意识的母婴健康倡导者", "相信体育及其资金应该优先于学生会竞选的校篮球队队长",]
https://arxiv.org/abs/2406.20094v1
我指示Haiku为这些角色编写可能有用的小程序。不幸的是,这并没有解决合成数据的质量问题。为了克服这个问题,我使用了一篇优秀论文中的想法,论文名为《Textbooks Are All You Need》。它要求LLM对一段代码进行质量评分为“高”或“低”。作者们然后将数据过滤,只保留高质量代码,并在这些数据上训练模型,最终提升了性能!🤯因此,我将我的大约1000个小程序通过LLM的质量筛选器过滤,看看是否也能改善我的合成数据。结果得到了754个小程序。我在这些程序上训练了我的模型,结果有效!我的新模型在同样的基准测试中获得了12.2%的pass@1分数🤓。我已经将完整的代码和实验写入了本文配套仓库的examples文件夹中。
https://arxiv.org/abs/2306.11644
https://github.com/AnswerDotAI/fastdata/tree/main/examples
如何自己动手操作
本篇文章将详细解释如何自己进行操作。它涵盖了合成数据时需要注意的一些关键点。我还将介绍fastdata,它是我们库claudette的一个小封装,旨在简化合成数据的生成过程。
生成合成数据
重要部分
让我们讨论合成数据的关键要素:质量和多样性。这两者经常相互冲突,但都至关重要。一个随机字符串生成器具有高度多样性但质量低,而《大英百科全书》内容质量高,但其范围有限,比如它并没有涵盖所有人们创作的《星际迷航》粉丝小说。
我们的挑战是要平衡这些因素。我们必须确保在多个主题上有高质量的数据。我们需要在专门领域中有深度,同时覆盖小众内容。这很棘手,但对于创建用于LLM的有效合成数据至关重要。
掌控质量和多样性
接下来我们进入技术层面。LLM本质上是复杂的单词预测机器。它们通过分析一系列单词来预测接下来可能出现的内容。我们可以操控这一预测过程,以覆盖更多的语言空间。
一个有用的技巧来自论文《Scaling Synthetic Data Creation with 1,000,000,000 Personas》。通过让LLM采用不同角色,我们可以生成多样化且连贯的内容。这种方法比仅仅提高温度(生成更为多样化但无意义的输出)要好得多。
《WizardLM: Empowering Large Language Models to Follow Complex Instructions》向我们展示了,多样性不仅涉及广度,还涉及深度。他们通过不断演变的指令,涵盖不同的主题和复杂性。这教会了LLM处理不同难度级别的广泛任务。
https://arxiv.org/abs/2304.12244
质量是多方面的,包含写作风格、准确性和连贯性。使用专家角色有助于提高质量,但不能完全解决如幻觉(模型错误地生成不存在的信息)等问题。一种有效的策略是生成后的过滤。它涉及创建一个大型、多样化的数据集,然后使用某些标准精心挑选出最高质量的示例。
《Textbooks Are All You Need》这篇论文提出了一个有趣的想法,它使用强大的LLM作为代码的质量评估器。在一些研究中,如《How to Train Data-Efficient LLMs》和《The FineWeb Datasets: Decanting the Web for the Finest Text Data at Scale》,该方法表现出了前景。
https://arxiv.org/abs/2402.09668
https://arxiv.org/abs/2406.17557
合成数据生成中的关键挑战在于平衡质量和多样性。但通过这些技术,你可以创建高质量、多样化的数据集,以训练LLM。
让我们玩转一些数据
不要只听信我的话。我们来使用 claudette,这是我们在 Answer.AI 构建的一个有趣的小库,用来展示这些想法并进行探索。claudette 是一个 Anthropic 的 Claude API 的极简封装器,旨在使其更易于使用。一个关键功能是使用 Claude 进行工具调用。我们将滥用它来生成合成数据!
这是它的工作方式:我们定义一个包含所需属性的类。然后,我们将该类与一个提示传递给 Claude 来填写空白。这种方法迫使生成结果遵循我们在 Python 类中定义的模式。让我们看看下面的实际操作。
class Translation():
"将英语短语翻译成西班牙语短语"
def __init__(self, english: str, spanish: str): store_attr()
def __repr__(self): return f"{self.english} ➡ *{self.spanish}*"
Translation("Hello, how are you today?", "Hola, ¿cómo estás hoy?")
Hello, how are you today? ➡ *Hola, ¿cómo estás hoy?*
注意
确保你有 Anthropic 的 API 密钥,即需要设置 ANTHROPIC_API_KEY
环境变量。
from claudette import *
model = models[-1] # haiku 3
sp = "你将帮助生成英语和西班牙语短语的合成数据。"
cli = Client(model)
def synthesize(pr): return cli.structured(pr, sp=sp, temp=1, tools=Translation)[0]
prompt = '创建一个英语和西班牙语的翻译对。'
translations = [synthesize(prompt) for _ in range(5)]
我们将创建一个小函数来清晰显示输出:
from IPython.display import Markdown
clps_fmt = '- {s}\n\n<details>\n<summary> 点击显示更多 </summary>\n{ls}\n</details>'
def to_md(ss, collapsible=False):
ls = '\n'.join(f'- {s}' for s in ss)
return clps_fmt.format(s=str(ss[0]), ls=ls.replace(f'- {ss[0]}', '')) if collapsible else ls
def show(ss, collapsible=False): return Markdown(to_md(ss, collapsible=collapsible))
好吧,让我们看看结果如何……
Hello, how are you today? ➡ Hola, ¿cómo estás hoy?
Hello, how are you today? ➡ Hola, ¿cómo estás hoy?
Good morning! ➡ ¡Buenos días!
How are you today? ➡ ¿Cómo estás hoy?
How are you today? ➡ ¿Cómo estás hoy?
或者当输出太长时……
Hello, how are you today? ➡ Hola, ¿cómo estás hoy?
Good morning! ➡ ¡Buenos días!
How are you today? ➡ ¿Cómo estás hoy?
How are you today? ➡ ¿Cómo estás hoy?
Fantástico! 输出展示了模型生成正确格式数据的能力。然而,这些翻译对相当简单,缺
examples = [
Translation(
english="Hello, my name is Nathan. I am a research scientist at an AI startup.",
spanish="Hola, me llamo Nathan. Soy ciencia investigador en un startup de IA."),
Translation(
english="How much wood could a woodchuck chuck if a woodchuck could chuck wood?",
spanish="¿Cuánta madera podría arrojar una marmota si una marmota pudiera arrojar madera?"),
Translation(
english="Thomas Cranmer (2 July 1489 - 21 March 1556) was a leader of the English Reformation and Archbishop of Canterbury during the reigns of Henry VIII, Edward VI and, for a short time, Mary I. He helped build the case for the annulment of Henry's marriage to Catherine of Aragon, which was one of the causes of the separation of the English Church from union with the Holy See.",
spanish="Thomas Cranmer (2 de julio de 1489 - 21 de marzo de 1556) fue un líder de la Reforma inglesa y arzobispo de Canterbury durante los reinados de Henry VIII, Edward VI y, por un corto tiempo, María I. Ayudó a construir el caso para la anulación de El matrimonio de Henry con Catalina de Aragón, que fue una de las causas de la separación de la Iglesia inglesa de la unión con la Santa Sede."
),
]
我们将使用 markdown 列表将它们提供给模型:
examples_md = to_md(examples)
Markdown(examples_md)
Hello, my name is Nathan. I am a research scientist at an AI startup. ➡ Hola, me llamo Nathan. Soy ciencia investigador en un startup de IA.
How much wood could a woodchuck chuck if a woodchuck could chuck wood? ➡ ¿Cuánta madera podría arrojar una marmota si una marmota pudiera arrojar madera?
Thomas Cranmer (2 July 1489 - 21 March 1556) was a leader of the English Reformation and Archbishop of Canterbury during the reigns of Henry VIII, Edward VI and, for a short time, Mary I. He helped build the case for the annulment of Henry’s marriage to Catherine of Aragon, which was one of the causes of the separation of the English Church from union with the Holy See. ➡ Thomas Cranmer (2 de julio de 1489 - 21 de marzo de 1556) fue un líder de la Reforma inglesa y arzobispo de Canterbury durante los reinados de Henry VIII, Edward VI y, por un corto tiempo, María I. Ayudó a construir el caso para la anulación de El matrimonio de Henry con Catalina de Aragón, que fue una de las causas de la separación de la Iglesia inglesa de la unión con la Santa Sede.
我们还需要一个包含这些示例的提示:
prompt_template = """\
Create an English and Spanish translation pair that is similar to the examples.
<examples>
{examples}
</examples>"""
prompt = prompt_template.format(examples=examples_md)
print(prompt)
Create an English and Spanish translation pair that is similar to the examples.
<examples>
- Hello, my name is Nathan. I am a research scientist at an AI startup. ➡ *Hola, me llamo Nathan. Soy ciencia investigador en un startup de IA.*
- How much wood could a woodchuck chuck if a woodchuck could chuck wood? ➡ *¿Cuánta madera podría arrojar una marmota si una marmota pudiera arrojar madera?*
- Thomas Cranmer (2 July 1489 - 21 March 1556) was a leader of the English Reformation and Archbishop of Canterbury during the reigns of Henry VIII, Edward VI and, for a short time, Mary I. He helped build the case for the annulment of Henry's marriage to Catherine of Aragon, which was one of the causes of the separation of the English Church from union with the Holy See. ➡ *Thomas Cranmer (2 de julio de 1489 - 21 de marzo de 1556) fue un líder de la Reforma inglesa y arzobispo de Canterbury durante los reinados de Henry VIII, Edward VI y, por un corto tiempo, María I. Ayudó a construir el caso para la anulación de El matrimonio de Henry con Catalina de Aragón, que fue una de las causas de la separación de la Iglesia inglesa de la unión con la Santa Sede.*
</examples>
show([synthesize(prompt) for _ in range(5)])
My favorite time of the year is autumn when the leaves change colors. ➡ Mi época favorita del año es el otoño cuando las hojas cambian de color.
Once upon a time, there was a kind-hearted farmer who lived in a small village. Every day, he would wake up early to tend to his fields and livestock. ➡ Había una vez un granjero de buen corazón que vivía en un pequeño pueblo. Cada día se levantaba temprano para atender sus campos y su ganado.
I love to go hiking in the mountains. The views are breathtaking. ➡ Me encanta ir de excursión en las montañas. Las vistas son impresionantes.
My favorite color is red. I enjoy swimming in the ocean. ➡ Mi color favorito es rojo. Me gusta nadar en el océano.
My favorite animal is the giraffe. They have such long necks and are so graceful. ➡ Mi animal favorito es la jirafa. Tienen cuellos tan largos y son tan elegantes.
有趣!我们看到了一些改进,但仍然有许多与我们提供的示例几乎重复的内容。这种重复展示了提示这些模型时的一个重要方面。示例在提示中的位置会极大地影响输出的质量和多样性。让我们尝试将示例放在提示的开头看看会发生什么。
prompt_template = """\
<examples>
{examples}
</examples>
Create an English and Spanish translation pair that is similar to the examples."""
prompt = prompt_template.format(examples=examples_md)
print(prompt)
Hello, my name is Nathan. I am a research scientist at an AI startup. ➡ Hola, me llamo Nathan. Soy ciencia investigador en un startup de IA.
How much wood could a woodchuck chuck if a woodchuck could chuck wood? ➡ ¿Cuánta madera podría arrojar una marmota si una marmota pudiera arrojar madera?
Thomas Cranmer (2 July 1489 - 21 March 1556) was a leader of the English Reformation and Archbishop of Canterbury during the reigns of Henry VIII, Edward VI and, for a short time, Mary I. He helped build the case for the annulment of Henry's marriage to Catherine of Aragon, which was one of the causes of the separation of the English Church from union with the Holy See. ➡ Thomas Cranmer (2 de julio de 1489 - 21 de marzo de 1556) fue un líder de la Reforma inglesa y arzobispo de Canterbury durante los reinados de Henry VIII, Edward VI y, por un corto tiempo, María I. Ayudó a construir el caso para la anulación de El matrimonio de Henry con Catalina de Aragón, que fue una de las causas de la separación de la Iglesia inglesa de la unión con la Santa Sede.
show([synthesize(prompt) for _ in range(5)])
The dog ran quickly across the field to catch the ball. ➡ El perro corrió rápidamente a través del campo para atrapar la pelota.
The sun is shining brightly in the clear blue sky today. ➡ El sol brilla intensamente en el cielo azul despejado hoy.
My friend Sam is an avid hiker who enjoys exploring the beautiful nature trails in our local park. Last weekend, he went on a long hike and came back with some interesting stories. ➡ Mi amigo Sam es un excursionista entusiasta que disfruta explorando los hermosos senderos naturales de nuestro parque local. El fin de semana pasado, fue a hacer una larga caminata y volvió con algunas historias interesantes.
I am an engineer at a tech company. I design software for our customers. ➡ Soy un ingeniero en una empresa de tecnología. Diseño software para nuestros clientes.
The quick brown fox jumps over the lazy dog. ➡ El zorro marrón rápido salta sobre el perro perezoso.
哇!多么大的差异!结果展示了比上次尝试更多的内容和结构的多样性。然而,主题的多样性仍然不够。让我们从质量转向多样性,看看会发生什么。我们将使用主题列表来指导生成。这应该有助于扩展翻译的主题范围。
topics = ["otters", "penguins", "sloths", "cats", "dogs"]
prompt_template = """\
Create an English and Spanish translation pair about the following topic:
<topic>{topic}</topic>"""
例如:
print(prompt_template.format(topic=topics[0]))
创建一个关于以下主题的英语和西班牙语翻译对:
<topic>otters</topic>
好的,让我们试试:
show([synthesize(prompt_template.format(topic=topic)) for topic in topics])
Otters are fascinating aquatic mammals that are found in various parts of the world. They are known for their playful and social behavior, as well as their remarkable adaptations for swimming and hunting in the water. ➡ Las nutrias son fascinantes mamíferos acuáticos que se encuentran en varias partes del mundo. Son conocidas por su comportamiento juguetón y social, así como por sus notables adaptaciones para nadar y cazar en el agua.
Penguins are flightless seabirds that live in the Southern Hemisphere. ➡ Los pingüinos son aves marinas que no pueden volar y viven en el hemisferio sur.
The sloth is a slow-moving mammal that lives in the trees of Central and South America. ➡ El perezoso es un mamífero de movimiento lento que vive en los árboles de América Central y del Sur.
The curious cat watched the birds from the window. ➡ El curioso gato observó a los pájaros desde la ventana.
The loyal dog wagged its tail excitedly as its owner returned home. ➡ El perro leal meneó la cola con emoción cuando su dueño regresó a casa.
好的,太棒了!我们基于话题列表看到了更多的多样性。然而,你会注意到猫和狗的例子质量有所下降。为了同时提升多样性和质量,让我们结合示例和话题的技术。
prompt_template = """\
<examples>
{examples}
</examples>
Create an English and Spanish translation pair that is similar to the examples and is about the following topic:
<topic>{topic}</topic>"""
然后我们生成翻译对:
translations = [synthesize(prompt_template.format(examples=examples_md, topic=topic))
for topic in topics]
show(translations, collapsible=True)
Otters are semiaquatic mammals that belong to the weasel family. They are found in many parts of the world, including North America, Europe, and Asia. Otters are known for their playful behavior, their sleek fur coats, and their ability to swim gracefully in the water. ➡ Los nutrias son mamíferos semiacuáticos que pertenecen a la familia de los comadrejas. Se encuentran en muchas partes del mundo, incluyendo América del Norte, Europa y Asia. Las nutrias son conocidas por su comportamiento juguetón, sus sedosos abrigos de piel y su capacidad para nadar con gracia en el agua.
Penguins are flightless birds that live in the Southern Hemisphere. They have black and white feathers and webbed feet that help them swim in the ocean. Penguins gather in large colonies and work together to raise their young. ➡ Los pingüinos son aves no voladoras que viven en el hemisferio sur. Tienen plumas negras y blancas y patas palmeadas que les ayudan a nadar en el océano. Los pingüinos se reúnen en grandes colonias y trabajan juntos para criar a sus crías.
Sloths are slow-moving mammals that live in the tropical rainforests of Central and South America. They are known for their distinctive appearance, with long limbs, curved claws, and a shaggy coat that helps them blend in with the trees they inhabit. Sloths spend most of their time hanging upside down from branches, moving very slowly and deliberately to conserve energy. They are herbivores, feeding primarily on leaves, and have a specialized digestive system that allows them to extract nutrients from this low-calorie diet. Despite their seemingly lazy behavior, sloths play an important role in the ecosystem, acting as seed dispersers and contributing to the overall biodiversity of the rainforest. ➡ Los perezosos son mamíferos de movimiento lento que viven en las selvas tropicales de América Central y del Sur. Se conocen por su apariencia distintiva, con extremidades largas, garras curvas y un pelaje espeso que les ayuda a fundirse con los árboles que habitan. Los perezosos pasan la mayor parte de su tiempo colgados boca abajo de las ramas, moviéndose muy lenta y deliberadamente para conservar energía. Son herbívoros, alimentándose principalmente de hojas, y tienen un sistema digestivo especializado que les permite extraer nutrientes de esta dieta baja en calorías. A pesar de su comportamiento aparentemente perezoso, los perezosos desempeñan un papel importante en el ecosistema, actuando como dispersores de semillas y contribuyendo a la biodiversidad general de la selva tropical.
Cats are furry, playful companions that many people love to have as pets. They are known for their independent nature, agility, and ability to hunt small prey. Caring for a cat requires providing food, water, litter, and plenty of toys and playtime to keep them healthy and happy. ➡ Los gatos son compañeros peludos y juguetones que a muchas personas les gusta tener como mascotas. Se les conoce por su naturaleza independiente, agilidad y capacidad para cazar presas pequeñas. Cuidar a un gato requiere proporcionarle alimento, agua, arena para gatos y muchos juguetes y tiempo de juego para mantenerlos saludables y felices.
Dogs are beloved companions that bring joy and unconditional love to many households. They come in a variety of breeds, each with their own unique personalities and characteristics. Whether playing fetch, going for walks, or cuddling on the couch, dogs enrich our lives in countless ways. ➡ Los perros son compañeros adorados que traen alegría y amor incondicional a muchos hogares. Vienen en una variedad de razas, cada una con sus propias personalidades y características únicas. Ya sea jugando a buscar, saliendo a caminar o acurrucándose en el sofá, los perros enriquecen nuestras vidas de innumerables maneras.
不算太差,而且我觉得比之前的例子好多了。我们在这次动物王国之旅中看到了更详细和多样的内容。但请注意这些有趣的细节:
我们现在正在为所有毛茸茸的朋友提供百科全书式的介绍。不再只是随便提一句“哦,对,那是个东西”那种随意的提及了。
更为奇特的动物(如水獭、企鹅、树懒)有详细的生物学和行为介绍。家养动物则有总体描述,并讨论它们与人类的关系。
我们之前的尝试在获取每种动物的信息方面不太一致。现在,我们看到了更多的一致性。
西班牙语的翻译几乎完美。它们在准确性和流畅性方面与英文版完全匹配。真是太棒了!
看起来我们的模型很好地融合了示例和话题提示。无论我们是在讨论挂在树上的树懒,还是一只正在做它自己事情的猫,它都在知识深度和保持话题之间取得了平衡。让我们试试看使用更强大的模型会得到什么结果。
sp = "You will help generate synthetic data of English and Spanish phrases."
cli = Client(models[1]) # sonnet 3.5
生成翻译对:
translations = [synthesize(prompt_template.format(examples=examples_md, topic=topic))
for topic in topics]
show(translations, collapsible=True)
Otters are playful and intelligent semi-aquatic mammals known for their thick fur and ability to use tools. They can often be seen floating on their backs, using their bellies as a table to crack open shellfish with rocks. ➡ Las nutrias son mamíferos semiacuáticos juguetones e inteligentes conocidos por su pelaje grueso y su capacidad para usar herramientas. A menudo se les puede ver flotando boca arriba, usando sus vientres como mesa para romper mariscos con rocas.
Penguins are flightless seabirds that are highly adapted for life in the water. They are found almost exclusively in the Southern Hemisphere, particularly in Antarctica. Despite their inability to fly, penguins are excellent swimmers and can dive to great depths to catch fish and squid. ➡ Los pingüinos son aves marinas no voladoras que están altamente adaptadas para la vida en el agua. Se encuentran casi exclusivamente en el hemisferio sur, particularmente en la Antártida. A pesar de su incapacidad para volar, los pingüinos son excelentes nadadores y pueden sumergirse a grandes profundidades para atrapar peces y calamares.
Sloths are fascinating creatures known for their slow movement and unique lifestyle. These tree-dwelling mammals can be found in the tropical rainforests of Central and South America. Despite their sluggish appearance, sloths are excellent swimmers and can hold their breath underwater for up to 40 minutes. ➡ Los perezosos son criaturas fascinantes conocidas por su movimiento lento y estilo de vida único. Estos mamíferos arborícolas se pueden encontrar en las selvas tropicales de América Central y del Sur. A pesar de su apariencia lenta, los perezosos son excelentes nadadores y pueden contener la respiración bajo el agua hasta por 40 minutos.
Cats are fascinating creatures that have been domesticated for thousands of years. They are known for their independence, playful nature, and ability to form strong bonds with their human companions. From tiny kittens to majestic big cats, felines come in a variety of sizes, colors, and personalities. ➡ Los gatos son criaturas fascinantes que han sido domesticadas durante miles de años. Son conocidos por su independencia, naturaleza juguetona y capacidad para formar fuertes vínculos con sus compañeros humanos. Desde pequeños gatitos hasta majestuosos felinos grandes, los felinos vienen en una variedad de tamaños, colores y personalidades.
Dogs are known as man’s best friend. They come in various breeds, sizes, and colors, each with their own unique characteristics. From loyal companions to working dogs, these furry animals have been by our side for thousands of years. They are known for their unconditional love, playful nature, and ability to provide emotional support to their human families. ➡ Los perros son conocidos como el mejor amigo del hombre. Vienen en varias razas, tamaños y colores, cada uno con sus propias características únicas. Desde compañeros leales hasta perros de trabajo, estos animales peludos han estado a nuestro lado durante miles de años. Son conocidos por su amor incondicional, naturaleza juguetona y capacidad para proporcionar apoyo emocional a sus familias humanas.
切换到更强大的Claude Sonnet 3.5模型后,情况有所改善。我们现在看到了对所有动物更一致、全面的描述。它不仅涵盖了动物的生活习性,还提高了准确性,包括它们的栖息地、行为和独特特征。对于猫和狗的描述,达到了动物知识与它们与人类关系之间的平衡。西班牙语的翻译也有了提升,处理复杂句子和专业词汇的能力更好。这次实验表明,使用更好的模型可以在所有话题上产生更好的输出,表现出更多的一致性、细节和准确性。
然而,我们仍然可能遇到幻觉问题和整体质量问题。
为了解决这些问题,我们将使用另一个提示来评估和过滤生成的内容。我们将采用《The FineWeb Datasets: Decanting the Web for the Finest Text Data at Scale》中提到的5分评分系统。该系统被证明是评估数据质量的最有效方法。
我们的方法包括:
让模型生成对翻译的书面评价。
使用这一评价来对生成的内容进行评分。
这种方法应该有助于我们更好地评估合成数据的质量。幸运的是,语言模型的自回归响应使这一过程变得简单。我们可以设计一个Python类,先生成评价,然后通过该评价来评分生成的内容。
让我们使用这个系统来评估我们的合成数据。首先,我们需要创建一个新类来存储结构化的输出。我们使用Claudette与Claude进行对话,它通过文档让我们直接添加注释,提供关于类的信息:
class TranslationCritique(BasicRepr):
"A critique of the translation."
def __init__(
self,
critique: str, # A brief 1-line critique of the translation.
score: int # A score of the translation from 1 to 5.
): store_attr()
现在我们可以创建Sonnet客户端——这次告诉它使用我们的评价工具:
cli = Client(models[1]) # sonnet 3.5
sp = "You will help critique synthetic data of English and Spanish phrases."
def synthesize(pr): return cli.structured(pr, temp=1, tools=TranslationCritique)[0]
我们需要一个新的提示模板,详细说明我们希望Claude如何评估翻译:
eval_prompt_template = """\
Below is an extract of a translation. Evaluate its quality as a senior translator would, considering its suitability for professional use. Use the additive 5-point scoring system described below. Points are accumulated based on the satisfaction of each criterion:
- Add 1 point if the translation conveys the basic meaning of the source text, even if it includes some minor errors or awkward phrasing.
- Add another point if the translation is generally accurate but lacks refinement in style or fails to capture some nuances of the original. It might use inconsistent terminology or have occasional lapses in register.
- Award a third point if the translation is appropriate for professional use and accurately conveys key concepts of the source text. It demonstrates good understanding of both languages, though it may not be flawless or could include some slight inconsistencies. It resembles the work of a competent translator but may have room for improvement in fluency or precision.
- Grant a fourth point if the translation is highly accurate and reads naturally in the target language, exhibiting a consistent and appropriate style. It could be similar to the work of an experienced translator, offering faithful rendering of content and tone, with minimal errors, and effectively handling complex concepts or cultural references. The result is coherent, well-expressed, and valuable for its intended purpose.
- Bestow a fifth point if the translation is outstanding, demonstrating mastery of both source and target languages. It captures subtle nuances, maintains the author's voice and intent, and reads as if it were originally written in the target language. The translator has made excellent choices in dealing with challenging elements like wordplay, idiomatic expressions, or culture-specific content.
<translation>
{translation}
</translation>
After examining the translation:
- Briefly justify your total score in a single line.
- Conclude with the score of the translation."""
接着,我们编写一个小函数来显示结果:
def show_critique(t, critique):
return f"""{t}
\t- **Critique**: {critique.critique}
\t- **Score**: {critique.score}"""
def get_critique(t):
critique = synthesize(eval_prompt_template.format(translation=t))
return show_critique(t, critique)
所以,Claude的看法是?……
show([get_critique(t) for t in translations], collapsible=True)
Otters are playful and intelligent semi-aquatic mammals known for their thick fur and ability to use tools. They can often be seen floating on their backs, using their bellies as a table to crack open shellfish with rocks. ➡ Las nutrias son mamíferos semiacuáticos juguetones e inteligentes conocidos por su pelaje grueso y su capacidad para usar herramientas. A menudo se les puede ver flotando boca arriba, usando sus vientres como mesa para romper mariscos con rocas.
Critique: 翻译出色,精准捕捉了细微差别,保持了语气,在西班牙语中读起来自然。
Score: 5Penguins are flightless seabirds that are highly adapted for life in the water. They are found almost exclusively in the Southern Hemisphere, particularly in Antarctica. Despite their inability to fly, penguins are excellent swimmers and can dive to great depths to catch fish and squid. ➡ Los pingüinos son aves marinas no voladoras que están altamente adaptadas para la vida en el agua. Se encuentran casi exclusivamente en el hemisferio sur, particularmente en la Antártida. A pesar de su incapacidad para volar, los pingüinos son excelentes nadadores y pueden sumergirse a grandes profundidades para atrapar peces y calamares.
Critique: 翻译非常出色,精准捕捉了细微差别,同时保持了准确性,在西班牙语中读起来自然。
Score: 5Sloths are fascinating creatures known for their slow movement and unique lifestyle. These tree-dwelling mammals can be found in the tropical rainforests of Central and South America. Despite their sluggish appearance, sloths are excellent swimmers and can hold their breath underwater for up to 40 minutes. ➡ Los perezosos son criaturas fascinantes conocidas por su movimiento lento y estilo de vida único. Estos mamíferos arborícolas se pueden encontrar en las selvas tropicales de América Central y del Sur. A pesar de su apariencia lenta, los perezosos son excelentes nadadores y pueden contener la respiración bajo el agua hasta por 40 minutos.
Critique: 翻译准确,听起来自然,风格适当;“contener la respiración”这个短语有轻微改进的空间。
Score: 4Cats are fascinating creatures that have been domesticated for thousands of years. They are known for their independence, playful nature, and ability to form strong bonds with their human companions. From tiny kittens to majestic big cats, felines come in a variety of sizes, colors, and personalities. ➡ Los gatos son criaturas fascinantes que han sido domesticadas durante miles de años. Son conocidos por su independencia, naturaleza juguetona y capacidad para formar fuertes vínculos con sus compañeros humanos. Desde pequeños gatitos hasta majestuosos felinos grandes, los felinos vienen en una variedad de tamaños, colores y personalidades.
Critique: 翻译出色,听起来自然,准确捕捉了细微差别并保持了风格。
Score: 5Dogs are known as man’s best friend. They come in various breeds, sizes, and colors, each with their own unique characteristics. From loyal companions to working dogs, these furry animals have been by our side for thousands of years. They are known for their unconditional love, playful nature, and ability to provide emotional support to their human families. ➡ Los perros son conocidos como el mejor amigo del hombre. Vienen en varias razas, tamaños y colores, cada uno con sus propias características únicas. Desde compañeros leales hasta perros de trabajo, estos animales peludos han estado a nuestro lado durante miles de años. Son conocidos por su amor incondicional, naturaleza juguetona y capacidad para proporcionar apoyo emocional a sus familias humanas.
Critique: 翻译高度准确,自然流畅,风格一致,捕捉了细微差别并保持了语气。
Score: 4
正如我们所见,模型成功地为每个翻译生成了评价和评分。模型似乎也非常喜欢自己生成的翻译!
让我们看看,当我们提供一个质量非常低的翻译时会发生什么。
bad_translation = Translation(
english="The city council meeting on climate change initiatives was contentious, with passionate arguments from both sides. Ultimately, the proposal for increased funding for renewable energy projects was approved by a narrow margin.",
spanish="El council ciudad reunion en cambio climatico era controversial, con argumentos pasionantes de ambos lados. Finalmente, la propuesta para aumentar el dinero para proyectos de energía renovables fue aprobada por un margen limitado.")
生成评价:
show([get_critique(bad_translation)])
翻译对:
The city council meeting on climate change initiatives was contentious, with passionate arguments from both sides. Ultimately, the proposal for increased funding for renewable energy projects was approved by a narrow margin. ➡ El council ciudad reunion en cambio climatico era controversial, con argumentos pasionantes de ambos lados. Finalmente, la propuesta para aumentar el dinero para proyectos de energía renovables fue aprobada por un margen limitado.
Critique: 传达了基本意思,但在语法、词汇和风格上存在许多错误;不适合专业使用。
Score: 2
太棒了!我们已经开发出了一种在大规模生成高质量数据的可靠方法。以下是该过程:
通过结合以下内容生成多样化的数据:
展示所需数据类型和质量的示例。
话题或人物角色来增加多样性。
使用另一个LLM进行质量控制,为每个数据点评分。
仅保留得分最高的数据。
这个过程让我们能够为AI训练创建高质量的数据。这是一种更系统的方式来满足你的模型对数据的需求。
如何创建高质量的合成数据
记住这些关键点:
质量和多样性 是合成数据中的关键要素。它们对训练在该数据上的模型性能有显著影响。平衡两者对于创建有效的合成数据集至关重要。
质量比多样性更难实现。质量是多维的,尤其是在自由格式内容中。这使得很难在生成的所有数据方面达到高标准。
合成数据是解决数据匮乏情境的宝贵工具。当你缺乏足够的数据用于任务时,它是一种成本效益高且快速的解决方案。如果正确生成,它可以显著提升任务的性能。
合成数据不是一种通用解决方案。但它是你AI开发工具中的一项强大工具。它的有效性取决于是否仔细实施并考虑你的具体用例。
对于有兴趣的读者,可以在我们的最小化合成数据代码库fastdata中找到本文使用的所有代码。
https://github.com/AnswerDotAI/fastdata
FastData介绍
from fastdata.core import *
与其手动完成所有这些工作,我们不如使用 fastdata
,这是我们刚刚发布的一个新库,用于生成高质量的合成数据。fastdata
的好处在于它抽象了所有你需要开始的样板代码。它还内置了速率限制和并发性。这让你可以在无忧的情况下进行扩展。
以下是你如何使用 fastdata
复现我们在这篇博客文章中所做的事情,首先是翻译:
class Translation(): ... # 同上
examples = [...] # 同上
topics = [...] # 同上
prompt_template = "..." # 同上
fast_data = FastData(model=models[1])
translations = fast_data.generate(
prompt_template=prompt_template,
inputs=[{"examples": examples_md, "topic": topic} for topic in topics],
schema=Translation,
sp=sp)
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 5/5 [00:06<00:00, 1.36s/it]
show(translations, collapsible=True)
你是否知道树懒是行动极其缓慢的动物?它们大部分时间都倒挂在热带雨林的树上。这些迷人的生物每天可以睡多达20个小时,移动得如此之慢,以至于藻类可以在它们的皮毛上生长!➡ ¿Sabías que los perezosos son animales que se mueven increíblemente despacio? Pasan la mayor parte de sus vidas colgados boca abajo en los árboles de las selvas tropicales. ¡Estas fascinantes criaturas pueden dormir hasta 20 horas al día y se mueven tan lentamente que las algas pueden crecer en su pelaje!
水獭是顽皮的半水生哺乳动物,以其厚皮毛、蹼足和使用工具的能力而闻名。它们可以在淡水和海洋环境中找到,经常看到它们背朝上漂浮,同时用石头敲开贝类。➡ Las nutrias son mamíferos semiacuáticos juguetones conocidos por su pelaje grueso, patas palmeadas y capacidad para usar herramientas. Se pueden encontrar tanto en ambientes de agua dulce como marinos, y a menudo se les ve flotando boca arriba mientras usan rocas para romper mariscos.
猫是被驯化了数千年的迷人生物。它们以独立性、顽皮的天性以及与人类建立牢固联系的能力而闻名。全世界许多人将猫作为宠物饲养,享受它们的陪伴和它们发出的舒缓的呼噜声。➡ Los gatos son criaturas fascinantes que han sido domesticadas durante miles de años. Son conocidos por su independencia, naturaleza juguetona y capacidad para formar fuertes vínculos con los humanos. Muchas personas en todo el mundo tienen gatos como mascotas, disfrutando de su compañía y el sonido relajante de su ronroneo.
企鹅是适应水中生活的不会飞的海鸟。虽然它们主要在南半球发现,特别是在南极洲,但一些物种可以在加拉帕戈斯群岛以北的地方找到。这些有魅力的鸟类以其独特的黑白羽毛、陆地上摇摇摆摆的步态和卓越的游泳能力而闻名。➡ Los pingüinos son aves marinas no voladoras que están altamente adaptadas para la vida en el agua. Aunque se encuentran principalmente en el hemisferio sur, particularmente en la Antártida, algunas especies se pueden encontrar tan al norte como las Islas Galápagos. Estas carismáticas aves son conocidas por su distintivo plumaje blanco y negro, su andar tambaleante en tierra y sus excepcionales habilidades para nadar.
狗被称为人类最好的朋友。它们有各种品种、大小和颜色,因其忠诚、陪伴和顽皮的天性而受到喜爱。许多人喜欢带狗散步,在公园里玩接球游戏,或者只是在家里与它们拥抱。狗已经被驯化了数千年,并在各个领域扮演着各种角色,从家庭宠物到执法、搜救和治疗等领域的工作动物。➡ Los perros son conocidos como el mejor amigo del hombre. Vienen en varias razas, tamaños y colores, y son amados por su lealtad, compañía y naturaleza juguetona. Muchas personas disfrutan llevar a sus perros a pasear, jugar a buscar en el parque o simplemente acurrucarse con ellos en casa. Los perros han sido domesticados durante miles de años y desempeñan diversos roles, desde mascotas familiares hasta animales de trabajo en campos como la aplicación de la ley, búsqueda y rescate, y terapia.
…以下是你如何复现批评:
class TranslationCritique(): ... # 同上
eval_prompt_template = "..." # 同上
fast_data = FastData(model="claude-3-5-sonnet-20240620")
critiques = fast_data.generate(
prompt_template=eval_prompt_template,
inputs=[{"translation": f"{translation}"} for translation in translations],
schema=TranslationCritique,
sp=sp)
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 5/5 [00:02<00:00, 1.82it/s]
show([show_critique(t, c) for t,c in zip(translations, critiques)], collapsible=True)
你是否知道树懒是行动极其缓慢的动物?它们大部分时间都倒挂在热带雨林的树上。这些迷人的生物每天可以睡多达20个小时,移动得如此之慢,以至于藻类可以在它们的皮毛上生长!➡ ¿Sabías que los perezosos son animales que se mueven increíblemente despacio? Pasan la mayor parte de sus vidas colgados boca abajo en los árboles de las selvas tropicales. ¡Estas fascinantes criaturas pueden dormir hasta 20 horas al día y se mueven tan lentamente que las algas pueden crecer en su pelaje! 批评:翻译出色,准确捕捉细微差别,并保持西班牙语的自然流畅。评分:5
水獭是顽皮的半水生哺乳动物,以其厚皮毛、蹼足和使用工具的能力而闻名。它们可以在淡水和海洋环境中找到,经常看到它们背朝上漂浮,同时用石头敲开贝类。➡ Las nutrias son mamíferos semiacuáticos juguetones conocidos por su pelaje grueso, patas palmeadas y capacidad para usar herramientas. Se pueden encontrar tanto en ambientes de agua dulce como marinos, y a menudo se les ve flotando boca arriba mientras usan rocas para romper mariscos. 批评:翻译出色,捕捉细微差别,读起来自然;忠实传达语气和内容。评分:5
猫是被驯化了数千年的迷人生物。它们以独立性、顽皮的天性以及与人类建立牢固联系的能力而闻名。全世界许多人将猫作为宠物饲养,享受它们的陪伴和它们发出的舒缓的呼噜声。➡ Los gatos son criaturas fascinantes que han sido domesticadas durante miles de años. Son conocidos por su independencia, naturaleza juguetona y capacidad para formar fuertes vínculos con los humanos. Muchas personas en todo el mundo tienen gatos como mascotas, disfrutando de su compañía y el sonido relajante de su ronroneo. 批评:翻译出色;准确传达内容,保持语气,并在西班牙语中读起来自然。评分:5
企鹅是适应水中生活的不会飞的海鸟。虽然它们主要在南半球发现,特别是在南极洲,但一些物种可以在加拉帕戈斯群岛以北的地方找到。这些有魅力的鸟类以其独特的黑白羽毛、陆地上摇摇摆摆的步态和卓越的游泳能力而闻名。➡ Los pingüinos son aves marinas no voladoras que están altamente adaptadas para la vida en el agua. Aunque se encuentran principalmente en el hemisferio sur, particularmente en la Antártida, algunas especies se pueden encontrar tan al norte como las Islas Galápagos. Estas carismáticas aves son conocidas por su distintivo plumaje blanco y negro, su andar tambaleante en tierra y sus excepcionales habilidades para nadar. 批评:翻译出色:准确、自然,并捕捉细微差别;专业适用,风格和术语一致。评分:5
狗被称为人类最好的朋友。它们有各种品种、大小和颜色,因其忠诚、陪伴和顽皮的天性而受到喜爱。许多人喜欢带狗散步,在公园里玩接球游戏,或者只是在家里与它们拥抱。狗已经被驯化了数千年,并在各个领域扮演着各种角色,从家庭宠物到执法、搜救和治疗等领域的工作动物。➡ Los perros son conocidos como el mejor amigo del hombre. Vienen en varias razas, tamaños y colores, y son amados por su lealtad, compañía y naturaleza juguetona. Muchas personas disfrutan llevar a sus perros a pasear, jugar a buscar en el parque o simplemente acurrucarse con ellos en casa. Los perros han sido domesticados durante miles de años y desempeñan diversos roles, desde mascotas familiares hasta animales de trabajo en campos como la aplicación de la ley, búsqueda y rescate, y terapia. 批评:翻译出色,捕捉细微差别,保持语气,并在西班牙语中读起来自然。评分:5
我们将继续在未来改进 fastdata
。我们路线图上的事项包括处理重试和其他模态的输入和输出。我们很兴奋看到你们如何在下一个项目中使用 fastdata
🤓!
进一步探索与资源
如果你有兴趣深入了解,以下是一些推荐的阅读材料:
The Curious Decline of Linguistic Diversity: Training Language Models on Synthetic Text
https://arxiv.org/abs/2311.09807
How Bad is Training on Synthetic Data? A Statistical Analysis of Language Model Collapse
https://arxiv.org/abs/2404.05090
The Curse of Recursion: Training on Generated Data Makes Models Forget
https://arxiv.org/abs/2305.17493
Best Practices and Lessons Learned on Synthetic Data for Language Models
https://arxiv.org/abs/2404.07503
WizardLM: Empowering Large Language Models to Follow Complex Instructions
https://arxiv.org/abs/2304.12244
🍷 FineWeb: decanting the web for the finest text data at scale
https://huggingface.co/spaces/HuggingFaceFW/blogpost-fineweb-v1
Textbooks Are All You Need
https://arxiv.org/abs/2306.11644
Nemotron-4 340B Technical Report
https://arxiv.org/abs/2406.11704
Scaling Synthetic Data Creation with 1,000,000,000 Personas
https://arxiv.org/abs/2406.20094v1
Quality-Diversity optimisation algorithms
https://quality-diversity.github.io/
ICML 2019 Tutorial: Recent Advances in Population-Based Search for Deep Neural Networks
https://www.youtube.com/watch?v=g6HiuEnbwJE
How to Train Data-Efficient LLMs
https://arxiv.org/abs/2402.09668
备注:昵称-学校/公司-方向/会议(eg.ACL),进入技术/投稿群
id:DLNLPer,记得备注呦