{"id":13498751,"url":"https://github.com/lucidrains/PaLM-rlhf-pytorch","last_synced_at":"2025-03-29T01:32:33.944Z","repository":{"id":64615824,"uuid":"576380523","full_name":"lucidrains/PaLM-rlhf-pytorch","owner":"lucidrains","description":"Implementation of RLHF (Reinforcement Learning with Human Feedback) on top of the PaLM architecture. Basically ChatGPT but with PaLM","archived":false,"fork":false,"pushed_at":"2024-01-14T17:55:25.000Z","size":35938,"stargazers_count":7694,"open_issues_count":16,"forks_count":666,"subscribers_count":143,"default_branch":"main","last_synced_at":"2024-10-29T15:02:54.312Z","etag":null,"topics":["artificial-intelligence","attention-mechanisms","deep-learning","human-feedback","reinforcement-learning","transformers"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/lucidrains.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-12-09T17:53:46.000Z","updated_at":"2024-10-29T12:38:06.000Z","dependencies_parsed_at":"2024-06-18T18:38:29.091Z","dependency_job_id":null,"html_url":"https://github.com/lucidrains/PaLM-rlhf-pytorch","commit_stats":{"total_commits":122,"total_committers":6,"mean_commits":"20.333333333333332","dds":"0.12295081967213117","last_synced_commit":"6b02ee329106baff78e293afa7d1d2e6dd4e5ca2"},"previous_names":[],"tags_count":81,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lucidrains%2FPaLM-rlhf-pytorch","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lucidrains%2FPaLM-rlhf-pytorch/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lucidrains%2FPaLM-rlhf-pytorch/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lucidrains%2FPaLM-rlhf-pytorch/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/lucidrains","download_url":"https://codeload.github.com/lucidrains/PaLM-rlhf-pytorch/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246126108,"owners_count":20727529,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["artificial-intelligence","attention-mechanisms","deep-learning","human-feedback","reinforcement-learning","transformers"],"created_at":"2024-07-31T21:00:42.738Z","updated_at":"2025-03-29T01:32:33.930Z","avatar_url":"https://github.com/lucidrains.png","language":"Python","funding_links":[],"categories":["Python","A01_文本生成_文本对话","Models","Other","Codebases","精选开源项目合集","Awesome RHLF","RLHF"],"sub_categories":["大语言对话模型及数据","Other sdk/libraries","2020 and before","GPT开源平替机器人","GPT开源平替机器人🔥🔥🔥","Tools and Resources","LLMOps vs MLOps"],"readme":"\u003cimg src=\"./chatgpt.png\" width=\"450px\"\u003e\u003c/img\u003e\n\n*\u003ca href=\"https://openai.com/blog/chatgpt/\"\u003eofficial chatgpt blogpost\u003c/a\u003e*\n\n## PaLM + RLHF - Pytorch (wip)\n\nImplementation of RLHF (Reinforcement Learning with Human Feedback) on top of the PaLM architecture. Maybe I'll add retrieval functionality too, à la \u003ca href=\"https://github.com/lucidrains/RETRO-pytorch\"\u003eRETRO\u003c/a\u003e\n\nIf you are interested in replicating something like ChatGPT out in the open, please consider joining \u003ca href=\"https://discord.gg/xBPBXfcFHd\"\u003eLaion \u003cimg alt=\"Join us on Discord\" src=\"https://img.shields.io/discord/823813159592001537?color=5865F2\u0026logo=discord\u0026logoColor=white\"\u003e\u003c/a\u003e\n\nPotential successor: \u003ca href=\"https://arxiv.org/abs/2305.18290\"\u003eDirect Preference Optimization\u003c/a\u003e - all the code in this repo becomes ~ binary cross entropy loss, \u003c 5 loc. So much for Reward models and PPO\n\n## FAQ\n\n- Does this contain a model for inference?\n\nThere 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.\n\n## Community\n\n\u003ca href=\"https://carper.ai/\"\u003eCarperAI\u003c/a\u003e had been working on \u003ca href=\"https://github.com/CarperAI/trlx\"\u003ean RLHF framework\u003c/a\u003e for large language models for many months prior to the release of ChatGPT.\n\n\u003ca href=\"https://www.youtube.com/watch?v=sswA4j_IUxg\"\u003eYannic Kilcher\u003c/a\u003e is also working on an \u003ca href=\"https://github.com/LAION-AI/Open-Assistant\"\u003eopen sourced implementation\u003c/a\u003e\n\n\u003ca href=\"https://www.youtube.com/watch?v=SWwQ3k-DWyo\"\u003eAI Coffeebreak w/ Letitia\u003c/a\u003e | \u003ca href=\"https://www.youtube.com/watch?v=NpmnWgQgcsA\"\u003eCode Emporium\u003c/a\u003e | \u003ca href=\"https://www.youtube.com/watch?v=_MPJ3CyDokU\"\u003eCode Emporium Part 2\u003c/a\u003e\n\n## Appreciation\n\n- \u003ca href=\"https://stability.ai/\"\u003eStability.ai\u003c/a\u003e for the generous sponsorship to work on cutting edge artificial intelligence research\n\n- \u003ca href=\"https://huggingface.co/\"\u003e🤗 Hugging Face\u003c/a\u003e and \u003ca href=\"https://carper.ai/\"\u003eCarperAI\u003c/a\u003e for penning the blog post \u003ca href=\"https://huggingface.co/blog/rlhf\"\u003eIllustrating Reinforcement Learning from Human Feedback (RLHF)\u003c/a\u003e, and the former also for their \u003ca href=\"https://huggingface.co/docs/accelerate/index\"\u003eaccelerate\u003c/a\u003e library\n\n- \u003ca href=\"https://github.com/kisseternity\"\u003e@kisseternity\u003c/a\u003e and \u003ca href=\"https://github.com/taynoel84\"\u003e@taynoel84\u003c/a\u003e for the code review and finding bugs\n\n- \u003ca href=\"https://github.com/conceptofmind\"\u003eEnrico\u003c/a\u003e for integrating \u003ca href=\"https://arxiv.org/abs/2205.14135\"\u003eFlash Attention\u003c/a\u003e from Pytorch 2.0\n\n## Install\n\n```bash\n$ pip install palm-rlhf-pytorch\n```\n\n## Usage\n\nFirst train `PaLM`, like any other autoregressive transformer\n\n```python\nimport torch\nfrom palm_rlhf_pytorch import PaLM\n\npalm = PaLM(\n    num_tokens = 20000,\n    dim = 512,\n    depth = 12,\n    flash_attn = True # https://arxiv.org/abs/2205.14135\n).cuda()\n\nseq = torch.randint(0, 20000, (1, 2048)).cuda()\n\nloss = palm(seq, return_loss = True)\nloss.backward()\n\n# after much training, you can now generate sequences\n\ngenerated = palm.generate(2048) # (1, 2048)\n```\n\nThen 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.\n\n```python\nimport torch\nfrom palm_rlhf_pytorch import PaLM, RewardModel\n\npalm = PaLM(\n    num_tokens = 20000,\n    dim = 512,\n    depth = 12,\n    causal = False\n)\n\nreward_model = RewardModel(\n    palm,\n    num_binned_output = 5 # say rating from 1 to 5\n).cuda()\n\n# mock data\n\nseq = torch.randint(0, 20000, (1, 1024)).cuda()\nprompt_mask = torch.zeros(1, 1024).bool().cuda() # which part of the sequence is prompt, which part is response\nlabels = torch.randint(0, 5, (1,)).cuda()\n\n# train\n\nloss = reward_model(seq, prompt_mask = prompt_mask, labels = labels)\nloss.backward()\n\n# after much training\n\nreward = reward_model(seq, prompt_mask = prompt_mask)\n```\n\nThen you will pass your transformer and the rewards model to the `RLHFTrainer`\n\n```python\nimport torch\nfrom palm_rlhf_pytorch import PaLM, RewardModel, RLHFTrainer\n\n# load your pretrained palm\n\npalm = PaLM(\n    num_tokens = 20000,\n    dim = 512,\n    depth = 12\n).cuda()\n\npalm.load('./path/to/pretrained/palm.pt')\n\n# load your pretrained reward model\n\nreward_model = RewardModel(\n    palm,\n    num_binned_output = 5\n).cuda()\n\nreward_model.load('./path/to/pretrained/reward_model.pt')\n\n# ready your list of prompts for reinforcement learning\n\nprompts = torch.randint(0, 256, (50000, 512)).cuda() # 50k prompts\n\n# pass it all to the trainer and train\n\ntrainer = RLHFTrainer(\n    palm = palm,\n    reward_model = reward_model,\n    prompt_token_ids = prompts\n)\n\ntrainer.train(num_episodes = 50000)\n\n# then, if it succeeded...\n# generate say 10 samples and use the reward model to return the best one\n\nanswer = trainer.generate(2048, prompt = prompts[0], num_samples = 10) # (\u003c= 2048,)\n```\n\n## Todo\n\n- [x] clone base transformer with separate lora for critic\n- [x] also allow for non-LoRA based finetuning\n- [x] 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\n- [x] equip with \u003ca href=\"https://github.com/hazyResearch/flash-attention\"\u003ethe best attention\u003c/a\u003e\n\n- [ ] add Hugging Face accelerate and test out wandb instrumentation\n- [ ] search literature to figure out what is the latest SOTA for PPO, assuming RL field is still making progress.\n- [ ] test the system using a pretrained sentiment network as reward model\n- [ ] write the memory in PPO to memmapped numpy file\n- [ ] get sampling with variable lengthed prompts working, even if it is not needed given bottleneck is human feedback\n- [ ] allow for finetuning penultimate N layers only in either actor or critic, assuming if pretrained\n- [ ] incorporate some learning points from Sparrow, given Letitia's video\n- [ ] simple web interface with django + htmx for collecting human feedback\n- [ ] consider \u003ca href=\"https://www.anthropic.com/constitutional.pdf\"\u003eRLAIF\u003c/a\u003e\n\n## Citations\n\n```bibtex\n@article{Stiennon2020LearningTS,\n    title   = {Learning to summarize from human feedback},\n    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},\n    journal = {ArXiv},\n    year    = {2020},\n    volume  = {abs/2009.01325}\n}\n```\n\n```bibtex\n@inproceedings{Chowdhery2022PaLMSL,\n    title   = {PaLM: Scaling Language Modeling with Pathways},\n    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},\n    year    = {2022}\n}\n```\n\n```bibtex\n@article{Hu2021LoRALA,\n    title   = {LoRA: Low-Rank Adaptation of Large Language Models},\n    author  = {Edward J. Hu and Yelong Shen and Phillip Wallis and Zeyuan Allen-Zhu and Yuanzhi Li and Shean Wang and Weizhu Chen},\n    journal = {ArXiv},\n    year    = {2021},\n    volume  = {abs/2106.09685}\n}\n```\n\n```bibtex\n@inproceedings{Sun2022ALT,\n    title     = {A Length-Extrapolatable Transformer},\n    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},\n    year      = {2022}\n}\n```\n\n```bibtex\n@misc{gilmer2023intriguing\n    title  = {Intriguing Properties of Transformer Training Instabilities},\n    author = {Justin Gilmer, Andrea Schioppa, and Jeremy Cohen},\n    year   = {2023},\n    status = {to be published - one attention stabilization technique is circulating within Google Brain, being used by multiple teams}\n}\n```\n\n```bibtex\n@inproceedings{dao2022flashattention,\n    title   = {Flash{A}ttention: Fast and Memory-Efficient Exact Attention with {IO}-Awareness},\n    author  = {Dao, Tri and Fu, Daniel Y. and Ermon, Stefano and Rudra, Atri and R{\\'e}, Christopher},\n    booktitle = {Advances in Neural Information Processing Systems},\n    year    = {2022}\n}\n```\n\n```bibtex\n@misc{Rubin2024,\n    author  = {Ohad Rubin},\n    url     = {https://medium.com/@ohadrubin/exploring-weight-decay-in-layer-normalization-challenges-and-a-reparameterization-solution-ad4d12c24950}\n}\n```\n\n```bibtex\n@inproceedings{Yuan2024FreePR,\n    title   = {Free Process Rewards without Process Labels},\n    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},\n    year    = {2024},\n    url     = {https://api.semanticscholar.org/CorpusID:274445748}\n}\n```\n\n```bibtex\n@article{Shao2024DeepSeekMathPT,\n    title   = {DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models},\n    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},\n    journal = {ArXiv},\n    year    = {2024},\n    volume  = {abs/2402.03300},\n    url     = {https://api.semanticscholar.org/CorpusID:267412607}\n}\n```\n\n```bibtex\n@article{Farebrother2024StopRT,\n    title   = {Stop Regressing: Training Value Functions via Classification for Scalable Deep RL},\n    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},\n    journal = {ArXiv},\n    year   = {2024},\n    volume = {abs/2403.03950},\n    url    = {https://api.semanticscholar.org/CorpusID:268253088}\n}\n```\n\n```bibtex\n@misc{Liu2025,\n    title   = {Understanding R1-Zero-Like Training: A Critical Perspective},\n    author  = {Zichen Liu, Changyu Chen, Wenjun Li, Penghui Qi, Tianyu Pang, Chao Du, Wee Sun Lee, Min Lin},\n    url     = {https://github.com/sail-sg/understand-r1-zero/blob/main/understand-r1-zero.pdf}\n}\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flucidrains%2FPaLM-rlhf-pytorch","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flucidrains%2FPaLM-rlhf-pytorch","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flucidrains%2FPaLM-rlhf-pytorch/lists"}