任务库¶
本节包含在 distilabel
中实现的现有 Task
子类。
tasks
¶
APIGenExecutionChecker
¶
基类:Step
执行生成的函数调用。
此 step 检查模型生成的给定答案(由 APIGenGenerator
生成)是否可以针对给定的库执行(由 libpath
给出,libpath
是指向包含函数的 python .py 文件的字符串)。
属性
名称 | 类型 | 描述 |
---|---|---|
libpath |
str
|
我们将从中检索函数的库的路径。它也可以指向包含函数的文件夹。在这种情况下,文件夹布局应为包含 .py 文件的文件夹,每个文件包含一个函数,函数名称与文件名相同。 |
check_is_dangerous |
bool
|
用于排除一些潜在危险函数的布尔值,它包含在测试中找到的一些启发式方法。这些函数可以运行子进程、处理操作系统或进行其他潜在危险的操作。默认为 True。 |
输入列
- answers (
str
): 包含要传递给函数的参数的列表,从字典列表转储为字符串。应使用json.loads
加载。
输出列
- keep_row_after_execution_check (
bool
): 是否应保留该函数。 - execution_result (
str
): 执行函数的结果。
类别
- 过滤
- 执行
示例
使用来自 LLM 的答案执行给定库中的函数
from distilabel.steps.tasks import APIGenExecutionChecker
# For the libpath you can use as an example the file at the tests folder:
# ../distilabel/tests/unit/steps/tasks/apigen/_sample_module.py
task = APIGenExecutionChecker(
libpath="../distilabel/tests/unit/steps/tasks/apigen/_sample_module.py",
)
task.load()
res = next(
task.process(
[
{
"answers": [
{
"arguments": {
"initial_velocity": 0.2,
"acceleration": 0.1,
"time": 0.5,
},
"name": "final_velocity",
}
],
}
]
)
)
res
#[{'answers': [{'arguments': {'initial_velocity': 0.2, 'acceleration': 0.1, 'time': 0.5}, 'name': 'final_velocity'}], 'keep_row_after_execution_check': True, 'execution_result': ['0.25']}]
源代码位于 src/distilabel/steps/tasks/apigen/execution_checker.py
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 |
|
inputs
property
¶
任务的输入是原始数据集中找到的输入。
outputs
property
¶
输出是 APIGenGenerator
任务所需的列。
load()
¶
_get_function(function_name)
¶
从工具箱中检索函数。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
function_name
|
str
|
要检索的函数的名称。 |
必需 |
返回
名称 | 类型 | 描述 |
---|---|---|
Callable |
Callable
|
要执行的函数。 |
源代码位于 src/distilabel/steps/tasks/apigen/execution_checker.py
_is_dangerous(function)
¶
检查函数是否危险以将其移除。包含启发式方法列表,以避免执行可能危险的函数。
源代码位于 src/distilabel/steps/tasks/apigen/execution_checker.py
process(inputs)
¶
检查答案以查看是否可以执行。捕获可能的错误并返回它们。
如果提供了单个示例,则会复制它以避免引发错误。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
inputs
|
StepInput
|
包含输入数据的字典列表。 |
必需 |
产生
类型 | 描述 |
---|---|
StepOutput
|
包含输出数据的字典列表。 |
源代码位于 src/distilabel/steps/tasks/apigen/execution_checker.py
APIGenGenerator
¶
基类:Task
以 JSON 格式为给定函数生成查询和答案。
The `APIGenGenerator` is inspired by the APIGen pipeline, which was designed to generate
verifiable and diverse function-calling datasets. The task generates a set of diverse queries
and corresponding answers for the given functions in JSON format.
Attributes:
system_prompt: The system prompt to guide the user in the generation of queries and answers.
use_tools: Whether to use the tools available in the prompt to generate the queries and answers.
In case the tools are given in the input, they will be added to the prompt.
number: The number of queries to generate. It can be a list, where each number will be
chosen randomly, or a dictionary with the number of queries and the probability of each.
I.e: `number=1`, `number=[1, 2, 3]`, `number={1: 0.5, 2: 0.3, 3: 0.2}` are all valid inputs.
It corresponds to the number of parallel queries to generate.
use_default_structured_output: Whether to use the default structured output or not.
Input columns:
- examples (`str`): Examples used as few shots to guide the model.
- func_name (`str`): Name for the function to generate.
- func_desc (`str`): Description of what the function should do.
- tools (`str`): JSON formatted string containing the tool representation of the function.
Output columns:
- query (`str`): The list of queries.
- answers (`str`): JSON formatted string with the list of answers, containing the info as
a dictionary to be passed to the functions.
Categories:
- text-generation
References:
- [APIGen: Automated Pipeline for Generating Verifiable and Diverse Function-Calling Datasets](https://arxiv.org/abs/2406.18518)
- [Salesforce/xlam-function-calling-60k](https://hugging-face.cn/datasets/Salesforce/xlam-function-calling-60k)
Examples:
Generate without structured output (original implementation):
```python
from distilabel.steps.tasks import ApiGenGenerator
from distilabel.models import InferenceEndpointsLLM
llm=InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
generation_kwargs={
"temperature": 0.7,
"max_new_tokens": 1024,
},
)
apigen = ApiGenGenerator(
use_default_structured_output=False,
llm=llm
)
apigen.load()
res = next(
apigen.process(
[
{
"examples": 'QUERY:
10010 和 11101 的二进制和是多少?答案:[{"name": "binary_addition", "arguments": {"a": "10010", "b": "11101"}}]', "func_name": "getrandommovie", "func_desc": "通过调用外部 API 从数据库返回随机电影列表。" } ] ) ) res # [{'examples': '查询:10010 和 11101 的二进制和是多少?答案:[{"name": "binary_addition", "arguments": {"a": "10010", "b": "11101"}}]', # 'number': 1, # 'func_name': 'getrandommovie', # 'func_desc': '通过调用外部 API 从数据库返回随机电影列表。', # 'queries': ['我今晚想看电影,你能从你的数据库中推荐一部随机电影吗?', # '给我 5 个来自你的数据库的随机电影建议,以便计划我的周末。'], # 'answers': [[{'name': 'getrandommovie', 'arguments': {}}], # [{'name': 'getrandommovie', 'arguments': {}}, # {'name': 'getrandommovie', 'arguments': {}}, # {'name': 'getrandommovie', 'arguments': {}}, # {'name': 'getrandommovie', 'arguments': {}}, # {'name': 'getrandommovie', 'arguments': {}}]], # 'raw_input_api_gen_generator_0': [{'role': 'system', # 'content': "你是一名数据标注员。你的职责是以 JSON 格式为给定函数生成一组多样化的查询和相应的答案。
构建查询和答案,以示例说明如何在实际场景中使用这些函数。在每个查询中包含每个参数的特定、合理的数值。例如,如果函数需要日期,请使用典型且合理的日期。
确保查询:- 清晰简洁 - 展示典型的用例 - 以有意义的方式包含所有必要的参数。对于数值参数,可以是数字或单词 - 涵盖各种难度级别,从初学者到高级用例 - 相应的参数类型和范围与函数描述匹配
确保答案:- 是 JSON 格式的函数调用列表 - 答案列表的长度应等于查询中的请求数量 - 可以有效地解决查询中的所有请求"}, # {'role': 'user', # 'content': '以下是类似函数的查询和相应答案的示例:查询:10010 和 11101 的二进制和是多少?答案:[{"name": "binary_addition", "arguments": {"a": "10010", "b": "11101"}}]
请注意,查询可以解释为几个独立请求的组合。基于这些示例,为函数 getrandommovie
生成 2 个不同的查询和答案对。详细的函数描述如下:通过调用外部 API 从数据库返回随机电影列表。
输出必须严格遵守以下 JSON 格式,并且不得包含任何其他文本
[
{
"query": "The generated query.",
"answers": [
{
"name": "api_name",
"arguments": {
"arg_name": "value"
... (more arguments as required)
}
},
... (more API calls as required)
]
}
]
现在请按照上述格式生成 2 个不同的查询和答案对。'}]}, # 'model_name': 'meta-llama/Meta-Llama-3.1-70B-Instruct'}] ```
Generate with structured output:
```python
from distilabel.steps.tasks import ApiGenGenerator
from distilabel.models import InferenceEndpointsLLM
llm=InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
tokenizer="meta-llama/Meta-Llama-3.1-70B-Instruct",
generation_kwargs={
"temperature": 0.7,
"max_new_tokens": 1024,
},
)
apigen = ApiGenGenerator(
use_default_structured_output=True,
llm=llm
)
apigen.load()
res_struct = next(
apigen.process(
[
{
"examples": 'QUERY:
10010 和 11101 的二进制和是多少?答案:[{"name": "binary_addition", "arguments": {"a": "10010", "b": "11101"}}]', "func_name": "getrandommovie", "func_desc": "通过调用外部 API 从数据库返回随机电影列表。" } ] ) ) res_struct # [{'examples': '查询:10010 和 11101 的二进制和是多少?答案:[{"name": "binary_addition", "arguments": {"a": "10010", "b": "11101"}}]', # 'number': 1, # 'func_name': 'getrandommovie', # 'func_desc': '通过调用外部 API 从数据库返回随机电影列表。', # 'queries': ["我很无聊,想看电影。你能推荐一些电影吗?", # "我和我的家人正在计划一个电影之夜。我们无法决定看什么。你能推荐一些随机电影名称吗?"], # 'answers': [[{'arguments': {}, 'name': 'getrandommovie'}], # [{'arguments': {}, 'name': 'getrandommovie'}]], # 'raw_input_api_gen_generator_0': [{'role': 'system', # 'content': "你是一名数据标注员。你的职责是以 JSON 格式为给定函数生成一组多样化的查询和相应的答案。
构建查询和答案,以示例说明如何在实际场景中使用这些函数。在每个查询中包含每个参数的特定、合理的数值。例如,如果函数需要日期,请使用典型且合理的日期。
确保查询:- 清晰简洁 - 展示典型的用例 - 以有意义的方式包含所有必要的参数。对于数值参数,可以是数字或单词 - 涵盖各种难度级别,从初学者到高级用例 - 相应的参数类型和范围与函数描述匹配
确保答案:- 是 JSON 格式的函数调用列表 - 答案列表的长度应等于查询中的请求数量 - 可以有效地解决查询中的所有请求"}, # {'role': 'user', # 'content': '以下是类似函数的查询和相应答案的示例:查询:10010 和 11101 的二进制和是多少?答案:[{"name": "binary_addition", "arguments": {"a": "10010", "b": "11101"}}]
请注意,查询可以解释为几个独立请求的组合。基于这些示例,为函数 getrandommovie
生成 2 个不同的查询和答案对。详细的函数描述如下:通过调用外部 API 从数据库返回随机电影列表。
现在请按照上述格式生成 2 个不同的查询和答案对。'}]}, # 'model_name': 'meta-llama/Meta-Llama-3.1-70B-Instruct'}] ```
源代码位于 src/distilabel/steps/tasks/apigen/generator.py
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 |
|
inputs
property
¶
任务的输入。
outputs
property
¶
任务的输出是查询和相应的答案。
load()
¶
加载生成器提示的模板。
源代码位于 src/distilabel/steps/tasks/apigen/generator.py
_parallel_queries(number)
¶
准备函数以更新提示中的并行查询指南。
引发
类型 | 描述 |
---|---|
ValueError
|
如果 |
返回
类型 | 描述 |
---|---|
Callable[[int], str]
|
生成并行查询指南的函数。 |
源代码位于 src/distilabel/steps/tasks/apigen/generator.py
_get_number()
¶
生成在单个调用中生成的查询数量。必须将数字设置为 _number
,以避免在调用 _default_error
时更改原始值。
源代码位于 src/distilabel/steps/tasks/apigen/generator.py
_set_format_inst()
¶
准备函数以生成提示的格式化指令。
如果使用默认的结构化输出,则返回一个空字符串,因为不需要其他任何操作,否则,返回添加到提示的原始内容,以指导模型生成格式化的 JSON。
源代码位于 src/distilabel/steps/tasks/apigen/generator.py
_get_func_desc(input)
¶
如果可用且需要,将在提示中使用来自工具的信息以获取额外信息。否则将仅使用函数描述。
源代码位于 src/distilabel/steps/tasks/apigen/generator.py
format_input(input)
¶
输入格式化为 ChatType
。
源代码位于 src/distilabel/steps/tasks/apigen/generator.py
format_output(output, input)
¶
输出格式化为包含每个指令分数的列表。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
output
|
Union[str, None]
|
LLM 的原始输出。 |
必需 |
input
|
Dict[str, Any]
|
任务的输入。用于获取响应数量。 |
必需 |
返回
类型 | 描述 |
---|---|
Dict[str, Any]
|
包含查询和答案对的字典。 |
Dict[str, Any]
|
答案是与查询对应的答案数组。 |
Dict[str, Any]
|
每个答案都表示为一个对象,具有以下属性:- name (string):用于生成答案的工具的名称。- arguments (object):表示传递给工具以生成答案的参数的对象。 |
Dict[str, Any]
|
每个参数都表示为键值对,其中键是参数名称, |
Dict[str, Any]
|
值是对应的值。 |
源代码位于 src/distilabel/steps/tasks/apigen/generator.py
_format_output(pairs, input)
¶
解析响应,返回包含查询和答案的字典。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
pairs
|
Dict[str, Any]
|
从 LLM 的输出中解析的字典。 |
必需 |
input
|
Dict[str, Any]
|
来自 |
必需 |
返回
类型 | 描述 |
---|---|
Dict[str, Any]
|
格式化输出,其中 |
Dict[str, Any]
|
是对象列表。 |
源代码位于 src/distilabel/steps/tasks/apigen/generator.py
_default_error(input)
¶
返回默认错误输出,以在失败时填充响应。
源代码位于 src/distilabel/steps/tasks/apigen/generator.py
get_structured_output()
¶
创建要传递给 LLM 的 json 模式,以强制生成一个字典,该字典的输出可以直接解析为 python 字典。
该模式对应于以下内容
from typing import Dict, List
from pydantic import BaseModel
class Answer(BaseModel):
name: str
arguments: Dict[str, str]
class QueryAnswer(BaseModel):
query: str
answers: List[Answer]
class QueryAnswerPairs(BaseModel):
pairs: List[QueryAnswer]
json.dumps(QueryAnswerPairs.model_json_schema(), indent=4)
返回
类型 | 描述 |
---|---|
Dict[str, Any]
|
强制执行的响应的 JSON 模式。 |
源代码位于 src/distilabel/steps/tasks/apigen/generator.py
APIGenSemanticChecker
¶
基类:Task
以 JSON 格式为给定函数生成查询和答案。
APIGenGenerator
的灵感来自 APIGen pipeline,该 pipeline 旨在生成可验证和多样化的函数调用数据集。该任务以 JSON 格式为给定函数生成一组多样化的查询和相应的答案。
属性
名称 | 类型 | 描述 |
---|---|---|
system_prompt |
str
|
任务的系统提示。有一个默认提示。 |
exclude_failed_execution |
str
|
是否排除失败的执行(不会在 |
输入列
- func_desc (
str
): 函数应执行的操作的描述。 - query (
str
): 用户的指令。 - answers (
str
): JSON 编码的列表,其中包含要传递给函数/API 的参数。应使用json.loads
加载。 - execution_result (
str
): 执行的函数/API 的结果。
输出列
- thought (
str
): 关于是否保留此输出的推理。 - keep_row_after_semantic_check (
bool
): True 或 False,可用于后续过滤。
类别
- 过滤
- 文本生成
示例
Semantic checker for generated function calls (original implementation):
```python
from distilabel.steps.tasks import APIGenSemanticChecker
from distilabel.models import InferenceEndpointsLLM
llm=InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
generation_kwargs={
"temperature": 0.7,
"max_new_tokens": 1024,
},
)
semantic_checker = APIGenSemanticChecker(
use_default_structured_output=False,
llm=llm
)
semantic_checker.load()
res = next(
semantic_checker.process(
[
{
"func_desc": "Fetch information about a specific cat breed from the Cat Breeds API.",
"query": "What information can be obtained about the Maine Coon cat breed?",
"answers": json.dumps([{"name": "get_breed_information", "arguments": {"breed": "Maine Coon"}}]),
"execution_result": "The Maine Coon is a big and hairy breed of cat",
}
]
)
)
res
# [{'func_desc': 'Fetch information about a specific cat breed from the Cat Breeds API.',
# 'query': 'What information can be obtained about the Maine Coon cat breed?',
# 'answers': [{"name": "get_breed_information", "arguments": {"breed": "Maine Coon"}}],
# 'execution_result': 'The Maine Coon is a big and hairy breed of cat',
# 'thought': '',
# 'keep_row_after_semantic_check': True,
# 'raw_input_a_p_i_gen_semantic_checker_0': [{'role': 'system',
# 'content': 'As a data quality evaluator, you must assess the alignment between a user query, corresponding function calls, and their execution results.\nThese function calls and results are generated by other models, and your task is to ensure these results accurately reflect the user’s intentions.\n\nDo not pass if:\n1. The function call does not align with the query’s objective, or the input arguments appear incorrect.\n2. The function call and arguments are not properly chosen from the available functions.\n3. The number of function calls does not correspond to the user’s intentions.\n4. The execution results are irrelevant and do not match the function’s purpose.\n5. The execution results contain errors or reflect that the function calls were not executed successfully.\n'},
# {'role': 'user',
# 'content': 'Given Information:\n- All Available Functions:\nFetch information about a specific cat breed from the Cat Breeds API.\n- User Query: What information can be obtained about the Maine Coon cat breed?\n- Generated Function Calls: [{"name": "get_breed_information", "arguments": {"breed": "Maine Coon"}}]\n- Execution Results: The Maine Coon is a big and hairy breed of cat\n\nNote: The query may have multiple intentions. Functions may be placeholders, and execution results may be truncated due to length, which is acceptable and should not cause a failure.\n\nThe main decision factor is wheather the function calls accurately reflect the query\'s intentions and the function descriptions.\nProvide your reasoning in the thought section and decide if the data passes (answer yes or no).\nIf not passing, concisely explain your reasons in the thought section; otherwise, leave this section blank.\n\nYour response MUST strictly adhere to the following JSON format, and NO other text MUST be included.\n```\n{\n "thought": "Concisely describe your reasoning here",\n "pass": "yes" or "no"\n}\n```\n'}]},
# 'model_name': 'meta-llama/Meta-Llama-3.1-70B-Instruct'}]
```
Semantic checker for generated function calls (structured output):
```python
from distilabel.steps.tasks import APIGenSemanticChecker
from distilabel.models import InferenceEndpointsLLM
llm=InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
generation_kwargs={
"temperature": 0.7,
"max_new_tokens": 1024,
},
)
semantic_checker = APIGenSemanticChecker(
use_default_structured_output=True,
llm=llm
)
semantic_checker.load()
res = next(
semantic_checker.process(
[
{
"func_desc": "Fetch information about a specific cat breed from the Cat Breeds API.",
"query": "What information can be obtained about the Maine Coon cat breed?",
"answers": json.dumps([{"name": "get_breed_information", "arguments": {"breed": "Maine Coon"}}]),
"execution_result": "The Maine Coon is a big and hairy breed of cat",
}
]
)
)
res
# [{'func_desc': 'Fetch information about a specific cat breed from the Cat Breeds API.',
# 'query': 'What information can be obtained about the Maine Coon cat breed?',
# 'answers': [{"name": "get_breed_information", "arguments": {"breed": "Maine Coon"}}],
# 'execution_result': 'The Maine Coon is a big and hairy breed of cat',
# 'keep_row_after_semantic_check': True,
# 'thought': '',
# 'raw_input_a_p_i_gen_semantic_checker_0': [{'role': 'system',
# 'content': 'As a data quality evaluator, you must assess the alignment between a user query, corresponding function calls, and their execution results.\nThese function calls and results are generated by other models, and your task is to ensure these results accurately reflect the user’s intentions.\n\nDo not pass if:\n1. The function call does not align with the query’s objective, or the input arguments appear incorrect.\n2. The function call and arguments are not properly chosen from the available functions.\n3. The number of function calls does not correspond to the user’s intentions.\n4. The execution results are irrelevant and do not match the function’s purpose.\n5. The execution results contain errors or reflect that the function calls were not executed successfully.\n'},
# {'role': 'user',
# 'content': 'Given Information:\n- All Available Functions:\nFetch information about a specific cat breed from the Cat Breeds API.\n- User Query: What information can be obtained about the Maine Coon cat breed?\n- Generated Function Calls: [{"name": "get_breed_information", "arguments": {"breed": "Maine Coon"}}]\n- Execution Results: The Maine Coon is a big and hairy breed of cat\n\nNote: The query may have multiple intentions. Functions may be placeholders, and execution results may be truncated due to length, which is acceptable and should not cause a failure.\n\nThe main decision factor is wheather the function calls accurately reflect the query\'s intentions and the function descriptions.\nProvide your reasoning in the thought section and decide if the data passes (answer yes or no).\nIf not passing, concisely explain your reasons in the thought section; otherwise, leave this section blank.\n'}]},
# 'model_name': 'meta-llama/Meta-Llama-3.1-70B-Instruct'}]
```
源代码位于 src/distilabel/steps/tasks/apigen/semantic_checker.py
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 |
|
inputs
property
¶
任务的输入。
outputs
property
¶
任务的输出是查询和相应的答案。
load()
¶
加载生成器提示的模板。
源代码位于 src/distilabel/steps/tasks/apigen/semantic_checker.py
_set_format_inst()
¶
准备函数以生成提示的格式化指令。
如果使用默认的结构化输出,则返回一个空字符串,因为不需要其他任何操作,否则,返回添加到提示的原始内容,以指导模型生成格式化的 JSON。
源代码位于 src/distilabel/steps/tasks/apigen/semantic_checker.py
format_input(input)
¶
输入格式化为 ChatType
。
源代码位于 src/distilabel/steps/tasks/apigen/semantic_checker.py
format_output(output, input)
¶
输出格式化为包含每个指令分数的列表。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
output
|
Union[str, None]
|
LLM 的原始输出。 |
必需 |
input
|
Dict[str, Any]
|
任务的输入。用于获取响应数量。 |
必需 |
返回
类型 | 描述 |
---|---|
Dict[str, Any]
|
包含查询和答案对的字典。 |
Dict[str, Any]
|
答案是与查询对应的答案数组。 |
Dict[str, Any]
|
每个答案都表示为一个对象,具有以下属性:- name (string):用于生成答案的工具的名称。- arguments (object):表示传递给工具以生成答案的参数的对象。 |
Dict[str, Any]
|
每个参数都表示为键值对,其中键是参数名称, |
Dict[str, Any]
|
值是对应的值。 |
源代码位于 src/distilabel/steps/tasks/apigen/semantic_checker.py
_default_error(input)
¶
get_structured_output()
¶
创建要传递给 LLM 的 json 模式,以强制生成一个字典,该字典的输出可以直接解析为 python 字典。
该模式对应于以下内容
from typing import Literal
from pydantic import BaseModel
import json
class Checker(BaseModel):
thought: str
passes: Literal["yes", "no"]
json.dumps(Checker.model_json_schema(), indent=4)
返回
类型 | 描述 |
---|---|
Dict[str, Any]
|
强制执行的响应的 JSON 模式。 |
源代码位于 src/distilabel/steps/tasks/apigen/semantic_checker.py
ArgillaLabeller
¶
基类:Task
根据输入字段、示例记录和问题设置注释 Argilla 记录。
此任务旨在通过利用预训练的 LLM 来促进 Argilla 记录的注释。它使用系统提示来引导 LLM 理解输入字段、问题类型和问题设置。然后,该任务格式化输入数据并根据问题生成响应。响应会根据问题的值模型进行验证,并准备最终的建议以进行注释。
属性
名称 | 类型 | 描述 |
---|---|---|
_template |
Union[Template, None]
|
用于格式化 LLM 输入的 Jinja2 模板。 |
输入列
- record (
argilla.Record
): 要注释的记录。 - fields (
Optional[List[Dict[str, Any]]]
): 输入字段的字段设置列表。 - question (
Optional[Dict[str, Any]]
): 要回答的问题的问题设置。 - example_records (
Optional[List[Dict[str, Any]]]
): 包含用于回答问题的响应的少量示例记录。 - guidelines (
Optional[str]
): 注释任务的指南。
输出列
- suggestion (
Dict[str, Any]
): 用于注释的最终建议。
类别
- 文本分类
- 评分器
- 文本生成
示例
使用相同的数据集和问题注释记录
import argilla as rg
from argilla import Suggestion
from distilabel.steps.tasks import ArgillaLabeller
from distilabel.models import InferenceEndpointsLLM
# Get information from Argilla dataset definition
dataset = rg.Dataset("my_dataset")
pending_records_filter = rg.Filter(("status", "==", "pending"))
completed_records_filter = rg.Filter(("status", "==", "completed"))
pending_records = list(
dataset.records(
query=rg.Query(filter=pending_records_filter),
limit=5,
)
)
example_records = list(
dataset.records(
query=rg.Query(filter=completed_records_filter),
limit=5,
)
)
field = dataset.settings.fields["text"]
question = dataset.settings.questions["label"]
# Initialize the labeller with the model and fields
labeller = ArgillaLabeller(
llm=InferenceEndpointsLLM(
model_id="mistralai/Mistral-7B-Instruct-v0.2",
),
fields=[field],
question=question,
example_records=example_records,
guidelines=dataset.guidelines
)
labeller.load()
# Process the pending records
result = next(
labeller.process(
[
{
"record": record
} for record in pending_records
]
)
)
# Add the suggestions to the records
for record, suggestion in zip(pending_records, result):
record.suggestions.add(Suggestion(**suggestion["suggestion"]))
# Log the updated records
dataset.records.log(pending_records)
使用交替的数据集和问题注释记录
import argilla as rg
from distilabel.steps.tasks import ArgillaLabeller
from distilabel.models import InferenceEndpointsLLM
# Get information from Argilla dataset definition
dataset = rg.Dataset("my_dataset")
field = dataset.settings.fields["text"]
question = dataset.settings.questions["label"]
question2 = dataset.settings.questions["label2"]
# Initialize the labeller with the model and fields
labeller = ArgillaLabeller(
llm=InferenceEndpointsLLM(
model_id="mistralai/Mistral-7B-Instruct-v0.2",
)
)
labeller.load()
# Process the record
record = next(dataset.records())
result = next(
labeller.process(
[
{
"record": record,
"fields": [field],
"question": question,
},
{
"record": record,
"fields": [field],
"question": question2,
}
]
)
)
# Add the suggestions to the record
for suggestion in result:
record.suggestions.add(rg.Suggestion(**suggestion["suggestion"]))
# Log the updated record
dataset.records.log([record])
覆盖默认提示和指令
import argilla as rg
from distilabel.steps.tasks import ArgillaLabeller
from distilabel.models import InferenceEndpointsLLM
# Overwrite default prompts and instructions
labeller = ArgillaLabeller(
llm=InferenceEndpointsLLM(
model_id="mistralai/Mistral-7B-Instruct-v0.2",
),
system_prompt="You are an expert annotator and labelling assistant that understands complex domains and natural language processing.",
question_to_label_instruction={
"label_selection": "Select the appropriate label from the list of provided labels.",
"multi_label_selection": "Select none, one or multiple labels from the list of provided labels.",
"text": "Provide a text response to the question.",
"rating": "Provide a rating for the question.",
},
)
labeller.load()
源代码位于 src/distilabel/steps/tasks/argilla_labeller.py
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 |
|
load()
¶
加载 Jinja2 模板。
源代码位于 src/distilabel/steps/tasks/argilla_labeller.py
_format_record(record, fields)
¶
将记录字段格式化为字符串。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
record
|
Dict[str, Any]
|
要格式化的记录。 |
必需 |
fields
|
List[Dict[str, Any]]
|
要格式化的字段。 |
必需 |
返回
名称 | 类型 | 描述 |
---|---|---|
str |
str
|
格式化的记录字段。 |
源代码位于 src/distilabel/steps/tasks/argilla_labeller.py
_get_label_instruction(question)
¶
获取问题标签指令。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
question
|
Dict[str, Any]
|
要获取标签指令的问题。 |
必需 |
返回
名称 | 类型 | 描述 |
---|---|---|
str |
str
|
问题的标签指令。 |
源代码位于 src/distilabel/steps/tasks/argilla_labeller.py
_format_question(question)
¶
将问题设置格式化为字符串。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
question
|
Dict[str, Any]
|
要格式化的问题。 |
必需 |
返回
名称 | 类型 | 描述 |
---|---|---|
str |
str
|
格式化后的问题。 |
源代码位于 src/distilabel/steps/tasks/argilla_labeller.py
_format_example_records(records, fields, question)
¶
将示例记录格式化为字符串。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
records
|
List[Dict[str, Any]]
|
要格式化的记录。 |
必需 |
fields
|
List[Dict[str, Any]]
|
要格式化的字段。 |
必需 |
question
|
Dict[str, Any]
|
要格式化的问题。 |
必需 |
返回
名称 | 类型 | 描述 |
---|---|---|
str |
str
|
格式化后的示例记录。 |
源代码位于 src/distilabel/steps/tasks/argilla_labeller.py
format_input(input)
¶
将输入格式化为聊天消息。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
input
|
Dict[str, Union[Dict[str, Any], Record, TextField, MultiLabelQuestion, LabelQuestion, RatingQuestion, TextQuestion]]
|
要格式化的输入。 |
必需 |
返回
类型 | 描述 |
---|---|
ChatType
|
格式化后的聊天消息。 |
引发
类型 | 描述 |
---|---|
ValueError
|
如果未提供问题或字段。 |
源代码位于 src/distilabel/steps/tasks/argilla_labeller.py
format_output(output, input)
¶
将输出格式化为字典。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
output
|
Union[str, None]
|
要格式化的输出。 |
必需 |
input
|
Dict[str, Any]
|
要格式化的输入。 |
必需 |
返回
类型 | 描述 |
---|---|
Dict[str, Any]
|
Dict[str, Any]: 格式化后的输出。 |
源代码位于 src/distilabel/steps/tasks/argilla_labeller.py
process(inputs)
¶
通过任务处理输入。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
inputs
|
StepInput
|
要处理的输入。 |
必需 |
返回
名称 | 类型 | 描述 |
---|---|---|
StepOutput |
StepOutput
|
任务的输出。 |
源代码位于 src/distilabel/steps/tasks/argilla_labeller.py
_get_value_from_question_value_model(question_value_model)
¶
从问题值模型中获取值。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
question_value_model
|
BaseModel
|
从中获取值的问题值模型。 |
必需 |
返回
名称 | 类型 | 描述 |
---|---|---|
Any |
Any
|
来自问题值模型的值。 |
源代码位于 src/distilabel/steps/tasks/argilla_labeller.py
_assign_value_to_question_value_model(value, question)
¶
将值分配给问题值模型。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
value
|
Any
|
要分配的值。 |
必需 |
question
|
Dict[str, Any]
|
要将值分配到的问题。 |
必需 |
返回
名称 | 类型 | 描述 |
---|---|---|
BaseModel |
BaseModel
|
具有已分配值的问题值模型。 |
源代码位于 src/distilabel/steps/tasks/argilla_labeller.py
_get_pydantic_model_of_structured_output(question)
¶
获取结构化输出的 Pydantic 模型。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
question
|
Dict[str, Any]
|
为其获取结构化输出的 Pydantic 模型的问题。 |
必需 |
返回
名称 | 类型 | 描述 |
---|---|---|
BaseModel |
BaseModel
|
结构化输出的 Pydantic 模型。 |
源代码位于 src/distilabel/steps/tasks/argilla_labeller.py
CLAIR
¶
基类:Task
人工智能修订的对比学习 (CLAIR)。
CLAIR 使用人工智能系统来最小限度地修订解决方案 A→A´,从而使得到的偏好 A preferred
A’ 更具对比性和精确性。
输入列
- task (
str
): 任务或指令。 - student_solution (
str
): 待修订任务的答案。
输出列
- revision (
str
): 修订后的文本。 - rational (
str
): 提供修订的理由。 - model_name (
str
): 用于生成修订和理由的模型的名称。
类别
- preference
- 文本生成
示例
创建对比偏好对
from distilabel.steps.tasks import CLAIR
from distilabel.models import InferenceEndpointsLLM
llm=InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
tokenizer_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
generation_kwargs={
"temperature": 0.7,
"max_new_tokens": 4096,
},
)
clair_task = CLAIR(llm=llm)
clair_task.load()
result = next(
clair_task.process(
[
{
"task": "How many gaps are there between the earth and the moon?",
"student_solution": 'There are no gaps between the Earth and the Moon. The Moon is actually in a close orbit around the Earth, and it is held in place by gravity. The average distance between the Earth and the Moon is about 384,400 kilometers (238,900 miles), and this distance is known as the "lunar distance" or "lunar mean distance."\n\nThe Moon does not have a gap between it and the Earth because it is a natural satellite that is gravitationally bound to our planet. The Moon's orbit is elliptical, which means that its distance from the Earth varies slightly over the course of a month, but it always remains within a certain range.\n\nSo, to summarize, there are no gaps between the Earth and the Moon. The Moon is simply a satellite that orbits the Earth, and its distance from our planet varies slightly due to the elliptical shape of its orbit.'
}
]
)
)
# result
# [{'task': 'How many gaps are there between the earth and the moon?',
# 'student_solution': 'There are no gaps between the Earth and the Moon. The Moon is actually in a close orbit around the Earth, and it is held in place by gravity. The average distance between the Earth and the Moon is about 384,400 kilometers (238,900 miles), and this distance is known as the "lunar distance" or "lunar mean distance."\n\nThe Moon does not have a gap between it and the Earth because it is a natural satellite that is gravitationally bound to our planet. The Moon\'s orbit is elliptical, which means that its distance from the Earth varies slightly over the course of a month, but it always remains within a certain range.\n\nSo, to summarize, there are no gaps between the Earth and the Moon. The Moon is simply a satellite that orbits the Earth, and its distance from our planet varies slightly due to the elliptical shape of its orbit.',
# 'revision': 'There are no physical gaps or empty spaces between the Earth and the Moon. The Moon is actually in a close orbit around the Earth, and it is held in place by gravity. The average distance between the Earth and the Moon is about 384,400 kilometers (238,900 miles), and this distance is known as the "lunar distance" or "lunar mean distance."\n\nThe Moon does not have a significant separation or gap between it and the Earth because it is a natural satellite that is gravitationally bound to our planet. The Moon\'s orbit is elliptical, which means that its distance from the Earth varies slightly over the course of a month, but it always remains within a certain range. This variation in distance is a result of the Moon\'s orbital path, not the presence of any gaps.\n\nIn summary, the Moon\'s orbit is continuous, with no intervening gaps, and its distance from the Earth varies due to the elliptical shape of its orbit.',
# 'rational': 'The student\'s solution provides a clear and concise answer to the question. However, there are a few areas where it can be improved. Firstly, the term "gaps" can be misleading in this context. The student should clarify what they mean by "gaps." Secondly, the student provides some additional information about the Moon\'s orbit, which is correct but could be more clearly connected to the main point. Lastly, the student\'s conclusion could be more concise.',
# 'distilabel_metadata': {'raw_output_c_l_a_i_r_0': '{teacher_reasoning}: The student\'s solution provides a clear and concise answer to the question. However, there are a few areas where it can be improved. Firstly, the term "gaps" can be misleading in this context. The student should clarify what they mean by "gaps." Secondly, the student provides some additional information about the Moon\'s orbit, which is correct but could be more clearly connected to the main point. Lastly, the student\'s conclusion could be more concise.\n\n{corrected_student_solution}: There are no physical gaps or empty spaces between the Earth and the Moon. The Moon is actually in a close orbit around the Earth, and it is held in place by gravity. The average distance between the Earth and the Moon is about 384,400 kilometers (238,900 miles), and this distance is known as the "lunar distance" or "lunar mean distance."\n\nThe Moon does not have a significant separation or gap between it and the Earth because it is a natural satellite that is gravitationally bound to our planet. The Moon\'s orbit is elliptical, which means that its distance from the Earth varies slightly over the course of a month, but it always remains within a certain range. This variation in distance is a result of the Moon\'s orbital path, not the presence of any gaps.\n\nIn summary, the Moon\'s orbit is continuous, with no intervening gaps, and its distance from the Earth varies due to the elliptical shape of its orbit.',
# 'raw_input_c_l_a_i_r_0': [{'role': 'system',
# 'content': "You are a teacher and your task is to minimally improve a student's answer. I will give you a {task} and a {student_solution}. Your job is to revise the {student_solution} such that it is clearer, more correct, and more engaging. Copy all non-corrected parts of the student's answer. Do not allude to the {corrected_student_solution} being a revision or a correction in your final solution."},
# {'role': 'user',
# 'content': '{task}: How many gaps are there between the earth and the moon?\n\n{student_solution}: There are no gaps between the Earth and the Moon. The Moon is actually in a close orbit around the Earth, and it is held in place by gravity. The average distance between the Earth and the Moon is about 384,400 kilometers (238,900 miles), and this distance is known as the "lunar distance" or "lunar mean distance."\n\nThe Moon does not have a gap between it and the Earth because it is a natural satellite that is gravitationally bound to our planet. The Moon\'s orbit is elliptical, which means that its distance from the Earth varies slightly over the course of a month, but it always remains within a certain range.\n\nSo, to summarize, there are no gaps between the Earth and the Moon. The Moon is simply a satellite that orbits the Earth, and its distance from our planet varies slightly due to the elliptical shape of its orbit.\n\n-----------------\n\nLet\'s first think step by step with a {teacher_reasoning} to decide how to improve the {student_solution}, then give the {corrected_student_solution}. Mention the {teacher_reasoning} and {corrected_student_solution} identifiers to structure your answer.'}]},
# 'model_name': 'meta-llama/Meta-Llama-3.1-70B-Instruct'}]
引用
```
@misc{doosterlinck2024anchoredpreferenceoptimizationcontrastive,
title={Anchored Preference Optimization and Contrastive Revisions: Addressing Underspecification in Alignment},
author={Karel D'Oosterlinck and Winnie Xu and Chris Develder and Thomas Demeester and Amanpreet Singh and Christopher Potts and Douwe Kiela and Shikib Mehri},
year={2024},
eprint={2408.06266},
archivePrefix={arXiv},
primaryClass={cs.LG},
url={https://arxiv.org/abs/2408.06266},
}
```
源代码位于 src/distilabel/steps/tasks/clair.py
中
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 |
|
format_input(input)
¶
输入被格式化为 ChatType
,假设指令是用户在对话中的首次互动。
源代码位于 src/distilabel/steps/tasks/clair.py
中
format_output(output, input)
¶
输出被格式化为一个列表,其中包含每个指令-响应对的分数。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
output
|
Union[str, None]
|
LLM 的原始输出。 |
必需 |
input
|
Dict[str, Any]
|
任务的输入。用于获取响应数量。 |
必需 |
返回
类型 | 描述 |
---|---|
Dict[str, Any]
|
一个字典,键为 |
源代码位于 src/distilabel/steps/tasks/clair.py
中
ComplexityScorer
¶
基类:Task
使用 LLM
根据指令的复杂性对其进行评分。
ComplexityScorer
是一个预定义的任务,用于根据指令列表的复杂性对其进行排名。它是论文“什么使对齐数据良好?指令调优中自动数据选择的综合研究”中复杂性评分任务的实现。
属性
名称 | 类型 | 描述 |
---|---|---|
_template |
Union[Template, None]
|
用于格式化 LLM 输入的 Jinja2 模板。 |
输入列
- instructions (
List[str]
): 要评分的指令列表。
输出列
- scores (
List[float]
): 每个指令的分数。 - model_name (
str
): 用于生成分数的模型名称。
类别
- 评分器
- complexity
- instruction
示例
评估指令的复杂性
from distilabel.steps.tasks import ComplexityScorer
from distilabel.models import InferenceEndpointsLLM
# Consider this as a placeholder for your actual LLM.
scorer = ComplexityScorer(
llm=InferenceEndpointsLLM(
model_id="mistralai/Mistral-7B-Instruct-v0.2",
)
)
scorer.load()
result = next(
scorer.process(
[{"instructions": ["plain instruction", "highly complex instruction"]}]
)
)
# result
# [{'instructions': ['plain instruction', 'highly complex instruction'], 'model_name': 'test', 'scores': [1, 5], 'distilabel_metadata': {'raw_output_complexity_scorer_0': 'output'}}]
使用默认模式生成结构化输出
from distilabel.steps.tasks import ComplexityScorer
from distilabel.models import InferenceEndpointsLLM
# Consider this as a placeholder for your actual LLM.
scorer = ComplexityScorer(
llm=InferenceEndpointsLLM(
model_id="mistralai/Mistral-7B-Instruct-v0.2",
),
use_default_structured_output=use_default_structured_output
)
scorer.load()
result = next(
scorer.process(
[{"instructions": ["plain instruction", "highly complex instruction"]}]
)
)
# result
# [{'instructions': ['plain instruction', 'highly complex instruction'], 'model_name': 'test', 'scores': [1, 2], 'distilabel_metadata': {'raw_output_complexity_scorer_0': '{ \n "scores": [\n 1, \n 2\n ]\n}'}}]
引用
@misc{liu2024makesgooddataalignment,
title={What Makes Good Data for Alignment? A Comprehensive Study of Automatic Data Selection in Instruction Tuning},
author={Wei Liu and Weihao Zeng and Keqing He and Yong Jiang and Junxian He},
year={2024},
eprint={2312.15685},
archivePrefix={arXiv},
primaryClass={cs.CL},
url={https://arxiv.org/abs/2312.15685},
}
源代码位于 src/distilabel/steps/tasks/complexity_scorer.py
中
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 |
|
inputs
property
¶
任务的输入是 instructions
。
outputs
property
¶
任务的输出是:一个 scores
列表,其中包含 instructions
中每个指令的复杂性评分,以及 model_name
。
load()
¶
加载 Jinja2 模板。
源代码位于 src/distilabel/steps/tasks/complexity_scorer.py
中
format_input(input)
¶
输入被格式化为 ChatType
,假设指令是用户在对话中的首次互动。
源代码位于 src/distilabel/steps/tasks/complexity_scorer.py
中
format_output(output, input)
¶
输出格式化为包含每个指令分数的列表。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
output
|
Union[str, None]
|
LLM 的原始输出。 |
必需 |
input
|
Dict[str, Any]
|
任务的输入。用于获取响应数量。 |
必需 |
返回
类型 | 描述 |
---|---|
Dict[str, Any]
|
一个字典,键为 |
源代码位于 src/distilabel/steps/tasks/complexity_scorer.py
中
get_structured_output()
¶
创建要传递给 LLM 的 json 模式,以强制生成一个字典,该字典的输出可以直接解析为 python 字典。
该模式对应于以下内容
from pydantic import BaseModel
from typing import List
class SchemaComplexityScorer(BaseModel):
scores: List[int]
返回
类型 | 描述 |
---|---|
Dict[str, Any]
|
强制执行的响应的 JSON 模式。 |
源代码位于 src/distilabel/steps/tasks/complexity_scorer.py
中
_format_structured_output(output, input)
¶
解析结构化响应,该响应应对应于一个字典,其中包含 positive
或 positive
和 negative
键。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
output
|
str
|
来自 |
必需 |
返回
类型 | 描述 |
---|---|
Dict[str, str]
|
格式化后的输出。 |
源代码位于 src/distilabel/steps/tasks/complexity_scorer.py
中
_sample_input()
¶
返回要在 print
方法中使用的示例输入。不遵循返回 str -> str 类型映射的格式输入的任务应覆盖此方法以返回示例输入。
源代码位于 src/distilabel/steps/tasks/complexity_scorer.py
中
EvolInstruct
¶
基类:Task
使用 LLM
进化指令。
WizardLM:使大型语言模型能够遵循复杂指令
属性
名称 | 类型 | 描述 |
---|---|---|
num_evolutions |
int
|
要执行的进化次数。 |
store_evolutions |
bool
|
是否存储所有进化过程,还是仅存储最后一个进化过程。默认为 |
generate_answers |
bool
|
是否为进化后的指令生成答案。默认为 |
include_original_instruction |
bool
|
是否在 |
mutation_templates |
Dict[str, str]
|
用于进化指令的突变模板。默认为 |
seed |
RuntimeParameter[int]
|
为 |
运行时参数
seed
:为numpy
设置的种子,以便随机选择突变方法。
输入列
- instruction (
str
): 要进化的指令。
输出列
- evolved_instruction (
str
): 如果store_evolutions=False
,则为进化后的指令。 - evolved_instructions (
List[str]
): 如果store_evolutions=True
,则为进化后的指令。 - model_name (
str
): 用于进化指令的 LLM 的名称。 - answer (
str
): 如果generate_answers=True
且store_evolutions=False
,则为进化后指令的答案。 - answers (
List[str]
): 如果generate_answers=True
且store_evolutions=True
,则为进化后指令的答案。
类别
- evol
- instruction
示例
使用 LLM 进化指令
from distilabel.steps.tasks import EvolInstruct
from distilabel.models import InferenceEndpointsLLM
# Consider this as a placeholder for your actual LLM.
evol_instruct = EvolInstruct(
llm=InferenceEndpointsLLM(
model_id="mistralai/Mistral-7B-Instruct-v0.2",
),
num_evolutions=2,
)
evol_instruct.load()
result = next(evol_instruct.process([{"instruction": "common instruction"}]))
# result
# [{'instruction': 'common instruction', 'evolved_instruction': 'evolved instruction', 'model_name': 'model_name'}]
保留进化迭代
from distilabel.steps.tasks import EvolInstruct
from distilabel.models import InferenceEndpointsLLM
# Consider this as a placeholder for your actual LLM.
evol_instruct = EvolInstruct(
llm=InferenceEndpointsLLM(
model_id="mistralai/Mistral-7B-Instruct-v0.2",
),
num_evolutions=2,
store_evolutions=True,
)
evol_instruct.load()
result = next(evol_instruct.process([{"instruction": "common instruction"}]))
# result
# [
# {
# 'instruction': 'common instruction',
# 'evolved_instructions': ['initial evolution', 'final evolution'],
# 'model_name': 'model_name'
# }
# ]
在单个步骤中为指令生成答案
from distilabel.steps.tasks import EvolInstruct
from distilabel.models import InferenceEndpointsLLM
# Consider this as a placeholder for your actual LLM.
evol_instruct = EvolInstruct(
llm=InferenceEndpointsLLM(
model_id="mistralai/Mistral-7B-Instruct-v0.2",
),
num_evolutions=2,
generate_answers=True,
)
evol_instruct.load()
result = next(evol_instruct.process([{"instruction": "common instruction"}]))
# result
# [
# {
# 'instruction': 'common instruction',
# 'evolved_instruction': 'evolved instruction',
# 'answer': 'answer to the instruction',
# 'model_name': 'model_name'
# }
# ]
引用
@misc{xu2023wizardlmempoweringlargelanguage,
title={WizardLM: Empowering Large Language Models to Follow Complex Instructions},
author={Can Xu and Qingfeng Sun and Kai Zheng and Xiubo Geng and Pu Zhao and Jiazhan Feng and Chongyang Tao and Daxin Jiang},
year={2023},
eprint={2304.12244},
archivePrefix={arXiv},
primaryClass={cs.CL},
url={https://arxiv.org/abs/2304.12244},
}
源代码位于 src/distilabel/steps/tasks/evol_instruct/base.py
中
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 |
|
inputs
property
¶
任务的输入是 instruction
。
outputs
property
¶
任务的输出是 evolved_instruction/s
、answer
(如果 generate_answers=True
)和 model_name
。
mutation_templates_names
property
¶
返回提供的 mutation_templates
的名称,即键。
format_input(input)
¶
输入被格式化为 ChatType
,假设指令是用户在对话中的首次互动。如果存在 system_prompt
,则将其添加为第一条消息。
源代码位于 src/distilabel/steps/tasks/evol_instruct/base.py
中
format_output(instructions, answers=None)
¶
任务的输出是一个字典,其中包含:evolved_instruction
或 evolved_instructions
,具体取决于 store_evolutions
的值为 False
还是 True
;answer
(如果 generate_answers=True
);以及最后的 model_name
。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
instructions
|
Union[str, List[str]]
|
要包含在输出中的指令。 |
必需 |
answers
|
Optional[List[str]]
|
如果 |
None
|
返回
类型 | 描述 |
---|---|
Dict[str, Any]
|
如果 |
Dict[str, Any]
|
如果 |
Dict[str, Any]
|
如果 |
Dict[str, Any]
|
如果 |
源代码位于 src/distilabel/steps/tasks/evol_instruct/base.py
中
_apply_random_mutation(instruction)
¶
应用从作为 mutation_templates
枚举一部分提供的突变中随机选择的突变,并在突变提示中返回提供的指令。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
instruction
|
str
|
要包含在突变提示中的指令。 |
必需 |
返回
类型 | 描述 |
---|---|
str
|
带有提供的指令的随机突变提示。 |
源代码位于 src/distilabel/steps/tasks/evol_instruct/base.py
中
_evolve_instructions(inputs)
¶
进化作为任务输入一部分提供的指令。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
inputs
|
StepInput
|
包含任务输入的 Python 字典列表。 |
必需 |
返回
类型 | 描述 |
---|---|
List[List[str]]
|
一个列表,其中每个项目都是一个列表,其中包含最后一个进化后的指令(如果 |
List[List[str]]
|
|
源代码位于 src/distilabel/steps/tasks/evol_instruct/base.py
中
_generate_answers(evolved_instructions)
¶
为 instructions
中的指令生成答案。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
evolved_instructions
|
List[List[str]]
|
一个列表的列表,其中每个项目都是一个列表,其中包含最后一个进化后的指令(如果 |
必需 |
返回
类型 | 描述 |
---|---|
Tuple[List[List[str]], LLMStatistics]
|
每个指令的答案列表。 |
源代码位于 src/distilabel/steps/tasks/evol_instruct/base.py
中
process(inputs)
¶
处理任务的输入,并使用 LLM 生成输出。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
inputs
|
StepInput
|
包含任务输入的 Python 字典列表。 |
必需 |
产生
类型 | 描述 |
---|---|
StepOutput
|
包含任务输出的 Python 字典列表。 |
源代码位于 src/distilabel/steps/tasks/evol_instruct/base.py
中
EvolComplexity
¶
基类:EvolInstruct
使用 LLM
进化指令以使其更复杂。
EvolComplexity
是一个进化指令以使其更复杂的任务,它基于 EvolInstruct 任务,使用略有不同的提示,但进化方法完全相同。
属性
名称 | 类型 | 描述 |
---|---|---|
num_instructions |
要生成的指令数量。 |
|
generate_answers |
bool
|
是否为指令生成答案。默认为 |
mutation_templates |
Dict[str, str]
|
用于生成指令的突变模板。 |
min_length |
Dict[str, str]
|
定义生成的指令需要高于的长度(以字节为单位),才能被视为有效。默认为 |
max_length |
Dict[str, str]
|
定义生成的指令需要低于的长度(以字节为单位),才能被视为有效。默认为 |
seed |
RuntimeParameter[int]
|
为 |
运行时参数
min_length
:定义生成的指令需要高于的长度(以字节为单位),才能被视为有效。max_length
:定义生成的指令需要低于的长度(以字节为单位),才能被视为有效。seed
:要运行的进化次数。
输入列
- instruction (
str
): 要进化的指令。
输出列
- evolved_instruction (
str
): 进化后的指令。 - answer (
str
, optional): 如果generate_answers=True
,则为指令的答案。 - model_name (
str
): 用于进化指令的 LLM 的名称。
类别
- evol
- instruction
- deita
示例
使用 LLM 进化指令
from distilabel.steps.tasks import EvolComplexity
from distilabel.models import InferenceEndpointsLLM
# Consider this as a placeholder for your actual LLM.
evol_complexity = EvolComplexity(
llm=InferenceEndpointsLLM(
model_id="mistralai/Mistral-7B-Instruct-v0.2",
),
num_evolutions=2,
)
evol_complexity.load()
result = next(evol_complexity.process([{"instruction": "common instruction"}]))
# result
# [{'instruction': 'common instruction', 'evolved_instruction': 'evolved instruction', 'model_name': 'model_name'}]
引用
@misc{liu2024makesgooddataalignment,
title={What Makes Good Data for Alignment? A Comprehensive Study of Automatic Data Selection in Instruction Tuning},
author={Wei Liu and Weihao Zeng and Keqing He and Yong Jiang and Junxian He},
year={2024},
eprint={2312.15685},
archivePrefix={arXiv},
primaryClass={cs.CL},
url={https://arxiv.org/abs/2312.15685},
}
@misc{xu2023wizardlmempoweringlargelanguage,
title={WizardLM: Empowering Large Language Models to Follow Complex Instructions},
author={Can Xu and Qingfeng Sun and Kai Zheng and Xiubo Geng and Pu Zhao and Jiazhan Feng and Chongyang Tao and Daxin Jiang},
year={2023},
eprint={2304.12244},
archivePrefix={arXiv},
primaryClass={cs.CL},
url={https://arxiv.org/abs/2304.12244},
}
源代码位于 src/distilabel/steps/tasks/evol_instruct/evol_complexity/base.py
中
EvolComplexityGenerator
¶
使用 LLM
生成复杂度增加的进化指令。
EvolComplexityGenerator
是一个生成任务,它进化指令以使其更复杂,它基于 EvolInstruct 任务,但使用略有不同的提示,但进化方法完全相同。
属性
名称 | 类型 | 描述 |
---|---|---|
num_instructions |
int
|
要生成的指令数量。 |
generate_answers |
bool
|
是否为指令生成答案。默认为 |
mutation_templates |
Dict[str, str]
|
用于生成指令的突变模板。 |
min_length |
RuntimeParameter[int]
|
定义生成的指令需要高于的长度(以字节为单位),才能被视为有效。默认为 |
max_length |
RuntimeParameter[int]
|
定义生成的指令需要低于的长度(以字节为单位),才能被视为有效。默认为 |
seed |
RuntimeParameter[int]
|
为 |
运行时参数
min_length
:定义生成的指令需要高于的长度(以字节为单位),才能被视为有效。max_length
:定义生成的指令需要低于的长度(以字节为单位),才能被视为有效。seed
:要运行的进化次数。
输出列
- instruction (
str
): 进化后的指令。 - answer (
str
, optional): 如果generate_answers=True
,则为指令的答案。 - model_name (
str
): 用于进化指令的 LLM 的名称。
类别
- evol
- instruction
- generation
- deita
示例
生成没有初始指令的进化指令
from distilabel.steps.tasks import EvolComplexityGenerator
from distilabel.models import InferenceEndpointsLLM
# Consider this as a placeholder for your actual LLM.
evol_complexity_generator = EvolComplexityGenerator(
llm=InferenceEndpointsLLM(
model_id="mistralai/Mistral-7B-Instruct-v0.2",
),
num_instructions=2,
)
evol_complexity_generator.load()
result = next(scorer.process())
# result
# [{'instruction': 'generated instruction', 'model_name': 'test'}]
引用
@misc{liu2024makesgooddataalignment,
title={What Makes Good Data for Alignment? A Comprehensive Study of Automatic Data Selection in Instruction Tuning},
author={Wei Liu and Weihao Zeng and Keqing He and Yong Jiang and Junxian He},
year={2024},
eprint={2312.15685},
archivePrefix={arXiv},
primaryClass={cs.CL},
url={https://arxiv.org/abs/2312.15685},
}
@misc{xu2023wizardlmempoweringlargelanguage,
title={WizardLM: Empowering Large Language Models to Follow Complex Instructions},
author={Can Xu and Qingfeng Sun and Kai Zheng and Xiubo Geng and Pu Zhao and Jiazhan Feng and Chongyang Tao and Daxin Jiang},
year={2023},
eprint={2304.12244},
archivePrefix={arXiv},
primaryClass={cs.CL},
url={https://arxiv.org/abs/2304.12244},
}
源代码位于 src/distilabel/steps/tasks/evol_instruct/evol_complexity/generator.py
中
EvolInstructGenerator
¶
使用 LLM
生成进化指令。
WizardLM:使大型语言模型能够遵循复杂指令
属性
名称 | 类型 | 描述 |
---|---|---|
num_instructions |
int
|
要生成的指令数量。 |
generate_answers |
bool
|
是否为指令生成答案。默认为 |
mutation_templates |
Dict[str, str]
|
用于生成指令的突变模板。 |
min_length |
RuntimeParameter[int]
|
定义生成的指令需要高于的长度(以字节为单位),才能被视为有效。默认为 |
max_length |
RuntimeParameter[int]
|
定义生成的指令需要低于的长度(以字节为单位),才能被视为有效。默认为 |
seed |
RuntimeParameter[int]
|
为 |
运行时参数
min_length
:定义生成的指令需要高于的长度(以字节为单位),才能被视为有效。max_length
:定义生成的指令需要低于的长度(以字节为单位),才能被视为有效。seed
:为numpy
设置的种子,以便随机选择突变方法。
输出列
- instruction (
str
): 如果generate_answers=False
,则为生成的指令。 - answer (
str
): 如果generate_answers=True
,则为生成的答案。 - instructions (
List[str]
): 如果generate_answers=True
,则为生成的指令。 - model_name (
str
): 用于生成和进化指令的 LLM 的名称。
类别
- evol
- instruction
- generation
示例
生成没有初始指令的进化指令
from distilabel.steps.tasks import EvolInstructGenerator
from distilabel.models import InferenceEndpointsLLM
# Consider this as a placeholder for your actual LLM.
evol_instruct_generator = EvolInstructGenerator(
llm=InferenceEndpointsLLM(
model_id="mistralai/Mistral-7B-Instruct-v0.2",
),
num_instructions=2,
)
evol_instruct_generator.load()
result = next(scorer.process())
# result
# [{'instruction': 'generated instruction', 'model_name': 'test'}]
引用
@misc{xu2023wizardlmempoweringlargelanguage,
title={WizardLM: Empowering Large Language Models to Follow Complex Instructions},
author={Can Xu and Qingfeng Sun and Kai Zheng and Xiubo Geng and Pu Zhao and Jiazhan Feng and Chongyang Tao and Daxin Jiang},
year={2023},
eprint={2304.12244},
archivePrefix={arXiv},
primaryClass={cs.CL},
url={https://arxiv.org/abs/2304.12244},
}
源代码位于 src/distilabel/steps/tasks/evol_instruct/generator.py
中
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 |
|
_english_nouns
cached
property
¶
作为任务起始提示一部分使用的英语名词列表。
参考
- https://github.com/h2oai/h2o-wizardlm
outputs
property
¶
任务的输出是 instruction
、answer
(如果 generate_answers=True
)和 model_name
。
mutation_templates_names
property
¶
返回提供的 mutation_templates
的名称,即键。
_generate_seed_texts()
¶
生成要用作任务起始提示一部分的种子文本列表。
它将使用 FRESH_START
突变模板,因为它需要从头开始生成文本;并且将使用英语单词列表来生成将提供给突变方法并包含在提示中的种子文本。
返回
类型 | 描述 |
---|---|
List[str]
|
要用作任务起始提示一部分的种子文本列表。 |
源代码位于 src/distilabel/steps/tasks/evol_instruct/generator.py
中
model_post_init(__context)
¶
覆盖此方法以在 __init__
和 model_construct
之后执行其他初始化。如果您想执行一些需要整个模型初始化的验证,这将非常有用。
源代码位于 src/distilabel/steps/tasks/evol_instruct/generator.py
中
format_output(instruction, answer=None)
¶
任务的输出是一个字典,其中包含:instruction
;answer
(如果 generate_answers=True
);以及最后的 model_name
。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
instruction
|
str
|
要包含在输出中的指令。 |
必需 |
answer
|
Optional[str]
|
如果 |
None
|
返回
类型 | 描述 |
---|---|
Dict[str, Any]
|
如果 |
Dict[str, Any]
|
如果 |
源代码位于 src/distilabel/steps/tasks/evol_instruct/generator.py
中
_apply_random_mutation(iter_no)
¶
应用从作为 mutation_templates
枚举一部分提供的突变中随机选择的突变,并在突变提示中返回提供的指令。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
iter_no
|
int
|
用于检查迭代是否是第一次迭代(即 FRESH_START)的迭代次数。 |
必需 |
返回
类型 | 描述 |
---|---|
List[ChatType]
|
带有提供的指令的随机突变提示,格式为 OpenAI 对话。 |
源代码位于 src/distilabel/steps/tasks/evol_instruct/generator.py
中
_generate_answers(instructions)
¶
为 instructions
中最后一个指令生成答案。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
instructions
|
List[List[str]]
|
一个列表的列表,其中每个项目都是一个列表,其中包含最后一个进化后的指令(如果 |
必需 |
返回
类型 | 描述 |
---|---|
Tuple[List[str], LLMStatistics]
|
|
源代码位于 src/distilabel/steps/tasks/evol_instruct/generator.py
中
process(offset=0)
¶
处理任务的输入,并使用 LLM 生成输出。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
offset
|
int
|
开始生成的偏移量。默认为 0。 |
0
|
产生
类型 | 描述 |
---|---|
GeneratorStepOutput
|
包含任务输出的 Python 字典列表,以及一个布尔值 |
GeneratorStepOutput
|
标志,指示任务是否已完成,即是否是最后一个批次。 |
源代码位于 src/distilabel/steps/tasks/evol_instruct/generator.py
中
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 |
|
EvolQuality
¶
基类:Task
使用 LLM
进化响应的质量。
EvolQuality
任务用于进化给定提示的响应质量,方法是使用语言模型生成新的响应。此步骤实现了论文“什么使对齐数据良好?指令调优中自动数据选择的综合研究”中的进化质量任务。
属性
名称 | 类型 | 描述 |
---|---|---|
num_evolutions |
int
|
要在响应上执行的进化次数。 |
store_evolutions |
bool
|
是否存储所有进化后的响应,还是仅存储最后一个响应。默认为 |
include_original_response |
bool
|
是否在进化后的响应中包含原始响应。默认为 |
mutation_templates |
Dict[str, str]
|
用于进化响应的突变模板。 |
seed |
RuntimeParameter[int]
|
为 |
运行时参数
seed
:为numpy
设置的种子,以便随机选择突变方法。
输入列
- instruction (
str
): 用于生成responses
的指令。 - response (
str
): 要重写的响应。
输出列
- evolved_response (
str
): 如果store_evolutions=False
,则为进化后的响应。 - evolved_responses (
List[str]
): 如果store_evolutions=True
,则为进化后的响应。 - model_name (
str
): 用于进化响应的 LLM 的名称。
类别
- evol
- response
- deita
示例
进化给定提示的响应质量
from distilabel.steps.tasks import EvolQuality
from distilabel.models import InferenceEndpointsLLM
# Consider this as a placeholder for your actual LLM.
evol_quality = EvolQuality(
llm=InferenceEndpointsLLM(
model_id="mistralai/Mistral-7B-Instruct-v0.2",
),
num_evolutions=2,
)
evol_quality.load()
result = next(
evol_quality.process(
[
{"instruction": "common instruction", "response": "a response"},
]
)
)
# result
# [
# {
# 'instruction': 'common instruction',
# 'response': 'a response',
# 'evolved_response': 'evolved response',
# 'model_name': '"mistralai/Mistral-7B-Instruct-v0.2"'
# }
# ]
引用
@misc{liu2024makesgooddataalignment,
title={What Makes Good Data for Alignment? A Comprehensive Study of Automatic Data Selection in Instruction Tuning},
author={Wei Liu and Weihao Zeng and Keqing He and Yong Jiang and Junxian He},
year={2024},
eprint={2312.15685},
archivePrefix={arXiv},
primaryClass={cs.CL},
url={https://arxiv.org/abs/2312.15685},
}
源代码位于 src/distilabel/steps/tasks/evol_quality/base.py
中
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 |
|
inputs
property
¶
任务的输入是 instruction
和 response
。
outputs
property
¶
任务的输出是 evolved_response/s
和 model_name
。
mutation_templates_names
property
¶
返回提供的 mutation_templates
枚举的名称,即键。
model_post_init(__context)
¶
覆盖此方法以在 __init__
和 model_construct
之后执行其他初始化。如果您想执行一些需要整个模型初始化的验证,这将非常有用。
源代码位于 src/distilabel/steps/tasks/evol_quality/base.py
中
format_input(input)
¶
输入被格式化为 ChatType
,假设指令是用户在对话中的首次互动。如果存在 system_prompt
,则将其添加为第一条消息。
源代码位于 src/distilabel/steps/tasks/evol_quality/base.py
中
format_output(responses)
¶
任务的输出是一个字典,其中包含:evolved_response
或 evolved_responses
,具体取决于 store_evolutions
的值为 False
还是 True
;以及最后的 model_name
。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
responses
|
Union[str, List[str]]
|
要包含在输出中的响应。 |
必需 |
返回
类型 | 描述 |
---|---|
Dict[str, Any]
|
如果 |
Dict[str, Any]
|
如果 |
源代码位于 src/distilabel/steps/tasks/evol_quality/base.py
中
_apply_random_mutation(instruction, response)
¶
应用从作为 mutation_templates
枚举一部分提供的突变中随机选择的突变,并在突变提示中返回提供的指令。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
instruction
|
str
|
要包含在突变提示中的指令。 |
必需 |
返回
类型 | 描述 |
---|---|
str
|
带有提供的指令的随机突变提示。 |
源代码位于 src/distilabel/steps/tasks/evol_quality/base.py
中
_evolve_reponses(inputs)
¶
进化作为任务输入一部分提供的指令。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
inputs
|
StepInput
|
包含任务输入的 Python 字典列表。 |
必需 |
返回
类型 | 描述 |
---|---|
List[List[str]]
|
一个列表,其中每个项目都是一个列表,其中包含最后一个进化后的指令(如果 |
Dict[str, Any]
|
|
源代码位于 src/distilabel/steps/tasks/evol_quality/base.py
中
process(inputs)
¶
处理任务的输入,并使用 LLM 生成输出。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
inputs
|
StepInput
|
包含任务输入的 Python 字典列表。 |
必需 |
返回
类型 | 描述 |
---|---|
StepOutput
|
包含任务输出的 Python 字典列表。 |
源代码位于 src/distilabel/steps/tasks/evol_quality/base.py
中
GenerateEmbeddings
¶
基类:Step
使用 LLM
的最后隐藏状态生成嵌入。
使用 LLM
的最后隐藏状态为文本输入生成嵌入,如论文“什么使对齐数据良好?指令调优中自动数据选择的综合研究”中所述。
属性
名称 | 类型 | 描述 |
---|---|---|
llm |
LLM
|
用于生成嵌入的 |
输入列
- text (
str
,List[Dict[str, str]]
): 要为其生成嵌入的输入文本或对话。
输出列
- embedding (
List[float]
): 输入文本或对话的嵌入。 - model_name (
str
): 用于生成嵌入的模型名称。
类别
- embedding
- llm
示例
对 LLM 候选对象进行排名
from distilabel.steps.tasks import GenerateEmbeddings
from distilabel.models.llms.huggingface import TransformersLLM
# Consider this as a placeholder for your actual LLM.
embedder = GenerateEmbeddings(
llm=TransformersLLM(
model="TaylorAI/bge-micro-v2",
model_kwargs={"is_decoder": True},
cuda_devices=[],
)
)
embedder.load()
result = next(
embedder.process(
[
{"text": "Hello, how are you?"},
]
)
)
引用
@misc{liu2024makesgooddataalignment,
title={What Makes Good Data for Alignment? A Comprehensive Study of Automatic Data Selection in Instruction Tuning},
author={Wei Liu and Weihao Zeng and Keqing He and Yong Jiang and Junxian He},
year={2024},
eprint={2312.15685},
archivePrefix={arXiv},
primaryClass={cs.CL},
url={https://arxiv.org/abs/2312.15685},
}
源代码位于 src/distilabel/steps/tasks/generate_embeddings.py
中
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 |
|
inputs
property
¶
任务的输入是一个 text
列,其中包含字符串或 OpenAI 类聊天格式的字典列表。
outputs
property
¶
任务的输出是一个 embedding
列,其中包含 text
输入的嵌入。
load()
¶
format_input(input)
¶
格式化输入以供 LLM 用于生成嵌入。输入可以是 ChatType
格式或字符串。如果是字符串,则将其转换为 OpenAI 类聊天格式的字典列表。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
input
|
Dict[str, Any]
|
要格式化的输入。 |
必需 |
返回
类型 | 描述 |
---|---|
ChatType
|
输入的 OpenAI 类聊天格式。 |
源代码位于 src/distilabel/steps/tasks/generate_embeddings.py
中
process(inputs)
¶
使用 LLM
的最后隐藏状态为每个输入生成嵌入。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
inputs
|
StepInput
|
包含任务输入的 Python 字典列表。 |
必需 |
产生
类型 | 描述 |
---|---|
StepOutput
|
包含任务输出的 Python 字典列表。 |
源代码位于 src/distilabel/steps/tasks/generate_embeddings.py
中
Genstruct
¶
基类:Task
使用 LLM
从文档中生成指令-响应对。
Genstruct
是一个预定义的任务,旨在从给定的原始文档(包含标题和内容)中生成有效的指令,从而能够从任何原始文本语料库中创建新的、部分合成的指令微调数据集。此任务基于 Nous Research 的 Genstruct 7B 模型,该模型灵感来源于 Ada-Instruct 论文。
注意
Genstruct 提示,即任务本身,实际上可以与任何模型一起使用,但最安全/推荐的选择是使用 NousResearch/Genstruct-7B
作为提供给任务的 LLM,因为它专门为这个特定任务而训练。
属性
名称 | 类型 | 描述 |
---|---|---|
_template |
Union[Template, None]
|
用于格式化 LLM 输入的 Jinja2 模板。 |
输入列
- title (
str
): 文档的标题。 - content (
str
): 文档的内容。
输出列
- user (
str
): 用户基于文档的指令。 - assistant (
str
): 助手基于用户指令的回复。 - model_name (
str
): 用于生成feedback
和result
的模型名称。
类别
- 文本生成
- instruction
- response
参考
示例
使用标题和内容从原始文档生成指令
from distilabel.steps.tasks import Genstruct
from distilabel.models import InferenceEndpointsLLM
# Consider this as a placeholder for your actual LLM.
genstruct = Genstruct(
llm=InferenceEndpointsLLM(
model_id="NousResearch/Genstruct-7B",
),
)
genstruct.load()
result = next(
genstruct.process(
[
{"title": "common instruction", "content": "content of the document"},
]
)
)
# result
# [
# {
# 'title': 'An instruction',
# 'content': 'content of the document',
# 'model_name': 'test',
# 'user': 'An instruction',
# 'assistant': 'content of the document',
# }
# ]
引用
源代码位于 src/distilabel/steps/tasks/genstruct.py
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 |
|
inputs
property
¶
任务的输入是 title
和 content
。
outputs
property
¶
任务的输出是基于提供的文档的 user
指令和基于用户指令的 assistant
回复。
load()
¶
加载 Jinja2 模板。
源代码位于 src/distilabel/steps/tasks/genstruct.py
format_input(input)
¶
输入被格式化为 ChatType
,假设指令是用户在对话中的首次互动。
源代码位于 src/distilabel/steps/tasks/genstruct.py
format_output(output, input)
¶
输出被格式化,以便用户和助手的消息都被捕获。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
output
|
Union[str, None]
|
LLM 的原始输出。 |
必需 |
input
|
Dict[str, Any]
|
任务的输入。用于获取响应数量。 |
必需 |
返回
类型 | 描述 |
---|---|
Dict[str, Any]
|
一个字典,包含键 |
源代码位于 src/distilabel/steps/tasks/genstruct.py
ImageGeneration
¶
Bases: ImageTask
使用图像到文本模型根据提示生成图像。
ImageGeneration
是一个预定义的任务,允许从提示生成图像。它适用于 distilabel.models.image_generation
下定义的任何 image_generation
,即已实现的允许图像生成的模型。默认情况下,图像以 base64 字符串格式生成,在数据集生成后,可以使用 Distiset.transform_columns_to_image
将图像自动转换为 PIL.Image.Image
。请查看文档中 Image Generation with distilabel
示例以获取更多信息。使用 save_artifacts
属性,可以将图像保存在 hugging face hub 存储库的 artifacts 文件夹中。
属性
名称 | 类型 | 描述 |
---|---|---|
save_artifacts |
bool
|
布尔值,用于将图像 artifacts 保存在其文件夹中。否则,图像的 base64 表示将作为字符串保存。默认为 False。 |
image_format |
str
|
PIL 支持的任何格式。默认为 |
输入列
- prompt (str): 列名为 prompt 的列,包含生成图像的提示。
输出列
- image (
str
): 生成的图像。最初是一个 base64 字符串,以便在管道运行期间保持简单,但在管道结束时返回 distiset 后,可以通过调用distiset.transform_columns_to_image(<IMAGE_COLUMN>)
将其转换为 Image 对象。 - image_path (
str
): 图像保存的路径。仅当save_artifacts
为 True 时可用。 - model_name (
str
): 用于生成图像的模型的名称。
类别
- image-generation
示例
从提示生成图像
from distilabel.steps.tasks import ImageGeneration
from distilabel.models.image_generation import InferenceEndpointsImageGeneration
igm = InferenceEndpointsImageGeneration(
model_id="black-forest-labs/FLUX.1-schnell"
)
# save_artifacts=True by default in JPEG format, if set to False, the image will be saved as a string.
image_gen = ImageGeneration(image_generation_model=igm)
image_gen.load()
result = next(
image_gen.process(
[{"prompt": "a white siamese cat"}]
)
)
生成图像并将其作为 artifacts 保存在 Hugging Face Hub 存储库中
from distilabel.steps.tasks import ImageGeneration
# Select the Image Generation model to use
from distilabel.models.image_generation import OpenAIImageGeneration
igm = OpenAIImageGeneration(
model="dall-e-3",
api_key="api.key",
generation_kwargs={
"size": "1024x1024",
"quality": "standard",
"style": "natural"
}
)
# save_artifacts=True by default in JPEG format, if set to False, the image will be saved as a string.
image_gen = ImageGeneration(
image_generation_model=igm,
save_artifacts=True,
image_format="JPEG" # By default will use JPEG, the options available can be seen in PIL documentation.
)
image_gen.load()
result = next(
image_gen.process(
[{"prompt": "a white siamese cat"}]
)
)
源代码位于 src/distilabel/steps/tasks/image_generation.py
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 |
|
BitextRetrievalGenerator
¶
Bases: _EmbeddingDataGenerator
使用 LLM
生成双语文本检索数据,以便稍后训练嵌入模型。
BitextRetrievalGenerator
是一个 GeneratorTask
,它使用 LLM
生成双语文本检索数据,以便稍后训练嵌入模型。此任务基于论文 "Improving Text Embeddings with Large Language Models",数据根据提供的属性生成,如果未提供,则随机抽样。
属性
名称 | 类型 | 描述 |
---|---|---|
source_language |
str
|
要生成的数据的源语言,可以是 https://aclanthology.org/2020.acl-main.747.pdf 附录 A 中 XLM-R 列表中检索到的任何语言。 |
target_language |
str
|
要生成的数据的目标语言,可以是 https://aclanthology.org/2020.acl-main.747.pdf 附录 A 中 XLM-R 列表中检索到的任何语言。 |
unit |
Optional[Literal['sentence', 'phrase', 'passage']]
|
要生成的数据的单元,可以是 |
difficulty |
Optional[Literal['elementary school', 'high school', 'college']]
|
要生成的查询的难度,可以是 |
high_score |
Optional[Literal['4', '4.5', '5']]
|
要生成的查询的高分,可以是 |
low_score |
Optional[Literal['2.5', '3', '3.5']]
|
要生成的查询的低分,可以是 |
seed |
int
|
随机种子,用于在 |
输出列
- S1 (
str
):LLM
生成的第一个句子。 - S2 (
str
):LLM
生成的第二个句子。 - S3 (
str
):LLM
生成的第三个句子。 - model_name (
str
): 用于生成双语文本检索数据的模型的名称。
示例
生成双语文本检索数据以训练嵌入模型
from distilabel.pipeline import Pipeline
from distilabel.steps.tasks import BitextRetrievalGenerator
with Pipeline("my-pipeline") as pipeline:
task = BitextRetrievalGenerator(
source_language="English",
target_language="Spanish",
unit="sentence",
difficulty="elementary school",
high_score="4",
low_score="2.5",
llm=...,
)
...
task >> ...
源代码位于 src/distilabel/steps/tasks/improving_text_embeddings.py
916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 |
|
GenerateLongTextMatchingData
¶
Bases: _EmbeddingDataGeneration
使用 LLM
生成长文本匹配数据,以便稍后训练嵌入模型。
GenerateLongTextMatchingData
是一个 Task
,它使用 LLM
生成长文本匹配数据,以便稍后训练嵌入模型。此任务基于论文 "Improving Text Embeddings with Large Language Models",数据根据提供的属性生成,如果未提供,则随机抽样。
注意
理想情况下,此任务应与 EmbeddingTaskGenerator
和 flatten_tasks=True
以及 category="text-matching-long"
一起使用;以便 LLM
生成一个任务列表,该列表被展平,以便每行包含一个用于 text-matching-long 类别的任务。
属性
名称 | 类型 | 描述 |
---|---|---|
language |
str
|
要生成的数据的语言,可以是 https://aclanthology.org/2020.acl-main.747.pdf 附录 A 中 XLM-R 列表中检索到的任何语言。 |
seed |
int
|
随机种子,用于在 |
输入列
- task (
str
): 要在生成中使用的任务描述。
输出列
- input (
str
): 由LLM
生成的输入。 - positive_document (
str
): 由LLM
生成的正向文档。 - model_name (
str
): 用于生成长文本匹配数据的模型的名称。
示例
生成用于训练嵌入模型的合成长文本匹配数据
from distilabel.pipeline import Pipeline
from distilabel.steps.tasks import EmbeddingTaskGenerator, GenerateLongTextMatchingData
with Pipeline("my-pipeline") as pipeline:
task = EmbeddingTaskGenerator(
category="text-matching-long",
flatten_tasks=True,
llm=..., # LLM instance
)
generate = GenerateLongTextMatchingData(
language="English",
llm=..., # LLM instance
)
task >> generate
源代码位于 src/distilabel/steps/tasks/improving_text_embeddings.py
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 |
|
keys
property
¶
包含将从 LLM
输出解析到 Python 字典中的 keys
。
format_input(input)
¶
基于 task
和提供的属性格式化输入的方法,或者如果未提供,则仅随机抽样这些属性。此方法将使用提供的参数渲染 _template
,并返回 OpenAI 格式的聊天,即 ChatType
,假设只有一个回合,来自用户,内容是渲染后的 _template
。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
input
|
Dict[str, Any]
|
包含要在 |
必需 |
返回
类型 | 描述 |
---|---|
ChatType
|
包含用户消息的单个聊天的列表,其中用户消息包含渲染后的 |
源代码位于 src/distilabel/steps/tasks/improving_text_embeddings.py
GenerateShortTextMatchingData
¶
Bases: _EmbeddingDataGeneration
使用 LLM
生成短文本匹配数据,以便稍后训练嵌入模型。
GenerateShortTextMatchingData
是一个 Task
,它使用 LLM
生成短文本匹配数据,以便稍后训练嵌入模型。此任务基于论文 "Improving Text Embeddings with Large Language Models",数据根据提供的属性生成,如果未提供,则随机抽样。
注意
理想情况下,此任务应与 EmbeddingTaskGenerator
和 flatten_tasks=True
以及 category="text-matching-short"
一起使用;以便 LLM
生成一个任务列表,该列表被展平,以便每行包含一个用于 text-matching-short 类别的任务。
属性
名称 | 类型 | 描述 |
---|---|---|
language |
str
|
要生成的数据的语言,可以是 https://aclanthology.org/2020.acl-main.747.pdf 附录 A 中 XLM-R 列表中检索到的任何语言。 |
seed |
int
|
随机种子,用于在 |
输入列
- task (
str
): 要在生成中使用的任务描述。
输出列
- input (
str
): 由LLM
生成的输入。 - positive_document (
str
): 由LLM
生成的正向文档。 - model_name (
str
): 用于生成短文本匹配数据的模型的名称。
示例
生成用于训练嵌入模型的合成短文本匹配数据
from distilabel.pipeline import Pipeline
from distilabel.steps.tasks import EmbeddingTaskGenerator, GenerateShortTextMatchingData
with Pipeline("my-pipeline") as pipeline:
task = EmbeddingTaskGenerator(
category="text-matching-short",
flatten_tasks=True,
llm=..., # LLM instance
)
generate = GenerateShortTextMatchingData(
language="English",
llm=..., # LLM instance
)
task >> generate
源代码位于 src/distilabel/steps/tasks/improving_text_embeddings.py
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 |
|
keys
property
¶
包含将从 LLM
输出解析到 Python 字典中的 keys
。
format_input(input)
¶
基于 task
和提供的属性格式化输入的方法,或者如果未提供,则仅随机抽样这些属性。此方法将使用提供的参数渲染 _template
,并返回 OpenAI 格式的聊天,即 ChatType
,假设只有一个回合,来自用户,内容是渲染后的 _template
。
Args:
input: The input dictionary containing the `task` to be used in the `_template`.
Returns:
A list with a single chat containing the user's message with the rendered `_template`.
源代码位于 src/distilabel/steps/tasks/improving_text_embeddings.py
GenerateTextClassificationData
¶
Bases: _EmbeddingDataGeneration
使用 LLM
生成文本分类数据,以便稍后训练嵌入模型。
GenerateTextClassificationData
是一个 Task
,它使用 LLM
生成文本分类数据,以便稍后训练嵌入模型。此任务基于论文 "Improving Text Embeddings with Large Language Models",数据根据提供的属性生成,如果未提供,则随机抽样。
注意
理想情况下,此任务应与 EmbeddingTaskGenerator
和 flatten_tasks=True
以及 category="text-classification"
一起使用;以便 LLM
生成一个任务列表,该列表被展平,以便每行包含一个用于 text-classification 类别的任务。
属性
名称 | 类型 | 描述 |
---|---|---|
language |
str
|
要生成的数据的语言,可以是 https://aclanthology.org/2020.acl-main.747.pdf 附录 A 中 XLM-R 列表中检索到的任何语言。 |
difficulty |
Optional[Literal['high school', 'college', 'PhD']]
|
要生成的查询的难度,可以是 |
clarity |
Optional[Literal['clear', 'understandable with some effort', 'ambiguous']]
|
要生成的查询的清晰度,可以是 |
seed |
int
|
随机种子,用于在 |
输入列
- task (
str
): 要在生成中使用的任务描述。
输出列
- input_text (
str
): 由LLM
生成的输入文本。 - label (
str
): 由LLM
生成的标签。 - misleading_label (
str
): 由LLM
生成的误导性标签。 - model_name (
str
): 用于生成文本分类数据的模型的名称。
示例
生成用于训练嵌入模型的合成文本分类数据
from distilabel.pipeline import Pipeline
from distilabel.steps.tasks import EmbeddingTaskGenerator, GenerateTextClassificationData
with Pipeline("my-pipeline") as pipeline:
task = EmbeddingTaskGenerator(
category="text-classification",
flatten_tasks=True,
llm=..., # LLM instance
)
generate = GenerateTextClassificationData(
language="English",
difficulty="high school",
clarity="clear",
llm=..., # LLM instance
)
task >> generate
源代码位于 src/distilabel/steps/tasks/improving_text_embeddings.py
720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 |
|
keys
property
¶
包含将从 LLM
输出解析到 Python 字典中的 keys
。
format_input(input)
¶
基于 task
和提供的属性格式化输入的方法,或者如果未提供,则仅随机抽样这些属性。此方法将使用提供的参数渲染 _template
,并返回 OpenAI 格式的聊天,即 ChatType
,假设只有一个回合,来自用户,内容是渲染后的 _template
。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
input
|
Dict[str, Any]
|
包含要在 |
必需 |
返回
类型 | 描述 |
---|---|
ChatType
|
包含用户消息的单个聊天的列表,其中用户消息包含渲染后的 |
源代码位于 src/distilabel/steps/tasks/improving_text_embeddings.py
GenerateTextRetrievalData
¶
Bases: _EmbeddingDataGeneration
使用 LLM
生成文本检索数据,以便稍后训练嵌入模型。
GenerateTextRetrievalData
是一个 Task
,它使用 LLM
生成文本检索数据,以便稍后训练嵌入模型。此任务基于论文 "Improving Text Embeddings with Large Language Models",数据根据提供的属性生成,如果未提供,则随机抽样。
注意
理想情况下,此任务应与 EmbeddingTaskGenerator
和 flatten_tasks=True
以及 category="text-retrieval"
一起使用;以便 LLM
生成一个任务列表,该列表被展平,以便每行包含一个用于 text-retrieval 类别的任务。
属性
名称 | 类型 | 描述 |
---|---|---|
language |
str
|
要生成的数据的语言,可以是 https://aclanthology.org/2020.acl-main.747.pdf 附录 A 中 XLM-R 列表中检索到的任何语言。 |
query_type |
Optional[Literal['extremely long-tail', 'long-tail', 'common']]
|
要生成的查询的类型,可以是 |
query_length |
Optional[Literal['less than 5 words', '5 to 15 words', 'at least 10 words']]
|
要生成的查询的长度,可以是 |
difficulty |
Optional[Literal['high school', 'college', 'PhD']]
|
要生成的查询的难度,可以是 |
clarity |
Optional[Literal['clear', 'understandable with some effort', 'ambiguous']]
|
要生成的查询的清晰度,可以是 |
num_words |
Optional[Literal[50, 100, 200, 300, 400, 500]]
|
要生成的查询中的单词数,可以是 |
seed |
int
|
随机种子,用于在 |
输入列
- task (
str
): 要在生成中使用的任务描述。
输出列
- user_query (
str
): 由LLM
生成的用户查询。 - positive_document (
str
): 由LLM
生成的正向文档。 - hard_negative_document (
str
): 由LLM
生成的困难负例文档。 - model_name (
str
): 用于生成文本检索数据的模型的名称。
示例
生成用于训练嵌入模型的合成文本检索数据
from distilabel.pipeline import Pipeline
from distilabel.steps.tasks import EmbeddingTaskGenerator, GenerateTextRetrievalData
with Pipeline("my-pipeline") as pipeline:
task = EmbeddingTaskGenerator(
category="text-retrieval",
flatten_tasks=True,
llm=..., # LLM instance
)
generate = GenerateTextRetrievalData(
language="English",
query_type="common",
query_length="5 to 15 words",
difficulty="high school",
clarity="clear",
num_words=100,
llm=..., # LLM instance
)
task >> generate
源代码位于 src/distilabel/steps/tasks/improving_text_embeddings.py
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 |
|
keys
property
¶
包含将从 LLM
输出解析到 Python 字典中的 keys
。
format_input(input)
¶
基于 task
和提供的属性格式化输入的方法,或者如果未提供,则仅随机抽样这些属性。此方法将使用提供的参数渲染 _template
,并返回 OpenAI 格式的聊天,即 ChatType
,假设只有一个回合,来自用户,内容是渲染后的 _template
。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
input
|
Dict[str, Any]
|
包含要在 |
必需 |
返回
类型 | 描述 |
---|---|
ChatType
|
包含用户消息的单个聊天的列表,其中用户消息包含渲染后的 |
源代码位于 src/distilabel/steps/tasks/improving_text_embeddings.py
MonolingualTripletGenerator
¶
Bases: _EmbeddingDataGenerator
使用 LLM
生成单语三元组,以便稍后训练嵌入模型。
MonolingualTripletGenerator
是一个 GeneratorTask
,它使用 LLM
生成单语三元组,以便稍后训练嵌入模型。此任务基于论文 "Improving Text Embeddings with Large Language Models",数据根据提供的属性生成,如果未提供,则随机抽样。
属性
名称 | 类型 | 描述 |
---|---|---|
language |
str
|
要生成的数据的语言,可以是 https://aclanthology.org/2020.acl-main.747.pdf 附录 A 中 XLM-R 列表中检索到的任何语言。 |
unit |
Optional[Literal['sentence', 'phrase', 'passage']]
|
要生成的数据的单元,可以是 |
difficulty |
Optional[Literal['elementary school', 'high school', 'college']]
|
要生成的查询的难度,可以是 |
high_score |
Optional[Literal['4', '4.5', '5']]
|
要生成的查询的高分,可以是 |
low_score |
Optional[Literal['2.5', '3', '3.5']]
|
要生成的查询的低分,可以是 |
seed |
int
|
随机种子,用于在 |
输出列
- S1 (
str
):LLM
生成的第一个句子。 - S2 (
str
):LLM
生成的第二个句子。 - S3 (
str
):LLM
生成的第三个句子。 - model_name (
str
): 用于生成单语三元组的模型的名称。
示例
生成用于训练嵌入模型的单语三元组
from distilabel.pipeline import Pipeline
from distilabel.steps.tasks import MonolingualTripletGenerator
with Pipeline("my-pipeline") as pipeline:
task = MonolingualTripletGenerator(
language="English",
unit="sentence",
difficulty="elementary school",
high_score="4",
low_score="2.5",
llm=...,
)
...
task >> ...
源代码位于 src/distilabel/steps/tasks/improving_text_embeddings.py
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 |
|
InstructionBacktranslation
¶
基类:Task
使用指令回译进行自我对齐。
属性
名称 | 类型 | 描述 |
---|---|---|
_template |
Optional[Template]
|
用于指令回译任务的 Jinja2 模板。 |
输入列
- instruction (
str
): 用于评估文本输出的参考指令。 - generation (
str
): 要根据给定指令评估的文本输出。
输出列
- score (
str
): 基于给定指令的生成结果的分数。 - reason (
str
): 提供分数的理由。 - model_name (
str
): 用于对生成结果进行评分的模型名称。
类别
- critique
参考
示例
为给定的指令和生成结果生成分数和理由
from distilabel.steps.tasks import InstructionBacktranslation
instruction_backtranslation = InstructionBacktranslation(
name="instruction_backtranslation",
llm=llm,
input_batch_size=10,
output_mappings={"model_name": "scoring_model"},
)
instruction_backtranslation.load()
result = next(
instruction_backtranslation.process(
[
{
"instruction": "How much is 2+2?",
"generation": "4",
}
]
)
)
# result
# [
# {
# "instruction": "How much is 2+2?",
# "generation": "4",
# "score": 3,
# "reason": "Reason for the generation.",
# "model_name": "meta-llama/Meta-Llama-3.1-8B-Instruct",
# }
# ]
引用
@misc{li2024selfalignmentinstructionbacktranslation,
title={Self-Alignment with Instruction Backtranslation},
author={Xian Li and Ping Yu and Chunting Zhou and Timo Schick and Omer Levy and Luke Zettlemoyer and Jason Weston and Mike Lewis},
year={2024},
eprint={2308.06259},
archivePrefix={arXiv},
primaryClass={cs.CL},
url={https://arxiv.org/abs/2308.06259},
}
源代码位于 src/distilabel/steps/tasks/instruction_backtranslation.py
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 |
|
inputs
property
¶
任务的输入是 instruction
和针对它的 generation
。
outputs
property
¶
任务的输出是 score
、reason
和 model_name
。
load()
¶
加载 Jinja2 模板。
源代码位于 src/distilabel/steps/tasks/instruction_backtranslation.py
format_input(input)
¶
输入被格式化为 ChatType
,假设指令是用户在对话中的首次互动。
源代码位于 src/distilabel/steps/tasks/instruction_backtranslation.py
format_output(output, input)
¶
输出被格式化为包含 score
和 reason
的字典。model_name
将自动包含在 Task
的 process
方法中。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
output
|
Union[str, None]
|
一个字符串,表示通过 |
必需 |
input
|
Dict[str, Any]
|
任务的输入,某些任务需要输入以格式化输出。 |
必需 |
返回
类型 | 描述 |
---|---|
Dict[str, Any]
|
一个字典,包含 |
源代码位于 src/distilabel/steps/tasks/instruction_backtranslation.py
Magpie
¶
Bases: Task
, MagpieBase
使用指令微调的 LLM 生成对话。
Magpie 是一种简洁的方法,它允许在没有种子数据或特定系统提示的情况下生成用户指令,这得益于指令微调的 LLM 的自回归能力。由于它们是使用由用户消息和期望的助手输出组成的聊天模板进行微调的,因此指令微调的 LLM 学习到在预查询或预指令标记之后是指令。如果将这些预查询标记发送到 LLM 而没有任何用户消息,则 LLM 将继续生成标记,就像它是用户一样。这个技巧允许从指令微调的 LLM 中“提取”指令。在此指令生成后,它可以再次发送到 LLM 以生成本次的助手回复。此过程可以重复 N 次,从而构建多轮对话。此方法在论文“Magpie: Alignment Data Synthesis from Scratch by Prompting Aligned LLMs with Nothing”中描述。
属性
名称 | 类型 | 描述 |
---|---|---|
n_turns |
RuntimeParameter[PositiveInt]
|
生成的对话将具有的回合数。默认为 |
end_with_user |
RuntimeParameter[bool]
|
对话是否应以用户消息结束。默认为 |
include_system_prompt |
RuntimeParameter[bool]
|
是否包含在生成的对话中使用的系统提示。默认为 |
only_instruction |
RuntimeParameter[bool]
|
是否仅生成指令。如果此参数为 |
system_prompt |
Optional[RuntimeParameter[Union[List[str], Dict[str, str], Dict[str, Tuple[str, float]], str]]]
|
可选的系统提示,或系统提示列表(将从中随机选择一个),或系统提示字典(将从中随机选择一个),或系统提示字典及其被选择的概率。随机系统提示将按每个输入/输出批次选择。此系统提示可用于指导指令 LLM 的生成,并引导其生成特定主题的指令。默认为 |
运行时参数
n_turns
: 生成的对话将具有的回合数。默认为1
。end_with_user
: 对话是否应以用户消息结束。默认为False
。include_system_prompt
: 是否包含在生成的对话中使用的系统提示。默认为False
。only_instruction
: 是否仅生成指令。如果此参数为True
,则将忽略n_turns
。默认为False
。system_prompt
: 可选的系统提示或系统提示列表,可用于引导 LLM 生成特定主题的内容、指导风格等。如果是系统提示列表,则将为每个输入/输出批次选择一个随机系统提示。如果提供的输入包含system_prompt
列,则将忽略此运行时参数,而使用该列中的参数。默认为None
。system_prompt
: 可选的系统提示,或系统提示列表(将从中随机选择一个),或系统提示字典(将从中随机选择一个),或系统提示字典及其被选择的概率。随机系统提示将按每个输入/输出批次选择。此系统提示可用于指导指令 LLM 的生成,并引导其生成特定主题的指令。
输入列
- system_prompt (
str
, optional): 可选的系统提示,可以提供该提示来指导指令 LLM 的生成,并引导其生成特定主题的指令。
输出列
- conversation (
ChatType
): 生成的对话,它是包含角色和消息的聊天项列表。仅当only_instruction=False
时。 - instruction (
str
): 生成的指令,如果only_instruction=True
或n_turns==1
。 - response (
str
): 生成的回复,如果n_turns==1
。 - system_prompt_key (
str
, optional): 用于生成对话或指令的系统提示的键。仅当system_prompt
是字典时。 - model_name (
str
): 用于生成conversation
或instruction
的模型名称。
类别
- 文本生成
- instruction
示例
使用 Llama 3 8B Instruct 和 TransformersLLM 生成指令
from distilabel.models import TransformersLLM
from distilabel.steps.tasks import Magpie
magpie = Magpie(
llm=TransformersLLM(
model="meta-llama/Meta-Llama-3-8B-Instruct",
magpie_pre_query_template="llama3",
generation_kwargs={
"temperature": 1.0,
"max_new_tokens": 64,
},
device="mps",
),
only_instruction=True,
)
magpie.load()
result = next(
magpie.process(
inputs=[
{
"system_prompt": "You're a math expert AI assistant that helps students of secondary school to solve calculus problems."
},
{
"system_prompt": "You're an expert florist AI assistant that helps user to erradicate pests in their crops."
},
]
)
)
# [
# {'instruction': "That's me! I'd love some help with solving calculus problems! What kind of calculation are you most effective at? Linear Algebra, derivatives, integrals, optimization?"},
# {'instruction': 'I was wondering if there are certain flowers and plants that can be used for pest control?'}
# ]
使用 Llama 3 8B Instruct 和 TransformersLLM 生成对话
from distilabel.models import TransformersLLM
from distilabel.steps.tasks import Magpie
magpie = Magpie(
llm=TransformersLLM(
model="meta-llama/Meta-Llama-3-8B-Instruct",
magpie_pre_query_template="llama3",
generation_kwargs={
"temperature": 1.0,
"max_new_tokens": 256,
},
device="mps",
),
n_turns=2,
)
magpie.load()
result = next(
magpie.process(
inputs=[
{
"system_prompt": "You're a math expert AI assistant that helps students of secondary school to solve calculus problems."
},
{
"system_prompt": "You're an expert florist AI assistant that helps user to erradicate pests in their crops."
},
]
)
)
# [
# {
# 'conversation': [
# {'role': 'system', 'content': "You're a math expert AI assistant that helps students of secondary school to solve calculus problems."},
# {
# 'role': 'user',
# 'content': 'I'm having trouble solving the limits of functions in calculus. Could you explain how to work with them? Limits of functions are denoted by lim x→a f(x) or lim x→a [f(x)]. It is read as "the limit as x approaches a of f
# of x".'
# },
# {
# 'role': 'assistant',
# 'content': 'Limits are indeed a fundamental concept in calculus, and understanding them can be a bit tricky at first, but don't worry, I'm here to help! The notation lim x→a f(x) indeed means "the limit as x approaches a of f of
# x". What it's asking us to do is find the'
# }
# ]
# },
# {
# 'conversation': [
# {'role': 'system', 'content': "You're an expert florist AI assistant that helps user to erradicate pests in their crops."},
# {
# 'role': 'user',
# 'content': "As a flower shop owner, I'm noticing some unusual worm-like creatures causing damage to my roses and other flowers. Can you help me identify what the problem is? Based on your expertise as a florist AI assistant, I think it
# might be pests or diseases, but I'm not sure which."
# },
# {
# 'role': 'assistant',
# 'content': "I'd be delighted to help you investigate the issue! Since you've noticed worm-like creatures damaging your roses and other flowers, I'll take a closer look at the possibilities. Here are a few potential culprits: 1.
# **Aphids**: These small, soft-bodied insects can secrete a sticky substance called"
# }
# ]
# }
# ]
源代码位于 src/distilabel/steps/tasks/magpie/base.py
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 |
|
outputs
property
¶
生成的多轮对话或指令。
model_post_init(__context)
¶
检查提供的 LLM
是否使用了 MagpieChatTemplateMixin
。
源代码位于 src/distilabel/steps/tasks/magpie/base.py
format_input(input)
¶
format_output(output, input=None)
¶
process(inputs)
¶
生成指定轮数的指令或对话列表。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
inputs
|
StepInput
|
可以包含 |
必需 |
产生
类型 | 描述 |
---|---|
StepOutput
|
生成的对话列表。 |
源代码位于 src/distilabel/steps/tasks/magpie/base.py
MagpieGenerator
¶
基类: GeneratorTask
, MagpieBase
生成器任务,使用 Magpie 生成指令或对话。
Magpie 是一种简洁的方法,它允许在没有种子数据或特定系统提示的情况下生成用户指令,这归功于指令微调的 LLM 的自回归能力。由于它们是使用由用户消息和期望的助手输出组成的聊天模板进行微调的,因此指令微调的 LLM 了解到在预查询或预指令令牌之后会跟着一个指令。如果将这些预查询令牌发送到 LLM 而不发送任何用户消息,则 LLM 将继续生成令牌,就像它是用户一样。这个技巧允许从指令微调的 LLM 中“提取”指令。在生成此指令后,可以再次将其发送到 LLM 以生成助手响应。这个过程可以重复 N 次,从而构建多轮对话。这种方法在论文“Magpie: Alignment Data Synthesis from Scratch by Prompting Aligned LLMs with Nothing”中进行了描述。
属性
名称 | 类型 | 描述 |
---|---|---|
n_turns |
RuntimeParameter[PositiveInt]
|
生成的对话将具有的回合数。默认为 |
end_with_user |
RuntimeParameter[bool]
|
对话是否应以用户消息结束。默认为 |
include_system_prompt |
RuntimeParameter[bool]
|
是否包含在生成的对话中使用的系统提示。默认为 |
only_instruction |
RuntimeParameter[bool]
|
是否仅生成指令。如果此参数为 |
system_prompt |
Optional[RuntimeParameter[Union[List[str], Dict[str, str], Dict[str, Tuple[str, float]], str]]]
|
可选的系统提示,或系统提示列表(将从中随机选择一个),或系统提示字典(将从中随机选择一个),或系统提示字典及其被选择的概率。随机系统提示将按每个输入/输出批次选择。此系统提示可用于指导指令 LLM 的生成,并引导其生成特定主题的指令。默认为 |
num_rows |
RuntimeParameter[int]
|
要生成的行数。 |
运行时参数
n_turns
: 生成的对话将具有的回合数。默认为1
。end_with_user
: 对话是否应以用户消息结束。默认为False
。include_system_prompt
: 是否包含在生成的对话中使用的系统提示。默认为False
。only_instruction
: 是否仅生成指令。如果此参数为True
,则将忽略n_turns
。默认为False
。system_prompt
: 可选的系统提示,或系统提示列表(将从中随机选择一个),或系统提示字典(将从中随机选择一个),或系统提示字典及其被选择的概率。随机系统提示将按每个输入/输出批次选择。此系统提示可用于指导指令 LLM 的生成,并引导其生成特定主题的指令。num_rows
: 要生成的行数。
输出列
- conversation (
ChatType
): 生成的对话,这是一个聊天项列表,包含角色和消息。 - instruction (
str
): 如果only_instruction=True
,则为生成的指令。 - response (
str
): 生成的回复,如果n_turns==1
。 - system_prompt_key (
str
, optional): 用于生成对话或指令的系统提示的键。仅当system_prompt
是字典时。 - model_name (
str
): 用于生成conversation
或instruction
的模型名称。
类别
- 文本生成
- instruction
- generator
示例
使用 Llama 3 8B Instruct 和 TransformersLLM 生成指令
from distilabel.models import TransformersLLM
from distilabel.steps.tasks import MagpieGenerator
generator = MagpieGenerator(
llm=TransformersLLM(
model="meta-llama/Meta-Llama-3-8B-Instruct",
magpie_pre_query_template="llama3",
generation_kwargs={
"temperature": 1.0,
"max_new_tokens": 256,
},
device="mps",
),
only_instruction=True,
num_rows=5,
)
generator.load()
result = next(generator.process())
# (
# [
# {"instruction": "I've just bought a new phone and I're excited to start using it."},
# {"instruction": "What are the most common types of companies that use digital signage?"}
# ],
# True
# )
使用 Llama 3 8B Instruct 和 TransformersLLM 生成对话
from distilabel.models import TransformersLLM
from distilabel.steps.tasks import MagpieGenerator
generator = MagpieGenerator(
llm=TransformersLLM(
model="meta-llama/Meta-Llama-3-8B-Instruct",
magpie_pre_query_template="llama3",
generation_kwargs={
"temperature": 1.0,
"max_new_tokens": 64,
},
device="mps",
),
n_turns=3,
num_rows=5,
)
generator.load()
result = next(generator.process())
# (
# [
# {
# 'conversation': [
# {
# 'role': 'system',
# 'content': 'You are a helpful Al assistant. The user will engage in a multi−round conversation with you,asking initial questions and following up with additional related questions. Your goal is to provide thorough, relevant and
# insightful responses to help the user with their queries.'
# },
# {'role': 'user', 'content': "I'm considering starting a social media campaign for my small business and I're not sure where to start. Can you help?"},
# {
# 'role': 'assistant',
# 'content': "Exciting endeavor! Creating a social media campaign can be a great way to increase brand awareness, drive website traffic, and ultimately boost sales. I'd be happy to guide you through the process. To get started,
# let's break down the basics. First, we need to identify your goals and target audience. What do"
# },
# {
# 'role': 'user',
# 'content': "Before I start a social media campaign, what kind of costs ammol should I expect to pay? There are several factors that contribute to the total cost of running a social media campaign. Let me outline some of the main
# expenses you might encounter: 1. Time: As the business owner, you'll likely spend time creating"
# },
# {
# 'role': 'assistant',
# 'content': 'Time is indeed one of the biggest investments when it comes to running a social media campaign! Besides time, you may also incur costs associated with: 2. Content creation: You might need to hire freelancers or
# agencies to create high-quality content (images, videos, captions) for your social media platforms. 3. Advertising'
# }
# ]
# },
# {
# 'conversation': [
# {
# 'role': 'system',
# 'content': 'You are a helpful Al assistant. The user will engage in a multi−round conversation with you,asking initial questions and following up with additional related questions. Your goal is to provide thorough, relevant and
# insightful responses to help the user with their queries.'
# },
# {'role': 'user', 'content': "I am thinking of buying a new laptop or computer. What are some important factors I should consider when making your decision? I'll make sure to let you know if any other favorites or needs come up!"},
# {
# 'role': 'assistant',
# 'content': 'Exciting times ahead! When considering a new laptop or computer, there are several key factors to think about to ensure you find the right one for your needs. Here are some crucial ones to get you started: 1.
# **Purpose**: How will you use your laptop or computer? For work, gaming, video editing,'
# },
# {
# 'role': 'user',
# 'content': 'Let me stop you there. Let's explore this "purpose" factor that you mentioned earlier. Can you elaborate more on what type of devices would be suitable for different purposes? For example, if I're primarily using my
# laptop for general usage like browsing, email, and word processing, would a budget-friendly laptop be sufficient'
# },
# {
# 'role': 'assistant',
# 'content': "Understanding your purpose can greatly impact the type of device you'll need. **General Usage (Browsing, Email, Word Processing)**: For casual users who mainly use their laptop for daily tasks, a budget-friendly
# option can be sufficient. Look for laptops with: * Intel Core i3 or i5 processor* "
# }
# ]
# }
# ],
# True
# )
使用带有概率的系统提示生成
from distilabel.models import InferenceEndpointsLLM
from distilabel.steps.tasks import MagpieGenerator
magpie = MagpieGenerator(
llm=InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3-8B-Instruct",
tokenizer_id="meta-llama/Meta-Llama-3-8B-Instruct",
magpie_pre_query_template="llama3",
generation_kwargs={
"temperature": 0.8,
"max_new_tokens": 256,
},
),
n_turns=2,
system_prompt={
"math": ("You're an expert AI assistant.", 0.8),
"writing": ("You're an expert writing assistant.", 0.2),
},
)
magpie.load()
result = next(magpie.process())
引用
@misc{xu2024magpiealignmentdatasynthesis,
title={Magpie: Alignment Data Synthesis from Scratch by Prompting Aligned LLMs with Nothing},
author={Zhangchen Xu and Fengqing Jiang and Luyao Niu and Yuntian Deng and Radha Poovendran and Yejin Choi and Bill Yuchen Lin},
year={2024},
eprint={2406.08464},
archivePrefix={arXiv},
primaryClass={cs.CL},
url={https://arxiv.org/abs/2406.08464},
}
源代码位于 src/distilabel/steps/tasks/magpie/generator.py
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 |
|
outputs
property
¶
生成的多轮对话或指令。
model_post_init(__context)
¶
检查提供的 LLM
是否使用了 MagpieChatTemplateMixin
。
源代码位于 src/distilabel/steps/tasks/magpie/generator.py
format_output(output, input=None)
¶
process(offset=0)
¶
使用 Magpie 生成所需数量的指令或对话。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
offset
|
int
|
开始生成的偏移量。默认为 |
0
|
产生
类型 | 描述 |
---|---|
GeneratorStepOutput
|
生成的指令或对话。 |
源代码位于 src/distilabel/steps/tasks/magpie/generator.py
MathShepherdCompleter
¶
基类:Task
Math Shepherd 完成器和自动标注器任务。
此任务负责:给定指令的一系列解决方案和一个黄金解决方案作为参考,为这些解决方案生成补全,并使用参考论文图 2 中的硬估计方法(公式 3)根据黄金解决方案对它们进行标注。这些属性使该任务能够灵活地用于不同类型的数据集和 LLM,并允许利用不同的字段来修改其系统提示和用户提示。在修改它们之前,请查看当前的默认值,以确保补全生成正确。
属性
名称 | 类型 | 描述 |
---|---|---|
system_prompt |
Optional[str]
|
要在补全中使用的系统提示。默认的系统提示已经过检查,在使用 Llama 3.1 的 8B 和 70B 模型时生成了良好的补全,但可以对其进行修改以使其适应所选的模型和数据集。 |
extra_rules |
Optional[str]
|
此字段可用于插入与数据集类型相关的额外规则。例如,在原始论文中,他们使用了 GSM8K 和 MATH 数据集,此字段可用于插入 GSM8K 数据集的规则。 |
few_shots |
Optional[str]
|
少量示例,用于帮助模型生成补全,以您数据集所需的解决方案类型格式编写它们。 |
N |
PositiveInt
|
为每个步骤生成的补全数量,对应于论文中的 N。他们在论文中使用了 8,但可以进行调整。 |
tags |
list[str]
|
要在补全中使用的标签列表,默认标签为 ["+", "-"],与论文中相同,其中第一个用作正标签,第二个用作负标签。可以更新此列表,但它必须是一个包含 2 个元素的列表,其中第一个是正标签,第二个是负标签。 |
输入列
- instruction (
str
): 任务或指令。 - solutions (
List[str]
): 任务的解决方案列表。 - golden_solution (
str
): 任务的参考解决方案,将用于标注候选解决方案。
输出列
- solutions (
List[str]
): 与用作输入的列相同的列,“solutions”列已修改。 - model_name (
str
): 用于生成修订的模型名称。
类别
- 文本生成
- labelling
示例
使用结构化输出(首选方式)通过 Math Shepherd 完成器标注您的步骤
from distilabel.steps.tasks import MathShepherdCompleter
from distilabel.models import InferenceEndpointsLLM
llm=InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3.1-8B-Instruct",
tokenizer_id="meta-llama/Meta-Llama-3.1-8B-Instruct",
generation_kwargs={
"temperature": 0.6,
"max_new_tokens": 1024,
},
)
task = MathShepherdCompleter(
llm=llm,
N=3,
use_default_structured_output=True
)
task.load()
result = next(
task.process(
[
{
"instruction": "Janet’s ducks lay 16 eggs per day. She eats three for breakfast every morning and bakes muffins for her friends every day with four. She sells the remainder at the farmers' market daily for $2 per fresh duck egg. How much in dollars does she make every day at the farmers' market?",
"golden_solution": ["Step 1: Janet sells 16 - 3 - 4 = <<16-3-4=9>>9 duck eggs a day.", "Step 2: She makes 9 * 2 = $<<9*2=18>>18 every day at the farmer’s market.", "The answer is: 18"],
"solutions": [
["Step 1: Janet sells 16 - 3 - 4 = <<16-3-4=9>>9 duck eggs a day.", "Step 2: She makes 9 * 2 = $<<9*2=18>>18 every day at the farmer’s market.", "The answer is: 18"],
['Step 1: Janets ducks lay 16 eggs per day, and she uses 3 + 4 = <<3+4=7>>7 for eating and baking.', 'Step 2: So she sells 16 - 7 = <<16-7=9>>9 duck eggs every day.', 'Step 3: Those 9 eggs are worth 9 * $2 = $<<9*2=18>>18.', 'The answer is: 18'],
]
},
]
)
)
# [[{'instruction': "Janet’s ducks lay 16 eggs per day. She eats three for breakfast every morning and bakes muffins for her friends every day with four. She sells the remainder at the farmers' market daily for $2 per fresh duck egg. How much in dollars does she make every day at the farmers' market?",
# 'golden_solution': ["Step 1: Janet sells 16 - 3 - 4 = <<16-3-4=9>>9 duck eggs a day.", "Step 2: She makes 9 * 2 = $<<9*2=18>>18 every day at the farmer\u2019s market.", "The answer is: 18"],
# 'solutions': [["Step 1: Janet sells 16 - 3 - 4 = <<16-3-4=9>>9 duck eggs a day. -", "Step 2: She makes 9 * 2 = $<<9*2=18>>18 every day at the farmer\u2019s market.", "The answer is: 18"], ["Step 1: Janets ducks lay 16 eggs per day, and she uses 3 + 4 = <<3+4=7>>7 for eating and baking. +", "Step 2: So she sells 16 - 7 = <<16-7=9>>9 duck eggs every day. +", "Step 3: Those 9 eggs are worth 9 * $2 = $<<9*2=18>>18.", "The answer is: 18"]]}]]
使用 Math Shepherd 完成器标注您的步骤
from distilabel.steps.tasks import MathShepherdCompleter
from distilabel.models import InferenceEndpointsLLM
llm=InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3.1-8B-Instruct",
tokenizer_id="meta-llama/Meta-Llama-3.1-8B-Instruct",
generation_kwargs={
"temperature": 0.6,
"max_new_tokens": 1024,
},
)
task = MathShepherdCompleter(
llm=llm,
N=3
)
task.load()
result = next(
task.process(
[
{
"instruction": "Janet’s ducks lay 16 eggs per day. She eats three for breakfast every morning and bakes muffins for her friends every day with four. She sells the remainder at the farmers' market daily for $2 per fresh duck egg. How much in dollars does she make every day at the farmers' market?",
"golden_solution": ["Step 1: Janet sells 16 - 3 - 4 = <<16-3-4=9>>9 duck eggs a day.", "Step 2: She makes 9 * 2 = $<<9*2=18>>18 every day at the farmer’s market.", "The answer is: 18"],
"solutions": [
["Step 1: Janet sells 16 - 3 - 4 = <<16-3-4=9>>9 duck eggs a day.", "Step 2: She makes 9 * 2 = $<<9*2=18>>18 every day at the farmer’s market.", "The answer is: 18"],
['Step 1: Janets ducks lay 16 eggs per day, and she uses 3 + 4 = <<3+4=7>>7 for eating and baking.', 'Step 2: So she sells 16 - 7 = <<16-7=9>>9 duck eggs every day.', 'Step 3: Those 9 eggs are worth 9 * $2 = $<<9*2=18>>18.', 'The answer is: 18'],
]
},
]
)
)
# [[{'instruction': "Janet’s ducks lay 16 eggs per day. She eats three for breakfast every morning and bakes muffins for her friends every day with four. She sells the remainder at the farmers' market daily for $2 per fresh duck egg. How much in dollars does she make every day at the farmers' market?",
# 'golden_solution': ["Step 1: Janet sells 16 - 3 - 4 = <<16-3-4=9>>9 duck eggs a day.", "Step 2: She makes 9 * 2 = $<<9*2=18>>18 every day at the farmer\u2019s market.", "The answer is: 18"],
# 'solutions': [["Step 1: Janet sells 16 - 3 - 4 = <<16-3-4=9>>9 duck eggs a day. -", "Step 2: She makes 9 * 2 = $<<9*2=18>>18 every day at the farmer\u2019s market.", "The answer is: 18"], ["Step 1: Janets ducks lay 16 eggs per day, and she uses 3 + 4 = <<3+4=7>>7 for eating and baking. +", "Step 2: So she sells 16 - 7 = <<16-7=9>>9 duck eggs every day. +", "Step 3: Those 9 eggs are worth 9 * $2 = $<<9*2=18>>18.", "The answer is: 18"]]}]]
引用
```
@misc{wang2024mathshepherdverifyreinforcellms,
title={Math-Shepherd: Verify and Reinforce LLMs Step-by-step without Human Annotations},
author={Peiyi Wang and Lei Li and Zhihong Shao and R. X. Xu and Damai Dai and Yifei Li and Deli Chen and Y. Wu and Zhifang Sui},
year={2024},
eprint={2312.08935},
archivePrefix={arXiv},
primaryClass={cs.AI},
url={https://arxiv.org/abs/2312.08935},
}
```
源代码位于 src/distilabel/steps/tasks/math_shepherd/completer.py
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 |
|
format_output(output, input=None)
¶
process(inputs)
¶
执行解决方案的补全生成处理,并使用论文图 2 中的逻辑(硬估计(公式 (3)))标注每个步骤。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
inputs
|
StepInput
|
步骤的输入 |
必需 |
产生
类型 | 描述 |
---|---|
StepOutput
|
带有补全的已标注输入。 |
源代码位于 src/distilabel/steps/tasks/math_shepherd/completer.py
_prepare_completions(instruction, steps)
¶
辅助方法,用于创建给定解决方案(步骤列表)和指令的要由 LLM 完成的文本。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
instruction
|
str
|
问题的指令。 |
必需 |
steps
|
list[str]
|
作为解决方案一部分的步骤列表。 |
必需 |
返回
类型 | 描述 |
---|---|
List[ChatType]
|
ChatType 列表,其中每个 ChatType 都是对应于要补全的步骤之一的提示 |
List[ChatType]
|
要补全。 |
源代码位于 src/distilabel/steps/tasks/math_shepherd/completer.py
_auto_label(inputs, final_outputs, input_positions, golden_answers, statistics, raw_outputs, raw_inputs)
¶
就地(在输入中)标注步骤,并返回输入。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
inputs
|
StepInput
|
原始输入 |
必需 |
final_outputs
|
list[Completions]
|
来自 LLM 的生成列表。它被组织为一个列表,其中发送到 LLM 的元素被分组在一起,然后每个元素包含补全,并且每个补全都是步骤列表。 |
必需 |
input_positions
|
list[tuple[int, int, int]]
|
一个列表,其中包含在 process 方法中生成的元组 (i, j, k),其中 i 是输入的索引,j 是解决方案的索引,k 是补全的索引。 |
必需 |
golden_answers
|
list[str]
|
每个输入的黄金答案列表。 |
必需 |
statistics
|
list[LLMStatistics]
|
来自 LLM 的统计信息列表。 |
必需 |
raw_outputs
|
list[str]
|
来自 LLM 的原始输出列表。 |
必需 |
raw_inputs
|
list[str]
|
到 LLM 的原始输入列表。 |
必需 |
返回
类型 | 描述 |
---|---|
StepInput
|
已标注的输入。 |
源代码位于 src/distilabel/steps/tasks/math_shepherd/completer.py
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 |
|
_add_metadata(input, statistics, raw_output, raw_input)
¶
将 distilabel_metadata
添加到输入。
此方法在通用 Tasks 中是免费提供的,但由于我们重新实现了 process
,因此我们必须在此处重复它。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
input
|
dict[str, Any]
|
要向其添加元数据的输入。 |
必需 |
statistics
|
list[LLMStatistics]
|
来自 LLM 的统计信息。 |
必需 |
raw_output
|
Union[str, None]
|
来自 LLM 的原始输出。 |
必需 |
raw_input
|
Union[list[dict[str, Any]], None]
|
到 LLM 的原始输入。 |
必需 |
返回
类型 | 描述 |
---|---|
dict[str, Any]
|
带有添加的元数据的输入(如果适用)。 |
源代码位于 src/distilabel/steps/tasks/math_shepherd/completer.py
get_structured_output()
¶
创建要传递给 LLM 的 json 模式,以强制生成一个字典,该字典的输出可以直接解析为 python 字典。
该模式对应于以下内容
from pydantic import BaseModel, Field
class Solution(BaseModel):
solution: str = Field(..., description="Step by step solution leading to the final answer")
class MathShepherdCompleter(BaseModel):
solutions: list[Solution] = Field(..., description="List of solutions")
MathShepherdCompleter.model_json_schema()
返回
类型 | 描述 |
---|---|
dict[str, Any]
|
强制执行的响应的 JSON 模式。 |
源代码位于 src/distilabel/steps/tasks/math_shepherd/completer.py
MathShepherdGenerator
¶
基类:Task
Math Shepherd 解决方案生成器。
此任务负责以 Math Shepherd Completer 任务期望的格式为给定指令生成补全。这些属性使该任务能够灵活地用于不同类型的数据集和 LLM,但我们提供了原始论文中提出的 GSM8K 和 MATH 数据集的示例。在修改它们之前,请查看当前的默认值,以确保补全生成正确。如果未提供黄金解决方案,则可以使用此任务为给定问题生成黄金解决方案,以及要由 Math Shepherd Completer 标注的可能解决方案。将仅生成 solutions
或 golden_solution
中的一个,具体取决于 M 的值。
属性
名称 | 类型 | 描述 |
---|---|---|
system_prompt |
Optional[str]
|
要在补全中使用的系统提示。默认的系统提示已经过检查,在使用 Llama 3.1 的 8B 和 70B 模型时生成了良好的补全,但可以对其进行修改以使其适应所选的模型和数据集。请注意,系统提示在 Jinja2 模板中包含 2 个变量:{{extra_rules}} 和 {{few_shot}}。这些变量用于包含额外的规则(例如,引导模型生成特定类型的响应)和少量示例(添加示例)。可以修改它们以使系统提示适应数据集和所使用的模型,而无需更改完整的系统提示。 |
extra_rules |
Optional[str]
|
此字段可用于插入与数据集类型相关的额外规则。例如,在原始论文中,他们使用了 GSM8K 和 MATH 数据集,此字段可用于插入 GSM8K 数据集的规则。 |
few_shots |
Optional[str]
|
少量示例,用于帮助模型生成补全,以您数据集所需的解决方案类型格式编写它们。 |
M |
Optional[PositiveInt]
|
为每个步骤生成的补全数量。默认设置为 1,这将生成“黄金解决方案”。在这种情况下,选择更强大的模型,因为它将用作标注期间的真实来源。如果 M 设置为大于 1 的数字,则该任务将生成要由 Math Shepherd Completer 任务标注的补全列表。 |
输入列
- instruction (
str
): 任务或指令。
输出列
- golden_solution (
str
): 指令的逐步解决方案。如果 M 等于 1,则将生成它。 - solutions (
List[List[str]]
): 指令的可能解决方案列表。如果 M 大于 1,则将生成它。 - model_name (
str
): 用于生成修订的模型名称。
类别
- 文本生成
示例
为给定指令生成解决方案(此处首选更强大的模型)
from distilabel.steps.tasks import MathShepherdGenerator
from distilabel.models import InferenceEndpointsLLM
llm=InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
tokenizer_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
generation_kwargs={
"temperature": 0.6,
"max_new_tokens": 1024,
},
)
task = MathShepherdGenerator(
name="golden_solution_generator",
llm=llm,
)
task.load()
result = next(
task.process(
[
{
"instruction": "Janet’s ducks lay 16 eggs per day. She eats three for breakfast every morning and bakes muffins for her friends every day with four. She sells the remainder at the farmers' market daily for $2 per fresh duck egg. How much in dollars does she make every day at the farmers' market?",
},
]
)
)
# [[{'instruction': "Janet’s ducks lay 16 eggs per day. She eats three for breakfast every morning and bakes muffins for her friends every day with four. She sells the remainder at the farmers' market daily for $2 per fresh duck egg. How much in dollars does she make every day at the farmers' market?",
# 'golden_solution': '["Step 1: Janet sells 16 - 3 - 4 = <<16-3-4=9>>9 duck eggs a day.", "Step 2: She makes 9 * 2 = $<<9*2=18>>18 every day at the farmer\u2019s market.", "The answer is: 18"]'}]]
为给定指令生成 M 个补全(使用结构化输出生成)
from distilabel.steps.tasks import MathShepherdGenerator
from distilabel.models import InferenceEndpointsLLM
llm=InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3.1-8B-Instruct",
tokenizer_id="meta-llama/Meta-Llama-3.1-8B-Instruct",
generation_kwargs={
"temperature": 0.7,
"max_new_tokens": 2048,
},
)
task = MathShepherdGenerator(
name="solution_generator",
llm=llm,
M=2,
use_default_structured_output=True,
)
task.load()
result = next(
task.process(
[
{
"instruction": "Janet’s ducks lay 16 eggs per day. She eats three for breakfast every morning and bakes muffins for her friends every day with four. She sells the remainder at the farmers' market daily for $2 per fresh duck egg. How much in dollars does she make every day at the farmers' market?",
},
]
)
)
# [[{'instruction': "Janet’s ducks lay 16 eggs per day. She eats three for breakfast every morning and bakes muffins for her friends every day with four. She sells the remainder at the farmers' market daily for $2 per fresh duck egg. How much in dollars does she make every day at the farmers' market?",
# 'solutions': [["Step 1: Janet sells 16 - 3 - 4 = <<16-3-4=9>>9 duck eggs a day. -", "Step 2: She makes 9 * 2 = $<<9*2=18>>18 every day at the farmer\u2019s market.", "The answer is: 18"], ["Step 1: Janets ducks lay 16 eggs per day, and she uses 3 + 4 = <<3+4=7>>7 for eating and baking. +", "Step 2: So she sells 16 - 7 = <<16-7=9>>9 duck eggs every day. +", "Step 3: Those 9 eggs are worth 9 * $2 = $<<9*2=18>>18.", "The answer is: 18"]]}]]
源代码位于 src/distilabel/steps/tasks/math_shepherd/generator.py
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 |
|
get_structured_output()
¶
创建要传递给 LLM 的 json 模式,以强制生成一个字典,该字典的输出可以直接解析为 python 字典。
该模式对应于以下内容
from pydantic import BaseModel, Field
class Solution(BaseModel):
solution: str = Field(..., description="Step by step solution leading to the final answer")
class MathShepherdGenerator(BaseModel):
solutions: list[Solution] = Field(..., description="List of solutions")
MathShepherdGenerator.model_json_schema()
返回
类型 | 描述 |
---|---|
dict[str, Any]
|
强制执行的响应的 JSON 模式。 |
源代码位于 src/distilabel/steps/tasks/math_shepherd/generator.py
FormatPRM
¶
基类:Step
辅助步骤,用于将数据转换为 PRM 模型期望的格式。
此步骤可用于将数据格式化为 2 种格式之一:遵循 peiyi9979/Math-Shepherd 中呈现的格式,在这种情况下,此步骤创建列 input 和 label,其中 input 是带有解决方案的指令(标签被令牌替换),label 是带有解决方案的指令,两者用换行符分隔。遵循 TRL 的训练格式,这将生成列 prompt、completions 和 labels。labels 对应于原始标签,这些标签被布尔值替换,其中 True 表示正确的步骤。
属性
名称 | 类型 | 描述 |
---|---|---|
format |
Literal['math-shepherd', 'trl']
|
用于 PRM 模型的格式。“math-shepherd”对应于原始论文,而“trl”是为使用 TRL 训练模型而准备的格式。 |
step_token |
str
|
用作表示预测步骤分数位置的唯一令牌的字符串。 |
tags |
list[str]
|
表示正确和不正确步骤的标签列表。仅当它与 |
输入列
- instruction (
str
): 任务或指令。 - solutions (
list[str]
): 带有任务解决方案的步骤列表。
输出列
- input (
str
): 带有解决方案的指令,其中标签被令牌替换。 - label (
str
): 带有解决方案的指令。 - prompt (
str
): 带有解决方案的指令,其中标签被令牌替换。 - completions (
List[str]
): 以步骤列表形式表示的解决方案。 - labels (
List[bool]
): 标签,以布尔值列表形式,其中 True 表示良好的响应。
类别
- text-manipulation
- columns
示例
准备您的数据以使用 Math-Shepherd 格式训练 PRM 模型
from distilabel.steps.tasks import FormatPRM
from distilabel.steps import ExpandColumns
expand_columns = ExpandColumns(columns=["solutions"])
expand_columns.load()
# Define our PRM formatter
formatter = FormatPRM()
formatter.load()
# Expand the solutions column as it comes from the MathShepherdCompleter
result = next(
expand_columns.process(
[
{
"instruction": "Janet’s ducks lay 16 eggs per day. She eats three for breakfast every morning and bakes muffins for her friends every day with four. She sells the remainder at the farmers' market daily for $2 per fresh duck egg. How much in dollars does she make every day at the farmers' market?",
"solutions": [["Step 1: Determine the amount of blue fiber needed: 2 bolts of blue fiber are required. +", "Step 2: Calculate the amount of white fiber needed: Since it's half that much, we can divide 2 by 2: 2 / 2 = <<2/2=1>>1 bolt of white fiber. +", "Step 3: Add the amount of blue and white fiber: 2 (blue) + 1 (white) = <<2+1=3>>3 bolts of fiber in total. The answer is: 3 +"], ["Step 1: Determine the amount of blue fiber needed: 2 bolts of blue fiber are required. +", "Step 2: Calculate the amount of white fiber needed: Since it's half that much, we can multiply 2 by 0.5 (which is the same as dividing by 2): 2 * 0.5 = <<2*0.5=1>>1 bolt of white fiber. +", "Step 3: Add the amount of blue and white fiber: 2 (blue) + 1 (white) = <<2+1=3>>3 bolts of fiber in total. The answer is: 3 +"], ["Step 1: Determine the amount of blue fiber needed: 2 bolts of blue fiber are required. +", "Step 2: Calculate the amount of white fiber needed: Since it's half that much, we can multiply 2 by 0.5 (which is the same as dividing by 2): 2 * 0.5 = <<2*0.5=1>>1 bolt of white fiber. +", "Step 3: Add the amount of blue and white fiber: 2 (blue) + 1 (white) = <<2+1=3>>3 bolts of fiber in total. The answer is: 3 +"], ["Step 1: Determine the amount of blue fiber needed: 2 bolts of blue fiber are required. +", "Step 2: Calculate the amount of white fiber needed: Since it's half that much, we can multiply 2 by 0.5 (which is the same as dividing by 2): 2 * 0.5 = <<2*0.5=1>>1 bolt of white fiber. +", "Step 3: Add the amount of blue and white fiber: 2 (blue) + 1 (white) = <<2+1=3>>3 bolts of fiber in total. The answer is: 3 +"], ["Step 1: Determine the amount of blue fiber needed: 2 bolts of blue fiber are required. +", "Step 2: Calculate the amount of white fiber needed: Since it's half that much, we can divide 2 by 2: 2 / 2 = <<2/2=1>>1 bolt of white fiber. +", "Step 3: Add the amount of blue and white fiber: 2 (blue) + 1 (white) = <<2+1=3>>3 bolts of fiber in total. The answer is: 3 +"]]
},
]
)
)
result = next(formatter.process(result))
准备您的数据以使用 TRL 格式训练 PRM 模型
from distilabel.steps.tasks import FormatPRM
from distilabel.steps import ExpandColumns
expand_columns = ExpandColumns(columns=["solutions"])
expand_columns.load()
# Define our PRM formatter
formatter = FormatPRM(format="trl")
formatter.load()
# Expand the solutions column as it comes from the MathShepherdCompleter
result = next(
expand_columns.process(
[
{
"instruction": "Janet’s ducks lay 16 eggs per day. She eats three for breakfast every morning and bakes muffins for her friends every day with four. She sells the remainder at the farmers' market daily for $2 per fresh duck egg. How much in dollars does she make every day at the farmers' market?",
"solutions": [["Step 1: Determine the amount of blue fiber needed: 2 bolts of blue fiber are required. +", "Step 2: Calculate the amount of white fiber needed: Since it's half that much, we can divide 2 by 2: 2 / 2 = <<2/2=1>>1 bolt of white fiber. +", "Step 3: Add the amount of blue and white fiber: 2 (blue) + 1 (white) = <<2+1=3>>3 bolts of fiber in total. The answer is: 3 +"], ["Step 1: Determine the amount of blue fiber needed: 2 bolts of blue fiber are required. +", "Step 2: Calculate the amount of white fiber needed: Since it's half that much, we can multiply 2 by 0.5 (which is the same as dividing by 2): 2 * 0.5 = <<2*0.5=1>>1 bolt of white fiber. +", "Step 3: Add the amount of blue and white fiber: 2 (blue) + 1 (white) = <<2+1=3>>3 bolts of fiber in total. The answer is: 3 +"], ["Step 1: Determine the amount of blue fiber needed: 2 bolts of blue fiber are required. +", "Step 2: Calculate the amount of white fiber needed: Since it's half that much, we can multiply 2 by 0.5 (which is the same as dividing by 2): 2 * 0.5 = <<2*0.5=1>>1 bolt of white fiber. +", "Step 3: Add the amount of blue and white fiber: 2 (blue) + 1 (white) = <<2+1=3>>3 bolts of fiber in total. The answer is: 3 +"], ["Step 1: Determine the amount of blue fiber needed: 2 bolts of blue fiber are required. +", "Step 2: Calculate the amount of white fiber needed: Since it's half that much, we can multiply 2 by 0.5 (which is the same as dividing by 2): 2 * 0.5 = <<2*0.5=1>>1 bolt of white fiber. +", "Step 3: Add the amount of blue and white fiber: 2 (blue) + 1 (white) = <<2+1=3>>3 bolts of fiber in total. The answer is: 3 +"], ["Step 1: Determine the amount of blue fiber needed: 2 bolts of blue fiber are required. +", "Step 2: Calculate the amount of white fiber needed: Since it's half that much, we can divide 2 by 2: 2 / 2 = <<2/2=1>>1 bolt of white fiber. +", "Step 3: Add the amount of blue and white fiber: 2 (blue) + 1 (white) = <<2+1=3>>3 bolts of fiber in total. The answer is: 3 +"]]
},
]
)
)
result = next(formatter.process(result))
# {
# "instruction": "Janet’s ducks lay 16 eggs per day. She eats three for breakfast every morning and bakes muffins for her friends every day with four. She sells the remainder at the farmers' market daily for $2 per fresh duck egg. How much in dollars does she make every day at the farmers' market?",
# "solutions": [
# "Step 1: Determine the amount of blue fiber needed: 2 bolts of blue fiber are required. +",
# "Step 2: Calculate the amount of white fiber needed: Since it's half that much, we can divide 2 by 2: 2 / 2 = <<2/2=1>>1 bolt of white fiber. +",
# "Step 3: Add the amount of blue and white fiber: 2 (blue) + 1 (white) = <<2+1=3>>3 bolts of fiber in total. The answer is: 3 +"
# ],
# "prompt": "Janet’s ducks lay 16 eggs per day. She eats three for breakfast every morning and bakes muffins for her friends every day with four. She sells the remainder at the farmers' market daily for $2 per fresh duck egg. How much in dollars does she make every day at the farmers' market?",
# "completions": [
# "Step 1: Determine the amount of blue fiber needed: 2 bolts of blue fiber are required.",
# "Step 2: Calculate the amount of white fiber needed: Since it's half that much, we can divide 2 by 2: 2 / 2 = <<2/2=1>>1 bolt of white fiber.",
# "Step 3: Add the amount of blue and white fiber: 2 (blue) + 1 (white) = <<2+1=3>>3 bolts of fiber in total. The answer is: 3"
# ],
# "labels": [
# true,
# true,
# true
# ]
# }
引用
```
@misc{wang2024mathshepherdverifyreinforcellms,
title={Math-Shepherd: Verify and Reinforce LLMs Step-by-step without Human Annotations},
author={Peiyi Wang and Lei Li and Zhihong Shao and R. X. Xu and Damai Dai and Yifei Li and Deli Chen and Y. Wu and Zhifang Sui},
year={2024},
eprint={2312.08935},
archivePrefix={arXiv},
primaryClass={cs.AI},
url={https://arxiv.org/abs/2312.08935},
}
```
源代码位于 src/distilabel/steps/tasks/math_shepherd/utils.py
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 |
|
process(inputs)
¶
该过程为 APIGenGenerator
任务准备数据。
如果提供了单个示例,则会复制它以避免引发错误。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
inputs
|
StepInput
|
包含输入数据的字典列表。 |
必需 |
产生
类型 | 描述 |
---|---|
StepOutput
|
包含输出数据的字典列表。 |
源代码位于 src/distilabel/steps/tasks/math_shepherd/utils.py
PairRM
¶
基类: Step
使用 LLM
模型根据输入对候选者进行排名。
属性
名称 | 类型 | 描述 |
---|---|---|
model |
str
|
用于排名的模型。默认为 |
instructions |
Optional[str]
|
用于模型的指令。默认为 |
输入列
- inputs (
List[Dict[str, Any]]
): 要为其候选者排名的输入文本或对话。 - candidates (
List[Dict[str, Any]]
): 要排名的候选者。
输出列
- ranks (
List[int]
): 基于输入的候选者排名。 - ranked_candidates (
List[Dict[str, Any]]
): 基于输入排名的候选者。 - model_name (
str
): 用于对候选响应进行排名的模型名称。默认为"llm-blender/PairRM"
。
类别
- preference
注意
此步骤与其他任务不同,因为目前此模型只有一个实现,我们将使用特定的 LLM
。
示例
对 LLM 候选对象进行排名
from distilabel.steps.tasks import PairRM
# Consider this as a placeholder for your actual LLM.
pair_rm = PairRM()
pair_rm.load()
result = next(
scorer.process(
[
{"input": "Hello, how are you?", "candidates": ["fine", "good", "bad"]},
]
)
)
# result
# [
# {
# 'input': 'Hello, how are you?',
# 'candidates': ['fine', 'good', 'bad'],
# 'ranks': [2, 1, 3],
# 'ranked_candidates': ['good', 'fine', 'bad'],
# 'model_name': 'llm-blender/PairRM',
# }
# ]
引用
@misc{jiang2023llmblenderensemblinglargelanguage,
title={LLM-Blender: Ensembling Large Language Models with Pairwise Ranking and Generative Fusion},
author={Dongfu Jiang and Xiang Ren and Bill Yuchen Lin},
year={2023},
eprint={2306.02561},
archivePrefix={arXiv},
primaryClass={cs.CL},
url={https://arxiv.org/abs/2306.02561},
}
源代码位于 src/distilabel/steps/tasks/pair_rm.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 |
|
inputs
property
¶
输入列对应于 Blender.rank
中的两个必需参数:inputs
和 candidates
。
outputs
property
¶
输出将包括 ranks
和 ranked_candidates
。
load()
¶
使用 llm_blender.Blender
加载通过 model
提供的 PairRM 模型,这是用于运行 PairRM 模型推理的自定义库。
源代码位于 src/distilabel/steps/tasks/pair_rm.py
format_input(input)
¶
输入应为包含键 input
和 candidates
的字典,其中 input
对应于模型的指令,candidates
是要排名的响应列表。
源代码位于 src/distilabel/steps/tasks/pair_rm.py
process(inputs)
¶
根据输入生成候选者的排名。
排名是候选者的位置,其中较低的排名更好,而排名后的候选者对应于根据获得的排名排序的候选者。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
inputs
|
StepInput
|
包含任务输入的 Python 字典列表。 |
必需 |
产生
类型 | 描述 |
---|---|
StepOutput
|
包含 |
源代码位于 src/distilabel/steps/tasks/pair_rm.py
PrometheusEval
¶
基类:Task
使用 Prometheus 2.0 评判和排名 LLM
生成的质量。
PrometheusEval
是为 Prometheus 2.0 创建的任务,涵盖绝对评估和相对评估。绝对评估,即 mode="absolute"
,用于评估 LLM 对给定指令的单个生成结果。相对评估,即 mode="relative"
,用于评估 LLM 对给定指令的两个生成结果。两种评估都可能使用参考答案进行比较,无论是否使用 reference
属性,并且两者都基于评分标准,该标准根据以下默认方面评判生成结果:helpfulness
、harmlessness
、honesty
、factual-validity
和 reasoning
,这些方面可以通过 rubrics
覆盖,并且通过属性 rubric
设置所选标准。
注意
PrometheusEval
任务更适合且旨在与 Kaist AI 发布的任何 Prometheus 2.0 模型一起使用,即:https://hugging-face.cn/prometheus-eval/prometheus-7b-v2.0 和 https://hugging-face.cn/prometheus-eval/prometheus-8x7b-v2.0。如果使用其他模型,则无法保证评判评估的格式和质量,尽管某些其他模型也可能能够正确遵循格式并生成有见地的评判。
属性
名称 | 类型 | 描述 |
---|---|---|
mode |
Literal['absolute', 'relative']
|
要使用的评估模式, |
rubric |
str
|
要在提示中使用的评分标准,以基于不同方面运行评判。可以是 |
rubrics |
Optional[Dict[str, str]]
|
包含用于评判的不同标准的字典,其中键是标准名称,值是标准描述。默认标准如下: |
reference |
bool
|
一个布尔标志,指示是否将提供参考答案/补全,以便模型评判基于与其的比较。这意味着除了其余输入之外,还需要在输入数据中提供列 |
_template |
Union[Template, None]
|
用于格式化 LLM 输入的 Jinja2 模板。 |
输入列
- instruction (
str
): 用作参考的指令。 - generation (
str
, optional): 来自给定instruction
的生成文本。如果mode=absolute
,则此列是必需的。 - generations (
List[str]
, optional): 来自给定instruction
的生成文本。它应仅包含 2 个生成结果。如果mode=relative
,则此列是必需的。 - reference (
str
, optional): 用于 LLM 与之比较的instruction
的参考答案/黄金答案。
输出列
- feedback (
str
): 反馈,解释了以下结果,由 LLM 使用预定义的评分标准评判,并与提供的reference
进行比较(如果提供)。 - result (
Union[int, Literal["A", "B"]]
): 如果mode=absolute
,则结果包含generation
的评分,采用 1-5 的李克特量表;否则,如果mode=relative
,则结果包含 “A” 或 “B”,“获胜”者是generations
索引 0 中的生成结果(如果result='A'
)或索引 1 中的生成结果(如果result='B'
)。 - model_name (
str
): 用于生成feedback
和result
的模型名称。
类别
- critique
- preference
示例
使用 Prometheus 2_0 评判和评估 LLM 生成质量
from distilabel.steps.tasks import PrometheusEval
from distilabel.models import vLLM
# Consider this as a placeholder for your actual LLM.
prometheus = PrometheusEval(
llm=vLLM(
model="prometheus-eval/prometheus-7b-v2.0",
chat_template="[INST] {{ messages[0]"content" }}\n{{ messages[1]"content" }}[/INST]",
),
mode="absolute",
rubric="factual-validity"
)
prometheus.load()
result = next(
prometheus.process(
[
{"instruction": "make something", "generation": "something done"},
]
)
)
# result
# [
# {
# 'instruction': 'make something',
# 'generation': 'something done',
# 'model_name': 'prometheus-eval/prometheus-7b-v2.0',
# 'feedback': 'the feedback',
# 'result': 6,
# }
# ]
相对评估的评判
from distilabel.steps.tasks import PrometheusEval
from distilabel.models import vLLM
# Consider this as a placeholder for your actual LLM.
prometheus = PrometheusEval(
llm=vLLM(
model="prometheus-eval/prometheus-7b-v2.0",
chat_template="[INST] {{ messages[0]"content" }}\n{{ messages[1]"content" }}[/INST]",
),
mode="relative",
rubric="honesty"
)
prometheus.load()
result = next(
prometheus.process(
[
{"instruction": "make something", "generations": ["something done", "other thing"]},
]
)
)
# result
# [
# {
# 'instruction': 'make something',
# 'generations': ['something done', 'other thing'],
# 'model_name': 'prometheus-eval/prometheus-7b-v2.0',
# 'feedback': 'the feedback',
# 'result': 'something done',
# }
# ]
使用自定义标准进行评判
from distilabel.steps.tasks import PrometheusEval
from distilabel.models import vLLM
# Consider this as a placeholder for your actual LLM.
prometheus = PrometheusEval(
llm=vLLM(
model="prometheus-eval/prometheus-7b-v2.0",
chat_template="[INST] {{ messages[0]"content" }}\n{{ messages[1]"content" }}[/INST]",
),
mode="absolute",
rubric="custom",
rubrics={
"custom": "[A]\nScore 1: A\nScore 2: B\nScore 3: C\nScore 4: D\nScore 5: E"
}
)
prometheus.load()
result = next(
prometheus.process(
[
{"instruction": "make something", "generation": "something done"},
]
)
)
# result
# [
# {
# 'instruction': 'make something',
# 'generation': 'something done',
# 'model_name': 'prometheus-eval/prometheus-7b-v2.0',
# 'feedback': 'the feedback',
# 'result': 6,
# }
# ]
使用参考答案进行评判
from distilabel.steps.tasks import PrometheusEval
from distilabel.models import vLLM
# Consider this as a placeholder for your actual LLM.
prometheus = PrometheusEval(
llm=vLLM(
model="prometheus-eval/prometheus-7b-v2.0",
chat_template="[INST] {{ messages[0]"content" }}\n{{ messages[1]"content" }}[/INST]",
),
mode="absolute",
rubric="helpfulness",
reference=True,
)
prometheus.load()
result = next(
prometheus.process(
[
{
"instruction": "make something",
"generation": "something done",
"reference": "this is a reference answer",
},
]
)
)
# result
# [
# {
# 'instruction': 'make something',
# 'generation': 'something done',
# 'reference': 'this is a reference answer',
# 'model_name': 'prometheus-eval/prometheus-7b-v2.0',
# 'feedback': 'the feedback',
# 'result': 6,
# }
# ]
引用
@misc{kim2024prometheus2opensource,
title={Prometheus 2: An Open Source Language Model Specialized in Evaluating Other Language Models},
author={Seungone Kim and Juyoung Suk and Shayne Longpre and Bill Yuchen Lin and Jamin Shin and Sean Welleck and Graham Neubig and Moontae Lee and Kyungjae Lee and Minjoon Seo},
year={2024},
eprint={2405.01535},
archivePrefix={arXiv},
primaryClass={cs.CL},
url={https://arxiv.org/abs/2405.01535},
}
源代码位于 src/distilabel/steps/tasks/prometheus_eval.py
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 |
|
inputs
property
¶
任务的默认输入是 instruction
和 generation
(如果 reference=False
),否则,输入是 instruction
、generation
和 reference
。
outputs
property
¶
任务的输出是由 Prometheus 生成的 feedback
和 result
,以及根据使用的 LLM
自动包含的 model_name
。
load()
¶
加载 Prometheus 2.0 的 Jinja2 模板,用于绝对或相对评估,具体取决于 mode
值,以及是否使用参考,具体取决于 reference
的值。
源代码位于 src/distilabel/steps/tasks/prometheus_eval.py
format_input(input)
¶
输入格式化为 ChatType
,其中提示根据为 Prometheus 2.0 选择的 Jinja2 模板进行格式化,假设这是用户的第一次交互,包括预定义的系统提示。
源代码位于 src/distilabel/steps/tasks/prometheus_eval.py
format_output(output, input)
¶
输出格式化为字典,其中键 feedback
和 result
是使用正则表达式从 Prometheus 输出中捕获的。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
output
|
Union[str, None]
|
LLM 的原始输出。 |
必需 |
input
|
Dict[str, Any]
|
任务的输入。可选提供,以防对构建输出有用。 |
必需 |
返回
类型 | 描述 |
---|---|
Dict[str, Any]
|
包含由 LLM 生成的键 |
源代码位于 src/distilabel/steps/tasks/prometheus_eval.py
QualityScorer
¶
基类:Task
使用 LLM
根据响应质量对其进行评分。
QualityScorer
是一个预定义的任务,它将 instruction
定义为输入,将 score
定义为输出。此任务用于评估指令和响应的质量。它是论文“What Makes Good Data for Alignment? A Comprehensive Study of Automatic Data Selection in Instruction Tuning”中质量评分任务的实现。该任务遵循与 Complexity Scorer 相同的方案,但指令-响应对在质量方面进行评分,从而获得每个指令的质量分数。
属性
名称 | 类型 | 描述 |
---|---|---|
_template |
Union[Template, None]
|
用于格式化 LLM 输入的 Jinja2 模板。 |
输入列
- instruction (
str
): 用于生成responses
的指令。 - responses (
List[str]
): 要评分的响应。每个响应都与指令形成一对。
输出列
- scores (
List[float]
): 每个指令的分数。 - model_name (
str
): 用于生成分数的模型名称。
类别
- 评分器
- quality
- response
示例
评估您的指令的质量
from distilabel.steps.tasks import QualityScorer
from distilabel.models import InferenceEndpointsLLM
# Consider this as a placeholder for your actual LLM.
scorer = QualityScorer(
llm=InferenceEndpointsLLM(
model_id="mistralai/Mistral-7B-Instruct-v0.2",
)
)
scorer.load()
result = next(
scorer.process(
[
{
"instruction": "instruction",
"responses": ["good response", "weird response", "bad response"]
}
]
)
)
# result
[
{
'instructions': 'instruction',
'model_name': 'test',
'scores': [5, 3, 1],
}
]
使用默认模式生成结构化输出
from distilabel.steps.tasks import QualityScorer
from distilabel.models import InferenceEndpointsLLM
scorer = QualityScorer(
llm=InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
),
use_default_structured_output=True
)
scorer.load()
result = next(
scorer.process(
[
{
"instruction": "instruction",
"responses": ["good response", "weird response", "bad response"]
}
]
)
)
# result
[{'instruction': 'instruction',
'responses': ['good response', 'weird response', 'bad response'],
'scores': [1, 2, 3],
'distilabel_metadata': {'raw_output_quality_scorer_0': '{ "scores": [1, 2, 3] }'},
'model_name': 'meta-llama/Meta-Llama-3.1-70B-Instruct'}]
引用
@misc{liu2024makesgooddataalignment,
title={What Makes Good Data for Alignment? A Comprehensive Study of Automatic Data Selection in Instruction Tuning},
author={Wei Liu and Weihao Zeng and Keqing He and Yong Jiang and Junxian He},
year={2024},
eprint={2312.15685},
archivePrefix={arXiv},
primaryClass={cs.CL},
url={https://arxiv.org/abs/2312.15685},
}
源代码位于 src/distilabel/steps/tasks/quality_scorer.py
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 |
|
inputs
property
¶
任务的输入是 instruction
和 responses
。
outputs
property
¶
任务的输出是一个 scores
列表,其中包含 responses
中每个响应的质量分数。
load()
¶
加载 Jinja2 模板。
源代码位于 src/distilabel/steps/tasks/quality_scorer.py
format_input(input)
¶
输入被格式化为 ChatType
,假设指令是用户在对话中的首次互动。
源代码位于 src/distilabel/steps/tasks/quality_scorer.py
format_output(output, input)
¶
输出被格式化为一个列表,其中包含每个指令-响应对的分数。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
output
|
Union[str, None]
|
LLM 的原始输出。 |
必需 |
input
|
Dict[str, Any]
|
任务的输入。用于获取响应数量。 |
必需 |
返回
类型 | 描述 |
---|---|
Dict[str, Any]
|
一个字典,键为 |
源代码位于 src/distilabel/steps/tasks/quality_scorer.py
get_structured_output()
¶
创建要传递给 LLM 的 json 模式,以强制生成一个字典,该字典的输出可以直接解析为 python 字典。
该模式对应于以下内容
from pydantic import BaseModel
from typing import List
class SchemaQualityScorer(BaseModel):
scores: List[int]
返回
类型 | 描述 |
---|---|
Dict[str, Any]
|
强制执行的响应的 JSON 模式。 |
源代码位于 src/distilabel/steps/tasks/quality_scorer.py
_format_structured_output(output, input)
¶
解析结构化响应,该响应应对应于包含分数的字典以及包含这些分数的列表。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
output
|
str
|
来自 |
必需 |
返回
类型 | 描述 |
---|---|
Dict[str, str]
|
格式化后的输出。 |
源代码位于 src/distilabel/steps/tasks/quality_scorer.py
SelfInstruct
¶
基类:Task
使用 LLM
基于给定输入生成指令。
SelfInstruct
是一个预定义的任务,它在给定一定数量的指令、查询生成标准、应用程序描述和输入的情况下,生成与给定输入相关并遵循查询生成标准和应用程序描述中声明的内容的指令。它基于论文 "Self-Instruct: Aligning Language Models with Self-Generated Instructions" 中的 SelfInstruct 框架。
属性
名称 | 类型 | 描述 |
---|---|---|
num_instructions |
int
|
要生成的指令数量。默认为 5。 |
criteria_for_query_generation |
str
|
查询生成的标准。默认为论文中定义的标准。 |
application_description |
str
|
想要使用这些指令构建的 AI 应用程序的描述。默认为 |
输入列
- input (
str
): 用于生成指令的输入。在论文中也称为种子 (seed)。
输出列
- instructions (
List[str]
): 生成的指令。 - model_name (
str
): 用于生成指令的模型名称。
类别
- 文本生成
示例
基于给定输入生成指令
from distilabel.steps.tasks import SelfInstruct
from distilabel.models import InferenceEndpointsLLM
self_instruct = SelfInstruct(
llm=InferenceEndpointsLLM(
model_id="mistralai/Mistral-7B-Instruct-v0.2",
),
num_instructions=5, # This is the default value
)
self_instruct.load()
result = next(self_instruct.process([{"input": "instruction"}]))
# result
# [
# {
# 'input': 'instruction',
# 'model_name': 'mistralai/Mistral-7B-Instruct-v0.2',
# 'instructions': ["instruction 1", "instruction 2", "instruction 3", "instruction 4", "instruction 5"],
# }
# ]
引用
@misc{wang2023selfinstructaligninglanguagemodels,
title={Self-Instruct: Aligning Language Models with Self-Generated Instructions},
author={Yizhong Wang and Yeganeh Kordi and Swaroop Mishra and Alisa Liu and Noah A. Smith and Daniel Khashabi and Hannaneh Hajishirzi},
year={2023},
eprint={2212.10560},
archivePrefix={arXiv},
primaryClass={cs.CL},
url={https://arxiv.org/abs/2212.10560},
}
源代码位于 src/distilabel/steps/tasks/self_instruct.py
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 |
|
inputs
property
¶
该任务的输入是 input
,即种子文本。
outputs
property
¶
该任务的输出是包含生成指令的 instructions
列表。
load()
¶
加载 Jinja2 模板。
源代码位于 src/distilabel/steps/tasks/self_instruct.py
format_input(input)
¶
输入被格式化为 ChatType
,假设指令是用户在对话中的首次互动。
源代码位于 src/distilabel/steps/tasks/self_instruct.py
format_output(output, input=None)
¶
输出格式化为包含生成指令的列表。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
output
|
Union[str, None]
|
LLM 的原始输出。 |
必需 |
input
|
Optional[Dict[str, Any]]
|
任务的输入。用于获取响应数量。 |
None
|
返回
类型 | 描述 |
---|---|
Dict[str, Any]
|
包含生成指令的字典。 |
源代码位于 src/distilabel/steps/tasks/self_instruct.py
GenerateSentencePair
¶
基类:Task
给定锚句子,生成正面和负面(可选)句子。
GenerateSentencePair
是一个预定义的任务,它在给定锚句子的情况下,生成与锚句子相关的正面句子,以及可选的与锚句子无关或与之相似的负面句子。可选地,您可以提供上下文来引导 LLM 朝向更具体的行为。此任务对于生成训练数据集以训练嵌入模型非常有用。
属性
名称 | 类型 | 描述 |
---|---|---|
triplet |
bool
|
一个标志,指示任务是否应生成三元组句子(锚句子、正面句子、负面句子)。默认为 |
action |
GenerationAction
|
执行的操作以生成正面句子。 |
context |
str
|
用于生成的上下文。可以帮助引导 LLM 朝向更具体的上下文。默认情况下不使用。 |
hard_negative |
bool
|
一个标志,指示负面句子是否应为硬负例。硬负例使模型难以区分正面句子,具有更高的语义相似度。 |
输入列
- anchor (
str
): 用于生成正面和负面句子的锚句子。
输出列
- positive (
str
): 与anchor
相关的正面句子。 - negative (
str
): 如果triplet=True
,则为与anchor
无关的负面句子;或者,如果hard_negative=True
,则为与正面句子更相似的负面句子,以增加模型区分的难度。 - model_name (
str
): 用于生成句子的模型名称。
类别
- embedding
示例
释义
from distilabel.steps.tasks import GenerateSentencePair
from distilabel.models import InferenceEndpointsLLM
generate_sentence_pair = GenerateSentencePair(
triplet=True, # `False` to generate only positive
action="paraphrase",
llm=InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
tokenizer_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
),
input_batch_size=10,
)
generate_sentence_pair.load()
result = generate_sentence_pair.process([{"anchor": "What Game of Thrones villain would be the most likely to give you mercy?"}])
生成语义相似的句子
from distilabel.models import InferenceEndpointsLLM
from distilabel.steps.tasks import GenerateSentencePair
generate_sentence_pair = GenerateSentencePair(
triplet=True, # `False` to generate only positive
action="semantically-similar",
llm=InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
tokenizer_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
),
input_batch_size=10,
)
generate_sentence_pair.load()
result = generate_sentence_pair.process([{"anchor": "How does 3D printing work?"}])
生成查询
from distilabel.steps.tasks import GenerateSentencePair
from distilabel.models import InferenceEndpointsLLM
generate_sentence_pair = GenerateSentencePair(
triplet=True, # `False` to generate only positive
action="query",
llm=InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
tokenizer_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
),
input_batch_size=10,
)
generate_sentence_pair.load()
result = generate_sentence_pair.process([{"anchor": "Argilla is an open-source data curation platform for LLMs. Using Argilla, ..."}])
生成答案
from distilabel.steps.tasks import GenerateSentencePair
from distilabel.models import InferenceEndpointsLLM
generate_sentence_pair = GenerateSentencePair(
triplet=True, # `False` to generate only positive
action="answer",
llm=InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
tokenizer_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
),
input_batch_size=10,
)
generate_sentence_pair.load()
result = generate_sentence_pair.process([{"anchor": "What Game of Thrones villain would be the most likely to give you mercy?"}])
生成带上下文的查询(适用于每个操作)
from distilabel.steps.tasks import GenerateSentencePair
from distilabel.models import InferenceEndpointsLLM
generate_sentence_pair = GenerateSentencePair(
triplet=True, # `False` to generate only positive
action="query",
context="Argilla is an open-source data curation platform for LLMs.",
llm=InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
tokenizer_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
),
input_batch_size=10,
)
generate_sentence_pair.load()
result = generate_sentence_pair.process([{"anchor": "I want to generate queries for my LLM."}])
生成硬负例(适用于每个操作)
from distilabel.steps.tasks import GenerateSentencePair
from distilabel.models import InferenceEndpointsLLM
generate_sentence_pair = GenerateSentencePair(
triplet=True, # `False` to generate only positive
action="query",
context="Argilla is an open-source data curation platform for LLMs.",
hard_negative=True,
llm=InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
tokenizer_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
),
input_batch_size=10,
)
generate_sentence_pair.load()
result = generate_sentence_pair.process([{"anchor": "I want to generate queries for my LLM."}])
使用默认模式生成结构化数据(适用于每个操作)
from distilabel.steps.tasks import GenerateSentencePair
from distilabel.models import InferenceEndpointsLLM
generate_sentence_pair = GenerateSentencePair(
triplet=True, # `False` to generate only positive
action="query",
context="Argilla is an open-source data curation platform for LLMs.",
hard_negative=True,
llm=InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
),
input_batch_size=10,
use_default_structured_output=True
)
generate_sentence_pair.load()
result = generate_sentence_pair.process([{"anchor": "I want to generate queries for my LLM."}])
源代码位于 src/distilabel/steps/tasks/sentence_transformers.py
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 |
|
inputs
property
¶
该任务的输入是 anchor
句子。
outputs
property
¶
该任务的输出是 positive
和 negative
句子,以及用于生成句子的 model_name
。
load()
¶
加载 Jinja2 模板。
源代码位于 src/distilabel/steps/tasks/sentence_transformers.py
format_input(input)
¶
输入格式化为 ChatType
,其中包含描述为锚句子生成正面和负面句子的任务的系统提示。锚句子作为对话中的第一个用户交互提供。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
input
|
Dict[str, Any]
|
包含 |
必需 |
返回
类型 | 描述 |
---|---|
ChatType
|
包含系统和用户交互的字典列表。 |
源代码位于 src/distilabel/steps/tasks/sentence_transformers.py
format_output(output, input=None)
¶
格式化 LLM 的输出,以提取生成的 positive
和 negative
句子。如果输出为 None
或正则表达式不匹配,则输出也将设置为 None
。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
output
|
Union[str, None]
|
LLM 的输出。 |
必需 |
input
|
Optional[Dict[str, Any]]
|
用于生成输出的输入。 |
None
|
返回
类型 | 描述 |
---|---|
Dict[str, Any]
|
包含 |
源代码位于 src/distilabel/steps/tasks/sentence_transformers.py
get_structured_output()
¶
创建要传递给 LLM 的 json 模式,以强制生成一个字典,该字典的输出可以直接解析为 python 字典。
返回
类型 | 描述 |
---|---|
Dict[str, Any]
|
强制执行的响应的 JSON 模式。 |
源代码位于 src/distilabel/steps/tasks/sentence_transformers.py
_format_structured_output(output)
¶
解析结构化响应,该响应应对应于一个字典,其中包含 positive
或 positive
和 negative
键。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
output
|
str
|
来自 |
必需 |
返回
类型 | 描述 |
---|---|
Dict[str, str]
|
格式化后的输出。 |
源代码位于 src/distilabel/steps/tasks/sentence_transformers.py
StructuredGeneration
¶
基类:Task
使用 LLM
为给定的 instruction
生成结构化内容。
StructuredGeneration
是一个预定义的任务,它将 instruction
和 structured_output
定义为输入,并将 generation
定义为输出。此任务用于根据输入指令并遵循每个 instruction
的 structured_output
列中提供的模式生成结构化内容。model_name
也作为输出的一部分返回,以增强输出。
属性
名称 | 类型 | 描述 |
---|---|---|
use_system_prompt |
bool
|
是否在生成中使用系统提示。默认为 |
输入列
- instruction (
str
): 用于生成结构化内容的指令。 - structured_output (
Dict[str, Any]
): 用于生成结构化内容的 structured_output。它应该是一个 Python 字典,其中包含键format
和schema
,其中format
应该是json
或regex
之一,schema
应该是 JSON 模式或正则表达式模式。
输出列
- generation (
str
): 生成的文本,如果可能,应与提供的模式匹配。 - model_name (
str
): 用于生成文本的模型名称。
类别
- outlines
- structured-generation
示例
从 JSON 模式生成结构化输出
from distilabel.steps.tasks import StructuredGeneration
from distilabel.models import InferenceEndpointsLLM
structured_gen = StructuredGeneration(
llm=InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3-70B-Instruct",
tokenizer_id="meta-llama/Meta-Llama-3-70B-Instruct",
),
)
structured_gen.load()
result = next(
structured_gen.process(
[
{
"instruction": "Create an RPG character",
"structured_output": {
"format": "json",
"schema": {
"properties": {
"name": {
"title": "Name",
"type": "string"
},
"description": {
"title": "Description",
"type": "string"
},
"role": {
"title": "Role",
"type": "string"
},
"weapon": {
"title": "Weapon",
"type": "string"
}
},
"required": [
"name",
"description",
"role",
"weapon"
],
"title": "Character",
"type": "object"
}
},
}
]
)
)
从正则表达式模式生成结构化输出(仅适用于支持正则表达式的 LLM,使用 outlines 的提供程序)
from distilabel.steps.tasks import StructuredGeneration
from distilabel.models import InferenceEndpointsLLM
structured_gen = StructuredGeneration(
llm=InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3-70B-Instruct",
tokenizer_id="meta-llama/Meta-Llama-3-70B-Instruct",
),
)
structured_gen.load()
result = next(
structured_gen.process(
[
{
"instruction": "What's the weather like today in Seattle in Celsius degrees?",
"structured_output": {
"format": "regex",
"schema": r"(\d{1,2})°C"
},
}
]
)
)
源代码位于 src/distilabel/steps/tasks/structured_generation.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 |
|
inputs
property
¶
该任务的输入是 instruction
和 structured_output
。可选地,如果 use_system_prompt
标志设置为 True,则也会使用 system_prompt
。
outputs
property
¶
该任务的输出是 generation
和 model_name
。
format_input(input)
¶
输入被格式化为 ChatType
,假设指令是用户在对话中的首次互动。
源代码位于 src/distilabel/steps/tasks/structured_generation.py
format_output(output, input)
¶
输出格式化为包含 generation
的字典。model_name
将自动包含在 Task
的 process
方法中。请注意,即使 structured_output
被定义为生成 JSON 模式,此方法也将返回原始输出,即不带任何解析的字符串。
源代码位于 src/distilabel/steps/tasks/structured_generation.py
TextClassification
¶
基类: Task
将文本分类为一个或多个类别或标签。
此任务可用于文本分类问题,其中目标是将一个或多个标签分配给给定的文本。默认情况下,它使用参考论文中的结构化生成,这有助于生成更简洁的标签。请参阅参考资料中的第 4.1 节。
输入列
- text (
str
): 我们要获取标签的参考文本。
输出列
- labels (
Union[str, List[str]]
): 文本的标签或标签列表。 - model_name (
str
): 用于生成标签的模型名称。
类别
- 文本分类
属性
名称 | 类型 | 描述 |
---|---|---|
system_prompt |
Optional[str]
|
在任务开始之前向用户显示的提示。包含默认消息,使模型表现得像分类专家。 |
n |
PositiveInt
|
要生成的标签数量。如果只需要 1 个,则对应于标签分类问题;如果 >1,则将返回文本最具代表性的 “n” 个标签。默认为 1。 |
context |
Optional[str]
|
生成标签时使用的上下文。默认情况下包含通用消息,但可用于自定义任务的上下文。 |
examples |
Optional[List[str]]
|
帮助模型理解任务的示例列表,少量样本。 |
available_labels |
Optional[Union[List[str], Dict[str, str]]]
|
分类文本时可供选择的可用标签列表,或包含标签及其描述的字典。 |
default_label |
Optional[Union[str, List[str]]]
|
当文本含糊不清或缺乏足够的分类信息时使用的默认标签。在多个标签的情况下可以是列表 (n>1)。 |
示例
为文本分配情感
from distilabel.steps.tasks import TextClassification
from distilabel.models import InferenceEndpointsLLM
llm = InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
tokenizer_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
)
text_classification = TextClassification(
llm=llm,
context="You are an AI system specialized in assigning sentiment to movies.",
available_labels=["positive", "negative"],
)
text_classification.load()
result = next(
text_classification.process(
[{"text": "This was a masterpiece. Not completely faithful to the books, but enthralling from beginning to end. Might be my favorite of the three."}]
)
)
# result
# [{'text': 'This was a masterpiece. Not completely faithful to the books, but enthralling from beginning to end. Might be my favorite of the three.',
# 'labels': 'positive',
# 'distilabel_metadata': {'raw_output_text_classification_0': '{\n "labels": "positive"\n}',
# 'raw_input_text_classification_0': [{'role': 'system',
# 'content': 'You are an AI system specialized in generating labels to classify pieces of text. Your sole purpose is to analyze the given text and provide appropriate classification labels.'},
# {'role': 'user',
# 'content': '# Instruction\nPlease classify the user query by assigning the most appropriate labels.\nDo not explain your reasoning or provide any additional commentary.\nIf the text is ambiguous or lacks sufficient information for classification, respond with "Unclassified".\nProvide the label that best describes the text.\nYou are an AI system specialized in assigning sentiment to movie the user queries.\n## Labeling the user input\nUse the available labels to classify the user query. Analyze the context of each label specifically:\navailable_labels = [\n "positive", # The text shows positive sentiment\n "negative", # The text shows negative sentiment\n]\n\n\n## User Query\n```\nThis was a masterpiece. Not completely faithful to the books, but enthralling from beginning to end. Might be my favorite of the three.\n```\n\n## Output Format\nNow, please give me the labels in JSON format, do not include any other text in your response:\n```\n{\n "labels": "label"\n}\n```'}]},
# 'model_name': 'meta-llama/Meta-Llama-3.1-70B-Instruct'}]
使用指定的描述分配预定义的标签
from distilabel.steps.tasks import TextClassification
text_classification = TextClassification(
llm=llm,
n=1,
context="Determine the intent of the text.",
available_labels={
"complaint": "A statement expressing dissatisfaction or annoyance about a product, service, or experience. It's a negative expression of discontent, often with the intention of seeking a resolution or compensation.",
"inquiry": "A question or request for information about a product, service, or situation. It's a neutral or curious expression seeking clarification or details.",
"feedback": "A statement providing evaluation, opinion, or suggestion about a product, service, or experience. It can be positive, negative, or neutral, and is often intended to help improve or inform.",
"praise": "A statement expressing admiration, approval, or appreciation for a product, service, or experience. It's a positive expression of satisfaction or delight, often with the intention of encouraging or recommending."
},
query_title="Customer Query",
)
text_classification.load()
result = next(
text_classification.process(
[{"text": "Can you tell me more about your return policy?"}]
)
)
# result
# [{'text': 'Can you tell me more about your return policy?',
# 'labels': 'inquiry',
# 'distilabel_metadata': {'raw_output_text_classification_0': '{\n "labels": "inquiry"\n}',
# 'raw_input_text_classification_0': [{'role': 'system',
# 'content': 'You are an AI system specialized in generating labels to classify pieces of text. Your sole purpose is to analyze the given text and provide appropriate classification labels.'},
# {'role': 'user',
# 'content': '# Instruction\nPlease classify the customer query by assigning the most appropriate labels.\nDo not explain your reasoning or provide any additional commentary.\nIf the text is ambiguous or lacks sufficient information for classification, respond with "Unclassified".\nProvide the label that best describes the text.\nDetermine the intent of the text.\n## Labeling the user input\nUse the available labels to classify the user query. Analyze the context of each label specifically:\navailable_labels = [\n "complaint", # A statement expressing dissatisfaction or annoyance about a product, service, or experience. It\'s a negative expression of discontent, often with the intention of seeking a resolution or compensation.\n "inquiry", # A question or request for information about a product, service, or situation. It\'s a neutral or curious expression seeking clarification or details.\n "feedback", # A statement providing evaluation, opinion, or suggestion about a product, service, or experience. It can be positive, negative, or neutral, and is often intended to help improve or inform.\n "praise", # A statement expressing admiration, approval, or appreciation for a product, service, or experience. It\'s a positive expression of satisfaction or delight, often with the intention of encouraging or recommending.\n]\n\n\n## Customer Query\n```\nCan you tell me more about your return policy?\n```\n\n## Output Format\nNow, please give me the labels in JSON format, do not include any other text in your response:\n```\n{\n "labels": "label"\n}\n```'}]},
# 'model_name': 'meta-llama/Meta-Llama-3.1-70B-Instruct'}]
没有预定义标签的自由多标签分类
from distilabel.steps.tasks import TextClassification
text_classification = TextClassification(
llm=llm,
n=3,
context=(
"Describe the main themes, topics, or categories that could describe the "
"following type of persona."
),
query_title="Example of Persona",
)
text_classification.load()
result = next(
text_classification.process(
[{"text": "A historian or curator of Mexican-American history and culture focused on the cultural, social, and historical impact of the Mexican presence in the United States."}]
)
)
# result
# [{'text': 'A historian or curator of Mexican-American history and culture focused on the cultural, social, and historical impact of the Mexican presence in the United States.',
# 'labels': ['Historical Researcher',
# 'Cultural Specialist',
# 'Ethnic Studies Expert'],
# 'distilabel_metadata': {'raw_output_text_classification_0': '{\n "labels": ["Historical Researcher", "Cultural Specialist", "Ethnic Studies Expert"]\n}',
# 'raw_input_text_classification_0': [{'role': 'system',
# 'content': 'You are an AI system specialized in generating labels to classify pieces of text. Your sole purpose is to analyze the given text and provide appropriate classification labels.'},
# {'role': 'user',
# 'content': '# Instruction\nPlease classify the example of persona by assigning the most appropriate labels.\nDo not explain your reasoning or provide any additional commentary.\nIf the text is ambiguous or lacks sufficient information for classification, respond with "Unclassified".\nProvide a list of 3 labels that best describe the text.\nDescribe the main themes, topics, or categories that could describe the following type of persona.\nUse clear, widely understood terms for labels.Avoid overly specific or obscure labels unless the text demands it.\n\n\n## Example of Persona\n```\nA historian or curator of Mexican-American history and culture focused on the cultural, social, and historical impact of the Mexican presence in the United States.\n```\n\n## Output Format\nNow, please give me the labels in JSON format, do not include any other text in your response:\n```\n{\n "labels": ["label_0", "label_1", "label_2"]\n}\n```'}]},
# 'model_name': 'meta-llama/Meta-Llama-3.1-70B-Instruct'}]
源代码位于 src/distilabel/steps/tasks/text_classification.py
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 |
|
inputs
property
¶
任务的输入是 instruction
。
outputs
property
¶
该任务的输出是 generation
和 model_name
。
_get_available_labels_message()
¶
准备要显示的消息,具体取决于可用标签(如果有)以及标签是否具有特定上下文。
源代码位于 src/distilabel/steps/tasks/text_classification.py
_get_examples_message()
¶
准备要显示的消息,具体取决于提供的示例。
源代码位于 src/distilabel/steps/tasks/text_classification.py
format_input(input)
¶
输入被格式化为 ChatType
,假设指令是用户在对话中的首次互动。
源代码位于 src/distilabel/steps/tasks/text_classification.py
format_output(output, input=None)
¶
输出格式化为包含 generation
的字典。model_name
将自动包含在 Task
的 process
方法中。
源代码位于 src/distilabel/steps/tasks/text_classification.py
get_structured_output()
¶
创建要传递给 LLM 的 json 模式,以强制生成一个字典,该字典的输出可以直接解析为 python 字典。
返回
类型 | 描述 |
---|---|
Dict[str, Any]
|
强制执行的响应的 JSON 模式。 |
源代码位于 src/distilabel/steps/tasks/text_classification.py
_format_structured_output(output)
¶
解析结构化响应,该响应应对应于包含 labels
的字典,以及包含标签的字符串或字符串列表。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
output
|
str
|
来自 |
必需 |
返回
类型 | 描述 |
---|---|
Dict[str, Union[str, List[str]]]
|
格式化后的输出。 |
源代码位于 src/distilabel/steps/tasks/text_classification.py
ChatGeneration
¶
基类:Task
根据对话生成文本。
ChatGeneration
是一个预定义的任务,它将 messages
定义为输入,并将 generation
定义为输出。此任务用于根据对话生成文本。model_name
也作为输出的一部分返回,以增强输出。
输入列
- messages (
List[Dict[Literal["role", "content"], str]]
): 用于生成后续补全的消息。
输出列
- generation (
str
): 助手生成的文本。 - model_name (
str
): 用于生成文本的模型名称。
类别
- chat-generation
图标
:material-chat
示例
从 OpenAI 聊天格式的对话生成文本
from distilabel.steps.tasks import ChatGeneration
from distilabel.models import InferenceEndpointsLLM
# Consider this as a placeholder for your actual LLM.
chat = ChatGeneration(
llm=InferenceEndpointsLLM(
model_id="mistralai/Mistral-7B-Instruct-v0.2",
)
)
chat.load()
result = next(
chat.process(
[
{
"messages": [
{"role": "user", "content": "How much is 2+2?"},
]
}
]
)
)
# result
# [
# {
# 'messages': [{'role': 'user', 'content': 'How much is 2+2?'}],
# 'model_name': 'mistralai/Mistral-7B-Instruct-v0.2',
# 'generation': '4',
# }
# ]
源代码位于 src/distilabel/steps/tasks/text_generation.py
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 |
|
inputs
property
¶
该任务的输入是 messages
。
outputs
property
¶
该任务的输出是 generation
和 model_name
。
format_input(input)
¶
输入格式化为 ChatType
,假设提供的消息已经以这种方式格式化,即遵循 OpenAI 聊天格式。
源代码位于 src/distilabel/steps/tasks/text_generation.py
format_output(output, input=None)
¶
输出格式化为包含 generation
的字典。model_name
将自动包含在 Task
的 process
方法中。
源代码位于 src/distilabel/steps/tasks/text_generation.py
TextGeneration
¶
基类:Task
使用 LLM
根据提示生成文本。
TextGeneration
是一个预定义的任务,允许使用 Jinja2 语法传递自定义提示。默认情况下,输入中需要 instruction
,但使用 template
和 columns
属性可以定义自定义提示和文本中预期的列。此任务应足以满足不需要对 LLM 生成的响应进行后处理的任务。
属性
名称 | 类型 | 描述 |
---|---|---|
system_prompt |
Union[str, None]
|
在生成中使用的系统提示。如果未提供,则将检查输入行是否有名为 |
template |
str
|
用于生成的模板。它必须遵循 Jinja2 模板语法。如果未提供,它将假定传递的文本是指令并构造适当的模板。 |
columns |
Union[str, List[str]]
|
columns |
use_system_prompt |
bool
|
DEPRECATED。将在 1.5.0 版本中移除。是否在生成中使用系统提示。默认为 |
输入列
- 输入 (dynamic (由
columns
属性确定)): 默认情况下将设置为instruction
。列可以指向要在模板中使用的str
或List[str]
。
输出列
- generation (
str
): 生成的文本。 - model_name (
str
): 用于生成文本的模型名称。
类别
- 文本生成
示例
从指令生成文本
from distilabel.steps.tasks import TextGeneration
from distilabel.models import InferenceEndpointsLLM
# Consider this as a placeholder for your actual LLM.
text_gen = TextGeneration(
llm=InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
)
)
text_gen.load()
result = next(
text_gen.process(
[{"instruction": "your instruction"}]
)
)
# result
# [
# {
# 'instruction': 'your instruction',
# 'model_name': 'meta-llama/Meta-Llama-3.1-70B-Instruct',
# 'generation': 'generation',
# }
# ]
使用自定义模板生成文本
from distilabel.steps.tasks import TextGeneration
from distilabel.models import InferenceEndpointsLLM
CUSTOM_TEMPLATE = '''Document:
{{ document }}
Question: {{ question }}
Please provide a clear and concise answer to the question based on the information in the document and your general knowledge:
'''.rstrip()
text_gen = TextGeneration(
llm=InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
),
system_prompt="You are a helpful AI assistant. Your task is to answer the following question based on the provided document. If the answer is not explicitly stated in the document, use your knowledge to provide the most relevant and accurate answer possible. If you cannot answer the question based on the given information, state that clearly.",
template=CUSTOM_TEMPLATE,
columns=["document", "question"],
)
text_gen.load()
result = next(
text_gen.process(
[
{
"document": "The Great Barrier Reef, located off the coast of Australia, is the world's largest coral reef system. It stretches over 2,300 kilometers and is home to a diverse array of marine life, including over 1,500 species of fish. However, in recent years, the reef has faced significant challenges due to climate change, with rising sea temperatures causing coral bleaching events.",
"question": "What is the main threat to the Great Barrier Reef mentioned in the document?"
}
]
)
)
# result
# [
# {
# 'document': 'The Great Barrier Reef, located off the coast of Australia, is the world's largest coral reef system. It stretches over 2,300 kilometers and is home to a diverse array of marine life, including over 1,500 species of fish. However, in recent years, the reef has faced significant challenges due to climate change, with rising sea temperatures causing coral bleaching events.',
# 'question': 'What is the main threat to the Great Barrier Reef mentioned in the document?',
# 'model_name': 'meta-llama/Meta-Llama-3.1-70B-Instruct',
# 'generation': 'According to the document, the main threat to the Great Barrier Reef is climate change, specifically rising sea temperatures causing coral bleaching events.',
# }
# ]
使用不同系统提示的少量样本学习
from distilabel.steps.tasks import TextGeneration
from distilabel.models import InferenceEndpointsLLM
CUSTOM_TEMPLATE = '''Generate a clear, single-sentence instruction based on the following examples:
{% for example in examples %}
Example {{ loop.index }}:
Instruction: {{ example }}
{% endfor %}
Now, generate a new instruction in a similar style:
'''.rstrip()
text_gen = TextGeneration(
llm=InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
),
template=CUSTOM_TEMPLATE,
columns="examples",
)
text_gen.load()
result = next(
text_gen.process(
[
{
"examples": ["This is an example", "Another relevant example"],
"system_prompt": "You are an AI assistant specialised in cybersecurity and computing in general, you make your point clear without any explanations."
}
]
)
)
# result
# [
# {
# 'examples': ['This is an example', 'Another relevant example'],
# 'system_prompt': 'You are an AI assistant specialised in cybersecurity and computing in general, you make your point clear without any explanations.',
# 'model_name': 'meta-llama/Meta-Llama-3.1-70B-Instruct',
# 'generation': 'Disable the firewall on the router',
# }
# ]
源代码位于 src/distilabel/steps/tasks/text_generation.py
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 |
|
inputs
property
¶
该任务的输入默认为 instruction
,或作为输入给出的 columns
。
outputs
property
¶
该任务的输出是 generation
和 model_name
。
_prepare_message_content(input)
¶
准备模板的内容并返回格式化的消息。
源代码位于 src/distilabel/steps/tasks/text_generation.py
format_input(input)
¶
输入被格式化为 ChatType
,假设指令是用户在对话中的首次互动。
源代码位于 src/distilabel/steps/tasks/text_generation.py
format_output(output, input=None)
¶
输出格式化为包含 generation
的字典。model_name
将自动包含在 Task
的 process
方法中。
源代码位于 src/distilabel/steps/tasks/text_generation.py
TextGenerationWithImage
¶
基类: TextGeneration
使用 LLM
根据提示和图像生成文本。
`TextGenerationWithImage` is a pre-defined task that allows passing a custom prompt using the
Jinja2 syntax. By default, a `instruction` is expected in the inputs, but the using
`template` and `columns` attributes one can define a custom prompt and columns expected
from the text. Additionally, an `image` column is expected containing one of the
url, base64 encoded image or PIL image. This task inherits from `TextGeneration`,
so all the functionality available in that task related to the prompt will be available
here too.
Attributes:
system_prompt: The system prompt to use in the generation.
If not, then no system prompt will be used. Defaults to `None`.
template: The template to use for the generation. It must follow the Jinja2 template
syntax. If not provided, it will assume the text passed is an instruction and
construct the appropriate template.
columns: A string with the column, or a list with columns expected in the template.
Take a look at the examples for more information. Defaults to `instruction`.
image_type: The type of the image provided, this will be used to preprocess if necessary.
Must be one of "url", "base64" or "PIL".
Input columns:
- dynamic (determined by `columns` attribute): By default will be set to `instruction`.
The columns can point both to a `str` or a `list[str]` to be used in the template.
- image: The column containing the image URL, base64 encoded image or PIL image.
Output columns:
- generation (`str`): The generated text.
- model_name (`str`): The name of the model used to generate the text.
Categories:
- text-generation
References:
- [Jinja2 Template Designer Documentation](https://jinja.flask.org.cn/en/3.1.x/templates/)
- [Image-Text-to-Text](https://hugging-face.cn/tasks/image-text-to-text)
- [OpenAI Vision](https://platform.openai.com/docs/guides/vision)
Examples:
Answer questions from an image:
```python
from distilabel.steps.tasks import TextGenerationWithImage
from distilabel.models.llms import InferenceEndpointsLLM
vision = TextGenerationWithImage(
name="vision_gen",
llm=InferenceEndpointsLLM(
model_id="meta-llama/Llama-3.2-11B-Vision-Instruct",
),
image_type="url"
)
vision.load()
result = next(
vision.process(
[
{
"instruction": "What’s in this image?",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"
}
]
)
)
# result
# [
# {
# "instruction": "What’s in this image?",
# "image": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg",
# "generation": "Based on the visual cues in the image...",
# "model_name": "meta-llama/Llama-3.2-11B-Vision-Instruct"
# ... # distilabel_metadata would be here
# }
# ]
# result[0]["generation"]
# "Based on the visual cues in the image, here are some possible story points:
- 图像的特色是一条木制木板路,穿过一片茂盛的草地,可能是在公园或自然保护区。
分析和想法:* 丰富的绿草和树木表明生态系统或栖息地健康。* 根据周围环境,可能存在鸟类或鹿等野生动物。* 人行天桥或小路可能是该区域的常见特征,可通往附近的景点或兴趣点。
要提出的其他问题:* 为什么该区域存在人行天桥?* 该地区栖息着什么样的野生动物?
Answer questions from an image stored as base64:
```python
# For this example we will assume that we have the string representation of the image
# stored, but will just take the image and transform it to base64 to ilustrate the example.
import requests
import base64
image_url ="https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"
img = requests.get(image_url).content
base64_image = base64.b64encode(img).decode("utf-8")
from distilabel.steps.tasks import TextGenerationWithImage
from distilabel.models.llms import InferenceEndpointsLLM
vision = TextGenerationWithImage(
name="vision_gen",
llm=InferenceEndpointsLLM(
model_id="meta-llama/Llama-3.2-11B-Vision-Instruct",
),
image_type="base64"
)
vision.load()
result = next(
vision.process(
[
{
"instruction": "What’s in this image?",
"image": base64_image
}
]
)
)
源代码位于 src/distilabel/steps/tasks/text_generation_with_image.py
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 |
|
_transform_image(image)
¶
根据 image_type
属性转换图像。
源代码位于 src/distilabel/steps/tasks/text_generation_with_image.py
_prepare_message_content(input)
¶
准备模板的内容并返回格式化的消息。
源代码位于 src/distilabel/steps/tasks/text_generation_with_image.py
format_input(input)
¶
输入被格式化为 ChatType
,假设指令是用户在对话中的首次互动。
源代码位于 src/distilabel/steps/tasks/text_generation_with_image.py
UltraFeedback
¶
基类:Task
使用 LLM
对关注不同方面的生成结果进行排序。
UltraFeedback:通过高质量反馈提升语言模型。
属性
名称 | 类型 | 描述 |
---|---|---|
aspect |
Literal['helpfulness', 'honesty', 'instruction-following', 'truthfulness', 'overall-rating']
|
使用 |
输入列
- instruction (
str
): 用于评估文本输出的参考指令。 - generations (
List[str]
): 要针对给定指令评估的文本输出。
输出列
- ratings (
List[float]
): 每个提供的文本输出的评分。 - rationales (
List[str]
): 每个提供的文本输出的理由。 - model_name (
str
): 用于生成评分和理由的模型名称。
类别
- preference
示例
根据所选方面对来自不同 LLM 的生成结果进行评分
from distilabel.steps.tasks import UltraFeedback
from distilabel.models import InferenceEndpointsLLM
# Consider this as a placeholder for your actual LLM.
ultrafeedback = UltraFeedback(
llm=InferenceEndpointsLLM(
model_id="mistralai/Mistral-7B-Instruct-v0.2",
),
use_default_structured_output=False
)
ultrafeedback.load()
result = next(
ultrafeedback.process(
[
{
"instruction": "How much is 2+2?",
"generations": ["4", "and a car"],
}
]
)
)
# result
# [
# {
# 'instruction': 'How much is 2+2?',
# 'generations': ['4', 'and a car'],
# 'ratings': [1, 2],
# 'rationales': ['explanation for 4', 'explanation for and a car'],
# 'model_name': 'mistralai/Mistral-7B-Instruct-v0.2',
# }
# ]
使用默认结构化输出,根据 honesty 对来自不同 LLM 的生成结果进行评分
from distilabel.steps.tasks import UltraFeedback
from distilabel.models import InferenceEndpointsLLM
# Consider this as a placeholder for your actual LLM.
ultrafeedback = UltraFeedback(
llm=InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
),
aspect="honesty"
)
ultrafeedback.load()
result = next(
ultrafeedback.process(
[
{
"instruction": "How much is 2+2?",
"generations": ["4", "and a car"],
}
]
)
)
# result
# [{'instruction': 'How much is 2+2?',
# 'generations': ['4', 'and a car'],
# 'ratings': [5, 1],
# 'rationales': ['The response is correct and confident, as it directly answers the question without expressing any uncertainty or doubt.',
# "The response is confidently incorrect, as it provides unrelated information ('a car') and does not address the question. The model shows no uncertainty or indication that it does not know the answer."],
# 'distilabel_metadata': {'raw_output_ultra_feedback_0': '{"ratings": [\n 5,\n 1\n] \n\n,"rationales": [\n "The response is correct and confident, as it directly answers the question without expressing any uncertainty or doubt.",\n "The response is confidently incorrect, as it provides unrelated information ('a car') and does not address the question. The model shows no uncertainty or indication that it does not know the answer."\n] }'},
# 'model_name': 'meta-llama/Meta-Llama-3.1-70B-Instruct'}]
使用默认结构化输出,根据 helpfulness 对来自不同 LLM 的生成结果进行评分
from distilabel.steps.tasks import UltraFeedback
from distilabel.models import InferenceEndpointsLLM
# Consider this as a placeholder for your actual LLM.
ultrafeedback = UltraFeedback(
llm=InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3.1-70B-Instruct",
generation_kwargs={"max_new_tokens": 512},
),
aspect="helpfulness"
)
ultrafeedback.load()
result = next(
ultrafeedback.process(
[
{
"instruction": "How much is 2+2?",
"generations": ["4", "and a car"],
}
]
)
)
# result
# [{'instruction': 'How much is 2+2?',
# 'generations': ['4', 'and a car'],
# 'ratings': [1, 5],
# 'rationales': ['Text 1 is clear and relevant, providing the correct answer to the question. It is also not lengthy and does not contain repetition. However, it lacks comprehensive information or detailed description.',
# 'Text 2 is neither clear nor relevant to the task. It does not provide any useful information and seems unrelated to the question.'],
# 'rationales_for_rating': ['Text 1 is rated as Correct (3) because it provides the accurate answer to the question, but lacks comprehensive information or detailed description.',
# 'Text 2 is rated as Severely Incorrect (1) because it does not provide any relevant information and seems unrelated to the question.'],
# 'types': [1, 3, 1],
# 'distilabel_metadata': {'raw_output_ultra_feedback_0': '{ \n "ratings": [\n 1,\n 5\n ]\n ,\n "rationales": [\n "Text 1 is clear and relevant, providing the correct answer to the question. It is also not lengthy and does not contain repetition. However, it lacks comprehensive information or detailed description.",\n "Text 2 is neither clear nor relevant to the task. It does not provide any useful information and seems unrelated to the question."\n ]\n ,\n "rationales_for_rating": [\n "Text 1 is rated as Correct (3) because it provides the accurate answer to the question, but lacks comprehensive information or detailed description.",\n "Text 2 is rated as Severely Incorrect (1) because it does not provide any relevant information and seems unrelated to the question."\n ]\n ,\n "types": [\n 1, 3,\n 1\n ]\n }'},
# 'model_name': 'meta-llama/Meta-Llama-3.1-70B-Instruct'}]
引用
@misc{cui2024ultrafeedbackboostinglanguagemodels,
title={UltraFeedback: Boosting Language Models with Scaled AI Feedback},
author={Ganqu Cui and Lifan Yuan and Ning Ding and Guanming Yao and Bingxiang He and Wei Zhu and Yuan Ni and Guotong Xie and Ruobing Xie and Yankai Lin and Zhiyuan Liu and Maosong Sun},
year={2024},
eprint={2310.01377},
archivePrefix={arXiv},
primaryClass={cs.CL},
url={https://arxiv.org/abs/2310.01377},
}
源代码位于 src/distilabel/steps/tasks/ultrafeedback.py
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 |
|
inputs
property
¶
该任务的输入是 instruction
和其对应的 generations
。
outputs
property
¶
该任务的输出是 generation
和 model_name
。
load()
¶
加载给定 aspect
的 Jinja2 模板。
源代码位于 src/distilabel/steps/tasks/ultrafeedback.py
format_input(input)
¶
输入被格式化为 ChatType
,假设指令是用户在对话中的首次互动。
源代码位于 src/distilabel/steps/tasks/ultrafeedback.py
format_output(output, input=None)
¶
输出格式为字典,其中包含针对给定 instruction
的每个提供的 generations
的 ratings
和 rationales
。model_name
将自动包含在 Task
的 process
方法中。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
output
|
Union[str, None]
|
一个字符串,表示通过 |
必需 |
input
|
Union[Dict[str, Any], None]
|
任务的输入,某些任务需要输入以格式化输出。 |
None
|
返回
类型 | 描述 |
---|---|
Dict[str, Any]
|
一个字典,其中包含针对提供的 |
Dict[str, Any]
|
如果提供的方面是 |
Dict[str, Any]
|
|
Dict[str, Any]
|
如果提供的方面是 |
Dict[str, Any]
|
给定 |
源代码位于 src/distilabel/steps/tasks/ultrafeedback.py
_format_ratings_rationales_output(output, input)
¶
当方面是 honesty
、instruction-following
或 overall-rating
时,格式化输出。
源代码位于 src/distilabel/steps/tasks/ultrafeedback.py
_format_types_ratings_rationales_output(output, input)
¶
当方面是 helpfulness
或 truthfulness
时,格式化输出。
源代码位于 src/distilabel/steps/tasks/ultrafeedback.py
get_structured_output()
¶
创建要传递给 LLM 的 json 模式,以强制生成一个字典,该字典的输出可以直接解析为 python 字典。
该模式对应于以下内容
from pydantic import BaseModel
from typing import List
class SchemaUltraFeedback(BaseModel):
ratings: List[int]
rationales: List[str]
class SchemaUltraFeedbackWithType(BaseModel):
types: List[Optional[int]]
ratings: List[int]
rationales: List[str]
rationales_for_rating: List[str]
返回
类型 | 描述 |
---|---|
Dict[str, Any]
|
强制执行的响应的 JSON 模式。 |
源代码位于 src/distilabel/steps/tasks/ultrafeedback.py
_format_structured_output(output, input)
¶
解析结构化响应,该响应应对应于一个字典,其中包含 positive
或 positive
和 negative
键。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
output
|
str
|
来自 |
必需 |
返回
类型 | 描述 |
---|---|
Dict[str, Any]
|
格式化后的输出。 |
源代码位于 src/distilabel/steps/tasks/ultrafeedback.py
URIAL
¶
基类: Task
使用非指令微调模型生成响应。
URIAL
是一个预定义的任务,它使用非指令微调模型生成响应。此任务用于根据作为输入提供的对话生成响应。
输入列
- instruction (
str
, optional): 用于生成响应的指令(可选)。 - conversation (
List[Dict[str, str]]
, optional): 用于生成响应的对话(可选)(最后一条消息必须来自用户)。
输出列
- generation (
str
): 生成的响应。 - model_name (
str
): 用于生成响应的模型的名称。
类别
- 文本生成
示例
从指令生成文本
from distilabel.models import vLLM
from distilabel.steps.tasks import URIAL
step = URIAL(
llm=vLLM(
model="meta-llama/Meta-Llama-3.1-8B",
generation_kwargs={"temperature": 0.7},
),
)
step.load()
results = next(
step.process(inputs=[{"instruction": "What's the most most common type of cloud?"}])
)
# [
# {
# 'instruction': "What's the most most common type of cloud?",
# 'generation': 'Clouds are classified into three main types, high, middle, and low. The most common type of cloud is the middle cloud.',
# 'distilabel_metadata': {...},
# 'model_name': 'meta-llama/Meta-Llama-3.1-8B'
# }
# ]
源代码位于 src/distilabel/steps/tasks/urial.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 |
|
load()
¶
加载给定 aspect
的 Jinja2 模板。
源代码位于 src/distilabel/steps/tasks/urial.py
task(inputs=None, outputs=None)
¶
从格式化输出函数创建 Task
。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
inputs
|
Union[StepColumns, None]
|
包含输入列/键名称的列表,或一个字典,其中键是列,值是布尔值,指示步骤是否需要该列。如果未提供,则默认值将为空列表 |
None
|
outputs
|
Union[StepColumns, None]
|
包含输出列/键名称的列表,或一个字典,其中键是列,值是布尔值,指示是否将生成该列。如果未提供,则默认值将为空列表 |
None
|