-
Notifications
You must be signed in to change notification settings - Fork 245
/
language_model.py
1543 lines (1323 loc) · 66.8 KB
/
language_model.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
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors, The HuggingFace Inc. Team and deepset Team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" Acknowledgements: Many of the modeling parts here come from the great transformers repository: https://github.com/huggingface/transformers.
Thanks for the great work! """
from __future__ import absolute_import, division, print_function, unicode_literals
import json
import logging
import os
import io
from pathlib import Path
from collections import OrderedDict
from dotmap import DotMap
from tqdm import tqdm
import copy
import numpy as np
import torch
from torch import nn
logger = logging.getLogger(__name__)
from transformers.modeling_bert import BertModel, BertConfig
from transformers.modeling_roberta import RobertaModel, RobertaConfig
from transformers.modeling_xlnet import XLNetModel, XLNetConfig
from transformers.modeling_albert import AlbertModel, AlbertConfig
from transformers.modeling_xlm_roberta import XLMRobertaModel, XLMRobertaConfig
from transformers.modeling_distilbert import DistilBertModel, DistilBertConfig
from transformers.modeling_electra import ElectraModel, ElectraConfig
from transformers.modeling_camembert import CamembertModel, CamembertConfig
from transformers.modeling_auto import AutoModel
from transformers.modeling_utils import SequenceSummary
from transformers.tokenization_bert import load_vocab
import transformers
from farm.modeling import wordembedding_utils
from farm.modeling.wordembedding_utils import s3e_pooling
# These are the names of the attributes in various model configs which refer to the number of dimensions
# in the output vectors
OUTPUT_DIM_NAMES = ["dim", "hidden_size", "d_model"]
class LanguageModel(nn.Module):
"""
The parent class for any kind of model that can embed language into a semantic vector space. Practically
speaking, these models read in tokenized sentences and return vectors that capture the meaning of sentences
or of tokens.
"""
subclasses = {}
def __init_subclass__(cls, **kwargs):
""" This automatically keeps track of all available subclasses.
Enables generic load() or all specific LanguageModel implementation.
"""
super().__init_subclass__(**kwargs)
cls.subclasses[cls.__name__] = cls
def forward(self, input_ids, padding_mask, **kwargs):
raise NotImplementedError
@classmethod
def from_scratch(cls, model_type, vocab_size):
if model_type.lower() == "bert":
model = Bert
return model.from_scratch(vocab_size)
@classmethod
def load(cls, pretrained_model_name_or_path, n_added_tokens=0, language_model_class=None, **kwargs):
"""
Load a pretrained language model either by
1. specifying its name and downloading it
2. or pointing to the directory it is saved in.
Available remote models:
* bert-base-uncased
* bert-large-uncased
* bert-base-cased
* bert-large-cased
* bert-base-multilingual-uncased
* bert-base-multilingual-cased
* bert-base-chinese
* bert-base-german-cased
* roberta-base
* roberta-large
* xlnet-base-cased
* xlnet-large-cased
* xlm-roberta-base
* xlm-roberta-large
* albert-base-v2
* albert-large-v2
* distilbert-base-german-cased
* distilbert-base-multilingual-cased
* google/electra-small-discriminator
* google/electra-base-discriminator
* google/electra-large-discriminator
* facebook/dpr-question_encoder-single-nq-base
* facebook/dpr-ctx_encoder-single-nq-base
See all supported model variations here: https://huggingface.co/models
The appropriate language model class is inferred automatically from `pretrained_model_name_or_path`
or can be manually supplied via `language_model_class`.
:param pretrained_model_name_or_path: The path of the saved pretrained model or its name.
:type pretrained_model_name_or_path: str
:param language_model_class: (Optional) Name of the language model class to load (e.g. `Bert`)
:type language_model_class: str
"""
config_file = Path(pretrained_model_name_or_path) / "language_model_config.json"
if os.path.exists(config_file):
# it's a local directory in FARM format
config = json.load(open(config_file))
language_model = cls.subclasses[config["name"]].load(pretrained_model_name_or_path)
else:
if language_model_class is None:
language_model_class = cls.get_language_model_class(pretrained_model_name_or_path)
if language_model_class:
language_model = cls.subclasses[language_model_class].load(pretrained_model_name_or_path, **kwargs)
else:
language_model = None
if not language_model:
raise Exception(
f"Model not found for {pretrained_model_name_or_path}. Either supply the local path for a saved "
f"model or one of bert/roberta/xlnet/albert/distilbert models that can be downloaded from remote. "
f"Ensure that the model class name can be inferred from the directory name when loading a "
f"Transformers' model. Here's a list of available models: "
f"https://farm.deepset.ai/api/modeling.html#farm.modeling.language_model.LanguageModel.load"
)
# resize embeddings in case of custom vocab
if n_added_tokens != 0:
# TODO verify for other models than BERT
model_emb_size = language_model.model.resize_token_embeddings(new_num_tokens=None).num_embeddings
vocab_size = model_emb_size + n_added_tokens
logger.info(
f"Resizing embedding layer of LM from {model_emb_size} to {vocab_size} to cope with custom vocab.")
language_model.model.resize_token_embeddings(vocab_size)
# verify
model_emb_size = language_model.model.resize_token_embeddings(new_num_tokens=None).num_embeddings
assert vocab_size == model_emb_size
return language_model
@classmethod
def get_language_model_class(cls, model_name_or_path):
# it's transformers format (either from model hub or local)
model_name_or_path = str(model_name_or_path)
if "xlm" in model_name_or_path and "roberta" in model_name_or_path:
language_model_class = 'XLMRoberta'
elif 'roberta' in model_name_or_path:
language_model_class = 'Roberta'
elif 'codebert' in model_name_or_path.lower():
if "mlm" in model_name_or_path.lower():
raise NotImplementedError("MLM part of codebert is currently not supported in FARM")
else:
language_model_class = 'Roberta'
elif 'camembert' in model_name_or_path or 'umberto' in model_name_or_path:
language_model_class = "Camembert"
elif 'albert' in model_name_or_path:
language_model_class = 'Albert'
elif 'distilbert' in model_name_or_path:
language_model_class = 'DistilBert'
elif 'bert' in model_name_or_path:
language_model_class = 'Bert'
elif 'xlnet' in model_name_or_path:
language_model_class = 'XLNet'
elif 'electra' in model_name_or_path:
language_model_class = 'Electra'
elif "word2vec" in model_name_or_path.lower() or "glove" in model_name_or_path.lower():
language_model_class = 'WordEmbedding_LM'
elif "minilm" in model_name_or_path.lower():
language_model_class = "Bert"
elif "dpr-question_encoder" in model_name_or_path.lower():
language_model_class = "DPRQuestionEncoder"
elif "dpr-ctx_encoder" in model_name_or_path.lower():
language_model_class = "DPRContextEncoder"
else:
language_model_class = None
return language_model_class
def get_output_dims(self):
config = self.model.config
for odn in OUTPUT_DIM_NAMES:
if odn in dir(config):
return getattr(config, odn)
else:
raise Exception("Could not infer the output dimensions of the language model")
def freeze(self, layers):
""" To be implemented"""
raise NotImplementedError()
def unfreeze(self):
""" To be implemented"""
raise NotImplementedError()
def save_config(self, save_dir):
save_filename = Path(save_dir) / "language_model_config.json"
with open(save_filename, "w") as file:
setattr(self.model.config, "name", self.__class__.__name__)
setattr(self.model.config, "language", self.language)
string = self.model.config.to_json_string()
file.write(string)
def save(self, save_dir):
"""
Save the model state_dict and its config file so that it can be loaded again.
:param save_dir: The directory in which the model should be saved.
:type save_dir: str
"""
# Save Weights
save_name = Path(save_dir) / "language_model.bin"
model_to_save = (
self.model.module if hasattr(self.model, "module") else self.model
) # Only save the model it-self
torch.save(model_to_save.state_dict(), save_name)
self.save_config(save_dir)
@classmethod
def _get_or_infer_language_from_name(cls, language, name):
if language is not None:
return language
else:
return cls._infer_language_from_name(name)
@classmethod
def _infer_language_from_name(cls, name):
known_languages = (
"german",
"english",
"chinese",
"indian",
"french",
"polish",
"spanish",
"multilingual",
)
matches = [lang for lang in known_languages if lang in name]
if "camembert" in name:
language = "french"
logger.info(
f"Automatically detected language from language model name: {language}"
)
elif "umberto" in name:
language = "italian"
logger.info(
f"Automatically detected language from language model name: {language}"
)
elif len(matches) == 0:
language = "english"
logger.warning(
"Could not automatically detect from language model name what language it is. \n"
"\t We guess it's an *ENGLISH* model ... \n"
"\t If not: Init the language model by supplying the 'language' param."
)
elif len(matches) > 1:
logger.warning(
"Could not automatically detect from language model name what language it is.\n"
f"\t Found multiple matches: {matches}\n"
"\t Please init the language model by manually supplying the 'language' as a parameter.\n"
f"\t Using {matches[0]} as language parameter for now.\n"
)
language = matches[0]
else:
language = matches[0]
logger.info(
f"Automatically detected language from language model name: {language}"
)
return language
def formatted_preds(self, logits, samples, ignore_first_token=True,
padding_mask=None, input_ids=None, **kwargs):
"""
Extracting vectors from language model (e.g. for extracting sentence embeddings).
Different pooling strategies and layers are available and will be determined from the object attributes
`extraction_layer` and `extraction_strategy`. Both should be set via the Inferencer:
Example: Inferencer(extraction_strategy='cls_token', extraction_layer=-1)
:param logits: Tuple of (sequence_output, pooled_output) from the language model.
Sequence_output: one vector per token, pooled_output: one vector for whole sequence
:param samples: For each item in logits we need additional meta information to format the prediction (e.g. input text).
This is created by the Processor and passed in here from the Inferencer.
:param ignore_first_token: Whether to include the first token for pooling operations (e.g. reduce_mean).
Many models have here a special token like [CLS] that you don't want to include into your average of token embeddings.
:param padding_mask: Mask for the padding tokens. Those will also not be included in the pooling operations to prevent a bias by the number of padding tokens.
:param input_ids: ids of the tokens in the vocab
:param kwargs: kwargs
:return: list of dicts containing preds, e.g. [{"context": "some text", "vec": [-0.01, 0.5 ...]}]
"""
if not hasattr(self, "extraction_layer") or not hasattr(self, "extraction_strategy"):
raise ValueError("`extraction_layer` or `extraction_strategy` not specified for LM. "
"Make sure to set both, e.g. via Inferencer(extraction_strategy='cls_token', extraction_layer=-1)`")
# unpack the tuple from LM forward pass
sequence_output = logits[0][0]
pooled_output = logits[0][1]
# aggregate vectors
if self.extraction_strategy == "pooled":
if self.extraction_layer != -1:
raise ValueError(f"Pooled output only works for the last layer, but got extraction_layer = {self.extraction_layer}. Please set `extraction_layer=-1`.)")
vecs = pooled_output.cpu().numpy()
elif self.extraction_strategy == "per_token":
vecs = sequence_output.cpu().numpy()
elif self.extraction_strategy == "reduce_mean":
vecs = self._pool_tokens(sequence_output, padding_mask, self.extraction_strategy, ignore_first_token=ignore_first_token)
elif self.extraction_strategy == "reduce_max":
vecs = self._pool_tokens(sequence_output, padding_mask, self.extraction_strategy, ignore_first_token=ignore_first_token)
elif self.extraction_strategy == "cls_token":
vecs = sequence_output[:, 0, :].cpu().numpy()
elif self.extraction_strategy == "s3e":
vecs = self._pool_tokens(sequence_output, padding_mask, self.extraction_strategy,
ignore_first_token=ignore_first_token,
input_ids=input_ids, s3e_stats=self.s3e_stats)
else:
raise NotImplementedError
preds = []
for vec, sample in zip(vecs, samples):
pred = {}
pred["context"] = sample.tokenized["tokens"]
pred["vec"] = vec
preds.append(pred)
return preds
def _pool_tokens(self, sequence_output, padding_mask, strategy, ignore_first_token, input_ids=None, s3e_stats=None):
token_vecs = sequence_output.cpu().numpy()
# we only take the aggregated value of non-padding tokens
padding_mask = padding_mask.cpu().numpy()
ignore_mask_2d = padding_mask == 0
# sometimes we want to exclude the CLS token as well from our aggregation operation
if ignore_first_token:
ignore_mask_2d[:, 0] = True
ignore_mask_3d = np.zeros(token_vecs.shape, dtype=bool)
ignore_mask_3d[:, :, :] = ignore_mask_2d[:, :, np.newaxis]
if strategy == "reduce_max":
pooled_vecs = np.ma.array(data=token_vecs, mask=ignore_mask_3d).max(axis=1).data
if strategy == "reduce_mean":
pooled_vecs = np.ma.array(data=token_vecs, mask=ignore_mask_3d).mean(axis=1).data
if strategy == "s3e":
input_ids = input_ids.cpu().numpy()
pooled_vecs = s3e_pooling(token_embs=token_vecs,
token_ids=input_ids,
token_weights=s3e_stats["token_weights"],
centroids=s3e_stats["centroids"],
token_to_cluster=s3e_stats["token_to_cluster"],
svd_components=s3e_stats.get("svd_components", None),
mask=padding_mask == 0)
return pooled_vecs
class Bert(LanguageModel):
"""
A BERT model that wraps HuggingFace's implementation
(https://github.com/huggingface/transformers) to fit the LanguageModel class.
Paper: https://arxiv.org/abs/1810.04805
"""
def __init__(self):
super(Bert, self).__init__()
self.model = None
self.name = "bert"
@classmethod
def from_scratch(cls, vocab_size, name="bert", language="en"):
bert = cls()
bert.name = name
bert.language = language
config = BertConfig(vocab_size=vocab_size)
bert.model = BertModel(config)
return bert
@classmethod
def load(cls, pretrained_model_name_or_path, language=None, **kwargs):
"""
Load a pretrained model by supplying
* the name of a remote model on s3 ("bert-base-cased" ...)
* OR a local path of a model trained via transformers ("some_dir/huggingface_model")
* OR a local path of a model trained via FARM ("some_dir/farm_model")
:param pretrained_model_name_or_path: The path of the saved pretrained model or its name.
:type pretrained_model_name_or_path: str
"""
bert = cls()
if "farm_lm_name" in kwargs:
bert.name = kwargs["farm_lm_name"]
else:
bert.name = pretrained_model_name_or_path
# We need to differentiate between loading model using FARM format and Pytorch-Transformers format
farm_lm_config = Path(pretrained_model_name_or_path) / "language_model_config.json"
if os.path.exists(farm_lm_config):
# FARM style
bert_config = BertConfig.from_pretrained(farm_lm_config)
farm_lm_model = Path(pretrained_model_name_or_path) / "language_model.bin"
bert.model = BertModel.from_pretrained(farm_lm_model, config=bert_config, **kwargs)
bert.language = bert.model.config.language
else:
# Pytorch-transformer Style
bert.model = BertModel.from_pretrained(str(pretrained_model_name_or_path), **kwargs)
bert.language = cls._get_or_infer_language_from_name(language, pretrained_model_name_or_path)
return bert
def forward(
self,
input_ids,
segment_ids,
padding_mask,
**kwargs,
):
"""
Perform the forward pass of the BERT model.
:param input_ids: The ids of each token in the input sequence. Is a tensor of shape [batch_size, max_seq_len]
:type input_ids: torch.Tensor
:param segment_ids: The id of the segment. For example, in next sentence prediction, the tokens in the
first sentence are marked with 0 and those in the second are marked with 1.
It is a tensor of shape [batch_size, max_seq_len]
:type segment_ids: torch.Tensor
:param padding_mask: A mask that assigns a 1 to valid input tokens and 0 to padding tokens
of shape [batch_size, max_seq_len]
:return: Embeddings for each token in the input sequence.
"""
output_tuple = self.model(
input_ids,
token_type_ids=segment_ids,
attention_mask=padding_mask,
)
if self.model.encoder.config.output_hidden_states == True:
sequence_output, pooled_output, all_hidden_states = output_tuple[0], output_tuple[1], output_tuple[2]
return sequence_output, pooled_output, all_hidden_states
else:
sequence_output, pooled_output = output_tuple[0], output_tuple[1]
return sequence_output, pooled_output
def enable_hidden_states_output(self):
self.model.encoder.config.output_hidden_states = True
def disable_hidden_states_output(self):
self.model.encoder.config.output_hidden_states = False
class Albert(LanguageModel):
"""
An ALBERT model that wraps the HuggingFace's implementation
(https://github.com/huggingface/transformers) to fit the LanguageModel class.
"""
def __init__(self):
super(Albert, self).__init__()
self.model = None
self.name = "albert"
@classmethod
def load(cls, pretrained_model_name_or_path, language=None, **kwargs):
"""
Load a language model either by supplying
* the name of a remote model on s3 ("albert-base" ...)
* or a local path of a model trained via transformers ("some_dir/huggingface_model")
* or a local path of a model trained via FARM ("some_dir/farm_model")
:param pretrained_model_name_or_path: name or path of a model
:param language: (Optional) Name of language the model was trained for (e.g. "german").
If not supplied, FARM will try to infer it from the model name.
:return: Language Model
"""
albert = cls()
if "farm_lm_name" in kwargs:
albert.name = kwargs["farm_lm_name"]
else:
albert.name = pretrained_model_name_or_path
# We need to differentiate between loading model using FARM format and Pytorch-Transformers format
farm_lm_config = Path(pretrained_model_name_or_path) / "language_model_config.json"
if os.path.exists(farm_lm_config):
# FARM style
config = AlbertConfig.from_pretrained(farm_lm_config)
farm_lm_model = Path(pretrained_model_name_or_path) / "language_model.bin"
albert.model = AlbertModel.from_pretrained(farm_lm_model, config=config, **kwargs)
albert.language = albert.model.config.language
else:
# Huggingface transformer Style
albert.model = AlbertModel.from_pretrained(str(pretrained_model_name_or_path), **kwargs)
albert.language = cls._get_or_infer_language_from_name(language, pretrained_model_name_or_path)
return albert
def forward(
self,
input_ids,
segment_ids,
padding_mask,
**kwargs,
):
"""
Perform the forward pass of the Albert model.
:param input_ids: The ids of each token in the input sequence. Is a tensor of shape [batch_size, max_seq_len]
:type input_ids: torch.Tensor
:param segment_ids: The id of the segment. For example, in next sentence prediction, the tokens in the
first sentence are marked with 0 and those in the second are marked with 1.
It is a tensor of shape [batch_size, max_seq_len]
:type segment_ids: torch.Tensor
:param padding_mask: A mask that assigns a 1 to valid input tokens and 0 to padding tokens
of shape [batch_size, max_seq_len]
:return: Embeddings for each token in the input sequence.
"""
output_tuple = self.model(
input_ids,
token_type_ids=segment_ids,
attention_mask=padding_mask,
)
if self.model.encoder.config.output_hidden_states == True:
sequence_output, pooled_output, all_hidden_states = output_tuple[0], output_tuple[1], output_tuple[2]
return sequence_output, pooled_output, all_hidden_states
else:
sequence_output, pooled_output = output_tuple[0], output_tuple[1]
return sequence_output, pooled_output
def enable_hidden_states_output(self):
self.model.encoder.config.output_hidden_states = True
def disable_hidden_states_output(self):
self.model.encoder.config.output_hidden_states = False
class Roberta(LanguageModel):
"""
A roberta model that wraps the HuggingFace's implementation
(https://github.com/huggingface/transformers) to fit the LanguageModel class.
Paper: https://arxiv.org/abs/1907.11692
"""
def __init__(self):
super(Roberta, self).__init__()
self.model = None
self.name = "roberta"
@classmethod
def load(cls, pretrained_model_name_or_path, language=None, **kwargs):
"""
Load a language model either by supplying
* the name of a remote model on s3 ("roberta-base" ...)
* or a local path of a model trained via transformers ("some_dir/huggingface_model")
* or a local path of a model trained via FARM ("some_dir/farm_model")
:param pretrained_model_name_or_path: name or path of a model
:param language: (Optional) Name of language the model was trained for (e.g. "german").
If not supplied, FARM will try to infer it from the model name.
:return: Language Model
"""
roberta = cls()
if "farm_lm_name" in kwargs:
roberta.name = kwargs["farm_lm_name"]
else:
roberta.name = pretrained_model_name_or_path
# We need to differentiate between loading model using FARM format and Pytorch-Transformers format
farm_lm_config = Path(pretrained_model_name_or_path) / "language_model_config.json"
if os.path.exists(farm_lm_config):
# FARM style
config = RobertaConfig.from_pretrained(farm_lm_config)
farm_lm_model = Path(pretrained_model_name_or_path) / "language_model.bin"
roberta.model = RobertaModel.from_pretrained(farm_lm_model, config=config, **kwargs)
roberta.language = roberta.model.config.language
else:
# Huggingface transformer Style
roberta.model = RobertaModel.from_pretrained(str(pretrained_model_name_or_path), **kwargs)
roberta.language = cls._get_or_infer_language_from_name(language, pretrained_model_name_or_path)
return roberta
def forward(
self,
input_ids,
segment_ids,
padding_mask,
**kwargs,
):
"""
Perform the forward pass of the Roberta model.
:param input_ids: The ids of each token in the input sequence. Is a tensor of shape [batch_size, max_seq_len]
:type input_ids: torch.Tensor
:param segment_ids: The id of the segment. For example, in next sentence prediction, the tokens in the
first sentence are marked with 0 and those in the second are marked with 1.
It is a tensor of shape [batch_size, max_seq_len]
:type segment_ids: torch.Tensor
:param padding_mask: A mask that assigns a 1 to valid input tokens and 0 to padding tokens
of shape [batch_size, max_seq_len]
:return: Embeddings for each token in the input sequence.
"""
output_tuple = self.model(
input_ids,
token_type_ids=segment_ids,
attention_mask=padding_mask,
)
if self.model.encoder.config.output_hidden_states == True:
sequence_output, pooled_output, all_hidden_states = output_tuple[0], output_tuple[1], output_tuple[2]
return sequence_output, pooled_output, all_hidden_states
else:
sequence_output, pooled_output = output_tuple[0], output_tuple[1]
return sequence_output, pooled_output
def enable_hidden_states_output(self):
self.model.encoder.config.output_hidden_states = True
def disable_hidden_states_output(self):
self.model.encoder.config.output_hidden_states = False
class XLMRoberta(LanguageModel):
"""
A roberta model that wraps the HuggingFace's implementation
(https://github.com/huggingface/transformers) to fit the LanguageModel class.
Paper: https://arxiv.org/abs/1907.11692
"""
def __init__(self):
super(XLMRoberta, self).__init__()
self.model = None
self.name = "xlm_roberta"
@classmethod
def load(cls, pretrained_model_name_or_path, language=None, **kwargs):
"""
Load a language model either by supplying
* the name of a remote model on s3 ("xlm-roberta-base" ...)
* or a local path of a model trained via transformers ("some_dir/huggingface_model")
* or a local path of a model trained via FARM ("some_dir/farm_model")
:param pretrained_model_name_or_path: name or path of a model
:param language: (Optional) Name of language the model was trained for (e.g. "german").
If not supplied, FARM will try to infer it from the model name.
:return: Language Model
"""
xlm_roberta = cls()
if "farm_lm_name" in kwargs:
xlm_roberta.name = kwargs["farm_lm_name"]
else:
xlm_roberta.name = pretrained_model_name_or_path
# We need to differentiate between loading model using FARM format and Pytorch-Transformers format
farm_lm_config = Path(pretrained_model_name_or_path) / "language_model_config.json"
if os.path.exists(farm_lm_config):
# FARM style
config = XLMRobertaConfig.from_pretrained(farm_lm_config)
farm_lm_model = Path(pretrained_model_name_or_path) / "language_model.bin"
xlm_roberta.model = XLMRobertaModel.from_pretrained(farm_lm_model, config=config, **kwargs)
xlm_roberta.language = xlm_roberta.model.config.language
else:
# Huggingface transformer Style
xlm_roberta.model = XLMRobertaModel.from_pretrained(str(pretrained_model_name_or_path), **kwargs)
xlm_roberta.language = cls._get_or_infer_language_from_name(language, pretrained_model_name_or_path)
return xlm_roberta
def forward(
self,
input_ids,
segment_ids,
padding_mask,
**kwargs,
):
"""
Perform the forward pass of the XLMRoberta model.
:param input_ids: The ids of each token in the input sequence. Is a tensor of shape [batch_size, max_seq_len]
:type input_ids: torch.Tensor
:param segment_ids: The id of the segment. For example, in next sentence prediction, the tokens in the
first sentence are marked with 0 and those in the second are marked with 1.
It is a tensor of shape [batch_size, max_seq_len]
:type segment_ids: torch.Tensor
:param padding_mask: A mask that assigns a 1 to valid input tokens and 0 to padding tokens
of shape [batch_size, max_seq_len]
:return: Embeddings for each token in the input sequence.
"""
output_tuple = self.model(
input_ids,
token_type_ids=segment_ids,
attention_mask=padding_mask,
)
if self.model.encoder.config.output_hidden_states == True:
sequence_output, pooled_output, all_hidden_states = output_tuple[0], output_tuple[1], output_tuple[2]
return sequence_output, pooled_output, all_hidden_states
else:
sequence_output, pooled_output = output_tuple[0], output_tuple[1]
return sequence_output, pooled_output
def enable_hidden_states_output(self):
self.model.encoder.config.output_hidden_states = True
def disable_hidden_states_output(self):
self.model.encoder.config.output_hidden_states = False
class DistilBert(LanguageModel):
"""
A DistilBERT model that wraps HuggingFace's implementation
(https://github.com/huggingface/transformers) to fit the LanguageModel class.
NOTE:
- DistilBert doesn’t have token_type_ids, you don’t need to indicate which
token belongs to which segment. Just separate your segments with the separation
token tokenizer.sep_token (or [SEP])
- Unlike the other BERT variants, DistilBert does not output the
pooled_output. An additional pooler is initialized.
"""
def __init__(self):
super(DistilBert, self).__init__()
self.model = None
self.name = "distilbert"
self.pooler = None
@classmethod
def load(cls, pretrained_model_name_or_path, language=None, **kwargs):
"""
Load a pretrained model by supplying
* the name of a remote model on s3 ("distilbert-base-german-cased" ...)
* OR a local path of a model trained via transformers ("some_dir/huggingface_model")
* OR a local path of a model trained via FARM ("some_dir/farm_model")
:param pretrained_model_name_or_path: The path of the saved pretrained model or its name.
:type pretrained_model_name_or_path: str
"""
distilbert = cls()
if "farm_lm_name" in kwargs:
distilbert.name = kwargs["farm_lm_name"]
else:
distilbert.name = pretrained_model_name_or_path
# We need to differentiate between loading model using FARM format and Pytorch-Transformers format
farm_lm_config = Path(pretrained_model_name_or_path) / "language_model_config.json"
if os.path.exists(farm_lm_config):
# FARM style
config = DistilBertConfig.from_pretrained(farm_lm_config)
farm_lm_model = Path(pretrained_model_name_or_path) / "language_model.bin"
distilbert.model = DistilBertModel.from_pretrained(farm_lm_model, config=config, **kwargs)
distilbert.language = distilbert.model.config.language
else:
# Pytorch-transformer Style
distilbert.model = DistilBertModel.from_pretrained(str(pretrained_model_name_or_path), **kwargs)
distilbert.language = cls._get_or_infer_language_from_name(language, pretrained_model_name_or_path)
config = distilbert.model.config
# DistilBERT does not provide a pooled_output by default. Therefore, we need to initialize an extra pooler.
# The pooler takes the first hidden representation & feeds it to a dense layer of (hidden_dim x hidden_dim).
# We don't want a dropout in the end of the pooler, since we do that already in the adaptive model before we
# feed everything to the prediction head
config.summary_last_dropout = 0
config.summary_type = 'first'
config.summary_activation = 'tanh'
distilbert.pooler = SequenceSummary(config)
distilbert.pooler.apply(distilbert.model._init_weights)
return distilbert
def forward(
self,
input_ids,
padding_mask,
**kwargs,
):
"""
Perform the forward pass of the DistilBERT model.
:param input_ids: The ids of each token in the input sequence. Is a tensor of shape [batch_size, max_seq_len]
:type input_ids: torch.Tensor
:param padding_mask: A mask that assigns a 1 to valid input tokens and 0 to padding tokens
of shape [batch_size, max_seq_len]
:return: Embeddings for each token in the input sequence.
"""
output_tuple = self.model(
input_ids,
attention_mask=padding_mask,
)
# We need to manually aggregate that to get a pooled output (one vec per seq)
pooled_output = self.pooler(output_tuple[0])
if self.model.config.output_hidden_states == True:
sequence_output, all_hidden_states = output_tuple[0], output_tuple[1]
return sequence_output, pooled_output
else:
sequence_output = output_tuple[0]
return sequence_output, pooled_output
def enable_hidden_states_output(self):
self.model.config.output_hidden_states = True
def disable_hidden_states_output(self):
self.model.config.output_hidden_states = False
class XLNet(LanguageModel):
"""
A XLNet model that wraps the HuggingFace's implementation
(https://github.com/huggingface/transformers) to fit the LanguageModel class.
Paper: https://arxiv.org/abs/1906.08237
"""
def __init__(self):
super(XLNet, self).__init__()
self.model = None
self.name = "xlnet"
self.pooler = None
@classmethod
def load(cls, pretrained_model_name_or_path, language=None, **kwargs):
"""
Load a language model either by supplying
* the name of a remote model on s3 ("xlnet-base-cased" ...)
* or a local path of a model trained via transformers ("some_dir/huggingface_model")
* or a local path of a model trained via FARM ("some_dir/farm_model")
:param pretrained_model_name_or_path: name or path of a model
:param language: (Optional) Name of language the model was trained for (e.g. "german").
If not supplied, FARM will try to infer it from the model name.
:return: Language Model
"""
xlnet = cls()
if "farm_lm_name" in kwargs:
xlnet.name = kwargs["farm_lm_name"]
else:
xlnet.name = pretrained_model_name_or_path
# We need to differentiate between loading model using FARM format and Pytorch-Transformers format
farm_lm_config = Path(pretrained_model_name_or_path) / "language_model_config.json"
if os.path.exists(farm_lm_config):
# FARM style
config = XLNetConfig.from_pretrained(farm_lm_config)
farm_lm_model = Path(pretrained_model_name_or_path) / "language_model.bin"
xlnet.model = XLNetModel.from_pretrained(farm_lm_model, config=config, **kwargs)
xlnet.language = xlnet.model.config.language
else:
# Pytorch-transformer Style
xlnet.model = XLNetModel.from_pretrained(str(pretrained_model_name_or_path), **kwargs)
xlnet.language = cls._get_or_infer_language_from_name(language, pretrained_model_name_or_path)
config = xlnet.model.config
# XLNet does not provide a pooled_output by default. Therefore, we need to initialize an extra pooler.
# The pooler takes the last hidden representation & feeds it to a dense layer of (hidden_dim x hidden_dim).
# We don't want a dropout in the end of the pooler, since we do that already in the adaptive model before we
# feed everything to the prediction head
config.summary_last_dropout = 0
xlnet.pooler = SequenceSummary(config)
xlnet.pooler.apply(xlnet.model._init_weights)
return xlnet
def forward(
self,
input_ids,
segment_ids,
padding_mask,
**kwargs,
):
"""
Perform the forward pass of the XLNet model.
:param input_ids: The ids of each token in the input sequence. Is a tensor of shape [batch_size, max_seq_len]
:type input_ids: torch.Tensor
:param segment_ids: The id of the segment. For example, in next sentence prediction, the tokens in the
first sentence are marked with 0 and those in the second are marked with 1.
It is a tensor of shape [batch_size, max_seq_len]
:type segment_ids: torch.Tensor
:param padding_mask: A mask that assigns a 1 to valid input tokens and 0 to padding tokens
of shape [batch_size, max_seq_len]
:return: Embeddings for each token in the input sequence.
"""
# Note: XLNet has a couple of special input tensors for pretraining / text generation (perm_mask, target_mapping ...)
# We will need to implement them, if we wanna support LM adaptation
output_tuple = self.model(
input_ids,
token_type_ids=segment_ids,
attention_mask=padding_mask,
)
# XLNet also only returns the sequence_output (one vec per token)
# We need to manually aggregate that to get a pooled output (one vec per seq)
# TODO verify that this is really doing correct pooling
pooled_output = self.pooler(output_tuple[0])
if self.model.output_hidden_states == True:
sequence_output, all_hidden_states = output_tuple[0], output_tuple[1]
return sequence_output, pooled_output, all_hidden_states
else:
sequence_output = output_tuple[0]
return sequence_output, pooled_output
def enable_hidden_states_output(self):
self.model.output_hidden_states = True
def disable_hidden_states_output(self):
self.model.output_hidden_states = False
class EmbeddingConfig():
"""
Config for Word Embeddings Models.
Necessary to work with Bert and other LM style functionality
"""
def __init__(self,
name=None,
embeddings_filename=None,
vocab_filename=None,
vocab_size=None,
hidden_size=None,
language=None,
**kwargs):
"""
:param name: Name of config
:param embeddings_filename:
:param vocab_filename:
:param vocab_size:
:param hidden_size:
:param language:
:param kwargs:
"""
self.name = name
self.embeddings_filename = embeddings_filename
self.vocab_filename = vocab_filename
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.language = language
if len(kwargs) > 0:
logger.info(f"Passed unused params {str(kwargs)} to the EmbeddingConfig. Might not be a problem.")
def to_dict(self):
"""
Serializes this instance to a Python dictionary.
Returns:
:obj:`Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
"""
output = copy.deepcopy(self.__dict__)
if hasattr(self.__class__, "model_type"):
output["model_type"] = self.__class__.model_type
return output
def to_json_string(self):
"""
Serializes this instance to a JSON string.
Returns:
:obj:`string`: String containing all the attributes that make up this configuration instance in JSON format.
"""
return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n"
class EmbeddingModel():
"""
Embedding Model that combines
- Embeddings
- Config Object
- Vocab
Necessary to work with Bert and other LM style functionality
"""
def __init__(self,
embedding_file,
config_dict,
vocab_file):