| """The RL core: GRPO with the judge as the reward model. |
| |
| This is the "constantly improving via reinforcement" engine. For each prompt the policy |
| samples GRPO_NUM_GENERATIONS candidates; the judge scores each (reward); GRPO nudges the |
| policy toward the higher-scoring ones (group-relative advantage). No human labels needed |
| in the loop -- the judge IS the reward -- which is exactly why the eval gate (evalgate.py) |
| is mandatory to catch reward-hacking / collapse. |
| """ |
| from pathlib import Path |
|
|
|
|
| def run_grpo(policy_model_name, prompts, types, judge, out_dir, steps, num_generations, lr, lora_r, lora_alpha): |
| import torch |
| from datasets import Dataset |
| from peft import LoraConfig |
| from trl import GRPOConfig, GRPOTrainer |
| from core.judge import make_reward_func |
|
|
| |
| |
| ds = Dataset.from_dict({"prompt": prompts, "type": types}) |
| cfg = GRPOConfig( |
| output_dir=out_dir, |
| learning_rate=lr, |
| per_device_train_batch_size=num_generations, |
| num_generations=num_generations, |
| max_steps=steps, |
| bf16=True, |
| gradient_checkpointing=True, |
| logging_steps=10, |
| save_strategy="no", |
| report_to="none", |
| ) |
| peft_cfg = LoraConfig(r=lora_r, lora_alpha=lora_alpha, task_type="CAUSAL_LM", |
| target_modules=["q_proj", "k_proj", "v_proj", "o_proj"]) |
| trainer = GRPOTrainer( |
| model=policy_model_name, |
| reward_funcs=[make_reward_func(judge)], |
| args=cfg, |
| train_dataset=ds, |
| peft_config=peft_cfg, |
| ) |
| trainer.train() |
| |
| from transformers import AutoTokenizer |
| merged = trainer.model.merge_and_unload() |
| merged.save_pretrained(out_dir) |
| AutoTokenizer.from_pretrained(policy_model_name).save_pretrained(out_dir) |
| return out_dir |
|
|