LADDER Python package
ladder-slices provides the six stages of 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:
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:
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
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.
# 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. 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:
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 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:
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, while Anthropic and Gemini 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:
{"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:
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.
# 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.
Metadata
Release files for ladder-slices 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| ladder_slices-0.1.0.tar.gz | 83.8 kB | Without provenance | Details for ladder_slices-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| ladder_slices-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for ladder_slices-0.1.0-py3-none-any.whl |
Total release size: 149.7 kB
Release files / ladder_slices-0.1.0.tar.gz
| Download URL | ladder_slices-0.1.0.tar.gz |
|---|---|
| Size | 83.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
ca99e3ec34afcc55e187eedfd01e5322dad8e497ae7c4d49e0561511e3f3e015
|
|
BLAKE2b-256 checksum How to use checksums |
8a462337c1123bb8732912c638c7c1288ed4206295e27a0653ba58e70f0e3501
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.10.20
|
Release files / ladder_slices-0.1.0-py3-none-any.whl
| Download URL | ladder_slices-0.1.0-py3-none-any.whl |
|---|---|
| Size | 65.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
0b2e19ceba2a01f5cf2f3d675310d8eb945547a09eaea872a6e53d82fef9fc1d
|
|
BLAKE2b-256 checksum How to use checksums |
03bc97d2eb2b71218ba2d0b6cb415ab0048a31d88c8fcd3fc73a7e61e958726c
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.10.20
|
Security for ladder-slices 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.