-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathtrain_npi.py
1769 lines (1517 loc) · 90.2 KB
/
train_npi.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
# Train Neural Programming Interfaces #
# #
# Adversarially in tandem with discriminator #
# (or 'Generation Classifier') #
# #
# Fulda, Brown, Wingate, Robinson #
# DRAGN #
# NPI Project #
# 2020 #
"""
Overview:
Classifiers:
- Includes functionality for either training in-tandem with NPI or not
- Includes functionality for loading pretrained classifiers
Style Transfer Inspired Adversarial Loss
Functionality for controlling various network activations:
- Supported neural models:
- GPT2
Functionality for interpretting NPI outputs:
- Not part of the NPI class, allows for reshaping generated 'controlled'
activations and running them through a given neural model
"""
import argparse
import gc
import time
import pickle as pkl
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import CrossEntropyLoss
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
from tqdm import tqdm
from matplotlib import pyplot as plt
from transformers import GPT2LMHeadModel, GPT2Tokenizer
from .modeling_neural_program_interfaces import *
from .train_classifier import Classifier, extract_needed_layers
from .utils import top_k_top_p_filtering
torch.manual_seed(1)
# NPI Code Block ################################################################################################
LOSS_BOOSTING_COEFF = 10000.
# first helper fcns
def my_accuracy(x, y):
"""
Accepts vector of ground truth labels and vector of generated labels
Order not important, as long as dims are equal
x, y are both 1-dim torch.Tensor objects or np.ndarray
"""
x, y = x.squeeze().data.cpu().numpy(), y.squeeze().data.cpu().numpy()
x = np.array([round(xi) for xi in x])
y = np.array([round(yi) for yi in y])
if len(x) != 0:
return len(x[x == y]) / len(x)
else:
return 0.
def load_training_data(file_path, pred_inds, split_ratio=.25): # with test-train split
with open(file_path, 'rb') as datafile:
dataset = pkl.load(datafile)
# rand.shuffle(dataset) # NOTE: WE ASSUME DATA HAS ALREADY BEEN SHUFFLED
max_train = len(dataset) - int(split_ratio * len(dataset))
# This commented-out bit for if you want the validation data to be set aside as you train
# (recommended to just set it aside beforehand by using fewer than the total number of pkl's)
# max_test = len(dataset[max_train:]) - int(split_ratio*len(dataset[max_train:]))
return NPIDataSet(dataset[:max_train], pred_inds), NPIDataSet(dataset[max_train:], pred_inds)
# , NPIDataSet(dataset[max_train:max_train+max_test]), NPIDataSet(dataset[max_train+max_test:]), None
class NPIDataSet(Dataset):
def __init__(self, dataset, pred_inds, permitted_rows=None, start_index=0):
"""
Assumes input dataset is of the form:
[[language_model_activations,
activations_classification,
target_classification (no longer used),
language_model_type,
meta_data,
...
],
...]
With objects of the following types:
language_model_activations : nxmx1 ndarray representing flattened activation sequences (required)
activations_classification : small ndarray representing the sentiment/content classification of the original activations (required)
target_classification : (not required)
language_model_type : str naming the language model being controlled (optional - assumed None)
meta_data : dict recording desired metadata (required for NPI training later)
"""
self.ORIG_ACTIV_INDEX = 0
self.ORIG_LABEL_INDEX = 1
self.TARG_LABEL_INDEX = 2
self.LANG_MODEL_INDEX = 3
self.META_DATA_INDEX = 4
# self.masking_coeff = 1e12
if permitted_rows is None:
self.dataset = dataset
else:
self.dataset = []
for i in range(len(dataset)):
if start_index + i in permitted_rows:
self.dataset.append(dataset[i])
for i in range(len(self.dataset)):
# mask the inf values in the activations to simply be VERY VERY LARGE values
# self.dataset[i][self.ORIG_ACTIV_INDEX][self.dataset[i][self.ORIG_ACTIV_INDEX] == np.inf] = self.masking_coeff
# self.dataset[i][self.ORIG_ACTIV_INDEX][self.dataset[i][self.ORIG_ACTIV_INDEX] == -1.*np.inf] = -1.*self.masking_coeff
# cast everything as torch tensors, extract needed layers
self.dataset[i][self.ORIG_ACTIV_INDEX] = torch.from_numpy(
extract_needed_layers(
self.dataset[i][self.ORIG_ACTIV_INDEX], pis=pred_inds)).double()
self.dataset[i][self.ORIG_LABEL_INDEX] = torch.from_numpy(
np.array(self.dataset[i][self.ORIG_LABEL_INDEX])).double()
self.dataset[i][self.TARG_LABEL_INDEX] = torch.tensor([]) # empty tensor
pass
def __getitem__(self, i):
acts = self.dataset[i][self.ORIG_ACTIV_INDEX]
true_label = self.dataset[i][self.ORIG_LABEL_INDEX]
targ = self.dataset[i][self.TARG_LABEL_INDEX] # None
return acts, true_label, targ, i
def __len__(self):
return len(self.dataset)
def get_row_data(self, i):
return self.dataset[i].copy()
class NPIDataLoader(DataLoader):
def __init__(self, data, batch_size, pin_memory):
super(NPIDataLoader, self).__init__(data, batch_size=batch_size, pin_memory=pin_memory)
self.data = data
def get_row_data(self, dataset_indices):
dataset_indices = dataset_indices.tolist()
rows = []
for index in dataset_indices:
rows.append(self.data.get_row_data(index))
return rows
class GPT2WithNPI(GPT2Model):
r"""
Modified from GPT2Model class in transformers module (from HuggingFace)
Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:
**last_hidden_state**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, hidden_size)``
Sequence of hidden-states at the last layer of the model.
**past**:
list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:
that contains pre-computed hidden-states (key and values in the attention blocks).
Can be used (see `past` input) to speed up sequential decoding.
**hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)
list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)
of shape ``(batch_size, sequence_length, hidden_size)``:
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
**attentions**: (`optional`, returned when ``config.output_attentions=True``)
list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
Examples::
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
model = GPT2Model.from_pretrained('gpt2')
input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1
outputs = model(input_ids)
last_hidden_states = outputs[0] # The last hidden-state is the first element of the output tuple
"""
def __init__(self, config): # NPI added functionality
super(GPT2WithNPI, self).__init__(config) # NPI added functionality
GPT2Model.__init__(self, config) # NPI added functionality
def initialize_npi(self, prediction_indices):
self.perturbation_indices = prediction_indices # NPI added functionality
self.output_hidden_states = True
def forward(self, input_ids, past=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None,
activation_perturbations=None):
input_shape = input_ids.size()
input_ids = input_ids.view(-1, input_shape[-1])
if token_type_ids is not None:
token_type_ids = token_type_ids.view(-1, input_shape[-1])
if position_ids is not None:
position_ids = position_ids.view(-1, input_shape[-1])
if past is None:
past_length = 0
past = [None] * len(self.h)
else:
past_length = past[0][0].size(-2)
if position_ids is None:
position_ids = torch.arange(past_length, input_ids.size(-1) + past_length, dtype=torch.long,
device=input_ids.device)
position_ids = position_ids.unsqueeze(0).expand_as(input_ids)
# Attention mask.
if attention_mask is not None:
attention_mask = attention_mask.view(-1, input_shape[-1])
# We create a 3D attention mask from a 2D tensor mask.
# Sizes are [batch_size, 1, 1, to_seq_length]
# So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
# this attention mask is more simple than the triangular masking of causal attention
# used in OpenAI GPT, we just need to prepare the broadcast dimension here.
attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for
# masked positions, this operation will create a tensor which is 0.0 for
# positions we want to attend and -10000.0 for masked positions.
# Since we are adding it to the raw scores before the softmax, this is
# effectively the same as removing these entirely.
attention_mask = attention_mask.to(dtype=next(self.parameters()).dtype) # fp16 compatibility
attention_mask = (1.0 - attention_mask) * -10000.0
# Prepare head mask if needed
# 1.0 in head_mask indicate we keep the head
# attention_probs has shape bsz x n_heads x N x N
# head_mask has shape n_layer x batch x n_heads x N x N
if head_mask is not None:
if head_mask.dim() == 1:
head_mask = head_mask.unsqueeze(0).unsqueeze(0).unsqueeze(-1).unsqueeze(-1)
head_mask = head_mask.expand(self.config.n_layer, -1, -1, -1, -1)
elif head_mask.dim() == 2:
head_mask = head_mask.unsqueeze(1).unsqueeze(-1).unsqueeze(
-1) # We can specify head_mask for each layer
head_mask = head_mask.to(
dtype=next(self.parameters()).dtype) # switch to fload if need + fp16 compatibility
else:
head_mask = [None] * self.config.n_layer
inputs_embeds = self.wte(input_ids)
position_embeds = self.wpe(position_ids)
if token_type_ids is not None:
token_type_embeds = self.wte(token_type_ids)
else:
token_type_embeds = 0
hidden_states = inputs_embeds + position_embeds + token_type_embeds
hidden_states = self.drop(hidden_states)
output_shape = input_shape + (hidden_states.size(-1),)
presents = ()
all_attentions = []
all_hidden_states = ()
# print("GPT2WithNPI: Total num layers == ", len(self.h))
for i, (block, layer_past) in enumerate(zip(self.h, past)):
if self.output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states.view(*output_shape),)
outputs = block(hidden_states,
layer_past=layer_past,
attention_mask=attention_mask,
head_mask=head_mask[i])
hidden_states, present = outputs[:2]
for j, index in enumerate(self.perturbation_indices):
if i == index:
# GPT2 MODEL: perturbing activation layer == i
# GPT2 MODEL: hidden_states size == hidden_states.size()
# GPT2 MODEL: activation_perturbations[j] size == activation_perturbations[j].size()
hidden_states = hidden_states + activation_perturbations[j]
presents = presents + (present,)
if self.output_attentions:
all_attentions.append(outputs[2])
hidden_states = self.ln_f(hidden_states)
hidden_states = hidden_states.view(*output_shape)
# Add last hidden state
if self.output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
outputs = (hidden_states, presents)
if self.output_hidden_states:
outputs = outputs + (all_hidden_states,)
if self.output_attentions:
# let the number of heads free (-1) so we can extract attention even after head pruning
attention_output_shape = input_shape[:-1] + (-1,) + all_attentions[0].shape[-2:]
all_attentions = tuple(t.view(*attention_output_shape) for t in all_attentions)
outputs = outputs + (all_attentions,)
return outputs # last hidden state, presents, (all hidden_states), (attentions)
class GPT2LMWithNPI(GPT2LMHeadModel):
r"""
Modified from GPT2LMHeadModel class in transformers module (from HuggingFace)
**labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:
Labels for language modeling.
Note that the labels **are shifted** inside the model, i.e. you can set ``lm_labels = input_ids``
Indices are selected in ``[-1, 0, ..., config.vocab_size]``
All labels set to ``-1`` are ignored (masked), the loss is only
computed for labels in ``[0, ..., config.vocab_size]``
Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:
**loss**: (`optional`, returned when ``labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:
Language modeling loss.
**prediction_scores**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, config.vocab_size)``
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
**past**:
list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:
that contains pre-computed hidden-states (key and values in the attention blocks).
Can be used (see `past` input) to speed up sequential decoding.
**hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)
list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)
of shape ``(batch_size, sequence_length, hidden_size)``:
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
**attentions**: (`optional`, returned when ``config.output_attentions=True``)
list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
Examples::
import torch
from transformers import GPT2Tokenizer, GPT2LMHeadModel
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
model = GPT2LMHeadModel.from_pretrained('gpt2')
input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1
outputs = model(input_ids, labels=input_ids)
loss, logits = outputs[:2]
"""
def __init__(self, config): # , npi_config):
super(GPT2LMWithNPI, self).__init__(config)
GPT2LMHeadModel.__init__(self, config) # NPI added functionality
def initialize_npi(self, prediction_indices, lang_model_type='gpt2'):
self.perturbation_indices = prediction_indices # NPI added functionality
# self.output_hidden_states = True
self.transformer = GPT2WithNPI.from_pretrained(
lang_model_type) # (config, self.npi, self.prediction_indices) # NPI added functionality
self.transformer.initialize_npi(prediction_indices)
self.npi_model = None
def forward(self, input_ids, past=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None,
labels=None, activation_perturbations=None):
"""
target_classification : nx1x1 target classification vector # NPI added functionality
"""
transformer_outputs = self.transformer(input_ids,
past=past,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
activation_perturbations=activation_perturbations) # NPI added functionality
hidden_states = transformer_outputs[0]
lm_logits = self.lm_head(hidden_states)
outputs = (lm_logits,) + transformer_outputs[1:]
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(ignore_index=-1)
loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)),
shift_labels.view(-1))
outputs = (loss,) + outputs
return outputs # (loss), lm_logits, presents, (all hidden_states), (attentions)
def obtain_perturbed_GPT2WithNPI_outputs(self, npi_batched_perturbations, perturbation_indices, \
data_rows, tokenizer=None, max_seq_len=10, num_seq_iters=10, device=None,
data_inds=None):
# obtain perturbed GPT2WithNPI outputs: START
LANG_MODEL_ACTS_IND = 0
ACTS_CLASSIF_IND = 1
TARG_CLASSIF_IND = 2
LANG_MODEL_TYPE_IND = 3
META_DATA_IND = 4
ORIG_TEXT_IND = 5
PRED_TEXT_IND = 6
TARG_TEXT_INDEX = 7
GPT2_TEXT_INDEX = 8 # the text of what the gpt2 actually produced
top_k = 1
top_p = .9
temperature = 1.
masking_coeff = 1e12
batched_deltas_shape = npi_batched_perturbations.size()
b = batched_deltas_shape[0]
n = batched_deltas_shape[1]
m = batched_deltas_shape[2]
k = batched_deltas_shape[3]
gpt2_perturbed_outs = []
npi_resulting_text = []
# iterating over batches
for j in range(b):
# create input_ids
tokens = data_rows[j][META_DATA_IND]['orig_tokens']
tokens = torch.tensor(tokens, dtype=torch.long) # , device=device)
tokens = tokens.unsqueeze(0).repeat(1, 1)
tokens = tokens.cuda()
# create list of un-flattened activation_perturbations from current batch elem
# creating curr_perturbs
reshaped = npi_batched_perturbations[j, :, :, 0].view(1, n, m, 1)
# chunking with reshaped size == reshaped.size()
chunked = torch.chunk(reshaped, num_seq_iters * len(self.perturbation_indices), dim=1)
# ^ each hidden layer in the hugging face repo has shape (batch, seq_len, hidden_size)
# casting chunked as list
curr_perturbs = [x.view(1, max_seq_len, m) for x in chunked]
# initializing big_array
# obtain flattened representation of the resulting perturbed forward pass in GPT-2
big_array = [] # nxmx1
sent = data_rows[j][ORIG_TEXT_IND]
generated_sent = ""
# iteratively producing big_array
for i in range(num_seq_iters):
# Now run the model
logits, presents, all_hiddens = self.forward(input_ids=tokens[:, -max_seq_len:], \
activation_perturbations=curr_perturbs[i * len(
self.perturbation_indices):(i + 1) * len(
self.perturbation_indices)])
# all_hiddens is a list of len
# 25 or 13 with tensors of shape (gpt2 medium of small)
# (1,sent_len,1024) or (1,sent_len,768)
# Add to big_array
for index in self.perturbation_indices:
big_array.append(all_hiddens[index]) # .data)
# Now we extract the new token and add it to the list of tokens
next_token_logits = logits[0, -1, :] / temperature
filtered_logits = top_k_top_p_filtering(next_token_logits, top_k=top_k, top_p=top_p)
next_token = torch.multinomial(F.softmax(filtered_logits, dim=-1), num_samples=1)
next_token_list = next_token.tolist()
next_word = tokenizer.decode(next_token_list)
sent = sent + " " + next_word # we just update this so sent remains accurate for dict
generated_sent = generated_sent + next_word + " "
# ...update list of tokens
tokens = torch.cat((tokens, next_token.unsqueeze(0)), dim=1).cuda()
if tokenizer is not None:
npi_sent_for_data_set = tokenizer.decode([x.item() for x in tokens[:, -max_seq_len:].flatten()])
npi_resulting_text.append(
[data_rows[j][ORIG_TEXT_IND], data_rows[j][GPT2_TEXT_INDEX], data_rows[j][TARG_TEXT_INDEX],
npi_sent_for_data_set, sent])
del tokens
# Now the big_array is a list of length (max_seq_len*2) of tensors with shape (1,max_seq_len,1024) or (1,max_seq_len,768)
# completing big_array
big_array = torch.cat(big_array, dim=1)
big_array = big_array.permute(1, 2, 0).view(1, n, m, 1)
# mask the inf values in the activations to simply be VERY VERY LARGE values
# big_array[big_array == float("Inf")] = masking_coeff
# big_array[big_array == -1.*float("Inf")] = -1.*masking_coeffs
# store for later concatenation
gpt2_perturbed_outs.append(big_array)
# iteration stop
# create the end-result of npi_perturbations
# casting output as single torch tensor
resulting_gpt2_activations = torch.cat(gpt2_perturbed_outs, dim=0)
# obtain perturbed GPT2WithNPI outputs: STOP
return resulting_gpt2_activations, npi_resulting_text # this is batched
# NPI Neural Model Code -------------------------------------------------------------------------------
class NPINetwork(nn.Module):
def __init__(self, input_activs_shape, input_targ_shape):
"""
input_activs_shape: tuple of (b, n, m, 1)
b is the number of batches
n x m x 1 slices contain the elements of the original activations, flattened into a 2D array
"""
super(NPINetwork, self).__init__()
print("NPI INITIALIZATION")
self.b = input_activs_shape[0]
self.n = input_activs_shape[1]
self.m = input_activs_shape[2]
self.k = input_activs_shape[3]
# Setting Scaling Factors
fact1 = 2 ** 2
fact2 = 2 ** 3
fact3 = 2 ** 3
# Defining first npi layer
self.first_linear = nn.Sequential(nn.Linear((self.n) * self.m * self.k, self.n // fact1),
nn.ReLU(),
)
self.second_linear = nn.Sequential(nn.Linear(self.n // fact1, self.n // fact1),
nn.ReLU(),
)
self.third_linear = nn.Sequential(nn.Linear(self.n // fact1, self.n // fact2),
nn.ReLU(),
)
self.fourth_linear = nn.Sequential(nn.Linear(self.n // fact2, self.n // fact2),
nn.ReLU(),
)
self.fourth_linear_residual = nn.Sequential(nn.Linear(self.n // fact2, self.n // fact3),
nn.ReLU(),
)
self.fifth_linear = nn.Sequential(nn.Linear(self.n // fact3, self.n // fact2),
nn.ReLU(),
)
self.sixth_linear = nn.Sequential(nn.Linear(self.n // fact2, self.n // fact1),
nn.ReLU(),
)
self.seventh_linear = nn.Sequential(nn.Linear(self.n // fact1, self.n // fact1),
nn.ReLU(),
)
self.last_linear = nn.Sequential(nn.Linear(self.n // fact1, self.n * self.m * self.k),
)
pass
def forward(self, orig_activs):
metadata = {'ordered_hidden_activations': [],
'final_out_preview': None,
'final_out_returned': None,
'concatenated_input': None}
combined = orig_activs # torch.cat((target_label, orig_activs), dim=1)
first_out = self.first_linear(combined.view(-1, (self.n) * self.m * self.k))
second_out = self.second_linear(first_out)
third_out = self.third_linear(second_out)
fourth_out = self.fourth_linear(third_out)
# fourth_out_resid = self.fourth_linear_residual(third_out+fourth_out)
# fifth_out = self.fifth_linear(fourth_out_resid)
# sixth_out = self.sixth_linear(third_out+fifth_out)
# seventh_out = self.seventh_linear(second_out+sixth_out)
# out_linear = self.last_linear(first_out+seventh_out)
fourth_out_resid = self.fourth_linear_residual(fourth_out)
fifth_out = self.fifth_linear(fourth_out_resid)
sixth_out = self.sixth_linear(fifth_out)
seventh_out = self.seventh_linear(sixth_out)
out_linear = self.last_linear(seventh_out)
final_out = out_linear.view(-1, self.n, self.m, self.k)
# metadata['ordered_hidden_activations'] = [first_out.detach().data.cpu().numpy(),
# second_out.detach().data.cpu().numpy(),
# third_out.detach().data.cpu().numpy(),
# fourth_out.detach().data.cpu().numpy(),
# fourth_out_resid.detach().data.cpu().numpy(),
# fifth_out.detach().data.cpu().numpy(),
# sixth_out.detach().data.cpu().numpy(),
# seventh_out.detach().data.cpu().numpy(),
# ]
# metadata['final_out_preview'] = out_linear.detach().data.cpu().numpy()
# metadata['final_out_returned'] = final_out.detach().data.cpu().numpy()
# metadata['concatenated_input'] = combined.detach().data.cpu().numpy()
return final_out # , metadata
# ------------------------------------------------------------------------------------------------------
class ContentClassifier(nn.Module): # classifies NPI outputs
def __init__(self, input_activs_shape, input_targ_shape):
raise NotImplementedError("Content classifier should be pre-trained")
"""
input_activs_shape: tuple of (b, n, m, 1)
b is the number of batches
n x m x 1 slices contain the elements of the original activations, flattened into a 2D array
"""
super(ContentClassifier, self).__init__()
print("ContentClassifier INIT")
self.b = input_activs_shape[0]
self.n = input_activs_shape[1]
self.m = input_activs_shape[2]
self.k = input_activs_shape[3]
self.l = 1 # input_targ_shape[2]
fact1 = 2 ** 3
fact2 = 2 ** 3
fact3 = 2 ** 3
print("Defining ContentClassifier model")
self.linear1 = nn.Sequential(nn.Linear(self.n * self.m * self.k, self.n // fact1),
nn.ReLU())
self.linear1Post = nn.Sequential(nn.Linear(self.n // fact1, self.n // fact1),
nn.ReLU())
self.linear2 = nn.Sequential(nn.Linear(self.n // fact1, self.n // fact1),
nn.ReLU())
self.linear3 = nn.Sequential(nn.Linear(self.n // fact1, self.n // fact2),
nn.ReLU())
self.linear4 = nn.Sequential(nn.Linear(self.n // fact2, self.n // fact2),
nn.ReLU())
self.linear5 = nn.Sequential(nn.Linear(self.n // fact2, self.n // fact3),
nn.ReLU())
self.linear6 = nn.Sequential(nn.Linear(self.n // fact3, self.n // fact3),
nn.ReLU())
self.linear7Pre = nn.Sequential(nn.Linear(self.n // fact3, self.n // fact3),
nn.ReLU())
self.linear7 = nn.Sequential(nn.Linear(self.n // fact3, 1 * self.l * self.k),
nn.Sigmoid())
def forward(self, x):
metadata = {'ordered_hidden_activations': [], 'final_out_preview': None, 'final_out_returned': None}
out1 = self.linear1(x.view(-1, self.n * self.m * self.k))
out1Post = self.linear1Post(out1)
out2 = self.linear2(out1Post)
out3 = self.linear3(out2)
out4 = self.linear4(out3)
out5 = self.linear5(out4)
out6 = self.linear6(out5)
out7Pre = self.linear7Pre(out6)
final_out = self.linear7(out6)
metadata['ordered_hidden_activations'] = [out1.detach().data.cpu().numpy(),
out1Post.detach().data.cpu().numpy(),
out2.detach().data.cpu().numpy(),
out3.detach().data.cpu().numpy(),
out4.detach().data.cpu().numpy(),
out5.detach().data.cpu().numpy(),
out6.detach().data.cpu().numpy(),
out7Pre.detach().data.cpu().numpy(),
]
metadata['final_out_preview'] = final_out.detach().data.cpu().numpy()
metadata['final_out_returned'] = final_out.view(-1, 1, self.l, self.k).detach().data.cpu().numpy()
return final_out.view(-1, 1, self.l, self.k), metadata
class GenerationClassifier(nn.Module): # classifies NPI outputs
def __init__(self, input_activs_shape, input_targ_shape):
"""
input_activs_shape: tuple of (b, n, m, 1)
b is the number of batches
n x m x 1 slices contain the elements of the original activations, flattened into a 2D array
target_label: tuple of (b, 1, m, 1)
the desired label for the predicted activations, as passed into the NPI network
"""
super(GenerationClassifier, self).__init__()
print("GenerationClassifier INIT")
self.b = input_activs_shape[0]
self.n = input_activs_shape[1]
self.m = input_activs_shape[2]
self.k = input_activs_shape[3]
self.l = 1
fact1 = 2 ** 3
fact2 = 2 ** 4
fact3 = 2 ** 5
print("Defining GenerationClassifier model")
self.layer1 = nn.Sequential(nn.Linear(self.n * self.m * self.k, self.n // fact1),
nn.ReLU())
self.layer2 = nn.Sequential(nn.Linear(self.n // fact1, self.n // fact1),
nn.ReLU())
self.layer3 = nn.Sequential(nn.Linear(self.n // fact1, self.n // fact2),
nn.ReLU())
self.layer4 = nn.Sequential(nn.Linear(self.n // fact2, self.n // fact2),
nn.ReLU())
self.layer5 = nn.Sequential(nn.Linear(self.n // fact2, self.n // fact3),
nn.ReLU())
self.layer6 = nn.Sequential(nn.Linear(self.n // fact3, self.n // fact3),
nn.ReLU())
self.layer7 = nn.Sequential(nn.Linear(self.n // fact3, self.l * self.k),
nn.Sigmoid())
def forward(self, x):
metadata = {'ordered_hidden_activations': [], 'final_out_preview': None, 'final_out_returned': None}
out1 = self.layer1(x.view(-1, self.n * self.m * self.k))
out2 = self.layer2(out1)
out3 = self.layer3(out2)
out4 = self.layer4(out3)
out5 = self.layer5(out4)
out6 = self.layer6(out5)
final_out = self.layer7(out6)
# metadata['ordered_hidden_activations'] = [out1.detach().data.cpu().numpy(),
# out2.detach().data.cpu().numpy(),
# out3.detach().data.cpu().numpy(),
# out4.detach().data.cpu().numpy(),
# out5.detach().data.cpu().numpy(),
# out6.detach().data.cpu().numpy(),
# ]
# metadata['final_out_preview'] = final_out.detach().data.cpu().numpy()
# metadata['final_out_returned'] = final_out.view(-1, 1, self.l, self.k).detach().data.cpu().numpy()
return final_out.view(-1, 1, self.l, self.k) # , metadata
class NPILoss(nn.Module):
def __init__(self, discrim_coeff, style_coeff, similarity_coeff, content_classifier_model=None,
generation_classifier_model=None):
super(NPILoss, self).__init__()
self.gamma = discrim_coeff
self.alpha = style_coeff
self.beta = similarity_coeff
self.mse = torch.nn.MSELoss()
self.bce = torch.nn.BCELoss()
if generation_classifier_model is not None:
self.generation_classifier_model = generation_classifier_model
if content_classifier_model is not None:
self.content_classifier_model = content_classifier_model
pass
def forward(self, predicted_activs, true_activs, target_label,
content_classifier_model=None, generation_classifier_model=None, return_loss_data=False):
"""
predicted_activs: torch tensor of shape (n, m, 1, b)
b is the number of batches
n x m x 1 slices contain the elements of the predicted activations, flattened into a 2D array
true_activs: torch tensor of shape (n, m, 1, b)
b is the number of batches
n x m x 1 slices contain the elements of the original activations, flattened into a 2D array
target_label: torch tensor of shape (1, m, 1, b)
the desired label for the predicted activations, as passed into the NPI network
classifier_model: an updated classifier model (optional: use for adversarial training)
"""
generation_classifier_labels, _ = self.generation_classifier_model(predicted_activs)
content_classifier_labels = self.content_classifier_model(predicted_activs).unsqueeze(1).unsqueeze(3)
aggregate_size = torch.cat((generation_classifier_labels, content_classifier_labels), dim=2).size()
classifier_labels = torch.zeros(aggregate_size, dtype=torch.float64).cuda()
classifier_labels[:, :, 0, :] = generation_classifier_labels[:, :, 0, :]
classifier_labels[:, :, 1, :] = content_classifier_labels[:, :, 0, :] # 1: to 1 and to 0
new_discrim_score = self.gamma * self.bce(classifier_labels[:, :, 0, :], target_label[:, :, 0, :].double())
new_style_score = self.alpha * self.bce(classifier_labels[:, :, 1, :],
target_label[:, :, 1, :].double()) # 1: to 1
old_content_score = self.beta * self.mse(predicted_activs, true_activs)
if return_loss_data:
return LOSS_BOOSTING_COEFF * (new_discrim_score + new_style_score + old_content_score), \
{"gen_class_loss": new_discrim_score.item(), "content_class_loss": new_style_score.item(),
"similarity_loss": old_content_score.item()}
return LOSS_BOOSTING_COEFF * (new_discrim_score + new_style_score + old_content_score)
# ------------------------------------------------------------------------------------------------------
def load_models(args, input_activs_shape, input_targ_shape):
npi_type = args.npi_type
content_class_type = args.content_classifier_type
generate_class_type = args.generation_classifier_type
# Creating NPI Model
npi_model = None
if npi_type == "adversarial":
npi_model = NPINetwork(input_activs_shape, input_targ_shape).float()
elif args.npi_model_path is not None:
raise NotImplementedError("NPI should be trained adversarially")
npi_model = torch.load(args.npi_model_path)
npi_model.eval()
else:
raise NotImplementedError("Requested model {} has not been implemented.".format(npi_type))
npi_model.cuda()
# Creating ContentClassifier Model
content_class_model = None
if content_class_type == 'adversarial':
raise NotImplementedError("Content classifier should be pre-trained")
print("INITIALIZING NEW CONTENT CLASSIFIER NETWORK")
content_class_model = ContentClassifier(input_activs_shape, input_targ_shape).float()
elif content_class_type == 'pretrained' and args.content_classifier_path is not None:
print("LOADING PRE-TRAINED CONTENT CLASSIFIER NETWORK")
content_class_model = torch.load(args.content_classifier_path, map_location=torch.device('cpu'))
content_class_model.eval()
else:
raise NotImplementedError("Requested model {} has not been implemented.".format(content_class_type))
content_class_model.cuda()
# Creating GenerationClassifier Model
generate_class_model = None
if generate_class_type == 'adversarial':
generate_class_model = GenerationClassifier(input_activs_shape, input_targ_shape).float()
elif generate_class_type == 'pretrained' and args.generation_classifier_path is not None:
raise NotImplementedError("Generation classifier should be trained adversarially in tandem with NPI")
generate_class_model = torch.load(args.generation_classifier_path)
generate_class_model.eval()
else:
raise NotImplementedError("Requested model {} has not been implemented.".format(generate_class_type))
generate_class_model.cuda()
return npi_model, content_class_model, generate_class_model
def make_classifier_plots(classifier_label, epoch, save_file_path, epoch_losses, false_test_losses, true_test_losses,
train_accuracies, false_test_accuracies, true_test_accuracies):
"""
Plot training progress for classifier network
"""
test_epochs = []
for i, elem in enumerate(true_test_losses):
if elem[0] not in test_epochs:
test_epochs.append(elem[0])
avg_epoch_test_losses = []
avg_epoch_test_accuracies = []
avg_epoch_false_test_losses = []
avg_epoch_false_test_accuracies = []
avg_epoch_train_accuracies = []
num_files = 0
# make_classifier_plots : constructing test / accuracy avgs
for i, ep in enumerate(test_epochs):
curr_ep_losses = [x[1] for x in true_test_losses if x[0] == ep]
curr_ep_accuracies = [x[1] for x in true_test_accuracies if x[0] == ep]
curr_ep_false_losses = [x[1] for x in false_test_losses if x[0] == ep]
curr_ep_false_accuracies = [x[1] for x in false_test_accuracies if x[0] == ep]
# condense everything into lists of averages
if curr_ep_losses:
avg_epoch_test_losses.append(sum(curr_ep_losses) / len(curr_ep_losses))
else:
avg_epoch_test_losses.append(0)
if curr_ep_accuracies:
avg_epoch_test_accuracies.append(sum(curr_ep_accuracies) / len(curr_ep_accuracies))
else:
avg_epoch_test_accuracies.append(0)
if curr_ep_false_losses:
avg_epoch_false_test_losses.append(sum(curr_ep_false_losses) / len(curr_ep_false_losses))
else:
avg_epoch_false_test_losses.append(0)
if curr_ep_false_accuracies:
avg_epoch_false_test_accuracies.append(sum(curr_ep_false_accuracies) / len(curr_ep_false_accuracies))
else:
avg_epoch_false_test_accuracies.append(0)
if train_accuracies is not None:
curr_ep_accuracies = [x[1] for x in train_accuracies if
x[0] == ep] # train_accuracies[i*num_files:(i+1)*num_files]
if curr_ep_accuracies:
avg_epoch_train_accuracies.append(sum(curr_ep_accuracies) / len(curr_ep_accuracies))
else:
avg_epoch_train_accuracies.append(0)
if i == 0:
num_files = len(curr_ep_losses)
avg_epoch_train_losses = []
if epoch_losses is not None:
# make_classifier_plots : averaging epoch losses
for i in range(epoch):
curr_ep_losses = epoch_losses[i * num_files:(i + 1) * num_files]
if curr_ep_losses:
avg_epoch_train_losses.append(sum(curr_ep_losses) / len(curr_ep_losses))
else:
avg_epoch_train_losses.append(0)
# make_classifier_plots
fig1, ax1 = plt.subplots()
if epoch_losses is not None:
ax1.plot(avg_epoch_train_losses, label='average train')
ax1.plot(test_epochs, avg_epoch_test_losses, label='average test')
ax1.plot(test_epochs, avg_epoch_false_test_losses, label='generated test')
ax1.set_xlabel("Epoch")
ax1.set_ylabel("Average Loss")
ax1.set_title("{} Average Losses Per Epoch".format(classifier_label))
plt.legend()
plt.draw()
fig1.savefig(save_file_path + "visualization_epoch{}_{}_train_vs_test_losses.png".format(epoch, classifier_label))
# make_classifier_plots : making plot 2
fig2, ax2 = plt.subplots()
if train_accuracies is not None:
ax2.plot(test_epochs, avg_epoch_train_accuracies, label='average train')
ax2.plot(test_epochs, avg_epoch_test_accuracies, label='average test')
ax2.plot(test_epochs, avg_epoch_false_test_accuracies, label='generated test')
ax2.set_xlabel("Epoch")
ax2.set_ylabel("Average Accuracy")
ax2.set_title("{} Average Accuracies Per Epoch".format(classifier_label))
plt.legend()
plt.draw()
fig2.savefig(
save_file_path + "visualization_epoch{}_{}_train_vs_test_accuracies.png".format(epoch, classifier_label))
return avg_epoch_train_losses, avg_epoch_test_losses, avg_epoch_false_test_losses, avg_epoch_train_accuracies, \
avg_epoch_test_accuracies, avg_epoch_false_test_accuracies, test_epochs
pass
def make_npi_plots(epoch, save_file_path, epoch_losses, test_losses):
"""
Make plots for training progress of NPI network
"""
test_epochs = []
# make_npi_plots: test_losses[0] == test_losses[0]
for i, elem in enumerate(test_losses):
if elem[0] not in test_epochs:
test_epochs.append(elem[0])
avg_epoch_test_losses = []
num_files = 0
# make_npi_plots: obtaining avg test losses
for i, ep in enumerate(test_epochs):
curr_ep_losses = [x[1] for x in test_losses if x[0] == ep]
if i == 0:
num_files = len(curr_ep_losses)
if curr_ep_losses:
avg_epoch_test_losses.append(sum(curr_ep_losses) / len(curr_ep_losses))
else:
avg_epoch_test_losses.append(0)
# make_npi_plots: obtaining avg train losses
avg_epoch_train_losses = []
for i in range(epoch):
curr_ep_losses = epoch_losses[i * num_files:(i + 1) * num_files]
if curr_ep_losses:
avg_epoch_train_losses.append(sum(curr_ep_losses) / len(curr_ep_losses))
else:
avg_epoch_train_losses.append(0)
# make_npi_plots: plotting
fig1, ax1 = plt.subplots()
ax1.plot(avg_epoch_train_losses, label='training')
ax1.plot(test_epochs, avg_epoch_test_losses, label='testing')
ax1.set_xlabel("Epoch")
ax1.set_ylabel("Average Loss")
ax1.set_title("NPI Average Losses Per Epoch")
plt.legend()
plt.draw()
fig1.savefig(save_file_path + "visualization_epoch{}_NPI_train_vs_test_losses.png".format(epoch))
return avg_epoch_train_losses, avg_epoch_test_losses, test_epochs
def train_adversarial_NPI(args): # train NPI and Classifiers in-tandem
"""
***Main function***
"""
start_time = time.time()
LANG_MODEL_ACTS_IND = 0
ACTS_CLASSIF_IND = 1
TARG_CLASSIF_IND = 2
LANG_MODEL_TYPE_IND = 3
META_DATA_IND = 4
ORIG_TEXT_IND = 5
PRED_TEXT_IND = 6
TARG_TEXT_INDEX = 7
GPT2_TEXT_INDEX = 8 # the text of what the gpt2 actually produced
HEAD_START_NUM = args.head_start_num
print("############################################################")
print("<<< USING THE FOLLOWING INPUT ARGUMENTS!!! >>>")
print(args)
print("############################################################")
# initialize function vars
save_file_path = args.save_file_path
train_file_path = args.train_file_path
if not "pkl" in train_file_path: # train file path should have specific format
train_file_path = train_file_path + ".pkl_"
num_pkls = args.num_pkls
train_file_names = [str(pn) for pn in range(num_pkls)] # os.listdir(train_file_path)
# train_file_names.sort()
print("############################################################")
print("<<< NOTE : ONLY FIRST {} FILES IN DATA SET BEING USED >>>".format(num_pkls))
print("############################################################")
device = torch.device('cuda:{}'.format(args.gpu_num))
discrim_coeff = args.discrim_coeff
style_coeff = args.style_coeff
similarity_coeff = args.similarity_coeff
npi_type = args.npi_type
content_class_type = args.content_classifier_type
generate_class_type = args.generation_classifier_type
num_epochs = args.num_epochs
batch_size = args.batch_size
test_freq = args.test_freq
save_freq = args.save_freq
try:
torch.cuda.empty_cache()
# READ IN DATASET
print("Loading Data")
print("<<<<<<<<< NOT FILTERING DATA -- ASSUMING RELATIVE CLASS BALANCE >>>>>>>>>>")
train_data, _ = load_training_data(train_file_path + train_file_names[0], args.perturbation_indices,
split_ratio=.25) # _, _, _ and .25