train_model_grpo_v0.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. import os
  2. import torch
  3. import torch.distributed as dist
  4. from unsloth import FastLanguageModel
  5. from unsloth import is_bfloat16_supported
  6. from trl import SFTTrainer, GRPOConfig, GRPOTrainer
  7. from datasets import load_dataset
  8. from transformers import TrainingArguments
  9. import re
  10. from datasets import load_dataset, Dataset
  11. from modelscope.msdatasets import MsDataset
  12. # Load and prep dataset
  13. SYSTEM_PROMPT = """
  14. Respond in the following format:
  15. <reasoning>
  16. ...
  17. </reasoning>
  18. <answer>
  19. ...
  20. </answer>
  21. """
  22. XML_COT_FORMAT = """\
  23. <reasoning>
  24. {reasoning}
  25. </reasoning>
  26. <answer>
  27. {answer}
  28. </answer>
  29. """
  30. def extract_xml_answer(text: str) -> str:
  31. answer = text.split("<answer>")[-1]
  32. answer = answer.split("</answer>")[0]
  33. return answer.strip()
  34. def extract_hash_answer(text: str) -> str | None:
  35. if "####" not in text:
  36. return None
  37. return text.split("####")[1].strip()
  38. # uncomment middle messages for 1-shot prompting
  39. def get_gsm8k_questions(split = "train") -> Dataset:
  40. # data = load_dataset('https://huggingface.co/datasets/openai/gsm8k', 'main')[split] # type: ignore
  41. data = MsDataset.load('openai-mirror/gsm8k', subset_name='main', split=split)
  42. data = data.map(lambda x: { # type: ignore
  43. 'prompt': [
  44. {'role': 'system', 'content': SYSTEM_PROMPT},
  45. {'role': 'user', 'content': x['question']}
  46. ],
  47. 'answer': extract_hash_answer(x['answer'])
  48. }) # type: ignore
  49. return data # type: ignore
  50. dataset = get_gsm8k_questions()
  51. # 方法 1:使用 datasets 库的 to_json 方法
  52. dataset.to_json(os.path.join("..","data","backup", "gsm8k_dataset_for_train.jsonl"), orient="records", lines=True, force_ascii=False)
  53. # Reward functions
  54. def correctness_reward_func(prompts, completions, answer, **kwargs) -> list[float]:
  55. responses = [completion[0]['content'] for completion in completions]
  56. q = prompts[0][-1]['content']
  57. extracted_responses = [extract_xml_answer(r) for r in responses]
  58. print('-'*20, f"Question:\n{q}", f"\nAnswer:\n{answer[0]}", f"\nResponse:\n{responses[0]}", f"\nExtracted:\n{extracted_responses[0]}")
  59. return [2.0 if r == a else 0.0 for r, a in zip(extracted_responses, answer)]
  60. def int_reward_func(completions, **kwargs) -> list[float]:
  61. responses = [completion[0]['content'] for completion in completions]
  62. extracted_responses = [extract_xml_answer(r) for r in responses]
  63. return [0.5 if r.isdigit() else 0.0 for r in extracted_responses]
  64. def strict_format_reward_func(completions, **kwargs) -> list[float]:
  65. """Reward function that checks if the completion has a specific format."""
  66. pattern = r"^<reasoning>\n.*?\n</reasoning>\n<answer>\n.*?\n</answer>\n$"
  67. responses = [completion[0]["content"] for completion in completions]
  68. matches = [re.match(pattern, r) for r in responses]
  69. return [0.5 if match else 0.0 for match in matches]
  70. def soft_format_reward_func(completions, **kwargs) -> list[float]:
  71. """Reward function that checks if the completion has a specific format."""
  72. pattern = r"<reasoning>.*?</reasoning>\s*<answer>.*?</answer>"
  73. responses = [completion[0]["content"] for completion in completions]
  74. matches = [re.match(pattern, r) for r in responses]
  75. return [0.5 if match else 0.0 for match in matches]
  76. def count_xml(text) -> float:
  77. count = 0.0
  78. if text.count("<reasoning>\n") == 1:
  79. count += 0.125
  80. if text.count("\n</reasoning>\n") == 1:
  81. count += 0.125
  82. if text.count("\n<answer>\n") == 1:
  83. count += 0.125
  84. count -= len(text.split("\n</answer>\n")[-1])*0.001
  85. if text.count("\n</answer>") == 1:
  86. count += 0.125
  87. count -= (len(text.split("\n</answer>")[-1]) - 1)*0.001
  88. return count
  89. def xmlcount_reward_func(completions, **kwargs) -> list[float]:
  90. contents = [completion[0]["content"] for completion in completions]
  91. return [count_xml(c) for c in contents]
  92. class ModelTrainer:
  93. def __init__(self, model_name, max_seq_length, dtype, load_in_4bit,lora_rank=32):
  94. # 初始化 ModelTrainer 类,设置模型名称、最大序列长度、数据类型和是否以4位加载
  95. self.model_name = model_name
  96. self.max_seq_length = max_seq_length
  97. self.dtype = dtype # dtype: 数据类型,如 torch.float16 或 torch.bfloat16
  98. self.load_in_4bit = load_in_4bit # load_in_4bit: 是否以4位精度加载模型,用于节省显存
  99. self.lora_rank=lora_rank #Larger rank = smarter, but slower
  100. def load_model(self,lora_rank=64):
  101. # 加载预训练模型和分词器
  102. model, tokenizer = FastLanguageModel.from_pretrained(
  103. model_name=self.model_name,
  104. max_seq_length=self.max_seq_length,
  105. load_in_4bit=self.load_in_4bit, # 值为True 以 4 bit量化进行微调,为False LoRA 16bit。这将内存使用量减少了 4 倍,使我们能够在免费的 16GB 内存 GPU 中实际进行微调。4 位量化本质上将权重转换为一组有限的数字以减少内存使用量。这样做的缺点是准确度会下降 1-2%。如果您想要这种微小的额外准确度,请在较大的 GPU(如 H100)上将其设置为 False。
  106. dtype=self.dtype,
  107. fast_inference = True, # Enable vLLM fast inference
  108. max_lora_rank = lora_rank,
  109. gpu_memory_utilization=0.005, # 0.6 # Reduce if out of memory
  110. )
  111. # 将模型移动到设备上
  112. model = model.to_empty(device='cuda') # 使用 to_empty 而不是 to
  113. # 初始化模型的权重
  114. for param in model.parameters():
  115. if param.is_meta:
  116. param.data = torch.randn_like(param) # 随机初始化
  117. # 添加 LoRA 适配器
  118. model = FastLanguageModel.get_peft_model(
  119. model,
  120. max_seq_length=self.max_seq_length, # 最大上下文(序列)长度
  121. r=lora_rank, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128
  122. target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
  123. "gate_proj", "up_proj", "down_proj"], # 应用 LoRA 的目标模块
  124. lora_alpha=16, # LoRA 的 alpha 参数,控制适配器的缩放
  125. lora_dropout=0, # LoRA 的 dropout 率,设置为0以优化性能
  126. bias="none", # 是否在 LoRA 中添加偏置,设置为 "none" 以优化性能
  127. use_gradient_checkpointing="unsloth", # 使用梯度检查点以节省显存,对于非常长的上下文,使用 True 或 "unsloth"
  128. random_state=3407, # 随机种子,确保实验可复现
  129. use_rslora=False, # 是否使用 rank stabilized LoRA,当前不支持
  130. loftq_config=None, # LoftQ 配置,当前不支持
  131. )
  132. return model, tokenizer
  133. def load_data(self, train_data_path):
  134. # 加载训练集和测试集
  135. with open(train_data_path, 'r') as f:
  136. train_dataset = load_dataset("json", data_files={"train": train_data_path}, split="train")
  137. # train_data_path: 训练数据路径,格式为 JSONL
  138. return train_dataset
  139. def train(self, model, tokenizer, train_dataset):
  140. print("is_bfloat16_supported()=", is_bfloat16_supported())
  141. # 监控显存使用情况
  142. print(f"Reserved memory: {torch.cuda.memory_reserved()}")
  143. print(f"Allocated memory: {torch.cuda.memory_allocated()}")
  144. # 启用 pin_memory 2025年3月10日未能验证通过
  145. train_loader = torch.utils.data.DataLoader(
  146. train_dataset, batch_size=1, shuffle=True, pin_memory=True
  147. )
  148. # 释放未使用的显存
  149. torch.cuda.empty_cache()
  150. training_args = GRPOConfig(
  151. use_vllm = True, # use vLLM for fast inference!
  152. learning_rate = 5e-6,
  153. adam_beta1 = 0.9,
  154. adam_beta2 = 0.99,
  155. weight_decay = 0.1,
  156. warmup_ratio = 0.1,
  157. lr_scheduler_type = "cosine",
  158. optim ="adamw_8bit", # "adamw_8bit" if device == "cuda" else "adamw_torch", # CPU 使用 adamw_torch
  159. logging_steps = 1,
  160. bf16 = is_bfloat16_supported(),
  161. fp16 = not is_bfloat16_supported(),
  162. per_device_train_batch_size = 1,
  163. gradient_accumulation_steps = 1, # Increase to 4 for smoother training
  164. num_generations = 4, # 8 # 每次生成 输出 个数
  165. max_prompt_length = 256, # 256 # 输入提示的最大长度
  166. max_completion_length = 200,# 200 # 生成内容的最大长度
  167. num_train_epochs = 1, # Set to 1 for a full training run
  168. max_steps = 250, # 250
  169. save_steps = 250, # 250
  170. max_grad_norm = 0.1,
  171. report_to = "none", # Can use Weights & Biases
  172. output_dir = os.path.join('..', 'models',"outputs"),
  173. )
  174. # 初始化 SFTTrainer
  175. trainer = GRPOTrainer(
  176. model = model,
  177. processing_class = tokenizer,
  178. reward_funcs = [
  179. xmlcount_reward_func,
  180. soft_format_reward_func,
  181. strict_format_reward_func,
  182. int_reward_func,
  183. correctness_reward_func,
  184. ],
  185. args = training_args,
  186. train_dataset = train_dataset,
  187. )
  188. # 训练模型
  189. trainer.train()
  190. return model
  191. def save_model(self, model, tokenizer, save_path):
  192. # 保存模型和分词器
  193. model.save_pretrained(save_path)
  194. tokenizer.save_pretrained(save_path)
  195. print(f"Model saved to {save_path}")
  196. if __name__ == "__main__":
  197. # 配置参数
  198. model_name = os.path.join('..', 'models', 'pretrained', 'DeepSeek-R1-Distill-Qwen-1.5B')
  199. # model_name: 预训练模型的路径
  200. max_seq_length = 512 # 单次会话(single session) 的最大 token 长度,一个token大约3-4 字节(Byte)
  201. dtype = torch.float16 # 数据类型
  202. load_in_4bit = True # 是否以4位精度加载模型
  203. lora_rank=16
  204. # 定义训练集和测试集路径
  205. train_data_path = os.path.join('..', 'data', 'processed', 'train.jsonl')
  206. # train_data_path: 训练数据路径
  207. try:
  208. # 设置环境变量
  209. # 单机多卡
  210. os.environ['RANK'] = '0' # 第一张卡的 rank
  211. os.environ['WORLD_SIZE'] = '1' # 总共有 1 张卡
  212. os.environ['MASTER_ADDR'] = 'localhost'
  213. os.environ['MASTER_PORT'] = '12345'
  214. # 多机多卡
  215. # export RANK=0 # 第一台机器的 rank
  216. # export WORLD_SIZE=4 # 总共有 4 台机器
  217. # export MASTER_ADDR=<主节点 IP>
  218. # export MASTER_PORT=12345
  219. # 初始化进程组
  220. # dist.init_process_group(backend='nccl', init_method='env://')
  221. # 初始化 ModelTrainer
  222. trainer = ModelTrainer(model_name, max_seq_length, dtype, load_in_4bit,lora_rank)
  223. # 加载模型和分词器
  224. model, tokenizer = trainer.load_model(lora_rank)
  225. # 加载数据集
  226. train_dataset = trainer.load_data(train_data_path)
  227. # 训练模型
  228. model = trainer.train(model, tokenizer, train_dataset)
  229. # 保存模型
  230. save_path = os.path.join('..', 'models', 'trained', 'DeepSeek-R1-Distill-Qwen-1.5B-GRPO')
  231. trainer.save_model(model, tokenizer, save_path)
  232. finally:
  233. # 确保进程组被销毁
  234. if dist.is_initialized():
  235. dist.destroy_process_group()
  236. print("train finally")