forked from nyu-mll/jiant
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tasks.py
2562 lines (2127 loc) · 105 KB
/
tasks.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
'''Define the tasks and code for loading their data.
- As much as possible, following the existing task hierarchy structure.
- When inheriting, be sure to write and call load_data.
- Set all text data as an attribute, task.sentences (List[List[str]])
- Each task's val_metric should be name_metric, where metric is returned by
get_metrics(): e.g. if task.val_metric = task_name + "_accuracy", then
task.get_metrics() should return {"accuracy": accuracy_val, ... }
'''
import copy
import collections
import itertools
import os
import math
import logging as log
import json
import numpy as np
from typing import Iterable, Sequence, List, Dict, Any, Type
import torch
import allennlp.common.util as allennlp_util
from allennlp.training.metrics import CategoricalAccuracy, \
BooleanAccuracy, F1Measure, Average
from allennlp.data.token_indexers import SingleIdTokenIndexer
from .allennlp_mods.correlation import Correlation, FastMatthews
# Fields for instance processing
from allennlp.data import Instance, Token
from allennlp.data.fields import TextField, LabelField, \
SpanField, ListField, MetadataField
from .allennlp_mods.numeric_field import NumericField
from .allennlp_mods.multilabel_field import MultiLabelField
from . import serialize
from . import utils
from .utils import load_tsv, process_sentence, truncate, load_diagnostic_tsv
import codecs
UNK_TOK_ALLENNLP = "@@UNKNOWN@@"
UNK_TOK_ATOMIC = "UNKNOWN" # an unk token that won't get split by tokenizers
REGISTRY = {} # Do not edit manually!
def register_task(name, rel_path, **kw):
'''Decorator to register a task.
Use this instead of adding to NAME2INFO in preprocess.py
If kw is not None, this will be passed as additional args when the Task is
constructed in preprocess.py.
Usage:
@register_task('mytask', 'my-task/data', **extra_kw)
class MyTask(SingleClassificationTask):
...
'''
def _wrap(cls):
entry = (cls, rel_path, kw) if kw else (cls, rel_path)
REGISTRY[name] = entry
return cls
return _wrap
def _sentence_to_text_field(sent: Sequence[str], indexers: Any):
''' Helper function to map a sequence of tokens into a sequence of
AllenNLP Tokens, then wrap in a TextField with the given indexers '''
return TextField(list(map(Token, sent)), token_indexers=indexers)
def _atomic_tokenize(sent: str, atomic_tok: str, nonatomic_toks: List[str], max_seq_len: int):
''' Replace tokens that will be split by tokenizer with a
placeholder token. Tokenize, and then substitute the placeholder
with the *first* nonatomic token in the list. '''
for nonatomic_tok in nonatomic_toks:
sent = sent.replace(nonatomic_tok, atomic_tok)
sent = process_sentence(sent, max_seq_len)
sent = [nonatomic_toks[0] if t == atomic_tok else t for t in sent]
return sent
def process_single_pair_task_split(split, indexers, is_pair=True, classification=True):
'''
Convert a dataset of sentences into padded sequences of indices. Shared
across several classes.
Args:
- split (list[list[str]]): list of inputs (possibly pair) and outputs
- pair_input (int)
- tok2idx (dict)
Returns:
- instances (list[Instance]): a list of AllenNLP Instances with fields
'''
def _make_instance(input1, input2, labels, idx):
d = {}
d["input1"] = _sentence_to_text_field(input1, indexers)
d['sent1_str'] = MetadataField(" ".join(input1[1:-1]))
if input2:
d["input2"] = _sentence_to_text_field(input2, indexers)
d['sent2_str'] = MetadataField(" ".join(input2[1:-1]))
if classification:
d["labels"] = LabelField(labels, label_namespace="labels",
skip_indexing=True)
else:
d["labels"] = NumericField(labels)
d["idx"] = LabelField(idx, label_namespace="idxs",
skip_indexing=True)
return Instance(d)
split = list(split)
if not is_pair: # dummy iterator for input2
split[1] = itertools.repeat(None)
if len(split) < 4: # counting iterator for idx
assert len(split) == 3
split.append(itertools.count())
# Map over columns: input2, (input2), labels, idx
instances = map(_make_instance, *split)
# return list(instances)
return instances # lazy iterator
class Task():
'''Generic class for a task
Methods and attributes:
- load_data: load dataset from a path and create splits
- truncate: truncate data to be at most some length
- get_metrics:
Outside the task:
- process: pad and indexify data given a mapping
- optimizer
'''
def __init__(self, name):
self.name = name
def load_data(self, path, max_seq_len):
''' Load data from path and create splits. '''
raise NotImplementedError
def truncate(self, max_seq_len, sos_tok, eos_tok):
''' Shorten sentences to max_seq_len and add sos and eos tokens. '''
raise NotImplementedError
def get_sentences(self) -> Iterable[Sequence[str]]:
''' Yield sentences, used to compute vocabulary. '''
yield from self.sentences
def count_examples(self, splits=['train', 'val', 'test']):
''' Count examples in the dataset. '''
self.example_counts = {}
for split in splits:
st = self.get_split_text(split)
count = self.get_num_examples(st)
self.example_counts[split] = count
@property
def tokenizer_name(self):
''' Get the name of the tokenizer used for this task.
Generally, this is just 'MosesTokenizer', but other tokenizations may
be needed in special cases such as when working with BPE-based models
such as the OpenAI transformer LM.
'''
return utils.TOKENIZER.__class__.__name__
@property
def n_train_examples(self):
return self.example_counts['train']
@property
def n_val_examples(self):
return self.example_counts['val']
def get_split_text(self, split: str):
''' Get split text, typically as list of columns.
Split should be one of 'train', 'val', or 'test'.
'''
return getattr(self, '%s_data_text' % split)
def get_num_examples(self, split_text):
''' Return number of examples in the result of get_split_text.
Subclass can override this if data is not stored in column format.
'''
return len(split_text[0])
def process_split(self, split, indexers) -> Iterable[Type[Instance]]:
''' Process split text into a list of AllenNLP Instances. '''
raise NotImplementedError
def get_metrics(self, reset: bool = False) -> Dict:
''' Get metrics specific to the task. '''
raise NotImplementedError
class ClassificationTask(Task):
''' General classification task '''
def __init__(self, name):
super().__init__(name)
class RegressionTask(Task):
''' General regression task '''
def __init__(self, name):
super().__init__(name)
class SingleClassificationTask(ClassificationTask):
''' Generic sentence pair classification '''
def __init__(self, name, n_classes):
super().__init__(name)
self.n_classes = n_classes
self.scorer1 = CategoricalAccuracy()
self.scorer2 = None
self.val_metric = "%s_accuracy" % self.name
self.val_metric_decreases = False
def truncate(self, max_seq_len, sos_tok="<SOS>", eos_tok="<EOS>"):
self.train_data_text = [truncate(self.train_data_text[0], max_seq_len,
sos_tok, eos_tok), self.train_data_text[1]]
self.val_data_text = [truncate(self.val_data_text[0], max_seq_len,
sos_tok, eos_tok), self.val_data_text[1]]
self.test_data_text = [truncate(self.test_data_text[0], max_seq_len,
sos_tok, eos_tok), self.test_data_text[1]]
def get_metrics(self, reset=False):
'''Get metrics specific to the task'''
acc = self.scorer1.get_metric(reset)
return {'accuracy': acc}
def process_split(self, split, indexers) -> Iterable[Type[Instance]]:
''' Process split text into a list of AllenNLP Instances. '''
return process_single_pair_task_split(split, indexers, is_pair=False)
class PairClassificationTask(ClassificationTask):
''' Generic sentence pair classification '''
def __init__(self, name, n_classes):
super().__init__(name)
self.n_classes = n_classes
self.scorer1 = CategoricalAccuracy()
self.scorer2 = None
self.val_metric = "%s_accuracy" % self.name
self.val_metric_decreases = False
def get_metrics(self, reset=False):
'''Get metrics specific to the task'''
acc = self.scorer1.get_metric(reset)
return {'accuracy': acc}
def process_split(self, split, indexers) -> Iterable[Type[Instance]]:
''' Process split text into a list of AllenNLP Instances. '''
return process_single_pair_task_split(split, indexers, is_pair=True)
# SRL CoNLL 2005, formulated as an edge-labeling task.
@register_task('edges-srl-conll2005', rel_path='edges/srl_conll2005',
label_file="labels.txt", files_by_split={
'train': "train.edges.json",
'val': "dev.edges.json",
'test': "test.wsj.edges.json",
}, is_symmetric=False)
# SRL CoNLL 2012 (OntoNotes), formulated as an edge-labeling task.
@register_task('edges-srl-conll2012', rel_path='edges/srl_conll2012',
label_file="labels.txt", files_by_split={
'train': "train.edges.json",
'val': "dev.edges.json",
'test': "test.edges.json",
}, is_symmetric=False)
# SPR1, as an edge-labeling task (multilabel).
@register_task('edges-spr1', rel_path='edges/spr1',
label_file="labels.txt", files_by_split={
'train': "spr1.train.json",
'val': "spr1.dev.json",
'test': "spr1.test.json",
}, is_symmetric=False)
# SPR2, as an edge-labeling task (multilabel).
@register_task('edges-spr2', rel_path='edges/spr2',
label_file="labels.txt", files_by_split={
'train': "train.edges.json",
'val': "dev.edges.json",
'test': "test.edges.json",
}, is_symmetric=False)
# Definite pronoun resolution. Two labels.
@register_task('edges-dpr', rel_path='edges/dpr',
label_file="labels.txt", files_by_split={
'train': "train.edges.json",
'val': "dev.edges.json",
'test': "test.edges.json",
}, is_symmetric=False)
# Coreference on OntoNotes corpus. Two labels.
@register_task('edges-coref-ontonotes', rel_path='edges/ontonotes-coref',
label_file="labels.txt", files_by_split={
'train': "train.edges.json",
'val': "dev.edges.json",
'test': "test.edges.json",
}, is_symmetric=False)
# Re-processed version of the above, via AllenNLP data loaders.
@register_task('edges-coref-ontonotes-conll',
rel_path='edges/ontonotes-coref-conll',
label_file="labels.txt", files_by_split={
'train': "coref_conll_ontonotes_en_train.json",
'val': "coref_conll_ontonotes_en_dev.json",
'test': "coref_conll_ontonotes_en_test.json",
}, is_symmetric=False)
# Entity type labeling on CoNLL 2003.
@register_task('edges-ner-conll2003', rel_path='edges/ner_conll2003',
label_file="labels.txt", files_by_split={
'train': "CoNLL-2003_train.json",
'val': "CoNLL-2003_dev.json",
'test': "CoNLL-2003_test.json",
}, single_sided=True)
# Entity type labeling on OntoNotes.
@register_task('edges-ner-ontonotes',
rel_path='edges/ontonotes-ner',
label_file="labels.txt", files_by_split={
'train': "ner_ontonotes_en_train.json",
'val': "ner_ontonotes_en_dev.json",
'test': "ner_ontonotes_en_test.json",
}, single_sided=True)
# Dependency edge labeling on UD treebank (GUM). Use 'ewt' version instead.
@register_task('edges-dep-labeling', rel_path='edges/dep',
label_file="labels.txt", files_by_split={
'train': "train.json",
'val': "dev.json",
'test': "test.json",
}, is_symmetric=False)
# Dependency edge labeling on English Web Treebank (UD).
@register_task('edges-dep-labeling-ewt', rel_path='edges/dep_ewt',
label_file="labels.txt", files_by_split={
'train': "train.edges.json",
'val': "dev.edges.json",
'test': "test.edges.json",
}, is_symmetric=False)
# PTB constituency membership / labeling.
@register_task('edges-constituent-ptb', rel_path='edges/ptb-membership',
label_file="labels.txt", files_by_split={
'train': "ptb_train.json",
'val': "ptb_dev.json",
'test': "ptb_test.json",
}, single_sided=True)
# Constituency membership / labeling on OntoNotes.
@register_task('edges-constituent-ontonotes',
rel_path='edges/ontonotes-constituents',
label_file="labels.txt", files_by_split={
'train': "consts_ontonotes_en_train.json",
'val': "consts_ontonotes_en_dev.json",
'test': "consts_ontonotes_en_test.json",
}, single_sided=True)
@register_task('edges-pos-ontonotes',
rel_path='edges/ontonotes-constituents',
label_file="labels.pos.txt", files_by_split={
'train': "consts_ontonotes_en_train.pos.json",
'val': "consts_ontonotes_en_dev.pos.json",
'test': "consts_ontonotes_en_test.pos.json",
}, single_sided=True)
@register_task('edges-nonterminal-ontonotes',
rel_path='edges/ontonotes-constituents',
label_file="labels.nonterminal.txt", files_by_split={
'train': "consts_ontonotes_en_train.nonterminal.json",
'val': "consts_ontonotes_en_dev.nonterminal.json",
'test': "consts_ontonotes_en_test.nonterminal.json",
}, single_sided=True)
# CCG tagging (tokens only).
@register_task('edges-ccg-tag', rel_path='edges/ccg_tag',
label_file="labels.txt", files_by_split={
'train': "ccg.tag.train.json",
'val': "ccg.tag.dev.json",
'test': "ccg.tag.test.json",
}, single_sided=True)
# CCG parsing (constituent labeling).
@register_task('edges-ccg-parse', rel_path='edges/ccg_parse',
label_file="labels.txt", files_by_split={
'train': "ccg.parse.train.json",
'val': "ccg.parse.dev.json",
'test': "ccg.parse.test.json",
}, single_sided=True)
class EdgeProbingTask(Task):
''' Generic class for fine-grained edge probing.
Acts as a classifier, but with multiple targets for each input text.
Targets are of the form (span1, span2, label), where span1 and span2 are
half-open token intervals [i, j).
Subclass this for each dataset, or use register_task with appropriate kw
args.
'''
@property
def _tokenizer_suffix(self):
''' Suffix to make sure we use the correct source files. '''
return ".retokenized." + self.tokenizer_name
def __init__(self, path: str, max_seq_len: int,
name: str,
label_file: str = None,
files_by_split: Dict[str, str] = None,
is_symmetric: bool = False,
single_sided: bool = False):
"""Construct an edge probing task.
path, max_seq_len, and name are passed by the code in preprocess.py;
remaining arguments should be provided by a subclass constructor or via
@register_task.
Args:
path: data directory
max_seq_len: maximum sequence length (currently ignored)
name: task name
label_file: relative path to labels file
files_by_split: split name ('train', 'val', 'test') mapped to
relative filenames (e.g. 'train': 'train.json')
is_symmetric: if true, span1 and span2 are assumed to be the same
type and share parameters. Otherwise, we learn a separate
projection layer and attention weight for each.
single_sided: if true, only use span1.
"""
super().__init__(name)
assert label_file is not None
assert files_by_split is not None
self._files_by_split = {
split: os.path.join(path, fname) + self._tokenizer_suffix
for split, fname in files_by_split.items()
}
self._iters_by_split = self.load_data()
self.max_seq_len = max_seq_len
self.is_symmetric = is_symmetric
self.single_sided = single_sided
label_file = os.path.join(path, label_file)
self.all_labels = list(utils.load_lines(label_file))
self.n_classes = len(self.all_labels)
# see add_task_label_namespace in preprocess.py
self._label_namespace = self.name + "_labels"
# Scorers
# self.acc_scorer = CategoricalAccuracy() # multiclass accuracy
self.mcc_scorer = FastMatthews()
self.acc_scorer = BooleanAccuracy() # binary accuracy
self.f1_scorer = F1Measure(positive_label=1) # binary F1 overall
self.val_metric = "%s_f1" % self.name # TODO: switch to MCC?
self.val_metric_decreases = False
def _stream_records(self, filename):
skip_ctr = 0
total_ctr = 0
for record in utils.load_json_data(filename):
total_ctr += 1
# Skip records with empty targets.
# TODO(ian): don't do this if generating negatives!
if not record.get('targets', None):
skip_ctr += 1
continue
yield record
log.info("Read=%d, Skip=%d, Total=%d from %s",
total_ctr - skip_ctr, skip_ctr, total_ctr,
filename)
@staticmethod
def merge_preds(record: Dict, preds: Dict) -> Dict:
""" Merge predictions into record, in-place.
List-valued predictions should align to targets,
and are attached to the corresponding target entry.
Non-list predictions are attached to the top-level record.
"""
record['preds'] = {}
for target in record['targets']:
target['preds'] = {}
for key, val in preds.items():
if isinstance(val, list):
assert len(val) == len(record['targets'])
for i, target in enumerate(record['targets']):
target['preds'][key] = val[i]
else:
# non-list predictions, attach to top-level preds
record['preds'][key] = val
return record
def load_data(self):
iters_by_split = collections.OrderedDict()
for split, filename in self._files_by_split.items():
# # Lazy-load using RepeatableIterator.
# loader = functools.partial(utils.load_json_data,
# filename=filename)
# iter = serialize.RepeatableIterator(loader)
iter = list(self._stream_records(filename))
iters_by_split[split] = iter
return iters_by_split
def get_split_text(self, split: str):
''' Get split text as iterable of records.
Split should be one of 'train', 'val', or 'test'.
'''
return self._iters_by_split[split]
def get_num_examples(self, split_text):
''' Return number of examples in the result of get_split_text.
Subclass can override this if data is not stored in column format.
'''
return len(split_text)
def _make_span_field(self, s, text_field, offset=1):
return SpanField(s[0] + offset, s[1] - 1 + offset, text_field)
def make_instance(self, record, idx, indexers) -> Type[Instance]:
"""Convert a single record to an AllenNLP Instance."""
tokens = record['text'].split() # already space-tokenized by Moses
tokens = [utils.SOS_TOK] + tokens + [utils.EOS_TOK]
text_field = _sentence_to_text_field(tokens, indexers)
d = {}
d["idx"] = MetadataField(idx)
d['input1'] = text_field
d['span1s'] = ListField([self._make_span_field(t['span1'], text_field, 1)
for t in record['targets']])
if not self.single_sided:
d['span2s'] = ListField([self._make_span_field(t['span2'], text_field, 1)
for t in record['targets']])
# Always use multilabel targets, so be sure each label is a list.
labels = [utils.wrap_singleton_string(t['label'])
for t in record['targets']]
d['labels'] = ListField([MultiLabelField(label_set,
label_namespace=self._label_namespace,
skip_indexing=False)
for label_set in labels])
return Instance(d)
def process_split(self, records, indexers) -> Iterable[Type[Instance]]:
''' Process split text into a list of AllenNLP Instances. '''
def _map_fn(r, idx): return self.make_instance(r, idx, indexers)
return map(_map_fn, records, itertools.count())
def get_all_labels(self) -> List[str]:
return self.all_labels
def get_sentences(self) -> Iterable[Sequence[str]]:
''' Yield sentences, used to compute vocabulary. '''
for split, iter in self._iters_by_split.items():
# Don't use test set for vocab building.
if split.startswith("test"):
continue
for record in iter:
yield record["text"].split()
def get_metrics(self, reset=False):
'''Get metrics specific to the task'''
metrics = {}
metrics['mcc'] = self.mcc_scorer.get_metric(reset)
metrics['acc'] = self.acc_scorer.get_metric(reset)
precision, recall, f1 = self.f1_scorer.get_metric(reset)
metrics['precision'] = precision
metrics['recall'] = recall
metrics['f1'] = f1
return metrics
class OpenAIEdgeProbingTask(EdgeProbingTask):
"""Version of EdgeProbingTask that loads BPE-tokenized data."""
@property
def tokenizer_name(self):
return "OpenAI.BPE"
# We need '-openai' versions of all edge probing tasks, which load the correct
# tokenization for that model. To avoid lots of boilerplate, add these to the
# registry at import time using the loop below.
for name in list(REGISTRY.keys()):
args = REGISTRY[name]
cls = args[0]
if (issubclass(cls, EdgeProbingTask)
and not issubclass(cls, OpenAIEdgeProbingTask)):
new_args = (OpenAIEdgeProbingTask, *args[1:])
new_name = name + "-openai"
REGISTRY[new_name] = new_args
class PairRegressionTask(RegressionTask):
''' Generic sentence pair classification '''
def __init__(self, name):
super().__init__(name)
self.n_classes = 1
self.scorer1 = Average() # for average MSE
self.scorer2 = None
self.val_metric = "%s_mse" % self.name
self.val_metric_decreases = True
def get_metrics(self, reset=False):
'''Get metrics specific to the task'''
mse = self.scorer1.get_metric(reset)
return {'mse': mse}
def process_split(self, split, indexers) -> Iterable[Type[Instance]]:
''' Process split text into a list of AllenNLP Instances. '''
return process_single_pair_task_split(split, indexers, is_pair=True,
classification=False)
class PairOrdinalRegressionTask(RegressionTask):
''' Generic sentence pair ordinal regression.
Currently just doing regression but added new class
in case we find a good way to implement ordinal regression with NN'''
def __init__(self, name):
super().__init__(name)
self.n_classes = 1
self.scorer1 = Average() # for average MSE
self.scorer2 = Correlation('spearman')
self.val_metric = "%s_1-mse" % self.name
self.val_metric_decreases = False
def get_metrics(self, reset=False):
mse = self.scorer1.get_metric(reset)
spearmanr = self.scorer2.get_metric(reset)
return {'1-mse': 1 - mse,
'mse': mse,
'spearmanr': spearmanr}
def process_split(self, split, indexers) -> Iterable[Type[Instance]]:
''' Process split text into a list of AllenNLP Instances. '''
return process_single_pair_task_split(split, indexers, is_pair=True,
classification=False)
class SequenceGenerationTask(Task):
''' Generic sentence generation task '''
def __init__(self, name):
super().__init__(name)
self.scorer1 = Average() # for average BLEU or something
self.scorer2 = None
self.val_metric = "%s_bleu" % self.name
self.val_metric_decreases = False
log.warning("BLEU scoring is turned off (current code in progress)."
"Please use outputed prediction files to score offline")
def get_metrics(self, reset=False):
'''Get metrics specific to the task'''
bleu = self.scorer1.get_metric(reset)
return {'bleu': bleu}
class RankingTask(Task):
''' Generic sentence ranking task, given some input '''
def __init__(self, name):
super().__init__(name)
class LanguageModelingTask(SequenceGenerationTask):
"""Generic language modeling task
See base class: SequenceGenerationTask
Attributes:
max_seq_len: (int) maximum sequence length
min_seq_len: (int) minimum sequence length
target_indexer: (Indexer Obejct) Indexer used for target
files_by_split: (dict) files for three data split (train, val, test)
"""
def __init__(self, path, max_seq_len, name):
"""Init class
Args:
path: (str) path that the data files are stored
max_seq_len: (int) maximum length of one sequence
name: (str) task name
"""
super().__init__(name)
self.scorer1 = Average()
self.scorer2 = None
self.val_metric = "%s_perplexity" % self.name
self.val_metric_decreases = True
self.max_seq_len = max_seq_len
self.min_seq_len = 0
self.target_indexer = {"words": SingleIdTokenIndexer(namespace="tokens")}
self.files_by_split = {'train': os.path.join(path, "train.txt"),
'val': os.path.join(path, "valid.txt"),
'test': os.path.join(path, "test.txt")}
def count_examples(self):
"""Computes number of samples
Assuming every line is one example.
"""
example_counts = {}
for split, split_path in self.files_by_split.items():
example_counts[split] = sum(1 for line in open(split_path))
self.example_counts = example_counts
def get_metrics(self, reset=False):
"""Get metrics specific to the task
Args:
reset: (boolean) reset any accumulators or internal state
"""
nll = self.scorer1.get_metric(reset)
return {'perplexity': math.exp(nll)}
def load_data(self, path):
"""Loading data file and tokenizing the text
Args:
path: (str) data file path
"""
with open(path) as txt_fh:
for row in txt_fh:
toks = row.strip()
if not toks:
continue
yield process_sentence(toks, self.max_seq_len)
def process_split(self, split, indexers) -> Iterable[Type[Instance]]:
"""Process a language modeling split by indexing and creating fields.
Args:
split: (list) a single list of sentences
indexers: (Indexer object) indexer to index input words
"""
def _make_instance(sent):
''' Forward targs adds <s> as a target for input </s>
and bwd targs adds </s> as a target for input <s>
to avoid issues with needing to strip extra tokens
in the input for each direction '''
d = {}
d["input"] = _sentence_to_text_field(sent, indexers)
d["targs"] = _sentence_to_text_field(sent[1:] + [sent[0]], self.target_indexer)
d["targs_b"] = _sentence_to_text_field([sent[-1]] + sent[:-1], self.target_indexer)
return Instance(d)
for sent in split:
yield _make_instance(sent)
def get_split_text(self, split: str):
"""Get split text as iterable of records.
Args:
split: (str) should be one of 'train', 'val', or 'test'.
"""
return self.load_data(self.files_by_split[split])
def get_sentences(self) -> Iterable[Sequence[str]]:
"""Yield sentences, used to compute vocabulary.
"""
for split in self.files_by_split:
# Don't use test set for vocab building.
if split.startswith("test"):
continue
path = self.files_by_split[split]
for sent in self.load_data(path):
yield sent
class WikiTextLMTask(LanguageModelingTask):
""" Language modeling on a Wikitext dataset
See base class: LanguageModelingTask
"""
def __init__(self, path, max_seq_len, name="wiki"):
super().__init__(path, max_seq_len, name)
def load_data(self, path):
''' Rather than return a whole list of examples, stream them '''
nonatomics_toks = [UNK_TOK_ALLENNLP, '<unk>']
with open(path) as txt_fh:
for row in txt_fh:
toks = row.strip()
if not toks:
continue
# WikiText103 preprocesses unknowns as '<unk>'
# which gets tokenized as '@', '@', 'UNKNOWN', ...
# We replace to avoid that
sent = _atomic_tokenize(toks, UNK_TOK_ATOMIC, nonatomics_toks, self.max_seq_len)
# we also filtering out headers (artifact of the data)
# which are processed to have multiple = signs
if sent.count("=") >= 2 or len(toks) < self.min_seq_len + 2:
continue
yield sent
@register_task('wiki103', rel_path='WikiText103/')
class WikiText103LMTask(WikiTextLMTask):
"""Language modeling task on Wikitext 103
See base class: WikiTextLMTask
"""
def __init__(self, path, max_seq_len, name="wiki103"):
super().__init__(path, max_seq_len, name)
self.files_by_split = {'train': os.path.join(path, "train.sentences.txt"),
'val': os.path.join(path, "valid.sentences.txt"),
'test': os.path.join(path, "test.sentences.txt")}
@register_task('bwb', rel_path='BWB/')
class BWBLMTask(LanguageModelingTask):
"""Language modeling task on Billion Word Benchmark
See base class: LanguageModelingTask
"""
def __init__(self, path, max_seq_len, name="bwb"):
super().__init__(path, max_seq_len, name)
self.max_seq_len = max_seq_len
@register_task('sst', rel_path='SST-2/')
class SSTTask(SingleClassificationTask):
''' Task class for Stanford Sentiment Treebank. '''
def __init__(self, path, max_seq_len, name="sst"):
''' '''
super(SSTTask, self).__init__(name, 2)
self.load_data(path, max_seq_len)
self.sentences = self.train_data_text[0] + self.val_data_text[0]
def load_data(self, path, max_seq_len):
''' Load data '''
tr_data = load_tsv(os.path.join(path, 'train.tsv'), max_seq_len,
s1_idx=0, s2_idx=None, targ_idx=1, skip_rows=1)
val_data = load_tsv(os.path.join(path, 'dev.tsv'), max_seq_len,
s1_idx=0, s2_idx=None, targ_idx=1, skip_rows=1)
te_data = load_tsv(os.path.join(path, 'test.tsv'), max_seq_len,
s1_idx=1, s2_idx=None, targ_idx=None, idx_idx=0, skip_rows=1)
self.train_data_text = tr_data
self.val_data_text = val_data
self.test_data_text = te_data
log.info("\tFinished loading SST data.")
@register_task('reddit', rel_path='Reddit_2008/')
@register_task('reddit_dummy', rel_path='Reddit_2008_TestSample/')
@register_task('reddit_3.4G', rel_path='Reddit_3.4G/')
@register_task('reddit_13G', rel_path='Reddit_13G/')
@register_task('reddit_softmax', rel_path='Reddit_2008/')
class RedditTask(RankingTask):
''' Task class for Reddit data. '''
def __init__(self, path, max_seq_len, name="reddit"):
''' '''
super().__init__(name)
self.scorer1 = Average() # CategoricalAccuracy()
self.scorer2 = None
self.val_metric = "%s_accuracy" % self.name
self.val_metric_decreases = False
self.files_by_split = {split: os.path.join(path, "%s.csv" % split) for
split in ["train", "val", "test"]}
self.max_seq_len = max_seq_len
def get_split_text(self, split: str):
''' Get split text as iterable of records.
Split should be one of 'train', 'val', or 'test'.
'''
return self.load_data(self.files_by_split[split])
def load_data(self, path):
''' Load data '''
with open(path, 'r') as txt_fh:
for row in txt_fh:
row = row.strip().split('\t')
if len(row) < 4 or not row[2] or not row[3]:
continue
sent1 = process_sentence(row[2], self.max_seq_len)
sent2 = process_sentence(row[3], self.max_seq_len)
targ = 1
yield (sent1, sent2, targ)
def get_sentences(self) -> Iterable[Sequence[str]]:
''' Yield sentences, used to compute vocabulary. '''
for split in self.files_by_split:
# Don't use test set for vocab building.
if split.startswith("test"):
continue
path = self.files_by_split[split]
for sent1, sent2, _ in self.load_data(path):
yield sent1
yield sent2
def count_examples(self):
''' Compute here b/c we're streaming the sentences. '''
example_counts = {}
for split, split_path in self.files_by_split.items():
example_counts[split] = sum(1 for line in open(split_path))
self.example_counts = example_counts
def process_split(self, split, indexers) -> Iterable[Type[Instance]]:
''' Process split text into a list of AllenNLP Instances. '''
def _make_instance(input1, input2, labels):
d = {}
d["input1"] = _sentence_to_text_field(input1, indexers)
#d['sent1_str'] = MetadataField(" ".join(input1[1:-1]))
d["input2"] = _sentence_to_text_field(input2, indexers)
#d['sent2_str'] = MetadataField(" ".join(input2[1:-1]))
d["labels"] = LabelField(labels, label_namespace="labels",
skip_indexing=True)
return Instance(d)
for sent1, sent2, trg in split:
yield _make_instance(sent1, sent2, trg)
def get_metrics(self, reset=False):
'''Get metrics specific to the task'''
acc = self.scorer1.get_metric(reset)
return {'accuracy': acc}
@register_task('reddit_pair_classif', rel_path='Reddit_2008/')
@register_task('reddit_pair_classif_dummy', rel_path='Reddit_2008_TestSample/')
@register_task('reddit_pair_classif_3.4G', rel_path='Reddit_3.4G/')
class RedditPairClassificationTask(PairClassificationTask):
''' Task class for Reddit data. '''
def __init__(self, path, max_seq_len, name="reddit_PairClassi"):
''' '''
super().__init__(name, 2)
self.scorer2 = None
self.val_metric = "%s_accuracy" % self.name
self.val_metric_decreases = False
self.files_by_split = {split: os.path.join(path, "%s.csv" % split) for
split in ["train", "val", "test"]}
self.max_seq_len = max_seq_len
def get_split_text(self, split: str):
''' Get split text as iterable of records.
Split should be one of 'train', 'val', or 'test'.
'''
return self.load_data(self.files_by_split[split])
def load_data(self, path):
''' Load data '''
with open(path, 'r') as txt_fh:
for row in txt_fh:
row = row.strip().split('\t')
if len(row) < 4 or not row[2] or not row[3]:
continue
sent1 = process_sentence(row[2], self.max_seq_len)
sent2 = process_sentence(row[3], self.max_seq_len)
targ = 1
yield (sent1, sent2, targ)
def get_sentences(self) -> Iterable[Sequence[str]]:
''' Yield sentences, used to compute vocabulary. '''
for split in self.files_by_split:
# Don't use test set for vocab building.
if split.startswith("test"):
continue
path = self.files_by_split[split]
for sent1, sent2, _ in self.load_data(path):
yield sent1
yield sent2
def count_examples(self):
''' Compute here b/c we're streaming the sentences. '''
example_counts = {}
for split, split_path in self.files_by_split.items():
example_counts[split] = sum(1 for line in open(split_path))
self.example_counts = example_counts
def process_split(self, split, indexers) -> Iterable[Type[Instance]]:
''' Process split text into a list of AllenNLP Instances. '''
def _make_instance(input1, input2, labels):
d = {}
d["input1"] = _sentence_to_text_field(input1, indexers)
#d['sent1_str'] = MetadataField(" ".join(input1[1:-1]))
d["input2"] = _sentence_to_text_field(input2, indexers)
#d['sent2_str'] = MetadataField(" ".join(input2[1:-1]))
d["labels"] = LabelField(labels, label_namespace="labels",
skip_indexing=True)
return Instance(d)
for sent1, sent2, trg in split:
yield _make_instance(sent1, sent2, trg)
def get_metrics(self, reset=False):
'''Get metrics specific to the task'''
acc = self.scorer1.get_metric(reset)
return {'accuracy': acc}
@register_task('mt_pair_classif', rel_path='wmt14_en_de_local/')
@register_task('mt_pair_classif_dummy', rel_path='wmt14_en_de_mini/')
class MTDataPairClassificationTask(RedditPairClassificationTask):
''' Task class for MT data pair classification using standard setup.
RedditPairClassificationTask and MTDataPairClassificationTask are same tasks with different data
'''
def __init__(self, path, max_seq_len, name="mt_data_PairClassi"):
''' '''
super().__init__(path, max_seq_len, name)
self.files_by_split = {split: os.path.join(path, "%s.txt" % split) for