-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathvisions.py
executable file
·1846 lines (1686 loc) · 77.2 KB
/
visions.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 json
import math
import pickle
import random
import re
import time
import unicodedata
import numpy
import scipy
from scipy import sparse
import torch
from transformers import BertTokenizer, BertForMaskedLM
from transformers import DistilBertTokenizer, DistilBertForMaskedLM
from transformers import RobertaTokenizer, RobertaForMaskedLM
from transformers import DebertaTokenizer, DebertaForMaskedLM
from transformers import DebertaV2Tokenizer, DebertaV2ForMaskedLM
from transformers import GPT2Tokenizer, GPT2LMHeadModel
#import logging
#logging.basicConfig(level=logging.INFO)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
tokenizer = None
model = None
loaded_model_type = None
loaded_model_path = None
from nltk.corpus import stopwords
from nltk.corpus import cmudict
dictionary = cmudict.dict()
from g2p_en import G2p
g2p = G2p()
m = torch.nn.Softmax(dim=0)
re_word = re.compile(r"^[▁a-zA-Z' ]+$")
re_space = re.compile(r"^[ \n\t]+$")
re_vowel = re.compile(r"[aeiouy]")
re_space_and_brackets = re.compile(r"^[\s{}]+$")
def get_pron(tok):
if tok.startswith('madeupword'):
return []
try:
tok = tokenizer.convert_tokens_to_string([tok])
except KeyError:
pass
if tok.startswith('##'):
tok = tok[2:]
if tok.startswith(' ') or tok.startswith('▁'):
tok = tok[1:]
if not re_word.match(tok):
# Punctuation
return []
if tok in dictionary:
pron = dictionary[tok][0]
else:
# Word not in CMU dict: guess using g2p_en
pron = g2p(tok)
return pron
def get_meter(pron):
if pron == []:
return 'p'
meter = ''
for ph in pron:
# We ignore stress levels in favor of poetic scansion
if ph[-1].isdigit():
meter += 'u' if ph[-1] == '0' else '-'
return meter
def get_rhyme(pron):
if pron == []:
return 'p'
rhyme = ''
for ph in reversed(pron):
rhyme = ph.replace('1', '').replace('2', '') + rhyme
if ph[-1].isdigit() and int(ph[-1]) > 0:
break
return rhyme
def is_word_piece(model, tok):
if model.startswith('bert') or model.startswith('distilbert'):
return tok.startswith('##')
elif model.startswith('microsoft/deberta') and '-v2' in model:
return re_word.match(tok) and not tok.startswith('▁')
elif model.startswith('roberta') or model.startswith('gpt2') or (model.startswith('microsoft/deberta') and '-v2' not in model):
try:
tok = tokenizer.convert_tokens_to_string([tok])
except ValueError:
pass
except KeyError:
pass
return re_word.match(tok) and not tok.startswith(' ')
def join_word_pieces(toks):
word = ''
for tok in toks:
if tok.startswith('##'):
tok = tok[2:]
word += tok
return word
def is_full_word(model_type, tok):
if model_type.startswith('bert') or model_type.startswith('distilbert'):
return re_word.match(tok) and not tok.startswith('##')
elif model.startswith('microsoft/deberta') and '-v2' in model:
return re_word.match(tok) and tok.startswith('▁')
elif model_type.startswith('roberta') or model.startswith('gpt2') or (model.startswith('microsoft/deberta') and '-v2' not in model):
try:
tok = tokenizer.convert_tokens_to_string([tok])
except ValueError:
pass
except KeyError:
pass
return re_word.match(tok) and (tok.startswith(' ') or tok.startswith('▁'))
def is_punctuation(tok):
if tok == mask_token:
return False
try:
tok = tokenizer.convert_tokens_to_string([tok])
except ValueError:
pass
except KeyError:
pass
if tok.startswith('▁'):
tok = tok[1:]
return not re_word.match(tok)
def is_space(tok):
if tok == mask_token:
return False
try:
tok = tokenizer.convert_tokens_to_string([tok])
except ValueError:
pass
except KeyError:
pass
if tok.startswith('▁'):
tok = tok[1:]
return re_space.match(tok)
# Scan a text to determine spacing and capitalization so that they can be
# preserved after detokenization.
def scan_tokenization(model, text, toks):
spacing = []
capitalization = []
char_idx = 0
tok_idx = 0
tok_char_idx = 0
current_spacing = ''
current_capitalization = None
after_apostrophe = False
after_double_quote = False
start_of_text = True
while char_idx < len(text):
char = text[char_idx]
if char == '{' or char == '}':
char_idx += 1
continue
word_piece = False
try:
tok = toks[tok_idx]
if model.startswith('microsoft/deberta') and '-v2' not in model:
tok = tokenizer.convert_tokens_to_string([tok])
if (is_word_piece(model, tok) and tok_idx > 0 and not after_double_quote) or tok == "'" or \
(after_apostrophe and tok in ("s", "d", "st", "ve", "re", "nt", "ll", "t", "m")):
tok = join_word_pieces([tok])
word_piece = True
except IndexError:
tok = ''
if tok_char_idx == 0 and (tok.startswith('Ġ') or tok.startswith('Ċ') or tok.startswith(' ') or tok.startswith('▁')) and len(tok) > 1:
if char != ' ':
# Advance the counter when the token contains an extraneous space
tok_char_idx += 1
elif current_spacing.endswith('\n') or start_of_text:
# We have to do this because the tokenizer always adds a space to tokens at
# the start of a line, which is stripped out in detokenize(). To account
# for this, we have to add an extra space in cases where a space really does
# exist at the start of a line.
current_spacing += ' '
try:
tok_char = tok[tok_char_idx]
except IndexError:
tok_char = ''
if tok_char in ('Ġ', 'Ċ', '▁'):
tok_char = ' '
# print(f'{char_idx}: \'{char}\' \'{tok}\' \'{tok_char}\'{" word_piece" if word_piece else ""}'); time.sleep(0.001)
# RoBERTa uses '▁' for both space and newline.
if not char.isspace() or char == tok_char or tok == '▁':
if tok_char_idx == 1 if (tok.startswith('Ġ') or tok.startswith('Ċ') or tok.startswith(' ') or tok.startswith('▁')) else tok_char_idx == 0:
if char.isupper():
current_capitalization = 'upper_ambiguous'
else:
current_capitalization = 'lower'
elif current_capitalization in ('upper_ambiguous', 'upper_all'):
if char.isupper():
current_capitalization = 'upper_all'
else:
current_capitalization = 'upper_initial'
char_idx += 1
start_of_text = False
tok_char_idx += 1
if tok_char_idx == len(tok):
tok_idx += 1
tok_char_idx = 0
after_apostrophe = tok == "'"
after_double_quote = tok in ('"', ' "', '▁"', 'Ġ"')
if not word_piece:
spacing.append(current_spacing)
capitalization.append(current_capitalization)
current_spacing = ''
current_capitalization = None
elif tok_char_idx == 0 or ((tok.startswith('Ġ') or tok.startswith('Ċ') or tok.startswith(' ') or tok.startswith('▁')) and tok_char_idx == 1):
current_spacing += char
char_idx += 1
start_of_text = False
else:
print("WARNING: Text scanner found an unexpected character. This probably indicates a bug in the detokenizer.")
char_idx += 1
print(f'Character {char_idx}: \'{char}\' / token: \'{tok}\' / token character: \'{tok_char}\'{" word_piece" if word_piece else ""}'); time.sleep(0.1)
spacing.append(current_spacing)
return (spacing, capitalization)
def detokenize(model, toks, spacing, capitalization, html=False, start_of_line=True):
text = ''
i = 0
j = 0
current_capitalization = None
after_apostrophe = False
after_double_quote = False
while i < len(toks):
tok = toks[i]
if model.startswith('microsoft/deberta') and '-v2' not in model:
if tok.startswith('<span'):
i1 = tok.index('>')+1
i2 = tok[1:].index('<')
try:
tok = tok[:i1] + tokenizer.convert_tokens_to_string([tok[i1:i2]]) + tok[i2:]
except ValueError:
pass
except KeyError:
pass
elif tok.startswith('<'):
try:
tok = '<' + tokenizer.convert_tokens_to_string([tok[1:-1]]) + '>'
except ValueError:
pass
except KeyError:
pass
else:
try:
tok = tokenizer.convert_tokens_to_string([tok])
except ValueError:
pass
except KeyError:
pass
if (is_word_piece(model, tok) and i > 0 and not after_double_quote) or tok == "'" or \
(after_apostrophe and tok in ("s", "d", "st", "ve", "re", "nt", "ll", "t", "m")):
tok = join_word_pieces([tok])
if current_capitalization == 'upper_all':
tok = tok.upper()
else:
current_spacing = spacing[j]
tok = tok.replace('Ġ', ' ')
tok = tok.replace('Ċ', '\n')
tok = tok.replace('▁', ' ')
if (i == 0 and start_of_line) or '\n' in current_spacing:
# Remove the extra space created by the tokenizer if we are at the start of a line.
if '< ' in tok:
tok = tok.replace('< ', '<')
if '> ' in tok:
tok = tok.replace('> ', '>')
if tok.startswith(' ') and len(tok) > 1:
tok = tok[1:]
if html:
current_spacing = current_spacing.replace(' ', ' ')
text += current_spacing
current_capitalization = capitalization[j]
if current_capitalization in ('upper_initial', 'upper_ambiguous'):
if tok.startswith('<span'):
# Special case for HTML visualization
i1 = tok.index('>')+1
if tok[i1] == ' ' and i1 < len(tok)-1:
i1 += 1
tok = tok[:i1] + tok[i1].upper() + tok[i1+1:]
elif tok[0] == '<' and tok[-1] == '>':
# Special case for tokens marked as just modified
if tok[1] == ' ' and len(tok) > 2:
tok = tok[0:2] + tok[2].upper() + tok[3:]
else:
tok = tok[0] + tok[1].upper() + tok[2:]
elif tok[0] == ' ' and len(tok) > 1:
tok = tok[0] + tok[1].upper() + tok[2:]
else:
tok = tok[0].upper() + tok[1:]
elif current_capitalization == 'upper_all':
tok = tok.upper()
elif current_capitalization == 'lower':
tok = tok.lower()
j += 1
text += tok
i += 1
after_apostrophe = tok == "'"
after_double_quote = tok in ('"', ' "', '▁"', 'Ġ"')
text += spacing[-1]
return text
def create_meter_dict(model_type):
print("Generating " + model_type.replace('/', '_') + '_meter_dict.pkl')
vocab = tokenizer.get_vocab()
meter_dict = {}
word_pieces = torch.zeros([vocab_size])
for tok in vocab:
i = vocab[tok]
pron = get_pron(tok)
meter = get_meter(pron)
if meter not in meter_dict:
meter_dict[meter] = torch.zeros([vocab_size])
meter_dict[meter][i] = 1.0
if is_word_piece(model_type, tok):
word_pieces[i] = 1.0
pickle.dump((word_pieces, meter_dict),
open(model_type.replace('/', '_') + '_meter_dict.pkl', 'wb'))
def create_rhyme_matrix(model_type):
print("Generating " + model_type.replace('/', '_') + '_rhyme_matrix.pkl')
vocab = tokenizer.get_vocab()
rhyme_matrix = sparse.lil_matrix((vocab_size, vocab_size))
rhymable_words = torch.zeros([vocab_size])
rhyme_groups = {}
for tok in vocab:
i = vocab[tok]
pron = get_pron(tok)
rhyme = get_rhyme(pron)
if rhyme not in rhyme_groups:
rhyme_groups[rhyme] = []
rhyme_groups[rhyme].append((i, pron))
for rhyme in rhyme_groups:
if len(rhyme_groups[rhyme]) < 2:
continue
for i, pron1 in rhyme_groups[rhyme]:
rhymable = False
for j, pron2 in rhyme_groups[rhyme]:
# Words with identical pronunciations can't be used as rhymes
if pron1 != pron2:
rhyme_matrix[i,j] = 1.0
rhymable = True
if rhymable:
rhymable_words[i] = 1.0
rhyme_matrix = sparse.csc_matrix(rhyme_matrix)
pickle.dump((rhymable_words, rhyme_matrix), open(model_type.replace('/', '_') + '_rhyme_matrix.pkl', 'wb'))
vocab = None
vocab_size = None
meter_dict = {}
word_pieces = None
rhymable_words = None
rhyme_matrix = None
rhyme_tensors = {}
rhyme_and_meter_loaded = None
def initialize_rhyme_and_meter(model, meter=False, rhymes=False):
global vocab, vocab_size, word_pieces, meter_dict, rhymable_words, rhyme_matrix, rhyme_and_meter_loaded
if rhyme_and_meter_loaded == model:
return
else:
rhyme_and_meter_loaded = model
vocab = tokenizer.get_vocab()
if meter:
try:
f = open(model.replace('/', '_') + '_meter_dict.pkl', 'rb')
except FileNotFoundError:
create_meter_dict(model)
f = open(model.replace('/', '_') + '_meter_dict.pkl', 'rb')
word_pieces, meter_dict = pickle.load(f)
word_pieces = word_pieces.to(device)
meter_dict = {k: v.to(device) for k, v in meter_dict.items()}
else:
try:
f = open(model.replace('/', '_') + '_meter_dict.pkl', 'rb')
except FileNotFoundError:
create_meter_dict(model)
f = open(model.replace('/', '_') + '_meter_dict.pkl', 'rb')
word_pieces, _ = pickle.load(f)
word_pieces = word_pieces.to(device)
if rhymes:
global rhyme_matrix
try:
f = open(model.replace('/', '_') + '_rhyme_matrix.pkl', 'rb')
except FileNotFoundError:
create_rhyme_matrix(model)
f = open(model.replace('/', '_') + '_rhyme_matrix.pkl', 'rb')
rhymable_words, rhyme_matrix = pickle.load(f)
def initialize_model(model_type, model_path):
global tokenizer, model, loaded_model_type, loaded_model_path, bos_token, eos_token, mask_token, pad_token_id, vocab_size
if loaded_model_type != model_type or loaded_model_path != model_path:
loaded_model_type = model_type
loaded_model_path = model_path
if model_type.startswith('distilbert'):
tokenizer = DistilBertTokenizer.from_pretrained(model_path or model_type)
model = DistilBertForMaskedLM.from_pretrained(model_path or model_type)
bos_token = '[CLS]'
eos_token = '[SEP]'
mask_token = '[MASK]'
elif model_type.startswith('bert'):
tokenizer = BertTokenizer.from_pretrained(model_path or model_type)
model = BertForMaskedLM.from_pretrained(model_path or model_type)
bos_token = '[CLS]'
eos_token = '[SEP]'
mask_token = '[MASK]'
elif model_type.startswith('roberta'):
tokenizer = RobertaTokenizer.from_pretrained(model_path or model_type)
model = RobertaForMaskedLM.from_pretrained(model_path or model_type)
bos_token = tokenizer.bos_token
eos_token = tokenizer.eos_token
mask_token = tokenizer.mask_token
elif model_type.startswith('microsoft/deberta') and '-v2' in model_type:
tokenizer = DebertaV2Tokenizer.from_pretrained(model_path or model_type)
model = DebertaV2ForMaskedLM.from_pretrained(model_path or model_type)
bos_token = tokenizer.cls_token
eos_token = tokenizer.sep_token
mask_token = tokenizer.mask_token
elif model_type.startswith('microsoft/deberta'):
tokenizer = DebertaTokenizer.from_pretrained(model_path or model_type)
model = DebertaForMaskedLM.from_pretrained(model_path or model_type)
bos_token = tokenizer.cls_token
eos_token = tokenizer.sep_token
mask_token = tokenizer.mask_token
vocab_size = model.config.vocab_size
pad_token_id = model.config.pad_token_id
model = torch.nn.DataParallel(model)
model.to(device)
model.eval()
# Computes the model's predictions for a text with a given set of ranges
# masked.
def compute_probs_for_masked_tokens(model, tokenized_texts, masked_index_lists, batch_size,
replacements_only=False):
indexed_tokens = []
tensor_indices = {}
wwm_tensor_indices = {}
for j1, (tokenized_text, masked_indices) in enumerate(zip(tokenized_texts, masked_index_lists)):
for j2, masked_index_set in enumerate(masked_indices):
n = len(masked_index_set)
multipart_words = False
tokens = tokenized_text.copy()
for i1, i2 in masked_index_set:
if i2 > i1:
multipart_words = True
if replacements_only:
break
tokens[i1:i2+1] = [mask_token] * (i2 - i1 + 1)
if not replacements_only or not multipart_words:
tensor_indices[(j1, j2)] = len(indexed_tokens)
indexed_tokens.append(tokenizer.convert_tokens_to_ids(tokens))
# If one of the ranges covers a multipart word, we need to compute probabilities
# both for the text with individual tokens masked and with the whole word masked.
if multipart_words:
wwm_tokens = tokenized_text.copy()
shift = 0
for i1, i2 in masked_index_set:
i1 -= shift
i2 -= shift
shift += (i2 - i1)
wwm_tokens[i1:i2+1] = [mask_token]
wwm_tensor_indices[(j1, j2)] = len(indexed_tokens)
indexed_tokens.append(tokenizer.convert_tokens_to_ids(wwm_tokens))
# Add padding so all index sequences are the same length.
max_len = 0
for indices in indexed_tokens:
n = len(indices)
if n > max_len:
max_len = n
attention_mask = []
for i in range(len(indexed_tokens)):
n = len(indexed_tokens[i])
if n < max_len:
indexed_tokens[i] = indexed_tokens[i] + [pad_token_id]*(max_len-n)
attention_mask.append([1]*n + [0]*(max_len-n))
tokens_tensor = torch.tensor(indexed_tokens, device='cpu')
attention_mask = torch.tensor(attention_mask, device='cpu')
all_predictions = []
ntexts = tokens_tensor.shape[0]
nbatches = math.ceil(ntexts / batch_size)
for batchnum in range(nbatches):
batch_start = batchnum * batch_size
batch_end = min(batch_start + batch_size, ntexts)
toks_slice = tokens_tensor[batch_start:batch_end].to(device)
mask_slice = attention_mask[batch_start:batch_end].to(device)
with torch.no_grad():
outputs = model(toks_slice,
attention_mask=mask_slice)
del toks_slice
del mask_slice
all_predictions.append(outputs[0].to('cpu'))
del outputs
del tokens_tensor
del attention_mask
if len(all_predictions) == 0:
return [None]*len(tokenized_texts), [None]*len(tokenized_texts)
all_probs = []
all_replacement_probs = []
for j1, (tokenized_text, masked_indices) in enumerate(zip(tokenized_texts, masked_index_lists)):
probs = []
replacement_probs = []
for j2, masked_index_set in enumerate(masked_indices):
n = len(masked_index_set)
multipart_words = (j1, j2) in wwm_tensor_indices
if not replacements_only or not multipart_words:
j = tensor_indices[(j1, j2)]
index_set_probs = [None] * n
for k, (i1, i2) in enumerate(masked_index_set):
word_probs = []
for i in range(i1, i2+1):
jbatch = j // batch_size
jpreds = j % batch_size
word_probs.append(all_predictions[jbatch][jpreds, i, :])
index_set_probs[k] = word_probs
if not replacements_only:
probs.append(index_set_probs)
if multipart_words:
j = wwm_tensor_indices[(j1, j2)]
index_set_probs = [None] * n
shift = 0
for k, (i1, i2) in enumerate(masked_index_set):
i1 -= shift
i2 -= shift
shift += (i2 - i1)
jbatch = j // batch_size
jpreds = j % batch_size
index_set_probs[k] = [all_predictions[jbatch][jpreds, i1, :]]
replacement_probs.append(index_set_probs)
all_probs.append(probs)
all_replacement_probs.append(replacement_probs)
for predictions in all_predictions:
del predictions
if replacements_only:
return [None]*len(tokenized_texts), all_replacement_probs
else:
return all_probs, all_replacement_probs
# Find words that could, if chosen for the masked indices, take us back to an
# arrangement that has already been tried. Because we are compiling independent
# lists of forbidden words for each index, this method can overcorrect.
def find_forbidden_words(tokenized_text, masked_indices, forbidden_texts):
forbidden_words = [torch.ones((vocab_size,))
for i in range(len(masked_indices))]
d = forbidden_texts
def f(d, start):
i = start
for tok in tokenized_text[start:]:
mask_num = None
mask_len = 0
for k, (i1, i2) in enumerate(masked_indices):
if i == i1:
mask_num = k
mask_len = i2 - i1 + 1
break
if mask_num is not None:
reached_end = False
for option_tok in d.keys():
if f(d[option_tok], i+mask_len):
option_idx = tokenizer \
.convert_tokens_to_ids([option_tok])[0]
forbidden_words[mask_num][option_idx] = 0.0
reached_end = True
return reached_end
else:
if tok in d:
d = d[tok]
else:
return False
i += 1
return True
if f(d, 0):
return forbidden_words
else:
return None
# Function to adjust the output of the model based on various options.
def adjust_probs(model, probs, tokenized_text, start, end, masked_indices,
modifier=None, match_meter=None, forbidden_texts=None,
random_factor=False, discouraged_words=None,
rhyme_with=None, rhymable_only=False, rhymable_with_meters=False,
allow_punctuation=None, no_word_pieces=False,
strong_topic_bias=False, topicless_probs=None):
if forbidden_texts is not None:
forbidden_words = find_forbidden_words(tokenized_text,
masked_indices,
forbidden_texts)
else:
forbidden_words = None
adj_probs = [[u.clone().to(device) for u in t] for t in probs]
for k in range(len(adj_probs)):
for j in range(len(adj_probs[k])):
if random_factor:
noise = torch.randn_like(adj_probs[k][j])
noise = noise * random_factor + 1.0
adj_probs[k][j] *= noise
adj_probs[k][j] = m(adj_probs[k][j])
# Do not produce word pieces. There is no way to keep the model
# behaving reliably if we allow it to produce words that are not
# actually in its vocabulary.
if no_word_pieces:
adj_probs[k][j] *= (1.0 - word_pieces)
if rhymable_only:
adj_probs[k][j] *= rhymable_words
if rhymable_with_meters:
for rhyme_meter in rhymable_with_meters:
test_meter = get_meter(get_pron(rhyme_meter))
meter_tensor = meter_dict[test_meter].to('cpu')
meter_matrix = sparse.dia_matrix((meter_tensor, [0]),
shape=(vocab_size, vocab_size))
# Take the dot product of meter and rhyme
mat = meter_matrix.dot(rhyme_matrix)
vec = torch.from_numpy(mat.sum(0)).squeeze().to(dtype=bool)
adj_probs[k][j] *= vec.to(device)
if forbidden_words is not None:
adj_probs[k][j] *= forbidden_words[k].to(device)
if allow_punctuation is False:
adj_probs[k][j] *= (1.0 - meter_dict['p'])
if match_meter is not None:
test_meter = get_meter(get_pron(match_meter[k]))
meter_tensor = meter_dict[test_meter]
if allow_punctuation is True:
adj_probs[k][j] *= (meter_tensor + meter_dict['p'])
else:
adj_probs[k][j] *= meter_tensor
if modifier is not None:
adj_probs[k][j] *= modifier
if discouraged_words is not None:
adj_probs[k][j] *= discouraged_words
if rhyme_with is not None:
for rhyme_word in rhyme_with:
rhyme_idx = tokenizer.convert_tokens_to_ids([rhyme_word])[0]
rhyme_tensor = rhyme_matrix[rhyme_idx, :].todense()
rhyme_tensor = torch.from_numpy(rhyme_tensor)
rhyme_tensor = rhyme_tensor.squeeze()
adj_probs[k][j] *= rhyme_tensor.to(device)
if strong_topic_bias:
adj_probs[k][j] /= m(topicless_probs[k][j].to(device)) ** strong_topic_bias
# Sometimes funky scores can arise from this division; we just avoid
# choosing those words.
nan_mask = adj_probs[k][j].isnan()
adj_probs[k][j].masked_fill_(nan_mask, 0.0)
inf_mask = adj_probs[k][j].isinf()
adj_probs[k][j].masked_fill_(inf_mask, 0.0)
return adj_probs
# Compute a score indicating how well the model's predictions improve the
# probability for certain words. If multiple words are chosen, it is
# assumed that they are supposed to rhyme.
def compute_score_for_tokens(probs1, probs2, tokenized_text,
indices, require_replacement, relative):
n = len(indices)
dim = [vocab_size] * n
mask_token_id = tokenizer.convert_tokens_to_ids([mask_token])[0]
existing_token_ids = [None] * n
for k, (i1, i2) in enumerate(indices):
existing_token_ids[k] = []
for i in range(i1, i2+1):
token = tokenized_text[i]
index = tokenizer.convert_tokens_to_ids([token])[0]
existing_token_ids[k].append(index)
existing_words_prob = 1.0
if probs1:
for k in range(n):
existing_word_prob = 0.0
if len(existing_token_ids[k]) > 1:
for i, tok_id in enumerate(existing_token_ids[k]):
prob_tensor = probs1[k][i]
existing_word_prob += prob_tensor[tok_id].log()
existing_word_prob /= len(existing_token_ids[k])
existing_words_prob *= existing_word_prob.exp()
else:
existing_words_prob = probs1[k][0][existing_token_ids[k]]
if require_replacement:
for k in range(n):
probs2[k][0][existing_token_ids[k][0]] = 0.0
if n == 1:
prob_tensor = probs2[0][0]
prediction_prob = torch.max(prob_tensor)
idx = prob_tensor.argmax().item()
predicted_token_ids = [idx]
elif n == 2:
# We compute scores for possible rhyme pairs using sparse matrix
# arithmetic. We use scipy instead of torch because torch's sparse
# tensors do not support the .max() function.
left_mat = sparse.dia_matrix((probs2[0][0].to('cpu'), [0]), shape=dim)
mat = left_mat.dot(rhyme_matrix)
right_mat = sparse.dia_matrix((probs2[1][0].to('cpu'), [0]), shape=dim)
mat = mat.dot(right_mat)
prediction_prob = mat.max()
idx = mat.argmax()
# Hack to deal with int32 overflow when the vocab is large
if idx < 0:
idx += 1 << 32
predicted_token_ids = list(numpy.unravel_index(idx, dim))
while mat[predicted_token_ids[0], predicted_token_ids[1]] < prediction_prob:
idx += 1 << 32
predicted_token_ids = list(numpy.unravel_index(idx, dim))
if probs1:
if relative:
score = existing_words_prob / prediction_prob
else:
score = existing_words_prob
else:
score = prediction_prob
predicted_tokens = [None] * n
for i in range(n):
predicted_tokens[i] \
= tokenizer.convert_ids_to_tokens([predicted_token_ids[i]])[0]
return predicted_tokens, float(score)
# Tokenize a text and figure out (as best we can) its rhyme scheme.
def process_text(model, text, start, end, match_rhyme, strip_punctuation=False):
lines = text.split('\n')
tok_index = start
toks = []
rhyme_types = {}
multipart_words = {}
fixed = False
fixed_toks = set()
line_ends = set()
first_line = True
for line in lines:
if (model.startswith('roberta') or model.startswith('gpt2') or (model.startswith('microsoft/deberta') and '-v2' not in model)) and not first_line and not line.startswith(' '):
line = ' ' + line
first_line = False
# Check for the special '{}' characters that indicate fixed text.
line_new = ''
shift = 0
fixed_chars = set()
for i, ch in enumerate(line):
if (model.startswith('bert') or model.startswith('distilbert') or (model.startswith('microsoft/deberta') and '-v2' in model)) and ch == ' ':
# BERT tokenizer strips spaces, so we must account for that.
shift += 1
if ch == '{':
fixed = True
shift += 1
elif ch == '}':
fixed = False
shift += 1
else:
line_new += ch
if fixed:
fixed_chars.add(i - shift)
line_toks = tokenizer.tokenize(line_new)
line_fixed_toks = set()
i = 0
for j, tok in enumerate(line_toks):
if model.startswith('microsoft/deberta') and '-v2' not in model:
tok = tokenizer.convert_tokens_to_string([tok])
if tok.startswith('##'):
tok = tok[2:]
if tok.startswith('▁'):
tok = tok[1:]
nchars = len(tok)
for k in range(nchars):
if i+k in fixed_chars:
line_fixed_toks.add(j + tok_index)
break
i += nchars
if strip_punctuation:
stripped_line_toks = []
stripped_fixed_toks = set()
shift = 0
for j, tok in enumerate(line_toks):
if is_punctuation(tok):
shift += 1
else:
stripped_line_toks.append(tok)
if j + tok_index in line_fixed_toks:
stripped_fixed_toks.add(j + tok_index - shift)
line_toks = stripped_line_toks
line_fixed_toks = stripped_fixed_toks
toks += line_toks
fixed_toks.update(line_fixed_toks)
# Check for multipart words.
word_bounds = []
after_apostrophe = False
after_double_quote = False
for i, tok in enumerate(line_toks):
if model.startswith('microsoft/deberta') and '-v2' not in model:
tok = tokenizer.convert_tokens_to_string([tok])
if (is_word_piece(model, tok) and not after_double_quote) or tok == "'" or \
(after_apostrophe and tok in ("s", "d", "st", "ve", "re", "nt", "ll", "t", "m")):
if not word_bounds:
word_bounds.append([i, i])
else:
word_bounds[-1][1] = i
else:
word_bounds.append([i, i])
after_apostrophe = tok == "'"
after_double_quote = tok in ('"', ' "', '▁"', 'Ġ"')
for i1, i2 in word_bounds:
if i1 == i2:
continue
for i in range(i1, i2+1):
multipart_words[i + tok_index] = (i1 + tok_index,
i2 + tok_index)
if match_rhyme:
rhyme_type = None
# Only check rhyme for the last non-punctuation word of a line.
word = ''
i = len(line_toks) - 1
while i >= 0:
if i + tok_index in multipart_words:
i1, i2 = multipart_words[i + tok_index]
word = join_word_pieces(line_toks[i1-tok_index:i2-tok_index+1])
i = multipart_words[i + tok_index][0] - tok_index
else:
word = line_toks[i]
pron = get_pron(word)
if pron != []:
rhyme_type = get_rhyme(pron)
if rhyme_type is not None:
if not rhyme_type in rhyme_types:
rhyme_types[rhyme_type] = []
rhyme_types[rhyme_type].append(tok_index + i)
break
i -= 1
tok_index += len(line_toks)
line_ends.add(tok_index)
if match_rhyme:
rhyme_groups = {}
for rhyme in rhyme_types:
tok_list = rhyme_types[rhyme]
# Rhyme groups of more than two not currently supported, so we
# split the groups up into pairs
for i in range(0, len(tok_list), 2):
group = tok_list[i:i+2]
for index in group:
rhyme_groups[index] = group
return toks, fixed_toks, multipart_words, rhyme_groups, line_ends
else:
return toks, fixed_toks, multipart_words, {}, line_ends
# Alters a text iteratively, word by word, using the model to pick
# replacements.
def depoeticize(text, max_iterations=100, batch_size=10,
match_meter=False, match_rhyme=False, title=None, author=None,
randomize=False, cooldown=0.01, modifier=None,
forbid_reversions=True, preserve_punctuation=False,
strong_topic_bias=False, stop_score=1.0,
discourage_repetition=False, stopwords=stopwords.words('english'),
model_type='bert-base-uncased', model_path=None,
preserve_spacing_and_capitalization=True,
allow_punctuation=None, sequential=False, verbose=True,
outfile=None, top_n=10, require_new_rhymes=False,
num_changes_per_iter=1):
stopwords = set(stopwords)
# The detokenizer doesn't properly handle cases where the input is all space. It is necessary
# to implement good behavior in this case because it can arise when this function is called
# by banalify.
if re_space_and_brackets.match(text):
return text.replace('{', '').replace('}', '')
# Stripping smart quotes because some of the models don't seem to handle them properly.
text = text.replace('“','"').replace('”','"').replace('‘','\'').replace('’','\'').replace('\r\n', '\n')
initialize_model(model_type, model_path)
initialize_rhyme_and_meter(model_type, meter=match_meter or allow_punctuation is not None,
rhymes=match_rhyme)
if modifier is not None:
modifier = modifier().to(device)
topicless_toks1 = tokenizer.tokenize(f'{bos_token}Title: {mask_token} / Author: {mask_token} {mask_token} / Text: \n\n')
if title and author:
toks1 = tokenizer.tokenize(f'{bos_token}Title: {title} / Author: {author} / Text: \n\n')
elif title:
toks1 = tokenizer.tokenize(f'{bos_token}Title: {title} / Author: {mask_token} {mask_token} / Text: \n\n')
elif author:
toks1 = tokenizer.tokenize(f'{bos_token}Title: {mask_token} / Author: {author} / Text: \n\n')
else:
toks1 = [bos_token]
toks3 = [eos_token]
start = len(toks1)
end = len(toks3)
toks2, fixed_toks, multipart_words, rhyme_groups, line_ends \
= process_text(model_type, text, start, end, match_rhyme)
tokenized_text = toks1 + toks2 + toks3
n = len(tokenized_text)
if preserve_spacing_and_capitalization:
spacing, capitalization = scan_tokenization(model_type, text, toks2)
forbidden_texts = {}
if outfile is not None:
outfile = open(outfile, 'w')
html = f'''
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="viz.css">
<script src='jquery.js'></script>
<script src='viz.js'></script>
</head>
<body>
Model: {model_type}{' "' + model_path + '"' if model_path else ''}<br />
Max iterations: {max_iterations}<br />
'''
if strong_topic_bias:
html += f'Strong topic bias: {strong_topic_bias}<br />'
if randomize:
html += f'Randomizing, cooldown={cooldown}<br />'
if stop_score != 1.0:
html += f'Stop score: {stop_score}<br />'
if match_meter:
html += 'Matching meter<br />'
if match_rhyme:
html += 'Matching rhyme<br />'
if require_new_rhymes:
html += 'Requiring new rhymes<br />'
if forbid_reversions:
html += 'Forbidding reversions<br />'
if preserve_punctuation:
html += 'Preserving punctuation<br />'
if discourage_repetition:
html += 'Discouraging repetition<br />'
if allow_punctuation is True:
html += 'Always allowing punctuation<br />'
if allow_punctuation is False:
html += 'Never allowing punctuation<br />'
if modifier is not None:
html += 'Modifier provided<br />'
if sequential:
html += 'Running in sequential mode<br />'
html += '<hr />'
if title:
html += f'Title: {title}<br />'
if author:
html += f'Author: {author}<br />'
html += '''<hr />
Highlight: <select name="highlighting" id="highlighting">
<option>Score</option>
<option>Entropy</option>
<option>None</option>
</select>
<input type="checkbox" id="changes" name="changes" value="Changes">
<label for="changes"> Indicate changes</label><br />Double-click on words to see predictions<hr />'''
outfile.write(html)
if sequential:
max_iterations = len(toks2)
new_token_indices = []
if require_new_rhymes:
original_rhymes = {}
for i in rhyme_groups:
original_rhymes[i] = tokenized_text[i]
for k in range(max_iterations):
last_score = 0.0