File size: 2,018 Bytes
ccbd209
 
 
 
 
 
 
 
 
 
 
9bd725a
ccbd209
 
 
 
 
 
9bd725a
 
 
ccbd209
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e35fb1
 
 
 
 
ccbd209
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
"""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

    # the "type" column rides along and reaches the reward_func as a kwarg, so each
    # completion is scored by the right modality verifier + judge.
    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()
    # merge the LoRA into the base so the next stage loads a full model (not a bare adapter)
    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