Metadata-Version: 2.4
Name: ladder-slices
Version: 0.1.0
Summary: LADDER: language-driven slice discovery and error rectification in vision classifiers
Author: Batman Lab
License-Expression: CC-BY-4.0
Project-URL: Homepage, https://github.com/batmanlab/Ladder
Project-URL: Documentation, https://github.com/batmanlab/Ladder/blob/main/docs/python-package.md
Project-URL: Checkpoints, https://huggingface.co/shawn24/Ladder
Project-URL: Issues, https://github.com/batmanlab/Ladder/issues
Keywords: LADDER,slice-discovery,vision,model-debugging
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE.txt
Requires-Dist: numpy<3,>=1.24
Requires-Dist: torch<3,>=2.6
Requires-Dist: huggingface-hub<1,>=0.27
Requires-Dist: Pillow<13,>=10
Provides-Extra: vision
Requires-Dist: torchvision<1,>=0.21; extra == "vision"
Requires-Dist: transformers<5,>=4.48; extra == "vision"
Requires-Dist: efficientnet-pytorch<0.8,>=0.7.1; extra == "vision"
Requires-Dist: omegaconf<3,>=2.3; extra == "vision"
Provides-Extra: openai
Requires-Dist: openai<3,>=1.68; extra == "openai"
Provides-Extra: anthropic
Requires-Dist: anthropic<1,>=0.49; extra == "anthropic"
Provides-Extra: gemini
Requires-Dist: google-genai<2,>=1; extra == "gemini"
Provides-Extra: all
Requires-Dist: torchvision<1,>=0.21; extra == "all"
Requires-Dist: transformers<5,>=4.48; extra == "all"
Requires-Dist: efficientnet-pytorch<0.8,>=0.7.1; extra == "all"
Requires-Dist: omegaconf<3,>=2.3; extra == "all"
Requires-Dist: openai<3,>=1.68; extra == "all"
Requires-Dist: anthropic<1,>=0.49; extra == "all"
Requires-Dist: google-genai<2,>=1; extra == "all"
Provides-Extra: dev
Requires-Dist: build>=1.2; extra == "dev"
Requires-Dist: twine>=6; extra == "dev"
Dynamic: license-file

# LADDER Python package

`ladder-slices` provides the six stages of [LADDER](https://github.com/batmanlab/Ladder): image embeddings, text embeddings, classifier-to-language alignment, sentence retrieval, LLM hypothesis generation and slice validation, and balanced last-layer retraining. Select a dataset and classifier architecture; the package resolves the released Hugging Face classifier and matching vision-language encoder. Imports do not download models or contact an LLM.

## Installation

Python 3.10+ and PyTorch 2.6+ are required. From a checkout containing this package:

```bash
python -m pip install '.[vision,openai]'
```

For Anthropic or Gemini, replace `openai` with `anthropic` or `gemini`. `.[all]` installs all adapters. Install the PyTorch/torchvision build appropriate for your CPU/CUDA environment before installing the package.

After version 0.1.0 is published to PyPI, the equivalent command will be:

```bash
python -m pip install 'ladder-slices[vision,openai]'
```

The import name is `ladder_slices`; the command is `ladder`. The unrelated PyPI names `ladder` and `ladder-ai` are already occupied. No model weights, private data, credentials, or research output directories are included in the wheel.

## Python API

```python
import os
from ladder_slices import Ladder

pipeline = Ladder(
    dataset="Waterbirds",
    architecture="resnet50",
    llm="openai",
    llm_model="gpt-4o",
    api_key=os.environ["OPENAI_API_KEY"],
    device="cuda",
)
result = pipeline.run("outputs/waterbirds-001")
print(result["test_baseline_accuracy"], result["test_mitigated_accuracy"])
```

This downloads the released training/validation representations and sentence bank, fits an aligner, retrieves explanations from validation errors, asks the specified LLM for hypotheses, validates the hypotheses, and retrains the original classifier's final layer. It then evaluates the fitted heads on the separate published test representations. The model weights, tokenizer and encoder configuration are downloaded into the Hugging Face cache as needed. The default run reuses already extracted image representations; use a manifest to recompute them from images.

The generated prompt contains the dataset, target class and retrieved sentences. It does not include images, per-example IDs or prediction tables. Keys are read from the argument/environment and are excluded from serialized results. Choose a provider appropriate for your sentence corpus; a callable can connect an institutional or local LLM. No paid LLM requests are made by installation or import.

```python
# Fresh extraction from local images, followed by all downstream stages:
result = pipeline.run(
    "outputs/waterbirds-local-001",
    manifest="samples.csv",
    sentences="sentences.json",  # optional override of the released sentence bank
    batch_size=8,
)

# Reuse validated hypotheses without an LLM key:
offline = Ladder("Waterbirds", "resnet50", local_files_only=True)
result = offline.run("outputs/reused-001", hypotheses="outputs/waterbirds-001/hypotheses.json")
```

`local_files_only=True` requires all selected assets to be cached; it does not disable a separately configured LLM. Reusing a hypotheses file requires no LLM client. Outputs go into a new directory; existing directories are rejected. A failed run never writes `complete.json`.

## Released dataset/model combinations

| Dataset | Architecture | Language-image encoder | Target classes analyzed |
| --- | --- | --- | --- |
| Waterbirds | `resnet_sup_in1k` (`resnet50` alias) | CLIP ViT-B/32 | landbirds, waterbirds |
| CelebA | `resnet_sup_in1k` (`resnet50` alias) | CLIP ViT-B/32 | blonde |
| MetaShift | `resnet_sup_in1k` (`resnet50` alias) | CLIP ViT-B/32 | dog, cat |
| NIH | `resnet50` | released CXR-CLIP Swin-Tiny | pneumothorax |
| RSNA | `efficientnet-b5` | released Mammo-CLIP B5 | cancer |
| ViNDr | `efficientnet-b5` | released Mammo-CLIP B5 | abnormal |

`RSNA-Mammo`, `VinDr-Mammo`, and `NIH-CXR` are accepted aliases. `tf_efficientnet_b5_ns-detect` aliases the released EfficientNet-B5 classifier. The registry covers the six released classifier pairs, not every architecture evaluated in the paper. An unsupported pair raises an error and is never replaced with another model.

The checkpoints and arrays come from [shawn24/Ladder](https://huggingface.co/shawn24/Ladder/tree/93b794d81a52b966acebeea064e264bbd92f216d). Registry revisions pin the classifier, medical encoders, CLIP, and tokenizer/config sources. In particular, RSNA uses `efficientnetb5_seed_10_best_aucroc0.89_ver084.pth` for classification and `b5-model-best-epoch-7.tar` for Mammo-CLIP. NIH's historical whole-module checkpoint is decoded using an explicit compatibility allowlist. State dictionaries are loaded strictly; missing trained parameters do not fall back to random or generic pretrained weights.

Use `available_models()` for exact filenames and revisions. `pipeline.classifier()`, `pipeline.encoder()`, `pipeline.embeddings(images)` and `pipeline.text_embeddings(sentences)` expose individual loading/extraction operations.

## Local dataset inputs

HF supplies model weights and cached intermediate representations, not the raw images. A local CSV or JSON manifest makes row order and split membership explicit:

```csv
id,image,label,split
train-001,images/train-001.jpg,0,train
train-002,images/train-002.jpg,1,train
valid-001,images/valid-001.jpg,0,valid
valid-002,images/valid-002.jpg,1,valid
test-001,images/test-001.jpg,1,test
```

This illustrates the schema, not a sufficient training cohort. Supply both classes and enough validation samples for correct/incorrect examples and balanced retraining. Labels must be 0/1, and IDs and image paths must be unique across splits. Relative image paths resolve against the manifest directory. Dataset splits, patient grouping and labels remain the dataset owner's responsibility. `train` and `valid` are required; `test` is optional. `val` and `validation` alias `valid`.

Natural-image evaluation preprocessing matches the original dataset-specific transforms. NIH uses resize/center crop to 224 and ImageNet normalization. Mammograms must already be processed RGB/grayscale PNGs of width 912 and height 1520; the package applies the original per-image min/max scaling and mammography normalization. It does not convert DICOMs. Both the classifier and matched language-image encoder receive the same tensor, preserving the original extraction contract. Fresh train extraction is deterministic and includes every manifest row; it does not apply the research loader's random training augmentation or drop its final batch.

`sentences.json` is a JSON array of strings. A `.txt` file contains one candidate sentence per line. Waterbirds/CelebA/MetaShift default to the released GPT-caption embeddings; NIH defaults to its released sentence embeddings. RSNA/ViNDr default to the synthetic [Mammo-FActOR prompts](https://github.com/batmanlab/Mammo-CLIP/blob/main/src/codebase/breastclip/data/datasets/prompts.json) bundled from this repository. Their original full report sentence banks were not published in the HF release; supply your own authorized corpus to reproduce that choice. The selected source is recorded in `run.json`.

## LLM selection

| `llm` | Key environment variable | Additional input |
| --- | --- | --- |
| `openai` | `OPENAI_API_KEY` | explicit `llm_model` |
| `anthropic` | `ANTHROPIC_API_KEY` | explicit `llm_model` |
| `gemini` | `GEMINI_API_KEY` | explicit `llm_model` |
| `openai-compatible` | `LLM_API_KEY` | `llm_model` and `base_url` |

For a hosted Llama or another compatible deployment:

```python
pipeline = Ladder("Waterbirds", "resnet50", llm="openai-compatible",
                  llm_model="your-deployment", api_key=os.environ["LLM_API_KEY"],
                  base_url="https://your-provider.example/v1")
```

Model identifiers are explicit because provider availability changes. Compatible endpoints must support chat completions with JSON-object output. The built-in OpenAI adapter uses the [Responses API with structured JSON](https://developers.openai.com/api/docs/guides/structured-outputs), while [Anthropic](https://github.com/anthropics/anthropic-sdk-python) and [Gemini](https://googleapis.github.io/python-genai/) use their SDKs. Responses are validated as JSON, never executed as code. Refusals, incomplete responses and malformed hypotheses fail the run.

To use another provider, pass `llm=generate`, where `generate(prompt)` returns this object or its JSON string:

```json
{"hypotheses": [{"name": "H1", "description": "Possible background bias", "prompts": ["A bird on water.", "A bird beside a lake."]}]}
```

Saved `hypotheses.json` groups these objects by numeric class string, such as `"0"` and `"1"`. Provider model choices and package updates can change hypotheses; bitwise reproduction of historical LLM responses is not promised.

## Algorithm and evaluation behavior

The array API exposes `LinearAligner`, `retrieve`, `discover`, `mitigate`, and `Mitigator` for existing embeddings. Shapes are checked before use. Retrieval preserves the published **mean correct minus mean incorrect** direction and dot-product scoring; a class with no correct or no incorrect validation examples cannot produce a meaningful direction and raises an error. Prompt vectors are averaged before final normalization. Alignment preserves the original SGD hyperparameters, validation checkpoint selection and legacy bias scaling by default; the low-level fit method offers `legacy_bias_scaling=False` for exact inverse scaling.

The package intentionally corrects two mitigation behaviors: each class contributes its own high/low-scoring examples, with no overlap within a hypothesis, and inference routes by hypothesis similarity without consulting ground-truth class labels. The original script's class-0 bottom-selection typo and label-dependent ensemble routing are not reproduced. This is a portable implementation of the method, not a claim of identical paper metrics.

Alignment uses training pairs and validation selection. Retrieval, hypothesis thresholds and head fitting use validation data. Test labels are used only for evaluation after fitting. Validation accuracy after mitigation is explicitly labeled training accuracy. The package reports overall and per-slice accuracy; it does not infer missing protected attributes or claim a worst-group metric without them.

## Outputs

Each successful run writes:

- `train_embeddings.npz`, `valid_embeddings.npz`: classifier/VLM features, labels, predictions, probabilities and row IDs.
- `sentences.json`, `text_embeddings.npy`, `retrieval.json`: candidate text and ranked evidence.
- `aligner.npz`, `hypotheses.json`, `slices.npz`, `validation_slices.json`: alignment and validation slice definitions.
- `mitigator.npz`: one trained final layer per hypothesis.
- `test_predictions.npz`, `test_slices.json`: separate test outputs, when requested and available.
- `run.json`: model provenance, settings, cohort sizes, and metrics; no API keys.
- `complete.json`: written last, with SHA-256 hashes of completed artifacts.

For inference from cached classifier features:

```python
import numpy as np
from ladder_slices import LinearAligner, Mitigator

aligner = LinearAligner.load("outputs/waterbirds-001/aligner.npz")
head = Mitigator.load("outputs/waterbirds-001/mitigator.npz")
with np.load("outputs/waterbirds-001/slices.npz") as slices:
    scores = aligner.transform(features) @ slices["prompt_embeddings"].T
probabilities = head.predict_proba(features, scores)  # shape (images, 2), no labels required
```

## CLI

The following commands assume `ladder` is already available in the active environment.

```bash
# Inspect the registered dataset/architecture combinations:
ladder models

# Run with the published HF representations and an explicit LLM:
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

# Recompute image embeddings from a local manifest:
ladder run \
  --dataset Waterbirds --architecture resnet50 \
  --manifest ./samples.csv --sentences ./sentences.json \
  --llm openai --llm-model gpt-4o --api-key-env OPENAI_API_KEY \
  --device cuda --output-dir ./outputs/waterbirds-local-001

# Cache all assets before an offline run (medical encoders can be large):
ladder download --dataset Waterbirds --architecture resnet50 --assets all

# Reuse hypotheses and cached assets without an LLM request:
ladder run --dataset Waterbirds --architecture resnet50 --offline \
  --hypotheses ./outputs/waterbirds-001/hypotheses.json \
  --output-dir ./outputs/waterbirds-reuse-001

# Success: JSON summary on stdout and complete.json in the output directory.
# Progress: stderr. Failure: nonzero exit status and no completion marker.
```

Use `ladder run --help` for training epochs, batch size, cache directory, seed, top-K retrieval, and test-evaluation controls. Package build and release instructions are in [package-release.md](https://github.com/batmanlab/Ladder/blob/main/docs/package-release.md).
