NeurIPS-Code / itrialspace /blinded_doc /vlm_eval_implementation.md
AnonymousUN's picture
Add full itrialspace framework, including code, slurm scripts, and configs
da53a66 verified
|
Raw History Blame Contribute Delete
16.4 kB

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; for the released numbers see vlm_results.md; for the data contract see 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│──▢ <model>/<cond>/<task>_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 <model>/<condition>/<task>_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:

…/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}/<profile>/{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: <model>/<condition>/<task>_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 <split.txt> 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.


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}.
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)