Skip to main content

mammofm Python package

Local, single-image inference with Mammo-FM. This first package provides mammofm.diagnosis and mammofm.features. Prognosis and report generation are not exposed by this release; use the repository's separate workflows for now.

Research only. Outputs are uncalibrated model scores, not clinical diagnoses or validated patient-level disease probabilities. Read the repository's LICENSE.txt and LICENSE_WEIGHTS.txt; packaging does not change their terms. Images stay on your machine. The package has no report-generation API key, telemetry, image upload, or remote inference service.

Contents

Installation

Python 3.10+ and PyTorch 2.6+ are required. CPU inference is supported; a compatible CUDA-enabled PyTorch installation is recommended for repeated inference. Install the appropriate PyTorch build for your machine before installing this package.

From the repository root, before the first PyPI publication:

python -m pip install .
# Include decoders for compressed mammography DICOMs:
python -m pip install '.[dicom]'

The distribution name is mammofm. Once the maintainer publishes it to PyPI, users can run:

python -m pip install 'mammofm[dicom]'
# For preprocessed PNGs and uncompressed DICOMs only:
python -m pip install mammofm

These are the intended public installation commands, not a claim that a PyPI release has already been published. No model weights or patient data are bundled in the wheel or source distribution.

On a shared CPU host with a low process/thread limit, set these before starting Python to bound numerical and tokenizer worker pools:

export OMP_NUM_THREADS=2 MKL_NUM_THREADS=2 OPENBLAS_NUM_THREADS=2
export TOKENIZERS_PARALLELISM=false TORCHINDUCTOR_COMPILE_THREADS=1

You can additionally set cv2.setNumThreads(2) in your application. The package does not change process-wide thread settings. The latter PyTorch setting avoids an import-time compiler worker pool in some Transformers versions even though Mammo-FM uses eager, noncompiled inference.

Diagnosis

import json
import mammofm as mf

output = mf.diagnosis('/data/mammogram.dcm', 'vindr')
print(json.dumps(output, indent=2, allow_nan=False))

# A preprocessed PNG uses the same API.
output = mf.diagnosis('/data/mammogram.png', 'nlbreast')

output is a Python dictionary that can be directly serialized to JSON. Its top-level prediction groups are zero_shot, linear_probe, and full_finetune. Each maps task names to positive-class probabilities (Python floats) or None (null in JSON) when that specific model has not been released.

output['zero_shot']['mass']
output['linear_probe']['mass']
output['full_finetune']['mass']
output['unavailable']  # Reasons for unavailable fields; never substitute zeros.
output['metadata']     # Input processing, pinned checkpoint identities, semantics.

Only binary positive-class scores are returned, not hard labels or a clinical threshold. Classifiers use sigmoid. Zero-shot preserves the official evaluator: normalize individual projected prompt embeddings, average within negative and positive classes, compute cosine similarity to each mean, and apply a two-class softmax. The checkpoint's learned logit scale is not multiplied into these scores, matching the original evaluation.

To avoid unnecessary models or downloads:

output = mf.diagnosis('/data/mammogram.png', 'rsna', methods=['linear_probe'])
print(mf.availability('rsna'))  # Does not load or download any weights.

Missing published models produce a warning and explicit null fields. Use strict=True to raise MissingModelError before any model download if any requested task/method is unavailable. Download failures, invalid inputs, checkpoint mismatches, and actual inference failures always raise errors rather than masquerading as a missing model.

Supported tasks and missing models

Registry pinned to HF revision 5e07ca4c4e88cd118b0c2cfaacadddfe69f30026:

Dataset argument Task key Zero-shot Linear probe Full finetune
rsna cancer Available Available Available
rsna invasive_cancer Not released Not released Not released
vindr abnormality Available, historical surrogate Available Available
vindr mass Available Available Available
vindr suspicious_calcification Available Available Available
nlbreast cancer Available Available Available

NL-Breast aliases such as nl_breast and NL-Breast are accepted. Unknown diagnosis datasets are rejected. RSNA cancer is not an invasive-cancer substitute. CMMD and LUMINA diagnosis are deferred and rejected by this release; only RSNA, VinDr, and NL-Breast are enabled.

VinDr abnormality means BI-RADS 4/5 versus 1/2, with BI-RADS 3 excluded in evaluation. It does not mean any finding or pathology-confirmed cancer. Its historical zero-shot surrogate uses the original cancer / no cancer prompts; this limitation is also recorded in the output metadata.

Image features

import numpy as np
import mammofm as mf

output = mf.features('/data/mammogram.dcm', 'rsna')
spatial = output['before_pooling']
pooled = output['after_pooling']
print(spatial.shape)  # (1, 2048, 48, 29) at the standard image size
print(pooled.shape)   # (1, 2048)
np.savez('/outputs/image_features.npz', before_pooling=spatial, after_pooling=pooled)

# An unknown or omitted dataset uses general min-max DICOM preprocessing.
output = mf.features('/data/mammogram.png', 'my_dataset')
output = mf.features('/data/mammogram.dcm')

The arrays are full float32 CPU NumPy arrays, retaining the batch dimension. They are the final image-encoder spatial map and its global average-pooled vector, before the CLIP projection and L2 normalization. Feature arrays are not automatically converted to enormous JSON lists. metadata identifies the checkpoint and preprocessing. Use .tolist() explicitly if JSON is required.

Both feature extraction and zero-shot use the requested Mammo-FM_ASU_Trained_CLIP.tar. At this pinned revision it is byte-identical to the Batmanlab CLIP release: SHA-256 58ae959de52d563acc1d43f50571498eddcd4fb7ca599e706540fdd319e3599b. The classifier paths load their own complete released encoder+head weights; fine-tuned encoders are not replaced with the ASU encoder.

DICOM and PNG preprocessing

img is a local path to one single-frame grayscale DICOM or an already preprocessed 8-bit PNG. RGB PNGs are also accepted. Color/multiframe DICOMs, 16-bit PNGs, and transparent PNGs are rejected rather than silently altered.

Dataset DICOM intensity route
RSNA, VinDr Original CPU-style min-max scaling
NL-Breast DICOM rescale + window center/width; 1st/99th-percentile fallback
Unknown/omitted dataset in features General min-max preprocessing

DICOMs use the unified converter's five-pixel border removal, MONOCHROME1 correction, original breast-cropping heuristic, and INTER_AREA resize to 1520H x 912W. Conversion is in memory; no temporary PNG or DICOM metadata is written. PNGs skip this contrast/cropping pipeline. PNG input should already have the intended breast preprocessing; being a PNG does not establish that.

All inputs then receive the model's RGB conversion, branch-specific resize when needed (INTER_LINEAR), per-image min-max normalization and (x - 0.3089279) / 0.25053555408335154. Constant images are handled without NaNs.

All enabled branches use 1520H x 912W. For arbitrary PNG sizes, this resize is a package standardization step; the original non-CMMD loaders expected already-preprocessed PNG dimensions and did not apply it. Image preprocessing does not update detection boxes, perform anatomical segmentation or anonymize burned-in text. No patient identifiers or source paths are included in results.

The shared image operations preserve the original CPU conventions, not a guarantee of byte-identical behavior for every legacy GPU/decoder path.

Checkpoints, caching, and offline use

The first relevant inference downloads weights from the public batmanLab/Mammo-FM repository. The ASU joint checkpoint is about 2.15 GB; each classifier is downloaded separately only when requested. No HF token is required for this pinned public release.

model = mf.MammoFM(device='cuda', cache_dir='/models/huggingface')
result = model.diagnosis('/data/image.png', 'vindr')
features = model.features('/data/image.png', 'vindr')
model.clear_cache()  # Release this client's model references; keep disk cache.

For offline use, first download the published assets, preserving their HF relative paths. Then use:

model = mf.MammoFM(device='cpu', model_dir='/models/Mammo-FM', local_files_only=True)
output = model.diagnosis('/data/image.png', 'nlbreast')

The base checkpoint sits directly under model_dir; classifiers remain under linear_probe_mammo_FM_image_encoder/... and fullfinetune_mammo_FM_image_encoder/.... Zero-shot also requires config.json, tokenizer.json, tokenizer_config.json, and special_tokens_map.json under text_encoders/modernbert_mlm_5epochs/. It does not require that directory's separate MLM initialization weights: fine-tuned text weights are already in the joint CLIP checkpoint.

MAMMOFM_MODEL_DIR and MAMMOFM_CACHE_DIR provide optional environment defaults. Otherwise, downloads use the standard Hugging Face cache, not the codebase. Every asset is pinned to a revision and SHA-256 checked before loading. Model loading is strict; there is no silent random-weight or ImageNet-weight fallback.

API reference

mf.diagnosis(img, dataset, *, methods=None, strict=False, device=None,
             cache_dir=None, model_dir=None, local_files_only=False)
mf.features(img, dataset=None, *, device=None, cache_dir=None,
            model_dir=None, local_files_only=False)
mf.availability(dataset=None)
mf.clear_cache()

mf.MammoFM(*, device=None, cache_dir=None, model_dir=None,
           local_files_only=False, prompt_batch_size=32)

device=None selects CUDA when available, otherwise CPU. methods selects zero_shot, linear_probe, and/or full_finetune. All three are requested by default. A reusable client caches its encoder, CLIP model, prompt prototypes, and at most two classifier models in memory. For parallel workers, construct one client per worker; clients are not promised to be thread-safe.

Testing and publishing

Synthetic tests do not need private data, downloaded checkpoints or GPUs:

python -m unittest discover -s tests/package -p 'test_*.py'

Build and check release artifacts from a clean checkout:

python -m pip install '.[dev]'
python -m build
python -m twine check dist/*

Before publishing, inspect both archives: they must contain only the inference package, public prompts, documentation, packaging metadata and license notices. Do not include weights, images, private CSVs, test-inference artifacts, secrets, editor/assistant files, or the original training code tree. Run an installed-wheel smoke test outside the repository so accidental checkout imports cannot pass.

PyPI publication is a separate maintainer action requiring project ownership and an authenticated upload or trusted-publishing configuration. Do not embed upload tokens in the repository. Only after release review and publication:

python -m twine upload dist/*

Metadata

Release files for mammofm 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for mammofm 0.1.0
File Size Uploaded Provenance Actions
mammofm-0.1.0.tar.gz 46.1 kB Without provenance Details for mammofm-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for mammofm 0.1.0
File Interpreter ABI Platform Actions
mammofm-0.1.0-py3-none-any.whl Python 3 none any Details for mammofm-0.1.0-py3-none-any.whl

Total release size: 93.8 kB

Release files / mammofm-0.1.0.tar.gz

Download URL mammofm-0.1.0.tar.gz
Size 46.1 kB
Tags Source
SHA-256 checksum
How to use checksums
40383ec741fac269d7fc633b9197974f849ca934ef32528dec09e448976d87ac
BLAKE2b-256 checksum
How to use checksums
e33b9f6db78ad5f27f67e3626547ac35cf181ca9fa0c1ce4c259520209e3ca54
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.10.20

Release files / mammofm-0.1.0-py3-none-any.whl

Download URL mammofm-0.1.0-py3-none-any.whl
Size 47.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
55e4aab09e41724b0af30bdb96becc923bf8f4fbf23a0356ac3b07d9e98dc290
BLAKE2b-256 checksum
How to use checksums
809fe4ba6ceb76a8e4974a19dad645ff3bc24152aa977ce5e66f3e7344ad652d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.10.20

Security for mammofm 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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page