模型概述
模型特點
模型能力
使用案例
🚀 RAD - DINO模型卡
RAD - DINO是一個基於自監督學習方法訓練的視覺變換器模型,專門用於對胸部X光片進行編碼。它為醫學圖像研究提供了強大的工具,有助於推動相關領域的發展。
🚀 快速開始
獲取數據
首先,編寫一個輔助函數來下載胸部X光片。
>>> import requests
>>> from PIL import Image
>>> def download_sample_image() -> Image.Image:
... """Download chest X-ray with CC license."""
... base_url = "https://upload.wikimedia.org/wikipedia/commons"
... image_url = f"{base_url}/2/20/Chest_X-ray_in_influenza_and_Haemophilus_influenzae.jpg"
... headers = {"User-Agent": "RAD-DINO"}
... response = requests.get(image_url, headers=headers, stream=True)
... return Image.open(response.raw)
...
加載模型
現在,下載模型並對圖像進行編碼。
>>> import torch
>>> from transformers import AutoModel
>>> from transformers import AutoImageProcessor
>>>
>>> # Download the model
>>> repo = "microsoft/rad-dino"
>>> rad_dino = AutoModel.from_pretrained(repo)
>>>
>>> # The processor takes a PIL image, performs resizing, center-cropping, and
>>> # intensity normalization using stats from MIMIC-CXR, and returns a
>>> # dictionary with a PyTorch tensor ready for the encoder
>>> processor = AutoImageProcessor.from_pretrained(repo)
編碼圖像
>>> # Download and preprocess a chest X-ray
>>> image = download_sample_image()
>>> image.size # (width, height)
(2765, 2505)
>>> inputs = processor(images=image, return_tensors="pt")
>>>
>>> # Encode the image!
>>> with torch.inference_mode():
>>> outputs = rad_dino(**inputs)
>>>
>>> # Look at the CLS embeddings
>>> cls_embeddings = outputs.pooler_output
>>> cls_embeddings.shape # (batch_size, num_channels)
torch.Size([1, 768])
如果我們對特徵圖感興趣,可以將補丁嵌入重新整形為網格。我們將使用einops
(使用pip install einops
安裝)來實現。
>>> def reshape_patch_embeddings(flat_tokens: torch.Tensor) -> torch.Tensor:
... """Reshape flat list of patch tokens into a nice grid."""
... from einops import rearrange
... image_size = processor.crop_size["height"]
... patch_size = model.config.patch_size
... embeddings_size = image_size // patch_size
... patches_grid = rearrange(flat_tokens, "b (h w) c -> b c h w", h=embeddings_size)
... return patches_grid
...
>>> flat_patch_embeddings = outputs.last_hidden_state[:, 1:] # first token is CLS
>>> reshaped_patch_embeddings = reshape_patch_embeddings(flat_patch_embeddings)
>>> reshaped_patch_embeddings.shape # (batch_size, num_channels, height, width)
torch.Size([1, 768, 37, 37])
微調權重
我們發佈了一個與原始DINOv2代碼兼容的檢查點,以幫助研究人員微調我們的模型。
首先,編寫代碼來加載safetensors
檢查點。
>>> import safetensors
>>> def safetensors_to_state_dict(checkpoint_path: str) -> dict[str, torch.Tensor]:
... state_dict = {}
... with safe_open(checkpoint_path, framework="pt") as ckpt_file:
... for key in ckpt_file.keys():
... state_dict[key] = ckpt_file.get_tensor(key)
... return state_dict
...
現在,我們可以使用hub模型並加載RAD - DINO的權重。克隆DINOv2倉庫,以便導入頭部的代碼。
git clone https://github.com/facebookresearch/dinov2.git
cd dinov2
>>> import torch
>>> rad_dino_gh = torch.hub.load(".", "dinov2_vitb14")
>>> backbone_state_dict = safetensors_to_state_dict("backbone_compatible.safetensors")
>>> rad_dino_gh.load_state_dict(backbone_state_dict, strict=True)
<All keys matched successfully>
頭部的權重也已發佈:
>>> from dinov2.layers import DINOHead
>>> rad_dino_head_gh = DINOHead(
... in_dim=768,
... out_dim=65536,
... hidden_dim=2048,
... bottleneck_dim=256,
... nlayers=3,
... )
>>> head_state_dict = safetensors_to_state_dict("dino_head.safetensors")
>>> rad_dino_head_gh.load_state_dict(head_state_dict, strict=True)
<All keys matched successfully>
配置和增強
配置文件ssl_default_config.yaml
和vitb14_cxr.yaml
,以及augmentations
模塊也可在倉庫中獲取,以幫助研究人員使用我們的超參數重現訓練過程。
✨ 主要特性
- 自監督學習:採用DINOv2自監督學習方法訓練,能有效編碼胸部X光片。
- 多下游任務支持:可作為視覺主幹網絡,應用於圖像分類、分割、聚類、檢索和報告生成等多種下游任務。
- 公開可用:模型及相關檢查點、配置文件等均公開,方便研究人員使用和微調。
📦 安裝指南
文檔未提及具體安裝步驟,暫不提供。
💻 使用示例
基礎用法
# 獲取數據
import requests
from PIL import Image
def download_sample_image() -> Image.Image:
"""Download chest X-ray with CC license."""
base_url = "https://upload.wikimedia.org/wikipedia/commons"
image_url = f"{base_url}/2/20/Chest_X-ray_in_influenza_and_Haemophilus_influenzae.jpg"
headers = {"User-Agent": "RAD-DINO"}
response = requests.get(image_url, headers=headers, stream=True)
return Image.open(response.raw)
# 加載模型
import torch
from transformers import AutoModel
from transformers import AutoImageProcessor
repo = "microsoft/rad-dino"
rad_dino = AutoModel.from_pretrained(repo)
processor = AutoImageProcessor.from_pretrained(repo)
# 編碼圖像
image = download_sample_image()
inputs = processor(images=image, return_tensors="pt")
with torch.inference_mode():
outputs = rad_dino(**inputs)
cls_embeddings = outputs.pooler_output
高級用法
# 處理特徵圖
from einops import rearrange
def reshape_patch_embeddings(flat_tokens: torch.Tensor) -> torch.Tensor:
"""Reshape flat list of patch tokens into a nice grid."""
image_size = processor.crop_size["height"]
patch_size = model.config.patch_size
embeddings_size = image_size // patch_size
patches_grid = rearrange(flat_tokens, "b (h w) c -> b c h w", h=embeddings_size)
return patches_grid
flat_patch_embeddings = outputs.last_hidden_state[:, 1:] # first token is CLS
reshaped_patch_embeddings = reshape_patch_embeddings(flat_patch_embeddings)
📚 詳細文檔
模型描述
RAD - DINO是一個視覺變換器模型,使用自監督學習方法DINOv2對胸部X光片進行編碼。該模型在Exploring Scalable Medical Image Encoders Beyond Text Supervision (F. Pérez - García, H. Sharma, S. Bond - Taylor, et al., 2024)中有詳細描述。
- 開發者:Microsoft Health Futures
- 模型類型:視覺變換器
- 許可證:MSRLA
- 微調基礎模型:[
dinov2 - base
](https://huggingface.co/facebook/dinov2 - base)
用途
RAD - DINO僅用於研究目的,不應用於臨床實踐。該模型可作為視覺主幹網絡,接入其他模型用於下游任務,一些潛在用途包括:
- 圖像分類:在
CLS
令牌之上訓練分類器。 - 圖像分割:使用補丁令牌訓練解碼器。
- 聚類:直接使用圖像嵌入。
- 圖像檢索:使用
CLS
令牌的最近鄰。 - 報告生成:使用語言模型解碼文本。 通常,在下游任務中,微調RAD - DINO並非獲得良好性能所必需。
偏差、風險和侷限性
RAD - DINO使用來自三個國家的數據進行訓練,因此可能對訓練數據中的人群存在偏差。訓練數據集的潛在偏差可能未得到充分表徵。
訓練細節
訓練數據
我們使用了五個公開的、去識別化的胸部X光片數據集的圖像來訓練RAD - DINO的這個檢查點。
數據集 | 圖像數量 |
---|---|
MIMIC - CXR | 368960 |
CheXpert | 223648 |
[NIH - CXR](https://openaccess.thecvf.com/content_cvpr_2017/html/Wang_ChestX - ray8_Hospital - Scale_Chest_CVPR_2017_paper.html) | 112120 |
PadChest | 136787 |
BRAX | 41260 |
總計 | 882775 |
用於訓練MAIRA的驗證集和測試集中的圖像被排除在RAD - DINO的訓練集之外。訓練使用的圖像文件列表可在./training_images.csv 中獲取。 |
|
注意,這個檢查點與論文中的不同,論文中使用了一些私有數據(且使用的GPU較少)。這裡共享的檢查點訓練了35000次迭代(運行的總迭代次數為100000次,但我們通過對論文中描述的評估數據集的驗證集進行線性探測來選擇這個檢查點)。我們使用了16個節點,每個節點有4個A100 GPU,每個GPU的批量大小為40張圖像。 |
訓練過程
我們參考論文獲取訓練過程的詳細描述。
預處理
所有DICOM文件使用B樣條插值進行調整大小,使其較短邊為518,進行最小 - 最大縮放至[0, 255],並存儲為PNG文件。
訓練超參數
- 訓練模式:使用PyTorch - FSDP混合精度的fp16。
評估
我們的評估在論文中有詳細描述。
環境影響
- 硬件類型:NVIDIA A100 GPUs
- 使用時長:40小時/ GPU × 16個節點 × 4個GPU/節點 = 2560 GPU小時
- 雲服務提供商:Azure
- 計算區域:美國西部2
- 碳排放:222 kg CO₂ 當量
計算基礎設施
RAD - DINO在[Azure Machine Learning](https://azure.microsoft.com/en - us/products/machine - learning)上進行訓練。
硬件
我們使用了16個Standard_NC96ads_A100_v4
節點,每個節點有四個NVIDIA A100(80 GB)GPU。
軟件
我們利用DINOv2中的代碼進行訓練。我們使用SimpleITK和Pydicom處理DICOM文件。
🔧 技術細節
- 模型架構:基於視覺變換器架構,採用DINOv2自監督學習方法訓練。
- 訓練方法:使用自監督學習,避免了大量人工標註數據的需求。
- 數據處理:對DICOM文件進行了特定的預處理,包括調整大小、縮放和存儲為PNG文件。
📄 許可證
本模型採用MSRLA許可證。
📚 引用
BibTeX:
@article{perez-garcia_exploring_2025,
title = {Exploring scalable medical image encoders beyond text supervision},
issn = {2522-5839},
url = {https://doi.org/10.1038/s42256-024-00965-w},
doi = {10.1038/s42256-024-00965-w},
journal = {Nature Machine Intelligence},
author = {Pérez-García, Fernando and Sharma, Harshita and Bond-Taylor, Sam and Bouzid, Kenza and Salvatelli, Valentina and Ilse, Maximilian and Bannur, Shruthi and Castro, Daniel C. and Schwaighofer, Anton and Lungren, Matthew P. and Wetscherek, Maria Teodora and Codella, Noel and Hyland, Stephanie L. and Alvarez-Valle, Javier and Oktay, Ozan},
month = jan,
year = {2025},
}
APA:
Pérez - García, F., Sharma, H., Bond - Taylor, S., Bouzid, K., Salvatelli, V., Ilse, M., Bannur, S., Castro, D. C., Schwaighofer, A., Lungren, M. P., Wetscherek, M. T., Codella, N., Hyland, S. L., Alvarez - Valle, J., & Oktay, O. (2025). Exploring scalable medical image encoders beyond text supervision. In Nature Machine Intelligence. Springer Science and Business Media LLC. https://doi.org/10.1038/s42256-024-00965 - w
模型卡聯繫人
Fernando Pérez - García (fperezgarcia@microsoft.com
)。









