forked from sunlab-osu/MISP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinteraction_editsql.py
2449 lines (2025 loc) · 120 KB
/
interaction_editsql.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
""" The main function for interactive semantic parsing based on EditSQL. Dataset: Spider. """
import os
import sys
import numpy as np
import random
import argparse
import torch
import datetime, pytimeparse
import json
import pickle
import traceback
import subprocess
import copy
import re
from collections import defaultdict, Counter
from EditSQL.postprocess_eval import read_schema, read_prediction, postprocess, write_and_evaluate, postprocess_one
from EditSQL.eval_scripts.evaluation import evaluate_single, build_foreign_key_map_from_json, evaluate
from EditSQL.eval_scripts.evaluation import WHERE_OPS, AGG_OPS
from EditSQL.data_util import dataset_split as ds
from EditSQL.data_util.interaction import load_function
from EditSQL.data_util.utterance import Utterance
from EditSQL.logger import Logger
from EditSQL.data_util import atis_data
from EditSQL.model.schema_interaction_model import SchemaInteractionATISModel
from EditSQL.model_util import Metrics, get_progressbar, write_prediction, update_sums, construct_averages,\
evaluate_interaction_sample, evaluate_utterance_sample, train_epoch_with_interactions, train_epoch_with_utterances
from EditSQL.world_model import WorldModel
from EditSQL.error_detector import ErrorDetectorProbability, ErrorDetectorBayesDropout, ErrorDetectorSim
from EditSQL.environment import ErrorEvaluator, UserSim, RealUser, GoldUserSim
from EditSQL.agent import Agent
from EditSQL.question_gen import QuestionGenerator
from MISP_SQL.error_detector import ErrorDetectorFNN
from MISP_SQL.ed_model.fnnv2 import ModelIndexer, MLP
from MISP_SQL.utils import SELECT_AGG_v2, WHERE_COL, WHERE_OP, WHERE_ROOT_TERM, GROUP_COL, HAV_AGG_v2, \
HAV_OP_v2, HAV_ROOT_TERM_v2, ORDER_AGG_v2, ORDER_DESC_ASC, ORDER_LIMIT, IUEN_v2, OUTSIDE
from user_study_utils import *
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
VALID_EVAL_METRICS = [Metrics.LOSS, Metrics.TOKEN_ACCURACY, Metrics.STRING_ACCURACY]
TRAIN_EVAL_METRICS = [Metrics.LOSS, Metrics.TOKEN_ACCURACY, Metrics.STRING_ACCURACY]
FINAL_EVAL_METRICS = [Metrics.STRING_ACCURACY, Metrics.TOKEN_ACCURACY]
def interpret_args():
""" Interprets the command line arguments, and returns a dictionary. """
parser = argparse.ArgumentParser()
### Data parameters
parser.add_argument(
'--raw_train_filename',
type=str,
default='../atis_data/data/resplit/processed/train_with_tables.pkl')
parser.add_argument(
'--raw_dev_filename',
type=str,
default='../atis_data/data/resplit/processed/dev_with_tables.pkl')
parser.add_argument(
'--raw_validation_filename',
type=str,
default='../atis_data/data/resplit/processed/valid_with_tables.pkl')
parser.add_argument(
'--raw_test_filename',
type=str,
default='../atis_data/data/resplit/processed/test_with_tables.pkl')
parser.add_argument('--data_directory', type=str, default='processed_data')
parser.add_argument('--processed_train_filename', type=str, default='train.pkl')
parser.add_argument('--processed_dev_filename', type=str, default='dev.pkl')
parser.add_argument('--processed_validation_filename', type=str, default='validation.pkl')
parser.add_argument('--processed_test_filename', type=str, default='test.pkl')
parser.add_argument('--database_schema_filename', type=str, default=None)
parser.add_argument('--embedding_filename', type=str, default=None)
parser.add_argument('--input_vocabulary_filename', type=str, default='input_vocabulary.pkl')
parser.add_argument('--output_vocabulary_filename',
type=str,
default='output_vocabulary.pkl')
parser.add_argument('--input_key', type=str, default='nl_with_dates')
parser.add_argument('--anonymize', type=bool, default=False)
parser.add_argument('--anonymization_scoring', type=bool, default=False)
parser.add_argument('--use_snippets', type=bool, default=False)
parser.add_argument('--use_previous_query', type=bool, default=False)
parser.add_argument('--maximum_queries', type=int, default=1)
parser.add_argument('--use_copy_switch', type=bool, default=False)
parser.add_argument('--use_query_attention', type=bool, default=False)
parser.add_argument('--use_utterance_attention', type=bool, default=False)
parser.add_argument('--freeze', type=bool, default=False)
parser.add_argument('--scheduler', type=bool, default=False)
parser.add_argument('--use_bert', type=bool, default=False)
parser.add_argument("--bert_type_abb", type=str, help="Type of BERT model to load. e.g.) uS, uL, cS, cL, and mcS")
parser.add_argument("--bert_input_version", type=str, default='v1')
parser.add_argument('--fine_tune_bert', type=bool, default=False)
parser.add_argument('--lr_bert', default=1e-5, type=float, help='BERT model learning rate.')
### Debugging/logging parameters
parser.add_argument('--logdir', type=str, default='logs')
parser.add_argument('--deterministic', type=bool, default=False)
parser.add_argument('--num_train', type=int, default=-1)
parser.add_argument('--logfile', type=str, default='log.txt')
parser.add_argument('--results_file', type=str, default='results.txt')
### Model architecture
parser.add_argument('--input_embedding_size', type=int, default=300)
parser.add_argument('--output_embedding_size', type=int, default=300)
parser.add_argument('--encoder_state_size', type=int, default=300)
parser.add_argument('--decoder_state_size', type=int, default=300)
parser.add_argument('--encoder_num_layers', type=int, default=1)
parser.add_argument('--decoder_num_layers', type=int, default=2)
parser.add_argument('--snippet_num_layers', type=int, default=1)
parser.add_argument('--maximum_utterances', type=int, default=5)
parser.add_argument('--state_positional_embeddings', type=bool, default=False)
parser.add_argument('--positional_embedding_size', type=int, default=50)
parser.add_argument('--snippet_age_embedding', type=bool, default=False)
parser.add_argument('--snippet_age_embedding_size', type=int, default=64)
parser.add_argument('--max_snippet_age_embedding', type=int, default=4)
parser.add_argument('--previous_decoder_snippet_encoding', type=bool, default=False)
parser.add_argument('--discourse_level_lstm', type=bool, default=False)
parser.add_argument('--use_schema_attention', type=bool, default=False)
parser.add_argument('--use_encoder_attention', type=bool, default=False)
parser.add_argument('--use_schema_encoder', type=bool, default=False)
parser.add_argument('--use_schema_self_attention', type=bool, default=False)
parser.add_argument('--use_schema_encoder_2', type=bool, default=False)
### Training parameters
parser.add_argument('--batch_size', type=int, default=16)
parser.add_argument('--train_maximum_sql_length', type=int, default=200)
parser.add_argument('--train_evaluation_size', type=int, default=100)
parser.add_argument('--dropout_amount', type=float, default=0.5)
parser.add_argument('--initial_patience', type=float, default=10.)
parser.add_argument('--patience_ratio', type=float, default=1.01)
parser.add_argument('--initial_learning_rate', type=float, default=0.001)
parser.add_argument('--learning_rate_ratio', type=float, default=0.8)
parser.add_argument('--interaction_level', type=bool, default=True)
parser.add_argument('--reweight_batch', type=bool, default=False)
### Setting
# parser.add_argument('--train', type=bool, default=False)
parser.add_argument('--train', type=int, choices=[0,1], default=0)
parser.add_argument('--debug', type=bool, default=False)
parser.add_argument('--evaluate', type=bool, default=False)
parser.add_argument('--attention', type=bool, default=False)
parser.add_argument('--enable_testing', type=bool, default=False)
parser.add_argument('--use_predicted_queries', type=bool, default=False)
parser.add_argument('--evaluate_split', type=str, default='dev')
parser.add_argument('--evaluate_with_gold_forcing', type=bool, default=False)
parser.add_argument('--eval_maximum_sql_length', type=int, default=1000)
parser.add_argument('--results_note', type=str, default='')
parser.add_argument('--compute_metrics', type=bool, default=False)
parser.add_argument('--reference_results', type=str, default='')
parser.add_argument('--interactive', type=bool, default=False)
parser.add_argument('--database_username', type=str, default="aviarmy")
parser.add_argument('--database_password', type=str, default="aviarmy")
parser.add_argument('--database_timeout', type=int, default=2)
# interaction params - Ziyu
parser.add_argument('--job', default='test_w_interaction', choices=['test_w_interaction', 'online_learning'],
help='Set the job. For parser pretraining, see other scripts.')
parser.add_argument('--seed', type=int, default=0, help='Random seed.')
parser.add_argument('--raw_data_directory', type=str, help='The data directory of the raw spider data.')
parser.add_argument('--num_options', type=str, default='3', help='[INTERACTION] Number of options.')
parser.add_argument('--user', type=str, default='sim', choices=['sim', 'gold_sim', 'real'],
help='[INTERACTION] User type.')
parser.add_argument('--err_detector', type=str, default='any',
help='[INTERACTION] The error detector: '
'(1) prob=x for using policy probability threshold;'
'(2) stddev=x for using Bayesian dropout threshold (need to set --dropout and --passes);'
'(3) any for querying about every policy action;'
'(4) perfect for using a simulated perfect detector.'
'(5) fnn for feed forward NN based error detector')
parser.add_argument('--dropout', type=float, default=0.0,
help='[INTERACTION] Dropout rate for Bayesian dropout-based uncertainty analysis. '
'This does NOT change the dropout rate in training.')
parser.add_argument('--passes', type=int, default=1,
help='[INTERACTION] Number of decoding passes for Bayesian dropout-based uncertainty analysis.')
parser.add_argument('--friendly_agent', type=int, default=0, choices=[0, 1],
help='[INTERACTION] If 1, the agent will not trigger further interactions '
'if any wrong decision is not resolved during parsing.')
parser.add_argument('--ask_structure', type=int, default=0, choices=[0, 1],
help='[INTERACTION] Set to True to allow questions about query structure '
'(WHERE/GROUP_COL, ORDER/HAV_AGG_v2) in NL.')
parser.add_argument('--output_path', type=str, default='temp', help='[INTERACTION] Where to save outputs.')
# online learning
parser.add_argument('--setting', type=str, default='', choices=['online_pretrain_10p', 'full_train'],
help='Model setting; checkpoints will be loaded accordingly.')
parser.add_argument('--supervision', type=str, default='full_expert',
choices=['full_expert', 'misp_neil', 'misp_neil_perfect', 'misp_neil_pos',
'bin_feedback', 'bin_feedback_expert',
'self_train', 'self_train_0.5'],
help='[LEARNING] Online learning supervision based on different algorithms.')
parser.add_argument('--data_seed', type=int, choices=[0, 10, 100],
help='[LEARNING] Seed for online learning data.')
parser.add_argument('--start_iter', type=int, default=0, help='[LEARNING] Starting iteration in online learing.')
parser.add_argument('--end_iter', type=int, default=-1, help='[LEARNING] Ending iteration in online learing.')
parser.add_argument('--update_iter', type=int, default=1000,
help='[LEARNING] Number of iterations per parser update.')
args = parser.parse_args()
if not os.path.exists(args.logdir):
os.makedirs(args.logdir)
if not (args.train or args.evaluate or args.interactive or args.attention):
raise ValueError('You need to be training or evaluating')
if args.enable_testing and not args.evaluate:
raise ValueError('You should evaluate the model if enabling testing')
# Seeds for random number generation
print("## seed: %d" % args.seed)
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(args.seed)
return args
def evaluation(model, data, eval_fn, valid_pred_path):
valid_examples = data.get_all_interactions(data.valid_data)
valid_eval_results = eval_fn(valid_examples,
model,
name=valid_pred_path,
metrics=FINAL_EVAL_METRICS,
total_num=atis_data.num_utterances(data.valid_data),
database_username=params.database_username,
database_password=params.database_password,
database_timeout=params.database_timeout,
use_predicted_queries=True,
max_generation_length=params.eval_maximum_sql_length,
write_results=True,
use_gpu=True,
compute_metrics=params.compute_metrics,
bool_progressbar=False)[0]
token_accuracy = valid_eval_results[Metrics.TOKEN_ACCURACY]
string_accuracy = valid_eval_results[Metrics.STRING_ACCURACY]
print("## postprocess_eval...")
database_schema = read_schema(table_schema_path)
predictions = read_prediction(valid_pred_path + "_predictions.json")
postprocess_db_sqls = postprocess(predictions, database_schema, True)
postprocess_sqls = []
for db in db_list:
for postprocess_sql, interaction_id, turn_id in postprocess_db_sqls[db]:
postprocess_sqls.append([postprocess_sql])
eval_acc = evaluate(gold_path, postprocess_sqls, db_path, "match",
kmaps, bool_verbal=False, bool_predict_file=False)['all']['exact']
eval_acc = float(eval_acc) * 100 # percentage
return eval_acc, token_accuracy, string_accuracy
def train(model, data, params, model_save_dir, patience=5):
""" Trains a model.
Inputs:
model (ATISModel): The model to train.
data (ATISData): The data that is used to train.
params (namespace): Training parameters.
"""
save_path = os.path.join(model_save_dir, "model_best.pt")
train_pred_path = os.path.join(model_save_dir, "train-eval")
valid_pred_path = os.path.join(model_save_dir, "valid-eval")
valid_pred_write_path = os.path.join(model_save_dir, "valid_use_predicted_queries")
# Get the training batches.
num_train_original = atis_data.num_utterances(data.train_data)
print("Original number of training utterances:\t" + str(num_train_original))
eval_fn = evaluate_utterance_sample
trainbatch_fn = data.get_utterance_batches
trainsample_fn = data.get_random_utterances
validsample_fn = data.get_all_utterances
batch_size = params.batch_size
if params.interaction_level:
batch_size = 1
eval_fn = evaluate_interaction_sample
trainbatch_fn = data.get_interaction_batches
trainsample_fn = data.get_random_interactions
validsample_fn = data.get_all_interactions
maximum_output_length = params.train_maximum_sql_length
train_batches = trainbatch_fn(batch_size,
max_output_length=maximum_output_length,
randomize=not params.deterministic)
if params.num_train >= 0:
train_batches = train_batches[:params.num_train]
training_sample = trainsample_fn(params.train_evaluation_size,
max_output_length=maximum_output_length)
valid_examples = validsample_fn(data.valid_data,
max_output_length=maximum_output_length)
num_train_examples = sum([len(batch) for batch in train_batches])
num_steps_per_epoch = len(train_batches)
print("Actual number of used training examples:\t" +
str(num_train_examples))
print("(Shortened by output limit of " +
str(maximum_output_length) + ")")
print("Number of steps per epoch:\t" + str(num_steps_per_epoch))
print("Batch size:\t" + str(batch_size))
print(
"Kept " +
str(num_train_examples) +
"/" +
str(num_train_original) +
" examples")
print(
"Batch size of " +
str(batch_size) +
" gives " +
str(num_steps_per_epoch) +
" steps per epoch")
# Keeping track of things during training.
epochs = 0
# patience = params.initial_patience
learning_rate_coefficient = 1.
previous_epoch_loss = float('inf')
maximum_eval_acc = 0.0
maximum_token_accuracy = 0.0
maximum_string_accuracy = 0.0
countdown = int(patience)
if params.scheduler:
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(model.trainer, mode='min', )
print("Time stamp: {}".format(datetime.datetime.now()))
keep_training = True
while keep_training:
print("Epoch:\t" + str(epochs))
model.set_dropout(params.dropout_amount)
if not params.scheduler:
model.set_learning_rate(learning_rate_coefficient * params.initial_learning_rate)
# Run a training step.
if params.interaction_level:
epoch_loss = train_epoch_with_interactions(
train_batches,
params,
model,
randomize=not params.deterministic,
bool_progressbar=False)
else:
epoch_loss = train_epoch_with_utterances(
train_batches,
model,
randomize=not params.deterministic)
print("train epoch loss:\t" + str(epoch_loss))
model.set_dropout(0.)
# Run an evaluation step on a sample of the training data.
train_eval_results = eval_fn(training_sample,
model,
params.train_maximum_sql_length,
name=train_pred_path,
write_results=True,
gold_forcing=True,
metrics=TRAIN_EVAL_METRICS,
bool_progressbar=False)[0]
for name, value in train_eval_results.items():
print(
"train final gold-passing " +
name.name +
":\t" +
"%.2f" %
value)
# Run an evaluation step on the validation set. - WITH GOLD FEED
valid_eval_results = eval_fn(valid_examples,
model,
params.eval_maximum_sql_length,
name=valid_pred_path,
write_results=True,
gold_forcing=True,
metrics=VALID_EVAL_METRICS,
bool_progressbar=False)[0]
for name, value in valid_eval_results.items():
print("valid gold-passing " + name.name + ":\t" + "%.2f" % value)
valid_loss = valid_eval_results[Metrics.LOSS]
# token_accuracy = valid_eval_results[Metrics.TOKEN_ACCURACY]
# string_accuracy = valid_eval_results[Metrics.STRING_ACCURACY]
if params.scheduler:
scheduler.step(valid_loss)
if valid_loss > previous_epoch_loss:
learning_rate_coefficient *= params.learning_rate_ratio
print(
"learning rate coefficient:\t" +
str(learning_rate_coefficient))
previous_epoch_loss = valid_loss
saved = False
# measuring the actual accuracy
eval_acc, actual_token_accuracy, actual_string_accuracy = evaluation(
model, data, eval_fn, valid_pred_write_path)
for name, value in zip(["eval accuracy", "actual token accuracy", "actual string accuracy"],
[eval_acc, actual_token_accuracy, actual_string_accuracy]):
print("valid post-eval " + name + ":\t" + "%.2f" % value)
if not saved and eval_acc > maximum_eval_acc:
maximum_eval_acc = eval_acc
countdown = int(patience)
model.save(save_path)
maximum_token_accuracy = actual_token_accuracy
maximum_string_accuracy = actual_string_accuracy
print("maximum eval accuracy:\t" + str(maximum_eval_acc))
print("actual token accuracy:\t" + str(actual_token_accuracy))
print("actual string accuracy:\t" + str(actual_string_accuracy))
print("patience:\t" + str(patience))
print("save file:\t" + str(save_path))
if countdown <= 0:
keep_training = False
countdown -= 1
print("countdown:\t" + str(countdown))
print("")
epochs += 1
print("Time stamp: {}".format(datetime.datetime.now()))
sys.stdout.flush()
print("Finished training!")
# loading the best checkpoint
print("## Loading the best checkpoint...")
model.load(save_path)
return maximum_eval_acc, maximum_token_accuracy, maximum_string_accuracy
def extract_weighted_example(old_example, generated_sql, utter_revision_fn,
feedback_records=None, gen_tag_seq=None, dec_seq=None, conf_threshold=None,
complete_vocab=None, weight_mode="pos,neg,conf", g_tag_seq=None, bool_verbal=True):
# should return a list like: [(['select', 'count', '(', 'head.*', ')', 'where', 'head.age', '>', 'value'], [])]
assert weight_mode in ("pos,neg,conf", "pos,conf", "pos", "pos2", "gold-assessment")
if generated_sql[-1] == "_EOS":
generated_sql = generated_sql[:-1]
if dec_seq is not None:
dec_seq = dec_seq[:-1]
true_sql = old_example.interaction.utterances[0].original_gold_query
new_example = copy.deepcopy(old_example)
new_output_sequences = [(generated_sql, [])]
new_utterance = utter_revision_fn(new_example.interaction.utterances[0], new_output_sequences)
# calculate weights
if weight_mode in ("pos,conf", "pos", "pos2", "gold-assessment"):
gold_query_to_use = new_utterance.gold_query_to_use
kw_indices = [complete_vocab.index(kw) for kw in ['select', 'where', 'group_by', 'having', 'order_by',
'intersect', 'union', 'except']]
if weight_mode == "pos,conf":
# collect positive or confident semantic units
su_list = [su for su, label in feedback_records if label == 'yes'] + \
[su for su in gen_tag_seq if su[-2] >= conf_threshold]
else:
# weight_mode in ("pos", "pos2", "gold-assessment")
su_list = [su for su, label in feedback_records if label == 'yes']
dec_seq_weights = [0.0] * len(dec_seq)
for su in su_list:
dec_idx = su[-1]
# dec_seq_weights[dec_idx] = 1.0
# revised 0206: there could be cases where dec_idx refers to an inaccurate position in multi-choice setting.
semantic_tag = su[0]
if semantic_tag in {SELECT_AGG_v2, ORDER_AGG_v2, HAV_AGG_v2}:
new_decision_item = []
col, agg, bool_distinct = su[1:4]
if agg[-1] > 0:
agg_name = AGG_OPS[agg[-1]]
new_decision_item.append(complete_vocab.index(agg_name))
new_decision_item.append(complete_vocab.index('('))
if bool_distinct:
new_decision_item.append(complete_vocab.index('distinct'))
new_decision_item.append(col[-1])
new_decision_item.append(complete_vocab.index(')'))
else:
if bool_distinct:
new_decision_item.append(complete_vocab.index('distinct'))
new_decision_item.append(col[-1])
if dec_seq[dec_idx] == new_decision_item:
dec_seq_weights[dec_idx] = 1.0
else:
bool_found = False
st_idx = dec_idx + 1
while st_idx < len(dec_seq) and (isinstance(dec_seq[st_idx], list) or dec_seq[st_idx] not in kw_indices):
if isinstance(dec_seq[st_idx], list) and dec_seq[st_idx] == new_decision_item:
dec_seq_weights[st_idx] = 1.0
bool_found = True
break
st_idx += 1
if not bool_found:
st_idx = dec_idx - 1
while st_idx >= 0 and (isinstance(dec_seq[st_idx], list) or dec_seq[st_idx] not in kw_indices):
if isinstance(dec_seq[st_idx], list) and dec_seq[st_idx] == new_decision_item:
bool_found = True
break
st_idx -= 1
if not bool_found: # likely appears before dec_idx
print("Exception in extract_weighted_example: su = {}, new_dec_item = {}\ndec_seq = {}\n".format(
su, new_decision_item, dec_seq))
elif semantic_tag in {WHERE_COL, GROUP_COL}:
new_decision_item = su[1][-1]
if not isinstance(dec_seq[dec_idx], list) and dec_seq[dec_idx] == new_decision_item:
dec_seq_weights[dec_idx] = 1.0
else:
bool_found = False
st_idx = dec_idx + 1
while st_idx < len(dec_seq) and (isinstance(dec_seq[st_idx], list) or dec_seq[st_idx] not in kw_indices):
if not isinstance(dec_seq[st_idx], list) and dec_seq[st_idx] == new_decision_item:
dec_seq_weights[st_idx] = 1.0
bool_found = True
break
st_idx += 1
if not bool_found:
st_idx = dec_idx - 1
while st_idx >= 0 and (isinstance(dec_seq[st_idx], list) or dec_seq[st_idx] not in kw_indices):
if not isinstance(dec_seq[st_idx], list) and dec_seq[st_idx] == new_decision_item:
bool_found = True
break
st_idx -= 1
if not bool_found: # likely appears before dec_idx
print("Exception in extract_weighted_example: su = {}, new_dec_item = {}\ndec_seq = {}\n".format(
su, new_decision_item, dec_seq))
else:
dec_seq_weights[dec_idx] = 1.0
gold_query_weights = []
gold_query_idx = 0
for dec_idx, dec_item in enumerate(dec_seq):
if dec_seq_weights[dec_idx] == 1.0:
if isinstance(dec_item, list):
gold_query_weights.extend([1.0] * len(dec_item))
gold_query_idx += len(dec_item)
else:
gold_query_weights.append(1.0)
gold_query_idx += 1
elif gold_query_to_use[gold_query_idx] in {'select', 'order_by', 'having', 'where', 'group_by',
'distinct', ',', 'and', 'or'}:
if weight_mode == "pos": # TODO: is this right?
gold_query_weights.append(0.0)
elif weight_mode == "pos2":
if gold_query_to_use[gold_query_idx] == 'distinct': # MISP does not verify it
gold_query_weights.append(0.0)
else:
gold_query_weights.append(None) # need further process
elif weight_mode == "gold-assessment":
if gold_query_to_use[gold_query_idx] == 'distinct' and gold_query_idx == 1:
gold_query_weights.append(float(true_sql[1] == 'distinct'))
else:
gold_query_weights.append(float(gold_query_to_use[gold_query_idx] in true_sql))
else:
gold_query_weights.append(1.0)
gold_query_idx += 1
elif gold_query_to_use[gold_query_idx] == 'value' and \
gold_query_to_use[gold_query_idx-3:gold_query_idx+1] == ['between', 'value', 'and', 'value'] and\
gold_query_weights[gold_query_idx-2] == 1:
gold_query_weights.append(1.0)
gold_query_idx += 1
else:
if isinstance(dec_item, list):
gold_query_weights.extend([0.0] * len(dec_item))
gold_query_idx += len(dec_item)
else:
gold_query_weights.append(0.0)
gold_query_idx += 1
if weight_mode == "pos2":
count_valid, count_valid_clause = 0, 0
for gold_query_idx in range(len(gold_query_weights))[::-1]:
if gold_query_weights[gold_query_idx] is None:
if gold_query_to_use[gold_query_idx] in {'select', 'order_by', 'having', 'where', 'group_by'}:
gold_query_weights[gold_query_idx] = float(count_valid_clause > 0)
count_valid_clause = 0
count_valid = 0
else:
assert gold_query_to_use[gold_query_idx] in {',', 'and', 'or'}
gold_query_weights[gold_query_idx] = float(count_valid > 0)
count_valid = 0
else:
count_valid += gold_query_weights[gold_query_idx]
count_valid_clause += gold_query_weights[gold_query_idx]
if weight_mode in ("pos", "pos2"):
if sum(gold_query_weights) == 0.0:
print("Example skipped with invalid weights!")
return None
else:
gold_query_weights += [0.0]
new_utterance.set_gold_query_weights(gold_query_weights)
elif weight_mode == "gold-assessment":
gold_query_weights += [float(len(g_tag_seq) == len(gen_tag_seq))] # no missing/redundant
new_utterance.set_gold_query_weights(gold_query_weights)
else:
gold_query_weights += [1.0] # with EOS
new_utterance.set_gold_query_weights(gold_query_weights)
if bool_verbal:
print("FINAL: gold_query_weights = {}".format(gold_query_weights))
new_example.interaction.utterances = [new_utterance]
return new_example.interaction
def online_learning(online_train_data_examples, init_train_data_examples, online_train_raw_examples, data,
user, agent, max_generation_length, model_save_dir, record_save_path,
update_iter, model_renew_fn, utter_revision_fn, start_idx=0, end_idx=-1,
metrics=None, database_username=None, database_password=None, database_timeout=None,
bool_interaction=True, supervision="misp_neil"):
""" Online learning with MISP. """
class pseudoDatasetSplit: # a simplified class to be used as DatasetSplit
def __init__(self, examples):
self.examples = examples
database_schema = read_schema(table_schema_path)
def _evaluation(example, gen_sequence, raw_query):
# check acc & add to record
flat_pred = example.flatten_sequence(gen_sequence)
pred_sql_str = ' '.join(flat_pred)
assert len(example.identifier.split('/')) == 2
database_id, interaction_id = example.identifier.split('/')
postprocessed_sql_str = postprocess_one(pred_sql_str, database_schema[database_id])
try:
exact_score, partial_scores, hardness = evaluate_single(
postprocessed_sql_str, raw_query, db_path, database_id, agent.world_model.kmaps)
except:
question = example.interaction.utterances[0].original_input_seq
print("Exception in evaluate_single:\nidx: {}, db: {}, question: {}\np_str: {}\ng_str: {}\n".format(
idx, database_id, " ".join(question), postprocessed_sql_str, raw_query))
exact_score = 0.0
partial_scores = "Exception"
hardness = "Unknown"
return exact_score, partial_scores, hardness
num_total_examples = len(online_train_data_examples)
online_train_data = data.get_all_interactions(pseudoDatasetSplit(online_train_data_examples))
if supervision == "misp_neil":
weight_mode = "pos,conf"
else:
assert supervision == "misp_neil_pos"
weight_mode = "pos"
metrics_sums = {}
for metric in metrics:
metrics_sums[metric] = 0.
interaction_records = []
annotation_buffer = []
# per 1K iteration
iter_annotation_buffer = []
iter_annotated_example_scores = [] # exact scores of annotated examples in the buffer (for analysis)
if start_idx > 0:
print("Loading interaction records from %s..." % record_save_path)
interaction_records = json.load(open(record_save_path, 'r'))
print("Record item size: %d " % len(interaction_records))
learning_start_time = datetime.datetime.now()
print("## Online starting time: {}".format(learning_start_time))
count_exception, count_exit = 0, 0
for idx, (raw_example, example) in enumerate(zip(online_train_raw_examples, online_train_data)):
if idx < len(interaction_records):
record = interaction_records[idx]
count_exception += int(record['exception'])
count_exit += int(record['exit'])
if record['exception']:
print("Example skipped!")
sequence = eval(record['sql'])
else:
sequence = eval(record['sql'])
try:
tag_seq = eval(record["tag_seq"])
except:
print(" exception in recovering tag_seq: {}".format(record['tag_seq']))
assert "array" in record["tag_seq"]
_tag_seq = record["tag_seq"].replace("array", "")
_tag_seq = eval(_tag_seq)
tag_seq = []
for su in _tag_seq:
if isinstance(su[-2], list):
su = list(su)
su[-2] = su[-2][0]
su = tuple(su)
tag_seq.append(su)
complete_vocab = []
try:
g_sql = eval(record['true_sql_i'])
except:
# this happens when base_vocab was incorrectly saved in json
assert 'base_vocab' in record['true_sql_i']
base_vocab_idx = record['true_sql_i'].index("\'base_vocab\'")
true_sql_i_str = record['true_sql_i'][:base_vocab_idx-2] + '}'
g_sql = eval(true_sql_i_str)
base_vocab = agent.world_model.vocab
for id in range(len(base_vocab)):
complete_vocab.append(base_vocab.id_to_token(id))
id2col_name = {v: k for k, v in g_sql["column_names_surface_form_to_id"].items()}
for id in range(len(g_sql["column_names_surface_form_to_id"])):
complete_vocab.append(id2col_name[id])
annotated_example = extract_weighted_example(example, sequence, utter_revision_fn,
feedback_records=eval(record['feedback_records']),
gen_tag_seq=tag_seq,
dec_seq=eval(record['dec_seq']),
conf_threshold=agent.error_detector.prob_threshold,
complete_vocab=complete_vocab,
weight_mode=weight_mode)
if annotated_example is not None:
iter_annotation_buffer.append(annotated_example)
iter_annotated_example_scores.append(record['exact_score'])
else:
with torch.no_grad():
input_item = agent.world_model.semparser.spider_single_turn_encoding(
example, max_generation_length)
question = example.interaction.utterances[0].original_input_seq
true_sql = example.interaction.utterances[0].original_gold_query
print("\n" + "#" * 50)
print("Example {}:".format(idx))
print("NL input: {}".format(" ".join(question)))
print("True SQL: {}".format(" ".join(true_sql)))
g_sql = raw_example['sql']
g_sql["extracted_clause_asterisk"] = extract_clause_asterisk(true_sql)
g_sql["column_names_surface_form_to_id"] = input_item[-1].column_names_surface_form_to_id
g_sql["base_vocab"] = agent.world_model.vocab
complete_vocab = []
for id in range(len(g_sql["base_vocab"])):
complete_vocab.append(g_sql["base_vocab"].id_to_token(id))
id2col_name = {v: k for k, v in g_sql["column_names_surface_form_to_id"].items()}
for id in range(len(g_sql["column_names_surface_form_to_id"])):
complete_vocab.append(id2col_name[id])
try:
hyp = agent.world_model.decode(input_item, bool_verbal=False, dec_beam_size=1)[0]
print("-" * 50 + "\nBefore interaction: \ninitial SQL: {}".format(" ".join(hyp.sql)))
except Exception: # tag_seq generation exception - e.g., when its syntax is wrong
count_exception += 1
# traceback.print_exc()
print("Decoding Exception (count = {}) in example {}!".format(count_exception, idx))
final_encoder_state, encoder_states, schema_states, max_generation_length, snippets, input_sequence, \
previous_queries, previous_query_states, input_schema = input_item
prediction = agent.world_model.semparser.decoder(
final_encoder_state,
encoder_states,
schema_states,
max_generation_length,
snippets=snippets,
input_sequence=input_sequence,
previous_queries=previous_queries,
previous_query_states=previous_query_states,
input_schema=input_schema,
dropout_amount=0.0)
print("-" * 50 + "\nBefore interaction: \ninitial SQL: {}".format(" ".join(prediction.sequence)))
sequence = prediction.sequence
probability = prediction.probability
exact_score, partial_scores, hardness = _evaluation(example, sequence, raw_example['query'])
g_sql.pop('base_vocab') # do not save it
record = {'nl': " ".join(question), 'true_sql': " ".join(true_sql),
'true_sql_i': "{}".format(g_sql),
'sql': "{}".format(sequence), 'dec_seq': "None",
'tag_seq': "None", 'logprob': "{}".format(np.log(probability)),
"questioned_indices": [], 'q_counter': 0,
'exit': False, 'exception': True,
'exact_score': exact_score, 'partial_scores': "{}".format(partial_scores),
'hardness': hardness, 'idx': idx}
interaction_records.append(record)
print("Example skipped!")
else:
if not bool_interaction:
exact_score, partial_scores, hardness = _evaluation(example, hyp.sql, raw_example['query'])
g_sql.pop('base_vocab') # do not save it
record = {'nl': " ".join(question), 'true_sql': " ".join(true_sql),
'true_sql_i': "{}".format(g_sql),
'sql': "{}".format(hyp.sql), 'dec_seq': "{}".format(hyp.dec_seq),
'tag_seq': "{}".format(hyp.tag_seq), 'logprob': "{}".format(hyp.logprob),
"questioned_indices": [], 'q_counter': 0, 'exit': False, 'exception': False,
'exact_score': exact_score, 'partial_scores': "{}".format(partial_scores),
'hardness': hardness, 'idx': idx}
interaction_records.append(record)
else:
try:
new_hyp, bool_exit = agent.interactive_parsing_session(user, input_item, g_sql, hyp,
bool_verbal=False)
if bool_exit:
count_exit += 1
except Exception:
count_exception += 1
# traceback.print_exc()
print("Interaction Exception (count = {}) in example {}!".format(count_exception, idx))
print("-" * 50 + "\nAfter interaction: \nfinal SQL: {}".format(" ".join(hyp.sql)))
exact_score, partial_scores, hardness = _evaluation(example, hyp.sql, raw_example['query'])
g_sql.pop('base_vocab') # do not save it
record = {'nl': " ".join(question), 'true_sql': " ".join(true_sql),
'true_sql_i': "{}".format(g_sql),
'sql': "{}".format(hyp.sql), 'dec_seq': "{}".format(hyp.dec_seq),
'tag_seq': "{}".format(hyp.tag_seq), 'logprob': "{}".format(hyp.logprob),
'exit': False, 'exception': True,
'q_counter': user.q_counter, # questions are still counted
'questioned_indices': user.questioned_pointers,
'questioned_tags': "{}".format(user.questioned_tags),
'feedback_records': "{}".format(user.feedback_records),
'exact_score': exact_score, 'partial_scores': "{}".format(partial_scores),
'hardness': hardness, 'idx': idx}
interaction_records.append(record)
print("Example skipped!")
else:
hyp = new_hyp
print("-" * 50 + "\nAfter interaction: \nfinal SQL: {}".format(" ".join(hyp.sql)))
exact_score, partial_scores, hardness = _evaluation(example, hyp.sql, raw_example['query'])
g_sql.pop('base_vocab') # do not save it
record = {'nl': " ".join(question), 'true_sql': " ".join(true_sql),
'true_sql_i': "{}".format(g_sql),
'sql': "{}".format(hyp.sql), 'dec_seq': "{}".format(hyp.dec_seq),
'tag_seq': "{}".format(hyp.tag_seq), 'logprob': "{}".format(hyp.logprob),
'exit': bool_exit, 'exception': False, 'q_counter': user.q_counter,
'questioned_indices': user.questioned_pointers,
'questioned_tags': "{}".format(user.questioned_tags),
'feedback_records': "{}".format(user.feedback_records),
'exact_score': exact_score, 'partial_scores': "{}".format(partial_scores),
'hardness': hardness, 'idx': idx}
interaction_records.append(record)
annotated_example = extract_weighted_example(example, hyp.sql, utter_revision_fn,
feedback_records=user.feedback_records,
gen_tag_seq=hyp.tag_seq,
dec_seq=hyp.dec_seq,
conf_threshold=agent.error_detector.prob_threshold,
complete_vocab=complete_vocab,
weight_mode=weight_mode)
if annotated_example is not None:
iter_annotation_buffer.append(annotated_example)
iter_annotated_example_scores.append(record['exact_score'])
sequence = hyp.sql
probability = np.exp(hyp.logprob)
original_utt = example.interaction.utterances[0]
gold_query = original_utt.gold_query_to_use
original_gold_query = original_utt.original_gold_query
gold_table = original_utt.gold_sql_results
gold_queries = [q[0] for q in original_utt.all_gold_queries]
gold_tables = [q[1] for q in original_utt.all_gold_queries]
flat_sequence = example.flatten_sequence(sequence)
update_sums(metrics,
metrics_sums,
sequence,
flat_sequence,
gold_query,
original_gold_query,
database_username=database_username,
database_password=database_password,
database_timeout=database_timeout,
gold_table=gold_table)
sys.stdout.flush()
if (idx+1) % update_iter == 0 or (idx+1) == num_total_examples: # update model
print("\n~~~\nCurrent interaction performance (iter {}): ".format(idx+1)) # interaction so far
eval_results = construct_averages(metrics_sums, idx+1)
for name, value in eval_results.items():
print(name.name + ":\t" + "%.2f" % value)
exact_acc = np.average([float(item['exact_score']) for item in interaction_records[:(idx+1)]])
print("Exact acc: %.3f" % (exact_acc * 100.0))
# per 1K iteration: the actual acc of collected examples
iter_annotated_example_acc = np.average(iter_annotated_example_scores)
print("ANALYSIS: iter_annotated_example_acc: %.3f\n" % (iter_annotated_example_acc * 100.0))
# stats
q_count = sum([item['q_counter'] for item in interaction_records[:(idx+1)]])
print("#questions: {}, #questions per example: {:.3f}.".format(
q_count, q_count * 1.0 / len(interaction_records[:(idx+1)])))
print("#exit: {}".format(count_exit))
if (idx + 1) <= start_idx:
annotation_buffer.extend(iter_annotation_buffer)
iter_annotation_buffer = []
iter_annotated_example_scores = []
continue
print("Saving interaction records to %s...\n" % record_save_path)
json.dump(interaction_records, open(record_save_path, 'w'), indent=4)
annotation_buffer.extend(iter_annotation_buffer)
iter_annotation_buffer = []
iter_annotated_example_scores = []
# parser update
print("~~~\nUpdating base semantic parser at iter {}".format(idx+1))
update_buffer = init_train_data_examples + annotation_buffer
print("Train data size: %d" % len(update_buffer))
print("Retraining from scratch...")
model = agent.world_model.semparser
# re-initialize
model = model_renew_fn(model)
model.build_optim()
agent.world_model.semparser = model
# train
print("## Starting update at iter {}, anno_cost {}...time spent {}".format(
idx+1, sum([item['q_counter'] for item in interaction_records]),
datetime.datetime.now() - learning_start_time))
data.train_data.examples = update_buffer
model_dir = os.path.join(model_save_dir, '%d/' % (idx + 1))
if not os.path.isdir(model_dir):
os.mkdir(model_dir)
sys.stdout.flush()
eval_acc, token_acc, string_acc = train(agent.world_model.semparser, data, params, model_dir)
print("## Ending update at iter {}, anno_cost {}, eval_acc {}, token_acc {}, string_acc {}...time spent {}\n".format(
idx+1, sum([item['q_counter'] for item in interaction_records]), eval_acc, token_acc, string_acc,