-
Notifications
You must be signed in to change notification settings - Fork 0
/
customized_transformers.py
831 lines (763 loc) · 29.9 KB
/
customized_transformers.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
import copy
from abc import ABC
import torch
from torch import nn
from torch.nn import CrossEntropyLoss
# from sentence_transformers import SentenceTransformer
from transformers.models.bert.modeling_bert import BertModel, BertPooler, BertLayer
from transformers.models.deberta.modeling_deberta import (
DebertaModel,
ContextPooler,
DebertaLayer,
)
from transformers.models.deberta_v2.modeling_deberta_v2 import DebertaV2Model
from transformers.models.gpt2.modeling_gpt2 import (
GPT2Block,
GPT2Model,
CausalLMOutputWithCrossAttentions,
GPT2PreTrainedModel,
)
from transformers.models.roberta.modeling_roberta import RobertaModel, RobertaLayer
from transformers.models.t5.modeling_t5 import T5Model, T5Stack
from transformers.models.albert.modeling_albert import AlbertModel
class BertForLatentConnector(BertModel, ABC):
def __init__(self, config, latent_size=64, pad_id=None):
super().__init__(config)
self.linear = nn.Linear(config.hidden_size, 2 * latent_size, bias=False)
self.pad_id = pad_id
self.init_weights()
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
past_key_values=None,
use_cache=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
if_pool=True,
):
# no_grad = True
avg_pool = False
outputs = super().forward(
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
past_key_values=past_key_values,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
if attention_mask is None:
attention_mask = (input_ids != self.pad_id).float()
if if_pool:
if avg_pool:
ave_pool = attention_mask / attention_mask.sum(-1, keepdim=True)
pooled_out = torch.bmm(
outputs[0].transpose(1, 2), ave_pool.unsqueeze(-1).half()
).transpose(1, 2)
pooled_out_final = self.pooler(pooled_out)
else:
pooled_out = outputs[0]
pooled_out_final = outputs[1]
return outputs[0], pooled_out_final, pooled_out
return (
outputs[0],
attention_mask,
)
class BertForLatentConnectorAVG(BertModel, ABC):
def __init__(self, config, latent_size=64, pad_id=None):
super().__init__(config)
self.linear = nn.Linear(config.hidden_size, 2 * latent_size, bias=False)
self.pad_id = pad_id
self.init_weights()
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
past_key_values=None,
use_cache=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
if_pool=True,
):
# no_grad = True1
avg_pool = True
outputs = super().forward(
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
past_key_values=past_key_values,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
if attention_mask is None:
attention_mask = input_ids != self.pad_id
if if_pool:
if avg_pool:
ave_pool = (attention_mask / attention_mask.sum(-1, keepdim=True)).to(
outputs[0].dtype
)
pooled_out = torch.bmm(
outputs[0].transpose(1, 2), ave_pool.unsqueeze(-1)
).transpose(1, 2)
pooled_out_final = self.pooler(pooled_out)
else:
pooled_out = outputs[0]
pooled_out_final = outputs[1]
return outputs[0], pooled_out_final, pooled_out
return (
outputs[0],
attention_mask,
)
class BertForLatentConnectorNew(BertForLatentConnector, ABC):
def __init__(self, config, latent_size=64, pad_id=None):
super().__init__(config=config, latent_size=latent_size, pad_id=pad_id)
self.linear_forbert = BertLayer(config)
self.init_weights()
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
past_key_values=None,
use_cache=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
if_pool=False,
):
avg_pool = True
with torch.no_grad():
outputs = super().forward(
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
past_key_values=past_key_values,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
if_pool=if_pool,
)
# outputs[0]: hidden, outputs[1]: attention_mask
if attention_mask is None:
attention_mask = outputs[1]
input_shape = input_ids.size()
device = input_ids.device
extended_attention_mask = self.get_extended_attention_mask(
attention_mask, input_shape, device
)
layer_outputs = self.linear_forbert(
hidden_states=outputs[0], attention_mask=extended_attention_mask
)
hidden_states = layer_outputs[0]
if avg_pool:
ave_pool = attention_mask / attention_mask.sum(-1, keepdim=True)
pooled_out = torch.bmm(
hidden_states.transpose(1, 2), ave_pool.unsqueeze(-1)
).transpose(1, 2)
pooled_out_final = self.pooler(pooled_out)
else:
pooled_out = layer_outputs[0]
pooled_out_final = self.pooler(pooled_out)
return hidden_states, pooled_out_final, pooled_out
class RobertaForLatentConnector(RobertaModel, ABC):
def __init__(self, config, latent_size=64, pad_id=None):
super().__init__(config)
self.linear = nn.Linear(config.hidden_size, 2 * latent_size, bias=False)
self.pad_id = pad_id
self.init_weights()
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
past_key_values=None,
use_cache=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
if_pool=True,
):
outputs = super().forward(
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
past_key_values=past_key_values,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
if attention_mask is None:
attention_mask = (input_ids != self.pad_id).float()
if if_pool:
ave_pool = attention_mask / attention_mask.sum(-1, keepdim=True)
pooled_out = torch.bmm(
outputs[0].transpose(1, 2), ave_pool.unsqueeze(-1).half()
).transpose(1, 2)
pooled_out_final = self.pooler(pooled_out)
return outputs[0], pooled_out_final, pooled_out
# pooled_out_final = outputs[1]
# pooled_out = outputs[0]
# return outputs[0], pooled_out_final, pooled_out
return outputs[0], attention_mask
class RobertaForLatentConnectorNew(RobertaForLatentConnector, ABC):
def __init__(
self,
config,
latent_size=64,
pad_id=None,
):
super().__init__(config=config, latent_size=latent_size, pad_id=pad_id)
self.linear_forbert = RobertaLayer(config)
self.init_weights()
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
past_key_values=None,
use_cache=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
if_pool=False,
):
with torch.no_grad():
outputs = super().forward(
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
past_key_values=past_key_values,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
if_pool=if_pool,
)
# outputs[0]: hidden, outputs[1]: attention_mask
if attention_mask is None:
attention_mask = outputs[1]
input_shape = input_ids.size()
device = input_ids.device
extended_attention_mask = self.get_extended_attention_mask(
attention_mask, input_shape, device
)
layer_outputs = self.linear_forbert(
hidden_states=outputs[0], attention_mask=extended_attention_mask
)
hidden_states = layer_outputs[0]
ave_pool = attention_mask / attention_mask.sum(-1, keepdim=True)
pooled_out = torch.bmm(
hidden_states.transpose(1, 2), ave_pool.unsqueeze(-1)
).transpose(1, 2)
pooled_out_final = self.pooler(pooled_out)
return hidden_states, pooled_out_final, pooled_out
class DebertaForLatentConnector(DebertaModel, ABC):
def __init__(self, config, latent_size=64, pad_id=None):
super().__init__(config)
self.linear = nn.Linear(config.hidden_size, 2 * latent_size, bias=False)
self.pooler = ContextPooler(config)
self.pad_id = pad_id
self.init_weights()
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
inputs_embeds=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
if_pool=True,
):
outputs = super().forward(
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
if attention_mask is None:
attention_mask = (input_ids != self.pad_id).float()
if if_pool:
# ave_pool = attention_mask / attention_mask.sum(-1, keepdim=True)
# pooled_out = torch.bmm(outputs[0].transpose(1, 2), ave_pool.unsqueeze(-1).half()).transpose(1, 2)
# pooled_out_final = self.pooler(pooled_out)
encoder_layer = outputs[0]
pooled_out_final = self.pooler(encoder_layer)
return outputs[0], pooled_out_final, None
return outputs[0], attention_mask
class DebertaForLatentConnectorNew(DebertaForLatentConnector, ABC):
def __init__(self, config, latent_size=64, pad_id=None):
super().__init__(config=config, latent_size=latent_size, pad_id=pad_id)
self.linear_forbert = DebertaLayer(config)
self.init_weights()
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
inputs_embeds=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
if_pool=False,
):
with torch.no_grad():
outputs = super().forward(
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
if_pool=if_pool,
)
if attention_mask is None:
attention_mask = (input_ids != self.pad_id).float()
extended_attention_mask = self.encoder.get_attention_mask(attention_mask)
relative_pos = self.encoder.get_rel_pos(outputs[0], None, None)
rel_embeddings = self.encoder.get_rel_embedding()
layer_outputs = self.linear_forbert(
outputs[0],
extended_attention_mask,
relative_pos=relative_pos,
rel_embeddings=rel_embeddings,
)
hidden_states = layer_outputs
ave_pool = attention_mask / attention_mask.sum(-1, keepdim=True)
pooled_out = torch.bmm(
hidden_states.transpose(1, 2), ave_pool.unsqueeze(-1)
).transpose(1, 2)
pooled_out_final = self.pooler(pooled_out)
return hidden_states, pooled_out_final, pooled_out
class T5EncoderForLatentConnector(T5Model, ABC):
def __init__(self, config, latent_size=64, pad_id=None):
super(T5Model, self).__init__(config)
self.shared = nn.Embedding(config.vocab_size, config.d_model)
encoder_config = copy.deepcopy(config)
encoder_config.is_decoder = False
encoder_config.use_cache = False
encoder_config.is_encoder_decoder = False
self.encoder = T5Stack(encoder_config, self.shared)
self.linear = nn.Linear(config.hidden_size, 2 * latent_size, bias=False)
self.pad_id = pad_id
self.pooler = BertPooler(config)
decoder_config = copy.deepcopy(config)
decoder_config.is_decoder = True
decoder_config.is_encoder_decoder = False
decoder_config.num_layers = config.num_decoder_layers
self.decoder = None # T5Stack(decoder_config, self.shared)
self.init_weights()
# Model parallel
self.model_parallel = False
self.device_map = None
def forward(
self,
input_ids=None,
attention_mask=None,
decoder_input_ids=None,
decoder_attention_mask=None,
head_mask=None,
decoder_head_mask=None,
cross_attn_head_mask=None,
encoder_outputs=None,
past_key_values=None,
inputs_embeds=None,
decoder_inputs_embeds=None,
use_cache=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
use_cache = use_cache if use_cache is not None else self.config.use_cache
return_dict = (
return_dict if return_dict is not None else self.config.use_return_dict
)
# FutureWarning: head_mask was separated into two input args - head_mask, decoder_head_mask
if head_mask is not None and decoder_head_mask is None:
if self.config.num_layers == self.config.num_decoder_layers:
warnings.warn(__HEAD_MASK_WARNING_MSG, FutureWarning)
decoder_head_mask = head_mask
# Encode if needed (training, first prediction pass)
if encoder_outputs is None:
encoder_outputs = self.encoder(
input_ids=input_ids,
attention_mask=attention_mask,
inputs_embeds=inputs_embeds,
head_mask=head_mask,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
encoder_outputs = BaseModelOutput(
last_hidden_state=encoder_outputs[0],
hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
)
hidden_states = encoder_outputs[0]
if self.model_parallel:
torch.cuda.set_device(self.decoder.first_device)
# Set device for model parallelism
if self.model_parallel:
torch.cuda.set_device(self.decoder.first_device)
hidden_states = hidden_states.to(self.decoder.first_device)
if decoder_input_ids is not None:
decoder_input_ids = decoder_input_ids.to(self.decoder.first_device)
if attention_mask is not None:
attention_mask = attention_mask.to(self.decoder.first_device)
if decoder_attention_mask is not None:
decoder_attention_mask = decoder_attention_mask.to(
self.decoder.first_device
)
if self.decoder:
# Decode
decoder_outputs = self.decoder(
input_ids=decoder_input_ids,
attention_mask=decoder_attention_mask,
inputs_embeds=decoder_inputs_embeds,
past_key_values=past_key_values,
encoder_hidden_states=hidden_states,
encoder_attention_mask=attention_mask,
head_mask=decoder_head_mask,
cross_attn_head_mask=cross_attn_head_mask,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
return decoder_outputs + encoder_outputs
else:
if attention_mask is None:
attention_mask = (input_ids != self.pad_id).float()
ave_pool = attention_mask / attention_mask.sum(-1, keepdim=True)
pooled_out = torch.bmm(
encoder_outputs[0].transpose(1, 2), ave_pool.unsqueeze(-1)
).transpose(1, 2)
pooled_out_final = self.pooler(pooled_out)
return encoder_outputs, pooled_out_final, pooled_out
class GPT2ModelForVAE(GPT2Model, ABC):
def __init__(self, config, latent_size=64):
super().__init__(config)
self.latent_size = latent_size
self.linear = nn.Linear(
self.latent_size, config.hidden_size * config.n_layer, bias=False
) # different latent vector for each layer
self.linear_emb = nn.Linear(
self.latent_size, config.hidden_size, bias=False
) # share the same latent vector as the embeddings
self.config = config
self.init_weights()
def forward(
self,
input_ids=None,
past_key_values=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
use_cache=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
latent_as_gpt_emb=True,
latent_as_gpt_memory=True,
):
# def forward(self, input_ids, past=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None,
# latent_as_gpt_emb=False, latent_as_gpt_memory=True):
if past_key_values is None:
past_length = 0
past_key_values = [None] * len(self.h)
else:
if latent_as_gpt_emb:
past_emb = self.linear_emb(
past_key_values
) # used as embeddings to add on other three embeddings
inputs_embeds = self.wte(input_ids) + past_emb.unsqueeze(1)
if latent_as_gpt_memory:
past_key_values = self.linear(past_key_values)
past_split = torch.split(
past_key_values.unsqueeze(1), self.config.hidden_size, dim=2
)
past_split = [
self.h[0].attn._split_heads(
past, self.h[0].attn.num_heads, self.h[0].attn.head_dim
)
for past in past_split
]
past_key_values = list(zip(past_split, past_split))
past_length = 1 # past[0][0].size(-2)
else:
past_length = 0
past_key_values = [None] * len(self.h)
return super().forward(
inputs_embeds=inputs_embeds,
past_key_values=past_key_values,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
)
class GPT2ForLatentConnector(GPT2PreTrainedModel, ABC):
def __init__(
self, config, latent_size=64, latent_as_gpt_emb=True, latent_as_gpt_memory=True
):
super().__init__(config)
self.transformer = GPT2ModelForVAE(config, latent_size=latent_size)
self.lm_head = nn.Linear(config.n_embd, config.vocab_size)
self.init_weights()
self.tie_weights()
self.latent_as_gpt_emb = latent_as_gpt_emb
self.latent_as_gpt_memory = latent_as_gpt_memory
def tie_weights(self):
"""Make sure we are sharing the input and output embeddings.
Export to TorchScript can't handle parameter sharing so we are cloning them instead.
"""
self._tie_or_clone_weights(self.lm_head, self.transformer.wte)
def forward(
self,
input_ids=None,
past=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
labels=None,
use_cache=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
label_ignore=None,
):
return_dict = (
return_dict if return_dict is not None else self.config.use_return_dict
)
transformer_outputs = self.transformer(
input_ids,
past_key_values=past,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
latent_as_gpt_emb=self.latent_as_gpt_emb,
latent_as_gpt_memory=self.latent_as_gpt_memory,
)
hidden_states = transformer_outputs[0]
# Set device for model parallelism
# if self.model_parallel:
# torch.cuda.set_device(self.transformer.first_device)
# hidden_states = hidden_states.to(self.lm_head.weight.device)
# print(hidden_states.sum(),'\n')
# import pdb
# pdb.set_trace()
lm_logits = self.lm_head(hidden_states)
loss = None
if labels is not None:
# Shift so that tokens < n predict n
shift_logits = lm_logits[..., :-1, :].contiguous()
shift_labels = labels[..., 1:].contiguous()
# Flatten the tokens
# loss_fct = CrossEntropyLoss()
loss_fct = CrossEntropyLoss(ignore_index=label_ignore, reduction="none")
loss = loss_fct(
shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1)
)
loss = torch.sum(loss.view(-1, shift_labels.shape[-1]), -1)
if not return_dict:
output = (lm_logits,) + transformer_outputs[1:]
return ((loss,) + output) if loss is not None else output
return CausalLMOutputWithCrossAttentions(
loss=loss,
logits=lm_logits,
past_key_values=transformer_outputs.past_key_values,
hidden_states=transformer_outputs.hidden_states,
attentions=transformer_outputs.attentions,
cross_attentions=transformer_outputs.cross_attentions,
)
class GPT2ModelForVAENew(GPT2ModelForVAE, ABC):
def __init__(self, config, latent_size=64):
super().__init__(config=config, latent_size=latent_size)
self.linear = nn.Linear(
self.latent_size, config.hidden_size * (config.n_layer + 1), bias=False
)
# config1 = copy.deepcopy(config)
# config1.n_inner = config.hidden_size*12
# net1=GPT2Block(config1)
# def count_parameters(model):
# return sum(p.numel() for p in model.parameters() if p.requires_grad)
# import pdb
# pdb.set_trace()
self.h.append(GPT2Block(config))
self.init_weights()
self.tie_weights()
def change_order(self, extra_num=1):
self.h = nn.ModuleList([self.h[-1], *self.h[:-1]])
self.config.n_layer += extra_num
class GPT2ForLatentConnectorNew(GPT2ForLatentConnector, ABC):
def __init__(
self, config, latent_size=64, latent_as_gpt_emb=True, latent_as_gpt_memory=True
):
super().__init__(
config=config,
latent_size=latent_size,
latent_as_gpt_emb=latent_as_gpt_emb,
latent_as_gpt_memory=latent_as_gpt_memory,
)
self.transformer = GPT2ModelForVAENew(config, latent_size=latent_size)
self.latent_as_gpt_emb = latent_as_gpt_emb
self.latent_as_gpt_memory = latent_as_gpt_memory
class GPT2ModelForVAENew2(GPT2ModelForVAE, ABC):
def __init__(self, config, latent_size=64):
super().__init__(config=config, latent_size=latent_size)
self.linear = nn.Linear(
self.latent_size, config.hidden_size * (config.n_layer + 1), bias=False
)
config1 = copy.deepcopy(config)
config1.n_inner = config.hidden_size * 12
self.h.append(GPT2Block(config1))
self.init_weights()
self.tie_weights()
def change_order(self, extra_num=1):
self.h = nn.ModuleList([self.h[-1], *self.h[:-1]])
self.config.n_layer += extra_num
class GPT2ForLatentConnectorNew2(GPT2ForLatentConnector, ABC):
def __init__(
self, config, latent_size=64, latent_as_gpt_emb=True, latent_as_gpt_memory=True
):
super().__init__(
config=config,
latent_size=latent_size,
latent_as_gpt_emb=latent_as_gpt_emb,
latent_as_gpt_memory=latent_as_gpt_memory,
)
self.transformer = GPT2ModelForVAENew2(config, latent_size=latent_size)
self.latent_as_gpt_emb = latent_as_gpt_emb
self.latent_as_gpt_memory = latent_as_gpt_memory
class AlbertForLatentConnector(AlbertModel, ABC):
def __init__(self, config, latent_size=64, pad_id=None):
super().__init__(config)
self.linear = nn.Linear(config.hidden_size, 2 * latent_size, bias=False)
self.pad_id = pad_id
self.init_weights()
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
if_pool=True,
):
avg_pool = True
outputs = super().forward(
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
if attention_mask is None:
attention_mask = (input_ids != self.pad_id).float()
if if_pool:
if avg_pool:
ave_pool = attention_mask / attention_mask.sum(-1, keepdim=True)
pooled_out = torch.bmm(
outputs[0].transpose(1, 2), ave_pool.unsqueeze(-1).half()
).transpose(1, 2)
pooled_out_final = self.pooler_activation(self.pooler(pooled_out[:, 0]))
else:
pooled_out = outputs[0]
pooled_out_final = outputs[1]
return outputs[0], pooled_out_final, pooled_out
return (
outputs[0],
attention_mask,
)