仓库不含任何已训练模型,需自备数百万美元级算力与数据自行训练;示例默认在 CUDA 上运行,无 GPU 需自行改设备;项目标注为 wip,部分 Todo 功能尚未实现

PaLM-rlhf-pytorch
lucidrainsMIT活跃维护在 PaLM 架构上实现 RLHF 人类反馈强化学习,复现 ChatGPT 式训练流程,适合研究大模型对齐与强化学习微调。
Implementation of RLHF (Reinforcement Learning with Human Feedback) on top of the PaLM architecture. Basically ChatGPT but with PaLM
pip install palm-rlhf-pytorchREADME 未说明具体显存要求,示例代码使用 .cuda(),需 NVIDIA GPU 环境
在 PaLM 架构上实现 RLHF 的开源框架,帮你搭建类似 ChatGPT 的训练流程
在 PaLM 架构上实现 RLHF 人类反馈强化学习,复现 ChatGPT 式训练流程,适合研究大模型对齐与强化学习微调。
核心能力
- 提供 PaLM 自回归 Transformer 训练与生成
- 内置 RewardModel 支持分箱打分与 LoRA 微调
- RLHFTrainer 串联 PPO 式强化学习训练
- 集成 Flash Attention 加速注意力计算
- 生成时可用奖励模型从多采样中选最优
容易踩的坑
- 0.7.1最新正式版2025-09-19 · 2025-09-19 17:04 UTC
- 0.6.32025-09-02 · 2025-09-02 19:37 UTC
查看更新说明
- 0.6.22025-09-02 · 2025-09-02 15:37 UTC
查看更新说明
- 0.6.12025-09-02 · 2025-09-02 15:02 UTC
查看更新说明
- 0.6.02025-09-02 · 2025-09-02 14:54 UTC
查看更新说明
用户点评
登录用户的真实使用记录,可按版本和硬件筛选还没有人点评。第一个说出真实体验的人最有价值。
official chatgpt blogpost
PaLM + RLHF - Pytorch (wip)
Implementation of RLHF (Reinforcement Learning with Human Feedback) on top of the PaLM architecture. Maybe I'll add retrieval functionality too, à la RETRO
If you are interested in replicating something like ChatGPT out in the open, please consider joining Laion
Potential successor: Direct Preference Optimization - all the code in this repo becomes ~ binary cross entropy loss, < 5 loc. So much for Reward models and PPO
FAQ
- Does this contain a model for inference?
There is no trained model. This is just the ship and overall map. We still need millions of dollars of compute + data to sail to the correct point in high dimensional parameter space. Even then, you need professional sailors (like Robin Rombach of Stable Diffusion fame) to actually guide the ship through turbulent times to that point.
Community
CarperAI had been working on an RLHF framework for large language models for many months prior to the release of ChatGPT.
Yannic Kilcher is also working on an open sourced implementation
AI Coffeebreak w/ Letitia | Code Emporium | Code Emporium Part 2
Appreciation
-
Stability.ai for the generous sponsorship to work on cutting edge artificial intelligence research
-
🤗 Hugging Face and CarperAI for penning the blog post Illustrating Reinforcement Learning from Human Feedback (RLHF), and the former also for their accelerate library
-
@kisseternity and @taynoel84 for the code review and finding bugs
-
Enrico for integrating Flash Attention from Pytorch 2.0
-
bycloud for his educational video for Reasoning with Exploration
Install
$ pip install palm-rlhf-pytorch
Usage
First train PaLM, like any other autoregressive transformer
import torch
from palm_rlhf_pytorch import PaLM
palm = PaLM(
num_tokens = 20000,
dim = 512,
depth = 12,
flash_attn = True # https://arxiv.org/abs/2205.14135
).cuda()
seq = torch.randint(0, 20000, (1, 2048)).cuda()
loss = palm(seq, return_loss = True)
loss.backward()
# after much training, you can now generate sequences
generated = palm.generate(2048) # (1, 2048)
Then train your reward model, with the curated human feedback. In the original paper, they could not get reward model to be finetuned from a pretrained transformer without overfitting, but I gave the option to finetune with LoRA anyways, since it is still open research.
import torch
from palm_rlhf_pytorch import PaLM, RewardModel
palm = PaLM(
num_tokens = 20000,
dim = 512,
depth = 12,
causal = False
)
reward_model = RewardModel(
palm,
num_binned_output = 5 # say rating from 1 to 5
).cuda()
# mock data
seq = torch.randint(0, 20000, (1, 1024)).cuda()
prompt_mask = torch.zeros(1, 1024).bool().cuda() # which part of the sequence is prompt, which part is response
labels = torch.randint(0, 5, (1,)).cuda()
# train
loss = reward_model(seq, prompt_mask = prompt_mask, labels = labels)
loss.backward()
# after much training
reward = reward_model(seq, prompt_mask = prompt_mask)
Then you will pass your transformer and the rewards model to the RLHFTrainer
import torch
from palm_rlhf_pytorch import PaLM, RewardModel, RLHFTrainer
# load your pretrained palm
palm = PaLM(
num_tokens = 20000,
dim = 512,
depth = 12
).cuda()
palm.load('./path/to/pretrained/palm.pt')
# load your pretrained reward model
reward_model = RewardModel(
palm,
num_binned_output = 5
).cuda()
reward_model.load('./path/to/pretrained/reward_model.pt')
# ready your list of prompts for reinforcement learning
prompts = torch.randint(0, 256, (50000, 512)).cuda() # 50k prompts
# pass it all to the trainer and train
trainer = RLHFTrainer(
palm = palm,
reward_model = reward_model,
prompt_token_ids = prompts
)
trainer.train(num_episodes = 50000)
# then, if it succeeded...
# generate say 10 samples and use the reward model to return the best one
answer = trainer.generate(2048, prompt = prompts[0], num_samples = 10) # (<= 2048,)
Todo
-
clone base transformer with separate lora for critic
-
also allow for non-LoRA based finetuning
-
redo normalize to be able to have a masked version, not sure if anyone will ever use per token rewards / values, but good practice to implement
-
equip with the best attention
-
add Hugging Face accelerate and test out wandb instrumentation
-
search literature to figure out what is the latest SOTA for PPO, assuming RL field is still making progress.
-
test the system using a pretrained sentiment network as reward model
-
write the memory in PPO to memmapped numpy file
-
get sampling with variable lengthed prompts working, even if it is not needed given bottleneck is human feedback
-
allow for finetuning penultimate N layers only in either actor or critic, assuming if pretrained
-
incorporate some learning points from Sparrow, given Letitia's video
-
simple web interface with django + htmx for collecting human feedback
-
consider RLAIF
Citations
@article{Stiennon2020LearningTS,
title = {Learning to summarize from human feedback},
author = {Nisan Stiennon and Long Ouyang and Jeff Wu and Daniel M. Ziegler and Ryan J. Lowe and Chelsea Voss and Alec Radford and Dario Amodei and Paul Christiano},
journal = {ArXiv},
year = {2020},
volume = {abs/2009.01325}
}
@inproceedings{Chowdhery2022PaLMSL,
title = {PaLM: Scaling Language Modeling with Pathways},
author = {Aakanksha Chowdhery and Sharan Narang and Jacob Devlin and Maarten Bosma and Gaurav Mishra and Adam Roberts and Paul Barham and Hyung Won Chung and Charles Sutton and Sebastian Gehrmann and Parker Schuh and Kensen Shi and Sasha Tsvyashchenko and Joshua Maynez and Abhishek Rao and Parker Barnes and Yi Tay and Noam M. Shazeer and Vinodkumar Prabhakaran and Emily Reif and Nan Du and Benton C. Hutchinson and Reiner Pope and James Bradbury and Jacob Austin and Michael Isard and Guy Gur-Ari and Pengcheng Yin and Toju Duke and Anselm Levskaya and Sanjay Ghemawat and Sunipa Dev and Henryk Michalewski and Xavier Garc{\'i}a and Vedant Misra and Kevin Robinson and Liam Fedus and Denny Zhou and Daphne Ippolito and David Luan and Hyeontaek Lim and Barret Zoph and Alexander Spiridonov and Ryan Sepassi and David Dohan and Shivani Agrawal and Mark Omernick and Andrew M. Dai and Thanumalayan Sankaranarayana Pillai and Marie Pellat and Aitor Lewkowycz and Erica Oliveira Moreira and Rewon Child and Oleksandr Polozov and Katherine Lee and Zongwei Zhou and Xuezhi Wang and Brennan Saeta and Mark Diaz and Orhan Firat and Michele Catasta and Jason Wei and Kathleen S. Meier-Hellstern and Douglas Eck and Jeff Dean and Slav Petrov and Noah Fiedel},
year = {2022}
}
@article{Hu2021LoRALA,
title = {LoRA: Low-Rank Adaptation of Large Language Models},
author = {Edward J. Hu and Yelong Shen and Phillip Wallis and Zeyuan Allen-Zhu and Yuanzhi Li and Shean Wang and Weizhu Chen},
journal = {ArXiv},
year = {2021},
volume = {abs/2106.09685}
}
@inproceedings{Sun2022ALT,
title = {A Length-Extrapolatable Transformer},
author = {Yutao Sun and Li Dong and Barun Patra and Shuming Ma and Shaohan Huang and Alon Benhaim and Vishrav Chaudhary and Xia Song and Furu Wei},
year = {2022}
}
@misc{gilmer2023intriguing
title = {Intriguing Properties of Transformer Training Instabilities},
author = {Justin Gilmer, Andrea Schioppa, and Jeremy Cohen},
year = {2023},
status = {to be published - one attention stabilization technique is circulating within Google Brain, being used by multiple teams}
}
@inproceedings{dao2022flashattention,
title = {Flash{A}ttention: Fast and Memory-Efficient Exact Attention with {IO}-Awareness},
author = {Dao, Tri and Fu, Daniel Y. and Ermon, Stefano and Rudra, Atri and R{\'e}, Christopher},
booktitle = {Advances in Neural Information Processing Systems},
year = {2022}
}
@misc{Rubin2024,
author = {Ohad Rubin},
url = {https://medium.com/@ohadrubin/exploring-weight-decay-in-layer-normalization-challenges-and-a-reparameterization-solution-ad4d12c24950}
}
@inproceedings{Yuan2024FreePR,
title = {Free Process Rewards without Process Labels},
author = {Lifan Yuan and Wendi Li and Huayu Chen and Ganqu Cui and Ning Ding and Kaiyan Zhang and Bowen Zhou and Zhiyuan Liu and Hao Peng},
year = {2024},
url = {https://api.semanticscholar.org/CorpusID:274445748}
}
@article{Shao2024DeepSeekMathPT,
title = {DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models},
author = {Zhihong Shao and Peiyi Wang and Qihao Zhu and Runxin Xu and Jun-Mei Song and Mingchuan Zhang and Y. K. Li and Yu Wu and Daya Guo},
journal = {ArXiv},
year = {2024},
volume = {abs/2402.03300},
url = {https://api.semanticscholar.org/CorpusID:267412607}
}
@article{Farebrother2024StopRT,
title = {Stop Regressing: Training Value Functions via Classification for Scalable Deep RL},
author = {Jesse Farebrother and Jordi Orbay and Quan Ho Vuong and Adrien Ali Taiga and Yevgen Chebotar and Ted Xiao and Alex Irpan and Sergey Levine and Pablo Samuel Castro and Aleksandra Faust and Aviral Kumar and Rishabh Agarwal},
journal = {ArXiv},
year = {2024},
volume = {abs/2403.03950},
url = {https://api.semanticscholar.org/CorpusID:268253088}
}
@misc{Liu2025,
title = {Understanding R1-Zero-Like Training: A Critical Perspective},
author = {Zichen Liu, Changyu Chen, Wenjun Li, Penghui Qi, Tianyu Pang, Chao Du, Wee Sun Lee, Min Lin},
url = {https://github.com/sail-sg/understand-r1-zero/blob/main/understand-r1-zero.pdf}
}
@inproceedings{Yue2025DoesRL,
title = {Does Reinforcement Learning Really Incentivize Reasoning Capacity in LLMs Beyond the Base Model?},
author = {Yang Yue and Zhiqi Chen and Rui Lu and Andrew Zhao and Zhaokai Wang and Shiji Song and Gao Huang},
year = {2025},
url = {https://api.semanticscholar.org/CorpusID:277940134}
}
@misc{xie2025simplepolicyoptimization,
title = {Simple Policy Optimization},
author = {Zhengpeng Xie and Qiang Zhang and Fan Yang and Marco Hutter and Renjing Xu},
year = {2025},
eprint = {2401.16025},
archivePrefix = {arXiv},
primaryClass = {cs.LG},
url = {https://arxiv.org/abs/2401.16025},
}
@misc{cheng2025reasoningexplorationentropyperspective,
title = {Reasoning with Exploration: An Entropy Perspective on Reinforcement Learning for LLMs},
author = {Daixuan Cheng and Shaohan Huang and Xuekai Zhu and Bo Dai and Wayne Xin Zhao and Zhenliang Zhang and Furu Wei},
year = {2025},
eprint = {2506.14758},
archivePrefix = {arXiv},
primaryClass = {cs.CL},
url = {https://arxiv.org/abs/2506.14758},
}
@article{Zhu2025FlowRL,
title = {FlowRL: Matching Reward Distributions for LLM Reasoning},
author = {Xuekai Zhu and Daixuan Cheng and Dinghuai Zhang and Hengli Li and Kaiyan Zhang and Che Jiang and Youbang Sun and Ermo Hua and Yuxin Zuo and Xingtai Lv and Qizheng Zhang and Lin Chen and Fanghao Shao and Bo Xue and Yunchong Song and Zhenjie Yang and Ganqu Cui and Ning Ding and Jianfeng Gao and Xiaodong Liu and Bowen Zhou and Hongyuan Mei and Zhouhan Lin},
journal = {ArXiv},
year = {2025},
volume = {abs/2509.15207},
eprint = {2509.15207},
archivePrefix = {arXiv},
primaryClass = {cs.LG},
url = {https://arxiv.org/abs/2509.15207}
}
@misc{kaddour2026targetpolicyoptimization,
title = {Target Policy Optimization},
author = {Jean Kaddour},
year = {2026},
eprint = {2604.06159},
archivePrefix = {arXiv},
primaryClass = {cs.LG},
url = {https://arxiv.org/abs/2604.06159},
}
@misc{tajwar2026maximumlikelihoodreinforcementlearning,
title = {Maximum Likelihood Reinforcement Learning},
author = {Fahim Tajwar and Guanning Zeng and Yueer Zhou and Yuda Song and Daman Arora and Yiding Jiang and Jeff Schneider and Ruslan Salakhutdinov and Haiwen Feng and Andrea Zanette},
year = {2026},
eprint = {2602.02710},
archivePrefix = {arXiv},
primaryClass = {cs.LG},
url = {https://arxiv.org/abs/2602.02710},
}
@misc{marek2026scorecenteringstabilizesoffpolicy,
title = {Score Centering Stabilizes Off-policy Reinforcement Learning},
author = {Martin Marek and Max Ryabinin},
year = {2026},
eprint = {2609.20807},
archivePrefix = {arXiv},
primaryClass = {cs.LG},
url = {https://arxiv.org/abs/2609.20807},
}