-
Notifications
You must be signed in to change notification settings - Fork 248
/
Copy pathprocessor.py
3084 lines (2731 loc) · 144 KB
/
processor.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
import abc
import inspect
import json
import logging
import os
import random
from abc import ABC
from inspect import signature
from pathlib import Path
from random import randint
import numpy as np
from numpy.random import random as random_float
from sklearn.preprocessing import StandardScaler
from tokenizers import Encoding
from tokenizers.pre_tokenizers import WhitespaceSplit
from transformers import AutoConfig
from farm.data_handler.dataset import convert_features_to_dataset
from farm.data_handler.input_features import sample_to_features_text
from farm.data_handler.nq_utils import (
sample_to_features_qa_Natural_Questions,
create_samples_qa_Natural_Question,
convert_qa_input_dict,
)
from farm.data_handler.samples import (
Sample,
SampleBasket,
get_passage_offsets,
offset_to_token_idx_vecorized
)
from farm.data_handler.utils import (
expand_labels,
read_tsv,
read_tsv_sentence_pair,
read_docs_from_txt,
read_ner_file,
read_squad_file,
read_jsonl,
read_dpr_json,
is_json,
get_sentence_pair,
split_with_metadata,
)
from farm.modeling.tokenization import (
Tokenizer,
tokenize_with_metadata,
truncate_sequences,
tokenize_batch_question_answering,
_get_start_of_word
)
from farm.utils import MLFlowLogger as MlLogger
from farm.utils import try_get
ID_NAMES = ["example_id", "external_id", "doc_id", "id"]
logger = logging.getLogger(__name__)
class Processor(ABC):
"""
Is used to generate PyTorch Datasets from input data. An implementation of this abstract class should be created
for each new data source.
Implement the abstract methods: file_to_dicts(), _dict_to_samples(), _sample_to_features()
to be compatible with your data format
"""
subclasses = {}
def __init__(
self,
tokenizer,
max_seq_len,
train_filename,
dev_filename,
test_filename,
dev_split,
data_dir,
tasks={},
proxies=None,
multithreading_rust=True,
):
"""
:param tokenizer: Used to split a sentence (str) into tokens.
:param max_seq_len: Samples are truncated after this many tokens.
:type max_seq_len: int
:param train_filename: The name of the file containing training data.
:type train_filename: str
:param dev_filename: The name of the file containing the dev data. If None and 0.0 < dev_split < 1.0 the dev set
will be a slice of the train set.
:type dev_filename: str or None
:param test_filename: The name of the file containing test data.
:type test_filename: str
:param dev_split: The proportion of the train set that will sliced. Only works if dev_filename is set to None
:type dev_split: float
:param data_dir: The directory in which the train, test and perhaps dev files can be found.
:type data_dir: str
:param tasks: Tasks for which the processor shall extract labels from the input data.
Usually this includes a single, default task, e.g. text classification.
In a multitask setting this includes multiple tasks, e.g. 2x text classification.
The task name will be used to connect with the related PredictionHead.
:type tasks: dict
:param proxies: proxy configuration to allow downloads of remote datasets.
Format as in "requests" library: https://2.python-requests.org//en/latest/user/advanced/#proxies
:type proxies: dict
:param multithreading_rust: Whether to allow multithreading in Rust, e.g. for FastTokenizers.
Note: Enabling multithreading in Rust AND multiprocessing in python might cause
deadlocks.
:type multithreading_rust: bool
"""
if not multithreading_rust:
os.environ["RAYON_RS_NUM_CPUS"] = "1"
self.tokenizer = tokenizer
self.max_seq_len = max_seq_len
self.tasks = tasks
self.proxies = proxies
# data sets
self.train_filename = train_filename
self.dev_filename = dev_filename
self.test_filename = test_filename
self.dev_split = dev_split
if data_dir:
self.data_dir = Path(data_dir)
else:
self.data_dir = None
self.baskets = []
self._log_params()
self.problematic_sample_ids = set()
def __init_subclass__(cls, **kwargs):
""" This automatically keeps track of all available subclasses.
Enables generic load() and load_from_dir() for all specific Processor implementation.
"""
super().__init_subclass__(**kwargs)
cls.subclasses[cls.__name__] = cls
@classmethod
def load(
cls,
processor_name,
data_dir,
tokenizer,
max_seq_len,
train_filename,
dev_filename,
test_filename,
dev_split,
**kwargs,
):
"""
Loads the class of processor specified by processor name.
:param processor_name: The class of processor to be loaded.
:type processor_name: str
:param data_dir: Directory where data files are located.
:type data_dir: str
:param tokenizer: A tokenizer object
:param max_seq_len: Sequences longer than this will be truncated.
:type max_seq_len: int
:param train_filename: The name of the file containing training data.
:type train_filename: str
:param dev_filename: The name of the file containing the dev data.
If None and 0.0 < dev_split < 1.0 the dev set
will be a slice of the train set.
:type dev_filename: str or None
:param test_filename: The name of the file containing test data.
:type test_filename: str
:param dev_split: The proportion of the train set that will sliced.
Only works if dev_filename is set to None
:type dev_split: float
:param kwargs: placeholder for passing generic parameters
:type kwargs: object
:return: An instance of the specified processor.
"""
sig = signature(cls.subclasses[processor_name])
unused_args = {k: v for k, v in kwargs.items() if k not in sig.parameters}
logger.debug(
f"Got more parameters than needed for loading {processor_name}: {unused_args}. "
f"Those won't be used!"
)
processor = cls.subclasses[processor_name](
data_dir=data_dir,
tokenizer=tokenizer,
max_seq_len=max_seq_len,
train_filename=train_filename,
dev_filename=dev_filename,
test_filename=test_filename,
dev_split=dev_split,
**kwargs,
)
return processor
@classmethod
def load_from_dir(cls, load_dir):
"""
Infers the specific type of Processor from a config file (e.g. GNADProcessor) and loads an instance of it.
:param load_dir: str, directory that contains a 'processor_config.json'
:return: An instance of a Processor Subclass (e.g. GNADProcessor)
"""
# read config
processor_config_file = Path(load_dir) / "processor_config.json"
config = json.load(open(processor_config_file))
config["inference"] = True
# init tokenizer
if "lower_case" in config.keys():
logger.warning("Loading tokenizer from deprecated FARM config. "
"If you used `custom_vocab` or `never_split_chars`, this won't work anymore.")
tokenizer = Tokenizer.load(load_dir, tokenizer_class=config["tokenizer"], do_lower_case=config["lower_case"])
else:
tokenizer = Tokenizer.load(load_dir, tokenizer_class=config["tokenizer"])
# we have to delete the tokenizer string from config, because we pass it as Object
del config["tokenizer"]
processor = cls.load(tokenizer=tokenizer, processor_name=config["processor"], **config)
for task_name, task in config["tasks"].items():
processor.add_task(name=task_name,
metric=task["metric"],
label_list=task["label_list"],
label_column_name=task["label_column_name"],
text_column_name=task.get("text_column_name", None),
task_type=task["task_type"])
if processor is None:
raise Exception
return processor
@classmethod
def convert_from_transformers(cls, tokenizer_name_or_path, task_type, max_seq_len, doc_stride,
revision=None, tokenizer_class=None, tokenizer_args=None, use_fast=True, **kwargs):
config = AutoConfig.from_pretrained(tokenizer_name_or_path, revision=revision, **kwargs)
tokenizer_args = tokenizer_args or {}
tokenizer = Tokenizer.load(tokenizer_name_or_path,
tokenizer_class=tokenizer_class,
use_fast=use_fast,
revision=revision,
**tokenizer_args,
**kwargs
)
# TODO infer task_type automatically from config (if possible)
if task_type == "question_answering":
processor = SquadProcessor(
tokenizer=tokenizer,
max_seq_len=max_seq_len,
label_list=["start_token", "end_token"],
metric="squad",
data_dir="data",
doc_stride=doc_stride
)
elif task_type == "embeddings":
processor = InferenceProcessor(tokenizer=tokenizer, max_seq_len=max_seq_len)
elif task_type == "text_classification":
label_list = list(config.id2label[id] for id in range(len(config.id2label)))
processor = TextClassificationProcessor(tokenizer=tokenizer,
max_seq_len=max_seq_len,
data_dir="data",
label_list=label_list,
label_column_name="label",
metric="acc",
quote_char='"',
)
elif task_type == "ner":
label_list = list(config.id2label.values())
processor = NERProcessor(
tokenizer=tokenizer, max_seq_len=max_seq_len, data_dir="data", metric="seq_f1",
label_list=label_list
)
else:
raise ValueError(f"`task_type` {task_type} is not supported yet. "
f"Valid options for arg `task_type`: 'question_answering', "
f"'embeddings', 'text_classification', 'ner'")
return processor
def save(self, save_dir):
"""
Saves the vocabulary to file and also creates a json file containing all the
information needed to load the same processor.
:param save_dir: Directory where the files are to be saved
:type save_dir: str
"""
os.makedirs(save_dir, exist_ok=True)
config = self.generate_config()
# save tokenizer incl. attributes
config["tokenizer"] = self.tokenizer.__class__.__name__
# Because the fast tokenizers expect a str and not Path
# always convert Path to str here.
self.tokenizer.save_pretrained(str(save_dir))
# save processor
config["processor"] = self.__class__.__name__
output_config_file = Path(save_dir) / "processor_config.json"
with open(output_config_file, "w") as file:
json.dump(config, file)
def generate_config(self):
"""
Generates config file from Class and instance attributes (only for sensible config parameters).
"""
config = {}
# self.__dict__ doesn't give parent class attributes
for key, value in inspect.getmembers(self):
if is_json(value) and key[0] != "_":
if issubclass(type(value), Path):
value = str(value)
config[key] = value
return config
def add_task(self, name, metric, label_list, label_column_name=None,
label_name=None, task_type=None, text_column_name=None):
if type(label_list) is not list:
raise ValueError(f"Argument `label_list` must be of type list. Got: f{type(label_list)}")
if label_name is None:
label_name = f"{name}_label"
label_tensor_name = label_name + "_ids"
self.tasks[name] = {
"label_list": label_list,
"metric": metric,
"label_tensor_name": label_tensor_name,
"label_name": label_name,
"label_column_name": label_column_name,
"text_column_name": text_column_name,
"task_type": task_type
}
@abc.abstractmethod
def file_to_dicts(self, file: str) -> [dict]:
raise NotImplementedError()
def _dict_to_samples(cls, dictionary: dict, all_dicts=None) -> [Sample]:
raise NotImplementedError()
def _sample_to_features(cls, sample: Sample) -> dict:
raise NotImplementedError()
def _dict_to_samples_and_features(self, dictionary: dict, all_dicts=None) -> [Sample]:
raise NotImplementedError()
def _init_samples_in_baskets(self):
all_dicts = [b.raw for b in self.baskets]
for basket in self.baskets:
try:
basket.samples = self._dict_to_samples(dictionary=basket.raw, all_dicts=all_dicts)
for num, sample in enumerate(basket.samples):
sample.id = f"{basket.id_internal}-{num}"
except Exception as e:
logger.error(f"Could not create sample(s) from this dict: \n {basket.raw}")
logger.error(f"Error message: {e}")
def _featurize_samples(self):
curr_problematic_sample_ids = []
for basket in self.baskets:
for sample in basket.samples:
try:
sample.features = self._sample_to_features(sample=sample)
except Exception as e:
curr_problematic_sample_ids.append(sample.id)
if curr_problematic_sample_ids:
self.problematic_sample_ids.update(curr_problematic_sample_ids)
@staticmethod
def log_problematic(problematic_sample_ids):
if problematic_sample_ids:
n_problematic = len(problematic_sample_ids)
problematic_id_str = ", ".join([str(i) for i in problematic_sample_ids])
logger.error(
f"Unable to convert {n_problematic} samples to features. Their ids are : {problematic_id_str}")
def _init_and_featurize_samples_in_baskets(self):
for basket in self.baskets:
all_dicts = [b.raw for b in self.baskets]
try:
basket.samples = self._dict_to_samples_and_features(dictionary=basket.raw,
all_dicts=all_dicts,
basket_id_internal=basket.id_internal)
for num, sample in enumerate(basket.samples):
sample.id = f"{basket.id_internal}-{num}"
except Exception as e:
logger.error(f"Could not create sample(s) from this dict: \n {basket.raw}")
logger.error(f"Error message: {e}")
@staticmethod
def _check_sample_features(basket):
"""Check if all samples in the basket has computed its features.
Args:
basket: the basket containing the samples
Returns:
True if all the samples in the basket has computed its features, False otherwise
"""
if len(basket.samples) == 0:
return False
for sample in basket.samples:
if sample.features is None:
return False
return True
def _create_dataset(self):
features_flat = []
basket_to_remove = []
for basket in self.baskets:
if self._check_sample_features(basket):
for sample in basket.samples:
features_flat.extend(sample.features)
else:
# remove the entire basket
basket_to_remove.append(basket)
if len(basket_to_remove) > 0:
for basket in basket_to_remove:
# if basket_to_remove is not empty remove the related baskets
self.baskets.remove(basket)
dataset, tensor_names = convert_features_to_dataset(features=features_flat)
return dataset, tensor_names
def dataset_from_dicts(self, dicts, indices=None, return_baskets = False):
"""
Contains all the functionality to turn a list of dict objects into a PyTorch Dataset and a
list of tensor names. This can be used for inference mode.
:param dicts: List of dictionaries where each contains the data of one input sample.
:type dicts: list of dicts
:return: a Pytorch dataset and a list of tensor names.
"""
# We need to add the index (coming from multiprocessing chunks) to have a unique basket ID
self.baskets = []
for id_internal, d in enumerate(dicts):
id_external = self._id_from_dict(d)
if indices:
id_internal = indices[id_internal]
self.baskets.append(SampleBasket(raw=d, id_external=id_external, id_internal=id_internal))
self._init_samples_in_baskets()
self._featurize_samples()
if indices:
if 0 in indices:
self._log_samples(1)
else:
self._log_samples(1)
dataset, tensor_names = self._create_dataset()
# This mode is for inference where we need to keep baskets
if return_baskets:
#TODO simplify
return dataset, tensor_names, self.problematic_sample_ids, self.baskets
# This mode is for training where we can free ram by removing baskets
else:
return dataset, tensor_names, self.problematic_sample_ids
def _log_samples(self, n_samples):
logger.info("*** Show {} random examples ***".format(n_samples))
for i in range(n_samples):
random_basket = random.choice(self.baskets)
random_sample = random.choice(random_basket.samples)
logger.info(random_sample)
def _log_params(self):
params = {
"processor": self.__class__.__name__,
"tokenizer": self.tokenizer.__class__.__name__,
}
names = ["max_seq_len", "dev_split"]
for name in names:
value = getattr(self, name)
params.update({name: str(value)})
MlLogger.log_params(params)
@staticmethod
def _id_from_dict(d):
ext_id = try_get(ID_NAMES, d)
if not ext_id and "qas" in d:
ext_id = try_get(ID_NAMES, d["qas"][0])
return ext_id
class TextClassificationProcessor(Processor):
"""
Used to handle the text classification datasets that come in tabular format (CSV, TSV, etc.)
"""
def __init__(
self,
tokenizer,
max_seq_len,
data_dir,
label_list=None,
metric=None,
train_filename="train.tsv",
dev_filename=None,
test_filename="test.tsv",
dev_split=0.1,
dev_stratification=False,
delimiter="\t",
quote_char="'",
skiprows=None,
label_column_name="label",
multilabel=False,
header=0,
proxies=None,
max_samples=None,
text_column_name="text",
**kwargs
):
"""
:param tokenizer: Used to split a sentence (str) into tokens.
:param max_seq_len: Samples are truncated after this many tokens.
:type max_seq_len: int
:param data_dir: The directory in which the train and dev files can be found.
If not available the dataset will be loaded automaticaly
if the last directory has the same name as a predefined dataset.
These predefined datasets are defined as the keys in the dict at
`farm.data_handler.utils.DOWNSTREAM_TASK_MAP <https://github.com/deepset-ai/FARM/blob/master/farm/data_handler/utils.py>`_.
:type data_dir: str
:param label_list: list of labels to predict (strings). For most cases this should be: ["start_token", "end_token"]
:type label_list: list
:param metric: name of metric that shall be used for evaluation, e.g. "acc" or "f1_macro".
Alternatively you can also supply a custom function, that takes preds and labels as args and returns a numerical value.
For using multiple metrics supply them as a list, e.g ["acc", my_custom_metric_fn].
:type metric: str, function, or list
:param train_filename: The name of the file containing training data.
:type train_filename: str
:param dev_filename: The name of the file containing the dev data. If None and 0.0 < dev_split < 1.0 the dev set
will be a slice of the train set.
:type dev_filename: str or None
:param test_filename: None
:type test_filename: str
:param dev_split: The proportion of the train set that will sliced. Only works if dev_filename is set to None
:type dev_split: float
:param dev_stratification: if True, create a class-stratified split for the dev set.
:type dev_stratification: bool
:param delimiter: Separator used in the input tsv / csv file
:type delimiter: str
:param quote_char: Character used for quoting strings in the input tsv/ csv file
:type quote_char: str
:param skiprows: number of rows to skip in the tsvs (e.g. for multirow headers)
:type skiprows: int
:param label_column_name: name of the column in the input csv/tsv that shall be used as training labels
:type label_column_name: str
:param multilabel: set to True for multilabel classification
:type multilabel: bool
:param header: which line to use as a header in the input csv/tsv
:type header: int
:param proxies: proxy configuration to allow downloads of remote datasets.
Format as in "requests" library: https://2.python-requests.org//en/latest/user/advanced/#proxies
:type proxies: dict
:param text_column_name: name of the column in the input csv/tsv that shall be used as training text
:type text_column_name: str
:param kwargs: placeholder for passing generic parameters
:type kwargs: object
"""
#TODO If an arg is misspelt, e.g. metrics, it will be swallowed silently by kwargs
# Custom processor attributes
self.delimiter = delimiter
self.quote_char = quote_char
self.skiprows = skiprows
self.header = header
self.max_samples = max_samples
self.dev_stratification = dev_stratification
logger.warning(f"Currently no support in Processor for returning problematic ids")
super(TextClassificationProcessor, self).__init__(
tokenizer=tokenizer,
max_seq_len=max_seq_len,
train_filename=train_filename,
dev_filename=dev_filename,
test_filename=test_filename,
dev_split=dev_split,
data_dir=data_dir,
tasks={},
proxies=proxies,
)
if metric and label_list:
if multilabel:
task_type = "multilabel_classification"
else:
task_type = "classification"
self.add_task(name="text_classification",
metric=metric,
label_list=label_list,
label_column_name=label_column_name,
text_column_name=text_column_name,
task_type=task_type)
else:
logger.info("Initialized processor without tasks. Supply `metric` and `label_list` to the constructor for "
"using the default task or add a custom task later via processor.add_task()")
def file_to_dicts(self, file: str) -> [dict]:
column_mapping = {}
for task in self.tasks.values():
column_mapping[task["label_column_name"]] = task["label_name"]
column_mapping[task["text_column_name"]] = "text"
dicts = read_tsv(
filename=file,
delimiter=self.delimiter,
skiprows=self.skiprows,
quotechar=self.quote_char,
rename_columns=column_mapping,
header=self.header,
proxies=self.proxies,
max_samples=self.max_samples
)
return dicts
def dataset_from_dicts(self, dicts, indices=None, return_baskets=False, debug=False):
self.baskets = []
# Tokenize in batches
texts = [x["text"] for x in dicts]
tokenized_batch = self.tokenizer.batch_encode_plus(
texts,
return_offsets_mapping=True,
return_special_tokens_mask=True,
return_token_type_ids=True,
return_attention_mask=True,
truncation=True,
max_length=self.max_seq_len,
padding="max_length"
)
input_ids_batch = tokenized_batch["input_ids"]
segment_ids_batch = tokenized_batch["token_type_ids"]
padding_masks_batch = tokenized_batch["attention_mask"]
tokens_batch = [x.tokens for x in tokenized_batch.encodings]
# From here we operate on a per sample basis
for dictionary, input_ids, segment_ids, padding_mask, tokens in zip(
dicts, input_ids_batch, segment_ids_batch, padding_masks_batch, tokens_batch
):
tokenized = {}
if debug:
tokenized["tokens"] = tokens
feat_dict = {"input_ids": input_ids,
"padding_mask": padding_mask,
"segment_ids": segment_ids}
# Create labels
# i.e. not inference
if not return_baskets:
label_dict = self.convert_labels(dictionary)
feat_dict.update(label_dict)
# Add Basket to self.baskets
curr_sample = Sample(id=None,
clear_text=dictionary,
tokenized=tokenized,
features=[feat_dict])
curr_basket = SampleBasket(id_internal=None,
raw=dictionary,
id_external=None,
samples=[curr_sample])
self.baskets.append(curr_basket)
if indices and 0 not in indices:
pass
else:
self._log_samples(1)
# TODO populate problematic ids
problematic_ids = set()
dataset, tensornames = self._create_dataset()
if return_baskets:
return dataset, tensornames, problematic_ids, self.baskets
else:
return dataset, tensornames, problematic_ids
def convert_labels(self, dictionary):
ret = {}
# Add labels for different tasks
for task_name, task in self.tasks.items():
label_name = task["label_name"]
label_raw = dictionary[label_name]
label_list = task["label_list"]
if task["task_type"] == "classification":
# id of label
label_ids = [label_list.index(label_raw)]
elif task["task_type"] == "multilabel_classification":
# multi-hot-format
label_ids = [0] * len(label_list)
for l in label_raw.split(","):
if l != "":
label_ids[label_list.index(l)] = 1
ret[task["label_tensor_name"]] = label_ids
return ret
def _create_dataset(self):
# TODO this is the proposed new version to replace the mother function
features_flat = []
basket_to_remove = []
for basket in self.baskets:
if self._check_sample_features(basket):
for sample in basket.samples:
features_flat.extend(sample.features)
else:
# remove the entire basket
basket_to_remove.append(basket)
dataset, tensor_names = convert_features_to_dataset(features=features_flat)
return dataset, tensor_names
class TextPairClassificationProcessor(TextClassificationProcessor):
"""
Used to handle text pair classification datasets (e.g. Answer Selection or Natural Inference) that come in
tsv format. The columns should be called text, text_b and label.
"""
def __init__(self, **kwargs):
super(TextPairClassificationProcessor, self).__init__(**kwargs)
def file_to_dicts(self, file: str) -> [dict]:
column_mapping = {}
for task in self.tasks.values():
column_mapping[task["label_column_name"]] = task["label_name"]
dicts = read_tsv_sentence_pair(
rename_columns=column_mapping,
filename=file,
delimiter=self.delimiter,
skiprows=self.skiprows,
proxies=self.proxies,
)
# during tokenization inside TextClassificationProcessor only the "text" field is tokenized
# To convert text pairs we combine text and text_b into a tuple, then the tokenizer takes care of
# adding separator tokens and correct segment IDs
for d in dicts:
d["text"] = (d["text"], d["text_b"])
return dicts
class RegressionProcessor(TextClassificationProcessor):
"""
Processor to handle a regression dataset in tab separated text + label,
It uses the text conversion functionality of a TextClassificationProcessor
but adds special label conversion (scaled float value as label)
"""
def __init__(
self,
tokenizer,
max_seq_len,
data_dir,
train_filename="train.tsv",
dev_filename=None,
test_filename="test.tsv",
dev_split=0.1,
delimiter="\t",
quote_char="'",
skiprows=None,
label_column_name="label",
label_name="regression_label",
scaler_mean=None,
scaler_scale=None,
proxies=None,
text_column_name="text",
**kwargs
):
"""
:param tokenizer: Used to split a sentence (str) into tokens.
:param max_seq_len: Samples are truncated after this many tokens.
:type max_seq_len: int
:param data_dir: The directory in which the train and dev files can be found.
If not available the dataset will be loaded automaticaly
if the last directory has the same name as a predefined dataset.
These predefined datasets are defined as the keys in the dict at
`farm.data_handler.utils.DOWNSTREAM_TASK_MAP <https://github.com/deepset-ai/FARM/blob/master/farm/data_handler/utils.py>`_.
:type data_dir: str
:param label_list: list of labels to predict (strings). For most cases this should be: ["start_token", "end_token"]
:type label_list: list
:param metric: name of metric that shall be used for evaluation, e.g. "acc" or "f1_macro".
Alternatively you can also supply a custom function, that takes preds and labels as args and returns a
numerical value. For using multiple metrics supply them as a list, e.g ["acc", my_custom_metric_fn].
:type metric: str, function, or list
:param train_filename: The name of the file containing training data.
:type train_filename: str
:param dev_filename: The name of the file containing the dev data. If None and 0.0 < dev_split < 1.0 the dev set
will be a slice of the train set.
:type dev_filename: str or None
:param test_filename: None
:type test_filename: str
:param dev_split: The proportion of the train set that will sliced. No devset is created if this is set to 0.0
Only used if dev_filename is set to None
:type dev_split: float
:param delimiter: Separator used in the input tsv / csv file
:type delimiter: str
:param quote_char: Character used for quoting strings in the input tsv/ csv file
:type quote_char: str
:param skiprows: number of rows to skip in the tsvs (e.g. for multirow headers)
:type skiprows: int
:param label_column_name: name of the column in the input csv/tsv that shall be used as training labels
:type label_column_name: str
:param label_name: name for the internal label variable in FARM (only needed to adjust in rare cases)
:type label_name: str
:param scaler_mean: Value to substract from the label for normalization
:type scaler_mean: float
:param scaler_scale: Value to divide the label by for normalization
:type scaler_scale: float
:param proxies: proxy configuration to allow downloads of remote datasets.
Format as in "requests" library: https://2.python-requests.org//en/latest/user/advanced/#proxies
:type proxies: dict
:param text_column_name: name of the column in the input csv/tsv that shall be used as training text
:type text_column_name: str
:param kwargs: placeholder for passing generic parameters
:type kwargs: object
"""
super(RegressionProcessor, self).__init__(
tokenizer=tokenizer,
max_seq_len=max_seq_len,
train_filename=train_filename,
dev_filename=dev_filename,
test_filename=test_filename,
dev_split=dev_split,
data_dir=data_dir,
proxies=proxies,
delimiter=delimiter,
quote_char=quote_char,
skiprows=skiprows,
)
# Note that label_list is being hijacked to store the scaling mean and scale
self.add_task(name="regression",
metric="mse",
label_list=[scaler_mean, scaler_scale],
label_column_name=label_column_name,
task_type="regression",
label_name=label_name,
text_column_name=text_column_name)
def file_to_dicts(self, file: str) -> [dict]:
column_mapping = {}
for task in self.tasks.values():
column_mapping[task["label_column_name"]] = task["label_name"]
column_mapping[task["text_column_name"]] = "text"
dicts = read_tsv(
rename_columns=column_mapping,
filename=file,
delimiter=self.delimiter,
skiprows=self.skiprows,
quotechar=self.quote_char,
proxies=self.proxies
)
self._set_label_scaling(dicts=dicts, file=file)
return dicts
def convert_labels(self, dictionary: dict):
# For regression the label should be scaled
ret = {}
for task_name, task in self.tasks.items():
label_name = task["label_name"]
label_raw = dictionary[label_name]
label_list = task["label_list"]
if task["task_type"] == "regression":
label = float(label_raw)
scaled_label = (label - label_list[0]) / label_list[1]
ret[task["label_tensor_name"]] = [scaled_label]
return ret
def _set_label_scaling(self, dicts, file):
# collect all labels and compute scaling stats
# for regression with Mean Squared Error loss we need to have labels centered around 0 with unit variance
train_labels = []
if self.train_filename in str(file):
for d in dicts:
train_labels.append(float(d[self.tasks["regression"]["label_name"]]))
scaler = StandardScaler()
scaler.fit(np.reshape(train_labels, (-1, 1)))
# add to label list in regression task
self.tasks["regression"]["label_list"] = [scaler.mean_.item(), scaler.scale_.item()]
class TextPairRegressionProcessor(RegressionProcessor):
"""
Used to handle text pair regression datasets that come in tsv format.
The columns should be called text, text_b and label.
"""
def __init__(self, **kwargs):
super(TextPairRegressionProcessor, self).__init__(**kwargs)
def file_to_dicts(self, file: str) -> [dict]:
column_mapping = {}
for task in self.tasks.values():
column_mapping[task["label_column_name"]] = task["label_name"]
dicts = read_tsv_sentence_pair(
rename_columns=column_mapping,
filename=file,
delimiter=self.delimiter,
skiprows=self.skiprows,
proxies=self.proxies,
)
self._set_label_scaling(dicts=dicts, file=file)
# during tokenization inside RegressionProcessor only the "text" field is tokenized
# To convert text pairs we combine text and text_b into a tuple, then the tokenizers takes care of
# adding separator tokens and correct segment IDs
for d in dicts:
d["text"] = (d["text"], d["text_b"])
return dicts
#########################################
# Processor for Basic Inference ####
#########################################
class InferenceProcessor(TextClassificationProcessor):
"""
Generic processor used at inference time:
- fast
- no labels
- pure encoding of text into pytorch dataset
- Doesn't read from file, but only consumes dictionaries (e.g. coming from API requests)
"""
def __init__(
self,
tokenizer,
max_seq_len,
**kwargs,
):
super(InferenceProcessor, self).__init__(
tokenizer=tokenizer,
max_seq_len=max_seq_len,
train_filename=None,
dev_filename=None,
test_filename=None,
dev_split=None,
data_dir=None,
tasks={},
)
@classmethod
def load_from_dir(cls, load_dir):
"""
Overwriting method from parent class to **always** load the InferenceProcessor instead of the specific class stored in the config.
:param load_dir: str, directory that contains a 'processor_config.json'
:return: An instance of an InferenceProcessor
"""
# read config
processor_config_file = Path(load_dir) / "processor_config.json"
config = json.load(open(processor_config_file))
# init tokenizer
tokenizer = Tokenizer.load(load_dir, tokenizer_class=config["tokenizer"])
# we have to delete the tokenizer string from config, because we pass it as Object
del config["tokenizer"]
processor = cls.load(tokenizer=tokenizer, processor_name="InferenceProcessor", **config)
for task_name, task in config["tasks"].items():
processor.add_task(name=task_name, metric=task["metric"], label_list=task["label_list"])
if processor is None:
raise Exception
return processor
def file_to_dicts(self, file: str) -> [dict]:
raise NotImplementedError
def convert_labels(self, dictionary: dict):
# For inference we do not need labels
ret = {}
return ret
def dataset_from_dicts(self, dicts, indices=None, return_baskets=False, debug=False):
"""
Function to convert input dictionaries containing text into a torch dataset.
For normal operation with Language Models it calls the superclass' TextClassification.dataset_from_dicts method.
For slow tokenizers, s3e or wordembedding tokenizers the function works on _dict_to_samples and _sample_to_features
"""
# TODO remove this sections once tokenizers work the same way for slow/fast and our special tokenizers
if not self.tokenizer.is_fast:
self.baskets = []
for d in dicts:
sample = self._dict_to_samples(dictionary=d)