File size: 8,399 Bytes
6d1bbc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
#!/usr/bin/env python3
"""GE LLM benchmark inference harness.

Mirrors scripts_ppi/run_ppi_llm_benchmark.py for the GE domain.
Reuses LLMClient from DTI. Uses GE-specific prompts and evaluation.

Usage:
  python scripts_depmap/run_ge_llm_benchmark.py --task ge-l1 --model gemini-2.0-flash \
      --provider gemini --config zero-shot

  python scripts_depmap/run_ge_llm_benchmark.py --task ge-l4 --model gpt-4o-mini \
      --provider openai --config 3-shot --fewshot-set 1

Output:
  results/ge_llm/{task}_{model}_{config}_fs{set}/
      predictions.jsonl, results.json, run_meta.json
"""

import argparse
import json
import time
from datetime import datetime, timezone
from pathlib import Path

import numpy as np

from negbiodb.llm_client import LLMClient
from negbiodb_depmap.llm_eval import compute_all_ge_llm_metrics
from negbiodb_depmap.llm_prompts import format_ge_prompt

PROJECT_ROOT = Path(__file__).resolve().parent.parent
DATA_DIR = PROJECT_ROOT / "exports" / "ge_llm"
OUTPUT_BASE = PROJECT_ROOT / "results" / "ge_llm"

TASK_FILES = {
    "ge-l1": "ge_l1_dataset.jsonl",
    "ge-l2": "ge_l2_dataset.jsonl",
    "ge-l3": "ge_l3_dataset.jsonl",
    "ge-l4": "ge_l4_dataset.jsonl",
}

TASK_MAX_TOKENS = {
    "ge-l1": 256,
    "ge-l2": 1024,
    "ge-l3": 2048,
    "ge-l4": 256,
}


def load_dataset(task: str, data_dir: Path) -> list[dict]:
    """Load dataset JSONL file."""
    path = data_dir / TASK_FILES[task]
    records = []
    with open(path) as f:
        for line in f:
            records.append(json.loads(line))
    return records


def get_fewshot_examples(
    records: list[dict], fewshot_set: int, n_per_class: int = 3
) -> list[dict]:
    """Select few-shot examples from fewshot split.

    3 independent sets (fewshot_set=0,1,2) for variance.
    """
    import random

    fewshot = [r for r in records if r.get("split") == "fewshot"]
    if not fewshot:
        return []

    by_class = {}
    for r in fewshot:
        cls = r.get("gold_answer", "default")
        by_class.setdefault(cls, []).append(r)

    rng = random.Random(42 + fewshot_set)
    examples = []
    for cls, cls_records in by_class.items():
        pool = list(cls_records)
        rng.shuffle(pool)
        start = fewshot_set * n_per_class
        end = start + n_per_class
        examples.extend(pool[start:end])

    rng.shuffle(examples)
    return examples


def sanitize_model_name(model: str) -> str:
    """Convert model path/name to filesystem-safe string."""
    return model.split("/")[-1].replace(".", "-").lower()


def _json_safe(obj):
    """Convert numpy/pandas types for JSON serialization."""
    if isinstance(obj, (np.integer,)):
        return int(obj)
    if isinstance(obj, (np.floating,)):
        return float(obj)
    if isinstance(obj, np.ndarray):
        return obj.tolist()
    raise TypeError(f"Object of type {type(obj)} is not JSON serializable")


def main():
    parser = argparse.ArgumentParser(description="Run GE LLM benchmark")
    parser.add_argument("--task", required=True, choices=list(TASK_FILES.keys()))
    parser.add_argument("--model", required=True, help="Model name or path")
    parser.add_argument(
        "--provider", required=True, choices=["vllm", "gemini", "openai", "anthropic"]
    )
    parser.add_argument(
        "--config", default="zero-shot", choices=["zero-shot", "3-shot"]
    )
    parser.add_argument("--fewshot-set", type=int, default=0, choices=[0, 1, 2])
    parser.add_argument("--api-base", default=None)
    parser.add_argument("--api-key", default=None)
    parser.add_argument("--data-dir", type=Path, default=DATA_DIR)
    parser.add_argument("--output-dir", type=Path, default=OUTPUT_BASE)
    parser.add_argument("--temperature", type=float, default=0.0)
    parser.add_argument("--max-tokens", type=int, default=None)
    args = parser.parse_args()

    if args.max_tokens is None:
        args.max_tokens = TASK_MAX_TOKENS.get(args.task, 1024)

    model_name = sanitize_model_name(args.model)
    run_name = f"{args.task}_{model_name}_{args.config}_fs{args.fewshot_set}"
    run_dir = args.output_dir / run_name
    run_dir.mkdir(parents=True, exist_ok=True)

    print(f"=== GE LLM Benchmark: {run_name} ===")
    print(f"Task: {args.task}, Model: {args.model} ({args.provider})")
    print(f"Config: {args.config}, fewshot_set={args.fewshot_set}")

    # Load data
    print("\nLoading dataset...")
    records = load_dataset(args.task, args.data_dir)
    test_records = [r for r in records if r.get("split") == "test"]
    print(f"  Total: {len(records)}, Test: {len(test_records)}")

    fewshot_examples = None
    if args.config == "3-shot":
        fewshot_examples = get_fewshot_examples(records, args.fewshot_set)
        print(f"  Few-shot examples: {len(fewshot_examples)}")

    # Init client
    print("\nInitializing LLM client...")
    client = LLMClient(
        provider=args.provider,
        model=args.model,
        api_base=args.api_base,
        api_key=args.api_key,
        temperature=args.temperature,
        max_tokens=args.max_tokens,
    )

    # Resume support
    pred_path = run_dir / "predictions.jsonl"
    predictions = []
    completed_ids = set()

    if pred_path.exists():
        with open(pred_path) as f:
            for line in f:
                rec = json.loads(line)
                completed_ids.add(rec["question_id"])
                predictions.append(rec["prediction"])
        if completed_ids:
            print(f"\nResuming: {len(completed_ids)} predictions already complete")

    remaining = [
        (i, r) for i, r in enumerate(test_records)
        if r.get("question_id", f"Q{i}") not in completed_ids
    ]

    print(f"\nRunning inference: {len(remaining)} remaining of {len(test_records)} total...")
    start_time = time.time()

    with open(pred_path, "a") as f:
        for j, (i, record) in enumerate(remaining):
            system, user = format_ge_prompt(
                args.task, record, args.config, fewshot_examples
            )
            try:
                response = client.generate(user, system)
            except Exception as e:
                response = f"ERROR: {e}"
                print(f"  Error on example {i}: {e}")

            predictions.append(response)

            pred_record = {
                "question_id": record.get("question_id", f"Q{i}"),
                "prediction": response,
                "gold_answer": record.get("gold_answer"),
            }
            f.write(json.dumps(pred_record, ensure_ascii=False) + "\n")
            f.flush()

            done = len(completed_ids) + j + 1
            if done % 50 == 0:
                elapsed = time.time() - start_time
                rate = (j + 1) / elapsed * 60
                print(f"  Progress: {done}/{len(test_records)} ({rate:.0f}/min)")

    elapsed = time.time() - start_time
    print(f"\nInference complete: {elapsed:.0f}s")

    # Evaluate
    print("\nEvaluating...")
    metrics = compute_all_ge_llm_metrics(args.task, predictions, test_records)

    results_path = run_dir / "results.json"
    with open(results_path, "w") as f:
        json.dump(metrics, f, indent=2, default=_json_safe)

    print("\n=== Results ===")
    for key, val in metrics.items():
        if isinstance(val, float):
            print(f"  {key}: {val:.4f}")
        elif isinstance(val, dict) and "mean" in val:
            print(f"  {key}: {val['mean']:.4f} +/- {val.get('std', 0):.4f}")
        else:
            print(f"  {key}: {val}")

    if args.task == "ge-l3":
        print(
            "\nNOTE: L3 results.json contains placeholder scores (n_parsed=0). "
            "Run scripts_depmap/run_ge_l3_judge.py to obtain real judge scores."
        )

    # Save metadata
    meta = {
        "task": args.task,
        "model": args.model,
        "provider": args.provider,
        "config": args.config,
        "fewshot_set": args.fewshot_set,
        "temperature": args.temperature,
        "max_tokens": args.max_tokens,
        "n_test": len(test_records),
        "n_predictions": len(predictions),
        "elapsed_seconds": elapsed,
        "timestamp": datetime.now(timezone.utc).isoformat(),
        "run_name": run_name,
    }
    meta_path = run_dir / "run_meta.json"
    with open(meta_path, "w") as f:
        json.dump(meta, f, indent=2)

    print(f"\nResults saved to {run_dir}/")


if __name__ == "__main__":
    main()