Transformers documentation
文本生成
文本生成
文本生成是大语言模型(LLM)最流行的应用。LLM 经过训练,可以根据给定的初始文本(prompt)以及其自身已生成的输出,生成下一个词(token),直到达到预定义的长度或遇到序列结束(EOS)token。
在 Transformers 中,generate() API 负责处理文本生成,并且适用于所有具备生成能力的模型。本指南将介绍使用 generate() 进行文本生成的基础知识,以及需要避免的一些常见陷阱。
对于以下命令,请确保
transformers serve正在运行。transformers chat Qwen/Qwen2.5-0.5B-Instruct
默认 generate
在开始之前,建议安装 bitsandbytes 以量化超大模型,从而降低其内存占用。
!pip install -U transformers bitsandbytes
除了基于 CUDA 的 GPU,Bitsandbytes 还支持多种后端。有关详细信息,请参阅多后端安装指南。
使用 from_pretrained() 加载 LLM,并添加以下两个参数以降低内存需求。
device_map="auto"启用了 Accelerate 的 Big Model Inference 功能,该功能会自动初始化模型骨架,并将模型权重加载并分发到所有可用设备上,优先使用最快的设备(GPU)。quantization_config是一个用于定义量化设置的配置对象。本示例使用 bitsandbytes 作为量化后端(有关更多可用后端,请参阅 量化 部分),并以 4 位 加载模型。
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
quantization_config = BitsAndBytesConfig(load_in_4bit=True)
model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-v0.1", device_map="auto", quantization_config=quantization_config)对输入进行分词,并将 padding_side() 参数设置为 "left",因为 LLM 并未针对从填充标记继续生成进行训练。分词器会返回输入 ID 和注意力掩码。
通过向分词器传入字符串列表,可以一次处理多个提示。对输入进行批处理可以在略微增加延迟和内存开销的情况下提高吞吐量。
tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1", padding_side="left")
model_inputs = tokenizer(["A list of colors: red, blue"], return_tensors="pt").to(model.device)将输入传递给 generate() 以生成 token,然后使用 batch_decode() 将生成的 token 解码回文本。
generated_ids = model.generate(**model_inputs)
tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
"A list of colors: red, blue, green, yellow, orange, purple, pink,"生成配置
所有生成设置都包含在 GenerationConfig 中。在上面的示例中,生成设置源自 mistralai/Mistral-7B-v0.1 的 generation_config.json 文件。如果模型未保存任何配置,则会使用默认的解码策略。
通过 generation_config 属性检查配置。它仅显示与默认配置不同的值,在本例中为 bos_token_id 和 eos_token_id。
from transformers import AutoModelForCausalLM
model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-v0.1", device_map="auto")
model.generation_config
GenerationConfig {
"bos_token_id": 1,
"eos_token_id": 2
}您可以通过覆盖 GenerationConfig 中的参数和值来自定义 generate()。有关常用调整参数,请参阅下文中的此部分。
# enable beam search sampling strategy
model.generate(**inputs, num_beams=4, do_sample=True)generate() 还可以通过外部库或自定义代码进行扩展:
logits_processor参数接受自定义的 LogitsProcessor 实例,用于操作下一个 token 的概率分布;stopping_criteria参数支持自定义的 StoppingCriteria,用于停止文本生成;- 其他自定义生成方法可以通过
custom_generate标志加载(文档)。
请参阅生成策略指南,以了解有关搜索、采样和解码策略的更多信息。
保存
创建一个 GenerationConfig 实例,并指定所需的解码参数。
from transformers import AutoModelForCausalLM, GenerationConfig
model = AutoModelForCausalLM.from_pretrained("my_account/my_model")
generation_config = GenerationConfig(
max_new_tokens=50, do_sample=True, top_k=50, eos_token_id=model.config.eos_token_id
)使用 save_pretrained() 保存特定的生成配置,并将 push_to_hub 参数设置为 True 以将其上传到 Hub。
generation_config.save_pretrained("my_account/my_model", push_to_hub=True)将 config_file_name 参数留空。当在单个目录中存储多个生成配置时,应使用此参数。它提供了一种指定要加载哪个生成配置的方法。您可以为不同的生成任务(如使用采样的创意文本生成、使用束搜索的摘要生成)创建不同的配置,供单个模型使用。
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer, GenerationConfig
tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-small")
model = AutoModelForSeq2SeqLM.from_pretrained("google-t5/t5-small")
translation_generation_config = GenerationConfig(
num_beams=4,
early_stopping=True,
decoder_start_token_id=0,
eos_token_id=model.config.eos_token_id,
pad_token=model.config.pad_token_id,
)
translation_generation_config.save_pretrained("/tmp", config_file_name="translation_generation_config.json", push_to_hub=True)
generation_config = GenerationConfig.from_pretrained("/tmp", config_file_name="translation_generation_config.json")
inputs = tokenizer("translate English to French: Configuration files are easy to use!", return_tensors="pt")
outputs = model.generate(**inputs, generation_config=generation_config)
print(tokenizer.batch_decode(outputs, skip_special_tokens=True))常用选项
generate() 是一个功能强大的工具,可以进行高度自定义。对于新用户来说,这可能会令人望而生畏。本节列出了在 Transformers 中大多数文本生成工具(如 generate()、GenerationConfig、pipelines、chat CLI 等)中可定义的常用生成选项:
| 选项名称 | 类型 | 简化描述 |
|---|---|---|
max_new_tokens | int | 控制最大生成长度。请务必定义该参数,因为其默认值通常较小。 |
do_sample | bool | 定义生成时是否对下一个 token 进行采样(True),还是采用贪心策略(False)。大多数使用场景应将该标志设置为 True。更多信息请参见此指南。 |
temperature | float | 下一个被选中的 token 的不可预测程度。较高的值(>0.8)适合创意类任务,较低的值(例如 <0.4)适合需要“思考”的任务。需要设置 do_sample=True。 |
num_beams | int | 当设置为 >1 时,将启用 beam search 算法。Beam search 在基于输入的任务上表现良好。有关更多信息,请参阅 此指南。 |
repetition_penalty | float | 如果模型经常重复自身,请将其设置为 >1.0。值越大,施加的惩罚越大。 |
eos_token_id | list[int] | 用于停止生成的标记。默认值通常已经足够好,但您也可以指定其他标记。 |
常见陷阱
以下部分介绍了一些在文本生成过程中可能遇到的常见问题及其解决方法。
输出长度
generate() 默认最多返回 20 个 token,除非在模型的 GenerationConfig 中另有指定。强烈建议通过 max_new_tokens 参数手动设置生成的 token 数量,以控制输出长度。Decoder-only 模型会返回初始提示词以及生成的 token。
model_inputs = tokenizer(["A sequence of numbers: 1, 2"], return_tensors="pt").to(model.device)generated_ids = model.generate(**model_inputs)
tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
'A sequence of numbers: 1, 2, 3, 4, 5'generated_ids = model.generate(**model_inputs, max_new_tokens=50)
tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
'A sequence of numbers: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,'解码策略
generate() 的默认解码策略是 greedy search(贪心搜索),它会选择下一个最可能的 token,除非在模型的 GenerationConfig 中另有指定。虽然这种解码策略在基于输入的任务(如转录、翻译)中表现良好,但对于更具创造性的用例(如故事创作、聊天应用)来说并非最优选择。
例如,启用多项式采样策略以生成更多样的输出。有关更多解码策略,请参阅生成策略指南。
model_inputs = tokenizer(["I am a cat."], return_tensors="pt").to(model.device)generated_ids = model.generate(**model_inputs)
tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]generated_ids = model.generate(**model_inputs, do_sample=True)
tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]填充侧
如果输入长度不一致,需要进行填充。但 LLM 并未针对从填充 token 继续生成进行训练,因此需要将 padding_side() 参数设置为输入的左侧。对于状态空间模型和混合模型而言,右侧填充的影响更差,因为它们的循环状态会持续在末尾的填充 token 上更新,导致缓存不再与提示词的末尾相匹配。
model_inputs = tokenizer(
["1, 2, 3", "A, B, C, D, E"], padding=True, return_tensors="pt"
).to(model.device)
generated_ids = model.generate(**model_inputs)
tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
'1, 2, 33333333333'tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1", padding_side="left")
tokenizer.pad_token = tokenizer.eos_token
model_inputs = tokenizer(
["1, 2, 3", "A, B, C, D, E"], padding=True, return_tensors="pt"
).to(model.device)
generated_ids = model.generate(**model_inputs)
tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
'1, 2, 3, 4, 5, 6,'提示格式
某些模型和任务要求特定的输入提示格式,如果格式不正确,模型将返回次优的输出。您可以在提示工程指南中了解有关提示的更多信息。
例如,聊天模型期望输入为聊天模板。你的提示词应包含role和content,以指明对话的参与者。如果你尝试将提示词作为单个字符串传入,模型并不总能返回预期的输出。
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
tokenizer = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-alpha")
model = AutoModelForCausalLM.from_pretrained(
"HuggingFaceH4/zephyr-7b-alpha", device_map="auto", quantization_config=BitsAndBytesConfig(load_in_4bit=True)
)prompt = """How many cats does it take to change a light bulb? Reply as a pirate."""
model_inputs = tokenizer([prompt], return_tensors="pt").to(model.device)
input_length = model_inputs.input_ids.shape[1]
generated_ids = model.generate(**model_inputs, max_new_tokens=50)
print(tokenizer.batch_decode(generated_ids[:, input_length:], skip_special_tokens=True)[0])
"Aye, matey! 'Tis a simple task for a cat with a keen eye and nimble paws. First, the cat will climb up the ladder, carefully avoiding the rickety rungs. Then, with"messages = [
{
"role": "system",
"content": "You are a friendly chatbot who always responds in the style of a pirate",
},
{"role": "user", "content": "How many cats does it take to change a light bulb?"},
]
model_inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt").to(model.device)
input_length = model_inputs["input_ids"].shape[1]
generated_ids = model.generate(**model_inputs, do_sample=True, max_new_tokens=50)
print(tokenizer.batch_decode(generated_ids[:, input_length:], skip_special_tokens=True)[0])
"Arr, matey! According to me beliefs, 'twas always one cat to hold the ladder and another to climb up it an’ change the light bulb, but if yer looking to save some catnip, maybe yer can资源
请查看下方更多具体且专业的文本生成库。
- Optimum:Transformers 的扩展,专注于在特定硬件设备上优化训练和推理
- Outlines:一个用于约束文本生成的库(例如生成 JSON 文件)。
- SynCode:一个用于上下文无关文法引导生成(JSON、SQL、Python)的库。
- Text Generation Inference:一个面向 LLM 的生产级服务器。
- 文本生成 Web UI:用于文本生成的 Gradio Web 界面。
- logits-processor-zoo:用于控制文本生成的额外 logits 处理器。