GithubHelp home page GithubHelp logo

mahmoodlab / uni Goto Github PK

View Code? Open in Web Editor NEW
170.0 2.0 22.0 5.93 MB

Towards a general-purpose foundation model for computational pathology - Nature Medicine

License: Other

Jupyter Notebook 97.76% Python 2.24%
foundation foundation-model histopathology mahmoodlab pathology uni pathology-foundation-model nature-medicine mass-100k pathology-dinov2

uni's Introduction

UNI

Towards a General-Purpose Foundation Model for Computational Pathology

Nature Medicine

Journal Link | Open Access Read Link | Download Model | Cite

Abstract: Quantitative evaluation of tissue images is crucial for computational pathology (CPath) tasks, requiring the objective characterization of histopathological entities from whole-slide images (WSIs). The high resolution of WSIs and the variability of morphological features present significant challenges, complicating the large-scale annotation of data for high-performance applications. To address this challenge, current efforts have proposed the use of pretrained image encoders through transfer learning from natural image datasets or self-supervised learning on publicly available histopathology datasets, but have not been extensively developed and evaluated across diverse tissue types at scale. We introduce UNI, a general-purpose self-supervised model for pathology, pretrained using more than 100 million images from over 100,000 diagnostic H&E-stained WSIs (>77 TB of data) across 20 major tissue types. The model was evaluated on 34 representative CPath tasks of varying diagnostic difficulty. In addition to outperforming previous state-of-the-art models, we demonstrate new modeling capabilities in CPath such as resolution-agnostic tissue classification, slide classification using few-shot class prototypes, and disease subtyping generalization in classifying up to 108 cancer types in the OncoTree classification system. UNI advances unsupervised representation learning at scale in CPath in terms of both pretraining data and downstream evaluation, enabling data-efficient artificial intelligence models that can generalize and transfer to a wide range of diagnostically challenging tasks and clinical workflows in anatomic pathology.

What is UNI?

UNI is the largest pretrained vision encoder for histopathology (100M images, 100K WSIs) developed on internal neoplastic, infectious, inflamatory and normal tissue and also made publicly available. We show state-of-the-art performance across 34 clinical tasks, with strong performance gains on rare and underrepresented cancer types.

  • Why use UNI?: UNI does not use open datasets and large public histology slide collections (TCGA, CPTAC, PAIP, CAMELYON, PANDA, and others in TCIA) for pretraining, which are routinely used in benchmark development in computational pathology. We make UNI available for the research community in building and evaluating pathology AI models without risk of data contamination on public benchmarks or private histopathology slide collections.

Installation

First clone the repo and cd into the directory:

git clone https://github.com/mahmoodlab/UNI.git
cd UNI

Then create a conda env and install the dependencies:

conda create -n UNI python=3.10 -y
conda activate UNI
pip install --upgrade pip  # enable PEP 660 support
pip install -e .

1. Getting access

Request access to the model weights from the Huggingface model page at: https://huggingface.co/mahmoodlab/UNI.

2. Downloading weights + Creating model

Following authentication (using huggingface_hub), the ViT-L/16 model architecture with pretrained weights and image transforms for UNI can be directly loaded using the timm library. This method automatically downloads the model weights to the huggingface_hub cache in your home directory (~/.cache/huggingface/hub/models--MahmoodLab--UNI), which timm will automatically find when using the commands below:

import timm
from timm.data import resolve_data_config
from timm.data.transforms_factory import create_transform
from huggingface_hub import login

login()  # login with your User Access Token, found at https://huggingface.co/settings/tokens

# pretrained=True needed to load UNI weights (and download weights for the first time)
# init_values need to be passed in to successfully load LayerScale parameters (e.g. - block.0.ls1.gamma)
model = timm.create_model("hf-hub:MahmoodLab/uni", pretrained=True, init_values=1e-5, dynamic_img_size=True)
transform = create_transform(**resolve_data_config(model.pretrained_cfg, model=model))
model.eval()

You can also download the model weights to a specified checkpoint location in your local directory. The timm library is still used for defining the ViT-L/16 model architecture. Pretrained weights and image transforms for UNI need to be manually loaded and defined.

import os
import torch
from torchvision import transforms
import timm
from huggingface_hub import login, hf_hub_download

login()  # login with your User Access Token, found at https://huggingface.co/settings/tokens

local_dir = "../assets/ckpts/vit_large_patch16_224.dinov2.uni_mass100k/"
os.makedirs(local_dir, exist_ok=True)  # create directory if it does not exist
hf_hub_download("MahmoodLab/UNI", filename="pytorch_model.bin", local_dir=local_dir, force_download=True)
model = timm.create_model(
    "vit_large_patch16_224", img_size=224, patch_size=16, init_values=1e-5, num_classes=0, dynamic_img_size=True
)
model.load_state_dict(torch.load(os.path.join(local_dir, "pytorch_model.bin"), map_location="cpu"), strict=True)
transform = transforms.Compose(
    [
        transforms.Resize(224),
        transforms.ToTensor(),
        transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
    ]
)
model.eval()

The function get_encoder performs the commands above, downloading in the checkpoint in the ./assets/ckpts/ relative path of this GitHub repository.

from uni import get_encoder
model, transform = get_encoder(enc_name='uni', device=device)

3. Running Inference

You can use the UNI pretrained encoder to extract features from histopathology ROIs, as follows:

from PIL import Image
image = Image.open("uni.jpg")
image = transform(image).unsqueeze(dim=0) # Image (torch.Tensor) with shape [1, 3, 224, 224] following image resizing and normalization (ImageNet parameters)
with torch.inference_mode():
    feature_emb = model(image) # Extracted features (torch.Tensor) with shape [1,1024]

These pre-extracted features can then be used ROI classification (via linear probing), slide classification (via multiple instance learning), and other machine learning settings.

Overview of specific usages

We provide high-level functions for loading the model and using it for inference. For model loading, the function get_encoder performs the commands above in Step 2, downloading in the checkpoint in the ./assets/ckpts/ relative path of this GitHub repository.

from uni import get_encoder
model, transform = get_encoder(enc_name='uni', device=device)

For inference:

from uni.downstream.extract_patch_features import extract_patch_features_from_dataloader
from uni.downstream.eval_patch_features.linear_probe import eval_linear_probe
from uni.downstream.eval_patch_features.fewshot import eval_knn, eval_fewshot
from uni.downstream.eval_patch_features.protonet import ProtoNet, prototype_topk_vote

Refer to the notebooks below for detailed examples.

More detailed starter code for loading / using the model:

See ./notebooks/uni_walkthrough.ipynb to get started with loading and using the model to create embeddings, and example code for extracting ROI features and performing ROI classification / retrieval.

Comparisons & Additional Benchmarks

ROI and slide classification results

A detailed set of benchmarks are in the paper [1] (also shown above). Some models were released after our study was in review. For a more comprehensive comparison, we have provided additional results on EBRAINS, PANDA, OncoTree, IHC ER / PR assessment, CRC-100K-Raw, and TCGA Uniform Tumor datasets as a representative set of benchmarks which cover a wide range of tissue types, diseases, difficulty levels (up to 108-classes) and staining (H&E and IHC). Results are reported using ABMIL and KNN (K=20) slide and ROI tasks respectively.

Please refer to the UNI [1] and CONCH [2] papers for more detailed benchmarking.

Slide Benchmarks

Model name Pretraining EBRAINS-C (12 classes, Public) EBRAINS-F (30 classes, Public) PANDA (5 classes, Public) OncoTree-108 (108 classes, Internal) IHC ER / PR Assess. (6 classes, Internal)
Balanced acc. Balanced acc. Quadratic-weight $\kappa$ Balanced acc. Quadratic-weight $\kappa$
UNI [1] Vision 0.883 0.675 0.946 0.538 0.785
CONCH [2] Vision-language 0.868 0.689 0.934 0.515 0.819
Phikon [3] Vision 0.810 0.659 0.950 0.486 0.744
REMEDIS [4] Vision 0.687 0.382 0.932 0.412 0.762
CTransPath [5] Vision 0.666 0.514 0.927 0.399 0.786
Quilt-Net [6] Vision-language 0.728 0.608 0.909 0.389 0.784
PLIP [7] Vision-language 0.683 0.562 0.901 0.369 0.759
ResNet-50 (Tr) [8] ImageNet Transfer 0.302 0.219 0.831 0.148 0.709

ROI Benchmarks

Model name Pretraining CRC-100K-Raw (9 classes, Public) TCGA Uniform Tumor (32 classes, Public)
Balanced acc. Balanced acc.
UNI [1] Vision 0.925 0.595
CONCH [2] Vision-language 0.941 0.556
Phikon [3] Vision 0.845 0.533
REMEDIS [4] Vision 0.908 0.541
CTransPath [5] Vision 0.836 0.463
Quilt-Net [6] Vision-language 0.878 0.359
PLIP [7] Vision-language 0.840 0.370
ResNet-50 [8] ImageNet Transfer 0.797 0.318

License and Terms of Tuse

ⓒ Mahmood Lab. This model and associated code are released under the CC-BY-NC-ND 4.0 license and may only be used for non-commercial, academic research purposes with proper attribution. Any commercial use, sale, or other monetization of the UNI model and its derivatives, which include models trained on outputs from the UNI model or datasets created from the UNI model, is prohibited and requires prior approval. Downloading the model requires prior registration on Hugging Face and agreeing to the terms of use. By downloading this model, you agree not to distribute, publish or reproduce a copy of the model. If another user within your organization wishes to use the UNI model, they must register as an individual user and agree to comply with the terms of use. Users may not attempt to re-identify the deidentified data used to develop the underlying model. If you are a commercial entity, please contact the corresponding author or Mass General Brigham Innovation Office.

Acknowledgements

The project was built on top of amazing repositories such as ViT, DINOv2, LGSSL, and Timm (ViT model implementation). We thank the authors and developers for their contribution.

Reference

If you find our work useful in your research or if you use parts of this code please consider citing our paper:

Chen, R.J., Ding, T., Lu, M.Y., Williamson, D.F.K., et al. Towards a general-purpose foundation model for computational pathology. Nat Med (2024). https://doi.org/10.1038/s41591-024-02857-3

@article{chen2024uni,
  title={Towards a General-Purpose Foundation Model for Computational Pathology},
  author={Chen, Richard J and Ding, Tong and Lu, Ming Y and Williamson, Drew FK and Jaume, Guillaume and Chen, Bowen and Zhang, Andrew and Shao, Daniel and Song, Andrew H and Shaban, Muhammad and others},
  journal={Nature Medicine},
  publisher={Nature Publishing Group},
  year={2024}
}

uni's People

Contributors

faisalml avatar fedshyvana avatar georgebatch avatar richarizardd avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

uni's Issues

No module named 'faiss'

Dear authors,

thank you for providing the code.
When testing your code with the uni_walkthrough.ipynb an error occurs, because the 'faiss' module is missing.

Note: can be fixed with: pip install faiss-cpu h5py ipywidgets.

Best,
Leon

About data downloda

Hello, I think your work is very meaningful. But I would like to inquire which of the data used can be downloaded. Can you provide a download address? Thank you.

How was figure 3e generated in the paper?

Screenshot 2024-03-25 at 8 51 32 PM

I used something similar to this to extract the attention scores for the penultimate layer, as explained in the caption for figure 3e. However, I found that the attention maps I'm getting are a lot less "intuitive" compared to the ones shown in this figure.

Was this figure generated with a fine-tuned UNI model on the ROI level task or is it just showing the attention maps of the SSL model (no fine-tuning)?

Also, are the 448^2, 896^2 and 1344^2 attention maps computed by concatenating the attention map for each non-overlapping 224^2 patch together?

ROI feature extraction

Hello, thank you very much for your contribution. In your paper, you mentioned using the UNI pre-trained encoder to extract features from histopathology ROI, and also provided sample code. What I want to know is whether the ROI needs to be segmented in advance or not. Using the whole WSI image as input, if an image has multiple ROIs, can you provide me with a code example, I will be grateful

What is the reasoning behind using ImageNet normalization constansts?

Dear authors,

Thank you for releasing this work! I think it will bring great value to the community.

In the Nature paper you say "All pretrained encoders use ImageNet mean and standard deviation parameters for image normalization (including UNI)". The code examples are also consistent with it.

Can you please clarify the reason for sticking to the ImageNet normalization constants? As far as I understand, they were computed on the original ImageNet dataset. Since you had a different dataset for pre-training the UNI model, why not calculate the constants on your dataset?

Many thanks,
George

Label for IDH1 mutation prediction

Thank you for this great work!

May I ask where to find the corresponding label for IDH1 mutation prediction task (TCGA & EBRAINS)?

Thanks!

Results of the PANDA Competition

Thank you very much for your great pre-trained model.

Regarding the results of the PANDA competition, can you tell us the results of your submission using kaggle's leaderborad, we can only claim PANDA's performance to be good if it exceeds some of the top solutions in 2019.

How to use UNI for segmentation task?

Dear authors,
thanks for your great work!
In your publication you mention that you also used UNI for segmentation of images. Could you please provide insights how to use UNI for segmentation tasks?
Thank you!
Kind regards.

Pretraining on 256x256 and 512x512, recommended inference on 224x224

Dear authors,

In the paper (and on HuggingFace), you mention that you used a dataset "composed of 75,832,905 [256×256] and 24,297,995 [512×512] histology images at 20× resolution". However, in the example code on GitHub and HuggingFace, you suggest using patch size 224x224 (224 is in the model name too: assets/ckpts/vit_large_patch16_224.dinov2.uni_mass100k/). Can you please explain why? Can the model accept other patch sizes?

Many thanks,
George

Mucinous tissue

Hello,

I have a question concerning the data used to train the model : Was mucinous tissue included in it?

When using UNI with CLAM, the attention scores seem incoherent if there is mucinous tissue in the slide. It tends to focus on the mucin rather than the tumor.

Training loss(es) during pre-training

Hello,
I was wondering if you could provide additional details on the evolution of loss functions during the pre-training of UNI.
It has indeed been observed that instabilities or convergence issues may hinder the pre-training. Is this something you already observed ?

Congratulations for this groundbreaking work and for publicly releasing weights.

Conch in arxiv

Thank you for your great work!

I've read your another paper called 'CONCH' in arxiv (https://arxiv.org/pdf/2307.12914.pdf).
Can I ask you is this work an extension of CONCH?
And if not, are you preparing an additional publication for CONCH?

Model weights result in nan-values for half precision

I'm not sure if this is resolvable, but the UNI weights result in nan values when doing training or inference on float16. The following is on a H&E stain image with imagenet normalization:

path = hf_hub_download("MahmoodLab/UNI", filename="pytorch_model.bin")
model = timm.create_model("vit_large_patch16_224", init_values=1e-5, num_classes=0).to(device)

missing_k, unexpected_k = model.load_state_dict(torch.load(path), strict=False)
print(f'Missing keys: {missing_k}')
print(f'Unexpected keys: {unexpected_k}')

with torch.autocast(device_type='cuda', dtype=torch.float32):
    print(f'float32 output: {model(batch_img)}')
with torch.autocast(device_type='cuda', dtype=torch.float16):
    print(f'float16 output: {model(batch_img)}')

model_imagenet = timm.create_model("vit_large_patch16_224", init_values=1e-5, num_classes=0, pretrained=True).to(device)

with torch.autocast(device_type='cuda', dtype=torch.float32):
    print(f'float32 output: {model_imagenet(batch_img)}')
with torch.autocast(device_type='cuda', dtype=torch.float16):
    print(f'float16 output: {model_imagenet(batch_img)}')

Output: Half-precision works for default ImageNet-pretrain weights but not UNI.

Missing keys: []
Unexpected keys: []
float32 output: tensor([[-0.9344, -0.0447,  2.0671,  ...,  0.1991,  1.0729, -0.1812]],
       device='cuda:0', grad_fn=<SelectBackward0>)
float16 output: tensor([[nan, nan, nan,  ..., nan, nan, nan]], device='cuda:0',
       grad_fn=<SelectBackward0>)
float32 output: tensor([[ 1.3607,  0.1251, -0.2508,  ...,  0.2557, -0.1732,  0.6628]],
       device='cuda:0', grad_fn=<SelectBackward0>)
float16 output: tensor([[ 1.3607,  0.1251, -0.2508,  ...,  0.2557, -0.1732,  0.6628]],
       device='cuda:0', grad_fn=<SelectBackward0>)

Does 20x magnification correspond to 0.5 microns per pixel?

Hello,

Does the 20x magnification correspond to the resolution of 0.5 microns per pixel (mupp)? I am asking because magnification is not standardised, and I have encountered slides from different scanners with 20x magnification, corresponding to a resolution from 0.23 mupp to 0.55 mupp.

Many thanks,
George

Wrong information about UniToPatho dataset

Hi, thank you for your amazing work.

In your paper, you wrote UniToPatho includes 9536 1,812x1,812 patches, but it actually contains 8669 1,812x1,812 patches and 867 15,855×15,855 patches
Not a big problem, just let you know.

access request accepted, authentification succeeded, but weights downloading and model creating failed

Hi,

I followed the procedure (access request via huggingface + authentification via login(token) + weights downloading and model creating), but got error with model = timm.create_model("hf-hub:MahmoodLab/uni", pretrained=True, init_values=1e-5, dynamic_img_size=True)

"GatedRepoError: 401 Client Error. (Request ID: Root=1-65fd9fbe-75542d9c27933ae862f55525)

Cannot access gated repo for url https://huggingface.co/MahmoodLab/UNI/resolve/main/config.json.
Repo model MahmoodLab/UNI is gated. You must be authenticated to access it."

that's just like my request has not been accepted yet, but it's not the case (first snapshot). I also tried to log out relog in hugging face in case these's a update delay....but I still got the same error. Detailed snapshots are shown below, I really don't know where the problem is....could you help me please? I'm using jupyter notebook on servors of my institution.

Thank you

1711120164210
1711120377731
1711120432472

CLAM config for HunCRC slide data

Hello authors,

Thank you for you amazing work.
Can you publish the config of CLAM for extracting HunCRC data ?

I can't extract, even with very low thresholds.
{'seg_params': {'seg_level': -1, 'sthresh': 1, 'mthresh': 1, 'close': 4, 'use_otsu': True, 'keep_ids': 'none', 'exclude_ids': 'none'}, 'filter_params': {'a_t': 1, 'a_h': 1, 'max_n_holes': 10}, 'patch_params': {'use_padding': True, 'contour_fn': 'four_pt'}, 'vis_params': {'vis_level': -1, 'line_thickness': 50}}

Thank you.

Clarifying augmentations used for student teacher, regarding fine cell detail

Thank you for releasing the weights attributed to UNI, as well as the fantastic paper. I am having some trouble understanding the use of some of the augmentations used by UNI. This video explaining DINO video timestamp 20:00 mins, suggests that the goal of using a local and global crop for S and T is that the student must learn a more global representation from what is offered, such that small structures shouldn't contribute in favor of a global structure representation. However, in pathology, the small structures matter a lot, like cell nuclei etc. Is this understanding correct? If so, is it necessary to bypass this for a good representation?

Weights are saved twice after running the walkthrough notebook: `models--MahmoodLab--UNI` and `models--MahmoodLab--uni`

Dear authors,

I ran the walkthrough notebook, and the model was downloaded twice (see screenshot).

  1. I get the symbolic link
    assets/ckpts/vit_large_patch16_224.dinov2.uni_mass100k/pytorch_model.bin pointing to a file in .cache/huggingface/hub/models--MahmoodLab--UNI/.

  2. The other downloaded model is in .cache/huggingface/hub/models--MahmoodLab--uni/

I think there are 2 different places in the code, one with capital letters "UNI" and one with non-capital letters "uni". They do not link to each other since each folder weighs 1.2 GB, while together, they occupy 2.4 GB.

Best wishes,
George

Screenshot 2024-03-26 at 15 07 46

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.