NotoriousH2 commited on
Commit
24e2849
ยท
verified ยท
1 Parent(s): d304eb5

Add rs_sample.py

Browse files
Files changed (1) hide show
  1. rs_sample.py +108 -0
rs_sample.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """RS sampling from C18-2 model (48.5% GSM8K)"""
2
+ import json, re, asyncio, random
3
+ from openai import AsyncOpenAI
4
+
5
+ SP = "์ฃผ์–ด์ง„ ์ˆ˜ํ•™ ๋ฌธ์ œ๋ฅผ ๋‹จ๊ณ„๋ณ„๋กœ ํ’€๊ณ  ๋‹ต๋ณ€์„ ์ž‘์„ฑํ•˜์„ธ์š”.\n๋ฐ˜๋“œ์‹œ ์ตœ์ข… ๋‹ต๋ณ€์„ \\boxed{์ •์ˆ˜} ํ˜•์‹์œผ๋กœ ๋งˆ์ง€๋ง‰ ์ค„์— ์ถœ๋ ฅํ•˜์„ธ์š”.\n์˜ˆ์‹œ: \\boxed{42}"
6
+
7
+ def extract_boxed(text):
8
+ m = re.findall(r'\\boxed\{([^}]+)\}', text)
9
+ return m[-1].strip() if m else None
10
+
11
+ def normalize(a):
12
+ if a is None: return None
13
+ s = str(a).replace(",","").replace(" ","").strip()
14
+ try:
15
+ n = float(s)
16
+ return str(int(n)) if n == int(n) else str(n)
17
+ except: return s
18
+
19
+ # Load GSM8K train questions (the ones we have gold answers for)
20
+ with open("data/GSM8K_full_qwen3_30b.json") as f:
21
+ data = json.load(f)
22
+
23
+ # Get unique questions with their gold answers
24
+ q_to_gold = {}
25
+ for d in data:
26
+ q = d["question"]
27
+ if q not in q_to_gold:
28
+ # Extract gold from the existing correct solutions
29
+ gold = extract_boxed(d["answer"])
30
+ if gold:
31
+ q_to_gold[q] = normalize(gold)
32
+
33
+ questions = list(q_to_gold.keys())
34
+ random.seed(42)
35
+ random.shuffle(questions)
36
+ # Sample a subset for RS (use all unique questions)
37
+ print(f"Total unique questions: {len(questions)}")
38
+
39
+ client = AsyncOpenAI(base_url="http://localhost:8000/v1", api_key="token-abc123")
40
+
41
+ async def sample_one(question, n=16):
42
+ messages = [{"role": "user", "content": SP + "\n\n" + question}]
43
+ try:
44
+ resp = await client.chat.completions.create(
45
+ model="outputs/models/c18-2-combined-rs",
46
+ messages=messages, temperature=0.8, max_tokens=2048, n=n
47
+ )
48
+ return [c.message.content for c in resp.choices]
49
+ except Exception as e:
50
+ print(f" Error: {e}")
51
+ return []
52
+
53
+ async def main():
54
+ sem = asyncio.Semaphore(100)
55
+ sft_data = []
56
+ dpo_data = []
57
+ batch_size = 200
58
+
59
+ for batch_start in range(0, len(questions), batch_size):
60
+ batch = questions[batch_start:batch_start+batch_size]
61
+
62
+ async def process(q):
63
+ async with sem:
64
+ return q, await sample_one(q)
65
+
66
+ results = await asyncio.gather(*[process(q) for q in batch])
67
+
68
+ for q, answers in results:
69
+ gold = q_to_gold[q]
70
+ correct = []
71
+ incorrect = []
72
+ for a in answers:
73
+ pred = normalize(extract_boxed(a))
74
+ if pred and pred == gold:
75
+ correct.append(a)
76
+ else:
77
+ incorrect.append(a)
78
+
79
+ if correct:
80
+ best = min(correct, key=len) # shortest correct
81
+ sft_data.append({
82
+ "question": q, "answer": best,
83
+ "n_correct": len(correct), "n_total": len(answers)
84
+ })
85
+
86
+ if correct and incorrect:
87
+ dpo_data.append({
88
+ "question": q,
89
+ "answer": min(correct, key=len),
90
+ "bad_answer": max(incorrect, key=len)
91
+ })
92
+
93
+ print(f" Batch {batch_start//batch_size + 1}: {len(sft_data)} sft, {len(dpo_data)} dpo")
94
+
95
+ import os
96
+ os.makedirs("outputs/c18_rs", exist_ok=True)
97
+ with open("outputs/c18_rs/sft_dataset.json", "w") as f:
98
+ json.dump(sft_data, f, ensure_ascii=False, indent=2)
99
+ with open("outputs/c18_rs/dpo_dataset.json", "w") as f:
100
+ json.dump(dpo_data, f, ensure_ascii=False, indent=2)
101
+
102
+ n4 = sum(1 for d in sft_data if d["n_correct"] >= 4)
103
+ print(f"\nRS Summary:")
104
+ print(f" SFT: {len(sft_data)} (4+/16 filter: {n4})")
105
+ print(f" DPO: {len(dpo_data)} pairs")
106
+ print(f" Avg correct: {sum(d['n_correct'] for d in sft_data)/len(sft_data):.1f}/16")
107
+
108
+ asyncio.run(main())