-
Notifications
You must be signed in to change notification settings - Fork 3
/
interact.py
1453 lines (1241 loc) · 69 KB
/
interact.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
import os
import torch
import random
import argparse
import numpy as np
import torch.nn as nn
from tqdm import tqdm
from itertools import chain
from collections import OrderedDict
from types import SimpleNamespace
from torch.nn.utils.rnn import pad_sequence
from transformers import T5ForConditionalGeneration, T5Tokenizer, GPT2LMHeadModel, GPT2Tokenizer, BertForNextSentencePrediction, BertTokenizer
from utils.utils import load_json, save_json, convert_goal_dict_to_span, convert_generate_action_span_to_dict, \
update_goal_states_during_gen, get_or_create_logger, split_user_act_and_resp
from utils import definitions
from external_knowledges import MultiWozDB
from evaluator import MultiWozEvaluator, convert_results_format
from reader import MultiWOZReader
logger = get_or_create_logger(__name__)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
device2 = torch.device('cpu') # GPU out of memory
# special tokens map
mttod_to_pptod = {
'<bos_user>': '<sos_u>',
'<eos_user>': '<eos_u>',
'<bos_resp>': '<sos_r>',
'<eos_resp>': '<eos_r>',
'<bos_belief>': '<sos_b>',
'<eos_belief>': '<eos_b>',
'<bos_act>': '<sos_a>',
'<eos_act>': '<eos_a>',
'<bos_db>': '<sos_d>',
'<eos_db>': '<eos_d>',
}
pptod_to_mttod = {
'<sos_u>': '<bos_user>',
'<eos_u>': '<eos_user>',
'<sos_r>': '<bos_resp>',
'<eos_r>': '<eos_resp>',
'<sos_b>': '<bos_belief>',
'<eos_b>': '<eos_belief>',
'<sos_a>': '<bos_act>',
'<eos_a>': '<eos_act>',
'<sos_d>': '<bos_db>',
'<eos_d>': '<eos_db>',
}
def get_config():
parser = argparse.ArgumentParser(description='RL config')
parser.add_argument("-rl_dial_one_epoch", type=int, default=200)
parser.add_argument("-rl_batch_size", type=int, default=1)
parser.add_argument("-epochs", type=int, default=20)
parser.add_argument("-simulator_path", type=str, default='./simulator_t5_small/ckpt-epoch11')
parser.add_argument("-dialog_sys_path", type=str, default='./dialogue_t5_small/ckpt-epoch11')
parser.add_argument("-simulator_save_path", type=str, default=None)
parser.add_argument("-dialog_save_path", type=str, default=None)
parser.add_argument("-max_turn_num", type=int, default=20)
parser.add_argument("-data_dir", type=str, default='./data/MultiWOZ_2.0/')
parser.add_argument("-model_dir", type=str, default="dialogue_t5_small")
parser.add_argument("-discount_factor", type=float, default=0.99)
parser.add_argument('-rl_lr', type=float, default=0.0001, help='learning rate for reinforcement learning')
parser.add_argument('-grad_clip', type=float, default=1)
parser.add_argument("-seed", type=int, default=1998)
parser.add_argument('-do_rl_training', action="store_true")
parser.add_argument('-use_ppl_as_reward', action="store_true")
parser.add_argument('-ppl_ckpt', type=str, default='./gpt_lm_model_lr_1e_4_sentence/ckpt-epoch6')
parser.add_argument('-use_nsp_score_as_reward', action="store_true")
parser.add_argument('-nsp_ckpt', type=str, default='./bert_nsp_model_lr_1e_5_1/ckpt-epoch9')
parser.add_argument('-gpt_score_ckpt', type=str, default='./bart_score_gpt_lm_model_lr_1e_4/ckpt-epoch6')
parser.add_argument('-nsp_coef', type=float, default=0.1)
parser.add_argument('-ppl_coef', type=float, default=0.1)
parser.add_argument('-use_bart_score', action="store_true")
parser.add_argument('-use_gpt_score_as_reward', action="store_true")
parser.add_argument('-gpt_score_coef', type=float, default=0.1)
parser.add_argument('-use_mean_rl_loss', action="store_true")
parser.add_argument('-generate_results_path', type=str, default='generate_results.json')
parser.add_argument('-interaction_type', type=str, default='test', choices=['test', 'dev'])
parser.add_argument('-model_name', type=str, default='mttod', choices=['mttod', 'ubar', 'pptod', 'galaxy'])
args = parser.parse_args()
return args
class InteractionEnvironment(object):
def __init__(self, cfg) -> None:
self.cfg = cfg
self.simulator_model = self.load_simulator(self.cfg.simulator_path)
self.dialog_model = self.load_system(self.cfg.dialog_sys_path)
self.simulator_tokenizer = self.load_simulator_tokenizer(self.cfg.simulator_path)
self.dialog_tokenizer = self.load_sys_tokenizer(self.cfg.dialog_sys_path)
self.data_dir = self.cfg.data_dir
db_path = os.path.join(os.path.dirname(self.data_dir), 'db')
logger.info("Load Database from {}".format(db_path))
self.db = MultiWozDB(db_path)
self.get_goal_list()
# pptod prefix
if self.cfg.model_name == 'pptod':
bs_prefix_text = 'translate dialogue to belief state:'
da_prefix_text = 'translate dialogue to dialogue action:'
nlg_prefix_text = 'translate dialogue to system response:'
self.bs_prefix_id = self.dialog_tokenizer.convert_tokens_to_ids(self.dialog_tokenizer.tokenize(bs_prefix_text))
self.da_prefix_id = self.dialog_tokenizer.convert_tokens_to_ids(self.dialog_tokenizer.tokenize(da_prefix_text))
self.nlg_prefix_id = self.dialog_tokenizer.convert_tokens_to_ids(self.dialog_tokenizer.tokenize(nlg_prefix_text))
self.sos_context_token_id = self.dialog_tokenizer.convert_tokens_to_ids(['<sos_context>'])[0]
self.eos_context_token_id = self.dialog_tokenizer.convert_tokens_to_ids(['<eos_context>'])[0]
@property
def all_goals(self):
return self.goal_list
def load_simulator(self, model_path):
logger.info("Load simulator model from {}".format(model_path))
if not os.path.exists(model_path):
raise Exception('Model path is invalid!')
return T5ForConditionalGeneration.from_pretrained(model_path)
def load_system(self, model_path):
if self.cfg.model_name == 'mttod':
logger.info("Load system model from {}".format(model_path))
if not os.path.exists(model_path):
raise Exception('Model path is invalid!')
return T5ForConditionalGeneration.from_pretrained(model_path)
elif self.cfg.model_name == 'ubar':
logger.info("Load system model from {}".format(model_path))
if not os.path.exists(model_path):
raise Exception('Model path is invalid!')
return GPT2LMHeadModel.from_pretrained(model_path)
elif self.cfg.model_name == 'pptod':
logger.info("Load system model from {}".format(model_path))
if not os.path.exists(model_path):
raise Exception('Model path is invalid!')
return T5ForConditionalGeneration.from_pretrained(model_path)
elif self.cfg.model_name == 'galaxy':
raise NotImplementedError
def load_simulator_tokenizer(self, tokenizer_path):
logger.info("Load simulator tokenizer from {}".format(tokenizer_path))
if not os.path.exists(tokenizer_path):
raise Exception('Tokenizer path is invalid!')
return T5Tokenizer.from_pretrained(tokenizer_path)
def load_sys_tokenizer(self, tokenizer_path):
if self.cfg.model_name == 'mttod':
logger.info("Load system tokenizer from {}".format(tokenizer_path))
if not os.path.exists(tokenizer_path):
raise Exception('Tokenizer path is invalid!')
return T5Tokenizer.from_pretrained(tokenizer_path)
elif self.cfg.model_name == 'ubar':
logger.info("Load system tokenizer from {}".format(tokenizer_path))
if not os.path.exists(tokenizer_path):
raise Exception('Tokenizer path is invalid!')
return GPT2Tokenizer.from_pretrained(tokenizer_path)
elif self.cfg.model_name == 'pptod':
logger.info("Load system tokenizer from {}".format(tokenizer_path))
if not os.path.exists(tokenizer_path):
raise Exception('Tokenizer path is invalid!')
return T5Tokenizer.from_pretrained(tokenizer_path)
elif self.cfg.model_name == 'galaxy':
raise NotImplementedError
logger.info("Load tokenizer from {}".format(tokenizer_path))
if not os.path.exists(tokenizer_path):
raise Exception('Tokenizer path is invalid!')
return T5Tokenizer.from_pretrained(tokenizer_path)
def get_goal_list(self):
train_data_path = os.path.join(self.data_dir, 'processed', 'train_data.json')
valid_data_path = os.path.join(self.data_dir, 'processed', 'dev_data.json')
test_data_path = os.path.join(self.data_dir, 'processed', 'test_data.json')
train_data = load_json(train_data_path)
valid_data = load_json(valid_data_path)
test_data = load_json(test_data_path)
data = {'train': train_data, 'valid': valid_data, 'test': test_data}
self.goal_list = {'train': [], 'valid': [], 'test': []}
for data_type in data:
for dialog_id, session in data[data_type].items():
self.goal_list[data_type].append({'dialog_id': dialog_id, 'goal': session['goal']})
assert len(data['train']) == len(self.goal_list['train'])
assert len(data['valid']) == len(self.goal_list['valid'])
assert len(data['test']) == len(self.goal_list['test'])
def flatten_dial_history(self, dial_history, len_postifx, max_length):
ctx_len = sum([len(c) for c in dial_history])
#consider eos_token
spare_len = max_length - len_postifx - 1
while ctx_len >= spare_len:
ctx_len -= len(dial_history[0])
dial_history.pop(0)
context = list(chain(*dial_history))
return context
def tensorize(self, ids):
return torch.tensor(ids, dtype=torch.long)
def encode_text(self, text, tokenizer, bos_token=None, eos_token=None, special_tokens_map=None):
tokens = text.split() if isinstance(text, str) else text
assert isinstance(tokens, list)
# replace special tokens
if special_tokens_map != None:
for i in range(len(tokens)):
if tokens[i] in special_tokens_map:
tokens[i] = special_tokens_map[tokens[i]]
if bos_token is not None:
if isinstance(bos_token, str):
bos_token = [bos_token]
tokens = bos_token + tokens
if eos_token is not None:
if isinstance(eos_token, str):
eos_token = [eos_token]
tokens = tokens + eos_token
encoded_text = tokenizer.encode(" ".join(tokens))
# except eos token
if encoded_text[-1] == tokenizer.eos_token_id:
encoded_text = encoded_text[:-1]
return encoded_text
def split_system_act_and_resp(self, model_output, model_output_prob=None):
if model_output_prob is not None:
pad_tensor = torch.tensor([0,0,0,0]).to(device)
model_output_prob = torch.cat((pad_tensor, model_output_prob)) # pad for db tokens
bos_act_token_id = self.dialog_tokenizer.convert_tokens_to_ids(definitions.BOS_ACTION_TOKEN)
eos_act_token_id = self.dialog_tokenizer.convert_tokens_to_ids(definitions.EOS_ACTION_TOKEN)
bos_resp_token_id = self.dialog_tokenizer.convert_tokens_to_ids(definitions.BOS_RESP_TOKEN)
eos_resp_token_id = self.dialog_tokenizer.convert_tokens_to_ids(definitions.EOS_RESP_TOKEN)
eos_token_id = self.dialog_tokenizer.eos_token_id
if eos_token_id in model_output:
eos_idx = model_output.index(eos_token_id)
model_output = model_output[:eos_idx]
if model_output_prob is not None:
model_output_prob = model_output_prob[:eos_idx]
# aspn
aspn_prob = None
if bos_act_token_id in model_output and eos_act_token_id in model_output:
bos_action_idx = model_output.index(bos_act_token_id)
eos_action_idx = model_output.index(eos_act_token_id)
aspn = model_output[bos_action_idx:eos_action_idx + 1]
if model_output_prob is not None:
aspn_prob = model_output_prob[bos_action_idx:eos_action_idx + 1]
else:
aspn = [bos_act_token_id, eos_act_token_id]
if model_output_prob is not None:
aspn_prob = model_output_prob[:2]
aspn_prob = 0 * aspn_prob
resp_prob = None
if bos_resp_token_id in model_output and eos_resp_token_id in model_output:
bos_resp_token_idx = model_output.index(bos_resp_token_id)
eos_resp_token_idx = model_output.index(eos_resp_token_id)
resp = model_output[bos_resp_token_idx:eos_resp_token_idx+1]
if model_output_prob is not None:
resp_prob = model_output_prob[bos_resp_token_idx:eos_resp_token_idx+1]
elif eos_act_token_id in model_output:
eos_action_idx = len(model_output) - model_output[::-1].index(eos_act_token_id) - 1
resp = model_output[eos_action_idx + 1:]
if model_output_prob is not None:
resp_prob = model_output_prob[eos_action_idx + 1:]
if resp[-1] != eos_resp_token_id:
resp.append(eos_resp_token_id)
if model_output_prob is not None:
pad_tensor = torch.tensor([1.0]).to(device)
resp_prob = torch.cat((resp_prob, pad_tensor))
if resp[0] != bos_resp_token_id:
resp = [bos_resp_token_id] + resp
if model_output_prob is not None:
pad_tensor = torch.tensor([1.0]).to(device)
resp_prob = torch.cat((pad_tensor, resp_prob))
else:
resp = [bos_resp_token_id, eos_resp_token_id]
if model_output_prob is not None:
resp_prob = model_output_prob[:2]
resp_prob = 0 * resp_prob
return aspn, resp, aspn_prob, resp_prob
def finalize_bspn(self, belief_outputs, belief_states_prob=None):
if self.cfg.model_name == 'mttod':
eos_belief_token_id = self.dialog_tokenizer.convert_tokens_to_ids(definitions.EOS_BELIEF_TOKEN)
else:
eos_belief_token_id = self.dialog_tokenizer.convert_tokens_to_ids('<eos_b>')
if belief_outputs[0] == self.dialog_tokenizer.pad_token_id:
belief_outputs = belief_outputs[1:]
if belief_outputs[-1] == self.dialog_tokenizer.eos_token_id:
belief_outputs = belief_outputs[:-1]
if belief_states_prob is not None:
belief_states_prob = belief_states_prob[:-1]
if eos_belief_token_id not in belief_outputs:
eos_idx = len(belief_outputs) - 1
else:
eos_idx = belief_outputs.index(eos_belief_token_id)
if belief_states_prob is not None:
return belief_outputs[:eos_idx+1], belief_states_prob[:eos_idx+1]
else:
return belief_outputs[:eos_idx+1], None
def finalize_aspn(self, aspn_outputs, aspn_states_prob=None):
if self.cfg.model_name == 'mttod':
eos_action_token_id = self.dialog_tokenizer.convert_tokens_to_ids(definitions.EOS_ACTION_TOKEN)
else:
eos_action_token_id = self.dialog_tokenizer.convert_tokens_to_ids('<eos_a>')
if aspn_outputs[0] == self.dialog_tokenizer.pad_token_id:
aspn_outputs = aspn_outputs[1:]
if aspn_outputs[-1] == self.dialog_tokenizer.eos_token_id:
aspn_outputs = aspn_outputs[:-1]
if aspn_states_prob is not None:
aspn_states_prob = aspn_states_prob[:-1]
if eos_action_token_id not in aspn_outputs:
eos_idx = len(aspn_outputs) - 1
else:
eos_idx = aspn_outputs.index(eos_action_token_id)
if aspn_states_prob is not None:
return aspn_outputs[:eos_idx+1], aspn_states_prob[:eos_idx+1]
else:
return aspn_outputs[:eos_idx+1], None
def finalize_resp(self, resp_outputs, resp_states_prob=None):
if self.cfg.model_name == 'mttod':
eos_resp_token_id = self.dialog_tokenizer.convert_tokens_to_ids(definitions.EOS_RESP_TOKEN)
else:
eos_resp_token_id = self.dialog_tokenizer.convert_tokens_to_ids('<eos_r>')
if resp_outputs[0] == self.dialog_tokenizer.pad_token_id:
resp_outputs = resp_outputs[1:]
if resp_outputs[-1] == self.dialog_tokenizer.eos_token_id:
resp_outputs = resp_outputs[:-1]
if resp_states_prob is not None:
resp_states_prob = resp_states_prob[:-1]
if eos_resp_token_id not in resp_outputs:
eos_idx = len(resp_outputs) - 1
else:
eos_idx = resp_outputs.index(eos_resp_token_id)
if resp_states_prob is not None:
return resp_outputs[:eos_idx+1], resp_states_prob[:eos_idx+1]
else:
return resp_outputs[:eos_idx+1], None
def bspn_to_constraint_dict(self, bspn):
bspn = bspn.split() if isinstance(bspn, str) else bspn
if self.cfg.model_name == 'mttod':
eos_belief_token = definitions.EOS_BELIEF_TOKEN
else:
eos_belief_token = '<eos_b>'
constraint_dict = OrderedDict()
domain, slot = None, None
for token in bspn:
if token == eos_belief_token:
break
if token.startswith("["):
token = token[1:-1]
if token in definitions.ALL_DOMAINS:
domain = token
if token.startswith("value_"):
if domain is None:
continue
if domain not in constraint_dict:
constraint_dict[domain] = OrderedDict()
slot = token.split("_")[1]
constraint_dict[domain][slot] = []
else:
try:
if domain is not None and slot is not None:
constraint_dict[domain][slot].append(token)
except KeyError:
continue
for domain, sv_dict in constraint_dict.items():
for s, value_tokens in sv_dict.items():
constraint_dict[domain][s] = " ".join(value_tokens)
return constraint_dict
def constraint_dict_to_bspn(self, constraint_dict):
tokens = []
for domain, sv_dict in constraint_dict.items():
tokens.append("[" + domain + "]")
for s, v in sv_dict.items():
tokens.append("[value_" + s + "]")
tokens.extend(v.split())
return " ".join(tokens)
def bspn_to_db_pointer(self, bspn, turn_domain):
constraint_dict = self.bspn_to_constraint_dict(bspn)
matnums = self.db.get_match_num(constraint_dict)
match_dom = turn_domain[0] if len(turn_domain) == 1 else turn_domain[1]
match_dom = match_dom[1:-1] if match_dom.startswith("[") else match_dom
match = matnums[match_dom]
db_token = self.db.addDBIndicator(match_dom, match)
return db_token
def generate_single_dialog(self, user_goal, with_logprob=False, agent=None):
self.simulator_model.to(device)
self.dialog_model.to(device)
# clear fail info and invalid/prev_invalid field
for domain in user_goal['goal']:
if 'fail_info' in user_goal['goal'][domain]:
del user_goal['goal'][domain]['fail_info']
if 'fail_book' in user_goal['goal'][domain]:
del user_goal['goal'][domain]['fail_book']
if 'book' in user_goal['goal'][domain]:
if 'invalid' in user_goal['goal'][domain]['book']:
del user_goal['goal'][domain]['book']['invalid']
if 'pre_invalid' in user_goal['goal'][domain]['book']:
del user_goal['goal'][domain]['book']['pre_invalid']
dial_gen = {user_goal['dialog_id']: {'goal': user_goal['goal']}}
log = []
dialog_history = []
goal_state_dict = user_goal['goal']
goal_state_span = convert_goal_dict_to_span(user_goal['goal'])
user_utterance = None
turn_domain = None
system_act = None
user_act = None
utterance_count = 0
single_turn = {}
if with_logprob:
output_scores=True
return_dict_in_generate=True
else:
output_scores=False
return_dict_in_generate=False
if_sys_need_grad = True if agent is not None and agent == 'sys' else False
if_usr_need_grad = True if agent is not None and agent == 'usr' else False
def is_continue(dial_gen):
if 'sys' not in single_turn and 'user' in single_turn:
# end up with system resp
return True
if len(goal_state_dict) == 0:
# goal清空后终止
dial_gen['terminate_reason'] = 'goal清空后终止'
return False
if len(log) >= self.cfg.max_turn_num:
# 超过固定轮数终止
dial_gen['terminate_reason'] = '超过{}轮终止'.format(self.cfg.max_turn_num)
return False
if system_act and ('[bye]' in system_act or '[thank]' in system_act):
dial_gen['terminate_reason'] = 'system said thank or bye'
return False
if user_act and ('[bye]' in user_act or '[thank]' in user_act):
dial_gen['terminate_reason'] = 'user said thank or bye'
return False
# 不满足退出条件则继续循环
return True
while is_continue(dial_gen): # 需要判断一个会话是否结束,满足结束条件则需要退出循环
if utterance_count & 1 :
'''
system agent:
input: user + dialog history;
output1: belief states;
output2: action + response;
update user's goal state;
'''
utterance_count += 1
if user_utterance is None:
raise Exception('Should generate user utterance first!')
user_utterance_ids = self.encode_text(user_utterance, self.dialog_tokenizer)
encoded_dialog_history = [self.encode_text(text, self.dialog_tokenizer) for text in dialog_history]
context = self.flatten_dial_history(encoded_dialog_history, len(user_utterance_ids), self.dialog_tokenizer.model_max_length)
input_ids = self.tensorize([context + user_utterance_ids + [self.dialog_tokenizer.eos_token_id]])
input_ids = input_ids.to(device)
dialog_generate = self.dialog_model.generate.__wrapped__
bspn_decoder_input_ids = self.tensorize([[self.dialog_tokenizer.pad_token_id] + [self.dialog_tokenizer.convert_tokens_to_ids(definitions.BOS_BELIEF_TOKEN)]])
bspn_decoder_input_ids = bspn_decoder_input_ids.to(device)
# belief states generation
torch.set_grad_enabled(if_sys_need_grad)
model_output = dialog_generate(
self.dialog_model,
input_ids=input_ids,
decoder_input_ids=bspn_decoder_input_ids,
eos_token_id=self.dialog_tokenizer.eos_token_id,
# max_length=100,
max_length=80,
output_scores=output_scores,
return_dict_in_generate=return_dict_in_generate,
)
torch.set_grad_enabled(True)
if with_logprob:
belief_states_output = model_output.sequences.cpu().numpy().tolist()
belief_states_prob = torch.max(torch.stack(model_output.scores, dim=1).softmax(-1), dim=-1).values[0]
else:
belief_states_output = model_output.cpu().numpy().tolist()
belief_states_prob = None
bspn_gen, _ = self.finalize_bspn(belief_states_output[0])
if with_logprob:
single_turn['bspn_prob'] = belief_states_prob
bspn_gen = self.dialog_tokenizer.decode(bspn_gen, clean_up_tokenization_spaces=False)
single_turn['belief_states'] = bspn_gen
if turn_domain is None:
raise Exception('Domain is empty')
db_token = self.bspn_to_db_pointer(bspn_gen, turn_domain)
dbpn_gen = self.encode_text(db_token, self.dialog_tokenizer, bos_token=definitions.BOS_DB_TOKEN, eos_token=definitions.EOS_DB_TOKEN)
single_turn['dbpn'] = self.dialog_tokenizer.decode(dbpn_gen)
dbpn_gen = [self.dialog_tokenizer.pad_token_id] + dbpn_gen
resp_decoder_input_ids = self.tensorize([dbpn_gen])
resp_decoder_input_ids = resp_decoder_input_ids.to(device)
# response generation
torch.set_grad_enabled(if_sys_need_grad)
model_output = dialog_generate(
self.dialog_model,
input_ids=input_ids,
decoder_input_ids=resp_decoder_input_ids,
eos_token_id=self.dialog_tokenizer.eos_token_id,
# max_length=200,
max_length=100,
output_scores=output_scores,
return_dict_in_generate=return_dict_in_generate,
)
torch.set_grad_enabled(True)
if with_logprob:
resp_outputs = model_output.sequences.cpu().numpy().tolist()
resp_prob = torch.max(torch.stack(model_output.scores, dim=1).softmax(-1), dim=-1).values[0]
else:
resp_outputs = model_output.cpu().numpy().tolist()
resp_prob = None
system_act, system_resp, sys_act_prob, sys_resp_prob = self.split_system_act_and_resp(resp_outputs[0])
if with_logprob:
single_turn['sys_act_resp_prob'] = resp_prob
system_act = self.dialog_tokenizer.decode(system_act, clean_up_tokenization_spaces=False).split()
system_resp = self.dialog_tokenizer.decode(system_resp, clean_up_tokenization_spaces=False).split()
system_act_dict = convert_generate_action_span_to_dict(system_act[1:-1])
goal_state_dict = update_goal_states_during_gen(goal_state_dict, system_act_dict, 'sys')
single_turn['sys_act'] = ' '.join(system_act[1:-1])
single_turn['sys'] = ' '.join(system_resp[1:-1])
# update dialog history with ur format
dialog_history.append(user_utterance)
dialog_history.append(system_resp)
log.append(single_turn.copy())
single_turn = {}
user_utterance = None
turn_domain = None
else:
'''
user agent:
input: dialog history + goal state span;
output: user action + user utterance;
update user's goal state;
'''
utterance_count += 1
goal_state_span = convert_goal_dict_to_span(goal_state_dict)
goal_state_ids = self.encode_text(goal_state_span, self.simulator_tokenizer, bos_token=definitions.BOS_GOAL_TOEKN, eos_token=definitions.EOS_GOAL_TOKEN)
encoded_dialog_history = [self.encode_text(text, self.simulator_tokenizer) for text in dialog_history]
context = self.flatten_dial_history(encoded_dialog_history, len(goal_state_ids), self.simulator_tokenizer.model_max_length)
input_ids = self.tensorize([context + goal_state_ids + [self.simulator_tokenizer.eos_token_id]])
input_ids = input_ids.to(device)
generate_with_graph = self.simulator_model.generate.__wrapped__
torch.set_grad_enabled(if_usr_need_grad)
model_output = generate_with_graph(
self.simulator_model,
input_ids=input_ids,
eos_token_id=self.simulator_tokenizer.eos_token_id,
# max_length=200,
max_length=100,
output_scores=output_scores,
return_dict_in_generate=return_dict_in_generate,
)
torch.set_grad_enabled(True)
if with_logprob:
user_utterance_output = model_output.sequences.cpu().numpy().tolist()
user_utterance_prob = torch.max(torch.stack(model_output.scores, dim=1).softmax(-1), dim=-1).values[0]
else:
user_utterance_output = model_output.cpu().numpy().tolist()
user_utterance_prob = None
user_act, user_utterance, user_act_prob, _ = split_user_act_and_resp(self.simulator_tokenizer, user_utterance_output[0])
if with_logprob:
single_turn['user_act_resp_prob'] = user_utterance_prob
user_act = self.simulator_tokenizer.decode(user_act, clean_up_tokenization_spaces=False).split(' ')
user_utterance = self.simulator_tokenizer.decode(user_utterance, clean_up_tokenization_spaces=False).split(' ')
if len(user_act[1:-1]) == 0 or user_act[1][1:-1] == 'general':
turn_domain = ['[general]']
elif user_act[1][1:-1] not in definitions.ALL_DOMAINS:
# raise Exception('Invalid domain token')
turn_domain = ['[general]']
else:
turn_domain = [user_act[1]]
# only add user utterance to history
single_turn['user'] = ' '.join(user_utterance[1:-1])
single_turn['user_act'] = ' '.join(user_act[1:-1])
# update goal state
user_act_dict = convert_generate_action_span_to_dict(user_act[1:-1])
goal_state_dict = update_goal_states_during_gen(goal_state_dict, user_act_dict, 'user')
dial_gen['log'] = log
dial_gen['final_goal_state'] = convert_goal_dict_to_span(goal_state_dict)
return dial_gen
def generate_single_dialog_pptod(self, user_goal):
self.simulator_model.to(device)
self.dialog_model.to(device)
# clear fail info and invalid/prev_invalid field
for domain in user_goal['goal']:
if 'fail_info' in user_goal['goal'][domain]:
del user_goal['goal'][domain]['fail_info']
if 'fail_book' in user_goal['goal'][domain]:
del user_goal['goal'][domain]['fail_book']
if 'book' in user_goal['goal'][domain]:
if 'invalid' in user_goal['goal'][domain]['book']:
del user_goal['goal'][domain]['book']['invalid']
if 'pre_invalid' in user_goal['goal'][domain]['book']:
del user_goal['goal'][domain]['book']['pre_invalid']
dial_gen = {user_goal['dialog_id']: {'goal': user_goal['goal']}}
log = []
dialog_history = []
goal_state_dict = user_goal['goal']
goal_state_span = convert_goal_dict_to_span(user_goal['goal'])
user_utterance = None
turn_domain = None
system_act = None
user_act = None
utterance_count = 0
single_turn = {}
def is_continue(dial_gen):
if 'sys' not in single_turn and 'user' in single_turn:
# end up with system resp
return True
if len(goal_state_dict) == 0:
# goal清空后终止
dial_gen['terminate_reason'] = 'goal清空后终止'
return False
if len(log) >= self.cfg.max_turn_num:
# 超过固定轮数终止
dial_gen['terminate_reason'] = '超过{}轮终止'.format(self.cfg.max_turn_num)
return False
if system_act and ('[bye]' in system_act or '[thank]' in system_act):
dial_gen['terminate_reason'] = 'system said thank or bye'
return False
if user_act and ('[bye]' in user_act or '[thank]' in user_act):
dial_gen['terminate_reason'] = 'user said thank or bye'
return False
# 不满足退出条件则继续循环
return True
while is_continue(dial_gen): # 需要判断一个会话是否结束,满足结束条件则需要退出循环
if utterance_count & 1:
'''
system agent:
input1: bs_prefix + context
output1: belief states;
input2: da_prefix + context + db_result
output2: system action
update user's goal state;
input3: nlg_prefix + context + db_result
output3: system response
'''
utterance_count += 1
if user_utterance is None:
raise Exception('Should generate user utterance first!')
# replace special tokens
user_utterance_ids = self.encode_text(user_utterance, self.dialog_tokenizer, special_tokens_map=mttod_to_pptod)
encoded_dialog_history = [self.encode_text(text, self.dialog_tokenizer, special_tokens_map=mttod_to_pptod) for text in dialog_history]
context = self.flatten_dial_history(encoded_dialog_history, len(user_utterance_ids) + len(self.bs_prefix_id) + 1, self.dialog_tokenizer.model_max_length)
input_ids = self.tensorize([self.bs_prefix_id + [self.sos_context_token_id] + context + user_utterance_ids + [self.eos_context_token_id]])
input_ids = input_ids.to(device)
with torch.no_grad():
model_output = self.dialog_model.generate(
input_ids=input_ids,
eos_token_id=self.dialog_tokenizer.eos_token_id,
max_length=100,
)
belief_states_output = model_output.cpu().numpy().tolist()
bspn_gen, _ = self.finalize_bspn(belief_states_output[0])
bspn_gen = self.dialog_tokenizer.decode(bspn_gen, clean_up_tokenization_spaces=False)
single_turn['belief_states'] = bspn_gen
if turn_domain is None:
raise Exception('Domain is empty')
db_token = self.bspn_to_db_pointer(bspn_gen, turn_domain)
dbpn_gen = self.encode_text(db_token, self.dialog_tokenizer, bos_token='<sos_d>', eos_token='<eos_d>')
single_turn['dbpn'] = self.dialog_tokenizer.decode(dbpn_gen)
#action generation
context_for_action = self.flatten_dial_history(encoded_dialog_history, len(user_utterance_ids) + len(self.da_prefix_id) + len(dbpn_gen) + 1, self.dialog_tokenizer.model_max_length)
input_ids_da = self.tensorize([self.da_prefix_id + [self.sos_context_token_id] + context_for_action + user_utterance_ids + [self.eos_context_token_id] + dbpn_gen])
input_ids_da = input_ids_da.to(device)
with torch.no_grad():
model_output = self.dialog_model.generate(
input_ids=input_ids_da,
eos_token_id=self.dialog_tokenizer.eos_token_id,
max_length=100,
)
aspn_outputs = model_output.cpu().numpy().tolist()
aspn_gen, _ = self.finalize_aspn(aspn_outputs[0])
aspn_gen = self.dialog_tokenizer.decode(aspn_gen, clean_up_tokenization_spaces=False).split()
system_act_dict = convert_generate_action_span_to_dict(aspn_gen[1:-1])
goal_state_dict = update_goal_states_during_gen(goal_state_dict, system_act_dict, 'sys')
single_turn['sys_act'] = ' '.join(aspn_gen[1:-1])
#response generation
context_for_resp = self.flatten_dial_history(encoded_dialog_history, len(user_utterance_ids) + len(self.nlg_prefix_id) + len(dbpn_gen) + 1, self.dialog_tokenizer.model_max_length)
input_ids_resp = self.tensorize([self.nlg_prefix_id + [self.sos_context_token_id] + context_for_resp + user_utterance_ids + [self.eos_context_token_id] + dbpn_gen])
input_ids_resp = input_ids_resp.to(device)
with torch.no_grad():
model_output = self.dialog_model.generate(
input_ids=input_ids_resp,
eos_token_id=self.dialog_tokenizer.eos_token_id,
max_length=200,
)
resp_outputs = model_output.cpu().numpy().tolist()
resp_gen, _ = self.finalize_resp(resp_outputs[0])
resp_gen = self.dialog_tokenizer.decode(resp_gen, clean_up_tokenization_spaces=False).split()
single_turn['sys'] = ' '.join(resp_gen[1:-1])
log.append(single_turn.copy())
single_turn = {}
# update dialog history
dialog_history.append(user_utterance)
dialog_history.append(resp_gen)
user_utterance = None
turn_domain = None
else:
'''
user agent:
input: dialog history + goal state span;
output: user action + user utterance;
update user's goal state;
'''
utterance_count += 1
goal_state_span = convert_goal_dict_to_span(goal_state_dict)
goal_state_ids = self.encode_text(goal_state_span, self.simulator_tokenizer, bos_token=definitions.BOS_GOAL_TOEKN, eos_token=definitions.EOS_GOAL_TOKEN)
encoded_dialog_history = [self.encode_text(text, self.simulator_tokenizer, special_tokens_map=pptod_to_mttod) for text in dialog_history]
context = self.flatten_dial_history(encoded_dialog_history, len(goal_state_ids), self.simulator_tokenizer.model_max_length)
input_ids = self.tensorize([context + goal_state_ids + [self.simulator_tokenizer.eos_token_id]])
input_ids = input_ids.to(device)
with torch.no_grad():
model_output = self.simulator_model.generate(
input_ids=input_ids,
eos_token_id=self.simulator_tokenizer.eos_token_id,
max_length=100,
)
user_utterance_output = model_output.cpu().numpy().tolist()
user_act, user_utterance, _, _ = split_user_act_and_resp(self.simulator_tokenizer, user_utterance_output[0])
user_act = self.simulator_tokenizer.decode(user_act, clean_up_tokenization_spaces=False).split(' ')
user_utterance = self.simulator_tokenizer.decode(user_utterance, clean_up_tokenization_spaces=False).split(' ')
if len(user_act[1:-1]) == 0 or user_act[1][1:-1] == 'general':
turn_domain = ['[general]']
elif user_act[1][1:-1] not in definitions.ALL_DOMAINS:
# raise Exception('Invalid domain token')
turn_domain = ['[general]']
else:
turn_domain = [user_act[1]]
# only add user utterance to history
single_turn['user'] = ' '.join(user_utterance[1:-1])
single_turn['user_act'] = ' '.join(user_act[1:-1])
# update goal state
user_act_dict = convert_generate_action_span_to_dict(user_act[1:-1])
goal_state_dict = update_goal_states_during_gen(goal_state_dict, user_act_dict, 'user')
dial_gen['log'] = log
dial_gen['final_goal_state'] = convert_goal_dict_to_span(goal_state_dict)
return dial_gen
def generate_single_dialog_ubar(self, user_goal):
self.simulator_model.to(device)
self.dialog_model.to(device)
# clear fail info and invalid/prev_invalid field
for domain in user_goal['goal']:
if 'fail_info' in user_goal['goal'][domain]:
del user_goal['goal'][domain]['fail_info']
if 'fail_book' in user_goal['goal'][domain]:
del user_goal['goal'][domain]['fail_book']
if 'book' in user_goal['goal'][domain]:
if 'invalid' in user_goal['goal'][domain]['book']:
del user_goal['goal'][domain]['book']['invalid']
if 'pre_invalid' in user_goal['goal'][domain]['book']:
del user_goal['goal'][domain]['book']['pre_invalid']
dial_gen = {user_goal['dialog_id']: {'goal': user_goal['goal']}}
log = []
dialog_history = []
dialog_history_for_us = []
goal_state_dict = user_goal['goal']
goal_state_span = convert_goal_dict_to_span(user_goal['goal'])
user_utterance = None
turn_domain = None
system_act = None
user_act = None
utterance_count = 0
single_turn = {}
def is_continue(dial_gen):
if 'sys' not in single_turn and 'user' in single_turn:
# end up with system resp
return True
if len(goal_state_dict) == 0:
# goal清空后终止
dial_gen['terminate_reason'] = 'goal清空后终止'
return False
if len(log) >= self.cfg.max_turn_num:
# 超过固定轮数终止
dial_gen['terminate_reason'] = '超过{}轮终止'.format(self.cfg.max_turn_num)
return False
if system_act and ('[bye]' in system_act or '[thank]' in system_act):
dial_gen['terminate_reason'] = 'system said thank or bye'
return False
if user_act and ('[bye]' in user_act or '[thank]' in user_act):
dial_gen['terminate_reason'] = 'user said thank or bye'
return False
# 不满足退出条件则继续循环
return True
while is_continue(dial_gen): # 需要判断一个会话是否结束,满足结束条件则需要退出循环
if utterance_count & 1:
'''
system agent:
input1: context
output1: belief states;
input2: context + bs + db_result
output2: system action
update user's goal state;
input3: context + bs + db_result + act
output3: system response
'''
utterance_count += 1
if user_utterance is None:
raise Exception('Should generate user utterance first!')
# replace special tokens
user_utterance_ids = self.encode_text(user_utterance, self.dialog_tokenizer, special_tokens_map=mttod_to_pptod)
encoded_dialog_history = [self.encode_text(text, self.dialog_tokenizer, special_tokens_map=mttod_to_pptod) for text in dialog_history]
context_for_bs = self.flatten_dial_history(encoded_dialog_history, len(user_utterance_ids) - 1 + 60, self.dialog_tokenizer.model_max_length)
input_ids = self.tensorize([context_for_bs + user_utterance_ids])
input_ids = input_ids.to(device)
with torch.no_grad():
model_output = self.dialog_model.generate(
input_ids=input_ids,
pad_token_id=self.dialog_tokenizer.eos_token_id,
eos_token_id=self.dialog_tokenizer.encode(['<eos_b>'])[0],
max_length= input_ids.shape[1] + 60,
temperature=0.7,
)
belief_states_output = model_output[:, input_ids.shape[1]:]
belief_states_output = belief_states_output.cpu().numpy().tolist()
bspn_gen, _ = self.finalize_bspn(belief_states_output[0])
bspn_decoded = self.dialog_tokenizer.decode(bspn_gen, clean_up_tokenization_spaces=False)
single_turn['belief_states'] = bspn_decoded
if turn_domain is None:
raise Exception('Domain is empty')
db_token = self.bspn_to_db_pointer(bspn_decoded, turn_domain)
dbpn_gen = self.encode_text(db_token, self.dialog_tokenizer, bos_token='<sos_d>', eos_token='<eos_d>')
dbpn_decoded = self.dialog_tokenizer.decode(dbpn_gen)
single_turn['dbpn'] = dbpn_decoded
#action generation
context_for_da = self.flatten_dial_history(encoded_dialog_history, len(user_utterance_ids) + len(bspn_gen) + len(dbpn_gen) - 1 + 60, self.dialog_tokenizer.model_max_length)
input_ids_da = self.tensorize([context_for_da + user_utterance_ids + bspn_gen + dbpn_gen])
input_ids_da = input_ids_da.to(device)
with torch.no_grad():
model_output = self.dialog_model.generate(
input_ids=input_ids_da,
pad_token_id=self.dialog_tokenizer.eos_token_id,
eos_token_id=self.dialog_tokenizer.encode(['<eos_a>'])[0],
max_length= input_ids_da.shape[1] + 60,
temperature=0.7,
)
aspn_outputs = model_output[:, input_ids_da.shape[1]:]
aspn_outputs = aspn_outputs.cpu().numpy().tolist()
aspn_gen, _ = self.finalize_aspn(aspn_outputs[0])
aspn_decoded = self.dialog_tokenizer.decode(aspn_gen, clean_up_tokenization_spaces=False).split()
system_act_dict = convert_generate_action_span_to_dict(aspn_decoded[1:-1])
goal_state_dict = update_goal_states_during_gen(goal_state_dict, system_act_dict, 'sys')
single_turn['sys_act'] = ' '.join(aspn_decoded[1:-1])
#response generation
context_for_resp = self.flatten_dial_history(encoded_dialog_history, len(user_utterance_ids) + len(bspn_gen) + len(dbpn_gen) + len(aspn_gen) - 1 + 200, self.dialog_tokenizer.model_max_length)
input_ids_resp = self.tensorize([context_for_resp + user_utterance_ids + bspn_gen + dbpn_gen + aspn_gen])
input_ids_resp = input_ids_resp.to(device)
with torch.no_grad():
model_output = self.dialog_model.generate(
input_ids=input_ids_resp,
pad_token_id=self.dialog_tokenizer.eos_token_id,
eos_token_id=self.dialog_tokenizer.encode(['<eos_r>'])[0],
max_length= input_ids_resp.shape[1] + 200,
temperature=0.7,
)
resp_outputs = model_output[:, input_ids_resp.shape[1]:]
resp_outputs = resp_outputs.cpu().numpy().tolist()
resp_gen, _ = self.finalize_resp(resp_outputs[0])
resp_decoded = self.dialog_tokenizer.decode(resp_gen, clean_up_tokenization_spaces=False).split()
single_turn['sys'] = ' '.join(resp_decoded[1:-1])
log.append(single_turn.copy())
single_turn = {}
prev_text = user_utterance + bspn_decoded.split() + dbpn_decoded.split() + aspn_decoded + resp_decoded
dialog_history.append(prev_text)
dialog_history_for_us.append(user_utterance)
dialog_history_for_us.append(resp_decoded)
user_utterance = None
turn_domain = None
else:
'''
user agent:
input: dialog history + goal state span;
output: user action + user utterance;
update user's goal state;
'''
utterance_count += 1
goal_state_span = convert_goal_dict_to_span(goal_state_dict)
goal_state_ids = self.encode_text(goal_state_span, self.simulator_tokenizer, bos_token=definitions.BOS_GOAL_TOEKN, eos_token=definitions.EOS_GOAL_TOKEN)
encoded_dialog_history = [self.encode_text(text, self.simulator_tokenizer, special_tokens_map=pptod_to_mttod) for text in dialog_history_for_us]
context = self.flatten_dial_history(encoded_dialog_history, len(goal_state_ids), self.simulator_tokenizer.model_max_length)
input_ids = self.tensorize([context + goal_state_ids + [self.simulator_tokenizer.eos_token_id]])
input_ids = input_ids.to(device)
with torch.no_grad():
model_output = self.simulator_model.generate(
input_ids=input_ids,
eos_token_id=self.simulator_tokenizer.eos_token_id,
max_length=100,