基于人类反馈的强化学习微调与模型部署优化
立即解锁
发布时间: 2025-09-03 00:28:28 阅读量: 19 订阅数: 21 AIGC 


生成式AI实战:从理论到应用
### 基于人类反馈的强化学习微调与模型部署优化
#### 1. 基于人类反馈的强化学习微调(RLHF)
在强化学习从人类反馈(RLHF)的过程中,每次迭代都会更新模型的权重,类似于其他类型的模型训练和微调,迭代会持续进行一定的步数和轮次。随着时间的推移,生成模型产生的有毒完成内容会减少,从而获得更高的奖励。迭代会一直持续,直到模型达到基于评估阈值(如毒性分数)的对齐标准,或者达到最大配置迭代次数 `max_ppo_steps`。
##### 1.1 RLHF 流程代码
```python
# Extract prompts from the input batch
prompt_tensors = batch["input_ids"]
# Prepare list to collect the summaries
summary_tensors = []
# For each input prompt, generate a summary completion
for prompt_tensor in prompt_tensors:
summary = ppo_trainer.generate(prompt_tensor,
**generation_kwargs)
# Append the summaries
summary_tensors.append(
summary.squeeze()[-max_new_tokens:])
# This needs to be called "response".
batch["response"] = [tokenizer.decode(r.squeeze()) for r in summary_tensors]
# Compute reward outputs for combined query and response
query_response_pairs = [q + r for q, r in zip(batch["query"],
batch["response"])]
# Calculate rewards across both classes
rewards = toxicity_evaluator(
query_response_pairs, **reward_kwargs)
# Extract the reward value from the `nothate` class
reward_tensors =
[torch.tensor(reward[not_hate_index]["score"]) for reward in rewards]
# Run PPO step with prompts, summaries, and rewards
ppo_trainer.step(prompt_tensors, summary_tensors, reward_tensors)
```
##### 1.2 缓解奖励作弊问题
在基于奖励的系统中,存在忽略约束并“破解奖励”的倾向。在强化学习中,智能体可能会学会作弊以最大化奖励,即使所选行动导致错误状态。例如,生成模型可能会生成无意义、语法错误的标记序列,以最大化奖励(如低毒性),但不遵循原始语言模型的学习成果,甚至完全偏离人类语言。
为避免奖励作弊,常用的技术是在进行任何强化学习或权重更新之前,先复制原始指令模型。然后冻结复制模型的权重,将其用作不可变的“参考模型”。在 RLHF 过程中,每个提示都会由冻结的参考模型和正在使用 RLHF 进行微调的模型完成。接着,比较这两个完成结果,使用 Kullback - Leibler 散度(KL 散度)计算两个标记概率分布之间的统计距离。
以下是配置 `PPOTrainer` 类以添加冻结参考模型的代码:
```python
from trl import PPOTrainer
from trl import AutoModelForCausalLMWithValueHead
from trl import create_reference_model
from transformers import AutoTokenizer
model_checkpoint = "..." # generative model like Llama2, Falcon
tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)
model = AutoModelForCausalLMWithValueHead.from_pretrained(
model_checkpoint,
torch_dtype=torch.bfloat16)
ref_model = create_reference_model(model)
ppo_trainer = PPOTrainer(
model=model, # tunable model
ref_model=ref_model, # frozen reference model
tokenizer=tokenizer,
dataset=dataset)
```
##### 1.3 使用参数高效微调(PEFT)与 RLHF
参数高效微调(PEFT)可与 RLHF 结合使用,以减少计算密集型的近端策略优化(PPO)算法所需的计算和内存资源。具体来说,只需要更新模型的较小的 PEFT 适配器权重,而不是可调模型的全部权重。
##### 1.4 评估 RLHF 微调模型
可以使用定性和定量评估技术来评估 RLHF 微调后的模型。
**定性评估**:
| 评估阶段 | 完成内容 |
| ---- | ---- |
| RLHF 前(较低奖励) | #Person1# asks #Person2# about the restaurant. #Person2# liked the food but it wasn't as good as #Person2# expected it to be. #Person2#'s tired of the restaurant. |
| RLHF 后(较高奖励) | #Person2# describes the restaurant to #Person1# and the food situation. #Person2# doesn't want to try the restaurant again. |
从主观比较来看,RLHF 后的完成
0
0
复制全文
相关推荐









