大模型文本生成解码策略概览

介绍贪心搜索作为默认解码策略的机制,并说明自定义生成方法可让模型在不确定时继续思考、在卡住时回滚生成,为文本生成任务提供基础与扩展思路。

Copyright 2024 HuggingFace Team. 全权保留. 根据 Apache 许可, 版本 2.0 (“ License ”) 获得许可; 您不能使用此文件, 除非符合 您可在下列地点获得许可证副本: http://www.apache.org/licenses/LICENSE-2.0 除非适用法律要求或书面同意,否则根据许可证分发的软件在下列网址分发: a " :ASIS"BASIS,WITHOUTWARRANTIESORCONDITIONSOFANYKIND,或明示的或暗示的。 《许可证》规定的许可和限制的具体语言。 QQ 注意, 此文件在 Markdown 中, 但包含我们doc- buildinger( 类似于 MDX ) 的特定语法, 可能不是 在您的Markdown 查看器中正确渲染。 # 世代战略 解码策略告诉一个模型应该如何选择下一个生成的符号。 有很多类型的解码策略, 选择合适的策略对生成文本的质量有重大影响 。 此指南将帮助您了解Transformers中可用的不同解码策略以及如何及何时使用这些策略. ## 基本编码方法 这些是既定的解码方法,应该成为文本生成任务的起点. ### 贪婪的搜索 贪婪的搜索是默认的解码策略。 它在每个步骤中选择下一个最可能的符号。 除非在 [`GenerationConfig`],此策略最多生成20新符. 贪婪的搜索对于产出相对较短、但创造力不是优先事项的任务很有效。然而,它由于开始重复,在生成较长的序列时会崩溃。 ```py import torch from transformers import AutoModelForCausalLM, AutoTokenizer from accelerate import Accelerator device = Accelerator().device tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf") inputs = tokenizer("Hugging Face is an open-source company", return_tensors="pt").to(device) model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf", dtype=torch.float16).to(device) # explicitly set to default length because Llama2 generation length is 4096 outputs = model.generate(**inputs, max_new_tokens=20) tokenizer.batch_decode(outputs, skip_special_tokens=True) 'Hugging Face is an open-source company that provides a suite of tools and services for building, deploying, and maintaining natural language processing' ``` ### 取样 抽样,或多名抽样,根据整个模型词汇的概率分布(相对于最可能的符号,如在贪婪的搜索中)随机选择一个符号。这意味着每个非零概率的符号都有被选中的机会。抽样策略可以减少重复,并产生更具创造性和多样化的输出。 启用多名采样方式 `do_sample=True` 财务报告和财务报告 `num_beams=1`. ```py import torch from transformers import AutoModelForCausalLM, AutoTokenizer from accelerate import Accelerator device = Accelerator().device tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf") inputs = tokenizer("Hugging Face is an open-source company", return_tensors="pt").to(device) model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf", dtype=torch.float16).to(device) # explicitly set to 100 because Llama2 generation length is 4096 outputs = model.generate(**inputs, max_new_tokens=50, do_sample=True, num_beams=1) tokenizer.batch_decode(outputs, skip_special_tokens=True) 'Hugging Face is an open-source company 🤗\nWe are open-source and believe that open-source is the best way to build technology. Our mission is to make AI accessible to everyone, and we believe that open-source is the best way to achieve that.' ``` ### 光束搜索 Beam 搜索会跟踪每个时间步骤上数个生成的序列( 束) 。 它会选择最高的序列 。 *总计* 概率 。 与贪婪搜索不同, 此策略可以“ 向前看 ” , 并选择一个整体概率较高的序列, 即使初始符号的概率较低。 它最适合输入基于任务, 如描述图像或语音识别 。 您也可以使用 。 `do_sample=True` 光束搜索在每一个步骤进行采样,但光束搜索仍然会贪婪地从各个步骤之间的低概率序列中排出. > [!TIP] > 检查一下 [束搜索可视化器](https://huggingface.co/spaces/m-ric/beam_search_visualizer) 看光束搜索是如何工作的。 启用带束的搜索 `num_beams` 参数(应该大于1 否则相当于贪婪的搜索). ```py import torch from transformers import AutoModelForCausalLM, AutoTokenizer from accelerate import Accelerator device = Accelerator().device tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf") inputs = tokenizer("Hugging Face is an open-source company", return_tensors="pt").to(device) model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf", dtype=torch.float16).to(device) # explicitly set to 100 because Llama2 generation length is 4096 outputs = model.generate(**inputs, max_new_tokens=50, num_beams=2) tokenizer.batch_decode(outputs, skip_special_tokens=True) "['Hugging Face is an open-source company that develops and maintains the Hugging Face platform, which is a collection of tools and libraries for building and deploying natural language processing (NLP) models. Hugging Face was founded in 2018 by Thomas Wolf']" ``` ## 自定义生成方法 自定义生成方法可以实现专业化行为,例如: - 如果不确定,让模型继续思考; - 如果模型被卡住,就倒置生成; - 处理带有自定义逻辑的特殊符号; - 使用专门的 KV 缓存; 我们通过模型寄存器实现自定义生成方法,假设一个特定的模型标记和文件结构(见下文小节)。 [自定义建模代码](<https://github.com/huggingface/transformers/blob/HEAD/docs/source/en/models.md#custom-models>) 因此,需要设置 `trust_remote_code=True`. 如果一个模型寄存器持有自定义生成方法,最简单的尝试方法是加载模型并与之生成: ```py from transformers import AutoModelForCausalLM, AutoTokenizer # `transformers-community/custom_generate_example` holds a copy of `Qwen/Qwen2.5-0.5B-Instruct`, but # with custom generation code -> calling `generate` uses the custom generation method! tokenizer = AutoTokenizer.from_pretrained("transformers-community/custom_generate_example") model = AutoModelForCausalLM.from_pretrained( "transformers-community/custom_generate_example", device_map="auto", trust_remote_code=True ) inputs = tokenizer(["The quick brown"], return_tensors="pt").to(model.device) # The custom generation method is a minimal greedy decoding implementation. It also prints a custom message at run time. gen_out = model.generate(**inputs) # you should now see its custom message, "✨ using a custom generation method ✨" print(tokenizer.batch_decode(gen_out, skip_special_tokens=True)) 'The quick brown fox jumps over a lazy dog, and the dog is a type of animal. Is' ``` 具有自定义生成方法的模型寄存器具有特殊属性:其生成方法可以从中加载 **任何** 模式通过 [`~GenerationMixin.generate`]'s `custom_generate` 参数。这意味着任何人都可以创建和分享自定义生成方法,从而有可能与任何Transformers模型合作,而不需要用户安装额外的Python软件包。 ```py from transformers import AutoModelForCausalLM, AutoTokenizer tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct") model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct", device_map="auto") inputs = tokenizer(["The quick brown"], return_tensors="pt").to(model.device) # `custom_generate` replaces the original `generate` by the custom generation method defined in # `transformers-community/custom_generate_example` gen_out = model.generate(**inputs, custom_generate="transformers-community/custom_generate_example", trust_remote_code=True) print(tokenizer.batch_decode(gen_out, skip_special_tokens=True)[0]) 'The quick brown fox jumps over a lazy dog, and the dog is a type of animal. Is' ``` 你应该读一下 `README.md` 包含自定义生成策略的寄存器文件,以查看新参数和输出类型差异,如果它们存在的话。否则,可以假设它像基础一样工作 [`~GenerationMixin.generate`] 方法 。 > [!TIP] > 您可以找到所有自定义生成方法 [正在搜索他们的自定义标签 。](https://huggingface.co/models?other=custom_generate), `custom_generate`. 考虑枢纽存储器 [transformers-community/custom_generate_example](https://huggingface.co/transformers-community/custom_generate_example) 举个例子。 `README.md` 指出它有另外的输入论据, `left_padding`,它会在提示前添加一些贴纸符号。 ```py gen_out = model.generate( **inputs, custom_generate="transformers-community/custom_generate_example", trust_remote_code=True, left_padding=5 ) print(tokenizer.batch_decode(gen_out)[0]) '<|endoftext|><|endoftext|><|endoftext|><|endoftext|><|endoftext|>The quick brown fox jumps over the lazy dog.\n\nThe sentence "The quick' ``` 如果自定义方法已锁定了 Python 环境不符合的要求, 你会得到一个关于缺少要求的例外。 例如, [transformers-community/custom_generate_bad_requirements](https://huggingface.co/transformers-community/custom_generate_bad_requirements) 其定义的一套不可能满足的要求 `custom_generate/requirements.txt` 文件,如果您尝试运行,您将看到下面的错误消息。 ```text ImportError: Missing requirements in your local environment for `transformers-community/custom_generate_bad_requirements`: foo (installed: None) bar==0.0.0 (installed: None) torch>=99.0 (installed: 2.6.0) ``` 相应地更新您的 Python 要求将删除此错误消息 。 ### 创建自定义生成方法 要创建新一代方法,需要创建新的 [**型号**](https://huggingface.co/new) 寄存器和将一些文件推入其中。 1. 你设计的模型 你的一代方法。 2. `custom_generate/generate.py`,它包含您自定义生成方法的所有逻辑。 3. `custom_generate/requirements.txt`,用于选择添加新的 Python 要求和/或锁定特定版本以正确使用您的方法。 4. `README.md`中,您应当添加 `custom_generate` 标记和记录您自定义方法中的任何新参数或输出类型差异。 在您添加了所有需要的文件后, 您的寄存器应该像这样 。 ```text your_repo/ ├── README.md # include the 'custom_generate' tag ├── config.json ├── ... └── custom_generate/ ├── generate.py └── requirements.txt ``` #### 添加基准模型 您自定义生成方法的起点是一个模型寄存器, 就像其它的一样。 添加到此寄存器的模型应该是您设计的方法的模型, 它应该是工作自成一体的模型生成器对的一部分。 当此寄存器中的模型装入时, 您的自定义生成器将覆盖 `generate`. 不用担心 - 您的生成方法仍然可以加载到任何其他的Transformers模型中,如上一节所解释的. 如果您只是想要复制一个已有的模型, 您可以这样做 ```py from transformers import AutoModelForCausalLM, AutoTokenizer tokenizer = AutoTokenizer.from_pretrained("source/model_repo") model = AutoModelForCausalLM.from_pretrained("source/model_repo") tokenizer.save_pretrained("your/generation_method", push_to_hub=True) model.save_pretrained("your/generation_method", push_to_hub=True) ``` #### 生成.py 这是你代代方法的核心 *必须* 包含一个命名方法 `generate`,而这种方法 *必须* 包含一个 `model` 参数作为它的第一个参数。 `model` 是模型实例,这意味着您可以访问模型中的所有属性和方法,包括其中定义的属性和方法。 [`GenerationMixin`] (就像基地一样) `generate` 页:1 > [!WARNING] > `generate.py` 必须在命名的文件夹中放置 `custom_generate`,而不是在寄存器的根层。此特性的文件路径是硬编码的。 引擎盖下,当基地 [`~GenerationMixin.generate`] 方法被调用为: `custom_generate` 参数,它首先检查它的 Python 要求(如果有的话),然后查找自定义 `generate` 输入方法 `generate.py`,最后将习惯称为 `generate`。所有收到的论点和 `model` 已转发到您的自定义 `generate` 方法,但用于触发自定义生成的参数除外(`trust_remote_code` 财务报告和财务报告 `custom_generate`). 这表示你 `generate` 可以有如下所示的原生参数和自定义参数的组合(以及不同的输出类型). ```py import torch def generate(model, input_ids, generation_config=None, left_padding=None, **kwargs): generation_config = generation_config or model.generation_config # default to the model generation config cur_length = input_ids.shape[1] max_length = generation_config.max_length or cur_length + generation_config.max_new_tokens # Example of custom argument: add `left_padding` (integer) pad tokens before the prompt if left_padding is not None: if not isinstance(left_padding, int) or left_padding < 0: raise ValueError(f"left_padding must be an integer larger than 0, but is {left_padding}") pad_token = kwargs.pop("pad_token", None) or generation_config.pad_token_id or model.config.pad_token_id if pad_token is None: raise ValueError("pad_token is not defined") batch_size = input_ids.shape[0] pad_tensor = torch.full(size=(batch_size, left_padding), fill_value=pad_token).to(input_ids.device) input_ids = torch.cat((pad_tensor, input_ids), dim=1) cur_length = input_ids.shape[1] # Simple greedy decoding loop while cur_length < max_length: logits = model(input_ids).logits next_token_logits = logits[:, -1, :] next_tokens = torch.argmax(next_token_logits, dim=-1) input_ids = torch.cat((input_ids, next_tokens[:, None]), dim=-1) cur_length += 1 return input_ids ``` 遵循下面推荐的做法,以确保您的自定义生成方法如预期的那样工作。 - 在原件中可以随意重新使用用于验证和输入准备的逻辑 [`~GenerationMixin.generate`]. - 扣紧 `transformers` 如果您使用任何私有方法/属性,则需要使用该版本。 `model`. - 考虑添加模型验证,输入验证,甚至一个单独的测试文件,以帮助用户在他们的环境下对您的代码进行理智检查. 您的习惯 `generate` 方法可以从 `custom_generate` 文件夹。例如,如果您有一个 `utils.py` 文件,您可以这样导入 : ```py from .utils import some_function ``` 仅从同级进口 `custom_generate` 文件夹被支持。父/父文件夹导入无效。 `custom_generate` 参数还在当地与任何包含 `custom_generate` 结构,是开发您自定义生成方法的推荐工作流程。 ```py gen_out = model.generate(**inputs, custom_generate="path/to/local/dir", trust_remote_code=True) ``` > [!WARNING] > 装入本地目录仍然执行 `custom_generate/generate.py`,所以它需要 `trust_remote_code=True` 就像Hub寄存器一样 只能通过 `trust_remote_code=True` 你写过或审查过密码 #### 所需经费.txt 您可以在 a 中选择指定额外的 Python 要求 `requirements.txt` 文档在 `custom_generate` 文件夹。这些在运行时被选中, 如果缺少, 将会丢弃一个例外, 将删除用户以相应更新环境 。 #### README . md (英语). 根级 `README.md` 然而,由于寄存器的重心是自定义生成方法,我们强烈建议将其重心转向描述自定义生成方法。除了对方法的描述外,我们还建议记录任何输入和/或输出差异到原始。 [`~GenerationMixin.generate`]. 这样,用户就可以专注于新事物,依靠Transformers docs来进行通用执行细节. 关于可发现性,我们强烈建议你添加 `custom_generate` 标记到您的仓库。为此,请在您的顶端 `README.md` 文件应该看起来像下面的例子。在您按下文件后,您应该在您的仓库中看到标记 ! ```text --- library_name: transformers tags: - custom_generate --- (your markdown content here) ``` 建议的做法: - 文档输入和输出差异 [`~GenerationMixin.generate`]. - 增加自成一体的示例,以便进行快速的实验. - 描述软要求,如该方法仅与某一个模型家族运作良好。 ### 重用 `generate`投入准备 如果您正在添加一个新的解码环路, 您可能想要保留其中的输入准备 `generate` (批量扩展、注意口罩、日志处理器、停止标准等)。 **可调用** 改为: `custom_generate` 用于再利用 [`~GenerationMixin.generate`]完全准备的管道,而仅凌驾于解码环路之上。 ```py def custom_loop(model, input_ids, attention_mask, logits_processor, stopping_criteria, generation_config, **model_kwargs): next_tokens = input_ids while input_ids.shape[1] < stopping_criteria[0].max_length: logits = model(next_tokens, attention_mask=attention_mask, **model_kwargs).logits next_token_logits = logits_processor(input_ids, logits[:, -1, :]) next_tokens = torch.argmax(next_token_logits, dim=-1)[:, None] input_ids = torch.cat((input_ids, next_tokens), dim=-1) attention_mask = torch.cat((attention_mask, torch.ones_like(next_tokens)), dim=-1) return input_ids output = model.generate( **inputs, custom_generate=custom_loop, max_new_tokens=10, ) ``` > [!TIP] > 如果你出版一个 `custom_generate` 仓库,您的 `generate` 执行本身可以定义一个可调用,并传递给 `model.generate()`。这可以让您自定义解码循环,同时仍然从Transformers的内置输入准备逻辑中受益。 ### 查找自定义生成方法 您可以找到所有自定义生成方法 [正在搜索他们的自定义标签 。](https://huggingface.co/models?other=custom_generate), `custom_generate`。除了标签之外,我们还整理了两组 `custom_generate` 方法: - [自定义生成方法 - 社区](https://huggingface.co/collections/transformers-community/custom-generation-methods-community-6888fb1da0efbc592d3a8ab6) - 收集社区贡献的有力方法; - [自定义生成方法 - 教学](https://huggingface.co/collections/transformers-community/custom-generation-methods-tutorials-6823589657a94940ea02cfec) - 以往作为其中一部分的方法的参考执行情况汇编 `transformers`,以及用于 `custom_generate`. ## 资源 读读 [如何生成文本:使用不同的解码方法生成语言,使用Transformers](https://huggingface.co/blog/how-to-generate) 以解释常见的解码策略如何运作。

查看原始来源