Shantanu Ghosh1, Rayan Syed1, Chenyu Wang1, Vaibhav Choudhary1, Binxu Li2, Clare B. Poynton3, Shyam Visweswaran4 Kayhan Batmanghelich1
1BU ECE, 2 Stanford University, 3 BUMC, 4 Pitt DBMI
- TL;DR
- Highlights
- Warnings
- Acknowledgements
- Python package
- Public Python API
- CLI
- Environment Setup
- Dataset Zoo
- Model Zoo
- Downloading Classifier Checkpoints
- Vision-Language Representation Space
- Generating Captions
- LADDER Pipeline
- Demo Notebooks
- Scripts
- Citation
- License
- Contact
- Contributing
LADDER is a modular framework that uses large language models (LLMs) to discover, explain, and mitigate hidden biases in vision classifiersβwithout requiring prior knowledge of the biases or attribute labels.
-
π 6 Datasets Evaluated
- π¦ Natural Images: Waterbirds, CelebA, MetaShift
- π₯ Medical Imaging: NIH ChestX-ray, RSNA-Mammo, VinDr-Mammo
-
π§ͺ ~20 Bias Mitigation Algorithms Benchmarked
- π‘ ERM, GroupDRO, CVaR-DRO, JTT, LfF, DFR
- 𧬠CORAL, IRM, V-REx, IB-IRM, Reweighting, Mixup, AugMix
-
π§ 11 Architectures Across 5 Pretraining Strategies
- π§± CNNs: ResNet-50, EfficientNet-B5
- π² ViTs: ViT-B/16, ViT-S/16
- π§ͺ Pretrained With: SimCLR, Barlow Twins, DINO, CLIP (OpenAI),
IN1K, IN21K, SWAG, LAION-2B
-
π¬ 4 LLMs for Hypothesis Generation
- π§ GPT-4o, Gemini, LLaMA, Claude
Star π us if you think it is helpful!!
π§ Replace all hardcoded paths like
/restricted/projectnb/batmanlab/shawn24/PhDwith your own directory.Following guidelines of [MIMIC-CXR] (https://physionet.org/news/post/gpt-responsible-use), we setup google vertex ai for setting GEMINI as LLM for hypothesis generation for medical images in this codebase.
π All LLMs were evaluated using checkpoints available before Jan 11, 2025.
Newer versions may produce different hypotheses than those reported in the paper.π§ Default setup uses:
- GPT-4o as captioner for the natural images
- ResNet-50 for the classifier
- ViT-B/32 for the vision-language representation space
- GPT-4o for hypothesis generation
The code is modular and can be easily extended to other models and LLMs.ποΈ Update cache directory locations in
save_img_reps.pyto your own:os.environ['TRANSFORMERS_CACHE'] = '/your/custom/.cache/huggingface/transformers' os.environ['TORCH_HOME'] = '/your/custom/.cache/torch'
We rely heavily on the Subpopulation Shift Benchmark (SubpopBench) codebase for:
- π₯ Downloading and processing datasets
- π§ Classifier training on natural image benchmarks
- Note: SubpopBench does not support NIH-CXR datasets.
To address this, our codebase includes extended experiments for NIH ChestX-ray (NIH-CXR), which are discussed in subsequent sections. Necessary compatibility modifications of SubPopShift are included in our repo undersrc/codebase/SubpopBench-main
The ladder-slices package exposes the full LADDER pipeline through a dataset/model-driven Python API. Install from PyPI with Python 3.10+ and PyTorch 2.6+:
python -m pip install 'ladder-slices[vision,openai]'The example below shows all seven public APIs using a local image manifest, samples.csv, with id,image,label,split columns and separate train, valid, and test splits. Use your actual image paths and binary labels, and ensure each Waterbirds validation class has both correct and incorrect baseline predictions. Set OPENAI_API_KEY and use an available CUDA GPU, or change each device="cuda" to device="cpu".
import csv
import os
from pathlib import Path
import numpy as np
from ladder_slices import Ladder, LinearAligner, retrieve, discover, mitigate
pipeline = Ladder("Waterbirds", "resnet50", llm="openai", llm_model="gpt-4o",
api_key=os.environ["OPENAI_API_KEY"], device="cuda")
# 1. Image embeddings: paired classifier/VLM features and baseline predictions.
manifest_path = Path("samples.csv").resolve()
with manifest_path.open(newline="") as stream:
rows = list(csv.DictReader(stream))
def embed_split(split):
samples = [row for row in rows if row["split"] == split]
paths = [manifest_path.parent / row["image"] for row in samples]
labels = np.array([int(row["label"]) for row in samples], dtype=np.int64)
return pipeline.embeddings(paths, batch_size=8), labels
train, _ = embed_split("train")
valid, y_valid = embed_split("valid")
# 2. Text embeddings: one normalized vector per candidate sentence.
sentences = ["A bird with water in the background.",
"A bird with trees and leaves in the background."]
text_vectors = pipeline.text_embeddings(sentences)
# 3. Alignment: fit on training pairs and select using validation pairs.
aligner = LinearAligner().fit(
train["features"], train["vision"],
validation=(valid["features"], valid["vision"]), device="cuda",
)
# 4. Sentence retrieval: rank evidence for landbird errors (class 0).
ranked = retrieve(
valid["features"], y_valid, valid["predictions"], text_vectors, sentences,
aligner=aligner, class_label=0,
)
# 5. Slice scoring: use the two sentences as illustrative manual hypotheses.
slices = discover(
valid["features"], y_valid, valid["predictions"], text_vectors,
aligner=aligner, names=["water_background", "forest_background"],
class_label=0,
)
# 6. Mitigation: retrain copies of the original classifier's final layer.
classifier = pipeline.classifier()
mitigator = mitigate(
valid["features"], y_valid, slices["scores"],
initial_weight=classifier.weight, initial_bias=classifier.bias, device="cuda",
)
# 7. Full pipeline: run all stages together, including LLM hypothesis generation.
result = pipeline.run(
"outputs/waterbirds-001", manifest=manifest_path, sentences=sentences,
)Calls 1β6 use manually supplied text and do not call an LLM. The final run() call repeats the workflow with generated hypotheses and saves its results. For a full run without the individual-stage calls, use pipeline.run("outputs/waterbirds-001", manifest="samples.csv") after creating the pipeline. The two example sentences illustrate the API; supply your caption/report corpus for an experiment. See Public Python API for outputs, shapes, defaults, and test-time inference.
The package selects the released classifier and matching vision-language encoder from Hugging Face. It supports the six published dataset/model pairs, OpenAI/Anthropic/Gemini, and OpenAI-compatible endpoints. The default run reuses published image representations; supply a local image manifest to recompute embeddings. See the Python package guide for the model registry, local inputs, optional dependencies, outputs, and documented differences from the research scripts.
All seven operations below are public. Ladder.embeddings(), Ladder.text_embeddings(), and Ladder.run() are instance methods; LinearAligner.fit() is called on an aligner instance; retrieve(), discover(), and mitigate() are standalone functions. Each stage can be used independently when its required inputs are available.
| Operation | Public API | Returns |
|---|---|---|
| Image embeddings | pipeline.embeddings(images) |
Classifier/VLM features and baseline predictions |
| Text embeddings | pipeline.text_embeddings(sentences) |
Normalized text vectors |
| Alignment | LinearAligner().fit(classifier, vision, validation=...) |
Fitted LinearAligner |
| Sentence retrieval | retrieve(...) |
Ranked sentence records |
| Slice scoring and validation | discover(...) |
Scores, membership, thresholds, and accuracy statistics |
| Mitigation | mitigate(...) |
Trained Mitigator |
| Full pipeline | pipeline.run(output_dir, ...) |
Run summary dictionary; artifacts saved to disk |
The manual examples below can be run in order. They use Python 3.10+, the vision extra for image/text extraction, and a local samples.csv with separate train, valid, and test splits. See the manifest schema for the required id,image,label,split columns and dataset label meanings in the model registry. Supply a real cohort with both classes and both correct and incorrect validation predictions for the class being analyzed.
import csv
from pathlib import Path
import numpy as np
from ladder_slices import (
Ladder, LinearAligner, Mitigator, retrieve, discover, mitigate,
)
# No LLM configuration or key is needed for the six individual stages below.
pipeline = Ladder("Waterbirds", "resnet50", device="cpu")Use device="cuda" on an available CUDA GPU. The constructor also accepts cache_dir and local_files_only=True; the latter requires model assets to be cached. Models are loaded lazily when an operation needs them. The array-based alignment, retrieval, discovery, and mitigation APIs can instead use your existing embeddings without constructing Ladder.
In the shapes below, N is the number of images in a split, D_c the classifier feature dimension, D_v the shared vision-language dimension, S the sentence count, and H the hypothesis count. All feature/score matrices must be finite and nonempty. Labels and predictions are binary vectors of shape (N,); keep their row order aligned with the images. Use the same encoder and embedding dimensions across all stages.
pipeline.embeddings(images, *, batch_size=8) extracts paired representations from the registered classifier and vision-language image encoder. Pass a nonempty list of image paths (str or Path) or Pillow images, including for a single image. The method applies the dataset's evaluation preprocessing, preserves input order, and returns NumPy arrays in memory:
| Dictionary key | Shape | Meaning |
|---|---|---|
features |
(N, D_c) |
Classifier features before the final classification layer |
vision |
(N, D_v) |
L2-normalized vision-language image embeddings |
predictions |
(N,) |
Original classifier's predicted class, 0 or 1 |
probabilities |
(N,) |
Original classifier's probability of class 1 |
The result does not include ground-truth labels or sample IDs; retain these alongside the input list. The following helper reads each split from a local manifest, resolving relative image paths against the CSV directory:
manifest_path = Path("samples.csv").resolve()
with manifest_path.open(newline="") as stream:
rows = list(csv.DictReader(stream))
def embed_split(split):
selected = [row for row in rows if row["split"] == split]
paths = [manifest_path.parent / row["image"] for row in selected]
labels = np.array([int(row["label"]) for row in selected], dtype=np.int64)
return pipeline.embeddings(paths, batch_size=8), labels
train, _ = embed_split("train")
valid, y_valid = embed_split("valid")
print(train["features"].shape, train["vision"].shape)This helper assumes the CSV already follows the manifest contract; Ladder.run(manifest=...) performs the package's full manifest validation. Mammography inputs must already be preprocessed PNGs of width 912 and height 1520; this API does not convert DICOMs. Natural-image and NIH transforms are described in the input guide. The same preprocessed image tensor is passed to both encoders, following the research extraction convention.
pipeline.text_embeddings(sentences, *, batch_size=32) encodes a nonempty list of nonblank strings with the matching vision-language text encoder. It returns a float32 NumPy array of shape (S, D_v), with one L2-normalized vector per input sentence in the same order. It requires the vision extra and encoder assets, but no classifier forward pass or LLM key.
# Illustrative candidates; use the caption/report corpus for your task.
sentences = [
"A bird standing in shallow water.",
"A bird beside a lake.",
"A bird among green leaves.",
"A bird perched on a tree branch.",
]
text_vectors = pipeline.text_embeddings(sentences, batch_size=32)
print(text_vectors.shape)These are embeddings of supplied text; this method does not caption images or generate hypotheses. Tokenization truncates to the encoder's configured maximum length: 77 tokens for the registered natural-image CLIP model and 256 for the medical encoders. The vectors can be passed directly to retrieve() or used as one prompt vector per hypothesis in discover().
LinearAligner().fit(classifier, vision, *, validation, ...) learns an affine map from classifier features into the vision-language space. Training inputs must be paired arrays of shapes (N_train, D_c) and (N_train, D_v). The required validation=(classifier_valid, vision_valid) tuple supplies separate paired arrays with matching feature dimensions; labels are not needed.
aligner = LinearAligner().fit(
train["features"],
train["vision"],
validation=(valid["features"], valid["vision"]),
epochs=30,
lr=0.01,
batch_size=100,
seed=0,
device="cpu",
)
aligned_valid = aligner.transform(valid["features"]) # (N_valid, D_v)
aligner.save("aligner.npz")
restored_aligner = LinearAligner.load("aligner.npz")fit() returns the fitted instance. It rescales training arrays using their global variances (target_variance=4.5 by default), optimizes mean squared error with SGD, and selects weights by validation MSE. The SGD momentum is 0.9, weight decay is 5e-4, and the cosine scheduler uses T_max=200. Constant training embeddings and incompatible row counts/dimensions raise ValueError.
The learned W has shape (D_v, D_c) and b has shape (D_v,); transform(X) computes X @ W.T + b without subsequent normalization. The default legacy_bias_scaling=True preserves the research script's bias rescaling; pass False for the exact inverse rescaling of the trained affine map. Set training options explicitly when reusing existing embeddings; Ladder.run() uses the dataset's registered aligner epoch count.
retrieve(features, targets, predictions, text_embeddings, sentences, *, aligner, class_label, top_k=50) ranks candidate sentences using validation examples from one ground-truth class. Supply classifier features (N, D_c), binary labels/predictions (N,), text vectors (S, D_v), and S corresponding strings. The aligner must already be fitted or loaded.
ranked = retrieve(
valid["features"], y_valid, valid["predictions"],
text_vectors, sentences,
aligner=aligner,
class_label=0, # Waterbirds: 0 = landbird, 1 = waterbird
top_k=50,
)
for item in ranked:
print(item["index"], item["sentence"], item["score"])For the selected class, the method computes mean aligned correct features minus mean aligned incorrect features, scores each sentence by its dot product with that difference, and sorts in descending order. This preserves the research implementation's score direction. It returns up to min(top_k, S) dictionaries containing index (the original sentence row), sentence, and score. Scores are ranking values, not probabilities.
class_label must be 0 or 1, top_k must be positive, and the selected class must have both correct and incorrect validation predictions. Otherwise retrieval raises ValueError. Retrieval does not call an LLM: use the ranked evidence to formulate hypotheses yourself or pass it to your chosen hypothesis generator. The full pipeline performs that generation automatically.
discover(features, targets, predictions, prompt_embeddings, *, aligner, names, class_label=1, percentile=55, thresholds=None) scores already supplied hypotheses. Each hypothesis needs one nonzero vector in prompt_embeddings (H, D_v) and a unique entry in names. Classifier features, labels, and predictions follow the same row contract as retrieval.
# Example hypotheses supplied manually after reviewing the retrieved evidence.
names = ["water_background", "forest_background"]
prompt_embeddings = pipeline.text_embeddings([
"A landbird with water in the background.",
"A landbird with trees and leaves in the background.",
])
slices = discover(
valid["features"], y_valid, valid["predictions"], prompt_embeddings,
aligner=aligner,
names=names,
class_label=0,
percentile=55,
)
print(slices["statistics"])The function normalizes each prompt vector and computes scores = aligner.transform(features) @ normalized_prompts.T. When thresholds=None, it estimates each hypothesis's threshold at the requested percentile across all supplied rows, then marks scores at or above that threshold as members. percentile must be between 0 and 100; supplied thresholds must be a finite vector of shape (H,). class_label filters the reported accuracy statistics, not the rows used to estimate thresholds or the returned membership matrix.
| Return key | Shape/type | Meaning |
|---|---|---|
scores |
(N, H) float array |
Continuous prompt-similarity scores |
membership |
(N, H) boolean array |
Whether each score is at least its threshold |
thresholds |
(H,) float array |
One fitted or supplied threshold per hypothesis |
statistics |
List of H dictionaries |
name, class_label, threshold, low_count, high_count, low_accuracy, high_accuracy |
An empty high- or low-scoring group has accuracy None. These are descriptive slice statistics; discover() does not generate hypotheses, discard hypotheses with small gaps, or run a statistical significance test. Scores are dot products, not calibrated probabilities or cosine similarities, because aligned image features are not normalized here.
For a hypothesis with several paraphrases, Ladder.run() averages the encoder's unnormalized text vectors and then normalizes the mean. To reproduce this manually, obtain raw vectors with pipeline.encoder().encode_text(prompts, normalized=False), average along axis 0, and L2-normalize the resulting nonzero vector. Averaging the already normalized output of pipeline.text_embeddings() can give a different result.
Fit thresholds on validation data and pass the same thresholds=slices["thresholds"] when scoring test data, preserving hypothesis order. The mitigation example below shows this reuse.
mitigate(features, targets, scores, *, initial_weight, initial_bias, ...) retrains one copy of the original classifier's final layer per hypothesis. Supply classifier features (N, D_c), binary labels (N,), and the continuous slice scores (N, H) from discovery. Initialize from the classifier that produced the features:
classifier = pipeline.classifier()
mitigator = mitigate(
valid["features"], y_valid, slices["scores"],
initial_weight=classifier.weight,
initial_bias=classifier.bias,
n_per_group=100,
epochs=20,
lr=0.001,
weight_decay=0.0,
batch_size=32,
seed=0,
device="cpu",
)
mitigator.save("mitigator.npz")
restored_mitigator = Mitigator.load("mitigator.npz")
# Evaluate only after fitting; retain the validation thresholds.
test, y_test = embed_split("test")
test_slices = discover(
test["features"], y_test, test["predictions"], prompt_embeddings,
aligner=aligner,
names=names,
class_label=0,
thresholds=slices["thresholds"],
)
probabilities = mitigator.predict_proba(test["features"], test_slices["scores"])
predictions = mitigator.predict(test["features"], test_slices["scores"])
print("Test accuracy:", float(np.mean(predictions == y_test)))initial_weight must have shape (C, D_c) and initial_bias shape (C,), where C=1 is a sigmoid head and C=2 is a two-logit softmax head. All training options shown above are the function defaults. Optimization uses SGD with binary cross-entropy for a one-logit head and cross-entropy for a two-logit head; image encoders remain fixed.
For each hypothesis, training balances four groups: low- and high-scoring examples within each of classes 0 and 1. The actual count per group is min(n_per_group, N_class0 // 2, N_class1 // 2), with no overlap between the low/high selections for a class. At least two examples of each class are required. Pass continuous similarity scores, not the boolean membership matrix.
The returned Mitigator stores weights (H, C, D_c) and biases (H, C). At prediction time it selects the head with the highest hypothesis score for each image. predict_proba() returns (N, 2) class probabilities and predict() returns (N,) binary labels. Neither method needs ground-truth labels or slice thresholds. For unlabeled images, compute scores directly as aligner.transform(features) @ prompt_embeddings.T using the normalized prompt vectors; the test discover() call above additionally reports baseline slice accuracy using known test labels.
pipeline.run(output_dir, ...) combines image/text representations, alignment, retrieval, LLM hypothesis generation, validation, and balanced head retraining. By default it reuses the published Hugging Face image representations and sentence bank; a local manifest requests fresh image extraction. Test evaluation runs after fitting, using the validation thresholds.
import os
full_pipeline = Ladder(
"Waterbirds", "resnet50",
llm="openai",
llm_model="gpt-4o",
api_key=os.environ["OPENAI_API_KEY"],
device="cpu",
)
result = full_pipeline.run(
"outputs/waterbirds-api-001",
manifest="samples.csv", # Omit to reuse published image representations.
sentences=sentences, # Omit to use the default sentence bank.
progress=print,
)
print(result["test_baseline_accuracy"], result["test_mitigated_accuracy"])This example requires the openai extra and calls the configured provider to generate hypotheses. Choose an explicit provider/model, supply a custom llm=callable, or reuse a saved hypotheses file. retrieve() and discover() alone do not make these LLM requests.
| Argument | Default | Behavior |
|---|---|---|
output_dir |
Required | A new directory; existing directories raise FileExistsError |
manifest |
None |
Local CSV/JSON with nonempty train/valid splits and optional test; otherwise uses released representations |
sentences |
None |
List of strings, JSON array file, or text file with one sentence per line; otherwise uses the registered sentence bank |
hypotheses |
None |
Saved JSON path or class-keyed dictionary; bypasses LLM generation |
evaluate_test |
True |
Evaluates the separate test split when present; set False to skip it |
top_k |
50 |
Number of retrieved sentences supplied for each analyzed class |
batch_size |
8 |
Image and text extraction batch size |
aligner_epochs |
None |
Uses the registered default: 30 epochs, or 200 for NIH |
mitigation_epochs |
20 |
Epochs for each hypothesis-specific head |
n_per_group |
100 |
Maximum examples per class/score group for mitigation |
seed |
0 |
Training seed |
progress |
None |
Optional callback accepting a progress-message string, such as print |
Local manifest IDs and image paths must be unique across splits, and labels must be 0 or 1. The mammography default sentence bank uses bundled Mammo-FActOR prompts; see the input guide for dataset-specific corpus choices. Saved hypotheses must map every analyzed class to an object with a hypotheses list; each list entry needs name, description, and prompts. For Waterbirds the saved dictionary has both "0" and "1" keys. Reuse the pipeline's generated hypotheses.json directly:
cached_pipeline = Ladder("Waterbirds", "resnet50", local_files_only=True)
reused = cached_pipeline.run(
"outputs/waterbirds-reused-001",
manifest="samples.csv",
sentences=sentences,
hypotheses="outputs/waterbirds-api-001/hypotheses.json",
)This reuse example extracts from the same local images and sentence bank again, using model weights and encoder/tokenizer files cached by the first run. local_files_only=True controls Hugging Face downloads; reusing hypotheses is what avoids the LLM request.
The returned dictionary includes configuration/provenance, cohort sizes, hypothesis count, validation_baseline_accuracy, and validation_mitigated_training_accuracy. Test runs additionally include test_baseline_accuracy and test_mitigated_accuracy; these keys are absent when test evaluation is skipped or a local manifest has no test split. Validation accuracy after mitigation is a training metric because head fitting uses validation samples.
The output directory contains image/text representations, retrieval.json, aligner.npz, hypotheses.json, slices.npz, validation_slices.json, mitigator.npz, and run.json. Test evaluation adds test_predictions.npz and test_slices.json. A successful run writes complete.json last, with artifact hashes; a failed run has no completion marker. The return value is a summary, so use LinearAligner.load() and Mitigator.load() to restore the fitted stages. See the complete output reference.
Once ladder is available in your environment and OPENAI_API_KEY is set:
ladder models
ladder run \
--dataset Waterbirds --architecture resnet50 \
--llm openai --llm-model gpt-4o --api-key-env OPENAI_API_KEY \
--device cuda --output-dir ./outputs/waterbirds-001
# Outputs: run.json, aligner.npz, hypotheses.json, slices.npz,
# mitigator.npz, separate test predictions, and complete.json on success.See the CLI guide for local-image extraction, cached/offline runs, and the full input/output contract.
Use environment.yaml
git clone git@github.com:batmanlab/Ladder.git
cd Ladder
conda env create --name Ladder -f environment.yml
conda activate LadderPlease refer to the dataset_zoo.md for the details of the datasets used in this project. For toy dataset in Fig. 1, run the python script.
For the details of the classifiers, pretraining methods and algorithms supported by this codebase, refer to the classifier_zoo.md.
We provide the pretrained ResNet-50 (resnet_sup_in1k) and EfficientNet-B5 (tf_efficientnet_b5_ns-detect)
classifier checkpoints used in our experiments
via Hugging Face Hub.
- π¦ Waterbirds (ResNet-50)
- π€ CelebA (ResNet-50)
- πΆ MetaShift (ResNet-50)
- π« NIH ChestX-ray (ResNet-50)
- π§ͺ RSNA-Mammo (EfficientNet-B5)
- π₯ VinDr-Mammo (EfficientNet-B5)
We use the following vision-language representation space for our experiments:
- Natual images: CLIP
- Mammograms: Mammo-CLIP
- Chest-X-Rays: CXR-CLIP
Download the latest checkpoints from the respective repositories.
Ladder requires captions for the images in the validation dataset. We provide a script to generate captions for the images using BLIP and GPT-4o. You can get the captions directly from the respective dataset directory in Hugging Face or generate them using the following scripts.
python ./src/codebase/caption_images.py \
--seed=0 \
--dataset="Waterbirds" \
--img-path="/restricted/projectnb/batmanlab/shawn24/PhD/Ladder/data/waterbirds/waterbird_complete95_forest2water2" \
--csv="/restricted/projectnb/batmanlab/shawn24/PhD/Ladder/data/waterbirds/metadata_waterbirds.csv" \
--save_csv="/restricted/projectnb/batmanlab/shawn24/PhD/Ladder/data/waterbirds/va_metadata_waterbirds_captioning_blip.csv" \
--split="va" \
--captioner="blip"python ./src/codebase/caption_images_gpt_4.py \
--seed=0 \
--dataset="Waterbirds" \
--img-path="/restricted/projectnb/batmanlab/shawn24/PhD/Ladder/data/waterbirds/waterbird_complete95_forest2water2" \
--csv="/restricted/projectnb/batmanlab/shawn24/PhD/Ladder/data/waterbirds/metadata_waterbirds.csv" \
--save_csv="/restricted/projectnb/batmanlab/shawn24/PhD/Ladder/data/waterbirds/va_metadata_waterbirds_captioning_GPT.csv" \
--split="va" \
--model="gpt-4o" \
--api_key="<open-ai key>"- For NIH-CXR, we use the radiology report from MIMIC-CXR dataset. Download the metadata csv containing impression and findings from here.
- For RSNA-Mammo and VinDr-Mammo, we use the radiology text from Mammo-FActOR codebase.
Ladder pipeline consists of 6 steps. We uploaded the outputs of every step in the huggingface. The steps are as follows:
Step1: Save image representations of the image classifier and vision encoder from vision language representation space
python ./src/codebase/save_img_reps.py \
--seed=0 \
--dataset="Waterbirds" \
--classifier="resnet_sup_in1k" \
--classifier_check_pt="/restricted/projectnb/batmanlab/shawn24/PhD/Ladder/out/Waterbirds/resnet_sup_in1k_attrNo/Waterbirds_ERM_hparams0_seed{}/model.pkl" \
--flattening-type="adaptive" \
--clip_vision_encoder="ViT-B/32" \
--data_dir="/restricted/projectnb/batmanlab/shawn24/PhD/Ladder/data" \
--save_path="/restricted/projectnb/batmanlab/shawn24/PhD/Ladder/out/Waterbirds/resnet_sup_in1k_attrNo/Waterbirds_ERM_hparams0_seed{}"python ./src/codebase/save_text_reps.py \
--seed=0 \
--dataset="Waterbirds" \
--clip_vision_encoder="ViT-B/32" \
--save_path="/restricted/projectnb/batmanlab/shawn24/PhD/Ladder/out/Waterbirds/resnet_sup_in1k_attrNo/Waterbirds_ERM_hparams0_seed{}" \
--prompt_sent_type="captioning" \
--captioning_type="gpt-4o" \
--prompt_csv="/restricted/projectnb/batmanlab/shawn24/PhD/Ladder/data/waterbirds/va_metadata_waterbirds_captioning_GPT.csv"python ./src/codebase/learn_aligner.py \
--seed=0 \
--epochs=30 \
--dataset="Waterbirds" \
--save_path="/restricted/projectnb/batmanlab/shawn24/PhD/Ladder/out/Waterbirds/resnet_sup_in1k_attrNo/Waterbirds_ERM_hparams0_seed{0}/clip_img_encoder_ViT-B/32" \
--clf_reps_path="/restricted/projectnb/batmanlab/shawn24/PhD/Ladder/out/Waterbirds/resnet_sup_in1k_attrNo/Waterbirds_ERM_hparams0_seed{0}/clip_img_encoder_ViT-B/32/{1}_classifier_embeddings.npy" \
--clip_reps_path="/restricted/projectnb/batmanlab/shawn24/PhD/Ladder/out/Waterbirds/resnet_sup_in1k_attrNo/Waterbirds_ERM_hparams0_seed{0}/clip_img_encoder_ViT-B/32/{1}_clip_embeddings.npy"python ./src/codebase/discover_error_slices.py \
--seed=0 \
--topKsent=200 \
--dataset="Waterbirds" \
--save_path="/restricted/projectnb/batmanlab/shawn24/PhD/Ladder/out/Waterbirds/resnet_sup_in1k_attrNo/Waterbirds_ERM_hparams0_seed{}/clip_img_encoder_ViT-B/32" \
--clf_results_csv="/restricted/projectnb/batmanlab/shawn24/PhD/Ladder/out/Waterbirds/resnet_sup_in1k_attrNo/Waterbirds_ERM_hparams0_seed{}/clip_img_encoder_ViT-B/32/test_additional_info.csv" \
--clf_image_emb_path="/restricted/projectnb/batmanlab/shawn24/PhD/Ladder/out/Waterbirds/resnet_sup_in1k_attrNo/Waterbirds_ERM_hparams0_seed{}/clip_img_encoder_ViT-B/32/test_classifier_embeddings.npy" \
--language_emb_path="/restricted/projectnb/batmanlab/shawn24/PhD/Ladder/out/Waterbirds/resnet_sup_in1k_attrNo/Waterbirds_ERM_hparams0_seed{}/clip_img_encoder_ViT-B/32/sent_emb_captions_gpt-4o.npy" \
--sent_path="/restricted/projectnb/batmanlab/shawn24/PhD/Ladder/out/Waterbirds/resnet_sup_in1k_attrNo/Waterbirds_ERM_hparams0_seed{}/clip_img_encoder_ViT-B/32/sentences_captions_gpt-4o.pkl" \
--aligner_path="/restricted/projectnb/batmanlab/shawn24/PhD/Ladder/out/Waterbirds/resnet_sup_in1k_attrNo/Waterbirds_ERM_hparams0_seed{}/clip_img_encoder_ViT-B/32/aligner_30.pth"python ./src/codebase/validate_error_slices_w_LLM.py \
--seed=0 \
--LLM="gpt-4o" \
--dataset="Waterbirds" \
--class_label="landbirds" \
--clip_vision_encoder="ViT-B/32" \
--key="<open-ai key>" \
--top50-err-text="/restricted/projectnb/batmanlab/shawn24/PhD/Ladder/out/Waterbirds/resnet_sup_in1k_attrNo/Waterbirds_ERM_hparams0_seed{}/clip_img_encoder_ViT-B/32/landbirds_error_top_200_sent_diff_emb.txt" \
--save_path="/restricted/projectnb/batmanlab/shawn24/PhD/Ladder/out/Waterbirds/resnet_sup_in1k_attrNo/Waterbirds_ERM_hparams0_seed{}/clip_img_encoder_ViT-B/32" \
--clf_results_csv="/restricted/projectnb/batmanlab/shawn24/PhD/Ladder/out/Waterbirds/resnet_sup_in1k_attrNo/Waterbirds_ERM_hparams0_seed{}/clip_img_encoder_ViT-B/32/{}_additional_info.csv" \
--clf_image_emb_path="/restricted/projectnb/batmanlab/shawn24/PhD/Ladder/out/Waterbirds/resnet_sup_in1k_attrNo/Waterbirds_ERM_hparams0_seed{}/clip_img_encoder_ViT-B/32/{}_classifier_embeddings.npy" \
--aligner_path="/restricted/projectnb/batmanlab/shawn24/PhD/Ladder/out/Waterbirds/resnet_sup_in1k_attrNo/Waterbirds_ERM_hparams0_seed{}/clip_img_encoder_ViT-B/32/aligner_30.pth"python ./src/codebase/mitigate_error_slices.py \
--seed=0 \
--epochs=9 \
--lr=0.001 \
--weight_decay=0.0001 \
--n=600 \
--mode="last_layer_finetune" \
--dataset="Waterbirds" \
--classifier="resnet_sup_in1k" \
--slice_names="/restricted/projectnb/batmanlab/shawn24/PhD/Ladder/out/Waterbirds/resnet_sup_in1k_attrNo/Waterbirds_ERM_hparams0_seed{}/clip_img_encoder_ViT-B/32/{}_prompt_dict.pkl" \
--classifier_check_pt="/restricted/projectnb/batmanlab/shawn24/PhD/Ladder/out/Waterbirds/resnet_sup_in1k_attrNo/Waterbirds_ERM_hparams0_seed{}/model.pkl" \
--save_path="/restricted/projectnb/batmanlab/shawn24/PhD/Ladder/out/Waterbirds/resnet_sup_in1k_attrNo/Waterbirds_ERM_hparams0_seed{}/clip_img_encoder_ViT-B/32" \
--clf_results_csv="/restricted/projectnb/batmanlab/shawn24/PhD/Ladder/out/Waterbirds/resnet_sup_in1k_attrNo/Waterbirds_ERM_hparams0_seed{}/clip_img_encoder_ViT-B/32/{}_{}_dataframe_mitigation.csv" \
--clf_image_emb_path="/restricted/projectnb/batmanlab/shawn24/PhD/Ladder/out/Waterbirds/resnet_sup_in1k_attrNo/Waterbirds_ERM_hparams0_seed{}/clip_img_encoder_ViT-B/32/{}_classifier_embeddings.npy"
Refer to notebook1 and notebook2 for qualitative results of the error slices discovered by LADDER.
We provide runnable shell scripts to replicate the full LADDER pipeline across all datasets:
If you find this work useful, please cite our paper:
@article{ghosh2024ladder,
title={LADDER: Language Driven Slice Discovery and Error Rectification},
author={Ghosh, Shantanu and Syed, Rayan and Wang, Chenyu and Poynton, Clare B and Visweswaran, Shyam and Batmanghelich, Kayhan},
journal={arXiv preprint arXiv:2408.07832},
year={2024}
}Licensed under the Creative Commons Attribution 4.0 International
Copyright Β© Batman Lab, 2025
For any queries, contact Shantanu Ghosh (email: shawn24@bu.edu)
Did you try some other classifier on a new dataset and want to report the results? Feel free to send a pull request.