File size: 7,843 Bytes
43f379c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
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()