Safemotion Lib
Loading...
Searching...
No Matches
non_local.py
Go to the documentation of this file.
1# encoding: utf-8
2
3
4import torch
5from torch import nn
6from .batch_norm import get_norm
7
8
9class Non_local(nn.Module):
10 def __init__(self, in_channels, bn_norm, reduc_ratio=2):
11 super(Non_local, self).__init__()
12
13 self.in_channels = in_channels
14 self.inter_channels = in_channels // reduc_ratio
15
16 self.g = nn.Conv2d(in_channels=self.in_channels, out_channels=self.inter_channels,
17 kernel_size=1, stride=1, padding=0)
18
19 self.W = nn.Sequential(
20 nn.Conv2d(in_channels=self.inter_channels, out_channels=self.in_channels,
21 kernel_size=1, stride=1, padding=0),
22 get_norm(bn_norm, self.in_channels),
23 )
24 nn.init.constant_(self.W[1].weight, 0.0)
25 nn.init.constant_(self.W[1].bias, 0.0)
26
27 self.theta = nn.Conv2d(in_channels=self.in_channels, out_channels=self.inter_channels,
28 kernel_size=1, stride=1, padding=0)
29
30 self.phi = nn.Conv2d(in_channels=self.in_channels, out_channels=self.inter_channels,
31 kernel_size=1, stride=1, padding=0)
32
33 def forward(self, x):
34 """
35 :param x: (b, t, h, w)
36 :return x: (b, t, h, w)
37 """
38 batch_size = x.size(0)
39 g_x = self.g(x).view(batch_size, self.inter_channels, -1)
40 g_x = g_x.permute(0, 2, 1)
41
42 theta_x = self.theta(x).view(batch_size, self.inter_channels, -1)
43 theta_x = theta_x.permute(0, 2, 1)
44 phi_x = self.phi(x).view(batch_size, self.inter_channels, -1)
45 f = torch.matmul(theta_x, phi_x)
46 N = f.size(-1)
47 f_div_C = f / N
48
49 y = torch.matmul(f_div_C, g_x)
50 y = y.permute(0, 2, 1).contiguous()
51 y = y.view(batch_size, self.inter_channels, *x.size()[2:])
52 W_y = self.W(y)
53 z = W_y + x
54 return z
__init__(self, in_channels, bn_norm, reduc_ratio=2)
Definition non_local.py:10