Download scripts/run_reasoning_language_eval.py from oof-baroomf/mac-mini-research-log: direct link, hf CLI and curl.
- Browser
- Download file 7.84 kB
-
https://huggingface.co/datasets/oof-baroomf/mac-mini-research-log/resolve/main/scripts/run_reasoning_language_eval.py
- Command line
-
hf download hf://datasets/oof-baroomf/mac-mini-research-log/scripts/run_reasoning_language_eval.py
-
curl -L -o run_reasoning_language_eval.py https://huggingface.co/datasets/oof-baroomf/mac-mini-research-log/resolve/main/scripts/run_reasoning_language_eval.py
7.84 kB
| from __future__ import annotations | |
| import argparse | |
| import datetime as dt | |
| import json | |
| import os | |
| import random | |
| import re | |
| import time | |
| import urllib.request | |
| from pathlib import Path | |
| SYSTEM_PROMPT = ( | |
| "You are solving exact-answer reasoning problems. " | |
| "Follow the requested reasoning style exactly. " | |
| "Always end with a single final line formatted as ANSWER: <answer>." | |
| ) | |
| CONDITIONS = { | |
| "direct": ( | |
| "Solve the problem internally. " | |
| "Return only the final line. " | |
| "End with one line exactly in the form ANSWER: <answer>." | |
| ), | |
| "english": ( | |
| "Reason step by step in plain English. " | |
| "Keep the reasoning concise but explicit. " | |
| "End with one line exactly in the form ANSWER: <answer>." | |
| ), | |
| "pseudocode": ( | |
| "Reason in terse pseudocode with explicit running state updates. " | |
| "Prefer lines like `x = ...`, `total = ...`, `state -> ...`. " | |
| "End with one line exactly in the form ANSWER: <answer>." | |
| ), | |
| "lojban": ( | |
| "Reason in Lojban before giving the answer. " | |
| "End with one line exactly in the form ANSWER: <answer>." | |
| ), | |
| } | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--models", nargs="+", required=True) | |
| parser.add_argument("--conditions", nargs="+", required=True, choices=sorted(CONDITIONS)) | |
| parser.add_argument("--output-dir", required=True) | |
| parser.add_argument("--task-count", type=int, default=18) | |
| parser.add_argument("--seed", type=int, default=20260406) | |
| parser.add_argument("--lojban-pilot-count", type=int, default=0) | |
| return parser.parse_args() | |
| def make_arithmetic_task(rng: random.Random, task_id: str) -> dict[str, str]: | |
| a = rng.randint(14, 49) | |
| b = rng.randint(5, 17) | |
| c = rng.randint(3, 11) | |
| d = rng.randint(2, 9) | |
| e = rng.randint(6, 15) | |
| start = rng.randint(20, 80) | |
| answer = ((start + a + b) * c) - (d * e) | |
| prompt = ( | |
| f"Start with {start}. Add {a}. Add {b}. Multiply the result by {c}. " | |
| f"Subtract {d} times {e}. What number do you get?" | |
| ) | |
| return {"id": task_id, "kind": "arithmetic", "prompt": prompt, "answer": str(answer)} | |
| def make_state_task(rng: random.Random, task_id: str) -> dict[str, str]: | |
| prompt = ( | |
| "Run this exact program and report the final value of x - y.\n\n" | |
| f"x = {rng.randint(2, 8)}\n" | |
| f"y = {rng.randint(3, 9)}\n" | |
| f"z = {rng.randint(4, 10)}\n" | |
| ) | |
| prompt_lines = prompt.splitlines() | |
| base_x = int(prompt_lines[2].split("=")[1].strip()) | |
| base_y = int(prompt_lines[3].split("=")[1].strip()) | |
| base_z = int(prompt_lines[4].split("=")[1].strip()) | |
| x = base_x | |
| y = base_y | |
| z = base_z | |
| lines = [ | |
| f"x = x + y", | |
| f"y = y * 2", | |
| f"z = z + x - 1", | |
| f"x = x * z", | |
| f"y = y + z", | |
| ] | |
| x = x + y | |
| y = y * 2 | |
| z = z + x - 1 | |
| x = x * z | |
| y = y + z | |
| answer = x - y | |
| prompt = ( | |
| "Run this exact program and report the final value of x - y.\n\n" | |
| f"x = {base_x}\n" | |
| f"y = {base_y}\n" | |
| f"z = {base_z}\n" | |
| + "\n".join(lines) | |
| ) | |
| return {"id": task_id, "kind": "state", "prompt": prompt, "answer": str(answer)} | |
| def make_tasks(task_count: int, seed: int) -> list[dict[str, str]]: | |
| rng = random.Random(seed) | |
| tasks: list[dict[str, str]] = [] | |
| for index in range(task_count): | |
| task_id = f"task-{index + 1:02d}" | |
| if index % 2 == 0: | |
| tasks.append(make_arithmetic_task(rng, task_id)) | |
| else: | |
| tasks.append(make_state_task(rng, task_id)) | |
| return tasks | |
| def extract_answer(text: str) -> str: | |
| matches = re.findall(r"ANSWER:\s*(.+)", text) | |
| return matches[-1].strip() if matches else "" | |
| def chat_completion(model: str, prompt: str) -> dict: | |
| payload = { | |
| "model": model, | |
| "temperature": 0, | |
| "messages": [ | |
| {"role": "system", "content": SYSTEM_PROMPT}, | |
| {"role": "user", "content": prompt}, | |
| ], | |
| } | |
| body = json.dumps(payload).encode("utf-8") | |
| request = urllib.request.Request( | |
| "https://api.openai.com/v1/chat/completions", | |
| data=body, | |
| headers={ | |
| "Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}", | |
| "Content-Type": "application/json", | |
| }, | |
| method="POST", | |
| ) | |
| with urllib.request.urlopen(request) as response: | |
| return json.loads(response.read().decode("utf-8")) | |
| def main() -> None: | |
| args = parse_args() | |
| timestamp = dt.datetime.now(dt.timezone.utc).strftime("%Y%m%dT%H%M%SZ") | |
| output_dir = Path(args.output_dir) / timestamp | |
| output_dir.mkdir(parents=True, exist_ok=False) | |
| tasks = make_tasks(args.task_count, args.seed) | |
| (output_dir / "tasks.json").write_text(json.dumps(tasks, indent=2) + "\n") | |
| raw_path = output_dir / "raw.jsonl" | |
| rows: list[dict] = [] | |
| for model in args.models: | |
| for condition in args.conditions: | |
| active_tasks = tasks | |
| if condition == "lojban" and args.lojban_pilot_count: | |
| active_tasks = tasks[: args.lojban_pilot_count] | |
| for task in active_tasks: | |
| prompt = f"{CONDITIONS[condition]}\n\nProblem:\n{task['prompt']}" | |
| started_at = time.time() | |
| response = chat_completion(model, prompt) | |
| ended_at = time.time() | |
| content = response["choices"][0]["message"]["content"] | |
| prediction = extract_answer(content) | |
| row = { | |
| "model": model, | |
| "condition": condition, | |
| "task_id": task["id"], | |
| "task_kind": task["kind"], | |
| "gold_answer": task["answer"], | |
| "predicted_answer": prediction, | |
| "correct": prediction == task["answer"], | |
| "latency_s": round(ended_at - started_at, 3), | |
| "usage": response.get("usage", {}), | |
| "response_id": response.get("id", ""), | |
| "prompt": prompt, | |
| "content": content, | |
| } | |
| rows.append(row) | |
| with raw_path.open("a", encoding="utf-8") as handle: | |
| handle.write(json.dumps(row) + "\n") | |
| (output_dir / "results.json").write_text(json.dumps(rows, indent=2) + "\n") | |
| summaries: list[dict] = [] | |
| for model in args.models: | |
| for condition in args.conditions: | |
| active_rows = [row for row in rows if row["model"] == model and row["condition"] == condition] | |
| correct = sum(1 for row in active_rows if row["correct"]) | |
| total = len(active_rows) | |
| summaries.append( | |
| { | |
| "model": model, | |
| "condition": condition, | |
| "correct": correct, | |
| "total": total, | |
| "accuracy": round(correct / total, 4), | |
| } | |
| ) | |
| (output_dir / "summary.json").write_text(json.dumps(summaries, indent=2) + "\n") | |
| samples: list[str] = ["# Manual Samples", ""] | |
| for model in args.models: | |
| for condition in args.conditions: | |
| subset = [row for row in rows if row["model"] == model and row["condition"] == condition][:2] | |
| samples.append(f"## {model} / {condition}") | |
| samples.append("") | |
| for row in subset: | |
| samples.append(f"- {row['task_id']} `{row['task_kind']}` correct={row['correct']}") | |
| samples.append(f" prompt: {row['prompt']}") | |
| samples.append(f" output: {row['content']}") | |
| samples.append("") | |
| (output_dir / "samples.md").write_text("\n".join(samples) + "\n") | |
| print(output_dir) | |
| if __name__ == "__main__": | |
| main() | |