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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
CPI-Bench: General / Practical benchmark evaluation script (open-source version).
|
| 3 |
+
|
| 4 |
+
Evaluates image-editing results against the CPI-General-Benchmark / CPI-Practical-Benchmark
|
| 5 |
+
datasets using a VLM judge with task-specific scoring prompts.
|
| 6 |
+
|
| 7 |
+
Dataset format (HuggingFace parquet):
|
| 8 |
+
- id : str
|
| 9 |
+
- task : str (task category, keyed into prompts.json)
|
| 10 |
+
- a_to_b_instructions : str (Chinese instruction)
|
| 11 |
+
- a_to_b_instructions_eng : str (English instruction)
|
| 12 |
+
- target_resolution : str
|
| 13 |
+
- source : List[PIL.Image] (one or more reference/input images)
|
| 14 |
+
|
| 15 |
+
Result JSONL format (produced by the user, one line per evaluated sample):
|
| 16 |
+
{"sample_index": 0, "result": "/path/to/result_0.png"}
|
| 17 |
+
{"sample_index": 1, "result": "/path/to/result_1.png"}
|
| 18 |
+
...
|
| 19 |
+
`sample_index` refers to the row index in the loaded HF dataset (0-based, in the
|
| 20 |
+
order returned by `datasets.load_dataset`). Use `export_samples.py` to dump the
|
| 21 |
+
dataset to local images + a template result JSONL if you need to know which row
|
| 22 |
+
maps to which sample.
|
| 23 |
+
|
| 24 |
+
Output:
|
| 25 |
+
<output_dir>/cases.jsonl — Per-sample raw response + parsed dimension scores
|
| 26 |
+
<output_dir>/summary.json — Aggregated scores:
|
| 27 |
+
* overall_avg_score / by_task_type : sample-weighted (micro) average
|
| 28 |
+
* hierarchy : re-aggregated by (level1, level2)
|
| 29 |
+
following the hard-coded maps below
|
| 30 |
+
|
| 31 |
+
Note:
|
| 32 |
+
Compared to earlier versions of this script, `overall_avg_score` and
|
| 33 |
+
`by_task_type` are now computed as **micro (sample-weighted) averages**
|
| 34 |
+
rather than macro averages, to stay consistent with our internal reporting
|
| 35 |
+
pipeline. Samples whose `task` is not present in the hierarchy map are
|
| 36 |
+
excluded from the level1/level2 aggregation and listed under
|
| 37 |
+
`hierarchy.unmapped_tasks` for inspection.
|
| 38 |
+
|
| 39 |
+
Usage:
|
| 40 |
+
python eval_general_practical.py \
|
| 41 |
+
--benchmark general \
|
| 42 |
+
--dataset_path "/path/to/Pi_general_benchmark-*.parquet" \
|
| 43 |
+
--result_jsonl /path/to/my_results.jsonl \
|
| 44 |
+
--prompts_json prompts/general_prompts.json \
|
| 45 |
+
--output_dir eval_output/my_model_general \
|
| 46 |
+
--api_key YOUR_KEY \
|
| 47 |
+
--lang eng \
|
| 48 |
+
--workers 8
|
| 49 |
+
|
| 50 |
+
python eval_general_practical.py \
|
| 51 |
+
--benchmark practical \
|
| 52 |
+
--dataset_path "/path/to/Pi_practical_benchmark-*.parquet" \
|
| 53 |
+
--result_jsonl /path/to/my_results.jsonl \
|
| 54 |
+
--prompts_json prompts/practical_prompts.json \
|
| 55 |
+
--output_dir eval_output/my_model_practical \
|
| 56 |
+
--api_key YOUR_KEY \
|
| 57 |
+
--lang eng \
|
| 58 |
+
--workers 8
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
import argparse
|
| 62 |
+
import json
|
| 63 |
+
import os
|
| 64 |
+
from collections import defaultdict
|
| 65 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 66 |
+
|
| 67 |
+
import numpy as np
|
| 68 |
+
from datasets import load_dataset
|
| 69 |
+
from tqdm import tqdm
|
| 70 |
+
|
| 71 |
+
from bench_utils import ApiKeyPool, call_vlm_with_retries, load_local_image, pil_to_base64
|
| 72 |
+
|
| 73 |
+
DEFAULT_MODEL = "gemini-3-flash-preview"
|
| 74 |
+
DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta/openai/"
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
# ---------------------------------------------------------------------------
|
| 78 |
+
# Hierarchy maps: task -> (level1, level2)
|
| 79 |
+
#
|
| 80 |
+
# These maps define the two-level taxonomy used for hierarchical aggregation
|
| 81 |
+
# in `summary.json -> hierarchy`. Newline characters in level1 names are kept
|
| 82 |
+
# intentionally (used for consistent formatting with downstream reporting).
|
| 83 |
+
# If you add new tasks to the benchmark, extend the corresponding map here.
|
| 84 |
+
# ---------------------------------------------------------------------------
|
| 85 |
+
|
| 86 |
+
PRACTICAL_HIERARCHY_MAP = {
|
| 87 |
+
"Smart Remove": ("Portrait Enhancement", "Basic Editing"),
|
| 88 |
+
"Restoration": ("Portrait Enhancement", "Basic Editing"),
|
| 89 |
+
"Image Super-Resolution": ("Portrait Enhancement", "Basic Editing"),
|
| 90 |
+
"Filter Application": ("Portrait Enhancement", "Basic Editing"),
|
| 91 |
+
"Background Change": ("Portrait Enhancement", "Basic Editing"),
|
| 92 |
+
"Portrait Matting": ("Portrait Enhancement", "Basic Editing"),
|
| 93 |
+
"Outpainting": ("Portrait Enhancement", "Basic Editing"),
|
| 94 |
+
"Facial Expression Editing": ("Portrait Enhancement", "Appearance Change"),
|
| 95 |
+
"Age Transformation": ("Portrait Enhancement", "Appearance Change"),
|
| 96 |
+
"Gender Transformation": ("Portrait Enhancement", "Appearance Change"),
|
| 97 |
+
"Figure Change": ("Portrait Enhancement", "Appearance Change"),
|
| 98 |
+
"Hair Change": ("Portrait Enhancement", "Appearance Change"),
|
| 99 |
+
"Face Swap (Reference-based)": ("Portrait Enhancement", "Appearance Change"),
|
| 100 |
+
"Face Generation (Prompt-based)": ("Portrait Enhancement", "Appearance Change"),
|
| 101 |
+
"Beauty": ("Portrait Enhancement", "Appearance Change"),
|
| 102 |
+
"Makeup": ("Portrait Enhancement", "Appearance Change"),
|
| 103 |
+
"ID Photo Generation": ("Portrait Enhancement", "Style and Creative Generation"),
|
| 104 |
+
"Photoshoot Generation": ("Portrait Enhancement", "Style and Creative Generation"),
|
| 105 |
+
"Meme Generation": ("Portrait Enhancement", "Style and Creative Generation"),
|
| 106 |
+
"Character Poster Generation": ("Portrait Enhancement", "Style and Creative Generation"),
|
| 107 |
+
"Viewpoint Change": ("Portrait Enhancement", "Pose and View Change"),
|
| 108 |
+
"Human Motion": ("Portrait Enhancement", "Pose and View Change"),
|
| 109 |
+
"Try-On": ("Portrait Enhancement", "Clothes Change"),
|
| 110 |
+
"Clothing Editing": ("Portrait Enhancement", "Clothes Change"),
|
| 111 |
+
"IP Product Rendering": ("E-commerce &\n Advertising Creativity", "Product Retouching"),
|
| 112 |
+
"Hand-Held Product Generation": ("E-commerce &\n Advertising Creativity", "Product Retouching"),
|
| 113 |
+
"Product Image Retouching": ("E-commerce &\n Advertising Creativity", "Product Retouching"),
|
| 114 |
+
"Product Image Generation (Single Image)": ("E-commerce &\n Advertising Creativity", "Product Retouching"),
|
| 115 |
+
"Product Image Generation (Multi Image)": ("E-commerce &\n Advertising Creativity", "Product Retouching"),
|
| 116 |
+
"Watermark Removal": ("E-commerce &\n Advertising Creativity", "Product Retouching"),
|
| 117 |
+
"Style-Referenced Product Image Generation": ("E-commerce &\n Advertising Creativity", "Product Retouching"),
|
| 118 |
+
"Multi-Product Composite Generation": ("E-commerce &\n Advertising Creativity", "Product Retouching"),
|
| 119 |
+
"Multi-Resolution Product Generation": ("E-commerce &\n Advertising Creativity", "Product Retouching"),
|
| 120 |
+
"Object Extraction": ("E-commerce &\n Advertising Creativity", "Product Retouching"),
|
| 121 |
+
"Promotional Poster Generation": ("E-commerce &\n Advertising Creativity", "Ad Creation"),
|
| 122 |
+
"Splash Ad Generation": ("E-commerce &\n Advertising Creativity", "Ad Creation"),
|
| 123 |
+
"Marketing Image Generation": ("E-commerce &\n Advertising Creativity", "Ad Creation"),
|
| 124 |
+
"Wall and Floor Material Replacement": ("Residential \n Interior Design", "Hard Finishes"),
|
| 125 |
+
"Door and Window Structure Modification": ("Residential \n Interior Design", "Hard Finishes"),
|
| 126 |
+
"Floor Plan Structural Adjustment": ("Residential \n Interior Design", "Hard Finishes"),
|
| 127 |
+
"Interior Staging": ("Residential \n Interior Design", "Soft Furnishings"),
|
| 128 |
+
"Single Furniture Placement": ("Residential \n Interior Design", "Soft Furnishings"),
|
| 129 |
+
"Multi-Furniture Placement": ("Residential \n Interior Design", "Soft Furnishings"),
|
| 130 |
+
"Rough-to-Finished Interior Rendering": ("Residential \n Interior Design", "Rendering"),
|
| 131 |
+
"Architectural Rendering Generation": ("Residential \n Interior Design", "Rendering"),
|
| 132 |
+
"Lighting Effect Simulation": ("Residential \n Interior Design", "Lighting Simulation"),
|
| 133 |
+
"Translation": ("Content Creation", "CN-EN Translation"),
|
| 134 |
+
"Style Transfer": ("Content Creation", "Style and Creative Generation"),
|
| 135 |
+
"Group Photo Generation": ("Content Creation", "Style and Creative Generation"),
|
| 136 |
+
"Multi-Panel Story Generation": ("Content Creation", "Style and Creative Generation"),
|
| 137 |
+
"Sketch Coloring & Refinement": ("Content Creation", "Style and Creative Generation"),
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
GENERAL_HIERARCHY_MAP = {
|
| 141 |
+
"Multi-Subject-Driven Generation": ("Multi-image editing", "Multi-Subject-Driven Generation"),
|
| 142 |
+
"PS Human": ("Single-image editing", "PS Human"),
|
| 143 |
+
"Ref-Based Text Modification": ("Multi-image editing", "Ref-Based Text Modification"),
|
| 144 |
+
"Subject-Driven Generation": ("Single-image editing", "Subject-Driven Generation"),
|
| 145 |
+
"Multi-Image Compose Edit": ("Multi-image editing", "Multi-Image Compose Edit"),
|
| 146 |
+
"Ref-Based Addition": ("Multi-image editing", "Ref-Based Addition"),
|
| 147 |
+
"Subject Replacement": ("Single-image editing", "Subject Replacement"),
|
| 148 |
+
"Compose Edit": ("Single-image editing", "Compose Edit"),
|
| 149 |
+
"Subject Removal": ("Single-image editing", "Subject Removal"),
|
| 150 |
+
"Text Modification": ("Single-image editing", "Text Modification"),
|
| 151 |
+
"Ref-Based Removal": ("Multi-image editing", "Ref-Based Removal"),
|
| 152 |
+
"Subject Addition": ("Single-image editing", "Subject Addition"),
|
| 153 |
+
"Ref-Based Replace": ("Multi-image editing", "Ref-Based Replace"),
|
| 154 |
+
"Motion Change": ("Single-image editing", "Motion Change"),
|
| 155 |
+
"Ref-Based Style Transfer": ("Multi-image editing", "Ref-Based Style Transfer"),
|
| 156 |
+
"Style Transfer": ("Single-image editing", "Style Transfer"),
|
| 157 |
+
"Ref-Based Change": ("Multi-image editing", "Ref-Based Change"),
|
| 158 |
+
"Low Level": ("Single-image editing", "Low Level"),
|
| 159 |
+
"Ref-Based Motion": ("Multi-image editing", "Ref-Based Motion"),
|
| 160 |
+
"Viewpoint Change": ("Single-image editing", "Viewpoint Change"),
|
| 161 |
+
"Subject Extraction": ("Single-image editing", "Subject Extraction"),
|
| 162 |
+
"Ref-Based Viewpoint Change": ("Multi-image editing", "Ref-Based Viewpoint Change"),
|
| 163 |
+
"Environment Change": ("Single-image editing", "Adjust"),
|
| 164 |
+
"Feature Extraction": ("Single-image editing", "Low Level"),
|
| 165 |
+
"Background Change": ("Single-image editing", "Adjust"),
|
| 166 |
+
"Material Modification": ("Single-image editing", "Adjust"),
|
| 167 |
+
"Color Alteration": ("Single-image editing", "Adjust"),
|
| 168 |
+
"Subject Re-orientation": ("Single-image editing", "Adjust"),
|
| 169 |
+
"Structure-Guided Generation": ("Single-image editing", "Structure-Guided Generation"),
|
| 170 |
+
"Attribute Change": ("Single-image editing", "Adjust"),
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
BENCHMARK_HIERARCHY_MAPS = {
|
| 174 |
+
"general": GENERAL_HIERARCHY_MAP,
|
| 175 |
+
"practical": PRACTICAL_HIERARCHY_MAP,
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
# ---------------------------------------------------------------------------
|
| 180 |
+
# Result JSONL
|
| 181 |
+
# ---------------------------------------------------------------------------
|
| 182 |
+
|
| 183 |
+
def load_result_jsonl(path: str) -> "dict[int, str]":
|
| 184 |
+
index_to_path = {}
|
| 185 |
+
with open(path, "r", encoding="utf-8") as f:
|
| 186 |
+
for line_no, line in enumerate(f, start=1):
|
| 187 |
+
line = line.strip()
|
| 188 |
+
if not line:
|
| 189 |
+
continue
|
| 190 |
+
try:
|
| 191 |
+
entry = json.loads(line)
|
| 192 |
+
except json.JSONDecodeError as e:
|
| 193 |
+
print(f"Warning: malformed line {line_no}: {e}")
|
| 194 |
+
continue
|
| 195 |
+
idx = entry.get("sample_index")
|
| 196 |
+
result_path = entry.get("result")
|
| 197 |
+
if idx is None or result_path is None:
|
| 198 |
+
print(f"Warning: line {line_no} missing 'sample_index' or 'result'")
|
| 199 |
+
continue
|
| 200 |
+
index_to_path[int(idx)] = str(result_path)
|
| 201 |
+
return index_to_path
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
# ---------------------------------------------------------------------------
|
| 205 |
+
# Scoring parse
|
| 206 |
+
# ---------------------------------------------------------------------------
|
| 207 |
+
|
| 208 |
+
def parse_dimension_scores(raw_text: str) -> dict:
|
| 209 |
+
"""Parse lines like 'Instruction Following: 8' into a dict."""
|
| 210 |
+
scores = {}
|
| 211 |
+
if not raw_text or not isinstance(raw_text, str) or raw_text.startswith("Error"):
|
| 212 |
+
return scores
|
| 213 |
+
for line in raw_text.splitlines():
|
| 214 |
+
parts = line.strip().split(": ")
|
| 215 |
+
if len(parts) == 2 and parts[1].strip().isdigit():
|
| 216 |
+
scores[parts[0].strip()] = int(parts[1].strip())
|
| 217 |
+
return scores
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def average_score(dim_scores: dict) -> "float | None":
|
| 221 |
+
if not dim_scores:
|
| 222 |
+
return None
|
| 223 |
+
return round(sum(dim_scores.values()) / len(dim_scores), 2)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
# ---------------------------------------------------------------------------
|
| 227 |
+
# Single sample scoring
|
| 228 |
+
# ---------------------------------------------------------------------------
|
| 229 |
+
|
| 230 |
+
def score_one_sample(
|
| 231 |
+
sample_index: int,
|
| 232 |
+
dataset,
|
| 233 |
+
result_path: str,
|
| 234 |
+
prompts_templates: dict,
|
| 235 |
+
lang: str,
|
| 236 |
+
key_pool: ApiKeyPool,
|
| 237 |
+
base_url: str,
|
| 238 |
+
model: str,
|
| 239 |
+
) -> dict:
|
| 240 |
+
try:
|
| 241 |
+
sample = dataset[sample_index]
|
| 242 |
+
except (IndexError, KeyError) as e:
|
| 243 |
+
return {"sample_index": sample_index, "error": f"Dataset access failed: {e}"}
|
| 244 |
+
|
| 245 |
+
task = sample.get("task", "unknown")
|
| 246 |
+
sample_id = sample.get("id")
|
| 247 |
+
source_images = sample.get("source") or []
|
| 248 |
+
|
| 249 |
+
if not source_images:
|
| 250 |
+
return {"sample_index": sample_index, "task": task, "id": sample_id,
|
| 251 |
+
"error": "No source image(s) in dataset sample"}
|
| 252 |
+
|
| 253 |
+
if not os.path.exists(result_path):
|
| 254 |
+
return {"sample_index": sample_index, "task": task, "id": sample_id,
|
| 255 |
+
"error": f"Result image not found: {result_path}"}
|
| 256 |
+
|
| 257 |
+
try:
|
| 258 |
+
result_img = load_local_image(result_path)
|
| 259 |
+
except Exception as e:
|
| 260 |
+
return {"sample_index": sample_index, "task": task, "id": sample_id,
|
| 261 |
+
"error": f"Failed to load result image: {e}"}
|
| 262 |
+
|
| 263 |
+
template = prompts_templates.get(task)
|
| 264 |
+
if not template:
|
| 265 |
+
return {"sample_index": sample_index, "task": task, "id": sample_id,
|
| 266 |
+
"error": f"No prompt template found for task '{task}'"}
|
| 267 |
+
|
| 268 |
+
if lang == "cn":
|
| 269 |
+
edit_prompt = sample.get("a_to_b_instructions", "")
|
| 270 |
+
else:
|
| 271 |
+
edit_prompt = sample.get("a_to_b_instructions_eng", "") or sample.get("a_to_b_instructions", "")
|
| 272 |
+
|
| 273 |
+
full_prompt = template.replace("<edit_prompt>", edit_prompt)
|
| 274 |
+
|
| 275 |
+
# --- Build multimodal message ---
|
| 276 |
+
content_parts = []
|
| 277 |
+
for i, ref_img in enumerate(source_images):
|
| 278 |
+
b64 = pil_to_base64(ref_img)
|
| 279 |
+
content_parts.append({"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64}"}})
|
| 280 |
+
label = "This is the original image A." if len(source_images) == 1 else f"This is reference image A{i+1}."
|
| 281 |
+
content_parts.append({"type": "text", "text": label})
|
| 282 |
+
|
| 283 |
+
result_b64 = pil_to_base64(result_img)
|
| 284 |
+
content_parts.append({"type": "image_url", "image_url": {"url": f"data:image/png;base64,{result_b64}"}})
|
| 285 |
+
content_parts.append({"type": "text", "text": "This is the edited image B. Please evaluate."})
|
| 286 |
+
content_parts.append({"type": "text", "text": full_prompt})
|
| 287 |
+
|
| 288 |
+
raw_text = call_vlm_with_retries(
|
| 289 |
+
content_parts, key_pool, base_url, model, tag=f"{task}-{sample_id}"
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
dim_scores = parse_dimension_scores(raw_text)
|
| 293 |
+
avg = average_score(dim_scores)
|
| 294 |
+
|
| 295 |
+
return {
|
| 296 |
+
"sample_index": sample_index,
|
| 297 |
+
"id": sample_id,
|
| 298 |
+
"task": task,
|
| 299 |
+
"instruction": edit_prompt,
|
| 300 |
+
"result_image": result_path,
|
| 301 |
+
"dimension_scores": dim_scores,
|
| 302 |
+
"avg_score": avg,
|
| 303 |
+
"raw_response": raw_text,
|
| 304 |
+
"error": None if avg is not None else "Failed to parse a valid score from VLM output",
|
| 305 |
+
}
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
# ---------------------------------------------------------------------------
|
| 309 |
+
# Aggregation
|
| 310 |
+
# ---------------------------------------------------------------------------
|
| 311 |
+
|
| 312 |
+
def _agg(scores: list) -> dict:
|
| 313 |
+
"""Return {avg_score, num_samples} for a list of per-sample scores."""
|
| 314 |
+
if not scores:
|
| 315 |
+
return {"avg_score": None, "num_samples": 0}
|
| 316 |
+
return {"avg_score": round(float(np.mean(scores)), 4), "num_samples": len(scores)}
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def build_hierarchy_summary(valid_cases: list, hierarchy_map: dict) -> dict:
|
| 320 |
+
"""Re-aggregate valid cases by (level1, level2) taxonomy.
|
| 321 |
+
|
| 322 |
+
Uses sample-weighted (micro) averaging: every valid sample contributes
|
| 323 |
+
equally to the level it belongs to.
|
| 324 |
+
|
| 325 |
+
Tasks not present in `hierarchy_map` are excluded from level1/level2
|
| 326 |
+
aggregation and reported under `unmapped_tasks`.
|
| 327 |
+
"""
|
| 328 |
+
level1_scores = defaultdict(list)
|
| 329 |
+
level2_scores = defaultdict(list) # key: (level1, level2)
|
| 330 |
+
nested_scores = defaultdict(lambda: defaultdict(list)) # nested[level1][level2] -> [scores]
|
| 331 |
+
unmapped_scores = defaultdict(list)
|
| 332 |
+
|
| 333 |
+
for c in valid_cases:
|
| 334 |
+
task = c.get("task", "")
|
| 335 |
+
score = c["avg_score"]
|
| 336 |
+
mapping = hierarchy_map.get(task)
|
| 337 |
+
if mapping is None:
|
| 338 |
+
unmapped_scores[task].append(score)
|
| 339 |
+
continue
|
| 340 |
+
level1, level2 = mapping
|
| 341 |
+
level1_scores[level1].append(score)
|
| 342 |
+
level2_scores[(level1, level2)].append(score)
|
| 343 |
+
nested_scores[level1][level2].append(score)
|
| 344 |
+
|
| 345 |
+
by_level1 = {level1: _agg(scores) for level1, scores in level1_scores.items()}
|
| 346 |
+
by_level2 = {
|
| 347 |
+
f"{level1} || {level2}": _agg(scores)
|
| 348 |
+
for (level1, level2), scores in level2_scores.items()
|
| 349 |
+
}
|
| 350 |
+
|
| 351 |
+
nested = {}
|
| 352 |
+
for level1, level2_dict in nested_scores.items():
|
| 353 |
+
all_scores = []
|
| 354 |
+
level2_out = {}
|
| 355 |
+
for level2, scores in level2_dict.items():
|
| 356 |
+
level2_out[level2] = _agg(scores)
|
| 357 |
+
all_scores.extend(scores)
|
| 358 |
+
node = _agg(all_scores)
|
| 359 |
+
node["level2"] = level2_out
|
| 360 |
+
nested[level1] = node
|
| 361 |
+
|
| 362 |
+
unmapped_tasks = {task: _agg(scores) for task, scores in unmapped_scores.items()}
|
| 363 |
+
unmapped_total_samples = sum(v["num_samples"] for v in unmapped_tasks.values())
|
| 364 |
+
|
| 365 |
+
return {
|
| 366 |
+
"by_level1": by_level1,
|
| 367 |
+
"by_level2": by_level2,
|
| 368 |
+
"nested": nested,
|
| 369 |
+
"unmapped_tasks": unmapped_tasks,
|
| 370 |
+
"unmapped_total_samples": unmapped_total_samples,
|
| 371 |
+
}
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
def build_summary(cases: list, benchmark: str) -> dict:
|
| 375 |
+
"""Aggregate results using **micro (sample-weighted) averages**.
|
| 376 |
+
|
| 377 |
+
- `overall_avg_score`: mean over all valid samples.
|
| 378 |
+
- `by_task_type`: mean per task, over samples of that task.
|
| 379 |
+
- `hierarchy`: re-aggregation by (level1, level2), only present if the
|
| 380 |
+
benchmark has a hierarchy map defined.
|
| 381 |
+
"""
|
| 382 |
+
valid = [c for c in cases if c.get("avg_score") is not None]
|
| 383 |
+
task_scores = defaultdict(list)
|
| 384 |
+
for c in valid:
|
| 385 |
+
task_scores[c["task"]].append(c["avg_score"])
|
| 386 |
+
|
| 387 |
+
by_task = {t: round(float(np.mean(s)), 2) for t, s in task_scores.items()}
|
| 388 |
+
overall = round(float(np.mean([c["avg_score"] for c in valid])), 2) if valid else 0.0
|
| 389 |
+
|
| 390 |
+
summary = {
|
| 391 |
+
"overall_avg_score": overall,
|
| 392 |
+
"by_task_type": dict(sorted(by_task.items())),
|
| 393 |
+
"total_samples": len(cases),
|
| 394 |
+
"scored_samples": len(valid),
|
| 395 |
+
"error_samples": len(cases) - len(valid),
|
| 396 |
+
}
|
| 397 |
+
|
| 398 |
+
hierarchy_map = BENCHMARK_HIERARCHY_MAPS.get(benchmark)
|
| 399 |
+
if hierarchy_map:
|
| 400 |
+
summary["hierarchy"] = build_hierarchy_summary(valid, hierarchy_map)
|
| 401 |
+
|
| 402 |
+
return summary
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
# ---------------------------------------------------------------------------
|
| 406 |
+
# Main pipeline
|
| 407 |
+
# ---------------------------------------------------------------------------
|
| 408 |
+
|
| 409 |
+
def run_evaluation(dataset, index_to_result, prompts_templates, args, key_pool):
|
| 410 |
+
cases_path = os.path.join(args.output_dir, "cases.jsonl")
|
| 411 |
+
|
| 412 |
+
# Resume support
|
| 413 |
+
done_indices = set()
|
| 414 |
+
if os.path.exists(cases_path) and args.resume:
|
| 415 |
+
with open(cases_path, "r", encoding="utf-8") as f:
|
| 416 |
+
for line in f:
|
| 417 |
+
try:
|
| 418 |
+
entry = json.loads(line)
|
| 419 |
+
if entry.get("avg_score") is not None:
|
| 420 |
+
done_indices.add(entry["sample_index"])
|
| 421 |
+
except json.JSONDecodeError:
|
| 422 |
+
pass
|
| 423 |
+
|
| 424 |
+
pending = [i for i in sorted(index_to_result) if i not in done_indices]
|
| 425 |
+
print(f"Total: {len(index_to_result)}, already scored: {len(done_indices)}, pending: {len(pending)}")
|
| 426 |
+
|
| 427 |
+
mode = "a" if (args.resume and os.path.exists(cases_path)) else "w"
|
| 428 |
+
if pending:
|
| 429 |
+
with open(cases_path, mode, encoding="utf-8") as out_f:
|
| 430 |
+
with ThreadPoolExecutor(max_workers=args.workers) as executor:
|
| 431 |
+
futures = {
|
| 432 |
+
executor.submit(
|
| 433 |
+
score_one_sample, idx, dataset, index_to_result[idx],
|
| 434 |
+
prompts_templates, args.lang, key_pool, args.base_url, args.model,
|
| 435 |
+
): idx
|
| 436 |
+
for idx in pending
|
| 437 |
+
}
|
| 438 |
+
for future in tqdm(as_completed(futures), total=len(futures), desc="Scoring"):
|
| 439 |
+
result = future.result()
|
| 440 |
+
out_f.write(json.dumps(result, ensure_ascii=False) + "\n")
|
| 441 |
+
out_f.flush()
|
| 442 |
+
|
| 443 |
+
all_cases = []
|
| 444 |
+
with open(cases_path, "r", encoding="utf-8") as f:
|
| 445 |
+
for line in f:
|
| 446 |
+
line = line.strip()
|
| 447 |
+
if line:
|
| 448 |
+
all_cases.append(json.loads(line))
|
| 449 |
+
|
| 450 |
+
summary = build_summary(all_cases, args.benchmark)
|
| 451 |
+
summary_path = os.path.join(args.output_dir, "summary.json")
|
| 452 |
+
with open(summary_path, "w", encoding="utf-8") as f:
|
| 453 |
+
json.dump(summary, f, ensure_ascii=False, indent=2)
|
| 454 |
+
|
| 455 |
+
# ---- Terminal report ----
|
| 456 |
+
print("\n" + "=" * 60)
|
| 457 |
+
print(f"[{args.benchmark}] Overall avg score (micro): {summary['overall_avg_score']:.2f}")
|
| 458 |
+
print(f"Scored {summary['scored_samples']}/{summary['total_samples']} "
|
| 459 |
+
f"(errors: {summary['error_samples']})")
|
| 460 |
+
|
| 461 |
+
print("\nBy task type (micro avg):")
|
| 462 |
+
print(json.dumps(summary["by_task_type"], indent=2, ensure_ascii=False))
|
| 463 |
+
|
| 464 |
+
hierarchy = summary.get("hierarchy")
|
| 465 |
+
if hierarchy:
|
| 466 |
+
print("\nBy level1 (micro avg):")
|
| 467 |
+
level1_display = {
|
| 468 |
+
level1.replace("\n", " ").strip(): info
|
| 469 |
+
for level1, info in hierarchy["by_level1"].items()
|
| 470 |
+
}
|
| 471 |
+
print(json.dumps(level1_display, indent=2, ensure_ascii=False))
|
| 472 |
+
|
| 473 |
+
print("\nBy level2 (micro avg):")
|
| 474 |
+
level2_display = {
|
| 475 |
+
key.replace("\n", " "): info
|
| 476 |
+
for key, info in hierarchy["by_level2"].items()
|
| 477 |
+
}
|
| 478 |
+
print(json.dumps(level2_display, indent=2, ensure_ascii=False))
|
| 479 |
+
|
| 480 |
+
if hierarchy["unmapped_total_samples"] > 0:
|
| 481 |
+
print("\n" + "!" * 60)
|
| 482 |
+
print(f"WARNING: {hierarchy['unmapped_total_samples']} sample(s) belong to "
|
| 483 |
+
f"task(s) NOT in the hierarchy map and were EXCLUDED from "
|
| 484 |
+
f"level1/level2 aggregation:")
|
| 485 |
+
for task, info in hierarchy["unmapped_tasks"].items():
|
| 486 |
+
print(f" - '{task}': {info['num_samples']} samples, "
|
| 487 |
+
f"avg_score={info['avg_score']}")
|
| 488 |
+
print(f"Please update {args.benchmark.upper()}_HIERARCHY_MAP in "
|
| 489 |
+
f"eval_general_practical.py to include these tasks.")
|
| 490 |
+
print("!" * 60)
|
| 491 |
+
|
| 492 |
+
print(f"\nCases: {cases_path}")
|
| 493 |
+
print(f"Summary: {summary_path}")
|
| 494 |
+
print("=" * 60)
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
def main():
|
| 498 |
+
parser = argparse.ArgumentParser(description="CPI-Bench: General/Practical benchmark evaluation")
|
| 499 |
+
parser.add_argument("--benchmark", choices=["general", "practical"], required=True)
|
| 500 |
+
parser.add_argument("--dataset_path", required=True,
|
| 501 |
+
help="Glob path to the benchmark parquet shards, e.g. 'Pi_general_benchmark-*.parquet'")
|
| 502 |
+
parser.add_argument("--result_jsonl", required=True,
|
| 503 |
+
help='JSONL with {"sample_index": int, "result": "/path/to/img.png"} per line')
|
| 504 |
+
parser.add_argument("--prompts_json", required=True,
|
| 505 |
+
help="Path to the task-specific scoring prompt templates (JSON: {task: template})")
|
| 506 |
+
parser.add_argument("--output_dir", default="eval_output")
|
| 507 |
+
parser.add_argument("--api_key", required=True, help="Comma-separated API key(s) for round-robin")
|
| 508 |
+
parser.add_argument("--base_url", default=DEFAULT_BASE_URL)
|
| 509 |
+
parser.add_argument("--model", default=DEFAULT_MODEL)
|
| 510 |
+
parser.add_argument("--lang", choices=["cn", "eng"], default="eng")
|
| 511 |
+
parser.add_argument("--workers", type=int, default=8)
|
| 512 |
+
parser.add_argument("--resume", action="store_true", default=True)
|
| 513 |
+
parser.add_argument("--no_resume", dest="resume", action="store_false")
|
| 514 |
+
parser.add_argument("--num_samples", type=int, default=None)
|
| 515 |
+
args = parser.parse_args()
|
| 516 |
+
|
| 517 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 518 |
+
|
| 519 |
+
key_pool = ApiKeyPool([k.strip() for k in args.api_key.split(",") if k.strip()])
|
| 520 |
+
|
| 521 |
+
print(f"Loading dataset: {args.dataset_path}")
|
| 522 |
+
dataset = load_dataset("parquet", data_files=args.dataset_path, split="train")
|
| 523 |
+
print(f"Dataset loaded: {len(dataset)} samples")
|
| 524 |
+
|
| 525 |
+
with open(args.prompts_json, "r", encoding="utf-8") as f:
|
| 526 |
+
prompts_templates = json.load(f)
|
| 527 |
+
|
| 528 |
+
index_to_result = load_result_jsonl(args.result_jsonl)
|
| 529 |
+
max_idx = len(dataset) - 1
|
| 530 |
+
invalid = [i for i in index_to_result if i < 0 or i > max_idx]
|
| 531 |
+
for i in invalid:
|
| 532 |
+
print(f"Warning: sample_index {i} out of range, skipped.")
|
| 533 |
+
del index_to_result[i]
|
| 534 |
+
|
| 535 |
+
if args.num_samples is not None:
|
| 536 |
+
keep = sorted(index_to_result)[:args.num_samples]
|
| 537 |
+
index_to_result = {i: index_to_result[i] for i in keep}
|
| 538 |
+
|
| 539 |
+
if not index_to_result:
|
| 540 |
+
print("No valid entries to evaluate. Exiting.")
|
| 541 |
+
return
|
| 542 |
+
|
| 543 |
+
run_evaluation(dataset, index_to_result, prompts_templates, args, key_pool)
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
if __name__ == "__main__":
|
| 547 |
+
main()
|