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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""OCC GRPO Training Demo β Minimal end-to-end GRPO with OCC reward hook.
|
| 3 |
+
|
| 4 |
+
This script trains Qwen2.5-0.5B-Instruct with GRPO using a cost-adjusted
|
| 5 |
+
marginal impact reward from OCC. The reward combines:
|
| 6 |
+
- Accuracy (is the answer correct?)
|
| 7 |
+
- Format (did the model think before answering?)
|
| 8 |
+
- Cost penalty (shorter completions are cheaper)
|
| 9 |
+
- Confident-wrong penalty (overconfident wrong answers are punished)
|
| 10 |
+
|
| 11 |
+
Intended as a minimal demonstration: even 10-50 steps on a T4 proves the
|
| 12 |
+
OCC reward integrates with TRL's GRPOTrainer.
|
| 13 |
+
|
| 14 |
+
Usage:
|
| 15 |
+
uv run --with transformers --with trl --with torch --with datasets \
|
| 16 |
+
--with accelerate scripts/grpo_train_occ.py
|
| 17 |
+
|
| 18 |
+
Or via accelerate launch for multi-GPU:
|
| 19 |
+
accelerate launch scripts/grpo_train_occ.py
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
import re
|
| 23 |
+
import json
|
| 24 |
+
import torch
|
| 25 |
+
from datasets import Dataset, load_dataset
|
| 26 |
+
from trl import GRPOTrainer, GRPOConfig
|
| 27 |
+
|
| 28 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 29 |
+
# OCC Reward Function
|
| 30 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 31 |
+
|
| 32 |
+
def occ_reward(completions, ground_truth, completion_ids=None, prompts=None, **kwargs):
|
| 33 |
+
"""
|
| 34 |
+
OCC cost-adjusted reward function for GRPO.
|
| 35 |
+
|
| 36 |
+
Reward components:
|
| 37 |
+
- correctness: +1.0 if answer matches ground truth, -1.0 otherwise
|
| 38 |
+
- format: +0.1 if completion contains thinking markers
|
| 39 |
+
- cost_penalty: -0.001 per token (incentivizes conciseness)
|
| 40 |
+
- confident_wrong_penalty: -0.5 extra if wrong but uses confident language
|
| 41 |
+
- abstention_bonus: +0.3 if model says "I don't know" (reward honest uncertainty)
|
| 42 |
+
|
| 43 |
+
Total reward = correctness + format + cost_penalty + confident_wrong_penalty + abstention_bonus
|
| 44 |
+
"""
|
| 45 |
+
rewards = []
|
| 46 |
+
for i, completion in enumerate(completions):
|
| 47 |
+
# Extract content from conversational format
|
| 48 |
+
if isinstance(completion, list) and len(completion) > 0:
|
| 49 |
+
content = completion[0].get("content", "")
|
| 50 |
+
else:
|
| 51 |
+
content = str(completion)
|
| 52 |
+
|
| 53 |
+
gt = ground_truth[i] if i < len(ground_truth) else ""
|
| 54 |
+
content_lower = content.lower()
|
| 55 |
+
|
| 56 |
+
# ββ Correctness ββββββββββββββββββββββββββββββββββββββ
|
| 57 |
+
# Extract final answer from boxed{} or "answer is X" patterns
|
| 58 |
+
final_answer = None
|
| 59 |
+
boxed_match = re.search(r"\\boxed\{(.*?)\}", content)
|
| 60 |
+
if boxed_match:
|
| 61 |
+
final_answer = boxed_match.group(1).strip()
|
| 62 |
+
else:
|
| 63 |
+
answer_match = re.search(r"(?:answer|result|solution)\s*(?:is|=)\s*([^\s,.]+)", content_lower)
|
| 64 |
+
if answer_match:
|
| 65 |
+
final_answer = answer_match.group(1).strip()
|
| 66 |
+
|
| 67 |
+
if final_answer:
|
| 68 |
+
correctness = 1.0 if final_answer == gt.strip() else -1.0
|
| 69 |
+
else:
|
| 70 |
+
# No answer extracted β penalize slightly
|
| 71 |
+
correctness = -0.5
|
| 72 |
+
|
| 73 |
+
# ββ Format reward ββββββββββββββββββββββββββββββββββββ
|
| 74 |
+
has_think = bool(re.search(r"|think", content, re.IGNORECASE))
|
| 75 |
+
format_reward = 0.1 if has_think else 0.0
|
| 76 |
+
|
| 77 |
+
# ββ Cost penalty βββββββββββββββββββββββββββββββββββββ
|
| 78 |
+
n_tokens = len(completion_ids[i]) if completion_ids else len(content.split())
|
| 79 |
+
cost_penalty = -0.001 * n_tokens
|
| 80 |
+
|
| 81 |
+
# ββ Confident-wrong penalty ββββββββββββββββββββββββββ
|
| 82 |
+
confident_markers = ["definitely", "certainly", "obviously", "clearly", "without doubt"]
|
| 83 |
+
is_confident = any(m in content_lower for m in confident_markers)
|
| 84 |
+
is_wrong = correctness < 0
|
| 85 |
+
confident_wrong_penalty = -0.5 if (is_confident and is_wrong) else 0.0
|
| 86 |
+
|
| 87 |
+
# ββ Abstention bonus βββββββββββββββββββββββββββββββββ
|
| 88 |
+
abstention_markers = ["i don't know", "i do not know", "cannot determine", "uncertain", "not sure"]
|
| 89 |
+
is_abstaining = any(m in content_lower for m in abstention_markers)
|
| 90 |
+
abstention_bonus = 0.3 if is_abstaining else 0.0
|
| 91 |
+
|
| 92 |
+
# ββ Assemble total reward ββββββββββββββββββββββββββββ
|
| 93 |
+
total = correctness + format_reward + cost_penalty + confident_wrong_penalty + abstention_bonus
|
| 94 |
+
rewards.append(total)
|
| 95 |
+
|
| 96 |
+
# Log reward breakdown for monitoring
|
| 97 |
+
if kwargs.get("log_extra"):
|
| 98 |
+
kwargs["log_extra"]("correctness", [1.0 if r > 0 else -1.0 if r < 0 else 0.0 for r in rewards])
|
| 99 |
+
|
| 100 |
+
return rewards
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
# βββββββββββββββββοΏ½οΏ½βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 104 |
+
# Main Training
|
| 105 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 106 |
+
|
| 107 |
+
def main():
|
| 108 |
+
print("[OCC-GRPO] Loading dataset...")
|
| 109 |
+
# Using DeepMath-103K β standard conversational format for GRPO
|
| 110 |
+
try:
|
| 111 |
+
dataset = load_dataset("trl-lib/DeepMath-103K", split="train")
|
| 112 |
+
# Take a small subset for quick demo
|
| 113 |
+
dataset = dataset.select(range(min(200, len(dataset))))
|
| 114 |
+
print(f"[OCC-GRPO] Loaded {len(dataset)} examples from DeepMath-103K")
|
| 115 |
+
except Exception:
|
| 116 |
+
print("[OCC-GRPO] DeepMath-103K not available, using synthetic dataset")
|
| 117 |
+
# Fallback: synthetic math problems
|
| 118 |
+
data = [
|
| 119 |
+
{"prompt": [{"role": "user", "content": f"What is {a} + {b}?"}],
|
| 120 |
+
"ground_truth": str(a + b)}
|
| 121 |
+
for a, b in [(i, j) for i in range(1, 20) for j in range(1, 20)][:200]
|
| 122 |
+
]
|
| 123 |
+
dataset = Dataset.from_list(data)
|
| 124 |
+
|
| 125 |
+
# Training config β minimal for quick demo
|
| 126 |
+
training_args = GRPOConfig(
|
| 127 |
+
output_dir="./occ_grpo_output",
|
| 128 |
+
per_device_train_batch_size=2,
|
| 129 |
+
per_device_eval_batch_size=2,
|
| 130 |
+
num_train_epochs=1,
|
| 131 |
+
max_steps=20, # Minimal demo
|
| 132 |
+
logging_steps=5,
|
| 133 |
+
save_steps=20,
|
| 134 |
+
learning_rate=1e-6,
|
| 135 |
+
bf16=True if torch.cuda.is_bf16_supported() else False,
|
| 136 |
+
fp16=True if not torch.cuda.is_bf16_supported() else False,
|
| 137 |
+
gradient_checkpointing=True,
|
| 138 |
+
gradient_accumulation_steps=2,
|
| 139 |
+
max_completion_length=256,
|
| 140 |
+
num_generations=4, # G=4 completions per prompt
|
| 141 |
+
report_to="none", # Disable wandb/tensorboard for simplicity
|
| 142 |
+
disable_tqdm=False,
|
| 143 |
+
logging_strategy="steps",
|
| 144 |
+
logging_first_step=True,
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
print(f"[OCC-GRPO] Model: Qwen/Qwen2.5-0.5B-Instruct")
|
| 148 |
+
print(f"[OCC-GRPO] Steps: {training_args.max_steps}")
|
| 149 |
+
print(f"[OCC-GRPO] Generations per prompt: {training_args.num_generations}")
|
| 150 |
+
print(f"[OCC-GRPO] Device: {'cuda' if torch.cuda.is_available() else 'cpu'}")
|
| 151 |
+
|
| 152 |
+
trainer = GRPOTrainer(
|
| 153 |
+
model="Qwen/Qwen2.5-0.5B-Instruct",
|
| 154 |
+
args=training_args,
|
| 155 |
+
reward_funcs=occ_reward,
|
| 156 |
+
train_dataset=dataset,
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
print("[OCC-GRPO] Starting training...")
|
| 160 |
+
trainer.train()
|
| 161 |
+
|
| 162 |
+
print("[OCC-GRPO] Saving model...")
|
| 163 |
+
trainer.save_model("./occ_grpo_output/final")
|
| 164 |
+
|
| 165 |
+
# Save a summary
|
| 166 |
+
summary = {
|
| 167 |
+
"method": "GRPO with OCC cost-adjusted reward",
|
| 168 |
+
"model": "Qwen/Qwen2.5-0.5B-Instruct",
|
| 169 |
+
"reward_components": [
|
| 170 |
+
"correctness (Β±1.0)",
|
| 171 |
+
"format (+0.1 if thinking markers)",
|
| 172 |
+
"cost_penalty (-0.001/token)",
|
| 173 |
+
"confident_wrong_penalty (-0.5)",
|
| 174 |
+
"abstention_bonus (+0.3)"
|
| 175 |
+
],
|
| 176 |
+
"steps": training_args.max_steps,
|
| 177 |
+
"generations_per_prompt": training_args.num_generations,
|
| 178 |
+
}
|
| 179 |
+
with open("./occ_grpo_output/summary.json", "w") as f:
|
| 180 |
+
json.dump(summary, f, indent=2)
|
| 181 |
+
|
| 182 |
+
print("[OCC-GRPO] Done. Output in ./occ_grpo_output/")
|
| 183 |
+
|
| 184 |
+
if __name__ == "__main__":
|
| 185 |
+
main()
|