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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
JustGRPO reproduction script (single-GPU, no distributed).
|
| 3 |
+
Adapted from the official JustGRPO repo (eval.py, generate.py, grader.py, parser.py).
|
| 4 |
+
|
| 5 |
+
Claims addressed:
|
| 6 |
+
C1: JustGRPO 89.1% on GSM8K (gen_length=256, steps=256, block_length=32)
|
| 7 |
+
C2: Retains parallel decoding + improves reasoning on math (MATH-500) and code (HumanEval/MBPP)
|
| 8 |
+
C3: Arbitrary order (AO) limits reasoning potential vs AR order (Pass@k / solution coverage)
|
| 9 |
+
|
| 10 |
+
Run on a single GPU (no torchrun needed). Supports --max_examples for budget control.
|
| 11 |
+
Results saved as JSON to --output.
|
| 12 |
+
"""
|
| 13 |
+
import os
|
| 14 |
+
import sys
|
| 15 |
+
import re
|
| 16 |
+
import ast
|
| 17 |
+
import json
|
| 18 |
+
import gzip
|
| 19 |
+
import argparse
|
| 20 |
+
import time
|
| 21 |
+
import random
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
|
| 24 |
+
import torch
|
| 25 |
+
import torch.nn.functional as F
|
| 26 |
+
from tqdm import tqdm
|
| 27 |
+
from datasets import load_dataset
|
| 28 |
+
from transformers import AutoModel, AutoTokenizer
|
| 29 |
+
|
| 30 |
+
# Make the JustGRPO package importable
|
| 31 |
+
HERE = Path(__file__).resolve().parent
|
| 32 |
+
sys.path.insert(0, str(HERE / "JustGRPO"))
|
| 33 |
+
|
| 34 |
+
from utils.generate import generate, add_gumbel_noise, get_num_transfer_tokens
|
| 35 |
+
from utils.grader import math_equal
|
| 36 |
+
from utils.parser import extract_answer, parse_ground_truth
|
| 37 |
+
from data.math import extract_answer_gsm8k, collate_fn_gsm8k, collate_fn_math
|
| 38 |
+
|
| 39 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 40 |
+
MASK_ID = 126336
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
# ---------------- LoRA merge (from eval.py) ----------------
|
| 44 |
+
def merge_lora(model, adapter_dir):
|
| 45 |
+
from safetensors.torch import load_file
|
| 46 |
+
with open(os.path.join(adapter_dir, "adapter_config.json")) as f:
|
| 47 |
+
cfg = json.load(f)
|
| 48 |
+
scaling = cfg["lora_alpha"] / cfg["r"]
|
| 49 |
+
state = load_file(os.path.join(adapter_dir, "adapter_model.safetensors"))
|
| 50 |
+
for key in [k for k in state if ".lora_A." in k]:
|
| 51 |
+
target = key.split(".lora_A.")[0].removeprefix("base_model.model.")
|
| 52 |
+
weight = model.get_submodule(target).weight
|
| 53 |
+
delta = (state[key.replace(".lora_A.", ".lora_B.")].float() @ state[key].float()) * scaling
|
| 54 |
+
weight.data += delta.to(weight.dtype)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def load_model(ckpt_path, base_path="GSAI-ML/LLaDA-8B-Instruct"):
|
| 58 |
+
tokenizer = AutoTokenizer.from_pretrained(base_path, trust_remote_code=True)
|
| 59 |
+
if os.path.exists(os.path.join(ckpt_path, "adapter_config.json")):
|
| 60 |
+
model = AutoModel.from_pretrained(base_path, trust_remote_code=True, torch_dtype=torch.bfloat16)
|
| 61 |
+
merge_lora(model, ckpt_path)
|
| 62 |
+
else:
|
| 63 |
+
model = AutoModel.from_pretrained(ckpt_path, trust_remote_code=True, torch_dtype=torch.bfloat16)
|
| 64 |
+
model.eval().requires_grad_(False).to(DEVICE)
|
| 65 |
+
return model, tokenizer
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
# ---------------- Math eval (GSM8K / MATH-500) ----------------
|
| 69 |
+
def eval_math(model, tokenizer, task, gen_length, steps, block_length, max_examples, temperature=0.0, seed=113):
|
| 70 |
+
if task == "gsm8k":
|
| 71 |
+
ds = load_dataset("gsm8k", "main", split="test")
|
| 72 |
+
collate_fn = collate_fn_gsm8k
|
| 73 |
+
problems = [ex["question"] for ex in ds]
|
| 74 |
+
answers = [ex["answer"] for ex in ds]
|
| 75 |
+
extract_gt = extract_answer_gsm8k
|
| 76 |
+
else:
|
| 77 |
+
ds = load_dataset("ankner/math-500", split="test")
|
| 78 |
+
instruct = r"(Please put the final answer in \boxed{} tag, i.e. $\boxed{answer here}$)"
|
| 79 |
+
problems = [ex["problem"] + instruct for ex in ds]
|
| 80 |
+
answers = [ex["solution"] for ex in ds]
|
| 81 |
+
extract_gt = lambda a: extract_answer(a)
|
| 82 |
+
|
| 83 |
+
n = len(problems)
|
| 84 |
+
if max_examples and max_examples < n:
|
| 85 |
+
# deterministic subset
|
| 86 |
+
rng = random.Random(seed)
|
| 87 |
+
idx = rng.sample(range(n), max_examples)
|
| 88 |
+
problems = [problems[i] for i in idx]
|
| 89 |
+
answers = [answers[i] for i in idx]
|
| 90 |
+
|
| 91 |
+
correct = 0
|
| 92 |
+
total = 0
|
| 93 |
+
t0 = time.time()
|
| 94 |
+
details = []
|
| 95 |
+
for i in tqdm(range(len(problems)), desc=f"eval {task}", disable=True):
|
| 96 |
+
p = problems[i]
|
| 97 |
+
msgs = [[{"role": "user", "content": p}]]
|
| 98 |
+
prompt_text = tokenizer.apply_chat_template(msgs, add_generation_prompt=True, tokenize=False)
|
| 99 |
+
prompt_ids = tokenizer(prompt_text, return_tensors="pt")["input_ids"].to(DEVICE)
|
| 100 |
+
gen_ids = generate(model=model, prompt=prompt_ids, steps=steps, gen_length=gen_length,
|
| 101 |
+
block_length=block_length, temperature=temperature)
|
| 102 |
+
resp = tokenizer.batch_decode(gen_ids[:, prompt_ids.shape[1]:], skip_special_tokens=True)[0]
|
| 103 |
+
gt = extract_gt(answers[i])
|
| 104 |
+
pred = extract_answer(resp) if task != "gsm8k" else extract_answer(resp)
|
| 105 |
+
ok = math_equal(gt, pred, timeout=(task != "gsm8k"))
|
| 106 |
+
correct += int(ok)
|
| 107 |
+
total += 1
|
| 108 |
+
if (i + 1) % 10 == 0:
|
| 109 |
+
elapsed = time.time() - t0
|
| 110 |
+
print(f" [{task}] {i+1}/{len(problems)} acc={correct/total*100:.2f}% elapsed={elapsed:.0f}s", flush=True)
|
| 111 |
+
if i < 5:
|
| 112 |
+
details.append({"idx": i, "correct": bool(ok), "gt": str(gt)[:80], "pred": str(pred)[:80]})
|
| 113 |
+
|
| 114 |
+
acc = correct / total
|
| 115 |
+
elapsed = time.time() - t0
|
| 116 |
+
print(f"\n{task} Accuracy: {correct}/{total} = {acc*100:.2f}% ({elapsed:.0f}s)", flush=True)
|
| 117 |
+
summary = {"task": task, "accuracy": acc, "correct": correct, "total": total,
|
| 118 |
+
"gen_length": gen_length, "steps": steps, "block_length": block_length,
|
| 119 |
+
"temperature": temperature, "elapsed_s": elapsed, "details": details}
|
| 120 |
+
print(f"RESULT_MARKER {task}: {json.dumps(summary)}", flush=True)
|
| 121 |
+
return summary
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
# ---------------- Code eval (HumanEval / MBPP) ----------------
|
| 125 |
+
def _format_humaneval(problems):
|
| 126 |
+
formatted = {}
|
| 127 |
+
for tid, p in problems.items():
|
| 128 |
+
formatted[tid] = dict(p)
|
| 129 |
+
formatted[tid]["prompt"] = (
|
| 130 |
+
"You are an expert Python programmer. Your task is to complete the "
|
| 131 |
+
f"implementation of a function named `{p['entry_point']}`.\n\n"
|
| 132 |
+
f"Here is the function to complete:\n```python\n{p['prompt'].rstrip()}\n```\n"
|
| 133 |
+
)
|
| 134 |
+
return formatted
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def _format_mbpp_prompt(ex):
|
| 138 |
+
func_name = ex["test_list"][0].split(" ")[1].split("(")[0]
|
| 139 |
+
tests_str = "\n".join(f" {t}" for t in ex["test_list"])
|
| 140 |
+
try:
|
| 141 |
+
tree = ast.parse(ex["test_list"][0].strip())
|
| 142 |
+
n_args = 0
|
| 143 |
+
for node in ast.walk(tree):
|
| 144 |
+
if isinstance(node, ast.Call) and getattr(node.func, "id", "") == func_name:
|
| 145 |
+
n_args = len(node.args)
|
| 146 |
+
break
|
| 147 |
+
except Exception:
|
| 148 |
+
n_args = 2
|
| 149 |
+
params = ", ".join(f"input_param_{i + 1}" for i in range(n_args))
|
| 150 |
+
return (
|
| 151 |
+
"You are an expert Python programmer. Your task is to complete the "
|
| 152 |
+
f"implementation of a function named `{func_name}`.\n\n"
|
| 153 |
+
f"** TARGET FUNCTION **\n{ex['text']}\n\n"
|
| 154 |
+
"** UNIT TESTS **\n"
|
| 155 |
+
f"Your code should pass unit tests like:\n{tests_str}\n\n"
|
| 156 |
+
"Here is the function to complete:\n"
|
| 157 |
+
f"```python\ndef {func_name}({params}):\n"
|
| 158 |
+
f" \"\"\"{ex['text']}\n \"\"\"\n```\n"
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def _load_code_tasks(task, max_examples):
|
| 163 |
+
from utils.code_exec import read_problems, stream_jsonl
|
| 164 |
+
if task == "humaneval":
|
| 165 |
+
probs = _format_humaneval(read_problems(str(HERE / "JustGRPO/datasets/HumanEval.jsonl.gz")))
|
| 166 |
+
items = list(probs.items())
|
| 167 |
+
else:
|
| 168 |
+
examples = list(stream_jsonl(str(HERE / "JustGRPO/datasets/mbpp.jsonl")))
|
| 169 |
+
probs = {ex["task_id"]: {"task_id": ex["task_id"], "prompt": _format_mbpp_prompt(ex)}
|
| 170 |
+
for ex in examples[10:510]}
|
| 171 |
+
items = list(probs.items())
|
| 172 |
+
if max_examples and max_examples < len(items):
|
| 173 |
+
items = items[:max_examples]
|
| 174 |
+
return probs, items
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def eval_code(model, tokenizer, task, gen_length, steps, block_length, max_examples):
|
| 178 |
+
from utils.code_exec import write_jsonl, evaluate_functional_correctness, stream_jsonl
|
| 179 |
+
probs, items = _load_code_tasks(task, max_examples)
|
| 180 |
+
samples = []
|
| 181 |
+
t0 = time.time()
|
| 182 |
+
for tid, _ in tqdm(items, desc=f"eval {task}"):
|
| 183 |
+
prompt = probs[tid]["prompt"]
|
| 184 |
+
msgs = [[{"role": "user", "content": prompt}]]
|
| 185 |
+
prompt_text = tokenizer.apply_chat_template(msgs, add_generation_prompt=True, tokenize=False)
|
| 186 |
+
prompt_ids = tokenizer(prompt_text, return_tensors="pt")["input_ids"].to(DEVICE)
|
| 187 |
+
gen_ids = generate(model=model, prompt=prompt_ids, steps=steps, gen_length=gen_length,
|
| 188 |
+
block_length=block_length, temperature=0.0)
|
| 189 |
+
completion = tokenizer.batch_decode(gen_ids[:, prompt_ids.shape[1]:], skip_special_tokens=True)[0]
|
| 190 |
+
row = {"task_id": tid, "completion": completion}
|
| 191 |
+
if task == "mbpp":
|
| 192 |
+
row["prompt"] = prompt
|
| 193 |
+
samples.append(row)
|
| 194 |
+
|
| 195 |
+
out_dir = HERE / "code_results"
|
| 196 |
+
out_dir.mkdir(exist_ok=True)
|
| 197 |
+
merged_path = str(out_dir / f"{task}_samples.jsonl")
|
| 198 |
+
write_jsonl(merged_path, samples)
|
| 199 |
+
problem_file = str(HERE / "JustGRPO/datasets/HumanEval.jsonl.gz") if task == "humaneval" \
|
| 200 |
+
else str(HERE / "JustGRPO/datasets/mbpp_test.jsonl")
|
| 201 |
+
result = evaluate_functional_correctness(
|
| 202 |
+
input_file=merged_path, problem_file=problem_file,
|
| 203 |
+
is_mbpp=(task == "mbpp"), n_workers=8, timeout=3.0, k=(1,),
|
| 204 |
+
)
|
| 205 |
+
elapsed = time.time() - t0
|
| 206 |
+
print(f"\n{task}: {result} ({elapsed:.0f}s)")
|
| 207 |
+
return {"task": task, "metrics": result, "pass@1": result.get("pass@1"),
|
| 208 |
+
"elapsed_s": elapsed, "n_samples": len(samples)}
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
# ---------------- C3: Pass@k (AR vs AO) ----------------
|
| 212 |
+
def eval_pass_at_k(model, tokenizer, task, gen_length, steps, n_problems, k, temperature, seed=113):
|
| 213 |
+
"""Compare AR order (block_length=1) vs Arbitrary Order (block_length=gen_length)."""
|
| 214 |
+
if task == "gsm8k":
|
| 215 |
+
ds = load_dataset("gsm8k", "main", split="test")
|
| 216 |
+
problems = [ex["question"] for ex in ds]
|
| 217 |
+
answers = [ex["answer"] for ex in ds]
|
| 218 |
+
extract_gt = extract_answer_gsm8k
|
| 219 |
+
use_timeout = False
|
| 220 |
+
else:
|
| 221 |
+
ds = load_dataset("ankner/math-500", split="test")
|
| 222 |
+
instruct = r"(Please put the final answer in \boxed{} tag, i.e. $\boxed{answer here}$)"
|
| 223 |
+
problems = [ex["problem"] + instruct for ex in ds]
|
| 224 |
+
answers = [ex["solution"] for ex in ds]
|
| 225 |
+
extract_gt = lambda a: extract_answer(a)
|
| 226 |
+
use_timeout = True
|
| 227 |
+
|
| 228 |
+
rng = random.Random(seed)
|
| 229 |
+
idx = rng.sample(range(len(problems)), min(n_problems, len(problems)))
|
| 230 |
+
problems = [problems[i] for i in idx]
|
| 231 |
+
answers = [answers[i] for i in idx]
|
| 232 |
+
|
| 233 |
+
modes = {
|
| 234 |
+
"AR": {"block_length": 1, "steps": gen_length}, # strictly left-to-right (1 token/step)
|
| 235 |
+
"AO": {"block_length": gen_length, "steps": steps}, # arbitrary order (full parallel, low-conf remasking)
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
results = {}
|
| 239 |
+
per_problem = {} # mode -> list of 0/1 per problem
|
| 240 |
+
for mode_name, cfg in modes.items():
|
| 241 |
+
t0 = time.time()
|
| 242 |
+
solved_list = [] # per problem: 1 if any of k samples correct
|
| 243 |
+
n_correct_samples = 0
|
| 244 |
+
n_total_samples = 0
|
| 245 |
+
for i in range(len(problems)):
|
| 246 |
+
p = problems[i]
|
| 247 |
+
gt = extract_gt(answers[i])
|
| 248 |
+
msgs = [[{"role": "user", "content": p}]]
|
| 249 |
+
prompt_text = tokenizer.apply_chat_template(msgs, add_generation_prompt=True, tokenize=False)
|
| 250 |
+
prompt_ids = tokenizer(prompt_text, return_tensors="pt")["input_ids"].to(DEVICE)
|
| 251 |
+
# generate k samples (temperature>0 for diversity)
|
| 252 |
+
prompt_batch = prompt_ids.repeat(k, 1)
|
| 253 |
+
gen_ids = generate(model=model, prompt=prompt_batch, steps=cfg["steps"],
|
| 254 |
+
gen_length=gen_length, block_length=cfg["block_length"],
|
| 255 |
+
temperature=temperature)
|
| 256 |
+
resps = tokenizer.batch_decode(gen_ids[:, prompt_ids.shape[1]:], skip_special_tokens=True)
|
| 257 |
+
solved = False
|
| 258 |
+
for resp in resps:
|
| 259 |
+
pred = extract_answer(resp)
|
| 260 |
+
ok = math_equal(gt, pred, timeout=use_timeout)
|
| 261 |
+
n_total_samples += 1
|
| 262 |
+
if ok:
|
| 263 |
+
n_correct_samples += 1
|
| 264 |
+
solved = True
|
| 265 |
+
solved_list.append(int(solved))
|
| 266 |
+
if (i + 1) % 5 == 0:
|
| 267 |
+
print(f" [Pass@k {mode_name}] {i+1}/{len(problems)} pass@{k}={sum(solved_list)/len(solved_list)*100:.1f}% elapsed={time.time()-t0:.0f}s", flush=True)
|
| 268 |
+
pass_k_acc = sum(solved_list) / len(solved_list)
|
| 269 |
+
sample_acc = n_correct_samples / max(n_total_samples, 1)
|
| 270 |
+
elapsed = time.time() - t0
|
| 271 |
+
results[mode_name] = {
|
| 272 |
+
"pass@k": pass_k_acc, "k": k, "n_problems": len(problems),
|
| 273 |
+
"sample_accuracy": sample_acc, "n_correct_samples": n_correct_samples,
|
| 274 |
+
"n_total_samples": n_total_samples, "block_length": cfg["block_length"],
|
| 275 |
+
"steps": cfg["steps"], "temperature": temperature, "elapsed_s": elapsed,
|
| 276 |
+
"solved_list": solved_list,
|
| 277 |
+
}
|
| 278 |
+
per_problem[mode_name] = solved_list
|
| 279 |
+
print(f"\n[{mode_name}] Pass@{k} = {pass_k_acc*100:.2f}% sample_acc={sample_acc*100:.2f}% ({elapsed:.0f}s)", flush=True)
|
| 280 |
+
|
| 281 |
+
# solution coverage overlap: problems solved by AR not AO, and vice versa
|
| 282 |
+
ar_s = set(i for i, v in enumerate(per_problem["AR"]) if v)
|
| 283 |
+
ao_s = set(i for i, v in enumerate(per_problem["AO"]) if v)
|
| 284 |
+
coverage = {
|
| 285 |
+
"ar_only_count": len(ar_s - ao_s),
|
| 286 |
+
"ao_only_count": len(ao_s - ar_s),
|
| 287 |
+
"both_count": len(ar_s & ao_s),
|
| 288 |
+
"neither_count": len(set(range(len(per_problem["AR"]))) - ar_s - ao_s),
|
| 289 |
+
"ar_only_pct": len(ar_s - ao_s) / max(len(ar_s), 1) * 100,
|
| 290 |
+
"ao_only_pct": len(ao_s - ar_s) / max(len(ao_s), 1) * 100,
|
| 291 |
+
}
|
| 292 |
+
results["coverage_overlap"] = coverage
|
| 293 |
+
print(f"Coverage: AR-only={coverage['ar_only_count']} AO-only={coverage['ao_only_count']} both={coverage['both_count']} ({coverage['ar_only_pct']:.1f}% of AR solutions not in AO)", flush=True)
|
| 294 |
+
print(f"RESULT_MARKER pass_at_k: {json.dumps(results)}", flush=True)
|
| 295 |
+
return results
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def main():
|
| 299 |
+
parser = argparse.ArgumentParser()
|
| 300 |
+
parser.add_argument("--claim", type=str, required=True, choices=["c1", "c2", "c3", "all"])
|
| 301 |
+
parser.add_argument("--ckpt_path", type=str, default="nzl-thu/LLaDA-Instruct-JustGRPO-GSM8K")
|
| 302 |
+
parser.add_argument("--math500_ckpt", type=str, default="nzl-thu/LLaDA-Instruct-JustGRPO-Math500")
|
| 303 |
+
parser.add_argument("--code_ckpt", type=str, default="nzl-thu/LLaDA-Instruct-JustGRPO-Code")
|
| 304 |
+
parser.add_argument("--base_ckpt", type=str, default="GSAI-ML/LLaDA-8B-Instruct")
|
| 305 |
+
parser.add_argument("--gen_length", type=int, default=256)
|
| 306 |
+
parser.add_argument("--steps", type=int, default=256)
|
| 307 |
+
parser.add_argument("--block_length", type=int, default=32)
|
| 308 |
+
parser.add_argument("--max_examples", type=int, default=0, help="0 = full set")
|
| 309 |
+
parser.add_argument("--k", type=int, default=4, help="Pass@k samples")
|
| 310 |
+
parser.add_argument("--n_problems", type=int, default=30, help="problems for Pass@k")
|
| 311 |
+
parser.add_argument("--temperature", type=float, default=0.7, help="temp for Pass@k sampling")
|
| 312 |
+
parser.add_argument("--output", type=str, default="results")
|
| 313 |
+
args = parser.parse_args()
|
| 314 |
+
|
| 315 |
+
os.makedirs(args.output, exist_ok=True)
|
| 316 |
+
torch.manual_seed(113)
|
| 317 |
+
print(f"Device: {DEVICE} | claim={args.claim}", flush=True)
|
| 318 |
+
|
| 319 |
+
if args.claim in ("c1", "all"):
|
| 320 |
+
print("\n===== C1: GSM8K eval (JustGRPO) =====", flush=True)
|
| 321 |
+
model, tokenizer = load_model(args.ckpt_path, base_path=args.base_ckpt)
|
| 322 |
+
res = eval_math(model, tokenizer, "gsm8k", args.gen_length, args.steps,
|
| 323 |
+
args.block_length, args.max_examples or 0)
|
| 324 |
+
with open(os.path.join(args.output, "c1_gsm8k.json"), "w") as f:
|
| 325 |
+
json.dump(res, f, indent=2)
|
| 326 |
+
# also AR mode (block_length=1) on a smaller subset for C2 parallel-decoding comparison
|
| 327 |
+
if args.claim == "all" or args.claim == "c1":
|
| 328 |
+
n_ar = 100
|
| 329 |
+
print("\n===== C2a: GSM8K AR mode (block_length=1) for parallel-decoding check =====", flush=True)
|
| 330 |
+
res_ar = eval_math(model, tokenizer, "gsm8k", args.gen_length, args.gen_length,
|
| 331 |
+
1, n_ar, temperature=0.0)
|
| 332 |
+
with open(os.path.join(args.output, "c2_gsm8k_ar.json"), "w") as f:
|
| 333 |
+
json.dump(res_ar, f, indent=2)
|
| 334 |
+
del model
|
| 335 |
+
torch.cuda.empty_cache()
|
| 336 |
+
|
| 337 |
+
if args.claim in ("c2", "all"):
|
| 338 |
+
n_math = min(args.max_examples or 150, 100)
|
| 339 |
+
print(f"\n===== C2b: MATH-500 eval ({n_math} ex, JustGRPO-Math500) =====", flush=True)
|
| 340 |
+
try:
|
| 341 |
+
model, tokenizer = load_model(args.math500_ckpt, base_path=args.base_ckpt)
|
| 342 |
+
res = eval_math(model, tokenizer, "math500", args.gen_length, args.steps,
|
| 343 |
+
args.block_length, n_math)
|
| 344 |
+
with open(os.path.join(args.output, "c2_math500.json"), "w") as f:
|
| 345 |
+
json.dump(res, f, indent=2)
|
| 346 |
+
del model
|
| 347 |
+
torch.cuda.empty_cache()
|
| 348 |
+
except Exception as e:
|
| 349 |
+
print(f"MATH-500 eval failed: {e}", flush=True)
|
| 350 |
+
|
| 351 |
+
n_code = 80
|
| 352 |
+
print(f"\n===== C2c: HumanEval eval ({n_code} ex, JustGRPO-Code) =====", flush=True)
|
| 353 |
+
try:
|
| 354 |
+
model, tokenizer = load_model(args.code_ckpt, base_path=args.base_ckpt)
|
| 355 |
+
res = eval_code(model, tokenizer, "humaneval", args.gen_length, args.steps,
|
| 356 |
+
args.block_length, n_code)
|
| 357 |
+
with open(os.path.join(args.output, "c2_humaneval.json"), "w") as f:
|
| 358 |
+
json.dump(res, f, indent=2)
|
| 359 |
+
del model
|
| 360 |
+
torch.cuda.empty_cache()
|
| 361 |
+
except Exception as e:
|
| 362 |
+
print(f"HumanEval eval failed: {e}", flush=True)
|
| 363 |
+
|
| 364 |
+
if args.claim in ("c3", "all"):
|
| 365 |
+
print("\n===== C3: Pass@k AR vs AO (base LLaDA-Instruct) =====", flush=True)
|
| 366 |
+
model, tokenizer = load_model(args.base_ckpt, base_path=args.base_ckpt)
|
| 367 |
+
res = eval_pass_at_k(model, tokenizer, "gsm8k", args.gen_length, args.steps,
|
| 368 |
+
args.n_problems, args.k, args.temperature)
|
| 369 |
+
with open(os.path.join(args.output, "c3_pass_at_k.json"), "w") as f:
|
| 370 |
+
json.dump(res, f, indent=2)
|
| 371 |
+
del model
|
| 372 |
+
torch.cuda.empty_cache()
|
| 373 |
+
|
| 374 |
+
# Best-effort upload of results to HF dataset repo for persistence
|
| 375 |
+
try:
|
| 376 |
+
from huggingface_hub import HfApi
|
| 377 |
+
api = HfApi()
|
| 378 |
+
repo_id = "feliksier/justgrpo-repro-results"
|
| 379 |
+
api.create_repo(repo_id, repo_type="dataset", exist_ok=True, private=False)
|
| 380 |
+
api.upload_folder(folder_path=args.output, repo_id=repo_id, repo_type="dataset")
|
| 381 |
+
print(f"Uploaded results to hf://datasets/{repo_id}", flush=True)
|
| 382 |
+
except Exception as e:
|
| 383 |
+
print(f"Upload failed (non-fatal): {e}", flush=True)
|
| 384 |
+
print("\n===== DONE =====", flush=True)
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
if __name__ == "__main__":
|
| 388 |
+
main()
|