├── framework.png ├── .gitignore ├── models ├── __init__.py └── vision_transformer.py ├── scripts ├── hssl_vit-base_100ep.sh └── hssl_vit-base_150ep.sh ├── README.md ├── loader.py ├── LICENSE ├── utils.py └── main_hssl_pretrain.py /framework.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lzyhha/HSSL/HEAD/framework.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.zip 2 | __pycache__/ 3 | .* 4 | .*/ 5 | *.pth 6 | *.out 7 | pics/ 8 | !.github/ 9 | !.gitignore -------------------------------------------------------------------------------- /models/__init__.py: -------------------------------------------------------------------------------- 1 | from .vision_transformer import vit_tiny, vit_small, vit_base, vit_large 2 | 3 | __all__ = ['vit_tiny', 'vit_small', 'vit_base', 'vit_large'] 4 | -------------------------------------------------------------------------------- /scripts/hssl_vit-base_100ep.sh: -------------------------------------------------------------------------------- 1 | ARCH=vit_base 2 | DATA="the path to imagenet training set" 3 | OUTPUT_PATH="the path to save checkpoints" 4 | BATCH=32 5 | EPOCHS=100 6 | OUT_DIM=8192 7 | 8 | python -m torch.distributed.launch --nproc_per_node=8 main_hssl_pretrain.py --arch $ARCH \ 9 | --auxiliary_depth 3 \ 10 | --output_dir $OUTPUT_PATH \ 11 | --data_path $DATA \ 12 | --teacher_temp 0.07 \ 13 | --teacher_patch_temp 0.07 \ 14 | --warmup_teacher_temp 0.04 \ 15 | --warmup_teacher_patch_temp 0.04 \ 16 | --warmup_teacher_temp_epochs 50 \ 17 | --norm_last_layer true \ 18 | --warmup_epochs 10 \ 19 | --epochs $EPOCHS \ 20 | --lr 0.00075 \ 21 | --min_lr 2e-6 \ 22 | --weight_decay 0.04 \ 23 | --weight_decay_end 0.4 \ 24 | --shared_head true \ 25 | --shared_head_teacher true \ 26 | --out_dim $OUT_DIM \ 27 | --patch_out_dim $OUT_DIM \ 28 | --local_crops_number 10 \ 29 | --global_crops_scale 0.32 1 \ 30 | --local_crops_scale 0.05 0.32 \ 31 | --pred_ratio 0 0.3 \ 32 | --pred_ratio_var 0 0.2 \ 33 | --pred_shape block \ 34 | --batch_size_per_gpu $BATCH \ 35 | --num_workers 6 \ 36 | --saveckp_freq 10 \ 37 | --freeze_last_layer 3 \ 38 | --accum_iter 1 --clip_grad 0.3 \ 39 | --use_fp16 true -------------------------------------------------------------------------------- /scripts/hssl_vit-base_150ep.sh: -------------------------------------------------------------------------------- 1 | ARCH=vit_base 2 | DATA="the path to imagenet training set" 3 | OUTPUT_PATH="the path to save checkpoints" 4 | BATCH=32 5 | EPOCHS=150 6 | OUT_DIM=8192 7 | 8 | python -m torch.distributed.launch --nproc_per_node=8 main_hssl_pretrain.py --arch $ARCH \ 9 | --auxiliary_depth 3 \ 10 | --output_dir $OUTPUT_PATH \ 11 | --data_path $DATA \ 12 | --teacher_temp 0.07 \ 13 | --teacher_patch_temp 0.07 \ 14 | --warmup_teacher_temp 0.04 \ 15 | --warmup_teacher_patch_temp 0.04 \ 16 | --warmup_teacher_temp_epochs 50 \ 17 | --norm_last_layer true \ 18 | --warmup_epochs 10 \ 19 | --epochs $EPOCHS \ 20 | --lr 0.0005 \ 21 | --min_lr 2e-6 \ 22 | --weight_decay 0.04 \ 23 | --weight_decay_end 0.4 \ 24 | --shared_head true \ 25 | --shared_head_teacher true \ 26 | --out_dim $OUT_DIM \ 27 | --patch_out_dim $OUT_DIM \ 28 | --local_crops_number 10 \ 29 | --global_crops_scale 0.32 1 \ 30 | --local_crops_scale 0.05 0.32 \ 31 | --pred_ratio 0 0.3 \ 32 | --pred_ratio_var 0 0.2 \ 33 | --pred_shape block \ 34 | --batch_size_per_gpu $BATCH \ 35 | --num_workers 6 \ 36 | --saveckp_freq 10 \ 37 | --freeze_last_layer 3 \ 38 | --accum_iter 1 --clip_grad 0.3 \ 39 | --use_fp16 true -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Enhancing Representations through Heterogeneous Self-Supervised Learning ([TPAMI 2025](https://ieeexplore.ieee.org/document/10955443)) 2 | 3 | The official codebase for [Enhancing Representations through Heterogeneous Self-Supervised Learning](https://arxiv.org/abs/2310.05108). 4 | 5 | ## Introduction 6 | 7 |
8 | HSSL framework 9 |
10 | 11 | Incorporating heterogeneous representations from different architectures has facilitated various vision tasks, e.g., some hybrid networks combine transformers and convolutions. However, complementarity between such heterogeneous architectures has not been well exploited in self-supervised learning. Thus, we propose Heterogeneous Self-Supervised Learning (HSSL), which enforces a base model to learn from an auxiliary head whose architecture is heterogeneous from the base model. In this process, HSSL endows the base model with new characteristics in a representation learning way without structural changes. To comprehensively understand the HSSL, we conduct experiments on various heterogeneous pairs containing a base model and an auxiliary head. We discover that the representation quality of the base model moves up as their architecture discrepancy grows. This observation motivates us to propose a search strategy that quickly determines the most suitable auxiliary head for a specific base model to learn and several simple but effective methods to enlarge the model discrepancy. The HSSL is compatible with various self-supervised methods, achieving superior performances on various downstream tasks, including image classification, semantic segmentation, instance segmentation, and object detection. 12 | 13 | ## Installation 14 | Please install [PyTorch](https://pytorch.org/) and download the [ImageNet](https://imagenet.stanford.edu/) dataset. 15 | 16 | ## Training and Pre-trained Models 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 46 | 47 | 48 |
ArchitectureParametersPre-training EpochsFine-tuning EpochsTop-1downloadscript
ViT-B/1685M10010083.8%huggingface | 35 | baiduscript
ViT-B/1685M15010084.1%huggingface | 45 | baiduscript
49 | 50 | ## Evaluation 51 | 52 | We fully fine-tune the pre-trained models on ImageNet-1K 53 | by using the codebase of [MAE](https://github.com/facebookresearch/mae). 54 | 55 | For downstream tasks, 56 | e.g., semantic segmentation, 57 | please refer to [iBOT](https://github.com/bytedance/ibot). 58 | 59 | Addentionally, we also use [ImageNetSegModel](https://github.com/LUSSeg/ImageNetSegModel/tree/main) 60 | to implement semi-supevised semantic segmentation on [ImageNet-S dataset](https://github.com/LUSSeg/ImageNet-S). 61 | 62 | ## Citation 63 | If you find this repository useful, please consider giving a star and a citation: 64 | ``` 65 | @article{li2025hssl, 66 | title={Enhancing Representations through Heterogeneous Self-Supervised Learning}, 67 | author={Li, Zhong-Yu and Yin, Bo-Wen and Liu, Yongxiang and Liu, Li and Cheng, Ming-Ming}, 68 | journal=TPAMI, 69 | year={2025} 70 | } 71 | ``` 72 | 73 | 74 | ## License 75 | The code is released under the [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License](https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode) for Noncommercial use only. Any commercial use should get formal permission first. 76 | 77 | ## Acknowledgement 78 | 79 | This repository is built using the [DINO](https://github.com/facebookresearch/dino) repository, the [iBOT](https://github.com/bytedance/ibot) repository, 80 | and the [MAE](https://github.com/facebookresearch/mae) repository. 81 | -------------------------------------------------------------------------------- /loader.py: -------------------------------------------------------------------------------- 1 | # This source code is licensed under the license found in the 2 | # LICENSE file in the root directory of this source tree. 3 | # -------------------------------------------------------- 4 | # References: 5 | # iBOT: https://github.com/bytedance/ibot 6 | # -------------------------------------------------------- 7 | 8 | import random 9 | import math 10 | import numpy as np 11 | 12 | from torchvision.datasets import ImageFolder 13 | 14 | 15 | class ImageFolderInstance(ImageFolder): 16 | def __getitem__(self, index): 17 | img, target = super(ImageFolderInstance, self).__getitem__(index) 18 | return img, target, index 19 | 20 | 21 | class ImageFolderMask(ImageFolder): 22 | def __init__(self, *args, patch_size, pred_ratio, pred_ratio_var, pred_aspect_ratio, 23 | pred_shape='block', pred_start_epoch=0, **kwargs): 24 | super(ImageFolderMask, self).__init__(*args, **kwargs) 25 | self.psz = patch_size 26 | self.pred_ratio = pred_ratio[0] if isinstance(pred_ratio, list) and \ 27 | len(pred_ratio) == 1 else pred_ratio 28 | self.pred_ratio_var = pred_ratio_var[0] if isinstance(pred_ratio_var, list) and \ 29 | len(pred_ratio_var) == 1 else pred_ratio_var 30 | if isinstance(self.pred_ratio, list) and not isinstance(self.pred_ratio_var, list): 31 | self.pred_ratio_var = [self.pred_ratio_var] * len(self.pred_ratio) 32 | self.log_aspect_ratio = tuple(map(lambda x: math.log(x), pred_aspect_ratio)) 33 | self.pred_shape = pred_shape 34 | self.pred_start_epoch = pred_start_epoch 35 | 36 | def get_pred_ratio(self): 37 | if hasattr(self, 'epoch') and self.epoch < self.pred_start_epoch: 38 | return 0 39 | 40 | if isinstance(self.pred_ratio, list): 41 | pred_ratio = [] 42 | for prm, prv in zip(self.pred_ratio, self.pred_ratio_var): 43 | assert prm >= prv 44 | pr = random.uniform(prm - prv, prm + prv) if prv > 0 else prm 45 | pred_ratio.append(pr) 46 | pred_ratio = random.choice(pred_ratio) 47 | else: 48 | assert self.pred_ratio >= self.pred_ratio_var 49 | pred_ratio = random.uniform(self.pred_ratio - self.pred_ratio_var, self.pred_ratio + \ 50 | self.pred_ratio_var) if self.pred_ratio_var > 0 else self.pred_ratio 51 | 52 | return pred_ratio 53 | 54 | def set_epoch(self, epoch): 55 | self.epoch = epoch 56 | 57 | def __getitem__(self, index): 58 | output = super(ImageFolderMask, self).__getitem__(index) 59 | 60 | masks = [] 61 | for img in output[0]: 62 | try: 63 | H, W = img.shape[1] // self.psz, img.shape[2] // self.psz 64 | except: 65 | # skip non-image 66 | continue 67 | 68 | high = self.get_pred_ratio() * H * W 69 | 70 | if self.pred_shape == 'block': 71 | # following BEiT (https://arxiv.org/abs/2106.08254), see at 72 | # https://github.com/microsoft/unilm/blob/b94ec76c36f02fb2b0bf0dcb0b8554a2185173cd/beit/masking_generator.py#L55 73 | mask = np.zeros((H, W), dtype=bool) 74 | mask_count = 0 75 | while mask_count < high: 76 | max_mask_patches = high - mask_count 77 | 78 | delta = 0 79 | for attempt in range(10): 80 | low = (min(H, W) // 3) ** 2 81 | target_area = random.uniform(low, max_mask_patches) 82 | aspect_ratio = math.exp(random.uniform(*self.log_aspect_ratio)) 83 | h = int(round(math.sqrt(target_area * aspect_ratio))) 84 | w = int(round(math.sqrt(target_area / aspect_ratio))) 85 | if w < W and h < H: 86 | top = random.randint(0, H - h) 87 | left = random.randint(0, W - w) 88 | 89 | num_masked = mask[top: top + h, left: left + w].sum() 90 | if 0 < h * w - num_masked <= max_mask_patches: 91 | for i in range(top, top + h): 92 | for j in range(left, left + w): 93 | if mask[i, j] == 0: 94 | mask[i, j] = 1 95 | delta += 1 96 | 97 | if delta > 0: 98 | break 99 | 100 | if delta == 0: 101 | break 102 | else: 103 | mask_count += delta 104 | 105 | elif self.pred_shape == 'rand': 106 | mask = np.hstack([ 107 | np.zeros(H * W - int(high)), 108 | np.ones(int(high)), 109 | ]).astype(bool) 110 | np.random.shuffle(mask) 111 | mask = mask.reshape(H, W) 112 | 113 | else: 114 | # no implementation 115 | assert False 116 | 117 | masks.append(mask) 118 | 119 | return output + (masks,) 120 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | ## creative commons 2 | 3 | # Attribution-NonCommercial 4.0 International 4 | 5 | Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. 6 | 7 | ### Using Creative Commons Public Licenses 8 | 9 | Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. 10 | 11 | * __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors). 12 | 13 | * __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees). 14 | 15 | ## Creative Commons Attribution-NonCommercial 4.0 International Public License 16 | 17 | By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. 18 | 19 | ### Section 1 – Definitions. 20 | 21 | a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. 22 | 23 | b. __Adapter's License__ means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. 24 | 25 | c. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. 26 | 27 | d. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. 28 | 29 | e. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. 30 | 31 | f. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License. 32 | 33 | g. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. 34 | 35 | h. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License. 36 | 37 | i. __NonCommercial__ means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange. 38 | 39 | j. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. 40 | 41 | k. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. 42 | 43 | l. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. 44 | 45 | ### Section 2 – Scope. 46 | 47 | a. ___License grant.___ 48 | 49 | 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: 50 | 51 | A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and 52 | 53 | B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only. 54 | 55 | 2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. 56 | 57 | 3. __Term.__ The term of this Public License is specified in Section 6(a). 58 | 59 | 4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. 60 | 61 | 5. __Downstream recipients.__ 62 | 63 | A. __Offer from the Licensor – Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. 64 | 65 | B. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. 66 | 67 | 6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). 68 | 69 | b. ___Other rights.___ 70 | 71 | 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. 72 | 73 | 2. Patent and trademark rights are not licensed under this Public License. 74 | 75 | 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes. 76 | 77 | ### Section 3 – License Conditions. 78 | 79 | Your exercise of the Licensed Rights is expressly made subject to the following conditions. 80 | 81 | a. ___Attribution.___ 82 | 83 | 1. If You Share the Licensed Material (including in modified form), You must: 84 | 85 | A. retain the following if it is supplied by the Licensor with the Licensed Material: 86 | 87 | i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); 88 | 89 | ii. a copyright notice; 90 | 91 | iii. a notice that refers to this Public License; 92 | 93 | iv. a notice that refers to the disclaimer of warranties; 94 | 95 | v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; 96 | 97 | B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and 98 | 99 | C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. 100 | 101 | 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 102 | 103 | 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. 104 | 105 | 4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License. 106 | 107 | ### Section 4 – Sui Generis Database Rights. 108 | 109 | Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: 110 | 111 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only; 112 | 113 | b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and 114 | 115 | c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. 116 | 117 | For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. 118 | 119 | ### Section 5 – Disclaimer of Warranties and Limitation of Liability. 120 | 121 | a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__ 122 | 123 | b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__ 124 | 125 | c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. 126 | 127 | ### Section 6 – Term and Termination. 128 | 129 | a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. 130 | 131 | b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 132 | 133 | 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 134 | 135 | 2. upon express reinstatement by the Licensor. 136 | 137 | For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. 138 | 139 | c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. 140 | 141 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. 142 | 143 | ### Section 7 – Other Terms and Conditions. 144 | 145 | a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. 146 | 147 | b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. 148 | 149 | ### Section 8 – Interpretation. 150 | 151 | a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. 152 | 153 | b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. 154 | 155 | c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. 156 | 157 | d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. 158 | 159 | > Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. 160 | > 161 | > Creative Commons may be contacted at creativecommons.org 162 | 163 | 164 | ### Commercial licensing opportunities 165 | For commercial uses of the Model & Software, please send email to cmm[AT]nankai.edu.cn 166 | 167 | Citation: 168 | 169 | @article{li2025hssl, 170 | title={Enhancing Representations through Heterogeneous Self-Supervised Learning}, 171 | author={Li, Zhong-Yu and Yin, Bo-Wen and Liu, Yongxiang and Liu, Li and Cheng, Ming-Ming}, 172 | journal=TPAMI, 173 | year={2025} 174 | } 175 | 176 | Copyright (c) 2025 MCG-NKU -------------------------------------------------------------------------------- /models/vision_transformer.py: -------------------------------------------------------------------------------- 1 | # This source code is licensed under the license found in the 2 | # LICENSE file in the root directory of this source tree. 3 | # -------------------------------------------------------- 4 | # References: 5 | # iBOT: https://github.com/bytedance/ibot 6 | # -------------------------------------------------------- 7 | 8 | import math 9 | import torch 10 | import torch.nn as nn 11 | import utils 12 | from functools import partial 13 | from utils import trunc_normal_ 14 | import torch.nn.functional as F 15 | from timm.models.registry import register_model 16 | 17 | 18 | def drop_path(x, drop_prob: float = 0., training: bool = False): 19 | if drop_prob == 0. or not training: 20 | return x 21 | keep_prob = 1 - drop_prob 22 | shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets 23 | random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device) 24 | random_tensor.floor_() # binarize 25 | output = x.div(keep_prob) * random_tensor 26 | return output 27 | 28 | 29 | class DropPath(nn.Module): 30 | """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). 31 | """ 32 | def __init__(self, drop_prob=None): 33 | super(DropPath, self).__init__() 34 | self.drop_prob = drop_prob 35 | 36 | def forward(self, x): 37 | return drop_path(x, self.drop_prob, self.training) 38 | 39 | 40 | class Mlp(nn.Module): 41 | def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): 42 | super().__init__() 43 | out_features = out_features or in_features 44 | hidden_features = hidden_features or in_features 45 | self.fc1 = nn.Linear(in_features, hidden_features) 46 | self.act = act_layer() 47 | self.fc2 = nn.Linear(hidden_features, out_features) 48 | self.drop = nn.Dropout(drop) 49 | 50 | def forward(self, x): 51 | x = self.fc1(x) 52 | x = self.act(x) 53 | x = self.drop(x) 54 | x = self.fc2(x) 55 | x = self.drop(x) 56 | return x 57 | 58 | 59 | class Attention(nn.Module): 60 | def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.): 61 | super().__init__() 62 | self.num_heads = num_heads 63 | head_dim = dim // num_heads 64 | self.scale = qk_scale or head_dim ** -0.5 65 | 66 | self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) 67 | self.attn_drop = nn.Dropout(attn_drop) 68 | self.proj = nn.Linear(dim, dim) 69 | self.proj_drop = nn.Dropout(proj_drop) 70 | 71 | def forward(self, x): 72 | B, N, C = x.shape 73 | qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) 74 | q, k, v = qkv[0], qkv[1], qkv[2] 75 | 76 | attn = (q @ k.transpose(-2, -1)) * self.scale 77 | attn = attn.softmax(dim=-1) 78 | attn = self.attn_drop(attn) 79 | 80 | x = (attn @ v).transpose(1, 2).reshape(B, N, C) 81 | x = self.proj(x) 82 | x = self.proj_drop(x) 83 | return x, attn 84 | 85 | 86 | class Block(nn.Module): 87 | def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., 88 | attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, init_values=0): 89 | super().__init__() 90 | self.norm1 = norm_layer(dim) 91 | self.attn = Attention( 92 | dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop) 93 | self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() 94 | self.norm2 = norm_layer(dim) 95 | mlp_hidden_dim = int(dim * mlp_ratio) 96 | self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) 97 | 98 | if init_values > 0: 99 | self.gamma_1 = nn.Parameter(init_values * torch.ones((dim)), requires_grad=True) 100 | self.gamma_2 = nn.Parameter(init_values * torch.ones((dim)), requires_grad=True) 101 | else: 102 | self.gamma_1, self.gamma_2 = None, None 103 | 104 | def forward(self, x, return_attention=False): 105 | y, attn = self.attn(self.norm1(x)) 106 | if return_attention: 107 | return attn 108 | if self.gamma_1 is None: 109 | x = x + self.drop_path(y) 110 | x = x + self.drop_path(self.mlp(self.norm2(x))) 111 | else: 112 | x = x + self.drop_path(self.gamma_1 * y) 113 | x = x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x))) 114 | return x 115 | 116 | 117 | class ConvNextLayerNorm(nn.Module): 118 | r""" LayerNorm that supports two data formats: channels_last (default) or channels_first. 119 | The ordering of the dimensions in the inputs. channels_last corresponds to inputs with 120 | shape (batch_size, height, width, channels) while channels_first corresponds to inputs 121 | with shape (batch_size, channels, height, width). 122 | """ 123 | def __init__(self, normalized_shape, eps=1e-6, data_format="channels_last"): 124 | super().__init__() 125 | self.weight = nn.Parameter(torch.ones(normalized_shape)) 126 | self.bias = nn.Parameter(torch.zeros(normalized_shape)) 127 | self.eps = eps 128 | self.data_format = data_format 129 | if self.data_format not in ["channels_last", "channels_first"]: 130 | raise NotImplementedError 131 | self.normalized_shape = (normalized_shape, ) 132 | 133 | def forward(self, x): 134 | if self.data_format == "channels_last": 135 | return F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps) 136 | elif self.data_format == "channels_first": 137 | u = x.mean(1, keepdim=True) 138 | s = (x - u).pow(2).mean(1, keepdim=True) 139 | x = (x - u) / torch.sqrt(s + self.eps) 140 | x = self.weight[:, None, None] * x + self.bias[:, None, None] 141 | return x 142 | 143 | 144 | class ConvNextBlock(nn.Module): 145 | r""" ConvNeXt Block. There are two equivalent implementations: 146 | (1) DwConv -> LayerNorm (channels_first) -> 1x1 Conv -> GELU -> 1x1 Conv; all in (N, C, H, W) 147 | (2) DwConv -> Permute to (N, H, W, C); LayerNorm (channels_last) -> Linear -> GELU -> Linear; Permute back 148 | We use (2) as we find it slightly faster in PyTorch 149 | 150 | Args: 151 | dim (int): Number of input channels. 152 | drop_path (float): Stochastic depth rate. Default: 0.0 153 | layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6. 154 | """ 155 | def __init__(self, dim, kernel_size=7, drop_path=0., short_cut=False): 156 | super().__init__() 157 | self.dwconv = nn.Conv2d(dim, dim, kernel_size=kernel_size, padding=(kernel_size // 2), groups=dim) # depthwise conv 158 | self.norm = ConvNextLayerNorm(dim, eps=1e-6) 159 | self.pwconv1 = nn.Linear(dim, 4 * dim) # pointwise/1x1 convs, implemented with linear layers 160 | self.act = nn.GELU() 161 | self.pwconv2 = nn.Linear(4 * dim, dim) 162 | self.short_cut = short_cut 163 | self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() 164 | 165 | def forward(self, x): 166 | input = x 167 | x = self.dwconv(x) 168 | x = x.permute(0, 2, 3, 1) # (N, C, H, W) -> (N, H, W, C) 169 | x = self.norm(x) 170 | x = self.pwconv1(x) 171 | x = self.act(x) 172 | x = self.pwconv2(x) 173 | x = x.permute(0, 3, 1, 2) # (N, H, W, C) -> (N, C, H, W) 174 | if self.short_cut: 175 | x = self.drop_path(x) + input 176 | return x 177 | 178 | 179 | class PatchEmbed(nn.Module): 180 | """ Image to Patch Embedding 181 | """ 182 | def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768): 183 | super().__init__() 184 | num_patches = (img_size // patch_size) * (img_size // patch_size) 185 | self.img_size = img_size 186 | self.patch_size = patch_size 187 | self.num_patches = num_patches 188 | 189 | self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size) 190 | 191 | def forward(self, x): 192 | x = self.proj(x) 193 | h, w = x.shape[2:] 194 | 195 | return x, h, w 196 | 197 | 198 | class VisionTransformer(nn.Module): 199 | """ Vision Transformer """ 200 | def __init__(self, img_size=[224], patch_size=16, in_chans=3, num_classes=0, embed_dim=768, depth=12, auxiliary_depth=0, 201 | num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0., 202 | drop_path_rate=0., norm_layer=partial(nn.LayerNorm, eps=1e-6), return_all_tokens=False, 203 | init_values=0, use_mean_pooling=False, masked_im_modeling=False, kernel_size=7): 204 | super().__init__() 205 | self.num_features = self.embed_dim = embed_dim 206 | self.return_all_tokens = return_all_tokens 207 | self.depth = depth 208 | self.auxiliary_depth = auxiliary_depth 209 | 210 | self.patch_embed = PatchEmbed( 211 | img_size=img_size[0], patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim) 212 | num_patches = self.patch_embed.num_patches 213 | 214 | self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) 215 | self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim)) 216 | self.pos_drop = nn.Dropout(p=drop_rate) 217 | 218 | dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth + auxiliary_depth)] # stochastic depth decay rule 219 | self.blocks = nn.ModuleList([ 220 | Block( 221 | dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, 222 | drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer, 223 | init_values=init_values) 224 | for i in range(depth)]) 225 | 226 | self.conv_blocks = nn.ModuleList() 227 | for i in range(auxiliary_depth): 228 | self.conv_blocks.append( 229 | ConvNextBlock( 230 | dim=embed_dim, kernel_size=kernel_size, drop_path=dpr[i + self.depth], short_cut=i > 0) 231 | ) 232 | 233 | self.norm = nn.Identity() if use_mean_pooling else norm_layer(embed_dim) 234 | self.norm2 = nn.Identity() if use_mean_pooling else norm_layer(embed_dim) 235 | assert not use_mean_pooling 236 | self.fc_norm = norm_layer(embed_dim) if use_mean_pooling else None 237 | # Classifier head 238 | self.head = nn.Linear(embed_dim, num_classes) if num_classes > 0 else nn.Identity() 239 | 240 | trunc_normal_(self.pos_embed, std=.02) 241 | trunc_normal_(self.cls_token, std=.02) 242 | self.apply(self._init_weights) 243 | 244 | # masked image modeling 245 | self.masked_im_modeling = masked_im_modeling 246 | if masked_im_modeling: 247 | self.masked_embed = nn.Parameter(torch.zeros(1, embed_dim)) 248 | 249 | def _init_weights(self, m): 250 | if isinstance(m, nn.Linear): 251 | trunc_normal_(m.weight, std=.02) 252 | if isinstance(m, nn.Linear) and m.bias is not None: 253 | nn.init.constant_(m.bias, 0) 254 | elif isinstance(m, nn.LayerNorm): 255 | nn.init.constant_(m.bias, 0) 256 | nn.init.constant_(m.weight, 1.0) 257 | 258 | def interpolate_pos_encoding(self, x, w, h): 259 | npatch = x.shape[1] - 1 260 | N = self.pos_embed.shape[1] - 1 261 | if npatch == N and w == h: 262 | return self.pos_embed 263 | class_pos_embed = self.pos_embed[:, 0] 264 | patch_pos_embed = self.pos_embed[:, 1:] 265 | dim = x.shape[-1] 266 | w0 = w // self.patch_embed.patch_size 267 | h0 = h // self.patch_embed.patch_size 268 | # we add a small number to avoid floating point error in the interpolation 269 | # see discussion at https://github.com/facebookresearch/dino/issues/8 270 | w0, h0 = w0 + 0.1, h0 + 0.1 271 | patch_pos_embed = nn.functional.interpolate( 272 | patch_pos_embed.reshape(1, int(math.sqrt(N)), int(math.sqrt(N)), dim).permute(0, 3, 1, 2), 273 | scale_factor=(w0 / math.sqrt(N), h0 / math.sqrt(N)), 274 | mode='bicubic', 275 | ) 276 | assert int(w0) == patch_pos_embed.shape[-2] and int(h0) == patch_pos_embed.shape[-1] 277 | patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim) 278 | return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1) 279 | 280 | def prepare_tokens(self, x, mask=None): 281 | B, _, w, h = x.shape 282 | x, fh, fw = self.patch_embed(x) 283 | 284 | # mask image modeling 285 | if mask is not None: 286 | x = self.mask_model(x, mask) 287 | x = x.flatten(2).transpose(1, 2) 288 | 289 | # add the [CLS] token to the embed patch tokens 290 | cls_tokens = self.cls_token.expand(B, -1, -1) 291 | x = torch.cat((cls_tokens, x), dim=1) 292 | 293 | # add positional encoding to each token 294 | x = x + self.interpolate_pos_encoding(x, w, h) 295 | 296 | return self.pos_drop(x), fh, fw 297 | 298 | def forward(self, x, return_all_tokens=None, mask=None): 299 | # mim 300 | if self.masked_im_modeling: 301 | assert mask is not None 302 | x, h, w = self.prepare_tokens(x, mask=mask) 303 | else: 304 | x, h, w = self.prepare_tokens(x) 305 | 306 | for blk in self.blocks: 307 | x = blk(x) 308 | out1 = self.norm(x) 309 | 310 | # conv 311 | B, N, C = x.shape 312 | x_auxiliary = x[:, 1:, :].view(B, h, w, C).permute(0, 3, 1, 2) # [B C H W] 313 | for conv_blk in self.conv_blocks: 314 | x_auxiliary = conv_blk(x_auxiliary) 315 | x_auxiliary_clstoken = x_auxiliary.mean(dim=[2, 3]) # [B C] 316 | x_auxiliary = x_auxiliary.view(B, C, h * w).permute(0, 2, 1) # [B N C] 317 | x_auxiliary = torch.cat([x_auxiliary_clstoken.unsqueeze(1), x_auxiliary], dim=1) 318 | out2 = self.norm2(x_auxiliary) 319 | 320 | assert self.fc_norm is None 321 | 322 | return_all_tokens = self.return_all_tokens if \ 323 | return_all_tokens is None else return_all_tokens 324 | if return_all_tokens: 325 | return out1, out2 326 | return out1[:, 0], out2[:, 0] 327 | 328 | def get_last_selfattention(self, x): 329 | x = self.prepare_tokens(x) 330 | for i, blk in enumerate(self.blocks): 331 | if i < len(self.blocks) - 1: 332 | x = blk(x) 333 | else: 334 | # return attention of the last block 335 | return blk(x, return_attention=True) 336 | 337 | def get_intermediate_layers(self, x, n=1): 338 | x = self.prepare_tokens(x) 339 | # we return the output tokens from the `n` last blocks 340 | output = [] 341 | for i, blk in enumerate(self.blocks): 342 | x = blk(x) 343 | if len(self.blocks) - i <= n: 344 | output.append(self.norm(x)) 345 | return output 346 | 347 | def get_num_layers(self): 348 | return len(self.blocks) 349 | 350 | def mask_model(self, x, mask): 351 | x.permute(0, 2, 3, 1)[mask, :] = self.masked_embed.to(x.dtype) 352 | return x 353 | 354 | 355 | def vit_tiny(patch_size=16, **kwargs): 356 | model = VisionTransformer( 357 | patch_size=patch_size, embed_dim=192, depth=12, num_heads=3, mlp_ratio=4, 358 | qkv_bias=True, **kwargs) 359 | return model 360 | 361 | 362 | def vit_small(patch_size=16, **kwargs): 363 | model = VisionTransformer( 364 | patch_size=patch_size, embed_dim=384, depth=12, num_heads=6, mlp_ratio=4, 365 | qkv_bias=True, **kwargs) 366 | return model 367 | 368 | 369 | def vit_base(patch_size=16, **kwargs): 370 | model = VisionTransformer( 371 | patch_size=patch_size, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4, 372 | qkv_bias=True, **kwargs) 373 | return model 374 | 375 | 376 | def vit_large(patch_size=16, **kwargs): 377 | model = VisionTransformer( 378 | patch_size=patch_size, embed_dim=1024, depth=24, num_heads=16, mlp_ratio=4, 379 | qkv_bias=True, **kwargs) 380 | return model 381 | 382 | 383 | class MultiCropWrapper(nn.Module): 384 | """ 385 | Perform forward pass separately on each resolution input. 386 | The inputs corresponding to a single resolution are clubbed and single 387 | forward is run on the same resolution inputs. Hence we do several 388 | forward passes = number of different resolutions used. We then 389 | concatenate all the output features and run the head forward on these 390 | concatenated features. 391 | """ 392 | def __init__(self, backbone, head=None): 393 | super(MultiCropWrapper, self).__init__() 394 | # disable layers dedicated to ImageNet labels classification 395 | backbone.fc, backbone.head = nn.Identity(), nn.Identity() 396 | self.backbone = backbone 397 | if head is None: 398 | self.head = nn.Identity() 399 | else: 400 | self.head = head 401 | 402 | def forward(self, x, mask=None, return_backbone_feat=False, **kwargs): 403 | if not isinstance(x, list): 404 | x = [x] 405 | mask = [mask] if mask is not None else None 406 | 407 | idx_crops = torch.cumsum(torch.unique_consecutive( 408 | torch.tensor([inp.shape[-1] for inp in x]), 409 | return_counts=True, 410 | )[1], 0) 411 | 412 | outputs = [] 413 | start_idx = 0 414 | for end_idx in idx_crops: 415 | inp_x = torch.cat(x[start_idx: end_idx]) 416 | if mask is not None: 417 | kwargs.update(dict(mask=torch.cat(mask[start_idx: end_idx]))) 418 | 419 | _out_base, _out_auxiliary = self.backbone(inp_x, **kwargs) 420 | outputs.append((_out_base, _out_auxiliary)) 421 | start_idx = end_idx 422 | 423 | output_base = torch.cat([out[0] for out in outputs]) 424 | output_auxiliary = torch.cat([out[1] for out in outputs]) 425 | 426 | output_base_1, output_base_2, output_auxiliary_1, output_auxiliary_2 = self.head(output_base, output_auxiliary) 427 | 428 | if return_backbone_feat: 429 | return output_base, output_auxiliary, output_base_1, output_base_2, output_auxiliary_1, output_auxiliary_2 430 | return output_base_1, output_base_2, output_auxiliary_1, output_auxiliary_2 431 | 432 | 433 | class CSyncBatchNorm(nn.SyncBatchNorm): 434 | def __init__(self, 435 | *args, 436 | with_var=False, 437 | **kwargs): 438 | super(CSyncBatchNorm, self).__init__(*args, **kwargs) 439 | self.with_var = with_var 440 | 441 | def forward(self, x): 442 | # center norm 443 | self.training = False 444 | if not self.with_var: 445 | self.running_var = torch.ones_like(self.running_var) 446 | normed_x = super(CSyncBatchNorm, self).forward(x) 447 | # udpate center 448 | self.training = True 449 | _ = super(CSyncBatchNorm, self).forward(x) 450 | return normed_x 451 | 452 | 453 | class PSyncBatchNorm(nn.SyncBatchNorm): 454 | def __init__(self, 455 | *args, 456 | bunch_size, 457 | **kwargs): 458 | procs_per_bunch = min(bunch_size, utils.get_world_size()) 459 | assert utils.get_world_size() % procs_per_bunch == 0 460 | n_bunch = utils.get_world_size() // procs_per_bunch 461 | # 462 | ranks = list(range(utils.get_world_size())) 463 | print('---ALL RANKS----\n{}'.format(ranks)) 464 | rank_groups = [ranks[i*procs_per_bunch: (i+1)*procs_per_bunch] for i in range(n_bunch)] 465 | print('---RANK GROUPS----\n{}'.format(rank_groups)) 466 | process_groups = [torch.distributed.new_group(pids) for pids in rank_groups] 467 | bunch_id = utils.get_rank() // procs_per_bunch 468 | process_group = process_groups[bunch_id] 469 | print('---CURRENT GROUP----\n{}'.format(process_group)) 470 | super(PSyncBatchNorm, self).__init__(*args, process_group=process_group, **kwargs) 471 | 472 | 473 | class CustomSequential(nn.Sequential): 474 | bn_types = (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d, nn.SyncBatchNorm) 475 | 476 | def forward(self, input): 477 | for module in self: 478 | dim = len(input.shape) 479 | if isinstance(module, self.bn_types) and dim > 2: 480 | perm = list(range(dim - 1)); perm.insert(1, dim - 1) 481 | inv_perm = list(range(dim)) + [1]; inv_perm.pop(1) 482 | input = module(input.permute(*perm)).permute(*inv_perm) 483 | else: 484 | input = module(input) 485 | return input 486 | 487 | 488 | class DINOHead(nn.Module): 489 | def __init__(self, in_dim, out_dim, norm=None, act='gelu', 490 | nlayers=3, hidden_dim=2048, bottleneck_dim=256, norm_last_layer=True, **kwargs): 491 | super().__init__() 492 | assert bottleneck_dim > 0, "bottleneck_dim must be greater than 0" 493 | norm1 = self._build_norm(norm, hidden_dim) 494 | norm2 = self._build_norm(norm, hidden_dim) 495 | act1 = self._build_act(act) 496 | act2 = self._build_act(act) 497 | 498 | nlayers = max(nlayers, 1) 499 | self.mlp = self.get_mlp(nlayers, in_dim, bottleneck_dim, hidden_dim, out_dim, norm1, act1) 500 | self.mlp2 = self.get_mlp(nlayers, in_dim, bottleneck_dim, hidden_dim, out_dim, norm2, act2) 501 | self.apply(self._init_weights) 502 | 503 | self.last_layer = nn.utils.weight_norm(nn.Linear(bottleneck_dim, out_dim, bias=False)) 504 | self.last_layer.weight_g.data.fill_(1) 505 | if norm_last_layer: 506 | self.last_layer.weight_g.requires_grad = False 507 | 508 | def get_mlp(self, nlayers, in_dim, bottleneck_dim, hidden_dim, out_dim, norm, act): 509 | if nlayers == 1: 510 | if bottleneck_dim > 0: 511 | mlp = nn.Linear(in_dim, bottleneck_dim) 512 | else: 513 | mlp = nn.Linear(in_dim, out_dim) 514 | else: 515 | layers = [nn.Linear(in_dim, hidden_dim)] 516 | if norm is not None: 517 | layers.append(norm) 518 | layers.append(act) 519 | for _ in range(nlayers - 2): 520 | layers.append(nn.Linear(hidden_dim, hidden_dim)) 521 | if norm is not None: 522 | layers.append(norm) 523 | layers.append(act) 524 | if bottleneck_dim > 0: 525 | layers.append(nn.Linear(hidden_dim, bottleneck_dim)) 526 | else: 527 | layers.append(nn.Linear(hidden_dim, out_dim)) 528 | mlp = CustomSequential(*layers) 529 | 530 | return mlp 531 | 532 | def _init_weights(self, m): 533 | if isinstance(m, nn.Linear): 534 | trunc_normal_(m.weight, std=.02) 535 | if isinstance(m, nn.Linear) and m.bias is not None: 536 | nn.init.constant_(m.bias, 0) 537 | 538 | def forward(self, x1, x2): 539 | x1 = self.mlp(x1) 540 | x2 = self.mlp2(x2) 541 | 542 | x1 = nn.functional.normalize(x1, dim=-1, p=2) 543 | x2 = nn.functional.normalize(x2, dim=-1, p=2) 544 | 545 | x1 = self.last_layer(x1) 546 | x2 = self.last_layer(x2) 547 | 548 | return x1, x2 549 | 550 | def _build_norm(self, norm, hidden_dim, **kwargs): 551 | if norm == 'bn': 552 | norm = nn.BatchNorm1d(hidden_dim, **kwargs) 553 | elif norm == 'syncbn': 554 | norm = nn.SyncBatchNorm(hidden_dim, **kwargs) 555 | elif norm == 'csyncbn': 556 | norm = CSyncBatchNorm(hidden_dim, **kwargs) 557 | elif norm == 'psyncbn': 558 | norm = PSyncBatchNorm(hidden_dim, **kwargs) 559 | elif norm == 'ln': 560 | norm = nn.LayerNorm(hidden_dim, **kwargs) 561 | else: 562 | assert norm is None, "unknown norm type {}".format(norm) 563 | return norm 564 | 565 | def _build_act(self, act): 566 | if act == 'relu': 567 | act = nn.ReLU() 568 | elif act == 'gelu': 569 | act = nn.GELU() 570 | else: 571 | assert False, "unknown act type {}".format(act) 572 | return act 573 | 574 | 575 | # Modified from iBOT: https://github.com/bytedance/ibot 576 | class HSSLHead(DINOHead): 577 | 578 | def __init__(self, *args, patch_out_dim=8192, norm=None, act='gelu', 579 | nlayers=3, hidden_dim=2048, bottleneck_dim=256, norm_last_layer=True, 580 | shared_head=False, **kwargs): 581 | 582 | super(HSSLHead, self).__init__(*args, 583 | norm=norm, 584 | act=act, 585 | nlayers=nlayers, 586 | hidden_dim=hidden_dim, 587 | bottleneck_dim=bottleneck_dim, 588 | norm_last_layer=norm_last_layer, 589 | **kwargs) 590 | assert shared_head 591 | assert bottleneck_dim > 0 592 | if not shared_head: 593 | self.last_layer2 = nn.utils.weight_norm(nn.Linear(bottleneck_dim, patch_out_dim, bias=False)) 594 | self.last_layer2.weight_g.data.fill_(1) 595 | if norm_last_layer: 596 | self.last_layer2.weight_g.requires_grad = False 597 | 598 | else: 599 | self.last_layer2 = self.last_layer 600 | 601 | def forward(self, x1, x2): 602 | 603 | x1 = self.mlp(x1) 604 | x2 = self.mlp2(x2) 605 | x1 = nn.functional.normalize(x1, dim=-1, p=2) 606 | x2 = nn.functional.normalize(x2, dim=-1, p=2) 607 | x1_1 = self.last_layer(x1[:, 0]) 608 | x1_2 = self.last_layer2(x1[:, 1:]) 609 | x2_1 = self.last_layer(x2[:, 0]) 610 | x2_2 = self.last_layer2(x2[:, 1:]) 611 | 612 | return x1_1, x1_2, x2_1, x2_2 613 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | # This source code is licensed under the license found in the 2 | # LICENSE file in the root directory of this source tree. 3 | # -------------------------------------------------------- 4 | # References: 5 | # iBOT: https://github.com/bytedance/ibot 6 | # -------------------------------------------------------- 7 | 8 | import os 9 | import sys 10 | import time 11 | import math 12 | import json 13 | import random 14 | import datetime 15 | import subprocess 16 | import numpy as np 17 | import torch 18 | import torch.distributed as dist 19 | 20 | from collections import defaultdict, deque 21 | from pathlib import Path 22 | from torch import nn 23 | from PIL import ImageFilter, ImageOps, Image, ImageDraw 24 | 25 | import argparse 26 | import warnings 27 | from sklearn import metrics 28 | from munkres import Munkres 29 | 30 | 31 | def eval_pred(label, pred, calc_acc=False): 32 | nmi = metrics.normalized_mutual_info_score(label, pred) 33 | ari = metrics.adjusted_rand_score(label, pred) 34 | f = metrics.fowlkes_mallows_score(label, pred) 35 | if not calc_acc: 36 | return nmi, ari, f, -1 37 | pred_adjusted = get_y_preds(label, pred, len(set(label))) 38 | acc = metrics.accuracy_score(pred_adjusted, label) 39 | return nmi, ari, f, acc 40 | 41 | 42 | def calculate_cost_matrix(C, n_clusters): 43 | cost_matrix = np.zeros((n_clusters, n_clusters)) 44 | # cost_matrix[i,j] will be the cost of assigning cluster i to label j 45 | for j in range(n_clusters): 46 | s = np.sum(C[:, j]) # number of examples in cluster i 47 | for i in range(n_clusters): 48 | t = C[i, j] 49 | cost_matrix[j, i] = s - t 50 | return cost_matrix 51 | 52 | 53 | def get_cluster_labels_from_indices(indices): 54 | n_clusters = len(indices) 55 | cluster_labels = np.zeros(n_clusters) 56 | for i in range(n_clusters): 57 | cluster_labels[i] = indices[i][1] 58 | return cluster_labels 59 | 60 | 61 | def get_y_preds(y_true, cluster_assignments, n_clusters): 62 | """ 63 | Computes the predicted labels, where label assignments now 64 | correspond to the actual labels in y_true (as estimated by Munkres) 65 | cluster_assignments: array of labels, outputted by kmeans 66 | y_true: true labels 67 | n_clusters: number of clusters in the dataset 68 | returns: a tuple containing the accuracy and confusion matrix, 69 | in that order 70 | """ 71 | confusion_matrix = metrics.confusion_matrix(y_true, cluster_assignments, labels=None) 72 | # compute accuracy based on optimal 1:1 assignment of clusters to labels 73 | cost_matrix = calculate_cost_matrix(confusion_matrix, n_clusters) 74 | indices = Munkres().compute(cost_matrix) 75 | kmeans_to_true_cluster_labels = get_cluster_labels_from_indices(indices) 76 | 77 | if np.min(cluster_assignments) != 0: 78 | cluster_assignments = cluster_assignments - np.min(cluster_assignments) 79 | y_pred = kmeans_to_true_cluster_labels[cluster_assignments] 80 | return y_pred 81 | 82 | 83 | class GaussianBlur(object): 84 | """ 85 | Apply Gaussian Blur to the PIL image. 86 | """ 87 | def __init__(self, p=0.5, radius_min=0.1, radius_max=2.): 88 | self.prob = p 89 | self.radius_min = radius_min 90 | self.radius_max = radius_max 91 | 92 | def __call__(self, img): 93 | do_it = random.random() <= self.prob 94 | if not do_it: 95 | return img 96 | 97 | return img.filter( 98 | ImageFilter.GaussianBlur( 99 | radius=random.uniform(self.radius_min, self.radius_max) 100 | ) 101 | ) 102 | 103 | 104 | class Solarization(object): 105 | """ 106 | Apply Solarization to the PIL image. 107 | """ 108 | def __init__(self, p): 109 | self.p = p 110 | 111 | def __call__(self, img): 112 | if random.random() < self.p: 113 | return ImageOps.solarize(img) 114 | else: 115 | return img 116 | 117 | 118 | class PermutePatch(object): 119 | """ 120 | Apply Patch permutation to the PIL image. 121 | """ 122 | def __init__(self, psz): 123 | self.psz = psz 124 | 125 | def __call__(self, img): 126 | imgs = [] 127 | imgwidth, imgheight = img.size 128 | for i in range(0, imgheight, self.psz): 129 | for j in range(0, imgwidth, self.psz): 130 | box = (j, i, j+self.psz, i+self.psz) 131 | imgs.append(img.crop(box)) 132 | random.shuffle(imgs) 133 | new_img = Image.new('RGB', (imgwidth, imgheight)) 134 | k = 0 135 | for i in range(0, imgheight, self.psz): 136 | for j in range(0, imgwidth, self.psz): 137 | new_img.paste(imgs[k], (j, i)) 138 | k += 1 139 | return new_img 140 | 141 | 142 | class HideAndSeek(object): 143 | """ 144 | Apply Patch permutation to the PIL image. 145 | """ 146 | def __init__(self, ratio, psz): 147 | self.ratio = ratio 148 | self.psz = psz 149 | 150 | def __call__(self, img): 151 | imgwidth, imgheight = img.size 152 | numw, numh = imgwidth // self.psz, imgheight // self.psz 153 | mask_num = int(numw * numh * self.ratio) 154 | mask_patch = np.random.choice(np.arange(numw * numh), mask_num, replace=False) 155 | mask_w, mask_h = mask_patch % numh, mask_patch // numh 156 | # img.save('test1.png') 157 | draw = ImageDraw.Draw(img) 158 | for mw, mh in zip(mask_w, mask_h): 159 | draw.rectangle((mw * self.psz, 160 | mh * self.psz, 161 | (mw + 1) * self.psz, 162 | (mh + 1) * self.psz), fill="black") 163 | # img.save('test2.png') 164 | return img 165 | 166 | 167 | def load_pretrained_weights(model, pretrained_weights, checkpoint_key, model_name, patch_size): 168 | if os.path.isfile(pretrained_weights): 169 | state_dict = torch.load(pretrained_weights, map_location="cpu") 170 | if checkpoint_key is not None and checkpoint_key in state_dict: 171 | print(f"Take key {checkpoint_key} in provided checkpoint dict") 172 | state_dict = state_dict[checkpoint_key] 173 | # remove `module.` prefix 174 | state_dict = {k.replace("module.", ""): v for k, v in state_dict.items()} 175 | # remove `backbone.` prefix induced by multicrop wrapper 176 | state_dict = {k.replace("backbone.", ""): v for k, v in state_dict.items()} 177 | msg = model.load_state_dict(state_dict, strict=False) 178 | print('Pretrained weights found at {} and loaded with msg: {}'.format(pretrained_weights, msg)) 179 | return 180 | elif pretrained_weights == 'download': 181 | url = None 182 | if model_name == "vit_small" and patch_size == 16: 183 | url = "dino_deitsmall16_pretrain/dino_deitsmall16_pretrain.pth" 184 | elif model_name == "vit_small" and patch_size == 8: 185 | url = "dino_deitsmall8_pretrain/dino_deitsmall8_pretrain.pth" 186 | elif model_name == "vit_base" and patch_size == 16: 187 | url = "dino_vitbase16_pretrain/dino_vitbase16_pretrain.pth" 188 | elif model_name == "vit_base" and patch_size == 8: 189 | url = "dino_vitbase8_pretrain/dino_vitbase8_pretrain.pth" 190 | if url is not None: 191 | print("Since no pretrained weights are provided, we load the pretrained weights from {}.".format(url)) 192 | state_dict = torch.hub.load_state_dict_from_url(url="https://dl.fbaipublicfiles.com/dino/" + url) 193 | model.load_state_dict(state_dict, strict=True) 194 | return 195 | elif pretrained_weights == 'supervised': 196 | url = None 197 | if model_name == "vit_small" and patch_size == 16: 198 | url = "deit_small_patch16_224-cd65a155.pth" 199 | elif model_name == "vit_base" and patch_size == 16: 200 | url = "deit_base_patch16_224-b5f2ef4d.pth" 201 | if url is not None: 202 | print("Since no pretrained weights are provided, we load the pretrained weights from {}.".format(url)) 203 | state_dict = torch.hub.load_state_dict_from_url(url="https://dl.fbaipublicfiles.com/deit/" + url) 204 | msg = model.load_state_dict(state_dict['model'], strict=False) 205 | print('Supervised weights found at {} and loaded with msg: {}'.format(url, msg)) 206 | return 207 | print("There is no reference weights available for this model => We use random weights.") 208 | 209 | 210 | def clip_gradients(model, clip): 211 | norms = [] 212 | for name, p in model.named_parameters(): 213 | if p.grad is not None: 214 | param_norm = p.grad.data.norm(2) 215 | norms.append(param_norm.item()) 216 | clip_coef = clip / (param_norm + 1e-6) 217 | if clip_coef < 1: 218 | p.grad.data.mul_(clip_coef) 219 | return norms 220 | 221 | 222 | def cancel_gradients_last_layer(epoch, model, freeze_last_layer): 223 | if epoch >= freeze_last_layer: 224 | return 225 | for n, p in model.named_parameters(): 226 | if "last_layer" in n: 227 | p.grad = None 228 | 229 | 230 | def restart_from_checkpoint(ckp_path, run_variables=None, **kwargs): 231 | """ 232 | Re-start from checkpoint 233 | """ 234 | if not os.path.isfile(ckp_path): 235 | return 236 | print("Found checkpoint at {}".format(ckp_path)) 237 | 238 | # open checkpoint file 239 | checkpoint = torch.load(ckp_path, map_location="cpu") 240 | 241 | # key is what to look for in the checkpoint file 242 | # value is the object to load 243 | # example: {'state_dict': model} 244 | for key, value in kwargs.items(): 245 | if key in checkpoint and value is not None: 246 | try: 247 | msg = value.load_state_dict(checkpoint[key], strict=False) 248 | print("=> loaded '{}' from checkpoint '{}' with msg {}".format(key, ckp_path, msg)) 249 | except TypeError: 250 | try: 251 | msg = value.load_state_dict(checkpoint[key]) 252 | print("=> loaded '{}' from checkpoint: '{}'".format(key, ckp_path)) 253 | except ValueError: 254 | print("=> failed to load '{}' from checkpoint: '{}'".format(key, ckp_path)) 255 | else: 256 | print("=> key '{}' not found in checkpoint: '{}'".format(key, ckp_path)) 257 | 258 | # re load variable important for the run 259 | if run_variables is not None: 260 | for var_name in run_variables: 261 | if var_name in checkpoint: 262 | run_variables[var_name] = checkpoint[var_name] 263 | 264 | 265 | def cosine_scheduler(base_value, final_value, epochs, niter_per_ep, warmup_epochs=0, start_warmup_value=0): 266 | warmup_schedule = np.array([]) 267 | warmup_iters = warmup_epochs * niter_per_ep 268 | if warmup_epochs > 0: 269 | warmup_schedule = np.linspace(start_warmup_value, base_value, warmup_iters) 270 | 271 | iters = np.arange(epochs * niter_per_ep - warmup_iters) 272 | schedule = final_value + 0.5 * (base_value - final_value) * (1 + np.cos(np.pi * iters / len(iters))) 273 | 274 | schedule = np.concatenate((warmup_schedule, schedule)) 275 | assert len(schedule) == epochs * niter_per_ep 276 | return schedule 277 | 278 | 279 | def bool_flag(s): 280 | """ 281 | Parse boolean arguments from the command line. 282 | """ 283 | FALSY_STRINGS = {"off", "false", "0"} 284 | TRUTHY_STRINGS = {"on", "true", "1"} 285 | if s.lower() in FALSY_STRINGS: 286 | return False 287 | elif s.lower() in TRUTHY_STRINGS: 288 | return True 289 | else: 290 | raise argparse.ArgumentTypeError("invalid value for a boolean flag") 291 | 292 | 293 | def fix_random_seeds(seed=31): 294 | """ 295 | Fix random seeds. 296 | """ 297 | random.seed(seed) 298 | os.environ['PYTHONHASHSEED'] = str(seed) 299 | torch.manual_seed(seed) 300 | torch.cuda.manual_seed_all(seed) 301 | np.random.seed(seed) 302 | 303 | 304 | class SmoothedValue(object): 305 | """Track a series of values and provide access to smoothed values over a 306 | window or the global series average. 307 | """ 308 | 309 | def __init__(self, window_size=20, fmt=None): 310 | if fmt is None: 311 | fmt = "{median:.6f} ({global_avg:.6f})" 312 | self.deque = deque(maxlen=window_size) 313 | self.total = 0.0 314 | self.count = 0 315 | self.fmt = fmt 316 | 317 | def update(self, value, n=1): 318 | self.deque.append(value) 319 | self.count += n 320 | self.total += value * n 321 | 322 | def synchronize_between_processes(self): 323 | """ 324 | Warning: does not synchronize the deque! 325 | """ 326 | if not is_dist_avail_and_initialized(): 327 | return 328 | t = torch.tensor([self.count, self.total], dtype=torch.float64, device='cuda') 329 | dist.barrier() 330 | dist.all_reduce(t) 331 | t = t.tolist() 332 | self.count = int(t[0]) 333 | self.total = t[1] 334 | 335 | @property 336 | def median(self): 337 | d = torch.tensor(list(self.deque)) 338 | return d.median().item() 339 | 340 | @property 341 | def avg(self): 342 | d = torch.tensor(list(self.deque), dtype=torch.float32) 343 | return d.mean().item() 344 | 345 | @property 346 | def global_avg(self): 347 | return self.total / self.count 348 | 349 | @property 350 | def max(self): 351 | return max(self.deque) 352 | 353 | @property 354 | def value(self): 355 | return self.deque[-1] 356 | 357 | def __str__(self): 358 | return self.fmt.format( 359 | median=self.median, 360 | avg=self.avg, 361 | global_avg=self.global_avg, 362 | max=self.max, 363 | value=self.value) 364 | 365 | 366 | def reduce_dict(input_dict, average=True): 367 | """ 368 | Args: 369 | input_dict (dict): all the values will be reduced 370 | average (bool): whether to do average or sum 371 | Reduce the values in the dictionary from all processes so that all processes 372 | have the averaged results. Returns a dict with the same fields as 373 | input_dict, after reduction. 374 | """ 375 | world_size = get_world_size() 376 | if world_size < 2: 377 | return input_dict 378 | with torch.no_grad(): 379 | names = [] 380 | values = [] 381 | # sort the keys so that they are consistent across processes 382 | for k in sorted(input_dict.keys()): 383 | names.append(k) 384 | values.append(input_dict[k]) 385 | values = torch.stack(values, dim=0) 386 | dist.all_reduce(values) 387 | if average: 388 | values /= world_size 389 | reduced_dict = {k: v for k, v in zip(names, values)} 390 | return reduced_dict 391 | 392 | 393 | class MetricLogger(object): 394 | def __init__(self, delimiter="\t"): 395 | self.meters = defaultdict(SmoothedValue) 396 | self.delimiter = delimiter 397 | 398 | def update(self, **kwargs): 399 | for k, v in kwargs.items(): 400 | if isinstance(v, torch.Tensor): 401 | v = v.item() 402 | assert isinstance(v, (float, int)) 403 | self.meters[k].update(v) 404 | 405 | def __getattr__(self, attr): 406 | if attr in self.meters: 407 | return self.meters[attr] 408 | if attr in self.__dict__: 409 | return self.__dict__[attr] 410 | raise AttributeError("'{}' object has no attribute '{}'".format( 411 | type(self).__name__, attr)) 412 | 413 | def __str__(self): 414 | loss_str = [] 415 | for name, meter in self.meters.items(): 416 | loss_str.append( 417 | "{}: {}".format(name, str(meter)) 418 | ) 419 | return self.delimiter.join(loss_str) 420 | 421 | def synchronize_between_processes(self): 422 | for meter in self.meters.values(): 423 | meter.synchronize_between_processes() 424 | 425 | def add_meter(self, name, meter): 426 | self.meters[name] = meter 427 | 428 | def log_every(self, iterable, print_freq, header=None): 429 | i = 0 430 | if not header: 431 | header = '' 432 | start_time = time.time() 433 | end = time.time() 434 | iter_time = SmoothedValue(fmt='{avg:.6f}') 435 | data_time = SmoothedValue(fmt='{avg:.6f}') 436 | space_fmt = ':' + str(len(str(len(iterable)))) + 'd' 437 | if torch.cuda.is_available(): 438 | log_msg = self.delimiter.join([ 439 | header, 440 | '[{0' + space_fmt + '}/{1}]', 441 | 'eta: {eta}', 442 | '{meters}', 443 | 'time: {time}', 444 | 'data: {data}', 445 | 'max mem: {memory:.0f}' 446 | ]) 447 | else: 448 | log_msg = self.delimiter.join([ 449 | header, 450 | '[{0' + space_fmt + '}/{1}]', 451 | 'eta: {eta}', 452 | '{meters}', 453 | 'time: {time}', 454 | 'data: {data}' 455 | ]) 456 | MB = 1024.0 * 1024.0 457 | for obj in iterable: 458 | data_time.update(time.time() - end) 459 | yield obj 460 | iter_time.update(time.time() - end) 461 | if i % print_freq == 0 or i == len(iterable) - 1: 462 | eta_seconds = iter_time.global_avg * (len(iterable) - i) 463 | eta_string = str(datetime.timedelta(seconds=int(eta_seconds))) 464 | if torch.cuda.is_available(): 465 | print(log_msg.format( 466 | i, len(iterable), eta=eta_string, 467 | meters=str(self), 468 | time=str(iter_time), data=str(data_time), 469 | memory=torch.cuda.max_memory_allocated() / MB)) 470 | else: 471 | print(log_msg.format( 472 | i, len(iterable), eta=eta_string, 473 | meters=str(self), 474 | time=str(iter_time), data=str(data_time))) 475 | i += 1 476 | end = time.time() 477 | total_time = time.time() - start_time 478 | total_time_str = str(datetime.timedelta(seconds=int(total_time))) 479 | print('{} Total time: {} ({:.6f} s / it)'.format( 480 | header, total_time_str, total_time / len(iterable))) 481 | 482 | 483 | def get_sha(): 484 | cwd = os.path.dirname(os.path.abspath(__file__)) 485 | 486 | def _run(command): 487 | return subprocess.check_output(command, cwd=cwd).decode('ascii').strip() 488 | sha = 'N/A' 489 | diff = "clean" 490 | branch = 'N/A' 491 | try: 492 | sha = _run(['git', 'rev-parse', 'HEAD']) 493 | subprocess.check_output(['git', 'diff'], cwd=cwd) 494 | diff = _run(['git', 'diff-index', 'HEAD']) 495 | diff = "has uncommited changes" if diff else "clean" 496 | branch = _run(['git', 'rev-parse', '--abbrev-ref', 'HEAD']) 497 | except Exception: 498 | pass 499 | message = f"sha: {sha}, status: {diff}, branch: {branch}" 500 | return message 501 | 502 | 503 | def is_dist_avail_and_initialized(): 504 | if not dist.is_available(): 505 | return False 506 | if not dist.is_initialized(): 507 | return False 508 | return True 509 | 510 | 511 | def get_world_size(): 512 | if not is_dist_avail_and_initialized(): 513 | return 1 514 | return dist.get_world_size() 515 | 516 | 517 | def get_rank(): 518 | if not is_dist_avail_and_initialized(): 519 | return 0 520 | return dist.get_rank() 521 | 522 | 523 | def is_main_process(): 524 | return get_rank() == 0 525 | 526 | 527 | def save_on_master(*args, **kwargs): 528 | if is_main_process(): 529 | torch.save(*args, **kwargs) 530 | 531 | 532 | def setup_for_distributed(is_master): 533 | """ 534 | This function disables printing when not in master process 535 | """ 536 | import builtins as __builtin__ 537 | builtin_print = __builtin__.print 538 | 539 | def print(*args, **kwargs): 540 | force = kwargs.pop('force', False) 541 | if is_master or force: 542 | builtin_print(*args, **kwargs) 543 | 544 | __builtin__.print = print 545 | 546 | 547 | def init_distributed_mode(args): 548 | # launched with torch.distributed.launch 549 | if 'RANK' in os.environ and 'WORLD_SIZE' in os.environ: 550 | args.rank = int(os.environ["RANK"]) 551 | args.world_size = int(os.environ['WORLD_SIZE']) 552 | args.gpu = int(os.environ['LOCAL_RANK']) 553 | # launched with submitit on a slurm cluster 554 | elif 'SLURM_PROCID' in os.environ: 555 | args.rank = int(os.environ['SLURM_PROCID']) 556 | args.gpu = args.rank % torch.cuda.device_count() 557 | # launched naively with `python main_dino.py` 558 | # we manually add MASTER_ADDR and MASTER_PORT to env variables 559 | elif torch.cuda.is_available(): 560 | print('Will run the code on one GPU.') 561 | args.rank, args.gpu, args.world_size = 0, 0, 1 562 | os.environ['MASTER_ADDR'] = '127.0.0.1' 563 | os.environ['MASTER_PORT'] = '29500' 564 | else: 565 | print('Does not support training without GPU.') 566 | sys.exit(1) 567 | 568 | dist.init_process_group( 569 | backend="nccl", 570 | init_method=args.dist_url, 571 | world_size=args.world_size, 572 | rank=args.rank, 573 | ) 574 | 575 | torch.cuda.set_device(args.gpu) 576 | print('| distributed init (rank {}): {}'.format( 577 | args.rank, args.dist_url), flush=True) 578 | dist.barrier() 579 | setup_for_distributed(args.rank == 0) 580 | 581 | 582 | def accuracy(output, target, topk=(1,)): 583 | """Computes the accuracy over the k top predictions for the specified values of k""" 584 | maxk = max(topk) 585 | batch_size = target.size(0) 586 | _, pred = output.topk(maxk, 1, True, True) 587 | pred = pred.t() 588 | correct = pred.eq(target.reshape(1, -1).expand_as(pred)) 589 | return [correct[:k].reshape(-1).float().sum(0) * 100. / batch_size for k in topk] 590 | 591 | 592 | def _no_grad_trunc_normal_(tensor, mean, std, a, b): 593 | # Cut & paste from PyTorch official master until it's in a few official releases - RW 594 | # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf 595 | def norm_cdf(x): 596 | # Computes standard normal cumulative distribution function 597 | return (1. + math.erf(x / math.sqrt(2.))) / 2. 598 | 599 | if (mean < a - 2 * std) or (mean > b + 2 * std): 600 | warnings.warn("mean is more than 2 std from [a, b] in nn.init.trunc_normal_. " 601 | "The distribution of values may be incorrect.", 602 | stacklevel=2) 603 | 604 | with torch.no_grad(): 605 | # Values are generated by using a truncated uniform distribution and 606 | # then using the inverse CDF for the normal distribution. 607 | # Get upper and lower cdf values 608 | l = norm_cdf((a - mean) / std) 609 | u = norm_cdf((b - mean) / std) 610 | 611 | # Uniformly fill tensor with values from [l, u], then translate to 612 | # [2l-1, 2u-1]. 613 | tensor.uniform_(2 * l - 1, 2 * u - 1) 614 | 615 | # Use inverse cdf transform for normal distribution to get truncated 616 | # standard normal 617 | tensor.erfinv_() 618 | 619 | # Transform to proper mean, std 620 | tensor.mul_(std * math.sqrt(2.)) 621 | tensor.add_(mean) 622 | 623 | # Clamp to ensure it's in the proper range 624 | tensor.clamp_(min=a, max=b) 625 | return tensor 626 | 627 | 628 | def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.): 629 | return _no_grad_trunc_normal_(tensor, mean, std, a, b) 630 | 631 | 632 | class LARS(torch.optim.Optimizer): 633 | """ 634 | Almost copy-paste from https://github.com/facebookresearch/barlowtwins/blob/main/main.py 635 | """ 636 | def __init__(self, params, lr=0, weight_decay=0, momentum=0.9, eta=0.001, 637 | weight_decay_filter=None, lars_adaptation_filter=None): 638 | defaults = dict(lr=lr, weight_decay=weight_decay, momentum=momentum, 639 | eta=eta, weight_decay_filter=weight_decay_filter, 640 | lars_adaptation_filter=lars_adaptation_filter) 641 | super().__init__(params, defaults) 642 | 643 | @torch.no_grad() 644 | def step(self): 645 | for g in self.param_groups: 646 | for p in g['params']: 647 | dp = p.grad 648 | 649 | if dp is None: 650 | continue 651 | 652 | if p.ndim != 1: 653 | dp = dp.add(p, alpha=g['weight_decay']) 654 | 655 | if p.ndim != 1: 656 | param_norm = torch.norm(p) 657 | update_norm = torch.norm(dp) 658 | one = torch.ones_like(param_norm) 659 | q = torch.where(param_norm > 0., 660 | torch.where(update_norm > 0, 661 | (g['eta'] * param_norm / update_norm), one), one) 662 | dp = dp.mul(q) 663 | 664 | param_state = self.state[p] 665 | if 'mu' not in param_state: 666 | param_state['mu'] = torch.zeros_like(p) 667 | mu = param_state['mu'] 668 | mu.mul_(g['momentum']).add_(dp) 669 | 670 | p.add_(mu, alpha=-g['lr']) 671 | 672 | 673 | def create_ds_config(args): 674 | args.deepspeed_config = os.path.join(args.output_dir, "deepspeed_config.json") 675 | with open(args.deepspeed_config, mode="w") as writer: 676 | ds_config = { 677 | "train_batch_size": args.batch_size * get_world_size(), 678 | "train_micro_batch_size_per_gpu": args.batch_size, 679 | "steps_per_print": 1000, 680 | "optimizer": { 681 | "type": "Adam", 682 | "adam_w_mode": True, 683 | "params": { 684 | "lr": args.lr, 685 | "weight_decay": args.weight_decay, 686 | "bias_correction": True, 687 | "betas": [ 688 | 0.9, 689 | 0.999 690 | ], 691 | "eps": 1e-8 692 | } 693 | }, 694 | "fp16": { 695 | "enabled": True, 696 | "loss_scale": 0, 697 | "initial_scale_power": 7, 698 | "loss_scale_window": 128 699 | } 700 | } 701 | 702 | writer.write(json.dumps(ds_config, indent=2)) 703 | 704 | 705 | class MultiCropWrapper(nn.Module): 706 | """ 707 | Perform forward pass separately on each resolution input. 708 | The inputs corresponding to a single resolution are clubbed and single 709 | forward is run on the same resolution inputs. Hence we do several 710 | forward passes = number of different resolutions used. We then 711 | concatenate all the output features and run the head forward on these 712 | concatenated features. 713 | """ 714 | def __init__(self, backbone, head=None): 715 | super(MultiCropWrapper, self).__init__() 716 | # disable layers dedicated to ImageNet labels classification 717 | backbone.fc, backbone.head = nn.Identity(), nn.Identity() 718 | self.backbone = backbone 719 | if head is None: 720 | self.head = nn.Identity() 721 | else: 722 | self.head = head 723 | 724 | def forward(self, x, mask=None, return_backbone_feat=False, 725 | **kwargs): 726 | # convert to list 727 | if not isinstance(x, list): 728 | x = [x] 729 | mask = [mask] if mask is not None else None 730 | idx_crops = torch.cumsum(torch.unique_consecutive( 731 | torch.tensor([inp.shape[-1] for inp in x]), 732 | return_counts=True, 733 | )[1], 0) 734 | start_idx = 0 735 | for end_idx in idx_crops: 736 | inp_x = torch.cat(x[start_idx: end_idx]) 737 | 738 | if mask is not None: 739 | inp_m = torch.cat(mask[start_idx: end_idx]) 740 | kwargs.update(dict(mask=inp_m)) 741 | 742 | _out = self.backbone(inp_x, **kwargs) 743 | if start_idx == 0: 744 | output = _out 745 | else: 746 | output = torch.cat((output, _out)) 747 | start_idx = end_idx 748 | # Run the head forward on the concatenated features. 749 | output_ = self.head(output) 750 | if return_backbone_feat: 751 | return output, output_ 752 | return output_ 753 | 754 | 755 | def get_params_groups(model): 756 | regularized = [] 757 | not_regularized = [] 758 | for name, param in model.named_parameters(): 759 | if not param.requires_grad: 760 | continue 761 | # we do not regularize biases nor Norm parameters 762 | if name.endswith(".bias") or len(param.shape) == 1: 763 | not_regularized.append(param) 764 | else: 765 | regularized.append(param) 766 | return [{'params': regularized}, {'params': not_regularized, 'weight_decay': 0.}] 767 | 768 | 769 | def has_batchnorms(model): 770 | bn_types = (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d, nn.SyncBatchNorm) 771 | for name, module in model.named_modules(): 772 | if isinstance(module, bn_types): 773 | return True 774 | return False 775 | 776 | 777 | def concat_all_gather(tensor): 778 | """ 779 | Performs all_gather operation on the provided tensors. 780 | *** Warning ***: torch.distributed.all_gather has no gradient. 781 | """ 782 | tensors_gather = [torch.ones_like(tensor) 783 | for _ in range(torch.distributed.get_world_size())] 784 | torch.distributed.all_gather(tensors_gather, tensor, async_op=False) 785 | 786 | output = torch.cat(tensors_gather, dim=0) 787 | return output 788 | 789 | 790 | class PCA(): 791 | """ 792 | Class to compute and apply PCA. 793 | """ 794 | def __init__(self, dim=256, whit=0.5): 795 | self.dim = dim 796 | self.whit = whit 797 | self.mean = None 798 | 799 | def train_pca(self, cov): 800 | """ 801 | Takes a covariance matrix (np.ndarray) as input. 802 | """ 803 | d, v = np.linalg.eigh(cov) 804 | eps = d.max() * 1e-5 805 | n_0 = (d < eps).sum() 806 | if n_0 > 0: 807 | d[d < eps] = eps 808 | 809 | # total energy 810 | totenergy = d.sum() 811 | 812 | # sort eigenvectors with eigenvalues order 813 | idx = np.argsort(d)[::-1][:self.dim] 814 | d = d[idx] 815 | v = v[:, idx] 816 | 817 | print("keeping %.2f %% of the energy" % (d.sum() / totenergy * 100.0)) 818 | 819 | # for the whitening 820 | d = np.diag(1. / d**self.whit) 821 | 822 | # principal components 823 | self.dvt = np.dot(d, v.T) 824 | 825 | def apply(self, x): 826 | # input is from numpy 827 | if isinstance(x, np.ndarray): 828 | if self.mean is not None: 829 | x -= self.mean 830 | return np.dot(self.dvt, x.T).T 831 | 832 | # input is from torch and is on GPU 833 | if x.is_cuda: 834 | if self.mean is not None: 835 | x -= torch.cuda.FloatTensor(self.mean) 836 | return torch.mm(torch.cuda.FloatTensor(self.dvt), x.transpose(0, 1)).transpose(0, 1) 837 | 838 | # input if from torch, on CPU 839 | if self.mean is not None: 840 | x -= torch.FloatTensor(self.mean) 841 | return torch.mm(torch.FloatTensor(self.dvt), x.transpose(0, 1)).transpose(0, 1) 842 | 843 | 844 | def compute_ap(ranks, nres): 845 | """ 846 | Computes average precision for given ranked indexes. 847 | Arguments 848 | --------- 849 | ranks : zerro-based ranks of positive images 850 | nres : number of positive images 851 | Returns 852 | ------- 853 | ap : average precision 854 | """ 855 | 856 | # number of images ranked by the system 857 | nimgranks = len(ranks) 858 | 859 | # accumulate trapezoids in PR-plot 860 | ap = 0 861 | 862 | recall_step = 1. / nres 863 | 864 | for j in np.arange(nimgranks): 865 | rank = ranks[j] 866 | 867 | if rank == 0: 868 | precision_0 = 1. 869 | else: 870 | precision_0 = float(j) / rank 871 | 872 | precision_1 = float(j + 1) / (rank + 1) 873 | 874 | ap += (precision_0 + precision_1) * recall_step / 2. 875 | 876 | return ap 877 | 878 | 879 | def compute_map(ranks, gnd, kappas=[]): 880 | """ 881 | Computes the mAP for a given set of returned results. 882 | Usage: 883 | map = compute_map (ranks, gnd) 884 | computes mean average precsion (map) only 885 | map, aps, pr, prs = compute_map (ranks, gnd, kappas) 886 | computes mean average precision (map), average precision (aps) for each query 887 | computes mean precision at kappas (pr), precision at kappas (prs) for each query 888 | Notes: 889 | 1) ranks starts from 0, ranks.shape = db_size X #queries 890 | 2) The junk results (e.g., the query itself) should be declared in the gnd stuct array 891 | 3) If there are no positive images for some query, that query is excluded from the evaluation 892 | """ 893 | 894 | map = 0. 895 | nq = len(gnd) # number of queries 896 | aps = np.zeros(nq) 897 | pr = np.zeros(len(kappas)) 898 | prs = np.zeros((nq, len(kappas))) 899 | nempty = 0 900 | 901 | for i in np.arange(nq): 902 | qgnd = np.array(gnd[i]['ok']) 903 | 904 | # no positive images, skip from the average 905 | if qgnd.shape[0] == 0: 906 | aps[i] = float('nan') 907 | prs[i, :] = float('nan') 908 | nempty += 1 909 | continue 910 | 911 | try: 912 | qgndj = np.array(gnd[i]['junk']) 913 | except: 914 | qgndj = np.empty(0) 915 | 916 | # sorted positions of positive and junk images (0 based) 917 | pos = np.arange(ranks.shape[0])[np.in1d(ranks[:,i], qgnd)] 918 | junk = np.arange(ranks.shape[0])[np.in1d(ranks[:,i], qgndj)] 919 | 920 | k = 0; 921 | ij = 0; 922 | if len(junk): 923 | # decrease positions of positives based on the number of 924 | # junk images appearing before them 925 | ip = 0 926 | while (ip < len(pos)): 927 | while (ij < len(junk) and pos[ip] > junk[ij]): 928 | k += 1 929 | ij += 1 930 | pos[ip] = pos[ip] - k 931 | ip += 1 932 | 933 | # compute ap 934 | ap = compute_ap(pos, len(qgnd)) 935 | map = map + ap 936 | aps[i] = ap 937 | 938 | # compute precision @ k 939 | pos += 1 # get it to 1-based 940 | for j in np.arange(len(kappas)): 941 | kq = min(max(pos), kappas[j]); 942 | prs[i, j] = (pos <= kq).sum() / kq 943 | pr = pr + prs[i, :] 944 | 945 | map = map / (nq - nempty) 946 | pr = pr / (nq - nempty) 947 | 948 | return map, aps, pr, prs 949 | -------------------------------------------------------------------------------- /main_hssl_pretrain.py: -------------------------------------------------------------------------------- 1 | # This source code is licensed under the license found in the 2 | # LICENSE file in the root directory of this source tree. 3 | # -------------------------------------------------------- 4 | # References: 5 | # iBOT: https://github.com/bytedance/ibot 6 | # -------------------------------------------------------- 7 | 8 | import argparse 9 | import os 10 | import sys 11 | import datetime 12 | import time 13 | import math 14 | import json 15 | import numpy as np 16 | import utils 17 | import models.vision_transformer as vision_transformer 18 | from models.vision_transformer import HSSLHead, MultiCropWrapper 19 | import torch 20 | import torch.nn as nn 21 | import torch.distributed as dist 22 | import torch.backends.cudnn as cudnn 23 | import torch.nn.functional as F 24 | 25 | from pathlib import Path 26 | from PIL import Image 27 | from torchvision import transforms 28 | from tensorboardX import SummaryWriter 29 | from loader import ImageFolderMask 30 | from utils import eval_pred 31 | 32 | 33 | def get_args_parser(): 34 | parser = argparse.ArgumentParser('HSSL', add_help=False) 35 | 36 | # Model parameters 37 | parser.add_argument('--arch', default='vit_small', type=str, 38 | help="""Name of architecture to train. For quick experiments with ViTs, 39 | we recommend using vit_tiny or vit_small.""") 40 | parser.add_argument('--patch_size', default=16, type=int, help="""Size in pixels 41 | of input square patches - default 16 (for 16x16 patches). Using smaller 42 | values leads to better performance but requires more memory. Applies only 43 | for ViTs (vit_tiny, vit_small and vit_base). If <16, we recommend disabling 44 | mixed precision training (--use_fp16 false) to avoid unstabilities.""") 45 | parser.add_argument('--auxiliary_depth', default=3, type=int, help="""The depth of the auxiliary head.""") 46 | parser.add_argument('--window_size', default=7, type=int, help="""Size of window - default 7. 47 | This config is only valid for Swin Transofmer and is ignoired for vanilla ViT architectures.""") 48 | parser.add_argument('--out_dim', default=8192, type=int, help="""Dimensionality of 49 | output for [CLS] token.""") 50 | parser.add_argument('--patch_out_dim', default=8192, type=int, help="""Dimensionality of 51 | output for patch tokens.""") 52 | parser.add_argument('--shared_head', default=False, type=utils.bool_flag, help="""Wether to share 53 | the same head for [CLS] token output and patch tokens output. When set to false, patch_out_dim 54 | is ignored and enforced to be same with out_dim. (Default: False)""") 55 | parser.add_argument('--shared_head_teacher', default=True, type=utils.bool_flag, help="""See above. 56 | Only works for teacher model. (Defeault: True)""") 57 | parser.add_argument('--norm_last_layer', default=True, type=utils.bool_flag, 58 | help="""Whether or not to weight normalize the last layer of the head. 59 | Not normalizing leads to better performance but can make the training unstable. 60 | In our experiments, we typically set this paramater to False with vit_small and True with vit_base.""") 61 | parser.add_argument('--momentum_teacher', default=0.996, type=float, help="""Base EMA 62 | parameter for teacher update. The value is increased to 1 during training with cosine schedule. 63 | We recommend setting a higher value with small batches: for example use 0.9995 with batch size of 256.""") 64 | parser.add_argument('--norm_in_head', default=None, 65 | help="Whether to use batch normalizations in projection head (Default: None)") 66 | parser.add_argument('--act_in_head', default='gelu', 67 | help="Whether to use batch normalizations in projection head (Default: gelu)") 68 | parser.add_argument('--use_masked_im_modeling', default=True, type=utils.bool_flag, 69 | help="Whether to use masked image modeling (mim) in backbone (Default: True)") 70 | parser.add_argument('--pred_ratio', default=0.3, type=float, nargs='+', help="""Ratio of partial prediction. 71 | If a list of ratio is specified, one of them will be randomly choosed for each patch.""") 72 | parser.add_argument('--pred_ratio_var', default=0, type=float, nargs='+', help="""Variance of partial prediction 73 | ratio. Length should be indentical to the length of pred_ratio. 0 for disabling. """) 74 | parser.add_argument('--pred_shape', default='block', type=str, help="""Shape of partial prediction.""") 75 | parser.add_argument('--pred_start_epoch', default=0, type=int, help="""Start epoch to perform masked 76 | image prediction. We typically set this to 50 for swin transformer. (Default: 0)""") 77 | parser.add_argument('--lambda1', default=1.0, type=float, help="""loss weight for dino 78 | loss over [CLS] tokens (Default: 1.0)""") 79 | parser.add_argument('--lambda2', default=1.0, type=float, help="""loss weight for beit 80 | loss over masked patch tokens (Default: 1.0)""") 81 | 82 | # Temperature teacher parameters 83 | parser.add_argument('--warmup_teacher_temp', default=0.04, type=float, 84 | help="""Initial value for the teacher temperature: 0.04 works well in most cases. 85 | Try decreasing it if the training loss does not decrease.""") 86 | parser.add_argument('--teacher_temp', default=0.04, type=float, help="""Final value (after linear warmup) 87 | of the teacher temperature. For most experiments, anything above 0.07 is unstable. We recommend 88 | starting with the default value of 0.04 and increase this slightly if needed.""") 89 | parser.add_argument('--warmup_teacher_patch_temp', default=0.04, type=float, help="""See 90 | `--warmup_teacher_temp`""") 91 | parser.add_argument('--teacher_patch_temp', default=0.07, type=float, help=""""See 92 | `--teacher_temp`""") 93 | parser.add_argument('--warmup_teacher_temp_epochs', default=30, type=int, 94 | help='Number of warmup epochs for the teacher temperature (Default: 30).') 95 | 96 | # Training/Optimization parameters 97 | parser.add_argument('--use_fp16', type=utils.bool_flag, default=True, help="""Whether or not 98 | to use half precision for training. Improves training time and memory requirements, 99 | but can provoke instability and slight decay of performance. We recommend disabling 100 | mixed precision if the loss is unstable, if reducing the patch size or if training with bigger ViTs.""") 101 | parser.add_argument('--weight_decay', type=float, default=0.04, help="""Initial value of the 102 | weight decay. With ViT, a smaller value at the beginning of training works well.""") 103 | parser.add_argument('--weight_decay_end', type=float, default=0.4, help="""Final value of the 104 | weight decay. We use a cosine schedule for WD and using a larger decay by 105 | the end of training improves performance for ViTs.""") 106 | parser.add_argument('--clip_grad', type=float, default=3.0, help="""Maximal parameter 107 | gradient norm if using gradient clipping. Clipping with norm .3 ~ 1.0 can 108 | help optimization for larger ViT architectures. 0 for disabling.""") 109 | parser.add_argument('--batch_size_per_gpu', default=128, type=int, 110 | help='Per-GPU batch-size : number of distinct images loaded on one GPU.') 111 | parser.add_argument('--epochs', default=100, type=int, help='Number of epochs of training.') 112 | parser.add_argument('--freeze_last_layer', default=1, type=int, help="""Number of epochs 113 | during which we keep the output layer fixed. Typically doing so during 114 | the first epoch helps training. Try increasing this value if the loss does not decrease.""") 115 | parser.add_argument("--lr", default=0.0005, type=float, help="""Learning rate at the end of 116 | linear warmup (highest LR used during training). The learning rate is linearly scaled 117 | with the batch size, and specified here for a reference batch size of 256.""") 118 | parser.add_argument("--warmup_epochs", default=10, type=int, 119 | help="Number of epochs for the linear learning-rate warm up.") 120 | parser.add_argument('--min_lr', type=float, default=1e-6, help="""Target LR at the 121 | end of optimization. We use a cosine LR schedule with linear warmup.""") 122 | parser.add_argument('--optimizer', default='adamw', type=str, 123 | choices=['adamw', 'sgd', 'lars'], help="""Type of optimizer. We recommend using adamw with ViTs.""") 124 | parser.add_argument('--load_from', default=None, help="""Path to load checkpoints to resume training.""") 125 | parser.add_argument('--drop_path', type=float, default=0.1, help="""Drop path rate for student network.""") 126 | parser.add_argument('--accum_iter', default=1, type=int, 127 | help='Accumulate gradient iterations (for increasing the effective batch size under memory constraints)') 128 | 129 | # Multi-crop parameters 130 | parser.add_argument('--global_crops_number', type=int, default=2, help="""Number of global 131 | views to generate. Default is to use two global crops. """) 132 | parser.add_argument('--global_crops_scale', type=float, nargs='+', default=(0.14, 1.), 133 | help="""Scale range of the cropped image before resizing, relatively to the origin image. 134 | Used for large global view cropping. When disabling multi-crop (--local_crops_number 0), we 135 | recommand using a wider range of scale ("--global_crops_scale 0.14 1." for example)""") 136 | parser.add_argument('--local_crops_number', type=int, default=0, help="""Number of small 137 | local views to generate. Set this parameter to 0 to disable multi-crop training. 138 | When disabling multi-crop we recommend to use "--global_crops_scale 0.14 1." """) 139 | parser.add_argument('--local_crops_scale', type=float, nargs='+', default=(0.05, 0.4), 140 | help="""Scale range of the cropped image before resizing, relatively to the origin image. 141 | Used for small local view cropping of multi-crop.""") 142 | 143 | # Misc 144 | parser.add_argument('--data_path', default='/path/to/imagenet/train/', type=str, 145 | help='Please specify path to the ImageNet training data.') 146 | parser.add_argument('--output_dir', default=".", type=str, help='Path to save logs and checkpoints.') 147 | parser.add_argument('--saveckp_freq', default=40, type=int, help='Save checkpoint every x epochs.') 148 | parser.add_argument('--seed', default=0, type=int, help='Random seed.') 149 | parser.add_argument('--num_workers', default=10, type=int, help='Number of data loading workers per GPU.') 150 | parser.add_argument("--dist_url", default="env://", type=str, help="""url used to set up 151 | distributed training; see https://pytorch.org/docs/stable/distributed.html""") 152 | parser.add_argument("--local_rank", default=0, type=int, help="Please ignore and do not set this argument.") 153 | return parser 154 | 155 | 156 | def train_hssl(args): 157 | utils.init_distributed_mode(args) 158 | utils.fix_random_seeds(args.seed) 159 | print("git:\n {}\n".format(utils.get_sha())) 160 | print("\n".join("%s: %s" % (k, str(v)) for k, v in sorted(dict(vars(args)).items()))) 161 | cudnn.benchmark = True 162 | 163 | # ============ preparing data ... ============ 164 | transform = DataAugmentationHSSL( 165 | args.global_crops_scale, 166 | args.local_crops_scale, 167 | args.global_crops_number, 168 | args.local_crops_number, 169 | ) 170 | pred_size = args.patch_size * 8 if 'swin' in args.arch else args.patch_size 171 | dataset = ImageFolderMask( 172 | args.data_path, 173 | transform=transform, 174 | patch_size=pred_size, 175 | pred_ratio=args.pred_ratio, 176 | pred_ratio_var=args.pred_ratio_var, 177 | pred_aspect_ratio=(0.3, 1/0.3), 178 | pred_shape=args.pred_shape, 179 | pred_start_epoch=args.pred_start_epoch) 180 | sampler = torch.utils.data.DistributedSampler(dataset, shuffle=True) 181 | data_loader = torch.utils.data.DataLoader( 182 | dataset, 183 | sampler=sampler, 184 | batch_size=args.batch_size_per_gpu, 185 | num_workers=args.num_workers, 186 | pin_memory=True, 187 | drop_last=True 188 | ) 189 | print(f"Data loaded: there are {len(dataset)} images.") 190 | 191 | # ============ building student and teacher networks ... ============ 192 | # we changed the name DeiT-S for ViT-S to avoid confusions 193 | args.arch = args.arch.replace("deit", "vit") 194 | # if the network is a vision transformer (i.e. vit_tiny, vit_small, vit_base, vit_large) 195 | if args.arch in vision_transformer.__dict__.keys(): 196 | student = vision_transformer.__dict__[args.arch]( 197 | patch_size=args.patch_size, 198 | drop_path_rate=args.drop_path, 199 | return_all_tokens=True, 200 | masked_im_modeling=args.use_masked_im_modeling, 201 | auxiliary_depth=args.auxiliary_depth, 202 | ) 203 | teacher = vision_transformer.__dict__[args.arch]( 204 | patch_size=args.patch_size, 205 | return_all_tokens=True, 206 | auxiliary_depth=args.auxiliary_depth, 207 | ) 208 | embed_dim = student.embed_dim 209 | else: 210 | print(f"Unknow architecture: {args.arch}") 211 | 212 | # multi-crop wrapper handles forward with inputs of different resolutions 213 | student = MultiCropWrapper(student, HSSLHead( 214 | embed_dim, 215 | args.out_dim, 216 | patch_out_dim=args.patch_out_dim, 217 | norm=args.norm_in_head, 218 | act=args.act_in_head, 219 | norm_last_layer=args.norm_last_layer, 220 | shared_head=args.shared_head, 221 | )) 222 | teacher = MultiCropWrapper( 223 | teacher, 224 | HSSLHead( 225 | embed_dim, 226 | args.out_dim, 227 | patch_out_dim=args.patch_out_dim, 228 | norm=args.norm_in_head, 229 | act=args.act_in_head, 230 | shared_head=args.shared_head_teacher, 231 | ), 232 | ) 233 | for i, (n, p) in enumerate(student.named_parameters()): 234 | print(i, n) 235 | # move networks to gpu 236 | student, teacher = student.cuda(), teacher.cuda() 237 | # synchronize batch norms (if any) 238 | if utils.has_batchnorms(student): 239 | student = nn.SyncBatchNorm.convert_sync_batchnorm(student) 240 | teacher = nn.SyncBatchNorm.convert_sync_batchnorm(teacher) 241 | 242 | # we need DDP wrapper to have synchro batch norms working... 243 | teacher = nn.parallel.DistributedDataParallel(teacher, device_ids=[args.gpu], broadcast_buffers=False) if \ 244 | 'swin' in args.arch else nn.parallel.DistributedDataParallel(teacher, device_ids=[args.gpu]) 245 | teacher_without_ddp = teacher.module 246 | else: 247 | # teacher_without_ddp and teacher are the same thing 248 | teacher_without_ddp = teacher 249 | student = nn.parallel.DistributedDataParallel(student, device_ids=[args.gpu], broadcast_buffers=False) if \ 250 | 'swin' in args.arch else nn.parallel.DistributedDataParallel(student, device_ids=[args.gpu]) 251 | # teacher and student start with the same weights 252 | teacher_without_ddp.load_state_dict(student.module.state_dict(), strict=False) 253 | # there is no backpropagation through the teacher, so no need for gradients 254 | for p in teacher.parameters(): 255 | p.requires_grad = False 256 | print(f"Student and Teacher are built: they are both {args.arch} network.") 257 | 258 | # ============ preparing loss ... ============ 259 | same_dim = args.shared_head or args.shared_head_teacher 260 | pretrain_loss = PretrainLoss( 261 | args.out_dim, 262 | args.out_dim if same_dim else args.patch_out_dim, 263 | args.global_crops_number, 264 | args.local_crops_number, 265 | args.warmup_teacher_temp, 266 | args.teacher_temp, 267 | args.warmup_teacher_patch_temp, 268 | args.teacher_patch_temp, 269 | args.warmup_teacher_temp_epochs, 270 | args.epochs, 271 | lambda1=args.lambda1, 272 | lambda2=args.lambda2, 273 | mim_start_epoch=args.pred_start_epoch, 274 | accum_iter=args.accum_iter 275 | ).cuda() 276 | 277 | if utils.is_main_process(): # Tensorboard configuration 278 | local_runs = os.path.join(args.output_dir, 'tf_logs') 279 | writer = SummaryWriter(logdir=local_runs) 280 | 281 | # ============ preparing optimizer ... ============ 282 | params_groups = utils.get_params_groups(student) 283 | if args.optimizer == "adamw": 284 | optimizer = torch.optim.AdamW(params_groups) # to use with ViTs 285 | elif args.optimizer == "sgd": 286 | optimizer = torch.optim.SGD(params_groups, lr=0, momentum=0.9) # lr is set by scheduler 287 | elif args.optimizer == "lars": 288 | optimizer = utils.LARS(params_groups) # to use with convnet and large batches 289 | # for mixed precision training 290 | fp16_scaler = None 291 | if args.use_fp16: 292 | fp16_scaler = torch.cuda.amp.GradScaler() 293 | 294 | # ============ init schedulers ... ============ 295 | eff_batch_size = args.batch_size_per_gpu * args.accum_iter * utils.get_world_size() 296 | print("Effective batch size: %d" % eff_batch_size) 297 | print("Base lr: %.2e" % args.lr) 298 | print("Actual lr: %.2e" % (args.lr * (eff_batch_size) / 256.)) 299 | lr_schedule = utils.cosine_scheduler( 300 | args.lr * (eff_batch_size) / 256., # linear scaling rule 301 | args.min_lr, 302 | args.epochs, len(data_loader), 303 | warmup_epochs=args.warmup_epochs, 304 | ) 305 | wd_schedule = utils.cosine_scheduler( 306 | args.weight_decay, 307 | args.weight_decay_end, 308 | args.epochs, len(data_loader), 309 | ) 310 | # momentum parameter is increased to 1. during training with a cosine schedule 311 | momentum_schedule = utils.cosine_scheduler(args.momentum_teacher, 1, 312 | args.epochs, len(data_loader)) 313 | 314 | print("Loss, optimizer and schedulers ready.") 315 | 316 | # ============ optionally resume training ... ============ 317 | to_restore = {"epoch": 0} 318 | if args.load_from: 319 | utils.restart_from_checkpoint( 320 | os.path.join(args.output_dir, args.load_from), 321 | run_variables=to_restore, 322 | student=student, 323 | teacher=teacher, 324 | optimizer=optimizer, 325 | fp16_scaler=fp16_scaler, 326 | pretrain_loss=pretrain_loss, 327 | ) 328 | start_epoch = to_restore["epoch"] 329 | 330 | start_time = time.time() 331 | print("Starting HSSL training!") 332 | for epoch in range(start_epoch, args.epochs): 333 | data_loader.sampler.set_epoch(epoch) 334 | data_loader.dataset.set_epoch(epoch) 335 | 336 | # ============ training one epoch of HSSL ... ============ 337 | train_stats = train_one_epoch(student, teacher, teacher_without_ddp, pretrain_loss, 338 | data_loader, optimizer, lr_schedule, wd_schedule, momentum_schedule, 339 | epoch, fp16_scaler, args) 340 | 341 | # ============ writing logs ... ============ 342 | save_dict = { 343 | 'student': student.state_dict(), 344 | 'teacher': teacher.state_dict(), 345 | 'optimizer': optimizer.state_dict(), 346 | 'epoch': epoch + 1, 347 | 'args': args, 348 | 'pretrain_loss': pretrain_loss.state_dict(), 349 | } 350 | if fp16_scaler is not None: 351 | save_dict['fp16_scaler'] = fp16_scaler.state_dict() 352 | utils.save_on_master(save_dict, os.path.join(args.output_dir, 'checkpoint.pth')) 353 | if args.saveckp_freq and (epoch % args.saveckp_freq == 0) and epoch: 354 | utils.save_on_master(save_dict, os.path.join(args.output_dir, f'checkpoint{epoch:04}.pth')) 355 | log_stats = {**{f'train_{k}': v for k, v in train_stats.items()}, 356 | 'epoch': epoch} 357 | if utils.is_main_process(): 358 | with (Path(args.output_dir) / "log.txt").open("a") as f: 359 | f.write(json.dumps(log_stats) + "\n") 360 | for k, v in train_stats.items(): 361 | writer.add_scalar(k, v, epoch) 362 | 363 | total_time = time.time() - start_time 364 | total_time_str = str(datetime.timedelta(seconds=int(total_time))) 365 | print('Training time {}'.format(total_time_str)) 366 | 367 | 368 | def train_one_epoch(student, teacher, teacher_without_ddp, pretrain_loss, data_loader, 369 | optimizer, lr_schedule, wd_schedule, momentum_schedule,epoch, 370 | fp16_scaler, args): 371 | metric_logger = utils.MetricLogger(delimiter=" ") 372 | header = 'Epoch: [{}/{}]'.format(epoch, args.epochs) 373 | 374 | accum_iter = args.accum_iter 375 | optimizer.zero_grad() 376 | 377 | # common params 378 | names_q, params_q, names_k, params_k = [], [], [], [] 379 | for name_q, param_q in student.module.named_parameters(): 380 | names_q.append(name_q) 381 | params_q.append(param_q) 382 | for name_k, param_k in teacher_without_ddp.named_parameters(): 383 | names_k.append(name_k) 384 | params_k.append(param_k) 385 | names_common = list(set(names_q) & set(names_k)) 386 | params_q = [param_q for name_q, param_q in zip(names_q, params_q) if name_q in names_common] 387 | params_k = [param_k for name_k, param_k in zip(names_k, params_k) if name_k in names_common] 388 | 389 | pred_labels, real_labels = [], [] 390 | for it_current_epoch, (images, labels, masks) in enumerate(metric_logger.log_every(data_loader, 10, header)): 391 | # update weight decay and learning rate according to their schedule 392 | it = len(data_loader) * epoch + it_current_epoch # global training iteration 393 | if it_current_epoch % accum_iter == 0: 394 | for i, param_group in enumerate(optimizer.param_groups): 395 | param_group["lr"] = lr_schedule[it] 396 | if i == 0: # only the first group is regularized 397 | param_group["weight_decay"] = wd_schedule[it] 398 | 399 | # move images to gpu 400 | images = [im.cuda(non_blocking=True) for im in images] 401 | masks = [msk.cuda(non_blocking=True) for msk in masks] 402 | 403 | with torch.cuda.amp.autocast(fp16_scaler is not None): 404 | # get global views 405 | teacher_output_cls1, teacher_output_patch1, teacher_output_cls2, teacher_output_patch2 = teacher(images[:args.global_crops_number]) 406 | student_output_cls1, student_output_patch1, student_output_cls2, student_output_patch2 = student(images[:args.global_crops_number], mask=masks[:args.global_crops_number]) 407 | 408 | # get local views 409 | student.module.backbone.masked_im_modeling = False 410 | if len(images) > args.global_crops_number: 411 | # assert False 412 | student_local_cls1, _, student_local_cls2, _ = student(images[args.global_crops_number:]) 413 | else: 414 | student_local_cls1 = None 415 | student_local_cls2 = None 416 | student.module.backbone.masked_im_modeling = args.use_masked_im_modeling 417 | 418 | all_loss = pretrain_loss( 419 | (student_output_cls1, student_output_patch1), 420 | (student_output_cls2, None), 421 | (teacher_output_cls2, teacher_output_patch1), 422 | (student_local_cls1, student_local_cls2), 423 | masks, epoch, it_current_epoch) 424 | loss = all_loss.pop('loss') 425 | 426 | if not math.isfinite(loss.item()): 427 | print("Loss is {}, stopping training".format(loss.item()), force=True) 428 | sys.exit(1) 429 | 430 | loss /= accum_iter 431 | 432 | # log statistics 433 | probs1 = teacher_output_cls1.chunk(args.global_crops_number) 434 | probs2 = student_output_cls1.chunk(args.global_crops_number) 435 | pred1 = utils.concat_all_gather(probs1[0].max(dim=1)[1]) 436 | pred2 = utils.concat_all_gather(probs2[1].max(dim=1)[1]) 437 | acc = (pred1 == pred2).sum() / pred1.size(0) 438 | pred_labels.append(pred1) 439 | real_labels.append(utils.concat_all_gather(labels.to(pred1.device))) 440 | 441 | # student update 442 | if fp16_scaler is None: 443 | loss.backward() 444 | else: 445 | fp16_scaler.scale(loss).backward() 446 | if (it_current_epoch + 1) % accum_iter == 0: 447 | param_norms = None 448 | if fp16_scaler is None: 449 | # loss.backward() 450 | if args.clip_grad: 451 | param_norms = utils.clip_gradients(student, args.clip_grad) 452 | utils.cancel_gradients_last_layer(epoch, student, 453 | args.freeze_last_layer) 454 | optimizer.step() 455 | else: 456 | # fp16_scaler.scale(loss).backward() 457 | if args.clip_grad: 458 | fp16_scaler.unscale_(optimizer) # unscale the gradients of optimizer's assigned params in-place 459 | param_norms = utils.clip_gradients(student, args.clip_grad) 460 | utils.cancel_gradients_last_layer(epoch, student, 461 | args.freeze_last_layer) 462 | fp16_scaler.step(optimizer) 463 | fp16_scaler.update() 464 | param_norms = None 465 | if (it_current_epoch + 1) % accum_iter == 0: 466 | optimizer.zero_grad() 467 | 468 | # EMA update for the teacher 469 | if (it_current_epoch + 1) % accum_iter == 0: 470 | with torch.no_grad(): 471 | m = momentum_schedule[it] # momentum parameter 472 | for param_q, param_k in zip(params_q, params_k): 473 | param_k.data.mul_(m).add_((1 - m) * param_q.detach().data) 474 | 475 | # logging 476 | torch.cuda.synchronize() 477 | metric_logger.update(loss=loss.item()) 478 | for key, value in all_loss.items(): 479 | metric_logger.update(**{key: value.item() if isinstance(value, torch.Tensor) else value}) 480 | metric_logger.update(lr=optimizer.param_groups[0]["lr"]) 481 | metric_logger.update(wd=optimizer.param_groups[0]["weight_decay"]) 482 | metric_logger.update(acc=acc) 483 | 484 | pred_labels = torch.cat(pred_labels).cpu().detach().numpy() 485 | real_labels = torch.cat(real_labels).cpu().detach().numpy() 486 | nmi, ari, fscore, adjacc = eval_pred(real_labels, pred_labels, calc_acc=False) 487 | # gather the stats from all processes 488 | metric_logger.synchronize_between_processes() 489 | print("NMI: {}, ARI: {}, F: {}, ACC: {}".format(nmi, ari, fscore, adjacc)) 490 | print("Averaged stats:", metric_logger) 491 | return_dict = {k: meter.global_avg for k, meter in metric_logger.meters.items()} 492 | return_dict.update({"nmi": nmi, "ari": ari, "fscore": fscore, "adjacc": adjacc}) 493 | return return_dict 494 | 495 | 496 | # Modified from iBOT: https://github.com/bytedance/ibot 497 | class PretrainLoss(nn.Module): 498 | def __init__(self, out_dim, patch_out_dim, ngcrops, nlcrops, warmup_teacher_temp, 499 | teacher_temp, warmup_teacher_temp2, teacher_temp2, 500 | warmup_teacher_temp_epochs, nepochs, student_temp=0.1, 501 | center_momentum=0.9, center_momentum2=0.9, 502 | lambda1=1.0, lambda2=1.0, mim_start_epoch=0, accum_iter=1): 503 | super().__init__() 504 | self.student_temp = student_temp 505 | self.center_momentum = center_momentum 506 | self.center_momentum2 = center_momentum2 507 | self.ngcrops = ngcrops 508 | self.nlcrops = nlcrops 509 | self.ncrops = ngcrops + nlcrops 510 | self.register_buffer("center", torch.zeros(1, out_dim)) 511 | self.register_buffer("center2", torch.zeros(1, 1, patch_out_dim)) 512 | self.lambda1 = lambda1 513 | self.lambda2 = lambda2 514 | self.accum_iter = accum_iter 515 | 516 | self.register_buffer("center_accum", torch.zeros(1, out_dim)) 517 | self.register_buffer("center2_accum", torch.zeros(1, 1, patch_out_dim)) 518 | 519 | # we apply a warm up for the teacher temperature because 520 | # a too high temperature makes the training instable at the beginning 521 | self.teacher_temp_schedule = np.concatenate(( 522 | np.linspace(warmup_teacher_temp, 523 | teacher_temp, warmup_teacher_temp_epochs), 524 | np.ones(nepochs - warmup_teacher_temp_epochs) * teacher_temp 525 | )) 526 | self.teacher_temp2_schedule = np.concatenate(( 527 | np.linspace(warmup_teacher_temp2, 528 | teacher_temp2, warmup_teacher_temp_epochs), 529 | np.ones(nepochs - warmup_teacher_temp_epochs) * teacher_temp2 530 | )) if mim_start_epoch == 0 else np.concatenate(( 531 | np.ones(mim_start_epoch) * warmup_teacher_temp2, 532 | np.linspace(warmup_teacher_temp2, 533 | teacher_temp2, warmup_teacher_temp_epochs), 534 | np.ones(nepochs - warmup_teacher_temp_epochs - mim_start_epoch) * teacher_temp2 535 | )) 536 | 537 | def forward(self, student_output1, student_output2, teacher_output, student_local_cls, student_mask, epoch, it): 538 | """ 539 | Cross-entropy between softmax outputs of the teacher and student networks. 540 | """ 541 | student_cls1, student_patch1 = student_output1 542 | student_cls2, student_patch2 = student_output2 543 | teacher_cls, teacher_patch = teacher_output 544 | student_local_cls1, student_local_cls2 = student_local_cls 545 | 546 | if student_local_cls1 is not None: 547 | student_cls1 = torch.cat([student_cls1, student_local_cls1]) 548 | if student_local_cls2 is not None: 549 | student_cls2 = torch.cat([student_cls2, student_local_cls2]) 550 | 551 | # [CLS] and patch for global patches 552 | if student_cls1 is not None: 553 | student_cls1 = student_cls1 / self.student_temp 554 | student_cls1_c = student_cls1.chunk(self.ncrops) 555 | else: 556 | student_cls1 = student_cls1_c = None 557 | 558 | if student_cls2 is not None: 559 | student_cls2 = student_cls2 / self.student_temp 560 | student_cls2_c = student_cls2.chunk(self.ncrops) 561 | else: 562 | student_cls2 = student_cls2_c = None 563 | 564 | if student_patch1 is not None: 565 | student_patch1 = student_patch1 / self.student_temp 566 | student_patch1_c = student_patch1.chunk(self.ngcrops) 567 | else: 568 | student_patch1 = student_patch1_c = None 569 | 570 | if student_patch2 is not None: 571 | student_patch2 = student_patch2 / self.student_temp 572 | student_patch2_c = student_patch2.chunk(self.ngcrops) 573 | else: 574 | student_patch2 = student_patch2_c = None 575 | 576 | # teacher centering and sharpening 577 | temp = self.teacher_temp_schedule[epoch] 578 | temp2 = self.teacher_temp2_schedule[epoch] 579 | teacher_cls_c = F.softmax((teacher_cls - self.center) / temp, dim=-1) 580 | teacher_cls_c = teacher_cls_c.detach().chunk(self.ngcrops) 581 | teacher_patch_c = F.softmax((teacher_patch - self.center2) / temp2, dim=-1) 582 | teacher_patch_c = teacher_patch_c.detach().chunk(self.ngcrops) 583 | 584 | total_loss1_1, n_loss_terms1_1 = 0, 0 585 | total_loss1_2, n_loss_terms1_2 = 0, 0 586 | total_loss2_1, n_loss_terms2_1 = 0, 0 587 | total_loss2_2, n_loss_terms2_2 = 0, 0 588 | for q in range(len(teacher_cls_c)): 589 | for v in range(self.ncrops): 590 | if v == q: 591 | if student_patch1_c is not None: 592 | loss2 = torch.sum(-teacher_patch_c[q] * F.log_softmax(student_patch1_c[v], dim=-1), dim=-1) 593 | mask = student_mask[v].flatten(-2, -1) 594 | loss2 = torch.sum(loss2 * mask.float(), dim=-1) / mask.sum(dim=-1).clamp(min=1.0) 595 | total_loss1_2 += loss2.mean() 596 | n_loss_terms1_2 += 1 597 | else: 598 | if student_cls1_c is not None: 599 | loss1 = torch.sum(-teacher_cls_c[q] * F.log_softmax(student_cls1_c[v], dim=-1), dim=-1) 600 | total_loss1_1 += loss1.mean() 601 | n_loss_terms1_1 += 1 602 | 603 | for v in range(self.ncrops): 604 | if v == q: 605 | if student_patch2_c is not None: 606 | loss2 = torch.sum(-teacher_patch_c[q] * F.log_softmax(student_patch2_c[v], dim=-1), dim=-1) 607 | mask = student_mask[v].flatten(-2, -1) 608 | loss2 = torch.sum(loss2 * mask.float(), dim=-1) / mask.sum(dim=-1).clamp(min=1.0) 609 | total_loss2_2 += loss2.mean() 610 | n_loss_terms2_2 += 1 611 | else: 612 | if student_cls2_c is not None: 613 | loss1 = torch.sum(-teacher_cls_c[q] * F.log_softmax(student_cls2_c[v], dim=-1), dim=-1) 614 | total_loss2_1 += loss1.mean() 615 | n_loss_terms2_1 += 1 616 | 617 | total_loss1_1 = total_loss1_1 / max(n_loss_terms1_1, 1) * self.lambda1 618 | total_loss1_2 = total_loss1_2 / max(n_loss_terms1_2, 1) * self.lambda2 619 | total_loss2_1 = total_loss2_1 / max(n_loss_terms2_1, 1) * self.lambda1 620 | total_loss2_2 = total_loss2_2 / max(n_loss_terms2_2, 1) * self.lambda2 621 | factor_loss_terms_patch = max(n_loss_terms1_2, n_loss_terms2_2) * 2 / (n_loss_terms1_2 + n_loss_terms2_2) 622 | factor_loss_terms_cls = max(n_loss_terms1_1, n_loss_terms2_1) * 2 / (n_loss_terms1_1 + n_loss_terms2_1) 623 | total_loss = dict( 624 | cls1=total_loss1_1, patch1=total_loss1_2, 625 | cls2=total_loss2_1, patch2=total_loss2_2, 626 | loss=( 627 | (total_loss1_1 + total_loss2_1) * factor_loss_terms_cls + \ 628 | (total_loss1_2 + total_loss2_2) * factor_loss_terms_patch) * 0.5) 629 | self.update_center_accum(teacher_cls, teacher_patch) 630 | if (it + 1) % self.accum_iter == 0: 631 | self.update_center(teacher_cls, teacher_patch) 632 | 633 | return total_loss 634 | 635 | @torch.no_grad() 636 | def update_center(self, teacher_cls, teacher_patch): 637 | """ 638 | Update center used for teacher output. 639 | """ 640 | # cls_center = torch.sum(teacher_cls, dim=0, keepdim=True) 641 | # dist.all_reduce(cls_center) 642 | cls_center = self.center_accum 643 | cls_center = cls_center / (len(teacher_cls) * dist.get_world_size() * args.accum_iter) 644 | self.center = self.center * self.center_momentum + cls_center * (1 - self.center_momentum) 645 | 646 | # patch_center = torch.sum(teacher_patch.mean(1), dim=0, keepdim=True) 647 | # dist.all_reduce(patch_center) 648 | patch_center = self.center2_accum 649 | patch_center = patch_center / (len(teacher_patch) * dist.get_world_size() * args.accum_iter) 650 | self.center2 = self.center2 * self.center_momentum2 + patch_center * (1 - self.center_momentum2) 651 | 652 | self.center_accum.fill_(0) 653 | self.center2_accum.fill_(0) 654 | 655 | @torch.no_grad() 656 | def update_center_accum(self, teacher_cls, teacher_patch): 657 | """ 658 | Update center used for teacher output. 659 | """ 660 | cls_center = torch.sum(teacher_cls, dim=0, keepdim=True) 661 | dist.all_reduce(cls_center) 662 | self.center_accum = self.center_accum + cls_center 663 | 664 | patch_center = torch.sum(teacher_patch.mean(1), dim=0, keepdim=True) 665 | dist.all_reduce(patch_center) 666 | self.center2_accum = self.center2_accum + patch_center 667 | 668 | 669 | # Copied from iBOT: https://github.com/bytedance/ibot 670 | class DataAugmentationHSSL(object): 671 | def __init__(self, global_crops_scale, local_crops_scale, global_crops_number, local_crops_number): 672 | flip_and_color_jitter = transforms.Compose([ 673 | transforms.RandomHorizontalFlip(p=0.5), 674 | transforms.RandomApply( 675 | [transforms.ColorJitter(brightness=0.4, contrast=0.4, saturation=0.2, hue=0.1)], 676 | p=0.8 677 | ), 678 | transforms.RandomGrayscale(p=0.2), 679 | ]) 680 | normalize = transforms.Compose([ 681 | transforms.ToTensor(), 682 | transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), 683 | ]) 684 | 685 | self.global_crops_number = global_crops_number 686 | # transformation for the first global crop 687 | self.global_transfo1 = transforms.Compose([ 688 | transforms.RandomResizedCrop(224, scale=global_crops_scale, interpolation=Image.BICUBIC), 689 | flip_and_color_jitter, 690 | utils.GaussianBlur(1.0), 691 | normalize, 692 | ]) 693 | # transformation for the rest of global crops 694 | self.global_transfo2 = transforms.Compose([ 695 | transforms.RandomResizedCrop(224, scale=global_crops_scale, interpolation=Image.BICUBIC), 696 | flip_and_color_jitter, 697 | utils.GaussianBlur(0.1), 698 | utils.Solarization(0.2), 699 | normalize, 700 | ]) 701 | # transformation for the local crops 702 | self.local_crops_number = local_crops_number 703 | self.local_transfo = transforms.Compose([ 704 | transforms.RandomResizedCrop(96, scale=local_crops_scale, interpolation=Image.BICUBIC), 705 | flip_and_color_jitter, 706 | utils.GaussianBlur(p=0.5), 707 | normalize, 708 | ]) 709 | 710 | def __call__(self, image): 711 | crops = [] 712 | crops.append(self.global_transfo1(image)) 713 | for _ in range(self.global_crops_number - 1): 714 | crops.append(self.global_transfo2(image)) 715 | for _ in range(self.local_crops_number): 716 | crops.append(self.local_transfo(image)) 717 | return crops 718 | 719 | 720 | if __name__ == '__main__': 721 | parser = argparse.ArgumentParser('HSSL', parents=[get_args_parser()]) 722 | args = parser.parse_args() 723 | Path(args.output_dir).mkdir(parents=True, exist_ok=True) 724 | train_hssl(args) 725 | --------------------------------------------------------------------------------