-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory_module.py
More file actions
217 lines (190 loc) · 7.73 KB
/
Copy pathmemory_module.py
File metadata and controls
217 lines (190 loc) · 7.73 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
from __future__ import absolute_import, print_function
import torch
from torch import nn
import math
from torch.nn.parameter import Parameter
from torch.nn import functional as F
import numpy as np
#
class MemoryUnit(nn.Module):
def __init__(self, mem_dim, fea_dim, shrink_thres=0.0025):
super(MemoryUnit, self).__init__()
self.mem_dim = mem_dim
self.fea_dim = fea_dim
self.weight = Parameter(torch.Tensor(self.mem_dim, self.fea_dim)) # M x C
self.bias = None
self.shrink_thres= shrink_thres
# self.hard_sparse_shrink_opt = nn.Hardshrink(lambd=shrink_thres)
self.reset_parameters()
def reset_parameters(self):
stdv = 1. / math.sqrt(self.weight.size(1))
self.weight.data.uniform_(-stdv, stdv)
if self.bias is not None:
self.bias.data.uniform_(-stdv, stdv)
def forward(self, input):
att_weight = F.linear(input, self.weight) # Fea x Mem^T, (TxC) x (CxM) = TxM
att_weight = F.softmax(att_weight, dim=1) # TxM
# ReLU based shrinkage, hard shrinkage for positive value
if(self.shrink_thres>0):
att_weight = hard_shrink_relu(att_weight, lambd=self.shrink_thres)
# att_weight = F.softshrink(att_weight, lambd=self.shrink_thres)
# normalize???
att_weight = F.normalize(att_weight, p=1, dim=1)
# att_weight = F.softmax(att_weight, dim=1)
# att_weight = self.hard_sparse_shrink_opt(att_weight)
mem_trans = self.weight.permute(1, 0) # Mem^T, MxC
# print(f'mem_trans : {mem_trans.size()}')
output = F.linear(att_weight, mem_trans) # AttWeight x Mem^T^T = AW x Mem, (TxM) x (MxC) = TxC
return {'output': output, 'att': att_weight} # output, att_weight
def extra_repr(self):
return 'mem_dim={}, fea_dim={}'.format(
self.mem_dim, self.fea_dim is not None
)
# NxCxHxW -> (NxHxW)xC -> addressing Mem, (NxHxW)xC -> NxCxHxW
class MemModule(nn.Module):
def __init__(self, mem_dim, fea_dim, shrink_thres=0.0025, device='cuda'):
super(MemModule, self).__init__()
self.mem_dim = mem_dim
self.fea_dim = fea_dim
self.shrink_thres = shrink_thres
self.memory = MemoryUnit(self.mem_dim, self.fea_dim, self.shrink_thres)
def forward(self, input):
s = input.data.shape
l = len(s)
# [2 64 8 8]
if l == 3:
x = input.permute(0, 2, 1)
elif l == 4:
x = input.permute(0, 2, 3, 1)
elif l == 5:
x = input.permute(0, 2, 3, 4, 1)
else:
x = []
print('wrong feature map size')
# print(f'input = {input.size()}')
# [2 8 8 64]
# print(f'x = {x.size()}')
x = x.contiguous()
x = x.view(-1, s[1])
# [2*8*8, 64]
# print(x.size())
#
y_and = self.memory(x)
#
y = y_and['output']
att = y_and['att']
if l == 3:
y = y.view(s[0], s[2], s[1])
y = y.permute(0, 2, 1)
att = att.view(s[0], s[2], self.mem_dim)
att = att.permute(0, 2, 1)
elif l == 4:
y = y.view(s[0], s[2], s[3], s[1])
y = y.permute(0, 3, 1, 2)
att = att.view(s[0], s[2], s[3], self.mem_dim)
att = att.permute(0, 3, 1, 2)
elif l == 5:
y = y.view(s[0], s[2], s[3], s[4], s[1])
y = y.permute(0, 4, 1, 2, 3)
att = att.view(s[0], s[2], s[3], s[4], self.mem_dim)
att = att.permute(0, 4, 1, 2, 3)
else:
y = x
att = att
print('wrong feature map size')
return {'output': y, 'att': att}
class MemoryUnit_VAE(nn.Module):
def __init__(self, mem_dim, fea_dim, shrink_thres=0.0025):
super(MemoryUnit, self).__init__()
self.mem_dim = mem_dim
self.fea_dim = fea_dim
self.weight = Parameter(torch.Tensor(self.mem_dim, self.fea_dim)) # M x C
self.bias = None
self.shrink_thres= shrink_thres
# self.hard_sparse_shrink_opt = nn.Hardshrink(lambd=shrink_thres)
self.reset_parameters()
def reset_parameters(self):
stdv = 1. / math.sqrt(self.weight.size(1))
self.weight.data.uniform_(-stdv, stdv)
if self.bias is not None:
self.bias.data.uniform_(-stdv, stdv)
def forward(self, input):
att_weight_mu = F.linear(input, self.weight) # Fea x Mem^T, (TxC) x (CxM) = TxM
att_weight_sigma = torch.exp(F.linear(input, self.wight))
att_weight_normal = torch.distributions.Normal(loc=att_weight_mu, scale=att_weight_sigma)
att_weight = att_weight_normal.rsample()
# ReLU based shrinkage, hard shrinkage for positive value
if(self.shrink_thres>0):
att_weight = z_score_shrinkage_normal(att_weight, att_weight_mu, att_weight_sigma, threshold=2)
# att_weight = F.softshrink(att_weight, lambd=self.shrink_thres)
# normalize???
att_weight = F.normalize(att_weight, p=1, dim=1)
# att_weight = F.softmax(att_weight, dim=1)
# att_weight = self.hard_sparse_shrink_opt(att_weight)
mem_trans = self.weight.permute(1, 0) # Mem^T, MxC
# print(f'mem_trans : {mem_trans.size()}')
output = F.linear(att_weight, mem_trans) # AttWeight x Mem^T^T = AW x Mem, (TxM) x (MxC) = TxC
return {'output': output, 'att': att_weight, 'normal':att_weight_normal} # output, att_weight
def extra_repr(self):
return 'mem_dim={}, fea_dim={}'.format(
self.mem_dim, self.fea_dim is not None
)
class MemModule_VAE(nn.Module):
def __init__(self, mem_dim, fea_dim, shrink_thres=0.0025, device='cuda'):
super(MemModule, self).__init__()
self.mem_dim = mem_dim
self.fea_dim = fea_dim
self.shrink_thres = shrink_thres
self.memory = MemoryUnit_VAE(self.mem_dim, self.fea_dim, self.shrink_thres)
def forward(self, input):
s = input.data.shape
l = len(s)
# [2 64 8 8]
if l == 3:
x = input.permute(0, 2, 1)
elif l == 4:
x = input.permute(0, 2, 3, 1)
elif l == 5:
x = input.permute(0, 2, 3, 4, 1)
else:
x = []
print('wrong feature map size')
# print(f'input = {input.size()}')
# [2 8 8 64]
# print(f'x = {x.size()}')
x = x.contiguous()
x = x.view(-1, s[1])
# [2*8*8, 64]
# print(x.size())
#
y_and = self.memory(x)
#
y = y_and['output']
att = y_and['att']
q_z = y_and['normal']
if l == 3:
y = y.view(s[0], s[2], s[1])
y = y.permute(0, 2, 1)
att = att.view(s[0], s[2], self.mem_dim)
att = att.permute(0, 2, 1)
elif l == 4:
y = y.view(s[0], s[2], s[3], s[1])
y = y.permute(0, 3, 1, 2)
att = att.view(s[0], s[2], s[3], self.mem_dim)
att = att.permute(0, 3, 1, 2)
elif l == 5:
y = y.view(s[0], s[2], s[3], s[4], s[1])
y = y.permute(0, 4, 1, 2, 3)
att = att.view(s[0], s[2], s[3], s[4], self.mem_dim)
att = att.permute(0, 4, 1, 2, 3)
else:
y = x
att = att
print('wrong feature map size')
return {'output': y, 'att': att, 'normal':q_z}
def z_score_shrinkage_normal(input, mu, sigma, threshold=2):
# Compute z-score directly using the provided mu and sigma from VAE
z_score = (input - mu) / sigma
# Apply threshold: set values with z-score greater than the threshold to 0
output = torch.where(torch.abs(z_score) > threshold, torch.tensor(0.0, device=input.device), input)
return output