Repository navigation
Expand file tree
/
Copy pathEntitySubstituteTest.py
More file actions
executable file
·1888 lines (1650 loc) · 83.9 KB
/
Copy pathEntitySubstituteTest.py
File metadata and controls
executable file
·1888 lines (1650 loc) · 83.9 KB
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
#!/usr/bin/env python
# coding: utf-8
import json
import os.path
from typing import Dict, Callable
from itertools import permutations
from transformers import AutoModelForMaskedLM, AutoTokenizer, BertForMaskedLM
import torch
from torch import nn
from tqdm import tqdm
import copy
import pickle
from torch.nn.functional import pad
from collections import defaultdict
from pathlib import Path
torch.cuda.empty_cache()
BATCH_SIZE = 512 # BS number, don't remember what it was, isn't used in the experiments. Remove after refactor.
# Borrowed the starter code from https://github.com/writerai/fitbert
# Heavily modified, assume there are some strange changes ahead
class FitBert:
def __init__(
self,
model_name="bert-large-uncased",
reduced_precision=False,
disable_gpu=False,
):
# self.mask_token = mask_token
self.model_name = model_name
self.device = torch.device(
"cuda" if torch.cuda.is_available() and not disable_gpu else "cpu"
)
# self._score = pll_score_batched
print("device:", self.device)
self.bert:AutoModelForMaskedLM = AutoModelForMaskedLM.from_pretrained(model_name)
self.bert.to(self.device)
# torch.compile(self.bert)
self.tokenizer = AutoTokenizer.from_pretrained(model_name, add_prefix_space=False)
self.mask_token = self.tokenizer.mask_token
self.pad_token = self.tokenizer.pad_token
self.cls_token = self.tokenizer.cls_token
self.sep_token = self.tokenizer.sep_token
self.input_embeddings = self.bert.get_input_embeddings()
self.reduced_precision = reduced_precision
self.float_dtype = torch.float32
if self.reduced_precision:
self.float_dtype = torch.float16
self.input_embeddings.to(dtype=self.float_dtype)
with torch.no_grad():
self.mask_token_vector = self.input_embeddings(torch.LongTensor([self.tokenizer.mask_token_id]).to(self.device))[0]
self.pad_token_vector = self.input_embeddings(torch.LongTensor([self.tokenizer.pad_token_id]).to(self.device))[0]
@staticmethod
def soft_top_k(x, k=10):
in_dtype = x.dtype
x = x.to(dtype=torch.float32)
tk = torch.topk(x, k, sorted=False)
# tk.values[tk.values <= 0] = -torch.inf
# indices = tk.indices[tk.values > 0]
# print("!=================")
# # print(x)
# print(tk.values)
# print(tk.indices)
# assert( torch.sum(tk.values).item() != 0 )
# print(FitBert.softmax_(tk.values.detach().clone()))
return torch.zeros_like(x).scatter_(-1, tk.indices, FitBert.softmax_(tk.values.detach().clone())).to(dtype=in_dtype)
def get_vocab_output_dim(self):
return self.bert.get_output_embeddings().out_features
def __call__(self, data, is_split_into_words=False, use_softmax=True, *args, **kwds):
if is_split_into_words:
_tokens = self.tokenizer.convert_tokens_to_ids(data)
_tokens = [self.tokenizer.cls_token_id] + _tokens + [self.tokenizer.sep_token_id]
tokens = {'input_ids':torch.LongTensor([_tokens]).to(self.device)}
else:
tokens = self.tokenizer(data, add_special_tokens=True,padding=True, return_tensors='pt').to(self.device)
# inp = torch.tensor(data, device=self.device)
# if len(tokens.shape) == 1:
# inp = inp.unsqueeze(0)
# print(tokens)
# print(tokens.input_ids)
# print(self.tokenizer.convert_ids_to_tokens(tokens.input_ids[0].tolist()))
# print("=="*50)
b = self.bert(**tokens)
# print(b.logits.shape)
if use_softmax:
return self.softmax(b[0])[:, 1:-1, :]
else:
return b[0][:, 1:-1, :]
# return self.softmax(self.bert_am(**tokens, **kwds)[0])[:, 1:, :]
# return self.bert_am(torch.tensor(self._tokens(data, **kwds)), *args, **kwds)
# def bert_with_subbed_tokens(self, data, tokens=None, **kwds):
# mask = tokens!=self.tokenizer.pad_token_id
# return self.softmax(self.bert(inputs_embeds=inp, attention_mask=mask, **kwds)[0])[:, 1:, :]
def bert_am(self, data, *args, **kwds):
return self.bert(data, *args, attention_mask=(data!=self.tokenizer.pad_token_id), **kwds)
def tokenize(self, *args, **kwds):
return self.tokenizer.tokenize(*args, **kwds)
# def mask_tokenize(self, tokens, keep_original=False, pad=0):
# # tokens = self.tokenize(sent)
# if keep_original:
# return [self._tokens(tokens, pad=pad)] + self.mask_tokenize(tokens, keep_original=False, pad=pad)
# else:
# return (seq(tokens)
# .enumerate()
# .starmap(lambda i, x: self._tokens_to_masked_ids(tokens, i, pad=pad))
# .list()
# )
def mask_tokenize(self, sent, keep_original=False, add_special_tokens=False, padding=False, return_full=False):
tokens = self.tokenize(sent, add_special_tokens=add_special_tokens, padding=padding)
# print(tokens)
tlen = len(tokens)
offset = 1 if add_special_tokens else 0
token_mat = [tokens[:] for i in range(tlen - (2*offset))]
for i in range(offset, tlen-offset):
token_mat[i-offset][i] = self.tokenizer.mask_token
if keep_original:
token_mat = [tokens[:]] + token_mat
if return_full:
return token_mat, self.tokenizer(token_mat, add_special_tokens=(not add_special_tokens), is_split_into_words=True, return_tensors='pt')
return token_mat
def _tokens_to_masked_ids(self, tokens, mask_ind, pad=0):
masked_tokens = tokens[:]
masked_tokens[mask_ind] = self.mask_token
masked_ids = self._tokens(masked_tokens, pad=pad)
return masked_ids
# def _tokens(self, tokens, pad=0, **kwds):
# tokens = tokens + [self.pad_token] * pad
# return self.tokenizer.convert_tokens_to_ids(tokens)
@staticmethod
def softmax(x:torch.Tensor):
# Break into two functions to minimize the memory impact of calling .exp() on very large tensors.
# print(torch.softmax(x.float(), dim=-1).shape)
# print(torch.softmax(x.float(), dim=-1))
# print(torch.softmax(x.float(), dim=-1).max(dim=-1))
# raise AssertionError("Don't call this?")
# in_dtype = x.dtype
return torch.softmax(x.to(dtype=torch.float32), dim=-1).to(dtype=x.dtype)
# return FitBert._inn_soft(x.to(dtype=torch.float32).exp()).to(dtype=x.dtype)
@staticmethod
def _inn_soft(xexp):
# print(xexp.max(-1)[0])
# print(xexp[0].shape)
# print(xexp[0])
# print("_inn_soft")
# print(xexp.sum(-1).shape)
# print(xexp.sum(-1))
# print(xexp.max(-1)[0])
# print((xexp / (xexp.sum(-1)).unsqueeze(-1))[0].shape)
# print((xexp / (xexp.sum(-1)).unsqueeze(-1))[0])
return xexp / (xexp.sum(-1)).unsqueeze(-1)
@staticmethod
def softmax_(x: torch.Tensor):
# Break into two functions to minimize the memory impact of calling .exp() on very large tensors.
# Further reduce memory impact by making it an in-place operation. Beware.
# Rather, that's what we used to try to do. Now it's easier to accept the overhead,
# otherwise we run into really rough floating point precision issues (lots of inf and NaN)
# print("softmax_")
return FitBert.softmax(x)
# return FitBert._inn_soft((x.float() + 10e-6).exp_())
@staticmethod
def masked_softmax(x: torch.Tensor):
# print("Masked_softmax")
mask = (x > 0.0).to(dtype=x.dtype)*-torch.inf
return torch.softmax(x * mask)
# x = x.clone().detach()
# return FitBert._inn_soft(x.float().exp() * (x > 0.0).float())
def nonlin(self, nonlinearity: str) -> Callable:
if nonlinearity in standard_nonlins:
nl = standard_nonlins[nonlinearity]
elif callable(nonlinearity):
nl = nonlinearity
else:
raise Exception(f"Invalid nonlinearity. Must be callable or one of: {list(standard_nonlins.keys())}")
nl = standard_nonlins[None]
# print(f"For {nonlinearity=} chose {nl=}")
return nl
def augment(self, vecs, nonlinearity: str, pooling):
nl=self.nonlin(nonlinearity=nonlinearity)
if pooling:
if pooling in ["mean", "avg"]:
return nl(torch.mean(vecs, dim=0, keepdim=True))
elif pooling == "max":
# print(e.shape)
# print(nl(e).shape)
# print(torch.max(ent_vecs[nl(e)], dim=0, keepdim=True))
# print(torch.max(ent_vecs[e], dim=0, keepdim=True))
return nl(torch.max(vecs, dim=0, keepdim=True)[0])
elif pooling == "sum":
return nl(torch.sum(vecs, dim=0, keepdim=True))
elif callable(pooling):
return nl(pooling(vecs))
else:
return nl(vecs)
def fuzzy_embed(self, vec):
# print(vec.to(device=self.device, dtype=self.float_dtype)@self.input_embeddings.weight)
# print("=================!")
return vec.to(device=self.device, dtype=self.float_dtype)@self.input_embeddings.weight
# FitBert.nonlins = {None: lambda x:x,
# "softmax": FitBert.softmax,
# "relu": torch.relu,
# "relmax": FitBert.masked_softmax,
# "top10": FitBert.soft_top_k,
# "top20": lambda x: FitBert.soft_top_k(x, 20),
# "top50": lambda x: FitBert.soft_top_k(x, 50),
# "top100": lambda x: FitBert.soft_top_k(x, 100)
# }
standard_nonlins: Dict[str, Callable] = {
None: lambda x:x,
"softmax": lambda _x_sm: FitBert.softmax(_x_sm),
"relu": torch.relu,
"relmax": FitBert.masked_softmax,
"top5": lambda x: FitBert.soft_top_k(x, 5),
"top10": lambda x: FitBert.soft_top_k(x, 10),
"top25": lambda x: FitBert.soft_top_k(x, 25),
"top50": lambda x: FitBert.soft_top_k(x, 50),
"top100": lambda x: FitBert.soft_top_k(x, 100)
}
def read_punctuation(fb):
punctuation = fb.tokenizer([".,-()[]{}_=+?!@#$%^&*\\/\"'`~;:|…)(•−"], add_special_tokens=False)['input_ids'][0]
one_hot_punctuation = torch.ones(fb.bert.get_output_embeddings().out_features, dtype=torch.long)
one_hot_punctuation[punctuation] = 0
one_hot_punctuation[1232] = 0
return one_hot_punctuation
class ScoringMethod(nn.Module):
def __init__(self, label):
super(ScoringMethod, self).__init__()
self.label = label
class PllScoringMethod(ScoringMethod):
def __init__(self, label):
super(PllScoringMethod, self).__init__(label)
def forward(self, probs, origids, return_all=False, **kwargs):
mask = origids >= 0
origids[~mask] = 0
slen = len(probs) - 1
dia = torch.diag(probs[1:].gather(-1, origids.unsqueeze(0).repeat(slen, 1).unsqueeze(-1)).squeeze(-1), diagonal=0)[mask]
dia_list = dia.tolist()
prob = torch.mean(torch.log(dia), dim=-1).detach().item()
if return_all:
return prob, dia_list
return prob
class ComparativeScoringMethod(ScoringMethod):
def __init__(self, label):
super(ComparativeScoringMethod, self).__init__(label)
def forward(self, probs, return_all=False, **kwargs):
slen = len(probs) - 1
dia = self.calc(probs[0, :slen], probs[torch.arange(1, slen + 1), torch.arange(slen)])
dia_list = dia.tolist()
prob = torch.mean(torch.log(dia), dim=-1).detach().item()
if return_all:
return prob, dia_list
return prob
def calc(self, p: torch.tensor, q: torch.tensor):
raise NotImplementedError
class JSD(ComparativeScoringMethod):
def __init__(self):
super(JSD, self).__init__("jsd")
self.kl = nn.KLDivLoss(reduction='none', log_target=True)
def calc(self, p: torch.tensor, q: torch.tensor):
m = torch.log((0.5 * (p + q)))
return 1 - (0.5 * (torch.sum(self.kl(m, p.log()), dim=-1) + torch.sum(self.kl(m, q.log()), dim=-1)))
class PLL(PllScoringMethod):
def __init__(self):
super(PLL, self).__init__("pll")
class CSD(ComparativeScoringMethod):
def __init__(self):
super(CSD, self).__init__("csd")
self.csd = torch.nn.CosineSimilarity(dim=1)
def calc(self, p: torch.tensor, q: torch.tensor):
return self.csd(p, q)
class ESD(ComparativeScoringMethod):
def __init__(self):
super(ESD, self).__init__("esd")
self.pwd = torch.nn.PairwiseDistance()
self.sqrt = torch.sqrt(torch.tensor(2, requires_grad=False))
def norm(self, dist):
return (torch.relu(self.sqrt - dist) + 0.000001) / self.sqrt
def calc(self, p: torch.tensor, q: torch.tensor):
return self.norm(self.pwd(p, q))
class MSD(ComparativeScoringMethod):
def __init__(self):
super(MSD, self).__init__("msd")
self.mse = torch.nn.MSELoss(reduction="none")
def calc(self, p: torch.tensor, q: torch.tensor):
return self.mse(p, q).mean(axis=-1)
class HSD(ComparativeScoringMethod):
def __init__(self):
super(HSD, self).__init__("hsd")
self.sqrt = torch.sqrt(torch.tensor(2, requires_grad=False))
def calc(self, p: torch.Tensor, q: torch.Tensor):
p = p.clone()
q = q.clone()
return 1 - torch.sqrt_(torch.sum(torch.pow(torch.sqrt_(p) - torch.sqrt_(q), 2), dim=-1)) / self.sqrt
KNOWN_METHODS = [CSD(), ESD(), JSD(), MSD(), HSD(), PLL()]
KNOWN_METHODS = {m.label: m for m in KNOWN_METHODS}
def prompt(rel, xy=True, ensure_period=True):
if xy:
prompt = rel_info[rel]['prompt_xy']
else:
prompt = rel_info[rel]['prompt_yx']
if ensure_period and prompt[-1] != '.':
return prompt + "."
else:
return prompt
def candidates(prompt:str, choices, return_ments=False):
for a, b in permutations(choices, 2):
if return_ments:
yield prompt.replace("?x", a, 1).replace("?y", b, 1), (a, b)
else:
yield prompt.replace("?x", a, 1).replace("?y", b, 1)
# scores equivalently to the old method, even with padding.
# Can be used to batch across examples.
def pll_score_batched(self, sents: list, return_all=False):
self.bert.eval()
key_to_sent = {}
with torch.no_grad():
data = {}
for sent in sents:
tkns = self.tokenizer.tokenize(sent)
data[len(data)] = {
'tokens': tkns,
'len': len(tkns)
}
scores = {"pll": {}}
all_plls = {"pll": {}}
sents_sorted = list(sorted(data.keys(), key=lambda k: data[k]['len']))
inds = []
lens = []
methods = [PLL()]
for sent in sents_sorted:
n_tokens = data[sent]['len']
if sum(lens) <= BATCH_SIZE:
inds.append(sent)
lens.append(n_tokens)
else:
# There is at least one sentence.
# If the count is zero, then its size is larger than the batch size.
# Send it anyway.
flag = (len(inds) == 0)
if flag:
inds.append(sent)
lens.append(n_tokens)
_inner_score_stuff(self, data, inds, lens, methods, scores, all_plls, return_all)
inds = [sent]
lens = [n_tokens]
if sent == sents_sorted[-1]:
_inner_score_stuff(self, data, inds, lens, methods, scores, all_plls, return_all)
for d in data:
data[d].clear()
data.clear()
# del all_probs
if self.device == "cuda":
torch.cuda.empty_cache()
for method in scores:
assert len(scores[method]) == len(sents_sorted)
if return_all:
return unsort_flatten(scores)["pll"], unsort_flatten(all_plls)["pll"]
return unsort_flatten(scores)["pll"]
def unsort_flatten(mapping):
# print(mapping.keys())
return {f: list(mapping[f][k] for k in range(len(mapping[f]))) for f in mapping}
def cos_score_batched(self, sents: list, return_all=True):
return score_batched(self, methods=[CSD()], sents=sents, return_all=return_all)
def euc_score_batched(self, sents: list, return_all=True):
return score_batched(self, methods=[ESD()], sents=sents, return_all=return_all)
def jsd_score_batched(self, sents: list, return_all=True):
return score_batched(self, methods=[JSD()], sents=sents, return_all=return_all)
def msd_score_batched(self, sents: list, return_all=True):
return score_batched(self, methods=[MSD()], sents=sents, return_all=return_all)
def hel_score_batched(self, sents: list, return_all=True):
return score_batched(self, methods=[HSD()], sents=sents, return_all=return_all)
def all_score_batched(self, sents: list, return_all=True):
return score_batched(self, methods=list(KNOWN_METHODS.values()), sents=sents, return_all=return_all)
# # Purely for reference.
# def mask_tokenize(self, sent, keep_original=False, add_special_tokens=False, padding=False, return_full=False):
# print("S:", type(sent), sent)
# tokens = self.tokenize(sent, add_special_tokens=add_special_tokens, padding=padding)
# # print(tokens)
# tlen = len(tokens)
# offset = 1 if add_special_tokens else 0
# token_mat = [tokens[:] for i in range(tlen - (2*offset))]
# for i in range(offset, tlen-offset):
# token_mat[i-offset][i] = self.tokenizer.mask_token
# if keep_original:
# token_mat = [tokens[:]] + token_mat
# if return_full:
# return token_mat, self.tokenizer(token_mat, add_special_tokens=(not add_special_tokens), is_split_into_words=True, return_tensors='pt')
# return token_mat
# For this one:
# Take a sentence, tokenize it, return all needed information like number of tokens.
def _inner_tokenize_sentence(self, sent, keep_original):
_, tkns = self.mask_tokenize(sent, keep_original=keep_original, add_special_tokens=True, return_full=True)
# print(tkns)
# print(f"TKNS:{len(tkns.input_ids[0]) - 2}")
return tkns, len(tkns.input_ids[0]) - 2
def score_batched(self, methods, sents: list, return_all=True):
# Enforce evaluation mode
self.bert.eval()
with torch.no_grad():
data = {}
for sent in sents:
# Tokenize every sentence
# print("S2:", sent)
tkns, n_tkns = _inner_tokenize_sentence(self, sent, keep_original=True)
data[len(data)] = {
'tokens': tkns,
'len': n_tkns
}
# print("Boo")
scores = {m.label: {} for m in methods}
all_plls = {m.label: {} for m in methods}
sents_sorted = list(sorted(data.keys(), key=lambda k: data[k]['len']))
inds = []
lens = []
for sent in sents_sorted:
n_tokens = data[sent]['len']
if sum(lens) <= BATCH_SIZE:
inds.append(sent)
lens.append(n_tokens)
else:
# There is at least one sentence.
# If the count is zero, then its size is larger than the batch size.
# Send it anyway.
flag = (len(inds) == 0)
if flag:
inds.append(sent)
lens.append(n_tokens)
_inner_score_stuff(self, data, inds, lens, methods, scores, all_plls, return_all)
inds = [sent]
lens = [n_tokens]
if sent == sents_sorted[-1]:
_inner_score_stuff(self, data, inds, lens, methods, scores, all_plls, return_all)
for d in data:
data[d].clear()
data.clear()
if self.device == "cuda":
torch.cuda.empty_cache()
for method in scores:
assert len(scores[method]) == len(sents_sorted)
if return_all:
return unsort_flatten(scores), unsort_flatten(all_plls)
return unsort_flatten(scores)
def bert_am(self, data, *args, **kwds):
return self.bert(data, *args, attention_mask=(data!=self.tokenizer.pad_token_id), **kwds)
def _inner_score_stuff(self, data, inds, lens, methods, scores, all_plls, return_all):
longest = max(lens)
bert_forward = torch.concat([pad(data[d]['tokens'].input_ids, (0, longest - l), 'constant', self.tokenizer.pad_token_id ) for d,l in zip(inds, lens)], dim=0).to(self.device)
token_type_ids = torch.concat([pad(data[d]['tokens'].token_type_ids, (0, longest - l), 'constant', 0) for d, l in zip(inds, lens)], dim=0).to(self.device)
_probs = self.softmax(bert_am(self, bert_forward, token_type_ids=token_type_ids)[0])[:, 1:, :]
del bert_forward
use_pll = any(["pll" in method.label for method in methods])
print(["pll" in method.label for method in methods])
print(use_pll)
for ind, slen in zip(inds, lens):
origids = data[ind]['tokens'].input_ids[0][1:-1].to(self.device) if use_pll else None
for method in methods:
prob, alls = method(_probs[:slen + 1], origids=origids, return_all=True)
if return_all:
assert ind not in all_plls[method.label]
all_plls[method.label][ind] = alls
assert ind not in scores[method.label]
scores[method.label][ind] = prob
del alls, prob
_probs = _probs[slen + 1:]
del _probs
def extend_bert(fb: FitBert, num_blanks:int, tokens_per_blank:int, roberta:bool=False) -> FitBert:
add_tokens = ['?x', '?y']
if roberta:
add_tokens.extend([' ?x', ' ?y'])
add_tokens.append(f' {fb.mask_token}')
for e in range(num_blanks):
for t in range(tokens_per_blank):
add_tokens.append(f"[ENT_{e}_{t}]")
if roberta:
add_tokens.append(f" [ENT_{e}_{t}]")
add_tokens.append(f"[ENT_{e}_x]") # Quick hack to help with preprocessing
if roberta:
add_tokens.append(f" [ENT_{e}_x]")
add_tokens.append('[ENT_BEG]')
add_tokens.append('[ENT_END]')
if roberta:
add_tokens.append(' [ENT_BEG]')
add_tokens.append(' [ENT_END]')
fb.tokenizer.add_tokens(add_tokens, special_tokens=True) # Add the tokens to the tokenizer.
fb.bert.resize_token_embeddings(len(fb.tokenizer)) # Add the tokens to the embedding matrix, initialize with defaults. DO NOT TRAIN.
fb.token_width = tokens_per_blank
fb.entity_tokens = fb.tokenizer("".join(add_tokens), add_special_tokens=False)['input_ids']
fb.input_embeddings = fb.bert.get_input_embeddings().to(dtype=fb.float_dtype)
return fb
class Document:
def __init__(self, doc, num, width=1, num_passes=1, mlm: FitBert=None, use_blanks=True, use_ent=True):
self.doc = doc
self.num = num
self.mlm = mlm
self.overlaps = {}
self.mentions, self.mention_types, self.m_to_e = self.read_mentions()
self.entities = self.read_entities(self.doc['vertexSet'])
self.relations = set([a[1] for a in self.answers(detailed=False)])
self.num_passes = num_passes
self.use_ent = use_ent
self.width = width
self.use_blanks = use_blanks
self._masked_doc = None
@property
def masked_doc(self):
if not self._masked_doc and (self.mlm and self.use_blanks):
self._masked_doc = self.apply_blank_width(self.mlm, self.width)
return self._masked_doc
def apply_blank_width(self, mlm, width):
if mlm:
self.mlm = mlm
self.blank_width = width
if self.blank_width > 0:
return self.mask_entities()
else:
return self.tokenize_entities()
def contextualize_doc(self):
self.unmasked_doc = self.contextualize(mask=False)
return self.unmasked_doc
def __getitem__(self, item):
return self.doc[item]
def __contains__(self, item):
return item in self.doc
def sentences(self):
for sent in self['sents']:
yield " ".join(sent)
def text(self):
return " ".join(self.sentences())
def read_mentions(self):
# Accumulate all mentions with their position (s, b, e) = (w, t)
# avoid duplicates
# Sort by key, ascending
# return ordered list of mentions (w), mapping from index to type (t).
mentions = dict()
m_to_e = dict()
for i, v in enumerate(self['vertexSet']):
for m in v:
s = m['sent_id']
b, e = m['pos']
w = self['sents'][s][b:e]
t = m['type']
if (s, b, e) not in mentions:
mentions[(s, b, e)] = (w, t, i)
ments = list()
types = dict()
for i, (_, v) in enumerate(sorted(mentions.items())):
w, t, e = v
ments.append(w)
m_to_e[i] = e
types[i] = t
return ments, types, m_to_e
@staticmethod
def read_entities(vertSet):
ents = {}
for i, ent in enumerate(vertSet):
ents[i] = list(set(e['name'] for e in ent))
return ents
def tokenize_entities(self):
# Step 1: Copy
sents = copy.deepcopy(self['sents'])
e_beg = '[ENT_BEG]'
e_end = '[ENT_END]'
seen_positions = []
positions = []
for i, v in enumerate(self['vertexSet']):
for m in v:
s = m['sent_id']
b, e = m['pos']
if (s, b, e) not in seen_positions:
seen_positions.append((s, b, e))
positions.append((s, b, e, i))
else:
print(f"Duplicate at {(s, b, e)}")
positions = list(sorted(positions, reverse=True))
for s, b, e, _ in positions:
sents[s][b:e] = [e_beg] + sents[s][b:e] + [e_end]
sents = sum(sents, [])
if "roberta" in self.mlm.model_name.lower():
alt_sents = self.fix_roberta_punctuation(" ".join(sents).replace(" [ENT_BEG]", e_beg).replace(" [ENT_END]", e_end))
tkns = self.mlm.tokenizer.tokenize(alt_sents, add_special_tokens=False, is_split_into_words=False)
else:
tkns = self.mlm.tokenizer.tokenize(sents, add_special_tokens=False, is_split_into_words=True)
print(tkns, flush=True)
# pass
# assert False
e = 0
mentions = [] # Handled.
mention_mask = [] # Handled.
mapp = {}
e = -1
m = len(positions)
m_types = [None]*m
ment_lens = [0]*m
# m -= 1
for i, w in enumerate(reversed(tkns)):
if w == e_end:
en = i
e = positions.pop(0)[-1]
if e not in mapp:
mapp[e] = []
m -= 1
mapp[e].append(m)
elif w == e_beg:
en = 0
e = -1
else:
if e > -1:
ment_lens[m] += 1
mention_mask.append(e > -1)
mentions.append(m if mention_mask[-1] else -1)
mentions = list(reversed(mentions))
mention_mask = list(reversed(mention_mask))
e_count = len(self['vertexSet'])
tokens = [t for t in tkns if t.upper() not in [e_beg, e_end] ]
# print(tokens)
# print(mentions)
# assert False
return {
"length": len(tokens),
"tokens": tokens,
"ments": mentions,
"ment_mask":mention_mask,
"ment_types":m_types,
"ment_lens":ment_lens,
"ents": mapp,
"m_count": len(m_types),
"e_count": e_count,
}
def fix_roberta_punctuation(self, text:str):
if "roberta" in self.mlm.model_name.lower():
for c in '.,;:!?)':
text = text.replace(f' {c}', c)
text = text.replace(' - ', '-')
text = text.replace(" 's ", "'s ")
return text
# Next step: How do we get entity types read from here?
def mask_entities(self):
# Step 1: Copy
sents = copy.deepcopy(self['sents'])
# Step 2: Replace all mention tokens with a placeholder
# Note that these tokens are tokenized differently from BERT's tokens.
for i, v in enumerate(self['vertexSet']):
ent = f'[ENT_{i}_x]'
for m in v:
sid = m['sent_id']
# Check for overlap here.
w = sents[sid][m['pos'][0]]
if (w[0:5].upper() == '[ENT_'):
self.overlaps[int(w.split("_")[1])] = i
for r in range(*m['pos']):
sents[sid][r] = ent
e_count = i + 1
# Step 3: Replace all placeholders with single tokens
mn = 0
entities = []
mentions = []
mention_mask = []
mapp = {}
tokens = []
e = -1
if "roberta" in self.mlm.model_name.lower():
alt_sents = self.fix_roberta_punctuation(" ".join(" ".join(s) for s in sents))
tkns = self.mlm.tokenizer.tokenize(alt_sents, add_special_tokens=False, is_split_into_words=False)
else:
tkns = self.mlm.tokenizer.tokenize(" ".join(" ".join(s) for s in sents), add_special_tokens=False, is_split_into_words=False)
print(tkns, flush=True)
# assert False
for w in tkns:
if ('[ENT_' in w[0:6].upper()):
_e = int(w.split("_")[1])
if e != _e:
e = _e
for i in range(self.blank_width):
if self.use_ent:
tokens.append(w.replace('x', str(i)))
else:
tokens.append(self.mlm.tokenizer.mask_token)
mentions.append(mn)
mention_mask.append(True)
if e not in mapp:
mapp[e] = []
mapp[e].append(mn)
mn += 1
else:
tokens.append(w)
mentions.append(-1)
mention_mask.append(False)
e = -1
m_types = [None]*mn
ment_lens = [self.blank_width]*mn
for i, v in enumerate(self['vertexSet']):
tl = [m['type'] for m in sorted(v, key=lambda x: (x['sent_id'], x['pos'][0]))]
if i in mapp:
for m, t in zip(mapp[i], tl):
m_types[m] = t
else:
# print(f"Missing entity {i} for doc {self.num}")
# if i in self.overlaps:
# print(f"It overlaps with {self.overlaps[i]}")
# else:
# print("It doesn't overlap with anything")
# found = False
# for ans in self.answers(detailed=False):
# # print(ans)
# if (ans[0] == i) or (ans[2] == 1):
# found=True
# if found:
# print("It WAS an answer entity.")
pass
print(tokens)
# assert False
return {
"length": len(tokens),
"tokens": tokens,
"ments": mentions,
"ment_mask":mention_mask,
"ment_types":m_types,
"ment_lens":ment_lens,
"ents": mapp,
"m_count": mn,
"e_count": e_count,
}
def answers(self, detailed=True):
ans = []
for an in self['labels']:
if detailed:
ents = self.entities
hs = ents[an['h']]
ts = ents[an['t']]
r = an['r']
trips = []
for h in hs:
for t in ts:
trips.append((h, r, t))
ans.append(trips)
else:
ans.append((an['h'], an['r'], an['t']))
return ans
def answer_prompts(self):
ents = self.entities()
if 'labels' in self:
ans = []
for an in self['labels']:
_ans = []
pmpt = prompt(an['r'])
for h in ents[an['h']]:
for t in ents[an['t']]:
_ans.append(pmpt.replace("?x", h, 1).replace("?y", t, 1))
ans.append(_ans)
return ans
def candidate_maps(self, rel:str=None, filt=True):
if rel:
rels = [rel]
else:
rels = rel_info
for rel in rels:
pmpt = prompt(rel)
prompts = {}
dom = rel_info[rel]['domain']
ran = rel_info[rel]['range']
for a, b in permutations(self.mentions, 2):
ta, tb = self.mention_types[a], self.mention_types[b]
if not filt or (ta in dom and tb in ran):
prompts[pmpt.replace("?x", a, 1).replace("?y", b, 1)] = ((a, ta), (b, tb))
return prompts
def entity_vecs(self, nonlinearity=lambda x:x, pooling=None, passes=0):
ent_vecs = {}
ment_inds = {}
if self.blank_width > 0:
for e, inds in self.masked_doc['ents'].items():
ent_vecs[e] = self.mlm.augment(self.ment_vecs[passes][inds], nonlinearity, pooling)
minus_one = torch.LongTensor([-1]*self.blank_width).cpu()
for i, s in enumerate(self.masked_doc['ment_lens']):
ment_inds[i] = minus_one.clone()
else:
# Each ent_vecs[e] needs to be the correct corresponding set of vectors.
# Lengths are available:
ment_vecs = {}
_s = 0
for i, s in enumerate(self.masked_doc['ment_lens']):
ment_vecs[i] = self.mlm.augment(self.ment_vecs[passes][_s:_s + s], nonlinearity, None) # We can't pool here.
ment_inds[i] = self.ment_inds[_s:_s + s]
if passes > 0:
# ment_inds[i] = [-1]*len(ment_inds[i])
ment_inds[i] = torch.ones_like(ment_inds[i]) * -1
_s += s
for e, inds in self.masked_doc['ents'].items():
ent_vecs[e] = [ment_vecs[m] for m in inds]
return ent_vecs, ment_inds
def read_document(task_name: str = 'docred', dset: str = 'dev', *, num_blanks=1, num_passes=1, mlm = None, path: str = 'data', doc=-1, verbose=False, use_ent=True):
if (task_name == 'docred' or task_name == "docred") and dset == 'train':
dset = 'train_annotated'
with open(f"{path}/{task_name}/{dset}.json") as datafile:
jfile = json.load(datafile)
if doc >= 0:
yield Document(jfile[doc], doc, width=num_blanks, mlm=mlm, num_passes=num_passes, use_ent=use_ent)
else:
for i, doc in enumerate(jfile):
yield Document(doc, i, width=num_blanks, mlm=mlm, num_passes=num_passes, use_ent=use_ent)
def repair_masking(masked_doc):
masked = ""
for token in masked_doc:
if token[:2] == "##":
masked += token[2:]
else:
if masked:
masked += " "
masked += token
return masked
def mask_vectors(self, sent, keep_original=False, add_special_tokens=False, pad_to=0):
# tokens = self.tokenize(sent, add_special_tokens=add_special_tokens, padding=padding)
# print(tokens)
sent.squeeze_(0)
# print(sent.shape)
tlen = len(sent)
offset = 1 if add_special_tokens else 0
if pad_to > 0:
pad_length = pad_to - tlen
if pad_length > 0:
sent = torch.cat( (sent, torch.clone(self.pad_token_vector).repeat((pad_length, 1)).to(sent.device)), dim=-2)
else:
pad_to = tlen
token_mat = [torch.clone(sent) for i in range(tlen - (2*offset))]
for i in range(offset, tlen-offset):
# print("ti B:", token_mat[i-offset][i])
token_mat[i-offset][i] = self.mask_token_vector
# print("ti A:", token_mat[i-offset][i])
if keep_original:
token_mat = [torch.clone(sent)] + token_mat
mask = torch.ones((len(token_mat), pad_to), dtype=torch.int)
mask[:, tlen:pad_to] = 0
# print(pad_to, tlen, len(token_mat), mask.shape)
assert mask.shape[-1] == pad_to
return torch.stack(token_mat), mask
def score_vectors(self, methods, probs, return_all=True):
# Enforce evaluation mode
self.bert.eval()
with torch.no_grad():
use_pll = "pll" in [method.label for method in methods]
assert not use_pll, "PLL cannot be used for raw vectors. Please choose a different metric."
all_plls = {}
scores = {}
for method in methods:
prob, alls = method(probs, return_all=True)
if return_all:
all_plls[method.label] = alls
scores[method.label] = prob