BiomedCLIP fine-tuned on PMC-PaIR for medical image retrieval

This repository holds two checkpoints of BiomedCLIP fine-tuned on the training partition of PMC-PaIR, a dataset of 86,144 pairs of clinically similar medical images from PubMed Central case reports. Both produce 512-dimensional image embeddings for retrieving images that show the same imaging modality, anatomical region and type of abnormality as a query image.

Checkpoint Query Contents
image_to_image.safetensors an image (image-only retrieval, i2i) image encoder
image_text_to_image.safetensors an image and short descriptions of the finding of interest (image-plus-text retrieval, (i+t)2i) image and text encoders
  • Dataset: dhtandguy21/PMC-PaIR; version of record at Zenodo, doi:10.5281/zenodo.23439169
  • Code: pmc-pair-retrieval (training, evaluation and saved per-query results)
  • Base model: microsoft/BiomedCLIP-PubMedBERT_256-vit_base_patch16_224, revision 9f341de24bfb00180f1b847274256e9b65a3a32e
  • Paper: a data descriptor is under review; this card will link it when it is available
  • License: MIT

These are research checkpoints. They have not been validated for clinical decision-making.

Files

File Size Contents
image_to_image.safetensors 345 MB i2i checkpoint: the image encoder (model.visual), 151 tensors
image_text_to_image.safetensors 784 MB (i+t)2i checkpoint: the full model, 351 tensors
image_to_image.json, image_text_to_image.json 2.5 kB, 2.6 kB training configuration, selected epoch, validation metrics and checksums of each checkpoint
config.json 1.8 kB base model, preprocessing and checkpoint list, read by the code below
LICENSE 2.5 kB MIT license of the weights, with Microsoft's license notice for BiomedCLIP

The two weight files are the files attached to release v1.0.3 of the retrieval repository.

SHA-256 checksums:

cb24963bcb0ddba73a1d7e4a1a4539933b05ee9b8bf8d8f3454ca5c7c9949622  image_to_image.safetensors
4d159e28b2ab1621e463bc3be8aab907356b83536d0ac9698620f32dabd54292  image_text_to_image.safetensors

How to use

The checkpoints are loaded into BiomedCLIP built with open_clip. They are not transformers models.

pip install open_clip_torch transformers torchvision safetensors huggingface_hub pillow

Load a checkpoint

import json

import open_clip
import torch
import torch.nn.functional as F
import torchvision.transforms as T
import torchvision.transforms.functional as TF
from huggingface_hub import hf_hub_download
from PIL import Image
from safetensors.torch import load_file

REPO = "dhtandguy21/PMC-PaIR-BiomedCLIP"

with open(hf_hub_download(REPO, "config.json"), encoding="utf-8") as f:
    cfg = json.load(f)

model, _, _ = open_clip.create_model_and_transforms(cfg["open_clip_model"])
tokenizer = open_clip.get_tokenizer(cfg["open_clip_model"])


def load_checkpoint(name):
    """name: "image_to_image" or "image_text_to_image"."""
    checkpoint = cfg["checkpoints"][name]
    state = load_file(hf_hub_download(REPO, checkpoint["file"]))
    # The image-only checkpoint holds the image encoder; the other holds the full model.
    target = model.visual if checkpoint["kind"] == "vision_tower" else model
    target.load_state_dict(state, strict=True)
    model.eval()


load_checkpoint("image_to_image")

Embed images

Both checkpoints were trained and evaluated with three views per image. The image is resized so that its shorter side is 224 pixels, and three 224 × 224 crops are taken at the start, center and end of its longer side, which covers wide and multi-panel figures. The three view embeddings are L2-normalized, averaged and normalized again.

pre = cfg["preprocessing"]
SIZE = pre["image_size"]
normalize = T.Normalize(pre["mean"], pre["std"])


def three_views(image):
    image = image.convert("RGB")
    image = TF.resize(image, SIZE, interpolation=T.InterpolationMode.BICUBIC, antialias=True)
    width, height = image.size
    views = []
    for fraction in pre["view_fractions"]:
        offset = int(round(fraction * (max(width, height) - SIZE)))
        if width >= height:
            box = (offset, 0, offset + SIZE, SIZE)
        else:
            box = (0, offset, SIZE, offset + SIZE)
        views.append(normalize(TF.to_tensor(image.crop(box))))
    return torch.stack(views)


@torch.no_grad()
def embed_images(paths):
    x = torch.stack([three_views(Image.open(p)) for p in paths])  # [N, 3, 3, 224, 224]
    z = model.encode_image(x.flatten(0, 1))                       # [N * 3, 512]
    z = F.normalize(z.float(), dim=1).view(len(paths), 3, -1).mean(dim=1)
    return F.normalize(z, dim=1)                                  # [N, 512], unit length


query = embed_images(["query.jpg"])
candidates = embed_images(["a.jpg", "b.jpg", "c.jpg"])
scores = query @ candidates.T                                     # cosine similarities, [1, 3]

Image-plus-text queries

Load the full model and add the text score. A description follows the template "{diagnosis} in the {anatomy} on {modality}." If a query has several descriptions, their unit embeddings are averaged without renormalizing.

load_checkpoint("image_text_to_image")


@torch.no_grad()
def embed_texts(descriptions):
    z = model.encode_text(tokenizer(descriptions))
    return F.normalize(z.float(), dim=1)


description = cfg["text"]["description_template"].format(
    diagnosis="paraspinal abscess with spinal epidural abscess",
    anatomy="lumbar spine/paraspinal muscles/epidural space",
    modality="MRI",
)
query = embed_images(["query.jpg"])
candidates = embed_images(["a.jpg", "b.jpg", "c.jpg"])
text = embed_texts([description]).mean(dim=0, keepdim=True)
scores = query @ candidates.T + text @ candidates.T

Notes:

  • open_clip downloads the current revision of the base model. The checkpoints were fine-tuned from the revision given above, and the retrieval repository shows how to pin it. The image-only checkpoint replaces the whole image encoder and leaves the text encoder at its pretrained weights. The other checkpoint replaces all weights.
  • The reported results were computed on a GPU under bfloat16 autocast with the library versions listed below. Other settings give slightly different embeddings.
  • To reproduce the benchmark, use the evaluation command of the retrieval repository, which also applies the candidate exclusions described under Evaluation.

Training

Data

The models were fine-tuned on the training partition of PMC-PaIR (70,552 images in 70,262 positive pairs), and checkpoints were selected on the validation partition (8,245 images). No pair and no source article spans two partitions. In both tasks, the eligible negatives of a training image are the images that are not linked to it, directly or indirectly, through positive pairs.

Training and evaluation used the complete partitions, including the 68 images whose files are withheld from the public dataset (60 training, 3 validation and 5 test images). The image-only run used 70,549 of the training images, after a filter for pixel-identical copies of validation images removed three.

Procedure

Setting i2i (i+t)2i
Text input none pair descriptions of up to 256 tokens
Trained parameters image encoder, with layer-wise learning-rate decay of 0.75; text encoder frozen text encoder, and image encoder except its first eight transformer blocks
Loss InfoNCE, temperature 0.10 image–image (weight 0.3) and image–text (weight 0.6) triplet-ranking losses, margin 0.09, over the mean score of up to four highest-scoring eligible negatives
Negatives eligible images in the batch images and descriptions in the batch; batches assembled with mined hard negatives
Augmentation crop jitter, brightness and contrast jitter, rotation of up to 5° crop jitter
Batch size 128 anchor–positive pairs 128 image pairs
Peak learning rate; weight decay 6 × 10⁻⁶; 0.05 1 × 10⁻⁶; 0.2
Epochs 12 at most 30, with early stopping after three epochs without improvement
Selected checkpoint (seed 42) epoch 11 epoch 21 (training stopped after epoch 24)
Validation Recall@10 at selection 19.55% 30.87%

Both models use three 224 × 224 crops per image, the AdamW optimizer, bfloat16 mixed precision, gradient clipping at 1.5, and 200 warm-up steps followed by cosine learning-rate decay scheduled over the maximum number of epochs. Checkpoints were selected by validation Recall@10. The hard negatives of the (i+t)2i model are images that pretrained BiomedCLIP rates as similar to a training image but that belong to a different connected component and a different source article.

The .json file beside each checkpoint records its full configuration, and configs/ in the retrieval repository documents every setting.

Software and hardware

Python 3.11.10, PyTorch 2.7.1 with CUDA 12.6, torchvision 0.22.1, open_clip_torch 3.1.0, timm 1.0.19, transformers 4.55.2 and safetensors 0.4.5, on one NVIDIA L40S GPU with 48 GB of memory. Training on a GPU is not bitwise reproducible.

Evaluation

Each of the 8,096 images of the PMC-PaIR test partition serves once as a query. Its candidates are all other test images except those linked to it only indirectly, through other positive pairs in its connected component. The images paired with the query are the relevant results. In (i+t)2i, the query image is accompanied by the descriptions of its positive pairs, and candidates are ranked by the unweighted sum of the image similarity and the mean similarity between the candidate image and the query's distinct descriptions. Each fine-tuned model is compared with pretrained BiomedCLIP queried in the same way.

Recall@k is the mean fraction of a query's positives among the k highest-ranked candidates, Hit@k is the proportion of queries with at least one positive among them, and MRR is the mean reciprocal rank of the first positive.

Test partition (8,096 queries)

Task Model Recall@1 Recall@5 Recall@10 Recall@100 Hit@10 mAP nDCG MRR Median rank of first positive
i2i pretrained 3.32 9.57 14.62 47.71 21.47 8.22 24.11 0.1105 65
i2i fine-tuned 4.31 12.91 20.15 60.03 28.31 10.89 27.65 0.1434 37
(i+t)2i pretrained 4.87 13.99 20.53 60.08 29.68 11.59 28.30 0.1541 34
(i+t)2i fine-tuned 7.46 21.19 31.62 76.33 42.98 17.13 34.59 0.2196 15

Recall@k, Hit@10, mAP and nDCG are percentages.

Task Metric Fine-tuned minus pretrained (95% CI)
i2i Recall@10 5.53 (4.61 to 6.55)
i2i Hit@10 6.84 (5.73 to 8.09)
(i+t)2i Recall@10 11.09 (9.89 to 12.38)
(i+t)2i Hit@10 13.30 (12.07 to 14.66)

Differences are in percentage points. The confidence intervals come from a cluster bootstrap that resamples whole test article groups 5,000 times.

On the validation partition (8,245 queries), Recall@10 rises from 14.50% to 19.55% for i2i and from 20.44% to 30.87% for (i+t)2i.

Among the 44 modality, anatomy and diagnosis categories with at least 140 test queries from at least 20 article groups, Hit@10 is higher for the fine-tuned model in every category in both tasks, and the 95% confidence interval of the difference excludes zero in 40 categories for i2i and in all 44 for (i+t)2i.

Across training seeds 42, 43 and 44, test Recall@10 is 20.11 ± 0.07% for i2i and 31.57 ± 0.04% for (i+t)2i (mean ± s.d.). The released checkpoints are those of seed 42.

A board-certified radiologist reviewed the five highest-ranked candidates of the fine-tuned (i+t)2i model for 17 test queries with CT and heart or vasculature labels. At least one of the five matched the query in modality and in anatomy for all 17 queries, in diagnosis for 12, and in all three for 11.

With the public dataset files, the 5 withheld test images and their pairs are unavailable. The retrieval code then evaluates 8,088 test queries, and the metrics differ slightly from those above. The reported results can be recomputed from the per-query results saved in the retrieval repository.

Intended use and limitations

The checkpoints were developed for research on medical image retrieval and for reproducing the results above.

  • Not for clinical use. The checkpoints have not been validated for clinical decision-making or deployment. The BiomedCLIP model card limits the intended use of the base model to research and states that deployed use is out of scope.
  • What the metrics measure. Relevance is defined by the positive pairs of PMC-PaIR, which were derived from figure captions and case text, not from image pixels. The metrics measure how well a model retrieves the annotated positives, not all clinically similar images.
  • Text at query time. The (i+t)2i checkpoint assumes that a description of the finding of interest is available with the query. In the evaluation, the descriptions come from the pair annotations of the query image.
  • Training images. The models were trained on figures from case reports. Many are compound figures or carry arrows, letters and other marks added by the authors. CT, MRI and radiography account for most images, and case reports often describe rare or atypical presentations.
  • Overlap with pretraining data. BiomedCLIP was pretrained on 15 million figure–caption pairs from PubMed Central, and may have encountered PMC-PaIR images during pretraining. The pretrained and fine-tuned models in each comparison above start from the same pretrained weights.
  • Pixel-identical images. Two groups of pixel-identical images span the training and validation partitions. None spans the test partition and another partition.

License

The weights and their metadata files are released under the MIT license in LICENSE, which also keeps Microsoft's copyright and license notice for BiomedCLIP. The license covers the weights to the extent of the authors' rights and grants no rights in the training images, which keep the terms recorded for each image in licenses.csv of the dataset.

Citation

Please cite the dataset and BiomedCLIP. A data descriptor is under review, and its reference will be added here.

@dataset{shmueli_pmc_pair_2026,
  author    = {Shmueli, Guy and Hope, Tom},
  title     = {{PMC-PaIR}: Clinically similar medical image pairs from {PubMed Central} case reports},
  year      = {2026},
  publisher = {Zenodo},
  version   = {v1},
  doi       = {10.5281/zenodo.23439169},
  url       = {https://doi.org/10.5281/zenodo.23439169}
}

@article{zhang_biomedclip_2025,
  author  = {Zhang, Sheng and Xu, Yanbo and Usuyama, Naoto and others},
  title   = {A Multimodal Biomedical Foundation Model Trained from Fifteen Million Image--Text Pairs},
  journal = {NEJM AI},
  volume  = {2},
  number  = {1},
  year    = {2025},
  doi     = {10.1056/AIoa2400640}
}

The training and evaluation code is archived at Zenodo: doi:10.5281/zenodo.24305019.

Contact

Open a discussion in the Community tab of this repository or an issue in the retrieval repository.

Downloads last month
-
Inference Providers NEW
This model isn't deployed by any Inference Provider. 🙋 Ask for provider support

Model tree for dhtandguy21/PMC-PaIR-BiomedCLIP

Dataset used to train dhtandguy21/PMC-PaIR-BiomedCLIP