├── banner.png ├── overall.png ├── moco ├── __init__.py ├── optimizer.py ├── loader.py ├── mae.py └── builder.py ├── used_TCGA.csv ├── CONTRIBUTING.md ├── convert_to_deit.py ├── transfer ├── oxford_pets_dataset.py ├── oxford_flowers_dataset.py ├── dataset.py └── README.md ├── CODE_OF_CONDUCT.md ├── generate_train_data.py ├── CONFIG.md ├── vits.py ├── README.md ├── main_moco.py ├── LICENSE ├── main_cross.py ├── main_bridge.py └── main_lincls.py /banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/openmedlab/PathoDuet/HEAD/banner.png -------------------------------------------------------------------------------- /overall.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/openmedlab/PathoDuet/HEAD/overall.png -------------------------------------------------------------------------------- /moco/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 2 | -------------------------------------------------------------------------------- /used_TCGA.csv: -------------------------------------------------------------------------------- 1 | dataset,index,used 2 | TCGA-BRCA,0,0 3 | TCGA-GBM,1,0 4 | TCGA-OV,2,0 5 | TCGA-LUAD,3,0 6 | TCGA-UCEC,4,0 7 | TCGA-KIRC,5,0 8 | TCGA-HNSC,6,0 9 | TCGA-LGG,7,0 10 | TCGA-THCA,8,0 11 | TCGA-LUSC,9,0 12 | TCGA-PRAD,10,0 13 | TCGA-SKCM,11,0 14 | TCGA-COAD,12,0 15 | TCGA-STAD,13,0 16 | TCGA-BLCA,14,0 17 | TCGA-LIHC,15,0 18 | TCGA-CESC,16,0 19 | TCGA-KIRP,17,0 20 | TCGA-SARC,18,0 21 | TCGA-ESCA,19,0 22 | TCGA-PAAD,20,0 23 | TCGA-PCPG,21,0 24 | TCGA-READ,22,0 25 | TCGA-TGCT,23,0 26 | TCGA-THYM,24,0 27 | TCGA-KICH,25,0 28 | TCGA-ACC,26,0 29 | TCGA-MESO,27,0 30 | TCGA-UVM,28,0 31 | TCGA-DLBC,29,0 32 | TCGA-UCS,30,0 33 | TCGA-CHOL,31,0 34 | TCGA-LAML,32,0 35 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to moco-v3 2 | We want to make contributing to this project as easy and transparent as 3 | possible. 4 | 5 | ## Pull Requests 6 | We actively welcome your pull requests. 7 | 8 | 1. Fork the repo and create your branch from `master`. 9 | 2. If you've added code that should be tested, add tests. 10 | 3. If you've changed APIs, update the documentation. 11 | 4. Ensure the test suite passes. 12 | 5. Make sure your code lints. 13 | 6. If you haven't already, complete the Contributor License Agreement ("CLA"). 14 | 15 | ## Contributor License Agreement ("CLA") 16 | In order to accept your pull request, we need you to submit a CLA. You only need 17 | to do this once to work on any of Facebook's open source projects. 18 | 19 | Complete your CLA here: 20 | 21 | ## Issues 22 | We use GitHub issues to track public bugs. Please ensure your description is 23 | clear and has sufficient instructions to be able to reproduce the issue. 24 | 25 | Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe 26 | disclosure of security bugs. In those cases, please go through the process 27 | outlined on that page and do not file a public issue. 28 | 29 | ## License 30 | By contributing to moco-v3, you agree that your contributions will be licensed 31 | under the LICENSE file in the root directory of this source tree. -------------------------------------------------------------------------------- /convert_to_deit.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # Copyright (c) Facebook, Inc. and its affiliates. 4 | # All rights reserved. 5 | 6 | # This source code is licensed under the license found in the 7 | # LICENSE file in the root directory of this source tree. 8 | 9 | import argparse 10 | import os 11 | import torch 12 | 13 | 14 | if __name__ == '__main__': 15 | parser = argparse.ArgumentParser(description='Convert MoCo Pre-Traind Model to DEiT') 16 | parser.add_argument('--input', default='', type=str, metavar='PATH', required=True, 17 | help='path to moco pre-trained checkpoint') 18 | parser.add_argument('--output', default='', type=str, metavar='PATH', required=True, 19 | help='path to output checkpoint in DEiT format') 20 | args = parser.parse_args() 21 | print(args) 22 | 23 | # load input 24 | checkpoint = torch.load(args.input, map_location="cpu") 25 | state_dict = checkpoint['state_dict'] 26 | for k in list(state_dict.keys()): 27 | # retain only base_encoder up to before the embedding layer 28 | if k.startswith('module.base_encoder') and not k.startswith('module.base_encoder.head'): 29 | # remove prefix 30 | state_dict[k[len("module.base_encoder."):]] = state_dict[k] 31 | # delete renamed or unused k 32 | del state_dict[k] 33 | 34 | # make output directory if necessary 35 | output_dir = os.path.dirname(args.output) 36 | if not os.path.isdir(output_dir): 37 | os.makedirs(output_dir) 38 | # save to output 39 | torch.save({'model': state_dict}, args.output) 40 | -------------------------------------------------------------------------------- /moco/optimizer.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | import torch 8 | 9 | 10 | class LARS(torch.optim.Optimizer): 11 | """ 12 | LARS optimizer, no rate scaling or weight decay for parameters <= 1D. 13 | """ 14 | def __init__(self, params, lr=0, weight_decay=0, momentum=0.9, trust_coefficient=0.001): 15 | defaults = dict(lr=lr, weight_decay=weight_decay, momentum=momentum, trust_coefficient=trust_coefficient) 16 | super().__init__(params, defaults) 17 | 18 | @torch.no_grad() 19 | def step(self): 20 | for g in self.param_groups: 21 | for p in g['params']: 22 | dp = p.grad 23 | 24 | if dp is None: 25 | continue 26 | 27 | if p.ndim > 1: # if not normalization gamma/beta or bias 28 | dp = dp.add(p, alpha=g['weight_decay']) 29 | param_norm = torch.norm(p) 30 | update_norm = torch.norm(dp) 31 | one = torch.ones_like(param_norm) 32 | q = torch.where(param_norm > 0., 33 | torch.where(update_norm > 0, 34 | (g['trust_coefficient'] * param_norm / update_norm), one), 35 | one) 36 | dp = dp.mul(q) 37 | 38 | param_state = self.state[p] 39 | if 'mu' not in param_state: 40 | param_state['mu'] = torch.zeros_like(p) 41 | mu = param_state['mu'] 42 | mu.mul_(g['momentum']).add_(dp) 43 | p.add_(mu, alpha=-g['lr']) 44 | -------------------------------------------------------------------------------- /transfer/oxford_pets_dataset.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | from PIL import Image 8 | from typing import Any, Callable, Optional, Tuple 9 | 10 | import numpy as np 11 | import os 12 | import os.path 13 | import pickle 14 | import scipy.io 15 | 16 | from torchvision.datasets.vision import VisionDataset 17 | 18 | 19 | class Pets(VisionDataset): 20 | 21 | def __init__( 22 | self, 23 | root: str, 24 | train: bool = True, 25 | transform: Optional[Callable] = None, 26 | target_transform: Optional[Callable] = None, 27 | download: bool = False, 28 | ) -> None: 29 | 30 | super(Pets, self).__init__(root, transform=transform, 31 | target_transform=target_transform) 32 | 33 | base_folder = root 34 | self.train = train 35 | annotations_path_dir = os.path.join(base_folder, "annotations") 36 | self.image_path_dir = os.path.join(base_folder, "images") 37 | 38 | if self.train: 39 | split_file = os.path.join(annotations_path_dir, "trainval.txt") 40 | with open(split_file) as f: 41 | self.images_list = f.readlines() 42 | else: 43 | split_file = os.path.join(annotations_path_dir, "test.txt") 44 | with open(split_file) as f: 45 | self.images_list = f.readlines() 46 | 47 | 48 | def __getitem__(self, index: int) -> Tuple[Any, Any]: 49 | 50 | img_name, label, species, _ = self.images_list[index].strip().split(" ") 51 | 52 | img_name += ".jpg" 53 | target = int(label) - 1 54 | 55 | img = Image.open(os.path.join(self.image_path_dir, img_name)) 56 | img = img.convert('RGB') 57 | 58 | if self.transform is not None: 59 | img = self.transform(img) 60 | 61 | if self.target_transform is not None: 62 | target = self.target_transform(target) 63 | 64 | return img, target 65 | 66 | def __len__(self) -> int: 67 | return len(self.images_list) 68 | -------------------------------------------------------------------------------- /transfer/oxford_flowers_dataset.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | from __future__ import print_function 8 | from PIL import Image 9 | from typing import Any, Callable, Optional, Tuple 10 | 11 | import numpy as np 12 | import os 13 | import os.path 14 | import pickle 15 | import scipy.io 16 | 17 | from torchvision.datasets.vision import VisionDataset 18 | 19 | 20 | class Flowers(VisionDataset): 21 | 22 | def __init__( 23 | self, 24 | root, 25 | train=True, 26 | transform=None, 27 | target_transform=None, 28 | download=False, 29 | ): 30 | 31 | super(Flowers, self).__init__(root, transform=transform, 32 | target_transform=target_transform) 33 | 34 | base_folder = root 35 | self.image_folder = os.path.join(base_folder, "jpg") 36 | label_file = os.path.join(base_folder, "imagelabels.mat") 37 | setid_file = os.path.join(base_folder, "setid.mat") 38 | 39 | self.train = train 40 | 41 | self.labels = scipy.io.loadmat(label_file)["labels"][0] 42 | train_list = scipy.io.loadmat(setid_file)["trnid"][0] 43 | val_list = scipy.io.loadmat(setid_file)["valid"][0] 44 | test_list = scipy.io.loadmat(setid_file)["tstid"][0] 45 | trainval_list = np.concatenate([train_list, val_list]) 46 | 47 | if self.train: 48 | self.img_files = trainval_list 49 | else: 50 | self.img_files = test_list 51 | 52 | 53 | def __getitem__(self, index): 54 | img_name = "image_%05d.jpg" % self.img_files[index] 55 | target = self.labels[self.img_files[index] - 1] - 1 56 | img = Image.open(os.path.join(self.image_folder, img_name)) 57 | 58 | if self.transform is not None: 59 | img = self.transform(img) 60 | 61 | if self.target_transform is not None: 62 | target = self.target_transform(target) 63 | 64 | return img, target 65 | 66 | def __len__(self): 67 | return len(self.img_files) 68 | -------------------------------------------------------------------------------- /transfer/dataset.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | import json 8 | import os 9 | 10 | from torchvision import datasets, transforms 11 | from torchvision.datasets.folder import ImageFolder, default_loader 12 | 13 | from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD 14 | 15 | import oxford_flowers_dataset, oxford_pets_dataset 16 | 17 | 18 | def build_transform(is_train, args): 19 | transform_train = transforms.Compose([ 20 | transforms.RandomResizedCrop((args.input_size, args.input_size), scale=(0.05, 1.0)), 21 | transforms.RandomHorizontalFlip(), 22 | transforms.ToTensor(), 23 | transforms.Normalize(IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD), 24 | ]) 25 | transform_test = transforms.Compose([ 26 | transforms.Resize(int((256 / 224) * args.input_size)), 27 | transforms.CenterCrop(args.input_size), 28 | transforms.ToTensor(), 29 | transforms.Normalize(IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD), 30 | ]) 31 | return transform_train if is_train else transform_test 32 | 33 | 34 | def build_dataset(is_train, args): 35 | transform = build_transform(is_train, args) 36 | 37 | if args.data_set == 'imagenet': 38 | raise NotImplementedError("Only [cifar10, cifar100, flowers, pets] are supported; \ 39 | for imagenet end-to-end finetuning, please refer to the instructions in the main README.") 40 | 41 | if args.data_set == 'imagenet': 42 | root = os.path.join(args.data_path, 'train' if is_train else 'val') 43 | dataset = datasets.ImageFolder(root, transform=transform) 44 | nb_classes = 1000 45 | 46 | elif args.data_set == 'cifar10': 47 | dataset = datasets.CIFAR10(root=args.data_path, 48 | train=is_train, 49 | download=True, 50 | transform=transform) 51 | nb_classes = 10 52 | elif args.data_set == "cifar100": 53 | dataset = datasets.CIFAR100(root=args.data_path, 54 | train=is_train, 55 | download=True, 56 | transform=transform) 57 | nb_classes = 100 58 | elif args.data_set == "flowers": 59 | dataset = oxford_flowers_dataset.Flowers(root=args.data_path, 60 | train=is_train, 61 | download=False, 62 | transform=transform) 63 | nb_classes = 102 64 | elif args.data_set == "pets": 65 | dataset = oxford_pets_dataset.Pets(root=args.data_path, 66 | train=is_train, 67 | download=False, 68 | transform=transform) 69 | nb_classes = 37 70 | else: 71 | raise NotImplementedError("Only [cifar10, cifar100, flowers, pets] are supported; \ 72 | for imagenet end-to-end finetuning, please refer to the instructions in the main README.") 73 | 74 | return dataset, nb_classes 75 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to make participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies within all project spaces, and it also applies when 49 | an individual is representing the project or its community in public spaces. 50 | Examples of representing a project or community include using an official 51 | project e-mail address, posting via an official social media account, or acting 52 | as an appointed representative at an online or offline event. Representation of 53 | a project may be further defined and clarified by project maintainers. 54 | 55 | This Code of Conduct also applies outside the project spaces when there is a 56 | reasonable belief that an individual's behavior may have a negative impact on 57 | the project or its community. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported by contacting the project team at . All 63 | complaints will be reviewed and investigated and will result in a response that 64 | is deemed necessary and appropriate to the circumstances. The project team is 65 | obligated to maintain confidentiality with regard to the reporter of an incident. 66 | Further details of specific enforcement policies may be posted separately. 67 | 68 | Project maintainers who do not follow or enforce the Code of Conduct in good 69 | faith may face temporary or permanent repercussions as determined by other 70 | members of the project's leadership. 71 | 72 | ## Attribution 73 | 74 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 75 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 76 | 77 | [homepage]: https://www.contributor-covenant.org 78 | 79 | For answers to common questions about this code of conduct, see 80 | https://www.contributor-covenant.org/faq 81 | -------------------------------------------------------------------------------- /generate_train_data.py: -------------------------------------------------------------------------------- 1 | import csv 2 | import glob 3 | import numpy as np 4 | import pandas as pd 5 | import matplotlib.pyplot as plt 6 | from tqdm import tqdm 7 | from PIL import Image 8 | from sklearn.utils import shuffle 9 | from multiprocessing import Pool 10 | 11 | from openslide import OpenSlide 12 | 13 | def get_tissue_mask(slide_path): 14 | ''' 15 | slide_path: path for each slide 16 | ''' 17 | 18 | slide = AllSlide(slide_path) 19 | thumb = slide.read_region((0, 0), slide.level_count-2, slide.level_dimensions[-2]) 20 | 21 | img_RGB = np.array(thumb) 22 | slide_lv = cv2.cvtColor(img_RGB, cv2.COLOR_RGBA2RGB) 23 | slide_lv = cv2.cvtColor(slide_lv, cv2.COLOR_BGR2HSV) 24 | slide_lv = slide_lv[:, :, 1] 25 | 26 | _, tissue_mask = cv2.threshold(slide_lv, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) 27 | tissue_mask[tissue_mask != 0] = 1 28 | 29 | _, label = cv2.connectedComponents(tissue_mask) 30 | tissue_mask = remove_small_objects(label, min_size=64) 31 | tissue_mask = np.array(tissue_mask, np.uint8) 32 | 33 | return Image.fromarray(tissue_mask) 34 | 35 | 36 | def get_mil_data(slide_path, slide_ind, savepath, dataset, num_region=200, ps_region=1024, region_level=1, 37 | num_patch=9, ps_patch=256, threshold_region=220, threshold_patch=240): 38 | ''' 39 | slide_path: path for each slide 40 | slide_id: index of the slide 41 | savepath: path to outpath/tcga-xxxx/ 42 | dataset: index of tcga datasets 43 | num_region: number of regions in a wsi 44 | ps_region: region size 45 | region_level: at which level the region is sampled (patch is sampled at level-1) 46 | num_patch: maximum number of patches in a region 47 | ps_patch: patch size 48 | threshold_*: used to remove the patch from background 49 | ''' 50 | 51 | # generate tissue mask 52 | slide = OpenSlide(slide_path) 53 | # slide_name = slide_path.split('/')[-1].split('.')[0] 54 | out_file_region = os.path.join(savepath, 'region') 55 | out_file_patch = os.path.join(savepath, 'patch') 56 | 57 | tissue_mask = get_tissue_mask(slide_path) 58 | if tissue_mask == None: 59 | print(f'{slide_ind} Skipped......') 60 | return 61 | 62 | w, h = slide.level_dimensions[region_level] 63 | downsample_region = int(slide.level_downsamples[region_level]) 64 | downsample_patch = int(slide.level_downsamples[region_level-1]) 65 | rs_w = int(w/ps_region); rs_h = int(h/ps_region) 66 | delta_hw = (128, ps_region*downsample_region-ps_patch*downsample_patch-128) 67 | 68 | tissue_mask = np.array(tissue_mask.resize((rs_w, rs_h))) 69 | h_list, w_list = np.where(tissue_mask != 0) 70 | 71 | idx = shuffle(list(range(len(h_list)))) 72 | h_select = h_list[idx] * ps_region * downsample_region 73 | w_select = w_list[idx] * ps_region * downsample_region 74 | 75 | # random select regions 76 | region_count = 0 77 | for i in range(len(h_select)): 78 | region = slide.read_region((w_select[i], h_select[i]), region_level, (ps_region, ps_region)) 79 | 80 | if np.mean(region) < threshold_region: 81 | region.resize((ps_patch, ps_patch)).save(os.path.join(out_file_region, f'{slide_ind}_{i}.png')) 82 | region_count += 1 83 | 84 | # random select patchs 85 | for j in range(num_patch): 86 | delta_h = np.random.randint(delta_hw[0], delta_hw[1]) 87 | delta_w = np.random.randint(delta_hw[0], delta_hw[1]) 88 | patch = slide.read_region((w_select[i]+delta_w, h_select[i]+delta_h), region_level-1, (ps_patch, ps_patch)) 89 | if np.mean(patch) < threshold_patch: 90 | patch.save(os.path.join(out_file_patch, f'{slide_ind}_{i}_{j}.png')) 91 | 92 | if region_count >= num_region: 93 | break 94 | 95 | print(f'{slide_ind} Done......') 96 | 97 | slide_list = glob.glob('./*.svs') 98 | 99 | with Pool(processes=8) as p: 100 | p.map(get_mil_data, slide_list) -------------------------------------------------------------------------------- /transfer/README.md: -------------------------------------------------------------------------------- 1 | ## MoCo v3 Transfer Learning with ViT 2 | 3 | This folder includes the transfer learning experiments on CIFAR-10, CIFAR-100, Flowers and Pets datasets. We provide finetuning recipes for the ViT-Base model. 4 | 5 | ### Transfer Results 6 | 7 | The following results are based on ImageNet-1k self-supervised pre-training, followed by end-to-end fine-tuning on downstream datasets. All results are based on a batch size of 128 and 100 training epochs. 8 | 9 | #### ViT-Base, transfer learning 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 |
datasetpretrain
epochs
pretrain
crops
finetune
epochs
transfer
acc
CIFAR-103002x22410098.9
CIFAR-1003002x22410090.5
Flowers3002x22410097.7
Pets3002x22410093.2
48 | 49 | Similar to the end-to-end fine-tuning experiment on ImageNet, the transfer learning results are also obtained using the [DEiT](https://github.com/facebookresearch/deit) repo, with the default model [deit_base_patch16_224]. 50 | 51 | ### Preparation: Transfer learning with ViT 52 | 53 | To perform transfer learning for ViT, use our script to convert the pre-trained ViT checkpoint to [DEiT](https://github.com/facebookresearch/deit) format: 54 | ``` 55 | python convert_to_deit.py \ 56 | --input [your checkpoint path]/[your checkpoint file].pth.tar \ 57 | --output [target checkpoint file].pth 58 | ``` 59 | Then copy (or replace) the following files to the DeiT folder: 60 | ``` 61 | datasets.py 62 | oxford_flowers_dataset.py 63 | oxford_pets_dataset.py 64 | ``` 65 | 66 | #### Download and prepare the datasets 67 | 68 | Pets [\[Homepage\]](https://www.robots.ox.ac.uk/~vgg/data/pets/) 69 | ``` 70 | ./data/ 71 | └── ./data/pets/ 72 | ├── ./data/pets/annotations/ # split and label files 73 | └── ./data/pets/images/ # data images 74 | ``` 75 | 76 | Flowers [\[Homepage\]](https://www.robots.ox.ac.uk/~vgg/data/flowers/102/) 77 | ``` 78 | ./data/ 79 | └── ./data/flowers/ 80 | ├── ./data/flowers/jpg/ # jpg images 81 | ├── ./data/flowers/setid.mat # dataset split 82 | └── ./data/flowers/imagelabels.mat # labels 83 | ``` 84 | 85 | 86 | CIFAR-10/CIFAR-100 datasets will be downloaded automatically. 87 | 88 | 89 | ### Transfer learning scripts (with a 8-GPU machine): 90 | 91 | #### CIFAR-10 92 | ``` 93 | python -u -m torch.distributed.launch --nproc_per_node=8 --use_env main.py \ 94 | --batch-size 128 --output_dir [your output dir path] --epochs 100 --lr 3e-4 --weight-decay 0.1 \ 95 | --no-pin-mem --warmup-epochs 3 --data-set cifar10 --data-path [cifar-10 data path] --no-repeated-aug \ 96 | --resume [your pretrain checkpoint file] \ 97 | --reprob 0.0 --drop-path 0.1 --mixup 0.8 --cutmix 1 98 | ``` 99 | 100 | #### CIFAR-100 101 | ``` 102 | python -u -m torch.distributed.launch --nproc_per_node=8 --use_env main.py \ 103 | --batch-size 128 --output_dir [your output dir path] --epochs 100 --lr 3e-4 --weight-decay 0.1 \ 104 | --no-pin-mem --warmup-epochs 3 --data-set cifar100 --data-path [cifar-100 data path] --no-repeated-aug \ 105 | --resume [your pretrain checkpoint file] \ 106 | --reprob 0.0 --drop-path 0.1 --mixup 0.5 --cutmix 1 107 | ``` 108 | 109 | #### Flowers 110 | ``` 111 | python -u -m torch.distributed.launch --nproc_per_node=8 --use_env main.py \ 112 | --batch-size 128 --output_dir [your output dir path] --epochs 100 --lr 3e-4 --weight-decay 0.3 \ 113 | --no-pin-mem --warmup-epochs 3 --data-set flowers --data-path [oxford-flowers data path] --no-repeated-aug \ 114 | --resume [your pretrain checkpoint file] \ 115 | --reprob 0.25 --drop-path 0.1 --mixup 0 --cutmix 0 116 | ``` 117 | 118 | #### Pets 119 | ``` 120 | python -u -m torch.distributed.launch --nproc_per_node=8 --use_env main.py \ 121 | --batch-size 128 --output_dir [your output dir path] --epochs 100 --lr 3e-4 --weight-decay 0.1 \ 122 | --no-pin-mem --warmup-epochs 3 --data-set pets --data-path [oxford-pets data path] --no-repeated-aug \ 123 | --resume [your pretrain checkpoint file] \ 124 | --reprob 0 --drop-path 0 --mixup 0.8 --cutmix 0 125 | ``` 126 | 127 | **Note**: 128 | Similar to the ImageNet end-to-end finetuning experiment, we use `--resume` rather than `--finetune` in the DeiT repo, as its `--finetune` option trains under eval mode. When loading the pre-trained model, revise `model_without_ddp.load_state_dict(checkpoint['model'])` with `strict=False`. 129 | -------------------------------------------------------------------------------- /CONFIG.md: -------------------------------------------------------------------------------- 1 | ## MoCo v3 Reference Setups and Models 2 | 3 | Here we document the reference commands for pre-training and evaluating various MoCo v3 models. 4 | 5 | ### ResNet-50 models 6 | 7 | With batch 4096, the training of all ResNet-50 models can fit into 2 nodes with a total of 16 Volta 32G GPUs. 8 | 9 |
10 | ResNet-50, 100-epoch pre-training. 11 | 12 | On the first node, run: 13 | ``` 14 | python main_moco.py \ 15 | --moco-m-cos --crop-min=.2 \ 16 | --dist-url 'tcp://[your first node address]:[specified port]' \ 17 | --multiprocessing-distributed --world-size 2 --rank 0 \ 18 | [your imagenet-folder with train and val folders] 19 | ``` 20 | On the second node, run the same command with `--rank 1`. 21 |
22 | 23 |
24 | ResNet-50, 300-epoch pre-training. 25 | 26 | On the first node, run: 27 | ``` 28 | python main_moco.py \ 29 | --lr=.3 --epochs=300 \ 30 | --moco-m-cos --crop-min=.2 \ 31 | --dist-url 'tcp://[your first node address]:[specified port]' \ 32 | --multiprocessing-distributed --world-size 2 --rank 0 \ 33 | [your imagenet-folder with train and val folders] 34 | ``` 35 | On the second node, run the same command with `--rank 1`. 36 |
37 | 38 |
39 | ResNet-50, 1000-epoch pre-training. 40 | 41 | On the first node, run: 42 | ``` 43 | python main_moco.py \ 44 | --lr=.3 --wd=1.5e-6 --epochs=1000 \ 45 | --moco-m=0.996 --moco-m-cos --crop-min=.2 \ 46 | --dist-url 'tcp://[your first node address]:[specified port]' \ 47 | --multiprocessing-distributed --world-size 2 --rank 0 \ 48 | [your imagenet-folder with train and val folders] 49 | ``` 50 | On the second node, run the same command with `--rank 1`. 51 |
52 | 53 |
54 | ResNet-50, linear classification. 55 | 56 | Run on single node: 57 | ``` 58 | python main_lincls.py \ 59 | --dist-url 'tcp://localhost:10001' \ 60 | --multiprocessing-distributed --world-size 1 --rank 0 \ 61 | --pretrained [your checkpoint path]/[your checkpoint file].pth.tar \ 62 | [your imagenet-folder with train and val folders] 63 | ``` 64 |
65 | 66 | Below are our pre-trained ResNet-50 models and logs. 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 82 | 83 | 84 | 85 | 86 | 87 | 89 | 90 | 91 | 92 | 93 | 94 | 96 | 97 |
pretrain
epochs
linear
acc
pretrain
files
linear
files
10068.9chptchpt / 81 | log
30072.8chptchpt / 88 | log
100074.6chptchpt / 95 | log
98 | 99 | 100 | ### ViT Models 101 | 102 | All ViT models are pre-trained for 300 epochs with AdamW. 103 | 104 |
105 | ViT-Small, 1-node (8-GPU), 1024-batch pre-training. 106 | 107 | This setup fits into a single node of 8 Volta 32G GPUs, for ease of debugging. 108 | ``` 109 | python main_moco.py \ 110 | -a vit_small -b 1024 \ 111 | --optimizer=adamw --lr=1.5e-4 --weight-decay=.1 \ 112 | --epochs=300 --warmup-epochs=40 \ 113 | --stop-grad-conv1 --moco-m-cos --moco-t=.2 \ 114 | --dist-url 'tcp://localhost:10001' \ 115 | --multiprocessing-distributed --world-size 1 --rank 0 \ 116 | [your imagenet-folder with train and val folders] 117 | ``` 118 | 119 |
120 | 121 |
122 | ViT-Small, 4-node (32-GPU) pre-training. 123 | 124 | On the first node, run: 125 | ``` 126 | python main_moco.py \ 127 | -a vit_small \ 128 | --optimizer=adamw --lr=1.5e-4 --weight-decay=.1 \ 129 | --epochs=300 --warmup-epochs=40 \ 130 | --stop-grad-conv1 --moco-m-cos --moco-t=.2 \ 131 | --dist-url 'tcp://[your first node address]:[specified port]' \ 132 | --multiprocessing-distributed --world-size 8 --rank 0 \ 133 | [your imagenet-folder with train and val folders] 134 | ``` 135 | On other nodes, run the same command with `--rank 1`, ..., `--rank 3` respectively. 136 |
137 | 138 |
139 | ViT-Small, linear classification. 140 | 141 | Run on single node: 142 | ``` 143 | python main_lincls.py \ 144 | -a vit_small --lr=3 \ 145 | --dist-url 'tcp://localhost:10001' \ 146 | --multiprocessing-distributed --world-size 1 --rank 0 \ 147 | --pretrained [your checkpoint path]/[your checkpoint file].pth.tar \ 148 | [your imagenet-folder with train and val folders] 149 | ``` 150 |
151 | 152 |
153 | ViT-Base, 8-node (64-GPU) pre-training. 154 | 155 | ``` 156 | python main_moco.py \ 157 | -a vit_base \ 158 | --optimizer=adamw --lr=1.5e-4 --weight-decay=.1 \ 159 | --epochs=300 --warmup-epochs=40 \ 160 | --stop-grad-conv1 --moco-m-cos --moco-t=.2 \ 161 | --dist-url 'tcp://[your first node address]:[specified port]' \ 162 | --multiprocessing-distributed --world-size 8 --rank 0 \ 163 | [your imagenet-folder with train and val folders] 164 | ``` 165 | On other nodes, run the same command with `--rank 1`, ..., `--rank 7` respectively. 166 |
167 | 168 |
169 | ViT-Base, linear classification. 170 | 171 | Run on single node: 172 | ``` 173 | python main_lincls.py \ 174 | -a vit_base --lr=3 \ 175 | --dist-url 'tcp://localhost:10001' \ 176 | --multiprocessing-distributed --world-size 1 --rank 0 \ 177 | --pretrained [your checkpoint path]/[your checkpoint file].pth.tar \ 178 | [your imagenet-folder with train and val folders] 179 | ``` 180 |
181 | 182 | 183 | Below are our pre-trained ViT models and logs (batch 4096). 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 209 | 210 |
modelpretrain
epochs
linear
acc
pretrain
files
linear
files
ViT-Small30073.2chptchpt / 200 | log
ViT-Base30076.7chptchpt / 208 | log
211 | -------------------------------------------------------------------------------- /moco/loader.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | from PIL import Image, ImageFilter, ImageOps 8 | import math 9 | import random 10 | import torchvision.transforms.functional as tf 11 | from torch.utils.data import Dataset 12 | import torchvision.transforms as transforms 13 | import pandas as pd 14 | import os 15 | import numpy as np 16 | import cv2 17 | 18 | def check_png(name): 19 | return (name) and ('png' in name) 20 | 21 | class TwoCropsTransform: 22 | """Take two random crops of one image""" 23 | 24 | def __init__(self, base_transform1, base_transform2): 25 | self.base_transform1 = base_transform1 26 | self.base_transform2 = base_transform2 27 | 28 | def __call__(self, x): 29 | im1 = self.base_transform1(x) 30 | im2 = self.base_transform2(x) 31 | return [im1, im2] 32 | 33 | 34 | class GaussianBlur(object): 35 | """Gaussian blur augmentation from SimCLR: https://arxiv.org/abs/2002.05709""" 36 | 37 | def __init__(self, sigma=[.1, 2.]): 38 | self.sigma = sigma 39 | 40 | def __call__(self, x): 41 | sigma = random.uniform(self.sigma[0], self.sigma[1]) 42 | x = x.filter(ImageFilter.GaussianBlur(radius=sigma)) 43 | return x 44 | 45 | 46 | class Solarize(object): 47 | """Solarize augmentation from BYOL: https://arxiv.org/abs/2006.07733""" 48 | 49 | def __call__(self, x): 50 | return ImageOps.solarize(x) 51 | 52 | class TCGADataset(Dataset): 53 | def __init__(self, 54 | data_dir, 55 | used_TCGA, 56 | transform=None): 57 | # data_dir: *TCGA_crop*/TCGA-xxxx/region(patch)/xxxxx.png 58 | 59 | # get all img paths 60 | 61 | self.data_paths = [] 62 | for tcga in used_TCGA: 63 | path_prefix = os.path.join(data_dir, tcga) 64 | patch_paths = [os.path.join(path_prefix,'patch',d) for d in os.listdir(os.path.join(path_prefix,'patch')) if check_png(d)] 65 | region_paths = [os.path.join(path_prefix,'region',d) for d in os.listdir(os.path.join(path_prefix,'region')) if check_png(d)] 66 | self.data_paths += patch_paths + region_paths 67 | self.transform = transform 68 | 69 | def __getitem__(self, idx): 70 | img_path = self.data_paths[idx] 71 | 72 | try: 73 | img = Image.open(img_path).convert('RGB') 74 | except: 75 | img = Image.new('RGB', (224,224)) 76 | 77 | 78 | if self.transform is not None: 79 | img = self.transform(img) 80 | 81 | return img 82 | 83 | def __len__(self): 84 | return len(self.data_paths) 85 | 86 | 87 | class BridgeDataset(Dataset): 88 | def __init__(self, 89 | data_dir, 90 | used_TCGA, 91 | meta_info_path, 92 | patch_transform, 93 | region_transform): 94 | 95 | # data_dir: *TCGA_crop*/TCGA-xxxx/region(patch)/xxxxx.png 96 | 97 | self.data_dir = data_dir 98 | self.patch_name_list = [] 99 | 100 | for tcga in used_TCGA: 101 | path_prefix = os.path.join(data_dir, tcga) 102 | patch_suffixes = [os.path.join(tcga,'patch',d) for d in os.listdir(os.path.join(path_prefix,'patch')) if check_png(d)] 103 | self.patch_name_list += patch_suffixes 104 | 105 | self.patch_transform = patch_transform 106 | self.region_transform = region_transform 107 | self.ref_transform = transforms.Compose([ 108 | transforms.Resize(16), 109 | transforms.RandomApply([ 110 | transforms.ColorJitter(0.4, 0.4, 0.2, 0.1) # not strengthened 111 | ], p=0.8), 112 | transforms.RandomGrayscale(p=0.2), 113 | transforms.RandomHorizontalFlip(), 114 | transforms.ToTensor() 115 | ]) 116 | 117 | def __getitem__(self, idx): 118 | patch_name = self.patch_name_list[idx] # TCGA-xxxx/patch/a_b_c.png c=0, 1, ..., 5 119 | region_name = patch_name[:-6] + '.png' # TCGA-xxxx/region/a_b.png 120 | region_name = region_name.replace('patch', 'region') 121 | patch_path = self.data_dir + patch_name 122 | region_path = self.data_dir + region_name 123 | 124 | try: 125 | patch = Image.open(patch_path).convert('RGB') 126 | region = Image.open(region_path).convert('RGB') 127 | except: 128 | patch = Image.new('RGB', (224,224)) 129 | region = Image.new('RGB', (224,224)) 130 | 131 | 132 | patchs = self.patch_transform(patch) 133 | region = self.region_transform(region) 134 | ref = self.ref_transform(patch) 135 | 136 | return patchs + [ref, region] 137 | 138 | def __len__(self): 139 | return len(self.patch_name_list) 140 | 141 | class BCIDataset(Dataset): 142 | def __init__(self, 143 | data_dir, 144 | transform_he, 145 | transform_ihc, 146 | transform_ihc_little, 147 | color_jitter_ihc): 148 | 149 | self.data_dir = data_dir 150 | self.patch_name_list = [d for d in os.listdir(os.path.join(data_dir, 'HE', 'train')) if 'png' in d] 151 | 152 | self.transform_he = transform_he 153 | self.transform_ihc = transform_ihc 154 | self.transform_ihc_little = transform_ihc_little 155 | self.color_jitter_ihc = color_jitter_ihc 156 | 157 | def __getitem__(self, idx): 158 | patch_name = self.patch_name_list[idx] 159 | he_path = os.path.join(self.data_dir, 'HE', 'train', patch_name) 160 | ihc_path = os.path.join(self.data_dir, 'IHC', 'train', patch_name) 161 | 162 | # Loading images 163 | he_img = Image.open(he_path).convert('RGB') 164 | ihc_img = Image.open(ihc_path).convert('RGB') 165 | 166 | he_img = self.transform_he(he_img) 167 | 168 | ihc_img = self.color_jitter_ihc(ihc_img) 169 | ihc_img_little = self.transform_ihc_little(ihc_img) 170 | ihc_img = self.transform_ihc(ihc_img) 171 | 172 | return (he_img, ihc_img, ihc_img_little) 173 | 174 | def __len__(self): 175 | return len(self.patch_name_list) 176 | 177 | class HyReCoDataset(Dataset): 178 | def __init__(self, 179 | data_dir, 180 | transform_he, 181 | transform_ihc, 182 | transform_ihc_little, 183 | color_jitter_ihc): 184 | 185 | self.data_dir = data_dir 186 | self.stains = os.listdir(data_dir) 187 | self.stains.remove('HE') 188 | wsi_names = os.listdir(os.path.join(data_dir, 'HE')) 189 | self.patch_name_list = [] 190 | for wsi_name in wsi_names: 191 | self.patch_name_list += [d for d in os.listdir(os.path.join(data_dir, 'HE', wsi_name)) if 'png' in d] 192 | 193 | self.transform_he = transform_he 194 | self.transform_ihc = transform_ihc 195 | self.transform_ihc_little = transform_ihc_little 196 | self.color_jitter_ihc = color_jitter_ihc 197 | 198 | def __getitem__(self, idx): 199 | to_stain = self.stains[idx // len(self.patch_name_list)] 200 | re_idx = idx % len(self.patch_name_list) 201 | patch_name = self.patch_name_list[re_idx] 202 | wsi_name = patch_name.split('_')[0] 203 | he_path = os.path.join(self.data_dir, 'HE', wsi_name, patch_name) 204 | ihc_path = os.path.join(self.data_dir, to_stain, wsi_name, patch_name) 205 | 206 | # Loading images 207 | he_img = Image.open(he_path).convert('RGB') 208 | ihc_img = Image.open(ihc_path).convert('RGB') 209 | 210 | he_img = self.transform_he(he_img) 211 | 212 | ihc_img = self.color_jitter_ihc(ihc_img) 213 | ihc_img_little = self.transform_ihc_little(ihc_img) 214 | ihc_img = self.transform_ihc(ihc_img) 215 | 216 | return (he_img, ihc_img, ihc_img_little) 217 | 218 | def __len__(self): 219 | return len(self.patch_name_list)*len(self.stains) -------------------------------------------------------------------------------- /vits.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | import math 8 | import torch 9 | import torch.nn as nn 10 | from functools import partial, reduce 11 | from operator import mul 12 | 13 | from timm.models.vision_transformer import VisionTransformer, _cfg 14 | from timm.models.layers.helpers import to_2tuple 15 | from timm.models.layers import PatchEmbed 16 | 17 | __all__ = [ 18 | 'vit_small', 19 | 'vit_base', 20 | 'vit_conv_small', 21 | 'vit_conv_base', 22 | ] 23 | 24 | 25 | class VisionTransformerMoCo(VisionTransformer): 26 | def __init__(self, pretext_token=True, stop_grad_conv1=False, **kwargs): 27 | super().__init__(**kwargs) 28 | # inserting a new token 29 | self.num_prefix_tokens += (1 if pretext_token else 0) 30 | self.pretext_token = nn.Parameter(torch.ones(1, 1, self.embed_dim)) if pretext_token else None 31 | embed_len = self.patch_embed.num_patches if self.no_embed_class else self.patch_embed.num_patches + 1 32 | embed_len += 1 if pretext_token else 0 33 | self.embed_len = embed_len 34 | 35 | # Use fixed 2D sin-cos position embedding 36 | self.build_2d_sincos_position_embedding() 37 | 38 | # weight initialization 39 | for name, m in self.named_modules(): 40 | if isinstance(m, nn.Linear): 41 | if 'qkv' in name: 42 | # treat the weights of Q, K, V separately 43 | val = math.sqrt(6. / float(m.weight.shape[0] // 3 + m.weight.shape[1])) 44 | nn.init.uniform_(m.weight, -val, val) 45 | else: 46 | nn.init.xavier_uniform_(m.weight) 47 | nn.init.zeros_(m.bias) 48 | nn.init.normal_(self.cls_token, std=1e-6) 49 | nn.init.normal_(self.pretext_token, std=1e-6) 50 | 51 | if isinstance(self.patch_embed, PatchEmbed): 52 | # xavier_uniform initialization 53 | val = math.sqrt(6. / float(3 * reduce(mul, self.patch_embed.patch_size, 1) + self.embed_dim)) 54 | nn.init.uniform_(self.patch_embed.proj.weight, -val, val) 55 | nn.init.zeros_(self.patch_embed.proj.bias) 56 | 57 | if stop_grad_conv1: 58 | self.patch_embed.proj.weight.requires_grad = False 59 | self.patch_embed.proj.bias.requires_grad = False 60 | 61 | @torch.jit.ignore 62 | def no_weight_decay(self): 63 | return {'pos_embed', 'cls_token', 'dist_token', 'pretext_token'} 64 | 65 | def _pos_embed(self, x): 66 | if self.no_embed_class: 67 | # deit-3, updated JAX (big vision) 68 | # position embedding does not overlap with class token, add then concat 69 | x = x + self.pos_embed 70 | if self.cls_token is not None: 71 | x = torch.cat((self.cls_token.expand(x.shape[0], -1, -1), x), dim=1) 72 | if self.pretext_token is not None: 73 | x = torch.cat((self.pretext_token.expand(x.shape[0], -1, -1), x), dim=1) 74 | else: 75 | # original timm, JAX, and deit vit impl 76 | # pos_embed has entry for class token, concat then add 77 | if self.cls_token is not None: 78 | x = torch.cat((self.cls_token.expand(x.shape[0], -1, -1), x), dim=1) 79 | if self.pretext_token is not None: 80 | x = torch.cat((self.pretext_token.expand(x.shape[0], -1, -1), x), dim=1) 81 | x = x + self.pos_embed 82 | return self.pos_drop(x) 83 | 84 | def _ref_embed(self, ref): 85 | B, C, H, W = ref.shape 86 | ref = self.patch_embed.proj(ref) 87 | if self.patch_embed.flatten: 88 | ref = ref.flatten(2).transpose(1, 2) # BCHW -> BNC 89 | ref = self.patch_embed.norm(ref) 90 | return ref 91 | 92 | 93 | def _pos_embed_with_ref(self, x, ref): 94 | pretext_tokens = self.pretext_token.expand(x.shape[0], -1, -1) * 0 + ref 95 | if self.no_embed_class: 96 | # deit-3, updated JAX (big vision) 97 | # position embedding does not overlap with class token, add then concat 98 | x = x + self.pos_embed 99 | if self.cls_token is not None: 100 | x = torch.cat((self.cls_token.expand(x.shape[0], -1, -1), x), dim=1) 101 | if self.pretext_token is not None: 102 | x = torch.cat((pretext_tokens, x), dim=1) 103 | else: 104 | # original timm, JAX, and deit vit impl 105 | # pos_embed has entry for class token, concat then add 106 | if self.cls_token is not None: 107 | x = torch.cat((self.cls_token.expand(x.shape[0], -1, -1), x), dim=1) 108 | if self.pretext_token is not None: 109 | x = torch.cat((pretext_tokens, x), dim=1) 110 | x = x + self.pos_embed 111 | return self.pos_drop(x) 112 | 113 | def forward_features(self, x, ref=None): 114 | x = self.patch_embed(x) 115 | if ref is None: 116 | x = self._pos_embed(x) 117 | else: 118 | ref = self._ref_embed(ref).mean(dim=1, keepdim=True) 119 | x = self._pos_embed_with_ref(x, ref) 120 | # x = self.norm_pre(x) 121 | if self.grad_checkpointing and not torch.jit.is_scripting(): 122 | x = checkpoint_seq(self.blocks, x) 123 | else: 124 | x = self.blocks(x) 125 | x = self.norm(x) 126 | return x 127 | 128 | def forward_head(self, x, pre_logits: bool = False): 129 | if self.global_pool: 130 | x = x[:, self.num_prefix_tokens:].mean(dim=1) if self.global_pool == 'avg' else x[:, 1] 131 | x = self.fc_norm(x) 132 | return x if pre_logits else self.head(x) 133 | 134 | def forward(self, x, ref=None): 135 | x_out = self.forward_features(x, ref) 136 | x = self.forward_head(x_out) 137 | return x_out, x 138 | 139 | def build_2d_sincos_position_embedding(self, temperature=10000.): 140 | h, w = self.patch_embed.grid_size 141 | grid_w = torch.arange(w, dtype=torch.float32) 142 | grid_h = torch.arange(h, dtype=torch.float32) 143 | grid_w, grid_h = torch.meshgrid(grid_w, grid_h) 144 | assert self.embed_dim % 4 == 0, 'Embed dimension must be divisible by 4 for 2D sin-cos position embedding' 145 | pos_dim = self.embed_dim // 4 146 | omega = torch.arange(pos_dim, dtype=torch.float32) / pos_dim 147 | omega = 1. / (temperature**omega) 148 | out_w = torch.einsum('m,d->md', [grid_w.flatten(), omega]) 149 | out_h = torch.einsum('m,d->md', [grid_h.flatten(), omega]) 150 | pos_emb = torch.cat([torch.sin(out_w), torch.cos(out_w), torch.sin(out_h), torch.cos(out_h)], dim=1)[None, :, :] 151 | 152 | assert self.num_prefix_tokens == 2, 'Assuming two and only two tokens, [pretext][cls]' 153 | pe_token = torch.zeros([1, 2, self.embed_dim], dtype=torch.float32) 154 | self.pos_embed = nn.Parameter(torch.cat([pe_token, pos_emb], dim=1)) 155 | self.pos_embed.requires_grad = False 156 | 157 | 158 | class ConvStem(nn.Module): 159 | """ 160 | ConvStem, from Early Convolutions Help Transformers See Better, Tete et al. https://arxiv.org/abs/2106.14881 161 | """ 162 | def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, norm_layer=None, flatten=True): 163 | super().__init__() 164 | 165 | assert patch_size == 16, 'ConvStem only supports patch size of 16' 166 | assert embed_dim % 8 == 0, 'Embed dimension must be divisible by 8 for ConvStem' 167 | 168 | img_size = to_2tuple(img_size) 169 | patch_size = to_2tuple(patch_size) 170 | self.img_size = img_size 171 | self.patch_size = patch_size 172 | self.grid_size = (img_size[0] // patch_size[0], img_size[1] // patch_size[1]) 173 | self.num_patches = self.grid_size[0] * self.grid_size[1] 174 | self.flatten = flatten 175 | 176 | # build stem, similar to the design in https://arxiv.org/abs/2106.14881 177 | stem = [] 178 | input_dim, output_dim = 3, embed_dim // 8 179 | for l in range(4): 180 | stem.append(nn.Conv2d(input_dim, output_dim, kernel_size=3, stride=2, padding=1, bias=False)) 181 | stem.append(nn.BatchNorm2d(output_dim)) 182 | stem.append(nn.ReLU(inplace=True)) 183 | input_dim = output_dim 184 | output_dim *= 2 185 | stem.append(nn.Conv2d(input_dim, embed_dim, kernel_size=1)) 186 | self.proj = nn.Sequential(*stem) 187 | 188 | self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity() 189 | 190 | def forward(self, x): 191 | B, C, H, W = x.shape 192 | assert H == self.img_size[0] and W == self.img_size[1], \ 193 | f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})." 194 | x = self.proj(x) 195 | if self.flatten: 196 | x = x.flatten(2).transpose(1, 2) # BCHW -> BNC 197 | x = self.norm(x) 198 | return x 199 | 200 | 201 | def vit_small(**kwargs): 202 | model = VisionTransformerMoCo( 203 | patch_size=16, embed_dim=384, depth=12, num_heads=12, mlp_ratio=4, qkv_bias=True, 204 | norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs) 205 | model.default_cfg = _cfg() 206 | return model 207 | 208 | def vit_base(**kwargs): 209 | model = VisionTransformerMoCo( 210 | patch_size=16, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4, qkv_bias=True, 211 | norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs) 212 | model.default_cfg = _cfg() 213 | return model 214 | 215 | def vit_conv_small(**kwargs): 216 | # minus one ViT block 217 | model = VisionTransformerMoCo( 218 | patch_size=16, embed_dim=384, depth=11, num_heads=12, mlp_ratio=4, qkv_bias=True, 219 | norm_layer=partial(nn.LayerNorm, eps=1e-6), embed_layer=ConvStem, **kwargs) 220 | model.default_cfg = _cfg() 221 | return model 222 | 223 | def vit_conv_base(**kwargs): 224 | # minus one ViT block 225 | model = VisionTransformerMoCo( 226 | patch_size=16, embed_dim=768, depth=11, num_heads=12, mlp_ratio=4, qkv_bias=True, 227 | norm_layer=partial(nn.LayerNorm, eps=1e-6), embed_layer=ConvStem, **kwargs) 228 | model.default_cfg = _cfg() 229 | return model -------------------------------------------------------------------------------- /moco/mae.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. 2 | # All rights reserved. 3 | 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # -------------------------------------------------------- 7 | # References: 8 | # timm: https://github.com/rwightman/pytorch-image-models/tree/master/timm 9 | # DeiT: https://github.com/facebookresearch/deit 10 | # -------------------------------------------------------- 11 | 12 | from functools import partial 13 | 14 | 15 | import torch 16 | import torchvision 17 | import torch.nn as nn 18 | from torchvision.transforms.functional import InterpolationMode 19 | from timm.models.vision_transformer import PatchEmbed, Block 20 | 21 | # from util.pos_embed import get_2d_sincos_pos_embed 22 | 23 | class MAE(nn.Module): 24 | """ Masked Autoencoder with VisionTransformer backbone 25 | """ 26 | def __init__(self, img_size=224, patch_size=16, in_chans=3, 27 | embed_dim=1024, depth=24, num_heads=16, 28 | decoder_embed_dim=512, decoder_depth=8, decoder_num_heads=16, 29 | mlp_ratio=4., norm_layer=nn.LayerNorm, norm_pix_loss=False): 30 | super().__init__() 31 | 32 | # -------------------------------------------------------------------------- 33 | # image encoder specifics 34 | self.patch_embed = PatchEmbed(img_size, patch_size, in_chans, embed_dim) 35 | num_patches = self.patch_embed.num_patches 36 | 37 | self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) 38 | self.pretext_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) 39 | self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 2, embed_dim), requires_grad=False) # fixed sin-cos embedding 40 | 41 | self.blocks = nn.ModuleList([ 42 | Block(embed_dim, num_heads, mlp_ratio, qkv_bias=True, norm_layer=norm_layer) 43 | for i in range(depth)]) 44 | self.norm = norm_layer(embed_dim) 45 | # -------------------------------------------------------------------------- 46 | 47 | # -------------------------------------------------------------------------- 48 | # image decoder specifics 49 | self.decoder_embed = nn.Linear(embed_dim, decoder_embed_dim, bias=True) 50 | 51 | self.mask_token = nn.Parameter(torch.zeros(1, 1, decoder_embed_dim*2)) 52 | 53 | self.decoder_pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, decoder_embed_dim*2), requires_grad=False) # fixed sin-cos embedding 54 | 55 | self.decoder_blocks = nn.ModuleList([ 56 | Block(decoder_embed_dim*2, decoder_num_heads, mlp_ratio, qkv_bias=True, norm_layer=norm_layer) 57 | for i in range(decoder_depth)]) 58 | 59 | self.decoder_norm = norm_layer(decoder_embed_dim*2) 60 | self.decoder_pred = nn.Linear(decoder_embed_dim*2, (patch_size)**2 * in_chans, bias=True) 61 | 62 | self.initialize_weights() 63 | 64 | def build_2d_sincos_position_embedding(self, temperature=10000.): 65 | h, w = self.patch_embed.grid_size 66 | grid_w = torch.arange(w, dtype=torch.float32) 67 | grid_h = torch.arange(h, dtype=torch.float32) 68 | grid_w, grid_h = torch.meshgrid(grid_w, grid_h) 69 | assert self.pos_embed.shape[-1] % 4 == 0, 'Embed dimension must be divisible by 4 for 2D sin-cos position embedding' 70 | pos_dim = self.pos_embed.shape[-1] // 4 71 | omega = torch.arange(pos_dim, dtype=torch.float32) / pos_dim 72 | omega = 1. / (temperature**omega) 73 | out_w = torch.einsum('m,d->md', [grid_w.flatten(), omega]) 74 | out_h = torch.einsum('m,d->md', [grid_h.flatten(), omega]) 75 | pos_emb = torch.cat([torch.sin(out_w), torch.cos(out_w), torch.sin(out_h), torch.cos(out_h)], dim=1)[None, :, :] 76 | pe_token = torch.zeros([1, 2, self.pos_embed.shape[-1]], dtype=torch.float32) 77 | self.pos_embed = nn.Parameter(torch.cat([pe_token, pos_emb], dim=1)) 78 | self.pos_embed.requires_grad = False 79 | 80 | assert self.decoder_pos_embed.shape[-1] % 4 == 0, 'Embed dimension must be divisible by 4 for 2D sin-cos position embedding' 81 | d_pos_dim = self.decoder_pos_embed.shape[-1] // 4 82 | d_omega = torch.arange(d_pos_dim, dtype=torch.float32) / d_pos_dim 83 | d_omega = 1. / (temperature**d_omega) 84 | d_out_w = torch.einsum('m,d->md', [grid_w.flatten(), d_omega]) 85 | d_out_h = torch.einsum('m,d->md', [grid_h.flatten(), d_omega]) 86 | d_pos_emb = torch.cat([torch.sin(d_out_w), torch.cos(d_out_w), torch.sin(d_out_h), torch.cos(d_out_h)], dim=1)[None, :, :] 87 | d_pe_token = torch.zeros([1, 1, self.decoder_pos_embed.shape[-1]], dtype=torch.float32) 88 | self.decoder_pos_embed = nn.Parameter(torch.cat([d_pe_token, d_pos_emb], dim=1)) 89 | self.decoder_pos_embed.requires_grad = False 90 | 91 | def initialize_weights(self): 92 | # initialization 93 | # initialize (and freeze) pos_embed by sin-cos embedding 94 | # pos_embed = get_2d_sincos_pos_embed(self.pos_embed.shape[-1], int(self.patch_embed.num_patches**.5), cls_token=True) 95 | # self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0)) 96 | 97 | # decoder_pos_embed = get_2d_sincos_pos_embed(self.decoder_pos_embed.shape[-1], int(self.patch_embed.num_patches**.5), cls_token=True) 98 | # self.decoder_pos_embed.data.copy_(torch.from_numpy(decoder_pos_embed).float().unsqueeze(0)) 99 | 100 | self.build_2d_sincos_position_embedding() 101 | 102 | # initialize patch_embed like nn.Linear (instead of nn.Conv2d) 103 | w = self.patch_embed.proj.weight.data 104 | torch.nn.init.xavier_uniform_(w.view([w.shape[0], -1])) 105 | 106 | # timm's trunc_normal_(std=.02) is effectively normal_(std=0.02) as cutoff is too big (2.) 107 | torch.nn.init.normal_(self.cls_token, std=.02) 108 | torch.nn.init.normal_(self.pretext_token, std=.02) 109 | torch.nn.init.normal_(self.mask_token, std=.02) 110 | 111 | # initialize nn.Linear and nn.LayerNorm 112 | self.apply(self._init_weights) 113 | 114 | def _init_weights(self, m): 115 | if isinstance(m, nn.Linear): 116 | # we use xavier_uniform following official JAX ViT: 117 | torch.nn.init.xavier_uniform_(m.weight) 118 | if isinstance(m, nn.Linear) and m.bias is not None: 119 | nn.init.constant_(m.bias, 0) 120 | elif isinstance(m, nn.LayerNorm): 121 | nn.init.constant_(m.bias, 0) 122 | nn.init.constant_(m.weight, 1.0) 123 | 124 | def patchify(self, imgs): 125 | """ 126 | imgs: (N, 3, H, W) 127 | x: (N, L, patch_size**2 *3) 128 | """ 129 | 130 | p = self.patch_embed.patch_size[0] 131 | assert imgs.shape[2] == imgs.shape[3] and imgs.shape[2] % p == 0 132 | 133 | h = w = imgs.shape[2] // p 134 | x = imgs.reshape(shape=(imgs.shape[0], 3, h, p, w, p)) 135 | x = torch.einsum('nchpwq->nhwpqc', x) 136 | x = x.reshape(shape=(imgs.shape[0], h * w, p**2 * 3)) 137 | return x 138 | 139 | def unpatchify(self, x): 140 | """ 141 | x: (N, L, patch_size**2 *3) 142 | imgs: (N, 3, H, W) 143 | """ 144 | p = self.patch_embed.patch_size[0] 145 | h = w = int(x.shape[1]**.5) 146 | assert h * w == x.shape[1] 147 | 148 | x = x.reshape(shape=(x.shape[0], h, w, p, p, 3)) 149 | x = torch.einsum('nhwpqc->nchpwq', x) 150 | imgs = x.reshape(shape=(x.shape[0], 3, h * p, h * p)) 151 | return imgs 152 | 153 | def random_masking(self, x, mask_ratio): 154 | """ 155 | Perform per-sample random masking by per-sample shuffling. 156 | Per-sample shuffling is done by argsort random noise. 157 | x: [N, L, D], sequence 158 | """ 159 | N, L, D = x.shape # batch, length, dim 160 | len_keep = int(L * (1 - mask_ratio)) 161 | 162 | noise = torch.rand(N, L, device=x.device) # noise in [0, 1] 163 | 164 | # sort noise for each sample 165 | ids_shuffle = torch.argsort(noise, dim=1) # ascend: small is keep, large is remove 166 | ids_restore = torch.argsort(ids_shuffle, dim=1) 167 | 168 | # keep the first subset 169 | ids_keep = ids_shuffle[:, :len_keep] 170 | x_masked = torch.gather(x, dim=1, index=ids_keep.unsqueeze(-1).repeat(1, 1, D)) 171 | 172 | # generate the binary mask: 0 is keep, 1 is remove 173 | mask = torch.ones([N, L], device=x.device) 174 | mask[:, :len_keep] = 0 175 | # unshuffle to get the binary mask 176 | mask = torch.gather(mask, dim=1, index=ids_restore) 177 | 178 | return x_masked, mask, ids_restore 179 | 180 | def _ref_embed(self, ref): 181 | B, C, H, W = ref.shape 182 | ref = self.patch_embed.proj(ref) 183 | if self.patch_embed.flatten: 184 | ref = ref.flatten(2).transpose(1, 2) # BCHW -> BNC 185 | ref = self.patch_embed.norm(ref) 186 | return ref 187 | 188 | def forward_encoder(self, x, mask_ratio): 189 | # embed patches 190 | x = self.patch_embed(x) 191 | # add pos embed w/o cls token 192 | x = x + self.pos_embed[:, 2:, :] 193 | 194 | # masking: length -> length * mask_ratio 195 | x, mask, ids_restore = self.random_masking(x, mask_ratio) 196 | 197 | # append cls token 198 | cls_token = self.cls_token + self.pos_embed[:, 1:2, :] 199 | cls_tokens = cls_token.expand(x.shape[0], -1, -1) 200 | x = torch.cat((cls_tokens, x), dim=1) 201 | 202 | # append pretext token 203 | pre_token = self.pretext_token + self.pos_embed[:, :1, :] 204 | pre_tokens = pre_token.expand(x.shape[0], -1, -1) 205 | x = torch.cat((pre_tokens, x), dim=1) 206 | 207 | # apply Transformer blocks 208 | for blk in self.blocks: 209 | x = blk(x) 210 | x = self.norm(x) 211 | 212 | return x, mask, ids_restore 213 | 214 | def forward_encoder_with_pretext(self, x, mask_ratio, pretext): 215 | # embed patches 216 | x = self.patch_embed(x) 217 | # add pos embed w/o cls token 218 | x = x + self.pos_embed[:, 2:, :] 219 | 220 | # masking: length -> length * mask_ratio 221 | x, mask, ids_restore = self.random_masking(x, mask_ratio) 222 | 223 | # append cls token 224 | cls_token = self.cls_token + self.pos_embed[:, 1:2, :] 225 | cls_tokens = cls_token.expand(x.shape[0], -1, -1) 226 | x = torch.cat((cls_tokens, x), dim=1) 227 | 228 | # append pretext token 229 | pre_token = self.pretext_token + self.pos_embed[:, :1, :] 230 | pre_tokens = pre_token.expand(x.shape[0], -1, -1)*0 + self._ref_embed(pretext) + self.pos_embed[:, :1, :] 231 | x = torch.cat((pre_tokens, x), dim=1) 232 | 233 | # apply Transformer blocks 234 | for blk in self.blocks: 235 | x = blk(x) 236 | x = self.norm(x) 237 | 238 | return x, mask, ids_restore 239 | 240 | def forward_decoder(self, x, ids_restore): 241 | # embed tokens 242 | x = self.decoder_embed(x) 243 | 244 | # concate pretext tokens to each patch 245 | pretext_tokens = x[:, :1, :].repeat(1, x.shape[1]-1, 1) # N*1*768 => N*L+1*768 246 | x = torch.cat((x[:,1:,:], pretext_tokens), dim=2) 247 | 248 | # append mask tokens to sequence 249 | mask_tokens = self.mask_token.repeat(x.shape[0], ids_restore.shape[1] + 1 - x.shape[1], 1) 250 | x_ = torch.cat([x[:, 1:, :], mask_tokens], dim=1) # no cls token 251 | x_ = torch.gather(x_, dim=1, index=ids_restore.unsqueeze(-1).repeat(1, 1, x.shape[2])) # unshuffle 252 | x = torch.cat([x[:, :1, :], x_], dim=1) # append cls token 253 | 254 | 255 | # add pos embed 256 | x = x + self.decoder_pos_embed 257 | 258 | # apply Transformer blocks 259 | for blk in self.decoder_blocks: 260 | x = blk(x) 261 | x = self.decoder_norm(x) 262 | 263 | # predictor projection 264 | x = self.decoder_pred(x) 265 | 266 | # remove cls token 267 | x = x[:, 1:, :] 268 | 269 | return x 270 | 271 | def forward_loss(self, imgs, pred, mask): 272 | """ 273 | imgs: [N, 3, H, W] 274 | pred: [N, L, p*p*3] 275 | mask: [N, L], 0 is keep, 1 is remove, 276 | """ 277 | target = self.patchify(imgs) 278 | # if self.norm_pix_loss: 279 | # mean = target.mean(dim=-1, keepdim=True) 280 | # var = target.var(dim=-1, keepdim=True) 281 | # target = (target - mean) / (var + 1.e-6)**.5 282 | 283 | loss = (pred - target) ** 2 284 | loss = loss.mean(dim=-1) # [N, L], mean loss per patch 285 | 286 | loss = (loss * mask).sum() / mask.sum() # mean loss on removed patches 287 | return loss 288 | 289 | def forward(self, img_1, img_2, mask_ratio=0.75): 290 | pretext = torchvision.transforms.Resize(64)(img_2) 291 | pretext = torchvision.transforms.RandomCrop(16)(img_2) 292 | 293 | latent, mask, ids_restore = self.forward_encoder_with_pretext(img_1, mask_ratio, pretext) 294 | pred = self.forward_decoder(latent, ids_restore) # [N, L, p*p*3] 295 | loss = self.forward_loss(img_2.float(), pred.float(), mask.float()) 296 | loss.type_as(img_1) 297 | return loss, self.unpatchify(pred), mask 298 | 299 | def mae(**kwargs): 300 | model = MAE( 301 | patch_size=16, in_chans=3, embed_dim=768, depth=12, num_heads=12, 302 | decoder_embed_dim=768, decoder_depth=4, decoder_num_heads=6, 303 | mlp_ratio=4, norm_layer=partial(nn.LayerNorm, eps=1e-5), **kwargs) 304 | return model -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # [Model/Code] PathoDuet: Foundation Models for Pathological Slide Analysis of H&E and IHC Stains 2 | 13 | 14 | 15 | 16 |
17 | 18 |
19 | 20 | --- 21 | 22 | 23 | Updated on 2023.12.15. We have revolutionized PathoDuet! Now, the p2/p3 models are named HE/IHC models, and a more detailed figure about our work is updated! ~~The paper is also done, and will be available on arXiv soon.~~ The paper is available now. 24 | 25 | ~~Updated on 2023.08.04. Sorry for the late release. Now the p3 model is available! The paper link will be available in next update soon.~~ 26 | 27 | 28 | 29 | ## Key Features 30 | 31 | This repository provides the official implementation of PathoDuet: Foundation Models for Pathological Slide Analysis of H&E and IHC Stains. 32 | 33 | Key feature bulletin points here 34 | - Foundation models for histopathological image analysis. 35 | - The models cover both H&E and IHC stained images. 36 | - The H&E model achieves outstanding performance on both patch classification (following either a typical linear evaluation scheme, or a usual full fine-tuning scheme) and weakly-supervised WSl classification (using CLAM-SB). 37 | - The IHC model is evaluated with some in-house tasks, and shows great performance. 38 | 39 | ## Links 40 | 41 | - [Model](https://drive.google.com/drive/folders/1aQHGabQzopSy9oxstmM9cPeF7QziIUxM) 42 | - [Paper](https://arxiv.org/abs/2312.09894) 43 | 47 | ## Details 48 | 49 | Our model is based on a new self-supervised learning (SSL) framework. This framework aims at exploiting characteristics of histopathological images by introducing a pretext token and following task raiser during the training. The pretext token is only a small piece of image, but contains special knowledge. 50 | 51 | In task 1, cross-scale positioning, the pretext token is a small patch contained in a large region. The special relation inspires us to position this patch in the region and use the features of the region to generate the feature of the patch in a global view. The patch is also sent to the encoder solely to obtain a local-view feature. The two features are pulled together to strengthen the H&E model. 52 | 53 | In task 2, cross-stain transferring, the pretext token is a small patch cropped from an image of one stain (H&E). The main input is the image of the other stain (IHC). These two images are roughly registered, so it is possible to style transfer one of them (H&E) to mimic the features of the other (IHC). The pseudo and real features are pulled together to obtain an IHC model on the basis of existing H&E model. 54 | 55 | 56 |
57 | 58 |
59 | 60 | ## Dataset Links 61 | 62 | - [The Cancer Genome Atlas (TCGA)](https://portal.gdc.cancer.gov/) for SSL. 63 | - [NCT-CRC-HE](https://zenodo.org/record/1214456#.YVrmANpBwRk), also known as the Kather datasets, for patch classification. 64 | - [Camelyon 16](https://camelyon16.grand-challenge.org/) for weakly-supervised WSI classification. 65 | - [HyReCo](https://ieee-dataport.org/open-access/hyreco-hybrid-re-stained-and-consecutive-histological-serial-sections) for training in task 2. 66 | - [BCI Dataset](https://bci.grand-challenge.org/) for training in task 2. 67 | 68 | ## Get Started 69 | 70 | **Main Requirements** 71 | > torch==1.12.1 72 | > 73 | > torchvision==0.13.1 74 | > 75 | > timm==0.6.7 76 | > 77 | > tensorboard 78 | > 79 | > pandas 80 | 81 | **Installation** 82 | ```bash 83 | git clone https://github.com/openmedlab/PathoDuet 84 | cd PathoDuet 85 | ``` 86 | 87 | **Download Model** 88 | 89 | If you just require a pretrain model for your own task, you can find our pretrained model weights [here](https://drive.google.com/drive/folders/1aQHGabQzopSy9oxstmM9cPeF7QziIUxM). We now provide you two versions of models. 90 | 91 | - A model pretrained with cross-scale position task (HE model). This model further strengthens its representation of H&E images. 92 | - A model fine-tuned towards IHC images with cross-stain transferring task (IHC model). This model transfers the strong H&E model to an interpreter of IHC images. 93 | 94 | You can try our model by the following codes. 95 | 96 | ```python 97 | from vits import VisionTransformerMoCo 98 | # init the model 99 | model = VisionTransformerMoCo(pretext_token=True, global_pool='avg') 100 | # init the fc layer 101 | model.head = nn.Linear(768, args.num_classes) 102 | # load checkpoint 103 | checkpoint = torch.load(your_checkpoint_path, map_location="cpu") 104 | model.load_state_dict(checkpoint, strict=False) 105 | # Your own tasks 106 | ``` 107 | 108 | Please note that considering the gap between pathological images and natural images, we do not use a normalize function in data augmentation. 109 | 110 | **Prepare Dataset** 111 | 112 | If you want to go through the whole process, you need to first prepare the training dataset. The H&E training dataset is cropped from TCGA, and should be arranged as 113 | ```bash 114 | TCGA 115 | ├── TCGA-ACC 116 | │ ├── patch 117 | │ │ ├── 0_0_1.png 118 | │ │ ├── 0_0_2.png 119 | │ │ └── ... 120 | │ └── region 121 | │ ├── 0_0.png 122 | │ ├── 0_1.png 123 | │ └── ... 124 | ├── TCGA-BRCA 125 | │ ├── patch 126 | │ │ └── ... 127 | │ └── region 128 | │ └── ... 129 | └── ... 130 | ``` 131 | To apply our data generating code, we recommend to install 132 | > openslide 133 | 134 | The dataset in task 2 should be arranged like 135 | ```bash 136 | root 137 | ├── Dataset1 138 | │ ├── HE 139 | │ │ ├── 001.png 140 | │ │ ├── a.png 141 | │ │ └── ... 142 | │ ├── IHC1 143 | │ │ ├── 001.png 144 | │ │ ├── a.png 145 | │ │ └── ... 146 | │ └── IHC2 147 | │ ├── 001.png 148 | │ ├── a.png 149 | │ └── ... 150 | ├── Dataset2 151 | │ ├── HE 152 | │ │ └── ... 153 | │ └── IHC 154 | │ └── ... 155 | └── ... 156 | ``` 157 | 158 | **Training** 159 | 160 | The code is modified from [MoCo v3](https://github.com/facebookresearch/moco-v3). 161 | 162 | For basic MoCo v3 training, 163 | ```python 164 | python main_moco.py \ 165 | --tcga ./used_TCGA.csv \ 166 | -a vit_base -b 2048 --workers 128 \ 167 | --optimizer=adamw --lr=1.5e-4 --weight-decay=.1 \ 168 | --epochs=100 --warmup-epochs=40 \ 169 | --stop-grad-conv1 --moco-m-cos --moco-t=.2 \ 170 | --multiprocessing-distributed --world-size 1 --rank 0 \ 171 | --dist-backend nccl \ 172 | --dist-url 'tcp://localhost:10001' \ 173 | [your dataset folders] 174 | ``` 175 | 176 | For a further patch positioning pretext task, 177 | ```python 178 | python main_bridge.py \ 179 | --tcga ./used_TCGA.csv \ 180 | -a vit_base -b 2048 --workers 128 \ 181 | --optimizer=adamw --lr=1.5e-4 --weight-decay=.1 \ 182 | --epochs=20 --warmup-epochs=10 \ 183 | --stop-grad-conv1 --moco-m-cos --moco-t=.2 --bridge-t=0.5 \ 184 | --multiprocessing-distributed --world-size 1 --rank 0 \ 185 | --dist-url 'tcp://localhost:10001' \ 186 | --ckp ./phase2 \ 187 | --firstphase ./checkpoint_0099.pth.tar \ 188 | [your dataset folders] 189 | ``` 190 | 191 | For a further multi-stain reconstruction task, 192 | ```python 193 | python main_cross.py \ 194 | -a vit_base -b 2048 --workers 128 \ 195 | --optimizer=adamw --lr=1.5e-4 --weight-decay=.1 \ 196 | --epochs=500 --warmup-epochs=100 \ 197 | --stop-grad-conv1 \ 198 | --multiprocessing-distributed --world-size 1 --rank 0 \ 199 | --dist-url 'tcp://localhost:10001' \ 200 | --ckp ./phase3 \ 201 | --firstphase .phase2/checkpoint_0099.pth.tar \ 202 | [your dataset folders] 203 | ``` 204 | 205 | ## Performance on Downstream Tasks 206 | 207 | We provide performance evaluation on some downstream tasks, and compare our models with ImageNet-pretrained models (using weights of MoCo v3) and [CTransPath](https://github.com/Xiyue-Wang/TransPath/tree/main). ImageNet has shown its great generalization ability in many pretrained models, so we choose MoCo v3's model as a baseline. CTransPath is also a pretrained model in pathology, which is based on 15 million patches from TCGA and PAIP. CTransPath has shown state-of-the-art performance on many pathological tasks of different diseases and sites. 208 | 209 | **Linear Evaluation** 210 | 211 | We use NCT-CRC-HE to evaluate the basic understanding of H&E images. We first follow the typical linear evaluation protocol used in [SimCLR](http://proceedings.mlr.press/v119/chen20j.html), which freezes all layers in the pretrained model and trains a newly-added linear layer from scratch. The result of CTransPath is copied from the original paper, and we also provide a reproduced one marked with a *. 212 | | Methods | Backbone | ACC | F1 | 213 | |----------|:-------------:|:------:|:-----:| 214 | | ImageNet-MoCo v3 | ViT-B/16 | 0.935 | 0.908 | 215 | | CTransPath | Modified Swin Transformer | **0.965** | _0.948_ | 216 | | CTransPath* | Modified Swin Transformer | 0.956 | 0.932 | 217 | | Ours-HE | ViT-B/16 | _0.964_ | **0.950** | 218 | 219 | **Full Fine-tuning** 220 | 221 | In practice, pretrained models are not freezed. Therefore, we also unfreeze the pretrained encoder and finetune all parameters. It is noted that the performance of CTransPath is based on their open model. 222 | | Methods | Backbone | ACC | F1 | 223 | |----------|:-------------:|:------:|:-----:| 224 | | ImageNet-MoCo v3 | ViT-B/16 | 0.958 | 0.945 | 225 | | CTransPath | Modified Swin Transformer | _0.969_ | _0.960_ | 226 | | Ours-HE | ViT-B/16 | **0.973** | **0.964** | 227 | 228 | 229 | **WSI Classification** 230 | 231 | For WSI classification, we reproduce the performance of CLAM-SB. Meanwhile, CTransPath filtered out some WSI in TCGA-NSCLC and TCGA-RCC due to some image quality consideration, so the performance of CTransPath is a reproduced one using their open model on the whole dataset, marked as CTP (Repro). 232 | 233 | | Methods | CAMELYON16: ACC | CAMELYON16: AUC | TCGA-NSCLC: ACC | TCGA-NSCLC: AUC | TCGA-RCC: ACC | TCGA-RCC: AUC | 234 | |----------|:------:|:-----:|:-----:|:-----:|:-----:|:-----:| 235 | | CLAM-SB | _0.884_ | _0.940_ | 0.894 | 0.951 | _0.929_ | 0.986| 236 | | CLAM-SB + CTP (Repro) | 0.868 | _0.940_ | _0.904_ | _0.956_ | 0.928 | _0.987_ | 237 | | CLAM-SB + Ours-HE | **0.930** | **0.956** | **0.908** | **0.963** | **0.954** | **0.993** | 238 | 239 | 240 | **PD-L1 Expression Level Assessment (IHC images)** 241 | 242 | Assessing IHC markers' expression levels is one of the primary tasks for pathologists to evaluate an IHC slide. We formulate this task as a 4-class classification task, with carefully selected thresholds. We compare our IHC model's performance with ImageNet-MoCo v3 and CTransPath as well. The metrics include accuracy (ACC), balanced accuracy (bACC) and weighted F1 score (wF1). Here, we give the performance with a limited amount of training data. 243 | 244 | | Methods | Backbone | ACC | bACC | wF1 | 245 | |----------|:----------:|:------:|:-----:|:------:| 246 | | ImageNet-MoCo v3 | ViT-B/16 | 0.686 | 0.698 | 0.695 | 247 | | CTransPath | Modified SwinT | _0.700_ | _0.709_ | _0.703_ | 248 | | Ours-IHC | ViT-B/16 | **0.726** | **0.721** | **0.732** | 249 | 250 | 251 | **Cross-Site Tumor Identification (IHC images)** 252 | 253 | Tumor identification is also of great importance. We formulate this task as a 2-class classification task, with/without tumor cells in the given patch. The metrics include accuracy (ACC) and F1 score (F1). Here, we give the performance in the case of 1) an in-site setting, and 2) an out-of-distribution setting. In the first setting, we use a small group of data from site 1 to train the models in a linear protocol, and evaluate on another group of data from site 1. In the second setting, we train the models with more data in site 1, and evaluate on data from an unseen site 2. 254 | 255 | | Methods | Backbone | ACC | F1 | ACC (OOD) | F1 (OOD) | 256 | |----------|:----------:|:------:|:-----:|:------:|:------:| 257 | | ImageNet-MoCo v3 | ViT-B/16 | 0.864 | 0.862 | 0.504 | 0.503 | 258 | | CTransPath | Modified SwinT | _0.872_ | _0.870_ | _0.677_ | _0.657_ | 259 | | Ours-IHC | ViT-B/16 | **0.900** | **0.900** | **0.826** | **0.769** | 260 | 261 | 262 | 263 | **Comparison with Giant Pathological Models** 264 | 265 | We also compare our model to some giant models pretrained with ultra-large amounts of pathological slides, namely UNI and Virchow. We use the NCT-CRC-HE and NCT-CRC-HE-NONORM (marked with a *), and copy the results from Virchow. To note, the result of CTransPath is also a copy from Virchow, so it is slightly different from previous results reproduced by us, but the gap is as small as 0.001 or 0.002, which is acceptable as randomness. The training parameters are similar to Virchow's. but we change the batch size to 512 and a rescaled learning rate as 0.001/8=0.000125, and we use typical augmentations like random crop and scale, random flip and random rotation. 266 | 267 | | Methods | Backbone | #WSIs | ACC | bACC | wF1 | ACC* | bACC* | wF1* | 268 | |----------|:----------:|:------:|:-----:|:------:|:------:|:------:|:------:|:------:| 269 | | Ours-H&E | ViT-B | ~11K | _0.964_ | _0.952_ | _0.964_ | _0.888_ | _0.875_ | _0.894_ | 270 | | CTransPath | Modified SwinT | ~32K | 0.958 | 0.931 | 0.955 | 0.879 | 0.852 | 0.883 | 271 | | UNI | ViT-L | ~100K | - | - | - |- | 0.874 | 0.875 | 272 | | Virchow | ViT-H | ~1.5M | **0.968** | **0.956** | **0.968** | **0.948** | **0.938** | **0.950** | 273 | 274 | **More Results can be found in our later released paper!** 275 | 276 | 277 | ## 🛡️ License 278 | 279 | This project is under the CC-BY-NC 4.0 license. See [LICENSE](LICENSE) for details. 280 | 281 | ## 🙏 Acknowledgement 282 | 283 | - Shanghai AI Laboratory. 284 | - Qingyuan Research Institute, Shanghai Jiao Tong University. 285 | 286 | ## 📝 Citation 287 | 288 | If you find this repository useful, please consider citing our arXiv paper. 289 | ``` 290 | @misc{hua2023pathoduet, 291 | title={PathoDuet: Foundation Models for Pathological Slide Analysis of H&E and IHC Stains}, 292 | author={Shengyi Hua and Fang Yan and Tianle Shen and Xiaofan Zhang}, 293 | year={2023}, 294 | eprint={2312.09894}, 295 | archivePrefix={arXiv}, 296 | primaryClass={cs.CV} 297 | } 298 | ``` 299 | -------------------------------------------------------------------------------- /moco/builder.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its affiliates. 2 | # All rights reserved. 3 | 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | 7 | import torch 8 | import torch.nn as nn 9 | import torch.nn.functional as F 10 | 11 | 12 | class MoCo(nn.Module): 13 | """ 14 | Build a MoCo model with a base encoder, a momentum encoder, and two MLPs 15 | https://arxiv.org/abs/1911.05722 16 | """ 17 | def __init__(self, base_encoder, dim=256, mlp_dim=4096, T=1.0): 18 | """ 19 | dim: feature dimension (default: 256) 20 | mlp_dim: hidden dimension in MLPs (default: 4096) 21 | T: softmax temperature (default: 1.0) 22 | """ 23 | super(MoCo, self).__init__() 24 | 25 | self.T = T 26 | 27 | # build encoders 28 | self.base_encoder = base_encoder(num_classes=mlp_dim) 29 | self.momentum_encoder = base_encoder(num_classes=mlp_dim) 30 | 31 | self._build_projector_and_predictor_mlps(dim, mlp_dim) 32 | 33 | for param_b, param_m in zip(self.base_encoder.parameters(), self.momentum_encoder.parameters()): 34 | param_m.data.copy_(param_b.data) # initialize 35 | param_m.requires_grad = False # not update by gradient 36 | 37 | def _build_mlp(self, num_layers, input_dim, mlp_dim, output_dim, last_bn=True): 38 | mlp = [] 39 | for l in range(num_layers): 40 | dim1 = input_dim if l == 0 else mlp_dim 41 | dim2 = output_dim if l == num_layers - 1 else mlp_dim 42 | 43 | mlp.append(nn.Linear(dim1, dim2, bias=False)) 44 | 45 | if l < num_layers - 1: 46 | mlp.append(nn.BatchNorm1d(dim2)) 47 | mlp.append(nn.ReLU(inplace=True)) 48 | elif last_bn: 49 | # follow SimCLR's design: https://github.com/google-research/simclr/blob/master/model_util.py#L157 50 | # for simplicity, we further removed gamma in BN 51 | mlp.append(nn.BatchNorm1d(dim2, affine=False)) 52 | 53 | return nn.Sequential(*mlp) 54 | 55 | def _build_projector_and_predictor_mlps(self, dim, mlp_dim): 56 | pass 57 | 58 | @torch.no_grad() 59 | def _update_momentum_encoder(self, m): 60 | """Momentum update of the momentum encoder""" 61 | for param_b, param_m in zip(self.base_encoder.parameters(), self.momentum_encoder.parameters()): 62 | param_m.data = param_m.data * m + param_b.data * (1. - m) 63 | 64 | def byol_loss(self, q, k): 65 | norm_q = F.normalize(q, dim=1, eps=1e-6) 66 | norm_k = F.normalize(k, dim=1, eps=1e-6) 67 | return 1.0 - torch.einsum('ij,ij->i', [norm_q, norm_k]).mean() 68 | 69 | def contrastive_loss(self, q, k): 70 | # normalize 71 | q = nn.functional.normalize(q, dim=1) 72 | k = nn.functional.normalize(k, dim=1) 73 | # gather all targets 74 | k = concat_all_gather(k) 75 | # Einstein sum is more intuitive 76 | logits = torch.einsum('nc,mc->nm', [q, k]) / self.T 77 | N = logits.shape[0] # batch size per GPU 78 | labels = (torch.arange(N, dtype=torch.long) + N * torch.distributed.get_rank()).cuda() 79 | return nn.CrossEntropyLoss()(logits, labels) * (2 * self.T) 80 | 81 | def forward(self, x1, x2, m): 82 | """ 83 | Input: 84 | x1: first views of images 85 | x2: second views of images 86 | m: moco momentum 87 | Output: 88 | loss 89 | """ 90 | 91 | # compute features 92 | _, tmp1 = self.base_encoder(x1) 93 | _, tmp2 = self.base_encoder(x2) 94 | q1 = self.predictor(tmp1) 95 | q2 = self.predictor(tmp2) 96 | 97 | with torch.no_grad(): # no gradient 98 | self._update_momentum_encoder(m) # update the momentum encoder 99 | 100 | # compute momentum features as targets 101 | _, k1 = self.momentum_encoder(x1) 102 | _, k2 = self.momentum_encoder(x2) 103 | 104 | loss = self.contrastive_loss(q1, k2) + self.contrastive_loss(q2, k1) 105 | return loss 106 | 107 | 108 | class MoCo_ResNet(MoCo): 109 | def _build_projector_and_predictor_mlps(self, dim, mlp_dim): 110 | hidden_dim = self.base_encoder.fc.weight.shape[1] 111 | del self.base_encoder.fc, self.momentum_encoder.fc # remove original fc layer 112 | 113 | # projectors 114 | self.base_encoder.fc = self._build_mlp(2, hidden_dim, mlp_dim, dim) 115 | self.momentum_encoder.fc = self._build_mlp(2, hidden_dim, mlp_dim, dim) 116 | 117 | # predictor 118 | self.predictor = self._build_mlp(2, dim, mlp_dim, dim, False) 119 | 120 | 121 | class MoCo_ViT(MoCo): 122 | def _build_projector_and_predictor_mlps(self, dim, mlp_dim): 123 | hidden_dim = self.base_encoder.head.weight.shape[1] 124 | del self.base_encoder.head, self.momentum_encoder.head # remove original fc layer 125 | 126 | # projectors 127 | self.base_encoder.head = self._build_mlp(3, hidden_dim, mlp_dim, dim) 128 | self.momentum_encoder.head = self._build_mlp(3, hidden_dim, mlp_dim, dim) 129 | 130 | # predictor 131 | self.predictor = self._build_mlp(2, dim, mlp_dim, dim) 132 | 133 | class Bridge(nn.Module): 134 | """ 135 | Build a Cross-scale positioning model 136 | """ 137 | def __init__(self, base_encoder, dim=256, mlp_dim=4096, T=1.0, B_T=1.0): 138 | """ 139 | dim: feature dimension (default: 256) 140 | mlp_dim: hidden dimension in MLPs (default: 4096) 141 | T: softmax temperature (default: 1.0) 142 | """ 143 | super(Bridge, self).__init__() 144 | 145 | self.T = T 146 | self.B_T = B_T 147 | 148 | # build encoders 149 | self.base_encoder = base_encoder(num_classes=mlp_dim) 150 | self.momentum_encoder = base_encoder(num_classes=mlp_dim) 151 | 152 | self._build_3p_mlps(dim, mlp_dim) 153 | 154 | for param_b, param_m in zip(self.base_encoder.parameters(), self.momentum_encoder.parameters()): 155 | param_m.data.copy_(param_b.data) # initialize 156 | param_m.requires_grad = False # not update by gradient 157 | 158 | def _build_mlp(self, num_layers, input_dim, mlp_dim, output_dim, last_bn=True): 159 | mlp = [] 160 | for l in range(num_layers): 161 | dim1 = input_dim if l == 0 else mlp_dim 162 | dim2 = output_dim if l == num_layers - 1 else mlp_dim 163 | 164 | mlp.append(nn.Linear(dim1, dim2, bias=False)) 165 | 166 | if l < num_layers - 1: 167 | mlp.append(nn.BatchNorm1d(dim2)) 168 | mlp.append(nn.ReLU(inplace=True)) 169 | elif last_bn: 170 | # follow SimCLR's design: https://github.com/google-research/simclr/blob/master/model_util.py#L157 171 | # for simplicity, we further removed gamma in BN 172 | mlp.append(nn.BatchNorm1d(dim2, affine=False)) 173 | 174 | return nn.Sequential(*mlp) 175 | 176 | def _build_3p_mlps(self, dim, mlp_dim): 177 | hidden_dim = self.base_encoder.head.weight.shape[1] 178 | patch_dim = self.base_encoder.embed_len - 2 179 | del self.base_encoder.head, self.momentum_encoder.head # remove original fc layer 180 | 181 | # projectors 182 | self.base_encoder.head = self._build_mlp(3, hidden_dim, mlp_dim, dim) 183 | self.momentum_encoder.head = self._build_mlp(3, hidden_dim, mlp_dim, dim) 184 | 185 | # predictor 186 | self.predictor = self._build_mlp(2, dim, mlp_dim, dim) 187 | 188 | # positioner 189 | self.positioner = self._build_mlp(2, hidden_dim, mlp_dim, patch_dim) 190 | 191 | @torch.no_grad() 192 | def _update_momentum_encoder(self, m): 193 | """Momentum update of the momentum encoder""" 194 | for param_b, param_m in zip(self.base_encoder.parameters(), self.momentum_encoder.parameters()): 195 | param_m.data = param_m.data * m + param_b.data * (1. - m) 196 | 197 | def byol_loss(self, q, k): 198 | return 1.001 - nn.CosineSimilarity()(q, k).mean() 199 | 200 | def moco_loss(self, q, k): 201 | # normalize 202 | q = nn.functional.normalize(q, dim=1) 203 | k = nn.functional.normalize(k, dim=1) 204 | # gather all targets 205 | k = concat_all_gather(k) 206 | # Einstein sum is more intuitive 207 | logits = torch.einsum('nc,mc->nm', [q, k]) / self.T 208 | N = logits.shape[0] # batch size per GPU 209 | labels = (torch.arange(N, dtype=torch.long) + N * torch.distributed.get_rank()).cuda() 210 | return nn.CrossEntropyLoss()(logits, labels) * (2 * self.T) 211 | 212 | def forward(self, x1, x2, x, r, m): 213 | """ 214 | Input: 215 | x1: first views of patches 216 | x2: second views of patches 217 | x: patches 218 | r: regions 219 | m: moco momentum 220 | Output: 221 | loss 222 | """ 223 | 224 | # compute features 225 | _, feat1 = self.base_encoder(x1) 226 | _, feat2 = self.base_encoder(x2) 227 | out_R, _ = self.base_encoder(r, x) 228 | q1 = self.predictor(feat1) 229 | q2 = self.predictor(feat2) 230 | 231 | c_feat = out_R[:, self.base_encoder.num_prefix_tokens:] 232 | pos1 = self.positioner(out_R[:, 0].float()) 233 | pos2 = F.softmax(pos1.float(), dim=-1).type_as(out_R) 234 | K1 = self.base_encoder.head(torch.einsum("ijk,ij->ik", [c_feat, pos2])) 235 | Q1 = self.predictor(K1) 236 | 237 | 238 | 239 | with torch.no_grad(): # no gradient 240 | self._update_momentum_encoder(m) # update the momentum encoder 241 | 242 | # compute momentum features as targets 243 | _, k1 = self.momentum_encoder(x1) 244 | _, k2 = self.momentum_encoder(x2) 245 | 246 | loss = self.moco_loss(q1, k2) + self.moco_loss(q2, k1) + \ 247 | self.B_T * (self.byol_loss(Q1, feat1.detach()) + \ 248 | self.byol_loss(Q1, feat2.detach()) + \ 249 | self.byol_loss(q1, K1.detach()) + \ 250 | self.byol_loss(q2, K1.detach())) 251 | 252 | return loss 253 | 254 | 255 | class CrossStain(nn.Module): 256 | """ 257 | Build a Cross-stain transferring model 258 | """ 259 | def __init__(self, base_encoder, dim=256, mlp_dim=4096, T=1.0): 260 | """ 261 | dim: feature dimension (default: 256) 262 | mlp_dim: hidden dimension in MLPs (default: 4096) 263 | T: softmax temperature (default: 1.0) 264 | """ 265 | super(CrossStain, self).__init__() 266 | 267 | self.T = T 268 | 269 | # build encoders 270 | self.base_encoder = base_encoder(num_classes=mlp_dim) 271 | self.momentum_encoder = base_encoder(num_classes=mlp_dim) 272 | 273 | self._build_projector_and_predictor_mlps(dim, mlp_dim) 274 | 275 | for param_b, param_m in zip(self.base_encoder.parameters(), self.momentum_encoder.parameters()): 276 | param_m.data.copy_(param_b.data) # initialize 277 | param_m.requires_grad = False # not update by gradient 278 | 279 | def _build_mlp(self, num_layers, input_dim, mlp_dim, output_dim, last_bn=True): 280 | mlp = [] 281 | for l in range(num_layers): 282 | dim1 = input_dim if l == 0 else mlp_dim 283 | dim2 = output_dim if l == num_layers - 1 else mlp_dim 284 | 285 | mlp.append(nn.Linear(dim1, dim2, bias=False)) 286 | 287 | if l < num_layers - 1: 288 | mlp.append(nn.BatchNorm1d(dim2)) 289 | mlp.append(nn.ReLU(inplace=True)) 290 | elif last_bn: 291 | # follow SimCLR's design: https://github.com/google-research/simclr/blob/master/model_util.py#L157 292 | # for simplicity, we further removed gamma in BN 293 | mlp.append(nn.BatchNorm1d(dim2, affine=False)) 294 | 295 | return nn.Sequential(*mlp) 296 | 297 | def _build_projector_and_predictor_mlps(self, dim, mlp_dim): 298 | hidden_dim = self.base_encoder.head.weight.shape[1] 299 | del self.base_encoder.head, self.momentum_encoder.head # remove original fc layer 300 | 301 | # projectors 302 | self.base_encoder.head = self._build_mlp(3, hidden_dim, mlp_dim, dim) 303 | self.momentum_encoder.head = self._build_mlp(3, hidden_dim, mlp_dim, dim) 304 | 305 | # predictor 306 | self.predictor = self._build_mlp(2, dim, mlp_dim, dim) 307 | 308 | def _ada_in(self, c_tensor, s_tensor): 309 | # c_tensor: BxNxC 310 | # s_tensor: BxC 311 | B, N, C = c_tensor.shape 312 | c_tensor = c_tensor.permute(0,2,1) # c_tensor: BxCxN 313 | c_mean = c_tensor.mean(dim=2) # BxC 314 | c_std = c_tensor.std(dim=2) # BxC 315 | c_tensor = c_tensor.reshape(B*C, N).permute(1,0) 316 | c_mean = c_mean.reshape(B*C) 317 | c_std = c_std.reshape(B*C) 318 | s_tensor = s_tensor.reshape(B*C) 319 | 320 | new_c = (c_tensor-c_mean)/c_std + s_tensor 321 | 322 | new_c = new_c.permute(1,0).reshape(B,C,N).permute(0,2,1) 323 | 324 | return new_c 325 | 326 | @torch.no_grad() 327 | def _update_momentum_encoder(self, m): 328 | """Momentum update of the momentum encoder""" 329 | for param_b, param_m in zip(self.base_encoder.parameters(), self.momentum_encoder.parameters()): 330 | param_m.data = param_m.data * m + param_b.data * (1. - m) 331 | 332 | def byol_loss(self, q, k): 333 | print(q.shape, k.shape) 334 | return 1.001 - nn.CosineSimilarity()(q, k).mean() 335 | 336 | def moco_loss(self, q, k): 337 | # normalize 338 | q = nn.functional.normalize(q, dim=1) 339 | k = nn.functional.normalize(k, dim=1) 340 | # gather all targets 341 | k = concat_all_gather(k) 342 | # Einstein sum is more intuitive 343 | logits = torch.einsum('nc,mc->nm', [q, k]) / self.T 344 | N = logits.shape[0] # batch size per GPU 345 | labels = (torch.arange(N, dtype=torch.long) + N * torch.distributed.get_rank()).cuda() 346 | return nn.CrossEntropyLoss()(logits, labels) * (2 * self.T) 347 | 348 | def forward(self, x1, x2, stain, m=0.9): 349 | """ 350 | Input: 351 | x1: first stain of images 352 | x2: second stain of images 353 | stain: crops of second stain 354 | m: moco momentum 355 | Output: 356 | loss 357 | """ 358 | 359 | # compute features 360 | _, feat2 = self.base_encoder(x2, stain) 361 | 362 | q2 = self.predictor(feat2) 363 | 364 | 365 | 366 | with torch.no_grad(): # no gradient 367 | c_out = self.momentum_encoder.forward_features(x1, stain) 368 | k1 = self.momentum_encoder.forward_head(self._ada_in(c_out, c_out[:, 0])) 369 | 370 | 371 | return self.moco_loss(q2, k1) 372 | 373 | 374 | # utils 375 | @torch.no_grad() 376 | def concat_all_gather(tensor): 377 | """ 378 | Performs all_gather operation on the provided tensors. 379 | *** Warning ***: torch.distributed.all_gather has no gradient. 380 | """ 381 | tensors_gather = [torch.ones_like(tensor) 382 | for _ in range(torch.distributed.get_world_size())] 383 | torch.distributed.all_gather(tensors_gather, tensor, async_op=False) 384 | 385 | output = torch.cat(tensors_gather, dim=0) 386 | return output 387 | -------------------------------------------------------------------------------- /main_moco.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # Copyright (c) Facebook, Inc. and its affiliates. 4 | # All rights reserved. 5 | 6 | # This source code is licensed under the license found in the 7 | # LICENSE file in the root directory of this source tree. 8 | 9 | import argparse 10 | import builtins 11 | import math 12 | import os 13 | import random 14 | import shutil 15 | import time 16 | import warnings 17 | from functools import partial 18 | 19 | import torch 20 | import torch.nn as nn 21 | import torch.nn.parallel 22 | import torch.backends.cudnn as cudnn 23 | import torch.distributed as dist 24 | import torch.optim 25 | import torch.multiprocessing as mp 26 | import torch.utils.data 27 | import torch.utils.data.distributed 28 | import torchvision.transforms as transforms 29 | import torchvision.datasets as datasets 30 | import torchvision.models as torchvision_models 31 | from torch.utils.tensorboard import SummaryWriter 32 | 33 | import moco.builder 34 | import moco.loader 35 | import moco.optimizer 36 | 37 | import vits 38 | import pandas as pd 39 | 40 | 41 | torchvision_model_names = sorted(name for name in torchvision_models.__dict__ 42 | if name.islower() and not name.startswith("__") 43 | and callable(torchvision_models.__dict__[name])) 44 | 45 | model_names = ['vit_small', 'vit_base', 'vit_conv_small', 'vit_conv_base'] + torchvision_model_names 46 | 47 | parser = argparse.ArgumentParser(description='MoCo ImageNet Pre-Training') 48 | parser.add_argument('data', metavar='DIR', 49 | help='path to dataset') 50 | parser.add_argument('--tcga', metavar='PATH', 51 | help='path to a csv record of used TCGA') 52 | parser.add_argument('-a', '--arch', metavar='ARCH', default='resnet50', 53 | choices=model_names, 54 | help='model architecture: ' + 55 | ' | '.join(model_names) + 56 | ' (default: resnet50)') 57 | parser.add_argument('-j', '--workers', default=32, type=int, metavar='N', 58 | help='number of data loading workers (default: 32)') 59 | parser.add_argument('--epochs', default=100, type=int, metavar='N', 60 | help='number of total epochs to run') 61 | parser.add_argument('--start-epoch', default=0, type=int, metavar='N', 62 | help='manual epoch number (useful on restarts)') 63 | parser.add_argument('-b', '--batch-size', default=4096, type=int, 64 | metavar='N', 65 | help='mini-batch size (default: 4096), this is the total ' 66 | 'batch size of all GPUs on all nodes when ' 67 | 'using Data Parallel or Distributed Data Parallel') 68 | parser.add_argument('--lr', '--learning-rate', default=0.6, type=float, 69 | metavar='LR', help='initial (base) learning rate', dest='lr') 70 | parser.add_argument('--momentum', default=0.9, type=float, metavar='M', 71 | help='momentum') 72 | parser.add_argument('--wd', '--weight-decay', default=1e-6, type=float, 73 | metavar='W', help='weight decay (default: 1e-6)', 74 | dest='weight_decay') 75 | parser.add_argument('-p', '--print-freq', default=10, type=int, 76 | metavar='N', help='print frequency (default: 10)') 77 | parser.add_argument('--resume', default='', type=str, metavar='PATH', 78 | help='path to latest checkpoint (default: none)') 79 | parser.add_argument('--world-size', default=-1, type=int, 80 | help='number of nodes for distributed training') 81 | parser.add_argument('--rank', default=-1, type=int, 82 | help='node rank for distributed training') 83 | parser.add_argument('--dist-url', default='tcp://224.66.41.62:23456', type=str, 84 | help='url used to set up distributed training') 85 | parser.add_argument('--dist-backend', default='nccl', type=str, 86 | help='distributed backend') 87 | parser.add_argument('--seed', default=None, type=int, 88 | help='seed for initializing training. ') 89 | parser.add_argument('--gpu', default=None, type=int, 90 | help='GPU id to use.') 91 | parser.add_argument('--multiprocessing-distributed', action='store_true', 92 | help='Use multi-processing distributed training to launch ' 93 | 'N processes per node, which has N GPUs. This is the ' 94 | 'fastest way to use PyTorch for either single node or ' 95 | 'multi node data parallel training') 96 | 97 | # moco specific configs: 98 | parser.add_argument('--moco-dim', default=256, type=int, 99 | help='feature dimension (default: 256)') 100 | parser.add_argument('--moco-mlp-dim', default=4096, type=int, 101 | help='hidden dimension in MLPs (default: 4096)') 102 | parser.add_argument('--moco-m', default=0.99, type=float, 103 | help='moco momentum of updating momentum encoder (default: 0.99)') 104 | parser.add_argument('--moco-m-cos', action='store_true', 105 | help='gradually increase moco momentum to 1 with a ' 106 | 'half-cycle cosine schedule') 107 | parser.add_argument('--moco-t', default=1.0, type=float, 108 | help='softmax temperature (default: 1.0)') 109 | 110 | # vit specific configs: 111 | parser.add_argument('--stop-grad-conv1', action='store_true', 112 | help='stop-grad after first conv, or patch embedding') 113 | 114 | # other upgrades 115 | parser.add_argument('--optimizer', default='lars', type=str, 116 | choices=['lars', 'adamw'], 117 | help='optimizer used (default: lars)') 118 | parser.add_argument('--warmup-epochs', default=10, type=int, metavar='N', 119 | help='number of warmup epochs') 120 | parser.add_argument('--crop-min', default=0.08, type=float, 121 | help='minimum scale for random cropping (default: 0.08)') 122 | 123 | 124 | def main(): 125 | args = parser.parse_args() 126 | 127 | if args.seed is not None: 128 | random.seed(args.seed) 129 | torch.manual_seed(args.seed) 130 | cudnn.deterministic = True 131 | warnings.warn('You have chosen to seed training. ' 132 | 'This will turn on the CUDNN deterministic setting, ' 133 | 'which can slow down your training considerably! ' 134 | 'You may see unexpected behavior when restarting ' 135 | 'from checkpoints.') 136 | 137 | if args.gpu is not None: 138 | warnings.warn('You have chosen a specific GPU. This will completely ' 139 | 'disable data parallelism.') 140 | 141 | if args.dist_url == "env://" and args.world_size == -1: 142 | args.world_size = int(os.environ["WORLD_SIZE"]) 143 | 144 | args.distributed = args.world_size > 1 or args.multiprocessing_distributed 145 | 146 | ngpus_per_node = torch.cuda.device_count() 147 | if args.multiprocessing_distributed: 148 | # Since we have ngpus_per_node processes per node, the total world_size 149 | # needs to be adjusted accordingly 150 | args.world_size = ngpus_per_node * args.world_size 151 | # Use torch.multiprocessing.spawn to launch distributed processes: the 152 | # main_worker process function 153 | mp.spawn(main_worker, nprocs=ngpus_per_node, args=(ngpus_per_node, args)) 154 | else: 155 | # Simply call main_worker function 156 | main_worker(args.gpu, ngpus_per_node, args) 157 | 158 | 159 | def main_worker(gpu, ngpus_per_node, args): 160 | args.gpu = gpu 161 | 162 | # suppress printing if not first GPU on each node 163 | if args.multiprocessing_distributed and (args.gpu != 0 or args.rank != 0): 164 | def print_pass(*args): 165 | pass 166 | builtins.print = print_pass 167 | 168 | if args.gpu is not None: 169 | print("Use GPU: {} for training".format(args.gpu)) 170 | 171 | if args.distributed: 172 | if args.dist_url == "env://" and args.rank == -1: 173 | args.rank = int(os.environ["RANK"]) 174 | if args.multiprocessing_distributed: 175 | # For multiprocessing distributed training, rank needs to be the 176 | # global rank among all the processes 177 | args.rank = args.rank * ngpus_per_node + gpu 178 | dist.init_process_group(backend=args.dist_backend, init_method=args.dist_url, 179 | world_size=args.world_size, rank=args.rank) 180 | torch.distributed.barrier() 181 | # create model 182 | print("=> creating model '{}'".format(args.arch)) 183 | if args.arch.startswith('vit'): 184 | model = moco.builder.MoCo_ViT( 185 | partial(vits.__dict__[args.arch], pretext_token=True, stop_grad_conv1=args.stop_grad_conv1, global_pool='avg'), 186 | args.moco_dim, args.moco_mlp_dim, args.moco_t) 187 | else: 188 | model = moco.builder.MoCo_ResNet( 189 | partial(torchvision_models.__dict__[args.arch], zero_init_residual=True), 190 | args.moco_dim, args.moco_mlp_dim, args.moco_t) 191 | 192 | # infer learning rate before changing batch size 193 | args.lr = args.lr * args.batch_size / 256 194 | 195 | if not torch.cuda.is_available(): 196 | print('using CPU, this will be slow') 197 | elif args.distributed: 198 | # apply SyncBN 199 | model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model) 200 | # For multiprocessing distributed, DistributedDataParallel constructor 201 | # should always set the single device scope, otherwise, 202 | # DistributedDataParallel will use all available devices. 203 | if args.gpu is not None: 204 | torch.cuda.set_device(args.gpu) 205 | model.cuda(args.gpu) 206 | # When using a single GPU per process and per 207 | # DistributedDataParallel, we need to divide the batch size 208 | # ourselves based on the total number of GPUs we have 209 | args.batch_size = int(args.batch_size / args.world_size) 210 | args.workers = int((args.workers + ngpus_per_node - 1) / ngpus_per_node) 211 | model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu]) 212 | else: 213 | model.cuda() 214 | # DistributedDataParallel will divide and allocate batch_size to all 215 | # available GPUs if device_ids are not set 216 | model = torch.nn.parallel.DistributedDataParallel(model) 217 | elif args.gpu is not None: 218 | torch.cuda.set_device(args.gpu) 219 | model = model.cuda(args.gpu) 220 | # comment out the following line for debugging 221 | raise NotImplementedError("Only DistributedDataParallel is supported.") 222 | else: 223 | # AllGather/rank implementation in this code only supports DistributedDataParallel. 224 | raise NotImplementedError("Only DistributedDataParallel is supported.") 225 | print(model) # print model after SyncBatchNorm 226 | 227 | if args.optimizer == 'lars': 228 | optimizer = moco.optimizer.LARS(model.parameters(), args.lr, 229 | weight_decay=args.weight_decay, 230 | momentum=args.momentum) 231 | elif args.optimizer == 'adamw': 232 | optimizer = torch.optim.AdamW(model.parameters(), args.lr, 233 | weight_decay=args.weight_decay) 234 | 235 | scaler = torch.cuda.amp.GradScaler() 236 | summary_writer = SummaryWriter() if args.rank == 0 else None 237 | 238 | # optionally resume from a checkpoint 239 | if args.resume: 240 | if os.path.isfile(args.resume): 241 | print("=> loading checkpoint '{}'".format(args.resume)) 242 | if args.gpu is None: 243 | checkpoint = torch.load(args.resume) 244 | else: 245 | # Map model to be loaded to specified single gpu. 246 | loc = 'cuda:{}'.format(args.gpu) 247 | checkpoint = torch.load(args.resume, map_location=loc) 248 | args.start_epoch = checkpoint['epoch'] 249 | model.load_state_dict(checkpoint['state_dict']) 250 | optimizer.load_state_dict(checkpoint['optimizer']) 251 | scaler.load_state_dict(checkpoint['scaler']) 252 | print("=> loaded checkpoint '{}' (epoch {})" 253 | .format(args.resume, checkpoint['epoch'])) 254 | else: 255 | print("=> no checkpoint found at '{}'".format(args.resume)) 256 | 257 | cudnn.benchmark = True 258 | 259 | # Data loading code 260 | traindir = args.data 261 | used_tcga_file = args.tcga 262 | df_tcga = pd.read_csv(used_tcga_file) 263 | used_TCGA = df_tcga[df_tcga['used']==1]['dataset'].tolist() 264 | # normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], 265 | # std=[0.229, 0.224, 0.225]) 266 | # follow BYOL's augmentation recipe: https://arxiv.org/abs/2006.07733 267 | augmentation1 = [ 268 | transforms.RandomResizedCrop(224, scale=(args.crop_min, 1.)), 269 | transforms.RandomApply([ 270 | transforms.ColorJitter(0.4, 0.4, 0.2, 0.1) # not strengthened 271 | ], p=0.8), 272 | transforms.RandomGrayscale(p=0.2), 273 | transforms.RandomApply([moco.loader.GaussianBlur([.1, 2.])], p=1.0), 274 | transforms.RandomHorizontalFlip(), 275 | transforms.ToTensor() 276 | ] 277 | 278 | augmentation2 = [ 279 | transforms.RandomResizedCrop(224, scale=(args.crop_min, 1.)), 280 | transforms.RandomApply([ 281 | transforms.ColorJitter(0.4, 0.4, 0.2, 0.1) # not strengthened 282 | ], p=0.8), 283 | transforms.RandomGrayscale(p=0.2), 284 | transforms.RandomApply([moco.loader.GaussianBlur([.1, 2.])], p=0.1), 285 | transforms.RandomApply([moco.loader.Solarize()], p=0.2), 286 | transforms.RandomHorizontalFlip(), 287 | transforms.ToTensor() 288 | ] 289 | 290 | train_dataset = moco.loader.TCGADataset(data_dir=traindir, 291 | used_TCGA=used_TCGA, 292 | transform=moco.loader.TwoCropsTransform(transforms.Compose(augmentation1), 293 | transforms.Compose(augmentation2))) 294 | 295 | if args.distributed: 296 | train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset) 297 | else: 298 | train_sampler = None 299 | 300 | train_loader = torch.utils.data.DataLoader( 301 | train_dataset, batch_size=args.batch_size, shuffle=(train_sampler is None), 302 | num_workers=args.workers, pin_memory=True, sampler=train_sampler, drop_last=True) 303 | 304 | for epoch in range(args.start_epoch, args.epochs): 305 | if args.distributed: 306 | train_sampler.set_epoch(epoch) 307 | 308 | # train for one epoch 309 | train(train_loader, model, optimizer, scaler, summary_writer, epoch, args) 310 | 311 | if not args.multiprocessing_distributed or (args.multiprocessing_distributed 312 | and args.rank == 0): # only the first GPU saves checkpoint 313 | save_checkpoint({ 314 | 'epoch': epoch + 1, 315 | 'arch': args.arch, 316 | 'state_dict': model.state_dict(), 317 | 'optimizer' : optimizer.state_dict(), 318 | 'scaler': scaler.state_dict(), 319 | }, is_best=False, filename='checkpoint_%04d.pth.tar' % epoch) 320 | 321 | if args.rank == 0: 322 | summary_writer.close() 323 | 324 | def train(train_loader, model, optimizer, scaler, summary_writer, epoch, args): 325 | batch_time = AverageMeter('Time', ':6.3f') 326 | data_time = AverageMeter('Data', ':6.3f') 327 | learning_rates = AverageMeter('LR', ':.4e') 328 | losses = AverageMeter('Loss', ':.4e') 329 | progress = ProgressMeter( 330 | len(train_loader), 331 | [batch_time, data_time, learning_rates, losses], 332 | prefix="Epoch: [{}]".format(epoch)) 333 | 334 | # switch to train mode 335 | model.train() 336 | 337 | end = time.time() 338 | iters_per_epoch = len(train_loader) 339 | moco_m = args.moco_m 340 | for i, images in enumerate(train_loader): 341 | # measure data loading time 342 | data_time.update(time.time() - end) 343 | 344 | # adjust learning rate and momentum coefficient per iteration 345 | lr = adjust_learning_rate(optimizer, epoch + i / iters_per_epoch, args) 346 | learning_rates.update(lr) 347 | if args.moco_m_cos: 348 | moco_m = adjust_moco_momentum(epoch + i / iters_per_epoch, args) 349 | 350 | if args.gpu is not None: 351 | images[0] = images[0].cuda(args.gpu, non_blocking=True) 352 | images[1] = images[1].cuda(args.gpu, non_blocking=True) 353 | 354 | # compute output 355 | with torch.cuda.amp.autocast(True): 356 | loss = model(images[0], images[1], moco_m) 357 | 358 | losses.update(loss.item(), images[0].size(0)) 359 | if args.rank == 0: 360 | summary_writer.add_scalar("loss", loss.item(), epoch * iters_per_epoch + i) 361 | 362 | # compute gradient and do SGD step 363 | optimizer.zero_grad() 364 | scaler.scale(loss).backward() 365 | scaler.step(optimizer) 366 | scaler.update() 367 | 368 | # measure elapsed time 369 | batch_time.update(time.time() - end) 370 | end = time.time() 371 | 372 | if i % args.print_freq == 0: 373 | progress.display(i) 374 | 375 | 376 | def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'): 377 | torch.save(state, filename) 378 | if is_best: 379 | shutil.copyfile(filename, 'model_best.pth.tar') 380 | 381 | 382 | class AverageMeter(object): 383 | """Computes and stores the average and current value""" 384 | def __init__(self, name, fmt=':f'): 385 | self.name = name 386 | self.fmt = fmt 387 | self.reset() 388 | 389 | def reset(self): 390 | self.val = 0 391 | self.avg = 0 392 | self.sum = 0 393 | self.count = 0 394 | 395 | def update(self, val, n=1): 396 | self.val = val 397 | self.sum += val * n 398 | self.count += n 399 | self.avg = self.sum / self.count 400 | 401 | def __str__(self): 402 | fmtstr = '{name} {val' + self.fmt + '} ({avg' + self.fmt + '})' 403 | return fmtstr.format(**self.__dict__) 404 | 405 | 406 | class ProgressMeter(object): 407 | def __init__(self, num_batches, meters, prefix=""): 408 | self.batch_fmtstr = self._get_batch_fmtstr(num_batches) 409 | self.meters = meters 410 | self.prefix = prefix 411 | 412 | def display(self, batch): 413 | entries = [self.prefix + self.batch_fmtstr.format(batch)] 414 | entries += [str(meter) for meter in self.meters] 415 | print('\t'.join(entries)) 416 | 417 | def _get_batch_fmtstr(self, num_batches): 418 | num_digits = len(str(num_batches // 1)) 419 | fmt = '{:' + str(num_digits) + 'd}' 420 | return '[' + fmt + '/' + fmt.format(num_batches) + ']' 421 | 422 | 423 | def adjust_learning_rate(optimizer, epoch, args): 424 | """Decays the learning rate with half-cycle cosine after warmup""" 425 | if epoch < args.warmup_epochs: 426 | lr = args.lr * epoch / args.warmup_epochs 427 | else: 428 | lr = args.lr * 0.5 * (1. + math.cos(math.pi * (epoch - args.warmup_epochs) / (args.epochs - args.warmup_epochs))) 429 | for param_group in optimizer.param_groups: 430 | param_group['lr'] = lr 431 | return lr 432 | 433 | 434 | def adjust_moco_momentum(epoch, args): 435 | """Adjust moco momentum based on current epoch""" 436 | m = 1. - 0.5 * (1. + math.cos(math.pi * epoch / args.epochs)) * (1. - args.moco_m) 437 | return m 438 | 439 | 440 | if __name__ == '__main__': 441 | main() 442 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Attribution-NonCommercial 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More_considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution-NonCommercial 4.0 International Public 58 | License 59 | 60 | By exercising the Licensed Rights (defined below), You accept and agree 61 | to be bound by the terms and conditions of this Creative Commons 62 | Attribution-NonCommercial 4.0 International Public License ("Public 63 | License"). To the extent this Public License may be interpreted as a 64 | contract, You are granted the Licensed Rights in consideration of Your 65 | acceptance of these terms and conditions, and the Licensor grants You 66 | such rights in consideration of benefits the Licensor receives from 67 | making the Licensed Material available under these terms and 68 | conditions. 69 | 70 | Section 1 -- Definitions. 71 | 72 | a. Adapted Material means material subject to Copyright and Similar 73 | Rights that is derived from or based upon the Licensed Material 74 | and in which the Licensed Material is translated, altered, 75 | arranged, transformed, or otherwise modified in a manner requiring 76 | permission under the Copyright and Similar Rights held by the 77 | Licensor. For purposes of this Public License, where the Licensed 78 | Material is a musical work, performance, or sound recording, 79 | Adapted Material is always produced where the Licensed Material is 80 | synched in timed relation with a moving image. 81 | 82 | b. Adapter's License means the license You apply to Your Copyright 83 | and Similar Rights in Your contributions to Adapted Material in 84 | accordance with the terms and conditions of this Public License. 85 | 86 | c. Copyright and Similar Rights means copyright and/or similar rights 87 | closely related to copyright including, without limitation, 88 | performance, broadcast, sound recording, and Sui Generis Database 89 | Rights, without regard to how the rights are labeled or 90 | categorized. For purposes of this Public License, the rights 91 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 92 | Rights. 93 | d. Effective Technological Measures means those measures that, in the 94 | absence of proper authority, may not be circumvented under laws 95 | fulfilling obligations under Article 11 of the WIPO Copyright 96 | Treaty adopted on December 20, 1996, and/or similar international 97 | agreements. 98 | 99 | e. Exceptions and Limitations means fair use, fair dealing, and/or 100 | any other exception or limitation to Copyright and Similar Rights 101 | that applies to Your use of the Licensed Material. 102 | 103 | f. Licensed Material means the artistic or literary work, database, 104 | or other material to which the Licensor applied this Public 105 | License. 106 | 107 | g. Licensed Rights means the rights granted to You subject to the 108 | terms and conditions of this Public License, which are limited to 109 | all Copyright and Similar Rights that apply to Your use of the 110 | Licensed Material and that the Licensor has authority to license. 111 | 112 | h. Licensor means the individual(s) or entity(ies) granting rights 113 | under this Public License. 114 | 115 | i. NonCommercial means not primarily intended for or directed towards 116 | commercial advantage or monetary compensation. For purposes of 117 | this Public License, the exchange of the Licensed Material for 118 | other material subject to Copyright and Similar Rights by digital 119 | file-sharing or similar means is NonCommercial provided there is 120 | no payment of monetary compensation in connection with the 121 | exchange. 122 | 123 | j. Share means to provide material to the public by any means or 124 | process that requires permission under the Licensed Rights, such 125 | as reproduction, public display, public performance, distribution, 126 | dissemination, communication, or importation, and to make material 127 | available to the public including in ways that members of the 128 | public may access the material from a place and at a time 129 | individually chosen by them. 130 | 131 | k. Sui Generis Database Rights means rights other than copyright 132 | resulting from Directive 96/9/EC of the European Parliament and of 133 | the Council of 11 March 1996 on the legal protection of databases, 134 | as amended and/or succeeded, as well as other essentially 135 | equivalent rights anywhere in the world. 136 | 137 | l. You means the individual or entity exercising the Licensed Rights 138 | under this Public License. Your has a corresponding meaning. 139 | 140 | Section 2 -- Scope. 141 | 142 | a. License grant. 143 | 144 | 1. Subject to the terms and conditions of this Public License, 145 | the Licensor hereby grants You a worldwide, royalty-free, 146 | non-sublicensable, non-exclusive, irrevocable license to 147 | exercise the Licensed Rights in the Licensed Material to: 148 | 149 | a. reproduce and Share the Licensed Material, in whole or 150 | in part, for NonCommercial purposes only; and 151 | 152 | b. produce, reproduce, and Share Adapted Material for 153 | NonCommercial purposes only. 154 | 155 | 2. Exceptions and Limitations. For the avoidance of doubt, where 156 | Exceptions and Limitations apply to Your use, this Public 157 | License does not apply, and You do not need to comply with 158 | its terms and conditions. 159 | 160 | 3. Term. The term of this Public License is specified in Section 161 | 6(a). 162 | 163 | 4. Media and formats; technical modifications allowed. The 164 | Licensor authorizes You to exercise the Licensed Rights in 165 | all media and formats whether now known or hereafter created, 166 | and to make technical modifications necessary to do so. The 167 | Licensor waives and/or agrees not to assert any right or 168 | authority to forbid You from making technical modifications 169 | necessary to exercise the Licensed Rights, including 170 | technical modifications necessary to circumvent Effective 171 | Technological Measures. For purposes of this Public License, 172 | simply making modifications authorized by this Section 2(a) 173 | (4) never produces Adapted Material. 174 | 175 | 5. Downstream recipients. 176 | 177 | a. Offer from the Licensor -- Licensed Material. Every 178 | recipient of the Licensed Material automatically 179 | receives an offer from the Licensor to exercise the 180 | Licensed Rights under the terms and conditions of this 181 | Public License. 182 | 183 | b. No downstream restrictions. You may not offer or impose 184 | any additional or different terms or conditions on, or 185 | apply any Effective Technological Measures to, the 186 | Licensed Material if doing so restricts exercise of the 187 | Licensed Rights by any recipient of the Licensed 188 | Material. 189 | 190 | 6. No endorsement. Nothing in this Public License constitutes or 191 | may be construed as permission to assert or imply that You 192 | are, or that Your use of the Licensed Material is, connected 193 | with, or sponsored, endorsed, or granted official status by, 194 | the Licensor or others designated to receive attribution as 195 | provided in Section 3(a)(1)(A)(i). 196 | 197 | b. Other rights. 198 | 199 | 1. Moral rights, such as the right of integrity, are not 200 | licensed under this Public License, nor are publicity, 201 | privacy, and/or other similar personality rights; however, to 202 | the extent possible, the Licensor waives and/or agrees not to 203 | assert any such rights held by the Licensor to the limited 204 | extent necessary to allow You to exercise the Licensed 205 | Rights, but not otherwise. 206 | 207 | 2. Patent and trademark rights are not licensed under this 208 | Public License. 209 | 210 | 3. To the extent possible, the Licensor waives any right to 211 | collect royalties from You for the exercise of the Licensed 212 | Rights, whether directly or through a collecting society 213 | under any voluntary or waivable statutory or compulsory 214 | licensing scheme. In all other cases the Licensor expressly 215 | reserves any right to collect such royalties, including when 216 | the Licensed Material is used other than for NonCommercial 217 | purposes. 218 | 219 | Section 3 -- License Conditions. 220 | 221 | Your exercise of the Licensed Rights is expressly made subject to the 222 | following conditions. 223 | 224 | a. Attribution. 225 | 226 | 1. If You Share the Licensed Material (including in modified 227 | form), You must: 228 | 229 | a. retain the following if it is supplied by the Licensor 230 | with the Licensed Material: 231 | 232 | i. identification of the creator(s) of the Licensed 233 | Material and any others designated to receive 234 | attribution, in any reasonable manner requested by 235 | the Licensor (including by pseudonym if 236 | designated); 237 | 238 | ii. a copyright notice; 239 | 240 | iii. a notice that refers to this Public License; 241 | 242 | iv. a notice that refers to the disclaimer of 243 | warranties; 244 | 245 | v. a URI or hyperlink to the Licensed Material to the 246 | extent reasonably practicable; 247 | 248 | b. indicate if You modified the Licensed Material and 249 | retain an indication of any previous modifications; and 250 | 251 | c. indicate the Licensed Material is licensed under this 252 | Public License, and include the text of, or the URI or 253 | hyperlink to, this Public License. 254 | 255 | 2. You may satisfy the conditions in Section 3(a)(1) in any 256 | reasonable manner based on the medium, means, and context in 257 | which You Share the Licensed Material. For example, it may be 258 | reasonable to satisfy the conditions by providing a URI or 259 | hyperlink to a resource that includes the required 260 | information. 261 | 262 | 3. If requested by the Licensor, You must remove any of the 263 | information required by Section 3(a)(1)(A) to the extent 264 | reasonably practicable. 265 | 266 | 4. If You Share Adapted Material You produce, the Adapter's 267 | License You apply must not prevent recipients of the Adapted 268 | Material from complying with this Public License. 269 | 270 | Section 4 -- Sui Generis Database Rights. 271 | 272 | Where the Licensed Rights include Sui Generis Database Rights that 273 | apply to Your use of the Licensed Material: 274 | 275 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 276 | to extract, reuse, reproduce, and Share all or a substantial 277 | portion of the contents of the database for NonCommercial purposes 278 | only; 279 | 280 | b. if You include all or a substantial portion of the database 281 | contents in a database in which You have Sui Generis Database 282 | Rights, then the database in which You have Sui Generis Database 283 | Rights (but not its individual contents) is Adapted Material; and 284 | 285 | c. You must comply with the conditions in Section 3(a) if You Share 286 | all or a substantial portion of the contents of the database. 287 | 288 | For the avoidance of doubt, this Section 4 supplements and does not 289 | replace Your obligations under this Public License where the Licensed 290 | Rights include other Copyright and Similar Rights. 291 | 292 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 293 | 294 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 295 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 296 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 297 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 298 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 299 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 300 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 301 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 302 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 303 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 304 | 305 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 306 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 307 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 308 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 309 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 310 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 311 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 312 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 313 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 314 | 315 | c. The disclaimer of warranties and limitation of liability provided 316 | above shall be interpreted in a manner that, to the extent 317 | possible, most closely approximates an absolute disclaimer and 318 | waiver of all liability. 319 | 320 | Section 6 -- Term and Termination. 321 | 322 | a. This Public License applies for the term of the Copyright and 323 | Similar Rights licensed here. However, if You fail to comply with 324 | this Public License, then Your rights under this Public License 325 | terminate automatically. 326 | 327 | b. Where Your right to use the Licensed Material has terminated under 328 | Section 6(a), it reinstates: 329 | 330 | 1. automatically as of the date the violation is cured, provided 331 | it is cured within 30 days of Your discovery of the 332 | violation; or 333 | 334 | 2. upon express reinstatement by the Licensor. 335 | 336 | For the avoidance of doubt, this Section 6(b) does not affect any 337 | right the Licensor may have to seek remedies for Your violations 338 | of this Public License. 339 | 340 | c. For the avoidance of doubt, the Licensor may also offer the 341 | Licensed Material under separate terms or conditions or stop 342 | distributing the Licensed Material at any time; however, doing so 343 | will not terminate this Public License. 344 | 345 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 346 | License. 347 | 348 | Section 7 -- Other Terms and Conditions. 349 | 350 | a. The Licensor shall not be bound by any additional or different 351 | terms or conditions communicated by You unless expressly agreed. 352 | 353 | b. Any arrangements, understandings, or agreements regarding the 354 | Licensed Material not stated herein are separate from and 355 | independent of the terms and conditions of this Public License. 356 | 357 | Section 8 -- Interpretation. 358 | 359 | a. For the avoidance of doubt, this Public License does not, and 360 | shall not be interpreted to, reduce, limit, restrict, or impose 361 | conditions on any use of the Licensed Material that could lawfully 362 | be made without permission under this Public License. 363 | 364 | b. To the extent possible, if any provision of this Public License is 365 | deemed unenforceable, it shall be automatically reformed to the 366 | minimum extent necessary to make it enforceable. If the provision 367 | cannot be reformed, it shall be severed from this Public License 368 | without affecting the enforceability of the remaining terms and 369 | conditions. 370 | 371 | c. No term or condition of this Public License will be waived and no 372 | failure to comply consented to unless expressly agreed to by the 373 | Licensor. 374 | 375 | d. Nothing in this Public License constitutes or may be interpreted 376 | as a limitation upon, or waiver of, any privileges and immunities 377 | that apply to the Licensor or You, including from the legal 378 | processes of any jurisdiction or authority. 379 | 380 | ======================================================================= 381 | 382 | Creative Commons is not a party to its public 383 | licenses. Notwithstanding, Creative Commons may elect to apply one of 384 | its public licenses to material it publishes and in those instances 385 | will be considered the “Licensor.” The text of the Creative Commons 386 | public licenses is dedicated to the public domain under the CC0 Public 387 | Domain Dedication. Except for the limited purpose of indicating that 388 | material is shared under a Creative Commons public license or as 389 | otherwise permitted by the Creative Commons policies published at 390 | creativecommons.org/policies, Creative Commons does not authorize the 391 | use of the trademark "Creative Commons" or any other trademark or logo 392 | of Creative Commons without its prior written consent including, 393 | without limitation, in connection with any unauthorized modifications 394 | to any of its public licenses or any other arrangements, 395 | understandings, or agreements concerning use of licensed material. For 396 | the avoidance of doubt, this paragraph does not form part of the 397 | public licenses. 398 | 399 | Creative Commons may be contacted at creativecommons.org. -------------------------------------------------------------------------------- /main_cross.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # Copyright (c) Facebook, Inc. and its affiliates. 4 | # All rights reserved. 5 | 6 | # This source code is licensed under the license found in the 7 | # LICENSE file in the root directory of this source tree. 8 | 9 | import argparse 10 | import builtins 11 | import math 12 | import os 13 | import random 14 | import shutil 15 | import time 16 | import warnings 17 | from functools import partial 18 | 19 | import torch 20 | import torch.nn as nn 21 | import torch.nn.parallel 22 | import torch.backends.cudnn as cudnn 23 | import torch.distributed as dist 24 | import torch.optim 25 | import torch.multiprocessing as mp 26 | import torch.utils.data 27 | import torch.utils.data.distributed 28 | import torchvision.transforms as transforms 29 | import torchvision.datasets as datasets 30 | # from petrel_client.utils.data import DataLoader 31 | import torchvision.models as torchvision_models 32 | from torch.utils.tensorboard import SummaryWriter 33 | 34 | import moco.builder 35 | import moco.loader 36 | import moco.optimizer 37 | 38 | import vits 39 | import pandas as pd 40 | 41 | 42 | torchvision_model_names = sorted(name for name in torchvision_models.__dict__ 43 | if name.islower() and not name.startswith("__") 44 | and callable(torchvision_models.__dict__[name])) 45 | 46 | model_names = ['vit_small', 'vit_base', 'vit_conv_small', 'vit_conv_base'] + torchvision_model_names 47 | 48 | parser = argparse.ArgumentParser(description='MoCo ImageNet Pre-Training') 49 | parser.add_argument('data', metavar='PATH', 50 | help='PATH to dataset') 51 | parser.add_argument('--tcga', metavar='PATH', 52 | help='path to a csv record of used TCGA') 53 | parser.add_argument('-a', '--arch', metavar='ARCH', default='vit_base', 54 | choices=model_names, 55 | help='model architecture: ' + 56 | ' | '.join(model_names) + 57 | ' (default: vit_base)') 58 | parser.add_argument('-j', '--workers', default=32, type=int, metavar='N', 59 | help='number of data loading workers (default: 32)') 60 | parser.add_argument('--epochs', default=100, type=int, metavar='N', 61 | help='number of total epochs to run') 62 | parser.add_argument('--start-epoch', default=0, type=int, metavar='N', 63 | help='manual epoch number (useful on restarts)') 64 | parser.add_argument('-b', '--batch-size', default=4096, type=int, 65 | metavar='N', 66 | help='mini-batch size (default: 4096), this is the total ' 67 | 'batch size of all GPUs on all nodes when ' 68 | 'using Data Parallel or Distributed Data Parallel') 69 | parser.add_argument('--lr', '--learning-rate', default=0.6, type=float, 70 | metavar='LR', help='initial (base) learning rate', dest='lr') 71 | parser.add_argument('--momentum', default=0.9, type=float, metavar='M', 72 | help='momentum') 73 | parser.add_argument('--wd', '--weight-decay', default=1e-6, type=float, 74 | metavar='W', help='weight decay (default: 1e-6)', 75 | dest='weight_decay') 76 | parser.add_argument('-p', '--print-freq', default=10, type=int, 77 | metavar='N', help='print frequency (default: 10)') 78 | parser.add_argument('--ckp', default='', type=str, metavar='DIR', 79 | help='path to a dir saving checkpoint (default: none)') 80 | parser.add_argument('--firstphase', default='', type=str, metavar='PATH', 81 | help='path to checkpoint in first phase (default: none)') 82 | parser.add_argument('--resume', default='', type=str, metavar='PATH', 83 | help='path to latest checkpoint (default: none)') 84 | parser.add_argument('--world-size', default=-1, type=int, 85 | help='number of nodes for distributed training') 86 | parser.add_argument('--rank', default=-1, type=int, 87 | help='node rank for distributed training') 88 | parser.add_argument('--dist-url', default='env://', type=str, 89 | help='url used to set up distributed training') 90 | parser.add_argument('--dist-backend', default='nccl', type=str, 91 | help='distributed backend') 92 | parser.add_argument('--seed', default=None, type=int, 93 | help='seed for initializing training. ') 94 | parser.add_argument('--gpu', default=None, type=int, 95 | help='GPU id to use.') 96 | parser.add_argument('--multiprocessing-distributed', action='store_true', 97 | help='Use multi-processing distributed training to launch ' 98 | 'N processes per node, which has N GPUs. This is the ' 99 | 'fastest way to use PyTorch for either single node or ' 100 | 'multi node data parallel training') 101 | 102 | # moco specific configs: 103 | parser.add_argument('--moco-dim', default=256, type=int, 104 | help='feature dimension (default: 256)') 105 | parser.add_argument('--moco-mlp-dim', default=4096, type=int, 106 | help='hidden dimension in MLPs (default: 4096)') 107 | parser.add_argument('--moco-m', default=0.99, type=float, 108 | help='moco momentum of updating momentum encoder (default: 0.99)') 109 | parser.add_argument('--moco-m-cos', action='store_true', 110 | help='gradually increase moco momentum to 1 with a ' 111 | 'half-cycle cosine schedule') 112 | parser.add_argument('--moco-t', default=1.0, type=float, 113 | help='softmax temperature (default: 1.0)') 114 | parser.add_argument('--bridge-t', default=1.0, type=float, 115 | help='bridging coefficient weighting MoCo and SimSiam (default: 1.0)') 116 | 117 | # vit specific configs: 118 | parser.add_argument('--stop-grad-conv1', action='store_true', 119 | help='stop-grad after first conv, or patch embedding') 120 | 121 | # other upgrades 122 | parser.add_argument('--optimizer', default='lars', type=str, 123 | choices=['lars', 'adamw'], 124 | help='optimizer used (default: lars)') 125 | parser.add_argument('--warmup-epochs', default=10, type=int, metavar='N', 126 | help='number of warmup epochs') 127 | parser.add_argument('--crop-min', default=0.08, type=float, 128 | help='minimum scale for random cropping (default: 0.08)') 129 | 130 | def main(): 131 | args = parser.parse_args() 132 | if not os.path.exists(args.ckp): 133 | os.makedirs(args.ckp) 134 | 135 | if args.seed is not None: 136 | random.seed(args.seed) 137 | torch.manual_seed(args.seed) 138 | cudnn.deterministic = True 139 | warnings.warn('You have chosen to seed training. ' 140 | 'This will turn on the CUDNN deterministic setting, ' 141 | 'which can slow down your training considerably! ' 142 | 'You may see unexpected behavior when restarting ' 143 | 'from checkpoints.') 144 | 145 | if args.gpu is not None: 146 | warnings.warn('You have chosen a specific GPU. This will completely ' 147 | 'disable data parallelism.') 148 | 149 | if args.dist_url == "env://" and args.world_size == -1: 150 | args.world_size = int(os.environ["WORLD_SIZE"]) 151 | 152 | args.distributed = args.world_size > 1 or args.multiprocessing_distributed 153 | 154 | ngpus_per_node = torch.cuda.device_count() 155 | if args.multiprocessing_distributed: 156 | # Since we have ngpus_per_node processes per node, the total world_size 157 | # needs to be adjusted accordingly 158 | args.world_size = ngpus_per_node * args.world_size 159 | # Use torch.multiprocessing.spawn to launch distributed processes: the 160 | # main_worker process function 161 | mp.spawn(main_worker, nprocs=ngpus_per_node, args=(ngpus_per_node, args)) 162 | else: 163 | # Simply call main_worker function 164 | main_worker(args.gpu, ngpus_per_node, args) 165 | 166 | 167 | def main_worker(gpu, ngpus_per_node, args): 168 | args.gpu = gpu 169 | 170 | # suppress printing if not first GPU on each node 171 | if args.multiprocessing_distributed and (args.gpu != 0 or args.rank != 0): 172 | def print_pass(*args): 173 | pass 174 | builtins.print = print_pass 175 | 176 | if args.gpu is not None: 177 | print("Use GPU: {} for training".format(args.gpu)) 178 | 179 | if args.distributed: 180 | if args.dist_url == "env://" and args.rank == -1: 181 | args.rank = int(os.environ["RANK"]) 182 | if args.multiprocessing_distributed: 183 | # For multiprocessing distributed training, rank needs to be the 184 | # global rank among all the processes 185 | args.rank = args.rank * ngpus_per_node + gpu 186 | dist.init_process_group(backend=args.dist_backend, init_method=args.dist_url, 187 | world_size=args.world_size, rank=args.rank) 188 | torch.distributed.barrier() 189 | # create model 190 | print("=> creating model '{}'".format(args.arch)) 191 | if args.arch.startswith('vit'): 192 | model = moco.builder.CrossStain( 193 | partial(vits.__dict__[args.arch], pretext_token=True, stop_grad_conv1=args.stop_grad_conv1, global_pool='avg'), 194 | args.moco_dim, args.moco_mlp_dim, args.moco_t) 195 | else: 196 | raise NotImplementedError('Only support ViT ...') 197 | 198 | # infer learning rate before changing batch size 199 | args.lr = args.lr * args.batch_size / 256 200 | 201 | if not torch.cuda.is_available(): 202 | print('using CPU, this will be slow') 203 | elif args.distributed: 204 | # apply SyncBN 205 | model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model) 206 | # For multiprocessing distributed, DistributedDataParallel constructor 207 | # should always set the single device scope, otherwise, 208 | # DistributedDataParallel will use all available devices. 209 | if args.gpu is not None: 210 | torch.cuda.set_device(args.gpu) 211 | model.cuda(args.gpu) 212 | # When using a single GPU per process and per 213 | # DistributedDataParallel, we need to divide the batch size 214 | # ourselves based on the total number of GPUs we have 215 | args.batch_size = int(args.batch_size / args.world_size) 216 | args.workers = int((args.workers + ngpus_per_node - 1) / ngpus_per_node) 217 | model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu]) 218 | else: 219 | model.cuda() 220 | # DistributedDataParallel will divide and allocate batch_size to all 221 | # available GPUs if device_ids are not set 222 | model = torch.nn.parallel.DistributedDataParallel(model) 223 | elif args.gpu is not None: 224 | torch.cuda.set_device(args.gpu) 225 | model = model.cuda(args.gpu) 226 | # comment out the following line for debugging 227 | raise NotImplementedError("Only DistributedDataParallel is supported.") 228 | else: 229 | # AllGather/rank implementation in this code only supports DistributedDataParallel. 230 | raise NotImplementedError("Only DistributedDataParallel is supported.") 231 | print(model) # print model after SyncBatchNorm 232 | 233 | if args.optimizer == 'lars': 234 | optimizer = moco.optimizer.LARS(model.parameters(), args.lr, 235 | weight_decay=args.weight_decay, 236 | momentum=args.momentum) 237 | elif args.optimizer == 'adamw': 238 | optimizer = torch.optim.AdamW(model.parameters(), args.lr, 239 | weight_decay=args.weight_decay) 240 | 241 | scaler = torch.cuda.amp.GradScaler() 242 | summary_writer = SummaryWriter() if args.rank == 0 else None 243 | 244 | # optionally continue from a checkpoint in first phase 245 | if args.firstphase: 246 | if os.path.isfile(args.firstphase): 247 | print("=> loading checkpoint '{}' in first stage".format(args.firstphase)) 248 | if args.gpu is None: 249 | checkpoint = torch.load(args.firstphase) 250 | else: 251 | # Map model to be loaded to specified single gpu. 252 | loc = 'cuda:{}'.format(args.gpu) 253 | checkpoint = torch.load(args.firstphase, map_location=loc) 254 | model.load_state_dict(checkpoint['state_dict'], strict=False) 255 | print("=> loaded checkpoint '{}' in first stage" 256 | .format(args.firstphase)) 257 | else: 258 | print("=> no checkpoint found at '{}'".format(args.firstphase)) 259 | # or resume from a checkpoint 260 | elif args.resume: 261 | if os.path.isfile(args.resume): 262 | print("=> loading checkpoint '{}'".format(args.resume)) 263 | if args.gpu is None: 264 | checkpoint = torch.load(args.resume) 265 | else: 266 | # Map model to be loaded to specified single gpu. 267 | loc = 'cuda:{}'.format(args.gpu) 268 | checkpoint = torch.load(args.resume, map_location=loc) 269 | args.start_epoch = checkpoint['epoch'] 270 | model.load_state_dict(checkpoint['state_dict']) 271 | optimizer.load_state_dict(checkpoint['optimizer']) 272 | scaler.load_state_dict(checkpoint['scaler']) 273 | print("=> loaded checkpoint '{}' (epoch {})" 274 | .format(args.resume, checkpoint['epoch'])) 275 | else: 276 | print("=> no checkpoint found at '{}'".format(args.resume)) 277 | 278 | cudnn.benchmark = True 279 | 280 | # Data loading code 281 | # traindir = os.path.join(args.data, 'train') 282 | traindir = args.data 283 | # normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], 284 | # std=[0.229, 0.224, 0.225]) 285 | 286 | augmentation_he = [ 287 | transforms.Resize(224), 288 | transforms.CenterCrop(224), 289 | transforms.RandomApply([ 290 | transforms.ColorJitter(0.4, 0.4, 0.2, 0.04) # not strengthened 291 | ], p=0.8), 292 | moco.loader.GaussianBlur([.1, 2.]), 293 | transforms.RandomHorizontalFlip(), 294 | transforms.ToTensor() 295 | ] 296 | 297 | color_jitter = transforms.RandomApply([transforms.ColorJitter(0.4, 0.4, 0.2, 0.04)], p=0.8) 298 | 299 | augmentation_ihc_large = [ 300 | transforms.Resize(224), 301 | transforms.CenterCrop(224), 302 | moco.loader.GaussianBlur([.1, 2.]), 303 | transforms.RandomHorizontalFlip(), 304 | transforms.ToTensor() 305 | ] 306 | 307 | augmentation_ihc_little = [ 308 | transforms.Resize(64), 309 | transforms.RandomCrop(16), 310 | moco.loader.GaussianBlur([.1, 2.]), 311 | transforms.RandomHorizontalFlip(), 312 | transforms.ToTensor() 313 | ] 314 | 315 | bci_dataset = moco.loader.BCIDataset( 316 | os.path.join(traindir, 'BCI_dataset'), 317 | transforms.Compose(augmentation_he), 318 | transforms.Compose(augmentation_ihc_large), 319 | transforms.Compose(augmentation_ihc_little), 320 | color_jitter 321 | ) 322 | 323 | hyreco_dataset1 = moco.loader.HyReCoDataset( 324 | os.path.join(traindir, 'hyreco_patch'), 325 | transforms.Compose(augmentation_he), 326 | transforms.Compose(augmentation_ihc_large), 327 | transforms.Compose(augmentation_ihc_little), 328 | color_jitter 329 | ) 330 | 331 | train_dataset = torch.utils.data.ConcatDataset([bci_dataset, hyreco_dataset1]) 332 | 333 | 334 | if args.distributed: 335 | train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset) 336 | else: 337 | train_sampler = None 338 | 339 | train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=args.batch_size, shuffle=(train_sampler is None), 340 | num_workers=args.workers, pin_memory=True, sampler=train_sampler, drop_last=True, 341 | persistent_workers=False) 342 | 343 | for epoch in range(args.start_epoch, args.epochs): 344 | if args.distributed: 345 | train_sampler.set_epoch(epoch) 346 | 347 | # train for one epoch 348 | train(train_loader, model, optimizer, scaler, summary_writer, epoch, args) 349 | 350 | if not args.multiprocessing_distributed or (args.multiprocessing_distributed 351 | and args.rank == 0): # only the first GPU saves checkpoint 352 | save_checkpoint({ 353 | 'epoch': epoch + 1, 354 | 'arch': args.arch, 355 | 'state_dict': model.state_dict(), 356 | 'optimizer' : optimizer.state_dict(), 357 | 'scaler': scaler.state_dict(), 358 | }, is_best=False, filename=os.path.join(args.ckp, 'checkpoint_%04d.pth.tar' % epoch)) 359 | 360 | if args.rank == 0: 361 | summary_writer.close() 362 | 363 | def train(train_loader, model, optimizer, scaler, summary_writer, epoch, args): 364 | batch_time = AverageMeter('Time', ':6.3f') 365 | data_time = AverageMeter('Data', ':6.3f') 366 | learning_rates = AverageMeter('LR', ':.4e') 367 | losses = AverageMeter('Loss', ':.4e') 368 | progress = ProgressMeter( 369 | len(train_loader), 370 | [batch_time, data_time, learning_rates, losses], 371 | prefix="Epoch: [{}]".format(epoch)) 372 | 373 | # switch to train mode 374 | model.train() 375 | 376 | end = time.time() 377 | iters_per_epoch = len(train_loader) 378 | moco_m = args.moco_m 379 | for i, (img_he, img_ihc, stain) in enumerate(train_loader): 380 | # measure data loading time 381 | data_time.update(time.time() - end) 382 | 383 | # adjust learning rate and momentum coefficient per iteration 384 | lr = adjust_learning_rate(optimizer, epoch + i / iters_per_epoch, args) 385 | learning_rates.update(lr) 386 | if args.moco_m_cos: 387 | moco_m = adjust_moco_momentum(epoch + i / iters_per_epoch, args) 388 | 389 | if args.gpu is not None: 390 | img_he = img_he.cuda(args.gpu, non_blocking=True) 391 | img_ihc = img_ihc.cuda(args.gpu, non_blocking=True) 392 | stain = stain.cuda(args.gpu, non_blocking=True) 393 | 394 | # compute output 395 | with torch.cuda.amp.autocast(True): 396 | loss = model(img_he, img_ihc, stain, moco_m) 397 | 398 | losses.update(loss.item(), img_he.size(0)) 399 | if args.rank == 0: 400 | summary_writer.add_scalar("loss", loss.item(), epoch * iters_per_epoch + i) 401 | 402 | # compute gradient and do SGD step 403 | optimizer.zero_grad() 404 | scaler.scale(loss).backward() 405 | scaler.step(optimizer) 406 | scaler.update() 407 | 408 | # measure elapsed time 409 | batch_time.update(time.time() - end) 410 | end = time.time() 411 | 412 | if i % args.print_freq == 0: 413 | progress.display(i) 414 | 415 | 416 | def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'): 417 | torch.save(state, filename) 418 | if is_best: 419 | shutil.copyfile(filename, 'model_best.pth.tar') 420 | 421 | 422 | class AverageMeter(object): 423 | """Computes and stores the average and current value""" 424 | def __init__(self, name, fmt=':f'): 425 | self.name = name 426 | self.fmt = fmt 427 | self.reset() 428 | 429 | def reset(self): 430 | self.val = 0 431 | self.avg = 0 432 | self.sum = 0 433 | self.count = 0 434 | 435 | def update(self, val, n=1): 436 | self.val = val 437 | self.sum += val * n 438 | self.count += n 439 | self.avg = self.sum / self.count 440 | 441 | def __str__(self): 442 | fmtstr = '{name} {val' + self.fmt + '} ({avg' + self.fmt + '})' 443 | return fmtstr.format(**self.__dict__) 444 | 445 | 446 | class ProgressMeter(object): 447 | def __init__(self, num_batches, meters, prefix=""): 448 | self.batch_fmtstr = self._get_batch_fmtstr(num_batches) 449 | self.meters = meters 450 | self.prefix = prefix 451 | 452 | def display(self, batch): 453 | entries = [self.prefix + self.batch_fmtstr.format(batch)] 454 | entries += [str(meter) for meter in self.meters] 455 | print('\t'.join(entries)) 456 | 457 | def _get_batch_fmtstr(self, num_batches): 458 | num_digits = len(str(num_batches // 1)) 459 | fmt = '{:' + str(num_digits) + 'd}' 460 | return '[' + fmt + '/' + fmt.format(num_batches) + ']' 461 | 462 | 463 | def adjust_learning_rate(optimizer, epoch, args): 464 | """Decays the learning rate with half-cycle cosine after warmup""" 465 | if epoch < args.warmup_epochs: 466 | lr = args.lr * epoch / args.warmup_epochs 467 | else: 468 | lr = args.lr * 0.5 * (1. + math.cos(math.pi * (epoch - args.warmup_epochs) / (args.epochs - args.warmup_epochs))) 469 | for param_group in optimizer.param_groups: 470 | param_group['lr'] = lr 471 | return lr 472 | 473 | 474 | def adjust_moco_momentum(epoch, args): 475 | """Adjust moco momentum based on current epoch""" 476 | m = 1. - 0.5 * (1. + math.cos(math.pi * epoch / args.epochs)) * (1. - args.moco_m) 477 | return m 478 | 479 | 480 | if __name__ == '__main__': 481 | main() 482 | -------------------------------------------------------------------------------- /main_bridge.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # Copyright (c) Facebook, Inc. and its affiliates. 4 | # All rights reserved. 5 | 6 | # This source code is licensed under the license found in the 7 | # LICENSE file in the root directory of this source tree. 8 | 9 | import argparse 10 | import builtins 11 | import math 12 | import os 13 | import random 14 | import shutil 15 | import time 16 | import warnings 17 | from functools import partial 18 | 19 | import torch 20 | import torch.nn as nn 21 | import torch.nn.parallel 22 | import torch.backends.cudnn as cudnn 23 | import torch.distributed as dist 24 | import torch.optim 25 | import torch.multiprocessing as mp 26 | import torch.utils.data 27 | import torch.utils.data.distributed 28 | import torchvision.transforms as transforms 29 | import torchvision.datasets as datasets 30 | # from petrel_client.utils.data import DataLoader 31 | import torchvision.models as torchvision_models 32 | from torch.utils.tensorboard import SummaryWriter 33 | 34 | import moco.builder 35 | import moco.loader 36 | import moco.optimizer 37 | 38 | import vits 39 | import pandas as pd 40 | 41 | 42 | torchvision_model_names = sorted(name for name in torchvision_models.__dict__ 43 | if name.islower() and not name.startswith("__") 44 | and callable(torchvision_models.__dict__[name])) 45 | 46 | model_names = ['vit_small', 'vit_base', 'vit_conv_small', 'vit_conv_base'] + torchvision_model_names 47 | 48 | parser = argparse.ArgumentParser(description='MoCo ImageNet Pre-Training') 49 | parser.add_argument('data', metavar='PATH', 50 | help='PATH to dataset') 51 | parser.add_argument('--tcga', metavar='PATH', 52 | help='path to a csv record of used TCGA') 53 | parser.add_argument('-a', '--arch', metavar='ARCH', default='vit_base', 54 | choices=model_names, 55 | help='model architecture: ' + 56 | ' | '.join(model_names) + 57 | ' (default: vit_base)') 58 | parser.add_argument('-j', '--workers', default=32, type=int, metavar='N', 59 | help='number of data loading workers (default: 32)') 60 | parser.add_argument('--epochs', default=100, type=int, metavar='N', 61 | help='number of total epochs to run') 62 | parser.add_argument('--start-epoch', default=0, type=int, metavar='N', 63 | help='manual epoch number (useful on restarts)') 64 | parser.add_argument('-b', '--batch-size', default=4096, type=int, 65 | metavar='N', 66 | help='mini-batch size (default: 4096), this is the total ' 67 | 'batch size of all GPUs on all nodes when ' 68 | 'using Data Parallel or Distributed Data Parallel') 69 | parser.add_argument('--lr', '--learning-rate', default=0.6, type=float, 70 | metavar='LR', help='initial (base) learning rate', dest='lr') 71 | parser.add_argument('--momentum', default=0.9, type=float, metavar='M', 72 | help='momentum') 73 | parser.add_argument('--wd', '--weight-decay', default=1e-6, type=float, 74 | metavar='W', help='weight decay (default: 1e-6)', 75 | dest='weight_decay') 76 | parser.add_argument('-p', '--print-freq', default=10, type=int, 77 | metavar='N', help='print frequency (default: 10)') 78 | parser.add_argument('--ckp', default='', type=str, metavar='DIR', 79 | help='path to a dir saving checkpoint (default: none)') 80 | parser.add_argument('--firstphase', default='', type=str, metavar='PATH', 81 | help='path to checkpoint in first phase (default: none)') 82 | parser.add_argument('--resume', default='', type=str, metavar='PATH', 83 | help='path to latest checkpoint (default: none)') 84 | parser.add_argument('--world-size', default=-1, type=int, 85 | help='number of nodes for distributed training') 86 | parser.add_argument('--rank', default=-1, type=int, 87 | help='node rank for distributed training') 88 | parser.add_argument('--dist-url', default='env://', type=str, 89 | help='url used to set up distributed training') 90 | parser.add_argument('--dist-backend', default='nccl', type=str, 91 | help='distributed backend') 92 | parser.add_argument('--seed', default=None, type=int, 93 | help='seed for initializing training. ') 94 | parser.add_argument('--gpu', default=None, type=int, 95 | help='GPU id to use.') 96 | parser.add_argument('--multiprocessing-distributed', action='store_true', 97 | help='Use multi-processing distributed training to launch ' 98 | 'N processes per node, which has N GPUs. This is the ' 99 | 'fastest way to use PyTorch for either single node or ' 100 | 'multi node data parallel training') 101 | 102 | # moco specific configs: 103 | parser.add_argument('--moco-dim', default=256, type=int, 104 | help='feature dimension (default: 256)') 105 | parser.add_argument('--moco-mlp-dim', default=4096, type=int, 106 | help='hidden dimension in MLPs (default: 4096)') 107 | parser.add_argument('--moco-m', default=0.99, type=float, 108 | help='moco momentum of updating momentum encoder (default: 0.99)') 109 | parser.add_argument('--moco-m-cos', action='store_true', 110 | help='gradually increase moco momentum to 1 with a ' 111 | 'half-cycle cosine schedule') 112 | parser.add_argument('--moco-t', default=1.0, type=float, 113 | help='softmax temperature (default: 1.0)') 114 | parser.add_argument('--bridge-t', default=1.0, type=float, 115 | help='bridging coefficient weighting MoCo and SimSiam (default: 1.0)') 116 | 117 | # vit specific configs: 118 | parser.add_argument('--stop-grad-conv1', action='store_true', 119 | help='stop-grad after first conv, or patch embedding') 120 | 121 | # other upgrades 122 | parser.add_argument('--optimizer', default='lars', type=str, 123 | choices=['lars', 'adamw'], 124 | help='optimizer used (default: lars)') 125 | parser.add_argument('--warmup-epochs', default=10, type=int, metavar='N', 126 | help='number of warmup epochs') 127 | parser.add_argument('--crop-min', default=0.08, type=float, 128 | help='minimum scale for random cropping (default: 0.08)') 129 | 130 | def main(): 131 | args = parser.parse_args() 132 | if not os.path.exists(args.ckp): 133 | os.makedirs(args.ckp) 134 | 135 | if args.seed is not None: 136 | random.seed(args.seed) 137 | torch.manual_seed(args.seed) 138 | cudnn.deterministic = True 139 | warnings.warn('You have chosen to seed training. ' 140 | 'This will turn on the CUDNN deterministic setting, ' 141 | 'which can slow down your training considerably! ' 142 | 'You may see unexpected behavior when restarting ' 143 | 'from checkpoints.') 144 | 145 | if args.gpu is not None: 146 | warnings.warn('You have chosen a specific GPU. This will completely ' 147 | 'disable data parallelism.') 148 | 149 | if args.dist_url == "env://" and args.world_size == -1: 150 | args.world_size = int(os.environ["WORLD_SIZE"]) 151 | 152 | args.distributed = args.world_size > 1 or args.multiprocessing_distributed 153 | 154 | ngpus_per_node = torch.cuda.device_count() 155 | if args.multiprocessing_distributed: 156 | # Since we have ngpus_per_node processes per node, the total world_size 157 | # needs to be adjusted accordingly 158 | args.world_size = ngpus_per_node * args.world_size 159 | # Use torch.multiprocessing.spawn to launch distributed processes: the 160 | # main_worker process function 161 | mp.spawn(main_worker, nprocs=ngpus_per_node, args=(ngpus_per_node, args)) 162 | else: 163 | # Simply call main_worker function 164 | main_worker(args.gpu, ngpus_per_node, args) 165 | 166 | 167 | def main_worker(gpu, ngpus_per_node, args): 168 | args.gpu = gpu 169 | 170 | # suppress printing if not first GPU on each node 171 | if args.multiprocessing_distributed and (args.gpu != 0 or args.rank != 0): 172 | def print_pass(*args): 173 | pass 174 | builtins.print = print_pass 175 | 176 | if args.gpu is not None: 177 | print("Use GPU: {} for training".format(args.gpu)) 178 | 179 | if args.distributed: 180 | if args.dist_url == "env://" and args.rank == -1: 181 | args.rank = int(os.environ["RANK"]) 182 | if args.multiprocessing_distributed: 183 | # For multiprocessing distributed training, rank needs to be the 184 | # global rank among all the processes 185 | args.rank = args.rank * ngpus_per_node + gpu 186 | dist.init_process_group(backend=args.dist_backend, init_method=args.dist_url, 187 | world_size=args.world_size, rank=args.rank) 188 | torch.distributed.barrier() 189 | # create model 190 | print("=> creating model '{}'".format(args.arch)) 191 | if args.arch.startswith('vit'): 192 | model = moco.builder.PatchPositioning( 193 | partial(vits.__dict__[args.arch], pretext_token=True, stop_grad_conv1=args.stop_grad_conv1, global_pool='avg'), 194 | args.moco_dim, args.moco_mlp_dim, args.moco_t, args.bridge_t) 195 | else: 196 | raise NotImplementedError('Only support ViT ...') 197 | 198 | # infer learning rate before changing batch size 199 | args.lr = args.lr * args.batch_size / 256 200 | 201 | if not torch.cuda.is_available(): 202 | print('using CPU, this will be slow') 203 | elif args.distributed: 204 | # apply SyncBN 205 | model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model) 206 | # For multiprocessing distributed, DistributedDataParallel constructor 207 | # should always set the single device scope, otherwise, 208 | # DistributedDataParallel will use all available devices. 209 | if args.gpu is not None: 210 | torch.cuda.set_device(args.gpu) 211 | model.cuda(args.gpu) 212 | # When using a single GPU per process and per 213 | # DistributedDataParallel, we need to divide the batch size 214 | # ourselves based on the total number of GPUs we have 215 | args.batch_size = int(args.batch_size / args.world_size) 216 | args.workers = int((args.workers + ngpus_per_node - 1) / ngpus_per_node) 217 | model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu]) 218 | else: 219 | model.cuda() 220 | # DistributedDataParallel will divide and allocate batch_size to all 221 | # available GPUs if device_ids are not set 222 | model = torch.nn.parallel.DistributedDataParallel(model) 223 | elif args.gpu is not None: 224 | torch.cuda.set_device(args.gpu) 225 | model = model.cuda(args.gpu) 226 | # comment out the following line for debugging 227 | raise NotImplementedError("Only DistributedDataParallel is supported.") 228 | else: 229 | # AllGather/rank implementation in this code only supports DistributedDataParallel. 230 | raise NotImplementedError("Only DistributedDataParallel is supported.") 231 | print(model) # print model after SyncBatchNorm 232 | 233 | if args.optimizer == 'lars': 234 | optimizer = moco.optimizer.LARS(model.parameters(), args.lr, 235 | weight_decay=args.weight_decay, 236 | momentum=args.momentum) 237 | elif args.optimizer == 'adamw': 238 | optimizer = torch.optim.AdamW(model.parameters(), args.lr, 239 | weight_decay=args.weight_decay) 240 | 241 | scaler = torch.cuda.amp.GradScaler() 242 | summary_writer = SummaryWriter() if args.rank == 0 else None 243 | 244 | # optionally continue from a checkpoint in first phase 245 | if args.firstphase: 246 | if os.path.isfile(args.firstphase): 247 | print("=> loading checkpoint '{}' in first stage".format(args.firstphase)) 248 | if args.gpu is None: 249 | checkpoint = torch.load(args.firstphase) 250 | else: 251 | # Map model to be loaded to specified single gpu. 252 | loc = 'cuda:{}'.format(args.gpu) 253 | checkpoint = torch.load(args.firstphase, map_location=loc) 254 | model.load_state_dict(checkpoint['state_dict'], strict=False) 255 | print("=> loaded checkpoint '{}' in first stage" 256 | .format(args.firstphase)) 257 | else: 258 | print("=> no checkpoint found at '{}'".format(args.firstphase)) 259 | # or resume from a checkpoint 260 | elif args.resume: 261 | if os.path.isfile(args.resume): 262 | print("=> loading checkpoint '{}'".format(args.resume)) 263 | if args.gpu is None: 264 | checkpoint = torch.load(args.resume) 265 | else: 266 | # Map model to be loaded to specified single gpu. 267 | loc = 'cuda:{}'.format(args.gpu) 268 | checkpoint = torch.load(args.resume, map_location=loc) 269 | args.start_epoch = checkpoint['epoch'] 270 | model.load_state_dict(checkpoint['state_dict']) 271 | optimizer.load_state_dict(checkpoint['optimizer']) 272 | scaler.load_state_dict(checkpoint['scaler']) 273 | print("=> loaded checkpoint '{}' (epoch {})" 274 | .format(args.resume, checkpoint['epoch'])) 275 | else: 276 | print("=> no checkpoint found at '{}'".format(args.resume)) 277 | 278 | cudnn.benchmark = True 279 | 280 | # Data loading code 281 | # traindir = os.path.join(args.data, 'train') 282 | traindir = args.data 283 | used_tcga_file = args.tcga 284 | df_tcga = pd.read_csv(used_tcga_file) 285 | used_TCGA = df_tcga[df_tcga['used']==1]['dataset'].tolist() 286 | # normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], 287 | # std=[0.229, 0.224, 0.225]) 288 | 289 | # follow BYOL's augmentation recipe: https://arxiv.org/abs/2006.07733 290 | augmentation1 = [ 291 | transforms.RandomResizedCrop(224, scale=(args.crop_min, 1.)), 292 | transforms.RandomApply([ 293 | transforms.ColorJitter(0.4, 0.4, 0.2, 0.1) # not strengthened 294 | ], p=0.8), 295 | transforms.RandomGrayscale(p=0.2), 296 | transforms.RandomApply([moco.loader.GaussianBlur([.1, 2.])], p=1.0), 297 | transforms.RandomHorizontalFlip(), 298 | transforms.ToTensor() 299 | ] 300 | 301 | augmentation2 = [ 302 | transforms.RandomResizedCrop(224, scale=(args.crop_min, 1.)), 303 | transforms.RandomApply([ 304 | transforms.ColorJitter(0.4, 0.4, 0.2, 0.1) # not strengthened 305 | ], p=0.8), 306 | transforms.RandomGrayscale(p=0.2), 307 | transforms.RandomApply([moco.loader.GaussianBlur([.1, 2.])], p=0.1), 308 | transforms.RandomApply([moco.loader.Solarize()], p=0.2), 309 | transforms.RandomHorizontalFlip(), 310 | transforms.ToTensor() 311 | ] 312 | 313 | augmentation_r = [ 314 | transforms.Resize(224), 315 | transforms.RandomApply([ 316 | transforms.ColorJitter(0.4, 0.4, 0.2, 0.1) # not strengthened 317 | ], p=0.8), 318 | transforms.RandomGrayscale(p=0.2), 319 | transforms.RandomApply([moco.loader.GaussianBlur([.1, 2.])], p=0.1), 320 | transforms.RandomHorizontalFlip(), 321 | transforms.ToTensor() 322 | ] 323 | 324 | train_dataset = moco.loader.BridgeDataset(data_dir=traindir, 325 | used_TCGA=used_TCGA, 326 | patch_transform=moco.loader.TwoCropsTransform(transforms.Compose(augmentation1), 327 | transforms.Compose(augmentation2)), 328 | region_transform=transforms.Compose(augmentation_r)) 329 | 330 | if args.distributed: 331 | train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset) 332 | else: 333 | train_sampler = None 334 | 335 | train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=args.batch_size, shuffle=(train_sampler is None), 336 | num_workers=args.workers, pin_memory=True, sampler=train_sampler, drop_last=True) 337 | 338 | for epoch in range(args.start_epoch, args.epochs): 339 | if args.distributed: 340 | train_sampler.set_epoch(epoch) 341 | 342 | # train for one epoch 343 | train(train_loader, model, optimizer, scaler, summary_writer, epoch, args) 344 | 345 | if not args.multiprocessing_distributed or (args.multiprocessing_distributed 346 | and args.rank == 0): # only the first GPU saves checkpoint 347 | save_checkpoint({ 348 | 'epoch': epoch + 1, 349 | 'arch': args.arch, 350 | 'state_dict': model.state_dict(), 351 | 'optimizer' : optimizer.state_dict(), 352 | 'scaler': scaler.state_dict(), 353 | }, is_best=False, filename=os.path.join(args.ckp, 'checkpoint_%04d.pth.tar' % epoch)) 354 | 355 | if args.rank == 0: 356 | summary_writer.close() 357 | 358 | def train(train_loader, model, optimizer, scaler, summary_writer, epoch, args): 359 | batch_time = AverageMeter('Time', ':6.3f') 360 | data_time = AverageMeter('Data', ':6.3f') 361 | learning_rates = AverageMeter('LR', ':.4e') 362 | losses = AverageMeter('Loss', ':.4e') 363 | progress = ProgressMeter( 364 | len(train_loader), 365 | [batch_time, data_time, learning_rates, losses], 366 | prefix="Epoch: [{}]".format(epoch)) 367 | 368 | # switch to train mode 369 | model.train() 370 | 371 | end = time.time() 372 | iters_per_epoch = len(train_loader) 373 | moco_m = args.moco_m 374 | for i, (patch1, patch2, ref, region) in enumerate(train_loader): 375 | # measure data loading time 376 | data_time.update(time.time() - end) 377 | 378 | # adjust learning rate and momentum coefficient per iteration 379 | lr = adjust_learning_rate(optimizer, epoch + i / iters_per_epoch, args) 380 | learning_rates.update(lr) 381 | if args.moco_m_cos: 382 | moco_m = adjust_moco_momentum(epoch + i / iters_per_epoch, args) 383 | 384 | if args.gpu is not None: 385 | patch1 = patch1.cuda(args.gpu, non_blocking=True) 386 | patch2 = patch2.cuda(args.gpu, non_blocking=True) 387 | ref = ref.cuda(args.gpu, non_blocking=True) 388 | region = region.cuda(args.gpu, non_blocking=True) 389 | 390 | # compute output 391 | with torch.cuda.amp.autocast(True): 392 | loss = model(patch1, patch2, ref, region, moco_m) 393 | 394 | losses.update(loss.item(), patch1.size(0)) 395 | if args.rank == 0: 396 | summary_writer.add_scalar("loss", loss.item(), epoch * iters_per_epoch + i) 397 | 398 | # compute gradient and do SGD step 399 | optimizer.zero_grad() 400 | scaler.scale(loss).backward() 401 | scaler.step(optimizer) 402 | scaler.update() 403 | 404 | # measure elapsed time 405 | batch_time.update(time.time() - end) 406 | end = time.time() 407 | 408 | if i % args.print_freq == 0: 409 | progress.display(i) 410 | 411 | 412 | def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'): 413 | torch.save(state, filename) 414 | if is_best: 415 | shutil.copyfile(filename, 'model_best.pth.tar') 416 | 417 | 418 | class AverageMeter(object): 419 | """Computes and stores the average and current value""" 420 | def __init__(self, name, fmt=':f'): 421 | self.name = name 422 | self.fmt = fmt 423 | self.reset() 424 | 425 | def reset(self): 426 | self.val = 0 427 | self.avg = 0 428 | self.sum = 0 429 | self.count = 0 430 | 431 | def update(self, val, n=1): 432 | self.val = val 433 | self.sum += val * n 434 | self.count += n 435 | self.avg = self.sum / self.count 436 | 437 | def __str__(self): 438 | fmtstr = '{name} {val' + self.fmt + '} ({avg' + self.fmt + '})' 439 | return fmtstr.format(**self.__dict__) 440 | 441 | 442 | class ProgressMeter(object): 443 | def __init__(self, num_batches, meters, prefix=""): 444 | self.batch_fmtstr = self._get_batch_fmtstr(num_batches) 445 | self.meters = meters 446 | self.prefix = prefix 447 | 448 | def display(self, batch): 449 | entries = [self.prefix + self.batch_fmtstr.format(batch)] 450 | entries += [str(meter) for meter in self.meters] 451 | print('\t'.join(entries)) 452 | 453 | def _get_batch_fmtstr(self, num_batches): 454 | num_digits = len(str(num_batches // 1)) 455 | fmt = '{:' + str(num_digits) + 'd}' 456 | return '[' + fmt + '/' + fmt.format(num_batches) + ']' 457 | 458 | 459 | def adjust_learning_rate(optimizer, epoch, args): 460 | """Decays the learning rate with half-cycle cosine after warmup""" 461 | if epoch < args.warmup_epochs: 462 | lr = args.lr * epoch / args.warmup_epochs 463 | else: 464 | lr = args.lr * 0.5 * (1. + math.cos(math.pi * (epoch - args.warmup_epochs) / (args.epochs - args.warmup_epochs))) 465 | for param_group in optimizer.param_groups: 466 | param_group['lr'] = lr 467 | return lr 468 | 469 | 470 | def adjust_moco_momentum(epoch, args): 471 | """Adjust moco momentum based on current epoch""" 472 | m = 1. - 0.5 * (1. + math.cos(math.pi * epoch / args.epochs)) * (1. - args.moco_m) 473 | return m 474 | 475 | 476 | if __name__ == '__main__': 477 | main() 478 | -------------------------------------------------------------------------------- /main_lincls.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # Copyright (c) Facebook, Inc. and its affiliates. 4 | # All rights reserved. 5 | 6 | # This source code is licensed under the license found in the 7 | # LICENSE file in the root directory of this source tree. 8 | 9 | import argparse 10 | import builtins 11 | import math 12 | import os 13 | import random 14 | import shutil 15 | import time 16 | import warnings 17 | 18 | import torch 19 | import torch.nn as nn 20 | import torch.nn.parallel 21 | import torch.backends.cudnn as cudnn 22 | import torch.distributed as dist 23 | import torch.optim 24 | import torch.multiprocessing as mp 25 | import torch.utils.data 26 | import torch.utils.data.distributed 27 | import torchvision.transforms as transforms 28 | import torchvision.datasets as datasets 29 | import torchvision.models as torchvision_models 30 | 31 | import vits 32 | 33 | torchvision_model_names = sorted(name for name in torchvision_models.__dict__ 34 | if name.islower() and not name.startswith("__") 35 | and callable(torchvision_models.__dict__[name])) 36 | 37 | model_names = ['vit_small', 'vit_base', 'vit_conv_small', 'vit_conv_base'] + torchvision_model_names 38 | 39 | parser = argparse.ArgumentParser(description='PyTorch ImageNet Training') 40 | parser.add_argument('data', metavar='DIR', 41 | help='path to dataset') 42 | parser.add_argument('-a', '--arch', metavar='ARCH', default='resnet50', 43 | choices=model_names, 44 | help='model architecture: ' + 45 | ' | '.join(model_names) + 46 | ' (default: resnet50)') 47 | parser.add_argument('-j', '--workers', default=32, type=int, metavar='N', 48 | help='number of data loading workers (default: 32)') 49 | parser.add_argument('--epochs', default=90, type=int, metavar='N', 50 | help='number of total epochs to run') 51 | parser.add_argument('--start-epoch', default=0, type=int, metavar='N', 52 | help='manual epoch number (useful on restarts)') 53 | parser.add_argument('-b', '--batch-size', default=1024, type=int, 54 | metavar='N', 55 | help='mini-batch size (default: 1024), this is the total ' 56 | 'batch size of all GPUs on all nodes when ' 57 | 'using Data Parallel or Distributed Data Parallel') 58 | parser.add_argument('--lr', '--learning-rate', default=0.1, type=float, 59 | metavar='LR', help='initial (base) learning rate', dest='lr') 60 | parser.add_argument('--momentum', default=0.9, type=float, metavar='M', 61 | help='momentum') 62 | parser.add_argument('--wd', '--weight-decay', default=0., type=float, 63 | metavar='W', help='weight decay (default: 0.)', 64 | dest='weight_decay') 65 | parser.add_argument('-p', '--print-freq', default=10, type=int, 66 | metavar='N', help='print frequency (default: 10)') 67 | parser.add_argument('--resume', default='', type=str, metavar='PATH', 68 | help='path to latest checkpoint (default: none)') 69 | parser.add_argument('-e', '--evaluate', dest='evaluate', action='store_true', 70 | help='evaluate model on validation set') 71 | parser.add_argument('--world-size', default=-1, type=int, 72 | help='number of nodes for distributed training') 73 | parser.add_argument('--rank', default=-1, type=int, 74 | help='node rank for distributed training') 75 | parser.add_argument('--dist-url', default='tcp://224.66.41.62:23456', type=str, 76 | help='url used to set up distributed training') 77 | parser.add_argument('--dist-backend', default='nccl', type=str, 78 | help='distributed backend') 79 | parser.add_argument('--seed', default=None, type=int, 80 | help='seed for initializing training. ') 81 | parser.add_argument('--gpu', default=None, type=int, 82 | help='GPU id to use.') 83 | parser.add_argument('--multiprocessing-distributed', action='store_true', 84 | help='Use multi-processing distributed training to launch ' 85 | 'N processes per node, which has N GPUs. This is the ' 86 | 'fastest way to use PyTorch for either single node or ' 87 | 'multi node data parallel training') 88 | 89 | # additional configs: 90 | parser.add_argument('--pretrained', default='', type=str, 91 | help='path to moco pretrained checkpoint') 92 | 93 | best_acc1 = 0 94 | 95 | 96 | def main(): 97 | args = parser.parse_args() 98 | 99 | if args.seed is not None: 100 | random.seed(args.seed) 101 | torch.manual_seed(args.seed) 102 | cudnn.deterministic = True 103 | warnings.warn('You have chosen to seed training. ' 104 | 'This will turn on the CUDNN deterministic setting, ' 105 | 'which can slow down your training considerably! ' 106 | 'You may see unexpected behavior when restarting ' 107 | 'from checkpoints.') 108 | 109 | if args.gpu is not None: 110 | warnings.warn('You have chosen a specific GPU. This will completely ' 111 | 'disable data parallelism.') 112 | 113 | if args.dist_url == "env://" and args.world_size == -1: 114 | args.world_size = int(os.environ["WORLD_SIZE"]) 115 | 116 | args.distributed = args.world_size > 1 or args.multiprocessing_distributed 117 | 118 | ngpus_per_node = torch.cuda.device_count() 119 | if args.multiprocessing_distributed: 120 | # Since we have ngpus_per_node processes per node, the total world_size 121 | # needs to be adjusted accordingly 122 | args.world_size = ngpus_per_node * args.world_size 123 | # Use torch.multiprocessing.spawn to launch distributed processes: the 124 | # main_worker process function 125 | mp.spawn(main_worker, nprocs=ngpus_per_node, args=(ngpus_per_node, args)) 126 | else: 127 | # Simply call main_worker function 128 | main_worker(args.gpu, ngpus_per_node, args) 129 | 130 | 131 | def main_worker(gpu, ngpus_per_node, args): 132 | global best_acc1 133 | args.gpu = gpu 134 | 135 | # suppress printing if not master 136 | if args.multiprocessing_distributed and args.gpu != 0: 137 | def print_pass(*args): 138 | pass 139 | builtins.print = print_pass 140 | 141 | if args.gpu is not None: 142 | print("Use GPU: {} for training".format(args.gpu)) 143 | 144 | if args.distributed: 145 | if args.dist_url == "env://" and args.rank == -1: 146 | args.rank = int(os.environ["RANK"]) 147 | if args.multiprocessing_distributed: 148 | # For multiprocessing distributed training, rank needs to be the 149 | # global rank among all the processes 150 | args.rank = args.rank * ngpus_per_node + gpu 151 | dist.init_process_group(backend=args.dist_backend, init_method=args.dist_url, 152 | world_size=args.world_size, rank=args.rank) 153 | torch.distributed.barrier() 154 | # create model 155 | print("=> creating model '{}'".format(args.arch)) 156 | if args.arch.startswith('vit'): 157 | model = vits.__dict__[args.arch]() 158 | linear_keyword = 'head' 159 | else: 160 | model = torchvision_models.__dict__[args.arch]() 161 | linear_keyword = 'fc' 162 | 163 | # freeze all layers but the last fc 164 | for name, param in model.named_parameters(): 165 | if name not in ['%s.weight' % linear_keyword, '%s.bias' % linear_keyword]: 166 | param.requires_grad = False 167 | # init the fc layer 168 | getattr(model, linear_keyword).weight.data.normal_(mean=0.0, std=0.01) 169 | getattr(model, linear_keyword).bias.data.zero_() 170 | 171 | # load from pre-trained, before DistributedDataParallel constructor 172 | if args.pretrained: 173 | if os.path.isfile(args.pretrained): 174 | print("=> loading checkpoint '{}'".format(args.pretrained)) 175 | checkpoint = torch.load(args.pretrained, map_location="cpu") 176 | 177 | # rename moco pre-trained keys 178 | state_dict = checkpoint['state_dict'] 179 | for k in list(state_dict.keys()): 180 | # retain only base_encoder up to before the embedding layer 181 | if k.startswith('module.base_encoder') and not k.startswith('module.base_encoder.%s' % linear_keyword): 182 | # remove prefix 183 | state_dict[k[len("module.base_encoder."):]] = state_dict[k] 184 | # delete renamed or unused k 185 | del state_dict[k] 186 | 187 | args.start_epoch = 0 188 | msg = model.load_state_dict(state_dict, strict=False) 189 | assert set(msg.missing_keys) == {"%s.weight" % linear_keyword, "%s.bias" % linear_keyword} 190 | 191 | print("=> loaded pre-trained model '{}'".format(args.pretrained)) 192 | else: 193 | print("=> no checkpoint found at '{}'".format(args.pretrained)) 194 | 195 | # infer learning rate before changing batch size 196 | init_lr = args.lr * args.batch_size / 256 197 | 198 | if not torch.cuda.is_available(): 199 | print('using CPU, this will be slow') 200 | elif args.distributed: 201 | # For multiprocessing distributed, DistributedDataParallel constructor 202 | # should always set the single device scope, otherwise, 203 | # DistributedDataParallel will use all available devices. 204 | if args.gpu is not None: 205 | torch.cuda.set_device(args.gpu) 206 | model.cuda(args.gpu) 207 | # When using a single GPU per process and per 208 | # DistributedDataParallel, we need to divide the batch size 209 | # ourselves based on the total number of GPUs we have 210 | args.batch_size = int(args.batch_size / args.world_size) 211 | args.workers = int((args.workers + ngpus_per_node - 1) / ngpus_per_node) 212 | model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu]) 213 | else: 214 | model.cuda() 215 | # DistributedDataParallel will divide and allocate batch_size to all 216 | # available GPUs if device_ids are not set 217 | model = torch.nn.parallel.DistributedDataParallel(model) 218 | elif args.gpu is not None: 219 | torch.cuda.set_device(args.gpu) 220 | model = model.cuda(args.gpu) 221 | else: 222 | # DataParallel will divide and allocate batch_size to all available GPUs 223 | if args.arch.startswith('alexnet') or args.arch.startswith('vgg'): 224 | model.features = torch.nn.DataParallel(model.features) 225 | model.cuda() 226 | else: 227 | model = torch.nn.DataParallel(model).cuda() 228 | 229 | # define loss function (criterion) and optimizer 230 | criterion = nn.CrossEntropyLoss().cuda(args.gpu) 231 | 232 | # optimize only the linear classifier 233 | parameters = list(filter(lambda p: p.requires_grad, model.parameters())) 234 | assert len(parameters) == 2 # weight, bias 235 | 236 | optimizer = torch.optim.SGD(parameters, init_lr, 237 | momentum=args.momentum, 238 | weight_decay=args.weight_decay) 239 | 240 | # optionally resume from a checkpoint 241 | if args.resume: 242 | if os.path.isfile(args.resume): 243 | print("=> loading checkpoint '{}'".format(args.resume)) 244 | if args.gpu is None: 245 | checkpoint = torch.load(args.resume) 246 | else: 247 | # Map model to be loaded to specified single gpu. 248 | loc = 'cuda:{}'.format(args.gpu) 249 | checkpoint = torch.load(args.resume, map_location=loc) 250 | args.start_epoch = checkpoint['epoch'] 251 | best_acc1 = checkpoint['best_acc1'] 252 | if args.gpu is not None: 253 | # best_acc1 may be from a checkpoint from a different GPU 254 | best_acc1 = best_acc1.to(args.gpu) 255 | model.load_state_dict(checkpoint['state_dict']) 256 | optimizer.load_state_dict(checkpoint['optimizer']) 257 | print("=> loaded checkpoint '{}' (epoch {})" 258 | .format(args.resume, checkpoint['epoch'])) 259 | else: 260 | print("=> no checkpoint found at '{}'".format(args.resume)) 261 | 262 | cudnn.benchmark = True 263 | 264 | # Data loading code 265 | traindir = os.path.join(args.data, 'train') 266 | valdir = os.path.join(args.data, 'val') 267 | # if using our model, please comment the normalize function 268 | # normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], 269 | # std=[0.229, 0.224, 0.225]) 270 | 271 | train_dataset = datasets.ImageFolder( 272 | traindir, 273 | transforms.Compose([ 274 | transforms.RandomResizedCrop(224), 275 | transforms.RandomHorizontalFlip(), 276 | transforms.ToTensor(), 277 | # normalize, 278 | ])) 279 | 280 | if args.distributed: 281 | train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset) 282 | else: 283 | train_sampler = None 284 | 285 | train_loader = torch.utils.data.DataLoader( 286 | train_dataset, batch_size=args.batch_size, shuffle=(train_sampler is None), 287 | num_workers=args.workers, pin_memory=True, sampler=train_sampler) 288 | 289 | val_loader = torch.utils.data.DataLoader( 290 | datasets.ImageFolder(valdir, transforms.Compose([ 291 | transforms.Resize(256), 292 | transforms.CenterCrop(224), 293 | transforms.ToTensor(), 294 | normalize, 295 | ])), 296 | batch_size=256, shuffle=False, 297 | num_workers=args.workers, pin_memory=True) 298 | 299 | if args.evaluate: 300 | validate(val_loader, model, criterion, args) 301 | return 302 | 303 | for epoch in range(args.start_epoch, args.epochs): 304 | if args.distributed: 305 | train_sampler.set_epoch(epoch) 306 | adjust_learning_rate(optimizer, init_lr, epoch, args) 307 | 308 | # train for one epoch 309 | train(train_loader, model, criterion, optimizer, epoch, args) 310 | 311 | # evaluate on validation set 312 | acc1 = validate(val_loader, model, criterion, args) 313 | 314 | # remember best acc@1 and save checkpoint 315 | is_best = acc1 > best_acc1 316 | best_acc1 = max(acc1, best_acc1) 317 | 318 | if not args.multiprocessing_distributed or (args.multiprocessing_distributed 319 | and args.rank == 0): # only the first GPU saves checkpoint 320 | save_checkpoint({ 321 | 'epoch': epoch + 1, 322 | 'arch': args.arch, 323 | 'state_dict': model.state_dict(), 324 | 'best_acc1': best_acc1, 325 | 'optimizer' : optimizer.state_dict(), 326 | }, is_best) 327 | if epoch == args.start_epoch: 328 | sanity_check(model.state_dict(), args.pretrained, linear_keyword) 329 | 330 | 331 | def train(train_loader, model, criterion, optimizer, epoch, args): 332 | batch_time = AverageMeter('Time', ':6.3f') 333 | data_time = AverageMeter('Data', ':6.3f') 334 | losses = AverageMeter('Loss', ':.4e') 335 | top1 = AverageMeter('Acc@1', ':6.2f') 336 | top5 = AverageMeter('Acc@5', ':6.2f') 337 | progress = ProgressMeter( 338 | len(train_loader), 339 | [batch_time, data_time, losses, top1, top5], 340 | prefix="Epoch: [{}]".format(epoch)) 341 | 342 | """ 343 | Switch to eval mode: 344 | Under the protocol of linear classification on frozen features/models, 345 | it is not legitimate to change any part of the pre-trained model. 346 | BatchNorm in train mode may revise running mean/std (even if it receives 347 | no gradient), which are part of the model parameters too. 348 | """ 349 | model.eval() 350 | 351 | end = time.time() 352 | for i, (images, target) in enumerate(train_loader): 353 | # measure data loading time 354 | data_time.update(time.time() - end) 355 | 356 | if args.gpu is not None: 357 | images = images.cuda(args.gpu, non_blocking=True) 358 | if torch.cuda.is_available(): 359 | target = target.cuda(args.gpu, non_blocking=True) 360 | 361 | # compute output 362 | output = model(images) 363 | loss = criterion(output, target) 364 | 365 | # measure accuracy and record loss 366 | acc1, acc5 = accuracy(output, target, topk=(1, 5)) 367 | losses.update(loss.item(), images.size(0)) 368 | top1.update(acc1[0], images.size(0)) 369 | top5.update(acc5[0], images.size(0)) 370 | 371 | # compute gradient and do SGD step 372 | optimizer.zero_grad() 373 | loss.backward() 374 | optimizer.step() 375 | 376 | # measure elapsed time 377 | batch_time.update(time.time() - end) 378 | end = time.time() 379 | 380 | if i % args.print_freq == 0: 381 | progress.display(i) 382 | 383 | 384 | def validate(val_loader, model, criterion, args): 385 | batch_time = AverageMeter('Time', ':6.3f') 386 | losses = AverageMeter('Loss', ':.4e') 387 | top1 = AverageMeter('Acc@1', ':6.2f') 388 | top5 = AverageMeter('Acc@5', ':6.2f') 389 | progress = ProgressMeter( 390 | len(val_loader), 391 | [batch_time, losses, top1, top5], 392 | prefix='Test: ') 393 | 394 | # switch to evaluate mode 395 | model.eval() 396 | 397 | with torch.no_grad(): 398 | end = time.time() 399 | for i, (images, target) in enumerate(val_loader): 400 | if args.gpu is not None: 401 | images = images.cuda(args.gpu, non_blocking=True) 402 | if torch.cuda.is_available(): 403 | target = target.cuda(args.gpu, non_blocking=True) 404 | 405 | # compute output 406 | output = model(images) 407 | loss = criterion(output, target) 408 | 409 | # measure accuracy and record loss 410 | acc1, acc5 = accuracy(output, target, topk=(1, 5)) 411 | losses.update(loss.item(), images.size(0)) 412 | top1.update(acc1[0], images.size(0)) 413 | top5.update(acc5[0], images.size(0)) 414 | 415 | # measure elapsed time 416 | batch_time.update(time.time() - end) 417 | end = time.time() 418 | 419 | if i % args.print_freq == 0: 420 | progress.display(i) 421 | 422 | # TODO: this should also be done with the ProgressMeter 423 | print(' * Acc@1 {top1.avg:.3f} Acc@5 {top5.avg:.3f}' 424 | .format(top1=top1, top5=top5)) 425 | 426 | return top1.avg 427 | 428 | 429 | def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'): 430 | torch.save(state, filename) 431 | if is_best: 432 | shutil.copyfile(filename, 'model_best.pth.tar') 433 | 434 | 435 | def sanity_check(state_dict, pretrained_weights, linear_keyword): 436 | """ 437 | Linear classifier should not change any weights other than the linear layer. 438 | This sanity check asserts nothing wrong happens (e.g., BN stats updated). 439 | """ 440 | print("=> loading '{}' for sanity check".format(pretrained_weights)) 441 | checkpoint = torch.load(pretrained_weights, map_location="cpu") 442 | state_dict_pre = checkpoint['state_dict'] 443 | 444 | for k in list(state_dict.keys()): 445 | # only ignore linear layer 446 | if '%s.weight' % linear_keyword in k or '%s.bias' % linear_keyword in k: 447 | continue 448 | 449 | # name in pretrained model 450 | k_pre = 'module.base_encoder.' + k[len('module.'):] \ 451 | if k.startswith('module.') else 'module.base_encoder.' + k 452 | 453 | assert ((state_dict[k].cpu() == state_dict_pre[k_pre]).all()), \ 454 | '{} is changed in linear classifier training.'.format(k) 455 | 456 | print("=> sanity check passed.") 457 | 458 | 459 | class AverageMeter(object): 460 | """Computes and stores the average and current value""" 461 | def __init__(self, name, fmt=':f'): 462 | self.name = name 463 | self.fmt = fmt 464 | self.reset() 465 | 466 | def reset(self): 467 | self.val = 0 468 | self.avg = 0 469 | self.sum = 0 470 | self.count = 0 471 | 472 | def update(self, val, n=1): 473 | self.val = val 474 | self.sum += val * n 475 | self.count += n 476 | self.avg = self.sum / self.count 477 | 478 | def __str__(self): 479 | fmtstr = '{name} {val' + self.fmt + '} ({avg' + self.fmt + '})' 480 | return fmtstr.format(**self.__dict__) 481 | 482 | 483 | class ProgressMeter(object): 484 | def __init__(self, num_batches, meters, prefix=""): 485 | self.batch_fmtstr = self._get_batch_fmtstr(num_batches) 486 | self.meters = meters 487 | self.prefix = prefix 488 | 489 | def display(self, batch): 490 | entries = [self.prefix + self.batch_fmtstr.format(batch)] 491 | entries += [str(meter) for meter in self.meters] 492 | print('\t'.join(entries)) 493 | 494 | def _get_batch_fmtstr(self, num_batches): 495 | num_digits = len(str(num_batches // 1)) 496 | fmt = '{:' + str(num_digits) + 'd}' 497 | return '[' + fmt + '/' + fmt.format(num_batches) + ']' 498 | 499 | 500 | def adjust_learning_rate(optimizer, init_lr, epoch, args): 501 | """Decay the learning rate based on schedule""" 502 | cur_lr = init_lr * 0.5 * (1. + math.cos(math.pi * epoch / args.epochs)) 503 | for param_group in optimizer.param_groups: 504 | param_group['lr'] = cur_lr 505 | 506 | 507 | def accuracy(output, target, topk=(1,)): 508 | """Computes the accuracy over the k top predictions for the specified values of k""" 509 | with torch.no_grad(): 510 | maxk = max(topk) 511 | batch_size = target.size(0) 512 | 513 | _, pred = output.topk(maxk, 1, True, True) 514 | pred = pred.t() 515 | correct = pred.eq(target.view(1, -1).expand_as(pred)) 516 | 517 | res = [] 518 | for k in topk: 519 | correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True) 520 | res.append(correct_k.mul_(100.0 / batch_size)) 521 | return res 522 | 523 | 524 | if __name__ == '__main__': 525 | main() 526 | --------------------------------------------------------------------------------