File size: 5,456 Bytes
209c437
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import argparse
import concurrent.futures
import json
import os
import random
import time
import urllib.request
from pathlib import Path

MODEL = "qwen/qwen3.5-9b"


def audit_batch(rows: list[dict]) -> list[bool]:
    pairs = [{"original": row["original_request"], "paraphrase": row["request"]} for row in rows]
    payload = {
        "model": MODEL,
        "messages": [
            {
                "role": "system",
                "content": (
                    "You audit technical paraphrases. Return only valid JSON. Mark equivalence true "
                    "only when both requests describe exactly the same text-processing operation, "
                    "including field positions and names, literal values, inclusion and exclusion, "
                    "input separators, output formatting, ordering, and tie-breaking. Wording may differ. "
                    "If either request adds, removes, or changes a constraint, mark false."
                ),
            },
            {
                "role": "user",
                "content": "Return {\"equivalent\": [true or false, ...]} with one boolean per pair.\n"
                + json.dumps(pairs, ensure_ascii=False),
            },
        ],
        "response_format": {"type": "json_object"},
        "temperature": 0,
        "max_tokens": 2000,
        "reasoning": {"enabled": False},
    }
    request = urllib.request.Request(
        os.environ["OPENROUTER_BASE_URL"].rstrip("/") + "/chat/completions",
        data=json.dumps(payload).encode("utf-8"),
        headers={
            "Authorization": "Bearer " + os.environ["OPENROUTER_API_KEY"],
            "Content-Type": "application/json",
        },
    )
    for attempt in range(6):
        try:
            with urllib.request.urlopen(request, timeout=120) as response:
                data = json.load(response)
            result = json.loads(data["choices"][0]["message"]["content"])["equivalent"]
            if not isinstance(result, list) or len(result) != len(rows) or not all(isinstance(value, bool) for value in result):
                raise ValueError("Invalid equivalence response")
            return result
        except Exception:
            if attempt == 5:
                raise
            time.sleep(min(30, 2 ** attempt))
    raise AssertionError("unreachable")


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("data", type=Path)
    parser.add_argument("output", type=Path)
    parser.add_argument("--rows", type=int, default=500)
    parser.add_argument("--batch-size", type=int, default=10)
    parser.add_argument("--workers", type=int, default=8)
    parser.add_argument("--seed", type=int, default=20261128)
    args = parser.parse_args()
    all_rows = [json.loads(line) for line in args.data.open(encoding="utf-8")]
    originals = {row["id"]: row for row in all_rows if not row.get("paraphrase_of")}
    candidates = [row for row in all_rows if row["source"] == "openrouter-paraphrase"]
    random.Random(args.seed).shuffle(candidates)
    selected = candidates[: args.rows]
    for row in selected:
        row["original_request"] = originals[row["paraphrase_of"]]["request"]
    existing = {}
    if args.output.exists():
        for line in args.output.open(encoding="utf-8"):
            row = json.loads(line)
            existing[row["id"]] = row
    pending = [row for row in selected if row["id"] not in existing]
    batches = [pending[index:index + args.batch_size] for index in range(0, len(pending), args.batch_size)]
    failures = 0
    completed = len(selected) - len(pending)
    with concurrent.futures.ThreadPoolExecutor(max_workers=args.workers) as executor:
        futures = {executor.submit(audit_batch, batch): batch for batch in batches}
        for future in concurrent.futures.as_completed(futures):
            batch = futures[future]
            try:
                verdicts = future.result()
            except Exception as error:
                failures += len(batch)
                print(f"Audit batch failed; rerun to resume: {error}", flush=True)
                continue
            with args.output.open("a", encoding="utf-8") as handle:
                for row, equivalent in zip(batch, verdicts):
                    handle.write(json.dumps({
                        "id": row["id"], "original": row["original_request"],
                        "paraphrase": row["request"], "equivalent": equivalent,
                    }, ensure_ascii=False, separators=(",", ":")) + "\n")
            completed += len(batch)
            print(f"audited {completed}/{len(selected)}", flush=True)
    results = list(existing.values())
    if args.output.exists():
        results = [json.loads(line) for line in args.output.open(encoding="utf-8")]
    results.sort(key=lambda row: row["id"])
    summary = {
        "model": MODEL, "seed": args.seed, "rows": len(results), "requested": len(selected),
        "missing": len(selected) - len(results), "equivalent": sum(row["equivalent"] for row in results),
        "disputed": sum(not row["equivalent"] for row in results),
        "audit_file": str(args.output),
    }
    args.output.with_suffix(".summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
    print(json.dumps(summary, indent=2))
    if failures or len(results) != len(selected):
        raise SystemExit(1)


if __name__ == "__main__":
    main()