TRL 文档
N 中选优采样:无需基于强化学习微调即可获得更好模型输出的替代方法
加入 Hugging Face 社区
并获得增强的文档体验
开始使用
N 中选优采样:无需基于强化学习微调即可获得更好模型输出的替代方法
在 extras 模块中,best-of-n
采样器类是一种生成更优模型输出的替代方法。至于它与基于强化学习的微调相比效果如何,请参阅 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 上更新