一、为什么需要推理模型?
一张经典的图
比如你问 GPT-4, 3.11 和 3.9 哪个大? GPT-4 的回答(3.11 大)是不对的,哈哈。 但是推理模型可以回答对。
基础大模型,可以看作一个复杂的映射。通过注意力机制等 捕获不同 token 间的关系,经全连接层拟合, softmax 后 转为一个向量, 向量中每一维 代表词表中对应词的概率。 再通过采样等方法 (如何 top-k, top-n)最终输出。
推理模型,通过强化学习增加了推理能力。每输出一个 token 都计算即时奖励, 目标是所有输出奖励期望最大化。这就好比同样回答一个问题,基础模型考虑的是单点 而推理模型是考虑的整体。
GRPO,PPO 等算法也可以说是对策略梯度算法的优化,比如加一些正则项, 加个 演员-裁判体系什么的。先把策略梯度弄明白再去理解 PPO, GRPO就很容易了。
二、GRPO 训练
GRPO 训练步骤
训练准备
a.模型准备:基础模型 > 1.5B参数
b.数据准备:准备 reasoning格式数据集 (question, answer, Cot), 可以 huggingface 搜索reasoning
c.价值函数:格式奖励函数等,或者自定义奖励函数
d.训练参数: num_generations ,epoch,adam w-8bit优化器,学习率调度器(预热,余弦退火),其他略
训练代码 https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Qwen2.5_(3B)-GRPO.ipynb#scrollTo=cXk993X6C2ZZ
训练日志
Step |
Training Loss |
reward |
reward_std |
completion_length |
kl |
1 |
0.000000 |
0.125000 |
0.000000 |
200.000000 |
0.000000 |
2 |
0.000000 |
0.072375 |
0.248112 |
200.000000 |
0.000000 |
3 |
0.000000 |
-0.079000 |
0.163776 |
182.500000 |
0.000005 |
注意事项
1.训练轮次:至少 1 个epoch,3个以上最佳。
2.本地使用 unsloth 需要安装pip install diffusers
3.基础模型: 参数至少 1.5 B
三、GRPO训练器
目标函数
看上去像是个复杂的函数, 实际上了解一遍发现很简单, 只需要计算三样东西:
重要性采样比率(那个带pi 的)
优势估计 (A_i)
KL 散度 (D_KL)
通过代码再理解下公式
损失计算代码实现
a._get_per_token_logps() 计算每个输入 token 的 logtis (最后一个隐藏层输出)后,使用 softmax得到概率
b.ref_per_token_logps, old_per_token_logps, per_token_logps(参考模型的输出概率, 用来代替奖励模型的概率, 当前演员模型的概率)
c.计算重要性采样比率
coef_1 = torch.exp(per_token_logps - old_per_token_logps)
d.计算 KL 散度
kl = torch.exp(ref_per_token_logps - per_token_logps) - (ref_per_token_logps - per_token_logps) - 1
e. 计算优势估计
\# Normalize the rewards to compute the advantages
mean\_grouped\_rewards = mean\_grouped\_rewards.repeat\_interleave(self.num\_generations, dim=0)
std\_grouped\_rewards = std\_grouped\_rewards.repeat\_interleave(self.num\_generations, dim=0)
advantages = (rewards - mean\_grouped\_rewards) / (std\_grouped\_rewards + 1e-4)
完整代码
\# 计算损失流程
def compute\_loss(self, model, inputs, return\_outputs=False, num\_items\_in\_batch=None):
if return\_outputs:
raise ValueError("The GRPOTrainer does not support returning outputs")
\# Compute the per-token log probabilities for the model
prompt\_ids, prompt\_mask = inputs\["prompt\_ids"\], inputs\["prompt\_mask"\]
completion\_ids, completion\_mask = inputs\["completion\_ids"\], inputs\["completion\_mask"\]
input\_ids = torch.cat(\[prompt\_ids, completion\_ids\], dim=1)
attention\_mask = torch.cat(\[prompt\_mask, completion\_mask\], dim=1)
logits\_to\_keep = completion\_ids.size(1) \# we only need to compute the logits for the completion tokens
per\_token\_logps = self.\_get\_per\_token\_logps(model, input\_ids, attention\_mask, logits\_to\_keep)
\# Compute the KL divergence between the model and the reference model
if self.beta != 0.0:
ref\_per\_token\_logps = inputs\["ref\_per\_token\_logps"\]
per\_token\_kl = (
torch.exp(ref\_per\_token\_logps - per\_token\_logps) - (ref\_per\_token\_logps - per\_token\_logps) - 1
)
\# Compute the loss
advantages = inputs\["advantages"\]
\# When using num\_iterations == 1, old\_per\_token\_logps == per\_token\_logps, so we can skip it's computation (see
\# \_generate\_and\_score\_completions) and use per\_token\_logps.detach() instead.
old\_per\_token\_logps = inputs\["old\_per\_token\_logps"\] if self.num\_iterations > 1 else per\_token\_logps.detach()
coef\_1 = torch.exp(per\_token\_logps - old\_per\_token\_logps)
coef\_2 = torch.clamp(coef\_1, 1 - self.epsilon, 1 + self.epsilon)
per\_token\_loss1 = coef\_1 \* advantages.unsqueeze(1)
per\_token\_loss2 = coef\_2 \* advantages.unsqueeze(1)
per\_token\_loss = -torch.min(per\_token\_loss1, per\_token\_loss2)
if self.beta != 0.0:
per\_token\_loss = per\_token\_loss + self.beta \* per\_token\_kl
loss = (per\_token\_loss \* completion\_mask).sum() / completion\_mask.sum()
\# Log the metrics
mode = "eval" if self.control.should\_evaluate else "train"
if self.beta != 0.0:
mean\_kl = ((per\_token\_kl \* completion\_mask).sum(dim=1) / completion\_mask.sum(dim=1)).mean()
self.\_metrics\[mode\]\["kl"\].append(self.accelerator.gather\_for\_metrics(mean\_kl).mean().item())
is\_clipped = (per\_token\_loss1 < per\_token\_loss2).float()
clip\_ratio = (is\_clipped \* completion\_mask).sum() / completion\_mask.sum()
self.\_metrics\[mode\]\["clip\_ratio"\].append(self.accelerator.gather\_for\_metrics(clip\_ratio).mean().item())
return loss
\# 计算每个token的输出概率分布
def \_get\_per\_token\_logps(self, model, input\_ids, attention\_mask, logits\_to\_keep):
\# We add 1 to \`logits\_to\_keep\` because the last logits of the sequence is later excluded
logits = model(input\_ids=input\_ids, attention\_mask=attention\_mask, logits\_to\_keep=logits\_to\_keep + 1).logits
logits = logits\[:, :-1, :\] \# (B, L-1, V), exclude the last logit: it corresponds to the next token pred
input\_ids = input\_ids\[:, -logits\_to\_keep:\]
\# For transformers<=4.48, logits\_to\_keep argument isn't supported, so here we drop logits ourselves.
\# See https://github.com/huggingface/trl/issues/2770
logits = logits\[:, -logits\_to\_keep:\]
return selective\_log\_softmax(logits, input\_ids) # compute logprobs for the input tokens
\# 计算损失前的 计算输入部分
def \_generate\_and\_score\_completions(
self, inputs: dict\[str, Union\[torch.Tensor, Any\]\]
) -> dict\[str, Union\[torch.Tensor, Any\]\]:
\# 。。。。
\# Normalize the rewards to compute the advantages
mean\_grouped\_rewards = mean\_grouped\_rewards.repeat\_interleave(self.num\_generations, dim=0)
std\_grouped\_rewards = std\_grouped\_rewards.repeat\_interleave(self.num\_generations, dim=0)
advantages = (rewards - mean\_grouped\_rewards) / (std\_grouped\_rewards + 1e-4)
\# 。。。。
四、总结
理解策略梯度是基础, 就很容易看懂 PPO 和 GRPO,懂了 PPO 自然就明白 GRPO。
对于弄懂损失的计算 和 损失计算的实现比较重要。
当然还有 还有 MLA (多头潜在注意力), MOE (混合专家模型)等等
五、如何系统学习掌握AI大模型?
AI大模型作为人工智能领域的重要技术突破,正成为推动各行各业创新和转型的关键力量。抓住AI大模型的风口,掌握AI大模型的知识和技能将变得越来越重要。
学习AI大模型是一个系统的过程,需要从基础开始,逐步深入到更高级的技术。
这里给大家精心整理了一份
全面的AI大模型学习资源
,包括:AI大模型全套学习路线图(从入门到实战)、精品AI大模型学习书籍手册、视频教程、实战学习、面试题等,资料免费分享
!
1. 成长路线图&学习规划
要学习一门新的技术,作为新手一定要先学习成长路线图,方向不对,努力白费。
这里,我们为新手和想要进一步提升的专业人士准备了一份详细的学习成长路线图和规划。可以说是最科学最系统的学习成长路线。
2. 大模型经典PDF书籍
书籍和学习文档资料是学习大模型过程中必不可少的,我们精选了一系列深入探讨大模型技术的书籍和学习文档,它们由领域内的顶尖专家撰写,内容全面、深入、详尽,为你学习大模型提供坚实的理论基础。(书籍含电子版PDF)
3. 大模型视频教程
对于很多自学或者没有基础的同学来说,书籍这些纯文字类的学习教材会觉得比较晦涩难以理解,因此,我们提供了丰富的大模型视频教程,以动态、形象的方式展示技术概念,帮助你更快、更轻松地掌握核心知识。
4. 2024行业报告
行业分析主要包括对不同行业的现状、趋势、问题、机会等进行系统地调研和评估,以了解哪些行业更适合引入大模型的技术和应用,以及在哪些方面可以发挥大模型的优势。
5. 大模型项目实战
学以致用 ,当你的理论知识积累到一定程度,就需要通过项目实战,在实际操作中检验和巩固你所学到的知识,同时为你找工作和职业发展打下坚实的基础。
6. 大模型面试题
面试不仅是技术的较量,更需要充分的准备。
在你已经掌握了大模型技术之后,就需要开始准备面试,我们将提供精心整理的大模型面试题库,涵盖当前面试中可能遇到的各种技术问题,让你在面试中游刃有余。
全套的AI大模型学习资源已经整理打包,有需要的小伙伴可以
微信扫描下方CSDN官方认证二维码
,免费领取【保证100%免费
】