HarryLee commited on
Commit
e87479b
1 Parent(s): 45da9c7

Add tools support

Browse files
Files changed (43) hide show
  1. models/__init__.py +1 -0
  2. models/ofa/__init__.py +1 -0
  3. models/ofa/ofa.py +434 -0
  4. models/ofa/resnet.py +225 -0
  5. models/ofa/unify_multihead_attention.py +518 -0
  6. models/ofa/unify_transformer.py +1512 -0
  7. models/ofa/unify_transformer_layer.py +542 -0
  8. models/search.py +814 -0
  9. models/sequence_generator.py +1053 -0
  10. ofa_module/__init__.py +5 -0
  11. run_scripts/caption/coco_eval.py +42 -0
  12. run_scripts/caption/evaluate_caption.sh +35 -0
  13. run_scripts/caption/evaluate_caption_base.sh +33 -0
  14. run_scripts/caption/train_caption_stage1.sh +108 -0
  15. run_scripts/caption/train_caption_stage1_base.sh +108 -0
  16. run_scripts/caption/train_caption_stage1_el.sh +109 -0
  17. run_scripts/caption/train_caption_stage1_el_db.sh +111 -0
  18. run_scripts/caption/train_caption_stage2.sh +105 -0
  19. run_scripts/caption/train_caption_stage2_base.sh +105 -0
  20. tasks/__init__.py +6 -0
  21. tasks/mm_tasks/__init__.py +5 -0
  22. tasks/mm_tasks/caption.py +249 -0
  23. tasks/mm_tasks/image_gen.py +329 -0
  24. tasks/mm_tasks/refcoco.py +160 -0
  25. tasks/mm_tasks/snli_ve.py +197 -0
  26. tasks/mm_tasks/vqa_gen.py +278 -0
  27. tasks/ofa_task.py +337 -0
  28. utils/BPE/__init__.py +0 -0
  29. utils/BPE/dict.txt +0 -0
  30. utils/BPE/encoder.json +0 -0
  31. utils/BPE/vocab.bpe +0 -0
  32. utils/__init__.py +0 -0
  33. utils/checkpoint_utils.py +875 -0
  34. utils/cider/pyciderevalcap/__init__.py +1 -0
  35. utils/cider/pyciderevalcap/cider/__init__.py +1 -0
  36. utils/cider/pyciderevalcap/cider/cider.py +65 -0
  37. utils/cider/pyciderevalcap/cider/cider_scorer.py +207 -0
  38. utils/cider/pyciderevalcap/ciderD/__init__.py +1 -0
  39. utils/cider/pyciderevalcap/ciderD/ciderD.py +58 -0
  40. utils/cider/pyciderevalcap/ciderD/ciderD_scorer.py +222 -0
  41. utils/eval_utils.py +349 -0
  42. utils/transforms.py +513 -0
  43. utils/trie.py +30 -0
models/__init__.py ADDED
@@ -0,0 +1 @@
 
1
+ from .ofa import OFAModel, ofa_base_architecture, ofa_large_architecture, ofa_huge_architecture
models/ofa/__init__.py ADDED
@@ -0,0 +1 @@
 
1
+ from .ofa import OFAModel, ofa_base_architecture, ofa_large_architecture, ofa_huge_architecture
models/ofa/ofa.py ADDED
@@ -0,0 +1,434 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The OFA-Sys Team.
2
+ # All rights reserved.
3
+ # This source code is licensed under the Apache 2.0 license
4
+ # found in the LICENSE file in the root directory.
5
+
6
+ """
7
+ OFA
8
+ """
9
+ from typing import Optional
10
+
11
+ import logging
12
+
13
+ import torch
14
+ import torch.nn as nn
15
+ import torch.nn.functional as F
16
+ from fairseq import utils
17
+ from fairseq.models import register_model, register_model_architecture
18
+ from fairseq.modules.transformer_sentence_encoder import init_bert_params
19
+
20
+ from .unify_transformer import TransformerModel
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+
25
+ @register_model("ofa")
26
+ class OFAModel(TransformerModel):
27
+ __jit_unused_properties__ = ["supported_targets"]
28
+
29
+ def __init__(self, args, encoder, decoder):
30
+ super().__init__(args, encoder, decoder)
31
+
32
+ # We follow BERT's random weight initialization
33
+ self.apply(init_bert_params)
34
+
35
+ self.classification_heads = nn.ModuleDict()
36
+ if hasattr(self.encoder, "dictionary"):
37
+ self.eos: int = self.encoder.dictionary.eos()
38
+
39
+ @staticmethod
40
+ def add_args(parser):
41
+ super(OFAModel, OFAModel).add_args(parser)
42
+ parser.add_argument(
43
+ "--pooler-dropout",
44
+ type=float,
45
+ metavar="D",
46
+ help="dropout probability in the masked_lm pooler layers",
47
+ )
48
+ parser.add_argument(
49
+ "--pooler-classifier",
50
+ type=str,
51
+ choices=['mlp', 'linear'],
52
+ help="type of pooler classifier",
53
+ )
54
+ parser.add_argument(
55
+ "--pooler-activation-fn",
56
+ choices=utils.get_available_activation_fns(),
57
+ help="activation function to use for pooler layer",
58
+ )
59
+ parser.add_argument(
60
+ "--spectral-norm-classification-head",
61
+ action="store_true",
62
+ help="Apply spectral normalization on the classification head",
63
+ )
64
+
65
+ @property
66
+ def supported_targets(self):
67
+ return {"self"}
68
+
69
+ def forward(
70
+ self,
71
+ src_tokens,
72
+ src_lengths,
73
+ prev_output_tokens,
74
+ patch_images: Optional[torch.Tensor] = None,
75
+ patch_images_2: Optional[torch.Tensor] = None,
76
+ patch_masks: Optional[torch.Tensor] = None,
77
+ code_masks: Optional[torch.Tensor] = None,
78
+ sample_patch_num: Optional[int] = None,
79
+ features_only: bool = False,
80
+ classification_head_name: Optional[str] = None,
81
+ token_embeddings: Optional[torch.Tensor] = None,
82
+ return_all_hiddens: bool = False,
83
+ alignment_layer: Optional[int] = None,
84
+ alignment_heads: Optional[int] = None,
85
+ ):
86
+ if classification_head_name is not None:
87
+ features_only = True
88
+
89
+ encoder_out = self.encoder(
90
+ src_tokens,
91
+ src_lengths=src_lengths,
92
+ patch_images=patch_images,
93
+ patch_masks=patch_masks,
94
+ patch_images_2=patch_images_2,
95
+ token_embeddings=token_embeddings,
96
+ return_all_hiddens=return_all_hiddens,
97
+ sample_patch_num=sample_patch_num
98
+ )
99
+ x, extra = self.decoder(
100
+ prev_output_tokens,
101
+ code_masks=code_masks,
102
+ encoder_out=encoder_out,
103
+ features_only=features_only,
104
+ alignment_layer=alignment_layer,
105
+ alignment_heads=alignment_heads,
106
+ src_lengths=src_lengths,
107
+ return_all_hiddens=return_all_hiddens,
108
+ )
109
+
110
+ pad = self.encoder.padding_idx
111
+ if classification_head_name is not None:
112
+ prev_lengths = prev_output_tokens.ne(pad).sum(1)
113
+ gather_index = prev_lengths[:, None, None].expand(x.size(0), 1, x.size(2)) - 1
114
+ sentence_representation = x.gather(1, gather_index).squeeze()
115
+ if self.classification_heads[classification_head_name].use_two_images:
116
+ hidden_size = sentence_representation.size(1)
117
+ sentence_representation = sentence_representation.view(-1, hidden_size * 2)
118
+ for k, head in self.classification_heads.items():
119
+ # for torch script only supports iteration
120
+ if k == classification_head_name:
121
+ x = head(sentence_representation)
122
+ break
123
+
124
+ return x, extra
125
+
126
+ def register_embedding_tokens(self, ans2label_dict, src_dict, bpe):
127
+ """Register embedding tokens"""
128
+ logger.info("Registering embedding tokens")
129
+ self.ans_tensor_list = []
130
+ for i in range(len(ans2label_dict)):
131
+ ans = src_dict[-len(ans2label_dict)+i]
132
+ ans = ans[5:-1].replace('_', ' ')
133
+ ans_tensor = src_dict.encode_line(
134
+ line=bpe.encode(' {}'.format(ans.lower())),
135
+ add_if_not_exist=False,
136
+ append_eos=False
137
+ ).long()
138
+ self.ans_tensor_list.append(ans_tensor)
139
+
140
+ def register_classification_head(
141
+ self, name, num_classes=None, inner_dim=None, use_two_images=False, **kwargs
142
+ ):
143
+ """Register a classification head."""
144
+ logger.info("Registering classification head: {0}".format(name))
145
+ if name in self.classification_heads:
146
+ prev_num_classes = self.classification_heads[name].out_proj.out_features
147
+ prev_inner_dim = self.classification_heads[name].dense.out_features
148
+ if num_classes != prev_num_classes or inner_dim != prev_inner_dim:
149
+ logger.warning(
150
+ 're-registering head "{}" with num_classes {} (prev: {}) '
151
+ "and inner_dim {} (prev: {})".format(
152
+ name, num_classes, prev_num_classes, inner_dim, prev_inner_dim
153
+ )
154
+ )
155
+ self.classification_heads[name] = OFAClassificationHead(
156
+ input_dim=self.args.encoder_embed_dim,
157
+ inner_dim=inner_dim or self.args.encoder_embed_dim,
158
+ num_classes=num_classes,
159
+ activation_fn=self.args.pooler_activation_fn,
160
+ pooler_dropout=self.args.pooler_dropout,
161
+ pooler_classifier=self.args.pooler_classifier,
162
+ use_two_images=use_two_images,
163
+ do_spectral_norm=getattr(
164
+ self.args, "spectral_norm_classification_head", False
165
+ ),
166
+ )
167
+
168
+ def upgrade_state_dict_named(self, state_dict, name):
169
+ super().upgrade_state_dict_named(state_dict, name)
170
+
171
+ prefix = name + "." if name != "" else ""
172
+ current_head_names = (
173
+ []
174
+ if not hasattr(self, "classification_heads")
175
+ else self.classification_heads.keys()
176
+ )
177
+
178
+ # Handle new classification heads present in the state dict.
179
+ keys_to_delete = []
180
+ for k in state_dict.keys():
181
+ if not k.startswith(prefix + "classification_heads."):
182
+ continue
183
+
184
+ head_name = k[len(prefix + "classification_heads.") :].split(".")[0]
185
+ num_classes = state_dict[
186
+ prefix + "classification_heads." + head_name + ".out_proj.weight"
187
+ ].size(0)
188
+ inner_dim = state_dict[
189
+ prefix + "classification_heads." + head_name + ".dense.weight"
190
+ ].size(0)
191
+
192
+ if getattr(self.args, "load_checkpoint_heads", False):
193
+ if head_name not in current_head_names:
194
+ self.register_classification_head(head_name, num_classes, inner_dim)
195
+ else:
196
+ if head_name not in current_head_names:
197
+ logger.warning(
198
+ "deleting classification head ({}) from checkpoint "
199
+ "not present in current model: {}".format(head_name, k)
200
+ )
201
+ keys_to_delete.append(k)
202
+ elif (
203
+ num_classes
204
+ != self.classification_heads[head_name].out_proj.out_features
205
+ or inner_dim
206
+ != self.classification_heads[head_name].dense.out_features
207
+ ):
208
+ logger.warning(
209
+ "deleting classification head ({}) from checkpoint "
210
+ "with different dimensions than current model: {}".format(
211
+ head_name, k
212
+ )
213
+ )
214
+ keys_to_delete.append(k)
215
+ for k in keys_to_delete:
216
+ del state_dict[k]
217
+
218
+ def truncate_emb(key):
219
+ if key in state_dict:
220
+ state_dict[key] = state_dict[key][:-1, :]
221
+
222
+ # When finetuning on translation task, remove last row of
223
+ # embedding matrix that corresponds to mask_idx token.
224
+ loaded_dict_size = state_dict["encoder.embed_tokens.weight"].size(0)
225
+ if (
226
+ loaded_dict_size == len(self.encoder.dictionary) + 1
227
+ and "<mask>" not in self.encoder.dictionary
228
+ ):
229
+ truncate_emb("encoder.embed_tokens.weight")
230
+ truncate_emb("decoder.embed_tokens.weight")
231
+ truncate_emb("encoder.output_projection.weight")
232
+ truncate_emb("decoder.output_projection.weight")
233
+
234
+ if loaded_dict_size < len(self.encoder.dictionary):
235
+ num_langids_to_add = len(self.encoder.dictionary) - loaded_dict_size
236
+ embed_dim = state_dict["encoder.embed_tokens.weight"].size(1)
237
+
238
+ new_lang_embed_to_add = torch.zeros(num_langids_to_add, embed_dim)
239
+ if getattr(self, "ans_tensor_list", None):
240
+ assert len(new_lang_embed_to_add) == len(self.ans_tensor_list)
241
+ for i, ans_tensor in enumerate(self.ans_tensor_list):
242
+ ans_embed = F.embedding(ans_tensor, state_dict["encoder.embed_tokens.weight"])
243
+ ans_embed = ans_embed.sum(0) / ans_embed.size(0)
244
+ new_lang_embed_to_add[i] = ans_embed
245
+ else:
246
+ nn.init.normal_(new_lang_embed_to_add, mean=0, std=embed_dim ** -0.5)
247
+ new_lang_embed_to_add = new_lang_embed_to_add.to(
248
+ dtype=state_dict["encoder.embed_tokens.weight"].dtype,
249
+ )
250
+
251
+ state_dict["encoder.embed_tokens.weight"] = torch.cat(
252
+ [state_dict["encoder.embed_tokens.weight"], new_lang_embed_to_add]
253
+ )
254
+ state_dict["decoder.embed_tokens.weight"] = torch.cat(
255
+ [state_dict["decoder.embed_tokens.weight"], new_lang_embed_to_add]
256
+ )
257
+ state_dict["decoder.output_projection.weight"] = torch.cat(
258
+ [state_dict["decoder.output_projection.weight"], new_lang_embed_to_add]
259
+ )
260
+
261
+ # Copy any newly-added classification heads into the state dict
262
+ # with their current weights.
263
+ if hasattr(self, "classification_heads"):
264
+ cur_state = self.classification_heads.state_dict()
265
+ for k, v in cur_state.items():
266
+ if prefix + "classification_heads." + k not in state_dict:
267
+ logger.info("Overwriting " + prefix + "classification_heads." + k)
268
+ state_dict[prefix + "classification_heads." + k] = v
269
+
270
+
271
+ class OFAClassificationHead(nn.Module):
272
+ """Head for sentence-level classification tasks."""
273
+
274
+ def __init__(
275
+ self,
276
+ input_dim,
277
+ inner_dim,
278
+ num_classes,
279
+ activation_fn,
280
+ pooler_dropout,
281
+ pooler_classifier,
282
+ use_two_images=False,
283
+ do_spectral_norm=False,
284
+ ):
285
+ super().__init__()
286
+ self.pooler_classifier = pooler_classifier
287
+ self.use_two_images = use_two_images
288
+ input_dim = input_dim * 2 if use_two_images else input_dim
289
+ if pooler_classifier == "mlp":
290
+ self.dense = nn.Linear(input_dim, inner_dim)
291
+ self.activation_fn = utils.get_activation_fn(activation_fn)
292
+ self.dropout = nn.Dropout(p=pooler_dropout)
293
+ self.out_proj = nn.Linear(inner_dim, num_classes)
294
+ elif pooler_classifier == "linear":
295
+ self.dropout = nn.Dropout(p=pooler_dropout)
296
+ self.out_proj = nn.Linear(input_dim, num_classes)
297
+ else:
298
+ raise NotImplementedError
299
+
300
+ if do_spectral_norm:
301
+ self.out_proj = torch.nn.utils.spectral_norm(self.out_proj)
302
+
303
+ def forward(self, features, **kwargs):
304
+ if self.pooler_classifier == 'mlp':
305
+ x = features
306
+ x = self.dropout(x)
307
+ x = self.dense(x)
308
+ x = self.activation_fn(x)
309
+ x = self.dropout(x)
310
+ x = self.out_proj(x)
311
+ elif self.pooler_classifier == 'linear':
312
+ x = features
313
+ x = self.dropout(x)
314
+ x = self.out_proj(x)
315
+ else:
316
+ raise NotImplementedError
317
+ return x
318
+
319
+
320
+ @register_model_architecture("ofa", "ofa_large")
321
+ def ofa_large_architecture(args):
322
+ args.encoder_embed_path = getattr(args, "encoder_embed_path", None)
323
+ args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 1024)
324
+ args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 4 * 1024)
325
+ args.encoder_layers = getattr(args, "encoder_layers", 12)
326
+ args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 16)
327
+ args.encoder_normalize_before = getattr(args, "encoder_normalize_before", True)
328
+ args.encoder_learned_pos = getattr(args, "encoder_learned_pos", True)
329
+ args.decoder_embed_path = getattr(args, "decoder_embed_path", None)
330
+ args.decoder_embed_dim = getattr(args, "decoder_embed_dim", args.encoder_embed_dim)
331
+ args.decoder_ffn_embed_dim = getattr(
332
+ args, "decoder_ffn_embed_dim", args.encoder_ffn_embed_dim
333
+ )
334
+ args.decoder_layers = getattr(args, "decoder_layers", 12)
335
+ args.decoder_attention_heads = getattr(args, "decoder_attention_heads", 16)
336
+ args.decoder_normalize_before = getattr(args, "decoder_normalize_before", True)
337
+ args.decoder_learned_pos = getattr(args, "decoder_learned_pos", True)
338
+ args.attention_dropout = getattr(args, "attention_dropout", 0.0)
339
+ args.relu_dropout = getattr(args, "relu_dropout", 0.0)
340
+ args.dropout = getattr(args, "dropout", 0.0)
341
+ args.max_target_positions = getattr(args, "max_target_positions", 1024)
342
+ args.max_source_positions = getattr(args, "max_source_positions", 1024)
343
+ args.adaptive_softmax_cutoff = getattr(args, "adaptive_softmax_cutoff", None)
344
+ args.adaptive_softmax_dropout = getattr(args, "adaptive_softmax_dropout", 0)
345
+ args.share_decoder_input_output_embed = getattr(
346
+ args, "share_decoder_input_output_embed", True
347
+ )
348
+ args.share_all_embeddings = getattr(args, "share_all_embeddings", True)
349
+
350
+ args.decoder_output_dim = getattr(
351
+ args, "decoder_output_dim", args.decoder_embed_dim
352
+ )
353
+ args.decoder_input_dim = getattr(args, "decoder_input_dim", args.decoder_embed_dim)
354
+
355
+ args.no_scale_embedding = getattr(args, "no_scale_embedding", True)
356
+ args.layernorm_embedding = getattr(args, "layernorm_embedding", True)
357
+
358
+ args.activation_fn = getattr(args, "activation_fn", "gelu")
359
+ args.pooler_activation_fn = getattr(args, "pooler_activation_fn", "tanh")
360
+ args.pooler_dropout = getattr(args, "pooler_dropout", 0.0)
361
+ args.pooler_classifier = getattr(args, "pooler_classifier", "mlp")
362
+
363
+ args.resnet_drop_path_rate = getattr(args, "resnet_drop_path_rate", 0.0)
364
+ args.encoder_drop_path_rate = getattr(args, "encoder_drop_path_rate", 0.0)
365
+ args.decoder_drop_path_rate = getattr(args, "decoder_drop_path_rate", 0.0)
366
+
367
+ args.resnet_type = getattr(args, "resnet_type", "resnet152")
368
+ args.token_bucket_size = getattr(args, "token_bucket_size", 256)
369
+ args.image_bucket_size = getattr(args, "image_bucket_size", 42)
370
+
371
+ args.freeze_encoder_embedding = getattr(args, "freeze_encoder_embedding", False)
372
+ args.freeze_decoder_embedding = getattr(args, "freeze_decoder_embedding", False)
373
+ args.add_type_embedding = getattr(args, "add_type_embedding", True)
374
+ args.attn_scale_factor = getattr(args, "attn_scale_factor", 2)
375
+
376
+ args.code_image_size = getattr(args, "code_image_size", 128)
377
+ args.patch_layernorm_embedding = getattr(args, "patch_layernorm_embedding", True)
378
+ args.code_layernorm_embedding = getattr(args, "code_layernorm_embedding", True)
379
+ args.entangle_position_embedding = getattr(args, "entangle_position_embedding", False)
380
+ args.disable_entangle = getattr(args, "disable_entangle", False)
381
+ args.sync_bn = getattr(args, "sync_bn", False)
382
+
383
+ args.scale_attn = getattr(args, "scale_attn", False)
384
+ args.scale_fc = getattr(args, "scale_fc", False)
385
+ args.scale_heads = getattr(args, "scale_heads", False)
386
+ args.scale_resids = getattr(args, "scale_resids", False)
387
+
388
+
389
+ @register_model_architecture("ofa", "ofa_base")
390
+ def ofa_base_architecture(args):
391
+ args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 768)
392
+ args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 4 * 768)
393
+ args.encoder_layers = getattr(args, "encoder_layers", 6)
394
+ args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 12)
395
+ args.decoder_layers = getattr(args, "decoder_layers", 6)
396
+ args.decoder_attention_heads = getattr(args, "decoder_attention_heads", 12)
397
+ args.resnet_type = getattr(args, "resnet_type", "resnet101")
398
+ ofa_large_architecture(args)
399
+
400
+
401
+ @register_model_architecture("ofa", "ofa_huge")
402
+ def ofa_huge_architecture(args):
403
+ args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 1280)
404
+ args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 4 * 1280)
405
+ args.encoder_layers = getattr(args, "encoder_layers", 24)
406
+ args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 16)
407
+ args.decoder_layers = getattr(args, "decoder_layers", 12)
408
+ args.decoder_attention_heads = getattr(args, "decoder_attention_heads", 16)
409
+ args.resnet_type = getattr(args, "resnet_type", "resnet152")
410
+ ofa_large_architecture(args)
411
+
412
+
413
+ @register_model_architecture("ofa", "ofa_medium")
414
+ def ofa_medium_architecture(args):
415
+ args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 512)
416
+ args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 4 * 512)
417
+ args.encoder_layers = getattr(args, "encoder_layers", 4)
418
+ args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 8)
419
+ args.decoder_layers = getattr(args, "decoder_layers", 4)
420
+ args.decoder_attention_heads = getattr(args, "decoder_attention_heads", 8)
421
+ args.resnet_type = getattr(args, "resnet_type", "resnet101")
422
+ ofa_large_architecture(args)
423
+
424
+
425
+ @register_model_architecture("ofa", "ofa_tiny")
426
+ def ofa_medium_architecture(args):
427
+ args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 256)
428
+ args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 4 * 256)
429
+ args.encoder_layers = getattr(args, "encoder_layers", 4)
430
+ args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 4)
431
+ args.decoder_layers = getattr(args, "decoder_layers", 4)
432
+ args.decoder_attention_heads = getattr(args, "decoder_attention_heads", 4)
433
+ args.resnet_type = getattr(args, "resnet_type", "resnet50")
434
+ ofa_large_architecture(args)
models/ofa/resnet.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+
5
+ def drop_path(x, drop_prob: float = 0., training: bool = False):
6
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
7
+ This is the same as the DropConnect impl I created for EfficientNet, etc networks, however,
8
+ the original name is misleading as 'Drop Connect' is a.sh different form of dropout in a.sh separate paper...
9
+ See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for
10
+ changing the layer and argument names to 'drop path' rather than mix DropConnect as a.sh layer name and use
11
+ 'survival rate' as the argument.
12
+ """
13
+ if drop_prob == 0. or not training:
14
+ return x
15
+ keep_prob = 1 - drop_prob
16
+ shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
17
+ random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
18
+ random_tensor.floor_() # binarize
19
+ output = x.div(keep_prob) * random_tensor
20
+ return output
21
+
22
+
23
+ class DropPath(nn.Module):
24
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
25
+ """
26
+ def __init__(self, drop_prob=None):
27
+ super(DropPath, self).__init__()
28
+ self.drop_prob = drop_prob
29
+
30
+ def forward(self, x):
31
+ return drop_path(x, self.drop_prob, self.training)
32
+
33
+
34
+ def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
35
+ """3x3 convolution with padding"""
36
+ return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
37
+ padding=dilation, groups=groups, bias=False, dilation=dilation)
38
+
39
+
40
+ def conv1x1(in_planes, out_planes, stride=1):
41
+ """1x1 convolution"""
42
+ return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
43
+
44
+
45
+ class BasicBlock(nn.Module):
46
+ expansion = 1
47
+
48
+ def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
49
+ base_width=64, dilation=1, norm_layer=None):
50
+ super(BasicBlock, self).__init__()
51
+ if norm_layer is None:
52
+ norm_layer = nn.BatchNorm2d
53
+ if groups != 1 or base_width != 64:
54
+ raise ValueError('BasicBlock only supports groups=1 and base_width=64')
55
+ if dilation > 1:
56
+ raise NotImplementedError("Dilation > 1 not supported in BasicBlock")
57
+ # Both self.conv1 and self.downsample layers downsample the input when stride != 1
58
+ self.conv1 = conv3x3(inplanes, planes, stride)
59
+ self.bn1 = norm_layer(planes)
60
+ self.relu = nn.ReLU(inplace=True)
61
+ self.conv2 = conv3x3(planes, planes)
62
+ self.bn2 = norm_layer(planes)
63
+ self.downsample = downsample
64
+ self.stride = stride
65
+
66
+ def forward(self, x):
67
+ assert False
68
+ identity = x
69
+
70
+ out = self.conv1(x)
71
+ out = self.bn1(out)
72
+ out = self.relu(out)
73
+
74
+ out = self.conv2(out)
75
+ out = self.bn2(out)
76
+
77
+ if self.downsample is not None:
78
+ identity = self.downsample(x)
79
+
80
+ out += identity
81
+ out = self.relu(out)
82
+
83
+ return out
84
+
85
+
86
+ class Bottleneck(nn.Module):
87
+ # Bottleneck in torchvision places the stride for downsampling at 3x3 convolution(self.conv2)
88
+ # while original implementation places the stride at the first 1x1 convolution(self.conv1)
89
+ # according to "Deep residual learning for image recognition"https://arxiv.org/abs/1512.03385.
90
+ # This variant is also known as ResNet V1.5 and improves accuracy according to
91
+ # https://ngc.nvidia.com/catalog/model-scripts/nvidia:resnet_50_v1_5_for_pytorch.
92
+
93
+ expansion = 4
94
+
95
+ def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
96
+ base_width=64, dilation=1, norm_layer=None, drop_path_rate=0.0):
97
+ super(Bottleneck, self).__init__()
98
+ if norm_layer is None:
99
+ norm_layer = nn.BatchNorm2d
100
+ width = int(planes * (base_width / 64.)) * groups
101
+ # Both self.conv2 and self.downsample layers downsample the input when stride != 1
102
+ self.conv1 = conv1x1(inplanes, width)
103
+ self.bn1 = norm_layer(width)
104
+ self.conv2 = conv3x3(width, width, stride, groups, dilation)
105
+ self.bn2 = norm_layer(width)
106
+ self.conv3 = conv1x1(width, planes * self.expansion)
107
+ self.bn3 = norm_layer(planes * self.expansion)
108
+ self.relu = nn.ReLU(inplace=True)
109
+ self.downsample = downsample
110
+ self.stride = stride
111
+ self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
112
+
113
+ def forward(self, x):
114
+ identity = x
115
+
116
+ out = self.conv1(x)
117
+ out = self.bn1(out)
118
+ out = self.relu(out)
119
+
120
+ out = self.conv2(out)
121
+ out = self.bn2(out)
122
+ out = self.relu(out)
123
+
124
+ out = self.conv3(out)
125
+ out = self.bn3(out)
126
+
127
+ if self.downsample is not None:
128
+ identity = self.downsample(x)
129
+
130
+ out = identity + self.drop_path(out)
131
+ out = self.relu(out)
132
+
133
+ return out
134
+
135
+
136
+ class ResNet(nn.Module):
137
+
138
+ def __init__(self, layers, zero_init_residual=False,
139
+ groups=1, width_per_group=64, replace_stride_with_dilation=None,
140
+ norm_layer=None, drop_path_rate=0.0):
141
+ super(ResNet, self).__init__()
142
+ if norm_layer is None:
143
+ norm_layer = nn.BatchNorm2d
144
+ self._norm_layer = norm_layer
145
+
146
+ self.inplanes = 64
147
+ self.dilation = 1
148
+ if replace_stride_with_dilation is None:
149
+ # each element in the tuple indicates if we should replace
150
+ # the 2x2 stride with a dilated convolution instead
151
+ replace_stride_with_dilation = [False, False, False]
152
+ if len(replace_stride_with_dilation) != 3:
153
+ raise ValueError("replace_stride_with_dilation should be None "
154
+ "or a 3-element tuple, got {}".format(replace_stride_with_dilation))
155
+ self.groups = groups
156
+ self.base_width = width_per_group
157
+ self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3,
158
+ bias=False)
159
+ self.bn1 = norm_layer(self.inplanes)
160
+ self.relu = nn.ReLU(inplace=True)
161
+ self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
162
+ self.layer1 = self._make_layer(Bottleneck, 64, layers[0], drop_path_rate=drop_path_rate)
163
+ self.layer2 = self._make_layer(Bottleneck, 128, layers[1], stride=2,
164
+ dilate=replace_stride_with_dilation[0], drop_path_rate=drop_path_rate)
165
+ self.layer3 = self._make_layer(Bottleneck, 256, layers[2], stride=2,
166
+ dilate=replace_stride_with_dilation[1], drop_path_rate=drop_path_rate)
167
+
168
+ for m in self.modules():
169
+ if isinstance(m, nn.Conv2d):
170
+ nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
171
+ elif isinstance(m, (nn.SyncBatchNorm, nn.BatchNorm2d, nn.GroupNorm)):
172
+ nn.init.constant_(m.weight, 1)
173
+ nn.init.constant_(m.bias, 0)
174
+
175
+ # Zero-initialize the last BN in each residual branch,
176
+ # so that the residual branch starts with zeros, and each residual block behaves like an identity.
177
+ # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
178
+ if zero_init_residual:
179
+ for m in self.modules():
180
+ if isinstance(m, Bottleneck):
181
+ nn.init.constant_(m.bn3.weight, 0)
182
+ elif isinstance(m, BasicBlock):
183
+ nn.init.constant_(m.bn2.weight, 0)
184
+
185
+ def _make_layer(self, block, planes, blocks, stride=1, dilate=False, drop_path_rate=0.0):
186
+ norm_layer = self._norm_layer
187
+ downsample = None
188
+ previous_dilation = self.dilation
189
+ if dilate:
190
+ self.dilation *= stride
191
+ stride = 1
192
+ if stride != 1 or self.inplanes != planes * block.expansion:
193
+ downsample = nn.Sequential(
194
+ conv1x1(self.inplanes, planes * block.expansion, stride),
195
+ norm_layer(planes * block.expansion),
196
+ )
197
+
198
+ layers = []
199
+ layers.append(block(self.inplanes, planes, stride, downsample, self.groups,
200
+ self.base_width, previous_dilation, norm_layer))
201
+ self.inplanes = planes * block.expansion
202
+
203
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, blocks)]
204
+ for i in range(1, blocks):
205
+ layers.append(block(self.inplanes, planes, groups=self.groups,
206
+ base_width=self.base_width, dilation=self.dilation,
207
+ norm_layer=norm_layer, drop_path_rate=dpr[i]))
208
+
209
+ return nn.Sequential(*layers)
210
+
211
+ def _forward_impl(self, x):
212
+ # See note [TorchScript super()]
213
+ x = self.conv1(x)
214
+ x = self.bn1(x)
215
+ x = self.relu(x)
216
+ x = self.maxpool(x)
217
+
218
+ x = self.layer1(x)
219
+ x = self.layer2(x)
220
+ x = self.layer3(x)
221
+
222
+ return x
223
+
224
+ def forward(self, x):
225
+ return self._forward_impl(x)
models/ofa/unify_multihead_attention.py ADDED
@@ -0,0 +1,518 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The OFA-Sys Team.
2
+ # All rights reserved.
3
+ # This source code is licensed under the Apache 2.0 license
4
+ # found in the LICENSE file in the root directory.
5
+
6
+ import math
7
+ from typing import Dict, Optional, Tuple
8
+
9
+ import torch
10
+ import torch.nn.functional as F
11
+ from fairseq import utils
12
+ from fairseq.incremental_decoding_utils import with_incremental_state
13
+ from fairseq.modules.fairseq_dropout import FairseqDropout
14
+ from fairseq.modules.quant_noise import quant_noise
15
+ from torch import Tensor, nn
16
+ from torch.nn import Parameter
17
+
18
+
19
+ @with_incremental_state
20
+ class MultiheadAttention(nn.Module):
21
+ """Multi-headed attention.
22
+
23
+ See "Attention Is All You Need" for more details.
24
+ """
25
+
26
+ def __init__(
27
+ self,
28
+ embed_dim,
29
+ num_heads,
30
+ kdim=None,
31
+ vdim=None,
32
+ dropout=0.0,
33
+ bias=True,
34
+ add_bias_kv=False,
35
+ add_zero_attn=False,
36
+ self_attention=False,
37
+ encoder_decoder_attention=False,
38
+ q_noise=0.0,
39
+ qn_block_size=8,
40
+ scale_factor=2,
41
+ scale_heads=False
42
+ ):
43
+ super().__init__()
44
+ self.embed_dim = embed_dim
45
+ self.kdim = kdim if kdim is not None else embed_dim
46
+ self.vdim = vdim if vdim is not None else embed_dim
47
+ self.qkv_same_dim = self.kdim == embed_dim and self.vdim == embed_dim
48
+
49
+ self.num_heads = num_heads
50
+ self.dropout_module = FairseqDropout(
51
+ dropout, module_name=self.__class__.__name__
52
+ )
53
+
54
+ self.head_dim = embed_dim // num_heads
55
+ assert (
56
+ self.head_dim * num_heads == self.embed_dim
57
+ ), "embed_dim must be divisible by num_heads"
58
+ self.scaling = float(self.head_dim * scale_factor) ** -0.5
59
+
60
+ self.self_attention = self_attention
61
+ self.encoder_decoder_attention = encoder_decoder_attention
62
+ self.c_attn = nn.Parameter(torch.ones((self.num_heads,)), requires_grad=True) if scale_heads else None
63
+
64
+ assert not self.self_attention or self.qkv_same_dim, (
65
+ "Self-attention requires query, key and " "value to be of the same size"
66
+ )
67
+
68
+ self.k_proj = quant_noise(
69
+ nn.Linear(self.kdim, embed_dim, bias=bias), q_noise, qn_block_size
70
+ )
71
+ self.v_proj = quant_noise(
72
+ nn.Linear(self.vdim, embed_dim, bias=bias), q_noise, qn_block_size
73
+ )
74
+ self.q_proj = quant_noise(
75
+ nn.Linear(embed_dim, embed_dim, bias=bias), q_noise, qn_block_size
76
+ )
77
+
78
+ self.out_proj = quant_noise(
79
+ nn.Linear(embed_dim, embed_dim, bias=bias), q_noise, qn_block_size
80
+ )
81
+
82
+ if add_bias_kv:
83
+ self.bias_k = Parameter(torch.Tensor(1, 1, embed_dim))
84
+ self.bias_v = Parameter(torch.Tensor(1, 1, embed_dim))
85
+ else:
86
+ self.bias_k = self.bias_v = None
87
+
88
+ self.add_zero_attn = add_zero_attn
89
+
90
+ self.reset_parameters()
91
+
92
+ self.onnx_trace = False
93
+
94
+ def prepare_for_onnx_export_(self):
95
+ self.onnx_trace = True
96
+
97
+ def reset_parameters(self):
98
+ if self.qkv_same_dim:
99
+ # Empirically observed the convergence to be much better with
100
+ # the scaled initialization
101
+ nn.init.xavier_uniform_(self.k_proj.weight, gain=1 / math.sqrt(2))
102
+ nn.init.xavier_uniform_(self.v_proj.weight, gain=1 / math.sqrt(2))
103
+ nn.init.xavier_uniform_(self.q_proj.weight, gain=1 / math.sqrt(2))
104
+ else:
105
+ nn.init.xavier_uniform_(self.k_proj.weight)
106
+ nn.init.xavier_uniform_(self.v_proj.weight)
107
+ nn.init.xavier_uniform_(self.q_proj.weight)
108
+
109
+ nn.init.xavier_uniform_(self.out_proj.weight)
110
+ if self.out_proj.bias is not None:
111
+ nn.init.constant_(self.out_proj.bias, 0.0)
112
+ if self.bias_k is not None:
113
+ nn.init.xavier_normal_(self.bias_k)
114
+ if self.bias_v is not None:
115
+ nn.init.xavier_normal_(self.bias_v)
116
+
117
+ def forward(
118
+ self,
119
+ query,
120
+ key: Optional[Tensor],
121
+ value: Optional[Tensor],
122
+ key_padding_mask: Optional[Tensor] = None,
123
+ incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None,
124
+ need_weights: bool = True,
125
+ static_kv: bool = False,
126
+ attn_mask: Optional[Tensor] = None,
127
+ self_attn_mask: Optional[Tensor] = None,
128
+ before_softmax: bool = False,
129
+ need_head_weights: bool = False,
130
+ attn_bias: Optional[Tensor] = None
131
+ ) -> Tuple[Tensor, Optional[Tensor]]:
132
+ """Input shape: Time x Batch x Channel
133
+
134
+ Args:
135
+ key_padding_mask (ByteTensor, optional): mask to exclude
136
+ keys that are pads, of shape `(batch, src_len)`, where
137
+ padding elements are indicated by 1s.
138
+ need_weights (bool, optional): return the attention weights,
139
+ averaged over heads (default: False).
140
+ attn_mask (ByteTensor, optional): typically used to
141
+ implement causal attention, where the mask prevents the
142
+ attention from looking forward in time (default: None).
143
+ before_softmax (bool, optional): return the raw attention
144
+ weights and values before the attention softmax.
145
+ need_head_weights (bool, optional): return the attention
146
+ weights for each head. Implies *need_weights*. Default:
147
+ return the average attention weights over all heads.
148
+ """
149
+ if need_head_weights:
150
+ need_weights = True
151
+
152
+ is_tpu = query.device.type == "xla"
153
+
154
+ tgt_len, bsz, embed_dim = query.size()
155
+ src_len = tgt_len
156
+ assert embed_dim == self.embed_dim, f"query dim {embed_dim} != {self.embed_dim}"
157
+ assert list(query.size()) == [tgt_len, bsz, embed_dim]
158
+ if key is not None:
159
+ src_len, key_bsz, _ = key.size()
160
+ if not torch.jit.is_scripting():
161
+ assert key_bsz == bsz
162
+ assert value is not None
163
+ assert src_len, bsz == value.shape[:2]
164
+
165
+ if (
166
+ not self.onnx_trace
167
+ and not is_tpu # don't use PyTorch version on TPUs
168
+ and incremental_state is None
169
+ and not static_kv
170
+ # A workaround for quantization to work. Otherwise JIT compilation
171
+ # treats bias in linear module as method.
172
+ and not torch.jit.is_scripting()
173
+ and self_attn_mask is None
174
+ and attn_bias is None
175
+ ):
176
+ assert key is not None and value is not None
177
+ return F.multi_head_attention_forward(
178
+ query,
179
+ key,
180
+ value,
181
+ self.embed_dim,
182
+ self.num_heads,
183
+ torch.empty([0]),
184
+ torch.cat((self.q_proj.bias, self.k_proj.bias, self.v_proj.bias)),
185
+ self.bias_k,
186
+ self.bias_v,
187
+ self.add_zero_attn,
188
+ self.dropout_module.p,
189
+ self.out_proj.weight,
190
+ self.out_proj.bias,
191
+ self.training or self.dropout_module.apply_during_inference,
192
+ key_padding_mask,
193
+ need_weights,
194
+ attn_mask,
195
+ use_separate_proj_weight=True,
196
+ q_proj_weight=self.q_proj.weight,
197
+ k_proj_weight=self.k_proj.weight,
198
+ v_proj_weight=self.v_proj.weight,
199
+ )
200
+
201
+ if incremental_state is not None:
202
+ saved_state = self._get_input_buffer(incremental_state)
203
+ if saved_state is not None and "prev_key" in saved_state:
204
+ # previous time steps are cached - no need to recompute
205
+ # key and value if they are static
206
+ if static_kv:
207
+ assert self.encoder_decoder_attention and not self.self_attention
208
+ key = value = None
209
+ else:
210
+ saved_state = None
211
+
212
+ if self.self_attention and self_attn_mask is None:
213
+ q = self.q_proj(query)
214
+ k = self.k_proj(query)
215
+ v = self.v_proj(query)
216
+ elif self.encoder_decoder_attention:
217
+ # encoder-decoder attention
218
+ q = self.q_proj(query)
219
+ if key is None:
220
+ assert value is None
221
+ k = v = None
222
+ else:
223
+ k = self.k_proj(key)
224
+ v = self.v_proj(key)
225
+
226
+ else:
227
+ assert key is not None and value is not None
228
+ q = self.q_proj(query)
229
+ k = self.k_proj(key)
230
+ v = self.v_proj(value)
231
+ q *= self.scaling
232
+
233
+ if self.bias_k is not None:
234
+ assert self.bias_v is not None
235
+ k = torch.cat([k, self.bias_k.repeat(1, bsz, 1)])
236
+ v = torch.cat([v, self.bias_v.repeat(1, bsz, 1)])
237
+ if attn_mask is not None:
238
+ attn_mask = torch.cat(
239
+ [attn_mask, attn_mask.new_zeros(attn_mask.size(0), 1)], dim=1
240
+ )
241
+ if key_padding_mask is not None:
242
+ key_padding_mask = torch.cat(
243
+ [
244
+ key_padding_mask,
245
+ key_padding_mask.new_zeros(key_padding_mask.size(0), 1),
246
+ ],
247
+ dim=1,
248
+ )
249
+
250
+ q = (
251
+ q.contiguous()
252
+ .view(tgt_len, bsz * self.num_heads, self.head_dim)
253
+ .transpose(0, 1)
254
+ )
255
+ if k is not None:
256
+ k = (
257
+ k.contiguous()
258
+ .view(-1, bsz * self.num_heads, self.head_dim)
259
+ .transpose(0, 1)
260
+ )
261
+ if v is not None:
262
+ v = (
263
+ v.contiguous()
264
+ .view(-1, bsz * self.num_heads, self.head_dim)
265
+ .transpose(0, 1)
266
+ )
267
+
268
+ if saved_state is not None:
269
+ # saved states are stored with shape (bsz, num_heads, seq_len, head_dim)
270
+ if "prev_key" in saved_state:
271
+ _prev_key = saved_state["prev_key"]
272
+ assert _prev_key is not None
273
+ prev_key = _prev_key.view(bsz * self.num_heads, -1, self.head_dim)
274
+ if static_kv:
275
+ k = prev_key
276
+ else:
277
+ assert k is not None
278
+ k = torch.cat([prev_key, k], dim=1)
279
+ src_len = k.size(1)
280
+ if "prev_value" in saved_state:
281
+ _prev_value = saved_state["prev_value"]
282
+ assert _prev_value is not None
283
+ prev_value = _prev_value.view(bsz * self.num_heads, -1, self.head_dim)
284
+ if static_kv:
285
+ v = prev_value
286
+ else:
287
+ assert v is not None
288
+ v = torch.cat([prev_value, v], dim=1)
289
+ prev_key_padding_mask: Optional[Tensor] = None
290
+ if "prev_key_padding_mask" in saved_state:
291
+ prev_key_padding_mask = saved_state["prev_key_padding_mask"]
292
+ assert k is not None and v is not None
293
+ key_padding_mask = MultiheadAttention._append_prev_key_padding_mask(
294
+ key_padding_mask=key_padding_mask,
295
+ prev_key_padding_mask=prev_key_padding_mask,
296
+ batch_size=bsz,
297
+ src_len=k.size(1),
298
+ static_kv=static_kv,
299
+ )
300
+
301
+ saved_state["prev_key"] = k.view(bsz, self.num_heads, -1, self.head_dim)
302
+ saved_state["prev_value"] = v.view(bsz, self.num_heads, -1, self.head_dim)
303
+ saved_state["prev_key_padding_mask"] = key_padding_mask
304
+ # In this branch incremental_state is never None
305
+ assert incremental_state is not None
306
+ incremental_state = self._set_input_buffer(incremental_state, saved_state)
307
+ assert k is not None
308
+ assert k.size(1) == src_len
309
+
310
+ # This is part of a workaround to get around fork/join parallelism
311
+ # not supporting Optional types.
312
+ if key_padding_mask is not None and key_padding_mask.dim() == 0:
313
+ key_padding_mask = None
314
+
315
+ if key_padding_mask is not None:
316
+ assert key_padding_mask.size(0) == bsz
317
+ assert key_padding_mask.size(1) == src_len
318
+
319
+ if self.add_zero_attn:
320
+ assert v is not None
321
+ src_len += 1
322
+ k = torch.cat([k, k.new_zeros((k.size(0), 1) + k.size()[2:])], dim=1)
323
+ v = torch.cat([v, v.new_zeros((v.size(0), 1) + v.size()[2:])], dim=1)
324
+ if attn_mask is not None:
325
+ attn_mask = torch.cat(
326
+ [attn_mask, attn_mask.new_zeros(attn_mask.size(0), 1)], dim=1
327
+ )
328
+ if key_padding_mask is not None:
329
+ key_padding_mask = torch.cat(
330
+ [
331
+ key_padding_mask,
332
+ torch.zeros(key_padding_mask.size(0), 1).type_as(
333
+ key_padding_mask
334
+ ),
335
+ ],
336
+ dim=1,
337
+ )
338
+
339
+ attn_weights = torch.bmm(q, k.transpose(1, 2))
340
+ attn_weights = self.apply_sparse_mask(attn_weights, tgt_len, src_len, bsz)
341
+
342
+ assert list(attn_weights.size()) == [bsz * self.num_heads, tgt_len, src_len]
343
+
344
+ if attn_bias is not None:
345
+ attn_weights += attn_bias
346
+
347
+ if attn_mask is not None:
348
+ attn_mask = attn_mask.unsqueeze(0)
349
+ if self.onnx_trace:
350
+ attn_mask = attn_mask.repeat(attn_weights.size(0), 1, 1)
351
+ attn_weights += attn_mask
352
+
353
+ if self_attn_mask is not None:
354
+ self_attn_mask = self_attn_mask.unsqueeze(1).expand(bsz, self.num_heads, tgt_len, src_len)
355
+ attn_weights += self_attn_mask.contiguous().view(bsz * self.num_heads, tgt_len, src_len)
356
+
357
+ if key_padding_mask is not None:
358
+ # don't attend to padding symbols
359
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
360
+ if not is_tpu:
361
+ attn_weights = attn_weights.masked_fill(
362
+ key_padding_mask.unsqueeze(1).unsqueeze(2).to(torch.bool),
363
+ float("-inf"),
364
+ )
365
+ else:
366
+ attn_weights = attn_weights.transpose(0, 2)
367
+ attn_weights = attn_weights.masked_fill(key_padding_mask, float("-inf"))
368
+ attn_weights = attn_weights.transpose(0, 2)
369
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
370
+
371
+ if before_softmax:
372
+ return attn_weights, v
373
+
374
+ attn_weights_float = utils.softmax(
375
+ attn_weights, dim=-1, onnx_trace=self.onnx_trace
376
+ )
377
+ attn_weights = attn_weights_float.type_as(attn_weights)
378
+ attn_probs = self.dropout_module(attn_weights)
379
+
380
+ assert v is not None
381
+ attn = torch.bmm(attn_probs, v)
382
+ assert list(attn.size()) == [bsz * self.num_heads, tgt_len, self.head_dim]
383
+ if self.onnx_trace and attn.size(1) == 1:
384
+ # when ONNX tracing a single decoder step (sequence length == 1)
385
+ # the transpose is a no-op copy before view, thus unnecessary
386
+ attn = attn.contiguous().view(tgt_len, bsz, embed_dim)
387
+ else:
388
+ attn = attn.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim)
389
+ if self.c_attn is not None:
390
+ attn = attn.view(tgt_len, bsz, self.num_heads, self.head_dim)
391
+ attn = torch.einsum('tbhd,h->tbhd', attn, self.c_attn)
392
+ attn = attn.reshape(tgt_len, bsz, self.embed_dim)
393
+ attn = self.out_proj(attn)
394
+ attn_weights: Optional[Tensor] = None
395
+ if need_weights:
396
+ attn_weights = attn_weights_float.view(
397
+ bsz, self.num_heads, tgt_len, src_len
398
+ ).transpose(1, 0)
399
+ if not need_head_weights:
400
+ # average attention weights over heads
401
+ attn_weights = attn_weights.mean(dim=0)
402
+
403
+ return attn, attn_weights
404
+
405
+ @staticmethod
406
+ def _append_prev_key_padding_mask(
407
+ key_padding_mask: Optional[Tensor],
408
+ prev_key_padding_mask: Optional[Tensor],
409
+ batch_size: int,
410
+ src_len: int,
411
+ static_kv: bool,
412
+ ) -> Optional[Tensor]:
413
+ # saved key padding masks have shape (bsz, seq_len)
414
+ if prev_key_padding_mask is not None and static_kv:
415
+ new_key_padding_mask = prev_key_padding_mask
416
+ elif prev_key_padding_mask is not None and key_padding_mask is not None:
417
+ new_key_padding_mask = torch.cat(
418
+ [prev_key_padding_mask.float(), key_padding_mask.float()], dim=1
419
+ )
420
+ # During incremental decoding, as the padding token enters and
421
+ # leaves the frame, there will be a time when prev or current
422
+ # is None
423
+ elif prev_key_padding_mask is not None:
424
+ if src_len > prev_key_padding_mask.size(1):
425
+ filler = torch.zeros(
426
+ (batch_size, src_len - prev_key_padding_mask.size(1)),
427
+ device=prev_key_padding_mask.device,
428
+ )
429
+ new_key_padding_mask = torch.cat(
430
+ [prev_key_padding_mask.float(), filler.float()], dim=1
431
+ )
432
+ else:
433
+ new_key_padding_mask = prev_key_padding_mask.float()
434
+ elif key_padding_mask is not None:
435
+ if src_len > key_padding_mask.size(1):
436
+ filler = torch.zeros(
437
+ (batch_size, src_len - key_padding_mask.size(1)),
438
+ device=key_padding_mask.device,
439
+ )
440
+ new_key_padding_mask = torch.cat(
441
+ [filler.float(), key_padding_mask.float()], dim=1
442
+ )
443
+ else:
444
+ new_key_padding_mask = key_padding_mask.float()
445
+ else:
446
+ new_key_padding_mask = prev_key_padding_mask
447
+ return new_key_padding_mask
448
+
449
+ @torch.jit.export
450
+ def reorder_incremental_state(
451
+ self,
452
+ incremental_state: Dict[str, Dict[str, Optional[Tensor]]],
453
+ new_order: Tensor,
454
+ ):
455
+ """Reorder buffered internal state (for incremental generation)."""
456
+ input_buffer = self._get_input_buffer(incremental_state)
457
+ if input_buffer is not None:
458
+ for k in input_buffer.keys():
459
+ input_buffer_k = input_buffer[k]
460
+ if input_buffer_k is not None:
461
+ if self.encoder_decoder_attention and input_buffer_k.size(
462
+ 0
463
+ ) == new_order.size(0):
464
+ break
465
+ input_buffer[k] = input_buffer_k.index_select(0, new_order)
466
+ incremental_state = self._set_input_buffer(incremental_state, input_buffer)
467
+ return incremental_state
468
+
469
+ def _get_input_buffer(
470
+ self, incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]]
471
+ ) -> Dict[str, Optional[Tensor]]:
472
+ result = self.get_incremental_state(incremental_state, "attn_state")
473
+ if result is not None:
474
+ return result
475
+ else:
476
+ empty_result: Dict[str, Optional[Tensor]] = {}
477
+ return empty_result
478
+
479
+ def _set_input_buffer(
480
+ self,
481
+ incremental_state: Dict[str, Dict[str, Optional[Tensor]]],
482
+ buffer: Dict[str, Optional[Tensor]],
483
+ ):
484
+ return self.set_incremental_state(incremental_state, "attn_state", buffer)
485
+
486
+ def apply_sparse_mask(self, attn_weights, tgt_len: int, src_len: int, bsz: int):
487
+ return attn_weights
488
+
489
+ def upgrade_state_dict_named(self, state_dict, name):
490
+ prefix = name + "." if name != "" else ""
491
+ items_to_add = {}
492
+ keys_to_remove = []
493
+ for k in state_dict.keys():
494
+ if k.endswith(prefix + "in_proj_weight"):
495
+ # in_proj_weight used to be q + k + v with same dimensions
496
+ dim = int(state_dict[k].shape[0] / 3)
497
+ items_to_add[prefix + "q_proj.weight"] = state_dict[k][:dim]
498
+ items_to_add[prefix + "k_proj.weight"] = state_dict[k][dim : 2 * dim]
499
+ items_to_add[prefix + "v_proj.weight"] = state_dict[k][2 * dim :]
500
+
501
+ keys_to_remove.append(k)
502
+
503
+ k_bias = prefix + "in_proj_bias"
504
+ if k_bias in state_dict.keys():
505
+ dim = int(state_dict[k].shape[0] / 3)
506
+ items_to_add[prefix + "q_proj.bias"] = state_dict[k_bias][:dim]
507
+ items_to_add[prefix + "k_proj.bias"] = state_dict[k_bias][
508
+ dim : 2 * dim
509
+ ]
510
+ items_to_add[prefix + "v_proj.bias"] = state_dict[k_bias][2 * dim :]
511
+
512
+ keys_to_remove.append(prefix + "in_proj_bias")
513
+
514
+ for k in keys_to_remove:
515
+ del state_dict[k]
516
+
517
+ for key, value in items_to_add.items():
518
+ state_dict[key] = value
models/ofa/unify_transformer.py ADDED
@@ -0,0 +1,1512 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The OFA-Sys Team.
2
+ # All rights reserved.
3
+ # This source code is licensed under the Apache 2.0 license
4
+ # found in the LICENSE file in the root directory.
5
+
6
+ import math
7
+ import random
8
+ from typing import Any, Dict, List, Optional, Tuple
9
+
10
+ import torch
11
+ import torch.nn as nn
12
+ import torch.nn.functional as F
13
+ from fairseq import utils
14
+ from fairseq.distributed import fsdp_wrap
15
+ from fairseq.models import (
16
+ FairseqEncoder,
17
+ FairseqEncoderDecoderModel,
18
+ FairseqIncrementalDecoder,
19
+ register_model,
20
+ register_model_architecture,
21
+ )
22
+ from fairseq.modules import (
23
+ AdaptiveSoftmax,
24
+ BaseLayer,
25
+ FairseqDropout,
26
+ LayerDropModuleList,
27
+ LayerNorm,
28
+ SinusoidalPositionalEmbedding,
29
+ GradMultiply
30
+ )
31
+ from fairseq.modules.checkpoint_activations import checkpoint_wrapper
32
+ from fairseq.modules.quant_noise import quant_noise as apply_quant_noise_
33
+ from torch import Tensor
34
+
35
+ from .unify_transformer_layer import TransformerEncoderLayer, TransformerDecoderLayer
36
+ from .resnet import ResNet
37
+
38
+
39
+ DEFAULT_MAX_SOURCE_POSITIONS = 1024
40
+ DEFAULT_MAX_TARGET_POSITIONS = 1024
41
+
42
+
43
+ DEFAULT_MIN_PARAMS_TO_WRAP = int(1e8)
44
+
45
+
46
+ def BatchNorm2d(out_chan, momentum=0.1, eps=1e-3):
47
+ return nn.SyncBatchNorm.convert_sync_batchnorm(
48
+ nn.BatchNorm2d(out_chan, momentum=momentum, eps=eps)
49
+ )
50
+
51
+
52
+ def make_token_bucket_position(bucket_size, max_position=DEFAULT_MAX_SOURCE_POSITIONS):
53
+ context_pos = torch.arange(max_position, dtype=torch.long)[:, None]
54
+ memory_pos = torch.arange(max_position, dtype=torch.long)[None, :]
55
+ relative_pos = context_pos - memory_pos
56
+ sign = torch.sign(relative_pos)
57
+ mid = bucket_size // 2
58
+ abs_pos = torch.where((relative_pos<mid) & (relative_pos > -mid), mid-1, torch.abs(relative_pos))
59
+ log_pos = torch.ceil(torch.log(abs_pos/mid)/math.log((max_position-1)/mid) * (mid-1)) + mid
60
+ log_pos = log_pos.int()
61
+ bucket_pos = torch.where(abs_pos.le(mid), relative_pos, log_pos*sign).long()
62
+ return bucket_pos + bucket_size - 1
63
+
64
+
65
+ def make_image_bucket_position(bucket_size, num_relative_distance):
66
+ coords_h = torch.arange(bucket_size)
67
+ coords_w = torch.arange(bucket_size)
68
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
69
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
70
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
71
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
72
+ relative_coords[:, :, 0] += bucket_size - 1 # shift to start from 0
73
+ relative_coords[:, :, 1] += bucket_size - 1
74
+ relative_coords[:, :, 0] *= 2 * bucket_size - 1
75
+ relative_position_index = torch.zeros(size=(bucket_size * bucket_size + 1,) * 2, dtype=relative_coords.dtype)
76
+ relative_position_index[1:, 1:] = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
77
+ relative_position_index[0, 0:] = num_relative_distance - 3
78
+ relative_position_index[0:, 0] = num_relative_distance - 2
79
+ relative_position_index[0, 0] = num_relative_distance - 1
80
+ return relative_position_index
81
+
82
+
83
+ @register_model("unify_transformer")
84
+ class TransformerModel(FairseqEncoderDecoderModel):
85
+ """
86
+ Transformer model from `"Attention Is All You Need" (Vaswani, et al, 2017)
87
+ <https://arxiv.org/abs/1706.03762>`_.
88
+
89
+ Args:
90
+ encoder (TransformerEncoder): the encoder
91
+ decoder (TransformerDecoder): the decoder
92
+
93
+ The Transformer model provides the following named architectures and
94
+ command-line arguments:
95
+
96
+ .. argparse::
97
+ :ref: fairseq.models.transformer_parser
98
+ :prog:
99
+ """
100
+
101
+ def __init__(self, args, encoder, decoder):
102
+ super().__init__(encoder, decoder)
103
+ self.args = args
104
+ self.supports_align_args = True
105
+
106
+ @staticmethod
107
+ def add_args(parser):
108
+ """Add model-specific arguments to the parser."""
109
+ # fmt: off
110
+ parser.add_argument('--activation-fn',
111
+ choices=utils.get_available_activation_fns(),
112
+ help='activation function to use')
113
+ parser.add_argument('--dropout', type=float, metavar='D',
114
+ help='dropout probability')
115
+ parser.add_argument('--attention-dropout', type=float, metavar='D',
116
+ help='dropout probability for attention weights')
117
+ parser.add_argument('--activation-dropout', '--relu-dropout', type=float, metavar='D',
118
+ help='dropout probability after activation in FFN.')
119
+ parser.add_argument('--encoder-embed-path', type=str, metavar='STR',
120
+ help='path to pre-trained encoder embedding')
121
+ parser.add_argument('--encoder-embed-dim', type=int, metavar='N',
122
+ help='encoder embedding dimension')
123
+ parser.add_argument('--encoder-ffn-embed-dim', type=int, metavar='N',
124
+ help='encoder embedding dimension for FFN')
125
+ parser.add_argument('--encoder-layers', type=int, metavar='N',
126
+ help='num encoder layers')
127
+ parser.add_argument('--encoder-attention-heads', type=int, metavar='N',
128
+ help='num encoder attention heads')
129
+ parser.add_argument('--encoder-normalize-before', action='store_true',
130
+ help='apply layernorm before each encoder block')
131
+ parser.add_argument('--encoder-learned-pos', action='store_true',
132
+ help='use learned positional embeddings in the encoder')
133
+ parser.add_argument('--decoder-embed-path', type=str, metavar='STR',
134
+ help='path to pre-trained decoder embedding')
135
+ parser.add_argument('--decoder-embed-dim', type=int, metavar='N',
136
+ help='decoder embedding dimension')
137
+ parser.add_argument('--decoder-ffn-embed-dim', type=int, metavar='N',
138
+ help='decoder embedding dimension for FFN')
139
+ parser.add_argument('--decoder-layers', type=int, metavar='N',
140
+ help='num decoder layers')
141
+ parser.add_argument('--decoder-attention-heads', type=int, metavar='N',
142
+ help='num decoder attention heads')
143
+ parser.add_argument('--decoder-learned-pos', action='store_true',
144
+ help='use learned positional embeddings in the decoder')
145
+ parser.add_argument('--decoder-normalize-before', action='store_true',
146
+ help='apply layernorm before each decoder block')
147
+ parser.add_argument('--decoder-output-dim', type=int, metavar='N',
148
+ help='decoder output dimension (extra linear layer '
149
+ 'if different from decoder embed dim')
150
+ parser.add_argument('--share-decoder-input-output-embed', action='store_true',
151
+ help='share decoder input and output embeddings')
152
+ parser.add_argument('--share-all-embeddings', action='store_true',
153
+ help='share encoder, decoder and output embeddings'
154
+ ' (requires shared dictionary and embed dim)')
155
+ parser.add_argument('--no-token-positional-embeddings', default=False, action='store_true',
156
+ help='if set, disables positional embeddings (outside self attention)')
157
+ parser.add_argument('--adaptive-softmax-cutoff', metavar='EXPR',
158
+ help='comma separated list of adaptive softmax cutoff points. '
159
+ 'Must be used with adaptive_loss criterion'),
160
+ parser.add_argument('--adaptive-softmax-dropout', type=float, metavar='D',
161
+ help='sets adaptive softmax dropout for the tail projections')
162
+ parser.add_argument('--layernorm-embedding', action='store_true',
163
+ help='add layernorm to embedding')
164
+ parser.add_argument('--no-scale-embedding', action='store_true',
165
+ help='if True, dont scale embeddings')
166
+ parser.add_argument('--checkpoint-activations', action='store_true',
167
+ help='checkpoint activations at each layer, which saves GPU '
168
+ 'memory usage at the cost of some additional compute')
169
+ parser.add_argument('--offload-activations', action='store_true',
170
+ help='checkpoint activations at each layer, then save to gpu. Sets --checkpoint-activations.')
171
+ # args for "Cross+Self-Attention for Transformer Models" (Peitz et al., 2019)
172
+ parser.add_argument('--no-cross-attention', default=False, action='store_true',
173
+ help='do not perform cross-attention')
174
+ parser.add_argument('--cross-self-attention', default=False, action='store_true',
175
+ help='perform cross+self-attention')
176
+ # args for "Reducing Transformer Depth on Demand with Structured Dropout" (Fan et al., 2019)
177
+ parser.add_argument('--encoder-layerdrop', type=float, metavar='D', default=0,
178
+ help='LayerDrop probability for encoder')
179
+ parser.add_argument('--decoder-layerdrop', type=float, metavar='D', default=0,
180
+ help='LayerDrop probability for decoder')
181
+ parser.add_argument('--encoder-layers-to-keep', default=None,
182
+ help='which layers to *keep* when pruning as a comma-separated list')
183
+ parser.add_argument('--decoder-layers-to-keep', default=None,
184
+ help='which layers to *keep* when pruning as a comma-separated list')
185
+ # args for Training with Quantization Noise for Extreme Model Compression ({Fan*, Stock*} et al., 2020)
186
+ parser.add_argument('--quant-noise-pq', type=float, metavar='D', default=0,
187
+ help='iterative PQ quantization noise at training time')
188
+ parser.add_argument('--quant-noise-pq-block-size', type=int, metavar='D', default=8,
189
+ help='block size of quantization noise at training time')
190
+ parser.add_argument('--quant-noise-scalar', type=float, metavar='D', default=0,
191
+ help='scalar quantization noise and scalar quantization at training time')
192
+ # args for Fully Sharded Data Parallel (FSDP) training
193
+ parser.add_argument(
194
+ '--min-params-to-wrap', type=int, metavar='D', default=DEFAULT_MIN_PARAMS_TO_WRAP,
195
+ help=(
196
+ 'minimum number of params for a layer to be wrapped with FSDP() when '
197
+ 'training with --ddp-backend=fully_sharded. Smaller values will '
198
+ 'improve memory efficiency, but may make torch.distributed '
199
+ 'communication less efficient due to smaller input sizes. This option '
200
+ 'is set to 0 (i.e., always wrap) when --checkpoint-activations or '
201
+ '--offload-activations are passed.'
202
+ )
203
+ )
204
+
205
+ parser.add_argument('--resnet-drop-path-rate', type=float,
206
+ help='resnet drop path rate')
207
+ parser.add_argument('--encoder-drop-path-rate', type=float,
208
+ help='encoder drop path rate')
209
+ parser.add_argument('--decoder-drop-path-rate', type=float,
210
+ help='encoder drop path rate')
211
+
212
+ parser.add_argument('--token-bucket-size', type=int,
213
+ help='token bucket size')
214
+ parser.add_argument('--image-bucket-size', type=int,
215
+ help='image bucket size')
216
+
217
+ parser.add_argument('--attn-scale-factor', type=float,
218
+ help='attention scale factor')
219
+ parser.add_argument('--freeze-resnet', action='store_true',
220
+ help='freeze resnet')
221
+ parser.add_argument('--freeze-encoder-embedding', action='store_true',
222
+ help='freeze encoder token embedding')
223
+ parser.add_argument('--freeze-decoder-embedding', action='store_true',
224
+ help='freeze decoder token embedding')
225
+ parser.add_argument('--add-type-embedding', action='store_true',
226
+ help='add source/region/patch type embedding')
227
+
228
+ parser.add_argument('--resnet-type', choices=['resnet50', 'resnet101', 'resnet152'],
229
+ help='resnet type')
230
+ parser.add_argument('--resnet-model-path', type=str, metavar='STR',
231
+ help='path to load resnet')
232
+ parser.add_argument('--code-image-size', type=int,
233
+ help='code image size')
234
+ parser.add_argument('--patch-layernorm-embedding', action='store_true',
235
+ help='add layernorm to patch embedding')
236
+ parser.add_argument('--code-layernorm-embedding', action='store_true',
237
+ help='add layernorm to code embedding')
238
+ parser.add_argument('--entangle-position-embedding', action='store_true',
239
+ help='entangle position embedding')
240
+ parser.add_argument('--disable-entangle', action='store_true',
241
+ help='disable entangle')
242
+ parser.add_argument('--sync-bn', action='store_true',
243
+ help='sync batchnorm')
244
+
245
+ parser.add_argument('--scale-attn', action='store_true',
246
+ help='scale attn')
247
+ parser.add_argument('--scale-fc', action='store_true',
248
+ help='scale fc')
249
+ parser.add_argument('--scale-heads', action='store_true',
250
+ help='scale heads')
251
+ parser.add_argument('--scale-resids', action='store_true',
252
+ help='scale resids')
253
+ # fmt: on
254
+
255
+ @classmethod
256
+ def build_model(cls, args, task):
257
+ """Build a new model instance."""
258
+
259
+ # make sure all arguments are present in older models
260
+ base_architecture(args)
261
+
262
+ if args.encoder_layers_to_keep:
263
+ args.encoder_layers = len(args.encoder_layers_to_keep.split(","))
264
+ if args.decoder_layers_to_keep:
265
+ args.decoder_layers = len(args.decoder_layers_to_keep.split(","))
266
+
267
+ if getattr(args, "max_source_positions", None) is None:
268
+ args.max_source_positions = DEFAULT_MAX_SOURCE_POSITIONS
269
+ if getattr(args, "max_target_positions", None) is None:
270
+ args.max_target_positions = DEFAULT_MAX_TARGET_POSITIONS
271
+
272
+ src_dict, tgt_dict = task.source_dictionary, task.target_dictionary
273
+
274
+ if args.share_all_embeddings:
275
+ if src_dict != tgt_dict:
276
+ raise ValueError("--share-all-embeddings requires a joined dictionary")
277
+ if args.encoder_embed_dim != args.decoder_embed_dim:
278
+ raise ValueError(
279
+ "--share-all-embeddings requires --encoder-embed-dim to match --decoder-embed-dim"
280
+ )
281
+ if args.decoder_embed_path and (
282
+ args.decoder_embed_path != args.encoder_embed_path
283
+ ):
284
+ raise ValueError(
285
+ "--share-all-embeddings not compatible with --decoder-embed-path"
286
+ )
287
+ encoder_embed_tokens = cls.build_embedding(
288
+ args, src_dict, args.encoder_embed_dim, args.encoder_embed_path
289
+ )
290
+ decoder_embed_tokens = encoder_embed_tokens
291
+ args.share_decoder_input_output_embed = True
292
+ else:
293
+ encoder_embed_tokens = cls.build_embedding(
294
+ args, src_dict, args.encoder_embed_dim, args.encoder_embed_path
295
+ )
296
+ decoder_embed_tokens = cls.build_embedding(
297
+ args, tgt_dict, args.decoder_embed_dim, args.decoder_embed_path
298
+ )
299
+ if getattr(args, "freeze_encoder_embedding", False):
300
+ encoder_embed_tokens.weight.requires_grad = False
301
+ if getattr(args, "freeze_decoder_embedding", False):
302
+ decoder_embed_tokens.weight.requires_grad = False
303
+ if getattr(args, "offload_activations", False):
304
+ args.checkpoint_activations = True # offloading implies checkpointing
305
+ encoder = cls.build_encoder(args, src_dict, encoder_embed_tokens)
306
+ decoder = cls.build_decoder(args, tgt_dict, decoder_embed_tokens)
307
+ if not args.share_all_embeddings:
308
+ min_params_to_wrap = getattr(
309
+ args, "min_params_to_wrap", DEFAULT_MIN_PARAMS_TO_WRAP
310
+ )
311
+ # fsdp_wrap is a no-op when --ddp-backend != fully_sharded
312
+ encoder = fsdp_wrap(encoder, min_num_params=min_params_to_wrap)
313
+ decoder = fsdp_wrap(decoder, min_num_params=min_params_to_wrap)
314
+ return cls(args, encoder, decoder)
315
+
316
+ @classmethod
317
+ def build_embedding(cls, args, dictionary, embed_dim, path=None):
318
+ num_embeddings = len(dictionary)
319
+ padding_idx = dictionary.pad()
320
+
321
+ emb = Embedding(num_embeddings, embed_dim, padding_idx)
322
+ # if provided, load from preloaded dictionaries
323
+ if path:
324
+ embed_dict = utils.parse_embedding(path)
325
+ utils.load_embedding(embed_dict, dictionary, emb)
326
+ return emb
327
+
328
+ @classmethod
329
+ def build_encoder(cls, args, src_dict, embed_tokens):
330
+ return TransformerEncoder(args, src_dict, embed_tokens)
331
+
332
+ @classmethod
333
+ def build_decoder(cls, args, tgt_dict, embed_tokens):
334
+ return TransformerDecoder(
335
+ args,
336
+ tgt_dict,
337
+ embed_tokens,
338
+ no_encoder_attn=getattr(args, "no_cross_attention", False),
339
+ )
340
+
341
+ # TorchScript doesn't support optional arguments with variable length (**kwargs).
342
+ # Current workaround is to add union of all arguments in child classes.
343
+ def forward(
344
+ self,
345
+ src_tokens,
346
+ src_lengths,
347
+ prev_output_tokens,
348
+ return_all_hiddens: bool = True,
349
+ features_only: bool = False,
350
+ alignment_layer: Optional[int] = None,
351
+ alignment_heads: Optional[int] = None,
352
+ ):
353
+ """
354
+ Run the forward pass for an encoder-decoder model.
355
+
356
+ Copied from the base class, but without ``**kwargs``,
357
+ which are not supported by TorchScript.
358
+ """
359
+ encoder_out = self.encoder(
360
+ src_tokens, src_lengths=src_lengths, return_all_hiddens=return_all_hiddens
361
+ )
362
+ decoder_out = self.decoder(
363
+ prev_output_tokens,
364
+ encoder_out=encoder_out,
365
+ features_only=features_only,
366
+ alignment_layer=alignment_layer,
367
+ alignment_heads=alignment_heads,
368
+ src_lengths=src_lengths,
369
+ return_all_hiddens=return_all_hiddens,
370
+ )
371
+ return decoder_out
372
+
373
+ # Since get_normalized_probs is in the Fairseq Model which is not scriptable,
374
+ # I rewrite the get_normalized_probs from Base Class to call the
375
+ # helper function in the Base Class.
376
+ @torch.jit.export
377
+ def get_normalized_probs(
378
+ self,
379
+ net_output: Tuple[Tensor, Optional[Dict[str, List[Optional[Tensor]]]]],
380
+ log_probs: bool,
381
+ sample: Optional[Dict[str, Tensor]] = None,
382
+ ):
383
+ """Get normalized probabilities (or log probs) from a net's output."""
384
+ return self.get_normalized_probs_scriptable(net_output, log_probs, sample)
385
+
386
+
387
+ class TransformerEncoder(FairseqEncoder):
388
+ """
389
+ Transformer encoder consisting of *args.encoder_layers* layers. Each layer
390
+ is a :class:`TransformerEncoderLayer`.
391
+
392
+ Args:
393
+ args (argparse.Namespace): parsed command-line arguments
394
+ dictionary (~fairseq.data.Dictionary): encoding dictionary
395
+ embed_tokens (torch.nn.Embedding): input embedding
396
+ """
397
+
398
+ def __init__(self, args, dictionary, embed_tokens):
399
+ self.args = args
400
+ super().__init__(dictionary)
401
+ self.register_buffer("version", torch.Tensor([3]))
402
+
403
+ self.dropout_module = FairseqDropout(
404
+ args.dropout, module_name=self.__class__.__name__
405
+ )
406
+ self.encoder_layerdrop = args.encoder_layerdrop
407
+
408
+ embed_dim = embed_tokens.embedding_dim
409
+ self.padding_idx = embed_tokens.padding_idx
410
+ self.max_source_positions = args.max_source_positions
411
+ self.num_attention_heads = args.encoder_attention_heads
412
+
413
+ self.embed_tokens = embed_tokens
414
+
415
+ self.embed_scale = 1.0 if args.no_scale_embedding else math.sqrt(embed_dim)
416
+
417
+ if getattr(args, "layernorm_embedding", False):
418
+ self.layernorm_embedding = LayerNorm(embed_dim)
419
+ else:
420
+ self.layernorm_embedding = None
421
+
422
+ if getattr(args, "add_type_embedding", False):
423
+ self.type_embedding = Embedding(2, embed_dim, padding_idx=None)
424
+ else:
425
+ self.type_embedding = None
426
+
427
+ if getattr(args, "sync_bn", False):
428
+ norm_layer = BatchNorm2d
429
+ else:
430
+ norm_layer = None
431
+
432
+ if args.resnet_type == 'resnet101':
433
+ self.embed_images = ResNet([3, 4, 23], norm_layer=norm_layer, drop_path_rate=args.resnet_drop_path_rate)
434
+ elif args.resnet_type == 'resnet152':
435
+ self.embed_images = ResNet([3, 8, 36], norm_layer=norm_layer, drop_path_rate=args.resnet_drop_path_rate)
436
+ elif args.resnet_type == 'resnet50':
437
+ self.embed_images = ResNet([3, 4, 6], norm_layer=norm_layer, drop_path_rate=args.resnet_drop_path_rate)
438
+ else:
439
+ raise NotImplementedError
440
+ self.image_proj = Linear(1024, embed_dim)
441
+ if getattr(args, "resnet_model_path", None):
442
+ print("load resnet {}".format(args.resnet_model_path))
443
+ resnet_state_dict = torch.load(self.args.resnet_model_path)
444
+ self.embed_images.load_state_dict(resnet_state_dict)
445
+ if getattr(args, "patch_layernorm_embedding", False):
446
+ self.patch_layernorm_embedding = LayerNorm(embed_dim)
447
+ else:
448
+ self.patch_layernorm_embedding = None
449
+
450
+ self.embed_positions = Embedding(args.max_source_positions + 2, embed_dim)
451
+ self.embed_image_positions = Embedding(args.image_bucket_size ** 2 + 1, embed_dim)
452
+ self.pos_ln = LayerNorm(embed_dim)
453
+ self.image_pos_ln = LayerNorm(embed_dim)
454
+ self.pos_scaling = float(embed_dim / args.encoder_attention_heads * args.attn_scale_factor) ** -0.5
455
+ self.pos_q_linear = nn.Linear(embed_dim, embed_dim)
456
+ self.pos_k_linear = nn.Linear(embed_dim, embed_dim)
457
+
458
+ if not args.adaptive_input and args.quant_noise_pq > 0:
459
+ self.quant_noise = apply_quant_noise_(
460
+ nn.Linear(embed_dim, embed_dim, bias=False),
461
+ args.quant_noise_pq,
462
+ args.quant_noise_pq_block_size,
463
+ )
464
+ else:
465
+ self.quant_noise = None
466
+
467
+ if self.encoder_layerdrop > 0.0:
468
+ self.layers = LayerDropModuleList(p=self.encoder_layerdrop)
469
+ else:
470
+ self.layers = nn.ModuleList([])
471
+
472
+ dpr = [x.item() for x in torch.linspace(0, args.encoder_drop_path_rate, args.encoder_layers)]
473
+ self.layers.extend(
474
+ [self.build_encoder_layer(args, drop_path_rate=dpr[i]) for i in range(args.encoder_layers)]
475
+ )
476
+ self.num_layers = len(self.layers)
477
+
478
+ if args.encoder_normalize_before:
479
+ self.layer_norm = LayerNorm(embed_dim)
480
+ else:
481
+ self.layer_norm = None
482
+
483
+ token_bucket_size = args.token_bucket_size
484
+ token_num_rel_dis = 2 * token_bucket_size - 1
485
+ token_rp_bucket = make_token_bucket_position(token_bucket_size)
486
+ self.token_rel_pos_table_list = nn.ModuleList(
487
+ [Embedding(token_num_rel_dis, self.num_attention_heads, zero_init=True) for _ in range(args.encoder_layers)]
488
+ )
489
+
490
+ image_bucket_size = args.image_bucket_size
491
+ image_num_rel_dis = (2 * image_bucket_size - 1) * (2 * image_bucket_size - 1) + 3
492
+ image_rp_bucket = make_image_bucket_position(image_bucket_size, image_num_rel_dis)
493
+ self.image_rel_pos_table_list = nn.ModuleList(
494
+ [Embedding(image_num_rel_dis, self.num_attention_heads, zero_init=True) for _ in range(args.encoder_layers)]
495
+ )
496
+
497
+ self.register_buffer("token_rp_bucket", token_rp_bucket)
498
+ self.register_buffer("image_rp_bucket", image_rp_bucket)
499
+ self.entangle_position_embedding = args.entangle_position_embedding
500
+
501
+ def train(self, mode=True):
502
+ super(TransformerEncoder, self).train(mode)
503
+ if getattr(self.args, "freeze_resnet", False):
504
+ for m in self.embed_images.modules():
505
+ if isinstance(m, nn.BatchNorm2d):
506
+ m.eval()
507
+ m.weight.requires_grad = False
508
+ m.bias.requires_grad = False
509
+
510
+ def build_encoder_layer(self, args, drop_path_rate=0.0):
511
+ layer = TransformerEncoderLayer(args, drop_path_rate=drop_path_rate)
512
+ checkpoint = getattr(args, "checkpoint_activations", False)
513
+ if checkpoint:
514
+ offload_to_cpu = getattr(args, "offload_activations", False)
515
+ layer = checkpoint_wrapper(layer, offload_to_cpu=offload_to_cpu)
516
+ # if we are checkpointing, enforce that FSDP always wraps the
517
+ # checkpointed layer, regardless of layer size
518
+ min_params_to_wrap = (
519
+ getattr(args, "min_params_to_wrap", DEFAULT_MIN_PARAMS_TO_WRAP)
520
+ if not checkpoint else 0
521
+ )
522
+ layer = fsdp_wrap(layer, min_num_params=min_params_to_wrap)
523
+ return layer
524
+
525
+ def get_rel_pos_bias(self, x, idx):
526
+ seq_len = x.size(1)
527
+ rp_bucket = self.token_rp_bucket[:seq_len, :seq_len]
528
+ values = F.embedding(rp_bucket, self.token_rel_pos_table_list[idx].weight)
529
+ values = values.unsqueeze(0).expand(x.size(0), -1, -1, -1)
530
+ values = values.permute([0, 3, 1, 2])
531
+ return values.contiguous()
532
+
533
+ def get_image_rel_pos_bias(self, image_position_ids, idx):
534
+ bsz, seq_len = image_position_ids.shape
535
+ rp_bucket_size = self.image_rp_bucket.size(1)
536
+
537
+ rp_bucket = self.image_rp_bucket.unsqueeze(0).expand(
538
+ bsz, rp_bucket_size, rp_bucket_size
539
+ ).gather(1, image_position_ids[:, :, None].expand(bsz, seq_len, rp_bucket_size)
540
+ ).gather(2, image_position_ids[:, None, :].expand(bsz, seq_len, seq_len))
541
+ values = F.embedding(rp_bucket, self.image_rel_pos_table_list[idx].weight)
542
+ values = values.permute(0, 3, 1, 2)
543
+ return values
544
+
545
+ def get_patch_images_info(self, patch_images, sample_patch_num, device):
546
+ image_embed = self.embed_images(patch_images)
547
+ h, w = image_embed.shape[-2:]
548
+ image_num_patches = h * w
549
+ image_padding_mask = patch_images.new_zeros((patch_images.size(0), image_num_patches)).bool()
550
+ image_position_idx = torch.arange(w).unsqueeze(0).expand(h, w) + \
551
+ torch.arange(h).unsqueeze(1) * self.args.image_bucket_size + 1
552
+ image_position_idx = image_position_idx.view(-1).to(device)
553
+ image_position_ids = image_position_idx[None, :].expand(patch_images.size(0), image_num_patches)
554
+
555
+ image_embed = image_embed.flatten(2).transpose(1, 2)
556
+ if sample_patch_num is not None:
557
+ patch_orders = [
558
+ random.sample(range(image_num_patches), k=sample_patch_num)
559
+ for _ in range(patch_images.size(0))
560
+ ]
561
+ patch_orders = torch.LongTensor(patch_orders).to(device)
562
+ image_embed = image_embed.gather(
563
+ 1, patch_orders.unsqueeze(2).expand(-1, -1, image_embed.size(2))
564
+ )
565
+ image_num_patches = sample_patch_num
566
+ image_padding_mask = image_padding_mask.gather(1, patch_orders)
567
+ image_position_ids = image_position_ids.gather(1, patch_orders)
568
+ image_pos_embed = self.embed_image_positions(image_position_ids)
569
+
570
+ return image_embed, image_num_patches, image_padding_mask, image_position_ids, image_pos_embed
571
+
572
+ def forward_embedding(
573
+ self,
574
+ src_tokens,
575
+ image_embed: Optional[torch.Tensor] = None,
576
+ image_embed_2: Optional[torch.Tensor] = None,
577
+ token_embedding: Optional[torch.Tensor] = None,
578
+ pos_embed: Optional[torch.Tensor] = None,
579
+ image_pos_embed: Optional[torch.Tensor] = None,
580
+ image_pos_embed_2: Optional[torch.Tensor] = None
581
+ ):
582
+ # embed tokens and positions
583
+ if token_embedding is None:
584
+ token_embedding = self.embed_tokens(src_tokens)
585
+ x = embed = self.embed_scale * token_embedding
586
+ if self.entangle_position_embedding and pos_embed is not None:
587
+ x += pos_embed
588
+ if self.type_embedding is not None:
589
+ x += self.type_embedding(src_tokens.new_zeros(x.size()[:2]))
590
+ if self.layernorm_embedding is not None:
591
+ x = self.layernorm_embedding(x)
592
+ x = self.dropout_module(x)
593
+ if self.quant_noise is not None:
594
+ x = self.quant_noise(x)
595
+
596
+ # embed raw images
597
+ if image_embed is not None:
598
+ image_embed = self.image_proj(image_embed)
599
+ image_x = image_embed = self.embed_scale * image_embed
600
+ if self.entangle_position_embedding and image_pos_embed is not None:
601
+ image_x += image_pos_embed
602
+ if self.type_embedding is not None:
603
+ image_x += self.type_embedding(src_tokens.new_ones(image_x.size()[:2]))
604
+ if self.patch_layernorm_embedding is not None:
605
+ image_x = self.patch_layernorm_embedding(image_x)
606
+ image_x = self.dropout_module(image_x)
607
+ if self.quant_noise is not None:
608
+ image_x = self.quant_noise(image_x)
609
+ x = torch.cat([image_x, x], dim=1)
610
+ embed = torch.cat([image_embed, embed], dim=1)
611
+
612
+ if image_embed_2 is not None:
613
+ assert self.type_embedding is not None
614
+ image_embed_2 = self.image_proj(image_embed_2)
615
+ image_x_2 = image_embed_2 = self.embed_scale * image_embed_2
616
+ if self.entangle_position_embedding and image_pos_embed_2 is not None:
617
+ image_x_2 += image_pos_embed_2
618
+ if self.type_embedding is not None:
619
+ image_x_2 += self.type_embedding(src_tokens.new_full(image_x_2.size()[:2], fill_value=2))
620
+ if self.patch_layernorm_embedding is not None:
621
+ image_x_2 = self.patch_layernorm_embedding(image_x_2)
622
+ image_x_2 = self.dropout_module(image_x_2)
623
+ if self.quant_noise is not None:
624
+ image_x_2 = self.quant_noise(image_x_2)
625
+ x = torch.cat([image_x_2, x], dim=1)
626
+ embed = torch.cat([image_embed_2, embed], dim=1)
627
+
628
+ return x, embed
629
+
630
+ def forward(
631
+ self,
632
+ src_tokens,
633
+ src_lengths,
634
+ patch_images: Optional[torch.Tensor] = None,
635
+ patch_images_2: Optional[torch.Tensor] = None,
636
+ patch_masks: Optional[torch.Tensor] = None,
637
+ code_masks: Optional[torch.Tensor] = None,
638
+ return_all_hiddens: bool = False,
639
+ token_embeddings: Optional[torch.Tensor] = None,
640
+ sample_patch_num: Optional[int] = None
641
+ ):
642
+ """
643
+ Args:
644
+ src_tokens (LongTensor): tokens in the source language of shape
645
+ `(batch, src_len)`
646
+ src_lengths (torch.LongTensor): lengths of each source sentence of
647
+ shape `(batch)`
648
+ return_all_hiddens (bool, optional): also return all of the
649
+ intermediate hidden states (default: False).
650
+ token_embeddings (torch.Tensor, optional): precomputed embeddings
651
+ default `None` will recompute embeddings
652
+
653
+ Returns:
654
+ dict:
655
+ - **encoder_out** (Tensor): the last encoder layer's output of
656
+ shape `(src_len, batch, embed_dim)`
657
+ - **encoder_padding_mask** (ByteTensor): the positions of
658
+ padding elements of shape `(batch, src_len)`
659
+ - **encoder_embedding** (Tensor): the (scaled) embedding lookup
660
+ of shape `(batch, src_len, embed_dim)`
661
+ - **encoder_states** (List[Tensor]): all intermediate
662
+ hidden states of shape `(src_len, batch, embed_dim)`.
663
+ Only populated if *return_all_hiddens* is True.
664
+ """
665
+ return self.forward_scriptable(src_tokens,
666
+ src_lengths,
667
+ patch_images,
668
+ patch_images_2,
669
+ patch_masks,
670
+ return_all_hiddens,
671
+ token_embeddings,
672
+ sample_patch_num)
673
+
674
+ # TorchScript doesn't support super() method so that the scriptable Subclass
675
+ # can't access the base class model in Torchscript.
676
+ # Current workaround is to add a helper function with different name and
677
+ # call the helper function from scriptable Subclass.
678
+ def forward_scriptable(
679
+ self,
680
+ src_tokens,
681
+ src_lengths,
682
+ patch_images: Optional[torch.Tensor] = None,
683
+ patch_images_2: Optional[torch.Tensor] = None,
684
+ patch_masks: Optional[torch.Tensor] = None,
685
+ return_all_hiddens: bool = False,
686
+ token_embeddings: Optional[torch.Tensor] = None,
687
+ sample_patch_num: Optional[int] = None
688
+ ):
689
+ """
690
+ Args:
691
+ src_tokens (LongTensor): tokens in the source language of shape
692
+ `(batch, src_len)`
693
+ src_lengths (torch.LongTensor): lengths of each source sentence of
694
+ shape `(batch)`
695
+ return_all_hiddens (bool, optional): also return all of the
696
+ intermediate hidden states (default: False).
697
+ token_embeddings (torch.Tensor, optional): precomputed embeddings
698
+ default `None` will recompute embeddings
699
+
700
+ Returns:
701
+ dict:
702
+ - **encoder_out** (Tensor): the last encoder layer's output of
703
+ shape `(src_len, batch, embed_dim)`
704
+ - **encoder_padding_mask** (ByteTensor): the positions of
705
+ padding elements of shape `(batch, src_len)`
706
+ - **encoder_embedding** (Tensor): the (scaled) embedding lookup
707
+ of shape `(batch, src_len, embed_dim)`
708
+ - **encoder_states** (List[Tensor]): all intermediate
709
+ hidden states of shape `(src_len, batch, embed_dim)`.
710
+ Only populated if *return_all_hiddens* is True.
711
+ """
712
+ image_embed = None
713
+ image_embed_2 = None
714
+ image_pos_embed = None
715
+ image_pos_embed_2 = None
716
+ if patch_images is not None:
717
+ image_embed, image_num_patches, image_padding_mask, image_position_ids, image_pos_embed = \
718
+ self.get_patch_images_info(patch_images, sample_patch_num, src_tokens.device)
719
+ image_padding_mask[~patch_masks] = True
720
+ if patch_images_2 is not None:
721
+ image_embed_2, image_num_patches_2, image_padding_mask_2, image_position_ids_2, image_pos_embed_2 = \
722
+ self.get_patch_images_info(patch_images_2, sample_patch_num, src_tokens.device)
723
+ image_padding_mask_2[~patch_masks] = True
724
+
725
+ encoder_padding_mask = src_tokens.eq(self.padding_idx)
726
+ if patch_images is not None:
727
+ encoder_padding_mask = torch.cat([image_padding_mask, encoder_padding_mask], dim=1)
728
+ if patch_images_2 is not None:
729
+ encoder_padding_mask = torch.cat([image_padding_mask_2, encoder_padding_mask], dim=1)
730
+ has_pads = (src_tokens.device.type == "xla" or encoder_padding_mask.any())
731
+
732
+ pos_embed = self.embed_positions(utils.new_arange(src_tokens))
733
+ x, encoder_embedding = self.forward_embedding(
734
+ src_tokens, image_embed, image_embed_2, token_embeddings,
735
+ pos_embed, image_pos_embed, image_pos_embed_2
736
+ )
737
+
738
+ # account for padding while computing the representation
739
+ if has_pads:
740
+ x = x * (1 - encoder_padding_mask.unsqueeze(-1).type_as(x))
741
+
742
+ # B x T x C -> T x B x C
743
+ x = x.transpose(0, 1)
744
+
745
+ pos_embed = self.pos_ln(pos_embed)
746
+ if patch_images is not None:
747
+ image_pos_embed = self.image_pos_ln(image_pos_embed)
748
+ pos_embed = torch.cat([image_pos_embed, pos_embed], dim=1)
749
+ if patch_images_2 is not None:
750
+ image_pos_embed_2 = self.image_pos_ln(image_pos_embed_2)
751
+ pos_embed = torch.cat([image_pos_embed_2, pos_embed], dim=1)
752
+
753
+ pos_q = self.pos_q_linear(pos_embed).view(
754
+ x.size(1), x.size(0), self.num_attention_heads, -1
755
+ ).transpose(1, 2) * self.pos_scaling
756
+ pos_k = self.pos_k_linear(pos_embed).view(
757
+ x.size(1), x.size(0), self.num_attention_heads, -1
758
+ ).transpose(1, 2)
759
+ abs_pos_bias = torch.matmul(pos_q, pos_k.transpose(2, 3))
760
+
761
+ encoder_states = []
762
+
763
+ if return_all_hiddens:
764
+ encoder_states.append(x)
765
+
766
+ # encoder layers
767
+ for idx, layer in enumerate(self.layers):
768
+ self_attn_bias = abs_pos_bias.clone()
769
+ self_attn_bias[:, :, -src_tokens.size(1):, -src_tokens.size(1):] += self.get_rel_pos_bias(src_tokens, idx)
770
+ if patch_images_2 is not None:
771
+ self_attn_bias[:, :, :image_num_patches_2, :image_num_patches_2] += \
772
+ self.get_image_rel_pos_bias(image_position_ids_2, idx)
773
+ self_attn_bias[:, :, image_num_patches_2:image_num_patches_2+image_num_patches, image_num_patches_2:image_num_patches_2+image_num_patches] += \
774
+ self.get_image_rel_pos_bias(image_position_ids, idx)
775
+ elif patch_images is not None:
776
+ self_attn_bias[:, :, :x.size(0) - src_tokens.size(1), :x.size(0) - src_tokens.size(1)] += \
777
+ self.get_image_rel_pos_bias(image_position_ids, idx)
778
+ self_attn_bias = self_attn_bias.reshape(-1, x.size(0), x.size(0))
779
+
780
+ x = layer(
781
+ x, encoder_padding_mask=encoder_padding_mask if has_pads else None, self_attn_bias=self_attn_bias
782
+ )
783
+ if return_all_hiddens:
784
+ assert encoder_states is not None
785
+ encoder_states.append(x)
786
+
787
+ if self.layer_norm is not None:
788
+ x = self.layer_norm(x)
789
+
790
+ # The Pytorch Mobile lite interpreter does not supports returning NamedTuple in
791
+ # `forward` so we use a dictionary instead.
792
+ # TorchScript does not support mixed values so the values are all lists.
793
+ # The empty list is equivalent to None.
794
+ return {
795
+ "encoder_out": [x], # T x B x C
796
+ "encoder_padding_mask": [encoder_padding_mask], # B x T
797
+ "encoder_embedding": [], # B x T x C
798
+ "encoder_states": encoder_states, # List[T x B x C]
799
+ "src_tokens": [],
800
+ "src_lengths": [],
801
+ "position_embeddings": [pos_embed], # B x T x C
802
+ }
803
+
804
+ @torch.jit.export
805
+ def reorder_encoder_out(self, encoder_out: Dict[str, List[Tensor]], new_order):
806
+ """
807
+ Reorder encoder output according to *new_order*.
808
+
809
+ Args:
810
+ encoder_out: output from the ``forward()`` method
811
+ new_order (LongTensor): desired order
812
+
813
+ Returns:
814
+ *encoder_out* rearranged according to *new_order*
815
+ """
816
+ if len(encoder_out["encoder_out"]) == 0:
817
+ new_encoder_out = []
818
+ else:
819
+ new_encoder_out = [encoder_out["encoder_out"][0].index_select(1, new_order)]
820
+ if len(encoder_out["encoder_padding_mask"]) == 0:
821
+ new_encoder_padding_mask = []
822
+ else:
823
+ new_encoder_padding_mask = [
824
+ encoder_out["encoder_padding_mask"][0].index_select(0, new_order)
825
+ ]
826
+ if len(encoder_out["encoder_embedding"]) == 0:
827
+ new_encoder_embedding = []
828
+ else:
829
+ new_encoder_embedding = [
830
+ encoder_out["encoder_embedding"][0].index_select(0, new_order)
831
+ ]
832
+
833
+ if len(encoder_out["src_tokens"]) == 0:
834
+ new_src_tokens = []
835
+ else:
836
+ new_src_tokens = [(encoder_out["src_tokens"][0]).index_select(0, new_order)]
837
+
838
+ if len(encoder_out["src_lengths"]) == 0:
839
+ new_src_lengths = []
840
+ else:
841
+ new_src_lengths = [(encoder_out["src_lengths"][0]).index_select(0, new_order)]
842
+
843
+ if len(encoder_out["position_embeddings"]) == 0:
844
+ new_position_embeddings = []
845
+ else:
846
+ new_position_embeddings = [(encoder_out["position_embeddings"][0]).index_select(0, new_order)]
847
+
848
+ encoder_states = encoder_out["encoder_states"]
849
+ if len(encoder_states) > 0:
850
+ for idx, state in enumerate(encoder_states):
851
+ encoder_states[idx] = state.index_select(1, new_order)
852
+
853
+ return {
854
+ "encoder_out": new_encoder_out, # T x B x C
855
+ "encoder_padding_mask": new_encoder_padding_mask, # B x T
856
+ "encoder_embedding": new_encoder_embedding, # B x T x C
857
+ "encoder_states": encoder_states, # List[T x B x C]
858
+ "src_tokens": new_src_tokens, # B x T
859
+ "src_lengths": new_src_lengths, # B x 1
860
+ "position_embeddings": new_position_embeddings, # B x T x C
861
+ }
862
+
863
+ def max_positions(self):
864
+ """Maximum input length supported by the encoder."""
865
+ if self.embed_positions is None:
866
+ return self.max_source_positions
867
+ return self.max_source_positions
868
+
869
+ def upgrade_state_dict_named(self, state_dict, name):
870
+ """Upgrade a (possibly old) state dict for new versions of fairseq."""
871
+ if isinstance(self.embed_positions, SinusoidalPositionalEmbedding):
872
+ weights_key = "{}.embed_positions.weights".format(name)
873
+ if weights_key in state_dict:
874
+ print("deleting {0}".format(weights_key))
875
+ del state_dict[weights_key]
876
+ state_dict[
877
+ "{}.embed_positions._float_tensor".format(name)
878
+ ] = torch.FloatTensor(1)
879
+ for i in range(self.num_layers):
880
+ # update layer norms
881
+ self.layers[i].upgrade_state_dict_named(
882
+ state_dict, "{}.layers.{}".format(name, i)
883
+ )
884
+
885
+ # version_key = "{}.version".format(name)
886
+ # if utils.item(state_dict.get(version_key, torch.Tensor([1]))[0]) < 2:
887
+ # # earlier checkpoints did not normalize after the stack of layers
888
+ # self.layer_norm = None
889
+ # self.normalize = False
890
+ # state_dict[version_key] = torch.Tensor([1])
891
+
892
+ prefix = name + "." if name != "" else ""
893
+ for param_name, param_tensor in self.state_dict().items():
894
+ if (prefix + param_name) not in state_dict:
895
+ state_dict[prefix + param_name] = self.state_dict()[param_name]
896
+
897
+ if len(state_dict["encoder.embed_image_positions.weight"]) < len(self.state_dict()["embed_image_positions.weight"]):
898
+ num_posids_to_add = len(self.state_dict()["embed_image_positions.weight"]) - len(state_dict["encoder.embed_image_positions.weight"])
899
+ embed_dim = state_dict["encoder.embed_image_positions.weight"].size(1)
900
+ new_pos_embed_to_add = torch.zeros(num_posids_to_add, embed_dim)
901
+ nn.init.normal_(new_pos_embed_to_add, mean=0, std=embed_dim ** -0.5)
902
+ new_pos_embed_to_add = new_pos_embed_to_add.to(
903
+ dtype=state_dict["encoder.embed_image_positions.weight"].dtype,
904
+ )
905
+ state_dict["encoder.embed_image_positions.weight"] = torch.cat(
906
+ [state_dict["encoder.embed_image_positions.weight"], new_pos_embed_to_add]
907
+ )
908
+ return state_dict
909
+
910
+
911
+ class TransformerDecoder(FairseqIncrementalDecoder):
912
+ """
913
+ Transformer decoder consisting of *args.decoder_layers* layers. Each layer
914
+ is a :class:`TransformerDecoderLayer`.
915
+
916
+ Args:
917
+ args (argparse.Namespace): parsed command-line arguments
918
+ dictionary (~fairseq.data.Dictionary): decoding dictionary
919
+ embed_tokens (torch.nn.Embedding): output embedding
920
+ no_encoder_attn (bool, optional): whether to attend to encoder outputs
921
+ (default: False).
922
+ """
923
+
924
+ def __init__(
925
+ self,
926
+ args,
927
+ dictionary,
928
+ embed_tokens,
929
+ no_encoder_attn=False,
930
+ output_projection=None,
931
+ ):
932
+ self.args = args
933
+ super().__init__(dictionary)
934
+ self.register_buffer("version", torch.Tensor([3]))
935
+ self._future_mask = torch.empty(0)
936
+
937
+ self.dropout_module = FairseqDropout(
938
+ args.dropout, module_name=self.__class__.__name__
939
+ )
940
+ self.decoder_layerdrop = args.decoder_layerdrop
941
+ self.share_input_output_embed = args.share_decoder_input_output_embed
942
+ self.num_attention_heads = args.decoder_attention_heads
943
+
944
+ input_embed_dim = embed_tokens.embedding_dim
945
+ embed_dim = args.decoder_embed_dim
946
+ self.embed_dim = embed_dim
947
+ self.output_embed_dim = args.decoder_output_dim
948
+
949
+ self.padding_idx = embed_tokens.padding_idx
950
+ self.max_target_positions = args.max_target_positions
951
+
952
+ self.embed_tokens = embed_tokens
953
+
954
+ self.embed_scale = 1.0 if args.no_scale_embedding else math.sqrt(embed_dim)
955
+
956
+ if not args.adaptive_input and args.quant_noise_pq > 0:
957
+ self.quant_noise = apply_quant_noise_(
958
+ nn.Linear(embed_dim, embed_dim, bias=False),
959
+ args.quant_noise_pq,
960
+ args.quant_noise_pq_block_size,
961
+ )
962
+ else:
963
+ self.quant_noise = None
964
+
965
+ self.project_in_dim = (
966
+ Linear(input_embed_dim, embed_dim, bias=False)
967
+ if embed_dim != input_embed_dim
968
+ else None
969
+ )
970
+
971
+ if getattr(args, "layernorm_embedding", False):
972
+ self.layernorm_embedding = LayerNorm(embed_dim)
973
+ else:
974
+ self.layernorm_embedding = None
975
+
976
+ self.window_size = args.code_image_size // 8
977
+
978
+ self.embed_positions = Embedding(args.max_target_positions + 2, embed_dim)
979
+ self.embed_image_positions = Embedding(args.image_bucket_size ** 2 + 1, embed_dim)
980
+ self.pos_ln = LayerNorm(embed_dim)
981
+ self.image_pos_ln = LayerNorm(embed_dim)
982
+ self.pos_scaling = float(embed_dim / self.num_attention_heads * args.attn_scale_factor) ** -0.5
983
+ self.self_pos_q_linear = nn.Linear(embed_dim, embed_dim)
984
+ self.self_pos_k_linear = nn.Linear(embed_dim, embed_dim)
985
+ self.cross_pos_q_linear = nn.Linear(embed_dim, embed_dim)
986
+ self.cross_pos_k_linear = nn.Linear(embed_dim, embed_dim)
987
+
988
+ if getattr(args, "code_layernorm_embedding", False):
989
+ self.code_layernorm_embedding = LayerNorm(embed_dim)
990
+ else:
991
+ self.code_layernorm_embedding = None
992
+
993
+ self.cross_self_attention = getattr(args, "cross_self_attention", False)
994
+
995
+ if self.decoder_layerdrop > 0.0:
996
+ self.layers = LayerDropModuleList(p=self.decoder_layerdrop)
997
+ else:
998
+ self.layers = nn.ModuleList([])
999
+
1000
+ dpr = [x.item() for x in torch.linspace(0, args.decoder_drop_path_rate, args.decoder_layers)]
1001
+ self.layers.extend(
1002
+ [
1003
+ self.build_decoder_layer(args, no_encoder_attn, drop_path_rate=dpr[i])
1004
+ for i in range(args.decoder_layers)
1005
+ ]
1006
+ )
1007
+ self.num_layers = len(self.layers)
1008
+
1009
+ if args.decoder_normalize_before:
1010
+ self.layer_norm = LayerNorm(embed_dim)
1011
+ else:
1012
+ self.layer_norm = None
1013
+
1014
+ self.project_out_dim = (
1015
+ Linear(embed_dim, self.output_embed_dim, bias=False)
1016
+ if embed_dim != self.output_embed_dim and not args.tie_adaptive_weights
1017
+ else None
1018
+ )
1019
+
1020
+ self.adaptive_softmax = None
1021
+ self.output_projection = output_projection
1022
+ if self.output_projection is None:
1023
+ self.build_output_projection(args, dictionary, embed_tokens)
1024
+
1025
+ token_bucket_size = args.token_bucket_size
1026
+ token_num_rel_dis = 2 * token_bucket_size - 1
1027
+ token_rp_bucket = make_token_bucket_position(token_bucket_size)
1028
+ self.token_rel_pos_table_list = nn.ModuleList(
1029
+ [Embedding(token_num_rel_dis, self.num_attention_heads, zero_init=True) for _ in range(args.decoder_layers)]
1030
+ )
1031
+
1032
+ image_bucket_size = args.image_bucket_size
1033
+ image_num_rel_dis = (2 * image_bucket_size - 1) * (2 * image_bucket_size - 1) + 3
1034
+ image_rp_bucket = make_image_bucket_position(image_bucket_size, image_num_rel_dis)
1035
+ image_position_idx = torch.arange(self.window_size).unsqueeze(0).expand(self.window_size, self.window_size) + \
1036
+ torch.arange(self.window_size).unsqueeze(1) * image_bucket_size + 1
1037
+ image_position_idx = torch.cat([torch.tensor([0]), image_position_idx.view(-1)])
1038
+ image_position_idx = torch.cat([image_position_idx, torch.tensor([1024] * 768)])
1039
+ self.image_rel_pos_table_list = nn.ModuleList(
1040
+ [Embedding(image_num_rel_dis, self.num_attention_heads, zero_init=True) for _ in range(args.decoder_layers)]
1041
+ )
1042
+
1043
+ self.register_buffer("token_rp_bucket", token_rp_bucket)
1044
+ self.register_buffer("image_rp_bucket", image_rp_bucket)
1045
+ self.register_buffer("image_position_idx", image_position_idx)
1046
+ self.entangle_position_embedding = args.entangle_position_embedding
1047
+
1048
+ def build_output_projection(self, args, dictionary, embed_tokens):
1049
+ if args.adaptive_softmax_cutoff is not None:
1050
+ self.adaptive_softmax = AdaptiveSoftmax(
1051
+ len(dictionary),
1052
+ self.output_embed_dim,
1053
+ utils.eval_str_list(args.adaptive_softmax_cutoff, type=int),
1054
+ dropout=args.adaptive_softmax_dropout,
1055
+ adaptive_inputs=embed_tokens if args.tie_adaptive_weights else None,
1056
+ factor=args.adaptive_softmax_factor,
1057
+ tie_proj=args.tie_adaptive_proj,
1058
+ )
1059
+ elif self.share_input_output_embed:
1060
+ self.output_projection = nn.Linear(
1061
+ self.embed_tokens.weight.shape[1],
1062
+ self.embed_tokens.weight.shape[0],
1063
+ bias=False,
1064
+ )
1065
+ self.output_projection.weight = self.embed_tokens.weight
1066
+ else:
1067
+ self.output_projection = nn.Linear(
1068
+ self.output_embed_dim, len(dictionary), bias=False
1069
+ )
1070
+ nn.init.normal_(
1071
+ self.output_projection.weight, mean=0, std=self.output_embed_dim ** -0.5
1072
+ )
1073
+ num_base_layers = getattr(args, "base_layers", 0)
1074
+ for i in range(num_base_layers):
1075
+ self.layers.insert(((i+1) * args.decoder_layers) // (num_base_layers + 1), BaseLayer(args))
1076
+
1077
+ def build_decoder_layer(self, args, no_encoder_attn=False, drop_path_rate=0.0):
1078
+ layer = TransformerDecoderLayer(args, no_encoder_attn, drop_path_rate=drop_path_rate)
1079
+ checkpoint = getattr(args, "checkpoint_activations", False)
1080
+ if checkpoint:
1081
+ offload_to_cpu = getattr(args, "offload_activations", False)
1082
+ layer = checkpoint_wrapper(layer, offload_to_cpu=offload_to_cpu)
1083
+ # if we are checkpointing, enforce that FSDP always wraps the
1084
+ # checkpointed layer, regardless of layer size
1085
+ min_params_to_wrap = (
1086
+ getattr(args, "min_params_to_wrap", DEFAULT_MIN_PARAMS_TO_WRAP)
1087
+ if not checkpoint else 0
1088
+ )
1089
+ layer = fsdp_wrap(layer, min_num_params=min_params_to_wrap)
1090
+ return layer
1091
+
1092
+ def get_rel_pos_bias(self, x, idx):
1093
+ seq_len = x.size(1)
1094
+ rp_bucket = self.token_rp_bucket[:seq_len, :seq_len]
1095
+ values = F.embedding(rp_bucket, self.token_rel_pos_table_list[idx].weight)
1096
+ values = values.permute([2, 0, 1])
1097
+ return values.contiguous()
1098
+
1099
+ def get_image_rel_pos_bias(self, x, idx):
1100
+ seq_len = x.size(1)
1101
+ image_position_idx = self.image_position_idx[:seq_len]
1102
+ rp_bucket = self.image_rp_bucket[image_position_idx][:, image_position_idx]
1103
+ values = F.embedding(rp_bucket, self.image_rel_pos_table_list[idx].weight)
1104
+ values = values.permute(2, 0, 1)
1105
+ return values
1106
+
1107
+ def get_pos_info(self, tokens, tgt_pos_embed, src_pos_embed=None, use_image=False):
1108
+ batch_size = tokens.size(0)
1109
+ tgt_len = tokens.size(1)
1110
+ tgt_pos_embed = self.image_pos_ln(tgt_pos_embed) if use_image else self.pos_ln(tgt_pos_embed)
1111
+ if src_pos_embed is not None:
1112
+ src_len = src_pos_embed.size(1)
1113
+ pos_q = self.cross_pos_q_linear(tgt_pos_embed).view(
1114
+ batch_size, tgt_len, self.num_attention_heads, -1
1115
+ ).transpose(1, 2) * self.pos_scaling
1116
+ pos_k = self.cross_pos_k_linear(src_pos_embed).view(
1117
+ batch_size, src_len, self.num_attention_heads, -1
1118
+ ).transpose(1, 2)
1119
+ else:
1120
+ src_len = tgt_pos_embed.size(1)
1121
+ pos_q = self.self_pos_q_linear(tgt_pos_embed).view(
1122
+ batch_size, tgt_len, self.num_attention_heads, -1
1123
+ ).transpose(1, 2) * self.pos_scaling
1124
+ pos_k = self.self_pos_k_linear(tgt_pos_embed).view(
1125
+ batch_size, src_len, self.num_attention_heads, -1
1126
+ ).transpose(1, 2)
1127
+ abs_pos_bias = torch.matmul(pos_q, pos_k.transpose(2, 3))
1128
+ return abs_pos_bias
1129
+
1130
+ def forward(
1131
+ self,
1132
+ prev_output_tokens,
1133
+ code_masks: Optional[torch.Tensor] = None,
1134
+ encoder_out: Optional[Dict[str, List[Tensor]]] = None,
1135
+ incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None,
1136
+ features_only: bool = False,
1137
+ full_context_alignment: bool = False,
1138
+ alignment_layer: Optional[int] = None,
1139
+ alignment_heads: Optional[int] = None,
1140
+ src_lengths: Optional[Any] = None,
1141
+ return_all_hiddens: bool = False,
1142
+ ):
1143
+ """
1144
+ Args:
1145
+ prev_output_tokens (LongTensor): previous decoder outputs of shape
1146
+ `(batch, tgt_len)`, for teacher forcing
1147
+ encoder_out (optional): output from the encoder, used for
1148
+ encoder-side attention, should be of size T x B x C
1149
+ incremental_state (dict): dictionary used for storing state during
1150
+ :ref:`Incremental decoding`
1151
+ features_only (bool, optional): only return features without
1152
+ applying output layer (default: False).
1153
+ full_context_alignment (bool, optional): don't apply
1154
+ auto-regressive mask to self-attention (default: False).
1155
+
1156
+ Returns:
1157
+ tuple:
1158
+ - the decoder's output of shape `(batch, tgt_len, vocab)`
1159
+ - a dictionary with any model-specific outputs
1160
+ """
1161
+
1162
+ x, extra = self.extract_features(
1163
+ prev_output_tokens,
1164
+ code_masks=code_masks,
1165
+ encoder_out=encoder_out,
1166
+ incremental_state=incremental_state,
1167
+ full_context_alignment=full_context_alignment,
1168
+ alignment_layer=alignment_layer,
1169
+ alignment_heads=alignment_heads,
1170
+ )
1171
+
1172
+ if not features_only:
1173
+ x = self.output_layer(x)
1174
+ return x, extra
1175
+
1176
+ def extract_features(
1177
+ self,
1178
+ prev_output_tokens,
1179
+ code_masks: Optional[torch.Tensor],
1180
+ encoder_out: Optional[Dict[str, List[Tensor]]],
1181
+ incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None,
1182
+ full_context_alignment: bool = False,
1183
+ alignment_layer: Optional[int] = None,
1184
+ alignment_heads: Optional[int] = None,
1185
+ ):
1186
+ return self.extract_features_scriptable(
1187
+ prev_output_tokens,
1188
+ code_masks,
1189
+ encoder_out,
1190
+ incremental_state,
1191
+ full_context_alignment,
1192
+ alignment_layer,
1193
+ alignment_heads,
1194
+ )
1195
+
1196
+ """
1197
+ A scriptable subclass of this class has an extract_features method and calls
1198
+ super().extract_features, but super() is not supported in torchscript. A copy of
1199
+ this function is made to be used in the subclass instead.
1200
+ """
1201
+
1202
+ def extract_features_scriptable(
1203
+ self,
1204
+ prev_output_tokens,
1205
+ code_masks: Optional[torch.Tensor],
1206
+ encoder_out: Optional[Dict[str, List[Tensor]]],
1207
+ incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None,
1208
+ full_context_alignment: bool = False,
1209
+ alignment_layer: Optional[int] = None,
1210
+ alignment_heads: Optional[int] = None,
1211
+ ):
1212
+ """
1213
+ Similar to *forward* but only return features.
1214
+
1215
+ Includes several features from "Jointly Learning to Align and
1216
+ Translate with Transformer Models" (Garg et al., EMNLP 2019).
1217
+
1218
+ Args:
1219
+ full_context_alignment (bool, optional): don't apply
1220
+ auto-regressive mask to self-attention (default: False).
1221
+ alignment_layer (int, optional): return mean alignment over
1222
+ heads at this layer (default: last layer).
1223
+ alignment_heads (int, optional): only average alignment over
1224
+ this many heads (default: all heads).
1225
+
1226
+ Returns:
1227
+ tuple:
1228
+ - the decoder's features of shape `(batch, tgt_len, embed_dim)`
1229
+ - a dictionary with any model-specific outputs
1230
+ """
1231
+ bs, slen = prev_output_tokens.size()
1232
+ if alignment_layer is None:
1233
+ alignment_layer = self.num_layers - 1
1234
+
1235
+ enc: Optional[Tensor] = None
1236
+ padding_mask: Optional[Tensor] = None
1237
+ if encoder_out is not None and len(encoder_out["encoder_out"]) > 0:
1238
+ enc = encoder_out["encoder_out"][0]
1239
+ assert (
1240
+ enc.size()[1] == bs
1241
+ ), f"Expected enc.shape == (t, {bs}, c) got {enc.shape}"
1242
+ if encoder_out is not None and len(encoder_out["encoder_padding_mask"]) > 0:
1243
+ padding_mask = encoder_out["encoder_padding_mask"][0]
1244
+
1245
+ bsz, tgt_len = prev_output_tokens.shape
1246
+ token_position_idx = utils.new_arange(prev_output_tokens)
1247
+ tgt_pos_embed = self.embed_positions(token_position_idx)
1248
+ if code_masks is not None and torch.any(code_masks):
1249
+ image_position_idx = self.image_position_idx[:prev_output_tokens.size(1)].unsqueeze(0).expand(bsz, tgt_len)
1250
+ tgt_pos_embed[code_masks] = self.embed_image_positions(image_position_idx)[code_masks]
1251
+
1252
+ # self attn position bias
1253
+ self_abs_pos_bias = self.get_pos_info(prev_output_tokens, tgt_pos_embed, use_image=False)
1254
+ if code_masks is not None and torch.any(code_masks):
1255
+ self_image_abs_pos_bias = self.get_pos_info(prev_output_tokens, tgt_pos_embed, use_image=True)
1256
+ self_abs_pos_bias[code_masks] = self_image_abs_pos_bias[code_masks]
1257
+ # cross attn position bias
1258
+ src_pos_embed = encoder_out['position_embeddings'][0]
1259
+ cross_abs_pos_bias = self.get_pos_info(prev_output_tokens, tgt_pos_embed, src_pos_embed=src_pos_embed)
1260
+ if code_masks is not None and torch.any(code_masks):
1261
+ cross_image_abs_pos_bias = self.get_pos_info(prev_output_tokens, tgt_pos_embed, src_pos_embed=src_pos_embed, use_image=True)
1262
+ cross_abs_pos_bias[code_masks] = cross_image_abs_pos_bias[code_masks]
1263
+ cross_abs_pos_bias = cross_abs_pos_bias.reshape(-1, *cross_abs_pos_bias.size()[-2:])
1264
+
1265
+ all_prev_output_tokens = prev_output_tokens.clone()
1266
+ if incremental_state is not None:
1267
+ prev_output_tokens = prev_output_tokens[:, -1:]
1268
+ cross_abs_pos_bias = cross_abs_pos_bias[:, -1:, :]
1269
+ tgt_pos_embed = tgt_pos_embed[:, -1:, :]
1270
+
1271
+ # embed tokens and positions
1272
+ x = self.embed_scale * self.embed_tokens(prev_output_tokens)
1273
+
1274
+ if self.quant_noise is not None:
1275
+ x = self.quant_noise(x)
1276
+
1277
+ if self.project_in_dim is not None:
1278
+ x = self.project_in_dim(x)
1279
+
1280
+ if self.entangle_position_embedding is not None and not self.args.disable_entangle:
1281
+ x += tgt_pos_embed
1282
+
1283
+ if self.layernorm_embedding is not None:
1284
+ if code_masks is None or not code_masks.any() or not getattr(self, "code_layernorm_embedding", False):
1285
+ x = self.layernorm_embedding(x)
1286
+ elif code_masks is not None and code_masks.all():
1287
+ x = self.code_layernorm_embedding(x)
1288
+ else:
1289
+ x[~code_masks] = self.layernorm_embedding(x[~code_masks])
1290
+ x[code_masks] = self.code_layernorm_embedding(x[code_masks])
1291
+
1292
+ x = self.dropout_module(x)
1293
+
1294
+ # B x T x C -> T x B x C
1295
+ x = x.transpose(0, 1)
1296
+
1297
+ self_attn_padding_mask: Optional[Tensor] = None
1298
+ if self.cross_self_attention or prev_output_tokens.eq(self.padding_idx).any():
1299
+ self_attn_padding_mask = prev_output_tokens.eq(self.padding_idx)
1300
+
1301
+ # decoder layers
1302
+ attn: Optional[Tensor] = None
1303
+ inner_states: List[Optional[Tensor]] = [x]
1304
+ for idx, layer in enumerate(self.layers):
1305
+ if incremental_state is None and not full_context_alignment:
1306
+ self_attn_mask = self.buffered_future_mask(x)
1307
+ else:
1308
+ self_attn_mask = None
1309
+
1310
+ self_attn_bias = self_abs_pos_bias.clone()
1311
+ if code_masks is None or not code_masks.any():
1312
+ self_attn_bias += self.get_rel_pos_bias(all_prev_output_tokens, idx).unsqueeze(0)
1313
+ elif code_masks is not None and code_masks.all():
1314
+ self_attn_bias += self.get_image_rel_pos_bias(all_prev_output_tokens, idx).unsqueeze(0)
1315
+ else:
1316
+ self_attn_bias[~code_masks] += self.get_rel_pos_bias(all_prev_output_tokens, idx).unsqueeze(0)
1317
+ self_attn_bias[code_masks] += self.get_image_rel_pos_bias(all_prev_output_tokens, idx).unsqueeze(0)
1318
+ self_attn_bias = self_attn_bias.reshape(-1, *self_attn_bias.size()[-2:])
1319
+ if incremental_state is not None:
1320
+ self_attn_bias = self_attn_bias[:, -1:, :]
1321
+
1322
+ x, layer_attn, _ = layer(
1323
+ x,
1324
+ enc,
1325
+ padding_mask,
1326
+ incremental_state,
1327
+ self_attn_mask=self_attn_mask,
1328
+ self_attn_padding_mask=self_attn_padding_mask,
1329
+ need_attn=bool((idx == alignment_layer)),
1330
+ need_head_weights=bool((idx == alignment_layer)),
1331
+ self_attn_bias=self_attn_bias,
1332
+ cross_attn_bias=cross_abs_pos_bias
1333
+ )
1334
+ inner_states.append(x)
1335
+ if layer_attn is not None and idx == alignment_layer:
1336
+ attn = layer_attn.float().to(x)
1337
+
1338
+ if attn is not None:
1339
+ if alignment_heads is not None:
1340
+ attn = attn[:alignment_heads]
1341
+
1342
+ # average probabilities over heads
1343
+ attn = attn.mean(dim=0)
1344
+
1345
+ if self.layer_norm is not None:
1346
+ x = self.layer_norm(x)
1347
+
1348
+ # T x B x C -> B x T x C
1349
+ x = x.transpose(0, 1)
1350
+
1351
+ if self.project_out_dim is not None:
1352
+ x = self.project_out_dim(x)
1353
+
1354
+ return x, {"attn": [attn], "inner_states": inner_states}
1355
+
1356
+ def output_layer(self, features):
1357
+ """Project features to the vocabulary size."""
1358
+ if self.adaptive_softmax is None:
1359
+ # project back to size of vocabulary
1360
+ return self.output_projection(features)
1361
+ else:
1362
+ return features
1363
+
1364
+ def max_positions(self):
1365
+ """Maximum output length supported by the decoder."""
1366
+ if self.embed_positions is None:
1367
+ return self.max_target_positions
1368
+ return self.max_target_positions
1369
+
1370
+ def buffered_future_mask(self, tensor):
1371
+ dim = tensor.size(0)
1372
+ # self._future_mask.device != tensor.device is not working in TorchScript. This is a workaround.
1373
+ if (
1374
+ self._future_mask.size(0) == 0
1375
+ or (not self._future_mask.device == tensor.device)
1376
+ or self._future_mask.size(0) < dim
1377
+ ):
1378
+ self._future_mask = torch.triu(
1379
+ utils.fill_with_neg_inf(torch.zeros([dim, dim])), 1
1380
+ )
1381
+ self._future_mask = self._future_mask.to(tensor)
1382
+ return self._future_mask[:dim, :dim]
1383
+
1384
+ def upgrade_state_dict_named(self, state_dict, name):
1385
+ """Upgrade a (possibly old) state dict for new versions of fairseq."""
1386
+ if isinstance(self.embed_positions, SinusoidalPositionalEmbedding):
1387
+ weights_key = "{}.embed_positions.weights".format(name)
1388
+ if weights_key in state_dict:
1389
+ del state_dict[weights_key]
1390
+ state_dict[
1391
+ "{}.embed_positions._float_tensor".format(name)
1392
+ ] = torch.FloatTensor(1)
1393
+
1394
+ if f"{name}.output_projection.weight" not in state_dict:
1395
+ if self.share_input_output_embed:
1396
+ embed_out_key = f"{name}.embed_tokens.weight"
1397
+ else:
1398
+ embed_out_key = f"{name}.embed_out"
1399
+ if embed_out_key in state_dict:
1400
+ state_dict[f"{name}.output_projection.weight"] = state_dict[
1401
+ embed_out_key
1402
+ ]
1403
+ if not self.share_input_output_embed:
1404
+ del state_dict[embed_out_key]
1405
+
1406
+ for i in range(self.num_layers):
1407
+ # update layer norms
1408
+ self.layers[i].upgrade_state_dict_named(
1409
+ state_dict, "{}.layers.{}".format(name, i)
1410
+ )
1411
+
1412
+ # version_key = "{}.version".format(name)
1413
+ # if utils.item(state_dict.get(version_key, torch.Tensor([1]))[0]) <= 2:
1414
+ # # earlier checkpoints did not normalize after the stack of layers
1415
+ # self.layer_norm = None
1416
+ # self.normalize = False
1417
+ # state_dict[version_key] = torch.Tensor([1])
1418
+
1419
+ prefix = name + "." if name != "" else ""
1420
+ image_params = ["image_position_idx"]
1421
+ for image_param in image_params:
1422
+ state_dict[prefix + image_param] = self.state_dict()[image_param]
1423
+ for param_name, param_tensor in self.state_dict().items():
1424
+ if (prefix + param_name) not in state_dict:
1425
+ state_dict[prefix + param_name] = self.state_dict()[param_name]
1426
+
1427
+ if len(state_dict["decoder.embed_image_positions.weight"]) < len(self.state_dict()["embed_image_positions.weight"]):
1428
+ num_posids_to_add = len(self.state_dict()["embed_image_positions.weight"]) - len(state_dict["decoder.embed_image_positions.weight"])
1429
+ embed_dim = state_dict["decoder.embed_image_positions.weight"].size(1)
1430
+ new_pos_embed_to_add = torch.zeros(num_posids_to_add, embed_dim)
1431
+ nn.init.normal_(new_pos_embed_to_add, mean=0, std=embed_dim ** -0.5)
1432
+ new_pos_embed_to_add = new_pos_embed_to_add.to(
1433
+ dtype=state_dict["decoder.embed_image_positions.weight"].dtype,
1434
+ )
1435
+ state_dict["decoder.embed_image_positions.weight"] = torch.cat(
1436
+ [state_dict["decoder.embed_image_positions.weight"], new_pos_embed_to_add]
1437
+ )
1438
+ return state_dict
1439
+
1440
+
1441
+ def Embedding(num_embeddings, embedding_dim, padding_idx=None, zero_init=False):
1442
+ m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx)
1443
+ nn.init.normal_(m.weight, mean=0, std=embedding_dim ** -0.5)
1444
+ if padding_idx is not None:
1445
+ nn.init.constant_(m.weight[padding_idx], 0)
1446
+ if zero_init:
1447
+ nn.init.constant_(m.weight, 0)
1448
+ return m
1449
+
1450
+
1451
+ def Linear(in_features, out_features, bias=True):
1452
+ m = nn.Linear(in_features, out_features, bias)
1453
+ nn.init.xavier_uniform_(m.weight)
1454
+ if bias:
1455
+ nn.init.constant_(m.bias, 0.0)
1456
+ return m
1457
+
1458
+
1459
+ @register_model_architecture("unify_transformer", "unify_transformer")
1460
+ def base_architecture(args):
1461
+ args.encoder_embed_path = getattr(args, "encoder_embed_path", None)
1462
+ args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 512)
1463
+ args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 2048)
1464
+ args.encoder_layers = getattr(args, "encoder_layers", 6)
1465
+ args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 8)
1466
+ args.encoder_normalize_before = getattr(args, "encoder_normalize_before", False)
1467
+ args.encoder_learned_pos = getattr(args, "encoder_learned_pos", False)
1468
+ args.decoder_embed_path = getattr(args, "decoder_embed_path", None)
1469
+ args.decoder_embed_dim = getattr(args, "decoder_embed_dim", args.encoder_embed_dim)
1470
+ args.decoder_ffn_embed_dim = getattr(
1471
+ args, "decoder_ffn_embed_dim", args.encoder_ffn_embed_dim
1472
+ )
1473
+ args.decoder_layers = getattr(args, "decoder_layers", 6)
1474
+ args.decoder_attention_heads = getattr(args, "decoder_attention_heads", 8)
1475
+ args.decoder_normalize_before = getattr(args, "decoder_normalize_before", False)
1476
+ args.decoder_learned_pos = getattr(args, "decoder_learned_pos", False)
1477
+ args.attention_dropout = getattr(args, "attention_dropout", 0.0)
1478
+ args.activation_dropout = getattr(args, "activation_dropout", 0.0)
1479
+ args.activation_fn = getattr(args, "activation_fn", "relu")
1480
+ args.dropout = getattr(args, "dropout", 0.1)
1481
+ args.adaptive_softmax_cutoff = getattr(args, "adaptive_softmax_cutoff", None)
1482
+ args.adaptive_softmax_dropout = getattr(args, "adaptive_softmax_dropout", 0)
1483
+ args.share_decoder_input_output_embed = getattr(
1484
+ args, "share_decoder_input_output_embed", False
1485
+ )
1486
+ args.share_all_embeddings = getattr(args, "share_all_embeddings", False)
1487
+ args.no_token_positional_embeddings = getattr(
1488
+ args, "no_token_positional_embeddings", False
1489
+ )
1490
+ args.adaptive_input = getattr(args, "adaptive_input", False)
1491
+ args.no_cross_attention = getattr(args, "no_cross_attention", False)
1492
+ args.cross_self_attention = getattr(args, "cross_self_attention", False)
1493
+
1494
+ args.decoder_output_dim = getattr(
1495
+ args, "decoder_output_dim", args.decoder_embed_dim
1496
+ )
1497
+ args.decoder_input_dim = getattr(args, "decoder_input_dim", args.decoder_embed_dim)
1498
+
1499
+ args.no_scale_embedding = getattr(args, "no_scale_embedding", False)
1500
+ args.layernorm_embedding = getattr(args, "layernorm_embedding", False)
1501
+ args.tie_adaptive_weights = getattr(args, "tie_adaptive_weights", False)
1502
+ args.checkpoint_activations = getattr(args, "checkpoint_activations", False)
1503
+ args.offload_activations = getattr(args, "offload_activations", False)
1504
+ if args.offload_activations:
1505
+ args.checkpoint_activations = True
1506
+ args.encoder_layers_to_keep = getattr(args, "encoder_layers_to_keep", None)
1507
+ args.decoder_layers_to_keep = getattr(args, "decoder_layers_to_keep", None)
1508
+ args.encoder_layerdrop = getattr(args, "encoder_layerdrop", 0)
1509
+ args.decoder_layerdrop = getattr(args, "decoder_layerdrop", 0)
1510
+ args.quant_noise_pq = getattr(args, "quant_noise_pq", 0)
1511
+ args.quant_noise_pq_block_size = getattr(args, "quant_noise_pq_block_size", 8)
1512
+ args.quant_noise_scalar = getattr(args, "quant_noise_scalar", 0)
models/ofa/unify_transformer_layer.py ADDED
@@ -0,0 +1,542 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The OFA-Sys Team.
2
+ # All rights reserved.
3
+ # This source code is licensed under the Apache 2.0 license
4
+ # found in the LICENSE file in the root directory.
5
+
6
+ from typing import Dict, List, Optional
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ from fairseq import utils
11
+ from fairseq.modules import LayerNorm
12
+ from fairseq.modules.fairseq_dropout import FairseqDropout
13
+ from fairseq.modules.quant_noise import quant_noise
14
+ from torch import Tensor
15
+
16
+ from .unify_multihead_attention import MultiheadAttention
17
+
18
+
19
+ def drop_path(x, drop_prob: float = 0.0, training: bool = False):
20
+ """
21
+ Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
22
+ Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
23
+ however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
24
+ See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
25
+ layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
26
+ argument.
27
+ """
28
+ if drop_prob == 0.0 or not training:
29
+ return x
30
+ keep_prob = 1 - drop_prob
31
+ shape = (1, x.shape[1], 1)
32
+ random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
33
+ random_tensor.floor_() # binarize
34
+ output = x.div(keep_prob) * random_tensor
35
+ return output
36
+
37
+
38
+ class DropPath(nn.Module):
39
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
40
+
41
+ def __init__(self, drop_prob=None):
42
+ super().__init__()
43
+ self.drop_prob = drop_prob
44
+
45
+ def forward(self, x):
46
+ return drop_path(x, self.drop_prob, self.training)
47
+
48
+ def extra_repr(self) -> str:
49
+ return "p={}".format(self.drop_prob)
50
+
51
+
52
+ class TransformerEncoderLayer(nn.Module):
53
+ """Encoder layer block.
54
+
55
+ In the original paper each operation (multi-head attention or FFN) is
56
+ postprocessed with: `dropout -> add residual -> layernorm`. In the
57
+ tensor2tensor code they suggest that learning is more robust when
58
+ preprocessing each layer with layernorm and postprocessing with:
59
+ `dropout -> add residual`. We default to the approach in the paper, but the
60
+ tensor2tensor approach can be enabled by setting
61
+ *args.encoder_normalize_before* to ``True``.
62
+
63
+ Args:
64
+ args (argparse.Namespace): parsed command-line arguments
65
+ """
66
+
67
+ def __init__(self, args, drop_path_rate=0.0):
68
+ super().__init__()
69
+ self.args = args
70
+ self.embed_dim = args.encoder_embed_dim
71
+ self.quant_noise = getattr(args, 'quant_noise_pq', 0)
72
+ self.quant_noise_block_size = getattr(args, 'quant_noise_pq_block_size', 8) or 8
73
+ self.self_attn = self.build_self_attention(self.embed_dim, args)
74
+ self.self_attn_layer_norm = LayerNorm(self.embed_dim)
75
+ self.dropout_module = FairseqDropout(
76
+ args.dropout, module_name=self.__class__.__name__
77
+ )
78
+ self.activation_fn = utils.get_activation_fn(
79
+ activation=getattr(args, 'activation_fn', 'relu') or "relu"
80
+ )
81
+ activation_dropout_p = getattr(args, "activation_dropout", 0) or 0
82
+ if activation_dropout_p == 0:
83
+ # for backwards compatibility with models that use args.relu_dropout
84
+ activation_dropout_p = getattr(args, "relu_dropout", 0) or 0
85
+ self.activation_dropout_module = FairseqDropout(
86
+ float(activation_dropout_p), module_name=self.__class__.__name__
87
+ )
88
+ self.normalize_before = args.encoder_normalize_before
89
+ self.fc1 = self.build_fc1(
90
+ self.embed_dim,
91
+ args.encoder_ffn_embed_dim,
92
+ self.quant_noise,
93
+ self.quant_noise_block_size,
94
+ )
95
+ self.fc2 = self.build_fc2(
96
+ args.encoder_ffn_embed_dim,
97
+ self.embed_dim,
98
+ self.quant_noise,
99
+ self.quant_noise_block_size,
100
+ )
101
+
102
+ self.attn_ln = LayerNorm(self.embed_dim) if getattr(args, 'scale_attn', False) else None
103
+ self.nh = self.self_attn.num_heads
104
+ self.head_dim = self.self_attn.head_dim
105
+
106
+ self.ffn_layernorm = LayerNorm(args.encoder_ffn_embed_dim) if getattr(args, 'scale_fc', False) else None
107
+ self.w_resid = nn.Parameter(torch.ones(self.embed_dim, ), requires_grad=True) if getattr(args, 'scale_resids', False) else None
108
+
109
+ self.final_layer_norm = LayerNorm(self.embed_dim)
110
+
111
+ self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
112
+
113
+ def build_fc1(self, input_dim, output_dim, q_noise, qn_block_size):
114
+ return quant_noise(
115
+ nn.Linear(input_dim, output_dim), p=q_noise, block_size=qn_block_size
116
+ )
117
+
118
+ def build_fc2(self, input_dim, output_dim, q_noise, qn_block_size):
119
+ return quant_noise(
120
+ nn.Linear(input_dim, output_dim), p=q_noise, block_size=qn_block_size
121
+ )
122
+
123
+ def build_self_attention(self, embed_dim, args):
124
+ return MultiheadAttention(
125
+ embed_dim,
126
+ args.encoder_attention_heads,
127
+ dropout=args.attention_dropout,
128
+ self_attention=True,
129
+ q_noise=self.quant_noise,
130
+ qn_block_size=self.quant_noise_block_size,
131
+ scale_factor=args.attn_scale_factor,
132
+ scale_heads=getattr(args, 'scale_heads', False)
133
+ )
134
+
135
+ def residual_connection(self, x, residual):
136
+ return residual + self.drop_path(x)
137
+
138
+ def upgrade_state_dict_named(self, state_dict, name):
139
+ """
140
+ Rename layer norm states from `...layer_norms.0.weight` to
141
+ `...self_attn_layer_norm.weight` and `...layer_norms.1.weight` to
142
+ `...final_layer_norm.weight`
143
+ """
144
+ layer_norm_map = {"0": "self_attn_layer_norm", "1": "final_layer_norm"}
145
+ for old, new in layer_norm_map.items():
146
+ for m in ("weight", "bias"):
147
+ k = "{}.layer_norms.{}.{}".format(name, old, m)
148
+ if k in state_dict:
149
+ state_dict["{}.{}.{}".format(name, new, m)] = state_dict[k]
150
+ del state_dict[k]
151
+ if "{}.{}.{}".format(name, new, m) not in state_dict and "{}.{}".format(new, m) in self.state_dict():
152
+ state_dict[
153
+ "{}.{}.{}".format(name, new, m)
154
+ ] = self.state_dict()["{}.{}".format(new, m)]
155
+
156
+ prefix = name + "." if name != "" else ""
157
+ for param_name, param_tensor in self.state_dict().items():
158
+ if (prefix + param_name) not in state_dict:
159
+ state_dict[prefix + param_name] = self.state_dict()[param_name]
160
+
161
+ def forward(
162
+ self,
163
+ x,
164
+ encoder_padding_mask: Optional[Tensor],
165
+ attn_mask: Optional[Tensor] = None,
166
+ self_attn_bias: Optional[Tensor] = None
167
+ ):
168
+ """
169
+ Args:
170
+ x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`
171
+ encoder_padding_mask (ByteTensor): binary ByteTensor of shape
172
+ `(batch, seq_len)` where padding elements are indicated by ``1``.
173
+ attn_mask (ByteTensor): binary tensor of shape `(tgt_len, src_len)`,
174
+ where `tgt_len` is the length of output and `src_len` is the
175
+ length of input, though here both are equal to `seq_len`.
176
+ `attn_mask[tgt_i, src_j] = 1` means that when calculating the
177
+ embedding for `tgt_i`, we exclude (mask out) `src_j`. This is
178
+ useful for strided self-attention.
179
+
180
+ Returns:
181
+ encoded output of shape `(seq_len, batch, embed_dim)`
182
+ """
183
+ # anything in original attn_mask = 1, becomes -1e8
184
+ # anything in original attn_mask = 0, becomes 0
185
+ # Note that we cannot use -inf here, because at some edge cases,
186
+ # the attention weight (before softmax) for some padded element in query
187
+ # will become -inf, which results in NaN in model parameters
188
+ if attn_mask is not None:
189
+ attn_mask = attn_mask.masked_fill(
190
+ attn_mask.to(torch.bool),
191
+ -1e8 if x.dtype == torch.float32 else -1e4
192
+ )
193
+
194
+ residual = x
195
+ if self.normalize_before:
196
+ x = self.self_attn_layer_norm(x)
197
+ x, _ = self.self_attn(
198
+ query=x,
199
+ key=x,
200
+ value=x,
201
+ key_padding_mask=encoder_padding_mask,
202
+ need_weights=False,
203
+ attn_mask=attn_mask,
204
+ attn_bias=self_attn_bias
205
+ )
206
+ if self.attn_ln is not None:
207
+ x = self.attn_ln(x)
208
+ x = self.dropout_module(x)
209
+ x = self.residual_connection(x, residual)
210
+ if not self.normalize_before:
211
+ x = self.self_attn_layer_norm(x)
212
+
213
+ residual = x
214
+ if self.normalize_before:
215
+ x = self.final_layer_norm(x)
216
+ x = self.activation_fn(self.fc1(x))
217
+ x = self.activation_dropout_module(x)
218
+ if self.ffn_layernorm is not None:
219
+ x = self.ffn_layernorm(x)
220
+ x = self.fc2(x)
221
+ x = self.dropout_module(x)
222
+ if self.w_resid is not None:
223
+ residual = torch.mul(self.w_resid, residual)
224
+ x = self.residual_connection(x, residual)
225
+ if not self.normalize_before:
226
+ x = self.final_layer_norm(x)
227
+ return x
228
+
229
+
230
+ class TransformerDecoderLayer(nn.Module):
231
+ """Decoder layer block.
232
+
233
+ In the original paper each operation (multi-head attention, encoder
234
+ attention or FFN) is postprocessed with: `dropout -> add residual ->
235
+ layernorm`. In the tensor2tensor code they suggest that learning is more
236
+ robust when preprocessing each layer with layernorm and postprocessing with:
237
+ `dropout -> add residual`. We default to the approach in the paper, but the
238
+ tensor2tensor approach can be enabled by setting
239
+ *args.decoder_normalize_before* to ``True``.
240
+
241
+ Args:
242
+ args (argparse.Namespace): parsed command-line arguments
243
+ no_encoder_attn (bool, optional): whether to attend to encoder outputs
244
+ (default: False).
245
+ """
246
+
247
+ def __init__(
248
+ self, args, no_encoder_attn=False, add_bias_kv=False, add_zero_attn=False, drop_path_rate=0.0
249
+ ):
250
+ super().__init__()
251
+ self.embed_dim = args.decoder_embed_dim
252
+ self.dropout_module = FairseqDropout(
253
+ args.dropout, module_name=self.__class__.__name__
254
+ )
255
+ self.quant_noise = getattr(args, "quant_noise_pq", 0)
256
+ self.quant_noise_block_size = getattr(args, "quant_noise_pq_block_size", 8)
257
+
258
+ self.cross_self_attention = getattr(args, "cross_self_attention", False)
259
+
260
+ self.self_attn = self.build_self_attention(
261
+ self.embed_dim,
262
+ args,
263
+ add_bias_kv=add_bias_kv,
264
+ add_zero_attn=add_zero_attn,
265
+ )
266
+ self.self_attn_ln = LayerNorm(self.embed_dim) if getattr(args, 'scale_attn', False) else None
267
+ self.cross_attn_ln = LayerNorm(self.embed_dim) if getattr(args, 'scale_attn', False) else None
268
+ self.nh = self.self_attn.num_heads
269
+ self.head_dim = self.self_attn.head_dim
270
+
271
+ self.activation_fn = utils.get_activation_fn(
272
+ activation=str(args.activation_fn)
273
+ if getattr(args, "activation_fn", None) is not None
274
+ else "relu"
275
+ )
276
+ activation_dropout_p = getattr(args, "activation_dropout", 0) or 0
277
+ if activation_dropout_p == 0:
278
+ # for backwards compatibility with models that use args.relu_dropout
279
+ activation_dropout_p = getattr(args, "relu_dropout", 0) or 0
280
+ self.activation_dropout_module = FairseqDropout(
281
+ float(activation_dropout_p), module_name=self.__class__.__name__
282
+ )
283
+ self.normalize_before = args.decoder_normalize_before
284
+
285
+ # use layerNorm rather than FusedLayerNorm for exporting.
286
+ # char_inputs can be used to determint this.
287
+ # TODO remove this once we update apex with the fix
288
+ export = getattr(args, "char_inputs", False)
289
+ self.self_attn_layer_norm = LayerNorm(self.embed_dim, export=export)
290
+
291
+ if no_encoder_attn:
292
+ self.encoder_attn = None
293
+ self.encoder_attn_layer_norm = None
294
+ else:
295
+ self.encoder_attn = self.build_encoder_attention(self.embed_dim, args)
296
+ self.encoder_attn_layer_norm = LayerNorm(self.embed_dim, export=export)
297
+
298
+ self.ffn_layernorm = LayerNorm(args.decoder_ffn_embed_dim) if getattr(args, 'scale_fc', False) else None
299
+ self.w_resid = nn.Parameter(torch.ones(self.embed_dim, ), requires_grad=True) if getattr(args, 'scale_resids', False) else None
300
+
301
+ self.fc1 = self.build_fc1(
302
+ self.embed_dim,
303
+ args.decoder_ffn_embed_dim,
304
+ self.quant_noise,
305
+ self.quant_noise_block_size,
306
+ )
307
+ self.fc2 = self.build_fc2(
308
+ args.decoder_ffn_embed_dim,
309
+ self.embed_dim,
310
+ self.quant_noise,
311
+ self.quant_noise_block_size,
312
+ )
313
+
314
+ self.final_layer_norm = LayerNorm(self.embed_dim, export=export)
315
+ self.need_attn = True
316
+
317
+ self.onnx_trace = False
318
+
319
+ self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
320
+
321
+ def build_fc1(self, input_dim, output_dim, q_noise, qn_block_size):
322
+ return quant_noise(nn.Linear(input_dim, output_dim), q_noise, qn_block_size)
323
+
324
+ def build_fc2(self, input_dim, output_dim, q_noise, qn_block_size):
325
+ return quant_noise(nn.Linear(input_dim, output_dim), q_noise, qn_block_size)
326
+
327
+ def build_self_attention(
328
+ self, embed_dim, args, add_bias_kv=False, add_zero_attn=False
329
+ ):
330
+ return MultiheadAttention(
331
+ embed_dim,
332
+ args.decoder_attention_heads,
333
+ dropout=args.attention_dropout,
334
+ add_bias_kv=add_bias_kv,
335
+ add_zero_attn=add_zero_attn,
336
+ self_attention=not getattr(args, "cross_self_attention", False),
337
+ q_noise=self.quant_noise,
338
+ qn_block_size=self.quant_noise_block_size,
339
+ scale_factor=args.attn_scale_factor,
340
+ scale_heads=getattr(args, 'scale_heads', False)
341
+ )
342
+
343
+ def build_encoder_attention(self, embed_dim, args):
344
+ return MultiheadAttention(
345
+ embed_dim,
346
+ args.decoder_attention_heads,
347
+ kdim=getattr(args, "encoder_embed_dim", None),
348
+ vdim=getattr(args, "encoder_embed_dim", None),
349
+ dropout=args.attention_dropout,
350
+ encoder_decoder_attention=True,
351
+ q_noise=self.quant_noise,
352
+ qn_block_size=self.quant_noise_block_size,
353
+ scale_factor=args.attn_scale_factor,
354
+ scale_heads=getattr(args, 'scale_heads', False)
355
+ )
356
+
357
+ def prepare_for_onnx_export_(self):
358
+ self.onnx_trace = True
359
+
360
+ def residual_connection(self, x, residual):
361
+ return residual + self.drop_path(x)
362
+
363
+ def forward(
364
+ self,
365
+ x,
366
+ encoder_out: Optional[torch.Tensor] = None,
367
+ encoder_padding_mask: Optional[torch.Tensor] = None,
368
+ incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None,
369
+ prev_self_attn_state: Optional[List[torch.Tensor]] = None,
370
+ prev_attn_state: Optional[List[torch.Tensor]] = None,
371
+ self_attn_mask: Optional[torch.Tensor] = None,
372
+ self_attn_padding_mask: Optional[torch.Tensor] = None,
373
+ need_attn: bool = False,
374
+ need_head_weights: bool = False,
375
+ self_attn_bias: Optional[Tensor] = None,
376
+ cross_attn_bias: Optional[Tensor] = None
377
+ ):
378
+ """
379
+ Args:
380
+ x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`
381
+ encoder_padding_mask (ByteTensor, optional): binary
382
+ ByteTensor of shape `(batch, src_len)` where padding
383
+ elements are indicated by ``1``.
384
+ need_attn (bool, optional): return attention weights
385
+ need_head_weights (bool, optional): return attention weights
386
+ for each head (default: return average over heads).
387
+
388
+ Returns:
389
+ encoded output of shape `(seq_len, batch, embed_dim)`
390
+ """
391
+ if need_head_weights:
392
+ need_attn = True
393
+
394
+ residual = x
395
+ if self.normalize_before:
396
+ x = self.self_attn_layer_norm(x)
397
+ if prev_self_attn_state is not None:
398
+ prev_key, prev_value = prev_self_attn_state[:2]
399
+ saved_state: Dict[str, Optional[Tensor]] = {
400
+ "prev_key": prev_key,
401
+ "prev_value": prev_value,
402
+ }
403
+ if len(prev_self_attn_state) >= 3:
404
+ saved_state["prev_key_padding_mask"] = prev_self_attn_state[2]
405
+ assert incremental_state is not None
406
+ self.self_attn._set_input_buffer(incremental_state, saved_state)
407
+ _self_attn_input_buffer = self.self_attn._get_input_buffer(incremental_state)
408
+ if self.cross_self_attention and not (
409
+ incremental_state is not None
410
+ and _self_attn_input_buffer is not None
411
+ and "prev_key" in _self_attn_input_buffer
412
+ ):
413
+ if self_attn_mask is not None:
414
+ assert encoder_out is not None
415
+ self_attn_mask = torch.cat(
416
+ (x.new_zeros(x.size(0), encoder_out.size(0)), self_attn_mask), dim=1
417
+ )
418
+ if self_attn_padding_mask is not None:
419
+ if encoder_padding_mask is None:
420
+ assert encoder_out is not None
421
+ encoder_padding_mask = self_attn_padding_mask.new_zeros(
422
+ encoder_out.size(1), encoder_out.size(0)
423
+ )
424
+ self_attn_padding_mask = torch.cat(
425
+ (encoder_padding_mask, self_attn_padding_mask), dim=1
426
+ )
427
+ assert encoder_out is not None
428
+ y = torch.cat((encoder_out, x), dim=0)
429
+ else:
430
+ y = x
431
+
432
+ x, attn = self.self_attn(
433
+ query=x,
434
+ key=y,
435
+ value=y,
436
+ key_padding_mask=self_attn_padding_mask,
437
+ incremental_state=incremental_state,
438
+ need_weights=False,
439
+ attn_mask=self_attn_mask,
440
+ attn_bias=self_attn_bias
441
+ )
442
+ if self.self_attn_ln is not None:
443
+ x = self.self_attn_ln(x)
444
+ x = self.dropout_module(x)
445
+ x = self.residual_connection(x, residual)
446
+ if not self.normalize_before:
447
+ x = self.self_attn_layer_norm(x)
448
+
449
+ if self.encoder_attn is not None and encoder_out is not None:
450
+ residual = x
451
+ if self.normalize_before:
452
+ x = self.encoder_attn_layer_norm(x)
453
+ if prev_attn_state is not None:
454
+ prev_key, prev_value = prev_attn_state[:2]
455
+ saved_state: Dict[str, Optional[Tensor]] = {
456
+ "prev_key": prev_key,
457
+ "prev_value": prev_value,
458
+ }
459
+ if len(prev_attn_state) >= 3:
460
+ saved_state["prev_key_padding_mask"] = prev_attn_state[2]
461
+ assert incremental_state is not None
462
+ self.encoder_attn._set_input_buffer(incremental_state, saved_state)
463
+
464
+ x, attn = self.encoder_attn(
465
+ query=x,
466
+ key=encoder_out,
467
+ value=encoder_out,
468
+ key_padding_mask=encoder_padding_mask,
469
+ incremental_state=incremental_state,
470
+ static_kv=True,
471
+ need_weights=need_attn or (not self.training and self.need_attn),
472
+ need_head_weights=need_head_weights,
473
+ attn_bias=cross_attn_bias
474
+ )
475
+ if self.cross_attn_ln is not None:
476
+ x = self.cross_attn_ln(x)
477
+ x = self.dropout_module(x)
478
+ x = self.residual_connection(x, residual)
479
+ if not self.normalize_before:
480
+ x = self.encoder_attn_layer_norm(x)
481
+
482
+ residual = x
483
+ if self.normalize_before:
484
+ x = self.final_layer_norm(x)
485
+
486
+ x = self.activation_fn(self.fc1(x))
487
+ x = self.activation_dropout_module(x)
488
+ if self.ffn_layernorm is not None:
489
+ x = self.ffn_layernorm(x)
490
+ x = self.fc2(x)
491
+ x = self.dropout_module(x)
492
+ if self.w_resid is not None:
493
+ residual = torch.mul(self.w_resid, residual)
494
+ x = self.residual_connection(x, residual)
495
+ if not self.normalize_before:
496
+ x = self.final_layer_norm(x)
497
+ if self.onnx_trace and incremental_state is not None:
498
+ saved_state = self.self_attn._get_input_buffer(incremental_state)
499
+ assert saved_state is not None
500
+ if self_attn_padding_mask is not None:
501
+ self_attn_state = [
502
+ saved_state["prev_key"],
503
+ saved_state["prev_value"],
504
+ saved_state["prev_key_padding_mask"],
505
+ ]
506
+ else:
507
+ self_attn_state = [saved_state["prev_key"], saved_state["prev_value"]]
508
+ return x, attn, self_attn_state
509
+ return x, attn, None
510
+
511
+ def make_generation_fast_(self, need_attn: bool = False, **kwargs):
512
+ self.need_attn = need_attn
513
+
514
+ def upgrade_state_dict_named(self, state_dict, name):
515
+ """
516
+ Rename layer norm states from `...layer_norms.0.weight` to
517
+ `...self_attn_layer_norm.weight` and `...layer_norms.1.weight` to
518
+ `...final_layer_norm.weight`
519
+ """
520
+ # update layer norms
521
+ layer_norm_map = {
522
+ "0": "self_attn_layer_norm",
523
+ "1": "encoder_attn_layer_norm",
524
+ "2": "final_layer_norm",
525
+ }
526
+ for old, new in layer_norm_map.items():
527
+ for m in ("weight", "bias"):
528
+ k = "{}.layer_norms.{}.{}".format(name, old, m)
529
+ if k in state_dict:
530
+ state_dict[
531
+ "{}.{}.{}".format(name, new, m)
532
+ ] = state_dict[k]
533
+ del state_dict[k]
534
+ if "{}.{}.{}".format(name, new, m) not in state_dict and "{}.{}".format(new, m) in self.state_dict():
535
+ state_dict[
536
+ "{}.{}.{}".format(name, new, m)
537
+ ] = self.state_dict()["{}.{}".format(new, m)]
538
+
539
+ prefix = name + "." if name != "" else ""
540
+ for param_name, param_tensor in self.state_dict().items():
541
+ if (prefix + param_name) not in state_dict:
542
+ state_dict[prefix + param_name] = self.state_dict()[param_name]
models/search.py ADDED
@@ -0,0 +1,814 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The OFA-Sys Team.
2
+ # All rights reserved.
3
+ # This source code is licensed under the Apache 2.0 license
4
+ # found in the LICENSE file in the root directory.
5
+
6
+ import math
7
+ from typing import List, Optional
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ from fairseq.token_generation_constraints import (
12
+ ConstraintState,
13
+ OrderedConstraintState,
14
+ UnorderedConstraintState,
15
+ )
16
+ from torch import Tensor
17
+
18
+
19
+ class Search(nn.Module):
20
+ def __init__(self, tgt_dict):
21
+ super().__init__()
22
+ self.pad = tgt_dict.pad()
23
+ self.unk = tgt_dict.unk()
24
+ self.eos = tgt_dict.eos()
25
+ self.vocab_size = len(tgt_dict)
26
+ self.src_lengths = torch.tensor(-1)
27
+ self.supports_constraints = False
28
+ self.stop_on_max_len = False
29
+
30
+ def step(
31
+ self, step, lprobs, scores, prev_output_tokens=None, original_batch_idxs=None
32
+ ):
33
+ """Take a single search step.
34
+
35
+ Args:
36
+ step: the current search step, starting at 0
37
+ lprobs: (bsz x input_beam_size x vocab_size)
38
+ the model's log-probabilities over the vocabulary at the current step
39
+ scores: (bsz x input_beam_size x step)
40
+ the historical model scores of each hypothesis up to this point
41
+ prev_output_tokens: (bsz x step)
42
+ the previously generated oputput tokens
43
+ original_batch_idxs: (bsz)
44
+ the tensor with the batch indices, in the range [0, bsz)
45
+ this is useful in case there has been applied a re-ordering
46
+ and we need to know the orignal indices
47
+
48
+ Return: A tuple of (scores, indices, beams) where:
49
+ scores: (bsz x output_beam_size)
50
+ the scores of the chosen elements; output_beam_size can be
51
+ larger than input_beam_size, e.g., we may return
52
+ 2*input_beam_size to account for EOS
53
+ indices: (bsz x output_beam_size)
54
+ the indices of the chosen elements
55
+ beams: (bsz x output_beam_size)
56
+ the hypothesis ids of the chosen elements, in the range [0, input_beam_size)
57
+ """
58
+ raise NotImplementedError
59
+
60
+ @torch.jit.export
61
+ def set_src_lengths(self, src_lengths):
62
+ self.src_lengths = src_lengths
63
+
64
+ @torch.jit.export
65
+ def init_constraints(self, batch_constraints: Optional[Tensor], beam_size: int):
66
+ """Initialize constraint states for constrained decoding (if supported).
67
+
68
+ Args:
69
+ batch_constraints: (torch.Tensor, optional)
70
+ the list of constraints, in packed form
71
+ beam_size: (int)
72
+ the beam size
73
+ Returns:
74
+ *encoder_out* rearranged according to *new_order*
75
+ """
76
+ pass
77
+
78
+ def prune_sentences(self, batch_idxs: Tensor):
79
+ """
80
+ Removes constraint states for completed sentences (if supported).
81
+ This is called from sequence_generator._generate() when sentences are
82
+ deleted from the batch.
83
+
84
+ Args:
85
+ batch_idxs: Indices of *sentences* whose constraint state should be *kept*.
86
+ """
87
+ pass
88
+
89
+ def update_constraints(self, active_hypos: Tensor):
90
+ """
91
+ Updates the constraint states by selecting the beam items that are retained.
92
+ This is called at each time step of sequence_generator._generate() when
93
+ the set of 2 * {beam_size} candidate hypotheses are reduced to the beam size.
94
+
95
+ Args:
96
+ active_hypos: (batch size, beam size)
97
+ list of integers denoting, for each sentence, which beam candidate items
98
+ should be kept.
99
+ """
100
+ pass
101
+
102
+
103
+ class BeamSearch(Search):
104
+ def __init__(self, tgt_dict):
105
+ super().__init__(tgt_dict)
106
+ self.constraint_states = None
107
+
108
+ @torch.jit.export
109
+ def step(
110
+ self,
111
+ step: int,
112
+ lprobs,
113
+ scores: Optional[Tensor],
114
+ prev_output_tokens: Optional[Tensor] = None,
115
+ original_batch_idxs: Optional[Tensor] = None,
116
+ ):
117
+ bsz, beam_size, vocab_size = lprobs.size()
118
+
119
+ if step == 0:
120
+ # at the first step all hypotheses are equally likely, so use
121
+ # only the first beam
122
+ lprobs = lprobs[:, ::beam_size, :].contiguous()
123
+ else:
124
+ # make probs contain cumulative scores for each hypothesis
125
+ assert scores is not None
126
+ lprobs = lprobs + scores[:, :, step - 1].unsqueeze(-1)
127
+
128
+ top_prediction = torch.topk(
129
+ lprobs.view(bsz, -1),
130
+ k=min(
131
+ # Take the best 2 x beam_size predictions. We'll choose the first
132
+ # beam_size of these which don't predict eos to continue with.
133
+ beam_size * 2,
134
+ lprobs.view(bsz, -1).size(1) - 1, # -1 so we never select pad
135
+ ),
136
+ )
137
+ scores_buf = top_prediction[0]
138
+ indices_buf = top_prediction[1]
139
+ # Project back into relative indices and beams
140
+ beams_buf = indices_buf // vocab_size
141
+ indices_buf = indices_buf.fmod(vocab_size)
142
+
143
+ # At this point, beams_buf and indices_buf are single-dim and contain relative indices
144
+ return scores_buf, indices_buf, beams_buf
145
+
146
+
147
+ class PrefixConstrainedBeamSearch(Search):
148
+ def __init__(self, tgt_dict, prefix_allowed_tokens_fn):
149
+ super().__init__(tgt_dict)
150
+ self.prefix_allowed_tokens_fn = prefix_allowed_tokens_fn
151
+ self.stop_on_max_len = True
152
+
153
+ @torch.jit.export
154
+ def apply_mask(self, x, prev_output_tokens, original_batch_idxs):
155
+ beam_size = x.shape[0] // original_batch_idxs.shape[0]
156
+ original_batch_idxs = (
157
+ original_batch_idxs.unsqueeze(-1).repeat((1, beam_size)).flatten().tolist()
158
+ )
159
+
160
+ mask = torch.full_like(x, -math.inf)
161
+ for sent_i, (sent, batch_i) in enumerate(
162
+ zip(prev_output_tokens, original_batch_idxs)
163
+ ):
164
+ mask[sent_i, :, self.prefix_allowed_tokens_fn(batch_i, sent)] = 0
165
+
166
+ return mask
167
+
168
+ @torch.jit.export
169
+ def step(
170
+ self,
171
+ step: int,
172
+ lprobs: Tensor,
173
+ scores: Tensor,
174
+ prev_output_tokens: Tensor,
175
+ original_batch_idxs: Tensor,
176
+ ):
177
+ bsz, beam_size, vocab_size = lprobs.size()
178
+
179
+ lprobs += self.apply_mask(
180
+ lprobs.view(bsz * beam_size, 1, vocab_size),
181
+ prev_output_tokens,
182
+ original_batch_idxs,
183
+ ).view(bsz, beam_size, vocab_size)
184
+
185
+ if step == 0:
186
+ # at the first step all hypotheses are equally likely, so use
187
+ # only the first beam
188
+ lprobs = lprobs[:, ::beam_size, :].contiguous()
189
+ else:
190
+ # make probs contain cumulative scores for each hypothesis
191
+ assert scores is not None
192
+ lprobs = lprobs + scores[:, :, step - 1].unsqueeze(-1)
193
+
194
+ top_prediction = torch.topk(
195
+ lprobs.view(bsz, -1),
196
+ k=min(
197
+ # Take the best beam_size predictions. We'll choose the first
198
+ # beam_size of these which don't predict eos to continue with.
199
+ beam_size,
200
+ lprobs.view(bsz, -1).size(1) - 1, # -1 so we never select pad
201
+ ),
202
+ )
203
+ scores_buf = top_prediction[0]
204
+ indices_buf = top_prediction[1]
205
+ beams_buf = indices_buf // vocab_size
206
+ indices_buf = indices_buf.fmod(vocab_size)
207
+ return scores_buf, indices_buf, beams_buf
208
+
209
+
210
+ class LexicallyConstrainedBeamSearch(Search):
211
+ """Implements lexically constrained beam search as described in
212
+
213
+ Fast Lexically Constrained Decoding with Dynamic Beam
214
+ Allocation for Neural Machine Translation. Post & Vilar,
215
+ NAACL 2018. https://www.aclweb.org/anthology/N18-1119/
216
+
217
+ and
218
+
219
+ Improved Lexically Constrained Decoding for Translation and
220
+ Monolingual Rewriting. Hu et al, NAACL
221
+ 2019. https://www.aclweb.org/anthology/N19-1090/
222
+
223
+ This is accomplished by maintaining, for each beam hypothesis, a
224
+ ConstraintState object (see constraints.py) that tracks which
225
+ constraints have been generated and using this information to
226
+ shape the beam for each input sentence.
227
+ """
228
+
229
+ def __init__(self, tgt_dict, representation):
230
+ super().__init__(tgt_dict)
231
+ self.representation = representation
232
+ self.vocab_size = len(tgt_dict)
233
+ self.num_cands = 0
234
+ self.supports_constraints = True
235
+
236
+ @torch.jit.export
237
+ def init_constraints(self, batch_constraints: Optional[Tensor], beam_size: int):
238
+ self.constraint_states = []
239
+ for constraint_tensor in batch_constraints:
240
+ if self.representation == "ordered":
241
+ constraint_state = OrderedConstraintState.create(constraint_tensor)
242
+ elif self.representation == "unordered":
243
+ constraint_state = UnorderedConstraintState.create(constraint_tensor)
244
+
245
+ self.constraint_states.append([constraint_state for i in range(beam_size)])
246
+
247
+ @torch.jit.export
248
+ def prune_sentences(self, batch_idxs: Tensor):
249
+ self.constraint_states = [
250
+ self.constraint_states[i] for i in batch_idxs.tolist()
251
+ ]
252
+
253
+ @torch.jit.export
254
+ def update_constraints(self, active_hypos: Tensor):
255
+ if self.constraint_states:
256
+ batch_size = active_hypos.size(0)
257
+ for sentid in range(batch_size):
258
+ self.constraint_states[sentid] = [
259
+ self.constraint_states[sentid][i] for i in active_hypos[sentid]
260
+ ]
261
+
262
+ @torch.jit.export
263
+ def step(
264
+ self,
265
+ step: int,
266
+ lprobs: Tensor,
267
+ scores: Optional[Tensor],
268
+ prev_output_tokens: Optional[Tensor] = None,
269
+ original_batch_idxs: Optional[Tensor] = None,
270
+ ):
271
+ """
272
+ A constrained step builds a large candidates list from the following:
273
+ - the top 2 * {beam_size} items over the whole beam
274
+ - for each item in the beam
275
+ - the top {each_k} (default 1)
276
+ - all next constraints
277
+ We then compute the constrained state of each beam item, and assign
278
+ stripe codes: 0 to the best in each bank, 1 to the 2nd-best, and so
279
+ on. We then sort by (stripe, score), and truncate the list at
280
+ 2 * beam size.
281
+
282
+ Args:
283
+ step: the decoder step
284
+ lprobs: (batch size, beam size, target vocab)
285
+ the target-vocab distributions for each item in the beam.
286
+ Retrun: A tuple of (scores, indices, beams, constraints) where:
287
+ scores: (batch, output beam size)
288
+ the scores of the chosen elements
289
+ indices: (batch, output beam size)
290
+ the target vocab indices of the chosen elements
291
+ beams: (batch, output beam size)
292
+ the 0-indexed hypothesis ids of the chosen elements
293
+ constraints: (batch, output beam size)
294
+ the new constraint states
295
+ """
296
+ each_k = 1
297
+ device = lprobs.device
298
+
299
+ batch_size, beam_size, vocab_size = lprobs.size()
300
+
301
+ self.num_cands = min(
302
+ # Just take the k-best. We'll get another k from the 1-best from each
303
+ # row, plus more from the constraints
304
+ beam_size * 2,
305
+ lprobs.view(batch_size, -1).size(1) - 1, # -1 so we never select pad
306
+ )
307
+
308
+ # STEP 0: Preliminary. Prevent EOS for unfinished hyps across all batch items
309
+ constraint_states = self.constraint_states
310
+ if constraint_states and step > 0:
311
+ not_finished_indices = []
312
+ for sentno, sent_constraints in enumerate(constraint_states):
313
+ for beamno, state in enumerate(sent_constraints):
314
+ index = sentno * beam_size + beamno
315
+ if not state.finished:
316
+ not_finished_indices.append(index)
317
+ not_finished_indices = torch.tensor(not_finished_indices)
318
+ if not_finished_indices.numel() > 0:
319
+ lprobs.view(batch_size * beam_size, -1)[
320
+ not_finished_indices, self.eos
321
+ ] = -math.inf
322
+
323
+ if step == 0:
324
+ # at the first step all hypotheses are equally likely, so use
325
+ # only the first beam entry for each batch item
326
+ lprobs = lprobs[:, ::beam_size, :].contiguous()
327
+ else:
328
+ # make probs contain cumulative scores for each hypothesis
329
+ assert scores is not None
330
+ lprobs = lprobs + scores[:, :, step - 1].unsqueeze(-1)
331
+
332
+ top_prediction = torch.topk(
333
+ lprobs.view(batch_size, -1),
334
+ self.num_cands,
335
+ )
336
+ scores_buf, indices_buf = top_prediction
337
+ # Project back into relative indices and beams
338
+ beams_buf = indices_buf // vocab_size
339
+ indices_buf = indices_buf.fmod(vocab_size)
340
+
341
+ # Short circuit if there are no constraints in this batch
342
+ if not constraint_states:
343
+ return scores_buf, indices_buf, beams_buf
344
+
345
+ # STEP 1: get top-1 from each hypothesis across all sentences in the batch
346
+ if step > 0:
347
+ top_scores, top_indices = torch.topk(
348
+ lprobs.view(batch_size * beam_size, -1),
349
+ k=each_k,
350
+ dim=1,
351
+ )
352
+ top_scores = top_scores.view(batch_size, -1)
353
+ top_indices = top_indices.view(batch_size, -1)
354
+ scores_buf = torch.cat((scores_buf, top_scores), dim=1)
355
+ indices_buf = torch.cat((indices_buf, top_indices), dim=1)
356
+ new_beams = torch.arange(0, beam_size, device=device).repeat(batch_size, 1)
357
+ beams_buf = torch.cat((beams_buf, new_beams), dim=1)
358
+
359
+ # Now, process sentences in the batch one by one.
360
+ new_scores_buf = torch.zeros((batch_size, 2 * beam_size), device=device)
361
+ new_indices_buf = torch.zeros((batch_size, 2 * beam_size), device=device).long()
362
+ new_beams_buf = torch.zeros((batch_size, 2 * beam_size), device=device).long()
363
+ for sentno, states in enumerate(constraint_states):
364
+ scores, indices, beams, new_states = self.step_sentence(
365
+ step,
366
+ sentno,
367
+ lprobs[sentno],
368
+ constraint_states[sentno],
369
+ beams_buf[sentno].clone(),
370
+ indices_buf[sentno].clone(),
371
+ scores_buf[sentno].clone(),
372
+ )
373
+ new_scores_buf[sentno] = scores
374
+ new_indices_buf[sentno] = indices
375
+ new_beams_buf[sentno] = beams
376
+ self.constraint_states[sentno] = new_states
377
+
378
+ return new_scores_buf, new_indices_buf, new_beams_buf
379
+
380
+ @torch.jit.export
381
+ def step_sentence(
382
+ self,
383
+ step: int,
384
+ sentno: int,
385
+ lprobs: Tensor,
386
+ constraint_states: List[List[ConstraintState]],
387
+ beams_buf: Tensor,
388
+ indices_buf: Tensor,
389
+ scores_buf: Tensor,
390
+ ):
391
+ """Does per-sentence processing. Adds all constraints for each
392
+ hypothesis to the list of candidates; then removes duplicates,
393
+ sorts, and dynamically stripes across the banks. All tensor inputs
394
+ are collapsed to those pertaining to a single input sentence.
395
+ """
396
+ device = lprobs.device
397
+
398
+ # STEP 2: Add all constraints for each beam item
399
+ for beamno, state in enumerate(constraint_states):
400
+ next_tokens = torch.tensor(list(state.next_tokens()), device=device).long()
401
+ if next_tokens.numel() != 0:
402
+ indices_buf = torch.cat((indices_buf, next_tokens))
403
+ next_beams = (
404
+ torch.tensor(beamno, device=device)
405
+ .repeat(next_tokens.size(0))
406
+ .long()
407
+ )
408
+ beams_buf = torch.cat((beams_buf, next_beams))
409
+ next_values = lprobs[beamno].take(next_tokens.view(-1))
410
+ scores_buf = torch.cat((scores_buf, next_values))
411
+
412
+ # At the 0th time step, there is just one beam item
413
+ if step == 0:
414
+ break
415
+
416
+ # STEP 3: Compute the "bank" for each candidate. This is the
417
+ # number of constraints it's generated. We need this so that
418
+ # we can do round-robin allocation of the beam across these
419
+ # banks. If C is the number of constraints, we select the best
420
+ # item in bank C, then the best in bank C-1, etc, followed by
421
+ # the 2nd-best in bank C, the 2nd-best in bank C-1, etc, and so
422
+ # on, until the maximum beam size. We accomplish this by
423
+ # creating a sort key and striping across the banks.
424
+
425
+ # Compute the new states for all candidates
426
+ cands_size = indices_buf.size(0)
427
+ constraint_states = [
428
+ constraint_states[beams_buf[i]].advance(indices_buf[i])
429
+ for i in range(cands_size)
430
+ ]
431
+
432
+ banks = torch.tensor([state.bank for state in constraint_states], device=device)
433
+
434
+ # STEP 4: Sort
435
+ num_constraint_tokens = len(state.tokens)
436
+
437
+ # Sort by keys (bank, score) (i.e., sort banks together, and scores
438
+ # within banks). AFAIK pytorch doesn't support either stable sort or
439
+ # multi-key sorting, so we have to hack this.
440
+ MAX_SCORE = -100
441
+ sort_key = (num_constraint_tokens - banks) * MAX_SCORE + scores_buf
442
+ sort_values, sort_indices = sort_key.sort(dim=0, descending=True)
443
+ scores_buf = scores_buf[sort_indices]
444
+ indices_buf = indices_buf[sort_indices]
445
+ beams_buf = beams_buf[sort_indices]
446
+ banks = banks[sort_indices]
447
+
448
+ # Sort the constraints to follow suit
449
+ constraint_states = [constraint_states[i] for i in sort_indices]
450
+
451
+ # STEP 5: Remove duplicates. The topk calls (overall and
452
+ # per-row) plus the per-row generation of constraints will
453
+ # produce duplicates. Here we remove them.
454
+
455
+ def roll(t):
456
+ """Rolls a 1d tensor left by 1.
457
+
458
+ [0, 1, 2, 3, 4] becomes [4, 0, 1, 2, 3]
459
+ """
460
+ return torch.cat((t[-1].unsqueeze(0), t[0:-1]), dim=0)
461
+
462
+ # We map candidates (beam, token_id) to a single dimension.
463
+ # This is then shifted by 1. We can then easily identify
464
+ # duplicates and create a mask that identifies unique
465
+ # extensions.
466
+ uniques_mask = beams_buf * (self.vocab_size + 1) + indices_buf
467
+ uniques_mask = roll(uniques_mask) != uniques_mask
468
+
469
+ # Use the mask to pare down the data structures
470
+ scores_buf = torch.masked_select(scores_buf, uniques_mask)
471
+ indices_buf = torch.masked_select(indices_buf, uniques_mask)
472
+ beams_buf = torch.masked_select(beams_buf, uniques_mask)
473
+ banks = torch.masked_select(banks, uniques_mask)
474
+ i = 1
475
+ for mask in uniques_mask[1:]:
476
+ if not mask:
477
+ constraint_states.pop(i)
478
+ i += mask
479
+
480
+ # STEP 6: Assign IDs round-robin across banks, sort, and
481
+ # truncate. Now that the candidates are sorted by (bank,
482
+ # score) and uniqed, we dynamically allocate the {beam_size}
483
+ # beam by striping across the candidates. These stripes will
484
+ # be used as sort keys to do round-robin selection. This is
485
+ # accomplished in a single pass with offsets. Sorting by
486
+ # highest-banks (furthest-along hypotheses) first ensures
487
+ # progress through the constraints.
488
+ #
489
+ # e.g., BANKS: 3 3 3 2 2 2 2 1 1 1 0 0
490
+ # OLD STRIPES: 0 1 2 0 1 2 3 0 1 2 0 1
491
+ # NEW STRIPES: 0 1+4 2+8 0+1 1+5 2+9 3+11 0+2 1+6 2+10 0+3 1+7
492
+ # = 0 5 10 1 6 11 13 2 7 12 3 8
493
+ #
494
+ # Sorting by this then gives the following banks:
495
+ #
496
+ # 3 2 1 0 3 2 1 0 3 2 1 2
497
+ #
498
+ # We'll take the top {beam_size} of these.
499
+ stripe_offsets = [offset * (len(banks) + 1) for offset in range(len(banks) + 1)]
500
+ stripes = torch.zeros_like(banks)
501
+ cur_bank_count = -1
502
+ cur_bank = banks[0]
503
+ for i, bank in enumerate(banks):
504
+ if bank != cur_bank:
505
+ cur_bank_count = 0
506
+ cur_bank = bank
507
+ else:
508
+ cur_bank_count += 1
509
+ stripes[i] = num_constraint_tokens - bank + stripe_offsets[cur_bank_count]
510
+
511
+ # STEP 7: Sort by the stripes values
512
+ sort_values, sort_indices = stripes.sort(dim=0)
513
+ scores_buf = scores_buf[sort_indices]
514
+ indices_buf = indices_buf[sort_indices]
515
+ beams_buf = beams_buf[sort_indices]
516
+ constraint_states = [constraint_states[i] for i in sort_indices]
517
+
518
+ # STEP 8: Truncate to the candidates size!
519
+ scores_buf = scores_buf[: self.num_cands]
520
+ indices_buf = indices_buf[: self.num_cands]
521
+ beams_buf = beams_buf[: self.num_cands]
522
+
523
+ return scores_buf, indices_buf, beams_buf, constraint_states
524
+
525
+
526
+ class LengthConstrainedBeamSearch(Search):
527
+ def __init__(self, tgt_dict, min_len_a, min_len_b, max_len_a, max_len_b):
528
+ super().__init__(tgt_dict)
529
+ self.min_len_a = min_len_a
530
+ self.min_len_b = min_len_b
531
+ self.max_len_a = max_len_a
532
+ self.max_len_b = max_len_b
533
+ self.beam = BeamSearch(tgt_dict)
534
+ self.needs_src_lengths = True
535
+
536
+ def step(
537
+ self,
538
+ step: int,
539
+ lprobs,
540
+ scores,
541
+ prev_output_tokens: Optional[Tensor] = None,
542
+ original_batch_idxs: Optional[Tensor] = None,
543
+ ):
544
+ min_lens = self.min_len_a * self.src_lengths + self.min_len_b
545
+ max_lens = self.max_len_a * self.src_lengths + self.max_len_b
546
+ lprobs[step < min_lens, :, self.eos] = -math.inf
547
+ lprobs[step >= max_lens, :, self.eos] = 0
548
+ return self.beam.step(step, lprobs, scores)
549
+
550
+
551
+ class DiverseBeamSearch(Search):
552
+ """Diverse Beam Search.
553
+
554
+ See "Diverse Beam Search: Decoding Diverse Solutions from Neural Sequence
555
+ Models" for details.
556
+
557
+ We only implement the Hamming Diversity penalty here, which performed best
558
+ in the original paper.
559
+ """
560
+
561
+ def __init__(self, tgt_dict, num_groups, diversity_strength):
562
+ super().__init__(tgt_dict)
563
+ self.num_groups = num_groups
564
+ self.diversity_strength = -diversity_strength
565
+ self.beam = BeamSearch(tgt_dict)
566
+
567
+ @torch.jit.export
568
+ def step(
569
+ self,
570
+ step: int,
571
+ lprobs,
572
+ scores,
573
+ prev_output_tokens: Optional[Tensor] = None,
574
+ original_batch_idxs: Optional[Tensor] = None,
575
+ ):
576
+ bsz, beam_size, vocab_size = lprobs.size()
577
+ if beam_size % self.num_groups != 0:
578
+ raise ValueError(
579
+ "DiverseBeamSearch requires --beam to be divisible by the number of groups"
580
+ )
581
+
582
+ # initialize diversity penalty
583
+ diversity_buf = torch.zeros(lprobs[:, 0, :].size()).to(lprobs)
584
+
585
+ scores_G, indices_G, beams_G = [], [], []
586
+ for g in range(self.num_groups):
587
+ lprobs_g = lprobs[:, g :: self.num_groups, :]
588
+ scores_g = scores[:, g :: self.num_groups, :] if step > 0 else None
589
+
590
+ # apply diversity penalty
591
+ if g > 0:
592
+ lprobs_g = torch.add(
593
+ lprobs_g,
594
+ other=diversity_buf.unsqueeze(1),
595
+ alpha=self.diversity_strength,
596
+ )
597
+ else:
598
+ lprobs_g = lprobs_g.contiguous()
599
+
600
+ scores_buf, indices_buf, beams_buf = self.beam.step(
601
+ step, lprobs_g, scores_g
602
+ )
603
+ beams_buf.mul_(self.num_groups).add_(g)
604
+
605
+ scores_G.append(scores_buf.clone())
606
+ indices_G.append(indices_buf.clone())
607
+ beams_G.append(beams_buf.clone())
608
+
609
+ # update diversity penalty
610
+ diversity_buf.scatter_add_(
611
+ 1, indices_buf, torch.ones(indices_buf.size()).to(diversity_buf)
612
+ )
613
+
614
+ # interleave results from different groups
615
+ scores_buf = torch.stack(scores_G, dim=2).view(bsz, -1)
616
+ indices_buf = torch.stack(indices_G, dim=2).view(bsz, -1)
617
+ beams_buf = torch.stack(beams_G, dim=2).view(bsz, -1)
618
+ return scores_buf, indices_buf, beams_buf
619
+
620
+
621
+ class Sampling(Search):
622
+ sampling_topk: int
623
+ sampling_topp: float
624
+
625
+ def __init__(self, tgt_dict, sampling_topk=-1, sampling_topp=-1.0):
626
+ super().__init__(tgt_dict)
627
+ self.sampling_topk = sampling_topk
628
+ self.sampling_topp = sampling_topp
629
+
630
+ def _sample_topp(self, lprobs):
631
+ """Sample among the smallest set of elements whose cumulative probability mass exceeds p.
632
+
633
+ See `"The Curious Case of Neural Text Degeneration"
634
+ (Holtzman et al., 2019) <https://arxiv.org/abs/1904.09751>`_.
635
+
636
+ Args:
637
+ lprobs: (bsz x input_beam_size x vocab_size)
638
+ the model's log-probabilities over the vocabulary at the current step
639
+
640
+ Return: A tuple of (trimed_probs, truncated_indices) where:
641
+ trimed_probs: (bsz x input_beam_size x ?)
642
+ the model's probabilities over the elements selected to sample from. The
643
+ width of the third dimension is determined by top-P.
644
+ truncated_indices: (bsz x input_beam_size x ?)
645
+ the indices of the chosen elements.
646
+ """
647
+ probs = lprobs.exp_()
648
+
649
+ # sort the last dimension (vocab dimension) in descending order
650
+ sorted_probs, sorted_indices = probs.sort(descending=True)
651
+
652
+ # compute a mask to indicate the words to be included in the top-P set.
653
+ cumsum_probs = sorted_probs.cumsum(dim=2)
654
+ mask = cumsum_probs.lt(self.sampling_topp)
655
+
656
+ # note that mask was computed by 'lt'. One more word needs to be included
657
+ # so that the cumulative probability mass can exceed p.
658
+ cumsum_mask = mask.cumsum(dim=2)
659
+ last_included = cumsum_mask[:, :, -1:]
660
+ last_included.clamp_(0, mask.size()[2] - 1)
661
+ mask = mask.scatter_(2, last_included, 1)
662
+
663
+ # truncate unnecessary dims.
664
+ max_dim = last_included.max()
665
+ truncated_mask = mask[:, :, : max_dim + 1]
666
+ truncated_probs = sorted_probs[:, :, : max_dim + 1]
667
+ truncated_indices = sorted_indices[:, :, : max_dim + 1]
668
+
669
+ # trim the words that are not in top-P by setting their probabilities
670
+ # to 0, so that they would not be sampled later.
671
+ trim_mask = ~truncated_mask
672
+ trimed_probs = truncated_probs.masked_fill_(trim_mask, 0)
673
+ return trimed_probs, truncated_indices
674
+
675
+ @torch.jit.export
676
+ def step(
677
+ self,
678
+ step: int,
679
+ lprobs,
680
+ scores,
681
+ prev_output_tokens: Optional[Tensor] = None,
682
+ original_batch_idxs: Optional[Tensor] = None,
683
+ ):
684
+ bsz, beam_size, vocab_size = lprobs.size()
685
+
686
+ if step == 0:
687
+ # at the first step all hypotheses are equally likely, so use
688
+ # only the first beam
689
+ lprobs = lprobs[:, ::beam_size, :].contiguous()
690
+
691
+ if self.sampling_topp > 0:
692
+ # only sample from the smallest set of words whose cumulative probability mass exceeds p
693
+ probs, top_indices = self._sample_topp(lprobs)
694
+ elif self.sampling_topk > 0:
695
+ # only sample from top-k candidates
696
+ lprobs, top_indices = lprobs.topk(self.sampling_topk)
697
+ probs = lprobs.exp_()
698
+ else:
699
+ probs = lprobs.exp_()
700
+
701
+ # dummy data to be consistent with true branch for type check
702
+ top_indices = torch.empty(0).to(probs)
703
+ # sample
704
+ if step == 0:
705
+ indices_buf = torch.multinomial(
706
+ probs.view(bsz, -1),
707
+ beam_size,
708
+ replacement=True,
709
+ ).view(bsz, beam_size)
710
+ else:
711
+ indices_buf = torch.multinomial(
712
+ probs.view(bsz * beam_size, -1),
713
+ 1,
714
+ replacement=True,
715
+ ).view(bsz, beam_size)
716
+
717
+ if step == 0:
718
+ # expand to beam size
719
+ probs = probs.expand(bsz, beam_size, -1)
720
+
721
+ # gather scores
722
+ scores_buf = torch.gather(probs, dim=2, index=indices_buf.unsqueeze(-1))
723
+ scores_buf = scores_buf.log_().view(bsz, -1)
724
+
725
+ # remap indices if using top-k or top-P sampling
726
+ if self.sampling_topk > 0 or self.sampling_topp > 0:
727
+ indices_buf = torch.gather(
728
+ top_indices.expand(bsz, beam_size, -1),
729
+ dim=2,
730
+ index=indices_buf.unsqueeze(-1),
731
+ ).squeeze(2)
732
+
733
+ if step == 0:
734
+ beams_buf = indices_buf.new_zeros(bsz, beam_size)
735
+ else:
736
+ beams_buf = torch.arange(0, beam_size).to(indices_buf).repeat(bsz, 1)
737
+ # make scores cumulative
738
+ scores_buf.add_(
739
+ torch.gather(scores[:, :, step - 1], dim=1, index=beams_buf)
740
+ )
741
+
742
+ return scores_buf, indices_buf, beams_buf
743
+
744
+
745
+ class DiverseSiblingsSearch(Search):
746
+ """
747
+ Beam search with diverse siblings.
748
+
749
+ See "A Simple, Fast Diverse Decoding Algorithm for Neural Generation" for details.
750
+ https://arxiv.org/abs/1611.08562
751
+
752
+ 1/ Calculate hypotheses for each beam
753
+ 2/ Intra-sibling ordering
754
+ 3/ Rewrite scores
755
+ 4/ Choose top K hypotheses
756
+
757
+ if diversity_rate == 0 is equivalent to BeamSearch
758
+ """
759
+
760
+ def __init__(self, tgt_dict, diversity_rate):
761
+ super().__init__(tgt_dict)
762
+ self.diversity_rate = diversity_rate
763
+ self.beam = BeamSearch(tgt_dict)
764
+
765
+ def step(
766
+ self,
767
+ step: int,
768
+ lprobs,
769
+ scores,
770
+ prev_output_tokens: Optional[Tensor] = None,
771
+ original_batch_idxs: Optional[Tensor] = None,
772
+ ):
773
+ bsz, beam_size, vocab_size = lprobs.size()
774
+ k = min(
775
+ # Take the best 2 x beam_size predictions. We'll choose the first
776
+ # beam_size of these which don't predict eos to continue with.
777
+ beam_size * 2,
778
+ lprobs.view(bsz, -1).size(1) - 1, # -1 so we never select pad
779
+ )
780
+ s_list: List[Tensor]
781
+ i_list: List[Tensor]
782
+ s_list = [torch.empty(0).to(lprobs) for i in range(beam_size)]
783
+ i_list = [torch.LongTensor().to(device=lprobs.device) for i in range(beam_size)]
784
+ sibling_score = torch.arange(1, k + 1).to(lprobs) * self.diversity_rate
785
+
786
+ if step == 0:
787
+ return self.beam.step(step, lprobs, scores)
788
+ lprobs.add_(scores[:, :, step - 1].unsqueeze(-1))
789
+
790
+ # 1/ Calculate hypotheses for each beam
791
+ for i in range(beam_size):
792
+ torch.topk(lprobs[:, i, :].view(bsz, -1), k, out=(s_list[i], i_list[i]))
793
+ i_list[i].fmod_(vocab_size)
794
+
795
+ # 2/ Intra-sibling ordering by default from topk + 3/ Rewrite scores
796
+ s_list[i].sub_(sibling_score)
797
+
798
+ # 4/ Choose top K hypotheses
799
+ indices = torch.stack(i_list, dim=1).view(bsz, -1)
800
+
801
+ final_scores = torch.empty(0).to(lprobs)
802
+ final_indices = torch.LongTensor().to(device=lprobs.device)
803
+ final_beams = torch.LongTensor().to(device=lprobs.device)
804
+ (final_scores, final_indices) = torch.topk(
805
+ torch.stack(s_list, dim=1).view(bsz, -1),
806
+ k,
807
+ )
808
+
809
+ final_beams = final_indices // k
810
+
811
+ for i in range(bsz):
812
+ final_indices[i] = indices[i][final_indices[i]]
813
+
814
+ return final_scores, final_indices, final_beams
models/sequence_generator.py ADDED
@@ -0,0 +1,1053 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The OFA-Sys Team.
2
+ # All rights reserved.
3
+ # This source code is licensed under the Apache 2.0 license
4
+ # found in the LICENSE file in the root directory.
5
+
6
+ import math
7
+ from typing import Dict, List, Optional
8
+ import sys
9
+
10
+ import torch
11
+ import torch.nn as nn
12
+ from fairseq import search, utils
13
+ from fairseq.models import FairseqIncrementalDecoder
14
+ from torch import Tensor
15
+ from fairseq.ngram_repeat_block import NGramRepeatBlock
16
+
17
+ from data import data_utils
18
+
19
+ class SequenceGenerator(nn.Module):
20
+ def __init__(
21
+ self,
22
+ models,
23
+ tgt_dict,
24
+ beam_size=1,
25
+ max_len_a=0,
26
+ max_len_b=200,
27
+ max_len=0,
28
+ min_len=1,
29
+ normalize_scores=True,
30
+ len_penalty=1.0,
31
+ unk_penalty=0.0,
32
+ temperature=1.0,
33
+ match_source_len=False,
34
+ no_repeat_ngram_size=0,
35
+ search_strategy=None,
36
+ eos=None,
37
+ symbols_to_strip_from_output=None,
38
+ lm_model=None,
39
+ lm_weight=1.0,
40
+ constraint_trie=None,
41
+ constraint_range=None,
42
+ gen_code=False,
43
+ gen_box=False,
44
+ ignore_eos=False,
45
+ zero_shot=False
46
+ ):
47
+ """Generates translations of a given source sentence.
48
+
49
+ Args:
50
+ models (List[~fairseq.models.FairseqModel]): ensemble of models,
51
+ currently support fairseq.models.TransformerModel for scripting
52
+ beam_size (int, optional): beam width (default: 1)
53
+ max_len_a/b (int, optional): generate sequences of maximum length
54
+ ax + b, where x is the source length
55
+ max_len (int, optional): the maximum length of the generated output
56
+ (not including end-of-sentence)
57
+ min_len (int, optional): the minimum length of the generated output
58
+ (not including end-of-sentence)
59
+ normalize_scores (bool, optional): normalize scores by the length
60
+ of the output (default: True)
61
+ len_penalty (float, optional): length penalty, where <1.0 favors
62
+ shorter, >1.0 favors longer sentences (default: 1.0)
63
+ unk_penalty (float, optional): unknown word penalty, where <0
64
+ produces more unks, >0 produces fewer (default: 0.0)
65
+ temperature (float, optional): temperature, where values
66
+ >1.0 produce more uniform samples and values <1.0 produce
67
+ sharper samples (default: 1.0)
68
+ match_source_len (bool, optional): outputs should match the source
69
+ length (default: False)
70
+ """
71
+ super().__init__()
72
+ if isinstance(models, EnsembleModel):
73
+ self.model = models
74
+ else:
75
+ self.model = EnsembleModel(models)
76
+ self.gen_code = gen_code
77
+ self.gen_box = gen_box
78
+ self.ignore_eos = ignore_eos
79
+ self.tgt_dict = tgt_dict
80
+ self.pad = tgt_dict.pad()
81
+ self.unk = tgt_dict.unk()
82
+ self.bos = tgt_dict.bos()
83
+ self.eos = tgt_dict.eos() if eos is None else eos
84
+ self.symbols_to_strip_from_output = (
85
+ symbols_to_strip_from_output.union({self.eos})
86
+ if symbols_to_strip_from_output is not None
87
+ else {self.bos, self.eos}
88
+ )
89
+ self.vocab_size = len(tgt_dict)
90
+ self.beam_size = beam_size
91
+ # the max beam size is the dictionary size - 1, since we never select pad
92
+ self.beam_size = min(beam_size, self.vocab_size - 1)
93
+ self.max_len_a = max_len_a
94
+ self.max_len_b = max_len_b
95
+ self.min_len = min_len
96
+ self.max_len = max_len or self.model.max_decoder_positions()
97
+
98
+ self.normalize_scores = normalize_scores
99
+ self.len_penalty = len_penalty
100
+ self.unk_penalty = unk_penalty
101
+ self.temperature = temperature
102
+ self.match_source_len = match_source_len
103
+ self.zero_shot = zero_shot
104
+
105
+ if no_repeat_ngram_size > 0:
106
+ self.repeat_ngram_blocker = NGramRepeatBlock(no_repeat_ngram_size)
107
+ else:
108
+ self.repeat_ngram_blocker = None
109
+
110
+ assert temperature > 0, "--temperature must be greater than 0"
111
+
112
+ self.search = (
113
+ search.BeamSearch(tgt_dict) if search_strategy is None else search_strategy
114
+ )
115
+ # We only need to set src_lengths in LengthConstrainedBeamSearch.
116
+ # As a module attribute, setting it would break in multithread
117
+ # settings when the model is shared.
118
+ self.should_set_src_lengths = (
119
+ hasattr(self.search, "needs_src_lengths") and self.search.needs_src_lengths
120
+ )
121
+
122
+ self.model.eval()
123
+
124
+ self.lm_model = lm_model
125
+ self.lm_weight = lm_weight
126
+ if self.lm_model is not None:
127
+ self.lm_model.eval()
128
+
129
+ self.constraint_trie = constraint_trie
130
+
131
+ self.constraint_start = None
132
+ self.constraint_end = None
133
+ if constraint_range is not None:
134
+ constraint_start, constraint_end = constraint_range.split(',')
135
+ self.constraint_start = int(constraint_start)
136
+ self.constraint_end = int(constraint_end)
137
+
138
+ def cuda(self):
139
+ self.model.cuda()
140
+ return self
141
+
142
+ @torch.no_grad()
143
+ def forward(
144
+ self,
145
+ sample: Dict[str, Dict[str, Tensor]],
146
+ prefix_tokens: Optional[Tensor] = None,
147
+ bos_token: Optional[int] = None,
148
+ ):
149
+ """Generate a batch of translations.
150
+
151
+ Args:
152
+ sample (dict): batch
153
+ prefix_tokens (torch.LongTensor, optional): force decoder to begin
154
+ with these tokens
155
+ bos_token (int, optional): beginning of sentence token
156
+ (default: self.eos)
157
+ """
158
+ return self._generate(sample, prefix_tokens, bos_token=bos_token)
159
+
160
+ # TODO(myleott): unused, deprecate after pytorch-translate migration
161
+ def generate_batched_itr(self, data_itr, beam_size=None, cuda=False, timer=None):
162
+ """Iterate over a batched dataset and yield individual translations.
163
+ Args:
164
+ cuda (bool, optional): use GPU for generation
165
+ timer (StopwatchMeter, optional): time generations
166
+ """
167
+ for sample in data_itr:
168
+ s = utils.move_to_cuda(sample) if cuda else sample
169
+ if "net_input" not in s:
170
+ continue
171
+ input = s["net_input"]
172
+ # model.forward normally channels prev_output_tokens into the decoder
173
+ # separately, but SequenceGenerator directly calls model.encoder
174
+ encoder_input = {
175
+ k: v for k, v in input.items() if k != "prev_output_tokens"
176
+ }
177
+ if timer is not None:
178
+ timer.start()
179
+ with torch.no_grad():
180
+ hypos = self.generate(encoder_input)
181
+ if timer is not None:
182
+ timer.stop(sum(len(h[0]["tokens"]) for h in hypos))
183
+ for i, id in enumerate(s["id"].data):
184
+ # remove padding
185
+ src = utils.strip_pad(input["src_tokens"].data[i, :], self.pad)
186
+ ref = (
187
+ utils.strip_pad(s["target"].data[i, :], self.pad)
188
+ if s["target"] is not None
189
+ else None
190
+ )
191
+ yield id, src, ref, hypos[i]
192
+
193
+ @torch.no_grad()
194
+ def generate(self, models, sample: Dict[str, Dict[str, Tensor]], **kwargs) -> List[List[Dict[str, Tensor]]]:
195
+ """Generate translations. Match the api of other fairseq generators.
196
+
197
+ Args:
198
+ models (List[~fairseq.models.FairseqModel]): ensemble of models
199
+ sample (dict): batch
200
+ prefix_tokens (torch.LongTensor, optional): force decoder to begin
201
+ with these tokens
202
+ constraints (torch.LongTensor, optional): force decoder to include
203
+ the list of constraints
204
+ bos_token (int, optional): beginning of sentence token
205
+ (default: self.eos)
206
+ """
207
+ return self._generate(models, sample, **kwargs)
208
+
209
+ def _generate(
210
+ self,
211
+ models,
212
+ sample: Dict[str, Dict[str, Tensor]],
213
+ prefix_tokens: Optional[Tensor] = None,
214
+ constraints: Optional[Tensor] = None,
215
+ bos_token: Optional[int] = None,
216
+ ):
217
+ model = EnsembleModel(models)
218
+ incremental_states = torch.jit.annotate(
219
+ List[Dict[str, Dict[str, Optional[Tensor]]]],
220
+ [
221
+ torch.jit.annotate(Dict[str, Dict[str, Optional[Tensor]]], {})
222
+ for i in range(model.models_size)
223
+ ],
224
+ )
225
+ net_input = sample["net_input"]
226
+
227
+ if "src_tokens" in net_input:
228
+ src_tokens = net_input["src_tokens"]
229
+ # length of the source text being the character length except EndOfSentence and pad
230
+ src_lengths = (
231
+ (src_tokens.ne(self.eos) & src_tokens.ne(self.pad)).long().sum(dim=1)
232
+ )
233
+ elif "source" in net_input:
234
+ src_tokens = net_input["source"]
235
+ src_lengths = (
236
+ net_input["padding_mask"].size(-1) - net_input["padding_mask"].sum(-1)
237
+ if net_input["padding_mask"] is not None
238
+ else torch.tensor(src_tokens.size(-1)).to(src_tokens)
239
+ )
240
+ elif "features" in net_input:
241
+ src_tokens = net_input["features"]
242
+ src_lengths = (
243
+ net_input["padding_mask"].size(-1) - net_input["padding_mask"].sum(-1)
244
+ if net_input["padding_mask"] is not None
245
+ else torch.tensor(src_tokens.size(-1)).to(src_tokens)
246
+ )
247
+ else:
248
+ raise Exception("expected src_tokens or source in net input. input keys: " + str(net_input.keys()))
249
+
250
+ # bsz: total number of sentences in beam
251
+ # Note that src_tokens may have more than 2 dimensions (i.e. audio features)
252
+ bsz, src_len = src_tokens.size()[:2]
253
+ beam_size = self.beam_size
254
+
255
+ if constraints is not None and not self.search.supports_constraints:
256
+ raise NotImplementedError(
257
+ "Target-side constraints were provided, but search method doesn't support them"
258
+ )
259
+
260
+ # Initialize constraints, when active
261
+ self.search.init_constraints(constraints, beam_size)
262
+
263
+ max_len: int = -1
264
+ if self.match_source_len:
265
+ max_len = src_lengths.max().item()
266
+ else:
267
+ max_len = int(self.max_len_a * src_len + self.max_len_b)
268
+ assert (
269
+ self.min_len <= max_len
270
+ ), "min_len cannot be larger than max_len, please adjust these!"
271
+ # compute the encoder output for each beam
272
+ with torch.autograd.profiler.record_function("EnsembleModel: forward_encoder"):
273
+ encoder_outs = model.forward_encoder(net_input)
274
+
275
+ # placeholder of indices for bsz * beam_size to hold tokens and accumulative scores
276
+ new_order = torch.arange(bsz).view(-1, 1).repeat(1, beam_size).view(-1)
277
+ new_order = new_order.to(src_tokens.device).long()
278
+ encoder_outs = model.reorder_encoder_out(encoder_outs, new_order)
279
+ # ensure encoder_outs is a List.
280
+ assert encoder_outs is not None
281
+
282
+ # initialize buffers
283
+ scores = (
284
+ torch.zeros(bsz * beam_size, max_len + 1).to(src_tokens).float()
285
+ ) # +1 for eos; pad is never chosen for scoring
286
+ tokens = (
287
+ torch.zeros(bsz * beam_size, max_len + 2)
288
+ .to(src_tokens)
289
+ .long()
290
+ .fill_(self.pad)
291
+ ) # +2 for eos and pad
292
+ # tokens[:, 0] = self.eos if bos_token is None else bos_token
293
+ tokens[:, 0] = self.bos
294
+ attn: Optional[Tensor] = None
295
+
296
+ # A list that indicates candidates that should be ignored.
297
+ # For example, suppose we're sampling and have already finalized 2/5
298
+ # samples. Then cands_to_ignore would mark 2 positions as being ignored,
299
+ # so that we only finalize the remaining 3 samples.
300
+ cands_to_ignore = (
301
+ torch.zeros(bsz, beam_size).to(src_tokens).eq(-1)
302
+ ) # forward and backward-compatible False mask
303
+
304
+ # list of completed sentences
305
+ finalized = torch.jit.annotate(
306
+ List[List[Dict[str, Tensor]]],
307
+ [torch.jit.annotate(List[Dict[str, Tensor]], []) for i in range(bsz)],
308
+ ) # contains lists of dictionaries of infomation about the hypothesis being finalized at each step
309
+
310
+ # a boolean array indicating if the sentence at the index is finished or not
311
+ finished = [False for i in range(bsz)]
312
+ num_remaining_sent = bsz # number of sentences remaining
313
+
314
+ # number of candidate hypos per step
315
+ cand_size = 2 * beam_size # 2 x beam size in case half are EOS
316
+
317
+ # offset arrays for converting between different indexing schemes
318
+ bbsz_offsets = (
319
+ (torch.arange(0, bsz) * beam_size)
320
+ .unsqueeze(1)
321
+ .type_as(tokens)
322
+ .to(src_tokens.device)
323
+ )
324
+ cand_offsets = torch.arange(0, cand_size).type_as(tokens).to(src_tokens.device)
325
+
326
+ reorder_state: Optional[Tensor] = None
327
+ batch_idxs: Optional[Tensor] = None
328
+
329
+ original_batch_idxs: Optional[Tensor] = None
330
+ if "id" in sample and isinstance(sample["id"], Tensor):
331
+ original_batch_idxs = sample["id"]
332
+ else:
333
+ original_batch_idxs = torch.arange(0, bsz).type_as(tokens)
334
+
335
+ for step in range(max_len + 1): # one extra step for EOS marker
336
+ # reorder decoder internal states based on the prev choice of beams
337
+ if reorder_state is not None:
338
+ if batch_idxs is not None:
339
+ # update beam indices to take into account removed sentences
340
+ corr = batch_idxs - torch.arange(batch_idxs.numel()).type_as(
341
+ batch_idxs
342
+ )
343
+ reorder_state.view(-1, beam_size).add_(
344
+ corr.unsqueeze(-1) * beam_size
345
+ )
346
+ original_batch_idxs = original_batch_idxs[batch_idxs]
347
+ model.reorder_incremental_state(incremental_states, reorder_state)
348
+ encoder_outs = model.reorder_encoder_out(
349
+ encoder_outs, reorder_state
350
+ )
351
+ with torch.autograd.profiler.record_function("EnsembleModel: forward_decoder"):
352
+ lprobs, avg_attn_scores = model.forward_decoder(
353
+ tokens[:, : step + 1],
354
+ encoder_outs,
355
+ incremental_states,
356
+ self.temperature,
357
+ constraint_trie=self.constraint_trie,
358
+ constraint_start=self.constraint_start,
359
+ constraint_end=self.constraint_end,
360
+ gen_code=self.gen_code,
361
+ zero_shot=self.zero_shot,
362
+ prefix_tokens=prefix_tokens
363
+ )
364
+
365
+ if self.lm_model is not None:
366
+ lm_out = self.lm_model(tokens[:, : step + 1])
367
+ probs = self.lm_model.get_normalized_probs(
368
+ lm_out, log_probs=True, sample=None
369
+ )
370
+ probs = probs[:, -1, :] * self.lm_weight
371
+ lprobs += probs
372
+ # handle prefix tokens (possibly with different lengths)
373
+ if (
374
+ prefix_tokens is not None
375
+ and step < prefix_tokens.size(1)
376
+ and step < max_len
377
+ ):
378
+ lprobs, tokens, scores = self._prefix_tokens(
379
+ step, lprobs, scores, tokens, prefix_tokens, beam_size
380
+ )
381
+ elif step < self.min_len:
382
+ # minimum length constraint (does not apply if using prefix_tokens)
383
+ lprobs[:, self.eos] = -math.inf
384
+
385
+ lprobs[lprobs != lprobs] = torch.tensor(-math.inf).to(lprobs)
386
+
387
+ lprobs[:, self.pad] = -math.inf # never select pad
388
+ lprobs[:, self.unk] -= self.unk_penalty # apply unk penalty
389
+
390
+ if (self.gen_code or self.gen_box) and step < max_len:
391
+ lprobs[:, :4] = -math.inf
392
+ if self.gen_box:
393
+ lprobs[:, -1] = -math.inf
394
+ if (step + 1) % 5 == 0:
395
+ lprobs[:, self.constraint_start:59457] = -math.inf
396
+ else:
397
+ lprobs[:, 59457:] = -math.inf
398
+
399
+ # handle max length constraint
400
+ if step >= max_len:
401
+ lprobs[:, : self.eos] = -math.inf
402
+ lprobs[:, self.eos + 1 :] = -math.inf
403
+ if self.ignore_eos:
404
+ lprobs[:, self.eos] = 1
405
+
406
+ # Record attention scores, only support avg_attn_scores is a Tensor
407
+ if avg_attn_scores is not None:
408
+ if attn is None:
409
+ attn = torch.empty(
410
+ bsz * beam_size, avg_attn_scores.size(1), max_len + 2
411
+ ).to(scores)
412
+ attn[:, :, step + 1].copy_(avg_attn_scores)
413
+
414
+ scores = scores.type_as(lprobs)
415
+ eos_bbsz_idx = torch.empty(0).to(
416
+ tokens
417
+ ) # indices of hypothesis ending with eos (finished sentences)
418
+ eos_scores = torch.empty(0).to(
419
+ scores
420
+ ) # scores of hypothesis ending with eos (finished sentences)
421
+
422
+ if self.should_set_src_lengths:
423
+ self.search.set_src_lengths(src_lengths)
424
+
425
+ if self.repeat_ngram_blocker is not None:
426
+ lprobs = self.repeat_ngram_blocker(tokens, lprobs, bsz, beam_size, step)
427
+
428
+ # Shape: (batch, cand_size)
429
+ cand_scores, cand_indices, cand_beams = self.search.step(
430
+ step,
431
+ lprobs.view(bsz, -1, self.vocab_size),
432
+ scores.view(bsz, beam_size, -1)[:, :, :step],
433
+ tokens[:, : step + 1],
434
+ original_batch_idxs,
435
+ )
436
+
437
+ # cand_bbsz_idx contains beam indices for the top candidate
438
+ # hypotheses, with a range of values: [0, bsz*beam_size),
439
+ # and dimensions: [bsz, cand_size]
440
+ cand_bbsz_idx = cand_beams.add(bbsz_offsets)
441
+
442
+ # finalize hypotheses that end in eos
443
+ # Shape of eos_mask: (batch size, beam size)
444
+ eos_mask = cand_indices.eq(self.eos) & cand_scores.ne(-math.inf)
445
+ eos_mask[:, :beam_size][cands_to_ignore] = torch.tensor(0).to(eos_mask)
446
+
447
+ # only consider eos when it's among the top beam_size indices
448
+ # Now we know what beam item(s) to finish
449
+ # Shape: 1d list of absolute-numbered
450
+ eos_bbsz_idx = torch.masked_select(
451
+ cand_bbsz_idx[:, :beam_size], mask=eos_mask[:, :beam_size]
452
+ )
453
+
454
+ finalized_sents: List[int] = []
455
+ if eos_bbsz_idx.numel() > 0:
456
+ eos_scores = torch.masked_select(
457
+ cand_scores[:, :beam_size], mask=eos_mask[:, :beam_size]
458
+ )
459
+
460
+ finalized_sents = self.finalize_hypos(
461
+ step,
462
+ eos_bbsz_idx,
463
+ eos_scores,
464
+ tokens,
465
+ scores,
466
+ finalized,
467
+ finished,
468
+ beam_size,
469
+ attn,
470
+ src_lengths,
471
+ max_len,
472
+ )
473
+ num_remaining_sent -= len(finalized_sents)
474
+
475
+ assert num_remaining_sent >= 0
476
+ if num_remaining_sent == 0:
477
+ break
478
+ if self.search.stop_on_max_len and step >= max_len:
479
+ break
480
+ assert step < max_len, f"{step} < {max_len}"
481
+
482
+ # Remove finalized sentences (ones for which {beam_size}
483
+ # finished hypotheses have been generated) from the batch.
484
+ if len(finalized_sents) > 0:
485
+ new_bsz = bsz - len(finalized_sents)
486
+
487
+ # construct batch_idxs which holds indices of batches to keep for the next pass
488
+ batch_mask = torch.ones(
489
+ bsz, dtype=torch.bool, device=cand_indices.device
490
+ )
491
+ batch_mask[finalized_sents] = False
492
+ # TODO replace `nonzero(as_tuple=False)` after TorchScript supports it
493
+ batch_idxs = torch.arange(
494
+ bsz, device=cand_indices.device
495
+ ).masked_select(batch_mask)
496
+
497
+ # Choose the subset of the hypothesized constraints that will continue
498
+ self.search.prune_sentences(batch_idxs)
499
+
500
+ eos_mask = eos_mask[batch_idxs]
501
+ cand_beams = cand_beams[batch_idxs]
502
+ bbsz_offsets.resize_(new_bsz, 1)
503
+ cand_bbsz_idx = cand_beams.add(bbsz_offsets)
504
+ cand_scores = cand_scores[batch_idxs]
505
+ cand_indices = cand_indices[batch_idxs]
506
+
507
+ if prefix_tokens is not None:
508
+ prefix_tokens = prefix_tokens[batch_idxs]
509
+ src_lengths = src_lengths[batch_idxs]
510
+ cands_to_ignore = cands_to_ignore[batch_idxs]
511
+
512
+ scores = scores.view(bsz, -1)[batch_idxs].view(new_bsz * beam_size, -1)
513
+ tokens = tokens.view(bsz, -1)[batch_idxs].view(new_bsz * beam_size, -1)
514
+ if attn is not None:
515
+ attn = attn.view(bsz, -1)[batch_idxs].view(
516
+ new_bsz * beam_size, attn.size(1), -1
517
+ )
518
+ bsz = new_bsz
519
+ else:
520
+ batch_idxs = None
521
+
522
+ # Set active_mask so that values > cand_size indicate eos hypos
523
+ # and values < cand_size indicate candidate active hypos.
524
+ # After, the min values per row are the top candidate active hypos
525
+
526
+ # Rewrite the operator since the element wise or is not supported in torchscript.
527
+
528
+ eos_mask[:, :beam_size] = ~((~cands_to_ignore) & (~eos_mask[:, :beam_size]))
529
+ active_mask = torch.add(
530
+ eos_mask.type_as(cand_offsets) * cand_size,
531
+ cand_offsets[: eos_mask.size(1)],
532
+ )
533
+
534
+ # get the top beam_size active hypotheses, which are just
535
+ # the hypos with the smallest values in active_mask.
536
+ # {active_hypos} indicates which {beam_size} hypotheses
537
+ # from the list of {2 * beam_size} candidates were
538
+ # selected. Shapes: (batch size, beam size)
539
+ new_cands_to_ignore, active_hypos = torch.topk(
540
+ active_mask, k=beam_size, dim=1, largest=False
541
+ )
542
+
543
+ # update cands_to_ignore to ignore any finalized hypos.
544
+ cands_to_ignore = new_cands_to_ignore.ge(cand_size)[:, :beam_size]
545
+ # Make sure there is at least one active item for each sentence in the batch.
546
+ assert (~cands_to_ignore).any(dim=1).all()
547
+
548
+ # update cands_to_ignore to ignore any finalized hypos
549
+
550
+ # {active_bbsz_idx} denotes which beam number is continued for each new hypothesis (a beam
551
+ # can be selected more than once).
552
+ active_bbsz_idx = torch.gather(cand_bbsz_idx, dim=1, index=active_hypos)
553
+ active_scores = torch.gather(cand_scores, dim=1, index=active_hypos)
554
+
555
+ active_bbsz_idx = active_bbsz_idx.view(-1)
556
+ active_scores = active_scores.view(-1)
557
+
558
+ # copy tokens and scores for active hypotheses
559
+
560
+ # Set the tokens for each beam (can select the same row more than once)
561
+ tokens[:, : step + 1] = torch.index_select(
562
+ tokens[:, : step + 1], dim=0, index=active_bbsz_idx
563
+ )
564
+ # Select the next token for each of them
565
+ tokens.view(bsz, beam_size, -1)[:, :, step + 1] = torch.gather(
566
+ cand_indices, dim=1, index=active_hypos
567
+ )
568
+ if step > 0:
569
+ scores[:, :step] = torch.index_select(
570
+ scores[:, :step], dim=0, index=active_bbsz_idx
571
+ )
572
+ scores.view(bsz, beam_size, -1)[:, :, step] = torch.gather(
573
+ cand_scores, dim=1, index=active_hypos
574
+ )
575
+
576
+ # Update constraints based on which candidates were selected for the next beam
577
+ self.search.update_constraints(active_hypos)
578
+
579
+ # copy attention for active hypotheses
580
+ if attn is not None:
581
+ attn[:, :, : step + 2] = torch.index_select(
582
+ attn[:, :, : step + 2], dim=0, index=active_bbsz_idx
583
+ )
584
+
585
+ # reorder incremental state in decoder
586
+ reorder_state = active_bbsz_idx
587
+
588
+ # sort by score descending
589
+ for sent in range(len(finalized)):
590
+ scores = torch.tensor(
591
+ [float(elem["score"].item()) for elem in finalized[sent]]
592
+ )
593
+ _, sorted_scores_indices = torch.sort(scores, descending=True)
594
+ finalized[sent] = [finalized[sent][ssi] for ssi in sorted_scores_indices]
595
+ finalized[sent] = torch.jit.annotate(
596
+ List[Dict[str, Tensor]], finalized[sent]
597
+ )
598
+ return finalized
599
+
600
+ def _prefix_tokens(
601
+ self, step: int, lprobs, scores, tokens, prefix_tokens, beam_size: int
602
+ ):
603
+ """Handle prefix tokens"""
604
+ prefix_toks = prefix_tokens[:, step].unsqueeze(-1).repeat(1, beam_size).view(-1)
605
+ prefix_lprobs = lprobs.gather(-1, prefix_toks.unsqueeze(-1))
606
+ prefix_mask = prefix_toks.ne(self.pad)
607
+ if self.constraint_trie is None:
608
+ lprobs[prefix_mask] = torch.min(prefix_lprobs) - 1
609
+ else:
610
+ lprobs[prefix_mask] = -math.inf
611
+ lprobs[prefix_mask] = lprobs[prefix_mask].scatter(
612
+ -1, prefix_toks[prefix_mask].unsqueeze(-1), prefix_lprobs[prefix_mask]
613
+ )
614
+ # if prefix includes eos, then we should make sure tokens and
615
+ # scores are the same across all beams
616
+ eos_mask = prefix_toks.eq(self.eos)
617
+ if eos_mask.any():
618
+ # validate that the first beam matches the prefix
619
+ first_beam = tokens[eos_mask].view(-1, beam_size, tokens.size(-1))[
620
+ :, 0, 1 : step + 1
621
+ ]
622
+ eos_mask_batch_dim = eos_mask.view(-1, beam_size)[:, 0]
623
+ target_prefix = prefix_tokens[eos_mask_batch_dim][:, :step]
624
+ assert (first_beam == target_prefix).all()
625
+
626
+ # copy tokens, scores and lprobs from the first beam to all beams
627
+ tokens = self.replicate_first_beam(tokens, eos_mask_batch_dim, beam_size)
628
+ scores = self.replicate_first_beam(scores, eos_mask_batch_dim, beam_size)
629
+ lprobs = self.replicate_first_beam(lprobs, eos_mask_batch_dim, beam_size)
630
+ return lprobs, tokens, scores
631
+
632
+ def replicate_first_beam(self, tensor, mask, beam_size: int):
633
+ tensor = tensor.view(-1, beam_size, tensor.size(-1))
634
+ tensor[mask] = tensor[mask][:, :1, :]
635
+ return tensor.view(-1, tensor.size(-1))
636
+
637
+ def finalize_hypos(
638
+ self,
639
+ step: int,
640
+ bbsz_idx,
641
+ eos_scores,
642
+ tokens,
643
+ scores,
644
+ finalized: List[List[Dict[str, Tensor]]],
645
+ finished: List[bool],
646
+ beam_size: int,
647
+ attn: Optional[Tensor],
648
+ src_lengths,
649
+ max_len: int,
650
+ ):
651
+ """Finalize hypothesis, store finalized information in `finalized`, and change `finished` accordingly.
652
+ A sentence is finalized when {beam_size} finished items have been collected for it.
653
+
654
+ Returns number of sentences (not beam items) being finalized.
655
+ These will be removed from the batch and not processed further.
656
+ Args:
657
+ bbsz_idx (Tensor):
658
+ """
659
+ assert bbsz_idx.numel() == eos_scores.numel()
660
+
661
+ # clone relevant token and attention tensors.
662
+ # tokens is (batch * beam, max_len). So the index_select
663
+ # gets the newly EOS rows, then selects cols 1..{step + 2}
664
+ tokens_clone = tokens.index_select(0, bbsz_idx)[
665
+ :, 1 : step + 2
666
+ ] # skip the first index, which is EOS
667
+
668
+ tokens_clone[:, step] = self.eos
669
+ attn_clone = (
670
+ attn.index_select(0, bbsz_idx)[:, :, 1 : step + 2]
671
+ if attn is not None
672
+ else None
673
+ )
674
+
675
+ # compute scores per token position
676
+ pos_scores = scores.index_select(0, bbsz_idx)[:, : step + 1]
677
+ pos_scores[:, step] = eos_scores
678
+ # convert from cumulative to per-position scores
679
+ pos_scores[:, 1:] = pos_scores[:, 1:] - pos_scores[:, :-1]
680
+
681
+ # normalize sentence-level scores
682
+ if self.normalize_scores:
683
+ eos_scores /= (step + 1) ** self.len_penalty
684
+
685
+ # cum_unfin records which sentences in the batch are finished.
686
+ # It helps match indexing between (a) the original sentences
687
+ # in the batch and (b) the current, possibly-reduced set of
688
+ # sentences.
689
+ cum_unfin: List[int] = []
690
+ prev = 0
691
+ for f in finished:
692
+ if f:
693
+ prev += 1
694
+ else:
695
+ cum_unfin.append(prev)
696
+ cum_fin_tensor = torch.tensor(cum_unfin, dtype=torch.int).to(bbsz_idx)
697
+
698
+ unfin_idx = bbsz_idx // beam_size
699
+ sent = unfin_idx + torch.index_select(cum_fin_tensor, 0, unfin_idx)
700
+
701
+ # Create a set of "{sent}{unfin_idx}", where
702
+ # "unfin_idx" is the index in the current (possibly reduced)
703
+ # list of sentences, and "sent" is the index in the original,
704
+ # unreduced batch
705
+ # For every finished beam item
706
+ # sentence index in the current (possibly reduced) batch
707
+ seen = (sent << 32) + unfin_idx
708
+ unique_seen: List[int] = torch.unique(seen).tolist()
709
+
710
+ if self.match_source_len:
711
+ condition = step > torch.index_select(src_lengths, 0, unfin_idx)
712
+ eos_scores = torch.where(condition, torch.tensor(-math.inf), eos_scores)
713
+ sent_list: List[int] = sent.tolist()
714
+ for i in range(bbsz_idx.size()[0]):
715
+ # An input sentence (among those in a batch) is finished when
716
+ # beam_size hypotheses have been collected for it
717
+ if len(finalized[sent_list[i]]) < beam_size:
718
+ if attn_clone is not None:
719
+ # remove padding tokens from attn scores
720
+ hypo_attn = attn_clone[i]
721
+ else:
722
+ hypo_attn = torch.empty(0)
723
+
724
+ finalized[sent_list[i]].append(
725
+ {
726
+ "tokens": tokens_clone[i],
727
+ "score": eos_scores[i],
728
+ "attention": hypo_attn, # src_len x tgt_len
729
+ "alignment": torch.empty(0),
730
+ "positional_scores": pos_scores[i],
731
+ }
732
+ )
733
+
734
+ newly_finished: List[int] = []
735
+ for unique_s in unique_seen:
736
+ # check termination conditions for this sentence
737
+ unique_sent: int = unique_s >> 32
738
+ unique_unfin_idx: int = unique_s - (unique_sent << 32)
739
+
740
+ if not finished[unique_sent] and self.is_finished(
741
+ step, unique_unfin_idx, max_len, len(finalized[unique_sent]), beam_size
742
+ ):
743
+ finished[unique_sent] = True
744
+ newly_finished.append(unique_unfin_idx)
745
+
746
+ return newly_finished
747
+
748
+ def is_finished(
749
+ self,
750
+ step: int,
751
+ unfin_idx: int,
752
+ max_len: int,
753
+ finalized_sent_len: int,
754
+ beam_size: int,
755
+ ):
756
+ """
757
+ Check whether decoding for a sentence is finished, which
758
+ occurs when the list of finalized sentences has reached the
759
+ beam size, or when we reach the maximum length.
760
+ """
761
+ assert finalized_sent_len <= beam_size
762
+ if finalized_sent_len == beam_size or step == max_len:
763
+ return True
764
+ return False
765
+
766
+
767
+ class EnsembleModel(nn.Module):
768
+ """A wrapper around an ensemble of models."""
769
+
770
+ def __init__(self, models):
771
+ super().__init__()
772
+ self.models_size = len(models)
773
+ # method '__len__' is not supported in ModuleList for torch script
774
+ self.single_model = models[0]
775
+ self.models = nn.ModuleList(models)
776
+
777
+ self.has_incremental: bool = False
778
+ if all(
779
+ hasattr(m, "decoder") and isinstance(m.decoder, FairseqIncrementalDecoder)
780
+ for m in models
781
+ ):
782
+ self.has_incremental = True
783
+
784
+ def forward(self):
785
+ pass
786
+
787
+ def has_encoder(self):
788
+ return hasattr(self.single_model, "encoder")
789
+
790
+ def has_incremental_states(self):
791
+ return self.has_incremental
792
+
793
+ def max_decoder_positions(self):
794
+ return min([m.max_decoder_positions() for m in self.models if hasattr(m, "max_decoder_positions")] + [sys.maxsize])
795
+
796
+ @torch.jit.export
797
+ def forward_encoder(self, net_input: Dict[str, Tensor]):
798
+ if not self.has_encoder():
799
+ return None
800
+ return [model.encoder.forward_torchscript(net_input) for model in self.models]
801
+
802
+ @torch.jit.export
803
+ def forward_decoder(
804
+ self,
805
+ tokens,
806
+ encoder_outs: List[Dict[str, List[Tensor]]],
807
+ incremental_states: List[Dict[str, Dict[str, Optional[Tensor]]]],
808
+ temperature: float = 1.0,
809
+ constraint_trie=None,
810
+ constraint_start=None,
811
+ constraint_end=None,
812
+ gen_code=False,
813
+ zero_shot=False,
814
+ prefix_tokens=None
815
+ ):
816
+ log_probs = []
817
+ avg_attn: Optional[Tensor] = None
818
+ encoder_out: Optional[Dict[str, List[Tensor]]] = None
819
+ code_mask = (tokens.new_ones(tokens.size(0))*gen_code).bool()
820
+ for i, model in enumerate(self.models):
821
+ if self.has_encoder():
822
+ encoder_out = encoder_outs[i]
823
+ # decode each model
824
+ if self.has_incremental_states():
825
+ decoder_out = model.decoder.forward(
826
+ tokens,
827
+ code_masks=code_mask,
828
+ encoder_out=encoder_out,
829
+ incremental_state=incremental_states[i],
830
+ )
831
+ else:
832
+ if hasattr(model, "decoder"):
833
+ decoder_out = model.decoder.forward(tokens, code_masks=code_mask, encoder_out=encoder_out)
834
+ else:
835
+ decoder_out = model.forward(tokens)
836
+
837
+ attn: Optional[Tensor] = None
838
+ decoder_len = len(decoder_out)
839
+ if decoder_len > 1 and decoder_out[1] is not None:
840
+ if isinstance(decoder_out[1], Tensor):
841
+ attn = decoder_out[1]
842
+ else:
843
+ attn_holder = decoder_out[1]["attn"]
844
+ if isinstance(attn_holder, Tensor):
845
+ attn = attn_holder
846
+ elif attn_holder is not None:
847
+ attn = attn_holder[0]
848
+ if attn is not None:
849
+ attn = attn[:, -1, :]
850
+
851
+ decoder_out_tuple = (
852
+ decoder_out[0][:, -1:, :].div_(temperature),
853
+ None if decoder_len <= 1 else decoder_out[1],
854
+ )
855
+
856
+ beam_size = decoder_out_tuple[0].size(0) // prefix_tokens.size(0) if prefix_tokens is not None else 0
857
+ if constraint_trie is not None and not zero_shot:
858
+ assert constraint_start is None and constraint_end is None
859
+ constraint_masks = decoder_out_tuple[0].new_zeros(decoder_out_tuple[0].size()).bool()
860
+ constraint_prefix_tokens = tokens.tolist()
861
+ for token_index, constraint_prefix_token in enumerate(constraint_prefix_tokens):
862
+ prefix_len = prefix_tokens[token_index // beam_size].ne(1).sum().item() if prefix_tokens is not None else 0
863
+ if len(constraint_prefix_token) > prefix_len:
864
+ constraint_prefix_token = [0] + constraint_prefix_token[prefix_len+1:]
865
+ constraint_nodes = constraint_trie.get_next_layer(constraint_prefix_token)
866
+ constraint_masks[token_index][:, constraint_nodes] = True
867
+ else:
868
+ constraint_masks[token_index] = True
869
+ decoder_out_tuple[0].masked_fill_(~constraint_masks, -math.inf)
870
+ if constraint_start is not None and constraint_end is not None and not zero_shot:
871
+ assert constraint_trie is None
872
+ decoder_out_tuple[0][:, :, 4:constraint_start] = -math.inf
873
+ decoder_out_tuple[0][:, :, constraint_end:] = -math.inf
874
+
875
+ probs = model.get_normalized_probs(
876
+ decoder_out_tuple, log_probs=True, sample=None
877
+ )
878
+ if constraint_trie is not None and zero_shot:
879
+ assert constraint_start is None and constraint_end is None
880
+ constraint_masks = decoder_out_tuple[0].new_zeros(decoder_out_tuple[0].size()).bool()
881
+ constraint_prefix_tokens = tokens.tolist()
882
+ for token_index, constraint_prefix_token in enumerate(constraint_prefix_tokens):
883
+ constraint_nodes = constraint_trie.get_next_layer(constraint_prefix_token)
884
+ constraint_masks[token_index][:, constraint_nodes] = True
885
+ probs.masked_fill_(~constraint_masks, -math.inf)
886
+ if constraint_start is not None and constraint_end is not None and zero_shot:
887
+ assert constraint_trie is None
888
+ probs[:, :, 4:constraint_start] = -math.inf
889
+ probs[:, :, constraint_end:] = -math.inf
890
+ probs = probs[:, -1, :]
891
+ if self.models_size == 1:
892
+ return probs, attn
893
+
894
+ log_probs.append(probs)
895
+ if attn is not None:
896
+ if avg_attn is None:
897
+ avg_attn = attn
898
+ else:
899
+ avg_attn.add_(attn)
900
+
901
+ avg_probs = torch.logsumexp(torch.stack(log_probs, dim=0), dim=0) - math.log(
902
+ self.models_size
903
+ )
904
+
905
+ if avg_attn is not None:
906
+ avg_attn.div_(self.models_size)
907
+ return avg_probs, avg_attn
908
+
909
+ @torch.jit.export
910
+ def reorder_encoder_out(
911
+ self, encoder_outs: Optional[List[Dict[str, List[Tensor]]]], new_order
912
+ ):
913
+ """
914
+ Reorder encoder output according to *new_order*.
915
+
916
+ Args:
917
+ encoder_out: output from the ``forward()`` method
918
+ new_order (LongTensor): desired order
919
+
920
+ Returns:
921
+ *encoder_out* rearranged according to *new_order*
922
+ """
923
+ new_outs: List[Dict[str, List[Tensor]]] = []
924
+ if not self.has_encoder():
925
+ return new_outs
926
+ for i, model in enumerate(self.models):
927
+ assert encoder_outs is not None
928
+ new_outs.append(
929
+ model.encoder.reorder_encoder_out(encoder_outs[i], new_order)
930
+ )
931
+ return new_outs
932
+
933
+ @torch.jit.export
934
+ def reorder_incremental_state(
935
+ self,
936
+ incremental_states: List[Dict[str, Dict[str, Optional[Tensor]]]],
937
+ new_order,
938
+ ):
939
+ if not self.has_incremental_states():
940
+ return
941
+ for i, model in enumerate(self.models):
942
+ model.decoder.reorder_incremental_state_scripting(
943
+ incremental_states[i], new_order
944
+ )
945
+
946
+
947
+ class SequenceGeneratorWithAlignment(SequenceGenerator):
948
+ def __init__(
949
+ self, models, tgt_dict, left_pad_target=False, print_alignment="hard", **kwargs
950
+ ):
951
+ """Generates translations of a given source sentence.
952
+
953
+ Produces alignments following "Jointly Learning to Align and
954
+ Translate with Transformer Models" (Garg et al., EMNLP 2019).
955
+
956
+ Args:
957
+ left_pad_target (bool, optional): Whether or not the
958
+ hypothesis should be left padded or not when they are
959
+ teacher forced for generating alignments.
960
+ """
961
+ super().__init__(EnsembleModelWithAlignment(models), tgt_dict, **kwargs)
962
+ self.left_pad_target = left_pad_target
963
+
964
+ if print_alignment == "hard":
965
+ self.extract_alignment = utils.extract_hard_alignment
966
+ elif print_alignment == "soft":
967
+ self.extract_alignment = utils.extract_soft_alignment
968
+
969
+ @torch.no_grad()
970
+ def generate(self, models, sample, **kwargs):
971
+ finalized = super()._generate(sample, **kwargs)
972
+
973
+ src_tokens = sample["net_input"]["src_tokens"]
974
+ bsz = src_tokens.shape[0]
975
+ beam_size = self.beam_size
976
+ (
977
+ src_tokens,
978
+ src_lengths,
979
+ prev_output_tokens,
980
+ tgt_tokens,
981
+ ) = self._prepare_batch_for_alignment(sample, finalized)
982
+ if any(getattr(m, "full_context_alignment", False) for m in self.model.models):
983
+ attn = self.model.forward_align(src_tokens, src_lengths, prev_output_tokens)
984
+ else:
985
+ attn = [
986
+ finalized[i // beam_size][i % beam_size]["attention"].transpose(1, 0)
987
+ for i in range(bsz * beam_size)
988
+ ]
989
+
990
+ if src_tokens.device != "cpu":
991
+ src_tokens = src_tokens.to("cpu")
992
+ tgt_tokens = tgt_tokens.to("cpu")
993
+ attn = [i.to("cpu") for i in attn]
994
+
995
+ # Process the attn matrix to extract hard alignments.
996
+ for i in range(bsz * beam_size):
997
+ alignment = self.extract_alignment(
998
+ attn[i], src_tokens[i], tgt_tokens[i], self.pad, self.eos
999
+ )
1000
+ finalized[i // beam_size][i % beam_size]["alignment"] = alignment
1001
+ return finalized
1002
+
1003
+ def _prepare_batch_for_alignment(self, sample, hypothesis):
1004
+ src_tokens = sample["net_input"]["src_tokens"]
1005
+ bsz = src_tokens.shape[0]
1006
+ src_tokens = (
1007
+ src_tokens[:, None, :]
1008
+ .expand(-1, self.beam_size, -1)
1009
+ .contiguous()
1010
+ .view(bsz * self.beam_size, -1)
1011
+ )
1012
+ src_lengths = sample["net_input"]["src_lengths"]
1013
+ src_lengths = (
1014
+ src_lengths[:, None]
1015
+ .expand(-1, self.beam_size)
1016
+ .contiguous()
1017
+ .view(bsz * self.beam_size)
1018
+ )
1019
+ prev_output_tokens = data_utils.collate_tokens(
1020
+ [beam["tokens"] for example in hypothesis for beam in example],
1021
+ self.pad,
1022
+ self.eos,
1023
+ self.left_pad_target,
1024
+ move_eos_to_beginning=True,
1025
+ )
1026
+ tgt_tokens = data_utils.collate_tokens(
1027
+ [beam["tokens"] for example in hypothesis for beam in example],
1028
+ self.pad,
1029
+ self.eos,
1030
+ self.left_pad_target,
1031
+ move_eos_to_beginning=False,
1032
+ )
1033
+ return src_tokens, src_lengths, prev_output_tokens, tgt_tokens
1034
+
1035
+
1036
+ class EnsembleModelWithAlignment(EnsembleModel):
1037
+ """A wrapper around an ensemble of models."""
1038
+
1039
+ def __init__(self, models):
1040
+ super().__init__(models)
1041
+
1042
+ def forward_align(self, src_tokens, src_lengths, prev_output_tokens):
1043
+ avg_attn = None
1044
+ for model in self.models:
1045
+ decoder_out = model(src_tokens, src_lengths, prev_output_tokens)
1046
+ attn = decoder_out[1]["attn"][0]
1047
+ if avg_attn is None:
1048
+ avg_attn = attn
1049
+ else:
1050
+ avg_attn.add_(attn)
1051
+ if len(self.models) > 1:
1052
+ avg_attn.div_(len(self.models))
1053
+ return avg_attn
ofa_module/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
1
+ import data
2
+ import models
3
+ import tasks
4
+ import criterions
5
+ import utils
run_scripts/caption/coco_eval.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import sys
3
+ import os.path as op
4
+
5
+ from pycocotools.coco import COCO
6
+ from pycocoevalcap.eval import COCOEvalCap
7
+
8
+
9
+ def evaluate_on_coco_caption(res_file, label_file, outfile=None):
10
+ """
11
+ res_file: txt file, each row is [image_key, json format list of captions].
12
+ Each caption is a dict, with fields "caption", "conf".
13
+ label_file: JSON file of ground truth captions in COCO format.
14
+ """
15
+ coco = COCO(label_file)
16
+ cocoRes = coco.loadRes(res_file)
17
+ cocoEval = COCOEvalCap(coco, cocoRes)
18
+
19
+ # evaluate on a subset of images by setting
20
+ # cocoEval.params['image_id'] = cocoRes.getImgIds()
21
+ # please remove this line when evaluating the full validation set
22
+ cocoEval.params['image_id'] = cocoRes.getImgIds()
23
+
24
+ # evaluate results
25
+ # SPICE will take a few minutes the first time, but speeds up due to caching
26
+ cocoEval.evaluate()
27
+ result = cocoEval.eval
28
+ if not outfile:
29
+ print(result)
30
+ else:
31
+ with open(outfile, 'w') as fp:
32
+ json.dump(result, fp, indent=4)
33
+ return result
34
+
35
+
36
+ if __name__ == "__main__":
37
+ if len(sys.argv) == 3:
38
+ evaluate_on_coco_caption(sys.argv[1], sys.argv[2])
39
+ elif len(sys.argv) == 4:
40
+ evaluate_on_coco_caption(sys.argv[1], sys.argv[2], sys.argv[3])
41
+ else:
42
+ raise NotImplementedError
run_scripts/caption/evaluate_caption.sh ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+
3
+ # The port for communication. Note that if you want to run multiple tasks on the same machine,
4
+ # you need to specify different port numbers.
5
+ export MASTER_PORT=1081
6
+ export CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7
7
+ export GPUS_PER_NODE=8
8
+
9
+ user_dir=../../ofa_module
10
+ bpe_dir=../../utils/BPE
11
+
12
+ data=../../dataset/caption_data/caption_test.tsv
13
+ path=../../checkpoints/caption_large_best_clean.pt
14
+ result_path=../../results/caption
15
+ selected_cols=1,4,2
16
+ split='test'
17
+
18
+ python3 -m torch.distributed.launch --nproc_per_node=${GPUS_PER_NODE} --master_port=${MASTER_PORT} ../../evaluate.py \
19
+ ${data} \
20
+ --path=${path} \
21
+ --user-dir=${user_dir} \
22
+ --task=caption \
23
+ --batch-size=16 \
24
+ --log-format=simple --log-interval=10 \
25
+ --seed=7 \
26
+ --gen-subset=${split} \
27
+ --results-path=${result_path} \
28
+ --beam=5 \
29
+ --max-len-b=16 \
30
+ --no-repeat-ngram-size=3 \
31
+ --fp16 \
32
+ --num-workers=0 \
33
+ --model-overrides="{\"data\":\"${data}\",\"bpe_dir\":\"${bpe_dir}\",\"eval_cider\":False,\"selected_cols\":\"${selected_cols}\"}"
34
+
35
+ python coco_eval.py ../../results/caption/test_predict.json ../../dataset/caption_data/test_caption_coco_format.json
run_scripts/caption/evaluate_caption_base.sh ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+
3
+ # The port for communication. Note that if you want to run multiple tasks on the same machine,
4
+ # you need to specify different port numbers.
5
+ export MASTER_PORT=1091
6
+
7
+ user_dir=../../ofa_module
8
+ bpe_dir=../../utils/BPE
9
+
10
+ data=../../dataset/caption_data/caption_test.tsv
11
+ path=../../checkpoints/caption_base_best.pt
12
+ result_path=../../results/caption
13
+ selected_cols=1,4,2
14
+ split='test'
15
+
16
+ CUDA_VISIBLE_DEVICES=4,5,6,7 python3 -m torch.distributed.launch --nproc_per_node=4 --master_port=${MASTER_PORT} ../../evaluate.py \
17
+ ${data} \
18
+ --path=${path} \
19
+ --user-dir=${user_dir} \
20
+ --task=caption \
21
+ --batch-size=16 \
22
+ --log-format=simple --log-interval=10 \
23
+ --seed=7 \
24
+ --gen-subset=${split} \
25
+ --results-path=${result_path} \
26
+ --beam=5 \
27
+ --max-len-b=16 \
28
+ --no-repeat-ngram-size=3 \
29
+ --fp16 \
30
+ --num-workers=0 \
31
+ --model-overrides="{\"data\":\"${data}\",\"bpe_dir\":\"${bpe_dir}\",\"eval_cider\":False,\"selected_cols\":\"${selected_cols}\"}"
32
+
33
+ python coco_eval.py ../../results/caption/test_predict.json ../../dataset/caption_data/test_caption_coco_format.json
run_scripts/caption/train_caption_stage1.sh ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env
2
+
3
+ # The port for communication. Note that if you want to run multiple tasks on the same machine,
4
+ # you need to specify different port numbers.
5
+ export MASTER_PORT=1051
6
+
7
+ log_dir=./stage1_logs
8
+ save_dir=./stage1_checkpoints
9
+ mkdir -p $log_dir $save_dir
10
+
11
+ bpe_dir=../../utils/BPE
12
+ user_dir=../../ofa_module
13
+
14
+ data_dir=../../dataset/caption_data
15
+ data=${data_dir}/caption_stage1_train.tsv,${data_dir}/caption_val.tsv
16
+ restore_file=../../checkpoints/ofa_large.pt
17
+ selected_cols=0,4,2
18
+
19
+ task=caption
20
+ arch=ofa_large
21
+ criterion=adjust_label_smoothed_cross_entropy
22
+ label_smoothing=0.1
23
+ lr=1e-5
24
+ max_epoch=5
25
+ warmup_ratio=0.06
26
+ batch_size=8
27
+ update_freq=4
28
+ resnet_drop_path_rate=0.0
29
+ encoder_drop_path_rate=0.1
30
+ decoder_drop_path_rate=0.1
31
+ dropout=0.1
32
+ attention_dropout=0.0
33
+ max_src_length=80
34
+ max_tgt_length=20
35
+ num_bins=1000
36
+ patch_image_size=480
37
+ eval_cider_cached=${data_dir}/cider_cached_tokens/coco-valid-words.p
38
+ drop_worst_ratio=0.2
39
+
40
+ for max_epoch in {2,}; do
41
+ echo "max_epoch "${max_epoch}
42
+ for warmup_ratio in {0.06,}; do
43
+ echo "warmup_ratio "${warmup_ratio}
44
+ for drop_worst_after in {2500,}; do
45
+ echo "drop_worst_after "${drop_worst_after}
46
+
47
+ log_file=${log_dir}/${max_epoch}"_"${warmup_ratio}"_"${drop_worst_after}".log"
48
+ save_path=${save_dir}/${max_epoch}"_"${warmup_ratio}"_"${drop_worst_after}
49
+ mkdir -p $save_path
50
+
51
+ CUDA_VISIBLE_DEVICES=0,1,2,3 python3 -m torch.distributed.launch --nproc_per_node=4 --master_port=${MASTER_PORT} ../../train.py \
52
+ $data \
53
+ --selected-cols=${selected_cols} \
54
+ --bpe-dir=${bpe_dir} \
55
+ --user-dir=${user_dir} \
56
+ --restore-file=${restore_file} \
57
+ --reset-optimizer --reset-dataloader --reset-meters \
58
+ --save-dir=${save_path} \
59
+ --task=${task} \
60
+ --arch=${arch} \
61
+ --criterion=${criterion} \
62
+ --label-smoothing=${label_smoothing} \
63
+ --batch-size=${batch_size} \
64
+ --update-freq=${update_freq} \
65
+ --encoder-normalize-before \
66
+ --decoder-normalize-before \
67
+ --share-decoder-input-output-embed \
68
+ --share-all-embeddings \
69
+ --layernorm-embedding \
70
+ --patch-layernorm-embedding \
71
+ --code-layernorm-embedding \
72
+ --resnet-drop-path-rate=${resnet_drop_path_rate} \
73
+ --encoder-drop-path-rate=${encoder_drop_path_rate} \
74
+ --decoder-drop-path-rate=${decoder_drop_path_rate} \
75
+ --dropout=${dropout} \
76
+ --attention-dropout=${attention_dropout} \
77
+ --weight-decay=0.01 --optimizer=adam --adam-betas="(0.9,0.999)" --adam-eps=1e-08 --clip-norm=1.0 \
78
+ --lr-scheduler=polynomial_decay --lr=${lr} \
79
+ --max-epoch=${max_epoch} --warmup-ratio=${warmup_ratio} \
80
+ --log-format=simple --log-interval=10 \
81
+ --fixed-validation-seed=7 \
82
+ --no-epoch-checkpoints --keep-best-checkpoints=1 \
83
+ --save-interval=1 --validate-interval=1 \
84
+ --save-interval-updates=500 --validate-interval-updates=500 \
85
+ --eval-cider \
86
+ --eval-cider-cached-tokens=${eval_cider_cached} \
87
+ --eval-args='{"beam":5,"max_len_b":16,"no_repeat_ngram_size":3}' \
88
+ --best-checkpoint-metric=cider --maximize-best-checkpoint-metric \
89
+ --max-src-length=${max_src_length} \
90
+ --max-tgt-length=${max_tgt_length} \
91
+ --find-unused-parameters \
92
+ --freeze-encoder-embedding \
93
+ --freeze-decoder-embedding \
94
+ --add-type-embedding \
95
+ --scale-attn \
96
+ --scale-fc \
97
+ --scale-heads \
98
+ --disable-entangle \
99
+ --num-bins=${num_bins} \
100
+ --patch-image-size=${patch_image_size} \
101
+ --drop-worst-ratio=${drop_worst_ratio} \
102
+ --drop-worst-after=${drop_worst_after} \
103
+ --fp16 \
104
+ --fp16-scale-window=512 \
105
+ --num-workers=0 > ${log_file} 2>&1
106
+ done
107
+ done
108
+ done
run_scripts/caption/train_caption_stage1_base.sh ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env
2
+
3
+ # The port for communication. Note that if you want to run multiple tasks on the same machine,
4
+ # you need to specify different port numbers.
5
+ export MASTER_PORT=1061
6
+
7
+ log_dir=./stage1_logs
8
+ save_dir=./stage1_checkpoints
9
+ mkdir -p $log_dir $save_dir
10
+
11
+ bpe_dir=../../utils/BPE
12
+ user_dir=../../ofa_module
13
+
14
+ data_dir=../../dataset/caption_data
15
+ data=${data_dir}/caption_stage1_train.tsv,${data_dir}/caption_val.tsv
16
+ restore_file=../../checkpoints/ofa_base.pt
17
+ selected_cols=0,4,2
18
+
19
+ task=caption
20
+ arch=ofa_base
21
+ criterion=adjust_label_smoothed_cross_entropy
22
+ label_smoothing=0.1
23
+ lr=1e-5
24
+ max_epoch=5
25
+ warmup_ratio=0.06
26
+ batch_size=8
27
+ update_freq=4
28
+ resnet_drop_path_rate=0.0
29
+ encoder_drop_path_rate=0.1
30
+ decoder_drop_path_rate=0.1
31
+ dropout=0.1
32
+ attention_dropout=0.0
33
+ max_src_length=80
34
+ max_tgt_length=20
35
+ num_bins=1000
36
+ patch_image_size=480
37
+ eval_cider_cached=${data_dir}/cider_cached_tokens/coco-valid-words.p
38
+ drop_worst_ratio=0.2
39
+
40
+ for max_epoch in {5,}; do
41
+ echo "max_epoch "${max_epoch}
42
+ for warmup_ratio in {0.06,}; do
43
+ echo "warmup_ratio "${warmup_ratio}
44
+ for drop_worst_after in {6000,}; do
45
+ echo "drop_worst_after "${drop_worst_after}
46
+
47
+ log_file=${log_dir}/${max_epoch}"_"${warmup_ratio}"_"${drop_worst_after}".log"
48
+ save_path=${save_dir}/${max_epoch}"_"${warmup_ratio}"_"${drop_worst_after}
49
+ mkdir -p $save_path
50
+
51
+ CUDA_VISIBLE_DEVICES=0,1,2,3 python3 -m torch.distributed.launch --nproc_per_node=4 --master_port=${MASTER_PORT} ../../train.py \
52
+ $data \
53
+ --selected-cols=${selected_cols} \
54
+ --bpe-dir=${bpe_dir} \
55
+ --user-dir=${user_dir} \
56
+ --restore-file=${restore_file} \
57
+ --reset-optimizer --reset-dataloader --reset-meters \
58
+ --save-dir=${save_path} \
59
+ --task=${task} \
60
+ --arch=${arch} \
61
+ --criterion=${criterion} \
62
+ --label-smoothing=${label_smoothing} \
63
+ --batch-size=${batch_size} \
64
+ --update-freq=${update_freq} \
65
+ --encoder-normalize-before \
66
+ --decoder-normalize-before \
67
+ --share-decoder-input-output-embed \
68
+ --share-all-embeddings \
69
+ --layernorm-embedding \
70
+ --patch-layernorm-embedding \
71
+ --code-layernorm-embedding \
72
+ --resnet-drop-path-rate=${resnet_drop_path_rate} \
73
+ --encoder-drop-path-rate=${encoder_drop_path_rate} \
74
+ --decoder-drop-path-rate=${decoder_drop_path_rate} \
75
+ --dropout=${dropout} \
76
+ --attention-dropout=${attention_dropout} \
77
+ --weight-decay=0.01 --optimizer=adam --adam-betas="(0.9,0.999)" --adam-eps=1e-08 --clip-norm=1.0 \
78
+ --lr-scheduler=polynomial_decay --lr=${lr} \
79
+ --max-epoch=${max_epoch} --warmup-ratio=${warmup_ratio} \
80
+ --log-format=simple --log-interval=10 \
81
+ --fixed-validation-seed=7 \
82
+ --no-epoch-checkpoints --keep-best-checkpoints=1 \
83
+ --save-interval=1 --validate-interval=1 \
84
+ --save-interval-updates=500 --validate-interval-updates=500 \
85
+ --eval-cider \
86
+ --eval-cider-cached-tokens=${eval_cider_cached} \
87
+ --eval-args='{"beam":5,"max_len_b":16,"no_repeat_ngram_size":3}' \
88
+ --best-checkpoint-metric=cider --maximize-best-checkpoint-metric \
89
+ --max-src-length=${max_src_length} \
90
+ --max-tgt-length=${max_tgt_length} \
91
+ --find-unused-parameters \
92
+ --freeze-encoder-embedding \
93
+ --freeze-decoder-embedding \
94
+ --add-type-embedding \
95
+ --scale-attn \
96
+ --scale-fc \
97
+ --scale-heads \
98
+ --disable-entangle \
99
+ --num-bins=${num_bins} \
100
+ --patch-image-size=${patch_image_size} \
101
+ --drop-worst-ratio=${drop_worst_ratio} \
102
+ --drop-worst-after=${drop_worst_after} \
103
+ --fp16 \
104
+ --fp16-scale-window=512 \
105
+ --num-workers=0 > ${log_file} 2>&1
106
+ done
107
+ done
108
+ done
run_scripts/caption/train_caption_stage1_el.sh ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env
2
+
3
+ # The port for communication. Note that if you want to run multiple tasks on the same machine,
4
+ # you need to specify different port numbers.
5
+ export MASTER_PORT=1051
6
+
7
+ log_dir=./stage1_logs
8
+ save_dir=./stage1_checkpoints
9
+ mkdir -p $log_dir $save_dir
10
+
11
+ bpe_dir=../../utils/BPE
12
+ user_dir=../../ofa_module
13
+
14
+ data_dir=../../dataset/caption_data
15
+ data=${data_dir}/caption_stage1_train.tsv,${data_dir}/caption_val.tsv
16
+ restore_file=../../checkpoints/ofa_large.pt
17
+ selected_cols=0,4,2
18
+
19
+ task=caption
20
+ arch=ofa_large
21
+ criterion=adjust_label_smoothed_encouraging_loss # for el
22
+ label_smoothing=0.1
23
+ lr=1e-5
24
+ max_epoch=5
25
+ warmup_ratio=0.06
26
+ batch_size=8
27
+ update_freq=4
28
+ resnet_drop_path_rate=0.0
29
+ encoder_drop_path_rate=0.1
30
+ decoder_drop_path_rate=0.1
31
+ dropout=0.1
32
+ attention_dropout=0.0
33
+ max_src_length=80
34
+ max_tgt_length=20
35
+ num_bins=1000
36
+ patch_image_size=480
37
+ eval_cider_cached=${data_dir}/cider_cached_tokens/coco-valid-words.p
38
+ drop_worst_ratio=0.05 # modified from 0.2 for el
39
+ log_end=0.75 # for el
40
+ for max_epoch in {2,}; do
41
+ echo "max_epoch "${max_epoch}
42
+ for warmup_ratio in {0.06,}; do
43
+ echo "warmup_ratio "${warmup_ratio}
44
+ for drop_worst_after in {2500,}; do
45
+ echo "drop_worst_after "${drop_worst_after}
46
+
47
+ log_file=${log_dir}/${max_epoch}"_"${warmup_ratio}"_"${drop_worst_after}_el${log_end}_".log"
48
+ save_path=${save_dir}/${max_epoch}"_"${warmup_ratio}"_"${drop_worst_after}_el${log_end}_
49
+ mkdir -p $save_path
50
+
51
+ CUDA_VISIBLE_DEVICES=0,1,2,3 python3 -m torch.distributed.launch --nproc_per_node=4 --master_port=${MASTER_PORT} ../../train.py \
52
+ $data \
53
+ --selected-cols=${selected_cols} \
54
+ --bpe-dir=${bpe_dir} \
55
+ --user-dir=${user_dir} \
56
+ --restore-file=${restore_file} \
57
+ --reset-optimizer --reset-dataloader --reset-meters \
58
+ --save-dir=${save_path} \
59
+ --task=${task} \
60
+ --arch=${arch} \
61
+ --criterion=${criterion} \
62
+ --label-smoothing=${label_smoothing} \
63
+ --batch-size=${batch_size} \
64
+ --update-freq=${update_freq} \
65
+ --encoder-normalize-before \
66
+ --decoder-normalize-before \
67
+ --share-decoder-input-output-embed \
68
+ --share-all-embeddings \
69
+ --layernorm-embedding \
70
+ --patch-layernorm-embedding \
71
+ --code-layernorm-embedding \
72
+ --resnet-drop-path-rate=${resnet_drop_path_rate} \
73
+ --encoder-drop-path-rate=${encoder_drop_path_rate} \
74
+ --decoder-drop-path-rate=${decoder_drop_path_rate} \
75
+ --dropout=${dropout} \
76
+ --attention-dropout=${attention_dropout} \
77
+ --weight-decay=0.01 --optimizer=adam --adam-betas="(0.9,0.999)" --adam-eps=1e-08 --clip-norm=1.0 \
78
+ --lr-scheduler=polynomial_decay --lr=${lr} \
79
+ --max-epoch=${max_epoch} --warmup-ratio=${warmup_ratio} \
80
+ --log-format=simple --log-interval=10 \
81
+ --fixed-validation-seed=7 \
82
+ --no-epoch-checkpoints --keep-best-checkpoints=1 \
83
+ --save-interval=1 --validate-interval=1 \
84
+ --save-interval-updates=500 --validate-interval-updates=500 \
85
+ --eval-cider \
86
+ --eval-cider-cached-tokens=${eval_cider_cached} \
87
+ --eval-args='{"beam":5,"max_len_b":16,"no_repeat_ngram_size":3}' \
88
+ --best-checkpoint-metric=cider --maximize-best-checkpoint-metric \
89
+ --max-src-length=${max_src_length} \
90
+ --max-tgt-length=${max_tgt_length} \
91
+ --find-unused-parameters \
92
+ --freeze-encoder-embedding \
93
+ --freeze-decoder-embedding \
94
+ --add-type-embedding \
95
+ --scale-attn \
96
+ --scale-fc \
97
+ --scale-heads \
98
+ --disable-entangle \
99
+ --num-bins=${num_bins} \
100
+ --patch-image-size=${patch_image_size} \
101
+ --drop-worst-ratio=${drop_worst_ratio} \
102
+ --drop-worst-after=${drop_worst_after} \
103
+ --log-end ${log_end} \
104
+ --fp16 \
105
+ --fp16-scale-window=512 \
106
+ --num-workers=0 > ${log_file} 2>&1
107
+ done
108
+ done
109
+ done
run_scripts/caption/train_caption_stage1_el_db.sh ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env
2
+
3
+ # The port for communication. Note that if you want to run multiple tasks on the same machine,
4
+ # you need to specify different port numbers.
5
+ export MASTER_PORT=1051
6
+
7
+ log_dir=./stage1_logs
8
+ save_dir=./stage1_checkpoints
9
+ mkdir -p $log_dir $save_dir
10
+
11
+ bpe_dir=../../utils/BPE
12
+ user_dir=../../ofa_module
13
+
14
+ data_dir=../../dataset/caption_data
15
+ data=${data_dir}/caption_stage1_train.tsv,${data_dir}/caption_val.tsv
16
+ restore_file=../../checkpoints/ofa_large.pt
17
+ selected_cols=0,4,2
18
+
19
+ task=caption
20
+ arch=ofa_large
21
+ criterion=adjust_label_smoothed_encouraging_loss # for el
22
+ label_smoothing=0.1
23
+ lr=1e-5
24
+ max_epoch=5
25
+ warmup_ratio=0.06
26
+ batch_size=8
27
+ update_freq=4
28
+ resnet_drop_path_rate=0.0
29
+ encoder_drop_path_rate=0.1
30
+ decoder_drop_path_rate=0.1
31
+ dropout=0.1
32
+ attention_dropout=0.0
33
+ max_src_length=80
34
+ max_tgt_length=20
35
+ num_bins=1000
36
+ patch_image_size=480
37
+ eval_cider_cached=${data_dir}/cider_cached_tokens/coco-valid-words.p
38
+ drop_worst_ratio=0.05 # modified from 0.2 for el
39
+ drop_best_ratio=0.05
40
+ drop_best_after=2500
41
+ log_end=0.75 # for el
42
+ for max_epoch in {2,}; do
43
+ echo "max_epoch "${max_epoch}
44
+ for warmup_ratio in {0.06,}; do
45
+ echo "warmup_ratio "${warmup_ratio}
46
+ for drop_worst_after in {2500,}; do
47
+ echo "drop_worst_after "${drop_worst_after}
48
+
49
+ log_file=${log_dir}/${max_epoch}"_"${warmup_ratio}"_dwdb"${drop_worst_after}_el${log_end}_".log"
50
+ save_path=${save_dir}/${max_epoch}"_"${warmup_ratio}"_dwdb"${drop_worst_after}_el${log_end}_
51
+ mkdir -p $save_path
52
+
53
+ CUDA_VISIBLE_DEVICES=0,1,2,3 python3 -m torch.distributed.launch --nproc_per_node=4 --master_port=${MASTER_PORT} ../../train.py \
54
+ $data \
55
+ --selected-cols=${selected_cols} \
56
+ --bpe-dir=${bpe_dir} \
57
+ --user-dir=${user_dir} \
58
+ --restore-file=${restore_file} \
59
+ --reset-optimizer --reset-dataloader --reset-meters \
60
+ --save-dir=${save_path} \
61
+ --task=${task} \
62
+ --arch=${arch} \
63
+ --criterion=${criterion} \
64
+ --label-smoothing=${label_smoothing} \
65
+ --batch-size=${batch_size} \
66
+ --update-freq=${update_freq} \
67
+ --encoder-normalize-before \
68
+ --decoder-normalize-before \
69
+ --share-decoder-input-output-embed \
70
+ --share-all-embeddings \
71
+ --layernorm-embedding \
72
+ --patch-layernorm-embedding \
73
+ --code-layernorm-embedding \
74
+ --resnet-drop-path-rate=${resnet_drop_path_rate} \
75
+ --encoder-drop-path-rate=${encoder_drop_path_rate} \
76
+ --decoder-drop-path-rate=${decoder_drop_path_rate} \
77
+ --dropout=${dropout} \
78
+ --attention-dropout=${attention_dropout} \
79
+ --weight-decay=0.01 --optimizer=adam --adam-betas="(0.9,0.999)" --adam-eps=1e-08 --clip-norm=1.0 \
80
+ --lr-scheduler=polynomial_decay --lr=${lr} \
81
+ --max-epoch=${max_epoch} --warmup-ratio=${warmup_ratio} \
82
+ --log-format=simple --log-interval=10 \
83
+ --fixed-validation-seed=7 \
84
+ --no-epoch-checkpoints --keep-best-checkpoints=1 \
85
+ --save-interval=1 --validate-interval=1 \
86
+ --save-interval-updates=500 --validate-interval-updates=500 \
87
+ --eval-cider \
88
+ --eval-cider-cached-tokens=${eval_cider_cached} \
89
+ --eval-args='{"beam":5,"max_len_b":16,"no_repeat_ngram_size":3}' \
90
+ --best-checkpoint-metric=cider --maximize-best-checkpoint-metric \
91
+ --max-src-length=${max_src_length} \
92
+ --max-tgt-length=${max_tgt_length} \
93
+ --find-unused-parameters \
94
+ --freeze-encoder-embedding \
95
+ --freeze-decoder-embedding \
96
+ --add-type-embedding \
97
+ --scale-attn \
98
+ --scale-fc \
99
+ --scale-heads \
100
+ --disable-entangle \
101
+ --num-bins=${num_bins} \
102
+ --patch-image-size=${patch_image_size} \
103
+ --drop-worst-ratio=${drop_worst_ratio} \
104
+ --drop-worst-after=${drop_worst_after} \
105
+ --log-end ${log_end} --drop-best-ratio ${drop_best_ratio} --drop-best-after ${drop_best_after} \
106
+ --fp16 \
107
+ --fp16-scale-window=512 \
108
+ --num-workers=0 > ${log_file} 2>&1
109
+ done
110
+ done
111
+ done
run_scripts/caption/train_caption_stage2.sh ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env
2
+
3
+ # The port for communication. Note that if you want to run multiple tasks on the same machine,
4
+ # you need to specify different port numbers.
5
+ export MASTER_PORT=1052
6
+
7
+ log_dir=./stage2_logs
8
+ save_dir=./stage2_checkpoints
9
+ mkdir -p $log_dir $save_dir
10
+
11
+ bpe_dir=../../utils/BPE
12
+ user_dir=../../ofa_module
13
+
14
+ data_dir=../../dataset/caption_data
15
+ data=${data_dir}/caption_stage2_train.tsv,${data_dir}/caption_val.tsv
16
+ restore_file=../../checkpoints/caption_stage1_best.pt
17
+ selected_cols=1,4,2
18
+
19
+ task=caption
20
+ arch=ofa_large
21
+ criterion=scst_reward_criterion
22
+ label_smoothing=0.1
23
+ lr=1e-5
24
+ max_epoch=5
25
+ warmup_ratio=0.06
26
+ batch_size=2
27
+ update_freq=4
28
+ resnet_drop_path_rate=0.0
29
+ encoder_drop_path_rate=0.0
30
+ decoder_drop_path_rate=0.0
31
+ dropout=0.0
32
+ attention_dropout=0.0
33
+ max_src_length=80
34
+ max_tgt_length=20
35
+ num_bins=1000
36
+ patch_image_size=480
37
+ eval_cider_cached=${data_dir}/cider_cached_tokens/coco-valid-words.p
38
+ scst_cider_cached=${data_dir}/cider_cached_tokens/coco-train-words.p
39
+
40
+ for lr in {1e-5,}; do
41
+ echo "lr "${lr}
42
+ for max_epoch in {3,}; do
43
+ echo "max_epoch "${max_epoch}
44
+
45
+ log_file=${log_dir}/${lr}"_"${max_epoch}".log"
46
+ save_path=${save_dir}/${lr}"_"${max_epoch}
47
+ mkdir -p $save_path
48
+
49
+ CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 python3 -m torch.distributed.launch --nproc_per_node=8 --master_port=${MASTER_PORT} ../../train.py \
50
+ $data \
51
+ --selected-cols=${selected_cols} \
52
+ --bpe-dir=${bpe_dir} \
53
+ --user-dir=${user_dir} \
54
+ --restore-file=${restore_file} \
55
+ --reset-optimizer --reset-dataloader --reset-meters \
56
+ --save-dir=${save_path} \
57
+ --task=${task} \
58
+ --arch=${arch} \
59
+ --criterion=${criterion} \
60
+ --batch-size=${batch_size} \
61
+ --update-freq=${update_freq} \
62
+ --encoder-normalize-before \
63
+ --decoder-normalize-before \
64
+ --share-decoder-input-output-embed \
65
+ --share-all-embeddings \
66
+ --layernorm-embedding \
67
+ --patch-layernorm-embedding \
68
+ --code-layernorm-embedding \
69
+ --resnet-drop-path-rate=${resnet_drop_path_rate} \
70
+ --encoder-drop-path-rate=${encoder_drop_path_rate} \
71
+ --decoder-drop-path-rate=${decoder_drop_path_rate} \
72
+ --dropout=${dropout} \
73
+ --attention-dropout=${attention_dropout} \
74
+ --weight-decay=0.01 --optimizer=adam --adam-betas="(0.9,0.999)" --adam-eps=1e-08 --clip-norm=1.0 \
75
+ --lr-scheduler=polynomial_decay --lr=${lr} --end-learning-rate=2e-7 \
76
+ --max-epoch=${max_epoch} --warmup-ratio=${warmup_ratio} \
77
+ --log-format=simple --log-interval=10 \
78
+ --fixed-validation-seed=7 \
79
+ --no-epoch-checkpoints --keep-best-checkpoints=1 \
80
+ --save-interval=1 --validate-interval=1 \
81
+ --save-interval-updates=500 --validate-interval-updates=500 \
82
+ --eval-cider \
83
+ --eval-cider-cached-tokens=${eval_cider_cached} \
84
+ --eval-args='{"beam":5,"max_len_b":16,"no_repeat_ngram_size":3}' \
85
+ --best-checkpoint-metric=cider --maximize-best-checkpoint-metric \
86
+ --max-src-length=${max_src_length} \
87
+ --max-tgt-length=${max_tgt_length} \
88
+ --find-unused-parameters \
89
+ --freeze-encoder-embedding \
90
+ --freeze-decoder-embedding \
91
+ --add-type-embedding \
92
+ --scale-attn \
93
+ --scale-fc \
94
+ --scale-heads \
95
+ --disable-entangle \
96
+ --num-bins=${num_bins} \
97
+ --patch-image-size=${patch_image_size} \
98
+ --scst \
99
+ --scst-cider-cached-tokens=${scst_cider_cached} \
100
+ --scst-args='{"beam":5,"max_len_b":16,"no_repeat_ngram_size":3}' \
101
+ --memory-efficient-fp16 \
102
+ --fp16-scale-window=512 \
103
+ --num-workers=0 > ${log_file} 2>&1
104
+ done
105
+ done
run_scripts/caption/train_caption_stage2_base.sh ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env
2
+
3
+ # The port for communication. Note that if you want to run multiple tasks on the same machine,
4
+ # you need to specify different port numbers.
5
+ export MASTER_PORT=1062
6
+
7
+ log_dir=./stage2_logs
8
+ save_dir=./stage2_checkpoints
9
+ mkdir -p $log_dir $save_dir
10
+
11
+ bpe_dir=../../utils/BPE
12
+ user_dir=../../ofa_module
13
+
14
+ data_dir=../../dataset/caption_data
15
+ data=${data_dir}/caption_stage2_train.tsv,${data_dir}/caption_val.tsv
16
+ restore_file=../../checkpoints/caption_stage1_base_best.pt
17
+ selected_cols=1,4,2
18
+
19
+ task=caption
20
+ arch=ofa_base
21
+ criterion=scst_reward_criterion
22
+ label_smoothing=0.1
23
+ lr=1e-5
24
+ max_epoch=5
25
+ warmup_ratio=0.06
26
+ batch_size=2
27
+ update_freq=4
28
+ resnet_drop_path_rate=0.0
29
+ encoder_drop_path_rate=0.0
30
+ decoder_drop_path_rate=0.0
31
+ dropout=0.0
32
+ attention_dropout=0.0
33
+ max_src_length=80
34
+ max_tgt_length=20
35
+ num_bins=1000
36
+ patch_image_size=480
37
+ eval_cider_cached=${data_dir}/cider_cached_tokens/coco-valid-words.p
38
+ scst_cider_cached=${data_dir}/cider_cached_tokens/coco-train-words.p
39
+
40
+ for lr in {1e-5,}; do
41
+ echo "lr "${lr}
42
+ for max_epoch in {3,}; do
43
+ echo "max_epoch "${max_epoch}
44
+
45
+ log_file=${log_dir}/${lr}"_"${max_epoch}".log"
46
+ save_path=${save_dir}/${lr}"_"${max_epoch}
47
+ mkdir -p $save_path
48
+
49
+ CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 python3 -m torch.distributed.launch --nproc_per_node=8 --master_port=${MASTER_PORT} ../../train.py \
50
+ $data \
51
+ --selected-cols=${selected_cols} \
52
+ --bpe-dir=${bpe_dir} \
53
+ --user-dir=${user_dir} \
54
+ --restore-file=${restore_file} \
55
+ --reset-optimizer --reset-dataloader --reset-meters \
56
+ --save-dir=${save_path} \
57
+ --task=${task} \
58
+ --arch=${arch} \
59
+ --criterion=${criterion} \
60
+ --batch-size=${batch_size} \
61
+ --update-freq=${update_freq} \
62
+ --encoder-normalize-before \
63
+ --decoder-normalize-before \
64
+ --share-decoder-input-output-embed \
65
+ --share-all-embeddings \
66
+ --layernorm-embedding \
67
+ --patch-layernorm-embedding \
68
+ --code-layernorm-embedding \
69
+ --resnet-drop-path-rate=${resnet_drop_path_rate} \
70
+ --encoder-drop-path-rate=${encoder_drop_path_rate} \
71
+ --decoder-drop-path-rate=${decoder_drop_path_rate} \
72
+ --dropout=${dropout} \
73
+ --attention-dropout=${attention_dropout} \
74
+ --weight-decay=0.01 --optimizer=adam --adam-betas="(0.9,0.999)" --adam-eps=1e-08 --clip-norm=1.0 \
75
+ --lr-scheduler=polynomial_decay --lr=${lr} \
76
+ --max-epoch=${max_epoch} --warmup-ratio=${warmup_ratio} \
77
+ --log-format=simple --log-interval=10 \
78
+ --fixed-validation-seed=7 \
79
+ --no-epoch-checkpoints --keep-best-checkpoints=1 \
80
+ --save-interval=1 --validate-interval=1 \
81
+ --save-interval-updates=500 --validate-interval-updates=500 \
82
+ --eval-cider \
83
+ --eval-cider-cached-tokens=${eval_cider_cached} \
84
+ --eval-args='{"beam":5,"max_len_b":16,"no_repeat_ngram_size":3}' \
85
+ --best-checkpoint-metric=cider --maximize-best-checkpoint-metric \
86
+ --max-src-length=${max_src_length} \
87
+ --max-tgt-length=${max_tgt_length} \
88
+ --find-unused-parameters \
89
+ --freeze-encoder-embedding \
90
+ --freeze-decoder-embedding \
91
+ --add-type-embedding \
92
+ --scale-attn \
93
+ --scale-fc \
94
+ --scale-heads \
95
+ --disable-entangle \
96
+ --num-bins=${num_bins} \
97
+ --patch-image-size=${patch_image_size} \
98
+ --scst \
99
+ --scst-cider-cached-tokens=${scst_cider_cached} \
100
+ --scst-args='{"beam":5,"max_len_b":16,"no_repeat_ngram_size":3}' \
101
+ --memory-efficient-fp16 \
102
+ --fp16-scale-window=512 \
103
+ --num-workers=0 > ${log_file} 2>&1
104
+ done
105
+ done
tasks/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
1
+ from .cv_tasks import *
2
+ from .mm_tasks import *
3
+ from .nlg_tasks import *
4
+ from .nlu_tasks import *
5
+ from .pretrain_tasks import *
6
+ from .ofa_task import OFATask
tasks/mm_tasks/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
1
+ from .caption import CaptionTask
2
+ from .image_gen import ImageGenTask
3
+ from .refcoco import RefcocoTask
4
+ from .snli_ve import SnliVeTask
5
+ from .vqa_gen import VqaGenTask
tasks/mm_tasks/caption.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The OFA-Sys Team.
2
+ # All rights reserved.
3
+ # This source code is licensed under the Apache 2.0 license
4
+ # found in the LICENSE file in the root directory.
5
+
6
+ from dataclasses import dataclass, field
7
+ import json
8
+ import logging
9
+ from typing import Optional
10
+ from argparse import Namespace
11
+ from itertools import zip_longest
12
+ from collections import OrderedDict
13
+
14
+ import numpy as np
15
+ import sacrebleu
16
+ import string
17
+ from fairseq import metrics, utils
18
+ from fairseq.tasks import register_task
19
+
20
+ from tasks.ofa_task import OFATask, OFAConfig
21
+ from data.mm_data.caption_dataset import CaptionDataset
22
+ from data.file_dataset import FileDataset
23
+ from utils.cider.pyciderevalcap.ciderD.ciderD import CiderD
24
+
25
+ EVAL_BLEU_ORDER = 4
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+
30
+ @dataclass
31
+ class CaptionConfig(OFAConfig):
32
+ eval_bleu: bool = field(
33
+ default=False, metadata={"help": "evaluation with BLEU scores"}
34
+ )
35
+ eval_cider: bool = field(
36
+ default=False, metadata={"help": "evaluation with CIDEr scores"}
37
+ )
38
+ eval_args: Optional[str] = field(
39
+ default='{}',
40
+ metadata={
41
+ "help": 'generation args for BLUE or CIDEr scoring, e.g., \'{"beam": 4, "lenpen": 0.6}\', as JSON string'
42
+ },
43
+ )
44
+ eval_print_samples: bool = field(
45
+ default=False, metadata={"help": "print sample generations during validation"}
46
+ )
47
+ eval_cider_cached_tokens: Optional[str] = field(
48
+ default=None,
49
+ metadata={"help": "path to cached cPickle file used to calculate CIDEr scores"},
50
+ )
51
+
52
+ scst: bool = field(
53
+ default=False, metadata={"help": "Self-critical sequence training"}
54
+ )
55
+ scst_args: str = field(
56
+ default='{}',
57
+ metadata={
58
+ "help": 'generation args for Self-critical sequence training, as JSON string'
59
+ },
60
+ )
61
+
62
+
63
+ @register_task("caption", dataclass=CaptionConfig)
64
+ class CaptionTask(OFATask):
65
+ def __init__(self, cfg: CaptionConfig, src_dict, tgt_dict):
66
+ super().__init__(cfg, src_dict, tgt_dict)
67
+
68
+ def load_dataset(self, split, epoch=1, combine=False, **kwargs):
69
+ paths = self.cfg.data.split(',')
70
+ assert len(paths) > 0
71
+
72
+ if split == 'train':
73
+ file_path = paths[(epoch - 1) % (len(paths) - 1)]
74
+ else:
75
+ file_path = paths[-1]
76
+ dataset = FileDataset(file_path, self.cfg.selected_cols)
77
+
78
+ self.datasets[split] = CaptionDataset(
79
+ split,
80
+ dataset,
81
+ self.bpe,
82
+ self.src_dict,
83
+ self.tgt_dict,
84
+ max_src_length=self.cfg.max_src_length,
85
+ max_tgt_length=self.cfg.max_tgt_length,
86
+ patch_image_size=self.cfg.patch_image_size,
87
+ imagenet_default_mean_and_std=self.cfg.imagenet_default_mean_and_std,
88
+ scst=getattr(self.cfg, 'scst', False)
89
+ )
90
+
91
+ def build_model(self, cfg):
92
+ model = super().build_model(cfg)
93
+ if self.cfg.eval_bleu or self.cfg.eval_cider:
94
+ gen_args = json.loads(self.cfg.eval_args)
95
+ self.sequence_generator = self.build_generator(
96
+ [model], Namespace(**gen_args)
97
+ )
98
+ if self.cfg.eval_cider:
99
+ self.CiderD_scorer = CiderD(df=self.cfg.eval_cider_cached_tokens)
100
+ if self.cfg.scst:
101
+ scst_args = json.loads(self.cfg.scst_args)
102
+ self.scst_generator = self.build_generator(
103
+ [model], Namespace(**scst_args)
104
+ )
105
+
106
+ return model
107
+
108
+ def _calculate_cider_scores(self, gen_res, gt_res):
109
+ '''
110
+ gen_res: generated captions, list of str
111
+ gt_idx: list of int, of the same length as gen_res
112
+ gt_res: ground truth captions, list of list of str.
113
+ gen_res[i] corresponds to gt_res[gt_idx[i]]
114
+ Each image can have multiple ground truth captions
115
+ '''
116
+ gen_res_size = len(gen_res)
117
+
118
+ res = OrderedDict()
119
+ for i in range(gen_res_size):
120
+ res[i] = [gen_res[i].strip()]
121
+
122
+ gts = OrderedDict()
123
+ gt_res_ = [
124
+ [gt_res[i][j].strip() for j in range(len(gt_res[i]))]
125
+ for i in range(len(gt_res))
126
+ ]
127
+ for i in range(gen_res_size):
128
+ gts[i] = gt_res_[i]
129
+
130
+ res_ = [{'image_id': i, 'caption': res[i]} for i in range(len(res))]
131
+ _, scores = self.CiderD_scorer.compute_score(gts, res_)
132
+ return scores
133
+
134
+ def valid_step(self, sample, model, criterion):
135
+ loss, sample_size, logging_output = criterion(model, sample)
136
+
137
+ model.eval()
138
+ if self.cfg.eval_bleu or self.cfg.eval_cider:
139
+ hyps, refs = self._inference(self.sequence_generator, sample, model)
140
+ if self.cfg.eval_bleu:
141
+ if self.cfg.eval_tokenized_bleu:
142
+ bleu = sacrebleu.corpus_bleu(hyps, list(zip_longest(*refs)), tokenize="none")
143
+ else:
144
+ bleu = sacrebleu.corpus_bleu(hyps, list(zip_longest(*refs)))
145
+ logging_output["_bleu_sys_len"] = bleu.sys_len
146
+ logging_output["_bleu_ref_len"] = bleu.ref_len
147
+ # we split counts into separate entries so that they can be
148
+ # summed efficiently across workers using fast-stat-sync
149
+ assert len(bleu.counts) == EVAL_BLEU_ORDER
150
+ for i in range(EVAL_BLEU_ORDER):
151
+ logging_output["_bleu_counts_" + str(i)] = bleu.counts[i]
152
+ logging_output["_bleu_totals_" + str(i)] = bleu.totals[i]
153
+ if self.cfg.eval_cider:
154
+ scores = self._calculate_cider_scores(hyps, refs)
155
+ logging_output["_cider_score_sum"] = scores.sum()
156
+ logging_output["_cider_cnt"] = scores.size
157
+
158
+ return loss, sample_size, logging_output
159
+
160
+ def reduce_metrics(self, logging_outputs, criterion):
161
+ super().reduce_metrics(logging_outputs, criterion)
162
+
163
+ def sum_logs(key):
164
+ import torch
165
+ result = sum(log.get(key, 0) for log in logging_outputs)
166
+ if torch.is_tensor(result):
167
+ result = result.cpu()
168
+ return result
169
+
170
+ if self.cfg.eval_bleu:
171
+ counts, totals = [], []
172
+ for i in range(EVAL_BLEU_ORDER):
173
+ counts.append(sum_logs("_bleu_counts_" + str(i)))
174
+ totals.append(sum_logs("_bleu_totals_" + str(i)))
175
+
176
+ if max(totals) > 0:
177
+ # log counts as numpy arrays -- log_scalar will sum them correctly
178
+ metrics.log_scalar("_bleu_counts", np.array(counts))
179
+ metrics.log_scalar("_bleu_totals", np.array(totals))
180
+ metrics.log_scalar("_bleu_sys_len", sum_logs("_bleu_sys_len"))
181
+ metrics.log_scalar("_bleu_ref_len", sum_logs("_bleu_ref_len"))
182
+
183
+ def compute_bleu(meters):
184
+ import inspect
185
+ import sacrebleu
186
+
187
+ fn_sig = inspect.getfullargspec(sacrebleu.compute_bleu)[0]
188
+ if "smooth_method" in fn_sig:
189
+ smooth = {"smooth_method": "exp"}
190
+ else:
191
+ smooth = {"smooth": "exp"}
192
+ bleu = sacrebleu.compute_bleu(
193
+ correct=meters["_bleu_counts"].sum,
194
+ total=meters["_bleu_totals"].sum,
195
+ sys_len=meters["_bleu_sys_len"].sum,
196
+ ref_len=meters["_bleu_ref_len"].sum,
197
+ **smooth
198
+ )
199
+ return round(bleu.score, 2)
200
+
201
+ metrics.log_derived("bleu", compute_bleu)
202
+
203
+ if self.cfg.eval_cider:
204
+ def compute_cider(meters):
205
+ cider = meters["_cider_score_sum"].sum / meters["_cider_cnt"].sum
206
+ cider = cider if isinstance(cider, float) else cider.item()
207
+ return round(cider, 3)
208
+
209
+ if sum_logs("_cider_cnt") > 0:
210
+ metrics.log_scalar("_cider_score_sum", sum_logs("_cider_score_sum"))
211
+ metrics.log_scalar("_cider_cnt", sum_logs("_cider_cnt"))
212
+ metrics.log_derived("cider", compute_cider)
213
+
214
+ def _inference(self, generator, sample, model):
215
+
216
+ def decode(toks, escape_unk=False):
217
+ s = self.tgt_dict.string(
218
+ toks.int().cpu(),
219
+ # The default unknown string in fairseq is `<unk>`, but
220
+ # this is tokenized by sacrebleu as `< unk >`, inflating
221
+ # BLEU scores. Instead, we use a somewhat more verbose
222
+ # alternative that is unlikely to appear in the real
223
+ # reference, but doesn't get split into multiple tokens.
224
+ unk_string=("UNKNOWNTOKENINREF" if escape_unk else "UNKNOWNTOKENINHYP"),
225
+ )
226
+ if self.bpe:
227
+ s = self.bpe.decode(s)
228
+ return s
229
+
230
+ gen_out = self.inference_step(generator, [model], sample)
231
+ hyps, refs = [], []
232
+ transtab = str.maketrans({key: None for key in string.punctuation})
233
+ for i in range(len(gen_out)):
234
+ decode_tokens = decode(gen_out[i][0]["tokens"])
235
+ hyps.append(decode_tokens.translate(transtab).strip())
236
+ refs.append(
237
+ [
238
+ sent.translate(transtab).strip()
239
+ for sent in decode(
240
+ utils.strip_pad(sample["target"][i], self.tgt_dict.pad()),
241
+ escape_unk=True, # don't count <unk> as matches to the hypo
242
+ ).split('&&')
243
+ ]
244
+ )
245
+ if self.cfg.eval_print_samples:
246
+ logger.info("example hypothesis: " + hyps[0])
247
+ logger.info("example reference: " + ' && '.join(refs[0]))
248
+
249
+ return hyps, refs
tasks/mm_tasks/image_gen.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The OFA-Sys Team.
2
+ # All rights reserved.
3
+ # This source code is licensed under the Apache 2.0 license
4
+ # found in the LICENSE file in the root directory.
5
+
6
+ from dataclasses import dataclass, field
7
+ import json
8
+ import logging
9
+ import os
10
+ import math
11
+ import base64
12
+ from typing import Optional
13
+ from argparse import Namespace
14
+ from omegaconf import DictConfig, OmegaConf
15
+ from torchvision import transforms
16
+ from PIL import Image
17
+ from io import BytesIO
18
+
19
+ import torch
20
+ import numpy as np
21
+ from fairseq import metrics
22
+ from fairseq.tasks import register_task
23
+ from fairseq.dataclass import ChoiceEnum
24
+
25
+ from models import search, clip
26
+ from models.taming.models.vqgan import GumbelVQ
27
+ from data.mm_data.image_gen_dataset import ImageGenDataset
28
+ from data.file_dataset import FileDataset
29
+
30
+ from tasks.ofa_task import OFATask, OFAConfig
31
+
32
+ logger = logging.getLogger(__name__)
33
+
34
+
35
+ def custom_to_pil(x):
36
+ x = x.detach().cpu()
37
+ x = torch.clamp(x, -1., 1.)
38
+ x = (x + 1.) / 2.
39
+ x = x.permute(1, 2, 0).numpy()
40
+ x = (255 * x).astype(np.uint8)
41
+ x = Image.fromarray(x)
42
+ if not x.mode == "RGB":
43
+ x = x.convert("RGB")
44
+ return x
45
+
46
+
47
+ EVAL_CLIP_METHOD = ChoiceEnum(["ii_sim", "ti_sim"])
48
+
49
+ @dataclass
50
+ class ImageGenConfig(OFAConfig):
51
+ sampling_times: int = field(
52
+ default=1, metadata={"help": "sample times"}
53
+ )
54
+
55
+ code_image_size: int = field(
56
+ default=256, metadata={"help": "code image size"}
57
+ )
58
+
59
+ # options for reporting CLIP score during validation
60
+ eval_clip_method: EVAL_CLIP_METHOD = field(
61
+ default='ti_sim',
62
+ metadata={
63
+ "help": "evaluation with CLIP scores. ii_sim means Similarity between generated Images and ref Images, ti_sim means Similarity between generated Images and input Text"}
64
+ )
65
+
66
+ eval_args: Optional[str] = field(
67
+ default='{}',
68
+ metadata={
69
+ "help": 'generation args for clip scoring, e.g., \'{"beam": 4, "lenpen": 0.6}\', as JSON string'
70
+ },
71
+ )
72
+
73
+ scst: bool = field(
74
+ default=False, metadata={"help": "Self-critical sequence training"}
75
+ )
76
+ scst_args: str = field(
77
+ default='{}',
78
+ metadata={
79
+ "help": 'generation args for Self-critical sequence training, as JSON string'
80
+ },
81
+ )
82
+
83
+ vqgan_model_path: Optional[str] = field(
84
+ default=None,
85
+ metadata={"help": "path of vqgan model"}
86
+ )
87
+ vqgan_config_path: Optional[str] = field(
88
+ default=None,
89
+ metadata={"help": "path of vqgan config"}
90
+ )
91
+ clip_model_path: Optional[str] = field(
92
+ default=None,
93
+ metadata={"help": "clip model path"}
94
+ )
95
+ gen_images_path: str = field(
96
+ default='', metadata={"help": "where to store generated images during evalution. Don't dump images if None. "}
97
+ )
98
+
99
+
100
+ @register_task("image_gen", dataclass=ImageGenConfig)
101
+ class ImageGenTask(OFATask):
102
+ def __init__(self, cfg: ImageGenConfig, src_dict, tgt_dict):
103
+ super().__init__(cfg, src_dict, tgt_dict)
104
+
105
+ def load_dataset(self, split, epoch=1, combine=False, **kwargs):
106
+ paths = self.cfg.data.split(',')
107
+ assert len(paths) > 0
108
+
109
+ if split == 'train':
110
+ file_path = paths[(epoch - 1) % (len(paths) - 1)]
111
+ else:
112
+ file_path = paths[-1]
113
+ dataset = FileDataset(file_path, self.cfg.selected_cols)
114
+
115
+ self.datasets[split] = ImageGenDataset(
116
+ split,
117
+ dataset,
118
+ self.bpe,
119
+ self.src_dict,
120
+ self.tgt_dict,
121
+ max_src_length=self.cfg.max_src_length,
122
+ code_dict_size=self.cfg.code_dict_size,
123
+ code_image_size=self.cfg.code_image_size
124
+ )
125
+
126
+ def build_model(self, cfg):
127
+ model = super().build_model(cfg)
128
+
129
+ device = torch.cuda.current_device()
130
+ clip_model, clip_preprocess = clip.load(self.cfg.clip_model_path, device=device)
131
+ self.clip_model = clip_model
132
+ self.clip_preprocess = clip_preprocess
133
+ self.clip_model.to(device)
134
+ self.clip_model.eval()
135
+
136
+ vqgan_config = OmegaConf.load(self.cfg.vqgan_config_path)
137
+ vqgan = GumbelVQ(**vqgan_config.model.params)
138
+ sd = torch.load(self.cfg.vqgan_model_path, map_location="cpu")["state_dict"]
139
+ missing, unexpected = vqgan.load_state_dict(sd, strict=False)
140
+ for k, v in vqgan.named_parameters():
141
+ v.requires_grad = False
142
+ self.image_tokenizer = vqgan
143
+ self.image_tokenizer.to(device)
144
+ self.image_tokenizer.eval()
145
+
146
+ gen_args = json.loads(self.cfg.eval_args)
147
+ self.sequence_generator = self.build_generator(
148
+ [model], Namespace(**gen_args)
149
+ )
150
+ if self.cfg.scst:
151
+ scst_args = json.loads(self.cfg.scst_args)
152
+ self.scst_generator = self.build_generator(
153
+ [model], Namespace(**scst_args)
154
+ )
155
+
156
+ return model
157
+
158
+ def build_generator(
159
+ self, models, args, seq_gen_cls=None, extra_gen_cls_kwargs=None, prefix_allowed_tokens_fn=None,
160
+ ):
161
+ """
162
+ Build a :class:`~fairseq.SequenceGenerator` instance for this
163
+ task.
164
+
165
+ Args:
166
+ models (List[~fairseq.models.FairseqModel]): ensemble of models
167
+ args (fairseq.dataclass.configs.GenerationConfig):
168
+ configuration object (dataclass) for generation
169
+ extra_gen_cls_kwargs (Dict[str, Any]): extra options to pass
170
+ through to SequenceGenerator
171
+ prefix_allowed_tokens_fn (Callable[[int, torch.Tensor], List[int]]):
172
+ If provided, this function constrains the beam search to
173
+ allowed tokens only at each step. The provided function
174
+ should take 2 arguments: the batch ID (`batch_id: int`)
175
+ and a unidimensional tensor of token ids (`inputs_ids:
176
+ torch.Tensor`). It has to return a `List[int]` with the
177
+ allowed tokens for the next generation step conditioned
178
+ on the previously generated tokens (`inputs_ids`) and
179
+ the batch ID (`batch_id`). This argument is useful for
180
+ constrained generation conditioned on the prefix, as
181
+ described in "Autoregressive Entity Retrieval"
182
+ (https://arxiv.org/abs/2010.00904) and
183
+ https://github.com/facebookresearch/GENRE.
184
+ """
185
+ from models.sequence_generator import SequenceGenerator
186
+
187
+ # Choose search strategy. Defaults to Sampling.
188
+ self.sampling_times = self.cfg.sampling_times
189
+ sampling = True # we have to use sampling instead of beam search in image generation task
190
+ sampling_topk = getattr(args, "sampling_topk", -1)
191
+ sampling_topp = getattr(args, "sampling_topp", -1.0)
192
+
193
+ assert sampling_topk < 0 or sampling, "--sampling-topk requires --sampling"
194
+ assert sampling_topp < 0 or sampling, "--sampling-topp requires --sampling"
195
+
196
+ search_strategy = search.Sampling(
197
+ self.target_dictionary, sampling_topk, sampling_topp
198
+ )
199
+ extra_gen_cls_kwargs = extra_gen_cls_kwargs or {}
200
+
201
+ return SequenceGenerator(
202
+ models,
203
+ self.target_dictionary,
204
+ beam_size=getattr(args, "beam", 5),
205
+ max_len_a=getattr(args, "max_len_a", 0),
206
+ max_len_b=getattr(args, "max_len_b", 200),
207
+ min_len=getattr(args, "min_len", 1),
208
+ normalize_scores=(not getattr(args, "unnormalized", False)),
209
+ len_penalty=getattr(args, "lenpen", 1),
210
+ unk_penalty=getattr(args, "unkpen", 0),
211
+ temperature=getattr(args, "temperature", 1.0),
212
+ match_source_len=getattr(args, "match_source_len", False),
213
+ no_repeat_ngram_size=getattr(args, "no_repeat_ngram_size", 0),
214
+ search_strategy=search_strategy,
215
+ constraint_range=self.cfg.constraint_range,
216
+ gen_code=True,
217
+ **extra_gen_cls_kwargs,
218
+ )
219
+
220
+ def compute_ref_image_similarity(self, hyps, ref, device):
221
+ hyp_images = torch.stack(
222
+ [self.clip_preprocess(hyp_image) for hyp_image in hyps], dim=0
223
+ ).to(device)
224
+
225
+ ref_images = self.clip_preprocess(ref).unsqueeze(0).to(device)
226
+ with torch.no_grad():
227
+ hyp_image_features = self.clip_model.encode_image(hyp_images)
228
+ ref_image_features = self.clip_model.encode_image(ref_images)
229
+ hyp_image_features /= hyp_image_features.norm(dim=-1, keepdim=True)
230
+ ref_image_features /= ref_image_features.norm(dim=-1, keepdim=True)
231
+ similarity = hyp_image_features @ ref_image_features.T
232
+ # scores.append(similarity.max().item())
233
+ sorted_score, indices = torch.sort(similarity.view(-1), descending=True)
234
+ return sorted_score, indices
235
+
236
+ def compute_text_similarity(self, hyps, text, device):
237
+ hyp_images = torch.stack(
238
+ [self.clip_preprocess(hyp_image) for hyp_image in hyps], dim=0
239
+ ).to(device)
240
+
241
+ clip_input = clip.tokenize([text]).to(device)
242
+ with torch.no_grad():
243
+ hyp_image_features = self.clip_model.encode_image(hyp_images)
244
+ hyp_image_features /= hyp_image_features.norm(dim=-1, keepdim=True)
245
+ text_features = self.clip_model.encode_text(clip_input)
246
+ text_features /= text_features.norm(dim=-1, keepdim=True)
247
+ ti_similarity = hyp_image_features @ text_features.T
248
+ sorted_score, indices = torch.sort(ti_similarity.view(-1), descending=True)
249
+ return sorted_score, indices
250
+
251
+ def valid_step(self, sample, model, criterion):
252
+ loss, sample_size, logging_output = criterion(model, sample)
253
+
254
+ model.eval()
255
+ device = sample['target'].device
256
+
257
+ hyps, ref = self.inference_image(self.sequence_generator, sample, [model])
258
+ scores = []
259
+
260
+ tokens = sample['net_input']['src_tokens'][0].view(-1).tolist()
261
+ caption = self.bpe.decode(self.tgt_dict.string([token for token in tokens if token >= 4]))[
262
+ 38:].replace('/', '')
263
+ if self.cfg.eval_clip_method == 'ii_sim':
264
+ similarity_score, indices = self.compute_ref_image_similarity(hyps, ref, device)
265
+ elif self.cfg.eval_clip_method == 'ti_sim':
266
+ similarity_score, indices = self.compute_text_similarity(hyps, caption, device)
267
+ else:
268
+ raise ValueError("unsupported eval method.")
269
+
270
+ scores.append(similarity_score.max().item())
271
+ sorted_hyps = [hyps[indice] for indice in indices]
272
+
273
+ if self.cfg.gen_images_path:
274
+ caption_tokens = sample['net_input']['src_tokens'][0].view(-1).tolist()
275
+ caption = self.bpe.decode(self.tgt_dict.string([token for token in caption_tokens if token >= 4]))[
276
+ 38:].replace('/', '')
277
+ self.dump_images(sorted_hyps, text=caption, path=os.path.join(self.cfg.gen_images_path, 'all_results'))
278
+ self.dump_images(sorted_hyps, text=caption, path=os.path.join(self.cfg.gen_images_path, 'top1'), topk=1)
279
+
280
+ logging_output["_score_sum"] = sum(scores)
281
+ logging_output["_score_cnt"] = len(scores)
282
+
283
+ return loss, sample_size, logging_output
284
+
285
+ def reduce_metrics(self, logging_outputs, criterion):
286
+ super().reduce_metrics(logging_outputs, criterion)
287
+
288
+ def sum_logs(key):
289
+ import torch
290
+ result = sum(log.get(key, 0) for log in logging_outputs)
291
+ if torch.is_tensor(result):
292
+ result = result.cpu()
293
+ return result
294
+
295
+ def compute_score(meters):
296
+ score = meters["_score_sum"].sum / meters["_score_cnt"].sum
297
+ score = score if isinstance(score, float) else score.item()
298
+ return round(score, 3)
299
+
300
+ if sum_logs("_score_cnt") > 0:
301
+ metrics.log_scalar("_score_sum", sum_logs("_score_sum"))
302
+ metrics.log_scalar("_score_cnt", sum_logs("_score_cnt"))
303
+ metrics.log_derived("score", compute_score)
304
+
305
+ def inference_image(self, generator, sample, models):
306
+ hyps, ref = [], None
307
+ for j in range(self.sampling_times):
308
+ gen_out = self.inference_step(generator, models, sample)
309
+ for i in range(len(gen_out)):
310
+ with torch.no_grad():
311
+ tokens = torch.stack([item['tokens'][:-1] for item in gen_out[i]], dim=0)
312
+ tokens += -len(self.src_dict) + self.cfg.code_dict_size + self.cfg.num_bins
313
+ images = self.image_tokenizer.decode_code(
314
+ tokens.view(-1, self.cfg.code_image_size // 8, self.cfg.code_image_size // 8)
315
+ )
316
+ images = [custom_to_pil(image) for image in images]
317
+ hyps += images
318
+ if 'code_images' in sample:
319
+ ref = Image.open(BytesIO(base64.urlsafe_b64decode(sample['code_images'][0]))).convert('RGB')
320
+
321
+ return hyps, ref
322
+
323
+ def dump_images(self, images, text, path, topk=None):
324
+ os.makedirs(path, exist_ok=True)
325
+ if topk:
326
+ images = images[:topk]
327
+ for j, image in enumerate(images):
328
+ save_path = os.path.join(path, f'{text}_{j}.png')
329
+ image.save(save_path)
tasks/mm_tasks/refcoco.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The OFA-Sys Team.
2
+ # All rights reserved.
3
+ # This source code is licensed under the Apache 2.0 license
4
+ # found in the LICENSE file in the root directory.
5
+
6
+ from dataclasses import dataclass, field
7
+ import json
8
+ import logging
9
+ from typing import Optional
10
+ from argparse import Namespace
11
+
12
+ import torch
13
+ from fairseq import metrics
14
+ from fairseq.tasks import register_task
15
+
16
+ from tasks.ofa_task import OFATask, OFAConfig
17
+ from data.mm_data.refcoco_dataset import RefcocoDataset
18
+ from data.file_dataset import FileDataset
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ @dataclass
24
+ class RefcocoConfig(OFAConfig):
25
+ eval_acc: bool = field(
26
+ default=False, metadata={"help": "evaluation with accuracy"}
27
+ )
28
+ eval_args: Optional[str] = field(
29
+ default='{}',
30
+ metadata={
31
+ "help": 'generation args, e.g., \'{"beam": 4, "lenpen": 0.6}\', as JSON string'
32
+ },
33
+ )
34
+ eval_print_samples: bool = field(
35
+ default=False, metadata={"help": "print sample generations during validation"}
36
+ )
37
+
38
+ max_image_size: int = field(
39
+ default=512, metadata={"help": "max image size for normalization"}
40
+ )
41
+ scst: bool = field(
42
+ default=False, metadata={"help": "Self-critical sequence training"}
43
+ )
44
+ scst_args: str = field(
45
+ default='{}',
46
+ metadata={
47
+ "help": 'generation args for Self-critical sequence training, as JSON string'
48
+ },
49
+ )
50
+
51
+
52
+ @register_task("refcoco", dataclass=RefcocoConfig)
53
+ class RefcocoTask(OFATask):
54
+ def __init__(self, cfg: RefcocoConfig, src_dict, tgt_dict):
55
+ super().__init__(cfg, src_dict, tgt_dict)
56
+
57
+ def load_dataset(self, split, epoch=1, combine=False, **kwargs):
58
+ paths = self.cfg.data.split(',')
59
+ assert len(paths) > 0
60
+
61
+ if split == 'train':
62
+ file_path = paths[(epoch - 1) % (len(paths) - 1)]
63
+ else:
64
+ file_path = paths[-1]
65
+ dataset = FileDataset(file_path, self.cfg.selected_cols)
66
+
67
+ self.datasets[split] = RefcocoDataset(
68
+ split,
69
+ dataset,
70
+ self.bpe,
71
+ self.src_dict,
72
+ self.tgt_dict,
73
+ max_src_length=self.cfg.max_src_length,
74
+ max_tgt_length=self.cfg.max_tgt_length,
75
+ patch_image_size=self.cfg.patch_image_size,
76
+ imagenet_default_mean_and_std=self.cfg.imagenet_default_mean_and_std,
77
+ num_bins=self.cfg.num_bins,
78
+ max_image_size=self.cfg.max_image_size
79
+ )
80
+
81
+ def build_model(self, cfg):
82
+ model = super().build_model(cfg)
83
+ if self.cfg.eval_acc:
84
+ gen_args = json.loads(self.cfg.eval_args)
85
+ self.sequence_generator = self.build_generator(
86
+ [model], Namespace(**gen_args)
87
+ )
88
+ if self.cfg.scst:
89
+ scst_args = json.loads(self.cfg.scst_args)
90
+ self.scst_generator = self.build_generator(
91
+ [model], Namespace(**scst_args)
92
+ )
93
+
94
+ return model
95
+
96
+ def _calculate_ap_score(self, hyps, refs, thresh=0.5):
97
+ interacts = torch.cat(
98
+ [torch.where(hyps[:, :2] < refs[:, :2], refs[:, :2], hyps[:, :2]),
99
+ torch.where(hyps[:, 2:] < refs[:, 2:], hyps[:, 2:], refs[:, 2:])],
100
+ dim=1
101
+ )
102
+ area_predictions = (hyps[:, 2] - hyps[:, 0]) * (hyps[:, 3] - hyps[:, 1])
103
+ area_targets = (refs[:, 2] - refs[:, 0]) * (refs[:, 3] - refs[:, 1])
104
+ interacts_w = interacts[:, 2] - interacts[:, 0]
105
+ interacts_h = interacts[:, 3] - interacts[:, 1]
106
+ area_interacts = interacts_w * interacts_h
107
+ ious = area_interacts / (area_predictions + area_targets - area_interacts + 1e-6)
108
+ return ((ious >= thresh) & (interacts_w > 0) & (interacts_h > 0)).float()
109
+
110
+ def valid_step(self, sample, model, criterion):
111
+ loss, sample_size, logging_output = criterion(model, sample)
112
+
113
+ model.eval()
114
+ if self.cfg.eval_acc:
115
+ hyps, refs = self._inference(self.sequence_generator, sample, model)
116
+ hyps = hyps / (self.cfg.num_bins - 1) * self.cfg.max_image_size
117
+ refs = refs / (self.cfg.num_bins - 1) * self.cfg.max_image_size
118
+ hyps[:, ::2] /= sample['w_resize_ratios'].unsqueeze(1)
119
+ hyps[:, 1::2] /= sample['h_resize_ratios'].unsqueeze(1)
120
+ refs[:, ::2] /= sample['w_resize_ratios'].unsqueeze(1)
121
+ refs[:, 1::2] /= sample['h_resize_ratios'].unsqueeze(1)
122
+
123
+ # scores = self._calculate_ap_score(hyps, refs)
124
+ scores = self._calculate_ap_score(hyps, sample['region_coords'].float())
125
+ logging_output["_score_sum"] = scores.sum().item()
126
+ logging_output["_score_cnt"] = scores.size(0)
127
+
128
+ return loss, sample_size, logging_output
129
+
130
+ def reduce_metrics(self, logging_outputs, criterion):
131
+ super().reduce_metrics(logging_outputs, criterion)
132
+
133
+ def sum_logs(key):
134
+ import torch
135
+ result = sum(log.get(key, 0) for log in logging_outputs)
136
+ if torch.is_tensor(result):
137
+ result = result.cpu()
138
+ return result
139
+
140
+ def compute_score(meters):
141
+ score = meters["_score_sum"].sum / meters["_score_cnt"].sum
142
+ score = score if isinstance(score, float) else score.item()
143
+ return round(score, 4)
144
+
145
+ if sum_logs("_score_cnt") > 0:
146
+ metrics.log_scalar("_score_sum", sum_logs("_score_sum"))
147
+ metrics.log_scalar("_score_cnt", sum_logs("_score_cnt"))
148
+ metrics.log_derived("score", compute_score)
149
+
150
+ def _inference(self, generator, sample, model):
151
+ gen_out = self.inference_step(generator, [model], sample)
152
+ hyps, refs = [], []
153
+ for i in range(len(gen_out)):
154
+ hyps.append(gen_out[i][0]["tokens"][:-1] - len(self.src_dict) + self.cfg.num_bins)
155
+ refs.append(sample["target"][i][:-1] - len(self.src_dict) + self.cfg.num_bins)
156
+ if self.cfg.eval_print_samples:
157
+ logger.info("example hypothesis: ", hyps[0])
158
+ logger.info("example reference: ", refs[0])
159
+
160
+ return torch.stack(hyps, dim=0), torch.stack(refs, dim=0)
tasks/mm_tasks/snli_ve.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The OFA-Sys Team.
2
+ # All rights reserved.
3
+ # This source code is licensed under the Apache 2.0 license
4
+ # found in the LICENSE file in the root directory.
5
+
6
+ import json
7
+ import logging
8
+ import math
9
+ from dataclasses import dataclass, field
10
+ from typing import Optional
11
+
12
+ import torch
13
+ from fairseq import metrics
14
+ from fairseq.tasks import register_task
15
+
16
+ from tasks.ofa_task import OFAConfig, OFATask
17
+ from data.mm_data.snli_ve_dataset import SnliVeDataset
18
+ from data.file_dataset import FileDataset
19
+ from data import data_utils
20
+ from utils.trie import Trie
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+
25
+ @dataclass
26
+ class SnliVeConfig(OFAConfig):
27
+ ans2label_dict: Optional[str] = field(
28
+ default='{"no": 0, "yes":1, "maybe": 2}',
29
+ metadata={"help": 'answer to label dict'},
30
+ )
31
+ add_caption: bool = field(
32
+ default=False,
33
+ metadata={"help": "add caption to encoder"},
34
+ )
35
+ valid_batch_size: int = field(
36
+ default=20,
37
+ metadata={"help": "valid batch size per step"},
38
+ )
39
+ prompt_type: Optional[str] = field(
40
+ default=None,
41
+ metadata={"help": "prompt_type"},
42
+ )
43
+
44
+
45
+ @register_task("snli_ve", dataclass=SnliVeConfig)
46
+ class SnliVeTask(OFATask):
47
+ def __init__(self, cfg: SnliVeConfig, src_dict, tgt_dict):
48
+ super().__init__(cfg, src_dict, tgt_dict)
49
+ self.ans2label_dict = json.loads(self.cfg.ans2label_dict)
50
+
51
+ def load_dataset(self, split, epoch=1, combine=False, **kwargs):
52
+ paths = self.cfg.data.split(',')
53
+ assert len(paths) > 0
54
+
55
+ if split == 'train':
56
+ file_path = paths[(epoch - 1) % (len(paths) - 1)]
57
+ else:
58
+ file_path = paths[-1]
59
+ dataset = FileDataset(file_path, self.cfg.selected_cols)
60
+
61
+ self.datasets[split] = SnliVeDataset(
62
+ split,
63
+ dataset,
64
+ self.bpe,
65
+ self.src_dict,
66
+ self.tgt_dict,
67
+ max_src_length=self.cfg.max_src_length,
68
+ max_tgt_length=self.cfg.max_tgt_length,
69
+ patch_image_size=self.cfg.patch_image_size,
70
+ add_caption=self.cfg.add_caption,
71
+ constraint_trie=self.constraint_trie,
72
+ imagenet_default_mean_and_std=self.cfg.imagenet_default_mean_and_std,
73
+ prompt_type=self.cfg.prompt_type
74
+ )
75
+
76
+ def build_model(self, cfg):
77
+ model = super().build_model(cfg)
78
+ answer_item_list = []
79
+ self.index2ans = {}
80
+ self.constraint_trie = Trie(self.tgt_dict.eos())
81
+ for i, answer in enumerate(self.ans2label_dict.keys()):
82
+ answer_item = self.tgt_dict.encode_line(
83
+ line=self.bpe.encode(' ' + answer),
84
+ add_if_not_exist=False,
85
+ append_eos=False
86
+ ).long()
87
+ answer_item_list.append(answer_item)
88
+ self.index2ans[i] = answer
89
+ self.constraint_trie.insert([self.tgt_dict.bos()] + answer_item.tolist() + [self.tgt_dict.eos()])
90
+
91
+ constraint_mask_list = []
92
+ for answer_item in answer_item_list:
93
+ constraint_mask = torch.zeros((len(answer_item)+1, len(self.tgt_dict))).bool()
94
+ for i in range(len(answer_item)+1):
95
+ constraint_prefix_token = [self.src_dict.bos()] + answer_item[:i].tolist()
96
+ constraint_nodes = self.constraint_trie.get_next_layer(constraint_prefix_token)
97
+ constraint_mask[i][constraint_nodes] = True
98
+ constraint_mask_list.append(constraint_mask)
99
+
100
+ self.valid_answers_list = []
101
+ self.valid_constraint_masks_list = []
102
+ for i in range(0, len(answer_item_list), self.cfg.valid_batch_size):
103
+ self.valid_answers_list += [answer_item_list[i:i+self.cfg.valid_batch_size]]
104
+ self.valid_constraint_masks_list += [constraint_mask_list[i:i+self.cfg.valid_batch_size]]
105
+
106
+ return model
107
+
108
+ def build_generator(
109
+ self, models, args, seq_gen_cls=None, extra_gen_cls_kwargs=None, prefix_allowed_tokens_fn=None,
110
+ ):
111
+ seq_generator = super().build_generator(models, args, seq_gen_cls, extra_gen_cls_kwargs, prefix_allowed_tokens_fn)
112
+ seq_generator.constraint_trie = self.constraint_trie
113
+
114
+ return seq_generator
115
+
116
+ def valid_step(self, sample, model, criterion, **extra_kwargs):
117
+ loss, sample_size, logging_output = super().valid_step(sample, model, criterion)
118
+
119
+ model.eval()
120
+ with torch.no_grad():
121
+ encoder_out = model.encoder(
122
+ sample["net_input"]["src_tokens"],
123
+ src_lengths=sample["net_input"]["src_lengths"],
124
+ patch_images=sample["net_input"]["patch_images"],
125
+ patch_masks=sample["net_input"]["patch_masks"]
126
+ )
127
+ device = sample["net_input"]["src_tokens"].device
128
+ eos_item = torch.tensor([self.src_dict.eos()])
129
+ pad = self.src_dict.pad()
130
+ valid_result = []
131
+ for valid_answers, valid_constraint_masks in zip(self.valid_answers_list, self.valid_constraint_masks_list):
132
+ valid_size = len(valid_answers)
133
+ valid_tgt_items = [
134
+ torch.cat([torch.tensor(decoder_prompt[1:]), valid_answer, eos_item])
135
+ for decoder_prompt in sample["decoder_prompts"] for valid_answer in valid_answers
136
+ ]
137
+ valid_prev_items = [
138
+ torch.cat([torch.tensor(decoder_prompt), valid_answer])
139
+ for decoder_prompt in sample["decoder_prompts"] for valid_answer in valid_answers
140
+ ]
141
+ valid_constraint_mask_items = [
142
+ torch.cat([torch.zeros(len(decoder_prompt)-1, valid_constraint_mask.size(1)).bool(), valid_constraint_mask], dim=0)
143
+ for decoder_prompt in sample["decoder_prompts"] for valid_constraint_mask in valid_constraint_masks
144
+ ]
145
+ valid_tgt = data_utils.collate_tokens(valid_tgt_items, pad_idx=pad, left_pad=False).to(device)
146
+ valid_prev_output = data_utils.collate_tokens(valid_prev_items, pad_idx=pad, left_pad=False).to(device)
147
+ valid_constraint_masks = data_utils.collate_tokens(valid_constraint_mask_items, pad_idx=pad, left_pad=False).to(device)
148
+
149
+ new_encoder_out = {}
150
+ new_encoder_out["encoder_out"] = [
151
+ encoder_out["encoder_out"][0].repeat_interleave(valid_size, dim=1)
152
+ ]
153
+ new_encoder_out["encoder_padding_mask"] = [
154
+ encoder_out["encoder_padding_mask"][0].repeat_interleave(valid_size, dim=0)
155
+ ]
156
+ new_encoder_out["position_embeddings"] = [
157
+ encoder_out["position_embeddings"][0].repeat_interleave(valid_size, dim=0)
158
+ ]
159
+
160
+ decoder_out = model.decoder(valid_prev_output, encoder_out=new_encoder_out)
161
+ decoder_out[0].masked_fill_(~valid_constraint_masks, -math.inf)
162
+ lprobs = model.get_normalized_probs(decoder_out, log_probs=True)
163
+ scores = lprobs.gather(dim=-1, index=valid_tgt.unsqueeze(-1)).squeeze(-1)
164
+ scores = scores.masked_fill(valid_tgt.eq(self.tgt_dict.pad()), 0)
165
+ scores = scores.masked_fill((~valid_constraint_masks).all(2), 0)
166
+ scores = scores.sum(1)
167
+ scores = scores.view(-1, valid_size)
168
+ valid_result.append(scores)
169
+
170
+ valid_result = torch.cat(valid_result, dim=-1)
171
+ predicts = valid_result.argmax(1).tolist()
172
+ hyps = [self.index2ans[predict_index] for predict_index in predicts]
173
+ scores = [ref_dict.get(hyp, 0) for ref_dict, hyp in zip(sample['ref_dict'], hyps)]
174
+ logging_output["_snli_score_sum"] = sum(scores)
175
+ logging_output["_snli_cnt"] = len(scores)
176
+
177
+ return loss, sample_size, logging_output
178
+
179
+ def reduce_metrics(self, logging_outputs, criterion):
180
+ super().reduce_metrics(logging_outputs, criterion)
181
+
182
+ def sum_logs(key):
183
+ import torch
184
+ result = sum(log.get(key, 0) for log in logging_outputs)
185
+ if torch.is_tensor(result):
186
+ result = result.cpu()
187
+ return result
188
+
189
+ def compute_score(meters):
190
+ score = meters["_snli_score_sum"].sum / meters["_snli_cnt"].sum
191
+ score = score if isinstance(score, float) else score.item()
192
+ return round(score, 4)
193
+
194
+ if sum_logs("_snli_cnt") > 0:
195
+ metrics.log_scalar("_snli_score_sum", sum_logs("_snli_score_sum"))
196
+ metrics.log_scalar("_snli_cnt", sum_logs("_snli_cnt"))
197
+ metrics.log_derived("snli_score", compute_score)
tasks/mm_tasks/vqa_gen.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The OFA-Sys Team.
2
+ # All rights reserved.
3
+ # This source code is licensed under the Apache 2.0 license
4
+ # found in the LICENSE file in the root directory.
5
+
6
+ from dataclasses import dataclass, field
7
+ import json
8
+ import logging
9
+ import os
10
+ import math
11
+ import pickle
12
+ from typing import Optional
13
+ from argparse import Namespace
14
+ from data.file_dataset import FileDataset
15
+
16
+ import torch
17
+ from fairseq import metrics
18
+ from fairseq.tasks import register_task
19
+
20
+ from models import search
21
+ from data.mm_data.vqa_gen_dataset import VqaGenDataset
22
+ from data import data_utils
23
+ from tasks.ofa_task import OFAConfig, OFATask
24
+ from utils.trie import Trie
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+
29
+ def get_symbols_to_strip_from_output(generator):
30
+ if hasattr(generator, "symbols_to_strip_from_output"):
31
+ return generator.symbols_to_strip_from_output
32
+ else:
33
+ return {generator.bos, generator.eos}
34
+
35
+
36
+ def decode_fn(x, tgt_dict, bpe, generator, tokenizer=None):
37
+ x = tgt_dict.string(x.int().cpu(), extra_symbols_to_ignore=get_symbols_to_strip_from_output(generator))
38
+ if bpe is not None:
39
+ x = bpe.decode(x)
40
+ if tokenizer is not None:
41
+ x = tokenizer.decode(x)
42
+ return x
43
+
44
+
45
+ @dataclass
46
+ class VqaGenConfig(OFAConfig):
47
+ max_object_length: int = field(
48
+ default=30, metadata={"help": "the maximum object sequence length"}
49
+ )
50
+ ans2label_dict: Optional[str] = field(
51
+ default='{"no": 0, "yes":1}',
52
+ metadata={"help": 'answer to label dict'},
53
+ )
54
+ ans2label_file: Optional[str] = field(
55
+ default=None,
56
+ metadata={"help": "path to load ans2label file"},
57
+ )
58
+
59
+ add_object: bool = field(
60
+ default=False,
61
+ metadata={"help": "add object to encoder"},
62
+ )
63
+ valid_batch_size: int = field(
64
+ default=20,
65
+ metadata={"help": "valid batch size per step"},
66
+ )
67
+ prompt_type: Optional[str] = field(
68
+ default=None,
69
+ metadata={"help": "prompt_type"},
70
+ )
71
+ uses_ema: Optional[bool] = field(
72
+ default=False,
73
+ metadata={"help": "whether to use ema"},
74
+ )
75
+ val_inference_type: Optional[str] = field(
76
+ default='allcand',
77
+ metadata={"help": "inference type in validation (allcand or beamsearch), default to allcand"},
78
+ )
79
+ eval_args: Optional[str] = field(
80
+ default='{"beam":5,"unnormalized":true,"temperature":1.0}',
81
+ metadata={
82
+ "help": 'generation args as JSON string for inference, only activated when --val-inference-type=beamsearch'
83
+ },
84
+ )
85
+
86
+
87
+ @register_task("vqa_gen", dataclass=VqaGenConfig)
88
+ class VqaGenTask(OFATask):
89
+ def __init__(self, cfg: VqaGenConfig, src_dict, tgt_dict):
90
+ super().__init__(cfg, src_dict, tgt_dict)
91
+
92
+ self.ans2label_dict = None
93
+ if self.cfg.ans2label_file is not None:
94
+ self.ans2label_dict = pickle.load(open(self.cfg.ans2label_file, "rb"))
95
+ else:
96
+ self.ans2label_dict = json.loads(self.cfg.ans2label_dict)
97
+
98
+ self.uses_ema = self.cfg.uses_ema
99
+
100
+ assert self.cfg.val_inference_type in ["allcand", "beamsearch"], \
101
+ "Unknown inference type encountered: {}, should be allcand or beamsearch.".format(self.cfg.val_inference_type)
102
+
103
+ def load_dataset(self, split, epoch=1, combine=False, **kwargs):
104
+ paths = self.cfg.data.split(',')
105
+ assert len(paths) > 0
106
+
107
+ if split == 'train':
108
+ table_path = paths[(epoch - 1) % (len(paths) - 1)]
109
+ else:
110
+ table_path = paths[-1]
111
+ dataset = FileDataset(table_path, self.cfg.selected_cols)
112
+
113
+ self.datasets[split] = VqaGenDataset(
114
+ split,
115
+ dataset,
116
+ self.bpe,
117
+ self.src_dict,
118
+ self.tgt_dict,
119
+ max_src_length=self.cfg.max_src_length,
120
+ max_object_length=self.cfg.max_object_length,
121
+ max_tgt_length=self.cfg.max_tgt_length,
122
+ patch_image_size=self.cfg.patch_image_size,
123
+ add_object=self.cfg.add_object,
124
+ constraint_trie=self.constraint_trie,
125
+ imagenet_default_mean_and_std=self.cfg.imagenet_default_mean_and_std,
126
+ prompt_type=self.cfg.prompt_type
127
+ )
128
+
129
+ def build_model(self, cfg):
130
+ model = super().build_model(cfg)
131
+ answer_item_list = []
132
+ self.index2ans = {}
133
+ self.constraint_trie = Trie(self.tgt_dict.eos())
134
+ for i, answer in enumerate(self.ans2label_dict.keys()):
135
+ answer_item = self.tgt_dict.encode_line(
136
+ line=self.bpe.encode(' ' + answer),
137
+ add_if_not_exist=False,
138
+ append_eos=False
139
+ ).long()
140
+ answer_item_list.append(answer_item)
141
+ self.index2ans[i] = answer
142
+ self.constraint_trie.insert([self.tgt_dict.bos()] + answer_item.tolist() + [self.tgt_dict.eos()])
143
+
144
+ constraint_mask_list = []
145
+ for answer_item in answer_item_list:
146
+ constraint_mask = torch.zeros((len(answer_item)+1, len(self.tgt_dict))).bool()
147
+ for i in range(len(answer_item)+1):
148
+ constraint_prefix_token = [self.src_dict.bos()] + answer_item[:i].tolist()
149
+ constraint_nodes = self.constraint_trie.get_next_layer(constraint_prefix_token)
150
+ constraint_mask[i][constraint_nodes] = True
151
+ constraint_mask_list.append(constraint_mask)
152
+
153
+ if self.cfg.val_inference_type == "allcand":
154
+ self.valid_answers_list = []
155
+ self.valid_constraint_masks_list = []
156
+ for i in range(0, len(answer_item_list), self.cfg.valid_batch_size):
157
+ self.valid_answers_list += [answer_item_list[i:i+self.cfg.valid_batch_size]]
158
+ self.valid_constraint_masks_list += [constraint_mask_list[i:i+self.cfg.valid_batch_size]]
159
+ elif self.cfg.val_inference_type == "beamsearch":
160
+ gen_args = json.loads(self.cfg.eval_args)
161
+ self.generator = self.build_generator(
162
+ [model], Namespace(**gen_args)
163
+ )
164
+ else:
165
+ raise NotImplementedError("Error: Unknown inference type encountered.")
166
+
167
+ return model
168
+
169
+ def build_generator(
170
+ self, models, args, seq_gen_cls=None, extra_gen_cls_kwargs=None, prefix_allowed_tokens_fn=None,
171
+ ):
172
+ seq_generator = super().build_generator(models, args, seq_gen_cls, extra_gen_cls_kwargs, prefix_allowed_tokens_fn)
173
+ seq_generator.constraint_trie = self.constraint_trie
174
+
175
+ return seq_generator
176
+
177
+ def valid_step(self, sample, model, criterion, **extra_kwargs):
178
+ loss, sample_size, logging_output = super().valid_step(sample, model, criterion)
179
+
180
+ if self.uses_ema:
181
+ assert 'ema_model' in extra_kwargs and extra_kwargs['ema_model'] is not None
182
+ if self.uses_ema:
183
+ eval_model = extra_kwargs['ema_model']
184
+ else:
185
+ eval_model = model
186
+
187
+ eval_model.eval()
188
+ with torch.no_grad():
189
+ if self.cfg.val_inference_type == "allcand":
190
+ encoder_out = eval_model.encoder(
191
+ sample["net_input"]["src_tokens"],
192
+ src_lengths=sample["net_input"]["src_lengths"],
193
+ patch_images=sample["net_input"]["patch_images"],
194
+ patch_masks=sample["net_input"]["patch_masks"]
195
+ )
196
+ device = sample["net_input"]["src_tokens"].device
197
+ eos_item = torch.tensor([self.src_dict.eos()])
198
+ pad = self.src_dict.pad()
199
+ valid_result = []
200
+ for valid_answers, valid_constraint_masks in zip(self.valid_answers_list, self.valid_constraint_masks_list):
201
+ valid_size = len(valid_answers)
202
+ valid_tgt_items = [
203
+ torch.cat([torch.tensor(decoder_prompt[1:]), valid_answer, eos_item])
204
+ for decoder_prompt in sample["decoder_prompts"] for valid_answer in valid_answers
205
+ ]
206
+ valid_prev_items = [
207
+ torch.cat([torch.tensor(decoder_prompt), valid_answer])
208
+ for decoder_prompt in sample["decoder_prompts"] for valid_answer in valid_answers
209
+ ]
210
+ valid_constraint_mask_items = [
211
+ torch.cat([torch.zeros(len(decoder_prompt)-1, valid_constraint_mask.size(1)).bool(), valid_constraint_mask], dim=0)
212
+ for decoder_prompt in sample["decoder_prompts"] for valid_constraint_mask in valid_constraint_masks
213
+ ]
214
+ valid_tgt = data_utils.collate_tokens(valid_tgt_items, pad_idx=pad, left_pad=False).to(device)
215
+ valid_prev_output = data_utils.collate_tokens(valid_prev_items, pad_idx=pad, left_pad=False).to(device)
216
+ valid_constraint_masks = data_utils.collate_tokens(valid_constraint_mask_items, pad_idx=pad, left_pad=False).to(device)
217
+
218
+ new_encoder_out = {}
219
+ new_encoder_out["encoder_out"] = [
220
+ encoder_out["encoder_out"][0].repeat_interleave(valid_size, dim=1)
221
+ ]
222
+ new_encoder_out["encoder_padding_mask"] = [
223
+ encoder_out["encoder_padding_mask"][0].repeat_interleave(valid_size, dim=0)
224
+ ]
225
+ new_encoder_out["position_embeddings"] = [
226
+ encoder_out["position_embeddings"][0].repeat_interleave(valid_size, dim=0)
227
+ ]
228
+
229
+ decoder_out = eval_model.decoder(valid_prev_output, encoder_out=new_encoder_out)
230
+ decoder_out[0].masked_fill_(~valid_constraint_masks, -math.inf)
231
+ lprobs = eval_model.get_normalized_probs(decoder_out, log_probs=True)
232
+ scores = lprobs.gather(dim=-1, index=valid_tgt.unsqueeze(-1)).squeeze(-1)
233
+ scores = scores.masked_fill(valid_tgt.eq(self.tgt_dict.pad()), 0)
234
+ scores = scores.masked_fill((~valid_constraint_masks).all(2), 0)
235
+ scores = scores.sum(1)
236
+ scores = scores.view(-1, valid_size)
237
+ valid_result.append(scores)
238
+
239
+ valid_result = torch.cat(valid_result, dim=-1)
240
+ predicts = valid_result.argmax(1).tolist()
241
+ hyps = [self.index2ans[predict_index] for predict_index in predicts]
242
+
243
+ elif self.cfg.val_inference_type == "beamsearch":
244
+ raw_hyps = self.inference_step(self.generator, [eval_model], sample, prefix_tokens=sample['prefix_tokens'])
245
+ hyps = []
246
+ for i, sample_id in enumerate(sample["id"].tolist()):
247
+ prefix_len = sample['prefix_tokens'][i].ne(1).sum().item()
248
+ detok_hypo_str = decode_fn(raw_hyps[i][0]["tokens"][prefix_len:], self.tgt_dict, self.bpe, self.generator)
249
+ hyps.append(detok_hypo_str.strip())
250
+
251
+ else:
252
+ raise NotImplementedError("Error: Unknown inference type encountered.")
253
+
254
+ scores = [ref_dict.get(hyp, 0) for ref_dict, hyp in zip(sample['ref_dict'], hyps)]
255
+ logging_output["_vqa_score_sum"] = sum(scores)
256
+ logging_output["_vqa_cnt"] = len(scores)
257
+
258
+ return loss, sample_size, logging_output
259
+
260
+ def reduce_metrics(self, logging_outputs, criterion):
261
+ super().reduce_metrics(logging_outputs, criterion)
262
+
263
+ def sum_logs(key):
264
+ import torch
265
+ result = sum(log.get(key, 0) for log in logging_outputs)
266
+ if torch.is_tensor(result):
267
+ result = result.cpu()
268
+ return result
269
+
270
+ def compute_score(meters):
271
+ score = meters["_vqa_score_sum"].sum / meters["_vqa_cnt"].sum
272
+ score = score if isinstance(score, float) else score.item()
273
+ return round(score, 4)
274
+
275
+ if sum_logs("_vqa_cnt") > 0:
276
+ metrics.log_scalar("_vqa_score_sum", sum_logs("_vqa_score_sum"))
277
+ metrics.log_scalar("_vqa_cnt", sum_logs("_vqa_cnt"))
278
+ metrics.log_derived("vqa_score", compute_score)
tasks/ofa_task.py ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The OFA-Sys Team.
2
+ # All rights reserved.
3
+ # This source code is licensed under the Apache 2.0 license
4
+ # found in the LICENSE file in the root directory.
5
+
6
+ from dataclasses import dataclass, field
7
+ import logging
8
+ import os
9
+ import math
10
+ import torch
11
+ from typing import Dict, Optional
12
+
13
+ from fairseq import search
14
+ from fairseq.data import FairseqDataset, iterators
15
+ from fairseq.optim.amp_optimizer import AMPOptimizer
16
+ from fairseq.dataclass import FairseqDataclass
17
+ from fairseq.tasks import FairseqTask, register_task
18
+ from omegaconf import DictConfig
19
+
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ @dataclass
25
+ class OFAConfig(FairseqDataclass):
26
+ data: Optional[str] = field(
27
+ default=None,
28
+ metadata={
29
+ "help": "comma separated path to data list, will be iterated upon during epochs "
30
+ "in round-robin manner; valid data are always in the last"
31
+ },
32
+ )
33
+ selected_cols: Optional[str] = field(
34
+ default=None,
35
+ metadata={"help": "selected cols"},
36
+ )
37
+ bpe_dir: Optional[str] = field(
38
+ default=None,
39
+ metadata={"help": "bpe dir"},
40
+ )
41
+ max_source_positions: int = field(
42
+ default=1024, metadata={"help": "max number of tokens in the source sequence"}
43
+ )
44
+ max_target_positions: int = field(
45
+ default=1024, metadata={"help": "max number of tokens in the target sequence"}
46
+ )
47
+ max_src_length: int = field(
48
+ default=128, metadata={"help": "the maximum src sequence length"}
49
+ )
50
+ max_tgt_length: int = field(
51
+ default=30, metadata={"help": "the maximum target sequence length"}
52
+ )
53
+
54
+ code_dict_size: int = field(
55
+ default=8192, metadata={"help": "code dict size"}
56
+ )
57
+ patch_image_size: int = field(
58
+ default=480, metadata={"help": "patch image size"}
59
+ )
60
+ num_bins: int = field(
61
+ default=1000, metadata={"help": "number of quantization bins"}
62
+ )
63
+
64
+ imagenet_default_mean_and_std: bool = field(
65
+ default=False,
66
+ metadata={"help": "imagenet normalize"},
67
+ )
68
+ constraint_range: Optional[str] = field(
69
+ default=None,
70
+ metadata={"help": "constraint range"}
71
+ )
72
+
73
+
74
+ @register_task("ofa", dataclass=OFAConfig)
75
+ class OFATask(FairseqTask):
76
+ def __init__(self, cfg: OFAConfig, src_dict, tgt_dict):
77
+ super().__init__(cfg)
78
+ self.src_dict = src_dict
79
+ self.tgt_dict = tgt_dict
80
+
81
+ @classmethod
82
+ def setup_task(cls, cfg: DictConfig, **kwargs):
83
+ """Setup the task."""
84
+
85
+ # load dictionaries
86
+ src_dict = cls.load_dictionary(
87
+ os.path.join(cfg.bpe_dir, "dict.txt")
88
+ )
89
+ tgt_dict = cls.load_dictionary(
90
+ os.path.join(cfg.bpe_dir, "dict.txt")
91
+ )
92
+ src_dict.add_symbol("<mask>")
93
+ tgt_dict.add_symbol("<mask>")
94
+ for i in range(cfg.code_dict_size):
95
+ src_dict.add_symbol("<code_{}>".format(i))
96
+ tgt_dict.add_symbol("<code_{}>".format(i))
97
+ # quantization
98
+ for i in range(cfg.num_bins):
99
+ src_dict.add_symbol("<bin_{}>".format(i))
100
+ tgt_dict.add_symbol("<bin_{}>".format(i))
101
+
102
+ logger.info("source dictionary: {} types".format(len(src_dict)))
103
+ logger.info("target dictionary: {} types".format(len(tgt_dict)))
104
+ return cls(cfg, src_dict, tgt_dict)
105
+
106
+ def get_batch_iterator(
107
+ self,
108
+ dataset,
109
+ max_tokens=None,
110
+ max_sentences=None,
111
+ max_positions=None,
112
+ ignore_invalid_inputs=False,
113
+ required_batch_size_multiple=1,
114
+ seed=1,
115
+ num_shards=1,
116
+ shard_id=0,
117
+ num_workers=0,
118
+ epoch=1,
119
+ data_buffer_size=0,
120
+ disable_iterator_cache=False,
121
+ ):
122
+ assert isinstance(dataset, FairseqDataset)
123
+
124
+ # initialize the dataset with the correct starting epoch
125
+ dataset.set_epoch(epoch)
126
+
127
+ # create mini-batches with given size constraints
128
+ batch_sampler = [
129
+ [j for j in range(i, min(i + max_sentences, len(dataset)))]
130
+ for i in range(0, len(dataset), max_sentences)
131
+ ]
132
+ total_row_count = dataset.dataset.get_total_row_count()
133
+ num_batches = math.ceil(math.ceil(total_row_count / num_shards) / max_sentences)
134
+ if len(batch_sampler) < num_batches:
135
+ batch_sampler.append([])
136
+
137
+ # return a reusable, sharded iterator
138
+ epoch_iter = iterators.EpochBatchIterator(
139
+ dataset=dataset,
140
+ collate_fn=dataset.collater,
141
+ batch_sampler=batch_sampler,
142
+ seed=seed,
143
+ num_shards=1,
144
+ shard_id=0,
145
+ num_workers=num_workers,
146
+ epoch=epoch,
147
+ buffer_size=data_buffer_size
148
+ )
149
+
150
+ return epoch_iter
151
+
152
+ def build_model(self, cfg: FairseqDataclass):
153
+ model = super().build_model(cfg)
154
+ bpe_dict = {
155
+ "_name": "gpt2",
156
+ "gpt2_encoder_json": os.path.join(self.cfg.bpe_dir, "encoder.json"),
157
+ "gpt2_vocab_bpe": os.path.join(self.cfg.bpe_dir, "vocab.bpe")
158
+ }
159
+ bpe_dict = DictConfig(bpe_dict)
160
+ self.bpe = self.build_bpe(bpe_dict)
161
+ return model
162
+
163
+ def build_generator(
164
+ self, models, args, seq_gen_cls=None, extra_gen_cls_kwargs=None, prefix_allowed_tokens_fn=None,
165
+ ):
166
+ """
167
+ Build a :class:`~fairseq.SequenceGenerator` instance for this
168
+ task.
169
+
170
+ Args:
171
+ models (List[~fairseq.models.FairseqModel]): ensemble of models
172
+ args (fairseq.dataclass.configs.GenerationConfig):
173
+ configuration object (dataclass) for generation
174
+ extra_gen_cls_kwargs (Dict[str, Any]): extra options to pass
175
+ through to SequenceGenerator
176
+ prefix_allowed_tokens_fn (Callable[[int, torch.Tensor], List[int]]):
177
+ If provided, this function constrains the beam search to
178
+ allowed tokens only at each step. The provided function
179
+ should take 2 arguments: the batch ID (`batch_id: int`)
180
+ and a unidimensional tensor of token ids (`inputs_ids:
181
+ torch.Tensor`). It has to return a `List[int]` with the
182
+ allowed tokens for the next generation step conditioned
183
+ on the previously generated tokens (`inputs_ids`) and
184
+ the batch ID (`batch_id`). This argument is useful for
185
+ constrained generation conditioned on the prefix, as
186
+ described in "Autoregressive Entity Retrieval"
187
+ (https://arxiv.org/abs/2010.00904) and
188
+ https://github.com/facebookresearch/GENRE.
189
+ """
190
+ if getattr(args, "score_reference", False):
191
+ from fairseq.sequence_scorer import SequenceScorer
192
+
193
+ return SequenceScorer(
194
+ self.target_dictionary,
195
+ compute_alignment=getattr(args, "print_alignment", False),
196
+ )
197
+
198
+ from fairseq.sequence_generator import (
199
+ # SequenceGenerator,
200
+ SequenceGeneratorWithAlignment,
201
+ )
202
+ from models.sequence_generator import SequenceGenerator
203
+
204
+ # Choose search strategy. Defaults to Beam Search.
205
+ sampling = getattr(args, "sampling", False)
206
+ sampling_topk = getattr(args, "sampling_topk", -1)
207
+ sampling_topp = getattr(args, "sampling_topp", -1.0)
208
+ diverse_beam_groups = getattr(args, "diverse_beam_groups", -1)
209
+ diverse_beam_strength = getattr(args, "diverse_beam_strength", 0.5)
210
+ match_source_len = getattr(args, "match_source_len", False)
211
+ diversity_rate = getattr(args, "diversity_rate", -1)
212
+ constrained = getattr(args, "constraints", False)
213
+ if prefix_allowed_tokens_fn is None:
214
+ prefix_allowed_tokens_fn = getattr(args, "prefix_allowed_tokens_fn", None)
215
+ if (
216
+ sum(
217
+ int(cond)
218
+ for cond in [
219
+ sampling,
220
+ diverse_beam_groups > 0,
221
+ match_source_len,
222
+ diversity_rate > 0,
223
+ ]
224
+ )
225
+ > 1
226
+ ):
227
+ raise ValueError("Provided Search parameters are mutually exclusive.")
228
+ assert sampling_topk < 0 or sampling, "--sampling-topk requires --sampling"
229
+ assert sampling_topp < 0 or sampling, "--sampling-topp requires --sampling"
230
+
231
+ if sampling:
232
+ search_strategy = search.Sampling(
233
+ self.target_dictionary, sampling_topk, sampling_topp
234
+ )
235
+ elif diverse_beam_groups > 0:
236
+ search_strategy = search.DiverseBeamSearch(
237
+ self.target_dictionary, diverse_beam_groups, diverse_beam_strength
238
+ )
239
+ elif match_source_len:
240
+ # this is useful for tagging applications where the output
241
+ # length should match the input length, so we hardcode the
242
+ # length constraints for simplicity
243
+ search_strategy = search.LengthConstrainedBeamSearch(
244
+ self.target_dictionary,
245
+ min_len_a=1,
246
+ min_len_b=0,
247
+ max_len_a=1,
248
+ max_len_b=0,
249
+ )
250
+ elif diversity_rate > -1:
251
+ search_strategy = search.DiverseSiblingsSearch(
252
+ self.target_dictionary, diversity_rate
253
+ )
254
+ elif constrained:
255
+ search_strategy = search.LexicallyConstrainedBeamSearch(
256
+ self.target_dictionary, args.constraints
257
+ )
258
+ elif prefix_allowed_tokens_fn:
259
+ search_strategy = search.PrefixConstrainedBeamSearch(
260
+ self.target_dictionary, prefix_allowed_tokens_fn
261
+ )
262
+ else:
263
+ search_strategy = search.BeamSearch(self.target_dictionary)
264
+
265
+ extra_gen_cls_kwargs = extra_gen_cls_kwargs or {}
266
+ if seq_gen_cls is None:
267
+ if getattr(args, "print_alignment", False):
268
+ seq_gen_cls = SequenceGeneratorWithAlignment
269
+ extra_gen_cls_kwargs["print_alignment"] = args.print_alignment
270
+ else:
271
+ seq_gen_cls = SequenceGenerator
272
+
273
+ return seq_gen_cls(
274
+ models,
275
+ self.target_dictionary,
276
+ beam_size=getattr(args, "beam", 5),
277
+ max_len_a=getattr(args, "max_len_a", 0),
278
+ max_len_b=getattr(args, "max_len_b", 200),
279
+ min_len=getattr(args, "min_len", 1),
280
+ normalize_scores=(not getattr(args, "unnormalized", False)),
281
+ len_penalty=getattr(args, "lenpen", 1),
282
+ unk_penalty=getattr(args, "unkpen", 0),
283
+ temperature=getattr(args, "temperature", 1.0),
284
+ match_source_len=getattr(args, "match_source_len", False),
285
+ no_repeat_ngram_size=getattr(args, "no_repeat_ngram_size", 0),
286
+ search_strategy=search_strategy,
287
+ constraint_range=self.cfg.constraint_range,
288
+ **extra_gen_cls_kwargs,
289
+ )
290
+
291
+ def train_step(
292
+ self, sample, model, criterion, optimizer, update_num, ignore_grad=False, **extra_kwargs
293
+ ):
294
+ """
295
+ Do forward and backward, and return the loss as computed by *criterion*
296
+ for the given *model* and *sample*.
297
+
298
+ Args:
299
+ sample (dict): the mini-batch. The format is defined by the
300
+ :class:`~fairseq.data.FairseqDataset`.
301
+ model (~fairseq.models.BaseFairseqModel): the model
302
+ criterion (~fairseq.criterions.FairseqCriterion): the criterion
303
+ optimizer (~fairseq.optim.FairseqOptimizer): the optimizer
304
+ update_num (int): the current update
305
+ ignore_grad (bool): multiply loss by 0 if this is set to True
306
+
307
+ Returns:
308
+ tuple:
309
+ - the loss
310
+ - the sample size, which is used as the denominator for the
311
+ gradient
312
+ - logging outputs to display while training
313
+ """
314
+ model.train()
315
+ model.set_num_updates(update_num)
316
+ with torch.autograd.profiler.record_function("forward"):
317
+ with torch.cuda.amp.autocast(enabled=(isinstance(optimizer, AMPOptimizer))):
318
+ loss, sample_size, logging_output = criterion(model, sample, update_num=update_num)
319
+ if ignore_grad:
320
+ loss *= 0
321
+ with torch.autograd.profiler.record_function("backward"):
322
+ optimizer.backward(loss)
323
+ return loss, sample_size, logging_output
324
+
325
+ def max_positions(self):
326
+ """Return the max sentence length allowed by the task."""
327
+ return (self.cfg.max_source_positions, self.cfg.max_target_positions)
328
+
329
+ @property
330
+ def source_dictionary(self):
331
+ """Return the source :class:`~fairseq.data.Dictionary`."""
332
+ return self.src_dict
333
+
334
+ @property
335
+ def target_dictionary(self):
336
+ """Return the target :class:`~fairseq.data.Dictionary`."""
337
+ return self.tgt_dict
utils/BPE/__init__.py ADDED
File without changes
utils/BPE/dict.txt ADDED
The diff for this file is too large to render. See raw diff
utils/BPE/encoder.json ADDED
The diff for this file is too large to render. See raw diff
utils/BPE/vocab.bpe ADDED
The diff for this file is too large to render. See raw diff
utils/__init__.py ADDED
File without changes
utils/checkpoint_utils.py ADDED
@@ -0,0 +1,875 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import ast
7
+ import collections
8
+ import contextlib
9
+ import logging
10
+ import numpy as np
11
+ import os
12
+ import re
13
+ import time
14
+ import traceback
15
+ import math
16
+ from collections import OrderedDict
17
+ from typing import Any, Dict, Optional, Union
18
+
19
+ import torch
20
+ from fairseq.dataclass.configs import CheckpointConfig
21
+ from fairseq.dataclass.utils import (
22
+ convert_namespace_to_omegaconf,
23
+ overwrite_args_by_name,
24
+ )
25
+ from fairseq.distributed.fully_sharded_data_parallel import FSDP, has_FSDP
26
+ from fairseq.file_io import PathManager
27
+ from fairseq.models import FairseqDecoder, FairseqEncoder
28
+ from omegaconf import DictConfig, open_dict, OmegaConf
29
+
30
+ from data import data_utils
31
+
32
+ logger = logging.getLogger(__name__)
33
+
34
+
35
+ def save_checkpoint(cfg: CheckpointConfig, trainer, epoch_itr, val_loss):
36
+ from fairseq import meters
37
+
38
+ # only one worker should attempt to create the required dir
39
+ if trainer.data_parallel_rank == 0:
40
+ os.makedirs(cfg.save_dir, exist_ok=True)
41
+
42
+ prev_best = getattr(save_checkpoint, "best", val_loss)
43
+ if val_loss is not None:
44
+ best_function = max if cfg.maximize_best_checkpoint_metric else min
45
+ save_checkpoint.best = best_function(val_loss, prev_best)
46
+
47
+ if cfg.no_save:
48
+ return
49
+
50
+ trainer.consolidate_optimizer() # TODO(SS): do we need this if no_save_optimizer_state
51
+
52
+ if not trainer.should_save_checkpoint_on_current_rank:
53
+ if trainer.always_call_state_dict_during_save_checkpoint:
54
+ trainer.state_dict()
55
+ return
56
+
57
+ write_timer = meters.StopwatchMeter()
58
+ write_timer.start()
59
+
60
+ epoch = epoch_itr.epoch
61
+ end_of_epoch = epoch_itr.end_of_epoch()
62
+ updates = trainer.get_num_updates()
63
+
64
+ logger.info(f"Preparing to save checkpoint for epoch {epoch} @ {updates} updates")
65
+
66
+ def is_better(a, b):
67
+ return a >= b if cfg.maximize_best_checkpoint_metric else a <= b
68
+
69
+ suffix = trainer.checkpoint_suffix
70
+ checkpoint_conds = collections.OrderedDict()
71
+ checkpoint_conds["checkpoint{}{}.pt".format(epoch, suffix)] = (
72
+ end_of_epoch and not cfg.no_epoch_checkpoints and epoch % cfg.save_interval == 0
73
+ )
74
+ checkpoint_conds["checkpoint_{}_{}{}.pt".format(epoch, updates, suffix)] = (
75
+ not end_of_epoch
76
+ and cfg.save_interval_updates > 0
77
+ and updates % cfg.save_interval_updates == 0
78
+ )
79
+ checkpoint_conds["checkpoint_best{}.pt".format(suffix)] = val_loss is not None and (
80
+ not hasattr(save_checkpoint, "best")
81
+ or is_better(val_loss, save_checkpoint.best)
82
+ )
83
+ if val_loss is not None and cfg.keep_best_checkpoints > 0:
84
+ worst_best = getattr(save_checkpoint, "best", None)
85
+ chkpts = checkpoint_paths(
86
+ cfg.save_dir,
87
+ pattern=r"checkpoint\.best_{}_(\d+\.?\d*){}\.pt".format(
88
+ cfg.best_checkpoint_metric, suffix
89
+ ),
90
+ )
91
+ if len(chkpts) > 0:
92
+ p = chkpts[-1] if cfg.maximize_best_checkpoint_metric else chkpts[0]
93
+ worst_best = float(p.rsplit("_")[-1].replace("{}.pt".format(suffix), ""))
94
+ # add random digits to resolve ties
95
+ with data_utils.numpy_seed(epoch, updates, val_loss):
96
+ rand_sfx = np.random.randint(0, cfg.keep_best_checkpoints)
97
+
98
+ checkpoint_conds[
99
+ "checkpoint.best_{}_{:.3f}{}{}.pt".format(
100
+ cfg.best_checkpoint_metric,
101
+ val_loss,
102
+ rand_sfx,
103
+ suffix
104
+ )
105
+ ] = worst_best is None or is_better(val_loss, worst_best)
106
+ checkpoint_conds[
107
+ "checkpoint_last{}.pt".format(suffix)
108
+ ] = not cfg.no_last_checkpoints
109
+
110
+ extra_state = {"train_iterator": epoch_itr.state_dict(), "val_loss": val_loss}
111
+ if hasattr(save_checkpoint, "best"):
112
+ extra_state.update({"best": save_checkpoint.best})
113
+
114
+ checkpoints = [
115
+ os.path.join(cfg.save_dir, fn) for fn, cond in checkpoint_conds.items() if cond
116
+ ]
117
+ if len(checkpoints) > 0:
118
+ trainer.save_checkpoint(checkpoints[0], extra_state)
119
+ for cp in checkpoints[1:]:
120
+ if cfg.write_checkpoints_asynchronously:
121
+ # TODO[ioPath]: Need to implement a delayed asynchronous
122
+ # file copying/moving feature.
123
+ logger.warning(
124
+ f"ioPath is not copying {checkpoints[0]} to {cp} "
125
+ "since async write mode is on."
126
+ )
127
+ else:
128
+ assert PathManager.copy(
129
+ checkpoints[0], cp, overwrite=True
130
+ ), f"Failed to copy {checkpoints[0]} to {cp}"
131
+
132
+ write_timer.stop()
133
+ logger.info(
134
+ "Saved checkpoint {} (epoch {} @ {} updates, score {}) (writing took {} seconds)".format(
135
+ checkpoints[0], epoch, updates, val_loss, write_timer.sum
136
+ )
137
+ )
138
+
139
+ if not end_of_epoch and cfg.keep_interval_updates > 0:
140
+ # remove old checkpoints; checkpoints are sorted in descending order
141
+ if cfg.keep_interval_updates_pattern == -1:
142
+ checkpoints = checkpoint_paths(
143
+ cfg.save_dir, pattern=r"checkpoint_\d+_(\d+){}\.pt".format(suffix)
144
+ )
145
+ else:
146
+ checkpoints = checkpoint_paths(
147
+ cfg.save_dir,
148
+ pattern=r"checkpoint_\d+_(\d+){}\.pt".format(suffix),
149
+ keep_match=True,
150
+ )
151
+ checkpoints = [
152
+ x[0]
153
+ for x in checkpoints
154
+ if x[1] % cfg.keep_interval_updates_pattern != 0
155
+ ]
156
+
157
+ for old_chk in checkpoints[cfg.keep_interval_updates :]:
158
+ if os.path.lexists(old_chk):
159
+ os.remove(old_chk)
160
+ elif PathManager.exists(old_chk):
161
+ PathManager.rm(old_chk)
162
+
163
+ if cfg.keep_last_epochs > 0:
164
+ # remove old epoch checkpoints; checkpoints are sorted in descending order
165
+ checkpoints = checkpoint_paths(
166
+ cfg.save_dir, pattern=r"checkpoint(\d+){}\.pt".format(suffix)
167
+ )
168
+ for old_chk in checkpoints[cfg.keep_last_epochs :]:
169
+ if os.path.lexists(old_chk):
170
+ os.remove(old_chk)
171
+ elif PathManager.exists(old_chk):
172
+ PathManager.rm(old_chk)
173
+
174
+ if cfg.keep_best_checkpoints > 0:
175
+ # only keep the best N checkpoints according to validation metric
176
+ checkpoints = checkpoint_paths(
177
+ cfg.save_dir,
178
+ pattern=r"checkpoint\.best_{}_(\d+\.?\d*){}\.pt".format(
179
+ cfg.best_checkpoint_metric, suffix
180
+ ),
181
+ )
182
+ if not cfg.maximize_best_checkpoint_metric:
183
+ checkpoints = checkpoints[::-1]
184
+ for old_chk in checkpoints[cfg.keep_best_checkpoints :]:
185
+ if os.path.lexists(old_chk):
186
+ os.remove(old_chk)
187
+ elif PathManager.exists(old_chk):
188
+ PathManager.rm(old_chk)
189
+
190
+
191
+ def load_checkpoint(cfg: CheckpointConfig, trainer, **passthrough_args):
192
+ """
193
+ Load a checkpoint and restore the training iterator.
194
+
195
+ *passthrough_args* will be passed through to
196
+ ``trainer.get_train_iterator``.
197
+ """
198
+
199
+ reset_optimizer = cfg.reset_optimizer
200
+ reset_lr_scheduler = cfg.reset_lr_scheduler
201
+ optimizer_overrides = ast.literal_eval(cfg.optimizer_overrides)
202
+ reset_meters = cfg.reset_meters
203
+ reset_dataloader = cfg.reset_dataloader
204
+
205
+ if cfg.finetune_from_model is not None and (
206
+ reset_optimizer or reset_lr_scheduler or reset_meters or reset_dataloader
207
+ ):
208
+ raise ValueError(
209
+ "--finetune-from-model can not be set together with either --reset-optimizer"
210
+ " or reset_lr_scheduler or reset_meters or reset_dataloader"
211
+ )
212
+
213
+ suffix = trainer.checkpoint_suffix
214
+ if (
215
+ cfg.restore_file == "checkpoint_last.pt"
216
+ ): # default value of restore_file is 'checkpoint_last.pt'
217
+ checkpoint_path = os.path.join(
218
+ cfg.save_dir, "checkpoint_last{}.pt".format(suffix)
219
+ )
220
+ first_launch = not PathManager.exists(checkpoint_path)
221
+ if cfg.finetune_from_model is not None and first_launch:
222
+ # if there is no last checkpoint to restore, start the finetune from pretrained model
223
+ # else just use usual logic to load checkpoint, e.g. restart from last checkpoint and etc.
224
+ if PathManager.exists(cfg.finetune_from_model):
225
+ checkpoint_path = cfg.finetune_from_model
226
+ reset_optimizer = True
227
+ reset_lr_scheduler = True
228
+ reset_meters = True
229
+ reset_dataloader = True
230
+ logger.info(
231
+ f"loading pretrained model from {checkpoint_path}: "
232
+ "optimizer, lr scheduler, meters, dataloader will be reset"
233
+ )
234
+ else:
235
+ raise ValueError(
236
+ f"--funetune-from-model {cfg.finetune_from_model} does not exist"
237
+ )
238
+ elif suffix is not None:
239
+ checkpoint_path = cfg.restore_file.replace(".pt", suffix + ".pt")
240
+ else:
241
+ checkpoint_path = cfg.restore_file
242
+
243
+ if cfg.restore_file != "checkpoint_last.pt" and cfg.finetune_from_model:
244
+ raise ValueError(
245
+ "--finetune-from-model and --restore-file (non-default value) "
246
+ "can not be specified together: " + str(cfg)
247
+ )
248
+
249
+ extra_state = trainer.load_checkpoint(
250
+ checkpoint_path,
251
+ reset_optimizer,
252
+ reset_lr_scheduler,
253
+ optimizer_overrides,
254
+ reset_meters=reset_meters,
255
+ )
256
+
257
+ if (
258
+ extra_state is not None
259
+ and "best" in extra_state
260
+ and not reset_optimizer
261
+ and not reset_meters
262
+ ):
263
+ save_checkpoint.best = extra_state["best"]
264
+
265
+ if extra_state is not None and not reset_dataloader:
266
+ # restore iterator from checkpoint
267
+ itr_state = extra_state["train_iterator"]
268
+ epoch_itr = trainer.get_train_iterator(
269
+ epoch=itr_state["epoch"], load_dataset=True, **passthrough_args
270
+ )
271
+ epoch_itr.load_state_dict(itr_state)
272
+ _n = itr_state['iterations_in_epoch']
273
+ offset = sum(len(_) for _ in epoch_itr.batch_sampler[:_n])
274
+ epoch_itr.dataset.dataset._seek(offset=offset)
275
+ true_num = int(math.ceil(len(epoch_itr.dataset) / 8)) * 8
276
+ another_offset = ((epoch_itr.epoch - 1) * true_num + offset) // 8
277
+ if hasattr(epoch_itr.dataset, 'pure_text_dataset'):
278
+ text_offset = (2 * another_offset) % len(epoch_itr.dataset.pure_text_dataset)
279
+ epoch_itr.dataset.pure_text_dataset._seek(offset=text_offset)
280
+ if hasattr(epoch_itr.dataset, 'pure_image_dataset'):
281
+ image_offset = another_offset % len(epoch_itr.dataset.pure_image_dataset)
282
+ epoch_itr.dataset.pure_image_dataset._seek(offset=image_offset)
283
+ if hasattr(epoch_itr.dataset, 'detection_dataset'):
284
+ detection_offset = another_offset % len(epoch_itr.dataset.detection_dataset)
285
+ epoch_itr.dataset.detection_dataset._seek(offset=detection_offset)
286
+ else:
287
+ epoch_itr = trainer.get_train_iterator(
288
+ epoch=1, load_dataset=True, **passthrough_args
289
+ )
290
+
291
+ trainer.lr_step(epoch_itr.epoch)
292
+
293
+ return extra_state, epoch_itr
294
+
295
+
296
+ def load_checkpoint_to_cpu(path, arg_overrides=None, load_on_all_ranks=False):
297
+ """Loads a checkpoint to CPU (with upgrading for backward compatibility).
298
+
299
+ If doing single-GPU training or if the checkpoint is only being loaded by at
300
+ most one process on each node (current default behavior is for only rank 0
301
+ to read the checkpoint from disk), load_on_all_ranks should be False to
302
+ avoid errors from torch.distributed not having been initialized or
303
+ torch.distributed.barrier() hanging.
304
+
305
+ If all processes on each node may be loading the checkpoint
306
+ simultaneously, load_on_all_ranks should be set to True to avoid I/O
307
+ conflicts.
308
+
309
+ There's currently no support for > 1 but < all processes loading the
310
+ checkpoint on each node.
311
+ """
312
+ local_path = PathManager.get_local_path(path)
313
+ # The locally cached file returned by get_local_path() may be stale for
314
+ # remote files that are periodically updated/overwritten (ex:
315
+ # checkpoint_last.pt) - so we remove the local copy, sync across processes
316
+ # (if needed), and then download a fresh copy.
317
+ if local_path != path and PathManager.path_requires_pathmanager(path):
318
+ try:
319
+ os.remove(local_path)
320
+ except FileNotFoundError:
321
+ # With potentially multiple processes removing the same file, the
322
+ # file being missing is benign (missing_ok isn't available until
323
+ # Python 3.8).
324
+ pass
325
+ if load_on_all_ranks:
326
+ torch.distributed.barrier()
327
+ local_path = PathManager.get_local_path(path)
328
+
329
+ with open(local_path, "rb") as f:
330
+ state = torch.load(f, map_location=torch.device("cpu"))
331
+
332
+ if "args" in state and state["args"] is not None and arg_overrides is not None:
333
+ args = state["args"]
334
+ for arg_name, arg_val in arg_overrides.items():
335
+ setattr(args, arg_name, arg_val)
336
+
337
+ if "cfg" in state and state["cfg"] is not None:
338
+
339
+ # hack to be able to set Namespace in dict config. this should be removed when we update to newer
340
+ # omegaconf version that supports object flags, or when we migrate all existing models
341
+ from omegaconf import _utils
342
+
343
+ old_primitive = _utils.is_primitive_type
344
+ _utils.is_primitive_type = lambda _: True
345
+
346
+ state["cfg"] = OmegaConf.create(state["cfg"])
347
+
348
+ _utils.is_primitive_type = old_primitive
349
+ OmegaConf.set_struct(state["cfg"], True)
350
+
351
+ if arg_overrides is not None:
352
+ overwrite_args_by_name(state["cfg"], arg_overrides)
353
+
354
+ state = _upgrade_state_dict(state)
355
+ return state
356
+
357
+
358
+ def load_model_ensemble(
359
+ filenames,
360
+ arg_overrides: Optional[Dict[str, Any]] = None,
361
+ task=None,
362
+ strict=True,
363
+ suffix="",
364
+ num_shards=1,
365
+ state=None,
366
+ ):
367
+ """Loads an ensemble of models.
368
+
369
+ Args:
370
+ filenames (List[str]): checkpoint files to load
371
+ arg_overrides (Dict[str,Any], optional): override model args that
372
+ were used during model training
373
+ task (fairseq.tasks.FairseqTask, optional): task to use for loading
374
+ """
375
+ assert not (
376
+ strict and num_shards > 1
377
+ ), "Cannot load state dict with strict=True and checkpoint shards > 1"
378
+ ensemble, args, _task = load_model_ensemble_and_task(
379
+ filenames,
380
+ arg_overrides,
381
+ task,
382
+ strict,
383
+ suffix,
384
+ num_shards,
385
+ state,
386
+ )
387
+ return ensemble, args
388
+
389
+
390
+ def get_maybe_sharded_checkpoint_filename(
391
+ filename: str, suffix: str, shard_idx: int, num_shards: int
392
+ ) -> str:
393
+ orig_filename = filename
394
+ filename = filename.replace(".pt", suffix + ".pt")
395
+ fsdp_filename = filename[:-3] + f"-shard{shard_idx}.pt"
396
+ model_parallel_filename = orig_filename[:-3] + f"_part{shard_idx}.pt"
397
+ if PathManager.exists(fsdp_filename):
398
+ return fsdp_filename
399
+ elif num_shards > 1:
400
+ return model_parallel_filename
401
+ else:
402
+ return filename
403
+
404
+
405
+ def load_model_ensemble_and_task(
406
+ filenames,
407
+ arg_overrides: Optional[Dict[str, Any]] = None,
408
+ task=None,
409
+ strict=True,
410
+ suffix="",
411
+ num_shards=1,
412
+ state=None,
413
+ ):
414
+ assert state is None or len(filenames) == 1
415
+
416
+ from fairseq import tasks
417
+
418
+ assert not (
419
+ strict and num_shards > 1
420
+ ), "Cannot load state dict with strict=True and checkpoint shards > 1"
421
+ ensemble = []
422
+ cfg = None
423
+ for filename in filenames:
424
+ orig_filename = filename
425
+ model_shard_state = {"shard_weights": [], "shard_metadata": []}
426
+ assert num_shards > 0
427
+ st = time.time()
428
+ for shard_idx in range(num_shards):
429
+ filename = get_maybe_sharded_checkpoint_filename(
430
+ orig_filename, suffix, shard_idx, num_shards
431
+ )
432
+
433
+ if not PathManager.exists(filename):
434
+ raise IOError("Model file not found: {}".format(filename))
435
+ if state is None:
436
+ state = load_checkpoint_to_cpu(filename, arg_overrides)
437
+ if "args" in state and state["args"] is not None:
438
+ cfg = convert_namespace_to_omegaconf(state["args"])
439
+ elif "cfg" in state and state["cfg"] is not None:
440
+ cfg = state["cfg"]
441
+ else:
442
+ raise RuntimeError(
443
+ f"Neither args nor cfg exist in state keys = {state.keys()}"
444
+ )
445
+
446
+ if task is None:
447
+ task = tasks.setup_task(cfg.task)
448
+
449
+ if "task_state" in state:
450
+ task.load_state_dict(state["task_state"])
451
+
452
+ if "fsdp_metadata" in state and num_shards > 1:
453
+ model_shard_state["shard_weights"].append(state["model"])
454
+ model_shard_state["shard_metadata"].append(state["fsdp_metadata"])
455
+ # check FSDP import before the code goes too far
456
+ if not has_FSDP:
457
+ raise ImportError(
458
+ "Cannot find FullyShardedDataParallel. "
459
+ "Please install fairscale with: pip install fairscale"
460
+ )
461
+ if shard_idx == num_shards - 1:
462
+ consolidated_model_state = FSDP.consolidate_shard_weights(
463
+ shard_weights=model_shard_state["shard_weights"],
464
+ shard_metadata=model_shard_state["shard_metadata"],
465
+ )
466
+ model = task.build_model(cfg.model)
467
+ model.load_state_dict(
468
+ consolidated_model_state, strict=strict, model_cfg=cfg.model
469
+ )
470
+ else:
471
+ # model parallel checkpoint or unsharded checkpoint
472
+ model = task.build_model(cfg.model)
473
+ model.load_state_dict(
474
+ state["model"], strict=strict, model_cfg=cfg.model
475
+ )
476
+
477
+ # reset state so it gets loaded for the next model in ensemble
478
+ state = None
479
+ if shard_idx % 10 == 0 and shard_idx > 0:
480
+ elapsed = time.time() - st
481
+ logger.info(
482
+ f"Loaded {shard_idx} shards in {elapsed:.2f}s, {elapsed / (shard_idx+1):.2f}s/shard"
483
+ )
484
+
485
+ # build model for ensemble
486
+ ensemble.append(model)
487
+ return ensemble, cfg, task
488
+
489
+
490
+ def checkpoint_paths(path, pattern=r"checkpoint(\d+)\.pt", keep_match=False):
491
+ """Retrieves all checkpoints found in `path` directory.
492
+
493
+ Checkpoints are identified by matching filename to the specified pattern. If
494
+ the pattern contains groups, the result will be sorted by the first group in
495
+ descending order.
496
+ """
497
+ pt_regexp = re.compile(pattern)
498
+ files = PathManager.ls(path)
499
+
500
+ entries = []
501
+ for i, f in enumerate(files):
502
+ m = pt_regexp.fullmatch(f)
503
+ if m is not None:
504
+ idx = float(m.group(1)) if len(m.groups()) > 0 else i
505
+ entries.append((idx, m.group(0)))
506
+ if keep_match:
507
+ return [(os.path.join(path, x[1]), x[0]) for x in sorted(entries, reverse=True)]
508
+ else:
509
+ return [os.path.join(path, x[1]) for x in sorted(entries, reverse=True)]
510
+
511
+
512
+ def torch_persistent_save(obj, filename, async_write: bool = False):
513
+ if async_write:
514
+ with PathManager.opena(filename, "wb") as f:
515
+ _torch_persistent_save(obj, f)
516
+ else:
517
+ with PathManager.open(filename, "wb") as f:
518
+ _torch_persistent_save(obj, f)
519
+ # if PathManager.supports_rename(filename):
520
+ # # do atomic save
521
+ # with PathManager.open(filename + ".tmp", "wb") as f:
522
+ # _torch_persistent_save(obj, f)
523
+ # PathManager.rename(filename + ".tmp", filename)
524
+ # else:
525
+ # # fallback to non-atomic save
526
+ # with PathManager.open(filename, "wb") as f:
527
+ # _torch_persistent_save(obj, f)
528
+
529
+
530
+ def _torch_persistent_save(obj, f):
531
+ if isinstance(f, str):
532
+ with PathManager.open(f, "wb") as h:
533
+ torch_persistent_save(obj, h)
534
+ return
535
+ for i in range(3):
536
+ try:
537
+ return torch.save(obj, f)
538
+ except Exception:
539
+ if i == 2:
540
+ logger.error(traceback.format_exc())
541
+ raise
542
+
543
+
544
+ def _upgrade_state_dict(state):
545
+ """Helper for upgrading old model checkpoints."""
546
+
547
+ # add optimizer_history
548
+ if "optimizer_history" not in state:
549
+ state["optimizer_history"] = [
550
+ {"criterion_name": "CrossEntropyCriterion", "best_loss": state["best_loss"]}
551
+ ]
552
+ state["last_optimizer_state"] = state["optimizer"]
553
+ del state["optimizer"]
554
+ del state["best_loss"]
555
+ # move extra_state into sub-dictionary
556
+ if "epoch" in state and "extra_state" not in state:
557
+ state["extra_state"] = {
558
+ "epoch": state["epoch"],
559
+ "batch_offset": state["batch_offset"],
560
+ "val_loss": state["val_loss"],
561
+ }
562
+ del state["epoch"]
563
+ del state["batch_offset"]
564
+ del state["val_loss"]
565
+ # reduce optimizer history's memory usage (only keep the last state)
566
+ if "optimizer" in state["optimizer_history"][-1]:
567
+ state["last_optimizer_state"] = state["optimizer_history"][-1]["optimizer"]
568
+ for optim_hist in state["optimizer_history"]:
569
+ del optim_hist["optimizer"]
570
+ # record the optimizer class name
571
+ if "optimizer_name" not in state["optimizer_history"][-1]:
572
+ state["optimizer_history"][-1]["optimizer_name"] = "FairseqNAG"
573
+ # move best_loss into lr_scheduler_state
574
+ if "lr_scheduler_state" not in state["optimizer_history"][-1]:
575
+ state["optimizer_history"][-1]["lr_scheduler_state"] = {
576
+ "best": state["optimizer_history"][-1]["best_loss"]
577
+ }
578
+ del state["optimizer_history"][-1]["best_loss"]
579
+ # keep track of number of updates
580
+ if "num_updates" not in state["optimizer_history"][-1]:
581
+ state["optimizer_history"][-1]["num_updates"] = 0
582
+ # old model checkpoints may not have separate source/target positions
583
+ if (
584
+ "args" in state
585
+ and hasattr(state["args"], "max_positions")
586
+ and not hasattr(state["args"], "max_source_positions")
587
+ ):
588
+ state["args"].max_source_positions = state["args"].max_positions
589
+ state["args"].max_target_positions = state["args"].max_positions
590
+ # use stateful training data iterator
591
+ if "train_iterator" not in state["extra_state"]:
592
+ state["extra_state"]["train_iterator"] = {
593
+ "epoch": state["extra_state"]["epoch"],
594
+ "iterations_in_epoch": state["extra_state"].get("batch_offset", 0),
595
+ }
596
+
597
+ # backward compatibility, cfg updates
598
+ if "args" in state and state["args"] is not None:
599
+ # default to translation task
600
+ if not hasattr(state["args"], "task"):
601
+ state["args"].task = "translation"
602
+ # --raw-text and --lazy-load are deprecated
603
+ if getattr(state["args"], "raw_text", False):
604
+ state["args"].dataset_impl = "raw"
605
+ elif getattr(state["args"], "lazy_load", False):
606
+ state["args"].dataset_impl = "lazy"
607
+ # epochs start at 1
608
+ if state["extra_state"]["train_iterator"] is not None:
609
+ state["extra_state"]["train_iterator"]["epoch"] = max(
610
+ state["extra_state"]["train_iterator"].get("epoch", 1), 1
611
+ )
612
+ # --remove-bpe ==> --postprocess
613
+ if hasattr(state["args"], "remove_bpe"):
614
+ state["args"].post_process = state["args"].remove_bpe
615
+ # --min-lr ==> --stop-min-lr
616
+ if hasattr(state["args"], "min_lr"):
617
+ state["args"].stop_min_lr = state["args"].min_lr
618
+ del state["args"].min_lr
619
+ # binary_cross_entropy / kd_binary_cross_entropy => wav2vec criterion
620
+ if (
621
+ hasattr(state["args"], "criterion")
622
+ and state["args"].criterion in [
623
+ "binary_cross_entropy",
624
+ "kd_binary_cross_entropy",
625
+ ]
626
+ ):
627
+ state["args"].criterion = "wav2vec"
628
+ # remove log_keys if it's None (criteria will supply a default value of [])
629
+ if hasattr(state["args"], "log_keys") and state["args"].log_keys is None:
630
+ delattr(state["args"], "log_keys")
631
+ # speech_pretraining => audio pretraining
632
+ if (
633
+ hasattr(state["args"], "task")
634
+ and state["args"].task == "speech_pretraining"
635
+ ):
636
+ state["args"].task = "audio_pretraining"
637
+ # audio_cpc => wav2vec
638
+ if hasattr(state["args"], "arch") and state["args"].arch == "audio_cpc":
639
+ state["args"].arch = "wav2vec"
640
+ # convert legacy float learning rate to List[float]
641
+ if hasattr(state["args"], "lr") and isinstance(state["args"].lr, float):
642
+ state["args"].lr = [state["args"].lr]
643
+ # convert task data arg to a string instead of List[string]
644
+ if (
645
+ hasattr(state["args"], "data")
646
+ and isinstance(state["args"].data, list)
647
+ and len(state["args"].data) > 0
648
+ ):
649
+ state["args"].data = state["args"].data[0]
650
+ # remove keys in state["args"] related to teacher-student learning
651
+ for key in [
652
+ "static_teachers",
653
+ "static_teacher_weights",
654
+ "dynamic_teachers",
655
+ "dynamic_teacher_weights",
656
+ ]:
657
+ if key in state["args"]:
658
+ delattr(state["args"], key)
659
+
660
+ state["cfg"] = convert_namespace_to_omegaconf(state["args"])
661
+
662
+ if "cfg" in state and state["cfg"] is not None:
663
+ cfg = state["cfg"]
664
+ with open_dict(cfg):
665
+ # any upgrades for Hydra-based configs
666
+ if (
667
+ "task" in cfg
668
+ and "eval_wer_config" in cfg.task
669
+ and isinstance(cfg.task.eval_wer_config.print_alignment, bool)
670
+ ):
671
+ cfg.task.eval_wer_config.print_alignment = "hard"
672
+ if "generation" in cfg and isinstance(cfg.generation.print_alignment, bool):
673
+ cfg.generation.print_alignment = "hard" if cfg.generation.print_alignment else None
674
+ if (
675
+ "model" in cfg
676
+ and "w2v_args" in cfg.model
677
+ and cfg.model.w2v_args is not None
678
+ and (
679
+ hasattr(cfg.model.w2v_args, "task") or "task" in cfg.model.w2v_args
680
+ )
681
+ and hasattr(cfg.model.w2v_args.task, "eval_wer_config")
682
+ and cfg.model.w2v_args.task.eval_wer_config is not None
683
+ and isinstance(
684
+ cfg.model.w2v_args.task.eval_wer_config.print_alignment, bool
685
+ )
686
+ ):
687
+ cfg.model.w2v_args.task.eval_wer_config.print_alignment = "hard"
688
+
689
+ return state
690
+
691
+
692
+ def prune_state_dict(state_dict, model_cfg: Optional[DictConfig]):
693
+ """Prune the given state_dict if desired for LayerDrop
694
+ (https://arxiv.org/abs/1909.11556).
695
+
696
+ Training with LayerDrop allows models to be robust to pruning at inference
697
+ time. This function prunes state_dict to allow smaller models to be loaded
698
+ from a larger model and re-maps the existing state_dict for this to occur.
699
+
700
+ It's called by functions that load models from checkpoints and does not
701
+ need to be called directly.
702
+ """
703
+ arch = None
704
+ if model_cfg is not None:
705
+ arch = (
706
+ model_cfg._name
707
+ if isinstance(model_cfg, DictConfig)
708
+ else getattr(model_cfg, "arch", None)
709
+ )
710
+
711
+ if not model_cfg or arch is None or arch == "ptt_transformer":
712
+ # args should not be none, but don't crash if it is.
713
+ return state_dict
714
+
715
+ encoder_layers_to_keep = getattr(model_cfg, "encoder_layers_to_keep", None)
716
+ decoder_layers_to_keep = getattr(model_cfg, "decoder_layers_to_keep", None)
717
+
718
+ if not encoder_layers_to_keep and not decoder_layers_to_keep:
719
+ return state_dict
720
+
721
+ # apply pruning
722
+ logger.info(
723
+ "Pruning model to specified layer configuration - this works best if the model was trained with LayerDrop"
724
+ )
725
+
726
+ def create_pruning_pass(layers_to_keep, layer_name):
727
+ keep_layers = sorted(
728
+ int(layer_string) for layer_string in layers_to_keep.split(",")
729
+ )
730
+ mapping_dict = {}
731
+ for i in range(len(keep_layers)):
732
+ mapping_dict[str(keep_layers[i])] = str(i)
733
+
734
+ regex = re.compile(r"^{layer}.*\.layers\.(\d+)".format(layer=layer_name))
735
+ return {"substitution_regex": regex, "mapping_dict": mapping_dict}
736
+
737
+ pruning_passes = []
738
+ if encoder_layers_to_keep:
739
+ pruning_passes.append(create_pruning_pass(encoder_layers_to_keep, "encoder"))
740
+ if decoder_layers_to_keep:
741
+ pruning_passes.append(create_pruning_pass(decoder_layers_to_keep, "decoder"))
742
+
743
+ new_state_dict = {}
744
+ for layer_name in state_dict.keys():
745
+ match = re.search(r"\.layers\.(\d+)\.", layer_name)
746
+ # if layer has no number in it, it is a supporting layer, such as an
747
+ # embedding
748
+ if not match:
749
+ new_state_dict[layer_name] = state_dict[layer_name]
750
+ continue
751
+
752
+ # otherwise, layer should be pruned.
753
+ original_layer_number = match.group(1)
754
+ # figure out which mapping dict to replace from
755
+ for pruning_pass in pruning_passes:
756
+ if original_layer_number in pruning_pass["mapping_dict"] and pruning_pass[
757
+ "substitution_regex"
758
+ ].search(layer_name):
759
+ new_layer_number = pruning_pass["mapping_dict"][original_layer_number]
760
+ substitution_match = pruning_pass["substitution_regex"].search(
761
+ layer_name
762
+ )
763
+ new_state_key = (
764
+ layer_name[: substitution_match.start(1)]
765
+ + new_layer_number
766
+ + layer_name[substitution_match.end(1) :]
767
+ )
768
+ new_state_dict[new_state_key] = state_dict[layer_name]
769
+
770
+ # Since layers are now pruned, *_layers_to_keep are no longer needed.
771
+ # This is more of "It would make it work fix" rather than a proper fix.
772
+ if isinstance(model_cfg, DictConfig):
773
+ context = open_dict(model_cfg)
774
+ else:
775
+ context = contextlib.ExitStack()
776
+ with context:
777
+ if hasattr(model_cfg, "encoder_layers_to_keep"):
778
+ model_cfg.encoder_layers_to_keep = None
779
+ if hasattr(model_cfg, "decoder_layers_to_keep"):
780
+ model_cfg.decoder_layers_to_keep = None
781
+
782
+ return new_state_dict
783
+
784
+
785
+ def load_pretrained_component_from_model(
786
+ component: Union[FairseqEncoder, FairseqDecoder], checkpoint: str
787
+ ):
788
+ """
789
+ Load a pretrained FairseqEncoder or FairseqDecoder from checkpoint into the
790
+ provided `component` object. If state_dict fails to load, there may be a
791
+ mismatch in the architecture of the corresponding `component` found in the
792
+ `checkpoint` file.
793
+ """
794
+ if not PathManager.exists(checkpoint):
795
+ raise IOError("Model file not found: {}".format(checkpoint))
796
+ state = load_checkpoint_to_cpu(checkpoint)
797
+ if isinstance(component, FairseqEncoder):
798
+ component_type = "encoder"
799
+ elif isinstance(component, FairseqDecoder):
800
+ component_type = "decoder"
801
+ else:
802
+ raise ValueError(
803
+ "component to load must be either a FairseqEncoder or "
804
+ "FairseqDecoder. Loading other component types are not supported."
805
+ )
806
+ component_state_dict = OrderedDict()
807
+ for key in state["model"].keys():
808
+ if key.startswith(component_type):
809
+ # encoder.input_layers.0.0.weight --> input_layers.0.0.weight
810
+ component_subkey = key[len(component_type) + 1 :]
811
+ component_state_dict[component_subkey] = state["model"][key]
812
+ component.load_state_dict(component_state_dict, strict=True)
813
+ return component
814
+
815
+
816
+ def verify_checkpoint_directory(save_dir: str) -> None:
817
+ if not os.path.exists(save_dir):
818
+ os.makedirs(save_dir, exist_ok=True)
819
+ temp_file_path = os.path.join(save_dir, "dummy")
820
+ try:
821
+ with open(temp_file_path, "w"):
822
+ pass
823
+ except OSError as e:
824
+ logger.warning(
825
+ "Unable to access checkpoint save directory: {}".format(save_dir)
826
+ )
827
+ raise e
828
+ else:
829
+ os.remove(temp_file_path)
830
+
831
+
832
+ def load_ema_from_checkpoint(fpath):
833
+ """Loads exponential moving averaged (EMA) checkpoint from input and
834
+ returns a model with ema weights.
835
+
836
+ Args:
837
+ fpath: A string path of checkpoint to load from.
838
+
839
+ Returns:
840
+ A dict of string keys mapping to various values. The 'model' key
841
+ from the returned dict should correspond to an OrderedDict mapping
842
+ string parameter names to torch Tensors.
843
+ """
844
+ params_dict = collections.OrderedDict()
845
+ new_state = None
846
+
847
+ with PathManager.open(fpath, 'rb') as f:
848
+ new_state = torch.load(
849
+ f,
850
+ map_location=(
851
+ lambda s, _: torch.serialization.default_restore_location(s, 'cpu')
852
+ ),
853
+ )
854
+
855
+ # EMA model is stored in a separate "extra state"
856
+ model_params = new_state['extra_state']['ema']
857
+
858
+ for key in list(model_params.keys()):
859
+ p = model_params[key]
860
+ if isinstance(p, torch.HalfTensor):
861
+ p = p.float()
862
+ if key not in params_dict:
863
+ params_dict[key] = p.clone()
864
+ # NOTE: clone() is needed in case of p is a shared parameter
865
+ else:
866
+ raise ValueError("Key {} is repeated in EMA model params.".format(key))
867
+
868
+ if len(params_dict) == 0:
869
+ raise ValueError(
870
+ f"Input checkpoint path '{fpath}' does not contain "
871
+ "ema model weights, is this model trained with EMA?"
872
+ )
873
+
874
+ new_state['model'] = params_dict
875
+ return new_state
utils/cider/pyciderevalcap/__init__.py ADDED
@@ -0,0 +1 @@
 
1
+ __author__ = 'tylin'
utils/cider/pyciderevalcap/cider/__init__.py ADDED
@@ -0,0 +1 @@
 
1
+ __author__ = 'tylin'
utils/cider/pyciderevalcap/cider/cider.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Filename: cider.py
2
+ #
3
+ #
4
+ # Description: Describes the class to compute the CIDEr
5
+ # (Consensus-Based Image Description Evaluation) Metric
6
+ # by Vedantam, Zitnick, and Parikh (http://arxiv.org/abs/1411.5726)
7
+ #
8
+ # Creation Date: Sun Feb 8 14:16:54 2015
9
+ #
10
+ # Authors: Ramakrishna Vedantam <vrama91@vt.edu> and
11
+ # Tsung-Yi Lin <tl483@cornell.edu>
12
+ from __future__ import absolute_import
13
+ from __future__ import division
14
+ from __future__ import print_function
15
+
16
+ from .cider_scorer import CiderScorer
17
+
18
+
19
+ class Cider:
20
+ """
21
+ Main Class to compute the CIDEr metric
22
+
23
+ """
24
+ def __init__(self, n=4, df="corpus"):
25
+ """
26
+ Initialize the CIDEr scoring function
27
+ : param n (int): n-gram size
28
+ : param df (string): specifies where to get the IDF values from
29
+ takes values 'corpus', 'coco-train'
30
+ : return: None
31
+ """
32
+ # set cider to sum over 1 to 4-grams
33
+ self._n = n
34
+ self._df = df
35
+ self.cider_scorer = CiderScorer(n=self._n, df_mode=self._df)
36
+
37
+ def compute_score(self, gts, res):
38
+ """
39
+ Main function to compute CIDEr score
40
+ : param gts (dict) : {image:tokenized reference sentence}
41
+ : param res (dict) : {image:tokenized candidate sentence}
42
+ : return: cider (float) : computed CIDEr score for the corpus
43
+ """
44
+
45
+ # clear all the previous hypos and refs
46
+ self.cider_scorer.clear()
47
+
48
+ for res_id in res:
49
+
50
+ hypo = res_id['caption']
51
+ ref = gts[res_id['image_id']]
52
+
53
+ # Sanity check.
54
+ assert(type(hypo) is list)
55
+ assert(len(hypo) == 1)
56
+ assert(type(ref) is list)
57
+ assert(len(ref) > 0)
58
+ self.cider_scorer += (hypo[0], ref)
59
+
60
+ (score, scores) = self.cider_scorer.compute_score()
61
+
62
+ return score, scores
63
+
64
+ def method(self):
65
+ return "CIDEr"
utils/cider/pyciderevalcap/cider/cider_scorer.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # Tsung-Yi Lin <tl483@cornell.edu>
3
+ # Ramakrishna Vedantam <vrama91@vt.edu>
4
+ from __future__ import absolute_import
5
+ from __future__ import division
6
+ from __future__ import print_function
7
+
8
+ import copy
9
+ import six
10
+ from six.moves import cPickle
11
+ from collections import defaultdict
12
+ import numpy as np
13
+ import math
14
+ import os
15
+
16
+ def precook(s, n=4, out=False):
17
+ """
18
+ Takes a string as input and returns an object that can be given to
19
+ either cook_refs or cook_test. This is optional: cook_refs and cook_test
20
+ can take string arguments as well.
21
+ :param s: string : sentence to be converted into ngrams
22
+ :param n: int : number of ngrams for which representation is calculated
23
+ :return: term frequency vector for occuring ngrams
24
+ """
25
+ words = s.split()
26
+ counts = defaultdict(int)
27
+ for k in range(1,n+1):
28
+ for i in range(len(words)-k+1):
29
+ ngram = tuple(words[i:i+k])
30
+ counts[ngram] += 1
31
+ return counts
32
+
33
+ def cook_refs(refs, n=4): ## lhuang: oracle will call with "average"
34
+ '''Takes a list of reference sentences for a single segment
35
+ and returns an object that encapsulates everything that BLEU
36
+ needs to know about them.
37
+ :param refs: list of string : reference sentences for some image
38
+ :param n: int : number of ngrams for which (ngram) representation is calculated
39
+ :return: result (list of dict)
40
+ '''
41
+ return [precook(ref, n) for ref in refs]
42
+
43
+ def cook_test(test, n=4):
44
+ '''Takes a test sentence and returns an object that
45
+ encapsulates everything that BLEU needs to know about it.
46
+ :param test: list of string : hypothesis sentence for some image
47
+ :param n: int : number of ngrams for which (ngram) representation is calculated
48
+ :return: result (dict)
49
+ '''
50
+ return precook(test, n, True)
51
+
52
+ class CiderScorer(object):
53
+ """CIDEr scorer.
54
+ """
55
+
56
+ def copy(self):
57
+ ''' copy the refs.'''
58
+ new = CiderScorer(n=self.n)
59
+ new.ctest = copy.copy(self.ctest)
60
+ new.crefs = copy.copy(self.crefs)
61
+ return new
62
+
63
+ def __init__(self, df_mode="corpus", test=None, refs=None, n=4, sigma=6.0):
64
+ ''' singular instance '''
65
+ self.n = n
66
+ self.sigma = sigma
67
+ self.crefs = []
68
+ self.ctest = []
69
+ self.df_mode = df_mode
70
+ self.ref_len = None
71
+ if self.df_mode != "corpus":
72
+ pkl_file = cPickle.load(open(os.path.join('data', df_mode + '.p'),'rb'), **(dict(encoding='latin1') if six.PY3 else {}))
73
+ self.ref_len = np.log(float(pkl_file['ref_len']))
74
+ self.document_frequency = pkl_file['document_frequency']
75
+ self.cook_append(test, refs)
76
+
77
+ def clear(self):
78
+ self.crefs = []
79
+ self.ctest = []
80
+
81
+ def cook_append(self, test, refs):
82
+ '''called by constructor and __iadd__ to avoid creating new instances.'''
83
+
84
+ if refs is not None:
85
+ self.crefs.append(cook_refs(refs))
86
+ if test is not None:
87
+ self.ctest.append(cook_test(test)) ## N.B.: -1
88
+ else:
89
+ self.ctest.append(None) # lens of crefs and ctest have to match
90
+
91
+ def size(self):
92
+ assert len(self.crefs) == len(self.ctest), "refs/test mismatch! %d<>%d" % (len(self.crefs), len(self.ctest))
93
+ return len(self.crefs)
94
+
95
+ def __iadd__(self, other):
96
+ '''add an instance (e.g., from another sentence).'''
97
+
98
+ if type(other) is tuple:
99
+ ## avoid creating new CiderScorer instances
100
+ self.cook_append(other[0], other[1])
101
+ else:
102
+ self.ctest.extend(other.ctest)
103
+ self.crefs.extend(other.crefs)
104
+
105
+ return self
106
+ def compute_doc_freq(self):
107
+ '''
108
+ Compute term frequency for reference data.
109
+ This will be used to compute idf (inverse document frequency later)
110
+ The term frequency is stored in the object
111
+ :return: None
112
+ '''
113
+ for refs in self.crefs:
114
+ # refs, k ref captions of one image
115
+ for ngram in set([ngram for ref in refs for (ngram,count) in ref.items()]):
116
+ self.document_frequency[ngram] += 1
117
+ # maxcounts[ngram] = max(maxcounts.get(ngram,0), count)
118
+
119
+ def compute_cider(self):
120
+ def counts2vec(cnts):
121
+ """
122
+ Function maps counts of ngram to vector of tfidf weights.
123
+ The function returns vec, an array of dictionary that store mapping of n-gram and tf-idf weights.
124
+ The n-th entry of array denotes length of n-grams.
125
+ :param cnts:
126
+ :return: vec (array of dict), norm (array of float), length (int)
127
+ """
128
+ vec = [defaultdict(float) for _ in range(self.n)]
129
+ length = 0
130
+ norm = [0.0 for _ in range(self.n)]
131
+ for (ngram,term_freq) in cnts.items():
132
+ # give word count 1 if it doesn't appear in reference corpus
133
+ df = np.log(max(1.0, self.document_frequency[ngram]))
134
+ # ngram index
135
+ n = len(ngram)-1
136
+ # tf (term_freq) * idf (precomputed idf) for n-grams
137
+ vec[n][ngram] = float(term_freq)*(self.ref_len - df)
138
+ # compute norm for the vector. the norm will be used for
139
+ # computing similarity
140
+ norm[n] += pow(vec[n][ngram], 2)
141
+
142
+ if n == 1:
143
+ length += term_freq
144
+ norm = [np.sqrt(n) for n in norm]
145
+ return vec, norm, length
146
+
147
+ def sim(vec_hyp, vec_ref, norm_hyp, norm_ref, length_hyp, length_ref):
148
+ '''
149
+ Compute the cosine similarity of two vectors.
150
+ :param vec_hyp: array of dictionary for vector corresponding to hypothesis
151
+ :param vec_ref: array of dictionary for vector corresponding to reference
152
+ :param norm_hyp: array of float for vector corresponding to hypothesis
153
+ :param norm_ref: array of float for vector corresponding to reference
154
+ :param length_hyp: int containing length of hypothesis
155
+ :param length_ref: int containing length of reference
156
+ :return: array of score for each n-grams cosine similarity
157
+ '''
158
+ delta = float(length_hyp - length_ref)
159
+ # measure consine similarity
160
+ val = np.array([0.0 for _ in range(self.n)])
161
+ for n in range(self.n):
162
+ # ngram
163
+ for (ngram,count) in vec_hyp[n].items():
164
+ val[n] += vec_hyp[n][ngram] * vec_ref[n][ngram]
165
+
166
+ if (norm_hyp[n] != 0) and (norm_ref[n] != 0):
167
+ val[n] /= (norm_hyp[n]*norm_ref[n])
168
+
169
+ assert(not math.isnan(val[n]))
170
+ return val
171
+
172
+ # compute log reference length
173
+ if self.df_mode == "corpus":
174
+ self.ref_len = np.log(float(len(self.crefs)))
175
+
176
+ scores = []
177
+ for test, refs in zip(self.ctest, self.crefs):
178
+ # compute vector for test captions
179
+ vec, norm, length = counts2vec(test)
180
+ # compute vector for ref captions
181
+ score = np.array([0.0 for _ in range(self.n)])
182
+ for ref in refs:
183
+ vec_ref, norm_ref, length_ref = counts2vec(ref)
184
+ score += sim(vec, vec_ref, norm, norm_ref, length, length_ref)
185
+ # change by vrama91 - mean of ngram scores, instead of sum
186
+ score_avg = np.mean(score)
187
+ # divide by number of references
188
+ score_avg /= len(refs)
189
+ # multiply score by 10
190
+ score_avg *= 10.0
191
+ # append score of an image to the score list
192
+ scores.append(score_avg)
193
+ return scores
194
+
195
+ def compute_score(self, option=None, verbose=0):
196
+ # compute idf
197
+ if self.df_mode == "corpus":
198
+ self.document_frequency = defaultdict(float)
199
+ self.compute_doc_freq()
200
+ # assert to check document frequency
201
+ assert(len(self.ctest) >= max(self.document_frequency.values()))
202
+ # import json for now and write the corresponding files
203
+ # compute cider score
204
+ score = self.compute_cider()
205
+ # debug
206
+ # print score
207
+ return np.mean(np.array(score)), np.array(score)
utils/cider/pyciderevalcap/ciderD/__init__.py ADDED
@@ -0,0 +1 @@
 
1
+ __author__ = 'tylin'
utils/cider/pyciderevalcap/ciderD/ciderD.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Filename: ciderD.py
2
+ #
3
+ # Description: Describes the class to compute the CIDEr-D (Consensus-Based Image Description Evaluation) Metric
4
+ # by Vedantam, Zitnick, and Parikh (http://arxiv.org/abs/1411.5726)
5
+ #
6
+ # Creation Date: Sun Feb 8 14:16:54 2015
7
+ #
8
+ # Authors: Ramakrishna Vedantam <vrama91@vt.edu> and Tsung-Yi Lin <tl483@cornell.edu>
9
+ from __future__ import absolute_import
10
+ from __future__ import division
11
+ from __future__ import print_function
12
+
13
+ from .ciderD_scorer import CiderScorer
14
+ import pdb
15
+
16
+ class CiderD:
17
+ """
18
+ Main Class to compute the CIDEr metric
19
+
20
+ """
21
+ def __init__(self, n=4, sigma=6.0, df="corpus"):
22
+ # set cider to sum over 1 to 4-grams
23
+ self._n = n
24
+ # set the standard deviation parameter for gaussian penalty
25
+ self._sigma = sigma
26
+ # set which where to compute document frequencies from
27
+ self._df = df
28
+ self.cider_scorer = CiderScorer(n=self._n, df_mode=self._df)
29
+
30
+ def compute_score(self, gts, res):
31
+ """
32
+ Main function to compute CIDEr score
33
+ :param hypo_for_image (dict) : dictionary with key <image> and value <tokenized hypothesis / candidate sentence>
34
+ ref_for_image (dict) : dictionary with key <image> and value <tokenized reference sentence>
35
+ :return: cider (float) : computed CIDEr score for the corpus
36
+ """
37
+
38
+ # clear all the previous hypos and refs
39
+ tmp_cider_scorer = self.cider_scorer.copy_empty()
40
+ tmp_cider_scorer.clear()
41
+ for res_id in res:
42
+
43
+ hypo = res_id['caption']
44
+ ref = gts[res_id['image_id']]
45
+
46
+ # Sanity check.
47
+ assert(type(hypo) is list)
48
+ assert(len(hypo) == 1)
49
+ assert(type(ref) is list)
50
+ assert(len(ref) > 0)
51
+ tmp_cider_scorer += (hypo[0], ref)
52
+
53
+ (score, scores) = tmp_cider_scorer.compute_score()
54
+
55
+ return score, scores
56
+
57
+ def method(self):
58
+ return "CIDEr-D"
utils/cider/pyciderevalcap/ciderD/ciderD_scorer.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # Tsung-Yi Lin <tl483@cornell.edu>
3
+ # Ramakrishna Vedantam <vrama91@vt.edu>
4
+ from __future__ import absolute_import
5
+ from __future__ import division
6
+ from __future__ import print_function
7
+
8
+ import copy
9
+ from collections import defaultdict
10
+ import numpy as np
11
+ import pdb
12
+ import math
13
+ import six
14
+ from six.moves import cPickle
15
+ import os
16
+
17
+ def precook(s, n=4, out=False):
18
+ """
19
+ Takes a string as input and returns an object that can be given to
20
+ either cook_refs or cook_test. This is optional: cook_refs and cook_test
21
+ can take string arguments as well.
22
+ :param s: string : sentence to be converted into ngrams
23
+ :param n: int : number of ngrams for which representation is calculated
24
+ :return: term frequency vector for occuring ngrams
25
+ """
26
+ words = s.split()
27
+ counts = defaultdict(int)
28
+ for k in range(1,n+1):
29
+ for i in range(len(words)-k+1):
30
+ ngram = tuple(words[i:i+k])
31
+ counts[ngram] += 1
32
+ return counts
33
+
34
+ def cook_refs(refs, n=4): ## lhuang: oracle will call with "average"
35
+ '''Takes a list of reference sentences for a single segment
36
+ and returns an object that encapsulates everything that BLEU
37
+ needs to know about them.
38
+ :param refs: list of string : reference sentences for some image
39
+ :param n: int : number of ngrams for which (ngram) representation is calculated
40
+ :return: result (list of dict)
41
+ '''
42
+ return [precook(ref, n) for ref in refs]
43
+
44
+ def cook_test(test, n=4):
45
+ '''Takes a test sentence and returns an object that
46
+ encapsulates everything that BLEU needs to know about it.
47
+ :param test: list of string : hypothesis sentence for some image
48
+ :param n: int : number of ngrams for which (ngram) representation is calculated
49
+ :return: result (dict)
50
+ '''
51
+ return precook(test, n, True)
52
+
53
+ class CiderScorer(object):
54
+ """CIDEr scorer.
55
+ """
56
+
57
+ def copy(self):
58
+ ''' copy the refs.'''
59
+ new = CiderScorer(n=self.n)
60
+ new.ctest = copy.copy(self.ctest)
61
+ new.crefs = copy.copy(self.crefs)
62
+ return new
63
+
64
+ def copy_empty(self):
65
+ new = CiderScorer(df_mode="corpus", n=self.n, sigma=self.sigma)
66
+ new.df_mode = self.df_mode
67
+ new.ref_len = self.ref_len
68
+ new.document_frequency = self.document_frequency
69
+ return new
70
+
71
+ def __init__(self, df_mode="corpus", test=None, refs=None, n=4, sigma=6.0):
72
+ ''' singular instance '''
73
+ self.n = n
74
+ self.sigma = sigma
75
+ self.crefs = []
76
+ self.ctest = []
77
+ self.df_mode = df_mode
78
+ self.ref_len = None
79
+ if self.df_mode != "corpus":
80
+ pkl_file = cPickle.load(open(df_mode,'rb'), **(dict(encoding='latin1') if six.PY3 else {}))
81
+ self.ref_len = np.log(float(pkl_file['ref_len']))
82
+ self.document_frequency = pkl_file['document_frequency']
83
+ else:
84
+ self.document_frequency = None
85
+ self.cook_append(test, refs)
86
+
87
+ def clear(self):
88
+ self.crefs = []
89
+ self.ctest = []
90
+
91
+ def cook_append(self, test, refs):
92
+ '''called by constructor and __iadd__ to avoid creating new instances.'''
93
+
94
+ if refs is not None:
95
+ self.crefs.append(cook_refs(refs))
96
+ if test is not None:
97
+ self.ctest.append(cook_test(test)) ## N.B.: -1
98
+ else:
99
+ self.ctest.append(None) # lens of crefs and ctest have to match
100
+
101
+ def size(self):
102
+ assert len(self.crefs) == len(self.ctest), "refs/test mismatch! %d<>%d" % (len(self.crefs), len(self.ctest))
103
+ return len(self.crefs)
104
+
105
+ def __iadd__(self, other):
106
+ '''add an instance (e.g., from another sentence).'''
107
+
108
+ if type(other) is tuple:
109
+ ## avoid creating new CiderScorer instances
110
+ self.cook_append(other[0], other[1])
111
+ else:
112
+ self.ctest.extend(other.ctest)
113
+ self.crefs.extend(other.crefs)
114
+
115
+ return self
116
+ def compute_doc_freq(self):
117
+ '''
118
+ Compute term frequency for reference data.
119
+ This will be used to compute idf (inverse document frequency later)
120
+ The term frequency is stored in the object
121
+ :return: None
122
+ '''
123
+ for refs in self.crefs:
124
+ # refs, k ref captions of one image
125
+ for ngram in set([ngram for ref in refs for (ngram,count) in ref.items()]):
126
+ self.document_frequency[ngram] += 1
127
+ # maxcounts[ngram] = max(maxcounts.get(ngram,0), count)
128
+
129
+ def compute_cider(self):
130
+ def counts2vec(cnts):
131
+ """
132
+ Function maps counts of ngram to vector of tfidf weights.
133
+ The function returns vec, an array of dictionary that store mapping of n-gram and tf-idf weights.
134
+ The n-th entry of array denotes length of n-grams.
135
+ :param cnts:
136
+ :return: vec (array of dict), norm (array of float), length (int)
137
+ """
138
+ vec = [defaultdict(float) for _ in range(self.n)]
139
+ length = 0
140
+ norm = [0.0 for _ in range(self.n)]
141
+ for (ngram,term_freq) in cnts.items():
142
+ # give word count 1 if it doesn't appear in reference corpus
143
+ df = np.log(max(1.0, self.document_frequency[ngram]))
144
+ # ngram index
145
+ n = len(ngram)-1
146
+ # tf (term_freq) * idf (precomputed idf) for n-grams
147
+ vec[n][ngram] = float(term_freq)*(self.ref_len - df)
148
+ # compute norm for the vector. the norm will be used for computing similarity
149
+ norm[n] += pow(vec[n][ngram], 2)
150
+
151
+ if n == 1:
152
+ length += term_freq
153
+ norm = [np.sqrt(n) for n in norm]
154
+ return vec, norm, length
155
+
156
+ def sim(vec_hyp, vec_ref, norm_hyp, norm_ref, length_hyp, length_ref):
157
+ '''
158
+ Compute the cosine similarity of two vectors.
159
+ :param vec_hyp: array of dictionary for vector corresponding to hypothesis
160
+ :param vec_ref: array of dictionary for vector corresponding to reference
161
+ :param norm_hyp: array of float for vector corresponding to hypothesis
162
+ :param norm_ref: array of float for vector corresponding to reference
163
+ :param length_hyp: int containing length of hypothesis
164
+ :param length_ref: int containing length of reference
165
+ :return: array of score for each n-grams cosine similarity
166
+ '''
167
+ delta = float(length_hyp - length_ref)
168
+ # measure consine similarity
169
+ val = np.array([0.0 for _ in range(self.n)])
170
+ for n in range(self.n):
171
+ # ngram
172
+ for (ngram,count) in vec_hyp[n].items():
173
+ # vrama91 : added clipping
174
+ val[n] += min(vec_hyp[n][ngram], vec_ref[n][ngram]) * vec_ref[n][ngram]
175
+
176
+ if (norm_hyp[n] != 0) and (norm_ref[n] != 0):
177
+ val[n] /= (norm_hyp[n]*norm_ref[n])
178
+
179
+ assert(not math.isnan(val[n]))
180
+ # vrama91: added a length based gaussian penalty
181
+ val[n] *= np.e**(-(delta**2)/(2*self.sigma**2))
182
+ return val
183
+
184
+ # compute log reference length
185
+ if self.df_mode == "corpus":
186
+ self.ref_len = np.log(float(len(self.crefs)))
187
+ #elif self.df_mode == "coco-val-df":
188
+ # if coco option selected, use length of coco-val set
189
+ # self.ref_len = np.log(float(40504))
190
+
191
+ scores = []
192
+ for test, refs in zip(self.ctest, self.crefs):
193
+ # compute vector for test captions
194
+ vec, norm, length = counts2vec(test)
195
+ # compute vector for ref captions
196
+ score = np.array([0.0 for _ in range(self.n)])
197
+ for ref in refs:
198
+ vec_ref, norm_ref, length_ref = counts2vec(ref)
199
+ score += sim(vec, vec_ref, norm, norm_ref, length, length_ref)
200
+ # change by vrama91 - mean of ngram scores, instead of sum
201
+ score_avg = np.mean(score)
202
+ # divide by number of references
203
+ score_avg /= len(refs)
204
+ # multiply score by 10
205
+ score_avg *= 10.0
206
+ # append score of an image to the score list
207
+ scores.append(score_avg)
208
+ return scores
209
+
210
+ def compute_score(self, option=None, verbose=0):
211
+ # compute idf
212
+ if self.df_mode == "corpus":
213
+ self.document_frequency = defaultdict(float)
214
+ self.compute_doc_freq()
215
+ # assert to check document frequency
216
+ assert(len(self.ctest) >= max(self.document_frequency.values()))
217
+ # import json for now and write the corresponding files
218
+ # compute cider score
219
+ score = self.compute_cider()
220
+ # debug
221
+ # print score
222
+ return np.mean(np.array(score)), np.array(score)
utils/eval_utils.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The OFA-Sys Team.
2
+ # All rights reserved.
3
+ # This source code is licensed under the Apache 2.0 license
4
+ # found in the LICENSE file in the root directory.
5
+
6
+ import string
7
+ import math
8
+ import json
9
+ from itertools import chain
10
+ import os
11
+
12
+ import torch
13
+ import torch.distributed as dist
14
+
15
+ from data import data_utils
16
+ from tasks.nlg_tasks.gigaword import fix_tokenization
17
+
18
+
19
+ def get_symbols_to_strip_from_output(generator):
20
+ if hasattr(generator, "symbols_to_strip_from_output"):
21
+ return generator.symbols_to_strip_from_output
22
+ else:
23
+ return {generator.bos, generator.eos}
24
+
25
+
26
+ def decode_fn(x, tgt_dict, bpe, generator, tokenizer=None):
27
+ x = tgt_dict.string(x.int().cpu(), extra_symbols_to_ignore=get_symbols_to_strip_from_output(generator))
28
+ if bpe is not None:
29
+ x = bpe.decode(x)
30
+ if tokenizer is not None:
31
+ x = tokenizer.decode(x)
32
+ return x
33
+
34
+
35
+ def eval_caption(task, generator, models, sample, **kwargs):
36
+ transtab = str.maketrans({key: None for key in string.punctuation})
37
+ hypos = task.inference_step(generator, models, sample)
38
+ results = []
39
+ for i, sample_id in enumerate(sample["id"].tolist()):
40
+ detok_hypo_str = decode_fn(hypos[i][0]["tokens"], task.tgt_dict, task.bpe, generator)
41
+ results.append({"image_id": str(sample_id), "caption": detok_hypo_str.translate(transtab).strip()})
42
+ return results, None
43
+
44
+
45
+ def eval_vqa_gen(task, generator, models, sample, **kwargs):
46
+ if kwargs['beam_search_vqa_eval']:
47
+ hypos = task.inference_step(generator, models, sample, prefix_tokens=sample['prefix_tokens'])
48
+ results = []
49
+ for i, sample_id in enumerate(sample["id"].tolist()):
50
+ prefix_len = sample['prefix_tokens'][i].ne(1).sum().item()
51
+ detok_hypo_str = decode_fn(hypos[i][0]["tokens"][prefix_len:], task.tgt_dict, task.bpe, generator)
52
+ results.append({"question_id": int(sample_id), "answer": detok_hypo_str.strip()})
53
+ scores = [ref_dict.get(result['answer'], 0) for ref_dict, result in zip(sample['ref_dict'], results)]
54
+ return results, scores
55
+
56
+ encoder_out = models[0].encoder(
57
+ sample["net_input"]["src_tokens"],
58
+ src_lengths=sample["net_input"]["src_lengths"],
59
+ patch_images=sample["net_input"]["patch_images"],
60
+ patch_masks=sample["net_input"]["patch_masks"]
61
+ )
62
+ device = sample["net_input"]["src_tokens"].device
63
+ eos_item = torch.tensor([task.src_dict.eos()])
64
+ pad = task.src_dict.pad()
65
+ valid_result = []
66
+ for valid_answers, valid_constraint_masks in zip(task.valid_answers_list, task.valid_constraint_masks_list):
67
+ valid_size = len(valid_answers)
68
+ valid_tgt_items = [
69
+ torch.cat([torch.tensor(decoder_prompt[1:]), valid_answer, eos_item])
70
+ for decoder_prompt in sample["decoder_prompts"] for valid_answer in valid_answers
71
+ ]
72
+ valid_prev_items = [
73
+ torch.cat([torch.tensor(decoder_prompt), valid_answer])
74
+ for decoder_prompt in sample["decoder_prompts"] for valid_answer in valid_answers
75
+ ]
76
+ valid_constraint_mask_items = [
77
+ torch.cat(
78
+ [torch.zeros(len(decoder_prompt) - 1, valid_constraint_mask.size(1)).bool(), valid_constraint_mask],
79
+ dim=0
80
+ )
81
+ for decoder_prompt in sample["decoder_prompts"] for valid_constraint_mask in valid_constraint_masks
82
+ ]
83
+ valid_tgt = data_utils.collate_tokens(valid_tgt_items, pad_idx=pad).to(device)
84
+ valid_prev_output = data_utils.collate_tokens(valid_prev_items, pad_idx=pad).to(device)
85
+ valid_constraint_masks = data_utils.collate_tokens(valid_constraint_mask_items, pad_idx=pad).to(device)
86
+
87
+ new_encoder_out = {}
88
+ new_encoder_out["encoder_out"] = [
89
+ encoder_out["encoder_out"][0].repeat_interleave(valid_size, dim=1)
90
+ ]
91
+ new_encoder_out["encoder_padding_mask"] = [
92
+ encoder_out["encoder_padding_mask"][0].repeat_interleave(valid_size, dim=0)
93
+ ]
94
+ new_encoder_out["position_embeddings"] = [
95
+ encoder_out["position_embeddings"][0].repeat_interleave(valid_size, dim=0)
96
+ ]
97
+
98
+ decoder_out = models[0].decoder(valid_prev_output, encoder_out=new_encoder_out)
99
+ decoder_out[0].masked_fill_(~valid_constraint_masks, -math.inf)
100
+ lprobs = models[0].get_normalized_probs(decoder_out, log_probs=True)
101
+ scores = lprobs.gather(dim=-1, index=valid_tgt.unsqueeze(-1)).squeeze(-1)
102
+ scores = scores.masked_fill(valid_tgt.eq(task.tgt_dict.pad()), 0)
103
+ scores = scores.masked_fill((~valid_constraint_masks).all(2), 0)
104
+ scores = scores.sum(1)
105
+ scores = scores.view(-1, valid_size)
106
+ valid_result.append(scores)
107
+ valid_result = torch.cat(valid_result, dim=-1)
108
+ predicts = valid_result.argmax(1).tolist()
109
+ hyps = [task.index2ans[predict_index] for predict_index in predicts]
110
+ results = [{"question_id": int(id), "answer": hyp} for id, hyp in zip(sample["id"].tolist(), hyps)]
111
+ scores = [ref_dict.get(hyp, 0) for ref_dict, hyp in zip(sample['ref_dict'], hyps)]
112
+ return results, scores
113
+
114
+
115
+ def eval_refcoco(task, generator, models, sample, **kwargs):
116
+ def _calculate_ap_score(hyps, refs, thresh=0.5):
117
+ interacts = torch.cat(
118
+ [torch.where(hyps[:, :2] < refs[:, :2], refs[:, :2], hyps[:, :2]),
119
+ torch.where(hyps[:, 2:] < refs[:, 2:], hyps[:, 2:], refs[:, 2:])],
120
+ dim=1
121
+ )
122
+ area_predictions = (hyps[:, 2] - hyps[:, 0]) * (hyps[:, 3] - hyps[:, 1])
123
+ area_targets = (refs[:, 2] - refs[:, 0]) * (refs[:, 3] - refs[:, 1])
124
+ interacts_w = interacts[:, 2] - interacts[:, 0]
125
+ interacts_h = interacts[:, 3] - interacts[:, 1]
126
+ area_interacts = interacts_w * interacts_h
127
+ ious = area_interacts / (area_predictions + area_targets - area_interacts + 1e-6)
128
+ return ((ious >= thresh) & (interacts_w > 0) & (interacts_h > 0)).float()
129
+
130
+ gen_out = task.inference_step(generator, models, sample)
131
+ hyps = []
132
+ for i in range(len(gen_out)):
133
+ hyps.append(gen_out[i][0]["tokens"][:-1] - len(task.src_dict) + task.cfg.num_bins)
134
+ hyps = torch.stack(hyps, dim=0)
135
+ hyps = hyps / (task.cfg.num_bins - 1) * task.cfg.max_image_size
136
+ hyps[:, ::2] /= sample['w_resize_ratios'].unsqueeze(1)
137
+ hyps[:, 1::2] /= sample['h_resize_ratios'].unsqueeze(1)
138
+
139
+ results = [
140
+ {"uniq_id": sample_id,
141
+ "box": [hyps[i][0].item(), hyps[i][1].item(), hyps[i][2].item(), hyps[i][3].item()]}
142
+ for i, sample_id in enumerate(sample["id"].tolist())
143
+ ]
144
+ scores = _calculate_ap_score(hyps, sample['region_coords'].float())
145
+ return results, scores
146
+
147
+
148
+ def eval_snli_ve(task, generator, models, sample, **kwargs):
149
+ encoder_out = models[0].encoder(
150
+ sample["net_input"]["src_tokens"],
151
+ src_lengths=sample["net_input"]["src_lengths"],
152
+ patch_images=sample["net_input"]["patch_images"],
153
+ patch_masks=sample["net_input"]["patch_masks"]
154
+ )
155
+ device = sample["net_input"]["src_tokens"].device
156
+ eos_item = torch.tensor([task.src_dict.eos()])
157
+ pad = task.src_dict.pad()
158
+ valid_result = []
159
+ for valid_answers, valid_constraint_masks in zip(task.valid_answers_list, task.valid_constraint_masks_list):
160
+ valid_size = len(valid_answers)
161
+ valid_tgt_items = [
162
+ torch.cat([torch.tensor(decoder_prompt[1:]), valid_answer, eos_item])
163
+ for decoder_prompt in sample["decoder_prompts"] for valid_answer in valid_answers
164
+ ]
165
+ valid_prev_items = [
166
+ torch.cat([torch.tensor(decoder_prompt), valid_answer])
167
+ for decoder_prompt in sample["decoder_prompts"] for valid_answer in valid_answers
168
+ ]
169
+ valid_constraint_mask_items = [
170
+ torch.cat(
171
+ [torch.zeros(len(decoder_prompt) - 1, valid_constraint_mask.size(1)).bool(), valid_constraint_mask],
172
+ dim=0
173
+ )
174
+ for decoder_prompt in sample["decoder_prompts"] for valid_constraint_mask in valid_constraint_masks
175
+ ]
176
+ valid_tgt = data_utils.collate_tokens(valid_tgt_items, pad_idx=pad).to(device)
177
+ valid_prev_output = data_utils.collate_tokens(valid_prev_items, pad_idx=pad).to(device)
178
+ valid_constraint_masks = data_utils.collate_tokens(valid_constraint_mask_items, pad_idx=pad).to(device)
179
+
180
+ new_encoder_out = {}
181
+ new_encoder_out["encoder_out"] = [
182
+ encoder_out["encoder_out"][0].repeat_interleave(valid_size, dim=1)
183
+ ]
184
+ new_encoder_out["encoder_padding_mask"] = [
185
+ encoder_out["encoder_padding_mask"][0].repeat_interleave(valid_size, dim=0)
186
+ ]
187
+ new_encoder_out["position_embeddings"] = [
188
+ encoder_out["position_embeddings"][0].repeat_interleave(valid_size, dim=0)
189
+ ]
190
+
191
+ decoder_out = models[0].decoder(valid_prev_output, encoder_out=new_encoder_out)
192
+ decoder_out[0].masked_fill_(~valid_constraint_masks, -math.inf)
193
+ lprobs = models[0].get_normalized_probs(decoder_out, log_probs=True)
194
+ scores = lprobs.gather(dim=-1, index=valid_tgt.unsqueeze(-1)).squeeze(-1)
195
+ scores = scores.masked_fill(valid_tgt.eq(task.tgt_dict.pad()), 0)
196
+ scores = scores.masked_fill((~valid_constraint_masks).all(2), 0)
197
+ scores = scores.sum(1)
198
+ scores = scores.view(-1, valid_size)
199
+ valid_result.append(scores)
200
+ valid_result = torch.cat(valid_result, dim=-1)
201
+ predicts = valid_result.argmax(1).tolist()
202
+ hyps = [task.index2ans[predict_index] for predict_index in predicts]
203
+ results = [{"uniq_id": id, "answer": hyp} for id, hyp in zip(sample["id"].tolist(), hyps)]
204
+ scores = [ref_dict.get(hyp, 0) for ref_dict, hyp in zip(sample['ref_dict'], hyps)]
205
+ return results, scores
206
+
207
+
208
+ def eval_image_gen(task, generator, models, sample, **kwargs):
209
+ hypos, _ = task.inference_image(generator, sample, models)
210
+ tokens = sample['net_input']['src_tokens'][0].view(-1).tolist()
211
+ caption = task.bpe.decode(task.tgt_dict.string([token for token in tokens if token >= 4]))[
212
+ 38:].replace('/', '')
213
+
214
+ text_similarity_score, indices = task.compute_text_similarity(hypos, caption,
215
+ sample['net_input']['src_tokens'].device)
216
+ results = []
217
+ for i, indice in enumerate(indices):
218
+ results.append({"sample_id": str(sample["id"][0]), "score": text_similarity_score[i], "image": hypos[indice]})
219
+ scores = [max(text_similarity_score).item()]
220
+ sorted_hyps = [hypos[indice] for indice in indices]
221
+ # dump results
222
+ if task.cfg.gen_images_path:
223
+ caption_tokens = sample['net_input']['src_tokens'][0].view(-1).tolist()
224
+ caption = task.bpe.decode(task.tgt_dict.string([token for token in caption_tokens if token >= 4]))[
225
+ 38:].replace('/', '')
226
+ task.dump_images(sorted_hyps, text=caption, path=os.path.join(task.cfg.gen_images_path, 'all_results'))
227
+ task.dump_images(sorted_hyps, text=caption, path=os.path.join(task.cfg.gen_images_path, 'top1'), topk=1)
228
+
229
+ return results, scores
230
+
231
+
232
+ def eval_glue(task, generator, models, sample, **kwargs):
233
+ net_output = models[0](**sample["net_input"])
234
+ net_output[0].masked_fill_(~sample["constraint_masks"], -math.inf)
235
+ last_token_ids = sample["net_input"]["prev_output_tokens"].ne(task.src_dict.pad()).sum(1, keepdim=True) - 1
236
+ logits = net_output[0].gather(1, last_token_ids.unsqueeze(2).expand(-1, -1, net_output[0].size(2)))
237
+ logits = logits.squeeze(1)
238
+ predicts = logits.argmax(1).tolist()
239
+ hyps = [task.bpe.decode(task.src_dict[predict]).strip() for predict in predicts]
240
+ results = [{"hyp": hyp, "ref": ref_dict.keys()[0]} for hyp, ref_dict in zip(hyps, sample['ref_dict'])]
241
+ return results, None
242
+
243
+
244
+ def eval_gigaword(task, generator, models, sample, **kwargs):
245
+ gen_out = task.inference_step(generator, models, sample)
246
+ hyps, refs = [], []
247
+ results = []
248
+ for i in range(len(gen_out)):
249
+ hyp = decode_fn(gen_out[i][0]["tokens"], task.tgt_dict, task.bpe, generator).lower().strip()
250
+ hyp = fix_tokenization(hyp).replace('1', '#')
251
+ ref = sample['target_strs'][i]
252
+ hyps.append(hyp)
253
+ refs.append(ref)
254
+ results.append({"hyp": hyp, "ref": ref})
255
+ return results, None
256
+
257
+
258
+ def eval_image_classify(task, generator, models, sample, **kwargs):
259
+ batch_size = sample["net_input"]["src_tokens"].size(0)
260
+ encoder_out = models[0].encoder(
261
+ sample["net_input"]["src_tokens"],
262
+ src_lengths=sample["net_input"]["src_lengths"],
263
+ patch_images=sample["net_input"]["patch_images"],
264
+ patch_masks=sample["net_input"]["patch_masks"]
265
+ )
266
+ device = sample["net_input"]["src_tokens"].device
267
+ valid_result = []
268
+ for valid_tgt, valid_prev_output, valid_constraint_masks in zip(task.valid_tgt_list,
269
+ task.valid_prev_output_list,
270
+ task.valid_constraint_masks_list):
271
+ valid_tgt_size = valid_tgt.size(0)
272
+ valid_tgt = valid_tgt.repeat(batch_size, 1).to(device)
273
+ valid_prev_output = valid_prev_output.repeat(batch_size, 1).to(device)
274
+ valid_constraint_masks = valid_constraint_masks.repeat(batch_size, 1, 1).to(device)
275
+ new_encoder_out = {}
276
+ new_encoder_out["encoder_out"] = [
277
+ encoder_out["encoder_out"][0].repeat_interleave(valid_tgt_size, dim=1)
278
+ ]
279
+ new_encoder_out["encoder_padding_mask"] = [
280
+ encoder_out["encoder_padding_mask"][0].repeat_interleave(valid_tgt_size, dim=0)
281
+ ]
282
+ new_encoder_out["position_embeddings"] = [
283
+ encoder_out["position_embeddings"][0].repeat_interleave(valid_tgt_size, dim=0)
284
+ ]
285
+
286
+ decoder_out = models[0].decoder(valid_prev_output, encoder_out=new_encoder_out)
287
+ decoder_out[0].masked_fill_(~valid_constraint_masks, -math.inf)
288
+ lprobs = models[0].get_normalized_probs(decoder_out, log_probs=True)
289
+ scores = lprobs.gather(dim=-1, index=valid_tgt.unsqueeze(-1)).squeeze(-1)
290
+ scores = scores.masked_fill(valid_tgt.eq(task.tgt_dict.pad()), 0)
291
+ scores = scores.sum(1)
292
+ scores = scores.view(-1, valid_tgt_size)
293
+ valid_result.append(scores)
294
+ valid_result = torch.cat(valid_result, dim=-1)
295
+ predicts = valid_result.argmax(1).tolist()
296
+ hyps = [task.index2ans[predict_index] for predict_index in predicts]
297
+ scores = [ref_dict.get(hyp, 0) for ref_dict, hyp in zip(sample['ref_dict'], hyps)]
298
+ results = [{"uniq_id": id, "answer": hyp} for id, hyp in zip(sample["id"].tolist(), hyps)]
299
+ return results, scores
300
+
301
+
302
+ def eval_step(task, generator, models, sample, **kwargs):
303
+ if task.cfg._name == 'caption':
304
+ return eval_caption(task, generator, models, sample, **kwargs)
305
+ elif task.cfg._name == 'vqa_gen':
306
+ return eval_vqa_gen(task, generator, models, sample, **kwargs)
307
+ elif task.cfg._name == 'refcoco':
308
+ return eval_refcoco(task, generator, models, sample, **kwargs)
309
+ elif task.cfg._name == 'snli_ve':
310
+ return eval_snli_ve(task, generator, models, sample, **kwargs)
311
+ elif task.cfg._name == 'image_gen':
312
+ return eval_image_gen(task, generator, models, sample, **kwargs)
313
+ elif task.cfg._name in {'cola', 'mnli', 'mrpc', 'qnli', 'qqp', 'rte', 'sst2'}:
314
+ return eval_glue(task, generator, models, sample, **kwargs)
315
+ elif task.cfg._name == 'gigaword':
316
+ return eval_gigaword(task, generator, models, sample, **kwargs)
317
+ elif task.cfg._name == 'image_classify':
318
+ return eval_image_classify(task, generator, models, sample, **kwargs)
319
+ else:
320
+ raise NotImplementedError
321
+
322
+
323
+ def merge_results(task, cfg, logger, score_cnt, score_sum, results):
324
+ if task.cfg._name == 'image_gen':
325
+ if cfg.distributed_training.distributed_world_size > 1:
326
+ dist.all_reduce(score_sum.data)
327
+ dist.all_reduce(score_cnt.data)
328
+ if score_cnt.item() > 0:
329
+ logger.info("score_sum: {}, score_cnt: {}, score: {}".format(
330
+ score_sum, score_cnt, round(score_sum.item() / score_cnt.item(), 4)
331
+ ))
332
+ else:
333
+ gather_results = None
334
+ if cfg.distributed_training.distributed_world_size > 1:
335
+ gather_results = [None for _ in range(dist.get_world_size())]
336
+ dist.all_gather_object(gather_results, results)
337
+ dist.all_reduce(score_sum.data)
338
+ dist.all_reduce(score_cnt.data)
339
+ if score_cnt.item() > 0:
340
+ logger.info("score_sum: {}, score_cnt: {}, score: {}".format(
341
+ score_sum, score_cnt, round(score_sum.item() / score_cnt.item(), 4)
342
+ ))
343
+
344
+ if cfg.distributed_training.distributed_world_size == 1 or dist.get_rank() == 0:
345
+ os.makedirs(cfg.common_eval.results_path, exist_ok=True)
346
+ output_path = os.path.join(cfg.common_eval.results_path, "{}_predict.json".format(cfg.dataset.gen_subset))
347
+ gather_results = list(chain(*gather_results)) if gather_results is not None else results
348
+ with open(output_path, 'w') as fw:
349
+ json.dump(gather_results, fw)
utils/transforms.py ADDED
@@ -0,0 +1,513 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The OFA-Sys Team.
2
+ # All rights reserved.
3
+ # This source code is licensed under the Apache 2.0 license
4
+ # found in the LICENSE file in the root directory.
5
+
6
+ import random
7
+
8
+ import torch
9
+ import torchvision.transforms as T
10
+ import torchvision.transforms.functional as F
11
+ import numpy as np
12
+ from PIL import Image
13
+
14
+
15
+ def crop(image, target, region, delete=True):
16
+ cropped_image = F.crop(image, *region)
17
+
18
+ target = target.copy()
19
+ i, j, h, w = region
20
+
21
+ # should we do something wrt the original size?
22
+ target["size"] = torch.tensor([h, w])
23
+
24
+ fields = ["labels", "area"]
25
+
26
+ if "boxes" in target:
27
+ boxes = target["boxes"]
28
+ max_size = torch.as_tensor([w, h], dtype=torch.float32)
29
+ cropped_boxes = boxes - torch.as_tensor([j, i, j, i])
30
+ cropped_boxes = torch.min(cropped_boxes.reshape(-1, 2, 2), max_size)
31
+ cropped_boxes = cropped_boxes.clamp(min=0)
32
+ area = (cropped_boxes[:, 1, :] - cropped_boxes[:, 0, :]).prod(dim=1)
33
+ target["boxes"] = cropped_boxes.reshape(-1, 4)
34
+ target["area"] = area
35
+ fields.append("boxes")
36
+
37
+ if "polygons" in target:
38
+ polygons = target["polygons"]
39
+ num_polygons = polygons.shape[0]
40
+ max_size = torch.as_tensor([w, h], dtype=torch.float32)
41
+ start_coord = torch.cat([torch.tensor([j, i], dtype=torch.float32)
42
+ for _ in range(polygons.shape[1] // 2)], dim=0)
43
+ cropped_boxes = polygons - start_coord
44
+ cropped_boxes = torch.min(cropped_boxes.reshape(num_polygons, -1, 2), max_size)
45
+ cropped_boxes = cropped_boxes.clamp(min=0)
46
+ target["polygons"] = cropped_boxes.reshape(num_polygons, -1)
47
+ fields.append("polygons")
48
+
49
+ if "masks" in target:
50
+ # FIXME should we update the area here if there are no boxes?
51
+ target['masks'] = target['masks'][:, i:i + h, j:j + w]
52
+ fields.append("masks")
53
+
54
+ # remove elements for which the boxes or masks that have zero area
55
+ if delete and ("boxes" in target or "masks" in target):
56
+ # favor boxes selection when defining which elements to keep
57
+ # this is compatible with previous implementation
58
+ if "boxes" in target:
59
+ cropped_boxes = target['boxes'].reshape(-1, 2, 2)
60
+ keep = torch.all(cropped_boxes[:, 1, :] > cropped_boxes[:, 0, :], dim=1)
61
+ else:
62
+ keep = target['masks'].flatten(1).any(1)
63
+
64
+ for field in fields:
65
+ target[field] = target[field][keep.tolist()]
66
+
67
+ return cropped_image, target
68
+
69
+
70
+ def hflip(image, target):
71
+ flipped_image = F.hflip(image)
72
+
73
+ w, h = image.size
74
+
75
+ target = target.copy()
76
+ if "boxes" in target:
77
+ boxes = target["boxes"]
78
+ boxes = boxes[:, [2, 1, 0, 3]] * torch.as_tensor([-1, 1, -1, 1]) + torch.as_tensor([w, 0, w, 0])
79
+ target["boxes"] = boxes
80
+
81
+ if "polygons" in target:
82
+ polygons = target["polygons"]
83
+ num_polygons = polygons.shape[0]
84
+ polygons = polygons.reshape(num_polygons, -1, 2) * torch.as_tensor([-1, 1]) + torch.as_tensor([w, 0])
85
+ target["polygons"] = polygons
86
+
87
+ if "masks" in target:
88
+ target['masks'] = target['masks'].flip(-1)
89
+
90
+ return flipped_image, target
91
+
92
+
93
+ def resize(image, target, size, max_size=None):
94
+ # size can be min_size (scalar) or (w, h) tuple
95
+
96
+ def get_size_with_aspect_ratio(image_size, size, max_size=None):
97
+ w, h = image_size
98
+
99
+ if (w <= h and w == size) or (h <= w and h == size):
100
+ if max_size is not None:
101
+ max_size = int(max_size)
102
+ h = min(h, max_size)
103
+ w = min(w, max_size)
104
+ return (h, w)
105
+
106
+ if w < h:
107
+ ow = size
108
+ oh = int(size * h / w)
109
+ else:
110
+ oh = size
111
+ ow = int(size * w / h)
112
+
113
+ if max_size is not None:
114
+ max_size = int(max_size)
115
+ oh = min(oh, max_size)
116
+ ow = min(ow, max_size)
117
+
118
+ return (oh, ow)
119
+
120
+ def get_size(image_size, size, max_size=None):
121
+ if isinstance(size, (list, tuple)):
122
+ return size[::-1]
123
+ else:
124
+ return get_size_with_aspect_ratio(image_size, size, max_size)
125
+
126
+ size = get_size(image.size, size, max_size)
127
+ rescaled_image = F.resize(image, size, interpolation=Image.BICUBIC)
128
+
129
+ if target is None:
130
+ return rescaled_image
131
+
132
+ ratios = tuple(float(s) / float(s_orig) for s, s_orig in zip(rescaled_image.size, image.size))
133
+ ratio_width, ratio_height = ratios
134
+
135
+ target = target.copy()
136
+ if "boxes" in target:
137
+ boxes = target["boxes"]
138
+ scaled_boxes = boxes * torch.as_tensor([ratio_width, ratio_height, ratio_width, ratio_height])
139
+ target["boxes"] = scaled_boxes
140
+
141
+ if "polygons" in target:
142
+ polygons = target["polygons"]
143
+ scaled_ratio = torch.cat([torch.tensor([ratio_width, ratio_height])
144
+ for _ in range(polygons.shape[1] // 2)], dim=0)
145
+ scaled_polygons = polygons * scaled_ratio
146
+ target["polygons"] = scaled_polygons
147
+
148
+ if "area" in target:
149
+ area = target["area"]
150
+ scaled_area = area * (ratio_width * ratio_height)
151
+ target["area"] = scaled_area
152
+
153
+ h, w = size
154
+ target["size"] = torch.tensor([h, w])
155
+
156
+ if "masks" in target:
157
+ assert False
158
+ # target['masks'] = interpolate(
159
+ # target['masks'][:, None].float(), size, mode="nearest")[:, 0] > 0.5
160
+
161
+ return rescaled_image, target
162
+
163
+
164
+ class CenterCrop(object):
165
+ def __init__(self, size):
166
+ self.size = size
167
+
168
+ def __call__(self, img, target):
169
+ image_width, image_height = img.size
170
+ crop_height, crop_width = self.size
171
+ crop_top = int(round((image_height - crop_height) / 2.))
172
+ crop_left = int(round((image_width - crop_width) / 2.))
173
+ return crop(img, target, (crop_top, crop_left, crop_height, crop_width))
174
+
175
+
176
+ class ObjectCenterCrop(object):
177
+ def __init__(self, size):
178
+ self.size = size
179
+
180
+ def __call__(self, img, target):
181
+ image_width, image_height = img.size
182
+ crop_height, crop_width = self.size
183
+
184
+ x0 = float(target['boxes'][0][0])
185
+ y0 = float(target['boxes'][0][1])
186
+ x1 = float(target['boxes'][0][2])
187
+ y1 = float(target['boxes'][0][3])
188
+
189
+ center_x = (x0 + x1) / 2
190
+ center_y = (y0 + y1) / 2
191
+ crop_left = max(center_x-crop_width/2 + min(image_width-center_x-crop_width/2, 0), 0)
192
+ crop_top = max(center_y-crop_height/2 + min(image_height-center_y-crop_height/2, 0), 0)
193
+
194
+ return crop(img, target, (crop_top, crop_left, crop_height, crop_width), delete=False)
195
+
196
+
197
+ class RandomHorizontalFlip(object):
198
+ def __init__(self, p=0.5):
199
+ self.p = p
200
+
201
+ def __call__(self, img, target):
202
+ if random.random() < self.p:
203
+ return hflip(img, target)
204
+ return img, target
205
+
206
+
207
+ class RandomResize(object):
208
+ def __init__(self, sizes, max_size=None, equal=False):
209
+ assert isinstance(sizes, (list, tuple))
210
+ self.sizes = sizes
211
+ self.max_size = max_size
212
+ self.equal = equal
213
+
214
+ def __call__(self, img, target=None):
215
+ size = random.choice(self.sizes)
216
+ if self.equal:
217
+ return resize(img, target, size, size)
218
+ else:
219
+ return resize(img, target, size, self.max_size)
220
+
221
+
222
+ class ToTensor(object):
223
+ def __call__(self, img, target):
224
+ return F.to_tensor(img), target
225
+
226
+
227
+ class Normalize(object):
228
+ def __init__(self, mean, std, max_image_size=512):
229
+ self.mean = mean
230
+ self.std = std
231
+ self.max_image_size = max_image_size
232
+
233
+ def __call__(self, image, target=None):
234
+ image = F.normalize(image, mean=self.mean, std=self.std)
235
+ if target is None:
236
+ return image, None
237
+ target = target.copy()
238
+ # h, w = image.shape[-2:]
239
+ h, w = target["size"][0], target["size"][1]
240
+ if "boxes" in target:
241
+ boxes = target["boxes"]
242
+ boxes = boxes / self.max_image_size
243
+ target["boxes"] = boxes
244
+ if "polygons" in target:
245
+ polygons = target["polygons"]
246
+ scale = torch.cat([torch.tensor([w, h], dtype=torch.float32)
247
+ for _ in range(polygons.shape[1] // 2)], dim=0)
248
+ polygons = polygons / scale
249
+ target["polygons"] = polygons
250
+ return image, target
251
+
252
+
253
+ class Compose(object):
254
+ def __init__(self, transforms):
255
+ self.transforms = transforms
256
+
257
+ def __call__(self, image, target):
258
+ for t in self.transforms:
259
+ image, target = t(image, target)
260
+ return image, target
261
+
262
+ def __repr__(self):
263
+ format_string = self.__class__.__name__ + "("
264
+ for t in self.transforms:
265
+ format_string += "\n"
266
+ format_string += " {0}".format(t)
267
+ format_string += "\n)"
268
+ return format_string
269
+
270
+
271
+ class LargeScaleJitter(object):
272
+ """
273
+ implementation of large scale jitter from copy_paste
274
+ """
275
+
276
+ def __init__(self, output_size=512, aug_scale_min=0.3, aug_scale_max=2.0):
277
+ self.desired_size = torch.tensor([output_size])
278
+ self.aug_scale_min = aug_scale_min
279
+ self.aug_scale_max = aug_scale_max
280
+
281
+ def rescale_target(self, scaled_size, image_size, target):
282
+ # compute rescaled targets
283
+ image_scale = scaled_size / image_size
284
+ ratio_height, ratio_width = image_scale
285
+
286
+ target = target.copy()
287
+ target["size"] = scaled_size
288
+
289
+ if "boxes" in target:
290
+ boxes = target["boxes"]
291
+ scaled_boxes = boxes * torch.as_tensor([ratio_width, ratio_height, ratio_width, ratio_height])
292
+ target["boxes"] = scaled_boxes
293
+
294
+ if "area" in target:
295
+ area = target["area"]
296
+ scaled_area = area * (ratio_width * ratio_height)
297
+ target["area"] = scaled_area
298
+
299
+ if "masks" in target:
300
+ assert False
301
+ masks = target['masks']
302
+ # masks = interpolate(
303
+ # masks[:, None].float(), scaled_size, mode="nearest")[:, 0] > 0.5
304
+ target['masks'] = masks
305
+ return target
306
+
307
+ def crop_target(self, region, target):
308
+ i, j, h, w = region
309
+ fields = ["labels", "area"]
310
+
311
+ target = target.copy()
312
+ target["size"] = torch.tensor([h, w])
313
+
314
+ if "boxes" in target:
315
+ boxes = target["boxes"]
316
+ max_size = torch.as_tensor([w, h], dtype=torch.float32)
317
+ cropped_boxes = boxes - torch.as_tensor([j, i, j, i])
318
+ cropped_boxes = torch.min(cropped_boxes.reshape(-1, 2, 2), max_size)
319
+ cropped_boxes = cropped_boxes.clamp(min=0)
320
+ area = (cropped_boxes[:, 1, :] - cropped_boxes[:, 0, :]).prod(dim=1)
321
+ target["boxes"] = cropped_boxes.reshape(-1, 4)
322
+ target["area"] = area
323
+ fields.append("boxes")
324
+
325
+ if "masks" in target:
326
+ # FIXME should we update the area here if there are no boxes?
327
+ target['masks'] = target['masks'][:, i:i + h, j:j + w]
328
+ fields.append("masks")
329
+
330
+ # remove elements for which the boxes or masks that have zero area
331
+ if "boxes" in target or "masks" in target:
332
+ # favor boxes selection when defining which elements to keep
333
+ # this is compatible with previous implementation
334
+ if "boxes" in target:
335
+ cropped_boxes = target['boxes'].reshape(-1, 2, 2)
336
+ keep = torch.all(cropped_boxes[:, 1, :] > cropped_boxes[:, 0, :], dim=1)
337
+ else:
338
+ keep = target['masks'].flatten(1).any(1)
339
+
340
+ for field in fields:
341
+ target[field] = target[field][keep.tolist()]
342
+ return target
343
+
344
+ def pad_target(self, padding, target):
345
+ target = target.copy()
346
+ if "masks" in target:
347
+ target['masks'] = torch.nn.functional.pad(target['masks'], (0, padding[1], 0, padding[0]))
348
+ return target
349
+
350
+ def __call__(self, image, target=None):
351
+ image_size = image.size
352
+ image_size = torch.tensor(image_size[::-1])
353
+
354
+ random_scale = torch.rand(1) * (self.aug_scale_max - self.aug_scale_min) + self.aug_scale_min
355
+ scaled_size = (random_scale * self.desired_size).round()
356
+
357
+ scale = torch.maximum(scaled_size / image_size[0], scaled_size / image_size[1])
358
+ scaled_size = (image_size * scale).round().int()
359
+
360
+ scaled_image = F.resize(image, scaled_size.tolist(), interpolation=Image.BICUBIC)
361
+
362
+ if target is not None:
363
+ target = self.rescale_target(scaled_size, image_size, target)
364
+
365
+ # randomly crop or pad images
366
+ if random_scale >= 1:
367
+ # Selects non-zero random offset (x, y) if scaled image is larger than desired_size.
368
+ max_offset = scaled_size - self.desired_size
369
+ offset = (max_offset * torch.rand(2)).floor().int()
370
+ region = (offset[0].item(), offset[1].item(),
371
+ self.desired_size[0].item(), self.desired_size[0].item())
372
+ output_image = F.crop(scaled_image, *region)
373
+ if target is not None:
374
+ target = self.crop_target(region, target)
375
+ else:
376
+ assert False
377
+ padding = self.desired_size - scaled_size
378
+ output_image = F.pad(scaled_image, [0, 0, padding[1].item(), padding[0].item()])
379
+ if target is not None:
380
+ target = self.pad_target(padding, target)
381
+
382
+ return output_image, target
383
+
384
+
385
+ class OriginLargeScaleJitter(object):
386
+ """
387
+ implementation of large scale jitter from copy_paste
388
+ """
389
+
390
+ def __init__(self, output_size=512, aug_scale_min=0.3, aug_scale_max=2.0):
391
+ self.desired_size = torch.tensor(output_size)
392
+ self.aug_scale_min = aug_scale_min
393
+ self.aug_scale_max = aug_scale_max
394
+
395
+ def rescale_target(self, scaled_size, image_size, target):
396
+ # compute rescaled targets
397
+ image_scale = scaled_size / image_size
398
+ ratio_height, ratio_width = image_scale
399
+
400
+ target = target.copy()
401
+ target["size"] = scaled_size
402
+
403
+ if "boxes" in target:
404
+ boxes = target["boxes"]
405
+ scaled_boxes = boxes * torch.as_tensor([ratio_width, ratio_height, ratio_width, ratio_height])
406
+ target["boxes"] = scaled_boxes
407
+
408
+ if "area" in target:
409
+ area = target["area"]
410
+ scaled_area = area * (ratio_width * ratio_height)
411
+ target["area"] = scaled_area
412
+
413
+ if "masks" in target:
414
+ assert False
415
+ masks = target['masks']
416
+ # masks = interpolate(
417
+ # masks[:, None].float(), scaled_size, mode="nearest")[:, 0] > 0.5
418
+ target['masks'] = masks
419
+ return target
420
+
421
+ def crop_target(self, region, target):
422
+ i, j, h, w = region
423
+ fields = ["labels", "area"]
424
+
425
+ target = target.copy()
426
+ target["size"] = torch.tensor([h, w])
427
+
428
+ if "boxes" in target:
429
+ boxes = target["boxes"]
430
+ max_size = torch.as_tensor([w, h], dtype=torch.float32)
431
+ cropped_boxes = boxes - torch.as_tensor([j, i, j, i])
432
+ cropped_boxes = torch.min(cropped_boxes.reshape(-1, 2, 2), max_size)
433
+ cropped_boxes = cropped_boxes.clamp(min=0)
434
+ area = (cropped_boxes[:, 1, :] - cropped_boxes[:, 0, :]).prod(dim=1)
435
+ target["boxes"] = cropped_boxes.reshape(-1, 4)
436
+ target["area"] = area
437
+ fields.append("boxes")
438
+
439
+ if "masks" in target:
440
+ # FIXME should we update the area here if there are no boxes?
441
+ target['masks'] = target['masks'][:, i:i + h, j:j + w]
442
+ fields.append("masks")
443
+
444
+ # remove elements for which the boxes or masks that have zero area
445
+ if "boxes" in target or "masks" in target:
446
+ # favor boxes selection when defining which elements to keep
447
+ # this is compatible with previous implementation
448
+ if "boxes" in target:
449
+ cropped_boxes = target['boxes'].reshape(-1, 2, 2)
450
+ keep = torch.all(cropped_boxes[:, 1, :] > cropped_boxes[:, 0, :], dim=1)
451
+ else:
452
+ keep = target['masks'].flatten(1).any(1)
453
+
454
+ for field in fields:
455
+ target[field] = target[field][keep.tolist()]
456
+ return target
457
+
458
+ def pad_target(self, padding, target):
459
+ target = target.copy()
460
+ if "masks" in target:
461
+ target['masks'] = torch.nn.functional.pad(target['masks'], (0, padding[1], 0, padding[0]))
462
+ return target
463
+
464
+ def __call__(self, image, target=None):
465
+ image_size = image.size
466
+ image_size = torch.tensor(image_size[::-1])
467
+
468
+ out_desired_size = (self.desired_size * image_size / max(image_size)).round().int()
469
+
470
+ random_scale = torch.rand(1) * (self.aug_scale_max - self.aug_scale_min) + self.aug_scale_min
471
+ scaled_size = (random_scale * self.desired_size).round()
472
+
473
+ scale = torch.minimum(scaled_size / image_size[0], scaled_size / image_size[1])
474
+ scaled_size = (image_size * scale).round().int()
475
+
476
+ scaled_image = F.resize(image, scaled_size.tolist())
477
+
478
+ if target is not None:
479
+ target = self.rescale_target(scaled_size, image_size, target)
480
+
481
+ # randomly crop or pad images
482
+ if random_scale > 1:
483
+ # Selects non-zero random offset (x, y) if scaled image is larger than desired_size.
484
+ max_offset = scaled_size - out_desired_size
485
+ offset = (max_offset * torch.rand(2)).floor().int()
486
+ region = (offset[0].item(), offset[1].item(),
487
+ out_desired_size[0].item(), out_desired_size[1].item())
488
+ output_image = F.crop(scaled_image, *region)
489
+ if target is not None:
490
+ target = self.crop_target(region, target)
491
+ else:
492
+ padding = out_desired_size - scaled_size
493
+ output_image = F.pad(scaled_image, [0, 0, padding[1].item(), padding[0].item()])
494
+ if target is not None:
495
+ target = self.pad_target(padding, target)
496
+
497
+ return output_image, target
498
+
499
+
500
+ class RandomDistortion(object):
501
+ """
502
+ Distort image w.r.t hue, saturation and exposure.
503
+ """
504
+
505
+ def __init__(self, brightness=0, contrast=0, saturation=0, hue=0, prob=0.5):
506
+ self.prob = prob
507
+ self.tfm = T.ColorJitter(brightness, contrast, saturation, hue)
508
+
509
+ def __call__(self, img, target=None):
510
+ if np.random.random() < self.prob:
511
+ return self.tfm(img), target
512
+ else:
513
+ return img, target
utils/trie.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The OFA-Sys Team.
2
+ # All rights reserved.
3
+ # This source code is licensed under the Apache 2.0 license
4
+ # found in the LICENSE file in the root directory.
5
+
6
+ from collections import defaultdict
7
+
8
+
9
+ class TreeNode():
10
+ def __init__(self):
11
+ self.child = defaultdict(TreeNode)
12
+
13
+ class Trie:
14
+
15
+ def __init__(self, eos):
16
+ self.root = TreeNode()
17
+ self.eos = eos
18
+
19
+ def insert(self, word):
20
+ cur = self.root
21
+ for c in word:
22
+ cur = cur.child[c]
23
+
24
+ def get_next_layer(self, word):
25
+ cur = self.root
26
+ for c in word:
27
+ cur = cur.child.get(c)
28
+ if cur is None:
29
+ return [self.eos]
30
+ return list(cur.child.keys())