30b-f / reflctrl /scripts /run_reflctrl_math500_single.py
JulianHJR's picture
Add files using upload-large-folder tool
592ba2c verified
Raw
History Blame Contribute Delete
13.6 kB
#!/usr/bin/env python3
import argparse
import json
import re
import time
from pathlib import Path
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from transformers import StoppingCriteria, StoppingCriteriaList
CREST_SYSTEM = (
"Answer the following questions. You should think step-by-step "
"and put your final answer within \\boxed{}."
)
def read_jsonl(path):
rows = []
with open(path, "r", encoding="utf-8") as f:
for line in f:
if line.strip():
rows.append(json.loads(line))
return rows
def append_jsonl(path, obj):
with open(path, "a", encoding="utf-8") as f:
f.write(json.dumps(obj, ensure_ascii=False) + "\n")
def build_prompt(tokenizer, problem):
messages = [
{"role": "system", "content": CREST_SYSTEM},
{"role": "user", "content": problem},
]
if hasattr(tokenizer, "apply_chat_template") and tokenizer.chat_template is not None:
return tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
return CREST_SYSTEM + "\n\n" + problem
def first_complete_boxed_end(text):
i = text.find("\\boxed")
if i < 0:
return None
j = text.find("{", i)
if j < 0:
return None
depth = 0
for k in range(j, len(text)):
if text[k] == "{":
depth += 1
elif text[k] == "}":
depth -= 1
if depth == 0:
return k + 1
return None
def truncate_after_first_boxed(text):
end = first_complete_boxed_end(text)
return text[:end] if end is not None else text
def last_boxed(text):
if not text:
return None
i = text.rfind("\\boxed")
if i < 0:
return None
j = text.find("{", i)
if j < 0:
return None
depth = 0
for k in range(j, len(text)):
if text[k] == "{":
depth += 1
elif text[k] == "}":
depth -= 1
if depth == 0:
return text[j + 1:k].strip()
return None
class StopAfterFirstBoxedMath(StoppingCriteria):
def __init__(self, tokenizer, prompt_len):
self.tokenizer = tokenizer
self.prompt_len = prompt_len
def __call__(self, input_ids, scores, **kwargs):
gen_text = self.tokenizer.decode(input_ids[0][self.prompt_len:], skip_special_tokens=True)
return first_complete_boxed_end(gen_text) is not None
class StepwiseState:
def __init__(self, tokenizer):
self.tokenizer = tokenizer
self.active = False
self.prefill_done = False
def update_from_input_ids(self, input_ids):
if input_ids.shape[-1] > 1:
self.active = False
self.prefill_done = True
return
tail = self.tokenizer.decode(input_ids[0][-8:], skip_special_tokens=False)
self.active = tail.endswith("\n\n") or tail.endswith("\n \n")
def _norm(s):
if s is None:
return ""
t = str(s).strip()
for x in ["\\left", "\\right", "\\!", "\\,", "\\;", "$", " "]:
t = t.replace(x, "")
return t.lower()
def _as_int(s):
if s is None:
return None
t = re.sub(r"[^\d\-]", "", str(s))
try:
return int(t)
except Exception:
return None
def _as_float(s):
if s is None:
return None
try:
return float(str(s).replace(",", "").replace("$", ""))
except Exception:
return None
def _latex_to_sympy_src(s):
t = str(s)
t = t.replace("\\dfrac", "\\frac")
t = re.sub(r"\\frac\{([^{}]+)\}\{([^{}]+)\}", r"((\1)/(\2))", t)
t = re.sub(r"\\sqrt\{([^{}]+)\}", r"sqrt(\1)", t)
t = re.sub(r"\\sqrt\s*(\d+)", r"sqrt(\1)", t)
t = t.replace("\\cdot", "*").replace("\\times", "*")
t = t.replace("^", "**")
t = re.sub(r"\\pi\b", "pi", t)
t = re.sub(r"\\(left|right|!|,|;|:)", "", t)
t = re.sub(r"\\[a-zA-Z]+", "", t)
t = t.replace("{", "(").replace("}", ")").replace("$", "")
return t
def _sympy_eq(a, b):
try:
from sympy import sympify, simplify
except ImportError:
return None
try:
pa = sympify(_latex_to_sympy_src(a))
pb = sympify(_latex_to_sympy_src(b))
return bool(simplify(pa - pb) == 0)
except Exception:
return None
def is_correct(pred, gold):
if pred is None or gold is None or not str(gold).strip():
return False
p, g = str(pred).strip(), str(gold).strip()
if p == g:
return True
pi, gi = _as_int(p), _as_int(g)
if pi is not None and gi is not None and "/" not in p and "/" not in g:
return pi == gi
pf, gf = _as_float(p), _as_float(g)
if pf is not None and gf is not None and abs(pf) < 1e9 and abs(gf) < 1e9:
if abs(pf - gf) < 1e-6:
return True
sym = _sympy_eq(p, g)
if sym is not None:
return sym
np_, ng_ = _norm(p), _norm(g)
return np_ == ng_ and np_ != ""
def think_tokens_like_crest(tokenizer, cot):
seg = cot.split("</think>", 1)[0] if "</think>" in cot else cot
return len(tokenizer.encode(seg, add_special_tokens=False))
def repetition_score(text, n=40):
if not text:
return 0.0
chunks = [text[i:i+n] for i in range(0, max(0, len(text) - n + 1), n)]
if not chunks:
return 0.0
counts = {}
for c in chunks:
counts[c] = counts.get(c, 0) + 1
return max(counts.values()) / max(1, len(chunks))
def mon_total(text):
markers = [
"wait", "Wait", "check", "Check", "rethink", "Rethink",
"however", "However", "maybe", "Maybe", "alternatively",
"Actually", "actually", "Let's verify", "verify",
]
return sum(text.count(m) for m in markers)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--data", required=True)
ap.add_argument("--model-path", required=True)
ap.add_argument("--direction-path", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--lambda-weight", type=float, default=-0.48)
ap.add_argument("--layers", default="6-47")
ap.add_argument("--max-new-tokens", type=int, default=32768)
ap.add_argument("--temperature", type=float, default=0.6)
ap.add_argument("--top-p", type=float, default=0.95)
ap.add_argument("--limit", type=int, default=None)
ap.add_argument("--force", action="store_true")
ap.add_argument("--stop-after-boxed", action="store_true")
args = ap.parse_args()
torch.manual_seed(args.seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(args.seed)
out_path = Path(args.out)
out_path.parent.mkdir(parents=True, exist_ok=True)
if args.force and out_path.exists():
out_path.unlink()
rows = read_jsonl(args.data)
if args.limit is not None:
rows = rows[:args.limit]
existing = set()
if out_path.exists():
for line in out_path.read_text(encoding="utf-8").splitlines():
if line.strip():
existing.add(json.loads(line).get("_key"))
l0, l1 = [int(x) for x in args.layers.split("-")]
layers = list(range(l0, l1 + 1))
print(f"[ReflCtrl-MATH500] model_path = {args.model_path}", flush=True)
print(f"[ReflCtrl-MATH500] data = {args.data}", flush=True)
print(f"[ReflCtrl-MATH500] direction = {args.direction_path}", flush=True)
print(f"[ReflCtrl-MATH500] out = {args.out}", flush=True)
print(f"[ReflCtrl-MATH500] n = {len(rows)}", flush=True)
print(f"[ReflCtrl-MATH500] seed = {args.seed}", flush=True)
print(f"[ReflCtrl-MATH500] lambda = {args.lambda_weight}", flush=True)
print(f"[ReflCtrl-MATH500] layers = {args.layers}", flush=True)
print(f"[ReflCtrl-MATH500] max_new_tokens = {args.max_new_tokens}", flush=True)
print(f"[ReflCtrl-MATH500] temperature = {args.temperature}", flush=True)
print(f"[ReflCtrl-MATH500] top_p = {args.top_p}", flush=True)
print(f"[ReflCtrl-MATH500] stop_after_boxed = {args.stop_after_boxed}", flush=True)
print(f"[ReflCtrl-MATH500] existing records = {len(existing)}", flush=True)
tokenizer = AutoTokenizer.from_pretrained(args.model_path, trust_remote_code=True, use_fast=True)
if tokenizer.pad_token_id is None:
tokenizer.pad_token = tokenizer.eos_token
model = AutoModelForCausalLM.from_pretrained(
args.model_path,
trust_remote_code=True,
torch_dtype="auto",
device_map="auto",
)
model.eval()
ckpt = torch.load(args.direction_path, map_location="cpu")
components = ckpt["components"]
state = StepwiseState(tokenizer)
original_forward = model.forward
def wrapped_forward(*f_args, **f_kwargs):
input_ids = f_kwargs.get("input_ids", None)
if input_ids is None and len(f_args) > 0:
input_ids = f_args[0]
if input_ids is not None:
state.update_from_input_ids(input_ids)
return original_forward(*f_args, **f_kwargs)
model.forward = wrapped_forward
handles = []
def make_hook(name):
vec = components[name]["mean_diff"].float()
def hook(module, inputs, output):
if not state.active:
return output
h = output[0] if isinstance(output, tuple) else output
v = vec.to(device=h.device, dtype=h.dtype)
h2 = h.clone()
h2[:, -1, :] = h2[:, -1, :] + args.lambda_weight * v
if isinstance(output, tuple):
return (h2,) + output[1:]
return h2
return hook
for l in layers:
for suffix, module in [
("self_attn", model.model.layers[l].self_attn),
("mlp", model.model.layers[l].mlp),
]:
name = f"model.layers[{l}].{suffix}"
if name in components:
handles.append(module.register_forward_hook(make_hook(name)))
else:
print(f"[WARN] missing direction component: {name}", flush=True)
first_device = next(model.parameters()).device
try:
for i, item in enumerate(rows):
key = f"P{i}_ReflCtrl_lam{args.lambda_weight:+.2f}".replace("+", "p").replace("-", "m").replace(".", "p")
if key in existing:
print(f"[SKIP] {key}", flush=True)
continue
problem = item.get("problem") or item.get("question") or item.get("prompt")
if problem is None:
raise KeyError(f"missing problem/question/prompt at row {i}")
gt = str(item.get("answer") or item.get("gt") or item.get("label") or "").strip()
prompt = build_prompt(tokenizer, problem)
inputs = tokenizer(prompt, return_tensors="pt")
inputs = {k: v.to(first_device) for k, v in inputs.items()}
input_len = inputs["input_ids"].shape[-1]
stopping = None
if args.stop_after_boxed:
stopping = StoppingCriteriaList([StopAfterFirstBoxedMath(tokenizer, input_len)])
state.active = False
state.prefill_done = False
gen_seed = args.seed * 1000 + i
torch.manual_seed(gen_seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(gen_seed)
t0 = time.time()
with torch.no_grad():
out = model.generate(
**inputs,
max_new_tokens=args.max_new_tokens,
do_sample=True,
temperature=args.temperature,
top_p=args.top_p,
pad_token_id=tokenizer.pad_token_id,
eos_token_id=tokenizer.eos_token_id,
stopping_criteria=stopping,
)
gen_ids = out[0][input_len:]
cot = tokenizer.decode(gen_ids, skip_special_tokens=True)
if args.stop_after_boxed:
cot = truncate_after_first_boxed(cot)
pred = last_boxed(cot)
correct = is_correct(pred, gt)
ttok = think_tokens_like_crest(tokenizer, cot)
rep = repetition_score(cot)
mtot = mon_total(cot)
elapsed = time.time() - t0
has_boxed = pred is not None
collapse = (not has_boxed) or rep >= 0.5 or ttok >= args.max_new_tokens
rec = {
"_key": key,
"problem_idx": i,
"seed": args.seed,
"lambda_weight": args.lambda_weight,
"layers": args.layers,
"problem": problem,
"cot": cot,
"pred": pred,
"gt": gt,
"correct": correct,
"has_boxed": has_boxed,
"think_tokens": ttok,
"n_chars": len(cot),
"mon_total": mtot,
"repetition_score": rep,
"collapse": collapse,
"elapsed_s": elapsed,
}
append_jsonl(out_path, rec)
print(
f"P{i}_ReflCtrl_lam{args.lambda_weight:+.2f} "
f"pred={pred} gt={gt} {'OK' if correct else 'BAD'} "
f"tok={ttok} mon={mtot} rep={rep:.2f} "
f"collapse={collapse} t={elapsed:.1f}s",
flush=True,
)
finally:
for h in handles:
h.remove()
if __name__ == "__main__":
main()