0

0

DeepSeek用的GRPO占用大量内存?有人给出了些破解方法

DDD

DDD

发布时间:2025-02-07 18:00:16

|

927人浏览过

|

来源于php中文网

原创

rtx 3080 移动版训练大型语言模型的实用指南

本文旨在指导 GPU 资源受限的开发者如何利用 GRPO (Group Relative Policy Optimization) 训练大型语言模型。DeepSeek-R1 的发布使得 GRPO 成为强化学习训练大型语言模型的热门方法,因为它高效且易于训练。 GRPO 通过利用模型自身生成的训练数据进行迭代改进,目标是最大化生成文本的优势函数,同时保持模型与参考策略的接近性。

☞☞☞AI 智能聊天, 问答助手, AI 智能搜索, 免费无限量使用 DeepSeek R1 模型☜☜☜

图片

选择合适的模型大小和训练方法(全参数微调或参数高效微调 - PEFT)是训练的关键。本文作者 Greg Schoeninger (Oxen.ai CEO) 使用配备 16GB 显存的 RTX 3080 笔记本电脑进行实验,并分享了其经验。

图片原文链接:https://www.php.cn/link/61d8c968f0a66dcf2b05982bdccb484b}}

作者在使用 trl 库的 GRPO 实现时,遇到了显存不足 (OOM) 错误:

  1. torch.OutOfMemoryError: CUDA out of memory.

  2. Tried to allocate 1.90 GiB. GPU 0 has a total capacity of 15.73 GiB of which 1.28 GiB is free.

  3. Including non-PyTorch memory, this process has 14.43 GiB memory in use. Of the allocated memory 11.82 GiB is allocated by PyTorch, and 2.41 GiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation.  See documentation for Memory Management  (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)

实验结果与内存需求分析

作者进行了一系列实验,测试不同模型大小(5亿到140亿参数)在 GSM8K 数据集上训练前 100 步的峰值内存使用情况,并比较了全参数微调和 PEFT 的内存需求。所有实验均在 Nvidia H100 上完成。

图片

使用的模型包括:

图片

GRPO 对内存需求高的原因在于其内部涉及多个模型(策略模型、参考模型、奖励模型)以及每个查询产生的多个输出。

图片

优化内存使用

8位优化器和梯度检查点技术可以有效减少内存占用。8位优化器更高效地存储优化器状态,而梯度检查点则通过在训练过程中拍摄快照来减少内存使用,虽然会降低训练速度。

代码示例

trl 库简化了 GRPO 的使用。以下代码示例展示了如何使用 trl 训练小型模型:

  1. import torch

  2. from datasets import load_dataset, Dataset

  3. from transformers import AutoTokenizer, AutoModelForCausalLM

  4. from trl import GRPOConfig, GRPOTrainer

  5. import re

  6. SYSTEM_PROMPT = """

  7. Respond in the following format:

  8. ...

  9. ...

  10. """

  11. def extract_hash_answer(text: str) -> str | None:

  12. if "####" not in text:

  13. return None

  14. return text.split("####")[1].strip()

  15. def get_gsm8k_questions(split = "train") -> Dataset:

  16. data = load_dataset('openai/gsm8k', 'main')[split]

  17. data = data.map(lambda x: {

  18. 'prompt': [

  19. {'role': 'system', 'content': SYSTEM_PROMPT},

  20. {'role': 'user', 'content': x['question']}

  21. ],

  22. 'answer': extract_hash_answer(x['answer'])

  23. })

  24. return data

  25. def extract_xml_answer(text: str) -> str:

  26. answer = text.split("")[-1]

  27. answer = answer.split("")[0]

  28. return answer.strip()

  29. def format_reward_func(completions, **kwargs) -> list[float]:

  30. """Reward function that checks if the completion has a specific format."""

  31. pattern = r"^\n.*?\n\n\n.*?\n\n$"

  32. responses = [completion[0]["content"] for completion in completions]

  33. matches = [re.match(pattern, r) for r in responses]

  34. return [0.5 if match else 0.0 for match in matches]

  35. def accuracy_reward_func(prompts, completions, answer, **kwargs) -> list[float]:

  36. """Reward function that extracts the answer from the xml tags and compares it to the correct answer."""

    Lobe
    Lobe

    微软旗下的一个训练器学习模型的平台

    下载
  37. responses = [completion[0]['content'] for completion in completions]

  38. extracted_responses = [extract_xml_answer(r) for r in responses]

  39. return [2.0 if r == a else 0.0 for r, a in zip(extracted_responses, answer)]

  40. def main():

  41. dataset = get_gsm8k_questions()

  42. model_name = "meta-llama/Llama-3.2-1B-Instruct"

  43. model = AutoModelForCausalLM.from_pretrained(

  44. model_name,

  45. torch_dtype=torch.bfloat16,

  46. attn_implementation="flash_attention_2",

  47. device_map=None

  48. ).to("cuda")

  49. tokenizer = AutoTokenizer.from_pretrained(model_name)

  50. tokenizer.pad_token = tokenizer.eos_token

  51. training_args = GRPOConfig(

  52. output_dir="output",

  53. learning_rate=5e-6,

  54. adam_beta1=0.9,

  55. adam_beta2=0.99,

  56. weight_decay=0.1,

  57. warmup_ratio=0.1,

  58. lr_scheduler_type='cosine',

  59. logging_steps=1,

  60. bf16=True,

  61. per_device_train_batch_size=1,

  62. gradient_accumulation_steps=4,

  63. num_generations=4,

  64. max_prompt_length=256,

  65. max_completion_length=786,

  66. num_train_epochs=1,

  67. save_steps=100,

  68. save_total_limit=1,

  69. max_grad_norm=0.1,

  70. log_on_each_node=False,

  71. )

  72. trainer = GRPOTrainer(

  73. model=model,

  74. processing_class=tokenizer,

  75. reward_funcs=[

  76. format_reward_func,

  77. accuracy_reward_func

  78. ],

  79. args=training_args,

  80. train_dataset=dataset,

  81. )

  82. trainer.train()

  83. if __name__ == "__main__":

  84. main()

trl 项目地址:https://www.php.cn/link/ccb8dbcf2c004cbbae8858760e4a22fa

超参数调整与VRAM估算

num_generations 超参数会显著影响 VRAM 消耗。建议在内存瓶颈解决前使用 num_generations=4

图片

GitHub 问题讨论:https://www.php.cn/link/3057aa0acb6d937295819f3d94f015e9

其他影响 VRAM 的因素包括 batch_sizegradient_accumulation_stepsmax_prompt_lengthmax_completion_length 和 LoRA 的 target_modules

图片

最后,作者分享了 10 亿参数 Llama 3.2 模型的训练结果,展示了 GRPO 在提高模型准确率方面的潜力。

通过合理的参数设置和优化技术,即使使用资源有限的 RTX 3080 移动版 GPU,也能有效训练大型语言模型。

相关专题

更多
github中文官网入口 github中文版官网网页进入
github中文官网入口 github中文版官网网页进入

github中文官网入口https://docs.github.com/zh/get-started,GitHub 是一种基于云的平台,可在其中存储、共享并与他人一起编写代码。 通过将代码存储在GitHub 上的“存储库”中,你可以: “展示或共享”你的工作。 持续“跟踪和管理”对代码的更改。

437

2026.01.21

http与https有哪些区别
http与https有哪些区别

http与https的区别:1、协议安全性;2、连接方式;3、证书管理;4、连接状态;5、端口号;6、资源消耗;7、兼容性。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

2060

2024.08.16

c++ 根号
c++ 根号

本专题整合了c++根号相关教程,阅读专题下面的文章了解更多详细内容。

42

2026.01.23

c++空格相关教程合集
c++空格相关教程合集

本专题整合了c++空格相关教程,阅读专题下面的文章了解更多详细内容。

46

2026.01.23

yy漫画官方登录入口地址合集
yy漫画官方登录入口地址合集

本专题整合了yy漫画入口相关合集,阅读专题下面的文章了解更多详细内容。

202

2026.01.23

漫蛙最新入口地址汇总2026
漫蛙最新入口地址汇总2026

本专题整合了漫蛙最新入口地址大全,阅读专题下面的文章了解更多详细内容。

341

2026.01.23

C++ 高级模板编程与元编程
C++ 高级模板编程与元编程

本专题深入讲解 C++ 中的高级模板编程与元编程技术,涵盖模板特化、SFINAE、模板递归、类型萃取、编译时常量与计算、C++17 的折叠表达式与变长模板参数等。通过多个实际示例,帮助开发者掌握 如何利用 C++ 模板机制编写高效、可扩展的通用代码,并提升代码的灵活性与性能。

16

2026.01.23

php远程文件教程合集
php远程文件教程合集

本专题整合了php远程文件相关教程,阅读专题下面的文章了解更多详细内容。

100

2026.01.22

PHP后端开发相关内容汇总
PHP后端开发相关内容汇总

本专题整合了PHP后端开发相关内容,阅读专题下面的文章了解更多详细内容。

73

2026.01.22

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号