-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinference.py
More file actions
175 lines (148 loc) · 8.05 KB
/
inference.py
File metadata and controls
175 lines (148 loc) · 8.05 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
import json
import os
import torch
from PIL import Image
from torchvision import transforms
import torch.nn.functional as F
def load_image(im_path):
img = Image.open(im_path)
tensor_img = transforms.Compose(
[
transforms.PILToTensor(),
transforms.Resize([256, 256],antialias=True),
transforms.ConvertImageDtype(torch.float),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
]
)
img = tensor_img(img)
return img
def inference_plain(im_path, saved_model_path, save_caption_file=False):
# device = "mps" if torch.backends.mps.is_available() else "cuda" if torch.cuda.is_available() else "cpu"
device = "cpu"
print(f"For plain, using device = {device}")
max_caption_size = 25
state_dict = torch.load(saved_model_path, map_location=device)
enc = state_dict["encoder"].to(device)
dec = state_dict["decoder"].to(device)
image = load_image(im_path)
image = image.unsqueeze(0).to(device)
enc_image = enc(image)
enc_image = enc_image.view(enc_image.size(0),-1, 2048)
prev_word = "<sos>"
hidden_state = dec.initialize_hidden_state(enc_image.mean(dim=1))
cell_state = dec.initialize_cell_state(enc_image.mean(dim=1))
caption = []
while (prev_word!="<eos>") and (len(caption)<max_caption_size):
alphas_for_each_pixel = dec.attention_net(enc_image,hidden_state)
gating_scalar = dec.layer_to_get_gating_scalar(hidden_state)
gating_scalar = dec.sigmoid_act(gating_scalar)
encoding_with_attention = gating_scalar * ((enc_image* alphas_for_each_pixel.unsqueeze(2)).sum(dim=1))
embedding_value = dec.embedding_layer(torch.LongTensor([word2idx[prev_word]]).to(device))
hidden_state, cell_state = dec.lstm_cell(torch.cat([embedding_value,encoding_with_attention,],dim=1,),(hidden_state,cell_state))
scores = dec.layer_to_get_word_scores(hidden_state)
scores = (F.softmax(scores,dim=1).squeeze().tolist())
max_ind = max(range(len(scores)), key = lambda a:scores[a])
prev_word = idx2word[max_ind]
if prev_word!="<eos>":
caption.append(prev_word)
caption = " ".join(caption)
if save_caption_file:
im_path_dir = os.path.dirname(im_path)
im_path_file = os.path.basename(im_path)
caption_path_basename = im_path_file.split(".")[0] + ".txt"
caption_path = os.path.join(im_path_dir, caption_path_basename)
with open(caption_path, "w") as f:
f.write(f"{im_path}:\n")
f.write(caption)
return caption
def inference_beam_search(im_path, saved_model_path, beam_size = 5, save_caption_file=False):
max_caption_size = 25
# device = "mps" if torch.backends.mps.is_available() else "cuda" if torch.cuda.is_available() else "cpu"
device = 'cpu'
print(f"For beam search, using device = {device}")
state_dict = torch.load(saved_model_path, map_location=device)
enc = state_dict["encoder"].to(device)
dec = state_dict["decoder"].to(device)
image = load_image(im_path)
image = image.unsqueeze(0).to(device)
enc_image = enc(image)
enc_image = enc_image.view(enc_image.size(0),-1, 2048)
n_pixels = enc_image.shape[1]
enc_image = enc_image.expand(beam_size, n_pixels, 2048)
caption_prev_words = torch.LongTensor([[word2idx['<sos>']]] * beam_size).to(device)
captions = caption_prev_words
top_caption_scores = torch.zeros(beam_size, 1).to(device)
# captions_alpha = torch.ones(beam_size, 1, enc.encoder_image_size, enc.encoder_image_size).to(device)
captions_alpha = torch.ones(beam_size, 1, 16, 16).to(device)
generated_captions, generated_caption_scores = [], []
time_step = 0
hidden_state = dec.initialize_hidden_state(enc_image.mean(dim=1))
cell_state = dec.initialize_cell_state(enc_image.mean(dim=1))
while time_step<max_caption_size:
embedding_value = dec.embedding_layer(caption_prev_words).squeeze(1).to(device)
alphas_for_each_pixel = dec.attention_net(enc_image, hidden_state)
gating_scalar = dec.layer_to_get_gating_scalar(hidden_state)
gating_scalar = dec.sigmoid_act(gating_scalar)
encoding_with_attention = gating_scalar * ((enc_image* alphas_for_each_pixel.unsqueeze(2)).sum(dim=1))
# alphas_for_each_pixel = alphas_for_each_pixel.view(-1, enc.encoder_image_size, enc.encoder_image_size)
alphas_for_each_pixel = alphas_for_each_pixel.view(-1, 16, 16)
hidden_state, cell_state = dec.lstm_cell(torch.cat([embedding_value,encoding_with_attention,],dim=1,),(hidden_state,cell_state))
scores = dec.layer_to_get_word_scores(hidden_state)
scores = F.log_softmax(scores,dim=1)
scores = top_caption_scores.expand(scores.shape) + scores
if time_step==0:
top_caption_scores, top_caption_words = scores[0].topk(k=beam_size, dim=0, largest=True, sorted=True)
else:
top_caption_scores, top_caption_words = scores.view(-1).topk(k=beam_size, dim=0, largest=True, sorted=True)
prev_word_inds = top_caption_words // one_hot_size
next_word_inds = top_caption_words % one_hot_size
captions = torch.cat([captions[prev_word_inds], next_word_inds.unsqueeze(1)], dim=1)
captions_alpha = torch.cat([captions_alpha[prev_word_inds], alphas_for_each_pixel[prev_word_inds].unsqueeze(1)], dim=1)
incomplete_inds = [ind for ind, next_word in enumerate(next_word_inds) if next_word != word2idx['<eos>']]
complete_inds = list(set(range(len(next_word_inds))) - set(incomplete_inds))
incomplete_inds, complete_inds = [],[]
for ind, next_word in enumerate(next_word_inds):
if next_word != word2idx['<eos>']:
incomplete_inds.append(ind)
else:
complete_inds.append(ind)
if len(complete_inds) > 0:
generated_captions.extend(captions[complete_inds].tolist())
generated_caption_scores.extend(top_caption_scores[complete_inds])
beam_size -= len(complete_inds)
captions = captions[incomplete_inds]
captions_alpha = captions_alpha[incomplete_inds]
hidden_state = hidden_state[prev_word_inds[incomplete_inds]]
cell_state = cell_state[prev_word_inds[incomplete_inds]]
enc_image = enc_image[prev_word_inds[incomplete_inds]]
top_caption_scores = top_caption_scores[incomplete_inds].unsqueeze(1)
caption_prev_words = next_word_inds[incomplete_inds].unsqueeze(1)
time_step += 1
golden_ind = generated_caption_scores.index(max(generated_caption_scores))
caption = generated_captions[golden_ind]
caption = " ".join([idx2word[token] for token in caption])
caption = caption.lstrip("<sos>").rstrip("<eos>")
return caption
if __name__=="__main__":
fraction = 1
lr = 4e-4 # Learning rate
dropout_probab = 0.5
dataset_path_suffix = f"dataset_{fraction}" if fraction!=1 else "dataset"
dataset_path = os.path.join(os.path.dirname(__file__), dataset_path_suffix)
with open(os.path.join(dataset_path, "index_to_word.json"), "r") as f:
idx2word = json.load(f)
idx2word = {int(k):v for k,v in idx2word.items()}
with open(os.path.join(dataset_path, "word_to_index_map.json"), "r") as f:
word2idx = json.load(f)
one_hot_size = len(word2idx)
save_dir = "model_files"
ckpt_filedir = os.path.join(os.path.dirname(__file__),save_dir)
ckpt_filename = f"best_model_{lr}LR_{dropout_probab}dropout_{dataset_path_suffix}.pth.tar"
ckpt_filepath = os.path.join(ckpt_filedir,ckpt_filename)
# ckpt_filepath = "model_files_backup/best_model_0.5dropout_dataset.pth.tar"
image_path = "sample3.jpg"
caption = inference_plain(im_path = image_path, saved_model_path = ckpt_filepath, save_caption_file = False)
print("Without beam search:", caption)
beam_size = 5
caption = inference_beam_search(im_path = image_path, saved_model_path = ckpt_filepath, beam_size = beam_size, save_caption_file = False)
print(f"With beam search (beam_size = {beam_size}):", caption)