-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathattn_model.py
executable file
·194 lines (154 loc) · 6.4 KB
/
attn_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
import torch
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence
from torch.autograd import Variable
from Attention import Attn
import torch.nn.functional as F
# 3x3 Convolution
def conv3x3(in_channels, out_channels, stride=1):
return nn.Conv2d(in_channels, out_channels, kernel_size=3,
stride=stride, padding=1, bias=False)
# Residual Block
class ResidualBlock(nn.Module):
def __init__(self, in_channels, out_channels, stride=1, downsample=None):
super(ResidualBlock, self).__init__()
self.conv1 = conv3x3(in_channels, out_channels, stride)
self.bn1 = nn.BatchNorm2d(out_channels)
self.relu = nn.ReLU(inplace=True)
self.conv2 = conv3x3(out_channels, out_channels)
self.bn2 = nn.BatchNorm2d(out_channels)
self.downsample = downsample
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
# ResNet Module for Show Attend and Tell model
class AttnEncoder(nn.Module):
def __init__(self, block, layers):
super(AttnEncoder, self).__init__()
self.in_channels = 32
self.conv = conv3x3(3, 32)
self.bn = nn.BatchNorm2d(32)
self.relu = nn.ReLU(inplace=True)
self.layer1 = self.make_layer(block, 32, layers[0])
self.layer2 = self.make_layer(block, 64, layers[0],2)
self.layer3 = self.make_layer(block, 128, layers[1],2)
#self.init_weights()
def init_weights(self):
"""Initialize the weights."""
self.fc.weight.data.normal_(0.0, 0.02)
self.fc.bias.data.fill_(0)
self.fc2.weight.data.normal_(0.0, 0.02)
self.fc2.bias.data.fill_(0)
def make_layer(self, block, out_channels, blocks, stride=1):
downsample = None
if (stride != 1) or (self.in_channels != out_channels):
downsample = nn.Sequential(
conv3x3(self.in_channels, out_channels, stride=stride),
nn.BatchNorm2d(out_channels))
layers = []
layers.append(block(self.in_channels, out_channels, stride, downsample))
self.in_channels = out_channels
for i in range(1, blocks):
layers.append(block(out_channels, out_channels))
return nn.Sequential(*layers)
def forward(self, x):
out = self.conv(x)
out = self.bn(out)
out = self.relu(out)
out = self.layer1(out)
out = self.layer2(out)
out = self.layer3(out)
out = out.view(out.size(0), out.size(1), -1)
return out
class AttnDecoderRnn(nn.Module):
def __init__(self, feature_size, hidden_size, vocab_size, num_layers):
super(AttnDecoderRnn, self).__init__()
#Define parameters
#Define layers
self.embed = nn.Embedding(vocab_size, feature_size)
self.init_layer = nn.Linear(feature_size, hidden_size)
self.attn = Attn('general', feature_size, hidden_size)
self.lstm = nn.LSTM(hidden_size, hidden_size, batch_first=True)
self.ctx2out = nn.Linear(feature_size, feature_size)
self.h2out = nn.Linear(hidden_size, feature_size)
self.out = nn.Linear(feature_size, vocab_size)
self.out_cat = nn.Linear(feature_size*3, vocab_size)
def decode_lstm(self, input_word, context, hidden, lstm_out):
hidden = hidden.squeeze(0)
out = self.h2out(hidden)
context = context.squeeze(1)
out += self.ctx2out(context)
out += input_word
out = F.tanh(out)
out = self.out(out)
# hidden = hidden.squeeze(0)
# out = self.h2out(hidden)
# context = context.squeeze(1)
# out1 = self.ctx2out(context)
# out = torch.cat((out, out1, input_word),1)
# out = F.tanh(out)
# out = self.out_cat(out)
return out
def init_lstm(self, features):
sums = torch.sum(features, 2)
out = torch.mul(sums, 1/features.size(2))
out = out.squeeze(2).unsqueeze(0) # 1, batch, feature_size
out = self.init_layer(out.squeeze(0)).unsqueeze(0)
out = F.tanh(out)
return out, out
def forward(self, features, captions, lengths):
max_length = max(lengths)
embed = self.embed(captions)
h, c= self.init_lstm(features)
arr = []
for i in range(max_length):
if i == 0 :
input_word = Variable(torch.zeros(embed.size(0), embed.size(2))).cuda()
else:
input_word = embed[:,i-1]
context = self.attn(h, features)
#input_word = embed[:,i]
lstm_input = torch.cat((context, input_word.unsqueeze(1)),2)
lstm_out, (h,c) = self.lstm(lstm_input, (h,c))
out = self.decode_lstm(input_word,context, h, lstm_out).unsqueeze(1)
#out = F.softmax(out)
arr += [out]
return torch.cat(arr,1)
def sample(self, features):
"""Samples captions for given image features (Greedy search)."""
sampled_ids = []
h,c = self.init_lstm(features)
for i in range(40): # maximum sampling length
if i == 0:
#word_init = Variable(torch.LongTensor([1])).cuda()
#x = self.embed(word_init).unsqueeze(1)
x = Variable(torch.rand(1,1,128)).cuda()
#sampled_ids.append(word_init)
else:
x = self.embed((predicted))
context = self.attn(h, features)
lstm_input = torch.cat((context, x) ,2)
lstm_out, (h,c) = self.lstm(lstm_input, (h,c)) # (batch_size, 1, hidden_size),
out = self.decode_lstm(x, context, h, lstm_out)
# hidden = lstm_out.squeeze(0)
# out = self.h2out(hidden)
# context = context.squeeze(1)
# out += self.ctx2out(context)
# out += x
# out = F.tanh(out)
# out = self.out(out)
predicted = out.max(1)[1]
#print(predicted)
sampled_ids.append(predicted)
#print(sampled_ids)
#sampled_ids = torch.cat(sampled_ids, 1) # (batch_size, 20)
return sampled_ids