-
Notifications
You must be signed in to change notification settings - Fork 3
/
sentence_attribute_control.py
1471 lines (1195 loc) · 59.1 KB
/
sentence_attribute_control.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
from __future__ import print_function
import logging
import os
import json
from dgmvae import evaluators, utt_utils
from dgmvae.dataset import corpora
from dgmvae.dataset import data_loaders
from dgmvae.models.sent_models import *
from dgmvae.utils import prepare_dirs_loggers, get_time
from dgmvae.multi_bleu import multi_bleu_perl
from dgmvae.options import get_parser
import yelp_datautil
logger = logging.getLogger()
ID_PAD = 0
ID_UNK = 1
ID_BOS = 2
ID_EOS = 3
#------------------------------ utils -----------------------------------#
import math
def log_gaussian(z, mean=None, log_var=None):
assert len(z.size()) == 2
if mean is None:
mean = torch.zeros_like(z)
if log_var is None:
log_var = torch.zeros_like(z)
log_p = - (z - mean) * (z - mean) / (2 * torch.exp(log_var) - 0.5 * log_var - 0.5 * math.log(math.pi * 2))
return log_p.sum(dim=-1)
#------------------------------ model -----------------------------------#
import torch
import torch.nn as nn
import torch.nn.functional as F
# from dgmvae.dataset.corpora import PAD, BOS, EOS, UNK
from torch.autograd import Variable
from dgmvae import criterions
from dgmvae.enc2dec.decoders import DecoderRNN
from dgmvae.enc2dec.encoders import EncoderRNN
from dgmvae.utils import INT, FLOAT, LONG, cast_type
from dgmvae import nn_lib
import numpy as np
from dgmvae.models.model_bases import BaseModel
from dgmvae.enc2dec.decoders import GEN, TEACH_FORCE
from dgmvae.utils import Pack, kl_anneal_function, interpolate, idx2onehot
import itertools
import math
from dgmvae.models.model_bases import summary
class GELU(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x):
return F.gelu(x)
class Classifier(nn.Module):
def __init__(self, vocab_size, id_to_word, config):
super().__init__()
self.config=config
self.vocab = id_to_word
# self.rev_vocab = corpus.rev_vocab
self.vocab_size = vocab_size
self.embed_size = config.embed_size
self.max_utt_len = config.max_utt_len
self.go_id = ID_BOS
self.eos_id = ID_EOS
self.unk_id = ID_UNK
self.pad_id = ID_PAD
self.eos = id_to_word[3]
self.pad = id_to_word[0]
self.bos = id_to_word[2]
self.num_layer_enc = config.num_layer_enc
self.num_layer_dec = config.num_layer_dec
self.dropout = config.dropout
self.enc_cell_size = config.enc_cell_size
self.dec_cell_size = config.dec_cell_size
self.rnn_cell = config.rnn_cell
self.max_dec_len = config.max_dec_len
self.use_attn = config.use_attn
self.beam_size = config.beam_size
self.utt_type = config.utt_type
self.bi_enc_cell = config.bi_enc_cell
self.attn_type = config.attn_type
self.enc_out_size = self.enc_cell_size * 2 if self.bi_enc_cell else self.enc_cell_size
self.concat_decoder_input = config.concat_decoder_input if "concat_decoder_input" in config else False
self.posterior_sample_n = config.post_sample_num if "post_sample_num" in config else 1
# build model here
self.embedding = nn.Embedding(self.vocab_size, self.embed_size,
padding_idx=self.pad_id)
self.x_encoder = EncoderRNN(self.embed_size, self.enc_cell_size,
dropout_p=self.dropout,
rnn_cell=self.rnn_cell,
variable_lengths=self.config.fix_batch,
bidirection=self.bi_enc_cell,
n_layers=self.num_layer_enc)
self.q_y_mean = nn.Linear(self.enc_out_size, config.latent_size)
self.ebm = nn.Sequential(
nn.Linear(config.latent_size, config.ebm_hidden),
GELU(),
nn.Linear(config.ebm_hidden, config.ebm_hidden),
GELU(),
nn.Linear(config.ebm_hidden, config.num_cls)
)
def ebm_prior(self, z, cls_output=False, temperature=1.):
assert len(z.size()) == 2
if cls_output:
return self.ebm(z)
else:
return temperature * (self.ebm(z.squeeze()) / temperature).logsumexp(dim=1)
def forward(self, data_feed):
out_utts = data_feed[2]
batch_size = out_utts.size(0)
# output encoder
output_embedding = self.embedding(out_utts)
x_outs, x_last = self.x_encoder(output_embedding)
if type(x_last) is tuple:
x_last = x_last[0].view(self.num_layer_enc, 1 + int(self.bi_enc_cell), -1, self.enc_cell_size)[-1]
x_last = x_last.transpose(0, 1).contiguous().view(-1, self.enc_out_size)
else:
x_last = x_last.view(self.num_layer_enc, 1 + int(self.bi_enc_cell), -1, self.enc_cell_size)[-1]
x_last = x_last.transpose(0, 1).contiguous().view(-1,
self.enc_out_size)
# q(z|x)
qz_mean = self.q_y_mean(x_last) # batch x (latent_size*mult_k)
# qz_logvar = self.q_y_logvar(x_last)
logits = self.ebm_prior(qz_mean, cls_output=True)
# sentiment classification
cls_labels = data_feed[1].long().squeeze(-1)
cls_loss = F.cross_entropy(logits, cls_labels)
with torch.no_grad():
cls_acc = (logits.argmax(dim=-1) == cls_labels).float().mean()
cls_acc_pos = ((logits.argmax(dim=-1) == cls_labels).to(torch.uint8) & (cls_labels == 1).to(torch.uint8)).float().sum() / ((cls_labels == 1).sum() + 10e-10)
cls_acc_neg = ((logits.argmax(dim=-1) == cls_labels).to(torch.uint8) & (cls_labels == 0).to(torch.uint8)).float().sum() / ((cls_labels == 0).sum() + 10e-10)
return cls_loss, cls_acc, cls_acc_pos, cls_acc_neg
class GMVAE(BaseModel):
def __init__(self, vocab_size, id_to_word, config):
super(GMVAE, self).__init__(config)
self.vocab = id_to_word
# self.rev_vocab = corpus.rev_vocab
self.vocab_size = vocab_size
self.embed_size = config.embed_size
self.max_utt_len = config.max_utt_len
self.go_id = ID_BOS
self.eos_id = ID_EOS
self.unk_id = ID_UNK
self.pad_id = ID_PAD
self.eos = id_to_word[3]
self.pad = id_to_word[0]
self.bos = id_to_word[2]
self.num_layer_enc = config.num_layer_enc
self.num_layer_dec = config.num_layer_dec
self.dropout = config.dropout
self.enc_cell_size = config.enc_cell_size
self.dec_cell_size = config.dec_cell_size
self.rnn_cell = config.rnn_cell
self.max_dec_len = config.max_dec_len
self.use_attn = config.use_attn
self.beam_size = config.beam_size
self.utt_type = config.utt_type
self.bi_enc_cell = config.bi_enc_cell
self.attn_type = config.attn_type
self.enc_out_size = self.enc_cell_size * 2 if self.bi_enc_cell else self.enc_cell_size
self.concat_decoder_input = config.concat_decoder_input if "concat_decoder_input" in config else False
self.posterior_sample_n = config.post_sample_num if "post_sample_num" in config else 1
# build model here
self.embedding = nn.Embedding(self.vocab_size, self.embed_size,
padding_idx=self.pad_id)
self.dec_embedding = nn.Embedding(self.vocab_size, self.embed_size,
padding_idx=self.pad_id)
self.x_encoder = EncoderRNN(self.embed_size, self.enc_cell_size,
dropout_p=self.dropout,
rnn_cell=self.rnn_cell,
variable_lengths=self.config.fix_batch,
bidirection=self.bi_enc_cell,
n_layers=self.num_layer_enc)
self.decoder = DecoderRNN(self.vocab_size, self.max_dec_len,
self.embed_size + self.config.latent_size if self.concat_decoder_input else self.embed_size,
self.dec_cell_size,
self.go_id, self.eos_id, self.unk_id,
n_layers=self.num_layer_dec, rnn_cell=self.rnn_cell,
input_dropout_p=self.dropout,
dropout_p=self.dropout,
use_attention=self.use_attn,
attn_size=self.enc_cell_size,
attn_mode=self.attn_type,
use_gpu=self.use_gpu,
tie_output_embed=config.tie_output_embed,
embedding=self.dec_embedding)
self.q_y_mean = nn.Linear(self.enc_out_size, config.latent_size)
self.q_y_logvar = nn.Linear(self.enc_out_size, config.latent_size)
self.dec_init_connector = nn_lib.LinearConnector(
config.latent_size,
self.dec_cell_size,
self.rnn_cell == 'lstm',
has_bias=False)
self.nll_loss = criterions.NLLEntropy(self.pad_id, self.config)
self.ebm = nn.Sequential(
nn.Linear(config.latent_size, config.ebm_hidden),
GELU(),
nn.Linear(config.ebm_hidden, config.ebm_hidden),
GELU(),
nn.Linear(config.ebm_hidden, config.num_cls)
)
self.return_latent_key = ('log_qy', 'dec_init_state', 'y_ids', 'z')
self.kl_w = 0.0
@staticmethod
def add_args(parser):
from dgmvae.utils import str2bool
# Latent variable:
parser.add_argument('--latent_size', type=int, default=40, help="The latent size of continuous latent variable.")
parser.add_argument('--mult_k', type=int, default=20, help="The number of discrete latent variables.")
parser.add_argument('--k', type=int, default=5, help="The dimension of discrete latent variable.")
# Network setting:
parser.add_argument('--rnn_cell', type=str, default='gru')
parser.add_argument('--embed_size', type=int, default=512)
parser.add_argument('--utt_type', type=str, default='rnn')
parser.add_argument('--enc_cell_size', type=int, default=512)
parser.add_argument('--dec_cell_size', type=int, default=512)
parser.add_argument('--bi_enc_cell', type=str2bool, default=True)
parser.add_argument('--num_layer_enc', type=int, default=1)
parser.add_argument('--num_layer_dec', type=int, default=1)
parser.add_argument('--use_attn', type=str2bool, default=False)
parser.add_argument('--attn_type', type=str, default='cat')
parser.add_argument('--tie_output_embed', type=str2bool, default=True)
parser.add_argument('--max_utt_len', type=int, default=55)
parser.add_argument('--max_dec_len', type=int, default=55)
parser.add_argument('--max_vocab_cnt', type=int, default=10000)
# Dispersed GMVAE settings:
parser.add_argument('--use_mutual', type=str2bool, default=False)
parser.add_argument('--beta', type=float, default=0.2)
parser.add_argument('--concat_decoder_input', type=str2bool, default=True)
parser.add_argument('--gmm', type=str2bool, default=True)
parser.add_argument('--klw_for_ckl', type=float, default=1.0)
parser.add_argument('--klw_for_zkl', type=float, default=1.0)
parser.add_argument('--pretrain_ae_step', type=int, default=0)
# lsebm
parser.add_argument('--ebm_hidden', type=int, default=200)
parser.add_argument('--e_l_steps', type=int, default=60)
parser.add_argument('--e_prior_sig', type=float, default=1.)
parser.add_argument('--e_l_step_size', type=float, default=0.5)
parser.add_argument('--e_l_with_noise', type=bool, default=True)
parser.add_argument('--dim_target_kl', type=float, default=1.0)
parser.add_argument('--mutual_weight', type=float, default=50.0)
parser.add_argument('--cls_weight', type=float, default=4.0)
parser.add_argument('--num_cls', type=int, default=2)
parser.add_argument('--max_kl_weight', type=float, default=1.)
parser.add_argument('--n_cycle', type=int, default=4)
parser.add_argument('--ratio_increase', type=float, default=0.2)
parser.add_argument('--ratio_zero', type=float, default=0.2)
# new
parser.add_argument('--word_dict_max_num', type=int, default=5)
parser.add_argument('--batch_size', type=int, default=128)
parser.add_argument('--max_sequence_length', type=int, default=60)
parser.add_argument('--task', type=str, default='yelp')
parser.add_argument('--data_path', type=str, default='data/yelp/processed_files/')
# new
parser.add_argument('--pretrain_cls_path', type=str, default='ckpts/yelp/pretrained/cls.pt')
parser.add_argument('--cls_max_epoch', type=int, default=2)
parser.add_argument('--cls_eval_step', type=int, default=4000)
return parser
def get_optimizer(self, config):
if config.op == 'adam':
return torch.optim.Adam([
{'params': [p[1] for p in self.named_parameters() if 'ebm' not in p[0] and p[1].requires_grad]},
{'params': [p[1] for p in self.named_parameters() if 'ebm' in p[0] and p[1].requires_grad], 'lr': 0.0001},
],
lr=config.init_lr)
def sample_p_0(self, n):
return torch.randn(*[n, self.config.latent_size]).cuda()
def sample_langevin_prior_z(self, z, verbose=False, y=None):
args = self.config
z = z.clone().detach().requires_grad_(True)
batch_size = z.size(0)
assert z.grad is None
for i in range(args.e_l_steps):
if y is None:
en = - self.ebm_prior(z)
else:
en = - self.ebm_prior(z, cls_output=True)[range(batch_size), y]
z_grad = torch.autograd.grad(en.sum(), z)[0]
z = z - 0.5 * args.e_l_step_size * args.e_l_step_size * (z_grad + z / (args.e_prior_sig * args.e_prior_sig))
if args.e_l_with_noise:
z += args.e_l_step_size * torch.randn_like(z)
if (i % 5 == 0 or i == args.e_l_steps - 1) and verbose:
logger.info('Langevin prior {:3d}/{:3d}: energy={:8.3f}'.format(i+1, args.e_l_steps, en.sum().item()))
z_grad_norm = z_grad.view(batch_size, -1).norm(dim=1).mean()
return z.detach().clone(), z_grad_norm
def ebm_prior(self, z, cls_output=False, temperature=1.):
assert len(z.size()) == 2
if cls_output:
return self.ebm(z)
else:
return temperature * (self.ebm(z.squeeze()) / temperature).logsumexp(dim=1)
def compute_mi(self, z, eps=1e-15):
z = z.squeeze()
assert len(z.size()) == 2
batch_size = z.size(0)
log_p_y_z = F.log_softmax(self.ebm_prior(z, cls_output=True), dim=-1)
p_y_z = torch.exp(log_p_y_z)
# H(y)
log_p_y = torch.log(torch.mean(p_y_z, dim=0) + eps)
H_y = - torch.sum(torch.exp(log_p_y) * log_p_y)
# H(y|z)
H_y_z = - torch.sum(log_p_y_z * p_y_z) / batch_size
mi = H_y - H_y_z
return mi
def model_sel_loss(self, loss, batch_cnt):
if batch_cnt is not None and batch_cnt < self.config.pretrain_ae_step:
return loss.nll
if "sel_metric" in self.config and self.config.sel_metric == "elbo":
return loss.elbo
return self.valid_loss(loss)
def freeze_recognition_net(self):
for param in self.embedding.parameters():
param.requires_grad = False
for param in self.x_encoder.parameters():
param.requires_grad = False
for param in self.q_y_mean.parameters():
param.requires_grad = False
for param in self.q_y_logvar.parameters():
param.requires_grad = False
for param in self.post_c.parameters():
param.requires_grad = False
for param in self.dec_init_connector.parameters():
param.requires_grad = False
def freeze_generation_net(self):
for param in self.decoder.parameters():
param.requires_grad = False
self.gaussian_mus.requires_grad = False
self.gaussian_logvar.requires_grad = False
def unfreeze_all(self):
for param in self.parameters():
param.requires_grad = True
def backward(self, batch_cnt, loss, step=None, vae_kl_weight=1.):
total_loss = self.valid_loss(loss, batch_cnt, step=step, vae_kl_weight=vae_kl_weight)
total_loss.backward()
def valid_loss(self, loss, batch_cnt=None, step=None, vae_kl_weight=1.):
if batch_cnt is not None:
step = batch_cnt
if batch_cnt is not None and batch_cnt < self.config.pretrain_ae_step:
return loss.nll
if step == self.config.pretrain_ae_step:
self.flush_valid = True
mi_weight = self.config.mutual_weight
cls_weight = self.config.cls_weight
if vae_kl_weight > 0.0:
total_loss = loss.nll + vae_kl_weight * (loss.zkl - loss.prob_pos + loss.prob_neg) - mi_weight * loss.mi + cls_weight * loss.cls_loss
else:
total_loss = loss.nll + cls_weight * loss.cls_loss
return total_loss
def reparameterization(self, mu, logvar, sample=True):
if self.training or sample:
std = torch.exp(0.5 * logvar)
z = self.torch2var(torch.randn(mu.size()))
z = z * std + mu
return z
else:
return mu
def zkl_loss(self, tgt_probs, mean, log_var, mean_prior=True):
mean = mean.view(-1, self.config.mult_k, self.config.latent_size)
log_var = log_var.view(-1, self.config.mult_k, self.config.latent_size)
if mean_prior:
tgt_probs_ = tgt_probs.unsqueeze(-1).expand(-1, -1, -1, self.config.latent_size)
eta1 = self.gaussian_mus / torch.exp(self.gaussian_logvar) # eta1 = \Sigma^-1 * mu
eta2 = -0.5 * torch.pow(torch.exp(self.gaussian_logvar), -1)
Eeta1 = torch.sum(tgt_probs_ * eta1, dim=-2) # [batch_size, mult_k, latent_size]
Eeta2 = torch.sum(tgt_probs_ * eta2, dim=-2)
Emu = -0.5 * Eeta1 / Eeta2
Evar = -0.5 * torch.pow(Eeta2, -1)
# [batch_size, mult_k, latent_size]
kl = 0.5 * (
torch.sum(log_var.exp().div(Evar), dim=-1)
+ torch.sum((Emu - mean).pow(2) / Evar, dim=-1)
- mean.size(-1)
+ torch.sum(Evar.log() - log_var, dim=-1)
)
# [batch_size, mult_k]
return kl
mu_repeat = mean.unsqueeze(-2).expand(-1, -1, self.config.k, -1) # batch_size x k x z_dim
logvar_repeat = log_var.unsqueeze(-2).expand(-1, -1, self.config.k, -1)
gaussian_logvars = self.gaussian_logvar
kl = 0.5 * (
torch.sum(logvar_repeat.exp().div(gaussian_logvars.exp()), dim=-1)
+ torch.sum((self.gaussian_mus - mu_repeat).pow(2) / gaussian_logvars.exp(), dim=-1)
- mean.size(-1)
+ torch.sum((gaussian_logvars - logvar_repeat), dim=-1)
) # batch_size x mult_k x k
return torch.sum(kl * tgt_probs, dim=-1) # batch_size*mult_k
def dispersion(self, tgt_probs):
# tgt_probs: batch_size x mult_k x k
tgt_probs_ = tgt_probs.unsqueeze(-1).expand(-1, -1, -1, self.config.latent_size)
eta1 = self.gaussian_mus / torch.exp(self.gaussian_logvar) # eta1 = \Sigma^-1 * mu
eta2 = -0.5 * torch.pow(torch.exp(self.gaussian_logvar), -1)
Eeta1 = torch.sum(tgt_probs_ * eta1, dim=-2) # [batch_size, mult_k, latent_size]
Eeta2 = torch.sum(tgt_probs_ * eta2, dim=-2)
AE = -0.25 * Eeta1 * Eeta1 / Eeta2 - 0.5 * torch.log(-2 * Eeta2) # [batch_size, mult_k, latent_size]
AE = torch.mean(torch.sum(AE, dim=(-1, -2)))
EA = torch.sum(-0.25 * eta1 * eta1 / eta2 - 0.5 * torch.log(-2 * eta2), dim=-1) # [mult_k, k]
EA = torch.mean(torch.sum(tgt_probs * EA, dim=(-1,-2)))
return EA-AE
def param_var(self, tgt_probs):
# Weighted variance of natural parameters
# tgt_probs: batch_size x mult_k x k
tgt_probs_ = tgt_probs.unsqueeze(-1).expand(-1, -1, -1, self.config.latent_size)
eta1 = self.gaussian_mus / torch.exp(self.gaussian_logvar) # eta1 = \Sigma^-1 * mu
eta2 = -0.5 * torch.pow(torch.exp(self.gaussian_logvar), -1)
var_eta1 = torch.sum(tgt_probs_ * (eta1 * eta1), dim=-2) - torch.sum(tgt_probs_ * eta1, dim=-2).pow(2)
var_eta2 = torch.sum(tgt_probs_ * (eta2 * eta2), dim=-2) - torch.sum(tgt_probs_ * eta2, dim=-2).pow(2)
return torch.sum(var_eta1 + var_eta2) / tgt_probs.size(0)
def st_forward(self, data_feed, mode, gen_type='greedy', sample_n=1, batch_cnt=1, return_latent=False, vae_kl_weight=1.):
posterior_sample_n = self.posterior_sample_n if self.training else 1
# if type(data_feed) is tuple:
# data_feed = data_feed[0]
# batch_size = len(data_feed['output_lens'])
# out_utts = self.np2var(data_feed['outputs'], LONG)
out_utts = data_feed[2]
batch_size = out_utts.size(0)
# output encoder
output_embedding = self.embedding(out_utts)
x_outs, x_last = self.x_encoder(output_embedding)
if type(x_last) is tuple:
x_last = x_last[0].view(self.num_layer_enc, 1 + int(self.bi_enc_cell), -1, self.enc_cell_size)[-1]
x_last = x_last.transpose(0, 1).contiguous().view(-1, self.enc_out_size)
else:
x_last = x_last.view(self.num_layer_enc, 1 + int(self.bi_enc_cell), -1, self.enc_cell_size)[-1]
x_last = x_last.transpose(0, 1).contiguous().view(-1,
self.enc_out_size)
# q(z|x)
qz_mean = self.q_y_mean(x_last) # batch x (latent_size*mult_k)
qz_logvar = self.q_y_logvar(x_last)
sample_z = self.reparameterization(qz_mean.repeat(posterior_sample_n, 1),
qz_logvar.repeat(posterior_sample_n, 1),
sample=True) # batch x (latent_size*mult_k)
return qz_mean
def st_sampling(self, z):
dec_init_state = self.dec_init_connector(z)
_, _, outputs = self.decoder(z.size(0),
None, dec_init_state,
mode=GEN, gen_type="greedy",
beam_size=self.config.beam_size,
latent_variable=z if self.concat_decoder_input else None)
return outputs
def forward(self, data_feed, mode, gen_type='greedy', sample_n=1, batch_cnt=1, return_latent=False, vae_kl_weight=1.):
posterior_sample_n = self.posterior_sample_n if self.training else 1
out_utts = data_feed[2]
batch_size = out_utts.size(0)
# output encoder
output_embedding = self.embedding(out_utts)
x_outs, x_last = self.x_encoder(output_embedding)
if type(x_last) is tuple:
x_last = x_last[0].view(self.num_layer_enc, 1 + int(self.bi_enc_cell), -1, self.enc_cell_size)[-1]
x_last = x_last.transpose(0, 1).contiguous().view(-1, self.enc_out_size)
else:
x_last = x_last.view(self.num_layer_enc, 1 + int(self.bi_enc_cell), -1, self.enc_cell_size)[-1]
x_last = x_last.transpose(0, 1).contiguous().view(-1,
self.enc_out_size)
# q(z|x)
qz_mean = self.q_y_mean(x_last) # batch x (latent_size*mult_k)
qz_logvar = self.q_y_logvar(x_last)
if vae_kl_weight > 0.0:
sample_z = self.reparameterization(qz_mean.repeat(posterior_sample_n, 1),
qz_logvar.repeat(posterior_sample_n, 1),
sample=gen_type != "greedy" or mode != GEN) # batch x (latent_size*mult_k)
else:
sample_z = self.reparameterization(qz_mean.repeat(posterior_sample_n, 1),
qz_logvar.repeat(posterior_sample_n, 1),
sample=False) # batch x (latent_size*mult_k)
# Prepare for decoding
dec_init_state = self.dec_init_connector(sample_z)
# labels = out_utts[:, 1:].contiguous()
# dec_inputs = out_utts[:, 0:-1]
labels = data_feed[5]
dec_inputs = data_feed[4]
if self.config.word_dropout_rate > 0:
# randomly replace decoder input with <unk>
prob = torch.rand(dec_inputs.size())
prob[(dec_inputs.data - self.go_id) * (dec_inputs.data - self.pad_id) * (dec_inputs.data - self.eos_id) == 0] = 1
dec_inputs_copy = dec_inputs.clone()
dec_inputs_copy[prob < self.config.word_dropout_rate] = self.unk_id
dec_inputs = dec_inputs_copy
# decode
dec_outs, dec_last, dec_ctx = self.decoder(batch_size * posterior_sample_n,
dec_inputs.repeat(posterior_sample_n, 1),
dec_init_state,
mode=mode, gen_type=gen_type,
beam_size=self.beam_size,
latent_variable=sample_z if self.concat_decoder_input else None)
# compute loss or return results
if mode == GEN:
return dec_ctx, labels
else:
# RNN reconstruction
nll = self.nll_loss(dec_outs, labels.repeat(posterior_sample_n, 1))
# KL(q(z|x) || p(z))
loss_g_kl = - 0.5 * (1 + qz_logvar - qz_mean ** 2 - qz_logvar.exp())
kl_mask = (loss_g_kl > self.config.dim_target_kl).float()
zkl = (kl_mask * loss_g_kl).sum(dim=1).mean()
logits = self.ebm_prior(sample_z, cls_output=True)
# sentiment classification
cls_labels = data_feed[1].long().squeeze(-1)
cls_loss = F.cross_entropy(logits, cls_labels)
# E_q(z|x) (f(z))
prob_pos = logits.mean()
# E_p(z) (f(z))
z_e_0 = self.sample_p_0(n=self.config.batch_size)
prior_sample_z, prior_z_grad_norm = self.sample_langevin_prior_z(z_e_0, verbose=(batch_cnt%500==0) if batch_cnt else False)
prob_neg = self.ebm_prior(prior_sample_z.detach()).mean()
cd = prob_pos - prob_neg
mi = self.compute_mi(sample_z)
with torch.no_grad():
cls_acc = (logits.argmax(dim=-1) == cls_labels).float().mean()
results = Pack(nll=nll, mi=mi, zkl=zkl, prob_pos=prob_pos, prob_neg=prob_neg, cd=cd, cls_loss=cls_loss, cls_acc=cls_acc)
if return_latent:
# results['log_qy'] = log_qc
results['dec_init_state'] = dec_init_state
# results['y_ids'] = c_ids
results['z'] = sample_z
return results
def sampling_for_likelihood(self, batch_size, data_feed, sample_num, sample_type="LL",
):
# Importance sampling for estimating the log-likelihood
assert sample_type in ("LL", "logLL")
if type(data_feed) is tuple:
data_feed = data_feed[0]
batch_size = len(data_feed['output_lens'])
out_utts = self.np2var(data_feed['outputs'], LONG) # batch_size * seq_len
out_utts = out_utts.repeat(sample_num, 1)
labels = out_utts[:, 1:].contiguous()
dec_inputs = out_utts[:, 0:-1]
output_embedding = self.embedding(out_utts)
x_outs, x_last = self.x_encoder(output_embedding)
if type(x_last) is tuple:
x_last = x_last[0].view(self.num_layer_enc, 1 + int(self.bi_enc_cell), -1, self.enc_cell_size)[-1]
x_last = x_last.transpose(0, 1).contiguous().view(-1, self.enc_out_size)
else:
x_last = x_last.view(self.num_layer_enc, 1 + int(self.bi_enc_cell), -1, self.enc_cell_size)[-1]
x_last = x_last.transpose(0, 1).contiguous().view(-1,
self.enc_out_size)
# q(z|x)
qz_mean = self.q_y_mean(x_last) # batch x (latent_size*mult_k)
qz_logvar = self.q_y_logvar(x_last)
sample_z = self.reparameterization(qz_mean, qz_logvar, sample=True)
# Calculate p(x|z)
dec_init_state = self.dec_init_connector(sample_z)
dec_outs, dec_last, outputs = self.decoder(sample_z.size(0),
dec_inputs, dec_init_state,
mode=TEACH_FORCE,
gen_type=self.config.gen_type,
beam_size=self.config.beam_size,
latent_variable=sample_z if self.concat_decoder_input else None)
nll = F.nll_loss(dec_outs.view(-1, dec_outs.size(-1)), labels.view(-1), reduction="none").view(out_utts.size(0),
-1)
nll = torch.sum(nll, dim=-1)
#(1)
# log D(z) = f(z) + log p_0(z) - log q(z|x)
f_z = self.ebm_prior(sample_z)
log_p_0 = log_gaussian(sample_z.double())
log_q_z = log_gaussian(sample_z.double(), mean=qz_mean.double(), log_var=qz_logvar.double())
assert len(f_z.size()) == 1
assert f_z.size() == log_p_0.size() and log_p_0.size() == log_q_z.size()
log_D = f_z.double() + log_p_0 - log_q_z
#(2)
# D(z) = exp(log D(z))
# denominator = E_q D(z) = D(z).mean()
denominator = log_D.exp().mean()
#(3)
# p(x|z) D(z) = exp(log p(z|x) + log D(z))
# numerator = E_q [p(x|z) D(z)]
assert nll.size() == log_D.size()
numerator = (-nll.double() + log_D).exp()
#(4)
# numerator / denominator
ll = numerator / denominator
ll = ll.view(-1, sample_num)
return ll
def sampling(self, batch_size):
z_e_0 = self.sample_p_0(n=batch_size)
zs, _ = self.sample_langevin_prior_z(z_e_0)
dec_init_state = self.dec_init_connector(zs)
_, _, outputs = self.decoder(zs.size(0),
None, dec_init_state,
mode=GEN, gen_type="greedy",
beam_size=self.config.beam_size,
latent_variable=zs if self.concat_decoder_input else None)
return outputs
#------------------------------ parser -----------------------------------#
from dgmvae.utils import str2bool, process_config
import argparse
import logging
# import dgmvae.models.sent_models as sent_models
# import dgmvae.models.sup_models as sup_models
# import dgmvae.models.dialog_models as dialog_models
def add_default_training_parser(parser):
parser.add_argument('--op', type=str, default='adam')
parser.add_argument('--backward_size', type=int, default=5)
parser.add_argument('--step_size', type=int, default=1)
parser.add_argument('--grad_clip', type=float, default=0.5)
parser.add_argument('--prior_grad_clip', type=float, default=1)
parser.add_argument('--init_w', type=float, default=0.08)
parser.add_argument('--init_lr', type=float, default=0.001)
parser.add_argument('--momentum', type=float, default=0.0)
parser.add_argument('--lr_hold', type=int, default=3)
parser.add_argument('--lr_decay', type=str2bool, default=True)
parser.add_argument('--lr_decay_rate', type=float, default=0.8)
parser.add_argument('--dropout', type=float, default=0.3)
parser.add_argument('--improve_threshold', type=float, default=0.996)
parser.add_argument('--patient_increase', type=float, default=2.0)
parser.add_argument('--early_stop', type=str2bool, default=True)
parser.add_argument('--max_epoch', type=int, default=24)
parser.add_argument('--save_model', type=str2bool, default=True)
parser.add_argument('--use_gpu', type=str2bool, default=True)
parser.add_argument('--gpu_idx', type=int, default=1)
parser.add_argument('--seed', default=3435, type=int)
parser.add_argument('--print_step', type=int, default=100)
parser.add_argument('--eval_step', type=int, default=3500)
# parser.add_argument('--eval_step', type=int, default=3)
parser.add_argument('--num_batch', type=int, default=3500)
parser.add_argument('--fix_batch', type=str2bool, default=False)
parser.add_argument('--ckpt_step', type=int, default=2000)
# parser.add_argument('--batch_size', type=int, default=128)
parser.add_argument('--preview_batch_num', type=int, default=1)
parser.add_argument('--gen_type', type=str, default='greedy')
parser.add_argument('--avg_type', type=str, default='seq')
parser.add_argument('--beam_size', type=int, default=10)
parser.add_argument('--forward_only', type=str2bool, default=False)
parser.add_argument('--load_sess', type=str, default="", help="Load model directory.")
parser.add_argument('--debug', type=bool, default=False)
return parser
def add_default_variational_training_parser(parser):
# KL-annealing
parser.add_argument('--anneal', type=str2bool, default=True)
parser.add_argument('--anneal_function', type=str, default='logistic')
parser.add_argument('--anneal_k', type=float, default=0.0025)
parser.add_argument('--anneal_x0', type=int, default=2500)
parser.add_argument('--anneal_warm_up_step', type=int, default=0)
parser.add_argument('--anneal_warm_up_value', type=float, default=0.000)
# Word dropout & posterior sampling number
parser.add_argument('--word_dropout_rate', type=float, default=0.0)
parser.add_argument('--post_sample_num', type=int, default=1)
parser.add_argument('--sel_metric', type=str, default="elbo", help="select best checkpoint base on what metric.",
choices=['elbo', 'obj'],)
# Other:
parser.add_argument('--aggressive', type=str2bool, default=False)
return parser
def add_default_data_parser(parser):
# Data & logging path
parser.add_argument('--data', type=str, default='yelp')
parser.add_argument('--data_dir', type=str, default='data/yelp')
parser.add_argument('--log_dir', type=str, default='logs/yelp/dgmvae')
# Draw points
parser.add_argument('--fig_dir', type=str, default='figs')
parser.add_argument('--draw_points', type=str2bool, default=False)
return parser
def get_parser(model_class="sent_models"):
parser = argparse.ArgumentParser()
parser.add_argument('--model', type=str, default="GMVAE")
parser = add_default_data_parser(parser)
parser = add_default_training_parser(parser)
parser = add_default_variational_training_parser(parser)
config, unparsed = parser.parse_known_args()
try:
model_name = config.model
model_class = eval(model_name)
parser = model_class.add_args(parser)
except Exception as e:
raise ValueError("Wrong model" + config.model)
config, _ = parser.parse_known_args()
print(config)
config = process_config(config)
return config
#------------------------------ engine -----------------------------------#
import numpy as np
from dgmvae.models.model_bases import summary
import torch
# from dgmvae.dataset.corpora import PAD, EOS, EOT
from dgmvae.enc2dec.decoders import TEACH_FORCE, GEN, DecoderRNN
from dgmvae.utils import get_dekenize, experiment_name, kl_anneal_function
import os
from collections import defaultdict
import logging
from dgmvae import utt_utils
logger = logging.getLogger()
def frange_cycle_zero_linear(n_iter, start=0.0, stop=1.0, n_cycle=4, ratio_increase=0.25, ratio_zero=0.5):
L = np.ones(n_iter) * stop
period = n_iter/n_cycle
step = (stop-start)/(period*ratio_increase) # linear schedule
for c in range(n_cycle):
v, i = start, 0
while v <= stop and (int(i+c*period) < n_iter):
if i < period*ratio_zero:
L[int(i+c*period)] = start
else:
L[int(i+c*period)] = v
v += step
i += 1
return L
class LossManager(object):
def __init__(self):
self.losses = defaultdict(list)
self.backward_losses = []
def add_loss(self, loss):
for key, val in loss.items():
if val is not None and type(val) is not bool:
self.losses[key].append(val.item())
def add_backward_loss(self, loss):
self.backward_losses.append(loss.item())
def clear(self):
self.losses = defaultdict(list)
self.backward_losses = []
def pprint(self, name, window=None, prefix=None):
str_losses = []
for key, loss in self.losses.items():
if loss is None:
continue
avg_loss = np.average(loss) if window is None else np.average(loss[-window:])
str_losses.append("{} {:.3f}".format(key, avg_loss))
if 'nll' in key and 'PPL' not in self.losses:
str_losses.append("PPL {:.3f}".format(np.exp(avg_loss)))
if prefix:
return "{}: {} {}".format(prefix, name, " ".join(str_losses))
else:
return "{} {}".format(name, " ".join(str_losses))
def return_dict(self, window=None):
ret_losses = {}
for key, loss in self.losses.items():
if loss is None:
continue
avg_loss = np.average(loss) if window is None else np.average(loss[-window:])
ret_losses[key] = avg_loss.item()
if 'nll' in key and 'PPL' not in self.losses:
ret_losses[key.split("nll")[0] + 'PPL'] = np.exp(avg_loss).item()
return ret_losses
def avg_loss(self):
return np.mean(self.backward_losses)
def adjust_learning_rate(optimizer, last_lr, decay_rate=0.5):
lr = last_lr * decay_rate
print('New learning rate=', lr)
for param_group in optimizer.param_groups:
param_group['lr'] = param_group['lr'] * decay_rate # all decay half
return lr
def get_sent(model, de_tknize, data, b_id, attn=None, attn_ctx=None, stop_eos=True, stop_pad=True):
ws = []
ids = []
attn_ws = []
has_attn = attn is not None and attn_ctx is not None
for t_id in range(data.shape[1]):
w = model.vocab[data[b_id, t_id]]
_id = data[b_id, t_id]
if has_attn:
a_val = np.max(attn[b_id, t_id])
if a_val > 0.1:
a = np.argmax(attn[b_id, t_id])
attn_w = model.vocab[attn_ctx[b_id, a]]
attn_ws.append("{}({})".format(attn_w, a_val))
if (stop_eos and w in model.eos) or (stop_pad and w == model.pad):
# if w == EOT:
# ws.append(w)
break
if w != model.pad:
ws.append(w)
ids.append(_id)
att_ws = "Attention: {}".format(" ".join(attn_ws)) if attn_ws else ""
if has_attn:
return de_tknize(ws), att_ws
else:
try:
return de_tknize(ws), "", ids
except:
return " ".join(ws), "", ids
def train(model, train_feed, valid_feed, test_feed, config, evaluator, classifier, gen=None):
if gen is None:
gen = generate
patience = 10 # wait for at least 10 epoch before stop
valid_loss_threshold = np.inf
best_valid_loss = np.inf
valid_loss_record = []
learning_rate = config.init_lr
optimizer = model.get_optimizer(config)
done_epoch = 0
epoch = 0
train_loss = LossManager()
model.train()
logger.info(summary(model, show_weights=False))
logger.info("**** Training Begins ****")
logger.info("**** Epoch 0/{} ****".format(config.max_epoch))
# num_batch = train_feed.num_batch
num_batch = config.num_batch
vae_kl_weights = frange_cycle_zero_linear(model.config.max_epoch * num_batch,
start=0.0,
stop=config.max_kl_weight,
n_cycle=config.n_cycle,
ratio_increase=config.ratio_increase,
ratio_zero=config.ratio_zero)
prior_params = [p[1] for p in model.named_parameters() if 'ebm' in p[0] and p[1].requires_grad is True]
likelihood_params = [p[1] for p in model.named_parameters() if 'ebm' not in p[0] and p[1].requires_grad is True]
batch_cnt = 0
while batch_cnt < (config.max_epoch * config.eval_step):
batch = train_feed.next_batch()
if batch is None:
break
if model.config.debug and batch_cnt > 200:
break
optimizer.zero_grad()
vae_kl_weight = vae_kl_weights[batch_cnt]
loss = model(batch, mode=TEACH_FORCE, batch_cnt=batch_cnt, vae_kl_weight=vae_kl_weight)
model.backward(batch_cnt, loss, step=batch_cnt, vae_kl_weight=vae_kl_weight)
torch.nn.utils.clip_grad_norm_(prior_params, config.prior_grad_clip, norm_type=2.)
torch.nn.utils.clip_grad_norm_(likelihood_params, config.grad_clip, norm_type=2.)
optimizer.step()
batch_cnt += 1
train_loss.add_loss(loss)
if batch_cnt % config.print_step == 0:
logger.info('batch/max_batch/ep: {:5d}/ {:5d}/ {:5d} '.format(batch_cnt, train_feed.num_batch, epoch) +
'rec: {:8.3f} '.format(loss.nll) +
'mi: {:10.8f} '.format(loss.mi) +
'zkl: {:8.3f} '.format(loss.zkl) +
'cls_loss: {:8.3f} '.format(loss.cls_loss) +
'cls_acc: {:8.3f} '.format(loss.cls_acc) +
'cd: {:8.3f} '.format(loss.cd) +
'pos_prob: {:8.3f} '.format(loss.prob_pos) +
'prob_neg: {:8.3f} '.format(loss.prob_neg) +
'kl_weight: {:8.3f} '.format(vae_kl_weight) +
'do_ae_train: {}'.format(str(not vae_kl_weight > 0.0))
)
# do bleu eval
if batch_cnt % config.eval_step == 0:
# if batch_cnt % 200 == 0:
evaluation(model, test_feed, train_feed, evaluator, batch_cnt, vae_kl_weight, classifier)