Upload EVPDepth
Browse files- attractor.py +208 -0
- config.json +4 -0
- dist_layers.py +121 -0
- evpconfig.py +16 -0
- layers.py +36 -0
- localbins_layers.py +169 -0
- miniViT.py +45 -0
- model.py +698 -0
- model.safetensors +1 -1
attractor.py
ADDED
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# MIT License
|
2 |
+
|
3 |
+
# Copyright (c) 2022 Intelligent Systems Lab Org
|
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.
|
22 |
+
|
23 |
+
# File author: Shariq Farooq Bhat
|
24 |
+
|
25 |
+
import torch
|
26 |
+
import torch.nn as nn
|
27 |
+
|
28 |
+
|
29 |
+
@torch.jit.script
|
30 |
+
def exp_attractor(dx, alpha: float = 300, gamma: int = 2):
|
31 |
+
"""Exponential attractor: dc = exp(-alpha*|dx|^gamma) * dx , where dx = a - c, a = attractor point, c = bin center, dc = shift in bin centermmary for exp_attractor
|
32 |
+
|
33 |
+
Args:
|
34 |
+
dx (torch.Tensor): The difference tensor dx = Ai - Cj, where Ai is the attractor point and Cj is the bin center.
|
35 |
+
alpha (float, optional): Proportional Attractor strength. Determines the absolute strength. Lower alpha = greater attraction. Defaults to 300.
|
36 |
+
gamma (int, optional): Exponential Attractor strength. Determines the "region of influence" and indirectly number of bin centers affected. Lower gamma = farther reach. Defaults to 2.
|
37 |
+
|
38 |
+
Returns:
|
39 |
+
torch.Tensor : Delta shifts - dc; New bin centers = Old bin centers + dc
|
40 |
+
"""
|
41 |
+
return torch.exp(-alpha*(torch.abs(dx)**gamma)) * (dx)
|
42 |
+
|
43 |
+
|
44 |
+
@torch.jit.script
|
45 |
+
def inv_attractor(dx, alpha: float = 300, gamma: int = 2):
|
46 |
+
"""Inverse attractor: dc = dx / (1 + alpha*dx^gamma), where dx = a - c, a = attractor point, c = bin center, dc = shift in bin center
|
47 |
+
This is the default one according to the accompanying paper.
|
48 |
+
|
49 |
+
Args:
|
50 |
+
dx (torch.Tensor): The difference tensor dx = Ai - Cj, where Ai is the attractor point and Cj is the bin center.
|
51 |
+
alpha (float, optional): Proportional Attractor strength. Determines the absolute strength. Lower alpha = greater attraction. Defaults to 300.
|
52 |
+
gamma (int, optional): Exponential Attractor strength. Determines the "region of influence" and indirectly number of bin centers affected. Lower gamma = farther reach. Defaults to 2.
|
53 |
+
|
54 |
+
Returns:
|
55 |
+
torch.Tensor: Delta shifts - dc; New bin centers = Old bin centers + dc
|
56 |
+
"""
|
57 |
+
return dx.div(1+alpha*dx.pow(gamma))
|
58 |
+
|
59 |
+
|
60 |
+
class AttractorLayer(nn.Module):
|
61 |
+
def __init__(self, in_features, n_bins, n_attractors=16, mlp_dim=128, min_depth=1e-3, max_depth=10,
|
62 |
+
alpha=300, gamma=2, kind='sum', attractor_type='exp', memory_efficient=False):
|
63 |
+
"""
|
64 |
+
Attractor layer for bin centers. Bin centers are bounded on the interval (min_depth, max_depth)
|
65 |
+
"""
|
66 |
+
super().__init__()
|
67 |
+
|
68 |
+
self.n_attractors = n_attractors
|
69 |
+
self.n_bins = n_bins
|
70 |
+
self.min_depth = min_depth
|
71 |
+
self.max_depth = max_depth
|
72 |
+
self.alpha = alpha
|
73 |
+
self.gamma = gamma
|
74 |
+
self.kind = kind
|
75 |
+
self.attractor_type = attractor_type
|
76 |
+
self.memory_efficient = memory_efficient
|
77 |
+
|
78 |
+
self._net = nn.Sequential(
|
79 |
+
nn.Conv2d(in_features, mlp_dim, 1, 1, 0),
|
80 |
+
nn.ReLU(inplace=True),
|
81 |
+
nn.Conv2d(mlp_dim, n_attractors*2, 1, 1, 0), # x2 for linear norm
|
82 |
+
nn.ReLU(inplace=True)
|
83 |
+
)
|
84 |
+
|
85 |
+
def forward(self, x, b_prev, prev_b_embedding=None, interpolate=True, is_for_query=False):
|
86 |
+
"""
|
87 |
+
Args:
|
88 |
+
x (torch.Tensor) : feature block; shape - n, c, h, w
|
89 |
+
b_prev (torch.Tensor) : previous bin centers normed; shape - n, prev_nbins, h, w
|
90 |
+
|
91 |
+
Returns:
|
92 |
+
tuple(torch.Tensor,torch.Tensor) : new bin centers normed and scaled; shape - n, nbins, h, w
|
93 |
+
"""
|
94 |
+
if prev_b_embedding is not None:
|
95 |
+
if interpolate:
|
96 |
+
prev_b_embedding = nn.functional.interpolate(
|
97 |
+
prev_b_embedding, x.shape[-2:], mode='bilinear', align_corners=True)
|
98 |
+
x = x + prev_b_embedding
|
99 |
+
|
100 |
+
A = self._net(x)
|
101 |
+
eps = 1e-3
|
102 |
+
A = A + eps
|
103 |
+
n, c, h, w = A.shape
|
104 |
+
A = A.view(n, self.n_attractors, 2, h, w)
|
105 |
+
A_normed = A / A.sum(dim=2, keepdim=True) # n, a, 2, h, w
|
106 |
+
A_normed = A[:, :, 0, ...] # n, na, h, w
|
107 |
+
|
108 |
+
b_prev = nn.functional.interpolate(
|
109 |
+
b_prev, (h, w), mode='bilinear', align_corners=True)
|
110 |
+
b_centers = b_prev
|
111 |
+
|
112 |
+
if self.attractor_type == 'exp':
|
113 |
+
dist = exp_attractor
|
114 |
+
else:
|
115 |
+
dist = inv_attractor
|
116 |
+
|
117 |
+
if not self.memory_efficient:
|
118 |
+
func = {'mean': torch.mean, 'sum': torch.sum}[self.kind]
|
119 |
+
# .shape N, nbins, h, w
|
120 |
+
delta_c = func(dist(A_normed.unsqueeze(
|
121 |
+
2) - b_centers.unsqueeze(1)), dim=1)
|
122 |
+
else:
|
123 |
+
delta_c = torch.zeros_like(b_centers, device=b_centers.device)
|
124 |
+
for i in range(self.n_attractors):
|
125 |
+
# .shape N, nbins, h, w
|
126 |
+
delta_c += dist(A_normed[:, i, ...].unsqueeze(1) - b_centers)
|
127 |
+
|
128 |
+
if self.kind == 'mean':
|
129 |
+
delta_c = delta_c / self.n_attractors
|
130 |
+
|
131 |
+
b_new_centers = b_centers + delta_c
|
132 |
+
B_centers = (self.max_depth - self.min_depth) * \
|
133 |
+
b_new_centers + self.min_depth
|
134 |
+
B_centers, _ = torch.sort(B_centers, dim=1)
|
135 |
+
B_centers = torch.clip(B_centers, self.min_depth, self.max_depth)
|
136 |
+
return b_new_centers, B_centers
|
137 |
+
|
138 |
+
|
139 |
+
class AttractorLayerUnnormed(nn.Module):
|
140 |
+
def __init__(self, in_features, n_bins, n_attractors=16, mlp_dim=128, min_depth=1e-3, max_depth=10,
|
141 |
+
alpha=300, gamma=2, kind='sum', attractor_type='exp', memory_efficient=False):
|
142 |
+
"""
|
143 |
+
Attractor layer for bin centers. Bin centers are unbounded
|
144 |
+
"""
|
145 |
+
super().__init__()
|
146 |
+
|
147 |
+
self.n_attractors = n_attractors
|
148 |
+
self.n_bins = n_bins
|
149 |
+
self.min_depth = min_depth
|
150 |
+
self.max_depth = max_depth
|
151 |
+
self.alpha = alpha
|
152 |
+
self.gamma = gamma
|
153 |
+
self.kind = kind
|
154 |
+
self.attractor_type = attractor_type
|
155 |
+
self.memory_efficient = memory_efficient
|
156 |
+
|
157 |
+
self._net = nn.Sequential(
|
158 |
+
nn.Conv2d(in_features, mlp_dim, 1, 1, 0),
|
159 |
+
nn.ReLU(inplace=True),
|
160 |
+
nn.Conv2d(mlp_dim, n_attractors, 1, 1, 0),
|
161 |
+
nn.Softplus()
|
162 |
+
)
|
163 |
+
|
164 |
+
def forward(self, x, b_prev, prev_b_embedding=None, interpolate=True, is_for_query=False):
|
165 |
+
"""
|
166 |
+
Args:
|
167 |
+
x (torch.Tensor) : feature block; shape - n, c, h, w
|
168 |
+
b_prev (torch.Tensor) : previous bin centers normed; shape - n, prev_nbins, h, w
|
169 |
+
|
170 |
+
Returns:
|
171 |
+
tuple(torch.Tensor,torch.Tensor) : new bin centers unbounded; shape - n, nbins, h, w. Two outputs just to keep the API consistent with the normed version
|
172 |
+
"""
|
173 |
+
if prev_b_embedding is not None:
|
174 |
+
if interpolate:
|
175 |
+
prev_b_embedding = nn.functional.interpolate(
|
176 |
+
prev_b_embedding, x.shape[-2:], mode='bilinear', align_corners=True)
|
177 |
+
x = x + prev_b_embedding
|
178 |
+
|
179 |
+
A = self._net(x)
|
180 |
+
n, c, h, w = A.shape
|
181 |
+
|
182 |
+
b_prev = nn.functional.interpolate(
|
183 |
+
b_prev, (h, w), mode='bilinear', align_corners=True)
|
184 |
+
b_centers = b_prev
|
185 |
+
|
186 |
+
if self.attractor_type == 'exp':
|
187 |
+
dist = exp_attractor
|
188 |
+
else:
|
189 |
+
dist = inv_attractor
|
190 |
+
|
191 |
+
if not self.memory_efficient:
|
192 |
+
func = {'mean': torch.mean, 'sum': torch.sum}[self.kind]
|
193 |
+
# .shape N, nbins, h, w
|
194 |
+
delta_c = func(
|
195 |
+
dist(A.unsqueeze(2) - b_centers.unsqueeze(1)), dim=1)
|
196 |
+
else:
|
197 |
+
delta_c = torch.zeros_like(b_centers, device=b_centers.device)
|
198 |
+
for i in range(self.n_attractors):
|
199 |
+
delta_c += dist(A[:, i, ...].unsqueeze(1) -
|
200 |
+
b_centers) # .shape N, nbins, h, w
|
201 |
+
|
202 |
+
if self.kind == 'mean':
|
203 |
+
delta_c = delta_c / self.n_attractors
|
204 |
+
|
205 |
+
b_new_centers = b_centers + delta_c
|
206 |
+
B_centers = b_new_centers
|
207 |
+
|
208 |
+
return b_new_centers, B_centers
|
config.json
CHANGED
@@ -2,6 +2,10 @@
|
|
2 |
"architectures": [
|
3 |
"EVPDepth"
|
4 |
],
|
|
|
|
|
|
|
|
|
5 |
"dataset": "nyudepthv2",
|
6 |
"deconv_kernels": [
|
7 |
2,
|
|
|
2 |
"architectures": [
|
3 |
"EVPDepth"
|
4 |
],
|
5 |
+
"auto_map": {
|
6 |
+
"AutoConfig": "evpconfig.EVPConfig",
|
7 |
+
"AutoModel": "model.EVPDepth"
|
8 |
+
},
|
9 |
"dataset": "nyudepthv2",
|
10 |
"deconv_kernels": [
|
11 |
2,
|
dist_layers.py
ADDED
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# MIT License
|
2 |
+
|
3 |
+
# Copyright (c) 2022 Intelligent Systems Lab Org
|
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.
|
22 |
+
|
23 |
+
# File author: Shariq Farooq Bhat
|
24 |
+
|
25 |
+
import torch
|
26 |
+
import torch.nn as nn
|
27 |
+
|
28 |
+
|
29 |
+
def log_binom(n, k, eps=1e-7):
|
30 |
+
""" log(nCk) using stirling approximation """
|
31 |
+
n = n + eps
|
32 |
+
k = k + eps
|
33 |
+
return n * torch.log(n) - k * torch.log(k) - (n-k) * torch.log(n-k+eps)
|
34 |
+
|
35 |
+
|
36 |
+
class LogBinomial(nn.Module):
|
37 |
+
def __init__(self, n_classes=256, act=torch.softmax):
|
38 |
+
"""Compute log binomial distribution for n_classes
|
39 |
+
|
40 |
+
Args:
|
41 |
+
n_classes (int, optional): number of output classes. Defaults to 256.
|
42 |
+
"""
|
43 |
+
super().__init__()
|
44 |
+
self.K = n_classes
|
45 |
+
self.act = act
|
46 |
+
self.register_buffer('k_idx', torch.arange(
|
47 |
+
0, n_classes).view(1, -1, 1, 1))
|
48 |
+
self.register_buffer('K_minus_1', torch.Tensor(
|
49 |
+
[self.K-1]).view(1, -1, 1, 1))
|
50 |
+
|
51 |
+
def forward(self, x, t=1., eps=1e-4):
|
52 |
+
"""Compute log binomial distribution for x
|
53 |
+
|
54 |
+
Args:
|
55 |
+
x (torch.Tensor - NCHW): probabilities
|
56 |
+
t (float, torch.Tensor - NCHW, optional): Temperature of distribution. Defaults to 1..
|
57 |
+
eps (float, optional): Small number for numerical stability. Defaults to 1e-4.
|
58 |
+
|
59 |
+
Returns:
|
60 |
+
torch.Tensor -NCHW: log binomial distribution logbinomial(p;t)
|
61 |
+
"""
|
62 |
+
if x.ndim == 3:
|
63 |
+
x = x.unsqueeze(1) # make it nchw
|
64 |
+
|
65 |
+
one_minus_x = torch.clamp(1 - x, eps, 1)
|
66 |
+
x = torch.clamp(x, eps, 1)
|
67 |
+
y = log_binom(self.K_minus_1, self.k_idx) + self.k_idx * \
|
68 |
+
torch.log(x) + (self.K - 1 - self.k_idx) * torch.log(one_minus_x)
|
69 |
+
return self.act(y/t, dim=1)
|
70 |
+
|
71 |
+
|
72 |
+
class ConditionalLogBinomial(nn.Module):
|
73 |
+
def __init__(self, in_features, condition_dim, n_classes=256, bottleneck_factor=2, p_eps=1e-4, max_temp=50, min_temp=1e-7, act=torch.softmax):
|
74 |
+
"""Conditional Log Binomial distribution
|
75 |
+
|
76 |
+
Args:
|
77 |
+
in_features (int): number of input channels in main feature
|
78 |
+
condition_dim (int): number of input channels in condition feature
|
79 |
+
n_classes (int, optional): Number of classes. Defaults to 256.
|
80 |
+
bottleneck_factor (int, optional): Hidden dim factor. Defaults to 2.
|
81 |
+
p_eps (float, optional): small eps value. Defaults to 1e-4.
|
82 |
+
max_temp (float, optional): Maximum temperature of output distribution. Defaults to 50.
|
83 |
+
min_temp (float, optional): Minimum temperature of output distribution. Defaults to 1e-7.
|
84 |
+
"""
|
85 |
+
super().__init__()
|
86 |
+
self.p_eps = p_eps
|
87 |
+
self.max_temp = max_temp
|
88 |
+
self.min_temp = min_temp
|
89 |
+
self.log_binomial_transform = LogBinomial(n_classes, act=act)
|
90 |
+
bottleneck = (in_features + condition_dim) // bottleneck_factor
|
91 |
+
self.mlp = nn.Sequential(
|
92 |
+
nn.Conv2d(in_features + condition_dim, bottleneck,
|
93 |
+
kernel_size=1, stride=1, padding=0),
|
94 |
+
nn.GELU(),
|
95 |
+
# 2 for p linear norm, 2 for t linear norm
|
96 |
+
nn.Conv2d(bottleneck, 2+2, kernel_size=1, stride=1, padding=0),
|
97 |
+
nn.Softplus()
|
98 |
+
)
|
99 |
+
|
100 |
+
def forward(self, x, cond):
|
101 |
+
"""Forward pass
|
102 |
+
|
103 |
+
Args:
|
104 |
+
x (torch.Tensor - NCHW): Main feature
|
105 |
+
cond (torch.Tensor - NCHW): condition feature
|
106 |
+
|
107 |
+
Returns:
|
108 |
+
torch.Tensor: Output log binomial distribution
|
109 |
+
"""
|
110 |
+
pt = self.mlp(torch.concat((x, cond), dim=1))
|
111 |
+
p, t = pt[:, :2, ...], pt[:, 2:, ...]
|
112 |
+
|
113 |
+
p = p + self.p_eps
|
114 |
+
p = p[:, 0, ...] / (p[:, 0, ...] + p[:, 1, ...])
|
115 |
+
|
116 |
+
t = t + self.p_eps
|
117 |
+
t = t[:, 0, ...] / (t[:, 0, ...] + t[:, 1, ...])
|
118 |
+
t = t.unsqueeze(1)
|
119 |
+
t = (self.max_temp - self.min_temp) * t + self.min_temp
|
120 |
+
|
121 |
+
return self.log_binomial_transform(p, t)
|
evpconfig.py
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import PretrainedConfig
|
2 |
+
|
3 |
+
class EVPConfig(PretrainedConfig):
|
4 |
+
model_type = "EVP"
|
5 |
+
def __init__(
|
6 |
+
self,
|
7 |
+
**kwargs,
|
8 |
+
):
|
9 |
+
self.num_deconv = 3
|
10 |
+
self.num_filters = [32,32,32]
|
11 |
+
self.deconv_kernels = [2,2,2]
|
12 |
+
self.dataset = 'nyudepthv2'
|
13 |
+
self.max_depth = 10
|
14 |
+
self.min_depth_eval = 1e-3
|
15 |
+
super().__init__(**kwargs)
|
16 |
+
|
layers.py
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
|
4 |
+
|
5 |
+
class PatchTransformerEncoder(nn.Module):
|
6 |
+
def __init__(self, in_channels, patch_size=10, embedding_dim=128, num_heads=4):
|
7 |
+
super(PatchTransformerEncoder, self).__init__()
|
8 |
+
encoder_layers = nn.TransformerEncoderLayer(embedding_dim, num_heads, dim_feedforward=1024)
|
9 |
+
self.transformer_encoder = nn.TransformerEncoder(encoder_layers, num_layers=4) # takes shape S,N,E
|
10 |
+
|
11 |
+
self.embedding_convPxP = nn.Conv2d(in_channels, embedding_dim,
|
12 |
+
kernel_size=patch_size, stride=patch_size, padding=0)
|
13 |
+
|
14 |
+
self.positional_encodings = nn.Parameter(torch.rand(900, embedding_dim), requires_grad=True)
|
15 |
+
|
16 |
+
def forward(self, x):
|
17 |
+
embeddings = self.embedding_convPxP(x).flatten(2) # .shape = n,c,s = n, embedding_dim, s
|
18 |
+
# embeddings = nn.functional.pad(embeddings, (1,0)) # extra special token at start ?
|
19 |
+
embeddings = embeddings + self.positional_encodings[:embeddings.shape[2], :].T.unsqueeze(0)
|
20 |
+
|
21 |
+
# change to S,N,E format required by transformer
|
22 |
+
embeddings = embeddings.permute(2, 0, 1)
|
23 |
+
x = self.transformer_encoder(embeddings) # .shape = S, N, E
|
24 |
+
return x
|
25 |
+
|
26 |
+
|
27 |
+
class PixelWiseDotProduct(nn.Module):
|
28 |
+
def __init__(self):
|
29 |
+
super(PixelWiseDotProduct, self).__init__()
|
30 |
+
|
31 |
+
def forward(self, x, K):
|
32 |
+
n, c, h, w = x.size()
|
33 |
+
_, cout, ck = K.size()
|
34 |
+
assert c == ck, "Number of channels in x and Embedding dimension (at dim 2) of K matrix must match"
|
35 |
+
y = torch.matmul(x.view(n, c, h * w).permute(0, 2, 1), K.permute(0, 2, 1)) # .shape = n, hw, cout
|
36 |
+
return y.permute(0, 2, 1).view(n, cout, h, w)
|
localbins_layers.py
ADDED
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# MIT License
|
2 |
+
|
3 |
+
# Copyright (c) 2022 Intelligent Systems Lab Org
|
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.
|
22 |
+
|
23 |
+
# File author: Shariq Farooq Bhat
|
24 |
+
|
25 |
+
import torch
|
26 |
+
import torch.nn as nn
|
27 |
+
|
28 |
+
|
29 |
+
class SeedBinRegressor(nn.Module):
|
30 |
+
def __init__(self, in_features, n_bins=16, mlp_dim=256, min_depth=1e-3, max_depth=10):
|
31 |
+
"""Bin center regressor network. Bin centers are bounded on (min_depth, max_depth) interval.
|
32 |
+
|
33 |
+
Args:
|
34 |
+
in_features (int): input channels
|
35 |
+
n_bins (int, optional): Number of bin centers. Defaults to 16.
|
36 |
+
mlp_dim (int, optional): Hidden dimension. Defaults to 256.
|
37 |
+
min_depth (float, optional): Min depth value. Defaults to 1e-3.
|
38 |
+
max_depth (float, optional): Max depth value. Defaults to 10.
|
39 |
+
"""
|
40 |
+
super().__init__()
|
41 |
+
self.version = "1_1"
|
42 |
+
self.min_depth = min_depth
|
43 |
+
self.max_depth = max_depth
|
44 |
+
|
45 |
+
self._net = nn.Sequential(
|
46 |
+
nn.Conv2d(in_features, mlp_dim, 1, 1, 0),
|
47 |
+
nn.ReLU(inplace=True),
|
48 |
+
nn.Conv2d(mlp_dim, n_bins, 1, 1, 0),
|
49 |
+
nn.ReLU(inplace=True)
|
50 |
+
)
|
51 |
+
|
52 |
+
def forward(self, x):
|
53 |
+
"""
|
54 |
+
Returns tensor of bin_width vectors (centers). One vector b for every pixel
|
55 |
+
"""
|
56 |
+
B = self._net(x)
|
57 |
+
eps = 1e-3
|
58 |
+
B = B + eps
|
59 |
+
B_widths_normed = B / B.sum(dim=1, keepdim=True)
|
60 |
+
B_widths = (self.max_depth - self.min_depth) * \
|
61 |
+
B_widths_normed # .shape NCHW
|
62 |
+
# pad has the form (left, right, top, bottom, front, back)
|
63 |
+
B_widths = nn.functional.pad(
|
64 |
+
B_widths, (0, 0, 0, 0, 1, 0), mode='constant', value=self.min_depth)
|
65 |
+
B_edges = torch.cumsum(B_widths, dim=1) # .shape NCHW
|
66 |
+
|
67 |
+
B_centers = 0.5 * (B_edges[:, :-1, ...] + B_edges[:, 1:, ...])
|
68 |
+
return B_widths_normed, B_centers
|
69 |
+
|
70 |
+
|
71 |
+
class SeedBinRegressorUnnormed(nn.Module):
|
72 |
+
def __init__(self, in_features, n_bins=16, mlp_dim=256, min_depth=1e-3, max_depth=10):
|
73 |
+
"""Bin center regressor network. Bin centers are unbounded
|
74 |
+
|
75 |
+
Args:
|
76 |
+
in_features (int): input channels
|
77 |
+
n_bins (int, optional): Number of bin centers. Defaults to 16.
|
78 |
+
mlp_dim (int, optional): Hidden dimension. Defaults to 256.
|
79 |
+
min_depth (float, optional): Not used. (for compatibility with SeedBinRegressor)
|
80 |
+
max_depth (float, optional): Not used. (for compatibility with SeedBinRegressor)
|
81 |
+
"""
|
82 |
+
super().__init__()
|
83 |
+
self.version = "1_1"
|
84 |
+
self._net = nn.Sequential(
|
85 |
+
nn.Conv2d(in_features, mlp_dim, 1, 1, 0),
|
86 |
+
nn.ReLU(inplace=True),
|
87 |
+
nn.Conv2d(mlp_dim, n_bins, 1, 1, 0),
|
88 |
+
nn.Softplus()
|
89 |
+
)
|
90 |
+
|
91 |
+
def forward(self, x):
|
92 |
+
"""
|
93 |
+
Returns tensor of bin_width vectors (centers). One vector b for every pixel
|
94 |
+
"""
|
95 |
+
B_centers = self._net(x)
|
96 |
+
return B_centers, B_centers
|
97 |
+
|
98 |
+
|
99 |
+
class Projector(nn.Module):
|
100 |
+
def __init__(self, in_features, out_features, mlp_dim=128):
|
101 |
+
"""Projector MLP
|
102 |
+
|
103 |
+
Args:
|
104 |
+
in_features (int): input channels
|
105 |
+
out_features (int): output channels
|
106 |
+
mlp_dim (int, optional): hidden dimension. Defaults to 128.
|
107 |
+
"""
|
108 |
+
super().__init__()
|
109 |
+
|
110 |
+
self._net = nn.Sequential(
|
111 |
+
nn.Conv2d(in_features, mlp_dim, 1, 1, 0),
|
112 |
+
nn.ReLU(inplace=True),
|
113 |
+
nn.Conv2d(mlp_dim, out_features, 1, 1, 0),
|
114 |
+
)
|
115 |
+
|
116 |
+
def forward(self, x):
|
117 |
+
return self._net(x)
|
118 |
+
|
119 |
+
|
120 |
+
|
121 |
+
class LinearSplitter(nn.Module):
|
122 |
+
def __init__(self, in_features, prev_nbins, split_factor=2, mlp_dim=128, min_depth=1e-3, max_depth=10):
|
123 |
+
super().__init__()
|
124 |
+
|
125 |
+
self.prev_nbins = prev_nbins
|
126 |
+
self.split_factor = split_factor
|
127 |
+
self.min_depth = min_depth
|
128 |
+
self.max_depth = max_depth
|
129 |
+
|
130 |
+
self._net = nn.Sequential(
|
131 |
+
nn.Conv2d(in_features, mlp_dim, 1, 1, 0),
|
132 |
+
nn.GELU(),
|
133 |
+
nn.Conv2d(mlp_dim, prev_nbins * split_factor, 1, 1, 0),
|
134 |
+
nn.ReLU()
|
135 |
+
)
|
136 |
+
|
137 |
+
def forward(self, x, b_prev, prev_b_embedding=None, interpolate=True, is_for_query=False):
|
138 |
+
"""
|
139 |
+
x : feature block; shape - n, c, h, w
|
140 |
+
b_prev : previous bin widths normed; shape - n, prev_nbins, h, w
|
141 |
+
"""
|
142 |
+
if prev_b_embedding is not None:
|
143 |
+
if interpolate:
|
144 |
+
prev_b_embedding = nn.functional.interpolate(prev_b_embedding, x.shape[-2:], mode='bilinear', align_corners=True)
|
145 |
+
x = x + prev_b_embedding
|
146 |
+
S = self._net(x)
|
147 |
+
eps = 1e-3
|
148 |
+
S = S + eps
|
149 |
+
n, c, h, w = S.shape
|
150 |
+
S = S.view(n, self.prev_nbins, self.split_factor, h, w)
|
151 |
+
S_normed = S / S.sum(dim=2, keepdim=True) # fractional splits
|
152 |
+
|
153 |
+
b_prev = nn.functional.interpolate(b_prev, (h,w), mode='bilinear', align_corners=True)
|
154 |
+
|
155 |
+
|
156 |
+
b_prev = b_prev / b_prev.sum(dim=1, keepdim=True) # renormalize for gurantees
|
157 |
+
# print(b_prev.shape, S_normed.shape)
|
158 |
+
# if is_for_query:(1).expand(-1, b_prev.size(0)//n, -1, -1, -1, -1).flatten(0,1) # TODO ? can replace all this with a single torch.repeat?
|
159 |
+
b = b_prev.unsqueeze(2) * S_normed
|
160 |
+
b = b.flatten(1,2) # .shape n, prev_nbins * split_factor, h, w
|
161 |
+
|
162 |
+
# calculate bin centers for loss calculation
|
163 |
+
B_widths = (self.max_depth - self.min_depth) * b # .shape N, nprev * splitfactor, H, W
|
164 |
+
# pad has the form (left, right, top, bottom, front, back)
|
165 |
+
B_widths = nn.functional.pad(B_widths, (0,0,0,0,1,0), mode='constant', value=self.min_depth)
|
166 |
+
B_edges = torch.cumsum(B_widths, dim=1) # .shape NCHW
|
167 |
+
|
168 |
+
B_centers = 0.5 * (B_edges[:, :-1, ...] + B_edges[:,1:,...])
|
169 |
+
return b, B_centers
|
miniViT.py
ADDED
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
|
4 |
+
from .layers import PatchTransformerEncoder, PixelWiseDotProduct
|
5 |
+
|
6 |
+
|
7 |
+
class mViT(nn.Module):
|
8 |
+
def __init__(self, in_channels, n_query_channels=128, patch_size=16, dim_out=256,
|
9 |
+
embedding_dim=128, num_heads=4, norm='linear'):
|
10 |
+
super(mViT, self).__init__()
|
11 |
+
self.norm = norm
|
12 |
+
self.n_query_channels = n_query_channels
|
13 |
+
self.patch_transformer = PatchTransformerEncoder(in_channels, patch_size, embedding_dim, num_heads)
|
14 |
+
self.dot_product_layer = PixelWiseDotProduct()
|
15 |
+
|
16 |
+
self.conv3x3 = nn.Conv2d(in_channels, embedding_dim, kernel_size=3, stride=1, padding=1)
|
17 |
+
self.regressor = nn.Sequential(nn.Linear(embedding_dim, 256),
|
18 |
+
nn.LeakyReLU(),
|
19 |
+
nn.Linear(256, 256),
|
20 |
+
nn.LeakyReLU(),
|
21 |
+
nn.Linear(256, dim_out))
|
22 |
+
|
23 |
+
def forward(self, x):
|
24 |
+
# n, c, h, w = x.size()
|
25 |
+
tgt = self.patch_transformer(x.clone()) # .shape = S, N, E
|
26 |
+
|
27 |
+
x = self.conv3x3(x)
|
28 |
+
|
29 |
+
regression_head, queries = tgt[0, ...], tgt[1:self.n_query_channels + 1, ...]
|
30 |
+
|
31 |
+
# Change from S, N, E to N, S, E
|
32 |
+
queries = queries.permute(1, 0, 2)
|
33 |
+
range_attention_maps = self.dot_product_layer(x, queries) # .shape = n, n_query_channels, h, w
|
34 |
+
|
35 |
+
y = self.regressor(regression_head) # .shape = N, dim_out
|
36 |
+
if self.norm == 'linear':
|
37 |
+
y = torch.relu(y)
|
38 |
+
eps = 0.1
|
39 |
+
y = y + eps
|
40 |
+
elif self.norm == 'softmax':
|
41 |
+
return torch.softmax(y, dim=1), range_attention_maps
|
42 |
+
else:
|
43 |
+
y = torch.sigmoid(y)
|
44 |
+
y = y / y.sum(dim=1, keepdim=True)
|
45 |
+
return y, range_attention_maps
|
model.py
ADDED
@@ -0,0 +1,698 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# ------------------------------------------------------------------------------
|
2 |
+
# Copyright (c) Microsoft
|
3 |
+
# Licensed under the MIT License.
|
4 |
+
# The deconvolution code is based on Simple Baseline.
|
5 |
+
# (https://github.com/microsoft/human-pose-estimation.pytorch/blob/master/lib/models/pose_resnet.py)
|
6 |
+
# Modified by Zigang Geng ([email protected]).
|
7 |
+
# ------------------------------------------------------------------------------
|
8 |
+
|
9 |
+
import torch
|
10 |
+
import torch.nn as nn
|
11 |
+
from timm.models.layers import trunc_normal_, DropPath
|
12 |
+
from mmcv.cnn import (build_conv_layer, build_norm_layer, build_upsample_layer,
|
13 |
+
constant_init, normal_init)
|
14 |
+
from omegaconf import OmegaConf
|
15 |
+
from ldm.util import instantiate_from_config
|
16 |
+
import torch.nn.functional as F
|
17 |
+
import sys
|
18 |
+
import os
|
19 |
+
current_script_path = os.path.abspath(__file__)
|
20 |
+
parent_folder_path = os.path.dirname(os.path.dirname(current_script_path))
|
21 |
+
sys.path.append(parent_folder_path)
|
22 |
+
parent_folder_path = os.path.dirname(parent_folder_path)
|
23 |
+
print(parent_folder_path)
|
24 |
+
# Add the parent folder to sys.path
|
25 |
+
sys.path.append(parent_folder_path)
|
26 |
+
|
27 |
+
from evpconfig import EVPConfig
|
28 |
+
|
29 |
+
from evp.models import UNetWrapper, TextAdapterRefer, FrozenCLIPEmbedder
|
30 |
+
from .miniViT import mViT
|
31 |
+
from .attractor import AttractorLayer, AttractorLayerUnnormed
|
32 |
+
from .dist_layers import ConditionalLogBinomial
|
33 |
+
from .localbins_layers import (Projector, SeedBinRegressor, SeedBinRegressorUnnormed)
|
34 |
+
import os
|
35 |
+
from transformers import PreTrainedModel
|
36 |
+
import sys
|
37 |
+
current_script_path = os.path.abspath(__file__)
|
38 |
+
parent_folder_path = os.path.dirname(os.path.dirname(current_script_path))
|
39 |
+
import torchvision.transforms as transforms
|
40 |
+
|
41 |
+
# Add the parent folder to sys.path
|
42 |
+
sys.path.append(parent_folder_path)
|
43 |
+
|
44 |
+
def icnr(x, scale=2, init=nn.init.kaiming_normal_):
|
45 |
+
"""
|
46 |
+
Checkerboard artifact free sub-pixel convolution
|
47 |
+
https://arxiv.org/abs/1707.02937
|
48 |
+
"""
|
49 |
+
ni,nf,h,w = x.shape
|
50 |
+
ni2 = int(ni/(scale**2))
|
51 |
+
k = init(torch.zeros([ni2,nf,h,w])).transpose(0, 1)
|
52 |
+
k = k.contiguous().view(ni2, nf, -1)
|
53 |
+
k = k.repeat(1, 1, scale**2)
|
54 |
+
k = k.contiguous().view([nf,ni,h,w]).transpose(0, 1)
|
55 |
+
x.data.copy_(k)
|
56 |
+
|
57 |
+
|
58 |
+
class PixelShuffle(nn.Module):
|
59 |
+
"""
|
60 |
+
Real-Time Single Image and Video Super-Resolution
|
61 |
+
https://arxiv.org/abs/1609.05158
|
62 |
+
"""
|
63 |
+
def __init__(self, n_channels, scale):
|
64 |
+
super(PixelShuffle, self).__init__()
|
65 |
+
self.conv = nn.Conv2d(n_channels, n_channels*(scale**2), kernel_size=1)
|
66 |
+
icnr(self.conv.weight)
|
67 |
+
self.shuf = nn.PixelShuffle(scale)
|
68 |
+
self.relu = nn.ReLU()
|
69 |
+
|
70 |
+
def forward(self,x):
|
71 |
+
x = self.shuf(self.relu(self.conv(x)))
|
72 |
+
return x
|
73 |
+
|
74 |
+
|
75 |
+
class AttentionModule(nn.Module):
|
76 |
+
def __init__(self, in_channels, out_channels):
|
77 |
+
super(AttentionModule, self).__init__()
|
78 |
+
|
79 |
+
# Convolutional Layers
|
80 |
+
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
|
81 |
+
|
82 |
+
# Group Normalization
|
83 |
+
self.group_norm = nn.GroupNorm(20, out_channels)
|
84 |
+
|
85 |
+
# ReLU Activation
|
86 |
+
self.relu = nn.ReLU()
|
87 |
+
|
88 |
+
# Spatial Attention
|
89 |
+
self.spatial_attention = nn.Sequential(
|
90 |
+
nn.Conv2d(in_channels, 1, kernel_size=1),
|
91 |
+
nn.Sigmoid()
|
92 |
+
)
|
93 |
+
|
94 |
+
def forward(self, x):
|
95 |
+
# Apply spatial attention
|
96 |
+
spatial_attention = self.spatial_attention(x)
|
97 |
+
x = x * spatial_attention
|
98 |
+
|
99 |
+
# Apply convolutional layer
|
100 |
+
x = self.conv1(x)
|
101 |
+
x = self.group_norm(x)
|
102 |
+
x = self.relu(x)
|
103 |
+
|
104 |
+
return x
|
105 |
+
|
106 |
+
|
107 |
+
class AttentionDownsamplingModule(nn.Module):
|
108 |
+
def __init__(self, in_channels, out_channels, scale_factor=2):
|
109 |
+
super(AttentionDownsamplingModule, self).__init__()
|
110 |
+
|
111 |
+
# Spatial Attention
|
112 |
+
self.spatial_attention = nn.Sequential(
|
113 |
+
nn.Conv2d(in_channels, 1, kernel_size=1),
|
114 |
+
nn.Sigmoid()
|
115 |
+
)
|
116 |
+
|
117 |
+
# Channel Attention
|
118 |
+
self.channel_attention = nn.Sequential(
|
119 |
+
nn.AdaptiveAvgPool2d(1),
|
120 |
+
nn.Conv2d(in_channels, in_channels // 8, kernel_size=1),
|
121 |
+
nn.ReLU(inplace=True),
|
122 |
+
nn.Conv2d(in_channels // 8, in_channels, kernel_size=1),
|
123 |
+
nn.Sigmoid()
|
124 |
+
)
|
125 |
+
|
126 |
+
# Convolutional Layers
|
127 |
+
if scale_factor == 2:
|
128 |
+
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
|
129 |
+
elif scale_factor == 4:
|
130 |
+
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=2, padding=1)
|
131 |
+
|
132 |
+
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=2, padding=1)
|
133 |
+
|
134 |
+
# Group Normalization
|
135 |
+
self.group_norm = nn.GroupNorm(20, out_channels)
|
136 |
+
|
137 |
+
# ReLU Activation
|
138 |
+
self.relu = nn.ReLU(inplace=True)
|
139 |
+
|
140 |
+
def forward(self, x):
|
141 |
+
# Apply spatial attention
|
142 |
+
spatial_attention = self.spatial_attention(x)
|
143 |
+
x = x * spatial_attention
|
144 |
+
|
145 |
+
# Apply channel attention
|
146 |
+
channel_attention = self.channel_attention(x)
|
147 |
+
x = x * channel_attention
|
148 |
+
|
149 |
+
# Apply convolutional layers
|
150 |
+
x = self.conv1(x)
|
151 |
+
x = self.group_norm(x)
|
152 |
+
x = self.relu(x)
|
153 |
+
x = self.conv2(x)
|
154 |
+
x = self.group_norm(x)
|
155 |
+
x = self.relu(x)
|
156 |
+
|
157 |
+
return x
|
158 |
+
|
159 |
+
|
160 |
+
class AttentionUpsamplingModule(nn.Module):
|
161 |
+
def __init__(self, in_channels, out_channels):
|
162 |
+
super(AttentionUpsamplingModule, self).__init__()
|
163 |
+
|
164 |
+
# Spatial Attention for outs[2]
|
165 |
+
self.spatial_attention = nn.Sequential(
|
166 |
+
nn.Conv2d(in_channels, 1, kernel_size=1),
|
167 |
+
nn.Sigmoid()
|
168 |
+
)
|
169 |
+
|
170 |
+
# Channel Attention for outs[2]
|
171 |
+
self.channel_attention = nn.Sequential(
|
172 |
+
nn.AdaptiveAvgPool2d(1),
|
173 |
+
nn.Conv2d(in_channels, in_channels // 8, kernel_size=1),
|
174 |
+
nn.ReLU(),
|
175 |
+
nn.Conv2d(in_channels // 8, in_channels, kernel_size=1),
|
176 |
+
nn.Sigmoid()
|
177 |
+
)
|
178 |
+
|
179 |
+
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
|
180 |
+
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
|
181 |
+
|
182 |
+
# Group Normalization
|
183 |
+
self.group_norm = nn.GroupNorm(20, out_channels)
|
184 |
+
|
185 |
+
# ReLU Activation
|
186 |
+
self.relu = nn.ReLU()
|
187 |
+
self.upscale = PixelShuffle(in_channels, 2)
|
188 |
+
|
189 |
+
def forward(self, x):
|
190 |
+
# Apply spatial attention
|
191 |
+
spatial_attention = self.spatial_attention(x)
|
192 |
+
x = x * spatial_attention
|
193 |
+
|
194 |
+
# Apply channel attention
|
195 |
+
channel_attention = self.channel_attention(x)
|
196 |
+
x = x * channel_attention
|
197 |
+
|
198 |
+
# Apply convolutional layers
|
199 |
+
x = self.conv1(x)
|
200 |
+
x = self.group_norm(x)
|
201 |
+
x = self.relu(x)
|
202 |
+
x = self.conv2(x)
|
203 |
+
x = self.group_norm(x)
|
204 |
+
x = self.relu(x)
|
205 |
+
|
206 |
+
# Upsample
|
207 |
+
x = self.upscale(x)
|
208 |
+
|
209 |
+
return x
|
210 |
+
|
211 |
+
|
212 |
+
class ConvLayer(nn.Module):
|
213 |
+
def __init__(self, in_channels, out_channels):
|
214 |
+
super(ConvLayer, self).__init__()
|
215 |
+
|
216 |
+
self.conv1 = nn.Sequential(
|
217 |
+
nn.Conv2d(in_channels, out_channels, 1),
|
218 |
+
nn.GroupNorm(20, out_channels),
|
219 |
+
nn.ReLU(),
|
220 |
+
)
|
221 |
+
|
222 |
+
def forward(self, x):
|
223 |
+
x = self.conv1(x)
|
224 |
+
|
225 |
+
return x
|
226 |
+
|
227 |
+
|
228 |
+
class InverseMultiAttentiveFeatureRefinement(nn.Module):
|
229 |
+
def __init__(self, in_channels_list):
|
230 |
+
super(InverseMultiAttentiveFeatureRefinement, self).__init__()
|
231 |
+
|
232 |
+
self.layer1 = AttentionModule(in_channels_list[0], in_channels_list[0])
|
233 |
+
self.layer2 = AttentionDownsamplingModule(in_channels_list[0], in_channels_list[0]//2, scale_factor = 2)
|
234 |
+
self.layer3 = ConvLayer(in_channels_list[0]//2 + in_channels_list[1], in_channels_list[1])
|
235 |
+
self.layer4 = AttentionDownsamplingModule(in_channels_list[1], in_channels_list[1]//2, scale_factor = 2)
|
236 |
+
self.layer5 = ConvLayer(in_channels_list[1]//2 + in_channels_list[2], in_channels_list[2])
|
237 |
+
self.layer6 = AttentionDownsamplingModule(in_channels_list[2], in_channels_list[2]//2, scale_factor = 2)
|
238 |
+
self.layer7 = ConvLayer(in_channels_list[2]//2 + in_channels_list[3], in_channels_list[3])
|
239 |
+
|
240 |
+
'''
|
241 |
+
self.layer8 = AttentionUpsamplingModule(in_channels_list[3], in_channels_list[3])
|
242 |
+
self.layer9 = ConvLayer(in_channels_list[2] + in_channels_list[3], in_channels_list[2])
|
243 |
+
self.layer10 = AttentionUpsamplingModule(in_channels_list[2], in_channels_list[2])
|
244 |
+
self.layer11 = ConvLayer(in_channels_list[1] + in_channels_list[2], in_channels_list[1])
|
245 |
+
self.layer12 = AttentionUpsamplingModule(in_channels_list[1], in_channels_list[1])
|
246 |
+
self.layer13 = ConvLayer(in_channels_list[0] + in_channels_list[1], in_channels_list[0])
|
247 |
+
'''
|
248 |
+
def forward(self, inputs):
|
249 |
+
x_c4, x_c3, x_c2, x_c1 = inputs
|
250 |
+
x_c4 = self.layer1(x_c4)
|
251 |
+
x_c4_3 = self.layer2(x_c4)
|
252 |
+
x_c3 = torch.cat([x_c4_3, x_c3], dim=1)
|
253 |
+
x_c3 = self.layer3(x_c3)
|
254 |
+
x_c3_2 = self.layer4(x_c3)
|
255 |
+
x_c2 = torch.cat([x_c3_2, x_c2], dim=1)
|
256 |
+
x_c2 = self.layer5(x_c2)
|
257 |
+
x_c2_1 = self.layer6(x_c2)
|
258 |
+
x_c1 = torch.cat([x_c2_1, x_c1], dim=1)
|
259 |
+
x_c1 = self.layer7(x_c1)
|
260 |
+
'''
|
261 |
+
x_c1_2 = self.layer8(x_c1)
|
262 |
+
x_c2 = torch.cat([x_c1_2, x_c2], dim=1)
|
263 |
+
x_c2 = self.layer9(x_c2)
|
264 |
+
x_c2_3 = self.layer10(x_c2)
|
265 |
+
x_c3 = torch.cat([x_c2_3, x_c3], dim=1)
|
266 |
+
x_c3 = self.layer11(x_c3)
|
267 |
+
x_c3_4 = self.layer12(x_c3)
|
268 |
+
x_c4 = torch.cat([x_c3_4, x_c4], dim=1)
|
269 |
+
x_c4 = self.layer13(x_c4)
|
270 |
+
'''
|
271 |
+
return [x_c4, x_c3, x_c2, x_c1]
|
272 |
+
|
273 |
+
|
274 |
+
class EVPDepthEncoder(nn.Module):
|
275 |
+
def __init__(self, out_dim=1024, ldm_prior=[320, 680, 1320+1280], sd_path=None, text_dim=768,
|
276 |
+
dataset='nyu', caption_aggregation=False
|
277 |
+
):
|
278 |
+
super().__init__()
|
279 |
+
|
280 |
+
|
281 |
+
self.layer1 = nn.Sequential(
|
282 |
+
nn.Conv2d(ldm_prior[0], ldm_prior[0], 3, stride=2, padding=1),
|
283 |
+
nn.GroupNorm(16, ldm_prior[0]),
|
284 |
+
nn.ReLU(),
|
285 |
+
nn.Conv2d(ldm_prior[0], ldm_prior[0], 3, stride=2, padding=1),
|
286 |
+
)
|
287 |
+
|
288 |
+
self.layer2 = nn.Sequential(
|
289 |
+
nn.Conv2d(ldm_prior[1], ldm_prior[1], 3, stride=2, padding=1),
|
290 |
+
)
|
291 |
+
|
292 |
+
self.out_layer = nn.Sequential(
|
293 |
+
nn.Conv2d(sum(ldm_prior), out_dim, 1),
|
294 |
+
nn.GroupNorm(16, out_dim),
|
295 |
+
nn.ReLU(),
|
296 |
+
)
|
297 |
+
|
298 |
+
self.aggregation = InverseMultiAttentiveFeatureRefinement([320, 680, 1320, 1280])
|
299 |
+
|
300 |
+
self.apply(self._init_weights)
|
301 |
+
|
302 |
+
### stable diffusion layers
|
303 |
+
|
304 |
+
config = OmegaConf.load('./v1-inference.yaml')
|
305 |
+
if sd_path is None:
|
306 |
+
if os.path.exists('../checkpoints/v1-5-pruned-emaonly.ckpt'):
|
307 |
+
config.model.params.ckpt_path = '../checkpoints/v1-5-pruned-emaonly.ckpt'
|
308 |
+
else:
|
309 |
+
config.model.params.ckpt_path = None
|
310 |
+
else:
|
311 |
+
config.model.params.ckpt_path = f'../{sd_path}'
|
312 |
+
|
313 |
+
sd_model = instantiate_from_config(config.model)
|
314 |
+
self.encoder_vq = sd_model.first_stage_model
|
315 |
+
|
316 |
+
self.unet = UNetWrapper(sd_model.model, use_attn=True)
|
317 |
+
if dataset == 'kitti':
|
318 |
+
self.unet = UNetWrapper(sd_model.model, use_attn=True, base_size=384)
|
319 |
+
|
320 |
+
del sd_model.cond_stage_model
|
321 |
+
del self.encoder_vq.decoder
|
322 |
+
del self.unet.unet.diffusion_model.out
|
323 |
+
del self.encoder_vq.post_quant_conv.weight
|
324 |
+
del self.encoder_vq.post_quant_conv.bias
|
325 |
+
|
326 |
+
for param in self.encoder_vq.parameters():
|
327 |
+
param.requires_grad = True
|
328 |
+
|
329 |
+
self.text_adapter = TextAdapterRefer(text_dim=text_dim)
|
330 |
+
self.gamma = nn.Parameter(torch.ones(text_dim) * 1e-4)
|
331 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
332 |
+
|
333 |
+
if caption_aggregation:
|
334 |
+
class_embeddings = torch.load(f'{dataset}_class_embeddings_my_captions.pth', map_location=device)
|
335 |
+
#class_embeddings_list = [value['class_embeddings'] for key, value in class_embeddings.items()]
|
336 |
+
#stacked_embeddings = torch.stack(class_embeddings_list, dim=0)
|
337 |
+
#class_embeddings = torch.mean(stacked_embeddings, dim=0).unsqueeze(0)
|
338 |
+
|
339 |
+
if 'aggregated' in class_embeddings:
|
340 |
+
class_embeddings = class_embeddings['aggregated']
|
341 |
+
else:
|
342 |
+
clip_model = FrozenCLIPEmbedder(max_length=40,pool=False).to(device)
|
343 |
+
class_embeddings_new = [clip_model.encode(value['caption'][0]) for key, value in class_embeddings.items()]
|
344 |
+
class_embeddings_new = torch.mean(torch.stack(class_embeddings_new, dim=0), dim=0)
|
345 |
+
class_embeddings['aggregated'] = class_embeddings_new
|
346 |
+
torch.save(class_embeddings, f'{dataset}_class_embeddings_my_captions.pth')
|
347 |
+
class_embeddings = class_embeddings['aggregated']
|
348 |
+
self.register_buffer('class_embeddings', class_embeddings)
|
349 |
+
else:
|
350 |
+
self.class_embeddings = torch.load(f'{dataset}_class_embeddings_my_captions.pth', map_location=device)
|
351 |
+
|
352 |
+
self.clip_model = FrozenCLIPEmbedder(max_length=40,pool=False)
|
353 |
+
for param in self.clip_model.parameters():
|
354 |
+
param.requires_grad = True
|
355 |
+
|
356 |
+
#if dataset == 'kitti':
|
357 |
+
# self.text_adapter_ = TextAdapterRefer(text_dim=text_dim)
|
358 |
+
# self.gamma_ = nn.Parameter(torch.ones(text_dim) * 1e-4)
|
359 |
+
|
360 |
+
self.caption_aggregation = caption_aggregation
|
361 |
+
self.dataset = dataset
|
362 |
+
|
363 |
+
def _init_weights(self, m):
|
364 |
+
if isinstance(m, (nn.Conv2d, nn.Linear)):
|
365 |
+
trunc_normal_(m.weight, std=.02)
|
366 |
+
nn.init.constant_(m.bias, 0)
|
367 |
+
|
368 |
+
def forward_features(self, feats):
|
369 |
+
x = self.ldm_to_net[0](feats[0])
|
370 |
+
for i in range(3):
|
371 |
+
if i > 0:
|
372 |
+
x = x + self.ldm_to_net[i](feats[i])
|
373 |
+
x = self.layers[i](x)
|
374 |
+
x = self.upsample_layers[i](x)
|
375 |
+
return self.out_conv(x)
|
376 |
+
|
377 |
+
def forward(self, x, class_ids=None, img_paths=None):
|
378 |
+
latents = self.encoder_vq.encode(x).mode()
|
379 |
+
|
380 |
+
# add division by std
|
381 |
+
if self.dataset == 'nyu':
|
382 |
+
latents = latents / 5.07543
|
383 |
+
elif self.dataset == 'kitti':
|
384 |
+
latents = latents / 4.6211
|
385 |
+
else:
|
386 |
+
print('Please calculate the STD for the dataset!')
|
387 |
+
|
388 |
+
if class_ids is not None:
|
389 |
+
if self.caption_aggregation:
|
390 |
+
class_embeddings = self.class_embeddings[[0]*len(class_ids.tolist())]#[class_ids.tolist()]
|
391 |
+
else:
|
392 |
+
class_embeddings = []
|
393 |
+
|
394 |
+
for img_path in img_paths:
|
395 |
+
class_embeddings.extend([value['caption'][0] for key, value in self.class_embeddings.items() if key in img_path.replace('//', '/')])
|
396 |
+
|
397 |
+
class_embeddings = self.clip_model.encode(class_embeddings)
|
398 |
+
else:
|
399 |
+
class_embeddings = self.class_embeddings
|
400 |
+
|
401 |
+
c_crossattn = self.text_adapter(latents, class_embeddings, self.gamma)
|
402 |
+
t = torch.ones((x.shape[0],), device=x.device).long()
|
403 |
+
|
404 |
+
#if self.dataset == 'kitti':
|
405 |
+
# c_crossattn_last = self.text_adapter_(latents, class_embeddings, self.gamma_)
|
406 |
+
# outs = self.unet(latents, t, c_crossattn=[c_crossattn, c_crossattn_last])
|
407 |
+
#else:
|
408 |
+
outs = self.unet(latents, t, c_crossattn=[c_crossattn])
|
409 |
+
outs = self.aggregation(outs)
|
410 |
+
|
411 |
+
feats = [outs[0], outs[1], torch.cat([outs[2], F.interpolate(outs[3], scale_factor=2)], dim=1)]
|
412 |
+
x = torch.cat([self.layer1(feats[0]), self.layer2(feats[1]), feats[2]], dim=1)
|
413 |
+
return self.out_layer(x)
|
414 |
+
|
415 |
+
def get_latent(self, x):
|
416 |
+
return self.encoder_vq.encode(x).mode()
|
417 |
+
|
418 |
+
|
419 |
+
class EVPDepth(PreTrainedModel):
|
420 |
+
config_class = EVPConfig
|
421 |
+
def __init__(self, config, caption_aggregation=True):
|
422 |
+
super().__init__(config)
|
423 |
+
args = config
|
424 |
+
self.max_depth = args.max_depth
|
425 |
+
self.min_depth = args.min_depth_eval
|
426 |
+
|
427 |
+
embed_dim = 192
|
428 |
+
|
429 |
+
channels_in = embed_dim*8
|
430 |
+
channels_out = embed_dim
|
431 |
+
|
432 |
+
if args.dataset == 'nyudepthv2':
|
433 |
+
self.encoder = EVPDepthEncoder(out_dim=channels_in, dataset='nyu', caption_aggregation=caption_aggregation)
|
434 |
+
else:
|
435 |
+
self.encoder = EVPDepthEncoder(out_dim=channels_in, dataset='kitti', caption_aggregation=caption_aggregation)
|
436 |
+
|
437 |
+
self.decoder = Decoder(channels_in, channels_out, args)
|
438 |
+
self.decoder.init_weights()
|
439 |
+
self.mViT = False
|
440 |
+
self.custom = False
|
441 |
+
|
442 |
+
|
443 |
+
if not self.mViT and not self.custom:
|
444 |
+
n_bins = 64
|
445 |
+
bin_embedding_dim = 128
|
446 |
+
num_out_features = [32, 32, 32, 192]
|
447 |
+
min_temp = 0.0212
|
448 |
+
max_temp = 50
|
449 |
+
btlnck_features = 256
|
450 |
+
n_attractors = [16, 8, 4, 1]
|
451 |
+
attractor_alpha = 1000
|
452 |
+
attractor_gamma = 2
|
453 |
+
attractor_kind = "mean"
|
454 |
+
attractor_type = "inv"
|
455 |
+
self.bin_centers_type = "softplus"
|
456 |
+
|
457 |
+
self.bottle_neck = nn.Sequential(
|
458 |
+
nn.Conv2d(channels_in, btlnck_features, kernel_size=3, stride=1, padding=1),
|
459 |
+
nn.ReLU(inplace=False),
|
460 |
+
nn.Conv2d(btlnck_features, btlnck_features, kernel_size=3, stride=1, padding=1))
|
461 |
+
|
462 |
+
|
463 |
+
for m in self.bottle_neck.modules():
|
464 |
+
if isinstance(m, nn.Conv2d):
|
465 |
+
normal_init(m, std=0.001, bias=0)
|
466 |
+
|
467 |
+
|
468 |
+
SeedBinRegressorLayer = SeedBinRegressorUnnormed
|
469 |
+
Attractor = AttractorLayerUnnormed
|
470 |
+
self.seed_bin_regressor = SeedBinRegressorLayer(
|
471 |
+
btlnck_features, n_bins=n_bins, min_depth=self.min_depth, max_depth=self.max_depth)
|
472 |
+
self.seed_projector = Projector(btlnck_features, bin_embedding_dim)
|
473 |
+
self.projectors = nn.ModuleList([
|
474 |
+
Projector(num_out, bin_embedding_dim)
|
475 |
+
for num_out in num_out_features
|
476 |
+
])
|
477 |
+
self.attractors = nn.ModuleList([
|
478 |
+
Attractor(bin_embedding_dim, n_bins, n_attractors=n_attractors[i], min_depth=self.min_depth, max_depth=self.max_depth,
|
479 |
+
alpha=attractor_alpha, gamma=attractor_gamma, kind=attractor_kind, attractor_type=attractor_type)
|
480 |
+
for i in range(len(num_out_features))
|
481 |
+
])
|
482 |
+
|
483 |
+
last_in = 192 + 1
|
484 |
+
self.conditional_log_binomial = ConditionalLogBinomial(
|
485 |
+
last_in, bin_embedding_dim, n_classes=n_bins, min_temp=min_temp, max_temp=max_temp)
|
486 |
+
elif self.mViT and not self.custom:
|
487 |
+
n_bins = 256
|
488 |
+
self.adaptive_bins_layer = mViT(192, n_query_channels=192, patch_size=16,
|
489 |
+
dim_out=n_bins,
|
490 |
+
embedding_dim=192, norm='linear')
|
491 |
+
self.conv_out = nn.Sequential(nn.Conv2d(192, n_bins, kernel_size=1, stride=1, padding=0),
|
492 |
+
nn.Softmax(dim=1))
|
493 |
+
|
494 |
+
|
495 |
+
def forward(self, image, class_ids=None, img_paths=None):
|
496 |
+
|
497 |
+
#image = transform(image).unsqueeze(0)
|
498 |
+
shape = image.shape
|
499 |
+
image = torch.nn.functional.interpolate(image, (440,480), mode='bilinear', align_corners=True)
|
500 |
+
x = F.pad(image, (0, 0, 40, 0))
|
501 |
+
|
502 |
+
b, c, h, w = x.shape
|
503 |
+
x = x*2.0 - 1.0 # normalize to [-1, 1]
|
504 |
+
if h == 480 and w == 480:
|
505 |
+
new_x = torch.zeros(b, c, 512, 512, device=x.device)
|
506 |
+
new_x[:, :, 0:480, 0:480] = x
|
507 |
+
x = new_x
|
508 |
+
elif h==352 and w==352:
|
509 |
+
new_x = torch.zeros(b, c, 384, 384, device=x.device)
|
510 |
+
new_x[:, :, 0:352, 0:352] = x
|
511 |
+
x = new_x
|
512 |
+
elif h == 512 and w == 512:
|
513 |
+
pass
|
514 |
+
else:
|
515 |
+
print(h,w)
|
516 |
+
raise NotImplementedError
|
517 |
+
conv_feats = self.encoder(x, class_ids, img_paths)
|
518 |
+
|
519 |
+
if h == 480 or h == 352:
|
520 |
+
conv_feats = conv_feats[:, :, :-1, :-1]
|
521 |
+
|
522 |
+
self.decoder.remove_hooks()
|
523 |
+
out_depth, out, x_blocks = self.decoder([conv_feats])
|
524 |
+
|
525 |
+
if not self.mViT and not self.custom:
|
526 |
+
x = self.bottle_neck(conv_feats)
|
527 |
+
_, seed_b_centers = self.seed_bin_regressor(x)
|
528 |
+
|
529 |
+
if self.bin_centers_type == 'normed' or self.bin_centers_type == 'hybrid2':
|
530 |
+
b_prev = (seed_b_centers - self.min_depth) / \
|
531 |
+
(self.max_depth - self.min_depth)
|
532 |
+
else:
|
533 |
+
b_prev = seed_b_centers
|
534 |
+
|
535 |
+
prev_b_embedding = self.seed_projector(x)
|
536 |
+
|
537 |
+
for projector, attractor, x in zip(self.projectors, self.attractors, x_blocks):
|
538 |
+
b_embedding = projector(x)
|
539 |
+
b, b_centers = attractor(
|
540 |
+
b_embedding, b_prev, prev_b_embedding, interpolate=True)
|
541 |
+
b_prev = b.clone()
|
542 |
+
prev_b_embedding = b_embedding.clone()
|
543 |
+
|
544 |
+
rel_cond = torch.sigmoid(out_depth) * self.max_depth
|
545 |
+
|
546 |
+
# concat rel depth with last. First interpolate rel depth to last size
|
547 |
+
rel_cond = nn.functional.interpolate(
|
548 |
+
rel_cond, size=out.shape[2:], mode='bilinear', align_corners=True)
|
549 |
+
last = torch.cat([out, rel_cond], dim=1)
|
550 |
+
|
551 |
+
b_embedding = nn.functional.interpolate(
|
552 |
+
b_embedding, last.shape[-2:], mode='bilinear', align_corners=True)
|
553 |
+
x = self.conditional_log_binomial(last, b_embedding)
|
554 |
+
|
555 |
+
# Now depth value is Sum px * cx , where cx are bin_centers from the last bin tensor
|
556 |
+
b_centers = nn.functional.interpolate(
|
557 |
+
b_centers, x.shape[-2:], mode='bilinear', align_corners=True)
|
558 |
+
out_depth = torch.sum(x * b_centers, dim=1, keepdim=True)
|
559 |
+
|
560 |
+
elif self.mViT and not self.custom:
|
561 |
+
bin_widths_normed, range_attention_maps = self.adaptive_bins_layer(out)
|
562 |
+
out = self.conv_out(range_attention_maps)
|
563 |
+
|
564 |
+
bin_widths = (self.max_depth - self.min_depth) * bin_widths_normed # .shape = N, dim_out
|
565 |
+
bin_widths = nn.functional.pad(bin_widths, (1, 0), mode='constant', value=self.min_depth)
|
566 |
+
bin_edges = torch.cumsum(bin_widths, dim=1)
|
567 |
+
|
568 |
+
centers = 0.5 * (bin_edges[:, :-1] + bin_edges[:, 1:])
|
569 |
+
n, dout = centers.size()
|
570 |
+
centers = centers.view(n, dout, 1, 1)
|
571 |
+
|
572 |
+
out_depth = torch.sum(out * centers, dim=1, keepdim=True)
|
573 |
+
else:
|
574 |
+
out_depth = torch.sigmoid(out_depth) * self.max_depth
|
575 |
+
|
576 |
+
pred = out_depth
|
577 |
+
pred = pred[:,:,40:,:]
|
578 |
+
pred = torch.nn.functional.interpolate(pred, shape[2:], mode='bilinear', align_corners=True)
|
579 |
+
pred_d_numpy = pred.squeeze().detach().cpu().numpy()
|
580 |
+
|
581 |
+
return pred_d_numpy
|
582 |
+
|
583 |
+
|
584 |
+
class Decoder(nn.Module):
|
585 |
+
def __init__(self, in_channels, out_channels, args):
|
586 |
+
super().__init__()
|
587 |
+
self.deconv = args.num_deconv
|
588 |
+
self.in_channels = in_channels
|
589 |
+
|
590 |
+
embed_dim = 192
|
591 |
+
|
592 |
+
channels_in = embed_dim*8
|
593 |
+
channels_out = embed_dim
|
594 |
+
|
595 |
+
self.deconv_layers, self.intermediate_results = self._make_deconv_layer(
|
596 |
+
args.num_deconv,
|
597 |
+
args.num_filters,
|
598 |
+
args.deconv_kernels,
|
599 |
+
)
|
600 |
+
self.last_layer_depth = nn.Sequential(
|
601 |
+
nn.Conv2d(channels_out, channels_out, kernel_size=3, stride=1, padding=1),
|
602 |
+
nn.ReLU(inplace=False),
|
603 |
+
nn.Conv2d(channels_out, 1, kernel_size=3, stride=1, padding=1))
|
604 |
+
|
605 |
+
for m in self.last_layer_depth.modules():
|
606 |
+
if isinstance(m, nn.Conv2d):
|
607 |
+
normal_init(m, std=0.001, bias=0)
|
608 |
+
|
609 |
+
conv_layers = []
|
610 |
+
conv_layers.append(
|
611 |
+
build_conv_layer(
|
612 |
+
dict(type='Conv2d'),
|
613 |
+
in_channels=args.num_filters[-1],
|
614 |
+
out_channels=out_channels,
|
615 |
+
kernel_size=3,
|
616 |
+
stride=1,
|
617 |
+
padding=1))
|
618 |
+
conv_layers.append(
|
619 |
+
build_norm_layer(dict(type='BN'), out_channels)[1])
|
620 |
+
conv_layers.append(nn.ReLU())
|
621 |
+
self.conv_layers = nn.Sequential(*conv_layers)
|
622 |
+
|
623 |
+
self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False)
|
624 |
+
|
625 |
+
def forward(self, conv_feats):
|
626 |
+
out = self.deconv_layers(conv_feats[0])
|
627 |
+
out = self.conv_layers(out)
|
628 |
+
out = self.up(out)
|
629 |
+
self.intermediate_results.append(out)
|
630 |
+
out = self.up(out)
|
631 |
+
out_depth = self.last_layer_depth(out)
|
632 |
+
|
633 |
+
return out_depth, out, self.intermediate_results
|
634 |
+
|
635 |
+
def _make_deconv_layer(self, num_layers, num_filters, num_kernels):
|
636 |
+
"""Make deconv layers."""
|
637 |
+
|
638 |
+
layers = []
|
639 |
+
in_planes = self.in_channels
|
640 |
+
intermediate_results = [] # List to store intermediate feature maps
|
641 |
+
|
642 |
+
for i in range(num_layers):
|
643 |
+
kernel, padding, output_padding = \
|
644 |
+
self._get_deconv_cfg(num_kernels[i])
|
645 |
+
|
646 |
+
planes = num_filters[i]
|
647 |
+
layers.append(
|
648 |
+
build_upsample_layer(
|
649 |
+
dict(type='deconv'),
|
650 |
+
in_channels=in_planes,
|
651 |
+
out_channels=planes,
|
652 |
+
kernel_size=kernel,
|
653 |
+
stride=2,
|
654 |
+
padding=padding,
|
655 |
+
output_padding=output_padding,
|
656 |
+
bias=False))
|
657 |
+
layers.append(nn.BatchNorm2d(planes))
|
658 |
+
layers.append(nn.ReLU())
|
659 |
+
in_planes = planes
|
660 |
+
|
661 |
+
# Add a hook to store the intermediate result
|
662 |
+
layers[-1].register_forward_hook(self._hook_fn(intermediate_results))
|
663 |
+
|
664 |
+
return nn.Sequential(*layers), intermediate_results
|
665 |
+
|
666 |
+
def _hook_fn(self, intermediate_results):
|
667 |
+
def hook(module, input, output):
|
668 |
+
intermediate_results.append(output)
|
669 |
+
return hook
|
670 |
+
|
671 |
+
def remove_hooks(self):
|
672 |
+
self.intermediate_results.clear()
|
673 |
+
|
674 |
+
def _get_deconv_cfg(self, deconv_kernel):
|
675 |
+
"""Get configurations for deconv layers."""
|
676 |
+
if deconv_kernel == 4:
|
677 |
+
padding = 1
|
678 |
+
output_padding = 0
|
679 |
+
elif deconv_kernel == 3:
|
680 |
+
padding = 1
|
681 |
+
output_padding = 1
|
682 |
+
elif deconv_kernel == 2:
|
683 |
+
padding = 0
|
684 |
+
output_padding = 0
|
685 |
+
else:
|
686 |
+
raise ValueError(f'Not supported num_kernels ({deconv_kernel}).')
|
687 |
+
|
688 |
+
return deconv_kernel, padding, output_padding
|
689 |
+
|
690 |
+
def init_weights(self):
|
691 |
+
"""Initialize model weights."""
|
692 |
+
for m in self.modules():
|
693 |
+
if isinstance(m, nn.Conv2d):
|
694 |
+
normal_init(m, std=0.001, bias=0)
|
695 |
+
elif isinstance(m, nn.BatchNorm2d):
|
696 |
+
constant_init(m, 1)
|
697 |
+
elif isinstance(m, nn.ConvTranspose2d):
|
698 |
+
normal_init(m, std=0.001)
|
model.safetensors
CHANGED
@@ -1,3 +1,3 @@
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
-
oid sha256:
|
3 |
size 3735516436
|
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b67d266d40074d28fd30fe8b341ce964d80773ad4bb0eb7d321fc4454e9c461b
|
3 |
size 3735516436
|