TaobaoTmall-AlgorithmProducts commited on
Commit
0e38484
·
verified ·
1 Parent(s): 1d3b260

Upload bench_eval_code/eval_intelligent.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. bench_eval_code/eval_intelligent.py +482 -0
bench_eval_code/eval_intelligent.py ADDED
@@ -0,0 +1,482 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ CPI-Bench: Intelligent benchmark evaluation script (open-source version).
3
+
4
+ Evaluates image-editing expert-domain reasoning results (with reference image(s))
5
+ using a 3-dimension weighted score:
6
+
7
+ 1. Knowledge Reasoning (fuses `rationale` as reference material) — 45%
8
+ 2. Visual Quality — 30%
9
+ 3. Input Consistency — 25%
10
+ (degrades to Knowledge 60% + Visual 40% if the sample has no reference image)
11
+
12
+ Knowledge score <= 2 -> final weighted score is multiplied by 0.6
13
+ (penalty for factual/knowledge errors).
14
+
15
+ Dataset format (CPI_intelligent_benchmark-*.parquet):
16
+ - id : str
17
+ - expert_domain : str (format: "<domain>-<subtask>")
18
+ - a_to_b_instructions : str (Chinese instruction)
19
+ - a_to_b_instructions_eng : str (English instruction)
20
+ - rationale : str (may be empty)
21
+ - target_resolution : str
22
+ - source : List[PIL.Image] (one or more reference images)
23
+
24
+ Result JSONL format:
25
+ {"sample_index": 0, "result": "/path/to/result_0.png"}
26
+
27
+ Output:
28
+ <output_dir>/cases.jsonl
29
+ <output_dir>/summary.json
30
+ - overall_avg_score / by_task_type / by_dimension : sample-weighted (micro) averages
31
+ - hierarchy : re-aggregated by (domain, subtask)
32
+ using each sample's own fields
33
+
34
+ Usage:
35
+ python eval_intelligent.py \
36
+ --dataset_path "/path/to/CPI_intelligent_benchmark-*.parquet" \
37
+ --result_jsonl /path/to/my_results.jsonl \
38
+ --prompts_json prompts/intelligent_prompts.json \
39
+ --output_dir eval_output/my_model_intelligent \
40
+ --api_key YOUR_KEY \
41
+ --lang eng \
42
+ --workers 8
43
+ """
44
+
45
+ import argparse
46
+ import json
47
+ import os
48
+ import re
49
+ from collections import defaultdict
50
+ from concurrent.futures import ThreadPoolExecutor, as_completed
51
+
52
+ import numpy as np
53
+ from datasets import load_dataset
54
+ from tqdm import tqdm
55
+
56
+ from bench_utils import ApiKeyPool, call_vlm_with_retries, load_local_image, pil_to_base64
57
+
58
+ DEFAULT_MODEL = "gemini-3-flash-preview"
59
+ DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta/openai/"
60
+
61
+ NO_RATIONALE_PLACEHOLDER = "(No reference rationale provided for this sample.)"
62
+
63
+ INSTRUCTION_FIELD = "a_to_b_instructions"
64
+ INSTRUCTION_FIELD_ENG = "a_to_b_instructions_eng"
65
+
66
+
67
+ # ---------------------------------------------------------------------------
68
+ # Prompts
69
+ # ---------------------------------------------------------------------------
70
+
71
+ def load_prompts(path: str) -> dict:
72
+ with open(path, "r", encoding="utf-8") as f:
73
+ cfg = json.load(f)
74
+ for key in ("dimensions", "task_focus"):
75
+ if key not in cfg:
76
+ raise KeyError(f"prompts.json missing key: '{key}'")
77
+ for dim in ("knowledge_reasoning", "visual_quality", "input_consistency"):
78
+ if dim not in cfg["dimensions"]:
79
+ raise KeyError(f"prompts.json 'dimensions' missing: '{dim}'")
80
+ return cfg
81
+
82
+
83
+ def get_task_focus(cfg: dict, task: str) -> str:
84
+ return cfg["task_focus"].get(
85
+ task,
86
+ cfg.get("generic_focus", "Evaluate based on general domain knowledge accuracy."),
87
+ )
88
+
89
+
90
+ # ---------------------------------------------------------------------------
91
+ # Result JSONL
92
+ # ---------------------------------------------------------------------------
93
+
94
+ def load_result_jsonl(path: str) -> "dict[int, str]":
95
+ index_to_path = {}
96
+ with open(path, "r", encoding="utf-8") as f:
97
+ for line_no, line in enumerate(f, start=1):
98
+ line = line.strip()
99
+ if not line:
100
+ continue
101
+ try:
102
+ entry = json.loads(line)
103
+ except json.JSONDecodeError as e:
104
+ print(f"Warning: malformed line {line_no}: {e}")
105
+ continue
106
+ idx = entry.get("sample_index")
107
+ result_path = entry.get("result")
108
+ if idx is None or result_path is None:
109
+ continue
110
+ index_to_path[int(idx)] = str(result_path)
111
+ return index_to_path
112
+
113
+
114
+ # ---------------------------------------------------------------------------
115
+ # Field access helpers
116
+ # ---------------------------------------------------------------------------
117
+
118
+ def get_expert_domain(sample: dict) -> str:
119
+ """Prefer the new `expert_domain` field; fall back to the legacy `task` field."""
120
+ return sample.get("expert_domain") or sample.get("task", "unknown-unknown")
121
+
122
+
123
+ def split_domain_subtask(expert_domain: str) -> "tuple[str, str]":
124
+ if "-" in expert_domain:
125
+ domain, subtask = expert_domain.split("-", 1)
126
+ else:
127
+ domain, subtask = expert_domain, "unknown"
128
+ return domain, subtask
129
+
130
+
131
+ def get_instruction(sample: dict, lang: str) -> str:
132
+ base = sample.get(INSTRUCTION_FIELD, "") or ""
133
+ if lang == "eng":
134
+ eng = sample.get(INSTRUCTION_FIELD_ENG, "") or ""
135
+ return eng or base
136
+ return base
137
+
138
+
139
+ # ---------------------------------------------------------------------------
140
+ # Score extraction
141
+ # ---------------------------------------------------------------------------
142
+
143
+ def extract_score(answer: str) -> "int | None":
144
+ if not answer:
145
+ return None
146
+ m = re.search(r"<score>\s*(\d+)\s*</score>", answer, re.IGNORECASE)
147
+ if m:
148
+ return int(m.group(1))
149
+ for pattern in (r"\*?\*?Final\s*Score\*?\*?\s*:?\s*\*?\*?\s*(\d+)",):
150
+ m = re.search(pattern, answer, re.IGNORECASE)
151
+ if m:
152
+ return int(m.group(1))
153
+ return None
154
+
155
+
156
+ def is_valid_score(v) -> bool:
157
+ return v is not None and not (isinstance(v, float) and np.isnan(v))
158
+
159
+
160
+ def weighted_score(knowledge, visual, consistency) -> "float | None":
161
+ """
162
+ Weighted composite score (1-5):
163
+ - With consistency: Knowledge 45% + Visual 30% + Consistency 25%
164
+ - Without consistency: Knowledge 60% + Visual 40% (safety fallback,
165
+ should rarely trigger for the i2i subset since it always has `source`)
166
+ - Knowledge <= 2 -> multiply final score by 0.6 (knowledge-error penalty)
167
+ """
168
+ if not is_valid_score(knowledge) or not is_valid_score(visual):
169
+ return None
170
+ if is_valid_score(consistency):
171
+ score = 0.45 * knowledge + 0.30 * visual + 0.25 * consistency
172
+ else:
173
+ score = 0.60 * knowledge + 0.40 * visual
174
+ if knowledge <= 2:
175
+ score *= 0.6
176
+ return round(score, 4)
177
+
178
+
179
+ # ---------------------------------------------------------------------------
180
+ # Single sample scoring
181
+ # ---------------------------------------------------------------------------
182
+
183
+ def score_one_sample(sample_index, dataset, result_path, prompts_cfg, lang, key_pool, base_url, model):
184
+ try:
185
+ sample = dataset[sample_index]
186
+ except (IndexError, KeyError) as e:
187
+ return {"sample_index": sample_index, "error": f"Dataset access failed: {e}"}
188
+
189
+ expert_domain = get_expert_domain(sample)
190
+ domain, subtask = split_domain_subtask(expert_domain)
191
+ sample_id = sample.get("id")
192
+ instruct = get_instruction(sample, lang)
193
+ rationale = (sample.get("rationale") or "").strip()
194
+ rationale_ref = rationale if rationale else NO_RATIONALE_PLACEHOLDER
195
+ source_images = sample.get("source") or []
196
+
197
+ if not os.path.exists(result_path):
198
+ return {"sample_index": sample_index, "task": expert_domain, "id": sample_id,
199
+ "error": f"Result image not found: {result_path}"}
200
+
201
+ try:
202
+ result_img = load_local_image(result_path)
203
+ except Exception as e:
204
+ return {"sample_index": sample_index, "task": expert_domain, "id": sample_id,
205
+ "error": f"Failed to load result image: {e}"}
206
+
207
+ result_b64 = pil_to_base64(result_img)
208
+ ref_b64_list = [pil_to_base64(img) for img in source_images]
209
+ domain_focus = get_task_focus(prompts_cfg, expert_domain)
210
+
211
+ def build_content(prompt_text, include_refs, include_result=True):
212
+ parts = [{"type": "text", "text": prompt_text}]
213
+ if include_refs:
214
+ for b64 in ref_b64_list:
215
+ parts.append({"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64}"}})
216
+ if include_result:
217
+ parts.append({"type": "image_url", "image_url": {"url": f"data:image/png;base64,{result_b64}"}})
218
+ return parts
219
+
220
+ extra_body = {"enableThinking": False, "thinkingBudget": 1024}
221
+
222
+ # --- Dim 1: Knowledge Reasoning (fuses rationale) ---
223
+ ref_note = "5. One or more **reference input images** provided by the user." if ref_b64_list else ""
224
+ prompt_knowledge = prompts_cfg["dimensions"]["knowledge_reasoning"].format(
225
+ instruct=instruct, domain=domain, subtask=subtask,
226
+ domain_focus=domain_focus, ref_image_note=ref_note, rationale=rationale_ref,
227
+ )
228
+ judge_knowledge = call_vlm_with_retries(
229
+ build_content(prompt_knowledge, include_refs=True), key_pool, base_url, model,
230
+ extra_body=extra_body, tag=f"{expert_domain}-{sample_id}-knowledge",
231
+ )
232
+
233
+ # --- Dim 2: Visual Quality ---
234
+ prompt_visual = prompts_cfg["dimensions"]["visual_quality"].format(
235
+ instruct=instruct, domain=domain, subtask=subtask,
236
+ )
237
+ judge_visual = call_vlm_with_retries(
238
+ build_content(prompt_visual, include_refs=False), key_pool, base_url, model,
239
+ extra_body=extra_body, tag=f"{expert_domain}-{sample_id}-visual",
240
+ )
241
+
242
+ # --- Dim 3: Input Consistency (only when reference images exist) ---
243
+ judge_consistency = None
244
+ if ref_b64_list:
245
+ prompt_consistency = prompts_cfg["dimensions"]["input_consistency"].format(
246
+ instruct=instruct, domain=domain, subtask=subtask,
247
+ )
248
+ judge_consistency = call_vlm_with_retries(
249
+ build_content(prompt_consistency, include_refs=True), key_pool, base_url, model,
250
+ extra_body=extra_body, tag=f"{expert_domain}-{sample_id}-consistency",
251
+ )
252
+
253
+ score_knowledge = extract_score(judge_knowledge)
254
+ score_visual = extract_score(judge_visual)
255
+ score_consistency = extract_score(judge_consistency) if judge_consistency else None
256
+ avg = weighted_score(score_knowledge, score_visual, score_consistency)
257
+
258
+ return {
259
+ "sample_index": sample_index,
260
+ "id": sample_id,
261
+ "task": expert_domain,
262
+ "domain": domain,
263
+ "subtask": subtask,
264
+ "instruction": instruct,
265
+ "result_image": result_path,
266
+ "dimension_scores": {
267
+ "KnowledgeReasoning": score_knowledge,
268
+ "VisualQuality": score_visual,
269
+ "InputConsistency": score_consistency,
270
+ },
271
+ "avg_score": avg,
272
+ "judge_knowledge": judge_knowledge,
273
+ "judge_visual": judge_visual,
274
+ "judge_consistency": judge_consistency,
275
+ "error": None if avg is not None else "Failed to compute weighted score",
276
+ }
277
+
278
+
279
+ # ---------------------------------------------------------------------------
280
+ # Aggregation
281
+ # ---------------------------------------------------------------------------
282
+
283
+ def _agg(scores: list) -> dict:
284
+ """Return {avg_score, num_samples} for a list of per-sample scores."""
285
+ if not scores:
286
+ return {"avg_score": None, "num_samples": 0}
287
+ return {"avg_score": round(float(np.mean(scores)), 4), "num_samples": len(scores)}
288
+
289
+
290
+ def build_hierarchy_summary(valid_cases: list) -> dict:
291
+ """Re-aggregate valid cases by (domain, subtask) taxonomy.
292
+
293
+ Uses sample-weighted (micro) averaging. Each sample's `domain` and
294
+ `subtask` fields (derived from `expert_domain`) are used directly — no
295
+ external map required.
296
+ """
297
+ domain_scores = defaultdict(list)
298
+ subtask_scores = defaultdict(list) # key: (domain, subtask)
299
+ nested_scores = defaultdict(lambda: defaultdict(list))
300
+
301
+ for c in valid_cases:
302
+ domain = c.get("domain") or "unknown"
303
+ subtask = c.get("subtask") or "unknown"
304
+ score = c["avg_score"]
305
+ domain_scores[domain].append(score)
306
+ subtask_scores[(domain, subtask)].append(score)
307
+ nested_scores[domain][subtask].append(score)
308
+
309
+ by_domain = {domain: _agg(scores) for domain, scores in domain_scores.items()}
310
+ by_subtask = {
311
+ f"{domain} || {subtask}": _agg(scores)
312
+ for (domain, subtask), scores in subtask_scores.items()
313
+ }
314
+
315
+ nested = {}
316
+ for domain, subtask_dict in nested_scores.items():
317
+ all_scores = []
318
+ subtask_out = {}
319
+ for subtask, scores in subtask_dict.items():
320
+ subtask_out[subtask] = _agg(scores)
321
+ all_scores.extend(scores)
322
+ node = _agg(all_scores)
323
+ node["subtask"] = subtask_out
324
+ nested[domain] = node
325
+
326
+ return {
327
+ "by_domain": by_domain,
328
+ "by_subtask": by_subtask,
329
+ "nested": nested,
330
+ }
331
+
332
+
333
+ def build_summary(cases: list) -> dict:
334
+ """Aggregate results using **micro (sample-weighted) averages**.
335
+
336
+ - `overall_avg_score`: mean weighted score over all valid samples.
337
+ - `by_task_type`: mean per `expert_domain`.
338
+ - `by_dimension`: global per-dimension micro averages.
339
+ - `hierarchy`: re-aggregation by (domain, subtask), using each sample's
340
+ own `domain` / `subtask` fields (no external map needed).
341
+ """
342
+ valid = [c for c in cases if c.get("avg_score") is not None]
343
+ task_scores = defaultdict(list)
344
+ for c in valid:
345
+ task_scores[c["task"]].append(c["avg_score"])
346
+
347
+ by_task = {t: round(float(np.mean(s)), 2) for t, s in task_scores.items()}
348
+ overall = round(float(np.mean([c["avg_score"] for c in valid])), 2) if valid else 0.0
349
+
350
+ def dim_mean(dim):
351
+ vals = [c["dimension_scores"][dim] for c in valid if is_valid_score(c["dimension_scores"].get(dim))]
352
+ return round(float(np.mean(vals)), 2) if vals else None
353
+
354
+ summary = {
355
+ "overall_avg_score": overall,
356
+ "by_task_type": dict(sorted(by_task.items())),
357
+ "by_dimension": {
358
+ "KnowledgeReasoning": dim_mean("KnowledgeReasoning"),
359
+ "VisualQuality": dim_mean("VisualQuality"),
360
+ "InputConsistency": dim_mean("InputConsistency"),
361
+ },
362
+ "total_samples": len(cases),
363
+ "scored_samples": len(valid),
364
+ "error_samples": len(cases) - len(valid),
365
+ "hierarchy": build_hierarchy_summary(valid),
366
+ }
367
+ return summary
368
+
369
+
370
+ # ---------------------------------------------------------------------------
371
+ # Main pipeline
372
+ # ---------------------------------------------------------------------------
373
+
374
+ def run_evaluation(dataset, index_to_result, prompts_cfg, args, key_pool):
375
+ cases_path = os.path.join(args.output_dir, "cases.jsonl")
376
+
377
+ done_indices = set()
378
+ if os.path.exists(cases_path) and args.resume:
379
+ with open(cases_path, "r", encoding="utf-8") as f:
380
+ for line in f:
381
+ try:
382
+ entry = json.loads(line)
383
+ if entry.get("avg_score") is not None:
384
+ done_indices.add(entry["sample_index"])
385
+ except json.JSONDecodeError:
386
+ pass
387
+
388
+ pending = [i for i in sorted(index_to_result) if i not in done_indices]
389
+ print(f"Total: {len(index_to_result)}, already scored: {len(done_indices)}, pending: {len(pending)}")
390
+
391
+ mode = "a" if (args.resume and os.path.exists(cases_path)) else "w"
392
+ if pending:
393
+ with open(cases_path, mode, encoding="utf-8") as out_f:
394
+ with ThreadPoolExecutor(max_workers=args.workers) as executor:
395
+ futures = {
396
+ executor.submit(
397
+ score_one_sample, idx, dataset, index_to_result[idx],
398
+ prompts_cfg, args.lang, key_pool, args.base_url, args.model,
399
+ ): idx
400
+ for idx in pending
401
+ }
402
+ for future in tqdm(as_completed(futures), total=len(futures), desc="Scoring"):
403
+ result = future.result()
404
+ out_f.write(json.dumps(result, ensure_ascii=False) + "\n")
405
+ out_f.flush()
406
+
407
+ all_cases = []
408
+ with open(cases_path, "r", encoding="utf-8") as f:
409
+ for line in f:
410
+ line = line.strip()
411
+ if line:
412
+ all_cases.append(json.loads(line))
413
+
414
+ summary = build_summary(all_cases)
415
+ summary_path = os.path.join(args.output_dir, "summary.json")
416
+ with open(summary_path, "w", encoding="utf-8") as f:
417
+ json.dump(summary, f, ensure_ascii=False, indent=2)
418
+
419
+ # ---- Terminal report ----
420
+ print("\n" + "=" * 60)
421
+ print(f"[intelligent] Overall (weighted 1-5, micro): {summary['overall_avg_score']:.2f}")
422
+ print(f"By dimension: {json.dumps(summary['by_dimension'], ensure_ascii=False)}")
423
+ print(f"Scored {summary['scored_samples']}/{summary['total_samples']} "
424
+ f"(errors: {summary['error_samples']})")
425
+
426
+ hierarchy = summary.get("hierarchy", {})
427
+ if hierarchy.get("by_domain"):
428
+ print("\nBy domain (micro avg):")
429
+ print(json.dumps(hierarchy["by_domain"], indent=2, ensure_ascii=False))
430
+ if hierarchy.get("by_subtask"):
431
+ print("\nBy subtask (micro avg):")
432
+ print(json.dumps(hierarchy["by_subtask"], indent=2, ensure_ascii=False))
433
+
434
+ print(f"\nCases: {cases_path}")
435
+ print(f"Summary: {summary_path}")
436
+ print("=" * 60)
437
+
438
+
439
+ def main():
440
+ parser = argparse.ArgumentParser(description="CPI-Bench: intelligent benchmark evaluation")
441
+ parser.add_argument("--dataset_path", required=True)
442
+ parser.add_argument("--result_jsonl", required=True)
443
+ parser.add_argument("--prompts_json", required=True)
444
+ parser.add_argument("--output_dir", default="eval_output")
445
+ parser.add_argument("--api_key", required=True)
446
+ parser.add_argument("--base_url", default=DEFAULT_BASE_URL)
447
+ parser.add_argument("--model", default=DEFAULT_MODEL)
448
+ parser.add_argument("--lang", choices=["cn", "eng"], default="eng")
449
+ parser.add_argument("--workers", type=int, default=8)
450
+ parser.add_argument("--resume", action="store_true", default=True)
451
+ parser.add_argument("--no_resume", dest="resume", action="store_false")
452
+ parser.add_argument("--num_samples", type=int, default=None)
453
+ args = parser.parse_args()
454
+
455
+ os.makedirs(args.output_dir, exist_ok=True)
456
+ key_pool = ApiKeyPool([k.strip() for k in args.api_key.split(",") if k.strip()])
457
+
458
+ print(f"Loading dataset: {args.dataset_path}")
459
+ dataset = load_dataset("parquet", data_files=args.dataset_path, split="train")
460
+ print(f"Dataset loaded: {len(dataset)} samples")
461
+
462
+ prompts_cfg = load_prompts(args.prompts_json)
463
+
464
+ index_to_result = load_result_jsonl(args.result_jsonl)
465
+ max_idx = len(dataset) - 1
466
+ for i in [i for i in index_to_result if i < 0 or i > max_idx]:
467
+ print(f"Warning: sample_index {i} out of range, skipped.")
468
+ del index_to_result[i]
469
+
470
+ if args.num_samples is not None:
471
+ keep = sorted(index_to_result)[:args.num_samples]
472
+ index_to_result = {i: index_to_result[i] for i in keep}
473
+
474
+ if not index_to_result:
475
+ print("No valid entries to evaluate. Exiting.")
476
+ return
477
+
478
+ run_evaluation(dataset, index_to_result, prompts_cfg, args, key_pool)
479
+
480
+
481
+ if __name__ == "__main__":
482
+ main()