ZhengPeng7 commited on
Commit
2878079
·
1 Parent(s): 7fee5ed

Intialization of BiRefNet_dynamic.

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