一、前言

最近在做文本生成,用到huggingface transformers库的文本生成 generate() 函数,是 GenerationMixin 类的实现(class transformers.generation_utils.GenerationMixin),是自回归文本生成预训练模型相关参数的集大成者。因此本文解读一下这些参数的含义以及常用的 Greedy SearchBeam SearchSamplingTemperatureTop-kTop-p)等各个算法的原理。

这个类对外提供的方法是 generate(),通过调参能完成以下事情:

  • greedy decoding:当 num_beams=1 而且 do_sample=False 时,调用 greedy_search()方法,每个step生成条件概率最高的词,因此生成单条文本。
  • multinomial sampling:当 num_beams=1do_sample=True 时,调用 sample() 方法,对词表做一个采样,而不是选条件概率最高的词,增加多样性。
  • beam-search decoding:当 num_beams>1do_sample=False 时,调用 beam_search() 方法,做一个 num_beams 的柱搜索,每次都是贪婪选择top N个柱。
  • beam-search multinomial sampling:当 num_beams>1do_sample=True 时,调用 beam_sample() 方法,相当于每次不再是贪婪选择top N个柱,而是加了一些采样。
  • diverse beam-search decoding:当 num_beams>1num_beam_groups>1 时,调用 group_beam_search() 方法。
  • constrained beam-search decoding:当 constraints!=None 或者 force_words_ids!=None,实现可控文本生成。

二、各输入参数含义

接下来分别看看各个输入参数(源代码):


我觉得对文本生成质量最有用的几个参数有:max_length、min_length、do_sample、top_k、top_p、repetition_penalty。接下来选择性地记录各个参数的含义。

inputs (torch.Tensor of varying shape depending on the modality, optional) — The sequence used as a prompt for the generation or as model inputs to the encoder. If None the method initializes it with bos_token_id and a batch size of 1. For decoder-only models inputs should of in the format of input_ids. For encoder-decoder models inputs can represent any of input_ids, input_values, input_features, or pixel_values.

inputs:输入prompt。如果为空,则用batch size为1的 bos_token_id 初始化。对于只有decoder的模型(GPT系列),输入需要是 input_ids;对于 encoder-decoder模型(BART、T5等),输入更多样化。

max_length (int, optional, defaults to model.config.max_length) — The maximum length of the sequence to be generated.

max_length:生成序列的最大长度。

min_length (int, optional, defaults to 10) — The minimum length of the sequence to be generated.

min_length:生成序列的最短长度,默认是10。

do_sample (bool, optional, defaults to False) — Whether or not to use sampling ; use greedy decoding otherwise.

do_sample:是否开启采样,默认是 False,即贪婪找最大条件概率的词。

early_stopping (bool, optional, defaults to False) — Whether to stop the beam search when at least num_beams sentences are finished per batch or not.

early_stopping:是否在至少生成 num_beams 个句子后停止 beam search,默认是False。

num_beams (int, optional, defaults to 1) — Number of beams for beam search. 1 means no beam search.

num_beams:默认是1,也就是不进行 beam search。

temperature (float, optional, defaults to 1.0) — The value used to module the next token probabilities.

默认是1.0,温度越低(小于1),softmax输出的贫富差距越大;温度越高,softmax差距越小。

top_k (int, optional, defaults to 50) — The number of highest probability vocabulary tokens to keep for top-k-filtering.

top_k:top-k-filtering 算法保留多少个 最高概率的词 作为候选,默认50。详见下文。

top_p (float, optional, defaults to 1.0) — If set to float < 1, only the most probable tokens with probabilities that add up to top_p or higher are kept for generation.

top_p:已知生成各个词的总概率是1(即默认是1.0)如果top_p小于1,则从高到低累加直到top_p,取这前N个词作为候选。

typical_p (float, optional, defaults to 1.0) — The amount of probability mass from the original distribution to be considered in typical decoding. If set to 1.0 it takes no effect. See this paper for more details.

typical_p:典型采样(不知道能否这样翻译),默认值 1.0 此参数无效,主要思想:不总是从分布高概率区域中选词,而是从信息含量接近预期值typical_p(即接近模型的条件熵)的单词集合中采样。
论文:Typical Decoding for Natural Language Generation

repetition_penalty (float, optional, defaults to 1.0) — The parameter for repetition penalty. 1.0 means no penalty. See this paper for more details.

repetition_penalty:默认是1.0,重复词惩罚。
论文:CTRL: A CONDITIONAL TRANSFORMER LANGUAGE MODEL FOR CONTROLLABLE GENERATION

pad_token_id (int, optional) — The id of the padding token.
bos_token_id (int, optional) — The id of the beginning-of-sequence token.
eos_token_id (int, optional) — The id of the end-of-sequence token.

pad_token_id / bos_token_id / eos_token_id:填充词<PAD>、起始附<s>、结束符</s> 的id。

length_penalty (float, optional, defaults to 1.0) — Exponential penalty to the length. 1.0 means that the beam score is penalized by the sequence length. 0.0 means no penalty. Set to values < 0.0 in order to encourage the model to generate longer sequences, to a value > 0.0 in order to encourage the model to produce shorter sequences.

length_penalty:长度惩罚,默认是1.0。

  • length_penalty=1.0:beam search分数会受到生成序列长度的惩罚
  • length_penalty=0.0:无惩罚
  • length_penalty<0.0:鼓励模型生成长句子
  • length_penalty>0.0:鼓励模型生成短句子

no_repeat_ngram_size (int, optional, defaults to 0) — If set to int > 0, all ngrams of that size can only occur once.

no_repeat_ngram_size:用于控制重复词生成,默认是0,如果大于0,则相应N-gram只出现一次

encoder_no_repeat_ngram_size (int, optional, defaults to 0) — If set to int > 0, all ngrams of that size that occur in the encoder_input_ids cannot occur in the decoder_input_ids.

encoder_no_repeat_ngram_size:也是用于控制重复词生成,默认是0,如果大于0,则encoder_input_ids的N-gram不会出现在 decoder_input_ids里。

bad_words_ids(List[List[int]], optional) — List of token ids that are not allowed to be generated. In order to get the token ids of the words that should not appear in the generated text, use tokenizer(bad_words, add_prefix_space=True, add_special_tokens=False).input_ids.

bad_words_ids:禁止生成的词id列表,可用 tokenizer(bad_words, add_prefix_space=True, add_special_tokens=False).input_ids 方法获取ids。

force_words_ids(List[List[int]] or List[List[List[int]]], optional) — List of token ids that must be generated. If given a List[List[int]], this is treated as a simple list of words that must be included, the opposite to bad_words_ids. If given List[List[List[int]]], this triggers a disjunctive constraint, where one can allow different forms of each word.

force_words_ids:跟上面的 bad_words_ids 相反,这个传入必须生成的token id 列表。如果ids格式是 [List[List[int]]],比如 [[1,2],[3,4]],则触发析取约束(Disjunctive Positive Constraint Decoding),大概意思就是可以生成一个单词不同的形式,比如“lonely”、“loneliness”等。
论文:Guided Generation of Cause and Effect

num_return_sequences(int, optional, defaults to 1) — The number of independently computed returned sequences for each element in the batch.

num_return_sequences:每条输入产生多少条输出序列,默认为1。

max_time:多少秒之后停止生成。

attention_mask:默认跟输入 input_ids 的shape一样,0代表mask,1代表不mask,被mask掉的token不参与计算注意力权重。

decoder_start_token_id:encoder-decoder架构的模型有可能解码起始符跟编码器不一样(比如[CLS]、<s>)时可指定一个int值。

num_beam_groups (int, optional, defaults to 1) :beam search的时候为了确保不同beam之间的多样性,可以将这些beam划分成group,详见论文 Diverse Beam Search: Decoding Diverse Solutions from Neural Sequence Models。

diversity_penalty (float, optional, defaults to 0.0):如果在同一个step中某个beam生成的词和其他beam有相同的,那么就减去这个值作为惩罚,仅在 num_beam_groups 启用时这个值才有效。

prefix_allowed_tokens_fn (Callable[[int, torch.Tensor], List[int]], optional):如果提供该函数,就会把beam search每个step限制在允许的token里搜索,否则不做约束。函数有2个输入,分别是 batch_id 和当前步的输入 input_ids,返回一个list,包含下个step允许的token。可用于条件约束生成。详见论文 Autoregressive Entity Retrieval。

output_attentions (bool, optional, defaults to False) :是否返回所有attention层的注意力矩阵值,默认False。

output_hidden_states (bool, optional, defaults to False):是否返回各个层的hidden_states,默认是False。

output_scores (bool, optional, defaults to False):是否返回预测分数。

forced_bos_token_id (int, optional):解码器在生成 decoder_start_token_id 对应token之后指定生成的token id,mBART这种多语言模型会用到,因为这个值一般用来区分target语种。

forced_eos_token_id (int, optional):达到最大长度 max_length 时,强制作为最后生成的token id。

remove_invalid_values (bool, optional):是否删除模型nan(not a number)和inf(正无穷)防止崩溃,但可能会减慢生成速度。

exponential_decay_length_penalty (tuple(int, float), optional):生成一定数量的token之后,施加一个指数增长的长度惩罚,格式为 (start_index, decay_factor),前者表示从开始施加惩罚的索引,后者表示指数衰减因子。

三、函数输出含义

return_dict_in_generate=True 或者 config.return_dict_in_generate=True 时返回 ModelOutput 类对象(class transformers.utils.ModelOutput),否则返回 torch.FloatTensor

四、各解码算法原理简述

本小节主要介绍自回归文本生成的几个最常用的解码方法,包括 Greedy search, Beam search, Top-K sampling 以及 Top-p sampling。自回归生成都是基于以下公式,也就是假设一个单词序列的概率分布等于各单词条件概率乘积。
P ( w 1 : T ∣ W 0 ) = ∏ t = 1 T P ( w t ∣ w 1 : t − 1 , W 0 ) ,with  w 1 : 0 = ∅ , P(w_{1:T} | W_0 ) = \prod_{t=1}^T P(w_{t} | w_{1: t-1}, W_0) \text{ ,with } w_{1: 0} = \emptyset, P(w1:T​∣W0​)=t=1∏T​P(wt​∣w1:t−1​,W0​) ,with w1:0​=∅,

4.1 Greedy Search

贪婪搜索,每个时间步 t t t 都选概率最高的那个词:
w t = a r g m a x w P ( w ∣ w 1 : t − 1 ) w_t = argmax_{w}P(w | w_{1:t-1}) wt​=argmaxw​P(w∣w1:t−1​)

比如图中,最终生成的序列是 (“The”,“nice”,“woman”)。这种贪婪算法和beam search的共同弊端就是容易生成重复词,小试一下:

此外,贪婪搜索容易忽略掉低概率词后面的高概率词,比如开头那个图里“the dog has”,概率是 0.4*0.9=0.36,比“the nice woman”的 0.5*0.4=0.20 要高,但由于第一轮dog概率比nice低,导致了与图中更优解擦肩而过。beam search 就能解决这个问题。

4.2 Beam Search

beam search每个时间步选择最可能的 Top - num_beams 个词,解决了贪婪搜索擦肩而过的风险。

如图例子,num_beams=2,第一步选了概率最高的序列 the nice(0.5) 和 the dog(0.4),第二步选了概率最高的序列 the dog has(0.4✖️0.9=0.36)和 the nice woman(0.5✖️0.4=0.20)。

注意,beam search虽然比贪婪搜索能找到概率更高的解,但不保证是全局最优解。

小试一下。设置num_beams > 1early_stopping=True,当指定数量个beam生成结束符就早停。

比刚才好一些了,但还是有重复,可以加上no_repeat_ngram_size=2 禁止模型生成重复的 2-gram。但是需要慎用,因为“喜欢”这个词生成完后面就不能生成了,这就导致“喜欢周杰伦”没了。

此外,还可以通过 num_return_sequences 参数指定返回概率最高的 topN 个序列。

可见生成的这个top5个序列差异不算太大。

关于beam search,有这么三个说法:

  • 如果生成长度是提前可预知,比如摘要、翻译,这种用beam search好;但开放式生成,比如对话,故事生成等,输出长度变化比较大,就不太适合用beam search了。
  • beam search容易重复生成单词。由于通过大量实验才能达到“禁止生成重复n-gram” 和 “允许周期性生成重复n-gram” 的平衡,所以在开放式生成任务上不太好用这种惩罚来控制重复。
  • 人类往往说话时不是总选择高概率的词作为下个词,而是经常猝不及防,出其不意,如图对比。所以beam search还是有很大问题的。

4.3 Sampling

采样算法不再拘泥于高概率词,而是根据条件概率分布随机挑选单词,如图,car这种低概率词也有机会被选中作为生成文本。

generate函数中,设置 do_sample=True,并通过 top_k=0 先暂时停用topk采样,来看看实际效果。

可以看到模型有点胡言乱语的感觉…这时候,temperature参数就派上用场了。

4.3.0 Temperature

temperature参数相当于给softmax降降温,让各个词概率差距加大(跟刚才的随机 sample 相比,增加了高概率词的可能性,降低了低概率词的可能性)公式如下:

对比一下:下图是加了 temperature 的。

下图是没加 temperature 的(默认是1.0)。

可以看到:

  • T越小,趋近于0,概率密度就越集中在高概率词,就更偏向贪婪搜索,更容易产生重复词。
  • T越大,趋近于1,就越趋向原始softmax,随机性就越大。
  • T越大,甚至大于1,采样越随机,概率分布越趋向均匀分布。

    小试一下:
    temperature = 0.7 时:

    temperature = 0.1 时:

4.3.1 Top-k 采样

Hierarchical Neural Story Generation 提出了 Top-K 采样方法,原理是先找出K个最有可能的单词,然后在这K个单词中计算概率分布,如图(蓝色为各个step的TopK)。GPT2就用了这种采样方法。


可见比之前要好很多,但是存在问题:

  • top-k 采样的问题就是这个 K 是死的,没法动态调整,这就导致上面例子中,左图 t=1 步骤,概率分布比较平缓,右图 t=2步骤,概率分布比较悬殊
  • 上面例子中,给定the后,t=1选的词还算合理,但t=2时,down 和 a 显然都不太适合但也被选到候选集里了

因此,将候选集限制为固定值K个,可能让模型在右图的悬殊分布里生成胡言乱语,也限制了在平缓分布中的一些创造性。所以top-p采样应运而生。

4.3.2 Top-p 采样

Top-p (nucleus) sampling 是 Ari Holtzman et al. (2019) 提出的算法。他是从使得累计概率超过 p 的最小候选集里选择单词,然后算这些单词的概率分布。这样候选单词集的大小就不跟topK似的一成不变了,会随下一个单词的概率分布动态增加和减少。

比如设置 p = 0.92,给定the后,t=1时前面9个词加起来概率为0.94,刚刚超过了0.92,于是前9个词成了候选词;t=2时前面3个词概率加起来已经达到了0.97。

也就是说,当下个单词不太可预测时,那候选就多一些;如果下个单词模型打眼一看就知道是哪些,那候选就少一些。

top_p 是 0-1 之间的值,值越接近1效果越好。

当 p 设置的比较大时,top-p 采样出来的候选词可能巨多,所以可以跟 top-k 结合起来用,避免那些 top-p 选中的概率很低的词,如图设置 top_p 和 top_k。

官方文档:https://huggingface.co/docs/transformers/v4.20.1/en/main_classes/text_generation#transformers.generation_utils.GenerationMixin.generate

参考资料:
https://zhuanlan.zhihu.com/p/115076102
https://zhuanlan.zhihu.com/p/453286395
https://huggingface.co/blog/how-to-generate

基于 transformers 的 generate() 方法实现多样化文本生成:参数含义和算法原理解读相关推荐

  1. NLP之WordCloud:基于jieba+matplotlib库对一段文本生成词云图~~情人节最好的礼物(给你一张过去的词云图,看看那时我们的爱情)

    NLP之WordCloud:基于jieba+matplotlib库对一段文本生成词云图~~情人节最好的礼物(给你一张过去的词云图,看看那时我们的爱情) 目录 输出词云图结果 输出文本统计 设计思路 实 ...

  2. CVPR2022 | ZeroCap:零样本图像到文本生成的视觉语义算法

    CVPR2022 | ZeroCap:零样本图像到文本生成的视觉语义算法 [写在前面] 最近的文本到图像匹配模型将对比学习应用于大量未经管理的图像和句子对.虽然此类模型可以为匹配和后续的zero-sh ...

  3. 【Transformers】第 5 章 :文本生成

  4. 文本生成的几种简单方法

    一.使用Chinese GPT2 Model from transformers import BertTokenizer, GPT2LMHeadModel, TextGenerationPipeli ...

  5. AI艺术的背后:详解文本生成图像模型【基于 Diffusion Model】

    系列文章链接: AI艺术的背后:详解文本生成图像模型[基于 VQ-VAE] AI艺术的背后:详解文本生成图像模型[基于GAN] AI艺术的背后:详解文本生成图像模型[基于Diffusion Model ...

  6. 基于层次过滤的文本生成

    ©PaperWeekly 原创 · 作者|邓云天 学校|哈佛大学计算机系博士生 研究方向|自然语言处理 论文标题:Cascaded Decoding with Markov Transformers ...

  7. 基于结构化数据的文本生成:非严格对齐生成任务及动态轻量的GCN生成模型

    作者|邴立东.程丽颖.付子豪.张琰等 单位|阿里巴巴达摩院.香港中文大学等 摘要 基于结构化数据生成文本(data-to-text)的任务旨在生成人类可读的文本来直观地描述给定的结构化数据.然而,目前 ...

  8. 文本生成与自动摘要:基于生成式预训练Transformer的实现与优化

    作者:禅与计算机程序设计艺术 1.简介 文本生成是自然语言处理领域中非常重要的问题之一.在不断地探索学习新知识和技能的同时,越来越多的人也需要通过自己创造或整合的手段,将自己的想法.观点和信息转化成语 ...

  9. ACL2022 | 文本生成的相关前沿进展

    每天给你送来NLP技术干货! 来自:复旦DISC 引言 文本生成作为人工智能领域研究热点之一,其研究进展与成果也引发了众多关注.本篇主要介绍了三篇ACL2022的三篇文章.主要包含了增强预训练语言模型 ...

最新文章

  1. 一本Python数据分析入门宝藏书,快藏不住了!
  2. 伍哥原创之安装nginx,mysql,php-fpm,redis
  3. forms oracle runtime_Oracle EBS R12 clone 完毕后,登陆到系统,在运行FORMS程序的时候出现FRM-92101...
  4. 如何让笨重的系统架构变灵巧?
  5. Django登陆以后重定向到请求登陆的页面
  6. 淘宝API接口:item_cat_get - 获得淘宝商品类目
  7. 计算机考试一级b软件未来教育,2019.9全国计算机一级MS Office考试每日一练
  8. I Want My Tears Back
  9. QtCharts:给QChartView换肤,换背景色添加背景图片
  10. 2021第十二届蓝桥杯国赛B组题解(C/C++)
  11. 蓝鲸作业平台:搞定与脚本相关的一切
  12. linux自动清理磁盘日志的一种方案
  13. 招聘网站的几个新控件(2)
  14. 读书笔记-->《精益数据分析》第二部分 | 第15章:创业阶段2——黏性
  15. 微软校招2015 Beautiful String
  16. iso-3166-伪2_伪类-基础
  17. 说说软件测试工作中4个软实力
  18. Phoenix 介绍和基本用法
  19. 第一个超级计算机深蓝,从“深蓝”到“阿尔法狗”, 人工智能发展的一大步...
  20. 大西洋月刊 2019年7月_Web开发人员月刊2018年10月

热门文章

  1. Nginx同时支持Http和Https的配置
  2. C语言字节对齐64位和32位
  3. javascript的 onchange
  4. Erp系统用友U8找不到打印机驱动解决办法
  5. socketio mysql_SocketIO + MySQL认证
  6. Python生成随机的4位验证码(由大小写英文字母以及数字构成的随机验证码)
  7. 正版免费 Noteexpress
  8. java 取反 值_java编程 按位取反的问题 java中取反操作是正数
  9. 你想学的都在这里!史上最全的《Android面试题及解析》,赶紧收藏!
  10. 映射网络驱动器共享网络硬盘