-
Notifications
You must be signed in to change notification settings - Fork 46
/
embeddings.py
4694 lines (3870 loc) · 196 KB
/
embeddings.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 os
import re
import logging
from abc import abstractmethod
from collections import Counter
from pathlib import Path
from typing import List, Union, Dict
import gensim
import numpy as np
import torch
from bpemb import BPEmb
from deprecated import deprecated
from torch.nn import ParameterList, Parameter
import time
import pdb
from pytorch_transformers import (
RobertaTokenizer,
RobertaModel,
TransfoXLTokenizer,
TransfoXLModel,
OpenAIGPTModel,
OpenAIGPTTokenizer,
GPT2Model,
GPT2Tokenizer,
XLMTokenizer,
XLMModel,
PreTrainedTokenizer,
PreTrainedModel,
)
from transformers import XLNetTokenizer, T5Tokenizer, GPT2Tokenizer, AutoTokenizer, AutoConfig, AutoModel
from transformers import (
XLNetModel,
XLNetTokenizer,
BertTokenizer,
BertModel,
XLMRobertaModel,
XLMRobertaTokenizer,
)
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
import flair
from flair.data import Corpus
from .nn import LockedDropout, WordDropout
from .data import Dictionary, Token, Sentence
from .file_utils import cached_path, open_inside_zip
log = logging.getLogger("flair")
def rand_emb(embedding):
bias = np.sqrt(3.0 / embedding.size(0))
torch.nn.init.uniform_(embedding, -bias, bias)
return embedding
class Embeddings(torch.nn.Module):
"""Abstract base class for all embeddings. Every new type of embedding must implement these methods."""
@property
@abstractmethod
def embedding_length(self) -> int:
"""Returns the length of the embedding vector."""
pass
@property
@abstractmethod
def embedding_type(self) -> str:
pass
def embed(self, sentences: Union[Sentence, List[Sentence]]) -> List[Sentence]:
"""Add embeddings to all words in a list of sentences. If embeddings are already added, updates only if embeddings
are non-static."""
# if only one sentence is passed, convert to list of sentence
if type(sentences) is Sentence:
sentences = [sentences]
everything_embedded: bool = True
if self.embedding_type == "word-level":
for sentence in sentences:
for token in sentence.tokens:
if self.name not in token._embeddings.keys():
everything_embedded = False
break
if not everything_embedded:
break
else:
for sentence in sentences:
if self.name not in sentence._embeddings.keys():
everything_embedded = False
break
if not everything_embedded or not self.static_embeddings or (hasattr(sentences,'features') and self.name not in sentences.features):
self._add_embeddings_internal(sentences)
return sentences
@abstractmethod
def _add_embeddings_internal(self, sentences: List[Sentence]) -> List[Sentence]:
"""Private method for adding embeddings to all words in a list of sentences."""
pass
def assign_batch_features(self, sentences, embedding_length=None, assign_zero=False):
if embedding_length is None:
embedding_length = self.embedding_length
sentence_lengths = [len(x) for x in sentences]
if not assign_zero:
sentence_tensor = torch.zeros([len(sentences),max(sentence_lengths),embedding_length]).type_as(sentences[0][0]._embeddings[self.name])
for sent_id, sentence in enumerate(sentences):
for token_id, token in enumerate(sentence):
sentence_tensor[sent_id,token_id]=token._embeddings[self.name]
else:
sentence_tensor = torch.zeros([len(sentences),max(sentence_lengths),embedding_length]).float()
sentence_tensor = sentence_tensor.cpu()
sentences.features[self.name]=sentence_tensor
return sentences
class TokenEmbeddings(Embeddings):
"""Abstract base class for all token-level embeddings. Ever new type of word embedding must implement these methods."""
@property
@abstractmethod
def embedding_length(self) -> int:
"""Returns the length of the embedding vector."""
pass
@property
def embedding_type(self) -> str:
return "word-level"
class DocumentEmbeddings(Embeddings):
"""Abstract base class for all document-level embeddings. Ever new type of document embedding must implement these methods."""
@property
@abstractmethod
def embedding_length(self) -> int:
"""Returns the length of the embedding vector."""
pass
@property
def embedding_type(self) -> str:
return "sentence-level"
class StackedEmbeddings(TokenEmbeddings):
"""A stack of embeddings, used if you need to combine several different embedding types."""
def __init__(self, embeddings: List[TokenEmbeddings], gpu_friendly = False):
"""The constructor takes a list of embeddings to be combined."""
super().__init__()
self.embeddings = embeddings
# IMPORTANT: add embeddings as torch modules
for i, embedding in enumerate(embeddings):
self.add_module("list_embedding_{}".format(i), embedding)
self.name: str = "Stack"
self.static_embeddings: bool = True
# self.gpu_friendly = gpu_friendly
self.__embedding_type: str = embeddings[0].embedding_type
self.__embedding_length: int = 0
for embedding in embeddings:
self.__embedding_length += embedding.embedding_length
def embed(
self, sentences: Union[Sentence, List[Sentence]], static_embeddings: bool = True, embedding_mask = None
):
# if only one sentence is passed, convert to list of sentence
if type(sentences) is Sentence:
sentences = [sentences]
if embedding_mask is not None:
# sort embeddings by name
embedlist = sorted([(embedding.name, embedding) for embedding in self.embeddings], key = lambda x: x[0])
for idx, embedding_tuple in enumerate(embedlist):
embedding = embedding_tuple[1]
if embedding_mask[idx] == 1:
# embedding.to(flair.device)
embedding.embed(sentences)
# embedding.to('cpu')
else:
embedding.assign_batch_features(sentences, assign_zero=True)
else:
for embedding in self.embeddings:
embedding.embed(sentences)
@property
def embedding_type(self) -> str:
return self.__embedding_type
@property
def embedding_length(self) -> int:
return self.__embedding_length
def _add_embeddings_internal(self, sentences: List[Sentence]) -> List[Sentence]:
for embedding in self.embeddings:
embedding._add_embeddings_internal(sentences)
return sentences
def __str__(self):
return f'StackedEmbeddings [{",".join([str(e) for e in self.embeddings])}]'
class WordEmbeddings(TokenEmbeddings):
"""Standard static word embeddings, such as GloVe or FastText."""
def __init__(self, embeddings: str, field: str = None):
"""
Initializes classic word embeddings. Constructor downloads required files if not there.
:param embeddings: one of: 'glove', 'extvec', 'crawl' or two-letter language code or custom
If you want to use a custom embedding file, just pass the path to the embeddings as embeddings variable.
"""
self.embeddings = embeddings
hu_path: str = "https://flair.informatik.hu-berlin.de/resources/embeddings/token"
cache_dir = Path("embeddings")
# GLOVE embeddings
if embeddings.lower() == "glove" or embeddings.lower() == "en-glove":
cached_path(f"{hu_path}/glove.gensim.vectors.npy", cache_dir=cache_dir)
embeddings = cached_path(f"{hu_path}/glove.gensim", cache_dir=cache_dir)
# TURIAN embeddings
elif embeddings.lower() == "turian" or embeddings.lower() == "en-turian":
cached_path(f"{hu_path}/turian.vectors.npy", cache_dir=cache_dir)
embeddings = cached_path(f"{hu_path}/turian", cache_dir=cache_dir)
# KOMNINOS embeddings
elif embeddings.lower() == "extvec" or embeddings.lower() == "en-extvec":
cached_path(f"{hu_path}/extvec.gensim.vectors.npy", cache_dir=cache_dir)
embeddings = cached_path(f"{hu_path}/extvec.gensim", cache_dir=cache_dir)
# pubmed embeddings
elif embeddings.lower() == "pubmed" or embeddings.lower() == "en-pubmed":
cached_path(f"{hu_path}/pubmed_pmc_wiki_sg_1M.gensim.vectors.npy", cache_dir=cache_dir)
embeddings = cached_path(f"{hu_path}/pubmed_pmc_wiki_sg_1M.gensim", cache_dir=cache_dir)
# FT-CRAWL embeddings
elif embeddings.lower() == "crawl" or embeddings.lower() == "en-crawl":
cached_path(f"{hu_path}/en-fasttext-crawl-300d-1M.vectors.npy", cache_dir=cache_dir)
embeddings = cached_path(f"{hu_path}/en-fasttext-crawl-300d-1M", cache_dir=cache_dir)
# FT-CRAWL embeddings
elif embeddings.lower() in ["news", "en-news", "en"]:
cached_path(f"{hu_path}/en-fasttext-news-300d-1M.vectors.npy", cache_dir=cache_dir)
embeddings = cached_path(f"{hu_path}/en-fasttext-news-300d-1M", cache_dir=cache_dir)
# twitter embeddings
elif embeddings.lower() in ["twitter", "en-twitter"]:
cached_path(f"{hu_path}/twitter.gensim.vectors.npy", cache_dir=cache_dir)
embeddings = cached_path(f"{hu_path}/twitter.gensim", cache_dir=cache_dir)
# two-letter language code wiki embeddings
elif len(embeddings.lower()) == 2:
cached_path(f"{hu_path}/{embeddings}-wiki-fasttext-300d-1M.vectors.npy", cache_dir=cache_dir)
embeddings = cached_path(f"{hu_path}/{embeddings}-wiki-fasttext-300d-1M", cache_dir=cache_dir)
# two-letter language code wiki embeddings
elif len(embeddings.lower()) == 7 and embeddings.endswith("-wiki"):
cached_path(f"{hu_path}/{embeddings[:2]}-wiki-fasttext-300d-1M.vectors.npy", cache_dir=cache_dir)
embeddings = cached_path(f"{hu_path}/{embeddings[:2]}-wiki-fasttext-300d-1M", cache_dir=cache_dir)
# two-letter language code crawl embeddings
elif len(embeddings.lower()) == 8 and embeddings.endswith("-crawl"):
cached_path(f"{hu_path}/{embeddings[:2]}-crawl-fasttext-300d-1M.vectors.npy", cache_dir=cache_dir)
embeddings = cached_path(f"{hu_path}/{embeddings[:2]}-crawl-fasttext-300d-1M", cache_dir=cache_dir)
elif embeddings.lower().startswith('conll_'):
embeddings = Path(flair.cache_root)/ cache_dir / f'{embeddings.lower()}.txt'
elif embeddings.lower().endswith('txt'):
embeddings = Path(flair.cache_root)/ cache_dir / f'{embeddings}'
elif embeddings.lower().endswith('cc.el'):
embeddings = Path(flair.cache_root)/ cache_dir / f'{embeddings.lower()}.300.txt'
elif not Path(embeddings).exists():
raise ValueError(
f'The given embeddings "{embeddings}" is not available or is not a valid path.'
)
self.name: str = str(embeddings)
self.static_embeddings = True
if str(embeddings).endswith(".bin"):
self.precomputed_word_embeddings = gensim.models.KeyedVectors.load_word2vec_format(
str(embeddings), binary=True
)
if str(embeddings).endswith(".txt"):
self.precomputed_word_embeddings = gensim.models.KeyedVectors.load_word2vec_format(
str(embeddings), binary=False
)
else:
self.precomputed_word_embeddings = gensim.models.KeyedVectors.load(
str(embeddings)
)
self.field = field
self.__embedding_length: int = self.precomputed_word_embeddings.vector_size
super().__init__()
@property
def embedding_length(self) -> int:
return self.__embedding_length
def _add_embeddings_internal(self, sentences: List[Sentence]) -> List[Sentence]:
if hasattr(sentences, 'features'):
if self.name in sentences.features:
return sentences
if len(sentences)>0:
if self.name in sentences[0][0]._embeddings.keys():
sentences = self.assign_batch_features(sentences)
return sentences
for i, sentence in enumerate(sentences):
for token, token_idx in zip(sentence.tokens, range(len(sentence.tokens))):
if "field" not in self.__dict__ or self.field is None:
word = token.text
else:
word = token.get_tag(self.field).value
if word in self.precomputed_word_embeddings:
word_embedding = self.precomputed_word_embeddings[word]
elif word.lower() in self.precomputed_word_embeddings:
word_embedding = self.precomputed_word_embeddings[word.lower()]
elif (
re.sub(r"\d", "#", word.lower()) in self.precomputed_word_embeddings
):
word_embedding = self.precomputed_word_embeddings[
re.sub(r"\d", "#", word.lower())
]
elif (
re.sub(r"\d", "0", word.lower()) in self.precomputed_word_embeddings
):
word_embedding = self.precomputed_word_embeddings[
re.sub(r"\d", "0", word.lower())
]
else:
word_embedding = np.zeros(self.embedding_length, dtype="float")
word_embedding = torch.FloatTensor(word_embedding)
token.set_embedding(self.name, word_embedding)
if hasattr(sentences, 'features'):
sentences = self.assign_batch_features(sentences)
return sentences
def __str__(self):
return self.name
def extra_repr(self):
# fix serialized models
if "embeddings" not in self.__dict__:
self.embeddings = self.name
return f"'{self.embeddings}'"
class FastWordEmbeddings(TokenEmbeddings):
"""Standard Fine Tune word embeddings, such as GloVe or FastText."""
def __init__(self, embeddings: str, all_tokens: list, field: str = None, if_cased: bool = True, freeze: bool = False, additional_empty_embedding: bool = False, keepall: bool = False, embedding_name: str = None):
"""
Initializes classic word embeddings. Constructor downloads required files if not there.
:param embeddings: one of: 'glove', 'extvec', 'crawl' or two-letter language code or custom
If you want to use a custom embedding file, just pass the path to the embeddings as embeddings variable.
"""
super().__init__()
embed_name = embeddings
hu_path: str = "https://flair.informatik.hu-berlin.de/resources/embeddings/token"
cache_dir = Path("embeddings")
# GLOVE embeddings
if embeddings.lower() == "glove" or embeddings.lower() == "en-glove":
cached_path(f"{hu_path}/glove.gensim.vectors.npy", cache_dir=cache_dir)
embeddings = cached_path(f"{hu_path}/glove.gensim", cache_dir=cache_dir)
# TURIAN embeddings
elif embeddings.lower() == "turian" or embeddings.lower() == "en-turian":
cached_path(f"{hu_path}/turian.vectors.npy", cache_dir=cache_dir)
embeddings = cached_path(f"{hu_path}/turian", cache_dir=cache_dir)
# KOMNINOS embeddings
elif embeddings.lower() == "extvec" or embeddings.lower() == "en-extvec":
cached_path(f"{hu_path}/extvec.gensim.vectors.npy", cache_dir=cache_dir)
embeddings = cached_path(f"{hu_path}/extvec.gensim", cache_dir=cache_dir)
# pubmed embeddings
elif embeddings.lower() == "pubmed" or embeddings.lower() == "en-pubmed":
cached_path(f"{hu_path}/pubmed_pmc_wiki_sg_1M.gensim.vectors.npy", cache_dir=cache_dir)
embeddings = cached_path(f"{hu_path}/pubmed_pmc_wiki_sg_1M.gensim", cache_dir=cache_dir)
# FT-CRAWL embeddings
elif embeddings.lower() == "crawl" or embeddings.lower() == "en-crawl":
cached_path(f"{hu_path}/en-fasttext-crawl-300d-1M.vectors.npy", cache_dir=cache_dir)
embeddings = cached_path(f"{hu_path}/en-fasttext-crawl-300d-1M", cache_dir=cache_dir)
# FT-CRAWL embeddings
elif embeddings.lower() in ["news", "en-news", "en"]:
cached_path(f"{hu_path}/en-fasttext-news-300d-1M.vectors.npy", cache_dir=cache_dir)
embeddings = cached_path(f"{hu_path}/en-fasttext-news-300d-1M", cache_dir=cache_dir)
# twitter embeddings
elif embeddings.lower() in ["twitter", "en-twitter"]:
cached_path(f"{hu_path}/twitter.gensim.vectors.npy", cache_dir=cache_dir)
embeddings = cached_path(f"{hu_path}/twitter.gensim", cache_dir=cache_dir)
# two-letter language code wiki embeddings
elif len(embeddings.lower()) == 2:
cached_path(f"{hu_path}/{embeddings}-wiki-fasttext-300d-1M.vectors.npy", cache_dir=cache_dir)
embeddings = cached_path(f"{hu_path}/{embeddings}-wiki-fasttext-300d-1M", cache_dir=cache_dir)
# two-letter language code wiki embeddings
elif len(embeddings.lower()) == 7 and embeddings.endswith("-wiki"):
cached_path(f"{hu_path}/{embeddings[:2]}-wiki-fasttext-300d-1M.vectors.npy", cache_dir=cache_dir)
embeddings = cached_path(f"{hu_path}/{embeddings[:2]}-wiki-fasttext-300d-1M", cache_dir=cache_dir)
# two-letter language code crawl embeddings
elif len(embeddings.lower()) == 8 and embeddings.endswith("-crawl"):
cached_path(f"{hu_path}/{embeddings[:2]}-crawl-fasttext-300d-1M.vectors.npy", cache_dir=cache_dir)
embeddings = cached_path(f"{hu_path}/{embeddings[:2]}-crawl-fasttext-300d-1M", cache_dir=cache_dir)
elif embeddings.lower().startswith('conll_'):
embeddings = Path(flair.cache_root) / cache_dir / f'{embeddings.lower()}.txt'
elif embeddings.lower().endswith('txt'):
embeddings = Path(flair.cache_root) / cache_dir / f'{embeddings}'
elif embeddings.lower().endswith('.cc'):
embeddings = Path(flair.cache_root) / cache_dir / f'{embeddings}'
elif embeddings.lower().endswith('.vec'):
embeddings = Path(flair.cache_root) / cache_dir / f'{embeddings}'
elif embeddings.lower().endswith('cc.el'):
embeddings = Path(flair.cache_root) / cache_dir / f'{embeddings.lower()}.300.txt'
elif not Path(embeddings).exists():
raise ValueError(
f'The given embeddings "{embeddings}" is not available or is not a valid path.'
)
self.static_embeddings = False
if str(embeddings).endswith(".bin"):
precomputed_word_embeddings = gensim.models.KeyedVectors.load_word2vec_format(
str(embeddings), binary=True
)
elif str(embeddings).endswith('.txt'):
precomputed_word_embeddings = gensim.models.KeyedVectors.load_word2vec_format(
str(embeddings), binary=False
)
elif str(embeddings).endswith('.vec'):
precomputed_word_embeddings = gensim.models.KeyedVectors.load_word2vec_format(str(embeddings), binary=False)
else:
precomputed_word_embeddings = gensim.models.KeyedVectors.load(
str(embeddings)
)
self.field = field
self.name = f'Word: {embed_name}'
if embedding_name is not None:
self.name = embedding_name
self.__embedding_length: int = precomputed_word_embeddings.vector_size
self.if_cased = if_cased
self.get = self.get_idx_cased if if_cased else self.get_idx
train_set = set([token for token in all_tokens[0]]) # | set([token.lower() for token in all_tokens[0]])
full_set = set([token for token in all_tokens[1]]) # | set([token.lower() for token in all_tokens[1]])
self.vocab = {}
if 'unk' not in self.vocab:
self.vocab['unk'] = len(self.vocab)
if 'unk' in precomputed_word_embeddings:
embeddings_tmp = [torch.FloatTensor(precomputed_word_embeddings['unk']).unsqueeze(0)]
else:
embeddings_tmp = [rand_emb(
torch.FloatTensor(self.__embedding_length)
).unsqueeze(0)]
in_train = True
train_emb = 0
train_rand = 0
if keepall:
full_set=set(precomputed_word_embeddings.vocab.keys())|full_set
for token in full_set:
if token in precomputed_word_embeddings:
word_embedding = torch.FloatTensor(precomputed_word_embeddings[token])
train_emb += 1
elif token.lower() in precomputed_word_embeddings:
word_embedding = torch.FloatTensor(precomputed_word_embeddings[token.lower()])
train_emb += 1
elif re.sub(r"\d", "#", token.lower()) in precomputed_word_embeddings:
word_embedding = torch.FloatTensor(
precomputed_word_embeddings[re.sub(r"\d", "#", token.lower())]
)
elif re.sub(r"\d", "0", token.lower()) in precomputed_word_embeddings:
word_embedding = torch.FloatTensor(
precomputed_word_embeddings[re.sub(r"\d", "0", token.lower())]
)
else:
if token in train_set:
word_embedding = rand_emb(
torch.FloatTensor(self.__embedding_length)
)
else:
in_train = False
pass
# word_embedding = word_embedding.view(word_embedding.size()[0]*word_embedding.size()[1])
if in_train:
if token not in self.vocab:
embeddings_tmp.append(word_embedding.unsqueeze(0))
self.vocab[token] = len(self.vocab)
train_rand += 1
else:
in_train = True
for i in range(3):
embeddings_tmp.append(rand_emb(
torch.FloatTensor(self.__embedding_length)
).unsqueeze(0))
self.vocab['<start>'] = len(self.vocab)
self.vocab['<end>'] = len(self.vocab)
self.vocab['<eof>'] = len(self.vocab)
embeddings_tmp = torch.cat(embeddings_tmp, 0)
assert len(self.vocab) == embeddings_tmp.size()[0], "vocab_dic and embedding size not match!"
self.word_embedding = torch.nn.Embedding(embeddings_tmp.shape[0], embeddings_tmp.shape[1])
self.word_embedding.weight = torch.nn.Parameter(embeddings_tmp)
if freeze:
self.word_embedding.weight.requires_grad=False
self.additional_empty_embedding=additional_empty_embedding
if self.additional_empty_embedding:
self.empty_embedding = torch.nn.Embedding(embeddings_tmp.shape[0], embeddings_tmp.shape[1])
torch.nn.init.zeros_(self.empty_embedding.weight)
# self.empty_embedding.weight = rand_emb(self.empty_embedding.weight)
@property
def embedding_length(self) -> int:
return self.__embedding_length
def get_idx(self, token: str):
return self.vocab.get(token.lower(), self.vocab['unk'])
def get_idx_cased(self, token: str):
return self.vocab.get(token, self.vocab.get(token.lower(), self.vocab['unk']))
def encode_sentences(self, sentence):
tokens = sentence.tokens
lines = torch.LongTensor(list(map(self.get, tokens)))
embed = sentence.set_word(lines.unsqueeze(0))
return embed
def embed_sentences(self, sentences):
# pdb.set_trace()
words=getattr(sentences,self.name+'words').to(flair.device)
embeddings = self.word_embedding(words)
if self.additional_empty_embedding:
embeddings +=self.empty_embedding(words)
return embeddings
def _add_embeddings_internal(self, sentences: List[Sentence]) -> List[Sentence]:
embeddings = self.embed_sentences(sentences)
embeddings = embeddings.cpu()
sentences.features[self.name]=embeddings
return sentences
def __str__(self):
return self.name
class FastCharacterEmbeddings(TokenEmbeddings):
"""Character embeddings of words, as proposed in Lample et al., 2016."""
def __init__(
self,
vocab: List = None,
char_embedding_dim: int = 25,
hidden_size_char: int = 25,
char_cnn = False,
debug = False,
embedding_name: str = None,
):
"""Uses the default character dictionary if none provided."""
super().__init__()
self.name = "Char"
if embedding_name is not None:
self.name = embedding_name
self.static_embeddings = False
self.char_cnn = char_cnn
self.debug = debug
# use list of common characters if none provided
self.char_dictionary = {'<u>': 0}
for word in vocab:
for c in word:
if c not in self.char_dictionary:
self.char_dictionary[c] = len(self.char_dictionary)
self.char_dictionary[' '] = len(self.char_dictionary) # concat for char
self.char_dictionary['\n'] = len(self.char_dictionary) # eof for char
self.char_embedding_dim: int = char_embedding_dim
self.hidden_size_char: int = hidden_size_char
self.char_embedding = torch.nn.Embedding(
len(self.char_dictionary), self.char_embedding_dim
)
if self.char_cnn:
print("Use character level CNN")
self.char_drop = torch.nn.Dropout(0.5)
self.char_layer = torch.nn.Conv1d(char_embedding_dim, hidden_size_char, kernel_size=3, padding=1)
self.__embedding_length = self.char_embedding_dim
else:
self.char_layer = torch.nn.LSTM(
self.char_embedding_dim,
self.hidden_size_char,
num_layers=1,
bidirectional=True,
)
self.__embedding_length = self.char_embedding_dim * 2
self.pad_word = rand_emb(torch.FloatTensor(self.__embedding_length)).unsqueeze(0).unsqueeze(0)
def _init_embeddings(self):
utils.init_embedding(self.char_embedding)
@property
def embedding_length(self) -> int:
return self.__embedding_length
def embed_sentences(self, sentences):
# batch_size = len(sentences)
# char_batch = sentences[0].total_len
batch_size = len(sentences)
char_batch = sentences.max_sent_len
# char_list = []
# char_lens = []
# for sent in sentences:
# char_list.append(sent.char_id)
# char_lens.append(sent.char_lengths)
# char_lengths = torch.cat(char_lens, 0)
# char_seqs = pad_sequence(char_list, batch_first=False, padding_value=0)
# char_seqs = char_seqs.view(-1, batch_size * char_batch)
char_seqs = sentences.char_seqs.to(flair.device)
char_lengths = sentences.char_lengths.to(flair.device)
char_embeds = self.char_embedding(char_seqs)
if self.char_cnn:
char_embeds = self.char_drop(char_embeds)
char_cnn_out = self.char_layer(char_embeds.permute(1,2,0))
char_cnn_out = torch.nn.functional.max_pool1d(char_cnn_out, char_cnn_out.size(2)).view(batch_size, char_batch, -1)
outs = char_cnn_out
else:
pack_char_seqs = pack_padded_sequence(input=char_embeds, lengths=char_lengths.to('cpu'), batch_first=False, enforce_sorted=False)
lstm_out, hidden = self.char_layer(pack_char_seqs, None)
# lstm_out = lstm_out.view(-1, self.hidden_dim)
# hidden[0] = h_t = (2, b * s, 25)
outs = hidden[0].transpose(0, 1).contiguous().view(batch_size * char_batch, -1)
outs = outs.view(batch_size, char_batch, -1)
return outs
def _add_embeddings_internal(self, sentences: List[Sentence]) -> List[Sentence]:
embeddings = self.embed_sentences(sentences)
embeddings = embeddings.cpu()
sentences.features[self.name]=embeddings
return sentences
def __str__(self):
return self.name
class LemmaEmbeddings(TokenEmbeddings):
"""Character embeddings of words, as proposed in Lample et al., 2016."""
def __init__(
self,
vocab: List = None,
lemma_embedding_dim: int = 100,
debug = False,
):
"""Uses the default character dictionary if none provided."""
super().__init__()
self.name = "lemma"
self.static_embeddings = False
self.debug = debug
# use list of common characters if none provided
self.lemma_dictionary = {'unk': 0,'_': 1}
for word in vocab:
if word not in self.lemma_dictionary:
self.lemma_dictionary[word] = len(self.lemma_dictionary)
self.lemma_embedding_dim: int = lemma_embedding_dim
self.lemma_embedding = torch.nn.Embedding(
len(self.lemma_dictionary), self.lemma_embedding_dim
)
self.__embedding_length = self.lemma_embedding_dim
def _init_embeddings(self):
utils.init_embedding(self.lemma_embedding)
@property
def embedding_length(self) -> int:
return self.__embedding_length
def embed_sentences(self, sentences):
# pdb.set_trace()
words=getattr(sentences,self.name).to(flair.device)
embeddings = self.lemma_embedding(words)
return embeddings
def _add_embeddings_internal(self, sentences: List[Sentence]) -> List[Sentence]:
embeddings = self.embed_sentences(sentences)
embeddings = embeddings.cpu()
sentences.features[self.name]=embeddings
return sentences
def __str__(self):
return self.name
class POSEmbeddings(TokenEmbeddings):
"""Character embeddings of words, as proposed in Lample et al., 2016."""
def __init__(
self,
vocab: List = None,
pos_embedding_dim: int = 50,
debug = False,
):
"""Uses the default character dictionary if none provided."""
super().__init__()
self.name = "pos"
self.static_embeddings = False
self.debug = debug
# use list of common characters if none provided
self.pos_dictionary = {'unk': 0,'_': 1}
for word in vocab:
if word not in self.pos_dictionary:
self.pos_dictionary[word] = len(self.pos_dictionary)
self.pos_embedding_dim: int = pos_embedding_dim
self.pos_embedding = torch.nn.Embedding(
len(self.pos_dictionary), self.pos_embedding_dim
)
self.__embedding_length = self.pos_embedding_dim
def _init_embeddings(self):
utils.init_embedding(self.pos_embedding)
@property
def embedding_length(self) -> int:
return self.__embedding_length
def embed_sentences(self, sentences):
# pdb.set_trace()
words=getattr(sentences,self.name).to(flair.device)
embeddings = self.pos_embedding(words)
return embeddings
def _add_embeddings_internal(self, sentences: List[Sentence]) -> List[Sentence]:
embeddings = self.embed_sentences(sentences)
embeddings = embeddings.cpu()
sentences.features[self.name]=embeddings
return sentences
def __str__(self):
return self.name
class FastTextEmbeddings(TokenEmbeddings):
"""FastText Embeddings with oov functionality"""
def __init__(self, embeddings: str, use_local: bool = True, field: str = None):
"""
Initializes fasttext word embeddings. Constructor downloads required embedding file and stores in cache
if use_local is False.
:param embeddings: path to your embeddings '.bin' file
:param use_local: set this to False if you are using embeddings from a remote source
"""
cache_dir = Path("embeddings")
if use_local:
if not Path(embeddings).exists():
raise ValueError(
f'The given embeddings "{embeddings}" is not available or is not a valid path.'
)
else:
embeddings = cached_path(f"{embeddings}", cache_dir=cache_dir)
self.embeddings = embeddings
self.name: str = str(embeddings)
self.static_embeddings = True
self.precomputed_word_embeddings = gensim.models.FastText.load_fasttext_format(
str(embeddings)
)
self.__embedding_length: int = self.precomputed_word_embeddings.vector_size
self.field = field
super().__init__()
@property
def embedding_length(self) -> int:
return self.__embedding_length
def _add_embeddings_internal(self, sentences: List[Sentence]) -> List[Sentence]:
for i, sentence in enumerate(sentences):
for token, token_idx in zip(sentence.tokens, range(len(sentence.tokens))):
if "field" not in self.__dict__ or self.field is None:
word = token.text
else:
word = token.get_tag(self.field).value
try:
word_embedding = self.precomputed_word_embeddings[word]
except:
word_embedding = np.zeros(self.embedding_length, dtype="float")
word_embedding = torch.FloatTensor(word_embedding)
token.set_embedding(self.name, word_embedding)
return sentences
def __str__(self):
return self.name
def extra_repr(self):
return f"'{self.embeddings}'"
class OneHotEmbeddings(TokenEmbeddings):
"""One-hot encoded embeddings."""
def __init__(
self,
corpus=Union[Corpus, List[Sentence]],
field: str = "text",
embedding_length: int = 300,
min_freq: int = 3,
):
super().__init__()
self.name = "one-hot"
self.static_embeddings = False
self.min_freq = min_freq
tokens = list(map((lambda s: s.tokens), corpus.train))
tokens = [token for sublist in tokens for token in sublist]
if field == "text":
most_common = Counter(list(map((lambda t: t.text), tokens))).most_common()
else:
most_common = Counter(
list(map((lambda t: t.get_tag(field)), tokens))
).most_common()
tokens = []
for token, freq in most_common:
if freq < min_freq:
break
tokens.append(token)
self.vocab_dictionary: Dictionary = Dictionary()
for token in tokens:
self.vocab_dictionary.add_item(token)
# max_tokens = 500
self.__embedding_length = embedding_length
print(self.vocab_dictionary.idx2item)
print(f"vocabulary size of {len(self.vocab_dictionary)}")
# model architecture
self.embedding_layer = torch.nn.Embedding(
len(self.vocab_dictionary), self.__embedding_length
)
torch.nn.init.xavier_uniform_(self.embedding_layer.weight)
@property
def embedding_length(self) -> int:
return self.__embedding_length
def _add_embeddings_internal(self, sentences: List[Sentence]) -> List[Sentence]:
one_hot_sentences = []
for i, sentence in enumerate(sentences):
context_idxs = [
self.vocab_dictionary.get_idx_for_item(t.text) for t in sentence.tokens
]
one_hot_sentences.extend(context_idxs)
one_hot_sentences = torch.tensor(one_hot_sentences, dtype=torch.long).to(
flair.device
)
embedded = self.embedding_layer.forward(one_hot_sentences)
index = 0
for sentence in sentences:
for token in sentence:
embedding = embedded[index]
token.set_embedding(self.name, embedding)
index += 1
return sentences
def __str__(self):
return self.name
def extra_repr(self):
return "min_freq={}".format(self.min_freq)
class BPEmbSerializable(BPEmb):
def __getstate__(self):
state = self.__dict__.copy()
# save the sentence piece model as binary file (not as path which may change)
state["spm_model_binary"] = open(self.model_file, mode="rb").read()
state["spm"] = None
return state
def __setstate__(self, state):
from bpemb.util import sentencepiece_load
model_file = self.model_tpl.format(lang=state["lang"], vs=state["vs"])
self.__dict__ = state
# write out the binary sentence piece model into the expected directory
self.cache_dir: Path = Path(flair.cache_root) / "embeddings"
if "spm_model_binary" in self.__dict__:
# if the model was saved as binary and it is not found on disk, write to appropriate path
if not os.path.exists(self.cache_dir / state["lang"]):
os.makedirs(self.cache_dir / state["lang"])
self.model_file = self.cache_dir / model_file
with open(self.model_file, "wb") as out:
out.write(self.__dict__["spm_model_binary"])
else:
# otherwise, use normal process and potentially trigger another download
self.model_file = self._load_file(model_file)
# once the modes if there, load it with sentence piece
state["spm"] = sentencepiece_load(self.model_file)
class MuseCrosslingualEmbeddings(TokenEmbeddings):
def __init__(self,):
self.name: str = f"muse-crosslingual"
self.static_embeddings = True
self.__embedding_length: int = 300
self.language_embeddings = {}
super().__init__()
def _add_embeddings_internal(self, sentences: List[Sentence]) -> List[Sentence]:
for i, sentence in enumerate(sentences):
language_code = sentence.get_language_code()
print(language_code)
supported = [
"en",
"de",
"bg",
"ca",
"hr",
"cs",
"da",
"nl",
"et",
"fi",
"fr",
"el",
"he",
"hu",
"id",
"it",
"mk",
"no",
"pl",
"pt",
"ro",
"ru",
"sk",
]
if language_code not in supported:
language_code = "en"
if language_code not in self.language_embeddings:
log.info(f"Loading up MUSE embeddings for '{language_code}'!")