当前位置: 首页 > news >正文

使用unsloth进行grpo强化学习训练

说明

unsloth框架可以进行各种sft训练,包括lora和grpo训练。我参考官方方法,使用模型Qwen2.5-3B-Instruct和数据集gsm8k,写了一个grpo训练的例子。

代码

这个代码加载模型Qwen2.5-3B-Instruct和数据集gsm8k。训练完成后先保存lora模型然后保存合并后的模型。

import os
from unsloth import FastLanguageModel, PatchFastRL
from unsloth import is_bfloat16_supported
import torch
import re
from datasets import load_dataset, Dataset


PatchFastRL("GRPO", FastLanguageModel)
from trl import GRPOConfig, GRPOTrainer


max_seq_length = 1024 # Can increase for longer reasoning traces
lora_rank = 64 # Larger rank = smarter, but slower

print(">>>>>>>>>>>>>>>FastLanguageModel.from_pretrained:")
model, tokenizer = FastLanguageModel.from_pretrained(
    model_name = "./Qwen2.5-3B-Instruct",
    max_seq_length = max_seq_length,
    load_in_4bit = True, # False for LoRA 16bit
    fast_inference = True, # Enable vLLM fast inference
    max_lora_rank = lora_rank,
    gpu_memory_utilization = 0.8, # Reduce if out of memory
)

print(">>>>>>>>>>>>>>>FastLanguageModel.get_peft_model:")
model = FastLanguageModel.get_peft_model(
    model,
    r = lora_rank, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128
    target_modules = [
        "q_proj", "k_proj", "v_proj", "o_proj",
        "gate_proj", "up_proj", "down_proj",
    ], # Remove QKVO if out of memory
    lora_alpha = lora_rank,
    use_gradient_checkpointing = "unsloth", # Enable long context finetuning
    random_state = 3407,
)


# Load and prep dataset
SYSTEM_PROMPT = """
Respond in the following format:
<reasoning>
...
</reasoning>
<answer>
...
</answer>
"""

XML_COT_FORMAT = """\
<reasoning>
{reasoning}
</reasoning>
<answer>
{answer}
</answer>
"""

def extract_xml_answer(text: str) -> str:
    answer = text.split("<answer>")[-1]
    answer = answer.split("</answer>")[0]
    return answer.strip()

def extract_hash_answer(text: str) -> str | None:
    if "####" not in text:
        return None
    return text.split("####")[1].strip()

# uncomment middle messages for 1-shot prompting
def get_gsm8k_questions(split = "train") -> Dataset:
    print(f">>>>>>>>>>>>>>>_get_gsm8k_questions, split:{split}")
    data = load_dataset('./gsm8k', 'main')[split] # type: ignore
    data = data.map(lambda x: { # type: ignore
        'prompt': [
            {'role': 'system', 'content': SYSTEM_PROMPT},
            {'role': 'user', 'content': x['question']}
        ],
        'answer': extract_hash_answer(x['answer'])
    }) # type: ignore
    return data # type: ignore

print(">>>>>>>>>>>>>>>get_gsm8k_questions:")
dataset = get_gsm8k_questions()

# Reward functions
def correctness_reward_func(prompts, completions, answer, **kwargs) -> list[float]:
    responses = [completion[0]['content'] for completion in completions]
    q = prompts[0][-1]['content']
    extracted_responses = [extract_xml_answer(r) for r in responses]
    print('-'*20, f"Question:\n{q}", f"\nAnswer:\n{answer[0]}", f"\nResponse:\n{responses[0]}", f"\nExtracted:\n{extracted_responses[0]}")
    return [2.0 if r == a else 0.0 for r, a in zip(extracted_responses, answer)]

def int_reward_func(completions, **kwargs) -> list[float]:
    responses = [completion[0]['content'] for completion in completions]
    extracted_responses = [extract_xml_answer(r) for r in responses]
    return [0.5 if r.isdigit() else 0.0 for r in extracted_responses]

def strict_format_reward_func(completions, **kwargs) -> list[float]:
    """Reward function that checks if the completion has a specific format."""
    pattern = r"^<reasoning>\n.*?\n</reasoning>\n<answer>\n.*?\n</answer>\n$"
    responses = [completion[0]["content"] for completion in completions]
    matches = [re.match(pattern, r) for r in responses]
    return [0.5 if match else 0.0 for match in matches]

def soft_format_reward_func(completions, **kwargs) -> list[float]:
    """Reward function that checks if the completion has a specific format."""
    pattern = r"<reasoning>.*?</reasoning>\s*<answer>.*?</answer>"
    responses = [completion[0]["content"] for completion in completions]
    matches = [re.match(pattern, r) for r in responses]
    return [0.5 if match else 0.0 for match in matches]

def count_xml(text) -> float:
    count = 0.0
    if text.count("<reasoning>\n") == 1:
        count += 0.125
    if text.count("\n</reasoning>\n") == 1:
        count += 0.125
    if text.count("\n<answer>\n") == 1:
        count += 0.125
        count -= len(text.split("\n</answer>\n")[-1])*0.001
    if text.count("\n</answer>") == 1:
        count += 0.125
        count -= (len(text.split("\n</answer>")[-1]) - 1)*0.001
    return count

def xmlcount_reward_func(completions, **kwargs) -> list[float]:
    contents = [completion[0]["content"] for completion in completions]
    return [count_xml(c) for c in contents]

print(">>>>>>>>>>>>>>>training_args:")
training_args = GRPOConfig(
    use_vllm = True, # use vLLM for fast inference!
    learning_rate = 5e-6,
    adam_beta1 = 0.9,
    adam_beta2 = 0.99,
    weight_decay = 0.1,
    warmup_ratio = 0.1,
    lr_scheduler_type = "cosine",
    optim = "adamw_8bit",
    logging_steps = 10,
    bf16 = is_bfloat16_supported(),
    fp16 = not is_bfloat16_supported(),
    per_device_train_batch_size = 1,
    gradient_accumulation_steps = 1, # Increase to 4 for smoother training
    num_generations = 8, # Decrease if out of memory
    max_prompt_length = 300,
    max_completion_length = 300,
    # num_train_epochs = 1, # Set to 1 for a full training run
    max_steps = 100,
    save_steps = 50,
    max_grad_norm = 0.1,
    report_to = "none", # Can use Weights & Biases
    output_dir = "outputs_2",
)
print(f"training_args:{training_args}")

print(">>>>>>>>>>>>>>>GRPOTrainer:")
trainer = GRPOTrainer(
    model = model,
    processing_class = tokenizer,
    reward_funcs = [
        xmlcount_reward_func,
        soft_format_reward_func,
        strict_format_reward_func,
        int_reward_func,
        correctness_reward_func,
    ],
    args = training_args,
    train_dataset = dataset,
)
print(">>>>>>>>>>>>>>>trainer.train:")
trainer.train()

print(">>>>>>>>>>>>>>>model.save_lora:")
model.save_lora("grpo_saved_lora_2")

print(">>>>>>>>>>>>>>>model.save_lora:")
model.save_pretrained_merged("./model_merged", tokenizer, save_method = "merged_16bit",)

print(">>>>>>>>>>>>>>>DONE<<<<<<<<<<<<<<")

参考消息

使用unsloth进行grpo训练报错及解决方法

相关文章:

  • html5制作2048游戏开发心得与技术分享
  • 仿最美博客POETIZE(简易版)
  • Android (Kotlin) 高版本 DownloadManager 封装工具类,支持 APK 断点续传与自动安装
  • Python基于深度学习的多模态人脸情绪识别研究与实现
  • DeepSeek使用指南
  • 什么是物理信息神经网络PINN
  • LeetCode hot 100 每日一题(8)——438. 找到字符串中所有字母异位词
  • p5.js:绘制各种内置的几何体,还能旋转
  • 设计模式分类解析与JavaScript实现
  • Linux Redis安装部署、注册服务
  • 蓝桥杯专项复习——stl(stack、queue)
  • hadoop伪分布式搭建--启动过程中如果发现某个datanode出现问题,如何处理?
  • 24.策略模式实现日志
  • leetcode日记(101)填充每个节点的下一个右侧节点指针Ⅱ
  • Deepseek+QuickAPI:打造 MySQL AI 智能体入门篇(一)
  • CVE-2017-5645(使用 docker 搭建)
  • Java面试:集合框架体系
  • 【web逆向】优某愿 字体混淆
  • 提升fcp
  • 八、Prometheus 静态配置(Static Configuration)
  • 假冒政府机构账号卖假货?“假官号”为何屡禁不绝?媒体调查
  • 私家车跑“顺风”出事故,意外险赔不赔?
  • 一旅客因上错车阻挡车门关闭 ,株洲西高铁站发布通报
  • 遭车祸罹难的村医遇“身份”难题:镇卫生院否认劳动关系,家属上诉后二审将开庭
  • 西班牙政府排除因国家电网遭攻击导致大停电的可能
  • “水运江苏”“航运浙江”,江浙两省为何都在发力内河航运?