yangbai123 commited on
Commit
80c695c
·
0 Parent(s):

Clinical3D release (English-only questions)

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 +261 -0
  3. assets/teaser.png +3 -0
  4. code/clinical3d_eval/__init__.py +0 -0
  5. code/clinical3d_eval/prompt.py +47 -0
  6. code/clinical3d_eval/run.py +88 -0
  7. code/clinical3d_eval/sampling.py +40 -0
  8. code/clinical3d_eval/score.py +68 -0
  9. code/clinical3d_eval/vlm/__init__.py +34 -0
  10. code/clinical3d_eval/vlm/base.py +69 -0
  11. code/clinical3d_eval/vlm/claude.py +93 -0
  12. code/clinical3d_eval/vlm/deepseek.py +67 -0
  13. code/clinical3d_eval/vlm/gemini.py +74 -0
  14. code/clinical3d_eval/vlm/internvl.py +128 -0
  15. code/clinical3d_eval/vlm/kimi.py +41 -0
  16. code/clinical3d_eval/vlm/llava.py +228 -0
  17. code/clinical3d_eval/vlm/openai_api.py +77 -0
  18. code/clinical3d_eval/vlm/qwen.py +199 -0
  19. code/clinical3d_eval/vlm/spatial_mllm.py +88 -0
  20. code/examples/custom_model.py +42 -0
  21. code/examples/run_api_models.sh +12 -0
  22. code/examples/run_open_models.sh +14 -0
  23. code/examples/show_masks.py +50 -0
  24. leaderboard.csv +42 -0
  25. masks/render/corridor_param_002_a.npz +3 -0
  26. masks/render/corridor_param_002_b.npz +3 -0
  27. masks/render/corridor_param_002_c.npz +3 -0
  28. masks/render/corridor_param_003_a.npz +3 -0
  29. masks/render/corridor_param_003_b.npz +3 -0
  30. masks/render/corridor_param_003_c.npz +3 -0
  31. masks/render/corridor_param_005_a.npz +3 -0
  32. masks/render/corridor_param_005_b.npz +3 -0
  33. masks/render/corridor_param_005_c.npz +3 -0
  34. masks/render/corridor_param_006_a.npz +3 -0
  35. masks/render/corridor_param_006_b.npz +3 -0
  36. masks/render/corridor_param_006_c.npz +3 -0
  37. masks/render/corridor_param_007_a.npz +3 -0
  38. masks/render/corridor_param_007_b.npz +3 -0
  39. masks/render/corridor_param_007_c.npz +3 -0
  40. masks/render/corridor_param_008_a.npz +3 -0
  41. masks/render/corridor_param_011_a.npz +3 -0
  42. masks/render/corridor_param_011_b.npz +3 -0
  43. masks/render/corridor_param_011_c.npz +3 -0
  44. masks/render/corridor_param_013_a.npz +3 -0
  45. masks/render/corridor_param_013_b.npz +3 -0
  46. masks/render/corridor_param_013_c.npz +3 -0
  47. masks/render/corridor_param_014_a.npz +3 -0
  48. masks/render/corridor_param_014_b.npz +3 -0
  49. masks/render/corridor_param_014_c.npz +3 -0
  50. masks/render/corridor_param_015_a.npz +3 -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,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-4.0
3
+ task_categories:
4
+ - visual-question-answering
5
+ - video-text-to-text
6
+ language:
7
+ - en
8
+ tags:
9
+ - spatial-reasoning
10
+ - 3d
11
+ - video
12
+ - hospital
13
+ - multimodal
14
+ - benchmark
15
+ pretty_name: Clinical3D-Bench
16
+ size_categories:
17
+ - 1K<n<10K
18
+ configs:
19
+ - config_name: default
20
+ data_files:
21
+ - split: test
22
+ path: questions.jsonl
23
+ ---
24
+
25
+ # Clinical3D-Bench
26
+
27
+ ![Clinical3D-Bench](assets/teaser.png)
28
+
29
+ *An MLLM answers questions from a walkthrough of a hospital room (middle). The exact answers are computed from the 3D
30
+ scene (right; the numbers mark the evidence). The three questions shown are examples of three of the eight question
31
+ types: clinical ownership, patient-centred reference frames and equipment clearance. Left: examples from the 16 room families.*
32
+
33
+ Clinical3D-Bench tests whether multimodal large language models (MLLMs) build a 3D picture of a hospital room
34
+ from an egocentric walkthrough video. It covers the patient's frame of reference, which device belongs to which bed,
35
+ and routes and clearances computed from the room's occupancy.
36
+
37
+ - **3,368** multiple-choice questions on **569** ten-second clips of **373** hospital-room layouts in **16** room families.
38
+ - **8 question types:** Count, Re-ID, Light owner, Patient frame, Device reference, Direction, Route and Passability.
39
+ - **Exact answers.** Every answer is computed from the simulated scene.
40
+ - **Paired states.** Many layouts come in two or three states that differ in one clinical fact (262 paired groups; in 204 the answer changes).
41
+ - **Photorealistic clips.** Each clip is a pose-verified photorealistic version of a path-traced render. The render is also released, together with **per-frame instance masks**.
42
+ - **Physician screening.** Ten physicians screened the layouts. Five physicians answered a 400-question subset (**79.0** macro accuracy).
43
+
44
+ ## Leaderboard
45
+
46
+ Accuracy (%) on the full set. **Avg.** is the macro average of the eight types and sets the rank. **Bold** and
47
+ <u>underline</u> mark the best and second best in each column among zero-shot models and, separately, among fine-tuned models.
48
+ "Frames" is the number of frames each model receives (32 unless the model's context or training sets another
49
+ budget). All numbers are from the paper.
50
+
51
+ | Model | Frames | Count | Re-ID | Light owner | Patient frame | Device ref. | Direction | Route | Passability | **Avg.** | Rank |
52
+ |---|---|---|---|---|---|---|---|---|---|---|---|
53
+ | ***References*** | | | | | | | | | | | |
54
+ | Chance (analytic) | – | 20.0 | 33.3 | 28.9 | 50.0 | 27.9 | 24.9 | 26.7 | 50.0 | 32.7 | – |
55
+ | Answer prior (test-fitted) | – | 34.0 | 39.5 | 46.0 | 54.8 | 39.1 | 28.3 | 30.0 | 54.3 | 40.8 | – |
56
+ | Human (physicians)† | – | 84.0 | 80.0 | 86.0 | 94.0 | 82.0 | 82.0 | 60.0 | 64.0 | 79.0 | – |
57
+ | ***Proprietary Models (API)*** | | | | | | | | | | | |
58
+ | Gemini 3.6 Flash | 10 | **59.2** | 47.2 | 76.2 | 46.0 | **64.8** | 49.1 | 31.1 | 55.0 | **53.6** | 4 |
59
+ | GPT-5.5 | 10 | 47.1 | <u>49.2</u> | <u>77.8</u> | 40.7 | 51.6 | <u>49.9</u> | **37.1** | <u>57.8</u> | <u>51.4</u> | 5 |
60
+ | Claude Sonnet 5.5 | 10 | 47.1 | **56.4** | 65.1 | <u>51.0</u> | 53.1 | **51.0** | 31.8 | 55.0 | 51.3 | 6 |
61
+ | ***Open-source General Models*** | | | | | | | | | | | |
62
+ | VideoJev-4B | 20 | 46.6 | 38.5 | 74.6 | 17.0 | 51.6 | 48.4 | 29.5 | **57.9** | 45.5 | 9 |
63
+ | Qwen2.5-VL-3B | 32 | 29.0 | 26.7 | 68.3 | 33.3 | 46.1 | 35.2 | 28.4 | 51.9 | 39.9 | 20 |
64
+ | Qwen2.5-VL-7B | 32 | 17.5 | 40.5 | 17.5 | 27.7 | 41.4 | 26.7 | 30.8 | 54.3 | 32.1 | 35 |
65
+ | Qwen2.5-VL-32B | 32 | 46.8 | 34.9 | 15.9 | 31.6 | 43.0 | 38.9 | 34.5 | 53.7 | 37.4 | 25 |
66
+ | Qwen2.5-VL-72B | 32 | 41.4 | 39.0 | 19.0 | 29.0 | 49.2 | 40.4 | 33.4 | 54.3 | 38.2 | 23 |
67
+ | Qwen3-VL-4B | 16 | 40.5 | 32.8 | 28.6 | 27.1 | 44.5 | 37.2 | 31.3 | 51.0 | 36.6 | 26 |
68
+ | Qwen3-VL-8B | 32 | 46.6 | 39.0 | 55.6 | 20.9 | 50.0 | 40.0 | 33.4 | 56.0 | 42.7 | 14 |
69
+ | Qwen3-VL-32B | 32 | 51.2 | 41.0 | 76.2 | 13.4 | 54.7 | 35.9 | 32.9 | 55.2 | 45.1 | 10 |
70
+ | InternVL3-8B | 32 | 44.9 | 33.8 | 74.6 | 25.3 | 43.0 | 33.1 | 23.7 | 54.7 | 41.6 | 16 |
71
+ | InternVL3-14B | 32 | 52.6 | 47.2 | 71.4 | 20.3 | 47.7 | 40.3 | 31.6 | 54.3 | 45.7 | 7 |
72
+ | InternVL3-38B | 32 | 54.2 | 44.1 | 57.1 | 18.6 | <u>56.2</u> | 45.2 | 30.3 | 54.7 | 45.1 | 11 |
73
+ | InternVL3-78B | 32 | <u>56.7</u> | 26.7 | 73.0 | 18.2 | 51.6 | 43.3 | 27.9 | 54.1 | 43.9 | 13 |
74
+ | InternVL3.5-4B | 32 | 29.0 | 40.0 | 74.6 | 27.9 | 43.8 | 34.0 | 30.8 | 49.2 | 41.2 | 19 |
75
+ | InternVL3.5-8B | 32 | 38.9 | 33.8 | **79.4** | 36.1 | 44.5 | 37.3 | 28.4 | 54.3 | 44.1 | 12 |
76
+ | InternVL3.5-14B | 32 | 47.4 | 32.3 | 71.4 | 32.7 | 50.8 | 41.8 | 34.2 | 54.7 | 45.7 | 8 |
77
+ | InternVL3.5-38B | 32 | 47.9 | 31.8 | 60.3 | 21.6 | 49.2 | 44.5 | 28.7 | 54.8 | 42.3 | 15 |
78
+ | LLaVA-CoT-11B | 16 | 4.9 | 34.9 | 20.6 | 44.4 | 40.6 | 25.6 | 28.9 | 55.2 | 31.9 | 36 |
79
+ | LLaVA-NeXT-Video-34B | 16 | 33.7 | 31.3 | 58.7 | 50.6 | 44.5 | 26.7 | 29.7 | 56.2 | 41.4 | 18 |
80
+ | Kimi-VL-A3B-Instruct | 32 | 23.0 | 29.7 | 46.0 | 32.0 | 35.9 | 35.6 | 28.4 | 54.3 | 35.6 | 28 |
81
+ | Kimi-VL-A3B-Thinking | 32 | 37.3 | 32.3 | 41.3 | 39.7 | 43.0 | 32.6 | 31.1 | 54.3 | 39.0 | 21 |
82
+ | DeepSeek-VL2 | 7 | 32.3 | 30.8 | 54.0 | 33.5 | 41.4 | 32.1 | 28.4 | 54.3 | 38.4 | 22 |
83
+ | Llama-3.2-11B-Vision | 16 | 19.7 | 32.3 | 49.2 | 44.9 | 35.2 | 24.1 | 27.9 | 55.4 | 36.1 | 27 |
84
+ | MiMo-VL-7B-SFT | 32 | 34.0 | 32.8 | 9.5 | 24.6 | 36.7 | 41.0 | 29.2 | 54.3 | 32.8 | 33 |
85
+ | MiMo-VL-7B-RL | 32 | 26.0 | 30.8 | 23.8 | 25.8 | 35.9 | 42.7 | 31.6 | 53.7 | 33.8 | 31 |
86
+ | ***Open-source Spatial Models*** | | | | | | | | | | | |
87
+ | SenseNova-SI-1.1-Qwen2.5-VL-7B | 32 | 19.2 | 34.4 | 1.6 | 35.2 | 40.6 | 33.0 | 31.8 | 53.9 | 31.2 | 37 |
88
+ | SenseNova-SI-1.1-Qwen3-VL-8B | 32 | 41.6 | 43.6 | 4.8 | 25.6 | 38.3 | 32.4 | <u>35.0</u> | 56.4 | 34.7 | 30 |
89
+ | SenseNova-SI-1.3-InternVL3-8B | 32 | 35.6 | 41.0 | 65.1 | 20.3 | 43.0 | 42.2 | 30.8 | 54.3 | 41.5 | 17 |
90
+ | Spatial-MLLM-135K | 32 | 34.0 | 33.8 | 38.1 | 41.6 | 38.3 | 34.5 | 30.3 | 51.6 | 37.8 | 24 |
91
+ | Spatial-MLLM-820K | 32 | 20.3 | 32.8 | 52.4 | 32.5 | 39.1 | 24.5 | 29.5 | 53.9 | 35.6 | 29 |
92
+ | SpaceR-7B | 32 | 17.8 | 36.9 | 20.6 | 29.2 | 43.0 | 31.7 | 33.4 | 55.2 | 33.5 | 32 |
93
+ | VST-7B-SFT | 32 | 24.1 | 29.7 | 6.3 | 27.1 | 46.9 | 36.3 | 33.9 | 53.9 | 32.3 | 34 |
94
+ | SpaceLLaVA-13B | 8 | 11.2 | 31.3 | 1.6 | **54.5** | 40.6 | 21.5 | 29.7 | 51.7 | 30.3 | 38 |
95
+ | ***Fine-tuned on Clinical3D-Train*** | | | | | | | | | | | |
96
+ | Spatial-MLLM SFT | 16 | 54.8 | 65.6 | **87.3** | 89.3 | 59.4 | 77.4 | **65.8** | 59.5 | 69.9 | 3 |
97
+ | VideoJev-4B SFT | 20 | <u>66.8</u> | <u>73.9</u> | <u>83.1</u> | <u>93.7</u> | <u>71.6</u> | <u>77.8</u> | 58.3 | <u>66.0</u> | <u>73.9</u> | 2 |
98
+ | GeoJeV (ours) | 20 | **69.3** | **77.8** | 82.5 | **93.9** | **71.9** | **81.2** | <u>59.5</u> | **69.8** | **75.7** | 1 |
99
+
100
+ † Five physicians answered a 400-question subset (`in_mini`, 50 per type, 80 clips). On this subset, the
101
+ macro average of the 38 models in the table ranks them almost exactly as the full set does (Spearman ρ = 0.986).
102
+ The answer prior is a per-subtask constant answer fitted on the test labels.
103
+ Fine-tuned rows are trained on Clinical3D-Train, which is not part of this release.
104
+ `leaderboard.csv` holds the same table and the `--model` key that reproduces each row (see below).
105
+
106
+ **Adding your model:** run the protocol below, score it with `clinical3d_eval.score`, and open a discussion on this
107
+ repository with your prediction file and the model's details (frames, resolution, prompting).
108
+
109
+ ## Files
110
+
111
+ ```
112
+ questions.jsonl 3,368 questions with answers (one JSON object per line)
113
+ videos/<clip>.mp4 photorealistic clip, the model input: 768x448, 6 fps, 60 frames (10 s)
114
+ videos_render/<clip>.mp4 the path-traced render it was made from: same camera path, same 60 frames
115
+ masks/render/<clip>.npz per-frame instance masks of the render (exact)
116
+ masks/video/<clip>.npz per-frame instance masks of the photorealistic clip
117
+ objects/<clip>.json object_id / part_id -> entity name and category
118
+ subsets/mini_ids.txt the 400 questions the physicians answered (Clinical3D-Bench-mini)
119
+ subsets/blind_flagged_ids.txt 739 questions flagged by the blind filter (excluded by the debiased score)
120
+ leaderboard.csv the leaderboard above
121
+ code/ evaluation code (clinical3d_eval) and examples
122
+ ```
123
+
124
+ ### Questions
125
+
126
+ ```json
127
+ {"id": "3010d94944f9ca88", "clip": "corridor_param_002_a", "video": "videos/corridor_param_002_a.mp4",
128
+ "n_frames": 60, "fps": 6, "type": "Count", "task": "A1", "subtask": "offscreen_count",
129
+ "question": "Of the wheelchairs that have appeared up to 5.0 s into the video, ...",
130
+ "choices": ["0", "1", "2", "3", "4 or more"],
131
+ "answer": 1, "answer_letter": "B", "time_anchors_s": [5.0],
132
+ "layout": "corridor_param_002", "family": "corridor", "state": "a", "pair_key": "baf814bb10af63c0",
133
+ "evidence": [{"kind": "object", "key": "parked_wheelchair_1"}, ...],
134
+ "blind_flagged": false, "in_mini": false}
135
+ ```
136
+
137
+ | Field | Meaning |
138
+ |---|---|
139
+ | `type` | one of the eight question types (the leaderboard columns) |
140
+ | `task`, `subtask` | the generator's finer subtask (several subtasks are pooled into one type) |
141
+ | `question`, `choices` | the question and its answer options |
142
+ | `answer` | the index of the correct choice (0 = A) |
143
+ | `time_anchors_s` | the times the question refers to |
144
+ | `anchor_frames` | Re-ID only: the two frame indices the question names; they are added to the sampled frames |
145
+ | `layout`, `state` | a layout's states (a, b, c) share the camera path and differ in one clinical fact |
146
+ | `pair_key` | questions from the same template on the states of one layout |
147
+ | `evidence` | the objects or parts (`objects/<clip>.json` keys) that the answer depends on |
148
+ | `blind_flagged` | flagged by the blind filter (text-only models and a text-statistics test); kept in the main score |
149
+ | `in_mini` | in the 400-question physician subset |
150
+
151
+ | Type | The question asks | #Q |
152
+ |---|---|---|
153
+ | Count | how many instances of a category seen so far are out of view at time t | 365 |
154
+ | Re-ID | which instance at t′ is the leftmost one of its category at t | 195 |
155
+ | Light owner | which bed the lit bed-head light belongs to | 63 |
156
+ | Patient frame | whether an object is on the supine patient's left or right | 759 |
157
+ | Device ref. | what the device nearest a named landmark is mounted on, or which bed label it carries | 128 |
158
+ | Direction | the first turn on the shortest walkable route, or the goal's quadrant from the start pose | 962 |
159
+ | Route | the missing turns of the shortest route, or which goal is nearest by walking | 380 |
160
+ | Passability | whether a crash cart or transport bed can reach the goal or pass along a marked route | 516 |
161
+
162
+ ### Masks
163
+
164
+ All masks are on the 768×448 raster of the videos, frame `i` of the mask matching frame `i` of the video.
165
+
166
+ - `masks/render/<clip>.npz`: `object_id` and `part_id`, uint16 arrays of shape (60, 448, 768), with 0 for
167
+ background. They are exact for `videos_render/<clip>.mp4`.
168
+ - `masks/video/<clip>.npz`: `object_id` (60, 448, 768) for `videos/<clip>.mp4`, plus `source` (60,) and `valid` (60,).
169
+ - `source[i] = "src"`: the photorealistic frame lies on the render's camera path, so the render's mask is used.
170
+ - `source[i] = "warp"`: the render's instances are re-projected (with depth and z-buffering) to the frame's estimated pose.
171
+ - `source[i] = "none"`: no trustworthy mask; `valid[i]` is False and the frame is all zeros.
172
+
173
+ Over all clips the frames are 30,901 src, 1,744 warp and 1,495 none. Photorealistic frames have no part masks.
174
+ - `objects/<clip>.json` maps `object_id` to its entity and category (`structural` marks walls, doors and the like),
175
+ `part_id` to its part (for example `door_04/call_light`), and lists small wall-mounted items.
176
+
177
+ ```python
178
+ import json, numpy as np
179
+ m = np.load('masks/video/corridor_param_002_a.npz')
180
+ objs = json.load(open('objects/corridor_param_002_a.json'))
181
+ wheelchair = next(o['object_id'] for o in objs['objects'] if o['entity'] == 'parked_wheelchair_3')
182
+ frame30 = (m['object_id'][30] == wheelchair) if m['valid'][30] else None
183
+ ```
184
+
185
+ `code/examples/show_masks.py` overlays a question's evidence objects on a frame.
186
+
187
+ ## Evaluation protocol
188
+
189
+ 1. **Frames.** Each question gets 32 frames sampled uniformly from its 60-frame clip, with indices
190
+ `round(linspace(0, 59, 32))`, or the model's own frame budget (the "Frames" column). For the 195 Re-ID questions,
191
+ the two frames the question names are added if they are not already sampled.
192
+ 2. **Prompt.** Every frame is preceded by its timestamp (`[2.5 s]`). After the frames come the question, the lettered
193
+ options and "Answer with the letter of the correct option only."
194
+ 3. **Decoding.** Greedy. Models with a reasoning mode use it, and the final letter is parsed from the reply.
195
+ 4. **Scoring.** Per-type accuracy pools a type's subtasks by question. **Avg.** is the macro average over the eight
196
+ types (chance 32.7).
197
+
198
+ ### Code
199
+
200
+ ```bash
201
+ cd code
202
+ python -m clinical3d_eval.run --list # the models of the leaderboard and their settings
203
+ python -m clinical3d_eval.run --model qwen3vl_8b --data .. --out preds/qwen3vl_8b.jsonl --batch 4
204
+ python -m clinical3d_eval.score --data .. --preds preds/*.jsonl # full set
205
+ python -m clinical3d_eval.score --data .. --preds preds/*.jsonl --subset debiased # without blind-flagged questions
206
+ python -m clinical3d_eval.score --data .. --preds preds/*.jsonl --subset mini # physician subset
207
+ ```
208
+
209
+ - `run.py` decodes the needed frames with ffmpeg into `<data>/.frames/`.
210
+ - `--weights` takes a local checkpoint directory or a Hugging Face repo id (default: the model's repo id).
211
+ - `--render` evaluates on the source renders instead of the photorealistic clips.
212
+ - A prediction file has one line per question: `{"id": ..., "pred": <option index or null>}`.
213
+
214
+ Examples in `code/examples/`:
215
+
216
+ - `run_open_models.sh`: Qwen2.5-VL, Qwen3-VL, InternVL3 / 3.5, LLaVA-NeXT-Video and Kimi-VL, then scoring.
217
+ - `run_api_models.sh`: GPT-5.5, Gemini 3.6 Flash and Claude Sonnet 5.5. These use 10 frames at 480×288, no
218
+ reasoning, and a reply constrained to one letter. Keys come from `OPENAI_API_KEY`, `GEMINI_API_KEY` and `ANTHROPIC_API_KEY`.
219
+ - `custom_model.py`: the protocol around your own model, with one function to replace.
220
+ - `show_masks.py`: draws masks on a frame.
221
+
222
+ Dependencies by model family:
223
+
224
+ | Models | Needs |
225
+ |---|---|
226
+ | Qwen2.5-VL, Qwen3-VL, SpaceR, VST, SenseNova-SI (Qwen) | `transformers>=4.57`, `qwen-vl-utils`, `torch` |
227
+ | Qwen3-VL-32B (FP8), MiMo-VL | `vllm>=0.11` |
228
+ | InternVL3 / 3.5, SenseNova-SI (InternVL) | `transformers`, `torchvision`, `flash-attn`, `timm`, `einops` |
229
+ | Llama-3.2-Vision, LLaVA-CoT, SpaceLLaVA, LLaVA-NeXT-Video | `transformers` |
230
+ | Kimi-VL | `vllm==0.9.2` |
231
+ | DeepSeek-VL2 | the `deepseek_vl2` package (two GPUs) |
232
+ | Spatial-MLLM | the upstream repository (https://github.com/THU-SI/Spatial-MLLM); set `SPATIAL_MLLM_UPSTREAM` to it |
233
+ | API models | `requests` (OpenAI, Gemini), `anthropic` (Claude), `pillow` |
234
+ | All | `ffmpeg`, `numpy`, `pillow` |
235
+
236
+ The rows VideoJev-4B and Qwen3-VL-4B were run with the fine-tuning codebase's input pipeline (20 frames at 2 fps, and
237
+ 16 frames at 480×288), so `run.py` has no key for them.
238
+
239
+ ## How the data was made
240
+
241
+ 1. **Scenes.** Each room family has a generator that follows hospital design guidance. Free-standing equipment uses
242
+ NVIDIA SimReady assets (CC BY 4.0); everything else is built procedurally.
243
+ 2. **Renders.** A camera walks through the room at eye height (1.55 m, 90° horizontal field of view) and passes every bed. The walk is path-traced in Blender.
244
+ 3. **Questions.** Questions are instantiated from templates over the scene record. Checks on evidence
245
+ visibility, answer margins and shortcuts keep them answerable and unambiguous.
246
+ 4. **Photorealistic clips.** Keyframes are edited with an image model, and the render plus the edited keyframes condition a
247
+ video-to-video model. Each clip is registered to its render by feature matching and PnP on the rendered depth. It
248
+ passes if at least 75% of its frames lie on the source path (649 of 657 clips pass).
249
+ 5. **Physician screening.** Physicians rated one clip of every layout. A layout is dropped if either rater gives a
250
+ score of 2 or lower on plausibility, realism or clinical usability.
251
+
252
+ The scenes are simulated and contain no patients or personal data.
253
+
254
+ ## Citation
255
+
256
+ ```bibtex
257
+ @misc{clinical3dbench,
258
+ title = {Clinical3D-Bench: Evaluating and Improving Spatial Intelligence of Multimodal LLMs in Hospital Environments},
259
+ year = {2026}
260
+ }
261
+ ```
assets/teaser.png ADDED

Git LFS Details

  • SHA256: 6439c25ca674109aeb9dea55d89bab2c92d09ce7aee49d02f5c5e0de0fccdccf
  • Pointer size: 132 Bytes
  • Size of remote file: 1.4 MB
code/clinical3d_eval/__init__.py ADDED
File without changes
code/clinical3d_eval/prompt.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Model-agnostic prompt: timestamped frames, the question, lettered options, answer with a letter."""
2
+ import re
3
+
4
+ LETTERS = 'ABCDEFGH'
5
+ HEADER = ('The following {k} frames are sampled in time order from one video of a walk through a hospital room. '
6
+ 'Each frame is preceded by its timestamp.')
7
+ FOOTER = 'Answer with the letter of the correct option only.'
8
+ FOOTER_NUMERIC = 'Answer with a single number only.'
9
+
10
+
11
+ def frame_label(t):
12
+ return f'[{t:.1f} s]'
13
+
14
+
15
+ def build_messages(item, frames, times, with_video=True, footer=None):
16
+ """Return a list of ('text'|'image', value) segments: the header, then a timestamp label and an image per
17
+ frame, then the question, the lettered options and the answer instruction."""
18
+ seg = []
19
+ if with_video:
20
+ seg.append(('text', HEADER.format(k=len(frames))))
21
+ for p, t in zip(frames, times):
22
+ seg.append(('text', frame_label(t)))
23
+ seg.append(('image', str(p)))
24
+ if item.get('answer_type') == 'numeric':
25
+ seg.append(('text', f"{item['question']}\n{FOOTER_NUMERIC}"))
26
+ return seg
27
+ opts = '\n'.join(f'{LETTERS[i]}. {c}' for i, c in enumerate(item['choices']))
28
+ seg.append(('text', f"{item['question']}\n{opts}\n{footer or FOOTER}"))
29
+ return seg
30
+
31
+
32
+ def parse_number(raw):
33
+ """First number in the reply, as a float; None if absent."""
34
+ m = re.search(r'-?\d+(?:\.\d+)?', raw)
35
+ return float(m.group()) if m else None
36
+
37
+
38
+ def parse_answer(raw, item):
39
+ return parse_number(raw) if item.get('answer_type') == 'numeric' else parse_letter(raw, len(item['choices']))
40
+
41
+
42
+ def parse_letter(raw, n_choices):
43
+ """First standalone option letter in the reply (e.g. 'B', 'B.', '(B)', 'Answer: B'); None if absent."""
44
+ m = re.search(r'(?<![A-Za-z])([A-H])(?![A-Za-z])', raw.strip())
45
+ if m and LETTERS.index(m.group(1)) < n_choices:
46
+ return LETTERS.index(m.group(1))
47
+ return None
code/clinical3d_eval/run.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run a registered MLLM on Clinical3D-Bench with the paper's protocol.
2
+
3
+ python -m clinical3d_eval.run --model qwen3vl_8b --data /path/to/Clinical3D-Bench --out preds/qwen3vl_8b.jsonl
4
+ python -m clinical3d_eval.run --list
5
+
6
+ Each question gets 32 frames (or the model's frame budget, see --list) chosen as round(linspace(0, 59, k)) from its
7
+ 60-frame clip, plus the two frames a Re-ID question names (anchor_frames) when they are not already sampled. Every
8
+ frame is preceded by its timestamp; the question and lettered options follow; greedy decoding.
9
+
10
+ --weights is a local checkpoint directory or a Hugging Face repo id (default: the spec's repo id).
11
+ --render evaluates on the source renders (videos_render/) instead of the photorealistic clips.
12
+ Resumable: ids already in --out are skipped. Score with python -m clinical3d_eval.score.
13
+ """
14
+ import argparse
15
+ import hashlib
16
+ import json
17
+ import time
18
+ from pathlib import Path
19
+
20
+ from clinical3d_eval.prompt import FOOTER, build_messages
21
+ from clinical3d_eval.sampling import extract_frames, protocol_indices
22
+ from clinical3d_eval.vlm import registry
23
+ from clinical3d_eval.vlm.base import COT_FOOTER, parse_reply
24
+
25
+
26
+ def segments(it, spec, frames_k, data, cache, video_dir):
27
+ idx = protocol_indices(it['n_frames'], frames_k, it.get('anchor_frames', []))
28
+ frames = extract_frames(data / video_dir / f"{it['clip']}.mp4", idx, cache / video_dir / it['clip'])
29
+ seg = build_messages(it, frames, [i / it['fps'] for i in idx])
30
+ if spec['mode'] == 'cot': # same question, reasoning asked for before the letter
31
+ kind, text = seg[-1]
32
+ seg[-1] = (kind, text.replace(FOOTER, COT_FOOTER))
33
+ return seg, len(frames)
34
+
35
+
36
+ def main():
37
+ ap = argparse.ArgumentParser()
38
+ ap.add_argument('--model')
39
+ ap.add_argument('--weights')
40
+ ap.add_argument('--data', type=Path, help='the dataset directory (questions.jsonl, videos/)')
41
+ ap.add_argument('--out', type=Path)
42
+ ap.add_argument('--cache', type=Path, help='where decoded frames go (default <data>/.frames)')
43
+ ap.add_argument('--render', action='store_true', help='use videos_render/ (source renders)')
44
+ ap.add_argument('--batch', type=int, default=1)
45
+ ap.add_argument('--limit', type=int, help='first N questions only (smoke test)')
46
+ ap.add_argument('--shard', type=int, nargs=2, metavar=('K', 'N'), help='questions k, k+n, k+2n, ...')
47
+ ap.add_argument('--list', action='store_true')
48
+ a = ap.parse_args()
49
+ reg = registry()
50
+ if a.list:
51
+ for k, s in reg.items():
52
+ print(f"{k:30s} {s['hf']:46s} frames={s['frames']:<3d} mode={s['mode']:7s} {s['note']}")
53
+ return
54
+ spec = reg[a.model]
55
+ items = [json.loads(l) for l in (a.data / 'questions.jsonl').read_text().splitlines()]
56
+ if a.shard:
57
+ items = items[a.shard[0]::a.shard[1]]
58
+ if a.limit:
59
+ items = items[:a.limit]
60
+ done = {json.loads(l)['id'] for l in a.out.read_text().splitlines()} if a.out.exists() else set()
61
+ todo = [it for it in items if it['id'] not in done]
62
+ a.out.parent.mkdir(parents=True, exist_ok=True)
63
+ print(a.model, 'todo', len(todo), 'of', len(items), flush=True)
64
+ if not todo:
65
+ return
66
+ video_dir = 'videos_render' if a.render else 'videos'
67
+ cache = a.cache or a.data / '.frames'
68
+ mod = __import__(f'clinical3d_eval.vlm.{spec["module"]}', fromlist=['x'])
69
+ adapter = getattr(mod, spec['adapter'])(a.weights or spec['hf'], spec)
70
+ adapter.load()
71
+ for k in range(0, len(todo), a.batch):
72
+ batch = todo[k:k + a.batch]
73
+ segs = [segments(it, spec, spec['frames'], a.data, cache, video_dir) for it in batch]
74
+ t0 = time.monotonic()
75
+ raws = adapter.generate([s for s, _ in segs])
76
+ seconds = round((time.monotonic() - t0) / len(batch), 2)
77
+ with a.out.open('a') as f:
78
+ for it, (seg, n_img), raw in zip(batch, segs, raws):
79
+ text = json.dumps([v if kind == 'text' else '<image>' for kind, v in seg], ensure_ascii=False)
80
+ rec = dict(id=it['id'], model=a.model, video=video_dir, frames=spec['frames'], n_images=n_img,
81
+ raw=raw, pred=parse_reply(raw, it, spec['mode']), seconds=seconds,
82
+ prompt_sha256=hashlib.sha256(text.encode()).hexdigest())
83
+ f.write(json.dumps(rec, ensure_ascii=False) + '\n')
84
+ print(it['id'], repr(raw.strip()[-30:]), rec['pred'], seconds, flush=True)
85
+
86
+
87
+ if __name__ == '__main__':
88
+ main()
code/clinical3d_eval/sampling.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Frame sampling exactly as stated in the paper (supplement, Protocol), and frame extraction from the released MP4."""
2
+ import os
3
+ import shutil
4
+ import subprocess
5
+ import tempfile
6
+ from pathlib import Path
7
+
8
+ import numpy as np
9
+
10
+
11
+ def protocol_indices(n, k, anchor_frames=()):
12
+ """k uniform indices round(linspace(0, n-1, k)), plus any anchored frames (disclosed rule)."""
13
+ idx = set(np.round(np.linspace(0, n - 1, min(k, n))).astype(int).tolist())
14
+ idx |= {int(a) for a in anchor_frames}
15
+ return sorted(idx)
16
+
17
+
18
+ def extract_frames(video, indices, out_dir):
19
+ """Decode the given frame indices from the MP4 (what any participant would see) into JPEG files."""
20
+ out_dir = Path(out_dir)
21
+ out_dir.mkdir(parents=True, exist_ok=True)
22
+ paths = [out_dir / f'{i:04d}.jpg' for i in indices]
23
+ missing = [i for i, p in zip(indices, paths) if not p.exists()]
24
+ if missing:
25
+ # Private temp dir per call: shards of one run share out_dir, and shared tmp names let one process
26
+ # rename another's frame under the wrong index. Final renames are atomic and same-index files identical.
27
+ tmp_dir = Path(tempfile.mkdtemp(prefix='.extract_', dir=out_dir))
28
+ try:
29
+ sel = '+'.join(f'eq(n\\,{i})' for i in missing)
30
+ subprocess.run(['ffmpeg', '-hide_banner', '-loglevel', 'error', '-y', '-i', str(video),
31
+ '-vf', f'select={sel}', '-vsync', '0', '-q:v', '2', str(tmp_dir / '%04d.jpg')], check=True)
32
+ got = sorted(tmp_dir.glob('*.jpg'))
33
+ if len(got) != len(missing):
34
+ raise RuntimeError(f'{video}: decoded {len(got)} of {len(missing)} frames')
35
+ for f, i in zip(got, missing):
36
+ os.replace(f, out_dir / f'{i:04d}.jpg')
37
+ finally:
38
+ shutil.rmtree(tmp_dir, ignore_errors=True)
39
+ return paths
40
+
code/clinical3d_eval/score.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Score prediction files on Clinical3D-Bench.
2
+
3
+ python -m clinical3d_eval.score --data /path/to/Clinical3D-Bench --preds preds/*.jsonl [--subset full|debiased|mini]
4
+
5
+ A prediction file has one JSON row per question with "id" and "pred" (the option index, 0 = A; null if unparsed).
6
+ Several files for one model (e.g. seeds) are averaged with --average.
7
+
8
+ Accuracy per type pools its subtasks by question; Avg. is the macro average over the eight types and sets the rank.
9
+ Each type's accuracy is rounded to 0.1 % before the macro average.
10
+ full all 3,368 questions (the paper's main table)
11
+ debiased without the 739 blind-flagged questions
12
+ mini the 400-question subset the physicians answered (Clinical3D-Bench-mini)
13
+ """
14
+ import argparse
15
+ import json
16
+ from pathlib import Path
17
+
18
+ TYPES = ['Count', 'Re-ID', 'Light owner', 'Patient frame', 'Device ref.', 'Direction', 'Route', 'Passability']
19
+
20
+
21
+ def score(questions, preds):
22
+ """preds: {id: option index or None}. Missing questions count as wrong."""
23
+ acc = {}
24
+ for t in TYPES:
25
+ qs = [q for q in questions if q['type'] == t]
26
+ acc[t] = round(sum(preds.get(q['id']) == q['answer'] for q in qs) / len(qs), 3) if qs else None
27
+ vals = [v for v in acc.values() if v is not None]
28
+ return dict(types={t: None if v is None else round(100 * v, 1) for t, v in acc.items()},
29
+ avg=round(100 * sum(vals) / len(vals), 1), n=len(questions),
30
+ answered=sum(q['id'] in preds for q in questions),
31
+ unparsed=sum(q['id'] in preds and preds[q['id']] is None for q in questions))
32
+
33
+
34
+ def load_preds(path):
35
+ return {r['id']: r['pred'] for r in map(json.loads, Path(path).read_text().splitlines())}
36
+
37
+
38
+ def main():
39
+ ap = argparse.ArgumentParser()
40
+ ap.add_argument('--data', type=Path, required=True)
41
+ ap.add_argument('--preds', type=Path, nargs='+', required=True)
42
+ ap.add_argument('--subset', choices=['full', 'debiased', 'mini'], default='full')
43
+ ap.add_argument('--average', action='store_true', help='average the given files (seeds of one model)')
44
+ ap.add_argument('--json', type=Path, help='also write the results here')
45
+ a = ap.parse_args()
46
+ qs = [json.loads(l) for l in (a.data / 'questions.jsonl').read_text().splitlines()]
47
+ if a.subset == 'debiased':
48
+ qs = [q for q in qs if not q['blind_flagged']]
49
+ elif a.subset == 'mini':
50
+ qs = [q for q in qs if q['in_mini']]
51
+ res = {p.stem: score(qs, load_preds(p)) for p in a.preds}
52
+ if a.average:
53
+ rs = list(res.values())
54
+ types = {t: None if rs[0]['types'][t] is None else round(sum(r['types'][t] for r in rs) / len(rs), 1)
55
+ for t in TYPES}
56
+ res = {'average': dict(types=types, avg=round(sum(r['avg'] for r in rs) / len(rs), 1), n=rs[0]['n'],
57
+ runs=len(rs))}
58
+ print(f"{'model':32s} " + ' '.join(f'{t[:8]:>8s}' for t in TYPES) + ' Avg.')
59
+ for k, r in res.items():
60
+ print(f'{k:32s} ' + ' '.join(f"{'-' if r['types'][t] is None else r['types'][t]:>8}" for t in TYPES)
61
+ + f" {r['avg']:6.1f}" + (f" ({r['answered']}/{r['n']} answered, {r['unparsed']} unparsed)"
62
+ if 'answered' in r else ''))
63
+ if a.json:
64
+ a.json.write_text(json.dumps(res, indent=1))
65
+
66
+
67
+ if __name__ == '__main__':
68
+ main()
code/clinical3d_eval/vlm/__init__.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One interface for testing any MLLM on the benchmark (clinical3d_eval.run_vlm).
2
+
3
+ Each module in this package defines MODELS = {key: spec} and the Adapter classes the specs name. A spec is a dict:
4
+ hf Hugging Face repo id of the weights
5
+ adapter Adapter subclass (clinical3d_eval.vlm.base) that loads the weights and generates replies
6
+ frames frames per question (protocol_indices; default 32, fewer only when the model's context cannot take it)
7
+ max_pixels pixels per frame (default 768 * 448)
8
+ mode 'direct' (answer with a letter), 'cot' (reason, then "Answer: X") or 'think' (the model's own
9
+ <think> block, then the answer); parse_reply reads the final answer for each
10
+ max_new_tokens default 16 for direct, 2048 for cot / think
11
+ gpus GPUs the model needs (default 1)
12
+ env name of the Python env it runs in on the cluster (scripts/ops/vlm/README.md)
13
+ note anything that departs from the default protocol (disclosed in the paper's appendix)
14
+ Heavy imports (torch, transformers, model code) belong inside Adapter.load, so listing the registry is cheap.
15
+ """
16
+ import importlib
17
+ import pkgutil
18
+
19
+ DEFAULTS = dict(frames=32, max_pixels=768 * 448, mode='direct', gpus=1, env='env', note='')
20
+
21
+
22
+ def registry():
23
+ out = {}
24
+ for m in pkgutil.iter_modules(__path__):
25
+ if m.name == 'base':
26
+ continue
27
+ mod = importlib.import_module(f'{__name__}.{m.name}')
28
+ for key, spec in getattr(mod, 'MODELS', {}).items():
29
+ if key in out:
30
+ raise KeyError(f'model key {key} defined twice ({m.name})')
31
+ spec = {**DEFAULTS, **spec, 'module': m.name}
32
+ spec.setdefault('max_new_tokens', 16 if spec['mode'] == 'direct' else 2048)
33
+ out[key] = spec
34
+ return out
code/clinical3d_eval/vlm/base.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Adapter base class and the reply parser shared by every model in clinical3d_eval.run_vlm."""
2
+ import re
3
+
4
+ from clinical3d_eval.prompt import LETTERS, parse_answer
5
+
6
+ COT_FOOTER = "Think step by step, then give your final answer on the last line as 'Answer: <letter>'."
7
+
8
+
9
+ class Adapter:
10
+ """Loads one model and turns prompts into replies.
11
+
12
+ segments: [('text', str) | ('image', path)] in order (clinical3d_eval.prompt.build_messages: header, then a timestamp
13
+ label and a frame per sampled frame, then the question, lettered options and the answer instruction).
14
+ """
15
+
16
+ def __init__(self, weights, spec):
17
+ self.weights, self.spec = weights, spec
18
+
19
+ def load(self):
20
+ raise NotImplementedError
21
+
22
+ def generate(self, batch):
23
+ """batch: list of segment lists -> list of reply strings (greedy decoding, spec['max_new_tokens'])."""
24
+ return [self.generate_one(seg) for seg in batch]
25
+
26
+ def generate_one(self, segments):
27
+ raise NotImplementedError
28
+
29
+
30
+ def strip_think(raw):
31
+ """Drop a <think>...</think> block (Kimi-VL: ◁think▷...◁/think▷), or everything up to a lone closing tag; keep
32
+ only the <CONCLUSION> of a LLaVA-CoT reply."""
33
+ raw = re.sub(r'<think>.*?</think>|◁think▷.*?◁/think▷', '', raw, flags=re.S)
34
+ for close in ('</think>', '◁/think▷'):
35
+ raw = raw.split(close)[-1]
36
+ m = re.search(r'<CONCLUSION>(.*?)(?:</CONCLUSION>|$)', raw, flags=re.S)
37
+ return m.group(1) if m else raw
38
+
39
+
40
+ def parse_reply(raw, item, mode):
41
+ """Option index (or number) of the final answer, None if absent.
42
+
43
+ direct: the first standalone letter, as clinical3d_eval.prompt.parse_answer. cot / think: after removing the thinking
44
+ block, the last '<answer>X' / 'Answer: X' / '答案:X' / '\\boxed{X}' / '\\mathbf{X}'; failing that, a reply that is just a letter
45
+ or a letter with that option's text ('D. turn left'), or a last line that is only a letter ('**C**'); a long
46
+ reasoning text without an explicit final answer counts as unparsed (its first letter may be the article 'A').
47
+ """
48
+ if mode == 'direct':
49
+ return parse_answer(raw, item)
50
+ tail = strip_think(raw).strip()
51
+ if item.get('answer_type') == 'numeric':
52
+ return parse_answer(tail, item)
53
+ n = len(item['choices'])
54
+ pats = [r'<answer>\s*\(?([A-H])\)?', r'\\boxed\{\s*\(?([A-H])\)?', r'(?:[Aa]nswer|答案)\**\s*(?:is)?\s*\**\s*[::]?\s*\**\s*\(?([A-H])\)?(?![A-Za-z])',
55
+ r'\\(?:mathbf|textbf|text)\{\s*\(?([A-H])\)?\s*\}']
56
+ for pat in pats:
57
+ hits = re.findall(pat, tail)
58
+ if hits and LETTERS.index(hits[-1]) < n:
59
+ return LETTERS.index(hits[-1])
60
+ if len(tail) <= 20:
61
+ return parse_answer(tail, item)
62
+ m = re.fullmatch(r'\(?([A-H])[.):]\s*(.+)', tail, re.S) # 'D. <that option's text>'
63
+ if m and LETTERS.index(m.group(1)) < n and \
64
+ m.group(2).strip().rstrip('.').lower() == item['choices'][LETTERS.index(m.group(1))].strip().rstrip('.').lower():
65
+ return LETTERS.index(m.group(1))
66
+ m = re.fullmatch(r'[*(\s]*([A-H])[)*.\s]*', tail.splitlines()[-1]) # a last line that is only the letter ('**C**')
67
+ if m and LETTERS.index(m.group(1)) < n:
68
+ return LETTERS.index(m.group(1))
69
+ return None
code/clinical3d_eval/vlm/claude.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Claude through the Anthropic API. Frames go as base64 JPEGs in the protocol's order
2
+ (resized to spec['size']); the frame prefix of a clip is prompt-cached so the other
3
+ questions on the same clip reuse it. The paper's spec turns thinking off and constrains the reply to one option
4
+ letter (structured output). A refusal is kept as an unparsed reply. Key: ANTHROPIC_API_KEY.
5
+ """
6
+ import base64
7
+ import json
8
+ import os
9
+ import time
10
+ from concurrent.futures import ThreadPoolExecutor
11
+ from pathlib import Path
12
+
13
+ from clinical3d_eval.vlm.base import Adapter
14
+
15
+ MODELS = {
16
+ 'claude_sonnet_5_5_nothink_f10': dict(hf='claude-sonnet-5-5', adapter='Claude', env='api', mode='think',
17
+ max_new_tokens=64, thinking=dict(type='between_tools'), frames=10,
18
+ size=(480, 288), letter_only=True,
19
+ note='Sonnet 5.5, thinking off (between_tools), reply constrained to one letter '
20
+ '(structured output), 10 frames 480x288'),
21
+ }
22
+ WORKERS = 8
23
+
24
+
25
+ class Claude(Adapter):
26
+ def load(self):
27
+ import anthropic
28
+ key = os.environ['ANTHROPIC_API_KEY']
29
+ self.client = anthropic.Anthropic(api_key=key, max_retries=8, timeout=600)
30
+
31
+ def jpeg(self, path):
32
+ """The cached frame, resized to spec['size'] (w, h) when the spec sets one."""
33
+ if 'size' not in self.spec:
34
+ return Path(path).read_bytes()
35
+ import io
36
+ from PIL import Image
37
+ buf = io.BytesIO()
38
+ Image.open(path).convert('RGB').resize(self.spec['size'], Image.BICUBIC).save(buf, 'JPEG', quality=95)
39
+ return buf.getvalue()
40
+
41
+ def content(self, segments):
42
+ out, last_img = [], 0
43
+ for kind, v in segments:
44
+ if kind == 'text':
45
+ out.append(dict(type='text', text=v))
46
+ else:
47
+ data = base64.b64encode(self.jpeg(v)).decode()
48
+ out.append(dict(type='image', source=dict(type='base64', media_type='image/jpeg', data=data)))
49
+ last_img = len(out)
50
+ if last_img:
51
+ out[last_img - 1]['cache_control'] = dict(type='ephemeral') # header + frames: shared by the clip
52
+ return out
53
+
54
+ def generate_one(self, segments):
55
+ oc = dict(effort=self.spec['effort']) if 'effort' in self.spec else {}
56
+ if self.spec.get('letter_only'): # structured output: the reply is {"answer": "<letter>"}
57
+ oc['format'] = dict(type='json_schema', schema=dict(
58
+ type='object', properties=dict(answer=dict(type='string', enum=list('ABCDEFGH'))),
59
+ required=['answer'], additionalProperties=False))
60
+ extra = dict(output_config=oc) if oc else {}
61
+ r = self.client.messages.create(model=self.spec['hf'], max_tokens=self.spec['max_new_tokens'],
62
+ thinking=self.spec.get('thinking', dict(type='adaptive')), **extra,
63
+ messages=[dict(role='user', content=self.content(segments))])
64
+ self.usage.append(r.usage)
65
+ if r.stop_reason == 'refusal':
66
+ return '[refusal]'
67
+ text = ''.join(b.text for b in r.content if b.type == 'text')
68
+ if self.spec.get('letter_only'):
69
+ try:
70
+ return json.loads(text)['answer']
71
+ except (ValueError, KeyError, TypeError):
72
+ return text
73
+ return text
74
+
75
+ def generate(self, batch):
76
+ """First question of each frame prefix alone (writes the cache), then the rest in parallel (read it)."""
77
+ self.usage = []
78
+ key = [tuple(str(v) for kind, v in s if kind == 'image') for s in batch]
79
+ first = {}
80
+ for i, k in enumerate(key):
81
+ first.setdefault(k, i)
82
+ out = [None] * len(batch)
83
+ with ThreadPoolExecutor(WORKERS) as ex:
84
+ for i, raw in zip(first.values(), ex.map(self.generate_one, [batch[i] for i in first.values()])):
85
+ out[i] = raw
86
+ rest = [i for i in range(len(batch)) if out[i] is None]
87
+ for i, raw in zip(rest, ex.map(self.generate_one, [batch[i] for i in rest])):
88
+ out[i] = raw
89
+ u = self.usage
90
+ print('usage in', sum(x.input_tokens for x in u), 'cache_w', sum(x.cache_creation_input_tokens or 0 for x in u),
91
+ 'cache_r', sum(x.cache_read_input_tokens or 0 for x in u), 'out', sum(x.output_tokens for x in u),
92
+ time.strftime('%H:%M:%S'), flush=True)
93
+ return out
code/clinical3d_eval/vlm/deepseek.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """DeepSeek-VL2 (27B MoE, 4.1B active) through the deepseek_vl2 package (model card usage), bf16 on 2 GPUs.
2
+
3
+ Prompt: the package's 'deepseek' conversation template with an empty system prompt, one user turn
4
+ ('<|User|>: {content}\n\n<|Assistant|>:'), the segments joined by newlines and each frame as '<image>'. Its context is
5
+ 4096 tokens; with more than two images the processor does no dynamic tiling (each frame is the 384 x 384 global view
6
+ plus one 384 x 384 local tile, ~420 tokens). 16 frames take ~7,000 tokens (replies were garbage), 8 frames plus two
7
+ anchor frames 4,380; 7 frames (at most 9 with anchors) take at most 3,962, so 7 is the most that fits every question.
8
+ Greedy, with the card's incremental (chunked) prefill; layers split over two GPUs with HF device_map.
9
+ """
10
+ from clinical3d_eval.vlm.base import Adapter
11
+
12
+ MODELS = {
13
+ 'deepseek_vl2': dict(hf='deepseek-ai/deepseek-vl2', adapter='DeepSeekVL2', env='dsvl2', frames=7, gpus=2,
14
+ note='7 frames (most that fit its 4096-token context with anchor frames: ~420 tokens per '
15
+ "frame); no dynamic tiling (the package's rule for more than two images); HF bf16 over "
16
+ '2 GPUs with chunked prefill'),
17
+ }
18
+
19
+
20
+ class DeepSeekVL2(Adapter):
21
+ def load(self):
22
+ import torch
23
+ from accelerate import infer_auto_device_map, init_empty_weights
24
+ from deepseek_vl2.models import DeepseekVLV2ForCausalLM, DeepseekVLV2Processor
25
+ from transformers import AutoConfig
26
+ self.torch = torch
27
+ self.proc = DeepseekVLV2Processor.from_pretrained(self.weights)
28
+ cfg = AutoConfig.from_pretrained(self.weights)
29
+ with init_empty_weights():
30
+ empty = DeepseekVLV2ForCausalLM._from_config(cfg, torch_dtype=torch.bfloat16)
31
+ n = torch.cuda.device_count()
32
+ mem = {i: f'{30 if i else 25}GiB' for i in range(n)} # ~52 GiB of weights; the rest for loading + activations
33
+ dmap = infer_auto_device_map(empty, max_memory=mem, dtype=torch.bfloat16,
34
+ no_split_module_classes=['DeepseekV2DecoderLayer', 'VisionTransformer', 'MlpProjector'])
35
+ for k in ('vision', 'projector', 'image_newline', 'view_seperator', 'language.model.embed_tokens'):
36
+ dmap[k] = 0
37
+ assert set(dmap.values()) <= set(range(n)), f'weights do not fit on {n} GPUs: {set(dmap.values())}'
38
+ self.model = DeepseekVLV2ForCausalLM.from_pretrained(self.weights, torch_dtype=torch.bfloat16,
39
+ device_map=dmap).eval()
40
+ torch.cuda.empty_cache()
41
+
42
+ def generate_one(self, segments):
43
+ from PIL import Image
44
+ body = '\n'.join(v if k == 'text' else '<image>' for k, v in segments)
45
+ images = [Image.open(v).convert('RGB') for k, v in segments if k == 'image']
46
+ conv = [dict(role='<|User|>', content=body), dict(role='<|Assistant|>', content='')]
47
+ inp = self.proc(conversations=conv, images=images, force_batchify=True, system_prompt='').to('cuda:0')
48
+ tok = self.proc.tokenizer
49
+ with self.torch.inference_mode():
50
+ # the card's incremental_prefilling (chunks of 512, all but the last token), keeping each layer's cache on
51
+ # its own GPU (the package moves caches to CPU and back onto one GPU, which breaks a two-GPU split)
52
+ emb = self.model.prepare_inputs_embeds(input_ids=inp.input_ids, images=inp.images,
53
+ images_seq_mask=inp.images_seq_mask,
54
+ images_spatial_crop=inp.images_spatial_crop)
55
+ past, n = None, emb.shape[1] - 1
56
+ for s in range(0, n, 512):
57
+ e = min(s + 512, n)
58
+ pos = self.torch.arange(s, e, device=emb.device).unsqueeze(0)
59
+ past = self.model.language(inputs_embeds=emb[:, s:e], attention_mask=inp.attention_mask[:, :e],
60
+ past_key_values=past, position_ids=pos, use_cache=True).past_key_values
61
+ past = past.to_legacy_cache() if hasattr(past, 'to_legacy_cache') else past
62
+ out = self.model.generate(
63
+ inputs_embeds=emb, input_ids=inp.input_ids, images=inp.images, images_seq_mask=inp.images_seq_mask,
64
+ images_spatial_crop=inp.images_spatial_crop, attention_mask=inp.attention_mask, past_key_values=past,
65
+ pad_token_id=tok.eos_token_id, bos_token_id=tok.bos_token_id, eos_token_id=tok.eos_token_id,
66
+ max_new_tokens=self.spec['max_new_tokens'], do_sample=False, use_cache=True)
67
+ return tok.decode(out[0][len(inp.input_ids[0]):].cpu().tolist(), skip_special_tokens=True)
code/clinical3d_eval/vlm/gemini.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Gemini through the Gemini API generateContent endpoint. Frames go as inline base64 JPEGs in
2
+ the protocol's order, resized to spec['size']; no thinking (thinkingBudget 0; the thoughts token count of every reply is
3
+ logged to check it) and the reply constrained to one option letter by a response schema, as openai_api.py (10 frames
4
+ 480x288). Gemini 3.x Pro cannot turn thinking off, so the main-table spec is
5
+ 3.6 Flash. Key: GEMINI_API_KEY.
6
+ """
7
+ import base64
8
+ import io
9
+ import json
10
+ import os
11
+ import time
12
+ from concurrent.futures import ThreadPoolExecutor
13
+ from pathlib import Path
14
+
15
+ from clinical3d_eval.vlm.base import Adapter
16
+
17
+ MODELS = {
18
+ # gemini-3.8-flash still thinks (~245 thought tokens per video question) with thinkingBudget 0, so 3.6 Flash
19
+ 'gemini_3_6_flash_nothink_f10': dict(hf='gemini-3.6-flash', adapter='Gemini', env='api', mode='think',
20
+ thinking=dict(thinkingBudget=0), max_new_tokens=32, frames=10, size=(480, 288),
21
+ note='Gemini 3.6 Flash, thinking budget 0 (0 thought tokens), reply constrained '
22
+ 'to one letter (response schema), 10 frames 480x288'),
23
+ }
24
+ URL = 'https://generativelanguage.googleapis.com/v1beta/models/{}:generateContent'
25
+ WORKERS = 8
26
+ SCHEMA = dict(type='OBJECT', properties=dict(answer=dict(type='STRING', enum=list('ABCDEFGH'))), required=['answer'])
27
+
28
+
29
+ class Gemini(Adapter):
30
+ def load(self):
31
+ import requests
32
+ self.http = requests.Session()
33
+ self.key = os.environ['GEMINI_API_KEY']
34
+
35
+ def jpeg(self, path):
36
+ from PIL import Image
37
+ buf = io.BytesIO()
38
+ Image.open(path).convert('RGB').resize(self.spec['size'], Image.BICUBIC).save(buf, 'JPEG', quality=95)
39
+ return base64.b64encode(buf.getvalue()).decode()
40
+
41
+ def body(self, segments):
42
+ parts = [dict(text=v) if kind == 'text' else dict(inline_data=dict(mime_type='image/jpeg', data=self.jpeg(v)))
43
+ for kind, v in segments]
44
+ return dict(contents=[dict(role='user', parts=parts)],
45
+ generationConfig=dict(maxOutputTokens=self.spec['max_new_tokens'], thinkingConfig=self.spec['thinking'],
46
+ responseMimeType='application/json', responseSchema=SCHEMA))
47
+
48
+ def generate_one(self, segments):
49
+ body = self.body(segments)
50
+ for attempt in range(8):
51
+ r = self.http.post(URL.format(self.spec['hf']), json=body, timeout=600, headers={'x-goog-api-key': self.key})
52
+ if r.status_code == 200:
53
+ break
54
+ if r.status_code not in (408, 409, 429) and r.status_code < 500:
55
+ raise RuntimeError(f'{r.status_code} {r.text[:500]}')
56
+ time.sleep(2 ** attempt)
57
+ d = r.json()
58
+ self.usage.append(d.get('usageMetadata', {}))
59
+ c = (d.get('candidates') or [{}])[0]
60
+ text = ''.join(p.get('text', '') for p in c.get('content', {}).get('parts', []) if not p.get('thought'))
61
+ try:
62
+ return json.loads(text)['answer']
63
+ except (ValueError, KeyError, TypeError):
64
+ return text or f"[{c.get('finishReason') or d.get('promptFeedback')}]"
65
+
66
+ def generate(self, batch):
67
+ self.usage = []
68
+ with ThreadPoolExecutor(WORKERS) as ex:
69
+ out = list(ex.map(self.generate_one, batch))
70
+ u = self.usage
71
+ print('usage in', sum(x.get('promptTokenCount', 0) for x in u), 'out', sum(x.get('candidatesTokenCount', 0) for x in u),
72
+ 'thoughts', sum(x.get('thoughtsTokenCount', 0) for x in u),
73
+ 'with thoughts', sum(1 for x in u if x.get('thoughtsTokenCount', 0)), time.strftime('%H:%M:%S'), flush=True)
74
+ return out
code/clinical3d_eval/vlm/internvl.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """InternVL3-family checkpoints (remote code, InternVLChatModel) through Hugging Face transformers.
2
+
3
+ Protocol as clinical3d_eval.run_internvl: every frame is one 448 x 448 tile (resized, InternVL's video recipe max_num=1, no
4
+ thumbnail), given as '<image>' in place of the frame in the segments; the text parts are joined with '\\n' and wrapped
5
+ in the checkpoint's own conversation template (internvl2_5, with its default system message) exactly as
6
+ InternVLChatModel.chat builds it. Batched: left-padded prompts through InternVLChatModel.generate (chat() itself takes
7
+ one prompt, batch_chat one image per prompt). Greedy.
8
+ """
9
+ import math
10
+
11
+ from clinical3d_eval.vlm.base import Adapter
12
+
13
+ MODELS = {
14
+ 'internvl3_78b': dict(
15
+ hf='OpenGVLab/InternVL3-78B', adapter='InternVL3', env='eaglevl', gpus=2, max_pixels=448 * 448,
16
+ vit_layers=11, # ViT-6B + embeddings + lm_head ~ 10 LLM layers of memory, placed on the first GPU
17
+ note='InternVL video recipe: 1 tile (448x448, aspect not kept) per frame; bf16 split over 2 x 80 GB GPUs'),
18
+ 'sensenova_si13_internvl3_8b': dict(
19
+ hf='sensenova/SenseNova-SI-1.3-InternVL3-8B', adapter='InternVL3', env='intern2', max_pixels=448 * 448,
20
+ note='InternVL video recipe: 1 tile (448x448, aspect not kept) per frame, interleaved with the timestamp '
21
+ 'labels; the SenseNova-SI example code would give each of 32 images up to 2 tiles + thumbnail and '
22
+ '"Image-i: <image>" prefixes'),
23
+ 'internvl3_8b': dict(hf='OpenGVLab/InternVL3-8B', adapter='InternVL3', env='intern2', max_pixels=448 * 448),
24
+ 'internvl3_14b': dict(hf='OpenGVLab/InternVL3-14B', adapter='InternVL3', env='intern2', max_pixels=448 * 448),
25
+ 'internvl3_38b': dict(hf='OpenGVLab/InternVL3-38B', adapter='InternVL3', env='intern2', max_pixels=448 * 448),
26
+ 'internvl35_4b': dict(hf='OpenGVLab/InternVL3_5-4B', adapter='InternVL3', env='intern2', max_pixels=448 * 448),
27
+ 'internvl35_8b': dict(hf='OpenGVLab/InternVL3_5-8B', adapter='InternVL3', env='intern2', max_pixels=448 * 448),
28
+ 'internvl35_14b': dict(hf='OpenGVLab/InternVL3_5-14B', adapter='InternVL3', env='intern2', max_pixels=448 * 448),
29
+ 'internvl35_38b': dict(hf='OpenGVLab/InternVL3_5-38B', adapter='InternVL3', env='intern2', max_pixels=448 * 448),
30
+ }
31
+
32
+ MEAN, STD, SIZE = (0.485, 0.456, 0.406), (0.229, 0.224, 0.225), 448
33
+ IMG_START, IMG_END, IMG_CONTEXT = '<img>', '</img>', '<IMG_CONTEXT>'
34
+
35
+
36
+ def dynamic_tiles(im, max_num):
37
+ """InternVL dynamic_preprocess: the tile grid (<= max_num tiles) closest to the image's aspect ratio, plus a
38
+ thumbnail when there is more than one tile."""
39
+ if max_num == 1:
40
+ return [im] # self.tf resizes it to one 448 x 448 tile
41
+ w, h = im.size
42
+ grids = sorted({(i, j) for n in range(1, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1)
43
+ if i * j <= max_num}, key=lambda g: g[0] * g[1])
44
+ best, diff = (1, 1), float('inf')
45
+ for g in grids:
46
+ d = abs(w / h - g[0] / g[1])
47
+ if d < diff or (d == diff and w * h > 0.5 * SIZE * SIZE * g[0] * g[1]):
48
+ best, diff = g, d
49
+ big = im.resize((SIZE * best[0], SIZE * best[1]))
50
+ tiles = [big.crop((x * SIZE, y * SIZE, (x + 1) * SIZE, (y + 1) * SIZE))
51
+ for y in range(best[1]) for x in range(best[0])]
52
+ return tiles + [im.resize((SIZE, SIZE))] if len(tiles) > 1 else tiles
53
+
54
+
55
+ def split_model(n_layers, n_gpus, vit_layers):
56
+ """Device map: vision tower, embeddings, norm, lm_head and the last layer on GPU 0, LLM layers balanced so every
57
+ GPU holds about (n_layers + vit_layers) / n_gpus layer-equivalents (the model card's split_model assumes 8-bit)."""
58
+ per = (n_layers + vit_layers) / n_gpus
59
+ counts = [max(0, math.floor(per - vit_layers))] + [math.ceil(per)] * (n_gpus - 1)
60
+ counts[-1] = n_layers - sum(counts[:-1])
61
+ dm, k = {}, 0
62
+ for g, c in enumerate(counts):
63
+ for _ in range(c):
64
+ dm[f'language_model.model.layers.{k}'] = g
65
+ k += 1
66
+ for name in ('vision_model', 'mlp1', 'language_model.model.embed_tokens', 'language_model.model.norm',
67
+ 'language_model.model.rotary_emb', 'language_model.lm_head', f'language_model.model.layers.{n_layers - 1}'):
68
+ dm[name] = 0
69
+ return dm
70
+
71
+
72
+ class InternVL3(Adapter):
73
+
74
+ def load(self):
75
+ import sys
76
+
77
+ import torch
78
+ import torchvision.transforms as T
79
+ from torchvision.transforms.functional import InterpolationMode
80
+ from transformers import AutoTokenizer
81
+ from transformers.dynamic_module_utils import get_class_from_dynamic_module
82
+ self.torch = torch
83
+ # the remote-code classes from the local checkpoint (some fine-tunes' auto_map points at their hub repo)
84
+ cls = lambda ref: get_class_from_dynamic_module(ref, str(self.weights))
85
+ cfg = cls('configuration_internvl_chat.InternVLChatConfig').from_pretrained(self.weights)
86
+ n = torch.cuda.device_count()
87
+ dm = split_model(cfg.llm_config.num_hidden_layers, n, self.spec.get('vit_layers', 10)) if n > 1 else {'': 0}
88
+ self.model = cls('modeling_internvl_chat.InternVLChatModel').from_pretrained(
89
+ self.weights, config=cfg, dtype=torch.bfloat16, low_cpu_mem_usage=True, use_flash_attn=True,
90
+ device_map=dm).eval()
91
+ self.tok = AutoTokenizer.from_pretrained(self.weights, trust_remote_code=True, use_fast=False)
92
+ self.tok.padding_side = 'left'
93
+ self.conv = sys.modules[type(self.model).__module__].get_conv_template
94
+ sep = self.conv(self.model.template).sep.strip()
95
+ self.sep, self.eos = sep, self.tok.convert_tokens_to_ids(sep)
96
+ self.model.img_context_token_id = self.tok.convert_tokens_to_ids(IMG_CONTEXT)
97
+ self.tf = T.Compose([T.Resize((SIZE, SIZE), interpolation=InterpolationMode.BICUBIC), T.ToTensor(),
98
+ T.Normalize(MEAN, STD)])
99
+ self.dev = self.model.vision_model.embeddings.patch_embedding.weight.device
100
+
101
+ def prompt(self, segments, pix):
102
+ from PIL import Image
103
+ parts = []
104
+ for kind, v in segments:
105
+ if kind == 'text':
106
+ parts.append(v)
107
+ else:
108
+ tiles = dynamic_tiles(Image.open(v).convert('RGB'), self.spec.get('tiles', 1))
109
+ parts.append(IMG_START + IMG_CONTEXT * self.model.num_image_token * len(tiles) + IMG_END)
110
+ pix += [self.tf(x) for x in tiles]
111
+ t = self.conv(self.model.template)
112
+ t.system_message = self.model.system_message
113
+ t.append_message(t.roles[0], '\n'.join(parts))
114
+ t.append_message(t.roles[1], None)
115
+ return t.get_prompt() # 1 tile per image unless spec['tiles']
116
+
117
+ def generate(self, batch):
118
+ torch = self.torch
119
+ pix = []
120
+ queries = [self.prompt(seg, pix) for seg in batch]
121
+ enc = self.tok(queries, return_tensors='pt', padding=True)
122
+ pv = torch.stack(pix).to(torch.bfloat16).to(self.dev) if pix else None
123
+ with torch.inference_mode():
124
+ out = self.model.generate(pixel_values=pv, input_ids=enc['input_ids'].to(self.dev),
125
+ attention_mask=enc['attention_mask'].to(self.dev),
126
+ max_new_tokens=self.spec['max_new_tokens'], do_sample=False,
127
+ eos_token_id=self.eos, pad_token_id=self.tok.pad_token_id)
128
+ return [r.split(self.sep)[0].strip() for r in self.tok.batch_decode(out, skip_special_tokens=True)]
code/clinical3d_eval/vlm/kimi.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Kimi-VL-A3B (Instruct / Thinking) through vLLM, with the model's own chat template (chat_template.jinja).
2
+
3
+ The template concatenates the user content items in order (text as is, each image as
4
+ <|media_start|>image<|media_content|><|media_pad|><|media_end|>) after the default system turn; it is rendered here
5
+ as written in the weights, so no remote code is needed for the prompt. Frames go to the model's own image processor
6
+ (MoonViT, native resolution; the released frames are 768 x 448, ~440 tokens each, below in_token_limit 4096).
7
+ Greedy decoding (the card recommends temperature 0.2 / 0.8; the protocol fixes greedy for every model).
8
+ """
9
+ from clinical3d_eval.vlm.base import Adapter
10
+
11
+ NOTE = 'vLLM 0.9.2 (bf16), Kimi chat template; greedy instead of the recommended temperature'
12
+ MODELS = {
13
+ 'kimi_vl_a3b': dict(hf='moonshotai/Kimi-VL-A3B-Instruct', adapter='KimiVL', env='vllm092', mode='direct',
14
+ note=NOTE),
15
+ 'kimi_vl_a3b_thinking': dict(hf='moonshotai/Kimi-VL-A3B-Thinking', adapter='KimiVL', env='vllm092', mode='think',
16
+ max_new_tokens=4096, note=NOTE + ' (0.8); thinking capped at 4096 new tokens'),
17
+ }
18
+
19
+ SYSTEM = '<|im_system|>system<|im_middle|>You are a helpful assistant<|im_end|>'
20
+ IMAGE = '<|media_start|>image<|media_content|><|media_pad|><|media_end|>'
21
+
22
+
23
+ class KimiVL(Adapter):
24
+ def load(self):
25
+ import torch
26
+ from vllm import LLM, SamplingParams
27
+ self.llm = LLM(model=str(self.weights), trust_remote_code=True, dtype='bfloat16',
28
+ tensor_parallel_size=torch.cuda.device_count(), max_model_len=32768,
29
+ limit_mm_per_prompt={'image': 40}, gpu_memory_utilization=0.9, seed=0)
30
+ self.params = SamplingParams(temperature=0.0, max_tokens=self.spec['max_new_tokens'])
31
+
32
+ def prompt(self, segments):
33
+ from PIL import Image
34
+ body = ''.join(v if k == 'text' else IMAGE for k, v in segments)
35
+ images = [Image.open(v).convert('RGB') for k, v in segments if k == 'image']
36
+ text = f'{SYSTEM}<|im_user|>user<|im_middle|>{body}<|im_end|><|im_assistant|>assistant<|im_middle|>'
37
+ return dict(prompt=text, multi_modal_data={'image': images}) if images else dict(prompt=text)
38
+
39
+ def generate(self, batch):
40
+ outs = self.llm.generate([self.prompt(s) for s in batch], self.params, use_tqdm=False)
41
+ return [o.outputs[0].text for o in outs]
code/clinical3d_eval/vlm/llava.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LLaMA-3.2-Vision (+ LLaVA-CoT), SpaceLLaVA (LLaVA-1.5-13B) and LLaVA-NeXT-Video-34B through Hugging Face transformers.
2
+
3
+ Single-image models (Mllama, LLaVA-1.5) get the sampled frames tiled into one grid image in time order (row-major:
4
+ left to right, then top to bottom), each tile labelled with its timestamp; the grid shape is the one whose canvas
5
+ is closest to square. The text keeps the header and question unchanged and lists the tile order with the timestamp
6
+ labels between them (GRID_NOTE). LLaVA-NeXT-Video gets the frames as its native video input; the timestamps go into
7
+ the text the same way (VIDEO_NOTE).
8
+ """
9
+ import math
10
+
11
+ from PIL import Image
12
+
13
+ from clinical3d_eval.vlm.base import Adapter
14
+
15
+ GRID_NOTE = 'The frames are tiled into one image in time order (left to right, then top to bottom), each tile ' \
16
+ 'labelled with its timestamp:'
17
+ VIDEO_NOTE = 'The frames are given as one video, in this order:'
18
+ GRID = 'frames tiled into one grid image in time order (row-major, grid shape closest to a square canvas, ' \
19
+ 'timestamp drawn on each tile; tile order and timestamps listed in the text)'
20
+
21
+ MODELS = {
22
+ # input check: the 16 frames as separate interleaved images (Mllama cross-attends to several images; each
23
+ # 768 x 448 frame keeps 2 tiles of 560 px instead of ~320 x 190 px inside one grid image)
24
+ 'llama32v_11b_mi': dict(hf='meta-llama/Llama-3.2-11B-Vision-Instruct', adapter='MllamaMulti', env='llava',
25
+ frames=16, mode='cot', max_new_tokens=1024,
26
+ note='16 frames as separate interleaved images (timestamp label before each); cot mode'),
27
+ 'llama32v_11b_cot_mi': dict(hf='Xkev/Llama-3.2V-11B-cot', adapter='MllamaMulti', env='llava', frames=16, mode='cot',
28
+ note='LLaVA-CoT; 16 frames as separate interleaved images; greedy; <CONCLUSION> stage'),
29
+ 'spacellava_13b': dict(hf='remyxai/SpaceLLaVA', adapter='SpaceLLaVA', env='llava', frames=8,
30
+ note=f'LLaVA-1.5-13B (original LLaVA weights, loaded into HF Llava with a key map); 8 {GRID}; '
31
+ 'padded to square and resized to 336 px as LLaVA-1.5 (image_aspect_ratio pad); '
32
+ 'llava_v1 conversation format'),
33
+ 'llava_next_video_34b': dict(hf='llava-hf/LLaVA-NeXT-Video-34B-hf', adapter='LlavaNextVideo', env='llava',
34
+ frames=16, note='HF conversion of lmms-lab/LLaVA-NeXT-Video-34B; 16 frames (32 x 144 '
35
+ 'video tokens exceed its 4096-token context) as its native video input (336 px '
36
+ 'center crop, 2x2 pooling); timestamps listed in the text'),
37
+ }
38
+
39
+
40
+ def split(segments):
41
+ """-> header text, timestamp labels, image paths, question text (clinical3d_eval.prompt.build_messages order)."""
42
+ texts = [v for k, v in segments if k == 'text']
43
+ images = [v for k, v in segments if k == 'image']
44
+ if not images:
45
+ return '', [], [], '\n'.join(texts)
46
+ return texts[0], texts[1:1 + len(images)], images, texts[-1]
47
+
48
+
49
+ def grid_shape(n, w, h):
50
+ """cols, rows for n tiles of w x h: canvas closest to square, then fewest empty cells."""
51
+ best = None
52
+ for c in range(1, n + 1):
53
+ r = math.ceil(n / c)
54
+ key = (abs(math.log(c * w / (r * h))), c * r - n)
55
+ if best is None or key < best[0]:
56
+ best = (key, c, r)
57
+ return best[1], best[2]
58
+
59
+
60
+ def tile(paths, labels, label_frac):
61
+ """Row-major grid of the frames with each timestamp drawn in the tile's top-left corner."""
62
+ from PIL import Image, ImageDraw, ImageFont
63
+ ims = [Image.open(p).convert('RGB') for p in paths]
64
+ w, h = ims[0].size
65
+ c, r = grid_shape(len(ims), w, h)
66
+ canvas = Image.new('RGB', (c * w, r * h), (0, 0, 0))
67
+ size = max(12, int(h * label_frac))
68
+ try:
69
+ font = ImageFont.truetype('DejaVuSans-Bold.ttf', size)
70
+ except OSError:
71
+ font = ImageFont.load_default(size)
72
+ for i, (im, lab) in enumerate(zip(ims, labels)):
73
+ x, y = (i % c) * w, (i // c) * h
74
+ canvas.paste(im.resize((w, h)), (x, y))
75
+ d = ImageDraw.Draw(canvas)
76
+ box = d.textbbox((x, y), lab.strip('[]'), font=font)
77
+ d.rectangle((x, y, box[2] + size // 3, box[3] + size // 4), fill=(0, 0, 0))
78
+ d.text((x + size // 6, y), lab.strip('[]'), font=font, fill=(255, 255, 0))
79
+ return canvas
80
+
81
+
82
+ class GridAdapter(Adapter):
83
+ label_frac = 0.1
84
+
85
+ def grid_prompt(self, segments):
86
+ header, labels, images, question = split(segments)
87
+ text = f"{header} {GRID_NOTE} {' '.join(labels)}\n{question}" if images else question
88
+ return text, (tile(images, labels, self.label_frac) if images else None)
89
+
90
+
91
+ class Mllama(GridAdapter):
92
+ """LLaMA-3.2-11B-Vision-Instruct and LLaVA-CoT (same architecture): one image, then the text (model card)."""
93
+
94
+ def load(self):
95
+ import torch
96
+ from transformers import AutoProcessor, MllamaForConditionalGeneration
97
+ self.torch = torch
98
+ self.model = MllamaForConditionalGeneration.from_pretrained(
99
+ self.weights, dtype=torch.bfloat16, device_map='auto').eval()
100
+ self.proc = AutoProcessor.from_pretrained(self.weights)
101
+ self.proc.tokenizer.padding_side = 'left'
102
+
103
+ def generate(self, batch):
104
+ prompts, images = [], []
105
+ for seg in batch:
106
+ text, im = self.grid_prompt(seg)
107
+ msgs = [dict(role='user', content=([dict(type='image')] if im else []) + [dict(type='text', text=text)])]
108
+ prompts.append(self.proc.apply_chat_template(msgs, add_generation_prompt=True))
109
+ images.append([im] if im else [])
110
+ inputs = self.proc(images=images if any(images) else None, text=prompts, add_special_tokens=False,
111
+ padding=True, return_tensors='pt').to(self.model.device)
112
+ with self.torch.inference_mode():
113
+ out = self.model.generate(**inputs, max_new_tokens=self.spec['max_new_tokens'], do_sample=False,
114
+ temperature=None, top_p=None)
115
+ return self.proc.batch_decode(out[:, inputs['input_ids'].shape[1]:], skip_special_tokens=True)
116
+
117
+
118
+ class MllamaMulti(Mllama):
119
+ """Same model, the frames as separate images interleaved with their timestamp labels (no grid)."""
120
+
121
+ def generate(self, batch):
122
+ prompts, images = [], []
123
+ for seg in batch:
124
+ content = [dict(type='image') if k == 'image' else dict(type='text', text=v) for k, v in seg]
125
+ prompts.append(self.proc.apply_chat_template([dict(role='user', content=content)], add_generation_prompt=True))
126
+ images.append([Image.open(v).convert('RGB') for k, v in seg if k == 'image'])
127
+ inputs = self.proc(images=images, text=prompts, add_special_tokens=False, padding=True,
128
+ return_tensors='pt').to(self.model.device)
129
+ with self.torch.inference_mode():
130
+ out = self.model.generate(**inputs, max_new_tokens=self.spec['max_new_tokens'], do_sample=False,
131
+ temperature=None, top_p=None)
132
+ return self.proc.batch_decode(out[:, inputs['input_ids'].shape[1]:], skip_special_tokens=True)
133
+
134
+
135
+ class SpaceLLaVA(GridAdapter):
136
+ """remyxai/SpaceLLaVA ships merged LLaVA-1.5 weights in the original LLaVA layout (LlavaLlamaForCausalLM:
137
+ model.mm_projector, model.vision_tower.vision_tower); they load into transformers' LlavaForConditionalGeneration
138
+ with a key map and the llava-1.5-13b configuration. Image: pad to square with the CLIP mean colour, 336 px."""
139
+ label_frac = 0.16
140
+ system = ("A chat between a curious human and an artificial intelligence assistant. "
141
+ "The assistant gives helpful, detailed, and polite answers to the human's questions.")
142
+
143
+ def load(self):
144
+ import torch
145
+ from transformers import (CLIPImageProcessor, CLIPVisionConfig, LlamaConfig, LlamaTokenizer, LlavaConfig,
146
+ LlavaForConditionalGeneration, LlavaProcessor)
147
+ self.torch = torch
148
+ vision = CLIPVisionConfig(hidden_size=1024, intermediate_size=4096, num_hidden_layers=24, num_attention_heads=16,
149
+ image_size=336, patch_size=14, projection_dim=768, hidden_act='quick_gelu')
150
+ text = LlamaConfig(hidden_size=5120, intermediate_size=13824, num_hidden_layers=40, num_attention_heads=40,
151
+ num_key_value_heads=40, max_position_embeddings=4096, rms_norm_eps=1e-5, vocab_size=32000,
152
+ pad_token_id=0, bos_token_id=1, eos_token_id=2)
153
+ cfg = LlavaConfig(vision_config=vision, text_config=text, image_token_index=32000, projector_hidden_act='gelu',
154
+ vision_feature_select_strategy='default', vision_feature_layer=-2)
155
+ keymap = {r'^model\.vision_tower\.vision_tower\.': 'model.vision_tower.',
156
+ r'^model\.mm_projector\.0\.': 'model.multi_modal_projector.linear_1.',
157
+ r'^model\.mm_projector\.2\.': 'model.multi_modal_projector.linear_2.',
158
+ r'^model\.(?!vision_tower|multi_modal_projector|mm_projector)': 'model.language_model.'}
159
+ self.model, info = LlavaForConditionalGeneration.from_pretrained(
160
+ self.weights, config=cfg, key_mapping=keymap, dtype=torch.float16, device_map='auto',
161
+ output_loading_info=True)
162
+ if info['missing_keys'] or info['unexpected_keys'] or info['mismatched_keys']:
163
+ raise RuntimeError(f'weights do not match: {info}')
164
+ self.model.resize_token_embeddings(32001, mean_resizing=False) # <image> placeholder row (never generated)
165
+ with torch.no_grad():
166
+ self.model.lm_head.weight[32000:] = 0
167
+ self.model.eval()
168
+ tok = LlamaTokenizer.from_pretrained(self.weights)
169
+ tok.add_tokens(['<image>'], special_tokens=True)
170
+ tok.pad_token_id, tok.padding_side = 0, 'left'
171
+ assert tok.convert_tokens_to_ids('<image>') == 32000
172
+ ip = CLIPImageProcessor.from_pretrained(self.weights)
173
+ self.mean = tuple(int(x * 255) for x in ip.image_mean)
174
+ self.proc = LlavaProcessor(image_processor=ip, tokenizer=tok, patch_size=14, image_token='<image>',
175
+ vision_feature_select_strategy='default', num_additional_image_tokens=1)
176
+
177
+ def square(self, im):
178
+ from PIL import Image
179
+ s = max(im.size)
180
+ out = Image.new('RGB', (s, s), self.mean)
181
+ out.paste(im, ((s - im.width) // 2, (s - im.height) // 2))
182
+ return out
183
+
184
+ def generate(self, batch):
185
+ prompts, images = [], []
186
+ for seg in batch:
187
+ text, im = self.grid_prompt(seg)
188
+ prompts.append(f"{self.system} USER: {'<image>' + chr(10) if im else ''}{text} ASSISTANT:")
189
+ if im:
190
+ images.append(self.square(im))
191
+ inputs = self.proc(images=images or None, text=prompts, padding=True, return_tensors='pt').to(
192
+ self.model.device, self.torch.float16)
193
+ with self.torch.inference_mode():
194
+ out = self.model.generate(**inputs, max_new_tokens=self.spec['max_new_tokens'], do_sample=False,
195
+ temperature=None, top_p=None, suppress_tokens=[32000])
196
+ return self.proc.batch_decode(out[:, inputs['input_ids'].shape[1]:], skip_special_tokens=True)
197
+
198
+
199
+ class LlavaNextVideo(Adapter):
200
+ """LLaVA-NeXT-Video-34B (llava-hf): the sampled frames as one <video>, the timestamps in the text (Yi-34B chatml)."""
201
+
202
+ def load(self):
203
+ import torch
204
+ from transformers import LlavaNextVideoForConditionalGeneration, LlavaNextVideoProcessor
205
+ self.torch = torch
206
+ self.model = LlavaNextVideoForConditionalGeneration.from_pretrained(
207
+ self.weights, dtype=torch.bfloat16, device_map='auto').eval()
208
+ self.proc = LlavaNextVideoProcessor.from_pretrained(self.weights)
209
+ self.proc.tokenizer.padding_side = 'left'
210
+
211
+ def generate(self, batch):
212
+ import numpy as np
213
+ from PIL import Image
214
+ prompts, videos = [], []
215
+ for seg in batch:
216
+ header, labels, images, question = split(seg)
217
+ text = f"{header} {VIDEO_NOTE} {' '.join(labels)}\n{question}" if images else question
218
+ msgs = [dict(role='user', content=([dict(type='video')] if images else []) + [dict(type='text', text=text)])]
219
+ prompts.append(self.proc.apply_chat_template(msgs, add_generation_prompt=True))
220
+ if images:
221
+ videos.append(np.stack([np.asarray(Image.open(p).convert('RGB')) for p in images]))
222
+ if len({v.shape[0] for v in videos}) > 1: # the processor needs one frame count per batch
223
+ return [r for seg in batch for r in self.generate([seg])]
224
+ inputs = self.proc(text=prompts, videos=videos or None, padding=True, return_tensors='pt').to(self.model.device)
225
+ with self.torch.inference_mode():
226
+ out = self.model.generate(**inputs, max_new_tokens=self.spec['max_new_tokens'], do_sample=False,
227
+ temperature=None, top_p=None)
228
+ return self.proc.batch_decode(out[:, inputs['input_ids'].shape[1]:], skip_special_tokens=True)
code/clinical3d_eval/vlm/openai_api.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """OpenAI models through the Responses API . Frames go as base64 JPEGs in the protocol's
2
+ order, resized to spec['size']; no reasoning (effort 'none') and the reply constrained to one option letter by a
3
+ JSON schema, the closed-model counterpart of the open models' direct mode.
4
+ Key: OPENAI_API_KEY.
5
+ """
6
+ import base64
7
+ import io
8
+ import json
9
+ import os
10
+ import time
11
+ from concurrent.futures import ThreadPoolExecutor
12
+ from pathlib import Path
13
+
14
+ from clinical3d_eval.vlm.base import Adapter
15
+
16
+ MODELS = {
17
+ 'gpt_5_5_nothink_f10': dict(hf='gpt-5.5', adapter='OpenAIResponses', env='api', mode='think', effort='none',
18
+ max_new_tokens=16, frames=10, size=(480, 288),
19
+ note='gpt-5.5, reasoning effort none, reply constrained to one letter (JSON schema), '
20
+ '10 frames 480x288'),
21
+ }
22
+ URL = 'https://api.openai.com/v1/responses'
23
+ WORKERS = 8
24
+ SCHEMA = dict(type='object', properties=dict(answer=dict(type='string', enum=list('ABCDEFGH'))),
25
+ required=['answer'], additionalProperties=False)
26
+
27
+
28
+ class OpenAIResponses(Adapter):
29
+ def load(self):
30
+ import requests
31
+ self.http = requests.Session()
32
+ self.key = os.environ['OPENAI_API_KEY']
33
+
34
+ def jpeg(self, path):
35
+ from PIL import Image
36
+ buf = io.BytesIO()
37
+ Image.open(path).convert('RGB').resize(self.spec['size'], Image.BICUBIC).save(buf, 'JPEG', quality=95)
38
+ return base64.b64encode(buf.getvalue()).decode()
39
+
40
+ def body(self, segments):
41
+ content = [dict(type='input_text', text=v) if kind == 'text' else
42
+ dict(type='input_image', image_url='data:image/jpeg;base64,' + self.jpeg(v)) for kind, v in segments]
43
+ body = dict(model=self.spec['hf'], input=[dict(role='user', content=content)],
44
+ reasoning=dict(effort=self.spec['effort']), max_output_tokens=self.spec['max_new_tokens'])
45
+ if self.spec['mode'] != 'cot': # CoT replies are free text, parsed like the open models'
46
+ body['text'] = dict(format=dict(type='json_schema', name='answer', schema=SCHEMA, strict=True))
47
+ return body
48
+
49
+ def generate_one(self, segments):
50
+ body = self.body(segments)
51
+ for attempt in range(8):
52
+ r = self.http.post(URL, json=body, timeout=600, headers={'Authorization': 'Bearer ' + self.key})
53
+ if r.status_code == 200:
54
+ break
55
+ if r.status_code not in (408, 409, 429) and r.status_code < 500:
56
+ raise RuntimeError(f'{r.status_code} {r.text[:500]}')
57
+ time.sleep(2 ** attempt)
58
+ d = r.json()
59
+ self.usage.append(d.get('usage', {}))
60
+ text = ''.join(c.get('text', '') for o in d.get('output', []) if o.get('type') == 'message'
61
+ for c in o.get('content', []))
62
+ try:
63
+ return json.loads(text)['answer']
64
+ except (ValueError, KeyError, TypeError):
65
+ return text or f"[{d.get('status')} {d.get('incomplete_details')}]"
66
+
67
+ def generate(self, batch):
68
+ self.usage = []
69
+ with ThreadPoolExecutor(WORKERS) as ex:
70
+ out = list(ex.map(self.generate_one, batch))
71
+ u = self.usage
72
+ print('usage in', sum(x.get('input_tokens', 0) for x in u),
73
+ 'cached', sum((x.get('input_tokens_details') or {}).get('cached_tokens', 0) for x in u),
74
+ 'out', sum(x.get('output_tokens', 0) for x in u),
75
+ 'reasoning', sum((x.get('output_tokens_details') or {}).get('reasoning_tokens', 0) for x in u),
76
+ time.strftime('%H:%M:%S'), flush=True)
77
+ return out
code/clinical3d_eval/vlm/qwen.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Qwen3-VL / Qwen2.5-VL family (the reference adapter; as clinical3d_eval.run_qwen), plus fine-tunes of those bases.
2
+
3
+ HF transformers adapters for the direct-answer models; a vLLM adapter (whole batch in one generate call) for the
4
+ models that reason in a <think> block. Frames are resized by qwen_vl_utils to spec['max_pixels'] (the factor is
5
+ 2 x patch: 28 for Qwen2.5-VL, 32 for Qwen3-VL); the processor's own limits are widened so it does not resize again.
6
+ """
7
+ from clinical3d_eval.vlm.base import Adapter
8
+
9
+ # MiMo-VL reasons in <think> by default, but after "Answer with the letter of the correct option only." it opens and
10
+ # closes an empty <think> block (smoke test: RL 20/20 even with '<think>\n' prefilled, SFT 16/20). So mode 'cot': the
11
+ # protocol's reasoning footer replaces the letter-only line, and the model then reasons in its own <think> block.
12
+ _THINK_NOTE = ("mode cot (protocol reasoning footer, 'Answer: <letter>'): with the letter-only footer the model skips its "
13
+ "<think> block; default chat template incl. its system prompt; greedy with repetition_penalty 1.05 "
14
+ "(the Qwen2.5-VL default; plain greedy loops until the cap on 2/20 smoke items), up to 4096 new tokens, "
15
+ "vLLM 0.11 batched")
16
+ MODELS = {
17
+ 'qwen3vl_8b': dict(hf='Qwen/Qwen3-VL-8B-Instruct', adapter='Qwen3VL', env='qwenvl'),
18
+ 'qwen3vl_32b': dict(hf='Qwen/Qwen3-VL-32B-Instruct-FP8', adapter='VLLMQwen3VL', env='qwenvl',
19
+ vllm=dict(gpu_memory_utilization=0.95, max_num_seqs=4, enforce_eager=True),
20
+ note="Qwen's official FP8 checkpoint (Qwen3-VL-32B-Instruct-FP8, fine-grained e4m3) on one 48 GB "
21
+ "GPU, vLLM 0.11, greedy"),
22
+ 'mimo_vl_7b_sft': dict(hf='XiaomiMiMo/MiMo-VL-7B-SFT', adapter='VLLMQwen25VL', env='qwenvl', mode='cot',
23
+ max_new_tokens=4096, repetition_penalty=1.05, note=_THINK_NOTE),
24
+ 'mimo_vl_7b_rl': dict(hf='XiaomiMiMo/MiMo-VL-7B-RL', adapter='VLLMQwen25VL', env='qwenvl', mode='cot',
25
+ max_new_tokens=4096, repetition_penalty=1.05, note=_THINK_NOTE),
26
+ # control: the base model of SpaceR / VST / SenseNova-SI-1.1-Qwen2.5 / MiMo-VL, same pipeline
27
+ 'qwen25vl_7b': dict(hf='Qwen/Qwen2.5-VL-7B-Instruct', adapter='Qwen25VL', env='qwenvl'),
28
+ 'qwen25vl_3b': dict(hf='Qwen/Qwen2.5-VL-3B-Instruct', adapter='Qwen25VL', env='evlf2'),
29
+ 'qwen25vl_32b': dict(hf='Qwen/Qwen2.5-VL-32B-Instruct', adapter='Qwen25VL', env='evlf2'),
30
+ 'qwen25vl_72b': dict(hf='Qwen/Qwen2.5-VL-72B-Instruct', adapter='Qwen25VL', env='evlf2', gpus=2,
31
+ note='bf16, HF device_map over two GPUs'),
32
+ # SpaceR-Eval's default prompt type answers directly ("Answer with the option's letter ... directly"), so direct
33
+ 'spacer_7b': dict(hf='RUBBISHLIKE/SpaceR', adapter='Qwen25VL', env='qwenvl'),
34
+ 'vst_7b_sft': dict(hf='rayruiyang/VST-7B-SFT', adapter='Qwen25VL', env='qwenvl'),
35
+ # SenseNova-SI ships max_pixels 147456 (384 x 384) in its processor config: frames at that size, not 768 x 448
36
+ 'sensenova_si11_qwen25vl_7b': dict(hf='sensenova/SenseNova-SI-1.1-Qwen2.5-VL-7B', adapter='Qwen25VL', env='qwenvl',
37
+ max_pixels=147456,
38
+ note="frames at the model's own processor default max_pixels 147456 (384x384)"),
39
+ 'sensenova_si11_qwen3vl_8b': dict(hf='sensenova/SenseNova-SI-1.1-Qwen3-VL-8B', adapter='Qwen3VL', env='qwenvl',
40
+ max_pixels=147456,
41
+ note="frames at the model's own processor default max_pixels 147456 (384x384)"),
42
+ }
43
+
44
+
45
+ def _widen_processor(proc, px):
46
+ """Let the pre-resized frames (qwen_vl_utils, ~px pixels) through the HF image processor unchanged."""
47
+ ip = proc.image_processor
48
+ lo, hi = 3136, max(4 * px, 1 << 20)
49
+ if getattr(ip, 'min_pixels', None) is not None:
50
+ ip.min_pixels = lo
51
+ if getattr(ip, 'max_pixels', None) is not None:
52
+ ip.max_pixels = hi
53
+ if isinstance(getattr(ip, 'size', None), dict) and 'longest_edge' in ip.size:
54
+ ip.size = {'shortest_edge': lo, 'longest_edge': hi}
55
+
56
+
57
+ class Qwen3VL(Adapter):
58
+ patch = 16
59
+
60
+ def load(self):
61
+ import torch
62
+ from transformers import AutoModelForImageTextToText, AutoProcessor
63
+ self.torch = torch
64
+ self.model = AutoModelForImageTextToText.from_pretrained(
65
+ self.weights, dtype=torch.bfloat16, device_map='auto', attn_implementation='sdpa').eval()
66
+ self.proc = AutoProcessor.from_pretrained(self.weights)
67
+ self.proc.tokenizer.padding_side = 'left'
68
+ _widen_processor(self.proc, self.spec['max_pixels'])
69
+
70
+ def messages(self, segments):
71
+ px = self.spec['max_pixels']
72
+ return [dict(role='user', content=[dict(type='text', text=v) if k == 'text' else
73
+ dict(type='image', image=v, min_pixels=px, max_pixels=px)
74
+ for k, v in segments])]
75
+
76
+ def prepare(self, seg):
77
+ from qwen_vl_utils import process_vision_info
78
+ msgs = self.messages(seg)
79
+ prompt = self.proc.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
80
+ im, _ = process_vision_info(msgs, image_patch_size=self.patch)
81
+ return prompt, im or []
82
+
83
+ def generate(self, batch):
84
+ prompts, images = [], []
85
+ for seg in batch:
86
+ p, im = self.prepare(seg)
87
+ prompts.append(p)
88
+ images += im
89
+ inputs = self.proc(text=prompts, images=images or None, return_tensors='pt', padding=True).to(self.model.device)
90
+ with self.torch.inference_mode():
91
+ # plain greedy: override generation_config extras (SpaceR ships repetition_penalty 1.05, use_cache False)
92
+ out = self.model.generate(**inputs, max_new_tokens=self.spec['max_new_tokens'], do_sample=False,
93
+ repetition_penalty=1.0, use_cache=True)
94
+ return self.proc.batch_decode(out[:, inputs['input_ids'].shape[1]:], skip_special_tokens=True)
95
+
96
+
97
+ class Qwen25VL(Qwen3VL):
98
+ """Qwen2.5-VL architecture (patch 14): SpaceR, VST, SenseNova-SI-Qwen2.5, MiMo-VL."""
99
+ patch = 14
100
+
101
+
102
+ class Qwen3VLVideo(Qwen3VL):
103
+ """The sampled frames as one Qwen video (timestamp labels as text before it, question after), not interleaved
104
+ images; frame size spec['min_pixels'] .. spec['max_pixels']. An odd frame count gets the last frame repeated."""
105
+
106
+ def messages(self, segments):
107
+ texts = [v for k, v in segments if k == 'text']
108
+ frames = [v for k, v in segments if k == 'image']
109
+ times = [float(t.strip('[] s')) for t in texts[1:-1]]
110
+ fps = (len(frames) - 1) / max(times[-1] - times[0], 1e-3)
111
+ px = self.spec['max_pixels']
112
+ video = dict(type='video', video=frames, sample_fps=fps, max_pixels=px,
113
+ min_pixels=self.spec.get('min_pixels', min(px, 128 * 32 * 32)))
114
+ return [dict(role='user', content=[dict(type='text', text=texts[0] + '\n' + ' '.join(texts[1:-1]) + '\n'),
115
+ video, dict(type='text', text=texts[-1])])]
116
+
117
+ def generate(self, batch):
118
+ from qwen_vl_utils import process_vision_info
119
+ msgs = [self.messages(seg) for seg in batch]
120
+ prompts = [self.proc.apply_chat_template(m, tokenize=False, add_generation_prompt=True) for m in msgs]
121
+ qwen3 = self.patch == 16 # Qwen3-VL takes frame times as metadata, Qwen2.5-VL as fps
122
+ videos, meta = [], []
123
+ for m in msgs:
124
+ _, v = process_vision_info(m, image_patch_size=self.patch, return_video_metadata=qwen3)
125
+ videos += [x[0] for x in v] if qwen3 else v
126
+ meta += [x[1] for x in v] if qwen3 else []
127
+ extra = dict(video_metadata=meta) if qwen3 else dict(fps=[m[0]['content'][1]['sample_fps'] for m in msgs])
128
+ inputs = self.proc(text=prompts, videos=videos, return_tensors='pt', padding=True, do_resize=False,
129
+ do_sample_frames=False, **extra).to(self.model.device)
130
+ with self.torch.inference_mode():
131
+ out = self.model.generate(**inputs, max_new_tokens=self.spec['max_new_tokens'], do_sample=False,
132
+ repetition_penalty=1.0, use_cache=True)
133
+ return self.proc.batch_decode(out[:, inputs['input_ids'].shape[1]:], skip_special_tokens=True)
134
+
135
+
136
+ class Qwen25VLVideo(Qwen3VLVideo):
137
+ patch = 14
138
+
139
+
140
+ class VLLMQwen25VL(Qwen25VL):
141
+ """Same prompt and frames as Qwen25VL; vLLM generates the whole batch at once (greedy)."""
142
+
143
+ def load(self):
144
+ # Engine in-process: CUDA is already initialised here, so a forked engine core could not use it.
145
+ import os
146
+ # Tensor-parallel workers are spawned (not forked) for the same reason.
147
+ os.environ['VLLM_ENABLE_V1_MULTIPROCESSING'] = '0'
148
+ os.environ['VLLM_WORKER_MULTIPROC_METHOD'] = 'spawn'
149
+ from transformers import AutoProcessor
150
+ from vllm import LLM, SamplingParams
151
+ px = self.spec['max_pixels']
152
+ self.proc = AutoProcessor.from_pretrained(self.weights)
153
+ kw = dict(dtype='bfloat16', tensor_parallel_size=self.spec['gpus'],
154
+ max_model_len=24576 if self.spec['mode'] != 'direct' else 16384,
155
+ limit_mm_per_prompt={'image': 40, 'video': 0}, mm_processor_kwargs=self.mm_kwargs(px),
156
+ gpu_memory_utilization=0.90, max_num_seqs=64, seed=0, enable_prefix_caching=False,
157
+ mm_processor_cache_gb=0) # vLLM 0.11: the cache asserts on frames repeated within a batch
158
+ self.llm = LLM(model=str(self.weights), **{**kw, **self.spec.get('vllm', {})})
159
+ self.sp = SamplingParams(temperature=0.0, max_tokens=self.spec['max_new_tokens'], skip_special_tokens=False,
160
+ repetition_penalty=self.spec.get('repetition_penalty', 1.0))
161
+
162
+ def mm_kwargs(self, px):
163
+ return {'min_pixels': 3136, 'max_pixels': max(4 * px, 1 << 20)}
164
+
165
+ def generate(self, batch):
166
+ reqs = []
167
+ for seg in batch:
168
+ p, im = self.prepare(seg)
169
+ reqs.append(dict(prompt=p + self.spec.get('prefill', ''), multi_modal_data={'image': im}))
170
+ outs = self.llm.generate(reqs, self.sp, use_tqdm=False)
171
+ return [self.spec.get('prefill', '') + o.outputs[0].text for o in outs]
172
+
173
+
174
+ class VLLMQwen25VLVideo(VLLMQwen25VL):
175
+ """The frames as one video (Qwen25VLVideo's message), generated with vLLM."""
176
+ messages = Qwen25VLVideo.messages
177
+
178
+ def mm_kwargs(self, px):
179
+ return None
180
+
181
+ def generate(self, batch):
182
+ from qwen_vl_utils import process_vision_info
183
+ reqs = []
184
+ for seg in batch:
185
+ m = self.messages(seg)
186
+ _, v = process_vision_info(m, image_patch_size=self.patch)
187
+ reqs.append(dict(prompt=self.proc.apply_chat_template(m, tokenize=False, add_generation_prompt=True),
188
+ multi_modal_data={'video': v[0]},
189
+ mm_processor_kwargs={'fps': m[0]['content'][1]['sample_fps'], 'do_resize': False}))
190
+ outs = self.llm.generate(reqs, self.sp, use_tqdm=False)
191
+ return [o.outputs[0].text for o in outs]
192
+
193
+
194
+ class VLLMQwen3VL(VLLMQwen25VL):
195
+ """Qwen3-VL through vLLM (patch 16); the processor's default limits (16.7 M pixels) already leave frames as they are."""
196
+ patch = 16
197
+
198
+ def mm_kwargs(self, px):
199
+ return None
code/clinical3d_eval/vlm/spatial_mllm.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Spatial-MLLM v1.1 (Qwen2.5-VL-3B + VGGT spatial encoder) through the unmodified upstream model code.
2
+
3
+ The VGGT spatial encoder needs the frames of one clip as one video, so the sampled frames are passed as a single
4
+ Qwen2.5-VL video (a list of frame files, the upstream frame-folder path), not as interleaved images. The prompt text
5
+ is unchanged; only its placement follows the model's own format: header, then the timestamp labels of the frames
6
+ (in order, one per frame), then the video, then question + options + answer instruction. Preprocessing, the
7
+ processor call and the extra video_tchw input follow upstream src/evaluation/vsibench/eval_vsibench.py
8
+ (prepare_chat_batch / prepare_spatial_mllm_inputs); decoding is greedy (upstream uses temperature 0.1, top_p 0.001).
9
+ Upstream code: clone https://github.com/THU-SI/Spatial-MLLM and set SPATIAL_MLLM_UPSTREAM to it.
10
+ """
11
+ import os
12
+ import sys
13
+ from pathlib import Path
14
+
15
+ from clinical3d_eval.vlm.base import Adapter
16
+
17
+ NOTE = ('3D encoder needs one clip: the sampled frames go in as one Qwen2.5-VL video (upstream preprocessing, '
18
+ '448x784 per frame), not interleaved; timestamp labels listed as text '
19
+ 'before the video, question after; an odd frame count (anchors) is padded by repeating the last frame '
20
+ '(upstream qwen_vl_utils FRAME_FACTOR 2)')
21
+
22
+ MODELS = {
23
+ 'spatial_mllm_135k': dict(hf='Diankun/Spatial-MLLM-v1.1-Instruct-135K', adapter='SpatialMLLM',
24
+ env='spatial-mllm', note=NOTE),
25
+ 'spatial_mllm_820k': dict(hf='Diankun/Spatial-MLLM-v1.1-Instruct-820K', adapter='SpatialMLLM',
26
+ env='spatial-mllm', note=NOTE),
27
+ }
28
+
29
+
30
+ def upstream_dir():
31
+ cands = [os.environ.get('SPATIAL_MLLM_UPSTREAM')]
32
+ for c in cands:
33
+ if c and (Path(c) / 'src' / 'qwenvl' / 'model' / 'spatial_mllm.py').exists():
34
+ return Path(c)
35
+ raise FileNotFoundError('Spatial-MLLM upstream code not found; set SPATIAL_MLLM_UPSTREAM')
36
+
37
+
38
+ class SpatialMLLM(Adapter):
39
+
40
+ def load(self):
41
+ up = upstream_dir()
42
+ sys.path[:0] = [str(up), str(up / 'src' / 'qwenvl' / 'external')]
43
+ import torch
44
+ from transformers import Qwen2_5_VLProcessor
45
+ from src.qwenvl.model.spatial_mllm import SpatialMLLMConfig, SpatialMLLMForConditionalGeneration
46
+ self.torch = torch
47
+ config = SpatialMLLMConfig.from_pretrained(self.weights)
48
+ self.model = SpatialMLLMForConditionalGeneration.from_pretrained(
49
+ self.weights, config=config, torch_dtype=torch.bfloat16, device_map='cuda',
50
+ attn_implementation='flash_attention_2').eval()
51
+ self.proc = Qwen2_5_VLProcessor.from_pretrained(self.weights)
52
+ # upstream forward projects every prompt position to the vocabulary (7.5k tokens x 152k per item); greedy
53
+ # decoding reads only the last position, so project just that one (same replies, batch 4 fits in 48 GB)
54
+ head = self.model.lm_head
55
+
56
+ class LastPosition(torch.nn.Module):
57
+ def forward(self, h):
58
+ return head(h[:, -1:, :])
59
+ self.model.lm_head = LastPosition()
60
+
61
+ @staticmethod
62
+ def message(segments):
63
+ texts = [v for k, v in segments if k == 'text']
64
+ frames = [v for k, v in segments if k == 'image']
65
+ header, labels, question = texts[0], texts[1:-1], texts[-1]
66
+ assert len(labels) == len(frames), (len(labels), len(frames))
67
+ return [dict(role='user', content=[dict(type='text', text=header + '\n' + ' '.join(labels) + '\n'),
68
+ dict(type='video', video=frames),
69
+ dict(type='text', text=question)])]
70
+
71
+ def generate(self, batch):
72
+ from qwen_vl_utils import process_vision_info
73
+ from src.evaluation.utils.common_utils import prepare_spatial_mllm_inputs
74
+ msgs = [self.message(seg) for seg in batch]
75
+ prompts = [self.proc.apply_chat_template(m, tokenize=False, add_generation_prompt=True) for m in msgs]
76
+ videos = []
77
+ for m in msgs:
78
+ _, v = process_vision_info(m)
79
+ videos.extend(v)
80
+ inputs = self.proc(text=prompts, videos=videos, return_tensors='pt', padding=True, padding_side='left')
81
+ inputs = prepare_spatial_mllm_inputs(inputs, videos, None)
82
+ inputs = inputs.to(self.model.device)
83
+ inputs['video_tchw'] = [v.to(self.model.device) for v in inputs['video_tchw']]
84
+ with self.torch.inference_mode():
85
+ out = self.model.generate(**inputs, max_new_tokens=self.spec['max_new_tokens'], do_sample=False,
86
+ temperature=None, top_p=None, top_k=None, use_cache=True)
87
+ return self.proc.batch_decode(out[:, inputs['input_ids'].shape[1]:], skip_special_tokens=True,
88
+ clean_up_tokenization_spaces=False)
code/examples/custom_model.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Evaluate your own model: build the protocol prompt (timestamped frames + question + lettered options), call the
2
+ model, parse the letter, write a prediction file that clinical3d_eval.score reads.
3
+
4
+ python code/examples/custom_model.py --data /path/to/Clinical3D-Bench --out preds/my_model.jsonl --limit 20
5
+
6
+ Replace answer() with your model. segments is a list of ('text', str) and ('image', path to a JPEG frame) in order.
7
+ """
8
+ import argparse
9
+ import json
10
+ from pathlib import Path
11
+
12
+ from clinical3d_eval.prompt import build_messages
13
+ from clinical3d_eval.sampling import extract_frames, protocol_indices
14
+ from clinical3d_eval.vlm.base import parse_reply
15
+
16
+
17
+ def answer(segments):
18
+ """Your model here: return its reply text (e.g. 'B')."""
19
+ return 'A'
20
+
21
+
22
+ def main():
23
+ ap = argparse.ArgumentParser()
24
+ ap.add_argument('--data', type=Path, required=True)
25
+ ap.add_argument('--out', type=Path, required=True)
26
+ ap.add_argument('--frames', type=int, default=32)
27
+ ap.add_argument('--limit', type=int)
28
+ a = ap.parse_args()
29
+ qs = [json.loads(l) for l in (a.data / 'questions.jsonl').read_text().splitlines()][:a.limit]
30
+ a.out.parent.mkdir(parents=True, exist_ok=True)
31
+ with a.out.open('w') as f:
32
+ for q in qs:
33
+ idx = protocol_indices(q['n_frames'], a.frames, q.get('anchor_frames', []))
34
+ frames = extract_frames(a.data / q['video'], idx, a.data / '.frames' / 'videos' / q['clip'])
35
+ segments = build_messages(q, frames, [i / q['fps'] for i in idx])
36
+ raw = answer(segments)
37
+ f.write(json.dumps(dict(id=q['id'], raw=raw, pred=parse_reply(raw, q, 'direct'))) + '\n')
38
+ print('wrote', len(qs), 'predictions to', a.out)
39
+
40
+
41
+ if __name__ == '__main__':
42
+ main()
code/examples/run_api_models.sh ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Proprietary models through their APIs: 10 frames at 480x288, no reasoning, reply constrained to one letter.
3
+ # The full set is 3,368 requests per model; try --limit 20 first.
4
+ # DATA=/path/to/Clinical3D-Bench OPENAI_API_KEY=... GEMINI_API_KEY=... ANTHROPIC_API_KEY=... bash code/examples/run_api_models.sh
5
+ set -e
6
+ DATA=${DATA:?set DATA to the dataset directory}
7
+ OUT=${OUT:-preds}
8
+ LIMIT=${LIMIT:+--limit $LIMIT}
9
+ python -m clinical3d_eval.run --model gpt_5_5_nothink_f10 --data $DATA --out $OUT/gpt_5_5.jsonl --batch 16 $LIMIT
10
+ python -m clinical3d_eval.run --model gemini_3_6_flash_nothink_f10 --data $DATA --out $OUT/gemini_3_6_flash.jsonl --batch 16 $LIMIT
11
+ python -m clinical3d_eval.run --model claude_sonnet_5_5_nothink_f10 --data $DATA --out $OUT/claude_sonnet_5_5.jsonl --batch 16 $LIMIT
12
+ python -m clinical3d_eval.score --data $DATA --preds $OUT/gpt_5_5.jsonl $OUT/gemini_3_6_flash.jsonl $OUT/claude_sonnet_5_5.jsonl
code/examples/run_open_models.sh ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Evaluate several open models with the paper's protocol, then score them.
3
+ # DATA=/path/to/Clinical3D-Bench bash code/examples/run_open_models.sh
4
+ # Run from the code/ directory (or put it on PYTHONPATH). Each family needs its own dependencies (see README).
5
+ set -e
6
+ DATA=${DATA:?set DATA to the dataset directory}
7
+ OUT=${OUT:-preds}
8
+ for m in qwen3vl_8b qwen25vl_7b internvl35_8b internvl3_14b llava_next_video_34b kimi_vl_a3b; do
9
+ python -m clinical3d_eval.run --model $m --data $DATA --out $OUT/$m.jsonl --batch 4
10
+ done
11
+ # vLLM models (FP8 Qwen3-VL-32B, MiMo-VL) and Spatial-MLLM (needs the upstream repo, see README):
12
+ # python -m clinical3d_eval.run --model qwen3vl_32b --data $DATA --out $OUT/qwen3vl_32b.jsonl --batch 32
13
+ # SPATIAL_MLLM_UPSTREAM=/path/to/Spatial-MLLM python -m clinical3d_eval.run --model spatial_mllm_135k --data $DATA --out $OUT/spatial_mllm_135k.jsonl
14
+ python -m clinical3d_eval.score --data $DATA --preds $OUT/*.jsonl
code/examples/show_masks.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Draw the instance masks of one question's evidence objects on its photorealistic clip.
2
+
3
+ python code/examples/show_masks.py --data /path/to/Clinical3D-Bench --id 3010d94944f9ca88 --frame 30 --out vis.png
4
+
5
+ masks/video/<clip>.npz holds object_id (60, 448, 768) on the videos/ raster, with source[i] in {src, warp, none}:
6
+ src = the frame is on the render's camera path and the render mask is used; warp = the render's instances
7
+ re-projected to the frame's estimated pose; none = no trustworthy mask (valid[i] False, all zeros).
8
+ masks/render/<clip>.npz holds object_id and part_id for videos_render/ (exact). objects/<clip>.json maps ids to
9
+ entities and categories; a question's evidence lists the entities (object or part keys) it depends on.
10
+ """
11
+ import argparse
12
+ import json
13
+ import subprocess
14
+ from pathlib import Path
15
+
16
+ import numpy as np
17
+ from PIL import Image
18
+
19
+
20
+ def main():
21
+ ap = argparse.ArgumentParser()
22
+ ap.add_argument('--data', type=Path, required=True)
23
+ ap.add_argument('--id', required=True)
24
+ ap.add_argument('--frame', type=int, default=30)
25
+ ap.add_argument('--out', type=Path, default=Path('vis.png'))
26
+ a = ap.parse_args()
27
+ q = next(r for r in map(json.loads, (a.data / 'questions.jsonl').read_text().splitlines()) if r['id'] == a.id)
28
+ print(q['type'], '|', q['question'], '| answer', q['answer_letter'])
29
+ objs = json.loads((a.data / 'objects' / f"{q['clip']}.json").read_text())
30
+ ids = {o['entity']: o['object_id'] for o in objs['objects']}
31
+ m = np.load(a.data / 'masks/video' / f"{q['clip']}.npz")
32
+ i = a.frame
33
+ print('mask source of frame', i, ':', m['source'][i])
34
+ raw = subprocess.run(['ffmpeg', '-loglevel', 'error', '-i', str(a.data / q['video']), '-vf', f'select=eq(n\\,{i})',
35
+ '-vsync', '0', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-'], capture_output=True, check=True).stdout
36
+ im = np.frombuffer(raw, np.uint8).reshape(448, 768, 3).copy()
37
+ colors = [(255, 60, 60), (60, 200, 255), (255, 200, 0), (120, 255, 120)]
38
+ for k, e in enumerate(q['evidence']):
39
+ oid = ids.get(e['key'].split('/')[0])
40
+ if oid is None:
41
+ continue
42
+ sel = m['object_id'][i] == oid
43
+ im[sel] = (0.5 * im[sel] + 0.5 * np.array(colors[k % 4])).astype(np.uint8)
44
+ print(e['key'], 'object_id', oid, 'pixels', int(sel.sum()))
45
+ Image.fromarray(im).save(a.out)
46
+ print('saved', a.out)
47
+
48
+
49
+ if __name__ == '__main__':
50
+ main()
leaderboard.csv ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ group,model,frames,Count,Re-ID,Light owner,Patient frame,Device ref.,Direction,Route,Passability,avg,rank,eval_key
2
+ References,Chance (analytic),,20.0,33.3,28.9,50.0,27.9,24.9,26.7,50.0,32.7,--,
3
+ References,Answer prior (test-fitted),,34.0,39.5,46.0,54.8,39.1,28.3,30.0,54.3,40.8,--,
4
+ References,Human,,84.0,80.0,86.0,94.0,82.0,82.0,60.0,64.0,79.0,--,
5
+ Proprietary Models (API),Gemini 3.6 Flash,10,59.2,47.2,76.2,46.0,64.8,49.1,31.1,55.0,53.6,4,gemini_3_6_flash_nothink_f10
6
+ Proprietary Models (API),GPT-5.5,10,47.1,49.2,77.8,40.7,51.6,49.9,37.1,57.8,51.4,5,gpt_5_5_nothink_f10
7
+ Proprietary Models (API),Claude Sonnet 5.5,10,47.1,56.4,65.1,51.0,53.1,51.0,31.8,55.0,51.3,6,claude_sonnet_5_5_nothink_f10
8
+ Open-source General Models,VideoJev-4B,20,46.6,38.5,74.6,17.0,51.6,48.4,29.5,57.9,45.5,9,
9
+ Open-source General Models,Qwen2.5-VL-3B,32,29.0,26.7,68.3,33.3,46.1,35.2,28.4,51.9,39.9,20,qwen25vl_3b
10
+ Open-source General Models,Qwen2.5-VL-7B,32,17.5,40.5,17.5,27.7,41.4,26.7,30.8,54.3,32.1,35,qwen25vl_7b
11
+ Open-source General Models,Qwen2.5-VL-32B,32,46.8,34.9,15.9,31.6,43.0,38.9,34.5,53.7,37.4,25,qwen25vl_32b
12
+ Open-source General Models,Qwen2.5-VL-72B,32,41.4,39.0,19.0,29.0,49.2,40.4,33.4,54.3,38.2,23,qwen25vl_72b
13
+ Open-source General Models,Qwen3-VL-4B,16,40.5,32.8,28.6,27.1,44.5,37.2,31.3,51.0,36.6,26,
14
+ Open-source General Models,Qwen3-VL-8B,32,46.6,39.0,55.6,20.9,50.0,40.0,33.4,56.0,42.7,14,qwen3vl_8b
15
+ Open-source General Models,Qwen3-VL-32B,32,51.2,41.0,76.2,13.4,54.7,35.9,32.9,55.2,45.1,10,qwen3vl_32b
16
+ Open-source General Models,InternVL3-8B,32,44.9,33.8,74.6,25.3,43.0,33.1,23.7,54.7,41.6,16,internvl3_8b
17
+ Open-source General Models,InternVL3-14B,32,52.6,47.2,71.4,20.3,47.7,40.3,31.6,54.3,45.7,7,internvl3_14b
18
+ Open-source General Models,InternVL3-38B,32,54.2,44.1,57.1,18.6,56.2,45.2,30.3,54.7,45.1,11,internvl3_38b
19
+ Open-source General Models,InternVL3-78B,32,56.7,26.7,73.0,18.2,51.6,43.3,27.9,54.1,43.9,13,internvl3_78b
20
+ Open-source General Models,InternVL3.5-4B,32,29.0,40.0,74.6,27.9,43.8,34.0,30.8,49.2,41.2,19,internvl35_4b
21
+ Open-source General Models,InternVL3.5-8B,32,38.9,33.8,79.4,36.1,44.5,37.3,28.4,54.3,44.1,12,internvl35_8b
22
+ Open-source General Models,InternVL3.5-14B,32,47.4,32.3,71.4,32.7,50.8,41.8,34.2,54.7,45.7,8,internvl35_14b
23
+ Open-source General Models,InternVL3.5-38B,32,47.9,31.8,60.3,21.6,49.2,44.5,28.7,54.8,42.3,15,internvl35_38b
24
+ Open-source General Models,LLaVA-CoT-11B,16,4.9,34.9,20.6,44.4,40.6,25.6,28.9,55.2,31.9,36,llama32v_11b_cot_mi
25
+ Open-source General Models,LLaVA-NeXT-Video-34B,16,33.7,31.3,58.7,50.6,44.5,26.7,29.7,56.2,41.4,18,llava_next_video_34b
26
+ Open-source General Models,Kimi-VL-A3B-Instruct,32,23.0,29.7,46.0,32.0,35.9,35.6,28.4,54.3,35.6,28,kimi_vl_a3b
27
+ Open-source General Models,Kimi-VL-A3B-Thinking,32,37.3,32.3,41.3,39.7,43.0,32.6,31.1,54.3,39.0,21,kimi_vl_a3b_thinking
28
+ Open-source General Models,DeepSeek-VL2,7,32.3,30.8,54.0,33.5,41.4,32.1,28.4,54.3,38.4,22,deepseek_vl2
29
+ Open-source General Models,Llama-3.2-11B-Vision,16,19.7,32.3,49.2,44.9,35.2,24.1,27.9,55.4,36.1,27,llama32v_11b_mi
30
+ Open-source General Models,MiMo-VL-7B-SFT,32,34.0,32.8,9.5,24.6,36.7,41.0,29.2,54.3,32.8,33,mimo_vl_7b_sft
31
+ Open-source General Models,MiMo-VL-7B-RL,32,26.0,30.8,23.8,25.8,35.9,42.7,31.6,53.7,33.8,31,mimo_vl_7b_rl
32
+ Open-source Spatial Models,SenseNova-SI-1.1-Qwen2.5-VL-7B,32,19.2,34.4,1.6,35.2,40.6,33.0,31.8,53.9,31.2,37,sensenova_si11_qwen25vl_7b
33
+ Open-source Spatial Models,SenseNova-SI-1.1-Qwen3-VL-8B,32,41.6,43.6,4.8,25.6,38.3,32.4,35.0,56.4,34.7,30,sensenova_si11_qwen3vl_8b
34
+ Open-source Spatial Models,SenseNova-SI-1.3-InternVL3-8B,32,35.6,41.0,65.1,20.3,43.0,42.2,30.8,54.3,41.5,17,sensenova_si13_internvl3_8b
35
+ Open-source Spatial Models,Spatial-MLLM-135K,32,34.0,33.8,38.1,41.6,38.3,34.5,30.3,51.6,37.8,24,spatial_mllm_135k
36
+ Open-source Spatial Models,Spatial-MLLM-820K,32,20.3,32.8,52.4,32.5,39.1,24.5,29.5,53.9,35.6,29,spatial_mllm_820k
37
+ Open-source Spatial Models,SpaceR-7B,32,17.8,36.9,20.6,29.2,43.0,31.7,33.4,55.2,33.5,32,spacer_7b
38
+ Open-source Spatial Models,VST-7B-SFT,32,24.1,29.7,6.3,27.1,46.9,36.3,33.9,53.9,32.3,34,vst_7b_sft
39
+ Open-source Spatial Models,SpaceLLaVA-13B,8,11.2,31.3,1.6,54.5,40.6,21.5,29.7,51.7,30.3,38,spacellava_13b
40
+ Fine-tuned on Clinical3D-Train,Spatial-MLLM SFT,16,54.8,65.6,87.3,89.3,59.4,77.4,65.8,59.5,69.9,3,
41
+ Fine-tuned on Clinical3D-Train,VideoJev-4B SFT,20,66.8,73.9,83.1,93.7,71.6,77.8,58.3,66.0,73.9,2,
42
+ Fine-tuned on Clinical3D-Train,GeoJeV (ours),20,69.3,77.8,82.5,93.9,71.9,81.2,59.5,69.8,75.7,1,
masks/render/corridor_param_002_a.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2a50b04abcc41ba2d315958be0e3de8e5f634ad8bdf2ecaf2d48b324329836dc
3
+ size 946627
masks/render/corridor_param_002_b.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d818dfd97045b33a51e9a2abe53485548989750eb45557cd785c571c1253bb21
3
+ size 943094
masks/render/corridor_param_002_c.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ab6609287777dd655d9629e89e29759c14b02a91c41d7404e0882be4967d02f7
3
+ size 732631
masks/render/corridor_param_003_a.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f15095d422ff6143474458835f1e7cac951f4b032008b0c7ce29a1d1882189f6
3
+ size 1076913
masks/render/corridor_param_003_b.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:51e8fbcbb6684ee24ee44d803dbaa5fc6bec04c4aca2c4ca91084c582d9a9106
3
+ size 1076918
masks/render/corridor_param_003_c.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:94ba84d15c23f442302496f62f87f9eb956c560156449b84133408dd9ad059ce
3
+ size 723824
masks/render/corridor_param_005_a.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c8c293ba0810c96690007165e85d0f0a532efd92b3a05903cafc2557a2136309
3
+ size 1098003
masks/render/corridor_param_005_b.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d32e44d3107bff48951ebcaa812c6fc97f9880cdd3c071a8fcc01fdd8fd319b1
3
+ size 1083270
masks/render/corridor_param_005_c.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:af1c82a34deb965c112e790422fab60f445de358943d3a95d91bceb08013dc5d
3
+ size 984903
masks/render/corridor_param_006_a.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0a0b6602a5b5fe6381974a4a89ecb603a39b7a16f945eb4185966c5a95bc4a53
3
+ size 1224043
masks/render/corridor_param_006_b.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a563ad418ce75251c5e33e50142d72237dc0db78ed7719f29c6e6d75dea66282
3
+ size 1226781
masks/render/corridor_param_006_c.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:12cb5f9799d7bd0bdafb649eb5c33a67c13a4581506c12aed3c287a695ed9bda
3
+ size 1123092
masks/render/corridor_param_007_a.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1176c41bf0753d48704ccdecf42ccde9321297d920e2f46cc1ed07d2b2a1f105
3
+ size 794610
masks/render/corridor_param_007_b.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0caaa98d10e1ccfc7f88e5a490ecf3a83cf807e92071cc81cb50e00d1a8e97ff
3
+ size 800256
masks/render/corridor_param_007_c.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:10438742406ddec93de588008c18b1f4d3baf56e90250a037970689498ea87c0
3
+ size 786628
masks/render/corridor_param_008_a.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f71cef67f0a82f1d06df1b61af22b3a5c08b71fb1cd7ae6e462a9b17a7aa6554
3
+ size 774156
masks/render/corridor_param_011_a.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4148f7eda50aa42d1d76cfb52d9432b6e6d9728613e094b470a0521e8b691e0a
3
+ size 1038909
masks/render/corridor_param_011_b.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4148f7eda50aa42d1d76cfb52d9432b6e6d9728613e094b470a0521e8b691e0a
3
+ size 1038909
masks/render/corridor_param_011_c.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:56b03a7651671de3d04b0f32c76c04a88ffe4e96f94410fb0d0b1b8a564863fb
3
+ size 1108011
masks/render/corridor_param_013_a.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:119fbabc44ed6eb57974c5ca50b92f4d4b47c31d255a90864a80e421a4e1b55a
3
+ size 748459
masks/render/corridor_param_013_b.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:00ca5f5ce8b816ccbd3364b8a08fa12e4b6b4aeae1f14a8e65fc25390f3b1950
3
+ size 731653
masks/render/corridor_param_013_c.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3b32e8736646390e1b946149300a7145867b5572777de30be5ff154a41771f24
3
+ size 892787
masks/render/corridor_param_014_a.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b2e916323e535f9580fba224a92ee9623e8102057f2a3c03bcd8042125880420
3
+ size 1034208
masks/render/corridor_param_014_b.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1bfb5f9ff28b3a0e3bf960c84339eb998c5b5aba69a6ac1e6f40e3aed16b309b
3
+ size 1039005
masks/render/corridor_param_014_c.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9fe96982a191b57c7fa9b1f99a9fa10d55bbff5d1934c3d2b125389d4fdb5a84
3
+ size 1040465
masks/render/corridor_param_015_a.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dbc76c40de749234c6007e42d806eead54a6b1acbc63bf9b4bc448c5600072f2
3
+ size 1079527