afs07fda89sdfas90 commited on
Commit
f79f2ee
·
0 Parent(s):

OccludeBench release

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +60 -0
  2. README.md +107 -0
  3. annotations.json +0 -0
  4. code/.env.example +4 -0
  5. code/README.md +77 -0
  6. code/appendix/box_sensitivity/generate_occluded_blue.py +56 -0
  7. code/appendix/box_sensitivity/run_blue_robustness.sh +26 -0
  8. code/appendix/human_learning_effects/learning_effect_test.py +131 -0
  9. code/appendix/image_generation/eval_image_gen.py +186 -0
  10. code/appendix/lexical_metrics/answer_lexical_metrics.py +173 -0
  11. code/appendix/token_length/token_length_vs_correctness_all_models_no_outliers.ipynb +464 -0
  12. code/prepare_data.py +82 -0
  13. code/requirements.txt +18 -0
  14. code/sec3_occludebench/eval_script.py +244 -0
  15. code/sec3_occludebench/human_baseline/human_accuracy_breakdown_pub_quality.ipynb +417 -0
  16. code/sec3_occludebench/human_baseline/judger_human.py +186 -0
  17. code/sec3_occludebench/image_category_plots.ipynb +187 -0
  18. code/sec3_occludebench/judger_script.py +261 -0
  19. code/sec3_occludebench/vetter_script.py +190 -0
  20. code/sec4_1_main_results/accuracy_breakdown_pub_quality.ipynb +997 -0
  21. code/sec4_1_main_results/category_accuracy/accuracy_by_category.ipynb +604 -0
  22. code/sec4_1_main_results/human_model_correlation/human_model_difficulty_correlation.ipynb +688 -0
  23. code/sec4_1_main_results/localization_unmasked/eval_transparent.py +135 -0
  24. code/sec4_1_main_results/localization_unmasked/generate_transparent.py +41 -0
  25. code/sec4_1_main_results/nudge_comparison.ipynb +342 -0
  26. code/sec4_1_main_results/run_all_evals.sh +48 -0
  27. code/sec4_2_why_vlms_fail/cue_removal/accuracy_breakdown_physical.ipynb +224 -0
  28. code/sec4_2_why_vlms_fail/cue_removal/run_cue_removed_eval.sh +27 -0
  29. code/sec4_2_why_vlms_fail/seeing_failure/eval_wrong_transparent.py +206 -0
  30. code/sec4_2_why_vlms_fail/seeing_failure/judge_wrong_transparent.py +114 -0
  31. code/sec4_2_why_vlms_fail/stage1_cue_detection/eval_reflection_shadow.py +195 -0
  32. code/sec4_2_why_vlms_fail/stage1_cue_detection/run_reflection_shadow.sh +20 -0
  33. code/sec4_2_why_vlms_fail/stage1_cue_detection/run_reflection_shadow_inferential.sh +14 -0
  34. code/sec4_2_why_vlms_fail/stage2_zoomed_recognition/app.py +150 -0
  35. code/sec4_2_why_vlms_fail/stage2_zoomed_recognition/ask_crops.py +118 -0
  36. code/sec4_2_why_vlms_fail/stage2_zoomed_recognition/judge_crops.py +101 -0
  37. code/sec4_2_why_vlms_fail/stage2_zoomed_recognition/run_crop_eval.sh +10 -0
  38. code/sec4_2_why_vlms_fail/stage2_zoomed_recognition/run_judge_loop.sh +24 -0
  39. code/sec4_2_why_vlms_fail/stage2_zoomed_recognition/templates/index.html +217 -0
  40. code/sec4_2_why_vlms_fail/stage2_zoomed_recognition/wait_and_judge.sh +13 -0
  41. code/sec4_2_why_vlms_fail/stage3_source_mapping/auto_annotate.py +193 -0
  42. code/sec4_2_why_vlms_fail/stage3_source_mapping/map_eval.py +126 -0
  43. code/sec4_2_why_vlms_fail/stage3_source_mapping/reverse_annotate.py +182 -0
  44. code/sec4_2_why_vlms_fail/stage3_source_mapping/reverse_map_eval.py +112 -0
  45. code/sec4_2_why_vlms_fail/stage3_source_mapping/run_map_eval.sh +9 -0
  46. code/sec4_2_why_vlms_fail/stage3_source_mapping/run_reverse_map_eval.sh +9 -0
  47. code/sec4_2_why_vlms_fail/stage4_highlighted_region/highlight_annotate.py +65 -0
  48. code/sec4_2_why_vlms_fail/stage4_highlighted_region/identify_highlight_eval.py +96 -0
  49. code/sec4_2_why_vlms_fail/stage4_highlighted_region/judge_highlight.py +38 -0
  50. code/sec4_2_why_vlms_fail/stage4_highlighted_region/run_identify_highlight.sh +9 -0
.gitattributes ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.avro filter=lfs diff=lfs merge=lfs -text
4
+ *.bin filter=lfs diff=lfs merge=lfs -text
5
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
6
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
7
+ *.ftz filter=lfs diff=lfs merge=lfs -text
8
+ *.gz filter=lfs diff=lfs merge=lfs -text
9
+ *.h5 filter=lfs diff=lfs merge=lfs -text
10
+ *.joblib filter=lfs diff=lfs merge=lfs -text
11
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
12
+ *.lz4 filter=lfs diff=lfs merge=lfs -text
13
+ *.mds filter=lfs diff=lfs merge=lfs -text
14
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
15
+ *.model filter=lfs diff=lfs merge=lfs -text
16
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
17
+ *.npy filter=lfs diff=lfs merge=lfs -text
18
+ *.npz filter=lfs diff=lfs merge=lfs -text
19
+ *.onnx filter=lfs diff=lfs merge=lfs -text
20
+ *.ot filter=lfs diff=lfs merge=lfs -text
21
+ *.parquet filter=lfs diff=lfs merge=lfs -text
22
+ *.pb filter=lfs diff=lfs merge=lfs -text
23
+ *.pickle filter=lfs diff=lfs merge=lfs -text
24
+ *.pkl filter=lfs diff=lfs merge=lfs -text
25
+ *.pt filter=lfs diff=lfs merge=lfs -text
26
+ *.pth filter=lfs diff=lfs merge=lfs -text
27
+ *.rar filter=lfs diff=lfs merge=lfs -text
28
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
29
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
30
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
31
+ *.tar filter=lfs diff=lfs merge=lfs -text
32
+ *.tflite filter=lfs diff=lfs merge=lfs -text
33
+ *.tgz filter=lfs diff=lfs merge=lfs -text
34
+ *.wasm filter=lfs diff=lfs merge=lfs -text
35
+ *.xz filter=lfs diff=lfs merge=lfs -text
36
+ *.zip filter=lfs diff=lfs merge=lfs -text
37
+ *.zst filter=lfs diff=lfs merge=lfs -text
38
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
39
+ # Audio files - uncompressed
40
+ *.pcm filter=lfs diff=lfs merge=lfs -text
41
+ *.sam filter=lfs diff=lfs merge=lfs -text
42
+ *.raw filter=lfs diff=lfs merge=lfs -text
43
+ # Audio files - compressed
44
+ *.aac filter=lfs diff=lfs merge=lfs -text
45
+ *.flac filter=lfs diff=lfs merge=lfs -text
46
+ *.mp3 filter=lfs diff=lfs merge=lfs -text
47
+ *.ogg filter=lfs diff=lfs merge=lfs -text
48
+ *.wav filter=lfs diff=lfs merge=lfs -text
49
+ # Image files - uncompressed
50
+ *.bmp filter=lfs diff=lfs merge=lfs -text
51
+ *.gif filter=lfs diff=lfs merge=lfs -text
52
+ *.png filter=lfs diff=lfs merge=lfs -text
53
+ *.tiff filter=lfs diff=lfs merge=lfs -text
54
+ # Image files - compressed
55
+ *.jpg filter=lfs diff=lfs merge=lfs -text
56
+ *.jpeg filter=lfs diff=lfs merge=lfs -text
57
+ *.webp filter=lfs diff=lfs merge=lfs -text
58
+ # Video files - compressed
59
+ *.mp4 filter=lfs diff=lfs merge=lfs -text
60
+ *.webm filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: OccludeBench
3
+ language:
4
+ - en
5
+ task_categories:
6
+ - visual-question-answering
7
+ - image-to-text
8
+ size_categories:
9
+ - n<1K
10
+ tags:
11
+ - occlusion
12
+ - visual-reasoning
13
+ - shadows
14
+ - reflections
15
+ - vision-language-models
16
+ configs:
17
+ - config_name: default
18
+ data_files:
19
+ - split: test
20
+ path: images/occluded/*
21
+ ---
22
+
23
+ # OccludeBench: Can VLMs See the Hint?
24
+
25
+ OccludeBench tests whether vision-language models use the specific visual evidence a question requires. Each of the 378 real photographs has one object fully hidden behind a drawn mask, and the model is asked to name it:
26
+
27
+ > What is the primary object that is completely occluded in this image? Be as specific as you can.
28
+
29
+ - **Direct** (197 images): the hidden object can only be recovered from a single visual cue, its shadow or its reflection.
30
+ - **Inferential** (181 images): the hidden object can be inferred from the surrounding scene.
31
+
32
+ Answers are open-ended and graded by an LLM judge against the reference answer.
33
+
34
+ ## Contents
35
+
36
+ | Path | Images | Used for |
37
+ |---|---|---|
38
+ | `images/occluded/` | 378 | Benchmark input: target object hidden by a black mask with a yellow border |
39
+ | `images/original/` | 378 | Unedited photographs |
40
+ | `images/unmasked/` | 378 | Mask drawn as an outline only, contents visible (localization control) |
41
+ | `images/cue_removed/` | 131 | Shadow/reflection edited out in Photoshop, then occluded (129 direct, 2 inferential) |
42
+ | `images/highlighted_cue/` | 136 | Direct images with the shadow/reflection region outlined (projection-region probe) |
43
+ | `images/blue_box/` | 378 | Mask filled blue with a yellow border (sensitivity to mask style) |
44
+ | `annotations.json` | | One record per image (fields below) |
45
+ | `code/` | | Evaluation, judging and analysis code for every experiment in the paper |
46
+
47
+ Images in every folder share the same `id`-based file name, e.g. `images/occluded/pic0001.png` and `images/original/pic0001.png`.
48
+
49
+ ## Annotations
50
+
51
+ `annotations.json` is a list of 378 records:
52
+
53
+ | Field | Description |
54
+ |---|---|
55
+ | `id` | Image id, `pic0001`–`pic0378` |
56
+ | `type` | `direct` or `inferential` |
57
+ | `category` | Direct: `specular reflection`, `diffuse reflection`, `shadow`. Inferential: `technology`, `household`, `culture`, `activities`, `nature` |
58
+ | `fine_category` | Finer annotation label the category was merged from |
59
+ | `answer` | Reference answer |
60
+ | `occluders` | Mask geometry in original-image pixels: `bbox` (`x1`, `y1`, `x2`, `y2`) or `polygon` (`points`) |
61
+ | `images` | Paths to this item's image in each folder (`null` where a variant does not exist) |
62
+ | `source_url` | Where the photograph was found |
63
+ | `annotator_note` | Annotator's rationale for the answer |
64
+
65
+ | Type | Category | Images |
66
+ |---|---|---|
67
+ | Direct | Specular reflection | 94 |
68
+ | Direct | Diffuse reflection | 56 |
69
+ | Direct | Shadow | 47 |
70
+ | Inferential | Technology | 45 |
71
+ | Inferential | Household | 44 |
72
+ | Inferential | Culture | 37 |
73
+ | Inferential | Activities | 31 |
74
+ | Inferential | Nature | 24 |
75
+
76
+ ## Loading
77
+
78
+ ```python
79
+ from datasets import load_dataset
80
+
81
+ ds = load_dataset("afs07fda89sdfas90/data", split="test") # occluded images + id, type, category, answer
82
+ ```
83
+
84
+ Or read `annotations.json` directly and open the image paths it lists.
85
+
86
+ ## Reproducing the experiments
87
+
88
+ ```bash
89
+ cd code
90
+ pip install -r requirements.txt
91
+ cp .env.example .env # API keys
92
+ python prepare_data.py # lays out the images the way the scripts expect
93
+ ```
94
+
95
+ `code/README.md` maps each section, table and figure of the paper to the script that produces it.
96
+
97
+ ## Grading
98
+
99
+ A response counts as correct if either of two judges (Claude Opus 4.6, GPT-5.4) accepts it as the same object as the reference answer. This ensemble agrees with author labels on 98% of items. The judge prompt is in `code/sec3_occludebench/judger_script.py`.
100
+
101
+ ## Notes
102
+
103
+ - `pic0360`: its occluded and unmasked images were made from a differently cropped copy of the photograph, so its `occluders` coordinates match `images/original/` and `images/blue_box/` but not `images/occluded/` or `images/unmasked/`.
104
+
105
+ ## Sources
106
+
107
+ Images come from the web, Visual Genome, and the authors' own photographs. Web images remain under their original owners' terms; see `source_url`.
annotations.json ADDED
The diff for this file is too large to render. See raw diff
 
code/.env.example ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ OpenAI_API_KEY=
2
+ Anthropic_API_KEY=
3
+ Gemini_API_KEY=
4
+ Together_API_KEY=
code/README.md ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # OccludeBench: Can VLMs See the Hint?
2
+
3
+ Code for the experiments in the paper, organized by paper section.
4
+
5
+ ## Setup
6
+
7
+ ```bash
8
+ pip install -r requirements.txt
9
+ cp .env.example .env # fill in API keys
10
+ python prepare_data.py # lays out the released images the way the scripts expect
11
+ ```
12
+
13
+ Run everything from this `code/` folder, e.g. `python sec3_occludebench/eval_script.py --model gpt-5.4`. The shell wrappers `cd` here themselves, and each notebook does so in its first cell.
14
+
15
+ Models: `gpt-5.4`, `claude-opus-4-6`, `gemini-3.1-pro-preview`, and Llama 4 Maverick / Qwen3-VL-8B via Together.
16
+
17
+ ## Layout
18
+
19
+ ### §3 OccludeBench: `sec3_occludebench/`
20
+
21
+ | Paper | Code |
22
+ |---|---|
23
+ | Dataset distribution (§3.1) | `image_category_plots.ipynb` |
24
+ | Main occluded query + reflection follow-up (§3.2, App. A) | `eval_script.py` |
25
+ | Occluder follow-up for Llama / Qwen responses that name the mask itself | `vetter_script.py` |
26
+ | Two-judge grading, Claude Opus 4.6 + GPT-5.4 (§3.2, App. A) | `judger_script.py` |
27
+ | Human baseline grading (§3.3) | `human_baseline/judger_human.py` |
28
+ | Human accuracy and per-image difficulty distribution (§4.1, App. D) | `human_baseline/human_accuracy_breakdown_pub_quality.ipynb` |
29
+
30
+ ### §4.1 Main Results: `sec4_1_main_results/`
31
+
32
+ | Paper | Code |
33
+ |---|---|
34
+ | Occluded + unmasked runs, all five models | `run_all_evals.sh` |
35
+ | Accuracy tables (occluded / unmasked, human solvability) | `accuracy_breakdown_pub_quality.ipynb` |
36
+ | Fig. 4: accuracy across base / thinking / tool use / steering | `nudge_comparison.ipynb` |
37
+ | Localization control, unmasked bounding box (Table 1) | `localization_unmasked/generate_transparent.py`, `localization_unmasked/eval_transparent.py` |
38
+ | Per-category accuracy + chi-square tests (Fig. 5, App. B) | `category_accuracy/accuracy_by_category.ipynb` |
39
+ | Model vs. human difficulty (Fig. 6) | `human_model_correlation/human_model_difficulty_correlation.ipynb` |
40
+
41
+ ### §4.2 Why do VLMs fail?: `sec4_2_why_vlms_fail/`
42
+
43
+ | Paper | Code |
44
+ |---|---|
45
+ | Tool-trace failure modes (App. H) | `tool_trace_failures/build_visualizer.py` |
46
+ | Cue removal (Table 1) | `cue_removal/run_cue_removed_eval.sh`, `cue_removal/accuracy_breakdown_physical.ipynb` |
47
+ | Seeing failure rate on the highlighted projection region (Table 1) | `seeing_failure/eval_wrong_transparent.py`, `seeing_failure/judge_wrong_transparent.py` |
48
+ | Stage 1: cue detection (Table 2) | `stage1_cue_detection/` |
49
+ | Stage 2: zoomed-in object recognition (Table 2) | `stage2_zoomed_recognition/` (`app.py` is the manual cropping tool) |
50
+ | Stage 3: source mapping (Table 2) | `stage3_source_mapping/` (`map_eval.py`, `reverse_map_eval.py`) |
51
+ | Stage 4: highlighted-region recovery (Table 2) | `stage4_highlighted_region/` |
52
+
53
+ ### §4.3 Can we improve performance on direct images?: `sec4_3_improvements/`
54
+
55
+ | Paper | Code |
56
+ |---|---|
57
+ | Fig. 8: improvement summary | `accuracy_improvements.ipynb` |
58
+ | Extended reasoning | `extended_reasoning/` |
59
+ | Tool use + tool-call analysis (Fig. 7, App. G) | `tool_use/` (`run_tool_use_eval.sh`; the paper's run used `OUTPUT_DIR=data/eval_results_tool_use_thinking_v2`) |
60
+ | Agentic harness, Codex + GPT-5.4 | `coding_agents/coding_agent_eval.sh` (needs the Codex CLI) |
61
+ | Steering prompts, short and long (App. A) | `steering_prompts/run_nudge_eval.sh`, `steering_prompts/run_occlusion_nudge_eval.sh` |
62
+ | Few-shot prompting | `few_shot/` |
63
+ | Inpainting multi-step execution (Table 3) | `inpainting_multistep/` (`gap_analysis_final.py` computes the Fisher tests) |
64
+
65
+ ### Appendix: `appendix/`
66
+
67
+ | Paper | Code |
68
+ |---|---|
69
+ | Sensitivity to bounding-box style (App. C) | `box_sensitivity/` |
70
+ | Lexical analysis of answers (App. D) | `lexical_metrics/answer_lexical_metrics.py` |
71
+ | Token count vs. accuracy (App. E) | `token_length/token_length_vs_correctness_all_models_no_outliers.ipynb` |
72
+ | Image understanding vs. generation (App. F) | `image_generation/eval_image_gen.py` |
73
+ | Learning effects in the human survey (App. I) | `human_learning_effects/learning_effect_test.py` |
74
+
75
+ ## Paths
76
+
77
+ `prepare_data.py` builds `data/combined_output/` (`annotations.json` plus `<id>.<ext>`, `<id>_occluded.png`, `<id>_transparent.png`), `data/combined_output_blue/`, `data/physical_occluded_combined/` (cue removed), `data/annotated/` (highlighted cue region) and `data/Image categories (3).xlsx` from the dataset one level up. Scripts write results to `data/eval_results*/` and figures to `data/figures/`.
code/appendix/box_sensitivity/generate_occluded_blue.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Robustness-check variant of the occluded images: every occluder shape is
2
+ filled BLUE with a YELLOW border, regardless of the colors stored in the
3
+ annotations. Geometry (bbox/polygon positions) is taken verbatim from
4
+ annotations.json so only the occluder color changes vs. the original
5
+ `_occluded.png` set."""
6
+ import json
7
+ import shutil
8
+ from pathlib import Path
9
+ from PIL import Image, ImageDraw
10
+
11
+ SRC_DIR = Path("data/combined_output")
12
+ ANNOTATIONS_PATH = SRC_DIR / "annotations.json"
13
+ OUT_DIR = Path("data/combined_output_blue")
14
+
15
+ FILL_COLOR = "#0000ff" # blue interior
16
+ BORDER_COLOR = "#eeff00" # yellow border
17
+ BORDER_WIDTH = 2
18
+
19
+ OUT_DIR.mkdir(exist_ok=True)
20
+ # eval_script.py reads annotations.json from the data_dir
21
+ shutil.copy(ANNOTATIONS_PATH, OUT_DIR / "annotations.json")
22
+
23
+ with open(ANNOTATIONS_PATH) as f:
24
+ data = json.load(f)
25
+
26
+ made = 0
27
+ for entry in data:
28
+ original_file = SRC_DIR / entry["original_file"]
29
+ if not original_file.exists():
30
+ print(f"Missing original: {original_file}")
31
+ continue
32
+
33
+ img = Image.open(original_file).convert("RGBA")
34
+ overlay = Image.new("RGBA", img.size, (0, 0, 0, 0))
35
+ draw = ImageDraw.Draw(overlay)
36
+
37
+ for ann in entry["annotations"]:
38
+ if ann["type"] == "bbox":
39
+ draw.rectangle(
40
+ [ann["x1"], ann["y1"], ann["x2"], ann["y2"]],
41
+ outline=BORDER_COLOR,
42
+ fill=FILL_COLOR,
43
+ width=BORDER_WIDTH,
44
+ )
45
+ elif ann["type"] == "polygon":
46
+ points = [(p["x"], p["y"]) for p in ann["points"]]
47
+ draw.polygon(points, outline=BORDER_COLOR, fill=FILL_COLOR)
48
+ # thicken the outline to match the border width used elsewhere
49
+ draw.line(points + [points[0]], fill=BORDER_COLOR, width=BORDER_WIDTH)
50
+
51
+ result = Image.alpha_composite(img, overlay).convert("RGB")
52
+ out_path = OUT_DIR / f"{original_file.stem}_occluded.png"
53
+ result.save(out_path)
54
+ made += 1
55
+
56
+ print(f"Done. Generated {made} blue-occluded images in {OUT_DIR}/")
code/appendix/box_sensitivity/run_blue_robustness.sh ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Robustness check: original occluded-object task, but occluders are blue-filled
3
+ # with a yellow border. Runs the 3 frontier models, then judges with the same
4
+ # two judges used for the main results (gpt-5.4 + claude-opus-4-6).
5
+ set -e
6
+ cd "$(dirname "$0")/../.."
7
+
8
+ DATA_DIR="data/combined_output_blue"
9
+ OUT_DIR="data/eval_results_blue"
10
+ mkdir -p "$OUT_DIR"
11
+
12
+ models=("gpt-5.4" "claude-opus-4-6" "gemini-3.1-pro-preview")
13
+
14
+ echo "=== Running evals (blue occluders) ==="
15
+ for m in "${models[@]}"; do
16
+ echo ">>> $m"
17
+ python -u sec3_occludebench/eval_script.py --model "$m" --data_dir "$DATA_DIR" --output_dir "$OUT_DIR"
18
+ done
19
+
20
+ echo "=== Judging ==="
21
+ python -u sec3_occludebench/judger_script.py \
22
+ --results_dir "$OUT_DIR" \
23
+ --output_dir "$OUT_DIR" \
24
+ --judge_models gpt-5.4 claude-opus-4-6
25
+
26
+ echo "=== Blue robustness run complete ==="
code/appendix/human_learning_effects/learning_effect_test.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Does human accuracy improve over the 6 questions each Prolific
3
+ participant answered? (learning / familiarity effect vs. stagnation)
4
+
5
+ Position (1..6) is derived from timestamp order within each participant.
6
+ Correctness = consensus_correct from the judged human results.
7
+
8
+ statsmodels is broken against the installed scipy, so the logistic regression
9
+ and its cluster-robust (by participant) standard errors are implemented by hand
10
+ via IRLS + a sandwich estimator.
11
+ """
12
+ import json
13
+ import os
14
+ import numpy as np
15
+ import pandas as pd
16
+ from scipy import stats
17
+
18
+ # ---- Load & join -----------------------------------------------------------
19
+ ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")
20
+ base = json.load(open(os.path.join(ROOT, "data/occlusion_prolific_human_baseline.json")))
21
+ judged = json.load(open(os.path.join(ROOT, "data/eval_results_human/human_prolific_judged_results.json")))
22
+
23
+ ts = {(r["prolific_pid"], r["image_id"]): r["timestamp"] for r in base}
24
+
25
+ rows = []
26
+ for r in judged:
27
+ key = (r["prolific_pid"], r["image_id"])
28
+ if key not in ts or r.get("consensus_correct") is None:
29
+ continue
30
+ rows.append({
31
+ "pid": r["prolific_pid"],
32
+ "image_id": r["image_id"],
33
+ "timestamp": ts[key],
34
+ "correct": int(bool(r["consensus_correct"])),
35
+ "rt_ms": r.get("response_time_ms"),
36
+ })
37
+
38
+ df = pd.DataFrame(rows)
39
+ df["timestamp"] = pd.to_datetime(df["timestamp"])
40
+ df = df.sort_values(["pid", "timestamp"])
41
+ df["position"] = df.groupby("pid").cumcount() + 1
42
+ df = df[df["position"] <= 6]
43
+
44
+ print(f"Joined responses: {len(df)} | participants: {df['pid'].nunique()}")
45
+
46
+ # ---- Accuracy by position --------------------------------------------------
47
+ print("\n=== Accuracy by question position ===")
48
+ g = df.groupby("position")["correct"].agg(["mean", "sum", "count"])
49
+ g["se"] = np.sqrt(g["mean"] * (1 - g["mean"]) / g["count"])
50
+ for pos, row in g.iterrows():
51
+ lo = row["mean"] - 1.96 * row["se"]
52
+ hi = row["mean"] + 1.96 * row["se"]
53
+ print(f" Q{pos}: acc={row['mean']:.3f} ({int(row['sum'])}/{int(row['count'])}) "
54
+ f"95% CI [{lo:.3f}, {hi:.3f}]")
55
+
56
+ # ---- Test 1: linear trend --------------------------------------------------
57
+ print("\n=== Test 1: Linear trend across positions ===")
58
+ r_pb, p_pb = stats.pointbiserialr(df["correct"], df["position"])
59
+ print(f" Point-biserial r(correct, position) = {r_pb:.4f}, p = {p_pb:.4f}")
60
+
61
+ counts = df.groupby("position")["correct"].agg(["sum", "count"])
62
+ n_i = counts["count"].values.astype(float)
63
+ x_i = counts.index.values.astype(float)
64
+ p1_i = counts["sum"].values.astype(float)
65
+ N = n_i.sum(); R = p1_i.sum(); pbar = R / N
66
+ xbar = (n_i * x_i).sum() / N
67
+ num = ((p1_i - n_i * pbar) * (x_i - xbar)).sum()
68
+ den = pbar * (1 - pbar) * (n_i * (x_i - xbar) ** 2).sum()
69
+ z_ca = num / np.sqrt(den)
70
+ p_ca = 2 * (1 - stats.norm.cdf(abs(z_ca)))
71
+ print(f" Cochran-Armitage trend: z = {z_ca:.3f}, p = {p_ca:.4f}")
72
+
73
+ # Q1 vs Q6 two-proportion z-test (first vs last)
74
+ def two_prop_z(s1, n1, s2, n2):
75
+ p1, p2 = s1 / n1, s2 / n2
76
+ pp = (s1 + s2) / (n1 + n2)
77
+ se = np.sqrt(pp * (1 - pp) * (1 / n1 + 1 / n2))
78
+ z = (p1 - p2) / se
79
+ return z, 2 * (1 - stats.norm.cdf(abs(z)))
80
+ z16, p16 = two_prop_z(counts.loc[1, "sum"], counts.loc[1, "count"],
81
+ counts.loc[6, "sum"], counts.loc[6, "count"])
82
+ print(f" Q1 vs Q6 two-proportion z = {z16:.3f}, p = {p16:.4f} "
83
+ f"(Q1={g.loc[1,'mean']:.3f} vs Q6={g.loc[6,'mean']:.3f})")
84
+
85
+ # ---- Test 2: logistic regression, cluster-robust SE by participant ---------
86
+ print("\n=== Test 2: Logistic correct ~ position (cluster-robust SE by pid) ===")
87
+ def logit_irls(X, y, iters=100, tol=1e-10):
88
+ beta = np.zeros(X.shape[1])
89
+ for _ in range(iters):
90
+ eta = X @ beta
91
+ mu = 1 / (1 + np.exp(-eta))
92
+ W = mu * (1 - mu)
93
+ WX = X * W[:, None]
94
+ H = X.T @ WX
95
+ grad = X.T @ (y - mu)
96
+ step = np.linalg.solve(H, grad)
97
+ beta += step
98
+ if np.max(np.abs(step)) < tol:
99
+ break
100
+ return beta, mu
101
+
102
+ y = df["correct"].values.astype(float)
103
+ X = np.column_stack([np.ones(len(df)), df["position"].values.astype(float)])
104
+ beta, mu = logit_irls(X, y)
105
+
106
+ # cluster-robust (sandwich) covariance, clustered by participant
107
+ W = mu * (1 - mu)
108
+ bread = np.linalg.inv((X * W[:, None]).T @ X)
109
+ u = X * (y - mu)[:, None] # score contributions
110
+ meat = np.zeros((X.shape[1], X.shape[1]))
111
+ pid_arr = df["pid"].values
112
+ for pid in np.unique(pid_arr):
113
+ idx = pid_arr == pid
114
+ ug = u[idx].sum(axis=0)
115
+ meat += np.outer(ug, ug)
116
+ cov = bread @ meat @ bread
117
+ se = np.sqrt(np.diag(cov))
118
+ z = beta / se
119
+ pvals = 2 * (1 - stats.norm.cdf(np.abs(z)))
120
+ print(f" intercept: coef={beta[0]:.4f} se={se[0]:.4f}")
121
+ print(f" position : coef={beta[1]:.4f} se={se[1]:.4f} OR={np.exp(beta[1]):.4f} "
122
+ f"z={z[1]:.3f} p={pvals[1]:.4f}")
123
+ print(f" -> OR>1 = improvement over questions; OR≈1 & p>.05 = stagnation")
124
+
125
+ # ---- Secondary: response time by position ----------------------------------
126
+ print("\n=== Secondary: response time by position (speed-up = familiarity) ===")
127
+ rtdf = df.dropna(subset=["rt_ms"])
128
+ for pos, v in rtdf.groupby("position")["rt_ms"].median().items():
129
+ print(f" Q{pos}: median RT = {v/1000:.1f}s")
130
+ r_rt, p_rt = stats.spearmanr(rtdf["position"], rtdf["rt_ms"])
131
+ print(f" Spearman(position, RT) = {r_rt:.4f}, p = {p_rt:.4g}")
code/appendix/image_generation/eval_image_gen.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import base64
3
+ import io
4
+ import json
5
+ import os
6
+ from google import genai
7
+ from google.genai import types
8
+ from openai import OpenAI
9
+ from dotenv import load_dotenv
10
+ from PIL import Image
11
+
12
+ load_dotenv()
13
+ Gemini_API_KEY = os.getenv("Gemini_API_KEY")
14
+ OpenAI_API_KEY = os.getenv("OpenAI_API_KEY")
15
+
16
+ GEMINI_GEN_MODEL = "gemini-3-pro-image-preview"
17
+
18
+ JUDGE_RESULTS = {
19
+ "gemini": "data/eval_results/gemini-3.1-pro-preview_judged_results.json",
20
+ "gpt": "data/eval_results/gpt-5.4_judged_results.json",
21
+ }
22
+
23
+ ANNOTATIONS_PATH = "data/combined_output/annotations.json"
24
+
25
+ GEN_PROMPT = (
26
+ "This image has a black region covering something. "
27
+ "Generate a new version of this image with the hidden object "
28
+ "naturally visible in place of the black region, keeping everything "
29
+ "else in the image exactly the same."
30
+ )
31
+
32
+
33
+ def load_qualifying_ids(judge_results_path, annotations_path):
34
+ with open(judge_results_path) as f:
35
+ judged = json.load(f)
36
+ with open(annotations_path) as f:
37
+ annotations = json.load(f)
38
+
39
+ phys_map = {str(a["id"]): a["physical"] for a in annotations}
40
+ orig_map = {str(a["id"]): a["original_file"] for a in annotations}
41
+
42
+ qualifying = []
43
+ for item in judged:
44
+ item_id = str(item["id"])
45
+ if phys_map.get(item_id):
46
+ qualifying.append({
47
+ "id": item_id,
48
+ "original_file": orig_map.get(item_id, ""),
49
+ "ground_truth": item["ground_truth"],
50
+ })
51
+ return qualifying
52
+
53
+
54
+ def encode_image_bytes(image_path, max_bytes=3.5 * 1024 * 1024):
55
+ with open(image_path, "rb") as f:
56
+ data = f.read()
57
+ if len(data) <= max_bytes:
58
+ return data
59
+ img = Image.open(io.BytesIO(data))
60
+ scale = 0.9
61
+ while True:
62
+ buf = io.BytesIO()
63
+ img.save(buf, format="PNG", optimize=True)
64
+ if buf.tell() <= max_bytes:
65
+ return buf.getvalue()
66
+ w, h = img.size
67
+ img = img.resize((int(w * scale), int(h * scale)), Image.LANCZOS)
68
+
69
+
70
+ def generate_gemini(client, image_bytes):
71
+ prompt = GEN_PROMPT
72
+ image_part = types.Part.from_bytes(data=image_bytes, mime_type="image/png")
73
+ response = client.models.generate_content(
74
+ model=GEMINI_GEN_MODEL,
75
+ contents=[image_part, prompt],
76
+ config=types.GenerateContentConfig(
77
+ response_modalities=["IMAGE", "TEXT"],
78
+ ),
79
+ )
80
+ for part in response.candidates[0].content.parts:
81
+ if part.inline_data is not None:
82
+ return part.inline_data.data
83
+ return None
84
+
85
+
86
+ def generate_gpt(client, image_bytes):
87
+ prompt = GEN_PROMPT
88
+ b64 = base64.b64encode(image_bytes).decode("utf-8")
89
+ response = client.responses.create(
90
+ model="gpt-5.4",
91
+ input=[{
92
+ "role": "user",
93
+ "content": [
94
+ {"type": "input_image", "image_url": f"data:image/png;base64,{b64}"},
95
+ {"type": "input_text", "text": prompt},
96
+ ],
97
+ }],
98
+ tools=[{"type": "image_generation"}],
99
+ )
100
+ for item in response.output:
101
+ if item.type == "image_generation_call":
102
+ return base64.b64decode(item.result)
103
+ return None
104
+
105
+
106
+ def run_eval(args):
107
+ provider = args.model
108
+ judge_results_path = JUDGE_RESULTS[provider]
109
+ qualifying = load_qualifying_ids(judge_results_path, args.annotations)
110
+ print(f"[{provider}] {len(qualifying)} qualifying items.")
111
+
112
+ output_dir = os.path.join(args.output_dir, provider)
113
+ os.makedirs(output_dir, exist_ok=True)
114
+ metadata_path = os.path.join(output_dir, "metadata.json")
115
+
116
+ if os.path.exists(metadata_path):
117
+ with open(metadata_path) as f:
118
+ metadata = json.load(f)
119
+ done_ids = {r["id"] for r in metadata}
120
+ print(f"Resuming: {len(done_ids)} done, {len(qualifying) - len(done_ids)} remaining.")
121
+ else:
122
+ metadata = []
123
+ done_ids = set()
124
+
125
+ if provider == "gemini":
126
+ client = genai.Client(api_key=Gemini_API_KEY)
127
+ generate_fn = generate_gemini
128
+ else:
129
+ client = OpenAI(api_key=OpenAI_API_KEY)
130
+ generate_fn = generate_gpt
131
+
132
+ for item in qualifying:
133
+ item_id = item["id"]
134
+ if item_id in done_ids:
135
+ continue
136
+
137
+ base = os.path.splitext(item["original_file"])[0]
138
+ occluded_path = os.path.join(args.data_dir, f"{base}_occluded.png")
139
+
140
+ if not os.path.exists(occluded_path):
141
+ print(f" [SKIP] Not found: {occluded_path}")
142
+ continue
143
+
144
+ print(f"Generating for {item_id} (GT: {item['ground_truth']})...")
145
+ image_bytes = encode_image_bytes(occluded_path)
146
+
147
+ try:
148
+ generated_bytes = generate_fn(client, image_bytes)
149
+ except Exception as e:
150
+ print(f" [ERROR] {e}")
151
+ continue
152
+
153
+ if generated_bytes is None:
154
+ print(f" [WARN] No image returned for {item_id}")
155
+ continue
156
+
157
+ out_path = os.path.join(output_dir, f"{item_id}_generated.png")
158
+ with open(out_path, "wb") as f:
159
+ f.write(generated_bytes)
160
+ print(f" Saved: {out_path}")
161
+
162
+ metadata.append({
163
+ "id": item_id,
164
+ "ground_truth": item["ground_truth"],
165
+ "original_file": item["original_file"],
166
+ "generated_file": f"{item_id}_generated.png",
167
+ })
168
+
169
+ with open(metadata_path, "w") as f:
170
+ json.dump(metadata, f, indent=2)
171
+
172
+ print(f"\nDone. {len(metadata)} images in {output_dir}/")
173
+
174
+
175
+ def parse_args():
176
+ parser = argparse.ArgumentParser()
177
+ parser.add_argument("--model", type=str, default="gemini", choices=["gemini", "gpt"])
178
+ parser.add_argument("--data_dir", type=str, default="data/combined_output")
179
+ parser.add_argument("--annotations", type=str, default=ANNOTATIONS_PATH)
180
+ parser.add_argument("--output_dir", type=str, default="data/eval_results_image_gen")
181
+ return parser.parse_args()
182
+
183
+
184
+ if __name__ == "__main__":
185
+ args = parse_args()
186
+ run_eval(args)
code/appendix/lexical_metrics/answer_lexical_metrics.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Are the ground-truth answers for DIRECT (reflection/shadow) images
3
+ really more "niche and abstract" than the INFERENTIAL ones?
4
+
5
+ We quantify each answer string with a SUITE of objective lexical norms and
6
+ compare the direct vs inferential groups (and physical vs non-physical as a
7
+ secondary cut). No single metric is decisive on its own; convergence across
8
+ several is the point.
9
+
10
+ Metrics (per answer, aggregated over its content words):
11
+ 1. Zipf frequency (wordfreq) higher = more COMMON
12
+ 2. Concreteness (Brysbaert 2014) higher = more CONCRETE (less abstract)
13
+ 3. Word prevalence (Brysbaert %known) higher = fewer people find it NICHE
14
+ 4. Valence (neutrality) (Warriner VAD) abstract words are more affect-loaded
15
+ 5. Word length (chars) higher = more complex
16
+ 6. Syllable count (CMUdict) higher = more complex
17
+ 7. Answer token count higher = more verbose/specific
18
+ 8. Out-of-norms rate fraction of words absent from the
19
+ 40k-word norms = a direct RARITY proxy
20
+ """
21
+ import json
22
+ import os
23
+ import re
24
+ import numpy as np
25
+ import pandas as pd
26
+ from scipy import stats
27
+ from wordfreq import zipf_frequency
28
+ from nltk.corpus import cmudict
29
+ from nltk.stem import WordNetLemmatizer
30
+
31
+ HERE = os.path.dirname(os.path.abspath(__file__))
32
+ ROOT = os.path.join(HERE, "..", "..")
33
+
34
+ CMU = cmudict.dict()
35
+ LEM = WordNetLemmatizer()
36
+ STOP = {"a", "an", "the", "of", "and", "or", "with", "in", "on", "to", "for",
37
+ "s", "its", "it", "is", "at", "by", "part"}
38
+
39
+ # ---- Norm tables -----------------------------------------------------------
40
+ conc = pd.read_csv(os.path.join(HERE, "norms/concreteness.csv"), sep="\t")
41
+ CONC = dict(zip(conc["Word"].astype(str).str.lower(), conc["Conc.M"]))
42
+ PKNOWN = dict(zip(conc["Word"].astype(str).str.lower(), conc["Percent_known"]))
43
+ vad = pd.read_csv(os.path.join(HERE, "norms/warriner_vad.csv"))
44
+ VAL = dict(zip(vad["Word"].astype(str).str.lower(), vad["V.Mean.Sum"]))
45
+
46
+
47
+ def syllables(w):
48
+ w = w.lower()
49
+ if w in CMU:
50
+ return min(len([p for p in pr if p[-1].isdigit()]) for pr in CMU[w])
51
+ # heuristic fallback: count vowel groups
52
+ return max(1, len(re.findall(r"[aeiouy]+", w)))
53
+
54
+
55
+ def content_words(answer):
56
+ """Primary alternative (before first '/'), stripped of parentheticals,
57
+ lowercased, lemmatized, stopwords removed."""
58
+ primary = answer.split("/")[0]
59
+ primary = re.sub(r"\([^)]*\)", " ", primary)
60
+ toks = re.findall(r"[a-zA-Z]+", primary.lower())
61
+ words = [LEM.lemmatize(t) for t in toks if t not in STOP and len(t) > 1]
62
+ return words or [LEM.lemmatize(t) for t in toks] or toks
63
+
64
+
65
+ def metrics_for_answer(answer):
66
+ words = content_words(answer)
67
+ if not words:
68
+ return None
69
+ zipf = [zipf_frequency(w, "en") for w in words]
70
+ conc_v = [CONC[w] for w in words if w in CONC]
71
+ pk_v = [PKNOWN[w] for w in words if w in PKNOWN]
72
+ val_v = [VAL[w] for w in words if w in VAL]
73
+ oov = sum(1 for w in words if w not in CONC) / len(words)
74
+ return {
75
+ "zipf": np.mean(zipf),
76
+ "concreteness": np.mean(conc_v) if conc_v else np.nan,
77
+ "pct_known": np.mean(pk_v) if pk_v else np.nan,
78
+ "valence_neutrality": -abs(np.mean(val_v) - 5.0) if val_v else np.nan, # closer to neutral = higher
79
+ "word_len": np.mean([len(w) for w in words]),
80
+ "syllables": np.mean([syllables(w) for w in words]),
81
+ "n_tokens": len(words),
82
+ "oov_rate": oov,
83
+ }
84
+
85
+
86
+ # ---- Build the table -------------------------------------------------------
87
+ cat = pd.read_excel(os.path.join(ROOT, "data/Image categories (3).xlsx"))[["image id", "direct or inferential"]]
88
+ cat["image id"] = cat["image id"].astype(str)
89
+ di = dict(zip(cat["image id"], cat["direct or inferential"]))
90
+
91
+ ann = json.load(open(os.path.join(ROOT, "data/combined_output/annotations.json")))
92
+ rows = []
93
+ for e in ann:
94
+ iid = str(e["id"])
95
+ grp = di.get(iid)
96
+ if grp not in ("direct", "inferential"):
97
+ continue
98
+ answer = (e.get("answer") or "").strip()
99
+ if not answer:
100
+ continue
101
+ m = metrics_for_answer(answer)
102
+ if m is None:
103
+ continue
104
+ m.update({"id": iid, "group": grp, "physical": e.get("physical", False),
105
+ "answer": answer})
106
+ rows.append(m)
107
+
108
+ df = pd.DataFrame(rows)
109
+ print(f"Answers scored: {len(df)} "
110
+ f"(direct={ (df.group=='direct').sum() }, inferential={ (df.group=='inferential').sum() })\n")
111
+
112
+ METRICS = ["zipf", "concreteness", "pct_known", "valence_neutrality",
113
+ "word_len", "syllables", "n_tokens", "oov_rate"]
114
+ # For these, HIGHER means "more common / less niche / less abstract":
115
+ HIGHER_IS_COMMONER = {"zipf": True, "concreteness": True, "pct_known": True,
116
+ "valence_neutrality": True, "word_len": False,
117
+ "syllables": False, "n_tokens": False, "oov_rate": False}
118
+
119
+
120
+ def cliffs_delta(a, b):
121
+ a, b = np.asarray(a), np.asarray(b)
122
+ gt = sum((a[:, None] > b[None, :]).sum(axis=1))
123
+ lt = sum((a[:, None] < b[None, :]).sum(axis=1))
124
+ return (gt - lt) / (len(a) * len(b))
125
+
126
+
127
+ LABEL = {"zipf": "Zipf frequency (common?)", "concreteness": "Concreteness (1-5)",
128
+ "pct_known": "Word prevalence %known", "valence_neutrality": "Valence neutrality",
129
+ "word_len": "Word length (chars)", "syllables": "Syllables",
130
+ "n_tokens": "Answer token count", "oov_rate": "Out-of-norms rate"}
131
+
132
+
133
+ def bh_adjust(pvals):
134
+ p = np.asarray(pvals); n = len(p); order = np.argsort(p)
135
+ adj = np.empty(n); prev = 1.0
136
+ for rank, idx in enumerate(reversed(order)):
137
+ k = n - rank
138
+ prev = min(prev, p[idx] * n / k); adj[idx] = prev
139
+ return adj
140
+
141
+
142
+ def compare(df, col_a, col_b, label):
143
+ A = df[df.grpcol == col_a]; B = df[df.grpcol == col_b]
144
+ print(f"===== {label} ({col_a} n={len(A)} vs {col_b} n={len(B)}) =====")
145
+ print(f"{'metric':<26}{'mean_'+col_a:>13}{'mean_'+col_b:>15} MWU p BH-p Cliff d verdict for "+col_a)
146
+ raw = []
147
+ for m in METRICS:
148
+ a = A[m].dropna(); b = B[m].dropna()
149
+ _, p = stats.mannwhitneyu(a, b, alternative="two-sided")
150
+ raw.append(p)
151
+ bh = bh_adjust(raw)
152
+ for m, p, q in zip(METRICS, raw, bh):
153
+ a = A[m].dropna(); b = B[m].dropna()
154
+ d = cliffs_delta(a.values, b.values) # +d => col_a values larger
155
+ commoner = (d > 0) == HIGHER_IS_COMMONER[m] # sign-based, tie-proof
156
+ mag = abs(d)
157
+ strength = "≈equal" if mag < 0.05 or q >= 0.05 else \
158
+ ("A more common/concrete" if commoner else "A more niche/abstract")
159
+ star = "*" if q < 0.05 else " "
160
+ print(f"{LABEL[m]:<26}{a.mean():>13.3f}{b.mean():>15.3f} {p:>7.3g} {q:>6.3g}{star} {d:>+7.3f} {strength}")
161
+ print()
162
+
163
+
164
+ # Only comparison needed: direct/physical vs inferential/non-physical
165
+ # (in this dataset direct==physical and inferential==non-physical exactly).
166
+ df["grpcol"] = df["group"]
167
+ compare(df, "direct", "inferential",
168
+ "DIRECT/PHYSICAL vs INFERENTIAL/NON-PHYSICAL")
169
+
170
+ df.drop(columns=["grpcol"]).to_csv(os.path.join(HERE, "answer_lexical_metrics.csv"), index=False)
171
+ print("Per-answer metrics written to appendix/lexical_metrics/answer_lexical_metrics.csv")
172
+ print("\nNote: in this dataset every 'direct' answer is a physically-occluded image and\n"
173
+ "every 'inferential' answer is digitally-occluded, so the two axes coincide.")
code/appendix/token_length/token_length_vs_correctness_all_models_no_outliers.ipynb ADDED
@@ -0,0 +1,464 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "002bd99c",
6
+ "metadata": {},
7
+ "source": [
8
+ "# Token Length vs. Correctness — All Models (Occluded Condition, Outliers Removed)\n",
9
+ "\n",
10
+ "Same as the base notebook but with responses above the **95th percentile of token count (per model)** removed before all analyses."
11
+ ]
12
+ },
13
+ {
14
+ "cell_type": "code",
15
+ "execution_count": null,
16
+ "id": "91bf2e2a",
17
+ "metadata": {},
18
+ "outputs": [],
19
+ "source": [
20
+ "# Run from the repo root so the root-relative data paths below resolve\n",
21
+ "import os\n",
22
+ "from pathlib import Path\n",
23
+ "os.chdir(next(p for p in [Path.cwd(), *Path.cwd().parents] if (p / \"sec3_occludebench\").is_dir()))"
24
+ ]
25
+ },
26
+ {
27
+ "cell_type": "code",
28
+ "execution_count": null,
29
+ "id": "b2161508",
30
+ "metadata": {},
31
+ "outputs": [],
32
+ "source": [
33
+ "import json\n",
34
+ "import numpy as np\n",
35
+ "import pandas as pd\n",
36
+ "import matplotlib.pyplot as plt\n",
37
+ "import matplotlib.ticker as mtick\n",
38
+ "import seaborn as sns\n",
39
+ "from scipy import stats\n",
40
+ "from pathlib import Path\n",
41
+ "from sklearn.linear_model import LogisticRegression\n",
42
+ "from sklearn.preprocessing import StandardScaler\n",
43
+ "import warnings\n",
44
+ "warnings.filterwarnings('ignore')\n",
45
+ "\n",
46
+ "plt.rcParams['figure.dpi'] = 120\n",
47
+ "plt.rcParams.update({'font.family': 'Arial', 'font.size': 20})"
48
+ ]
49
+ },
50
+ {
51
+ "cell_type": "code",
52
+ "execution_count": null,
53
+ "id": "4a22f66a",
54
+ "metadata": {},
55
+ "outputs": [],
56
+ "source": [
57
+ "import subprocess, sys\n",
58
+ "subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'tiktoken', '-q'])"
59
+ ]
60
+ },
61
+ {
62
+ "cell_type": "code",
63
+ "execution_count": null,
64
+ "id": "80dff012",
65
+ "metadata": {},
66
+ "outputs": [],
67
+ "source": [
68
+ "import tiktoken\n",
69
+ "MODELS = ['claude-opus-4-6', 'gemini-3.1-pro-preview', 'gpt-5.4', 'Llama-4-Maverick-17B-128E-Instruct-FP8', 'Qwen3-VL-8B-Instruct']\n",
70
+ "\n",
71
+ "_enc = tiktoken.get_encoding('cl100k_base')\n",
72
+ "\n",
73
+ "def approx_tokens(text):\n",
74
+ " return len(_enc.encode(text)) if text else 0\n",
75
+ "\n",
76
+ "def load_model(model):\n",
77
+ " with open(Path(\"data/eval_results\") / f\"{model}_judged_results.json\") as f:\n",
78
+ " raw = json.load(f)\n",
79
+ " rows = []\n",
80
+ " for entry in raw:\n",
81
+ " occ_j = entry.get('occluded_correct', {})\n",
82
+ " rows.append({\n",
83
+ " 'id': entry['id'],\n",
84
+ " 'model': model,\n",
85
+ " 'tokens': approx_tokens(entry.get('occluded_response') or ''),\n",
86
+ " 'correct': any(occ_j.values()) if occ_j else False,\n",
87
+ " 'gpt': occ_j.get('gpt-5.4'),\n",
88
+ " 'claude': occ_j.get('claude-opus-4-6'),\n",
89
+ " })\n",
90
+ " return pd.DataFrame(rows)\n",
91
+ "\n",
92
+ "frames = [load_model(m) for m in MODELS]\n",
93
+ "raw_df = pd.concat(frames, ignore_index=True)\n",
94
+ "\n",
95
+ "PERCENTILE_CAP = 95\n",
96
+ "all_df = raw_df.groupby('model', group_keys=False).apply(\n",
97
+ " lambda g: g[g['tokens'] <= g['tokens'].quantile(PERCENTILE_CAP / 100)]\n",
98
+ ").reset_index(drop=True)\n",
99
+ "print(f\"Rows before: {len(raw_df)}, after p{PERCENTILE_CAP} cap: {len(all_df)}\")\n",
100
+ "\n",
101
+ "DISPLAY = {\n",
102
+ " 'claude-opus-4-6': 'Claude Opus 4-6',\n",
103
+ " 'gemini-3.1-pro-preview': 'Gemini 3.1 Pro',\n",
104
+ " 'gpt-5.4': 'GPT-5.4',\n",
105
+ " 'Llama-4-Maverick-17B-128E-Instruct-FP8': 'Llama-4 Maverick',\n",
106
+ " 'Qwen3-VL-8B-Instruct': 'Qwen3-VL-8B',\n",
107
+ "}\n",
108
+ "all_df['model_short'] = all_df['model'].map(DISPLAY)\n",
109
+ "MODEL_ORDER = [DISPLAY[m] for m in MODELS]\n",
110
+ "PALETTE = dict(zip(MODEL_ORDER, sns.color_palette('tab10', len(MODELS))))\n",
111
+ "\n",
112
+ "print(all_df.groupby('model_short')['correct'].mean().reindex(MODEL_ORDER).round(3))"
113
+ ]
114
+ },
115
+ {
116
+ "cell_type": "markdown",
117
+ "id": "7413a939",
118
+ "metadata": {},
119
+ "source": [
120
+ "## 1. Overall Accuracy by Model"
121
+ ]
122
+ },
123
+ {
124
+ "cell_type": "code",
125
+ "execution_count": null,
126
+ "id": "aca32425",
127
+ "metadata": {},
128
+ "outputs": [],
129
+ "source": [
130
+ "fig, ax = plt.subplots(figsize=(9, 5))\n",
131
+ "agg = all_df.groupby('model_short')['correct'].mean().reindex(MODEL_ORDER)\n",
132
+ "colors = [PALETTE[m] for m in MODEL_ORDER]\n",
133
+ "bars = ax.bar(MODEL_ORDER, agg, color=colors, edgecolor='grey', linewidth=0.6)\n",
134
+ "for bar, val in zip(bars, agg):\n",
135
+ " ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.01,\n",
136
+ " f'{val:.1%}', ha='center', va='bottom', fontsize=10)\n",
137
+ "ax.set_ylim(0, 1.1)\n",
138
+ "ax.set_ylabel('Accuracy (either judge)')\n",
139
+ "ax.set_title('Overall Occluded Accuracy by Model')\n",
140
+ "ax.set_xticklabels(MODEL_ORDER, rotation=15, ha='right')\n",
141
+ "ax.spines[['top', 'right']].set_visible(False)\n",
142
+ "plt.tight_layout()\n",
143
+ "plt.savefig('data/figures/token_length_no_outliers_overall_occluded_accuracy_by_model.pdf', bbox_inches='tight')\n",
144
+ "plt.show()"
145
+ ]
146
+ },
147
+ {
148
+ "cell_type": "markdown",
149
+ "id": "031744db",
150
+ "metadata": {},
151
+ "source": [
152
+ "## 2. Token Length Distribution by Correctness"
153
+ ]
154
+ },
155
+ {
156
+ "cell_type": "code",
157
+ "execution_count": null,
158
+ "id": "784c798c",
159
+ "metadata": {},
160
+ "outputs": [],
161
+ "source": [
162
+ "fig, axes = plt.subplots(1, len(MODELS), figsize=(4 * len(MODELS), 5), sharey=False)\n",
163
+ "fig.suptitle('Token Length by Correctness (Occluded)', fontsize=13)\n",
164
+ "\n",
165
+ "for ax, m in zip(axes, MODELS):\n",
166
+ " sub = all_df[all_df['model'] == m][['correct', 'tokens']].copy()\n",
167
+ " sub['correct'] = sub['correct'].map({True: 'Correct', False: 'Incorrect'})\n",
168
+ " sns.violinplot(data=sub, x='correct', y='tokens',\n",
169
+ " order=['Incorrect', 'Correct'],\n",
170
+ " palette={'Correct': '#4CAF50', 'Incorrect': '#F44336'},\n",
171
+ " inner='box', ax=ax)\n",
172
+ " ax.set_title(DISPLAY[m], fontsize=10)\n",
173
+ " ax.set_xlabel('')\n",
174
+ " ax.set_ylabel('Approx. Tokens' if ax == axes[0] else '')\n",
175
+ " ax.spines[['top', 'right']].set_visible(False)\n",
176
+ "\n",
177
+ "plt.tight_layout()\n",
178
+ "plt.savefig('data/figures/token_length_no_outliers_token_length_by_correctness_occluded.pdf', bbox_inches='tight')\n",
179
+ "plt.show()"
180
+ ]
181
+ },
182
+ {
183
+ "cell_type": "markdown",
184
+ "id": "4f96d425",
185
+ "metadata": {},
186
+ "source": [
187
+ "## 3. Point-Biserial Correlation (Token Length ↔ Correctness)"
188
+ ]
189
+ },
190
+ {
191
+ "cell_type": "code",
192
+ "execution_count": null,
193
+ "id": "120c5456",
194
+ "metadata": {},
195
+ "outputs": [],
196
+ "source": [
197
+ "corr_rows = []\n",
198
+ "for m in MODELS:\n",
199
+ " s = all_df[all_df['model'] == m][['tokens', 'correct']].dropna()\n",
200
+ " r, p = stats.pointbiserialr(s['correct'].astype(int), s['tokens'])\n",
201
+ " corr_rows.append({'Model': DISPLAY[m], 'r': r, 'p': p,\n",
202
+ " 'sig': '***' if p<0.001 else '**' if p<0.01 else '*' if p<0.05 else ''})\n",
203
+ "\n",
204
+ "corr_df = pd.DataFrame(corr_rows)\n",
205
+ "print(corr_df.to_string(index=False))\n",
206
+ "\n",
207
+ "fig, ax = plt.subplots(figsize=(9, 5))\n",
208
+ "colors = [PALETTE[DISPLAY[m]] for m in MODELS]\n",
209
+ "bars = ax.bar(corr_df['Model'], corr_df['r'], color=colors, edgecolor='grey', lw=0.5)\n",
210
+ "for bar, row in zip(bars, corr_df.itertuples()):\n",
211
+ " ax.text(bar.get_x() + bar.get_width()/2,\n",
212
+ " bar.get_height() + (0.004 if row.r >= 0 else -0.012),\n",
213
+ " f'{row.r:.3f}{row.sig}', ha='center', va='bottom', fontsize=9)\n",
214
+ "ax.axhline(0, color='black', lw=0.8)\n",
215
+ "ax.set_ylabel('Point-Biserial r')\n",
216
+ "ax.set_title('Point-Biserial Correlation: Token Length ↔ Correctness')\n",
217
+ "ax.set_xticklabels(corr_df['Model'], rotation=15, ha='right')\n",
218
+ "ax.spines[['top', 'right']].set_visible(False)\n",
219
+ "plt.tight_layout()\n",
220
+ "plt.savefig('data/figures/token_length_no_outliers_point_biserial_correlation_token_length_correctnes.pdf', bbox_inches='tight')\n",
221
+ "plt.show()"
222
+ ]
223
+ },
224
+ {
225
+ "cell_type": "markdown",
226
+ "id": "703f3ab6",
227
+ "metadata": {},
228
+ "source": [
229
+ "## 4. Scatter + Logistic Regression Curve"
230
+ ]
231
+ },
232
+ {
233
+ "cell_type": "code",
234
+ "execution_count": null,
235
+ "id": "9abf68c3",
236
+ "metadata": {},
237
+ "outputs": [],
238
+ "source": [
239
+ "fig, axes = plt.subplots(1, len(MODELS), figsize=(4.2 * len(MODELS), 4.5), sharey=True)\n",
240
+ "fig.suptitle('P(Correct) vs Token Length — Occluded', fontsize=13)\n",
241
+ "\n",
242
+ "for ax, m in zip(axes, MODELS):\n",
243
+ " sub = all_df[all_df['model'] == m][['tokens', 'correct']].dropna()\n",
244
+ " X = sub['tokens'].values\n",
245
+ " y = sub['correct'].astype(int).values\n",
246
+ " jitter = np.random.default_rng(42).uniform(-0.025, 0.025, len(y))\n",
247
+ " colors = ['#4CAF50' if c else '#F44336' for c in y]\n",
248
+ " ax.scatter(X, y + jitter, c=colors, alpha=0.3, s=14, edgecolors='none')\n",
249
+ "\n",
250
+ " scaler = StandardScaler()\n",
251
+ " lr = LogisticRegression()\n",
252
+ " lr.fit(scaler.fit_transform(X.reshape(-1, 1)), y)\n",
253
+ " xr = np.linspace(X.min(), X.max(), 300)\n",
254
+ " ph = lr.predict_proba(scaler.transform(xr.reshape(-1, 1)))[:, 1]\n",
255
+ " ax.plot(xr, ph, color='navy', lw=2)\n",
256
+ "\n",
257
+ " r, p = stats.pointbiserialr(y, X)\n",
258
+ " ax.set_title(f'{DISPLAY[m]}\\nr={r:.3f}, p={p:.2e}', fontsize=9)\n",
259
+ " ax.set_xlabel('Approx. Tokens')\n",
260
+ " if ax == axes[0]:\n",
261
+ " ax.set_ylabel('Correct')\n",
262
+ " ax.set_yticks([0, 1])\n",
263
+ " ax.set_yticklabels(['No', 'Yes'])\n",
264
+ " ax.spines[['top', 'right']].set_visible(False)\n",
265
+ "\n",
266
+ "plt.tight_layout()\n",
267
+ "plt.savefig('data/figures/token_length_no_outliers_p_correct_vs_token_length_occluded.pdf', bbox_inches='tight')\n",
268
+ "plt.show()"
269
+ ]
270
+ },
271
+ {
272
+ "cell_type": "markdown",
273
+ "id": "4ba925a0",
274
+ "metadata": {},
275
+ "source": [
276
+ "## 5. Accuracy by Token-Length Quintile"
277
+ ]
278
+ },
279
+ {
280
+ "cell_type": "code",
281
+ "execution_count": null,
282
+ "id": "700a945c",
283
+ "metadata": {},
284
+ "outputs": [],
285
+ "source": [
286
+ "fig, axes = plt.subplots(1, len(MODELS), figsize=(5.5 * len(MODELS), 6), sharey=True)\n",
287
+ "fig.suptitle('Accuracy by Token-Length Quintile — Occluded', fontsize=20)\n",
288
+ "\n",
289
+ "for ax, m in zip(axes, MODELS):\n",
290
+ " sub = all_df[all_df['model'] == m][['tokens', 'correct']].dropna().copy()\n",
291
+ " sub['q'] = pd.qcut(sub['tokens'], q=5, labels=['Q1','Q2','Q3','Q4','Q5'])\n",
292
+ " agg = sub.groupby('q', observed=True)['correct'].agg(['mean','count']).reset_index()\n",
293
+ " colors = plt.cm.RdYlGn(np.linspace(0.2, 0.8, len(agg)))\n",
294
+ " bars = ax.bar(agg['q'], agg['mean'], color=colors, edgecolor='grey', lw=0.5)\n",
295
+ " for bar, row in zip(bars, agg.itertuples()):\n",
296
+ " ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.01,\n",
297
+ " f'{row.mean:.0%}', ha='center', va='bottom', fontsize=14)\n",
298
+ " ax.set_ylim(0, 1.2)\n",
299
+ " ax.yaxis.set_major_formatter(mtick.PercentFormatter(xmax=1))\n",
300
+ " ax.set_title(DISPLAY[m], fontsize=20)\n",
301
+ " ax.set_xlabel('Quintile (Q1=shortest)', fontsize=20)\n",
302
+ " ax.tick_params(labelsize=20)\n",
303
+ " if ax == axes[0]:\n",
304
+ " ax.set_ylabel('Accuracy', fontsize=20)\n",
305
+ " ax.spines[['top', 'right']].set_visible(False)\n",
306
+ "\n",
307
+ "plt.tight_layout()\n",
308
+ "plt.savefig('data/figures/token_length_no_outliers_accuracy_by_token_length_quintile_occluded.pdf', bbox_inches='tight')\n",
309
+ "plt.show()"
310
+ ]
311
+ },
312
+ {
313
+ "cell_type": "markdown",
314
+ "id": "e5794c1a",
315
+ "metadata": {},
316
+ "source": [
317
+ "## 6. GPT vs. Claude Judge Accuracy by Quintile"
318
+ ]
319
+ },
320
+ {
321
+ "cell_type": "code",
322
+ "execution_count": null,
323
+ "id": "ba08bc0d",
324
+ "metadata": {},
325
+ "outputs": [],
326
+ "source": [
327
+ "fig, axes = plt.subplots(1, len(MODELS), figsize=(4.2 * len(MODELS), 4.5), sharey=True)\n",
328
+ "fig.suptitle('Judge Accuracy by Token-Length Quintile — Occluded', fontsize=13)\n",
329
+ "\n",
330
+ "for ax, m in zip(axes, MODELS):\n",
331
+ " sub = all_df[all_df['model'] == m][['tokens', 'gpt', 'claude']].dropna(subset=['gpt','claude']).copy()\n",
332
+ " sub['q'] = pd.qcut(sub['tokens'], q=5, labels=['Q1','Q2','Q3','Q4','Q5'])\n",
333
+ " agg = sub.groupby('q', observed=True)[['gpt','claude']].mean()\n",
334
+ " x = np.arange(len(agg))\n",
335
+ " w = 0.35\n",
336
+ " ax.bar(x - w/2, agg['gpt'], width=w, label='GPT-5.4', color='#2196F3', alpha=0.85)\n",
337
+ " ax.bar(x + w/2, agg['claude'], width=w, label='Claude Opus 4-6', color='#FF9800', alpha=0.85)\n",
338
+ " ax.set_xticks(x)\n",
339
+ " ax.set_xticklabels(['Q1','Q2','Q3','Q4','Q5'], fontsize=8)\n",
340
+ " ax.set_ylim(0, 1.1)\n",
341
+ " ax.set_title(DISPLAY[m], fontsize=10)\n",
342
+ " ax.set_xlabel('Quintile')\n",
343
+ " if ax == axes[0]:\n",
344
+ " ax.set_ylabel('Judge Accuracy')\n",
345
+ " if ax == axes[-1]:\n",
346
+ " ax.legend(fontsize=8)\n",
347
+ " ax.spines[['top', 'right']].set_visible(False)\n",
348
+ "\n",
349
+ "plt.tight_layout()\n",
350
+ "plt.savefig('data/figures/token_length_no_outliers_judge_accuracy_by_token_length_quintile_occluded.pdf', bbox_inches='tight')\n",
351
+ "plt.show()"
352
+ ]
353
+ },
354
+ {
355
+ "cell_type": "markdown",
356
+ "id": "1102495e",
357
+ "metadata": {},
358
+ "source": [
359
+ "## 7. Summary Table"
360
+ ]
361
+ },
362
+ {
363
+ "cell_type": "code",
364
+ "execution_count": null,
365
+ "id": "f8a5c15d",
366
+ "metadata": {},
367
+ "outputs": [],
368
+ "source": [
369
+ "summary_rows = []\n",
370
+ "for m in MODELS:\n",
371
+ " s = all_df[all_df['model'] == m][['tokens', 'correct']].dropna()\n",
372
+ " r, p = stats.pointbiserialr(s['correct'].astype(int), s['tokens'])\n",
373
+ " summary_rows.append({\n",
374
+ " 'Model': DISPLAY[m],\n",
375
+ " 'Accuracy': s['correct'].mean(),\n",
376
+ " 'r': r,\n",
377
+ " 'p': p,\n",
378
+ " 'Correct tokens': s.loc[s['correct'], 'tokens'].mean(),\n",
379
+ " 'Incorrect tokens': s.loc[~s['correct'], 'tokens'].mean(),\n",
380
+ " })\n",
381
+ "\n",
382
+ "sum_df = pd.DataFrame(summary_rows)\n",
383
+ "print(sum_df.round(3).to_string(index=False))"
384
+ ]
385
+ },
386
+ {
387
+ "cell_type": "markdown",
388
+ "id": "93e0eea5",
389
+ "metadata": {},
390
+ "source": [
391
+ "## 8. Accuracy vs Token Count (Binned)"
392
+ ]
393
+ },
394
+ {
395
+ "cell_type": "code",
396
+ "execution_count": null,
397
+ "id": "359c0682",
398
+ "metadata": {},
399
+ "outputs": [],
400
+ "source": [
401
+ "BIN_SIZE = 10 # tokens per bin\n",
402
+ "\n",
403
+ "fig, axes = plt.subplots(1, len(MODELS), figsize=(5.5 * len(MODELS), 6), sharey=True)\n",
404
+ "#fig.suptitle('Accuracy vs Token Count', fontsize=20)\n",
405
+ "\n",
406
+ "for ax, m in zip(axes, MODELS):\n",
407
+ " sub = all_df[all_df['model'] == m][['tokens', 'correct']].dropna().copy()\n",
408
+ " sub['bin'] = (sub['tokens'] // BIN_SIZE) * BIN_SIZE + BIN_SIZE // 2 # midpoint\n",
409
+ " agg = sub.groupby('bin')['correct'].agg(['mean', 'count']).reset_index()\n",
410
+ " agg = agg[agg['count'] >= 5]\n",
411
+ " color = PALETTE[DISPLAY[m]]\n",
412
+ " ax.scatter(agg['bin'], agg['mean'], s=agg['count'] * 2,\n",
413
+ " color=color, alpha=0.75, edgecolors='white', linewidth=0.4, zorder=3)\n",
414
+ " ax.plot(agg['bin'], agg['mean'], color=color, alpha=0.4, linewidth=1)\n",
415
+ " ax.set_title(DISPLAY[m], fontsize=20)\n",
416
+ " ax.set_xlabel('Token Count', fontsize=20)\n",
417
+ " ax.set_ylim(0, 1.05)\n",
418
+ " ax.yaxis.set_major_formatter(mtick.PercentFormatter(xmax=1))\n",
419
+ " ax.tick_params(labelsize=20)\n",
420
+ " if ax == axes[0]:\n",
421
+ " ax.set_ylabel('Accuracy', fontsize=20)\n",
422
+ " ax.spines[['top', 'right']].set_visible(False)\n",
423
+ "\n",
424
+ "# Dot-size reference\n",
425
+ "ref_ns = [5, 20, 50]\n",
426
+ "ref_handles = [\n",
427
+ " plt.scatter([], [], s=n * 2, color='black', alpha=0.7,\n",
428
+ " edgecolors='white', linewidths=0.4, label=f'n = {n}')\n",
429
+ " for n in ref_ns\n",
430
+ "]\n",
431
+ "fig.legend(handles=ref_handles, loc='lower center', ncol=len(ref_ns),\n",
432
+ " bbox_to_anchor=(0.5, -0.04), frameon=False,\n",
433
+ " title='Items per bin\\n', title_fontsize=20, fontsize=20,\n",
434
+ " columnspacing=1.2, handletextpad=0.4)\n",
435
+ "\n",
436
+ "#plt.tight_layout()\n",
437
+ "plt.subplots_adjust(bottom=0.35)\n",
438
+ "plt.savefig('data/figures/token_length_no_outliers_accuracy_vs_token_count_binned_occluded.pdf', bbox_inches='tight')\n",
439
+ "plt.show()"
440
+ ]
441
+ }
442
+ ],
443
+ "metadata": {
444
+ "kernelspec": {
445
+ "display_name": "cos429",
446
+ "language": "python",
447
+ "name": "python3"
448
+ },
449
+ "language_info": {
450
+ "codemirror_mode": {
451
+ "name": "ipython",
452
+ "version": 3
453
+ },
454
+ "file_extension": ".py",
455
+ "mimetype": "text/x-python",
456
+ "name": "python",
457
+ "nbconvert_exporter": "python",
458
+ "pygments_lexer": "ipython3",
459
+ "version": "3.8.18"
460
+ }
461
+ },
462
+ "nbformat": 4,
463
+ "nbformat_minor": 5
464
+ }
code/prepare_data.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Lay out the released images the way the experiment scripts expect.
2
+
3
+ Run once from this folder after downloading the dataset:
4
+ python prepare_data.py
5
+
6
+ Creates, in data/ next to this script:
7
+ combined_output/ <id>.<ext>, <id>_occluded.png, <id>_transparent.png, annotations.json
8
+ combined_output_blue/ <id>_occluded.png, annotations.json (App. C box style)
9
+ physical_occluded_combined/ <id>_occluded.png, annotations.json (cue removed)
10
+ annotated/ <id>.<ext> (highlighted cue region)
11
+ Image categories (3).xlsx image id / direct or inferential / subcategory
12
+ Files are hard-linked where possible, copied otherwise.
13
+ """
14
+ import json
15
+ import os
16
+ import shutil
17
+
18
+ import openpyxl
19
+
20
+ HERE = os.path.dirname(os.path.abspath(__file__))
21
+ DATASET = os.path.dirname(HERE)
22
+
23
+
24
+ def link(src_rel, dst):
25
+ src = os.path.join(DATASET, src_rel)
26
+ os.makedirs(os.path.dirname(dst), exist_ok=True)
27
+ if os.path.exists(dst):
28
+ os.remove(dst)
29
+ try:
30
+ os.link(src, dst)
31
+ except OSError:
32
+ shutil.copyfile(src, dst)
33
+
34
+
35
+ def main():
36
+ records = json.load(open(os.path.join(DATASET, "annotations.json")))
37
+
38
+ # Annotation format read by the experiment scripts
39
+ legacy = [{
40
+ "id": r["id"],
41
+ "original_file": os.path.basename(r["images"]["original"]),
42
+ "url": r["source_url"],
43
+ "answer": r["answer"],
44
+ "reasoning": r["annotator_note"],
45
+ "physical": r["type"] == "direct",
46
+ "annotations": r["occluders"],
47
+ } for r in records]
48
+
49
+ out = os.path.join(HERE, "data")
50
+ dirs = {
51
+ "main": os.path.join(out, "combined_output"),
52
+ "blue": os.path.join(out, "combined_output_blue"),
53
+ "cue_removed": os.path.join(out, "physical_occluded_combined"),
54
+ "highlighted": os.path.join(out, "annotated"),
55
+ }
56
+ for r in records:
57
+ rid, im = r["id"], r["images"]
58
+ link(im["original"], os.path.join(dirs["main"], os.path.basename(im["original"])))
59
+ link(im["occluded"], os.path.join(dirs["main"], f"{rid}_occluded.png"))
60
+ link(im["unmasked"], os.path.join(dirs["main"], f"{rid}_transparent.png"))
61
+ link(im["blue_box"], os.path.join(dirs["blue"], f"{rid}_occluded.png"))
62
+ if im["cue_removed"]:
63
+ link(im["cue_removed"], os.path.join(dirs["cue_removed"], f"{rid}_occluded.png"))
64
+ if im["highlighted_cue"]:
65
+ link(im["highlighted_cue"], os.path.join(dirs["highlighted"], os.path.basename(im["highlighted_cue"])))
66
+
67
+ for key in ("main", "blue", "cue_removed"):
68
+ with open(os.path.join(dirs[key], "annotations.json"), "w") as f:
69
+ json.dump(legacy, f, indent=2, ensure_ascii=False)
70
+
71
+ wb = openpyxl.Workbook()
72
+ ws = wb.active
73
+ ws.append(["image id", "direct or inferential", "subcategory"])
74
+ for r in records:
75
+ ws.append([r["id"], r["type"], r["fine_category"]])
76
+ wb.save(os.path.join(out, "Image categories (3).xlsx"))
77
+
78
+ print(f"Prepared {len(records)} items under {out}")
79
+
80
+
81
+ if __name__ == "__main__":
82
+ main()
code/requirements.txt ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ anthropic
2
+ openai
3
+ together
4
+ google-genai
5
+ python-dotenv
6
+ pillow
7
+ numpy
8
+ pandas
9
+ scipy
10
+ statsmodels
11
+ scikit-learn
12
+ matplotlib
13
+ seaborn
14
+ openpyxl
15
+ tiktoken
16
+ flask
17
+ nltk
18
+ wordfreq
code/sec3_occludebench/eval_script.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import base64
3
+ import io
4
+ import json
5
+ import os
6
+ from openai import OpenAI
7
+ from together import Together
8
+ import anthropic
9
+ from dotenv import load_dotenv
10
+ from PIL import Image
11
+
12
+ load_dotenv()
13
+ OpenAI_API_KEY = os.getenv("OpenAI_API_KEY")
14
+ Anthropic_API_KEY = os.getenv("Anthropic_API_KEY")
15
+ Gemini_API_KEY = os.getenv("Gemini_API_KEY")
16
+ Together_API_KEY = os.getenv("Together_API_KEY")
17
+
18
+ PROMPT = "What is the primary object that is completely occluded in this image? Be as specific as you can."
19
+ NUDGE_SUFFIX = " Pay close attention to any reflective surfaces or shadows in the image as you will need it to answer the question."
20
+ NUDGE_OCCLUSION = (
21
+ "You are answering visual questions about images where a primary object may be completely occluded by a visible mask, box, or polygon.\n\n"
22
+ "Your task is to identify the hidden object, not the occluder and not merely a shadow, reflection, surface, or visible nearby object.\n\n"
23
+ "Before answering, carefully inspect the whole image. Pay special attention to:\n"
24
+ "- shadows, reflections, mirrors, glass, water, shiny surfaces, and other indirect visual cues;\n"
25
+ "- whether those cues physically correspond to the hidden object given position, lighting, orientation, scale, and scene geometry;\n"
26
+ "- surrounding context, but only as secondary evidence when direct visual cues are insufficient.\n\n"
27
+ "Do not rely mainly on common-sense priors if a shadow or reflection provides more specific evidence. Do not answer \"shadow\" or \"reflection\" unless the question specifically asks for the visual phenomenon itself; answer the object casting the shadow or being reflected.\n\n"
28
+ "Give your best single answer. Be specific enough to distinguish the object when the image supports it, but do not over-specify uncertain details."
29
+ )
30
+ FOLLOWUP_PROMPT = "What is it a reflection of?"
31
+
32
+ JUDGE_RESPONSE_PROMPT = (
33
+ "A vision model was asked to identify the primary occluded object in an image. "
34
+ "Here is its response:\n\n\"{response}\"\n\n"
35
+ "Does this response identify a reflective surface (such as a mirror, puddle, or similar) "
36
+ "WITHOUT specifying what that surface is reflecting? "
37
+ "Answer only 'yes' or 'no'."
38
+ )
39
+
40
+ JUDGE_GT_PROMPT = (
41
+ "The ground truth answer for an occluded object identification task is:\n\n\"{ground_truth}\"\n\n"
42
+ "Is this ground truth answer itself just a reflective surface (e.g. a mirror or puddle), "
43
+ "with no information about what it is reflecting? "
44
+ "Answer only 'yes' or 'no'."
45
+ )
46
+
47
+ def init_client(model):
48
+ if "gpt" in model or model[0] == 'o':
49
+ return OpenAI(api_key=OpenAI_API_KEY)
50
+ elif "gemini" in model:
51
+ return OpenAI(api_key=Gemini_API_KEY, base_url="https://generativelanguage.googleapis.com/v1beta/openai/")
52
+ elif "claude" in model:
53
+ return anthropic.Anthropic(api_key=Anthropic_API_KEY)
54
+ else:
55
+ return Together(api_key=Together_API_KEY)
56
+
57
+ def judge(prompt, judge_model):
58
+ client = OpenAI(api_key=OpenAI_API_KEY)
59
+ verdict = client.chat.completions.create(
60
+ model=judge_model,
61
+ temperature=0,
62
+ messages=[{"role": "user", "content": prompt}]
63
+ ).choices[0].message.content.strip().lower()
64
+ return verdict.startswith("yes")
65
+
66
+ def encode_image(image_path, max_bytes=3.5 * 1024 * 1024):
67
+ with open(image_path, "rb") as f:
68
+ data = f.read()
69
+ if len(data) <= max_bytes:
70
+ return base64.b64encode(data).decode("utf-8")
71
+ # Scale down until under max_bytes
72
+ img = Image.open(io.BytesIO(data))
73
+ scale = 0.9
74
+ while True:
75
+ buf = io.BytesIO()
76
+ img.save(buf, format="PNG", optimize=True)
77
+ if buf.tell() <= max_bytes:
78
+ break
79
+ w, h = img.size
80
+ img = img.resize((int(w * scale), int(h * scale)), Image.LANCZOS)
81
+ return base64.b64encode(buf.getvalue()).decode("utf-8")
82
+
83
+ def chat_completion(model, client, image_path, prompt=PROMPT):
84
+ b64 = encode_image(image_path)
85
+ media_type = "image/png"
86
+
87
+ if "claude" in model:
88
+ return client.messages.create(
89
+ model=model,
90
+ max_tokens=500,
91
+ temperature=0,
92
+ messages=[{
93
+ "role": "user",
94
+ "content": [
95
+ {"type": "image", "source": {"type": "base64", "media_type": media_type, "data": b64}},
96
+ {"type": "text", "text": prompt}
97
+ ]
98
+ }]
99
+ ).content[0].text
100
+ else:
101
+ return client.chat.completions.create(
102
+ model=model,
103
+ temperature=0,
104
+ messages=[{
105
+ "role": "user",
106
+ "content": [
107
+ {"type": "image_url", "image_url": {"url": f"data:{media_type};base64,{b64}"}},
108
+ {"type": "text", "text": prompt}
109
+ ]
110
+ }]
111
+ ).choices[0].message.content
112
+
113
+ def followup_completion(model, client, image_path, initial_response, prompt=PROMPT):
114
+ b64 = encode_image(image_path)
115
+ media_type = "image/png"
116
+
117
+ if "claude" in model:
118
+ return client.messages.create(
119
+ model=model,
120
+ max_tokens=500,
121
+ temperature=0,
122
+ messages=[
123
+ {
124
+ "role": "user",
125
+ "content": [
126
+ {"type": "image", "source": {"type": "base64", "media_type": media_type, "data": b64}},
127
+ {"type": "text", "text": prompt}
128
+ ]
129
+ },
130
+ {"role": "assistant", "content": initial_response},
131
+ {"role": "user", "content": FOLLOWUP_PROMPT}
132
+ ]
133
+ ).content[0].text
134
+ else:
135
+ return client.chat.completions.create(
136
+ model=model,
137
+ temperature=0,
138
+ messages=[
139
+ {
140
+ "role": "user",
141
+ "content": [
142
+ {"type": "image_url", "image_url": {"url": f"data:{media_type};base64,{b64}"}},
143
+ {"type": "text", "text": prompt}
144
+ ]
145
+ },
146
+ {"role": "assistant", "content": initial_response},
147
+ {"role": "user", "content": FOLLOWUP_PROMPT}
148
+ ]
149
+ ).choices[0].message.content
150
+
151
+ def run_eval(args, client):
152
+ with open(os.path.join(args.data_dir, "annotations.json")) as f:
153
+ entries = json.load(f)
154
+
155
+ model_name = args.model.split("/")[-1]
156
+ output_path = os.path.join(args.output_dir, f"{model_name}_results.json")
157
+
158
+ # Load existing results for recovery
159
+ if os.path.exists(output_path):
160
+ with open(output_path) as f:
161
+ results = json.load(f)
162
+ done_ids = {r["id"] for r in results}
163
+ print(f"Resuming: {len(done_ids)} already done, {len(entries) - len(done_ids)} remaining.")
164
+ else:
165
+ results = []
166
+ done_ids = set()
167
+
168
+ for entry in entries:
169
+ if entry["id"] in done_ids:
170
+ continue
171
+
172
+ base = os.path.splitext(entry["original_file"])[0]
173
+ occluded_path = os.path.join(args.data_dir, f"{base}_occluded.png")
174
+ if not os.path.exists(occluded_path):
175
+ continue
176
+ ground_truth = entry.get("answer", "")
177
+
178
+ is_physical = entry.get("physical", False)
179
+ if args.nudge and not is_physical:
180
+ continue
181
+ if args.nudge == "reflective":
182
+ prompt = PROMPT + NUDGE_SUFFIX
183
+ elif args.nudge == "occlusion":
184
+ prompt = NUDGE_OCCLUSION
185
+ else:
186
+ prompt = PROMPT
187
+
188
+ print(f"Running {entry['id']}...")
189
+ response = chat_completion(args.model, client, occluded_path, prompt=prompt)
190
+ print(f" Response: {response}")
191
+
192
+ result = {
193
+ "id": entry["id"],
194
+ "ground_truth": ground_truth,
195
+ "response": response,
196
+ "followup_response": None
197
+ }
198
+
199
+ # Only consider a follow-up if the GT itself isn't just a bare reflective surface
200
+ gt_is_bare_reflective = judge(
201
+ JUDGE_GT_PROMPT.format(ground_truth=ground_truth),
202
+ args.judge_model
203
+ )
204
+
205
+ if not gt_is_bare_reflective:
206
+ response_is_bare_reflective = judge(
207
+ JUDGE_RESPONSE_PROMPT.format(response=response),
208
+ args.judge_model
209
+ )
210
+ if response_is_bare_reflective:
211
+ print(f" [Judge] Reflective surface without specifics — sending follow-up...")
212
+ followup = followup_completion(args.model, client, occluded_path, response, prompt=prompt)
213
+ print(f" Follow-up: {followup}")
214
+ result["followup_response"] = followup
215
+
216
+ results.append(result)
217
+
218
+ # Save after each entry so progress is never lost
219
+ os.makedirs(args.output_dir, exist_ok=True)
220
+ with open(output_path, "w") as f:
221
+ json.dump(results, f, indent=2)
222
+
223
+ return results
224
+
225
+ def parse_args():
226
+ parser = argparse.ArgumentParser()
227
+ parser.add_argument("--model", type=str, default="gpt-4o")
228
+ parser.add_argument("--data_dir", type=str, default="data/combined_output")
229
+ parser.add_argument("--output_dir", type=str, default="data/eval_results")
230
+ parser.add_argument("--judge_model", type=str, default="gpt-5.4")
231
+ parser.add_argument("--nudge", type=str, default=None, choices=["reflective", "occlusion"],
232
+ help="Nudge variant for physical entries: 'reflective' appends the reflective-surface hint; 'occlusion' uses a detailed occlusion-aware prompt.")
233
+ return parser.parse_args()
234
+
235
+ def main(args):
236
+ client = init_client(args.model)
237
+ os.makedirs(args.output_dir, exist_ok=True)
238
+ results = run_eval(args, client)
239
+ model_name = args.model.split("/")[-1]
240
+ print(f"Done. {len(results)} results in {os.path.join(args.output_dir, f'{model_name}_results.json')}")
241
+
242
+ if __name__ == "__main__":
243
+ args = parse_args()
244
+ main(args)
code/sec3_occludebench/human_baseline/human_accuracy_breakdown_pub_quality.ipynb ADDED
@@ -0,0 +1,417 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Human Baseline — Accuracy by Category\n",
8
+ "\n",
9
+ "Direct vs inferential accuracy for Prolific human participants on the **occlusion** test.\n",
10
+ "All results use Combined scoring (correct if either GPT-5.4 or Claude Opus 4.6 judge says correct)."
11
+ ]
12
+ },
13
+ {
14
+ "cell_type": "code",
15
+ "execution_count": null,
16
+ "metadata": {},
17
+ "outputs": [],
18
+ "source": [
19
+ "# Run from the repo root so the root-relative data paths below resolve\n",
20
+ "import os\n",
21
+ "from pathlib import Path\n",
22
+ "os.chdir(next(p for p in [Path.cwd(), *Path.cwd().parents] if (p / \"sec3_occludebench\").is_dir()))"
23
+ ]
24
+ },
25
+ {
26
+ "cell_type": "code",
27
+ "execution_count": null,
28
+ "id": "d1994747",
29
+ "metadata": {},
30
+ "outputs": [],
31
+ "source": [
32
+ "import json\n",
33
+ "import os\n",
34
+ "import pandas as pd\n",
35
+ "import matplotlib.pyplot as plt\n",
36
+ "import matplotlib.ticker as mtick\n",
37
+ "import numpy as np\n",
38
+ "from scipy import stats\n",
39
+ "\n",
40
+ "JUDGED_PATH = 'data/eval_results_human/human_prolific_judged_results.json'\n",
41
+ "JUDGE_GPT = 'gpt-5.4'\n",
42
+ "JUDGE_CLAUDE = 'claude-opus-4-6'\n",
43
+ "JUDGE_MODELS = [JUDGE_GPT, JUDGE_CLAUDE]\n",
44
+ "\n",
45
+ "with open(JUDGED_PATH) as f:\n",
46
+ " data = json.load(f)\n",
47
+ "\n",
48
+ "print(f'Total entries: {len(data)}')\n",
49
+ "n_phys = sum(1 for r in data if r.get('is_physical') is True)\n",
50
+ "n_nonphys = sum(1 for r in data if r.get('is_physical') is False)\n",
51
+ "print(f'Direct: {n_phys} | Inferential: {n_nonphys}')\n",
52
+ "\n",
53
+ "import matplotlib as mpl\n",
54
+ "\n",
55
+ "mpl.rcParams.update({\n",
56
+ " 'font.family': 'Arial',\n",
57
+ " 'font.size': 17,\n",
58
+ " 'axes.titlesize': 18,\n",
59
+ " 'axes.labelsize': 17,\n",
60
+ " 'xtick.labelsize': 17,\n",
61
+ " 'ytick.labelsize': 17,\n",
62
+ " 'legend.fontsize': 17,\n",
63
+ " 'axes.titleweight': 'normal',\n",
64
+ " 'axes.grid': False,\n",
65
+ " 'axes.spines.top': False,\n",
66
+ " 'axes.spines.right': False,\n",
67
+ " 'figure.dpi': 150,\n",
68
+ "})\n",
69
+ "\n",
70
+ "FIG_DIR = 'data/figures'\n",
71
+ "os.makedirs(FIG_DIR, exist_ok=True)\n",
72
+ "\n",
73
+ "def save(fig, name):\n",
74
+ " fig.savefig(os.path.join(FIG_DIR, name + '.pdf'), bbox_inches='tight', format='pdf')"
75
+ ]
76
+ },
77
+ {
78
+ "cell_type": "code",
79
+ "execution_count": null,
80
+ "id": "013f8a9e",
81
+ "metadata": {},
82
+ "outputs": [],
83
+ "source": [
84
+ "def wilson_ci(k, n, z=1.96):\n",
85
+ " if n == 0:\n",
86
+ " return (None, None)\n",
87
+ " p = k / n\n",
88
+ " denom = 1 + z**2 / n\n",
89
+ " center = (p + z**2 / (2 * n)) / denom\n",
90
+ " margin = z * np.sqrt(p * (1 - p) / n + z**2 / (4 * n**2)) / denom\n",
91
+ " return (100 * (center - margin), 100 * (center + margin))\n",
92
+ "\n",
93
+ "\n",
94
+ "def compute_accuracy(data, judge_models):\n",
95
+ " \"\"\"Returns dict: overall/physical/non_physical -> (pct, n_correct, n_total, ci_lo, ci_hi).\"\"\"\n",
96
+ " buckets = {'overall': [], 'physical': [], 'non_physical': []}\n",
97
+ " for r in data:\n",
98
+ " correct_dict = r.get('correct', {})\n",
99
+ " if not isinstance(correct_dict, dict):\n",
100
+ " continue\n",
101
+ " scores = [correct_dict.get(jm) for jm in judge_models]\n",
102
+ " if any(s is None for s in scores):\n",
103
+ " continue\n",
104
+ " verdict = any(scores) # OR\n",
105
+ " buckets['overall'].append(verdict)\n",
106
+ " if r.get('is_physical') is True:\n",
107
+ " buckets['physical'].append(verdict)\n",
108
+ " elif r.get('is_physical') is False:\n",
109
+ " buckets['non_physical'].append(verdict)\n",
110
+ "\n",
111
+ " result = {}\n",
112
+ " for key, vals in buckets.items():\n",
113
+ " if vals:\n",
114
+ " k, n = sum(vals), len(vals)\n",
115
+ " pct = 100 * k / n\n",
116
+ " ci_lo, ci_hi = wilson_ci(k, n)\n",
117
+ " result[key] = (pct, k, n, ci_lo, ci_hi)\n",
118
+ " else:\n",
119
+ " result[key] = (None, 0, 0, None, None)\n",
120
+ " return result\n",
121
+ "\n",
122
+ "\n",
123
+ "acc = compute_accuracy(data, JUDGE_MODELS)\n",
124
+ "for cat, (pct, correct, total, ci_lo, ci_hi) in acc.items():\n",
125
+ " print(f'{cat:15s}: {pct:.1f}% 95% CI [{ci_lo:.1f}%, {ci_hi:.1f}%] ({correct}/{total})')\n"
126
+ ]
127
+ },
128
+ {
129
+ "cell_type": "markdown",
130
+ "id": "23f3e4f4",
131
+ "metadata": {},
132
+ "source": [
133
+ "---\n",
134
+ "## Summary Table"
135
+ ]
136
+ },
137
+ {
138
+ "cell_type": "code",
139
+ "execution_count": null,
140
+ "id": "75efb5fb",
141
+ "metadata": {},
142
+ "outputs": [],
143
+ "source": [
144
+ "label_map = {'overall': 'Overall', 'physical': 'Direct', 'non_physical': 'Inferential'}\n",
145
+ "rows = {}\n",
146
+ "for cat in ('overall', 'physical', 'non_physical'):\n",
147
+ " pct, correct, total, ci_lo, ci_hi = acc[cat]\n",
148
+ " rows[label_map[cat]] = f'{pct:.1f}% [{ci_lo:.1f}, {ci_hi:.1f}] ({correct}/{total})'\n",
149
+ "\n",
150
+ "display(pd.DataFrame([rows], index=['Combined (OR)']))"
151
+ ]
152
+ },
153
+ {
154
+ "cell_type": "markdown",
155
+ "id": "f2abfbbc",
156
+ "metadata": {},
157
+ "source": [
158
+ "---\n",
159
+ "## Human Accuracy — Overall, Direct, Inferential"
160
+ ]
161
+ },
162
+ {
163
+ "cell_type": "code",
164
+ "execution_count": null,
165
+ "id": "3c82f77d",
166
+ "metadata": {},
167
+ "outputs": [],
168
+ "source": [
169
+ "cat_keys = ['physical', 'non_physical']\n",
170
+ "cat_labels = ['Direct', 'Inferential']\n",
171
+ "colors = ['#DD8452', '#55A868']\n",
172
+ "\n",
173
+ "x = np.arange(len(cat_keys))\n",
174
+ "width = 0.5\n",
175
+ "\n",
176
+ "fig, ax = plt.subplots(figsize=(5, 4.5))\n",
177
+ "\n",
178
+ "for i, (cat_key, cat_label, color) in enumerate(zip(cat_keys, cat_labels, colors)):\n",
179
+ " pct, _, _, ci_lo, ci_hi = acc[cat_key]\n",
180
+ " bar = ax.bar(i, pct, width, label=cat_label, color=color)\n",
181
+ " ax.errorbar(i, pct,\n",
182
+ " yerr=[[pct - ci_lo], [ci_hi - pct]],\n",
183
+ " fmt='none', color='black', capsize=4, linewidth=1.2)\n",
184
+ " ax.annotate(f'{pct:.1f}',\n",
185
+ " xy=(i, pct),\n",
186
+ " xytext=(0, 8), textcoords='offset points',\n",
187
+ " ha='center', va='bottom', fontsize=8)\n",
188
+ "\n",
189
+ "ax.set_title('Human Baseline — Occlusion Accuracy (95% CI)')\n",
190
+ "ax.set_xticks(x)\n",
191
+ "ax.set_xticklabels(cat_labels)\n",
192
+ "ax.set_ylim(0, 110)\n",
193
+ "ax.set_yticks([0, 20, 40, 60, 80, 100])\n",
194
+ "ax.yaxis.set_major_formatter(mtick.PercentFormatter())\n",
195
+ "ax.set_ylabel('Accuracy (%)')\n",
196
+ "\n",
197
+ "plt.tight_layout()\n",
198
+ "save(fig, 'human_accuracy_bar')\n",
199
+ "plt.show()"
200
+ ]
201
+ },
202
+ {
203
+ "cell_type": "markdown",
204
+ "id": "5d9ca1c1",
205
+ "metadata": {},
206
+ "source": [
207
+ "---\n",
208
+ "## Per-Image Accuracy"
209
+ ]
210
+ },
211
+ {
212
+ "cell_type": "code",
213
+ "execution_count": null,
214
+ "id": "64fd0d61",
215
+ "metadata": {},
216
+ "outputs": [],
217
+ "source": [
218
+ "from collections import defaultdict\n",
219
+ "\n",
220
+ "image_buckets = defaultdict(lambda: {'verdicts': [], 'is_physical': None})\n",
221
+ "\n",
222
+ "for r in data:\n",
223
+ " correct_dict = r.get('correct', {})\n",
224
+ " if not isinstance(correct_dict, dict):\n",
225
+ " continue\n",
226
+ " g = correct_dict.get(JUDGE_GPT)\n",
227
+ " c = correct_dict.get(JUDGE_CLAUDE)\n",
228
+ " if g is None or c is None:\n",
229
+ " continue\n",
230
+ " verdict = g or c\n",
231
+ " img_id = r.get('image_id')\n",
232
+ " image_buckets[img_id]['verdicts'].append(verdict)\n",
233
+ " image_buckets[img_id]['is_physical'] = r.get('is_physical')\n",
234
+ "\n",
235
+ "per_image = [\n",
236
+ " {\n",
237
+ " 'image_id': img_id,\n",
238
+ " 'accuracy': 100 * sum(v['verdicts']) / len(v['verdicts']),\n",
239
+ " 'is_physical': v['is_physical'],\n",
240
+ " }\n",
241
+ " for img_id, v in image_buckets.items()\n",
242
+ " if v['verdicts'] and v['is_physical'] is not None\n",
243
+ "]\n",
244
+ "\n",
245
+ "per_image_df = pd.DataFrame(per_image)\n",
246
+ "per_image_sorted = per_image_df.sort_values('accuracy', ascending=False).reset_index(drop=True)\n",
247
+ "print(f'Images: {len(per_image_df)} | Physical: {per_image_df[\"is_physical\"].sum()} | Non-physical: {(~per_image_df[\"is_physical\"]).sum()}')\n"
248
+ ]
249
+ },
250
+ {
251
+ "cell_type": "code",
252
+ "execution_count": null,
253
+ "id": "01a53e29",
254
+ "metadata": {},
255
+ "outputs": [],
256
+ "source": [
257
+ "from scipy.stats import mannwhitneyu, ttest_ind\n",
258
+ "from statsmodels.stats.proportion import proportions_ztest\n",
259
+ "\n",
260
+ "def get_response_counts(data, is_phys):\n",
261
+ " correct, total = 0, 0\n",
262
+ " for r in data:\n",
263
+ " if r.get('is_physical') is not is_phys:\n",
264
+ " continue\n",
265
+ " cd = r.get('correct', {})\n",
266
+ " g = cd.get(JUDGE_GPT)\n",
267
+ " c = cd.get(JUDGE_CLAUDE)\n",
268
+ " if g is None or c is None:\n",
269
+ " continue\n",
270
+ " total += 1\n",
271
+ " if g or c:\n",
272
+ " correct += 1\n",
273
+ " return correct, total\n",
274
+ "\n",
275
+ "phys_correct, phys_total = get_response_counts(data, True)\n",
276
+ "nonphys_correct, nonphys_total = get_response_counts(data, False)\n",
277
+ "\n",
278
+ "z_stat, p_two_prop = proportions_ztest(\n",
279
+ " [phys_correct, nonphys_correct],\n",
280
+ " [phys_total, nonphys_total]\n",
281
+ ")\n",
282
+ "print('Response-level z-test (direct vs inferential):')\n",
283
+ "print(f' Direct: {phys_correct}/{phys_total} ({100*phys_correct/phys_total:.1f}%)')\n",
284
+ "print(f' Inferential: {nonphys_correct}/{nonphys_total} ({100*nonphys_correct/nonphys_total:.1f}%)')\n",
285
+ "print(f' z = {z_stat:.3f}, p = {p_two_prop:.4f}')\n",
286
+ "\n",
287
+ "phys_acc = per_image_df.loc[per_image_df['is_physical'] == True, 'accuracy']\n",
288
+ "nonphys_acc = per_image_df.loc[per_image_df['is_physical'] == False, 'accuracy']\n",
289
+ "u_stat, p_mw = mannwhitneyu(phys_acc, nonphys_acc, alternative='two-sided')\n",
290
+ "t_stat, p_tt = ttest_ind(phys_acc, nonphys_acc, equal_var=False)\n",
291
+ "\n",
292
+ "print(f'\\nPer-image level:')\n",
293
+ "print(f' Direct mean: {phys_acc.mean():.1f}% (n={len(phys_acc)} images)')\n",
294
+ "print(f' Inferential mean: {nonphys_acc.mean():.1f}% (n={len(nonphys_acc)} images)')\n",
295
+ "print(f' Mann-Whitney U: U = {u_stat:.1f}, p = {p_mw:.4f}')\n",
296
+ "print(f' Welch t-test: t = {t_stat:.3f}, p = {p_tt:.4f}')"
297
+ ]
298
+ },
299
+ {
300
+ "cell_type": "markdown",
301
+ "id": "51d3b65b",
302
+ "metadata": {},
303
+ "source": [
304
+ "---\n",
305
+ "## Per-Image Accuracy Distribution"
306
+ ]
307
+ },
308
+ {
309
+ "cell_type": "code",
310
+ "execution_count": null,
311
+ "id": "634af53e",
312
+ "metadata": {},
313
+ "outputs": [],
314
+ "source": [
315
+ "fig, axes = plt.subplots(1, 2, figsize=(10, 4), sharey=True)\n",
316
+ "\n",
317
+ "means = {'Direct': 63.4, 'Inferential': 68.5}\n",
318
+ "\n",
319
+ "for ax, is_phys, label, color in zip(\n",
320
+ " axes, [True, False], ['Direct', 'Inferential'], ['#4C72B0', '#DD8452']\n",
321
+ "):\n",
322
+ " subset = per_image_df[per_image_df['is_physical'] == is_phys]['accuracy']\n",
323
+ " mean_val = means[label]\n",
324
+ " ax.hist(subset, bins=20, range=(0, 100), color=color, edgecolor='white', alpha=0.85)\n",
325
+ " ax.axvline(mean_val, color='black', linestyle='--', linewidth=1.2,\n",
326
+ " label=f'Mean: {mean_val:.1f}%')\n",
327
+ " ax.set_title(f'{label} Images')\n",
328
+ " ax.set_xlabel('% of participants correct')\n",
329
+ " ax.set_ylabel('Number of images')\n",
330
+ " ax.set_xticks([0, 20, 40, 60, 80, 100])\n",
331
+ " ax.xaxis.set_major_formatter(mtick.PercentFormatter())\n",
332
+ " ax.legend()\n",
333
+ "\n",
334
+ "fig.suptitle('Per-Image Accuracy Distribution', y=1.02)\n",
335
+ "plt.tight_layout()\n",
336
+ "save(fig, 'human_per_image_dist')\n",
337
+ "plt.show()"
338
+ ]
339
+ },
340
+ {
341
+ "cell_type": "markdown",
342
+ "id": "58a4b034",
343
+ "metadata": {},
344
+ "source": [
345
+ "---\n",
346
+ "## Per-Image Accuracy — Sorted"
347
+ ]
348
+ },
349
+ {
350
+ "cell_type": "code",
351
+ "execution_count": null,
352
+ "id": "a45b7617",
353
+ "metadata": {},
354
+ "outputs": [],
355
+ "source": [
356
+ "phys_acc_vals = per_image_sorted.loc[per_image_sorted['is_physical'] == True, 'accuracy']\n",
357
+ "nonphys_acc_vals = per_image_sorted.loc[per_image_sorted['is_physical'] == False, 'accuracy']\n",
358
+ "\n",
359
+ "DIRECT_MEAN = 63.4\n",
360
+ "INF_MEAN = 68.5\n",
361
+ "\n",
362
+ "fig, ax_bar = plt.subplots(figsize=(14, 4))\n",
363
+ "\n",
364
+ "colors_bar = ['#4C72B0' if p else '#DD8452' for p in per_image_sorted['is_physical']]\n",
365
+ "ax_bar.bar(range(len(per_image_sorted)), per_image_sorted['accuracy'],\n",
366
+ " color=colors_bar, width=1.0, linewidth=0)\n",
367
+ "ax_bar.axhline(DIRECT_MEAN, color='#4C72B0', linestyle='--', linewidth=1.2,\n",
368
+ " label=f'Direct mean: {DIRECT_MEAN:.1f}%')\n",
369
+ "ax_bar.axhline(INF_MEAN, color='#DD8452', linestyle='--', linewidth=1.2,\n",
370
+ " label=f'Inferential mean: {INF_MEAN:.1f}%')\n",
371
+ "ax_bar.set_xlabel('Image rank (easiest to hardest)')\n",
372
+ "ax_bar.set_ylabel('% of participants correct')\n",
373
+ "ax_bar.set_title('Human Accuracy per Image')\n",
374
+ "ax_bar.set_xlim(-1, len(per_image_sorted))\n",
375
+ "ax_bar.set_ylim(0, 105)\n",
376
+ "ax_bar.set_yticks([0, 20, 40, 60, 80, 100])\n",
377
+ "ax_bar.yaxis.set_major_formatter(mtick.PercentFormatter())\n",
378
+ "\n",
379
+ "import matplotlib.patches as mpatches\n",
380
+ "import matplotlib.lines as mlines\n",
381
+ "bar_handles = [\n",
382
+ " mpatches.Patch(color='#4C72B0', label='Direct'),\n",
383
+ " mpatches.Patch(color='#DD8452', label='Inferential'),\n",
384
+ " mlines.Line2D([], [], color='#4C72B0', linestyle='--', linewidth=1.2, label=f'Direct mean: {DIRECT_MEAN:.1f}%'),\n",
385
+ " mlines.Line2D([], [], color='#DD8452', linestyle='--', linewidth=1.2, label=f'Inferential mean: {INF_MEAN:.1f}%'),\n",
386
+ "]\n",
387
+ "fig.legend(handles=bar_handles, loc='lower center', ncol=4, bbox_to_anchor=(0.5, -0.18),\n",
388
+ " frameon=False, fontsize=17)\n",
389
+ "\n",
390
+ "plt.tight_layout()\n",
391
+ "save(fig, 'human_per_image_sorted')\n",
392
+ "plt.show()"
393
+ ]
394
+ }
395
+ ],
396
+ "metadata": {
397
+ "kernelspec": {
398
+ "display_name": "cos429",
399
+ "language": "python",
400
+ "name": "python3"
401
+ },
402
+ "language_info": {
403
+ "codemirror_mode": {
404
+ "name": "ipython",
405
+ "version": 3
406
+ },
407
+ "file_extension": ".py",
408
+ "mimetype": "text/x-python",
409
+ "name": "python",
410
+ "nbconvert_exporter": "python",
411
+ "pygments_lexer": "ipython3",
412
+ "version": "3.8.18"
413
+ }
414
+ },
415
+ "nbformat": 4,
416
+ "nbformat_minor": 5
417
+ }
code/sec3_occludebench/human_baseline/judger_human.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import os
4
+ from openai import OpenAI
5
+ import anthropic
6
+ from dotenv import load_dotenv
7
+
8
+ load_dotenv()
9
+ OpenAI_API_KEY = os.getenv("OpenAI_API_KEY")
10
+ Anthropic_API_KEY = os.getenv("Anthropic_API_KEY")
11
+
12
+ JUDGE_CORRECT_PROMPT = (
13
+ "You are evaluating whether a human participant correctly identified an occluded object.\n\n"
14
+ "Ground truth: \"{ground_truth}\"\n\n"
15
+ "Human response: \"{response}\"\n\n"
16
+ "Does the human's response correctly identify the same object as the ground truth? "
17
+ "Allow for reasonable variation in phrasing, specificity, or synonyms "
18
+ "(e.g., 'barber pole' matches 'barber's pole', 'wing mirror' matches 'side mirror', "
19
+ "'cat' matches 'pet' if the ground truth is 'Reasonable Pet'). "
20
+ "The response should identify the core object — partial credit guesses that get the "
21
+ "category right but miss specifics should be marked correct only if the category-level "
22
+ "answer is what the ground truth describes. "
23
+ "Exception: if the ground truth explicitly refers to a reflection or shadow of an object "
24
+ "(e.g., 'pen shadow', 'reflection of a car'), the response must identify both the shadow/reflection "
25
+ "nature AND the underlying object to be marked correct — identifying only the object (e.g., 'pen') "
26
+ "is not sufficient. "
27
+ "Answer only 'yes' or 'no'."
28
+ )
29
+
30
+
31
+ def judge_correct(ground_truth, response, judge_model, clients):
32
+ prompt = JUDGE_CORRECT_PROMPT.format(
33
+ ground_truth=ground_truth.strip(),
34
+ response=response.strip()
35
+ )
36
+ if judge_model.startswith("claude"):
37
+ verdict = clients["anthropic"].messages.create(
38
+ model=judge_model,
39
+ temperature=0,
40
+ max_tokens=10,
41
+ messages=[{"role": "user", "content": prompt}]
42
+ ).content[0].text.strip().lower()
43
+ else:
44
+ verdict = clients["openai"].chat.completions.create(
45
+ model=judge_model,
46
+ temperature=0,
47
+ messages=[{"role": "user", "content": prompt}]
48
+ ).choices[0].message.content.strip().lower()
49
+ return verdict.startswith("yes")
50
+
51
+
52
+ def run_judger(args):
53
+ clients = {
54
+ "openai": OpenAI(api_key=OpenAI_API_KEY),
55
+ "anthropic": anthropic.Anthropic(api_key=Anthropic_API_KEY),
56
+ }
57
+
58
+ judge_models = args.judge_models
59
+ input_path = args.input
60
+ output_path = args.output
61
+
62
+ with open(input_path) as f:
63
+ entries = json.load(f)
64
+
65
+ # Resume support: load existing judged output
66
+ if os.path.exists(output_path):
67
+ with open(output_path) as f:
68
+ existing_judged = json.load(f)
69
+ judged_by_id = {r["id"]: r for r in existing_judged}
70
+ print(f"Resuming: {len(judged_by_id)} already judged.")
71
+ else:
72
+ judged_by_id = {}
73
+
74
+ print(f"Total entries: {len(entries)}")
75
+ print(f"Judge models: {', '.join(judge_models)}\n")
76
+
77
+ os.makedirs(os.path.dirname(output_path) if os.path.dirname(output_path) else ".", exist_ok=True)
78
+
79
+ for entry in entries:
80
+ entry_id = entry["id"]
81
+ ground_truth = str(entry.get("ground_truth") or "").strip()
82
+ response = str(entry.get("response") or "").strip()
83
+
84
+ existing = judged_by_id.get(entry_id, {"id": entry_id})
85
+
86
+ # Migrate old format: occluded_correct -> correct
87
+ if "occluded_correct" in existing and "correct" not in existing:
88
+ existing["correct"] = existing.pop("occluded_correct")
89
+
90
+ # Carry over metadata fields
91
+ for field in ("image_id", "prolific_pid", "is_physical", "response_time_ms", "ground_truth", "response"):
92
+ if field in entry:
93
+ existing[field] = entry[field]
94
+
95
+ if not isinstance(existing.get("correct"), dict):
96
+ existing["correct"] = {}
97
+
98
+ pending = [jm for jm in judge_models if jm not in existing["correct"]]
99
+ if not pending:
100
+ judged_by_id[entry_id] = existing
101
+ continue
102
+
103
+ print(f"Judging {entry_id} ...")
104
+
105
+ for jm in pending:
106
+ if ground_truth and response:
107
+ correct = judge_correct(ground_truth, response, jm, clients)
108
+ existing["correct"][jm] = correct
109
+ print(f" [{jm}]: {'CORRECT' if correct else 'WRONG'} | gt={ground_truth!r} resp={response!r}")
110
+ else:
111
+ existing["correct"][jm] = None
112
+ print(f" [{jm}]: skipped (missing ground truth or response)")
113
+
114
+ # Consensus: True only if all judge models agree correct
115
+ verdicts = [v for v in existing["correct"].values() if v is not None]
116
+ existing["consensus_correct"] = all(verdicts) if verdicts else None
117
+
118
+ judged_by_id[entry_id] = existing
119
+
120
+ with open(output_path, "w") as f:
121
+ json.dump(list(judged_by_id.values()), f, indent=2)
122
+
123
+ # Final save
124
+ with open(output_path, "w") as f:
125
+ json.dump(list(judged_by_id.values()), f, indent=2)
126
+
127
+ # Summary
128
+ all_judged = list(judged_by_id.values())
129
+ print(f"\n===== Summary =====")
130
+ for jm in judge_models:
131
+ judged = [r for r in all_judged if isinstance(r.get("correct"), dict) and r["correct"].get(jm) is not None]
132
+ correct = sum(1 for r in judged if r["correct"][jm])
133
+ print(f"[{jm}]: {correct}/{len(judged)} correct ({100 * correct / len(judged):.1f}%)" if judged else f"[{jm}]: no results")
134
+
135
+ consensus = [r for r in all_judged if r.get("consensus_correct") is not None]
136
+ consensus_correct = sum(1 for r in consensus if r["consensus_correct"])
137
+ print(f"[consensus]: {consensus_correct}/{len(consensus)} correct ({100 * consensus_correct / len(consensus):.1f}%)" if consensus else "[consensus]: no results")
138
+
139
+ # Per-image accuracy (consensus)
140
+ image_scores = {}
141
+ for r in all_judged:
142
+ img_id = r.get("image_id", "unknown")
143
+ if img_id not in image_scores:
144
+ image_scores[img_id] = {"correct": 0, "total": 0}
145
+ if r.get("consensus_correct") is not None:
146
+ image_scores[img_id]["total"] += 1
147
+ if r["consensus_correct"]:
148
+ image_scores[img_id]["correct"] += 1
149
+
150
+ per_image_accs = [v["correct"] / v["total"] for v in image_scores.values() if v["total"] > 0]
151
+ if per_image_accs:
152
+ avg = sum(per_image_accs) / len(per_image_accs)
153
+ print(f"\nPer-image accuracy (consensus, averaged across images): {avg * 100:.1f}% ({len(per_image_accs)} images)")
154
+
155
+ # Physical vs digital breakdown (consensus)
156
+ for is_phys, label in [(True, "physical"), (False, "digital")]:
157
+ subset = [r for r in all_judged if r.get("is_physical") == is_phys and r.get("consensus_correct") is not None]
158
+ if subset:
159
+ n_correct = sum(1 for r in subset if r["consensus_correct"])
160
+ print(f"[{label}] consensus: {n_correct}/{len(subset)} correct ({100 * n_correct / len(subset):.1f}%)")
161
+
162
+ print(f"\nOutput saved to: {output_path}")
163
+
164
+
165
+ def parse_args():
166
+ parser = argparse.ArgumentParser(
167
+ description="Judge human prolific baseline responses against ground truth."
168
+ )
169
+ parser.add_argument(
170
+ "--input", type=str, default="data/eval_results_human/human_prolific_results.json",
171
+ help="Path to the converted human baseline results JSON."
172
+ )
173
+ parser.add_argument(
174
+ "--output", type=str, default="data/eval_results_human/human_prolific_judged_results.json",
175
+ help="Path to write judged results JSON."
176
+ )
177
+ parser.add_argument(
178
+ "--judge_models", type=str, nargs="+", default=["gpt-5.4", "claude-opus-4-6"],
179
+ help="Judge models to use (consensus requires all to agree)."
180
+ )
181
+ return parser.parse_args()
182
+
183
+
184
+ if __name__ == "__main__":
185
+ args = parse_args()
186
+ run_judger(args)
code/sec3_occludebench/image_category_plots.ipynb ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "b3645177",
6
+ "metadata": {},
7
+ "source": [
8
+ "# Image Category Distribution Plots\n",
9
+ "Using `data/Image categories (2).xlsx` — only IDs present in `data/combined_output/annotations.json`."
10
+ ]
11
+ },
12
+ {
13
+ "cell_type": "code",
14
+ "execution_count": null,
15
+ "id": "189e57e3",
16
+ "metadata": {},
17
+ "outputs": [],
18
+ "source": [
19
+ "# Run from the repo root so the root-relative data paths below resolve\n",
20
+ "import os\n",
21
+ "from pathlib import Path\n",
22
+ "os.chdir(next(p for p in [Path.cwd(), *Path.cwd().parents] if (p / \"sec3_occludebench\").is_dir()))"
23
+ ]
24
+ },
25
+ {
26
+ "cell_type": "code",
27
+ "execution_count": null,
28
+ "id": "de61e81b",
29
+ "metadata": {
30
+ "execution": {
31
+ "iopub.execute_input": "2026-05-02T06:18:15.611919Z",
32
+ "iopub.status.busy": "2026-05-02T06:18:15.611750Z",
33
+ "iopub.status.idle": "2026-05-02T06:18:15.982477Z",
34
+ "shell.execute_reply": "2026-05-02T06:18:15.982177Z"
35
+ }
36
+ },
37
+ "outputs": [],
38
+ "source": [
39
+ "import json\n",
40
+ "import openpyxl\n",
41
+ "import matplotlib.pyplot as plt\n",
42
+ "import matplotlib.patches as mpatches\n",
43
+ "from collections import Counter\n",
44
+ "\n",
45
+ "# ── Load annotation IDs ──────────────────────────────────────────────────────\n",
46
+ "with open('data/combined_output/annotations.json') as f:\n",
47
+ " data = json.load(f)\n",
48
+ "ann_set = set(item['id'] for item in data)\n",
49
+ "\n",
50
+ "# ── Load Excel ────────────────────────────────────────────────────────────────\n",
51
+ "def normalize_id(x):\n",
52
+ " if isinstance(x, float) and x == int(x):\n",
53
+ " return str(int(x))\n",
54
+ " return str(x)\n",
55
+ "\n",
56
+ "wb = openpyxl.load_workbook('data/Image categories (3).xlsx')\n",
57
+ "ws = wb.active\n",
58
+ "\n",
59
+ "direct_cats = Counter()\n",
60
+ "inferential_cats = Counter()\n",
61
+ "\n",
62
+ "for row in ws.iter_rows(values_only=True):\n",
63
+ " if row[0] is None or row[0] == 'image id':\n",
64
+ " continue\n",
65
+ " img_id = normalize_id(row[0])\n",
66
+ " if img_id not in ann_set:\n",
67
+ " continue\n",
68
+ " kind, subcat = row[1], row[2]\n",
69
+ " if kind == 'direct':\n",
70
+ " direct_cats[subcat] += 1\n",
71
+ " elif kind == 'inferential':\n",
72
+ " inferential_cats[subcat] += 1\n",
73
+ "\n",
74
+ "print('Direct:', dict(direct_cats), '| total:', sum(direct_cats.values()))\n",
75
+ "print('Inferential:', dict(inferential_cats), '| total:', sum(inferential_cats.values()))"
76
+ ]
77
+ },
78
+ {
79
+ "cell_type": "code",
80
+ "execution_count": null,
81
+ "id": "2e96f62c",
82
+ "metadata": {
83
+ "execution": {
84
+ "iopub.execute_input": "2026-05-02T06:18:15.983889Z",
85
+ "iopub.status.busy": "2026-05-02T06:18:15.983790Z",
86
+ "iopub.status.idle": "2026-05-02T06:18:16.269460Z",
87
+ "shell.execute_reply": "2026-05-02T06:18:16.269184Z"
88
+ }
89
+ },
90
+ "outputs": [],
91
+ "source": [
92
+ "direct_colors = {\n",
93
+ " 'shadow': '#4C72B0',\n",
94
+ " 'specular': '#55A868',\n",
95
+ " 'water': '#64B5CD',\n",
96
+ "}\n",
97
+ "\n",
98
+ "inferential_colors = {\n",
99
+ " 'household': '#DD8452',\n",
100
+ " 'machinery/technology': '#4C72B0',\n",
101
+ " 'sports/activity': '#55A868',\n",
102
+ " 'culture/symbol': '#C44E52',\n",
103
+ " 'nature': '#8172B3',\n",
104
+ "}\n",
105
+ "\n",
106
+ "# Merge direct subcategories\n",
107
+ "direct_merged = Counter()\n",
108
+ "direct_merged['shadow'] = direct_cats.get('shadow', 0)\n",
109
+ "direct_merged['specular'] = direct_cats.get('mirror/glass', 0) + direct_cats.get('other reflection', 0) + direct_cats.get('phone', 0)\n",
110
+ "direct_merged['water'] = direct_cats.get('water', 0)\n",
111
+ "\n",
112
+ "# Merge culture + symbol\n",
113
+ "inferential_merged = Counter(inferential_cats)\n",
114
+ "inferential_merged['culture/symbol'] = inferential_merged.pop('culture', 0) + inferential_merged.pop('symbol', 0)\n",
115
+ "\n",
116
+ "def make_pie(ax, counter, color_map, title, legend_ncol=2, split_legend=False):\n",
117
+ " labels_order = sorted(counter.keys(), key=lambda k: -counter[k])\n",
118
+ " sizes = [counter[k] for k in labels_order]\n",
119
+ " colors = [color_map[k] for k in labels_order]\n",
120
+ " total = sum(sizes)\n",
121
+ "\n",
122
+ " wedges, texts, autotexts = ax.pie(\n",
123
+ " sizes,\n",
124
+ " labels=None,\n",
125
+ " colors=colors,\n",
126
+ " autopct=lambda pct: f'{pct:.1f}%' if pct >= 4 else '',\n",
127
+ " pctdistance=0.72,\n",
128
+ " startangle=140,\n",
129
+ " wedgeprops=dict(linewidth=0.8, edgecolor='white'),\n",
130
+ " )\n",
131
+ " for at in autotexts:\n",
132
+ " at.set_fontsize(9)\n",
133
+ " at.set_color('white')\n",
134
+ "\n",
135
+ " patches = [mpatches.Patch(color=color_map[k], label=k.title())\n",
136
+ " for k in labels_order]\n",
137
+ "\n",
138
+ " if split_legend:\n",
139
+ " leg1 = ax.legend(handles=patches[:3], loc='lower center', bbox_to_anchor=(0.5, -0.06),\n",
140
+ " ncol=3, fontsize=9, frameon=False)\n",
141
+ " ax.add_artist(leg1)\n",
142
+ " ax.legend(handles=patches[3:], loc='lower center', bbox_to_anchor=(0.5, -0.16),\n",
143
+ " ncol=2, fontsize=9, frameon=False)\n",
144
+ " else:\n",
145
+ " ax.legend(handles=patches, loc='lower center', bbox_to_anchor=(0.5, -0.12),\n",
146
+ " ncol=legend_ncol, fontsize=9, frameon=False)\n",
147
+ "\n",
148
+ " ax.set_title(f'{title}\\n(n={total})', fontsize=13, pad=12)\n",
149
+ "\n",
150
+ "\n",
151
+ "fig, axes = plt.subplots(1, 2, figsize=(13, 6.5))\n",
152
+ "fig.patch.set_facecolor('white')\n",
153
+ "\n",
154
+ "make_pie(axes[0], direct_merged, direct_colors, 'Direct Images', legend_ncol=3)\n",
155
+ "make_pie(axes[1], inferential_merged, inferential_colors, 'Inferential Images', split_legend=True)\n",
156
+ "\n",
157
+ "plt.tight_layout(rect=[0, 0.05, 1, 1])\n",
158
+ "\n",
159
+ "plt.savefig('data/figures/image_category_distribution_pie.pdf', bbox_inches='tight', dpi=300)\n",
160
+ "plt.savefig('data/figures/image_category_distribution_pie.png', bbox_inches='tight', dpi=200)\n",
161
+ "plt.show()\n",
162
+ "print('Saved.')"
163
+ ]
164
+ }
165
+ ],
166
+ "metadata": {
167
+ "kernelspec": {
168
+ "display_name": "cos429",
169
+ "language": "python",
170
+ "name": "python3"
171
+ },
172
+ "language_info": {
173
+ "codemirror_mode": {
174
+ "name": "ipython",
175
+ "version": 3
176
+ },
177
+ "file_extension": ".py",
178
+ "mimetype": "text/x-python",
179
+ "name": "python",
180
+ "nbconvert_exporter": "python",
181
+ "pygments_lexer": "ipython3",
182
+ "version": "3.8.18"
183
+ }
184
+ },
185
+ "nbformat": 4,
186
+ "nbformat_minor": 5
187
+ }
code/sec3_occludebench/judger_script.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import os
4
+ import re
5
+ from openai import OpenAI
6
+ import anthropic
7
+ from dotenv import load_dotenv
8
+
9
+ load_dotenv()
10
+ OpenAI_API_KEY = os.getenv("OpenAI_API_KEY")
11
+ Anthropic_API_KEY = os.getenv("Anthropic_API_KEY")
12
+
13
+ JUDGE_CORRECT_PROMPT = (
14
+ "You are evaluating whether a vision model correctly identified an occluded object.\n\n"
15
+ "Ground truth: \"{ground_truth}\"\n\n"
16
+ "Model response: \"{response}\"\n\n"
17
+ "Does the model's response correctly identify the same object as the ground truth? "
18
+ "Allow for reasonable variation in phrasing, specificity, or synonyms "
19
+ "(e.g., 'barber pole' matches 'barber's pole', 'wing mirror' matches 'side mirror', "
20
+ "'cat' matches 'pet' if the ground truth is 'Reasonable Pet'). "
21
+ "The response should identify the core object — partial credit guesses that get the "
22
+ "category right but miss specifics should be marked correct only if the category-level "
23
+ "answer is what the ground truth describes. "
24
+ "Exception: if the ground truth explicitly refers to a reflection or shadow of an object "
25
+ "(e.g., 'pen shadow', 'reflection of a car'), the response must identify both the shadow/reflection "
26
+ "nature AND the underlying object to be marked correct — identifying only the object (e.g., 'pen') "
27
+ "is not sufficient. "
28
+ "Answer only 'yes' or 'no'."
29
+ )
30
+
31
+
32
+ def judge_correct(ground_truth, response, judge_model, clients):
33
+ prompt = JUDGE_CORRECT_PROMPT.format(
34
+ ground_truth=ground_truth.strip(),
35
+ response=response.strip()
36
+ )
37
+ if judge_model.startswith("claude"):
38
+ verdict = clients["anthropic"].messages.create(
39
+ model=judge_model,
40
+ temperature=0,
41
+ max_tokens=10,
42
+ messages=[{"role": "user", "content": prompt}]
43
+ ).content[0].text.strip().lower()
44
+ else:
45
+ verdict = clients["openai"].chat.completions.create(
46
+ model=judge_model,
47
+ temperature=0,
48
+ messages=[{"role": "user", "content": prompt}]
49
+ ).choices[0].message.content.strip().lower()
50
+ return verdict.startswith("yes")
51
+
52
+
53
+ def get_effective_response(entry):
54
+ """Pick the best response from an occluded-eval entry."""
55
+ for key in ("mask_followup_response", "followup_response", "response"):
56
+ val = entry.get(key)
57
+ if val:
58
+ return val, key
59
+ return "", "response"
60
+
61
+
62
+ def discover_model_stems(results_dir):
63
+ """Return all unique model stems found in the results directory."""
64
+ stems = set()
65
+ for fname in os.listdir(results_dir):
66
+ if not fname.endswith(".json") or fname.endswith("_judged_results.json"):
67
+ continue
68
+ for suffix in ("_vetted_results.json", "_transparent_results.json", "_results.json"):
69
+ if fname.endswith(suffix):
70
+ stems.add(fname[: -len(suffix)])
71
+ break
72
+ return sorted(stems)
73
+
74
+
75
+ def load_results(results_dir, stem):
76
+ """Load occluded results: prefer vetted, fall back to plain results."""
77
+ vetted_path = os.path.join(results_dir, f"{stem}_vetted_results.json")
78
+ plain_path = os.path.join(results_dir, f"{stem}_results.json")
79
+ if os.path.exists(vetted_path):
80
+ with open(vetted_path) as f:
81
+ return json.load(f), "vetted"
82
+ elif os.path.exists(plain_path):
83
+ with open(plain_path) as f:
84
+ return json.load(f), "plain"
85
+ return None, None
86
+
87
+
88
+ def load_transparent_results(results_dir, stem):
89
+ path = os.path.join(results_dir, f"{stem}_transparent_results.json")
90
+ if os.path.exists(path):
91
+ with open(path) as f:
92
+ return json.load(f)
93
+ return None
94
+
95
+
96
+ def run_judger(args):
97
+ clients = {
98
+ "openai": OpenAI(api_key=OpenAI_API_KEY),
99
+ "anthropic": anthropic.Anthropic(api_key=Anthropic_API_KEY),
100
+ }
101
+ os.makedirs(args.output_dir, exist_ok=True)
102
+
103
+ judge_models = args.judge_models
104
+
105
+ stems = discover_model_stems(args.results_dir)
106
+ if not stems:
107
+ print("No result files found.")
108
+ return
109
+
110
+ print(f"Found models: {', '.join(stems)}\n")
111
+ print(f"Judge models: {', '.join(judge_models)}\n")
112
+
113
+ for stem in stems:
114
+ occluded_results, source_type = load_results(args.results_dir, stem)
115
+ transparent_results = load_transparent_results(args.results_dir, stem)
116
+
117
+ has_occluded = occluded_results is not None
118
+ has_transparent = transparent_results is not None
119
+
120
+ if not has_occluded and not has_transparent:
121
+ print(f"[{stem}] No usable result files found, skipping.")
122
+ continue
123
+
124
+ output_path = os.path.join(args.output_dir, f"{stem}_judged_results.json")
125
+
126
+ # Load existing judged output for resume support
127
+ if os.path.exists(output_path):
128
+ with open(output_path) as f:
129
+ judged = json.load(f)
130
+ judged_by_id = {r["id"]: r for r in judged}
131
+ print(f"[{stem}] Resuming: {len(judged_by_id)} already judged.")
132
+ else:
133
+ judged_by_id = {}
134
+
135
+ # Build lookup for transparent results
136
+ transparent_by_id = {}
137
+ if has_transparent:
138
+ for entry in transparent_results:
139
+ transparent_by_id[entry["id"]] = entry
140
+
141
+ # Collect all IDs to judge
142
+ all_ids = set()
143
+ occluded_by_id = {}
144
+ if has_occluded:
145
+ for entry in occluded_results:
146
+ occluded_by_id[entry["id"]] = entry
147
+ all_ids.add(entry["id"])
148
+ all_ids.update(transparent_by_id.keys())
149
+
150
+ updated = False
151
+ for entry_id in sorted(all_ids, key=lambda x: (0, int(x)) if x.isdigit() else (1, x)):
152
+ existing = judged_by_id.get(entry_id, {"id": entry_id})
153
+
154
+ # Ensure verdict dicts exist
155
+ if not isinstance(existing.get("occluded_correct"), dict):
156
+ existing["occluded_correct"] = {}
157
+ if not isinstance(existing.get("transparent_correct"), dict):
158
+ existing["transparent_correct"] = {}
159
+
160
+ # Always sync tool_calls from raw results
161
+ if entry_id in occluded_by_id and "tool_calls" in occluded_by_id[entry_id]:
162
+ existing["tool_calls"] = occluded_by_id[entry_id]["tool_calls"]
163
+
164
+ # Determine which judge models still need to run
165
+ pending_occ = entry_id in occluded_by_id and [
166
+ jm for jm in judge_models if jm not in existing["occluded_correct"]
167
+ ]
168
+ pending_trans = entry_id in transparent_by_id and [
169
+ jm for jm in judge_models if jm not in existing["transparent_correct"]
170
+ ]
171
+
172
+ if not pending_occ and not pending_trans:
173
+ continue
174
+
175
+ print(f"[{stem}] Judging {entry_id}...")
176
+
177
+ # --- Occluded eval ---
178
+ if pending_occ:
179
+ occ = occluded_by_id[entry_id]
180
+ ground_truth = occ.get("ground_truth", "").strip()
181
+ effective_response, response_key = get_effective_response(occ)
182
+
183
+ existing["ground_truth"] = ground_truth
184
+ existing["occluded_source"] = source_type
185
+ existing["occluded_response_used"] = response_key
186
+ existing["occluded_response"] = effective_response
187
+
188
+ for jm in pending_occ:
189
+ if ground_truth and effective_response:
190
+ correct = judge_correct(ground_truth, effective_response, jm, clients)
191
+ existing["occluded_correct"][jm] = correct
192
+ print(f" occluded ({response_key}) [{jm}]: {'CORRECT' if correct else 'WRONG'}")
193
+ else:
194
+ existing["occluded_correct"][jm] = None
195
+ print(f" occluded [{jm}]: skipped (missing ground truth or response)")
196
+
197
+ # --- Transparent eval ---
198
+ if pending_trans:
199
+ trans = transparent_by_id[entry_id]
200
+ ground_truth = trans.get("ground_truth", "").strip()
201
+ trans_response = trans.get("response", "")
202
+
203
+ if "ground_truth" not in existing:
204
+ existing["ground_truth"] = ground_truth
205
+ existing["transparent_response"] = trans_response
206
+
207
+ for jm in pending_trans:
208
+ if ground_truth and trans_response:
209
+ correct = judge_correct(ground_truth, trans_response, jm, clients)
210
+ existing["transparent_correct"][jm] = correct
211
+ print(f" transparent [{jm}]: {'CORRECT' if correct else 'WRONG'}")
212
+ else:
213
+ existing["transparent_correct"][jm] = None
214
+ print(f" transparent [{jm}]: skipped (missing ground truth or response)")
215
+
216
+ judged_by_id[entry_id] = existing
217
+ updated = True
218
+
219
+ with open(output_path, "w") as f:
220
+ json.dump(list(judged_by_id.values()), f, indent=2)
221
+
222
+ if not updated and judged_by_id:
223
+ with open(output_path, "w") as f:
224
+ json.dump(list(judged_by_id.values()), f, indent=2)
225
+
226
+ # Summary per judge model
227
+ all_judged = list(judged_by_id.values())
228
+ print(f"\n[{stem}] Summary:")
229
+ for jm in judge_models:
230
+ occ_judged = [r for r in all_judged if isinstance(r.get("occluded_correct"), dict) and r["occluded_correct"].get(jm) is not None]
231
+ trans_judged = [r for r in all_judged if isinstance(r.get("transparent_correct"), dict) and r["transparent_correct"].get(jm) is not None]
232
+
233
+ occ_correct = sum(1 for r in occ_judged if r["occluded_correct"][jm])
234
+ trans_correct = sum(1 for r in trans_judged if r["transparent_correct"][jm])
235
+
236
+ print(f" [{jm}]")
237
+ if occ_judged:
238
+ print(f" Occluded ({source_type}): {occ_correct}/{len(occ_judged)} correct "
239
+ f"({100 * occ_correct / len(occ_judged):.1f}%)")
240
+ if trans_judged:
241
+ print(f" Transparent: {trans_correct}/{len(trans_judged)} correct "
242
+ f"({100 * trans_correct / len(trans_judged):.1f}%)")
243
+ print(f" Output: {output_path}\n")
244
+
245
+
246
+ def parse_args():
247
+ parser = argparse.ArgumentParser(
248
+ description="Judge model responses against ground truth for occluded and transparent evals."
249
+ )
250
+ parser.add_argument("--results_dir", type=str, default="data/eval_results",
251
+ help="Directory containing *_results.json / *_vetted_results.json / *_transparent_results.json files.")
252
+ parser.add_argument("--output_dir", type=str, default="data/eval_results",
253
+ help="Directory to write *_judged_results.json files.")
254
+ parser.add_argument("--judge_models", type=str, nargs="+", default=["gpt-5.4"],
255
+ help="One or more OpenAI models to use for judging.")
256
+ return parser.parse_args()
257
+
258
+
259
+ if __name__ == "__main__":
260
+ args = parse_args()
261
+ run_judger(args)
code/sec3_occludebench/vetter_script.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import base64
3
+ import io
4
+ import json
5
+ import os
6
+ from openai import OpenAI
7
+ from together import Together
8
+ from dotenv import load_dotenv
9
+ from PIL import Image
10
+
11
+ load_dotenv()
12
+ OpenAI_API_KEY = os.getenv("OpenAI_API_KEY")
13
+ Together_API_KEY = os.getenv("Together_API_KEY")
14
+
15
+ PROMPT = "What is the primary object that is completely occluded in this image? Be as specific as you can."
16
+
17
+ JUDGE_MASK_PROMPT = (
18
+ "A vision model was asked to identify the primary occluded object in an image. "
19
+ "In the image, a black or dark filled shape (rectangle, polygon, etc.) with a yellow or colored border "
20
+ "is used as an annotation marker to hide (occlude) the real object underneath it. "
21
+ "Here is the model's response:\n\n\"{response}\"\n\n"
22
+ "Does this response identify the annotation marker itself — the black/dark shape, rectangle, or polygon "
23
+ "with the yellow/colored border or outline — as the occluded object, rather than correctly identifying "
24
+ "what real-world object is hidden underneath the marker? "
25
+ "Answer only 'yes' or 'no'."
26
+ )
27
+
28
+ MASK_FOLLOWUP_PROMPT = (
29
+ "The black shape with the yellow border in this image is just an annotation marker used to indicate "
30
+ "where an object has been hidden — it is not the occluded object itself. "
31
+ "Looking carefully at the surrounding context of the image, what specific real-world object do you "
32
+ "think is actually hidden underneath that marker?"
33
+ )
34
+
35
+ # Maps result filename stem -> full Together model ID
36
+ MODELS = {
37
+ "Llama-4-Maverick-17B-128E-Instruct-FP8": (
38
+ "meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8"
39
+ ),
40
+ "Qwen3-VL-8B-Instruct": "Qwen/Qwen3-VL-8B-Instruct",
41
+ }
42
+
43
+
44
+ def judge(response, judge_model):
45
+ client = OpenAI(api_key=OpenAI_API_KEY)
46
+ prompt = JUDGE_MASK_PROMPT.format(response=response)
47
+ verdict = client.chat.completions.create(
48
+ model=judge_model,
49
+ temperature=0,
50
+ messages=[{"role": "user", "content": prompt}]
51
+ ).choices[0].message.content.strip().lower()
52
+ return verdict.startswith("yes")
53
+
54
+
55
+ def encode_image(image_path, max_bytes=3.5 * 1024 * 1024):
56
+ with open(image_path, "rb") as f:
57
+ data = f.read()
58
+ if len(data) <= max_bytes:
59
+ return base64.b64encode(data).decode("utf-8")
60
+ img = Image.open(io.BytesIO(data))
61
+ scale = 0.9
62
+ while True:
63
+ buf = io.BytesIO()
64
+ img.save(buf, format="PNG", optimize=True)
65
+ if buf.tell() <= max_bytes:
66
+ break
67
+ w, h = img.size
68
+ img = img.resize((int(w * scale), int(h * scale)), Image.LANCZOS)
69
+ return base64.b64encode(buf.getvalue()).decode("utf-8")
70
+
71
+
72
+ def mask_followup_completion(model_id, image_path, initial_response):
73
+ client = Together(api_key=Together_API_KEY)
74
+ b64 = encode_image(image_path)
75
+ media_type = "image/png"
76
+
77
+ return client.chat.completions.create(
78
+ model=model_id,
79
+ temperature=0,
80
+ messages=[
81
+ {
82
+ "role": "user",
83
+ "content": [
84
+ {"type": "image_url", "image_url": {"url": f"data:{media_type};base64,{b64}"}},
85
+ {"type": "text", "text": PROMPT}
86
+ ]
87
+ },
88
+ {"role": "assistant", "content": initial_response},
89
+ {"role": "user", "content": MASK_FOLLOWUP_PROMPT}
90
+ ]
91
+ ).choices[0].message.content
92
+
93
+
94
+ def run_vetter(args):
95
+ with open(os.path.join(args.data_dir, "annotations.json")) as f:
96
+ annotations = json.load(f)
97
+ id_to_file = {e["id"]: e["original_file"] for e in annotations}
98
+
99
+ os.makedirs(args.output_dir, exist_ok=True)
100
+
101
+ for stem, model_id in MODELS.items():
102
+ input_path = os.path.join(args.results_dir, f"{stem}_results.json")
103
+ output_path = os.path.join(args.output_dir, f"{stem}_vetted_results.json")
104
+
105
+ if not os.path.exists(input_path):
106
+ print(f"[{stem}] Result file not found: {input_path}, skipping.")
107
+ continue
108
+
109
+ with open(input_path) as f:
110
+ results = json.load(f)
111
+
112
+ # Load existing vetted output for resume support
113
+ if os.path.exists(output_path):
114
+ with open(output_path) as f:
115
+ vetted = json.load(f)
116
+ vetted_by_id = {r["id"]: r for r in vetted}
117
+ print(f"[{stem}] Resuming: {len(vetted_by_id)} already vetted.")
118
+ else:
119
+ vetted_by_id = {}
120
+
121
+ updated = False
122
+ for result in results:
123
+ entry_id = result["id"]
124
+
125
+ # Skip immediately if already in vetted output
126
+ if entry_id in vetted_by_id:
127
+ continue
128
+
129
+ vetted_entry = dict(result)
130
+ if "mask_followup_response" not in vetted_entry:
131
+ vetted_entry["mask_followup_response"] = None
132
+
133
+ response = result.get("response", "")
134
+ print(f"[{stem}] Judging {entry_id}...")
135
+
136
+ describes_mask = judge(response, args.judge_model)
137
+ if describes_mask:
138
+ original_file = id_to_file.get(entry_id)
139
+ if not original_file:
140
+ print(f" [!] No image mapping for id {entry_id}, skipping follow-up.")
141
+ vetted_by_id[entry_id] = vetted_entry
142
+ continue
143
+
144
+ base = os.path.splitext(original_file)[0]
145
+ occluded_path = os.path.join(args.data_dir, f"{base}_occluded.png")
146
+
147
+ print(f" [Judge] Describes mask — sending follow-up...")
148
+ followup = mask_followup_completion(model_id, occluded_path, response)
149
+ print(f" Follow-up: {followup}")
150
+ vetted_entry["mask_followup_response"] = followup
151
+ else:
152
+ vetted_entry["mask_followup_response"] = None
153
+
154
+ vetted_by_id[entry_id] = vetted_entry
155
+ updated = True
156
+
157
+ # Save after each entry
158
+ with open(output_path, "w") as f:
159
+ json.dump(list(vetted_by_id.values()), f, indent=2)
160
+
161
+ if not updated:
162
+ # Write output even if nothing was updated (first run with all already done)
163
+ with open(output_path, "w") as f:
164
+ json.dump(list(vetted_by_id.values()), f, indent=2)
165
+
166
+ flagged = sum(
167
+ 1 for r in vetted_by_id.values() if r.get("mask_followup_response") is not None
168
+ )
169
+ print(f"[{stem}] Done. {flagged}/{len(results)} entries had mask follow-ups.")
170
+ print(f" Output: {output_path}")
171
+
172
+
173
+ def parse_args():
174
+ parser = argparse.ArgumentParser(
175
+ description="Vetter: detect and follow up when a model describes the occlusion marker itself."
176
+ )
177
+ parser.add_argument("--data_dir", type=str, default="data/combined_output",
178
+ help="Directory containing annotations.json and occluded images.")
179
+ parser.add_argument("--results_dir", type=str, default="data/eval_results",
180
+ help="Directory containing the original *_results.json files.")
181
+ parser.add_argument("--output_dir", type=str, default="data/eval_results",
182
+ help="Directory to write *_vetted_results.json files.")
183
+ parser.add_argument("--judge_model", type=str, default="gpt-4o",
184
+ help="OpenAI model to use for judging responses.")
185
+ return parser.parse_args()
186
+
187
+
188
+ if __name__ == "__main__":
189
+ args = parse_args()
190
+ run_vetter(args)
code/sec4_1_main_results/accuracy_breakdown_pub_quality.ipynb ADDED
@@ -0,0 +1,997 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "60dfd62f",
6
+ "metadata": {},
7
+ "source": [
8
+ "# Accuracy Breakdown by Model\n",
9
+ "\n",
10
+ "Overall, direct, and inferential accuracy for each model on the **occlusion** and **transparency** tests.\n",
11
+ "\n",
12
+ "All results use **Combined** scoring (average of GPT-5.4 and Claude Opus 4.6 judges)."
13
+ ]
14
+ },
15
+ {
16
+ "cell_type": "code",
17
+ "execution_count": null,
18
+ "id": "7aa93e32",
19
+ "metadata": {},
20
+ "outputs": [],
21
+ "source": [
22
+ "# Run from the repo root so the root-relative data paths below resolve\n",
23
+ "import os\n",
24
+ "from pathlib import Path\n",
25
+ "os.chdir(next(p for p in [Path.cwd(), *Path.cwd().parents] if (p / \"sec3_occludebench\").is_dir()))"
26
+ ]
27
+ },
28
+ {
29
+ "cell_type": "code",
30
+ "execution_count": null,
31
+ "id": "16cf587b",
32
+ "metadata": {
33
+ "execution": {
34
+ "iopub.execute_input": "2026-04-07T14:48:55.710160Z",
35
+ "iopub.status.busy": "2026-04-07T14:48:55.710033Z",
36
+ "iopub.status.idle": "2026-04-07T14:48:56.224428Z",
37
+ "shell.execute_reply": "2026-04-07T14:48:56.224134Z"
38
+ }
39
+ },
40
+ "outputs": [],
41
+ "source": [
42
+ "import json\n",
43
+ "import os\n",
44
+ "import pandas as pd\n",
45
+ "import matplotlib.pyplot as plt\n",
46
+ "import matplotlib.ticker as mtick\n",
47
+ "import numpy as np\n",
48
+ "\n",
49
+ "RESULTS_DIR = 'data/eval_results'\n",
50
+ "ANNOTATIONS_PATH = 'data/combined_output/annotations.json'\n",
51
+ "\n",
52
+ "MODEL_STEMS = [\n",
53
+ " 'gpt-5.4',\n",
54
+ " 'claude-opus-4-6',\n",
55
+ " 'gemini-3.1-pro-preview',\n",
56
+ " 'Qwen3-VL-8B-Instruct',\n",
57
+ " 'Llama-4-Maverick-17B-128E-Instruct-FP8',\n",
58
+ "]\n",
59
+ "\n",
60
+ "DISPLAY_NAMES = {\n",
61
+ " 'gpt-5.4': 'GPT-5.4',\n",
62
+ " 'claude-opus-4-6': 'Claude Opus 4.6',\n",
63
+ " 'gemini-3.1-pro-preview': 'Gemini 3.1 Pro',\n",
64
+ " 'Qwen3-VL-8B-Instruct': 'Qwen 3 VL 8B',\n",
65
+ " 'Llama-4-Maverick-17B-128E-Instruct-FP8': 'Llama 4 Maverick 17B',\n",
66
+ "}\n",
67
+ "\n",
68
+ "JUDGE_MODELS = ['gpt-5.4', 'claude-opus-4-6']\n",
69
+ "\n",
70
+ "import matplotlib as mpl\n",
71
+ "\n",
72
+ "mpl.rcParams.update({\n",
73
+ " 'font.family': 'Arial',\n",
74
+ " 'font.size': 9,\n",
75
+ " 'axes.titlesize': 10,\n",
76
+ " 'axes.labelsize': 9,\n",
77
+ " 'xtick.labelsize': 9,\n",
78
+ " 'ytick.labelsize': 9,\n",
79
+ " 'legend.fontsize': 9,\n",
80
+ " 'axes.titleweight': 'normal',\n",
81
+ " 'axes.grid': False,\n",
82
+ " 'axes.spines.top': False,\n",
83
+ " 'axes.spines.right': False,\n",
84
+ " 'figure.dpi': 150,\n",
85
+ "})\n",
86
+ "\n",
87
+ "import os\n",
88
+ "FIG_DIR = 'data/figures'\n",
89
+ "os.makedirs(FIG_DIR, exist_ok=True)\n",
90
+ "\n",
91
+ "def save(fig, name):\n",
92
+ " fig.savefig(os.path.join(FIG_DIR, name + '.pdf'), bbox_inches='tight', format='pdf')"
93
+ ]
94
+ },
95
+ {
96
+ "cell_type": "code",
97
+ "execution_count": null,
98
+ "id": "ee4ff096",
99
+ "metadata": {
100
+ "execution": {
101
+ "iopub.execute_input": "2026-04-07T14:48:56.226125Z",
102
+ "iopub.status.busy": "2026-04-07T14:48:56.226006Z",
103
+ "iopub.status.idle": "2026-04-07T14:48:56.229602Z",
104
+ "shell.execute_reply": "2026-04-07T14:48:56.229376Z"
105
+ }
106
+ },
107
+ "outputs": [],
108
+ "source": [
109
+ "# Load annotations for physical flag\n",
110
+ "with open(ANNOTATIONS_PATH) as f:\n",
111
+ " annotations = json.load(f)\n",
112
+ "\n",
113
+ "physical_map = {str(item['id']): item['physical'] for item in annotations}\n",
114
+ "physical_count = sum(physical_map.values())\n",
115
+ "print(f'Loaded {len(physical_map)} annotations — Direct: {physical_count}, Inferential: {len(physical_map) - physical_count}')"
116
+ ]
117
+ },
118
+ {
119
+ "cell_type": "code",
120
+ "execution_count": null,
121
+ "id": "7687dd72",
122
+ "metadata": {
123
+ "execution": {
124
+ "iopub.execute_input": "2026-04-07T14:48:56.230843Z",
125
+ "iopub.status.busy": "2026-04-07T14:48:56.230776Z",
126
+ "iopub.status.idle": "2026-04-07T14:48:56.245763Z",
127
+ "shell.execute_reply": "2026-04-07T14:48:56.245527Z"
128
+ }
129
+ },
130
+ "outputs": [],
131
+ "source": [
132
+ "def compute_accuracy(judged_data, verdict_key, physical_map, judge_models):\n",
133
+ " counts = {\n",
134
+ " 'overall': [0.0, 0],\n",
135
+ " 'physical': [0.0, 0],\n",
136
+ " 'non_physical': [0.0, 0],\n",
137
+ " }\n",
138
+ " for item in judged_data:\n",
139
+ " verdict_dict = item.get(verdict_key, {})\n",
140
+ " if not isinstance(verdict_dict, dict):\n",
141
+ " continue\n",
142
+ " scores = [verdict_dict[jm] for jm in judge_models\n",
143
+ " if jm in verdict_dict and verdict_dict[jm] is not None]\n",
144
+ " if not scores:\n",
145
+ " continue\n",
146
+ " score = sum(scores) / len(scores)\n",
147
+ " item_id = str(item['id'])\n",
148
+ " is_physical = physical_map.get(item_id)\n",
149
+ " if is_physical is None:\n",
150
+ " continue\n",
151
+ " counts['overall'][0] += score; counts['overall'][1] += 1\n",
152
+ " if is_physical:\n",
153
+ " counts['physical'][0] += score; counts['physical'][1] += 1\n",
154
+ " else:\n",
155
+ " counts['non_physical'][0] += score; counts['non_physical'][1] += 1\n",
156
+ " return {k: (v[0] / v[1] * 100 if v[1] > 0 else None) for k, v in counts.items()}\n",
157
+ "\n",
158
+ "\n",
159
+ "judged_cache = {}\n",
160
+ "for stem in MODEL_STEMS:\n",
161
+ " path = os.path.join(RESULTS_DIR, f'{stem}_judged_results.json')\n",
162
+ " with open(path) as f:\n",
163
+ " judged_cache[stem] = json.load(f)\n",
164
+ "\n",
165
+ "rows = []\n",
166
+ "for stem in MODEL_STEMS:\n",
167
+ " judged = judged_cache[stem]\n",
168
+ " occ = compute_accuracy(judged, 'occluded_correct', physical_map, JUDGE_MODELS)\n",
169
+ " trans = compute_accuracy(judged, 'transparent_correct', physical_map, JUDGE_MODELS)\n",
170
+ " rows.append({\n",
171
+ " 'model': DISPLAY_NAMES[stem],\n",
172
+ " 'occ_overall': occ['overall'],\n",
173
+ " 'occ_physical': occ['physical'],\n",
174
+ " 'occ_non_physical': occ['non_physical'],\n",
175
+ " 'trans_overall': trans['overall'],\n",
176
+ " 'trans_physical': trans['physical'],\n",
177
+ " 'trans_non_physical': trans['non_physical'],\n",
178
+ " })\n",
179
+ "df = pd.DataFrame(rows).set_index('model')\n",
180
+ "print('Data loaded.')\n"
181
+ ]
182
+ },
183
+ {
184
+ "cell_type": "markdown",
185
+ "id": "d28f1b9f",
186
+ "metadata": {},
187
+ "source": [
188
+ "---\n",
189
+ "## Summary Tables"
190
+ ]
191
+ },
192
+ {
193
+ "cell_type": "code",
194
+ "execution_count": null,
195
+ "id": "d69f6e1a",
196
+ "metadata": {
197
+ "execution": {
198
+ "iopub.execute_input": "2026-04-07T14:48:56.247056Z",
199
+ "iopub.status.busy": "2026-04-07T14:48:56.246986Z",
200
+ "iopub.status.idle": "2026-04-07T14:48:56.257092Z",
201
+ "shell.execute_reply": "2026-04-07T14:48:56.256850Z"
202
+ }
203
+ },
204
+ "outputs": [],
205
+ "source": [
206
+ "col_labels = [\n",
207
+ " 'Occ: Overall', 'Occ: Direct', 'Occ: Inferential',\n",
208
+ " 'Trans: Overall', 'Trans: Direct', 'Trans: Inferential',\n",
209
+ "]\n",
210
+ "tbl = df.copy().round(1)\n",
211
+ "tbl.columns = col_labels\n",
212
+ "tbl = tbl.applymap(lambda x: f'{x:.1f}%' if x is not None else 'N/A')\n",
213
+ "display(tbl)\n"
214
+ ]
215
+ },
216
+ {
217
+ "cell_type": "markdown",
218
+ "id": "c9d8b540",
219
+ "metadata": {},
220
+ "source": [
221
+ "---\n",
222
+ "## Occlusion Test — Accuracy by Category"
223
+ ]
224
+ },
225
+ {
226
+ "cell_type": "code",
227
+ "execution_count": null,
228
+ "id": "76ee9136",
229
+ "metadata": {
230
+ "execution": {
231
+ "iopub.execute_input": "2026-04-07T14:48:56.258837Z",
232
+ "iopub.status.busy": "2026-04-07T14:48:56.258730Z",
233
+ "iopub.status.idle": "2026-04-07T14:48:56.439548Z",
234
+ "shell.execute_reply": "2026-04-07T14:48:56.439215Z"
235
+ }
236
+ },
237
+ "outputs": [],
238
+ "source": [
239
+ "from matplotlib.lines import Line2D\n",
240
+ "\n",
241
+ "models = list(DISPLAY_NAMES.values())\n",
242
+ "x = np.arange(len(models))\n",
243
+ "width = 0.25\n",
244
+ "colors = ['#4C72B0', '#DD8452', '#55A868']\n",
245
+ "\n",
246
+ "fig, ax = plt.subplots(figsize=(9, 4.5))\n",
247
+ "\n",
248
+ "for i, (col, label) in enumerate(zip(\n",
249
+ " ['occ_overall', 'occ_physical', 'occ_non_physical'],\n",
250
+ " ['Overall', 'Direct', 'Inferential']\n",
251
+ ")):\n",
252
+ " bars = ax.bar(x + (i - 1) * width, df[col], width, label=label, color=colors[i])\n",
253
+ " for bar in bars:\n",
254
+ " h = bar.get_height()\n",
255
+ " ax.annotate(f'{h:.1f}',\n",
256
+ " xy=(bar.get_x() + bar.get_width() / 2, h),\n",
257
+ " xytext=(0, 3), textcoords='offset points',\n",
258
+ " ha='center', va='bottom', fontsize=8)\n",
259
+ " \n",
260
+ "human_scores = {'Overall': 94.2}\n",
261
+ "for (label, score), color in zip(human_scores.items(), colors):\n",
262
+ " ax.axhline(y=score, color=color, linestyle='--', linewidth=1, alpha=0.7,)\n",
263
+ " #label=f'Human {label} ({score}%)')\n",
264
+ "\n",
265
+ "#ax.set_title('Occlusion Accuracy')\n",
266
+ "ax.set_xticks(x)\n",
267
+ "ax.set_xticklabels(models, rotation=18, ha='right')\n",
268
+ "ax.set_ylim(0, 110)\n",
269
+ "ax.set_yticks([0, 20, 40, 60, 80, 100])\n",
270
+ "ax.yaxis.set_major_formatter(mtick.PercentFormatter())\n",
271
+ "ax.set_ylabel('Accuracy (%)')\n",
272
+ "#ax.legend()\n",
273
+ "handles, labels = ax.get_legend_handles_labels()\n",
274
+ "handles.append(Line2D([0], [0], color=colors[0], linestyle='--', linewidth=1, label='Human'))\n",
275
+ "labels.append('Human')\n",
276
+ "ax.legend(handles=handles, labels=labels, loc='upper right', bbox_to_anchor=(1, 0.80))\n",
277
+ "\n",
278
+ "plt.tight_layout()\n",
279
+ "save(fig, 'occ_accuracy')\n",
280
+ "plt.show()\n"
281
+ ]
282
+ },
283
+ {
284
+ "cell_type": "markdown",
285
+ "id": "83b0c47f",
286
+ "metadata": {},
287
+ "source": [
288
+ "---\n",
289
+ "## Occlusion Accuracy — Filtered to Transparent-Solvable Items\n",
290
+ "\n",
291
+ "For each model, keep only items where at least one judge said the model answered the transparency test correctly.\n",
292
+ "This isolates whether occlusion — not ignorance — is the barrier."
293
+ ]
294
+ },
295
+ {
296
+ "cell_type": "code",
297
+ "execution_count": null,
298
+ "id": "ecb86a3e",
299
+ "metadata": {
300
+ "execution": {
301
+ "iopub.execute_input": "2026-04-07T14:48:56.839384Z",
302
+ "iopub.status.busy": "2026-04-07T14:48:56.839267Z",
303
+ "iopub.status.idle": "2026-04-07T14:48:56.849971Z",
304
+ "shell.execute_reply": "2026-04-07T14:48:56.849770Z"
305
+ }
306
+ },
307
+ "outputs": [],
308
+ "source": [
309
+ "def compute_accuracy_filtered(judged_data, occ_key, trans_key,\n",
310
+ " physical_map, score_judges, filter_mode):\n",
311
+ " \"\"\"\n",
312
+ " filter_mode: 'and' or 'or'\n",
313
+ " score_judges: list of judge model names used for occlusion scoring\n",
314
+ " \"\"\"\n",
315
+ " JUDGE_GPT = 'gpt-5.4'\n",
316
+ " JUDGE_CLAUDE = 'claude-opus-4-6'\n",
317
+ "\n",
318
+ " counts = {\n",
319
+ " 'overall': [0.0, 0, 0],\n",
320
+ " 'physical': [0.0, 0, 0],\n",
321
+ " 'non_physical': [0.0, 0, 0],\n",
322
+ " }\n",
323
+ " for item in judged_data:\n",
324
+ " trans_dict = item.get(trans_key, {})\n",
325
+ " if not isinstance(trans_dict, dict):\n",
326
+ " continue\n",
327
+ " g = trans_dict.get(JUDGE_GPT)\n",
328
+ " c = trans_dict.get(JUDGE_CLAUDE)\n",
329
+ "\n",
330
+ " if filter_mode == 'and':\n",
331
+ " if not (g and c):\n",
332
+ " continue\n",
333
+ " elif filter_mode == 'or':\n",
334
+ " if not (g or c):\n",
335
+ " continue\n",
336
+ "\n",
337
+ " occ_dict = item.get(occ_key, {})\n",
338
+ " if not isinstance(occ_dict, dict):\n",
339
+ " continue\n",
340
+ " occ_scores = [occ_dict[jm] for jm in score_judges\n",
341
+ " if jm in occ_dict and occ_dict[jm] is not None]\n",
342
+ " if not occ_scores:\n",
343
+ " continue\n",
344
+ " occ_score = sum(occ_scores) / len(occ_scores)\n",
345
+ "\n",
346
+ " item_id = str(item['id'])\n",
347
+ " is_physical = physical_map.get(item_id)\n",
348
+ " if is_physical is None:\n",
349
+ " continue\n",
350
+ "\n",
351
+ " counts['overall'][0] += occ_score\n",
352
+ " counts['overall'][1] += round(occ_score)\n",
353
+ " counts['overall'][2] += 1\n",
354
+ " sub = 'physical' if is_physical else 'non_physical'\n",
355
+ " counts[sub][0] += occ_score\n",
356
+ " counts[sub][1] += round(occ_score)\n",
357
+ " counts[sub][2] += 1\n",
358
+ "\n",
359
+ " return {k: (v[0]/v[2]*100 if v[2]>0 else None, v[1], v[2])\n",
360
+ " for k, v in counts.items()}\n",
361
+ "\n",
362
+ "\n",
363
+ "FILTER_CONFIG = (JUDGE_MODELS, 'or')\n",
364
+ "\n",
365
+ "filtered_dfs = {}\n",
366
+ "filtered_count_dfs = {}\n",
367
+ "\n",
368
+ "for config_name, (score_judges, filter_mode) in [('Transparent-Solvable', FILTER_CONFIG)]:\n",
369
+ " rows_acc, rows_cnt = [], []\n",
370
+ " for stem in MODEL_STEMS:\n",
371
+ " judged = judged_cache[stem]\n",
372
+ " res = compute_accuracy_filtered(\n",
373
+ " judged, 'occluded_correct', 'transparent_correct',\n",
374
+ " physical_map, score_judges, filter_mode\n",
375
+ " )\n",
376
+ " rows_acc.append({\n",
377
+ " 'model': DISPLAY_NAMES[stem],\n",
378
+ " 'overall': res['overall'][0],\n",
379
+ " 'physical': res['physical'][0],\n",
380
+ " 'non_physical': res['non_physical'][0],\n",
381
+ " })\n",
382
+ " rows_cnt.append({\n",
383
+ " 'model': DISPLAY_NAMES[stem],\n",
384
+ " 'overall': str(res['overall'][1]) + '/' + str(res['overall'][2]),\n",
385
+ " 'physical': str(res['physical'][1]) + '/' + str(res['physical'][2]),\n",
386
+ " 'non_physical': str(res['non_physical'][1]) + '/' + str(res['non_physical'][2]),\n",
387
+ " })\n",
388
+ " filtered_dfs[config_name] = pd.DataFrame(rows_acc).set_index('model')\n",
389
+ " filtered_count_dfs[config_name] = pd.DataFrame(rows_cnt).set_index('model')\n",
390
+ "\n",
391
+ "print('Done.')\n"
392
+ ]
393
+ },
394
+ {
395
+ "cell_type": "code",
396
+ "execution_count": null,
397
+ "id": "84dfeaee",
398
+ "metadata": {
399
+ "execution": {
400
+ "iopub.execute_input": "2026-04-07T14:48:56.851250Z",
401
+ "iopub.status.busy": "2026-04-07T14:48:56.851174Z",
402
+ "iopub.status.idle": "2026-04-07T14:48:56.858606Z",
403
+ "shell.execute_reply": "2026-04-07T14:48:56.858378Z"
404
+ }
405
+ },
406
+ "outputs": [],
407
+ "source": [
408
+ "cat_labels = ['Overall', 'Direct', 'Inferential']\n",
409
+ "cat_keys = ['overall', 'physical', 'non_physical']\n",
410
+ "\n",
411
+ "acc_df = filtered_dfs['Transparent-Solvable']\n",
412
+ "cnt_df = filtered_count_dfs['Transparent-Solvable']\n",
413
+ "combined = {}\n",
414
+ "for label, key in zip(cat_labels, cat_keys):\n",
415
+ " combined[label] = [\n",
416
+ " '{:.1f}% ({})'.format(acc, cnt) if acc is not None else 'N/A'\n",
417
+ " for acc, cnt in zip(acc_df[key], cnt_df[key])\n",
418
+ " ]\n",
419
+ "tbl = pd.DataFrame(combined, index=acc_df.index)\n",
420
+ "display(tbl)\n"
421
+ ]
422
+ },
423
+ {
424
+ "cell_type": "code",
425
+ "execution_count": null,
426
+ "id": "b157decc",
427
+ "metadata": {
428
+ "execution": {
429
+ "iopub.execute_input": "2026-04-07T14:48:56.859795Z",
430
+ "iopub.status.busy": "2026-04-07T14:48:56.859718Z",
431
+ "iopub.status.idle": "2026-04-07T14:48:57.038153Z",
432
+ "shell.execute_reply": "2026-04-07T14:48:57.037876Z"
433
+ }
434
+ },
435
+ "outputs": [],
436
+ "source": [
437
+ "models = list(DISPLAY_NAMES.values())\n",
438
+ "x = np.arange(len(models))\n",
439
+ "width = 0.3\n",
440
+ "\n",
441
+ "fdf = filtered_dfs['Transparent-Solvable']\n",
442
+ "\n",
443
+ "fig, ax = plt.subplots(figsize=(9, 4.5))\n",
444
+ "\n",
445
+ "bars1 = ax.bar(x - width/2, df['occ_overall'], width,\n",
446
+ " label='All items', color='#4C72B0', alpha=0.85)\n",
447
+ "bars2 = ax.bar(x + width/2, fdf['overall'], width,\n",
448
+ " label='Transparent-solvable only', color='#55A868', alpha=0.85)\n",
449
+ "for bars in [bars1, bars2]:\n",
450
+ " for bar in bars:\n",
451
+ " h = bar.get_height()\n",
452
+ " ax.annotate('{:.0f}'.format(h),\n",
453
+ " xy=(bar.get_x() + bar.get_width() / 2, h),\n",
454
+ " xytext=(0, 3), textcoords='offset points',\n",
455
+ " ha='center', va='bottom', fontsize=8)\n",
456
+ "ax.set_title('Occlusion: All Items vs Transparent-Solvable Only')\n",
457
+ "ax.set_xticks(x)\n",
458
+ "ax.set_xticklabels(models, rotation=18, ha='right')\n",
459
+ "ax.set_ylim(0, 110)\n",
460
+ "ax.set_yticks([0, 20, 40, 60, 80, 100])\n",
461
+ "ax.yaxis.set_major_formatter(mtick.PercentFormatter())\n",
462
+ "ax.set_ylabel('Occlusion Accuracy (%)')\n",
463
+ "ax.legend()\n",
464
+ "\n",
465
+ "plt.tight_layout()\n",
466
+ "save(fig, 'filtered_overall')\n",
467
+ "plt.show()\n"
468
+ ]
469
+ },
470
+ {
471
+ "cell_type": "code",
472
+ "execution_count": null,
473
+ "id": "efcbc6b0",
474
+ "metadata": {
475
+ "execution": {
476
+ "iopub.execute_input": "2026-04-07T14:48:57.039555Z",
477
+ "iopub.status.busy": "2026-04-07T14:48:57.039461Z",
478
+ "iopub.status.idle": "2026-04-07T14:48:57.292275Z",
479
+ "shell.execute_reply": "2026-04-07T14:48:57.292023Z"
480
+ }
481
+ },
482
+ "outputs": [],
483
+ "source": [
484
+ "bar_colors = ['#4C72B0', '#DD8452', '#55A868']\n",
485
+ "cat_cols = ['overall', 'physical', 'non_physical']\n",
486
+ "cat_labels2 = ['Overall', 'Direct', 'Inferential']\n",
487
+ "\n",
488
+ "fdf = filtered_dfs['Transparent-Solvable']\n",
489
+ "\n",
490
+ "fig, ax = plt.subplots(figsize=(9, 4.5))\n",
491
+ "\n",
492
+ "for i, (col, label, color) in enumerate(zip(cat_cols, cat_labels2, bar_colors)):\n",
493
+ " bars = ax.bar(x + (i - 1) * width, fdf[col], width, label=label, color=color)\n",
494
+ " cnt_col = filtered_count_dfs['Transparent-Solvable'][col]\n",
495
+ " for bar, cnt in zip(bars, cnt_col):\n",
496
+ " h = bar.get_height()\n",
497
+ " ax.annotate('{:.0f}%\\n({})'.format(h, cnt),\n",
498
+ " xy=(bar.get_x() + bar.get_width() / 2, h),\n",
499
+ " xytext=(0, 3), textcoords='offset points',\n",
500
+ " ha='center', va='bottom', fontsize=7.5)\n",
501
+ "ax.set_title('Transparent-Solvable Items — Direct vs Inferential')\n",
502
+ "ax.set_xticks(x)\n",
503
+ "ax.set_xticklabels(models, rotation=18, ha='right')\n",
504
+ "ax.set_ylim(0, 120)\n",
505
+ "ax.set_yticks([0, 20, 40, 60, 80, 100])\n",
506
+ "ax.yaxis.set_major_formatter(mtick.PercentFormatter())\n",
507
+ "ax.set_ylabel('Occlusion Accuracy (%)')\n",
508
+ "ax.legend()\n",
509
+ "\n",
510
+ "plt.tight_layout()\n",
511
+ "save(fig, 'filtered_phys_nonphys')\n",
512
+ "plt.show()\n"
513
+ ]
514
+ },
515
+ {
516
+ "cell_type": "markdown",
517
+ "id": "80a4fc4c",
518
+ "metadata": {},
519
+ "source": [
520
+ "---\n",
521
+ "## Thinking Models — Accuracy Breakdown\n",
522
+ "\n",
523
+ "Same analysis for **thinking/reasoning mode** variants of GPT-5.4 and Claude Opus 4.6 (`data/eval_results_thinking`).\n",
524
+ "All results use Combined scoring.\n"
525
+ ]
526
+ },
527
+ {
528
+ "cell_type": "code",
529
+ "execution_count": null,
530
+ "id": "4fac2893",
531
+ "metadata": {},
532
+ "outputs": [],
533
+ "source": [
534
+ "THINKING_DIR = 'data/eval_results_thinking'\n",
535
+ "THINKING_STEMS = ['gpt-5.4', 'claude-opus-4-6']\n",
536
+ "THINKING_DISPLAY = {\n",
537
+ " 'gpt-5.4': 'GPT-5.4 (thinking)',\n",
538
+ " 'claude-opus-4-6': 'Claude Opus 4.6 (thinking)',\n",
539
+ "}\n",
540
+ "\n",
541
+ "thinking_cache = {}\n",
542
+ "for stem in THINKING_STEMS:\n",
543
+ " path = os.path.join(THINKING_DIR, f'{stem}_judged_results.json')\n",
544
+ " with open(path) as f:\n",
545
+ " thinking_cache[stem] = json.load(f)\n",
546
+ "\n",
547
+ "rows = []\n",
548
+ "for stem in THINKING_STEMS:\n",
549
+ " judged = thinking_cache[stem]\n",
550
+ " occ = compute_accuracy(judged, 'occluded_correct', physical_map, JUDGE_MODELS)\n",
551
+ " trans = compute_accuracy(judged, 'transparent_correct', physical_map, JUDGE_MODELS)\n",
552
+ " rows.append({\n",
553
+ " 'model': THINKING_DISPLAY[stem],\n",
554
+ " 'occ_overall': occ['overall'],\n",
555
+ " 'occ_physical': occ['physical'],\n",
556
+ " 'occ_non_physical': occ['non_physical'],\n",
557
+ " 'trans_overall': trans['overall'],\n",
558
+ " 'trans_physical': trans['physical'],\n",
559
+ " 'trans_non_physical': trans['non_physical'],\n",
560
+ " })\n",
561
+ "thinking_df = pd.DataFrame(rows).set_index('model')\n",
562
+ "print('Thinking data loaded.')\n"
563
+ ]
564
+ },
565
+ {
566
+ "cell_type": "markdown",
567
+ "id": "32600155",
568
+ "metadata": {},
569
+ "source": [
570
+ "### Summary Tables — Thinking Models"
571
+ ]
572
+ },
573
+ {
574
+ "cell_type": "code",
575
+ "execution_count": null,
576
+ "id": "71b112bb",
577
+ "metadata": {},
578
+ "outputs": [],
579
+ "source": [
580
+ "tbl = thinking_df.copy().round(1)\n",
581
+ "tbl.columns = col_labels\n",
582
+ "tbl = tbl.applymap(lambda x: f'{x:.1f}%' if x is not None else 'N/A')\n",
583
+ "display(tbl)\n"
584
+ ]
585
+ },
586
+ {
587
+ "cell_type": "markdown",
588
+ "id": "bb7d6775",
589
+ "metadata": {},
590
+ "source": [
591
+ "### Thinking vs Base — Occlusion & Transparency Overall Accuracy"
592
+ ]
593
+ },
594
+ {
595
+ "cell_type": "code",
596
+ "execution_count": null,
597
+ "id": "90ea6a0b",
598
+ "metadata": {},
599
+ "outputs": [],
600
+ "source": [
601
+ "stems_pair = ['gpt-5.4', 'claude-opus-4-6']\n",
602
+ "pair_labels = [DISPLAY_NAMES[s] for s in stems_pair]\n",
603
+ "x2 = np.arange(len(stems_pair))\n",
604
+ "w = 0.2\n",
605
+ "\n",
606
+ "bar_configs = [\n",
607
+ " ('occ_overall', 'Occ Base', '#4C72B0', 1.0, df),\n",
608
+ " ('occ_overall', 'Occ Think', '#4C72B0', 0.45, thinking_df),\n",
609
+ " ('trans_overall', 'Trans Base', '#C44E52', 1.0, df),\n",
610
+ " ('trans_overall', 'Trans Think', '#C44E52', 0.45, thinking_df),\n",
611
+ "]\n",
612
+ "\n",
613
+ "fig, ax = plt.subplots(figsize=(7, 4))\n",
614
+ "\n",
615
+ "offsets = [-1.5*w, -0.5*w, 0.5*w, 1.5*w]\n",
616
+ "for offset, (col, label, color, alpha, src_df) in zip(offsets, bar_configs):\n",
617
+ " if src_df is thinking_df:\n",
618
+ " vals = [src_df.loc[THINKING_DISPLAY[s], col] for s in stems_pair]\n",
619
+ " else:\n",
620
+ " vals = [src_df.loc[DISPLAY_NAMES[s], col] for s in stems_pair]\n",
621
+ " bars = ax.bar(x2 + offset, vals, w, label=label, color=color, alpha=alpha)\n",
622
+ " for bar in bars:\n",
623
+ " h = bar.get_height()\n",
624
+ " if h is not None:\n",
625
+ " ax.annotate(f'{h:.0f}', xy=(bar.get_x() + bar.get_width()/2, h),\n",
626
+ " xytext=(0, 3), textcoords='offset points',\n",
627
+ " ha='center', va='bottom', fontsize=8)\n",
628
+ "\n",
629
+ "ax.set_title('Thinking vs Base — Overall Accuracy')\n",
630
+ "ax.set_xticks(x2)\n",
631
+ "ax.set_xticklabels(pair_labels, rotation=10, ha='right')\n",
632
+ "ax.set_ylim(0, 110)\n",
633
+ "ax.set_yticks([0, 20, 40, 60, 80, 100])\n",
634
+ "ax.yaxis.set_major_formatter(mtick.PercentFormatter())\n",
635
+ "ax.set_ylabel('Accuracy (%)')\n",
636
+ "ax.legend()\n",
637
+ "\n",
638
+ "plt.tight_layout()\n",
639
+ "save(fig, 'thinking_vs_base_overall')\n",
640
+ "plt.show()\n"
641
+ ]
642
+ },
643
+ {
644
+ "cell_type": "markdown",
645
+ "id": "c2a84ac0",
646
+ "metadata": {},
647
+ "source": [
648
+ "### Thinking vs Base — Direct / Inferential Breakdown (Occlusion)"
649
+ ]
650
+ },
651
+ {
652
+ "cell_type": "code",
653
+ "execution_count": null,
654
+ "id": "14e80d90",
655
+ "metadata": {},
656
+ "outputs": [],
657
+ "source": [
658
+ "cat_pairs = [\n",
659
+ " ('occ_physical', 'Occlusion — Direct'),\n",
660
+ " ('occ_non_physical', 'Occlusion — Inferential'),\n",
661
+ "]\n",
662
+ "\n",
663
+ "fig, axes = plt.subplots(1, 2, figsize=(11, 4), sharey=True)\n",
664
+ "\n",
665
+ "for ax, (col, title) in zip(axes, cat_pairs):\n",
666
+ " base_vals = [df.loc[DISPLAY_NAMES[s], col] for s in stems_pair]\n",
667
+ " think_vals = [thinking_df.loc[THINKING_DISPLAY[s], col] for s in stems_pair]\n",
668
+ " bars1 = ax.bar(x2 - w/2, base_vals, w, label='Base', color='#4C72B0')\n",
669
+ " bars2 = ax.bar(x2 + w/2, think_vals, w, label='Thinking', color='#4C72B0', alpha=0.45)\n",
670
+ " for bars in [bars1, bars2]:\n",
671
+ " for bar in bars:\n",
672
+ " h = bar.get_height()\n",
673
+ " if h is not None:\n",
674
+ " ax.annotate(f'{h:.0f}', xy=(bar.get_x() + bar.get_width()/2, h),\n",
675
+ " xytext=(0, 3), textcoords='offset points',\n",
676
+ " ha='center', va='bottom', fontsize=8)\n",
677
+ " ax.set_title(title)\n",
678
+ " ax.set_xticks(x2)\n",
679
+ " ax.set_xticklabels(pair_labels, rotation=10, ha='right')\n",
680
+ " ax.set_ylim(0, 110)\n",
681
+ " ax.set_yticks([0, 20, 40, 60, 80, 100])\n",
682
+ " ax.yaxis.set_major_formatter(mtick.PercentFormatter())\n",
683
+ " if ax == axes[0]:\n",
684
+ " ax.set_ylabel('Accuracy (%)')\n",
685
+ " ax.legend()\n",
686
+ "\n",
687
+ "fig.suptitle('Thinking vs Base — Direct / Inferential (Occlusion)', y=1.02)\n",
688
+ "plt.tight_layout()\n",
689
+ "save(fig, 'thinking_vs_base_phys_nonphys')\n",
690
+ "plt.show()\n"
691
+ ]
692
+ },
693
+ {
694
+ "cell_type": "markdown",
695
+ "id": "7aa21a1e",
696
+ "metadata": {},
697
+ "source": [
698
+ "### Thinking Models — Direct vs Inferential Breakdown (Occlusion & Transparency)"
699
+ ]
700
+ },
701
+ {
702
+ "cell_type": "markdown",
703
+ "id": "e6b15e45",
704
+ "metadata": {},
705
+ "source": [
706
+ "### Thinking — Transparent-Solvable Filter"
707
+ ]
708
+ },
709
+ {
710
+ "cell_type": "code",
711
+ "execution_count": null,
712
+ "id": "6c708284",
713
+ "metadata": {},
714
+ "outputs": [],
715
+ "source": [
716
+ "thinking_filtered_dfs = {}\n",
717
+ "thinking_filtered_count_dfs = {}\n",
718
+ "\n",
719
+ "for config_name, (score_judges, filter_mode) in [('Transparent-Solvable', FILTER_CONFIG)]:\n",
720
+ " rows_acc, rows_cnt = [], []\n",
721
+ " for stem in THINKING_STEMS:\n",
722
+ " judged = thinking_cache[stem]\n",
723
+ " res = compute_accuracy_filtered(\n",
724
+ " judged, 'occluded_correct', 'transparent_correct',\n",
725
+ " physical_map, score_judges, filter_mode\n",
726
+ " )\n",
727
+ " rows_acc.append({\n",
728
+ " 'model': THINKING_DISPLAY[stem],\n",
729
+ " 'overall': res['overall'][0],\n",
730
+ " 'physical': res['physical'][0],\n",
731
+ " 'non_physical': res['non_physical'][0],\n",
732
+ " })\n",
733
+ " rows_cnt.append({\n",
734
+ " 'model': THINKING_DISPLAY[stem],\n",
735
+ " 'overall': str(res['overall'][1]) + '/' + str(res['overall'][2]),\n",
736
+ " 'physical': str(res['physical'][1]) + '/' + str(res['physical'][2]),\n",
737
+ " 'non_physical': str(res['non_physical'][1]) + '/' + str(res['non_physical'][2]),\n",
738
+ " })\n",
739
+ " thinking_filtered_dfs[config_name] = pd.DataFrame(rows_acc).set_index('model')\n",
740
+ " thinking_filtered_count_dfs[config_name] = pd.DataFrame(rows_cnt).set_index('model')\n",
741
+ "\n",
742
+ "acc_df = thinking_filtered_dfs['Transparent-Solvable']\n",
743
+ "cnt_df = thinking_filtered_count_dfs['Transparent-Solvable']\n",
744
+ "combined = {}\n",
745
+ "for label, key in zip(cat_labels, cat_keys):\n",
746
+ " combined[label] = [\n",
747
+ " '{:.1f}% ({})'.format(acc, cnt) if acc is not None else 'N/A'\n",
748
+ " for acc, cnt in zip(acc_df[key], cnt_df[key])\n",
749
+ " ]\n",
750
+ "tbl = pd.DataFrame(combined, index=acc_df.index)\n",
751
+ "display(tbl)\n"
752
+ ]
753
+ },
754
+ {
755
+ "cell_type": "code",
756
+ "execution_count": null,
757
+ "id": "4942e9fc",
758
+ "metadata": {},
759
+ "outputs": [],
760
+ "source": [
761
+ "THINKING_TOOL_DIR = 'data/eval_results_tool_use_thinking'\n",
762
+ "thinking_tool_cache = {}\n",
763
+ "for stem in THINKING_STEMS:\n",
764
+ " path = os.path.join(THINKING_TOOL_DIR, f'{stem}_judged_results.json')\n",
765
+ " with open(path) as f:\n",
766
+ " thinking_tool_cache[stem] = json.load(f)\n",
767
+ "\n",
768
+ "rows = []\n",
769
+ "for stem in THINKING_STEMS:\n",
770
+ " judged = thinking_tool_cache[stem]\n",
771
+ " occ = compute_accuracy(judged, 'occluded_correct', physical_map, JUDGE_MODELS)\n",
772
+ " trans = compute_accuracy(judged, 'transparent_correct', physical_map, JUDGE_MODELS)\n",
773
+ " rows.append({\n",
774
+ " 'model': THINKING_DISPLAY[stem],\n",
775
+ " 'occ_overall': occ['overall'],\n",
776
+ " 'occ_physical': occ['physical'],\n",
777
+ " 'occ_non_physical': occ['non_physical'],\n",
778
+ " 'trans_overall': trans['overall'],\n",
779
+ " 'trans_physical': trans['physical'],\n",
780
+ " 'trans_non_physical': trans['non_physical'],\n",
781
+ " })\n",
782
+ "thinking_tool_df = pd.DataFrame(rows).set_index('model')\n",
783
+ "\n",
784
+ "think_labels = [THINKING_DISPLAY[s] for s in THINKING_STEMS]\n",
785
+ "x_t = np.arange(len(THINKING_STEMS))\n",
786
+ "w_t = 0.2\n",
787
+ "\n",
788
+ "fig, ax = plt.subplots(figsize=(7, 4))\n",
789
+ "\n",
790
+ "occ_default = [thinking_df.loc[THINKING_DISPLAY[s], 'occ_physical'] for s in THINKING_STEMS]\n",
791
+ "occ_tool = [thinking_tool_df.loc[THINKING_DISPLAY[s], 'occ_physical'] for s in THINKING_STEMS]\n",
792
+ "\n",
793
+ "bars1 = ax.bar(x_t - w_t/2, occ_default, w_t, label='Default', color='#4C72B0')\n",
794
+ "bars2 = ax.bar(x_t + w_t/2, occ_tool, w_t, label='Tool Use', color='#4C72B0', alpha=0.5)\n",
795
+ "\n",
796
+ "for bars in [bars1, bars2]:\n",
797
+ " for bar in bars:\n",
798
+ " h = bar.get_height()\n",
799
+ " if h:\n",
800
+ " ax.annotate(f'{h:.0f}', xy=(bar.get_x() + bar.get_width()/2, h),\n",
801
+ " xytext=(0, 3), textcoords='offset points',\n",
802
+ " ha='center', va='bottom', fontsize=8)\n",
803
+ "\n",
804
+ "ax.set_title('Thinking Models — Direct Accuracy: Default vs Tool Use')\n",
805
+ "ax.set_xticks(x_t)\n",
806
+ "ax.set_xticklabels(think_labels, rotation=12, ha='right')\n",
807
+ "ax.set_ylim(0, 110)\n",
808
+ "ax.set_yticks([0, 20, 40, 60, 80, 100])\n",
809
+ "ax.yaxis.set_major_formatter(mtick.PercentFormatter())\n",
810
+ "ax.set_ylabel('Direct Accuracy (%)')\n",
811
+ "ax.legend()\n",
812
+ "\n",
813
+ "plt.tight_layout()\n",
814
+ "save(fig, 'thinking_tool_use')\n",
815
+ "plt.show()\n"
816
+ ]
817
+ },
818
+ {
819
+ "cell_type": "markdown",
820
+ "id": "dcbd2465",
821
+ "metadata": {},
822
+ "source": [
823
+ "---\n",
824
+ "## Few-Shot Prompting — Base vs Few-Shot Accuracy (Occlusion)\n",
825
+ "\n",
826
+ "Comparison of occlusion accuracy with and without 2-shot prompting (examples: image pic0025 — bird wings, pic0317 — dark mug).\n",
827
+ "No transparency test was run for the few-shot condition."
828
+ ]
829
+ },
830
+ {
831
+ "cell_type": "code",
832
+ "execution_count": null,
833
+ "id": "428f3a8f",
834
+ "metadata": {},
835
+ "outputs": [],
836
+ "source": [
837
+ "FEWSHOT_DIR = 'data/eval_results_fewshot'\n",
838
+ "\n",
839
+ "fewshot_cache = {}\n",
840
+ "for stem in MODEL_STEMS:\n",
841
+ " path = os.path.join(FEWSHOT_DIR, f'{stem}_judged_results.json')\n",
842
+ " with open(path) as f:\n",
843
+ " fewshot_cache[stem] = json.load(f)\n",
844
+ "\n",
845
+ "rows = []\n",
846
+ "for stem in MODEL_STEMS:\n",
847
+ " judged = fewshot_cache[stem]\n",
848
+ " occ = compute_accuracy(judged, 'occluded_correct', physical_map, JUDGE_MODELS)\n",
849
+ " rows.append({\n",
850
+ " 'model': DISPLAY_NAMES[stem],\n",
851
+ " 'occ_overall': occ['overall'],\n",
852
+ " 'occ_physical': occ['physical'],\n",
853
+ " 'occ_non_physical': occ['non_physical'],\n",
854
+ " })\n",
855
+ "fewshot_df = pd.DataFrame(rows).set_index('model')\n",
856
+ "print('Few-shot data loaded.')\n"
857
+ ]
858
+ },
859
+ {
860
+ "cell_type": "code",
861
+ "execution_count": null,
862
+ "id": "02d6b93a",
863
+ "metadata": {},
864
+ "outputs": [],
865
+ "source": [
866
+ "models = list(DISPLAY_NAMES.values())\n",
867
+ "x = np.arange(len(models))\n",
868
+ "w = 0.3\n",
869
+ "\n",
870
+ "BASE_COLOR = '#4C72B0'\n",
871
+ "FEWSHOT_COLOR = '#C44E52'\n",
872
+ "\n",
873
+ "fig, ax = plt.subplots(figsize=(9, 4.5))\n",
874
+ "\n",
875
+ "base_overall = [df.loc[m, 'occ_overall'] for m in models]\n",
876
+ "fewshot_overall = [fewshot_df.loc[m, 'occ_overall'] for m in models]\n",
877
+ "\n",
878
+ "bars1 = ax.bar(x - w/2, base_overall, w, label='Base', color=BASE_COLOR, alpha=0.9)\n",
879
+ "bars2 = ax.bar(x + w/2, fewshot_overall, w, label='Few-Shot', color=FEWSHOT_COLOR, alpha=0.9)\n",
880
+ "\n",
881
+ "for bars in [bars1, bars2]:\n",
882
+ " for bar in bars:\n",
883
+ " h = bar.get_height()\n",
884
+ " if h is not None:\n",
885
+ " ax.annotate(f'{h:.0f}',\n",
886
+ " xy=(bar.get_x() + bar.get_width() / 2, h),\n",
887
+ " xytext=(0, 3), textcoords='offset points',\n",
888
+ " ha='center', va='bottom', fontsize=8)\n",
889
+ "\n",
890
+ "ax.set_title('Base vs Few-Shot — Occlusion Overall Accuracy')\n",
891
+ "ax.set_xticks(x)\n",
892
+ "ax.set_xticklabels(models, rotation=15, ha='right')\n",
893
+ "ax.set_ylim(0, 110)\n",
894
+ "ax.set_yticks([0, 20, 40, 60, 80, 100])\n",
895
+ "ax.yaxis.set_major_formatter(mtick.PercentFormatter())\n",
896
+ "ax.set_ylabel('Accuracy (%)')\n",
897
+ "ax.legend()\n",
898
+ "\n",
899
+ "plt.tight_layout()\n",
900
+ "save(fig, 'fewshot_overall')\n",
901
+ "plt.show()\n"
902
+ ]
903
+ },
904
+ {
905
+ "cell_type": "code",
906
+ "execution_count": null,
907
+ "id": "0a75f77a",
908
+ "metadata": {},
909
+ "outputs": [],
910
+ "source": [
911
+ "BASE_COLOR = '#4C72B0'\n",
912
+ "FEWSHOT_COLOR = '#C44E52'\n",
913
+ "\n",
914
+ "alphas = [0.95, 0.5]\n",
915
+ "\n",
916
+ "n_bars = 4\n",
917
+ "group_width = 0.72\n",
918
+ "bar_w = group_width / n_bars\n",
919
+ "offsets = np.linspace(-group_width/2 + bar_w/2, group_width/2 - bar_w/2, n_bars)\n",
920
+ "\n",
921
+ "configs = [\n",
922
+ " (df, 'occ_physical', BASE_COLOR, alphas[0], 'Base — Direct'),\n",
923
+ " (df, 'occ_non_physical', BASE_COLOR, alphas[1], 'Base — Inferential'),\n",
924
+ " (fewshot_df, 'occ_physical', FEWSHOT_COLOR, alphas[0], 'Few-Shot — Direct'),\n",
925
+ " (fewshot_df, 'occ_non_physical', FEWSHOT_COLOR, alphas[1], 'Few-Shot — Inferential'),\n",
926
+ "]\n",
927
+ "\n",
928
+ "fig, ax = plt.subplots(figsize=(9, 4.5))\n",
929
+ "\n",
930
+ "for (src_df, col, color, alpha, label), offset in zip(configs, offsets):\n",
931
+ " vals = [src_df.loc[m, col] for m in models]\n",
932
+ " bars = ax.bar(x + offset, vals, bar_w, label=label, color=color, alpha=alpha)\n",
933
+ " for bar in bars:\n",
934
+ " h = bar.get_height()\n",
935
+ " if h is not None:\n",
936
+ " ax.annotate(f'{h:.0f}',\n",
937
+ " xy=(bar.get_x() + bar.get_width() / 2, h),\n",
938
+ " xytext=(0, 3), textcoords='offset points',\n",
939
+ " ha='center', va='bottom', fontsize=8)\n",
940
+ "\n",
941
+ "ax.set_title('Base vs Few-Shot — Direct & Inferential Occlusion Accuracy')\n",
942
+ "ax.set_xticks(x)\n",
943
+ "ax.set_xticklabels(models, rotation=15, ha='right')\n",
944
+ "ax.set_ylim(0, 120)\n",
945
+ "ax.set_yticks([0, 20, 40, 60, 80, 100])\n",
946
+ "ax.yaxis.set_major_formatter(mtick.PercentFormatter())\n",
947
+ "ax.set_ylabel('Accuracy (%)')\n",
948
+ "ax.legend()\n",
949
+ "\n",
950
+ "plt.tight_layout()\n",
951
+ "save(fig, 'fewshot_phys_nonphys')\n",
952
+ "plt.show()\n"
953
+ ]
954
+ },
955
+ {
956
+ "cell_type": "code",
957
+ "execution_count": null,
958
+ "id": "43595f42",
959
+ "metadata": {},
960
+ "outputs": [],
961
+ "source": [
962
+ "tbl_fewshot = pd.DataFrame({\n",
963
+ " 'model': ['GPT-5.4', 'Claude Opus 4.6', 'Gemini 3.1 Pro', 'Qwen3-VL 8B', 'Llama-4 Maverick 17B'],\n",
964
+ " 'occ_overall': fewshot_df['occ_overall'].values,\n",
965
+ " 'occ_physical': fewshot_df['occ_physical'].values,\n",
966
+ " 'occ_non_physical': fewshot_df['occ_non_physical'].values,\n",
967
+ "}).set_index('model')\n",
968
+ "\n",
969
+ "tbl_fewshot = tbl_fewshot.round(1)\n",
970
+ "tbl_fewshot.columns = ['Few-Shot Overall', 'Few-Shot Direct', 'Few-Shot Inferential']\n",
971
+ "tbl_fewshot = tbl_fewshot.applymap(lambda x: f'{x:.1f}%' if x is not None else 'N/A')\n",
972
+ "display(tbl_fewshot)"
973
+ ]
974
+ }
975
+ ],
976
+ "metadata": {
977
+ "kernelspec": {
978
+ "display_name": "cos429",
979
+ "language": "python",
980
+ "name": "python3"
981
+ },
982
+ "language_info": {
983
+ "codemirror_mode": {
984
+ "name": "ipython",
985
+ "version": 3
986
+ },
987
+ "file_extension": ".py",
988
+ "mimetype": "text/x-python",
989
+ "name": "python",
990
+ "nbconvert_exporter": "python",
991
+ "pygments_lexer": "ipython3",
992
+ "version": "3.8.18"
993
+ }
994
+ },
995
+ "nbformat": 4,
996
+ "nbformat_minor": 5
997
+ }
code/sec4_1_main_results/category_accuracy/accuracy_by_category.ipynb ADDED
@@ -0,0 +1,604 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "76fdb1ef",
6
+ "metadata": {},
7
+ "source": [
8
+ "# Occlusion Accuracy by Image Category — Base Models\n",
9
+ "\n",
10
+ "Per-subcategory accuracy for each model on the **occlusion** test (base eval, combined judge scoring).\n",
11
+ "Categories from `data/Image categories (3).xlsx`, filtered to IDs in `annotations.json`.\n",
12
+ "\n",
13
+ "**Direct** subcategories: Shadow · Specular (mirror/glass + other reflection + phone) · Water/Diffuse \n",
14
+ "**Inferential** subcategories: Household · Machinery/Technology · Sports/Activity · Culture/Symbol · Nature"
15
+ ]
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "execution_count": null,
20
+ "id": "0802b3d5",
21
+ "metadata": {},
22
+ "outputs": [],
23
+ "source": [
24
+ "# Run from the repo root so the root-relative data paths below resolve\n",
25
+ "import os\n",
26
+ "from pathlib import Path\n",
27
+ "os.chdir(next(p for p in [Path.cwd(), *Path.cwd().parents] if (p / \"sec3_occludebench\").is_dir()))"
28
+ ]
29
+ },
30
+ {
31
+ "cell_type": "code",
32
+ "execution_count": null,
33
+ "id": "bd5c3ba9",
34
+ "metadata": {
35
+ "execution": {
36
+ "iopub.execute_input": "2026-05-02T06:33:52.889424Z",
37
+ "iopub.status.busy": "2026-05-02T06:33:52.889326Z",
38
+ "iopub.status.idle": "2026-05-02T06:33:53.521685Z",
39
+ "shell.execute_reply": "2026-05-02T06:33:53.521287Z"
40
+ }
41
+ },
42
+ "outputs": [],
43
+ "source": [
44
+ "import json\n",
45
+ "import os\n",
46
+ "import openpyxl\n",
47
+ "import pandas as pd\n",
48
+ "import matplotlib.pyplot as plt\n",
49
+ "import matplotlib.ticker as mtick\n",
50
+ "import numpy as np\n",
51
+ "from collections import defaultdict\n",
52
+ "\n",
53
+ "import matplotlib as mpl\n",
54
+ "mpl.rcParams.update({\n",
55
+ " 'font.family': 'Arial',\n",
56
+ " 'font.size': 26,\n",
57
+ " 'axes.titlesize': 26,\n",
58
+ " 'axes.labelsize': 26,\n",
59
+ " 'xtick.labelsize': 26,\n",
60
+ " 'ytick.labelsize': 26,\n",
61
+ " 'legend.fontsize': 26,\n",
62
+ " 'axes.titleweight': 'normal',\n",
63
+ " 'axes.grid': False,\n",
64
+ " 'axes.spines.top': False,\n",
65
+ " 'axes.spines.right': False,\n",
66
+ " 'figure.dpi': 150,\n",
67
+ "})\n",
68
+ "\n",
69
+ "RESULTS_DIR = 'data/eval_results'\n",
70
+ "ANNOTATIONS_PATH = 'data/combined_output/annotations.json'\n",
71
+ "EXCEL_PATH = 'data/Image categories (3).xlsx'\n",
72
+ "\n",
73
+ "MODEL_STEMS = [\n",
74
+ " 'gpt-5.4',\n",
75
+ " 'claude-opus-4-6',\n",
76
+ " 'gemini-3.1-pro-preview',\n",
77
+ " 'Qwen3-VL-8B-Instruct',\n",
78
+ " 'Llama-4-Maverick-17B-128E-Instruct-FP8',\n",
79
+ "]\n",
80
+ "DISPLAY_NAMES = {\n",
81
+ " 'gpt-5.4': 'GPT-5.4',\n",
82
+ " 'claude-opus-4-6': 'Claude Opus 4.6',\n",
83
+ " 'gemini-3.1-pro-preview': 'Gemini 3.1 Pro',\n",
84
+ " 'Qwen3-VL-8B-Instruct': 'Qwen 3 VL 8B',\n",
85
+ " 'Llama-4-Maverick-17B-128E-Instruct-FP8': 'Llama 4 Maverick',\n",
86
+ "}\n",
87
+ "JUDGE_MODELS = ['gpt-5.4', 'claude-opus-4-6']\n",
88
+ "\n",
89
+ "FIG_DIR = 'data/figures'\n",
90
+ "os.makedirs(FIG_DIR, exist_ok=True)\n",
91
+ "\n",
92
+ "def save(fig, name):\n",
93
+ " fig.savefig(os.path.join(FIG_DIR, name + '.pdf'), bbox_inches='tight', format='pdf')\n"
94
+ ]
95
+ },
96
+ {
97
+ "cell_type": "code",
98
+ "execution_count": null,
99
+ "id": "2ada77e3",
100
+ "metadata": {
101
+ "execution": {
102
+ "iopub.execute_input": "2026-05-02T06:33:53.523849Z",
103
+ "iopub.status.busy": "2026-05-02T06:33:53.523668Z",
104
+ "iopub.status.idle": "2026-05-02T06:33:53.543892Z",
105
+ "shell.execute_reply": "2026-05-02T06:33:53.543497Z"
106
+ }
107
+ },
108
+ "outputs": [],
109
+ "source": [
110
+ "# ── Load annotations ────────────────────────────────────────────────────────\n",
111
+ "with open(ANNOTATIONS_PATH) as f:\n",
112
+ " annotations = json.load(f)\n",
113
+ "ann_set = set(item['id'] for item in annotations)\n",
114
+ "\n",
115
+ "# ── Load & normalise category map from Excel ─────────────────────────────────\n",
116
+ "def normalize_id(x):\n",
117
+ " if isinstance(x, float) and x == int(x):\n",
118
+ " return str(int(x))\n",
119
+ " return str(x)\n",
120
+ "\n",
121
+ "SPECULAR_RAW = {'mirror/glass', 'other reflection', 'phone'}\n",
122
+ "\n",
123
+ "wb = openpyxl.load_workbook(EXCEL_PATH)\n",
124
+ "ws = wb.active\n",
125
+ "\n",
126
+ "id_to_cat = {} # img_id -> merged subcategory label\n",
127
+ "id_to_kind = {} # img_id -> 'direct' | 'inferential'\n",
128
+ "\n",
129
+ "for row in ws.iter_rows(values_only=True):\n",
130
+ " if row[0] is None or row[0] == 'image id':\n",
131
+ " continue\n",
132
+ " img_id = normalize_id(row[0])\n",
133
+ " if img_id not in ann_set:\n",
134
+ " continue\n",
135
+ " kind, subcat = row[1], row[2]\n",
136
+ " # merge\n",
137
+ " if subcat in SPECULAR_RAW:\n",
138
+ " subcat = 'specular'\n",
139
+ " elif subcat == 'water':\n",
140
+ " subcat = 'water/diffuse'\n",
141
+ " elif subcat == 'culture' or subcat == 'symbol':\n",
142
+ " subcat = 'culture/symbol'\n",
143
+ " id_to_cat[img_id] = subcat\n",
144
+ " id_to_kind[img_id] = kind\n",
145
+ "\n",
146
+ "print(f'Categorised {len(id_to_cat)} images')\n",
147
+ "print('Direct categories:', sorted({v for k,v in id_to_cat.items() if id_to_kind[k]=='direct'}))\n",
148
+ "print('Inferential categories:', sorted({v for k,v in id_to_cat.items() if id_to_kind[k]=='inferential'}))"
149
+ ]
150
+ },
151
+ {
152
+ "cell_type": "code",
153
+ "execution_count": null,
154
+ "id": "700e2bb9",
155
+ "metadata": {
156
+ "execution": {
157
+ "iopub.execute_input": "2026-05-02T06:33:53.545632Z",
158
+ "iopub.status.busy": "2026-05-02T06:33:53.545533Z",
159
+ "iopub.status.idle": "2026-05-02T06:33:53.557319Z",
160
+ "shell.execute_reply": "2026-05-02T06:33:53.556941Z"
161
+ }
162
+ },
163
+ "outputs": [],
164
+ "source": [
165
+ "# ── Compute per-category accuracy for one judged file ───────────────────────\n",
166
+ "def compute_cat_accuracy(judged_data, verdict_key, id_to_cat, id_to_kind, judge_models):\n",
167
+ " sums = defaultdict(float)\n",
168
+ " counts = defaultdict(int)\n",
169
+ " for item in judged_data:\n",
170
+ " vdict = item.get(verdict_key, {})\n",
171
+ " if not isinstance(vdict, dict):\n",
172
+ " continue\n",
173
+ " scores = [vdict[jm] for jm in judge_models if jm in vdict and vdict[jm] is not None]\n",
174
+ " if not scores:\n",
175
+ " continue\n",
176
+ " score = sum(scores) / len(scores)\n",
177
+ " img_id = str(item['id'])\n",
178
+ " cat = id_to_cat.get(img_id)\n",
179
+ " if cat is None:\n",
180
+ " continue\n",
181
+ " sums[cat] += score\n",
182
+ " counts[cat] += 1\n",
183
+ " return {cat: (sums[cat] / counts[cat] * 100, counts[cat])\n",
184
+ " for cat in counts}\n",
185
+ "\n",
186
+ "# ── Load all base judged results ──────────────────────────────────────────────\n",
187
+ "judged_cache = {}\n",
188
+ "for stem in MODEL_STEMS:\n",
189
+ " path = os.path.join(RESULTS_DIR, f'{stem}_judged_results.json')\n",
190
+ " with open(path) as f:\n",
191
+ " judged_cache[stem] = json.load(f)\n",
192
+ "\n",
193
+ "# ── Build per-model accuracy DataFrames ──────────────────────────────────────\n",
194
+ "DIRECT_CATS = ['shadow', 'specular', 'water/diffuse']\n",
195
+ "INFERENTIAL_CATS = ['household', 'machinery/technology', 'sports/activity', 'culture/symbol', 'nature']\n",
196
+ "ALL_CATS = DIRECT_CATS + INFERENTIAL_CATS\n",
197
+ "\n",
198
+ "cat_acc = {} # stem -> {cat: (acc, n)}\n",
199
+ "for stem in MODEL_STEMS:\n",
200
+ " cat_acc[stem] = compute_cat_accuracy(\n",
201
+ " judged_cache[stem], 'occluded_correct', id_to_cat, id_to_kind, JUDGE_MODELS\n",
202
+ " )\n",
203
+ " print(DISPLAY_NAMES[stem])\n",
204
+ " for cat in ALL_CATS:\n",
205
+ " acc, n = cat_acc[stem].get(cat, (None, 0))\n",
206
+ " print(f' {cat:<25} {acc:.1f}% (n={n})' if acc is not None else f' {cat:<25} N/A')\n",
207
+ " print()"
208
+ ]
209
+ },
210
+ {
211
+ "cell_type": "code",
212
+ "execution_count": null,
213
+ "id": "c3695fc4",
214
+ "metadata": {
215
+ "execution": {
216
+ "iopub.execute_input": "2026-05-02T06:33:53.559264Z",
217
+ "iopub.status.busy": "2026-05-02T06:33:53.559120Z",
218
+ "iopub.status.idle": "2026-05-02T06:33:53.566020Z",
219
+ "shell.execute_reply": "2026-05-02T06:33:53.565690Z"
220
+ }
221
+ },
222
+ "outputs": [],
223
+ "source": [
224
+ "cat_labels_display = {\n",
225
+ " 'shadow': 'Shadow',\n",
226
+ " 'specular': 'Specular',\n",
227
+ " 'water/diffuse': 'Diffuse',\n",
228
+ " 'household': 'Household',\n",
229
+ " 'machinery/technology': 'Technology',\n",
230
+ " 'sports/activity': 'Activity',\n",
231
+ " 'culture/symbol': 'Culture',\n",
232
+ " 'nature': 'Nature',\n",
233
+ "}\n",
234
+ "\n",
235
+ "rows = {}\n",
236
+ "for stem in MODEL_STEMS:\n",
237
+ " row = {}\n",
238
+ " for cat in ALL_CATS:\n",
239
+ " acc, n = cat_acc[stem].get(cat, (None, 0))\n",
240
+ " row[cat_labels_display[cat]] = f'{acc:.1f}%' if acc is not None else 'N/A'\n",
241
+ " rows[DISPLAY_NAMES[stem]] = row\n",
242
+ "\n",
243
+ "tbl = pd.DataFrame(rows).T\n",
244
+ "tbl = tbl[[cat_labels_display[c] for c in ALL_CATS]]\n",
245
+ "display(tbl)"
246
+ ]
247
+ },
248
+ {
249
+ "cell_type": "markdown",
250
+ "id": "959c874d",
251
+ "metadata": {},
252
+ "source": [
253
+ "## Statistical Testing\n",
254
+ "\n",
255
+ "For each model and category group (Direct / Inferential):\n",
256
+ "- **Chi-square omnibus test** across all categories in that group\n",
257
+ "- **Pairwise Fisher's exact tests** (Bonferroni-corrected) between every pair of categories\n",
258
+ "\n",
259
+ "Outcomes are binarised: score ≥ 0.5 → correct (majority-judge agreement)."
260
+ ]
261
+ },
262
+ {
263
+ "cell_type": "code",
264
+ "execution_count": null,
265
+ "id": "6423ebd6",
266
+ "metadata": {
267
+ "execution": {
268
+ "iopub.execute_input": "2026-05-02T06:33:53.567827Z",
269
+ "iopub.status.busy": "2026-05-02T06:33:53.567716Z",
270
+ "iopub.status.idle": "2026-05-02T06:33:54.041462Z",
271
+ "shell.execute_reply": "2026-05-02T06:33:54.041145Z"
272
+ }
273
+ },
274
+ "outputs": [],
275
+ "source": [
276
+ "from scipy.stats import chi2_contingency, fisher_exact\n",
277
+ "from itertools import combinations\n",
278
+ "\n",
279
+ "def collect_binary_outcomes(judged_data, verdict_key, id_to_cat, judge_models):\n",
280
+ " \"\"\"Returns {cat: [list of 0/1 outcomes]} binarised at majority-judge threshold.\"\"\"\n",
281
+ " outcomes = defaultdict(list)\n",
282
+ " for item in judged_data:\n",
283
+ " vdict = item.get(verdict_key, {})\n",
284
+ " if not isinstance(vdict, dict):\n",
285
+ " continue\n",
286
+ " scores = [vdict[jm] for jm in judge_models if jm in vdict and vdict[jm] is not None]\n",
287
+ " if not scores:\n",
288
+ " continue\n",
289
+ " score = sum(scores) / len(scores)\n",
290
+ " binary = 1 if score >= 0.5 else 0\n",
291
+ " cat = id_to_cat.get(str(item['id']))\n",
292
+ " if cat is not None:\n",
293
+ " outcomes[cat].append(binary)\n",
294
+ " return outcomes\n",
295
+ "\n",
296
+ "\n",
297
+ "def chi2_across_cats(outcomes, cats):\n",
298
+ " \"\"\"Chi-square test of independence across multiple categories.\"\"\"\n",
299
+ " table = np.array([[sum(outcomes[c]), len(outcomes[c]) - sum(outcomes[c])]\n",
300
+ " for c in cats if c in outcomes])\n",
301
+ " if table.shape[0] < 2:\n",
302
+ " return None, None\n",
303
+ " chi2, p, dof, _ = chi2_contingency(table)\n",
304
+ " return chi2, p\n",
305
+ "\n",
306
+ "\n",
307
+ "def pairwise_fisher(outcomes, cats, alpha=0.05):\n",
308
+ " \"\"\"\n",
309
+ " All pairwise Fisher's exact tests, Bonferroni-corrected.\n",
310
+ " Returns dict {(cat_a, cat_b): {'p_raw': .., 'p_adj': .., 'sig': bool}}.\n",
311
+ " \"\"\"\n",
312
+ " pairs = list(combinations([c for c in cats if c in outcomes], 2))\n",
313
+ " n_comparisons = len(pairs)\n",
314
+ " results = {}\n",
315
+ " for ca, cb in pairs:\n",
316
+ " a = outcomes[ca]; b = outcomes[cb]\n",
317
+ " contingency = [[sum(a), len(a) - sum(a)],\n",
318
+ " [sum(b), len(b) - sum(b)]]\n",
319
+ " _, p = fisher_exact(contingency)\n",
320
+ " p_adj = min(p * n_comparisons, 1.0)\n",
321
+ " results[(ca, cb)] = {'p_raw': p, 'p_adj': p_adj, 'sig': p_adj < alpha}\n",
322
+ " return results\n",
323
+ "\n",
324
+ "\n",
325
+ "def stars(p):\n",
326
+ " if p < 0.001: return '***'\n",
327
+ " if p < 0.01: return '**'\n",
328
+ " if p < 0.05: return '*'\n",
329
+ " return 'ns'\n",
330
+ "\n",
331
+ "\n",
332
+ "# ── Collect outcomes and run tests for all models ────────────────────────────\n",
333
+ "binary_outcomes = {} # stem -> {cat: [outcomes]}\n",
334
+ "omnibus = {} # stem -> {'direct': (chi2,p), 'inferential': (chi2,p)}\n",
335
+ "pairwise = {} # stem -> {'direct': {...}, 'inferential': {...}}\n",
336
+ "\n",
337
+ "for stem in MODEL_STEMS:\n",
338
+ " bo = collect_binary_outcomes(judged_cache[stem], 'occluded_correct', id_to_cat, JUDGE_MODELS)\n",
339
+ " binary_outcomes[stem] = bo\n",
340
+ " omnibus[stem] = {\n",
341
+ " 'direct': chi2_across_cats(bo, DIRECT_CATS),\n",
342
+ " 'inferential': chi2_across_cats(bo, INFERENTIAL_CATS),\n",
343
+ " }\n",
344
+ " pairwise[stem] = {\n",
345
+ " 'direct': pairwise_fisher(bo, DIRECT_CATS),\n",
346
+ " 'inferential': pairwise_fisher(bo, INFERENTIAL_CATS),\n",
347
+ " }\n",
348
+ "\n",
349
+ "print('Omnibus chi-square results (p-values):')\n",
350
+ "print(f\"{'Model':<25} {'Direct p':>12} {'Inferential p':>15}\")\n",
351
+ "print('-' * 55)\n",
352
+ "for stem in MODEL_STEMS:\n",
353
+ " _, dp = omnibus[stem]['direct']\n",
354
+ " _, ip = omnibus[stem]['inferential']\n",
355
+ " print(f\"{DISPLAY_NAMES[stem]:<25} {dp:>12.4f} {ip:>15.4f}\")"
356
+ ]
357
+ },
358
+ {
359
+ "cell_type": "code",
360
+ "execution_count": null,
361
+ "id": "1da117a2",
362
+ "metadata": {
363
+ "execution": {
364
+ "iopub.execute_input": "2026-05-02T06:33:54.043198Z",
365
+ "iopub.status.busy": "2026-05-02T06:33:54.043054Z",
366
+ "iopub.status.idle": "2026-05-02T06:33:55.374530Z",
367
+ "shell.execute_reply": "2026-05-02T06:33:55.374272Z"
368
+ }
369
+ },
370
+ "outputs": [],
371
+ "source": [
372
+ "# ── Pairwise p-value heatmaps (one figure per model) ─────────────────────────\n",
373
+ "for stem in MODEL_STEMS:\n",
374
+ " name = DISPLAY_NAMES[stem]\n",
375
+ " fig, axes = plt.subplots(1, 2, figsize=(11, 3.8))\n",
376
+ " fig.suptitle(f'{name} — Pairwise Fisher\\'s Exact (Bonferroni-corrected)', fontsize=10, fontweight='bold')\n",
377
+ "\n",
378
+ " for ax, cats, group_key, title in [\n",
379
+ " (axes[0], DIRECT_CATS, 'direct', 'Direct'),\n",
380
+ " (axes[1], INFERENTIAL_CATS, 'inferential', 'Inferential'),\n",
381
+ " ]:\n",
382
+ " pw = pairwise[stem][group_key]\n",
383
+ " n = len(cats)\n",
384
+ " labels = [cat_labels_display[c] for c in cats]\n",
385
+ "\n",
386
+ " # Build symmetric matrix\n",
387
+ " mat = np.ones((n, n))\n",
388
+ " for i, ca in enumerate(cats):\n",
389
+ " for j, cb in enumerate(cats):\n",
390
+ " if i == j: continue\n",
391
+ " key = (ca, cb) if (ca, cb) in pw else (cb, ca)\n",
392
+ " if key in pw:\n",
393
+ " mat[i, j] = pw[key]['p_adj']\n",
394
+ "\n",
395
+ " im = ax.imshow(mat, vmin=0, vmax=1, cmap='RdYlGn_r', aspect='auto')\n",
396
+ " ax.set_xticks(range(n)); ax.set_xticklabels(labels, rotation=30, ha='right', fontsize=8)\n",
397
+ " ax.set_yticks(range(n)); ax.set_yticklabels(labels, fontsize=8)\n",
398
+ " ax.set_title(title)\n",
399
+ "\n",
400
+ " for i in range(n):\n",
401
+ " for j in range(n):\n",
402
+ " if i == j:\n",
403
+ " ax.text(j, i, '—', ha='center', va='center', fontsize=9, color='gray')\n",
404
+ " else:\n",
405
+ " p_val = mat[i, j]\n",
406
+ " txt = f'{p_val:.3f}\\n{stars(p_val)}'\n",
407
+ " color = 'white' if p_val < 0.3 else 'black'\n",
408
+ " ax.text(j, i, txt, ha='center', va='center', fontsize=7.5, color=color)\n",
409
+ "\n",
410
+ " plt.colorbar(im, ax=ax, label='adj. p-value', shrink=0.8)\n",
411
+ "\n",
412
+ " plt.tight_layout()\n",
413
+ " slug = name.lower().replace(' ', '_').replace('.', '')\n",
414
+ " save(fig, f'pairwise_fisher_{slug}')\n",
415
+ " plt.show()"
416
+ ]
417
+ },
418
+ {
419
+ "cell_type": "markdown",
420
+ "id": "357f27f5",
421
+ "metadata": {},
422
+ "source": [
423
+ "## Per-model category breakdown"
424
+ ]
425
+ },
426
+ {
427
+ "cell_type": "code",
428
+ "execution_count": null,
429
+ "id": "4ddfe146",
430
+ "metadata": {
431
+ "execution": {
432
+ "iopub.execute_input": "2026-05-02T06:33:55.375925Z",
433
+ "iopub.status.busy": "2026-05-02T06:33:55.375832Z",
434
+ "iopub.status.idle": "2026-05-02T06:33:56.022264Z",
435
+ "shell.execute_reply": "2026-05-02T06:33:56.022004Z"
436
+ }
437
+ },
438
+ "outputs": [],
439
+ "source": [
440
+ "DIRECT_COLORS = {\n",
441
+ " 'shadow': '#4C72B0',\n",
442
+ " 'specular': '#55A868',\n",
443
+ " 'water/diffuse': '#64B5CD',\n",
444
+ "}\n",
445
+ "INFERENTIAL_COLORS = {\n",
446
+ " 'household': '#DD8452',\n",
447
+ " 'machinery/technology': '#4472C4',\n",
448
+ " 'sports/activity': '#70AD47',\n",
449
+ " 'culture/symbol': '#C44E52',\n",
450
+ " 'nature': '#8172B3',\n",
451
+ "}\n",
452
+ "ALL_COLORS = {**DIRECT_COLORS, **INFERENTIAL_COLORS}\n",
453
+ "\n",
454
+ "\n",
455
+ "def add_sig_brackets(ax, x_positions, accs, pw_results, cats, y_top=105, step=7):\n",
456
+ " \"\"\"Draw significance brackets for all significant pairwise comparisons.\"\"\"\n",
457
+ " sig_pairs = [(ca, cb) for (ca, cb), r in pw_results.items() if r['sig']]\n",
458
+ " level = 0\n",
459
+ " for ca, cb in sig_pairs:\n",
460
+ " if ca not in cats or cb not in cats:\n",
461
+ " continue\n",
462
+ " xi = cats.index(ca)\n",
463
+ " xj = cats.index(cb)\n",
464
+ " y = y_top + level * step\n",
465
+ " ax.plot([xi, xi, xj, xj], [y - 1, y, y, y - 1],\n",
466
+ " lw=1, color='black', clip_on=False)\n",
467
+ " ax.text((xi + xj) / 2, y + 0.5, stars(pw_results[(ca, cb)]['p_adj']),\n",
468
+ " ha='center', va='bottom', fontsize=26)\n",
469
+ " level += 1\n",
470
+ "\n",
471
+ "\n",
472
+ "# ── One plot per model ─────────────────────────────────────────────────────────\n",
473
+ "for stem in MODEL_STEMS:\n",
474
+ " name = DISPLAY_NAMES[stem]\n",
475
+ " data = cat_acc[stem]\n",
476
+ "\n",
477
+ " fig, axes = plt.subplots(1, 2, figsize=(16, 6), sharey=True)\n",
478
+ " fig.suptitle(f'{name} — Occlusion', fontsize=26, fontweight='bold')\n",
479
+ "\n",
480
+ " for ax, cats, group_key, title in [\n",
481
+ " (axes[0], DIRECT_CATS, 'direct', 'Direct'),\n",
482
+ " (axes[1], INFERENTIAL_CATS, 'inferential', 'Inferential'),\n",
483
+ " ]:\n",
484
+ " accs = [data.get(c, (None, 0))[0] for c in cats]\n",
485
+ " ns = [data.get(c, (None, 0))[1] for c in cats]\n",
486
+ " colors = [ALL_COLORS[c] for c in cats]\n",
487
+ " labels = [cat_labels_display[c] for c in cats]\n",
488
+ " x = np.arange(len(cats))\n",
489
+ "\n",
490
+ " bars = ax.bar(x, accs, color=colors, width=0.55, edgecolor='black', linewidth=0.8)\n",
491
+ "\n",
492
+ " pw = pairwise[stem][group_key]\n",
493
+ " add_sig_brackets(ax, x, accs, pw, cats, y_top=104, step=8)\n",
494
+ "\n",
495
+ " _, p_omni = omnibus[stem][group_key]\n",
496
+ " ax.set_title(f'{title} (χ² p={p_omni:.3f} {stars(p_omni)})', fontsize=26)\n",
497
+ " ax.set_xticks(x)\n",
498
+ " ax.set_xticklabels(labels, rotation=0, ha='center', fontsize=26)\n",
499
+ " ax.tick_params(axis='x', labelsize=26, pad=12)\n",
500
+ " ax.tick_params(axis='y', labelsize=26)\n",
501
+ " ax.set_ylim(0, 130)\n",
502
+ " ax.set_yticks([0, 20, 40, 60, 80, 100])\n",
503
+ " ax.yaxis.set_major_formatter(mtick.PercentFormatter())\n",
504
+ " if ax is axes[0]:\n",
505
+ " ax.set_ylabel('Accuracy', fontsize=26)\n",
506
+ "\n",
507
+ " plt.tight_layout()\n",
508
+ " slug = name.lower().replace(' ', '_').replace('.', '')\n",
509
+ " save(fig, f'cat_accuracy_{slug}')\n",
510
+ " plt.show()\n"
511
+ ]
512
+ },
513
+ {
514
+ "cell_type": "markdown",
515
+ "id": "ab2e5701",
516
+ "metadata": {},
517
+ "source": [
518
+ "## All models — grouped by category"
519
+ ]
520
+ },
521
+ {
522
+ "cell_type": "code",
523
+ "execution_count": null,
524
+ "id": "5d0c2022",
525
+ "metadata": {
526
+ "execution": {
527
+ "iopub.execute_input": "2026-05-02T06:33:56.023681Z",
528
+ "iopub.status.busy": "2026-05-02T06:33:56.023589Z",
529
+ "iopub.status.idle": "2026-05-02T06:33:56.289739Z",
530
+ "shell.execute_reply": "2026-05-02T06:33:56.289459Z"
531
+ }
532
+ },
533
+ "outputs": [],
534
+ "source": [
535
+ "MODEL_COLORS = {\n",
536
+ " 'gpt-5.4': '#4C72B0',\n",
537
+ " 'claude-opus-4-6': '#DD8452',\n",
538
+ " 'gemini-3.1-pro-preview': '#55A868',\n",
539
+ " 'Qwen3-VL-8B-Instruct': '#C44E52',\n",
540
+ " 'Llama-4-Maverick-17B-128E-Instruct-FP8': '#8172B3',\n",
541
+ "}\n",
542
+ "\n",
543
+ "n_models = len(MODEL_STEMS)\n",
544
+ "group_w = 0.8\n",
545
+ "bar_w = group_w / n_models\n",
546
+ "offsets = np.linspace(-group_w/2 + bar_w/2, group_w/2 - bar_w/2, n_models)\n",
547
+ "\n",
548
+ "fig, axes = plt.subplots(1, 2, figsize=(22, 5),\n",
549
+ " gridspec_kw={'width_ratios': [3, 5]})\n",
550
+ "\n",
551
+ "for ax, (cats, side_title) in zip(axes, [(DIRECT_CATS, 'Direct'), (INFERENTIAL_CATS, 'Inferential')]):\n",
552
+ " x = np.arange(len(cats))\n",
553
+ "\n",
554
+ " for i, stem in enumerate(MODEL_STEMS):\n",
555
+ " accs = [cat_acc[stem].get(c, (None, 0))[0] for c in cats]\n",
556
+ " ax.bar(x + offsets[i], accs, bar_w,\n",
557
+ " label=DISPLAY_NAMES[stem],\n",
558
+ " color=MODEL_COLORS[stem], alpha=0.9,\n",
559
+ " edgecolor='black', linewidth=0.8)\n",
560
+ "\n",
561
+ " ax.set_title(f'{side_title} Images', fontsize=26)\n",
562
+ " ax.set_xticks(x)\n",
563
+ " ax.set_xticklabels([cat_labels_display[c] for c in cats], rotation=0, ha='center', fontsize=26)\n",
564
+ " ax.tick_params(axis='x', labelsize=26, pad=12)\n",
565
+ " ax.set_ylim(0, 115)\n",
566
+ " ax.set_yticks([0, 20, 40, 60, 80, 100])\n",
567
+ " ax.tick_params(axis='y', labelsize=26)\n",
568
+ " ax.yaxis.set_major_formatter(mtick.PercentFormatter())\n",
569
+ " ax.set_ylabel('Accuracy', fontsize=26)\n",
570
+ "\n",
571
+ "# Single shared legend at the bottom\n",
572
+ "handles, labels = axes[0].get_legend_handles_labels()\n",
573
+ "fig.legend(handles, labels, loc='lower center', ncol=n_models,\n",
574
+ " bbox_to_anchor=(0.5, -0.08), frameon=False, fontsize=26,\n",
575
+ " columnspacing=1.0, handlelength=1.4, handletextpad=0.5)\n",
576
+ "\n",
577
+ "plt.subplots_adjust(bottom=0.22)\n",
578
+ "save(fig, 'cat_accuracy_all_models')\n",
579
+ "plt.show()\n"
580
+ ]
581
+ }
582
+ ],
583
+ "metadata": {
584
+ "kernelspec": {
585
+ "display_name": "cos429",
586
+ "language": "python",
587
+ "name": "python3"
588
+ },
589
+ "language_info": {
590
+ "codemirror_mode": {
591
+ "name": "ipython",
592
+ "version": 3
593
+ },
594
+ "file_extension": ".py",
595
+ "mimetype": "text/x-python",
596
+ "name": "python",
597
+ "nbconvert_exporter": "python",
598
+ "pygments_lexer": "ipython3",
599
+ "version": "3.8.18"
600
+ }
601
+ },
602
+ "nbformat": 4,
603
+ "nbformat_minor": 5
604
+ }
code/sec4_1_main_results/human_model_correlation/human_model_difficulty_correlation.ipynb ADDED
@@ -0,0 +1,688 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "title",
6
+ "metadata": {},
7
+ "source": [
8
+ "# Human vs. Model Difficulty Correlation\n",
9
+ "\n",
10
+ "For each image in the occluded condition, we compute **human accuracy** (fraction of Prolific respondents who answered correctly) and check whether models also struggle on the same images.\n",
11
+ "\n",
12
+ "Judge correctness uses **either** GPT-5.4 or Claude Opus 4-6 agreeing (same convention as the token-length notebooks)."
13
+ ]
14
+ },
15
+ {
16
+ "cell_type": "code",
17
+ "execution_count": null,
18
+ "id": "1b72c0fe",
19
+ "metadata": {},
20
+ "outputs": [],
21
+ "source": [
22
+ "# Run from the repo root so the root-relative data paths below resolve\n",
23
+ "import os\n",
24
+ "from pathlib import Path\n",
25
+ "os.chdir(next(p for p in [Path.cwd(), *Path.cwd().parents] if (p / \"sec3_occludebench\").is_dir()))"
26
+ ]
27
+ },
28
+ {
29
+ "cell_type": "code",
30
+ "execution_count": null,
31
+ "id": "imports",
32
+ "metadata": {
33
+ "execution": {
34
+ "iopub.execute_input": "2026-05-06T19:01:35.890765Z",
35
+ "iopub.status.busy": "2026-05-06T19:01:35.890440Z",
36
+ "iopub.status.idle": "2026-05-06T19:01:36.926874Z",
37
+ "shell.execute_reply": "2026-05-06T19:01:36.926539Z"
38
+ }
39
+ },
40
+ "outputs": [],
41
+ "source": [
42
+ "import json\n",
43
+ "import numpy as np\n",
44
+ "import pandas as pd\n",
45
+ "import matplotlib as mpl\n",
46
+ "import matplotlib.pyplot as plt\n",
47
+ "import matplotlib.ticker as mtick\n",
48
+ "import seaborn as sns # colour palette only\n",
49
+ "from scipy import stats\n",
50
+ "from pathlib import Path\n",
51
+ "from collections import defaultdict\n",
52
+ "import warnings\n",
53
+ "warnings.filterwarnings('ignore')\n",
54
+ "\n",
55
+ "mpl.rcParams.update({\n",
56
+ " 'font.family': 'Arial',\n",
57
+ " 'font.size': 9,\n",
58
+ " 'axes.titlesize': 10,\n",
59
+ " 'axes.labelsize': 9,\n",
60
+ " 'xtick.labelsize': 9,\n",
61
+ " 'ytick.labelsize': 9,\n",
62
+ " 'legend.fontsize': 9,\n",
63
+ " 'axes.titleweight': 'normal',\n",
64
+ " 'axes.grid': False,\n",
65
+ " 'axes.spines.top': False,\n",
66
+ " 'axes.spines.right': False,\n",
67
+ " 'figure.dpi': 150,\n",
68
+ "})\n",
69
+ "\n",
70
+ "ROOT = Path('.')\n",
71
+ "EVAL_DIR = ROOT / 'data/eval_results'\n",
72
+ "HUMAN_DIR = ROOT / 'data/eval_results_human'"
73
+ ]
74
+ },
75
+ {
76
+ "cell_type": "markdown",
77
+ "id": "load-md",
78
+ "metadata": {},
79
+ "source": [
80
+ "## 1. Load Data"
81
+ ]
82
+ },
83
+ {
84
+ "cell_type": "code",
85
+ "execution_count": null,
86
+ "id": "load-human",
87
+ "metadata": {
88
+ "execution": {
89
+ "iopub.execute_input": "2026-05-06T19:01:36.928542Z",
90
+ "iopub.status.busy": "2026-05-06T19:01:36.928373Z",
91
+ "iopub.status.idle": "2026-05-06T19:01:36.934746Z",
92
+ "shell.execute_reply": "2026-05-06T19:01:36.934523Z"
93
+ }
94
+ },
95
+ "outputs": [],
96
+ "source": [
97
+ "# --- Human accuracy per image ---\n",
98
+ "with open(HUMAN_DIR / 'human_prolific_judged_results.json') as f:\n",
99
+ " human_raw = json.load(f)\n",
100
+ "\n",
101
+ "human_by_image = defaultdict(list)\n",
102
+ "for r in human_raw:\n",
103
+ " human_by_image[str(r['image_id'])].append(r['consensus_correct'])\n",
104
+ "\n",
105
+ "human_acc = {\n",
106
+ " img_id: sum(vals) / len(vals)\n",
107
+ " for img_id, vals in human_by_image.items()\n",
108
+ "}\n",
109
+ "human_n = {img_id: len(vals) for img_id, vals in human_by_image.items()}\n",
110
+ "\n",
111
+ "print(f'Images with human data: {len(human_acc)}')\n",
112
+ "print(f'Total human responses: {len(human_raw)}')\n",
113
+ "print(f'Avg respondents/image: {np.mean(list(human_n.values())):.1f}')\n",
114
+ "print(f'Overall human accuracy: {np.mean(list(human_acc.values())):.3f}')"
115
+ ]
116
+ },
117
+ {
118
+ "cell_type": "code",
119
+ "execution_count": null,
120
+ "id": "load-models",
121
+ "metadata": {
122
+ "execution": {
123
+ "iopub.execute_input": "2026-05-06T19:01:36.935782Z",
124
+ "iopub.status.busy": "2026-05-06T19:01:36.935718Z",
125
+ "iopub.status.idle": "2026-05-06T19:01:36.975392Z",
126
+ "shell.execute_reply": "2026-05-06T19:01:36.975157Z"
127
+ }
128
+ },
129
+ "outputs": [],
130
+ "source": [
131
+ "# --- Model accuracy per image ---\n",
132
+ "MODELS = [\n",
133
+ " 'gpt-5.4',\n",
134
+ " 'claude-opus-4-6',\n",
135
+ " 'gemini-3.1-pro-preview',\n",
136
+ " 'Qwen3-VL-8B-Instruct',\n",
137
+ " 'Llama-4-Maverick-17B-128E-Instruct-FP8',\n",
138
+ "]\n",
139
+ "DISPLAY = {\n",
140
+ " 'claude-opus-4-6': 'Claude Opus 4.6',\n",
141
+ " 'gemini-3.1-pro-preview': 'Gemini 3.1 Pro',\n",
142
+ " 'gpt-5.4': 'GPT-5.4',\n",
143
+ " 'Llama-4-Maverick-17B-128E-Instruct-FP8': 'Llama 4 Maverick',\n",
144
+ " 'Qwen3-VL-8B-Instruct': 'Qwen 3 VL 8B',\n",
145
+ "}\n",
146
+ "MODEL_ORDER = [DISPLAY[m] for m in MODELS]\n",
147
+ "PALETTE = {\n",
148
+ " 'Claude Opus 4.6': '#DD8452',\n",
149
+ " 'Gemini 3.1 Pro': '#55A868',\n",
150
+ " 'GPT-5.4': '#4C72B0',\n",
151
+ " 'Llama 4 Maverick': '#8172B3',\n",
152
+ " 'Qwen 3 VL 8B': '#C44E52',\n",
153
+ "}\n",
154
+ "\n",
155
+ "rows = []\n",
156
+ "for model in MODELS:\n",
157
+ " with open(EVAL_DIR / f'{model}_judged_results.json') as f:\n",
158
+ " data = json.load(f)\n",
159
+ " for entry in data:\n",
160
+ " img_id = str(entry['id'])\n",
161
+ " occ_j = entry.get('occluded_correct', {})\n",
162
+ " correct = any(occ_j.values()) if occ_j else False\n",
163
+ " rows.append({\n",
164
+ " 'image_id': img_id,\n",
165
+ " 'model': model,\n",
166
+ " 'model_short': DISPLAY[model],\n",
167
+ " 'correct': correct,\n",
168
+ " 'human_acc': human_acc.get(img_id, np.nan),\n",
169
+ " 'human_n': human_n.get(img_id, 0),\n",
170
+ " })\n",
171
+ "\n",
172
+ "df = pd.DataFrame(rows).dropna(subset=['human_acc'])\n",
173
+ "print(df.groupby('model_short')['correct'].mean().reindex(MODEL_ORDER).round(3))\n",
174
+ "print(f'\\nImages with both human + model data: {df[\"image_id\"].nunique()}')"
175
+ ]
176
+ },
177
+ {
178
+ "cell_type": "markdown",
179
+ "id": "corr-md",
180
+ "metadata": {},
181
+ "source": [
182
+ "## 2. Point-Biserial Correlation: Human Accuracy ↔ Model Correctness\n",
183
+ "\n",
184
+ "Positive r means models are more likely to be correct on images humans also find easy."
185
+ ]
186
+ },
187
+ {
188
+ "cell_type": "code",
189
+ "execution_count": null,
190
+ "id": "corr-cell",
191
+ "metadata": {
192
+ "execution": {
193
+ "iopub.execute_input": "2026-05-06T19:01:36.976706Z",
194
+ "iopub.status.busy": "2026-05-06T19:01:36.976633Z",
195
+ "iopub.status.idle": "2026-05-06T19:01:37.228775Z",
196
+ "shell.execute_reply": "2026-05-06T19:01:37.228191Z"
197
+ }
198
+ },
199
+ "outputs": [],
200
+ "source": [
201
+ "corr_rows = []\n",
202
+ "for model in MODELS:\n",
203
+ " sub = df[df['model'] == model][['human_acc', 'correct']].dropna()\n",
204
+ " r, p = stats.pointbiserialr(sub['correct'].astype(int), sub['human_acc'])\n",
205
+ " corr_rows.append({\n",
206
+ " 'Model': DISPLAY[model],\n",
207
+ " 'r': r,\n",
208
+ " 'p': p,\n",
209
+ " 'sig': '***' if p < 0.001 else '**' if p < 0.01 else '*' if p < 0.05 else 'ns',\n",
210
+ " })\n",
211
+ "\n",
212
+ "corr_df = pd.DataFrame(corr_rows)\n",
213
+ "print(corr_df.to_string(index=False))\n",
214
+ "\n",
215
+ "fig, ax = plt.subplots(figsize=(9, 4))\n",
216
+ "colors = [PALETTE[DISPLAY[m]] for m in MODELS]\n",
217
+ "bars = ax.bar(corr_df['Model'], corr_df['r'], color=colors, edgecolor='grey', lw=0.5)\n",
218
+ "for bar, row in zip(bars, corr_df.itertuples()):\n",
219
+ " yoff = 0.005 if row.r >= 0 else -0.015\n",
220
+ " ax.text(bar.get_x() + bar.get_width() / 2, bar.get_height() + yoff,\n",
221
+ " f'{row.r:.3f} ({row.sig})', ha='center', va='bottom', fontsize=9)\n",
222
+ "ax.axhline(0, color='black', lw=0.8)\n",
223
+ "ax.set_ylabel('Point-Biserial r (human accuracy ↔ model correct)')\n",
224
+ "ax.set_title('Human–Model Difficulty Correlation (Occluded)', fontweight='bold')\n",
225
+ "ax.set_xticklabels(corr_df['Model'], rotation=15, ha='right')\n",
226
+ "plt.tight_layout()\n",
227
+ "plt.savefig('data/figures/human_model_corr_point_biserial.pdf', bbox_inches='tight')\n",
228
+ "plt.show()"
229
+ ]
230
+ },
231
+ {
232
+ "cell_type": "markdown",
233
+ "id": "quintile-md",
234
+ "metadata": {},
235
+ "source": [
236
+ "## 3. Model Accuracy by Human-Difficulty Quintile\n",
237
+ "\n",
238
+ "Images are split into 5 equal-sized bins by human accuracy (Q1 = hardest for humans, Q5 = easiest). We then plot model accuracy within each bin."
239
+ ]
240
+ },
241
+ {
242
+ "cell_type": "code",
243
+ "execution_count": null,
244
+ "id": "quintile-cell",
245
+ "metadata": {
246
+ "execution": {
247
+ "iopub.execute_input": "2026-05-06T19:01:37.232081Z",
248
+ "iopub.status.busy": "2026-05-06T19:01:37.231734Z",
249
+ "iopub.status.idle": "2026-05-06T19:01:37.570376Z",
250
+ "shell.execute_reply": "2026-05-06T19:01:37.570120Z"
251
+ }
252
+ },
253
+ "outputs": [],
254
+ "source": [
255
+ "\n",
256
+ "# Assign quintiles based on human accuracy (same bins for all models)\n",
257
+ "# Note: many images have human_acc == 1.0 so qcut collapses to 4 unique bins\n",
258
+ "image_df = df[df['model'] == MODELS[0]][['image_id', 'human_acc']].drop_duplicates().copy()\n",
259
+ "image_df['quintile'], bin_edges = pd.qcut(\n",
260
+ " image_df['human_acc'], q=5, retbins=True, duplicates='drop'\n",
261
+ ")\n",
262
+ "n_bins = len(bin_edges) - 1\n",
263
+ "\n",
264
+ "# Build short labels: Q1=(hardest)..Qn=(easiest)\n",
265
+ "bin_cats = image_df['quintile'].cat.categories.tolist()\n",
266
+ "short_labels = [f'Q{i+1}' for i in range(n_bins)]\n",
267
+ "short_labels[0] += '\\n(hardest)'\n",
268
+ "short_labels[-1] += '\\n(easiest)'\n",
269
+ "cat_to_short = dict(zip(bin_cats, short_labels))\n",
270
+ "image_df['q_label'] = image_df['quintile'].map(cat_to_short)\n",
271
+ "\n",
272
+ "df = df.merge(image_df[['image_id', 'quintile', 'q_label']], on='image_id', how='left')\n",
273
+ "\n",
274
+ "fig, axes = plt.subplots(1, len(MODELS), figsize=(4.2 * len(MODELS), 5), sharey=True)\n",
275
+ "fig.suptitle('Model Accuracy by Human-Difficulty Quintile (Occluded)',\n",
276
+ " fontsize=13, fontweight='bold')\n",
277
+ "\n",
278
+ "for ax, model in zip(axes, MODELS):\n",
279
+ " sub = df[df['model'] == model].copy()\n",
280
+ " agg = (sub.groupby('q_label', observed=True)['correct']\n",
281
+ " .agg(['mean', 'count'])\n",
282
+ " .reindex(short_labels))\n",
283
+ " colors = plt.cm.RdYlGn(np.linspace(0.15, 0.85, len(agg)))\n",
284
+ " bars = ax.bar(short_labels, agg['mean'], color=colors, edgecolor='grey', lw=0.5)\n",
285
+ " for bar, row in zip(bars, agg.itertuples()):\n",
286
+ " ax.text(bar.get_x() + bar.get_width() / 2, bar.get_height() + 0.01,\n",
287
+ " f'{row.mean:.0%}\\n(n={row.count})', ha='center', va='bottom', fontsize=7.5)\n",
288
+ " ax.set_ylim(0, 1.2)\n",
289
+ " ax.set_title(DISPLAY[model], fontsize=10)\n",
290
+ " ax.set_xlabel('Human accuracy quintile')\n",
291
+ " if ax is axes[0]:\n",
292
+ " ax.set_ylabel('Model accuracy')\n",
293
+ " ax.tick_params(axis='x', labelsize=8)\n",
294
+ "\n",
295
+ "plt.tight_layout()\n",
296
+ "plt.savefig('data/figures/human_model_corr_accuracy_by_quintile.pdf', bbox_inches='tight')\n",
297
+ "plt.show()\n"
298
+ ]
299
+ },
300
+ {
301
+ "cell_type": "markdown",
302
+ "id": "scatter-md",
303
+ "metadata": {},
304
+ "source": [
305
+ "## 4. Scatter: Human Accuracy vs. Model Accuracy (Per Image)\n",
306
+ "\n",
307
+ "Each dot is one image. x = fraction of humans correct, y = model's binary 0/1 (jittered). Logistic regression curve overlaid."
308
+ ]
309
+ },
310
+ {
311
+ "cell_type": "code",
312
+ "execution_count": null,
313
+ "id": "scatter-cell",
314
+ "metadata": {
315
+ "execution": {
316
+ "iopub.execute_input": "2026-05-06T19:01:37.571886Z",
317
+ "iopub.status.busy": "2026-05-06T19:01:37.571703Z",
318
+ "iopub.status.idle": "2026-05-06T19:01:38.139140Z",
319
+ "shell.execute_reply": "2026-05-06T19:01:38.138879Z"
320
+ }
321
+ },
322
+ "outputs": [],
323
+ "source": [
324
+ "from sklearn.linear_model import LogisticRegression\n",
325
+ "\n",
326
+ "rng = np.random.default_rng(42)\n",
327
+ "fig, axes = plt.subplots(1, len(MODELS), figsize=(4.2 * len(MODELS), 4.5), sharey=True)\n",
328
+ "fig.suptitle('P(Model Correct) vs Human Accuracy — Occluded', fontsize=13, fontweight='bold')\n",
329
+ "\n",
330
+ "for ax, model in zip(axes, MODELS):\n",
331
+ " sub = df[df['model'] == model][['human_acc', 'correct']].dropna().copy()\n",
332
+ " X = sub['human_acc'].values\n",
333
+ " y = sub['correct'].astype(int).values\n",
334
+ " jitter = rng.uniform(-0.03, 0.03, len(y))\n",
335
+ " point_colors = ['#4CAF50' if c else '#F44336' for c in y]\n",
336
+ " ax.scatter(X, y + jitter, c=point_colors, alpha=0.35, s=14, edgecolors='none')\n",
337
+ "\n",
338
+ " lr = LogisticRegression()\n",
339
+ " lr.fit(X.reshape(-1, 1), y)\n",
340
+ " xr = np.linspace(0, 1, 200)\n",
341
+ " ph = lr.predict_proba(xr.reshape(-1, 1))[:, 1]\n",
342
+ " ax.plot(xr, ph, color=PALETTE[DISPLAY[model]], lw=2.5)\n",
343
+ "\n",
344
+ " r, p = stats.pointbiserialr(y, X)\n",
345
+ " sig = '***' if p < 0.001 else '**' if p < 0.01 else '*' if p < 0.05 else 'ns'\n",
346
+ " ax.set_title(f'{DISPLAY[model]}\\nr={r:.3f} ({sig})', fontsize=9)\n",
347
+ " ax.set_xlabel('Human accuracy')\n",
348
+ " ax.set_xlim(-0.05, 1.05)\n",
349
+ " if ax is axes[0]:\n",
350
+ " ax.set_ylabel('Model correct (jittered)')\n",
351
+ " ax.set_yticks([0, 1])\n",
352
+ " ax.set_yticklabels(['No', 'Yes'])\n",
353
+ "\n",
354
+ "plt.tight_layout()\n",
355
+ "plt.savefig('data/figures/human_model_corr_scatter_logistic.pdf', bbox_inches='tight')\n",
356
+ "plt.show()"
357
+ ]
358
+ },
359
+ {
360
+ "cell_type": "markdown",
361
+ "id": "heatmap-md",
362
+ "metadata": {},
363
+ "source": [
364
+ "## 5. Combined Accuracy by Human-Difficulty Bin (All Models)\n",
365
+ "\n",
366
+ "A single panel showing all models together, binned by human accuracy decile. Also shows the human baseline in each bin."
367
+ ]
368
+ },
369
+ {
370
+ "cell_type": "code",
371
+ "execution_count": null,
372
+ "id": "combined-cell",
373
+ "metadata": {
374
+ "execution": {
375
+ "iopub.execute_input": "2026-05-06T19:01:38.141007Z",
376
+ "iopub.status.busy": "2026-05-06T19:01:38.140846Z",
377
+ "iopub.status.idle": "2026-05-06T19:01:38.291447Z",
378
+ "shell.execute_reply": "2026-05-06T19:01:38.291183Z"
379
+ }
380
+ },
381
+ "outputs": [],
382
+ "source": [
383
+ "from matplotlib.lines import Line2D\n",
384
+ "\n",
385
+ "# Build per-image pivot\n",
386
+ "pivot = df.pivot_table(index='image_id', columns='model_short', values='correct', aggfunc='first')\n",
387
+ "pivot['human_acc'] = pivot.index.map(human_acc)\n",
388
+ "pivot = pivot.dropna(subset=['human_acc'])\n",
389
+ "\n",
390
+ "# Bin by human accuracy (10% bins) for the dots\n",
391
+ "BIN_W = 0.1\n",
392
+ "bins = np.arange(0, 1 + BIN_W, BIN_W)\n",
393
+ "pivot['bin_mid'] = pd.cut(pivot['human_acc'], bins=bins, include_lowest=True).apply(\n",
394
+ " lambda iv: iv.mid * 100 if pd.notna(iv) else np.nan\n",
395
+ ")\n",
396
+ "\n",
397
+ "fig, ax = plt.subplots(figsize=(11, 4.0))\n",
398
+ "\n",
399
+ "model_handles = []\n",
400
+ "for model in MODEL_ORDER:\n",
401
+ " color = PALETTE[model]\n",
402
+ " model_data = pivot[['human_acc', 'bin_mid', model]].dropna()\n",
403
+ "\n",
404
+ " agg = model_data.groupby('bin_mid')[model].agg(['mean', 'count']).reset_index()\n",
405
+ " agg = agg[agg['count'] >= 3]\n",
406
+ " ax.scatter(agg['bin_mid'], agg['mean'] * 100,\n",
407
+ " s=agg['count'] * 8, color=color, alpha=0.85,\n",
408
+ " edgecolors='white', linewidths=0.5, zorder=3)\n",
409
+ "\n",
410
+ " ax.plot(agg['bin_mid'], agg['mean'] * 100, color=color, lw=1.5,\n",
411
+ " linestyle=':', zorder=2)\n",
412
+ "\n",
413
+ " model_handles.append(\n",
414
+ " Line2D([0], [0], color=color, lw=1.5, linestyle=':', marker='o', markersize=6,\n",
415
+ " markerfacecolor=color, markeredgecolor='white', label=model)\n",
416
+ " )\n",
417
+ "\n",
418
+ "ax.set_xlim(-2, 102)\n",
419
+ "ax.set_ylim(-5, 108)\n",
420
+ "ax.set_xticks([0, 20, 40, 60, 80, 100])\n",
421
+ "ax.set_yticks([0, 20, 40, 60, 80, 100])\n",
422
+ "ax.minorticks_off()\n",
423
+ "ax.tick_params(axis='both', which='major', direction='out', length=4, labelsize=14)\n",
424
+ "ax.set_xlabel('Human accuracy', fontsize=14)\n",
425
+ "ax.set_ylabel('Model accuracy', fontsize=14)\n",
426
+ "ax.xaxis.set_major_formatter(mtick.PercentFormatter())\n",
427
+ "ax.yaxis.set_major_formatter(mtick.PercentFormatter())\n",
428
+ "\n",
429
+ "ref_ns = [5, 15, 30]\n",
430
+ "ref_handles = [\n",
431
+ " plt.scatter([], [], s=n * 8, color='black', alpha=1.0,\n",
432
+ " edgecolors='black', linewidths=0, label=f'n = {n}')\n",
433
+ " for n in ref_ns\n",
434
+ "]\n",
435
+ "\n",
436
+ "plt.subplots_adjust(bottom=0.36)\n",
437
+ "\n",
438
+ "# Row 1: model line+dot handles\n",
439
+ "leg1 = ax.legend(handles=model_handles,\n",
440
+ " labels=[h.get_label() for h in model_handles],\n",
441
+ " loc='upper center', bbox_to_anchor=(0.5, -0.28),\n",
442
+ " ncol=len(model_handles), frameon=False,\n",
443
+ " fontsize=12, columnspacing=1.0,\n",
444
+ " handlelength=1.6, handletextpad=0.4)\n",
445
+ "ax.add_artist(leg1)\n",
446
+ "\n",
447
+ "# Row 2: bubble size indicators\n",
448
+ "ax.legend(handles=ref_handles,\n",
449
+ " labels=[f'n = {n}' for n in ref_ns],\n",
450
+ " loc='upper center', bbox_to_anchor=(0.5, -0.42),\n",
451
+ " ncol=len(ref_handles), frameon=False,\n",
452
+ " title='Images per bin', title_fontsize=12,\n",
453
+ " fontsize=12, columnspacing=1.2, handletextpad=0.4)\n",
454
+ "\n",
455
+ "plt.savefig('data/figures/human_model_corr_combined_dots.pdf', bbox_inches='tight')\n",
456
+ "plt.show()\n"
457
+ ]
458
+ },
459
+ {
460
+ "cell_type": "code",
461
+ "execution_count": null,
462
+ "id": "00126acd",
463
+ "metadata": {},
464
+ "outputs": [],
465
+ "source": [
466
+ "# ---- Same combined dot-plot, split into DIRECT/PHYSICAL and INFERENTIAL ----\n",
467
+ "# Category label per image from the manual \"direct or inferential\" annotations\n",
468
+ "# (in this dataset direct == physically-occluded, inferential == digitally-occluded).\n",
469
+ "_cat = pd.read_excel(ROOT / 'data/Image categories (3).xlsx')[['image id', 'direct or inferential']]\n",
470
+ "_cat['image id'] = _cat['image id'].astype(str)\n",
471
+ "img_cat = dict(zip(_cat['image id'], _cat['direct or inferential']))\n",
472
+ "\n",
473
+ "# Rebuild the pivot with a category column (reuses the human-accuracy binning above)\n",
474
+ "pivot_cat = df.pivot_table(index='image_id', columns='model_short', values='correct', aggfunc='first')\n",
475
+ "pivot_cat['human_acc'] = pivot_cat.index.map(human_acc)\n",
476
+ "pivot_cat['category'] = pivot_cat.index.map(img_cat)\n",
477
+ "pivot_cat = pivot_cat.dropna(subset=['human_acc'])\n",
478
+ "pivot_cat['bin_mid'] = pd.cut(pivot_cat['human_acc'], bins=bins, include_lowest=True).apply(\n",
479
+ " lambda iv: iv.mid * 100 if pd.notna(iv) else np.nan\n",
480
+ ")\n",
481
+ "\n",
482
+ "\n",
483
+ "def plot_human_model_dots(sub, title, outfile):\n",
484
+ " fig, ax = plt.subplots(figsize=(11, 4.0))\n",
485
+ " model_handles = []\n",
486
+ " for model in MODEL_ORDER:\n",
487
+ " color = PALETTE[model]\n",
488
+ " model_data = sub[['human_acc', 'bin_mid', model]].dropna()\n",
489
+ " agg = model_data.groupby('bin_mid')[model].agg(['mean', 'count']).reset_index()\n",
490
+ " agg = agg[agg['count'] >= 3]\n",
491
+ " ax.scatter(agg['bin_mid'], agg['mean'] * 100,\n",
492
+ " s=agg['count'] * 8, color=color, alpha=0.85,\n",
493
+ " edgecolors='white', linewidths=0.5, zorder=3)\n",
494
+ " ax.plot(agg['bin_mid'], agg['mean'] * 100, color=color, lw=1.5,\n",
495
+ " linestyle=':', zorder=2)\n",
496
+ " model_handles.append(\n",
497
+ " Line2D([0], [0], color=color, lw=1.5, linestyle=':', marker='o', markersize=6,\n",
498
+ " markerfacecolor=color, markeredgecolor='white', label=model)\n",
499
+ " )\n",
500
+ "\n",
501
+ " ax.set_xlim(-2, 102)\n",
502
+ " ax.set_ylim(-5, 108)\n",
503
+ " ax.set_xticks([0, 20, 40, 60, 80, 100])\n",
504
+ " ax.set_yticks([0, 20, 40, 60, 80, 100])\n",
505
+ " ax.minorticks_off()\n",
506
+ " ax.tick_params(axis='both', which='major', direction='out', length=4, labelsize=14)\n",
507
+ " ax.set_xlabel('Human accuracy', fontsize=14)\n",
508
+ " ax.set_ylabel('Model accuracy', fontsize=14)\n",
509
+ " ax.set_title(title, fontsize=14, fontweight='bold')\n",
510
+ " ax.xaxis.set_major_formatter(mtick.PercentFormatter())\n",
511
+ " ax.yaxis.set_major_formatter(mtick.PercentFormatter())\n",
512
+ "\n",
513
+ " ref_ns = [5, 15, 30]\n",
514
+ " ref_handles = [\n",
515
+ " plt.scatter([], [], s=n * 8, color='black', alpha=1.0,\n",
516
+ " edgecolors='black', linewidths=0, label=f'n = {n}')\n",
517
+ " for n in ref_ns\n",
518
+ " ]\n",
519
+ "\n",
520
+ " plt.subplots_adjust(bottom=0.36)\n",
521
+ " leg1 = ax.legend(handles=model_handles, labels=[h.get_label() for h in model_handles],\n",
522
+ " loc='upper center', bbox_to_anchor=(0.5, -0.28),\n",
523
+ " ncol=len(model_handles), frameon=False, fontsize=12,\n",
524
+ " columnspacing=1.0, handlelength=1.6, handletextpad=0.4)\n",
525
+ " ax.add_artist(leg1)\n",
526
+ " ax.legend(handles=ref_handles, labels=[f'n = {n}' for n in ref_ns],\n",
527
+ " loc='upper center', bbox_to_anchor=(0.5, -0.42),\n",
528
+ " ncol=len(ref_handles), frameon=False, title='Images per bin',\n",
529
+ " title_fontsize=12, fontsize=12, columnspacing=1.2, handletextpad=0.4)\n",
530
+ " plt.savefig(outfile, bbox_inches='tight')\n",
531
+ " plt.show()\n",
532
+ "\n",
533
+ "\n",
534
+ "plot_human_model_dots(\n",
535
+ " pivot_cat[pivot_cat['category'] == 'direct'],\n",
536
+ " 'Human vs Model Accuracy — Direct/Physical',\n",
537
+ " 'data/figures/human_model_corr_combined_dots_direct.pdf')\n",
538
+ "\n",
539
+ "plot_human_model_dots(\n",
540
+ " pivot_cat[pivot_cat['category'] == 'inferential'],\n",
541
+ " 'Human vs Model Accuracy — Inferential',\n",
542
+ " 'data/figures/human_model_corr_combined_dots_inferential.pdf')\n"
543
+ ]
544
+ },
545
+ {
546
+ "cell_type": "markdown",
547
+ "id": "hard-images-md",
548
+ "metadata": {},
549
+ "source": [
550
+ "## 6. Hardest-for-Humans Images: Do All Models Fail Together?\n",
551
+ "\n",
552
+ "For images where human accuracy < 20%, what fraction do ALL models get wrong simultaneously?"
553
+ ]
554
+ },
555
+ {
556
+ "cell_type": "code",
557
+ "execution_count": null,
558
+ "id": "hard-images-cell",
559
+ "metadata": {
560
+ "execution": {
561
+ "iopub.execute_input": "2026-05-06T19:01:38.292845Z",
562
+ "iopub.status.busy": "2026-05-06T19:01:38.292749Z",
563
+ "iopub.status.idle": "2026-05-06T19:01:38.637556Z",
564
+ "shell.execute_reply": "2026-05-06T19:01:38.637302Z"
565
+ }
566
+ },
567
+ "outputs": [],
568
+ "source": [
569
+ "THRESHOLDS = [0.2, 0.4, 0.6, 0.8]\n",
570
+ "\n",
571
+ "rows_thresh = []\n",
572
+ "for thresh in THRESHOLDS:\n",
573
+ " hard_images = [img for img, acc in human_acc.items() if acc < thresh]\n",
574
+ " easy_images = [img for img, acc in human_acc.items() if acc >= thresh]\n",
575
+ " for model in MODELS:\n",
576
+ " sub_hard = df[(df['model'] == model) & (df['image_id'].isin(hard_images))]\n",
577
+ " sub_easy = df[(df['model'] == model) & (df['image_id'].isin(easy_images))]\n",
578
+ " rows_thresh.append({\n",
579
+ " 'Model': DISPLAY[model],\n",
580
+ " 'threshold': thresh,\n",
581
+ " 'acc_hard': sub_hard['correct'].mean() if len(sub_hard) else np.nan,\n",
582
+ " 'acc_easy': sub_easy['correct'].mean() if len(sub_easy) else np.nan,\n",
583
+ " 'n_hard': len(sub_hard),\n",
584
+ " 'n_easy': len(sub_easy),\n",
585
+ " })\n",
586
+ "\n",
587
+ "thresh_df = pd.DataFrame(rows_thresh)\n",
588
+ "\n",
589
+ "fig, axes = plt.subplots(1, len(THRESHOLDS), figsize=(4.5 * len(THRESHOLDS), 5), sharey=True)\n",
590
+ "fig.suptitle('Model Accuracy: Images Hard vs. Easy for Humans', fontsize=13, fontweight='bold')\n",
591
+ "\n",
592
+ "for ax, thresh in zip(axes, THRESHOLDS):\n",
593
+ " sub = thresh_df[thresh_df['threshold'] == thresh].set_index('Model').reindex(MODEL_ORDER)\n",
594
+ " x = np.arange(len(MODEL_ORDER))\n",
595
+ " w = 0.35\n",
596
+ " bars_hard = ax.bar(x - w/2, sub['acc_hard'], width=w,\n",
597
+ " color='#F44336', alpha=0.8, label=f'Human acc < {int(thresh*100)}%',\n",
598
+ " edgecolor='grey', lw=0.4)\n",
599
+ " bars_easy = ax.bar(x + w/2, sub['acc_easy'], width=w,\n",
600
+ " color='#4CAF50', alpha=0.8, label=f'Human acc ≥ {int(thresh*100)}%',\n",
601
+ " edgecolor='grey', lw=0.4)\n",
602
+ " for bar in list(bars_hard) + list(bars_easy):\n",
603
+ " h = bar.get_height()\n",
604
+ " if not np.isnan(h):\n",
605
+ " ax.text(bar.get_x() + bar.get_width()/2, h + 0.01,\n",
606
+ " f'{h:.0%}', ha='center', va='bottom', fontsize=7)\n",
607
+ " ax.set_xticks(x)\n",
608
+ " ax.set_xticklabels(MODEL_ORDER, rotation=20, ha='right', fontsize=7.5)\n",
609
+ " ax.set_ylim(0, 1.15)\n",
610
+ " ax.set_title(f'Threshold = {int(thresh*100)}%', fontsize=10)\n",
611
+ " if ax is axes[0]:\n",
612
+ " ax.set_ylabel('Model accuracy')\n",
613
+ " ax.legend(fontsize=7, loc='upper left')\n",
614
+ "\n",
615
+ "plt.tight_layout()\n",
616
+ "plt.savefig('data/figures/human_model_corr_hard_vs_easy.pdf', bbox_inches='tight')\n",
617
+ "plt.show()"
618
+ ]
619
+ },
620
+ {
621
+ "cell_type": "markdown",
622
+ "id": "summary-md",
623
+ "metadata": {},
624
+ "source": [
625
+ "## 7. Summary Table"
626
+ ]
627
+ },
628
+ {
629
+ "cell_type": "code",
630
+ "execution_count": null,
631
+ "id": "summary-cell",
632
+ "metadata": {
633
+ "execution": {
634
+ "iopub.execute_input": "2026-05-06T19:01:38.638922Z",
635
+ "iopub.status.busy": "2026-05-06T19:01:38.638831Z",
636
+ "iopub.status.idle": "2026-05-06T19:01:38.648383Z",
637
+ "shell.execute_reply": "2026-05-06T19:01:38.648127Z"
638
+ }
639
+ },
640
+ "outputs": [],
641
+ "source": [
642
+ "summary_rows = []\n",
643
+ "for model in MODELS:\n",
644
+ " sub = df[df['model'] == model][['human_acc', 'correct']].dropna()\n",
645
+ " r, p = stats.pointbiserialr(sub['correct'].astype(int), sub['human_acc'])\n",
646
+ " hard = sub[sub['human_acc'] < 0.4]['correct'].mean()\n",
647
+ " easy = sub[sub['human_acc'] >= 0.6]['correct'].mean()\n",
648
+ " summary_rows.append({\n",
649
+ " 'Model': DISPLAY[model],\n",
650
+ " 'Overall acc': sub['correct'].mean(),\n",
651
+ " 'Acc (human hard <40%)': hard,\n",
652
+ " 'Acc (human easy ≥60%)': easy,\n",
653
+ " 'Easy–Hard gap': easy - hard,\n",
654
+ " 'r (corr w/ human)': r,\n",
655
+ " 'p': p,\n",
656
+ " 'sig': '***' if p < 0.001 else '**' if p < 0.01 else '*' if p < 0.05 else 'ns',\n",
657
+ " })\n",
658
+ "\n",
659
+ "sum_df = pd.DataFrame(summary_rows)\n",
660
+ "pd.set_option('display.float_format', '{:.3f}'.format)\n",
661
+ "pd.set_option('display.max_columns', None)\n",
662
+ "pd.set_option('display.width', 200)\n",
663
+ "print(sum_df.to_string(index=False))"
664
+ ]
665
+ }
666
+ ],
667
+ "metadata": {
668
+ "kernelspec": {
669
+ "display_name": "cos429",
670
+ "language": "python",
671
+ "name": "python3"
672
+ },
673
+ "language_info": {
674
+ "codemirror_mode": {
675
+ "name": "ipython",
676
+ "version": 3
677
+ },
678
+ "file_extension": ".py",
679
+ "mimetype": "text/x-python",
680
+ "name": "python",
681
+ "nbconvert_exporter": "python",
682
+ "pygments_lexer": "ipython3",
683
+ "version": "3.8.18"
684
+ }
685
+ },
686
+ "nbformat": 4,
687
+ "nbformat_minor": 5
688
+ }
code/sec4_1_main_results/localization_unmasked/eval_transparent.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import base64
3
+ import io
4
+ import json
5
+ import os
6
+ from openai import OpenAI
7
+ from together import Together
8
+ import anthropic
9
+ from dotenv import load_dotenv
10
+ from PIL import Image
11
+
12
+ load_dotenv()
13
+ OpenAI_API_KEY = os.getenv("OpenAI_API_KEY")
14
+ Anthropic_API_KEY = os.getenv("Anthropic_API_KEY")
15
+ Gemini_API_KEY = os.getenv("Gemini_API_KEY")
16
+ Together_API_KEY = os.getenv("Together_API_KEY")
17
+
18
+ PROMPT = "What is the object outlined by the yellow border in this image? Be as specific as you can."
19
+
20
+ def init_client(args):
21
+ if "gpt" in args.model or args.model[0] == 'o':
22
+ return OpenAI(api_key=OpenAI_API_KEY)
23
+ elif "gemini" in args.model:
24
+ return OpenAI(api_key=Gemini_API_KEY, base_url="https://generativelanguage.googleapis.com/v1beta/openai/")
25
+ elif "claude" in args.model:
26
+ return anthropic.Anthropic(api_key=Anthropic_API_KEY)
27
+ else:
28
+ return Together(api_key=Together_API_KEY)
29
+
30
+ def encode_image(image_path, max_bytes=3.5 * 1024 * 1024):
31
+ with open(image_path, "rb") as f:
32
+ data = f.read()
33
+ if len(data) <= max_bytes:
34
+ return base64.b64encode(data).decode("utf-8")
35
+ img = Image.open(io.BytesIO(data))
36
+ scale = 0.9
37
+ while True:
38
+ buf = io.BytesIO()
39
+ img.save(buf, format="PNG", optimize=True)
40
+ if buf.tell() <= max_bytes:
41
+ break
42
+ w, h = img.size
43
+ img = img.resize((int(w * scale), int(h * scale)), Image.LANCZOS)
44
+ return base64.b64encode(buf.getvalue()).decode("utf-8")
45
+
46
+ def chat_completion(args, client, image_path):
47
+ b64 = encode_image(image_path)
48
+ media_type = "image/png"
49
+
50
+ if "claude" in args.model:
51
+ return client.messages.create(
52
+ model=args.model,
53
+ max_tokens=500,
54
+ temperature=0,
55
+ messages=[{
56
+ "role": "user",
57
+ "content": [
58
+ {"type": "image", "source": {"type": "base64", "media_type": media_type, "data": b64}},
59
+ {"type": "text", "text": PROMPT}
60
+ ]
61
+ }]
62
+ ).content[0].text
63
+ else:
64
+ return client.chat.completions.create(
65
+ model=args.model,
66
+ temperature=0,
67
+ messages=[{
68
+ "role": "user",
69
+ "content": [
70
+ {"type": "image_url", "image_url": {"url": f"data:{media_type};base64,{b64}"}},
71
+ {"type": "text", "text": PROMPT}
72
+ ]
73
+ }]
74
+ ).choices[0].message.content
75
+
76
+ def run_eval(args, client):
77
+ with open(os.path.join(args.data_dir, "annotations.json")) as f:
78
+ entries = json.load(f)
79
+
80
+ model_name = args.model.split("/")[-1]
81
+ output_path = os.path.join(args.output_dir, f"{model_name}_transparent_results.json")
82
+
83
+ if os.path.exists(output_path):
84
+ with open(output_path) as f:
85
+ results = json.load(f)
86
+ done_ids = {r["id"] for r in results}
87
+ print(f"Resuming: {len(done_ids)} already done, {len(entries) - len(done_ids)} remaining.")
88
+ else:
89
+ results = []
90
+ done_ids = set()
91
+
92
+ for entry in entries:
93
+ if entry["id"] in done_ids:
94
+ continue
95
+
96
+ base = os.path.splitext(entry["original_file"])[0]
97
+ transparent_path = os.path.join(args.data_dir, f"{base}_transparent.png")
98
+
99
+ if not os.path.exists(transparent_path):
100
+ print(f"Missing transparent image for {entry['id']}, skipping.")
101
+ continue
102
+
103
+ print(f"Running {entry['id']}...")
104
+ response = chat_completion(args, client, transparent_path)
105
+ print(f" {response}")
106
+
107
+ results.append({
108
+ "id": entry["id"],
109
+ "ground_truth": entry.get("answer", ""),
110
+ "response": response
111
+ })
112
+
113
+ os.makedirs(args.output_dir, exist_ok=True)
114
+ with open(output_path, "w") as f:
115
+ json.dump(results, f, indent=2)
116
+
117
+ return results
118
+
119
+ def parse_args():
120
+ parser = argparse.ArgumentParser()
121
+ parser.add_argument("--model", type=str, default="gpt-4o")
122
+ parser.add_argument("--data_dir", type=str, default="data/combined_output")
123
+ parser.add_argument("--output_dir", type=str, default="data/eval_results")
124
+ return parser.parse_args()
125
+
126
+ def main(args):
127
+ client = init_client(args)
128
+ os.makedirs(args.output_dir, exist_ok=True)
129
+ results = run_eval(args, client)
130
+ model_name = args.model.split("/")[-1]
131
+ print(f"Done. {len(results)} results in {os.path.join(args.output_dir, f'{model_name}_transparent_results.json')}")
132
+
133
+ if __name__ == "__main__":
134
+ args = parse_args()
135
+ main(args)
code/sec4_1_main_results/localization_unmasked/generate_transparent.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from pathlib import Path
3
+ from PIL import Image, ImageDraw
4
+
5
+ ANNOTATIONS_PATH = Path("data/combined_output/annotations.json")
6
+ OUTPUT_DIR = Path("data/combined_output")
7
+ BORDER_COLOR = "#f5ec00"
8
+ BORDER_WIDTH = 2
9
+
10
+ with open(ANNOTATIONS_PATH) as f:
11
+ data = json.load(f)
12
+
13
+ for entry in data:
14
+ original_file = OUTPUT_DIR / entry["original_file"]
15
+ if not original_file.exists():
16
+ print(f"Missing: {original_file}")
17
+ continue
18
+
19
+ img = Image.open(original_file).convert("RGBA")
20
+ overlay = Image.new("RGBA", img.size, (0, 0, 0, 0))
21
+ draw = ImageDraw.Draw(overlay)
22
+
23
+ for ann in entry["annotations"]:
24
+ if ann["type"] == "bbox":
25
+ draw.rectangle(
26
+ [ann["x1"], ann["y1"], ann["x2"], ann["y2"]],
27
+ outline=BORDER_COLOR,
28
+ fill=None,
29
+ width=BORDER_WIDTH,
30
+ )
31
+ elif ann["type"] == "polygon":
32
+ points = [(p["x"], p["y"]) for p in ann["points"]]
33
+ draw.polygon(points, outline=BORDER_COLOR, fill=None)
34
+ # thicken the outline
35
+ draw.line(points + [points[0]], fill=BORDER_COLOR, width=BORDER_WIDTH)
36
+
37
+ result = Image.alpha_composite(img, overlay).convert("RGB")
38
+ out_path = OUTPUT_DIR / f"{original_file.stem}_transparent.png"
39
+ result.save(out_path)
40
+
41
+ print(f"Done. Generated {len(data)} transparent images.")
code/sec4_1_main_results/nudge_comparison.ipynb ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Nudge vs Base — Physical Accuracy Comparison\n",
8
+ "\n",
9
+ "Compares physical occlusion accuracy with and without the reflective-surface nudge across three experiment types: base, thinking, and tool use."
10
+ ]
11
+ },
12
+ {
13
+ "cell_type": "code",
14
+ "execution_count": null,
15
+ "metadata": {},
16
+ "outputs": [],
17
+ "source": [
18
+ "# Run from the repo root so the root-relative data paths below resolve\n",
19
+ "import os\n",
20
+ "from pathlib import Path\n",
21
+ "os.chdir(next(p for p in [Path.cwd(), *Path.cwd().parents] if (p / \"sec3_occludebench\").is_dir()))"
22
+ ]
23
+ },
24
+ {
25
+ "cell_type": "code",
26
+ "execution_count": null,
27
+ "metadata": {
28
+ "execution": {
29
+ "iopub.execute_input": "2026-05-06T18:27:12.356478Z",
30
+ "iopub.status.busy": "2026-05-06T18:27:12.356276Z",
31
+ "iopub.status.idle": "2026-05-06T18:27:12.644296Z",
32
+ "shell.execute_reply": "2026-05-06T18:27:12.643992Z"
33
+ }
34
+ },
35
+ "outputs": [],
36
+ "source": [
37
+ "import json\n",
38
+ "import os\n",
39
+ "import math\n",
40
+ "import numpy as np\n",
41
+ "import matplotlib.pyplot as plt\n",
42
+ "import matplotlib.ticker as mtick\n",
43
+ "\n",
44
+ "plt.rcParams.update({'font.family': 'Arial', 'font.size': 38})\n",
45
+ "\n",
46
+ "ANNOTATIONS_PATH = 'data/combined_output/annotations.json'\n",
47
+ "JUDGE_MODELS = ['gpt-5.4', 'claude-opus-4-6']\n",
48
+ "\n",
49
+ "with open(ANNOTATIONS_PATH) as f:\n",
50
+ " annotations = json.load(f)\n",
51
+ "physical_map = {str(item['id']): item['physical'] for item in annotations}\n",
52
+ "\n",
53
+ "DISPLAY = {\n",
54
+ " 'gpt-5.4': 'GPT-5.4',\n",
55
+ " 'claude-opus-4-6': 'Claude\\nOpus 4.6',\n",
56
+ " 'gemini-3.1-pro-preview': 'Gemini\\n3.1 Pro',\n",
57
+ " 'Llama-4-Maverick-17B-128E-Instruct-FP8': 'Llama 4\\nMaverick',\n",
58
+ " 'Qwen3-VL-8B-Instruct': 'Qwen 3\\nVL 8B',\n",
59
+ "}\n",
60
+ "\n",
61
+ "def load_judged(directory, stem):\n",
62
+ " path = os.path.join(directory, f'{stem}_judged_results.json')\n",
63
+ " if not os.path.exists(path):\n",
64
+ " return []\n",
65
+ " with open(path) as f:\n",
66
+ " return json.load(f)\n",
67
+ "\n",
68
+ "def accuracy_by_physicality(judged_data, is_physical, judge_models=JUDGE_MODELS):\n",
69
+ " total, correct = 0, 0.0\n",
70
+ " for item in judged_data:\n",
71
+ " if physical_map.get(str(item['id'])) != is_physical:\n",
72
+ " continue\n",
73
+ " vd = item.get('occluded_correct', {})\n",
74
+ " scores = [vd[jm] for jm in judge_models if jm in vd and vd[jm] is not None]\n",
75
+ " if not scores:\n",
76
+ " continue\n",
77
+ " correct += sum(scores) / len(scores)\n",
78
+ " total += 1\n",
79
+ " return correct / total * 100 if total else None\n",
80
+ "\n",
81
+ "def physical_accuracy(judged_data, judge_models=JUDGE_MODELS):\n",
82
+ " return accuracy_by_physicality(judged_data, True, judge_models)\n",
83
+ "\n",
84
+ "def nonphysical_accuracy(judged_data, judge_models=JUDGE_MODELS):\n",
85
+ " return accuracy_by_physicality(judged_data, False, judge_models)\n",
86
+ "\n",
87
+ "print('Loaded', sum(physical_map.values()), 'physical entries')"
88
+ ]
89
+ },
90
+ {
91
+ "cell_type": "code",
92
+ "execution_count": null,
93
+ "metadata": {
94
+ "execution": {
95
+ "iopub.execute_input": "2026-05-06T18:27:12.660916Z",
96
+ "iopub.status.busy": "2026-05-06T18:27:12.660767Z",
97
+ "iopub.status.idle": "2026-05-06T18:27:12.683797Z",
98
+ "shell.execute_reply": "2026-05-06T18:27:12.683559Z"
99
+ }
100
+ },
101
+ "outputs": [],
102
+ "source": [
103
+ "# --- Experiment configs ---\n",
104
+ "EXPERIMENTS = [\n",
105
+ " {\n",
106
+ " 'title': 'Base',\n",
107
+ " 'stems': ['gpt-5.4', 'claude-opus-4-6', 'gemini-3.1-pro-preview',\n",
108
+ " 'Llama-4-Maverick-17B-128E-Instruct-FP8',\n",
109
+ " 'Qwen3-VL-8B-Instruct'],\n",
110
+ " 'base_dir': 'data/eval_results',\n",
111
+ " 'nudge_dir': 'data/eval_results_nudge',\n",
112
+ " 'occlusion_dir': None,\n",
113
+ " 'show_nonphys': True,\n",
114
+ " 'occlusion_only_stems': [],\n",
115
+ " },\n",
116
+ " {\n",
117
+ " 'title': 'Thinking',\n",
118
+ " 'stems': ['gpt-5.4', 'claude-opus-4-6'],\n",
119
+ " 'base_dir': 'data/eval_results_thinking',\n",
120
+ " 'nudge_dir': 'data/eval_results_thinking_nudge',\n",
121
+ " 'occlusion_dir': 'data/eval_results_thinking_occlusion_nudge',\n",
122
+ " 'show_nonphys': True,\n",
123
+ " },\n",
124
+ " {\n",
125
+ " 'title': 'Tool Use',\n",
126
+ " 'stems': ['gpt-5.4', 'claude-opus-4-6'],\n",
127
+ " 'base_dir': 'data/eval_results_tool_use_thinking_v2',\n",
128
+ " 'nudge_dir': 'data/eval_results_tool_use_thinking_nudge',\n",
129
+ " 'occlusion_dir': 'data/eval_results_tool_use_thinking_occlusion_nudge',\n",
130
+ " 'show_nonphys': False, # filled from Thinking below\n",
131
+ " },\n",
132
+ "]\n",
133
+ "\n",
134
+ "# Known values not yet in judged results files\n",
135
+ "HARDCODED_NUDGE = {\n",
136
+ " ('Base', 'Qwen3-VL-8B-Instruct', 'nudge'): 25.7,\n",
137
+ "}\n",
138
+ "\n",
139
+ "results = {}\n",
140
+ "for exp in EXPERIMENTS:\n",
141
+ " rows = []\n",
142
+ " for stem in exp['stems']:\n",
143
+ " base_data = load_judged(exp['base_dir'], stem)\n",
144
+ " nudge_data = load_judged(exp['nudge_dir'], stem)\n",
145
+ " occ_data = load_judged(exp['occlusion_dir'], stem) if exp['occlusion_dir'] else None\n",
146
+ "\n",
147
+ " nudge_val = (HARDCODED_NUDGE.get((exp['title'], stem, 'nudge'))\n",
148
+ " or physical_accuracy(nudge_data))\n",
149
+ "\n",
150
+ " row = {\n",
151
+ " 'model': DISPLAY[stem],\n",
152
+ " 'base': physical_accuracy(base_data),\n",
153
+ " 'nudge': nudge_val,\n",
154
+ " 'occlusion': physical_accuracy(occ_data) if occ_data is not None else None,\n",
155
+ " 'nonphys': nonphysical_accuracy(base_data) if exp['show_nonphys'] else None,\n",
156
+ " }\n",
157
+ " rows.append(row)\n",
158
+ " line = (f\"[{exp['title']}] {DISPLAY[stem]:25s}\"\n",
159
+ " f\" base={row['base']:.1f}%\" if row['base'] else f\"[{exp['title']}] {DISPLAY[stem]:25s} base=N/A\")\n",
160
+ " if row['nudge'] is not None:\n",
161
+ " line += f\" steer(short)={row['nudge']:.1f}% delta={row['nudge']-row['base']:+.1f}pp\"\n",
162
+ " if row['occlusion'] is not None:\n",
163
+ " line += f\" steer(long)={row['occlusion']:.1f}% delta={row['occlusion']-row['base']:+.1f}pp\"\n",
164
+ " if row['nonphys'] is not None:\n",
165
+ " line += f\" non-phys={row['nonphys']:.1f}%\"\n",
166
+ " print(line)\n",
167
+ "\n",
168
+ " for stem in exp.get('occlusion_only_stems', []):\n",
169
+ " occ_data = load_judged(exp['occlusion_dir'], stem) if exp['occlusion_dir'] else None\n",
170
+ " row = {\n",
171
+ " 'model': DISPLAY[stem],\n",
172
+ " 'base': None,\n",
173
+ " 'nudge': None,\n",
174
+ " 'occlusion': physical_accuracy(occ_data) if occ_data else None,\n",
175
+ " 'nonphys': None,\n",
176
+ " }\n",
177
+ " rows.append(row)\n",
178
+ " line = f\"[{exp['title']}] {DISPLAY[stem]:25s} base=N/A steer(short)=N/A\"\n",
179
+ " if row['occlusion'] is not None:\n",
180
+ " line += f\" steer(long)={row['occlusion']:.1f}% delta=N/A\"\n",
181
+ " print(line)\n",
182
+ "\n",
183
+ " results[exp['title']] = rows\n",
184
+ " print()\n",
185
+ "# Tool Use has no non-physical items — borrow inferential from Thinking\n",
186
+ "thinking_nonphys = {r[\"model\"]: r[\"nonphys\"] for r in results[\"Thinking\"]}\n",
187
+ "for row in results[\"Tool Use\"]:\n",
188
+ " row[\"nonphys\"] = thinking_nonphys.get(row[\"model\"])\n",
189
+ " if row[\"nonphys\"] is not None:\n",
190
+ " print(f\"[Tool Use] {row['model']:<25} inferential (from Thinking) = {row['nonphys']:.1f}%\")"
191
+ ]
192
+ },
193
+ {
194
+ "cell_type": "code",
195
+ "execution_count": null,
196
+ "metadata": {
197
+ "execution": {
198
+ "iopub.execute_input": "2026-05-06T18:27:12.685130Z",
199
+ "iopub.status.busy": "2026-05-06T18:27:12.685056Z",
200
+ "iopub.status.idle": "2026-05-06T18:27:13.039634Z",
201
+ "shell.execute_reply": "2026-05-06T18:27:13.039343Z"
202
+ }
203
+ },
204
+ "outputs": [],
205
+ "source": [
206
+ "import matplotlib.patches as mpatches\n",
207
+ "import matplotlib.lines as mlines\n",
208
+ "\n",
209
+ "BASE_COLOR = '#4C72B0'\n",
210
+ "NUDGE_COLOR = '#55A868'\n",
211
+ "OCCLUSION_COLOR = '#8172B2'\n",
212
+ "NONPHYS_COLOR = '#DD8452'\n",
213
+ "\n",
214
+ "HUMAN_PHYS_SOLV = 93.9\n",
215
+ "HUMAN_INF_SOLV = 94.5\n",
216
+ "\n",
217
+ "def _nan(lst):\n",
218
+ " return [v if v is not None else float('nan') for v in lst]\n",
219
+ "\n",
220
+ "fig, axes = plt.subplots(1, 3, figsize=(37, 10),\n",
221
+ " gridspec_kw={'width_ratios': [1.5, 1, 1], 'wspace': 0.35})\n",
222
+ "\n",
223
+ "for ax, exp in zip(axes, EXPERIMENTS):\n",
224
+ " rows = results[exp['title']]\n",
225
+ " models = [r['model'] for r in rows]\n",
226
+ " base = _nan([r['base'] for r in rows])\n",
227
+ " nudge = _nan([r['nudge'] for r in rows])\n",
228
+ " occlusion = _nan([r['occlusion'] for r in rows])\n",
229
+ " nonphys = _nan([r['nonphys'] for r in rows])\n",
230
+ " x = np.arange(len(models))\n",
231
+ "\n",
232
+ " has_nonphys = any(not math.isnan(v) for v in nonphys)\n",
233
+ " has_occlusion = any(not math.isnan(v) for v in occlusion)\n",
234
+ "\n",
235
+ " bkw = dict(edgecolor='black', linewidth=0.8)\n",
236
+ "\n",
237
+ " if has_nonphys and has_occlusion:\n",
238
+ " w = 0.2\n",
239
+ " ax.bar(x - 1.5*w, base, w, label='Direct (base)', color=BASE_COLOR, **bkw)\n",
240
+ " ax.bar(x - 0.5*w, nudge, w, label='Direct (short steer)', color=NUDGE_COLOR, **bkw)\n",
241
+ " ax.bar(x + 0.5*w, occlusion, w, label='Direct (long steer)', color=OCCLUSION_COLOR, **bkw)\n",
242
+ " ax.bar(x + 1.5*w, nonphys, w, label='Inferential (base)', color=NONPHYS_COLOR, **bkw)\n",
243
+ " elif has_nonphys:\n",
244
+ " w = 0.25\n",
245
+ " ax.bar(x - w, base, w, label='Direct (base)', color=BASE_COLOR, **bkw)\n",
246
+ " ax.bar(x, nudge, w, label='Direct (short steer)', color=NUDGE_COLOR, **bkw)\n",
247
+ " ax.bar(x + w, nonphys, w, label='Inferential (base)', color=NONPHYS_COLOR, **bkw)\n",
248
+ " elif has_occlusion:\n",
249
+ " w = 0.25\n",
250
+ " ax.bar(x - w, base, w, label='Direct (base)', color=BASE_COLOR, **bkw)\n",
251
+ " ax.bar(x, nudge, w, label='Direct (short steer)', color=NUDGE_COLOR, **bkw)\n",
252
+ " ax.bar(x + w, occlusion, w, label='Direct (long steer)', color=OCCLUSION_COLOR, **bkw)\n",
253
+ " else:\n",
254
+ " w = 0.25\n",
255
+ " ax.bar(x - w/2, base, w, label='Direct (base)', color=BASE_COLOR, **bkw)\n",
256
+ " ax.bar(x + w/2, nudge, w, label='Direct (short steer)', color=NUDGE_COLOR, **bkw)\n",
257
+ "\n",
258
+ " x_label = len(models) - 1 + 0.45\n",
259
+ "\n",
260
+ " ax.axhline(HUMAN_PHYS_SOLV, color=BASE_COLOR, linestyle='-', linewidth=2.5)\n",
261
+ " ax.text(x_label, HUMAN_PHYS_SOLV - 4.5, f'{HUMAN_PHYS_SOLV}%',\n",
262
+ " color=BASE_COLOR, ha='right', va='top', fontsize=28, fontweight='bold')\n",
263
+ "\n",
264
+ " if has_nonphys:\n",
265
+ " ax.axhline(HUMAN_INF_SOLV, color=NONPHYS_COLOR, linestyle='-', linewidth=2.5)\n",
266
+ " ax.text(x_label, HUMAN_INF_SOLV + 4.5, f'{HUMAN_INF_SOLV}%',\n",
267
+ " color=NONPHYS_COLOR, ha='right', va='bottom', fontsize=28, fontweight='bold')\n",
268
+ "\n",
269
+ " ax.set_title(exp['title'], fontsize=34)\n",
270
+ " ax.set_xticks(x)\n",
271
+ " ax.set_xticklabels(models, rotation=0, ha='center', fontsize=34)\n",
272
+ " ax.set_ylim(0, 100)\n",
273
+ " ax.set_ylabel('Accuracy', fontsize=34)\n",
274
+ " ax.tick_params(axis='x', labelsize=34, pad=12)\n",
275
+ " ax.tick_params(axis='y', labelsize=34)\n",
276
+ " ax.yaxis.set_major_formatter(mtick.PercentFormatter())\n",
277
+ " ax.spines['top'].set_visible(False)\n",
278
+ " ax.spines['right'].set_visible(False)\n",
279
+ "\n",
280
+ "# --- Row 1: bar handles (deduplicated, Inferential last) ---\n",
281
+ "bar_handles, bar_labels = [], []\n",
282
+ "seen = set()\n",
283
+ "for ax in axes:\n",
284
+ " for h, l in zip(*ax.get_legend_handles_labels()):\n",
285
+ " if l not in seen:\n",
286
+ " bar_handles.append(h)\n",
287
+ " bar_labels.append(l)\n",
288
+ " seen.add(l)\n",
289
+ "if 'Inferential (base)' in bar_labels:\n",
290
+ " idx = bar_labels.index('Inferential (base)')\n",
291
+ " bar_labels.append(bar_labels.pop(idx))\n",
292
+ " bar_handles.append(bar_handles.pop(idx))\n",
293
+ "\n",
294
+ "# --- Row 2: line handles ---\n",
295
+ "line_handles = [\n",
296
+ " mlines.Line2D([], [], color=BASE_COLOR, linestyle='-', linewidth=2.5),\n",
297
+ " mlines.Line2D([], [], color=NONPHYS_COLOR, linestyle='-', linewidth=2.5),\n",
298
+ "]\n",
299
+ "line_labels = [\n",
300
+ " 'Human (direct)',\n",
301
+ " 'Human (inferential)',\n",
302
+ "]\n",
303
+ "\n",
304
+ "plt.subplots_adjust(bottom=0.35)\n",
305
+ "\n",
306
+ "leg1 = fig.legend(bar_handles, bar_labels,\n",
307
+ " loc='lower center', ncol=len(bar_handles),\n",
308
+ " bbox_to_anchor=(0.5, 0.08), frameon=False, fontsize=34,\n",
309
+ " columnspacing=1.2, handlelength=1.4, handletextpad=0.5)\n",
310
+ "fig.legend(line_handles, line_labels,\n",
311
+ " loc='lower center', ncol=len(line_handles),\n",
312
+ " bbox_to_anchor=(0.5, -0.02), frameon=False, fontsize=34,\n",
313
+ " columnspacing=1.2, handlelength=1.4, handletextpad=0.5)\n",
314
+ "fig.add_artist(leg1)\n",
315
+ "\n",
316
+ "plt.savefig('data/figures/nudge_comparison_base_vs_nudge_physical_occlusion_accuracy_combined.pdf', bbox_inches='tight')\n",
317
+ "plt.show()"
318
+ ]
319
+ }
320
+ ],
321
+ "metadata": {
322
+ "kernelspec": {
323
+ "display_name": "cos429",
324
+ "language": "python",
325
+ "name": "python3"
326
+ },
327
+ "language_info": {
328
+ "codemirror_mode": {
329
+ "name": "ipython",
330
+ "version": 3
331
+ },
332
+ "file_extension": ".py",
333
+ "mimetype": "text/x-python",
334
+ "name": "python",
335
+ "nbconvert_exporter": "python",
336
+ "pygments_lexer": "ipython3",
337
+ "version": "3.8.18"
338
+ }
339
+ },
340
+ "nbformat": 4,
341
+ "nbformat_minor": 4
342
+ }
code/sec4_1_main_results/run_all_evals.sh ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Run from the repo root (data and result paths are root-relative)
3
+ cd "$(dirname "$0")/.."
4
+
5
+ # ===== MODEL FAMILIES =====
6
+ openai_models=("gpt-5.4")
7
+ claude_models=("claude-opus-4-6")
8
+ gemini_models=("gemini-3.1-pro-preview")
9
+ llama_models=("meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8")
10
+ qwen_models=("Qwen/Qwen3-VL-8B-Instruct")
11
+
12
+ # ===== TASK FUNCTIONS (per single model) =====
13
+ run_model() {
14
+ local model="$1"
15
+ echo "Running: $model"
16
+ python -u sec3_occludebench/eval_script.py --model "$model"
17
+ }
18
+
19
+ run_model_transparent() {
20
+ local model="$1"
21
+ echo "Running transparent: $model"
22
+ python -u sec4_1_main_results/localization_unmasked/eval_transparent.py --model "$model"
23
+ }
24
+
25
+ run_all_tasks_for_model() {
26
+ local model="$1"
27
+ run_model "$model"
28
+ run_model_transparent "$model"
29
+ }
30
+
31
+ # ===== EXECUTION HELPERS =====
32
+ run_family_serially() {
33
+ local models=("$@")
34
+ for model in "${models[@]}"; do
35
+ run_all_tasks_for_model "$model"
36
+ done
37
+ }
38
+
39
+ # ===== PARALLEL EXECUTION: One process per family =====
40
+ (run_family_serially "${openai_models[@]}") &
41
+ (run_family_serially "${claude_models[@]}") &
42
+ (run_family_serially "${gemini_models[@]}") &
43
+ (run_family_serially "${llama_models[@]}") &
44
+ (run_family_serially "${qwen_models[@]}") &
45
+
46
+ wait
47
+
48
+ echo "All evals complete."
code/sec4_2_why_vlms_fail/cue_removal/accuracy_breakdown_physical.ipynb ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Accuracy Breakdown — Physical Occluded Subset\n",
8
+ "\n",
9
+ "Overall accuracy for each model on the **physical occlusion** test.\n",
10
+ "\n",
11
+ "Results are shown under three scoring systems: **GPT-only**, **Claude-only**, and **Combined** (average of both judges)."
12
+ ]
13
+ },
14
+ {
15
+ "cell_type": "code",
16
+ "execution_count": null,
17
+ "metadata": {},
18
+ "outputs": [],
19
+ "source": [
20
+ "# Run from the repo root so the root-relative data paths below resolve\n",
21
+ "import os\n",
22
+ "from pathlib import Path\n",
23
+ "os.chdir(next(p for p in [Path.cwd(), *Path.cwd().parents] if (p / \"sec3_occludebench\").is_dir()))"
24
+ ]
25
+ },
26
+ {
27
+ "cell_type": "code",
28
+ "execution_count": null,
29
+ "metadata": {},
30
+ "outputs": [],
31
+ "source": [
32
+ "import json\n",
33
+ "import os\n",
34
+ "import pandas as pd\n",
35
+ "import matplotlib.pyplot as plt\n",
36
+ "import matplotlib.ticker as mtick\n",
37
+ "import numpy as np\n",
38
+ "\n",
39
+ "RESULTS_DIR = 'data/eval_results_physical'\n",
40
+ "ANNOTATIONS_PATH = 'data/combined_output/annotations.json'\n",
41
+ "\n",
42
+ "MODEL_STEMS = [\n",
43
+ " 'gpt-5.4',\n",
44
+ " 'claude-opus-4-6',\n",
45
+ " 'gemini-3.1-pro-preview',\n",
46
+ " 'Qwen3-VL-8B-Instruct',\n",
47
+ " 'Llama-4-Maverick-17B-128E-Instruct-FP8',\n",
48
+ "]\n",
49
+ "\n",
50
+ "DISPLAY_NAMES = {\n",
51
+ " 'gpt-5.4': 'GPT-5.4',\n",
52
+ " 'claude-opus-4-6': 'Claude Opus 4.6',\n",
53
+ " 'gemini-3.1-pro-preview': 'Gemini 3.1 Pro',\n",
54
+ " 'Qwen3-VL-8B-Instruct': 'Qwen3-VL 8B',\n",
55
+ " 'Llama-4-Maverick-17B-128E-Instruct-FP8': 'Llama-4 Maverick 17B',\n",
56
+ "}\n",
57
+ "\n",
58
+ "SCORING_SYSTEMS = {\n",
59
+ " 'GPT-only': ['gpt-5.4'],\n",
60
+ " 'Claude-only': ['claude-opus-4-6'],\n",
61
+ " 'Combined': ['gpt-5.4', 'claude-opus-4-6'],\n",
62
+ "}"
63
+ ]
64
+ },
65
+ {
66
+ "cell_type": "code",
67
+ "execution_count": null,
68
+ "metadata": {},
69
+ "outputs": [],
70
+ "source": [
71
+ "with open(ANNOTATIONS_PATH) as f:\n",
72
+ " annotations = json.load(f)\n",
73
+ "\n",
74
+ "physical_map = {str(item['id']): item['physical'] for item in annotations}\n",
75
+ "print(f'Loaded {len(physical_map)} annotations')"
76
+ ]
77
+ },
78
+ {
79
+ "cell_type": "code",
80
+ "execution_count": null,
81
+ "metadata": {},
82
+ "outputs": [],
83
+ "source": [
84
+ "def compute_accuracy(judged_data, verdict_key, judge_models):\n",
85
+ " correct = total = 0\n",
86
+ " for item in judged_data:\n",
87
+ " verdict_dict = item.get(verdict_key, {})\n",
88
+ " if not isinstance(verdict_dict, dict):\n",
89
+ " continue\n",
90
+ " scores = [verdict_dict[jm] for jm in judge_models\n",
91
+ " if jm in verdict_dict and verdict_dict[jm] is not None]\n",
92
+ " if not scores:\n",
93
+ " continue\n",
94
+ " correct += sum(scores) / len(scores)\n",
95
+ " total += 1\n",
96
+ " return correct / total * 100 if total > 0 else None\n",
97
+ "\n",
98
+ "\n",
99
+ "judged_cache = {}\n",
100
+ "for stem in MODEL_STEMS:\n",
101
+ " path = os.path.join(RESULTS_DIR, f'{stem}_judged_results.json')\n",
102
+ " if os.path.exists(path):\n",
103
+ " with open(path) as f:\n",
104
+ " judged_cache[stem] = json.load(f)\n",
105
+ " else:\n",
106
+ " print(f'Missing: {path}')\n",
107
+ "\n",
108
+ "rows_by_scoring = {}\n",
109
+ "for scoring_name, judge_models in SCORING_SYSTEMS.items():\n",
110
+ " rows = []\n",
111
+ " for stem in MODEL_STEMS:\n",
112
+ " if stem not in judged_cache:\n",
113
+ " continue\n",
114
+ " acc = compute_accuracy(judged_cache[stem], 'occluded_correct', judge_models)\n",
115
+ " rows.append({'model': DISPLAY_NAMES[stem], 'accuracy': acc})\n",
116
+ " rows_by_scoring[scoring_name] = pd.DataFrame(rows).set_index('model')\n",
117
+ "\n",
118
+ "print('Done.')"
119
+ ]
120
+ },
121
+ {
122
+ "cell_type": "markdown",
123
+ "metadata": {},
124
+ "source": [
125
+ "---\n",
126
+ "## Summary Table"
127
+ ]
128
+ },
129
+ {
130
+ "cell_type": "code",
131
+ "execution_count": null,
132
+ "metadata": {},
133
+ "outputs": [],
134
+ "source": [
135
+ "summary = pd.concat(\n",
136
+ " [df.rename(columns={'accuracy': name}) for name, df in rows_by_scoring.items()],\n",
137
+ " axis=1\n",
138
+ ")\n",
139
+ "display(summary.applymap(lambda x: f'{x:.1f}%' if x is not None else 'N/A'))"
140
+ ]
141
+ },
142
+ {
143
+ "cell_type": "markdown",
144
+ "metadata": {},
145
+ "source": [
146
+ "---\n",
147
+ "## Accuracy Bar Chart"
148
+ ]
149
+ },
150
+ {
151
+ "cell_type": "code",
152
+ "execution_count": null,
153
+ "metadata": {},
154
+ "outputs": [],
155
+ "source": [
156
+ "models = [DISPLAY_NAMES[s] for s in MODEL_STEMS if s in judged_cache]\n",
157
+ "x = np.arange(len(models))\n",
158
+ "width = 0.25\n",
159
+ "colors = ['#4C72B0', '#DD8452', '#55A868']\n",
160
+ "\n",
161
+ "fig, ax = plt.subplots(figsize=(10, 5))\n",
162
+ "\n",
163
+ "for i, (scoring_name, df) in enumerate(rows_by_scoring.items()):\n",
164
+ " vals = [df.loc[m, 'accuracy'] if m in df.index else 0 for m in models]\n",
165
+ " bars = ax.bar(x + (i - 1) * width, vals, width, label=scoring_name, color=colors[i])\n",
166
+ " for bar, v in zip(bars, vals):\n",
167
+ " if v is not None:\n",
168
+ " ax.annotate(f'{v:.1f}',\n",
169
+ " xy=(bar.get_x() + bar.get_width() / 2, v),\n",
170
+ " xytext=(0, 2), textcoords='offset points',\n",
171
+ " ha='center', va='bottom', fontsize=7.5)\n",
172
+ "\n",
173
+ "ax.set_title('Physical Occlusion Accuracy by Model & Scoring System',\n",
174
+ " fontsize=13, fontweight='bold')\n",
175
+ "ax.set_xticks(x)\n",
176
+ "ax.set_xticklabels(models, rotation=15, ha='right', fontsize=9)\n",
177
+ "ax.set_ylim(0, 105)\n",
178
+ "ax.yaxis.set_major_formatter(mtick.PercentFormatter())\n",
179
+ "ax.set_ylabel('Accuracy (%)')\n",
180
+ "ax.legend(fontsize=9)\n",
181
+ "ax.grid(axis='y', alpha=0.3)\n",
182
+ "ax.spines['top'].set_visible(False)\n",
183
+ "ax.spines['right'].set_visible(False)\n",
184
+ "plt.tight_layout()\n",
185
+ "plt.show()"
186
+ ]
187
+ },
188
+ {
189
+ "cell_type": "code",
190
+ "execution_count": null,
191
+ "metadata": {},
192
+ "outputs": [],
193
+ "source": [
194
+ "summary_or = pd.concat(\n",
195
+ " [df.rename(columns={'accuracy': name}) for name, df in rows_by_scoring.items()],\n",
196
+ " axis=1\n",
197
+ ")\n",
198
+ "summary_or['Combined'] = summary_or[['GPT-only', 'Claude-only']].max(axis=1)\n",
199
+ "display(summary_or[['GPT-only', 'Claude-only', 'Combined']].applymap(lambda x: f'{x:.1f}%' if x is not None else 'N/A'))"
200
+ ]
201
+ }
202
+ ],
203
+ "metadata": {
204
+ "kernelspec": {
205
+ "display_name": "cos429",
206
+ "language": "python",
207
+ "name": "python3"
208
+ },
209
+ "language_info": {
210
+ "codemirror_mode": {
211
+ "name": "ipython",
212
+ "version": 3
213
+ },
214
+ "file_extension": ".py",
215
+ "mimetype": "text/x-python",
216
+ "name": "python",
217
+ "nbconvert_exporter": "python",
218
+ "pygments_lexer": "ipython3",
219
+ "version": "3.8.18"
220
+ }
221
+ },
222
+ "nbformat": 4,
223
+ "nbformat_minor": 4
224
+ }
code/sec4_2_why_vlms_fail/cue_removal/run_cue_removed_eval.sh ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Cue removal: the base occluded query on direct images whose shadow/reflection
3
+ # was removed in Photoshop (data/physical_occluded_combined/), all five models.
4
+ set -e
5
+ # Run from the repo root (data and result paths are root-relative)
6
+ cd "$(dirname "$0")/../.."
7
+
8
+ DATA_DIR="data/physical_occluded_combined"
9
+ OUT_DIR="data/eval_results_physical"
10
+
11
+ models=(
12
+ "gpt-5.4"
13
+ "claude-opus-4-6"
14
+ "gemini-3.1-pro-preview"
15
+ "meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8"
16
+ "Qwen/Qwen3-VL-8B-Instruct"
17
+ )
18
+
19
+ for m in "${models[@]}"; do
20
+ (python -u sec3_occludebench/eval_script.py --model "$m" --data_dir "$DATA_DIR" --output_dir "$OUT_DIR") &
21
+ done
22
+ wait
23
+
24
+ python -u sec3_occludebench/judger_script.py \
25
+ --results_dir "$OUT_DIR" \
26
+ --output_dir "$OUT_DIR" \
27
+ --judge_models gpt-5.4 claude-opus-4-6
code/sec4_2_why_vlms_fail/seeing_failure/eval_wrong_transparent.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ For each model in data/eval_results/, find images where both judges marked occluded as wrong,
3
+ filter to only images in the annotated/ folder, then have THAT SAME MODEL describe the
4
+ transparent image comprehensively.
5
+ """
6
+
7
+ import argparse
8
+ import base64
9
+ import io
10
+ import json
11
+ import os
12
+ from pathlib import Path
13
+
14
+ from openai import OpenAI
15
+ from together import Together
16
+ import anthropic
17
+ from dotenv import load_dotenv
18
+ from PIL import Image
19
+
20
+ load_dotenv()
21
+ OpenAI_API_KEY = os.getenv("OpenAI_API_KEY")
22
+ Anthropic_API_KEY = os.getenv("Anthropic_API_KEY")
23
+ Gemini_API_KEY = os.getenv("Gemini_API_KEY")
24
+ Together_API_KEY = os.getenv("Together_API_KEY")
25
+
26
+ PROMPT = (
27
+ "This image contains a thick-bordered transparent bounding box (the border may be yellow, red, or green) "
28
+ "highlighting a region of the scene. Provide a comprehensive, detailed description of the entire scene: "
29
+ "describe every object, person, animal, text, surface, background, lighting, colors, textures, "
30
+ "spatial relationships, and any other visual details you can observe. Be exhaustive and precise."
31
+ )
32
+
33
+ EVAL_MODELS = [
34
+ "claude-opus-4-6",
35
+ "gemini-3.1-pro-preview",
36
+ "gpt-5.4",
37
+ "Llama-4-Maverick-17B-128E-Instruct-FP8",
38
+ "Qwen3-VL-8B-Instruct",
39
+ ]
40
+
41
+ # Map from file stem (used in result filenames) to actual API model name
42
+ MODEL_API_NAME = {
43
+ "Qwen3-VL-8B-Instruct": "Qwen/Qwen3-VL-8B-Instruct",
44
+ "Llama-4-Maverick-17B-128E-Instruct-FP8": "meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8",
45
+ }
46
+
47
+
48
+ def init_client(model):
49
+ if "gpt" in model or model[0] == 'o':
50
+ return OpenAI(api_key=OpenAI_API_KEY)
51
+ elif "gemini" in model:
52
+ return OpenAI(api_key=Gemini_API_KEY, base_url="https://generativelanguage.googleapis.com/v1beta/openai/")
53
+ elif "claude" in model:
54
+ return anthropic.Anthropic(api_key=Anthropic_API_KEY)
55
+ else:
56
+ return Together(api_key=Together_API_KEY)
57
+
58
+
59
+ def encode_image(image_path, max_bytes=3.5 * 1024 * 1024):
60
+ with open(image_path, "rb") as f:
61
+ data = f.read()
62
+ if len(data) <= max_bytes:
63
+ return base64.b64encode(data).decode("utf-8")
64
+ img = Image.open(io.BytesIO(data))
65
+ scale = 0.9
66
+ while True:
67
+ buf = io.BytesIO()
68
+ img.save(buf, format="PNG", optimize=True)
69
+ if buf.tell() <= max_bytes:
70
+ break
71
+ w, h = img.size
72
+ img = img.resize((int(w * scale), int(h * scale)), Image.LANCZOS)
73
+ return base64.b64encode(buf.getvalue()).decode("utf-8")
74
+
75
+
76
+ PIL_TO_MEDIA_TYPE = {
77
+ "PNG": "image/png",
78
+ "JPEG": "image/jpeg",
79
+ "WEBP": "image/webp",
80
+ }
81
+
82
+ def detect_media_type(image_path):
83
+ with Image.open(image_path) as img:
84
+ return PIL_TO_MEDIA_TYPE.get(img.format, "image/png")
85
+
86
+ def query_model(model, client, image_path):
87
+ b64 = encode_image(image_path)
88
+ media_type = detect_media_type(image_path)
89
+
90
+ if "claude" in model:
91
+ return client.messages.create(
92
+ model=model,
93
+ max_tokens=1024,
94
+ temperature=0,
95
+ messages=[{
96
+ "role": "user",
97
+ "content": [
98
+ {"type": "image", "source": {"type": "base64", "media_type": media_type, "data": b64}},
99
+ {"type": "text", "text": PROMPT}
100
+ ]
101
+ }]
102
+ ).content[0].text
103
+ else:
104
+ return client.chat.completions.create(
105
+ model=model,
106
+ temperature=0,
107
+ messages=[{
108
+ "role": "user",
109
+ "content": [
110
+ {"type": "image_url", "image_url": {"url": f"data:{media_type};base64,{b64}"}},
111
+ {"type": "text", "text": PROMPT}
112
+ ]
113
+ }]
114
+ ).choices[0].message.content
115
+
116
+
117
+ def get_wrong_annotated_entries(judged_path, annotated_stems):
118
+ """Return entries where all judges said wrong AND image is in annotated/."""
119
+ with open(judged_path) as f:
120
+ data = json.load(f)
121
+ return [
122
+ e for e in data
123
+ if all(v is False for v in e["occluded_correct"].values())
124
+ and e["id"] in annotated_stems
125
+ ]
126
+
127
+
128
+ def run(args):
129
+ # Map stem -> full path for every image in annotated/
130
+ annotated_map = {
131
+ Path(f).stem: os.path.join(args.annotated_dir, f)
132
+ for f in os.listdir(args.annotated_dir)
133
+ if not f.endswith(".json")
134
+ }
135
+ annotated_stems = set(annotated_map.keys())
136
+ print(f"Annotated images: {len(annotated_stems)}")
137
+
138
+ os.makedirs(args.output_dir, exist_ok=True)
139
+
140
+ models = [args.model] if args.model else EVAL_MODELS
141
+ for model in models:
142
+ judged_path = os.path.join(args.eval_results_dir, f"{model}_judged_results.json")
143
+ if not os.path.exists(judged_path):
144
+ print(f"[SKIP] No judged results for {model}")
145
+ continue
146
+
147
+ output_path = os.path.join(args.output_dir, f"{model}_wrong_transparent.json")
148
+
149
+ if os.path.exists(output_path):
150
+ with open(output_path) as f:
151
+ results = json.load(f)
152
+ done_ids = {r["id"] for r in results}
153
+ else:
154
+ results = []
155
+ done_ids = set()
156
+
157
+ wrong_entries = get_wrong_annotated_entries(judged_path, annotated_stems)
158
+ remaining = [e for e in wrong_entries if e["id"] not in done_ids]
159
+ print(f"\n[{model}] Wrong & annotated: {len(wrong_entries)} | Done: {len(done_ids)} | Remaining: {len(remaining)}")
160
+
161
+ if not remaining:
162
+ continue
163
+
164
+ api_model = MODEL_API_NAME.get(model, model)
165
+ client = init_client(api_model)
166
+
167
+ for entry in remaining:
168
+ image_path = annotated_map.get(entry["id"])
169
+ if not image_path:
170
+ print(f" [SKIP] No annotated image for id={entry['id']}")
171
+ continue
172
+
173
+ print(f" id={entry['id']} gt={entry['ground_truth']!r} ...", end=" ", flush=True)
174
+ try:
175
+ response = query_model(api_model, client, image_path)
176
+ print("OK")
177
+ except Exception as e:
178
+ print(f"ERROR: {e}")
179
+ continue
180
+
181
+ results.append({
182
+ "id": entry["id"],
183
+ "ground_truth": entry["ground_truth"],
184
+ "transparent_description": response,
185
+ "occluded_correct": entry["occluded_correct"],
186
+ "occluded_response": entry.get("occluded_response"),
187
+ })
188
+
189
+ with open(output_path, "w") as f:
190
+ json.dump(results, f, indent=2)
191
+
192
+ print(f" Saved {len(results)} results -> {output_path}")
193
+
194
+
195
+ def parse_args():
196
+ parser = argparse.ArgumentParser()
197
+ parser.add_argument("--model", default=None, help="Run a single model (default: all)")
198
+ parser.add_argument("--annotated_dir", default="data/annotated")
199
+ parser.add_argument("--eval_results_dir", default="data/eval_results")
200
+ parser.add_argument("--output_dir", default="data/eval_results_wrong_transparent")
201
+ return parser.parse_args()
202
+
203
+
204
+ if __name__ == "__main__":
205
+ args = parse_args()
206
+ run(args)
code/sec4_2_why_vlms_fail/seeing_failure/judge_wrong_transparent.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ For each model's wrong_transparent results, judge whether the ground truth object
3
+ is mentioned/present in the model's scene description.
4
+ """
5
+
6
+ import argparse
7
+ import json
8
+ import os
9
+
10
+ from openai import OpenAI
11
+ from dotenv import load_dotenv
12
+
13
+ load_dotenv()
14
+ OpenAI_API_KEY = os.getenv("OpenAI_API_KEY")
15
+
16
+ JUDGE_PROMPT = (
17
+ "A vision model was given an image and produced the following scene description:\n\n"
18
+ "\"{description}\"\n\n"
19
+ "The ground truth answer for the highlighted object in that image is: \"{ground_truth}\"\n\n"
20
+ "Is the ground truth object mentioned or present as an object in the model's description? "
21
+ "Answer only 'yes' or 'no'."
22
+ )
23
+
24
+ EVAL_MODELS = [
25
+ "claude-opus-4-6",
26
+ "gemini-3.1-pro-preview",
27
+ "gpt-5.4",
28
+ "Llama-4-Maverick-17B-128E-Instruct-FP8",
29
+ "Qwen3-VL-8B-Instruct",
30
+ ]
31
+
32
+
33
+ def judge(description, ground_truth, judge_model, client):
34
+ prompt = JUDGE_PROMPT.format(description=description, ground_truth=ground_truth)
35
+ verdict = client.chat.completions.create(
36
+ model=judge_model,
37
+ temperature=0,
38
+ messages=[{"role": "user", "content": prompt}]
39
+ ).choices[0].message.content.strip().lower()
40
+ return verdict.startswith("yes")
41
+
42
+
43
+ def run(args):
44
+ client = OpenAI(api_key=OpenAI_API_KEY)
45
+ os.makedirs(args.output_dir, exist_ok=True)
46
+
47
+ models = [args.model] if args.model else EVAL_MODELS
48
+
49
+ for model in models:
50
+ input_path = os.path.join(args.input_dir, f"{model}_wrong_transparent.json")
51
+ if not os.path.exists(input_path):
52
+ print(f"[SKIP] No results for {model}")
53
+ continue
54
+
55
+ output_path = os.path.join(args.output_dir, f"{model}_wrong_transparent_judged.json")
56
+
57
+ if os.path.exists(output_path):
58
+ with open(output_path) as f:
59
+ results = json.load(f)
60
+ done_ids = {r["id"] for r in results}
61
+ else:
62
+ results = []
63
+ done_ids = set()
64
+
65
+ with open(input_path) as f:
66
+ entries = json.load(f)
67
+
68
+ remaining = [e for e in entries if e["id"] not in done_ids]
69
+ print(f"\n[{model}] Total: {len(entries)} | Done: {len(done_ids)} | Remaining: {len(remaining)}")
70
+
71
+ for entry in remaining:
72
+ print(f" id={entry['id']} gt={entry['ground_truth']!r} ...", end=" ", flush=True)
73
+ try:
74
+ mentioned = judge(
75
+ entry["transparent_description"],
76
+ entry["ground_truth"],
77
+ args.judge_model,
78
+ client
79
+ )
80
+ print("yes" if mentioned else "no")
81
+ except Exception as e:
82
+ print(f"ERROR: {e}")
83
+ continue
84
+
85
+ results.append({
86
+ "id": entry["id"],
87
+ "ground_truth": entry["ground_truth"],
88
+ "ground_truth_mentioned": mentioned,
89
+ "transparent_description": entry["transparent_description"],
90
+ "occluded_response": entry.get("occluded_response"),
91
+ })
92
+
93
+ with open(output_path, "w") as f:
94
+ json.dump(results, f, indent=2)
95
+
96
+ # Summary
97
+ if results:
98
+ n_mentioned = sum(1 for r in results if r["ground_truth_mentioned"])
99
+ print(f" Ground truth mentioned: {n_mentioned}/{len(results)} ({100*n_mentioned/len(results):.1f}%)")
100
+ print(f" Saved -> {output_path}")
101
+
102
+
103
+ def parse_args():
104
+ parser = argparse.ArgumentParser()
105
+ parser.add_argument("--model", default=None, help="Run a single model (default: all)")
106
+ parser.add_argument("--input_dir", default="data/eval_results_wrong_transparent")
107
+ parser.add_argument("--output_dir", default="data/eval_results_wrong_transparent")
108
+ parser.add_argument("--judge_model", default="gpt-5.4")
109
+ return parser.parse_args()
110
+
111
+
112
+ if __name__ == "__main__":
113
+ args = parse_args()
114
+ run(args)
code/sec4_2_why_vlms_fail/stage1_cue_detection/eval_reflection_shadow.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reflection/shadow presence on the PHYSICAL occluded images.
3
+
4
+ Asks each model a single yes/no-style question about every physical=True entry
5
+ in annotations.json, using the occluded PNG from data/combined_output/.
6
+
7
+ Prompt (verbatim, as requested):
8
+ "Is there the presence of a reflection or a shadow in this image?"
9
+
10
+ Models run: gpt-5.4, claude-opus-4-6, gemini-3.1-pro-preview, Qwen3-VL-8B.
11
+ (Llama-4-Maverick intentionally excluded for now.)
12
+
13
+ Results are written next to this script as <model>_reflection_shadow_results.json.
14
+ Adapted from sec3_occludebench/eval_script.py (client init + image encoding + chat_completion).
15
+ """
16
+ import argparse
17
+ import base64
18
+ import io
19
+ import json
20
+ import os
21
+
22
+ from openai import OpenAI
23
+ from together import Together
24
+ import anthropic
25
+ from dotenv import load_dotenv
26
+ from PIL import Image
27
+
28
+ HERE = os.path.dirname(os.path.abspath(__file__))
29
+ ROOT = os.path.abspath(os.path.join(HERE, "..", ".."))
30
+ load_dotenv(os.path.join(ROOT, ".env"))
31
+ OpenAI_API_KEY = os.getenv("OpenAI_API_KEY")
32
+ Anthropic_API_KEY = os.getenv("Anthropic_API_KEY")
33
+ Gemini_API_KEY = os.getenv("Gemini_API_KEY")
34
+ Together_API_KEY = os.getenv("Together_API_KEY")
35
+
36
+ PROMPT = "Is there the presence of a reflection or a shadow in this image?"
37
+
38
+
39
+ def init_client(model):
40
+ if "gpt" in model or model[0] == "o":
41
+ return OpenAI(api_key=OpenAI_API_KEY)
42
+ elif "gemini" in model:
43
+ return OpenAI(
44
+ api_key=Gemini_API_KEY,
45
+ base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
46
+ )
47
+ elif "claude" in model:
48
+ return anthropic.Anthropic(api_key=Anthropic_API_KEY)
49
+ else:
50
+ return Together(api_key=Together_API_KEY)
51
+
52
+
53
+ def encode_image(image_path, max_bytes=3.5 * 1024 * 1024):
54
+ with open(image_path, "rb") as f:
55
+ data = f.read()
56
+ if len(data) <= max_bytes:
57
+ return base64.b64encode(data).decode("utf-8")
58
+ img = Image.open(io.BytesIO(data))
59
+ scale = 0.9
60
+ while True:
61
+ buf = io.BytesIO()
62
+ img.save(buf, format="PNG", optimize=True)
63
+ if buf.tell() <= max_bytes:
64
+ break
65
+ w, h = img.size
66
+ img = img.resize((int(w * scale), int(h * scale)), Image.LANCZOS)
67
+ return base64.b64encode(buf.getvalue()).decode("utf-8")
68
+
69
+
70
+ def chat_completion(model, client, image_path, prompt=PROMPT):
71
+ b64 = encode_image(image_path)
72
+ media_type = "image/png"
73
+
74
+ if "claude" in model:
75
+ return client.messages.create(
76
+ model=model,
77
+ max_tokens=500,
78
+ temperature=0,
79
+ messages=[{
80
+ "role": "user",
81
+ "content": [
82
+ {"type": "image", "source": {"type": "base64", "media_type": media_type, "data": b64}},
83
+ {"type": "text", "text": prompt},
84
+ ],
85
+ }],
86
+ ).content[0].text
87
+ else:
88
+ return client.chat.completions.create(
89
+ model=model,
90
+ temperature=0,
91
+ messages=[{
92
+ "role": "user",
93
+ "content": [
94
+ {"type": "image_url", "image_url": {"url": f"data:{media_type};base64,{b64}"}},
95
+ {"type": "text", "text": prompt},
96
+ ],
97
+ }],
98
+ ).choices[0].message.content
99
+
100
+
101
+ def select_ids(select, cat_file):
102
+ """Return the set of image ids (as str) to include, or None for 'all'."""
103
+ if select in ("inferential", "direct"):
104
+ import pandas as pd
105
+ x = pd.read_excel(cat_file)
106
+ ids = x[x["direct or inferential"] == select]["image id"]
107
+ return {str(i) for i in ids}
108
+ return None # physical/all handled via the physical flag
109
+
110
+
111
+ def run_eval(args, client):
112
+ with open(os.path.join(args.data_dir, "annotations.json")) as f:
113
+ entries = json.load(f)
114
+
115
+ if args.select == "physical":
116
+ entries = [e for e in entries if e.get("physical", False)]
117
+ tag = "reflection_shadow"
118
+ elif args.select == "all":
119
+ tag = "reflection_shadow_all"
120
+ else: # inferential or direct
121
+ keep = select_ids(args.select, args.cat_file)
122
+ entries = [e for e in entries if str(e["id"]) in keep]
123
+ tag = f"reflection_shadow_{args.select}"
124
+ print(f"Selection '{args.select}': {len(entries)} candidate entries")
125
+
126
+ model_name = args.model.split("/")[-1]
127
+ output_path = os.path.join(args.output_dir, f"{model_name}_{tag}_results.json")
128
+
129
+ # Resume support: skip ids already done.
130
+ if os.path.exists(output_path):
131
+ with open(output_path) as f:
132
+ results = json.load(f)
133
+ done_ids = {r["id"] for r in results}
134
+ print(f"Resuming: {len(done_ids)} already done, "
135
+ f"{len(entries) - len(done_ids)} remaining.")
136
+ else:
137
+ results = []
138
+ done_ids = set()
139
+
140
+ os.makedirs(args.output_dir, exist_ok=True)
141
+
142
+ for entry in entries:
143
+ if entry["id"] in done_ids:
144
+ continue
145
+
146
+ base = os.path.splitext(entry["original_file"])[0]
147
+ occluded_path = os.path.join(args.image_dir, f"{base}_occluded.png")
148
+ if not os.path.exists(occluded_path):
149
+ print(f" [skip] no occluded image for id={entry['id']} ({base})")
150
+ continue
151
+
152
+ print(f"Running {entry['id']} ({base})...")
153
+ response = chat_completion(args.model, client, occluded_path, prompt=PROMPT)
154
+ print(f" Response: {response}")
155
+
156
+ results.append({
157
+ "id": entry["id"],
158
+ "original_file": entry["original_file"],
159
+ "ground_truth": entry.get("answer", ""),
160
+ "prompt": PROMPT,
161
+ "response": response,
162
+ })
163
+
164
+ # Save after each entry so progress is never lost.
165
+ with open(output_path, "w") as f:
166
+ json.dump(results, f, indent=2)
167
+
168
+ return results, output_path
169
+
170
+
171
+ def parse_args():
172
+ parser = argparse.ArgumentParser()
173
+ parser.add_argument("--model", type=str, required=True)
174
+ parser.add_argument("--data_dir", type=str, default=os.path.join(ROOT, "data/combined_output"),
175
+ help="Directory containing annotations.json.")
176
+ parser.add_argument("--image_dir", type=str, default=os.path.join(ROOT, "data/combined_output"),
177
+ help="Directory containing the *_occluded.png images.")
178
+ parser.add_argument("--output_dir", type=str, default=HERE,
179
+ help="Where to write results (this folder).")
180
+ parser.add_argument("--select", type=str, default="physical",
181
+ choices=["physical", "inferential", "direct", "all"],
182
+ help="Which image subset to ask the reflection/shadow question about.")
183
+ parser.add_argument("--cat_file", type=str, default=os.path.join(ROOT, "data/Image categories (3).xlsx"),
184
+ help="Category spreadsheet for direct/inferential selection.")
185
+ return parser.parse_args()
186
+
187
+
188
+ def main(args):
189
+ client = init_client(args.model)
190
+ results, output_path = run_eval(args, client)
191
+ print(f"Done. {len(results)} results in {output_path}")
192
+
193
+
194
+ if __name__ == "__main__":
195
+ main(parse_args())
code/sec4_2_why_vlms_fail/stage1_cue_detection/run_reflection_shadow.sh ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Reflection/shadow-presence question on the physical occluded images.
3
+ # Runs one process per model family in parallel. Llama-4-Maverick excluded.
4
+ set -euo pipefail
5
+ cd "$(dirname "$0")"
6
+
7
+ openai_model="gpt-5.4"
8
+ claude_model="claude-opus-4-6"
9
+ gemini_model="gemini-3.1-pro-preview"
10
+ qwen_model="Qwen/Qwen3-VL-8B-Instruct"
11
+
12
+ run_one() { echo "Running: $1"; python -u eval_reflection_shadow.py --model "$1"; }
13
+
14
+ (run_one "$openai_model") &
15
+ (run_one "$claude_model") &
16
+ (run_one "$gemini_model") &
17
+ (run_one "$qwen_model") &
18
+
19
+ wait
20
+ echo "All reflection/shadow evals complete."
code/sec4_2_why_vlms_fail/stage1_cue_detection/run_reflection_shadow_inferential.sh ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Control: reflection/shadow-presence question on the INFERENTIAL images
3
+ # (both physical and non-physical). Expected answer is mostly "no" if these are
4
+ # truly solved by context rather than a direct reflection/shadow cue.
5
+ # 3 models (Qwen endpoint down, Llama excluded).
6
+ set -euo pipefail
7
+ cd "$(dirname "$0")"
8
+
9
+ for model in "gpt-5.4" "claude-opus-4-6" "gemini-3.1-pro-preview"; do
10
+ echo "Running (inferential): $model"
11
+ python -u eval_reflection_shadow.py --model "$model" --select inferential &
12
+ done
13
+ wait
14
+ echo "All inferential reflection/shadow evals complete."
code/sec4_2_why_vlms_fail/stage2_zoomed_recognition/app.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Cropper platform.
3
+
4
+ Browse the ORIGINAL (un-occluded) direct/physical images and manually crop the
5
+ reflection- or shadow-bearing region. Each crop is saved to disk. No LLM here —
6
+ run sec4_2_why_vlms_fail/stage2_zoomed_recognition/ask_crops.py separately over the saved crops when ready.
7
+
8
+ Run:
9
+ cd sec4_2_why_vlms_fail/stage2_zoomed_recognition
10
+ python app.py # then open http://127.0.0.1:5005
11
+ """
12
+ import base64
13
+ import io
14
+ import json
15
+ import os
16
+ import re
17
+
18
+ from flask import Flask, jsonify, request, send_file, render_template, abort
19
+ from PIL import Image
20
+
21
+ # ---- paths -----------------------------------------------------------------
22
+ HERE = os.path.dirname(os.path.abspath(__file__))
23
+ ROOT = os.path.abspath(os.path.join(HERE, "..", "..")) # project root
24
+ IMG_DIR = os.path.join(ROOT, "data/combined_output") # originals live here
25
+ CAT_FILE = os.path.join(ROOT, "data/Image categories (3).xlsx")
26
+ ANN_FILE = os.path.join(IMG_DIR, "annotations.json")
27
+ META = os.path.join(HERE, "crop_meta.json") # crop index
28
+ CROP_DIR = os.path.join(HERE, "crops")
29
+ os.makedirs(CROP_DIR, exist_ok=True)
30
+
31
+ app = Flask(__name__)
32
+
33
+
34
+ # ---- data: the direct/physical originals -----------------------------------
35
+ def load_items():
36
+ import pandas as pd
37
+ cat = pd.read_excel(CAT_FILE)[["image id", "direct or inferential"]]
38
+ cat["image id"] = cat["image id"].astype(str)
39
+ direct = set(cat[cat["direct or inferential"] == "direct"]["image id"])
40
+ ann = json.load(open(ANN_FILE))
41
+ items = []
42
+ for e in ann:
43
+ iid = str(e["id"])
44
+ if iid not in direct:
45
+ continue
46
+ of = e["original_file"]
47
+ if not os.path.exists(os.path.join(IMG_DIR, of)):
48
+ continue
49
+ items.append({
50
+ "id": iid,
51
+ "original_file": of,
52
+ "ground_truth": (e.get("answer") or "").strip(),
53
+ })
54
+ items.sort(key=lambda x: (len(x["id"]), x["id"]))
55
+ return items
56
+
57
+
58
+ ITEMS = load_items()
59
+ ITEM_BY_ID = {it["id"]: it for it in ITEMS}
60
+
61
+
62
+ # ---- crop metadata persistence ---------------------------------------------
63
+ def load_meta():
64
+ if os.path.exists(META):
65
+ return json.load(open(META))
66
+ return []
67
+
68
+
69
+ def save_meta(rows):
70
+ with open(META, "w") as f:
71
+ json.dump(rows, f, indent=2)
72
+
73
+
74
+ # ---- routes ----------------------------------------------------------------
75
+ @app.route("/")
76
+ def index():
77
+ return render_template("index.html", total=len(ITEMS))
78
+
79
+
80
+ @app.route("/api/items")
81
+ def api_items():
82
+ meta = load_meta()
83
+ counts = {}
84
+ for r in meta:
85
+ counts[r["id"]] = counts.get(r["id"], 0) + 1
86
+ return jsonify([{**it, "crops": counts.get(it["id"], 0)} for it in ITEMS])
87
+
88
+
89
+ @app.route("/img/<iid>")
90
+ def img(iid):
91
+ it = ITEM_BY_ID.get(iid)
92
+ if not it:
93
+ abort(404)
94
+ return send_file(os.path.join(IMG_DIR, it["original_file"]))
95
+
96
+
97
+ @app.route("/api/save", methods=["POST"])
98
+ def api_save():
99
+ data = request.get_json()
100
+ iid = str(data["id"])
101
+ it = ITEM_BY_ID.get(iid)
102
+ if not it:
103
+ return jsonify({"error": "unknown id"}), 400
104
+
105
+ m = re.match(r"data:image/\w+;base64,(.*)", data["crop"], re.DOTALL)
106
+ if not m:
107
+ return jsonify({"error": "bad crop payload"}), 400
108
+ png = base64.b64decode(m.group(1))
109
+ buf = io.BytesIO()
110
+ Image.open(io.BytesIO(png)).convert("RGB").save(buf, format="PNG")
111
+ png = buf.getvalue()
112
+
113
+ meta = load_meta()
114
+ k = sum(1 for r in meta if r["id"] == iid) + 1 # per-image crop index
115
+ crop_name = f"{iid}-{k}.png"
116
+ with open(os.path.join(CROP_DIR, crop_name), "wb") as f:
117
+ f.write(png)
118
+
119
+ meta.append({
120
+ "id": iid,
121
+ "ground_truth": it["ground_truth"],
122
+ "label": (data.get("label") or "").strip(), # optional: "shadow"/"reflection"
123
+ "crop_box": data.get("box"), # {x,y,w,h} native px
124
+ "crop_file": os.path.join("crops", crop_name),
125
+ "original_file": it["original_file"],
126
+ })
127
+ save_meta(meta)
128
+ return jsonify({"crop_file": crop_name, "crops_for_id": k, "total_saved": len(meta)})
129
+
130
+
131
+ @app.route("/api/delete_last", methods=["POST"])
132
+ def api_delete_last():
133
+ """Undo the most recent crop for a given image id."""
134
+ iid = str(request.get_json()["id"])
135
+ meta = load_meta()
136
+ for i in range(len(meta) - 1, -1, -1):
137
+ if meta[i]["id"] == iid:
138
+ path = os.path.join(HERE, meta[i]["crop_file"])
139
+ if os.path.exists(path):
140
+ os.remove(path)
141
+ meta.pop(i)
142
+ save_meta(meta)
143
+ return jsonify({"ok": True, "crops_for_id": sum(1 for r in meta if r["id"] == iid)})
144
+ return jsonify({"ok": False, "crops_for_id": 0})
145
+
146
+
147
+ if __name__ == "__main__":
148
+ print(f"Loaded {len(ITEMS)} direct/physical originals from {IMG_DIR}")
149
+ print("Open http://127.0.0.1:5005")
150
+ app.run(port=5005, debug=False)
code/sec4_2_why_vlms_fail/stage2_zoomed_recognition/ask_crops.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Mass eval over the manually-saved crops (run AFTER cropping in the web tool).
3
+
4
+ Reads sec4_2_why_vlms_fail/stage2_zoomed_recognition/crop_meta.json, sends each saved crop image to the given
5
+ model, and writes sec4_2_why_vlms_fail/stage2_zoomed_recognition/crop_eval_<model>_results.json.
6
+
7
+ Usage:
8
+ python ask_crops.py --model gpt-5.4
9
+ python ask_crops.py --model claude-opus-4-6
10
+ python ask_crops.py --model gemini-3.1-pro-preview
11
+ # or all three:
12
+ ./run_crop_eval.sh
13
+ """
14
+ import argparse
15
+ import base64
16
+ import io
17
+ import json
18
+ import os
19
+
20
+ from dotenv import load_dotenv
21
+ from PIL import Image
22
+ from openai import OpenAI
23
+ import anthropic
24
+
25
+ HERE = os.path.dirname(os.path.abspath(__file__))
26
+ ROOT = os.path.abspath(os.path.join(HERE, "..", ".."))
27
+ META = os.path.join(HERE, "crop_meta.json")
28
+
29
+ load_dotenv(os.path.join(ROOT, ".env"))
30
+ KEYS = {"openai": os.getenv("OpenAI_API_KEY"),
31
+ "anthropic": os.getenv("Anthropic_API_KEY"),
32
+ "gemini": os.getenv("Gemini_API_KEY")}
33
+
34
+ PROMPT = ("Depicted in this image is a shadow or reflection of another object. "
35
+ "What is the original object that it is a shadow or reflection of? "
36
+ "Be as specific as you can.")
37
+
38
+
39
+ def init_client(model):
40
+ if "gemini" in model:
41
+ return OpenAI(api_key=KEYS["gemini"],
42
+ base_url="https://generativelanguage.googleapis.com/v1beta/openai/")
43
+ if "claude" in model:
44
+ return anthropic.Anthropic(api_key=KEYS["anthropic"])
45
+ return OpenAI(api_key=KEYS["openai"])
46
+
47
+
48
+ def encode(path, max_bytes=3.5 * 1024 * 1024):
49
+ with open(path, "rb") as f:
50
+ data = f.read()
51
+ if len(data) <= max_bytes:
52
+ return base64.b64encode(data).decode("utf-8")
53
+ img = Image.open(io.BytesIO(data)); scale = 0.9
54
+ while True:
55
+ buf = io.BytesIO(); img.save(buf, format="PNG", optimize=True)
56
+ if buf.tell() <= max_bytes:
57
+ break
58
+ w, h = img.size; img = img.resize((int(w * scale), int(h * scale)), Image.LANCZOS)
59
+ return base64.b64encode(buf.getvalue()).decode("utf-8")
60
+
61
+
62
+ def ask(model, client, path, prompt):
63
+ b64 = encode(path)
64
+ if "claude" in model:
65
+ return client.messages.create(
66
+ model=model, max_tokens=500, temperature=0,
67
+ messages=[{"role": "user", "content": [
68
+ {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": b64}},
69
+ {"type": "text", "text": prompt}]}],
70
+ ).content[0].text
71
+ return client.chat.completions.create(
72
+ model=model, temperature=0,
73
+ messages=[{"role": "user", "content": [
74
+ {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64}"}},
75
+ {"type": "text", "text": prompt}]}],
76
+ ).choices[0].message.content
77
+
78
+
79
+ def main():
80
+ ap = argparse.ArgumentParser()
81
+ ap.add_argument("--model", required=True)
82
+ ap.add_argument("--prompt", default=PROMPT)
83
+ args = ap.parse_args()
84
+
85
+ meta = json.load(open(META))
86
+ model_name = args.model.split("/")[-1]
87
+ out_path = os.path.join(HERE, f"crop_eval_{model_name}_results.json")
88
+
89
+ if os.path.exists(out_path):
90
+ results = json.load(open(out_path))
91
+ done = {r["crop_file"] for r in results}
92
+ else:
93
+ results, done = [], set()
94
+
95
+ client = init_client(args.model)
96
+ for i, m in enumerate(meta):
97
+ if m["crop_file"] in done:
98
+ continue
99
+ path = os.path.join(HERE, m["crop_file"])
100
+ if not os.path.exists(path):
101
+ print(f" [skip] missing {m['crop_file']}")
102
+ continue
103
+ print(f"[{i+1}/{len(meta)}] {m['crop_file']} (gt={m['ground_truth']!r})")
104
+ resp = ask(args.model, client, path, args.prompt)
105
+ print(f" -> {resp[:100]}")
106
+ results.append({
107
+ "id": m["id"], "crop_file": m["crop_file"], "label": m.get("label", ""),
108
+ "ground_truth": m["ground_truth"], "crop_box": m.get("crop_box"),
109
+ "prompt": args.prompt, "response": resp,
110
+ })
111
+ with open(out_path, "w") as f:
112
+ json.dump(results, f, indent=2)
113
+
114
+ print(f"Done. {len(results)} results -> {out_path}")
115
+
116
+
117
+ if __name__ == "__main__":
118
+ main()
code/sec4_2_why_vlms_fail/stage2_zoomed_recognition/judge_crops.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Judge the crop-eval responses for correctness (OBJECT-ONLY criterion).
3
+
4
+ Because the crop prompt already tells the model the region is a shadow/reflection
5
+ and asks only for the underlying object, a response is correct if it names the
6
+ right underlying object (e.g. 'mountain' matches 'Reflection of a mountain') —
7
+ it need NOT restate that it is a shadow/reflection.
8
+
9
+ 2-judge consensus (gpt-5.4 + claude-opus-4-6), matching the physical baseline.
10
+ Writes crop_eval_<model>_judged_results.json and prints an accuracy summary.
11
+
12
+ Usage:
13
+ python judge_crops.py # judge all crop_eval_*_results.json
14
+ """
15
+ import glob
16
+ import json
17
+ import os
18
+
19
+ from dotenv import load_dotenv
20
+ from openai import OpenAI
21
+ import anthropic
22
+
23
+ HERE = os.path.dirname(os.path.abspath(__file__))
24
+ ROOT = os.path.abspath(os.path.join(HERE, "..", ".."))
25
+ load_dotenv(os.path.join(ROOT, ".env"))
26
+
27
+ CLIENTS = {
28
+ "openai": OpenAI(api_key=os.getenv("OpenAI_API_KEY")),
29
+ "anthropic": anthropic.Anthropic(api_key=os.getenv("Anthropic_API_KEY")),
30
+ }
31
+ JUDGES = ["gpt-5.4", "claude-opus-4-6"]
32
+
33
+ JUDGE_OBJECT_ONLY = (
34
+ "You are evaluating whether a vision model correctly identified an object.\n\n"
35
+ "The model was shown a cropped region that is a shadow or reflection of some object, "
36
+ "and was asked to name the underlying object.\n\n"
37
+ "Ground truth: \"{ground_truth}\"\n\n"
38
+ "Model response: \"{response}\"\n\n"
39
+ "Does the response correctly identify the same underlying object as the ground truth? "
40
+ "The ground truth may be phrased as 'reflection of a car' or 'car shadow'; the response "
41
+ "only needs to identify the underlying OBJECT (e.g. 'car') and does NOT need to state "
42
+ "that it is a shadow or reflection. Allow reasonable variation in phrasing, specificity, "
43
+ "or synonyms (e.g. 'wing mirror' matches 'side mirror'). "
44
+ "Answer only 'yes' or 'no'."
45
+ )
46
+
47
+
48
+ def judge_correct(ground_truth, response, judge_model):
49
+ prompt = JUDGE_OBJECT_ONLY.format(ground_truth=(ground_truth or "").strip(),
50
+ response=(response or "").strip())
51
+ if judge_model.startswith("claude"):
52
+ v = CLIENTS["anthropic"].messages.create(
53
+ model=judge_model, temperature=0, max_tokens=10,
54
+ messages=[{"role": "user", "content": prompt}]).content[0].text
55
+ else:
56
+ v = CLIENTS["openai"].chat.completions.create(
57
+ model=judge_model, temperature=0,
58
+ messages=[{"role": "user", "content": prompt}]).choices[0].message.content
59
+ return v.strip().lower().startswith("yes")
60
+
61
+
62
+ def judge_file(path):
63
+ results = json.load(open(path))
64
+ model = os.path.basename(path).replace("crop_eval_", "").replace("_results.json", "")
65
+ out = path.replace("_results.json", "_judged_results.json")
66
+ if os.path.exists(out):
67
+ judged = json.load(open(out))
68
+ by_key = {r["crop_file"]: r for r in judged}
69
+ else:
70
+ judged, by_key = [], {}
71
+
72
+ for r in results:
73
+ rec = by_key.get(r["crop_file"])
74
+ if rec is None:
75
+ rec = dict(r); rec["correct"] = {}
76
+ judged.append(rec); by_key[r["crop_file"]] = rec
77
+ rec.setdefault("correct", {})
78
+ for jm in JUDGES:
79
+ if jm in rec["correct"]:
80
+ continue
81
+ rec["correct"][jm] = judge_correct(r["ground_truth"], r["response"], jm)
82
+ votes = list(rec["correct"].values())
83
+ rec["consensus_correct"] = bool(votes) and all(votes)
84
+ with open(out, "w") as f:
85
+ json.dump(judged, f, indent=2)
86
+
87
+ n = len(judged)
88
+ corr = sum(1 for r in judged if r.get("consensus_correct"))
89
+ print(f"{model:26} crop accuracy (object-only, consensus): {corr}/{n} = {corr/n:.1%}")
90
+ return model, {r["id"]: r.get("consensus_correct") for r in judged}
91
+
92
+
93
+ if __name__ == "__main__":
94
+ files = sorted(glob.glob(os.path.join(HERE, "crop_eval_*_results.json")))
95
+ files = [f for f in files if "_judged_" not in f]
96
+ print(f"Judging {len(files)} crop-eval files with {JUDGES} (object-only)...\n")
97
+ per_model = {}
98
+ for f in files:
99
+ m, acc = judge_file(f)
100
+ per_model[m] = acc
101
+ print("\nDone. Per-model judged files written as crop_eval_<model>_judged_results.json")
code/sec4_2_why_vlms_fail/stage2_zoomed_recognition/run_crop_eval.sh ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Mass eval over the manually-saved crops, all 3 models (run AFTER cropping).
3
+ set -euo pipefail
4
+ cd "$(dirname "$0")"
5
+ for model in "gpt-5.4" "claude-opus-4-6" "gemini-3.1-pro-preview"; do
6
+ echo "=== crop eval: $model ==="
7
+ python -u ask_crops.py --model "$model" &
8
+ done
9
+ wait
10
+ echo "All crop evals complete."
code/sec4_2_why_vlms_fail/stage2_zoomed_recognition/run_judge_loop.sh ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Run the crop judger concurrently with the eval: keep judging (resumable) until
3
+ # every eval response has a consensus judgement. Tolerant of transient read
4
+ # errors caused by the eval writing its results file mid-judge.
5
+ cd "$(dirname "$0")"
6
+ for i in $(seq 1 60); do
7
+ python judge_crops.py 2>/dev/null || echo " (transient error, retrying)"
8
+ # done when each judged file count == its eval file count
9
+ remaining=$(python3 - <<'PY'
10
+ import json, glob, os
11
+ rem=0
12
+ for f in glob.glob('crop_eval_*_results.json'):
13
+ if '_judged_' in f: continue
14
+ jf=f.replace('_results.json','_judged_results.json')
15
+ n=len(json.load(open(f)))
16
+ j=len(json.load(open(jf))) if os.path.exists(jf) else 0
17
+ rem += max(0, n-j)
18
+ print(rem)
19
+ PY
20
+ )
21
+ echo "iteration $i: $remaining responses still unjudged"
22
+ [ "$remaining" = "0" ] && { echo "All judged."; break; }
23
+ sleep 15
24
+ done
code/sec4_2_why_vlms_fail/stage2_zoomed_recognition/templates/index.html ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>Cropper — direct/physical images</title>
7
+ <style>
8
+ :root { --bg:#0f1115; --panel:#171a21; --line:#2a2f3a; --fg:#e6e8ee; --mut:#9aa3b2;
9
+ --accent:#5b8cff; --ok:#31c48d; }
10
+ * { box-sizing:border-box; }
11
+ body { margin:0; font:14px/1.45 -apple-system,Segoe UI,Roboto,sans-serif;
12
+ background:var(--bg); color:var(--fg); height:100vh; display:flex; }
13
+ #sidebar { width:240px; border-right:1px solid var(--line); background:var(--panel);
14
+ display:flex; flex-direction:column; }
15
+ #sidebar h2 { margin:0; padding:12px 14px; font-size:13px; border-bottom:1px solid var(--line); }
16
+ #progress { padding:6px 14px; color:var(--mut); font-size:12px; border-bottom:1px solid var(--line); }
17
+ #list { overflow-y:auto; flex:1; }
18
+ .row { padding:7px 14px; cursor:pointer; border-bottom:1px solid #20242e;
19
+ display:flex; align-items:center; gap:8px; font-size:12px; }
20
+ .row:hover { background:#1e222b; }
21
+ .row.active { background:#243049; color:#fff; }
22
+ .row .gt { color:var(--mut); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; flex:1; }
23
+ .dot { width:8px; height:8px; border-radius:50%; background:#3a4150; flex:none; }
24
+ .dot.done { background:var(--ok); }
25
+ .cnt { color:var(--ok); font-size:11px; }
26
+ #main { flex:1; display:flex; flex-direction:column; min-width:0; }
27
+ #topbar { padding:10px 14px; border-bottom:1px solid var(--line); display:flex;
28
+ gap:10px; align-items:center; flex-wrap:wrap; background:var(--panel); }
29
+ #stage { flex:1; overflow:auto; display:flex; align-items:center; justify-content:center;
30
+ background:#0a0c10; position:relative; }
31
+ #wrap { position:relative; line-height:0; }
32
+ #img { max-width:none; user-select:none; -webkit-user-drag:none; }
33
+ #sel { position:absolute; border:2px dashed var(--accent); background:rgba(91,140,255,.15);
34
+ display:none; pointer-events:none; }
35
+ #panel { border-top:1px solid var(--line); background:var(--panel); padding:12px 14px;
36
+ display:flex; gap:16px; align-items:center; flex-wrap:wrap; }
37
+ select,input,button { font:inherit; color:var(--fg); background:#0f1218;
38
+ border:1px solid var(--line); border-radius:6px; padding:8px 11px; }
39
+ button { cursor:pointer; background:var(--accent); border-color:var(--accent); color:#fff; font-weight:600; }
40
+ button.secondary { background:#232833; border-color:var(--line); color:var(--fg); font-weight:500; }
41
+ button:disabled { opacity:.45; cursor:default; }
42
+ .kv { color:var(--mut); font-size:12px; }
43
+ .gtbox { background:#12331f; border:1px solid #1f5c38; color:#bff0d3; padding:6px 9px;
44
+ border-radius:6px; display:inline-block; }
45
+ .hint { color:var(--mut); font-size:12px; }
46
+ #zoom { width:120px; }
47
+ .thumb { border:1px solid var(--line); border-radius:6px; max-width:150px; max-height:96px; }
48
+ #toast { position:fixed; bottom:16px; left:50%; transform:translateX(-50%);
49
+ background:#1f5c38; color:#d6ffe8; padding:8px 16px; border-radius:8px;
50
+ opacity:0; transition:opacity .2s; pointer-events:none; font-size:13px; }
51
+ #toast.show { opacity:1; }
52
+ </style>
53
+ </head>
54
+ <body>
55
+ <div id="sidebar">
56
+ <h2>Direct / physical originals</h2>
57
+ <div id="progress">0 / {{ total }} cropped</div>
58
+ <div id="list"></div>
59
+ </div>
60
+
61
+ <div id="main">
62
+ <div id="topbar">
63
+ <button class="secondary" id="prev">◀ Prev</button>
64
+ <button class="secondary" id="next">Next ▶</button>
65
+ <span class="gtbox" id="idpill">—</span>
66
+ <label class="kv">Zoom <input type="range" id="zoom" min="0.2" max="3" step="0.05" value="1"></label>
67
+ <button class="secondary" id="clearsel">Clear box</button>
68
+ <button class="secondary" id="undo">Undo last crop</button>
69
+ <span class="hint">Drag on the image to box the reflection/shadow region, then Save crop.</span>
70
+ </div>
71
+
72
+ <div id="stage">
73
+ <div id="wrap">
74
+ <img id="img" alt="">
75
+ <div id="sel"></div>
76
+ </div>
77
+ </div>
78
+
79
+ <div id="panel">
80
+ <div>
81
+ <div class="kv">Ground truth</div>
82
+ <div><span class="gtbox" id="gt">—</span></div>
83
+ </div>
84
+ <label class="kv">Label (optional)
85
+ <input id="label" list="labels" placeholder="shadow / reflection" style="width:150px">
86
+ <datalist id="labels"><option>shadow</option><option>reflection</option></datalist>
87
+ </label>
88
+ <button id="save" disabled>Save crop ▸</button>
89
+ <span class="kv" id="cropinfo">no box</span>
90
+ <span class="kv" id="idcount"></span>
91
+ <img id="thumb" class="thumb" style="display:none">
92
+ </div>
93
+ </div>
94
+ <div id="toast"></div>
95
+
96
+ <script>
97
+ const $ = s => document.querySelector(s);
98
+ let items = [], idx = 0, box = null, natW = 0, natH = 0, scale = 1;
99
+
100
+ function toast(msg){ const t=$('#toast'); t.textContent=msg; t.classList.add('show');
101
+ clearTimeout(t._t); t._t=setTimeout(()=>t.classList.remove('show'),1200); }
102
+
103
+ async function loadItems() {
104
+ items = await (await fetch('/api/items')).json();
105
+ renderList(); select(0);
106
+ }
107
+ function doneCount(){ return items.filter(i=>i.crops>0).length; }
108
+ function renderList() {
109
+ const list = $('#list'); list.innerHTML = '';
110
+ items.forEach((it, i) => {
111
+ const row = document.createElement('div');
112
+ row.className = 'row' + (i===idx ? ' active':'');
113
+ row.innerHTML = `<span class="dot ${it.crops>0?'done':''}"></span>
114
+ <span>#${it.id}</span>
115
+ <span class="gt">${it.ground_truth||''}</span>
116
+ ${it.crops>0?`<span class="cnt">${it.crops}</span>`:''}`;
117
+ row.onclick = () => select(i);
118
+ list.appendChild(row);
119
+ });
120
+ $('#progress').textContent = `${doneCount()} / ${items.length} cropped`;
121
+ }
122
+ function select(i) {
123
+ idx = Math.max(0, Math.min(items.length-1, i));
124
+ const it = items[idx];
125
+ $('#idpill').textContent = `#${it.id}`;
126
+ $('#gt').textContent = it.ground_truth || '(none)';
127
+ updateCount();
128
+ clearSel();
129
+ const img = $('#img');
130
+ img.onload = () => { natW = img.naturalWidth; natH = img.naturalHeight; applyZoom(); };
131
+ img.src = '/img/' + it.id + '?t=' + Date.now();
132
+ renderList();
133
+ }
134
+ function updateCount(){ const n=items[idx].crops; $('#idcount').textContent = n>0?`(${n} saved for this image)`:''; }
135
+ function applyZoom() {
136
+ scale = parseFloat($('#zoom').value);
137
+ $('#img').style.width = (natW * scale) + 'px';
138
+ clearSel();
139
+ }
140
+ function clearSel(){ box=null; $('#sel').style.display='none'; $('#thumb').style.display='none';
141
+ $('#cropinfo').textContent='no box'; $('#save').disabled=true; }
142
+
143
+ // ---- drag to select ----
144
+ let dragging=false, sx=0, sy=0;
145
+ const wrap = $('#wrap'), sel = $('#sel');
146
+ wrap.addEventListener('mousedown', e => {
147
+ if (e.target.id!=='img' && e.target.id!=='sel') return;
148
+ dragging=true; const r=wrap.getBoundingClientRect(); sx=e.clientX-r.left; sy=e.clientY-r.top;
149
+ sel.style.display='block'; sel.style.left=sx+'px'; sel.style.top=sy+'px';
150
+ sel.style.width='0px'; sel.style.height='0px'; e.preventDefault();
151
+ });
152
+ window.addEventListener('mousemove', e => {
153
+ if(!dragging) return;
154
+ const r=wrap.getBoundingClientRect();
155
+ let cx=Math.max(0,Math.min(e.clientX-r.left, natW*scale));
156
+ let cy=Math.max(0,Math.min(e.clientY-r.top, natH*scale));
157
+ const x=Math.min(sx,cx), y=Math.min(sy,cy), w=Math.abs(cx-sx), h=Math.abs(cy-sy);
158
+ sel.style.left=x+'px'; sel.style.top=y+'px'; sel.style.width=w+'px'; sel.style.height=h+'px';
159
+ });
160
+ window.addEventListener('mouseup', () => {
161
+ if(!dragging) return; dragging=false;
162
+ const w=parseFloat(sel.style.width), h=parseFloat(sel.style.height);
163
+ if(w<5||h<5){ clearSel(); return; }
164
+ box = { x: Math.round(parseFloat(sel.style.left)/scale),
165
+ y: Math.round(parseFloat(sel.style.top)/scale),
166
+ w: Math.round(w/scale), h: Math.round(h/scale) };
167
+ makeThumb();
168
+ $('#cropinfo').textContent = `box ${box.w}×${box.h}px @(${box.x},${box.y})`;
169
+ $('#save').disabled=false;
170
+ });
171
+
172
+ function cropCanvas() {
173
+ const c=document.createElement('canvas'); c.width=box.w; c.height=box.h;
174
+ c.getContext('2d').drawImage($('#img'), box.x, box.y, box.w, box.h, 0,0, box.w, box.h);
175
+ return c;
176
+ }
177
+ function makeThumb(){ const t=$('#thumb'); t.src=cropCanvas().toDataURL('image/png'); t.style.display='block'; }
178
+
179
+ async function save() {
180
+ if(!box) return;
181
+ const it=items[idx];
182
+ $('#save').disabled=true;
183
+ const crop = cropCanvas().toDataURL('image/png');
184
+ const res = await fetch('/api/save', {method:'POST', headers:{'Content-Type':'application/json'},
185
+ body: JSON.stringify({id:it.id, crop, box, label:$('#label').value})});
186
+ const data = await res.json();
187
+ if(data.error){ toast('ERROR: '+data.error); return; }
188
+ items[idx].crops = data.crops_for_id;
189
+ renderList(); updateCount();
190
+ toast(`Saved ${data.crop_file} (total ${data.total_saved})`);
191
+ clearSel();
192
+ }
193
+ async function undo() {
194
+ const it=items[idx];
195
+ const res = await fetch('/api/delete_last', {method:'POST', headers:{'Content-Type':'application/json'},
196
+ body: JSON.stringify({id:it.id})});
197
+ const data = await res.json();
198
+ items[idx].crops = data.crops_for_id;
199
+ renderList(); updateCount(); toast('Removed last crop for #'+it.id);
200
+ }
201
+
202
+ $('#save').onclick = save;
203
+ $('#undo').onclick = undo;
204
+ $('#prev').onclick = ()=>select(idx-1);
205
+ $('#next').onclick = ()=>select(idx+1);
206
+ $('#clearsel').onclick = clearSel;
207
+ $('#zoom').oninput = applyZoom;
208
+ window.addEventListener('keydown', e=>{
209
+ if(e.target.tagName==='INPUT') return;
210
+ if(e.key==='ArrowLeft') select(idx-1);
211
+ if(e.key==='ArrowRight') select(idx+1);
212
+ if(e.key==='Enter' && !$('#save').disabled) save();
213
+ });
214
+ loadItems();
215
+ </script>
216
+ </body>
217
+ </html>
code/sec4_2_why_vlms_fail/stage2_zoomed_recognition/wait_and_judge.sh ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ cd "$(dirname "$0")"
3
+ # wait until gemini eval reaches 153 (or ask_crops process exits), then judge to completion
4
+ for i in $(seq 1 120); do
5
+ ec=$(python3 -c "import json;print(len(json.load(open('crop_eval_gemini-3.1-pro-preview_results.json'))))" 2>/dev/null || echo 0)
6
+ echo "wait $i: gemini eval $ec/153"
7
+ if [ "$ec" -ge 153 ] || ! pgrep -f "ask_crops.py" >/dev/null; then
8
+ echo "eval done (or stopped). Final judging pass..."
9
+ python judge_crops.py
10
+ break
11
+ fi
12
+ sleep 15
13
+ done
code/sec4_2_why_vlms_fail/stage3_source_mapping/auto_annotate.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Auto-generate the mapping/localization test for the physical (direct) images.
3
+
4
+ Each image already has ONE correct region = the manually-cropped reflection/shadow
5
+ box (from the cropper's crop_meta.json). We add 3 non-overlapping distractor boxes
6
+ of similar size elsewhere in the image, label all four A-D in randomized order,
7
+ render an annotated PNG, and record the answer key.
8
+
9
+ Images where 3 distractors cannot be placed (box too large, or multi-crop) are
10
+ flagged status="needs_manual" for the manual platform.
11
+
12
+ Outputs:
13
+ sec4_2_why_vlms_fail/stage3_source_mapping/annotated/<id>.png annotated image (boxes + letters)
14
+ sec4_2_why_vlms_fail/stage3_source_mapping/regions.json boxes, correct letter, status per image
15
+ """
16
+ import hashlib
17
+ import json
18
+ import os
19
+ import random
20
+
21
+ import numpy as np
22
+ from PIL import Image, ImageDraw, ImageFont
23
+
24
+ HERE = os.path.dirname(os.path.abspath(__file__))
25
+ ROOT = os.path.abspath(os.path.join(HERE, "..", ".."))
26
+ IMG_DIR = os.path.join(ROOT, "data/combined_output")
27
+ CROP_META = os.path.join(ROOT, "sec4_2_why_vlms_fail", "stage2_zoomed_recognition", "crop_meta.json")
28
+ ANN_DIR = os.path.join(HERE, "annotated")
29
+ OUT = os.path.join(HERE, "regions.json")
30
+ os.makedirs(ANN_DIR, exist_ok=True)
31
+
32
+ FONT_PATH = "/System/Library/Fonts/Supplemental/Arial.ttf"
33
+ LETTERS = ["A", "B", "C", "D"]
34
+ PINK = (255, 0, 170) # all candidate boxes pink
35
+
36
+
37
+ def intersects(a, b, margin):
38
+ return not (a["x"] + a["w"] + margin <= b["x"] or
39
+ b["x"] + b["w"] + margin <= a["x"] or
40
+ a["y"] + a["h"] + margin <= b["y"] or
41
+ b["y"] + b["h"] + margin <= a["y"])
42
+
43
+
44
+ def dark_fraction(dark_small, sW, sH, W, H, b):
45
+ """Fraction of near-black (occluder) pixels inside box b, via downscaled map."""
46
+ x1 = int(b["x"] / W * sW); x2 = int((b["x"] + b["w"]) / W * sW)
47
+ y1 = int(b["y"] / H * sH); y2 = int((b["y"] + b["h"]) / H * sH)
48
+ x2 = max(x2, x1 + 1); y2 = max(y2, y1 + 1)
49
+ region = dark_small[y1:y2, x1:x2]
50
+ return region.mean() if region.size else 0.0
51
+
52
+
53
+ def place_distractors(correct, W, H, seed, dark_small, n=3):
54
+ sH, sW = dark_small.shape
55
+ rng = random.Random(seed)
56
+ margin = max(8, int(0.02 * min(W, H)))
57
+ placed = []
58
+ for _ in range(n):
59
+ got = None
60
+ # shrink attempts: try same size, then progressively smaller
61
+ for shrink in (1.0, 0.85, 0.7, 0.55):
62
+ cw = max(12, int(correct["w"] * shrink))
63
+ ch = max(12, int(correct["h"] * shrink))
64
+ if cw >= W or ch >= H:
65
+ continue
66
+ for _ in range(400):
67
+ jx = rng.uniform(0.85, 1.15) # mild size jitter
68
+ jy = rng.uniform(0.85, 1.15)
69
+ w = min(W - 2, max(12, int(cw * jx)))
70
+ h = min(H - 2, max(12, int(ch * jy)))
71
+ x = rng.randint(0, W - w)
72
+ y = rng.randint(0, H - h)
73
+ cand = {"x": x, "y": y, "w": w, "h": h}
74
+ if intersects(cand, correct, margin):
75
+ continue
76
+ if any(intersects(cand, p, margin) for p in placed):
77
+ continue
78
+ # avoid the black occluder: decoy must be mostly real content
79
+ if dark_fraction(dark_small, sW, sH, W, H, cand) > 0.30:
80
+ continue
81
+ got = cand
82
+ break
83
+ if got:
84
+ break
85
+ if not got:
86
+ return None # couldn't fit -> needs_manual
87
+ placed.append(got)
88
+ return placed
89
+
90
+
91
+ def render(item, W, H, occ_path):
92
+ """Draw all candidate regions as PINK outlines (interior kept transparent so
93
+ the shadow/reflection content stays fully visible) on the hand-occluded image."""
94
+ img = Image.open(occ_path).convert("RGBA")
95
+ overlay = Image.new("RGBA", img.size, (0, 0, 0, 0))
96
+ draw = ImageDraw.Draw(overlay)
97
+ lw = max(3, int(min(W, H) / 200))
98
+ fs = max(18, int(min(W, H) / 16))
99
+ try:
100
+ font = ImageFont.truetype(FONT_PATH, fs)
101
+ except Exception:
102
+ font = ImageFont.load_default()
103
+ for letter, b in item["boxes"].items():
104
+ x1, y1, x2, y2 = b["x"], b["y"], b["x"] + b["w"], b["y"] + b["h"]
105
+ # pink border only; NO interior fill -> region stays transparent/visible
106
+ draw.rectangle([x1, y1, x2, y2], outline=PINK + (255,), width=lw)
107
+ # letter tag in a solid pink chip at the top-left corner
108
+ tw, th = fs * 0.85, fs
109
+ tx, ty = x1, max(0, y1 - th - 2)
110
+ draw.rectangle([tx, ty, tx + tw + 8, ty + th + 4], fill=PINK + (255,))
111
+ draw.text((tx + 4, ty + 2), letter, fill=(255, 255, 255), font=font)
112
+ out = Image.alpha_composite(img, overlay).convert("RGB")
113
+ out.save(os.path.join(ANN_DIR, f"{item['id']}.png"))
114
+
115
+
116
+ def main():
117
+ meta = json.load(open(CROP_META))
118
+ # one correct box per image (first crop); note multi-crop for manual review
119
+ from collections import Counter
120
+ counts = Counter(r["id"] for r in meta)
121
+ seen = set()
122
+ regions = []
123
+ n_auto = n_manual = n_excluded = 0
124
+ for r in meta:
125
+ iid = str(r["id"])
126
+ if iid in seen:
127
+ continue
128
+ seen.add(iid)
129
+ base = os.path.splitext(r["original_file"])[0]
130
+ occ = os.path.join(IMG_DIR, f"{base}_occluded.png") # HAND-OCCLUDED version
131
+ if not os.path.exists(occ):
132
+ continue
133
+ occ_img = Image.open(occ).convert("RGB")
134
+ W, H = occ_img.size
135
+ # downscaled near-black map to keep decoys off the black occluder
136
+ small = occ_img.resize((min(W, 300), max(1, int(min(W, 300) * H / W)))).convert("L")
137
+ dark_small = (np.asarray(small) < 25).astype(np.float32)
138
+ correct = {k: int(r["crop_box"][k]) for k in ("x", "y", "w", "h")}
139
+ seed = int(hashlib.md5(iid.encode()).hexdigest(), 16) % (2**32)
140
+
141
+ # EXCLUDE cue-occluded images: if the clue crop is itself mostly blacked
142
+ # out, the shadow/reflection is the occluded target -> answer is trivially
143
+ # "the black box". Keep only object-occluded (cue-visible) images.
144
+ crop_region = np.asarray(occ_img.crop(
145
+ (correct["x"], correct["y"], correct["x"] + correct["w"],
146
+ correct["y"] + correct["h"])).convert("L"))
147
+ crop_dark = float((crop_region < 25).mean()) if crop_region.size else 0.0
148
+ if crop_dark > 0.40:
149
+ regions.append({"id": iid, "original_file": r["original_file"], "W": W, "H": H,
150
+ "ground_truth": r["ground_truth"], "status": "excluded_cue_occluded",
151
+ "reason": f"clue crop {crop_dark:.0%} black", "boxes": {},
152
+ "correct_letter": None, "correct_box": correct})
153
+ n_excluded += 1
154
+ continue
155
+
156
+ needs_manual = counts[iid] > 1
157
+ distractors = None if needs_manual else place_distractors(correct, W, H, seed, dark_small)
158
+ if distractors is None:
159
+ status = "needs_manual"
160
+ reason = "multi-crop" if counts[iid] > 1 else "cannot fit 3 distractors"
161
+ # still record the correct box so the manual tool can start from it
162
+ item = {"id": iid, "original_file": r["original_file"], "W": W, "H": H,
163
+ "ground_truth": r["ground_truth"], "status": status, "reason": reason,
164
+ "boxes": {}, "correct_letter": None,
165
+ "correct_box": correct}
166
+ n_manual += 1
167
+ else:
168
+ boxes4 = [correct] + distractors
169
+ rng = random.Random(seed + 7)
170
+ order = LETTERS[:]
171
+ rng.shuffle(order)
172
+ boxes = {order[i]: boxes4[i] for i in range(4)}
173
+ correct_letter = order[0] # correct is boxes4[0]
174
+ item = {"id": iid, "original_file": r["original_file"], "W": W, "H": H,
175
+ "ground_truth": r["ground_truth"], "status": "auto", "reason": "",
176
+ "boxes": boxes, "correct_letter": correct_letter,
177
+ "correct_box": correct}
178
+ render(item, W, H, occ)
179
+ n_auto += 1
180
+ regions.append(item)
181
+
182
+ with open(OUT, "w") as f:
183
+ json.dump(regions, f, indent=2)
184
+ print(f"Total images: {len(regions)}")
185
+ print(f" auto-annotated: {n_auto} (rendered to annotated/)")
186
+ print(f" excluded (cue-occl): {n_excluded}")
187
+ print(f" needs_manual: {n_manual}")
188
+ print(" needs_manual ids:", [r["id"] for r in regions if r["status"] == "needs_manual"])
189
+ print(" excluded ids:", [r["id"] for r in regions if r["status"] == "excluded_cue_occluded"])
190
+
191
+
192
+ if __name__ == "__main__":
193
+ main()
code/sec4_2_why_vlms_fail/stage3_source_mapping/map_eval.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Mapping / localization eval on the auto-annotated physical images.
3
+
4
+ Each image shows an object that is physically occluded; its shadow/reflection is
5
+ visible in exactly one of four labeled regions (A-D). The model must pick the
6
+ region that is the shadow/reflection of the hidden object. Scored vs the answer
7
+ key (correct_letter) in regions.json. Chance = 25%.
8
+
9
+ Usage:
10
+ python map_eval.py --model gpt-5.4
11
+ """
12
+ import argparse
13
+ import base64
14
+ import io
15
+ import json
16
+ import os
17
+ import re
18
+
19
+ from dotenv import load_dotenv
20
+ from PIL import Image
21
+ from openai import OpenAI
22
+ import anthropic
23
+
24
+ HERE = os.path.dirname(os.path.abspath(__file__))
25
+ ROOT = os.path.abspath(os.path.join(HERE, "..", ".."))
26
+ ANN_DIR = os.path.join(HERE, "annotated")
27
+ REGIONS = os.path.join(HERE, "regions.json")
28
+
29
+ load_dotenv(os.path.join(ROOT, ".env"))
30
+ KEYS = {"openai": os.getenv("OpenAI_API_KEY"),
31
+ "anthropic": os.getenv("Anthropic_API_KEY"),
32
+ "gemini": os.getenv("Gemini_API_KEY")}
33
+
34
+ PROMPT = (
35
+ "This image contains an object that is completely occluded (hidden from view). "
36
+ "Its shadow or reflection is visible in exactly ONE of the four labeled regions "
37
+ "A, B, C, or D. Which labeled region contains the shadow or reflection of the "
38
+ "hidden object? Answer with only the single letter: A, B, C, or D."
39
+ )
40
+
41
+
42
+ def init_client(model):
43
+ if "gemini" in model:
44
+ return OpenAI(api_key=KEYS["gemini"],
45
+ base_url="https://generativelanguage.googleapis.com/v1beta/openai/")
46
+ if "claude" in model:
47
+ return anthropic.Anthropic(api_key=KEYS["anthropic"])
48
+ return OpenAI(api_key=KEYS["openai"])
49
+
50
+
51
+ def encode(path, max_bytes=3.5 * 1024 * 1024):
52
+ with open(path, "rb") as f:
53
+ data = f.read()
54
+ if len(data) <= max_bytes:
55
+ return base64.b64encode(data).decode("utf-8")
56
+ img = Image.open(io.BytesIO(data)); s = 0.9
57
+ while True:
58
+ buf = io.BytesIO(); img.save(buf, format="PNG", optimize=True)
59
+ if buf.tell() <= max_bytes:
60
+ break
61
+ w, h = img.size; img = img.resize((int(w * s), int(h * s)), Image.LANCZOS)
62
+ return base64.b64encode(buf.getvalue()).decode("utf-8")
63
+
64
+
65
+ def ask(model, client, path):
66
+ b64 = encode(path)
67
+ if "claude" in model:
68
+ return client.messages.create(
69
+ model=model, max_tokens=50, temperature=0,
70
+ messages=[{"role": "user", "content": [
71
+ {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": b64}},
72
+ {"type": "text", "text": PROMPT}]}]).content[0].text
73
+ return client.chat.completions.create(
74
+ model=model, temperature=0,
75
+ messages=[{"role": "user", "content": [
76
+ {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64}"}},
77
+ {"type": "text", "text": PROMPT}]}]).choices[0].message.content
78
+
79
+
80
+ def parse_letter(text):
81
+ if not text:
82
+ return None
83
+ m = re.search(r"\b([ABCD])\b", text.upper())
84
+ if m:
85
+ return m.group(1)
86
+ m = re.search(r"([ABCD])", text.upper())
87
+ return m.group(1) if m else None
88
+
89
+
90
+ def main():
91
+ ap = argparse.ArgumentParser()
92
+ ap.add_argument("--model", required=True)
93
+ args = ap.parse_args()
94
+
95
+ items = [r for r in json.load(open(REGIONS)) if r["status"] == "auto"]
96
+ model_name = args.model.split("/")[-1]
97
+ out = os.path.join(HERE, f"map_eval_{model_name}_results.json")
98
+ if os.path.exists(out):
99
+ results = json.load(open(out)); done = {r["id"] for r in results}
100
+ else:
101
+ results, done = [], set()
102
+
103
+ client = init_client(args.model)
104
+ for i, it in enumerate(items):
105
+ if it["id"] in done:
106
+ continue
107
+ path = os.path.join(ANN_DIR, f"{it['id']}.png")
108
+ resp = ask(args.model, client, path)
109
+ letter = parse_letter(resp)
110
+ correct = (letter == it["correct_letter"])
111
+ print(f"[{i+1}/{len(items)}] {it['id']}: picked {letter} (key {it['correct_letter']}) "
112
+ f"{'✓' if correct else '✗'}")
113
+ results.append({
114
+ "id": it["id"], "ground_truth": it["ground_truth"],
115
+ "correct_letter": it["correct_letter"], "response": resp,
116
+ "parsed_letter": letter, "correct": correct,
117
+ })
118
+ with open(out, "w") as f:
119
+ json.dump(results, f, indent=2)
120
+
121
+ n = len(results); c = sum(r["correct"] for r in results)
122
+ print(f"\n{model_name}: {c}/{n} = {c/n:.1%} (chance 25%)")
123
+
124
+
125
+ if __name__ == "__main__":
126
+ main()
code/sec4_2_why_vlms_fail/stage3_source_mapping/reverse_annotate.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ REVERSE mapping test: the shadow/reflection is visible; the OBJECT is occluded.
3
+ Four candidate regions are ALL blacked out (the real object occluder + 3 decoy
4
+ occluders elsewhere). The model must use the visible shadow/reflection to pick
5
+ which occluded region actually hides the object.
6
+
7
+ To avoid a shape giveaway, all four regions are drawn as uniform black rectangles
8
+ (the real occluder's bbox is filled to match the decoys), outlined pink + lettered.
9
+ Decoys never cover the shadow crop (kept visible).
10
+
11
+ Only object-occluded images are used (clue crop must be visible, not blacked out).
12
+
13
+ Outputs:
14
+ sec4_2_why_vlms_fail/stage3_source_mapping/annotated_reverse/<id>.png
15
+ sec4_2_why_vlms_fail/stage3_source_mapping/regions_reverse.json
16
+ """
17
+ import hashlib
18
+ import json
19
+ import os
20
+ import random
21
+
22
+ import numpy as np
23
+ from PIL import Image, ImageDraw, ImageFont
24
+
25
+ HERE = os.path.dirname(os.path.abspath(__file__))
26
+ ROOT = os.path.abspath(os.path.join(HERE, "..", ".."))
27
+ IMG_DIR = os.path.join(ROOT, "data/combined_output")
28
+ CROP_META = os.path.join(ROOT, "sec4_2_why_vlms_fail", "stage2_zoomed_recognition", "crop_meta.json")
29
+ ANN_JSON = os.path.join(IMG_DIR, "annotations.json")
30
+ ANN_DIR = os.path.join(HERE, "annotated_reverse")
31
+ OUT = os.path.join(HERE, "regions_reverse.json")
32
+ os.makedirs(ANN_DIR, exist_ok=True)
33
+
34
+ # original hand-annotated occluder shapes (polygons/bboxes), indexed by id
35
+ ANN = {str(e["id"]): e for e in json.load(open(ANN_JSON))}
36
+
37
+ FONT_PATH = "/System/Library/Fonts/Supplemental/Arial.ttf"
38
+ LETTERS = ["A", "B", "C", "D"]
39
+ PINK = (237, 28, 36) # red markings for the reverse test
40
+
41
+
42
+ def intersects(a, b, margin):
43
+ return not (a["x"] + a["w"] + margin <= b["x"] or
44
+ b["x"] + b["w"] + margin <= a["x"] or
45
+ a["y"] + a["h"] + margin <= b["y"] or
46
+ b["y"] + b["h"] + margin <= a["y"])
47
+
48
+
49
+ def occluder_bbox(iid):
50
+ """Bounding box of the ORIGINAL hand-annotated occluder shape(s) in
51
+ annotations.json (polygons and/or bboxes), unioned."""
52
+ e = ANN.get(iid)
53
+ if not e:
54
+ return None
55
+ xs, ys = [], []
56
+ for a in e.get("annotations", []):
57
+ if a.get("type") == "polygon":
58
+ for p in a["points"]:
59
+ xs.append(p["x"]); ys.append(p["y"])
60
+ elif a.get("type") == "bbox":
61
+ xs += [a["x1"], a["x2"]]; ys += [a["y1"], a["y2"]]
62
+ if not xs:
63
+ return None
64
+ x1, y1, x2, y2 = min(xs), min(ys), max(xs), max(ys)
65
+ return {"x": int(x1), "y": int(y1), "w": int(x2 - x1), "h": int(y2 - y1)}
66
+
67
+
68
+ def place_decoys(real, shadow, W, H, seed, n=3):
69
+ rng = random.Random(seed)
70
+ margin = max(8, int(0.02 * min(W, H)))
71
+ placed = []
72
+ for _ in range(n):
73
+ got = None
74
+ for shrink in (1.0, 0.85, 0.7, 0.55):
75
+ cw = max(14, int(real["w"] * shrink))
76
+ ch = max(14, int(real["h"] * shrink))
77
+ if cw >= W or ch >= H:
78
+ continue
79
+ for _ in range(500):
80
+ w = min(W - 2, max(14, int(cw * rng.uniform(0.85, 1.15))))
81
+ h = min(H - 2, max(14, int(ch * rng.uniform(0.85, 1.15))))
82
+ x = rng.randint(0, W - w); y = rng.randint(0, H - h)
83
+ cand = {"x": x, "y": y, "w": w, "h": h}
84
+ if intersects(cand, real, margin):
85
+ continue
86
+ if intersects(cand, shadow, margin): # keep shadow visible
87
+ continue
88
+ if any(intersects(cand, p, margin) for p in placed):
89
+ continue
90
+ got = cand; break
91
+ if got:
92
+ break
93
+ if not got:
94
+ return None
95
+ placed.append(got)
96
+ return placed
97
+
98
+
99
+ def render(iid, occ_img, boxes, real_letter):
100
+ img = occ_img.convert("RGBA")
101
+ draw = ImageDraw.Draw(img)
102
+ W, H = img.size
103
+ # fill EVERY candidate box solid black so all four look identical
104
+ for b in boxes.values():
105
+ draw.rectangle([b["x"], b["y"], b["x"] + b["w"], b["y"] + b["h"]], fill=(0, 0, 0, 255))
106
+ lw = max(3, int(min(W, H) / 200))
107
+ fs = max(18, int(min(W, H) / 16))
108
+ try:
109
+ font = ImageFont.truetype(FONT_PATH, fs)
110
+ except Exception:
111
+ font = ImageFont.load_default()
112
+ for letter, b in boxes.items():
113
+ draw.rectangle([b["x"], b["y"], b["x"] + b["w"], b["y"] + b["h"]],
114
+ outline=PINK + (255,), width=lw)
115
+ tw, th = fs * 0.85, fs
116
+ tx, ty = b["x"], max(0, b["y"] - th - 2)
117
+ draw.rectangle([tx, ty, tx + tw + 8, ty + th + 4], fill=PINK + (255,))
118
+ draw.text((tx + 4, ty + 2), letter, fill=(255, 255, 255), font=font)
119
+ img.convert("RGB").save(os.path.join(ANN_DIR, f"{iid}.png"))
120
+
121
+
122
+ def main():
123
+ meta = json.load(open(CROP_META))
124
+ from collections import Counter
125
+ counts = Counter(str(r["id"]) for r in meta)
126
+ seen = set()
127
+ regions = []
128
+ n_auto = n_excluded = n_fail = 0
129
+ for r in meta:
130
+ iid = str(r["id"])
131
+ if iid in seen:
132
+ continue
133
+ seen.add(iid)
134
+ base = os.path.splitext(r["original_file"])[0]
135
+ occ = os.path.join(IMG_DIR, f"{base}_occluded.png")
136
+ if not os.path.exists(occ):
137
+ continue
138
+ occ_img = Image.open(occ).convert("RGB")
139
+ W, H = occ_img.size
140
+ shadow = {k: int(r["crop_box"][k]) for k in ("x", "y", "w", "h")}
141
+
142
+ # object-occluded only (shadow crop must be visible)
143
+ cr = np.asarray(occ_img.crop((shadow["x"], shadow["y"],
144
+ shadow["x"] + shadow["w"], shadow["y"] + shadow["h"])).convert("L"))
145
+ if cr.size and (cr < 25).mean() > 0.40:
146
+ regions.append({"id": iid, "status": "excluded_cue_occluded"})
147
+ n_excluded += 1
148
+ continue
149
+
150
+ real = occluder_bbox(iid)
151
+ seed = int(hashlib.md5(iid.encode()).hexdigest(), 16) % (2**32)
152
+ decoys = None
153
+ if real and counts[iid] == 1:
154
+ decoys = place_decoys(real, shadow, W, H, seed)
155
+ if not real or decoys is None:
156
+ regions.append({"id": iid, "status": "needs_manual",
157
+ "reason": "no occluder" if not real else "cant place decoys"})
158
+ n_fail += 1
159
+ continue
160
+
161
+ boxes4 = [real] + decoys
162
+ rng = random.Random(seed + 11)
163
+ order = LETTERS[:]; rng.shuffle(order)
164
+ boxes = {order[i]: boxes4[i] for i in range(4)}
165
+ real_letter = order[0]
166
+ render(iid, occ_img, boxes, real_letter)
167
+ regions.append({"id": iid, "original_file": r["original_file"], "W": W, "H": H,
168
+ "ground_truth": r["ground_truth"], "status": "auto",
169
+ "boxes": boxes, "correct_letter": real_letter,
170
+ "real_occluder": real, "shadow_box": shadow})
171
+ n_auto += 1
172
+
173
+ with open(OUT, "w") as f:
174
+ json.dump(regions, f, indent=2)
175
+ print(f"Total unique images: {len(regions)}")
176
+ print(f" auto (reverse) annotated: {n_auto}")
177
+ print(f" excluded (cue-occluded): {n_excluded}")
178
+ print(f" needs_manual/failed: {n_fail}")
179
+
180
+
181
+ if __name__ == "__main__":
182
+ main()
code/sec4_2_why_vlms_fail/stage3_source_mapping/reverse_map_eval.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ REVERSE mapping eval: the shadow/reflection is visible; four regions are all
3
+ blacked out; the model must pick which occluded region hides the actual object.
4
+ Scored vs regions_reverse.json (correct_letter). Chance = 25%.
5
+
6
+ Usage: python reverse_map_eval.py --model gpt-5.4
7
+ """
8
+ import argparse
9
+ import base64
10
+ import io
11
+ import json
12
+ import os
13
+ import re
14
+
15
+ from dotenv import load_dotenv
16
+ from PIL import Image
17
+ from openai import OpenAI
18
+ import anthropic
19
+
20
+ HERE = os.path.dirname(os.path.abspath(__file__))
21
+ ROOT = os.path.abspath(os.path.join(HERE, "..", ".."))
22
+ ANN_DIR = os.path.join(HERE, "annotated_reverse")
23
+ REGIONS = os.path.join(HERE, "regions_reverse.json")
24
+
25
+ load_dotenv(os.path.join(ROOT, ".env"))
26
+ KEYS = {"openai": os.getenv("OpenAI_API_KEY"),
27
+ "anthropic": os.getenv("Anthropic_API_KEY"),
28
+ "gemini": os.getenv("Gemini_API_KEY")}
29
+
30
+ PROMPT = (
31
+ "The shadow or reflection of an object is clearly visible in this image. "
32
+ "One of the four labeled regions (A, B, C, D) is occluded (blacked out) and "
33
+ "hides the actual object that casts that shadow or reflection. Which labeled "
34
+ "region contains the hidden object? Answer with only the single letter: A, B, C, or D."
35
+ )
36
+
37
+
38
+ def init_client(model):
39
+ if "gemini" in model:
40
+ return OpenAI(api_key=KEYS["gemini"],
41
+ base_url="https://generativelanguage.googleapis.com/v1beta/openai/")
42
+ if "claude" in model:
43
+ return anthropic.Anthropic(api_key=KEYS["anthropic"])
44
+ return OpenAI(api_key=KEYS["openai"])
45
+
46
+
47
+ def encode(path, max_bytes=3.5 * 1024 * 1024):
48
+ with open(path, "rb") as f:
49
+ data = f.read()
50
+ if len(data) <= max_bytes:
51
+ return base64.b64encode(data).decode("utf-8")
52
+ img = Image.open(io.BytesIO(data)); s = 0.9
53
+ while True:
54
+ buf = io.BytesIO(); img.save(buf, format="PNG", optimize=True)
55
+ if buf.tell() <= max_bytes:
56
+ break
57
+ w, h = img.size; img = img.resize((int(w * s), int(h * s)), Image.LANCZOS)
58
+ return base64.b64encode(buf.getvalue()).decode("utf-8")
59
+
60
+
61
+ def ask(model, client, path):
62
+ b64 = encode(path)
63
+ if "claude" in model:
64
+ return client.messages.create(
65
+ model=model, max_tokens=50, temperature=0,
66
+ messages=[{"role": "user", "content": [
67
+ {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": b64}},
68
+ {"type": "text", "text": PROMPT}]}]).content[0].text
69
+ return client.chat.completions.create(
70
+ model=model, temperature=0,
71
+ messages=[{"role": "user", "content": [
72
+ {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64}"}},
73
+ {"type": "text", "text": PROMPT}]}]).choices[0].message.content
74
+
75
+
76
+ def parse_letter(text):
77
+ if not text:
78
+ return None
79
+ m = re.search(r"\b([ABCD])\b", text.upper()) or re.search(r"([ABCD])", text.upper())
80
+ return m.group(1) if m else None
81
+
82
+
83
+ def main():
84
+ ap = argparse.ArgumentParser()
85
+ ap.add_argument("--model", required=True)
86
+ args = ap.parse_args()
87
+ items = [r for r in json.load(open(REGIONS)) if r.get("status") == "auto"]
88
+ model_name = args.model.split("/")[-1]
89
+ out = os.path.join(HERE, f"reverse_map_eval_{model_name}_results.json")
90
+ if os.path.exists(out):
91
+ results = json.load(open(out)); done = {r["id"] for r in results}
92
+ else:
93
+ results, done = [], set()
94
+ client = init_client(args.model)
95
+ for i, it in enumerate(items):
96
+ if it["id"] in done:
97
+ continue
98
+ resp = ask(args.model, client, os.path.join(ANN_DIR, f"{it['id']}.png"))
99
+ letter = parse_letter(resp)
100
+ correct = (letter == it["correct_letter"])
101
+ print(f"[{i+1}/{len(items)}] {it['id']}: {letter} (key {it['correct_letter']}) {'✓' if correct else '✗'}")
102
+ results.append({"id": it["id"], "ground_truth": it["ground_truth"],
103
+ "correct_letter": it["correct_letter"], "response": resp,
104
+ "parsed_letter": letter, "correct": correct})
105
+ with open(out, "w") as f:
106
+ json.dump(results, f, indent=2)
107
+ n = len(results); c = sum(r["correct"] for r in results)
108
+ print(f"\n{model_name}: {c}/{n} = {c/n:.1%} (chance 25%)")
109
+
110
+
111
+ if __name__ == "__main__":
112
+ main()
code/sec4_2_why_vlms_fail/stage3_source_mapping/run_map_eval.sh ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ cd "$(dirname "$0")"
4
+ for m in "gpt-5.4" "claude-opus-4-6" "gemini-3.1-pro-preview"; do
5
+ echo "=== map eval: $m ==="
6
+ python -u map_eval.py --model "$m" &
7
+ done
8
+ wait
9
+ echo "All map evals complete."
code/sec4_2_why_vlms_fail/stage3_source_mapping/run_reverse_map_eval.sh ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ cd "$(dirname "$0")"
4
+ for m in "gpt-5.4" "claude-opus-4-6" "gemini-3.1-pro-preview"; do
5
+ echo "=== reverse map eval: $m ==="
6
+ python -u reverse_map_eval.py --model "$m" &
7
+ done
8
+ wait
9
+ echo "All reverse map evals complete."
code/sec4_2_why_vlms_fail/stage4_highlighted_region/highlight_annotate.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Single-highlight images for the identify-from-highlighted-surface question.
3
+
4
+ For each object-occluded image (object hidden, reflection/shadow visible), draw
5
+ ONE pink box around the correct reflection/shadow region (the user's crop). The
6
+ model is then asked to identify the occluded object from that highlighted surface.
7
+
8
+ Only object-occluded images (clue crop visible, not blacked out) are used.
9
+
10
+ Outputs:
11
+ sec4_2_why_vlms_fail/stage4_highlighted_region/annotated_highlight/<id>.png
12
+ sec4_2_why_vlms_fail/stage4_highlighted_region/regions_highlight.json
13
+ """
14
+ import json
15
+ import os
16
+
17
+ import numpy as np
18
+ from PIL import Image, ImageDraw
19
+
20
+ HERE = os.path.dirname(os.path.abspath(__file__))
21
+ ROOT = os.path.abspath(os.path.join(HERE, "..", ".."))
22
+ IMG_DIR = os.path.join(ROOT, "data/combined_output")
23
+ CROP_META = os.path.join(ROOT, "sec4_2_why_vlms_fail", "stage2_zoomed_recognition", "crop_meta.json")
24
+ ANN_DIR = os.path.join(HERE, "annotated_highlight")
25
+ OUT = os.path.join(HERE, "regions_highlight.json")
26
+ os.makedirs(ANN_DIR, exist_ok=True)
27
+ PINK = (255, 0, 170)
28
+
29
+
30
+ def main():
31
+ meta = json.load(open(CROP_META))
32
+ seen = set()
33
+ regions = []
34
+ n = n_excl = 0
35
+ for r in meta:
36
+ iid = str(r["id"])
37
+ if iid in seen:
38
+ continue
39
+ seen.add(iid)
40
+ base = os.path.splitext(r["original_file"])[0]
41
+ occ = os.path.join(IMG_DIR, f"{base}_occluded.png")
42
+ if not os.path.exists(occ):
43
+ continue
44
+ img = Image.open(occ).convert("RGB")
45
+ W, H = img.size
46
+ b = {k: int(r["crop_box"][k]) for k in ("x", "y", "w", "h")}
47
+ # object-occluded only (highlighted surface must be visible)
48
+ cr = np.asarray(img.crop((b["x"], b["y"], b["x"] + b["w"], b["y"] + b["h"])).convert("L"))
49
+ if cr.size and (cr < 25).mean() > 0.40:
50
+ n_excl += 1
51
+ continue
52
+ draw = ImageDraw.Draw(img)
53
+ lw = max(3, int(min(W, H) / 200))
54
+ draw.rectangle([b["x"], b["y"], b["x"] + b["w"], b["y"] + b["h"]], outline=PINK, width=lw)
55
+ img.save(os.path.join(ANN_DIR, f"{iid}.png"))
56
+ regions.append({"id": iid, "original_file": r["original_file"],
57
+ "ground_truth": r["ground_truth"], "box": b})
58
+ n += 1
59
+ with open(OUT, "w") as f:
60
+ json.dump(regions, f, indent=2)
61
+ print(f"highlighted (object-occluded): {n} | excluded (cue-occluded): {n_excl}")
62
+
63
+
64
+ if __name__ == "__main__":
65
+ main()
code/sec4_2_why_vlms_fail/stage4_highlighted_region/identify_highlight_eval.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Identify-from-highlighted-surface eval.
3
+ Shows the occluded image with the correct reflection/shadow region highlighted
4
+ (pink box) and asks the model to name the occluded object.
5
+
6
+ Usage: python identify_highlight_eval.py --model gpt-5.4
7
+ """
8
+ import argparse
9
+ import base64
10
+ import io
11
+ import json
12
+ import os
13
+
14
+ from dotenv import load_dotenv
15
+ from PIL import Image
16
+ from openai import OpenAI
17
+ import anthropic
18
+
19
+ HERE = os.path.dirname(os.path.abspath(__file__))
20
+ ROOT = os.path.abspath(os.path.join(HERE, "..", ".."))
21
+ ANN_DIR = os.path.join(HERE, "annotated_highlight")
22
+ REGIONS = os.path.join(HERE, "regions_highlight.json")
23
+
24
+ load_dotenv(os.path.join(ROOT, ".env"))
25
+ KEYS = {"openai": os.getenv("OpenAI_API_KEY"),
26
+ "anthropic": os.getenv("Anthropic_API_KEY"),
27
+ "gemini": os.getenv("Gemini_API_KEY")}
28
+
29
+ PROMPT = ("The occluded object is portrayed in the highlighted reflected surface. "
30
+ "What is this occluded object? Be as specific as you can.")
31
+
32
+
33
+ def init_client(model):
34
+ if "gemini" in model:
35
+ return OpenAI(api_key=KEYS["gemini"],
36
+ base_url="https://generativelanguage.googleapis.com/v1beta/openai/")
37
+ if "claude" in model:
38
+ return anthropic.Anthropic(api_key=KEYS["anthropic"])
39
+ return OpenAI(api_key=KEYS["openai"])
40
+
41
+
42
+ def encode(path, max_bytes=3.5 * 1024 * 1024):
43
+ with open(path, "rb") as f:
44
+ data = f.read()
45
+ if len(data) <= max_bytes:
46
+ return base64.b64encode(data).decode("utf-8")
47
+ img = Image.open(io.BytesIO(data)); s = 0.9
48
+ while True:
49
+ buf = io.BytesIO(); img.save(buf, format="PNG", optimize=True)
50
+ if buf.tell() <= max_bytes:
51
+ break
52
+ w, h = img.size; img = img.resize((int(w * s), int(h * s)), Image.LANCZOS)
53
+ return base64.b64encode(buf.getvalue()).decode("utf-8")
54
+
55
+
56
+ def ask(model, client, path):
57
+ b64 = encode(path)
58
+ if "claude" in model:
59
+ return client.messages.create(
60
+ model=model, max_tokens=500, temperature=0,
61
+ messages=[{"role": "user", "content": [
62
+ {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": b64}},
63
+ {"type": "text", "text": PROMPT}]}]).content[0].text
64
+ return client.chat.completions.create(
65
+ model=model, temperature=0,
66
+ messages=[{"role": "user", "content": [
67
+ {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64}"}},
68
+ {"type": "text", "text": PROMPT}]}]).choices[0].message.content
69
+
70
+
71
+ def main():
72
+ ap = argparse.ArgumentParser()
73
+ ap.add_argument("--model", required=True)
74
+ args = ap.parse_args()
75
+ items = json.load(open(REGIONS))
76
+ model_name = args.model.split("/")[-1]
77
+ out = os.path.join(HERE, f"identify_highlight_{model_name}_results.json")
78
+ if os.path.exists(out):
79
+ results = json.load(open(out)); done = {r["id"] for r in results}
80
+ else:
81
+ results, done = [], set()
82
+ client = init_client(args.model)
83
+ for i, it in enumerate(items):
84
+ if it["id"] in done:
85
+ continue
86
+ resp = ask(args.model, client, os.path.join(ANN_DIR, f"{it['id']}.png"))
87
+ print(f"[{i+1}/{len(items)}] {it['id']} (gt={it['ground_truth']!r}) -> {resp[:80]}")
88
+ results.append({"id": it["id"], "ground_truth": it["ground_truth"],
89
+ "prompt": PROMPT, "response": resp})
90
+ with open(out, "w") as f:
91
+ json.dump(results, f, indent=2)
92
+ print(f"Done. {len(results)} -> {out}")
93
+
94
+
95
+ if __name__ == "__main__":
96
+ main()
code/sec4_2_why_vlms_fail/stage4_highlighted_region/judge_highlight.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob, json, os, sys
2
+ from dotenv import load_dotenv
3
+ from openai import OpenAI
4
+ import anthropic
5
+ HERE=os.path.dirname(os.path.abspath(__file__)); ROOT=os.path.abspath(os.path.join(HERE,'..','..'))
6
+ load_dotenv(os.path.join(ROOT,'.env'))
7
+ CL={'openai':OpenAI(api_key=os.getenv('OpenAI_API_KEY')),'anthropic':anthropic.Anthropic(api_key=os.getenv('Anthropic_API_KEY'))}
8
+ JUDGES=['gpt-5.4','claude-opus-4-6']
9
+ P=("You are evaluating whether a vision model correctly identified an object.\n\n"
10
+ "The model was shown an occluded image with a reflection/shadow region highlighted, "
11
+ "and asked to name the underlying object.\n\nGround truth: \"{gt}\"\n\nModel response: \"{resp}\"\n\n"
12
+ "Does the response correctly identify the same underlying OBJECT as the ground truth? "
13
+ "The ground truth may be phrased as 'reflection of a car' or 'car shadow'; the response only needs "
14
+ "to identify the underlying object (e.g. 'car') and need NOT state it is a shadow/reflection. "
15
+ "Allow reasonable variation in phrasing/synonyms. Answer only 'yes' or 'no'.")
16
+ def jc(gt,resp,jm):
17
+ pr=P.format(gt=(gt or '').strip(),resp=(resp or '').strip())
18
+ if jm.startswith('claude'):
19
+ v=CL['anthropic'].messages.create(model=jm,temperature=0,max_tokens=10,messages=[{'role':'user','content':pr}]).content[0].text
20
+ else:
21
+ v=CL['openai'].chat.completions.create(model=jm,temperature=0,messages=[{'role':'user','content':pr}]).choices[0].message.content
22
+ return v.strip().lower().startswith('yes')
23
+ for model in sys.argv[1:]:
24
+ d=json.load(open(f'identify_highlight_{model}_results.json'))
25
+ out=f'identify_highlight_{model}_judged_results.json'
26
+ judged=json.load(open(out)) if os.path.exists(out) else []
27
+ by={r['id']:r for r in judged}
28
+ for r in d:
29
+ rec=by.get(r['id'])
30
+ if rec is None:
31
+ rec=dict(r); rec['correct']={}; judged.append(rec); by[r['id']]=rec
32
+ rec.setdefault('correct',{})
33
+ for jm in JUDGES:
34
+ if jm not in rec['correct']: rec['correct'][jm]=jc(r['ground_truth'],r['response'],jm)
35
+ rec['consensus_correct']=all(rec['correct'].values())
36
+ json.dump(judged,open(out,'w'),indent=2)
37
+ c=sum(1 for r in judged if r.get('consensus_correct'))
38
+ print(f"{model}: {c}/{len(judged)} = {c/len(judged):.1%}")
code/sec4_2_why_vlms_fail/stage4_highlighted_region/run_identify_highlight.sh ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ cd "$(dirname "$0")"
4
+ for m in "gpt-5.4" "claude-opus-4-6" "gemini-3.1-pro-preview"; do
5
+ echo "=== identify-highlight eval: $m ==="
6
+ python -u identify_highlight_eval.py --model "$m" &
7
+ done
8
+ wait
9
+ echo "All identify-highlight evals complete."