-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtrain.py
2288 lines (2131 loc) · 88.5 KB
/
train.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
# coding: utf-8
from builtins import NotImplementedError
import argparse
import time
import warnings
import os
import random
import math
import torch
import torch.optim as optim
import numpy as np
import scipy
import pandas as pd
from itertools import chain
try:
from apex import amp
import apex
except ImportError:
warnings.warn(
"Failed to import apex. You can still train in FP32, but you need to install apex for half-precision training."
)
from hashlib import sha1
import wandb
import data
from gflownet_parser import *
from pcfg_neural import MLPPCFG
global global_step
global_step = 0
parser = argparse.ArgumentParser(
description="GFlowNet for hierarchical latent structures"
)
# Arch
parser.add_argument(
"--d_model", type=int, default=256, help="number of hidden units per layer"
)
parser.add_argument("--nlayers", type=int, default=2, help="number of layers")
parser.add_argument("--norm_type", default="preln", choices=["postln", "preln"])
parser.add_argument(
"--nhead",
type=int,
default=4,
help="the number of heads in the encoder/decoder of the transformer model",
)
parser.add_argument(
"--dropout",
type=float,
default=0.0,
help="dropout applied to layers (0 = no dropout)",
)
parser.add_argument("--gfn_arch", default="parser", choices=["parser"])
parser.add_argument(
"--tie_tgt_embedding",
action="store_true",
help="whether to tie transformer target embedding",
)
parser.add_argument(
"--share_grammar_embedding",
action="store_true",
help="whether to use the grammar symbol embeddings for GFN",
)
parser.add_argument(
"--agg_type",
default="none",
choices=["none", "simplemlp", "skipmlp"],
help="Aggregation Type",
)
# Optim
parser.add_argument("--lr", type=float, default=0.01, help="initial learning rate")
parser.add_argument(
"--lr_encoder", type=float, default=None, help="initial learning rate"
)
parser.add_argument("--lr_flow", type=float, default=None, help="initial learning rate")
parser.add_argument(
"--lr_forward", type=float, default=None, help="initial learning rate"
)
parser.add_argument(
"--lr_backward", type=float, default=None, help="initial learning rate"
)
parser.add_argument(
"--lr_grammar", type=float, default=None, help="initial learning rate"
)
parser.add_argument(
"--init_mult_encoder", type=float, default=1.0, help="initialization std multiplier"
)
parser.add_argument(
"--init_mult_flow", type=float, default=1.0, help="initialization std multiplier"
)
parser.add_argument(
"--init_mult_forward", type=float, default=1.0, help="initialization std multiplier"
)
parser.add_argument(
"--init_mult_backward",
type=float,
default=1.0,
help="initialization std multiplier",
)
parser.add_argument("--momentum", type=float, default=0, help="momentum")
parser.add_argument("--adam_beta1", type=float, default=0.9)
parser.add_argument("--adam_beta2", type=float, default=0.99)
parser.add_argument("--adam_beta1_grammar", type=float, default=0.75)
parser.add_argument("--adam_beta2_grammar", type=float, default=0.999)
parser.add_argument("--optimizer", default="adam", choices=["sgd", "adam"])
parser.add_argument(
"--schedule",
default="constant",
choices=[
"constant",
"linear",
"cosine",
"inverse_sqrt",
],
)
parser.add_argument(
"--init_var",
type=float,
default=1,
help="embeddings are initialized with variance emb_var/ninp",
)
parser.add_argument("--clip", type=float, default=3, help="gradient clipping")
parser.add_argument("--wd", type=float, default=0.0, help="weight decay")
parser.add_argument(
"--grad_acc", type=int, default=1, help="number of gradient accumulation steps"
)
parser.add_argument("--batch_size", type=int, default=32, help="batch size")
parser.add_argument("--valid_batch_size", type=int, default=64, help="batch size")
parser.add_argument(
"--batch_group_size",
type=int,
default=999999,
help="batch group size for grouped shuffling",
)
# Train
parser.add_argument("--seqlen", type=int, default=20, help="sequence length")
parser.add_argument("--epochs", type=int, default=999, help="upper epoch limit")
parser.add_argument(
"--scheduler_epochs", type=int, default=-1, help="upper epoch limit"
)
parser.add_argument(
"--uniform_pos_until",
type=int,
default=0,
help="use uniform position decoders until a certain epoch",
)
parser.add_argument("--updates", type=int, default=999999, help="max GFlowNet updates")
parser.add_argument(
"--max_grammar_updates", type=int, default=10000, help="max grammar updates"
)
parser.add_argument("--warmup", type=int, default=40, help="step of warmup from 0 lr")
parser.add_argument(
"--train_grammar", type=int, default=1, help="whether to train the neural grammar"
)
parser.add_argument("--tjb_forward", type=int, default=1, help="go forward from s_0")
parser.add_argument(
"--go_back_and_forward",
type=int,
default=1,
help="go backward from a known terminal state and then forward",
)
parser.add_argument(
"--sleep_mle",
type=int,
default=1,
help="update logPF for tree hallucinated from grammar",
)
parser.add_argument("--bnf_gamma", type=float, default=1.0)
parser.add_argument("--smle_gamma", type=float, default=10.0)
parser.add_argument(
"--backward_until_epochs",
type=int,
default=-1,
help="stop going backward after a certain number of epochs",
)
parser.add_argument("--temperature", type=float, default=1.0, help="GFN policy temp")
parser.add_argument(
"--temperature_pos",
type=float,
default=-1.0,
help="GFN policy temp for position decoders; it falls back to --temp if negative",
)
parser.add_argument(
"--temperature_tok",
type=float,
default=-1.0,
help="GFN policy temp for token decoders; it falls back to --temp if negative",
)
parser.add_argument("--uniform_pb", action="store_true")
parser.add_argument("--modular_energy", action="store_true")
parser.add_argument("--flow_estimator", action="store_true")
parser.add_argument(
"--grammar_pretrain_epochs",
default=0,
type=int,
help="Number of epochs to pretrain grammar with exact sampling",
)
parser.add_argument(
"--pf_uniform_eps_tok",
type=float,
default=0.0,
help="P_F is uniform with probability eps",
)
parser.add_argument(
"--pf_uniform_eps_pos",
type=float,
default=0.0,
help="P_F is uniform with probability eps",
)
parser.add_argument("--subtb_lambda", type=float, default=1.0)
parser.add_argument("--symbol_dropout", type=float, default=0.0)
parser.add_argument("--mc_em", action="store_true")
# Reward and Eval
parser.add_argument(
"--reward_temperature", type=float, default=1, help="reward = reward**pow"
)
parser.add_argument("--reward_scale", type=float, default=1.0, help="reward multiplier")
# IO
parser.add_argument(
"--data", type=str, default="./data/ptb", help="location of the data corpus"
)
parser.add_argument(
"--log_interval", type=int, default=64, metavar="N", help="report interval"
)
parser.add_argument(
"--grammar_log_interval",
type=int,
default=100,
metavar="N",
help="grammar report interval",
)
parser.add_argument(
"--save_dir", type=str, default=None, help="path to save the final model"
)
parser.add_argument(
"--resume_dir", type=str, default=None, help="path to resume training"
)
parser.add_argument("--log_dir", type=str, default="./ckpts", help="path to save logs")
parser.add_argument("--wandb_tag", type=str, default="none", help="wandb tag")
parser.add_argument("--use_wandb", action="store_true")
parser.add_argument("--curriculum_len", type=int, default=0)
parser.add_argument("--curriculum_step", type=int, default=1)
# Decoding
parser.add_argument(
"--decode_temperature",
type=float,
default=1.0,
help="temperature used when decoding by sampling",
)
# parser.add_argument('--decode_mode', choices=['greedy', 'sample'],
# help='decoding mode')
# grammar
parser.add_argument("--grammar_type", default="ncfg", choices=["cfg", "ncfg"])
parser.add_argument(
"--fixed_grammar_num",
type=int,
default=0,
help="choice of fixed grammar for debugging",
)
parser.add_argument(
"--grammar_param",
type=str,
default="mlp_neural",
choices=["fixed", "mlp_neural"],
help="choice of grammar parametrization",
)
parser.add_argument(
"--extra_nts", type=int, default=90, help="extra nts for the learned grammar"
)
parser.add_argument("--num_pts", type=int, default=60, help="number of pts for grammar")
parser.add_argument("--grammar_mlp_dim", type=int, default=256)
parser.add_argument("--grammar_optimizer", default=None, choices=["sgd", "adam", None])
# GFN-PCFG tracking trick
parser.add_argument("--grammar_update_tb_threshold_max", default=10e20, type=float)
parser.add_argument("--grammar_update_tb_threshold_min", default=10e20, type=float)
parser.add_argument("--grammar_update_tb_threshold_horizon", default=10e20, type=float)
parser.add_argument("--threshold_beta", default=0.9, type=float)
parser.add_argument("--mcmc_steps", default=1, type=int)
parser.add_argument("--use_off_policy_mcmc", action="store_true")
parser.add_argument("--bnf_starting_steps", default=10, type=int)
parser.add_argument("--temp_cond_prob", default=0.0, type=float)
parser.add_argument("--temp_cond_min", default=0.0, type=float)
parser.add_argument("--temp_cond_max", default=0.0, type=float)
parser.add_argument("--ebm_reward", type=str, default=None)
parser.add_argument("--ebm_reward_temp_start", type=float, default=1.0)
parser.add_argument("--ebm_reward_temp_end", type=float, default=1.0)
parser.add_argument("--ebm_reward_temp_horizon", type=float, default=1.0)
parser.add_argument(
"--ebm_reward_temp_schedule_type", choices=["linear", "exp"], default="linear"
)
# Misc
parser.add_argument("--seed", type=int, default=1111, help="random seed")
parser.add_argument("--cuda", action="store_true", help="use CUDA")
parser.add_argument(
"--precision", type=str, default="float", help="float | double | half"
)
parser.add_argument("--reset_lr_schedule", action="store_true")
parser.add_argument("--plot", action="store_true")
parser.add_argument("--only_pretrain_grammar", action="store_true")
parser.add_argument("--restore_grammar_only", action="store_true")
parser.add_argument("--compute_grammar_spans", action="store_true", default=False)
parser.add_argument("--use_spans_f1", action="store_true")
parser.add_argument("--train_gfn", type=int, default=1)
parser.add_argument(
"--parser_type",
default="gfn",
choices=["gfn", "marginalization", "sample_from_posterior"],
)
args = parser.parse_args()
# initializing cox
args_dict = args.__dict__
args_to_ignore = [
"log_dir",
"save_dir",
"resume_dir",
"tb_dir" "cuda",
"log_interval",
"decode_temperature",
"decode_mode",
]
exp_id = sha1(
repr(
sorted(
frozenset(filter(lambda x: x[0] not in args_to_ignore, args_dict.items()))
)
).encode("ASCII")
).hexdigest()
# wandb
wandb.init(
project="GFN-Parser-PT-marginalization",
entity=f"{os.environ.get('WANDB_USERNAME', default='edwardhu')}",
config=args_dict,
tags=[args.wandb_tag],
id=exp_id,
mode="online" if args.use_wandb else "disabled",
)
wandb.define_metric("train_loss", summary="min", step_metric="epoch")
wandb.define_metric("val_marginal_nll", summary="min", step_metric="grammar_step")
wandb.define_metric("val_r_pb_over_pf", summary="max", step_metric="epoch")
wandb.define_metric("val_posterior_ent", summary="min", step_metric="grammar_step")
wandb.define_metric("val_sampler_nll", summary="min", step_metric="epoch")
wandb.define_metric("val_sample_sent_f1", summary="max", step_metric="grammar_step")
wandb.define_metric("val_sample_corpus_f1", summary="max", step_metric="grammar_step")
wandb.define_metric("per_step_F_DB", summary="min", step_metric="step")
wandb.define_metric("per_step_BF_DB", summary="min", step_metric="step")
wandb.define_metric("per_step_loss", summary="min", step_metric="step")
wandb.define_metric("per_step_R_F", summary="min", step_metric="step")
wandb.define_metric("per_step_R_BnF", summary="min", step_metric="step")
parse_table = wandb.Table(
columns=["PCFG steps", "logz_hat", "true_ll", "sample parse"], data=[]
)
tag_dist_table = wandb.Table(
columns=["PCFG steps"] + [f"Q{i}" for i in range(args.extra_nts - args.num_pts)],
data=[],
)
# manipulate args
args.temperature_pos = (
args.temperature if args.temperature_pos < 0 else args.temperature_pos
)
args.temperature_tok = (
args.temperature if args.temperature_tok < 0 else args.temperature_tok
)
print(args)
# Set the random seed manually for reproducibility.
torch.manual_seed(args.seed)
random.seed(args.seed)
np.random.seed(args.seed)
if args.save_dir is not None:
os.makedirs(os.path.join(args.save_dir, exp_id), exist_ok=True)
if torch.cuda.is_available():
if not args.cuda:
print("WARNING: You have a CUDA device, so you should probably run with --cuda")
device = torch.device("cuda" if args.cuda else "cpu")
###############################################################################
# Load data
###############################################################################
corpus = data.SeqCorpus(
args.data,
seqlen=args.seqlen,
train_batch_size=args.batch_size,
valid_batch_size=args.valid_batch_size,
batch_group_size=args.batch_group_size,
add_master_token=False,
load_spans=args.use_spans_f1,
)
train_dataloader = corpus.train
val_dataloader = corpus.valid
test_dataloader = corpus.test
if args.use_spans_f1:
# train_spans_dataloader = corpus.train
val_spans_dataloader = corpus.valid_spans
test_spans_dataloader = corpus.test_spans
print("training samples:", len(train_dataloader))
print("validation samples:", len(val_dataloader))
###############################################################################
# Build the model
###############################################################################
def setprec(t):
if args.precision == "half":
# do nothing since this is handled by AMP
return t
elif args.precision == "float":
return t.float()
elif args.precision == "double":
return t.double()
else:
raise ValueError(f"invalid precision string {args.precision}")
ntokens_src = len(corpus.dict)
controller = parser_controller(
device,
args={
"n_vocab": ntokens_src,
"reward_temperature": args.reward_temperature,
"reward_scale": args.reward_scale,
"vocab_dict": corpus.dict.idx2word,
"fixed_grammar_num": args.fixed_grammar_num,
"grammar_type": args.grammar_type,
"grammar_param": args.grammar_param,
"only_unary_from_s": True,
"extra_nts": args.extra_nts,
"num_pts": args.num_pts,
"mlp_dim": args.grammar_mlp_dim,
"ebm_reward": args.ebm_reward,
"ebm_d_model": 16,
"ebm_agg_type": "simplemlp",
},
)
state = tree_state(
device,
args={
"n_vocab": ntokens_src,
"n_nts": len(controller.nts_list),
"num_pts": args.num_pts,
"seqlen": args.seqlen + 2,
"vocab_dict": corpus.dict.idx2word,
"start_sym": controller.grammar.start,
"nt_dict": controller.nts_list,
},
)
all_toks = list(corpus.dict.idx2word) + list(controller.nts_list)
id_to_token_overall = {}
for i, tok in enumerate(all_toks):
id_to_token_overall[i] = tok
overall_tokenizer = lambda x: id_to_token_overall[x]
print(f"vocab size: {ntokens_src}")
print(f"num of nonterminal symbols: {len(controller.nts_list)}")
n_nts = len(controller.nts_list)
model_flow = GFlowNet_Z(d_model=args.d_model)
if args.agg_type == "none":
model_shared_embedding = GFlowNet_shared_embedding(
n_vocab=ntokens_src,
n_nts=n_nts,
d_model=args.d_model,
seqlen=(args.seqlen + 2),
grammar_emb=controller.grammar.emb_input
if args.share_grammar_embedding
else None,
)
else:
model_shared_embedding = GFlowNet_shared_embedding_with_aggregation(
n_vocab=ntokens_src,
n_nts=n_nts,
d_model=args.d_model,
seqlen=(args.seqlen + 2),
agg_type=args.agg_type,
)
model_encoder = GFlowNet_encoder(
n_vocab=ntokens_src,
n_nts=n_nts,
d_model=args.d_model,
nhead=args.nhead,
dim_feedforward=4 * args.d_model,
seqlen=(args.seqlen + 2),
nlayers=args.nlayers,
dropout=args.dropout,
batch_first=True,
norm_first=args.norm_type == "preln",
shared_embedding=model_shared_embedding,
)
model_forward = GFlowNet_forward(
n_nts=n_nts,
d_model=args.d_model,
shared_embedding=model_shared_embedding if args.agg_type == "none" else None,
tie_tgt_embedding=False,
preterminal_mask=controller.pt_mask,
) # args.tie_tgt_embedding)
model_backward = GFlowNet_backward(
n_vocab=ntokens_src, n_nts=n_nts, d_model=args.d_model
)
from mup import set_base_shapes
try:
from torchdistx.deferred_init import deferred_init
__no_torchdistx__ = False
except:
__no_torchdistx__ = True
if __no_torchdistx__:
set_base_shapes(
model_encoder,
GFlowNet_encoder(
n_vocab=ntokens_src,
n_nts=n_nts,
d_model=128,
nhead=args.nhead,
dim_feedforward=128,
seqlen=(args.seqlen + 2),
nlayers=args.nlayers,
dropout=args.dropout,
batch_first=True,
norm_first=args.norm_type == "preln",
shared_embedding=model_shared_embedding,
),
delta=GFlowNet_encoder(
n_vocab=ntokens_src,
n_nts=n_nts,
d_model=256,
nhead=args.nhead,
dim_feedforward=256,
seqlen=(args.seqlen + 2),
nlayers=args.nlayers,
dropout=args.dropout,
batch_first=True,
norm_first=args.norm_type == "preln",
shared_embedding=model_shared_embedding,
),
)
set_base_shapes(model_flow, GFlowNet_Z(d_model=128), delta=GFlowNet_Z(d_model=256))
set_base_shapes(
model_forward,
GFlowNet_forward(
n_nts=n_nts,
d_model=128,
shared_embedding=model_shared_embedding
if args.agg_type == "none"
else None,
tie_tgt_embedding=False,
preterminal_mask=controller.pt_mask,
),
delta=GFlowNet_forward(
n_nts=n_nts,
d_model=256,
shared_embedding=model_shared_embedding
if args.agg_type == "none"
else None,
tie_tgt_embedding=False,
preterminal_mask=controller.pt_mask,
),
)
set_base_shapes(
model_backward,
GFlowNet_backward(n_vocab=ntokens_src, n_nts=n_nts, d_model=128),
delta=GFlowNet_backward(n_vocab=ntokens_src, n_nts=n_nts, d_model=256),
)
if args.grammar_param == "mlp_neural":
set_base_shapes(
controller.grammar,
MLPPCFG(
n_nts,
ntokens_src,
ntokens_src,
np.concatenate(
(np.zeros(n_nts - args.num_pts), np.ones(args.num_pts))
).astype(bool),
True,
128,
grammar_type=args.grammar_type,
),
delta=MLPPCFG(
n_nts,
ntokens_src,
ntokens_src,
np.concatenate(
(np.zeros(n_nts - args.num_pts), np.ones(args.num_pts))
).astype(bool),
True,
512,
grammar_type=args.grammar_type,
),
)
else:
set_base_shapes(
model_encoder,
deferred_init(
GFlowNet_encoder,
n_vocab=ntokens_src,
n_nts=n_nts,
d_model=128,
nhead=args.nhead,
dim_feedforward=128,
seqlen=(args.seqlen + 2),
nlayers=args.nlayers,
dropout=args.dropout,
batch_first=True,
norm_first=args.norm_type == "preln",
shared_embedding=model_shared_embedding,
),
delta=deferred_init(
GFlowNet_encoder,
n_vocab=ntokens_src,
n_nts=n_nts,
d_model=256,
nhead=args.nhead,
dim_feedforward=256,
seqlen=(args.seqlen + 2),
nlayers=args.nlayers,
dropout=args.dropout,
batch_first=True,
norm_first=args.norm_type == "preln",
shared_embedding=model_shared_embedding,
),
)
set_base_shapes(
model_flow,
deferred_init(GFlowNet_Z, d_model=128),
delta=deferred_init(GFlowNet_Z, d_model=256),
)
set_base_shapes(
model_forward,
deferred_init(
GFlowNet_forward,
n_nts=n_nts,
d_model=128,
shared_embedding=model_shared_embedding
if args.agg_type == "none"
else None,
tie_tgt_embedding=False,
preterminal_mask=controller.pt_mask,
),
delta=deferred_init(
GFlowNet_forward,
n_nts=n_nts,
d_model=256,
shared_embedding=model_shared_embedding
if args.agg_type == "none"
else None,
tie_tgt_embedding=False,
preterminal_mask=controller.pt_mask,
),
)
set_base_shapes(
model_backward,
deferred_init(GFlowNet_backward, n_vocab=ntokens_src, n_nts=n_nts, d_model=128),
delta=deferred_init(
GFlowNet_backward, n_vocab=ntokens_src, n_nts=n_nts, d_model=256
),
)
if args.grammar_param == "mlp_neural":
set_base_shapes(
controller.grammar,
deferred_init(
MLPPCFG,
n_nts,
ntokens_src,
ntokens_src,
np.concatenate(
(np.zeros(n_nts - args.num_pts), np.ones(args.num_pts))
).astype(bool),
True,
128,
grammar_type=args.grammar_type,
),
delta=deferred_init(
MLPPCFG,
n_nts,
ntokens_src,
ntokens_src,
np.concatenate(
(np.zeros(n_nts - args.num_pts), np.ones(args.num_pts))
).astype(bool),
True,
512,
grammar_type=args.grammar_type,
),
)
model_flow = setprec(model_flow).to(device)
model_encoder = setprec(model_encoder).to(device)
model_shared_embedding = setprec(model_shared_embedding).to(device)
model_forward = setprec(model_forward).to(device)
model_backward = setprec(model_backward).to(device)
if args.train_grammar == 1:
controller.grammar = setprec(controller.grammar).to(device)
# adjust GFN init std
for p in model_encoder.parameters():
p.data *= args.init_mult_encoder
for p in model_forward.parameters():
p.data *= args.init_mult_forward
for p in model_backward.parameters():
p.data *= args.init_mult_backward
for p in model_flow.parameters():
p.data *= args.init_mult_flow
"""
import numpy as np
pretrained_emb = np.load('ptb.emb.npy')
pretrained_vocab = np.load('ptb.vocab.npy')
pretrained_ind = torch.tensor([np.where(pretrained_vocab==word)[0].item() if word in pretrained_vocab else -1 for word in corpus.dict.idx2word], dtype=torch.long)
pretrained_emb = torch.from_numpy(pretrained_emb)
pretrained_emb = torch.cat([pretrained_emb, pretrained_emb.mean(dim=0, keepdim=True)], dim=0)
pretrained_emb_mat = pretrained_emb[pretrained_ind]
model_shared_embedding.embedding_tgt.weight.data[:pretrained_emb_mat.size(0), :] = pretrained_emb_mat.to(model_shared_embedding.embedding_tgt.weight.data.dtype).to(device)
"""
###############################################################################
# Training code
###############################################################################
def get_ebm_temp(grammar_step):
if grammar_step >= args.ebm_reward_temp_horizon:
return args.ebm_reward_temp_end
if args.ebm_reward_temp_schedule_type == "linear":
return args.ebm_reward_temp_start + (
args.ebm_reward_temp_end - args.ebm_reward_temp_start
) * (grammar_step / args.ebm_reward_temp_horizon)
elif args.ebm_reward_temp_schedule_type == "exp":
c = (grammar_step / args.ebm_reward_temp_horizon) * math.log(
args.ebm_reward_temp_end / args.ebm_reward_temp_start
)
# print(args.ebm_reward_temp_start * math.exp(c))
return args.ebm_reward_temp_start * math.exp(c)
else:
raise NotImplementedError
def compare_spans(pred_span, label_span):
pred_span_set = set(sorted(set(pred_span), key=lambda x: x[1])[:-1])
label_span_set = set(label_span[:-1])
tp = 0
fp = 0
fn = 0
for span in pred_span_set:
if span in label_span_set:
tp += 1
else:
fp += 1
for span in label_span_set:
if span not in pred_span_set:
fn += 1
overlap = pred_span_set.intersection(label_span_set)
prec = float(len(overlap)) / (len(pred_span_set) + 1e-8)
reca = float(len(overlap)) / (len(label_span_set) + 1e-8)
if len(label_span_set) == 0:
reca = 1.0
if len(pred_span_set) == 0:
prec = 1.0
f1 = 2 * prec * reca / (prec + reca + 1e-8)
return f1, (tp, fp, fn)
@torch.no_grad()
def decode_and_evaluate(original_seq, gold_spans):
model_flow.eval()
model_encoder.eval()
model_backward.eval()
model_forward.eval()
forward_seq = [seq.clone() for seq in original_seq]
def calc_stats_from_torch_struct(sample):
sent_f1s = []
corpus_f1s = [0, 0, 0]
charts = sample[3].detach().cpu().numpy()
tags = charts.argmax(-1).reshape(-1)
if gold_spans is not None:
for i in range(len(charts)):
spans = [(s, s + t + 1) for s, t in zip(*charts[i].nonzero()[1::-1])]
gold_span = gold_spans[i]
sent_f1, corpus_f1 = compare_spans(spans, gold_span)
sent_f1s.append(sent_f1)
corpus_f1s = [corpus_f1s[i] + corpus_f1[i] for i in range(3)]
return (sent_f1s, corpus_f1s), tags
def calc_stats_from_gfn(forward_seq):
sent_f1s = []
corpus_f1s = [0, 0, 0]
if gold_spans is not None:
for i, seq in enumerate(forward_seq):
# convert to (start, end) and ignore PT tags
spans = [
(span[0], span[0] + span[1] - 1)
for span in seq.trees[0].all_spans(0)[0]
if span[1] != 1
]
gold_span = gold_spans[i]
sent_f1, corpus_f1 = compare_spans(spans, gold_span)
sent_f1s.append(sent_f1)
corpus_f1s = [corpus_f1s[i] + corpus_f1[i] for i in range(3)]
return (sent_f1s, corpus_f1s)
seqs = [
torch.tensor([root.data for root in state._state], device=device)
for state in forward_seq
]
lengths = [len(s) for s in seqs]
batch_seq = torch.nn.utils.rnn.pad_sequence(seqs, batch_first=True)
if args.parser_type == "gfn":
bsz = len(forward_seq)
encoded_tokens, pad_mask = model_encoder(
forward_seq,
seq_type="all_root",
temp_cond=0 if args.temp_cond_prob > 0 else None,
)
if args.tjb_forward >= 1:
estimated_ll = model_flow(encoded_tokens, pad_mask=pad_mask)
else:
estimated_ll = encoded_tokens.new_zeros(len(encoded_tokens))
forward_step = 0
forward_logp = torch.zeros((bsz,), device=device)
backward_logp = torch.zeros((bsz,), device=device)
while True:
F_logits = model_forward(encoded_tokens)
sample_forward_result = controller.sample_forward(
F_logits, forward_seq, greedy=False
)
forward_seq = sample_forward_result["new_states"]
forward_logp += sample_forward_result["policy_log_pf"]
backward_actions = sample_forward_result["backward_actions"]
forward_step += 1
encoded_tokens, _ = model_encoder(
forward_seq,
seq_type="all_root",
temp_cond=0 if args.temp_cond_prob > 0 else None,
)
B_logits = model_backward(encoded_tokens, uniform_pos=args.uniform_pb)
backward_logp += controller.batch_calc_backward_prob(
B_logits, forward_seq, B_actions=backward_actions
)[0]
if all([s.is_terminated for s in forward_seq]):
break
if args.mc_em:
for mcmc_i in range(args.mcmc_steps):
starting_seq = [seq.clone() for seq in forward_seq]
starting_ll = controller.calc_log_reward(
starting_seq, temp_cond=0 if args.temp_cond_prob > 0 else None
)
for i in range(len(forward_seq)):
if mcmc_i % 2 == 0:
forward_seq[i]._state[0].random_rotate()
else:
forward_seq[i]._state[0].random_change_symbol(
[
x + ntokens_src
for x in range(args.extra_nts - args.num_pts)
]
)
forward_seq[i]._state[0].clear_ll()
forward_seq_ll = controller.calc_log_reward(
forward_seq, temp_cond=0 if args.temp_cond_prob > 0 else None
)
mcmc_accept_prob = forward_seq_ll - starting_ll
mcmc_outcomes = (
mcmc_accept_prob
< torch.rand(starting_ll.shape, device=starting_ll.device).log()
)
new_seq = []
for i, ele in enumerate(mcmc_outcomes):
if ele.item():
new_seq.append(starting_seq[i])
else:
new_seq.append(forward_seq[i])
forward_seq = new_seq
# print an example parse
sample_parse = (
f"{estimated_ll[0]:2.3f}",
"\t",
forward_seq[0]._state[0].print(tostr=overall_tokenizer),
)
# sample_parse = None
sampler_ll = controller.calc_log_reward(forward_seq)
parse_table.add_data(
f"{global_grammar_updates}",
f"{estimated_ll[0]:2.3f}",
f"{sampler_ll[0]:2.3f}",
forward_seq[0]._state[0].print(tostr=overall_tokenizer),
)
all_parses = [(forward_seq[i]._state[0].print(tostr=overall_tokenizer), estimated_ll[i], sampler_ll[i]) for i in range(len(forward_seq))]
# spans and tags
tags = []
for i, seq in enumerate(forward_seq):
# convert to (start, end) and ignore PT tags
tags += seq.trees[0].all_tags()
tags = np.array(tags) - ntokens_src
sampled_parse_f1s = calc_stats_from_gfn(forward_seq)
else:
# baselines
if args.grammar_type == "ncfg":
raise NotImplementedError
else:
sample, sampler_ll = controller.grammar.sample_batch(batch_seq, lengths)
sampled_parse_f1s, tags = calc_stats_from_torch_struct(sample)
estimated_ll = sampler_ll.new_zeros(sampler_ll.shape)
forward_logp = sampler_ll.new_zeros(sampler_ll.shape)
backward_logp = sampler_ll.new_zeros(sampler_ll.shape)
sample_parse = None
all_parses = []
# calculate the F1 for the most likely parse from the grammar
if args.grammar_type == "ncfg":
max_parse_f1s = ([0.0, 0.0, 0.0], [0.0, 0.0, 0.0]) # no max parse for NCFG
else:
sample, sampler_ll = controller.grammar.maxll_batch(batch_seq, lengths)
max_parse_f1s, _ = calc_stats_from_torch_struct(sample)
return (
sampler_ll,
estimated_ll,
forward_logp,
backward_logp,
(sampled_parse_f1s, max_parse_f1s),
tags[tags.nonzero()],
sample_parse,
all_parses
)
@torch.no_grad()
def valid():
sampler_ll = []
estimated_ll = []
forward_logp = []
backward_logp = []
pcfg_max_ll = []
posterior_ent = []
sample_sent_f1 = []
sample_corpus_f1 = [0.0, 0.0, 0.0]
tag_bincount = None
lengths = []
sample_parses = []
parses = []
iterable = (
zip(val_dataloader, val_spans_dataloader)
if args.use_spans_f1
else val_dataloader
)
# for PCFG
marginal_ll = []
pcfg_max_ll = []
posterior_ent = []
max_sent_f1 = []
max_corpus_f1 = [0.0, 0.0, 0.0]
for item in iterable:
if args.use_spans_f1:
src, gold_span = item
else:
src = item
gold_span = None
# calculate marginal LL and pcfg max LL under the grammar
forward_seq = [state.from_iterable(t) for t in src]
seqs = [
torch.tensor([root.data for root in state._state], device=device)
for state in forward_seq
]