# VLM evaluation — implementation reference This is the **engineering/architecture reference** for the vision-language-model (VLM) evaluation subsystem (`itrialspace.evaluation.vlm_eval`). It documents the design, the data model, every module's responsibility, and the extension points. For task-oriented instructions (how to run a demo, reproduce the study, troubleshoot) see the user guide [vlm_eval.md](vlm_eval.md); for the released numbers see [vlm_results.md](vlm_results.md); for the data contract see [dataset_card.md](dataset_card.md). --- ## 1. Scope and design goals The subsystem evaluates three zero-shot VLMs — **BiomedCLIP**, **LLaVA-Med**, and **MedGemma** — on three clinical tasks (**presence**, **lobe**, **size**) over four image **conditions** (`plain`, `bbox`, `contour`, `bbox_contour`), on both **synthetic** and **real** lung-nodule CT. It is built around five principles: 1. **Single tidy data contract.** Every model run emits the same row schema; every analysis is a group-by over one long table. No bespoke per-model parsing downstream. 2. **Stable identity.** A case is identified by a **canonical uid** derived from its slice path — never the non-unique `case_id` index in the CSVs (§4). 3. **Reproducible, fixed reporting sets.** Accuracy is reported on a frozen, checksummed **split** so reruns and re-reports score the same cases (§7). 4. **Auto-discovery.** Tools infer which models/conditions/tasks are present, so the *same* code serves the full released dataset and a tiny demo run. 5. **Portable & secret-free.** All paths come from `ITRIALSPACE_DATA_DIR`/`settings`; the HuggingFace token comes from `.env` (`HF_TOKEN`), never from code (§9). --- ## 2. Architecture at a glance ``` ┌──────────────────────── Stage 1: dataset construction ────────────────────────┐ manifests / profiles ──▶│ build_dataset (synthetic) · build_real_dataset (real) │ generated_cts / masks │ └─ slice_extractor (centre-slice + z±1) · overlay (bbox/contour) │──▶ eval_dataset.csv raw_ct / nodule_seg │ └─ preprocess_profiles (lung_axial / lung_axial_medgemma) │ + slices/*.png └───────────────────────────────────────────────────────────────────────────────┘ ┌──────────────────────── Stage 2: inference ──────────────────────────────────┐ eval_dataset.csv ──────▶│ runners/run_conditions ─▶ run_biomedclip · runners/run_llava_med · run_medgemma│──▶ //_results.csv │ models/{biomedclip,llava_med,medgemma} · prompt_templates · parsers │ │ inference_cache (resume) │ └───────────────────────────────────────────────────────────────────────────────┘ ┌──────────────────────── Stage 3: scoring & reporting ────────────────────────┐ *_results.csv ─────────▶│ splits / make_split (frozen sets) · metrics · comparison / cross_model │──▶ accuracy / deltas / splits.json └───────────────────────────────────────────────────────────────────────────────┘ ┌──────────────────────── Stage 4: analysis suite ─────────────────────────────┐ *_results.csv + split ─▶│ eval_analysis: load ─▶ tables · stats · plots ─▶ report │──▶ tables/ + figures/ + report.md └───────────────────────────────────────────────────────────────────────────────┘ ``` | Layer | Modules | Responsibility | |-------|---------|----------------| | Dataset construction | `build_dataset`, `build_real_dataset`, `build_negative_dataset`, `slice_extractor`, `overlay`, `preprocess_profiles` | Turn 3-D CTs + masks into 2-D eval slices + ground truth | | Model adapters | `models/biomedclip_model`*, `models/llava_med`, `models/medgemma` | Uniform `predict`/`predict_batch` over each backbone | | Inference orchestration | `runners/run_conditions`, `run_biomedclip`, `runners/run_llava_med`, `runners/run_medgemma`, `run_all` | Drive a model across conditions/tasks; write result CSVs | | Prompting & parsing | `prompt_templates`, `parsers` | Task prompts + robust free-text → label parsing | | Scoring | `metrics`, `comparison`, `cross_model_comparison`, `inference_cache` | Accuracy/F1, condition deltas, resume | | Reporting sets | `splits`, `make_split` | Canonical uid, frozen checksummed splits, `--case-ids` | | Analysis suite | `eval_analysis/{load,tables,stats,plots,report}` | Full tables, figures, statistics, markdown report | \* `biomedclip_model.py` lives at the package root; the generative adapters live under `models/`. --- ## 3. The two stages of data, and what "results" mean - A **case** is one nodule on one CT. Synthetic cases come from a trial-mode manifest (an inserted donor nodule on a host CT); real cases come from a dataset's nodule profile. - Each case yields, per **preprocessing profile**, **3 z-slices** (`z`, `z-1`, `z+1`) × **4 conditions** = up to 12 PNGs. **Evaluation uses the centre (`z`) slice**; `z±1` are context that MedGemma may stack (BiomedCLIP/LLaVA-Med use the centre slice only). - A **run** scores one `(model × condition × task)` and writes one `//_results.csv`, one row per case, with `prediction`, `ground_truth`, `correct`, and the slice `image_path`. --- ## 4. Data model ### 4.1 `eval_dataset.csv` (Stage 1 output) One row per case (per profile). Key columns: | Column | Meaning | |--------|---------| | `png_path`, `png_bbox_path`, `png_contour_path`, `png_bbox_contour_path` | centre-slice PNG per condition | | `slice_z`, `slice_method`, `preprocess_profile` | extraction provenance | | `ground_truth_presence` | `present` / `absent` | | `ground_truth_lobe` | 5 classes (`right_lung_upper_lobe` … `left_lung_lower_lobe`) | | `ground_truth_size_bucket` | `<5mm`, `5-10mm`, `10-20mm`, `>20mm` | | `mode` / `dataset`, `effective_diam_mm`/`nodule_mean_diam_mm`, `insertion_lobe`, `population_type` | metadata for breakdowns | **Ground-truth derivation.** Synthetic labels are **known by construction** (insertion lobe; `effective_diam_mm` binned to a size bucket; `present` unless a deliberately nodule-free case). Real labels come from the source dataset's annotations (lobe normalised to the 5 canonical classes via `prompt_templates.normalise_lobe`; diameter binned via `diameter_to_size_bucket`; all `present`). ### 4.2 Canonical uid — the only stable key The `case_id` column in both `eval_dataset.csv` and the result CSVs is a **non-unique positional index** (it restarts per shard). The stable identity is the slice path with the condition sub-dir and extension stripped, computed by [`splits.canonical_uid`](../src/itrialspace/evaluation/vlm_eval/splits.py): ``` …/slices/mode1_controlled_prevalence/NLST_cohort__C0000.png ┐ …/slices/mode1_controlled_prevalence/bbox/NLST_cohort__C0000.png ┘ → mode1_controlled_prevalence/NLST_cohort__C0000 ``` so one case maps to one uid across all four conditions, and results join cleanly to `eval_dataset.csv`. **All joins, intersections, and de-duplication use the uid, never `case_id`.** --- ## 5. Stage 1 — dataset construction - **`slice_extractor`** locates the nodule centroid (from the inserted/nodule mask), extracts the axial centre slice and `z±1`, converts to radiological orientation, applies the HU window, and drops artefact slices. `preprocess_profiles` defines the windows: `lung_axial` (BiomedCLIP/LLaVA-Med) and `lung_axial_medgemma` (3-channel z-stack). - **`overlay`** renders the spatial-guidance variants from the mask: `bbox` (bounding box), `contour` (segmentation outline), `bbox_contour` (both). `VALID_CONDITIONS` is the single source of truth for the condition set. - **`build_dataset`** (synthetic) resolves each manifest case's `synthetic_ct` + mask, extracts slices, draws overlays (`--overlays`), and writes `eval_dataset.csv` (multiprocessing via `--workers`). **`build_real_dataset`** does the same from real profiles + `raw_ct/` + `nodule_seg/`. **`build_negative_dataset`** samples nodule-free lung slices for presence negatives. Output: `vlm_dataset/{synthetic,real}//{eval_dataset.csv, slices/…}`. --- ## 6. Stage 2 — inference - **Model adapters** (`models/…`) present a uniform interface (lazy weight loading; batched `predict`). BiomedCLIP is contrastive (open_clip; scores label prompts); LLaVA-Med and MedGemma are generative (`transformers`), prompted via `prompt_templates.get_generative_prompt`. - **`parsers`** turns free-text generative answers into a label + a `ParseResult` status (handles synonyms, negation, partial matches) so scoring is robust. - **`runners/run_conditions`** is the orchestrator: it remaps `png_path` to the chosen condition column, optionally restricts to a split (`--case-ids`, §7), and dispatches to the per-model runner for each condition. `run_all` chains the full matrix. - **`inference_cache`** lets a run resume by reusing prior rows for unchanged cases (`--skip-existing`). Output: `//_results.csv` (+ per-mode and `aggregate/` copies). --- ## 7. Stage 3 — reporting sets and the reporting-N convention > **Convention.** Report accuracy on the cases scored in *every* `(model × condition × > task)` you compare — the canonical-uid **intersection** — so every number shares one N. - **`metrics.common_case_ids`** computes that intersection (keyed on the uid). - **`splits` / `make_split`** freeze it as a checksummed artifact under `vlm_dataset/splits/`: a sorted uid list per set plus `splits.json` (count, SHA-256, source globs, git commit). Two ship with the release: | Split | Synthetic | Real | Scope | |-------|----------:|-----:|-------| | `release_v1` | 42,858 | 13,087 | all models × `plain` × 3 tasks | | `release_v1_full` | 41,502 | 13,047 | all models × **4 conditions** × 3 tasks | - Every runner accepts **`--case-ids `** to score exactly that set. - `comparison` / `cross_model_comparison` produce per-condition deltas for a single run. This is also the reconciliation point for the paper: the submission's synthetic N = 42,382 is the *same rule* at a pre-inference snapshot; the release completes inference, so `release_v1` = 42,858. See [dataset_card.md](dataset_card.md#reporting-convention-evaluation-n--read-before-comparing-to-the-paper). --- ## 8. Stage 4 — the `eval_analysis` suite A reusable engine that turns result CSVs into a full report: - **`load`** — auto-discovers condition-level `*_results.csv` under any root, joins each row to its `eval_dataset.csv` metadata, applies a split, and returns **one tidy long DataFrame** (`set, model, condition, task, uid, prediction, ground_truth, correct, mode, source_dataset, lobe, size_bucket, diam_mm, population`). - **`tables`** — accuracy, Δ-vs-baseline, breakdowns (mode / dataset / size / lobe), confusion, per-class. - **`stats`** — percentile **bootstrap CIs** and paired **McNemar** significance of each condition vs the baseline. - **`plots`** — publication-style figures (top/right spines removed, shared y-axis with labels on the first panel, blue-shade palette, 300-dpi PNG + vector PDF). - **`report`** — orchestrates everything into `out/{tables/*.csv, figures/*, report.md}`. ```bash python -m itrialspace.evaluation.vlm_eval.eval_analysis \ --results $ITRIALSPACE_DATA_DIR/vlm_dataset --split release_v1_full --out analysis/ # demo: --results out/demo (omit --split; auto-discovers what's present) ``` --- ## 9. Configuration, portability, and secrets - **Paths** are never hardcoded. `itrialspace.config.settings` resolves everything from `ITRIALSPACE_DATA_DIR` / `ITRIALSPACE_OUTPUT_DIR` (with `.env` loaded once at import; real environment variables win). `tools/check_portability.py` gates against stray absolute paths. - **HuggingFace token.** Gated models (MedGemma; some LLaVA-Med checkpoints) read the token from the environment via `settings.hf_token()` (`.env` → `HF_TOKEN`, or the legacy `HUGGING_FACE_HUB_TOKEN`) and pass it to `from_pretrained`. **No token is ever committed**; `.env` is gitignored. To share, clear the value — each user supplies their own. BiomedCLIP is public and needs none. - **Weights** are not bundled; models load from the HuggingFace cache (or a local `--model-id`). --- ## 10. Extension points | To add… | Do this | |---------|---------| | **a model** | Add an adapter under `models/` with `predict`/`predict_batch`; register a dispatch branch in `runners/run_conditions._run_model`. | | **a task** | Add a `TaskDefinition` to `prompt_templates.ALL_TASKS` (+ generative prompt) and a parser in `parsers`. | | **a condition** | Extend `overlay.VALID_CONDITIONS` + the draw function and the `_CONDITION_COLUMNS` map in `run_conditions`. | | **a preprocessing profile** | Add a `PreprocessProfile` in `preprocess_profiles`. | | **an analysis breakdown** | Add the column to `eval_analysis.load` metadata and a `breakdown_table(by=…)` call in `report`. | --- ## 11. Quality gates - **Lint/format:** `ruff` + `black` (CI; repo standard). - **Portability:** `tools/check_portability.py`. - **Reproducibility:** split SHA-256 in `splits.json` — regenerate with `make_split` and the hash must match. - **Tests:** unit tests run under `pytest -m "not full_volume"`; full-volume/model tests are env-gated (need data/GPU). --- ## 12. Module reference | Module | One-line role | |--------|---------------| | `build_dataset.py` | Build synthetic eval dataset from trial manifests | | `build_real_dataset.py` | Build real-CT eval dataset from nodule profiles | | `build_negative_dataset.py` | Sample nodule-free slices (presence negatives) | | `slice_extractor.py` | Centroid-centred axial slice extraction + HU windowing | | `overlay.py` | bbox / contour / bbox_contour spatial-guidance overlays | | `preprocess_profiles.py` | Named preprocessing profiles (windows, z-stack) | | `prompt_templates.py` | Task definitions, prompts, lobe/size normalisation | | `parsers.py` | Free-text answer → label (robust) | | `biomedclip_model.py`, `models/llava_med.py`, `models/medgemma.py` | Model adapters | | `run_biomedclip.py`, `runners/run_llava_med.py`, `runners/run_medgemma.py` | Per-model runners | | `runners/run_conditions.py`, `run_all.py` | Condition/matrix orchestration | | `inference_cache.py` | Resume support | | `metrics.py` | Accuracy/F1/confusion + `common_case_ids` | | `comparison.py`, `cross_model_comparison.py` | Per-condition / cross-model deltas | | `splits.py`, `make_split.py` | Canonical uid + frozen checksummed splits | | `report.py` | Quick single-table headline report | | `eval_analysis/` | Full analysis suite (tables, stats, figures, report) | ```