Datasets:
Formats:
parquet
Languages:
English
Size:
< 1K
Tags:
video-language-model
egocentric-video
laboratory
wet-lab
procedural-monitoring
error-detection
License:
Initial commit
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +2 -56
- README.md +242 -0
- data/clips.parquet +3 -0
- data/dji.parquet +3 -0
- data/monitor_next_step.json +0 -0
- data/monitoring_step_eval.json +0 -0
- data/multiview.parquet +3 -0
- data/pmd.parquet +3 -0
- data/xm.parquet +3 -0
- generate_report.py +26 -0
- inference.py +378 -0
- lsvbench/__init__.py +8 -0
- lsvbench/__pycache__/__init__.cpython-313.pyc +0 -0
- lsvbench/__pycache__/io.cpython-313.pyc +0 -0
- lsvbench/__pycache__/metrics.cpython-313.pyc +0 -0
- lsvbench/__pycache__/parsing.cpython-313.pyc +0 -0
- lsvbench/__pycache__/plots.cpython-313.pyc +0 -0
- lsvbench/__pycache__/report.cpython-313.pyc +0 -0
- lsvbench/io.py +135 -0
- lsvbench/metrics.py +107 -0
- lsvbench/parsing.py +204 -0
- lsvbench/plots.py +300 -0
- lsvbench/prompts.py +211 -0
- lsvbench/report.py +151 -0
- lsvbench/tasks/__init__.py +23 -0
- lsvbench/tasks/__pycache__/__init__.cpython-313.pyc +0 -0
- lsvbench/tasks/__pycache__/base.cpython-313.pyc +0 -0
- lsvbench/tasks/__pycache__/monitor_next_step.cpython-313.pyc +0 -0
- lsvbench/tasks/__pycache__/monitoring_step.cpython-313.pyc +0 -0
- lsvbench/tasks/__pycache__/pmd.cpython-313.pyc +0 -0
- lsvbench/tasks/base.py +56 -0
- lsvbench/tasks/monitor_next_step.py +140 -0
- lsvbench/tasks/monitoring_step.py +121 -0
- lsvbench/tasks/pmd.py +180 -0
- lsvbench/tasks/prompts/pmd.md +14 -0
- pmd/README.md +27 -0
- pmd/correct/pmd_correct_01.mp4 +3 -0
- pmd/correct/pmd_correct_02.mp4 +3 -0
- pmd/correct/pmd_correct_03.mp4 +3 -0
- pmd/correct/pmd_correct_04.mp4 +3 -0
- pmd/correct/pmd_correct_05.mp4 +3 -0
- pmd/correct/pmd_correct_06.mp4 +3 -0
- pmd/correct/pmd_correct_07.mp4 +3 -0
- pmd/correct/pmd_correct_08.mp4 +3 -0
- pmd/correct/pmd_correct_09.mp4 +3 -0
- pmd/correct/pmd_correct_10.mp4 +3 -0
- pmd/correct/pmd_correct_11.mp4 +3 -0
- pmd/correct/pmd_correct_12.mp4 +3 -0
- pmd/correct/pmd_correct_13.mp4 +3 -0
- pmd/correct/pmd_correct_14.mp4 +3 -0
.gitattributes
CHANGED
|
@@ -1,60 +1,6 @@
|
|
| 1 |
-
*.
|
| 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 |
-
*.
|
| 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
|
|
|
|
| 1 |
+
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
| 4 |
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 5 |
*.pth filter=lfs diff=lfs merge=lfs -text
|
|
|
|
| 6 |
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
README.md
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: cc-by-nc-4.0
|
| 3 |
+
pretty_name: LabOS LSV Benchmark
|
| 4 |
+
language:
|
| 5 |
+
- en
|
| 6 |
+
task_categories:
|
| 7 |
+
- visual-question-answering
|
| 8 |
+
- video-text-to-text
|
| 9 |
+
tags:
|
| 10 |
+
- video-language-model
|
| 11 |
+
- egocentric-video
|
| 12 |
+
- laboratory
|
| 13 |
+
- wet-lab
|
| 14 |
+
- procedural-monitoring
|
| 15 |
+
- error-detection
|
| 16 |
+
- benchmark
|
| 17 |
+
size_categories:
|
| 18 |
+
- 1K<n<10K
|
| 19 |
+
viewer: true
|
| 20 |
+
configs:
|
| 21 |
+
- config_name: DJI
|
| 22 |
+
data_files:
|
| 23 |
+
- split: test
|
| 24 |
+
path: data/dji.parquet
|
| 25 |
+
- config_name: XMglass
|
| 26 |
+
data_files:
|
| 27 |
+
- split: test
|
| 28 |
+
path: data/xm.parquet
|
| 29 |
+
- config_name: Multiview
|
| 30 |
+
data_files:
|
| 31 |
+
- split: test
|
| 32 |
+
path: data/multiview.parquet
|
| 33 |
+
- config_name: PMD
|
| 34 |
+
data_files:
|
| 35 |
+
- split: test
|
| 36 |
+
path: data/pmd.parquet
|
| 37 |
+
- config_name: all
|
| 38 |
+
data_files:
|
| 39 |
+
- split: test
|
| 40 |
+
path: data/clips.parquet
|
| 41 |
+
---
|
| 42 |
+
|
| 43 |
+
# LabOS LSV Benchmark
|
| 44 |
+
|
| 45 |
+
LabOS LSV is the benchmark for evaluating video-language models on wet-lab procedural supervision. It contains egocentric, third-person, and multiview laboratory videos paired with protocol-aligned evaluation manifests for monitoring what step is happening, whether the monitored procedure advances, and whether tool clips contain a certain type of error.
|
| 46 |
+
|
| 47 |
+
The package includes the media, benchmark manifests, prompt loaders, inference runner, and report generator used for the LabOS LSV benchmark.
|
| 48 |
+
|
| 49 |
+
## Benchmark Tasks
|
| 50 |
+
|
| 51 |
+
1. **Step Prediction Accuracy**: identify the visible protocol step in a lab short video monitoring window.
|
| 52 |
+
2. **Step Advanced Prediction Accuracy**: determine whether the monitored state advances to a new protocol step in a fine-tuning-style monitoring prompt and video window.
|
| 53 |
+
3. **Error Detection**: detect whether a clip is correct usage of a pipette or contains an error.
|
| 54 |
+
|
| 55 |
+
The PMD error-detection prompts preserve detailed answer options such as `ERROR_REUSE`, `ERROR_SURFACE`, `ERROR_RELEASE`, `ERROR_INSTALL`, and `ERROR_OTHER`. The public benchmark report collapses non-`CORRECT` predictions into `ERROR` for the reported Error Detection metric.
|
| 56 |
+
|
| 57 |
+
## Repository Layout
|
| 58 |
+
|
| 59 |
+
```text
|
| 60 |
+
lsv/
|
| 61 |
+
README.md
|
| 62 |
+
requirements.txt
|
| 63 |
+
inference.py
|
| 64 |
+
generate_report.py
|
| 65 |
+
data/
|
| 66 |
+
clips.parquet
|
| 67 |
+
dji.parquet
|
| 68 |
+
xm.parquet
|
| 69 |
+
multiview.parquet
|
| 70 |
+
pmd.parquet
|
| 71 |
+
monitoring_step_eval.json
|
| 72 |
+
monitor_next_step.json
|
| 73 |
+
videos/ # full-resolution LSV clips
|
| 74 |
+
videos640/ # 640px video mirrors for faster inference
|
| 75 |
+
pmd/
|
| 76 |
+
README.md
|
| 77 |
+
pmd.parquet
|
| 78 |
+
correct/ # correct pipette-use clips
|
| 79 |
+
incorrect/ # pipette-use clips with labeled mistakes
|
| 80 |
+
lsvbench/
|
| 81 |
+
io.py
|
| 82 |
+
parsing.py
|
| 83 |
+
metrics.py
|
| 84 |
+
prompts.py
|
| 85 |
+
plots.py
|
| 86 |
+
report.py
|
| 87 |
+
tasks/
|
| 88 |
+
monitoring_step.py
|
| 89 |
+
monitor_next_step.py
|
| 90 |
+
pmd.py
|
| 91 |
+
prompts/pmd.md
|
| 92 |
+
```
|
| 93 |
+
|
| 94 |
+
## Data Files
|
| 95 |
+
|
| 96 |
+
- `data/clips.parquet`: master LSV clip manifest with relative paths to `videos/` and `videos640/`.
|
| 97 |
+
- `data/dji.parquet`, `data/xm.parquet`, `data/multiview.parquet`: per-camera type manifests for DJI third-person, XM glasses egocentric, and synchronized multiview clips.
|
| 98 |
+
- `data/monitoring_step_eval.json`: 255 step-identification examples using 640px videos.
|
| 99 |
+
- `data/monitor_next_step.json`: 512 monitoring-delta examples matching the LabOS prompt style.
|
| 100 |
+
- `pmd/pmd.parquet`: 246 short pipette-manipulation clips for correct-vs-error and mistake-type evaluation.
|
| 101 |
+
|
| 102 |
+
The JSON manifests reference videos by relative path. The default benchmark loaders expect the media directories to remain at `videos640/`, `videos/`, `pmd/correct/`, and `pmd/incorrect/` relative to the repository root.
|
| 103 |
+
|
| 104 |
+
## Example Prompts
|
| 105 |
+
|
| 106 |
+
Monitoring examples pair a short video window with a protocol state JSON and ask the model to identify or update the current step. For example, `data/monitoring_step_eval.json` includes prompts like:
|
| 107 |
+
|
| 108 |
+
```text
|
| 109 |
+
You are a real-time lab assistant monitoring a scientist's wet-lab procedure from short video windows.
|
| 110 |
+
|
| 111 |
+
The current protocol state/history is provided below. Watch the current window and update the state.
|
| 112 |
+
|
| 113 |
+
Report protocol errors only when supported by the visible time window or state.
|
| 114 |
+
|
| 115 |
+
Compare the protocol order, prior history, and watched window.
|
| 116 |
+
|
| 117 |
+
Identify the main protocol step being performed in this watched video window.
|
| 118 |
+
|
| 119 |
+
STATE:
|
| 120 |
+
{"history":[{"step":"2","tas":0,"tds":0},{"step":"3","tas":30,"tds":30}],"on":"3","protocol":[{"desc":"Take HEK293T cells and culture them to ~70% confluency in a 10 cm dish.","order":1,"step":"1"},{"desc":"In a sterile 1.5 mL tube, mix 10 µg lentiviral backbone plasmid, 7.5 µg packaging plasmid, and 5 µg envelope plasmid.","order":2,"step":"2"},{"desc":"Add 60 µL of transfection reagent and bring the volume up to 300 µL with serum-free medium.","order":3,"step":"3"},{"desc":"Incubate the mixture at room temperature for 15 minutes.","order":4,"step":"4"},{"desc":"Add the transfection mix dropwise to the HEK293T cells.","order":5,"step":"5"},{"desc":"Gently swirl the dish to evenly distribute the complex.","order":6,"step":"6"}]}
|
| 121 |
+
|
| 122 |
+
Return the visible protocol step ID for the watched video window.
|
| 123 |
+
```
|
| 124 |
+
|
| 125 |
+
PMD pipette mistake detection examples use a short clip and a fixed multiple-choice prompt:
|
| 126 |
+
|
| 127 |
+
```text
|
| 128 |
+
You are monitoring a scientist learning how to utilize tools in the wet-lab. You are in simple detection mode and are observing for common technique issues or misuse of tools. In the snippet of user practicing their pipette usage please select the closest option below that describes what happened in the video.
|
| 129 |
+
|
| 130 |
+
## Options
|
| 131 |
+
1. CORRECT: correct usage of pipette tip no mistakes
|
| 132 |
+
2. ERROR_REUSE: reused tip on different media causing contamination
|
| 133 |
+
3. ERROR_SURFACE: tip was contaminated by touching surface
|
| 134 |
+
4. ERROR_RELEASE: tip was dropped or released unexpectedly
|
| 135 |
+
5. ERROR_INSTALL: pipette tip installed (or attempted) was of wrong size/incorrectly fitted
|
| 136 |
+
6. ERROR_OTHER: when you are sure its wrong but it does not fit above category label as other
|
| 137 |
+
|
| 138 |
+
## Output format
|
| 139 |
+
Strict SINGLE_WORD all cap option response no other symbols or description from the options above.
|
| 140 |
+
```
|
| 141 |
+
|
| 142 |
+
## Install
|
| 143 |
+
|
| 144 |
+
```bash
|
| 145 |
+
python -m pip install -r requirements.txt
|
| 146 |
+
```
|
| 147 |
+
|
| 148 |
+
For local model inference, install a CUDA-enabled PyTorch stack plus the dependencies in `requirements.txt`. The reference inference runner supports Qwen2.5-VL-compatible models.
|
| 149 |
+
|
| 150 |
+
## Run Inference
|
| 151 |
+
|
| 152 |
+
```bash
|
| 153 |
+
python inference.py \
|
| 154 |
+
--model Qwen/Qwen2.5-VL-7B-Instruct \
|
| 155 |
+
--adapter cong-lab/labos-vlm-7b \
|
| 156 |
+
--output runs/labos_vlm_7b \
|
| 157 |
+
--gpus 0
|
| 158 |
+
```
|
| 159 |
+
|
| 160 |
+
Run the base model without an adapter:
|
| 161 |
+
|
| 162 |
+
```bash
|
| 163 |
+
python inference.py \
|
| 164 |
+
--model Qwen/Qwen2.5-VL-7B-Instruct \
|
| 165 |
+
--output runs/qwen25vl_7b \
|
| 166 |
+
--gpus 0
|
| 167 |
+
```
|
| 168 |
+
|
| 169 |
+
By default, `inference.py` runs `monitoring_step`, `monitor_next_step`, and `pmd`. To run a subset:
|
| 170 |
+
|
| 171 |
+
```bash
|
| 172 |
+
python inference.py \
|
| 173 |
+
--model Qwen/Qwen2.5-VL-7B-Instruct \
|
| 174 |
+
--tasks monitoring_step,pmd \
|
| 175 |
+
--output runs/subset
|
| 176 |
+
```
|
| 177 |
+
|
| 178 |
+
## Generate Report
|
| 179 |
+
|
| 180 |
+
```bash
|
| 181 |
+
python generate_report.py \
|
| 182 |
+
--output runs/qwen25vl_7b \
|
| 183 |
+
--report-dir runs/report
|
| 184 |
+
```
|
| 185 |
+
|
| 186 |
+
Compare multiple model outputs:
|
| 187 |
+
|
| 188 |
+
```bash
|
| 189 |
+
python generate_report.py \
|
| 190 |
+
--output runs/qwen25vl_7b \
|
| 191 |
+
--compare runs/labos_vlm_7b \
|
| 192 |
+
--report-dir runs/comparison_report
|
| 193 |
+
```
|
| 194 |
+
|
| 195 |
+
The report command writes `report.md`, `metrics.json`, `metrics.csv`, and plots. Metrics include balanced accuracy, F1, precision, recall, parse success, and confusion matrices. For PMD, these metrics are computed for Error Detection.
|
| 196 |
+
|
| 197 |
+
## Loading Examples
|
| 198 |
+
|
| 199 |
+
```python
|
| 200 |
+
from pathlib import Path
|
| 201 |
+
|
| 202 |
+
from lsvbench.tasks import get_task
|
| 203 |
+
|
| 204 |
+
root = Path(".")
|
| 205 |
+
task = get_task("monitoring_step")
|
| 206 |
+
rows = task.load_examples(benchmark_root=root, video_root=root, limit=5)
|
| 207 |
+
|
| 208 |
+
for row in rows:
|
| 209 |
+
print(row["eval_id"], row["video_path"], row["target_step_id"])
|
| 210 |
+
```
|
| 211 |
+
|
| 212 |
+
Load the table manifests directly with PyArrow:
|
| 213 |
+
|
| 214 |
+
```python
|
| 215 |
+
import pyarrow.parquet as pq
|
| 216 |
+
|
| 217 |
+
clips = pq.read_table("data/clips.parquet").to_pandas()
|
| 218 |
+
pmd = pq.read_table("pmd/pmd.parquet").to_pandas()
|
| 219 |
+
```
|
| 220 |
+
|
| 221 |
+
## Intended Use
|
| 222 |
+
|
| 223 |
+
This benchmark is intended for research on video-language models that assist with laboratory procedure monitoring, procedural state tracking, and visible error detection. It is not intended for clinical decision-making, safety-critical automation, or replacing trained human supervision in a real lab.
|
| 224 |
+
|
| 225 |
+
## Limitations
|
| 226 |
+
|
| 227 |
+
- The benchmark measures prompt-following and video understanding for specific LSV tasks; it is not a complete measure of wet-lab competence.
|
| 228 |
+
- Some tasks use 640px video mirrors for practical inference speed, which may omit fine visual details present in the original-resolution videos.
|
| 229 |
+
- PMD labels are designed for pipette-manipulation error detection and should not be interpreted as exhaustive procedural-error coverage.
|
| 230 |
+
- Model outputs are parsed from raw text responses, so formatting failures can affect reported metrics. If you notice very low scores on PMD error classification type or errors, please inspect outputs first to ensure it's not a parsing issue.
|
| 231 |
+
|
| 232 |
+
## License
|
| 233 |
+
|
| 234 |
+
This public package is released for non-commercial research use under the Creative Commons Attribution-NonCommercial 4.0 license (`CC-BY-NC-4.0`). Users are responsible for ensuring that their use of the videos, manifests, and derived model outputs complies with the license and applicable institutional policies.
|
| 235 |
+
|
| 236 |
+
## Research Use Only
|
| 237 |
+
|
| 238 |
+
This dataset is provided for research purposes only and for non-commercial use. It is not intended for clinical decision-making, autonomous laboratory operation, or replacing trained human supervision in real wet-lab procedures.
|
| 239 |
+
|
| 240 |
+
## Citation
|
| 241 |
+
|
| 242 |
+
If you use this benchmark, please cite the LabOS manuscript or dataset release associated with this repository.
|
data/clips.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5b035be1b30cf0225e15f6f7d5c7fa82970b88a7e297dd99c610d06d6d4ac04c
|
| 3 |
+
size 91092
|
data/dji.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5cd43dba110e875eb498e64c961e71f149635f40e0da2dca6b38622e2c0e6882
|
| 3 |
+
size 45190
|
data/monitor_next_step.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/monitoring_step_eval.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/multiview.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:707f019ed256d5fc975cd9a136c416107f01c66cb97700afb80aa43cab116132
|
| 3 |
+
size 32900
|
data/pmd.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f3a55d60cf79a0ac75514ce16bf697ba810981aa5897a9be4fbed7c250660991
|
| 3 |
+
size 23237
|
data/xm.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:70f6fdfc293c53e92ebf506930697aba4676341aadc2024a7ec7036da33a81a6
|
| 3 |
+
size 38633
|
generate_report.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Generate Markdown, JSON, CSV, and plots from benchmark raw outputs."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import json
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
from lsvbench.report import generate_report
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def main() -> None:
|
| 14 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 15 |
+
parser.add_argument("--output", type=Path, action="append", required=True, help="Benchmark output directory. Can be repeated.")
|
| 16 |
+
parser.add_argument("--compare", type=Path, action="append", default=[], help="Additional output directory to compare.")
|
| 17 |
+
parser.add_argument("--report-dir", type=Path, help="Where to write report.md, metrics, and plots. Defaults to first --output.")
|
| 18 |
+
args = parser.parse_args()
|
| 19 |
+
|
| 20 |
+
output_dirs = [*args.output, *args.compare]
|
| 21 |
+
result = generate_report(output_dirs, report_dir=args.report_dir)
|
| 22 |
+
print(json.dumps(result, indent=2, sort_keys=True))
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
if __name__ == "__main__":
|
| 26 |
+
main()
|
inference.py
ADDED
|
@@ -0,0 +1,378 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Reference Qwen/LabOS inference runner for standardized benchmark outputs."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
import subprocess
|
| 10 |
+
import sys
|
| 11 |
+
from datetime import datetime, timezone
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from typing import Any
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
from peft import PeftModel
|
| 17 |
+
from qwen_vl_utils import process_vision_info
|
| 18 |
+
from transformers import AutoConfig, AutoProcessor, Qwen2_5_VLForConditionalGeneration
|
| 19 |
+
|
| 20 |
+
from lsvbench.io import BENCHMARK_ROOT, OutputLayout, merge_shards, write_json, write_jsonl
|
| 21 |
+
from lsvbench.tasks import get_task
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
DEFAULT_LSV_ROOT = BENCHMARK_ROOT
|
| 25 |
+
MODEL_ALIASES = {
|
| 26 |
+
"labos-vlm7b": "Qwen/Qwen2.5-VL-7B-Instruct",
|
| 27 |
+
"labos-vlm-7b": "Qwen/Qwen2.5-VL-7B-Instruct",
|
| 28 |
+
"qwen25-7b": "Qwen/Qwen2.5-VL-7B-Instruct",
|
| 29 |
+
"qwen2.5-7b": "Qwen/Qwen2.5-VL-7B-Instruct",
|
| 30 |
+
}
|
| 31 |
+
ADAPTER_ALIASES = {
|
| 32 |
+
"labos-vlm7b": "cong-lab/labos-vlm-7b",
|
| 33 |
+
"labos-vlm-7b": "cong-lab/labos-vlm-7b",
|
| 34 |
+
}
|
| 35 |
+
MODEL_FAMILY_ALIASES = {
|
| 36 |
+
"auto": "auto",
|
| 37 |
+
"qwen25": "qwen2.5-vl",
|
| 38 |
+
"qwen25-vl": "qwen2.5-vl",
|
| 39 |
+
"qwen2.5": "qwen2.5-vl",
|
| 40 |
+
"qwen2.5-vl": "qwen2.5-vl",
|
| 41 |
+
}
|
| 42 |
+
QWEN25_VL_MODEL_TYPES = {"qwen2_5_vl"}
|
| 43 |
+
QWEN25_VL_ARCHITECTURES = {"Qwen2_5_VLForConditionalGeneration"}
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def parse_gpus(value: str) -> list[str]:
|
| 47 |
+
text = value.strip()
|
| 48 |
+
if not text:
|
| 49 |
+
return ["0"]
|
| 50 |
+
if "-" in text and "," not in text:
|
| 51 |
+
start, end = [int(part) for part in text.split("-", 1)]
|
| 52 |
+
return [str(idx) for idx in range(start, end + 1)]
|
| 53 |
+
return [part.strip() for part in text.split(",") if part.strip()]
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def resolve_model(value: str) -> str:
|
| 57 |
+
return MODEL_ALIASES.get(value, value)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def normalize_model_family(value: str) -> str:
|
| 61 |
+
family = MODEL_FAMILY_ALIASES.get(value.strip().lower())
|
| 62 |
+
if family is None:
|
| 63 |
+
supported = ", ".join(sorted(MODEL_FAMILY_ALIASES))
|
| 64 |
+
raise ValueError(f"Unsupported --model-family {value!r}. Supported values: {supported}")
|
| 65 |
+
return family
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def detect_model_family(model_name: str) -> str:
|
| 69 |
+
config = AutoConfig.from_pretrained(model_name, trust_remote_code=True)
|
| 70 |
+
model_type = str(getattr(config, "model_type", "") or "")
|
| 71 |
+
architectures = {str(item) for item in (getattr(config, "architectures", None) or [])}
|
| 72 |
+
if model_type in QWEN25_VL_MODEL_TYPES or architectures & QWEN25_VL_ARCHITECTURES:
|
| 73 |
+
return "qwen2.5-vl"
|
| 74 |
+
detail = f"model_type={model_type!r}, architectures={sorted(architectures)!r}"
|
| 75 |
+
raise ValueError(
|
| 76 |
+
"Could not infer a supported model family from model config "
|
| 77 |
+
f"for {model_name!r} ({detail}). Only qwen2.5-vl is currently implemented. "
|
| 78 |
+
"Pass --model-family qwen2.5-vl if this is a compatible Qwen2.5-VL checkpoint."
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def resolve_model_family(value: str, model_name: str) -> str:
|
| 83 |
+
family = normalize_model_family(value)
|
| 84 |
+
return detect_model_family(model_name) if family == "auto" else family
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def adapter_value(value: str | None) -> str | None:
|
| 88 |
+
if value is None:
|
| 89 |
+
return None
|
| 90 |
+
text = str(value).strip()
|
| 91 |
+
return None if not text or text.lower() in {"none", "null", "base"} else text
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def resolve_adapter(model_arg: str, adapter_arg: str | None) -> str | None:
|
| 95 |
+
explicit = adapter_value(adapter_arg)
|
| 96 |
+
return explicit if explicit is not None else ADAPTER_ALIASES.get(model_arg)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def load_model(args: argparse.Namespace) -> tuple[Any, Any]:
|
| 100 |
+
model_name = resolve_model(args.model)
|
| 101 |
+
model_family = resolve_model_family(args.model_family, model_name)
|
| 102 |
+
if model_family != "qwen2.5-vl":
|
| 103 |
+
raise ValueError(f"Unsupported model family {model_family!r}. Only qwen2.5-vl is currently implemented.")
|
| 104 |
+
processor = AutoProcessor.from_pretrained(model_name, trust_remote_code=True)
|
| 105 |
+
model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
| 106 |
+
model_name,
|
| 107 |
+
torch_dtype=torch.bfloat16,
|
| 108 |
+
device_map={"": "cuda:0"},
|
| 109 |
+
attn_implementation=args.attn_impl,
|
| 110 |
+
trust_remote_code=True,
|
| 111 |
+
)
|
| 112 |
+
adapter = resolve_adapter(args.model, args.adapter)
|
| 113 |
+
if adapter is not None:
|
| 114 |
+
model = PeftModel.from_pretrained(model, adapter)
|
| 115 |
+
model.eval()
|
| 116 |
+
return model, processor
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def normalize_video_kwargs(video_kwargs: dict[str, Any], batch_size: int) -> dict[str, Any]:
|
| 120 |
+
out = dict(video_kwargs)
|
| 121 |
+
for key, value in list(out.items()):
|
| 122 |
+
if isinstance(value, list) and len(value) == 1 and batch_size == 1:
|
| 123 |
+
out[key] = value[0]
|
| 124 |
+
return out
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def video_settings_for_task(task_name: str, args: argparse.Namespace) -> dict[str, Any]:
|
| 128 |
+
if task_name == "pmd":
|
| 129 |
+
return {
|
| 130 |
+
"fps": args.pmd_fps,
|
| 131 |
+
"min_frames": args.min_frames,
|
| 132 |
+
"max_frames": args.pmd_max_frames,
|
| 133 |
+
"min_pixels": args.min_pixels,
|
| 134 |
+
"max_pixels": args.pmd_max_pixels,
|
| 135 |
+
}
|
| 136 |
+
return {
|
| 137 |
+
"fps": args.fps,
|
| 138 |
+
"min_frames": args.min_frames,
|
| 139 |
+
"max_frames": args.max_frames,
|
| 140 |
+
"min_pixels": args.min_pixels,
|
| 141 |
+
"max_pixels": args.max_pixels,
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def prompt_for_row(task_name: str, row: dict[str, Any], args: argparse.Namespace) -> str:
|
| 146 |
+
if task_name == "pmd":
|
| 147 |
+
return Path(args.pmd_prompt).read_text(encoding="utf-8").strip()
|
| 148 |
+
return str(row["prompt"])
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def build_messages(task_name: str, row: dict[str, Any], args: argparse.Namespace) -> list[dict[str, Any]]:
|
| 152 |
+
video = {
|
| 153 |
+
"type": "video",
|
| 154 |
+
"video": row["_video_abs"],
|
| 155 |
+
**video_settings_for_task(task_name, args),
|
| 156 |
+
}
|
| 157 |
+
if task_name != "pmd":
|
| 158 |
+
video["video_start"] = float(row["video_start"])
|
| 159 |
+
video["video_end"] = float(row["video_end"])
|
| 160 |
+
return [
|
| 161 |
+
{
|
| 162 |
+
"role": "user",
|
| 163 |
+
"content": [
|
| 164 |
+
video,
|
| 165 |
+
{"type": "text", "text": prompt_for_row(task_name, row, args)},
|
| 166 |
+
],
|
| 167 |
+
}
|
| 168 |
+
]
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def generate_batch(model: Any, processor: Any, task_name: str, rows: list[dict[str, Any]], args: argparse.Namespace) -> list[str]:
|
| 172 |
+
batch_messages = [build_messages(task_name, row, args) for row in rows]
|
| 173 |
+
texts = [processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) for messages in batch_messages]
|
| 174 |
+
image_inputs, video_inputs, video_kwargs = process_vision_info(batch_messages, return_video_kwargs=True)
|
| 175 |
+
video_kwargs = normalize_video_kwargs(video_kwargs, len(rows))
|
| 176 |
+
inputs = processor(
|
| 177 |
+
text=texts,
|
| 178 |
+
images=image_inputs,
|
| 179 |
+
videos=video_inputs,
|
| 180 |
+
padding=True,
|
| 181 |
+
return_tensors="pt",
|
| 182 |
+
**video_kwargs,
|
| 183 |
+
).to(model.device)
|
| 184 |
+
with torch.inference_mode():
|
| 185 |
+
generated = model.generate(
|
| 186 |
+
**inputs,
|
| 187 |
+
max_new_tokens=args.pmd_max_new_tokens if task_name == "pmd" else args.max_new_tokens,
|
| 188 |
+
do_sample=False,
|
| 189 |
+
temperature=None,
|
| 190 |
+
top_p=None,
|
| 191 |
+
)
|
| 192 |
+
prompt_lens = inputs["attention_mask"].sum(dim=1).tolist()
|
| 193 |
+
decoded: list[str] = []
|
| 194 |
+
for idx, prompt_len in enumerate(prompt_lens):
|
| 195 |
+
text = processor.decode(
|
| 196 |
+
generated[idx, int(prompt_len) :],
|
| 197 |
+
skip_special_tokens=True,
|
| 198 |
+
clean_up_tokenization_spaces=False,
|
| 199 |
+
)
|
| 200 |
+
decoded.append(text.strip())
|
| 201 |
+
return decoded
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def safe_generate_batch(model: Any, processor: Any, task_name: str, rows: list[dict[str, Any]], args: argparse.Namespace) -> list[tuple[str, str | None]]:
|
| 205 |
+
try:
|
| 206 |
+
return [(text, None) for text in generate_batch(model, processor, task_name, rows, args)]
|
| 207 |
+
except Exception as exc:
|
| 208 |
+
if torch.cuda.is_available():
|
| 209 |
+
torch.cuda.empty_cache()
|
| 210 |
+
if len(rows) == 1:
|
| 211 |
+
return [("", f"{type(exc).__name__}: {exc}")]
|
| 212 |
+
outputs: list[tuple[str, str | None]] = []
|
| 213 |
+
for row in rows:
|
| 214 |
+
outputs.extend(safe_generate_batch(model, processor, task_name, [row], args))
|
| 215 |
+
return outputs
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def chunks(rows: list[dict[str, Any]], size: int) -> list[list[dict[str, Any]]]:
|
| 219 |
+
return [rows[idx : idx + size] for idx in range(0, len(rows), size)]
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def record_for_output(task_name: str, row: dict[str, Any], raw: str, error: str | None, args: argparse.Namespace) -> dict[str, Any]:
|
| 223 |
+
keep = {key: value for key, value in row.items() if not key.startswith("_")}
|
| 224 |
+
keep.update(
|
| 225 |
+
{
|
| 226 |
+
"task": task_name,
|
| 227 |
+
"raw_response": raw,
|
| 228 |
+
"error": error,
|
| 229 |
+
"shard_index": args.shard_index,
|
| 230 |
+
"num_shards": args.num_shards,
|
| 231 |
+
}
|
| 232 |
+
)
|
| 233 |
+
return keep
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def run_worker(args: argparse.Namespace) -> None:
|
| 237 |
+
os.environ.setdefault("FORCE_QWENVL_VIDEO_READER", "decord")
|
| 238 |
+
task = get_task(args.task)
|
| 239 |
+
video_root = BENCHMARK_ROOT if args.task == "pmd" else args.lsv_root
|
| 240 |
+
rows = task.load_examples(
|
| 241 |
+
benchmark_root=BENCHMARK_ROOT,
|
| 242 |
+
manifest_path=args.manifest,
|
| 243 |
+
video_root=video_root,
|
| 244 |
+
num_shards=args.num_shards,
|
| 245 |
+
shard_index=args.shard_index,
|
| 246 |
+
limit=args.limit,
|
| 247 |
+
)
|
| 248 |
+
model, processor = load_model(args)
|
| 249 |
+
layout = OutputLayout(args.output)
|
| 250 |
+
result_path = layout.shard_path(args.task, args.shard_index)
|
| 251 |
+
result_path.parent.mkdir(parents=True, exist_ok=True)
|
| 252 |
+
records: list[dict[str, Any]] = []
|
| 253 |
+
batch_size = args.pmd_batch_size if args.task == "pmd" else args.batch_size
|
| 254 |
+
for batch in chunks(rows, batch_size):
|
| 255 |
+
generated = safe_generate_batch(model, processor, args.task, batch, args)
|
| 256 |
+
for row, (raw, error) in zip(batch, generated, strict=True):
|
| 257 |
+
record = record_for_output(args.task, row, raw, error, args)
|
| 258 |
+
records.append(record)
|
| 259 |
+
print(json.dumps({"task": args.task, "id": row.get("eval_id") or row.get("video_id"), "error": error}), flush=True)
|
| 260 |
+
write_jsonl(result_path, records)
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def launch_workers(args: argparse.Namespace) -> None:
|
| 264 |
+
gpus = parse_gpus(args.gpus)
|
| 265 |
+
args.output.mkdir(parents=True, exist_ok=True)
|
| 266 |
+
write_json(
|
| 267 |
+
args.output / "run_config.json",
|
| 268 |
+
{
|
| 269 |
+
"model": resolve_model(args.model),
|
| 270 |
+
"model_arg": args.model,
|
| 271 |
+
"model_family": resolve_model_family(args.model_family, resolve_model(args.model)),
|
| 272 |
+
"adapter": resolve_adapter(args.model, args.adapter),
|
| 273 |
+
"tasks": args.tasks.split(","),
|
| 274 |
+
"created_at": datetime.now(timezone.utc).isoformat(),
|
| 275 |
+
"gpus": gpus,
|
| 276 |
+
"fps": args.fps,
|
| 277 |
+
"max_frames": args.max_frames,
|
| 278 |
+
"max_pixels": args.max_pixels,
|
| 279 |
+
"pmd_fps": args.pmd_fps,
|
| 280 |
+
"pmd_max_frames": args.pmd_max_frames,
|
| 281 |
+
"pmd_max_pixels": args.pmd_max_pixels,
|
| 282 |
+
},
|
| 283 |
+
)
|
| 284 |
+
for task_name in [task.strip() for task in args.tasks.split(",") if task.strip()]:
|
| 285 |
+
procs: list[subprocess.Popen[Any]] = []
|
| 286 |
+
for shard_index, gpu in enumerate(gpus):
|
| 287 |
+
cmd = [
|
| 288 |
+
sys.executable,
|
| 289 |
+
str(Path(__file__).resolve()),
|
| 290 |
+
"--worker",
|
| 291 |
+
"--task",
|
| 292 |
+
task_name,
|
| 293 |
+
"--model",
|
| 294 |
+
args.model,
|
| 295 |
+
"--model-family",
|
| 296 |
+
args.model_family,
|
| 297 |
+
"--output",
|
| 298 |
+
str(args.output),
|
| 299 |
+
"--gpus",
|
| 300 |
+
gpu,
|
| 301 |
+
"--num-shards",
|
| 302 |
+
str(len(gpus)),
|
| 303 |
+
"--shard-index",
|
| 304 |
+
str(shard_index),
|
| 305 |
+
"--batch-size",
|
| 306 |
+
str(args.batch_size),
|
| 307 |
+
"--pmd-batch-size",
|
| 308 |
+
str(args.pmd_batch_size),
|
| 309 |
+
"--max-new-tokens",
|
| 310 |
+
str(args.max_new_tokens),
|
| 311 |
+
"--pmd-max-new-tokens",
|
| 312 |
+
str(args.pmd_max_new_tokens),
|
| 313 |
+
"--attn-impl",
|
| 314 |
+
args.attn_impl,
|
| 315 |
+
"--lsv-root",
|
| 316 |
+
str(args.lsv_root),
|
| 317 |
+
]
|
| 318 |
+
effective_adapter = resolve_adapter(args.model, args.adapter)
|
| 319 |
+
if effective_adapter:
|
| 320 |
+
cmd.extend(["--adapter", effective_adapter])
|
| 321 |
+
if args.limit is not None:
|
| 322 |
+
cmd.extend(["--limit", str(args.limit)])
|
| 323 |
+
env = os.environ.copy()
|
| 324 |
+
env["CUDA_VISIBLE_DEVICES"] = gpu
|
| 325 |
+
env.setdefault("PYTHONPATH", str(BENCHMARK_ROOT))
|
| 326 |
+
env["PYTHONPATH"] = f"{BENCHMARK_ROOT}:{env['PYTHONPATH']}"
|
| 327 |
+
procs.append(subprocess.Popen(cmd, cwd=str(BENCHMARK_ROOT), env=env))
|
| 328 |
+
failures = [proc.wait() for proc in procs]
|
| 329 |
+
if any(code != 0 for code in failures):
|
| 330 |
+
raise SystemExit(f"Task {task_name} failed with exit codes: {failures}")
|
| 331 |
+
merge_shards(OutputLayout(args.output).task_dir(task_name), sort_key=get_task(task_name).sort_key)
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def main() -> None:
|
| 335 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 336 |
+
parser.add_argument("--model", required=True, help="Base or merged model as a Hugging Face repo ID, local path, or alias such as qwen25-7b.")
|
| 337 |
+
parser.add_argument(
|
| 338 |
+
"--model-family",
|
| 339 |
+
default="auto",
|
| 340 |
+
help="Inference backend to use: auto or qwen2.5-vl. Auto reads the model config from a Hugging Face repo ID or local path.",
|
| 341 |
+
)
|
| 342 |
+
parser.add_argument("--adapter", help="Optional PEFT/LoRA adapter as a Hugging Face repo ID or local path.")
|
| 343 |
+
parser.add_argument("--output", type=Path, required=True)
|
| 344 |
+
parser.add_argument("--tasks", default="monitoring_step,monitor_next_step,pmd")
|
| 345 |
+
parser.add_argument("--task", choices=sorted(["monitoring_step", "monitor_next_step", "pmd"]))
|
| 346 |
+
parser.add_argument("--manifest", type=Path)
|
| 347 |
+
parser.add_argument("--gpus", default="0")
|
| 348 |
+
parser.add_argument("--worker", action="store_true")
|
| 349 |
+
parser.add_argument("--num-shards", type=int, default=1)
|
| 350 |
+
parser.add_argument("--shard-index", type=int, default=0)
|
| 351 |
+
parser.add_argument("--limit", type=int)
|
| 352 |
+
parser.add_argument("--lsv-root", type=Path, default=DEFAULT_LSV_ROOT)
|
| 353 |
+
parser.add_argument("--batch-size", type=int, default=4)
|
| 354 |
+
parser.add_argument("--pmd-batch-size", type=int, default=4)
|
| 355 |
+
parser.add_argument("--fps", type=float, default=2.0)
|
| 356 |
+
parser.add_argument("--pmd-fps", type=float, default=8.0)
|
| 357 |
+
parser.add_argument("--min-frames", type=int, default=4)
|
| 358 |
+
parser.add_argument("--max-frames", type=int, default=128)
|
| 359 |
+
parser.add_argument("--pmd-max-frames", type=int, default=512)
|
| 360 |
+
parser.add_argument("--min-pixels", type=int, default=50176)
|
| 361 |
+
parser.add_argument("--max-pixels", type=int, default=100352)
|
| 362 |
+
parser.add_argument("--pmd-max-pixels", type=int, default=200704)
|
| 363 |
+
parser.add_argument("--max-new-tokens", type=int, default=2048)
|
| 364 |
+
parser.add_argument("--pmd-max-new-tokens", type=int, default=64)
|
| 365 |
+
parser.add_argument("--attn-impl", default="flash_attention_3")
|
| 366 |
+
parser.add_argument("--pmd-prompt", type=Path, default=BENCHMARK_ROOT / "lsvbench" / "tasks" / "prompts" / "pmd.md")
|
| 367 |
+
args = parser.parse_args()
|
| 368 |
+
|
| 369 |
+
if args.worker:
|
| 370 |
+
if not args.task:
|
| 371 |
+
raise SystemExit("--worker requires --task")
|
| 372 |
+
run_worker(args)
|
| 373 |
+
else:
|
| 374 |
+
launch_workers(args)
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
if __name__ == "__main__":
|
| 378 |
+
main()
|
lsvbench/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Modular benchmark helpers for lab VLM evaluation."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from .io import BENCHMARK_ROOT, OutputLayout
|
| 6 |
+
from .tasks import TASK_REGISTRY, get_task
|
| 7 |
+
|
| 8 |
+
__all__ = ["BENCHMARK_ROOT", "OutputLayout", "TASK_REGISTRY", "get_task"]
|
lsvbench/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (433 Bytes). View file
|
|
|
lsvbench/__pycache__/io.cpython-313.pyc
ADDED
|
Binary file (8.32 kB). View file
|
|
|
lsvbench/__pycache__/metrics.cpython-313.pyc
ADDED
|
Binary file (5.77 kB). View file
|
|
|
lsvbench/__pycache__/parsing.cpython-313.pyc
ADDED
|
Binary file (9.83 kB). View file
|
|
|
lsvbench/__pycache__/plots.cpython-313.pyc
ADDED
|
Binary file (16.9 kB). View file
|
|
|
lsvbench/__pycache__/report.cpython-313.pyc
ADDED
|
Binary file (8.52 kB). View file
|
|
|
lsvbench/io.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""I/O helpers and standard output layout for LSV benchmarks."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import shutil
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Any, Iterable
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
BENCHMARK_ROOT = Path(__file__).resolve().parents[1]
|
| 13 |
+
DATA_DIR = BENCHMARK_ROOT / "data"
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@dataclass(frozen=True)
|
| 17 |
+
class OutputLayout:
|
| 18 |
+
root: Path
|
| 19 |
+
|
| 20 |
+
@property
|
| 21 |
+
def run_config_path(self) -> Path:
|
| 22 |
+
return self.root / "run_config.json"
|
| 23 |
+
|
| 24 |
+
def task_dir(self, task_name: str) -> Path:
|
| 25 |
+
return self.root / task_name
|
| 26 |
+
|
| 27 |
+
def predictions_path(self, task_name: str) -> Path:
|
| 28 |
+
return self.task_dir(task_name) / "predictions.jsonl"
|
| 29 |
+
|
| 30 |
+
def legacy_predictions_path(self, task_name: str) -> Path:
|
| 31 |
+
return self.task_dir(task_name) / "per_video_results.jsonl"
|
| 32 |
+
|
| 33 |
+
def shard_path(self, task_name: str, shard_index: int) -> Path:
|
| 34 |
+
return self.task_dir(task_name) / f"predictions_shard_{shard_index:02d}.jsonl"
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def read_json(path: Path) -> dict[str, Any]:
|
| 38 |
+
return json.loads(path.read_text(encoding="utf-8"))
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def write_json(path: Path, value: Any) -> None:
|
| 42 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 43 |
+
path.write_text(json.dumps(value, indent=2, sort_keys=True, ensure_ascii=False) + "\n", encoding="utf-8")
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def read_jsonl(path: Path) -> list[dict[str, Any]]:
|
| 47 |
+
rows: list[dict[str, Any]] = []
|
| 48 |
+
if not path.exists():
|
| 49 |
+
return rows
|
| 50 |
+
with path.open("r", encoding="utf-8") as fh:
|
| 51 |
+
for line in fh:
|
| 52 |
+
line = line.strip()
|
| 53 |
+
if not line:
|
| 54 |
+
continue
|
| 55 |
+
try:
|
| 56 |
+
rows.append(json.loads(line))
|
| 57 |
+
except json.JSONDecodeError:
|
| 58 |
+
continue
|
| 59 |
+
return rows
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def write_jsonl(path: Path, rows: Iterable[dict[str, Any]]) -> None:
|
| 63 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 64 |
+
with path.open("w", encoding="utf-8") as fh:
|
| 65 |
+
for row in rows:
|
| 66 |
+
fh.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n")
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def append_jsonl(path: Path, row: dict[str, Any]) -> None:
|
| 70 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 71 |
+
with path.open("a", encoding="utf-8") as fh:
|
| 72 |
+
fh.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def load_json_manifest(path: Path) -> dict[str, Any]:
|
| 76 |
+
return read_json(path)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def manifest_examples(path: Path) -> list[dict[str, Any]]:
|
| 80 |
+
payload = load_json_manifest(path)
|
| 81 |
+
rows = payload.get("examples")
|
| 82 |
+
if not isinstance(rows, list):
|
| 83 |
+
raise ValueError(f"Manifest has no examples list: {path}")
|
| 84 |
+
return [dict(row) for row in rows if isinstance(row, dict)]
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def read_parquet(path: Path) -> list[dict[str, Any]]:
|
| 88 |
+
import pyarrow.parquet as pq
|
| 89 |
+
|
| 90 |
+
return pq.read_table(path).to_pylist()
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def select_shard(rows: list[dict[str, Any]], num_shards: int, shard_index: int) -> list[dict[str, Any]]:
|
| 94 |
+
if num_shards < 1:
|
| 95 |
+
raise ValueError("num_shards must be >= 1")
|
| 96 |
+
if not (0 <= shard_index < num_shards):
|
| 97 |
+
raise ValueError("shard_index must satisfy 0 <= shard_index < num_shards")
|
| 98 |
+
if num_shards == 1:
|
| 99 |
+
return rows
|
| 100 |
+
return [row for idx, row in enumerate(rows) if idx % num_shards == shard_index]
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def candidate_prediction_files(task_dir: Path) -> list[Path]:
|
| 104 |
+
paths = sorted(task_dir.glob("predictions_shard_*.jsonl"))
|
| 105 |
+
if paths:
|
| 106 |
+
return paths
|
| 107 |
+
paths = sorted(task_dir.glob("per_video_results_shard_*.jsonl"))
|
| 108 |
+
if paths:
|
| 109 |
+
return paths
|
| 110 |
+
for name in ("predictions.jsonl", "per_video_results.jsonl"):
|
| 111 |
+
path = task_dir / name
|
| 112 |
+
if path.exists():
|
| 113 |
+
return [path]
|
| 114 |
+
return []
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def load_prediction_rows(task_dir: Path, *, sort_key: str = "eval_id") -> list[dict[str, Any]]:
|
| 118 |
+
rows: list[dict[str, Any]] = []
|
| 119 |
+
for path in candidate_prediction_files(task_dir):
|
| 120 |
+
rows.extend(read_jsonl(path))
|
| 121 |
+
return sorted(rows, key=lambda row: str(row.get(sort_key) or row.get("video_id") or row.get("eval_id") or ""))
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def merge_shards(task_dir: Path, *, sort_key: str = "eval_id") -> list[dict[str, Any]]:
|
| 125 |
+
rows = load_prediction_rows(task_dir, sort_key=sort_key)
|
| 126 |
+
if rows:
|
| 127 |
+
write_jsonl(task_dir / "predictions.jsonl", rows)
|
| 128 |
+
return rows
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def copy_legacy_predictions(task_dir: Path) -> None:
|
| 132 |
+
predictions = task_dir / "predictions.jsonl"
|
| 133 |
+
legacy = task_dir / "per_video_results.jsonl"
|
| 134 |
+
if predictions.exists() and not legacy.exists():
|
| 135 |
+
shutil.copyfile(predictions, legacy)
|
lsvbench/metrics.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Generic metric helpers for benchmark tasks."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import random
|
| 6 |
+
import statistics
|
| 7 |
+
from collections import Counter
|
| 8 |
+
from typing import Any, Callable, Iterable
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def safe_div(num: float, denom: float) -> float | None:
|
| 12 |
+
return num / denom if denom else None
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def mean(values: Iterable[float | None]) -> float | None:
|
| 16 |
+
clean = [value for value in values if value is not None]
|
| 17 |
+
return sum(clean) / len(clean) if clean else None
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def classification_scores(
|
| 21 |
+
pairs: Iterable[tuple[Any, Any]],
|
| 22 |
+
*,
|
| 23 |
+
labels: Iterable[Any] | None = None,
|
| 24 |
+
none_is_wrong: bool = True,
|
| 25 |
+
) -> dict[str, Any]:
|
| 26 |
+
"""Compute accuracy, balanced accuracy, F1, precision, recall, and confusion."""
|
| 27 |
+
pair_list = list(pairs)
|
| 28 |
+
if labels is None:
|
| 29 |
+
label_values = sorted(
|
| 30 |
+
{
|
| 31 |
+
str(value)
|
| 32 |
+
for target, pred in pair_list
|
| 33 |
+
for value in (target, pred)
|
| 34 |
+
if value is not None
|
| 35 |
+
}
|
| 36 |
+
)
|
| 37 |
+
else:
|
| 38 |
+
label_values = [str(label) for label in labels]
|
| 39 |
+
total = len(pair_list)
|
| 40 |
+
correct = sum(1 for target, pred in pair_list if pred is not None and str(target) == str(pred))
|
| 41 |
+
target_total: Counter[str] = Counter()
|
| 42 |
+
pred_total: Counter[str] = Counter()
|
| 43 |
+
class_correct: Counter[str] = Counter()
|
| 44 |
+
confusion: Counter[str] = Counter()
|
| 45 |
+
for target, pred in pair_list:
|
| 46 |
+
target_s = str(target)
|
| 47 |
+
pred_s = "UNPARSED" if pred is None and none_is_wrong else str(pred)
|
| 48 |
+
target_total[target_s] += 1
|
| 49 |
+
pred_total[pred_s] += 1
|
| 50 |
+
confusion[f"{target_s}->{pred_s}"] += 1
|
| 51 |
+
if target_s == pred_s:
|
| 52 |
+
class_correct[target_s] += 1
|
| 53 |
+
|
| 54 |
+
recall: dict[str, float] = {}
|
| 55 |
+
precision: dict[str, float] = {}
|
| 56 |
+
f1: dict[str, float] = {}
|
| 57 |
+
for label in label_values:
|
| 58 |
+
recall[label] = class_correct[label] / target_total[label] if target_total[label] else 0.0
|
| 59 |
+
precision[label] = class_correct[label] / pred_total[label] if pred_total[label] else 0.0
|
| 60 |
+
denom = precision[label] + recall[label]
|
| 61 |
+
f1[label] = 2 * precision[label] * recall[label] / denom if denom else 0.0
|
| 62 |
+
return {
|
| 63 |
+
"accuracy": correct / total if total else None,
|
| 64 |
+
"balanced_accuracy": mean(recall.values()) if total and label_values else None,
|
| 65 |
+
"macro_f1": mean(f1.values()) if total and label_values else None,
|
| 66 |
+
"macro_precision": mean(precision.values()) if total and label_values else None,
|
| 67 |
+
"macro_recall": mean(recall.values()) if total and label_values else None,
|
| 68 |
+
"precision": precision,
|
| 69 |
+
"recall": recall,
|
| 70 |
+
"f1": f1,
|
| 71 |
+
"confusion": dict(confusion),
|
| 72 |
+
"target_counts": dict(target_total),
|
| 73 |
+
"pred_counts": dict(pred_total),
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def parse_success_rate(rows: list[dict[str, Any]], field: str = "pred_parse_ok") -> float | None:
|
| 78 |
+
if not rows:
|
| 79 |
+
return None
|
| 80 |
+
return sum(1 for row in rows if row.get(field)) / len(rows)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def metric_value(summary: dict[str, Any], metric: str) -> float | None:
|
| 84 |
+
value = summary.get(metric)
|
| 85 |
+
return value if isinstance(value, (int, float)) else None
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def bootstrap_sem(
|
| 89 |
+
rows: list[dict[str, Any]],
|
| 90 |
+
metric: str,
|
| 91 |
+
summarize_fn: Callable[[list[dict[str, Any]]], dict[str, Any]],
|
| 92 |
+
*,
|
| 93 |
+
iterations: int = 500,
|
| 94 |
+
seed: int = 17,
|
| 95 |
+
) -> float | None:
|
| 96 |
+
if not rows:
|
| 97 |
+
return None
|
| 98 |
+
rng = random.Random(f"{seed}:{metric}:{len(rows)}")
|
| 99 |
+
values: list[float] = []
|
| 100 |
+
for _ in range(iterations):
|
| 101 |
+
sample = [rows[rng.randrange(len(rows))] for _ in rows]
|
| 102 |
+
value = metric_value(summarize_fn(sample), metric)
|
| 103 |
+
if value is not None:
|
| 104 |
+
values.append(value)
|
| 105 |
+
if not values:
|
| 106 |
+
return None
|
| 107 |
+
return statistics.stdev(values) if len(values) > 1 else 0.0
|
lsvbench/parsing.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pure parsing helpers for benchmark model outputs."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import re
|
| 7 |
+
from typing import Any, Iterable, Mapping
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
FENCED_JSON_RE = re.compile(r"^\s*```(?:json|JSON)?\s*(.*?)\s*```\s*$", re.DOTALL)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def strip_markdown_json_fence(text: str) -> str:
|
| 14 |
+
cleaned = str(text or "").strip()
|
| 15 |
+
match = FENCED_JSON_RE.match(cleaned)
|
| 16 |
+
return match.group(1).strip() if match else cleaned
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def extract_json_text(text: str) -> str | None:
|
| 20 |
+
cleaned = strip_markdown_json_fence(text)
|
| 21 |
+
if not cleaned:
|
| 22 |
+
return None
|
| 23 |
+
start = cleaned.find("{")
|
| 24 |
+
if start < 0:
|
| 25 |
+
return None
|
| 26 |
+
depth = 0
|
| 27 |
+
in_string = False
|
| 28 |
+
escape = False
|
| 29 |
+
for idx, char in enumerate(cleaned[start:], start=start):
|
| 30 |
+
if in_string:
|
| 31 |
+
if escape:
|
| 32 |
+
escape = False
|
| 33 |
+
elif char == "\\":
|
| 34 |
+
escape = True
|
| 35 |
+
elif char == '"':
|
| 36 |
+
in_string = False
|
| 37 |
+
continue
|
| 38 |
+
if char == '"':
|
| 39 |
+
in_string = True
|
| 40 |
+
elif char == "{":
|
| 41 |
+
depth += 1
|
| 42 |
+
elif char == "}":
|
| 43 |
+
depth -= 1
|
| 44 |
+
if depth == 0:
|
| 45 |
+
return cleaned[start : idx + 1]
|
| 46 |
+
return None
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def extract_json_payload(text: str) -> dict[str, Any] | None:
|
| 50 |
+
payload_text = extract_json_text(text)
|
| 51 |
+
if not payload_text:
|
| 52 |
+
return None
|
| 53 |
+
try:
|
| 54 |
+
payload = json.loads(payload_text)
|
| 55 |
+
except Exception:
|
| 56 |
+
return None
|
| 57 |
+
return payload if isinstance(payload, dict) else None
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def normalize_step_id(value: Any) -> str | None:
|
| 61 |
+
if value is None:
|
| 62 |
+
return None
|
| 63 |
+
text = str(value).strip()
|
| 64 |
+
if not text or text.lower() == "null":
|
| 65 |
+
return None
|
| 66 |
+
match = re.fullmatch(r"(?:step|s)[_\-\s]*(\d+)", text, flags=re.IGNORECASE)
|
| 67 |
+
if match:
|
| 68 |
+
return match.group(1)
|
| 69 |
+
digits = re.sub(r"\D+", "", text)
|
| 70 |
+
return digits or None
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def parse_bool_field(value: Any) -> bool | None:
|
| 74 |
+
if isinstance(value, bool):
|
| 75 |
+
return value
|
| 76 |
+
if value is None:
|
| 77 |
+
return None
|
| 78 |
+
text = str(value).strip().lower()
|
| 79 |
+
if text in {"true", "yes", "y", "1", "correct"}:
|
| 80 |
+
return True
|
| 81 |
+
if text in {"false", "no", "n", "0", "incorrect"}:
|
| 82 |
+
return False
|
| 83 |
+
return None
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def parse_step_field(value: Any) -> str | None:
|
| 87 |
+
return normalize_step_id(value)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _normalize_option(value: Any) -> str:
|
| 91 |
+
return re.sub(r"[\s\-]+", "_", str(value or "").strip().upper())
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def strip_answer_tag(text: str) -> str:
|
| 95 |
+
cleaned = str(text or "").strip()
|
| 96 |
+
match = re.fullmatch(r"<answer>\s*(.*?)\s*</answer>", cleaned, flags=re.IGNORECASE | re.DOTALL)
|
| 97 |
+
return match.group(1).strip() if match else cleaned
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def parse_choice_option(
|
| 101 |
+
text: str,
|
| 102 |
+
options: Iterable[str],
|
| 103 |
+
*,
|
| 104 |
+
json_keys: Iterable[str] = ("option", "answer", "prediction", "pred_option", "choice", "label", "mistake_type"),
|
| 105 |
+
number_map: Mapping[str, str] | None = None,
|
| 106 |
+
) -> str | None:
|
| 107 |
+
option_list = [_normalize_option(option) for option in options]
|
| 108 |
+
option_set = set(option_list)
|
| 109 |
+
normalized_number_map = {
|
| 110 |
+
str(key): _normalize_option(value)
|
| 111 |
+
for key, value in (number_map or {}).items()
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
payload = extract_json_payload(text)
|
| 115 |
+
if payload is not None:
|
| 116 |
+
for key in json_keys:
|
| 117 |
+
if key not in payload:
|
| 118 |
+
continue
|
| 119 |
+
parsed = parse_choice_option(
|
| 120 |
+
str(payload[key]),
|
| 121 |
+
option_list,
|
| 122 |
+
json_keys=(),
|
| 123 |
+
number_map=normalized_number_map,
|
| 124 |
+
)
|
| 125 |
+
if parsed is not None:
|
| 126 |
+
return parsed
|
| 127 |
+
|
| 128 |
+
cleaned = strip_answer_tag(strip_markdown_json_fence(text))
|
| 129 |
+
upper = _normalize_option(cleaned)
|
| 130 |
+
if upper in option_set:
|
| 131 |
+
return upper
|
| 132 |
+
if upper in normalized_number_map:
|
| 133 |
+
return normalized_number_map[upper]
|
| 134 |
+
|
| 135 |
+
first_line = cleaned.splitlines()[0].strip() if cleaned else ""
|
| 136 |
+
first_token = re.split(r"[\s:.)\-\]]+", first_line, maxsplit=1)[0].strip().upper()
|
| 137 |
+
if first_token in normalized_number_map:
|
| 138 |
+
return normalized_number_map[first_token]
|
| 139 |
+
if first_token in option_set:
|
| 140 |
+
return first_token
|
| 141 |
+
|
| 142 |
+
pattern = r"\b(" + "|".join(re.escape(option) for option in sorted(option_set, key=len, reverse=True)) + r")\b"
|
| 143 |
+
matches = re.findall(pattern, _normalize_option(cleaned))
|
| 144 |
+
unique = sorted(set(matches))
|
| 145 |
+
return unique[0] if len(unique) == 1 else None
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def parse_monitoring_response(text: str) -> tuple[bool | None, str | None]:
|
| 149 |
+
cleaned = strip_markdown_json_fence(text)
|
| 150 |
+
payload = extract_json_payload(cleaned)
|
| 151 |
+
if payload is not None:
|
| 152 |
+
candidate = parse_bool_field(payload.get("candidate_matches_visible_step"))
|
| 153 |
+
step_id = payload.get("observed_step_id")
|
| 154 |
+
step_value = None if step_id in (None, "", "null") else str(step_id)
|
| 155 |
+
return candidate, step_value
|
| 156 |
+
|
| 157 |
+
upper = cleaned.upper()
|
| 158 |
+
if re.search(r"\b(TRUE|YES)\b", upper):
|
| 159 |
+
return True, None
|
| 160 |
+
if re.search(r"\b(FALSE|NO)\b", upper):
|
| 161 |
+
return False, None
|
| 162 |
+
return None, None
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def parse_next_step_delta_response(text: str) -> dict[str, Any]:
|
| 166 |
+
payload = extract_json_payload(text)
|
| 167 |
+
if payload is None:
|
| 168 |
+
return {
|
| 169 |
+
"pred_current_step_id": None,
|
| 170 |
+
"pred_has_error": None,
|
| 171 |
+
"pred_has_step_skipped": None,
|
| 172 |
+
"pred_error_type": None,
|
| 173 |
+
"pred_error_step_id": None,
|
| 174 |
+
"pred_parse_ok": False,
|
| 175 |
+
}
|
| 176 |
+
current = payload.get("current_step")
|
| 177 |
+
if current in (None, "", "null"):
|
| 178 |
+
current = None
|
| 179 |
+
errors = payload.get("errors")
|
| 180 |
+
if not isinstance(errors, list):
|
| 181 |
+
errors = []
|
| 182 |
+
parsed_errors = [item for item in errors if isinstance(item, dict)]
|
| 183 |
+
error_types = [
|
| 184 |
+
str(item.get("error_type") or "").strip()
|
| 185 |
+
for item in parsed_errors
|
| 186 |
+
if str(item.get("error_type") or "").strip()
|
| 187 |
+
]
|
| 188 |
+
non_none_error_types = [kind for kind in error_types if kind.lower() != "none"]
|
| 189 |
+
skipped = any(kind.lower() == "step_skipped" for kind in error_types)
|
| 190 |
+
step_ref = None
|
| 191 |
+
for item in parsed_errors:
|
| 192 |
+
if str(item.get("error_type") or "").strip().lower() == "step_skipped":
|
| 193 |
+
step_ref = item.get("step_ref")
|
| 194 |
+
break
|
| 195 |
+
if step_ref in (None, "", "null"):
|
| 196 |
+
step_ref = None
|
| 197 |
+
return {
|
| 198 |
+
"pred_current_step_id": None if current is None else str(current),
|
| 199 |
+
"pred_has_error": bool(non_none_error_types),
|
| 200 |
+
"pred_has_step_skipped": skipped,
|
| 201 |
+
"pred_error_type": non_none_error_types[0] if non_none_error_types else None,
|
| 202 |
+
"pred_error_step_id": None if step_ref is None else str(step_ref),
|
| 203 |
+
"pred_parse_ok": True,
|
| 204 |
+
}
|
lsvbench/plots.py
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Standard matplotlib plots for benchmark reports."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
import matplotlib.pyplot as plt
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
TASK_METRICS = {
|
| 12 |
+
"monitoring_step": {
|
| 13 |
+
"source_task": "monitoring_step",
|
| 14 |
+
"label": "Step Prediction",
|
| 15 |
+
"balanced_accuracy": "step_balanced_accuracy",
|
| 16 |
+
"f1": "step_macro_f1",
|
| 17 |
+
"precision": "step_macro_precision",
|
| 18 |
+
"recall": "step_macro_recall",
|
| 19 |
+
"accuracy": "step_identification_accuracy",
|
| 20 |
+
"parse_success": "parse_success_rate",
|
| 21 |
+
},
|
| 22 |
+
"monitor_next_step": {
|
| 23 |
+
"source_task": "monitor_next_step",
|
| 24 |
+
"label": "Advance Prediction",
|
| 25 |
+
"balanced_accuracy": "advance_step_balanced_accuracy",
|
| 26 |
+
"f1": "advance_step_macro_f1",
|
| 27 |
+
"precision": "advance_step_macro_precision",
|
| 28 |
+
"recall": "advance_step_macro_recall",
|
| 29 |
+
"accuracy": "advance_step_accuracy",
|
| 30 |
+
"parse_success": "parse_success_rate",
|
| 31 |
+
},
|
| 32 |
+
"pmd_detection": {
|
| 33 |
+
"source_task": "pmd",
|
| 34 |
+
"label": "Error Detection",
|
| 35 |
+
"balanced_accuracy": "binary_balanced_accuracy",
|
| 36 |
+
"f1": "binary_macro_f1",
|
| 37 |
+
"precision": "binary_macro_precision",
|
| 38 |
+
"recall": "binary_macro_recall",
|
| 39 |
+
"accuracy": "binary_accuracy",
|
| 40 |
+
"parse_success": "parse_success_rate",
|
| 41 |
+
},
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
TASK_LABELS = {
|
| 46 |
+
"monitoring_step": "Step Prediction",
|
| 47 |
+
"monitor_next_step": "Advance Prediction",
|
| 48 |
+
"pmd": "Error Detection",
|
| 49 |
+
"pmd_detection": "Error Detection",
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
LSV_BALANCED_PANELS = [
|
| 54 |
+
("monitoring_step", "step_balanced_accuracy", "Protocol Monitoring Step\nPrediction Accuracy"),
|
| 55 |
+
("monitor_next_step", "advance_step_balanced_accuracy", "Protocol Monitoring Step\nAdvanced Prediction Accuracy"),
|
| 56 |
+
("pmd", "binary_balanced_accuracy", "Error Detection"),
|
| 57 |
+
]
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
MODEL_STYLE = {
|
| 61 |
+
"cosmos_reason": ("Cosmos\nReason", "#6B7280"),
|
| 62 |
+
"qwen25vl_7b": ("Qwen2.5\n7B", "#8C6D31"),
|
| 63 |
+
"labos7b_lora750": ("LabOS\nVLM 7B", "#2A7F62"),
|
| 64 |
+
"qwen25vl_32b": ("Qwen2.5\n32B", "#B08A3C"),
|
| 65 |
+
"labos32b_lora750": ("LabOS\nVLM 32B", "#1F6B53"),
|
| 66 |
+
"labos7b_lora750_hf": ("LabOS\nVLM 7B HF", "#2A7F62"),
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _value(summary: dict[str, Any], metric: str) -> float:
|
| 71 |
+
value = summary.get(metric)
|
| 72 |
+
return float(value) * 100.0 if isinstance(value, (int, float)) else 0.0
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _sem(summary: dict[str, Any], metric: str) -> float:
|
| 76 |
+
value = summary.get(f"{metric}_sem")
|
| 77 |
+
return float(value) * 100.0 if isinstance(value, (int, float)) else 0.0
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _model_style(row: dict[str, Any]) -> tuple[str, str]:
|
| 81 |
+
key = str(row.get("model_key") or row.get("model_label") or "")
|
| 82 |
+
label = str(row.get("model_label") or key)
|
| 83 |
+
if key in MODEL_STYLE:
|
| 84 |
+
return MODEL_STYLE[key]
|
| 85 |
+
if label in MODEL_STYLE:
|
| 86 |
+
return MODEL_STYLE[label]
|
| 87 |
+
pretty = label.replace("_", "\n")
|
| 88 |
+
return pretty, "#4F9B7B"
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _paper_x_positions(labels: list[str]) -> list[float]:
|
| 92 |
+
positions: list[float] = []
|
| 93 |
+
current = 0.0
|
| 94 |
+
previous = ""
|
| 95 |
+
for idx, label in enumerate(labels):
|
| 96 |
+
flat_label = label.replace("\n", " ")
|
| 97 |
+
if idx == 0:
|
| 98 |
+
current = 0.0
|
| 99 |
+
elif "Cosmos" in previous:
|
| 100 |
+
current += 1.25
|
| 101 |
+
elif "32B" in flat_label and "32B" not in previous:
|
| 102 |
+
current += 1.02
|
| 103 |
+
else:
|
| 104 |
+
current += 0.68
|
| 105 |
+
positions.append(current)
|
| 106 |
+
previous = flat_label
|
| 107 |
+
return positions
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def _paper_group_separators(labels: list[str], x: list[float]) -> list[float]:
|
| 111 |
+
separators: list[float] = []
|
| 112 |
+
for idx in range(len(labels) - 1):
|
| 113 |
+
left = labels[idx].replace("\n", " ")
|
| 114 |
+
right = labels[idx + 1].replace("\n", " ")
|
| 115 |
+
if "Cosmos" in left or ("32B" in right and "32B" not in left):
|
| 116 |
+
separators.append((x[idx] + x[idx + 1]) / 2.0)
|
| 117 |
+
return separators
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def plot_lsv_balanced_accuracy(model_results: list[dict[str, Any]], output_path: Path) -> None:
|
| 121 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 122 |
+
labels: list[str] = []
|
| 123 |
+
colors: list[str] = []
|
| 124 |
+
for row in model_results:
|
| 125 |
+
label, color = _model_style(row)
|
| 126 |
+
labels.append(label)
|
| 127 |
+
colors.append(color)
|
| 128 |
+
x = _paper_x_positions(labels)
|
| 129 |
+
fig, axes = plt.subplots(1, 3, figsize=(9.4, 3.25), sharey=True)
|
| 130 |
+
for ax, (task_name, metric, title) in zip(axes, LSV_BALANCED_PANELS, strict=True):
|
| 131 |
+
values = []
|
| 132 |
+
errors = []
|
| 133 |
+
for row in model_results:
|
| 134 |
+
summary = row["tasks"].get(task_name, {})
|
| 135 |
+
values.append(_value(summary, metric))
|
| 136 |
+
errors.append(_sem(summary, metric))
|
| 137 |
+
bars = ax.bar(
|
| 138 |
+
x,
|
| 139 |
+
values,
|
| 140 |
+
width=0.66,
|
| 141 |
+
color=colors,
|
| 142 |
+
edgecolor="#2F2F2F",
|
| 143 |
+
linewidth=0.5,
|
| 144 |
+
yerr=errors,
|
| 145 |
+
capsize=2.5,
|
| 146 |
+
error_kw={"elinewidth": 0.8, "capthick": 0.8, "ecolor": "#333333"},
|
| 147 |
+
)
|
| 148 |
+
for bar, value, error in zip(bars, values, errors, strict=True):
|
| 149 |
+
ax.text(
|
| 150 |
+
bar.get_x() + bar.get_width() / 2,
|
| 151 |
+
value + error + 1.2,
|
| 152 |
+
f"{value:.0f}",
|
| 153 |
+
ha="center",
|
| 154 |
+
va="bottom",
|
| 155 |
+
fontsize=7,
|
| 156 |
+
clip_on=False,
|
| 157 |
+
)
|
| 158 |
+
ax.set_title(title, fontsize=10)
|
| 159 |
+
ax.set_ylim(0, 80)
|
| 160 |
+
ax.set_xticks(x)
|
| 161 |
+
ax.set_xticklabels(labels, fontsize=7)
|
| 162 |
+
for tick in ax.get_xticklabels():
|
| 163 |
+
if "LabOS" in tick.get_text():
|
| 164 |
+
tick.set_fontweight("bold")
|
| 165 |
+
for separator in _paper_group_separators(labels, x):
|
| 166 |
+
ax.axvline(separator, color="#6B7280", linewidth=0.6, alpha=0.35)
|
| 167 |
+
ax.spines["top"].set_visible(False)
|
| 168 |
+
ax.spines["right"].set_visible(False)
|
| 169 |
+
axes[0].set_ylabel(r"Accuracy (%) $\pm$ SEM")
|
| 170 |
+
fig.suptitle("LSV Benchmark v1", y=0.98, fontsize=11)
|
| 171 |
+
fig.tight_layout(pad=0.7, rect=(0, 0, 1, 0.95))
|
| 172 |
+
fig.savefig(output_path, dpi=220, bbox_inches="tight")
|
| 173 |
+
plt.close(fig)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def plot_grouped_metric(
|
| 177 |
+
model_results: list[dict[str, Any]],
|
| 178 |
+
*,
|
| 179 |
+
metric_kind: str,
|
| 180 |
+
output_path: Path,
|
| 181 |
+
ylabel: str,
|
| 182 |
+
) -> None:
|
| 183 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 184 |
+
models = [row["model_label"] for row in model_results]
|
| 185 |
+
tasks = [
|
| 186 |
+
task
|
| 187 |
+
for task, metrics in TASK_METRICS.items()
|
| 188 |
+
if any(metrics["source_task"] in row["tasks"] for row in model_results)
|
| 189 |
+
]
|
| 190 |
+
x = list(range(len(tasks)))
|
| 191 |
+
width = min(0.8 / max(len(models), 1), 0.22)
|
| 192 |
+
fig, ax = plt.subplots(figsize=(max(6.5, 1.2 * len(tasks) + 0.8 * len(models)), 3.8))
|
| 193 |
+
for model_idx, row in enumerate(model_results):
|
| 194 |
+
offsets = [pos + (model_idx - (len(models) - 1) / 2) * width for pos in x]
|
| 195 |
+
values = []
|
| 196 |
+
errors = []
|
| 197 |
+
for task in tasks:
|
| 198 |
+
task_metrics = TASK_METRICS[task]
|
| 199 |
+
summary = row["tasks"].get(task_metrics["source_task"], {})
|
| 200 |
+
metric = TASK_METRICS[task][metric_kind]
|
| 201 |
+
values.append(_value(summary, metric))
|
| 202 |
+
errors.append(_sem(summary, metric))
|
| 203 |
+
ax.bar(offsets, values, width=width, label=row["model_label"], yerr=errors, capsize=2)
|
| 204 |
+
ax.set_title(f"{metric_kind.replace('_', ' ').title()} Across Tasks")
|
| 205 |
+
ax.set_ylabel(ylabel)
|
| 206 |
+
ax.set_ylim(0, 105)
|
| 207 |
+
ax.set_xticks(x)
|
| 208 |
+
ax.set_xticklabels([TASK_METRICS[task]["label"] for task in tasks])
|
| 209 |
+
ax.legend(fontsize=7)
|
| 210 |
+
ax.spines["top"].set_visible(False)
|
| 211 |
+
ax.spines["right"].set_visible(False)
|
| 212 |
+
fig.tight_layout()
|
| 213 |
+
fig.savefig(output_path, dpi=220, bbox_inches="tight")
|
| 214 |
+
plt.close(fig)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def plot_composite(model_results: list[dict[str, Any]], output_path: Path) -> None:
|
| 218 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 219 |
+
labels = [row["model_label"] for row in model_results]
|
| 220 |
+
values = []
|
| 221 |
+
for row in model_results:
|
| 222 |
+
task_values = []
|
| 223 |
+
for _, metrics in TASK_METRICS.items():
|
| 224 |
+
source_task = metrics["source_task"]
|
| 225 |
+
if source_task in row["tasks"]:
|
| 226 |
+
value = row["tasks"][source_task].get(metrics["balanced_accuracy"])
|
| 227 |
+
if isinstance(value, (int, float)):
|
| 228 |
+
task_values.append(float(value))
|
| 229 |
+
values.append((sum(task_values) / len(task_values) * 100.0) if task_values else 0.0)
|
| 230 |
+
fig, ax = plt.subplots(figsize=(max(5.5, 0.8 * len(labels)), 3.4))
|
| 231 |
+
bars = ax.bar(range(len(labels)), values, color="#4F9B7B", edgecolor="#2F2F2F", linewidth=0.5)
|
| 232 |
+
for bar, value in zip(bars, values, strict=True):
|
| 233 |
+
ax.text(bar.get_x() + bar.get_width() / 2, value + 1, f"{value:.0f}", ha="center", va="bottom", fontsize=8)
|
| 234 |
+
ax.set_title("Composite Balanced Accuracy")
|
| 235 |
+
ax.set_ylabel("Score (%)")
|
| 236 |
+
ax.set_ylim(0, 105)
|
| 237 |
+
ax.set_xticks(range(len(labels)))
|
| 238 |
+
ax.set_xticklabels(labels, rotation=25, ha="right")
|
| 239 |
+
ax.spines["top"].set_visible(False)
|
| 240 |
+
ax.spines["right"].set_visible(False)
|
| 241 |
+
fig.tight_layout()
|
| 242 |
+
fig.savefig(output_path, dpi=220, bbox_inches="tight")
|
| 243 |
+
plt.close(fig)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def plot_confusion(confusion: dict[str, int], output_path: Path, title: str) -> None:
|
| 247 |
+
if not confusion:
|
| 248 |
+
return
|
| 249 |
+
labels = sorted({part for key in confusion for part in key.split("->", 1)})
|
| 250 |
+
matrix = [[confusion.get(f"{target}->{pred}", 0) for pred in labels] for target in labels]
|
| 251 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 252 |
+
fig, ax = plt.subplots(figsize=(max(4.2, 0.55 * len(labels)), max(3.8, 0.45 * len(labels))))
|
| 253 |
+
image = ax.imshow(matrix, cmap="Blues")
|
| 254 |
+
ax.set_title(title)
|
| 255 |
+
ax.set_xlabel("Predicted")
|
| 256 |
+
ax.set_ylabel("Target")
|
| 257 |
+
ax.set_xticks(range(len(labels)))
|
| 258 |
+
ax.set_xticklabels(labels, rotation=45, ha="right", fontsize=7)
|
| 259 |
+
ax.set_yticks(range(len(labels)))
|
| 260 |
+
ax.set_yticklabels(labels, fontsize=7)
|
| 261 |
+
for row_idx, row in enumerate(matrix):
|
| 262 |
+
for col_idx, value in enumerate(row):
|
| 263 |
+
ax.text(col_idx, row_idx, str(value), ha="center", va="center", fontsize=7)
|
| 264 |
+
fig.colorbar(image, ax=ax, fraction=0.046, pad=0.04)
|
| 265 |
+
fig.tight_layout()
|
| 266 |
+
fig.savefig(output_path, dpi=220, bbox_inches="tight")
|
| 267 |
+
plt.close(fig)
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def write_standard_plots(model_results: list[dict[str, Any]], output_dir: Path) -> list[Path]:
|
| 271 |
+
plots_dir = output_dir / "plots"
|
| 272 |
+
paths: list[Path] = []
|
| 273 |
+
plot_composite(model_results, plots_dir / "composite_balanced_accuracy.png")
|
| 274 |
+
paths.append(plots_dir / "composite_balanced_accuracy.png")
|
| 275 |
+
plot_lsv_balanced_accuracy(model_results, plots_dir / "lsv_benchmark_v1_balanced_accuracy.png")
|
| 276 |
+
paths.append(plots_dir / "lsv_benchmark_v1_balanced_accuracy.png")
|
| 277 |
+
for metric_kind, ylabel in (
|
| 278 |
+
("balanced_accuracy", "Balanced Accuracy (%)"),
|
| 279 |
+
("f1", "F1 (%)"),
|
| 280 |
+
("precision", "Macro Precision (%)"),
|
| 281 |
+
("recall", "Macro Recall (%)"),
|
| 282 |
+
("parse_success", "Parse Success (%)"),
|
| 283 |
+
):
|
| 284 |
+
path = plots_dir / f"{metric_kind}.png"
|
| 285 |
+
plot_grouped_metric(model_results, metric_kind=metric_kind, output_path=path, ylabel=ylabel)
|
| 286 |
+
paths.append(path)
|
| 287 |
+
for row in model_results:
|
| 288 |
+
safe_model = row["model_label"].replace("/", "_")
|
| 289 |
+
for task, summary in row["tasks"].items():
|
| 290 |
+
confusion = (
|
| 291 |
+
summary.get("step_confusion")
|
| 292 |
+
or summary.get("advance_step_confusion")
|
| 293 |
+
or summary.get("binary_confusion")
|
| 294 |
+
or {}
|
| 295 |
+
)
|
| 296 |
+
path = plots_dir / f"{safe_model}_{task}_confusion.png"
|
| 297 |
+
plot_confusion(confusion, path, f"{row['model_label']} - {TASK_LABELS.get(task, task)} Confusion")
|
| 298 |
+
if path.exists():
|
| 299 |
+
paths.append(path)
|
| 300 |
+
return paths
|
lsvbench/prompts.py
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Reusable prompt builders for LSV benchmark tasks."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
from typing import Any, Literal
|
| 7 |
+
|
| 8 |
+
ProtocolStyle = Literal["json", "flat_numbered", "substeps", "substeps_with_details"]
|
| 9 |
+
|
| 10 |
+
MONITORING_DELTA_SCHEMA: dict[str, Any] = {
|
| 11 |
+
"current_step": "step_id string or null",
|
| 12 |
+
"new_notes": [
|
| 13 |
+
{
|
| 14 |
+
"t": "number # start time of the action in seconds",
|
| 15 |
+
"note": "string # concise natural-language observation",
|
| 16 |
+
}
|
| 17 |
+
],
|
| 18 |
+
"errors": [
|
| 19 |
+
{
|
| 20 |
+
"t": "number",
|
| 21 |
+
"error_type": (
|
| 22 |
+
"step_skipped | step_reordered | reagent_wrong | volume_wrong | "
|
| 23 |
+
"technique_error | contamination_risk | timing_error | none"
|
| 24 |
+
),
|
| 25 |
+
"step_ref": "step_id string or null",
|
| 26 |
+
"description": "string",
|
| 27 |
+
}
|
| 28 |
+
],
|
| 29 |
+
"suggestion": "string or null # brief next-action hint for the user",
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def compact_json(value: Any) -> str:
|
| 34 |
+
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def response_format_block(skeleton: Any) -> str:
|
| 38 |
+
rendered = skeleton.strip() if isinstance(skeleton, str) else json.dumps(skeleton, ensure_ascii=False, sort_keys=True, indent=2)
|
| 39 |
+
return f"Return strict JSON only.\n\n## Response Format\n{rendered}"
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def render_monitoring_delta_prompt(state: dict[str, Any]) -> str:
|
| 43 |
+
instructions = [
|
| 44 |
+
"You are a real-time lab assistant monitoring a scientist's wet-lab procedure from short video windows.",
|
| 45 |
+
"The current protocol state/history is provided below. Watch the current window and update the state.",
|
| 46 |
+
"Report protocol errors only when supported by the visible time window or state.",
|
| 47 |
+
"Ignore irrelevant unknown keys in the state JSON.",
|
| 48 |
+
"Given the protocol being followed, the history of completed steps, and a new video window, update the monitoring state by returning a delta JSON.",
|
| 49 |
+
]
|
| 50 |
+
return "\n\n".join(
|
| 51 |
+
[
|
| 52 |
+
*instructions,
|
| 53 |
+
f"STATE:\n{compact_json(state)}",
|
| 54 |
+
response_format_block(MONITORING_DELTA_SCHEMA),
|
| 55 |
+
"Return a delta JSON for only the watched lab video window.",
|
| 56 |
+
]
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _load_protocol(protocol: dict[str, Any] | str) -> dict[str, Any]:
|
| 61 |
+
return json.loads(protocol) if isinstance(protocol, str) and protocol.strip() else (protocol if isinstance(protocol, dict) else {})
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def executable_steps(protocol: dict[str, Any] | str) -> list[dict[str, Any]]:
|
| 65 |
+
payload = _load_protocol(protocol)
|
| 66 |
+
return [
|
| 67 |
+
step
|
| 68 |
+
for step in list(payload.get("steps") or [])
|
| 69 |
+
if isinstance(step, dict) and str(step.get("text") or "").strip()
|
| 70 |
+
]
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def protocol_to_text(protocol: dict[str, Any] | str, style: ProtocolStyle = "flat_numbered") -> str:
|
| 74 |
+
payload = _load_protocol(protocol)
|
| 75 |
+
if style == "json":
|
| 76 |
+
return compact_json(payload)
|
| 77 |
+
if style == "flat_numbered":
|
| 78 |
+
return "\n".join(
|
| 79 |
+
f"{idx}. {step.get('text', '')}"
|
| 80 |
+
for idx, step in enumerate(executable_steps(payload), start=1)
|
| 81 |
+
)
|
| 82 |
+
title = str(payload.get("title") or "Demonstrated procedure").strip()
|
| 83 |
+
lines = [f"1. {title}"]
|
| 84 |
+
include_details = style == "substeps_with_details"
|
| 85 |
+
for idx, step in enumerate(executable_steps(payload), start=1):
|
| 86 |
+
suffix = ""
|
| 87 |
+
if include_details:
|
| 88 |
+
details = []
|
| 89 |
+
if step.get("demonstrated") is not None:
|
| 90 |
+
details.append(f"demonstrated={bool(step.get('demonstrated'))}")
|
| 91 |
+
if step.get("t_start") is not None and step.get("t_end") is not None:
|
| 92 |
+
details.append(f"time={float(step['t_start']):.1f}-{float(step['t_end']):.1f}s")
|
| 93 |
+
suffix = f" ({'; '.join(details)})" if details else ""
|
| 94 |
+
lines.append(f" 1.{idx}. {step.get('text', '')}{suffix}")
|
| 95 |
+
return "\n".join(lines)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def protocol_response_format(output_style: ProtocolStyle = "flat_numbered", include_flat_lists: bool = False) -> str:
|
| 99 |
+
if output_style == "json":
|
| 100 |
+
return response_format_block(
|
| 101 |
+
{
|
| 102 |
+
"title": "string",
|
| 103 |
+
"summary": "string or null",
|
| 104 |
+
"steps": [
|
| 105 |
+
{
|
| 106 |
+
"step_id": "string",
|
| 107 |
+
"order": "number or null",
|
| 108 |
+
"text": "string",
|
| 109 |
+
"reagents": ["string"],
|
| 110 |
+
"equipment": ["string"],
|
| 111 |
+
"objects": ["string"],
|
| 112 |
+
}
|
| 113 |
+
],
|
| 114 |
+
}
|
| 115 |
+
)
|
| 116 |
+
if output_style == "flat_numbered":
|
| 117 |
+
lists = "\n\nReagent List:\n1. <observed reagent or material>\n\nTools Used:\n1. <observed tool or equipment>" if include_flat_lists else ""
|
| 118 |
+
return "\n".join(
|
| 119 |
+
[
|
| 120 |
+
"Please respond with the following format:",
|
| 121 |
+
"",
|
| 122 |
+
"## Response Format",
|
| 123 |
+
"1. <observed action step with no substeps>",
|
| 124 |
+
"2. <observed action step with no substeps>",
|
| 125 |
+
lists,
|
| 126 |
+
"",
|
| 127 |
+
"Use simple flat numbered protocol steps. Do not include step IDs, substeps, bullets, or JSON.",
|
| 128 |
+
"",
|
| 129 |
+
"## Question",
|
| 130 |
+
]
|
| 131 |
+
)
|
| 132 |
+
return "\n".join(
|
| 133 |
+
[
|
| 134 |
+
"Please respond with the following format:",
|
| 135 |
+
"",
|
| 136 |
+
"## Response Format",
|
| 137 |
+
"1. <section or procedure title>",
|
| 138 |
+
" 1.1. <observed action>",
|
| 139 |
+
" 1.2. <observed action>",
|
| 140 |
+
"",
|
| 141 |
+
"Use numbered sections and substeps. Do not include JSON.",
|
| 142 |
+
"",
|
| 143 |
+
"## Question",
|
| 144 |
+
]
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def _timed_steps(protocol: dict[str, Any] | str) -> list[dict[str, Any]]:
|
| 149 |
+
rows = [
|
| 150 |
+
step
|
| 151 |
+
for step in executable_steps(protocol)
|
| 152 |
+
if step.get("t_start") is not None and step.get("t_end") is not None
|
| 153 |
+
]
|
| 154 |
+
return sorted(rows, key=lambda row: (float(row["t_start"]), float(row["t_end"])))
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def step_timeline_text(protocol: dict[str, Any] | str) -> str:
|
| 158 |
+
"""Render demonstrated protocol steps as timestamped timeline lines."""
|
| 159 |
+
lines = []
|
| 160 |
+
for step in _timed_steps(protocol):
|
| 161 |
+
start = float(step["t_start"])
|
| 162 |
+
end = float(step["t_end"])
|
| 163 |
+
step_id = str(step.get("step_id") or "?")
|
| 164 |
+
text = str(step.get("text") or "")
|
| 165 |
+
lines.append(f"[{start:.1f}-{end:.1f}s] step {step_id}: {text}")
|
| 166 |
+
return "\n".join(lines)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def monitoring_state(protocol: dict[str, Any] | str, t: float) -> dict[str, Any]:
|
| 170 |
+
"""Return completed/current/remaining timed protocol steps at timestamp ``t``."""
|
| 171 |
+
completed: list[dict[str, Any]] = []
|
| 172 |
+
current: list[dict[str, Any]] = []
|
| 173 |
+
remaining: list[dict[str, Any]] = []
|
| 174 |
+
for step in _timed_steps(protocol):
|
| 175 |
+
start = float(step["t_start"])
|
| 176 |
+
end = float(step["t_end"])
|
| 177 |
+
item = {
|
| 178 |
+
"step_id": str(step.get("step_id") or "?"),
|
| 179 |
+
"text": str(step.get("text") or ""),
|
| 180 |
+
"t_start": start,
|
| 181 |
+
"t_end": end,
|
| 182 |
+
}
|
| 183 |
+
if end <= t:
|
| 184 |
+
completed.append(item)
|
| 185 |
+
elif start <= t <= end:
|
| 186 |
+
current.append(item)
|
| 187 |
+
else:
|
| 188 |
+
remaining.append(item)
|
| 189 |
+
return {"t": float(t), "completed": completed, "current": current, "remaining": remaining}
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def error_summary(row: dict[str, Any]) -> str:
|
| 193 |
+
"""Summarize the flat benchmark error fields from a parquet row."""
|
| 194 |
+
if not row.get("has_error"):
|
| 195 |
+
return "No annotated procedural error."
|
| 196 |
+
error = str(row.get("error") or "").strip()
|
| 197 |
+
return f"Error: {error}" if error else "Annotated procedural error present."
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def row_video_context(row: dict[str, Any], include_timeline: bool = True) -> str:
|
| 201 |
+
operation = str(row.get("operation") or row.get("protocol_title") or "the demonstrated wet-lab procedure").strip()
|
| 202 |
+
lines = [f"Reconstruct the demonstrated protocol for {operation}."]
|
| 203 |
+
if row.get("error"):
|
| 204 |
+
lines.append("If an error is visible, include only the observed action sequence; do not add diagnostic commentary.")
|
| 205 |
+
if include_timeline and row.get("protocol_json"):
|
| 206 |
+
timeline = step_timeline_text(row["protocol_json"])
|
| 207 |
+
if timeline:
|
| 208 |
+
lines.extend(["", "Visible timeline:", timeline])
|
| 209 |
+
return "\n".join(line for line in lines if str(line).strip())
|
| 210 |
+
|
| 211 |
+
|
lsvbench/report.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Markdown report generation for standardized benchmark outputs."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import csv
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
from .io import OutputLayout, load_prediction_rows, read_json, write_json
|
| 10 |
+
from .plots import TASK_LABELS, TASK_METRICS, write_standard_plots
|
| 11 |
+
from .tasks import TASK_REGISTRY
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _model_key(output_dir: Path) -> str:
|
| 15 |
+
config_path = output_dir / "run_config.json"
|
| 16 |
+
if config_path.exists():
|
| 17 |
+
config = read_json(config_path)
|
| 18 |
+
return str(config.get("model") or config.get("model_path") or output_dir.name)
|
| 19 |
+
return output_dir.name
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _model_label(output_dir: Path) -> str:
|
| 23 |
+
key = _model_key(output_dir)
|
| 24 |
+
return output_dir.name if output_dir.name not in {"output", "outputs"} else key
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def score_output_dir(output_dir: Path) -> dict[str, Any]:
|
| 28 |
+
layout = OutputLayout(output_dir)
|
| 29 |
+
tasks: dict[str, Any] = {}
|
| 30 |
+
for task_name, task in TASK_REGISTRY.items():
|
| 31 |
+
task_dir = layout.task_dir(task_name)
|
| 32 |
+
rows = load_prediction_rows(task_dir, sort_key=task.sort_key)
|
| 33 |
+
if not rows:
|
| 34 |
+
continue
|
| 35 |
+
parsed_rows = task.parse_rows(rows)
|
| 36 |
+
# Materialize normalized predictions for easier auditing.
|
| 37 |
+
from .io import write_jsonl
|
| 38 |
+
|
| 39 |
+
write_jsonl(task_dir / "predictions_scored.jsonl", parsed_rows)
|
| 40 |
+
tasks[task_name] = task.score(parsed_rows)
|
| 41 |
+
return {
|
| 42 |
+
"model_key": _model_key(output_dir),
|
| 43 |
+
"model_label": _model_label(output_dir),
|
| 44 |
+
"output_dir": str(output_dir),
|
| 45 |
+
"tasks": tasks,
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def flatten_metrics(model_results: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
| 50 |
+
rows: list[dict[str, Any]] = []
|
| 51 |
+
for model in model_results:
|
| 52 |
+
for task_name, metric_map in TASK_METRICS.items():
|
| 53 |
+
source_task = metric_map["source_task"]
|
| 54 |
+
summary = model["tasks"].get(source_task)
|
| 55 |
+
if not summary:
|
| 56 |
+
continue
|
| 57 |
+
rows.append(
|
| 58 |
+
{
|
| 59 |
+
"model": model["model_key"],
|
| 60 |
+
"model_label": model["model_label"],
|
| 61 |
+
"task": task_name,
|
| 62 |
+
"task_label": metric_map["label"],
|
| 63 |
+
"rows": summary.get("rows"),
|
| 64 |
+
"scored": summary.get("scored"),
|
| 65 |
+
"errors": summary.get("errors"),
|
| 66 |
+
"parse_errors": summary.get("parse_errors"),
|
| 67 |
+
"parse_success_rate": summary.get("parse_success_rate"),
|
| 68 |
+
"accuracy": summary.get(metric_map.get("accuracy", "")),
|
| 69 |
+
"balanced_accuracy": summary.get(metric_map.get("balanced_accuracy", "")),
|
| 70 |
+
"f1": summary.get(metric_map.get("f1", "")),
|
| 71 |
+
"precision": summary.get(metric_map.get("precision", "")),
|
| 72 |
+
"recall": summary.get(metric_map.get("recall", "")),
|
| 73 |
+
}
|
| 74 |
+
)
|
| 75 |
+
return rows
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def write_metrics_csv(path: Path, rows: list[dict[str, Any]]) -> None:
|
| 79 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 80 |
+
if not rows:
|
| 81 |
+
path.write_text("", encoding="utf-8")
|
| 82 |
+
return
|
| 83 |
+
with path.open("w", encoding="utf-8", newline="") as fh:
|
| 84 |
+
writer = csv.DictWriter(fh, fieldnames=list(rows[0]))
|
| 85 |
+
writer.writeheader()
|
| 86 |
+
writer.writerows(rows)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _pct(value: Any) -> str:
|
| 90 |
+
return f"{float(value) * 100:.1f}%" if isinstance(value, (int, float)) else "n/a"
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def write_report_md(report_dir: Path, model_results: list[dict[str, Any]], metric_rows: list[dict[str, Any]], plot_paths: list[Path]) -> None:
|
| 94 |
+
lines = [
|
| 95 |
+
"# Benchmark Report",
|
| 96 |
+
"",
|
| 97 |
+
"This report is generated from raw model outputs. Responses are parsed and scored at report time.",
|
| 98 |
+
"",
|
| 99 |
+
"## Summary Metrics",
|
| 100 |
+
"",
|
| 101 |
+
"| Model | Task | Balanced Accuracy | F1 | Precision | Recall | Parse Success |",
|
| 102 |
+
"|---|---|---:|---:|---:|---:|---:|",
|
| 103 |
+
]
|
| 104 |
+
for row in metric_rows:
|
| 105 |
+
lines.append(
|
| 106 |
+
"| {model_label} | {task_label} | {balanced_accuracy} | {f1} | {precision} | {recall} | {parse_success_rate} |".format(
|
| 107 |
+
model_label=row["model_label"],
|
| 108 |
+
task_label=row["task_label"],
|
| 109 |
+
balanced_accuracy=_pct(row["balanced_accuracy"]),
|
| 110 |
+
f1=_pct(row["f1"]),
|
| 111 |
+
precision=_pct(row["precision"]),
|
| 112 |
+
recall=_pct(row["recall"]),
|
| 113 |
+
parse_success_rate=_pct(row["parse_success_rate"]),
|
| 114 |
+
)
|
| 115 |
+
)
|
| 116 |
+
lines.extend(["", "## Plots", ""])
|
| 117 |
+
for path in plot_paths:
|
| 118 |
+
rel = path.relative_to(report_dir)
|
| 119 |
+
title = path.stem.replace("_", " ").title()
|
| 120 |
+
lines.extend([f"### {title}", "", f"})", ""])
|
| 121 |
+
lines.extend(["## Task Details", ""])
|
| 122 |
+
for model in model_results:
|
| 123 |
+
lines.extend([f"### {model['model_label']}", ""])
|
| 124 |
+
for task_name, summary in model["tasks"].items():
|
| 125 |
+
lines.extend(
|
| 126 |
+
[
|
| 127 |
+
f"#### {TASK_LABELS.get(task_name, task_name)}",
|
| 128 |
+
"",
|
| 129 |
+
f"- Rows: `{summary.get('rows')}`",
|
| 130 |
+
f"- Scored: `{summary.get('scored')}`",
|
| 131 |
+
f"- Errors: `{summary.get('errors')}`",
|
| 132 |
+
f"- Parse errors: `{summary.get('parse_errors')}`",
|
| 133 |
+
f"- Parse success: `{_pct(summary.get('parse_success_rate'))}`",
|
| 134 |
+
"",
|
| 135 |
+
]
|
| 136 |
+
)
|
| 137 |
+
(report_dir / "report.md").write_text("\n".join(lines), encoding="utf-8")
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def generate_report(output_dirs: list[Path], report_dir: Path | None = None) -> dict[str, Any]:
|
| 141 |
+
if not output_dirs:
|
| 142 |
+
raise ValueError("Provide at least one output directory.")
|
| 143 |
+
report_dir = report_dir or output_dirs[0]
|
| 144 |
+
report_dir.mkdir(parents=True, exist_ok=True)
|
| 145 |
+
model_results = [score_output_dir(path) for path in output_dirs]
|
| 146 |
+
metric_rows = flatten_metrics(model_results)
|
| 147 |
+
write_json(report_dir / "metrics.json", {"models": model_results, "rows": metric_rows})
|
| 148 |
+
write_metrics_csv(report_dir / "metrics.csv", metric_rows)
|
| 149 |
+
plot_paths = write_standard_plots(model_results, report_dir)
|
| 150 |
+
write_report_md(report_dir, model_results, metric_rows, plot_paths)
|
| 151 |
+
return {"report_dir": str(report_dir), "models": [row["model_key"] for row in model_results], "plots": [str(path) for path in plot_paths]}
|
lsvbench/tasks/__init__.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Built-in benchmark task registry."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from .base import BenchmarkTask
|
| 6 |
+
from .monitor_next_step import MonitorNextStepTask
|
| 7 |
+
from .monitoring_step import MonitoringStepTask
|
| 8 |
+
from .pmd import PmdTask
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
TASK_REGISTRY: dict[str, BenchmarkTask] = {
|
| 12 |
+
"monitoring_step": MonitoringStepTask(),
|
| 13 |
+
"monitor_next_step": MonitorNextStepTask(),
|
| 14 |
+
"pmd": PmdTask(),
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def get_task(name: str) -> BenchmarkTask:
|
| 19 |
+
try:
|
| 20 |
+
return TASK_REGISTRY[name]
|
| 21 |
+
except KeyError as exc:
|
| 22 |
+
known = ", ".join(sorted(TASK_REGISTRY))
|
| 23 |
+
raise KeyError(f"Unknown task {name!r}. Known tasks: {known}") from exc
|
lsvbench/tasks/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (1.08 kB). View file
|
|
|
lsvbench/tasks/__pycache__/base.cpython-313.pyc
ADDED
|
Binary file (3.05 kB). View file
|
|
|
lsvbench/tasks/__pycache__/monitor_next_step.cpython-313.pyc
ADDED
|
Binary file (9.03 kB). View file
|
|
|
lsvbench/tasks/__pycache__/monitoring_step.cpython-313.pyc
ADDED
|
Binary file (7.86 kB). View file
|
|
|
lsvbench/tasks/__pycache__/pmd.cpython-313.pyc
ADDED
|
Binary file (8.99 kB). View file
|
|
|
lsvbench/tasks/base.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Task interface for modular benchmark parsing and scoring."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
from ..io import BENCHMARK_ROOT
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@dataclass(frozen=True)
|
| 13 |
+
class TaskSpec:
|
| 14 |
+
name: str
|
| 15 |
+
display_name: str
|
| 16 |
+
default_manifest: Path | None
|
| 17 |
+
sort_key: str = "eval_id"
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class BenchmarkTask:
|
| 21 |
+
spec: TaskSpec
|
| 22 |
+
primary_metric: str
|
| 23 |
+
|
| 24 |
+
@property
|
| 25 |
+
def name(self) -> str:
|
| 26 |
+
return self.spec.name
|
| 27 |
+
|
| 28 |
+
@property
|
| 29 |
+
def display_name(self) -> str:
|
| 30 |
+
return self.spec.display_name
|
| 31 |
+
|
| 32 |
+
@property
|
| 33 |
+
def default_manifest(self) -> Path | None:
|
| 34 |
+
return self.spec.default_manifest
|
| 35 |
+
|
| 36 |
+
@property
|
| 37 |
+
def sort_key(self) -> str:
|
| 38 |
+
return self.spec.sort_key
|
| 39 |
+
|
| 40 |
+
def load_examples(
|
| 41 |
+
self,
|
| 42 |
+
*,
|
| 43 |
+
benchmark_root: Path = BENCHMARK_ROOT,
|
| 44 |
+
manifest_path: Path | None = None,
|
| 45 |
+
video_root: Path | None = None,
|
| 46 |
+
) -> list[dict[str, Any]]:
|
| 47 |
+
raise NotImplementedError
|
| 48 |
+
|
| 49 |
+
def parse_record(self, row: dict[str, Any]) -> dict[str, Any]:
|
| 50 |
+
raise NotImplementedError
|
| 51 |
+
|
| 52 |
+
def parse_rows(self, rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
| 53 |
+
return [self.parse_record(dict(row)) for row in rows]
|
| 54 |
+
|
| 55 |
+
def score(self, rows: list[dict[str, Any]]) -> dict[str, Any]:
|
| 56 |
+
raise NotImplementedError
|
lsvbench/tasks/monitor_next_step.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Finetune-style monitor-next delta task."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from collections import Counter
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
from ..io import BENCHMARK_ROOT, DATA_DIR, manifest_examples, select_shard
|
| 10 |
+
from ..metrics import bootstrap_sem, classification_scores
|
| 11 |
+
from ..parsing import normalize_step_id, parse_next_step_delta_response
|
| 12 |
+
from .base import BenchmarkTask, TaskSpec
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class MonitorNextStepTask(BenchmarkTask):
|
| 16 |
+
spec = TaskSpec(
|
| 17 |
+
name="monitor_next_step",
|
| 18 |
+
display_name="Protocol Monitoring Advance Prediction",
|
| 19 |
+
default_manifest=DATA_DIR / "monitor_next_step.json",
|
| 20 |
+
)
|
| 21 |
+
primary_metric = "advance_step_balanced_accuracy"
|
| 22 |
+
|
| 23 |
+
def load_examples(
|
| 24 |
+
self,
|
| 25 |
+
*,
|
| 26 |
+
benchmark_root: Path = BENCHMARK_ROOT,
|
| 27 |
+
manifest_path: Path | None = None,
|
| 28 |
+
video_root: Path | None = None,
|
| 29 |
+
num_shards: int = 1,
|
| 30 |
+
shard_index: int = 0,
|
| 31 |
+
limit: int | None = None,
|
| 32 |
+
) -> list[dict[str, Any]]:
|
| 33 |
+
rows = manifest_examples(manifest_path or self.default_manifest)
|
| 34 |
+
root = video_root or benchmark_root
|
| 35 |
+
for row in rows:
|
| 36 |
+
row["task"] = self.name
|
| 37 |
+
row["_video_abs"] = str(root / str(row["video_path"]))
|
| 38 |
+
rows = sorted(rows, key=lambda row: str(row.get("eval_id")))
|
| 39 |
+
if limit is not None:
|
| 40 |
+
rows = rows[:limit]
|
| 41 |
+
return select_shard(rows, num_shards, shard_index)
|
| 42 |
+
|
| 43 |
+
def parse_record(self, row: dict[str, Any]) -> dict[str, Any]:
|
| 44 |
+
if row.get("error"):
|
| 45 |
+
return row
|
| 46 |
+
parsed = parse_next_step_delta_response(str(row.get("raw_response") or ""))
|
| 47 |
+
pred_current_norm = normalize_step_id(parsed.get("pred_current_step_id"))
|
| 48 |
+
target_current_norm = normalize_step_id(row.get("target_current_step_id"))
|
| 49 |
+
target_start_norm = normalize_step_id(row.get("target_start_step_id"))
|
| 50 |
+
pred_advances = None
|
| 51 |
+
if pred_current_norm is not None and target_start_norm is not None:
|
| 52 |
+
pred_advances = pred_current_norm != target_start_norm
|
| 53 |
+
row.update(
|
| 54 |
+
{
|
| 55 |
+
**parsed,
|
| 56 |
+
"pred_current_step_id_normalized": pred_current_norm,
|
| 57 |
+
"target_current_step_id_normalized": target_current_norm,
|
| 58 |
+
"pred_advances_step": pred_advances,
|
| 59 |
+
"current_step_correct": pred_current_norm is not None and pred_current_norm == target_current_norm,
|
| 60 |
+
}
|
| 61 |
+
)
|
| 62 |
+
return row
|
| 63 |
+
|
| 64 |
+
def _summary(self, rows: list[dict[str, Any]]) -> dict[str, Any]:
|
| 65 |
+
parsed = self.parse_rows(rows)
|
| 66 |
+
scored = [row for row in parsed if not row.get("error")]
|
| 67 |
+
current_correct = 0
|
| 68 |
+
current_parsed = 0
|
| 69 |
+
advance_pairs: list[tuple[str, str | None]] = []
|
| 70 |
+
skipped_pairs: list[tuple[str, str | None]] = []
|
| 71 |
+
skipped_step_ref_correct = 0
|
| 72 |
+
skipped_step_ref_total = 0
|
| 73 |
+
for row in scored:
|
| 74 |
+
pred_current = normalize_step_id(row.get("pred_current_step_id"))
|
| 75 |
+
target_current = normalize_step_id(row.get("target_current_step_id"))
|
| 76 |
+
target_start = normalize_step_id(row.get("target_start_step_id"))
|
| 77 |
+
if pred_current is not None:
|
| 78 |
+
current_parsed += 1
|
| 79 |
+
current_correct += int(pred_current is not None and pred_current == target_current)
|
| 80 |
+
pred_advances = None
|
| 81 |
+
if pred_current is not None and target_start is not None:
|
| 82 |
+
pred_advances = pred_current != target_start
|
| 83 |
+
advance_pairs.append((str(bool(row.get("target_advances_step"))), None if pred_advances is None else str(bool(pred_advances))))
|
| 84 |
+
skipped_pred = row.get("pred_has_step_skipped")
|
| 85 |
+
skipped_pairs.append((str(bool(row.get("target_has_error"))), None if skipped_pred is None else str(bool(skipped_pred))))
|
| 86 |
+
if row.get("target_has_error"):
|
| 87 |
+
skipped_step_ref_total += 1
|
| 88 |
+
pred_ref = normalize_step_id(row.get("pred_error_step_id"))
|
| 89 |
+
target_ref = normalize_step_id(row.get("target_error_step_id"))
|
| 90 |
+
skipped_step_ref_correct += int(pred_ref is not None and pred_ref == target_ref)
|
| 91 |
+
advance = classification_scores(advance_pairs, labels=["False", "True"])
|
| 92 |
+
skipped = classification_scores(skipped_pairs, labels=["False", "True"])
|
| 93 |
+
n = len(scored)
|
| 94 |
+
parse_errors = sum(1 for row in scored if not row.get("pred_parse_ok"))
|
| 95 |
+
return {
|
| 96 |
+
"task": self.name,
|
| 97 |
+
"display_name": self.display_name,
|
| 98 |
+
"rows": len(rows),
|
| 99 |
+
"scored": n,
|
| 100 |
+
"errors": sum(1 for row in rows if row.get("error")),
|
| 101 |
+
"parse_errors": parse_errors,
|
| 102 |
+
"parse_success_rate": (n - parse_errors) / n if n else None,
|
| 103 |
+
"current_step_accuracy": current_correct / n if n else None,
|
| 104 |
+
"current_step_accuracy_parsed_only": current_correct / current_parsed if current_parsed else None,
|
| 105 |
+
"advance_step_accuracy": advance["accuracy"],
|
| 106 |
+
"advance_step_balanced_accuracy": advance["balanced_accuracy"],
|
| 107 |
+
"advance_step_macro_f1": advance["macro_f1"],
|
| 108 |
+
"advance_step_macro_precision": advance["macro_precision"],
|
| 109 |
+
"advance_step_macro_recall": advance["macro_recall"],
|
| 110 |
+
"advance_step_precision": advance["precision"],
|
| 111 |
+
"advance_step_recall": advance["recall"],
|
| 112 |
+
"advance_step_f1": advance["f1"],
|
| 113 |
+
"advance_step_confusion": advance["confusion"],
|
| 114 |
+
"skipped_step_accuracy": skipped["accuracy"],
|
| 115 |
+
"skipped_step_balanced_accuracy": skipped["balanced_accuracy"],
|
| 116 |
+
"skipped_step_macro_f1": skipped["macro_f1"],
|
| 117 |
+
"skipped_step_macro_precision": skipped["macro_precision"],
|
| 118 |
+
"skipped_step_macro_recall": skipped["macro_recall"],
|
| 119 |
+
"skipped_step_confusion": skipped["confusion"],
|
| 120 |
+
"skipped_step_ref_accuracy": skipped_step_ref_correct / skipped_step_ref_total if skipped_step_ref_total else None,
|
| 121 |
+
"task_counts": dict(Counter(str(row.get("task_type")) for row in scored)),
|
| 122 |
+
"history_variant_counts": dict(Counter(str(row.get("history_variant")) for row in scored)),
|
| 123 |
+
"window_kind_counts": dict(Counter(str(row.get("window_kind")) for row in scored)),
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
def score(self, rows: list[dict[str, Any]]) -> dict[str, Any]:
|
| 127 |
+
parsed = self.parse_rows(rows)
|
| 128 |
+
summary = self._summary(parsed)
|
| 129 |
+
for metric in (
|
| 130 |
+
"advance_step_accuracy",
|
| 131 |
+
"advance_step_balanced_accuracy",
|
| 132 |
+
"advance_step_macro_f1",
|
| 133 |
+
"advance_step_macro_precision",
|
| 134 |
+
"advance_step_macro_recall",
|
| 135 |
+
"skipped_step_accuracy",
|
| 136 |
+
"skipped_step_balanced_accuracy",
|
| 137 |
+
"skipped_step_macro_f1",
|
| 138 |
+
):
|
| 139 |
+
summary[f"{metric}_sem"] = bootstrap_sem(parsed, metric, self._summary, iterations=200)
|
| 140 |
+
return summary
|
lsvbench/tasks/monitoring_step.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Monitoring step-identification task."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from collections import Counter
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
from ..io import BENCHMARK_ROOT, DATA_DIR, manifest_examples, select_shard
|
| 10 |
+
from ..metrics import bootstrap_sem, classification_scores
|
| 11 |
+
from ..parsing import normalize_step_id, parse_monitoring_response
|
| 12 |
+
from .base import BenchmarkTask, TaskSpec
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class MonitoringStepTask(BenchmarkTask):
|
| 16 |
+
spec = TaskSpec(
|
| 17 |
+
name="monitoring_step",
|
| 18 |
+
display_name="Protocol Monitoring Step Prediction",
|
| 19 |
+
default_manifest=DATA_DIR / "monitoring_step_eval.json",
|
| 20 |
+
)
|
| 21 |
+
primary_metric = "step_balanced_accuracy"
|
| 22 |
+
|
| 23 |
+
def load_examples(
|
| 24 |
+
self,
|
| 25 |
+
*,
|
| 26 |
+
benchmark_root: Path = BENCHMARK_ROOT,
|
| 27 |
+
manifest_path: Path | None = None,
|
| 28 |
+
video_root: Path | None = None,
|
| 29 |
+
num_shards: int = 1,
|
| 30 |
+
shard_index: int = 0,
|
| 31 |
+
limit: int | None = None,
|
| 32 |
+
) -> list[dict[str, Any]]:
|
| 33 |
+
rows = manifest_examples(manifest_path or self.default_manifest)
|
| 34 |
+
root = video_root or benchmark_root
|
| 35 |
+
for row in rows:
|
| 36 |
+
row["task"] = self.name
|
| 37 |
+
row["_video_abs"] = str(root / str(row["video_path"]))
|
| 38 |
+
rows = sorted(rows, key=lambda row: str(row.get("eval_id")))
|
| 39 |
+
if limit is not None:
|
| 40 |
+
rows = rows[:limit]
|
| 41 |
+
return select_shard(rows, num_shards, shard_index)
|
| 42 |
+
|
| 43 |
+
def parse_record(self, row: dict[str, Any]) -> dict[str, Any]:
|
| 44 |
+
if row.get("error"):
|
| 45 |
+
return row
|
| 46 |
+
raw = str(row.get("raw_response") or "")
|
| 47 |
+
pred_candidate, pred_step = parse_monitoring_response(raw) if raw else (None, None)
|
| 48 |
+
pred_step_normalized = normalize_step_id(pred_step)
|
| 49 |
+
target_step_normalized = normalize_step_id(row.get("target_step_id"))
|
| 50 |
+
row.update(
|
| 51 |
+
{
|
| 52 |
+
"pred_candidate_matches": pred_candidate,
|
| 53 |
+
"pred_observed_step_id": pred_step,
|
| 54 |
+
"pred_observed_step_id_normalized": pred_step_normalized,
|
| 55 |
+
"target_step_id_normalized": target_step_normalized,
|
| 56 |
+
"pred_parse_ok": pred_step_normalized is not None,
|
| 57 |
+
"candidate_correct": (
|
| 58 |
+
pred_candidate is not None
|
| 59 |
+
and bool(pred_candidate) == bool(row.get("target_candidate_matches"))
|
| 60 |
+
)
|
| 61 |
+
if row.get("target_candidate_matches") is not None
|
| 62 |
+
else None,
|
| 63 |
+
"observed_step_correct": pred_step_normalized is not None
|
| 64 |
+
and pred_step_normalized == target_step_normalized,
|
| 65 |
+
}
|
| 66 |
+
)
|
| 67 |
+
return row
|
| 68 |
+
|
| 69 |
+
def _summary(self, rows: list[dict[str, Any]]) -> dict[str, Any]:
|
| 70 |
+
parsed = self.parse_rows(rows)
|
| 71 |
+
scored = [row for row in parsed if not row.get("error")]
|
| 72 |
+
step_rows = [row for row in scored if str(row.get("task_type") or "step_identification") == "step_identification"]
|
| 73 |
+
pairs = [
|
| 74 |
+
(normalize_step_id(row.get("target_step_id")), normalize_step_id(row.get("pred_observed_step_id")))
|
| 75 |
+
for row in step_rows
|
| 76 |
+
if normalize_step_id(row.get("target_step_id")) is not None
|
| 77 |
+
]
|
| 78 |
+
labels = sorted({str(target) for target, _ in pairs})
|
| 79 |
+
scores = classification_scores(pairs, labels=labels)
|
| 80 |
+
candidate_rows = [row for row in scored if row.get("target_candidate_matches") is not None]
|
| 81 |
+
candidate_correct = sum(1 for row in candidate_rows if row.get("candidate_correct"))
|
| 82 |
+
parse_errors = sum(1 for row in scored if not row.get("pred_parse_ok"))
|
| 83 |
+
return {
|
| 84 |
+
"task": self.name,
|
| 85 |
+
"display_name": self.display_name,
|
| 86 |
+
"rows": len(rows),
|
| 87 |
+
"scored": len(scored),
|
| 88 |
+
"errors": sum(1 for row in rows if row.get("error")),
|
| 89 |
+
"parse_errors": parse_errors,
|
| 90 |
+
"parse_success_rate": (len(scored) - parse_errors) / len(scored) if scored else None,
|
| 91 |
+
"candidate_match_rows": len(candidate_rows),
|
| 92 |
+
"candidate_match_accuracy": candidate_correct / len(candidate_rows) if candidate_rows else None,
|
| 93 |
+
"step_identification_rows": len(step_rows),
|
| 94 |
+
"step_identification_accuracy": scores["accuracy"],
|
| 95 |
+
"observed_step_id_accuracy": scores["accuracy"],
|
| 96 |
+
"step_parse_success_rate": (len(step_rows) - parse_errors) / len(step_rows) if step_rows else None,
|
| 97 |
+
"step_balanced_accuracy": scores["balanced_accuracy"],
|
| 98 |
+
"step_macro_f1": scores["macro_f1"],
|
| 99 |
+
"step_macro_precision": scores["macro_precision"],
|
| 100 |
+
"step_macro_recall": scores["macro_recall"],
|
| 101 |
+
"step_precision_by_id": scores["precision"],
|
| 102 |
+
"step_recall_by_id": scores["recall"],
|
| 103 |
+
"step_f1_by_id": scores["f1"],
|
| 104 |
+
"step_confusion": scores["confusion"],
|
| 105 |
+
"task_counts": dict(Counter(str(row.get("task_type")) for row in scored)),
|
| 106 |
+
"target_counts": scores["target_counts"],
|
| 107 |
+
"pred_counts": scores["pred_counts"],
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
def score(self, rows: list[dict[str, Any]]) -> dict[str, Any]:
|
| 111 |
+
parsed = self.parse_rows(rows)
|
| 112 |
+
summary = self._summary(parsed)
|
| 113 |
+
for metric in (
|
| 114 |
+
"step_identification_accuracy",
|
| 115 |
+
"step_balanced_accuracy",
|
| 116 |
+
"step_macro_f1",
|
| 117 |
+
"step_macro_precision",
|
| 118 |
+
"step_macro_recall",
|
| 119 |
+
):
|
| 120 |
+
summary[f"{metric}_sem"] = bootstrap_sem(parsed, metric, self._summary, iterations=200)
|
| 121 |
+
return summary
|
lsvbench/tasks/pmd.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pipette mistake / error detection task."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from collections import Counter
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
from ..io import BENCHMARK_ROOT, read_parquet, select_shard
|
| 10 |
+
from ..metrics import bootstrap_sem, classification_scores
|
| 11 |
+
from ..parsing import parse_choice_option
|
| 12 |
+
from .base import BenchmarkTask, TaskSpec
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
PMD_OPTIONS = {
|
| 16 |
+
"CORRECT",
|
| 17 |
+
"ERROR_REUSE",
|
| 18 |
+
"ERROR_SURFACE",
|
| 19 |
+
"ERROR_RELEASE",
|
| 20 |
+
"ERROR_INSTALL",
|
| 21 |
+
"ERROR_OTHER",
|
| 22 |
+
}
|
| 23 |
+
PMD_MISTAKE_TO_OPTION = {
|
| 24 |
+
"none": "CORRECT",
|
| 25 |
+
"reuse_tip": "ERROR_REUSE",
|
| 26 |
+
"reuse_same_media": "ERROR_REUSE",
|
| 27 |
+
"reuse_same_tip": "ERROR_REUSE",
|
| 28 |
+
"surface_contamination": "ERROR_SURFACE",
|
| 29 |
+
"early_release": "ERROR_RELEASE",
|
| 30 |
+
"wrong_tip_for_pipette": "ERROR_INSTALL",
|
| 31 |
+
}
|
| 32 |
+
PMD_NUMBER_TO_OPTION = {
|
| 33 |
+
"1": "CORRECT",
|
| 34 |
+
"2": "ERROR_REUSE",
|
| 35 |
+
"3": "ERROR_SURFACE",
|
| 36 |
+
"4": "ERROR_RELEASE",
|
| 37 |
+
"5": "ERROR_INSTALL",
|
| 38 |
+
"6": "ERROR_OTHER",
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def pmd_target_option(label: str, mistake_type: str) -> str:
|
| 43 |
+
return "CORRECT" if label == "correct" else PMD_MISTAKE_TO_OPTION.get(mistake_type, "ERROR_OTHER")
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class PmdTask(BenchmarkTask):
|
| 47 |
+
spec = TaskSpec(
|
| 48 |
+
name="pmd",
|
| 49 |
+
display_name="Error Detection",
|
| 50 |
+
default_manifest=BENCHMARK_ROOT / "pmd" / "pmd.parquet",
|
| 51 |
+
sort_key="video_id",
|
| 52 |
+
)
|
| 53 |
+
primary_metric = "binary_balanced_accuracy"
|
| 54 |
+
|
| 55 |
+
def load_examples(
|
| 56 |
+
self,
|
| 57 |
+
*,
|
| 58 |
+
benchmark_root: Path = BENCHMARK_ROOT,
|
| 59 |
+
manifest_path: Path | None = None,
|
| 60 |
+
video_root: Path | None = None,
|
| 61 |
+
num_shards: int = 1,
|
| 62 |
+
shard_index: int = 0,
|
| 63 |
+
limit: int | None = None,
|
| 64 |
+
) -> list[dict[str, Any]]:
|
| 65 |
+
rows = read_parquet(manifest_path or self.default_manifest)
|
| 66 |
+
selected: list[dict[str, Any]] = []
|
| 67 |
+
root = video_root or benchmark_root
|
| 68 |
+
for row in rows:
|
| 69 |
+
rel_video = str(row.get("video_path") or "")
|
| 70 |
+
if not rel_video:
|
| 71 |
+
continue
|
| 72 |
+
video_path = root / rel_video
|
| 73 |
+
target = pmd_target_option(str(row.get("label")), str(row.get("mistake_type")))
|
| 74 |
+
selected.append(
|
| 75 |
+
{
|
| 76 |
+
**row,
|
| 77 |
+
"task": self.name,
|
| 78 |
+
"_video_abs": str(video_path),
|
| 79 |
+
"target_option": target,
|
| 80 |
+
"target_binary": "CORRECT" if target == "CORRECT" else "ERROR",
|
| 81 |
+
}
|
| 82 |
+
)
|
| 83 |
+
selected = sorted(selected, key=lambda row: str(row.get("video_id") or ""))
|
| 84 |
+
if limit is not None:
|
| 85 |
+
selected = selected[:limit]
|
| 86 |
+
return select_shard(selected, num_shards, shard_index)
|
| 87 |
+
|
| 88 |
+
def parse_record(self, row: dict[str, Any]) -> dict[str, Any]:
|
| 89 |
+
if row.get("error"):
|
| 90 |
+
return row
|
| 91 |
+
pred = parse_choice_option(str(row.get("raw_response") or ""), PMD_OPTIONS, number_map=PMD_NUMBER_TO_OPTION)
|
| 92 |
+
pred_binary = None if pred is None else ("CORRECT" if pred == "CORRECT" else "ERROR")
|
| 93 |
+
target = str(row.get("target_option") or pmd_target_option(str(row.get("label")), str(row.get("mistake_type"))))
|
| 94 |
+
target_binary = "CORRECT" if target == "CORRECT" else "ERROR"
|
| 95 |
+
row.update(
|
| 96 |
+
{
|
| 97 |
+
"target_option": target,
|
| 98 |
+
"target_binary": target_binary,
|
| 99 |
+
"pred_option": pred,
|
| 100 |
+
"pred_binary": pred_binary,
|
| 101 |
+
"pred_parse_ok": pred is not None,
|
| 102 |
+
"binary_correct": pred_binary == target_binary if pred_binary is not None else False,
|
| 103 |
+
"option_correct": pred == target if pred is not None else False,
|
| 104 |
+
}
|
| 105 |
+
)
|
| 106 |
+
return row
|
| 107 |
+
|
| 108 |
+
def _summary(self, rows: list[dict[str, Any]]) -> dict[str, Any]:
|
| 109 |
+
parsed = self.parse_rows(rows)
|
| 110 |
+
scored = [row for row in parsed if not row.get("error")]
|
| 111 |
+
binary_pairs: list[tuple[str, str | None]] = []
|
| 112 |
+
option_pairs: list[tuple[str, str | None]] = []
|
| 113 |
+
error_type_pairs: list[tuple[str, str | None]] = []
|
| 114 |
+
for row in scored:
|
| 115 |
+
target = str(row.get("target_option"))
|
| 116 |
+
pred = row.get("pred_option")
|
| 117 |
+
target_binary = "CORRECT" if target == "CORRECT" else "ERROR"
|
| 118 |
+
pred_binary = None if pred is None else ("CORRECT" if pred == "CORRECT" else "ERROR")
|
| 119 |
+
binary_pairs.append((target_binary, pred_binary))
|
| 120 |
+
option_pairs.append((target, None if pred is None else str(pred)))
|
| 121 |
+
if target != "CORRECT":
|
| 122 |
+
error_type_pairs.append((target, None if pred in (None, "CORRECT") else str(pred)))
|
| 123 |
+
binary = classification_scores(binary_pairs, labels=["CORRECT", "ERROR"])
|
| 124 |
+
option = classification_scores(option_pairs, labels=sorted(PMD_OPTIONS))
|
| 125 |
+
error_type = classification_scores(
|
| 126 |
+
error_type_pairs,
|
| 127 |
+
labels=sorted(option for option in PMD_OPTIONS if option != "CORRECT"),
|
| 128 |
+
)
|
| 129 |
+
parse_errors = sum(1 for row in scored if row.get("pred_option") is None)
|
| 130 |
+
return {
|
| 131 |
+
"task": self.name,
|
| 132 |
+
"display_name": self.display_name,
|
| 133 |
+
"rows": len(rows),
|
| 134 |
+
"scored": len(scored),
|
| 135 |
+
"errors": sum(1 for row in rows if row.get("error")),
|
| 136 |
+
"parse_errors": parse_errors,
|
| 137 |
+
"parse_success_rate": (len(scored) - parse_errors) / len(scored) if scored else None,
|
| 138 |
+
"binary_accuracy": binary["accuracy"],
|
| 139 |
+
"binary_balanced_accuracy": binary["balanced_accuracy"],
|
| 140 |
+
"binary_macro_f1": binary["macro_f1"],
|
| 141 |
+
"binary_macro_precision": binary["macro_precision"],
|
| 142 |
+
"binary_macro_recall": binary["macro_recall"],
|
| 143 |
+
"binary_precision": binary["precision"],
|
| 144 |
+
"binary_recall": binary["recall"],
|
| 145 |
+
"binary_f1": binary["f1"],
|
| 146 |
+
"binary_confusion": binary["confusion"],
|
| 147 |
+
"option_accuracy": option["accuracy"],
|
| 148 |
+
"option_balanced_accuracy": option["balanced_accuracy"],
|
| 149 |
+
"option_macro_f1": option["macro_f1"],
|
| 150 |
+
"option_confusion": option["confusion"],
|
| 151 |
+
"error_type_accuracy": error_type["accuracy"],
|
| 152 |
+
"error_type_balanced_accuracy": error_type["balanced_accuracy"],
|
| 153 |
+
"error_type_macro_f1": error_type["macro_f1"],
|
| 154 |
+
"error_type_macro_precision": error_type["macro_precision"],
|
| 155 |
+
"error_type_macro_recall": error_type["macro_recall"],
|
| 156 |
+
"error_type_precision": error_type["precision"],
|
| 157 |
+
"error_type_recall": error_type["recall"],
|
| 158 |
+
"error_type_f1": error_type["f1"],
|
| 159 |
+
"error_type_confusion": error_type["confusion"],
|
| 160 |
+
"target_counts": dict(Counter(str(row.get("target_option")) for row in scored)),
|
| 161 |
+
"pred_counts": dict(Counter(str(row.get("pred_option")) for row in scored)),
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
def score(self, rows: list[dict[str, Any]]) -> dict[str, Any]:
|
| 165 |
+
parsed = self.parse_rows(rows)
|
| 166 |
+
summary = self._summary(parsed)
|
| 167 |
+
for metric in (
|
| 168 |
+
"binary_accuracy",
|
| 169 |
+
"binary_balanced_accuracy",
|
| 170 |
+
"binary_macro_f1",
|
| 171 |
+
"binary_macro_precision",
|
| 172 |
+
"binary_macro_recall",
|
| 173 |
+
"error_type_accuracy",
|
| 174 |
+
"error_type_balanced_accuracy",
|
| 175 |
+
"error_type_macro_f1",
|
| 176 |
+
"error_type_macro_precision",
|
| 177 |
+
"error_type_macro_recall",
|
| 178 |
+
):
|
| 179 |
+
summary[f"{metric}_sem"] = bootstrap_sem(parsed, metric, self._summary, iterations=200)
|
| 180 |
+
return summary
|
lsvbench/tasks/prompts/pmd.md
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
You are monitoring a scientist learning how to utilize tools in the wet-lab. You are in simple detection mode and are observing for common technique issues or misuse of tools. In the snippet of user practicing their pipette usage please select the closest option below that describes what happened in the video.
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
## Options
|
| 5 |
+
1. CORRECT: correct usage of pipette tip no mistakes
|
| 6 |
+
2. ERROR_REUSE: reused tip on different media causing contamination
|
| 7 |
+
3. ERROR_SURFACE: tip was contaminated by touching surface
|
| 8 |
+
4. ERROR_RELEASE: tip was dropped or released unexpectedly
|
| 9 |
+
5. ERROR_INSTALL: pipette tip installed (or attempted) was of wrong size/incorrectly fitted
|
| 10 |
+
6. ERROR_OTHER: when you are sure its wrong but it does not fit above cateogory label as other
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
## Output format
|
| 14 |
+
Strict SINGLE_WORD all cap option response no other symbols or description from the options above.
|
pmd/README.md
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LSV PMD Split Benchmark Dataset
|
| 2 |
+
|
| 3 |
+
PMD split clips provide short pipetting examples for correct-vs-mistake and mistake-type evaluation.
|
| 4 |
+
|
| 5 |
+
## Layout
|
| 6 |
+
|
| 7 |
+
- `correct/`: split correct demonstration clips
|
| 8 |
+
- `incorrect/`: split mistake demonstration clips
|
| 9 |
+
- `pmd.parquet`: split-clip benchmark manifest
|
| 10 |
+
|
| 11 |
+
## Counts
|
| 12 |
+
|
| 13 |
+
- split clips: `246`
|
| 14 |
+
- by label: `{'correct': 15, 'incorrect': 231}`
|
| 15 |
+
- by mistake_type: `{'early_release': 45, 'none': 15, 'reuse_same_media': 27, 'reuse_same_tip': 4, 'reuse_tip': 53, 'surface_contamination': 44, 'wrong_tip_for_pipette': 58}`
|
| 16 |
+
|
| 17 |
+
## Review Flags
|
| 18 |
+
|
| 19 |
+
- needs_review clips: `6`
|
| 20 |
+
|
| 21 |
+
The `needs_review` and `notes` columns preserve human review notes for a small number of clips whose source labels required normalization.
|
| 22 |
+
|
| 23 |
+
## Evaluation
|
| 24 |
+
|
| 25 |
+
Use `pmd/pmd.parquet` with `lsvbench/tasks/prompts/pmd.md` or the `pmd` task in `lsvbench`.
|
| 26 |
+
|
| 27 |
+
The prompt preserves detailed answer options (`ERROR_REUSE`, `ERROR_SURFACE`, `ERROR_RELEASE`, `ERROR_INSTALL`, `ERROR_OTHER`) for compatibility with existing model outputs. The public benchmark report collapses all non-`CORRECT` options into binary `ERROR` and reports only **Error Detection** metrics.
|
pmd/correct/pmd_correct_01.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e73ea20cbedd36a0311382f985693e956f7ead7bce6fab59f1b262a61d26577a
|
| 3 |
+
size 29669544
|
pmd/correct/pmd_correct_02.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:24aa5fb73837e1f36d6b86339f305dc314a6cc8fd7a7bb42ef895f770fb3f84c
|
| 3 |
+
size 19931616
|
pmd/correct/pmd_correct_03.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7bd7edec6bad845b9aef98d7755d4efc48b9bbe3f6bdf4e51d8fa9e053c8b6a3
|
| 3 |
+
size 23753995
|
pmd/correct/pmd_correct_04.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:56d3e55fa6e2dbae9a50f81e12a936bf9ec4286d656ea1dbe065c201d0b55c4c
|
| 3 |
+
size 31180894
|
pmd/correct/pmd_correct_05.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d2519168af56b1cb993a199380ae08026e1f2eee09300afe81bec914e6d39741
|
| 3 |
+
size 29044577
|
pmd/correct/pmd_correct_06.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e08a1e88f6d8c65bf8a3faeca03b44da71a00fc6b1ef2b75ae740be9bca86aab
|
| 3 |
+
size 22768550
|
pmd/correct/pmd_correct_07.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:fc28e94e32a3051d3e07994e7c9ee33048d80c4e85c7e838fd8921a5dbd743a3
|
| 3 |
+
size 27954211
|
pmd/correct/pmd_correct_08.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:20409a5cc2852d9ac419281f8e8ec9b15045e66ae2f3bafe0c5f11d96e1c0039
|
| 3 |
+
size 21897593
|
pmd/correct/pmd_correct_09.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9b0fe081df18c80a994f5fabad6a59815c04b96e36c9612a63dc8ce8ceda44cd
|
| 3 |
+
size 22096226
|
pmd/correct/pmd_correct_10.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:171b41c5f13a4ed4f8498b0637c147e69fccad67c32b92bc498e623fcc9d8a6f
|
| 3 |
+
size 23004076
|
pmd/correct/pmd_correct_11.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:453304575a1d05c41aecf5a19f00de1cc966a27d5acba4a6e9db02933e854141
|
| 3 |
+
size 18543452
|
pmd/correct/pmd_correct_12.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:192f6bb3f7463e288818f23aa572084b1eaf02dbf90ef9e94c3a523c20e6990b
|
| 3 |
+
size 16675324
|
pmd/correct/pmd_correct_13.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b62e4b12fc49b6dde9ebad32a55a61e55005091513cad8687acb0fdde6e54911
|
| 3 |
+
size 28687702
|
pmd/correct/pmd_correct_14.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:598314cc30c3263d3c65749ef6ca06da11bb8a64a2db729f531c74e6717b1f11
|
| 3 |
+
size 19221727
|