Repository navigation
Expand file tree
/
Copy pathevaluate.py
More file actions
274 lines (237 loc) · 11.5 KB
/
Copy pathevaluate.py
File metadata and controls
274 lines (237 loc) · 11.5 KB
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
#!/usr/bin/env python3
"""Evaluate model outputs against a benchmark and write per-sample results."""
import argparse
import asyncio
import json
import math
import os
import re
import shlex
import sys
import time
from pathlib import Path
import yaml
from tqdm import tqdm
from metrics import MetricsEngine
from categories import subject_consistency_applicable
REQUIRED_API_ENV = ("INTREAL_API_MODEL", "INTREAL_API_BASE_URL", "INTREAL_API_KEY")
OPTIONAL_EXPERT_ENV = ("INTREAL_RALI_PATH", "INTREAL_RALI_DEVICE", "INTREAL_DINO_PATH", "INTREAL_DINO_DEVICE")
METRIC_NAMES = (
"text_richness", "text_logicality", "image_aesthetic", "image_diversity",
"quantity_compliance", "context_fidelity", "subject_consistency",
)
def incomplete_metrics(metrics, benchmark_item, enabled):
"""Return enabled metrics without a finite score, except inapplicable SC."""
if not isinstance(metrics, dict):
metrics = {}
missing = []
for name in METRIC_NAMES:
if not enabled.get(name, True):
continue
if name == "subject_consistency" and not subject_consistency_applicable(benchmark_item):
continue
value = metrics.get(name)
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
missing.append(name)
return missing
def ensure_api_environment():
"""Fill missing API settings from the adjacent .env, preserving shell values."""
missing = [name for name in (*REQUIRED_API_ENV, *OPTIONAL_EXPERT_ENV) if not os.environ.get(name)]
if not missing:
return
env_path = Path(__file__).resolve().parent / ".env"
if env_path.is_file():
try:
for line_number, line in enumerate(env_path.read_text(encoding="utf-8").splitlines(), 1):
line = line.strip()
if not line or line.startswith("#"):
continue
if line.startswith("export "):
line = line[len("export "):].lstrip()
name, separator, raw_value = line.partition("=")
name = name.strip()
if not separator or name not in missing:
continue
try:
parts = shlex.split(raw_value, comments=True, posix=True)
except ValueError:
raise ValueError(f"Invalid quoting in {env_path} at line {line_number}") from None
if len(parts) > 1:
raise ValueError(f"Quote values containing spaces in {env_path} at line {line_number}")
value = parts[0] if parts else ""
if value:
os.environ[name] = value
except (OSError, ValueError) as exc:
print(f"[FATAL] Cannot load API environment: {exc}", file=sys.stderr)
raise SystemExit(1) from None
missing = [name for name in REQUIRED_API_ENV if not os.environ.get(name)]
if missing:
print(
f"[FATAL] Required environment variables are missing or empty: {', '.join(missing)}. "
f"Export them in your shell or set them in {env_path}.",
file=sys.stderr,
)
raise SystemExit(1)
def load_jsonl(path: Path):
with open(path, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if line:
yield json.loads(line)
async def evaluate_sample(engine, bench_item, out_item, tf_item, pbar, start_time,
total_ref, semaphore, fout, write_lock,
is_real_mode=False):
async with semaphore:
t0 = time.time()
sample_id = bench_item.get("id", "?")
metrics = await engine.compute_all(bench_item, out_item, tf_item=tf_item)
if is_real_mode:
metrics["text_richness"] = 1.0
missing = incomplete_metrics(metrics, bench_item, engine.metrics_config.get("enabled", {}))
if missing:
print(f"[WARN] id={sample_id} incomplete metrics: {', '.join(missing)}; "
"not written, will retry on the next run.", file=sys.stderr)
pbar.update(1)
return
result_item = dict(out_item)
result_item["response_sf"] = result_item.pop("response", [])
result_item["metrics"] = metrics
if tf_item is not None:
result_item["response_tf"] = tf_item.get("response", [])
line = json.dumps(result_item, ensure_ascii=False) + "\n"
async with write_lock:
loop = asyncio.get_running_loop()
await loop.run_in_executor(None, fout.write, line)
await loop.run_in_executor(None, fout.flush)
total_ref[0] += 1
elapsed = time.time() - t0
avg_time = (time.time() - start_time) / total_ref[0]
pbar.set_postfix(avg=f"{avg_time:.2f}s/sample", last=f"{elapsed:.2f}s", id=sample_id)
pbar.update(1)
async def main_async(args):
ensure_api_environment()
config_dir = Path(args.config_dir)
output_dir = Path(args.output_dir)
result_dir = Path(args.result_dir)
with open(config_dir / "experts.yaml", "r", encoding="utf-8") as f:
experts_config = yaml.safe_load(f)
with open(config_dir / "metrics.yaml", "r", encoding="utf-8") as f:
metrics_config = yaml.safe_load(f)
with open(config_dir / "prompts.yaml", "r", encoding="utf-8") as f:
prompts_config = yaml.safe_load(f)
for expert in experts_config.get("local", {}).values():
for key in ("path", "cuda"):
value = expert.get(key)
if isinstance(value, str):
expert[key] = re.sub(
r"\$\{([A-Z_][A-Z_0-9]*):-([^}]*)\}",
lambda match: os.environ.get(match[1]) or match[2], value,
)
benchmark_arg = Path(args.benchmark)
benchmark_path = (benchmark_arg if benchmark_arg.suffix == ".jsonl"
else Path("benchmark") / f"{args.benchmark}.jsonl")
args.benchmark = benchmark_path.stem
model_output_path = output_dir / args.model / f"{args.benchmark}.jsonl"
result_path = result_dir / args.model / f"{args.benchmark}.jsonl"
if not benchmark_path.exists():
print(f"[FATAL] Benchmark not found: {benchmark_path}", file=sys.stderr)
raise SystemExit(1)
is_real_mode = args.model == "real"
if is_real_mode and metrics_config.get("enabled", {}).get("text_richness", False):
metrics_config["enabled"]["text_richness"] = False
print("[INFO] real mode: text_richness auto-disabled to save API calls.", file=sys.stderr)
if not is_real_mode and not model_output_path.exists():
print(f"[FATAL] Model output not found: {model_output_path}", file=sys.stderr)
raise SystemExit(1)
result_path.parent.mkdir(parents=True, exist_ok=True)
engine = MetricsEngine(experts_config, metrics_config, prompts_config)
print("[INFO] Pre-loading local expert models...", file=sys.stderr)
enabled = metrics_config.get("enabled", {})
if enabled.get("image_diversity", True) or enabled.get("subject_consistency", True):
engine.get_dinov3()
if enabled.get("image_aesthetic", True):
engine.get_rali_scorer()
print("[INFO] Models loaded.", file=sys.stderr)
bench_items = list(load_jsonl(benchmark_path))
if is_real_mode:
out_items = [{"model": "real", "eval_set": args.benchmark,
"eval_set_id": b["id"], "response": b.get("golden_result", [])}
for b in bench_items]
tf_by_id = {}
else:
raw_items = list(load_jsonl(model_output_path))
has_tf = "response_tf" in raw_items[0] if raw_items else False
if has_tf:
tf_by_id = {}
out_items = []
for item in raw_items:
out_items.append({"model": item["model"], "eval_set": item["eval_set"],
"eval_set_id": item["eval_set_id"],
"response": item["response_sf"]})
tf_by_id[item["eval_set_id"]] = {"response": item["response_tf"]}
else:
out_items = raw_items
tf_by_id = {}
bench_by_id = {b["id"]: b for b in bench_items}
out_by_id = {o["eval_set_id"]: o for o in out_items}
common_ids = sorted(set(bench_by_id) & set(out_by_id))
missing_in_output = sorted(set(bench_by_id) - set(out_by_id))
missing_in_benchmark = sorted(set(out_by_id) - set(bench_by_id))
if missing_in_output:
print(f"[WARN] {len(missing_in_output)} benchmark samples missing in output: {missing_in_output[:20]}", file=sys.stderr)
if missing_in_benchmark:
print(f"[WARN] {len(missing_in_benchmark)} output samples missing in benchmark: {missing_in_benchmark[:20]}", file=sys.stderr)
if not common_ids:
print("[FATAL] No matching samples found between benchmark and output.", file=sys.stderr)
raise SystemExit(2)
already_done = set()
if result_path.exists():
try:
for line in result_path.read_text(encoding="utf-8").splitlines():
if line.strip():
item = json.loads(line)
sample_id = item["eval_set_id"]
if sample_id in bench_by_id and not incomplete_metrics(
item.get("metrics"), bench_by_id[sample_id], enabled
):
already_done.add(sample_id)
except Exception:
pass
if already_done:
common_ids = [i for i in common_ids if i not in already_done]
print(f"[INFO] Resume mode: {len(already_done)} samples already done, {len(common_ids)} remaining.", file=sys.stderr)
if not common_ids:
if set(bench_by_id) - already_done:
raise SystemExit(2)
print("[DONE] All samples already evaluated. Nothing to do.", file=sys.stderr)
return
print(f"[INFO] Evaluating {len(common_ids)} samples. Results: {result_path}", file=sys.stderr)
start_time = time.time()
total_ref = [0]
semaphore = asyncio.Semaphore(args.concurrency)
pbar = tqdm(total=len(common_ids), desc="Evaluating", unit="sample", ncols=100)
with open(result_path, "a", encoding="utf-8") as fout:
write_lock = asyncio.Lock()
tasks = [evaluate_sample(engine, bench_by_id[i], out_by_id[i], tf_by_id.get(i),
pbar, start_time, total_ref, semaphore, fout, write_lock,
is_real_mode)
for i in common_ids]
await asyncio.gather(*tasks)
pbar.close()
avg_time = (time.time() - start_time) / len(common_ids)
print(f"[DONE] Evaluated {len(common_ids)} samples, recorded {total_ref[0]}. Avg {avg_time:.2f}s/sample. Results written to {result_path}", file=sys.stderr)
if missing_in_output or total_ref[0] != len(common_ids):
raise SystemExit(2)
def main():
parser = argparse.ArgumentParser(description="IntReal model evaluation")
parser.add_argument("--model", required=True, help="Model name (must match outputs/ dir)")
parser.add_argument("--benchmark", default="IntReal", help="Benchmark name or JSONL path (default: IntReal)")
parser.add_argument("--config-dir", default="config", help="Path to config directory")
parser.add_argument("--output-dir", default="outputs", help="Path to output directory")
parser.add_argument("--result-dir", default="results", help="Path to result directory")
parser.add_argument("--concurrency", type=int, default=20,
help="Evaluation concurrency for LLM API calls")
args = parser.parse_args()
asyncio.run(main_async(args))
if __name__ == "__main__":
main()