BiomedCLIP is a biomedical vision-language foundation model that is pretrained on
PMC-15M, a dataset of 15 million figure-caption pairs extracted from biomedical research articles in PubMed Central, using contrastive learning.
It uses PubMedBERT as the text encoder and Vision Transformer as the image encoder, with domain-specific adaptations.
It can perform various vision-language processing (VLP) tasks such as cross-modal retrieval, image classification, and visual question answering.
BiomedCLIP establishes new state of the art in a wide range of standard datasets, and substantially outperforms prior VLP approaches:
We have released BiomedCLIP Data Pipeline at
https://github.com/microsoft/BiomedCLIP_data_pipeline, which automatically downloads and processes a set of articles from the PubMed Central Open Access dataset.
BiomedCLIP builds upon the PMC-15M dataset, which is a large-scale parallel image-text dataset generated by this data pipeline for biomedical vision-language processing. It contains 15 million figure-caption pairs extracted from biomedical research articles in PubMed Central and covers a diverse range of biomedical image types, such as microscopy, radiography, histology, and more.
1conda create -n biomedclip python=3.10 -y
2conda activate biomedclip
3pip install open_clip_torch==2.23.0 transformers==4.35.2 matplotlib
1import torch
2from urllib.request import urlopen
3from PIL import Image
4from open_clip import create_model_from_pretrained, get_tokenizer
5
6# Load the model and config files from the Hugging Face Hub
7model, preprocess = create_model_from_pretrained('hf-hub:microsoft/BiomedCLIP-PubMedBERT_256-vit_base_patch16_224')
8tokenizer = get_tokenizer('hf-hub:microsoft/BiomedCLIP-PubMedBERT_256-vit_base_patch16_224')
9
10
11# Zero-shot image classification
12template = 'this is a photo of '
13labels = [
14 'adenocarcinoma histopathology',
15 'brain MRI',
16 'covid line chart',
17 'squamous cell carcinoma histopathology',
18 'immunohistochemistry histopathology',
19 'bone X-ray',
20 'chest X-ray',
21 'pie chart',
22 'hematoxylin and eosin histopathology'
23]
24
25dataset_url = 'https://huggingface.co/microsoft/BiomedCLIP-PubMedBERT_256-vit_base_patch16_224/resolve/main/example_data/biomed_image_classification_example_data/'
26test_imgs = [
27 'squamous_cell_carcinoma_histopathology.jpeg',
28 'H_and_E_histopathology.jpg',
29 'bone_X-ray.jpg',
30 'adenocarcinoma_histopathology.jpg',
31 'covid_line_chart.png',
32 'IHC_histopathology.jpg',
33 'chest_X-ray.jpg',
34 'brain_MRI.jpg',
35 'pie_chart.png'
36]
37device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
38model.to(device)
39model.eval()
40
41context_length = 256
42
43images = torch.stack([preprocess(Image.open(urlopen(dataset_url + img))) for img in test_imgs]).to(device)
44texts = tokenizer([template + l for l in labels], context_length=context_length).to(device)
45with torch.no_grad():
46 image_features, text_features, logit_scale = model(images, texts)
47
48 logits = (logit_scale * image_features @ text_features.t()).detach().softmax(dim=-1)
49 sorted_indices = torch.argsort(logits, dim=-1, descending=True)
50
51 logits = logits.cpu().numpy()
52 sorted_indices = sorted_indices.cpu().numpy()
53
54top_k = -1
55
56for i, img in enumerate(test_imgs):
57 pred = labels[sorted_indices[i][0]]
58
59 top_k = len(labels) if top_k == -1 else top_k
60 print(img.split('/')[-1] + ':')
61 for j in range(top_k):
62 jth_index = sorted_indices[i][j]
63 print(f'{labels[jth_index]}: {logits[i][jth_index]}')
64 print('\n')
1import json
2
3from urllib.request import urlopen
4from PIL import Image
5import torch
6from huggingface_hub import hf_hub_download
7from open_clip import create_model_and_transforms, get_tokenizer
8from open_clip.factory import HF_HUB_PREFIX, _MODEL_CONFIGS
9
10
11# Download the model and config files
12hf_hub_download(
13 repo_id="microsoft/BiomedCLIP-PubMedBERT_256-vit_base_patch16_224",
14 filename="open_clip_pytorch_model.bin",
15 local_dir="checkpoints"
16)
17hf_hub_download(
18 repo_id="microsoft/BiomedCLIP-PubMedBERT_256-vit_base_patch16_224",
19 filename="open_clip_config.json",
20 local_dir="checkpoints"
21)
22
23
24# Load the model and config files
25model_name = "biomedclip_local"
26
27with open("checkpoints/open_clip_config.json", "r") as f:
28 config = json.load(f)
29 model_cfg = config["model_cfg"]
30 preprocess_cfg = config["preprocess_cfg"]
31
32
33if (not model_name.startswith(HF_HUB_PREFIX)
34 and model_name not in _MODEL_CONFIGS
35 and config is not None):
36 _MODEL_CONFIGS[model_name] = model_cfg
37
38tokenizer = get_tokenizer(model_name)
39
40model, _, preprocess = create_model_and_transforms(
41 model_name=model_name,
42 pretrained="checkpoints/open_clip_pytorch_model.bin",
43 **{f"image_{k}": v for k, v in preprocess_cfg.items()},
44)
45
46
47# Zero-shot image classification
48template = 'this is a photo of '
49labels = [
50 'adenocarcinoma histopathology',
51 'brain MRI',
52 'covid line chart',
53 'squamous cell carcinoma histopathology',
54 'immunohistochemistry histopathology',
55 'bone X-ray',
56 'chest X-ray',
57 'pie chart',
58 'hematoxylin and eosin histopathology'
59]
60
61dataset_url = 'https://huggingface.co/microsoft/BiomedCLIP-PubMedBERT_256-vit_base_patch16_224/resolve/main/example_data/biomed_image_classification_example_data/'
62test_imgs = [
63 'squamous_cell_carcinoma_histopathology.jpeg',
64 'H_and_E_histopathology.jpg',
65 'bone_X-ray.jpg',
66 'adenocarcinoma_histopathology.jpg',
67 'covid_line_chart.png',
68 'IHC_histopathology.jpg',
69 'chest_X-ray.jpg',
70 'brain_MRI.jpg',
71 'pie_chart.png'
72]
73device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
74model.to(device)
75model.eval()
76
77context_length = 256
78
79images = torch.stack([preprocess(Image.open(urlopen(dataset_url + img))) for img in test_imgs]).to(device)
80texts = tokenizer([template + l for l in labels], context_length=context_length).to(device)
81with torch.no_grad():
82 image_features, text_features, logit_scale = model(images, texts)
83
84 logits = (logit_scale * image_features @ text_features.t()).detach().softmax(dim=-1)
85 sorted_indices = torch.argsort(logits, dim=-1, descending=True)
86
87 logits = logits.cpu().numpy()
88 sorted_indices = sorted_indices.cpu().numpy()
89
90top_k = -1
91
92for i, img in enumerate(test_imgs):
93 pred = labels[sorted_indices[i][0]]
94
95 top_k = len(labels) if top_k == -1 else top_k
96 print(img.split('/')[-1] + ':')
97 for j in range(top_k):
98 jth_index = sorted_indices[i][j]
99 print(f'{labels[jth_index]}: {logits[i][jth_index]}')
100 print('\n')
101
This model is intended to be used solely for (I) future research on visual-language processing and (II) reproducibility of the experimental results reported in the reference paper.
The primary intended use is to support AI researchers building on top of this work. BiomedCLIP and its associated models should be helpful for exploring various biomedical VLP research questions, especially in the radiology domain.
Any deployed use case of the model --- commercial or otherwise --- is currently out of scope. Although we evaluated the models using a broad set of publicly-available research benchmarks, the models and evaluations are not intended for deployed use cases. Please refer to
the associated paper for more details.
1@article{zhang2024biomedclip,
2 title={A Multimodal Biomedical Foundation Model Trained from Fifteen Million Image–Text Pairs},
3 author={Sheng Zhang and Yanbo Xu and Naoto Usuyama and Hanwen Xu and Jaspreet Bagga and Robert Tinn and Sam Preston and Rajesh Rao and Mu Wei and Naveen Valluri and Cliff Wong and Andrea Tupini and Yu Wang and Matt Mazzola and Swadheen Shukla and Lars Liden and Jianfeng Gao and Angela Crabtree and Brian Piening and Carlo Bifulco and Matthew P. Lungren and Tristan Naumann and Sheng Wang and Hoifung Poon},
4 journal={NEJM AI},
5 year={2024},
6 volume={2},
7 number={1},
8 doi={10.1056/AIoa2400640},
9 url={https://ai.nejm.org/doi/full/10.1056/AIoa2400640}
10}
This model was developed using English corpora, and thus can be considered English-only.
Please refer to the corresponding paper,
"Large-Scale Domain-Specific Pretraining for Biomedical Vision-Language Processing" for additional details on the model training and evaluation.