GRPO 对内存需求较高的原因在于,其内部涉及多个模型,并且在训练数据中每个查询会产生多个输出。上图中的策略模型、参考模型和奖励模型各自都是一个需要进行推理的 LLM。(尽管从技术上讲,奖励模型可能不需要参数化,可以只是一个 Python 函数或正则表达式,但不影响 GRPO 对内存的高需求。) 为什么 8-Bit 优化和梯度检查点有助于减少内存占用?
通常来讲,训练一个大型语言模型需要在内存中存储三种主要类型的信息:模型参数、模型学习所需的梯度、优化器的跟踪数据。
对上述内容我们可以这样理解:如果模型的参数占用了 X 的空间,那么梯度也会占用大约相同的空间。然后,像 AdamW 这样的优化器需要更多的空间,因为它们就像一个记录员,跟踪最近的更新历史,以便更好地决定未来的优化。
为了减轻这种内存负担,通常采用两种技术: 首先,可以使用像 AdamW 这样的 8-bit 优化器版本,它们能更高效地存储跟踪数据,同时仍保持良好的性能 —— 类似于压缩照片可以节省空间,同时保留大部分图像质量;其次,使用梯度检查点技术,这就像在训练过程中拍摄快照,而不是记录所有内容。虽然这会使训练速度减慢约 20-30%,但它显著减少了内存使用。
结合这些技术,即使对 GPU 资源有限的人来说,也能够训练更大的模型。 代码示例
像 trl 这样的库已经开始支持 GRPO,使得微调由 transformers 构成的 LLM 变得非常简单。代码也非常简洁,只需将训练器替换为 GRPOTrainer 并定义一些奖励即可。GRPO 的最小代码量大约只有 99 行,如果你使用的是像 meta-llama/Llama-3.2-1B-Instruct 这样的小型模型和像 openai/GSM8K 这样的数据集,可以非常快速地启动。
trl 项目地址:https://github.com/huggingface/trl?ref=ghost.oxen.ai
[ol]importtorchfromdatasetsimportload_datasetDatasetfromtransformersimportAutoTokenizerAutoModelForCausalLMfromtrlimportGRPOConfigGRPOTrainerimportreSYSTEM_PROMPTRespond in the following format:defextract_hash_answertextstrstrNoneif"####"notintextreturnNonereturntextsplit"####"1stripdefget_gsm8k_questionssplit"train"Datasetdataload_dataset'openai/gsm8k''main'splitdatadatamaplambda'prompt''role''system''content'SYSTEM_PROMPT},'role''user''content''question'],'answer'extract_hash_answer'answer'returndatadefextract_xml_answertextstrstranswertextsplit1answeranswersplit""0returnanswerstripdefformat_reward_funccompletionskwargslistfloat"""Reward function that checks if the completion has a specific format."""patternr"^\n\n$"\n.*?\n\n.*?\nresponsescompletion0"content"forcompletionincompletionsmatchesrematchpatternrforrinresponsesreturn0.5ifmatchelse0.0formatchinmatchesdefaccuracy_reward_funcpromptscompletionsanswerkwargslistfloat"""Reward function that extracts the answer from the xml tags and compares it to the correct answer."""responsescompletion0'content'forcompletionincompletionsextracted_responsesextract_xml_answerrforrinresponsesreturn2.0ifraelse0.0forrainzipextracted_responsesanswerdefmaindatasetget_gsm8k_questionsmodel_name"meta-llama/Llama-3.2-1B-Instruct"modelAutoModelForCausalLMfrom_pretrainedmodel_nametorch_dtypetorchbfloat16attn_implementation"flash_attention_2"device_mapNoneto"cuda"tokenizerAutoTokenizerfrom_pretrainedmodel_nametokenizerpad_tokentokenizereos_tokentraining_argsGRPOConfigoutput_dir"output"learning_rate5e-6adam_beta10.9adam_beta20.99weight_decay0.1warmup_ratio0.1lr_scheduler_type'cosine'logging_steps1bf16Trueper_device_train_batch_size1gradient_accumulation_steps4num_generations4max_prompt_length256max_completion_length786num_train_epochs1save_steps100save_total_limit1max_grad_norm0.1log_on_each_nodeFalsetrainerGRPOTrainermodelmodelprocessing_classtokenizerreward_funcsformat_reward_funcaccuracy_reward_func],argstraining_argstrain_datasetdatasettrainertrainif__name__"__main__"main[/ol] Num Generations 有什么用
Num Generations 是一个超参数,它决定了我们将在训练数据中对每个查询采样多少个补全。然而,这会显著增加 VRAM 的消耗。