-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.py
184 lines (147 loc) · 8.01 KB
/
model.py
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
import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from util import normalize
class SFTFuse(nn.Module):
def __init__(self, args):
super().__init__()
self.args = args
self.wcoef = args.beta
self.xcoef = args.gamma
self.h_dim = args.h_dim
self.enc1 = nn.Dropout(args.dropout)
self.enc2 = nn.Dropout(args.dropout)
def split_instances(self, data):
args = self.args
if self.training:
return (torch.Tensor(np.arange(args.train_way*args.shot)).long().view(1, args.shot, args.train_way),
torch.Tensor(np.arange(args.train_way*args.shot, args.train_way * (args.shot + args.train_query))).long().view(1, args.train_query, args.train_way))
else:
return (torch.Tensor(np.arange(args.test_way*args.shot)).long().view(1, args.shot, args.test_way),
torch.Tensor(np.arange(args.test_way*args.shot, args.test_way * (args.shot + args.test_query))).long().view(1, args.test_query, args.test_way))
def forward(self, x, y):
# dropout layers
x = self.enc1(x)
y = self.enc2(y)
# feature fusion
x = x * self.wcoef
y = y * self.xcoef
x = x + y
instance_embs = x
# split support query set for few-shot data
support_idx, query_idx = self.split_instances(x)
if self.training:
logits, logits_reg = self._forward(instance_embs, support_idx, query_idx)
return logits, logits_reg
else:
logits = self._forward(instance_embs, support_idx, query_idx)
return logits
def _forward(self, x, support_idx, query_idx):
raise NotImplementedError('Suppose to be implemented by subclass')
class ScaledDotProductAttention(nn.Module):
''' Scaled Dot-Product Attention '''
def __init__(self, temperature, attn_dropout=0.1):
super().__init__()
self.temperature = temperature
self.dropout = nn.Dropout(attn_dropout)
self.softmax = nn.Softmax(dim=2)
def forward(self, q, k, v):
attn = torch.bmm(q, k.transpose(1, 2))
attn = attn / self.temperature
log_attn = F.log_softmax(attn, 2)
attn = self.softmax(attn)
attn = self.dropout(attn)
output = torch.bmm(attn, v)
return output, attn, log_attn
class MultiHeadAttention(nn.Module):
''' Multi-Head Attention module '''
def __init__(self, n_head, d_model, d_k, d_v, dropout=0.1):
super().__init__()
self.n_head = n_head
self.d_k = d_k
self.d_v = d_v
self.w_qs = nn.Linear(d_model, n_head * d_k, bias=False)
self.w_ks = nn.Linear(d_model, n_head * d_k, bias=False)
self.w_vs = nn.Linear(d_model, n_head * d_v, bias=False)
nn.init.normal_(self.w_qs.weight, mean=0, std=np.sqrt(2.0 / (d_model + d_k)))
nn.init.normal_(self.w_ks.weight, mean=0, std=np.sqrt(2.0 / (d_model + d_k)))
nn.init.normal_(self.w_vs.weight, mean=0, std=np.sqrt(2.0 / (d_model + d_v)))
self.attention = ScaledDotProductAttention(temperature=np.power(d_k, 0.5))
self.layer_norm = nn.LayerNorm(d_model)
self.fc = nn.Linear(n_head * d_v, d_model)
nn.init.xavier_normal_(self.fc.weight)
self.dropout = nn.Dropout(dropout)
def forward(self, q, k, v):
d_k, d_v, n_head = self.d_k, self.d_v, self.n_head
sz_b, len_q, _ = q.size()
sz_b, len_k, _ = k.size()
sz_b, len_v, _ = v.size()
residual = q
q = self.w_qs(q).view(sz_b, len_q, n_head, d_k)
k = self.w_ks(k).view(sz_b, len_k, n_head, d_k)
v = self.w_vs(v).view(sz_b, len_v, n_head, d_v)
q = q.permute(2, 0, 1, 3).contiguous().view(-1, len_q, d_k) # (n*b) x lq x dk
k = k.permute(2, 0, 1, 3).contiguous().view(-1, len_k, d_k) # (n*b) x lk x dk
v = v.permute(2, 0, 1, 3).contiguous().view(-1, len_v, d_v) # (n*b) x lv x dv
output, _, _ = self.attention(q, k, v)
output = output.view(n_head, sz_b, len_q, d_v)
output = output.permute(1, 2, 0, 3).contiguous().view(sz_b, len_q, -1) # b x lq x (n*dv)
output = self.dropout(self.fc(output))
output = self.layer_norm(output + residual)
return output
class SFTAttn(SFTFuse):
def __init__(self, args):
super().__init__(args)
self.slf_attn = MultiHeadAttention(1, self.h_dim, self.h_dim, self.h_dim, dropout=0.5)
def _forward(self, instance_embs, support_idx, query_idx):
emb_dim = instance_embs.size(-1)
# normalize during eval stage
if not self.training and self.args.norm:
instance_embs = normalize(instance_embs)
# organize support/query data
support = instance_embs[support_idx.contiguous().view(-1)].contiguous().view(*(support_idx.shape + (-1,)))
query = instance_embs[query_idx.contiguous().view(-1)].contiguous().view( *(query_idx.shape + (-1,)))
# get mean of the support
proto = support.mean(dim=1) # Ntask x NK x d
num_batch = proto.shape[0]
num_proto = proto.shape[1]
num_query = np.prod(query_idx.shape[-2:])
# query: (num_batch, num_query, num_proto, num_emb)
# proto: (num_batch, num_proto, num_emb)
proto = self.slf_attn(proto, proto, proto)
if self.args.distance == 'euc':
query = query.view(-1, emb_dim).unsqueeze(1) # (Nbatch*Nq*Nw, 1, d)
proto = proto.unsqueeze(1).expand(num_batch, num_query, num_proto, emb_dim).contiguous()
proto = proto.view(num_batch*num_query, num_proto, emb_dim) # (Nbatch x Nq, Nk, d)
logits = - torch.sum((proto - query) ** 2, 2) / self.args.temperature
else:
proto = F.normalize(proto, dim=-1) # normalize for cosine distance
query = query.view(num_batch, -1, emb_dim) # (Nbatch, Nq*Nw, d)
logits = torch.bmm(query, proto.permute([0,2,1])) / self.args.temperature
logits = logits.view(-1, num_proto)
# for regularization
if self.training:
aux_task = torch.cat([support.view(1, self.args.shot, self.args.train_way, emb_dim),
query.view(1, self.args.train_query, self.args.train_way, emb_dim)], 1) # T x (K+Kq) x N x d
num_query = np.prod(aux_task.shape[1:3])
aux_task = aux_task.permute([0, 2, 1, 3])
aux_task = aux_task.contiguous().view(-1, self.args.shot + self.args.train_query, emb_dim)
# apply the transformation over the Aug Task
aux_emb = self.slf_attn(aux_task, aux_task, aux_task) # T x N x (K+Kq) x d
# compute class mean
aux_emb = aux_emb.view(num_batch, self.args.train_way, self.args.shot + self.args.train_query, emb_dim)
aux_center = torch.mean(aux_emb, 2) # T x N x d
if self.args.distance == 'euc':
aux_task = aux_task.permute([1,0,2]).contiguous().view(-1, emb_dim).unsqueeze(1) # (Nbatch*Nq*Nw, 1, d)
aux_center = aux_center.unsqueeze(1).expand(num_batch, num_query, num_proto, emb_dim).contiguous()
aux_center = aux_center.view(num_batch*num_query, num_proto, emb_dim) # (Nbatch x Nq, Nk, d)
logits_reg = - torch.sum((aux_center - aux_task) ** 2, 2) / self.args.temperature2
else:
aux_center = F.normalize(aux_center, dim=-1) # normalize for cosine distance
aux_task = aux_task.permute([1,0,2]).contiguous().view(num_batch, -1, emb_dim) # (Nbatch, Nq*Nw, d)
logits_reg = torch.bmm(aux_task, aux_center.permute([0,2,1])) / self.args.temperature2
logits_reg = logits_reg.view(-1, num_proto)
return logits, logits_reg
else:
return logits