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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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
#!/usr/bin/env python3
"""
SenseMath v2 Judge Task Inference + Analysis (J1 / J2).

Supports both vLLM local models and OpenAI API.

Usage:
  # vLLM inference
  python run_judge_tasks.py --step inference --task j1 --model Qwen/Qwen3-30B-A3B-Instruct-2507 --tp 4

  # OpenAI API inference
  python run_judge_tasks.py --step inference --task j1 --api --api-model gpt-5-mini --concurrency 20

  # Run paper judge tasks at once
  python run_judge_tasks.py --step inference --task all --model Qwen/Qwen3-30B-A3B-Instruct-2507 --tp 4

  # Analyze results
  python run_judge_tasks.py --step analyze
"""

import os
import re
import json
import asyncio
import argparse
from pathlib import Path
from typing import List, Dict, Optional
from collections import defaultdict

from dataset_registry import J1_PROFILES, load_judge_dataset, validate_existing_results

SCRIPT_DIR = Path(__file__).parent
V2_DATA_DIR = SCRIPT_DIR.parent / "benchmark"
if not V2_DATA_DIR.exists():
    V2_DATA_DIR = SCRIPT_DIR.parent / "data"
V2_RESULTS_DIR = SCRIPT_DIR.parent / "results" / "paper-aligned-v1"
J1_PROFILE = "paper-filtered"


# ── Helpers ───────────────────────────────────────────────────────────────────

def safe_model_name(model: str) -> str:
    return re.sub(r"[/: ]", "_", model)


def load_json(path: Path) -> List[Dict]:
    with open(path) as f:
        return json.load(f)


def save_json(data, path: Path):
    path.parent.mkdir(parents=True, exist_ok=True)
    with open(path, "w") as f:
        json.dump(data, f, indent=2, ensure_ascii=False)


def extract_yes_no(response: str) -> str:
    """Extract YES/NO from a J1 response."""
    text = re.sub(r"<think>.*?</think>", "", response, flags=re.DOTALL).strip()
    # Look for explicit YES/NO (case-insensitive)
    m = re.search(r"\b(YES|NO)\b", text, re.IGNORECASE)
    if m:
        return m.group(1).upper()
    return ""


def extract_strategy(response: str) -> str:
    """Extract SHORTCUT/COMPUTATION from a J2 strategy response."""
    text = re.sub(r"<think>.*?</think>", "", response, flags=re.DOTALL).strip()
    m = re.search(r"\b(SHORTCUT|COMPUTATION)\b", text, re.IGNORECASE)
    if m:
        return m.group(1).upper()
    return ""


def result_path(task: str, model_name: str) -> Path:
    scope = f"j1_{J1_PROFILE}" if task == "j1" else task
    return V2_RESULTS_DIR / f"judge_{scope}_{safe_model_name(model_name)}.json"


def build_record(item: Dict, task: str, model: str, raw_response: str, token_count: int,
                 dataset: Optional[Dict] = None) -> Dict:
    """Build a result record from a judge item and its response."""
    rec = {
        "task_id": item["task_id"],
        "task_type": item["task_type"],
        "category": item["category"],
        "model": model,
        "prompt": item["prompt"],
        "raw_response": raw_response,
        "response_token_count": token_count,
    }
    if dataset is not None:
        rec["dataset"] = dataset

    # Variant metadata is present in both public judge tasks.
    if "variant" in item:
        rec["variant"] = item["variant"]

    # Ground truth field differs by task
    if task == "j1":
        rec["ground_truth"] = item["ground_truth"]
        rec["predicted"] = extract_yes_no(raw_response)
    elif task == "j2":
        rec["ground_truth"] = item["ground_truth"]
        rec["predicted"] = extract_strategy(raw_response)
        rec["is_correct"] = rec["predicted"] == rec["ground_truth"]
        if "source_condition" in item:
            rec["source_condition"] = item["source_condition"]
        if "source_description" in item:
            rec["source_description"] = item["source_description"]

    return rec


# ── vLLM inference ────────────────────────────────────────────────────────────

def run_vllm_inference(args, task: str):
    from vllm import LLM, SamplingParams
    from transformers import AutoTokenizer

    model = args.model
    model_safe = safe_model_name(model)
    V2_RESULTS_DIR.mkdir(parents=True, exist_ok=True)

    # Load dataset
    items, dataset = load_judge_dataset(V2_DATA_DIR, task, J1_PROFILE)
    print(f"Loaded {len(items)} items: {dataset['task_key']}")

    # Load existing results for resumption
    out_path = result_path(task, model)
    existing = load_json(out_path) if out_path.exists() else []
    validate_existing_results(existing, items, dataset)
    done_ids = {r["task_id"] for r in existing}

    # Filter to pending items
    pending = [it for it in items if it["task_id"] not in done_ids]
    if not pending:
        print(f"All {task.upper()} items already done for {model}.")
        return
    print(f"Pending: {len(pending)} / {len(items)}")

    # Load tokenizer for chat template
    tok = AutoTokenizer.from_pretrained(
        model, trust_remote_code=True,
        cache_dir=os.environ.get("HF_HOME"),
    )
    chat = hasattr(tok, "chat_template") and tok.chat_template
    is_thinking_model = "enable_thinking" in (tok.chat_template or "")

    def apply_template(prompt: str) -> str:
        if chat:
            messages = [{"role": "user", "content": prompt}]
            try:
                kwargs = dict(tokenize=False, add_generation_prompt=True)
                if is_thinking_model:
                    kwargs["enable_thinking"] = False
                return tok.apply_chat_template(messages, **kwargs)
            except Exception:
                pass
        return prompt

    # Build prompts
    prompts = [apply_template(it["prompt"]) for it in pending]

    # Load vLLM
    llm_kwargs = dict(
        model=model, dtype="bfloat16",
        tensor_parallel_size=args.tp,
        gpu_memory_utilization=args.gpu_mem,
        trust_remote_code=True,
        max_model_len=2048,
    )
    if os.environ.get("HF_HOME"):
        llm_kwargs["download_dir"] = os.environ["HF_HOME"]

    print("Loading vLLM model...")
    llm = LLM(**llm_kwargs)
    sp = SamplingParams(temperature=0, max_tokens=args.max_tokens, seed=42)

    print(f"Running batch inference on {len(prompts)} prompts...")
    outputs = llm.generate(prompts, sp)

    new_records = []
    for out, item in zip(outputs, pending):
        raw = out.outputs[0].text.strip()
        tok_count = len(out.outputs[0].token_ids)
        rec = build_record(item, task, model, raw, tok_count, dataset)
        new_records.append(rec)

    all_records = existing + new_records
    save_json(all_records, out_path)
    print(f"Saved {len(all_records)} records -> {out_path}")


# ── API inference ─────────────────────────────────────────────────────────────

async def call_openai(client, model: str, prompt: str, max_tokens: int,
                      semaphore: asyncio.Semaphore):
    """Make a single OpenAI chat completion call with concurrency control."""
    async with semaphore:
        try:
            kwargs = dict(
                model=model,
                messages=[{"role": "user", "content": prompt}],
                max_completion_tokens=max_tokens,
            )
            # Some models don't support temperature=0
            if "5-mini" not in model and "o1" not in model and "o3" not in model and "o4" not in model:
                kwargs["temperature"] = 0
            response = await client.chat.completions.create(**kwargs)
            text = response.choices[0].message.content or ""
            token_count = response.usage.completion_tokens if response.usage else 0
            return text.strip(), token_count
        except Exception as e:
            print(f"  API error: {e}")
            return "", 0


async def run_api_inference_async(args, task: str):
    from openai import AsyncOpenAI

    api_key = os.environ.get("OPENAI_API_KEY")
    if not api_key:
        print("Error: OPENAI_API_KEY environment variable is not set.")
        return

    model = args.api_model
    model_safe = safe_model_name(model)
    V2_RESULTS_DIR.mkdir(parents=True, exist_ok=True)

    # Load dataset
    items, dataset = load_judge_dataset(V2_DATA_DIR, task, J1_PROFILE)
    print(f"Loaded {len(items)} items: {dataset['task_key']}")

    # Load existing results for resumption
    out_path = result_path(task, model)
    existing = load_json(out_path) if out_path.exists() else []
    validate_existing_results(existing, items, dataset)
    done_ids = {r["task_id"] for r in existing}

    pending = [it for it in items if it["task_id"] not in done_ids]
    if not pending:
        print(f"All {task.upper()} items already done for {model}.")
        return
    print(f"Pending: {len(pending)} / {len(items)}")

    client = AsyncOpenAI(api_key=api_key)
    semaphore = asyncio.Semaphore(args.concurrency)

    async_tasks = [
        call_openai(client, model, it["prompt"], args.max_tokens, semaphore)
        for it in pending
    ]

    print(f"Running {len(async_tasks)} API calls with concurrency={args.concurrency}...")
    results = await asyncio.gather(*async_tasks)

    new_records = []
    for item, (response_text, token_count) in zip(pending, results):
        rec = build_record(item, task, model, response_text, token_count, dataset)
        new_records.append(rec)

    all_records = existing + new_records
    save_json(all_records, out_path)
    print(f"Saved {len(all_records)} records -> {out_path}")

    await client.close()


def run_api_inference(args, task: str):
    asyncio.run(run_api_inference_async(args, task))


# ── Inference dispatcher ──────────────────────────────────────────────────────

def step_inference(args):
    tasks = ["j1", "j2"] if args.task == "all" else [args.task]

    for task in tasks:
        print(f"\n{'='*60}")
        print(f"  Judge task: {task.upper()}")
        print(f"{'='*60}")

        if args.api:
            run_api_inference(args, task)
        else:
            run_vllm_inference(args, task)


# ── Analysis ──────────────────────────────────────────────────────────────────

def step_analyze(args):
    V2_RESULTS_DIR.mkdir(parents=True, exist_ok=True)

    # Discover all judge result files
    j1_files = sorted(V2_RESULTS_DIR.glob(f"judge_j1_{J1_PROFILE}_*.json"))
    j2_files = sorted(V2_RESULTS_DIR.glob("judge_j2_*.json"))

    if not j1_files and not j2_files:
        print("No judge result files found.")
        return

    print(f"\n{'='*80}")
    print(f"  SenseMath v2 Judge Task Analysis")
    print(f"{'='*80}")

    summary = {}
    selected = {task: load_judge_dataset(V2_DATA_DIR, task, J1_PROFILE) for task in ("j1", "j2")}

    # ── J1 Analysis (YES/NO accuracy) ────────────────────────────────────
    if j1_files:
        print(f"\n--- J1: Strategy Appropriateness (YES/NO) ---")
        print(f"  {'Model':<35} {'N':>5} {'Acc%':>7} | "
              f"{'strong':>7} {'weak':>7} {'control':>7}")
        print(f"  {'-'*80}")

        for fpath in j1_files:
            records = load_json(fpath)
            validate_existing_results(records, *selected["j1"])
            if not records:
                continue
            model = records[0]["model"]
            model_short = model.split("/")[-1][:33]

            unlabeled = sum(r.get("ground_truth") is None for r in records)
            records = [r for r in records if r.get("ground_truth") is not None]
            total = len(records)
            correct = sum(1 for r in records if r.get("predicted") == r.get("ground_truth"))
            acc = correct / total if total else 0

            # Per-variant accuracy
            variant_acc = {}
            for var in ("strong_shortcut", "weak_shortcut", "control"):
                var_recs = [r for r in records if r.get("variant") == var]
                if var_recs:
                    va = sum(1 for r in var_recs if r.get("predicted") == r.get("ground_truth")) / len(var_recs)
                    variant_acc[var] = va
                else:
                    variant_acc[var] = float("nan")

            print(f"  {model_short:<35} {total:>5} {acc:>6.1%} | "
                  f"{variant_acc.get('strong_shortcut', 0):>6.1%} "
                  f"{variant_acc.get('weak_shortcut', 0):>6.1%} "
                  f"{variant_acc.get('control', 0):>6.1%}")

            # Per-category breakdown
            categories = sorted(set(r["category"] for r in records))
            cat_detail = {}
            for cat in categories:
                cat_recs = [r for r in records if r["category"] == cat]
                cat_acc = sum(1 for r in cat_recs if r.get("predicted") == r.get("ground_truth")) / len(cat_recs)
                cat_detail[cat] = round(cat_acc, 4)

            summary[f"J1|{safe_model_name(model)}"] = {
                "model": model, "task": "J1", "n": total, "unlabeled": unlabeled,
                "accuracy": round(acc, 4),
                "variant_accuracy": {k: round(v, 4) for k, v in variant_acc.items()},
                "category_accuracy": cat_detail,
            }

        # Detailed per-category table
        print(f"\n  J1 per-category breakdown:")
        for fpath in j1_files:
            records = [r for r in load_json(fpath) if r.get("ground_truth") is not None]
            if not records:
                continue
            model_short = records[0]["model"].split("/")[-1][:25]
            categories = sorted(set(r["category"] for r in records))
            print(f"    {model_short}:")
            for cat in categories:
                cat_recs = [r for r in records if r["category"] == cat]
                cat_acc = sum(1 for r in cat_recs if r.get("predicted") == r.get("ground_truth")) / len(cat_recs)
                print(f"      {cat:<30} {len(cat_recs):>4} items  {cat_acc:>6.1%}")

    # ── J2 Analysis (strategy identification accuracy) ───────────────────
    if j2_files:
        print(f"\n--- J2: Strategy Identification (SHORTCUT/COMPUTATION) ---")
        print(f"  {'Model':<35} {'N':>5} {'Acc%':>7} | "
              f"{'SHORT':>7} {'COMP':>7}")
        print(f"  {'-'*70}")

        for fpath in j2_files:
            records = load_json(fpath)
            validate_existing_results(records, *selected["j2"])
            if not records:
                continue
            model = records[0]["model"]
            model_short = model.split("/")[-1][:33]
            aligned = [r for r in records if "ground_truth" in r]
            n = len(aligned)
            correct = sum(1 for r in aligned if r.get("predicted") == r.get("ground_truth"))
            acc = correct / n if n else 0

            class_acc = {}
            for label in ("SHORTCUT", "COMPUTATION"):
                label_recs = [r for r in aligned if r.get("ground_truth") == label]
                class_acc[label] = (
                    sum(1 for r in label_recs if r.get("predicted") == label) / len(label_recs)
                    if label_recs else float("nan")
                )

            print(f"  {model_short:<35} {n:>5} {acc:>6.1%} | "
                  f"{class_acc.get('SHORTCUT', 0):>6.1%} "
                  f"{class_acc.get('COMPUTATION', 0):>6.1%}")

            summary[f"J2|{safe_model_name(model)}"] = {
                "model": model, "task": "J2", "n": n,
                "accuracy": round(acc, 4),
                "strategy_accuracy": {
                    "SHORTCUT": round(class_acc.get("SHORTCUT", 0), 4),
                    "COMPUTATION": round(class_acc.get("COMPUTATION", 0), 4),
                },
            }

    # Save summary
    out_path = V2_RESULTS_DIR / f"judge_analysis_{J1_PROFILE}.json"
    save_json(summary, out_path)
    print(f"\nSaved analysis -> {out_path}")


# ── Main ──────────────────────────────────────────────────────────────────────

def main():
    global V2_DATA_DIR, V2_RESULTS_DIR, J1_PROFILE
    parser = argparse.ArgumentParser(
        description="SenseMath v2 Judge Task Inference + Analysis (J1/J2)")

    parser.add_argument("--step", required=True,
                        choices=["inference", "analyze", "validate"])
    parser.add_argument("--task", default="all",
                        choices=["j1", "j2", "all"],
                        help="Which judge task to run. all runs paper J1/J2.")
    parser.add_argument("--data-dir", type=Path, default=V2_DATA_DIR,
                        help="Directory containing the shared dataset manifest (benchmark/ or HF data/).")
    parser.add_argument("--j1-profile", choices=list(J1_PROFILES), default="paper-filtered",
                        help="J1 full 300-item set or paper-filtered 261-item subset; never pooled.")

    # vLLM options
    parser.add_argument("--model", default="Qwen/Qwen3-30B-A3B-Instruct-2507",
                        help="HuggingFace model for vLLM")
    parser.add_argument("--tp", type=int, default=1,
                        help="Tensor parallel size for vLLM")
    parser.add_argument("--gpu-mem", type=float, default=0.90,
                        help="GPU memory utilization for vLLM")

    # API options
    parser.add_argument("--api", action="store_true",
                        help="Use OpenAI API instead of vLLM")
    parser.add_argument("--api-model", default="gpt-5-mini",
                        help="OpenAI model name (used with --api)")
    parser.add_argument("--concurrency", type=int, default=20,
                        help="Max concurrent API requests")

    # Shared
    parser.add_argument("--max-tokens", type=int, default=512,
                        help="Max tokens for generation")

    args = parser.parse_args()
    V2_DATA_DIR = args.data_dir
    J1_PROFILE = args.j1_profile
    manifest = load_json(V2_DATA_DIR / "manifest.json")
    V2_RESULTS_DIR = SCRIPT_DIR.parent / "results" / manifest["release_id"]

    if args.step == "validate":
        for task in (["j1", "j2"] if args.task == "all" else [args.task]):
            _, metadata = load_judge_dataset(V2_DATA_DIR, task, J1_PROFILE)
            print(json.dumps(metadata, sort_keys=True))
    elif args.step == "inference":
        step_inference(args)
    elif args.step == "analyze":
        step_analyze(args)


if __name__ == "__main__":
    main()