/
processors.py
1355 lines (1074 loc) · 43.1 KB
/
processors.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) Facebook, Inc. and its affiliates.
"""
The processors exist in MMF to make data processing pipelines in various
datasets as similar as possible while allowing code reuse.
The processors also help maintain proper abstractions to keep only what matters
inside the dataset's code. This allows us to keep the dataset ``__getitem__``
logic really clean and no need about maintaining opinions about data type.
Processors can work on both images and text due to their generic structure.
To create a new processor, follow these steps:
1. Inherit the ``BaseProcessor`` class.
2. Implement ``_call`` function which takes in a dict and returns a dict with
same keys preprocessed as well as any extra keys that need to be returned.
3. Register the processor using ``@registry.register_processor('name')`` to
registry where 'name' will be used to refer to your processor later.
In processor's config you can specify ``preprocessor`` option to specify
different kind of preprocessors you want in your dataset.
Let's break down processor's config inside a dataset (VQA2.0) a bit to understand
different moving parts.
Config::
dataset_config:
vqa2:
processors:
text_processor:
type: vocab
params:
max_length: 14
vocab:
type: intersected
embedding_name: glove.6B.300d
vocab_file: vocabs/vocabulary_100k.txt
answer_processor:
type: vqa_answer
params:
num_answers: 10
vocab_file: vocabs/answers_vqa.txt
preprocessor:
type: simple_word
params: {}
``BaseDataset`` will init the processors and they will available inside your
dataset with same attribute name as the key name, for e.g. `text_processor` will
be available as `self.text_processor` inside your dataset. As is with every module
in MMF, processor also accept a ``DictConfig`` with a `type` and `params`
attributes. `params` defined the custom parameters for each of the processors.
By default, processor initialization process will also init `preprocessor` attribute
which can be a processor config in itself. `preprocessor` can be then be accessed
inside the processor's functions.
Example::
from mmf.common.registry import registry
from mmf.datasets.processors import BaseProcessor
class MyProcessor(BaseProcessor):
def __init__(self, config, *args, **kwargs):
return
def __call__(self, item, *args, **kwargs):
text = item['text']
text = [t.strip() for t in text.split(" ")]
return {"text": text}
"""
import copy
import os
import re
import warnings
from collections import Counter, defaultdict
import numpy as np
import torch
from mmf.common.registry import registry
from mmf.utils.configuration import get_mmf_cache_dir
from mmf.utils.distributed import is_master, synchronize
from mmf.utils.file_io import PathManager
from mmf.utils.text import VocabDict
from mmf.utils.vocab import Vocab, WordToVectorDict
class BaseProcessor:
"""Every processor in MMF needs to inherit this class for compatibility
with MMF. End user mainly needs to implement ``__call__`` function.
Args:
config (DictConfig): Config for this processor, containing `type` and
`params` attributes if available.
"""
def __init__(self, config, *args, **kwargs):
return
def __call__(self, item, *args, **kwargs):
"""Main function of the processor. Takes in a dict and returns back
a dict
Args:
item (Dict): Some item that needs to be processed.
Returns:
Dict: Processed dict.
"""
return item
class Processor:
"""Wrapper class used by MMF to initialized processor based on their
``type`` as passed in configuration. It retrieves the processor class
registered in registry corresponding to the ``type`` key and initializes
with ``params`` passed in configuration. All functions and attributes of
the processor initialized are directly available via this class.
Args:
config (DictConfig): DictConfig containing ``type`` of the processor to
be initialized and ``params`` of that procesor.
"""
def __init__(self, config, *args, **kwargs):
self.writer = registry.get("writer")
if not hasattr(config, "type"):
raise AttributeError(
"Config must have 'type' attribute to specify type of processor"
)
processor_class = registry.get_processor_class(config.type)
params = {}
if not hasattr(config, "params"):
self.writer.write(
"Config doesn't have 'params' attribute to "
"specify parameters of the processor "
"of type {}. Setting to default {{}}".format(config.type)
)
else:
params = config.params
self.processor = processor_class(params, *args, **kwargs)
self._dir_representation = dir(self)
def __call__(self, item, *args, **kwargs):
return self.processor(item, *args, **kwargs)
def __getattr__(self, name):
if "_dir_representation" in self.__dict__ and name in self._dir_representation:
return getattr(self, name)
elif "processor" in self.__dict__ and hasattr(self.processor, name):
return getattr(self.processor, name)
else:
raise AttributeError(name)
@registry.register_processor("vocab")
class VocabProcessor(BaseProcessor):
"""Use VocabProcessor when you have vocab file and you want to process
words to indices. Expects UNK token as "<unk>" and pads sentences using
"<pad>" token. Config parameters can have ``preprocessor`` property which
is used to preprocess the item passed and ``max_length`` property which
points to maximum length of the sentence/tokens which can be convert to
indices. If the length is smaller, the sentence will be padded. Parameters
for "vocab" are necessary to be passed.
**Key**: vocab
Example Config::
task_attributes:
vqa:
vqa2:
processors:
text_processor:
type: vocab
params:
max_length: 14
vocab:
type: intersected
embedding_name: glove.6B.300d
vocab_file: vocabs/vocabulary_100k.txt
Args:
config (DictConfig): node containing configuration parameters of
the processor
Attributes:
vocab (Vocab): Vocab class object which is abstraction over the vocab
file passed.
"""
MAX_LENGTH_DEFAULT = 50
PAD_TOKEN = "<pad>"
PAD_INDEX = 0
def __init__(self, config, *args, **kwargs):
if not hasattr(config, "vocab"):
raise AttributeError(
"config passed to the processor has no attribute vocab"
)
self.vocab = Vocab(*args, **config.vocab, **kwargs)
self._init_extras(config)
def _init_extras(self, config, *args, **kwargs):
self.writer = registry.get("writer")
self.preprocessor = None
if hasattr(config, "max_length"):
self.max_length = config.max_length
else:
warnings.warn(
"No 'max_length' parameter in Processor's "
"configuration. Setting to {}.".format(self.MAX_LENGTH_DEFAULT)
)
self.max_length = self.MAX_LENGTH_DEFAULT
if "preprocessor" in config:
self.preprocessor = Processor(config.preprocessor, *args, **kwargs)
if self.preprocessor is None:
raise ValueError(
f"No text processor named {config.preprocessor} is defined."
)
def __call__(self, item):
"""Call requires item to have either "tokens" attribute or either
"text" attribute. If "text" is present, it will tokenized using
the preprocessor.
Args:
item (Dict): Dict containing the "text" or "tokens".
Returns:
Dict: Dict containing indices in "text" key, "tokens" in "tokens"
key and "length" of the string in "length" key.
"""
indices = None
if not isinstance(item, dict):
raise TypeError(
"Argument passed to the processor must be "
"a dict with either 'text' or 'tokens' as "
"keys"
)
if "tokens" in item:
tokens = item["tokens"]
indices = self._map_strings_to_indices(item["tokens"])
elif "text" in item:
if self.preprocessor is None:
raise AssertionError(
"If tokens are not provided, a text "
"processor must be defined in the config"
)
tokens = self.preprocessor({"text": item["text"]})["text"]
indices = self._map_strings_to_indices(tokens)
else:
raise AssertionError(
"A dict with either 'text' or 'tokens' keys "
"must be passed to the processor"
)
tokens, length = self._pad_tokens(tokens)
return {"text": indices, "tokens": tokens, "length": length}
def _pad_tokens(self, tokens):
padded_tokens = [self.PAD_TOKEN] * self.max_length
token_length = min(len(tokens), self.max_length)
padded_tokens[:token_length] = tokens[:token_length]
token_length = torch.tensor(token_length, dtype=torch.long)
return padded_tokens, token_length
def get_pad_index(self):
"""Get index of padding <pad> token in vocabulary.
Returns:
int: index of the padding token.
"""
return self.vocab.get_pad_index()
def get_vocab_size(self):
"""Get size of the vocabulary.
Returns:
int: size of the vocabulary.
"""
return self.vocab.get_size()
def _map_strings_to_indices(self, tokens):
length = min(len(tokens), self.max_length)
tokens = tokens[:length]
output = torch.zeros(self.max_length, dtype=torch.long)
output.fill_(self.vocab.get_pad_index())
for idx, token in enumerate(tokens):
output[idx] = self.vocab.stoi[token]
return output
@registry.register_processor("glove")
class GloVeProcessor(VocabProcessor):
"""Inherits VocabProcessor, and returns GloVe vectors for each of the
words. Maps them to index using vocab processor, and then gets GloVe vectors
corresponding to those indices.
Args:
config (DictConfig): Configuration parameters for GloVe same as
:func:`~VocabProcessor`.
"""
def __init__(self, config, *args, **kwargs):
if not hasattr(config, "vocab"):
raise AttributeError(
"Config passed to the processor has no attribute vocab"
)
vocab_processor_config = copy.deepcopy(config)
# GloVeProcessor needs vocab type to be "intersected"
vocab_processor_config.vocab.type = "intersected"
if "vocab_file" not in vocab_processor_config.vocab:
warnings.warn(
"'vocab_file' key is not present in the config."
" Switching to pretrained vocab."
)
vocab_processor_config.vocab.type = "pretrained"
super().__init__(vocab_processor_config, *args, **kwargs)
def __call__(self, item):
indices = super().__call__(item)["text"]
embeddings = torch.zeros(
(len(indices), self.vocab.get_embedding_dim()), dtype=torch.float
)
for idx, index in enumerate(indices):
embeddings[idx] = self.vocab.vectors[index]
return {"text": embeddings}
@registry.register_processor("fasttext")
class FastTextProcessor(VocabProcessor):
"""FastText processor, similar to GloVe processor but returns FastText vectors.
Args:
config (DictConfig): Configuration values for the processor.
"""
def __init__(self, config, *args, **kwargs):
self._init_extras(config)
self.config = config
self._download_initially = config.get("download_initially", True)
self._already_downloaded = False
self._already_loaded = False
if self._download_initially:
self._try_download()
def _try_download(self):
_is_master = is_master()
if self._already_downloaded:
return
needs_download = False
if not hasattr(self.config, "model_file"):
if _is_master:
warnings.warn(
"'model_file' key is required but missing "
"from FastTextProcessor's config."
)
needs_download = True
model_file = self.config.model_file
# If model_file is already an existing path don't join to cache dir
if not PathManager.exists(model_file):
model_file = os.path.join(get_mmf_cache_dir(), model_file)
if not PathManager.exists(model_file):
if _is_master:
warnings.warn(f"No model file present at {model_file}.")
needs_download = True
if needs_download:
self.writer.write("Downloading FastText bin", "info")
model_file = self._download_model()
self.model_file = model_file
self._already_downloaded = True
synchronize()
def _download_model(self):
_is_master = is_master()
model_file_path = os.path.join(get_mmf_cache_dir(), "wiki.en.bin")
if not _is_master:
return model_file_path
if PathManager.exists(model_file_path):
self.writer.write(f"Vectors already present at {model_file_path}.", "info")
return model_file_path
import requests
from mmf.common.constants import FASTTEXT_WIKI_URL
from tqdm import tqdm
PathManager.mkdirs(os.path.dirname(model_file_path))
response = requests.get(FASTTEXT_WIKI_URL, stream=True)
with PathManager.open(model_file_path, "wb") as f:
pbar = tqdm(
total=int(response.headers["Content-Length"]) / 4096,
miniters=50,
disable=not _is_master,
)
idx = 0
for data in response.iter_content(chunk_size=4096):
if data:
if idx % 50 == 0:
pbar.update(len(data))
f.write(data)
idx += 1
pbar.close()
self.writer.write(f"fastText bin downloaded at {model_file_path}.", "info")
return model_file_path
def _load_fasttext_model(self, model_file):
if self._already_loaded:
return
from fasttext import load_model
self.writer.write("Loading fasttext model now from %s" % model_file)
self.model = load_model(model_file)
# String to Vector
self.stov = WordToVectorDict(self.model)
self.writer.write("Finished loading fasttext model")
self._already_loaded = True
def _map_strings_to_indices(self, tokens):
length = min(len(tokens), self.max_length)
tokens = tokens[:length]
output = torch.full(
(self.max_length, self.model.get_dimension()),
fill_value=self.PAD_INDEX,
dtype=torch.float,
)
for idx, token in enumerate(tokens):
output[idx] = torch.from_numpy(self.stov[token])
return output
def __call__(self, item):
self._load_fasttext_model(self.model_file)
return super().__call__(item)
@registry.register_processor("vqa_answer")
class VQAAnswerProcessor(BaseProcessor):
"""Processor for generating answer scores for answers passed using VQA
accuracy formula. Using VocabDict class to represent answer vocabulary,
so parameters must specify "vocab_file". "num_answers" in parameter config
specify the max number of answers possible. Takes in dict containing
"answers" or "answers_tokens". "answers" are preprocessed to generate
"answers_tokens" if passed.
Args:
config (DictConfig): Configuration for the processor
Attributes:
answer_vocab (VocabDict): Class representing answer vocabulary
"""
DEFAULT_NUM_ANSWERS = 10
def __init__(self, config, *args, **kwargs):
self.writer = registry.get("writer")
if not hasattr(config, "vocab_file"):
raise AttributeError(
"'vocab_file' argument required, but not "
"present in AnswerProcessor's config"
)
self.answer_vocab = VocabDict(config.vocab_file, *args, **kwargs)
self.preprocessor = None
if hasattr(config, "preprocessor"):
self.preprocessor = Processor(config.preprocessor)
if self.preprocessor is None:
raise ValueError(
f"No processor named {config.preprocessor} is defined."
)
if hasattr(config, "num_answers"):
self.num_answers = config.num_answers
else:
self.num_answers = self.DEFAULT_NUM_ANSWERS
warnings.warn(
"'num_answers' not defined in the config. "
"Setting to default of {}".format(self.DEFAULT_NUM_ANSWERS)
)
def __call__(self, item):
"""Takes in dict with answers or answers_tokens, and returns back
a dict with answers (processed), "answers_indices" which point to
indices of the answers if present and "answers_scores" which represent
VQA style scores for the answers.
Args:
item (Dict): Dict containing answers or answers_tokens
Returns:
Dict: Processed answers, indices and scores.
"""
tokens = None
if not isinstance(item, dict):
raise TypeError("'item' passed to processor must be a dict")
if "answer_tokens" in item:
tokens = item["answer_tokens"]
elif "answers" in item:
if self.preprocessor is None:
raise AssertionError(
"'preprocessor' must be defined if you "
"don't pass 'answer_tokens'"
)
tokens = [
self.preprocessor({"text": answer})["text"]
for answer in item["answers"]
]
else:
raise AssertionError(
"'answers' or 'answer_tokens' must be passed"
" to answer processor in a dict"
)
tokens = self._increase_to_ten(tokens)
answers_indices = torch.zeros(self.DEFAULT_NUM_ANSWERS, dtype=torch.long)
answers_indices.fill_(self.answer_vocab.get_unk_index())
for idx, token in enumerate(tokens):
answers_indices[idx] = self.answer_vocab.word2idx(token)
answers_scores = self.compute_answers_scores(answers_indices)
return {
"answers": tokens,
"answers_indices": answers_indices,
"answers_scores": answers_scores,
}
def get_vocab_size(self):
"""Get vocab size of the answer vocabulary. Can also include
soft copy dynamic answer space size.
Returns:
int: size of the answer vocabulary
"""
return self.answer_vocab.num_vocab
def get_true_vocab_size(self):
"""True vocab size can be different from normal vocab size in some cases
such as soft copy where dynamic answer space is added.
Returns:
int: True vocab size.
"""
return self.answer_vocab.num_vocab
def word2idx(self, word):
"""Convert a word to its index according to vocabulary
Args:
word (str): Word to be converted to index.
Returns:
int: Index of the word.
"""
return self.answer_vocab.word2idx(word)
def idx2word(self, idx):
"""Index to word according to the vocabulary.
Args:
idx (int): Index to be converted to the word.
Returns:
str: Word corresponding to the index.
"""
return self.answer_vocab.idx2word(idx)
def compute_answers_scores(self, answers_indices):
"""Generate VQA based answer scores for answers_indices.
Args:
answers_indices (torch.LongTensor): tensor containing indices of the answers
Returns:
torch.FloatTensor: tensor containing scores.
"""
scores = torch.zeros(self.get_vocab_size(), dtype=torch.float)
gt_answers = list(enumerate(answers_indices))
unique_answers = set(answers_indices.tolist())
for answer in unique_answers:
accs = []
for gt_answer in gt_answers:
other_answers = [item for item in gt_answers if item != gt_answer]
matching_answers = [item for item in other_answers if item[1] == answer]
acc = min(1, float(len(matching_answers)) / 3)
accs.append(acc)
avg_acc = sum(accs) / len(accs)
if answer != self.answer_vocab.UNK_INDEX:
scores[answer] = avg_acc
return scores
def _increase_to_ten(self, tokens):
while len(tokens) < self.DEFAULT_NUM_ANSWERS:
tokens += tokens[: self.DEFAULT_NUM_ANSWERS - len(tokens)]
return tokens
@registry.register_processor("multi_hot_answer_from_vocab")
class MultiHotAnswerFromVocabProcessor(VQAAnswerProcessor):
def __init__(self, config, *args, **kwargs):
super().__init__(config, *args, **kwargs)
def compute_answers_scores(self, answers_indices):
scores = torch.zeros(self.get_vocab_size(), dtype=torch.float)
scores[answers_indices] = 1
scores[self.answer_vocab.UNK_INDEX] = 0
return scores
@registry.register_processor("soft_copy_answer")
class SoftCopyAnswerProcessor(VQAAnswerProcessor):
"""Similar to Answer Processor but adds soft copy dynamic answer space to it.
Read https://arxiv.org/abs/1904.08920 for extra information on soft copy
and LoRRA.
Args:
config (DictConfig): Configuration for soft copy processor.
"""
DEFAULT_MAX_LENGTH = 50
def __init__(self, config, *args, **kwargs):
super().__init__(config, *args, **kwargs)
if hasattr(config, "max_length"):
self.max_length = config.max_length
else:
self.max_length = self.DEFAULT_MAX_LENGTH
warnings.warn(
"'max_length' not defined in the config. "
"Setting to default of {}".format(self.DEFAULT_MAX_LENGTH)
)
self.context_preprocessor = None
if hasattr(config, "context_preprocessor"):
self.context_preprocessor = Processor(config.context_preprocessor)
def get_vocab_size(self):
"""Size of Vocab + Size of Dynamic soft-copy based answer space
Returns:
int: Size of vocab + size of dynamic soft-copy answer space.
"""
answer_vocab_nums = self.answer_vocab.num_vocab
answer_vocab_nums += self.max_length
return answer_vocab_nums
def get_true_vocab_size(self):
"""Actual vocab size which only include size of the vocabulary file.
Returns:
int: Actual size of vocabs.
"""
return self.answer_vocab.num_vocab
def __call__(self, item):
answers = item["answers"]
scores = super().__call__({"answers": answers})
indices = scores["answers_indices"]
answers = scores["answers"]
scores = scores["answers_scores"]
tokens_scores = scores.new_zeros(self.max_length)
tokens = item["tokens"]
length = min(len(tokens), self.max_length)
gt_answers = list(enumerate(answers))
if self.context_preprocessor is not None:
tokens = [
self.context_preprocessor({"text": token})["text"] for token in tokens
]
answer_counter = Counter(answers)
for idx, token in enumerate(tokens[:length]):
if answer_counter[token] == 0:
continue
accs = []
for gt_answer in gt_answers:
other_answers = [item for item in gt_answers if item != gt_answer]
matching_answers = [item for item in other_answers if item[1] == token]
acc = min(1, float(len(matching_answers)) / 3)
accs.append(acc)
tokens_scores[idx] = sum(accs) / len(accs)
# Scores are already proper size, see L314. Now,
# fix scores for soft copy candidates
scores[-len(tokens_scores) :] = tokens_scores
return {
"answers": answers,
"answers_indices": indices,
"answers_scores": scores,
}
@registry.register_processor("simple_word")
class SimpleWordProcessor(BaseProcessor):
"""Tokenizes a word and processes it.
Attributes:
tokenizer (function): Type of tokenizer to be used.
"""
def __init__(self, *args, **kwargs):
from mmf.utils.text import word_tokenize
self.tokenizer = word_tokenize
def __call__(self, item, *args, **kwargs):
return {"text": self.tokenizer(item["text"], *args, **kwargs)}
@registry.register_processor("simple_sentence")
class SimpleSentenceProcessor(BaseProcessor):
"""Tokenizes a sentence and processes it.
Attributes:
tokenizer (function): Type of tokenizer to be used.
"""
def __init__(self, *args, **kwargs):
from mmf.utils.text import tokenize
self.tokenizer = tokenize
def __call__(self, item, *args, **kwargs):
return {"text": self.tokenizer(item["text"], *args, **kwargs)}
@registry.register_processor("bbox")
class BBoxProcessor(VocabProcessor):
"""Generates bboxes in proper format.
Takes in a dict which contains "info" key which is a list of dicts
containing following for each of the the bounding box
Example bbox input::
{
"info": [
{
"bounding_box": {
"top_left_x": 100,
"top_left_y": 100,
"width": 200,
"height": 300
}
},
...
]
}
This will further return a Sample in a dict with key "bbox" with last
dimension of 4 corresponding to "xyxy". So sample will look like following:
Example Sample::
Sample({
"coordinates": torch.Size(n, 4),
"width": List[number], # size n
"height": List[number], # size n
"bbox_types": List[str] # size n, either xyxy or xywh.
# currently only supports xyxy.
})
"""
def __init__(self, config, *args, **kwargs):
from mmf.utils.dataset import build_bbox_tensors
self.lambda_fn = build_bbox_tensors
self._init_extras(config)
def __call__(self, item):
info = item["info"]
if self.preprocessor is not None:
info = self.preprocessor(info)
return {"bbox": self.lambda_fn(info, self.max_length)}
@registry.register_processor("caption")
class CaptionProcessor(BaseProcessor):
"""Processes a caption with start, end and pad tokens and returns raw string.
Args:
config (DictConfig): Configuration for caption processor.
"""
def __init__(self, config, *args, **kwargs):
if not hasattr(config, "vocab"):
raise AttributeError(
"config passed to the processor has no " "attribute vocab"
)
self.vocab = Vocab(*args, **config.vocab, **kwargs)
def __call__(self, item):
for idx, v in enumerate(item):
if v == self.vocab.EOS_INDEX:
item = item[:idx]
break
tokens = [
self.vocab.get_itos()[w]
for w in item
if w
not in {self.vocab.SOS_INDEX, self.vocab.EOS_INDEX, self.vocab.PAD_INDEX}
]
caption = " ".join(tokens)
return {"tokens": tokens, "caption": caption}
@registry.register_processor("evalai_answer")
class EvalAIAnswerProcessor(BaseProcessor):
"""Processes an answer similar to Eval AI
"""
CONTRACTIONS = {
"aint": "ain't",
"arent": "aren't",
"cant": "can't",
"couldve": "could've",
"couldnt": "couldn't",
"couldn'tve": "couldn't've",
"couldnt've": "couldn't've",
"didnt": "didn't",
"doesnt": "doesn't",
"dont": "don't",
"hadnt": "hadn't",
"hadnt've": "hadn't've",
"hadn'tve": "hadn't've",
"hasnt": "hasn't",
"havent": "haven't",
"hed": "he'd",
"hed've": "he'd've",
"he'dve": "he'd've",
"hes": "he's",
"howd": "how'd",
"howll": "how'll",
"hows": "how's",
"Id've": "I'd've",
"I'dve": "I'd've",
"Im": "I'm",
"Ive": "I've",
"isnt": "isn't",
"itd": "it'd",
"itd've": "it'd've",
"it'dve": "it'd've",
"itll": "it'll",
"let's": "let's",
"maam": "ma'am",
"mightnt": "mightn't",
"mightnt've": "mightn't've",
"mightn'tve": "mightn't've",
"mightve": "might've",
"mustnt": "mustn't",
"mustve": "must've",
"neednt": "needn't",
"notve": "not've",
"oclock": "o'clock",
"oughtnt": "oughtn't",
"ow's'at": "'ow's'at",
"'ows'at": "'ow's'at",
"'ow'sat": "'ow's'at",
"shant": "shan't",
"shed've": "she'd've",
"she'dve": "she'd've",
"she's": "she's",
"shouldve": "should've",
"shouldnt": "shouldn't",
"shouldnt've": "shouldn't've",
"shouldn'tve": "shouldn't've",
"somebody'd": "somebodyd",
"somebodyd've": "somebody'd've",
"somebody'dve": "somebody'd've",
"somebodyll": "somebody'll",
"somebodys": "somebody's",
"someoned": "someone'd",
"someoned've": "someone'd've",
"someone'dve": "someone'd've",
"someonell": "someone'll",
"someones": "someone's",
"somethingd": "something'd",
"somethingd've": "something'd've",
"something'dve": "something'd've",
"somethingll": "something'll",
"thats": "that's",
"thered": "there'd",
"thered've": "there'd've",
"there'dve": "there'd've",
"therere": "there're",
"theres": "there's",
"theyd": "they'd",
"theyd've": "they'd've",
"they'dve": "they'd've",
"theyll": "they'll",
"theyre": "they're",
"theyve": "they've",
"twas": "'twas",
"wasnt": "wasn't",
"wed've": "we'd've",
"we'dve": "we'd've",
"weve": "we've",
"werent": "weren't",
"whatll": "what'll",
"whatre": "what're",
"whats": "what's",
"whatve": "what've",
"whens": "when's",
"whered": "where'd",
"wheres": "where's",
"whereve": "where've",
"whod": "who'd",
"whod've": "who'd've",
"who'dve": "who'd've",
"wholl": "who'll",
"whos": "who's",
"whove": "who've",
"whyll": "why'll",