模型简介
模型特点
模型能力
使用案例
🚀 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
)。









