TRL 文档
Best of N 采样:无需基于 RL 的微调即可获得更好模型输出的替代方法
加入 Hugging Face 社区
并获得增强的文档体验
开始使用
Best of N 采样:无需基于 RL 的微调即可获得更好模型输出的替代方法
在 extras 模块中,best-of-n
采样器类作为生成更好模型输出的替代方法。至于它与基于 RL 的微调相比如何,请查看 examples
目录中的比较示例
用法
要快速开始,请使用模型、长度采样器、分词器以及充当代理奖励管道的可调用对象实例化该类的实例,该管道输出输入查询的奖励分数
from transformers import pipeline, AutoTokenizer
from trl import AutoModelForCausalLMWithValueHead
from trl.core import LengthSampler
from trl.extras import BestOfNSampler
ref_model = AutoModelForCausalLMWithValueHead.from_pretrained(ref_model_name)
reward_pipe = pipeline("sentiment-analysis", model=reward_model, device=device)
tokenizer = AutoTokenizer.from_pretrained(ref_model_name)
tokenizer.pad_token = tokenizer.eos_token
# callable that takes a list of raw text and returns a list of corresponding reward scores
def queries_to_scores(list_of_strings):
return [output["score"] for output in reward_pipe(list_of_strings)]
best_of_n = BestOfNSampler(model, tokenizer, queries_to_scores, length_sampler=output_length_sampler)
假设您有一个标记化查询的列表/张量,您可以通过调用 generate
方法生成更好的输出
best_of_n.generate(query_tensors, device=device, **gen_kwargs)
默认样本大小为 4,但您可以在实例初始化时更改它,如下所示
best_of_n = BestOfNSampler(model, tokenizer, queries_to_scores, length_sampler=output_length_sampler, sample_size=8)
默认输出是为每个查询取得分最高的输出的结果,但您可以通过在实例初始化时传递 n_candidates
参数将其更改为前 2 个等等
best_of_n = BestOfNSampler(model, tokenizer, queries_to_scores, length_sampler=output_length_sampler, n_candidates=2)
可以选择在实例创建时设置生成设置(如 temperature
、pad_token_id
),而不是在调用 generate
方法时设置。这可以通过在初始化时从 transformers
库传递 GenerationConfig
来完成
from transformers import GenerationConfig
generation_config = GenerationConfig(min_length= -1, top_k=0.0, top_p= 1.0, do_sample= True, pad_token_id=tokenizer.eos_token_id)
best_of_n = BestOfNSampler(model, tokenizer, queries_to_scores, length_sampler=output_length_sampler, generation_config=generation_config)
best_of_n.generate(query_tensors, device=device)
此外,在初始化时,您可以设置种子以控制生成过程的可重复性和为每个查询生成的样本数
< > 在 GitHub 上更新