ZhengPeng7 commited on
Commit
4c3c428
·
1 Parent(s): f224c4d

Initial uploading of BiRefNet_512x512.

Browse files
Files changed (7) hide show
  1. BiRefNet_config.py +11 -0
  2. README.md +86 -3
  3. birefnet.py +2248 -0
  4. config.json +20 -0
  5. handler.py +138 -0
  6. model.safetensors +3 -0
  7. requirements.txt +16 -0
BiRefNet_config.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+ class BiRefNetConfig(PretrainedConfig):
4
+ model_type = "SegformerForSemanticSegmentation"
5
+ def __init__(
6
+ self,
7
+ bb_pretrained=False,
8
+ **kwargs
9
+ ):
10
+ self.bb_pretrained = bb_pretrained
11
+ super().__init__(**kwargs)
README.md CHANGED
@@ -1,3 +1,86 @@
1
- ---
2
- license: mit
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: birefnet
3
+ tags:
4
+ - background-removal
5
+ - mask-generation
6
+ - Dichotomous Image Segmentation
7
+ - Camouflaged Object Detection
8
+ - Salient Object Detection
9
+ - pytorch_model_hub_mixin
10
+ - model_hub_mixin
11
+ repo_url: https://github.com/ZhengPeng7/BiRefNet
12
+ pipeline_tag: image-segmentation
13
+ license: mit
14
+ ---
15
+
16
+ > This BiRefNet was trained with images in `512x512` for higher resolution inference.
17
+ ### Performance:
18
+ > All tested in FP16 mode.
19
+
20
+ | Dataset | Method | Resolution | maxFm | wFmeasure | MAE | Smeasure | meanEm | HCE | maxEm | meanFm | adpEm | adpFm | mBA | maxBIoU | meanBIoU |
21
+ | :------: | :------: | :------: | :------: | :------: | :------: | :------: | :------: | :------: | :------: | :------: | :------: | :------: | :------: | :------: | :------: |
22
+ | DIS-VD | [**BiRefNet_512x512**-epoch_216](https://huggingface.co/ZhengPeng7/BiRefNet_512x512) | 512x512 | .879 & .840 & .040 & .888 & .931 & 1526 & .941 & .864 & .938 & .857 & .732 & .747 & .726 |
23
+ | DIS-VD | [**BiRefNet**-general-epoch_244](https://huggingface.co/ZhengPeng7/BiRefNet) | 512x512 | .834 & .789 & .050 & .860 & .891 & 1589 & .905 & .817 & .902 & .816 & .708 & .698 & .669 |
24
+ | DIS-VD | [**BiRefNet_HR**-general-epoch_130](https://huggingface.co/ZhengPeng7/BiRefNet_HR) | 512x512 | .540 & .409 & .112 & .634 & .565 & 1647 & .682 & .428 & .690 & .576 & .585 & .384 & .309 |
25
+
26
+ <h1 align="center">Bilateral Reference for High-Resolution Dichotomous Image Segmentation</h1>
27
+
28
+ <div align='center'>
29
+ <a href='https://scholar.google.com/citations?user=TZRzWOsAAAAJ' target='_blank'><strong>Peng Zheng</strong></a><sup> 1,4,5,6</sup>,&thinsp;
30
+ <a href='https://scholar.google.com/citations?user=0uPb8MMAAAAJ' target='_blank'><strong>Dehong Gao</strong></a><sup> 2</sup>,&thinsp;
31
+ <a href='https://scholar.google.com/citations?user=kakwJ5QAAAAJ' target='_blank'><strong>Deng-Ping Fan</strong></a><sup> 1*</sup>,&thinsp;
32
+ <a href='https://scholar.google.com/citations?user=9cMQrVsAAAAJ' target='_blank'><strong>Li Liu</strong></a><sup> 3</sup>,&thinsp;
33
+ <a href='https://scholar.google.com/citations?user=qQP6WXIAAAAJ' target='_blank'><strong>Jorma Laaksonen</strong></a><sup> 4</sup>,&thinsp;
34
+ <a href='https://scholar.google.com/citations?user=pw_0Z_UAAAAJ' target='_blank'><strong>Wanli Ouyang</strong></a><sup> 5</sup>,&thinsp;
35
+ <a href='https://scholar.google.com/citations?user=stFCYOAAAAAJ' target='_blank'><strong>Nicu Sebe</strong></a><sup> 6</sup>
36
+ </div>
37
+
38
+ <div align='center'>
39
+ <sup>1 </sup>Nankai University&ensp; <sup>2 </sup>Northwestern Polytechnical University&ensp; <sup>3 </sup>National University of Defense Technology&ensp; <sup>4 </sup>Aalto University&ensp; <sup>5 </sup>Shanghai AI Laboratory&ensp; <sup>6 </sup>University of Trento&ensp;
40
+ </div>
41
+
42
+ <div align="center" style="display: flex; justify-content: center; flex-wrap: wrap;">
43
+ <a href='https://www.sciopen.com/article/pdf/10.26599/AIR.2024.9150038.pdf'><img src='https://img.shields.io/badge/Journal-Paper-red'></a>&ensp;
44
+ <a href='https://arxiv.org/pdf/2401.03407'><img src='https://img.shields.io/badge/arXiv-BiRefNet-red'></a>&ensp;
45
+ <a href='https://drive.google.com/file/d/1aBnJ_R9lbnC2dm8dqD0-pzP2Cu-U1Xpt/view?usp=drive_link'><img src='https://img.shields.io/badge/中文版-BiRefNet-red'></a>&ensp;
46
+ <a href='https://www.birefnet.top'><img src='https://img.shields.io/badge/Page-BiRefNet-red'></a>&ensp;
47
+ <a href='https://drive.google.com/drive/folders/1s2Xe0cjq-2ctnJBR24563yMSCOu4CcxM'><img src='https://img.shields.io/badge/Drive-Stuff-green'></a>&ensp;
48
+ <a href='LICENSE'><img src='https://img.shields.io/badge/License-MIT-yellow'></a>&ensp;
49
+ <a href='https://huggingface.co/spaces/ZhengPeng7/BiRefNet_demo'><img src='https://img.shields.io/badge/%F0%9F%A4%97%20HF%20Spaces-BiRefNet-blue'></a>&ensp;
50
+ <a href='https://huggingface.co/ZhengPeng7/BiRefNet'><img src='https://img.shields.io/badge/%F0%9F%A4%97%20HF%20Models-BiRefNet-blue'></a>&ensp;
51
+ <a href='https://colab.research.google.com/drive/14Dqg7oeBkFEtchaHLNpig2BcdkZEogba?usp=drive_link'><img src='https://img.shields.io/badge/Single_Image_Inference-F9AB00?style=for-the-badge&logo=googlecolab&color=525252'></a>&ensp;
52
+ <a href='https://colab.research.google.com/drive/1MaEiBfJ4xIaZZn0DqKrhydHB8X97hNXl#scrollTo=DJ4meUYjia6S'><img src='https://img.shields.io/badge/Inference_&_Evaluation-F9AB00?style=for-the-badge&logo=googlecolab&color=525252'></a>&ensp;
53
+ </div>
54
+
55
+
56
+ | *DIS-Sample_1* | *DIS-Sample_2* |
57
+ | :------------------------------: | :-------------------------------: |
58
+ | <img src="https://drive.google.com/thumbnail?id=1ItXaA26iYnE8XQ_GgNLy71MOWePoS2-g&sz=w400" /> | <img src="https://drive.google.com/thumbnail?id=1Z-esCujQF_uEa_YJjkibc3NUrW4aR_d4&sz=w400" /> |
59
+
60
+ This repo is the official implementation of "[**Bilateral Reference for High-Resolution Dichotomous Image Segmentation**](https://arxiv.org/pdf/2401.03407.pdf)" (___CAAI AIR 2024___).
61
+
62
+
63
+
64
+ **Check the main BiRefNet model repo for more info and how to use it:**
65
+ https://huggingface.co/ZhengPeng7/BiRefNet/blob/main/README.md
66
+
67
+ **Also check the GitHub repo of BiRefNet for all things you may want:**
68
+ https://github.com/ZhengPeng7/BiRefNet
69
+
70
+ ## Acknowledgement:
71
+
72
+ + Many thanks to @freepik for their generous support on GPU resources for training this model!
73
+
74
+
75
+ ## Citation
76
+
77
+ ```
78
+ @article{zheng2024birefnet,
79
+ title={Bilateral Reference for High-Resolution Dichotomous Image Segmentation},
80
+ author={Zheng, Peng and Gao, Dehong and Fan, Deng-Ping and Liu, Li and Laaksonen, Jorma and Ouyang, Wanli and Sebe, Nicu},
81
+ journal={CAAI Artificial Intelligence Research},
82
+ volume = {3},
83
+ pages = {9150038},
84
+ year={2024}
85
+ }
86
+ ```
birefnet.py ADDED
@@ -0,0 +1,2248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### config.py
2
+
3
+ import os
4
+ import math
5
+
6
+
7
+ class Config():
8
+ def __init__(self) -> None:
9
+ # PATH settings
10
+ self.sys_home_dir = os.path.expanduser('~') # Make up your file system as: SYS_HOME_DIR/codes/dis/BiRefNet, SYS_HOME_DIR/datasets/dis/xx, SYS_HOME_DIR/weights/xx
11
+
12
+ # TASK settings
13
+ self.task = ['DIS5K', 'COD', 'HRSOD', 'DIS5K+HRSOD+HRS10K', 'P3M-10k'][0]
14
+ self.training_set = {
15
+ 'DIS5K': ['DIS-TR', 'DIS-TR+DIS-TE1+DIS-TE2+DIS-TE3+DIS-TE4'][0],
16
+ 'COD': 'TR-COD10K+TR-CAMO',
17
+ 'HRSOD': ['TR-DUTS', 'TR-HRSOD', 'TR-UHRSD', 'TR-DUTS+TR-HRSOD', 'TR-DUTS+TR-UHRSD', 'TR-HRSOD+TR-UHRSD', 'TR-DUTS+TR-HRSOD+TR-UHRSD'][5],
18
+ 'DIS5K+HRSOD+HRS10K': 'DIS-TE1+DIS-TE2+DIS-TE3+DIS-TE4+DIS-TR+TE-HRS10K+TE-HRSOD+TE-UHRSD+TR-HRS10K+TR-HRSOD+TR-UHRSD', # leave DIS-VD for evaluation.
19
+ 'P3M-10k': 'TR-P3M-10k',
20
+ }[self.task]
21
+ self.prompt4loc = ['dense', 'sparse'][0]
22
+
23
+ # Faster-Training settings
24
+ self.load_all = True
25
+ self.compile = True # 1. Trigger CPU memory leak in some extend, which is an inherent problem of PyTorch.
26
+ # Machines with > 70GB CPU memory can run the whole training on DIS5K with default setting.
27
+ # 2. Higher PyTorch version may fix it: https://github.com/pytorch/pytorch/issues/119607.
28
+ # 3. But compile in Pytorch > 2.0.1 seems to bring no acceleration for training.
29
+ self.precisionHigh = True
30
+
31
+ # MODEL settings
32
+ self.ms_supervision = True
33
+ self.out_ref = self.ms_supervision and True
34
+ self.dec_ipt = True
35
+ self.dec_ipt_split = True
36
+ self.cxt_num = [0, 3][1] # multi-scale skip connections from encoder
37
+ self.mul_scl_ipt = ['', 'add', 'cat'][2]
38
+ self.dec_att = ['', 'ASPP', 'ASPPDeformable'][2]
39
+ self.squeeze_block = ['', 'BasicDecBlk_x1', 'ResBlk_x4', 'ASPP_x3', 'ASPPDeformable_x3'][1]
40
+ self.dec_blk = ['BasicDecBlk', 'ResBlk', 'HierarAttDecBlk'][0]
41
+
42
+ # TRAINING settings
43
+ self.batch_size = 4
44
+ self.IoU_finetune_last_epochs = [
45
+ 0,
46
+ {
47
+ 'DIS5K': -50,
48
+ 'COD': -20,
49
+ 'HRSOD': -20,
50
+ 'DIS5K+HRSOD+HRS10K': -20,
51
+ 'P3M-10k': -20,
52
+ }[self.task]
53
+ ][1] # choose 0 to skip
54
+ self.lr = (1e-4 if 'DIS5K' in self.task else 1e-5) * math.sqrt(self.batch_size / 4) # DIS needs high lr to converge faster. Adapt the lr linearly
55
+ self.size = 1024
56
+ self.num_workers = max(4, self.batch_size) # will be decrease to min(it, batch_size) at the initialization of the data_loader
57
+
58
+ # Backbone settings
59
+ self.bb = [
60
+ 'vgg16', 'vgg16bn', 'resnet50', # 0, 1, 2
61
+ 'swin_v1_t', 'swin_v1_s', # 3, 4
62
+ 'swin_v1_b', 'swin_v1_l', # 5-bs9, 6-bs4
63
+ 'pvt_v2_b0', 'pvt_v2_b1', # 7, 8
64
+ 'pvt_v2_b2', 'pvt_v2_b5', # 9-bs10, 10-bs5
65
+ ][6]
66
+ self.lateral_channels_in_collection = {
67
+ 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64],
68
+ 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64],
69
+ 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192],
70
+ 'swin_v1_t': [768, 384, 192, 96], 'swin_v1_s': [768, 384, 192, 96],
71
+ 'pvt_v2_b0': [256, 160, 64, 32], 'pvt_v2_b1': [512, 320, 128, 64],
72
+ }[self.bb]
73
+ if self.mul_scl_ipt == 'cat':
74
+ self.lateral_channels_in_collection = [channel * 2 for channel in self.lateral_channels_in_collection]
75
+ self.cxt = self.lateral_channels_in_collection[1:][::-1][-self.cxt_num:] if self.cxt_num else []
76
+
77
+ # MODEL settings - inactive
78
+ self.lat_blk = ['BasicLatBlk'][0]
79
+ self.dec_channels_inter = ['fixed', 'adap'][0]
80
+ self.refine = ['', 'itself', 'RefUNet', 'Refiner', 'RefinerPVTInChannels4'][0]
81
+ self.progressive_ref = self.refine and True
82
+ self.ender = self.progressive_ref and False
83
+ self.scale = self.progressive_ref and 2
84
+ self.auxiliary_classification = False # Only for DIS5K, where class labels are saved in `dataset.py`.
85
+ self.refine_iteration = 1
86
+ self.freeze_bb = False
87
+ self.model = [
88
+ 'BiRefNet',
89
+ ][0]
90
+ if self.dec_blk == 'HierarAttDecBlk':
91
+ self.batch_size = 2 ** [0, 1, 2, 3, 4][2]
92
+
93
+ # TRAINING settings - inactive
94
+ self.preproc_methods = ['flip', 'enhance', 'rotate', 'pepper', 'crop'][:4]
95
+ self.optimizer = ['Adam', 'AdamW'][1]
96
+ self.lr_decay_epochs = [1e5] # Set to negative N to decay the lr in the last N-th epoch.
97
+ self.lr_decay_rate = 0.5
98
+ # Loss
99
+ self.lambdas_pix_last = {
100
+ # not 0 means opening this loss
101
+ # original rate -- 1 : 30 : 1.5 : 0.2, bce x 30
102
+ 'bce': 30 * 1, # high performance
103
+ 'iou': 0.5 * 1, # 0 / 255
104
+ 'iou_patch': 0.5 * 0, # 0 / 255, win_size = (64, 64)
105
+ 'mse': 150 * 0, # can smooth the saliency map
106
+ 'triplet': 3 * 0,
107
+ 'reg': 100 * 0,
108
+ 'ssim': 10 * 1, # help contours,
109
+ 'cnt': 5 * 0, # help contours
110
+ 'structure': 5 * 0, # structure loss from codes of MVANet. A little improvement on DIS-TE[1,2,3], a bit more decrease on DIS-TE4.
111
+ }
112
+ self.lambdas_cls = {
113
+ 'ce': 5.0
114
+ }
115
+ # Adv
116
+ self.lambda_adv_g = 10. * 0 # turn to 0 to avoid adv training
117
+ self.lambda_adv_d = 3. * (self.lambda_adv_g > 0)
118
+
119
+ # PATH settings - inactive
120
+ self.data_root_dir = os.path.join(self.sys_home_dir, 'datasets/dis')
121
+ self.weights_root_dir = os.path.join(self.sys_home_dir, 'weights')
122
+ self.weights = {
123
+ 'pvt_v2_b2': os.path.join(self.weights_root_dir, 'pvt_v2_b2.pth'),
124
+ 'pvt_v2_b5': os.path.join(self.weights_root_dir, ['pvt_v2_b5.pth', 'pvt_v2_b5_22k.pth'][0]),
125
+ 'swin_v1_b': os.path.join(self.weights_root_dir, ['swin_base_patch4_window12_384_22kto1k.pth', 'swin_base_patch4_window12_384_22k.pth'][0]),
126
+ 'swin_v1_l': os.path.join(self.weights_root_dir, ['swin_large_patch4_window12_384_22kto1k.pth', 'swin_large_patch4_window12_384_22k.pth'][0]),
127
+ 'swin_v1_t': os.path.join(self.weights_root_dir, ['swin_tiny_patch4_window7_224_22kto1k_finetune.pth'][0]),
128
+ 'swin_v1_s': os.path.join(self.weights_root_dir, ['swin_small_patch4_window7_224_22kto1k_finetune.pth'][0]),
129
+ 'pvt_v2_b0': os.path.join(self.weights_root_dir, ['pvt_v2_b0.pth'][0]),
130
+ 'pvt_v2_b1': os.path.join(self.weights_root_dir, ['pvt_v2_b1.pth'][0]),
131
+ }
132
+
133
+ # Callbacks - inactive
134
+ self.verbose_eval = True
135
+ self.only_S_MAE = False
136
+ self.use_fp16 = False # Bugs. It may cause nan in training.
137
+ self.SDPA_enabled = False # Bugs. Slower and errors occur in multi-GPUs
138
+
139
+ # others
140
+ self.device = [0, 'cpu'][0] # .to(0) == .to('cuda:0')
141
+
142
+ self.batch_size_valid = 1
143
+ self.rand_seed = 7
144
+ # run_sh_file = [f for f in os.listdir('.') if 'train.sh' == f] + [os.path.join('..', f) for f in os.listdir('..') if 'train.sh' == f]
145
+ # with open(run_sh_file[0], 'r') as f:
146
+ # lines = f.readlines()
147
+ # self.save_last = int([l.strip() for l in lines if '"{}")'.format(self.task) in l and 'val_last=' in l][0].split('val_last=')[-1].split()[0])
148
+ # self.save_step = int([l.strip() for l in lines if '"{}")'.format(self.task) in l and 'step=' in l][0].split('step=')[-1].split()[0])
149
+ # self.val_step = [0, self.save_step][0]
150
+
151
+ def print_task(self) -> None:
152
+ # Return task for choosing settings in shell scripts.
153
+ print(self.task)
154
+
155
+
156
+
157
+ ### models/backbones/pvt_v2.py
158
+
159
+ import torch
160
+ import torch.nn as nn
161
+ from functools import partial
162
+
163
+ from timm.models.layers import DropPath, to_2tuple, trunc_normal_
164
+ from timm.models.registry import register_model
165
+
166
+ import math
167
+
168
+ # from config import Config
169
+
170
+ # config = Config()
171
+
172
+ class Mlp(nn.Module):
173
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
174
+ super().__init__()
175
+ out_features = out_features or in_features
176
+ hidden_features = hidden_features or in_features
177
+ self.fc1 = nn.Linear(in_features, hidden_features)
178
+ self.dwconv = DWConv(hidden_features)
179
+ self.act = act_layer()
180
+ self.fc2 = nn.Linear(hidden_features, out_features)
181
+ self.drop = nn.Dropout(drop)
182
+
183
+ self.apply(self._init_weights)
184
+
185
+ def _init_weights(self, m):
186
+ if isinstance(m, nn.Linear):
187
+ trunc_normal_(m.weight, std=.02)
188
+ if isinstance(m, nn.Linear) and m.bias is not None:
189
+ nn.init.constant_(m.bias, 0)
190
+ elif isinstance(m, nn.LayerNorm):
191
+ nn.init.constant_(m.bias, 0)
192
+ nn.init.constant_(m.weight, 1.0)
193
+ elif isinstance(m, nn.Conv2d):
194
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
195
+ fan_out //= m.groups
196
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
197
+ if m.bias is not None:
198
+ m.bias.data.zero_()
199
+
200
+ def forward(self, x, H, W):
201
+ x = self.fc1(x)
202
+ x = self.dwconv(x, H, W)
203
+ x = self.act(x)
204
+ x = self.drop(x)
205
+ x = self.fc2(x)
206
+ x = self.drop(x)
207
+ return x
208
+
209
+
210
+ class Attention(nn.Module):
211
+ def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., sr_ratio=1):
212
+ super().__init__()
213
+ assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}."
214
+
215
+ self.dim = dim
216
+ self.num_heads = num_heads
217
+ head_dim = dim // num_heads
218
+ self.scale = qk_scale or head_dim ** -0.5
219
+
220
+ self.q = nn.Linear(dim, dim, bias=qkv_bias)
221
+ self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias)
222
+ self.attn_drop_prob = attn_drop
223
+ self.attn_drop = nn.Dropout(attn_drop)
224
+ self.proj = nn.Linear(dim, dim)
225
+ self.proj_drop = nn.Dropout(proj_drop)
226
+
227
+ self.sr_ratio = sr_ratio
228
+ if sr_ratio > 1:
229
+ self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio)
230
+ self.norm = nn.LayerNorm(dim)
231
+
232
+ self.apply(self._init_weights)
233
+
234
+ def _init_weights(self, m):
235
+ if isinstance(m, nn.Linear):
236
+ trunc_normal_(m.weight, std=.02)
237
+ if isinstance(m, nn.Linear) and m.bias is not None:
238
+ nn.init.constant_(m.bias, 0)
239
+ elif isinstance(m, nn.LayerNorm):
240
+ nn.init.constant_(m.bias, 0)
241
+ nn.init.constant_(m.weight, 1.0)
242
+ elif isinstance(m, nn.Conv2d):
243
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
244
+ fan_out //= m.groups
245
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
246
+ if m.bias is not None:
247
+ m.bias.data.zero_()
248
+
249
+ def forward(self, x, H, W):
250
+ B, N, C = x.shape
251
+ q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
252
+
253
+ if self.sr_ratio > 1:
254
+ x_ = x.permute(0, 2, 1).reshape(B, C, H, W)
255
+ x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1)
256
+ x_ = self.norm(x_)
257
+ kv = self.kv(x_).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
258
+ else:
259
+ kv = self.kv(x).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
260
+ k, v = kv[0], kv[1]
261
+
262
+ if config.SDPA_enabled:
263
+ x = torch.nn.functional.scaled_dot_product_attention(
264
+ q, k, v,
265
+ attn_mask=None, dropout_p=self.attn_drop_prob, is_causal=False
266
+ ).transpose(1, 2).reshape(B, N, C)
267
+ else:
268
+ attn = (q @ k.transpose(-2, -1)) * self.scale
269
+ attn = attn.softmax(dim=-1)
270
+ attn = self.attn_drop(attn)
271
+
272
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
273
+ x = self.proj(x)
274
+ x = self.proj_drop(x)
275
+
276
+ return x
277
+
278
+
279
+ class Block(nn.Module):
280
+
281
+ def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
282
+ drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, sr_ratio=1):
283
+ super().__init__()
284
+ self.norm1 = norm_layer(dim)
285
+ self.attn = Attention(
286
+ dim,
287
+ num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
288
+ attn_drop=attn_drop, proj_drop=drop, sr_ratio=sr_ratio)
289
+ # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
290
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
291
+ self.norm2 = norm_layer(dim)
292
+ mlp_hidden_dim = int(dim * mlp_ratio)
293
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
294
+
295
+ self.apply(self._init_weights)
296
+
297
+ def _init_weights(self, m):
298
+ if isinstance(m, nn.Linear):
299
+ trunc_normal_(m.weight, std=.02)
300
+ if isinstance(m, nn.Linear) and m.bias is not None:
301
+ nn.init.constant_(m.bias, 0)
302
+ elif isinstance(m, nn.LayerNorm):
303
+ nn.init.constant_(m.bias, 0)
304
+ nn.init.constant_(m.weight, 1.0)
305
+ elif isinstance(m, nn.Conv2d):
306
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
307
+ fan_out //= m.groups
308
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
309
+ if m.bias is not None:
310
+ m.bias.data.zero_()
311
+
312
+ def forward(self, x, H, W):
313
+ x = x + self.drop_path(self.attn(self.norm1(x), H, W))
314
+ x = x + self.drop_path(self.mlp(self.norm2(x), H, W))
315
+
316
+ return x
317
+
318
+
319
+ class OverlapPatchEmbed(nn.Module):
320
+ """ Image to Patch Embedding
321
+ """
322
+
323
+ def __init__(self, img_size=224, patch_size=7, stride=4, in_channels=3, embed_dim=768):
324
+ super().__init__()
325
+ img_size = to_2tuple(img_size)
326
+ patch_size = to_2tuple(patch_size)
327
+
328
+ self.img_size = img_size
329
+ self.patch_size = patch_size
330
+ self.H, self.W = img_size[0] // patch_size[0], img_size[1] // patch_size[1]
331
+ self.num_patches = self.H * self.W
332
+ self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=stride,
333
+ padding=(patch_size[0] // 2, patch_size[1] // 2))
334
+ self.norm = nn.LayerNorm(embed_dim)
335
+
336
+ self.apply(self._init_weights)
337
+
338
+ def _init_weights(self, m):
339
+ if isinstance(m, nn.Linear):
340
+ trunc_normal_(m.weight, std=.02)
341
+ if isinstance(m, nn.Linear) and m.bias is not None:
342
+ nn.init.constant_(m.bias, 0)
343
+ elif isinstance(m, nn.LayerNorm):
344
+ nn.init.constant_(m.bias, 0)
345
+ nn.init.constant_(m.weight, 1.0)
346
+ elif isinstance(m, nn.Conv2d):
347
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
348
+ fan_out //= m.groups
349
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
350
+ if m.bias is not None:
351
+ m.bias.data.zero_()
352
+
353
+ def forward(self, x):
354
+ x = self.proj(x)
355
+ _, _, H, W = x.shape
356
+ x = x.flatten(2).transpose(1, 2)
357
+ x = self.norm(x)
358
+
359
+ return x, H, W
360
+
361
+
362
+ class PyramidVisionTransformerImpr(nn.Module):
363
+ def __init__(self, img_size=224, patch_size=16, in_channels=3, num_classes=1000, embed_dims=[64, 128, 256, 512],
364
+ num_heads=[1, 2, 4, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=False, qk_scale=None, drop_rate=0.,
365
+ attn_drop_rate=0., drop_path_rate=0., norm_layer=nn.LayerNorm,
366
+ depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1]):
367
+ super().__init__()
368
+ self.num_classes = num_classes
369
+ self.depths = depths
370
+
371
+ # patch_embed
372
+ self.patch_embed1 = OverlapPatchEmbed(img_size=img_size, patch_size=7, stride=4, in_channels=in_channels,
373
+ embed_dim=embed_dims[0])
374
+ self.patch_embed2 = OverlapPatchEmbed(img_size=img_size // 4, patch_size=3, stride=2, in_channels=embed_dims[0],
375
+ embed_dim=embed_dims[1])
376
+ self.patch_embed3 = OverlapPatchEmbed(img_size=img_size // 8, patch_size=3, stride=2, in_channels=embed_dims[1],
377
+ embed_dim=embed_dims[2])
378
+ self.patch_embed4 = OverlapPatchEmbed(img_size=img_size // 16, patch_size=3, stride=2, in_channels=embed_dims[2],
379
+ embed_dim=embed_dims[3])
380
+
381
+ # transformer encoder
382
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
383
+ cur = 0
384
+ self.block1 = nn.ModuleList([Block(
385
+ dim=embed_dims[0], num_heads=num_heads[0], mlp_ratio=mlp_ratios[0], qkv_bias=qkv_bias, qk_scale=qk_scale,
386
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
387
+ sr_ratio=sr_ratios[0])
388
+ for i in range(depths[0])])
389
+ self.norm1 = norm_layer(embed_dims[0])
390
+
391
+ cur += depths[0]
392
+ self.block2 = nn.ModuleList([Block(
393
+ dim=embed_dims[1], num_heads=num_heads[1], mlp_ratio=mlp_ratios[1], qkv_bias=qkv_bias, qk_scale=qk_scale,
394
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
395
+ sr_ratio=sr_ratios[1])
396
+ for i in range(depths[1])])
397
+ self.norm2 = norm_layer(embed_dims[1])
398
+
399
+ cur += depths[1]
400
+ self.block3 = nn.ModuleList([Block(
401
+ dim=embed_dims[2], num_heads=num_heads[2], mlp_ratio=mlp_ratios[2], qkv_bias=qkv_bias, qk_scale=qk_scale,
402
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
403
+ sr_ratio=sr_ratios[2])
404
+ for i in range(depths[2])])
405
+ self.norm3 = norm_layer(embed_dims[2])
406
+
407
+ cur += depths[2]
408
+ self.block4 = nn.ModuleList([Block(
409
+ dim=embed_dims[3], num_heads=num_heads[3], mlp_ratio=mlp_ratios[3], qkv_bias=qkv_bias, qk_scale=qk_scale,
410
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
411
+ sr_ratio=sr_ratios[3])
412
+ for i in range(depths[3])])
413
+ self.norm4 = norm_layer(embed_dims[3])
414
+
415
+ # classification head
416
+ # self.head = nn.Linear(embed_dims[3], num_classes) if num_classes > 0 else nn.Identity()
417
+
418
+ self.apply(self._init_weights)
419
+
420
+ def _init_weights(self, m):
421
+ if isinstance(m, nn.Linear):
422
+ trunc_normal_(m.weight, std=.02)
423
+ if isinstance(m, nn.Linear) and m.bias is not None:
424
+ nn.init.constant_(m.bias, 0)
425
+ elif isinstance(m, nn.LayerNorm):
426
+ nn.init.constant_(m.bias, 0)
427
+ nn.init.constant_(m.weight, 1.0)
428
+ elif isinstance(m, nn.Conv2d):
429
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
430
+ fan_out //= m.groups
431
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
432
+ if m.bias is not None:
433
+ m.bias.data.zero_()
434
+
435
+ def init_weights(self, pretrained=None):
436
+ if isinstance(pretrained, str):
437
+ logger = 1
438
+ #load_checkpoint(self, pretrained, map_location='cpu', strict=False, logger=logger)
439
+
440
+ def reset_drop_path(self, drop_path_rate):
441
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(self.depths))]
442
+ cur = 0
443
+ for i in range(self.depths[0]):
444
+ self.block1[i].drop_path.drop_prob = dpr[cur + i]
445
+
446
+ cur += self.depths[0]
447
+ for i in range(self.depths[1]):
448
+ self.block2[i].drop_path.drop_prob = dpr[cur + i]
449
+
450
+ cur += self.depths[1]
451
+ for i in range(self.depths[2]):
452
+ self.block3[i].drop_path.drop_prob = dpr[cur + i]
453
+
454
+ cur += self.depths[2]
455
+ for i in range(self.depths[3]):
456
+ self.block4[i].drop_path.drop_prob = dpr[cur + i]
457
+
458
+ def freeze_patch_emb(self):
459
+ self.patch_embed1.requires_grad = False
460
+
461
+ @torch.jit.ignore
462
+ def no_weight_decay(self):
463
+ return {'pos_embed1', 'pos_embed2', 'pos_embed3', 'pos_embed4', 'cls_token'} # has pos_embed may be better
464
+
465
+ def get_classifier(self):
466
+ return self.head
467
+
468
+ def reset_classifier(self, num_classes, global_pool=''):
469
+ self.num_classes = num_classes
470
+ self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()
471
+
472
+ def forward_features(self, x):
473
+ B = x.shape[0]
474
+ outs = []
475
+
476
+ # stage 1
477
+ x, H, W = self.patch_embed1(x)
478
+ for i, blk in enumerate(self.block1):
479
+ x = blk(x, H, W)
480
+ x = self.norm1(x)
481
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
482
+ outs.append(x)
483
+
484
+ # stage 2
485
+ x, H, W = self.patch_embed2(x)
486
+ for i, blk in enumerate(self.block2):
487
+ x = blk(x, H, W)
488
+ x = self.norm2(x)
489
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
490
+ outs.append(x)
491
+
492
+ # stage 3
493
+ x, H, W = self.patch_embed3(x)
494
+ for i, blk in enumerate(self.block3):
495
+ x = blk(x, H, W)
496
+ x = self.norm3(x)
497
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
498
+ outs.append(x)
499
+
500
+ # stage 4
501
+ x, H, W = self.patch_embed4(x)
502
+ for i, blk in enumerate(self.block4):
503
+ x = blk(x, H, W)
504
+ x = self.norm4(x)
505
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
506
+ outs.append(x)
507
+
508
+ return outs
509
+
510
+ # return x.mean(dim=1)
511
+
512
+ def forward(self, x):
513
+ x = self.forward_features(x)
514
+ # x = self.head(x)
515
+
516
+ return x
517
+
518
+
519
+ class DWConv(nn.Module):
520
+ def __init__(self, dim=768):
521
+ super(DWConv, self).__init__()
522
+ self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim)
523
+
524
+ def forward(self, x, H, W):
525
+ B, N, C = x.shape
526
+ x = x.transpose(1, 2).view(B, C, H, W).contiguous()
527
+ x = self.dwconv(x)
528
+ x = x.flatten(2).transpose(1, 2)
529
+
530
+ return x
531
+
532
+
533
+ def _conv_filter(state_dict, patch_size=16):
534
+ """ convert patch embedding weight from manual patchify + linear proj to conv"""
535
+ out_dict = {}
536
+ for k, v in state_dict.items():
537
+ if 'patch_embed.proj.weight' in k:
538
+ v = v.reshape((v.shape[0], 3, patch_size, patch_size))
539
+ out_dict[k] = v
540
+
541
+ return out_dict
542
+
543
+
544
+ ## @register_model
545
+ class pvt_v2_b0(PyramidVisionTransformerImpr):
546
+ def __init__(self, **kwargs):
547
+ super(pvt_v2_b0, self).__init__(
548
+ patch_size=4, embed_dims=[32, 64, 160, 256], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
549
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1],
550
+ drop_rate=0.0, drop_path_rate=0.1)
551
+
552
+
553
+
554
+ ## @register_model
555
+ class pvt_v2_b1(PyramidVisionTransformerImpr):
556
+ def __init__(self, **kwargs):
557
+ super(pvt_v2_b1, self).__init__(
558
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
559
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1],
560
+ drop_rate=0.0, drop_path_rate=0.1)
561
+
562
+ ## @register_model
563
+ class pvt_v2_b2(PyramidVisionTransformerImpr):
564
+ def __init__(self, in_channels=3, **kwargs):
565
+ super(pvt_v2_b2, self).__init__(
566
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
567
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1],
568
+ drop_rate=0.0, drop_path_rate=0.1, in_channels=in_channels)
569
+
570
+ ## @register_model
571
+ class pvt_v2_b3(PyramidVisionTransformerImpr):
572
+ def __init__(self, **kwargs):
573
+ super(pvt_v2_b3, self).__init__(
574
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
575
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 18, 3], sr_ratios=[8, 4, 2, 1],
576
+ drop_rate=0.0, drop_path_rate=0.1)
577
+
578
+ ## @register_model
579
+ class pvt_v2_b4(PyramidVisionTransformerImpr):
580
+ def __init__(self, **kwargs):
581
+ super(pvt_v2_b4, self).__init__(
582
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
583
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 8, 27, 3], sr_ratios=[8, 4, 2, 1],
584
+ drop_rate=0.0, drop_path_rate=0.1)
585
+
586
+
587
+ ## @register_model
588
+ class pvt_v2_b5(PyramidVisionTransformerImpr):
589
+ def __init__(self, **kwargs):
590
+ super(pvt_v2_b5, self).__init__(
591
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4],
592
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 6, 40, 3], sr_ratios=[8, 4, 2, 1],
593
+ drop_rate=0.0, drop_path_rate=0.1)
594
+
595
+
596
+
597
+ ### models/backbones/swin_v1.py
598
+
599
+ # --------------------------------------------------------
600
+ # Swin Transformer
601
+ # Copyright (c) 2021 Microsoft
602
+ # Licensed under The MIT License [see LICENSE for details]
603
+ # Written by Ze Liu, Yutong Lin, Yixuan Wei
604
+ # --------------------------------------------------------
605
+
606
+ import torch
607
+ import torch.nn as nn
608
+ import torch.nn.functional as F
609
+ import torch.utils.checkpoint as checkpoint
610
+ import numpy as np
611
+ from timm.models.layers import DropPath, to_2tuple, trunc_normal_
612
+
613
+ # from config import Config
614
+
615
+
616
+ # config = Config()
617
+
618
+
619
+ class Mlp(nn.Module):
620
+ """ Multilayer perceptron."""
621
+
622
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
623
+ super().__init__()
624
+ out_features = out_features or in_features
625
+ hidden_features = hidden_features or in_features
626
+ self.fc1 = nn.Linear(in_features, hidden_features)
627
+ self.act = act_layer()
628
+ self.fc2 = nn.Linear(hidden_features, out_features)
629
+ self.drop = nn.Dropout(drop)
630
+
631
+ def forward(self, x):
632
+ x = self.fc1(x)
633
+ x = self.act(x)
634
+ x = self.drop(x)
635
+ x = self.fc2(x)
636
+ x = self.drop(x)
637
+ return x
638
+
639
+
640
+ def window_partition(x, window_size):
641
+ """
642
+ Args:
643
+ x: (B, H, W, C)
644
+ window_size (int): window size
645
+
646
+ Returns:
647
+ windows: (num_windows*B, window_size, window_size, C)
648
+ """
649
+ B, H, W, C = x.shape
650
+ x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
651
+ windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
652
+ return windows
653
+
654
+
655
+ def window_reverse(windows, window_size, H, W):
656
+ """
657
+ Args:
658
+ windows: (num_windows*B, window_size, window_size, C)
659
+ window_size (int): Window size
660
+ H (int): Height of image
661
+ W (int): Width of image
662
+
663
+ Returns:
664
+ x: (B, H, W, C)
665
+ """
666
+ B = int(windows.shape[0] / (H * W / window_size / window_size))
667
+ x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
668
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
669
+ return x
670
+
671
+
672
+ class WindowAttention(nn.Module):
673
+ """ Window based multi-head self attention (W-MSA) module with relative position bias.
674
+ It supports both of shifted and non-shifted window.
675
+
676
+ Args:
677
+ dim (int): Number of input channels.
678
+ window_size (tuple[int]): The height and width of the window.
679
+ num_heads (int): Number of attention heads.
680
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
681
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
682
+ attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
683
+ proj_drop (float, optional): Dropout ratio of output. Default: 0.0
684
+ """
685
+
686
+ def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.):
687
+
688
+ super().__init__()
689
+ self.dim = dim
690
+ self.window_size = window_size # Wh, Ww
691
+ self.num_heads = num_heads
692
+ head_dim = dim // num_heads
693
+ self.scale = qk_scale or head_dim ** -0.5
694
+
695
+ # define a parameter table of relative position bias
696
+ self.relative_position_bias_table = nn.Parameter(
697
+ torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH
698
+
699
+ # get pair-wise relative position index for each token inside the window
700
+ coords_h = torch.arange(self.window_size[0])
701
+ coords_w = torch.arange(self.window_size[1])
702
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w], indexing='ij')) # 2, Wh, Ww
703
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
704
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
705
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
706
+ relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
707
+ relative_coords[:, :, 1] += self.window_size[1] - 1
708
+ relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
709
+ relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
710
+ self.register_buffer("relative_position_index", relative_position_index)
711
+
712
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
713
+ self.attn_drop_prob = attn_drop
714
+ self.attn_drop = nn.Dropout(attn_drop)
715
+ self.proj = nn.Linear(dim, dim)
716
+ self.proj_drop = nn.Dropout(proj_drop)
717
+
718
+ trunc_normal_(self.relative_position_bias_table, std=.02)
719
+ self.softmax = nn.Softmax(dim=-1)
720
+
721
+ def forward(self, x, mask=None):
722
+ """ Forward function.
723
+
724
+ Args:
725
+ x: input features with shape of (num_windows*B, N, C)
726
+ mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
727
+ """
728
+ B_, N, C = x.shape
729
+ qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
730
+ q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
731
+
732
+ q = q * self.scale
733
+
734
+ if config.SDPA_enabled:
735
+ x = torch.nn.functional.scaled_dot_product_attention(
736
+ q, k, v,
737
+ attn_mask=None, dropout_p=self.attn_drop_prob, is_causal=False
738
+ ).transpose(1, 2).reshape(B_, N, C)
739
+ else:
740
+ attn = (q @ k.transpose(-2, -1))
741
+
742
+ relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
743
+ self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1
744
+ ) # Wh*Ww, Wh*Ww, nH
745
+ relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
746
+ attn = attn + relative_position_bias.unsqueeze(0)
747
+
748
+ if mask is not None:
749
+ nW = mask.shape[0]
750
+ attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
751
+ attn = attn.view(-1, self.num_heads, N, N)
752
+ attn = self.softmax(attn)
753
+ else:
754
+ attn = self.softmax(attn)
755
+
756
+ attn = self.attn_drop(attn)
757
+
758
+ x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
759
+ x = self.proj(x)
760
+ x = self.proj_drop(x)
761
+ return x
762
+
763
+
764
+ class SwinTransformerBlock(nn.Module):
765
+ """ Swin Transformer Block.
766
+
767
+ Args:
768
+ dim (int): Number of input channels.
769
+ num_heads (int): Number of attention heads.
770
+ window_size (int): Window size.
771
+ shift_size (int): Shift size for SW-MSA.
772
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
773
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
774
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
775
+ drop (float, optional): Dropout rate. Default: 0.0
776
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
777
+ drop_path (float, optional): Stochastic depth rate. Default: 0.0
778
+ act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
779
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
780
+ """
781
+
782
+ def __init__(self, dim, num_heads, window_size=7, shift_size=0,
783
+ mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0.,
784
+ act_layer=nn.GELU, norm_layer=nn.LayerNorm):
785
+ super().__init__()
786
+ self.dim = dim
787
+ self.num_heads = num_heads
788
+ self.window_size = window_size
789
+ self.shift_size = shift_size
790
+ self.mlp_ratio = mlp_ratio
791
+ assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
792
+
793
+ self.norm1 = norm_layer(dim)
794
+ self.attn = WindowAttention(
795
+ dim, window_size=to_2tuple(self.window_size), num_heads=num_heads,
796
+ qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
797
+
798
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
799
+ self.norm2 = norm_layer(dim)
800
+ mlp_hidden_dim = int(dim * mlp_ratio)
801
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
802
+
803
+ self.H = None
804
+ self.W = None
805
+
806
+ def forward(self, x, mask_matrix):
807
+ """ Forward function.
808
+
809
+ Args:
810
+ x: Input feature, tensor size (B, H*W, C).
811
+ H, W: Spatial resolution of the input feature.
812
+ mask_matrix: Attention mask for cyclic shift.
813
+ """
814
+ B, L, C = x.shape
815
+ H, W = self.H, self.W
816
+ assert L == H * W, "input feature has wrong size"
817
+
818
+ shortcut = x
819
+ x = self.norm1(x)
820
+ x = x.view(B, H, W, C)
821
+
822
+ # pad feature maps to multiples of window size
823
+ pad_l = pad_t = 0
824
+ pad_r = (self.window_size - W % self.window_size) % self.window_size
825
+ pad_b = (self.window_size - H % self.window_size) % self.window_size
826
+ x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b))
827
+ _, Hp, Wp, _ = x.shape
828
+
829
+ # cyclic shift
830
+ if self.shift_size > 0:
831
+ shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
832
+ attn_mask = mask_matrix
833
+ else:
834
+ shifted_x = x
835
+ attn_mask = None
836
+
837
+ # partition windows
838
+ x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C
839
+ x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C
840
+
841
+ # W-MSA/SW-MSA
842
+ attn_windows = self.attn(x_windows, mask=attn_mask) # nW*B, window_size*window_size, C
843
+
844
+ # merge windows
845
+ attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
846
+ shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp) # B H' W' C
847
+
848
+ # reverse cyclic shift
849
+ if self.shift_size > 0:
850
+ x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
851
+ else:
852
+ x = shifted_x
853
+
854
+ if pad_r > 0 or pad_b > 0:
855
+ x = x[:, :H, :W, :].contiguous()
856
+
857
+ x = x.view(B, H * W, C)
858
+
859
+ # FFN
860
+ x = shortcut + self.drop_path(x)
861
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
862
+
863
+ return x
864
+
865
+
866
+ class PatchMerging(nn.Module):
867
+ """ Patch Merging Layer
868
+
869
+ Args:
870
+ dim (int): Number of input channels.
871
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
872
+ """
873
+ def __init__(self, dim, norm_layer=nn.LayerNorm):
874
+ super().__init__()
875
+ self.dim = dim
876
+ self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
877
+ self.norm = norm_layer(4 * dim)
878
+
879
+ def forward(self, x, H, W):
880
+ """ Forward function.
881
+
882
+ Args:
883
+ x: Input feature, tensor size (B, H*W, C).
884
+ H, W: Spatial resolution of the input feature.
885
+ """
886
+ B, L, C = x.shape
887
+ assert L == H * W, "input feature has wrong size"
888
+
889
+ x = x.view(B, H, W, C)
890
+
891
+ # padding
892
+ pad_input = (H % 2 == 1) or (W % 2 == 1)
893
+ if pad_input:
894
+ x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2))
895
+
896
+ x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C
897
+ x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C
898
+ x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C
899
+ x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C
900
+ x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C
901
+ x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C
902
+
903
+ x = self.norm(x)
904
+ x = self.reduction(x)
905
+
906
+ return x
907
+
908
+
909
+ class BasicLayer(nn.Module):
910
+ """ A basic Swin Transformer layer for one stage.
911
+
912
+ Args:
913
+ dim (int): Number of feature channels
914
+ depth (int): Depths of this stage.
915
+ num_heads (int): Number of attention head.
916
+ window_size (int): Local window size. Default: 7.
917
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
918
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
919
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
920
+ drop (float, optional): Dropout rate. Default: 0.0
921
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
922
+ drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
923
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
924
+ downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
925
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
926
+ """
927
+
928
+ def __init__(self,
929
+ dim,
930
+ depth,
931
+ num_heads,
932
+ window_size=7,
933
+ mlp_ratio=4.,
934
+ qkv_bias=True,
935
+ qk_scale=None,
936
+ drop=0.,
937
+ attn_drop=0.,
938
+ drop_path=0.,
939
+ norm_layer=nn.LayerNorm,
940
+ downsample=None,
941
+ use_checkpoint=False):
942
+ super().__init__()
943
+ self.window_size = window_size
944
+ self.shift_size = window_size // 2
945
+ self.depth = depth
946
+ self.use_checkpoint = use_checkpoint
947
+
948
+ # build blocks
949
+ self.blocks = nn.ModuleList([
950
+ SwinTransformerBlock(
951
+ dim=dim,
952
+ num_heads=num_heads,
953
+ window_size=window_size,
954
+ shift_size=0 if (i % 2 == 0) else window_size // 2,
955
+ mlp_ratio=mlp_ratio,
956
+ qkv_bias=qkv_bias,
957
+ qk_scale=qk_scale,
958
+ drop=drop,
959
+ attn_drop=attn_drop,
960
+ drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
961
+ norm_layer=norm_layer)
962
+ for i in range(depth)])
963
+
964
+ # patch merging layer
965
+ if downsample is not None:
966
+ self.downsample = downsample(dim=dim, norm_layer=norm_layer)
967
+ else:
968
+ self.downsample = None
969
+
970
+ def forward(self, x, H, W):
971
+ """ Forward function.
972
+
973
+ Args:
974
+ x: Input feature, tensor size (B, H*W, C).
975
+ H, W: Spatial resolution of the input feature.
976
+ """
977
+
978
+ # calculate attention mask for SW-MSA
979
+ # Turn int to torch.tensor for the compatiability with torch.compile in PyTorch 2.5.
980
+ Hp = torch.ceil(torch.tensor(H) / self.window_size).to(torch.int64) * self.window_size
981
+ Wp = torch.ceil(torch.tensor(W) / self.window_size).to(torch.int64) * self.window_size
982
+ img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device) # 1 Hp Wp 1
983
+ h_slices = (slice(0, -self.window_size),
984
+ slice(-self.window_size, -self.shift_size),
985
+ slice(-self.shift_size, None))
986
+ w_slices = (slice(0, -self.window_size),
987
+ slice(-self.window_size, -self.shift_size),
988
+ slice(-self.shift_size, None))
989
+ cnt = 0
990
+ for h in h_slices:
991
+ for w in w_slices:
992
+ img_mask[:, h, w, :] = cnt
993
+ cnt += 1
994
+
995
+ mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1
996
+ mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
997
+ attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
998
+ attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)).to(x.dtype)
999
+
1000
+ for blk in self.blocks:
1001
+ blk.H, blk.W = H, W
1002
+ if self.use_checkpoint:
1003
+ x = checkpoint.checkpoint(blk, x, attn_mask)
1004
+ else:
1005
+ x = blk(x, attn_mask)
1006
+ if self.downsample is not None:
1007
+ x_down = self.downsample(x, H, W)
1008
+ Wh, Ww = (H + 1) // 2, (W + 1) // 2
1009
+ return x, H, W, x_down, Wh, Ww
1010
+ else:
1011
+ return x, H, W, x, H, W
1012
+
1013
+
1014
+ class PatchEmbed(nn.Module):
1015
+ """ Image to Patch Embedding
1016
+
1017
+ Args:
1018
+ patch_size (int): Patch token size. Default: 4.
1019
+ in_channels (int): Number of input image channels. Default: 3.
1020
+ embed_dim (int): Number of linear projection output channels. Default: 96.
1021
+ norm_layer (nn.Module, optional): Normalization layer. Default: None
1022
+ """
1023
+
1024
+ def __init__(self, patch_size=4, in_channels=3, embed_dim=96, norm_layer=None):
1025
+ super().__init__()
1026
+ patch_size = to_2tuple(patch_size)
1027
+ self.patch_size = patch_size
1028
+
1029
+ self.in_channels = in_channels
1030
+ self.embed_dim = embed_dim
1031
+
1032
+ self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
1033
+ if norm_layer is not None:
1034
+ self.norm = norm_layer(embed_dim)
1035
+ else:
1036
+ self.norm = None
1037
+
1038
+ def forward(self, x):
1039
+ """Forward function."""
1040
+ # padding
1041
+ _, _, H, W = x.size()
1042
+ if W % self.patch_size[1] != 0:
1043
+ x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1]))
1044
+ if H % self.patch_size[0] != 0:
1045
+ x = F.pad(x, (0, 0, 0, self.patch_size[0] - H % self.patch_size[0]))
1046
+
1047
+ x = self.proj(x) # B C Wh Ww
1048
+ if self.norm is not None:
1049
+ Wh, Ww = x.size(2), x.size(3)
1050
+ x = x.flatten(2).transpose(1, 2)
1051
+ x = self.norm(x)
1052
+ x = x.transpose(1, 2).view(-1, self.embed_dim, Wh, Ww)
1053
+
1054
+ return x
1055
+
1056
+
1057
+ class SwinTransformer(nn.Module):
1058
+ """ Swin Transformer backbone.
1059
+ A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` -
1060
+ https://arxiv.org/pdf/2103.14030
1061
+
1062
+ Args:
1063
+ pretrain_img_size (int): Input image size for training the pretrained model,
1064
+ used in absolute postion embedding. Default 224.
1065
+ patch_size (int | tuple(int)): Patch size. Default: 4.
1066
+ in_channels (int): Number of input image channels. Default: 3.
1067
+ embed_dim (int): Number of linear projection output channels. Default: 96.
1068
+ depths (tuple[int]): Depths of each Swin Transformer stage.
1069
+ num_heads (tuple[int]): Number of attention head of each stage.
1070
+ window_size (int): Window size. Default: 7.
1071
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
1072
+ qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
1073
+ qk_scale (float): Override default qk scale of head_dim ** -0.5 if set.
1074
+ drop_rate (float): Dropout rate.
1075
+ attn_drop_rate (float): Attention dropout rate. Default: 0.
1076
+ drop_path_rate (float): Stochastic depth rate. Default: 0.2.
1077
+ norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
1078
+ ape (bool): If True, add absolute position embedding to the patch embedding. Default: False.
1079
+ patch_norm (bool): If True, add normalization after patch embedding. Default: True.
1080
+ out_indices (Sequence[int]): Output from which stages.
1081
+ frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
1082
+ -1 means not freezing any parameters.
1083
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
1084
+ """
1085
+
1086
+ def __init__(self,
1087
+ pretrain_img_size=224,
1088
+ patch_size=4,
1089
+ in_channels=3,
1090
+ embed_dim=96,
1091
+ depths=[2, 2, 6, 2],
1092
+ num_heads=[3, 6, 12, 24],
1093
+ window_size=7,
1094
+ mlp_ratio=4.,
1095
+ qkv_bias=True,
1096
+ qk_scale=None,
1097
+ drop_rate=0.,
1098
+ attn_drop_rate=0.,
1099
+ drop_path_rate=0.2,
1100
+ norm_layer=nn.LayerNorm,
1101
+ ape=False,
1102
+ patch_norm=True,
1103
+ out_indices=(0, 1, 2, 3),
1104
+ frozen_stages=-1,
1105
+ use_checkpoint=False):
1106
+ super().__init__()
1107
+
1108
+ self.pretrain_img_size = pretrain_img_size
1109
+ self.num_layers = len(depths)
1110
+ self.embed_dim = embed_dim
1111
+ self.ape = ape
1112
+ self.patch_norm = patch_norm
1113
+ self.out_indices = out_indices
1114
+ self.frozen_stages = frozen_stages
1115
+
1116
+ # split image into non-overlapping patches
1117
+ self.patch_embed = PatchEmbed(
1118
+ patch_size=patch_size, in_channels=in_channels, embed_dim=embed_dim,
1119
+ norm_layer=norm_layer if self.patch_norm else None)
1120
+
1121
+ # absolute position embedding
1122
+ if self.ape:
1123
+ pretrain_img_size = to_2tuple(pretrain_img_size)
1124
+ patch_size = to_2tuple(patch_size)
1125
+ patches_resolution = [pretrain_img_size[0] // patch_size[0], pretrain_img_size[1] // patch_size[1]]
1126
+
1127
+ self.absolute_pos_embed = nn.Parameter(torch.zeros(1, embed_dim, patches_resolution[0], patches_resolution[1]))
1128
+ trunc_normal_(self.absolute_pos_embed, std=.02)
1129
+
1130
+ self.pos_drop = nn.Dropout(p=drop_rate)
1131
+
1132
+ # stochastic depth
1133
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
1134
+
1135
+ # build layers
1136
+ self.layers = nn.ModuleList()
1137
+ for i_layer in range(self.num_layers):
1138
+ layer = BasicLayer(
1139
+ dim=int(embed_dim * 2 ** i_layer),
1140
+ depth=depths[i_layer],
1141
+ num_heads=num_heads[i_layer],
1142
+ window_size=window_size,
1143
+ mlp_ratio=mlp_ratio,
1144
+ qkv_bias=qkv_bias,
1145
+ qk_scale=qk_scale,
1146
+ drop=drop_rate,
1147
+ attn_drop=attn_drop_rate,
1148
+ drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])],
1149
+ norm_layer=norm_layer,
1150
+ downsample=PatchMerging if (i_layer < self.num_layers - 1) else None,
1151
+ use_checkpoint=use_checkpoint)
1152
+ self.layers.append(layer)
1153
+
1154
+ num_features = [int(embed_dim * 2 ** i) for i in range(self.num_layers)]
1155
+ self.num_features = num_features
1156
+
1157
+ # add a norm layer for each output
1158
+ for i_layer in out_indices:
1159
+ layer = norm_layer(num_features[i_layer])
1160
+ layer_name = f'norm{i_layer}'
1161
+ self.add_module(layer_name, layer)
1162
+
1163
+ self._freeze_stages()
1164
+
1165
+ def _freeze_stages(self):
1166
+ if self.frozen_stages >= 0:
1167
+ self.patch_embed.eval()
1168
+ for param in self.patch_embed.parameters():
1169
+ param.requires_grad = False
1170
+
1171
+ if self.frozen_stages >= 1 and self.ape:
1172
+ self.absolute_pos_embed.requires_grad = False
1173
+
1174
+ if self.frozen_stages >= 2:
1175
+ self.pos_drop.eval()
1176
+ for i in range(0, self.frozen_stages - 1):
1177
+ m = self.layers[i]
1178
+ m.eval()
1179
+ for param in m.parameters():
1180
+ param.requires_grad = False
1181
+
1182
+
1183
+ def forward(self, x):
1184
+ """Forward function."""
1185
+ x = self.patch_embed(x)
1186
+
1187
+ Wh, Ww = x.size(2), x.size(3)
1188
+ if self.ape:
1189
+ # interpolate the position embedding to the corresponding size
1190
+ absolute_pos_embed = F.interpolate(self.absolute_pos_embed, size=(Wh, Ww), mode='bicubic')
1191
+ x = (x + absolute_pos_embed) # B Wh*Ww C
1192
+
1193
+ outs = []#x.contiguous()]
1194
+ x = x.flatten(2).transpose(1, 2)
1195
+ x = self.pos_drop(x)
1196
+ for i in range(self.num_layers):
1197
+ layer = self.layers[i]
1198
+ x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww)
1199
+
1200
+ if i in self.out_indices:
1201
+ norm_layer = getattr(self, f'norm{i}')
1202
+ x_out = norm_layer(x_out)
1203
+
1204
+ out = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous()
1205
+ outs.append(out)
1206
+
1207
+ return tuple(outs)
1208
+
1209
+ def train(self, mode=True):
1210
+ """Convert the model into training mode while keep layers freezed."""
1211
+ super(SwinTransformer, self).train(mode)
1212
+ self._freeze_stages()
1213
+
1214
+ def swin_v1_t():
1215
+ model = SwinTransformer(embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7)
1216
+ return model
1217
+
1218
+ def swin_v1_s():
1219
+ model = SwinTransformer(embed_dim=96, depths=[2, 2, 18, 2], num_heads=[3, 6, 12, 24], window_size=7)
1220
+ return model
1221
+
1222
+ def swin_v1_b():
1223
+ model = SwinTransformer(embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=12)
1224
+ return model
1225
+
1226
+ def swin_v1_l():
1227
+ model = SwinTransformer(embed_dim=192, depths=[2, 2, 18, 2], num_heads=[6, 12, 24, 48], window_size=12)
1228
+ return model
1229
+
1230
+
1231
+
1232
+ ### models/modules/deform_conv.py
1233
+
1234
+ import torch
1235
+ import torch.nn as nn
1236
+ from torchvision.ops import deform_conv2d
1237
+
1238
+
1239
+ class DeformableConv2d(nn.Module):
1240
+ def __init__(self,
1241
+ in_channels,
1242
+ out_channels,
1243
+ kernel_size=3,
1244
+ stride=1,
1245
+ padding=1,
1246
+ bias=False):
1247
+
1248
+ super(DeformableConv2d, self).__init__()
1249
+
1250
+ assert type(kernel_size) == tuple or type(kernel_size) == int
1251
+
1252
+ kernel_size = kernel_size if type(kernel_size) == tuple else (kernel_size, kernel_size)
1253
+ self.stride = stride if type(stride) == tuple else (stride, stride)
1254
+ self.padding = padding
1255
+
1256
+ self.offset_conv = nn.Conv2d(in_channels,
1257
+ 2 * kernel_size[0] * kernel_size[1],
1258
+ kernel_size=kernel_size,
1259
+ stride=stride,
1260
+ padding=self.padding,
1261
+ bias=True)
1262
+
1263
+ nn.init.constant_(self.offset_conv.weight, 0.)
1264
+ nn.init.constant_(self.offset_conv.bias, 0.)
1265
+
1266
+ self.modulator_conv = nn.Conv2d(in_channels,
1267
+ 1 * kernel_size[0] * kernel_size[1],
1268
+ kernel_size=kernel_size,
1269
+ stride=stride,
1270
+ padding=self.padding,
1271
+ bias=True)
1272
+
1273
+ nn.init.constant_(self.modulator_conv.weight, 0.)
1274
+ nn.init.constant_(self.modulator_conv.bias, 0.)
1275
+
1276
+ self.regular_conv = nn.Conv2d(in_channels,
1277
+ out_channels=out_channels,
1278
+ kernel_size=kernel_size,
1279
+ stride=stride,
1280
+ padding=self.padding,
1281
+ bias=bias)
1282
+
1283
+ def forward(self, x):
1284
+ #h, w = x.shape[2:]
1285
+ #max_offset = max(h, w)/4.
1286
+
1287
+ offset = self.offset_conv(x)#.clamp(-max_offset, max_offset)
1288
+ modulator = 2. * torch.sigmoid(self.modulator_conv(x))
1289
+
1290
+ x = deform_conv2d(
1291
+ input=x,
1292
+ offset=offset,
1293
+ weight=self.regular_conv.weight,
1294
+ bias=self.regular_conv.bias,
1295
+ padding=self.padding,
1296
+ mask=modulator,
1297
+ stride=self.stride,
1298
+ )
1299
+ return x
1300
+
1301
+
1302
+
1303
+
1304
+ ### utils.py
1305
+
1306
+ import torch.nn as nn
1307
+
1308
+
1309
+ def build_act_layer(act_layer):
1310
+ if act_layer == 'ReLU':
1311
+ return nn.ReLU(inplace=True)
1312
+ elif act_layer == 'SiLU':
1313
+ return nn.SiLU(inplace=True)
1314
+ elif act_layer == 'GELU':
1315
+ return nn.GELU()
1316
+
1317
+ raise NotImplementedError(f'build_act_layer does not support {act_layer}')
1318
+
1319
+
1320
+ def build_norm_layer(dim,
1321
+ norm_layer,
1322
+ in_format='channels_last',
1323
+ out_format='channels_last',
1324
+ eps=1e-6):
1325
+ layers = []
1326
+ if norm_layer == 'BN':
1327
+ if in_format == 'channels_last':
1328
+ layers.append(to_channels_first())
1329
+ layers.append(nn.BatchNorm2d(dim))
1330
+ if out_format == 'channels_last':
1331
+ layers.append(to_channels_last())
1332
+ elif norm_layer == 'LN':
1333
+ if in_format == 'channels_first':
1334
+ layers.append(to_channels_last())
1335
+ layers.append(nn.LayerNorm(dim, eps=eps))
1336
+ if out_format == 'channels_first':
1337
+ layers.append(to_channels_first())
1338
+ else:
1339
+ raise NotImplementedError(
1340
+ f'build_norm_layer does not support {norm_layer}')
1341
+ return nn.Sequential(*layers)
1342
+
1343
+
1344
+ class to_channels_first(nn.Module):
1345
+
1346
+ def __init__(self):
1347
+ super().__init__()
1348
+
1349
+ def forward(self, x):
1350
+ return x.permute(0, 3, 1, 2)
1351
+
1352
+
1353
+ class to_channels_last(nn.Module):
1354
+
1355
+ def __init__(self):
1356
+ super().__init__()
1357
+
1358
+ def forward(self, x):
1359
+ return x.permute(0, 2, 3, 1)
1360
+
1361
+
1362
+
1363
+ ### dataset.py
1364
+
1365
+ _class_labels_TR_sorted = (
1366
+ 'Airplane, Ant, Antenna, Archery, Axe, BabyCarriage, Bag, BalanceBeam, Balcony, Balloon, Basket, BasketballHoop, Beatle, Bed, Bee, Bench, Bicycle, '
1367
+ 'BicycleFrame, BicycleStand, Boat, Bonsai, BoomLift, Bridge, BunkBed, Butterfly, Button, Cable, CableLift, Cage, Camcorder, Cannon, Canoe, Car, '
1368
+ 'CarParkDropArm, Carriage, Cart, Caterpillar, CeilingLamp, Centipede, Chair, Clip, Clock, Clothes, CoatHanger, Comb, ConcretePumpTruck, Crack, Crane, '
1369
+ 'Cup, DentalChair, Desk, DeskChair, Diagram, DishRack, DoorHandle, Dragonfish, Dragonfly, Drum, Earphone, Easel, ElectricIron, Excavator, Eyeglasses, '
1370
+ 'Fan, Fence, Fencing, FerrisWheel, FireExtinguisher, Fishing, Flag, FloorLamp, Forklift, GasStation, Gate, Gear, Goal, Golf, GymEquipment, Hammock, '
1371
+ 'Handcart, Handcraft, Handrail, HangGlider, Harp, Harvester, Headset, Helicopter, Helmet, Hook, HorizontalBar, Hydrovalve, IroningTable, Jewelry, Key, '
1372
+ 'KidsPlayground, Kitchenware, Kite, Knife, Ladder, LaundryRack, Lightning, Lobster, Locust, Machine, MachineGun, MagazineRack, Mantis, Medal, MemorialArchway, '
1373
+ 'Microphone, Missile, MobileHolder, Monitor, Mosquito, Motorcycle, MovingTrolley, Mower, MusicPlayer, MusicStand, ObservationTower, Octopus, OilWell, '
1374
+ 'OlympicLogo, OperatingTable, OutdoorFitnessEquipment, Parachute, Pavilion, Piano, Pipe, PlowHarrow, PoleVault, Punchbag, Rack, Racket, Rifle, Ring, Robot, '
1375
+ 'RockClimbing, Rope, Sailboat, Satellite, Scaffold, Scale, Scissor, Scooter, Sculpture, Seadragon, Seahorse, Seal, SewingMachine, Ship, Shoe, ShoppingCart, '
1376
+ 'ShoppingTrolley, Shower, Shrimp, Signboard, Skateboarding, Skeleton, Skiing, Spade, SpeedBoat, Spider, Spoon, Stair, Stand, Stationary, SteeringWheel, '
1377
+ 'Stethoscope, Stool, Stove, StreetLamp, SweetStand, Swing, Sword, TV, Table, TableChair, TableLamp, TableTennis, Tank, Tapeline, Teapot, Telescope, Tent, '
1378
+ 'TobaccoPipe, Toy, Tractor, TrafficLight, TrafficSign, Trampoline, TransmissionTower, Tree, Tricycle, TrimmerCover, Tripod, Trombone, Truck, Trumpet, Tuba, '
1379
+ 'UAV, Umbrella, UnevenBars, UtilityPole, VacuumCleaner, Violin, Wakesurfing, Watch, WaterTower, WateringPot, Well, WellLid, Wheel, Wheelchair, WindTurbine, Windmill, WineGlass, WireWhisk, Yacht'
1380
+ )
1381
+ class_labels_TR_sorted = _class_labels_TR_sorted.split(', ')
1382
+
1383
+
1384
+ ### models/backbones/build_backbones.py
1385
+
1386
+ import torch
1387
+ import torch.nn as nn
1388
+ from collections import OrderedDict
1389
+ from torchvision.models import vgg16, vgg16_bn, VGG16_Weights, VGG16_BN_Weights, resnet50, ResNet50_Weights
1390
+ # from models.pvt_v2 import pvt_v2_b0, pvt_v2_b1, pvt_v2_b2, pvt_v2_b5
1391
+ # from models.swin_v1 import swin_v1_t, swin_v1_s, swin_v1_b, swin_v1_l
1392
+ # from config import Config
1393
+
1394
+
1395
+ config = Config()
1396
+
1397
+ def build_backbone(bb_name, pretrained=True, params_settings=''):
1398
+ if bb_name == 'vgg16':
1399
+ bb_net = list(vgg16(pretrained=VGG16_Weights.DEFAULT if pretrained else None).children())[0]
1400
+ bb = nn.Sequential(OrderedDict({'conv1': bb_net[:4], 'conv2': bb_net[4:9], 'conv3': bb_net[9:16], 'conv4': bb_net[16:23]}))
1401
+ elif bb_name == 'vgg16bn':
1402
+ bb_net = list(vgg16_bn(pretrained=VGG16_BN_Weights.DEFAULT if pretrained else None).children())[0]
1403
+ bb = nn.Sequential(OrderedDict({'conv1': bb_net[:6], 'conv2': bb_net[6:13], 'conv3': bb_net[13:23], 'conv4': bb_net[23:33]}))
1404
+ elif bb_name == 'resnet50':
1405
+ bb_net = list(resnet50(pretrained=ResNet50_Weights.DEFAULT if pretrained else None).children())
1406
+ bb = nn.Sequential(OrderedDict({'conv1': nn.Sequential(*bb_net[0:3]), 'conv2': bb_net[4], 'conv3': bb_net[5], 'conv4': bb_net[6]}))
1407
+ else:
1408
+ bb = eval('{}({})'.format(bb_name, params_settings))
1409
+ if pretrained:
1410
+ bb = load_weights(bb, bb_name)
1411
+ return bb
1412
+
1413
+ def load_weights(model, model_name):
1414
+ save_model = torch.load(config.weights[model_name], map_location='cpu')
1415
+ model_dict = model.state_dict()
1416
+ state_dict = {k: v if v.size() == model_dict[k].size() else model_dict[k] for k, v in save_model.items() if k in model_dict.keys()}
1417
+ # to ignore the weights with mismatched size when I modify the backbone itself.
1418
+ if not state_dict:
1419
+ save_model_keys = list(save_model.keys())
1420
+ sub_item = save_model_keys[0] if len(save_model_keys) == 1 else None
1421
+ state_dict = {k: v if v.size() == model_dict[k].size() else model_dict[k] for k, v in save_model[sub_item].items() if k in model_dict.keys()}
1422
+ if not state_dict or not sub_item:
1423
+ print('Weights are not successully loaded. Check the state dict of weights file.')
1424
+ return None
1425
+ else:
1426
+ print('Found correct weights in the "{}" item of loaded state_dict.'.format(sub_item))
1427
+ model_dict.update(state_dict)
1428
+ model.load_state_dict(model_dict)
1429
+ return model
1430
+
1431
+
1432
+
1433
+ ### models/modules/decoder_blocks.py
1434
+
1435
+ import torch
1436
+ import torch.nn as nn
1437
+ # from models.aspp import ASPP, ASPPDeformable
1438
+ # from config import Config
1439
+
1440
+
1441
+ # config = Config()
1442
+
1443
+
1444
+ class BasicDecBlk(nn.Module):
1445
+ def __init__(self, in_channels=64, out_channels=64, inter_channels=64):
1446
+ super(BasicDecBlk, self).__init__()
1447
+ inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64
1448
+ self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, padding=1)
1449
+ self.relu_in = nn.ReLU(inplace=True)
1450
+ if config.dec_att == 'ASPP':
1451
+ self.dec_att = ASPP(in_channels=inter_channels)
1452
+ elif config.dec_att == 'ASPPDeformable':
1453
+ self.dec_att = ASPPDeformable(in_channels=inter_channels)
1454
+ self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, padding=1)
1455
+ self.bn_in = nn.BatchNorm2d(inter_channels) if config.batch_size > 1 else nn.Identity()
1456
+ self.bn_out = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
1457
+
1458
+ def forward(self, x):
1459
+ x = self.conv_in(x)
1460
+ x = self.bn_in(x)
1461
+ x = self.relu_in(x)
1462
+ if hasattr(self, 'dec_att'):
1463
+ x = self.dec_att(x)
1464
+ x = self.conv_out(x)
1465
+ x = self.bn_out(x)
1466
+ return x
1467
+
1468
+
1469
+ class ResBlk(nn.Module):
1470
+ def __init__(self, in_channels=64, out_channels=None, inter_channels=64):
1471
+ super(ResBlk, self).__init__()
1472
+ if out_channels is None:
1473
+ out_channels = in_channels
1474
+ inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64
1475
+
1476
+ self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, padding=1)
1477
+ self.bn_in = nn.BatchNorm2d(inter_channels) if config.batch_size > 1 else nn.Identity()
1478
+ self.relu_in = nn.ReLU(inplace=True)
1479
+
1480
+ if config.dec_att == 'ASPP':
1481
+ self.dec_att = ASPP(in_channels=inter_channels)
1482
+ elif config.dec_att == 'ASPPDeformable':
1483
+ self.dec_att = ASPPDeformable(in_channels=inter_channels)
1484
+
1485
+ self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, padding=1)
1486
+ self.bn_out = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
1487
+
1488
+ self.conv_resi = nn.Conv2d(in_channels, out_channels, 1, 1, 0)
1489
+
1490
+ def forward(self, x):
1491
+ _x = self.conv_resi(x)
1492
+ x = self.conv_in(x)
1493
+ x = self.bn_in(x)
1494
+ x = self.relu_in(x)
1495
+ if hasattr(self, 'dec_att'):
1496
+ x = self.dec_att(x)
1497
+ x = self.conv_out(x)
1498
+ x = self.bn_out(x)
1499
+ return x + _x
1500
+
1501
+
1502
+
1503
+ ### models/modules/lateral_blocks.py
1504
+
1505
+ import numpy as np
1506
+ import torch
1507
+ import torch.nn as nn
1508
+ import torch.nn.functional as F
1509
+ from functools import partial
1510
+
1511
+ # from config import Config
1512
+
1513
+
1514
+ # config = Config()
1515
+
1516
+
1517
+ class BasicLatBlk(nn.Module):
1518
+ def __init__(self, in_channels=64, out_channels=64, inter_channels=64):
1519
+ super(BasicLatBlk, self).__init__()
1520
+ inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64
1521
+ self.conv = nn.Conv2d(in_channels, out_channels, 1, 1, 0)
1522
+
1523
+ def forward(self, x):
1524
+ x = self.conv(x)
1525
+ return x
1526
+
1527
+
1528
+
1529
+ ### models/modules/aspp.py
1530
+
1531
+ import torch
1532
+ import torch.nn as nn
1533
+ import torch.nn.functional as F
1534
+ # from models.deform_conv import DeformableConv2d
1535
+ # from config import Config
1536
+
1537
+
1538
+ # config = Config()
1539
+
1540
+
1541
+ class _ASPPModule(nn.Module):
1542
+ def __init__(self, in_channels, planes, kernel_size, padding, dilation):
1543
+ super(_ASPPModule, self).__init__()
1544
+ self.atrous_conv = nn.Conv2d(in_channels, planes, kernel_size=kernel_size,
1545
+ stride=1, padding=padding, dilation=dilation, bias=False)
1546
+ self.bn = nn.BatchNorm2d(planes) if config.batch_size > 1 else nn.Identity()
1547
+ self.relu = nn.ReLU(inplace=True)
1548
+
1549
+ def forward(self, x):
1550
+ x = self.atrous_conv(x)
1551
+ x = self.bn(x)
1552
+
1553
+ return self.relu(x)
1554
+
1555
+
1556
+ class ASPP(nn.Module):
1557
+ def __init__(self, in_channels=64, out_channels=None, output_stride=16):
1558
+ super(ASPP, self).__init__()
1559
+ self.down_scale = 1
1560
+ if out_channels is None:
1561
+ out_channels = in_channels
1562
+ self.in_channelster = 256 // self.down_scale
1563
+ if output_stride == 16:
1564
+ dilations = [1, 6, 12, 18]
1565
+ elif output_stride == 8:
1566
+ dilations = [1, 12, 24, 36]
1567
+ else:
1568
+ raise NotImplementedError
1569
+
1570
+ self.aspp1 = _ASPPModule(in_channels, self.in_channelster, 1, padding=0, dilation=dilations[0])
1571
+ self.aspp2 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[1], dilation=dilations[1])
1572
+ self.aspp3 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[2], dilation=dilations[2])
1573
+ self.aspp4 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[3], dilation=dilations[3])
1574
+
1575
+ self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)),
1576
+ nn.Conv2d(in_channels, self.in_channelster, 1, stride=1, bias=False),
1577
+ nn.BatchNorm2d(self.in_channelster) if config.batch_size > 1 else nn.Identity(),
1578
+ nn.ReLU(inplace=True))
1579
+ self.conv1 = nn.Conv2d(self.in_channelster * 5, out_channels, 1, bias=False)
1580
+ self.bn1 = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
1581
+ self.relu = nn.ReLU(inplace=True)
1582
+ self.dropout = nn.Dropout(0.5)
1583
+
1584
+ def forward(self, x):
1585
+ x1 = self.aspp1(x)
1586
+ x2 = self.aspp2(x)
1587
+ x3 = self.aspp3(x)
1588
+ x4 = self.aspp4(x)
1589
+ x5 = self.global_avg_pool(x)
1590
+ x5 = F.interpolate(x5, size=x1.size()[2:], mode='bilinear', align_corners=True)
1591
+ x = torch.cat((x1, x2, x3, x4, x5), dim=1)
1592
+
1593
+ x = self.conv1(x)
1594
+ x = self.bn1(x)
1595
+ x = self.relu(x)
1596
+
1597
+ return self.dropout(x)
1598
+
1599
+
1600
+ ##################### Deformable
1601
+ class _ASPPModuleDeformable(nn.Module):
1602
+ def __init__(self, in_channels, planes, kernel_size, padding):
1603
+ super(_ASPPModuleDeformable, self).__init__()
1604
+ self.atrous_conv = DeformableConv2d(in_channels, planes, kernel_size=kernel_size,
1605
+ stride=1, padding=padding, bias=False)
1606
+ self.bn = nn.BatchNorm2d(planes) if config.batch_size > 1 else nn.Identity()
1607
+ self.relu = nn.ReLU(inplace=True)
1608
+
1609
+ def forward(self, x):
1610
+ x = self.atrous_conv(x)
1611
+ x = self.bn(x)
1612
+
1613
+ return self.relu(x)
1614
+
1615
+
1616
+ class ASPPDeformable(nn.Module):
1617
+ def __init__(self, in_channels, out_channels=None, parallel_block_sizes=[1, 3, 7]):
1618
+ super(ASPPDeformable, self).__init__()
1619
+ self.down_scale = 1
1620
+ if out_channels is None:
1621
+ out_channels = in_channels
1622
+ self.in_channelster = 256 // self.down_scale
1623
+
1624
+ self.aspp1 = _ASPPModuleDeformable(in_channels, self.in_channelster, 1, padding=0)
1625
+ self.aspp_deforms = nn.ModuleList([
1626
+ _ASPPModuleDeformable(in_channels, self.in_channelster, conv_size, padding=int(conv_size//2)) for conv_size in parallel_block_sizes
1627
+ ])
1628
+
1629
+ self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)),
1630
+ nn.Conv2d(in_channels, self.in_channelster, 1, stride=1, bias=False),
1631
+ nn.BatchNorm2d(self.in_channelster) if config.batch_size > 1 else nn.Identity(),
1632
+ nn.ReLU(inplace=True))
1633
+ self.conv1 = nn.Conv2d(self.in_channelster * (2 + len(self.aspp_deforms)), out_channels, 1, bias=False)
1634
+ self.bn1 = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
1635
+ self.relu = nn.ReLU(inplace=True)
1636
+ self.dropout = nn.Dropout(0.5)
1637
+
1638
+ def forward(self, x):
1639
+ x1 = self.aspp1(x)
1640
+ x_aspp_deforms = [aspp_deform(x) for aspp_deform in self.aspp_deforms]
1641
+ x5 = self.global_avg_pool(x)
1642
+ x5 = F.interpolate(x5, size=x1.size()[2:], mode='bilinear', align_corners=True)
1643
+ x = torch.cat((x1, *x_aspp_deforms, x5), dim=1)
1644
+
1645
+ x = self.conv1(x)
1646
+ x = self.bn1(x)
1647
+ x = self.relu(x)
1648
+
1649
+ return self.dropout(x)
1650
+
1651
+
1652
+
1653
+ ### models/refinement/refiner.py
1654
+
1655
+ import torch
1656
+ import torch.nn as nn
1657
+ from collections import OrderedDict
1658
+ import torch
1659
+ import torch.nn as nn
1660
+ import torch.nn.functional as F
1661
+ from torchvision.models import vgg16, vgg16_bn
1662
+ from torchvision.models import resnet50
1663
+
1664
+ # from config import Config
1665
+ # from dataset import class_labels_TR_sorted
1666
+ # from models.build_backbone import build_backbone
1667
+ # from models.decoder_blocks import BasicDecBlk
1668
+ # from models.lateral_blocks import BasicLatBlk
1669
+ # from models.ing import *
1670
+ # from models.stem_layer import StemLayer
1671
+
1672
+
1673
+ class RefinerPVTInChannels4(nn.Module):
1674
+ def __init__(self, in_channels=3+1):
1675
+ super(RefinerPVTInChannels4, self).__init__()
1676
+ self.config = Config()
1677
+ self.epoch = 1
1678
+ self.bb = build_backbone(self.config.bb, params_settings='in_channels=4')
1679
+
1680
+ lateral_channels_in_collection = {
1681
+ 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64],
1682
+ 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64],
1683
+ 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192],
1684
+ }
1685
+ channels = lateral_channels_in_collection[self.config.bb]
1686
+ self.squeeze_module = BasicDecBlk(channels[0], channels[0])
1687
+
1688
+ self.decoder = Decoder(channels)
1689
+
1690
+ if 0:
1691
+ for key, value in self.named_parameters():
1692
+ if 'bb.' in key:
1693
+ value.requires_grad = False
1694
+
1695
+ def forward(self, x):
1696
+ if isinstance(x, list):
1697
+ x = torch.cat(x, dim=1)
1698
+ ########## Encoder ##########
1699
+ if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']:
1700
+ x1 = self.bb.conv1(x)
1701
+ x2 = self.bb.conv2(x1)
1702
+ x3 = self.bb.conv3(x2)
1703
+ x4 = self.bb.conv4(x3)
1704
+ else:
1705
+ x1, x2, x3, x4 = self.bb(x)
1706
+
1707
+ x4 = self.squeeze_module(x4)
1708
+
1709
+ ########## Decoder ##########
1710
+
1711
+ features = [x, x1, x2, x3, x4]
1712
+ scaled_preds = self.decoder(features)
1713
+
1714
+ return scaled_preds
1715
+
1716
+
1717
+ class Refiner(nn.Module):
1718
+ def __init__(self, in_channels=3+1):
1719
+ super(Refiner, self).__init__()
1720
+ self.config = Config()
1721
+ self.epoch = 1
1722
+ self.stem_layer = StemLayer(in_channels=in_channels, inter_channels=48, out_channels=3, norm_layer='BN' if self.config.batch_size > 1 else 'LN')
1723
+ self.bb = build_backbone(self.config.bb)
1724
+
1725
+ lateral_channels_in_collection = {
1726
+ 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64],
1727
+ 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64],
1728
+ 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192],
1729
+ }
1730
+ channels = lateral_channels_in_collection[self.config.bb]
1731
+ self.squeeze_module = BasicDecBlk(channels[0], channels[0])
1732
+
1733
+ self.decoder = Decoder(channels)
1734
+
1735
+ if 0:
1736
+ for key, value in self.named_parameters():
1737
+ if 'bb.' in key:
1738
+ value.requires_grad = False
1739
+
1740
+ def forward(self, x):
1741
+ if isinstance(x, list):
1742
+ x = torch.cat(x, dim=1)
1743
+ x = self.stem_layer(x)
1744
+ ########## Encoder ##########
1745
+ if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']:
1746
+ x1 = self.bb.conv1(x)
1747
+ x2 = self.bb.conv2(x1)
1748
+ x3 = self.bb.conv3(x2)
1749
+ x4 = self.bb.conv4(x3)
1750
+ else:
1751
+ x1, x2, x3, x4 = self.bb(x)
1752
+
1753
+ x4 = self.squeeze_module(x4)
1754
+
1755
+ ########## Decoder ##########
1756
+
1757
+ features = [x, x1, x2, x3, x4]
1758
+ scaled_preds = self.decoder(features)
1759
+
1760
+ return scaled_preds
1761
+
1762
+
1763
+ class Decoder(nn.Module):
1764
+ def __init__(self, channels):
1765
+ super(Decoder, self).__init__()
1766
+ self.config = Config()
1767
+ DecoderBlock = eval('BasicDecBlk')
1768
+ LateralBlock = eval('BasicLatBlk')
1769
+
1770
+ self.decoder_block4 = DecoderBlock(channels[0], channels[1])
1771
+ self.decoder_block3 = DecoderBlock(channels[1], channels[2])
1772
+ self.decoder_block2 = DecoderBlock(channels[2], channels[3])
1773
+ self.decoder_block1 = DecoderBlock(channels[3], channels[3]//2)
1774
+
1775
+ self.lateral_block4 = LateralBlock(channels[1], channels[1])
1776
+ self.lateral_block3 = LateralBlock(channels[2], channels[2])
1777
+ self.lateral_block2 = LateralBlock(channels[3], channels[3])
1778
+
1779
+ if self.config.ms_supervision:
1780
+ self.conv_ms_spvn_4 = nn.Conv2d(channels[1], 1, 1, 1, 0)
1781
+ self.conv_ms_spvn_3 = nn.Conv2d(channels[2], 1, 1, 1, 0)
1782
+ self.conv_ms_spvn_2 = nn.Conv2d(channels[3], 1, 1, 1, 0)
1783
+ self.conv_out1 = nn.Sequential(nn.Conv2d(channels[3]//2, 1, 1, 1, 0))
1784
+
1785
+ def forward(self, features):
1786
+ x, x1, x2, x3, x4 = features
1787
+ outs = []
1788
+ p4 = self.decoder_block4(x4)
1789
+ _p4 = F.interpolate(p4, size=x3.shape[2:], mode='bilinear', align_corners=True)
1790
+ _p3 = _p4 + self.lateral_block4(x3)
1791
+
1792
+ p3 = self.decoder_block3(_p3)
1793
+ _p3 = F.interpolate(p3, size=x2.shape[2:], mode='bilinear', align_corners=True)
1794
+ _p2 = _p3 + self.lateral_block3(x2)
1795
+
1796
+ p2 = self.decoder_block2(_p2)
1797
+ _p2 = F.interpolate(p2, size=x1.shape[2:], mode='bilinear', align_corners=True)
1798
+ _p1 = _p2 + self.lateral_block2(x1)
1799
+
1800
+ _p1 = self.decoder_block1(_p1)
1801
+ _p1 = F.interpolate(_p1, size=x.shape[2:], mode='bilinear', align_corners=True)
1802
+ p1_out = self.conv_out1(_p1)
1803
+
1804
+ if self.config.ms_supervision:
1805
+ outs.append(self.conv_ms_spvn_4(p4))
1806
+ outs.append(self.conv_ms_spvn_3(p3))
1807
+ outs.append(self.conv_ms_spvn_2(p2))
1808
+ outs.append(p1_out)
1809
+ return outs
1810
+
1811
+
1812
+ class RefUNet(nn.Module):
1813
+ # Refinement
1814
+ def __init__(self, in_channels=3+1):
1815
+ super(RefUNet, self).__init__()
1816
+ self.encoder_1 = nn.Sequential(
1817
+ nn.Conv2d(in_channels, 64, 3, 1, 1),
1818
+ nn.Conv2d(64, 64, 3, 1, 1),
1819
+ nn.BatchNorm2d(64),
1820
+ nn.ReLU(inplace=True)
1821
+ )
1822
+
1823
+ self.encoder_2 = nn.Sequential(
1824
+ nn.MaxPool2d(2, 2, ceil_mode=True),
1825
+ nn.Conv2d(64, 64, 3, 1, 1),
1826
+ nn.BatchNorm2d(64),
1827
+ nn.ReLU(inplace=True)
1828
+ )
1829
+
1830
+ self.encoder_3 = nn.Sequential(
1831
+ nn.MaxPool2d(2, 2, ceil_mode=True),
1832
+ nn.Conv2d(64, 64, 3, 1, 1),
1833
+ nn.BatchNorm2d(64),
1834
+ nn.ReLU(inplace=True)
1835
+ )
1836
+
1837
+ self.encoder_4 = nn.Sequential(
1838
+ nn.MaxPool2d(2, 2, ceil_mode=True),
1839
+ nn.Conv2d(64, 64, 3, 1, 1),
1840
+ nn.BatchNorm2d(64),
1841
+ nn.ReLU(inplace=True)
1842
+ )
1843
+
1844
+ self.pool4 = nn.MaxPool2d(2, 2, ceil_mode=True)
1845
+ #####
1846
+ self.decoder_5 = nn.Sequential(
1847
+ nn.Conv2d(64, 64, 3, 1, 1),
1848
+ nn.BatchNorm2d(64),
1849
+ nn.ReLU(inplace=True)
1850
+ )
1851
+ #####
1852
+ self.decoder_4 = nn.Sequential(
1853
+ nn.Conv2d(128, 64, 3, 1, 1),
1854
+ nn.BatchNorm2d(64),
1855
+ nn.ReLU(inplace=True)
1856
+ )
1857
+
1858
+ self.decoder_3 = nn.Sequential(
1859
+ nn.Conv2d(128, 64, 3, 1, 1),
1860
+ nn.BatchNorm2d(64),
1861
+ nn.ReLU(inplace=True)
1862
+ )
1863
+
1864
+ self.decoder_2 = nn.Sequential(
1865
+ nn.Conv2d(128, 64, 3, 1, 1),
1866
+ nn.BatchNorm2d(64),
1867
+ nn.ReLU(inplace=True)
1868
+ )
1869
+
1870
+ self.decoder_1 = nn.Sequential(
1871
+ nn.Conv2d(128, 64, 3, 1, 1),
1872
+ nn.BatchNorm2d(64),
1873
+ nn.ReLU(inplace=True)
1874
+ )
1875
+
1876
+ self.conv_d0 = nn.Conv2d(64, 1, 3, 1, 1)
1877
+
1878
+ self.upscore2 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
1879
+
1880
+ def forward(self, x):
1881
+ outs = []
1882
+ if isinstance(x, list):
1883
+ x = torch.cat(x, dim=1)
1884
+ hx = x
1885
+
1886
+ hx1 = self.encoder_1(hx)
1887
+ hx2 = self.encoder_2(hx1)
1888
+ hx3 = self.encoder_3(hx2)
1889
+ hx4 = self.encoder_4(hx3)
1890
+
1891
+ hx = self.decoder_5(self.pool4(hx4))
1892
+ hx = torch.cat((self.upscore2(hx), hx4), 1)
1893
+
1894
+ d4 = self.decoder_4(hx)
1895
+ hx = torch.cat((self.upscore2(d4), hx3), 1)
1896
+
1897
+ d3 = self.decoder_3(hx)
1898
+ hx = torch.cat((self.upscore2(d3), hx2), 1)
1899
+
1900
+ d2 = self.decoder_2(hx)
1901
+ hx = torch.cat((self.upscore2(d2), hx1), 1)
1902
+
1903
+ d1 = self.decoder_1(hx)
1904
+
1905
+ x = self.conv_d0(d1)
1906
+ outs.append(x)
1907
+ return outs
1908
+
1909
+
1910
+
1911
+ ### models/stem_layer.py
1912
+
1913
+ import torch.nn as nn
1914
+ # from utils import build_act_layer, build_norm_layer
1915
+
1916
+
1917
+ class StemLayer(nn.Module):
1918
+ r""" Stem layer of InternImage
1919
+ Args:
1920
+ in_channels (int): number of input channels
1921
+ out_channels (int): number of output channels
1922
+ act_layer (str): activation layer
1923
+ norm_layer (str): normalization layer
1924
+ """
1925
+
1926
+ def __init__(self,
1927
+ in_channels=3+1,
1928
+ inter_channels=48,
1929
+ out_channels=96,
1930
+ act_layer='GELU',
1931
+ norm_layer='BN'):
1932
+ super().__init__()
1933
+ self.conv1 = nn.Conv2d(in_channels,
1934
+ inter_channels,
1935
+ kernel_size=3,
1936
+ stride=1,
1937
+ padding=1)
1938
+ self.norm1 = build_norm_layer(
1939
+ inter_channels, norm_layer, 'channels_first', 'channels_first'
1940
+ )
1941
+ self.act = build_act_layer(act_layer)
1942
+ self.conv2 = nn.Conv2d(inter_channels,
1943
+ out_channels,
1944
+ kernel_size=3,
1945
+ stride=1,
1946
+ padding=1)
1947
+ self.norm2 = build_norm_layer(
1948
+ out_channels, norm_layer, 'channels_first', 'channels_first'
1949
+ )
1950
+
1951
+ def forward(self, x):
1952
+ x = self.conv1(x)
1953
+ x = self.norm1(x)
1954
+ x = self.act(x)
1955
+ x = self.conv2(x)
1956
+ x = self.norm2(x)
1957
+ return x
1958
+
1959
+
1960
+ ### models/birefnet.py
1961
+
1962
+ import torch
1963
+ import torch.nn as nn
1964
+ import torch.nn.functional as F
1965
+ from kornia.filters import laplacian
1966
+ from transformers import PreTrainedModel
1967
+ from einops import rearrange
1968
+
1969
+ # from config import Config
1970
+ # from dataset import class_labels_TR_sorted
1971
+ # from models.build_backbone import build_backbone
1972
+ # from models.decoder_blocks import BasicDecBlk, ResBlk, HierarAttDecBlk
1973
+ # from models.lateral_blocks import BasicLatBlk
1974
+ # from models.aspp import ASPP, ASPPDeformable
1975
+ # from models.ing import *
1976
+ # from models.refiner import Refiner, RefinerPVTInChannels4, RefUNet
1977
+ # from models.stem_layer import StemLayer
1978
+ from .BiRefNet_config import BiRefNetConfig
1979
+
1980
+
1981
+ def image2patches(image, grid_h=2, grid_w=2, patch_ref=None, transformation='b c (hg h) (wg w) -> (b hg wg) c h w'):
1982
+ if patch_ref is not None:
1983
+ grid_h, grid_w = image.shape[-2] // patch_ref.shape[-2], image.shape[-1] // patch_ref.shape[-1]
1984
+ patches = rearrange(image, transformation, hg=grid_h, wg=grid_w)
1985
+ return patches
1986
+
1987
+ def patches2image(patches, grid_h=2, grid_w=2, patch_ref=None, transformation='(b hg wg) c h w -> b c (hg h) (wg w)'):
1988
+ if patch_ref is not None:
1989
+ grid_h, grid_w = patch_ref.shape[-2] // patches[0].shape[-2], patch_ref.shape[-1] // patches[0].shape[-1]
1990
+ image = rearrange(patches, transformation, hg=grid_h, wg=grid_w)
1991
+ return image
1992
+
1993
+ class BiRefNet(
1994
+ PreTrainedModel
1995
+ ):
1996
+ config_class = BiRefNetConfig
1997
+ def __init__(self, bb_pretrained=True, config=BiRefNetConfig()):
1998
+ super(BiRefNet, self).__init__(config)
1999
+ bb_pretrained = config.bb_pretrained
2000
+ self.config = Config()
2001
+ self.epoch = 1
2002
+ self.bb = build_backbone(self.config.bb, pretrained=bb_pretrained)
2003
+
2004
+ channels = self.config.lateral_channels_in_collection
2005
+
2006
+ if self.config.auxiliary_classification:
2007
+ self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
2008
+ self.cls_head = nn.Sequential(
2009
+ nn.Linear(channels[0], len(class_labels_TR_sorted))
2010
+ )
2011
+
2012
+ if self.config.squeeze_block:
2013
+ self.squeeze_module = nn.Sequential(*[
2014
+ eval(self.config.squeeze_block.split('_x')[0])(channels[0]+sum(self.config.cxt), channels[0])
2015
+ for _ in range(eval(self.config.squeeze_block.split('_x')[1]))
2016
+ ])
2017
+
2018
+ self.decoder = Decoder(channels)
2019
+
2020
+ if self.config.ender:
2021
+ self.dec_end = nn.Sequential(
2022
+ nn.Conv2d(1, 16, 3, 1, 1),
2023
+ nn.Conv2d(16, 1, 3, 1, 1),
2024
+ nn.ReLU(inplace=True),
2025
+ )
2026
+
2027
+ # refine patch-level segmentation
2028
+ if self.config.refine:
2029
+ if self.config.refine == 'itself':
2030
+ self.stem_layer = StemLayer(in_channels=3+1, inter_channels=48, out_channels=3, norm_layer='BN' if self.config.batch_size > 1 else 'LN')
2031
+ else:
2032
+ self.refiner = eval('{}({})'.format(self.config.refine, 'in_channels=3+1'))
2033
+
2034
+ if self.config.freeze_bb:
2035
+ # Freeze the backbone...
2036
+ print(self.named_parameters())
2037
+ for key, value in self.named_parameters():
2038
+ if 'bb.' in key and 'refiner.' not in key:
2039
+ value.requires_grad = False
2040
+
2041
+ def forward_enc(self, x):
2042
+ if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']:
2043
+ x1 = self.bb.conv1(x); x2 = self.bb.conv2(x1); x3 = self.bb.conv3(x2); x4 = self.bb.conv4(x3)
2044
+ else:
2045
+ x1, x2, x3, x4 = self.bb(x)
2046
+ if self.config.mul_scl_ipt == 'cat':
2047
+ B, C, H, W = x.shape
2048
+ x1_, x2_, x3_, x4_ = self.bb(F.interpolate(x, size=(H//2, W//2), mode='bilinear', align_corners=True))
2049
+ x1 = torch.cat([x1, F.interpolate(x1_, size=x1.shape[2:], mode='bilinear', align_corners=True)], dim=1)
2050
+ x2 = torch.cat([x2, F.interpolate(x2_, size=x2.shape[2:], mode='bilinear', align_corners=True)], dim=1)
2051
+ x3 = torch.cat([x3, F.interpolate(x3_, size=x3.shape[2:], mode='bilinear', align_corners=True)], dim=1)
2052
+ x4 = torch.cat([x4, F.interpolate(x4_, size=x4.shape[2:], mode='bilinear', align_corners=True)], dim=1)
2053
+ elif self.config.mul_scl_ipt == 'add':
2054
+ B, C, H, W = x.shape
2055
+ x1_, x2_, x3_, x4_ = self.bb(F.interpolate(x, size=(H//2, W//2), mode='bilinear', align_corners=True))
2056
+ x1 = x1 + F.interpolate(x1_, size=x1.shape[2:], mode='bilinear', align_corners=True)
2057
+ x2 = x2 + F.interpolate(x2_, size=x2.shape[2:], mode='bilinear', align_corners=True)
2058
+ x3 = x3 + F.interpolate(x3_, size=x3.shape[2:], mode='bilinear', align_corners=True)
2059
+ x4 = x4 + F.interpolate(x4_, size=x4.shape[2:], mode='bilinear', align_corners=True)
2060
+ class_preds = self.cls_head(self.avgpool(x4).view(x4.shape[0], -1)) if self.training and self.config.auxiliary_classification else None
2061
+ if self.config.cxt:
2062
+ x4 = torch.cat(
2063
+ (
2064
+ *[
2065
+ F.interpolate(x1, size=x4.shape[2:], mode='bilinear', align_corners=True),
2066
+ F.interpolate(x2, size=x4.shape[2:], mode='bilinear', align_corners=True),
2067
+ F.interpolate(x3, size=x4.shape[2:], mode='bilinear', align_corners=True),
2068
+ ][-len(self.config.cxt):],
2069
+ x4
2070
+ ),
2071
+ dim=1
2072
+ )
2073
+ return (x1, x2, x3, x4), class_preds
2074
+
2075
+ def forward_ori(self, x):
2076
+ ########## Encoder ##########
2077
+ (x1, x2, x3, x4), class_preds = self.forward_enc(x)
2078
+ if self.config.squeeze_block:
2079
+ x4 = self.squeeze_module(x4)
2080
+ ########## Decoder ##########
2081
+ features = [x, x1, x2, x3, x4]
2082
+ if self.training and self.config.out_ref:
2083
+ features.append(laplacian(torch.mean(x, dim=1).unsqueeze(1), kernel_size=5))
2084
+ scaled_preds = self.decoder(features)
2085
+ return scaled_preds, class_preds
2086
+
2087
+ def forward(self, x):
2088
+ scaled_preds, class_preds = self.forward_ori(x)
2089
+ class_preds_lst = [class_preds]
2090
+ return [scaled_preds, class_preds_lst] if self.training else scaled_preds
2091
+
2092
+
2093
+ class Decoder(nn.Module):
2094
+ def __init__(self, channels):
2095
+ super(Decoder, self).__init__()
2096
+ self.config = Config()
2097
+ DecoderBlock = eval(self.config.dec_blk)
2098
+ LateralBlock = eval(self.config.lat_blk)
2099
+
2100
+ if self.config.dec_ipt:
2101
+ self.split = self.config.dec_ipt_split
2102
+ N_dec_ipt = 64
2103
+ DBlock = SimpleConvs
2104
+ ic = 64
2105
+ ipt_cha_opt = 1
2106
+ self.ipt_blk5 = DBlock(2**10*3 if self.split else 3, [N_dec_ipt, channels[0]//8][ipt_cha_opt], inter_channels=ic)
2107
+ self.ipt_blk4 = DBlock(2**8*3 if self.split else 3, [N_dec_ipt, channels[0]//8][ipt_cha_opt], inter_channels=ic)
2108
+ self.ipt_blk3 = DBlock(2**6*3 if self.split else 3, [N_dec_ipt, channels[1]//8][ipt_cha_opt], inter_channels=ic)
2109
+ self.ipt_blk2 = DBlock(2**4*3 if self.split else 3, [N_dec_ipt, channels[2]//8][ipt_cha_opt], inter_channels=ic)
2110
+ self.ipt_blk1 = DBlock(2**0*3 if self.split else 3, [N_dec_ipt, channels[3]//8][ipt_cha_opt], inter_channels=ic)
2111
+ else:
2112
+ self.split = None
2113
+
2114
+ self.decoder_block4 = DecoderBlock(channels[0]+([N_dec_ipt, channels[0]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[1])
2115
+ self.decoder_block3 = DecoderBlock(channels[1]+([N_dec_ipt, channels[0]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[2])
2116
+ self.decoder_block2 = DecoderBlock(channels[2]+([N_dec_ipt, channels[1]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[3])
2117
+ self.decoder_block1 = DecoderBlock(channels[3]+([N_dec_ipt, channels[2]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[3]//2)
2118
+ self.conv_out1 = nn.Sequential(nn.Conv2d(channels[3]//2+([N_dec_ipt, channels[3]//8][ipt_cha_opt] if self.config.dec_ipt else 0), 1, 1, 1, 0))
2119
+
2120
+ self.lateral_block4 = LateralBlock(channels[1], channels[1])
2121
+ self.lateral_block3 = LateralBlock(channels[2], channels[2])
2122
+ self.lateral_block2 = LateralBlock(channels[3], channels[3])
2123
+
2124
+ if self.config.ms_supervision:
2125
+ self.conv_ms_spvn_4 = nn.Conv2d(channels[1], 1, 1, 1, 0)
2126
+ self.conv_ms_spvn_3 = nn.Conv2d(channels[2], 1, 1, 1, 0)
2127
+ self.conv_ms_spvn_2 = nn.Conv2d(channels[3], 1, 1, 1, 0)
2128
+
2129
+ if self.config.out_ref:
2130
+ _N = 16
2131
+ self.gdt_convs_4 = nn.Sequential(nn.Conv2d(channels[1], _N, 3, 1, 1), nn.BatchNorm2d(_N) if self.config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True))
2132
+ self.gdt_convs_3 = nn.Sequential(nn.Conv2d(channels[2], _N, 3, 1, 1), nn.BatchNorm2d(_N) if self.config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True))
2133
+ self.gdt_convs_2 = nn.Sequential(nn.Conv2d(channels[3], _N, 3, 1, 1), nn.BatchNorm2d(_N) if self.config.batch_size > 1 else nn.Identity(), nn.ReLU(inplace=True))
2134
+
2135
+ self.gdt_convs_pred_4 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2136
+ self.gdt_convs_pred_3 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2137
+ self.gdt_convs_pred_2 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2138
+
2139
+ self.gdt_convs_attn_4 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2140
+ self.gdt_convs_attn_3 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2141
+ self.gdt_convs_attn_2 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
2142
+
2143
+ def forward(self, features):
2144
+ if self.training and self.config.out_ref:
2145
+ outs_gdt_pred = []
2146
+ outs_gdt_label = []
2147
+ x, x1, x2, x3, x4, gdt_gt = features
2148
+ else:
2149
+ x, x1, x2, x3, x4 = features
2150
+ outs = []
2151
+
2152
+ if self.config.dec_ipt:
2153
+ patches_batch = image2patches(x, patch_ref=x4, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2154
+ x4 = torch.cat((x4, self.ipt_blk5(F.interpolate(patches_batch, size=x4.shape[2:], mode='bilinear', align_corners=True))), 1)
2155
+ p4 = self.decoder_block4(x4)
2156
+ m4 = self.conv_ms_spvn_4(p4) if self.config.ms_supervision and self.training else None
2157
+ if self.config.out_ref:
2158
+ p4_gdt = self.gdt_convs_4(p4)
2159
+ if self.training:
2160
+ # >> GT:
2161
+ m4_dia = m4
2162
+ gdt_label_main_4 = gdt_gt * F.interpolate(m4_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True)
2163
+ outs_gdt_label.append(gdt_label_main_4)
2164
+ # >> Pred:
2165
+ gdt_pred_4 = self.gdt_convs_pred_4(p4_gdt)
2166
+ outs_gdt_pred.append(gdt_pred_4)
2167
+ gdt_attn_4 = self.gdt_convs_attn_4(p4_gdt).sigmoid()
2168
+ # >> Finally:
2169
+ p4 = p4 * gdt_attn_4
2170
+ _p4 = F.interpolate(p4, size=x3.shape[2:], mode='bilinear', align_corners=True)
2171
+ _p3 = _p4 + self.lateral_block4(x3)
2172
+
2173
+ if self.config.dec_ipt:
2174
+ patches_batch = image2patches(x, patch_ref=_p3, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2175
+ _p3 = torch.cat((_p3, self.ipt_blk4(F.interpolate(patches_batch, size=x3.shape[2:], mode='bilinear', align_corners=True))), 1)
2176
+ p3 = self.decoder_block3(_p3)
2177
+ m3 = self.conv_ms_spvn_3(p3) if self.config.ms_supervision and self.training else None
2178
+ if self.config.out_ref:
2179
+ p3_gdt = self.gdt_convs_3(p3)
2180
+ if self.training:
2181
+ # >> GT:
2182
+ # m3 --dilation--> m3_dia
2183
+ # G_3^gt * m3_dia --> G_3^m, which is the label of gradient
2184
+ m3_dia = m3
2185
+ gdt_label_main_3 = gdt_gt * F.interpolate(m3_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True)
2186
+ outs_gdt_label.append(gdt_label_main_3)
2187
+ # >> Pred:
2188
+ # p3 --conv--BN--> F_3^G, where F_3^G predicts the \hat{G_3} with xx
2189
+ # F_3^G --sigmoid--> A_3^G
2190
+ gdt_pred_3 = self.gdt_convs_pred_3(p3_gdt)
2191
+ outs_gdt_pred.append(gdt_pred_3)
2192
+ gdt_attn_3 = self.gdt_convs_attn_3(p3_gdt).sigmoid()
2193
+ # >> Finally:
2194
+ # p3 = p3 * A_3^G
2195
+ p3 = p3 * gdt_attn_3
2196
+ _p3 = F.interpolate(p3, size=x2.shape[2:], mode='bilinear', align_corners=True)
2197
+ _p2 = _p3 + self.lateral_block3(x2)
2198
+
2199
+ if self.config.dec_ipt:
2200
+ patches_batch = image2patches(x, patch_ref=_p2, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2201
+ _p2 = torch.cat((_p2, self.ipt_blk3(F.interpolate(patches_batch, size=x2.shape[2:], mode='bilinear', align_corners=True))), 1)
2202
+ p2 = self.decoder_block2(_p2)
2203
+ m2 = self.conv_ms_spvn_2(p2) if self.config.ms_supervision and self.training else None
2204
+ if self.config.out_ref:
2205
+ p2_gdt = self.gdt_convs_2(p2)
2206
+ if self.training:
2207
+ # >> GT:
2208
+ m2_dia = m2
2209
+ gdt_label_main_2 = gdt_gt * F.interpolate(m2_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True)
2210
+ outs_gdt_label.append(gdt_label_main_2)
2211
+ # >> Pred:
2212
+ gdt_pred_2 = self.gdt_convs_pred_2(p2_gdt)
2213
+ outs_gdt_pred.append(gdt_pred_2)
2214
+ gdt_attn_2 = self.gdt_convs_attn_2(p2_gdt).sigmoid()
2215
+ # >> Finally:
2216
+ p2 = p2 * gdt_attn_2
2217
+ _p2 = F.interpolate(p2, size=x1.shape[2:], mode='bilinear', align_corners=True)
2218
+ _p1 = _p2 + self.lateral_block2(x1)
2219
+
2220
+ if self.config.dec_ipt:
2221
+ patches_batch = image2patches(x, patch_ref=_p1, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2222
+ _p1 = torch.cat((_p1, self.ipt_blk2(F.interpolate(patches_batch, size=x1.shape[2:], mode='bilinear', align_corners=True))), 1)
2223
+ _p1 = self.decoder_block1(_p1)
2224
+ _p1 = F.interpolate(_p1, size=x.shape[2:], mode='bilinear', align_corners=True)
2225
+
2226
+ if self.config.dec_ipt:
2227
+ patches_batch = image2patches(x, patch_ref=_p1, transformation='b c (hg h) (wg w) -> b (c hg wg) h w') if self.split else x
2228
+ _p1 = torch.cat((_p1, self.ipt_blk1(F.interpolate(patches_batch, size=x.shape[2:], mode='bilinear', align_corners=True))), 1)
2229
+ p1_out = self.conv_out1(_p1)
2230
+
2231
+ if self.config.ms_supervision and self.training:
2232
+ outs.append(m4)
2233
+ outs.append(m3)
2234
+ outs.append(m2)
2235
+ outs.append(p1_out)
2236
+ return outs if not (self.config.out_ref and self.training) else ([outs_gdt_pred, outs_gdt_label], outs)
2237
+
2238
+
2239
+ class SimpleConvs(nn.Module):
2240
+ def __init__(
2241
+ self, in_channels: int, out_channels: int, inter_channels=64
2242
+ ) -> None:
2243
+ super().__init__()
2244
+ self.conv1 = nn.Conv2d(in_channels, inter_channels, 3, 1, 1)
2245
+ self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, 1)
2246
+
2247
+ def forward(self, x):
2248
+ return self.conv_out(self.conv1(x))
config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "ZhengPeng7/BiRefNet_512x512",
3
+ "architectures": [
4
+ "BiRefNet"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "BiRefNet_config.BiRefNetConfig",
8
+ "AutoModelForImageSegmentation": "birefnet.BiRefNet"
9
+ },
10
+ "custom_pipelines": {
11
+ "image-segmentation": {
12
+ "pt": [
13
+ "AutoModelForImageSegmentation"
14
+ ],
15
+ "tf": [],
16
+ "type": "image"
17
+ }
18
+ },
19
+ "bb_pretrained": false
20
+ }
handler.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # These HF deployment codes refer to https://huggingface.co/not-lain/BiRefNet/raw/main/handler.py.
2
+ from typing import Dict, List, Any, Tuple
3
+ import os
4
+ import requests
5
+ from io import BytesIO
6
+ import cv2
7
+ import numpy as np
8
+ from PIL import Image
9
+ import torch
10
+ from torchvision import transforms
11
+ from transformers import AutoModelForImageSegmentation
12
+
13
+ torch.set_float32_matmul_precision(["high", "highest"][0])
14
+
15
+ device = "cuda" if torch.cuda.is_available() else "cpu"
16
+
17
+ ### image_proc.py
18
+ def refine_foreground(image, mask, r=90):
19
+ if mask.size != image.size:
20
+ mask = mask.resize(image.size)
21
+ image = np.array(image) / 255.0
22
+ mask = np.array(mask) / 255.0
23
+ estimated_foreground = FB_blur_fusion_foreground_estimator_2(image, mask, r=r)
24
+ image_masked = Image.fromarray((estimated_foreground * 255.0).astype(np.uint8))
25
+ return image_masked
26
+
27
+
28
+ def FB_blur_fusion_foreground_estimator_2(image, alpha, r=90):
29
+ # Thanks to the source: https://github.com/Photoroom/fast-foreground-estimation
30
+ alpha = alpha[:, :, None]
31
+ F, blur_B = FB_blur_fusion_foreground_estimator(image, image, image, alpha, r)
32
+ return FB_blur_fusion_foreground_estimator(image, F, blur_B, alpha, r=6)[0]
33
+
34
+
35
+ def FB_blur_fusion_foreground_estimator(image, F, B, alpha, r=90):
36
+ if isinstance(image, Image.Image):
37
+ image = np.array(image) / 255.0
38
+ blurred_alpha = cv2.blur(alpha, (r, r))[:, :, None]
39
+
40
+ blurred_FA = cv2.blur(F * alpha, (r, r))
41
+ blurred_F = blurred_FA / (blurred_alpha + 1e-5)
42
+
43
+ blurred_B1A = cv2.blur(B * (1 - alpha), (r, r))
44
+ blurred_B = blurred_B1A / ((1 - blurred_alpha) + 1e-5)
45
+ F = blurred_F + alpha * \
46
+ (image - alpha * blurred_F - (1 - alpha) * blurred_B)
47
+ F = np.clip(F, 0, 1)
48
+ return F, blurred_B
49
+
50
+
51
+ class ImagePreprocessor():
52
+ def __init__(self, resolution: Tuple[int, int] = (1024, 1024)) -> None:
53
+ self.transform_image = transforms.Compose([
54
+ transforms.Resize(resolution),
55
+ transforms.ToTensor(),
56
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
57
+ ])
58
+
59
+ def proc(self, image: Image.Image) -> torch.Tensor:
60
+ image = self.transform_image(image)
61
+ return image
62
+
63
+ usage_to_weights_file = {
64
+ 'General': 'BiRefNet',
65
+ 'General-HR': 'BiRefNet_HR',
66
+ 'General-Lite': 'BiRefNet_lite',
67
+ 'General-Lite-2K': 'BiRefNet_lite-2K',
68
+ 'General-reso_512': 'BiRefNet_512x512',
69
+ 'Matting': 'BiRefNet-matting',
70
+ 'Portrait': 'BiRefNet-portrait',
71
+ 'DIS': 'BiRefNet-DIS5K',
72
+ 'HRSOD': 'BiRefNet-HRSOD',
73
+ 'COD': 'BiRefNet-COD',
74
+ 'DIS-TR_TEs': 'BiRefNet-DIS5K-TR_TEs',
75
+ 'General-legacy': 'BiRefNet-legacy'
76
+ }
77
+
78
+ # Choose the version of BiRefNet here.
79
+ usage = 'General-HR'
80
+
81
+ # Set resolution
82
+ if usage in ['General-Lite-2K']:
83
+ resolution = (2560, 1440)
84
+ elif usage in ['General-reso_512']:
85
+ resolution = (512, 512)
86
+ elif usage in ['General-HR']:
87
+ resolution = (2048, 2048)
88
+ else:
89
+ resolution = (1024, 1024)
90
+
91
+ half_precision = True
92
+
93
+ class EndpointHandler():
94
+ def __init__(self, path=''):
95
+ self.birefnet = AutoModelForImageSegmentation.from_pretrained(
96
+ '/'.join(('zhengpeng7', usage_to_weights_file[usage])), trust_remote_code=True
97
+ )
98
+ self.birefnet.to(device)
99
+ self.birefnet.eval()
100
+ if half_precision:
101
+ self.birefnet.half()
102
+
103
+ def __call__(self, data: Dict[str, Any]):
104
+ """
105
+ data args:
106
+ inputs (:obj: `str`)
107
+ date (:obj: `str`)
108
+ Return:
109
+ A :obj:`list` | `dict`: will be serialized and returned
110
+ """
111
+ print('data["inputs"] = ', data["inputs"])
112
+ image_src = data["inputs"]
113
+ if isinstance(image_src, str):
114
+ if os.path.isfile(image_src):
115
+ image_ori = Image.open(image_src)
116
+ else:
117
+ response = requests.get(image_src)
118
+ image_data = BytesIO(response.content)
119
+ image_ori = Image.open(image_data)
120
+ else:
121
+ image_ori = Image.fromarray(image_src)
122
+
123
+ image = image_ori.convert('RGB')
124
+ # Preprocess the image
125
+ image_preprocessor = ImagePreprocessor(resolution=tuple(resolution))
126
+ image_proc = image_preprocessor.proc(image)
127
+ image_proc = image_proc.unsqueeze(0)
128
+
129
+ # Prediction
130
+ with torch.no_grad():
131
+ preds = self.birefnet(image_proc.to(device).half() if half_precision else image_proc.to(device))[-1].sigmoid().cpu()
132
+ pred = preds[0].squeeze()
133
+
134
+ # Show Results
135
+ pred_pil = transforms.ToPILImage()(pred)
136
+ image_masked = refine_foreground(image, pred_pil)
137
+ image_masked.putalpha(pred_pil.resize(image.size))
138
+ return image_masked
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d94ae0eefb2d2020192001e984ecd6b367478118257a3132e6a484bbf18b0f41
3
+ size 444473596
requirements.txt ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch==2.5.1
2
+ torchvision==0.20.1
3
+ numpy<2
4
+ opencv-python
5
+ timm
6
+ scipy
7
+ scikit-image
8
+ kornia
9
+ einops
10
+
11
+ tqdm
12
+ prettytable
13
+
14
+ transformers
15
+ huggingface-hub>0.25
16
+ accelerate