ZhengPeng7 commited on
Commit
2a41a22
1 Parent(s): c49f4c7

For users to load in one key.

Browse files
Files changed (38) hide show
  1. BiRefNet_codes +0 -1
  2. BiRefNet_github/LICENSE +21 -0
  3. BiRefNet_github/README.md +234 -0
  4. BiRefNet_github/config.py +156 -0
  5. BiRefNet_github/dataset.py +112 -0
  6. BiRefNet_github/eval_existingOnes.py +139 -0
  7. BiRefNet_github/evaluation/evaluate.py +60 -0
  8. BiRefNet_github/evaluation/metrics.py +612 -0
  9. BiRefNet_github/evaluation/valid.py +9 -0
  10. BiRefNet_github/gen_best_ep.py +85 -0
  11. BiRefNet_github/inference.py +105 -0
  12. BiRefNet_github/loss.py +274 -0
  13. BiRefNet_github/make_a_copy.sh +18 -0
  14. BiRefNet_github/models/backbones/build_backbone.py +44 -0
  15. BiRefNet_github/models/backbones/pvt_v2.py +435 -0
  16. BiRefNet_github/models/backbones/swin_v1.py +627 -0
  17. BiRefNet_github/models/birefnet.py +287 -0
  18. BiRefNet_github/models/modules/aspp.py +119 -0
  19. BiRefNet_github/models/modules/attentions.py +93 -0
  20. BiRefNet_github/models/modules/decoder_blocks.py +101 -0
  21. BiRefNet_github/models/modules/deform_conv.py +66 -0
  22. BiRefNet_github/models/modules/ing.py +29 -0
  23. BiRefNet_github/models/modules/lateral_blocks.py +21 -0
  24. BiRefNet_github/models/modules/mlp.py +118 -0
  25. BiRefNet_github/models/modules/prompt_encoder.py +222 -0
  26. BiRefNet_github/models/modules/utils.py +54 -0
  27. BiRefNet_github/models/refinement/refiner.py +253 -0
  28. BiRefNet_github/models/refinement/stem_layer.py +45 -0
  29. BiRefNet_github/preproc.py +85 -0
  30. BiRefNet_github/requirements.txt +15 -0
  31. BiRefNet_github/rm_cache.sh +20 -0
  32. BiRefNet_github/sub.sh +19 -0
  33. BiRefNet_github/test.sh +28 -0
  34. BiRefNet_github/train.py +377 -0
  35. BiRefNet_github/train.sh +41 -0
  36. BiRefNet_github/train_test.sh +11 -0
  37. BiRefNet_github/utils.py +97 -0
  38. BiRefNet_github/waiting4eval.py +141 -0
BiRefNet_codes DELETED
@@ -1 +0,0 @@
1
- Subproject commit 6921f57da442c87e2020bf2aea2cee85527be482
 
 
BiRefNet_github/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2024 ZhengPeng
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
BiRefNet_github/README.md ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # <p align=center>`Bilateral Reference for High-Resolution Dichotomous Image Segmentation`</p>
2
+
3
+ | *DIS-Sample_1* | *DIS-Sample_2* |
4
+ | :------------------------------: | :-------------------------------: |
5
+ | <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" /> |
6
+
7
+ This repo is the official implementation of "[**Bilateral Reference for High-Resolution Dichotomous Image Segmentation**](https://arxiv.org/pdf/2401.03407.pdf)" (___arXiv 2024___).
8
+
9
+ > **Authors:**
10
+ > [Peng Zheng](https://scholar.google.com/citations?user=TZRzWOsAAAAJ),
11
+ > [Dehong Gao](https://scholar.google.com/citations?user=0uPb8MMAAAAJ),
12
+ > [Deng-Ping Fan](https://scholar.google.com/citations?user=kakwJ5QAAAAJ),
13
+ > [Li Liu](https://scholar.google.com/citations?user=9cMQrVsAAAAJ),
14
+ > [Jorma Laaksonen](https://scholar.google.com/citations?user=qQP6WXIAAAAJ),
15
+ > [Wanli Ouyang](https://scholar.google.com/citations?user=pw_0Z_UAAAAJ), &
16
+ > [Nicu Sebe](https://scholar.google.com/citations?user=stFCYOAAAAAJ).
17
+
18
+ [[**arXiv**](https://arxiv.org/abs/2401.03407)] [[**code**](https://github.com/ZhengPeng7/BiRefNet)] [[**stuff**](https://drive.google.com/drive/folders/1s2Xe0cjq-2ctnJBR24563yMSCOu4CcxM)] [[**中文版**](https://drive.google.com/file/d/1aBnJ_R9lbnC2dm8dqD0-pzP2Cu-U1Xpt/view?usp=drive_link)]
19
+
20
+ Our BiRefNet has achieved SOTA on many similar HR tasks:
21
+
22
+ **DIS**: [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/bilateral-reference-for-high-resolution/dichotomous-image-segmentation-on-dis-te1)](https://paperswithcode.com/sota/dichotomous-image-segmentation-on-dis-te1?p=bilateral-reference-for-high-resolution) [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/bilateral-reference-for-high-resolution/dichotomous-image-segmentation-on-dis-te2)](https://paperswithcode.com/sota/dichotomous-image-segmentation-on-dis-te2?p=bilateral-reference-for-high-resolution) [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/bilateral-reference-for-high-resolution/dichotomous-image-segmentation-on-dis-te3)](https://paperswithcode.com/sota/dichotomous-image-segmentation-on-dis-te3?p=bilateral-reference-for-high-resolution) [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/bilateral-reference-for-high-resolution/dichotomous-image-segmentation-on-dis-te4)](https://paperswithcode.com/sota/dichotomous-image-segmentation-on-dis-te4?p=bilateral-reference-for-high-resolution) [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/bilateral-reference-for-high-resolution/dichotomous-image-segmentation-on-dis-vd)](https://paperswithcode.com/sota/dichotomous-image-segmentation-on-dis-vd?p=bilateral-reference-for-high-resolution)
23
+
24
+ <details><summary>Figure of Comparison on Papers with Codes (by the time of this work):</summary><p>
25
+ <img src="https://drive.google.com/thumbnail?id=1DLt6CFXdT1QSWDj_6jRkyZINXZ4vmyRp&sz=w1620" />
26
+ <img src="https://drive.google.com/thumbnail?id=1gn5GyKFlJbMIkre1JyEdHDSYcrFmcLD0&sz=w1620" />
27
+ <img src="https://drive.google.com/thumbnail?id=16CVYYOtafEeZhHqv0am2Daku1n_exMP6&sz=w1620" />
28
+ <img src="https://drive.google.com/thumbnail?id=10K45xwPXmaTG4Ex-29ss9payA9yBnyLn&sz=w1620" />
29
+ <img src="https://drive.google.com/thumbnail?id=16EuyqKFJOqwMmagvfnbC9hUurL9pYLLB&sz=w1620" />
30
+ </details>
31
+ <br />
32
+
33
+ **COD**:[![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/bilateral-reference-for-high-resolution/camouflaged-object-segmentation-on-cod)](https://paperswithcode.com/sota/camouflaged-object-segmentation-on-cod?p=bilateral-reference-for-high-resolution) [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/bilateral-reference-for-high-resolution/camouflaged-object-segmentation-on-nc4k)](https://paperswithcode.com/sota/camouflaged-object-segmentation-on-nc4k?p=bilateral-reference-for-high-resolution) [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/bilateral-reference-for-high-resolution/camouflaged-object-segmentation-on-camo)](https://paperswithcode.com/sota/camouflaged-object-segmentation-on-camo?p=bilateral-reference-for-high-resolution) [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/bilateral-reference-for-high-resolution/camouflaged-object-segmentation-on-chameleon)](https://paperswithcode.com/sota/camouflaged-object-segmentation-on-chameleon?p=bilateral-reference-for-high-resolution)
34
+
35
+ <details><summary>Figure of Comparison on Papers with Codes (by the time of this work):</summary><p>
36
+ <img src="https://drive.google.com/thumbnail?id=1DLt6CFXdT1QSWDj_6jRkyZINXZ4vmyRp&sz=w1620" />
37
+ <img src="https://drive.google.com/thumbnail?id=1gn5GyKFlJbMIkre1JyEdHDSYcrFmcLD0&sz=w1620" />
38
+ <img src="https://drive.google.com/thumbnail?id=16CVYYOtafEeZhHqv0am2Daku1n_exMP6&sz=w1620" />
39
+ </details>
40
+ <br />
41
+
42
+ **HRSOD**: [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/bilateral-reference-for-high-resolution/rgb-salient-object-detection-on-davis-s)](https://paperswithcode.com/sota/rgb-salient-object-detection-on-davis-s?p=bilateral-reference-for-high-resolution) [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/bilateral-reference-for-high-resolution/rgb-salient-object-detection-on-hrsod)](https://paperswithcode.com/sota/rgb-salient-object-detection-on-hrsod?p=bilateral-reference-for-high-resolution) [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/bilateral-reference-for-high-resolution/rgb-salient-object-detection-on-uhrsd)](https://paperswithcode.com/sota/rgb-salient-object-detection-on-uhrsd?p=bilateral-reference-for-high-resolution) [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/bilateral-reference-for-high-resolution/salient-object-detection-on-duts-te)](https://paperswithcode.com/sota/salient-object-detection-on-duts-te?p=bilateral-reference-for-high-resolution) [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/bilateral-reference-for-high-resolution/salient-object-detection-on-dut-omron)](https://paperswithcode.com/sota/salient-object-detection-on-dut-omron?p=bilateral-reference-for-high-resolution)
43
+
44
+ <details><summary>Figure of Comparison on Papers with Codes (by the time of this work):</summary><p>
45
+ <img src="https://drive.google.com/thumbnail?id=1hNfQtlTAHT4-AVbk_47852zyRp1NOFLs&sz=w1620" />
46
+ <img src="https://drive.google.com/thumbnail?id=1bcVldUAxYkMI3OMTyaP_jNuOugDfYj-d&sz=w1620" />
47
+ <img src="https://drive.google.com/thumbnail?id=1p1zgyVz27cGEqQMtOKzm_6zoYK3Sw_Zk&sz=w1620" />
48
+ <img src="https://drive.google.com/thumbnail?id=1TubAvcoEbH_mHu3I-AxflnB71nkf35jJ&sz=w1620" />
49
+ <img src="https://drive.google.com/thumbnail?id=1A3V9HjVtcMQdnGPwuy-DBVhwKuo0q2lT&sz=w1620" />
50
+ </details>
51
+ <br />
52
+
53
+ #### Try our online demos for inference:
54
+
55
+ + **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)
56
+ + **Online Inference with GUI** 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)
57
+ + Online **Single 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)
58
+ <img src="https://drive.google.com/thumbnail?id=12XmDhKtO1o2fEvBu4OE4ULVB2BK0ecWi&sz=w1620" />
59
+
60
+
61
+
62
+ ## Model Zoo
63
+
64
+ > For more general use of our BiRefNet, I managed to extend the original adademic one to more general ones for better application in real life.
65
+ >
66
+ > Datasets and datasets are suggested to download from official pages. But you can also download the packaged ones: [DIS](https://drive.google.com/drive/folders/1hZW6tAGPJwo9mPS7qGGGdpxuvuXiyoMJ?usp=drive_link), [HRSOD](https://drive.google.com/drive/folders/18_hAE3QM4cwAzEAKXuSNtKjmgFXTQXZN?usp=drive_link), [COD](https://drive.google.com/drive/folders/1EyHmKWsXfaCR9O0BiZEc3roZbRcs4ECO?usp=drive_link), [Backbones](https://drive.google.com/drive/folders/1cmce_emsS8A5ha5XT2c_CZiJzlLM81ms?usp=drive_link).
67
+ >
68
+ > Find performances (almost all metrics) of all models in the `exp-TASK_SETTINGS` folders in [[**stuff**](https://drive.google.com/drive/folders/1s2Xe0cjq-2ctnJBR24563yMSCOu4CcxM)].
69
+
70
+
71
+
72
+ <details><summary>Models in the original paper, for <b>comparison on benchmarks</b>:</summary><p>
73
+
74
+ | Task | Training Sets | Backbone | Download |
75
+ | :---: | :-------------------------: | :-----------: | :----------------------------------------------------------: |
76
+ | DIS | DIS5K-TR | swin_v1_large | [google-drive](https://drive.google.com/file/d/1J90LucvDQaS3R_-9E7QUh1mgJ8eQvccb/view?usp=drive_link) |
77
+ | COD | COD10K-TR, CAMO-TR | swin_v1_large | [google-drive](https://drive.google.com/file/d/1tM5M72k7a8aKF-dYy-QXaqvfEhbFaWkC/view?usp=drive_link) |
78
+ | HRSOD | DUTS-TR | swin_v1_large | [google-drive](https://drive.google.com/file/d/1f7L0Pb1Y3RkOMbqLCW_zO31dik9AiUFa/view?usp=drive_link) |
79
+ | HRSOD | HRSOD-TR | swin_v1_large | google-drive |
80
+ | HRSOD | UHRSD-TR | swin_v1_large | google-drive |
81
+ | HRSOD | DUTS-TR, HRSOD-TR | swin_v1_large | [google-drive](https://drive.google.com/file/d/1WJooyTkhoDLllaqwbpur_9Hle0XTHEs_/view?usp=drive_link) |
82
+ | HRSOD | DUTS-TR, UHRSD-TR | swin_v1_large | [google-drive](https://drive.google.com/file/d/1Pu1mv3ORobJatIuUoEuZaWDl2ylP3Gw7/view?usp=drive_link) |
83
+ | HRSOD | HRSOD-TR, UHRSD-TR | swin_v1_large | [google-drive](https://drive.google.com/file/d/1xEh7fsgWGaS5c3IffMswasv0_u-aVM9E/view?usp=drive_link) |
84
+ | HRSOD | DUTS-TR, HRSOD-TR, UHRSD-TR | swin_v1_large | [google-drive](https://drive.google.com/file/d/13FaxyyOwyCddfZn2vZo1xG1KNZ3cZ-6B/view?usp=drive_link) |
85
+
86
+ </details>
87
+
88
+
89
+
90
+ <details><summary>Models trained with customed data (massive, portrait), for <b>general use in practical application</b>:</summary>
91
+
92
+ | Task | Training Sets | Backbone | Test Set | Metric (S, wF[, HCE]) | Download |
93
+ | :-----------------------: | :----------------------------------------------------------: | :-----------: | :-------: | :-------------------: | :----------------------------------------------------------: |
94
+ | **general use** | DIS5K-TR,DIS-TEs, DUTS-TR_TE,HRSOD-TR_TE,UHRSD-TR_TE, HRS10K-TR_TE | swin_v1_large | DIS-VD | 0.889, 0.840, 1152 | [google-drive](https://drive.google.com/file/d/1KRVE-U3OHrUuuFPY4FFdE4eYBeHJSA0H/view?usp=drive_link) |
95
+ | **general use** | DIS5K-TR,DIS-TEs, DUTS-TR_TE,HRSOD-TR_TE,UHRSD-TR_TE, HRS10K-TR_TE | swin_v1_tiny | DIS-VD | 0.867, 0.809, 1182 | [Google-drive](https://drive.google.com/file/d/16gDZISjNp7rKi5vsJm6_fbYF8ZBK8AoF/view?usp=drive_link) |
96
+ | **general use** | DIS5K-TR, DIS-TEs | swin_v1_large | DIS-VD | 0.907, 0.865, 1059 | [google-drive](https://drive.google.com/file/d/1P6NJzG3Jf1sl7js2q1CPC3yqvBn_O8UJ/view?usp=drive_link) |
97
+ | **portrait segmentation** | P3M-10k | swin_v1_large | P3M-500-P | 0.982, 0.990 | [google-drive](https://drive.google.com/file/d/1vrjPoOGj05iSxb4MMeznX5k67VlyfZX5/view?usp=drive_link) |
98
+
99
+ </details>
100
+
101
+
102
+
103
+ <details><summary>Segmentation with box <b>guidance</b>:</summary>
104
+
105
+ ​ *In progress...*
106
+
107
+ </details>
108
+
109
+
110
+
111
+ <details><summary>Model <b>efficiency</b>:</summary><p>
112
+
113
+ > Screenshot from the original paper. All tests are conducted on a single A100 GPU.
114
+
115
+ <img src="https://drive.google.com/thumbnail?id=1mTfSD_qt-rFO1t8DRQcyIa5cgWLf1w2-&sz=h300" /> <img src="https://drive.google.com/thumbnail?id=1F_OURIWILVe4u1rSz-aqt6ur__bAef25&sz=h300" />
116
+
117
+ </details>
118
+
119
+
120
+
121
+ ## Third-Party Creations
122
+
123
+ > Concerning edge devices with less computing power, we provide a lightweight version with `swin_v1_tiny` as the backbone, which is x4+ faster and x5+ smaller. The details can be found in [this issue](https://github.com/ZhengPeng7/BiRefNet/issues/11#issuecomment-2041033576) and links there.
124
+
125
+ We found there've been some 3rd party applications based on our BiRefNet. Many thanks for their contribution to the community!
126
+ Choose the one you like to try with clicks instead of codes:
127
+ 1. **Applications**:
128
+ + Thanks [**fal.ai/birefnet**](https://fal.ai/models/birefnet): this project on `fal.ai` encapsulates BiRefNet **online** with more useful options in **UI** and **API** to call the model.
129
+ <p align="center"><img src="https://drive.google.com/thumbnail?id=1rNk81YV_Pzb2GykrzfGvX6T7KBXR0wrA&sz=w1620" /></p>
130
+
131
+ + Thanks [**ZHO-ZHO-ZHO/ComfyUI-BiRefNet-ZHO**](https://github.com/ZHO-ZHO-ZHO/ComfyUI-BiRefNet-ZHO): this project further improves the **UI** for BiRefNet in ComfyUI, especially for **video data**.
132
+ <p align="center"><img src="https://drive.google.com/thumbnail?id=1GOqEreyS7ENzTPN0RqxEjaA76RpMlkYM&sz=w1620" /></p>
133
+
134
+ <https://github.com/ZhengPeng7/BiRefNet/assets/25921713/3a1c7ab2-9847-4dac-8935-43a2d3cd2671>
135
+
136
+ + Thanks [**viperyl/ComfyUI-BiRefNet**](https://github.com/viperyl/ComfyUI-BiRefNet): this project packs BiRefNet as **ComfyUI nodes**, and makes this SOTA model easier use for everyone.
137
+ <p align="center"><img src="https://drive.google.com/thumbnail?id=1KfxCQUUa2y9T-aysEaeVVjCUt3Z0zSkL&sz=w1620" /></p>
138
+
139
+ + Thanks [**Rishabh**](https://github.com/rishabh063) for offerring a demo for the [easier single image inference on colab](https://colab.research.google.com/drive/14Dqg7oeBkFEtchaHLNpig2BcdkZEogba?usp=drive_link).
140
+
141
+ 2. **More Visual Comparisons**
142
+ + Thanks [**twitter.com/ZHOZHO672070**](https://twitter.com/ZHOZHO672070) for the comparison with more background-removal methods in images:
143
+
144
+ <img src="https://drive.google.com/thumbnail?id=1nvVIFt_Ezs-crPSQxUDqkUBz598fTe63&sz=w1620" />
145
+
146
+ + Thanks [**twitter.com/toyxyz3**](https://twitter.com/toyxyz3) for the comparison with more background-removal methods in videos:
147
+
148
+ <https://github.com/ZhengPeng7/BiRefNet/assets/25921713/40136198-01cc-4106-81f9-81c985f02e31>
149
+
150
+ <https://github.com/ZhengPeng7/BiRefNet/assets/25921713/1a32860c-0893-49dd-b557-c2e35a83c160>
151
+
152
+
153
+ ## Usage
154
+
155
+ #### Environment Setup
156
+
157
+ ```shell
158
+ # PyTorch==2.0.1 is used for faster training with compilation.
159
+ conda create -n dis python=3.9 -y && conda activate dis
160
+ pip install -r requirements.txt
161
+ ```
162
+
163
+ #### Dataset Preparation
164
+
165
+ Download combined training / test sets I have organized well from: [DIS](https://drive.google.com/drive/folders/1hZW6tAGPJwo9mPS7qGGGdpxuvuXiyoMJ)--[COD](https://drive.google.com/drive/folders/1EyHmKWsXfaCR9O0BiZEc3roZbRcs4ECO)--[HRSOD](https://drive.google.com/drive/folders/18_hAE3QM4cwAzEAKXuSNtKjmgFXTQXZN) or the single official ones in the `single_ones` folder, or their official pages. You can also find the same ones on my **BaiduDisk**: [DIS](https://pan.baidu.com/s/1O_pQIGAE4DKqL93xOxHpxw?pwd=PSWD)--[COD](https://pan.baidu.com/s/1RnxAzaHSTGBC1N6r_RfeqQ?pwd=PSWD)--[HRSOD](https://pan.baidu.com/s/1_Del53_0lBuG0DKJJAk4UA?pwd=PSWD).
166
+
167
+ #### Weights Preparation
168
+
169
+ Download backbone weights from [my google-drive folder](https://drive.google.com/drive/folders/1s2Xe0cjq-2ctnJBR24563yMSCOu4CcxM) or their official pages.
170
+
171
+ #### Run
172
+
173
+ ```shell
174
+ # Train & Test & Evaluation
175
+ ./train_test.sh RUN_NAME GPU_NUMBERS_FOR_TRAINING GPU_NUMBERS_FOR_TEST
176
+ # See train.sh / test.sh for only training / test-evaluation.
177
+ # After the evluation, run `gen_best_ep.py` to select the best ckpt from a specific metric (you choose it from Sm, wFm, HCE (DIS only)).
178
+ ```
179
+
180
+ #### Well-trained weights:
181
+
182
+ Download the `BiRefNet-{TASK}-{EPOCH}.pth` from [[**stuff**](https://drive.google.com/drive/folders/1s2Xe0cjq-2ctnJBR24563yMSCOu4CcxM)]. Info of the corresponding (predicted\_maps/performance/training\_log) weights can be also found in folders like `exp-BiRefNet-{TASK_SETTINGS}` in the same directory.
183
+
184
+ You can also download the weights from the release of this repo.
185
+
186
+ The results might be a bit different from those in the original paper, you can see them in the `eval_results-BiRefNet-{TASK_SETTINGS}` folder in each `exp-xx`, we will update them in the following days. Due to the very high cost I used (A100-80G x 8) which many people cannot afford to (including myself....), I re-trained BiRefNet on a single A100-40G only and achieve the performance on the same level (even better). It means you can directly train the model on a single GPU with 36.5G+ memory. BTW, 5.5G GPU memory is needed for inference in 1024x1024. (I personally paid a lot for renting an A100-40G to re-train BiRefNet on the three tasks... T_T. Hope it can help you.)
187
+
188
+ But if you have more and more powerful GPUs, you can set GPU IDs and increase the batch size in `config.py` to accelerate the training. We have made all this kind of things adaptive in scripts to seamlessly switch between single-card training and multi-card training. Enjoy it :)
189
+
190
+ #### Some of my messages:
191
+
192
+ This project was originally built for DIS only. But after the updates one by one, I made it larger and larger with many functions embedded together. Finally, you can **use it for any binary image segmentation tasks**, such as DIS/COD/SOD, medical image segmentation, anomaly segmentation, etc. You can eaily open/close below things (usually in `config.py`):
193
+ + Multi-GPU training: open/close with one variable.
194
+ + Backbone choices: Swin_v1, PVT_v2, ConvNets, ...
195
+ + Weighted losses: BCE, IoU, SSIM, MAE, Reg, ...
196
+ + Adversarial loss for binary segmentation (proposed in my previous work [MCCL](https://arxiv.org/pdf/2302.14485.pdf)).
197
+ + Training tricks: multi-scale supervision, freezing backbone, multi-scale input...
198
+ + Data collator: loading all in memory, smooth combination of different datasets for combined training and test.
199
+ + ...
200
+ I really hope you enjoy this project and use it in more works to achieve new SOTAs.
201
+
202
+
203
+ ### Quantitative Results
204
+
205
+ <p align="center"><img src="https://drive.google.com/thumbnail?id=184e84BwLuNu1FytSAQ2EnANZ0RFHKPip&sz=w1620" /></p>
206
+
207
+ <p align="center"><img src="https://drive.google.com/thumbnail?id=1W0mi0ZiYbqsaGuohNXU8Gh7Zj4M3neFg&sz=w1620" /></p>
208
+
209
+
210
+
211
+ ### Qualitative Results
212
+
213
+ <p align="center"><img src="https://drive.google.com/thumbnail?id=1TYZF8pVZc2V0V6g3ik4iAr9iKvJ8BNrf&sz=w1620" /></p>
214
+
215
+ <p align="center"><img src="https://drive.google.com/thumbnail?id=1ZGHC32CAdT9cwRloPzOCKWCrVQZvUAlJ&sz=w1620" /></p>
216
+
217
+
218
+
219
+ ### Citation
220
+
221
+ ```
222
+ @article{zheng2024birefnet,
223
+ title={Bilateral Reference for High-Resolution Dichotomous Image Segmentation},
224
+ author={Zheng, Peng and Gao, Dehong and Fan, Deng-Ping and Liu, Li and Laaksonen, Jorma and Ouyang, Wanli and Sebe, Nicu},
225
+ journal={arXiv},
226
+ year={2024}
227
+ }
228
+ ```
229
+
230
+
231
+
232
+ ## Contact
233
+
234
+ Any question, discussion or even complaint, feel free to leave issues here or send me e-mails (zhengpeng0108@gmail.com).
BiRefNet_github/config.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import math
3
+
4
+
5
+ class Config():
6
+ def __init__(self) -> None:
7
+ # PATH settings
8
+ self.sys_home_dir = os.environ['HOME'] # Make up your file system as: SYS_HOME_DIR/codes/dis/BiRefNet, SYS_HOME_DIR/datasets/dis/xx, SYS_HOME_DIR/weights/xx
9
+
10
+ # TASK settings
11
+ self.task = ['DIS5K', 'COD', 'HRSOD', 'DIS5K+HRSOD+HRS10K', 'P3M-10k'][0]
12
+ self.training_set = {
13
+ 'DIS5K': ['DIS-TR', 'DIS-TR+DIS-TE1+DIS-TE2+DIS-TE3+DIS-TE4'][0],
14
+ 'COD': 'TR-COD10K+TR-CAMO',
15
+ '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],
16
+ '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.
17
+ 'P3M-10k': 'TR-P3M-10k',
18
+ }[self.task]
19
+ self.prompt4loc = ['dense', 'sparse'][0]
20
+
21
+ # Faster-Training settings
22
+ self.load_all = True
23
+ self.compile = True # 1. Trigger CPU memory leak in some extend, which is an inherent problem of PyTorch.
24
+ # Machines with > 70GB CPU memory can run the whole training on DIS5K with default setting.
25
+ # 2. Higher PyTorch version may fix it: https://github.com/pytorch/pytorch/issues/119607.
26
+ # 3. But compile in Pytorch > 2.0.1 seems to bring no acceleration for training.
27
+ self.precisionHigh = True
28
+
29
+ # MODEL settings
30
+ self.ms_supervision = True
31
+ self.out_ref = self.ms_supervision and True
32
+ self.dec_ipt = True
33
+ self.dec_ipt_split = True
34
+ self.cxt_num = [0, 3][1] # multi-scale skip connections from encoder
35
+ self.mul_scl_ipt = ['', 'add', 'cat'][2]
36
+ self.dec_att = ['', 'ASPP', 'ASPPDeformable'][2]
37
+ self.squeeze_block = ['', 'BasicDecBlk_x1', 'ResBlk_x4', 'ASPP_x3', 'ASPPDeformable_x3'][1]
38
+ self.dec_blk = ['BasicDecBlk', 'ResBlk', 'HierarAttDecBlk'][0]
39
+
40
+ # TRAINING settings
41
+ self.batch_size = 4
42
+ self.IoU_finetune_last_epochs = [
43
+ 0,
44
+ {
45
+ 'DIS5K': -50,
46
+ 'COD': -20,
47
+ 'HRSOD': -20,
48
+ 'DIS5K+HRSOD+HRS10K': -20,
49
+ 'P3M-10k': -20,
50
+ }[self.task]
51
+ ][1] # choose 0 to skip
52
+ 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
53
+ self.size = 1024
54
+ self.num_workers = max(4, self.batch_size) # will be decrease to min(it, batch_size) at the initialization of the data_loader
55
+
56
+ # Backbone settings
57
+ self.bb = [
58
+ 'vgg16', 'vgg16bn', 'resnet50', # 0, 1, 2
59
+ 'swin_v1_t', 'swin_v1_s', # 3, 4
60
+ 'swin_v1_b', 'swin_v1_l', # 5-bs9, 6-bs4
61
+ 'pvt_v2_b0', 'pvt_v2_b1', # 7, 8
62
+ 'pvt_v2_b2', 'pvt_v2_b5', # 9-bs10, 10-bs5
63
+ ][6]
64
+ self.lateral_channels_in_collection = {
65
+ 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64],
66
+ 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64],
67
+ 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192],
68
+ 'swin_v1_t': [768, 384, 192, 96], 'swin_v1_s': [768, 384, 192, 96],
69
+ 'pvt_v2_b0': [256, 160, 64, 32], 'pvt_v2_b1': [512, 320, 128, 64],
70
+ }[self.bb]
71
+ if self.mul_scl_ipt == 'cat':
72
+ self.lateral_channels_in_collection = [channel * 2 for channel in self.lateral_channels_in_collection]
73
+ self.cxt = self.lateral_channels_in_collection[1:][::-1][-self.cxt_num:] if self.cxt_num else []
74
+
75
+ # MODEL settings - inactive
76
+ self.lat_blk = ['BasicLatBlk'][0]
77
+ self.dec_channels_inter = ['fixed', 'adap'][0]
78
+ self.refine = ['', 'itself', 'RefUNet', 'Refiner', 'RefinerPVTInChannels4'][0]
79
+ self.progressive_ref = self.refine and True
80
+ self.ender = self.progressive_ref and False
81
+ self.scale = self.progressive_ref and 2
82
+ self.auxiliary_classification = False # Only for DIS5K, where class labels are saved in `dataset.py`.
83
+ self.refine_iteration = 1
84
+ self.freeze_bb = False
85
+ self.model = [
86
+ 'BiRefNet',
87
+ ][0]
88
+ if self.dec_blk == 'HierarAttDecBlk':
89
+ self.batch_size = 2 ** [0, 1, 2, 3, 4][2]
90
+
91
+ # TRAINING settings - inactive
92
+ self.preproc_methods = ['flip', 'enhance', 'rotate', 'pepper', 'crop'][:4]
93
+ self.optimizer = ['Adam', 'AdamW'][1]
94
+ self.lr_decay_epochs = [1e5] # Set to negative N to decay the lr in the last N-th epoch.
95
+ self.lr_decay_rate = 0.5
96
+ # Loss
97
+ self.lambdas_pix_last = {
98
+ # not 0 means opening this loss
99
+ # original rate -- 1 : 30 : 1.5 : 0.2, bce x 30
100
+ 'bce': 30 * 1, # high performance
101
+ 'iou': 0.5 * 1, # 0 / 255
102
+ 'iou_patch': 0.5 * 0, # 0 / 255, win_size = (64, 64)
103
+ 'mse': 150 * 0, # can smooth the saliency map
104
+ 'triplet': 3 * 0,
105
+ 'reg': 100 * 0,
106
+ 'ssim': 10 * 1, # help contours,
107
+ 'cnt': 5 * 0, # help contours
108
+ '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.
109
+ }
110
+ self.lambdas_cls = {
111
+ 'ce': 5.0
112
+ }
113
+ # Adv
114
+ self.lambda_adv_g = 10. * 0 # turn to 0 to avoid adv training
115
+ self.lambda_adv_d = 3. * (self.lambda_adv_g > 0)
116
+
117
+ # PATH settings - inactive
118
+ self.data_root_dir = os.path.join(self.sys_home_dir, 'datasets/dis')
119
+ self.weights_root_dir = os.path.join(self.sys_home_dir, 'weights')
120
+ self.weights = {
121
+ 'pvt_v2_b2': os.path.join(self.weights_root_dir, 'pvt_v2_b2.pth'),
122
+ 'pvt_v2_b5': os.path.join(self.weights_root_dir, ['pvt_v2_b5.pth', 'pvt_v2_b5_22k.pth'][0]),
123
+ '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]),
124
+ '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]),
125
+ 'swin_v1_t': os.path.join(self.weights_root_dir, ['swin_tiny_patch4_window7_224_22kto1k_finetune.pth'][0]),
126
+ 'swin_v1_s': os.path.join(self.weights_root_dir, ['swin_small_patch4_window7_224_22kto1k_finetune.pth'][0]),
127
+ 'pvt_v2_b0': os.path.join(self.weights_root_dir, ['pvt_v2_b0.pth'][0]),
128
+ 'pvt_v2_b1': os.path.join(self.weights_root_dir, ['pvt_v2_b1.pth'][0]),
129
+ }
130
+
131
+ # Callbacks - inactive
132
+ self.verbose_eval = True
133
+ self.only_S_MAE = False
134
+ self.use_fp16 = False # Bugs. It may cause nan in training.
135
+ self.SDPA_enabled = False # Bugs. Slower and errors occur in multi-GPUs
136
+
137
+ # others
138
+ self.device = [0, 'cpu'][0] # .to(0) == .to('cuda:0')
139
+
140
+ self.batch_size_valid = 1
141
+ self.rand_seed = 7
142
+ 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]
143
+ with open(run_sh_file[0], 'r') as f:
144
+ lines = f.readlines()
145
+ 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])
146
+ 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])
147
+ self.val_step = [0, self.save_step][0]
148
+
149
+ def print_task(self) -> None:
150
+ # Return task for choosing settings in shell scripts.
151
+ print(self.task)
152
+
153
+ if __name__ == '__main__':
154
+ config = Config()
155
+ config.print_task()
156
+
BiRefNet_github/dataset.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ from tqdm import tqdm
4
+ from PIL import Image
5
+ from torch.utils import data
6
+ from torchvision import transforms
7
+
8
+ from preproc import preproc
9
+ from config import Config
10
+ from utils import path_to_image
11
+
12
+
13
+ Image.MAX_IMAGE_PIXELS = None # remove DecompressionBombWarning
14
+ config = Config()
15
+ _class_labels_TR_sorted = (
16
+ 'Airplane, Ant, Antenna, Archery, Axe, BabyCarriage, Bag, BalanceBeam, Balcony, Balloon, Basket, BasketballHoop, Beatle, Bed, Bee, Bench, Bicycle, '
17
+ 'BicycleFrame, BicycleStand, Boat, Bonsai, BoomLift, Bridge, BunkBed, Butterfly, Button, Cable, CableLift, Cage, Camcorder, Cannon, Canoe, Car, '
18
+ 'CarParkDropArm, Carriage, Cart, Caterpillar, CeilingLamp, Centipede, Chair, Clip, Clock, Clothes, CoatHanger, Comb, ConcretePumpTruck, Crack, Crane, '
19
+ 'Cup, DentalChair, Desk, DeskChair, Diagram, DishRack, DoorHandle, Dragonfish, Dragonfly, Drum, Earphone, Easel, ElectricIron, Excavator, Eyeglasses, '
20
+ 'Fan, Fence, Fencing, FerrisWheel, FireExtinguisher, Fishing, Flag, FloorLamp, Forklift, GasStation, Gate, Gear, Goal, Golf, GymEquipment, Hammock, '
21
+ 'Handcart, Handcraft, Handrail, HangGlider, Harp, Harvester, Headset, Helicopter, Helmet, Hook, HorizontalBar, Hydrovalve, IroningTable, Jewelry, Key, '
22
+ 'KidsPlayground, Kitchenware, Kite, Knife, Ladder, LaundryRack, Lightning, Lobster, Locust, Machine, MachineGun, MagazineRack, Mantis, Medal, MemorialArchway, '
23
+ 'Microphone, Missile, MobileHolder, Monitor, Mosquito, Motorcycle, MovingTrolley, Mower, MusicPlayer, MusicStand, ObservationTower, Octopus, OilWell, '
24
+ 'OlympicLogo, OperatingTable, OutdoorFitnessEquipment, Parachute, Pavilion, Piano, Pipe, PlowHarrow, PoleVault, Punchbag, Rack, Racket, Rifle, Ring, Robot, '
25
+ 'RockClimbing, Rope, Sailboat, Satellite, Scaffold, Scale, Scissor, Scooter, Sculpture, Seadragon, Seahorse, Seal, SewingMachine, Ship, Shoe, ShoppingCart, '
26
+ 'ShoppingTrolley, Shower, Shrimp, Signboard, Skateboarding, Skeleton, Skiing, Spade, SpeedBoat, Spider, Spoon, Stair, Stand, Stationary, SteeringWheel, '
27
+ 'Stethoscope, Stool, Stove, StreetLamp, SweetStand, Swing, Sword, TV, Table, TableChair, TableLamp, TableTennis, Tank, Tapeline, Teapot, Telescope, Tent, '
28
+ 'TobaccoPipe, Toy, Tractor, TrafficLight, TrafficSign, Trampoline, TransmissionTower, Tree, Tricycle, TrimmerCover, Tripod, Trombone, Truck, Trumpet, Tuba, '
29
+ 'UAV, Umbrella, UnevenBars, UtilityPole, VacuumCleaner, Violin, Wakesurfing, Watch, WaterTower, WateringPot, Well, WellLid, Wheel, Wheelchair, WindTurbine, Windmill, WineGlass, WireWhisk, Yacht'
30
+ )
31
+ class_labels_TR_sorted = _class_labels_TR_sorted.split(', ')
32
+
33
+
34
+ class MyData(data.Dataset):
35
+ def __init__(self, datasets, image_size, is_train=True):
36
+ self.size_train = image_size
37
+ self.size_test = image_size
38
+ self.keep_size = not config.size
39
+ self.data_size = (config.size, config.size)
40
+ self.is_train = is_train
41
+ self.load_all = config.load_all
42
+ self.device = config.device
43
+ if self.is_train and config.auxiliary_classification:
44
+ self.cls_name2id = {_name: _id for _id, _name in enumerate(class_labels_TR_sorted)}
45
+ self.transform_image = transforms.Compose([
46
+ transforms.Resize(self.data_size),
47
+ transforms.ToTensor(),
48
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
49
+ ][self.load_all or self.keep_size:])
50
+ self.transform_label = transforms.Compose([
51
+ transforms.Resize(self.data_size),
52
+ transforms.ToTensor(),
53
+ ][self.load_all or self.keep_size:])
54
+ dataset_root = os.path.join(config.data_root_dir, config.task)
55
+ # datasets can be a list of different datasets for training on combined sets.
56
+ self.image_paths = []
57
+ for dataset in datasets.split('+'):
58
+ image_root = os.path.join(dataset_root, dataset, 'im')
59
+ self.image_paths += [os.path.join(image_root, p) for p in os.listdir(image_root)]
60
+ self.label_paths = []
61
+ for p in self.image_paths:
62
+ for ext in ['.png', '.jpg', '.PNG', '.JPG', '.JPEG']:
63
+ ## 'im' and 'gt' may need modifying
64
+ p_gt = p.replace('/im/', '/gt/')[:-(len(p.split('.')[-1])+1)] + ext
65
+ file_exists = False
66
+ if os.path.exists(p_gt):
67
+ self.label_paths.append(p_gt)
68
+ file_exists = True
69
+ break
70
+ if not file_exists:
71
+ print('Not exists:', p_gt)
72
+ if self.load_all:
73
+ self.images_loaded, self.labels_loaded = [], []
74
+ self.class_labels_loaded = []
75
+ # for image_path, label_path in zip(self.image_paths, self.label_paths):
76
+ for image_path, label_path in tqdm(zip(self.image_paths, self.label_paths), total=len(self.image_paths)):
77
+ _image = path_to_image(image_path, size=(config.size, config.size), color_type='rgb')
78
+ _label = path_to_image(label_path, size=(config.size, config.size), color_type='gray')
79
+ self.images_loaded.append(_image)
80
+ self.labels_loaded.append(_label)
81
+ self.class_labels_loaded.append(
82
+ self.cls_name2id[label_path.split('/')[-1].split('#')[3]] if self.is_train and config.auxiliary_classification else -1
83
+ )
84
+
85
+ def __getitem__(self, index):
86
+
87
+ if self.load_all:
88
+ image = self.images_loaded[index]
89
+ label = self.labels_loaded[index]
90
+ class_label = self.class_labels_loaded[index] if self.is_train and config.auxiliary_classification else -1
91
+ else:
92
+ image = path_to_image(self.image_paths[index], size=(config.size, config.size), color_type='rgb')
93
+ label = path_to_image(self.label_paths[index], size=(config.size, config.size), color_type='gray')
94
+ class_label = self.cls_name2id[self.label_paths[index].split('/')[-1].split('#')[3]] if self.is_train and config.auxiliary_classification else -1
95
+
96
+ # loading image and label
97
+ if self.is_train:
98
+ image, label = preproc(image, label, preproc_methods=config.preproc_methods)
99
+ # else:
100
+ # if _label.shape[0] > 2048 or _label.shape[1] > 2048:
101
+ # _image = cv2.resize(_image, (2048, 2048), interpolation=cv2.INTER_LINEAR)
102
+ # _label = cv2.resize(_label, (2048, 2048), interpolation=cv2.INTER_LINEAR)
103
+
104
+ image, label = self.transform_image(image), self.transform_label(label)
105
+
106
+ if self.is_train:
107
+ return image, label, class_label
108
+ else:
109
+ return image, label, self.label_paths[index]
110
+
111
+ def __len__(self):
112
+ return len(self.image_paths)
BiRefNet_github/eval_existingOnes.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import argparse
3
+ from glob import glob
4
+ import prettytable as pt
5
+
6
+ from evaluation.evaluate import evaluator
7
+ from config import Config
8
+
9
+
10
+ config = Config()
11
+
12
+
13
+ def do_eval(args):
14
+ # evaluation for whole dataset
15
+ # dataset first in evaluation
16
+ for _data_name in args.data_lst.split('+'):
17
+ pred_data_dir = sorted(glob(os.path.join(args.pred_root, args.model_lst[0], _data_name)))
18
+ if not pred_data_dir:
19
+ print('Skip dataset {}.'.format(_data_name))
20
+ continue
21
+ gt_src = os.path.join(args.gt_root, _data_name)
22
+ gt_paths = sorted(glob(os.path.join(gt_src, 'gt', '*')))
23
+ print('#' * 20, _data_name, '#' * 20)
24
+ filename = os.path.join(args.save_dir, '{}_eval.txt'.format(_data_name))
25
+ tb = pt.PrettyTable()
26
+ tb.vertical_char = '&'
27
+ if config.task == 'DIS5K':
28
+ tb.field_names = ["Dataset", "Method", "maxFm", "wFmeasure", 'MAE', "Smeasure", "meanEm", "HCE", "maxEm", "meanFm", "adpEm", "adpFm"]
29
+ elif config.task == 'COD':
30
+ tb.field_names = ["Dataset", "Method", "Smeasure", "wFmeasure", "meanFm", "meanEm", "maxEm", 'MAE', "maxFm", "adpEm", "adpFm", "HCE"]
31
+ elif config.task == 'HRSOD':
32
+ tb.field_names = ["Dataset", "Method", "Smeasure", "maxFm", "meanEm", 'MAE', "maxEm", "meanFm", "wFmeasure", "adpEm", "adpFm", "HCE"]
33
+ elif config.task == 'DIS5K+HRSOD+HRS10K':
34
+ tb.field_names = ["Dataset", "Method", "maxFm", "wFmeasure", 'MAE', "Smeasure", "meanEm", "HCE", "maxEm", "meanFm", "adpEm", "adpFm"]
35
+ elif config.task == 'P3M-10k':
36
+ tb.field_names = ["Dataset", "Method", "Smeasure", "maxFm", "meanEm", 'MAE', "maxEm", "meanFm", "wFmeasure", "adpEm", "adpFm", "HCE"]
37
+ else:
38
+ tb.field_names = ["Dataset", "Method", "Smeasure", 'MAE', "maxEm", "meanEm", "maxFm", "meanFm", "wFmeasure", "adpEm", "adpFm", "HCE"]
39
+ for _model_name in args.model_lst[:]:
40
+ print('\t', 'Evaluating model: {}...'.format(_model_name))
41
+ pred_paths = [p.replace(args.gt_root, os.path.join(args.pred_root, _model_name)).replace('/gt/', '/') for p in gt_paths]
42
+ # print(pred_paths[:1], gt_paths[:1])
43
+ em, sm, fm, mae, wfm, hce = evaluator(
44
+ gt_paths=gt_paths,
45
+ pred_paths=pred_paths,
46
+ metrics=args.metrics.split('+'),
47
+ verbose=config.verbose_eval
48
+ )
49
+ if config.task == 'DIS5K':
50
+ scores = [
51
+ fm['curve'].max().round(3), wfm.round(3), mae.round(3), sm.round(3), em['curve'].mean().round(3), int(hce.round()),
52
+ em['curve'].max().round(3), fm['curve'].mean().round(3), em['adp'].round(3), fm['adp'].round(3),
53
+ ]
54
+ elif config.task == 'COD':
55
+ scores = [
56
+ sm.round(3), wfm.round(3), fm['curve'].mean().round(3), em['curve'].mean().round(3), em['curve'].max().round(3), mae.round(3),
57
+ fm['curve'].max().round(3), em['adp'].round(3), fm['adp'].round(3), int(hce.round()),
58
+ ]
59
+ elif config.task == 'HRSOD':
60
+ scores = [
61
+ sm.round(3), fm['curve'].max().round(3), em['curve'].mean().round(3), mae.round(3),
62
+ em['curve'].max().round(3), fm['curve'].mean().round(3), wfm.round(3), em['adp'].round(3), fm['adp'].round(3), int(hce.round()),
63
+ ]
64
+ elif config.task == 'DIS5K+HRSOD+HRS10K':
65
+ scores = [
66
+ fm['curve'].max().round(3), wfm.round(3), mae.round(3), sm.round(3), em['curve'].mean().round(3), int(hce.round()),
67
+ em['curve'].max().round(3), fm['curve'].mean().round(3), em['adp'].round(3), fm['adp'].round(3),
68
+ ]
69
+ elif config.task == 'P3M-10k':
70
+ scores = [
71
+ sm.round(3), fm['curve'].max().round(3), em['curve'].mean().round(3), mae.round(3),
72
+ em['curve'].max().round(3), fm['curve'].mean().round(3), wfm.round(3), em['adp'].round(3), fm['adp'].round(3), int(hce.round()),
73
+ ]
74
+ else:
75
+ scores = [
76
+ sm.round(3), mae.round(3), em['curve'].max().round(3), em['curve'].mean().round(3),
77
+ fm['curve'].max().round(3), fm['curve'].mean().round(3), wfm.round(3),
78
+ em['adp'].round(3), fm['adp'].round(3), int(hce.round()),
79
+ ]
80
+
81
+ for idx_score, score in enumerate(scores):
82
+ scores[idx_score] = '.' + format(score, '.3f').split('.')[-1] if score <= 1 else format(score, '<4')
83
+ records = [_data_name, _model_name] + scores
84
+ tb.add_row(records)
85
+ # Write results after every check.
86
+ with open(filename, 'w+') as file_to_write:
87
+ file_to_write.write(str(tb)+'\n')
88
+ print(tb)
89
+
90
+
91
+ if __name__ == '__main__':
92
+ # set parameters
93
+ parser = argparse.ArgumentParser()
94
+ parser.add_argument(
95
+ '--gt_root', type=str, help='ground-truth root',
96
+ default=os.path.join(config.data_root_dir, config.task))
97
+ parser.add_argument(
98
+ '--pred_root', type=str, help='prediction root',
99
+ default='./e_preds')
100
+ parser.add_argument(
101
+ '--data_lst', type=str, help='test dataset',
102
+ default={
103
+ 'DIS5K': '+'.join(['DIS-VD', 'DIS-TE1', 'DIS-TE2', 'DIS-TE3', 'DIS-TE4'][:]),
104
+ 'COD': '+'.join(['TE-COD10K', 'NC4K', 'TE-CAMO', 'CHAMELEON'][:]),
105
+ 'HRSOD': '+'.join(['DAVIS-S', 'TE-HRSOD', 'TE-UHRSD', 'TE-DUTS', 'DUT-OMRON'][:]),
106
+ 'DIS5K+HRSOD+HRS10K': '+'.join(['DIS-VD'][:]),
107
+ 'P3M-10k': '+'.join(['TE-P3M-500-P', 'TE-P3M-500-NP'][:]),
108
+ }[config.task])
109
+ parser.add_argument(
110
+ '--save_dir', type=str, help='candidate competitors',
111
+ default='e_results')
112
+ parser.add_argument(
113
+ '--check_integrity', type=bool, help='whether to check the file integrity',
114
+ default=False)
115
+ parser.add_argument(
116
+ '--metrics', type=str, help='candidate competitors',
117
+ default='+'.join(['S', 'MAE', 'E', 'F', 'WF', 'HCE'][:100 if 'DIS5K' in config.task else -1]))
118
+ args = parser.parse_args()
119
+
120
+ os.makedirs(args.save_dir, exist_ok=True)
121
+ try:
122
+ args.model_lst = [m for m in sorted(os.listdir(args.pred_root), key=lambda x: int(x.split('epoch_')[-1]), reverse=True) if int(m.split('epoch_')[-1]) % 1 == 0]
123
+ except:
124
+ args.model_lst = [m for m in sorted(os.listdir(args.pred_root))]
125
+
126
+ # check the integrity of each candidates
127
+ if args.check_integrity:
128
+ for _data_name in args.data_lst.split('+'):
129
+ for _model_name in args.model_lst:
130
+ gt_pth = os.path.join(args.gt_root, _data_name)
131
+ pred_pth = os.path.join(args.pred_root, _model_name, _data_name)
132
+ if not sorted(os.listdir(gt_pth)) == sorted(os.listdir(pred_pth)):
133
+ print(len(sorted(os.listdir(gt_pth))), len(sorted(os.listdir(pred_pth))))
134
+ print('The {} Dataset of {} Model is not matching to the ground-truth'.format(_data_name, _model_name))
135
+ else:
136
+ print('>>> skip check the integrity of each candidates')
137
+
138
+ # start engine
139
+ do_eval(args)
BiRefNet_github/evaluation/evaluate.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import prettytable as pt
3
+
4
+ from evaluation.metrics import evaluator
5
+ from config import Config
6
+
7
+
8
+ config = Config()
9
+
10
+ def evaluate(pred_dir, method, testset, only_S_MAE=False, epoch=0):
11
+ filename = os.path.join('evaluation', 'eval-{}.txt'.format(method))
12
+ if os.path.exists(filename):
13
+ id_suffix = 1
14
+ filename = filename.rstrip('.txt') + '_{}.txt'.format(id_suffix)
15
+ while os.path.exists(filename):
16
+ id_suffix += 1
17
+ filename = filename.replace('_{}.txt'.format(id_suffix-1), '_{}.txt'.format(id_suffix))
18
+ gt_paths = sorted([
19
+ os.path.join(config.data_root_dir, config.task, testset, 'gt', p)
20
+ for p in os.listdir(os.path.join(config.data_root_dir, config.task, testset, 'gt'))
21
+ ])
22
+ pred_paths = sorted([os.path.join(pred_dir, method, testset, p) for p in os.listdir(os.path.join(pred_dir, method, testset))])
23
+ with open(filename, 'a+') as file_to_write:
24
+ tb = pt.PrettyTable()
25
+ field_names = [
26
+ "Dataset", "Method", "maxFm", "wFmeasure", 'MAE', "Smeasure", "meanEm", "maxEm", "meanFm",
27
+ "adpEm", "adpFm", 'HCE'
28
+ ]
29
+ tb.field_names = [name for name in field_names if not only_S_MAE or all(metric not in name for metric in ['Em', 'Fm'])]
30
+ em, sm, fm, mae, wfm, hce = evaluator(
31
+ gt_paths=gt_paths[:],
32
+ pred_paths=pred_paths[:],
33
+ metrics=['S', 'MAE', 'E', 'F', 'HCE'][:10*(not only_S_MAE) + 2], # , 'WF'
34
+ verbose=config.verbose_eval,
35
+ )
36
+ e_max, e_mean, e_adp = em['curve'].max(), em['curve'].mean(), em['adp'].mean()
37
+ f_max, f_mean, f_wfm, f_adp = fm['curve'].max(), fm['curve'].mean(), wfm, fm['adp']
38
+ tb.add_row(
39
+ [
40
+ method+str(epoch), testset, f_max.round(3), f_wfm.round(3), mae.round(3), sm.round(3),
41
+ e_mean.round(3), e_max.round(3), f_mean.round(3), em['adp'].round(3), f_adp.round(3), hce.round(3)
42
+ ] if not only_S_MAE else [method, testset, mae.round(3), sm.round(3)]
43
+ )
44
+ print(tb)
45
+ file_to_write.write(str(tb).replace('+', '|')+'\n')
46
+ file_to_write.close()
47
+ return {'e_max': e_max, 'e_mean': e_mean, 'e_adp': e_adp, 'sm': sm, 'mae': mae, 'f_max': f_max, 'f_mean': f_mean, 'f_wfm': f_wfm, 'f_adp': f_adp, 'hce': hce}
48
+
49
+
50
+ def main():
51
+ only_S_MAE = False
52
+ pred_dir = '.'
53
+ method = 'tmp_val'
54
+ testsets = 'DIS-VD+DIS-TE1'
55
+ for testset in testsets.split('+'):
56
+ res_dct = evaluate(pred_dir, method, testset, only_S_MAE=only_S_MAE)
57
+
58
+
59
+ if __name__ == '__main__':
60
+ main()
BiRefNet_github/evaluation/metrics.py ADDED
@@ -0,0 +1,612 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from tqdm import tqdm
3
+ import cv2
4
+ import numpy as np
5
+ from scipy.ndimage import convolve, distance_transform_edt as bwdist
6
+ from skimage.morphology import skeletonize
7
+ from skimage.morphology import disk
8
+ from skimage.measure import label
9
+
10
+
11
+ _EPS = np.spacing(1)
12
+ _TYPE = np.float64
13
+
14
+
15
+ def evaluator(gt_paths, pred_paths, metrics=['S', 'MAE', 'E', 'F', 'WF', 'HCE'], verbose=False):
16
+ # define measures
17
+ if 'E' in metrics:
18
+ EM = Emeasure()
19
+ if 'S' in metrics:
20
+ SM = Smeasure()
21
+ if 'F' in metrics:
22
+ FM = Fmeasure()
23
+ if 'MAE' in metrics:
24
+ MAE = MAEmeasure()
25
+ if 'WF' in metrics:
26
+ WFM = WeightedFmeasure()
27
+ if 'HCE' in metrics:
28
+ HCE = HCEMeasure()
29
+
30
+ if isinstance(gt_paths, list) and isinstance(pred_paths, list):
31
+ # print(len(gt_paths), len(pred_paths))
32
+ assert len(gt_paths) == len(pred_paths)
33
+
34
+ for idx_sample in tqdm(range(len(gt_paths)), total=len(gt_paths)) if verbose else range(len(gt_paths)):
35
+ gt = gt_paths[idx_sample]
36
+ pred = pred_paths[idx_sample]
37
+
38
+ pred = pred[:-4] + '.png'
39
+ if os.path.exists(pred):
40
+ pred_ary = cv2.imread(pred, cv2.IMREAD_GRAYSCALE)
41
+ else:
42
+ pred_ary = cv2.imread(pred.replace('.png', '.jpg'), cv2.IMREAD_GRAYSCALE)
43
+ gt_ary = cv2.imread(gt, cv2.IMREAD_GRAYSCALE)
44
+ pred_ary = cv2.resize(pred_ary, (gt_ary.shape[1], gt_ary.shape[0]))
45
+
46
+ if 'E' in metrics:
47
+ EM.step(pred=pred_ary, gt=gt_ary)
48
+ if 'S' in metrics:
49
+ SM.step(pred=pred_ary, gt=gt_ary)
50
+ if 'F' in metrics:
51
+ FM.step(pred=pred_ary, gt=gt_ary)
52
+ if 'MAE' in metrics:
53
+ MAE.step(pred=pred_ary, gt=gt_ary)
54
+ if 'WF' in metrics:
55
+ WFM.step(pred=pred_ary, gt=gt_ary)
56
+ if 'HCE' in metrics:
57
+ ske_path = gt.replace('/gt/', '/ske/')
58
+ if os.path.exists(ske_path):
59
+ ske_ary = cv2.imread(ske_path, cv2.IMREAD_GRAYSCALE)
60
+ ske_ary = ske_ary > 128
61
+ else:
62
+ ske_ary = skeletonize(gt_ary > 128)
63
+ ske_save_dir = os.path.join(*ske_path.split(os.sep)[:-1])
64
+ if ske_path[0] == os.sep:
65
+ ske_save_dir = os.sep + ske_save_dir
66
+ os.makedirs(ske_save_dir, exist_ok=True)
67
+ cv2.imwrite(ske_path, ske_ary.astype(np.uint8) * 255)
68
+ HCE.step(pred=pred_ary, gt=gt_ary, gt_ske=ske_ary)
69
+
70
+ if 'E' in metrics:
71
+ em = EM.get_results()['em']
72
+ else:
73
+ em = {'curve': np.array([np.float64(-1)]), 'adp': np.float64(-1)}
74
+ if 'S' in metrics:
75
+ sm = SM.get_results()['sm']
76
+ else:
77
+ sm = np.float64(-1)
78
+ if 'F' in metrics:
79
+ fm = FM.get_results()['fm']
80
+ else:
81
+ fm = {'curve': np.array([np.float64(-1)]), 'adp': np.float64(-1)}
82
+ if 'MAE' in metrics:
83
+ mae = MAE.get_results()['mae']
84
+ else:
85
+ mae = np.float64(-1)
86
+ if 'WF' in metrics:
87
+ wfm = WFM.get_results()['wfm']
88
+ else:
89
+ wfm = np.float64(-1)
90
+ if 'HCE' in metrics:
91
+ hce = HCE.get_results()['hce']
92
+ else:
93
+ hce = np.float64(-1)
94
+
95
+ return em, sm, fm, mae, wfm, hce
96
+
97
+
98
+ def _prepare_data(pred: np.ndarray, gt: np.ndarray) -> tuple:
99
+ gt = gt > 128
100
+ pred = pred / 255
101
+ if pred.max() != pred.min():
102
+ pred = (pred - pred.min()) / (pred.max() - pred.min())
103
+ return pred, gt
104
+
105
+
106
+ def _get_adaptive_threshold(matrix: np.ndarray, max_value: float = 1) -> float:
107
+ return min(2 * matrix.mean(), max_value)
108
+
109
+
110
+ class Fmeasure(object):
111
+ def __init__(self, beta: float = 0.3):
112
+ self.beta = beta
113
+ self.precisions = []
114
+ self.recalls = []
115
+ self.adaptive_fms = []
116
+ self.changeable_fms = []
117
+
118
+ def step(self, pred: np.ndarray, gt: np.ndarray):
119
+ pred, gt = _prepare_data(pred, gt)
120
+
121
+ adaptive_fm = self.cal_adaptive_fm(pred=pred, gt=gt)
122
+ self.adaptive_fms.append(adaptive_fm)
123
+
124
+ precisions, recalls, changeable_fms = self.cal_pr(pred=pred, gt=gt)
125
+ self.precisions.append(precisions)
126
+ self.recalls.append(recalls)
127
+ self.changeable_fms.append(changeable_fms)
128
+
129
+ def cal_adaptive_fm(self, pred: np.ndarray, gt: np.ndarray) -> float:
130
+ adaptive_threshold = _get_adaptive_threshold(pred, max_value=1)
131
+ binary_predcition = pred >= adaptive_threshold
132
+ area_intersection = binary_predcition[gt].sum()
133
+ if area_intersection == 0:
134
+ adaptive_fm = 0
135
+ else:
136
+ pre = area_intersection / np.count_nonzero(binary_predcition)
137
+ rec = area_intersection / np.count_nonzero(gt)
138
+ adaptive_fm = (1 + self.beta) * pre * rec / (self.beta * pre + rec)
139
+ return adaptive_fm
140
+
141
+ def cal_pr(self, pred: np.ndarray, gt: np.ndarray) -> tuple:
142
+ pred = (pred * 255).astype(np.uint8)
143
+ bins = np.linspace(0, 256, 257)
144
+ fg_hist, _ = np.histogram(pred[gt], bins=bins)
145
+ bg_hist, _ = np.histogram(pred[~gt], bins=bins)
146
+ fg_w_thrs = np.cumsum(np.flip(fg_hist), axis=0)
147
+ bg_w_thrs = np.cumsum(np.flip(bg_hist), axis=0)
148
+ TPs = fg_w_thrs
149
+ Ps = fg_w_thrs + bg_w_thrs
150
+ Ps[Ps == 0] = 1
151
+ T = max(np.count_nonzero(gt), 1)
152
+ precisions = TPs / Ps
153
+ recalls = TPs / T
154
+ numerator = (1 + self.beta) * precisions * recalls
155
+ denominator = np.where(numerator == 0, 1, self.beta * precisions + recalls)
156
+ changeable_fms = numerator / denominator
157
+ return precisions, recalls, changeable_fms
158
+
159
+ def get_results(self) -> dict:
160
+ adaptive_fm = np.mean(np.array(self.adaptive_fms, _TYPE))
161
+ changeable_fm = np.mean(np.array(self.changeable_fms, dtype=_TYPE), axis=0)
162
+ precision = np.mean(np.array(self.precisions, dtype=_TYPE), axis=0) # N, 256
163
+ recall = np.mean(np.array(self.recalls, dtype=_TYPE), axis=0) # N, 256
164
+ return dict(fm=dict(adp=adaptive_fm, curve=changeable_fm),
165
+ pr=dict(p=precision, r=recall))
166
+
167
+
168
+ class MAEmeasure(object):
169
+ def __init__(self):
170
+ self.maes = []
171
+
172
+ def step(self, pred: np.ndarray, gt: np.ndarray):
173
+ pred, gt = _prepare_data(pred, gt)
174
+
175
+ mae = self.cal_mae(pred, gt)
176
+ self.maes.append(mae)
177
+
178
+ def cal_mae(self, pred: np.ndarray, gt: np.ndarray) -> float:
179
+ mae = np.mean(np.abs(pred - gt))
180
+ return mae
181
+
182
+ def get_results(self) -> dict:
183
+ mae = np.mean(np.array(self.maes, _TYPE))
184
+ return dict(mae=mae)
185
+
186
+
187
+ class Smeasure(object):
188
+ def __init__(self, alpha: float = 0.5):
189
+ self.sms = []
190
+ self.alpha = alpha
191
+
192
+ def step(self, pred: np.ndarray, gt: np.ndarray):
193
+ pred, gt = _prepare_data(pred=pred, gt=gt)
194
+
195
+ sm = self.cal_sm(pred, gt)
196
+ self.sms.append(sm)
197
+
198
+ def cal_sm(self, pred: np.ndarray, gt: np.ndarray) -> float:
199
+ y = np.mean(gt)
200
+ if y == 0:
201
+ sm = 1 - np.mean(pred)
202
+ elif y == 1:
203
+ sm = np.mean(pred)
204
+ else:
205
+ sm = self.alpha * self.object(pred, gt) + (1 - self.alpha) * self.region(pred, gt)
206
+ sm = max(0, sm)
207
+ return sm
208
+
209
+ def object(self, pred: np.ndarray, gt: np.ndarray) -> float:
210
+ fg = pred * gt
211
+ bg = (1 - pred) * (1 - gt)
212
+ u = np.mean(gt)
213
+ object_score = u * self.s_object(fg, gt) + (1 - u) * self.s_object(bg, 1 - gt)
214
+ return object_score
215
+
216
+ def s_object(self, pred: np.ndarray, gt: np.ndarray) -> float:
217
+ x = np.mean(pred[gt == 1])
218
+ sigma_x = np.std(pred[gt == 1], ddof=1)
219
+ score = 2 * x / (np.power(x, 2) + 1 + sigma_x + _EPS)
220
+ return score
221
+
222
+ def region(self, pred: np.ndarray, gt: np.ndarray) -> float:
223
+ x, y = self.centroid(gt)
224
+ part_info = self.divide_with_xy(pred, gt, x, y)
225
+ w1, w2, w3, w4 = part_info['weight']
226
+ pred1, pred2, pred3, pred4 = part_info['pred']
227
+ gt1, gt2, gt3, gt4 = part_info['gt']
228
+ score1 = self.ssim(pred1, gt1)
229
+ score2 = self.ssim(pred2, gt2)
230
+ score3 = self.ssim(pred3, gt3)
231
+ score4 = self.ssim(pred4, gt4)
232
+
233
+ return w1 * score1 + w2 * score2 + w3 * score3 + w4 * score4
234
+
235
+ def centroid(self, matrix: np.ndarray) -> tuple:
236
+ h, w = matrix.shape
237
+ area_object = np.count_nonzero(matrix)
238
+ if area_object == 0:
239
+ x = np.round(w / 2)
240
+ y = np.round(h / 2)
241
+ else:
242
+ # More details can be found at: https://www.yuque.com/lart/blog/gpbigm
243
+ y, x = np.argwhere(matrix).mean(axis=0).round()
244
+ return int(x) + 1, int(y) + 1
245
+
246
+ def divide_with_xy(self, pred: np.ndarray, gt: np.ndarray, x, y) -> dict:
247
+ h, w = gt.shape
248
+ area = h * w
249
+
250
+ gt_LT = gt[0:y, 0:x]
251
+ gt_RT = gt[0:y, x:w]
252
+ gt_LB = gt[y:h, 0:x]
253
+ gt_RB = gt[y:h, x:w]
254
+
255
+ pred_LT = pred[0:y, 0:x]
256
+ pred_RT = pred[0:y, x:w]
257
+ pred_LB = pred[y:h, 0:x]
258
+ pred_RB = pred[y:h, x:w]
259
+
260
+ w1 = x * y / area
261
+ w2 = y * (w - x) / area
262
+ w3 = (h - y) * x / area
263
+ w4 = 1 - w1 - w2 - w3
264
+
265
+ return dict(gt=(gt_LT, gt_RT, gt_LB, gt_RB),
266
+ pred=(pred_LT, pred_RT, pred_LB, pred_RB),
267
+ weight=(w1, w2, w3, w4))
268
+
269
+ def ssim(self, pred: np.ndarray, gt: np.ndarray) -> float:
270
+ h, w = pred.shape
271
+ N = h * w
272
+
273
+ x = np.mean(pred)
274
+ y = np.mean(gt)
275
+
276
+ sigma_x = np.sum((pred - x) ** 2) / (N - 1)
277
+ sigma_y = np.sum((gt - y) ** 2) / (N - 1)
278
+ sigma_xy = np.sum((pred - x) * (gt - y)) / (N - 1)
279
+
280
+ alpha = 4 * x * y * sigma_xy
281
+ beta = (x ** 2 + y ** 2) * (sigma_x + sigma_y)
282
+
283
+ if alpha != 0:
284
+ score = alpha / (beta + _EPS)
285
+ elif alpha == 0 and beta == 0:
286
+ score = 1
287
+ else:
288
+ score = 0
289
+ return score
290
+
291
+ def get_results(self) -> dict:
292
+ sm = np.mean(np.array(self.sms, dtype=_TYPE))
293
+ return dict(sm=sm)
294
+
295
+
296
+ class Emeasure(object):
297
+ def __init__(self):
298
+ self.adaptive_ems = []
299
+ self.changeable_ems = []
300
+
301
+ def step(self, pred: np.ndarray, gt: np.ndarray):
302
+ pred, gt = _prepare_data(pred=pred, gt=gt)
303
+ self.gt_fg_numel = np.count_nonzero(gt)
304
+ self.gt_size = gt.shape[0] * gt.shape[1]
305
+
306
+ changeable_ems = self.cal_changeable_em(pred, gt)
307
+ self.changeable_ems.append(changeable_ems)
308
+ adaptive_em = self.cal_adaptive_em(pred, gt)
309
+ self.adaptive_ems.append(adaptive_em)
310
+
311
+ def cal_adaptive_em(self, pred: np.ndarray, gt: np.ndarray) -> float:
312
+ adaptive_threshold = _get_adaptive_threshold(pred, max_value=1)
313
+ adaptive_em = self.cal_em_with_threshold(pred, gt, threshold=adaptive_threshold)
314
+ return adaptive_em
315
+
316
+ def cal_changeable_em(self, pred: np.ndarray, gt: np.ndarray) -> np.ndarray:
317
+ changeable_ems = self.cal_em_with_cumsumhistogram(pred, gt)
318
+ return changeable_ems
319
+
320
+ def cal_em_with_threshold(self, pred: np.ndarray, gt: np.ndarray, threshold: float) -> float:
321
+ binarized_pred = pred >= threshold
322
+ fg_fg_numel = np.count_nonzero(binarized_pred & gt)
323
+ fg_bg_numel = np.count_nonzero(binarized_pred & ~gt)
324
+
325
+ fg___numel = fg_fg_numel + fg_bg_numel
326
+ bg___numel = self.gt_size - fg___numel
327
+
328
+ if self.gt_fg_numel == 0:
329
+ enhanced_matrix_sum = bg___numel
330
+ elif self.gt_fg_numel == self.gt_size:
331
+ enhanced_matrix_sum = fg___numel
332
+ else:
333
+ parts_numel, combinations = self.generate_parts_numel_combinations(
334
+ fg_fg_numel=fg_fg_numel, fg_bg_numel=fg_bg_numel,
335
+ pred_fg_numel=fg___numel, pred_bg_numel=bg___numel,
336
+ )
337
+
338
+ results_parts = []
339
+ for i, (part_numel, combination) in enumerate(zip(parts_numel, combinations)):
340
+ align_matrix_value = 2 * (combination[0] * combination[1]) / \
341
+ (combination[0] ** 2 + combination[1] ** 2 + _EPS)
342
+ enhanced_matrix_value = (align_matrix_value + 1) ** 2 / 4
343
+ results_parts.append(enhanced_matrix_value * part_numel)
344
+ enhanced_matrix_sum = sum(results_parts)
345
+
346
+ em = enhanced_matrix_sum / (self.gt_size - 1 + _EPS)
347
+ return em
348
+
349
+ def cal_em_with_cumsumhistogram(self, pred: np.ndarray, gt: np.ndarray) -> np.ndarray:
350
+ pred = (pred * 255).astype(np.uint8)
351
+ bins = np.linspace(0, 256, 257)
352
+ fg_fg_hist, _ = np.histogram(pred[gt], bins=bins)
353
+ fg_bg_hist, _ = np.histogram(pred[~gt], bins=bins)
354
+ fg_fg_numel_w_thrs = np.cumsum(np.flip(fg_fg_hist), axis=0)
355
+ fg_bg_numel_w_thrs = np.cumsum(np.flip(fg_bg_hist), axis=0)
356
+
357
+ fg___numel_w_thrs = fg_fg_numel_w_thrs + fg_bg_numel_w_thrs
358
+ bg___numel_w_thrs = self.gt_size - fg___numel_w_thrs
359
+
360
+ if self.gt_fg_numel == 0:
361
+ enhanced_matrix_sum = bg___numel_w_thrs
362
+ elif self.gt_fg_numel == self.gt_size:
363
+ enhanced_matrix_sum = fg___numel_w_thrs
364
+ else:
365
+ parts_numel_w_thrs, combinations = self.generate_parts_numel_combinations(
366
+ fg_fg_numel=fg_fg_numel_w_thrs, fg_bg_numel=fg_bg_numel_w_thrs,
367
+ pred_fg_numel=fg___numel_w_thrs, pred_bg_numel=bg___numel_w_thrs,
368
+ )
369
+
370
+ results_parts = np.empty(shape=(4, 256), dtype=np.float64)
371
+ for i, (part_numel, combination) in enumerate(zip(parts_numel_w_thrs, combinations)):
372
+ align_matrix_value = 2 * (combination[0] * combination[1]) / \
373
+ (combination[0] ** 2 + combination[1] ** 2 + _EPS)
374
+ enhanced_matrix_value = (align_matrix_value + 1) ** 2 / 4
375
+ results_parts[i] = enhanced_matrix_value * part_numel
376
+ enhanced_matrix_sum = results_parts.sum(axis=0)
377
+
378
+ em = enhanced_matrix_sum / (self.gt_size - 1 + _EPS)
379
+ return em
380
+
381
+ def generate_parts_numel_combinations(self, fg_fg_numel, fg_bg_numel, pred_fg_numel, pred_bg_numel):
382
+ bg_fg_numel = self.gt_fg_numel - fg_fg_numel
383
+ bg_bg_numel = pred_bg_numel - bg_fg_numel
384
+
385
+ parts_numel = [fg_fg_numel, fg_bg_numel, bg_fg_numel, bg_bg_numel]
386
+
387
+ mean_pred_value = pred_fg_numel / self.gt_size
388
+ mean_gt_value = self.gt_fg_numel / self.gt_size
389
+
390
+ demeaned_pred_fg_value = 1 - mean_pred_value
391
+ demeaned_pred_bg_value = 0 - mean_pred_value
392
+ demeaned_gt_fg_value = 1 - mean_gt_value
393
+ demeaned_gt_bg_value = 0 - mean_gt_value
394
+
395
+ combinations = [
396
+ (demeaned_pred_fg_value, demeaned_gt_fg_value),
397
+ (demeaned_pred_fg_value, demeaned_gt_bg_value),
398
+ (demeaned_pred_bg_value, demeaned_gt_fg_value),
399
+ (demeaned_pred_bg_value, demeaned_gt_bg_value)
400
+ ]
401
+ return parts_numel, combinations
402
+
403
+ def get_results(self) -> dict:
404
+ adaptive_em = np.mean(np.array(self.adaptive_ems, dtype=_TYPE))
405
+ changeable_em = np.mean(np.array(self.changeable_ems, dtype=_TYPE), axis=0)
406
+ return dict(em=dict(adp=adaptive_em, curve=changeable_em))
407
+
408
+
409
+ class WeightedFmeasure(object):
410
+ def __init__(self, beta: float = 1):
411
+ self.beta = beta
412
+ self.weighted_fms = []
413
+
414
+ def step(self, pred: np.ndarray, gt: np.ndarray):
415
+ pred, gt = _prepare_data(pred=pred, gt=gt)
416
+
417
+ if np.all(~gt):
418
+ wfm = 0
419
+ else:
420
+ wfm = self.cal_wfm(pred, gt)
421
+ self.weighted_fms.append(wfm)
422
+
423
+ def cal_wfm(self, pred: np.ndarray, gt: np.ndarray) -> float:
424
+ # [Dst,IDXT] = bwdist(dGT);
425
+ Dst, Idxt = bwdist(gt == 0, return_indices=True)
426
+
427
+ # %Pixel dependency
428
+ # E = abs(FG-dGT);
429
+ E = np.abs(pred - gt)
430
+ Et = np.copy(E)
431
+ Et[gt == 0] = Et[Idxt[0][gt == 0], Idxt[1][gt == 0]]
432
+
433
+ # K = fspecial('gaussian',7,5);
434
+ # EA = imfilter(Et,K);
435
+ K = self.matlab_style_gauss2D((7, 7), sigma=5)
436
+ EA = convolve(Et, weights=K, mode="constant", cval=0)
437
+ # MIN_E_EA = E;
438
+ # MIN_E_EA(GT & EA<E) = EA(GT & EA<E);
439
+ MIN_E_EA = np.where(gt & (EA < E), EA, E)
440
+
441
+ # %Pixel importance
442
+ B = np.where(gt == 0, 2 - np.exp(np.log(0.5) / 5 * Dst), np.ones_like(gt))
443
+ Ew = MIN_E_EA * B
444
+
445
+ TPw = np.sum(gt) - np.sum(Ew[gt == 1])
446
+ FPw = np.sum(Ew[gt == 0])
447
+
448
+
449
+ R = 1 - np.mean(Ew[gt == 1])
450
+ P = TPw / (TPw + FPw + _EPS)
451
+
452
+ # % Q = (1+Beta^2)*(R*P)./(eps+R+(Beta.*P));
453
+ Q = (1 + self.beta) * R * P / (R + self.beta * P + _EPS)
454
+
455
+ return Q
456
+
457
+ def matlab_style_gauss2D(self, shape: tuple = (7, 7), sigma: int = 5) -> np.ndarray:
458
+ """
459
+ 2D gaussian mask - should give the same result as MATLAB's
460
+ fspecial('gaussian',[shape],[sigma])
461
+ """
462
+ m, n = [(ss - 1) / 2 for ss in shape]
463
+ y, x = np.ogrid[-m: m + 1, -n: n + 1]
464
+ h = np.exp(-(x * x + y * y) / (2 * sigma * sigma))
465
+ h[h < np.finfo(h.dtype).eps * h.max()] = 0
466
+ sumh = h.sum()
467
+ if sumh != 0:
468
+ h /= sumh
469
+ return h
470
+
471
+ def get_results(self) -> dict:
472
+ weighted_fm = np.mean(np.array(self.weighted_fms, dtype=_TYPE))
473
+ return dict(wfm=weighted_fm)
474
+
475
+
476
+ class HCEMeasure(object):
477
+ def __init__(self):
478
+ self.hces = []
479
+
480
+ def step(self, pred: np.ndarray, gt: np.ndarray, gt_ske):
481
+ # pred, gt = _prepare_data(pred, gt)
482
+
483
+ hce = self.cal_hce(pred, gt, gt_ske)
484
+ self.hces.append(hce)
485
+
486
+ def get_results(self) -> dict:
487
+ hce = np.mean(np.array(self.hces, _TYPE))
488
+ return dict(hce=hce)
489
+
490
+
491
+ def cal_hce(self, pred: np.ndarray, gt: np.ndarray, gt_ske: np.ndarray, relax=5, epsilon=2.0) -> float:
492
+ # Binarize gt
493
+ if(len(gt.shape)>2):
494
+ gt = gt[:, :, 0]
495
+
496
+ epsilon_gt = 128#(np.amin(gt)+np.amax(gt))/2.0
497
+ gt = (gt>epsilon_gt).astype(np.uint8)
498
+
499
+ # Binarize pred
500
+ if(len(pred.shape)>2):
501
+ pred = pred[:, :, 0]
502
+ epsilon_pred = 128#(np.amin(pred)+np.amax(pred))/2.0
503
+ pred = (pred>epsilon_pred).astype(np.uint8)
504
+
505
+ Union = np.logical_or(gt, pred)
506
+ TP = np.logical_and(gt, pred)
507
+ FP = pred - TP
508
+ FN = gt - TP
509
+
510
+ # relax the Union of gt and pred
511
+ Union_erode = Union.copy()
512
+ Union_erode = cv2.erode(Union_erode.astype(np.uint8), disk(1), iterations=relax)
513
+
514
+ # --- get the relaxed False Positive regions for computing the human efforts in correcting them ---
515
+ FP_ = np.logical_and(FP, Union_erode) # get the relaxed FP
516
+ for i in range(0, relax):
517
+ FP_ = cv2.dilate(FP_.astype(np.uint8), disk(1))
518
+ FP_ = np.logical_and(FP_, 1-np.logical_or(TP, FN))
519
+ FP_ = np.logical_and(FP, FP_)
520
+
521
+ # --- get the relaxed False Negative regions for computing the human efforts in correcting them ---
522
+ FN_ = np.logical_and(FN, Union_erode) # preserve the structural components of FN
523
+ ## recover the FN, where pixels are not close to the TP borders
524
+ for i in range(0, relax):
525
+ FN_ = cv2.dilate(FN_.astype(np.uint8), disk(1))
526
+ FN_ = np.logical_and(FN_, 1-np.logical_or(TP, FP))
527
+ FN_ = np.logical_and(FN, FN_)
528
+ FN_ = np.logical_or(FN_, np.logical_xor(gt_ske, np.logical_and(TP, gt_ske))) # preserve the structural components of FN
529
+
530
+ ## 2. =============Find exact polygon control points and independent regions==============
531
+ ## find contours from FP_
532
+ ctrs_FP, hier_FP = cv2.findContours(FP_.astype(np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
533
+ ## find control points and independent regions for human correction
534
+ bdies_FP, indep_cnt_FP = self.filter_bdy_cond(ctrs_FP, FP_, np.logical_or(TP,FN_))
535
+ ## find contours from FN_
536
+ ctrs_FN, hier_FN = cv2.findContours(FN_.astype(np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
537
+ ## find control points and independent regions for human correction
538
+ bdies_FN, indep_cnt_FN = self.filter_bdy_cond(ctrs_FN, FN_, 1-np.logical_or(np.logical_or(TP, FP_), FN_))
539
+
540
+ poly_FP, poly_FP_len, poly_FP_point_cnt = self.approximate_RDP(bdies_FP, epsilon=epsilon)
541
+ poly_FN, poly_FN_len, poly_FN_point_cnt = self.approximate_RDP(bdies_FN, epsilon=epsilon)
542
+
543
+ # FP_points+FP_indep+FN_points+FN_indep
544
+ return poly_FP_point_cnt+indep_cnt_FP+poly_FN_point_cnt+indep_cnt_FN
545
+
546
+ def filter_bdy_cond(self, bdy_, mask, cond):
547
+
548
+ cond = cv2.dilate(cond.astype(np.uint8), disk(1))
549
+ labels = label(mask) # find the connected regions
550
+ lbls = np.unique(labels) # the indices of the connected regions
551
+ indep = np.ones(lbls.shape[0]) # the label of each connected regions
552
+ indep[0] = 0 # 0 indicate the background region
553
+
554
+ boundaries = []
555
+ h,w = cond.shape[0:2]
556
+ ind_map = np.zeros((h, w))
557
+ indep_cnt = 0
558
+
559
+ for i in range(0, len(bdy_)):
560
+ tmp_bdies = []
561
+ tmp_bdy = []
562
+ for j in range(0, bdy_[i].shape[0]):
563
+ r, c = bdy_[i][j,0,1],bdy_[i][j,0,0]
564
+
565
+ if(np.sum(cond[r, c])==0 or ind_map[r, c]!=0):
566
+ if(len(tmp_bdy)>0):
567
+ tmp_bdies.append(tmp_bdy)
568
+ tmp_bdy = []
569
+ continue
570
+ tmp_bdy.append([c, r])
571
+ ind_map[r, c] = ind_map[r, c] + 1
572
+ indep[labels[r, c]] = 0 # indicates part of the boundary of this region needs human correction
573
+ if(len(tmp_bdy)>0):
574
+ tmp_bdies.append(tmp_bdy)
575
+
576
+ # check if the first and the last boundaries are connected
577
+ # if yes, invert the first boundary and attach it after the last boundary
578
+ if(len(tmp_bdies)>1):
579
+ first_x, first_y = tmp_bdies[0][0]
580
+ last_x, last_y = tmp_bdies[-1][-1]
581
+ if((abs(first_x-last_x)==1 and first_y==last_y) or
582
+ (first_x==last_x and abs(first_y-last_y)==1) or
583
+ (abs(first_x-last_x)==1 and abs(first_y-last_y)==1)
584
+ ):
585
+ tmp_bdies[-1].extend(tmp_bdies[0][::-1])
586
+ del tmp_bdies[0]
587
+
588
+ for k in range(0, len(tmp_bdies)):
589
+ tmp_bdies[k] = np.array(tmp_bdies[k])[:, np.newaxis, :]
590
+ if(len(tmp_bdies)>0):
591
+ boundaries.extend(tmp_bdies)
592
+
593
+ return boundaries, np.sum(indep)
594
+
595
+ # this function approximate each boundary by DP algorithm
596
+ # https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm
597
+ def approximate_RDP(self, boundaries, epsilon=1.0):
598
+
599
+ boundaries_ = []
600
+ boundaries_len_ = []
601
+ pixel_cnt_ = 0
602
+
603
+ # polygon approximate of each boundary
604
+ for i in range(0, len(boundaries)):
605
+ boundaries_.append(cv2.approxPolyDP(boundaries[i], epsilon, False))
606
+
607
+ # count the control points number of each boundary and the total control points number of all the boundaries
608
+ for i in range(0, len(boundaries_)):
609
+ boundaries_len_.append(len(boundaries_[i]))
610
+ pixel_cnt_ = pixel_cnt_ + len(boundaries_[i])
611
+
612
+ return boundaries_, boundaries_len_, pixel_cnt_
BiRefNet_github/evaluation/valid.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from inference import inference
2
+ from evaluation.evaluate import evaluate
3
+
4
+
5
+ def valid(model, data_loader_test, pred_dir, method='tmp_val', testset='DIS-VD', only_S_MAE=True, device=0):
6
+ model.eval()
7
+ inference(model, data_loader_test, pred_dir, method, testset, device=device)
8
+ performance_dict = evaluate(pred_dir, method, testset, only_S_MAE=only_S_MAE, epoch=model.epoch)
9
+ return performance_dict
BiRefNet_github/gen_best_ep.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from glob import glob
3
+ import numpy as np
4
+ from config import Config
5
+
6
+
7
+ config = Config()
8
+
9
+ eval_txts = sorted(glob('e_results/*_eval.txt'))
10
+ print('eval_txts:', [_.split(os.sep)[-1] for _ in eval_txts])
11
+ score_panel = {}
12
+ sep = '&'
13
+ metrics = ['sm', 'wfm', 'hce'] # we used HCE for DIS and wFm for others.
14
+ if 'DIS5K' not in config.task:
15
+ metrics.remove('hce')
16
+
17
+ for metric in metrics:
18
+ print('Metric:', metric)
19
+ current_line_nums = []
20
+ for idx_et, eval_txt in enumerate(eval_txts):
21
+ with open(eval_txt, 'r') as f:
22
+ lines = [l for l in f.readlines()[3:] if '.' in l]
23
+ current_line_nums.append(len(lines))
24
+ for idx_et, eval_txt in enumerate(eval_txts):
25
+ with open(eval_txt, 'r') as f:
26
+ lines = [l for l in f.readlines()[3:] if '.' in l]
27
+ for idx_line, line in enumerate(lines[:min(current_line_nums)]): # Consist line numbers by the minimal result file.
28
+ properties = line.strip().strip(sep).split(sep)
29
+ dataset = properties[0].strip()
30
+ ckpt = properties[1].strip()
31
+ if int(ckpt.split('--epoch_')[-1].strip()) < 0:
32
+ continue
33
+ targe_idx = {
34
+ 'sm': [5, 2, 2, 5, 2],
35
+ 'wfm': [3, 3, 8, 3, 8],
36
+ 'hce': [7, -1, -1, 7, -1]
37
+ }[metric][['DIS5K', 'COD', 'HRSOD', 'DIS5K+HRSOD+HRS10K', 'P3M-10k'].index(config.task)]
38
+ if metric != 'hce':
39
+ score_sm = float(properties[targe_idx].strip())
40
+ else:
41
+ score_sm = int(properties[targe_idx].strip().strip('.'))
42
+ if idx_et == 0:
43
+ score_panel[ckpt] = []
44
+ score_panel[ckpt].append(score_sm)
45
+
46
+ metrics_min = ['hce', 'mae']
47
+ max_or_min = min if metric in metrics_min else max
48
+ score_max = max_or_min(score_panel.values(), key=lambda x: np.sum(x))
49
+
50
+ good_models = []
51
+ for k, v in score_panel.items():
52
+ if (np.sum(v) <= np.sum(score_max)) if metric in metrics_min else (np.sum(v) >= np.sum(score_max)):
53
+ print(k, v)
54
+ good_models.append(k)
55
+
56
+ # Write
57
+ with open(eval_txt, 'r') as f:
58
+ lines = f.readlines()
59
+ info4good_models = lines[:3]
60
+ metric_names = [m.strip() for m in lines[1].strip().strip('&').split('&')[2:]]
61
+ testset_mean_values = {metric_name: [] for metric_name in metric_names}
62
+ for good_model in good_models:
63
+ for idx_et, eval_txt in enumerate(eval_txts):
64
+ with open(eval_txt, 'r') as f:
65
+ lines = f.readlines()
66
+ for line in lines:
67
+ if set([good_model]) & set([_.strip() for _ in line.split(sep)]):
68
+ info4good_models.append(line)
69
+ metric_scores = [float(m.strip()) for m in line.strip().strip('&').split('&')[2:]]
70
+ for idx_score, metric_score in enumerate(metric_scores):
71
+ testset_mean_values[metric_names[idx_score]].append(metric_score)
72
+
73
+ if 'DIS5K' in config.task:
74
+ testset_mean_values_lst = ['{:<4}'.format(int(np.mean(v_lst[:-1]).round())) if name == 'HCE' else '{:.3f}'.format(np.mean(v_lst[:-1])).lstrip('0') for name, v_lst in testset_mean_values.items()] # [:-1] to remove DIS-VD
75
+ sample_line_for_placing_mean_values = info4good_models[-2]
76
+ numbers_placed_well = sample_line_for_placing_mean_values.replace(sample_line_for_placing_mean_values.split('&')[1].strip(), 'DIS-TEs').strip().split('&')[3:]
77
+ for idx_number, (number_placed_well, testset_mean_value) in enumerate(zip(numbers_placed_well, testset_mean_values_lst)):
78
+ numbers_placed_well[idx_number] = number_placed_well.replace(number_placed_well.strip(), testset_mean_value)
79
+ testset_mean_line = '&'.join(sample_line_for_placing_mean_values.replace(sample_line_for_placing_mean_values.split('&')[1].strip(), 'DIS-TEs').split('&')[:3] + numbers_placed_well) + '\n'
80
+ info4good_models.append(testset_mean_line)
81
+ info4good_models.append(lines[-1])
82
+ info = ''.join(info4good_models)
83
+ print(info)
84
+ with open(os.path.join('e_results', 'eval-{}_best_on_{}.txt'.format(config.task, metric)), 'w') as f:
85
+ f.write(info + '\n')
BiRefNet_github/inference.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import argparse
3
+ from glob import glob
4
+ from tqdm import tqdm
5
+ import cv2
6
+ import torch
7
+
8
+ from dataset import MyData
9
+ from models.birefnet import BiRefNet
10
+ from utils import save_tensor_img, check_state_dict
11
+ from config import Config
12
+
13
+
14
+ config = Config()
15
+
16
+
17
+ def inference(model, data_loader_test, pred_root, method, testset, device=0):
18
+ model_training = model.training
19
+ if model_training:
20
+ model.eval()
21
+ for batch in tqdm(data_loader_test, total=len(data_loader_test)) if 1 or config.verbose_eval else data_loader_test:
22
+ inputs = batch[0].to(device)
23
+ # gts = batch[1].to(device)
24
+ label_paths = batch[-1]
25
+ with torch.no_grad():
26
+ scaled_preds = model(inputs)[-1].sigmoid()
27
+
28
+ os.makedirs(os.path.join(pred_root, method, testset), exist_ok=True)
29
+
30
+ for idx_sample in range(scaled_preds.shape[0]):
31
+ res = torch.nn.functional.interpolate(
32
+ scaled_preds[idx_sample].unsqueeze(0),
33
+ size=cv2.imread(label_paths[idx_sample], cv2.IMREAD_GRAYSCALE).shape[:2],
34
+ mode='bilinear',
35
+ align_corners=True
36
+ )
37
+ save_tensor_img(res, os.path.join(os.path.join(pred_root, method, testset), label_paths[idx_sample].replace('\\', '/').split('/')[-1])) # test set dir + file name
38
+ if model_training:
39
+ model.train()
40
+ return None
41
+
42
+
43
+ def main(args):
44
+ # Init model
45
+
46
+ device = config.device
47
+ if args.ckpt_folder:
48
+ print('Testing with models in {}'.format(args.ckpt_folder))
49
+ else:
50
+ print('Testing with model {}'.format(args.ckpt))
51
+
52
+ if config.model == 'BiRefNet':
53
+ model = BiRefNet(bb_pretrained=False)
54
+ weights_lst = sorted(
55
+ glob(os.path.join(args.ckpt_folder, '*.pth')) if args.ckpt_folder else [args.ckpt],
56
+ key=lambda x: int(x.split('epoch_')[-1].split('.pth')[0]),
57
+ reverse=True
58
+ )
59
+ for testset in args.testsets.split('+'):
60
+ print('>>>> Testset: {}...'.format(testset))
61
+ data_loader_test = torch.utils.data.DataLoader(
62
+ dataset=MyData(testset, image_size=config.size, is_train=False),
63
+ batch_size=config.batch_size_valid, shuffle=False, num_workers=config.num_workers, pin_memory=True
64
+ )
65
+ for weights in weights_lst:
66
+ if int(weights.strip('.pth').split('epoch_')[-1]) % 1 != 0:
67
+ continue
68
+ print('\tInferencing {}...'.format(weights))
69
+ # model.load_state_dict(torch.load(weights, map_location='cpu'))
70
+ state_dict = torch.load(weights, map_location='cpu')
71
+ state_dict = check_state_dict(state_dict)
72
+ model.load_state_dict(state_dict)
73
+ model = model.to(device)
74
+ inference(
75
+ model, data_loader_test=data_loader_test, pred_root=args.pred_root,
76
+ method='--'.join([w.rstrip('.pth') for w in weights.split(os.sep)[-2:]]),
77
+ testset=testset, device=config.device
78
+ )
79
+
80
+
81
+ if __name__ == '__main__':
82
+ # Parameter from command line
83
+ parser = argparse.ArgumentParser(description='')
84
+ parser.add_argument('--ckpt', type=str, help='model folder')
85
+ parser.add_argument('--ckpt_folder', default=sorted(glob(os.path.join('ckpt', '*')))[-1], type=str, help='model folder')
86
+ parser.add_argument('--pred_root', default='e_preds', type=str, help='Output folder')
87
+ parser.add_argument('--testsets',
88
+ default={
89
+ 'DIS5K': 'DIS-VD+DIS-TE1+DIS-TE2+DIS-TE3+DIS-TE4',
90
+ 'COD': 'TE-COD10K+NC4K+TE-CAMO+CHAMELEON',
91
+ 'HRSOD': 'DAVIS-S+TE-HRSOD+TE-UHRSD+TE-DUTS+DUT-OMRON',
92
+ 'DIS5K+HRSOD+HRS10K': 'DIS-VD',
93
+ 'P3M-10k': 'TE-P3M-500-P+TE-P3M-500-NP',
94
+ 'DIS5K-': 'DIS-VD',
95
+ 'COD-': 'TE-COD10K',
96
+ 'SOD-': 'DAVIS-S+TE-HRSOD+TE-UHRSD',
97
+ }[config.task + ''],
98
+ type=str,
99
+ help="Test all sets: , 'DIS-VD+DIS-TE1+DIS-TE2+DIS-TE3+DIS-TE4'")
100
+
101
+ args = parser.parse_args()
102
+
103
+ if config.precisionHigh:
104
+ torch.set_float32_matmul_precision('high')
105
+ main(args)
BiRefNet_github/loss.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ import torch.nn.functional as F
4
+ from torch.autograd import Variable
5
+ from math import exp
6
+ from config import Config
7
+
8
+
9
+ class Discriminator(nn.Module):
10
+ def __init__(self, channels=1, img_size=256):
11
+ super(Discriminator, self).__init__()
12
+
13
+ def discriminator_block(in_filters, out_filters, bn=Config().batch_size > 1):
14
+ block = [nn.Conv2d(in_filters, out_filters, 3, 2, 1), nn.LeakyReLU(0.2, inplace=True), nn.Dropout2d(0.25)]
15
+ if bn:
16
+ block.append(nn.BatchNorm2d(out_filters, 0.8))
17
+ return block
18
+
19
+ self.model = nn.Sequential(
20
+ *discriminator_block(channels, 16, bn=False),
21
+ *discriminator_block(16, 32),
22
+ *discriminator_block(32, 64),
23
+ *discriminator_block(64, 128),
24
+ )
25
+
26
+ # The height and width of downsampled image
27
+ ds_size = img_size // 2 ** 4
28
+ self.adv_layer = nn.Sequential(nn.Linear(128 * ds_size ** 2, 1), nn.Sigmoid())
29
+
30
+ def forward(self, img):
31
+ out = self.model(img)
32
+ out = out.view(out.shape[0], -1)
33
+ validity = self.adv_layer(out)
34
+
35
+ return validity
36
+
37
+
38
+ class ContourLoss(torch.nn.Module):
39
+ def __init__(self):
40
+ super(ContourLoss, self).__init__()
41
+
42
+ def forward(self, pred, target, weight=10):
43
+ '''
44
+ target, pred: tensor of shape (B, C, H, W), where target[:,:,region_in_contour] == 1,
45
+ target[:,:,region_out_contour] == 0.
46
+ weight: scalar, length term weight.
47
+ '''
48
+ # length term
49
+ delta_r = pred[:,:,1:,:] - pred[:,:,:-1,:] # horizontal gradient (B, C, H-1, W)
50
+ delta_c = pred[:,:,:,1:] - pred[:,:,:,:-1] # vertical gradient (B, C, H, W-1)
51
+
52
+ delta_r = delta_r[:,:,1:,:-2]**2 # (B, C, H-2, W-2)
53
+ delta_c = delta_c[:,:,:-2,1:]**2 # (B, C, H-2, W-2)
54
+ delta_pred = torch.abs(delta_r + delta_c)
55
+
56
+ epsilon = 1e-8 # where is a parameter to avoid square root is zero in practice.
57
+ length = torch.mean(torch.sqrt(delta_pred + epsilon)) # eq.(11) in the paper, mean is used instead of sum.
58
+
59
+ c_in = torch.ones_like(pred)
60
+ c_out = torch.zeros_like(pred)
61
+
62
+ region_in = torch.mean( pred * (target - c_in )**2 ) # equ.(12) in the paper, mean is used instead of sum.
63
+ region_out = torch.mean( (1-pred) * (target - c_out)**2 )
64
+ region = region_in + region_out
65
+
66
+ loss = weight * length + region
67
+
68
+ return loss
69
+
70
+
71
+ class IoULoss(torch.nn.Module):
72
+ def __init__(self):
73
+ super(IoULoss, self).__init__()
74
+
75
+ def forward(self, pred, target):
76
+ b = pred.shape[0]
77
+ IoU = 0.0
78
+ for i in range(0, b):
79
+ # compute the IoU of the foreground
80
+ Iand1 = torch.sum(target[i, :, :, :] * pred[i, :, :, :])
81
+ Ior1 = torch.sum(target[i, :, :, :]) + torch.sum(pred[i, :, :, :]) - Iand1
82
+ IoU1 = Iand1 / Ior1
83
+ # IoU loss is (1-IoU1)
84
+ IoU = IoU + (1-IoU1)
85
+ # return IoU/b
86
+ return IoU
87
+
88
+
89
+ class StructureLoss(torch.nn.Module):
90
+ def __init__(self):
91
+ super(StructureLoss, self).__init__()
92
+
93
+ def forward(self, pred, target):
94
+ weit = 1+5*torch.abs(F.avg_pool2d(target, kernel_size=31, stride=1, padding=15)-target)
95
+ wbce = F.binary_cross_entropy_with_logits(pred, target, reduction='none')
96
+ wbce = (weit*wbce).sum(dim=(2,3))/weit.sum(dim=(2,3))
97
+
98
+ pred = torch.sigmoid(pred)
99
+ inter = ((pred * target) * weit).sum(dim=(2, 3))
100
+ union = ((pred + target) * weit).sum(dim=(2, 3))
101
+ wiou = 1-(inter+1)/(union-inter+1)
102
+
103
+ return (wbce+wiou).mean()
104
+
105
+
106
+ class PatchIoULoss(torch.nn.Module):
107
+ def __init__(self):
108
+ super(PatchIoULoss, self).__init__()
109
+ self.iou_loss = IoULoss()
110
+
111
+ def forward(self, pred, target):
112
+ win_y, win_x = 64, 64
113
+ iou_loss = 0.
114
+ for anchor_y in range(0, target.shape[0], win_y):
115
+ for anchor_x in range(0, target.shape[1], win_y):
116
+ patch_pred = pred[:, :, anchor_y:anchor_y+win_y, anchor_x:anchor_x+win_x]
117
+ patch_target = target[:, :, anchor_y:anchor_y+win_y, anchor_x:anchor_x+win_x]
118
+ patch_iou_loss = self.iou_loss(patch_pred, patch_target)
119
+ iou_loss += patch_iou_loss
120
+ return iou_loss
121
+
122
+
123
+ class ThrReg_loss(torch.nn.Module):
124
+ def __init__(self):
125
+ super(ThrReg_loss, self).__init__()
126
+
127
+ def forward(self, pred, gt=None):
128
+ return torch.mean(1 - ((pred - 0) ** 2 + (pred - 1) ** 2))
129
+
130
+
131
+ class ClsLoss(nn.Module):
132
+ """
133
+ Auxiliary classification loss for each refined class output.
134
+ """
135
+ def __init__(self):
136
+ super(ClsLoss, self).__init__()
137
+ self.config = Config()
138
+ self.lambdas_cls = self.config.lambdas_cls
139
+
140
+ self.criterions_last = {
141
+ 'ce': nn.CrossEntropyLoss()
142
+ }
143
+
144
+ def forward(self, preds, gt):
145
+ loss = 0.
146
+ for _, pred_lvl in enumerate(preds):
147
+ if pred_lvl is None:
148
+ continue
149
+ for criterion_name, criterion in self.criterions_last.items():
150
+ loss += criterion(pred_lvl, gt) * self.lambdas_cls[criterion_name]
151
+ return loss
152
+
153
+
154
+ class PixLoss(nn.Module):
155
+ """
156
+ Pixel loss for each refined map output.
157
+ """
158
+ def __init__(self):
159
+ super(PixLoss, self).__init__()
160
+ self.config = Config()
161
+ self.lambdas_pix_last = self.config.lambdas_pix_last
162
+
163
+ self.criterions_last = {}
164
+ if 'bce' in self.lambdas_pix_last and self.lambdas_pix_last['bce']:
165
+ self.criterions_last['bce'] = nn.BCELoss() if not self.config.use_fp16 else nn.BCEWithLogitsLoss()
166
+ if 'iou' in self.lambdas_pix_last and self.lambdas_pix_last['iou']:
167
+ self.criterions_last['iou'] = IoULoss()
168
+ if 'iou_patch' in self.lambdas_pix_last and self.lambdas_pix_last['iou_patch']:
169
+ self.criterions_last['iou_patch'] = PatchIoULoss()
170
+ if 'ssim' in self.lambdas_pix_last and self.lambdas_pix_last['ssim']:
171
+ self.criterions_last['ssim'] = SSIMLoss()
172
+ if 'mse' in self.lambdas_pix_last and self.lambdas_pix_last['mse']:
173
+ self.criterions_last['mse'] = nn.MSELoss()
174
+ if 'reg' in self.lambdas_pix_last and self.lambdas_pix_last['reg']:
175
+ self.criterions_last['reg'] = ThrReg_loss()
176
+ if 'cnt' in self.lambdas_pix_last and self.lambdas_pix_last['cnt']:
177
+ self.criterions_last['cnt'] = ContourLoss()
178
+ if 'structure' in self.lambdas_pix_last and self.lambdas_pix_last['structure']:
179
+ self.criterions_last['structure'] = StructureLoss()
180
+
181
+ def forward(self, scaled_preds, gt):
182
+ loss = 0.
183
+ criterions_embedded_with_sigmoid = ['structure', ] + ['bce'] if self.config.use_fp16 else []
184
+ for _, pred_lvl in enumerate(scaled_preds):
185
+ if pred_lvl.shape != gt.shape:
186
+ pred_lvl = nn.functional.interpolate(pred_lvl, size=gt.shape[2:], mode='bilinear', align_corners=True)
187
+ for criterion_name, criterion in self.criterions_last.items():
188
+ _loss = criterion(pred_lvl.sigmoid() if criterion_name not in criterions_embedded_with_sigmoid else pred_lvl, gt) * self.lambdas_pix_last[criterion_name]
189
+ loss += _loss
190
+ # print(criterion_name, _loss.item())
191
+ return loss
192
+
193
+
194
+ class SSIMLoss(torch.nn.Module):
195
+ def __init__(self, window_size=11, size_average=True):
196
+ super(SSIMLoss, self).__init__()
197
+ self.window_size = window_size
198
+ self.size_average = size_average
199
+ self.channel = 1
200
+ self.window = create_window(window_size, self.channel)
201
+
202
+ def forward(self, img1, img2):
203
+ (_, channel, _, _) = img1.size()
204
+ if channel == self.channel and self.window.data.type() == img1.data.type():
205
+ window = self.window
206
+ else:
207
+ window = create_window(self.window_size, channel)
208
+ if img1.is_cuda:
209
+ window = window.cuda(img1.get_device())
210
+ window = window.type_as(img1)
211
+ self.window = window
212
+ self.channel = channel
213
+ return 1 - _ssim(img1, img2, window, self.window_size, channel, self.size_average)
214
+
215
+
216
+ def gaussian(window_size, sigma):
217
+ gauss = torch.Tensor([exp(-(x - window_size//2)**2/float(2*sigma**2)) for x in range(window_size)])
218
+ return gauss/gauss.sum()
219
+
220
+
221
+ def create_window(window_size, channel):
222
+ _1D_window = gaussian(window_size, 1.5).unsqueeze(1)
223
+ _2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0)
224
+ window = Variable(_2D_window.expand(channel, 1, window_size, window_size).contiguous())
225
+ return window
226
+
227
+
228
+ def _ssim(img1, img2, window, window_size, channel, size_average=True):
229
+ mu1 = F.conv2d(img1, window, padding = window_size//2, groups=channel)
230
+ mu2 = F.conv2d(img2, window, padding = window_size//2, groups=channel)
231
+
232
+ mu1_sq = mu1.pow(2)
233
+ mu2_sq = mu2.pow(2)
234
+ mu1_mu2 = mu1*mu2
235
+
236
+ sigma1_sq = F.conv2d(img1*img1, window, padding=window_size//2, groups=channel) - mu1_sq
237
+ sigma2_sq = F.conv2d(img2*img2, window, padding=window_size//2, groups=channel) - mu2_sq
238
+ sigma12 = F.conv2d(img1*img2, window, padding=window_size//2, groups=channel) - mu1_mu2
239
+
240
+ C1 = 0.01**2
241
+ C2 = 0.03**2
242
+
243
+ ssim_map = ((2*mu1_mu2 + C1)*(2*sigma12 + C2))/((mu1_sq + mu2_sq + C1)*(sigma1_sq + sigma2_sq + C2))
244
+
245
+ if size_average:
246
+ return ssim_map.mean()
247
+ else:
248
+ return ssim_map.mean(1).mean(1).mean(1)
249
+
250
+
251
+ def SSIM(x, y):
252
+ C1 = 0.01 ** 2
253
+ C2 = 0.03 ** 2
254
+
255
+ mu_x = nn.AvgPool2d(3, 1, 1)(x)
256
+ mu_y = nn.AvgPool2d(3, 1, 1)(y)
257
+ mu_x_mu_y = mu_x * mu_y
258
+ mu_x_sq = mu_x.pow(2)
259
+ mu_y_sq = mu_y.pow(2)
260
+
261
+ sigma_x = nn.AvgPool2d(3, 1, 1)(x * x) - mu_x_sq
262
+ sigma_y = nn.AvgPool2d(3, 1, 1)(y * y) - mu_y_sq
263
+ sigma_xy = nn.AvgPool2d(3, 1, 1)(x * y) - mu_x_mu_y
264
+
265
+ SSIM_n = (2 * mu_x_mu_y + C1) * (2 * sigma_xy + C2)
266
+ SSIM_d = (mu_x_sq + mu_y_sq + C1) * (sigma_x + sigma_y + C2)
267
+ SSIM = SSIM_n / SSIM_d
268
+
269
+ return torch.clamp((1 - SSIM) / 2, 0, 1)
270
+
271
+
272
+ def saliency_structure_consistency(x, y):
273
+ ssim = torch.mean(SSIM(x,y))
274
+ return ssim
BiRefNet_github/make_a_copy.sh ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Set dst repo here.
3
+ repo=$1
4
+ mkdir ../${repo}
5
+ mkdir ../${repo}/evaluation
6
+ mkdir ../${repo}/models
7
+ mkdir ../${repo}/models/backbones
8
+ mkdir ../${repo}/models/modules
9
+ mkdir ../${repo}/models/refinement
10
+
11
+ cp ./*.sh ../${repo}
12
+ cp ./*.py ../${repo}
13
+ cp ./evaluation/*.py ../${repo}/evaluation
14
+ cp ./models/*.py ../${repo}/models
15
+ cp ./models/backbones/*.py ../${repo}/models/backbones
16
+ cp ./models/modules/*.py ../${repo}/models/modules
17
+ cp ./models/refinement/*.py ../${repo}/models/refinement
18
+ cp -r ./.git* ../${repo}
BiRefNet_github/models/backbones/build_backbone.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from collections import OrderedDict
4
+ from torchvision.models import vgg16, vgg16_bn, VGG16_Weights, VGG16_BN_Weights, resnet50, ResNet50_Weights
5
+ from models.backbones.pvt_v2 import pvt_v2_b0, pvt_v2_b1, pvt_v2_b2, pvt_v2_b5
6
+ from models.backbones.swin_v1 import swin_v1_t, swin_v1_s, swin_v1_b, swin_v1_l
7
+ from config import Config
8
+
9
+
10
+ config = Config()
11
+
12
+ def build_backbone(bb_name, pretrained=True, params_settings=''):
13
+ if bb_name == 'vgg16':
14
+ bb_net = list(vgg16(pretrained=VGG16_Weights.DEFAULT if pretrained else None).children())[0]
15
+ bb = nn.Sequential(OrderedDict({'conv1': bb_net[:4], 'conv2': bb_net[4:9], 'conv3': bb_net[9:16], 'conv4': bb_net[16:23]}))
16
+ elif bb_name == 'vgg16bn':
17
+ bb_net = list(vgg16_bn(pretrained=VGG16_BN_Weights.DEFAULT if pretrained else None).children())[0]
18
+ bb = nn.Sequential(OrderedDict({'conv1': bb_net[:6], 'conv2': bb_net[6:13], 'conv3': bb_net[13:23], 'conv4': bb_net[23:33]}))
19
+ elif bb_name == 'resnet50':
20
+ bb_net = list(resnet50(pretrained=ResNet50_Weights.DEFAULT if pretrained else None).children())
21
+ bb = nn.Sequential(OrderedDict({'conv1': nn.Sequential(*bb_net[0:3]), 'conv2': bb_net[4], 'conv3': bb_net[5], 'conv4': bb_net[6]}))
22
+ else:
23
+ bb = eval('{}({})'.format(bb_name, params_settings))
24
+ if pretrained:
25
+ bb = load_weights(bb, bb_name)
26
+ return bb
27
+
28
+ def load_weights(model, model_name):
29
+ save_model = torch.load(config.weights[model_name], map_location='cpu')
30
+ model_dict = model.state_dict()
31
+ 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()}
32
+ # to ignore the weights with mismatched size when I modify the backbone itself.
33
+ if not state_dict:
34
+ save_model_keys = list(save_model.keys())
35
+ sub_item = save_model_keys[0] if len(save_model_keys) == 1 else None
36
+ 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()}
37
+ if not state_dict or not sub_item:
38
+ print('Weights are not successully loaded. Check the state dict of weights file.')
39
+ return None
40
+ else:
41
+ print('Found correct weights in the "{}" item of loaded state_dict.'.format(sub_item))
42
+ model_dict.update(state_dict)
43
+ model.load_state_dict(model_dict)
44
+ return model
BiRefNet_github/models/backbones/pvt_v2.py ADDED
@@ -0,0 +1,435 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from functools import partial
4
+
5
+ from timm.models.layers import DropPath, to_2tuple, trunc_normal_
6
+ from timm.models.registry import register_model
7
+
8
+ import math
9
+
10
+ from config import Config
11
+
12
+ config = Config()
13
+
14
+ class Mlp(nn.Module):
15
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
16
+ super().__init__()
17
+ out_features = out_features or in_features
18
+ hidden_features = hidden_features or in_features
19
+ self.fc1 = nn.Linear(in_features, hidden_features)
20
+ self.dwconv = DWConv(hidden_features)
21
+ self.act = act_layer()
22
+ self.fc2 = nn.Linear(hidden_features, out_features)
23
+ self.drop = nn.Dropout(drop)
24
+
25
+ self.apply(self._init_weights)
26
+
27
+ def _init_weights(self, m):
28
+ if isinstance(m, nn.Linear):
29
+ trunc_normal_(m.weight, std=.02)
30
+ if isinstance(m, nn.Linear) and m.bias is not None:
31
+ nn.init.constant_(m.bias, 0)
32
+ elif isinstance(m, nn.LayerNorm):
33
+ nn.init.constant_(m.bias, 0)
34
+ nn.init.constant_(m.weight, 1.0)
35
+ elif isinstance(m, nn.Conv2d):
36
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
37
+ fan_out //= m.groups
38
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
39
+ if m.bias is not None:
40
+ m.bias.data.zero_()
41
+
42
+ def forward(self, x, H, W):
43
+ x = self.fc1(x)
44
+ x = self.dwconv(x, H, W)
45
+ x = self.act(x)
46
+ x = self.drop(x)
47
+ x = self.fc2(x)
48
+ x = self.drop(x)
49
+ return x
50
+
51
+
52
+ class Attention(nn.Module):
53
+ def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., sr_ratio=1):
54
+ super().__init__()
55
+ assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}."
56
+
57
+ self.dim = dim
58
+ self.num_heads = num_heads
59
+ head_dim = dim // num_heads
60
+ self.scale = qk_scale or head_dim ** -0.5
61
+
62
+ self.q = nn.Linear(dim, dim, bias=qkv_bias)
63
+ self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias)
64
+ self.attn_drop_prob = attn_drop
65
+ self.attn_drop = nn.Dropout(attn_drop)
66
+ self.proj = nn.Linear(dim, dim)
67
+ self.proj_drop = nn.Dropout(proj_drop)
68
+
69
+ self.sr_ratio = sr_ratio
70
+ if sr_ratio > 1:
71
+ self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio)
72
+ self.norm = nn.LayerNorm(dim)
73
+
74
+ self.apply(self._init_weights)
75
+
76
+ def _init_weights(self, m):
77
+ if isinstance(m, nn.Linear):
78
+ trunc_normal_(m.weight, std=.02)
79
+ if isinstance(m, nn.Linear) and m.bias is not None:
80
+ nn.init.constant_(m.bias, 0)
81
+ elif isinstance(m, nn.LayerNorm):
82
+ nn.init.constant_(m.bias, 0)
83
+ nn.init.constant_(m.weight, 1.0)
84
+ elif isinstance(m, nn.Conv2d):
85
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
86
+ fan_out //= m.groups
87
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
88
+ if m.bias is not None:
89
+ m.bias.data.zero_()
90
+
91
+ def forward(self, x, H, W):
92
+ B, N, C = x.shape
93
+ q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
94
+
95
+ if self.sr_ratio > 1:
96
+ x_ = x.permute(0, 2, 1).reshape(B, C, H, W)
97
+ x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1)
98
+ x_ = self.norm(x_)
99
+ kv = self.kv(x_).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
100
+ else:
101
+ kv = self.kv(x).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
102
+ k, v = kv[0], kv[1]
103
+
104
+ if config.SDPA_enabled:
105
+ x = torch.nn.functional.scaled_dot_product_attention(
106
+ q, k, v,
107
+ attn_mask=None, dropout_p=self.attn_drop_prob, is_causal=False
108
+ ).transpose(1, 2).reshape(B, N, C)
109
+ else:
110
+ attn = (q @ k.transpose(-2, -1)) * self.scale
111
+ attn = attn.softmax(dim=-1)
112
+ attn = self.attn_drop(attn)
113
+
114
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
115
+ x = self.proj(x)
116
+ x = self.proj_drop(x)
117
+
118
+ return x
119
+
120
+
121
+ class Block(nn.Module):
122
+
123
+ def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
124
+ drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, sr_ratio=1):
125
+ super().__init__()
126
+ self.norm1 = norm_layer(dim)
127
+ self.attn = Attention(
128
+ dim,
129
+ num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
130
+ attn_drop=attn_drop, proj_drop=drop, sr_ratio=sr_ratio)
131
+ # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
132
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
133
+ self.norm2 = norm_layer(dim)
134
+ mlp_hidden_dim = int(dim * mlp_ratio)
135
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
136
+
137
+ self.apply(self._init_weights)
138
+
139
+ def _init_weights(self, m):
140
+ if isinstance(m, nn.Linear):
141
+ trunc_normal_(m.weight, std=.02)
142
+ if isinstance(m, nn.Linear) and m.bias is not None:
143
+ nn.init.constant_(m.bias, 0)
144
+ elif isinstance(m, nn.LayerNorm):
145
+ nn.init.constant_(m.bias, 0)
146
+ nn.init.constant_(m.weight, 1.0)
147
+ elif isinstance(m, nn.Conv2d):
148
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
149
+ fan_out //= m.groups
150
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
151
+ if m.bias is not None:
152
+ m.bias.data.zero_()
153
+
154
+ def forward(self, x, H, W):
155
+ x = x + self.drop_path(self.attn(self.norm1(x), H, W))
156
+ x = x + self.drop_path(self.mlp(self.norm2(x), H, W))
157
+
158
+ return x
159
+
160
+
161
+ class OverlapPatchEmbed(nn.Module):
162
+ """ Image to Patch Embedding
163
+ """
164
+
165
+ def __init__(self, img_size=224, patch_size=7, stride=4, in_channels=3, embed_dim=768):
166
+ super().__init__()
167
+ img_size = to_2tuple(img_size)
168
+ patch_size = to_2tuple(patch_size)
169
+
170
+ self.img_size = img_size
171
+ self.patch_size = patch_size
172
+ self.H, self.W = img_size[0] // patch_size[0], img_size[1] // patch_size[1]
173
+ self.num_patches = self.H * self.W
174
+ self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=stride,
175
+ padding=(patch_size[0] // 2, patch_size[1] // 2))
176
+ self.norm = nn.LayerNorm(embed_dim)
177
+
178
+ self.apply(self._init_weights)
179
+
180
+ def _init_weights(self, m):
181
+ if isinstance(m, nn.Linear):
182
+ trunc_normal_(m.weight, std=.02)
183
+ if isinstance(m, nn.Linear) and m.bias is not None:
184
+ nn.init.constant_(m.bias, 0)
185
+ elif isinstance(m, nn.LayerNorm):
186
+ nn.init.constant_(m.bias, 0)
187
+ nn.init.constant_(m.weight, 1.0)
188
+ elif isinstance(m, nn.Conv2d):
189
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
190
+ fan_out //= m.groups
191
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
192
+ if m.bias is not None:
193
+ m.bias.data.zero_()
194
+
195
+ def forward(self, x):
196
+ x = self.proj(x)
197
+ _, _, H, W = x.shape
198
+ x = x.flatten(2).transpose(1, 2)
199
+ x = self.norm(x)
200
+
201
+ return x, H, W
202
+
203
+
204
+ class PyramidVisionTransformerImpr(nn.Module):
205
+ def __init__(self, img_size=224, patch_size=16, in_channels=3, num_classes=1000, embed_dims=[64, 128, 256, 512],
206
+ num_heads=[1, 2, 4, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=False, qk_scale=None, drop_rate=0.,
207
+ attn_drop_rate=0., drop_path_rate=0., norm_layer=nn.LayerNorm,
208
+ depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1]):
209
+ super().__init__()
210
+ self.num_classes = num_classes
211
+ self.depths = depths
212
+
213
+ # patch_embed
214
+ self.patch_embed1 = OverlapPatchEmbed(img_size=img_size, patch_size=7, stride=4, in_channels=in_channels,
215
+ embed_dim=embed_dims[0])
216
+ self.patch_embed2 = OverlapPatchEmbed(img_size=img_size // 4, patch_size=3, stride=2, in_channels=embed_dims[0],
217
+ embed_dim=embed_dims[1])
218
+ self.patch_embed3 = OverlapPatchEmbed(img_size=img_size // 8, patch_size=3, stride=2, in_channels=embed_dims[1],
219
+ embed_dim=embed_dims[2])
220
+ self.patch_embed4 = OverlapPatchEmbed(img_size=img_size // 16, patch_size=3, stride=2, in_channels=embed_dims[2],
221
+ embed_dim=embed_dims[3])
222
+
223
+ # transformer encoder
224
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
225
+ cur = 0
226
+ self.block1 = nn.ModuleList([Block(
227
+ dim=embed_dims[0], num_heads=num_heads[0], mlp_ratio=mlp_ratios[0], qkv_bias=qkv_bias, qk_scale=qk_scale,
228
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
229
+ sr_ratio=sr_ratios[0])
230
+ for i in range(depths[0])])
231
+ self.norm1 = norm_layer(embed_dims[0])
232
+
233
+ cur += depths[0]
234
+ self.block2 = nn.ModuleList([Block(
235
+ dim=embed_dims[1], num_heads=num_heads[1], mlp_ratio=mlp_ratios[1], qkv_bias=qkv_bias, qk_scale=qk_scale,
236
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
237
+ sr_ratio=sr_ratios[1])
238
+ for i in range(depths[1])])
239
+ self.norm2 = norm_layer(embed_dims[1])
240
+
241
+ cur += depths[1]
242
+ self.block3 = nn.ModuleList([Block(
243
+ dim=embed_dims[2], num_heads=num_heads[2], mlp_ratio=mlp_ratios[2], qkv_bias=qkv_bias, qk_scale=qk_scale,
244
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
245
+ sr_ratio=sr_ratios[2])
246
+ for i in range(depths[2])])
247
+ self.norm3 = norm_layer(embed_dims[2])
248
+
249
+ cur += depths[2]
250
+ self.block4 = nn.ModuleList([Block(
251
+ dim=embed_dims[3], num_heads=num_heads[3], mlp_ratio=mlp_ratios[3], qkv_bias=qkv_bias, qk_scale=qk_scale,
252
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur + i], norm_layer=norm_layer,
253
+ sr_ratio=sr_ratios[3])
254
+ for i in range(depths[3])])
255
+ self.norm4 = norm_layer(embed_dims[3])
256
+
257
+ # classification head
258
+ # self.head = nn.Linear(embed_dims[3], num_classes) if num_classes > 0 else nn.Identity()
259
+
260
+ self.apply(self._init_weights)
261
+
262
+ def _init_weights(self, m):
263
+ if isinstance(m, nn.Linear):
264
+ trunc_normal_(m.weight, std=.02)
265
+ if isinstance(m, nn.Linear) and m.bias is not None:
266
+ nn.init.constant_(m.bias, 0)
267
+ elif isinstance(m, nn.LayerNorm):
268
+ nn.init.constant_(m.bias, 0)
269
+ nn.init.constant_(m.weight, 1.0)
270
+ elif isinstance(m, nn.Conv2d):
271
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
272
+ fan_out //= m.groups
273
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
274
+ if m.bias is not None:
275
+ m.bias.data.zero_()
276
+
277
+ def init_weights(self, pretrained=None):
278
+ if isinstance(pretrained, str):
279
+ logger = 1
280
+ #load_checkpoint(self, pretrained, map_location='cpu', strict=False, logger=logger)
281
+
282
+ def reset_drop_path(self, drop_path_rate):
283
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(self.depths))]
284
+ cur = 0
285
+ for i in range(self.depths[0]):
286
+ self.block1[i].drop_path.drop_prob = dpr[cur + i]
287
+
288
+ cur += self.depths[0]
289
+ for i in range(self.depths[1]):
290
+ self.block2[i].drop_path.drop_prob = dpr[cur + i]
291
+
292
+ cur += self.depths[1]
293
+ for i in range(self.depths[2]):
294
+ self.block3[i].drop_path.drop_prob = dpr[cur + i]
295
+
296
+ cur += self.depths[2]
297
+ for i in range(self.depths[3]):
298
+ self.block4[i].drop_path.drop_prob = dpr[cur + i]
299
+
300
+ def freeze_patch_emb(self):
301
+ self.patch_embed1.requires_grad = False
302
+
303
+ @torch.jit.ignore
304
+ def no_weight_decay(self):
305
+ return {'pos_embed1', 'pos_embed2', 'pos_embed3', 'pos_embed4', 'cls_token'} # has pos_embed may be better
306
+
307
+ def get_classifier(self):
308
+ return self.head
309
+
310
+ def reset_classifier(self, num_classes, global_pool=''):
311
+ self.num_classes = num_classes
312
+ self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()
313
+
314
+ def forward_features(self, x):
315
+ B = x.shape[0]
316
+ outs = []
317
+
318
+ # stage 1
319
+ x, H, W = self.patch_embed1(x)
320
+ for i, blk in enumerate(self.block1):
321
+ x = blk(x, H, W)
322
+ x = self.norm1(x)
323
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
324
+ outs.append(x)
325
+
326
+ # stage 2
327
+ x, H, W = self.patch_embed2(x)
328
+ for i, blk in enumerate(self.block2):
329
+ x = blk(x, H, W)
330
+ x = self.norm2(x)
331
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
332
+ outs.append(x)
333
+
334
+ # stage 3
335
+ x, H, W = self.patch_embed3(x)
336
+ for i, blk in enumerate(self.block3):
337
+ x = blk(x, H, W)
338
+ x = self.norm3(x)
339
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
340
+ outs.append(x)
341
+
342
+ # stage 4
343
+ x, H, W = self.patch_embed4(x)
344
+ for i, blk in enumerate(self.block4):
345
+ x = blk(x, H, W)
346
+ x = self.norm4(x)
347
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
348
+ outs.append(x)
349
+
350
+ return outs
351
+
352
+ # return x.mean(dim=1)
353
+
354
+ def forward(self, x):
355
+ x = self.forward_features(x)
356
+ # x = self.head(x)
357
+
358
+ return x
359
+
360
+
361
+ class DWConv(nn.Module):
362
+ def __init__(self, dim=768):
363
+ super(DWConv, self).__init__()
364
+ self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim)
365
+
366
+ def forward(self, x, H, W):
367
+ B, N, C = x.shape
368
+ x = x.transpose(1, 2).view(B, C, H, W).contiguous()
369
+ x = self.dwconv(x)
370
+ x = x.flatten(2).transpose(1, 2)
371
+
372
+ return x
373
+
374
+
375
+ def _conv_filter(state_dict, patch_size=16):
376
+ """ convert patch embedding weight from manual patchify + linear proj to conv"""
377
+ out_dict = {}
378
+ for k, v in state_dict.items():
379
+ if 'patch_embed.proj.weight' in k:
380
+ v = v.reshape((v.shape[0], 3, patch_size, patch_size))
381
+ out_dict[k] = v
382
+
383
+ return out_dict
384
+
385
+
386
+ ## @register_model
387
+ class pvt_v2_b0(PyramidVisionTransformerImpr):
388
+ def __init__(self, **kwargs):
389
+ super(pvt_v2_b0, self).__init__(
390
+ patch_size=4, embed_dims=[32, 64, 160, 256], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
391
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1],
392
+ drop_rate=0.0, drop_path_rate=0.1)
393
+
394
+
395
+
396
+ ## @register_model
397
+ class pvt_v2_b1(PyramidVisionTransformerImpr):
398
+ def __init__(self, **kwargs):
399
+ super(pvt_v2_b1, self).__init__(
400
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
401
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1],
402
+ drop_rate=0.0, drop_path_rate=0.1)
403
+
404
+ ## @register_model
405
+ class pvt_v2_b2(PyramidVisionTransformerImpr):
406
+ def __init__(self, in_channels=3, **kwargs):
407
+ super(pvt_v2_b2, self).__init__(
408
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
409
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1],
410
+ drop_rate=0.0, drop_path_rate=0.1, in_channels=in_channels)
411
+
412
+ ## @register_model
413
+ class pvt_v2_b3(PyramidVisionTransformerImpr):
414
+ def __init__(self, **kwargs):
415
+ super(pvt_v2_b3, self).__init__(
416
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
417
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 18, 3], sr_ratios=[8, 4, 2, 1],
418
+ drop_rate=0.0, drop_path_rate=0.1)
419
+
420
+ ## @register_model
421
+ class pvt_v2_b4(PyramidVisionTransformerImpr):
422
+ def __init__(self, **kwargs):
423
+ super(pvt_v2_b4, self).__init__(
424
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4],
425
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 8, 27, 3], sr_ratios=[8, 4, 2, 1],
426
+ drop_rate=0.0, drop_path_rate=0.1)
427
+
428
+
429
+ ## @register_model
430
+ class pvt_v2_b5(PyramidVisionTransformerImpr):
431
+ def __init__(self, **kwargs):
432
+ super(pvt_v2_b5, self).__init__(
433
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4],
434
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 6, 40, 3], sr_ratios=[8, 4, 2, 1],
435
+ drop_rate=0.0, drop_path_rate=0.1)
BiRefNet_github/models/backbones/swin_v1.py ADDED
@@ -0,0 +1,627 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # Swin Transformer
3
+ # Copyright (c) 2021 Microsoft
4
+ # Licensed under The MIT License [see LICENSE for details]
5
+ # Written by Ze Liu, Yutong Lin, Yixuan Wei
6
+ # --------------------------------------------------------
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.nn.functional as F
11
+ import torch.utils.checkpoint as checkpoint
12
+ import numpy as np
13
+ from timm.models.layers import DropPath, to_2tuple, trunc_normal_
14
+
15
+ from config import Config
16
+
17
+
18
+ config = Config()
19
+
20
+ class Mlp(nn.Module):
21
+ """ Multilayer perceptron."""
22
+
23
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
24
+ super().__init__()
25
+ out_features = out_features or in_features
26
+ hidden_features = hidden_features or in_features
27
+ self.fc1 = nn.Linear(in_features, hidden_features)
28
+ self.act = act_layer()
29
+ self.fc2 = nn.Linear(hidden_features, out_features)
30
+ self.drop = nn.Dropout(drop)
31
+
32
+ def forward(self, x):
33
+ x = self.fc1(x)
34
+ x = self.act(x)
35
+ x = self.drop(x)
36
+ x = self.fc2(x)
37
+ x = self.drop(x)
38
+ return x
39
+
40
+
41
+ def window_partition(x, window_size):
42
+ """
43
+ Args:
44
+ x: (B, H, W, C)
45
+ window_size (int): window size
46
+
47
+ Returns:
48
+ windows: (num_windows*B, window_size, window_size, C)
49
+ """
50
+ B, H, W, C = x.shape
51
+ x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
52
+ windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
53
+ return windows
54
+
55
+
56
+ def window_reverse(windows, window_size, H, W):
57
+ """
58
+ Args:
59
+ windows: (num_windows*B, window_size, window_size, C)
60
+ window_size (int): Window size
61
+ H (int): Height of image
62
+ W (int): Width of image
63
+
64
+ Returns:
65
+ x: (B, H, W, C)
66
+ """
67
+ B = int(windows.shape[0] / (H * W / window_size / window_size))
68
+ x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
69
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
70
+ return x
71
+
72
+
73
+ class WindowAttention(nn.Module):
74
+ """ Window based multi-head self attention (W-MSA) module with relative position bias.
75
+ It supports both of shifted and non-shifted window.
76
+
77
+ Args:
78
+ dim (int): Number of input channels.
79
+ window_size (tuple[int]): The height and width of the window.
80
+ num_heads (int): Number of attention heads.
81
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
82
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
83
+ attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
84
+ proj_drop (float, optional): Dropout ratio of output. Default: 0.0
85
+ """
86
+
87
+ def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.):
88
+
89
+ super().__init__()
90
+ self.dim = dim
91
+ self.window_size = window_size # Wh, Ww
92
+ self.num_heads = num_heads
93
+ head_dim = dim // num_heads
94
+ self.scale = qk_scale or head_dim ** -0.5
95
+
96
+ # define a parameter table of relative position bias
97
+ self.relative_position_bias_table = nn.Parameter(
98
+ torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH
99
+
100
+ # get pair-wise relative position index for each token inside the window
101
+ coords_h = torch.arange(self.window_size[0])
102
+ coords_w = torch.arange(self.window_size[1])
103
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w], indexing='ij')) # 2, Wh, Ww
104
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
105
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
106
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
107
+ relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
108
+ relative_coords[:, :, 1] += self.window_size[1] - 1
109
+ relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
110
+ relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
111
+ self.register_buffer("relative_position_index", relative_position_index)
112
+
113
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
114
+ self.attn_drop_prob = attn_drop
115
+ self.attn_drop = nn.Dropout(attn_drop)
116
+ self.proj = nn.Linear(dim, dim)
117
+ self.proj_drop = nn.Dropout(proj_drop)
118
+
119
+ trunc_normal_(self.relative_position_bias_table, std=.02)
120
+ self.softmax = nn.Softmax(dim=-1)
121
+
122
+ def forward(self, x, mask=None):
123
+ """ Forward function.
124
+
125
+ Args:
126
+ x: input features with shape of (num_windows*B, N, C)
127
+ mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
128
+ """
129
+ B_, N, C = x.shape
130
+ qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
131
+ q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
132
+
133
+ q = q * self.scale
134
+
135
+ if config.SDPA_enabled:
136
+ x = torch.nn.functional.scaled_dot_product_attention(
137
+ q, k, v,
138
+ attn_mask=None, dropout_p=self.attn_drop_prob, is_causal=False
139
+ ).transpose(1, 2).reshape(B_, N, C)
140
+ else:
141
+ attn = (q @ k.transpose(-2, -1))
142
+
143
+ relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
144
+ self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1) # Wh*Ww,Wh*Ww,nH
145
+ relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
146
+ attn = attn + relative_position_bias.unsqueeze(0)
147
+
148
+ if mask is not None:
149
+ nW = mask.shape[0]
150
+ attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
151
+ attn = attn.view(-1, self.num_heads, N, N)
152
+ attn = self.softmax(attn)
153
+ else:
154
+ attn = self.softmax(attn)
155
+
156
+ attn = self.attn_drop(attn)
157
+
158
+ x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
159
+ x = self.proj(x)
160
+ x = self.proj_drop(x)
161
+ return x
162
+
163
+
164
+ class SwinTransformerBlock(nn.Module):
165
+ """ Swin Transformer Block.
166
+
167
+ Args:
168
+ dim (int): Number of input channels.
169
+ num_heads (int): Number of attention heads.
170
+ window_size (int): Window size.
171
+ shift_size (int): Shift size for SW-MSA.
172
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
173
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
174
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
175
+ drop (float, optional): Dropout rate. Default: 0.0
176
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
177
+ drop_path (float, optional): Stochastic depth rate. Default: 0.0
178
+ act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
179
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
180
+ """
181
+
182
+ def __init__(self, dim, num_heads, window_size=7, shift_size=0,
183
+ mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0.,
184
+ act_layer=nn.GELU, norm_layer=nn.LayerNorm):
185
+ super().__init__()
186
+ self.dim = dim
187
+ self.num_heads = num_heads
188
+ self.window_size = window_size
189
+ self.shift_size = shift_size
190
+ self.mlp_ratio = mlp_ratio
191
+ assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
192
+
193
+ self.norm1 = norm_layer(dim)
194
+ self.attn = WindowAttention(
195
+ dim, window_size=to_2tuple(self.window_size), num_heads=num_heads,
196
+ qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
197
+
198
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
199
+ self.norm2 = norm_layer(dim)
200
+ mlp_hidden_dim = int(dim * mlp_ratio)
201
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
202
+
203
+ self.H = None
204
+ self.W = None
205
+
206
+ def forward(self, x, mask_matrix):
207
+ """ Forward function.
208
+
209
+ Args:
210
+ x: Input feature, tensor size (B, H*W, C).
211
+ H, W: Spatial resolution of the input feature.
212
+ mask_matrix: Attention mask for cyclic shift.
213
+ """
214
+ B, L, C = x.shape
215
+ H, W = self.H, self.W
216
+ assert L == H * W, "input feature has wrong size"
217
+
218
+ shortcut = x
219
+ x = self.norm1(x)
220
+ x = x.view(B, H, W, C)
221
+
222
+ # pad feature maps to multiples of window size
223
+ pad_l = pad_t = 0
224
+ pad_r = (self.window_size - W % self.window_size) % self.window_size
225
+ pad_b = (self.window_size - H % self.window_size) % self.window_size
226
+ x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b))
227
+ _, Hp, Wp, _ = x.shape
228
+
229
+ # cyclic shift
230
+ if self.shift_size > 0:
231
+ shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
232
+ attn_mask = mask_matrix
233
+ else:
234
+ shifted_x = x
235
+ attn_mask = None
236
+
237
+ # partition windows
238
+ x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C
239
+ x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C
240
+
241
+ # W-MSA/SW-MSA
242
+ attn_windows = self.attn(x_windows, mask=attn_mask) # nW*B, window_size*window_size, C
243
+
244
+ # merge windows
245
+ attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
246
+ shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp) # B H' W' C
247
+
248
+ # reverse cyclic shift
249
+ if self.shift_size > 0:
250
+ x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
251
+ else:
252
+ x = shifted_x
253
+
254
+ if pad_r > 0 or pad_b > 0:
255
+ x = x[:, :H, :W, :].contiguous()
256
+
257
+ x = x.view(B, H * W, C)
258
+
259
+ # FFN
260
+ x = shortcut + self.drop_path(x)
261
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
262
+
263
+ return x
264
+
265
+
266
+ class PatchMerging(nn.Module):
267
+ """ Patch Merging Layer
268
+
269
+ Args:
270
+ dim (int): Number of input channels.
271
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
272
+ """
273
+ def __init__(self, dim, norm_layer=nn.LayerNorm):
274
+ super().__init__()
275
+ self.dim = dim
276
+ self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
277
+ self.norm = norm_layer(4 * dim)
278
+
279
+ def forward(self, x, H, W):
280
+ """ Forward function.
281
+
282
+ Args:
283
+ x: Input feature, tensor size (B, H*W, C).
284
+ H, W: Spatial resolution of the input feature.
285
+ """
286
+ B, L, C = x.shape
287
+ assert L == H * W, "input feature has wrong size"
288
+
289
+ x = x.view(B, H, W, C)
290
+
291
+ # padding
292
+ pad_input = (H % 2 == 1) or (W % 2 == 1)
293
+ if pad_input:
294
+ x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2))
295
+
296
+ x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C
297
+ x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C
298
+ x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C
299
+ x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C
300
+ x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C
301
+ x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C
302
+
303
+ x = self.norm(x)
304
+ x = self.reduction(x)
305
+
306
+ return x
307
+
308
+
309
+ class BasicLayer(nn.Module):
310
+ """ A basic Swin Transformer layer for one stage.
311
+
312
+ Args:
313
+ dim (int): Number of feature channels
314
+ depth (int): Depths of this stage.
315
+ num_heads (int): Number of attention head.
316
+ window_size (int): Local window size. Default: 7.
317
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
318
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
319
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
320
+ drop (float, optional): Dropout rate. Default: 0.0
321
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
322
+ drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
323
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
324
+ downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
325
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
326
+ """
327
+
328
+ def __init__(self,
329
+ dim,
330
+ depth,
331
+ num_heads,
332
+ window_size=7,
333
+ mlp_ratio=4.,
334
+ qkv_bias=True,
335
+ qk_scale=None,
336
+ drop=0.,
337
+ attn_drop=0.,
338
+ drop_path=0.,
339
+ norm_layer=nn.LayerNorm,
340
+ downsample=None,
341
+ use_checkpoint=False):
342
+ super().__init__()
343
+ self.window_size = window_size
344
+ self.shift_size = window_size // 2
345
+ self.depth = depth
346
+ self.use_checkpoint = use_checkpoint
347
+
348
+ # build blocks
349
+ self.blocks = nn.ModuleList([
350
+ SwinTransformerBlock(
351
+ dim=dim,
352
+ num_heads=num_heads,
353
+ window_size=window_size,
354
+ shift_size=0 if (i % 2 == 0) else window_size // 2,
355
+ mlp_ratio=mlp_ratio,
356
+ qkv_bias=qkv_bias,
357
+ qk_scale=qk_scale,
358
+ drop=drop,
359
+ attn_drop=attn_drop,
360
+ drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
361
+ norm_layer=norm_layer)
362
+ for i in range(depth)])
363
+
364
+ # patch merging layer
365
+ if downsample is not None:
366
+ self.downsample = downsample(dim=dim, norm_layer=norm_layer)
367
+ else:
368
+ self.downsample = None
369
+
370
+ def forward(self, x, H, W):
371
+ """ Forward function.
372
+
373
+ Args:
374
+ x: Input feature, tensor size (B, H*W, C).
375
+ H, W: Spatial resolution of the input feature.
376
+ """
377
+
378
+ # calculate attention mask for SW-MSA
379
+ Hp = int(np.ceil(H / self.window_size)) * self.window_size
380
+ Wp = int(np.ceil(W / self.window_size)) * self.window_size
381
+ img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device) # 1 Hp Wp 1
382
+ h_slices = (slice(0, -self.window_size),
383
+ slice(-self.window_size, -self.shift_size),
384
+ slice(-self.shift_size, None))
385
+ w_slices = (slice(0, -self.window_size),
386
+ slice(-self.window_size, -self.shift_size),
387
+ slice(-self.shift_size, None))
388
+ cnt = 0
389
+ for h in h_slices:
390
+ for w in w_slices:
391
+ img_mask[:, h, w, :] = cnt
392
+ cnt += 1
393
+
394
+ mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1
395
+ mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
396
+ attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
397
+ attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0))
398
+
399
+ for blk in self.blocks:
400
+ blk.H, blk.W = H, W
401
+ if self.use_checkpoint:
402
+ x = checkpoint.checkpoint(blk, x, attn_mask)
403
+ else:
404
+ x = blk(x, attn_mask)
405
+ if self.downsample is not None:
406
+ x_down = self.downsample(x, H, W)
407
+ Wh, Ww = (H + 1) // 2, (W + 1) // 2
408
+ return x, H, W, x_down, Wh, Ww
409
+ else:
410
+ return x, H, W, x, H, W
411
+
412
+
413
+ class PatchEmbed(nn.Module):
414
+ """ Image to Patch Embedding
415
+
416
+ Args:
417
+ patch_size (int): Patch token size. Default: 4.
418
+ in_channels (int): Number of input image channels. Default: 3.
419
+ embed_dim (int): Number of linear projection output channels. Default: 96.
420
+ norm_layer (nn.Module, optional): Normalization layer. Default: None
421
+ """
422
+
423
+ def __init__(self, patch_size=4, in_channels=3, embed_dim=96, norm_layer=None):
424
+ super().__init__()
425
+ patch_size = to_2tuple(patch_size)
426
+ self.patch_size = patch_size
427
+
428
+ self.in_channels = in_channels
429
+ self.embed_dim = embed_dim
430
+
431
+ self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
432
+ if norm_layer is not None:
433
+ self.norm = norm_layer(embed_dim)
434
+ else:
435
+ self.norm = None
436
+
437
+ def forward(self, x):
438
+ """Forward function."""
439
+ # padding
440
+ _, _, H, W = x.size()
441
+ if W % self.patch_size[1] != 0:
442
+ x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1]))
443
+ if H % self.patch_size[0] != 0:
444
+ x = F.pad(x, (0, 0, 0, self.patch_size[0] - H % self.patch_size[0]))
445
+
446
+ x = self.proj(x) # B C Wh Ww
447
+ if self.norm is not None:
448
+ Wh, Ww = x.size(2), x.size(3)
449
+ x = x.flatten(2).transpose(1, 2)
450
+ x = self.norm(x)
451
+ x = x.transpose(1, 2).view(-1, self.embed_dim, Wh, Ww)
452
+
453
+ return x
454
+
455
+
456
+ class SwinTransformer(nn.Module):
457
+ """ Swin Transformer backbone.
458
+ A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` -
459
+ https://arxiv.org/pdf/2103.14030
460
+
461
+ Args:
462
+ pretrain_img_size (int): Input image size for training the pretrained model,
463
+ used in absolute postion embedding. Default 224.
464
+ patch_size (int | tuple(int)): Patch size. Default: 4.
465
+ in_channels (int): Number of input image channels. Default: 3.
466
+ embed_dim (int): Number of linear projection output channels. Default: 96.
467
+ depths (tuple[int]): Depths of each Swin Transformer stage.
468
+ num_heads (tuple[int]): Number of attention head of each stage.
469
+ window_size (int): Window size. Default: 7.
470
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
471
+ qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
472
+ qk_scale (float): Override default qk scale of head_dim ** -0.5 if set.
473
+ drop_rate (float): Dropout rate.
474
+ attn_drop_rate (float): Attention dropout rate. Default: 0.
475
+ drop_path_rate (float): Stochastic depth rate. Default: 0.2.
476
+ norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
477
+ ape (bool): If True, add absolute position embedding to the patch embedding. Default: False.
478
+ patch_norm (bool): If True, add normalization after patch embedding. Default: True.
479
+ out_indices (Sequence[int]): Output from which stages.
480
+ frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
481
+ -1 means not freezing any parameters.
482
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
483
+ """
484
+
485
+ def __init__(self,
486
+ pretrain_img_size=224,
487
+ patch_size=4,
488
+ in_channels=3,
489
+ embed_dim=96,
490
+ depths=[2, 2, 6, 2],
491
+ num_heads=[3, 6, 12, 24],
492
+ window_size=7,
493
+ mlp_ratio=4.,
494
+ qkv_bias=True,
495
+ qk_scale=None,
496
+ drop_rate=0.,
497
+ attn_drop_rate=0.,
498
+ drop_path_rate=0.2,
499
+ norm_layer=nn.LayerNorm,
500
+ ape=False,
501
+ patch_norm=True,
502
+ out_indices=(0, 1, 2, 3),
503
+ frozen_stages=-1,
504
+ use_checkpoint=False):
505
+ super().__init__()
506
+
507
+ self.pretrain_img_size = pretrain_img_size
508
+ self.num_layers = len(depths)
509
+ self.embed_dim = embed_dim
510
+ self.ape = ape
511
+ self.patch_norm = patch_norm
512
+ self.out_indices = out_indices
513
+ self.frozen_stages = frozen_stages
514
+
515
+ # split image into non-overlapping patches
516
+ self.patch_embed = PatchEmbed(
517
+ patch_size=patch_size, in_channels=in_channels, embed_dim=embed_dim,
518
+ norm_layer=norm_layer if self.patch_norm else None)
519
+
520
+ # absolute position embedding
521
+ if self.ape:
522
+ pretrain_img_size = to_2tuple(pretrain_img_size)
523
+ patch_size = to_2tuple(patch_size)
524
+ patches_resolution = [pretrain_img_size[0] // patch_size[0], pretrain_img_size[1] // patch_size[1]]
525
+
526
+ self.absolute_pos_embed = nn.Parameter(torch.zeros(1, embed_dim, patches_resolution[0], patches_resolution[1]))
527
+ trunc_normal_(self.absolute_pos_embed, std=.02)
528
+
529
+ self.pos_drop = nn.Dropout(p=drop_rate)
530
+
531
+ # stochastic depth
532
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
533
+
534
+ # build layers
535
+ self.layers = nn.ModuleList()
536
+ for i_layer in range(self.num_layers):
537
+ layer = BasicLayer(
538
+ dim=int(embed_dim * 2 ** i_layer),
539
+ depth=depths[i_layer],
540
+ num_heads=num_heads[i_layer],
541
+ window_size=window_size,
542
+ mlp_ratio=mlp_ratio,
543
+ qkv_bias=qkv_bias,
544
+ qk_scale=qk_scale,
545
+ drop=drop_rate,
546
+ attn_drop=attn_drop_rate,
547
+ drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])],
548
+ norm_layer=norm_layer,
549
+ downsample=PatchMerging if (i_layer < self.num_layers - 1) else None,
550
+ use_checkpoint=use_checkpoint)
551
+ self.layers.append(layer)
552
+
553
+ num_features = [int(embed_dim * 2 ** i) for i in range(self.num_layers)]
554
+ self.num_features = num_features
555
+
556
+ # add a norm layer for each output
557
+ for i_layer in out_indices:
558
+ layer = norm_layer(num_features[i_layer])
559
+ layer_name = f'norm{i_layer}'
560
+ self.add_module(layer_name, layer)
561
+
562
+ self._freeze_stages()
563
+
564
+ def _freeze_stages(self):
565
+ if self.frozen_stages >= 0:
566
+ self.patch_embed.eval()
567
+ for param in self.patch_embed.parameters():
568
+ param.requires_grad = False
569
+
570
+ if self.frozen_stages >= 1 and self.ape:
571
+ self.absolute_pos_embed.requires_grad = False
572
+
573
+ if self.frozen_stages >= 2:
574
+ self.pos_drop.eval()
575
+ for i in range(0, self.frozen_stages - 1):
576
+ m = self.layers[i]
577
+ m.eval()
578
+ for param in m.parameters():
579
+ param.requires_grad = False
580
+
581
+
582
+ def forward(self, x):
583
+ """Forward function."""
584
+ x = self.patch_embed(x)
585
+
586
+ Wh, Ww = x.size(2), x.size(3)
587
+ if self.ape:
588
+ # interpolate the position embedding to the corresponding size
589
+ absolute_pos_embed = F.interpolate(self.absolute_pos_embed, size=(Wh, Ww), mode='bicubic')
590
+ x = (x + absolute_pos_embed) # B Wh*Ww C
591
+
592
+ outs = []#x.contiguous()]
593
+ x = x.flatten(2).transpose(1, 2)
594
+ x = self.pos_drop(x)
595
+ for i in range(self.num_layers):
596
+ layer = self.layers[i]
597
+ x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww)
598
+
599
+ if i in self.out_indices:
600
+ norm_layer = getattr(self, f'norm{i}')
601
+ x_out = norm_layer(x_out)
602
+
603
+ out = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous()
604
+ outs.append(out)
605
+
606
+ return tuple(outs)
607
+
608
+ def train(self, mode=True):
609
+ """Convert the model into training mode while keep layers freezed."""
610
+ super(SwinTransformer, self).train(mode)
611
+ self._freeze_stages()
612
+
613
+ def swin_v1_t():
614
+ model = SwinTransformer(embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7)
615
+ return model
616
+
617
+ def swin_v1_s():
618
+ model = SwinTransformer(embed_dim=96, depths=[2, 2, 18, 2], num_heads=[3, 6, 12, 24], window_size=7)
619
+ return model
620
+
621
+ def swin_v1_b():
622
+ model = SwinTransformer(embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=12)
623
+ return model
624
+
625
+ def swin_v1_l():
626
+ model = SwinTransformer(embed_dim=192, depths=[2, 2, 18, 2], num_heads=[6, 12, 24, 48], window_size=12)
627
+ return model
BiRefNet_github/models/birefnet.py ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from kornia.filters import laplacian
5
+ from huggingface_hub import PyTorchModelHubMixin
6
+
7
+ from config import Config
8
+ from dataset import class_labels_TR_sorted
9
+ from models.backbones.build_backbone import build_backbone
10
+ from models.modules.decoder_blocks import BasicDecBlk, ResBlk, HierarAttDecBlk
11
+ from models.modules.lateral_blocks import BasicLatBlk
12
+ from models.modules.aspp import ASPP, ASPPDeformable
13
+ from models.modules.ing import *
14
+ from models.refinement.refiner import Refiner, RefinerPVTInChannels4, RefUNet
15
+ from models.refinement.stem_layer import StemLayer
16
+
17
+
18
+ class BiRefNet(
19
+ nn.Module,
20
+ PyTorchModelHubMixin,
21
+ library_name="birefnet",
22
+ repo_url="https://github.com/ZhengPeng7/BiRefNet",
23
+ tags=['Image Segmentation', 'Background Removal', 'Mask Generation', 'Dichotomous Image Segmentation', 'Camouflaged Object Detection', 'Salient Object Detection']
24
+ ):
25
+ def __init__(self, bb_pretrained=True):
26
+ super(BiRefNet, self).__init__()
27
+ self.config = Config()
28
+ self.epoch = 1
29
+ self.bb = build_backbone(self.config.bb, pretrained=bb_pretrained)
30
+
31
+ channels = self.config.lateral_channels_in_collection
32
+
33
+ if self.config.auxiliary_classification:
34
+ self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
35
+ self.cls_head = nn.Sequential(
36
+ nn.Linear(channels[0], len(class_labels_TR_sorted))
37
+ )
38
+
39
+ if self.config.squeeze_block:
40
+ self.squeeze_module = nn.Sequential(*[
41
+ eval(self.config.squeeze_block.split('_x')[0])(channels[0]+sum(self.config.cxt), channels[0])
42
+ for _ in range(eval(self.config.squeeze_block.split('_x')[1]))
43
+ ])
44
+
45
+ self.decoder = Decoder(channels)
46
+
47
+ if self.config.ender:
48
+ self.dec_end = nn.Sequential(
49
+ nn.Conv2d(1, 16, 3, 1, 1),
50
+ nn.Conv2d(16, 1, 3, 1, 1),
51
+ nn.ReLU(inplace=True),
52
+ )
53
+
54
+ # refine patch-level segmentation
55
+ if self.config.refine:
56
+ if self.config.refine == 'itself':
57
+ 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')
58
+ else:
59
+ self.refiner = eval('{}({})'.format(self.config.refine, 'in_channels=3+1'))
60
+
61
+ if self.config.freeze_bb:
62
+ # Freeze the backbone...
63
+ print(self.named_parameters())
64
+ for key, value in self.named_parameters():
65
+ if 'bb.' in key and 'refiner.' not in key:
66
+ value.requires_grad = False
67
+
68
+ def forward_enc(self, x):
69
+ if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']:
70
+ x1 = self.bb.conv1(x); x2 = self.bb.conv2(x1); x3 = self.bb.conv3(x2); x4 = self.bb.conv4(x3)
71
+ else:
72
+ x1, x2, x3, x4 = self.bb(x)
73
+ if self.config.mul_scl_ipt == 'cat':
74
+ B, C, H, W = x.shape
75
+ x1_, x2_, x3_, x4_ = self.bb(F.interpolate(x, size=(H//2, W//2), mode='bilinear', align_corners=True))
76
+ x1 = torch.cat([x1, F.interpolate(x1_, size=x1.shape[2:], mode='bilinear', align_corners=True)], dim=1)
77
+ x2 = torch.cat([x2, F.interpolate(x2_, size=x2.shape[2:], mode='bilinear', align_corners=True)], dim=1)
78
+ x3 = torch.cat([x3, F.interpolate(x3_, size=x3.shape[2:], mode='bilinear', align_corners=True)], dim=1)
79
+ x4 = torch.cat([x4, F.interpolate(x4_, size=x4.shape[2:], mode='bilinear', align_corners=True)], dim=1)
80
+ elif self.config.mul_scl_ipt == 'add':
81
+ B, C, H, W = x.shape
82
+ x1_, x2_, x3_, x4_ = self.bb(F.interpolate(x, size=(H//2, W//2), mode='bilinear', align_corners=True))
83
+ x1 = x1 + F.interpolate(x1_, size=x1.shape[2:], mode='bilinear', align_corners=True)
84
+ x2 = x2 + F.interpolate(x2_, size=x2.shape[2:], mode='bilinear', align_corners=True)
85
+ x3 = x3 + F.interpolate(x3_, size=x3.shape[2:], mode='bilinear', align_corners=True)
86
+ x4 = x4 + F.interpolate(x4_, size=x4.shape[2:], mode='bilinear', align_corners=True)
87
+ class_preds = self.cls_head(self.avgpool(x4).view(x4.shape[0], -1)) if self.training and self.config.auxiliary_classification else None
88
+ if self.config.cxt:
89
+ x4 = torch.cat(
90
+ (
91
+ *[
92
+ F.interpolate(x1, size=x4.shape[2:], mode='bilinear', align_corners=True),
93
+ F.interpolate(x2, size=x4.shape[2:], mode='bilinear', align_corners=True),
94
+ F.interpolate(x3, size=x4.shape[2:], mode='bilinear', align_corners=True),
95
+ ][-len(self.config.cxt):],
96
+ x4
97
+ ),
98
+ dim=1
99
+ )
100
+ return (x1, x2, x3, x4), class_preds
101
+
102
+ def forward_ori(self, x):
103
+ ########## Encoder ##########
104
+ (x1, x2, x3, x4), class_preds = self.forward_enc(x)
105
+ if self.config.squeeze_block:
106
+ x4 = self.squeeze_module(x4)
107
+ ########## Decoder ##########
108
+ features = [x, x1, x2, x3, x4]
109
+ if self.training and self.config.out_ref:
110
+ features.append(laplacian(torch.mean(x, dim=1).unsqueeze(1), kernel_size=5))
111
+ scaled_preds = self.decoder(features)
112
+ return scaled_preds, class_preds
113
+
114
+ def forward(self, x):
115
+ scaled_preds, class_preds = self.forward_ori(x)
116
+ class_preds_lst = [class_preds]
117
+ return [scaled_preds, class_preds_lst] if self.training else scaled_preds
118
+
119
+
120
+ class Decoder(nn.Module):
121
+ def __init__(self, channels):
122
+ super(Decoder, self).__init__()
123
+ self.config = Config()
124
+ DecoderBlock = eval(self.config.dec_blk)
125
+ LateralBlock = eval(self.config.lat_blk)
126
+
127
+ if self.config.dec_ipt:
128
+ self.split = self.config.dec_ipt_split
129
+ N_dec_ipt = 64
130
+ DBlock = SimpleConvs
131
+ ic = 64
132
+ ipt_cha_opt = 1
133
+ self.ipt_blk5 = DBlock(2**10*3 if self.split else 3, [N_dec_ipt, channels[0]//8][ipt_cha_opt], inter_channels=ic)
134
+ self.ipt_blk4 = DBlock(2**8*3 if self.split else 3, [N_dec_ipt, channels[0]//8][ipt_cha_opt], inter_channels=ic)
135
+ self.ipt_blk3 = DBlock(2**6*3 if self.split else 3, [N_dec_ipt, channels[1]//8][ipt_cha_opt], inter_channels=ic)
136
+ self.ipt_blk2 = DBlock(2**4*3 if self.split else 3, [N_dec_ipt, channels[2]//8][ipt_cha_opt], inter_channels=ic)
137
+ self.ipt_blk1 = DBlock(2**0*3 if self.split else 3, [N_dec_ipt, channels[3]//8][ipt_cha_opt], inter_channels=ic)
138
+ else:
139
+ self.split = None
140
+
141
+ self.decoder_block4 = DecoderBlock(channels[0]+([N_dec_ipt, channels[0]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[1])
142
+ self.decoder_block3 = DecoderBlock(channels[1]+([N_dec_ipt, channels[0]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[2])
143
+ self.decoder_block2 = DecoderBlock(channels[2]+([N_dec_ipt, channels[1]//8][ipt_cha_opt] if self.config.dec_ipt else 0), channels[3])
144
+ 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)
145
+ 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))
146
+
147
+ self.lateral_block4 = LateralBlock(channels[1], channels[1])
148
+ self.lateral_block3 = LateralBlock(channels[2], channels[2])
149
+ self.lateral_block2 = LateralBlock(channels[3], channels[3])
150
+
151
+ if self.config.ms_supervision:
152
+ self.conv_ms_spvn_4 = nn.Conv2d(channels[1], 1, 1, 1, 0)
153
+ self.conv_ms_spvn_3 = nn.Conv2d(channels[2], 1, 1, 1, 0)
154
+ self.conv_ms_spvn_2 = nn.Conv2d(channels[3], 1, 1, 1, 0)
155
+
156
+ if self.config.out_ref:
157
+ _N = 16
158
+ 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))
159
+ 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))
160
+ 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))
161
+
162
+ self.gdt_convs_pred_4 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
163
+ self.gdt_convs_pred_3 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
164
+ self.gdt_convs_pred_2 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
165
+
166
+ self.gdt_convs_attn_4 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
167
+ self.gdt_convs_attn_3 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
168
+ self.gdt_convs_attn_2 = nn.Sequential(nn.Conv2d(_N, 1, 1, 1, 0))
169
+
170
+ def get_patches_batch(self, x, p):
171
+ _size_h, _size_w = p.shape[2:]
172
+ patches_batch = []
173
+ for idx in range(x.shape[0]):
174
+ columns_x = torch.split(x[idx], split_size_or_sections=_size_w, dim=-1)
175
+ patches_x = []
176
+ for column_x in columns_x:
177
+ patches_x += [p.unsqueeze(0) for p in torch.split(column_x, split_size_or_sections=_size_h, dim=-2)]
178
+ patch_sample = torch.cat(patches_x, dim=1)
179
+ patches_batch.append(patch_sample)
180
+ return torch.cat(patches_batch, dim=0)
181
+
182
+ def forward(self, features):
183
+ if self.training and self.config.out_ref:
184
+ outs_gdt_pred = []
185
+ outs_gdt_label = []
186
+ x, x1, x2, x3, x4, gdt_gt = features
187
+ else:
188
+ x, x1, x2, x3, x4 = features
189
+ outs = []
190
+
191
+ if self.config.dec_ipt:
192
+ patches_batch = self.get_patches_batch(x, x4) if self.split else x
193
+ x4 = torch.cat((x4, self.ipt_blk5(F.interpolate(patches_batch, size=x4.shape[2:], mode='bilinear', align_corners=True))), 1)
194
+ p4 = self.decoder_block4(x4)
195
+ m4 = self.conv_ms_spvn_4(p4) if self.config.ms_supervision else None
196
+ if self.config.out_ref:
197
+ p4_gdt = self.gdt_convs_4(p4)
198
+ if self.training:
199
+ # >> GT:
200
+ m4_dia = m4
201
+ gdt_label_main_4 = gdt_gt * F.interpolate(m4_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True)
202
+ outs_gdt_label.append(gdt_label_main_4)
203
+ # >> Pred:
204
+ gdt_pred_4 = self.gdt_convs_pred_4(p4_gdt)
205
+ outs_gdt_pred.append(gdt_pred_4)
206
+ gdt_attn_4 = self.gdt_convs_attn_4(p4_gdt).sigmoid()
207
+ # >> Finally:
208
+ p4 = p4 * gdt_attn_4
209
+ _p4 = F.interpolate(p4, size=x3.shape[2:], mode='bilinear', align_corners=True)
210
+ _p3 = _p4 + self.lateral_block4(x3)
211
+
212
+ if self.config.dec_ipt:
213
+ patches_batch = self.get_patches_batch(x, _p3) if self.split else x
214
+ _p3 = torch.cat((_p3, self.ipt_blk4(F.interpolate(patches_batch, size=x3.shape[2:], mode='bilinear', align_corners=True))), 1)
215
+ p3 = self.decoder_block3(_p3)
216
+ m3 = self.conv_ms_spvn_3(p3) if self.config.ms_supervision else None
217
+ if self.config.out_ref:
218
+ p3_gdt = self.gdt_convs_3(p3)
219
+ if self.training:
220
+ # >> GT:
221
+ # m3 --dilation--> m3_dia
222
+ # G_3^gt * m3_dia --> G_3^m, which is the label of gradient
223
+ m3_dia = m3
224
+ gdt_label_main_3 = gdt_gt * F.interpolate(m3_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True)
225
+ outs_gdt_label.append(gdt_label_main_3)
226
+ # >> Pred:
227
+ # p3 --conv--BN--> F_3^G, where F_3^G predicts the \hat{G_3} with xx
228
+ # F_3^G --sigmoid--> A_3^G
229
+ gdt_pred_3 = self.gdt_convs_pred_3(p3_gdt)
230
+ outs_gdt_pred.append(gdt_pred_3)
231
+ gdt_attn_3 = self.gdt_convs_attn_3(p3_gdt).sigmoid()
232
+ # >> Finally:
233
+ # p3 = p3 * A_3^G
234
+ p3 = p3 * gdt_attn_3
235
+ _p3 = F.interpolate(p3, size=x2.shape[2:], mode='bilinear', align_corners=True)
236
+ _p2 = _p3 + self.lateral_block3(x2)
237
+
238
+ if self.config.dec_ipt:
239
+ patches_batch = self.get_patches_batch(x, _p2) if self.split else x
240
+ _p2 = torch.cat((_p2, self.ipt_blk3(F.interpolate(patches_batch, size=x2.shape[2:], mode='bilinear', align_corners=True))), 1)
241
+ p2 = self.decoder_block2(_p2)
242
+ m2 = self.conv_ms_spvn_2(p2) if self.config.ms_supervision else None
243
+ if self.config.out_ref:
244
+ p2_gdt = self.gdt_convs_2(p2)
245
+ if self.training:
246
+ # >> GT:
247
+ m2_dia = m2
248
+ gdt_label_main_2 = gdt_gt * F.interpolate(m2_dia, size=gdt_gt.shape[2:], mode='bilinear', align_corners=True)
249
+ outs_gdt_label.append(gdt_label_main_2)
250
+ # >> Pred:
251
+ gdt_pred_2 = self.gdt_convs_pred_2(p2_gdt)
252
+ outs_gdt_pred.append(gdt_pred_2)
253
+ gdt_attn_2 = self.gdt_convs_attn_2(p2_gdt).sigmoid()
254
+ # >> Finally:
255
+ p2 = p2 * gdt_attn_2
256
+ _p2 = F.interpolate(p2, size=x1.shape[2:], mode='bilinear', align_corners=True)
257
+ _p1 = _p2 + self.lateral_block2(x1)
258
+
259
+ if self.config.dec_ipt:
260
+ patches_batch = self.get_patches_batch(x, _p1) if self.split else x
261
+ _p1 = torch.cat((_p1, self.ipt_blk2(F.interpolate(patches_batch, size=x1.shape[2:], mode='bilinear', align_corners=True))), 1)
262
+ _p1 = self.decoder_block1(_p1)
263
+ _p1 = F.interpolate(_p1, size=x.shape[2:], mode='bilinear', align_corners=True)
264
+
265
+ if self.config.dec_ipt:
266
+ patches_batch = self.get_patches_batch(x, _p1) if self.split else x
267
+ _p1 = torch.cat((_p1, self.ipt_blk1(F.interpolate(patches_batch, size=x.shape[2:], mode='bilinear', align_corners=True))), 1)
268
+ p1_out = self.conv_out1(_p1)
269
+
270
+ if self.config.ms_supervision:
271
+ outs.append(m4)
272
+ outs.append(m3)
273
+ outs.append(m2)
274
+ outs.append(p1_out)
275
+ return outs if not (self.config.out_ref and self.training) else ([outs_gdt_pred, outs_gdt_label], outs)
276
+
277
+
278
+ class SimpleConvs(nn.Module):
279
+ def __init__(
280
+ self, in_channels: int, out_channels: int, inter_channels=64
281
+ ) -> None:
282
+ super().__init__()
283
+ self.conv1 = nn.Conv2d(in_channels, inter_channels, 3, 1, 1)
284
+ self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, 1)
285
+
286
+ def forward(self, x):
287
+ return self.conv_out(self.conv1(x))
BiRefNet_github/models/modules/aspp.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from models.modules.deform_conv import DeformableConv2d
5
+ from config import Config
6
+
7
+
8
+ config = Config()
9
+
10
+
11
+ class _ASPPModule(nn.Module):
12
+ def __init__(self, in_channels, planes, kernel_size, padding, dilation):
13
+ super(_ASPPModule, self).__init__()
14
+ self.atrous_conv = nn.Conv2d(in_channels, planes, kernel_size=kernel_size,
15
+ stride=1, padding=padding, dilation=dilation, bias=False)
16
+ self.bn = nn.BatchNorm2d(planes) if config.batch_size > 1 else nn.Identity()
17
+ self.relu = nn.ReLU(inplace=True)
18
+
19
+ def forward(self, x):
20
+ x = self.atrous_conv(x)
21
+ x = self.bn(x)
22
+
23
+ return self.relu(x)
24
+
25
+
26
+ class ASPP(nn.Module):
27
+ def __init__(self, in_channels=64, out_channels=None, output_stride=16):
28
+ super(ASPP, self).__init__()
29
+ self.down_scale = 1
30
+ if out_channels is None:
31
+ out_channels = in_channels
32
+ self.in_channelster = 256 // self.down_scale
33
+ if output_stride == 16:
34
+ dilations = [1, 6, 12, 18]
35
+ elif output_stride == 8:
36
+ dilations = [1, 12, 24, 36]
37
+ else:
38
+ raise NotImplementedError
39
+
40
+ self.aspp1 = _ASPPModule(in_channels, self.in_channelster, 1, padding=0, dilation=dilations[0])
41
+ self.aspp2 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[1], dilation=dilations[1])
42
+ self.aspp3 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[2], dilation=dilations[2])
43
+ self.aspp4 = _ASPPModule(in_channels, self.in_channelster, 3, padding=dilations[3], dilation=dilations[3])
44
+
45
+ self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)),
46
+ nn.Conv2d(in_channels, self.in_channelster, 1, stride=1, bias=False),
47
+ nn.BatchNorm2d(self.in_channelster) if config.batch_size > 1 else nn.Identity(),
48
+ nn.ReLU(inplace=True))
49
+ self.conv1 = nn.Conv2d(self.in_channelster * 5, out_channels, 1, bias=False)
50
+ self.bn1 = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
51
+ self.relu = nn.ReLU(inplace=True)
52
+ self.dropout = nn.Dropout(0.5)
53
+
54
+ def forward(self, x):
55
+ x1 = self.aspp1(x)
56
+ x2 = self.aspp2(x)
57
+ x3 = self.aspp3(x)
58
+ x4 = self.aspp4(x)
59
+ x5 = self.global_avg_pool(x)
60
+ x5 = F.interpolate(x5, size=x1.size()[2:], mode='bilinear', align_corners=True)
61
+ x = torch.cat((x1, x2, x3, x4, x5), dim=1)
62
+
63
+ x = self.conv1(x)
64
+ x = self.bn1(x)
65
+ x = self.relu(x)
66
+
67
+ return self.dropout(x)
68
+
69
+
70
+ ##################### Deformable
71
+ class _ASPPModuleDeformable(nn.Module):
72
+ def __init__(self, in_channels, planes, kernel_size, padding):
73
+ super(_ASPPModuleDeformable, self).__init__()
74
+ self.atrous_conv = DeformableConv2d(in_channels, planes, kernel_size=kernel_size,
75
+ stride=1, padding=padding, bias=False)
76
+ self.bn = nn.BatchNorm2d(planes) if config.batch_size > 1 else nn.Identity()
77
+ self.relu = nn.ReLU(inplace=True)
78
+
79
+ def forward(self, x):
80
+ x = self.atrous_conv(x)
81
+ x = self.bn(x)
82
+
83
+ return self.relu(x)
84
+
85
+
86
+ class ASPPDeformable(nn.Module):
87
+ def __init__(self, in_channels, out_channels=None, parallel_block_sizes=[1, 3, 7]):
88
+ super(ASPPDeformable, self).__init__()
89
+ self.down_scale = 1
90
+ if out_channels is None:
91
+ out_channels = in_channels
92
+ self.in_channelster = 256 // self.down_scale
93
+
94
+ self.aspp1 = _ASPPModuleDeformable(in_channels, self.in_channelster, 1, padding=0)
95
+ self.aspp_deforms = nn.ModuleList([
96
+ _ASPPModuleDeformable(in_channels, self.in_channelster, conv_size, padding=int(conv_size//2)) for conv_size in parallel_block_sizes
97
+ ])
98
+
99
+ self.global_avg_pool = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)),
100
+ nn.Conv2d(in_channels, self.in_channelster, 1, stride=1, bias=False),
101
+ nn.BatchNorm2d(self.in_channelster) if config.batch_size > 1 else nn.Identity(),
102
+ nn.ReLU(inplace=True))
103
+ self.conv1 = nn.Conv2d(self.in_channelster * (2 + len(self.aspp_deforms)), out_channels, 1, bias=False)
104
+ self.bn1 = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
105
+ self.relu = nn.ReLU(inplace=True)
106
+ self.dropout = nn.Dropout(0.5)
107
+
108
+ def forward(self, x):
109
+ x1 = self.aspp1(x)
110
+ x_aspp_deforms = [aspp_deform(x) for aspp_deform in self.aspp_deforms]
111
+ x5 = self.global_avg_pool(x)
112
+ x5 = F.interpolate(x5, size=x1.size()[2:], mode='bilinear', align_corners=True)
113
+ x = torch.cat((x1, *x_aspp_deforms, x5), dim=1)
114
+
115
+ x = self.conv1(x)
116
+ x = self.bn1(x)
117
+ x = self.relu(x)
118
+
119
+ return self.dropout(x)
BiRefNet_github/models/modules/attentions.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ from torch import nn
4
+ from torch.nn import init
5
+
6
+
7
+ class SEWeightModule(nn.Module):
8
+ def __init__(self, channels, reduction=16):
9
+ super(SEWeightModule, self).__init__()
10
+ self.avg_pool = nn.AdaptiveAvgPool2d(1)
11
+ self.fc1 = nn.Conv2d(channels, channels//reduction, kernel_size=1, padding=0)
12
+ self.relu = nn.ReLU(inplace=True)
13
+ self.fc2 = nn.Conv2d(channels//reduction, channels, kernel_size=1, padding=0)
14
+ self.sigmoid = nn.Sigmoid()
15
+
16
+ def forward(self, x):
17
+ out = self.avg_pool(x)
18
+ out = self.fc1(out)
19
+ out = self.relu(out)
20
+ out = self.fc2(out)
21
+ weight = self.sigmoid(out)
22
+ return weight
23
+
24
+
25
+ class PSA(nn.Module):
26
+
27
+ def __init__(self, in_channels, S=4, reduction=4):
28
+ super().__init__()
29
+ self.S = S
30
+
31
+ _convs = []
32
+ for i in range(S):
33
+ _convs.append(nn.Conv2d(in_channels//S, in_channels//S, kernel_size=2*(i+1)+1, padding=i+1))
34
+ self.convs = nn.ModuleList(_convs)
35
+
36
+ self.se_block = SEWeightModule(in_channels//S, reduction=S*reduction)
37
+
38
+ self.softmax = nn.Softmax(dim=1)
39
+
40
+ def forward(self, x):
41
+ b, c, h, w = x.size()
42
+
43
+ # Step1: SPC module
44
+ SPC_out = x.view(b, self.S, c//self.S, h, w) #bs,s,ci,h,w
45
+ for idx, conv in enumerate(self.convs):
46
+ SPC_out[:,idx,:,:,:] = conv(SPC_out[:,idx,:,:,:].clone())
47
+
48
+ # Step2: SE weight
49
+ se_out=[]
50
+ for idx in range(self.S):
51
+ se_out.append(self.se_block(SPC_out[:, idx, :, :, :]))
52
+ SE_out = torch.stack(se_out, dim=1)
53
+ SE_out = SE_out.expand_as(SPC_out)
54
+
55
+ # Step3: Softmax
56
+ softmax_out = self.softmax(SE_out)
57
+
58
+ # Step4: SPA
59
+ PSA_out = SPC_out * softmax_out
60
+ PSA_out = PSA_out.view(b, -1, h, w)
61
+
62
+ return PSA_out
63
+
64
+
65
+ class SGE(nn.Module):
66
+
67
+ def __init__(self, groups):
68
+ super().__init__()
69
+ self.groups=groups
70
+ self.avg_pool = nn.AdaptiveAvgPool2d(1)
71
+ self.weight=nn.Parameter(torch.zeros(1,groups,1,1))
72
+ self.bias=nn.Parameter(torch.zeros(1,groups,1,1))
73
+ self.sig=nn.Sigmoid()
74
+
75
+ def forward(self, x):
76
+ b, c, h,w=x.shape
77
+ x=x.view(b*self.groups,-1,h,w) #bs*g,dim//g,h,w
78
+ xn=x*self.avg_pool(x) #bs*g,dim//g,h,w
79
+ xn=xn.sum(dim=1,keepdim=True) #bs*g,1,h,w
80
+ t=xn.view(b*self.groups,-1) #bs*g,h*w
81
+
82
+ t=t-t.mean(dim=1,keepdim=True) #bs*g,h*w
83
+ std=t.std(dim=1,keepdim=True)+1e-5
84
+ t=t/std #bs*g,h*w
85
+ t=t.view(b,self.groups,h,w) #bs,g,h*w
86
+
87
+ t=t*self.weight+self.bias #bs,g,h*w
88
+ t=t.view(b*self.groups,1,h,w) #bs*g,1,h*w
89
+ x=x*self.sig(t)
90
+ x=x.view(b,c,h,w)
91
+
92
+ return x
93
+
BiRefNet_github/models/modules/decoder_blocks.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from models.modules.aspp import ASPP, ASPPDeformable
4
+ from models.modules.attentions import PSA, SGE
5
+ from config import Config
6
+
7
+
8
+ config = Config()
9
+
10
+
11
+ class BasicDecBlk(nn.Module):
12
+ def __init__(self, in_channels=64, out_channels=64, inter_channels=64):
13
+ super(BasicDecBlk, self).__init__()
14
+ inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64
15
+ self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, padding=1)
16
+ self.relu_in = nn.ReLU(inplace=True)
17
+ if config.dec_att == 'ASPP':
18
+ self.dec_att = ASPP(in_channels=inter_channels)
19
+ elif config.dec_att == 'ASPPDeformable':
20
+ self.dec_att = ASPPDeformable(in_channels=inter_channels)
21
+ self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, padding=1)
22
+ self.bn_in = nn.BatchNorm2d(inter_channels) if config.batch_size > 1 else nn.Identity()
23
+ self.bn_out = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
24
+
25
+ def forward(self, x):
26
+ x = self.conv_in(x)
27
+ x = self.bn_in(x)
28
+ x = self.relu_in(x)
29
+ if hasattr(self, 'dec_att'):
30
+ x = self.dec_att(x)
31
+ x = self.conv_out(x)
32
+ x = self.bn_out(x)
33
+ return x
34
+
35
+
36
+ class ResBlk(nn.Module):
37
+ def __init__(self, in_channels=64, out_channels=None, inter_channels=64):
38
+ super(ResBlk, self).__init__()
39
+ if out_channels is None:
40
+ out_channels = in_channels
41
+ inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64
42
+
43
+ self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, padding=1)
44
+ self.bn_in = nn.BatchNorm2d(inter_channels) if config.batch_size > 1 else nn.Identity()
45
+ self.relu_in = nn.ReLU(inplace=True)
46
+
47
+ if config.dec_att == 'ASPP':
48
+ self.dec_att = ASPP(in_channels=inter_channels)
49
+ elif config.dec_att == 'ASPPDeformable':
50
+ self.dec_att = ASPPDeformable(in_channels=inter_channels)
51
+
52
+ self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, padding=1)
53
+ self.bn_out = nn.BatchNorm2d(out_channels) if config.batch_size > 1 else nn.Identity()
54
+
55
+ self.conv_resi = nn.Conv2d(in_channels, out_channels, 1, 1, 0)
56
+
57
+ def forward(self, x):
58
+ _x = self.conv_resi(x)
59
+ x = self.conv_in(x)
60
+ x = self.bn_in(x)
61
+ x = self.relu_in(x)
62
+ if hasattr(self, 'dec_att'):
63
+ x = self.dec_att(x)
64
+ x = self.conv_out(x)
65
+ x = self.bn_out(x)
66
+ return x + _x
67
+
68
+
69
+ class HierarAttDecBlk(nn.Module):
70
+ def __init__(self, in_channels=64, out_channels=None, inter_channels=64):
71
+ super(HierarAttDecBlk, self).__init__()
72
+ if out_channels is None:
73
+ out_channels = in_channels
74
+ inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64
75
+ self.split_y = 8 # must be divided by channels of all intermediate features
76
+ self.split_x = 8
77
+
78
+ self.conv_in = nn.Conv2d(in_channels, inter_channels, 3, 1, 1)
79
+
80
+ self.psa = PSA(inter_channels*self.split_y*self.split_x, S=config.batch_size)
81
+ self.sge = SGE(groups=config.batch_size)
82
+
83
+ if config.dec_att == 'ASPP':
84
+ self.dec_att = ASPP(in_channels=inter_channels)
85
+ elif config.dec_att == 'ASPPDeformable':
86
+ self.dec_att = ASPPDeformable(in_channels=inter_channels)
87
+ self.conv_out = nn.Conv2d(inter_channels, out_channels, 3, 1, 1)
88
+
89
+ def forward(self, x):
90
+ x = self.conv_in(x)
91
+ N, C, H, W = x.shape
92
+ x_patchs = x.reshape(N, -1, H//self.split_y, W//self.split_x)
93
+
94
+ # Hierarchical attention: group attention X patch spatial attention
95
+ x_patchs = self.psa(x_patchs) # Group Channel Attention -- each group is a single image
96
+ x_patchs = self.sge(x_patchs) # Patch Spatial Attention
97
+ x = x.reshape(N, C, H, W)
98
+ if hasattr(self, 'dec_att'):
99
+ x = self.dec_att(x)
100
+ x = self.conv_out(x)
101
+ return x
BiRefNet_github/models/modules/deform_conv.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from torchvision.ops import deform_conv2d
4
+
5
+
6
+ class DeformableConv2d(nn.Module):
7
+ def __init__(self,
8
+ in_channels,
9
+ out_channels,
10
+ kernel_size=3,
11
+ stride=1,
12
+ padding=1,
13
+ bias=False):
14
+
15
+ super(DeformableConv2d, self).__init__()
16
+
17
+ assert type(kernel_size) == tuple or type(kernel_size) == int
18
+
19
+ kernel_size = kernel_size if type(kernel_size) == tuple else (kernel_size, kernel_size)
20
+ self.stride = stride if type(stride) == tuple else (stride, stride)
21
+ self.padding = padding
22
+
23
+ self.offset_conv = nn.Conv2d(in_channels,
24
+ 2 * kernel_size[0] * kernel_size[1],
25
+ kernel_size=kernel_size,
26
+ stride=stride,
27
+ padding=self.padding,
28
+ bias=True)
29
+
30
+ nn.init.constant_(self.offset_conv.weight, 0.)
31
+ nn.init.constant_(self.offset_conv.bias, 0.)
32
+
33
+ self.modulator_conv = nn.Conv2d(in_channels,
34
+ 1 * kernel_size[0] * kernel_size[1],
35
+ kernel_size=kernel_size,
36
+ stride=stride,
37
+ padding=self.padding,
38
+ bias=True)
39
+
40
+ nn.init.constant_(self.modulator_conv.weight, 0.)
41
+ nn.init.constant_(self.modulator_conv.bias, 0.)
42
+
43
+ self.regular_conv = nn.Conv2d(in_channels,
44
+ out_channels=out_channels,
45
+ kernel_size=kernel_size,
46
+ stride=stride,
47
+ padding=self.padding,
48
+ bias=bias)
49
+
50
+ def forward(self, x):
51
+ #h, w = x.shape[2:]
52
+ #max_offset = max(h, w)/4.
53
+
54
+ offset = self.offset_conv(x)#.clamp(-max_offset, max_offset)
55
+ modulator = 2. * torch.sigmoid(self.modulator_conv(x))
56
+
57
+ x = deform_conv2d(
58
+ input=x,
59
+ offset=offset,
60
+ weight=self.regular_conv.weight,
61
+ bias=self.regular_conv.bias,
62
+ padding=self.padding,
63
+ mask=modulator,
64
+ stride=self.stride,
65
+ )
66
+ return x
BiRefNet_github/models/modules/ing.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+ from models.modules.mlp import MLPLayer
3
+
4
+
5
+ class BlockA(nn.Module):
6
+ def __init__(self, in_channels=64, out_channels=64, inter_channels=64, mlp_ratio=4.):
7
+ super(BlockA, self).__init__()
8
+ inter_channels = in_channels
9
+ self.conv = nn.Conv2d(in_channels, inter_channels, 3, 1, 1)
10
+ self.norm1 = nn.LayerNorm(inter_channels)
11
+ self.ffn = MLPLayer(in_features=inter_channels,
12
+ hidden_features=int(inter_channels * mlp_ratio),
13
+ act_layer=nn.GELU,
14
+ drop=0.)
15
+ self.norm2 = nn.LayerNorm(inter_channels)
16
+
17
+ def forward(self, x):
18
+ B, C, H, W = x.shape
19
+ _x = self.conv(x)
20
+ _x = _x.flatten(2).transpose(1, 2)
21
+ _x = self.norm1(_x)
22
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
23
+
24
+ x = x + _x
25
+ _x1 = self.ffn(x)
26
+ _x1 = self.norm2(_x1)
27
+ _x1 = _x1.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
28
+ x = x + _x1
29
+ return x
BiRefNet_github/models/modules/lateral_blocks.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ from functools import partial
6
+
7
+ from config import Config
8
+
9
+
10
+ config = Config()
11
+
12
+
13
+ class BasicLatBlk(nn.Module):
14
+ def __init__(self, in_channels=64, out_channels=64, inter_channels=64):
15
+ super(BasicLatBlk, self).__init__()
16
+ inter_channels = in_channels // 4 if config.dec_channels_inter == 'adap' else 64
17
+ self.conv = nn.Conv2d(in_channels, out_channels, 1, 1, 0)
18
+
19
+ def forward(self, x):
20
+ x = self.conv(x)
21
+ return x
BiRefNet_github/models/modules/mlp.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from functools import partial
4
+
5
+ from timm.models.layers import DropPath, to_2tuple, trunc_normal_
6
+ from timm.models.registry import register_model
7
+
8
+ import math
9
+
10
+
11
+ class MLPLayer(nn.Module):
12
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
13
+ super().__init__()
14
+ out_features = out_features or in_features
15
+ hidden_features = hidden_features or in_features
16
+ self.fc1 = nn.Linear(in_features, hidden_features)
17
+ self.act = act_layer()
18
+ self.fc2 = nn.Linear(hidden_features, out_features)
19
+ self.drop = nn.Dropout(drop)
20
+
21
+ def forward(self, x):
22
+ x = self.fc1(x)
23
+ x = self.act(x)
24
+ x = self.drop(x)
25
+ x = self.fc2(x)
26
+ x = self.drop(x)
27
+ return x
28
+
29
+
30
+ class Attention(nn.Module):
31
+ def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., sr_ratio=1):
32
+ super().__init__()
33
+ assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}."
34
+
35
+ self.dim = dim
36
+ self.num_heads = num_heads
37
+ head_dim = dim // num_heads
38
+ self.scale = qk_scale or head_dim ** -0.5
39
+
40
+ self.q = nn.Linear(dim, dim, bias=qkv_bias)
41
+ self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias)
42
+ self.attn_drop = nn.Dropout(attn_drop)
43
+ self.proj = nn.Linear(dim, dim)
44
+ self.proj_drop = nn.Dropout(proj_drop)
45
+
46
+ self.sr_ratio = sr_ratio
47
+ if sr_ratio > 1:
48
+ self.sr = nn.Conv2d(dim, dim, kernel_size=sr_ratio, stride=sr_ratio)
49
+ self.norm = nn.LayerNorm(dim)
50
+
51
+ def forward(self, x, H, W):
52
+ B, N, C = x.shape
53
+ q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
54
+
55
+ if self.sr_ratio > 1:
56
+ x_ = x.permute(0, 2, 1).reshape(B, C, H, W)
57
+ x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1)
58
+ x_ = self.norm(x_)
59
+ kv = self.kv(x_).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
60
+ else:
61
+ kv = self.kv(x).reshape(B, -1, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
62
+ k, v = kv[0], kv[1]
63
+
64
+ attn = (q @ k.transpose(-2, -1)) * self.scale
65
+ attn = attn.softmax(dim=-1)
66
+ attn = self.attn_drop(attn)
67
+
68
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
69
+ x = self.proj(x)
70
+ x = self.proj_drop(x)
71
+ return x
72
+
73
+
74
+ class Block(nn.Module):
75
+ def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
76
+ drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, sr_ratio=1):
77
+ super().__init__()
78
+ self.norm1 = norm_layer(dim)
79
+ self.attn = Attention(
80
+ dim,
81
+ num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
82
+ attn_drop=attn_drop, proj_drop=drop, sr_ratio=sr_ratio)
83
+ # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
84
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
85
+ self.norm2 = norm_layer(dim)
86
+ mlp_hidden_dim = int(dim * mlp_ratio)
87
+ self.mlp = MLPLayer(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
88
+
89
+ def forward(self, x, H, W):
90
+ x = x + self.drop_path(self.attn(self.norm1(x), H, W))
91
+ x = x + self.drop_path(self.mlp(self.norm2(x), H, W))
92
+ return x
93
+
94
+
95
+ class OverlapPatchEmbed(nn.Module):
96
+ """ Image to Patch Embedding
97
+ """
98
+
99
+ def __init__(self, img_size=224, patch_size=7, stride=4, in_channels=3, embed_dim=768):
100
+ super().__init__()
101
+ img_size = to_2tuple(img_size)
102
+ patch_size = to_2tuple(patch_size)
103
+
104
+ self.img_size = img_size
105
+ self.patch_size = patch_size
106
+ self.H, self.W = img_size[0] // patch_size[0], img_size[1] // patch_size[1]
107
+ self.num_patches = self.H * self.W
108
+ self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=patch_size, stride=stride,
109
+ padding=(patch_size[0] // 2, patch_size[1] // 2))
110
+ self.norm = nn.LayerNorm(embed_dim)
111
+
112
+ def forward(self, x):
113
+ x = self.proj(x)
114
+ _, _, H, W = x.shape
115
+ x = x.flatten(2).transpose(1, 2)
116
+ x = self.norm(x)
117
+ return x, H, W
118
+
BiRefNet_github/models/modules/prompt_encoder.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ import torch.nn as nn
4
+ from typing import Any, Optional, Tuple, Type
5
+
6
+
7
+ class PromptEncoder(nn.Module):
8
+ def __init__(
9
+ self,
10
+ embed_dim=256,
11
+ image_embedding_size=1024,
12
+ input_image_size=(1024, 1024),
13
+ mask_in_chans=16,
14
+ activation=nn.GELU
15
+ ) -> None:
16
+ super().__init__()
17
+ """
18
+ Codes are partially from SAM: https://github.com/facebookresearch/segment-anything/blob/6fdee8f2727f4506cfbbe553e23b895e27956588/segment_anything/modeling/prompt_encoder.py.
19
+
20
+ Arguments:
21
+ embed_dim (int): The prompts' embedding dimension
22
+ image_embedding_size (tuple(int, int)): The spatial size of the
23
+ image embedding, as (H, W).
24
+ input_image_size (int): The padded size of the image as input
25
+ to the image encoder, as (H, W).
26
+ mask_in_chans (int): The number of hidden channels used for
27
+ encoding input masks.
28
+ activation (nn.Module): The activation to use when encoding
29
+ input masks.
30
+ """
31
+ super().__init__()
32
+ self.embed_dim = embed_dim
33
+ self.input_image_size = input_image_size
34
+ self.image_embedding_size = image_embedding_size
35
+ self.pe_layer = PositionEmbeddingRandom(embed_dim // 2)
36
+
37
+ self.num_point_embeddings: int = 4 # pos/neg point + 2 box corners
38
+ point_embeddings = [nn.Embedding(1, embed_dim) for i in range(self.num_point_embeddings)]
39
+ self.point_embeddings = nn.ModuleList(point_embeddings)
40
+ self.not_a_point_embed = nn.Embedding(1, embed_dim)
41
+
42
+ self.mask_input_size = (4 * image_embedding_size[0], 4 * image_embedding_size[1])
43
+ self.mask_downscaling = nn.Sequential(
44
+ nn.Conv2d(1, mask_in_chans // 4, kernel_size=2, stride=2),
45
+ LayerNorm2d(mask_in_chans // 4),
46
+ activation(),
47
+ nn.Conv2d(mask_in_chans // 4, mask_in_chans, kernel_size=2, stride=2),
48
+ LayerNorm2d(mask_in_chans),
49
+ activation(),
50
+ nn.Conv2d(mask_in_chans, embed_dim, kernel_size=1),
51
+ )
52
+ self.no_mask_embed = nn.Embedding(1, embed_dim)
53
+
54
+ def get_dense_pe(self) -> torch.Tensor:
55
+ """
56
+ Returns the positional encoding used to encode point prompts,
57
+ applied to a dense set of points the shape of the image encoding.
58
+
59
+ Returns:
60
+ torch.Tensor: Positional encoding with shape
61
+ 1x(embed_dim)x(embedding_h)x(embedding_w)
62
+ """
63
+ return self.pe_layer(self.image_embedding_size).unsqueeze(0)
64
+
65
+ def _embed_points(
66
+ self,
67
+ points: torch.Tensor,
68
+ labels: torch.Tensor,
69
+ pad: bool,
70
+ ) -> torch.Tensor:
71
+ """Embeds point prompts."""
72
+ points = points + 0.5 # Shift to center of pixel
73
+ if pad:
74
+ padding_point = torch.zeros((points.shape[0], 1, 2), device=points.device)
75
+ padding_label = -torch.ones((labels.shape[0], 1), device=labels.device)
76
+ points = torch.cat([points, padding_point], dim=1)
77
+ labels = torch.cat([labels, padding_label], dim=1)
78
+ point_embedding = self.pe_layer.forward_with_coords(points, self.input_image_size)
79
+ point_embedding[labels == -1] = 0.0
80
+ point_embedding[labels == -1] += self.not_a_point_embed.weight
81
+ point_embedding[labels == 0] += self.point_embeddings[0].weight
82
+ point_embedding[labels == 1] += self.point_embeddings[1].weight
83
+ return point_embedding
84
+
85
+ def _embed_boxes(self, boxes: torch.Tensor) -> torch.Tensor:
86
+ """Embeds box prompts."""
87
+ boxes = boxes + 0.5 # Shift to center of pixel
88
+ coords = boxes.reshape(-1, 2, 2)
89
+ corner_embedding = self.pe_layer.forward_with_coords(coords, self.input_image_size)
90
+ corner_embedding[:, 0, :] += self.point_embeddings[2].weight
91
+ corner_embedding[:, 1, :] += self.point_embeddings[3].weight
92
+ return corner_embedding
93
+
94
+ def _embed_masks(self, masks: torch.Tensor) -> torch.Tensor:
95
+ """Embeds mask inputs."""
96
+ mask_embedding = self.mask_downscaling(masks)
97
+ return mask_embedding
98
+
99
+ def _get_batch_size(
100
+ self,
101
+ points: Optional[Tuple[torch.Tensor, torch.Tensor]],
102
+ boxes: Optional[torch.Tensor],
103
+ masks: Optional[torch.Tensor],
104
+ ) -> int:
105
+ """
106
+ Gets the batch size of the output given the batch size of the input prompts.
107
+ """
108
+ if points is not None:
109
+ return points[0].shape[0]
110
+ elif boxes is not None:
111
+ return boxes.shape[0]
112
+ elif masks is not None:
113
+ return masks.shape[0]
114
+ else:
115
+ return 1
116
+
117
+ def _get_device(self) -> torch.device:
118
+ return self.point_embeddings[0].weight.device
119
+
120
+ def forward(
121
+ self,
122
+ points: Optional[Tuple[torch.Tensor, torch.Tensor]],
123
+ boxes: Optional[torch.Tensor],
124
+ masks: Optional[torch.Tensor],
125
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
126
+ """
127
+ Embeds different types of prompts, returning both sparse and dense
128
+ embeddings.
129
+
130
+ Arguments:
131
+ points (tuple(torch.Tensor, torch.Tensor) or none): point coordinates
132
+ and labels to embed.
133
+ boxes (torch.Tensor or none): boxes to embed
134
+ masks (torch.Tensor or none): masks to embed
135
+
136
+ Returns:
137
+ torch.Tensor: sparse embeddings for the points and boxes, with shape
138
+ BxNx(embed_dim), where N is determined by the number of input points
139
+ and boxes.
140
+ torch.Tensor: dense embeddings for the masks, in the shape
141
+ Bx(embed_dim)x(embed_H)x(embed_W)
142
+ """
143
+ bs = self._get_batch_size(points, boxes, masks)
144
+ sparse_embeddings = torch.empty((bs, 0, self.embed_dim), device=self._get_device())
145
+ if points is not None:
146
+ coords, labels = points
147
+ point_embeddings = self._embed_points(coords, labels, pad=(boxes is None))
148
+ sparse_embeddings = torch.cat([sparse_embeddings, point_embeddings], dim=1)
149
+ if boxes is not None:
150
+ box_embeddings = self._embed_boxes(boxes)
151
+ sparse_embeddings = torch.cat([sparse_embeddings, box_embeddings], dim=1)
152
+
153
+ if masks is not None:
154
+ dense_embeddings = self._embed_masks(masks)
155
+ else:
156
+ dense_embeddings = self.no_mask_embed.weight.reshape(1, -1, 1, 1).expand(
157
+ bs, -1, self.image_embedding_size[0], self.image_embedding_size[1]
158
+ )
159
+
160
+ return sparse_embeddings, dense_embeddings
161
+
162
+
163
+ class PositionEmbeddingRandom(nn.Module):
164
+ """
165
+ Positional encoding using random spatial frequencies.
166
+ """
167
+
168
+ def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None:
169
+ super().__init__()
170
+ if scale is None or scale <= 0.0:
171
+ scale = 1.0
172
+ self.register_buffer(
173
+ "positional_encoding_gaussian_matrix",
174
+ scale * torch.randn((2, num_pos_feats)),
175
+ )
176
+
177
+ def _pe_encoding(self, coords: torch.Tensor) -> torch.Tensor:
178
+ """Positionally encode points that are normalized to [0,1]."""
179
+ # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape
180
+ coords = 2 * coords - 1
181
+ coords = coords @ self.positional_encoding_gaussian_matrix
182
+ coords = 2 * np.pi * coords
183
+ # outputs d_1 x ... x d_n x C shape
184
+ return torch.cat([torch.sin(coords), torch.cos(coords)], dim=-1)
185
+
186
+ def forward(self, size: Tuple[int, int]) -> torch.Tensor:
187
+ """Generate positional encoding for a grid of the specified size."""
188
+ h, w = size
189
+ device: Any = self.positional_encoding_gaussian_matrix.device
190
+ grid = torch.ones((h, w), device=device, dtype=torch.float32)
191
+ y_embed = grid.cumsum(dim=0) - 0.5
192
+ x_embed = grid.cumsum(dim=1) - 0.5
193
+ y_embed = y_embed / h
194
+ x_embed = x_embed / w
195
+
196
+ pe = self._pe_encoding(torch.stack([x_embed, y_embed], dim=-1))
197
+ return pe.permute(2, 0, 1) # C x H x W
198
+
199
+ def forward_with_coords(
200
+ self, coords_input: torch.Tensor, image_size: Tuple[int, int]
201
+ ) -> torch.Tensor:
202
+ """Positionally encode points that are not normalized to [0,1]."""
203
+ coords = coords_input.clone()
204
+ coords[:, :, 0] = coords[:, :, 0] / image_size[1]
205
+ coords[:, :, 1] = coords[:, :, 1] / image_size[0]
206
+ return self._pe_encoding(coords.to(torch.float)) # B x N x C
207
+
208
+
209
+ class LayerNorm2d(nn.Module):
210
+ def __init__(self, num_channels: int, eps: float = 1e-6) -> None:
211
+ super().__init__()
212
+ self.weight = nn.Parameter(torch.ones(num_channels))
213
+ self.bias = nn.Parameter(torch.zeros(num_channels))
214
+ self.eps = eps
215
+
216
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
217
+ u = x.mean(1, keepdim=True)
218
+ s = (x - u).pow(2).mean(1, keepdim=True)
219
+ x = (x - u) / torch.sqrt(s + self.eps)
220
+ x = self.weight[:, None, None] * x + self.bias[:, None, None]
221
+ return x
222
+
BiRefNet_github/models/modules/utils.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+
3
+
4
+ def build_act_layer(act_layer):
5
+ if act_layer == 'ReLU':
6
+ return nn.ReLU(inplace=True)
7
+ elif act_layer == 'SiLU':
8
+ return nn.SiLU(inplace=True)
9
+ elif act_layer == 'GELU':
10
+ return nn.GELU()
11
+
12
+ raise NotImplementedError(f'build_act_layer does not support {act_layer}')
13
+
14
+
15
+ def build_norm_layer(dim,
16
+ norm_layer,
17
+ in_format='channels_last',
18
+ out_format='channels_last',
19
+ eps=1e-6):
20
+ layers = []
21
+ if norm_layer == 'BN':
22
+ if in_format == 'channels_last':
23
+ layers.append(to_channels_first())
24
+ layers.append(nn.BatchNorm2d(dim))
25
+ if out_format == 'channels_last':
26
+ layers.append(to_channels_last())
27
+ elif norm_layer == 'LN':
28
+ if in_format == 'channels_first':
29
+ layers.append(to_channels_last())
30
+ layers.append(nn.LayerNorm(dim, eps=eps))
31
+ if out_format == 'channels_first':
32
+ layers.append(to_channels_first())
33
+ else:
34
+ raise NotImplementedError(
35
+ f'build_norm_layer does not support {norm_layer}')
36
+ return nn.Sequential(*layers)
37
+
38
+
39
+ class to_channels_first(nn.Module):
40
+
41
+ def __init__(self):
42
+ super().__init__()
43
+
44
+ def forward(self, x):
45
+ return x.permute(0, 3, 1, 2)
46
+
47
+
48
+ class to_channels_last(nn.Module):
49
+
50
+ def __init__(self):
51
+ super().__init__()
52
+
53
+ def forward(self, x):
54
+ return x.permute(0, 2, 3, 1)
BiRefNet_github/models/refinement/refiner.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from collections import OrderedDict
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ from torchvision.models import vgg16, vgg16_bn
8
+ from torchvision.models import resnet50
9
+
10
+ from config import Config
11
+ from dataset import class_labels_TR_sorted
12
+ from models.backbones.build_backbone import build_backbone
13
+ from models.modules.decoder_blocks import BasicDecBlk
14
+ from models.modules.lateral_blocks import BasicLatBlk
15
+ from models.modules.ing import *
16
+ from models.refinement.stem_layer import StemLayer
17
+
18
+
19
+ class RefinerPVTInChannels4(nn.Module):
20
+ def __init__(self, in_channels=3+1):
21
+ super(RefinerPVTInChannels4, self).__init__()
22
+ self.config = Config()
23
+ self.epoch = 1
24
+ self.bb = build_backbone(self.config.bb, params_settings='in_channels=4')
25
+
26
+ lateral_channels_in_collection = {
27
+ 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64],
28
+ 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64],
29
+ 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192],
30
+ }
31
+ channels = lateral_channels_in_collection[self.config.bb]
32
+ self.squeeze_module = BasicDecBlk(channels[0], channels[0])
33
+
34
+ self.decoder = Decoder(channels)
35
+
36
+ if 0:
37
+ for key, value in self.named_parameters():
38
+ if 'bb.' in key:
39
+ value.requires_grad = False
40
+
41
+ def forward(self, x):
42
+ if isinstance(x, list):
43
+ x = torch.cat(x, dim=1)
44
+ ########## Encoder ##########
45
+ if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']:
46
+ x1 = self.bb.conv1(x)
47
+ x2 = self.bb.conv2(x1)
48
+ x3 = self.bb.conv3(x2)
49
+ x4 = self.bb.conv4(x3)
50
+ else:
51
+ x1, x2, x3, x4 = self.bb(x)
52
+
53
+ x4 = self.squeeze_module(x4)
54
+
55
+ ########## Decoder ##########
56
+
57
+ features = [x, x1, x2, x3, x4]
58
+ scaled_preds = self.decoder(features)
59
+
60
+ return scaled_preds
61
+
62
+
63
+ class Refiner(nn.Module):
64
+ def __init__(self, in_channels=3+1):
65
+ super(Refiner, self).__init__()
66
+ self.config = Config()
67
+ self.epoch = 1
68
+ 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')
69
+ self.bb = build_backbone(self.config.bb)
70
+
71
+ lateral_channels_in_collection = {
72
+ 'vgg16': [512, 256, 128, 64], 'vgg16bn': [512, 256, 128, 64], 'resnet50': [1024, 512, 256, 64],
73
+ 'pvt_v2_b2': [512, 320, 128, 64], 'pvt_v2_b5': [512, 320, 128, 64],
74
+ 'swin_v1_b': [1024, 512, 256, 128], 'swin_v1_l': [1536, 768, 384, 192],
75
+ }
76
+ channels = lateral_channels_in_collection[self.config.bb]
77
+ self.squeeze_module = BasicDecBlk(channels[0], channels[0])
78
+
79
+ self.decoder = Decoder(channels)
80
+
81
+ if 0:
82
+ for key, value in self.named_parameters():
83
+ if 'bb.' in key:
84
+ value.requires_grad = False
85
+
86
+ def forward(self, x):
87
+ if isinstance(x, list):
88
+ x = torch.cat(x, dim=1)
89
+ x = self.stem_layer(x)
90
+ ########## Encoder ##########
91
+ if self.config.bb in ['vgg16', 'vgg16bn', 'resnet50']:
92
+ x1 = self.bb.conv1(x)
93
+ x2 = self.bb.conv2(x1)
94
+ x3 = self.bb.conv3(x2)
95
+ x4 = self.bb.conv4(x3)
96
+ else:
97
+ x1, x2, x3, x4 = self.bb(x)
98
+
99
+ x4 = self.squeeze_module(x4)
100
+
101
+ ########## Decoder ##########
102
+
103
+ features = [x, x1, x2, x3, x4]
104
+ scaled_preds = self.decoder(features)
105
+
106
+ return scaled_preds
107
+
108
+
109
+ class Decoder(nn.Module):
110
+ def __init__(self, channels):
111
+ super(Decoder, self).__init__()
112
+ self.config = Config()
113
+ DecoderBlock = eval('BasicDecBlk')
114
+ LateralBlock = eval('BasicLatBlk')
115
+
116
+ self.decoder_block4 = DecoderBlock(channels[0], channels[1])
117
+ self.decoder_block3 = DecoderBlock(channels[1], channels[2])
118
+ self.decoder_block2 = DecoderBlock(channels[2], channels[3])
119
+ self.decoder_block1 = DecoderBlock(channels[3], channels[3]//2)
120
+
121
+ self.lateral_block4 = LateralBlock(channels[1], channels[1])
122
+ self.lateral_block3 = LateralBlock(channels[2], channels[2])
123
+ self.lateral_block2 = LateralBlock(channels[3], channels[3])
124
+
125
+ if self.config.ms_supervision:
126
+ self.conv_ms_spvn_4 = nn.Conv2d(channels[1], 1, 1, 1, 0)
127
+ self.conv_ms_spvn_3 = nn.Conv2d(channels[2], 1, 1, 1, 0)
128
+ self.conv_ms_spvn_2 = nn.Conv2d(channels[3], 1, 1, 1, 0)
129
+ self.conv_out1 = nn.Sequential(nn.Conv2d(channels[3]//2, 1, 1, 1, 0))
130
+
131
+ def forward(self, features):
132
+ x, x1, x2, x3, x4 = features
133
+ outs = []
134
+ p4 = self.decoder_block4(x4)
135
+ _p4 = F.interpolate(p4, size=x3.shape[2:], mode='bilinear', align_corners=True)
136
+ _p3 = _p4 + self.lateral_block4(x3)
137
+
138
+ p3 = self.decoder_block3(_p3)
139
+ _p3 = F.interpolate(p3, size=x2.shape[2:], mode='bilinear', align_corners=True)
140
+ _p2 = _p3 + self.lateral_block3(x2)
141
+
142
+ p2 = self.decoder_block2(_p2)
143
+ _p2 = F.interpolate(p2, size=x1.shape[2:], mode='bilinear', align_corners=True)
144
+ _p1 = _p2 + self.lateral_block2(x1)
145
+
146
+ _p1 = self.decoder_block1(_p1)
147
+ _p1 = F.interpolate(_p1, size=x.shape[2:], mode='bilinear', align_corners=True)
148
+ p1_out = self.conv_out1(_p1)
149
+
150
+ if self.config.ms_supervision:
151
+ outs.append(self.conv_ms_spvn_4(p4))
152
+ outs.append(self.conv_ms_spvn_3(p3))
153
+ outs.append(self.conv_ms_spvn_2(p2))
154
+ outs.append(p1_out)
155
+ return outs
156
+
157
+
158
+ class RefUNet(nn.Module):
159
+ # Refinement
160
+ def __init__(self, in_channels=3+1):
161
+ super(RefUNet, self).__init__()
162
+ self.encoder_1 = nn.Sequential(
163
+ nn.Conv2d(in_channels, 64, 3, 1, 1),
164
+ nn.Conv2d(64, 64, 3, 1, 1),
165
+ nn.BatchNorm2d(64),
166
+ nn.ReLU(inplace=True)
167
+ )
168
+
169
+ self.encoder_2 = nn.Sequential(
170
+ nn.MaxPool2d(2, 2, ceil_mode=True),
171
+ nn.Conv2d(64, 64, 3, 1, 1),
172
+ nn.BatchNorm2d(64),
173
+ nn.ReLU(inplace=True)
174
+ )
175
+
176
+ self.encoder_3 = nn.Sequential(
177
+ nn.MaxPool2d(2, 2, ceil_mode=True),
178
+ nn.Conv2d(64, 64, 3, 1, 1),
179
+ nn.BatchNorm2d(64),
180
+ nn.ReLU(inplace=True)
181
+ )
182
+
183
+ self.encoder_4 = nn.Sequential(
184
+ nn.MaxPool2d(2, 2, ceil_mode=True),
185
+ nn.Conv2d(64, 64, 3, 1, 1),
186
+ nn.BatchNorm2d(64),
187
+ nn.ReLU(inplace=True)
188
+ )
189
+
190
+ self.pool4 = nn.MaxPool2d(2, 2, ceil_mode=True)
191
+ #####
192
+ self.decoder_5 = nn.Sequential(
193
+ nn.Conv2d(64, 64, 3, 1, 1),
194
+ nn.BatchNorm2d(64),
195
+ nn.ReLU(inplace=True)
196
+ )
197
+ #####
198
+ self.decoder_4 = nn.Sequential(
199
+ nn.Conv2d(128, 64, 3, 1, 1),
200
+ nn.BatchNorm2d(64),
201
+ nn.ReLU(inplace=True)
202
+ )
203
+
204
+ self.decoder_3 = nn.Sequential(
205
+ nn.Conv2d(128, 64, 3, 1, 1),
206
+ nn.BatchNorm2d(64),
207
+ nn.ReLU(inplace=True)
208
+ )
209
+
210
+ self.decoder_2 = nn.Sequential(
211
+ nn.Conv2d(128, 64, 3, 1, 1),
212
+ nn.BatchNorm2d(64),
213
+ nn.ReLU(inplace=True)
214
+ )
215
+
216
+ self.decoder_1 = nn.Sequential(
217
+ nn.Conv2d(128, 64, 3, 1, 1),
218
+ nn.BatchNorm2d(64),
219
+ nn.ReLU(inplace=True)
220
+ )
221
+
222
+ self.conv_d0 = nn.Conv2d(64, 1, 3, 1, 1)
223
+
224
+ self.upscore2 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
225
+
226
+ def forward(self, x):
227
+ outs = []
228
+ if isinstance(x, list):
229
+ x = torch.cat(x, dim=1)
230
+ hx = x
231
+
232
+ hx1 = self.encoder_1(hx)
233
+ hx2 = self.encoder_2(hx1)
234
+ hx3 = self.encoder_3(hx2)
235
+ hx4 = self.encoder_4(hx3)
236
+
237
+ hx = self.decoder_5(self.pool4(hx4))
238
+ hx = torch.cat((self.upscore2(hx), hx4), 1)
239
+
240
+ d4 = self.decoder_4(hx)
241
+ hx = torch.cat((self.upscore2(d4), hx3), 1)
242
+
243
+ d3 = self.decoder_3(hx)
244
+ hx = torch.cat((self.upscore2(d3), hx2), 1)
245
+
246
+ d2 = self.decoder_2(hx)
247
+ hx = torch.cat((self.upscore2(d2), hx1), 1)
248
+
249
+ d1 = self.decoder_1(hx)
250
+
251
+ x = self.conv_d0(d1)
252
+ outs.append(x)
253
+ return outs
BiRefNet_github/models/refinement/stem_layer.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+ from models.modules.utils import build_act_layer, build_norm_layer
3
+
4
+
5
+ class StemLayer(nn.Module):
6
+ r""" Stem layer of InternImage
7
+ Args:
8
+ in_channels (int): number of input channels
9
+ out_channels (int): number of output channels
10
+ act_layer (str): activation layer
11
+ norm_layer (str): normalization layer
12
+ """
13
+
14
+ def __init__(self,
15
+ in_channels=3+1,
16
+ inter_channels=48,
17
+ out_channels=96,
18
+ act_layer='GELU',
19
+ norm_layer='BN'):
20
+ super().__init__()
21
+ self.conv1 = nn.Conv2d(in_channels,
22
+ inter_channels,
23
+ kernel_size=3,
24
+ stride=1,
25
+ padding=1)
26
+ self.norm1 = build_norm_layer(
27
+ inter_channels, norm_layer, 'channels_first', 'channels_first'
28
+ )
29
+ self.act = build_act_layer(act_layer)
30
+ self.conv2 = nn.Conv2d(inter_channels,
31
+ out_channels,
32
+ kernel_size=3,
33
+ stride=1,
34
+ padding=1)
35
+ self.norm2 = build_norm_layer(
36
+ out_channels, norm_layer, 'channels_first', 'channels_first'
37
+ )
38
+
39
+ def forward(self, x):
40
+ x = self.conv1(x)
41
+ x = self.norm1(x)
42
+ x = self.act(x)
43
+ x = self.conv2(x)
44
+ x = self.norm2(x)
45
+ return x
BiRefNet_github/preproc.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image, ImageEnhance
2
+ import random
3
+ import numpy as np
4
+ import random
5
+
6
+
7
+ def preproc(image, label, preproc_methods=['flip']):
8
+ if 'flip' in preproc_methods:
9
+ image, label = cv_random_flip(image, label)
10
+ if 'crop' in preproc_methods:
11
+ image, label = random_crop(image, label)
12
+ if 'rotate' in preproc_methods:
13
+ image, label = random_rotate(image, label)
14
+ if 'enhance' in preproc_methods:
15
+ image = color_enhance(image)
16
+ if 'pepper' in preproc_methods:
17
+ label = random_pepper(label)
18
+ return image, label
19
+
20
+
21
+ def cv_random_flip(img, label):
22
+ if random.random() > 0.5:
23
+ img = img.transpose(Image.FLIP_LEFT_RIGHT)
24
+ label = label.transpose(Image.FLIP_LEFT_RIGHT)
25
+ return img, label
26
+
27
+
28
+ def random_crop(image, label):
29
+ border = 30
30
+ image_width = image.size[0]
31
+ image_height = image.size[1]
32
+ border = int(min(image_width, image_height) * 0.1)
33
+ crop_win_width = np.random.randint(image_width - border, image_width)
34
+ crop_win_height = np.random.randint(image_height - border, image_height)
35
+ random_region = (
36
+ (image_width - crop_win_width) >> 1, (image_height - crop_win_height) >> 1, (image_width + crop_win_width) >> 1,
37
+ (image_height + crop_win_height) >> 1)
38
+ return image.crop(random_region), label.crop(random_region)
39
+
40
+
41
+ def random_rotate(image, label, angle=15):
42
+ mode = Image.BICUBIC
43
+ if random.random() > 0.8:
44
+ random_angle = np.random.randint(-angle, angle)
45
+ image = image.rotate(random_angle, mode)
46
+ label = label.rotate(random_angle, mode)
47
+ return image, label
48
+
49
+
50
+ def color_enhance(image):
51
+ bright_intensity = random.randint(5, 15) / 10.0
52
+ image = ImageEnhance.Brightness(image).enhance(bright_intensity)
53
+ contrast_intensity = random.randint(5, 15) / 10.0
54
+ image = ImageEnhance.Contrast(image).enhance(contrast_intensity)
55
+ color_intensity = random.randint(0, 20) / 10.0
56
+ image = ImageEnhance.Color(image).enhance(color_intensity)
57
+ sharp_intensity = random.randint(0, 30) / 10.0
58
+ image = ImageEnhance.Sharpness(image).enhance(sharp_intensity)
59
+ return image
60
+
61
+
62
+ def random_gaussian(image, mean=0.1, sigma=0.35):
63
+ def gaussianNoisy(im, mean=mean, sigma=sigma):
64
+ for _i in range(len(im)):
65
+ im[_i] += random.gauss(mean, sigma)
66
+ return im
67
+
68
+ img = np.asarray(image)
69
+ width, height = img.shape
70
+ img = gaussianNoisy(img[:].flatten(), mean, sigma)
71
+ img = img.reshape([width, height])
72
+ return Image.fromarray(np.uint8(img))
73
+
74
+
75
+ def random_pepper(img, N=0.0015):
76
+ img = np.array(img)
77
+ noiseNum = int(N * img.shape[0] * img.shape[1])
78
+ for i in range(noiseNum):
79
+ randX = random.randint(0, img.shape[0] - 1)
80
+ randY = random.randint(0, img.shape[1] - 1)
81
+ if random.randint(0, 1) == 0:
82
+ img[randX, randY] = 0
83
+ else:
84
+ img[randX, randY] = 255
85
+ return Image.fromarray(img)
BiRefNet_github/requirements.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ --extra-index-url https://download.pytorch.org/whl/cu118
2
+ torch==2.0.1
3
+ --extra-index-url https://download.pytorch.org/whl/cu118
4
+ torchvision==0.15.2
5
+ numpy<2
6
+ opencv-python
7
+ timm
8
+ scipy
9
+ scikit-image
10
+ kornia
11
+
12
+ tqdm
13
+ prettytable
14
+
15
+ huggingface_hub
BiRefNet_github/rm_cache.sh ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ rm -rf __pycache__ */__pycache__
3
+
4
+ # Val
5
+ rm -r tmp*
6
+
7
+ # Train
8
+ rm slurm*
9
+ rm -r ckpt
10
+ rm nohup.out*
11
+
12
+ # Eval
13
+ rm -r evaluation/eval-*
14
+ rm -r tmp*
15
+ rm -r e_logs/
16
+
17
+ # System
18
+ rm core-*-python-*
19
+
20
+ clear
BiRefNet_github/sub.sh ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/sh
2
+ # Example: ./sub.sh tmp_proj 0,1,2,3 3 --> Use 0,1,2,3 for training, release GPUs, use GPU:3 for inference.
3
+
4
+ module load compilers/cuda/11.8
5
+
6
+ export PYTHONUNBUFFERED=1
7
+ export LD_PRELOAD=/home/bingxing2/apps/compilers/gcc/12.2.0/lib64/libstdc++.so.6
8
+ export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:${HOME}/miniconda3/lib:/home/bingxing2/apps/cudnn/8.4.0.27_cuda11.x/lib
9
+
10
+ method=${1:-"BSL"}
11
+ devices=${2:-0}
12
+
13
+ sbatch --nodes=1 -p vip_gpu_ailab -A ai4bio \
14
+ --ntasks-per-node=1 \
15
+ --gres=gpu:$(($(echo ${devices%%,} | grep -o "," | wc -l)+1)) \
16
+ --cpus-per-task=32 \
17
+ ./train_test.sh ${method} ${devices}
18
+
19
+ hostname
BiRefNet_github/test.sh ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ devices=${1:-0}
2
+ pred_root=${2:-e_preds}
3
+
4
+ # Inference
5
+
6
+ CUDA_VISIBLE_DEVICES=${devices} python inference.py --pred_root ${pred_root}
7
+
8
+ echo Inference finished at $(date)
9
+
10
+ # Evaluation
11
+ log_dir=e_logs && mkdir ${log_dir}
12
+
13
+ task=$(python3 config.py)
14
+ case "${task}" in
15
+ "DIS5K") testsets='DIS-VD,DIS-TE1,DIS-TE2,DIS-TE3,DIS-TE4' ;;
16
+ "COD") testsets='CHAMELEON,NC4K,TE-CAMO,TE-COD10K' ;;
17
+ "HRSOD") testsets='DAVIS-S,TE-HRSOD,TE-UHRSD,DUT-OMRON,TE-DUTS' ;;
18
+ "DIS5K+HRSOD+HRS10K") testsets='DIS-VD' ;;
19
+ "P3M-10k") testsets='TE-P3M-500-P,TE-P3M-500-NP' ;;
20
+ esac
21
+ testsets=(`echo ${testsets} | tr ',' ' '`) && testsets=${testsets[@]}
22
+
23
+ for testset in ${testsets}; do
24
+ nohup python eval_existingOnes.py --pred_root ${pred_root} --data_lst ${testset} > ${log_dir}/eval_${testset}.out 2>&1 &
25
+ done
26
+
27
+
28
+ echo Evaluation started at $(date)
BiRefNet_github/train.py ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import datetime
3
+ import argparse
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.optim as optim
7
+ from torch.autograd import Variable
8
+
9
+ from config import Config
10
+ from loss import PixLoss, ClsLoss
11
+ from dataset import MyData
12
+ from models.birefnet import BiRefNet
13
+ from utils import Logger, AverageMeter, set_seed, check_state_dict
14
+ from evaluation.valid import valid
15
+
16
+ from torch.utils.data.distributed import DistributedSampler
17
+ from torch.nn.parallel import DistributedDataParallel as DDP
18
+ from torch.distributed import init_process_group, destroy_process_group, get_rank
19
+ from torch.cuda import amp
20
+
21
+
22
+ parser = argparse.ArgumentParser(description='')
23
+ parser.add_argument('--resume', default=None, type=str, help='path to latest checkpoint')
24
+ parser.add_argument('--epochs', default=120, type=int)
25
+ parser.add_argument('--trainset', default='DIS5K', type=str, help="Options: 'DIS5K'")
26
+ parser.add_argument('--ckpt_dir', default=None, help='Temporary folder')
27
+ parser.add_argument('--testsets', default='DIS-VD+DIS-TE1+DIS-TE2+DIS-TE3+DIS-TE4', type=str)
28
+ parser.add_argument('--dist', default=False, type=lambda x: x == 'True')
29
+ args = parser.parse_args()
30
+
31
+
32
+ config = Config()
33
+ if config.rand_seed:
34
+ set_seed(config.rand_seed)
35
+
36
+ if config.use_fp16:
37
+ # Half Precision
38
+ scaler = amp.GradScaler(enabled=config.use_fp16)
39
+
40
+ # DDP
41
+ to_be_distributed = args.dist
42
+ if to_be_distributed:
43
+ init_process_group(backend="nccl", timeout=datetime.timedelta(seconds=3600*10))
44
+ device = int(os.environ["LOCAL_RANK"])
45
+ else:
46
+ device = config.device
47
+
48
+ epoch_st = 1
49
+ # make dir for ckpt
50
+ os.makedirs(args.ckpt_dir, exist_ok=True)
51
+
52
+ # Init log file
53
+ logger = Logger(os.path.join(args.ckpt_dir, "log.txt"))
54
+ logger_loss_idx = 1
55
+
56
+ # log model and optimizer params
57
+ # logger.info("Model details:"); logger.info(model)
58
+ logger.info("datasets: load_all={}, compile={}.".format(config.load_all, config.compile))
59
+ logger.info("Other hyperparameters:"); logger.info(args)
60
+ print('batch size:', config.batch_size)
61
+
62
+
63
+ if os.path.exists(os.path.join(config.data_root_dir, config.task, args.testsets.strip('+').split('+')[0])):
64
+ args.testsets = args.testsets.strip('+').split('+')
65
+ else:
66
+ args.testsets = []
67
+
68
+ # Init model
69
+ def prepare_dataloader(dataset: torch.utils.data.Dataset, batch_size: int, to_be_distributed=False, is_train=True):
70
+ if to_be_distributed:
71
+ return torch.utils.data.DataLoader(
72
+ dataset=dataset, batch_size=batch_size, num_workers=min(config.num_workers, batch_size), pin_memory=True,
73
+ shuffle=False, sampler=DistributedSampler(dataset), drop_last=True
74
+ )
75
+ else:
76
+ return torch.utils.data.DataLoader(
77
+ dataset=dataset, batch_size=batch_size, num_workers=min(config.num_workers, batch_size, 0), pin_memory=True,
78
+ shuffle=is_train, drop_last=True
79
+ )
80
+
81
+
82
+ def init_data_loaders(to_be_distributed):
83
+ # Prepare dataset
84
+ train_loader = prepare_dataloader(
85
+ MyData(datasets=config.training_set, image_size=config.size, is_train=True),
86
+ config.batch_size, to_be_distributed=to_be_distributed, is_train=True
87
+ )
88
+ print(len(train_loader), "batches of train dataloader {} have been created.".format(config.training_set))
89
+ test_loaders = {}
90
+ for testset in args.testsets:
91
+ _data_loader_test = prepare_dataloader(
92
+ MyData(datasets=testset, image_size=config.size, is_train=False),
93
+ config.batch_size_valid, is_train=False
94
+ )
95
+ print(len(_data_loader_test), "batches of valid dataloader {} have been created.".format(testset))
96
+ test_loaders[testset] = _data_loader_test
97
+ return train_loader, test_loaders
98
+
99
+
100
+ def init_models_optimizers(epochs, to_be_distributed):
101
+ model = BiRefNet(bb_pretrained=True)
102
+ if args.resume:
103
+ if os.path.isfile(args.resume):
104
+ logger.info("=> loading checkpoint '{}'".format(args.resume))
105
+ state_dict = torch.load(args.resume, map_location='cpu')
106
+ state_dict = check_state_dict(state_dict)
107
+ model.load_state_dict(state_dict)
108
+ global epoch_st
109
+ epoch_st = int(args.resume.rstrip('.pth').split('epoch_')[-1]) + 1
110
+ else:
111
+ logger.info("=> no checkpoint found at '{}'".format(args.resume))
112
+ if to_be_distributed:
113
+ model = model.to(device)
114
+ model = DDP(model, device_ids=[device])
115
+ else:
116
+ model = model.to(device)
117
+ if config.compile:
118
+ model = torch.compile(model, mode=['default', 'reduce-overhead', 'max-autotune'][0])
119
+ if config.precisionHigh:
120
+ torch.set_float32_matmul_precision('high')
121
+
122
+
123
+ # Setting optimizer
124
+ if config.optimizer == 'AdamW':
125
+ optimizer = optim.AdamW(params=model.parameters(), lr=config.lr, weight_decay=1e-2)
126
+ elif config.optimizer == 'Adam':
127
+ optimizer = optim.Adam(params=model.parameters(), lr=config.lr, weight_decay=0)
128
+ lr_scheduler = torch.optim.lr_scheduler.MultiStepLR(
129
+ optimizer,
130
+ milestones=[lde if lde > 0 else epochs + lde + 1 for lde in config.lr_decay_epochs],
131
+ gamma=config.lr_decay_rate
132
+ )
133
+ logger.info("Optimizer details:"); logger.info(optimizer)
134
+ logger.info("Scheduler details:"); logger.info(lr_scheduler)
135
+
136
+ return model, optimizer, lr_scheduler
137
+
138
+
139
+ class Trainer:
140
+ def __init__(
141
+ self, data_loaders, model_opt_lrsch,
142
+ ):
143
+ self.model, self.optimizer, self.lr_scheduler = model_opt_lrsch
144
+ self.train_loader, self.test_loaders = data_loaders
145
+ if config.out_ref:
146
+ self.criterion_gdt = nn.BCELoss() if not config.use_fp16 else nn.BCEWithLogitsLoss()
147
+
148
+ # Setting Losses
149
+ self.pix_loss = PixLoss()
150
+ self.cls_loss = ClsLoss()
151
+
152
+ # Others
153
+ self.loss_log = AverageMeter()
154
+ if config.lambda_adv_g:
155
+ self.optimizer_d, self.lr_scheduler_d, self.disc, self.adv_criterion = self._load_adv_components()
156
+ self.disc_update_for_odd = 0
157
+
158
+ def _load_adv_components(self):
159
+ # AIL
160
+ from loss import Discriminator
161
+ disc = Discriminator(channels=3, img_size=config.size)
162
+ if to_be_distributed:
163
+ disc = disc.to(device)
164
+ disc = DDP(disc, device_ids=[device], broadcast_buffers=False)
165
+ else:
166
+ disc = disc.to(device)
167
+ if config.compile:
168
+ disc = torch.compile(disc, mode=['default', 'reduce-overhead', 'max-autotune'][0])
169
+ adv_criterion = nn.BCELoss() if not config.use_fp16 else nn.BCEWithLogitsLoss()
170
+ if config.optimizer == 'AdamW':
171
+ optimizer_d = optim.AdamW(params=disc.parameters(), lr=config.lr, weight_decay=1e-2)
172
+ elif config.optimizer == 'Adam':
173
+ optimizer_d = optim.Adam(params=disc.parameters(), lr=config.lr, weight_decay=0)
174
+ lr_scheduler_d = torch.optim.lr_scheduler.MultiStepLR(
175
+ optimizer_d,
176
+ milestones=[lde if lde > 0 else args.epochs + lde + 1 for lde in config.lr_decay_epochs],
177
+ gamma=config.lr_decay_rate
178
+ )
179
+ return optimizer_d, lr_scheduler_d, disc, adv_criterion
180
+
181
+ def _train_batch(self, batch):
182
+ inputs = batch[0].to(device)
183
+ gts = batch[1].to(device)
184
+ class_labels = batch[2].to(device)
185
+ if config.use_fp16:
186
+ with amp.autocast(enabled=config.use_fp16):
187
+ scaled_preds, class_preds_lst = self.model(inputs)
188
+ if config.out_ref:
189
+ (outs_gdt_pred, outs_gdt_label), scaled_preds = scaled_preds
190
+ for _idx, (_gdt_pred, _gdt_label) in enumerate(zip(outs_gdt_pred, outs_gdt_label)):
191
+ _gdt_pred = nn.functional.interpolate(_gdt_pred, size=_gdt_label.shape[2:], mode='bilinear', align_corners=True)#.sigmoid()
192
+ # _gdt_label = _gdt_label.sigmoid()
193
+ loss_gdt = self.criterion_gdt(_gdt_pred, _gdt_label) if _idx == 0 else self.criterion_gdt(_gdt_pred, _gdt_label) + loss_gdt
194
+ # self.loss_dict['loss_gdt'] = loss_gdt.item()
195
+ if None in class_preds_lst:
196
+ loss_cls = 0.
197
+ else:
198
+ loss_cls = self.cls_loss(class_preds_lst, class_labels) * 1.0
199
+ self.loss_dict['loss_cls'] = loss_cls.item()
200
+
201
+ # Loss
202
+ loss_pix = self.pix_loss(scaled_preds, torch.clamp(gts, 0, 1)) * 1.0
203
+ self.loss_dict['loss_pix'] = loss_pix.item()
204
+ # since there may be several losses for sal, the lambdas for them (lambdas_pix) are inside the loss.py
205
+ loss = loss_pix + loss_cls
206
+ if config.out_ref:
207
+ loss = loss + loss_gdt * 1.0
208
+
209
+ if config.lambda_adv_g:
210
+ # gen
211
+ valid = Variable(torch.cuda.FloatTensor(scaled_preds[-1].shape[0], 1).fill_(1.0), requires_grad=False).to(device)
212
+ adv_loss_g = self.adv_criterion(self.disc(scaled_preds[-1] * inputs), valid) * config.lambda_adv_g
213
+ loss += adv_loss_g
214
+ self.loss_dict['loss_adv'] = adv_loss_g.item()
215
+ self.disc_update_for_odd += 1
216
+ # self.loss_log.update(loss.item(), inputs.size(0))
217
+ # self.optimizer.zero_grad()
218
+ # loss.backward()
219
+ # self.optimizer.step()
220
+ self.optimizer.zero_grad()
221
+ scaler.scale(loss).backward()
222
+ scaler.step(self.optimizer)
223
+ scaler.update()
224
+
225
+ if config.lambda_adv_g and self.disc_update_for_odd % 2 == 0:
226
+ # disc
227
+ fake = Variable(torch.cuda.FloatTensor(scaled_preds[-1].shape[0], 1).fill_(0.0), requires_grad=False).to(device)
228
+ adv_loss_real = self.adv_criterion(self.disc(gts * inputs), valid)
229
+ adv_loss_fake = self.adv_criterion(self.disc(scaled_preds[-1].detach() * inputs.detach()), fake)
230
+ adv_loss_d = (adv_loss_real + adv_loss_fake) / 2 * config.lambda_adv_d
231
+ self.loss_dict['loss_adv_d'] = adv_loss_d.item()
232
+ # self.optimizer_d.zero_grad()
233
+ # adv_loss_d.backward()
234
+ # self.optimizer_d.step()
235
+ self.optimizer_d.zero_grad()
236
+ scaler.scale(adv_loss_d).backward()
237
+ scaler.step(self.optimizer_d)
238
+ scaler.update()
239
+ else:
240
+ scaled_preds, class_preds_lst = self.model(inputs)
241
+ if config.out_ref:
242
+ (outs_gdt_pred, outs_gdt_label), scaled_preds = scaled_preds
243
+ for _idx, (_gdt_pred, _gdt_label) in enumerate(zip(outs_gdt_pred, outs_gdt_label)):
244
+ _gdt_pred = nn.functional.interpolate(_gdt_pred, size=_gdt_label.shape[2:], mode='bilinear', align_corners=True).sigmoid()
245
+ _gdt_label = _gdt_label.sigmoid()
246
+ loss_gdt = self.criterion_gdt(_gdt_pred, _gdt_label) if _idx == 0 else self.criterion_gdt(_gdt_pred, _gdt_label) + loss_gdt
247
+ # self.loss_dict['loss_gdt'] = loss_gdt.item()
248
+ if None in class_preds_lst:
249
+ loss_cls = 0.
250
+ else:
251
+ loss_cls = self.cls_loss(class_preds_lst, class_labels) * 1.0
252
+ self.loss_dict['loss_cls'] = loss_cls.item()
253
+
254
+ # Loss
255
+ loss_pix = self.pix_loss(scaled_preds, torch.clamp(gts, 0, 1)) * 1.0
256
+ self.loss_dict['loss_pix'] = loss_pix.item()
257
+ # since there may be several losses for sal, the lambdas for them (lambdas_pix) are inside the loss.py
258
+ loss = loss_pix + loss_cls
259
+ if config.out_ref:
260
+ loss = loss + loss_gdt * 1.0
261
+
262
+ if config.lambda_adv_g:
263
+ # gen
264
+ valid = Variable(torch.cuda.FloatTensor(scaled_preds[-1].shape[0], 1).fill_(1.0), requires_grad=False).to(device)
265
+ adv_loss_g = self.adv_criterion(self.disc(scaled_preds[-1] * inputs), valid) * config.lambda_adv_g
266
+ loss += adv_loss_g
267
+ self.loss_dict['loss_adv'] = adv_loss_g.item()
268
+ self.disc_update_for_odd += 1
269
+ self.loss_log.update(loss.item(), inputs.size(0))
270
+ self.optimizer.zero_grad()
271
+ loss.backward()
272
+ self.optimizer.step()
273
+
274
+ if config.lambda_adv_g and self.disc_update_for_odd % 2 == 0:
275
+ # disc
276
+ fake = Variable(torch.cuda.FloatTensor(scaled_preds[-1].shape[0], 1).fill_(0.0), requires_grad=False).to(device)
277
+ adv_loss_real = self.adv_criterion(self.disc(gts * inputs), valid)
278
+ adv_loss_fake = self.adv_criterion(self.disc(scaled_preds[-1].detach() * inputs.detach()), fake)
279
+ adv_loss_d = (adv_loss_real + adv_loss_fake) / 2 * config.lambda_adv_d
280
+ self.loss_dict['loss_adv_d'] = adv_loss_d.item()
281
+ self.optimizer_d.zero_grad()
282
+ adv_loss_d.backward()
283
+ self.optimizer_d.step()
284
+
285
+ def train_epoch(self, epoch):
286
+ global logger_loss_idx
287
+ self.model.train()
288
+ self.loss_dict = {}
289
+ if epoch > args.epochs + config.IoU_finetune_last_epochs:
290
+ self.pix_loss.lambdas_pix_last['bce'] *= 0
291
+ self.pix_loss.lambdas_pix_last['ssim'] *= 1
292
+ self.pix_loss.lambdas_pix_last['iou'] *= 0.5
293
+
294
+ for batch_idx, batch in enumerate(self.train_loader):
295
+ self._train_batch(batch)
296
+ # Logger
297
+ if batch_idx % 20 == 0:
298
+ info_progress = 'Epoch[{0}/{1}] Iter[{2}/{3}].'.format(epoch, args.epochs, batch_idx, len(self.train_loader))
299
+ info_loss = 'Training Losses'
300
+ for loss_name, loss_value in self.loss_dict.items():
301
+ info_loss += ', {}: {:.3f}'.format(loss_name, loss_value)
302
+ logger.info(' '.join((info_progress, info_loss)))
303
+ info_loss = '@==Final== Epoch[{0}/{1}] Training Loss: {loss.avg:.3f} '.format(epoch, args.epochs, loss=self.loss_log)
304
+ logger.info(info_loss)
305
+
306
+ self.lr_scheduler.step()
307
+ if config.lambda_adv_g:
308
+ self.lr_scheduler_d.step()
309
+ return self.loss_log.avg
310
+
311
+ def validate_model(self, epoch):
312
+ num_image_testset_all = {'DIS-VD': 470, 'DIS-TE1': 500, 'DIS-TE2': 500, 'DIS-TE3': 500, 'DIS-TE4': 500}
313
+ num_image_testset = {}
314
+ for testset in args.testsets:
315
+ if 'DIS-TE' in testset:
316
+ num_image_testset[testset] = num_image_testset_all[testset]
317
+ weighted_scores = {'f_max': 0, 'f_mean': 0, 'f_wfm': 0, 'sm': 0, 'e_max': 0, 'e_mean': 0, 'mae': 0}
318
+ len_all_data_loaders = 0
319
+ self.model.epoch = epoch
320
+ for testset, data_loader_test in self.test_loaders.items():
321
+ print('Validating {}...'.format(testset))
322
+ performance_dict = valid(
323
+ self.model,
324
+ data_loader_test,
325
+ pred_dir='.',
326
+ method=args.ckpt_dir.split('/')[-1] if args.ckpt_dir.split('/')[-1].strip('.').strip('/') else 'tmp_val',
327
+ testset=testset,
328
+ only_S_MAE=config.only_S_MAE,
329
+ device=device
330
+ )
331
+ print('Test set: {}:'.format(testset))
332
+ if config.only_S_MAE:
333
+ print('Smeasure: {:.4f}, MAE: {:.4f}'.format(
334
+ performance_dict['sm'], performance_dict['mae']
335
+ ))
336
+ else:
337
+ print('Fmax: {:.4f}, Fwfm: {:.4f}, Smeasure: {:.4f}, Emean: {:.4f}, MAE: {:.4f}'.format(
338
+ performance_dict['f_max'], performance_dict['f_wfm'], performance_dict['sm'], performance_dict['e_mean'], performance_dict['mae']
339
+ ))
340
+ if '-TE' in testset:
341
+ for metric in ['sm', 'mae'] if config.only_S_MAE else ['f_max', 'f_mean', 'f_wfm', 'sm', 'e_max', 'e_mean', 'mae']:
342
+ weighted_scores[metric] += performance_dict[metric] * len(data_loader_test)
343
+ len_all_data_loaders += len(data_loader_test)
344
+ print('Weighted Scores:')
345
+ for metric, score in weighted_scores.items():
346
+ if score:
347
+ print('\t{}: {:.4f}.'.format(metric, score / len_all_data_loaders))
348
+
349
+
350
+ def main():
351
+
352
+ trainer = Trainer(
353
+ data_loaders=init_data_loaders(to_be_distributed),
354
+ model_opt_lrsch=init_models_optimizers(args.epochs, to_be_distributed)
355
+ )
356
+
357
+ for epoch in range(epoch_st, args.epochs+1):
358
+ train_loss = trainer.train_epoch(epoch)
359
+ # Save checkpoint
360
+ # DDP
361
+ if epoch >= args.epochs - config.save_last and epoch % config.save_step == 0:
362
+ torch.save(
363
+ trainer.model.module.state_dict() if to_be_distributed else trainer.model.state_dict(),
364
+ os.path.join(args.ckpt_dir, 'epoch_{}.pth'.format(epoch))
365
+ )
366
+ if config.val_step and epoch >= args.epochs - config.save_last and (args.epochs - epoch) % config.val_step == 0:
367
+ if to_be_distributed:
368
+ if get_rank() == 0:
369
+ print('Validating at rank-{}...'.format(get_rank()))
370
+ trainer.validate_model(epoch)
371
+ else:
372
+ trainer.validate_model(epoch)
373
+ if to_be_distributed:
374
+ destroy_process_group()
375
+
376
+ if __name__ == '__main__':
377
+ main()
BiRefNet_github/train.sh ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Run script
3
+ # Settings of training & test for different tasks.
4
+ method="$1"
5
+ task=$(python3 config.py)
6
+ case "${task}" in
7
+ "DIS5K") epochs=600 && val_last=100 && step=5 ;;
8
+ "COD") epochs=150 && val_last=50 && step=5 ;;
9
+ "HRSOD") epochs=150 && val_last=50 && step=5 ;;
10
+ "DIS5K+HRSOD+HRS10K") epochs=250 && val_last=50 && step=5 ;;
11
+ "P3M-10k") epochs=150 && val_last=50 && step=5 ;;
12
+ esac
13
+ testsets=NO # Non-existing folder to skip.
14
+ # testsets=TE-COD10K # for COD
15
+
16
+ # Train
17
+ devices=$2
18
+ nproc_per_node=$(echo ${devices%%,} | grep -o "," | wc -l)
19
+
20
+ to_be_distributed=`echo ${nproc_per_node} | awk '{if($e > 0) print "True"; else print "False";}'`
21
+
22
+ echo Training started at $(date)
23
+ if [ ${to_be_distributed} == "True" ]
24
+ then
25
+ # Adapt the nproc_per_node by the number of GPUs. Give 8989 as the default value of master_port.
26
+ echo "Multi-GPU mode received..."
27
+ CUDA_VISIBLE_DEVICES=${devices} \
28
+ torchrun --nproc_per_node $((nproc_per_node+1)) --master_port=${3:-8989} \
29
+ train.py --ckpt_dir ckpt/${method} --epochs ${epochs} \
30
+ --testsets ${testsets} \
31
+ --dist ${to_be_distributed}
32
+ else
33
+ echo "Single-GPU mode received..."
34
+ CUDA_VISIBLE_DEVICES=${devices} \
35
+ python train.py --ckpt_dir ckpt/${method} --epochs ${epochs} \
36
+ --testsets ${testsets} \
37
+ --dist ${to_be_distributed} \
38
+ --resume ckpt/xx/ep100.pth
39
+ fi
40
+
41
+ echo Training finished at $(date)
BiRefNet_github/train_test.sh ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/sh
2
+
3
+ method=${1:-"BSL"}
4
+ devices=${2:-"0,1,2,3,4,5,6,7"}
5
+
6
+ bash train.sh ${method} ${devices}
7
+
8
+ devices_test=${3:-0}
9
+ bash test.sh ${devices_test}
10
+
11
+ hostname
BiRefNet_github/utils.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ import torch
4
+ from torchvision import transforms
5
+ import numpy as np
6
+ import random
7
+ import cv2
8
+ from PIL import Image
9
+
10
+
11
+ def path_to_image(path, size=(1024, 1024), color_type=['rgb', 'gray'][0]):
12
+ if color_type.lower() == 'rgb':
13
+ image = cv2.imread(path)
14
+ elif color_type.lower() == 'gray':
15
+ image = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
16
+ else:
17
+ print('Select the color_type to return, either to RGB or gray image.')
18
+ return
19
+ if size:
20
+ image = cv2.resize(image, size, interpolation=cv2.INTER_LINEAR)
21
+ if color_type.lower() == 'rgb':
22
+ image = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)).convert('RGB')
23
+ else:
24
+ image = Image.fromarray(image).convert('L')
25
+ return image
26
+
27
+
28
+
29
+ def check_state_dict(state_dict, unwanted_prefix='_orig_mod.'):
30
+ for k, v in list(state_dict.items()):
31
+ if k.startswith(unwanted_prefix):
32
+ state_dict[k[len(unwanted_prefix):]] = state_dict.pop(k)
33
+ return state_dict
34
+
35
+
36
+ def generate_smoothed_gt(gts):
37
+ epsilon = 0.001
38
+ new_gts = (1-epsilon)*gts+epsilon/2
39
+ return new_gts
40
+
41
+
42
+ class Logger():
43
+ def __init__(self, path="log.txt"):
44
+ self.logger = logging.getLogger('BiRefNet')
45
+ self.file_handler = logging.FileHandler(path, "w")
46
+ self.stdout_handler = logging.StreamHandler()
47
+ self.stdout_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
48
+ self.file_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
49
+ self.logger.addHandler(self.file_handler)
50
+ self.logger.addHandler(self.stdout_handler)
51
+ self.logger.setLevel(logging.INFO)
52
+ self.logger.propagate = False
53
+
54
+ def info(self, txt):
55
+ self.logger.info(txt)
56
+
57
+ def close(self):
58
+ self.file_handler.close()
59
+ self.stdout_handler.close()
60
+
61
+
62
+ class AverageMeter(object):
63
+ """Computes and stores the average and current value"""
64
+ def __init__(self):
65
+ self.reset()
66
+
67
+ def reset(self):
68
+ self.val = 0.0
69
+ self.avg = 0.0
70
+ self.sum = 0.0
71
+ self.count = 0.0
72
+
73
+ def update(self, val, n=1):
74
+ self.val = val
75
+ self.sum += val * n
76
+ self.count += n
77
+ self.avg = self.sum / self.count
78
+
79
+
80
+ def save_checkpoint(state, path, filename="latest.pth"):
81
+ torch.save(state, os.path.join(path, filename))
82
+
83
+
84
+ def save_tensor_img(tenor_im, path):
85
+ im = tenor_im.cpu().clone()
86
+ im = im.squeeze(0)
87
+ tensor2pil = transforms.ToPILImage()
88
+ im = tensor2pil(im)
89
+ im.save(path)
90
+
91
+
92
+ def set_seed(seed):
93
+ torch.manual_seed(seed)
94
+ torch.cuda.manual_seed_all(seed)
95
+ np.random.seed(seed)
96
+ random.seed(seed)
97
+ torch.backends.cudnn.deterministic = True
BiRefNet_github/waiting4eval.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # Make evaluation along with training. Swith time with space/computation.
3
+ # Licensed under The MIT License [see LICENSE for details]
4
+ # Written by Peng Zheng
5
+ # --------------------------------------------------------
6
+ import os
7
+ from glob import glob
8
+ from time import sleep
9
+ import argparse
10
+ import torch
11
+
12
+ from config import Config
13
+ from models.birefnet import BiRefNet
14
+ from dataset import MyData
15
+ from evaluation.valid import valid
16
+
17
+
18
+ parser = argparse.ArgumentParser(description='')
19
+ parser.add_argument('--cuda_idx', default=-1, type=int)
20
+ parser.add_argument('--val_step', default=5*1, type=int)
21
+ parser.add_argument('--program_id', default=0, type=int)
22
+ # id-th one of this program will evaluate val_step * N + program_id -th epoch model.
23
+ # Test more models, number of programs == number of GPUs: [models[num_all - program_id_1], models[num_all - program_id_max(n, val_step-1)], ...] programs with id>val_step will speed up the evaluation on (val_step - id)%val_step -th epoch models.
24
+ # Test fastest, only sequentially searched val_step*N -th models -- set all program_id as the same.
25
+ parser.add_argument('--testsets', default='DIS-VD+DIS-TE1+DIS-TE2+DIS-TE3+DIS-TE4', type=str)
26
+ args_eval = parser.parse_args()
27
+
28
+ args_eval.program_id = (args_eval.val_step - args_eval.program_id) % args_eval.val_step
29
+
30
+ config = Config()
31
+ config.only_S_MAE = True
32
+ device = 'cpu' if args_eval.cuda_idx < 0 else 'cuda:{}'.format(args_eval.cuda_idx)
33
+ ckpt_dir, testsets = glob(os.path.join('ckpt', '*'))[0], args_eval.testsets
34
+
35
+
36
+ def validate_model(model, test_loaders, epoch):
37
+ num_image_testset_all = {'DIS-VD': 470, 'DIS-TE1': 500, 'DIS-TE2': 500, 'DIS-TE3': 500, 'DIS-TE4': 500}
38
+ num_image_testset = {}
39
+ for testset in testsets.split('+'):
40
+ if 'DIS-TE' in testset:
41
+ num_image_testset[testset] = num_image_testset_all[testset]
42
+ weighted_scores = {'f_max': 0, 'sm': 0, 'e_max': 0, 'mae': 0}
43
+ len_all_data_loaders = 0
44
+ model.epoch = epoch
45
+ for testset, data_loader_test in test_loaders.items():
46
+ print('Validating {}...'.format(testset))
47
+ performance_dict = valid(
48
+ model,
49
+ data_loader_test,
50
+ pred_dir='.',
51
+ method=ckpt_dir.split('/')[-1] if ckpt_dir.split('/')[-1].strip('.').strip('/') else 'tmp_val',
52
+ testset=testset,
53
+ only_S_MAE=config.only_S_MAE,
54
+ device=device
55
+ )
56
+ print('Test set: {}:'.format(testset))
57
+ if config.only_S_MAE:
58
+ print('Smeasure: {:.4f}, MAE: {:.4f}'.format(
59
+ performance_dict['sm'], performance_dict['mae']
60
+ ))
61
+ else:
62
+ print('Fmax: {:.4f}, Fwfm: {:.4f}, Smeasure: {:.4f}, Emean: {:.4f}, MAE: {:.4f}'.format(
63
+ performance_dict['f_max'], performance_dict['f_wfm'], performance_dict['sm'], performance_dict['e_mean'], performance_dict['mae']
64
+ ))
65
+ if '-TE' in testset:
66
+ for metric in ['sm', 'mae'] if config.only_S_MAE else ['f_max', 'f_wfm', 'sm', 'e_mean', 'mae']:
67
+ weighted_scores[metric] += performance_dict[metric] * len(data_loader_test)
68
+ len_all_data_loaders += len(data_loader_test)
69
+ print('Weighted Scores:')
70
+ for metric, score in weighted_scores.items():
71
+ if score:
72
+ print('\t{}: {:.4f}.'.format(metric, score / len_all_data_loaders))
73
+
74
+ @torch.no_grad()
75
+ def main():
76
+ config = Config()
77
+ # Dataloader
78
+ test_loaders = {}
79
+ for testset in testsets.split('+'):
80
+ dataset = MyData(
81
+ datasets=testset,
82
+ image_size=config.size, is_train=False
83
+ )
84
+ _data_loader_test = torch.utils.data.DataLoader(
85
+ dataset=dataset, batch_size=config.batch_size_valid, num_workers=min(config.num_workers, config.batch_size_valid),
86
+ pin_memory=device != 'cpu', shuffle=False
87
+ )
88
+ print(len(_data_loader_test), "batches of valid dataloader {} have been created.".format(testset))
89
+ test_loaders[testset] = _data_loader_test
90
+
91
+ # Model, 3070MiB GPU memory for inference
92
+ model = BiRefNet(bb_pretrained=False).to(device)
93
+ models_evaluated = []
94
+ continous_sleep_time = 0
95
+ while True:
96
+ if (
97
+ (models_evaluated and continous_sleep_time > 60*60*2) or
98
+ (not models_evaluated and continous_sleep_time > 60*60*24)
99
+ ):
100
+ # If no ckpt has been saved, we wait for 24h;
101
+ # elif some ckpts have been saved, we wait for 2h for new ones;
102
+ # else: exit this waiting.
103
+ print('Exiting the waiting for evaluation.')
104
+ break
105
+ models_evaluated_record = 'tmp_models_evaluated.txt'
106
+ if os.path.exists(models_evaluated_record):
107
+ with open(models_evaluated_record, 'r') as f:
108
+ models_evaluated_global = f.read().splitlines()
109
+ else:
110
+ models_evaluated_global = []
111
+ models_detected = [
112
+ m for idx_m, m in enumerate(sorted(
113
+ glob(os.path.join(ckpt_dir, '*.pth')),
114
+ key=lambda x: int(x.rstrip('.pth').split('epoch_')[-1]), reverse=True
115
+ )) if idx_m % args_eval.val_step == args_eval.program_id and m not in models_evaluated + models_evaluated_global
116
+ ]
117
+ if models_detected:
118
+ from time import time
119
+ time_st = time()
120
+ # register the evaluated models
121
+ model_not_evaluated_latest = models_detected[0]
122
+ with open('tmp_models_evaluated.txt', 'a') as f:
123
+ f.write(model_not_evaluated_latest + '\n')
124
+ models_evaluated.append(model_not_evaluated_latest)
125
+ print('Loading {} for validation...'.format(model_not_evaluated_latest))
126
+
127
+ # evaluate the current model
128
+ state_dict = torch.load(model_not_evaluated_latest, map_location=device)
129
+ model.load_state_dict(state_dict, strict=False)
130
+ validate_model(model, test_loaders, int(model_not_evaluated_latest.rstrip('.pth').split('epoch_')[-1]))
131
+ continous_sleep_time = 0
132
+ print('Duration of this evaluation:', time() - time_st)
133
+ else:
134
+ sleep_interval = 60 * 2
135
+ sleep(sleep_interval)
136
+ continous_sleep_time += sleep_interval
137
+ continue
138
+
139
+
140
+ if __name__ == '__main__':
141
+ main()