anon commited on
Commit
25cbcc2
·
0 Parent(s):

Add EditJudge-Bench evaluation code

Browse files
.gitignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ .cache/
2
+ __pycache__/
3
+ *.egg-info/
4
+ outputs/
5
+ .venv/
README.md ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: EditJudge-Bench Evaluation Code
3
+ tags:
4
+ - benchmark
5
+ - evaluation
6
+ - vision-language-models
7
+ - image-editing
8
+ - vlm-as-a-judge
9
+ ---
10
+
11
+ # EditJudge-Bench Evaluation Code
12
+
13
+ This repository contains lightweight, anonymous evaluation utilities for the
14
+ EditJudge-Bench dataset release. The code validates a local dataset snapshot, expands
15
+ edit-level rows into verification triplets, and computes the AUROC metrics used
16
+ to audit VLM-as-a-judge behaviour.
17
+
18
+ Dataset URL: `https://huggingface.co/datasets/EDAnonSubmission/benchmark`
19
+
20
+ ## Install
21
+
22
+ ```bash
23
+ python -m venv .venv
24
+ source .venv/bin/activate
25
+ pip install -r requirements.txt
26
+ ```
27
+
28
+ ## Dataset Layout
29
+
30
+ The scripts expect a local dataset snapshot with:
31
+
32
+ ```text
33
+ benchmark.parquet
34
+ images/<sample_id>/before.jpg
35
+ images/<sample_id>/after.jpg
36
+ ```
37
+
38
+ Each parquet row is one edit pair. A positive verification triplet is created
39
+ from `instruction_pos`; negative triplets are created from
40
+ `instruction_neg_list` and `instruction_neg_types`.
41
+
42
+ ## Validate the Dataset
43
+
44
+ ```bash
45
+ python scripts/validate_dataset.py \
46
+ --dataset-root /path/to/benchmark
47
+ ```
48
+
49
+ The validator checks row count, image coverage, negative-instruction alignment,
50
+ edit-type balance, and that image paths are portable and repo-relative.
51
+
52
+ ## Prediction Schema
53
+
54
+ Prediction files may be CSV, JSONL, JSON, or Parquet. The simplest schema is:
55
+
56
+ ```text
57
+ sample_id,example_type,negative_index,score
58
+ ```
59
+
60
+ For positives, set `example_type=positive` and `negative_index=-1`. For negatives,
61
+ set `example_type=negative` and use the index in `instruction_neg_list`.
62
+
63
+ The scripts also accept `parquet_row_index` instead of `sample_id`, or an
64
+ expanded table that already contains `label`, `edit_type`, `negative_type`, and
65
+ `score`.
66
+
67
+ ## Compute Main Metrics
68
+
69
+ ```bash
70
+ python scripts/compute_benchpress_metrics.py \
71
+ --dataset-root /path/to/benchmark \
72
+ --predictions /path/to/predictions.parquet \
73
+ --out-dir outputs/judge_name
74
+ ```
75
+
76
+ Outputs:
77
+
78
+ - `overall_metrics.csv`: global AUROC and macro edit-type AUROC.
79
+ - `per_edit_type_auc.csv`: AUROC for each edit type.
80
+
81
+ ## Negative-Type Breakdown
82
+
83
+ ```bash
84
+ python scripts/compute_negative_type_breakdown.py \
85
+ --dataset-root /path/to/benchmark \
86
+ --predictions /path/to/predictions.parquet \
87
+ --out-dir outputs/judge_name
88
+ ```
89
+
90
+ Outputs:
91
+
92
+ - `per_negative_type_auc.csv`
93
+ - `semantic_vs_noedit_summary.csv`
94
+
95
+ ## Ground-Truth Salience Tables
96
+
97
+ ```bash
98
+ python scripts/make_salience_tables.py \
99
+ --dataset-root /path/to/benchmark \
100
+ --predictions /path/to/predictions.parquet \
101
+ --out-dir outputs/judge_name \
102
+ --bins 5
103
+ ```
104
+
105
+ This conditions no-edit rejection AUROC on saved Blender parameters such as
106
+ shape delta, articulation delta, scale delta, movement distance, rotation angle,
107
+ lighting magnitude, and camera changes.
108
+
109
+ ## Notes
110
+
111
+ This code release evaluates judge scores; it does not run VLM inference. The
112
+ paper's model-specific prompts and inference wrappers are implementation details
113
+ around producing the prediction files consumed here.
benchpress_eval/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Small utilities for evaluating judges on the EditJudge-Bench dataset release."""
2
+
3
+ from .data import expand_triplets, load_dataset, validate_dataset
4
+ from .metrics import (
5
+ align_predictions,
6
+ compute_overall_metrics,
7
+ per_edit_type_auc,
8
+ per_negative_type_auc,
9
+ )
10
+
11
+ __all__ = [
12
+ "align_predictions",
13
+ "compute_overall_metrics",
14
+ "expand_triplets",
15
+ "load_dataset",
16
+ "per_edit_type_auc",
17
+ "per_negative_type_auc",
18
+ "validate_dataset",
19
+ ]
benchpress_eval/data.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+ import numpy as np
8
+ import pandas as pd
9
+ from PIL import Image
10
+
11
+ REQUIRED_COLUMNS = (
12
+ "sample_id",
13
+ "edit_type",
14
+ "before",
15
+ "after",
16
+ "instruction_pos",
17
+ "instruction_neg_list",
18
+ "instruction_neg_types",
19
+ )
20
+
21
+ PATH_COLUMNS = ("before", "after")
22
+
23
+
24
+ def load_dataset(dataset_root: str | Path) -> pd.DataFrame:
25
+ dataset_root = Path(dataset_root)
26
+ parquet_path = dataset_root / "benchmark.parquet"
27
+ if not parquet_path.exists():
28
+ raise FileNotFoundError(f"Missing dataset parquet: {parquet_path}")
29
+ return pd.read_parquet(parquet_path)
30
+
31
+
32
+ def as_list(value: Any) -> list[Any]:
33
+ if value is None:
34
+ return []
35
+ if isinstance(value, float) and np.isnan(value):
36
+ return []
37
+ if isinstance(value, np.ndarray):
38
+ return value.tolist()
39
+ if isinstance(value, (list, tuple)):
40
+ return list(value)
41
+ return [value]
42
+
43
+
44
+ def parse_metadata(value: Any) -> dict[str, Any]:
45
+ if isinstance(value, dict):
46
+ return value
47
+ if isinstance(value, str):
48
+ try:
49
+ parsed = json.loads(value)
50
+ return parsed if isinstance(parsed, dict) else {}
51
+ except json.JSONDecodeError:
52
+ return {}
53
+ return {}
54
+
55
+
56
+ def expand_triplets(df: pd.DataFrame) -> pd.DataFrame:
57
+ """Expand edit-level rows into positive/negative verification triplets."""
58
+ rows: list[dict[str, Any]] = []
59
+ for row_index, row in df.reset_index(drop=True).iterrows():
60
+ sample_id = row.get("sample_id", f"row-{row_index:05d}")
61
+ base = {
62
+ "sample_id": sample_id,
63
+ "parquet_row_index": int(row.get("parquet_row_index", row_index)),
64
+ "edit_type": row["edit_type"],
65
+ "before": row["before"],
66
+ "after": row["after"],
67
+ }
68
+ rows.append(
69
+ {
70
+ **base,
71
+ "instruction": row["instruction_pos"],
72
+ "label": 1,
73
+ "ground_truth": True,
74
+ "example_type": "positive",
75
+ "negative_type": "positive",
76
+ "negative_index": -1,
77
+ }
78
+ )
79
+
80
+ negs = as_list(row["instruction_neg_list"])
81
+ neg_types = as_list(row["instruction_neg_types"])
82
+ if len(negs) != len(neg_types):
83
+ raise ValueError(f"Negative instruction/type length mismatch for {sample_id}")
84
+ for neg_index, (instruction, negative_type) in enumerate(zip(negs, neg_types)):
85
+ rows.append(
86
+ {
87
+ **base,
88
+ "instruction": instruction,
89
+ "label": 0,
90
+ "ground_truth": False,
91
+ "example_type": "negative",
92
+ "negative_type": str(negative_type),
93
+ "negative_index": neg_index,
94
+ }
95
+ )
96
+ return pd.DataFrame(rows)
97
+
98
+
99
+ def _is_portable_relative_path(value: Any) -> bool:
100
+ if value is None:
101
+ return False
102
+ path = Path(str(value))
103
+ return not path.is_absolute() and ".." not in path.parts
104
+
105
+
106
+ def validate_dataset(dataset_root: str | Path, strict_core: bool = True) -> dict[str, Any]:
107
+ """Validate the public Hugging Face dataset layout."""
108
+ dataset_root = Path(dataset_root)
109
+ df = load_dataset(dataset_root)
110
+ report: dict[str, Any] = {
111
+ "row_count": int(len(df)),
112
+ "required_missing": [col for col in REQUIRED_COLUMNS if col not in df.columns],
113
+ "edit_type_counts": df["edit_type"].value_counts().sort_index().to_dict()
114
+ if "edit_type" in df.columns
115
+ else {},
116
+ }
117
+
118
+ before_exists = df["before"].map(lambda p: (dataset_root / str(p)).exists())
119
+ after_exists = df["after"].map(lambda p: (dataset_root / str(p)).exists())
120
+ report["before_paths_resolvable"] = int(before_exists.sum())
121
+ report["after_paths_resolvable"] = int(after_exists.sum())
122
+
123
+ length_matches = []
124
+ for _, row in df.iterrows():
125
+ length_matches.append(
126
+ len(as_list(row["instruction_neg_list"])) == len(as_list(row["instruction_neg_types"]))
127
+ )
128
+ report["negative_instruction_lengths_match"] = int(sum(length_matches))
129
+
130
+ non_portable_paths: dict[str, int] = {}
131
+ for col in PATH_COLUMNS:
132
+ if col in df.columns:
133
+ bad_count = int((~df[col].map(_is_portable_relative_path)).sum())
134
+ if bad_count:
135
+ non_portable_paths[col] = bad_count
136
+ report["non_portable_path_columns"] = non_portable_paths
137
+
138
+ dimensions: dict[str, int] = {}
139
+ for path_text in pd.concat([df["before"], df["after"]]).head(100):
140
+ path = dataset_root / str(path_text)
141
+ if path.exists():
142
+ with Image.open(path) as image:
143
+ key = f"{image.width}x{image.height}"
144
+ dimensions[key] = dimensions.get(key, 0) + 1
145
+ report["sampled_image_dimension_counts"] = dimensions
146
+
147
+ checks = [
148
+ not report["required_missing"],
149
+ report["before_paths_resolvable"] == len(df),
150
+ report["after_paths_resolvable"] == len(df),
151
+ report["negative_instruction_lengths_match"] == len(df),
152
+ not report["non_portable_path_columns"],
153
+ ]
154
+ if strict_core:
155
+ checks.extend(
156
+ [
157
+ len(df) == 1500,
158
+ set(report["edit_type_counts"].values()) == {150},
159
+ ]
160
+ )
161
+ report["passed"] = bool(all(checks))
162
+ return report
benchpress_eval/io.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+ import pandas as pd
8
+
9
+
10
+ def read_table(path: str | Path) -> pd.DataFrame:
11
+ """Read a CSV, JSONL, JSON, or Parquet table."""
12
+ path = Path(path)
13
+ suffix = path.suffix.lower()
14
+ if suffix == ".parquet":
15
+ return pd.read_parquet(path)
16
+ if suffix == ".csv":
17
+ return pd.read_csv(path)
18
+ if suffix == ".jsonl":
19
+ return pd.read_json(path, lines=True)
20
+ if suffix == ".json":
21
+ return pd.read_json(path)
22
+ raise ValueError(f"Unsupported table format: {path}")
23
+
24
+
25
+ def write_json(obj: dict[str, Any], path: str | Path) -> None:
26
+ path = Path(path)
27
+ path.parent.mkdir(parents=True, exist_ok=True)
28
+ path.write_text(json.dumps(obj, indent=2, sort_keys=True) + "\n", encoding="utf-8")
29
+
30
+
31
+ def write_csv(df: pd.DataFrame, path: str | Path) -> None:
32
+ path = Path(path)
33
+ path.parent.mkdir(parents=True, exist_ok=True)
34
+ df.to_csv(path, index=False)
benchpress_eval/metrics.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+
8
+ from .data import expand_triplets
9
+
10
+
11
+ def auroc_safe(y_true: pd.Series | np.ndarray, y_score: pd.Series | np.ndarray) -> float:
12
+ """Rank-based AUROC with average ranks for ties."""
13
+ y = pd.Series(y_true).astype(float)
14
+ s = pd.to_numeric(pd.Series(y_score), errors="coerce")
15
+ mask = np.isfinite(y) & np.isfinite(s)
16
+ y = y[mask].astype(int)
17
+ s = s[mask].astype(float)
18
+ if y.nunique() < 2:
19
+ return float("nan")
20
+ n_pos = int((y == 1).sum())
21
+ n_neg = int((y == 0).sum())
22
+ if n_pos == 0 or n_neg == 0:
23
+ return float("nan")
24
+ ranks = s.rank(method="average")
25
+ pos_rank_sum = float(ranks[y == 1].sum())
26
+ return (pos_rank_sum - n_pos * (n_pos + 1) / 2.0) / (n_pos * n_neg)
27
+
28
+
29
+ def _score_column(predictions: pd.DataFrame, requested: str | None) -> str:
30
+ if requested and requested in predictions.columns:
31
+ return requested
32
+ for candidate in ("score", "score_norm", "raw_score"):
33
+ if candidate in predictions.columns:
34
+ return candidate
35
+ raise ValueError("Predictions must contain a score column, e.g. score or score_norm.")
36
+
37
+
38
+ def _standardize_negative_index(df: pd.DataFrame) -> pd.DataFrame:
39
+ df = df.copy()
40
+ if "negative_index" in df.columns:
41
+ df["negative_index"] = pd.to_numeric(df["negative_index"], errors="coerce").fillna(-1).astype(int)
42
+ return df
43
+
44
+
45
+ def align_predictions(
46
+ dataset_df: pd.DataFrame,
47
+ predictions: pd.DataFrame,
48
+ score_col: str | None = None,
49
+ ) -> pd.DataFrame:
50
+ """Align model scores to EditJudge-Bench triplets.
51
+
52
+ Supported prediction schemas:
53
+ 1. Expanded rows with label/edit_type/negative_type/score already present.
54
+ 2. Rows keyed by sample_id or parquet_row_index plus example_type and negative_index.
55
+ 3. Rows keyed by sample_id or parquet_row_index plus instruction text.
56
+ """
57
+ predictions = _standardize_negative_index(predictions)
58
+ score_col = _score_column(predictions, score_col)
59
+ predictions = predictions.rename(columns={score_col: "score"}).copy()
60
+ predictions["score"] = pd.to_numeric(predictions["score"], errors="coerce")
61
+
62
+ expanded_cols = {"label", "edit_type", "negative_type", "score"}
63
+ if expanded_cols.issubset(predictions.columns):
64
+ out = predictions.copy()
65
+ if "ground_truth" not in out.columns:
66
+ out["ground_truth"] = out["label"].astype(bool)
67
+ return out
68
+
69
+ triplets = expand_triplets(dataset_df)
70
+ key = "sample_id" if "sample_id" in predictions.columns else "parquet_row_index"
71
+ if key not in predictions.columns:
72
+ raise ValueError("Predictions must contain sample_id or parquet_row_index.")
73
+
74
+ if {"example_type", "negative_index"}.issubset(predictions.columns):
75
+ join_cols = [key, "example_type", "negative_index"]
76
+ elif "instruction" in predictions.columns:
77
+ join_cols = [key, "instruction"]
78
+ else:
79
+ raise ValueError(
80
+ "Predictions must include either example_type+negative_index or instruction."
81
+ )
82
+
83
+ keep_cols = join_cols + ["score"] + [
84
+ col for col in ("raw_score", "raw_output", "model", "method") if col in predictions.columns
85
+ ]
86
+ merged = triplets.merge(predictions[keep_cols], on=join_cols, how="left", validate="one_to_one")
87
+ missing = int(merged["score"].isna().sum())
88
+ if missing:
89
+ raise ValueError(f"Could not align {missing} triplets to prediction scores.")
90
+ return merged
91
+
92
+
93
+ def compute_overall_metrics(aligned: pd.DataFrame) -> pd.DataFrame:
94
+ per_edit = per_edit_type_auc(aligned)
95
+ row: dict[str, Any] = {
96
+ "global_auc": auroc_safe(aligned["label"], aligned["score"]),
97
+ "macro_edit_auc": per_edit["auc"].mean(),
98
+ "n_triplets": int(len(aligned)),
99
+ "n_edits": int(aligned["sample_id"].nunique()) if "sample_id" in aligned.columns else np.nan,
100
+ }
101
+ return pd.DataFrame([row])
102
+
103
+
104
+ def per_edit_type_auc(aligned: pd.DataFrame) -> pd.DataFrame:
105
+ rows = []
106
+ for edit_type, group in aligned.groupby("edit_type", sort=True):
107
+ rows.append(
108
+ {
109
+ "edit_type": edit_type,
110
+ "auc": auroc_safe(group["label"], group["score"]),
111
+ "n_triplets": int(len(group)),
112
+ "n_edits": int(group["sample_id"].nunique()) if "sample_id" in group.columns else np.nan,
113
+ }
114
+ )
115
+ return pd.DataFrame(rows)
116
+
117
+
118
+ def per_negative_type_auc(aligned: pd.DataFrame) -> pd.DataFrame:
119
+ positives = aligned[aligned["label"] == 1]
120
+ negatives = aligned[aligned["label"] == 0]
121
+ rows = []
122
+ for negative_type, neg_group in negatives.groupby("negative_type", sort=True):
123
+ group = pd.concat([positives, neg_group], ignore_index=True)
124
+ rows.append(
125
+ {
126
+ "negative_type": negative_type,
127
+ "auc": auroc_safe(group["label"], group["score"]),
128
+ "n_negative_triplets": int(len(neg_group)),
129
+ "n_positive_triplets": int(len(positives)),
130
+ }
131
+ )
132
+ return pd.DataFrame(rows)
133
+
134
+
135
+ def semantic_vs_noedit_summary(per_negative: pd.DataFrame) -> pd.DataFrame:
136
+ semantic_names = {"counterfactual", "cross_type", "wrong_object"}
137
+ semantic = per_negative[per_negative["negative_type"].isin(semantic_names)]
138
+ no_edit = per_negative[per_negative["negative_type"].eq("no_edit")]
139
+ return pd.DataFrame(
140
+ [
141
+ {
142
+ "semantic_auc": semantic["auc"].mean(),
143
+ "no_edit_auc": no_edit["auc"].mean(),
144
+ "semantic_negative_types": ",".join(sorted(semantic["negative_type"].unique())),
145
+ }
146
+ ]
147
+ )
benchpress_eval/salience.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Callable
5
+
6
+ import numpy as np
7
+ import pandas as pd
8
+
9
+ from .data import parse_metadata
10
+ from .metrics import auroc_safe
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class ParameterSpec:
15
+ name: str
16
+ edit_types: tuple[str, ...]
17
+ column_candidates: tuple[str, ...]
18
+ metadata_candidates: tuple[str, ...] = ()
19
+ transform: Callable[[pd.Series], pd.Series] | None = None
20
+
21
+
22
+ def _abs(series: pd.Series) -> pd.Series:
23
+ return pd.to_numeric(series, errors="coerce").abs()
24
+
25
+
26
+ def _scale_delta(series: pd.Series) -> pd.Series:
27
+ return (pd.to_numeric(series, errors="coerce") - 1.0).abs()
28
+
29
+
30
+ PARAMETERS = (
31
+ ParameterSpec(
32
+ "shape_delta",
33
+ ("shape",),
34
+ ("meta.delta", "shape_delta", "delta_theta"),
35
+ ("delta", "shape_delta", "delta_theta"),
36
+ _abs,
37
+ ),
38
+ ParameterSpec(
39
+ "articulation_delta",
40
+ ("articulation",),
41
+ ("meta.delta", "articulation_delta", "delta_psi"),
42
+ ("delta", "articulation_delta", "delta_psi"),
43
+ _abs,
44
+ ),
45
+ ParameterSpec(
46
+ "scale_delta",
47
+ ("scale",),
48
+ ("meta.factor", "scale_factor", "factor"),
49
+ ("factor", "scale_factor"),
50
+ _scale_delta,
51
+ ),
52
+ ParameterSpec(
53
+ "movement_distance",
54
+ ("movement",),
55
+ ("meta.distance_moved", "movement_distance", "distance_moved"),
56
+ ("distance_moved", "movement_distance"),
57
+ None,
58
+ ),
59
+ ParameterSpec(
60
+ "rotation_angle",
61
+ ("rotation",),
62
+ ("meta.angle_deg", "rotation_angle_deg", "angle_deg"),
63
+ ("angle_deg", "rotation_angle_deg"),
64
+ _abs,
65
+ ),
66
+ ParameterSpec(
67
+ "camera_position_delta",
68
+ ("camera",),
69
+ ("meta.position_delta", "camera_position_delta", "position_delta"),
70
+ ("position_delta", "camera_position_delta"),
71
+ None,
72
+ ),
73
+ ParameterSpec(
74
+ "camera_focal_delta",
75
+ ("camera",),
76
+ ("meta.delta_lens", "focal_delta", "delta_f"),
77
+ ("delta_lens", "focal_delta", "delta_f"),
78
+ _abs,
79
+ ),
80
+ ParameterSpec(
81
+ "lighting_magnitude",
82
+ ("lighting",),
83
+ ("meta.magnitude", "lighting_magnitude"),
84
+ ("magnitude", "lighting_magnitude"),
85
+ None,
86
+ ),
87
+ ParameterSpec(
88
+ "removal_visibility",
89
+ ("removal",),
90
+ ("meta.visibility", "visibility"),
91
+ ("visibility",),
92
+ None,
93
+ ),
94
+ )
95
+
96
+
97
+ def _metadata_series(df: pd.DataFrame, candidates: tuple[str, ...]) -> pd.Series:
98
+ if "metadata" not in df.columns:
99
+ return pd.Series(np.nan, index=df.index)
100
+ values = []
101
+ for value in df["metadata"]:
102
+ metadata = parse_metadata(value)
103
+ found = np.nan
104
+ for key in candidates:
105
+ if key in metadata:
106
+ found = metadata[key]
107
+ break
108
+ values.append(found)
109
+ return pd.Series(values, index=df.index)
110
+
111
+
112
+ def parameter_values(dataset_df: pd.DataFrame, spec: ParameterSpec) -> pd.Series:
113
+ values = pd.Series(np.nan, index=dataset_df.index, dtype="float64")
114
+ for column in spec.column_candidates:
115
+ if column in dataset_df.columns:
116
+ values = pd.to_numeric(dataset_df[column], errors="coerce")
117
+ break
118
+ if values.isna().all() and spec.metadata_candidates:
119
+ values = pd.to_numeric(_metadata_series(dataset_df, spec.metadata_candidates), errors="coerce")
120
+ if spec.transform:
121
+ values = spec.transform(values)
122
+ return values
123
+
124
+
125
+ def compute_noedit_salience(
126
+ dataset_df: pd.DataFrame,
127
+ aligned_predictions: pd.DataFrame,
128
+ n_bins: int = 5,
129
+ ) -> tuple[pd.DataFrame, pd.DataFrame]:
130
+ """Compute no-edit AUROC stratified by ground-truth parameter magnitude."""
131
+ id_col = "sample_id" if "sample_id" in aligned_predictions.columns else "parquet_row_index"
132
+ base = dataset_df.reset_index(drop=True).copy()
133
+ if "parquet_row_index" not in base.columns:
134
+ base["parquet_row_index"] = base.index
135
+
136
+ usable = aligned_predictions[
137
+ (aligned_predictions["label"].eq(1)) | (aligned_predictions["negative_type"].eq("no_edit"))
138
+ ].copy()
139
+ rows = []
140
+ summary = []
141
+
142
+ for spec in PARAMETERS:
143
+ mask = base["edit_type"].isin(spec.edit_types)
144
+ param = parameter_values(base, spec)
145
+ param_df = base.loc[mask, [id_col if id_col in base.columns else "parquet_row_index"]].copy()
146
+ param_df["parameter_value"] = param[mask].values
147
+ param_df = param_df.dropna(subset=["parameter_value"])
148
+ if param_df["parameter_value"].nunique() < 2:
149
+ continue
150
+
151
+ try:
152
+ bins = pd.qcut(param_df["parameter_value"], q=n_bins, duplicates="drop")
153
+ except ValueError:
154
+ continue
155
+ param_df["bin"] = bins.astype(str)
156
+ merged = usable.merge(param_df, on=id_col, how="inner")
157
+ if merged.empty:
158
+ continue
159
+
160
+ for bin_label, group in merged.groupby("bin", sort=False):
161
+ rows.append(
162
+ {
163
+ "parameter": spec.name,
164
+ "edit_types": ",".join(spec.edit_types),
165
+ "bin": bin_label,
166
+ "auc": auroc_safe(group["label"], group["score"]),
167
+ "n_triplets": int(len(group)),
168
+ "n_edits": int(group[id_col].nunique()),
169
+ "value_min": float(group["parameter_value"].min()),
170
+ "value_max": float(group["parameter_value"].max()),
171
+ }
172
+ )
173
+
174
+ summary.append(
175
+ {
176
+ "parameter": spec.name,
177
+ "edit_types": ",".join(spec.edit_types),
178
+ "spearman_auc_vs_bin_midpoint": _bin_spearman(rows, spec.name),
179
+ "n_bins": int(param_df["bin"].nunique()),
180
+ "n_edits": int(param_df[id_col].nunique()),
181
+ }
182
+ )
183
+
184
+ return pd.DataFrame(rows), pd.DataFrame(summary)
185
+
186
+
187
+ def _bin_spearman(rows: list[dict], parameter_name: str) -> float:
188
+ subset = pd.DataFrame([row for row in rows if row["parameter"] == parameter_name])
189
+ if len(subset) < 2:
190
+ return float("nan")
191
+ mids = (subset["value_min"] + subset["value_max"]) / 2.0
192
+ x = pd.to_numeric(mids, errors="coerce")
193
+ y = pd.to_numeric(subset["auc"], errors="coerce")
194
+ mask = x.notna() & y.notna()
195
+ if mask.sum() < 2:
196
+ return float("nan")
197
+ x_rank = x[mask].rank(method="average")
198
+ y_rank = y[mask].rank(method="average")
199
+ if x_rank.nunique() < 2 or y_rank.nunique() < 2:
200
+ return float("nan")
201
+ return float(x_rank.corr(y_rank))
examples/README.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Example prediction file
2
+
3
+ `example_predictions.csv` is a tiny synthetic score file for smoke-testing the metric
4
+ scripts. It is not a model result. Real judge outputs can use the same schema:
5
+
6
+ ```text
7
+ sample_id,example_type,negative_index,score
8
+ ```
9
+
10
+ For positive triplets, use `example_type=positive` and `negative_index=-1`.
11
+ For negative triplets, use `example_type=negative` and the index of the
12
+ corresponding entry in `instruction_neg_list`.
examples/example_predictions.csv ADDED
The diff for this file is too large to render. See raw diff
 
pyproject.toml ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "benchpress_eval"
7
+ version = "0.1.0"
8
+ requires-python = ">=3.9"
9
+ dependencies = [
10
+ "pandas>=2.0",
11
+ "pyarrow>=14.0",
12
+ "numpy>=1.23",
13
+ "Pillow>=10.0",
14
+ ]
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ pandas>=2.0
2
+ pyarrow>=14.0
3
+ numpy>=1.23
4
+ Pillow>=10.0
scripts/compute_benchpress_metrics.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ from pathlib import Path
6
+
7
+ from benchpress_eval.data import load_dataset
8
+ from benchpress_eval.io import read_table, write_csv
9
+ from benchpress_eval.metrics import align_predictions, compute_overall_metrics, per_edit_type_auc
10
+
11
+
12
+ def main() -> None:
13
+ parser = argparse.ArgumentParser(description="Compute EditJudge-Bench AUROC metrics for one judge run.")
14
+ parser.add_argument("--dataset-root", required=True, help="Folder containing benchmark.parquet.")
15
+ parser.add_argument("--predictions", required=True, help="CSV/JSONL/Parquet prediction file.")
16
+ parser.add_argument("--out-dir", required=True, help="Directory for metric CSV outputs.")
17
+ parser.add_argument("--score-col", default=None, help="Prediction score column; auto-detected by default.")
18
+ args = parser.parse_args()
19
+
20
+ out_dir = Path(args.out_dir)
21
+ dataset = load_dataset(args.dataset_root)
22
+ predictions = read_table(args.predictions)
23
+ aligned = align_predictions(dataset, predictions, score_col=args.score_col)
24
+
25
+ write_csv(compute_overall_metrics(aligned), out_dir / "overall_metrics.csv")
26
+ write_csv(per_edit_type_auc(aligned), out_dir / "per_edit_type_auc.csv")
27
+
28
+
29
+ if __name__ == "__main__":
30
+ main()
scripts/compute_negative_type_breakdown.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ from pathlib import Path
6
+
7
+ from benchpress_eval.data import load_dataset
8
+ from benchpress_eval.io import read_table, write_csv
9
+ from benchpress_eval.metrics import align_predictions, per_negative_type_auc, semantic_vs_noedit_summary
10
+
11
+
12
+ def main() -> None:
13
+ parser = argparse.ArgumentParser(description="Compute AUROC by negative instruction family.")
14
+ parser.add_argument("--dataset-root", required=True)
15
+ parser.add_argument("--predictions", required=True)
16
+ parser.add_argument("--out-dir", required=True)
17
+ parser.add_argument("--score-col", default=None)
18
+ args = parser.parse_args()
19
+
20
+ out_dir = Path(args.out_dir)
21
+ dataset = load_dataset(args.dataset_root)
22
+ predictions = read_table(args.predictions)
23
+ aligned = align_predictions(dataset, predictions, score_col=args.score_col)
24
+ per_negative = per_negative_type_auc(aligned)
25
+
26
+ write_csv(per_negative, out_dir / "per_negative_type_auc.csv")
27
+ write_csv(semantic_vs_noedit_summary(per_negative), out_dir / "semantic_vs_noedit_summary.csv")
28
+
29
+
30
+ if __name__ == "__main__":
31
+ main()
scripts/make_salience_tables.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ from pathlib import Path
6
+
7
+ from benchpress_eval.data import load_dataset
8
+ from benchpress_eval.io import read_table, write_csv
9
+ from benchpress_eval.metrics import align_predictions
10
+ from benchpress_eval.salience import compute_noedit_salience
11
+
12
+
13
+ def main() -> None:
14
+ parser = argparse.ArgumentParser(
15
+ description="Compute no-edit AUROC stratified by ground-truth edit parameters."
16
+ )
17
+ parser.add_argument("--dataset-root", required=True)
18
+ parser.add_argument("--predictions", required=True)
19
+ parser.add_argument("--out-dir", required=True)
20
+ parser.add_argument("--score-col", default=None)
21
+ parser.add_argument("--bins", type=int, default=5)
22
+ args = parser.parse_args()
23
+
24
+ out_dir = Path(args.out_dir)
25
+ dataset = load_dataset(args.dataset_root)
26
+ predictions = read_table(args.predictions)
27
+ aligned = align_predictions(dataset, predictions, score_col=args.score_col)
28
+ by_bin, summary = compute_noedit_salience(dataset, aligned, n_bins=args.bins)
29
+
30
+ write_csv(by_bin, out_dir / "salience_by_parameter_bin.csv")
31
+ write_csv(summary, out_dir / "salience_summary.csv")
32
+
33
+
34
+ if __name__ == "__main__":
35
+ main()
scripts/validate_dataset.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+
7
+ from benchpress_eval.data import validate_dataset
8
+
9
+
10
+ def main() -> None:
11
+ parser = argparse.ArgumentParser(description="Validate a local EditJudge-Bench dataset snapshot.")
12
+ parser.add_argument("--dataset-root", required=True, help="Folder containing benchmark.parquet.")
13
+ parser.add_argument("--no-strict-core", action="store_true", help="Do not require the 1,500-row core release.")
14
+ args = parser.parse_args()
15
+
16
+ report = validate_dataset(args.dataset_root, strict_core=not args.no_strict_core)
17
+ print(json.dumps(report, indent=2, sort_keys=True))
18
+ if not report["passed"]:
19
+ raise SystemExit(1)
20
+
21
+
22
+ if __name__ == "__main__":
23
+ main()