-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmodel_1_to_1_seg.py
2587 lines (2220 loc) · 104 KB
/
model_1_to_1_seg.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 torch
from torch.autograd import Variable
from torch import nn
from transformers import BertModel, BertForMaskedLM, DistilBertForMaskedLM, DistilBertModel, AutoModel
from transformers import AutoModelWithLMHead, AlbertModel, AlbertForMaskedLM
from transformers import AlbertForSequenceClassification
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# device = torch.device("cpu")
class EncoderStackedCnnBnLSTMLSTM(nn.Module):
"""添加额外CNN向量
1、cnn提取特征,后RNN;
2、bert直连LSTM
1+2
"""
def __init__(self, bert, hidden_size, n_layers, cnn_kernel_size, cnn_filter_num):
super(EncoderStackedCnnBnLSTMLSTM, self).__init__()
self.bert = bert
self.hidden_size = hidden_size
self.n_layers = n_layers
self.cnn_kernel_size = cnn_kernel_size
self.cnn_filter_num = cnn_filter_num
# GRU输入为bert + cnn_out
# self.gru = nn.GRU(bert_size+(bert_size-cnn_kernel_size[1]+1)*cnn_filter_num, hidden_size, n_layers, bidirectional=True, batch_first=False)
# cnn_kernel_size包含高度(多少词一个卷)和宽度(每个词的多少位一个卷)
self.conv = nn.ModuleList()
cnn_layer_num = 4
for i in range(cnn_layer_num):
module_tmp = nn.ModuleDict({
'conv_w_{}'.format(i):
nn.Conv2d(1 if i == 0 else cnn_filter_num,
cnn_filter_num,
cnn_kernel_size,
padding=((cnn_kernel_size[0] - 1) // 2,
(cnn_kernel_size[1] - 1) // 2)),
'bn_w_{}'.format(i): nn.BatchNorm2d(cnn_filter_num),
'conv_v_{}'.format(i):
nn.Conv2d(1 if i == 0 else cnn_filter_num,
cnn_filter_num,
cnn_kernel_size,
padding=((cnn_kernel_size[0] - 1) // 2,
(cnn_kernel_size[1] - 1) // 2)),
'bn_v_{}'.format(i): nn.BatchNorm2d(cnn_filter_num),
})
self.conv.append(module_tmp)
# LSTM输入为bert + cnn_out
self.lstm = nn.ModuleDict({
'cnn_lstm': nn.LSTM(
# cnn的每个词对应的输入尺寸为 cnn_layer_num=4层CNN,每层cnn_filter_num=10 filter
input_size=(bert.embedding_size-((cnn_kernel_size[1]-1) % 2 * cnn_layer_num))*cnn_filter_num,
hidden_size=hidden_size, num_layers=n_layers, bidirectional=True, batch_first=False
),
'emb_lstm': nn.LSTM(
bert.embedding_size,
hidden_size,
n_layers,
bidirectional=True,
batch_first=False
),
})
# @torchsnooper.snoop()
def forward(self, word_inputs):
# Note: we run this all at once (over the whole input sequence)
# [S, B, Emb]
embedded = self.bert(word_inputs)[0]
# [S, B, Emb] -> [B, S, Emb]
embedded_cnn = embedded.transpose(0, 1)
# # 补上padding,使得conv得到seq_len个向量
# batch_size = embedded_cnn.shape[0]
# padding_size = self.cnn_kernel_size[0] - 1
# # [B, padding_size, Emb]
# pad_start = torch.zeros(batch_size, padding_size//2, self.bert_size).to(device)
# pad_end = torch.zeros(batch_size, padding_size//2, self.bert_size).to(device)
# # [B, S, Emb] -> [B, S+p_s, Emb]
# embedded_cnn = torch.cat([pad_start, embedded_cnn, pad_end], dim=1)
# [B, S+p_s, Emb] -> [B, Channel, S+p_s, Emb]
embedded_cnn = embedded_cnn.unsqueeze(1)
# cnn_out: [B, Channel, S, x] 向量维度未知
""" print('cnn_out size', embedded_cnn.shape) """
cnn_out = []
cnn_out = embedded_cnn
for i, conv_dict in enumerate(self.conv):
w = conv_dict['conv_w_{}'.format(i)](cnn_out)
w = conv_dict['bn_w_{}'.format(i)](w)
v = conv_dict['conv_v_{}'.format(i)](cnn_out)
v = conv_dict['bn_v_{}'.format(i)](v)
cnn_out = w * torch.sigmoid(v)
# for conv in self.conv:
# cnn_out_temp = conv(embedded_cnn)
# # cat cnn_out的filter_num维度
# # [B, Channel, S, x] -> [B, S, x]
# # filter_size = 2
# cnn_out.append(torch.cat([cnn_out_temp[:, i, :, :] for i in range(2)], dim=-1))
# cnn_out = torch.cat(cnn_out, dim=-1)
# 通过拼接 [B, Channel, S, x] -> [B, S, x]
# print(cnn_out.shape)
cnn_out = torch.cat([cnn_out[:, i, :, :] for i in range(self.cnn_filter_num)], dim=-1)
# cnn_out = cnn_out.squeeze(1)
# print(cnn_out.shape)
# [B, S, x] -> [S, B, x]
cnn_out = cnn_out.transpose(0, 1)
""" print('cnn_out size', cnn_out.shape) """
# 打印嵌入的 词向量shape 和 隐状态shape。
# print('enc_emb size', embedded.shape)
# print('hidden size', hidden.shape)
cnn_lstm_input = cnn_out
emb_lstm_input = embedded
# output1 = [S, B, 2H] hidden1=[lyr*direct, B, H]
output1, hidden1 = self.lstm['cnn_lstm'](cnn_lstm_input, None)
output2, hidden2 = self.lstm['emb_lstm'](emb_lstm_input, None)
# 在第三维cat起来
output = torch.cat([output1, output2], dim=-1)
# output size: [S, B, 4H]; hidden: ([lyr*direct, B, H], [lyr*direct, B, H])
return output
class EncoderStackedNmlCnnLSTMLSTM(nn.Module):
"""添加额外CNN向量
1、cnn提取特征,后RNN;
2、bert直连LSTM
1+2
"""
def __init__(self, bert, hidden_size, n_layers, cnn_kernel_size, cnn_filter_num):
super(EncoderStackedNmlCnnLSTMLSTM, self).__init__()
self.bert = bert
self.hidden_size = hidden_size
self.n_layers = n_layers
self.cnn_kernel_size = cnn_kernel_size
self.cnn_filter_num = cnn_filter_num
# GRU输入为bert + cnn_out
# self.gru = nn.GRU(bert_size+(bert_size-cnn_kernel_size[1]+1)*cnn_filter_num, hidden_size, n_layers, bidirectional=True, batch_first=False)
# cnn_kernel_size包含高度(多少词一个卷)和宽度(每个词的多少位一个卷)
self.conv = nn.ModuleList()
cnn_layer_num = 2
self.cnn_layer_num = cnn_layer_num
for i in range(cnn_layer_num):
module_tmp = nn.Conv2d(
1 if i == 0 else cnn_filter_num,
cnn_filter_num,
cnn_kernel_size,
padding=(
(cnn_kernel_size[0] - 1) // 2,
(cnn_kernel_size[1] - 1) // 2
)
)
self.conv.append(module_tmp)
# LSTM输入为bert + cnn_out
self.lstm = nn.ModuleDict({
'cnn_lstm': nn.LSTM(
# cnn的每个词对应的输入尺寸为 cnn_layer_num=4层CNN,每层cnn_filter_num=10 filter
input_size=(bert.embedding_size-((cnn_kernel_size[1]-1) % 2 * cnn_layer_num))*cnn_filter_num,
hidden_size=bert.embedding_size, num_layers=n_layers, bidirectional=True, batch_first=True
),
'emb_lstm': nn.LSTM(
bert.embedding_size,
bert.embedding_size,
n_layers,
bidirectional=True,
batch_first=False
),
})
# @torchsnooper.snoop()
def forward(self, word_inputs):
# Note: we run this all at once (over the whole input sequence)
# [B, S, Emb]
embedded = self.bert(word_inputs)[0]
# # 补上padding,使得conv得到seq_len个向量
# batch_size = embedded_cnn.shape[0]
# padding_size = self.cnn_kernel_size[0] - 1
# # [B, padding_size, Emb]
# pad_start = torch.zeros(batch_size, padding_size//2, self.bert_size).to(device)
# pad_end = torch.zeros(batch_size, padding_size//2, self.bert_size).to(device)
# # [B, S, Emb] -> [B, S+p_s, Emb]
# embedded_cnn = torch.cat([pad_start, embedded_cnn, pad_end], dim=1)
# [B, S+p_s, Emb] -> [B, Channel, S+p_s, Emb]
embedded_cnn = embedded.unsqueeze(1)
# cnn_out: [B, Channel, S, x] 向量维度未知
""" print('cnn_out size', embedded_cnn.shape) """
cnn_out = []
cnn_out = embedded_cnn
for conv in self.conv:
cnn_out = conv(cnn_out)
# for conv in self.conv:
# cnn_out_temp = conv(embedded_cnn)
# # cat cnn_out的filter_num维度
# # [B, Channel, S, x] -> [B, S, x]
# # filter_size = 2
# cnn_out.append(torch.cat([cnn_out_temp[:, i, :, :] for i in range(2)], dim=-1))
# cnn_out = torch.cat(cnn_out, dim=-1)
# 通过拼接 [B, Channel, S, x] -> [B, S, x]
# print(cnn_out.shape)
cnn_out = torch.cat([cnn_out[:, i, :, :] for i in range(self.cnn_filter_num)], dim=-1)
# cnn_out = cnn_out.squeeze(1)
""" print('cnn_out size', cnn_out.shape) """
# 打印嵌入的 词向量shape 和 隐状态shape。
# print('enc_emb size', embedded.shape)
# print('hidden size', hidden.shape)
cnn_lstm_input = cnn_out
emb_lstm_input = embedded
# output1 = [B, S, 2H] hidden1=[lyr*direct, B, H]
output1, hidden1 = self.lstm['cnn_lstm'](cnn_lstm_input, None)
output2, hidden2 = self.lstm['emb_lstm'](emb_lstm_input, None)
# 在第三维cat起来
output = torch.cat([output1, output2], dim=-1)
# output size: [S, B, 4H]; hidden: ([lyr*direct, B, H], [lyr*direct, B, H])
return output
class EncoderStackedCnnLSTMLSTM(nn.Module):
"""添加额外CNN向量
1、cnn提取特征,后RNN;
2、bert直连LSTM
1+2
"""
def __init__(self, bert, hidden_size, n_layers, cnn_kernel_size, cnn_filter_num):
super(EncoderStackedCnnLSTMLSTM, self).__init__()
self.bert = bert
self.hidden_size = hidden_size
self.n_layers = n_layers
self.cnn_kernel_size = cnn_kernel_size
self.cnn_filter_num = cnn_filter_num
# GRU输入为bert + cnn_out
# self.gru = nn.GRU(bert_size+(bert_size-cnn_kernel_size[1]+1)*cnn_filter_num, hidden_size, n_layers, bidirectional=True, batch_first=False)
# cnn_kernel_size包含高度(多少词一个卷)和宽度(每个词的多少位一个卷)
self.conv = nn.ModuleList()
cnn_layer_num = 4
for i in range(cnn_layer_num):
module_tmp = nn.ModuleDict({
'conv_w_{}'.format(i):
nn.Conv2d(1 if i == 0 else cnn_filter_num,
cnn_filter_num,
cnn_kernel_size,
padding=((cnn_kernel_size[0] - 1) // 2,
(cnn_kernel_size[1] - 1) // 2)),
'conv_v_{}'.format(i):
nn.Conv2d(1 if i == 0 else cnn_filter_num,
cnn_filter_num,
cnn_kernel_size,
padding=((cnn_kernel_size[0] - 1) // 2,
(cnn_kernel_size[1] - 1) // 2)),
})
self.conv.append(module_tmp)
# LSTM输入为bert + cnn_out
self.lstm = nn.ModuleDict({
'cnn_lstm': nn.LSTM(
# cnn的每个词对应的输入尺寸为 cnn_layer_num=4层CNN,每层cnn_filter_num=10 filter
input_size=(bert.embedding_size-((cnn_kernel_size[1]-1) % 2 * cnn_layer_num))*cnn_filter_num,
hidden_size=bert.embedding_size, num_layers=n_layers, bidirectional=True, batch_first=True
),
'emb_lstm': nn.LSTM(
bert.embedding_size,
bert.embedding_size,
n_layers,
bidirectional=True,
batch_first=False
),
})
# @torchsnooper.snoop()
def forward(self, word_inputs):
# Note: we run this all at once (over the whole input sequence)
# [B, S, Emb]
embedded = self.bert(word_inputs)[0]
# # 补上padding,使得conv得到seq_len个向量
# batch_size = embedded_cnn.shape[0]
# padding_size = self.cnn_kernel_size[0] - 1
# # [B, padding_size, Emb]
# pad_start = torch.zeros(batch_size, padding_size//2, self.bert_size).to(device)
# pad_end = torch.zeros(batch_size, padding_size//2, self.bert_size).to(device)
# # [B, S, Emb] -> [B, S+p_s, Emb]
# embedded_cnn = torch.cat([pad_start, embedded_cnn, pad_end], dim=1)
# [B, S+p_s, Emb] -> [B, Channel, S+p_s, Emb]
embedded_cnn = embedded.unsqueeze(1)
# cnn_out: [B, Channel, S, x] 向量维度未知
""" print('cnn_out size', embedded_cnn.shape) """
cnn_out = []
cnn_out = embedded_cnn
for i, conv_dict in enumerate(self.conv):
w = conv_dict['conv_w_{}'.format(i)](cnn_out)
v = conv_dict['conv_v_{}'.format(i)](cnn_out)
cnn_out = w * torch.sigmoid(v)
# for conv in self.conv:
# cnn_out_temp = conv(embedded_cnn)
# # cat cnn_out的filter_num维度
# # [B, Channel, S, x] -> [B, S, x]
# # filter_size = 2
# cnn_out.append(torch.cat([cnn_out_temp[:, i, :, :] for i in range(2)], dim=-1))
# cnn_out = torch.cat(cnn_out, dim=-1)
# 通过拼接 [B, Channel, S, x] -> [B, S, x]
# print(cnn_out.shape)
cnn_out = torch.cat([cnn_out[:, i, :, :] for i in range(self.cnn_filter_num)], dim=-1)
# cnn_out = cnn_out.squeeze(1)
""" print('cnn_out size', cnn_out.shape) """
# 打印嵌入的 词向量shape 和 隐状态shape。
# print('enc_emb size', embedded.shape)
# print('hidden size', hidden.shape)
cnn_lstm_input = cnn_out
emb_lstm_input = embedded
# output1 = [B, S, 2H] hidden1=[lyr*direct, B, H]
output1, hidden1 = self.lstm['cnn_lstm'](cnn_lstm_input, None)
output2, hidden2 = self.lstm['emb_lstm'](emb_lstm_input, None)
# 在第三维cat起来
output = torch.cat([output1, output2], dim=-1)
# output size: [S, B, 4H]; hidden: ([lyr*direct, B, H], [lyr*direct, B, H])
return output
class EncoderStackedSlimCnn(nn.Module):
"""添加额外CNN向量
1、cnn提取特征,后RNN;
2、bert直连LSTM
1+2
"""
def __init__(self, bert, hidden_size, n_layers, cnn_kernel_size, cnn_filter_num):
super(EncoderStackedCnndivided, self).__init__()
self.bert = bert
self.hidden_size = hidden_size
self.n_layers = n_layers
self.cnn_kernel_size = cnn_kernel_size
self.cnn_filter_num = cnn_filter_num
# GRU输入为bert + cnn_out
# self.gru = nn.GRU(bert_size+(bert_size-cnn_kernel_size[1]+1)*cnn_filter_num, hidden_size, n_layers, bidirectional=True, batch_first=False)
# cnn_kernel_size包含高度(多少词一个卷)和宽度(每个词的多少位一个卷)
self.conv = nn.ModuleList()
cnn_layer_num = 4
for i in range(cnn_layer_num):
module_tmp = nn.ModuleDict({
'conv_w_{}'.format(i):
nn.Conv2d(1 if i == 0 else cnn_filter_num,
cnn_filter_num,
cnn_kernel_size if i == 0 else (cnn_kernel_size[0], cnn_filter_num),
padding=((cnn_kernel_size[0] - 1) // 2,
(cnn_kernel_size[1] - 1) // 2)),
'conv_v_{}'.format(i):
nn.Conv2d(1 if i == 0 else cnn_filter_num,
cnn_filter_num,
cnn_kernel_size if i == 0 else (cnn_kernel_size[0], cnn_filter_num),
padding=((cnn_kernel_size[0] - 1) // 2,
(cnn_kernel_size[1] - 1) // 2)),
})
self.conv.append(module_tmp)
# LSTM输入为bert + cnn_out
self.lstm = nn.ModuleDict({
'cnn_lstm': nn.LSTM(
# cnn的每个词对应的输入尺寸为 cnn_layer_num=4层CNN,每层cnn_filter_num=10 filter
input_size=(bert.embedding_size-((cnn_kernel_size[1]-1) % 2 * cnn_layer_num))*cnn_filter_num,
hidden_size=bert.embedding_size, num_layers=n_layers, bidirectional=True, batch_first=True
),
'emb_lstm': nn.LSTM(
bert.embedding_size,
bert.embedding_size,
n_layers,
bidirectional=True,
batch_first=False
),
})
# @torchsnooper.snoop()
def forward(self, word_inputs):
# Note: we run this all at once (over the whole input sequence)
# [B, S, Emb]
embedded = self.bert(word_inputs)[0]
# # 补上padding,使得conv得到seq_len个向量
# batch_size = embedded_cnn.shape[0]
# padding_size = self.cnn_kernel_size[0] - 1
# # [B, padding_size, Emb]
# pad_start = torch.zeros(batch_size, padding_size//2, self.bert_size).to(device)
# pad_end = torch.zeros(batch_size, padding_size//2, self.bert_size).to(device)
# # [B, S, Emb] -> [B, S+p_s, Emb]
# embedded_cnn = torch.cat([pad_start, embedded_cnn, pad_end], dim=1)
# [B, S+p_s, Emb] -> [B, Channel, S+p_s, Emb]
embedded_cnn = embedded.unsqueeze(1)
# cnn_out: [B, Channel, S, x] 向量维度未知
""" print('cnn_out size', embedded_cnn.shape) """
cnn_out = []
cnn_out = embedded_cnn
for i, conv_dict in enumerate(self.conv):
w = conv_dict['conv_w_{}'.format(i)](cnn_out)
v = conv_dict['conv_v_{}'.format(i)](cnn_out)
cnn_out = w * torch.sigmoid(v)
# for conv in self.conv:
# cnn_out_temp = conv(embedded_cnn)
# # cat cnn_out的filter_num维度
# # [B, Channel, S, x] -> [B, S, x]
# # filter_size = 2
# cnn_out.append(torch.cat([cnn_out_temp[:, i, :, :] for i in range(2)], dim=-1))
# cnn_out = torch.cat(cnn_out, dim=-1)
# 通过拼接 [B, Channel, S, x] -> [B, S, x]
# print(cnn_out.shape)
cnn_out = torch.cat([cnn_out[:, i, :, :] for i in range(self.cnn_filter_num)], dim=-1)
# cnn_out = cnn_out.squeeze(1)
""" print('cnn_out size', cnn_out.shape) """
# 打印嵌入的 词向量shape 和 隐状态shape。
# print('enc_emb size', embedded.shape)
# print('hidden size', hidden.shape)
cnn_lstm_input = cnn_out
emb_lstm_input = embedded
# output1 = [B, S, 2H] hidden1=[lyr*direct, B, H]
output1, hidden1 = self.lstm['cnn_lstm'](cnn_lstm_input, None)
output2, hidden2 = self.lstm['emb_lstm'](emb_lstm_input, None)
# 在第三维cat起来
output = torch.cat([output1, output2], dim=-1)
# output size: [S, B, 4H]; hidden: ([lyr*direct, B, H], [lyr*direct, B, H])
return output
class EncoderStackedCnndivided(nn.Module):
"""添加额外CNN向量
1、cnn提取特征,后RNN;
2、bert直连LSTM
1+2
"""
def __init__(self, bert, hidden_size, n_layers, cnn_kernel_size, cnn_filter_num):
super(EncoderStackedCnndivided, self).__init__()
self.bert = bert
self.hidden_size = hidden_size
self.n_layers = n_layers
self.cnn_kernel_size = cnn_kernel_size
self.cnn_filter_num = cnn_filter_num
# GRU输入为bert + cnn_out
# self.gru = nn.GRU(bert_size+(bert_size-cnn_kernel_size[1]+1)*cnn_filter_num, hidden_size, n_layers, bidirectional=True, batch_first=False)
# cnn_kernel_size包含高度(多少词一个卷)和宽度(每个词的多少位一个卷)
self.conv = nn.ModuleList()
cnn_layer_num = 1
for i in range(cnn_layer_num):
module_tmp = nn.ModuleDict({
'conv_w_{}'.format(i):
nn.Conv2d(1 if i == 0 else cnn_filter_num,
cnn_filter_num,
cnn_kernel_size,
padding=((cnn_kernel_size[0] - 1) // 2,
(cnn_kernel_size[1] - 1) // 2)),
'conv_v_{}'.format(i):
nn.Conv2d(1 if i == 0 else cnn_filter_num,
cnn_filter_num,
cnn_kernel_size,
padding=((cnn_kernel_size[0] - 1) // 2,
(cnn_kernel_size[1] - 1) // 2)),
})
self.conv.append(module_tmp)
self.lstm = nn.LSTM(
# cnn的每个词对应的输入尺寸为 cnn_layer_num=4层CNN,每层cnn_filter_num=10 filter
input_size=(bert.embedding_size-((cnn_kernel_size[1]-1) % 2 * cnn_layer_num))*cnn_filter_num,
hidden_size=bert.embedding_size, num_layers=n_layers, bidirectional=True, batch_first=True
)
# self.out_size = (bert.embedding_size-((cnn_kernel_size[1]-1) % 2 * cnn_layer_num))*cnn_filter_num
self.out_size = bert.embedding_size*2
# # LSTM输入为bert + cnn_out
# self.lstm = nn.ModuleDict({
# 'cnn_lstm': nn.LSTM(
# # cnn的每个词对应的输入尺寸为 cnn_layer_num=4层CNN,每层cnn_filter_num=10 filter
# input_size=(bert.embedding_size-((cnn_kernel_size[1]-1) % 2 * cnn_layer_num))*cnn_filter_num,
# hidden_size=bert.embedding_size, num_layers=n_layers, bidirectional=True, batch_first=True
# ),
# })
# @torchsnooper.snoop()
def forward(self, word_inputs):
# Note: we run this all at once (over the whole input sequence)
# [B, S, Emb]
embedded = self.bert(word_inputs)[0]
# # 补上padding,使得conv得到seq_len个向量
# batch_size = embedded_cnn.shape[0]
# padding_size = self.cnn_kernel_size[0] - 1
# # [B, padding_size, Emb]
# pad_start = torch.zeros(batch_size, padding_size//2, self.bert_size).to(device)
# pad_end = torch.zeros(batch_size, padding_size//2, self.bert_size).to(device)
# # [B, S, Emb] -> [B, S+p_s, Emb]
# embedded_cnn = torch.cat([pad_start, embedded_cnn, pad_end], dim=1)
# [B, S+p_s, Emb] -> [B, Channel, S+p_s, Emb]
embedded_cnn = embedded.unsqueeze(1)
# cnn_out: [B, Channel, S, x] 向量维度未知
""" print('cnn_out size', embedded_cnn.shape) """
cnn_out = []
cnn_out = embedded_cnn
for i, conv_dict in enumerate(self.conv):
w = conv_dict['conv_w_{}'.format(i)](cnn_out)
v = conv_dict['conv_v_{}'.format(i)](cnn_out)
cnn_out = w * torch.sigmoid(v)
# for conv in self.conv:
# cnn_out_temp = conv(embedded_cnn)
# # cat cnn_out的filter_num维度
# # [B, Channel, S, x] -> [B, S, x]
# # filter_size = 2
# cnn_out.append(torch.cat([cnn_out_temp[:, i, :, :] for i in range(2)], dim=-1))
# cnn_out = torch.cat(cnn_out, dim=-1)
# 通过拼接 [B, Channel, S, x] -> [B, S, x]
# print(cnn_out.shape)
cnn_out = torch.cat([cnn_out[:, i, :, :] for i in range(self.cnn_filter_num)], dim=-1)
# cnn_out = cnn_out.squeeze(1)
cnn_out, hidden = self.lstm(cnn_out)
""" print('cnn_out size', cnn_out.shape) """
output = [cnn_out, embedded]
# 打印嵌入的 词向量shape 和 隐状态shape。
# print('enc_emb size', embedded.shape)
# print('hidden size', hidden.shape)
# output size: [S, B, 4H]; hidden: ([lyr*direct, B, H], [lyr*direct, B, H])
return output
class EncoderStackedCnndividedBert(nn.Module):
"""添加额外CNN向量
1、cnn提取特征,后RNN;
2、bert直连LSTM
1+2
"""
def __init__(self, bert, hidden_size, n_layers, cnn_kernel_size, cnn_filter_num):
super(EncoderStackedCnndividedBert, self).__init__()
self.bert = bert
self.hidden_size = hidden_size
self.n_layers = n_layers
self.cnn_kernel_size = cnn_kernel_size
self.cnn_filter_num = cnn_filter_num
# GRU输入为bert + cnn_out
# self.gru = nn.GRU(bert_size+(bert_size-cnn_kernel_size[1]+1)*cnn_filter_num, hidden_size, n_layers, bidirectional=True, batch_first=False)
# cnn_kernel_size包含高度(多少词一个卷)和宽度(每个词的多少位一个卷)
self.conv = nn.ModuleList()
cnn_layer_num = 1
for i in range(cnn_layer_num):
module_tmp = nn.ModuleDict({
'conv_w_{}'.format(i):
nn.Conv2d(1 if i == 0 else cnn_filter_num,
cnn_filter_num,
cnn_kernel_size,
padding=((cnn_kernel_size[0] - 1) // 2,
(cnn_kernel_size[1] - 1) // 2)),
'conv_v_{}'.format(i):
nn.Conv2d(1 if i == 0 else cnn_filter_num,
cnn_filter_num,
cnn_kernel_size,
padding=((cnn_kernel_size[0] - 1) // 2,
(cnn_kernel_size[1] - 1) // 2)),
})
self.conv.append(module_tmp)
self.lstm = nn.LSTM(
# cnn的每个词对应的输入尺寸为 cnn_layer_num=4层CNN,每层cnn_filter_num=10 filter
input_size=(bert.embedding_size-((cnn_kernel_size[1]-1) % 2 * cnn_layer_num))*cnn_filter_num,
hidden_size=bert.embedding_size, num_layers=n_layers, bidirectional=True, batch_first=True
)
# self.out_size = (bert.embedding_size-((cnn_kernel_size[1]-1) % 2 * cnn_layer_num))*cnn_filter_num
self.out_size = bert.embedding_size*2
# # LSTM输入为bert + cnn_out
# self.lstm = nn.ModuleDict({
# 'cnn_lstm': nn.LSTM(
# # cnn的每个词对应的输入尺寸为 cnn_layer_num=4层CNN,每层cnn_filter_num=10 filter
# input_size=(bert.embedding_size-((cnn_kernel_size[1]-1) % 2 * cnn_layer_num))*cnn_filter_num,
# hidden_size=bert.embedding_size, num_layers=n_layers, bidirectional=True, batch_first=True
# ),
# })
# @torchsnooper.snoop()
def forward(self, word_inputs):
# Note: we run this all at once (over the whole input sequence)
# [B, S, Emb]
embedded = self.bert(word_inputs)[0]
# # 补上padding,使得conv得到seq_len个向量
# batch_size = embedded_cnn.shape[0]
# padding_size = self.cnn_kernel_size[0] - 1
# # [B, padding_size, Emb]
# pad_start = torch.zeros(batch_size, padding_size//2, self.bert_size).to(device)
# pad_end = torch.zeros(batch_size, padding_size//2, self.bert_size).to(device)
# # [B, S, Emb] -> [B, S+p_s, Emb]
# embedded_cnn = torch.cat([pad_start, embedded_cnn, pad_end], dim=1)
# [B, S+p_s, Emb] -> [B, Channel, S+p_s, Emb]
embedded_cnn = embedded.unsqueeze(1)
# cnn_out: [B, Channel, S, x] 向量维度未知
""" print('cnn_out size', embedded_cnn.shape) """
cnn_out = []
cnn_out = embedded_cnn
for i, conv_dict in enumerate(self.conv):
w = conv_dict['conv_w_{}'.format(i)](cnn_out)
v = conv_dict['conv_v_{}'.format(i)](cnn_out)
cnn_out = w * torch.sigmoid(v)
# for conv in self.conv:
# cnn_out_temp = conv(embedded_cnn)
# # cat cnn_out的filter_num维度
# # [B, Channel, S, x] -> [B, S, x]
# # filter_size = 2
# cnn_out.append(torch.cat([cnn_out_temp[:, i, :, :] for i in range(2)], dim=-1))
# cnn_out = torch.cat(cnn_out, dim=-1)
# 通过拼接 [B, Channel, S, x] -> [B, S, x]
# print(cnn_out.shape)
cnn_out = torch.cat([cnn_out[:, i, :, :] for i in range(self.cnn_filter_num)], dim=-1)
# cnn_out = cnn_out.squeeze(1)
cnn_out, hidden = self.lstm(cnn_out)
""" print('cnn_out size', cnn_out.shape) """
output = cnn_out
# 打印嵌入的 词向量shape 和 隐状态shape。
# print('enc_emb size', embedded.shape)
# print('hidden size', hidden.shape)
# output size: [S, B, 4H]; hidden: ([lyr*direct, B, H], [lyr*direct, B, H])
return output
class EncoderStackedCnnDivideUniLSTM(nn.Module):
"""添加额外CNN向量
1、cnn提取特征,后RNN;
2、bert直连LSTM
1+2
"""
def __init__(self, bert, hidden_size, n_layers, cnn_kernel_size, cnn_filter_num):
super(EncoderStackedCnnDivideUniLSTM, self).__init__()
self.bert = bert
self.hidden_size = hidden_size
self.n_layers = n_layers
self.cnn_kernel_size = cnn_kernel_size
self.cnn_filter_num = cnn_filter_num
# GRU输入为bert + cnn_out
# self.gru = nn.GRU(bert_size+(bert_size-cnn_kernel_size[1]+1)*cnn_filter_num, hidden_size, n_layers, bidirectional=True, batch_first=False)
# cnn_kernel_size包含高度(多少词一个卷)和宽度(每个词的多少位一个卷)
self.conv = nn.ModuleList()
cnn_layer_num = 1
for i in range(cnn_layer_num):
module_tmp = nn.ModuleDict({
'conv_w_{}'.format(i):
nn.Conv2d(1 if i == 0 else cnn_filter_num,
cnn_filter_num,
cnn_kernel_size,
padding=((cnn_kernel_size[0] - 1) // 2,
(cnn_kernel_size[1] - 1) // 2)),
'conv_v_{}'.format(i):
nn.Conv2d(1 if i == 0 else cnn_filter_num,
cnn_filter_num,
cnn_kernel_size,
padding=((cnn_kernel_size[0] - 1) // 2,
(cnn_kernel_size[1] - 1) // 2)),
})
self.conv.append(module_tmp)
# self.lstm = nn.LSTM(
# # cnn的每个词对应的输入尺寸为 cnn_layer_num=4层CNN,每层cnn_filter_num=10 filter
# input_size=(bert.embedding_size-((cnn_kernel_size[1]-1) % 2 * cnn_layer_num))*cnn_filter_num,
# hidden_size=bert.embedding_size, num_layers=n_layers, bidirectional=False, batch_first=True
# )
self.out_size = (bert.embedding_size-((cnn_kernel_size[1]-1) % 2 * cnn_layer_num))*cnn_filter_num
# self.out_size = bert.embedding_size
# # LSTM输入为bert + cnn_out
# self.lstm = nn.ModuleDict({
# 'cnn_lstm': nn.LSTM(
# # cnn的每个词对应的输入尺寸为 cnn_layer_num=4层CNN,每层cnn_filter_num=10 filter
# input_size=(bert.embedding_size-((cnn_kernel_size[1]-1) % 2 * cnn_layer_num))*cnn_filter_num,
# hidden_size=bert.embedding_size, num_layers=n_layers, bidirectional=True, batch_first=True
# ),
# })
# @torchsnooper.snoop()
def forward(self, word_inputs):
# Note: we run this all at once (over the whole input sequence)
# [B, S, Emb]
embedded = self.bert(word_inputs)[0]
# # 补上padding,使得conv得到seq_len个向量
# batch_size = embedded_cnn.shape[0]
# padding_size = self.cnn_kernel_size[0] - 1
# # [B, padding_size, Emb]
# pad_start = torch.zeros(batch_size, padding_size//2, self.bert_size).to(device)
# pad_end = torch.zeros(batch_size, padding_size//2, self.bert_size).to(device)
# # [B, S, Emb] -> [B, S+p_s, Emb]
# embedded_cnn = torch.cat([pad_start, embedded_cnn, pad_end], dim=1)
# [B, S+p_s, Emb] -> [B, Channel, S+p_s, Emb]
embedded_cnn = embedded.unsqueeze(1)
# cnn_out: [B, Channel, S, x] 向量维度未知
""" print('cnn_out size', embedded_cnn.shape) """
cnn_out = []
cnn_out = embedded_cnn
for i, conv_dict in enumerate(self.conv):
w = conv_dict['conv_w_{}'.format(i)](cnn_out)
v = conv_dict['conv_v_{}'.format(i)](cnn_out)
cnn_out = w * torch.sigmoid(v)
# for conv in self.conv:
# cnn_out_temp = conv(embedded_cnn)
# # cat cnn_out的filter_num维度
# # [B, Channel, S, x] -> [B, S, x]
# # filter_size = 2
# cnn_out.append(torch.cat([cnn_out_temp[:, i, :, :] for i in range(2)], dim=-1))
# cnn_out = torch.cat(cnn_out, dim=-1)
# 通过拼接 [B, Channel, S, x] -> [B, S, x]
# print(cnn_out.shape)
cnn_out = torch.cat([cnn_out[:, i, :, :] for i in range(self.cnn_filter_num)], dim=-1)
# cnn_out = cnn_out.squeeze(1)
# cnn_out, hidden = self.lstm(cnn_out)
""" print('cnn_out size', cnn_out.shape) """
output = cnn_out
# 打印嵌入的 词向量shape 和 隐状态shape。
# print('enc_emb size', embedded.shape)
# print('hidden size', hidden.shape)
# output size: [S, B, 4H]; hidden: ([lyr*direct, B, H], [lyr*direct, B, H])
return output
class EncoderStackedNoCnnLSTMLSTM(nn.Module):
"""添加额外CNN向量
1、cnn提取特征,后RNN;
2、bert直连LSTM
1+2
"""
def __init__(self, bert, hidden_size, n_layers, cnn_kernel_size, cnn_filter_num):
super(EncoderStackedNoCnnLSTMLSTM, self).__init__()
self.bert = bert
self.hidden_size = hidden_size
self.n_layers = n_layers
self.cnn_kernel_size = cnn_kernel_size
self.cnn_filter_num = cnn_filter_num
# GRU输入为bert + cnn_out
# self.gru = nn.GRU(bert_size+(bert_size-cnn_kernel_size[1]+1)*cnn_filter_num, hidden_size, n_layers, bidirectional=True, batch_first=False)
# cnn_kernel_size包含高度(多少词一个卷)和宽度(每个词的多少位一个卷)
self.conv = nn.ModuleList()
cnn_layer_num = 4
for i in range(cnn_layer_num):
module_tmp = nn.ModuleDict({
'conv_w_{}'.format(i):
nn.Conv2d(1 if i == 0 else cnn_filter_num,
cnn_filter_num,
cnn_kernel_size,
padding=((cnn_kernel_size[0] - 1) // 2,
(cnn_kernel_size[1] - 1) // 2)),
'conv_v_{}'.format(i):
nn.Conv2d(1 if i == 0 else cnn_filter_num,
cnn_filter_num,
cnn_kernel_size,
padding=((cnn_kernel_size[0] - 1) // 2,
(cnn_kernel_size[1] - 1) // 2)),
})
self.conv.append(module_tmp)
# LSTM输入为bert + cnn_out
self.lstm = nn.ModuleDict({
'cnn_lstm': nn.LSTM(
# cnn的每个词对应的输入尺寸为 cnn_layer_num=4层CNN,每层cnn_filter_num=10 filter
input_size=(bert.embedding_size-((cnn_kernel_size[1]-1) % 2 * cnn_layer_num))*cnn_filter_num,
hidden_size=hidden_size, num_layers=n_layers, bidirectional=True, batch_first=True
),
'emb_lstm': nn.LSTM(
bert.embedding_size,
hidden_size,
n_layers,
bidirectional=True,
batch_first=False
),
})
# @torchsnooper.snoop()
def forward(self, word_inputs):
# Note: we run this all at once (over the whole input sequence)
# [B, S, Emb]
embedded = self.bert(word_inputs)[0]
emb_lstm_input = embedded
# output1 = [B, S, 2H] hidden1=[lyr*direct, B, H]
output2, hidden2 = self.lstm['emb_lstm'](emb_lstm_input, None)
# 在第三维cat起来
output = output2
# output size: [S, B, 4H]; hidden: ([lyr*direct, B, H], [lyr*direct, B, H])
return output
# TODO
class ALBertSmallCNNLSTMPunc(nn.Module):
# NOTE bert hidden_size=384
def __init__(self, segment_size, output_size, dropout, vocab_size):
super(ALBertSmallCNNLSTMPunc, self).__init__()
self.bert = AutoModel.from_pretrained('./models/albert_chinese_small/')
self.bert.embedding_size = 384
self.hidden_size = 200
print(type(self.bert))
# self.bert_vocab_size = vocab_size
# self.bn = nn.BatchNorm1d(segment_size*self.bert_vocab_size)
# self.fc = nn.Linear(segment_size*self.bert_vocab_size, output_size)
self.encoder = EncoderStackedCnnLSTMLSTM(
bert=self.bert,
hidden_size=self.hidden_size,
n_layers=3,
# 额外的参数
# cnn -> rnn
# NOTE 使用了args作为参数传递工具
cnn_kernel_size=(5, 20),
# rnn -> cnn
# cnn_kernel_size=(3, hidden_size*2),
cnn_filter_num=5
)
# 以rnn输出为输入
self.fc = nn.Linear(
# fc_input:late_fusion `f_t = a_t W_{fa} ◦ σ(a_t W_{fa} W_{ff} + h_t W_{fh} + b_f) + h_t `
# size: [self.hidden_size*2] 双向的尺寸
self.hidden_size*2*2,
output_size
)
# 以单向的rnn输出和CNN输出 作为 输入
# self.fc = nn.Linear(
# # rnn_out
# hidden_size * 2 +
# # cnn_out
# (hidden_size * 2 - self.encoder.cnn_kernel_size[1] + 1) *
# self.encoder.cnn_filter_num,
# num_class
# )
# NOTE rnn_hidden*2 使用bert中间层hidden_state 384
# self.fc = nn.Linear(384*2, output_size)
# self.dropout = nn.Dropout(dropout)
def forward(self, x):
# src = src.transpose(0, 1).contiguous()
x = x.transpose(0, 1)
# print('enc_hidden size', enc_hidden.shape)
# tuple类型([S, B, H], [S, B, H]) ,因为没有batch_first,所以S在B之前
outputs = self.encoder(x) # 输入pack,lstm默认输出pack
# [S,B,H] -> [B, S, H]
outputs = outputs.transpose(0, 1)
# 记录尺寸,进行变换,以对每一时间步的输出进行late fuse
out_size_S = outputs.size(0)
out_size_B = outputs.size(1)
out_size_H = outputs.size(2)
# print(out_size_S, out_size_B)
# print(outputs[1].shape)
outputs = outputs.contiguous()
# print(outputs.shape)
outputs = outputs.view(out_size_S*out_size_B, out_size_H)
outputs = outputs.contiguous()
# for i in range(l):
# print('{} shape:'.format(i), x[i].shape)
# print('x', type(x))
# print('shape', x.shape)
# x = self.fc(self.dropout(self.bn(x)))
x = self.fc(outputs)
return x
class ALBertSmallRNNPunc(nn.Module):
def __init__(self, segment_size, output_size, dropout, vocab_size):
super(ALBertSmallRNNPunc, self).__init__()
self.bert = AutoModel.from_pretrained('./models/albert_chinese_small/')
# self.bert_vocab_size = vocab_size
# self.bn = nn.BatchNorm1d(segment_size*self.bert_vocab_size)
# self.fc = nn.Linear(segment_size*self.bert_vocab_size, output_size)
# 批标准化
# self.gru = nn.GRU(384, 384, 2, bidirectional=True, batch_first=True)
self.lstm = nn.LSTM(384, 384, 2, bidirectional=True, batch_first=True)
# NOTE rnn_hidden*2 使用bert中间层hidden_state 384
self.fc = nn.Linear(384*2, output_size)
self.dropout = nn.Dropout(dropout)
def forward(self, x):
# 修改后
x = self.bert(x)[0]
# 原始版
# x = self.bert(x)
shape1 = x.shape[1]
shape2 = x.shape[2]
x = x.view(x.shape[0], -1)
# x = self.bn(x)
x = x.view(-1, shape1, shape2)
# GRU*************************************
# init_GRU_hidden
def init_gru_hidden(batch_size):
# when NOT bidirection (layer, B, H)
h = Variable(torch.zeros(self.gru.num_layers*2, batch_size, self.gru.hidden_size)).to(device)
# h for storing hidden layer weight
return h
# init_LSTM_hidden
def init_lstm_hidden(batch_size):
# when NOT bidirection (layer, B, H)
h = Variable(torch.zeros(self.lstm.num_layers*2, batch_size, self.lstm.hidden_size)).to(device)
c = Variable(torch.zeros(self.lstm.num_layers*2, batch_size, self.lstm.hidden_size)).to(device)
# h for storing hidden layer weight
return (h, c)
# hidden = init_gru_hidden(x.shape[0])
# x, hidden = self.gru(x, hidden)
hidden = init_lstm_hidden(x.shape[0])
x, hidden = self.lstm(x, hidden)
x = x.contiguous()
# ***************************************
# l = len(x)
# for i in range(l):
# print('{} shape:'.format(i), x[i].shape)
# print('x', type(x))
# print('shape', x.shape)
shape1 = x.shape[0]
shape2 = x.shape[1]
x = x.view(-1, x.shape[2])
# x = self.fc(self.dropout(self.bn(x)))
x = self.fc(self.dropout(x))
return x
class ALBertSmallRNNnewLinearPunc(nn.Module):
def __init__(self, segment_size, output_size, dropout, vocab_size):
super(ALBertSmallRNNnewLinearPunc, self).__init__()
print("fucking code**************")
self.bert = AutoModelWithLMHead.from_pretrained('./models/albert_chinese_small/')
# self.bert_vocab_size = vocab_size
# self.bn = nn.BatchNorm1d(segment_size*self.bert_vocab_size)
# self.fc = nn.Linear(segment_size*self.bert_vocab_size, output_size)
# 批标准化
# NOTE dense*2 使用bert中间层 dense hidden_state 128
self.bn = nn.BatchNorm1d(segment_size*128)
# NOTE dense*2 使用bert中间层 dense hidden_state 128
self.gru = nn.GRU(128, 128, 2, bidirectional=True, batch_first=True)
# # rnn_hidden*2 使用bert中间层hidden_state 384
# NOTE dense*2 使用bert中间层 dense hidden_state 128
self.fc = nn.Linear(128*2, output_size)
self.dropout = nn.Dropout(dropout)
def forward(self, x):
# 修改后
# print('input 的shape', x.shape)
x = self.bert.albert(x)[0]
# 384 -> 128
x = self.bert.predictions.dense(x)
# 原始版