train_model_grpo_v1.2.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. #!/usr/bin/env python3
  2. import re
  3. import torch
  4. import os
  5. import json
  6. from unsloth import FastLanguageModel, PatchFastRL, is_bfloat16_supported
  7. from datasets import Dataset
  8. from trl import GRPOConfig, GRPOTrainer
  9. from vllm import SamplingParams
  10. import trl.trainer.grpo_trainer
  11. from conf_train import load_config
  12. class GRPOTrainerWrapper:
  13. """
  14. Wrapper class for GRPO training with object-oriented design.
  15. """
  16. # Constants
  17. SYSTEM_PROMPT = """
  18. Respond in the following format:
  19. <reasoning>
  20. ...
  21. </reasoning>
  22. <answer>
  23. ...
  24. </answer>
  25. """
  26. XML_COT_FORMAT = """\
  27. <reasoning>
  28. {reasoning}
  29. </reasoning>
  30. <answer>
  31. {answer}
  32. </answer>
  33. """
  34. def __init__(self, config):
  35. """
  36. Initialize the trainer with configuration.
  37. """
  38. self.config = config
  39. self.model = None
  40. self.tokenizer = None
  41. self.trainer = None
  42. # Enable Unsloth's CLI training metrics visualization
  43. os.environ["UNSLOTH_DISPLAY_METRICS"] = "true"
  44. # Apply patch
  45. PatchFastRL("GRPO", FastLanguageModel)
  46. # Monkey patch the validation in the GRPOTrainer
  47. self._patch_grpo_trainer()
  48. def _patch_grpo_trainer(self):
  49. """
  50. Monkey patch the GRPOTrainer to bypass the divisibility check.
  51. """
  52. original_init = trl.trainer.grpo_trainer.GRPOTrainer.__init__
  53. def patched_init(self, *args, **kwargs):
  54. try:
  55. original_init(self, *args, **kwargs)
  56. except ValueError as e:
  57. if "evenly divisible by the number of generations per prompt" in str(e):
  58. print("Bypassing TRL's batch divisibility check...")
  59. # Continue with initialization despite the error
  60. self.args = kwargs.get("args")
  61. self.model = kwargs.get("model")
  62. self.processing_class = kwargs.get("processing_class")
  63. self.reward_funcs = kwargs.get("reward_funcs")
  64. self.train_dataset = kwargs.get("train_dataset")
  65. # Set up necessary trainer components without the check
  66. self._setup_trainer()
  67. else:
  68. raise e
  69. trl.trainer.grpo_trainer.GRPOTrainer.__init__ = patched_init
  70. def load_model(self):
  71. """
  72. Load the model and tokenizer.
  73. """
  74. self.model, self.tokenizer = FastLanguageModel.from_pretrained(
  75. model_name=self.config.model_name,
  76. max_seq_length=self.config.max_seq_length,
  77. load_in_4bit=self.config.load_in_4bit,
  78. fast_inference=self.config.fast_inference,
  79. max_lora_rank=self.config.lora_rank,
  80. gpu_memory_utilization=self.config.gpu_memory_utilization,
  81. )
  82. self.model = FastLanguageModel.get_peft_model(
  83. self.model,
  84. r=self.config.lora_rank,
  85. target_modules=[
  86. "q_proj", "k_proj", "v_proj", "o_proj",
  87. "gate_proj", "up_proj", "down_proj",
  88. ],
  89. lora_alpha=self.config.lora_rank,
  90. use_gradient_checkpointing="unsloth",
  91. random_state=3407,
  92. )
  93. @staticmethod
  94. def extract_xml_answer(text: str) -> str:
  95. """
  96. Extract answer from XML formatted text.
  97. """
  98. answer = text.split("<answer>")[-1]
  99. answer = answer.split("</answer>")[0]
  100. return answer.strip()
  101. @staticmethod
  102. def extract_hash_answer(text: str) -> str | None:
  103. """
  104. Extract answer from hash formatted text.
  105. """
  106. if "####" not in text:
  107. return None
  108. return text.split("####")[1].strip()
  109. def load_dataset(self) -> Dataset:
  110. """
  111. Load and prepare the training dataset.
  112. """
  113. # Read JSONL file
  114. data = []
  115. with open(self.config.train_data_path, 'r') as f:
  116. for line in f:
  117. data.append(json.loads(line))
  118. # Convert list to HuggingFace Dataset object
  119. return Dataset.from_list(data)
  120. def correctness_reward_func(self, prompts, completions, answer, **kwargs) -> list[float]:
  121. """
  122. Reward function for answer correctness.
  123. """
  124. responses = [completion[0]['content'] for completion in completions]
  125. q = prompts[0][-1]['content']
  126. extracted_responses = [self.extract_xml_answer(r) for r in responses]
  127. print('-'*20, f"Question:\n{q}", f"\nAnswer:\n{answer[0]}",
  128. f"\nResponse:\n{responses[0]}", f"\nExtracted:\n{extracted_responses[0]}")
  129. return [2.0 if r == a else 0.0 for r, a in zip(extracted_responses, answer)]
  130. def int_reward_func(self, completions, **kwargs) -> list[float]:
  131. """
  132. Reward function for integer answers.
  133. """
  134. responses = [completion[0]['content'] for completion in completions]
  135. extracted_responses = [self.extract_xml_answer(r) for r in responses]
  136. return [0.5 if r.isdigit() else 0.0 for r in extracted_responses]
  137. def strict_format_reward_func(self, completions, **kwargs) -> list[float]:
  138. """
  139. Strict format reward function.
  140. """
  141. pattern = r"^<reasoning>\n.*?\n</reasoning>\n<answer>\n.*?\n</answer>\n$"
  142. responses = [completion[0]["content"] for completion in completions]
  143. matches = [re.match(pattern, r) for r in responses]
  144. return [0.5 if match else 0.0 for match in matches]
  145. def soft_format_reward_func(self, completions, **kwargs) -> list[float]:
  146. """
  147. Soft format reward function.
  148. """
  149. pattern = r"<reasoning>.*?</reasoning>\s*<answer>.*?</answer>"
  150. responses = [completion[0]["content"] for completion in completions]
  151. matches = [re.match(pattern, r) for r in responses]
  152. return [0.5 if match else 0.0 for match in matches]
  153. def count_xml(self, text) -> float:
  154. """
  155. Count XML tags in text.
  156. """
  157. count = 0.0
  158. if text.count("<reasoning>\n") == 1:
  159. count += 0.125
  160. if text.count("\n</reasoning>\n") == 1:
  161. count += 0.125
  162. if text.count("\n<answer>\n") == 1:
  163. count += 0.125
  164. count -= len(text.split("\n</answer>\n")[-1])*0.001
  165. if text.count("\n</answer>") == 1:
  166. count += 0.125
  167. count -= (len(text.split("\n</answer>")[-1]) - 1)*0.001
  168. return count
  169. def xmlcount_reward_func(self, completions, **kwargs) -> list[float]:
  170. """
  171. Reward function based on XML tag count.
  172. """
  173. contents = [completion[0]["content"] for completion in completions]
  174. return [self.count_xml(c) for c in contents]
  175. def prepare_training_args(self) -> GRPOConfig:
  176. """
  177. Prepare training arguments from config.
  178. """
  179. return GRPOConfig(
  180. use_vllm=self.config.use_vllm,
  181. learning_rate=float(self.config.learning_rate) ,
  182. adam_beta1=self.config.adam_beta1,
  183. adam_beta2=self.config.adam_beta2,
  184. weight_decay=self.config.weight_decay,
  185. warmup_ratio=self.config.warmup_ratio,
  186. lr_scheduler_type=self.config.lr_scheduler_type,
  187. optim=self.config.optim,
  188. logging_steps=self.config.logging_steps,
  189. bf16=is_bfloat16_supported(),
  190. fp16=not is_bfloat16_supported(),
  191. per_device_train_batch_size=self.config.per_device_train_batch_size,
  192. gradient_accumulation_steps=self.config.gradient_accumulation_steps,
  193. num_generations=self.config.num_generations,
  194. max_prompt_length=self.config.max_prompt_length,
  195. max_completion_length=self.config.max_completion_length,
  196. max_steps=self.config.max_steps,
  197. save_steps=self.config.save_steps,
  198. max_grad_norm=self.config.max_grad_norm,
  199. report_to=self.config.report_to,
  200. output_dir=self.config.output_dir,
  201. save_total_limit=3,
  202. log_level="info",
  203. disable_tqdm=False,
  204. evaluation_strategy="no",
  205. )
  206. def initialize_trainer(self, dataset):
  207. """
  208. Initialize the GRPO trainer.
  209. """
  210. training_args = self.prepare_training_args()
  211. self.trainer = GRPOTrainer(
  212. model=self.model,
  213. processing_class=self.tokenizer,
  214. reward_funcs=[
  215. self.xmlcount_reward_func,
  216. self.soft_format_reward_func,
  217. self.strict_format_reward_func,
  218. self.int_reward_func,
  219. self.correctness_reward_func,
  220. ],
  221. args=training_args,
  222. train_dataset=dataset,
  223. )
  224. def train(self):
  225. """
  226. Execute the training process.
  227. """
  228. print("Starting GRPO training...")
  229. print(f"per_device_train_batch_size = {self.config.per_device_train_batch_size}")
  230. print(f"gradient_accumulation_steps = {self.config.gradient_accumulation_steps}")
  231. print(f"num_generations = {self.config.num_generations}")
  232. print(f"max_steps = {self.config.max_steps}")
  233. self.trainer.train()
  234. def save_model(self):
  235. """
  236. Save the trained model.
  237. """
  238. print(f"Saving model to {self.config.save_path}...")
  239. os.makedirs(os.path.dirname(self.config.save_path), exist_ok=True)
  240. self.model.save_pretrained(self.config.save_path)
  241. self.tokenizer.save_pretrained(self.config.save_path)
  242. print("Training complete!")
  243. def main():
  244. # Load configuration
  245. config = load_config()
  246. # Initialize and run trainer
  247. trainer = GRPOTrainerWrapper(config)
  248. trainer.load_model()
  249. dataset = trainer.load_dataset()
  250. trainer.initialize_trainer(dataset)
  251. trainer.train()
  252. trainer.save_model()
  253. if __name__ == "__main__":
  254. main()