File size: 1,985 Bytes
31d2102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
"""TinyDepth: MobileNetV4-Small encoder + lightweight depthwise FPN decoder for relative (disparity) depth."""
import timm
import torch
import torch.nn as nn
import torch.nn.functional as F


def dwconv(cin, cout):
    """Depthwise-separable 3x3 conv block (cheap on CPU / edge NPUs)."""
    return nn.Sequential(
        nn.Conv2d(cin, cin, 3, padding=1, groups=cin, bias=False), nn.BatchNorm2d(cin), nn.ReLU(inplace=True),
        nn.Conv2d(cin, cout, 1, bias=False), nn.BatchNorm2d(cout), nn.ReLU(inplace=True),
    )


class TinyDepth(nn.Module):
    def __init__(self, backbone="mobilenetv4_conv_small.e2400_r224_in1k", dec_ch=64, pretrained=True):
        super().__init__()
        self.encoder = timm.create_model(backbone, pretrained=pretrained, features_only=True, out_indices=(0, 1, 2, 3, 4))
        chs = self.encoder.feature_info.channels()  # strides 2,4,8,16,32
        self.lateral = nn.ModuleList([nn.Conv2d(c, dec_ch, 1) for c in chs])
        self.fuse = nn.ModuleList([dwconv(dec_ch, dec_ch) for _ in chs[:-1]])
        self.head = nn.Sequential(
            dwconv(dec_ch, 32),
            nn.Conv2d(32, 1, 3, padding=1),
            nn.ReLU(),  # disparity is non-negative
        )

    def forward(self, x):
        feats = self.encoder(x)
        y = self.lateral[-1](feats[-1])
        for i in range(len(feats) - 2, -1, -1):
            y = F.interpolate(y, size=feats[i].shape[-2:], mode="bilinear", align_corners=False)
            y = self.fuse[i](y + self.lateral[i](feats[i]))
        y = self.head(y)  # head runs at stride 2; upsample only the 1-channel map (much cheaper on CPU)
        y = F.interpolate(y, size=x.shape[-2:], mode="bilinear", align_corners=False)
        return y[:, 0]  # (B, H, W) relative inverse depth


if __name__ == "__main__":
    m = TinyDepth()
    print("channels", m.encoder.feature_info.channels())
    print(f"params {sum(p.numel() for p in m.parameters())/1e6:.2f}M")
    print(m(torch.randn(2, 3, 240, 320)).shape)