artelabsuper commited on
Commit
b4eade4
·
1 Parent(s): 8c753d1

demo with model

Browse files
Files changed (9) hide show
  1. .gitattributes +1 -0
  2. .gitignore +3 -0
  3. README.md +5 -0
  4. app.py +39 -5
  5. best_model.ckpt +3 -0
  6. models/mit.py +437 -0
  7. models/model.py +112 -0
  8. requirements.txt +2 -0
  9. test.py +36 -0
.gitattributes CHANGED
@@ -25,3 +25,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
25
  *.zip filter=lfs diff=lfs merge=lfs -text
26
  *.zstandard filter=lfs diff=lfs merge=lfs -text
27
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
25
  *.zip filter=lfs diff=lfs merge=lfs -text
26
  *.zstandard filter=lfs diff=lfs merge=lfs -text
27
  *tfevents* filter=lfs diff=lfs merge=lfs -text
28
+ best_model.ckpt filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ venv
2
+ __pycache__
3
+ test.png
README.md CHANGED
@@ -10,3 +10,8 @@ pinned: false
10
  ---
11
 
12
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
10
  ---
11
 
12
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
13
+
14
+ ```
15
+ pip install -r requirements.txt
16
+ python3.8 app.py
17
+ ```
app.py CHANGED
@@ -1,20 +1,54 @@
1
  import gradio as gr
2
  from PIL import Image
3
- import torchvision
4
  import torch
 
 
 
 
 
 
 
 
 
5
 
6
  # load model
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
  def predict(input_image):
9
  pil_image = Image.fromarray(input_image.astype('uint8'), 'RGB')
10
  # transform image to torch and do preprocessing
11
- torch_image = torchvision.transforms.ToTensor()(pil_image)
12
  # model predict
13
- prediction = torch.rand(torch_image.shape)
 
14
  # transform torch to image
15
- predicted_pil_image = torchvision.transforms.ToPILImage()(prediction)
16
  # return correct image
17
- return predicted_pil_image
 
 
 
 
 
 
 
 
18
 
19
  iface = gr.Interface(
20
  fn=predict,
 
1
  import gradio as gr
2
  from PIL import Image
3
+ from collections import OrderedDict
4
  import torch
5
+ from models.model import GLPDepth
6
+ from PIL import Image
7
+ from torchvision import transforms
8
+ import matplotlib.pyplot as plt
9
+ from matplotlib.backends.backend_agg import FigureCanvasAgg
10
+ import numpy as np
11
+
12
+
13
+
14
 
15
  # load model
16
+ DEVICE='cpu'
17
+ def load_mde_model(path):
18
+ model = GLPDepth(max_depth=700.0, is_train=False).to(DEVICE)
19
+ model_weight = torch.load(path, map_location=torch.device('cpu'))
20
+ model_weight = model_weight['model_state_dict']
21
+ if 'module' in next(iter(model_weight.items()))[0]:
22
+ model_weight = OrderedDict((k[7:], v) for k, v in model_weight.items())
23
+ model.load_state_dict(model_weight)
24
+ model.eval()
25
+ return model
26
+
27
+ model = load_mde_model('best_model.ckpt')
28
+ preprocess = transforms.Compose([
29
+ transforms.Resize((512, 512)),
30
+ transforms.ToTensor()
31
+ ])
32
 
33
  def predict(input_image):
34
  pil_image = Image.fromarray(input_image.astype('uint8'), 'RGB')
35
  # transform image to torch and do preprocessing
36
+ torch_img = preprocess(pil_image).to(DEVICE).unsqueeze(0)
37
  # model predict
38
+ with torch.no_grad():
39
+ output_patch = model(torch_img)
40
  # transform torch to image
41
+ predicted_image = output_patch['pred_d'].squeeze().cpu().detach().numpy()
42
  # return correct image
43
+ fig, ax = plt.subplots()
44
+ im = ax.imshow(predicted_image, cmap='jet', vmin=0, vmax=np.max(predicted_image))
45
+ plt.colorbar(im, ax=ax)
46
+
47
+ fig.canvas.draw()
48
+ data = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
49
+ data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
50
+
51
+ return data
52
 
53
  iface = gr.Interface(
54
  fn=predict,
best_model.ckpt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ccef15e6acd9e19231d0093d365d4a14c68454a83ac49ba8b292ce5df9ca4d23
3
+ size 735542869
models/mit.py ADDED
@@ -0,0 +1,437 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ---------------------------------------------------------------
2
+ # Copyright (c) 2021, NVIDIA Corporation. All rights reserved.
3
+ #
4
+ # This work is licensed under the NVIDIA Source Code License
5
+ # ---------------------------------------------------------------
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+ from functools import partial
10
+
11
+ from timm.models.layers import DropPath, to_2tuple, trunc_normal_
12
+ from timm.models.registry import register_model
13
+ from timm.models.vision_transformer import _cfg
14
+ # from mmseg.models.builder import BACKBONES
15
+ from mmcv.runner import load_checkpoint
16
+ import math
17
+
18
+
19
+ class Mlp(nn.Module):
20
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
21
+ super().__init__()
22
+ out_features = out_features or in_features
23
+ hidden_features = hidden_features or in_features
24
+ self.fc1 = nn.Linear(in_features, hidden_features)
25
+ self.dwconv = DWConv(hidden_features)
26
+ self.act = act_layer()
27
+ self.fc2 = nn.Linear(hidden_features, out_features)
28
+ self.drop = nn.Dropout(drop)
29
+
30
+ self.apply(self._init_weights)
31
+
32
+ def _init_weights(self, m):
33
+ if isinstance(m, nn.Linear):
34
+ trunc_normal_(m.weight, std=.02)
35
+ if isinstance(m, nn.Linear) and m.bias is not None:
36
+ nn.init.constant_(m.bias, 0)
37
+ elif isinstance(m, nn.LayerNorm):
38
+ nn.init.constant_(m.bias, 0)
39
+ nn.init.constant_(m.weight, 1.0)
40
+ elif isinstance(m, nn.Conv2d):
41
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
42
+ fan_out //= m.groups
43
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
44
+ if m.bias is not None:
45
+ m.bias.data.zero_()
46
+
47
+ def forward(self, x, H, W):
48
+ x = self.fc1(x)
49
+ x = self.dwconv(x, H, W)
50
+ x = self.act(x)
51
+ x = self.drop(x)
52
+ x = self.fc2(x)
53
+ x = self.drop(x)
54
+ return x
55
+
56
+
57
+ class Attention(nn.Module):
58
+ def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., sr_ratio=1):
59
+ super().__init__()
60
+ assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}."
61
+
62
+ self.dim = dim
63
+ self.num_heads = num_heads
64
+ head_dim = dim // num_heads
65
+ self.scale = qk_scale or head_dim ** -0.5
66
+
67
+ self.q = nn.Linear(dim, dim, bias=qkv_bias)
68
+ self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias)
69
+ self.attn_drop = nn.Dropout(attn_drop)
70
+ self.proj = nn.Linear(dim, dim)
71
+ self.proj_drop = nn.Dropout(proj_drop)
72
+
73
+ self.sr_ratio = sr_ratio
74
+ if sr_ratio > 1:
75
+ self.sr = nn.Conv2d(
76
+ dim, dim, kernel_size=sr_ratio, stride=sr_ratio)
77
+ self.norm = nn.LayerNorm(dim)
78
+
79
+ self.apply(self._init_weights)
80
+
81
+ def _init_weights(self, m):
82
+ if isinstance(m, nn.Linear):
83
+ trunc_normal_(m.weight, std=.02)
84
+ if isinstance(m, nn.Linear) and m.bias is not None:
85
+ nn.init.constant_(m.bias, 0)
86
+ elif isinstance(m, nn.LayerNorm):
87
+ nn.init.constant_(m.bias, 0)
88
+ nn.init.constant_(m.weight, 1.0)
89
+ elif isinstance(m, nn.Conv2d):
90
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
91
+ fan_out //= m.groups
92
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
93
+ if m.bias is not None:
94
+ m.bias.data.zero_()
95
+
96
+ def forward(self, x, H, W):
97
+ B, N, C = x.shape
98
+ q = self.q(x).reshape(B, N, self.num_heads, C //
99
+ self.num_heads).permute(0, 2, 1, 3)
100
+
101
+ if self.sr_ratio > 1:
102
+ x_ = x.permute(0, 2, 1).reshape(B, C, H, W)
103
+ x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1)
104
+ x_ = self.norm(x_)
105
+ kv = self.kv(x_).reshape(B, -1, 2, self.num_heads,
106
+ C // self.num_heads).permute(2, 0, 3, 1, 4)
107
+ else:
108
+ kv = self.kv(x).reshape(B, -1, 2, self.num_heads, C //
109
+ self.num_heads).permute(2, 0, 3, 1, 4)
110
+ k, v = kv[0], kv[1]
111
+
112
+ attn = (q @ k.transpose(-2, -1)) * self.scale
113
+ attn = attn.softmax(dim=-1)
114
+ attn = self.attn_drop(attn)
115
+
116
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
117
+ x = self.proj(x)
118
+ x = self.proj_drop(x)
119
+
120
+ return x
121
+
122
+
123
+ class Block(nn.Module):
124
+
125
+ def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
126
+ drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, sr_ratio=1):
127
+ super().__init__()
128
+ self.norm1 = norm_layer(dim)
129
+ self.attn = Attention(
130
+ dim,
131
+ num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
132
+ attn_drop=attn_drop, proj_drop=drop, sr_ratio=sr_ratio)
133
+ # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
134
+ self.drop_path = DropPath(
135
+ drop_path) if drop_path > 0. else nn.Identity()
136
+ self.norm2 = norm_layer(dim)
137
+ mlp_hidden_dim = int(dim * mlp_ratio)
138
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim,
139
+ act_layer=act_layer, drop=drop)
140
+
141
+ self.apply(self._init_weights)
142
+
143
+ def _init_weights(self, m):
144
+ if isinstance(m, nn.Linear):
145
+ trunc_normal_(m.weight, std=.02)
146
+ if isinstance(m, nn.Linear) and m.bias is not None:
147
+ nn.init.constant_(m.bias, 0)
148
+ elif isinstance(m, nn.LayerNorm):
149
+ nn.init.constant_(m.bias, 0)
150
+ nn.init.constant_(m.weight, 1.0)
151
+ elif isinstance(m, nn.Conv2d):
152
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
153
+ fan_out //= m.groups
154
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
155
+ if m.bias is not None:
156
+ m.bias.data.zero_()
157
+
158
+ def forward(self, x, H, W):
159
+ x = x + self.drop_path(self.attn(self.norm1(x), H, W))
160
+ x = x + self.drop_path(self.mlp(self.norm2(x), H, W))
161
+
162
+ return x
163
+
164
+
165
+ class OverlapPatchEmbed(nn.Module):
166
+ """ Image to Patch Embedding
167
+ """
168
+
169
+ def __init__(self, img_size=224, patch_size=7, stride=4, in_chans=3, embed_dim=768):
170
+ super().__init__()
171
+ img_size = to_2tuple(img_size)
172
+ patch_size = to_2tuple(patch_size)
173
+
174
+ self.img_size = img_size
175
+ self.patch_size = patch_size
176
+ self.H, self.W = img_size[0] // patch_size[0], img_size[1] // patch_size[1]
177
+ self.num_patches = self.H * self.W
178
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride,
179
+ padding=(patch_size[0] // 2, patch_size[1] // 2))
180
+ self.norm = nn.LayerNorm(embed_dim)
181
+
182
+ self.apply(self._init_weights)
183
+
184
+ def _init_weights(self, m):
185
+ if isinstance(m, nn.Linear):
186
+ trunc_normal_(m.weight, std=.02)
187
+ if isinstance(m, nn.Linear) and m.bias is not None:
188
+ nn.init.constant_(m.bias, 0)
189
+ elif isinstance(m, nn.LayerNorm):
190
+ nn.init.constant_(m.bias, 0)
191
+ nn.init.constant_(m.weight, 1.0)
192
+ elif isinstance(m, nn.Conv2d):
193
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
194
+ fan_out //= m.groups
195
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
196
+ if m.bias is not None:
197
+ m.bias.data.zero_()
198
+
199
+ def forward(self, x):
200
+ x = self.proj(x)
201
+ _, _, H, W = x.shape
202
+ x = x.flatten(2).transpose(1, 2)
203
+ x = self.norm(x)
204
+
205
+ return x, H, W
206
+
207
+
208
+ class MixVisionTransformer(nn.Module):
209
+ def __init__(self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, embed_dims=[64, 128, 256, 512],
210
+ num_heads=[1, 2, 4, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=False, qk_scale=None, drop_rate=0.,
211
+ attn_drop_rate=0., drop_path_rate=0., norm_layer=nn.LayerNorm,
212
+ depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1]):
213
+ super().__init__()
214
+ self.num_classes = num_classes
215
+ self.depths = depths
216
+
217
+ # patch_embed
218
+ self.patch_embed1 = OverlapPatchEmbed(img_size=img_size, patch_size=7, stride=4, in_chans=in_chans,
219
+ embed_dim=embed_dims[0])
220
+ self.patch_embed2 = OverlapPatchEmbed(img_size=img_size // 4, patch_size=3, stride=2, in_chans=embed_dims[0],
221
+ embed_dim=embed_dims[1])
222
+ self.patch_embed3 = OverlapPatchEmbed(img_size=img_size // 8, patch_size=3, stride=2, in_chans=embed_dims[1],
223
+ embed_dim=embed_dims[2])
224
+ self.patch_embed4 = OverlapPatchEmbed(img_size=img_size // 16, patch_size=3, stride=2, in_chans=embed_dims[2],
225
+ embed_dim=embed_dims[3])
226
+
227
+ # transformer encoder
228
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate,
229
+ sum(depths))] # stochastic depth decay rule
230
+ cur = 0
231
+ self.block1 = nn.ModuleList([Block(
232
+ dim=embed_dims[0], num_heads=num_heads[0], mlp_ratio=mlp_ratios[0], qkv_bias=qkv_bias, qk_scale=qk_scale,
233
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur +
234
+ i], norm_layer=norm_layer,
235
+ sr_ratio=sr_ratios[0])
236
+ for i in range(depths[0])])
237
+ self.norm1 = norm_layer(embed_dims[0])
238
+
239
+ cur += depths[0]
240
+ self.block2 = nn.ModuleList([Block(
241
+ dim=embed_dims[1], num_heads=num_heads[1], mlp_ratio=mlp_ratios[1], qkv_bias=qkv_bias, qk_scale=qk_scale,
242
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur +
243
+ i], norm_layer=norm_layer,
244
+ sr_ratio=sr_ratios[1])
245
+ for i in range(depths[1])])
246
+ self.norm2 = norm_layer(embed_dims[1])
247
+
248
+ cur += depths[1]
249
+ self.block3 = nn.ModuleList([Block(
250
+ dim=embed_dims[2], num_heads=num_heads[2], mlp_ratio=mlp_ratios[2], qkv_bias=qkv_bias, qk_scale=qk_scale,
251
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur +
252
+ i], norm_layer=norm_layer,
253
+ sr_ratio=sr_ratios[2])
254
+ for i in range(depths[2])])
255
+ self.norm3 = norm_layer(embed_dims[2])
256
+
257
+ cur += depths[2]
258
+ self.block4 = nn.ModuleList([Block(
259
+ dim=embed_dims[3], num_heads=num_heads[3], mlp_ratio=mlp_ratios[3], qkv_bias=qkv_bias, qk_scale=qk_scale,
260
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[cur +
261
+ i], norm_layer=norm_layer,
262
+ sr_ratio=sr_ratios[3])
263
+ for i in range(depths[3])])
264
+ self.norm4 = norm_layer(embed_dims[3])
265
+
266
+ # classification head
267
+ # self.head = nn.Linear(embed_dims[3], num_classes) if num_classes > 0 else nn.Identity()
268
+
269
+ self.apply(self._init_weights)
270
+
271
+ def _init_weights(self, m):
272
+ if isinstance(m, nn.Linear):
273
+ trunc_normal_(m.weight, std=.02)
274
+ if isinstance(m, nn.Linear) and m.bias is not None:
275
+ nn.init.constant_(m.bias, 0)
276
+ elif isinstance(m, nn.LayerNorm):
277
+ nn.init.constant_(m.bias, 0)
278
+ nn.init.constant_(m.weight, 1.0)
279
+ elif isinstance(m, nn.Conv2d):
280
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
281
+ fan_out //= m.groups
282
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
283
+ if m.bias is not None:
284
+ m.bias.data.zero_()
285
+
286
+ def init_weights(self, pretrained=None):
287
+ if isinstance(pretrained, str):
288
+ load_checkpoint(self, pretrained, map_location='cpu',
289
+ strict=False)
290
+
291
+ def reset_drop_path(self, drop_path_rate):
292
+ dpr = [x.item() for x in torch.linspace(
293
+ 0, drop_path_rate, sum(self.depths))]
294
+ cur = 0
295
+ for i in range(self.depths[0]):
296
+ self.block1[i].drop_path.drop_prob = dpr[cur + i]
297
+
298
+ cur += self.depths[0]
299
+ for i in range(self.depths[1]):
300
+ self.block2[i].drop_path.drop_prob = dpr[cur + i]
301
+
302
+ cur += self.depths[1]
303
+ for i in range(self.depths[2]):
304
+ self.block3[i].drop_path.drop_prob = dpr[cur + i]
305
+
306
+ cur += self.depths[2]
307
+ for i in range(self.depths[3]):
308
+ self.block4[i].drop_path.drop_prob = dpr[cur + i]
309
+
310
+ def freeze_patch_emb(self):
311
+ self.patch_embed1.requires_grad = False
312
+
313
+ @torch.jit.ignore
314
+ def no_weight_decay(self):
315
+ # has pos_embed may be better
316
+ return {'pos_embed1', 'pos_embed2', 'pos_embed3', 'pos_embed4', 'cls_token'}
317
+
318
+ def get_classifier(self):
319
+ return self.head
320
+
321
+ def reset_classifier(self, num_classes, global_pool=''):
322
+ self.num_classes = num_classes
323
+ self.head = nn.Linear(
324
+ self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()
325
+
326
+ def forward_features(self, x):
327
+ B = x.shape[0]
328
+ outs = []
329
+
330
+ # stage 1
331
+ x, H, W = self.patch_embed1(x)
332
+ for i, blk in enumerate(self.block1):
333
+ x = blk(x, H, W)
334
+ x = self.norm1(x)
335
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
336
+ outs.append(x)
337
+
338
+ # stage 2
339
+ x, H, W = self.patch_embed2(x)
340
+ for i, blk in enumerate(self.block2):
341
+ x = blk(x, H, W)
342
+ x = self.norm2(x)
343
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
344
+ outs.append(x)
345
+
346
+ # stage 3
347
+ x, H, W = self.patch_embed3(x)
348
+ for i, blk in enumerate(self.block3):
349
+ x = blk(x, H, W)
350
+ x = self.norm3(x)
351
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
352
+ outs.append(x)
353
+
354
+ # stage 4
355
+ x, H, W = self.patch_embed4(x)
356
+ for i, blk in enumerate(self.block4):
357
+ x = blk(x, H, W)
358
+ x = self.norm4(x)
359
+ x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous()
360
+ outs.append(x)
361
+
362
+ return outs
363
+
364
+ def forward(self, x):
365
+ x = self.forward_features(x)
366
+ # x = self.head(x)
367
+
368
+ return x
369
+
370
+
371
+ class DWConv(nn.Module):
372
+ def __init__(self, dim=768):
373
+ super(DWConv, self).__init__()
374
+ self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim)
375
+
376
+ def forward(self, x, H, W):
377
+ B, N, C = x.shape
378
+ x = x.transpose(1, 2).view(B, C, H, W)
379
+ x = self.dwconv(x)
380
+ x = x.flatten(2).transpose(1, 2)
381
+
382
+ return x
383
+
384
+
385
+ class mit_b0(MixVisionTransformer):
386
+ def __init__(self, **kwargs):
387
+ super(mit_b0, self).__init__(
388
+ patch_size=4, embed_dims=[32, 64, 160, 256], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4],
389
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1],
390
+ drop_rate=0.0, drop_path_rate=0.1)
391
+
392
+
393
+ class mit_b1(MixVisionTransformer):
394
+ def __init__(self, **kwargs):
395
+ super(mit_b1, self).__init__(
396
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4],
397
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1],
398
+ drop_rate=0.0, drop_path_rate=0.1)
399
+
400
+
401
+ class mit_b2(MixVisionTransformer):
402
+ def __init__(self, **kwargs):
403
+ super(mit_b2, self).__init__(
404
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4],
405
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1],
406
+ drop_rate=0.0, drop_path_rate=0.1)
407
+
408
+
409
+ class mit_b3(MixVisionTransformer):
410
+ def __init__(self, **kwargs):
411
+ super(mit_b3, self).__init__(
412
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4],
413
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 4, 18, 3], sr_ratios=[8, 4, 2, 1],
414
+ drop_rate=0.0, drop_path_rate=0.1)
415
+
416
+
417
+ class mit_b4(MixVisionTransformer):
418
+ def __init__(self, **kwargs):
419
+ super(mit_b4, self).__init__(
420
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4],
421
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 8, 27, 3], sr_ratios=[8, 4, 2, 1],
422
+ drop_rate=0.0, drop_path_rate=0.1)
423
+
424
+
425
+ class mit_b5(MixVisionTransformer):
426
+ def __init__(self, **kwargs):
427
+ super(mit_b5, self).__init__(
428
+ patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4],
429
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), depths=[3, 6, 40, 3], sr_ratios=[8, 4, 2, 1],
430
+ drop_rate=0.0, drop_path_rate=0.1)
431
+
432
+
433
+ if __name__ == "__main__":
434
+ import pdb
435
+
436
+ model = mit_b5()
437
+ pdb.set_trace()
models/model.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+ from mmcv.runner import load_checkpoint
5
+ from models.mit import mit_b4
6
+
7
+
8
+ class GLPDepth(nn.Module):
9
+ def __init__(self, max_depth=10.0, is_train=False):
10
+ super().__init__()
11
+ self.max_depth = max_depth
12
+
13
+ self.encoder = mit_b4()
14
+ if is_train:
15
+ ckpt_path = './models/weights/mit_b4.pth'
16
+ try:
17
+ load_checkpoint(self.encoder, ckpt_path, logger=None)
18
+ except:
19
+ import gdown
20
+ print("Download pre-trained encoder weights...")
21
+ id = '1BUtU42moYrOFbsMCE-LTTkUE-mrWnfG2'
22
+ url = 'https://drive.google.com/uc?id=' + id
23
+ output = './models/weights/mit_b4.pth'
24
+ gdown.download(url, output, quiet=False)
25
+
26
+ channels_in = [512, 320, 128]
27
+ channels_out = 64
28
+
29
+ self.decoder = Decoder(channels_in, channels_out)
30
+
31
+ self.last_layer_depth = nn.Sequential(
32
+ nn.Conv2d(channels_out, channels_out, kernel_size=3, stride=1, padding=1),
33
+ nn.ReLU(inplace=False),
34
+ nn.Conv2d(channels_out, 1, kernel_size=3, stride=1, padding=1))
35
+
36
+ def forward(self, x):
37
+ conv1, conv2, conv3, conv4 = self.encoder(x)
38
+ out = self.decoder(conv1, conv2, conv3, conv4)
39
+ out_depth = self.last_layer_depth(out)
40
+ out_depth = torch.sigmoid(out_depth) * self.max_depth
41
+
42
+ return {'pred_d': out_depth}
43
+
44
+
45
+ class Decoder(nn.Module):
46
+ def __init__(self, in_channels, out_channels):
47
+ super().__init__()
48
+
49
+ self.bot_conv = nn.Conv2d(
50
+ in_channels=in_channels[0], out_channels=out_channels, kernel_size=1)
51
+ self.skip_conv1 = nn.Conv2d(
52
+ in_channels=in_channels[1], out_channels=out_channels, kernel_size=1)
53
+ self.skip_conv2 = nn.Conv2d(
54
+ in_channels=in_channels[2], out_channels=out_channels, kernel_size=1)
55
+
56
+ self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False)
57
+
58
+ self.fusion1 = SelectiveFeatureFusion(out_channels)
59
+ self.fusion2 = SelectiveFeatureFusion(out_channels)
60
+ self.fusion3 = SelectiveFeatureFusion(out_channels)
61
+
62
+ def forward(self, x_1, x_2, x_3, x_4):
63
+ x_4_ = self.bot_conv(x_4)
64
+ out = self.up(x_4_)
65
+
66
+ x_3_ = self.skip_conv1(x_3)
67
+ out = self.fusion1(x_3_, out)
68
+ out = self.up(out)
69
+
70
+ x_2_ = self.skip_conv2(x_2)
71
+ out = self.fusion2(x_2_, out)
72
+ out = self.up(out)
73
+
74
+ out = self.fusion3(x_1, out)
75
+ out = self.up(out)
76
+ out = self.up(out)
77
+
78
+ return out
79
+
80
+
81
+ class SelectiveFeatureFusion(nn.Module):
82
+ def __init__(self, in_channel=64):
83
+ super().__init__()
84
+
85
+ self.conv1 = nn.Sequential(
86
+ nn.Conv2d(in_channels=int(in_channel * 2),
87
+ out_channels=in_channel, kernel_size=3, stride=1, padding=1),
88
+ nn.BatchNorm2d(in_channel),
89
+ nn.ReLU())
90
+
91
+ self.conv2 = nn.Sequential(
92
+ nn.Conv2d(in_channels=in_channel,
93
+ out_channels=int(in_channel / 2), kernel_size=3, stride=1, padding=1),
94
+ nn.BatchNorm2d(int(in_channel / 2)),
95
+ nn.ReLU())
96
+
97
+ self.conv3 = nn.Conv2d(in_channels=int(in_channel / 2),
98
+ out_channels=2, kernel_size=3, stride=1, padding=1)
99
+
100
+ self.sigmoid = nn.Sigmoid()
101
+
102
+ def forward(self, x_local, x_global):
103
+ x = torch.cat((x_local, x_global), dim=1)
104
+ x = self.conv1(x)
105
+ x = self.conv2(x)
106
+ x = self.conv3(x)
107
+ attn = self.sigmoid(x)
108
+
109
+ out = x_local * attn[:, 0, :, :].unsqueeze(1) + \
110
+ x_global * attn[:, 1, :, :].unsqueeze(1)
111
+
112
+ return out
requirements.txt CHANGED
@@ -1,3 +1,5 @@
1
  gradio
2
  torch
3
  torchvision
 
 
 
1
  gradio
2
  torch
3
  torchvision
4
+ mmcv==1.4.3
5
+ timm==0.5.4
test.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+ import torch
3
+ from models.model import GLPDepth
4
+ from PIL import Image
5
+ from torchvision import transforms
6
+ import matplotlib.pyplot as plt
7
+ import numpy as np
8
+
9
+ DEVICE='cpu'
10
+
11
+ def load_mde_model(path):
12
+ model = GLPDepth(max_depth=700.0, is_train=False).to(DEVICE)
13
+ model_weight = torch.load(path, map_location=torch.device('cpu'))
14
+ model_weight = model_weight['model_state_dict']
15
+ if 'module' in next(iter(model_weight.items()))[0]:
16
+ model_weight = OrderedDict((k[7:], v) for k, v in model_weight.items())
17
+ model.load_state_dict(model_weight)
18
+ model.eval()
19
+ return model
20
+
21
+ model = load_mde_model('best_model.ckpt')
22
+ preprocess = transforms.Compose([
23
+ transforms.Resize((512, 512)),
24
+ transforms.ToTensor()
25
+ ])
26
+
27
+ input_img = Image.open('demo_imgs/fake.jpg')
28
+ torch_img = preprocess(input_img).to(DEVICE).unsqueeze(0)
29
+ with torch.no_grad():
30
+ output_patch = model(torch_img)
31
+ output_patch = output_patch['pred_d'].squeeze().cpu().detach().numpy()
32
+ print(output_patch.shape)
33
+
34
+ plt.imshow(output_patch, cmap='jet', vmin=0, vmax=np.max(output_patch))
35
+ plt.colorbar()
36
+ plt.savefig('test.png')