code
stringlengths
17
6.64M
class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes) self.bn2 = nn.BatchNorm2d(planes) self.downsample = downsample self.stride = stride 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 is not None): residual = self.downsample(x) out += residual out = self.relu(out) return out
class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, stride=stride, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, (planes * 4), kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d((planes * 4)) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride 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) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if (self.downsample is not None): residual = self.downsample(x) out += residual out = self.relu(out) return out
class ResNet(nn.Module): def __init__(self, block, layers, num_classes=1000): self.inplanes = 64 super(ResNet, self).__init__() self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(64) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=0, ceil_mode=True) self.layer1 = self._make_layer(block, 64, layers[0]) self.layer2 = self._make_layer(block, 128, layers[1], stride=2) self.layer3 = self._make_layer(block, 256, layers[2], stride=2) self.layer4 = self._make_layer(block, 512, layers[3], stride=2) self.avgpool = nn.AvgPool2d(7) self.fc = nn.Linear((512 * block.expansion), num_classes) for m in self.modules(): if isinstance(m, nn.Conv2d): n = ((m.kernel_size[0] * m.kernel_size[1]) * m.out_channels) m.weight.data.normal_(0, math.sqrt((2.0 / n))) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def _make_layer(self, block, planes, blocks, stride=1): downsample = None if ((stride != 1) or (self.inplanes != (planes * block.expansion))): downsample = nn.Sequential(nn.Conv2d(self.inplanes, (planes * block.expansion), kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d((planes * block.expansion))) layers = [] layers.append(block(self.inplanes, planes, stride, downsample)) self.inplanes = (planes * block.expansion) for i in range(1, blocks): layers.append(block(self.inplanes, planes)) return nn.Sequential(*layers) def forward(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) x = self.avgpool(x) x = x.view(x.size(0), (- 1)) x = self.fc(x) return x
def resnet18(pretrained=False): 'Constructs a ResNet-18 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = ResNet(BasicBlock, [2, 2, 2, 2]) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet18'])) return model
def resnet34(pretrained=False): 'Constructs a ResNet-34 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = ResNet(BasicBlock, [3, 4, 6, 3]) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet34'])) return model
def resnet50(pretrained=False): 'Constructs a ResNet-50 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = ResNet(Bottleneck, [3, 4, 6, 3]) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet50'])) return model
def resnet101(pretrained=False): 'Constructs a ResNet-101 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = ResNet(Bottleneck, [3, 4, 23, 3]) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet101'])) return model
def resnet152(pretrained=False): 'Constructs a ResNet-152 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = ResNet(Bottleneck, [3, 8, 36, 3]) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet152'])) return model
class myResnet(nn.Module): def __init__(self, resnet): super(myResnet, self).__init__() self.resnet = resnet def forward(self, img, att_size=14): x = img.unsqueeze(0) x = self.resnet.conv1(x) x = self.resnet.bn1(x) x = self.resnet.relu(x) x = self.resnet.maxpool(x) x = self.resnet.layer1(x) x = self.resnet.layer2(x) x = self.resnet.layer3(x) x = self.resnet.layer4(x) fc = x.mean(3).mean(2).squeeze() att = F.adaptive_avg_pool2d(x, [att_size, att_size]).squeeze().permute(1, 2, 0) return (fc, att)
def init_scorer(cached_tokens): global CiderD_scorer CiderD_scorer = (CiderD_scorer or CiderD(df=cached_tokens))
def array_to_str(arr): out = '' for i in range(len(arr)): out += (str(arr[i]) + ' ') if (arr[i] == 0): break return out.strip()
def get_self_critical_reward(data, gen_result, greedy_res): batch_size = gen_result.size(0) seq_per_img = (batch_size // len(data['gts'])) res = OrderedDict() gen_result = gen_result.data.cpu().numpy() greedy_res = greedy_res.data.cpu().numpy() for i in range(batch_size): res[i] = [array_to_str(gen_result[i])] for i in range(batch_size): res[(batch_size + i)] = [array_to_str(greedy_res[i])] gts = OrderedDict() for i in range(len(data['gts'])): gts[i] = [array_to_str(data['gts'][i][j]) for j in range(len(data['gts'][i]))] res_ = [{'image_id': i, 'caption': res[i]} for i in range((2 * batch_size))] res__ = {i: res[i] for i in range((2 * batch_size))} gts = {i: gts[((i % batch_size) // seq_per_img)] for i in range((2 * batch_size))} (_, cider_scores) = CiderD_scorer.compute_score(gts, res_) print('Cider scores:', _) scores = cider_scores cider_greedy = scores[batch_size:].mean() scores = (scores[:batch_size] - scores[batch_size:]) return (scores, cider_greedy)
def setup(opt, model_name, caption=True): if caption: if (model_name == 'show_tell'): model = ShowTellModel(opt) elif (model_name == 'show_attend_tell'): model = ShowAttendTellModel(opt) elif (model_name == 'all_img'): model = AllImgModel(opt) elif (model_name == 'fc'): model = FCModel(opt) elif (model_name == 'fc2'): model = FC2Model(opt) elif (model_name == 'att2in'): model = Att2inModel(opt) elif (model_name == 'att2in2'): model = Att2in2Model(opt) elif (model_name == 'adaatt'): model = AdaAttModel(opt) elif (model_name == 'adaattmo'): model = AdaAttMOModel(opt) elif (model_name == 'topdown'): model = TopDownModel(opt) else: raise Exception('Caption model not supported: {}'.format(model_name)) elif (model_name == 'fc'): model = VSEFCModel(opt) elif (model_name == 'dual_att'): model = VSEAttModel(opt) else: raise Exception('VSE model not supported: {}'.format(model_name)) return model
def load(model, opt): if (vars(opt).get('start_from', None) is not None): assert os.path.isdir(opt.start_from), (' %s must be a a path' % opt.start_from) assert os.path.isfile(os.path.join(opt.start_from, (('infos_' + opt.id) + '.pkl'))), ('infos.pkl file does not exist in path %s' % opt.start_from) utils.load_state_dict(model, torch.load(os.path.join(opt.start_from, 'model.pth')))
def parse_opt(): parser = argparse.ArgumentParser() parser.add_argument('--input_json', type=str, default='data/coco.json', help='path to the json file containing additional info and vocab') parser.add_argument('--input_fc_dir', type=str, default='data/cocotalk_fc', help='path to the directory containing the preprocessed fc feats') parser.add_argument('--input_att_dir', type=str, default='data/cocotalk_att', help='path to the directory containing the preprocessed att feats') parser.add_argument('--input_label_h5', type=str, default='data/coco_label.h5', help='path to the h5file containing the preprocessed dataset') parser.add_argument('--start_from', type=str, default=None, help="continue training from saved model at this path. Path must contain files saved by previous training process: \n 'infos.pkl' : configuration;\n 'checkpoint' : paths to model file(s) (created by tf).\n Note: this file contains absolute paths, be careful when moving files around;\n 'model.ckpt-*' : file(s) with model definition (created by tf)\n ") parser.add_argument('--initialize_retrieval', type=str, default=None, help='xxxx.pth') parser.add_argument('--cached_tokens', type=str, default='coco-train-idxs', help='Cached token file for calculating cider score during self critical training.') parser.add_argument('--cider_optimization', type=int, default=0, help='optimize cider?') parser.add_argument('--caption_model', type=str, default='show_tell', help='show_tell, show_attend_tell, all_img, fc, att2in, att2in2, adaatt, adaattmo, topdown') parser.add_argument('--rnn_size', type=int, default=512, help='size of the rnn in number of hidden nodes in each layer') parser.add_argument('--num_layers', type=int, default=1, help='number of layers in the RNN') parser.add_argument('--rnn_type', type=str, default='lstm', help='rnn, gru, or lstm') parser.add_argument('--input_encoding_size', type=int, default=512, help='the encoding size of each token in the vocabulary, and the image.') parser.add_argument('--att_hid_size', type=int, default=512, help='the hidden size of the attention MLP; only useful in show_attend_tell; 0 if not using hidden layer') parser.add_argument('--fc_feat_size', type=int, default=2048, help='2048 for resnet, 4096 for vgg') parser.add_argument('--att_feat_size', type=int, default=2048, help='2048 for resnet, 512 for vgg') parser.add_argument('--use_bn', type=int, default=0, help='If 1, then do batch_normalization first in att_embed') parser.add_argument('--decoding_constraint', type=int, default=0, help='1 if not allowing decoding two same words in a row, 2 if not allowing any word appear twice in a caption') parser.add_argument('--max_epochs', type=int, default=(- 1), help='number of epochs') parser.add_argument('--batch_size', type=int, default=16, help='minibatch size') parser.add_argument('--grad_clip', type=float, default=0.1, help='clip gradients at this value') parser.add_argument('--drop_prob_lm', type=float, default=0.5, help='strength of dropout in the Language Model RNN') parser.add_argument('--seq_per_img', type=int, default=1, help='number of captions to sample for each image during training. Done for efficiency since CNN forward pass is expensive. E.g. coco has 5 sents/image') parser.add_argument('--beam_size', type=int, default=1, help='used when sample_max = 1, indicates number of beams in beam search. Usually 2 or 3 works well. More is not better. Set this to 1 for faster runtime but a bit worse performance.') parser.add_argument('--optim', type=str, default='adam', help='what update to use? rmsprop|sgd|sgdmom|adagrad|adam') parser.add_argument('--learning_rate', type=float, default=0.0004, help='learning rate') parser.add_argument('--learning_rate_decay_start', type=int, default=(- 1), help='at what iteration to start decaying learning rate? (-1 = dont) (in epoch)') parser.add_argument('--learning_rate_decay_every', type=int, default=3, help='every how many iterations thereafter to drop LR?(in epoch)') parser.add_argument('--learning_rate_decay_rate', type=float, default=0.8, help='every how many iterations thereafter to drop LR?(in epoch)') parser.add_argument('--optim_alpha', type=float, default=0.9, help='alpha for adam') parser.add_argument('--optim_beta', type=float, default=0.999, help='beta used for adam') parser.add_argument('--optim_epsilon', type=float, default=1e-08, help='epsilon that goes into denominator for smoothing') parser.add_argument('--weight_decay', type=float, default=0, help='weight_decay') parser.add_argument('--scheduled_sampling_start', type=int, default=(- 1), help='at what iteration to start decay gt probability') parser.add_argument('--scheduled_sampling_increase_every', type=int, default=5, help='every how many iterations thereafter to gt probability') parser.add_argument('--scheduled_sampling_increase_prob', type=float, default=0.05, help='How much to update the prob') parser.add_argument('--scheduled_sampling_max_prob', type=float, default=0.25, help='Maximum scheduled sampling prob.') parser.add_argument('--retrieval_reward_weight_decay_start', type=int, default=(- 1), help='at what iteration to start decaying learning rate? (-1 = dont) (in epoch)') parser.add_argument('--retrieval_reward_weight_decay_every', type=int, default=15, help='every how many iterations thereafter to drop LR?(in epoch)') parser.add_argument('--retrieval_reward_weight_decay_rate', type=float, default=0.8, help='every how many iterations thereafter to drop LR?(in epoch)') parser.add_argument('--gate_type', type=str, default='softmax', help='sigmoid or softmax.') parser.add_argument('--closest_num', type=int, default=10, help='sigmoid or softmax.') parser.add_argument('--closest_file', type=str, default='data/closest.pkl', help='Closest_file') parser.add_argument('--val_images_use', type=int, default=3200, help='how many images to use when periodically evaluating the validation loss? (-1 = all)') parser.add_argument('--save_checkpoint_every', type=int, default=2500, help='how often to save a model checkpoint (in iterations)?') parser.add_argument('--checkpoint_path', type=str, default='save', help='directory to store checkpointed models') parser.add_argument('--language_eval', type=int, default=0, help='Evaluate language as well (1 = yes, 0 = no)? BLEU/CIDEr/METEOR/ROUGE_L? requires coco-caption code from Github.') parser.add_argument('--rank_eval', type=int, default=0, help='Evaluate vse rank') parser.add_argument('--losses_log_every', type=int, default=25, help='How often do we snapshot losses, for inclusion in the progress dump? (0 = disable)') parser.add_argument('--load_best_score', type=int, default=1, help='Do we load previous best score when resuming training.') parser.add_argument('--id', type=str, default='', help='an id identifying this run/job. used in cross-val and appended when writing progress files') parser.add_argument('--train_only', type=int, default=0, help='if true then use 80k, else use 110k') parser.add_argument('--vse_model', type=str, default='None', help='fc, None') parser.add_argument('--vse_rnn_type', type=str, default='gru', help='rnn, gru, or lstm') parser.add_argument('--vse_margin', default=0.2, type=float, help='Rank loss margin; when margin is -1, it means use binary cross entropy (usually works with MLP).') parser.add_argument('--vse_embed_size', default=1024, type=int, help='Dimensionality of the joint embedding.') parser.add_argument('--vse_num_layers', default=1, type=int, help='Number of GRU layers.') parser.add_argument('--vse_max_violation', default=1, type=int, help='Use max instead of sum in the rank loss.') parser.add_argument('--vse_measure', default='cosine', help='Similarity measure used (cosine|order|MLP)') parser.add_argument('--vse_use_abs', default=0, type=int, help='Take the absolute value of embedding vectors.') parser.add_argument('--vse_no_imgnorm', default=0, type=int, help='Do not normalize the image embeddings.') parser.add_argument('--vse_loss_type', default='contrastive', type=str, help='contrastive or pair') parser.add_argument('--vse_pool_type', default='last', type=str, help='last, mean, max') parser.add_argument('--retrieval_reward', default='gumbel', type=str, help='gumbel, reinforce, prob') parser.add_argument('--retrieval_reward_weight', default=0, type=float, help='gumbel, reinforce') parser.add_argument('--only_one_retrieval', default='off', type=str, help='image, caption, only used when optimizing generator') parser.add_argument('--share_embed', default=0, type=int, help='Share embed') parser.add_argument('--share_fc', default=0, type=int, help='Share fc') parser.add_argument('--caption_loss_weight', default=1, type=float, help='Loss weight.') parser.add_argument('--vse_loss_weight', default=0, type=float, help='Loss weight.') parser.add_argument('--vse_eval_criterion', default='rsum', type=str, help='The criterion to decide which to take: rsum, t2i_ar, i2t_ar, ....') parser.add_argument('--reinforce_baseline_type', default='greedy', type=str, help='no, greedy, gt') args = parser.parse_args() assert (args.rnn_size > 0), 'rnn_size should be greater than 0' assert (args.num_layers > 0), 'num_layers should be greater than 0' assert (args.input_encoding_size > 0), 'input_encoding_size should be greater than 0' assert (args.batch_size > 0), 'batch_size should be greater than 0' assert ((args.drop_prob_lm >= 0) and (args.drop_prob_lm < 1)), 'drop_prob_lm should be between 0 and 1' assert (args.seq_per_img > 0), 'seq_per_img should be greater than 0' assert (args.beam_size > 0), 'beam_size should be greater than 0' assert (args.save_checkpoint_every > 0), 'save_checkpoint_every should be greater than 0' assert (args.losses_log_every > 0), 'losses_log_every should be greater than 0' assert ((args.language_eval == 0) or (args.language_eval == 1)), 'language_eval should be 0 or 1' assert ((args.load_best_score == 0) or (args.load_best_score == 1)), 'language_eval should be 0 or 1' assert ((args.train_only == 0) or (args.train_only == 1)), 'language_eval should be 0 or 1' return args
def build_vocab(imgs, params): count_thr = params['word_count_threshold'] counts = {} for img in imgs: for sent in img['sentences']: for w in sent['tokens']: counts[w] = (counts.get(w, 0) + 1) cw = sorted([(count, w) for (w, count) in counts.items()], reverse=True) print('top words and their counts:') print('\n'.join(map(str, cw[:20]))) total_words = sum(counts.values()) print('total words:', total_words) bad_words = [w for (w, n) in counts.items() if (n <= count_thr)] vocab = [w for (w, n) in counts.items() if (n > count_thr)] bad_count = sum((counts[w] for w in bad_words)) print(('number of bad words: %d/%d = %.2f%%' % (len(bad_words), len(counts), ((len(bad_words) * 100.0) / len(counts))))) print(('number of words in vocab would be %d' % (len(vocab),))) print(('number of UNKs: %d/%d = %.2f%%' % (bad_count, total_words, ((bad_count * 100.0) / total_words)))) sent_lengths = {} for img in imgs: for sent in img['sentences']: txt = sent['tokens'] nw = len(txt) sent_lengths[nw] = (sent_lengths.get(nw, 0) + 1) max_len = max(sent_lengths.keys()) print('max length sentence in raw data: ', max_len) print('sentence length distribution (count, number of words):') sum_len = sum(sent_lengths.values()) for i in range((max_len + 1)): print(('%2d: %10d %f%%' % (i, sent_lengths.get(i, 0), ((sent_lengths.get(i, 0) * 100.0) / sum_len)))) if (bad_count > 0): print('inserting the special UNK token') vocab.append('UNK') for img in imgs: img['final_captions'] = [] for sent in img['sentences']: txt = sent['tokens'] caption = [(w if (counts.get(w, 0) > count_thr) else 'UNK') for w in txt] img['final_captions'].append(caption) return vocab
def encode_captions(imgs, params, wtoi): ' \n encode all captions into one large array, which will be 1-indexed.\n also produces label_start_ix and label_end_ix which store 1-indexed \n and inclusive (Lua-style) pointers to the first and last caption for\n each image in the dataset.\n ' max_length = params['max_length'] N = len(imgs) M = sum((len(img['final_captions']) for img in imgs)) label_arrays = [] label_start_ix = np.zeros(N, dtype='uint32') label_end_ix = np.zeros(N, dtype='uint32') label_length = np.zeros(M, dtype='uint32') caption_counter = 0 counter = 1 for (i, img) in enumerate(imgs): n = len(img['final_captions']) assert (n > 0), 'error: some image has no captions' Li = np.zeros((n, max_length), dtype='uint32') for (j, s) in enumerate(img['final_captions']): label_length[caption_counter] = min(max_length, len(s)) caption_counter += 1 for (k, w) in enumerate(s): if (k < max_length): Li[(j, k)] = wtoi[w] label_arrays.append(Li) label_start_ix[i] = counter label_end_ix[i] = ((counter + n) - 1) counter += n L = np.concatenate(label_arrays, axis=0) assert (L.shape[0] == M), "lengths don't match? that's weird" assert np.all((label_length > 0)), 'error: some caption had no words?' print('encoded captions to array of size ', L.shape) return (L, label_start_ix, label_end_ix, label_length)
def main(params): imgs = json.load(open(params['input_json'], 'r')) imgs = imgs['images'] seed(123) vocab = build_vocab(imgs, params) itow = {(i + 1): w for (i, w) in enumerate(vocab)} wtoi = {w: (i + 1) for (i, w) in enumerate(vocab)} (L, label_start_ix, label_end_ix, label_length) = encode_captions(imgs, params, wtoi) N = len(imgs) f_lb = h5py.File((params['output_h5'] + '_label.h5'), 'w') f_lb.create_dataset('labels', dtype='uint32', data=L) f_lb.create_dataset('label_start_ix', dtype='uint32', data=label_start_ix) f_lb.create_dataset('label_end_ix', dtype='uint32', data=label_end_ix) f_lb.create_dataset('label_length', dtype='uint32', data=label_length) f_lb.close() out = {} out['ix_to_word'] = itow out['images'] = [] for (i, img) in enumerate(imgs): jimg = {} jimg['split'] = img['split'] if ('filename' in img): jimg['file_path'] = os.path.join(img['filepath'], img['filename']) if ('cocoid' in img): jimg['id'] = img['cocoid'] out['images'].append(jimg) json.dump(out, open(params['output_json'], 'w')) print('wrote ', params['output_json'])
def precook(s, n=4, out=False): '\n Takes a string as input and returns an object that can be given to\n either cook_refs or cook_test. This is optional: cook_refs and cook_test\n can take string arguments as well.\n :param s: string : sentence to be converted into ngrams\n :param n: int : number of ngrams for which representation is calculated\n :return: term frequency vector for occuring ngrams\n ' words = s.split() counts = defaultdict(int) for k in xrange(1, (n + 1)): for i in xrange(((len(words) - k) + 1)): ngram = tuple(words[i:(i + k)]) counts[ngram] += 1 return counts
def cook_refs(refs, n=4): 'Takes a list of reference sentences for a single segment\n and returns an object that encapsulates everything that BLEU\n needs to know about them.\n :param refs: list of string : reference sentences for some image\n :param n: int : number of ngrams for which (ngram) representation is calculated\n :return: result (list of dict)\n ' return [precook(ref, n) for ref in refs]
def create_crefs(refs): crefs = [] for ref in refs: crefs.append(cook_refs(ref)) return crefs
def compute_doc_freq(crefs): '\n Compute term frequency for reference data.\n This will be used to compute idf (inverse document frequency later)\n The term frequency is stored in the object\n :return: None\n ' document_frequency = defaultdict(float) for refs in crefs: for ngram in set([ngram for ref in refs for (ngram, count) in ref.iteritems()]): document_frequency[ngram] += 1 return document_frequency
def build_dict(imgs, wtoi, params): wtoi['<eos>'] = 0 count_imgs = 0 refs_words = [] refs_idxs = [] for img in imgs: if ((params['split'] == img['split']) or ((params['split'] == 'train') and (img['split'] == 'restval')) or (params['split'] == 'all')): ref_words = [] ref_idxs = [] for sent in img['sentences']: tmp_tokens = (sent['tokens'] + ['<eos>']) tmp_tokens = [(_ if (_ in wtoi) else 'UNK') for _ in tmp_tokens] ref_words.append(' '.join(tmp_tokens)) ref_idxs.append(' '.join([str(wtoi[_]) for _ in tmp_tokens])) refs_words.append(ref_words) refs_idxs.append(ref_idxs) count_imgs += 1 print('total imgs:', count_imgs) ngram_words = compute_doc_freq(create_crefs(refs_words)) ngram_idxs = compute_doc_freq(create_crefs(refs_idxs)) return (ngram_words, ngram_idxs, count_imgs)
def main(params): imgs = json.load(open(params['input_json'], 'r')) itow = json.load(open(params['dict_json'], 'r'))['ix_to_word'] wtoi = {w: i for (i, w) in itow.items()} imgs = imgs['images'] (ngram_words, ngram_idxs, ref_len) = build_dict(imgs, wtoi, params) cPickle.dump({'document_frequency': ngram_words, 'ref_len': ref_len}, open((params['output_pkl'] + '-words.p'), 'w'), protocol=cPickle.HIGHEST_PROTOCOL) cPickle.dump({'document_frequency': ngram_idxs, 'ref_len': ref_len}, open((params['output_pkl'] + '-idxs.p'), 'w'), protocol=cPickle.HIGHEST_PROTOCOL)
def train(opt): opt.use_att = utils.if_use_att(opt) loader = DataLoader(opt) opt.vocab_size = loader.vocab_size opt.seq_length = loader.seq_length tf_summary_writer = (tf and SummaryWriter(opt.checkpoint_path)) infos = {} histories = {} if (opt.start_from is not None): with open(os.path.join(opt.start_from, (('infos_' + opt.id) + '.pkl'))) as f: infos = cPickle.load(f) saved_model_opt = infos['opt'] need_be_same = ['caption_model', 'rnn_type', 'rnn_size', 'num_layers'] for checkme in need_be_same: assert (vars(saved_model_opt)[checkme] == vars(opt)[checkme]), ("Command line argument and saved model disagree on '%s' " % checkme) if os.path.isfile(os.path.join(opt.start_from, (('histories_' + opt.id) + '.pkl'))): with open(os.path.join(opt.start_from, (('histories_' + opt.id) + '.pkl'))) as f: histories = cPickle.load(f) iteration = infos.get('iter', 0) epoch = infos.get('epoch', 0) val_result_history = histories.get('val_result_history', {}) loss_history = histories.get('loss_history', {}) lr_history = histories.get('lr_history', {}) ss_prob_history = histories.get('ss_prob_history', {}) loader.iterators = infos.get('iterators', loader.iterators) loader.split_ix = infos.get('split_ix', loader.split_ix) if (opt.load_best_score == 1): best_val_score = infos.get('best_val_score', None) best_val_score_vse = infos.get('best_val_score_vse', None) model = models.JointModel(opt) model.cuda() update_lr_flag = True model.train() optimizer = optim.Adam([p for p in model.parameters() if p.requires_grad], lr=opt.learning_rate, weight_decay=opt.weight_decay) if ((vars(opt).get('start_from', None) is not None) and os.path.isfile(os.path.join(opt.start_from, 'optimizer.pth'))): state_dict = torch.load(os.path.join(opt.start_from, 'optimizer.pth')) if (len(state_dict['state']) == len(optimizer.state_dict()['state'])): optimizer.load_state_dict(state_dict) else: print('Optimizer param group number not matched? There must be new parameters. Reinit the optimizer.') init_scorer(opt.cached_tokens) while True: if update_lr_flag: if ((epoch > opt.learning_rate_decay_start) and (opt.learning_rate_decay_start >= 0)): frac = ((epoch - opt.learning_rate_decay_start) // opt.learning_rate_decay_every) decay_factor = (opt.learning_rate_decay_rate ** frac) opt.current_lr = (opt.learning_rate * decay_factor) utils.set_lr(optimizer, opt.current_lr) else: opt.current_lr = opt.learning_rate if ((epoch > opt.scheduled_sampling_start) and (opt.scheduled_sampling_start >= 0)): frac = ((epoch - opt.scheduled_sampling_start) // opt.scheduled_sampling_increase_every) opt.ss_prob = min((opt.scheduled_sampling_increase_prob * frac), opt.scheduled_sampling_max_prob) model.caption_generator.ss_prob = opt.ss_prob if ((epoch > opt.retrieval_reward_weight_decay_start) and (opt.retrieval_reward_weight_decay_start >= 0)): frac = ((epoch - opt.retrieval_reward_weight_decay_start) // opt.retrieval_reward_weight_decay_every) model.retrieval_reward_weight = (opt.retrieval_reward_weight * (opt.retrieval_reward_weight_decay_rate ** frac)) update_lr_flag = False start = time.time() data = loader.get_batch('train') print('Read data:', (time.time() - start)) torch.cuda.synchronize() start = time.time() tmp = [data['fc_feats'], data['att_feats'], data['att_masks'], data['labels'], data['masks']] tmp = utils.var_wrapper(tmp) (fc_feats, att_feats, att_masks, labels, masks) = tmp optimizer.zero_grad() loss = model(fc_feats, att_feats, att_masks, labels, masks, data) loss.backward() utils.clip_gradient(optimizer, opt.grad_clip) optimizer.step() train_loss = loss.item() torch.cuda.synchronize() end = time.time() print('iter {} (epoch {}), train_loss = {:.3f}, time/batch = {:.3f}'.format(iteration, epoch, train_loss, (end - start))) prt_str = '' for (k, v) in model.loss().items(): prt_str += '{} = {:.3f} '.format(k, v) print(prt_str) iteration += 1 if data['bounds']['wrapped']: epoch += 1 update_lr_flag = True if ((iteration % opt.losses_log_every) == 0): if (tf is not None): tf_summary_writer.add_scalar('train_loss', train_loss, iteration) for (k, v) in model.loss().items(): tf_summary_writer.add_scalar(k, v, iteration) tf_summary_writer.add_scalar('learning_rate', opt.current_lr, iteration) tf_summary_writer.add_scalar('scheduled_sampling_prob', model.caption_generator.ss_prob, iteration) tf_summary_writer.add_scalar('retrieval_reward_weight', model.retrieval_reward_weight, iteration) tf_summary_writer.file_writer.flush() loss_history[iteration] = train_loss lr_history[iteration] = opt.current_lr ss_prob_history[iteration] = model.caption_generator.ss_prob if ((iteration % opt.save_checkpoint_every) == 0): eval_kwargs = {'split': 'val', 'dataset': opt.input_json} eval_kwargs.update(vars(opt)) (val_loss, predictions, lang_stats) = eval_utils.eval_split(model, loader, eval_kwargs) if (tf is not None): for (k, v) in val_loss.items(): tf_summary_writer.add_scalar(('validation ' + k), v, iteration) for (k, v) in lang_stats.items(): tf_summary_writer.add_scalar(k, v, iteration) tf_summary_writer.add_text('Captions', '.\n\n'.join([_['caption'] for _ in predictions[:100]]), iteration) tf_summary_writer.file_writer.flush() val_result_history[iteration] = {'loss': val_loss, 'lang_stats': lang_stats, 'predictions': predictions} if (opt.language_eval == 1): current_score = (lang_stats['SPICE'] * 100) else: current_score = (- val_loss['loss_cap']) current_score_vse = (val_loss.get(opt.vse_eval_criterion, 0) * 100) best_flag = False best_flag_vse = False if True: if ((best_val_score is None) or (current_score > best_val_score)): best_val_score = current_score best_flag = True if ((best_val_score_vse is None) or (current_score_vse > best_val_score_vse)): best_val_score_vse = current_score_vse best_flag_vse = True checkpoint_path = os.path.join(opt.checkpoint_path, 'model.pth') torch.save(model.state_dict(), checkpoint_path) print('model saved to {}'.format(checkpoint_path)) checkpoint_path = os.path.join(opt.checkpoint_path, ('model-%d.pth' % iteration)) torch.save(model.state_dict(), checkpoint_path) print('model saved to {}'.format(checkpoint_path)) optimizer_path = os.path.join(opt.checkpoint_path, 'optimizer.pth') torch.save(optimizer.state_dict(), optimizer_path) infos['iter'] = iteration infos['epoch'] = epoch infos['iterators'] = loader.iterators infos['split_ix'] = loader.split_ix infos['best_val_score'] = best_val_score infos['best_val_score_vse'] = best_val_score_vse infos['opt'] = opt infos['vocab'] = loader.get_vocab() histories['val_result_history'] = val_result_history histories['loss_history'] = loss_history histories['lr_history'] = lr_history histories['ss_prob_history'] = ss_prob_history with open(os.path.join(opt.checkpoint_path, (('infos_' + opt.id) + '.pkl')), 'wb') as f: cPickle.dump(infos, f) with open(os.path.join(opt.checkpoint_path, (('infos_' + opt.id) + ('-%d.pkl' % iteration))), 'wb') as f: cPickle.dump(infos, f) with open(os.path.join(opt.checkpoint_path, (('histories_' + opt.id) + '.pkl')), 'wb') as f: cPickle.dump(histories, f) if best_flag: checkpoint_path = os.path.join(opt.checkpoint_path, 'model-best.pth') torch.save(model.state_dict(), checkpoint_path) print('model saved to {}'.format(checkpoint_path)) with open(os.path.join(opt.checkpoint_path, (('infos_' + opt.id) + '-best.pkl')), 'wb') as f: cPickle.dump(infos, f) if best_flag_vse: checkpoint_path = os.path.join(opt.checkpoint_path, 'model_vse-best.pth') torch.save(model.state_dict(), checkpoint_path) print('model saved to {}'.format(checkpoint_path)) with open(os.path.join(opt.checkpoint_path, (('infos_vse_' + opt.id) + '-best.pkl')), 'wb') as f: cPickle.dump(infos, f) if ((epoch >= opt.max_epochs) and (opt.max_epochs != (- 1))): break
def find_ngrams(input_list, n): return zip(*[input_list[i:] for i in range(n)])
def compute_div_n(caps, n=1): aggr_div = [] for k in caps: all_ngrams = set() lenT = 0.0 for c in caps[k]: tkns = c.split() lenT += len(tkns) ng = find_ngrams(tkns, n) all_ngrams.update(ng) aggr_div.append((float(len(all_ngrams)) / (1e-06 + float(lenT)))) return (np.array(aggr_div).mean(), np.array(aggr_div))
def compute_global_div_n(caps, n=1): aggr_div = [] all_ngrams = set() lenT = 0.0 for k in caps: for c in caps[k]: tkns = c.split() lenT += len(tkns) ng = find_ngrams(tkns, n) all_ngrams.update(ng) if (n == 1): aggr_div.append(float(len(all_ngrams))) else: aggr_div.append((float(len(all_ngrams)) / (1e-06 + float(lenT)))) return (aggr_div[0], np.repeat(np.array(aggr_div), len(caps)))
class ResNet(torchvision.models.resnet.ResNet): def __init__(self, block, layers, num_classes=1000): super(ResNet, self).__init__(block, layers, num_classes) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=0, ceil_mode=True) for i in range(2, 5): getattr(self, ('layer%d' % i))[0].conv1.stride = (2, 2) getattr(self, ('layer%d' % i))[0].conv2.stride = (1, 1)
def resnet18(pretrained=False): 'Constructs a ResNet-18 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = ResNet(BasicBlock, [2, 2, 2, 2]) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet18'])) return model
def resnet34(pretrained=False): 'Constructs a ResNet-34 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = ResNet(BasicBlock, [3, 4, 6, 3]) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet34'])) return model
def resnet50(pretrained=False): 'Constructs a ResNet-50 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = ResNet(Bottleneck, [3, 4, 6, 3]) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet50'])) return model
def resnet101(pretrained=False): 'Constructs a ResNet-101 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = ResNet(Bottleneck, [3, 4, 23, 3]) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet101'])) return model
def resnet152(pretrained=False): 'Constructs a ResNet-152 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = ResNet(Bottleneck, [3, 8, 36, 3]) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet152'])) return model
class myResnet(nn.Module): def __init__(self, resnet): super(myResnet, self).__init__() self.resnet = resnet def forward(self, img, att_size=14): x = img.unsqueeze(0) x = self.resnet.conv1(x) x = self.resnet.bn1(x) x = self.resnet.relu(x) x = self.resnet.maxpool(x) x = self.resnet.layer1(x) x = self.resnet.layer2(x) x = self.resnet.layer3(x) x = self.resnet.layer4(x) fc = x.mean(3).mean(2).squeeze() att = F.adaptive_avg_pool2d(x, [att_size, att_size]).squeeze().permute(1, 2, 0) return (fc, att)
def setup(opt): if (opt.caption_model == 'fc'): model = FCModel(opt) elif (opt.caption_model == 'language_model'): model = LMModel(opt) elif (opt.caption_model == 'newfc'): model = NewFCModel(opt) elif (opt.caption_model == 'show_tell'): model = ShowTellModel(opt) elif (opt.caption_model == 'att2in'): model = Att2inModel(opt) elif (opt.caption_model == 'att2in2'): model = Att2in2Model(opt) elif (opt.caption_model == 'att2all2'): model = Att2all2Model(opt) elif (opt.caption_model == 'adaatt'): model = AdaAttModel(opt) elif (opt.caption_model == 'adaattmo'): model = AdaAttMOModel(opt) elif (opt.caption_model == 'topdown'): model = TopDownModel(opt) elif (opt.caption_model == 'stackatt'): model = StackAttModel(opt) elif (opt.caption_model == 'denseatt'): model = DenseAttModel(opt) elif (opt.caption_model == 'transformer'): model = TransformerModel(opt) else: raise Exception('Caption model not supported: {}'.format(opt.caption_model)) if (vars(opt).get('start_from', None) is not None): assert os.path.isdir(opt.start_from), (' %s must be a a path' % opt.start_from) assert os.path.isfile(os.path.join(opt.start_from, (('infos_' + opt.id) + '.pkl'))), ('infos.pkl file does not exist in path %s' % opt.start_from) model.load_state_dict(torch.load(os.path.join(opt.start_from, 'model.pth'))) return model
def parse_opt(): parser = argparse.ArgumentParser() parser.add_argument('--input_json', type=str, default='data/coco.json', help='path to the json file containing additional info and vocab') parser.add_argument('--input_fc_dir', type=str, default='data/cocotalk_fc', help='path to the directory containing the preprocessed fc feats') parser.add_argument('--input_att_dir', type=str, default='data/cocotalk_att', help='path to the directory containing the preprocessed att feats') parser.add_argument('--input_box_dir', type=str, default='data/cocotalk_box', help='path to the directory containing the boxes of att feats') parser.add_argument('--input_label_h5', type=str, default='data/coco_label.h5', help='path to the h5file containing the preprocessed dataset') parser.add_argument('--start_from', type=str, default=None, help="continue training from saved model at this path. Path must contain files saved by previous training process: \n 'infos.pkl' : configuration;\n 'checkpoint' : paths to model file(s) (created by tf).\n Note: this file contains absolute paths, be careful when moving files around;\n 'model.ckpt-*' : file(s) with model definition (created by tf)\n ") parser.add_argument('--cached_tokens', type=str, default='google-train-idxs', help='Cached token file for calculating cider score during self critical training.') parser.add_argument('--caption_model', type=str, default='show_tell', help='show_tell, show_attend_tell, all_img, fc, att2in, att2in2, att2all2, adaatt, adaattmo, topdown, stackatt, denseatt, transformer') parser.add_argument('--rnn_size', type=int, default=512, help='size of the rnn in number of hidden nodes in each layer') parser.add_argument('--num_layers', type=int, default=1, help='number of layers in the RNN') parser.add_argument('--rnn_type', type=str, default='lstm', help='rnn, gru, or lstm') parser.add_argument('--input_encoding_size', type=int, default=512, help='the encoding size of each token in the vocabulary, and the image.') parser.add_argument('--att_hid_size', type=int, default=512, help='the hidden size of the attention MLP; only useful in show_attend_tell; 0 if not using hidden layer') parser.add_argument('--fc_feat_size', type=int, default=2048, help='2048 for resnet, 4096 for vgg') parser.add_argument('--att_feat_size', type=int, default=2048, help='2048 for resnet, 512 for vgg') parser.add_argument('--logit_layers', type=int, default=1, help='number of layers in the RNN') parser.add_argument('--use_bn', type=int, default=0, help='If 1, then do batch_normalization first in att_embed, if 2 then do bn both in the beginning and the end of att_embed') parser.add_argument('--norm_att_feat', type=int, default=0, help='If normalize attention features') parser.add_argument('--use_box', type=int, default=0, help='If use box features') parser.add_argument('--norm_box_feat', type=int, default=0, help='If use box, do we normalize box feature') parser.add_argument('--max_epochs', type=int, default=(- 1), help='number of epochs') parser.add_argument('--batch_size', type=int, default=16, help='minibatch size') parser.add_argument('--grad_clip', type=float, default=0.1, help='clip gradients at this value') parser.add_argument('--drop_prob_lm', type=float, default=0.5, help='strength of dropout in the Language Model RNN') parser.add_argument('--self_critical_after', type=int, default=(- 1), help='After what epoch do we start finetuning the CNN? (-1 = disable; never finetune, 0 = finetune from start)') parser.add_argument('--seq_per_img', type=int, default=5, help='number of captions to sample for each image during training. Done for efficiency since CNN forward pass is expensive. E.g. coco has 5 sents/image') parser.add_argument('--beam_size', type=int, default=1, help='used when sample_max = 1, indicates number of beams in beam search. Usually 2 or 3 works well. More is not better. Set this to 1 for faster runtime but a bit worse performance.') parser.add_argument('--max_length', type=int, default=20, help='Maximum length during sampling') parser.add_argument('--length_penalty', type=str, default='', help='wu_X or avg_X, X is the alpha') parser.add_argument('--block_trigrams', type=int, default=0, help='block repeated trigram.') parser.add_argument('--remove_bad_endings', type=int, default=0, help='Remove bad endings') parser.add_argument('--optim', type=str, default='adam', help='what update to use? rmsprop|sgd|sgdmom|adagrad|adam') parser.add_argument('--learning_rate', type=float, default=0.0004, help='learning rate') parser.add_argument('--learning_rate_decay_start', type=int, default=(- 1), help='at what iteration to start decaying learning rate? (-1 = dont) (in epoch)') parser.add_argument('--learning_rate_decay_every', type=int, default=3, help='every how many iterations thereafter to drop LR?(in epoch)') parser.add_argument('--learning_rate_decay_rate', type=float, default=0.8, help='every how many iterations thereafter to drop LR?(in epoch)') parser.add_argument('--optim_alpha', type=float, default=0.9, help='alpha for adam') parser.add_argument('--optim_beta', type=float, default=0.999, help='beta used for adam') parser.add_argument('--optim_epsilon', type=float, default=1e-08, help='epsilon that goes into denominator for smoothing') parser.add_argument('--weight_decay', type=float, default=0, help='weight_decay') parser.add_argument('--label_smoothing', type=float, default=0, help='') parser.add_argument('--noamopt', action='store_true', help='') parser.add_argument('--noamopt_warmup', type=int, default=2000, help='') parser.add_argument('--noamopt_factor', type=float, default=1, help='') parser.add_argument('--reduce_on_plateau', action='store_true', help='') parser.add_argument('--scheduled_sampling_start', type=int, default=(- 1), help='at what iteration to start decay gt probability') parser.add_argument('--scheduled_sampling_increase_every', type=int, default=5, help='every how many iterations thereafter to gt probability') parser.add_argument('--scheduled_sampling_increase_prob', type=float, default=0.05, help='How much to update the prob') parser.add_argument('--scheduled_sampling_max_prob', type=float, default=0.25, help='Maximum scheduled sampling prob.') parser.add_argument('--val_images_use', type=int, default=3200, help='how many images to use when periodically evaluating the validation loss? (-1 = all)') parser.add_argument('--save_checkpoint_every', type=int, default=2500, help='how often to save a model checkpoint (in iterations)?') parser.add_argument('--save_history_ckpt', type=int, default=1, help='If save checkpoints at every save point') parser.add_argument('--checkpoint_path', type=str, default='save', help='directory to store checkpointed models') parser.add_argument('--language_eval', type=int, default=0, help='Evaluate language as well (1 = yes, 0 = no)? BLEU/CIDEr/METEOR/ROUGE_L? requires coco-caption code from Github.') parser.add_argument('--losses_log_every', type=int, default=25, help='How often do we snapshot losses, for inclusion in the progress dump? (0 = disable)') parser.add_argument('--load_best_score', type=int, default=1, help='Do we load previous best score when resuming training.') parser.add_argument('--id', type=str, default='', help='an id identifying this run/job. used in cross-val and appended when writing progress files') parser.add_argument('--train_only', type=int, default=0, help='if true then use 80k, else use 110k') parser.add_argument('--cider_reward_weight', type=float, default=1, help='The reward weight from cider') parser.add_argument('--bleu_reward_weight', type=float, default=0, help='The reward weight from bleu4') parser.add_argument('--structure_loss_weight', type=float, default=1, help='The reward weight from cider') parser.add_argument('--structure_after', type=float, default=(- 1), help='The reward weight from cider') parser.add_argument('--structure_sample_n', type=float, default=16, help='The reward weight from cider') parser.add_argument('--structure_loss_type', type=str, default='seqnll', help='The reward weight from cider') parser.add_argument('--struc_use_logsoftmax', action='store_true', help='') parser.add_argument('--entropy_reward_weight', type=float, default=0, help='Entropy reward, seems very interesting') parser.add_argument('--drop_worst_after', type=float, default=(- 1), help='') parser.add_argument('--drop_worst_rate', type=float, default=0, help='') add_vse_options(parser) args = parser.parse_args() assert (args.rnn_size > 0), 'rnn_size should be greater than 0' assert (args.num_layers > 0), 'num_layers should be greater than 0' assert (args.input_encoding_size > 0), 'input_encoding_size should be greater than 0' assert (args.batch_size > 0), 'batch_size should be greater than 0' assert ((args.drop_prob_lm >= 0) and (args.drop_prob_lm < 1)), 'drop_prob_lm should be between 0 and 1' assert (args.seq_per_img > 0), 'seq_per_img should be greater than 0' assert (args.beam_size > 0), 'beam_size should be greater than 0' assert (args.save_checkpoint_every > 0), 'save_checkpoint_every should be greater than 0' assert (args.losses_log_every > 0), 'losses_log_every should be greater than 0' assert ((args.language_eval == 0) or (args.language_eval == 1)), 'language_eval should be 0 or 1' assert ((args.load_best_score == 0) or (args.load_best_score == 1)), 'language_eval should be 0 or 1' assert ((args.train_only == 0) or (args.train_only == 1)), 'language_eval should be 0 or 1' return args
def add_vse_options(parser): parser.add_argument('--initialize_retrieval', type=str, default=None, help='xxxx.pth') parser.add_argument('--vse_model', type=str, default='None', help='fc, None') parser.add_argument('--vse_rnn_type', type=str, default='gru', help='rnn, gru, or lstm') parser.add_argument('--vse_margin', default=0.2, type=float, help='Rank loss margin; when margin is -1, it means use binary cross entropy (usually works with MLP).') parser.add_argument('--vse_word_dim', default=300, type=int, help='Dimensionality of the word embedding.') parser.add_argument('--vse_embed_size', default=1024, type=int, help='Dimensionality of the joint embedding.') parser.add_argument('--vse_num_layers', default=1, type=int, help='Number of GRU layers.') parser.add_argument('--vse_max_violation', default=1, type=int, help='Use max instead of sum in the rank loss.') parser.add_argument('--vse_measure', default='cosine', help='Similarity measure used (cosine|order|MLP)') parser.add_argument('--vse_use_abs', default=0, type=int, help='Take the absolute value of embedding vectors.') parser.add_argument('--vse_no_imgnorm', default=0, type=int, help='Do not normalize the image embeddings.') parser.add_argument('--vse_loss_type', default='contrastive', type=str, help='contrastive or pair') parser.add_argument('--vse_pool_type', default='last', type=str, help='last, mean, max') parser.add_argument('--retrieval_reward_weight', default=0, type=float, help='gumbel, reinforce')
def add_eval_options(parser): parser.add_argument('--batch_size', type=int, default=0, help='if > 0 then overrule, otherwise load from checkpoint.') parser.add_argument('--num_images', type=int, default=(- 1), help='how many images to use when periodically evaluating the loss? (-1 = all)') parser.add_argument('--language_eval', type=int, default=0, help='Evaluate language as well (1 = yes, 0 = no)? BLEU/CIDEr/METEOR/ROUGE_L? requires coco-caption code from Github.') parser.add_argument('--dump_images', type=int, default=1, help='Dump images into vis/imgs folder for vis? (1=yes,0=no)') parser.add_argument('--dump_json', type=int, default=1, help='Dump json with predictions into vis folder? (1=yes,0=no)') parser.add_argument('--dump_path', type=int, default=0, help='Write image paths along with predictions into vis json? (1=yes,0=no)') parser.add_argument('--sample_max', type=int, default=1, help='1 = sample argmax words. 0 = sample from distributions. 2 = gumbel softmax sample. negative means topk sampling') parser.add_argument('--beam_size', type=int, default=2, help='used when sample_max = 1, indicates number of beams in beam search. Usually 2 or 3 works well. More is not better. Set this to 1 for faster runtime but a bit worse performance.') parser.add_argument('--max_length', type=int, default=20, help='Maximum length during sampling') parser.add_argument('--length_penalty', type=str, default='', help='wu_X or avg_X, X is the alpha') parser.add_argument('--group_size', type=int, default=1, help="used for diverse beam search. if group_size is 1, then it's normal beam search") parser.add_argument('--diversity_lambda', type=float, default=0.5, help='used for diverse beam search. Usually from 0.2 to 0.8. Higher value of lambda produces a more diverse list') parser.add_argument('--temperature', type=float, default=1.0, help='temperature when sampling from distributions (i.e. when sample_max = 0). Lower = "safer" predictions.') parser.add_argument('--decoding_constraint', type=int, default=0, help='If 1, not allowing same word in a row') parser.add_argument('--block_trigrams', type=int, default=0, help='block repeated trigram.') parser.add_argument('--remove_bad_endings', type=int, default=0, help='Remove bad endings') parser.add_argument('--image_folder', type=str, default='', help='If this is nonempty then will predict on the images in this folder path') parser.add_argument('--image_root', type=str, default='', help='In case the image paths have to be preprended with a root path to an image folder') parser.add_argument('--input_fc_dir', type=str, default='', help='path to the h5file containing the preprocessed dataset') parser.add_argument('--input_att_dir', type=str, default='', help='path to the h5file containing the preprocessed dataset') parser.add_argument('--input_box_dir', type=str, default='', help='path to the h5file containing the preprocessed dataset') parser.add_argument('--input_label_h5', type=str, default='', help='path to the h5file containing the preprocessed dataset') parser.add_argument('--input_json', type=str, default='', help='path to the json file containing additional info and vocab. empty = fetch from model checkpoint.') parser.add_argument('--split', type=str, default='test', help='if running on MSCOCO images, which split to use: val|test|train') parser.add_argument('--coco_json', type=str, default='', help='if nonempty then use this file in DataLoaderRaw (see docs there). Used only in MSCOCO test evaluation, where we have a specific json file of only test set images.') parser.add_argument('--id', type=str, default='', help='an id identifying this run/job. used only if language_eval = 1 for appending to intermediate files') parser.add_argument('--verbose_beam', type=int, default=1, help='if we need to print out all beam search beams.') parser.add_argument('--verbose_loss', type=int, default=0, help='If calculate loss using ground truth during evaluation') parser.add_argument('--post_processing', type=int, default=0, help='nasty post processing')
def add_diversity_opts(parser): parser.add_argument('--sample_n', type=int, default=1, help='Diverse sampling') parser.add_argument('--sample_n_method', type=str, default='sample', help='sample, bs, dbs, gumbel, topk') parser.add_argument('--eval_oracle', type=int, default=1, help='if we need to calculate loss.')
def build_vocab(imgs, params): count_thr = params['word_count_threshold'] counts = {} for img in imgs: for sent in img['sentences']: for w in sent['tokens']: counts[w] = (counts.get(w, 0) + 1) cw = sorted([(count, w) for (w, count) in counts.items()], reverse=True) print('top words and their counts:') print('\n'.join(map(str, cw[:20]))) total_words = sum(counts.values()) print('total words:', total_words) bad_words = [w for (w, n) in counts.items() if (n <= count_thr)] vocab = [w for (w, n) in counts.items() if (n > count_thr)] bad_count = sum((counts[w] for w in bad_words)) print(('number of bad words: %d/%d = %.2f%%' % (len(bad_words), len(counts), ((len(bad_words) * 100.0) / len(counts))))) print(('number of words in vocab would be %d' % (len(vocab),))) print(('number of UNKs: %d/%d = %.2f%%' % (bad_count, total_words, ((bad_count * 100.0) / total_words)))) sent_lengths = {} for img in imgs: for sent in img['sentences']: txt = sent['tokens'] nw = len(txt) sent_lengths[nw] = (sent_lengths.get(nw, 0) + 1) max_len = max(sent_lengths.keys()) print('max length sentence in raw data: ', max_len) print('sentence length distribution (count, number of words):') sum_len = sum(sent_lengths.values()) for i in range((max_len + 1)): print(('%2d: %10d %f%%' % (i, sent_lengths.get(i, 0), ((sent_lengths.get(i, 0) * 100.0) / sum_len)))) if (bad_count > 0): print('inserting the special UNK token') vocab.append('UNK') for img in imgs: img['final_captions'] = [] for sent in img['sentences']: txt = sent['tokens'] caption = [(w if (counts.get(w, 0) > count_thr) else 'UNK') for w in txt] img['final_captions'].append(caption) return vocab
def encode_captions(imgs, params, wtoi): ' \n encode all captions into one large array, which will be 1-indexed.\n also produces label_start_ix and label_end_ix which store 1-indexed \n and inclusive (Lua-style) pointers to the first and last caption for\n each image in the dataset.\n ' max_length = params['max_length'] N = len(imgs) M = sum((len(img['final_captions']) for img in imgs)) label_arrays = [] label_start_ix = np.zeros(N, dtype='uint32') label_end_ix = np.zeros(N, dtype='uint32') label_length = np.zeros(M, dtype='uint32') caption_counter = 0 counter = 1 for (i, img) in enumerate(imgs): n = len(img['final_captions']) assert (n > 0), 'error: some image has no captions' Li = np.zeros((n, max_length), dtype='uint32') for (j, s) in enumerate(img['final_captions']): label_length[caption_counter] = min(max_length, len(s)) caption_counter += 1 for (k, w) in enumerate(s): if (k < max_length): Li[(j, k)] = wtoi[w] label_arrays.append(Li) label_start_ix[i] = counter label_end_ix[i] = ((counter + n) - 1) counter += n L = np.concatenate(label_arrays, axis=0) assert (L.shape[0] == M), "lengths don't match? that's weird" assert np.all((label_length > 0)), 'error: some caption had no words?' print('encoded captions to array of size ', L.shape) return (L, label_start_ix, label_end_ix, label_length)
def main(params): imgs = json.load(open(params['input_json'], 'r')) imgs = imgs['images'] seed(123) vocab = build_vocab(imgs, params) itow = {(i + 1): w for (i, w) in enumerate(vocab)} wtoi = {w: (i + 1) for (i, w) in enumerate(vocab)} (L, label_start_ix, label_end_ix, label_length) = encode_captions(imgs, params, wtoi) N = len(imgs) f_lb = h5py.File((params['output_h5'] + '_label.h5'), 'w') f_lb.create_dataset('labels', dtype='uint32', data=L) f_lb.create_dataset('label_start_ix', dtype='uint32', data=label_start_ix) f_lb.create_dataset('label_end_ix', dtype='uint32', data=label_end_ix) f_lb.create_dataset('label_length', dtype='uint32', data=label_length) f_lb.close() out = {} out['ix_to_word'] = itow out['images'] = [] for (i, img) in enumerate(imgs): jimg = {} jimg['split'] = img['split'] if ('filename' in img): jimg['file_path'] = os.path.join(img['filepath'], img['filename']) if ('cocoid' in img): jimg['id'] = img['cocoid'] if (params['images_root'] != ''): with Image.open(os.path.join(params['images_root'], img['filepath'], img['filename'])) as _img: (jimg['width'], jimg['height']) = _img.size out['images'].append(jimg) json.dump(out, open(params['output_json'], 'w')) print('wrote ', params['output_json'])
def precook(s, n=4, out=False): '\n Takes a string as input and returns an object that can be given to\n either cook_refs or cook_test. This is optional: cook_refs and cook_test\n can take string arguments as well.\n :param s: string : sentence to be converted into ngrams\n :param n: int : number of ngrams for which representation is calculated\n :return: term frequency vector for occuring ngrams\n ' words = s.split() counts = defaultdict(int) for k in xrange(1, (n + 1)): for i in xrange(((len(words) - k) + 1)): ngram = tuple(words[i:(i + k)]) counts[ngram] += 1 return counts
def cook_refs(refs, n=4): 'Takes a list of reference sentences for a single segment\n and returns an object that encapsulates everything that BLEU\n needs to know about them.\n :param refs: list of string : reference sentences for some image\n :param n: int : number of ngrams for which (ngram) representation is calculated\n :return: result (list of dict)\n ' return [precook(ref, n) for ref in refs]
def create_crefs(refs): crefs = [] for ref in refs: crefs.append(cook_refs(ref)) return crefs
def compute_doc_freq(crefs): '\n Compute term frequency for reference data.\n This will be used to compute idf (inverse document frequency later)\n The term frequency is stored in the object\n :return: None\n ' document_frequency = defaultdict(float) for refs in crefs: for ngram in set([ngram for ref in refs for (ngram, count) in ref.iteritems()]): document_frequency[ngram] += 1 return document_frequency
def build_dict(imgs, wtoi, params): wtoi['<eos>'] = 0 count_imgs = 0 refs_words = [] refs_idxs = [] for img in imgs: if ((params['split'] == img['split']) or ((params['split'] == 'train') and (img['split'] == 'restval')) or (params['split'] == 'all')): ref_words = [] ref_idxs = [] for sent in img['sentences']: tmp_tokens = (sent['tokens'] + ['<eos>']) tmp_tokens = [(_ if (_ in wtoi) else 'UNK') for _ in tmp_tokens] ref_words.append(' '.join(tmp_tokens)) ref_idxs.append(' '.join([str(wtoi[_]) for _ in tmp_tokens])) refs_words.append(ref_words) refs_idxs.append(ref_idxs) count_imgs += 1 print('total imgs:', count_imgs) ngram_words = compute_doc_freq(create_crefs(refs_words)) ngram_idxs = compute_doc_freq(create_crefs(refs_idxs)) return (ngram_words, ngram_idxs, count_imgs)
def main(params): imgs = json.load(open(params['input_json'], 'r')) itow = json.load(open(params['dict_json'], 'r'))['ix_to_word'] wtoi = {w: i for (i, w) in itow.items()} imgs = imgs['images'] (ngram_words, ngram_idxs, ref_len) = build_dict(imgs, wtoi, params) utils.pickle_dump({'document_frequency': ngram_words, 'ref_len': ref_len}, open((params['output_pkl'] + '-words.p'), 'w')) utils.pickle_dump({'document_frequency': ngram_idxs, 'ref_len': ref_len}, open((params['output_pkl'] + '-idxs.p'), 'w'))
class MultiHeadedDotAttention(nn.Module): def __init__(self, h, d_model, dropout=0.1, scale=1, project_k_v=1, use_output_layer=1, do_aoa=0, norm_q=0, dropout_aoa=0.3): super(MultiHeadedDotAttention, self).__init__() assert (((d_model * scale) % h) == 0) self.d_k = ((d_model * scale) // h) self.h = h self.project_k_v = project_k_v if norm_q: self.norm = LayerNorm(d_model) else: self.norm = (lambda x: x) self.linears = clones(nn.Linear(d_model, (d_model * scale)), (1 + (2 * project_k_v))) self.output_layer = nn.Linear((d_model * scale), d_model) self.use_aoa = do_aoa if self.use_aoa: self.aoa_layer = nn.Sequential(nn.Linear(((1 + scale) * d_model), (2 * d_model)), nn.GLU()) if (dropout_aoa > 0): self.dropout_aoa = nn.Dropout(p=dropout_aoa) else: self.dropout_aoa = (lambda x: x) if (self.use_aoa or (not use_output_layer)): del self.output_layer self.output_layer = (lambda x: x) self.attn = None self.dropout = nn.Dropout(p=dropout) def forward(self, query, value, key, mask=None): if (mask is not None): if (len(mask.size()) == 2): mask = mask.unsqueeze((- 2)) mask = mask.unsqueeze(1) single_query = 0 if (len(query.size()) == 2): single_query = 1 query = query.unsqueeze(1) nbatches = query.size(0) query = self.norm(query) if (self.project_k_v == 0): query_ = self.linears[0](query).view(nbatches, (- 1), self.h, self.d_k).transpose(1, 2) key_ = key.view(nbatches, (- 1), self.h, self.d_k).transpose(1, 2) value_ = value.view(nbatches, (- 1), self.h, self.d_k).transpose(1, 2) else: (query_, key_, value_) = [l(x).view(nbatches, (- 1), self.h, self.d_k).transpose(1, 2) for (l, x) in zip(self.linears, (query, key, value))] (x, self.attn) = attention(query_, key_, value_, mask=mask, dropout=self.dropout) x = x.transpose(1, 2).contiguous().view(nbatches, (- 1), (self.h * self.d_k)) if self.use_aoa: x = self.aoa_layer(self.dropout_aoa(torch.cat([x, query], (- 1)))) x = self.output_layer(x) if single_query: query = query.squeeze(1) x = x.squeeze(1) return x
class AoA_Refiner_Layer(nn.Module): def __init__(self, size, self_attn, feed_forward, dropout): super(AoA_Refiner_Layer, self).__init__() self.self_attn = self_attn self.feed_forward = feed_forward self.use_ff = 0 if (self.feed_forward is not None): self.use_ff = 1 self.sublayer = clones(SublayerConnection(size, dropout), (1 + self.use_ff)) self.size = size def forward(self, x, mask): x = self.sublayer[0](x, (lambda x: self.self_attn(x, x, x, mask))) return (self.sublayer[(- 1)](x, self.feed_forward) if self.use_ff else x)
class AoA_Refiner_Core(nn.Module): def __init__(self, opt): super(AoA_Refiner_Core, self).__init__() attn = MultiHeadedDotAttention(opt.num_heads, opt.rnn_size, project_k_v=1, scale=opt.multi_head_scale, do_aoa=opt.refine_aoa, norm_q=0, dropout_aoa=getattr(opt, 'dropout_aoa', 0.3)) layer = AoA_Refiner_Layer(opt.rnn_size, attn, (PositionwiseFeedForward(opt.rnn_size, 2048, 0.1) if opt.use_ff else None), 0.1) self.layers = clones(layer, 6) self.norm = LayerNorm(layer.size) def forward(self, x, mask): for layer in self.layers: x = layer(x, mask) return self.norm(x)
class AoA_Decoder_Core(nn.Module): def __init__(self, opt): super(AoA_Decoder_Core, self).__init__() self.drop_prob_lm = opt.drop_prob_lm self.d_model = opt.rnn_size self.use_multi_head = opt.use_multi_head self.multi_head_scale = opt.multi_head_scale self.use_ctx_drop = getattr(opt, 'ctx_drop', 0) self.out_res = getattr(opt, 'out_res', 0) self.decoder_type = getattr(opt, 'decoder_type', 'AoA') self.att_lstm = nn.LSTMCell((opt.input_encoding_size + opt.rnn_size), opt.rnn_size) self.out_drop = nn.Dropout(self.drop_prob_lm) if (self.decoder_type == 'AoA'): self.att2ctx = nn.Sequential(nn.Linear(((self.d_model * opt.multi_head_scale) + opt.rnn_size), (2 * opt.rnn_size)), nn.GLU()) elif (self.decoder_type == 'LSTM'): self.att2ctx = nn.LSTMCell(((self.d_model * opt.multi_head_scale) + opt.rnn_size), opt.rnn_size) else: self.att2ctx = nn.Sequential(nn.Linear(((self.d_model * opt.multi_head_scale) + opt.rnn_size), opt.rnn_size), nn.ReLU()) if (opt.use_multi_head == 2): self.attention = MultiHeadedDotAttention(opt.num_heads, opt.rnn_size, project_k_v=0, scale=opt.multi_head_scale, use_output_layer=0, do_aoa=0, norm_q=1) else: self.attention = Attention(opt) if self.use_ctx_drop: self.ctx_drop = nn.Dropout(self.drop_prob_lm) else: self.ctx_drop = (lambda x: x) def forward(self, xt, mean_feats, att_feats, p_att_feats, state, att_masks=None): (h_att, c_att) = self.att_lstm(torch.cat([xt, (mean_feats + self.ctx_drop(state[0][1]))], 1), (state[0][0], state[1][0])) if (self.use_multi_head == 2): att = self.attention(h_att, p_att_feats.narrow(2, 0, (self.multi_head_scale * self.d_model)), p_att_feats.narrow(2, (self.multi_head_scale * self.d_model), (self.multi_head_scale * self.d_model)), att_masks) else: att = self.attention(h_att, att_feats, p_att_feats, att_masks) ctx_input = torch.cat([att, h_att], 1) if (self.decoder_type == 'LSTM'): (output, c_logic) = self.att2ctx(ctx_input, (state[0][1], state[1][1])) state = (torch.stack((h_att, output)), torch.stack((c_att, c_logic))) else: output = self.att2ctx(ctx_input) state = (torch.stack((h_att, output)), torch.stack((c_att, state[1][1]))) if self.out_res: output = (output + h_att) output = self.out_drop(output) return (output, state)
class AoAModel(AttModel): def __init__(self, opt): super(AoAModel, self).__init__(opt) self.num_layers = 2 self.use_mean_feats = getattr(opt, 'mean_feats', 1) if (opt.use_multi_head == 2): del self.ctx2att self.ctx2att = nn.Linear(opt.rnn_size, ((2 * opt.multi_head_scale) * opt.rnn_size)) if self.use_mean_feats: del self.fc_embed if opt.refine: self.refiner = AoA_Refiner_Core(opt) else: self.refiner = (lambda x, y: x) self.core = AoA_Decoder_Core(opt) def _prepare_feature(self, fc_feats, att_feats, att_masks): (att_feats, att_masks) = self.clip_att(att_feats, att_masks) att_feats = pack_wrapper(self.att_embed, att_feats, att_masks) att_feats = self.refiner(att_feats, att_masks) if self.use_mean_feats: if (att_masks is None): mean_feats = torch.mean(att_feats, dim=1) else: mean_feats = (torch.sum((att_feats * att_masks.unsqueeze((- 1))), 1) / torch.sum(att_masks.unsqueeze((- 1)), 1)) else: mean_feats = self.fc_embed(fc_feats) p_att_feats = self.ctx2att(att_feats) return (mean_feats, att_feats, p_att_feats, att_masks)
def setup(opt): if (opt.caption_model in ['fc', 'show_tell']): print(('Warning: %s model is mostly deprecated; many new features are not supported.' % opt.caption_model)) if (opt.caption_model == 'fc'): print('Use newfc instead of fc') if (opt.caption_model == 'fc'): model = FCModel(opt) elif (opt.caption_model == 'language_model'): model = LMModel(opt) elif (opt.caption_model == 'newfc'): model = NewFCModel(opt) elif (opt.caption_model == 'show_tell'): model = ShowTellModel(opt) elif (opt.caption_model == 'att2in'): model = Att2inModel(opt) elif (opt.caption_model == 'att2in2'): model = Att2in2Model(opt) elif (opt.caption_model == 'att2all2'): print('Warning: this is not a correct implementation of the att2all model in the original paper.') model = Att2all2Model(opt) elif (opt.caption_model == 'adaatt'): model = AdaAttModel(opt) elif (opt.caption_model == 'adaattmo'): model = AdaAttMOModel(opt) elif (opt.caption_model in ['topdown', 'updown']): model = UpDownModel(opt) elif (opt.caption_model == 'stackatt'): model = StackAttModel(opt) elif (opt.caption_model == 'denseatt'): model = DenseAttModel(opt) elif (opt.caption_model == 'transformer'): if getattr(opt, 'cached_transformer', False): model = cachedTransformer(opt) else: model = TransformerModel(opt) elif (opt.caption_model == 'aoa'): model = AoAModel(opt) elif (opt.caption_model == 'bert'): model = BertCapModel(opt) elif (opt.caption_model == 'm2transformer'): model = M2TransformerModel(opt) else: raise Exception('Caption model not supported: {}'.format(opt.caption_model)) return model
def repeat_tensors(n, x): '\n For a tensor of size Bx..., we repeat it n times, and make it Bnx...\n For collections, do nested repeat\n ' if torch.is_tensor(x): x = x.unsqueeze(1) x = x.expand((- 1), n, *([(- 1)] * len(x.shape[2:]))) x = x.reshape((x.shape[0] * n), *x.shape[2:]) elif ((type(x) is list) or (type(x) is tuple)): x = [repeat_tensors(n, _) for _ in x] return x
def split_tensors(n, x): if torch.is_tensor(x): assert ((x.shape[0] % n) == 0) x = x.reshape((x.shape[0] // n), n, *x.shape[1:]).unbind(1) elif ((type(x) is list) or (type(x) is tuple)): x = [split_tensors(n, _) for _ in x] elif (x is None): x = ([None] * n) return x
class CfgNode(_CfgNode): '\n Our own extended version of :class:`yacs.config.CfgNode`.\n It contains the following extra features:\n\n 1. The :meth:`merge_from_file` method supports the "_BASE_" key,\n which allows the new CfgNode to inherit all the attributes from the\n base configuration file.\n 2. Keys that start with "COMPUTED_" are treated as insertion-only\n "computed" attributes. They can be inserted regardless of whether\n the CfgNode is frozen or not.\n 3. With "allow_unsafe=True", it supports pyyaml tags that evaluate\n expressions in config. See examples in\n https://pyyaml.org/wiki/PyYAMLDocumentation#yaml-tags-and-python-types\n Note that this may lead to arbitrary code execution: you must not\n load a config file from untrusted sources before manually inspecting\n the content of the file.\n ' @staticmethod def load_yaml_with_base(filename, allow_unsafe=False): '\n Just like `yaml.load(open(filename))`, but inherit attributes from its\n `_BASE_`.\n\n Args:\n filename (str): the file name of the current config. Will be used to\n find the base config file.\n allow_unsafe (bool): whether to allow loading the config file with\n `yaml.unsafe_load`.\n\n Returns:\n (dict): the loaded yaml\n ' with PathManager.open(filename, 'r') as f: try: cfg = yaml.safe_load(f) except yaml.constructor.ConstructorError: if (not allow_unsafe): raise logger = logging.getLogger(__name__) logger.warning('Loading config {} with yaml.unsafe_load. Your machine may be at risk if the file contains malicious content.'.format(filename)) f.close() with open(filename, 'r') as f: cfg = yaml.unsafe_load(f) def merge_a_into_b(a, b): for (k, v) in a.items(): if (isinstance(v, dict) and (k in b)): assert isinstance(b[k], dict), "Cannot inherit key '{}' from base!".format(k) merge_a_into_b(v, b[k]) else: b[k] = v if (BASE_KEY in cfg): base_cfg_file = cfg[BASE_KEY] if base_cfg_file.startswith('~'): base_cfg_file = os.path.expanduser(base_cfg_file) if (not any(map(base_cfg_file.startswith, ['/', 'https://', 'http://']))): base_cfg_file = os.path.join(os.path.dirname(filename), base_cfg_file) base_cfg = CfgNode.load_yaml_with_base(base_cfg_file, allow_unsafe=allow_unsafe) del cfg[BASE_KEY] merge_a_into_b(cfg, base_cfg) return base_cfg return cfg def merge_from_file(self, cfg_filename, allow_unsafe=False): '\n Merge configs from a given yaml file.\n\n Args:\n cfg_filename: the file name of the yaml config.\n allow_unsafe: whether to allow loading the config file with\n `yaml.unsafe_load`.\n ' loaded_cfg = CfgNode.load_yaml_with_base(cfg_filename, allow_unsafe=allow_unsafe) loaded_cfg = type(self)(loaded_cfg) self.merge_from_other_cfg(loaded_cfg) def merge_from_other_cfg(self, cfg_other): '\n Args:\n cfg_other (CfgNode): configs to merge from.\n ' assert (BASE_KEY not in cfg_other), "The reserved key '{}' can only be used in files!".format(BASE_KEY) return super().merge_from_other_cfg(cfg_other) def merge_from_list(self, cfg_list): '\n Args:\n cfg_list (list): list of configs to merge from.\n ' keys = set(cfg_list[0::2]) assert (BASE_KEY not in keys), "The reserved key '{}' can only be used in files!".format(BASE_KEY) return super().merge_from_list(cfg_list) def __setattr__(self, name, val): if name.startswith('COMPUTED_'): if (name in self): old_val = self[name] if (old_val == val): return raise KeyError("Computed attributed '{}' already exists with a different value! old={}, new={}.".format(name, old_val, val)) self[name] = val else: super().__setattr__(name, val)
def find_ngrams(input_list, n): return zip(*[input_list[i:] for i in range(n)])
def compute_div_n(caps, n=1): aggr_div = [] for k in caps: all_ngrams = set() lenT = 0.0 for c in caps[k]: tkns = c.split() lenT += len(tkns) ng = find_ngrams(tkns, n) all_ngrams.update(ng) aggr_div.append((float(len(all_ngrams)) / (1e-06 + float(lenT)))) return (np.array(aggr_div).mean(), np.array(aggr_div))
def compute_global_div_n(caps, n=1): aggr_div = [] all_ngrams = set() lenT = 0.0 for k in caps: for c in caps[k]: tkns = c.split() lenT += len(tkns) ng = find_ngrams(tkns, n) all_ngrams.update(ng) if (n == 1): aggr_div.append(float(len(all_ngrams))) else: aggr_div.append((float(len(all_ngrams)) / (1e-06 + float(lenT)))) return (aggr_div[0], np.repeat(np.array(aggr_div), len(caps)))
def pickle_load(f): ' Load a pickle.\n Parameters\n ----------\n f: file-like object\n ' if six.PY3: return cPickle.load(f, encoding='latin-1') else: return cPickle.load(f)
def pickle_dump(obj, f): ' Dump a pickle.\n Parameters\n ----------\n obj: pickled object\n f: file-like object\n ' if six.PY3: return cPickle.dump(obj, f, protocol=2) else: return cPickle.dump(obj, f)
def serialize_to_tensor(data): device = torch.device('cpu') buffer = cPickle.dumps(data) storage = torch.ByteStorage.from_buffer(buffer) tensor = torch.ByteTensor(storage).to(device=device) return tensor
def deserialize(tensor): buffer = tensor.cpu().numpy().tobytes() return cPickle.loads(buffer)
def decode_sequence(ix_to_word, seq): (N, D) = seq.size() out = [] for i in range(N): txt = '' for j in range(D): ix = seq[(i, j)] if (ix > 0): if (j >= 1): txt = (txt + ' ') txt = (txt + ix_to_word[str(ix.item())]) else: break if int(os.getenv('REMOVE_BAD_ENDINGS', '0')): flag = 0 words = txt.split(' ') for j in range(len(words)): if (words[((- j) - 1)] not in bad_endings): flag = (- j) break txt = ' '.join(words[0:(len(words) + flag)]) out.append(txt.replace('@@ ', '')) return out
def save_checkpoint(opt, model, infos, optimizer, histories=None, append=''): if (len(append) > 0): append = ('-' + append) if (not os.path.isdir(opt.checkpoint_path)): os.makedirs(opt.checkpoint_path) checkpoint_path = os.path.join(opt.checkpoint_path, ('model%s.pth' % append)) torch.save(model.state_dict(), checkpoint_path) print('model saved to {}'.format(checkpoint_path)) optimizer_path = os.path.join(opt.checkpoint_path, ('optimizer%s.pth' % append)) torch.save(optimizer.state_dict(), optimizer_path) with open(os.path.join(opt.checkpoint_path, (('infos_' + opt.id) + ('%s.pkl' % append))), 'wb') as f: pickle_dump(infos, f) if histories: with open(os.path.join(opt.checkpoint_path, (('histories_' + opt.id) + ('%s.pkl' % append))), 'wb') as f: pickle_dump(histories, f)
def set_lr(optimizer, lr): for group in optimizer.param_groups: group['lr'] = lr
def get_lr(optimizer): for group in optimizer.param_groups: return group['lr']
def build_optimizer(params, opt): if (opt.optim == 'rmsprop'): return optim.RMSprop(params, opt.learning_rate, opt.optim_alpha, opt.optim_epsilon, weight_decay=opt.weight_decay) elif (opt.optim == 'adagrad'): return optim.Adagrad(params, opt.learning_rate, weight_decay=opt.weight_decay) elif (opt.optim == 'sgd'): return optim.SGD(params, opt.learning_rate, weight_decay=opt.weight_decay) elif (opt.optim == 'sgdm'): return optim.SGD(params, opt.learning_rate, opt.optim_alpha, weight_decay=opt.weight_decay) elif (opt.optim == 'sgdmom'): return optim.SGD(params, opt.learning_rate, opt.optim_alpha, weight_decay=opt.weight_decay, nesterov=True) elif (opt.optim == 'adam'): return optim.Adam(params, opt.learning_rate, (opt.optim_alpha, opt.optim_beta), opt.optim_epsilon, weight_decay=opt.weight_decay) elif (opt.optim == 'adamw'): return optim.AdamW(params, opt.learning_rate, (opt.optim_alpha, opt.optim_beta), opt.optim_epsilon, weight_decay=opt.weight_decay) else: raise Exception('bad option opt.optim: {}'.format(opt.optim))
def penalty_builder(penalty_config): if (penalty_config == ''): return (lambda x, y: y) (pen_type, alpha) = penalty_config.split('_') alpha = float(alpha) if (pen_type == 'wu'): return (lambda x, y: length_wu(x, y, alpha)) if (pen_type == 'avg'): return (lambda x, y: length_average(x, y, alpha))
def length_wu(length, logprobs, alpha=0.0): '\n NMT length re-ranking score from\n "Google\'s Neural Machine Translation System" :cite:`wu2016google`.\n ' modifier = (((5 + length) ** alpha) / ((5 + 1) ** alpha)) return (logprobs / modifier)
def length_average(length, logprobs, alpha=0.0): '\n Returns the average probability of tokens in a sequence.\n ' return (logprobs / length)
class NoamOpt(torch.optim.Optimizer): 'Optim wrapper that implements rate.' def __init__(self, model_size, factor, warmup, optimizer): self.optimizer = optimizer self._step = 0 self.warmup = warmup self.factor = factor self.model_size = model_size self._rate = 0 def step(self, *args, **kwargs): 'Update parameters and rate' self._step += 1 rate = self.rate() for p in self.optimizer.param_groups: p['lr'] = rate self._rate = rate self.optimizer.step(*args, **kwargs) def rate(self, step=None): 'Implement `lrate` above' if (step is None): step = self._step return (self.factor * ((self.model_size ** (- 0.5)) * min((step ** (- 0.5)), (step * (self.warmup ** (- 1.5)))))) def __getattr__(self, name): return getattr(self.optimizer, name) def state_dict(self): state_dict = self.optimizer.state_dict() state_dict['_step'] = self._step return state_dict def load_state_dict(self, state_dict): if ('_step' in state_dict): self._step = state_dict['_step'] del state_dict['_step'] self.optimizer.load_state_dict(state_dict)
class ReduceLROnPlateau(torch.optim.Optimizer): 'Optim wrapper that implements rate.' def __init__(self, optimizer, mode='min', factor=0.1, patience=10, threshold=0.0001, threshold_mode='rel', cooldown=0, min_lr=0, eps=1e-08, verbose=False): self.scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode, factor, patience, threshold, threshold_mode, cooldown, min_lr, eps, verbose) self.optimizer = optimizer self.current_lr = get_lr(optimizer) def step(self, *args, **kwargs): 'Update parameters and rate' self.optimizer.step(*args, **kwargs) def scheduler_step(self, val): self.scheduler.step(val) self.current_lr = get_lr(self.optimizer) def state_dict(self): return {'current_lr': self.current_lr, 'scheduler_state_dict': self.scheduler.state_dict(), 'optimizer_state_dict': self.optimizer.state_dict()} def load_state_dict(self, state_dict): if ('current_lr' not in state_dict): self.optimizer.load_state_dict(state_dict) set_lr(self.optimizer, self.current_lr) else: self.current_lr = state_dict['current_lr'] self.scheduler.load_state_dict(state_dict['scheduler_state_dict']) self.optimizer.load_state_dict(state_dict['optimizer_state_dict']) def rate(self, step=None): 'Implement `lrate` above' if (step is None): step = self._step return (self.factor * ((self.model_size ** (- 0.5)) * min((step ** (- 0.5)), (step * (self.warmup ** (- 1.5)))))) def __getattr__(self, name): return getattr(self.optimizer, name)
def get_std_opt(model, optim_func='adam', factor=1, warmup=2000): optim_func = dict(adam=torch.optim.Adam, adamw=torch.optim.AdamW)[optim_func] return NoamOpt(model.d_model, factor, warmup, optim_func(model.parameters(), lr=0, betas=(0.9, 0.98), eps=1e-09))
def if_use_feat(caption_model): if (caption_model in ['show_tell', 'all_img', 'fc', 'newfc']): (use_att, use_fc) = (False, True) elif (caption_model == 'language_model'): (use_att, use_fc) = (False, False) elif (caption_model in ['updown', 'topdown']): (use_fc, use_att) = (True, True) else: (use_att, use_fc) = (True, False) return (use_fc, use_att)
def parse_opt(): parser = argparse.ArgumentParser() parser.add_argument('--input_json', type=str, default='data/coco.json', help='path to the json file containing additional info and vocab') parser.add_argument('--input_fc_dir', type=str, default='data/cocotalk_fc', help='path to the directory containing the preprocessed fc feats') parser.add_argument('--input_att_dir', type=str, default='data/cocotalk_att', help='path to the directory containing the preprocessed att feats') parser.add_argument('--input_box_dir', type=str, default='data/cocotalk_box', help='path to the directory containing the boxes of att feats') parser.add_argument('--input_label_h5', type=str, default='data/coco_label.h5', help='path to the h5file containing the preprocessed dataset') parser.add_argument('--data_in_memory', action='store_true', help='True if we want to save the features in memory') parser.add_argument('--start_from', type=str, default=None, help="continue training from saved model at this path. Path must contain files saved by previous training process: \n 'infos.pkl' : configuration;\n 'model.pth' : weights\n ") parser.add_argument('--cached_tokens', type=str, default='coco-train-idxs', help='Cached token file for calculating cider score during self critical training.') parser.add_argument('--caption_model', type=str, default='show_tell', help='show_tell, show_attend_tell, all_img, fc, att2in, att2in2, att2all2, adaatt, adaattmo, updown, stackatt, denseatt, transformer') parser.add_argument('--rnn_size', type=int, default=512, help='size of the rnn in number of hidden nodes in each layer') parser.add_argument('--num_layers', type=int, default=1, help='number of layers in the RNN') parser.add_argument('--rnn_type', type=str, default='lstm', help='rnn, gru, or lstm') parser.add_argument('--input_encoding_size', type=int, default=512, help='the encoding size of each token in the vocabulary, and the image.') parser.add_argument('--att_hid_size', type=int, default=512, help='the hidden size of the attention MLP; only useful in show_attend_tell; 0 if not using hidden layer') parser.add_argument('--fc_feat_size', type=int, default=2048, help='2048 for resnet, 4096 for vgg') parser.add_argument('--att_feat_size', type=int, default=2048, help='2048 for resnet, 512 for vgg') parser.add_argument('--logit_layers', type=int, default=1, help='number of layers in the RNN') parser.add_argument('--use_bn', type=int, default=0, help='If 1, then do batch_normalization first in att_embed, if 2 then do bn both in the beginning and the end of att_embed') parser.add_argument('--norm_att_feat', type=int, default=0, help='If normalize attention features') parser.add_argument('--use_box', type=int, default=0, help='If use box features') parser.add_argument('--norm_box_feat', type=int, default=0, help='If use box, do we normalize box feature') parser.add_argument('--max_epochs', type=int, default=(- 1), help='number of epochs') parser.add_argument('--batch_size', type=int, default=16, help='minibatch size') parser.add_argument('--grad_clip_mode', type=str, default='value', help='value or norm') parser.add_argument('--grad_clip_value', type=float, default=0.1, help='clip gradients at this value/max_norm, 0 means no clipping') parser.add_argument('--drop_prob_lm', type=float, default=0.5, help='strength of dropout in the Language Model RNN') parser.add_argument('--self_critical_after', type=int, default=(- 1), help='After what epoch do we start finetuning the CNN? (-1 = disable; never finetune, 0 = finetune from start)') parser.add_argument('--seq_per_img', type=int, default=5, help='number of captions to sample for each image during training. Done for efficiency since CNN forward pass is expensive. E.g. coco has 5 sents/image') add_eval_sample_opts(parser) parser.add_argument('--optim', type=str, default='adam', help='what update to use? rmsprop|sgd|sgdmom|adagrad|adam|adamw') parser.add_argument('--learning_rate', type=float, default=0.0004, help='learning rate') parser.add_argument('--learning_rate_decay_start', type=int, default=(- 1), help='at what iteration to start decaying learning rate? (-1 = dont) (in epoch)') parser.add_argument('--learning_rate_decay_every', type=int, default=3, help='every how many iterations thereafter to drop LR?(in epoch)') parser.add_argument('--learning_rate_decay_rate', type=float, default=0.8, help='every how many iterations thereafter to drop LR?(in epoch)') parser.add_argument('--optim_alpha', type=float, default=0.9, help='alpha for adam') parser.add_argument('--optim_beta', type=float, default=0.999, help='beta used for adam') parser.add_argument('--optim_epsilon', type=float, default=1e-08, help='epsilon that goes into denominator for smoothing') parser.add_argument('--weight_decay', type=float, default=0, help='weight_decay') parser.add_argument('--label_smoothing', type=float, default=0, help='') parser.add_argument('--noamopt', action='store_true', help='') parser.add_argument('--noamopt_warmup', type=int, default=2000, help='') parser.add_argument('--noamopt_factor', type=float, default=1, help='') parser.add_argument('--reduce_on_plateau', action='store_true', help='') parser.add_argument('--reduce_on_plateau_factor', type=float, default=0.5, help='') parser.add_argument('--reduce_on_plateau_patience', type=int, default=3, help='') parser.add_argument('--cached_transformer', action='store_true', help='') parser.add_argument('--use_warmup', action='store_true', help='warm up the learing rate?') parser.add_argument('--scheduled_sampling_start', type=int, default=(- 1), help='at what iteration to start decay gt probability') parser.add_argument('--scheduled_sampling_increase_every', type=int, default=5, help='every how many iterations thereafter to gt probability') parser.add_argument('--scheduled_sampling_increase_prob', type=float, default=0.05, help='How much to update the prob') parser.add_argument('--scheduled_sampling_max_prob', type=float, default=0.25, help='Maximum scheduled sampling prob.') parser.add_argument('--val_images_use', type=int, default=3200, help='how many images to use when periodically evaluating the validation loss? (-1 = all)') parser.add_argument('--save_checkpoint_every', type=int, default=2500, help='how often to save a model checkpoint (in iterations)?') parser.add_argument('--save_every_epoch', action='store_true', help='Save checkpoint every epoch, will overwrite save_checkpoint_every') parser.add_argument('--save_history_ckpt', type=int, default=0, help='If save checkpoints at every save point') parser.add_argument('--checkpoint_path', type=str, default=None, help='directory to store checkpointed models') parser.add_argument('--language_eval', type=int, default=0, help='Evaluate language as well (1 = yes, 0 = no)? BLEU/CIDEr/METEOR/ROUGE_L? requires coco-caption code from Github.') parser.add_argument('--losses_log_every', type=int, default=25, help='How often do we snapshot losses, for inclusion in the progress dump? (0 = disable)') parser.add_argument('--load_best_score', type=int, default=1, help='Do we load previous best score when resuming training.') parser.add_argument('--id', type=str, default='', help='an id identifying this run/job. used in cross-val and appended when writing progress files') parser.add_argument('--train_only', type=int, default=0, help='if true then use 80k, else use 110k') parser.add_argument('--cider_reward_weight', type=float, default=1, help='The reward weight from cider') parser.add_argument('--bleu_reward_weight', type=float, default=0, help='The reward weight from bleu4') parser.add_argument('--structure_loss_weight', type=float, default=1, help='') parser.add_argument('--structure_after', type=int, default=(- 1), help='') parser.add_argument('--structure_loss_type', type=str, default='seqnll', help='') parser.add_argument('--struc_use_logsoftmax', action='store_true', help='') parser.add_argument('--entropy_reward_weight', type=float, default=0, help='Entropy reward, seems very interesting') parser.add_argument('--self_cider_reward_weight', type=float, default=0, help='self cider reward') parser.add_argument('--use_ppo', type=int, default=0, help='if use ppo. when using ppo, we reuse things like structure_loss_weight and structure_after.') parser.add_argument('--ppo_old_model_path', type=str, default=None, help='The old model used to calculate PPO loss.') parser.add_argument('--ppo_cliprange', type=float, default=0.2, help='cliprange for PPO. 0.2 is used by InstructGPT') parser.add_argument('--ppo_kl_coef', type=float, default=0.02, help='kl reward cooef for PPO. 0.02 is used by InstructGPT') parser.add_argument('--train_sample_n', type=int, default=16, help='The reward weight from cider') parser.add_argument('--train_sample_method', type=str, default='sample', help='') parser.add_argument('--train_beam_size', type=int, default=1, help='') parser.add_argument('--sc_sample_method', type=str, default='greedy', help='') parser.add_argument('--sc_beam_size', type=int, default=1, help='') parser.add_argument('--drop_worst_after', type=float, default=(- 1), help='') parser.add_argument('--drop_worst_rate', type=float, default=0, help='') add_diversity_opts(parser) parser.add_argument('--cfg', type=str, default=None, help='configuration; similar to what is used in detectron') parser.add_argument('--set_cfgs', dest='set_cfgs', help='Set config keys. Key value sequence seperate by whitespace.e.g. [key] [value] [key] [value]\n This has higher prioritythan cfg file but lower than other args. (You can only overwritearguments that have alerady been defined in config file.)', default=[], nargs='+') args = parser.parse_args() if ((args.cfg is not None) or (args.set_cfgs is not None)): from .config import CfgNode if (args.cfg is not None): cn = CfgNode(CfgNode.load_yaml_with_base(args.cfg)) else: cn = CfgNode() if (args.set_cfgs is not None): cn.merge_from_list(args.set_cfgs) for (k, v) in cn.items(): if (not hasattr(args, k)): print(('Warning: key %s not in args' % k)) setattr(args, k, v) args = parser.parse_args(namespace=args) assert (args.rnn_size > 0), 'rnn_size should be greater than 0' assert (args.num_layers > 0), 'num_layers should be greater than 0' assert (args.input_encoding_size > 0), 'input_encoding_size should be greater than 0' assert (args.batch_size > 0), 'batch_size should be greater than 0' assert ((args.drop_prob_lm >= 0) and (args.drop_prob_lm < 1)), 'drop_prob_lm should be between 0 and 1' assert (args.seq_per_img > 0), 'seq_per_img should be greater than 0' assert (args.beam_size > 0), 'beam_size should be greater than 0' assert (args.save_checkpoint_every > 0), 'save_checkpoint_every should be greater than 0' assert (args.losses_log_every > 0), 'losses_log_every should be greater than 0' assert ((args.language_eval == 0) or (args.language_eval == 1)), 'language_eval should be 0 or 1' assert ((args.load_best_score == 0) or (args.load_best_score == 1)), 'language_eval should be 0 or 1' assert ((args.train_only == 0) or (args.train_only == 1)), 'language_eval should be 0 or 1' args.checkpoint_path = (args.checkpoint_path or ('./log_%s' % args.id)) args.start_from = (args.start_from or args.checkpoint_path) (args.use_fc, args.use_att) = if_use_feat(args.caption_model) if args.use_box: args.att_feat_size = (args.att_feat_size + 5) return args
def add_eval_options(parser): parser.add_argument('--batch_size', type=int, default=0, help='if > 0 then overrule, otherwise load from checkpoint.') parser.add_argument('--num_images', type=int, default=(- 1), help='how many images to use when periodically evaluating the loss? (-1 = all)') parser.add_argument('--language_eval', type=int, default=0, help='Evaluate language as well (1 = yes, 0 = no)? BLEU/CIDEr/METEOR/ROUGE_L? requires coco-caption code from Github.') parser.add_argument('--dump_images', type=int, default=1, help='Dump images into vis/imgs folder for vis? (1=yes,0=no)') parser.add_argument('--dump_json', type=int, default=1, help='Dump json with predictions into vis folder? (1=yes,0=no)') parser.add_argument('--dump_path', type=int, default=0, help='Write image paths along with predictions into vis json? (1=yes,0=no)') add_eval_sample_opts(parser) parser.add_argument('--image_folder', type=str, default='', help='If this is nonempty then will predict on the images in this folder path') parser.add_argument('--image_root', type=str, default='', help='In case the image paths have to be preprended with a root path to an image folder') parser.add_argument('--input_fc_dir', type=str, default='', help='path to the h5file containing the preprocessed dataset') parser.add_argument('--input_att_dir', type=str, default='', help='path to the h5file containing the preprocessed dataset') parser.add_argument('--input_box_dir', type=str, default='', help='path to the h5file containing the preprocessed dataset') parser.add_argument('--input_label_h5', type=str, default='', help='path to the h5file containing the preprocessed dataset') parser.add_argument('--input_json', type=str, default='', help='path to the json file containing additional info and vocab. empty = fetch from model checkpoint.') parser.add_argument('--split', type=str, default='test', help='if running on MSCOCO images, which split to use: val|test|train') parser.add_argument('--coco_json', type=str, default='', help='if nonempty then use this file in DataLoaderRaw (see docs there). Used only in MSCOCO test evaluation, where we have a specific json file of only test set images.') parser.add_argument('--id', type=str, default='', help='an id identifying this run/job. used only if language_eval = 1 for appending to intermediate files') parser.add_argument('--verbose_beam', type=int, default=1, help='if we need to print out all beam search beams.') parser.add_argument('--verbose_loss', type=int, default=0, help='If calculate loss using ground truth during evaluation')
def add_diversity_opts(parser): parser.add_argument('--sample_n', type=int, default=1, help='Diverse sampling') parser.add_argument('--sample_n_method', type=str, default='sample', help='sample, bs, dbs, gumbel, topk, dgreedy, dsample, dtopk, dtopp') parser.add_argument('--eval_oracle', type=int, default=1, help='if we need to calculate loss.')
def add_eval_sample_opts(parser): parser.add_argument('--sample_method', type=str, default='greedy', help='greedy; sample; gumbel; top<int>, top<0-1>') parser.add_argument('--beam_size', type=int, default=1, help='used when sample_method = greedy, indicates number of beams in beam search. Usually 2 or 3 works well. More is not better. Set this to 1 for faster runtime but a bit worse performance.') parser.add_argument('--max_length', type=int, default=20, help='Maximum length during sampling') parser.add_argument('--length_penalty', type=str, default='', help='wu_X or avg_X, X is the alpha') parser.add_argument('--group_size', type=int, default=1, help="used for diverse beam search. if group_size is 1, then it's normal beam search") parser.add_argument('--diversity_lambda', type=float, default=0.5, help='used for diverse beam search. Usually from 0.2 to 0.8. Higher value of lambda produces a more diverse list') parser.add_argument('--temperature', type=float, default=1.0, help='temperature when sampling from distributions (i.e. when sample_method = sample). Lower = "safer" predictions.') parser.add_argument('--decoding_constraint', type=int, default=0, help='If 1, not allowing same word in a row') parser.add_argument('--block_trigrams', type=int, default=0, help='block repeated trigram.') parser.add_argument('--remove_bad_endings', type=int, default=0, help='Remove bad endings') parser.add_argument('--suppress_UNK', type=int, default=1, help='Not predicting UNK')
class ResNet(torchvision.models.resnet.ResNet): def __init__(self, block, layers, num_classes=1000): super(ResNet, self).__init__(block, layers, num_classes) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=0, ceil_mode=True) for i in range(2, 5): getattr(self, ('layer%d' % i))[0].conv1.stride = (2, 2) getattr(self, ('layer%d' % i))[0].conv2.stride = (1, 1)
def resnet18(pretrained=False): 'Constructs a ResNet-18 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = ResNet(BasicBlock, [2, 2, 2, 2]) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet18'])) return model
def resnet34(pretrained=False): 'Constructs a ResNet-34 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = ResNet(BasicBlock, [3, 4, 6, 3]) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet34'])) return model
def resnet50(pretrained=False): 'Constructs a ResNet-50 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = ResNet(Bottleneck, [3, 4, 6, 3]) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet50'])) return model
def resnet101(pretrained=False): 'Constructs a ResNet-101 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = ResNet(Bottleneck, [3, 4, 23, 3]) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet101'])) return model
def resnet152(pretrained=False): 'Constructs a ResNet-152 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = ResNet(Bottleneck, [3, 8, 36, 3]) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet152'])) return model
class myResnet(nn.Module): def __init__(self, resnet): super(myResnet, self).__init__() self.resnet = resnet def forward(self, img, att_size=14): x = img.unsqueeze(0) x = self.resnet.conv1(x) x = self.resnet.bn1(x) x = self.resnet.relu(x) x = self.resnet.maxpool(x) x = self.resnet.layer1(x) x = self.resnet.layer2(x) x = self.resnet.layer3(x) x = self.resnet.layer4(x) fc = x.mean(3).mean(2).squeeze() att = F.adaptive_avg_pool2d(x, [att_size, att_size]).squeeze().permute(1, 2, 0) return (fc, att)
def build_vocab(imgs, params): captions = [] for img in imgs: for sent in img['sentences']: captions.append(' '.join(sent['tokens'])) captions = '\n'.join(captions) all_captions = tempfile.NamedTemporaryFile(delete=False) all_captions.close() with open(all_captions.name, 'w') as txt_file: txt_file.write(captions) codecs_output = tempfile.NamedTemporaryFile(delete=False) codecs_output.close() with codecs.open(codecs_output.name, 'w', encoding='UTF-8') as output: learn_bpe.learn_bpe(codecs.open(all_captions.name, encoding='UTF-8'), output, params['symbol_count']) with codecs.open(codecs_output.name, encoding='UTF-8') as codes: bpe = apply_bpe.BPE(codes) tmp = tempfile.NamedTemporaryFile(delete=False) tmp.close() tmpout = codecs.open(tmp.name, 'w', encoding='UTF-8') for (_, img) in enumerate(imgs): img['final_captions'] = [] for sent in img['sentences']: txt = ' '.join(sent['tokens']) txt = bpe.segment(txt).strip() img['final_captions'].append(txt.split(' ')) tmpout.write(txt) tmpout.write('\n') if (_ < 20): print(txt) tmpout.close() tmpin = codecs.open(tmp.name, encoding='UTF-8') vocab = learn_bpe.get_vocabulary(tmpin) vocab = sorted(vocab.keys(), key=(lambda x: vocab[x]), reverse=True) print('inserting the special UNK token') vocab.append('UNK') print('Vocab size:', len(vocab)) os.remove(all_captions.name) with open(codecs_output.name, 'r') as codes: bpe = codes.read() os.remove(codecs_output.name) os.remove(tmp.name) return (vocab, bpe)
def encode_captions(imgs, params, wtoi): ' \n\tencode all captions into one large array, which will be 1-indexed.\n\talso produces label_start_ix and label_end_ix which store 1-indexed \n\tand inclusive (Lua-style) pointers to the first and last caption for\n\teach image in the dataset.\n\t' max_length = params['max_length'] N = len(imgs) M = sum((len(img['final_captions']) for img in imgs)) label_arrays = [] label_start_ix = np.zeros(N, dtype='uint32') label_end_ix = np.zeros(N, dtype='uint32') label_length = np.zeros(M, dtype='uint32') caption_counter = 0 counter = 1 for (i, img) in enumerate(imgs): n = len(img['final_captions']) assert (n > 0), 'error: some image has no captions' Li = np.zeros((n, max_length), dtype='uint32') for (j, s) in enumerate(img['final_captions']): label_length[caption_counter] = min(max_length, len(s)) caption_counter += 1 for (k, w) in enumerate(s): if (k < max_length): Li[(j, k)] = wtoi[w] label_arrays.append(Li) label_start_ix[i] = counter label_end_ix[i] = ((counter + n) - 1) counter += n L = np.concatenate(label_arrays, axis=0) assert (L.shape[0] == M), "lengths don't match? that's weird" assert np.all((label_length > 0)), 'error: some caption had no words?' print('encoded captions to array of size ', L.shape) return (L, label_start_ix, label_end_ix, label_length)
def main(params): imgs = json.load(open(params['input_json'], 'r')) imgs = imgs['images'] seed(123) (vocab, bpe) = build_vocab(imgs, params) itow = {(i + 1): w for (i, w) in enumerate(vocab)} wtoi = {w: (i + 1) for (i, w) in enumerate(vocab)} (L, label_start_ix, label_end_ix, label_length) = encode_captions(imgs, params, wtoi) N = len(imgs) f_lb = h5py.File((params['output_h5'] + '_label.h5'), 'w') f_lb.create_dataset('labels', dtype='uint32', data=L) f_lb.create_dataset('label_start_ix', dtype='uint32', data=label_start_ix) f_lb.create_dataset('label_end_ix', dtype='uint32', data=label_end_ix) f_lb.create_dataset('label_length', dtype='uint32', data=label_length) f_lb.close() out = {} out['ix_to_word'] = itow out['images'] = [] out['bpe'] = bpe for (i, img) in enumerate(imgs): jimg = {} jimg['split'] = img['split'] if ('filename' in img): jimg['file_path'] = os.path.join(img['filepath'], img['filename']) if ('cocoid' in img): jimg['id'] = img['cocoid'] if (params['images_root'] != ''): with Image.open(os.path.join(params['images_root'], img['filepath'], img['filename'])) as _img: (jimg['width'], jimg['height']) = _img.size out['images'].append(jimg) json.dump(out, open(params['output_json'], 'w')) print('wrote ', params['output_json'])
def main(params): imgs = json.load(open(params['input_json'], 'r')) imgs = imgs['images'] N = len(imgs) if (params['fc_input_dir'] is not None): print('processing fc') with h5py.File(params['fc_output']) as file_fc: for (i, img) in enumerate(tqdm(imgs)): npy_fc_path = os.path.join(params['fc_input_dir'], (str(img['cocoid']) + '.npy')) d_set_fc = file_fc.create_dataset(str(img['cocoid']), data=np.load(npy_fc_path)) file_fc.close() if (params['att_input_dir'] is not None): print('processing att') with h5py.File(params['att_output']) as file_att: for (i, img) in enumerate(tqdm(imgs)): npy_att_path = os.path.join(params['att_input_dir'], (str(img['cocoid']) + '.npz')) d_set_att = file_att.create_dataset(str(img['cocoid']), data=np.load(npy_att_path)['feat']) file_att.close()
class FolderLMDB(data.Dataset): def __init__(self, db_path, fn_list=None): self.db_path = db_path self.lmdb = lmdbdict(db_path, unsafe=True) self.lmdb._key_dumps = DUMPS_FUNC['ascii'] self.lmdb._value_loads = LOADS_FUNC['identity'] if (fn_list is not None): self.length = len(fn_list) self.keys = fn_list else: raise Error def __getitem__(self, index): byteflow = self.lmdb[self.keys[index]] imgbuf = byteflow buf = six.BytesIO() buf.write(imgbuf) buf.seek(0) try: if (args.extension == '.npz'): feat = np.load(buf)['feat'] else: feat = np.load(buf) except Exception as e: print(self.keys[index], e) return None return feat def __len__(self): return self.length def __repr__(self): return (((self.__class__.__name__ + ' (') + self.db_path) + ')')
def make_dataset(dir, extension): images = [] dir = os.path.expanduser(dir) for (root, _, fnames) in sorted(os.walk(dir)): for fname in sorted(fnames): if has_file_allowed_extension(fname, [extension]): path = os.path.join(root, fname) images.append(path) return images
def raw_reader(path): with open(path, 'rb') as f: bin_data = f.read() return bin_data
def raw_npz_reader(path): with open(path, 'rb') as f: bin_data = f.read() try: npz_data = np.load(six.BytesIO(bin_data))['feat'] except Exception as e: print(path) npz_data = None print(e) return (bin_data, npz_data)
def raw_npy_reader(path): with open(path, 'rb') as f: bin_data = f.read() try: npy_data = np.load(six.BytesIO(bin_data)) except Exception as e: print(path) npy_data = None print(e) return (bin_data, npy_data)
class Folder(data.Dataset): def __init__(self, root, loader, extension, fn_list=None): super(Folder, self).__init__() self.root = root if fn_list: samples = [os.path.join(root, (str(_) + extension)) for _ in fn_list] else: samples = make_dataset(self.root, extension) self.loader = loader self.extension = extension self.samples = samples def __getitem__(self, index): '\n Args:\n index (int): Index\n Returns:\n tuple: (sample, target) where target is class_index of the target class.\n ' path = self.samples[index] sample = self.loader(path) return ((path.split('/')[(- 1)].split('.')[0],) + sample) def __len__(self): return len(self.samples)
def folder2lmdb(dpath, fn_list, write_frequency=5000): directory = osp.expanduser(osp.join(dpath)) print(('Loading dataset from %s' % directory)) if (args.extension == '.npz'): dataset = Folder(directory, loader=raw_npz_reader, extension='.npz', fn_list=fn_list) else: dataset = Folder(directory, loader=raw_npy_reader, extension='.npy', fn_list=fn_list) data_loader = DataLoader(dataset, num_workers=16, collate_fn=(lambda x: x)) lmdb_path = osp.join(('%s.lmdb' % directory)) isdir = os.path.isdir(lmdb_path) print(('Generate LMDB to %s' % lmdb_path)) db = lmdbdict(lmdb_path, mode='w', key_method='ascii', value_method='identity') tsvfile = open(args.output_file, 'a') writer = csv.DictWriter(tsvfile, delimiter='\t', fieldnames=FIELDNAMES) names = [] all_keys = [] for (idx, data) in enumerate(tqdm.tqdm(data_loader)): (name, byte, npz) = data[0] if (npz is not None): db[name] = byte all_keys.append(name) names.append({'image_id': name, 'status': str((npz is not None))}) if ((idx % write_frequency) == 0): print(('[%d/%d]' % (idx, len(data_loader)))) print('writing') db.flush() for name in names: writer.writerow(name) names = [] tsvfile.flush() print('writing finished') for name in names: writer.writerow(name) tsvfile.flush() tsvfile.close() print('Flushing database ...') db.flush() del db
def parse_args(): '\n Parse input arguments\n ' parser = argparse.ArgumentParser(description='Generate bbox output from a Fast R-CNN network') parser.add_argument('--input_json', default='./data/dataset_coco.json', type=str) parser.add_argument('--output_file', default='.dump_cache.tsv', type=str) parser.add_argument('--folder', default='./data/cocobu_att', type=str) parser.add_argument('--extension', default='.npz', type=str) args = parser.parse_args() return args