RLHF 与 PPO 的 N 个实现细节:复现 OpenAI lm-human-preferences
The N Implementation Details of RLHF with PPO
作者复现了 OpenAI 2019 年的 RLHF 代码库 openai/lm-human-preferences,在情感和描述性任务上得到与原始代码几乎一致的学习曲线,并整理出一份实现细节清单。
作者复现 OpenAI 原始 RLHF 代码并逐条列出实现细节,其中 PyTorch 与 TensorFlow 版 Adam 的差异会直接影响训练稳定性。
RLHF / ChatGPT 近来一直是一个热门研究话题。在我们对 RLHF 进行更多研究的过程中,这篇博客文章尝试复现 OpenAI 2019 年最初的 RLHF 代码库 openai/lm-human-preferences。尽管它带有“TensorFlow 1.x 风格”,OpenAI 的原始代码库经过了非常充分的评估和基准测试,因此是研究 RLHF 实现工程细节的好地方。
我们的目标是:
- 在风格任务中复现 OAI 的结果,并匹配 openai/lm-human-preferences 的学习曲线。
- 呈现一份实现细节清单,其精神类似于 The 37 Implementation Details of Proximal Policy Optimization;Debugging RL, Without the Agonizing Pain。
- 提供一个简单易读且极简的 RLHF 参考实现;
这项工作仅用于教育 / 学习目的。对于需要更多功能的高级用户,例如使用 PEFT 运行更大的模型,huggingface/trl 会是一个很好的选择。
- 在 Matching Learning Curves 中,我们展示了我们的主要贡献:创建一个代码库,能够在风格任务中复现 OAI 的结果,并与 openai/lm-human-preferences 的学习曲线非常接近地匹配。
- We then take a technical deep dive into the implementation details that are relevant to reproducing OAI’s work. In General Implementation Details, we talk about basic details, such as how rewards/values are generated and how responses are generated. In Reward Model Implementation Details, we talk about details such as reward normalization. In Policy Training Implementation Details, we discuss details such as rejection sampling and reward “whitening”.
- 在 PyTorch Adam optimizer numerical issues w.r.t RLHF 中,我们重点介绍了 TensorFlow 与 PyTorch 之间 Adam 的一个非常有趣的实现差异,它会导致模型训练中出现激进的更新。
- 接下来,鉴于奖励标签是用
gpt2-large生成的,我们考察训练不同基础模型(例如 gpt2-xl、falcon-1b)的效果。 - 最后,我们以局限性和讨论来结束我们的工作。
以下是重要链接:
- 💾 我们的复现代码库 https://github.com/vwxyzjn/lm-human-preference-details
- 🤗 RLHF 模型比较演示:https://huggingface.co/spaces/lm-human-preference-details/rlhf-demo
- 🐝 所有 w&b 训练日志 https://wandb.ai/openrlbenchmark/lm_human_preference_details
匹配学习曲线
我们的主要贡献是在风格任务中复现 OAI 的结果,例如情感和描述性。如下图所示,我们的代码库(橙色曲线)可以产生与 OAI 的代码库(蓝色曲线)几乎完全相同的学习曲线。
关于运行 openai/lm-human-preferences 的说明
为了进行直接比较,我们运行了 openai/lm-human-preferences 中的原始 RLHF 代码,这将提供有价值的指标,帮助验证和诊断我们的复现。我们能够把原始的 TensorFlow 1.x 代码设置起来,但它需要非常特定的环境:
- OAI’s dataset was partially corrupted/lost (so we replaced them with similar HF datasets, which may or may not cause a performance difference)
- 具体来说,它的书籍数据集在 OpenAI 从 GCP 迁移到 Azure 期间丢失了(https://github.com/openai/lm-human-preferences/issues/17#issuecomment-1044051496)。我用 Hugging Face 的
bookcorpus数据集替换了书籍数据集,原则上这就是 OAI 使用的数据集。
- 具体来说,它的书籍数据集在 OpenAI 从 GCP 迁移到 Azure 期间丢失了(https://github.com/openai/lm-human-preferences/issues/17#issuecomment-1044051496)。我用 Hugging Face 的
- 它无法在 1 块 V100 上运行,因为它没有实现梯度累积。相反,它使用大批量大小并将批次拆分到 8 块 GPU 上,仅 1 块 GPU 就会 OOM。
- 它无法在 8x A100 上运行,因为它使用 TensorFlow 1.x,而后者与 Cuda 8+ 不兼容
- 它无法在 8x V100(16GB)上运行,因为会 OOM
- 它只能在 8x V100(32GB)上运行,而只有 AWS 以
p3dn.24xlarge实例提供这种配置。
常规实现细节
我们现在深入探讨与复现OAI工作相关的技术实现细节。在本节中,我们将讨论一些基本细节,例如奖励/价值是如何生成的,以及响应是如何生成的。以下是这些细节,不分先后顺序:
奖励模型和策略的价值头将
query和response的拼接作为输入- 奖励模型和策略的价值头并非仅关注响应。相反,它将
query和response拼接在一起作为query_response(lm_human_preferences/rewards.py#L105-L107)。 - 因此,例如,如果
query = "he was quiet for a minute, his eyes unreadable",且response = "He looked at his left hand, which held the arm that held his arm out in front of him.",那么奖励模型和策略的价值会对query_response = "he was quiet for a minute, his eyes unreadable. He looked at his left hand, which held the arm that held his arm out in front of him."进行前向传播,并产生形状为(B, T, 1)的奖励和价值,其中B是批量大小,T是序列长度,1是奖励头的维度1(lm_human_preferences/rewards.py#L105-L107,lm_human_preferences/policy.py#L111)。 T意味着每个token都有一个与其自身及先前上下文相关的奖励。例如,eyestoken会有一个对应于he was quiet for a minute, his eyes的奖励。
- 奖励模型和策略的价值头并非仅关注响应。相反,它将
使用特殊填充token进行填充并截断输入。
OAI为查询
query_length设置了固定的输入长度;对于过短的序列,它使用pad_token进行填充(lm_human_preferences/language/datasets.py#L66-L67),对于过长的序列则进行截断(lm_human_preferences/language/datasets.py#L57)。关于该概念的通用介绍,请参见此处。在填充输入时,OAI使用了一个超出词汇表的token(lm_human_preferences/language/encodings.py#L56)。- 关于HF transformers的说明——填充token。根据(transformers#2630#issuecomment-578159876),GPT和GPT-2的预训练过程中并未使用填充token;因此,transformers的gpt2模型没有与其分词器关联的官方填充token。常见的做法是设置
tokenizer.pad_token = tokenizer.eos_token,但在本工作中,为了匹配OAI的原始设置,我们将区分这两个特殊token,因此我们将使用tokenizer.add_special_tokens({"pad_token": "[PAD]"})。
请注意,对于解码器模型而言,没有填充token是默认设置,因为它们在预训练时采用“打包”方式训练,这意味着许多序列被拼接在一起,并由EOS token分隔,而预训练期间总是将具有最大长度的序列块馈送给模型。
- 关于HF transformers的说明——填充token。根据(transformers#2630#issuecomment-578159876),GPT和GPT-2的预训练过程中并未使用填充token;因此,transformers的gpt2模型没有与其分词器关联的官方填充token。常见的做法是设置
将所有内容整合在一起,以下是一个示例
import transformers tokenizer = transformers.AutoTokenizer.from_pretrained("gpt2", padding_side="right") tokenizer.add_special_tokens({"pad_token": "[PAD]"}) query_length = 5 texts = [ "usually, he would", "she thought about it", ] tokens = [] for text in texts: tokens.append(tokenizer.encode(text)[:query_length]) print("tokens", tokens) inputs = tokenizer.pad( {"input_ids": tokens}, padding="max_length", max_length=query_length, return_tensors="pt", return_attention_mask=True, ) print("inputs", inputs) """prints are tokens [[23073, 11, 339, 561], [7091, 1807, 546, 340]] inputs {'input_ids': tensor([[23073, 11, 339, 561, 50257], [ 7091, 1807, 546, 340, 50257]]), 'attention_mask': tensor([[1, 1, 1, 1, 0], [1, 1, 1, 1, 0]])} """相应调整填充token的位置索引
在计算logits时,OAI的代码通过适当屏蔽填充token来工作。这是通过找出对应于填充token的token索引(lm_human_preferences/language/model.py#L296-L297),然后相应地调整它们的位置索引(lm_human_preferences/language/model.py#L320)来实现的。
例如,如果
query=[23073, 50259, 50259]和response=[11, 339, 561],其中(50259是OAI的填充token),那么它会创建位置索引[[0 1 1 1 2 3]],并生成如下logits。注意对应于填充token的logits保持不变!这正是我们在复现中应追求的效果。all_logits [[[ -35.28693 -34.2875 -38.16074 ... -41.595802 -41.082108 -35.36577 ] [ -35.28693 -34.2875 -38.16074 ... -41.595802 -41.082108 -35.36577 ] [ -35.28693 -34.2875 -38.16074 ... -41.595802 -41.082108 -35.36577 ] [-111.303955 -110.94471 -112.90624 ... -113.13064 -113.7788 -109.17345 ] [-111.51512 -109.61077 -114.90231 ... -118.43514 -111.56671 -112.12478 ] [-122.69775 -121.84468 -128.27417 ... -132.28055 -130.39604 -125.707756]]] (1, 6, 50257)关于HF transformers的说明——
position_ids和padding_side。我们可以使用Hugging Face的transformer通过1)左侧填充和2)传入适当的position_ids来精确复现logits:import torch import transformers tokenizer = transformers.AutoTokenizer.from_pretrained("gpt2", padding_side="right") tokenizer.add_special_tokens({"pad_token": "[PAD]"}) pad_id = tokenizer.pad_token_id query = torch.tensor([ [pad_id, pad_id, 23073], ]) response = torch.tensor([ [11, 339, 561], ]) temperature = 1.0 query = torch.tensor(query) response = torch.tensor(response).long() context_length = query.shape[1] query_response = torch.cat((query, response), 1) pretrained_model = transformers.AutoModelForCausalLM.from_pretrained("gpt2") def forward(policy, query_responses, tokenizer): attention_mask = query_responses != tokenizer.pad_token_id position_ids = attention_mask.cumsum(1) - attention_mask.long() # exclusive cumsum input_ids = query_responses.clone() input_ids[~attention_mask] = 0 return policy( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, return_dict=True, output_hidden_states=True, ) output = forward(pretrained_model, query_response, tokenizer) logits = output.logits logits /= temperature print(logits) """ tensor([[[ -26.9395, -26.4709, -30.0456, ..., -33.2208, -33.2884, -27.4360], [ -27.1677, -26.7330, -30.2386, ..., -33.6813, -33.6931, -27.5928], [ -35.2869, -34.2875, -38.1608, ..., -41.5958, -41.0821, -35.3658], [-111.3040, -110.9447, -112.9062, ..., -113.1306, -113.7788, -109.1734], [-111.5152, -109.6108, -114.9024, ..., -118.4352, -111.5668, -112.1248], [-122.6978, -121.8447, -128.2742, ..., -132.2805, -130.3961, -125.7078]]], grad_fn=<DivBackward0>) """关于 HF transformers 的说明 — 在
generate期间position_ids:在 generate 过程中我们不应传入position_ids,因为position_ids已经在transformers中调整过了(见 huggingface/transformers#/7552。
通常,我们在 transformers 中几乎从不传入
position_ids。所有的掩码和移位逻辑都已经实现,例如在generate函数中(需要永久代码链接)。响应生成采样固定长度响应且不进行填充。
在响应生成过程中,OAI 使用
top_k=0, top_p=1.0,并仅在整个词表上进行分类采样(lm_human_preferences/language/sample.py#L43),代码会持续采样直到生成固定长度的响应(lm_human_preferences/policy.py#L103)。值得注意的是,即使遇到 EOS(序列结束)标记,它也会继续采样。关于 HF transformers 的说明 — 采样可能在
eos_token处停止:在transformers中,生成可能在eos_token处停止(src/transformers/generation/utils.py#L2248-L2256),这与 OAI 的设置不同。为了对齐设置,我们需要设置pretrained_model.generation_config.eos_token_id = None, pretrained_model.generation_config.pad_token_id = None。注意transformers.GenerationConfig(eos_token_id=None, pad_token_id=None, ...)不起作用,因为pretrained_model.generation_config会覆盖并设置一个eos_token。import torch import transformers tokenizer = transformers.AutoTokenizer.from_pretrained("gpt2", padding_side="right") tokenizer.add_special_tokens({"pad_token": "[PAD]"}) pad_id = tokenizer.pad_token_id query = torch.tensor([ [pad_id, pad_id, 23073], ]) response = torch.tensor([ [11, 339, 561], ]) response_length = 4 temperature = 0.7 pretrained_model = transformers.AutoModelForCausalLM.from_pretrained("gpt2") pretrained_model.generation_config.eos_token_id = None # disable `pad_token_id` and `eos_token_id` because we just want to pretrained_model.generation_config.pad_token_id = None # generate tokens without truncation / padding generation_config = transformers.GenerationConfig( max_new_tokens=response_length, min_new_tokens=response_length, temperature=temperature, top_k=0.0, top_p=1.0, do_sample=True, ) context_length = query.shape[1] attention_mask = query != tokenizer.pad_token_id input_ids = query.clone() input_ids[~attention_mask] = 0 # set padding tokens to 0 output = pretrained_model.generate( input_ids=input_ids, attention_mask=attention_mask, # position_ids=attention_mask.cumsum(1) - attention_mask.long(), # generation collapsed if this was turned on. generation_config=generation_config, return_dict_in_generate=True, ) print(output.sequences) """ tensor([[ 0, 0, 23073, 16851, 11, 475, 991]]) """注意,在更新的代码库 https://github.com/openai/summarize-from-feedback 中,OAI 在遇到 EOS 标记时确实会停止采样(summarize_from_feedback/utils/experiment_helpers.py#L19)。然而在这项工作中,我们旨在进行 1:1 复现,因此我们对齐了即使遇到 eos_token 也继续采样的设置
奖励模型和策略训练的学习率退火。
- 正如 Ziegler 等人(2019)所建议的,奖励模型仅训练一个 epoch,以避免对有限的人类标注数据过拟合(例如,
descriptiveness任务只有大约 5000 个标签)。在这单个 epoch 中,学习率退火至零(lm_human_preferences/train_reward.py#L249)。 - 与奖励模型训练类似,学习率退火至零(lm_human_preferences/train_policy.py#L172-L173)。
- 正如 Ziegler 等人(2019)所建议的,奖励模型仅训练一个 epoch,以避免对有限的人类标注数据过拟合(例如,
为不同进程使用不同的种子
- When spawning 8 GPU processes to do data parallelism, OAI sets a different random seed per process (lm_human_preferences/utils/core.py#L108-L111). Implementation-wise, this is done via
local_seed = args.seed + process_rank * 100003. The seed is going to make the model produce different responses and get different scores, for example.- 注意:我认为数据集洗牌有一个 bug — 由于某种原因,数据集使用相同的种子进行洗牌(lm_human_preferences/lm_tasks.py#L94-L97)。
- When spawning 8 GPU processes to do data parallelism, OAI sets a different random seed per process (lm_human_preferences/utils/core.py#L108-L111). Implementation-wise, this is done via
奖励模型实现细节
在本节中,我们讨论奖励模型特定的实现细节。我们讨论诸如奖励归一化和层初始化等细节。以下是这些细节,不分先后顺序:
- The reward model only outputs the value at the last token.
- 请注意,在
query和response的拼接上执行前向传播后获得的奖励将具有形状(B, T, 1),其中B是批量大小,T是序列长度(始终相同;在 OAI 的风格任务设置中为query_length + response_length = 64 + 24 = 88,见 launch.py#L9-L11),而1是奖励头的维度 1。出于 RLHF 目的,原始代码库提取最后一个标记的奖励(lm_human_preferences/rewards.py#L132),因此奖励将仅具有形状(B, 1)。 - 请注意,在更新的代码库 openai/summarize-from-feedback 中,OAI 在遇到 EOS token 时停止采样(summarize_from_feedback/utils/experiment_helpers.py#L19)。提取奖励时,它会识别
last_response_index,即 EOS token 之前的索引(#L11-L13),并提取该索引处的奖励(summarize_from_feedback/reward_model.py#L59)。然而,在本工作中我们只是沿用原始设置。
- 请注意,在
- Reward head layer initialization
- 奖励头的权重根据 N(0,1/(dmodel +1)) \mathcal{N}\left(0,1 /\left(\sqrt{d_{\text {model }}+1}\right)\right) 初始化(lm_human_preferences/language/model.py#L368, lm_human_preferences/language/model.py#L251-L252)。这与 Stiennon 等人 2020 年的设置一致(summarize_from_feedback/query_response_model.py#L106-L107)(附注:Stiennon 等人 2020 年在第 17 页有一个笔误,称分布为 N(0,1/(dmodel +1)) \mathcal{N}\left(0,1 /\left(d_{\text {model }}+1\right)\right) ,缺少平方根)
- 奖励头的偏置设置为 0(lm_human_preferences/language/model.py#L254)。
- Reward model normalization before and after
- 在论文中,Ziegler 等人(2019)提到“为了保持奖励模型的尺度在训练过程中一致,我们对其进行归一化,使其对于 x∼D,y∼ρ(⋅∣x) x \sim \mathcal{D}, y \sim \rho(·|x) 具有均值 0 和方差 1。”为了执行归一化过程,代码首先创建一个
reward_gain和reward_bias,这样奖励可以通过reward = reward * reward_gain + reward_bias计算(lm_human_preferences/rewards.py#L50-L51)。 - 执行归一化过程时,代码首先设置
reward_gain=1, reward_bias=0(lm_human_preferences/train_reward.py#L211),然后从目标数据集(例如bookcorpus, tldr, cnndm)收集采样的查询、完成的响应和评估的奖励。接着获取评估奖励的经验均值和标准差(lm_human_preferences/train_reward.py#L162-L167),并尝试计算reward_gain和reward_bias应该是什么。 - 让我们用 μD \mu_{\mathcal{D}} 表示经验均值,σD \sigma_{\mathcal{D}} 表示经验标准差,gg 表示
reward_gain,bb 表示reward_bias,μT=0 \mu_{\mathcal{T}} = 0 表示目标均值,σT=1 \sigma_{\mathcal{T}}=1 表示目标标准差。那么我们有如下公式。 g∗N(μD,σD)+b=N(g∗μD,g∗σD)+b=N(g∗μD+b,g∗σD)=N(μT,σT)g=σTσDb=μT−g∗μD\begin{aligned}g*\mathcal{N}(\mu_{\mathcal{D}}, \sigma_{\mathcal{D}}) + b &= \mathcal{N}(g*\mu_{\mathcal{D}}, g*\sigma_{\mathcal{D}}) + b\\&= \mathcal{N}(g*\mu_{\mathcal{D}} + b, g*\sigma_{\mathcal{D}}) \\&= \mathcal{N}(\mu_{\mathcal{T}}, \sigma_{\mathcal{T}}) \\g &= \frac{\sigma_{\mathcal{T}}}{\sigma_{\mathcal{D}}} \\b &= \mu_{\mathcal{T}} - g*\mu_{\mathcal{D}}\end{aligned} - 归一化过程随后在奖励模型训练之前和之后应用(lm_human_preferences/train_reward.py#L232-L234,lm_human_preferences/train_reward.py#L252-L254)。
- 请注意,我们为归一化目的生成的响应 y∼ρ(⋅∣x) y \sim \rho(·|x) 来自预训练语言模型 ρ\rho 。模型 ρ\rho 作为参考固定不变,在奖励学习中不会更新(lm_human_preferences/train_reward.py#L286C1-L286C31)。
- 在论文中,Ziegler 等人(2019)提到“为了保持奖励模型的尺度在训练过程中一致,我们对其进行归一化,使其对于 x∼D,y∼ρ(⋅∣x) x \sim \mathcal{D}, y \sim \rho(·|x) 具有均值 0 和方差 1。”为了执行归一化过程,代码首先创建一个
策略训练实施细节
在本节中,我们将深入探讨诸如层初始化、数据后处理和dropout设置等细节。我们还将探索拒绝采样和奖励“白化”以及自适应KL等技术。以下是这些细节,不分先后顺序:
通过采样温度缩放logits。
- 在计算响应的对数概率时,模型首先输出响应中token的logits,然后将logits除以采样温度(lm_human_preferences/policy.py#L121)。即,
logits /= self.temperature - 在一次非正式测试中,我们发现如果没有这种缩放,KL会以超出预期的速度上升,性能也会恶化。
- 在计算响应的对数概率时,模型首先输出响应中token的logits,然后将logits除以采样温度(lm_human_preferences/policy.py#L121)。即,
价值头层初始化
- 价值头的权重根据 N(0,0)\mathcal{N}\left(0,0\right) 初始化(lm_human_preferences/language/model.py#L368, lm_human_preferences/language/model.py#L251-L252)。这是
- 奖励头的偏置设置为0(lm_human_preferences/language/model.py#L254)。
选择以句号开始和结束的查询文本
- This is done as part of the data preprocessing;
- 尝试仅选择
start_text="."之后的文本(lm_human_preferences/language/datasets.py#L51) - 尝试选择
end_text="."之前的文本(lm_human_preferences/language/datasets.py#L61) - 然后填充文本(lm_human_preferences/language/datasets.py#L66-L67)
- 尝试仅选择
- 在运行
openai/lm-human-preferences时,OAI的数据集部分损坏/丢失(openai/lm-human-preferences/issues/17#issuecomment-104405149),因此我们不得不将它们替换为类似的HF数据集,这可能会导致性能差异,也可能不会) - 对于书籍数据集,我们使用了 https://huggingface.co/datasets/bookcorpus,我们发现没有必要提取以句号开始和结束的句子,因为该数据集已经以这种方式预处理过(例如,
"usually , he would be tearing around the living room , playing with his toys .")。为此,我们为sentiment和descriptiveness任务设置了start_text=None, end_text=None。
- This is done as part of the data preprocessing;
禁用dropout
- Ziegler等人(2019)建议,“我们不使用dropout进行策略训练。”这在代码中也得到了体现(lm_human_preferences/policy.py#L48)。
拒绝采样
- Ziegler等人(2019)建议,“我们使用拒绝采样来确保token 16到24之间有一个句号,然后在该句号处截断(这是对‘句子结束’的粗略近似。我们选择它是因为它易于集成到RL循环中,即使粗略近似也足以实现使人类评估任务稍微容易一些的预期目的)。在RL微调期间,我们通过给予固定奖励−1来惩罚没有这种句号的延续。”
- Specifically, this is achieved with the following steps:
Token截断:我们希望在响应中首次出现位于位置
truncate_after或之后的truncate_token处进行截断(lm_human_preferences/train_policy.py#L378)- 代码注释:“中心示例:将truncate_token之后的所有token替换为padding_token”
在截断响应上运行奖励模型:在响应被 token 截断过程截断后,代码会在截断响应上运行奖励模型。
拒绝采样:如果 token 16 和 24 之间没有句号,则将响应的分数替换为固定的低值(例如 -1)(lm_human_preferences/train_policy.py#L384,lm_human_preferences/train_policy.py#L384-L402)
- 代码注释:“中心示例:确保样本包含
truncate_token” - 代码注释:“仅对通过该函数的响应查询人类”
- 代码注释:“中心示例:确保样本包含
在
descriptiveness中给出一些示例:从我们的复现中提取的样本 https://wandb.ai/openrlbenchmark/lm_human_preference_details/runs/djf8yymv/logs。注意第 1 个和第 3 个示例在句号后 token 过多,因此其分数被替换为 -1。
折扣因子 = 1
- 折扣参数 γ\gamma 设置为 1(lm_human_preferences/train_policy.py#L56),这意味着未来奖励与即时奖励具有相同的权重。
训练循环的术语:PPO 中的批次和小批次
OAI 使用以下训练循环(lm_human_preferences/train_policy.py#L184-L192)。注意:我们额外添加了
micro_batch_size以帮助处理梯度累积中的情况。在每个 epoch,它会打乱批次索引。import numpy as np batch_size = 8 nminibatches = 2 gradient_accumulation_steps = 2 mini_batch_size = batch_size // nminibatches micro_batch_size = mini_batch_size // gradient_accumulation_steps data = np.arange(batch_size).astype(np.float32) print("data:", data) print("batch_size:", batch_size) print("mini_batch_size:", mini_batch_size) print("micro_batch_size:", micro_batch_size) for epoch in range(4): batch_inds = np.random.permutation(batch_size) print("epoch:", epoch, "batch_inds:", batch_inds) for mini_batch_start in range(0, batch_size, mini_batch_size): mini_batch_end = mini_batch_start + mini_batch_size mini_batch_inds = batch_inds[mini_batch_start:mini_batch_end] # `optimizer.zero_grad()` set optimizer to zero for gradient accumulation for micro_batch_start in range(0, mini_batch_size, micro_batch_size): micro_batch_end = micro_batch_start + micro_batch_size micro_batch_inds = mini_batch_inds[micro_batch_start:micro_batch_end] print("____⏩ a forward pass on", data[micro_batch_inds]) # `optimizer.step()` print("⏪ a backward pass on", data[mini_batch_inds]) # data: [0. 1. 2. 3. 4. 5. 6. 7.] # batch_size: 8 # mini_batch_size: 4 # micro_batch_size: 2 # epoch: 0 batch_inds: [6 4 0 7 3 5 1 2] # ____⏩ a forward pass on [6. 4.] # ____⏩ a forward pass on [0. 7.] # ⏪ a backward pass on [6. 4. 0. 7.] # ____⏩ a forward pass on [3. 5.] # ____⏩ a forward pass on [1. 2.] # ⏪ a backward pass on [3. 5. 1. 2.] # epoch: 1 batch_inds: [6 7 3 2 0 4 5 1] # ____⏩ a forward pass on [6. 7.] # ____⏩ a forward pass on [3. 2.] # ⏪ a backward pass on [6. 7. 3. 2.] # ____⏩ a forward pass on [0. 4.] # ____⏩ a forward pass on [5. 1.] # ⏪ a backward pass on [0. 4. 5. 1.] # epoch: 2 batch_inds: [1 4 5 6 0 7 3 2] # ____⏩ a forward pass on [1. 4.] # ____⏩ a forward pass on [5. 6.] # ⏪ a backward pass on [1. 4. 5. 6.] # ____⏩ a forward pass on [0. 7.] # ____⏩ a forward pass on [3. 2.] # ⏪ a backward pass on [0. 7. 3. 2.] # epoch: 3 batch_inds: [7 2 4 1 3 0 6 5] # ____⏩ a forward pass on [7. 2.] # ____⏩ a forward pass on [4. 1.] # ⏪ a backward pass on [7. 2. 4. 1.] # ____⏩ a forward pass on [3. 0.] # ____⏩ a forward pass on [6. 5.] # ⏪ a backward pass on [3. 0. 6. 5.]
每 token KL 惩罚
- 代码向奖励中添加了每 token KL 惩罚(lm_human_preferences/train_policy.py#L150-L153),以阻止策略与原始策略差异过大。
- Using the
"usually, he would"as an example, it gets tokenized to[23073, 11, 339, 561]. Say we use[23073]as the query and[11, 339, 561]as the response. Then under the defaultgpt2parameters, the response tokens will have log probabilities of the reference policylogprobs=[-3.3213, -4.9980, -3.8690].- 在第一个 PPO 更新 epoch 和小批次更新期间,因此活动策略将具有相同的对数概率
new_logprobs=[-3.3213, -4.9980, -3.8690]。,因此每 token KL 惩罚将为kl = new_logprobs - logprobs = [0., 0., 0.,] - 然而,在第一次梯度反向传播之后,我们可能有
new_logprob=[-3.6528, -5.0406, -3.2339],因此每 token KL 惩罚变为kl = new_logprobs - logprobs = [-0.3315, -0.0426, 0.6351] - 然后
non_score_reward = beta * kl,其中beta是 KL 惩罚系数 β\beta,它被添加到从奖励模型获得的score中,以创建用于训练的rewards。score仅在 episode 结束时给出;它可能看起来像[0.4,],并且我们有rewards = [beta * -0.3315, beta * -0.0426, beta * 0.6351 + 0.4]。
- 在第一个 PPO 更新 epoch 和小批次更新期间,因此活动策略将具有相同的对数概率
每小批次奖励和优势白化,可选均值偏移
- OAI 实现了一个
whiten函数,如下所示,基本上通过减去其均值然后除以其标准差来归一化values。可选地,whiten可以用shift_mean=True将白化后的values的均值移回。
def whiten(values, shift_mean=True): mean, var = torch.mean(values), torch.var(values, unbiased=False) whitened = (values - mean) * torch.rsqrt(var + 1e-8) if not shift_mean: whitened += mean return whitened在每个小批次中,OAI 然后白化奖励
whiten(rewards, shift_mean=False)而不移动均值(lm_human_preferences/train_policy.py#L325),并白化优势whiten(advantages)并移动均值(lm_human_preferences/train_policy.py#L338)。优化说明:如果小批次数量为 1(本复现中就是这种情况),我们只需要白化奖励,计算并白化优势一次,因为它们的值不会改变。
TensorFlow 与 PyTorch 说明:
tf.moments与torch.var的不同行为:白化的行为在 torch 和 tf 中不同,因为方差计算不同:import numpy as np import tensorflow as tf import torch def whiten_tf(values, shift_mean=True): mean, var = tf.nn.moments(values, axes=list(range(values.shape.rank))) mean = tf.Print(mean, [mean], 'mean', summarize=100) var = tf.Print(var, [var], 'var', summarize=100) whitened = (values - mean) * tf.rsqrt(var + 1e-8) if not shift_mean: whitened += mean return whitened def whiten_pt(values, shift_mean=True, unbiased=True): mean, var = torch.mean(values), torch.var(values, unbiased=unbiased) print("mean", mean) print("var", var) whitened = (values - mean) * torch.rsqrt(var + 1e-8) if not shift_mean: whitened += mean return whitened rewards = np.array([ [1.2, 1.3, 1.4], [1.5, 1.6, 1.7], [1.8, 1.9, 2.0], ]) with tf.Session() as sess: print(sess.run(whiten_tf(tf.constant(rewards, dtype=tf.float32), shift_mean=False))) print(whiten_pt(torch.tensor(rewards), shift_mean=False, unbiased=True)) print(whiten_pt(torch.tensor(rewards), shift_mean=False, unbiased=False))mean[1.5999999] var[0.0666666627] [[0.05080712 0.4381051 0.8254035 ] [1.2127019 1.6000004 1.9872988 ] [2.3745968 2.7618952 3.1491938 ]] mean tensor(1.6000, dtype=torch.float64) var tensor(0.0750, dtype=torch.float64) tensor([[0.1394, 0.5046, 0.8697], [1.2349, 1.6000, 1.9651], [2.3303, 2.6954, 3.0606]], dtype=torch.float64) mean tensor(1.6000, dtype=torch.float64) var tensor(0.0667, dtype=torch.float64) tensor([[0.0508, 0.4381, 0.8254], [1.2127, 1.6000, 1.9873], [2.3746, 2.7619, 3.1492]], dtype=torch.float64)
- OAI 实现了一个
裁剪值函数
- 如原始 PPO 中所做(baselines/ppo2/model.py#L68-L75),值函数以与策略目标类似的方式被裁剪(lm_human_preferences/train_policy.py#L343-L348)。
自适应 KL
KL 散度惩罚系数 β\beta 会根据当前策略与先前策略之间的 KL 散度进行自适应调整。如果 KL 散度超出预定义的目标范围,则调整惩罚系数以使其更接近目标范围(lm_human_preferences/train_policy.py#L115-L124)。其实现如下:
class AdaptiveKLController: def __init__(self, init_kl_coef, hparams): self.value = init_kl_coef self.hparams = hparams def update(self, current, n_steps): target = self.hparams.target proportional_error = np.clip(current / target - 1, -0.2, 0.2) mult = 1 + proportional_error * n_steps / self.hparams.horizon self.value *= mult对于本工作中考察的
sentiment和descriptiveness任务,我们有init_kl_coef=0.15, hparams.target=6, hparams.horizon=10000。
PyTorch Adam 优化器在 RLHF 中的数值问题
- 这个实现细节非常有趣,值得用一整节来讨论。
- PyTorch Adam 优化器(torch.optim.Adam.html)与 TensorFlow 的 Adam 优化器(TF1 Adam 见 tensorflow/v1.15.2/adam.py,TF2 Adam 见 keras/adam.py#L26-L220)实现不同。具体来说,PyTorch 遵循 Kingma 和 Ba 的 Adam 论文中的算法 1(arxiv/1412.6980),但 TensorFlow 使用的是该论文第 2.1 节之前的公式,此处提到的
epsilon对应论文中的epsilon hat。在伪代码比较中,我们有以下内容
### pytorch adam implementation:
bias_correction1 = 1 - beta1 ** step
bias_correction2 = 1 - beta2 ** step
step_size = lr / bias_correction1
bias_correction2_sqrt = _dispatch_sqrt(bias_correction2)
denom = (exp_avg_sq.sqrt() / bias_correction2_sqrt).add_(eps)
param.addcdiv_(exp_avg, denom, value=-step_size)
### tensorflow adam implementation:
lr_t = lr * _dispatch_sqrt((1 - beta2 ** step)) / (1 - beta1 ** step)
denom = exp_avg_sq.sqrt().add_(eps)
param.addcdiv_(exp_avg, denom, value=-lr_t)
- 让我们比较 pytorch 风格和 tensorflow 风格 adam 的更新方程。按照 adam 论文的符号 (Kingma and Ba, 2014),我们得到 pytorch adam(Kingma 和 Ba 论文的算法 1)和 tensorflow 风格 adam(Kingma 和 Ba 论文第 2.1 节之前的公式)的梯度更新规则如下:
pytorch adam :θt=θt−1−α⋅m^t/(v^t+ε)=θt−1−α[mt/(1−β1t)]⏟=m^t/[vt/(1−β2t)⏟=v^t+ε]=θt−1−α[mt/(1−β1t)]1−β2tvt+ε1−β2t\begin{aligned}\text{pytorch adam :}\quad \theta_t & =\theta_{t-1}-\alpha \cdot \hat{m}_t /\left(\sqrt{\hat{v}_t}+\varepsilon\right) \\& =\theta_{t-1}- \alpha \underbrace{\left[m_t /\left(1-\beta_1^t\right)\right]}_{=\hat{m}_t} /\left[\sqrt{\underbrace{v_t /\left(1-\beta_2^t\right)}_{=\hat{v}_t} }+\varepsilon\right]\\& =\theta_{t-1}- \alpha\left[m_t /\left(1-\beta_1^t\right)\right]\frac{\sqrt{1-\beta_2^t}}{\sqrt{v_t}+\color{green}{\varepsilon \sqrt{1-\beta_2^t}}}\end{aligned}
tensorflow adam:θt=θt−1−αtmt/(vt+ε^)=θt−1−[α1−β2t/(1−β1t)]⏟=αtmt/(vt+ε^)=θt−1−α[mt/(1−β1t)]1−β2tvt+ε^\begin{aligned}\text{tensorflow adam:}\quad \theta_t & =\theta_{t-1}-\alpha_t m_t /\left(\sqrt{v_t}+\hat{\varepsilon}\right) \\& =\theta_{t-1}-\underbrace{\left[\alpha \sqrt{1-\beta_2^t} /\left(1-\beta_1^t\right)\right]}_{=\alpha_t} m_t /\left(\sqrt{v_t}+\hat{\varepsilon}\right) \\& =\theta_{t-1}- \alpha\left[m_t /\left(1-\beta_1^t\right)\right] \frac{\sqrt{1-\beta_2^t}}{\sqrt{v_t}+\color{green}{\hat{\varepsilon}}} \end{aligned}
上述方程强调了 pytorch 和 tensorflow 实现之间的区别在于它们的归一化项,ε1−β2t\color{green}{\varepsilon \sqrt{1-\beta_2^t}} 和 ε^\color{green}{\hat{\varepsilon}}。如果我们设置 ε^=ε1−β2t\hat{\varepsilon} =\varepsilon \sqrt{1-\beta_2^t},这两个版本是等价的。然而,在 pytorch 和 tensorflow 的 API 中,我们只能通过
eps参数设置 ε\varepsilon(pytorch)和 ε^\hat{\varepsilon}(tensorflow),导致它们的更新方程存在差异。如果我们把 ε\varepsilon 和 ε^\hat{\varepsilon} 设置为相同的值,比如 1e-5 呢?那么对于 tensorflow adam,归一化项 ε^=1e-5\hat{\varepsilon} = \text{1e-5} 只是一个常数。但对于 pytorch adam,归一化项 ε1−β2t{\varepsilon \sqrt{1-\beta_2^t}} 随时间变化。重要的是,在时间步 tt 较小时,它最初远小于 1e-5,随着时间步增加,项 ε1−β2t{\varepsilon \sqrt{1-\beta_2^t}} 逐渐接近 1e-5。下图比较了这两个归一化项随时间步的变化:上图显示,如果我们在 pytorch adam 和 tensorflow adam 中设置相同的
eps,那么在训练早期,pytorch-adam 使用的归一化项远小于 tensorflow-adam。换句话说,pytorch adam 在训练早期进行更激进的梯度更新。我们的实验支持这一发现,如下所示。这如何影响可复现性和性能?为了对齐设置,我们从 https://github.com/openai/lm-human-preferences 记录原始查询、响应和奖励,并保存在 https://huggingface.co/datasets/vwxyzjn/lm-human-preferences-debug/tree/main。我还记录了使用 TF1 的
AdamOptimizer优化器进行前两个 epoch 训练的指标作为基准。以下是一些关键指标:OAI 的 TF1 Adam PyTorch 的 Adam 我们自定义的 Tensorflow 风格 Adam policy/approxkl 0.00037167023 0.0023672834504395723 0.000374998344341293 policy/clipfrac 0.0045572915 0.02018229104578495 0.0052083334885537624 ratio_mean 1.0051285 1.0105520486831665 1.0044583082199097 ratio_var 0.0007716546 0.005374275613576174 0.0007942612282931805 ratio_max 1.227216 1.8121057748794556 1.250215768814087 ratio_min 0.7400441 0.4011387825012207 0.7299948930740356 logprob_diff_mean 0.0047487603 0.008101251907646656 0.004073789343237877 logprob_diff_var 0.0007207897 0.004668936599045992 0.0007334011606872082 logprob_diff_max 0.20474821 0.594489574432373 0.22331619262695312 logprob_diff_min -0.30104542 -0.9134478569030762 -0.31471776962280273 PyTorch 的
Adam由于某种原因产生了更激进的更新。以下是一些证据:- PyTorch 的
Adam的logprob_diff_var高出 6 倍。这里logprobs_diff = new_logprobs - logprobs是训练两个 epoch 后初始策略和当前策略之间 token 对数概率的差异。具有更大的logprob_diff_var意味着对数概率变化的规模大于 OAI 的 TF1 Adam。 - PyTorch 的
Adam呈现出更极端的比率最大值和最小值。这里ratio = torch.exp(logprobs_diff)。具有ratio_max=1.8121057748794556意味着对于某些 token,在当前策略下采样该 token 的概率是 1.8 倍,而 OAI 的 TF1 Adam 只有 1.2 倍。 - 更大的
policy/approxklpolicy/clipfrac。由于激进的更新,比率被裁剪的频率高出 4.4 倍,近似 KL 散度大 6 倍。 - 这次激进的更新很可能会导致更多问题。例如,
logprob_diff_mean在 PyTorch 的Adam中大了 1.7 倍,这相当于在下一次奖励计算中 KL 惩罚大了 1.7 倍;这可能会被进一步放大。事实上,这可能与著名的 KL 散度问题有关——KL 惩罚比应有的值大得多,模型可能会更关注它并更多地针对它进行优化,从而导致负的 KL 散度。
- PyTorch 的
更大的模型受影响更大。我们进行了实验,比较了 PyTorch 的
Adam(代号pt_adam)和我们自定义的 TensorFlow 风格实现(代号tf_adam),分别使用gpt2和gpt2-xl。我们发现,在gpt2下性能大致相似;然而在使用gpt2-xl时,我们观察到更新更为激进,这意味着更大的模型受此问题影响更大。- 当
gpt2-xl中的初始策略更新更为激进时,训练动态会受到影响。例如,我们观察到使用pt_adam时objective/kl和objective/scores的尖峰要大得多,尤其是在使用sentiment时——在其中一个随机种子中,最大的 KL 高达 17.5,表明出现了不理想的过度优化。 - 此外,由于 KL 更大,许多其他训练指标也受到影响。例如,我们观察到
clipfrac(ratio被 PPO 目标裁剪系数 0.2 裁剪的时间比例)和approxkl都要大得多。
- 当
局限性
注意到这项工作并未尝试复现 CNN DM 或 TL;DR 中的摘要工作。这是因为我们发现训练既耗时又脆弱。
我们进行的那次特定训练运行显示出较低的 GPU 利用率(约 30%),因此完成一次训练运行几乎需要 4 天,成本非常高(只有 AWS 出售 p3dn.24xlarge,每小时 31.212 美元)
此外,训练很脆弱。虽然奖励上升了,但我们发现很难复现 Ziegler 等人(2019)所报告的“智能复制器”行为。以下是一些示例输出——显然,智能体在某种程度上过拟合了。更完整的日志请参见 https://wandb.ai/openrlbenchmark/lm-human-preferences/runs/1ab47rqi/logs。
结论
在这项工作中,我们深入研究了 OAI 最初的 RLHF 代码库,并整理了其实现细节清单。我们还创建了一个最小基础版本,在控制数据集和超参数的情况下,能够复现与 OAI 最初 RLHF 代码库相同的学习曲线。此外,我们发现了令人惊讶的实现细节,例如 adam 优化器的设置会在 RLHF 训练早期导致激进的更新。
致谢
这项工作得到了 Hugging Face 的 Big Science 集群 🤗 的支持。我们还要感谢与 @lewtun 和 @natolambert 的有益讨论。
Bibtex
@article{Huang2023implementation,
author = {Huang, Shengyi and Liu, Tianlin and von Werra, Leandro},
title = {The N Implementation Details of RLHF with PPO},
journal = {Hugging Face Blog},
year = {2023},
note = {https://huggingface.co/blog/the_n_implementation_details_of_rlhf_with_ppo},
}
来源:Hugging Face Blog · huggingface.co

. Notice the 1st and 3rd example has too many tokens after the period, so its score was replaced by -1.](/api/img-proxy?u=https%3A%2F%2Fhuggingface.co%2Fdatasets%2Ftrl-internal-testing%2Fexample-images%2Fresolve%2Fmain%2Frlhf_implementation_details%2FUntitled%25201.png&mode=full&exp=1796428800&sig=59e1e91685ae39f4)




