ghost233lism commited on
Commit
7f0f123
·
verified ·
1 Parent(s): 10b4781

upload models

Browse files
.gitattributes CHANGED
@@ -33,3 +33,9 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ toyset/1.png filter=lfs diff=lfs merge=lfs -text
37
+ toyset/2.png filter=lfs diff=lfs merge=lfs -text
38
+ toyset/3.png filter=lfs diff=lfs merge=lfs -text
39
+ toyset/4.png filter=lfs diff=lfs merge=lfs -text
40
+ toyset/5.png filter=lfs diff=lfs merge=lfs -text
41
+ toyset/good.png filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ key628.txt
2
+ key628.txt.pub
app.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import cv2
4
+ import numpy as np
5
+ import torch
6
+ import torch.nn.functional as F
7
+ from PIL import Image
8
+ import tempfile
9
+ import io
10
+
11
+ from depth_anything.dpt import DepthAnything_AC
12
+
13
+
14
+ def normalize_depth(disparity_tensor):
15
+ """Standard normalization method to convert disparity to depth"""
16
+ eps = 1e-6
17
+ disparity_min = disparity_tensor.min()
18
+ disparity_max = disparity_tensor.max()
19
+ normalized_disparity = (disparity_tensor - disparity_min) / (disparity_max - disparity_min + eps)
20
+ return normalized_disparity
21
+
22
+
23
+ def load_model(model_path='checkpoints/depth_anything_AC_vits.pth', encoder='vits'):
24
+ """Load trained depth estimation model"""
25
+ model_configs = {
26
+ 'vitl': {'encoder': 'vitl', 'features': 256, 'out_channels': [256, 512, 1024, 1024], 'version': 'v2'},
27
+ 'vitb': {'encoder': 'vitb', 'features': 128, 'out_channels': [96, 192, 384, 768], 'version': 'v2'},
28
+ 'vits': {'encoder': 'vits', 'features': 64, 'out_channels': [48, 96, 192, 384], 'version': 'v2'}
29
+ }
30
+
31
+ model = DepthAnything_AC(model_configs[encoder])
32
+
33
+ if os.path.exists(model_path):
34
+ checkpoint = torch.load(model_path, map_location='cpu')
35
+ model.load_state_dict(checkpoint, strict=False)
36
+ else:
37
+ print(f"Warning: Model file {model_path} not found")
38
+
39
+ model.eval()
40
+ if torch.cuda.is_available():
41
+ model.cuda()
42
+
43
+ return model
44
+
45
+
46
+ def preprocess_image(image, target_size=518):
47
+ """Preprocess input image"""
48
+ if isinstance(image, Image.Image):
49
+ image = np.array(image)
50
+
51
+ if len(image.shape) == 3 and image.shape[2] == 3:
52
+ pass
53
+ elif len(image.shape) == 3 and image.shape[2] == 4:
54
+ image = image[:, :, :3]
55
+
56
+ image = image.astype(np.float32) / 255.0
57
+ h, w = image.shape[:2]
58
+ scale = target_size / min(h, w)
59
+ new_h, new_w = int(h * scale), int(w * scale)
60
+
61
+ new_h = ((new_h + 13) // 14) * 14
62
+ new_w = ((new_w + 13) // 14) * 14
63
+ image = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_CUBIC)
64
+
65
+ mean = np.array([0.485, 0.456, 0.406])
66
+ std = np.array([0.229, 0.224, 0.225])
67
+ image = (image - mean) / std
68
+
69
+ image = torch.from_numpy(image.transpose(2, 0, 1)).float()
70
+ image = image.unsqueeze(0)
71
+
72
+ return image, (h, w)
73
+
74
+
75
+ def postprocess_depth(depth_tensor, original_size):
76
+ """Post-process depth map"""
77
+ if depth_tensor.dim() == 3:
78
+ depth_tensor = depth_tensor.unsqueeze(1)
79
+ elif depth_tensor.dim() == 2:
80
+ depth_tensor = depth_tensor.unsqueeze(0).unsqueeze(1)
81
+
82
+ h, w = original_size
83
+ depth = F.interpolate(depth_tensor, size=(h, w), mode='bilinear', align_corners=True)
84
+ depth = depth.squeeze().cpu().numpy()
85
+
86
+ return depth
87
+
88
+
89
+ def create_colored_depth_map(depth, colormap='spectral'):
90
+ """Create colored depth map"""
91
+ if colormap == 'inferno':
92
+ depth_colored = cv2.applyColorMap((depth * 255).astype(np.uint8), cv2.COLORMAP_INFERNO)
93
+ depth_colored = cv2.cvtColor(depth_colored, cv2.COLOR_BGR2RGB)
94
+ elif colormap == 'spectral':
95
+ from matplotlib import cm
96
+ spectral_cmap = cm.get_cmap('Spectral_r')
97
+ depth_colored = (spectral_cmap(depth) * 255).astype(np.uint8)
98
+ depth_colored = depth_colored[:, :, :3]
99
+ else:
100
+ depth_colored = (depth * 255).astype(np.uint8)
101
+ depth_colored = np.stack([depth_colored] * 3, axis=2)
102
+
103
+ return depth_colored
104
+
105
+
106
+ print("Loading model...")
107
+ model = load_model()
108
+ print("Model loaded successfully!")
109
+
110
+
111
+ def predict_depth(input_image, colormap_choice):
112
+ """Main depth prediction function"""
113
+ try:
114
+ image_tensor, original_size = preprocess_image(input_image)
115
+
116
+ if torch.cuda.is_available():
117
+ image_tensor = image_tensor.cuda()
118
+
119
+ with torch.no_grad():
120
+ prediction = model(image_tensor)
121
+ disparity_tensor = prediction['out']
122
+ depth_tensor = normalize_depth(disparity_tensor)
123
+
124
+ depth = postprocess_depth(depth_tensor, original_size)
125
+
126
+ depth_colored = create_colored_depth_map(depth, colormap_choice.lower())
127
+
128
+ return Image.fromarray(depth_colored)
129
+
130
+ except Exception as e:
131
+ print(f"Error during inference: {str(e)}")
132
+ return None
133
+
134
+
135
+ with gr.Blocks(title="Depth Anything AC - Depth Estimation Demo", theme=gr.themes.Soft()) as demo:
136
+ gr.Markdown("""
137
+ # 🌊 Depth Anything AC - Depth Estimation Demo
138
+
139
+ Upload an image and AI will generate the corresponding depth map! Different colors in the depth map represent different distances, allowing you to see the three-dimensional structure of the image.
140
+
141
+ ## How to Use
142
+ 1. Click the upload area to select an image
143
+ 2. Choose your preferred colormap style
144
+ 3. Click the "Generate Depth Map" button
145
+ 4. View the results and download
146
+ """)
147
+
148
+ with gr.Row():
149
+ with gr.Column():
150
+ input_image = gr.Image(
151
+ label="Upload Image",
152
+ type="pil",
153
+ height=400
154
+ )
155
+
156
+ colormap_choice = gr.Dropdown(
157
+ choices=["Spectral", "Inferno", "Gray"],
158
+ value="Spectral",
159
+ label="Colormap"
160
+ )
161
+
162
+ submit_btn = gr.Button(
163
+ "🎯 Generate Depth Map",
164
+ variant="primary",
165
+ size="lg"
166
+ )
167
+
168
+ with gr.Column():
169
+ output_image = gr.Image(
170
+ label="Depth Map Result",
171
+ type="pil",
172
+ height=400
173
+ )
174
+
175
+ gr.Examples(
176
+ examples=[
177
+ ["toyset/1.png", "Spectral"],
178
+ ["toyset/2.png", "Spectral"],
179
+ ["toyset/good.png", "Spectral"],
180
+ ] if os.path.exists("toyset") else [],
181
+ inputs=[input_image, colormap_choice],
182
+ outputs=output_image,
183
+ fn=predict_depth,
184
+ cache_examples=False,
185
+ label="Try these example images"
186
+ )
187
+
188
+ submit_btn.click(
189
+ fn=predict_depth,
190
+ inputs=[input_image, colormap_choice],
191
+ outputs=output_image,
192
+ show_progress=True
193
+ )
194
+
195
+ gr.Markdown("""
196
+ ## 📝 Notes
197
+ - **Spectral**: Rainbow spectrum with distinct near-far contrast
198
+ - **Inferno**: Flame spectrum with warm tones
199
+ - **Gray**: Grayscale with classic effect
200
+ """)
201
+
202
+
203
+ if __name__ == "__main__":
204
+ demo.launch(
205
+ server_name="0.0.0.0",
206
+ server_port=7860,
207
+ share=False,
208
+ show_error=True
209
+ )
depth_anything/__pycache__/dpt.cpython-39.pyc ADDED
Binary file (8.4 kB). View file
 
depth_anything/dinov2.py ADDED
@@ -0,0 +1,415 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the Apache License, Version 2.0
4
+ # found in the LICENSE file in the root directory of this source tree.
5
+
6
+ # References:
7
+ # https://github.com/facebookresearch/dino/blob/main/vision_transformer.py
8
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
9
+
10
+ from functools import partial
11
+ import math
12
+ import logging
13
+ from typing import Sequence, Tuple, Union, Callable
14
+
15
+ import torch
16
+ import torch.nn as nn
17
+ import torch.utils.checkpoint
18
+ from torch.nn.init import trunc_normal_
19
+
20
+ from .dinov2_layers import Mlp, PatchEmbed, SwiGLUFFNFused, MemEffAttention, NestedTensorBlock as Block
21
+
22
+
23
+ logger = logging.getLogger("dinov2")
24
+
25
+
26
+ def named_apply(fn: Callable, module: nn.Module, name="", depth_first=True, include_root=False) -> nn.Module:
27
+ if not depth_first and include_root:
28
+ fn(module=module, name=name)
29
+ for child_name, child_module in module.named_children():
30
+ child_name = ".".join((name, child_name)) if name else child_name
31
+ named_apply(fn=fn, module=child_module, name=child_name, depth_first=depth_first, include_root=True)
32
+ if depth_first and include_root:
33
+ fn(module=module, name=name)
34
+ return module
35
+
36
+
37
+ class BlockChunk(nn.ModuleList):
38
+ def forward(self, x):
39
+ for b in self:
40
+ x = b(x)
41
+ return x
42
+
43
+
44
+ class DinoVisionTransformer(nn.Module):
45
+ def __init__(
46
+ self,
47
+ img_size=224,
48
+ patch_size=16,
49
+ in_chans=3,
50
+ embed_dim=768,
51
+ depth=12,
52
+ num_heads=12,
53
+ mlp_ratio=4.0,
54
+ qkv_bias=True,
55
+ ffn_bias=True,
56
+ proj_bias=True,
57
+ drop_path_rate=0.0,
58
+ drop_path_uniform=False,
59
+ init_values=None, # for layerscale: None or 0 => no layerscale
60
+ embed_layer=PatchEmbed,
61
+ act_layer=nn.GELU,
62
+ block_fn=Block,
63
+ ffn_layer="mlp",
64
+ block_chunks=1,
65
+ num_register_tokens=0,
66
+ interpolate_antialias=False,
67
+ interpolate_offset=0.1,
68
+ ):
69
+ """
70
+ Args:
71
+ img_size (int, tuple): input image size
72
+ patch_size (int, tuple): patch size
73
+ in_chans (int): number of input channels
74
+ embed_dim (int): embedding dimension
75
+ depth (int): depth of transformer
76
+ num_heads (int): number of attention heads
77
+ mlp_ratio (int): ratio of mlp hidden dim to embedding dim
78
+ qkv_bias (bool): enable bias for qkv if True
79
+ proj_bias (bool): enable bias for proj in attn if True
80
+ ffn_bias (bool): enable bias for ffn if True
81
+ drop_path_rate (float): stochastic depth rate
82
+ drop_path_uniform (bool): apply uniform drop rate across blocks
83
+ weight_init (str): weight init scheme
84
+ init_values (float): layer-scale init values
85
+ embed_layer (nn.Module): patch embedding layer
86
+ act_layer (nn.Module): MLP activation layer
87
+ block_fn (nn.Module): transformer block class
88
+ ffn_layer (str): "mlp", "swiglu", "swiglufused" or "identity"
89
+ block_chunks: (int) split block sequence into block_chunks units for FSDP wrap
90
+ num_register_tokens: (int) number of extra cls tokens (so-called "registers")
91
+ interpolate_antialias: (str) flag to apply anti-aliasing when interpolating positional embeddings
92
+ interpolate_offset: (float) work-around offset to apply when interpolating positional embeddings
93
+ """
94
+ super().__init__()
95
+ norm_layer = partial(nn.LayerNorm, eps=1e-6)
96
+
97
+ self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
98
+ self.num_tokens = 1
99
+ self.n_blocks = depth
100
+ self.num_heads = num_heads
101
+ self.patch_size = patch_size
102
+ self.num_register_tokens = num_register_tokens
103
+ self.interpolate_antialias = interpolate_antialias
104
+ self.interpolate_offset = interpolate_offset
105
+
106
+ self.patch_embed = embed_layer(img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim)
107
+ num_patches = self.patch_embed.num_patches
108
+
109
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
110
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, embed_dim))
111
+ assert num_register_tokens >= 0
112
+ self.register_tokens = (
113
+ nn.Parameter(torch.zeros(1, num_register_tokens, embed_dim)) if num_register_tokens else None
114
+ )
115
+
116
+ if drop_path_uniform is True:
117
+ dpr = [drop_path_rate] * depth
118
+ else:
119
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
120
+
121
+ if ffn_layer == "mlp":
122
+ logger.info("using MLP layer as FFN")
123
+ ffn_layer = Mlp
124
+ elif ffn_layer == "swiglufused" or ffn_layer == "swiglu":
125
+ logger.info("using SwiGLU layer as FFN")
126
+ ffn_layer = SwiGLUFFNFused
127
+ elif ffn_layer == "identity":
128
+ logger.info("using Identity layer as FFN")
129
+
130
+ def f(*args, **kwargs):
131
+ return nn.Identity()
132
+
133
+ ffn_layer = f
134
+ else:
135
+ raise NotImplementedError
136
+
137
+ blocks_list = [
138
+ block_fn(
139
+ dim=embed_dim,
140
+ num_heads=num_heads,
141
+ mlp_ratio=mlp_ratio,
142
+ qkv_bias=qkv_bias,
143
+ proj_bias=proj_bias,
144
+ ffn_bias=ffn_bias,
145
+ drop_path=dpr[i],
146
+ norm_layer=norm_layer,
147
+ act_layer=act_layer,
148
+ ffn_layer=ffn_layer,
149
+ init_values=init_values,
150
+ )
151
+ for i in range(depth)
152
+ ]
153
+ if block_chunks > 0:
154
+ self.chunked_blocks = True
155
+ chunked_blocks = []
156
+ chunksize = depth // block_chunks
157
+ for i in range(0, depth, chunksize):
158
+ # this is to keep the block index consistent if we chunk the block list
159
+ chunked_blocks.append([nn.Identity()] * i + blocks_list[i : i + chunksize])
160
+ self.blocks = nn.ModuleList([BlockChunk(p) for p in chunked_blocks])
161
+ else:
162
+ self.chunked_blocks = False
163
+ self.blocks = nn.ModuleList(blocks_list)
164
+
165
+ self.norm = norm_layer(embed_dim)
166
+ self.head = nn.Identity()
167
+
168
+ self.mask_token = nn.Parameter(torch.zeros(1, embed_dim))
169
+
170
+ self.init_weights()
171
+
172
+ def init_weights(self):
173
+ trunc_normal_(self.pos_embed, std=0.02)
174
+ nn.init.normal_(self.cls_token, std=1e-6)
175
+ if self.register_tokens is not None:
176
+ nn.init.normal_(self.register_tokens, std=1e-6)
177
+ named_apply(init_weights_vit_timm, self)
178
+
179
+ def interpolate_pos_encoding(self, x, w, h):
180
+ previous_dtype = x.dtype
181
+ npatch = x.shape[1] - 1
182
+ N = self.pos_embed.shape[1] - 1
183
+ if npatch == N and w == h:
184
+ return self.pos_embed
185
+ pos_embed = self.pos_embed.float()
186
+ class_pos_embed = pos_embed[:, 0]
187
+ patch_pos_embed = pos_embed[:, 1:]
188
+ dim = x.shape[-1]
189
+ w0 = w // self.patch_size
190
+ h0 = h // self.patch_size
191
+ # we add a small number to avoid floating point error in the interpolation
192
+ # see discussion at https://github.com/facebookresearch/dino/issues/8
193
+ # DINOv2 with register modify the interpolate_offset from 0.1 to 0.0
194
+ w0, h0 = w0 + self.interpolate_offset, h0 + self.interpolate_offset
195
+ # w0, h0 = w0 + 0.1, h0 + 0.1
196
+
197
+ sqrt_N = math.sqrt(N)
198
+ sx, sy = float(w0) / sqrt_N, float(h0) / sqrt_N
199
+ patch_pos_embed = nn.functional.interpolate(
200
+ patch_pos_embed.reshape(1, int(sqrt_N), int(sqrt_N), dim).permute(0, 3, 1, 2),
201
+ scale_factor=(sx, sy),
202
+ # (int(w0), int(h0)), # to solve the upsampling shape issue
203
+ mode="bicubic",
204
+ antialias=self.interpolate_antialias
205
+ )
206
+
207
+ assert int(w0) == patch_pos_embed.shape[-2]
208
+ assert int(h0) == patch_pos_embed.shape[-1]
209
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
210
+ return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1).to(previous_dtype)
211
+
212
+ def prepare_tokens_with_masks(self, x, masks=None):
213
+ B, nc, w, h = x.shape
214
+ x = self.patch_embed(x)
215
+ if masks is not None:
216
+ x = torch.where(masks.unsqueeze(-1), self.mask_token.to(x.dtype).unsqueeze(0), x)
217
+
218
+ x = torch.cat((self.cls_token.expand(x.shape[0], -1, -1), x), dim=1)
219
+ x = x + self.interpolate_pos_encoding(x, w, h)
220
+
221
+ if self.register_tokens is not None:
222
+ x = torch.cat(
223
+ (
224
+ x[:, :1],
225
+ self.register_tokens.expand(x.shape[0], -1, -1),
226
+ x[:, 1:],
227
+ ),
228
+ dim=1,
229
+ )
230
+
231
+ return x
232
+
233
+ def forward_features_list(self, x_list, masks_list):
234
+ x = [self.prepare_tokens_with_masks(x, masks) for x, masks in zip(x_list, masks_list)]
235
+ for blk in self.blocks:
236
+ x = blk(x)
237
+
238
+ all_x = x
239
+ output = []
240
+ for x, masks in zip(all_x, masks_list):
241
+ x_norm = self.norm(x)
242
+ output.append(
243
+ {
244
+ "x_norm_clstoken": x_norm[:, 0],
245
+ "x_norm_regtokens": x_norm[:, 1 : self.num_register_tokens + 1],
246
+ "x_norm_patchtokens": x_norm[:, self.num_register_tokens + 1 :],
247
+ "x_prenorm": x,
248
+ "masks": masks,
249
+ }
250
+ )
251
+ return output
252
+
253
+ def forward_features(self, x, masks=None):
254
+ if isinstance(x, list):
255
+ return self.forward_features_list(x, masks)
256
+
257
+ x = self.prepare_tokens_with_masks(x, masks)
258
+
259
+ for blk in self.blocks:
260
+ x = blk(x)
261
+
262
+ x_norm = self.norm(x)
263
+ return {
264
+ "x_norm_clstoken": x_norm[:, 0],
265
+ "x_norm_regtokens": x_norm[:, 1 : self.num_register_tokens + 1],
266
+ "x_norm_patchtokens": x_norm[:, self.num_register_tokens + 1 :],
267
+ "x_prenorm": x,
268
+ "masks": masks,
269
+ }
270
+
271
+ def _get_intermediate_layers_not_chunked(self, x, n=1):
272
+ x = self.prepare_tokens_with_masks(x)
273
+ # If n is an int, take the n last blocks. If it's a list, take them
274
+ output, total_block_len = [], len(self.blocks)
275
+ blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n
276
+ for i, blk in enumerate(self.blocks):
277
+ x = blk(x)
278
+ if i in blocks_to_take:
279
+ output.append(x)
280
+ assert len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found"
281
+ return output
282
+
283
+ def _get_intermediate_layers_chunked(self, x, n=1):
284
+ x = self.prepare_tokens_with_masks(x)
285
+ output, i, total_block_len = [], 0, len(self.blocks[-1])
286
+ # If n is an int, take the n last blocks. If it's a list, take them
287
+ blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n
288
+ for block_chunk in self.blocks:
289
+ for blk in block_chunk[i:]: # Passing the nn.Identity()
290
+ x = blk(x)
291
+ if i in blocks_to_take:
292
+ output.append(x)
293
+ i += 1
294
+ assert len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found"
295
+ return output
296
+
297
+ def get_intermediate_layers(
298
+ self,
299
+ x: torch.Tensor,
300
+ n: Union[int, Sequence] = 1, # Layers or n last layers to take
301
+ reshape: bool = False,
302
+ return_class_token: bool = False,
303
+ norm=True
304
+ ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]]]:
305
+ if self.chunked_blocks:
306
+ outputs = self._get_intermediate_layers_chunked(x, n)
307
+ else:
308
+ outputs = self._get_intermediate_layers_not_chunked(x, n)
309
+ if norm:
310
+ outputs = [self.norm(out) for out in outputs]
311
+ class_tokens = [out[:, 0] for out in outputs]
312
+ outputs = [out[:, 1 + self.num_register_tokens:] for out in outputs]
313
+ if reshape:
314
+ B, _, w, h = x.shape
315
+ outputs = [
316
+ out.reshape(B, w // self.patch_size, h // self.patch_size, -1).permute(0, 3, 1, 2).contiguous()
317
+ for out in outputs
318
+ ]
319
+ if return_class_token:
320
+ return tuple(zip(outputs, class_tokens))
321
+ return tuple(outputs)
322
+
323
+ def forward(self, *args, is_training=False, **kwargs):
324
+ ret = self.forward_features(*args, **kwargs)
325
+ if is_training:
326
+ return ret
327
+ else:
328
+ return self.head(ret["x_norm_clstoken"])
329
+
330
+
331
+ def init_weights_vit_timm(module: nn.Module, name: str = ""):
332
+ """ViT weight initialization, original timm impl (for reproducibility)"""
333
+ if isinstance(module, nn.Linear):
334
+ trunc_normal_(module.weight, std=0.02)
335
+ if module.bias is not None:
336
+ nn.init.zeros_(module.bias)
337
+
338
+
339
+ def vit_small(patch_size=16, num_register_tokens=0, **kwargs):
340
+ model = DinoVisionTransformer(
341
+ patch_size=patch_size,
342
+ embed_dim=384,
343
+ depth=12,
344
+ num_heads=6,
345
+ mlp_ratio=4,
346
+ block_fn=partial(Block, attn_class=MemEffAttention),
347
+ num_register_tokens=num_register_tokens,
348
+ **kwargs,
349
+ )
350
+ return model
351
+
352
+
353
+ def vit_base(patch_size=16, num_register_tokens=0, **kwargs):
354
+ model = DinoVisionTransformer(
355
+ patch_size=patch_size,
356
+ embed_dim=768,
357
+ depth=12,
358
+ num_heads=12,
359
+ mlp_ratio=4,
360
+ block_fn=partial(Block, attn_class=MemEffAttention),
361
+ num_register_tokens=num_register_tokens,
362
+ **kwargs,
363
+ )
364
+ return model
365
+
366
+
367
+ def vit_large(patch_size=16, num_register_tokens=0, **kwargs):
368
+ model = DinoVisionTransformer(
369
+ patch_size=patch_size,
370
+ embed_dim=1024,
371
+ depth=24,
372
+ num_heads=16,
373
+ mlp_ratio=4,
374
+ block_fn=partial(Block, attn_class=MemEffAttention),
375
+ num_register_tokens=num_register_tokens,
376
+ **kwargs,
377
+ )
378
+ return model
379
+
380
+
381
+ def vit_giant2(patch_size=16, num_register_tokens=0, **kwargs):
382
+ """
383
+ Close to ViT-giant, with embed-dim 1536 and 24 heads => embed-dim per head 64
384
+ """
385
+ model = DinoVisionTransformer(
386
+ patch_size=patch_size,
387
+ embed_dim=1536,
388
+ depth=40,
389
+ num_heads=24,
390
+ mlp_ratio=4,
391
+ block_fn=partial(Block, attn_class=MemEffAttention),
392
+ num_register_tokens=num_register_tokens,
393
+ **kwargs,
394
+ )
395
+ return model
396
+
397
+
398
+ def DINOv2(model_name):
399
+ model_zoo = {
400
+ "vits": vit_small,
401
+ "vitb": vit_base,
402
+ "vitl": vit_large,
403
+ "vitg": vit_giant2
404
+ }
405
+
406
+ return model_zoo[model_name](
407
+ img_size=518,
408
+ patch_size=14,
409
+ init_values=1.0,
410
+ ffn_layer="mlp" if model_name != "vitg" else "swiglufused",
411
+ block_chunks=0,
412
+ num_register_tokens=0,
413
+ interpolate_antialias=False,
414
+ interpolate_offset=0.1
415
+ )
depth_anything/dinov2_layers/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from .mlp import Mlp
8
+ from .patch_embed import PatchEmbed
9
+ from .swiglu_ffn import SwiGLUFFN, SwiGLUFFNFused
10
+ from .block import NestedTensorBlock
11
+ from .attention import MemEffAttention
depth_anything/dinov2_layers/attention.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ # References:
8
+ # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
9
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
10
+
11
+ import logging
12
+
13
+ from torch import Tensor
14
+ from torch import nn
15
+
16
+
17
+ logger = logging.getLogger("dinov2")
18
+
19
+
20
+ try:
21
+ from xformers.ops import memory_efficient_attention, unbind, fmha
22
+
23
+ XFORMERS_AVAILABLE = True
24
+ except ImportError:
25
+ logger.warning("xFormers not available")
26
+ XFORMERS_AVAILABLE = False
27
+
28
+
29
+ class Attention(nn.Module):
30
+ def __init__(
31
+ self,
32
+ dim: int,
33
+ num_heads: int = 8,
34
+ qkv_bias: bool = False,
35
+ proj_bias: bool = True,
36
+ attn_drop: float = 0.0,
37
+ proj_drop: float = 0.0,
38
+ ) -> None:
39
+ super().__init__()
40
+ self.num_heads = num_heads
41
+ head_dim = dim // num_heads
42
+ self.scale = head_dim**-0.5
43
+
44
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
45
+ self.attn_drop = nn.Dropout(attn_drop)
46
+ self.proj = nn.Linear(dim, dim, bias=proj_bias)
47
+ self.proj_drop = nn.Dropout(proj_drop)
48
+
49
+ def forward(self, x: Tensor) -> Tensor:
50
+ B, N, C = x.shape
51
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
52
+
53
+ q, k, v = qkv[0] * self.scale, qkv[1], qkv[2]
54
+ attn = q @ k.transpose(-2, -1)
55
+
56
+ attn = attn.softmax(dim=-1)
57
+ attn = self.attn_drop(attn)
58
+
59
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
60
+ x = self.proj(x)
61
+ x = self.proj_drop(x)
62
+ return x
63
+
64
+
65
+ class MemEffAttention(Attention):
66
+ def forward(self, x: Tensor, attn_bias=None) -> Tensor:
67
+ if not XFORMERS_AVAILABLE:
68
+ assert attn_bias is None, "xFormers is required for nested tensors usage"
69
+ return super().forward(x)
70
+
71
+ B, N, C = x.shape
72
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads)
73
+
74
+ q, k, v = unbind(qkv, 2)
75
+
76
+ x = memory_efficient_attention(q, k, v, attn_bias=attn_bias)
77
+ x = x.reshape([B, N, C])
78
+
79
+ x = self.proj(x)
80
+ x = self.proj_drop(x)
81
+ return x
82
+
83
+
depth_anything/dinov2_layers/block.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ # References:
8
+ # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
9
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py
10
+
11
+ import logging
12
+ from typing import Callable, List, Any, Tuple, Dict
13
+
14
+ import torch
15
+ from torch import nn, Tensor
16
+
17
+ from .attention import Attention, MemEffAttention
18
+ from .drop_path import DropPath
19
+ from .layer_scale import LayerScale
20
+ from .mlp import Mlp
21
+
22
+
23
+ logger = logging.getLogger("dinov2")
24
+
25
+
26
+ try:
27
+ from xformers.ops import fmha
28
+ from xformers.ops import scaled_index_add, index_select_cat
29
+
30
+ XFORMERS_AVAILABLE = True
31
+ except ImportError:
32
+ logger.warning("xFormers not available")
33
+ XFORMERS_AVAILABLE = False
34
+
35
+
36
+ class Block(nn.Module):
37
+ def __init__(
38
+ self,
39
+ dim: int,
40
+ num_heads: int,
41
+ mlp_ratio: float = 4.0,
42
+ qkv_bias: bool = False,
43
+ proj_bias: bool = True,
44
+ ffn_bias: bool = True,
45
+ drop: float = 0.0,
46
+ attn_drop: float = 0.0,
47
+ init_values=None,
48
+ drop_path: float = 0.0,
49
+ act_layer: Callable[..., nn.Module] = nn.GELU,
50
+ norm_layer: Callable[..., nn.Module] = nn.LayerNorm,
51
+ attn_class: Callable[..., nn.Module] = Attention,
52
+ ffn_layer: Callable[..., nn.Module] = Mlp,
53
+ ) -> None:
54
+ super().__init__()
55
+ # print(f"biases: qkv: {qkv_bias}, proj: {proj_bias}, ffn: {ffn_bias}")
56
+ self.norm1 = norm_layer(dim)
57
+ self.attn = attn_class(
58
+ dim,
59
+ num_heads=num_heads,
60
+ qkv_bias=qkv_bias,
61
+ proj_bias=proj_bias,
62
+ attn_drop=attn_drop,
63
+ proj_drop=drop,
64
+ )
65
+ self.ls1 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
66
+ self.drop_path1 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
67
+
68
+ self.norm2 = norm_layer(dim)
69
+ mlp_hidden_dim = int(dim * mlp_ratio)
70
+ self.mlp = ffn_layer(
71
+ in_features=dim,
72
+ hidden_features=mlp_hidden_dim,
73
+ act_layer=act_layer,
74
+ drop=drop,
75
+ bias=ffn_bias,
76
+ )
77
+ self.ls2 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
78
+ self.drop_path2 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
79
+
80
+ self.sample_drop_ratio = drop_path
81
+
82
+ def forward(self, x: Tensor) -> Tensor:
83
+ def attn_residual_func(x: Tensor) -> Tensor:
84
+ return self.ls1(self.attn(self.norm1(x)))
85
+
86
+ def ffn_residual_func(x: Tensor) -> Tensor:
87
+ return self.ls2(self.mlp(self.norm2(x)))
88
+
89
+ if self.training and self.sample_drop_ratio > 0.1:
90
+ # the overhead is compensated only for a drop path rate larger than 0.1
91
+ x = drop_add_residual_stochastic_depth(
92
+ x,
93
+ residual_func=attn_residual_func,
94
+ sample_drop_ratio=self.sample_drop_ratio,
95
+ )
96
+ x = drop_add_residual_stochastic_depth(
97
+ x,
98
+ residual_func=ffn_residual_func,
99
+ sample_drop_ratio=self.sample_drop_ratio,
100
+ )
101
+ elif self.training and self.sample_drop_ratio > 0.0:
102
+ x = x + self.drop_path1(attn_residual_func(x))
103
+ x = x + self.drop_path1(ffn_residual_func(x)) # FIXME: drop_path2
104
+ else:
105
+ x = x + attn_residual_func(x)
106
+ x = x + ffn_residual_func(x)
107
+ return x
108
+
109
+
110
+ def drop_add_residual_stochastic_depth(
111
+ x: Tensor,
112
+ residual_func: Callable[[Tensor], Tensor],
113
+ sample_drop_ratio: float = 0.0,
114
+ ) -> Tensor:
115
+ # 1) extract subset using permutation
116
+ b, n, d = x.shape
117
+ sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1)
118
+ brange = (torch.randperm(b, device=x.device))[:sample_subset_size]
119
+ x_subset = x[brange]
120
+
121
+ # 2) apply residual_func to get residual
122
+ residual = residual_func(x_subset)
123
+
124
+ x_flat = x.flatten(1)
125
+ residual = residual.flatten(1)
126
+
127
+ residual_scale_factor = b / sample_subset_size
128
+
129
+ # 3) add the residual
130
+ x_plus_residual = torch.index_add(x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor)
131
+ return x_plus_residual.view_as(x)
132
+
133
+
134
+ def get_branges_scales(x, sample_drop_ratio=0.0):
135
+ b, n, d = x.shape
136
+ sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1)
137
+ brange = (torch.randperm(b, device=x.device))[:sample_subset_size]
138
+ residual_scale_factor = b / sample_subset_size
139
+ return brange, residual_scale_factor
140
+
141
+
142
+ def add_residual(x, brange, residual, residual_scale_factor, scaling_vector=None):
143
+ if scaling_vector is None:
144
+ x_flat = x.flatten(1)
145
+ residual = residual.flatten(1)
146
+ x_plus_residual = torch.index_add(x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor)
147
+ else:
148
+ x_plus_residual = scaled_index_add(
149
+ x, brange, residual.to(dtype=x.dtype), scaling=scaling_vector, alpha=residual_scale_factor
150
+ )
151
+ return x_plus_residual
152
+
153
+
154
+ attn_bias_cache: Dict[Tuple, Any] = {}
155
+
156
+
157
+ def get_attn_bias_and_cat(x_list, branges=None):
158
+ """
159
+ this will perform the index select, cat the tensors, and provide the attn_bias from cache
160
+ """
161
+ batch_sizes = [b.shape[0] for b in branges] if branges is not None else [x.shape[0] for x in x_list]
162
+ all_shapes = tuple((b, x.shape[1]) for b, x in zip(batch_sizes, x_list))
163
+ if all_shapes not in attn_bias_cache.keys():
164
+ seqlens = []
165
+ for b, x in zip(batch_sizes, x_list):
166
+ for _ in range(b):
167
+ seqlens.append(x.shape[1])
168
+ attn_bias = fmha.BlockDiagonalMask.from_seqlens(seqlens)
169
+ attn_bias._batch_sizes = batch_sizes
170
+ attn_bias_cache[all_shapes] = attn_bias
171
+
172
+ if branges is not None:
173
+ cat_tensors = index_select_cat([x.flatten(1) for x in x_list], branges).view(1, -1, x_list[0].shape[-1])
174
+ else:
175
+ tensors_bs1 = tuple(x.reshape([1, -1, *x.shape[2:]]) for x in x_list)
176
+ cat_tensors = torch.cat(tensors_bs1, dim=1)
177
+
178
+ return attn_bias_cache[all_shapes], cat_tensors
179
+
180
+
181
+ def drop_add_residual_stochastic_depth_list(
182
+ x_list: List[Tensor],
183
+ residual_func: Callable[[Tensor, Any], Tensor],
184
+ sample_drop_ratio: float = 0.0,
185
+ scaling_vector=None,
186
+ ) -> Tensor:
187
+ # 1) generate random set of indices for dropping samples in the batch
188
+ branges_scales = [get_branges_scales(x, sample_drop_ratio=sample_drop_ratio) for x in x_list]
189
+ branges = [s[0] for s in branges_scales]
190
+ residual_scale_factors = [s[1] for s in branges_scales]
191
+
192
+ # 2) get attention bias and index+concat the tensors
193
+ attn_bias, x_cat = get_attn_bias_and_cat(x_list, branges)
194
+
195
+ # 3) apply residual_func to get residual, and split the result
196
+ residual_list = attn_bias.split(residual_func(x_cat, attn_bias=attn_bias)) # type: ignore
197
+
198
+ outputs = []
199
+ for x, brange, residual, residual_scale_factor in zip(x_list, branges, residual_list, residual_scale_factors):
200
+ outputs.append(add_residual(x, brange, residual, residual_scale_factor, scaling_vector).view_as(x))
201
+ return outputs
202
+
203
+
204
+ class NestedTensorBlock(Block):
205
+ def forward_nested(self, x_list: List[Tensor]) -> List[Tensor]:
206
+ """
207
+ x_list contains a list of tensors to nest together and run
208
+ """
209
+ assert isinstance(self.attn, MemEffAttention)
210
+
211
+ if self.training and self.sample_drop_ratio > 0.0:
212
+
213
+ def attn_residual_func(x: Tensor, attn_bias=None) -> Tensor:
214
+ return self.attn(self.norm1(x), attn_bias=attn_bias)
215
+
216
+ def ffn_residual_func(x: Tensor, attn_bias=None) -> Tensor:
217
+ return self.mlp(self.norm2(x))
218
+
219
+ x_list = drop_add_residual_stochastic_depth_list(
220
+ x_list,
221
+ residual_func=attn_residual_func,
222
+ sample_drop_ratio=self.sample_drop_ratio,
223
+ scaling_vector=self.ls1.gamma if isinstance(self.ls1, LayerScale) else None,
224
+ )
225
+ x_list = drop_add_residual_stochastic_depth_list(
226
+ x_list,
227
+ residual_func=ffn_residual_func,
228
+ sample_drop_ratio=self.sample_drop_ratio,
229
+ scaling_vector=self.ls2.gamma if isinstance(self.ls1, LayerScale) else None,
230
+ )
231
+ return x_list
232
+ else:
233
+
234
+ def attn_residual_func(x: Tensor, attn_bias=None) -> Tensor:
235
+ return self.ls1(self.attn(self.norm1(x), attn_bias=attn_bias))
236
+
237
+ def ffn_residual_func(x: Tensor, attn_bias=None) -> Tensor:
238
+ return self.ls2(self.mlp(self.norm2(x)))
239
+
240
+ attn_bias, x = get_attn_bias_and_cat(x_list)
241
+ x = x + attn_residual_func(x, attn_bias=attn_bias)
242
+ x = x + ffn_residual_func(x)
243
+ return attn_bias.split(x)
244
+
245
+ def forward(self, x_or_x_list):
246
+ if isinstance(x_or_x_list, Tensor):
247
+ return super().forward(x_or_x_list)
248
+ elif isinstance(x_or_x_list, list):
249
+ assert XFORMERS_AVAILABLE, "Please install xFormers for nested tensors usage"
250
+ return self.forward_nested(x_or_x_list)
251
+ else:
252
+ raise AssertionError
depth_anything/dinov2_layers/drop_path.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ # References:
8
+ # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
9
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/drop.py
10
+
11
+
12
+ from torch import nn
13
+
14
+
15
+ def drop_path(x, drop_prob: float = 0.0, training: bool = False):
16
+ if drop_prob == 0.0 or not training:
17
+ return x
18
+ keep_prob = 1 - drop_prob
19
+ shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
20
+ random_tensor = x.new_empty(shape).bernoulli_(keep_prob)
21
+ if keep_prob > 0.0:
22
+ random_tensor.div_(keep_prob)
23
+ output = x * random_tensor
24
+ return output
25
+
26
+
27
+ class DropPath(nn.Module):
28
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
29
+
30
+ def __init__(self, drop_prob=None):
31
+ super(DropPath, self).__init__()
32
+ self.drop_prob = drop_prob
33
+
34
+ def forward(self, x):
35
+ return drop_path(x, self.drop_prob, self.training)
depth_anything/dinov2_layers/layer_scale.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ # Modified from: https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/vision_transformer.py#L103-L110
8
+
9
+ from typing import Union
10
+
11
+ import torch
12
+ from torch import Tensor
13
+ from torch import nn
14
+
15
+
16
+ class LayerScale(nn.Module):
17
+ def __init__(
18
+ self,
19
+ dim: int,
20
+ init_values: Union[float, Tensor] = 1e-5,
21
+ inplace: bool = False,
22
+ ) -> None:
23
+ super().__init__()
24
+ self.inplace = inplace
25
+ self.gamma = nn.Parameter(init_values * torch.ones(dim))
26
+
27
+ def forward(self, x: Tensor) -> Tensor:
28
+ return x.mul_(self.gamma) if self.inplace else x * self.gamma
depth_anything/dinov2_layers/mlp.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ # References:
8
+ # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
9
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/mlp.py
10
+
11
+
12
+ from typing import Callable, Optional
13
+
14
+ from torch import Tensor, nn
15
+
16
+
17
+ class Mlp(nn.Module):
18
+ def __init__(
19
+ self,
20
+ in_features: int,
21
+ hidden_features: Optional[int] = None,
22
+ out_features: Optional[int] = None,
23
+ act_layer: Callable[..., nn.Module] = nn.GELU,
24
+ drop: float = 0.0,
25
+ bias: bool = True,
26
+ ) -> None:
27
+ super().__init__()
28
+ out_features = out_features or in_features
29
+ hidden_features = hidden_features or in_features
30
+ self.fc1 = nn.Linear(in_features, hidden_features, bias=bias)
31
+ self.act = act_layer()
32
+ self.fc2 = nn.Linear(hidden_features, out_features, bias=bias)
33
+ self.drop = nn.Dropout(drop)
34
+
35
+ def forward(self, x: Tensor) -> Tensor:
36
+ x = self.fc1(x)
37
+ x = self.act(x)
38
+ x = self.drop(x)
39
+ x = self.fc2(x)
40
+ x = self.drop(x)
41
+ return x
depth_anything/dinov2_layers/patch_embed.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ # References:
8
+ # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
9
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py
10
+
11
+ from typing import Callable, Optional, Tuple, Union
12
+
13
+ from torch import Tensor
14
+ import torch.nn as nn
15
+
16
+
17
+ def make_2tuple(x):
18
+ if isinstance(x, tuple):
19
+ assert len(x) == 2
20
+ return x
21
+
22
+ assert isinstance(x, int)
23
+ return (x, x)
24
+
25
+
26
+ class PatchEmbed(nn.Module):
27
+ """
28
+ 2D image to patch embedding: (B,C,H,W) -> (B,N,D)
29
+
30
+ Args:
31
+ img_size: Image size.
32
+ patch_size: Patch token size.
33
+ in_chans: Number of input image channels.
34
+ embed_dim: Number of linear projection output channels.
35
+ norm_layer: Normalization layer.
36
+ """
37
+
38
+ def __init__(
39
+ self,
40
+ img_size: Union[int, Tuple[int, int]] = 224,
41
+ patch_size: Union[int, Tuple[int, int]] = 16,
42
+ in_chans: int = 3,
43
+ embed_dim: int = 768,
44
+ norm_layer: Optional[Callable] = None,
45
+ flatten_embedding: bool = True,
46
+ ) -> None:
47
+ super().__init__()
48
+
49
+ image_HW = make_2tuple(img_size)
50
+ patch_HW = make_2tuple(patch_size)
51
+ patch_grid_size = (
52
+ image_HW[0] // patch_HW[0],
53
+ image_HW[1] // patch_HW[1],
54
+ )
55
+
56
+ self.img_size = image_HW
57
+ self.patch_size = patch_HW
58
+ self.patches_resolution = patch_grid_size
59
+ self.num_patches = patch_grid_size[0] * patch_grid_size[1]
60
+
61
+ self.in_chans = in_chans
62
+ self.embed_dim = embed_dim
63
+
64
+ self.flatten_embedding = flatten_embedding
65
+
66
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_HW, stride=patch_HW)
67
+ self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
68
+
69
+ def forward(self, x: Tensor) -> Tensor:
70
+ _, _, H, W = x.shape
71
+ patch_H, patch_W = self.patch_size
72
+
73
+ assert H % patch_H == 0, f"Input image height {H} is not a multiple of patch height {patch_H}"
74
+ assert W % patch_W == 0, f"Input image width {W} is not a multiple of patch width: {patch_W}"
75
+
76
+ x = self.proj(x) # B C H W
77
+ H, W = x.size(2), x.size(3)
78
+ x = x.flatten(2).transpose(1, 2) # B HW C
79
+ x = self.norm(x)
80
+ if not self.flatten_embedding:
81
+ x = x.reshape(-1, H, W, self.embed_dim) # B H W C
82
+ return x
83
+
84
+ def flops(self) -> float:
85
+ Ho, Wo = self.patches_resolution
86
+ flops = Ho * Wo * self.embed_dim * self.in_chans * (self.patch_size[0] * self.patch_size[1])
87
+ if self.norm is not None:
88
+ flops += Ho * Wo * self.embed_dim
89
+ return flops
depth_anything/dinov2_layers/swiglu_ffn.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from typing import Callable, Optional
8
+
9
+ from torch import Tensor, nn
10
+ import torch.nn.functional as F
11
+
12
+
13
+ class SwiGLUFFN(nn.Module):
14
+ def __init__(
15
+ self,
16
+ in_features: int,
17
+ hidden_features: Optional[int] = None,
18
+ out_features: Optional[int] = None,
19
+ act_layer: Callable[..., nn.Module] = None,
20
+ drop: float = 0.0,
21
+ bias: bool = True,
22
+ ) -> None:
23
+ super().__init__()
24
+ out_features = out_features or in_features
25
+ hidden_features = hidden_features or in_features
26
+ self.w12 = nn.Linear(in_features, 2 * hidden_features, bias=bias)
27
+ self.w3 = nn.Linear(hidden_features, out_features, bias=bias)
28
+
29
+ def forward(self, x: Tensor) -> Tensor:
30
+ x12 = self.w12(x)
31
+ x1, x2 = x12.chunk(2, dim=-1)
32
+ hidden = F.silu(x1) * x2
33
+ return self.w3(hidden)
34
+
35
+
36
+ try:
37
+ from xformers.ops import SwiGLU
38
+
39
+ XFORMERS_AVAILABLE = True
40
+ except ImportError:
41
+ SwiGLU = SwiGLUFFN
42
+ XFORMERS_AVAILABLE = False
43
+
44
+
45
+ class SwiGLUFFNFused(SwiGLU):
46
+ def __init__(
47
+ self,
48
+ in_features: int,
49
+ hidden_features: Optional[int] = None,
50
+ out_features: Optional[int] = None,
51
+ act_layer: Callable[..., nn.Module] = None,
52
+ drop: float = 0.0,
53
+ bias: bool = True,
54
+ ) -> None:
55
+ out_features = out_features or in_features
56
+ hidden_features = hidden_features or in_features
57
+ hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8
58
+ super().__init__(
59
+ in_features=in_features,
60
+ hidden_features=hidden_features,
61
+ out_features=out_features,
62
+ bias=bias,
63
+ )
depth_anything/dpt.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ import torchhub.facebookresearch_dinov2_main.hubconf as dinov2
5
+
6
+ from depth_anything.util.blocksv2 import FeatureFusionBlock, _make_scratch
7
+ from torchvision.transforms import Compose
8
+ from depth_anything.util.transform import Resize, NormalizeImage, PrepareForNet
9
+ import cv2
10
+ import numpy as np
11
+
12
+ def _make_fusion_block(features, use_bn, size = None):
13
+ return FeatureFusionBlock(
14
+ features,
15
+ nn.ReLU(False),
16
+ deconv=False,
17
+ bn=use_bn,
18
+ expand=False,
19
+ align_corners=True,
20
+ size=size,
21
+ )
22
+
23
+
24
+ class DPTHead(nn.Module):
25
+ def __init__(self, nclass, in_channels, features=256, use_bn=False, out_channels=[256, 512, 1024, 1024], use_clstoken=False):
26
+ super(DPTHead, self).__init__()
27
+
28
+ self.nclass = nclass
29
+ self.use_clstoken = use_clstoken
30
+
31
+ self.projects = nn.ModuleList([
32
+ nn.Conv2d(
33
+ in_channels=in_channels,
34
+ out_channels=out_channel,
35
+ kernel_size=1,
36
+ stride=1,
37
+ padding=0,
38
+ ) for out_channel in out_channels
39
+ ])
40
+
41
+ self.resize_layers = nn.ModuleList([
42
+ nn.ConvTranspose2d(
43
+ in_channels=out_channels[0],
44
+ out_channels=out_channels[0],
45
+ kernel_size=4,
46
+ stride=4,
47
+ padding=0),
48
+ nn.ConvTranspose2d(
49
+ in_channels=out_channels[1],
50
+ out_channels=out_channels[1],
51
+ kernel_size=2,
52
+ stride=2,
53
+ padding=0),
54
+ nn.Identity(),
55
+ nn.Conv2d(
56
+ in_channels=out_channels[3],
57
+ out_channels=out_channels[3],
58
+ kernel_size=3,
59
+ stride=2,
60
+ padding=1)
61
+ ])
62
+
63
+ if use_clstoken:
64
+ self.readout_projects = nn.ModuleList()
65
+ for _ in range(len(self.projects)):
66
+ self.readout_projects.append(
67
+ nn.Sequential(
68
+ nn.Linear(2 * in_channels, in_channels),
69
+ nn.GELU()))
70
+
71
+ self.scratch = _make_scratch(
72
+ out_channels,
73
+ features,
74
+ groups=1,
75
+ expand=False,
76
+ )
77
+
78
+ self.scratch.stem_transpose = nn.Identity()
79
+
80
+ self.scratch.refinenet1 = _make_fusion_block(features, use_bn)
81
+ self.scratch.refinenet2 = _make_fusion_block(features, use_bn)
82
+ self.scratch.refinenet3 = _make_fusion_block(features, use_bn)
83
+ self.scratch.refinenet4 = _make_fusion_block(features, use_bn)
84
+
85
+ head_features_1 = features
86
+ head_features_2 = 32
87
+
88
+ if nclass > 1:
89
+ self.scratch.output_conv = nn.Sequential(
90
+ nn.Conv2d(head_features_1, head_features_1, kernel_size=3, stride=1, padding=1),
91
+ nn.ReLU(True),
92
+ nn.Conv2d(head_features_1, nclass, kernel_size=1, stride=1, padding=0),
93
+ )
94
+ else:
95
+ self.scratch.output_conv1 = nn.Conv2d(head_features_1, head_features_1 // 2, kernel_size=3, stride=1, padding=1)
96
+
97
+ self.scratch.output_conv2 = nn.Sequential(
98
+ nn.Conv2d(head_features_1 // 2, head_features_2, kernel_size=3, stride=1, padding=1),
99
+ nn.ReLU(True),
100
+ nn.Conv2d(head_features_2, 1, kernel_size=1, stride=1, padding=0),
101
+ nn.ReLU(True),
102
+ nn.Identity(),
103
+ )
104
+
105
+ def forward(self, out_features, patch_h, patch_w,need_fp=False,need_prior=False,teacher_features=None,alpha=0.8):
106
+ depth_out={}
107
+ out = []
108
+ for i, x in enumerate(out_features):
109
+ if self.use_clstoken:
110
+ x, cls_token = x[0], x[1]
111
+ readout = cls_token.unsqueeze(1).expand_as(x)
112
+ x = self.readout_projects[i](torch.cat((x, readout), -1))
113
+ else:
114
+ x = x[0]
115
+ x = x.permute(0, 2, 1).reshape((x.shape[0], x.shape[-1], patch_h, patch_w)).contiguous()
116
+
117
+ x = self.projects[i](x)
118
+ x = self.resize_layers[i](x)
119
+
120
+ out.append(x)
121
+
122
+ layer_1, layer_2, layer_3, layer_4 = out
123
+
124
+ layer_1_rn = self.scratch.layer1_rn(layer_1)
125
+ layer_2_rn = self.scratch.layer2_rn(layer_2)
126
+ layer_3_rn = self.scratch.layer3_rn(layer_3)
127
+ layer_4_rn = self.scratch.layer4_rn(layer_4)
128
+
129
+ path_4 = self.scratch.refinenet4(layer_4_rn, size=layer_3_rn.shape[2:])
130
+ path_3 = self.scratch.refinenet3(path_4, layer_3_rn, size=layer_2_rn.shape[2:])
131
+ path_2 = self.scratch.refinenet2(path_3, layer_2_rn, size=layer_1_rn.shape[2:])
132
+ path_1 = self.scratch.refinenet1(path_2, layer_1_rn)
133
+
134
+ out = self.scratch.output_conv1(path_1)
135
+ out = F.interpolate(out, (int(patch_h * 14), int(patch_w * 14)), mode="bilinear", align_corners=True)
136
+ out = self.scratch.output_conv2(out)
137
+
138
+ depth_out['out']=out
139
+
140
+ return depth_out
141
+
142
+
143
+ class DPT_DINOv2(nn.Module):
144
+ def __init__(self, encoder='vitl', features=256, out_channels=[256, 512, 1024, 1024], use_bn=False, use_clstoken=False, localhub=True, version='v1'):
145
+ super(DPT_DINOv2, self).__init__()
146
+
147
+ assert encoder in ['vits', 'vitb', 'vitl']
148
+ self.intermediate_layer_idx = {
149
+ 'vits': [2, 5, 8, 11],
150
+ 'vitb': [2, 5, 8, 11],
151
+ 'vitl': [4, 11, 17, 23],
152
+ 'vitg': [9, 19, 29, 39]
153
+ }
154
+ self.encoder = encoder
155
+ self.version = version
156
+ # in case the Internet connection is not stable, please load the DINOv2 locally
157
+ # if localhub:
158
+ # self.pretrained = torch.hub.load('torchhub/facebookresearch_dinov2_main', 'dinov2_{:}14'.format(encoder), source='local', pretrained=True)
159
+ # else:
160
+ # self.pretrained = torch.hub.load('facebookresearch/dinov2', 'dinov2_{:}14'.format(encoder))
161
+ self.pretrained = dinov2.__dict__['dinov2_{:}14'.format(encoder)](pretrained=True)
162
+
163
+ dim = self.pretrained.blocks[0].attn.qkv.in_features
164
+
165
+ self.depth_head = DPTHead(1, dim, features, use_bn, out_channels=out_channels, use_clstoken=use_clstoken)
166
+
167
+
168
+ def forward(self, x,need_fp=False,teacher_features=None,alpha=0.8,prior_mode='teacher'):
169
+ depth_out={}
170
+ h, w = x.shape[-2:]
171
+ if self.version == 'v1':
172
+ features = self.pretrained.get_intermediate_layers(x, 4, return_class_token=True)
173
+ else:
174
+
175
+ features = self.pretrained.get_intermediate_layers(x, self.intermediate_layer_idx[self.encoder], return_class_token=True)
176
+ patch_h, patch_w = h // 14, w // 14
177
+
178
+ depth_all = self.depth_head(features, patch_h, patch_w,need_fp,teacher_features,alpha)
179
+ depth=depth_all['out']
180
+ depth = F.interpolate(depth, size=(h, w), mode="bilinear", align_corners=True)
181
+ depth = F.relu(depth).squeeze(1)
182
+ depth_out['out']=depth
183
+
184
+ return depth_out
185
+
186
+
187
+ class DepthAnything_AC(DPT_DINOv2):
188
+ def __init__(self, config):
189
+ super().__init__(**config)
190
+
191
+
192
+ def get_intermediate_features(self, x):
193
+ """
194
+ Extract intermediate features from the model
195
+
196
+ Args:
197
+ x: Input tensor of shape (B, C, H, W)
198
+
199
+ Returns:
200
+ dict: Dictionary containing intermediate features including:
201
+ - encoder_features: List of encoder feature maps
202
+ - decoder_features: List of decoder feature maps
203
+ - decoder_features_path: List of decoder path features
204
+ - cls_token: List of classification tokens
205
+ """
206
+ features = {
207
+ 'encoder_features': [],
208
+ 'decoder_features': [],
209
+ 'decoder_features_path': [],
210
+ 'cls_token': []
211
+ }
212
+
213
+ h, w = x.shape[-2:]
214
+ patch_h, patch_w = h // 14, w // 14
215
+
216
+ all_features = []
217
+ for i in range(len(self.pretrained.blocks)):
218
+ feat = self.pretrained.get_intermediate_layers(x, [i], return_class_token=True)[0]
219
+ all_features.append(feat)
220
+ if i in [2, 5, 8, 11]:
221
+ feat_map = feat[0]
222
+ B, N, C = feat_map.shape
223
+ H = W = int(np.sqrt(N))
224
+ features['encoder_features'].append(feat_map.reshape(B, H, W, C).permute(0, 3, 1, 2))
225
+
226
+ out_features = []
227
+ for layer_idx in self.intermediate_layer_idx[self.encoder]:
228
+ out_features.append(all_features[layer_idx])
229
+ out = []
230
+ for i, feat in enumerate(out_features):
231
+ if self.depth_head.use_clstoken:
232
+ feat_map, cls_token = feat[0], feat[1]
233
+ readout = cls_token.unsqueeze(1).expand_as(feat_map)
234
+ feat_map = self.depth_head.readout_projects[i](torch.cat((feat_map, readout), -1))
235
+ features['cls_token'].append(cls_token)
236
+ else:
237
+ feat_map = feat[0]
238
+ feat_map = feat_map.permute(0, 2, 1).reshape((feat_map.shape[0], feat_map.shape[-1], patch_h, patch_w)).contiguous()
239
+
240
+ feat_map = self.depth_head.projects[i](feat_map)
241
+ feat_map = self.depth_head.resize_layers[i](feat_map)
242
+
243
+ out.append(feat_map)
244
+
245
+ layer_1, layer_2, layer_3, layer_4 = out
246
+
247
+ layer_1_rn = self.depth_head.scratch.layer1_rn(layer_1)
248
+ layer_2_rn = self.depth_head.scratch.layer2_rn(layer_2)
249
+ layer_3_rn = self.depth_head.scratch.layer3_rn(layer_3)
250
+ layer_4_rn = self.depth_head.scratch.layer4_rn(layer_4)
251
+
252
+ features['decoder_features'].append(layer_1_rn)
253
+ features['decoder_features'].append(layer_2_rn)
254
+ features['decoder_features'].append(layer_3_rn)
255
+ features['decoder_features'].append(layer_4_rn)
256
+
257
+ path_4 = self.depth_head.scratch.refinenet4(layer_4_rn, size=layer_3_rn.shape[2:])
258
+ path_3 = self.depth_head.scratch.refinenet3(path_4, layer_3_rn, size=layer_2_rn.shape[2:])
259
+ path_2 = self.depth_head.scratch.refinenet2(path_3, layer_2_rn, size=layer_1_rn.shape[2:])
260
+ path_1 = self.depth_head.scratch.refinenet1(path_2, layer_1_rn)
261
+
262
+ features['decoder_features_path'].append(path_1)
263
+ features['decoder_features_path'].append(path_2)
264
+ features['decoder_features_path'].append(path_3)
265
+ features['decoder_features_path'].append(path_4)
266
+
267
+ return features
268
+
depth_anything/dpt_teacher.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+
6
+ from depth_anything.util.blocksv1 import FeatureFusionBlock, _make_scratch
7
+
8
+
9
+ def _make_fusion_block(features, use_bn, size = None):
10
+ return FeatureFusionBlock(
11
+ features,
12
+ nn.ReLU(False),
13
+ deconv=False,
14
+ bn=use_bn,
15
+ expand=False,
16
+ align_corners=True,
17
+ size=size,
18
+ )
19
+
20
+
21
+ class DPTHead(nn.Module):
22
+ def __init__(self, nclass, in_channels, features=256, use_bn=False, out_channels=[256, 512, 1024, 1024], use_clstoken=False):
23
+ super(DPTHead, self).__init__()
24
+
25
+ self.nclass = nclass
26
+ self.use_clstoken = use_clstoken
27
+
28
+ self.projects = nn.ModuleList([
29
+ nn.Conv2d(
30
+ in_channels=in_channels,
31
+ out_channels=out_channel,
32
+ kernel_size=1,
33
+ stride=1,
34
+ padding=0,
35
+ ) for out_channel in out_channels
36
+ ])
37
+
38
+ self.resize_layers = nn.ModuleList([
39
+ nn.ConvTranspose2d(
40
+ in_channels=out_channels[0],
41
+ out_channels=out_channels[0],
42
+ kernel_size=4,
43
+ stride=4,
44
+ padding=0),
45
+ nn.ConvTranspose2d(
46
+ in_channels=out_channels[1],
47
+ out_channels=out_channels[1],
48
+ kernel_size=2,
49
+ stride=2,
50
+ padding=0),
51
+ nn.Identity(),
52
+ nn.Conv2d(
53
+ in_channels=out_channels[3],
54
+ out_channels=out_channels[3],
55
+ kernel_size=3,
56
+ stride=2,
57
+ padding=1)
58
+ ])
59
+
60
+ if use_clstoken:
61
+ self.readout_projects = nn.ModuleList()
62
+ for _ in range(len(self.projects)):
63
+ self.readout_projects.append(
64
+ nn.Sequential(
65
+ nn.Linear(2 * in_channels, in_channels),
66
+ nn.GELU()))
67
+
68
+ self.scratch = _make_scratch(
69
+ out_channels,
70
+ features,
71
+ groups=1,
72
+ expand=False,
73
+ )
74
+
75
+ self.scratch.stem_transpose = nn.Identity()
76
+
77
+ self.scratch.refinenet1 = _make_fusion_block(features, use_bn)
78
+ self.scratch.refinenet2 = _make_fusion_block(features, use_bn)
79
+ self.scratch.refinenet3 = _make_fusion_block(features, use_bn)
80
+ self.scratch.refinenet4 = _make_fusion_block(features, use_bn)
81
+
82
+ head_features_1 = features
83
+ head_features_2 = 32
84
+
85
+ if nclass > 1:
86
+ self.scratch.output_conv = nn.Sequential(
87
+ nn.Conv2d(head_features_1, head_features_1, kernel_size=3, stride=1, padding=1),
88
+ nn.ReLU(True),
89
+ nn.Conv2d(head_features_1, nclass, kernel_size=1, stride=1, padding=0),
90
+ )
91
+ else:
92
+ self.scratch.output_conv1 = nn.Conv2d(head_features_1, head_features_1 // 2, kernel_size=3, stride=1, padding=1)
93
+
94
+ self.scratch.output_conv2 = nn.Sequential(
95
+ nn.Conv2d(head_features_1 // 2, head_features_2, kernel_size=3, stride=1, padding=1),
96
+ nn.ReLU(True),
97
+ nn.Conv2d(head_features_2, 1, kernel_size=1, stride=1, padding=0),
98
+ nn.ReLU(True),
99
+ nn.Identity(),
100
+ )
101
+
102
+ def forward(self, out_features, patch_h, patch_w):
103
+ out = []
104
+ for i, x in enumerate(out_features):
105
+ if self.use_clstoken:
106
+ x, cls_token = x[0], x[1]
107
+ readout = cls_token.unsqueeze(1).expand_as(x)
108
+ x = self.readout_projects[i](torch.cat((x, readout), -1))
109
+ else:
110
+ x = x[0]
111
+ x = x.permute(0, 2, 1).reshape((x.shape[0], x.shape[-1], patch_h, patch_w)).contiguous()
112
+
113
+ x = self.projects[i](x)
114
+ x = self.resize_layers[i](x)
115
+
116
+ out.append(x)
117
+
118
+
119
+ layer_1, layer_2, layer_3, layer_4 = out
120
+
121
+ layer_1_rn = self.scratch.layer1_rn(layer_1)
122
+ layer_2_rn = self.scratch.layer2_rn(layer_2)
123
+ layer_3_rn = self.scratch.layer3_rn(layer_3)
124
+ layer_4_rn = self.scratch.layer4_rn(layer_4)
125
+
126
+ path_4 = self.scratch.refinenet4(layer_4_rn, size=layer_3_rn.shape[2:])
127
+ path_3 = self.scratch.refinenet3(path_4, layer_3_rn, size=layer_2_rn.shape[2:])
128
+ path_2 = self.scratch.refinenet2(path_3, layer_2_rn, size=layer_1_rn.shape[2:])
129
+ path_1 = self.scratch.refinenet1(path_2, layer_1_rn)
130
+
131
+ out = self.scratch.output_conv1(path_1)
132
+ out = F.interpolate(out, (int(patch_h * 14), int(patch_w * 14)), mode="bilinear", align_corners=True)
133
+ out = self.scratch.output_conv2(out)
134
+
135
+ return out
136
+
137
+
138
+ class DPT_DINOv2(nn.Module):
139
+ def __init__(self, encoder='vitl', features=256, out_channels=[256, 512, 1024, 1024], use_bn=False, use_clstoken=False, localhub=True):
140
+ super(DPT_DINOv2, self).__init__()
141
+
142
+ assert encoder in ['vits', 'vitb', 'vitl']
143
+
144
+ # in case the Internet connection is not stable, please load the DINOv2 locally
145
+ if localhub:
146
+ self.pretrained = torch.hub.load('torchhub/facebookresearch_dinov2_main', 'dinov2_{:}14'.format(encoder), source='local', pretrained=True)
147
+ else:
148
+ self.pretrained = torch.hub.load('facebookresearch/dinov2', 'dinov2_{:}14'.format(encoder))
149
+
150
+ dim = self.pretrained.blocks[0].attn.qkv.in_features
151
+
152
+ self.depth_head = DPTHead(1, dim, features, use_bn, out_channels=out_channels, use_clstoken=use_clstoken)
153
+
154
+ def forward(self, x):
155
+ h, w = x.shape[-2:]
156
+
157
+ features = self.pretrained.get_intermediate_layers(x, 4, return_class_token=True)
158
+ patch_h, patch_w = h // 14, w // 14
159
+
160
+ depth = self.depth_head(features, patch_h, patch_w)
161
+ depth = F.interpolate(depth, size=(h, w), mode="bilinear", align_corners=True)
162
+ depth = F.relu(depth)
163
+
164
+
165
+ return depth.squeeze(1)
166
+
167
+
168
+ class DepthAnythingTeacher(DPT_DINOv2):
169
+ def __init__(self, config):
170
+ super().__init__(**config)
171
+
172
+
173
+
depth_anything/util/__pycache__/blocksv2.cpython-39.pyc ADDED
Binary file (3.28 kB). View file
 
depth_anything/util/__pycache__/transform.cpython-39.pyc ADDED
Binary file (6.06 kB). View file
 
depth_anything/util/blocksv1.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+
3
+
4
+ def _make_scratch(in_shape, out_shape, groups=1, expand=False):
5
+ scratch = nn.Module()
6
+
7
+ out_shape1 = out_shape
8
+ out_shape2 = out_shape
9
+ out_shape3 = out_shape
10
+ if len(in_shape) >= 4:
11
+ out_shape4 = out_shape
12
+
13
+ if expand:
14
+ out_shape1 = out_shape
15
+ out_shape2 = out_shape*2
16
+ out_shape3 = out_shape*4
17
+ if len(in_shape) >= 4:
18
+ out_shape4 = out_shape*8
19
+
20
+ scratch.layer1_rn = nn.Conv2d(
21
+ in_shape[0], out_shape1, kernel_size=3, stride=1, padding=1, bias=False, groups=groups
22
+ )
23
+ scratch.layer2_rn = nn.Conv2d(
24
+ in_shape[1], out_shape2, kernel_size=3, stride=1, padding=1, bias=False, groups=groups
25
+ )
26
+ scratch.layer3_rn = nn.Conv2d(
27
+ in_shape[2], out_shape3, kernel_size=3, stride=1, padding=1, bias=False, groups=groups
28
+ )
29
+ if len(in_shape) >= 4:
30
+ scratch.layer4_rn = nn.Conv2d(
31
+ in_shape[3], out_shape4, kernel_size=3, stride=1, padding=1, bias=False, groups=groups
32
+ )
33
+
34
+ return scratch
35
+
36
+
37
+ class ResidualConvUnit(nn.Module):
38
+ """Residual convolution module.
39
+ """
40
+
41
+ def __init__(self, features, activation, bn):
42
+ """Init.
43
+
44
+ Args:
45
+ features (int): number of features
46
+ """
47
+ super().__init__()
48
+
49
+ self.bn = bn
50
+
51
+ self.groups=1
52
+
53
+ self.conv1 = nn.Conv2d(
54
+ features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups
55
+ )
56
+
57
+ self.conv2 = nn.Conv2d(
58
+ features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups
59
+ )
60
+
61
+ if self.bn==True:
62
+ self.bn1 = nn.BatchNorm2d(features)
63
+ self.bn2 = nn.BatchNorm2d(features)
64
+
65
+ self.activation = activation
66
+
67
+ self.skip_add = nn.quantized.FloatFunctional()
68
+
69
+ def forward(self, x):
70
+ """Forward pass.
71
+
72
+ Args:
73
+ x (tensor): input
74
+
75
+ Returns:
76
+ tensor: output
77
+ """
78
+
79
+ out = self.activation(x)
80
+ out = self.conv1(out)
81
+ if self.bn==True:
82
+ out = self.bn1(out)
83
+
84
+ out = self.activation(out)
85
+ out = self.conv2(out)
86
+ if self.bn==True:
87
+ out = self.bn2(out)
88
+
89
+ if self.groups > 1:
90
+ out = self.conv_merge(out)
91
+
92
+ return self.skip_add.add(out, x)
93
+
94
+
95
+ class FeatureFusionBlock(nn.Module):
96
+ """Feature fusion block.
97
+ """
98
+
99
+ def __init__(self, features, activation, deconv=False, bn=False, expand=False, align_corners=True, size=None):
100
+ """Init.
101
+
102
+ Args:
103
+ features (int): number of features
104
+ """
105
+ super(FeatureFusionBlock, self).__init__()
106
+
107
+ self.deconv = deconv
108
+ self.align_corners = align_corners
109
+
110
+ self.groups=1
111
+
112
+ self.expand = expand
113
+ out_features = features
114
+ if self.expand==True:
115
+ out_features = features//2
116
+
117
+ self.out_conv = nn.Conv2d(features, out_features, kernel_size=1, stride=1, padding=0, bias=True, groups=1)
118
+
119
+ self.resConfUnit1 = ResidualConvUnit(features, activation, bn)
120
+ self.resConfUnit2 = ResidualConvUnit(features, activation, bn)
121
+
122
+ self.skip_add = nn.quantized.FloatFunctional()
123
+
124
+ self.size=size
125
+
126
+ def forward(self, *xs, size=None):
127
+ """Forward pass.
128
+
129
+ Returns:
130
+ tensor: output
131
+ """
132
+ output = xs[0]
133
+
134
+ if len(xs) == 2:
135
+ res = self.resConfUnit1(xs[1])
136
+ output = self.skip_add.add(output, res)
137
+
138
+ output = self.resConfUnit2(output)
139
+
140
+ if (size is None) and (self.size is None):
141
+ modifier = {"scale_factor": 2}
142
+ elif size is None:
143
+ modifier = {"size": self.size}
144
+ else:
145
+ modifier = {"size": size}
146
+
147
+ output = nn.functional.interpolate(
148
+ output, **modifier, mode="bilinear", align_corners=self.align_corners
149
+ )
150
+
151
+ output = self.out_conv(output)
152
+
153
+ return output
depth_anything/util/blocksv2.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+
3
+
4
+ def _make_scratch(in_shape, out_shape, groups=1, expand=False):
5
+ scratch = nn.Module()
6
+
7
+ out_shape1 = out_shape
8
+ out_shape2 = out_shape
9
+ out_shape3 = out_shape
10
+ if len(in_shape) >= 4:
11
+ out_shape4 = out_shape
12
+
13
+ if expand:
14
+ out_shape1 = out_shape
15
+ out_shape2 = out_shape * 2
16
+ out_shape3 = out_shape * 4
17
+ if len(in_shape) >= 4:
18
+ out_shape4 = out_shape * 8
19
+
20
+ scratch.layer1_rn = nn.Conv2d(in_shape[0], out_shape1, kernel_size=3, stride=1, padding=1, bias=False, groups=groups)
21
+ scratch.layer2_rn = nn.Conv2d(in_shape[1], out_shape2, kernel_size=3, stride=1, padding=1, bias=False, groups=groups)
22
+ scratch.layer3_rn = nn.Conv2d(in_shape[2], out_shape3, kernel_size=3, stride=1, padding=1, bias=False, groups=groups)
23
+ if len(in_shape) >= 4:
24
+ scratch.layer4_rn = nn.Conv2d(in_shape[3], out_shape4, kernel_size=3, stride=1, padding=1, bias=False, groups=groups)
25
+
26
+ return scratch
27
+
28
+
29
+ class ResidualConvUnit(nn.Module):
30
+ """Residual convolution module.
31
+ """
32
+
33
+ def __init__(self, features, activation, bn):
34
+ """Init.
35
+
36
+ Args:
37
+ features (int): number of features
38
+ """
39
+ super().__init__()
40
+
41
+ self.bn = bn
42
+
43
+ self.groups=1
44
+
45
+ self.conv1 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups)
46
+
47
+ self.conv2 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups)
48
+
49
+ if self.bn == True:
50
+ self.bn1 = nn.BatchNorm2d(features)
51
+ self.bn2 = nn.BatchNorm2d(features)
52
+
53
+ self.activation = activation
54
+
55
+ self.skip_add = nn.quantized.FloatFunctional()
56
+
57
+ def forward(self, x):
58
+ """Forward pass.
59
+
60
+ Args:
61
+ x (tensor): input
62
+
63
+ Returns:
64
+ tensor: output
65
+ """
66
+
67
+ out = self.activation(x)
68
+ out = self.conv1(out)
69
+ if self.bn == True:
70
+ out = self.bn1(out)
71
+
72
+ out = self.activation(out)
73
+ out = self.conv2(out)
74
+ if self.bn == True:
75
+ out = self.bn2(out)
76
+
77
+ if self.groups > 1:
78
+ out = self.conv_merge(out)
79
+
80
+ return self.skip_add.add(out, x)
81
+
82
+
83
+ class FeatureFusionBlock(nn.Module):
84
+ """Feature fusion block.
85
+ """
86
+
87
+ def __init__(
88
+ self,
89
+ features,
90
+ activation,
91
+ deconv=False,
92
+ bn=False,
93
+ expand=False,
94
+ align_corners=True,
95
+ size=None
96
+ ):
97
+ """Init.
98
+
99
+ Args:
100
+ features (int): number of features
101
+ """
102
+ super(FeatureFusionBlock, self).__init__()
103
+
104
+ self.deconv = deconv
105
+ self.align_corners = align_corners
106
+
107
+ self.groups=1
108
+
109
+ self.expand = expand
110
+ out_features = features
111
+ if self.expand == True:
112
+ out_features = features // 2
113
+
114
+ self.out_conv = nn.Conv2d(features, out_features, kernel_size=1, stride=1, padding=0, bias=True, groups=1)
115
+
116
+ self.resConfUnit1 = ResidualConvUnit(features, activation, bn)
117
+ self.resConfUnit2 = ResidualConvUnit(features, activation, bn)
118
+
119
+ self.skip_add = nn.quantized.FloatFunctional()
120
+
121
+ self.size=size
122
+
123
+ def forward(self, *xs, size=None):
124
+ """Forward pass.
125
+
126
+ Returns:
127
+ tensor: output
128
+ """
129
+ output = xs[0]
130
+
131
+ if len(xs) == 2:
132
+ res = self.resConfUnit1(xs[1])
133
+ output = self.skip_add.add(output, res)
134
+
135
+ output = self.resConfUnit2(output)
136
+
137
+ if (size is None) and (self.size is None):
138
+ modifier = {"scale_factor": 2}
139
+ elif size is None:
140
+ modifier = {"size": self.size}
141
+ else:
142
+ modifier = {"size": size}
143
+
144
+ output = nn.functional.interpolate(output, **modifier, mode="bilinear", align_corners=self.align_corners)
145
+
146
+ output = self.out_conv(output)
147
+
148
+ return output
depth_anything/util/dformerv2.py ADDED
@@ -0,0 +1,622 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ DFormerv2: Geometry Self-Attention for RGBD Semantic Segmentation
3
+ Code: https://github.com/VCIP-RGBD/DFormer
4
+
5
+ Author: yinbow
6
7
+
8
+ This source code is licensed under the license found in the
9
+ LICENSE file in the root directory of this source tree.
10
+ '''
11
+
12
+ import torch
13
+ import torch.nn as nn
14
+ import torch.nn.functional as F
15
+ import torch.utils.checkpoint as checkpoint
16
+ import math
17
+ from timm.models.layers import DropPath, trunc_normal_
18
+ from typing import List
19
+ from mmengine.runner.checkpoint import load_state_dict
20
+ from mmengine.runner.checkpoint import load_checkpoint
21
+ from typing import Tuple
22
+ import sys
23
+ import os
24
+ from collections import OrderedDict
25
+
26
+ class LayerNorm2d(nn.Module):
27
+ def __init__(self, dim):
28
+ super().__init__()
29
+ self.norm = nn.LayerNorm(dim, eps=1e-6)
30
+
31
+ def forward(self, x: torch.Tensor):
32
+ '''
33
+ input shape (b c h w)
34
+ '''
35
+ x = x.permute(0, 2, 3, 1).contiguous() #(b h w c)
36
+ x = self.norm(x) #(b h w c)
37
+ x = x.permute(0, 3, 1, 2).contiguous()
38
+ return x
39
+
40
+ class PatchEmbed(nn.Module):
41
+ """
42
+ Image to Patch Embedding
43
+ """
44
+
45
+ def __init__(self, in_chans=3, embed_dim=96, norm_layer=None):
46
+ super().__init__()
47
+ self.in_chans = in_chans
48
+ self.embed_dim = embed_dim
49
+
50
+ self.proj = nn.Sequential(
51
+ nn.Conv2d(in_chans, embed_dim//2, 3, 2, 1),
52
+ nn.SyncBatchNorm(embed_dim//2),
53
+ nn.GELU(),
54
+ nn.Conv2d(embed_dim//2, embed_dim//2, 3, 1, 1),
55
+ nn.SyncBatchNorm(embed_dim//2),
56
+ nn.GELU(),
57
+ nn.Conv2d(embed_dim//2, embed_dim, 3, 2, 1),
58
+ nn.SyncBatchNorm(embed_dim),
59
+ nn.GELU(),
60
+ nn.Conv2d(embed_dim, embed_dim, 3, 1, 1),
61
+ nn.SyncBatchNorm(embed_dim)
62
+ )
63
+
64
+ def forward(self, x):
65
+ B, C, H, W = x.shape
66
+ x = self.proj(x).permute(0, 2, 3, 1)
67
+ return x
68
+
69
+ class DWConv2d(nn.Module):
70
+
71
+ def __init__(self, dim, kernel_size, stride, padding):
72
+ super().__init__()
73
+ self.dwconv = nn.Conv2d(dim, dim, kernel_size, stride, padding, groups=dim)
74
+
75
+ def forward(self, x: torch.Tensor):
76
+ '''
77
+ input (b h w c)
78
+ '''
79
+ x = x.permute(0, 3, 1, 2)
80
+ x = self.dwconv(x)
81
+ x = x.permute(0, 2, 3, 1)
82
+ return x
83
+
84
+ class PatchMerging(nn.Module):
85
+ """
86
+ Patch Merging Layer.
87
+ """
88
+ def __init__(self, dim, out_dim, norm_layer=nn.LayerNorm):
89
+ super().__init__()
90
+ self.dim = dim
91
+ self.reduction = nn.Conv2d(dim, out_dim, 3, 2, 1)
92
+ self.norm = nn.SyncBatchNorm(out_dim)
93
+
94
+ def forward(self, x):
95
+ '''
96
+ x: B H W C
97
+ '''
98
+ x = x.permute(0, 3, 1, 2).contiguous() #(b c h w)
99
+ x = self.reduction(x) #(b oc oh ow)
100
+ x = self.norm(x)
101
+ x = x.permute(0, 2, 3, 1) #(b oh ow oc)
102
+ return x
103
+
104
+ def angle_transform(x, sin, cos):
105
+ x1 = x[:, :, :, :, ::2]
106
+ x2 = x[:, :, :, :, 1::2]
107
+ return (x * cos) + (torch.stack([-x2, x1], dim=-1).flatten(-2) * sin)
108
+
109
+ class GeoPriorGen(nn.Module):
110
+
111
+ def __init__(self, embed_dim, num_heads, initial_value, heads_range):
112
+ super().__init__()
113
+ angle = 1.0 / (10000 ** torch.linspace(0, 1, embed_dim // num_heads // 2))
114
+ angle = angle.unsqueeze(-1).repeat(1, 2).flatten()
115
+ self.weight = nn.Parameter(torch.ones(2,1,1,1), requires_grad=True)
116
+ decay = torch.log(1 - 2 ** (-initial_value - heads_range * torch.arange(num_heads, dtype=torch.float) / num_heads))
117
+ self.register_buffer('angle', angle)
118
+ self.register_buffer('decay', decay)
119
+
120
+ def generate_depth_decay(self, H: int, W: int, depth_grid):
121
+ '''
122
+ generate 2d decay mask, the result is (HW)*(HW)
123
+ H, W are the numbers of patches at each column and row
124
+ '''
125
+ B,_,H,W = depth_grid.shape
126
+ grid_d = depth_grid.reshape(B, H*W, 1)
127
+ mask_d = grid_d[:, :, None, :] - grid_d[:, None, :, :]
128
+ mask_d = (mask_d.abs()).sum(dim=-1)
129
+ mask_d = mask_d.unsqueeze(1) * self.decay[None, :, None, None]
130
+ return mask_d
131
+
132
+ def generate_pos_decay(self, H: int, W: int):
133
+ '''
134
+ generate 2d decay mask, the result is (HW)*(HW)
135
+ H, W are the numbers of patches at each column and row
136
+ '''
137
+ index_h = torch.arange(H).to(self.decay)
138
+ index_w = torch.arange(W).to(self.decay)
139
+ grid = torch.meshgrid([index_h, index_w])
140
+ grid = torch.stack(grid, dim=-1).reshape(H*W, 2)
141
+ mask = grid[:, None, :] - grid[None, :, :]
142
+ mask = (mask.abs()).sum(dim=-1)
143
+ mask = mask * self.decay[:, None, None]
144
+ return mask
145
+
146
+ def generate_1d_depth_decay(self, H, W, depth_grid):
147
+ '''
148
+ generate 1d depth decay mask, the result is l*l
149
+ '''
150
+ mask = depth_grid[:, :, :, :, None] - depth_grid[:, :, :, None, :]
151
+ mask = mask.abs()
152
+ mask = mask * self.decay[:, None, None, None]
153
+ assert mask.shape[2:] == (W,H,H)
154
+ return mask
155
+
156
+
157
+ def generate_1d_decay(self, l: int):
158
+ '''
159
+ generate 1d decay mask, the result is l*l
160
+ '''
161
+ index = torch.arange(l).to(self.decay)
162
+ mask = index[:, None] - index[None, :]
163
+ mask = mask.abs()
164
+ mask = mask * self.decay[:, None, None]
165
+ return mask
166
+
167
+ def forward(self, HW_tuple: Tuple[int], depth_map, split_or_not=False):
168
+ '''
169
+ depth_map: depth patches
170
+ HW_tuple: (H, W)
171
+ H * W == l
172
+ '''
173
+ depth_map = F.interpolate(depth_map, size=HW_tuple,mode='bilinear',align_corners=False)
174
+
175
+ if split_or_not:
176
+ index = torch.arange(HW_tuple[0]*HW_tuple[1]).to(self.decay)
177
+ sin = torch.sin(index[:, None] * self.angle[None, :])
178
+ sin = sin.reshape(HW_tuple[0], HW_tuple[1], -1)
179
+ cos = torch.cos(index[:, None] * self.angle[None, :])
180
+ cos = cos.reshape(HW_tuple[0], HW_tuple[1], -1)
181
+
182
+ mask_d_h = self.generate_1d_depth_decay(HW_tuple[0], HW_tuple[1], depth_map.transpose(-2,-1))
183
+ mask_d_w = self.generate_1d_depth_decay(HW_tuple[1], HW_tuple[0], depth_map)
184
+
185
+
186
+ mask_h = self.generate_1d_decay(HW_tuple[0])
187
+ mask_w = self.generate_1d_decay(HW_tuple[1])
188
+
189
+ mask_h = self.weight[0]*mask_h.unsqueeze(0).unsqueeze(2) + self.weight[1]*mask_d_h
190
+ mask_w = self.weight[0]*mask_w.unsqueeze(0).unsqueeze(2) + self.weight[1]*mask_d_w
191
+
192
+
193
+ geo_prior = ((sin, cos), (mask_h, mask_w))
194
+
195
+ else:
196
+ index = torch.arange(HW_tuple[0]*HW_tuple[1]).to(self.decay)
197
+ sin = torch.sin(index[:, None] * self.angle[None, :])
198
+ sin = sin.reshape(HW_tuple[0], HW_tuple[1], -1)
199
+ cos = torch.cos(index[:, None] * self.angle[None, :])
200
+ cos = cos.reshape(HW_tuple[0], HW_tuple[1], -1)
201
+ mask = self.generate_pos_decay(HW_tuple[0], HW_tuple[1])
202
+
203
+ mask_d = self.generate_depth_decay(HW_tuple[0], HW_tuple[1], depth_map)
204
+ mask = (self.weight[0]*mask+self.weight[1]*mask_d)
205
+
206
+ geo_prior = ((sin, cos), mask)
207
+
208
+ return geo_prior
209
+
210
+ class Decomposed_GSA(nn.Module):
211
+
212
+ def __init__(self, embed_dim, num_heads, value_factor=1):
213
+ super().__init__()
214
+ self.factor = value_factor
215
+ self.embed_dim = embed_dim
216
+ self.num_heads = num_heads
217
+ self.head_dim = self.embed_dim * self.factor // num_heads
218
+ self.key_dim = self.embed_dim // num_heads
219
+ self.scaling = self.key_dim ** -0.5
220
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=True)
221
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=True)
222
+ self.v_proj = nn.Linear(embed_dim, embed_dim * self.factor, bias=True)
223
+ self.lepe = DWConv2d(embed_dim, 5, 1, 2)
224
+
225
+ self.out_proj = nn.Linear(embed_dim*self.factor, embed_dim, bias=True)
226
+ self.reset_parameters()
227
+
228
+ def forward(self, x: torch.Tensor, rel_pos, split_or_not=False):
229
+
230
+ bsz, h, w, _ = x.size()
231
+
232
+ (sin, cos), (mask_h, mask_w) = rel_pos
233
+
234
+ q = self.q_proj(x)
235
+ k = self.k_proj(x)
236
+ v = self.v_proj(x)
237
+ lepe = self.lepe(v)
238
+
239
+ k = k * self.scaling
240
+ q = q.view(bsz, h, w, self.num_heads, self.key_dim).permute(0, 3, 1, 2, 4) #(b n h w d1)
241
+ k = k.view(bsz, h, w, self.num_heads, self.key_dim).permute(0, 3, 1, 2, 4) #(b n h w d1)
242
+ qr = angle_transform(q, sin, cos)
243
+ kr = angle_transform(k, sin, cos)
244
+
245
+ qr_w = qr.transpose(1, 2)
246
+ kr_w = kr.transpose(1, 2)
247
+ v = v.reshape(bsz, h, w, self.num_heads, -1).permute(0, 1, 3, 2, 4)
248
+
249
+ qk_mat_w = qr_w @ kr_w.transpose(-1, -2)
250
+ qk_mat_w = qk_mat_w + mask_w.transpose(1,2)
251
+ qk_mat_w = torch.softmax(qk_mat_w, -1)
252
+ v = torch.matmul(qk_mat_w, v)
253
+
254
+
255
+ qr_h = qr.permute(0, 3, 1, 2, 4)
256
+ kr_h = kr.permute(0, 3, 1, 2, 4)
257
+ v = v.permute(0, 3, 2, 1, 4)
258
+
259
+ qk_mat_h = qr_h @ kr_h.transpose(-1, -2)
260
+ qk_mat_h = qk_mat_h + mask_h.transpose(1,2)
261
+ qk_mat_h = torch.softmax(qk_mat_h, -1)
262
+ output = torch.matmul(qk_mat_h, v)
263
+
264
+ output = output.permute(0, 3, 1, 2, 4).flatten(-2, -1)
265
+ output = output + lepe
266
+ output = self.out_proj(output)
267
+ return output
268
+
269
+ def reset_parameters(self):
270
+ nn.init.xavier_normal_(self.q_proj.weight, gain=2 ** -2.5)
271
+ nn.init.xavier_normal_(self.k_proj.weight, gain=2 ** -2.5)
272
+ nn.init.xavier_normal_(self.v_proj.weight, gain=2 ** -2.5)
273
+ nn.init.xavier_normal_(self.out_proj.weight)
274
+ nn.init.constant_(self.out_proj.bias, 0.0)
275
+
276
+ class Full_GSA(nn.Module):
277
+
278
+ def __init__(self, embed_dim, num_heads, value_factor=1):
279
+ super().__init__()
280
+ self.factor = value_factor
281
+ self.embed_dim = embed_dim
282
+ self.num_heads = num_heads
283
+ self.head_dim = self.embed_dim * self.factor // num_heads
284
+ self.key_dim = self.embed_dim // num_heads
285
+ self.scaling = self.key_dim ** -0.5
286
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=True)
287
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=True)
288
+ self.v_proj = nn.Linear(embed_dim, embed_dim * self.factor, bias=True)
289
+ self.lepe = DWConv2d(embed_dim, 5, 1, 2)
290
+ self.out_proj = nn.Linear(embed_dim*self.factor, embed_dim, bias=True)
291
+ self.reset_parameters()
292
+
293
+ def forward(self, x: torch.Tensor, rel_pos, split_or_not=False):
294
+ '''
295
+ x: (b h w c)
296
+ rel_pos: mask: (n l l)
297
+ '''
298
+ bsz, h, w, _ = x.size()
299
+ (sin, cos), mask = rel_pos
300
+ assert h*w == mask.size(3)
301
+ q = self.q_proj(x)
302
+ k = self.k_proj(x)
303
+ v = self.v_proj(x)
304
+ lepe = self.lepe(v)
305
+
306
+ k = k * self.scaling
307
+ q = q.view(bsz, h, w, self.num_heads, -1).permute(0, 3, 1, 2, 4)
308
+ k = k.view(bsz, h, w, self.num_heads, -1).permute(0, 3, 1, 2, 4)
309
+ qr = angle_transform(q, sin, cos)
310
+ kr = angle_transform(k, sin, cos)
311
+
312
+ qr = qr.flatten(2, 3)
313
+ kr = kr.flatten(2, 3)
314
+ vr = v.reshape(bsz, h, w, self.num_heads, -1).permute(0, 3, 1, 2, 4)
315
+ vr = vr.flatten(2, 3)
316
+ qk_mat = qr @ kr.transpose(-1, -2)
317
+ qk_mat = qk_mat + mask
318
+ qk_mat = torch.softmax(qk_mat, -1)
319
+ output = torch.matmul(qk_mat, vr)
320
+ output = output.transpose(1, 2).reshape(bsz, h, w, -1)
321
+ output = output + lepe
322
+ output = self.out_proj(output)
323
+ return output
324
+
325
+ def reset_parameters(self):
326
+ nn.init.xavier_normal_(self.q_proj.weight, gain=2 ** -2.5)
327
+ nn.init.xavier_normal_(self.k_proj.weight, gain=2 ** -2.5)
328
+ nn.init.xavier_normal_(self.v_proj.weight, gain=2 ** -2.5)
329
+ nn.init.xavier_normal_(self.out_proj.weight)
330
+ nn.init.constant_(self.out_proj.bias, 0.0)
331
+
332
+ class FeedForwardNetwork(nn.Module):
333
+ def __init__(
334
+ self,
335
+ embed_dim,
336
+ ffn_dim,
337
+ activation_fn=F.gelu,
338
+ dropout=0.0,
339
+ activation_dropout=0.0,
340
+ layernorm_eps=1e-6,
341
+ subln=False,
342
+ subconv=True
343
+ ):
344
+ super().__init__()
345
+ self.embed_dim = embed_dim
346
+ self.activation_fn = activation_fn
347
+ self.activation_dropout_module = torch.nn.Dropout(activation_dropout)
348
+ self.dropout_module = torch.nn.Dropout(dropout)
349
+ self.fc1 = nn.Linear(self.embed_dim, ffn_dim)
350
+ self.fc2 = nn.Linear(ffn_dim, self.embed_dim)
351
+ self.ffn_layernorm = nn.LayerNorm(ffn_dim, eps=layernorm_eps) if subln else None
352
+ self.dwconv = DWConv2d(ffn_dim, 3, 1, 1) if subconv else None
353
+
354
+ def reset_parameters(self):
355
+ self.fc1.reset_parameters()
356
+ self.fc2.reset_parameters()
357
+ if self.ffn_layernorm is not None:
358
+ self.ffn_layernorm.reset_parameters()
359
+
360
+ def forward(self, x: torch.Tensor):
361
+ '''
362
+ input shape: (b h w c)
363
+ '''
364
+ x = self.fc1(x)
365
+ x = self.activation_fn(x)
366
+ x = self.activation_dropout_module(x)
367
+ residual = x
368
+ if self.dwconv is not None:
369
+ x = self.dwconv(x)
370
+ if self.ffn_layernorm is not None:
371
+ x = self.ffn_layernorm(x)
372
+ x = x + residual
373
+ x = self.fc2(x)
374
+ x = self.dropout_module(x)
375
+ return x
376
+
377
+ class RGBD_Block(nn.Module):
378
+
379
+ def __init__(self, split_or_not: str, embed_dim: int, num_heads: int, ffn_dim: int, drop_path=0., layerscale=False, layer_init_values=1e-5, init_value=2, heads_range=4):
380
+ super().__init__()
381
+ self.layerscale = layerscale
382
+ self.embed_dim = embed_dim
383
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=1e-6)
384
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=1e-6)
385
+ if split_or_not:
386
+ self.Attention = Decomposed_GSA(embed_dim, num_heads)
387
+ else:
388
+ self.Attention = Full_GSA(embed_dim, num_heads)
389
+ self.drop_path = DropPath(drop_path)
390
+ # FFN
391
+ self.ffn = FeedForwardNetwork(embed_dim, ffn_dim)
392
+ self.cnn_pos_encode = DWConv2d(embed_dim, 3, 1, 1)
393
+ # the function to generate the geometry prior for the current block
394
+ self.Geo = GeoPriorGen(embed_dim, num_heads, init_value, heads_range)
395
+
396
+ if layerscale:
397
+ self.gamma_1 = nn.Parameter(layer_init_values * torch.ones(1, 1, 1, embed_dim),requires_grad=True)
398
+ self.gamma_2 = nn.Parameter(layer_init_values * torch.ones(1, 1, 1, embed_dim),requires_grad=True)
399
+
400
+ def forward(
401
+ self,
402
+ x: torch.Tensor,
403
+ x_e: torch.Tensor,
404
+ split_or_not=False
405
+ ):
406
+ x = x + self.cnn_pos_encode(x)
407
+ b, h, w, d = x.size()
408
+
409
+ geo_prior = self.Geo((h, w), x_e, split_or_not=split_or_not)
410
+ if self.layerscale:
411
+ x = x + self.drop_path(self.gamma_1 * self.Attention(self.layer_norm1(x), geo_prior, split_or_not))
412
+ x = x + self.drop_path(self.gamma_2 * self.ffn(self.layer_norm2(x)))
413
+ else:
414
+ x = x + self.drop_path(self.Attention(self.layer_norm1(x), geo_prior, split_or_not))
415
+ x = x + self.drop_path(self.ffn(self.layer_norm2(x)))
416
+ return x
417
+
418
+ class BasicLayer(nn.Module):
419
+ """
420
+ A basic RGB-D layer in DFormerv2.
421
+ """
422
+
423
+ def __init__(self, embed_dim, out_dim, depth, num_heads,
424
+ init_value: float, heads_range: float,
425
+ ffn_dim=96., drop_path=0., norm_layer=nn.LayerNorm, split_or_not=False,
426
+ downsample: PatchMerging=None, use_checkpoint=False,
427
+ layerscale=False, layer_init_values=1e-5):
428
+
429
+ super().__init__()
430
+ self.embed_dim = embed_dim
431
+ self.depth = depth
432
+ self.use_checkpoint = use_checkpoint
433
+ self.split_or_not = split_or_not
434
+
435
+ # build blocks
436
+ self.blocks = nn.ModuleList([
437
+ RGBD_Block(split_or_not, embed_dim, num_heads, ffn_dim,
438
+ drop_path[i] if isinstance(drop_path, list) else drop_path, layerscale, layer_init_values, init_value=init_value, heads_range=heads_range)
439
+ for i in range(depth)])
440
+
441
+ # patch merging layer
442
+ if downsample is not None:
443
+ self.downsample = downsample(dim=embed_dim, out_dim=out_dim, norm_layer=norm_layer)
444
+ else:
445
+ self.downsample = None
446
+
447
+ def forward(self, x, x_e):
448
+ b, h, w, d = x.size()
449
+ for blk in self.blocks:
450
+ if self.use_checkpoint:
451
+ x = checkpoint.checkpoint(blk, x=x, x_e=x_e, split_or_not=self.split_or_not)
452
+ else:
453
+ x = blk(x, x_e, split_or_not=self.split_or_not)
454
+ if self.downsample is not None:
455
+ x_down = self.downsample(x)
456
+ return x, x_down
457
+ else:
458
+ return x, x
459
+
460
+ class dformerv2(nn.Module):
461
+
462
+ def __init__(self, out_indices=(0, 1, 2, 3),
463
+ embed_dims=[64, 128, 256, 512], depths=[2, 2, 8, 2], num_heads=[4, 4, 8, 16],
464
+ init_values=[2, 2, 2, 2], heads_ranges=[4, 4, 6, 6], mlp_ratios=[4, 4, 3, 3], drop_path_rate=0.1, norm_layer=nn.LayerNorm,
465
+ patch_norm=True, use_checkpoint=False, projection=1024, norm_cfg = None,
466
+ layerscales=[False, False, False, False], layer_init_values=1e-6, norm_eval=True):
467
+ super().__init__()
468
+ self.out_indices = out_indices
469
+ self.num_layers = len(depths)
470
+ self.embed_dim = embed_dims[0]
471
+ self.patch_norm = patch_norm
472
+ self.num_features = embed_dims[-1]
473
+ self.mlp_ratios = mlp_ratios
474
+ self.norm_eval = norm_eval
475
+
476
+ # patch embedding
477
+ self.patch_embed = PatchEmbed(in_chans=3, embed_dim=embed_dims[0],
478
+ norm_layer=norm_layer if self.patch_norm else None)
479
+
480
+
481
+ # drop path rate
482
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))]
483
+
484
+ # build layers
485
+ self.layers = nn.ModuleList()
486
+
487
+ for i_layer in range(self.num_layers):
488
+ layer = BasicLayer(
489
+ embed_dim=embed_dims[i_layer],
490
+ out_dim=embed_dims[i_layer+1] if (i_layer < self.num_layers - 1) else None,
491
+ depth=depths[i_layer],
492
+ num_heads=num_heads[i_layer],
493
+ init_value=init_values[i_layer],
494
+ heads_range=heads_ranges[i_layer],
495
+ ffn_dim=int(mlp_ratios[i_layer]*embed_dims[i_layer]),
496
+ drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])],
497
+ norm_layer=norm_layer,
498
+ split_or_not=(i_layer!=3),
499
+ downsample=PatchMerging if (i_layer < self.num_layers - 1) else None,
500
+ use_checkpoint=use_checkpoint,
501
+ layerscale=layerscales[i_layer],
502
+ layer_init_values=layer_init_values
503
+ )
504
+ self.layers.append(layer)
505
+
506
+ self.extra_norms = nn.ModuleList()
507
+ for i in range(3):
508
+ self.extra_norms.append(nn.LayerNorm(embed_dims[i+1]))
509
+
510
+ self.apply(self._init_weights)
511
+
512
+ def _init_weights(self, m):
513
+ if isinstance(m, nn.Linear):
514
+ trunc_normal_(m.weight, std=.02)
515
+ if isinstance(m, nn.Linear) and m.bias is not None:
516
+ nn.init.constant_(m.bias, 0)
517
+ elif isinstance(m, nn.LayerNorm):
518
+ try:
519
+ nn.init.constant_(m.bias, 0)
520
+ nn.init.constant_(m.weight, 1.0)
521
+ except:
522
+ pass
523
+
524
+ def init_weights(self, pretrained=None):
525
+ """Initialize the weights in backbone.
526
+
527
+ Args:
528
+ pretrained (str, optional): Path to pre-trained weights.
529
+ Defaults to None.
530
+ """
531
+
532
+ def _init_weights(m):
533
+ if isinstance(m, nn.Linear):
534
+ trunc_normal_(m.weight, std=.02)
535
+ if isinstance(m, nn.Linear) and m.bias is not None:
536
+ nn.init.constant_(m.bias, 0)
537
+ elif isinstance(m, nn.LayerNorm):
538
+ nn.init.constant_(m.bias, 0)
539
+ nn.init.constant_(m.weight, 1.0)
540
+
541
+ if isinstance(pretrained, str):
542
+ self.apply(_init_weights)
543
+ # logger = get_root_logger()
544
+ _state_dict = torch.load(pretrained)
545
+ if 'model' in _state_dict.keys():
546
+ _state_dict=_state_dict['model']
547
+ if 'state_dict' in _state_dict.keys():
548
+ _state_dict=_state_dict['state_dict']
549
+ state_dict = OrderedDict()
550
+
551
+ for k, v in _state_dict.items():
552
+ if k.startswith('backbone.'):
553
+ state_dict[k[9:]] = v
554
+ else:
555
+ state_dict[k] = v
556
+ print('load '+pretrained)
557
+ load_state_dict(self, state_dict, strict=False)
558
+ # load_checkpoint(self, pretrained, strict=False)
559
+ # load_checkpoint(self, pretrained, strict=False, logger=logger)
560
+ elif pretrained is None:
561
+ self.apply(_init_weights)
562
+ else:
563
+ raise TypeError('pretrained must be a str or None')
564
+
565
+ @torch.jit.ignore
566
+ def no_weight_decay(self):
567
+ return {'absolute_pos_embed'}
568
+
569
+ @torch.jit.ignore
570
+ def no_weight_decay_keywords(self):
571
+ return {'relative_position_bias_table'}
572
+
573
+ def forward(self, x, x_e):
574
+ # rgb input
575
+ x = self.patch_embed(x)
576
+ # depth input
577
+ x_e = x_e[:,0,:,:].unsqueeze(1)
578
+
579
+ outs = []
580
+
581
+ for i in range(self.num_layers):
582
+ layer = self.layers[i]
583
+ x_out, x = layer(x, x_e)
584
+ if i in self.out_indices:
585
+ if i != 0:
586
+ x_out = self.extra_norms[i-1](x_out)
587
+ out = x_out.permute(0, 3, 1, 2).contiguous()
588
+ outs.append(out)
589
+
590
+ return tuple(outs)
591
+
592
+
593
+ def train(self, mode=True):
594
+ """Convert the model into training mode while keep normalization layer
595
+ freezed."""
596
+ super().train(mode)
597
+ if mode and self.norm_eval:
598
+ for m in self.modules():
599
+ # trick: eval have effect on BatchNorm only
600
+ if isinstance(m, nn.BatchNorm2d):
601
+ m.eval()
602
+
603
+ def DFormerv2_S(pretrained=False, **kwargs):
604
+ model = dformerv2(embed_dims=[64, 128, 256, 512], depths=[3, 4, 18, 4], num_heads=[4, 4, 8, 16],
605
+ heads_ranges=[4, 4, 6, 6], **kwargs)
606
+ return model
607
+
608
+ def DFormerv2_B(pretrained=False, **kwargs):
609
+ model = dformerv2(embed_dims=[80, 160, 320, 512], depths=[4, 8, 25, 8], num_heads=[5, 5, 10, 16],
610
+ heads_ranges=[5, 5, 6, 6],
611
+ layerscales=[False, False, True, True],
612
+ layer_init_values=1e-6, **kwargs)
613
+ return model
614
+
615
+ def DFormerv2_L(pretrained=False, **kwargs):
616
+ model = dformerv2(embed_dims=[112, 224, 448, 640], depths=[4, 8, 25, 8], num_heads=[7, 7, 14, 20],
617
+ heads_ranges=[6, 6, 6, 6],
618
+ layerscales=[False, False, True, True],
619
+ layer_init_values=1e-6, **kwargs)
620
+ return model
621
+
622
+
depth_anything/util/priorgenerate.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from typing import Tuple
5
+
6
+
7
+
8
+ class GeoPriorGen(nn.Module):
9
+
10
+ def __init__(self,weight=[0.5,0.5]):
11
+ super().__init__()
12
+ self.weight = weight
13
+
14
+
15
+ def generate_depth_decay(self, H: int, W: int, depth_grid):
16
+ '''
17
+ generate 2d decay mask, the result is (HW)*(HW)
18
+ H, W are the numbers of patches at each column and row
19
+ '''
20
+ B,_,H,W = depth_grid.shape
21
+ grid_d = depth_grid.reshape(B, H*W, 1)
22
+ mask_d = grid_d[:, :, None, :] - grid_d[:, None, :, :]
23
+ mask_d = (mask_d.abs()).sum(dim=-1)
24
+ mask_d = mask_d.unsqueeze(1) * self.decay[None, :, None, None]
25
+ return mask_d
26
+
27
+ def generate_pos_decay(self, H: int, W: int):
28
+ '''
29
+ generate 2d decay mask, the result is (HW)*(HW)
30
+ H, W are the numbers of patches at each column and row
31
+ '''
32
+ index_h = torch.arange(H).to(self.decay)
33
+ index_w = torch.arange(W).to(self.decay)
34
+ grid = torch.meshgrid([index_h, index_w])
35
+ grid = torch.stack(grid, dim=-1).reshape(H*W, 2)
36
+ mask = grid[:, None, :] - grid[None, :, :]
37
+ mask = (mask.abs()).sum(dim=-1)
38
+ mask = mask * self.decay[:, None, None]
39
+ return mask
40
+
41
+ def generate_1d_depth_decay(self, H, W, depth_grid):
42
+ '''
43
+ generate 1d depth decay mask, the result is l*l
44
+ '''
45
+ mask = depth_grid[:, :, :, :, None] - depth_grid[:, :, :, None, :]
46
+ mask = mask.abs()
47
+ mask = mask * self.decay[:, None, None, None]
48
+ assert mask.shape[2:] == (W,H,H)
49
+ return mask
50
+
51
+
52
+ def generate_1d_decay(self, l: int):
53
+ '''
54
+ generate 1d decay mask, the result is l*l
55
+ '''
56
+ index = torch.arange(l).to(self.decay)
57
+ mask = index[:, None] - index[None, :]
58
+ mask = mask.abs()
59
+ mask = mask * self.decay[:, None, None]
60
+ return mask
61
+
62
+ def forward(self, HW_tuple: Tuple[int], depth_map, split_or_not=False):
63
+ '''
64
+ depth_map: depth patches
65
+ HW_tuple: (H, W)
66
+ H * W == l
67
+ '''
68
+ depth_map = F.interpolate(depth_map, size=HW_tuple,mode='bilinear',align_corners=False)
69
+
70
+ if split_or_not:
71
+ index = torch.arange(HW_tuple[0]*HW_tuple[1]).to(self.decay)
72
+ sin = torch.sin(index[:, None] * self.angle[None, :])
73
+ sin = sin.reshape(HW_tuple[0], HW_tuple[1], -1)
74
+ cos = torch.cos(index[:, None] * self.angle[None, :])
75
+ cos = cos.reshape(HW_tuple[0], HW_tuple[1], -1)
76
+
77
+ mask_d_h = self.generate_1d_depth_decay(HW_tuple[0], HW_tuple[1], depth_map.transpose(-2,-1))
78
+ mask_d_w = self.generate_1d_depth_decay(HW_tuple[1], HW_tuple[0], depth_map)
79
+
80
+
81
+ mask_h = self.generate_1d_decay(HW_tuple[0])
82
+ mask_w = self.generate_1d_decay(HW_tuple[1])
83
+
84
+ mask_h = self.weight[0]*mask_h.unsqueeze(0).unsqueeze(2) + self.weight[1]*mask_d_h
85
+ mask_w = self.weight[0]*mask_w.unsqueeze(0).unsqueeze(2) + self.weight[1]*mask_d_w
86
+
87
+
88
+ geo_prior = ((sin, cos), (mask_h, mask_w))
89
+
90
+ else:
91
+ index = torch.arange(HW_tuple[0]*HW_tuple[1]).to(self.decay)
92
+ sin = torch.sin(index[:, None] * self.angle[None, :])
93
+ sin = sin.reshape(HW_tuple[0], HW_tuple[1], -1)
94
+ cos = torch.cos(index[:, None] * self.angle[None, :])
95
+ cos = cos.reshape(HW_tuple[0], HW_tuple[1], -1)
96
+ mask = self.generate_pos_decay(HW_tuple[0], HW_tuple[1])
97
+
98
+ mask_d = self.generate_depth_decay(HW_tuple[0], HW_tuple[1], depth_map)
99
+ mask = (self.weight[0]*mask+self.weight[1]*mask_d)
100
+
101
+ geo_prior = ((sin, cos), mask)
102
+
103
+ return geo_prior
depth_anything/util/transform.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ from PIL import Image, ImageOps, ImageFilter
3
+ import torch
4
+ from torchvision import transforms
5
+ import torch.nn.functional as F
6
+
7
+ import numpy as np
8
+ import cv2
9
+ import math
10
+
11
+
12
+ def apply_min_size(sample, size, image_interpolation_method=cv2.INTER_AREA):
13
+ """Rezise the sample to ensure the given size. Keeps aspect ratio.
14
+
15
+ Args:
16
+ sample (dict): sample
17
+ size (tuple): image size
18
+
19
+ Returns:
20
+ tuple: new size
21
+ """
22
+ shape = list(sample["disparity"].shape)
23
+
24
+ if shape[0] >= size[0] and shape[1] >= size[1]:
25
+ return sample
26
+
27
+ scale = [0, 0]
28
+ scale[0] = size[0] / shape[0]
29
+ scale[1] = size[1] / shape[1]
30
+
31
+ scale = max(scale)
32
+
33
+ shape[0] = math.ceil(scale * shape[0])
34
+ shape[1] = math.ceil(scale * shape[1])
35
+
36
+ # resize
37
+ sample["image"] = cv2.resize(
38
+ sample["image"], tuple(shape[::-1]), interpolation=image_interpolation_method
39
+ )
40
+
41
+ sample["disparity"] = cv2.resize(
42
+ sample["disparity"], tuple(shape[::-1]), interpolation=cv2.INTER_NEAREST
43
+ )
44
+ sample["mask"] = cv2.resize(
45
+ sample["mask"].astype(np.float32),
46
+ tuple(shape[::-1]),
47
+ interpolation=cv2.INTER_NEAREST,
48
+ )
49
+ sample["mask"] = sample["mask"].astype(bool)
50
+
51
+ return tuple(shape)
52
+
53
+
54
+ class Resize(object):
55
+ """Resize sample to given size (width, height).
56
+ """
57
+
58
+ def __init__(
59
+ self,
60
+ width,
61
+ height,
62
+ resize_target=True,
63
+ keep_aspect_ratio=False,
64
+ ensure_multiple_of=1,
65
+ resize_method="lower_bound",
66
+ image_interpolation_method=cv2.INTER_AREA,
67
+ ):
68
+ """Init.
69
+
70
+ Args:
71
+ width (int): desired output width
72
+ height (int): desired output height
73
+ resize_target (bool, optional):
74
+ True: Resize the full sample (image, mask, target).
75
+ False: Resize image only.
76
+ Defaults to True.
77
+ keep_aspect_ratio (bool, optional):
78
+ True: Keep the aspect ratio of the input sample.
79
+ Output sample might not have the given width and height, and
80
+ resize behaviour depends on the parameter 'resize_method'.
81
+ Defaults to False.
82
+ ensure_multiple_of (int, optional):
83
+ Output width and height is constrained to be multiple of this parameter.
84
+ Defaults to 1.
85
+ resize_method (str, optional):
86
+ "lower_bound": Output will be at least as large as the given size.
87
+ "upper_bound": Output will be at max as large as the given size. (Output size might be smaller than given size.)
88
+ "minimal": Scale as least as possible. (Output size might be smaller than given size.)
89
+ Defaults to "lower_bound".
90
+ """
91
+ self.__width = width
92
+ self.__height = height
93
+
94
+ self.__resize_target = resize_target
95
+ self.__keep_aspect_ratio = keep_aspect_ratio
96
+ self.__multiple_of = ensure_multiple_of
97
+ self.__resize_method = resize_method
98
+ self.__image_interpolation_method = image_interpolation_method
99
+
100
+ def constrain_to_multiple_of(self, x, min_val=0, max_val=None):
101
+ y = (np.round(x / self.__multiple_of) * self.__multiple_of).astype(int)
102
+
103
+ if max_val is not None and y > max_val:
104
+ y = (np.floor(x / self.__multiple_of) * self.__multiple_of).astype(int)
105
+
106
+ if y < min_val:
107
+ y = (np.ceil(x / self.__multiple_of) * self.__multiple_of).astype(int)
108
+
109
+ return y
110
+
111
+ def get_size(self, width, height):
112
+ # determine new height and width
113
+ scale_height = self.__height / height
114
+ scale_width = self.__width / width
115
+
116
+ if self.__keep_aspect_ratio:
117
+ if self.__resize_method == "lower_bound":
118
+ # scale such that output size is lower bound
119
+ if scale_width > scale_height:
120
+ # fit width
121
+ scale_height = scale_width
122
+ else:
123
+ # fit height
124
+ scale_width = scale_height
125
+ elif self.__resize_method == "upper_bound":
126
+ # scale such that output size is upper bound
127
+ if scale_width < scale_height:
128
+ # fit width
129
+ scale_height = scale_width
130
+ else:
131
+ # fit height
132
+ scale_width = scale_height
133
+ elif self.__resize_method == "minimal":
134
+ # scale as least as possbile
135
+ if abs(1 - scale_width) < abs(1 - scale_height):
136
+ # fit width
137
+ scale_height = scale_width
138
+ else:
139
+ # fit height
140
+ scale_width = scale_height
141
+ else:
142
+ raise ValueError(
143
+ f"resize_method {self.__resize_method} not implemented"
144
+ )
145
+
146
+ if self.__resize_method == "lower_bound":
147
+ new_height = self.constrain_to_multiple_of(
148
+ scale_height * height, min_val=self.__height
149
+ )
150
+ new_width = self.constrain_to_multiple_of(
151
+ scale_width * width, min_val=self.__width
152
+ )
153
+ elif self.__resize_method == "upper_bound":
154
+ new_height = self.constrain_to_multiple_of(
155
+ scale_height * height, max_val=self.__height
156
+ )
157
+ new_width = self.constrain_to_multiple_of(
158
+ scale_width * width, max_val=self.__width
159
+ )
160
+ elif self.__resize_method == "minimal":
161
+ new_height = self.constrain_to_multiple_of(scale_height * height)
162
+ new_width = self.constrain_to_multiple_of(scale_width * width)
163
+ else:
164
+ raise ValueError(f"resize_method {self.__resize_method} not implemented")
165
+
166
+ return (new_width, new_height)
167
+
168
+ def __call__(self, sample):
169
+ width, height = self.get_size(
170
+ sample["image"].shape[1], sample["image"].shape[0]
171
+ )
172
+
173
+ # resize sample
174
+ sample["image"] = cv2.resize(
175
+ sample["image"],
176
+ (width, height),
177
+ interpolation=self.__image_interpolation_method,
178
+ )
179
+
180
+ if self.__resize_target:
181
+ if "disparity" in sample:
182
+ sample["disparity"] = cv2.resize(
183
+ sample["disparity"],
184
+ (width, height),
185
+ interpolation=cv2.INTER_NEAREST,
186
+ )
187
+
188
+ if "depth" in sample:
189
+ sample["depth"] = cv2.resize(
190
+ sample["depth"], (width, height), interpolation=cv2.INTER_NEAREST
191
+ )
192
+
193
+ if "semseg_mask" in sample:
194
+ # sample["semseg_mask"] = cv2.resize(
195
+ # sample["semseg_mask"], (width, height), interpolation=cv2.INTER_NEAREST
196
+ # )
197
+ sample["semseg_mask"] = F.interpolate(torch.from_numpy(sample["semseg_mask"]).float()[None, None, ...], (height, width), mode='nearest').numpy()[0, 0]
198
+
199
+ if "mask" in sample:
200
+ sample["mask"] = cv2.resize(
201
+ sample["mask"].astype(np.float32),
202
+ (width, height),
203
+ interpolation=cv2.INTER_NEAREST,
204
+ )
205
+ # sample["mask"] = sample["mask"].astype(bool)
206
+
207
+ # print(sample['image'].shape, sample['depth'].shape)
208
+ return sample
209
+
210
+
211
+ class NormalizeImage(object):
212
+ """Normlize image by given mean and std.
213
+ """
214
+
215
+ def __init__(self, mean, std):
216
+ self.__mean = mean
217
+ self.__std = std
218
+
219
+ def __call__(self, sample):
220
+ sample["image"] = (sample["image"] - self.__mean) / self.__std
221
+
222
+ return sample
223
+
224
+
225
+ class PrepareForNet(object):
226
+ """Prepare sample for usage as network input.
227
+ """
228
+
229
+ def __init__(self):
230
+ pass
231
+
232
+ def __call__(self, sample):
233
+ image = np.transpose(sample["image"], (2, 0, 1))
234
+ sample["image"] = np.ascontiguousarray(image).astype(np.float32)
235
+
236
+ if "mask" in sample:
237
+ sample["mask"] = sample["mask"].astype(np.float32)
238
+ sample["mask"] = np.ascontiguousarray(sample["mask"])
239
+
240
+ if "depth" in sample:
241
+ depth = sample["depth"].astype(np.float32)
242
+ sample["depth"] = np.ascontiguousarray(depth)
243
+
244
+ if "semseg_mask" in sample:
245
+ sample["semseg_mask"] = sample["semseg_mask"].astype(np.float32)
246
+ sample["semseg_mask"] = np.ascontiguousarray(sample["semseg_mask"])
247
+
248
+ return sample
requirements.txt ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio==4.44.0
2
+ torch==2.3.0
3
+ torchvision==0.18.0
4
+ torchaudio==2.3.0
5
+ numpy==1.26.4
6
+ opencv-python==4.9.0.80
7
+ Pillow==10.3.0
8
+ matplotlib==3.8.4
9
+ scikit-image==0.24.0
10
+ scikit-learn==1.6.1
11
+ pandas==2.2.3
12
+ scipy==1.13.0
13
+ tqdm==4.66.4
14
+ PyYAML==6.0.1
15
+ tensorboardX==2.6.2.2
16
+ transformers==4.39.0
toyset/1.png ADDED

Git LFS Details

  • SHA256: 6a25ba1f6f86bda9951b6f47bcc8a996f65140530c1f16672a1f07f6f4ece055
  • Pointer size: 131 Bytes
  • Size of remote file: 429 kB
toyset/2.png ADDED

Git LFS Details

  • SHA256: 4a5aa69b49444f60ae482ae904e4e663c0fe77b00aa77123410ec9ad9ae67e39
  • Pointer size: 131 Bytes
  • Size of remote file: 234 kB
toyset/3.png ADDED

Git LFS Details

  • SHA256: 5b09c33944dd9a31159fdcb97f670a7e4697528afe181305ce9e0d71ab1dc7b6
  • Pointer size: 131 Bytes
  • Size of remote file: 540 kB
toyset/4.png ADDED

Git LFS Details

  • SHA256: 2212c2a8562b38130c7be453f35843c77750516ef0710fe762345cc34cbc0dec
  • Pointer size: 131 Bytes
  • Size of remote file: 261 kB
toyset/5.png ADDED

Git LFS Details

  • SHA256: e413743e29d0be695f1edc660f969053eb9c6a307fab86db779d0c84aa0776a9
  • Pointer size: 131 Bytes
  • Size of remote file: 187 kB
toyset/good.png ADDED

Git LFS Details

  • SHA256: f09738a2381bd43ca148cc8df4c980997ba20b23b7cf162d76b7ad50cc102995
  • Pointer size: 131 Bytes
  • Size of remote file: 368 kB
util/__pycache__/dist_helper.cpython-39.pyc ADDED
Binary file (813 Bytes). View file
 
util/__pycache__/utils.cpython-39.pyc ADDED
Binary file (3.57 kB). View file
 
util/__pycache__/visualize_utils.cpython-39.pyc ADDED
Binary file (4.52 kB). View file
 
util/dist_helper.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+
4
+ import torch
5
+ import torch.distributed as dist
6
+
7
+
8
+ def setup_distributed(backend="nccl", port=None):
9
+ """AdaHessian Optimizer
10
+ Lifted from https://github.com/BIGBALLON/distribuuuu/blob/master/distribuuuu/utils.py
11
+ Originally licensed MIT, Copyright (c) 2020 Wei Li
12
+ """
13
+ num_gpus = torch.cuda.device_count()
14
+ rank = int(os.environ["RANK"])
15
+ world_size = int(os.environ["WORLD_SIZE"])
16
+
17
+ torch.cuda.set_device(rank % num_gpus)
18
+
19
+ dist.init_process_group(
20
+ backend=backend,
21
+ world_size=world_size,
22
+ rank=rank,
23
+ )
24
+ return rank, world_size
util/utils.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import logging
3
+ import os
4
+
5
+
6
+ def count_params(model):
7
+ param_num = sum(p.numel() for p in model.parameters())
8
+ return param_num / 1e6
9
+
10
+
11
+ def color_map(dataset='pascal'):
12
+ cmap = np.zeros((256, 3), dtype='uint8')
13
+
14
+ if dataset == 'pascal' or dataset == 'coco':
15
+ def bitget(byteval, idx):
16
+ return (byteval & (1 << idx)) != 0
17
+
18
+ for i in range(256):
19
+ r = g = b = 0
20
+ c = i
21
+ for j in range(8):
22
+ r = r | (bitget(c, 0) << 7-j)
23
+ g = g | (bitget(c, 1) << 7-j)
24
+ b = b | (bitget(c, 2) << 7-j)
25
+ c = c >> 3
26
+
27
+ cmap[i] = np.array([r, g, b])
28
+
29
+ elif dataset == 'cityscapes':
30
+ cmap[0] = np.array([128, 64, 128])
31
+ cmap[1] = np.array([244, 35, 232])
32
+ cmap[2] = np.array([70, 70, 70])
33
+ cmap[3] = np.array([102, 102, 156])
34
+ cmap[4] = np.array([190, 153, 153])
35
+ cmap[5] = np.array([153, 153, 153])
36
+ cmap[6] = np.array([250, 170, 30])
37
+ cmap[7] = np.array([220, 220, 0])
38
+ cmap[8] = np.array([107, 142, 35])
39
+ cmap[9] = np.array([152, 251, 152])
40
+ cmap[10] = np.array([70, 130, 180])
41
+ cmap[11] = np.array([220, 20, 60])
42
+ cmap[12] = np.array([255, 0, 0])
43
+ cmap[13] = np.array([0, 0, 142])
44
+ cmap[14] = np.array([0, 0, 70])
45
+ cmap[15] = np.array([0, 60, 100])
46
+ cmap[16] = np.array([0, 80, 100])
47
+ cmap[17] = np.array([0, 0, 230])
48
+ cmap[18] = np.array([119, 11, 32])
49
+
50
+ return cmap
51
+
52
+
53
+ class AverageMeter(object):
54
+ """Computes and stores the average and current value"""
55
+
56
+ def __init__(self, length=0):
57
+ self.length = length
58
+ self.reset()
59
+
60
+ def reset(self):
61
+ if self.length > 0:
62
+ self.history = []
63
+ else:
64
+ self.count = 0
65
+ self.sum = 0.0
66
+ self.val = 0.0
67
+ self.avg = 0.0
68
+
69
+ def update(self, val, num=1):
70
+ if self.length > 0:
71
+ # currently assert num==1 to avoid bad usage, refine when there are some explict requirements
72
+ assert num == 1
73
+ self.history.append(val)
74
+ if len(self.history) > self.length:
75
+ del self.history[0]
76
+
77
+ self.val = self.history[-1]
78
+ self.avg = np.mean(self.history)
79
+ else:
80
+ self.val = val
81
+ self.sum += val * num
82
+ self.count += num
83
+ self.avg = self.sum / self.count
84
+
85
+
86
+ logs = set()
87
+
88
+
89
+ def init_log(name, level=logging.INFO):
90
+ if (name, level) in logs:
91
+ return
92
+ logs.add((name, level))
93
+ logger = logging.getLogger(name)
94
+ logger.setLevel(level)
95
+ ch = logging.StreamHandler()
96
+ ch.setLevel(level)
97
+ if "SLURM_PROCID" in os.environ:
98
+ rank = int(os.environ["SLURM_PROCID"])
99
+ logger.addFilter(lambda record: rank == 0)
100
+ else:
101
+ rank = 0
102
+ format_str = "[%(asctime)s][%(levelname)8s] %(message)s"
103
+ formatter = logging.Formatter(format_str)
104
+ ch.setFormatter(formatter)
105
+ logger.addHandler(ch)
106
+ return logger
util/visualize_utils.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ import matplotlib.pyplot as plt
4
+ import torch
5
+
6
+ def visualize_geo_prior(img, geo_prior, save_path, batch_idx=0, point_coords=None, normalize=True, alpha=0.6):
7
+ """
8
+ Visualize geometric prior matrix and overlay the result on the original image
9
+ Args:
10
+ img: Original image tensor [B,C,H,W]
11
+ geo_prior: Geometric prior tensor with shape [B,HW,HW]
12
+ save_path: Save path
13
+ batch_idx: Batch index to visualize
14
+ point_coords: Reference point coordinates in format (h, w). If None, center point will be used
15
+ normalize: Whether to normalize the display result
16
+ alpha: Heatmap transparency, 0.0 means completely transparent, 1.0 means completely opaque
17
+ """
18
+ B, HW, _ = geo_prior.shape
19
+ H = int(np.sqrt(HW))
20
+ W = H
21
+ geo_prior_single = geo_prior[batch_idx] # [HW,HW]
22
+
23
+ if point_coords is None:
24
+ center_h, center_w = H // 2, W // 2
25
+ point_idx = center_h * W + center_w
26
+ else:
27
+ h, w = point_coords
28
+ point_idx = h * W + w
29
+ relation = geo_prior_single[point_idx] # [HW]
30
+ relation_map = relation.reshape(H, W)
31
+ relation_np = relation_map.detach().cpu().numpy()
32
+
33
+ if normalize:
34
+ relation_np = (relation_np - relation_np.min()) / (relation_np.max() - relation_np.min() + 1e-6)
35
+
36
+ orig_img = img[batch_idx].detach().cpu().numpy()
37
+ orig_img = np.transpose(orig_img, (1, 2, 0))
38
+ mean = np.array([0.485, 0.456, 0.406])
39
+ std = np.array([0.229, 0.224, 0.225])
40
+ orig_img = std * orig_img + mean
41
+ orig_img = np.clip(orig_img * 255, 0, 255).astype(np.uint8)
42
+ orig_img = cv2.cvtColor(orig_img, cv2.COLOR_RGB2BGR)
43
+
44
+ orig_h, orig_w = orig_img.shape[:2]
45
+
46
+ colored_map = cv2.applyColorMap((relation_np * 255).astype(np.uint8), cv2.COLORMAP_RAINBOW)
47
+ colored_map = cv2.resize(colored_map, (orig_w, orig_h), interpolation=cv2.INTER_LINEAR)
48
+
49
+ overlay = cv2.addWeighted(orig_img, 1-alpha, colored_map, alpha, 0)
50
+
51
+ if point_coords is None:
52
+ center_w_orig = int(center_w * orig_w / W)
53
+ center_h_orig = int(center_h * orig_h / H)
54
+ cv2.drawMarker(overlay, (center_w_orig, center_h_orig), (255, 255, 255), cv2.MARKER_CROSS, 20, 2)
55
+ else:
56
+ w_orig = int(w * orig_w / W)
57
+ h_orig = int(h * orig_h / H)
58
+ cv2.drawMarker(overlay, (w_orig, h_orig), (255, 255, 255), cv2.MARKER_CROSS, 20, 2)
59
+
60
+ cv2.imwrite(save_path.replace('.png', '_overlay.png'), overlay)
61
+
62
+ colored_map = cv2.applyColorMap((relation_np * 255).astype(np.uint8), cv2.COLORMAP_RAINBOW)
63
+ cv2.imwrite(save_path.replace('.png', '_heatmap.png'), colored_map)
64
+ cv2.imwrite(save_path.replace('.png', '_original.png'), orig_img)
65
+
66
+ plt.figure(figsize=(10, 8))
67
+ plt.imshow(relation_np, cmap='rainbow')
68
+ plt.colorbar(label='Geometric Prior Strength')
69
+
70
+ if point_coords is None:
71
+ plt.plot(center_w, center_h, 'w*', markersize=10)
72
+ else:
73
+ plt.plot(w, h, 'w*', markersize=10)
74
+
75
+ plt.title(f'Geometric Prior Visualization (Ref Point: {"center" if point_coords is None else f"({point_coords[0]}, {point_coords[1]})"})')
76
+ plt.savefig(save_path)
77
+ plt.close()
78
+
79
+ return relation_map
80
+
81
+
82
+ def save_feature_visualization(feature_map, save_path):
83
+ """
84
+ Visualize feature map by averaging all feature maps into one image and resize to 518*518
85
+ Args:
86
+ feature_map: feature map tensor with shape [C,H,W]
87
+ save_path: save path
88
+ """
89
+
90
+ if len(feature_map.shape) == 4:
91
+ feature_map = feature_map.squeeze(0)
92
+ mean_feature = torch.mean(feature_map, dim=0).detach().cpu().numpy()
93
+ mean_feature = (mean_feature - mean_feature.min()) / (mean_feature.max() - mean_feature.min() + 1e-6)
94
+ mean_feature = (mean_feature * 255).astype(np.uint8)
95
+ mean_feature = cv2.resize(mean_feature, (518, 518), interpolation=cv2.INTER_LINEAR)
96
+
97
+ colored_feature = cv2.applyColorMap(mean_feature, cv2.COLORMAP_VIRIDIS)
98
+ cv2.imwrite(save_path, colored_feature)
99
+
100
+ def save_depth_visualization(depth_map, filename):
101
+ """
102
+ Save depth map visualization as a colored image.
103
+
104
+ Args:
105
+ depth_map (torch.Tensor): Depth map tensor with shape [H, W] or [B, H, W]
106
+ filename (str): Output file path for the visualization
107
+ """
108
+ depth_norm = (depth_map - depth_map.min()) / (depth_map.max() - depth_map.min()) * 255.0
109
+ depth_norm = depth_norm.detach().cpu().numpy().astype(np.uint8)
110
+ colored_depth = cv2.applyColorMap(depth_norm, cv2.COLORMAP_INFERNO)
111
+ cv2.imwrite(filename, colored_depth)
112
+
113
+ def save_image(img_tensor, filename):
114
+ """
115
+ Save image tensor as a BGR image file.
116
+
117
+ Args:
118
+ img_tensor (torch.Tensor): Image tensor with shape [C, H, W] or [B, C, H, W]
119
+ filename (str): Output file path for the image
120
+ """
121
+ img = img_tensor.detach().cpu().numpy()
122
+
123
+ if img.shape[0] == 3:
124
+ img = np.transpose(img, (1, 2, 0))
125
+ mean = np.array([0.485, 0.456, 0.406])
126
+ std = np.array([0.229, 0.224, 0.225])
127
+ img = std * img + mean
128
+ img = np.clip(img * 255, 0, 255).astype(np.uint8)
129
+ img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
130
+ cv2.imwrite(filename, img)