train_model_grpo.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. import os
  2. import torch
  3. from unsloth import FastLanguageModel
  4. from unsloth import is_bfloat16_supported
  5. from trl import SFTTrainer, GRPOConfig, GRPOTrainer
  6. from datasets import load_dataset
  7. from transformers import TrainingArguments
  8. import re
  9. from datasets import load_dataset, Dataset
  10. from modelscope.msdatasets import MsDataset
  11. # Load and prep dataset
  12. SYSTEM_PROMPT = """
  13. Respond in the following format:
  14. <reasoning>
  15. ...
  16. </reasoning>
  17. <answer>
  18. ...
  19. </answer>
  20. """
  21. XML_COT_FORMAT = """\
  22. <reasoning>
  23. {reasoning}
  24. </reasoning>
  25. <answer>
  26. {answer}
  27. </answer>
  28. """
  29. def extract_xml_answer(text: str) -> str:
  30. answer = text.split("<answer>")[-1]
  31. answer = answer.split("</answer>")[0]
  32. return answer.strip()
  33. def extract_hash_answer(text: str) -> str | None:
  34. if "####" not in text:
  35. return None
  36. return text.split("####")[1].strip()
  37. # uncomment middle messages for 1-shot prompting
  38. def get_gsm8k_questions(split = "train") -> Dataset:
  39. # data = load_dataset('https://huggingface.co/datasets/openai/gsm8k', 'main')[split] # type: ignore
  40. data = MsDataset.load('openai-mirror/gsm8k', subset_name='main', split=split)
  41. data = data.map(lambda x: { # type: ignore
  42. 'prompt': [
  43. {'role': 'system', 'content': SYSTEM_PROMPT},
  44. {'role': 'user', 'content': x['question']}
  45. ],
  46. 'answer': extract_hash_answer(x['answer'])
  47. }) # type: ignore
  48. return data # type: ignore
  49. dataset = get_gsm8k_questions()
  50. # Reward functions
  51. def correctness_reward_func(prompts, completions, answer, **kwargs) -> list[float]:
  52. responses = [completion[0]['content'] for completion in completions]
  53. q = prompts[0][-1]['content']
  54. extracted_responses = [extract_xml_answer(r) for r in responses]
  55. print('-'*20, f"Question:\n{q}", f"\nAnswer:\n{answer[0]}", f"\nResponse:\n{responses[0]}", f"\nExtracted:\n{extracted_responses[0]}")
  56. return [2.0 if r == a else 0.0 for r, a in zip(extracted_responses, answer)]
  57. def int_reward_func(completions, **kwargs) -> list[float]:
  58. responses = [completion[0]['content'] for completion in completions]
  59. extracted_responses = [extract_xml_answer(r) for r in responses]
  60. return [0.5 if r.isdigit() else 0.0 for r in extracted_responses]
  61. def strict_format_reward_func(completions, **kwargs) -> list[float]:
  62. """Reward function that checks if the completion has a specific format."""
  63. pattern = r"^<reasoning>\n.*?\n</reasoning>\n<answer>\n.*?\n</answer>\n$"
  64. responses = [completion[0]["content"] for completion in completions]
  65. matches = [re.match(pattern, r) for r in responses]
  66. return [0.5 if match else 0.0 for match in matches]
  67. def soft_format_reward_func(completions, **kwargs) -> list[float]:
  68. """Reward function that checks if the completion has a specific format."""
  69. pattern = r"<reasoning>.*?</reasoning>\s*<answer>.*?</answer>"
  70. responses = [completion[0]["content"] for completion in completions]
  71. matches = [re.match(pattern, r) for r in responses]
  72. return [0.5 if match else 0.0 for match in matches]
  73. def count_xml(text) -> float:
  74. count = 0.0
  75. if text.count("<reasoning>\n") == 1:
  76. count += 0.125
  77. if text.count("\n</reasoning>\n") == 1:
  78. count += 0.125
  79. if text.count("\n<answer>\n") == 1:
  80. count += 0.125
  81. count -= len(text.split("\n</answer>\n")[-1])*0.001
  82. if text.count("\n</answer>") == 1:
  83. count += 0.125
  84. count -= (len(text.split("\n</answer>")[-1]) - 1)*0.001
  85. return count
  86. def xmlcount_reward_func(completions, **kwargs) -> list[float]:
  87. contents = [completion[0]["content"] for completion in completions]
  88. return [count_xml(c) for c in contents]
  89. class ModelTrainer:
  90. def __init__(self, model_name, max_seq_length, dtype, load_in_4bit,lora_rank=32):
  91. # 初始化 ModelTrainer 类,设置模型名称、最大序列长度、数据类型和是否以4位加载
  92. self.model_name = model_name
  93. self.max_seq_length = max_seq_length
  94. self.dtype = dtype # dtype: 数据类型,如 torch.float16 或 torch.bfloat16
  95. self.load_in_4bit = load_in_4bit # load_in_4bit: 是否以4位精度加载模型,用于节省显存
  96. self.lora_rank=lora_rank #Larger rank = smarter, but slower
  97. def load_model(self):
  98. # 加载预训练模型和分词器
  99. model, tokenizer = FastLanguageModel.from_pretrained(
  100. model_name=self.model_name,
  101. max_seq_length=self.max_seq_length,
  102. load_in_4bit=self.load_in_4bit, # 值为True 以 4 bit量化进行微调,为False LoRA 16bit。这将内存使用量减少了 4 倍,使我们能够在免费的 16GB 内存 GPU 中实际进行微调。4 位量化本质上将权重转换为一组有限的数字以减少内存使用量。这样做的缺点是准确度会下降 1-2%。如果您想要这种微小的额外准确度,请在较大的 GPU(如 H100)上将其设置为 False。
  103. dtype=self.dtype,
  104. fast_inference = True, # Enable vLLM fast inference
  105. max_lora_rank = lora_rank,
  106. gpu_memory_utilization=0.8,# Reduce if out of memory
  107. )
  108. # 添加 LoRA 适配器
  109. model = FastLanguageModel.get_peft_model(
  110. model,
  111. max_seq_length=self.max_seq_length, # 最大上下文(序列)长度
  112. r=16, # LoRA 的秩,控制适配器的复杂度
  113. target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
  114. "gate_proj", "up_proj", "down_proj"], # 应用 LoRA 的目标模块
  115. lora_alpha=16, # LoRA 的 alpha 参数,控制适配器的缩放
  116. lora_dropout=0, # LoRA 的 dropout 率,设置为0以优化性能
  117. bias="none", # 是否在 LoRA 中添加偏置,设置为 "none" 以优化性能
  118. use_gradient_checkpointing="unsloth", # 使用梯度检查点以节省显存,对于非常长的上下文,使用 True 或 "unsloth"
  119. random_state=3407, # 随机种子,确保实验可复现
  120. use_rslora=False, # 是否使用 rank stabilized LoRA,当前不支持
  121. loftq_config=None, # LoftQ 配置,当前不支持
  122. )
  123. return model, tokenizer
  124. def load_data(self, train_data_path):
  125. # 加载训练集和测试集
  126. train_dataset = load_dataset("json", data_files={"train": train_data_path}, split="train")
  127. # train_data_path: 训练数据路径,格式为 JSONL
  128. return train_dataset
  129. def train(self, model, tokenizer, train_dataset):
  130. print("is_bfloat16_supported()=",is_bfloat16_supported())
  131. training_args = GRPOConfig(
  132. use_vllm = True, # use vLLM for fast inference!
  133. learning_rate = 5e-6,
  134. adam_beta1 = 0.9,
  135. adam_beta2 = 0.99,
  136. weight_decay = 0.1,
  137. warmup_ratio = 0.1,
  138. lr_scheduler_type = "cosine",
  139. optim = "adamw_8bit",
  140. logging_steps = 1,
  141. bf16 = is_bfloat16_supported(),
  142. fp16 = not is_bfloat16_supported(),
  143. per_device_train_batch_size = 1,
  144. gradient_accumulation_steps = 1, # Increase to 4 for smoother training
  145. num_generations = 4, # Decrease if out of memory
  146. max_prompt_length = 256,
  147. max_completion_length = 200,
  148. # num_train_epochs = 1, # Set to 1 for a full training run
  149. max_steps = 250,
  150. save_steps = 250,
  151. max_grad_norm = 0.1,
  152. report_to = "none", # Can use Weights & Biases
  153. output_dir = os.path.join('..', 'models',"outputs"),
  154. )
  155. # 初始化 SFTTrainer
  156. trainer = GRPOTrainer(
  157. model = model,
  158. processing_class = tokenizer,
  159. reward_funcs = [
  160. xmlcount_reward_func,
  161. soft_format_reward_func,
  162. strict_format_reward_func,
  163. int_reward_func,
  164. correctness_reward_func,
  165. ],
  166. args = training_args,
  167. train_dataset = dataset,
  168. )
  169. # 训练模型
  170. trainer.train()
  171. return model
  172. def save_model(self, model, tokenizer, save_path):
  173. # 保存模型和分词器
  174. model.save_pretrained(save_path)
  175. tokenizer.save_pretrained(save_path)
  176. print(f"Model saved to {save_path}")
  177. if __name__ == "__main__":
  178. # 配置参数
  179. model_name = os.path.join('..', 'models', 'pretrained', 'DeepSeek-R1-Distill-Qwen-1.5B')
  180. # model_name: 预训练模型的路径
  181. max_seq_length = 1024 # 2048 # 最大序列长度
  182. dtype = torch.float16 # 数据类型
  183. load_in_4bit = True # 是否以4位精度加载模型
  184. lora_rank=32
  185. # 定义训练集和测试集路径
  186. train_data_path = os.path.join('..', 'data', 'processed', 'train.jsonl')
  187. # train_data_path: 训练数据路径
  188. # 初始化 ModelTrainer
  189. trainer = ModelTrainer(model_name, max_seq_length, dtype, load_in_4bit)
  190. # 加载模型和分词器
  191. model, tokenizer = trainer.load_model()
  192. # 加载数据集
  193. train_dataset = trainer.load_data(train_data_path)
  194. # 训练模型
  195. model = trainer.train(model, tokenizer, train_dataset)
  196. # 保存模型
  197. save_path = os.path.join('..', 'models', 'trained', 'DeepSeek-R1-Distill-Qwen-1.5B')
  198. trainer.save_model(model, tokenizer, save_path)