Spaces:
Running
on
Zero
Running
on
Zero
xiank he
commited on
Commit
·
33a65b5
1
Parent(s):
166cff2
distill-any-depth
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- app.py +68 -0
- geobench/depth_anything_v2/__pycache__/dinov2.cpython-310.pyc +0 -0
- geobench/depth_anything_v2/__pycache__/dpt.cpython-310.pyc +0 -0
- geobench/depth_anything_v2/dinov2.py +415 -0
- geobench/depth_anything_v2/dinov2_layers/__init__.py +11 -0
- geobench/depth_anything_v2/dinov2_layers/__pycache__/__init__.cpython-310.pyc +0 -0
- geobench/depth_anything_v2/dinov2_layers/__pycache__/attention.cpython-310.pyc +0 -0
- geobench/depth_anything_v2/dinov2_layers/__pycache__/block.cpython-310.pyc +0 -0
- geobench/depth_anything_v2/dinov2_layers/__pycache__/drop_path.cpython-310.pyc +0 -0
- geobench/depth_anything_v2/dinov2_layers/__pycache__/layer_scale.cpython-310.pyc +0 -0
- geobench/depth_anything_v2/dinov2_layers/__pycache__/mlp.cpython-310.pyc +0 -0
- geobench/depth_anything_v2/dinov2_layers/__pycache__/patch_embed.cpython-310.pyc +0 -0
- geobench/depth_anything_v2/dinov2_layers/__pycache__/swiglu_ffn.cpython-310.pyc +0 -0
- geobench/depth_anything_v2/dinov2_layers/attention.py +83 -0
- geobench/depth_anything_v2/dinov2_layers/block.py +252 -0
- geobench/depth_anything_v2/dinov2_layers/drop_path.py +35 -0
- geobench/depth_anything_v2/dinov2_layers/layer_scale.py +28 -0
- geobench/depth_anything_v2/dinov2_layers/mlp.py +41 -0
- geobench/depth_anything_v2/dinov2_layers/patch_embed.py +89 -0
- geobench/depth_anything_v2/dinov2_layers/swiglu_ffn.py +63 -0
- geobench/depth_anything_v2/dpt.py +230 -0
- geobench/depth_anything_v2/util/__pycache__/blocks.cpython-310.pyc +0 -0
- geobench/depth_anything_v2/util/__pycache__/transform.cpython-310.pyc +0 -0
- geobench/depth_anything_v2/util/blocks.py +148 -0
- geobench/depth_anything_v2/util/transform.py +158 -0
- geobench/midas/__pycache__/base_model.cpython-310.pyc +0 -0
- geobench/midas/__pycache__/blocks.cpython-310.pyc +0 -0
- geobench/midas/__pycache__/dpt_depth.cpython-310.pyc +0 -0
- geobench/midas/__pycache__/midas_net.cpython-310.pyc +0 -0
- geobench/midas/__pycache__/midas_net_custom.cpython-310.pyc +0 -0
- geobench/midas/__pycache__/model_loader.cpython-310.pyc +0 -0
- geobench/midas/__pycache__/transforms.cpython-310.pyc +0 -0
- geobench/midas/backbones/__pycache__/beit.cpython-310.pyc +0 -0
- geobench/midas/backbones/__pycache__/levit.cpython-310.pyc +0 -0
- geobench/midas/backbones/__pycache__/swin.cpython-310.pyc +0 -0
- geobench/midas/backbones/__pycache__/swin2.cpython-310.pyc +0 -0
- geobench/midas/backbones/__pycache__/swin_common.cpython-310.pyc +0 -0
- geobench/midas/backbones/__pycache__/utils.cpython-310.pyc +0 -0
- geobench/midas/backbones/__pycache__/vit.cpython-310.pyc +0 -0
- geobench/midas/backbones/beit.py +196 -0
- geobench/midas/backbones/levit.py +106 -0
- geobench/midas/backbones/next_vit.py +39 -0
- geobench/midas/backbones/swin.py +13 -0
- geobench/midas/backbones/swin2.py +34 -0
- geobench/midas/backbones/swin_common.py +52 -0
- geobench/midas/backbones/utils.py +249 -0
- geobench/midas/backbones/vit.py +221 -0
- geobench/midas/base_model.py +17 -0
- geobench/midas/blocks.py +439 -0
- geobench/midas/dpt_depth.py +166 -0
app.py
ADDED
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import torch
|
3 |
+
from PIL import Image
|
4 |
+
import cv2
|
5 |
+
import numpy as np
|
6 |
+
from geobench.modeling.archs.dam.dam import DepthAnything
|
7 |
+
from geobench.utils.image_util import colorize_depth_maps
|
8 |
+
from geobench.midas.transforms import Resize, NormalizeImage, PrepareForNet
|
9 |
+
from torchvision.transforms import Compose
|
10 |
+
import os
|
11 |
+
|
12 |
+
# Helper function to load model (same as your original code)
|
13 |
+
def load_model_by_name(arch_name, checkpoint_path, device):
|
14 |
+
if arch_name == 'depthanything':
|
15 |
+
if '.safetensors' in checkpoint_path:
|
16 |
+
model = DepthAnything.from_pretrained(os.path.dirname(checkpoint_path)).to(device)
|
17 |
+
else:
|
18 |
+
raise NotImplementedError("Model architecture not implemented.")
|
19 |
+
else:
|
20 |
+
raise NotImplementedError(f"Unknown architecture: {arch_name}")
|
21 |
+
return model
|
22 |
+
|
23 |
+
# Image processing function (same as your original code, modified for Gradio)
|
24 |
+
def process_image(image, model, device, mode='rel_depth'):
|
25 |
+
# Preprocess the image
|
26 |
+
image_np = np.array(image)[..., ::-1] / 255
|
27 |
+
transform = Compose([
|
28 |
+
Resize(512, 512, resize_target=None, keep_aspect_ratio=False, ensure_multiple_of=32, image_interpolation_method=cv2.INTER_CUBIC),
|
29 |
+
NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
|
30 |
+
PrepareForNet()
|
31 |
+
])
|
32 |
+
|
33 |
+
image_tensor = transform({'image': image_np})['image']
|
34 |
+
image_tensor = torch.from_numpy(image_tensor).unsqueeze(0).to(device)
|
35 |
+
|
36 |
+
with torch.no_grad(): # Disable autograd since we don't need gradients on CPU
|
37 |
+
pred_disp, _ = model(image_tensor)
|
38 |
+
pred_disp_np = pred_disp.cpu().detach().numpy()[0, :, :, :].transpose(1, 2, 0)
|
39 |
+
pred_disp = (pred_disp_np - pred_disp_np.min()) / (pred_disp_np.max() - pred_disp_np.min())
|
40 |
+
|
41 |
+
# Colorize depth map
|
42 |
+
cmap = "Spectral_r" if mode != 'metric' else 'Spectral_r'
|
43 |
+
depth_colored = colorize_depth_maps(pred_disp[None, ...], 0, 1, cmap=cmap).squeeze()
|
44 |
+
depth_colored = (depth_colored * 255).astype(np.uint8)
|
45 |
+
|
46 |
+
depth_image = Image.fromarray(depth_colored)
|
47 |
+
return depth_image
|
48 |
+
|
49 |
+
# Gradio interface function
|
50 |
+
def gradio_interface(image, mode='rel_depth'):
|
51 |
+
# Set device to CPU explicitly
|
52 |
+
device = torch.device("cpu") # Force using CPU
|
53 |
+
model = load_model_by_name("depthanything", "your_checkpoint_path_here", device)
|
54 |
+
|
55 |
+
# Process image and return output
|
56 |
+
return process_image(image, model, device, mode)
|
57 |
+
|
58 |
+
# Create Gradio interface
|
59 |
+
iface = gr.Interface(
|
60 |
+
fn=gradio_interface,
|
61 |
+
inputs=[gr.Image(type="pil"), gr.Dropdown(choices=['rel_depth', 'metric_depth', 'disparity'], label="Mode")],
|
62 |
+
outputs=gr.Image(type="pil"),
|
63 |
+
title="Depth Estimation Demo",
|
64 |
+
description="Upload an image to see the depth estimation results."
|
65 |
+
)
|
66 |
+
|
67 |
+
# Launch the Gradio interface
|
68 |
+
iface.launch()
|
geobench/depth_anything_v2/__pycache__/dinov2.cpython-310.pyc
ADDED
Binary file (12.2 kB). View file
|
|
geobench/depth_anything_v2/__pycache__/dpt.cpython-310.pyc
ADDED
Binary file (6.17 kB). View file
|
|
geobench/depth_anything_v2/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 |
+
)
|
geobench/depth_anything_v2/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
|
geobench/depth_anything_v2/dinov2_layers/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (423 Bytes). View file
|
|
geobench/depth_anything_v2/dinov2_layers/__pycache__/attention.cpython-310.pyc
ADDED
Binary file (2.39 kB). View file
|
|
geobench/depth_anything_v2/dinov2_layers/__pycache__/block.cpython-310.pyc
ADDED
Binary file (8 kB). View file
|
|
geobench/depth_anything_v2/dinov2_layers/__pycache__/drop_path.cpython-310.pyc
ADDED
Binary file (1.22 kB). View file
|
|
geobench/depth_anything_v2/dinov2_layers/__pycache__/layer_scale.cpython-310.pyc
ADDED
Binary file (1.03 kB). View file
|
|
geobench/depth_anything_v2/dinov2_layers/__pycache__/mlp.cpython-310.pyc
ADDED
Binary file (1.22 kB). View file
|
|
geobench/depth_anything_v2/dinov2_layers/__pycache__/patch_embed.cpython-310.pyc
ADDED
Binary file (2.67 kB). View file
|
|
geobench/depth_anything_v2/dinov2_layers/__pycache__/swiglu_ffn.cpython-310.pyc
ADDED
Binary file (2.02 kB). View file
|
|
geobench/depth_anything_v2/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 |
+
|
geobench/depth_anything_v2/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
|
geobench/depth_anything_v2/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)
|
geobench/depth_anything_v2/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
|
geobench/depth_anything_v2/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
|
geobench/depth_anything_v2/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
|
geobench/depth_anything_v2/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 |
+
)
|
geobench/depth_anything_v2/dpt.py
ADDED
@@ -0,0 +1,230 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import cv2
|
2 |
+
import torch
|
3 |
+
import torch.nn as nn
|
4 |
+
import torch.nn.functional as F
|
5 |
+
from torchvision.transforms import Compose
|
6 |
+
|
7 |
+
from .dinov2 import DINOv2
|
8 |
+
from .util.blocks import FeatureFusionBlock, _make_scratch
|
9 |
+
from .util.transform import Resize, NormalizeImage, PrepareForNet
|
10 |
+
from huggingface_hub import PyTorchModelHubMixin, hf_hub_download
|
11 |
+
from geobench.modeling.necks.image_projector import ImageProjModel
|
12 |
+
|
13 |
+
|
14 |
+
def _make_fusion_block(features, use_bn, size=None):
|
15 |
+
return FeatureFusionBlock(
|
16 |
+
features,
|
17 |
+
nn.ReLU(False),
|
18 |
+
deconv=False,
|
19 |
+
bn=use_bn,
|
20 |
+
expand=False,
|
21 |
+
align_corners=True,
|
22 |
+
size=size,
|
23 |
+
)
|
24 |
+
|
25 |
+
|
26 |
+
class ConvBlock(nn.Module):
|
27 |
+
def __init__(self, in_feature, out_feature):
|
28 |
+
super().__init__()
|
29 |
+
|
30 |
+
self.conv_block = nn.Sequential(
|
31 |
+
nn.Conv2d(in_feature, out_feature, kernel_size=3, stride=1, padding=1),
|
32 |
+
nn.BatchNorm2d(out_feature),
|
33 |
+
nn.ReLU(True)
|
34 |
+
)
|
35 |
+
|
36 |
+
def forward(self, x):
|
37 |
+
return self.conv_block(x)
|
38 |
+
|
39 |
+
|
40 |
+
class DPTHead(nn.Module):
|
41 |
+
def __init__(
|
42 |
+
self,
|
43 |
+
in_channels,
|
44 |
+
features=256,
|
45 |
+
use_bn=False,
|
46 |
+
out_channels=[256, 512, 1024, 1024],
|
47 |
+
use_clstoken=False
|
48 |
+
):
|
49 |
+
super(DPTHead, self).__init__()
|
50 |
+
|
51 |
+
self.use_clstoken = use_clstoken
|
52 |
+
|
53 |
+
self.projects = nn.ModuleList([
|
54 |
+
nn.Conv2d(
|
55 |
+
in_channels=in_channels,
|
56 |
+
out_channels=out_channel,
|
57 |
+
kernel_size=1,
|
58 |
+
stride=1,
|
59 |
+
padding=0,
|
60 |
+
) for out_channel in out_channels
|
61 |
+
])
|
62 |
+
|
63 |
+
self.resize_layers = nn.ModuleList([
|
64 |
+
nn.ConvTranspose2d(
|
65 |
+
in_channels=out_channels[0],
|
66 |
+
out_channels=out_channels[0],
|
67 |
+
kernel_size=4,
|
68 |
+
stride=4,
|
69 |
+
padding=0),
|
70 |
+
nn.ConvTranspose2d(
|
71 |
+
in_channels=out_channels[1],
|
72 |
+
out_channels=out_channels[1],
|
73 |
+
kernel_size=2,
|
74 |
+
stride=2,
|
75 |
+
padding=0),
|
76 |
+
nn.Identity(),
|
77 |
+
nn.Conv2d(
|
78 |
+
in_channels=out_channels[3],
|
79 |
+
out_channels=out_channels[3],
|
80 |
+
kernel_size=3,
|
81 |
+
stride=2,
|
82 |
+
padding=1)
|
83 |
+
])
|
84 |
+
|
85 |
+
if use_clstoken:
|
86 |
+
self.readout_projects = nn.ModuleList()
|
87 |
+
for _ in range(len(self.projects)):
|
88 |
+
self.readout_projects.append(
|
89 |
+
nn.Sequential(
|
90 |
+
nn.Linear(2 * in_channels, in_channels),
|
91 |
+
nn.GELU()))
|
92 |
+
|
93 |
+
self.scratch = _make_scratch(
|
94 |
+
out_channels,
|
95 |
+
features,
|
96 |
+
groups=1,
|
97 |
+
expand=False,
|
98 |
+
)
|
99 |
+
|
100 |
+
self.scratch.stem_transpose = None
|
101 |
+
|
102 |
+
self.scratch.refinenet1 = _make_fusion_block(features, use_bn)
|
103 |
+
self.scratch.refinenet2 = _make_fusion_block(features, use_bn)
|
104 |
+
self.scratch.refinenet3 = _make_fusion_block(features, use_bn)
|
105 |
+
self.scratch.refinenet4 = _make_fusion_block(features, use_bn)
|
106 |
+
|
107 |
+
head_features_1 = features
|
108 |
+
head_features_2 = 32
|
109 |
+
|
110 |
+
self.scratch.output_conv1 = nn.Conv2d(head_features_1, head_features_1 // 2, kernel_size=3, stride=1, padding=1)
|
111 |
+
self.scratch.output_conv2 = nn.Sequential(
|
112 |
+
nn.Conv2d(head_features_1 // 2, head_features_2, kernel_size=3, stride=1, padding=1),
|
113 |
+
nn.ReLU(True),
|
114 |
+
nn.Conv2d(head_features_2, 1, kernel_size=1, stride=1, padding=0),
|
115 |
+
nn.ReLU(True),
|
116 |
+
nn.Identity(),
|
117 |
+
)
|
118 |
+
|
119 |
+
def forward(self, out_features, patch_h, patch_w):
|
120 |
+
out = []
|
121 |
+
for i, x in enumerate(out_features):
|
122 |
+
if self.use_clstoken:
|
123 |
+
x, cls_token = x[0], x[1]
|
124 |
+
readout = cls_token.unsqueeze(1).expand_as(x)
|
125 |
+
x = self.readout_projects[i](torch.cat((x, readout), -1))
|
126 |
+
else:
|
127 |
+
x = x[0]
|
128 |
+
|
129 |
+
x = x.permute(0, 2, 1).reshape((x.shape[0], x.shape[-1], patch_h, patch_w))
|
130 |
+
|
131 |
+
x = self.projects[i](x)
|
132 |
+
x = self.resize_layers[i](x)
|
133 |
+
|
134 |
+
out.append(x)
|
135 |
+
|
136 |
+
layer_1, layer_2, layer_3, layer_4 = out
|
137 |
+
|
138 |
+
layer_1_rn = self.scratch.layer1_rn(layer_1)
|
139 |
+
layer_2_rn = self.scratch.layer2_rn(layer_2)
|
140 |
+
layer_3_rn = self.scratch.layer3_rn(layer_3)
|
141 |
+
layer_4_rn = self.scratch.layer4_rn(layer_4)
|
142 |
+
|
143 |
+
path_4 = self.scratch.refinenet4(layer_4_rn, size=layer_3_rn.shape[2:])
|
144 |
+
path_3 = self.scratch.refinenet3(path_4, layer_3_rn, size=layer_2_rn.shape[2:])
|
145 |
+
path_2 = self.scratch.refinenet2(path_3, layer_2_rn, size=layer_1_rn.shape[2:])
|
146 |
+
path_1 = self.scratch.refinenet1(path_2, layer_1_rn)
|
147 |
+
|
148 |
+
out = self.scratch.output_conv1(path_1)
|
149 |
+
out = F.interpolate(out, (int(patch_h * 14), int(patch_w * 14)), mode="bilinear", align_corners=True)
|
150 |
+
out = self.scratch.output_conv2(out)
|
151 |
+
|
152 |
+
return out
|
153 |
+
|
154 |
+
|
155 |
+
class DepthAnythingV2(nn.Module, PyTorchModelHubMixin):
|
156 |
+
def __init__(
|
157 |
+
self,
|
158 |
+
encoder='vitl',
|
159 |
+
features=256,
|
160 |
+
out_channels=[256, 512, 1024, 1024],
|
161 |
+
use_bn=False,
|
162 |
+
use_clstoken=False
|
163 |
+
):
|
164 |
+
super(DepthAnythingV2, self).__init__()
|
165 |
+
|
166 |
+
self.intermediate_layer_idx = {
|
167 |
+
'vits': [2, 5, 8, 11],
|
168 |
+
'vitb': [2, 5, 8, 11],
|
169 |
+
'vitl': [4, 11, 17, 23],
|
170 |
+
'vitg': [9, 19, 29, 39]
|
171 |
+
}
|
172 |
+
|
173 |
+
self.encoder = encoder
|
174 |
+
self.pretrained = DINOv2(model_name=encoder)
|
175 |
+
# self.proj = ImageProjModel()
|
176 |
+
|
177 |
+
self.depth_head = DPTHead(self.pretrained.embed_dim, features, use_bn, out_channels=out_channels, use_clstoken=use_clstoken)
|
178 |
+
|
179 |
+
def forward(self, x):
|
180 |
+
bs, _, h, w = x.shape
|
181 |
+
|
182 |
+
patch_h, patch_w = x.shape[-2] // 14, x.shape[-1] // 14
|
183 |
+
|
184 |
+
features = self.pretrained.get_intermediate_layers(x, self.intermediate_layer_idx[self.encoder], return_class_token=True)
|
185 |
+
# features_output = self.proj(features[3][0])
|
186 |
+
|
187 |
+
depth = self.depth_head(features, patch_h, patch_w)
|
188 |
+
# depth = F.interpolate(depth, size=(h, w), mode="bilinear", align_corners=True)
|
189 |
+
|
190 |
+
depth = F.relu(depth)
|
191 |
+
# import pdb; pdb.set_trace()
|
192 |
+
# return depth.squeeze(1), features[3][0]
|
193 |
+
return depth, features[3][0]
|
194 |
+
|
195 |
+
@torch.no_grad()
|
196 |
+
def infer_image(self, raw_image, input_size=518):
|
197 |
+
image, (h, w) = self.image2tensor(raw_image, input_size)
|
198 |
+
|
199 |
+
depth = self.forward(image)
|
200 |
+
|
201 |
+
depth = F.interpolate(depth[:, None], (h, w), mode="bilinear", align_corners=True)[0, 0]
|
202 |
+
|
203 |
+
return depth.cpu().numpy()
|
204 |
+
|
205 |
+
def image2tensor(self, raw_image, input_size=518):
|
206 |
+
transform = Compose([
|
207 |
+
Resize(
|
208 |
+
width=input_size,
|
209 |
+
height=input_size,
|
210 |
+
resize_target=False,
|
211 |
+
keep_aspect_ratio=True,
|
212 |
+
ensure_multiple_of=14,
|
213 |
+
resize_method='lower_bound',
|
214 |
+
image_interpolation_method=cv2.INTER_CUBIC,
|
215 |
+
),
|
216 |
+
NormalizeImage(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
217 |
+
PrepareForNet(),
|
218 |
+
])
|
219 |
+
|
220 |
+
h, w = raw_image.shape[:2]
|
221 |
+
|
222 |
+
image = cv2.cvtColor(raw_image, cv2.COLOR_BGR2RGB) / 255.0
|
223 |
+
|
224 |
+
image = transform({'image': image})['image']
|
225 |
+
image = torch.from_numpy(image).unsqueeze(0)
|
226 |
+
|
227 |
+
DEVICE = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
|
228 |
+
image = image.to(DEVICE)
|
229 |
+
|
230 |
+
return image, (h, w)
|
geobench/depth_anything_v2/util/__pycache__/blocks.cpython-310.pyc
ADDED
Binary file (3.29 kB). View file
|
|
geobench/depth_anything_v2/util/__pycache__/transform.cpython-310.pyc
ADDED
Binary file (4.73 kB). View file
|
|
geobench/depth_anything_v2/util/blocks.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
|
geobench/depth_anything_v2/util/transform.py
ADDED
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import cv2
|
3 |
+
|
4 |
+
|
5 |
+
class Resize(object):
|
6 |
+
"""Resize sample to given size (width, height).
|
7 |
+
"""
|
8 |
+
|
9 |
+
def __init__(
|
10 |
+
self,
|
11 |
+
width,
|
12 |
+
height,
|
13 |
+
resize_target=True,
|
14 |
+
keep_aspect_ratio=False,
|
15 |
+
ensure_multiple_of=1,
|
16 |
+
resize_method="lower_bound",
|
17 |
+
image_interpolation_method=cv2.INTER_AREA,
|
18 |
+
):
|
19 |
+
"""Init.
|
20 |
+
|
21 |
+
Args:
|
22 |
+
width (int): desired output width
|
23 |
+
height (int): desired output height
|
24 |
+
resize_target (bool, optional):
|
25 |
+
True: Resize the full sample (image, mask, target).
|
26 |
+
False: Resize image only.
|
27 |
+
Defaults to True.
|
28 |
+
keep_aspect_ratio (bool, optional):
|
29 |
+
True: Keep the aspect ratio of the input sample.
|
30 |
+
Output sample might not have the given width and height, and
|
31 |
+
resize behaviour depends on the parameter 'resize_method'.
|
32 |
+
Defaults to False.
|
33 |
+
ensure_multiple_of (int, optional):
|
34 |
+
Output width and height is constrained to be multiple of this parameter.
|
35 |
+
Defaults to 1.
|
36 |
+
resize_method (str, optional):
|
37 |
+
"lower_bound": Output will be at least as large as the given size.
|
38 |
+
"upper_bound": Output will be at max as large as the given size. (Output size might be smaller than given size.)
|
39 |
+
"minimal": Scale as least as possible. (Output size might be smaller than given size.)
|
40 |
+
Defaults to "lower_bound".
|
41 |
+
"""
|
42 |
+
self.__width = width
|
43 |
+
self.__height = height
|
44 |
+
|
45 |
+
self.__resize_target = resize_target
|
46 |
+
self.__keep_aspect_ratio = keep_aspect_ratio
|
47 |
+
self.__multiple_of = ensure_multiple_of
|
48 |
+
self.__resize_method = resize_method
|
49 |
+
self.__image_interpolation_method = image_interpolation_method
|
50 |
+
|
51 |
+
def constrain_to_multiple_of(self, x, min_val=0, max_val=None):
|
52 |
+
y = (np.round(x / self.__multiple_of) * self.__multiple_of).astype(int)
|
53 |
+
|
54 |
+
if max_val is not None and y > max_val:
|
55 |
+
y = (np.floor(x / self.__multiple_of) * self.__multiple_of).astype(int)
|
56 |
+
|
57 |
+
if y < min_val:
|
58 |
+
y = (np.ceil(x / self.__multiple_of) * self.__multiple_of).astype(int)
|
59 |
+
|
60 |
+
return y
|
61 |
+
|
62 |
+
def get_size(self, width, height):
|
63 |
+
# determine new height and width
|
64 |
+
scale_height = self.__height / height
|
65 |
+
scale_width = self.__width / width
|
66 |
+
|
67 |
+
if self.__keep_aspect_ratio:
|
68 |
+
if self.__resize_method == "lower_bound":
|
69 |
+
# scale such that output size is lower bound
|
70 |
+
if scale_width > scale_height:
|
71 |
+
# fit width
|
72 |
+
scale_height = scale_width
|
73 |
+
else:
|
74 |
+
# fit height
|
75 |
+
scale_width = scale_height
|
76 |
+
elif self.__resize_method == "upper_bound":
|
77 |
+
# scale such that output size is upper bound
|
78 |
+
if scale_width < scale_height:
|
79 |
+
# fit width
|
80 |
+
scale_height = scale_width
|
81 |
+
else:
|
82 |
+
# fit height
|
83 |
+
scale_width = scale_height
|
84 |
+
elif self.__resize_method == "minimal":
|
85 |
+
# scale as least as possbile
|
86 |
+
if abs(1 - scale_width) < abs(1 - scale_height):
|
87 |
+
# fit width
|
88 |
+
scale_height = scale_width
|
89 |
+
else:
|
90 |
+
# fit height
|
91 |
+
scale_width = scale_height
|
92 |
+
else:
|
93 |
+
raise ValueError(f"resize_method {self.__resize_method} not implemented")
|
94 |
+
|
95 |
+
if self.__resize_method == "lower_bound":
|
96 |
+
new_height = self.constrain_to_multiple_of(scale_height * height, min_val=self.__height)
|
97 |
+
new_width = self.constrain_to_multiple_of(scale_width * width, min_val=self.__width)
|
98 |
+
elif self.__resize_method == "upper_bound":
|
99 |
+
new_height = self.constrain_to_multiple_of(scale_height * height, max_val=self.__height)
|
100 |
+
new_width = self.constrain_to_multiple_of(scale_width * width, max_val=self.__width)
|
101 |
+
elif self.__resize_method == "minimal":
|
102 |
+
new_height = self.constrain_to_multiple_of(scale_height * height)
|
103 |
+
new_width = self.constrain_to_multiple_of(scale_width * width)
|
104 |
+
else:
|
105 |
+
raise ValueError(f"resize_method {self.__resize_method} not implemented")
|
106 |
+
|
107 |
+
return (new_width, new_height)
|
108 |
+
|
109 |
+
def __call__(self, sample):
|
110 |
+
width, height = self.get_size(sample["image"].shape[1], sample["image"].shape[0])
|
111 |
+
|
112 |
+
# resize sample
|
113 |
+
sample["image"] = cv2.resize(sample["image"], (width, height), interpolation=self.__image_interpolation_method)
|
114 |
+
|
115 |
+
if self.__resize_target:
|
116 |
+
if "depth" in sample:
|
117 |
+
sample["depth"] = cv2.resize(sample["depth"], (width, height), interpolation=cv2.INTER_NEAREST)
|
118 |
+
|
119 |
+
if "mask" in sample:
|
120 |
+
sample["mask"] = cv2.resize(sample["mask"].astype(np.float32), (width, height), interpolation=cv2.INTER_NEAREST)
|
121 |
+
|
122 |
+
return sample
|
123 |
+
|
124 |
+
|
125 |
+
class NormalizeImage(object):
|
126 |
+
"""Normlize image by given mean and std.
|
127 |
+
"""
|
128 |
+
|
129 |
+
def __init__(self, mean, std):
|
130 |
+
self.__mean = mean
|
131 |
+
self.__std = std
|
132 |
+
|
133 |
+
def __call__(self, sample):
|
134 |
+
sample["image"] = (sample["image"] - self.__mean) / self.__std
|
135 |
+
|
136 |
+
return sample
|
137 |
+
|
138 |
+
|
139 |
+
class PrepareForNet(object):
|
140 |
+
"""Prepare sample for usage as network input.
|
141 |
+
"""
|
142 |
+
|
143 |
+
def __init__(self):
|
144 |
+
pass
|
145 |
+
|
146 |
+
def __call__(self, sample):
|
147 |
+
image = np.transpose(sample["image"], (2, 0, 1))
|
148 |
+
sample["image"] = np.ascontiguousarray(image).astype(np.float32)
|
149 |
+
|
150 |
+
if "depth" in sample:
|
151 |
+
depth = sample["depth"].astype(np.float32)
|
152 |
+
sample["depth"] = np.ascontiguousarray(depth)
|
153 |
+
|
154 |
+
if "mask" in sample:
|
155 |
+
sample["mask"] = sample["mask"].astype(np.float32)
|
156 |
+
sample["mask"] = np.ascontiguousarray(sample["mask"])
|
157 |
+
|
158 |
+
return sample
|
geobench/midas/__pycache__/base_model.cpython-310.pyc
ADDED
Binary file (786 Bytes). View file
|
|
geobench/midas/__pycache__/blocks.cpython-310.pyc
ADDED
Binary file (8.88 kB). View file
|
|
geobench/midas/__pycache__/dpt_depth.cpython-310.pyc
ADDED
Binary file (4.11 kB). View file
|
|
geobench/midas/__pycache__/midas_net.cpython-310.pyc
ADDED
Binary file (2.59 kB). View file
|
|
geobench/midas/__pycache__/midas_net_custom.cpython-310.pyc
ADDED
Binary file (3.71 kB). View file
|
|
geobench/midas/__pycache__/model_loader.cpython-310.pyc
ADDED
Binary file (4.89 kB). View file
|
|
geobench/midas/__pycache__/transforms.cpython-310.pyc
ADDED
Binary file (5.58 kB). View file
|
|
geobench/midas/backbones/__pycache__/beit.cpython-310.pyc
ADDED
Binary file (5.52 kB). View file
|
|
geobench/midas/backbones/__pycache__/levit.cpython-310.pyc
ADDED
Binary file (3.42 kB). View file
|
|
geobench/midas/backbones/__pycache__/swin.cpython-310.pyc
ADDED
Binary file (529 Bytes). View file
|
|
geobench/midas/backbones/__pycache__/swin2.cpython-310.pyc
ADDED
Binary file (984 Bytes). View file
|
|
geobench/midas/backbones/__pycache__/swin_common.cpython-310.pyc
ADDED
Binary file (1.37 kB). View file
|
|
geobench/midas/backbones/__pycache__/utils.cpython-310.pyc
ADDED
Binary file (5.78 kB). View file
|
|
geobench/midas/backbones/__pycache__/vit.cpython-310.pyc
ADDED
Binary file (4.52 kB). View file
|
|
geobench/midas/backbones/beit.py
ADDED
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import timm
|
2 |
+
import torch
|
3 |
+
import types
|
4 |
+
|
5 |
+
import numpy as np
|
6 |
+
import torch.nn.functional as F
|
7 |
+
|
8 |
+
from .utils import forward_adapted_unflatten, make_backbone_default
|
9 |
+
from timm.models.beit import gen_relative_position_index
|
10 |
+
from torch.utils.checkpoint import checkpoint
|
11 |
+
from typing import Optional
|
12 |
+
|
13 |
+
|
14 |
+
def forward_beit(pretrained, x):
|
15 |
+
return forward_adapted_unflatten(pretrained, x, "forward_features")
|
16 |
+
|
17 |
+
|
18 |
+
def patch_embed_forward(self, x):
|
19 |
+
"""
|
20 |
+
Modification of timm.models.layers.patch_embed.py: PatchEmbed.forward to support arbitrary window sizes.
|
21 |
+
"""
|
22 |
+
x = self.proj(x)
|
23 |
+
if self.flatten:
|
24 |
+
x = x.flatten(2).transpose(1, 2)
|
25 |
+
x = self.norm(x)
|
26 |
+
return x
|
27 |
+
|
28 |
+
|
29 |
+
def _get_rel_pos_bias(self, window_size):
|
30 |
+
"""
|
31 |
+
Modification of timm.models.beit.py: Attention._get_rel_pos_bias to support arbitrary window sizes.
|
32 |
+
"""
|
33 |
+
old_height = 2 * self.window_size[0] - 1
|
34 |
+
old_width = 2 * self.window_size[1] - 1
|
35 |
+
|
36 |
+
new_height = 2 * window_size[0] - 1
|
37 |
+
new_width = 2 * window_size[1] - 1
|
38 |
+
|
39 |
+
old_relative_position_bias_table = self.relative_position_bias_table
|
40 |
+
|
41 |
+
old_num_relative_distance = self.num_relative_distance
|
42 |
+
new_num_relative_distance = new_height * new_width + 3
|
43 |
+
|
44 |
+
old_sub_table = old_relative_position_bias_table[:old_num_relative_distance - 3]
|
45 |
+
|
46 |
+
old_sub_table = old_sub_table.reshape(1, old_width, old_height, -1).permute(0, 3, 1, 2)
|
47 |
+
new_sub_table = F.interpolate(old_sub_table, size=(new_height, new_width), mode="bilinear")
|
48 |
+
new_sub_table = new_sub_table.permute(0, 2, 3, 1).reshape(new_num_relative_distance - 3, -1)
|
49 |
+
|
50 |
+
new_relative_position_bias_table = torch.cat(
|
51 |
+
[new_sub_table, old_relative_position_bias_table[old_num_relative_distance - 3:]])
|
52 |
+
|
53 |
+
key = str(window_size[1]) + "," + str(window_size[0])
|
54 |
+
if key not in self.relative_position_indices.keys():
|
55 |
+
self.relative_position_indices[key] = gen_relative_position_index(window_size)
|
56 |
+
|
57 |
+
relative_position_bias = new_relative_position_bias_table[
|
58 |
+
self.relative_position_indices[key].view(-1)].view(
|
59 |
+
window_size[0] * window_size[1] + 1,
|
60 |
+
window_size[0] * window_size[1] + 1, -1) # Wh*Ww,Wh*Ww,nH
|
61 |
+
relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
|
62 |
+
return relative_position_bias.unsqueeze(0)
|
63 |
+
|
64 |
+
|
65 |
+
def attention_forward(self, x, resolution, shared_rel_pos_bias: Optional[torch.Tensor] = None):
|
66 |
+
"""
|
67 |
+
Modification of timm.models.beit.py: Attention.forward to support arbitrary window sizes.
|
68 |
+
"""
|
69 |
+
B, N, C = x.shape
|
70 |
+
|
71 |
+
qkv_bias = torch.cat((self.q_bias, self.k_bias, self.v_bias)) if self.q_bias is not None else None
|
72 |
+
qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias)
|
73 |
+
qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
|
74 |
+
q, k, v = qkv.unbind(0) # make torchscript happy (cannot use tensor as tuple)
|
75 |
+
|
76 |
+
q = q * self.scale
|
77 |
+
attn = (q @ k.transpose(-2, -1))
|
78 |
+
|
79 |
+
if self.relative_position_bias_table is not None:
|
80 |
+
window_size = tuple(np.array(resolution) // 16)
|
81 |
+
attn = attn + self._get_rel_pos_bias(window_size)
|
82 |
+
if shared_rel_pos_bias is not None:
|
83 |
+
attn = attn + shared_rel_pos_bias
|
84 |
+
|
85 |
+
attn = attn.softmax(dim=-1)
|
86 |
+
attn = self.attn_drop(attn)
|
87 |
+
|
88 |
+
x = (attn @ v).transpose(1, 2).reshape(B, N, -1)
|
89 |
+
x = self.proj(x)
|
90 |
+
x = self.proj_drop(x)
|
91 |
+
return x
|
92 |
+
|
93 |
+
|
94 |
+
def block_forward(self, x, resolution, shared_rel_pos_bias: Optional[torch.Tensor] = None):
|
95 |
+
"""
|
96 |
+
Modification of timm.models.beit.py: Block.forward to support arbitrary window sizes.
|
97 |
+
"""
|
98 |
+
if self.gamma_1 is None:
|
99 |
+
x = x + self.drop_path(self.attn(self.norm1(x), resolution, shared_rel_pos_bias=shared_rel_pos_bias))
|
100 |
+
x = x + self.drop_path(self.mlp(self.norm2(x)))
|
101 |
+
else:
|
102 |
+
x = x + self.drop_path(self.gamma_1 * self.attn(self.norm1(x), resolution,
|
103 |
+
shared_rel_pos_bias=shared_rel_pos_bias))
|
104 |
+
x = x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x)))
|
105 |
+
return x
|
106 |
+
|
107 |
+
|
108 |
+
def beit_forward_features(self, x):
|
109 |
+
"""
|
110 |
+
Modification of timm.models.beit.py: Beit.forward_features to support arbitrary window sizes.
|
111 |
+
"""
|
112 |
+
resolution = x.shape[2:]
|
113 |
+
|
114 |
+
x = self.patch_embed(x)
|
115 |
+
x = torch.cat((self.cls_token.expand(x.shape[0], -1, -1), x), dim=1)
|
116 |
+
if self.pos_embed is not None:
|
117 |
+
x = x + self.pos_embed
|
118 |
+
x = self.pos_drop(x)
|
119 |
+
|
120 |
+
rel_pos_bias = self.rel_pos_bias() if self.rel_pos_bias is not None else None
|
121 |
+
for blk in self.blocks:
|
122 |
+
if self.grad_checkpointing and not torch.jit.is_scripting():
|
123 |
+
x = checkpoint(blk, x, shared_rel_pos_bias=rel_pos_bias)
|
124 |
+
else:
|
125 |
+
x = blk(x, resolution, shared_rel_pos_bias=rel_pos_bias)
|
126 |
+
x = self.norm(x)
|
127 |
+
return x
|
128 |
+
|
129 |
+
|
130 |
+
def _make_beit_backbone(
|
131 |
+
model,
|
132 |
+
features=[96, 192, 384, 768],
|
133 |
+
size=[384, 384],
|
134 |
+
hooks=[0, 4, 8, 11],
|
135 |
+
vit_features=768,
|
136 |
+
use_readout="ignore",
|
137 |
+
start_index=1,
|
138 |
+
start_index_readout=1,
|
139 |
+
):
|
140 |
+
backbone = make_backbone_default(model, features, size, hooks, vit_features, use_readout, start_index,
|
141 |
+
start_index_readout)
|
142 |
+
|
143 |
+
backbone.model.patch_embed.forward = types.MethodType(patch_embed_forward, backbone.model.patch_embed)
|
144 |
+
backbone.model.forward_features = types.MethodType(beit_forward_features, backbone.model)
|
145 |
+
|
146 |
+
for block in backbone.model.blocks:
|
147 |
+
attn = block.attn
|
148 |
+
attn._get_rel_pos_bias = types.MethodType(_get_rel_pos_bias, attn)
|
149 |
+
attn.forward = types.MethodType(attention_forward, attn)
|
150 |
+
attn.relative_position_indices = {}
|
151 |
+
|
152 |
+
block.forward = types.MethodType(block_forward, block)
|
153 |
+
|
154 |
+
return backbone
|
155 |
+
|
156 |
+
|
157 |
+
def _make_pretrained_beitl16_512(pretrained, use_readout="ignore", hooks=None):
|
158 |
+
model = timm.create_model("beit_large_patch16_512", pretrained=pretrained)
|
159 |
+
|
160 |
+
hooks = [5, 11, 17, 23] if hooks is None else hooks
|
161 |
+
|
162 |
+
features = [256, 512, 1024, 1024]
|
163 |
+
|
164 |
+
return _make_beit_backbone(
|
165 |
+
model,
|
166 |
+
features=features,
|
167 |
+
size=[512, 512],
|
168 |
+
hooks=hooks,
|
169 |
+
vit_features=1024,
|
170 |
+
use_readout=use_readout,
|
171 |
+
)
|
172 |
+
|
173 |
+
|
174 |
+
def _make_pretrained_beitl16_384(pretrained, use_readout="ignore", hooks=None):
|
175 |
+
model = timm.create_model("beit_large_patch16_384", pretrained=pretrained)
|
176 |
+
|
177 |
+
hooks = [5, 11, 17, 23] if hooks is None else hooks
|
178 |
+
return _make_beit_backbone(
|
179 |
+
model,
|
180 |
+
features=[256, 512, 1024, 1024],
|
181 |
+
hooks=hooks,
|
182 |
+
vit_features=1024,
|
183 |
+
use_readout=use_readout,
|
184 |
+
)
|
185 |
+
|
186 |
+
|
187 |
+
def _make_pretrained_beitb16_384(pretrained, use_readout="ignore", hooks=None):
|
188 |
+
model = timm.create_model("beit_base_patch16_384", pretrained=pretrained)
|
189 |
+
|
190 |
+
hooks = [2, 5, 8, 11] if hooks is None else hooks
|
191 |
+
return _make_beit_backbone(
|
192 |
+
model,
|
193 |
+
features=[96, 192, 384, 768],
|
194 |
+
hooks=hooks,
|
195 |
+
use_readout=use_readout,
|
196 |
+
)
|
geobench/midas/backbones/levit.py
ADDED
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import timm
|
2 |
+
import torch
|
3 |
+
import torch.nn as nn
|
4 |
+
import numpy as np
|
5 |
+
|
6 |
+
from .utils import activations, get_activation, Transpose
|
7 |
+
|
8 |
+
|
9 |
+
def forward_levit(pretrained, x):
|
10 |
+
pretrained.model.forward_features(x)
|
11 |
+
|
12 |
+
layer_1 = pretrained.activations["1"]
|
13 |
+
layer_2 = pretrained.activations["2"]
|
14 |
+
layer_3 = pretrained.activations["3"]
|
15 |
+
|
16 |
+
layer_1 = pretrained.act_postprocess1(layer_1)
|
17 |
+
layer_2 = pretrained.act_postprocess2(layer_2)
|
18 |
+
layer_3 = pretrained.act_postprocess3(layer_3)
|
19 |
+
|
20 |
+
return layer_1, layer_2, layer_3
|
21 |
+
|
22 |
+
|
23 |
+
def _make_levit_backbone(
|
24 |
+
model,
|
25 |
+
hooks=[3, 11, 21],
|
26 |
+
patch_grid=[14, 14]
|
27 |
+
):
|
28 |
+
pretrained = nn.Module()
|
29 |
+
|
30 |
+
pretrained.model = model
|
31 |
+
pretrained.model.blocks[hooks[0]].register_forward_hook(get_activation("1"))
|
32 |
+
pretrained.model.blocks[hooks[1]].register_forward_hook(get_activation("2"))
|
33 |
+
pretrained.model.blocks[hooks[2]].register_forward_hook(get_activation("3"))
|
34 |
+
|
35 |
+
pretrained.activations = activations
|
36 |
+
|
37 |
+
patch_grid_size = np.array(patch_grid, dtype=int)
|
38 |
+
|
39 |
+
pretrained.act_postprocess1 = nn.Sequential(
|
40 |
+
Transpose(1, 2),
|
41 |
+
nn.Unflatten(2, torch.Size(patch_grid_size.tolist()))
|
42 |
+
)
|
43 |
+
pretrained.act_postprocess2 = nn.Sequential(
|
44 |
+
Transpose(1, 2),
|
45 |
+
nn.Unflatten(2, torch.Size((np.ceil(patch_grid_size / 2).astype(int)).tolist()))
|
46 |
+
)
|
47 |
+
pretrained.act_postprocess3 = nn.Sequential(
|
48 |
+
Transpose(1, 2),
|
49 |
+
nn.Unflatten(2, torch.Size((np.ceil(patch_grid_size / 4).astype(int)).tolist()))
|
50 |
+
)
|
51 |
+
|
52 |
+
return pretrained
|
53 |
+
|
54 |
+
|
55 |
+
class ConvTransposeNorm(nn.Sequential):
|
56 |
+
"""
|
57 |
+
Modification of
|
58 |
+
https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/levit.py: ConvNorm
|
59 |
+
such that ConvTranspose2d is used instead of Conv2d.
|
60 |
+
"""
|
61 |
+
|
62 |
+
def __init__(
|
63 |
+
self, in_chs, out_chs, kernel_size=1, stride=1, pad=0, dilation=1,
|
64 |
+
groups=1, bn_weight_init=1):
|
65 |
+
super().__init__()
|
66 |
+
self.add_module('c',
|
67 |
+
nn.ConvTranspose2d(in_chs, out_chs, kernel_size, stride, pad, dilation, groups, bias=False))
|
68 |
+
self.add_module('bn', nn.BatchNorm2d(out_chs))
|
69 |
+
|
70 |
+
nn.init.constant_(self.bn.weight, bn_weight_init)
|
71 |
+
|
72 |
+
@torch.no_grad()
|
73 |
+
def fuse(self):
|
74 |
+
c, bn = self._modules.values()
|
75 |
+
w = bn.weight / (bn.running_var + bn.eps) ** 0.5
|
76 |
+
w = c.weight * w[:, None, None, None]
|
77 |
+
b = bn.bias - bn.running_mean * bn.weight / (bn.running_var + bn.eps) ** 0.5
|
78 |
+
m = nn.ConvTranspose2d(
|
79 |
+
w.size(1), w.size(0), w.shape[2:], stride=self.c.stride,
|
80 |
+
padding=self.c.padding, dilation=self.c.dilation, groups=self.c.groups)
|
81 |
+
m.weight.data.copy_(w)
|
82 |
+
m.bias.data.copy_(b)
|
83 |
+
return m
|
84 |
+
|
85 |
+
|
86 |
+
def stem_b4_transpose(in_chs, out_chs, activation):
|
87 |
+
"""
|
88 |
+
Modification of
|
89 |
+
https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/levit.py: stem_b16
|
90 |
+
such that ConvTranspose2d is used instead of Conv2d and stem is also reduced to the half.
|
91 |
+
"""
|
92 |
+
return nn.Sequential(
|
93 |
+
ConvTransposeNorm(in_chs, out_chs, 3, 2, 1),
|
94 |
+
activation(),
|
95 |
+
ConvTransposeNorm(out_chs, out_chs // 2, 3, 2, 1),
|
96 |
+
activation())
|
97 |
+
|
98 |
+
|
99 |
+
def _make_pretrained_levit_384(pretrained, hooks=None):
|
100 |
+
model = timm.create_model("levit_384", pretrained=pretrained)
|
101 |
+
|
102 |
+
hooks = [3, 11, 21] if hooks == None else hooks
|
103 |
+
return _make_levit_backbone(
|
104 |
+
model,
|
105 |
+
hooks=hooks
|
106 |
+
)
|
geobench/midas/backbones/next_vit.py
ADDED
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import timm
|
2 |
+
|
3 |
+
import torch.nn as nn
|
4 |
+
|
5 |
+
from pathlib import Path
|
6 |
+
from .utils import activations, forward_default, get_activation
|
7 |
+
|
8 |
+
from ..external.next_vit.classification.nextvit import *
|
9 |
+
|
10 |
+
|
11 |
+
def forward_next_vit(pretrained, x):
|
12 |
+
return forward_default(pretrained, x, "forward")
|
13 |
+
|
14 |
+
|
15 |
+
def _make_next_vit_backbone(
|
16 |
+
model,
|
17 |
+
hooks=[2, 6, 36, 39],
|
18 |
+
):
|
19 |
+
pretrained = nn.Module()
|
20 |
+
|
21 |
+
pretrained.model = model
|
22 |
+
pretrained.model.features[hooks[0]].register_forward_hook(get_activation("1"))
|
23 |
+
pretrained.model.features[hooks[1]].register_forward_hook(get_activation("2"))
|
24 |
+
pretrained.model.features[hooks[2]].register_forward_hook(get_activation("3"))
|
25 |
+
pretrained.model.features[hooks[3]].register_forward_hook(get_activation("4"))
|
26 |
+
|
27 |
+
pretrained.activations = activations
|
28 |
+
|
29 |
+
return pretrained
|
30 |
+
|
31 |
+
|
32 |
+
def _make_pretrained_next_vit_large_6m(hooks=None):
|
33 |
+
model = timm.create_model("nextvit_large")
|
34 |
+
|
35 |
+
hooks = [2, 6, 36, 39] if hooks == None else hooks
|
36 |
+
return _make_next_vit_backbone(
|
37 |
+
model,
|
38 |
+
hooks=hooks,
|
39 |
+
)
|
geobench/midas/backbones/swin.py
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import timm
|
2 |
+
|
3 |
+
from .swin_common import _make_swin_backbone
|
4 |
+
|
5 |
+
|
6 |
+
def _make_pretrained_swinl12_384(pretrained, hooks=None):
|
7 |
+
model = timm.create_model("swin_large_patch4_window12_384", pretrained=pretrained)
|
8 |
+
|
9 |
+
hooks = [1, 1, 17, 1] if hooks == None else hooks
|
10 |
+
return _make_swin_backbone(
|
11 |
+
model,
|
12 |
+
hooks=hooks
|
13 |
+
)
|
geobench/midas/backbones/swin2.py
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import timm
|
2 |
+
|
3 |
+
from .swin_common import _make_swin_backbone
|
4 |
+
|
5 |
+
|
6 |
+
def _make_pretrained_swin2l24_384(pretrained, hooks=None):
|
7 |
+
model = timm.create_model("swinv2_large_window12to24_192to384_22kft1k", pretrained=pretrained)
|
8 |
+
|
9 |
+
hooks = [1, 1, 17, 1] if hooks == None else hooks
|
10 |
+
return _make_swin_backbone(
|
11 |
+
model,
|
12 |
+
hooks=hooks
|
13 |
+
)
|
14 |
+
|
15 |
+
|
16 |
+
def _make_pretrained_swin2b24_384(pretrained, hooks=None):
|
17 |
+
model = timm.create_model("swinv2_base_window12to24_192to384_22kft1k", pretrained=pretrained)
|
18 |
+
|
19 |
+
hooks = [1, 1, 17, 1] if hooks == None else hooks
|
20 |
+
return _make_swin_backbone(
|
21 |
+
model,
|
22 |
+
hooks=hooks
|
23 |
+
)
|
24 |
+
|
25 |
+
|
26 |
+
def _make_pretrained_swin2t16_256(pretrained, hooks=None):
|
27 |
+
model = timm.create_model("swinv2_tiny_window16_256", pretrained=pretrained)
|
28 |
+
|
29 |
+
hooks = [1, 1, 5, 1] if hooks == None else hooks
|
30 |
+
return _make_swin_backbone(
|
31 |
+
model,
|
32 |
+
hooks=hooks,
|
33 |
+
patch_grid=[64, 64]
|
34 |
+
)
|
geobench/midas/backbones/swin_common.py
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
|
3 |
+
import torch.nn as nn
|
4 |
+
import numpy as np
|
5 |
+
|
6 |
+
from .utils import activations, forward_default, get_activation, Transpose
|
7 |
+
|
8 |
+
|
9 |
+
def forward_swin(pretrained, x):
|
10 |
+
return forward_default(pretrained, x)
|
11 |
+
|
12 |
+
|
13 |
+
def _make_swin_backbone(
|
14 |
+
model,
|
15 |
+
hooks=[1, 1, 17, 1],
|
16 |
+
patch_grid=[96, 96]
|
17 |
+
):
|
18 |
+
pretrained = nn.Module()
|
19 |
+
|
20 |
+
pretrained.model = model
|
21 |
+
pretrained.model.layers[0].blocks[hooks[0]].register_forward_hook(get_activation("1"))
|
22 |
+
pretrained.model.layers[1].blocks[hooks[1]].register_forward_hook(get_activation("2"))
|
23 |
+
pretrained.model.layers[2].blocks[hooks[2]].register_forward_hook(get_activation("3"))
|
24 |
+
pretrained.model.layers[3].blocks[hooks[3]].register_forward_hook(get_activation("4"))
|
25 |
+
|
26 |
+
pretrained.activations = activations
|
27 |
+
|
28 |
+
if hasattr(model, "patch_grid"):
|
29 |
+
used_patch_grid = model.patch_grid
|
30 |
+
else:
|
31 |
+
used_patch_grid = patch_grid
|
32 |
+
|
33 |
+
patch_grid_size = np.array(used_patch_grid, dtype=int)
|
34 |
+
|
35 |
+
pretrained.act_postprocess1 = nn.Sequential(
|
36 |
+
Transpose(1, 2),
|
37 |
+
nn.Unflatten(2, torch.Size(patch_grid_size.tolist()))
|
38 |
+
)
|
39 |
+
pretrained.act_postprocess2 = nn.Sequential(
|
40 |
+
Transpose(1, 2),
|
41 |
+
nn.Unflatten(2, torch.Size((patch_grid_size // 2).tolist()))
|
42 |
+
)
|
43 |
+
pretrained.act_postprocess3 = nn.Sequential(
|
44 |
+
Transpose(1, 2),
|
45 |
+
nn.Unflatten(2, torch.Size((patch_grid_size // 4).tolist()))
|
46 |
+
)
|
47 |
+
pretrained.act_postprocess4 = nn.Sequential(
|
48 |
+
Transpose(1, 2),
|
49 |
+
nn.Unflatten(2, torch.Size((patch_grid_size // 8).tolist()))
|
50 |
+
)
|
51 |
+
|
52 |
+
return pretrained
|
geobench/midas/backbones/utils.py
ADDED
@@ -0,0 +1,249 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
|
3 |
+
import torch.nn as nn
|
4 |
+
|
5 |
+
|
6 |
+
class Slice(nn.Module):
|
7 |
+
def __init__(self, start_index=1):
|
8 |
+
super(Slice, self).__init__()
|
9 |
+
self.start_index = start_index
|
10 |
+
|
11 |
+
def forward(self, x):
|
12 |
+
return x[:, self.start_index:]
|
13 |
+
|
14 |
+
|
15 |
+
class AddReadout(nn.Module):
|
16 |
+
def __init__(self, start_index=1):
|
17 |
+
super(AddReadout, self).__init__()
|
18 |
+
self.start_index = start_index
|
19 |
+
|
20 |
+
def forward(self, x):
|
21 |
+
if self.start_index == 2:
|
22 |
+
readout = (x[:, 0] + x[:, 1]) / 2
|
23 |
+
else:
|
24 |
+
readout = x[:, 0]
|
25 |
+
return x[:, self.start_index:] + readout.unsqueeze(1)
|
26 |
+
|
27 |
+
|
28 |
+
class ProjectReadout(nn.Module):
|
29 |
+
def __init__(self, in_features, start_index=1):
|
30 |
+
super(ProjectReadout, self).__init__()
|
31 |
+
self.start_index = start_index
|
32 |
+
|
33 |
+
self.project = nn.Sequential(nn.Linear(2 * in_features, in_features), nn.GELU())
|
34 |
+
|
35 |
+
def forward(self, x):
|
36 |
+
readout = x[:, 0].unsqueeze(1).expand_as(x[:, self.start_index:])
|
37 |
+
features = torch.cat((x[:, self.start_index:], readout), -1)
|
38 |
+
|
39 |
+
return self.project(features)
|
40 |
+
|
41 |
+
|
42 |
+
class Transpose(nn.Module):
|
43 |
+
def __init__(self, dim0, dim1):
|
44 |
+
super(Transpose, self).__init__()
|
45 |
+
self.dim0 = dim0
|
46 |
+
self.dim1 = dim1
|
47 |
+
|
48 |
+
def forward(self, x):
|
49 |
+
x = x.transpose(self.dim0, self.dim1)
|
50 |
+
return x
|
51 |
+
|
52 |
+
|
53 |
+
activations = {}
|
54 |
+
|
55 |
+
|
56 |
+
def get_activation(name):
|
57 |
+
def hook(model, input, output):
|
58 |
+
activations[name] = output
|
59 |
+
|
60 |
+
return hook
|
61 |
+
|
62 |
+
|
63 |
+
def forward_default(pretrained, x, function_name="forward_features"):
|
64 |
+
exec(f"pretrained.model.{function_name}(x)")
|
65 |
+
|
66 |
+
layer_1 = pretrained.activations["1"]
|
67 |
+
layer_2 = pretrained.activations["2"]
|
68 |
+
layer_3 = pretrained.activations["3"]
|
69 |
+
layer_4 = pretrained.activations["4"]
|
70 |
+
|
71 |
+
if hasattr(pretrained, "act_postprocess1"):
|
72 |
+
layer_1 = pretrained.act_postprocess1(layer_1)
|
73 |
+
if hasattr(pretrained, "act_postprocess2"):
|
74 |
+
layer_2 = pretrained.act_postprocess2(layer_2)
|
75 |
+
if hasattr(pretrained, "act_postprocess3"):
|
76 |
+
layer_3 = pretrained.act_postprocess3(layer_3)
|
77 |
+
if hasattr(pretrained, "act_postprocess4"):
|
78 |
+
layer_4 = pretrained.act_postprocess4(layer_4)
|
79 |
+
|
80 |
+
return layer_1, layer_2, layer_3, layer_4
|
81 |
+
|
82 |
+
|
83 |
+
def forward_adapted_unflatten(pretrained, x, function_name="forward_features"):
|
84 |
+
b, c, h, w = x.shape
|
85 |
+
|
86 |
+
exec(f"glob = pretrained.model.{function_name}(x)")
|
87 |
+
|
88 |
+
layer_1 = pretrained.activations["1"]
|
89 |
+
layer_2 = pretrained.activations["2"]
|
90 |
+
layer_3 = pretrained.activations["3"]
|
91 |
+
layer_4 = pretrained.activations["4"]
|
92 |
+
|
93 |
+
layer_1 = pretrained.act_postprocess1[0:2](layer_1)
|
94 |
+
layer_2 = pretrained.act_postprocess2[0:2](layer_2)
|
95 |
+
layer_3 = pretrained.act_postprocess3[0:2](layer_3)
|
96 |
+
layer_4 = pretrained.act_postprocess4[0:2](layer_4)
|
97 |
+
|
98 |
+
unflatten = nn.Sequential(
|
99 |
+
nn.Unflatten(
|
100 |
+
2,
|
101 |
+
torch.Size(
|
102 |
+
[
|
103 |
+
h // pretrained.model.patch_size[1],
|
104 |
+
w // pretrained.model.patch_size[0],
|
105 |
+
]
|
106 |
+
),
|
107 |
+
)
|
108 |
+
)
|
109 |
+
|
110 |
+
if layer_1.ndim == 3:
|
111 |
+
layer_1 = unflatten(layer_1)
|
112 |
+
if layer_2.ndim == 3:
|
113 |
+
layer_2 = unflatten(layer_2)
|
114 |
+
if layer_3.ndim == 3:
|
115 |
+
layer_3 = unflatten(layer_3)
|
116 |
+
if layer_4.ndim == 3:
|
117 |
+
layer_4 = unflatten(layer_4)
|
118 |
+
|
119 |
+
layer_1 = pretrained.act_postprocess1[3: len(pretrained.act_postprocess1)](layer_1)
|
120 |
+
layer_2 = pretrained.act_postprocess2[3: len(pretrained.act_postprocess2)](layer_2)
|
121 |
+
layer_3 = pretrained.act_postprocess3[3: len(pretrained.act_postprocess3)](layer_3)
|
122 |
+
layer_4 = pretrained.act_postprocess4[3: len(pretrained.act_postprocess4)](layer_4)
|
123 |
+
|
124 |
+
return layer_1, layer_2, layer_3, layer_4
|
125 |
+
|
126 |
+
|
127 |
+
def get_readout_oper(vit_features, features, use_readout, start_index=1):
|
128 |
+
if use_readout == "ignore":
|
129 |
+
readout_oper = [Slice(start_index)] * len(features)
|
130 |
+
elif use_readout == "add":
|
131 |
+
readout_oper = [AddReadout(start_index)] * len(features)
|
132 |
+
elif use_readout == "project":
|
133 |
+
readout_oper = [
|
134 |
+
ProjectReadout(vit_features, start_index) for out_feat in features
|
135 |
+
]
|
136 |
+
else:
|
137 |
+
assert (
|
138 |
+
False
|
139 |
+
), "wrong operation for readout token, use_readout can be 'ignore', 'add', or 'project'"
|
140 |
+
|
141 |
+
return readout_oper
|
142 |
+
|
143 |
+
|
144 |
+
def make_backbone_default(
|
145 |
+
model,
|
146 |
+
features=[96, 192, 384, 768],
|
147 |
+
size=[384, 384],
|
148 |
+
hooks=[2, 5, 8, 11],
|
149 |
+
vit_features=768,
|
150 |
+
use_readout="ignore",
|
151 |
+
start_index=1,
|
152 |
+
start_index_readout=1,
|
153 |
+
):
|
154 |
+
pretrained = nn.Module()
|
155 |
+
|
156 |
+
pretrained.model = model
|
157 |
+
pretrained.model.blocks[hooks[0]].register_forward_hook(get_activation("1"))
|
158 |
+
pretrained.model.blocks[hooks[1]].register_forward_hook(get_activation("2"))
|
159 |
+
pretrained.model.blocks[hooks[2]].register_forward_hook(get_activation("3"))
|
160 |
+
pretrained.model.blocks[hooks[3]].register_forward_hook(get_activation("4"))
|
161 |
+
|
162 |
+
pretrained.activations = activations
|
163 |
+
|
164 |
+
readout_oper = get_readout_oper(vit_features, features, use_readout, start_index_readout)
|
165 |
+
|
166 |
+
# 32, 48, 136, 384
|
167 |
+
pretrained.act_postprocess1 = nn.Sequential(
|
168 |
+
readout_oper[0],
|
169 |
+
Transpose(1, 2),
|
170 |
+
nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),
|
171 |
+
nn.Conv2d(
|
172 |
+
in_channels=vit_features,
|
173 |
+
out_channels=features[0],
|
174 |
+
kernel_size=1,
|
175 |
+
stride=1,
|
176 |
+
padding=0,
|
177 |
+
),
|
178 |
+
nn.ConvTranspose2d(
|
179 |
+
in_channels=features[0],
|
180 |
+
out_channels=features[0],
|
181 |
+
kernel_size=4,
|
182 |
+
stride=4,
|
183 |
+
padding=0,
|
184 |
+
bias=True,
|
185 |
+
dilation=1,
|
186 |
+
groups=1,
|
187 |
+
),
|
188 |
+
)
|
189 |
+
|
190 |
+
pretrained.act_postprocess2 = nn.Sequential(
|
191 |
+
readout_oper[1],
|
192 |
+
Transpose(1, 2),
|
193 |
+
nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),
|
194 |
+
nn.Conv2d(
|
195 |
+
in_channels=vit_features,
|
196 |
+
out_channels=features[1],
|
197 |
+
kernel_size=1,
|
198 |
+
stride=1,
|
199 |
+
padding=0,
|
200 |
+
),
|
201 |
+
nn.ConvTranspose2d(
|
202 |
+
in_channels=features[1],
|
203 |
+
out_channels=features[1],
|
204 |
+
kernel_size=2,
|
205 |
+
stride=2,
|
206 |
+
padding=0,
|
207 |
+
bias=True,
|
208 |
+
dilation=1,
|
209 |
+
groups=1,
|
210 |
+
),
|
211 |
+
)
|
212 |
+
|
213 |
+
pretrained.act_postprocess3 = nn.Sequential(
|
214 |
+
readout_oper[2],
|
215 |
+
Transpose(1, 2),
|
216 |
+
nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),
|
217 |
+
nn.Conv2d(
|
218 |
+
in_channels=vit_features,
|
219 |
+
out_channels=features[2],
|
220 |
+
kernel_size=1,
|
221 |
+
stride=1,
|
222 |
+
padding=0,
|
223 |
+
),
|
224 |
+
)
|
225 |
+
|
226 |
+
pretrained.act_postprocess4 = nn.Sequential(
|
227 |
+
readout_oper[3],
|
228 |
+
Transpose(1, 2),
|
229 |
+
nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),
|
230 |
+
nn.Conv2d(
|
231 |
+
in_channels=vit_features,
|
232 |
+
out_channels=features[3],
|
233 |
+
kernel_size=1,
|
234 |
+
stride=1,
|
235 |
+
padding=0,
|
236 |
+
),
|
237 |
+
nn.Conv2d(
|
238 |
+
in_channels=features[3],
|
239 |
+
out_channels=features[3],
|
240 |
+
kernel_size=3,
|
241 |
+
stride=2,
|
242 |
+
padding=1,
|
243 |
+
),
|
244 |
+
)
|
245 |
+
|
246 |
+
pretrained.model.start_index = start_index
|
247 |
+
pretrained.model.patch_size = [16, 16]
|
248 |
+
|
249 |
+
return pretrained
|
geobench/midas/backbones/vit.py
ADDED
@@ -0,0 +1,221 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
import timm
|
4 |
+
import types
|
5 |
+
import math
|
6 |
+
import torch.nn.functional as F
|
7 |
+
|
8 |
+
from .utils import (activations, forward_adapted_unflatten, get_activation, get_readout_oper,
|
9 |
+
make_backbone_default, Transpose)
|
10 |
+
|
11 |
+
|
12 |
+
def forward_vit(pretrained, x):
|
13 |
+
return forward_adapted_unflatten(pretrained, x, "forward_flex")
|
14 |
+
|
15 |
+
|
16 |
+
def _resize_pos_embed(self, posemb, gs_h, gs_w):
|
17 |
+
posemb_tok, posemb_grid = (
|
18 |
+
posemb[:, : self.start_index],
|
19 |
+
posemb[0, self.start_index:],
|
20 |
+
)
|
21 |
+
|
22 |
+
gs_old = int(math.sqrt(len(posemb_grid)))
|
23 |
+
|
24 |
+
posemb_grid = posemb_grid.reshape(1, gs_old, gs_old, -1).permute(0, 3, 1, 2)
|
25 |
+
posemb_grid = F.interpolate(posemb_grid, size=(gs_h, gs_w), mode="bilinear")
|
26 |
+
posemb_grid = posemb_grid.permute(0, 2, 3, 1).reshape(1, gs_h * gs_w, -1)
|
27 |
+
|
28 |
+
posemb = torch.cat([posemb_tok, posemb_grid], dim=1)
|
29 |
+
|
30 |
+
return posemb
|
31 |
+
|
32 |
+
|
33 |
+
def forward_flex(self, x):
|
34 |
+
b, c, h, w = x.shape
|
35 |
+
|
36 |
+
pos_embed = self._resize_pos_embed(
|
37 |
+
self.pos_embed, h // self.patch_size[1], w // self.patch_size[0]
|
38 |
+
)
|
39 |
+
|
40 |
+
B = x.shape[0]
|
41 |
+
|
42 |
+
if hasattr(self.patch_embed, "backbone"):
|
43 |
+
x = self.patch_embed.backbone(x)
|
44 |
+
if isinstance(x, (list, tuple)):
|
45 |
+
x = x[-1] # last feature if backbone outputs list/tuple of features
|
46 |
+
|
47 |
+
x = self.patch_embed.proj(x).flatten(2).transpose(1, 2)
|
48 |
+
|
49 |
+
if getattr(self, "dist_token", None) is not None:
|
50 |
+
cls_tokens = self.cls_token.expand(
|
51 |
+
B, -1, -1
|
52 |
+
) # stole cls_tokens impl from Phil Wang, thanks
|
53 |
+
dist_token = self.dist_token.expand(B, -1, -1)
|
54 |
+
x = torch.cat((cls_tokens, dist_token, x), dim=1)
|
55 |
+
else:
|
56 |
+
if self.no_embed_class:
|
57 |
+
x = x + pos_embed
|
58 |
+
cls_tokens = self.cls_token.expand(
|
59 |
+
B, -1, -1
|
60 |
+
) # stole cls_tokens impl from Phil Wang, thanks
|
61 |
+
x = torch.cat((cls_tokens, x), dim=1)
|
62 |
+
|
63 |
+
if not self.no_embed_class:
|
64 |
+
x = x + pos_embed
|
65 |
+
x = self.pos_drop(x)
|
66 |
+
|
67 |
+
for blk in self.blocks:
|
68 |
+
x = blk(x)
|
69 |
+
|
70 |
+
x = self.norm(x)
|
71 |
+
|
72 |
+
return x
|
73 |
+
|
74 |
+
|
75 |
+
def _make_vit_b16_backbone(
|
76 |
+
model,
|
77 |
+
features=[96, 192, 384, 768],
|
78 |
+
size=[384, 384],
|
79 |
+
hooks=[2, 5, 8, 11],
|
80 |
+
vit_features=768,
|
81 |
+
use_readout="ignore",
|
82 |
+
start_index=1,
|
83 |
+
start_index_readout=1,
|
84 |
+
):
|
85 |
+
pretrained = make_backbone_default(model, features, size, hooks, vit_features, use_readout, start_index,
|
86 |
+
start_index_readout)
|
87 |
+
|
88 |
+
# We inject this function into the VisionTransformer instances so that
|
89 |
+
# we can use it with interpolated position embeddings without modifying the library source.
|
90 |
+
pretrained.model.forward_flex = types.MethodType(forward_flex, pretrained.model)
|
91 |
+
pretrained.model._resize_pos_embed = types.MethodType(
|
92 |
+
_resize_pos_embed, pretrained.model
|
93 |
+
)
|
94 |
+
|
95 |
+
return pretrained
|
96 |
+
|
97 |
+
|
98 |
+
def _make_pretrained_vitl16_384(pretrained, use_readout="ignore", hooks=None):
|
99 |
+
model = timm.create_model("vit_large_patch16_384", pretrained=pretrained)
|
100 |
+
|
101 |
+
hooks = [5, 11, 17, 23] if hooks == None else hooks
|
102 |
+
return _make_vit_b16_backbone(
|
103 |
+
model,
|
104 |
+
features=[256, 512, 1024, 1024],
|
105 |
+
hooks=hooks,
|
106 |
+
vit_features=1024,
|
107 |
+
use_readout=use_readout,
|
108 |
+
)
|
109 |
+
|
110 |
+
|
111 |
+
def _make_pretrained_vitb16_384(pretrained, use_readout="ignore", hooks=None):
|
112 |
+
model = timm.create_model("vit_base_patch16_384", pretrained=pretrained)
|
113 |
+
|
114 |
+
hooks = [2, 5, 8, 11] if hooks == None else hooks
|
115 |
+
return _make_vit_b16_backbone(
|
116 |
+
model, features=[96, 192, 384, 768], hooks=hooks, use_readout=use_readout
|
117 |
+
)
|
118 |
+
|
119 |
+
|
120 |
+
def _make_vit_b_rn50_backbone(
|
121 |
+
model,
|
122 |
+
features=[256, 512, 768, 768],
|
123 |
+
size=[384, 384],
|
124 |
+
hooks=[0, 1, 8, 11],
|
125 |
+
vit_features=768,
|
126 |
+
patch_size=[16, 16],
|
127 |
+
number_stages=2,
|
128 |
+
use_vit_only=False,
|
129 |
+
use_readout="ignore",
|
130 |
+
start_index=1,
|
131 |
+
):
|
132 |
+
pretrained = nn.Module()
|
133 |
+
|
134 |
+
pretrained.model = model
|
135 |
+
|
136 |
+
used_number_stages = 0 if use_vit_only else number_stages
|
137 |
+
for s in range(used_number_stages):
|
138 |
+
pretrained.model.patch_embed.backbone.stages[s].register_forward_hook(
|
139 |
+
get_activation(str(s + 1))
|
140 |
+
)
|
141 |
+
for s in range(used_number_stages, 4):
|
142 |
+
pretrained.model.blocks[hooks[s]].register_forward_hook(get_activation(str(s + 1)))
|
143 |
+
|
144 |
+
pretrained.activations = activations
|
145 |
+
|
146 |
+
readout_oper = get_readout_oper(vit_features, features, use_readout, start_index)
|
147 |
+
|
148 |
+
for s in range(used_number_stages):
|
149 |
+
value = nn.Sequential(nn.Identity(), nn.Identity(), nn.Identity())
|
150 |
+
exec(f"pretrained.act_postprocess{s + 1}=value")
|
151 |
+
for s in range(used_number_stages, 4):
|
152 |
+
if s < number_stages:
|
153 |
+
final_layer = nn.ConvTranspose2d(
|
154 |
+
in_channels=features[s],
|
155 |
+
out_channels=features[s],
|
156 |
+
kernel_size=4 // (2 ** s),
|
157 |
+
stride=4 // (2 ** s),
|
158 |
+
padding=0,
|
159 |
+
bias=True,
|
160 |
+
dilation=1,
|
161 |
+
groups=1,
|
162 |
+
)
|
163 |
+
elif s > number_stages:
|
164 |
+
final_layer = nn.Conv2d(
|
165 |
+
in_channels=features[3],
|
166 |
+
out_channels=features[3],
|
167 |
+
kernel_size=3,
|
168 |
+
stride=2,
|
169 |
+
padding=1,
|
170 |
+
)
|
171 |
+
else:
|
172 |
+
final_layer = None
|
173 |
+
|
174 |
+
layers = [
|
175 |
+
readout_oper[s],
|
176 |
+
Transpose(1, 2),
|
177 |
+
nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),
|
178 |
+
nn.Conv2d(
|
179 |
+
in_channels=vit_features,
|
180 |
+
out_channels=features[s],
|
181 |
+
kernel_size=1,
|
182 |
+
stride=1,
|
183 |
+
padding=0,
|
184 |
+
),
|
185 |
+
]
|
186 |
+
if final_layer is not None:
|
187 |
+
layers.append(final_layer)
|
188 |
+
|
189 |
+
value = nn.Sequential(*layers)
|
190 |
+
exec(f"pretrained.act_postprocess{s + 1}=value")
|
191 |
+
|
192 |
+
pretrained.model.start_index = start_index
|
193 |
+
pretrained.model.patch_size = patch_size
|
194 |
+
|
195 |
+
# We inject this function into the VisionTransformer instances so that
|
196 |
+
# we can use it with interpolated position embeddings without modifying the library source.
|
197 |
+
pretrained.model.forward_flex = types.MethodType(forward_flex, pretrained.model)
|
198 |
+
|
199 |
+
# We inject this function into the VisionTransformer instances so that
|
200 |
+
# we can use it with interpolated position embeddings without modifying the library source.
|
201 |
+
pretrained.model._resize_pos_embed = types.MethodType(
|
202 |
+
_resize_pos_embed, pretrained.model
|
203 |
+
)
|
204 |
+
|
205 |
+
return pretrained
|
206 |
+
|
207 |
+
|
208 |
+
def _make_pretrained_vitb_rn50_384(
|
209 |
+
pretrained, use_readout="ignore", hooks=None, use_vit_only=False
|
210 |
+
):
|
211 |
+
model = timm.create_model("vit_base_resnet50_384", pretrained=pretrained)
|
212 |
+
|
213 |
+
hooks = [0, 1, 8, 11] if hooks == None else hooks
|
214 |
+
return _make_vit_b_rn50_backbone(
|
215 |
+
model,
|
216 |
+
features=[256, 512, 768, 768],
|
217 |
+
size=[384, 384],
|
218 |
+
hooks=hooks,
|
219 |
+
use_vit_only=use_vit_only,
|
220 |
+
use_readout=use_readout,
|
221 |
+
)
|
geobench/midas/base_model.py
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from huggingface_hub import PyTorchModelHubMixin, hf_hub_download
|
3 |
+
|
4 |
+
|
5 |
+
class BaseModel(torch.nn.Module, PyTorchModelHubMixin):
|
6 |
+
def load(self, path):
|
7 |
+
"""Load model from file.
|
8 |
+
|
9 |
+
Args:
|
10 |
+
path (str): file path
|
11 |
+
"""
|
12 |
+
parameters = torch.load(path, map_location=torch.device('cpu'))
|
13 |
+
|
14 |
+
if "optimizer" in parameters:
|
15 |
+
parameters = parameters["model"]
|
16 |
+
|
17 |
+
self.load_state_dict(parameters, strict=False)
|
geobench/midas/blocks.py
ADDED
@@ -0,0 +1,439 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
|
4 |
+
from .backbones.beit import (
|
5 |
+
_make_pretrained_beitl16_512,
|
6 |
+
_make_pretrained_beitl16_384,
|
7 |
+
_make_pretrained_beitb16_384,
|
8 |
+
forward_beit,
|
9 |
+
)
|
10 |
+
from .backbones.swin_common import (
|
11 |
+
forward_swin,
|
12 |
+
)
|
13 |
+
from .backbones.swin2 import (
|
14 |
+
_make_pretrained_swin2l24_384,
|
15 |
+
_make_pretrained_swin2b24_384,
|
16 |
+
_make_pretrained_swin2t16_256,
|
17 |
+
)
|
18 |
+
from .backbones.swin import (
|
19 |
+
_make_pretrained_swinl12_384,
|
20 |
+
)
|
21 |
+
from .backbones.levit import (
|
22 |
+
_make_pretrained_levit_384,
|
23 |
+
forward_levit,
|
24 |
+
)
|
25 |
+
from .backbones.vit import (
|
26 |
+
_make_pretrained_vitb_rn50_384,
|
27 |
+
_make_pretrained_vitl16_384,
|
28 |
+
_make_pretrained_vitb16_384,
|
29 |
+
forward_vit,
|
30 |
+
)
|
31 |
+
|
32 |
+
def _make_encoder(backbone, features, use_pretrained, groups=1, expand=False, exportable=True, hooks=None,
|
33 |
+
use_vit_only=False, use_readout="ignore", in_features=[96, 256, 512, 1024]):
|
34 |
+
if backbone == "beitl16_512":
|
35 |
+
pretrained = _make_pretrained_beitl16_512(
|
36 |
+
use_pretrained, hooks=hooks, use_readout=use_readout
|
37 |
+
)
|
38 |
+
scratch = _make_scratch(
|
39 |
+
[256, 512, 1024, 1024], features, groups=groups, expand=expand
|
40 |
+
) # BEiT_512-L (backbone)
|
41 |
+
elif backbone == "beitl16_384":
|
42 |
+
pretrained = _make_pretrained_beitl16_384(
|
43 |
+
use_pretrained, hooks=hooks, use_readout=use_readout
|
44 |
+
)
|
45 |
+
scratch = _make_scratch(
|
46 |
+
[256, 512, 1024, 1024], features, groups=groups, expand=expand
|
47 |
+
) # BEiT_384-L (backbone)
|
48 |
+
elif backbone == "beitb16_384":
|
49 |
+
pretrained = _make_pretrained_beitb16_384(
|
50 |
+
use_pretrained, hooks=hooks, use_readout=use_readout
|
51 |
+
)
|
52 |
+
scratch = _make_scratch(
|
53 |
+
[96, 192, 384, 768], features, groups=groups, expand=expand
|
54 |
+
) # BEiT_384-B (backbone)
|
55 |
+
elif backbone == "swin2l24_384":
|
56 |
+
pretrained = _make_pretrained_swin2l24_384(
|
57 |
+
use_pretrained, hooks=hooks
|
58 |
+
)
|
59 |
+
scratch = _make_scratch(
|
60 |
+
[192, 384, 768, 1536], features, groups=groups, expand=expand
|
61 |
+
) # Swin2-L/12to24 (backbone)
|
62 |
+
elif backbone == "swin2b24_384":
|
63 |
+
pretrained = _make_pretrained_swin2b24_384(
|
64 |
+
use_pretrained, hooks=hooks
|
65 |
+
)
|
66 |
+
scratch = _make_scratch(
|
67 |
+
[128, 256, 512, 1024], features, groups=groups, expand=expand
|
68 |
+
) # Swin2-B/12to24 (backbone)
|
69 |
+
elif backbone == "swin2t16_256":
|
70 |
+
pretrained = _make_pretrained_swin2t16_256(
|
71 |
+
use_pretrained, hooks=hooks
|
72 |
+
)
|
73 |
+
scratch = _make_scratch(
|
74 |
+
[96, 192, 384, 768], features, groups=groups, expand=expand
|
75 |
+
) # Swin2-T/16 (backbone)
|
76 |
+
elif backbone == "swinl12_384":
|
77 |
+
pretrained = _make_pretrained_swinl12_384(
|
78 |
+
use_pretrained, hooks=hooks
|
79 |
+
)
|
80 |
+
scratch = _make_scratch(
|
81 |
+
[192, 384, 768, 1536], features, groups=groups, expand=expand
|
82 |
+
) # Swin-L/12 (backbone)
|
83 |
+
elif backbone == "next_vit_large_6m":
|
84 |
+
from .backbones.next_vit import _make_pretrained_next_vit_large_6m
|
85 |
+
pretrained = _make_pretrained_next_vit_large_6m(hooks=hooks)
|
86 |
+
scratch = _make_scratch(
|
87 |
+
in_features, features, groups=groups, expand=expand
|
88 |
+
) # Next-ViT-L on ImageNet-1K-6M (backbone)
|
89 |
+
elif backbone == "levit_384":
|
90 |
+
pretrained = _make_pretrained_levit_384(
|
91 |
+
use_pretrained, hooks=hooks
|
92 |
+
)
|
93 |
+
scratch = _make_scratch(
|
94 |
+
[384, 512, 768], features, groups=groups, expand=expand
|
95 |
+
) # LeViT 384 (backbone)
|
96 |
+
elif backbone == "vitl16_384":
|
97 |
+
pretrained = _make_pretrained_vitl16_384(
|
98 |
+
use_pretrained, hooks=hooks, use_readout=use_readout
|
99 |
+
)
|
100 |
+
scratch = _make_scratch(
|
101 |
+
[256, 512, 1024, 1024], features, groups=groups, expand=expand
|
102 |
+
) # ViT-L/16 - 85.0% Top1 (backbone)
|
103 |
+
elif backbone == "vitb_rn50_384":
|
104 |
+
pretrained = _make_pretrained_vitb_rn50_384(
|
105 |
+
use_pretrained,
|
106 |
+
hooks=hooks,
|
107 |
+
use_vit_only=use_vit_only,
|
108 |
+
use_readout=use_readout,
|
109 |
+
)
|
110 |
+
scratch = _make_scratch(
|
111 |
+
[256, 512, 768, 768], features, groups=groups, expand=expand
|
112 |
+
) # ViT-H/16 - 85.0% Top1 (backbone)
|
113 |
+
elif backbone == "vitb16_384":
|
114 |
+
pretrained = _make_pretrained_vitb16_384(
|
115 |
+
use_pretrained, hooks=hooks, use_readout=use_readout
|
116 |
+
)
|
117 |
+
scratch = _make_scratch(
|
118 |
+
[96, 192, 384, 768], features, groups=groups, expand=expand
|
119 |
+
) # ViT-B/16 - 84.6% Top1 (backbone)
|
120 |
+
elif backbone == "resnext101_wsl":
|
121 |
+
pretrained = _make_pretrained_resnext101_wsl(use_pretrained)
|
122 |
+
scratch = _make_scratch([256, 512, 1024, 2048], features, groups=groups, expand=expand) # efficientnet_lite3
|
123 |
+
elif backbone == "efficientnet_lite3":
|
124 |
+
pretrained = _make_pretrained_efficientnet_lite3(use_pretrained, exportable=exportable)
|
125 |
+
scratch = _make_scratch([32, 48, 136, 384], features, groups=groups, expand=expand) # efficientnet_lite3
|
126 |
+
else:
|
127 |
+
print(f"Backbone '{backbone}' not implemented")
|
128 |
+
assert False
|
129 |
+
|
130 |
+
return pretrained, scratch
|
131 |
+
|
132 |
+
|
133 |
+
def _make_scratch(in_shape, out_shape, groups=1, expand=False):
|
134 |
+
scratch = nn.Module()
|
135 |
+
|
136 |
+
out_shape1 = out_shape
|
137 |
+
out_shape2 = out_shape
|
138 |
+
out_shape3 = out_shape
|
139 |
+
if len(in_shape) >= 4:
|
140 |
+
out_shape4 = out_shape
|
141 |
+
|
142 |
+
if expand:
|
143 |
+
out_shape1 = out_shape
|
144 |
+
out_shape2 = out_shape*2
|
145 |
+
out_shape3 = out_shape*4
|
146 |
+
if len(in_shape) >= 4:
|
147 |
+
out_shape4 = out_shape*8
|
148 |
+
|
149 |
+
scratch.layer1_rn = nn.Conv2d(
|
150 |
+
in_shape[0], out_shape1, kernel_size=3, stride=1, padding=1, bias=False, groups=groups
|
151 |
+
)
|
152 |
+
scratch.layer2_rn = nn.Conv2d(
|
153 |
+
in_shape[1], out_shape2, kernel_size=3, stride=1, padding=1, bias=False, groups=groups
|
154 |
+
)
|
155 |
+
scratch.layer3_rn = nn.Conv2d(
|
156 |
+
in_shape[2], out_shape3, kernel_size=3, stride=1, padding=1, bias=False, groups=groups
|
157 |
+
)
|
158 |
+
if len(in_shape) >= 4:
|
159 |
+
scratch.layer4_rn = nn.Conv2d(
|
160 |
+
in_shape[3], out_shape4, kernel_size=3, stride=1, padding=1, bias=False, groups=groups
|
161 |
+
)
|
162 |
+
|
163 |
+
return scratch
|
164 |
+
|
165 |
+
|
166 |
+
def _make_pretrained_efficientnet_lite3(use_pretrained, exportable=False):
|
167 |
+
efficientnet = torch.hub.load(
|
168 |
+
"rwightman/gen-efficientnet-pytorch",
|
169 |
+
"tf_efficientnet_lite3",
|
170 |
+
pretrained=use_pretrained,
|
171 |
+
exportable=exportable
|
172 |
+
)
|
173 |
+
return _make_efficientnet_backbone(efficientnet)
|
174 |
+
|
175 |
+
|
176 |
+
def _make_efficientnet_backbone(effnet):
|
177 |
+
pretrained = nn.Module()
|
178 |
+
|
179 |
+
pretrained.layer1 = nn.Sequential(
|
180 |
+
effnet.conv_stem, effnet.bn1, effnet.act1, *effnet.blocks[0:2]
|
181 |
+
)
|
182 |
+
pretrained.layer2 = nn.Sequential(*effnet.blocks[2:3])
|
183 |
+
pretrained.layer3 = nn.Sequential(*effnet.blocks[3:5])
|
184 |
+
pretrained.layer4 = nn.Sequential(*effnet.blocks[5:9])
|
185 |
+
|
186 |
+
return pretrained
|
187 |
+
|
188 |
+
|
189 |
+
def _make_resnet_backbone(resnet):
|
190 |
+
pretrained = nn.Module()
|
191 |
+
pretrained.layer1 = nn.Sequential(
|
192 |
+
resnet.conv1, resnet.bn1, resnet.relu, resnet.maxpool, resnet.layer1
|
193 |
+
)
|
194 |
+
|
195 |
+
pretrained.layer2 = resnet.layer2
|
196 |
+
pretrained.layer3 = resnet.layer3
|
197 |
+
pretrained.layer4 = resnet.layer4
|
198 |
+
|
199 |
+
return pretrained
|
200 |
+
|
201 |
+
|
202 |
+
def _make_pretrained_resnext101_wsl(use_pretrained):
|
203 |
+
resnet = torch.hub.load("facebookresearch/WSL-Images", "resnext101_32x8d_wsl")
|
204 |
+
return _make_resnet_backbone(resnet)
|
205 |
+
|
206 |
+
|
207 |
+
|
208 |
+
class Interpolate(nn.Module):
|
209 |
+
"""Interpolation module.
|
210 |
+
"""
|
211 |
+
|
212 |
+
def __init__(self, scale_factor, mode, align_corners=False):
|
213 |
+
"""Init.
|
214 |
+
|
215 |
+
Args:
|
216 |
+
scale_factor (float): scaling
|
217 |
+
mode (str): interpolation mode
|
218 |
+
"""
|
219 |
+
super(Interpolate, self).__init__()
|
220 |
+
|
221 |
+
self.interp = nn.functional.interpolate
|
222 |
+
self.scale_factor = scale_factor
|
223 |
+
self.mode = mode
|
224 |
+
self.align_corners = align_corners
|
225 |
+
|
226 |
+
def forward(self, x):
|
227 |
+
"""Forward pass.
|
228 |
+
|
229 |
+
Args:
|
230 |
+
x (tensor): input
|
231 |
+
|
232 |
+
Returns:
|
233 |
+
tensor: interpolated data
|
234 |
+
"""
|
235 |
+
|
236 |
+
x = self.interp(
|
237 |
+
x, scale_factor=self.scale_factor, mode=self.mode, align_corners=self.align_corners
|
238 |
+
)
|
239 |
+
|
240 |
+
return x
|
241 |
+
|
242 |
+
|
243 |
+
class ResidualConvUnit(nn.Module):
|
244 |
+
"""Residual convolution module.
|
245 |
+
"""
|
246 |
+
|
247 |
+
def __init__(self, features):
|
248 |
+
"""Init.
|
249 |
+
|
250 |
+
Args:
|
251 |
+
features (int): number of features
|
252 |
+
"""
|
253 |
+
super().__init__()
|
254 |
+
|
255 |
+
self.conv1 = nn.Conv2d(
|
256 |
+
features, features, kernel_size=3, stride=1, padding=1, bias=True
|
257 |
+
)
|
258 |
+
|
259 |
+
self.conv2 = nn.Conv2d(
|
260 |
+
features, features, kernel_size=3, stride=1, padding=1, bias=True
|
261 |
+
)
|
262 |
+
|
263 |
+
self.relu = nn.ReLU(inplace=True)
|
264 |
+
|
265 |
+
def forward(self, x):
|
266 |
+
"""Forward pass.
|
267 |
+
|
268 |
+
Args:
|
269 |
+
x (tensor): input
|
270 |
+
|
271 |
+
Returns:
|
272 |
+
tensor: output
|
273 |
+
"""
|
274 |
+
out = self.relu(x)
|
275 |
+
out = self.conv1(out)
|
276 |
+
out = self.relu(out)
|
277 |
+
out = self.conv2(out)
|
278 |
+
|
279 |
+
return out + x
|
280 |
+
|
281 |
+
|
282 |
+
class FeatureFusionBlock(nn.Module):
|
283 |
+
"""Feature fusion block.
|
284 |
+
"""
|
285 |
+
|
286 |
+
def __init__(self, features):
|
287 |
+
"""Init.
|
288 |
+
|
289 |
+
Args:
|
290 |
+
features (int): number of features
|
291 |
+
"""
|
292 |
+
super(FeatureFusionBlock, self).__init__()
|
293 |
+
|
294 |
+
self.resConfUnit1 = ResidualConvUnit(features)
|
295 |
+
self.resConfUnit2 = ResidualConvUnit(features)
|
296 |
+
|
297 |
+
def forward(self, *xs):
|
298 |
+
"""Forward pass.
|
299 |
+
|
300 |
+
Returns:
|
301 |
+
tensor: output
|
302 |
+
"""
|
303 |
+
output = xs[0]
|
304 |
+
|
305 |
+
if len(xs) == 2:
|
306 |
+
output += self.resConfUnit1(xs[1])
|
307 |
+
|
308 |
+
output = self.resConfUnit2(output)
|
309 |
+
|
310 |
+
output = nn.functional.interpolate(
|
311 |
+
output, scale_factor=2, mode="bilinear", align_corners=True
|
312 |
+
)
|
313 |
+
|
314 |
+
return output
|
315 |
+
|
316 |
+
|
317 |
+
|
318 |
+
|
319 |
+
class ResidualConvUnit_custom(nn.Module):
|
320 |
+
"""Residual convolution module.
|
321 |
+
"""
|
322 |
+
|
323 |
+
def __init__(self, features, activation, bn):
|
324 |
+
"""Init.
|
325 |
+
|
326 |
+
Args:
|
327 |
+
features (int): number of features
|
328 |
+
"""
|
329 |
+
super().__init__()
|
330 |
+
|
331 |
+
self.bn = bn
|
332 |
+
|
333 |
+
self.groups=1
|
334 |
+
|
335 |
+
self.conv1 = nn.Conv2d(
|
336 |
+
features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups
|
337 |
+
)
|
338 |
+
|
339 |
+
self.conv2 = nn.Conv2d(
|
340 |
+
features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups
|
341 |
+
)
|
342 |
+
|
343 |
+
if self.bn==True:
|
344 |
+
self.bn1 = nn.BatchNorm2d(features)
|
345 |
+
self.bn2 = nn.BatchNorm2d(features)
|
346 |
+
|
347 |
+
self.activation = activation
|
348 |
+
|
349 |
+
self.skip_add = nn.quantized.FloatFunctional()
|
350 |
+
|
351 |
+
def forward(self, x):
|
352 |
+
"""Forward pass.
|
353 |
+
|
354 |
+
Args:
|
355 |
+
x (tensor): input
|
356 |
+
|
357 |
+
Returns:
|
358 |
+
tensor: output
|
359 |
+
"""
|
360 |
+
|
361 |
+
out = self.activation(x)
|
362 |
+
out = self.conv1(out)
|
363 |
+
if self.bn==True:
|
364 |
+
out = self.bn1(out)
|
365 |
+
|
366 |
+
out = self.activation(out)
|
367 |
+
out = self.conv2(out)
|
368 |
+
if self.bn==True:
|
369 |
+
out = self.bn2(out)
|
370 |
+
|
371 |
+
if self.groups > 1:
|
372 |
+
out = self.conv_merge(out)
|
373 |
+
|
374 |
+
return self.skip_add.add(out, x)
|
375 |
+
|
376 |
+
# return out + x
|
377 |
+
|
378 |
+
|
379 |
+
class FeatureFusionBlock_custom(nn.Module):
|
380 |
+
"""Feature fusion block.
|
381 |
+
"""
|
382 |
+
|
383 |
+
def __init__(self, features, activation, deconv=False, bn=False, expand=False, align_corners=True, size=None):
|
384 |
+
"""Init.
|
385 |
+
|
386 |
+
Args:
|
387 |
+
features (int): number of features
|
388 |
+
"""
|
389 |
+
super(FeatureFusionBlock_custom, self).__init__()
|
390 |
+
|
391 |
+
self.deconv = deconv
|
392 |
+
self.align_corners = align_corners
|
393 |
+
|
394 |
+
self.groups=1
|
395 |
+
|
396 |
+
self.expand = expand
|
397 |
+
out_features = features
|
398 |
+
if self.expand==True:
|
399 |
+
out_features = features//2
|
400 |
+
|
401 |
+
self.out_conv = nn.Conv2d(features, out_features, kernel_size=1, stride=1, padding=0, bias=True, groups=1)
|
402 |
+
|
403 |
+
self.resConfUnit1 = ResidualConvUnit_custom(features, activation, bn)
|
404 |
+
self.resConfUnit2 = ResidualConvUnit_custom(features, activation, bn)
|
405 |
+
|
406 |
+
self.skip_add = nn.quantized.FloatFunctional()
|
407 |
+
|
408 |
+
self.size=size
|
409 |
+
|
410 |
+
def forward(self, *xs, size=None):
|
411 |
+
"""Forward pass.
|
412 |
+
|
413 |
+
Returns:
|
414 |
+
tensor: output
|
415 |
+
"""
|
416 |
+
output = xs[0]
|
417 |
+
|
418 |
+
if len(xs) == 2:
|
419 |
+
res = self.resConfUnit1(xs[1])
|
420 |
+
output = self.skip_add.add(output, res)
|
421 |
+
# output += res
|
422 |
+
|
423 |
+
output = self.resConfUnit2(output)
|
424 |
+
|
425 |
+
if (size is None) and (self.size is None):
|
426 |
+
modifier = {"scale_factor": 2}
|
427 |
+
elif size is None:
|
428 |
+
modifier = {"size": self.size}
|
429 |
+
else:
|
430 |
+
modifier = {"size": size}
|
431 |
+
|
432 |
+
output = nn.functional.interpolate(
|
433 |
+
output, **modifier, mode="bilinear", align_corners=self.align_corners
|
434 |
+
)
|
435 |
+
|
436 |
+
output = self.out_conv(output)
|
437 |
+
|
438 |
+
return output
|
439 |
+
|
geobench/midas/dpt_depth.py
ADDED
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
|
4 |
+
from .base_model import BaseModel
|
5 |
+
from .blocks import (
|
6 |
+
FeatureFusionBlock_custom,
|
7 |
+
Interpolate,
|
8 |
+
_make_encoder,
|
9 |
+
forward_beit,
|
10 |
+
forward_swin,
|
11 |
+
forward_levit,
|
12 |
+
forward_vit,
|
13 |
+
)
|
14 |
+
from .backbones.levit import stem_b4_transpose
|
15 |
+
from timm.models.layers import get_act_layer
|
16 |
+
|
17 |
+
|
18 |
+
def _make_fusion_block(features, use_bn, size = None):
|
19 |
+
return FeatureFusionBlock_custom(
|
20 |
+
features,
|
21 |
+
nn.ReLU(False),
|
22 |
+
deconv=False,
|
23 |
+
bn=use_bn,
|
24 |
+
expand=False,
|
25 |
+
align_corners=True,
|
26 |
+
size=size,
|
27 |
+
)
|
28 |
+
|
29 |
+
|
30 |
+
class DPT(BaseModel):
|
31 |
+
def __init__(
|
32 |
+
self,
|
33 |
+
head,
|
34 |
+
features=256,
|
35 |
+
backbone="vitb_rn50_384",
|
36 |
+
readout="project",
|
37 |
+
channels_last=False,
|
38 |
+
use_bn=False,
|
39 |
+
**kwargs
|
40 |
+
):
|
41 |
+
|
42 |
+
super(DPT, self).__init__()
|
43 |
+
|
44 |
+
self.channels_last = channels_last
|
45 |
+
|
46 |
+
# For the Swin, Swin 2, LeViT and Next-ViT Transformers, the hierarchical architectures prevent setting the
|
47 |
+
# hooks freely. Instead, the hooks have to be chosen according to the ranges specified in the comments.
|
48 |
+
hooks = {
|
49 |
+
"beitl16_512": [5, 11, 17, 23],
|
50 |
+
"beitl16_384": [5, 11, 17, 23],
|
51 |
+
"beitb16_384": [2, 5, 8, 11],
|
52 |
+
"swin2l24_384": [1, 1, 17, 1], # Allowed ranges: [0, 1], [0, 1], [ 0, 17], [ 0, 1]
|
53 |
+
"swin2b24_384": [1, 1, 17, 1], # [0, 1], [0, 1], [ 0, 17], [ 0, 1]
|
54 |
+
"swin2t16_256": [1, 1, 5, 1], # [0, 1], [0, 1], [ 0, 5], [ 0, 1]
|
55 |
+
"swinl12_384": [1, 1, 17, 1], # [0, 1], [0, 1], [ 0, 17], [ 0, 1]
|
56 |
+
"next_vit_large_6m": [2, 6, 36, 39], # [0, 2], [3, 6], [ 7, 36], [37, 39]
|
57 |
+
"levit_384": [3, 11, 21], # [0, 3], [6, 11], [14, 21]
|
58 |
+
"vitb_rn50_384": [0, 1, 8, 11],
|
59 |
+
"vitb16_384": [2, 5, 8, 11],
|
60 |
+
"vitl16_384": [5, 11, 17, 23],
|
61 |
+
}[backbone]
|
62 |
+
|
63 |
+
if "next_vit" in backbone:
|
64 |
+
in_features = {
|
65 |
+
"next_vit_large_6m": [96, 256, 512, 1024],
|
66 |
+
}[backbone]
|
67 |
+
else:
|
68 |
+
in_features = None
|
69 |
+
|
70 |
+
# Instantiate backbone and reassemble blocks
|
71 |
+
self.pretrained, self.scratch = _make_encoder(
|
72 |
+
backbone,
|
73 |
+
features,
|
74 |
+
False, # Set to true of you want to train from scratch, uses ImageNet weights
|
75 |
+
groups=1,
|
76 |
+
expand=False,
|
77 |
+
exportable=False,
|
78 |
+
hooks=hooks,
|
79 |
+
use_readout=readout,
|
80 |
+
in_features=in_features,
|
81 |
+
)
|
82 |
+
|
83 |
+
self.number_layers = len(hooks) if hooks is not None else 4
|
84 |
+
size_refinenet3 = None
|
85 |
+
self.scratch.stem_transpose = None
|
86 |
+
|
87 |
+
if "beit" in backbone:
|
88 |
+
self.forward_transformer = forward_beit
|
89 |
+
elif "swin" in backbone:
|
90 |
+
self.forward_transformer = forward_swin
|
91 |
+
elif "next_vit" in backbone:
|
92 |
+
from .backbones.next_vit import forward_next_vit
|
93 |
+
self.forward_transformer = forward_next_vit
|
94 |
+
elif "levit" in backbone:
|
95 |
+
self.forward_transformer = forward_levit
|
96 |
+
size_refinenet3 = 7
|
97 |
+
self.scratch.stem_transpose = stem_b4_transpose(256, 128, get_act_layer("hard_swish"))
|
98 |
+
else:
|
99 |
+
self.forward_transformer = forward_vit
|
100 |
+
|
101 |
+
self.scratch.refinenet1 = _make_fusion_block(features, use_bn)
|
102 |
+
self.scratch.refinenet2 = _make_fusion_block(features, use_bn)
|
103 |
+
self.scratch.refinenet3 = _make_fusion_block(features, use_bn, size_refinenet3)
|
104 |
+
if self.number_layers >= 4:
|
105 |
+
self.scratch.refinenet4 = _make_fusion_block(features, use_bn)
|
106 |
+
|
107 |
+
self.scratch.output_conv = head
|
108 |
+
|
109 |
+
|
110 |
+
def forward(self, x):
|
111 |
+
if self.channels_last == True:
|
112 |
+
x.contiguous(memory_format=torch.channels_last)
|
113 |
+
|
114 |
+
layers = self.forward_transformer(self.pretrained, x)
|
115 |
+
if self.number_layers == 3:
|
116 |
+
layer_1, layer_2, layer_3 = layers
|
117 |
+
else:
|
118 |
+
layer_1, layer_2, layer_3, layer_4 = layers
|
119 |
+
|
120 |
+
layer_1_rn = self.scratch.layer1_rn(layer_1)
|
121 |
+
layer_2_rn = self.scratch.layer2_rn(layer_2)
|
122 |
+
layer_3_rn = self.scratch.layer3_rn(layer_3)
|
123 |
+
if self.number_layers >= 4:
|
124 |
+
layer_4_rn = self.scratch.layer4_rn(layer_4)
|
125 |
+
|
126 |
+
if self.number_layers == 3:
|
127 |
+
path_3 = self.scratch.refinenet3(layer_3_rn, size=layer_2_rn.shape[2:])
|
128 |
+
else:
|
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 |
+
if self.scratch.stem_transpose is not None:
|
135 |
+
path_1 = self.scratch.stem_transpose(path_1)
|
136 |
+
|
137 |
+
out = self.scratch.output_conv(path_1)
|
138 |
+
|
139 |
+
return out
|
140 |
+
|
141 |
+
|
142 |
+
class DPTDepthModel(DPT):
|
143 |
+
def __init__(self, path=None, non_negative=True, **kwargs):
|
144 |
+
features = kwargs["features"] if "features" in kwargs else 256
|
145 |
+
head_features_1 = kwargs["head_features_1"] if "head_features_1" in kwargs else features
|
146 |
+
head_features_2 = kwargs["head_features_2"] if "head_features_2" in kwargs else 32
|
147 |
+
kwargs.pop("head_features_1", None)
|
148 |
+
kwargs.pop("head_features_2", None)
|
149 |
+
|
150 |
+
head = nn.Sequential(
|
151 |
+
nn.Conv2d(head_features_1, head_features_1 // 2, kernel_size=3, stride=1, padding=1),
|
152 |
+
Interpolate(scale_factor=2, mode="bilinear", align_corners=True),
|
153 |
+
nn.Conv2d(head_features_1 // 2, head_features_2, kernel_size=3, stride=1, padding=1),
|
154 |
+
nn.ReLU(True),
|
155 |
+
nn.Conv2d(head_features_2, 1, kernel_size=1, stride=1, padding=0),
|
156 |
+
nn.ReLU(True) if non_negative else nn.Identity(),
|
157 |
+
nn.Identity(),
|
158 |
+
)
|
159 |
+
|
160 |
+
super().__init__(head, **kwargs)
|
161 |
+
|
162 |
+
if path is not None:
|
163 |
+
self.load(path)
|
164 |
+
|
165 |
+
def forward(self, x):
|
166 |
+
return super().forward(x)
|