shunk031 commited on
Commit
0c6516e
·
verified ·
1 Parent(s): 14dd216

Upload ISNet

Browse files
Files changed (5) hide show
  1. README.md +199 -0
  2. config.json +13 -0
  3. configuration_isnet.py +8 -0
  4. model.safetensors +3 -0
  5. modeling_isnet.py +713 -0
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "ISNet"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_isnet.ISNetConfig",
7
+ "AutoModel": "modeling_isnet.ISNet"
8
+ },
9
+ "in_channels": 3,
10
+ "out_channels": 1,
11
+ "torch_dtype": "float32",
12
+ "transformers_version": "4.43.1"
13
+ }
configuration_isnet.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+
4
+ class ISNetConfig(PretrainedConfig):
5
+ def __init__(self, in_channels: int = 3, out_channels: int = 1, **kwargs) -> None:
6
+ super().__init__(**kwargs)
7
+ self.in_channels = in_channels
8
+ self.out_channels = out_channels
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:31468665a1c188807d53fc0713f8c4fd60afb8458b58e2058a0343d36a057c82
3
+ size 176381984
modeling_isnet.py ADDED
@@ -0,0 +1,713 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from typing import Literal, Optional, Tuple
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ from transformers import PreTrainedModel
8
+
9
+ from .configuration_isnet import ISNetConfig
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+ bce_loss = nn.BCELoss(size_average=True)
14
+
15
+
16
+ def muti_loss_fusion(preds, target):
17
+ loss0 = 0.0
18
+ loss = 0.0
19
+
20
+ for i in range(0, len(preds)):
21
+ # print("i: ", i, preds[i].shape)
22
+ if preds[i].shape[2] != target.shape[2] or preds[i].shape[3] != target.shape[3]:
23
+ # tmp_target = _upsample_like(target,preds[i])
24
+ tmp_target = F.interpolate(
25
+ target, size=preds[i].size()[2:], mode="bilinear", align_corners=True
26
+ )
27
+ loss = loss + bce_loss(preds[i], tmp_target)
28
+ else:
29
+ loss = loss + bce_loss(preds[i], target)
30
+ if i == 0:
31
+ loss0 = loss
32
+ return loss0, loss
33
+
34
+
35
+ fea_loss = nn.MSELoss(size_average=True)
36
+ kl_loss = nn.KLDivLoss(size_average=True)
37
+ l1_loss = nn.L1Loss(size_average=True)
38
+ smooth_l1_loss = nn.SmoothL1Loss(size_average=True)
39
+
40
+ LossMode = Literal["MSE", "KL", "MAE", "SmoothL1"]
41
+
42
+
43
+ def muti_loss_fusion_kl(
44
+ preds, target, dfs, fs, mode: LossMode = "MSE"
45
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
46
+ loss0 = 0.0
47
+ loss = 0.0
48
+
49
+ for i in range(0, len(preds)):
50
+ # print("i: ", i, preds[i].shape)
51
+ if preds[i].shape[2] != target.shape[2] or preds[i].shape[3] != target.shape[3]:
52
+ # tmp_target = _upsample_like(target,preds[i])
53
+ tmp_target = F.interpolate(
54
+ target, size=preds[i].size()[2:], mode="bilinear", align_corners=True
55
+ )
56
+ loss = loss + bce_loss(preds[i], tmp_target)
57
+ else:
58
+ loss = loss + bce_loss(preds[i], target)
59
+ if i == 0:
60
+ loss0 = loss
61
+
62
+ for i in range(0, len(dfs)):
63
+ if mode == "MSE":
64
+ loss = loss + fea_loss(
65
+ dfs[i], fs[i]
66
+ ) ### add the mse loss of features as additional constraints
67
+ # print("fea_loss: ", fea_loss(dfs[i],fs[i]).item())
68
+ elif mode == "KL":
69
+ loss = loss + kl_loss(F.log_softmax(dfs[i], dim=1), F.softmax(fs[i], dim=1))
70
+ # print("kl_loss: ", kl_loss(F.log_softmax(dfs[i],dim=1),F.softmax(fs[i],dim=1)).item())
71
+ elif mode == "MAE":
72
+ loss = loss + l1_loss(dfs[i], fs[i])
73
+ # print("ls_loss: ", l1_loss(dfs[i],fs[i]))
74
+ elif mode == "SmoothL1":
75
+ loss = loss + smooth_l1_loss(dfs[i], fs[i])
76
+ # print("SmoothL1: ", smooth_l1_loss(dfs[i],fs[i]).item())
77
+
78
+ return loss0, loss
79
+
80
+
81
+ class REBNCONV(nn.Module):
82
+ def __init__(self, in_ch=3, out_ch=3, dirate=1, stride=1):
83
+ super(REBNCONV, self).__init__()
84
+
85
+ self.conv_s1 = nn.Conv2d(
86
+ in_ch, out_ch, 3, padding=1 * dirate, dilation=1 * dirate, stride=stride
87
+ )
88
+ self.bn_s1 = nn.BatchNorm2d(out_ch)
89
+ self.relu_s1 = nn.ReLU(inplace=True)
90
+
91
+ def forward(self, x):
92
+ hx = x
93
+ xout = self.relu_s1(self.bn_s1(self.conv_s1(hx)))
94
+
95
+ return xout
96
+
97
+
98
+ def _upsample_like(src, tar: torch.Tensor) -> torch.Tensor:
99
+ """upsample tensor 'src' to have the same spatial size with tensor 'tar'"""
100
+ return F.upsample(src, size=tar.shape[2:], mode="bilinear")
101
+
102
+
103
+ ### RSU-7 ###
104
+ class RSU7(nn.Module):
105
+ def __init__(self, in_ch=3, mid_ch=12, out_ch=3, img_size=512) -> None:
106
+ super().__init__()
107
+
108
+ self.in_ch = in_ch
109
+ self.mid_ch = mid_ch
110
+ self.out_ch = out_ch
111
+
112
+ self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1) ## 1 -> 1/2
113
+
114
+ self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1)
115
+ self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
116
+
117
+ self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=1)
118
+ self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
119
+
120
+ self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=1)
121
+ self.pool3 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
122
+
123
+ self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=1)
124
+ self.pool4 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
125
+
126
+ self.rebnconv5 = REBNCONV(mid_ch, mid_ch, dirate=1)
127
+ self.pool5 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
128
+
129
+ self.rebnconv6 = REBNCONV(mid_ch, mid_ch, dirate=1)
130
+
131
+ self.rebnconv7 = REBNCONV(mid_ch, mid_ch, dirate=2)
132
+
133
+ self.rebnconv6d = REBNCONV(mid_ch * 2, mid_ch, dirate=1)
134
+ self.rebnconv5d = REBNCONV(mid_ch * 2, mid_ch, dirate=1)
135
+ self.rebnconv4d = REBNCONV(mid_ch * 2, mid_ch, dirate=1)
136
+ self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=1)
137
+ self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=1)
138
+ self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1)
139
+
140
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
141
+ # b, c, h, w = x.shape
142
+
143
+ hx = x
144
+ hxin = self.rebnconvin(hx)
145
+
146
+ hx1 = self.rebnconv1(hxin)
147
+ hx = self.pool1(hx1)
148
+
149
+ hx2 = self.rebnconv2(hx)
150
+ hx = self.pool2(hx2)
151
+
152
+ hx3 = self.rebnconv3(hx)
153
+ hx = self.pool3(hx3)
154
+
155
+ hx4 = self.rebnconv4(hx)
156
+ hx = self.pool4(hx4)
157
+
158
+ hx5 = self.rebnconv5(hx)
159
+ hx = self.pool5(hx5)
160
+
161
+ hx6 = self.rebnconv6(hx)
162
+
163
+ hx7 = self.rebnconv7(hx6)
164
+
165
+ hx6d = self.rebnconv6d(torch.cat((hx7, hx6), 1))
166
+ hx6dup = _upsample_like(hx6d, hx5)
167
+
168
+ hx5d = self.rebnconv5d(torch.cat((hx6dup, hx5), 1))
169
+ hx5dup = _upsample_like(hx5d, hx4)
170
+
171
+ hx4d = self.rebnconv4d(torch.cat((hx5dup, hx4), 1))
172
+ hx4dup = _upsample_like(hx4d, hx3)
173
+
174
+ hx3d = self.rebnconv3d(torch.cat((hx4dup, hx3), 1))
175
+ hx3dup = _upsample_like(hx3d, hx2)
176
+
177
+ hx2d = self.rebnconv2d(torch.cat((hx3dup, hx2), 1))
178
+ hx2dup = _upsample_like(hx2d, hx1)
179
+
180
+ hx1d = self.rebnconv1d(torch.cat((hx2dup, hx1), 1))
181
+
182
+ return hx1d + hxin
183
+
184
+
185
+ ### RSU-6 ###
186
+ class RSU6(nn.Module):
187
+ def __init__(self, in_ch=3, mid_ch=12, out_ch=3) -> None:
188
+ super().__init__()
189
+
190
+ self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1)
191
+
192
+ self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1)
193
+ self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
194
+
195
+ self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=1)
196
+ self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
197
+
198
+ self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=1)
199
+ self.pool3 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
200
+
201
+ self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=1)
202
+ self.pool4 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
203
+
204
+ self.rebnconv5 = REBNCONV(mid_ch, mid_ch, dirate=1)
205
+
206
+ self.rebnconv6 = REBNCONV(mid_ch, mid_ch, dirate=2)
207
+
208
+ self.rebnconv5d = REBNCONV(mid_ch * 2, mid_ch, dirate=1)
209
+ self.rebnconv4d = REBNCONV(mid_ch * 2, mid_ch, dirate=1)
210
+ self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=1)
211
+ self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=1)
212
+ self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1)
213
+
214
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
215
+ hx = x
216
+
217
+ hxin = self.rebnconvin(hx)
218
+
219
+ hx1 = self.rebnconv1(hxin)
220
+ hx = self.pool1(hx1)
221
+
222
+ hx2 = self.rebnconv2(hx)
223
+ hx = self.pool2(hx2)
224
+
225
+ hx3 = self.rebnconv3(hx)
226
+ hx = self.pool3(hx3)
227
+
228
+ hx4 = self.rebnconv4(hx)
229
+ hx = self.pool4(hx4)
230
+
231
+ hx5 = self.rebnconv5(hx)
232
+
233
+ hx6 = self.rebnconv6(hx5)
234
+
235
+ hx5d = self.rebnconv5d(torch.cat((hx6, hx5), 1))
236
+ hx5dup = _upsample_like(hx5d, hx4)
237
+
238
+ hx4d = self.rebnconv4d(torch.cat((hx5dup, hx4), 1))
239
+ hx4dup = _upsample_like(hx4d, hx3)
240
+
241
+ hx3d = self.rebnconv3d(torch.cat((hx4dup, hx3), 1))
242
+ hx3dup = _upsample_like(hx3d, hx2)
243
+
244
+ hx2d = self.rebnconv2d(torch.cat((hx3dup, hx2), 1))
245
+ hx2dup = _upsample_like(hx2d, hx1)
246
+
247
+ hx1d = self.rebnconv1d(torch.cat((hx2dup, hx1), 1))
248
+
249
+ return hx1d + hxin
250
+
251
+
252
+ ### RSU-5 ###
253
+ class RSU5(nn.Module):
254
+ def __init__(self, in_ch=3, mid_ch=12, out_ch=3) -> None:
255
+ super().__init__()
256
+
257
+ self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1)
258
+
259
+ self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1)
260
+ self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
261
+
262
+ self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=1)
263
+ self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
264
+
265
+ self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=1)
266
+ self.pool3 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
267
+
268
+ self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=1)
269
+
270
+ self.rebnconv5 = REBNCONV(mid_ch, mid_ch, dirate=2)
271
+
272
+ self.rebnconv4d = REBNCONV(mid_ch * 2, mid_ch, dirate=1)
273
+ self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=1)
274
+ self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=1)
275
+ self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1)
276
+
277
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
278
+ hx = x
279
+
280
+ hxin = self.rebnconvin(hx)
281
+
282
+ hx1 = self.rebnconv1(hxin)
283
+ hx = self.pool1(hx1)
284
+
285
+ hx2 = self.rebnconv2(hx)
286
+ hx = self.pool2(hx2)
287
+
288
+ hx3 = self.rebnconv3(hx)
289
+ hx = self.pool3(hx3)
290
+
291
+ hx4 = self.rebnconv4(hx)
292
+
293
+ hx5 = self.rebnconv5(hx4)
294
+
295
+ hx4d = self.rebnconv4d(torch.cat((hx5, hx4), 1))
296
+ hx4dup = _upsample_like(hx4d, hx3)
297
+
298
+ hx3d = self.rebnconv3d(torch.cat((hx4dup, hx3), 1))
299
+ hx3dup = _upsample_like(hx3d, hx2)
300
+
301
+ hx2d = self.rebnconv2d(torch.cat((hx3dup, hx2), 1))
302
+ hx2dup = _upsample_like(hx2d, hx1)
303
+
304
+ hx1d = self.rebnconv1d(torch.cat((hx2dup, hx1), 1))
305
+
306
+ return hx1d + hxin
307
+
308
+
309
+ ### RSU-4 ###
310
+ class RSU4(nn.Module):
311
+ def __init__(self, in_ch=3, mid_ch=12, out_ch=3) -> None:
312
+ super(RSU4, self).__init__()
313
+
314
+ self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1)
315
+
316
+ self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1)
317
+ self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
318
+
319
+ self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=1)
320
+ self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
321
+
322
+ self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=1)
323
+
324
+ self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=2)
325
+
326
+ self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=1)
327
+ self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=1)
328
+ self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1)
329
+
330
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
331
+ hx = x
332
+
333
+ hxin = self.rebnconvin(hx)
334
+
335
+ hx1 = self.rebnconv1(hxin)
336
+ hx = self.pool1(hx1)
337
+
338
+ hx2 = self.rebnconv2(hx)
339
+ hx = self.pool2(hx2)
340
+
341
+ hx3 = self.rebnconv3(hx)
342
+
343
+ hx4 = self.rebnconv4(hx3)
344
+
345
+ hx3d = self.rebnconv3d(torch.cat((hx4, hx3), 1))
346
+ hx3dup = _upsample_like(hx3d, hx2)
347
+
348
+ hx2d = self.rebnconv2d(torch.cat((hx3dup, hx2), 1))
349
+ hx2dup = _upsample_like(hx2d, hx1)
350
+
351
+ hx1d = self.rebnconv1d(torch.cat((hx2dup, hx1), 1))
352
+
353
+ return hx1d + hxin
354
+
355
+
356
+ ### RSU-4F ###
357
+ class RSU4F(nn.Module):
358
+ def __init__(self, in_ch=3, mid_ch=12, out_ch=3) -> None:
359
+ super().__init__()
360
+
361
+ self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1)
362
+
363
+ self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1)
364
+ self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=2)
365
+ self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=4)
366
+
367
+ self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=8)
368
+
369
+ self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=4)
370
+ self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=2)
371
+ self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1)
372
+
373
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
374
+ hx = x
375
+
376
+ hxin = self.rebnconvin(hx)
377
+
378
+ hx1 = self.rebnconv1(hxin)
379
+ hx2 = self.rebnconv2(hx1)
380
+ hx3 = self.rebnconv3(hx2)
381
+
382
+ hx4 = self.rebnconv4(hx3)
383
+
384
+ hx3d = self.rebnconv3d(torch.cat((hx4, hx3), 1))
385
+ hx2d = self.rebnconv2d(torch.cat((hx3d, hx2), 1))
386
+ hx1d = self.rebnconv1d(torch.cat((hx2d, hx1), 1))
387
+
388
+ return hx1d + hxin
389
+
390
+
391
+ class myrebnconv(nn.Module):
392
+ def __init__(
393
+ self,
394
+ in_ch=3,
395
+ out_ch=1,
396
+ kernel_size=3,
397
+ stride=1,
398
+ padding=1,
399
+ dilation=1,
400
+ groups=1,
401
+ ) -> None:
402
+ super().__init__()
403
+
404
+ self.conv = nn.Conv2d(
405
+ in_ch,
406
+ out_ch,
407
+ kernel_size=kernel_size,
408
+ stride=stride,
409
+ padding=padding,
410
+ dilation=dilation,
411
+ groups=groups,
412
+ )
413
+ self.bn = nn.BatchNorm2d(out_ch)
414
+ self.rl = nn.ReLU(inplace=True)
415
+
416
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
417
+ return self.rl(self.bn(self.conv(x)))
418
+
419
+
420
+ class ISNetGTEncoder(nn.Module):
421
+ def __init__(self, in_ch=1, out_ch=1) -> None:
422
+ super(ISNetGTEncoder, self).__init__()
423
+
424
+ self.conv_in = myrebnconv(
425
+ in_ch, 16, 3, stride=2, padding=1
426
+ ) # nn.Conv2d(in_ch,64,3,stride=2,padding=1)
427
+
428
+ self.stage1 = RSU7(16, 16, 64)
429
+ self.pool12 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
430
+
431
+ self.stage2 = RSU6(64, 16, 64)
432
+ self.pool23 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
433
+
434
+ self.stage3 = RSU5(64, 32, 128)
435
+ self.pool34 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
436
+
437
+ self.stage4 = RSU4(128, 32, 256)
438
+ self.pool45 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
439
+
440
+ self.stage5 = RSU4F(256, 64, 512)
441
+ self.pool56 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
442
+
443
+ self.stage6 = RSU4F(512, 64, 512)
444
+
445
+ self.side1 = nn.Conv2d(64, out_ch, 3, padding=1)
446
+ self.side2 = nn.Conv2d(64, out_ch, 3, padding=1)
447
+ self.side3 = nn.Conv2d(128, out_ch, 3, padding=1)
448
+ self.side4 = nn.Conv2d(256, out_ch, 3, padding=1)
449
+ self.side5 = nn.Conv2d(512, out_ch, 3, padding=1)
450
+ self.side6 = nn.Conv2d(512, out_ch, 3, padding=1)
451
+
452
+ def compute_loss(self, preds, targets):
453
+ return muti_loss_fusion(preds, targets)
454
+
455
+ def forward(
456
+ self, x: torch.Tensor
457
+ ) -> Tuple[
458
+ Tuple[
459
+ torch.Tensor,
460
+ torch.Tensor,
461
+ torch.Tensor,
462
+ torch.Tensor,
463
+ torch.Tensor,
464
+ torch.Tensor,
465
+ ],
466
+ Tuple[
467
+ torch.Tensor,
468
+ torch.Tensor,
469
+ torch.Tensor,
470
+ torch.Tensor,
471
+ torch.Tensor,
472
+ torch.Tensor,
473
+ ],
474
+ ]:
475
+ hx = x
476
+
477
+ hxin = self.conv_in(hx)
478
+ # hx = self.pool_in(hxin)
479
+
480
+ # stage 1
481
+ hx1 = self.stage1(hxin)
482
+ hx = self.pool12(hx1)
483
+
484
+ # stage 2
485
+ hx2 = self.stage2(hx)
486
+ hx = self.pool23(hx2)
487
+
488
+ # stage 3
489
+ hx3 = self.stage3(hx)
490
+ hx = self.pool34(hx3)
491
+
492
+ # stage 4
493
+ hx4 = self.stage4(hx)
494
+ hx = self.pool45(hx4)
495
+
496
+ # stage 5
497
+ hx5 = self.stage5(hx)
498
+ hx = self.pool56(hx5)
499
+
500
+ # stage 6
501
+ hx6 = self.stage6(hx)
502
+
503
+ # side output
504
+ d1 = self.side1(hx1)
505
+ d1 = _upsample_like(d1, x)
506
+
507
+ d2 = self.side2(hx2)
508
+ d2 = _upsample_like(d2, x)
509
+
510
+ d3 = self.side3(hx3)
511
+ d3 = _upsample_like(d3, x)
512
+
513
+ d4 = self.side4(hx4)
514
+ d4 = _upsample_like(d4, x)
515
+
516
+ d5 = self.side5(hx5)
517
+ d5 = _upsample_like(d5, x)
518
+
519
+ d6 = self.side6(hx6)
520
+ d6 = _upsample_like(d6, x)
521
+
522
+ # d0 = self.outconv(torch.cat((d1,d2,d3,d4,d5,d6),1))
523
+
524
+ activated = (
525
+ F.sigmoid(d1),
526
+ F.sigmoid(d2),
527
+ F.sigmoid(d3),
528
+ F.sigmoid(d4),
529
+ F.sigmoid(d5),
530
+ F.sigmoid(d6),
531
+ )
532
+ hidden_states = (
533
+ hx1,
534
+ hx2,
535
+ hx3,
536
+ hx4,
537
+ hx5,
538
+ hx6,
539
+ )
540
+ return activated, hidden_states
541
+
542
+
543
+ class ISNet(PreTrainedModel):
544
+ config_class = ISNetConfig
545
+
546
+ def __init__(self, config: ISNetConfig) -> None:
547
+ super().__init__(config)
548
+
549
+ self.conv_in = nn.Conv2d(config.in_channels, 64, 3, stride=2, padding=1)
550
+ self.pool_in = nn.MaxPool2d(2, stride=2, ceil_mode=True)
551
+
552
+ self.stage1 = RSU7(64, 32, 64)
553
+ self.pool12 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
554
+
555
+ self.stage2 = RSU6(64, 32, 128)
556
+ self.pool23 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
557
+
558
+ self.stage3 = RSU5(128, 64, 256)
559
+ self.pool34 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
560
+
561
+ self.stage4 = RSU4(256, 128, 512)
562
+ self.pool45 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
563
+
564
+ self.stage5 = RSU4F(512, 256, 512)
565
+ self.pool56 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
566
+
567
+ self.stage6 = RSU4F(512, 256, 512)
568
+
569
+ # decoder
570
+ self.stage5d = RSU4F(1024, 256, 512)
571
+ self.stage4d = RSU4(1024, 128, 256)
572
+ self.stage3d = RSU5(512, 64, 128)
573
+ self.stage2d = RSU6(256, 32, 64)
574
+ self.stage1d = RSU7(128, 16, 64)
575
+
576
+ self.side1 = nn.Conv2d(64, config.out_channels, 3, padding=1)
577
+ self.side2 = nn.Conv2d(64, config.out_channels, 3, padding=1)
578
+ self.side3 = nn.Conv2d(128, config.out_channels, 3, padding=1)
579
+ self.side4 = nn.Conv2d(256, config.out_channels, 3, padding=1)
580
+ self.side5 = nn.Conv2d(512, config.out_channels, 3, padding=1)
581
+ self.side6 = nn.Conv2d(512, config.out_channels, 3, padding=1)
582
+
583
+ # self.outconv = nn.Conv2d(6*out_ch,out_ch,1)
584
+
585
+ def compute_loss_kl(self, preds, targets, dfs, fs, mode="MSE"):
586
+ # return muti_loss_fusion(preds,targets)
587
+ return muti_loss_fusion_kl(preds, targets, dfs, fs, mode=mode)
588
+
589
+ def compute_loss(self, preds, targets):
590
+ # return muti_loss_fusion(preds,targets)
591
+ return muti_loss_fusion(preds, targets)
592
+
593
+ def forward(
594
+ self, pixel_values: torch.Tensor
595
+ ) -> Tuple[
596
+ Tuple[
597
+ torch.Tensor,
598
+ torch.Tensor,
599
+ torch.Tensor,
600
+ torch.Tensor,
601
+ torch.Tensor,
602
+ torch.Tensor,
603
+ ],
604
+ Tuple[
605
+ torch.Tensor,
606
+ torch.Tensor,
607
+ torch.Tensor,
608
+ torch.Tensor,
609
+ torch.Tensor,
610
+ torch.Tensor,
611
+ ],
612
+ ]:
613
+ x = pixel_values
614
+ hx = x
615
+
616
+ hxin = self.conv_in(hx)
617
+ # hx = self.pool_in(hxin)
618
+
619
+ # stage 1
620
+ hx1 = self.stage1(hxin)
621
+ hx = self.pool12(hx1)
622
+
623
+ # stage 2
624
+ hx2 = self.stage2(hx)
625
+ hx = self.pool23(hx2)
626
+
627
+ # stage 3
628
+ hx3 = self.stage3(hx)
629
+ hx = self.pool34(hx3)
630
+
631
+ # stage 4
632
+ hx4 = self.stage4(hx)
633
+ hx = self.pool45(hx4)
634
+
635
+ # stage 5
636
+ hx5 = self.stage5(hx)
637
+ hx = self.pool56(hx5)
638
+
639
+ # stage 6
640
+ hx6 = self.stage6(hx)
641
+ hx6up = _upsample_like(hx6, hx5)
642
+
643
+ # -------------------- decoder --------------------
644
+ hx5d = self.stage5d(torch.cat((hx6up, hx5), 1))
645
+ hx5dup = _upsample_like(hx5d, hx4)
646
+
647
+ hx4d = self.stage4d(torch.cat((hx5dup, hx4), 1))
648
+ hx4dup = _upsample_like(hx4d, hx3)
649
+
650
+ hx3d = self.stage3d(torch.cat((hx4dup, hx3), 1))
651
+ hx3dup = _upsample_like(hx3d, hx2)
652
+
653
+ hx2d = self.stage2d(torch.cat((hx3dup, hx2), 1))
654
+ hx2dup = _upsample_like(hx2d, hx1)
655
+
656
+ hx1d = self.stage1d(torch.cat((hx2dup, hx1), 1))
657
+
658
+ # side output
659
+ d1 = self.side1(hx1d)
660
+ d1 = _upsample_like(d1, x)
661
+
662
+ d2 = self.side2(hx2d)
663
+ d2 = _upsample_like(d2, x)
664
+
665
+ d3 = self.side3(hx3d)
666
+ d3 = _upsample_like(d3, x)
667
+
668
+ d4 = self.side4(hx4d)
669
+ d4 = _upsample_like(d4, x)
670
+
671
+ d5 = self.side5(hx5d)
672
+ d5 = _upsample_like(d5, x)
673
+
674
+ d6 = self.side6(hx6)
675
+ d6 = _upsample_like(d6, x)
676
+
677
+ # d0 = self.outconv(torch.cat((d1,d2,d3,d4,d5,d6),1))
678
+
679
+ activated = (
680
+ F.sigmoid(d1),
681
+ F.sigmoid(d2),
682
+ F.sigmoid(d3),
683
+ F.sigmoid(d4),
684
+ F.sigmoid(d5),
685
+ F.sigmoid(d6),
686
+ )
687
+ hidden_states = (
688
+ hx1d,
689
+ hx2d,
690
+ hx3d,
691
+ hx4d,
692
+ hx5d,
693
+ hx6,
694
+ )
695
+ return activated, hidden_states
696
+
697
+
698
+ def convert_from_checkpoint(
699
+ repo_id: str, filename: str, config: Optional[ISNetConfig] = None
700
+ ) -> ISNet:
701
+ from huggingface_hub import hf_hub_download
702
+
703
+ checkpoint_path = hf_hub_download(repo_id=repo_id, filename=filename)
704
+ config = config or ISNetConfig()
705
+ model = ISNet(config)
706
+
707
+ logger.info(f"Loading checkpoint from {checkpoint_path}")
708
+ state_dict = torch.load(checkpoint_path)
709
+
710
+ model.load_state_dict(state_dict, strict=True)
711
+ model.eval()
712
+
713
+ return model