-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevaluation.py
1419 lines (1186 loc) · 69.7 KB
/
evaluation.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 json
import data_preprocessing
import models
import numpy as np
import torch
import random
import datetime
import argparse
import socket
from similarity.damerau import Damerau # pip install strsim
import utils
from fast_transformers.masking import TriangularCausalMask
from copy import deepcopy
def iterate_over_generated_suffixes(predictions=None):
damerau = Damerau()
nb_worst_situs = 0
nb_all_situs = 0
average_damerau_levenshtein_similarity = 0
average_mae = 0.0
average_mae_denormalised = 0.0
eos_token = predictions['eos_token']
predictions['dls'] = {}
predictions['mae'] = {}
predictions['mae_denormalised'] = {}
predictions['evaluated_ids'] = {}
for prefix in predictions['ids'].keys():
predictions['dls'][prefix] = []
predictions['mae'][prefix] = []
predictions['mae_denormalised'][prefix] = []
predictions['evaluated_ids'][prefix] = []
for i in range(len(predictions['activities']['suffixes']['target'][prefix])):
target_activity_suffix_padded = predictions['activities']['suffixes']['target'][prefix][i]
target_activity_suffix = []
target_time_suffix_padded = predictions['times']['suffixes']['target'][prefix][i]
target_time_suffix = []
target_time_denormalised_suffix_padded = predictions['times_denormalised']['suffixes']['target'][prefix][i]
target_time_denormalised_suffix = []
# The situ when the original trace was shorter than the given prefix is:
# prepared for an expanded dimensionality too:
if (len(target_activity_suffix_padded) > 0) and isinstance(target_activity_suffix_padded[0], list):
if target_activity_suffix_padded[0][0] == predictions['pad_token']:
continue
else:
if target_activity_suffix_padded[0] == predictions['pad_token']:
continue
# prepared for an expanded dimensionality too:
# for the activities:
target_length = 0
if (len(target_activity_suffix_padded) > 0) and isinstance(target_activity_suffix_padded[0], list):
for j in target_activity_suffix_padded:
if j[0] != eos_token:
target_activity_suffix.append(j[0])
target_length += 1
else:
break
else:
for j in target_activity_suffix_padded:
if j != eos_token:
target_activity_suffix.append(j)
target_length += 1
else:
break
# for the times:
if (len(target_time_suffix_padded) > 0) and isinstance(target_time_suffix_padded[0], list):
for j in range(target_length):
target_time_suffix.append(target_time_suffix_padded[j][0])
target_time_denormalised_suffix.append(target_time_denormalised_suffix_padded[j][0])
else:
for j in range(target_length):
target_time_suffix.append(target_time_suffix_padded[j])
target_time_denormalised_suffix.append(target_time_denormalised_suffix_padded[j])
is_the_worst_situ = True
prediction_activity_suffix_padded = predictions['activities']['suffixes']['prediction'][prefix][i]
prediction_activity_suffix = []
prediction_time_suffix_padded = predictions['times']['suffixes']['prediction'][prefix][i]
prediction_time_suffix = []
prediction_time_denormalised_suffix_padded = predictions['times_denormalised']['suffixes']['prediction'][prefix][i]
prediction_time_denormalised_suffix = []
# In the worst case it stops at the length of the longest suffix
# prepared for an expanded dimensionality too:
# for the activities:
prediction_length = 0
if (len(prediction_activity_suffix_padded) > 0) and isinstance(prediction_activity_suffix_padded[0], list):
for j in prediction_activity_suffix_padded:
if j[0] != eos_token:
prediction_activity_suffix.append(j[0])
prediction_length += 1
else:
is_the_worst_situ = False
break
else:
for j in prediction_activity_suffix_padded:
if j != eos_token:
prediction_activity_suffix.append(j)
prediction_length += 1
else:
is_the_worst_situ = False
break
# for the times:
if (len(prediction_time_suffix_padded) > 0) and isinstance(prediction_time_suffix_padded[0], list):
for j in range(prediction_length):
prediction_time_suffix.append(prediction_time_suffix_padded[j][0])
prediction_time_denormalised_suffix.append(prediction_time_denormalised_suffix_padded[j][0])
else:
for j in range(prediction_length):
prediction_time_suffix.append(prediction_time_suffix_padded[j])
prediction_time_denormalised_suffix.append(prediction_time_denormalised_suffix_padded[j])
if is_the_worst_situ:
nb_worst_situs += 1
# The situ when the suffix had an [EOS] position only and that is perfectly predicted:
if len(prediction_activity_suffix) == len(target_activity_suffix) == 0:
damerau_levenshtein_similarity = 1.0
mae = 0.0
mae_denormalised = 0.0
else:
damerau_levenshtein_similarity = 1.0 - damerau.distance(prediction_activity_suffix, target_activity_suffix) / max(len(prediction_activity_suffix), len(target_activity_suffix))
if len(target_time_suffix) == 0:
sum_target_time_suffix = 0.0
elif len(target_time_suffix) == 1:
sum_target_time_suffix = target_time_suffix[0]
elif len(target_time_suffix) > 1:
sum_target_time_suffix = sum(target_time_suffix)
if len(prediction_time_suffix) == 0:
sum_prediction_time_suffix = 0.0
elif len(prediction_time_suffix) == 1:
sum_prediction_time_suffix = prediction_time_suffix[0]
elif len(prediction_time_suffix) > 1:
sum_prediction_time_suffix = sum(prediction_time_suffix)
if len(target_time_denormalised_suffix) == 0:
sum_target_time_denormalised_suffix = 0.0
elif len(target_time_denormalised_suffix) == 1:
sum_target_time_denormalised_suffix = target_time_denormalised_suffix[0]
elif len(target_time_denormalised_suffix) > 1:
sum_target_time_denormalised_suffix = sum(target_time_denormalised_suffix)
if len(prediction_time_denormalised_suffix) == 0:
sum_prediction_time_denormalised_suffix = 0.0
elif len(prediction_time_denormalised_suffix) == 1:
sum_prediction_time_denormalised_suffix = prediction_time_denormalised_suffix[0]
elif len(prediction_time_denormalised_suffix) > 1:
sum_prediction_time_denormalised_suffix = sum(prediction_time_denormalised_suffix)
mae = abs(sum_target_time_suffix - sum_prediction_time_suffix)
mae_denormalised = abs(sum_target_time_denormalised_suffix - sum_prediction_time_denormalised_suffix)
trace_id = predictions['ids'][prefix][i]
average_damerau_levenshtein_similarity += damerau_levenshtein_similarity
average_mae += mae
average_mae_denormalised += mae_denormalised
predictions['dls'][prefix].append(damerau_levenshtein_similarity) # in-place editing of the input dictionary
predictions['mae'][prefix].append(mae) # in-place editing of the input dictionary
predictions['mae_denormalised'][prefix].append(mae_denormalised) # in-place editing of the input dictionary
predictions['evaluated_ids'][prefix].append(trace_id) # in-place editing of the input dictionary
nb_all_situs += 1
# the list (of the prefix) is created in the beggining hence if it remains empty it is deleted now:
prefix_to_delete = []
for prefix in predictions['dls'].keys():
if len(predictions['dls'][prefix]) == 0:
prefix_to_delete.append(prefix)
for prefix in prefix_to_delete:
del predictions['dls'][prefix]
del predictions['mae'][prefix]
del predictions['mae_denormalised'][prefix]
del predictions['evaluated_ids'][prefix]
average_damerau_levenshtein_similarity /= nb_all_situs
average_mae /= nb_all_situs
average_mae_denormalised /= nb_all_situs
return average_damerau_levenshtein_similarity, average_mae, average_mae_denormalised, nb_worst_situs, nb_all_situs
def seq_ae_predict(seq_ae_teacher_forcing_ratio, model, model_input_x, model_input_y, temperature=1.0, top_k=None, sample=False):
prediction = ()
# TODO prepare it for activity labels only
# Semi open loop:
encoder_hidden = model.encoder(model_input_x)[1]
decoder_hidden = encoder_hidden
input_sos = (model_input_y[0][:, 0, :].unsqueeze(-1), model_input_y[1][:, 0, :].unsqueeze(-1))
input_position = input_sos
for i in range(model_input_y[0].size(1)):
inter_position, decoder_hidden = model.decoder.cell(model.decoder.value_embedding(input_position), decoder_hidden)
output_position = model.decoder.readout(inter_position)
if i == 0:
a_decoded = utils.generate(output_position[0], temperature=temperature, top_k=top_k, sample=sample)
prediction = (a_decoded, output_position[1])
elif i > 0:
a_decoded = utils.generate(output_position[0], temperature=temperature, top_k=top_k, sample=sample)
a_pred = torch.cat((prediction[0], a_decoded), dim=1)
t_pred = torch.cat((prediction[1], output_position[1]), dim=1)
prediction = (a_pred, t_pred)
a_inp = a_decoded
t_inp = output_position[1]
input_position = (a_inp, t_inp)
return prediction
def transformer_full_predict(seq_ae_teacher_forcing_ratio, model, model_input_x, model_input_y, temperature=1.0, top_k=None, sample=False):
# TODO prepare it for activity labels only
# Semi open loop:
model_input_x = model.value_embedding(model_input_x)
model_input_x = model.position_embedding(model_input_x)
memory = model.self_attentional_block.encoder(model_input_x)
input_sos = (model_input_y[0][:, 0, :].unsqueeze(-1), model_input_y[1][:, 0, :].unsqueeze(-1))
input_positions = input_sos
for i in range(model_input_y[0].size(1)):
input_positions_embedded = model.value_embedding(input_positions)
input_positions_embedded = model.position_embedding(input_positions_embedded)
inter_positions = model.self_attentional_block.decoder(input_positions_embedded, memory, tgt_mask=model.target_lookahead_mask[:input_positions[0].size(1), :input_positions[0].size(1)])
output_positions = model.readout(inter_positions)
a_decoded = utils.generate(output_positions[0][:, -1, :].unsqueeze(1), temperature=temperature, top_k=top_k, sample=sample)
a_pred = torch.cat((input_positions[0], a_decoded), dim=1)
t_pred = torch.cat((input_positions[1], output_positions[1][:, -1, :].unsqueeze(1)), dim=1)
input_positions = (a_pred, t_pred)
prediction = (input_positions[0][:, 1:, :], input_positions[1][:, 1:, :]) # Cut the starting [SOS] position
return prediction
def rnn_predict(seq_ae_teacher_forcing_ratio, model, model_input_x, model_input_y, temperature=1.0, top_k=None, sample=False, max_length=None):
# TODO prepare it for activity labels only
# init model wiht prefix input:
prefix = model_input_x[0].size(1)
inp_p = (model_input_x[0], model_input_x[1])
output = model(inp_p)
a_decoded = utils.generate(output[0][:, -1, :].unsqueeze(1), temperature=temperature, top_k=top_k, sample=sample)
prediction = (a_decoded, output[1][:, -1, :].unsqueeze(1))
input_position = prediction
# Semi open loop:
for i in range(prefix, max_length - 1):
output_position = model(input_position)
a_decoded = utils.generate(output_position[0], temperature=temperature, top_k=top_k, sample=sample)
a_pred = torch.cat((prediction[0], a_decoded), dim=1)
t_pred = torch.cat((prediction[1], output_position[1]), dim=1)
prediction = (a_pred, t_pred)
a_inp = a_decoded
t_inp = output_position[1]
input_position = (a_inp, t_inp)
return prediction
def gpt_predict(model, inp, target, ids, temperature=1.0, top_k=None, sample=False, min_prefix=2):
gpt_min_prefix = min_prefix + 1 # For fair comparison with other model architectures due to the [SOS] at first position
batch_of_traces = {'activities': {'prefixes': {}, 'suffixes': {'target': {}, 'prediction': {}}},
'times': {'prefixes': {}, 'suffixes': {'target': {}, 'prediction': {}}},
'ids': {}}
for prefix in range(gpt_min_prefix, inp[0].size(1) + 1): # Plus one: we want the very last [EOS] predictions too
# TODO prepare it for activity labels only
# Initial input condition:
input_condition = (inp[0][:, :prefix, :], inp[1][:, :prefix, :])
# Open-loop inference:
for i in range(inp[0].size(1) + 1 - prefix): # very important -> the complete output is: [SOS] trace [EOS]
causal_mask = TriangularCausalMask(input_condition[0].size(1), device=next(model.parameters()).device)
output = model(input_condition, attn_mask=causal_mask)
a_decoded = utils.generate(output[0][:, -1, :].unsqueeze(1), temperature=temperature, top_k=top_k, sample=sample)
a_pred = torch.cat((input_condition[0], a_decoded), dim=1)
t_pred = torch.cat((input_condition[1], output[1][:, -1, :].unsqueeze(1)), dim=1)
input_condition = (a_pred, t_pred)
del causal_mask
del output
prediction = (input_condition[0][:, 1:, :], input_condition[1][:, 1:, :]) # Cut the starting [SOS] position
real_prefix = prefix - 1 # without the [SOS] position
batch_of_traces['activities']['prefixes'][real_prefix] = prediction[0][:, :real_prefix, :].tolist()
batch_of_traces['times']['prefixes'][real_prefix] = prediction[1][:, :real_prefix, :].tolist()
batch_of_traces['activities']['suffixes']['prediction'][real_prefix] = prediction[0][:, real_prefix:, :].tolist()
batch_of_traces['times']['suffixes']['prediction'][real_prefix] = prediction[1][:, real_prefix:, :].tolist()
batch_of_traces['activities']['suffixes']['target'][real_prefix] = target[0][:, real_prefix:].tolist()
batch_of_traces['times']['suffixes']['target'][real_prefix] = target[1][:, real_prefix:, :].tolist()
# real ids:
batch_of_traces['ids'][real_prefix] = ids
del input_condition
del prediction
return batch_of_traces
def wavenet_predict(model, inp, target, ids, temperature=1.0, top_k=None, sample=False, min_prefix=2):
gpt_min_prefix = min_prefix + 1 # For fair comparison with other model architectures due to the [SOS] at first position
batch_of_traces = {'activities': {'prefixes': {}, 'suffixes': {'target': {}, 'prediction': {}}},
'times': {'prefixes': {}, 'suffixes': {'target': {}, 'prediction': {}}},
'ids': {}}
receptive_field = model.left_padding + 1
for prefix in range(gpt_min_prefix, inp[0].size(1) + 1): # Plus one: we want the very last [EOS] predictions too
# TODO prepare it for activity labels only
# Initial input condition:
input_condition = (inp[0][:, :prefix, :], inp[1][:, :prefix, :])
# Open-loop inference:
for i in range(inp[0].size(1) + 1 - prefix): # very important -> the complete output is: [SOS] trace [EOS]
if input_condition[0].size(1) < receptive_field:
left_padding = receptive_field - input_condition[0].size(1)
else:
left_padding = 0
output = model((input_condition[0][:, -receptive_field:, :], input_condition[1][:, -receptive_field:, :]), left_padding=left_padding)
a_decoded = utils.generate(output[0][:, -1, :].unsqueeze(1), temperature=temperature, top_k=top_k, sample=sample)
a_pred = torch.cat((input_condition[0], a_decoded), dim=1)
t_pred = torch.cat((input_condition[1], output[1][:, -1, :].unsqueeze(1)), dim=1)
input_condition = (a_pred, t_pred)
del output
prediction = (input_condition[0][:, 1:, :], input_condition[1][:, 1:, :]) # Cut the starting [SOS] position
real_prefix = prefix - 1 # without the [SOS] position
batch_of_traces['activities']['prefixes'][real_prefix] = prediction[0][:, :real_prefix, :].tolist()
batch_of_traces['times']['prefixes'][real_prefix] = prediction[1][:, :real_prefix, :].tolist()
batch_of_traces['activities']['suffixes']['prediction'][real_prefix] = prediction[0][:, real_prefix:, :].tolist()
batch_of_traces['times']['suffixes']['prediction'][real_prefix] = prediction[1][:, real_prefix:, :].tolist()
batch_of_traces['activities']['suffixes']['target'][real_prefix] = target[0][:, real_prefix:].tolist()
batch_of_traces['times']['suffixes']['target'][real_prefix] = target[1][:, real_prefix:, :].tolist()
# real ids:
batch_of_traces['ids'][real_prefix] = deepcopy(ids)
del prediction
del input_condition
return batch_of_traces
def bert_predict(model, inp, target, ids, temperature=1.0, top_k=None, sample=False, min_prefix=2, order='random'):
bert_min_prefix = min_prefix
batch_of_traces = {'activities': {'prefixes': {}, 'suffixes': {'target': {}, 'prediction': {}}},
'times': {'prefixes': {}, 'suffixes': {'target': {}, 'prediction': {}}},
'ids': {}}
for prefix in range(bert_min_prefix, inp[0].size(1)): # TODO validation of upper limit
# TODO prepare it for activity labels only
if order == 'random' or order == 'l2r':
if order == 'random':
suffix_indexes = torch.randperm(n=inp[0].size(1) - prefix, device=inp[0].device, dtype=torch.long)
suffix_indexes = torch.add(suffix_indexes, prefix)
elif order == 'l2r':
suffix_indexes = torch.arange(start=prefix, end=inp[0].size(1), device=inp[0].device, dtype=torch.long)
a_input_condition = inp[0].detach().clone()
t_input_condition = inp[1].detach().clone()
# fully mask the suffix as step 0:
a_input_condition[:, suffix_indexes, :] = float(model.mask_token) * torch.ones(
(a_input_condition.size(0), suffix_indexes.size(0), a_input_condition.size(2)), device=a_input_condition.device)
t_input_condition[:, suffix_indexes, :] = float(model.attributes_meta[1]['min_value']) * torch.ones(
(t_input_condition.size(0), suffix_indexes.size(0), t_input_condition.size(2)), device=t_input_condition.device)
for suffix_index in suffix_indexes:
model.mlm.method = 'fix_masks'
model.mlm.fix_masks = suffix_index
output = model((a_input_condition, t_input_condition), attn_mask=None)
a_decoded = utils.generate(output[0][:, suffix_index, :], temperature=temperature, top_k=top_k, sample=sample)
a_input_condition[:, suffix_index, :] = a_decoded
t_input_condition[:, suffix_index, :] = output[1][:, suffix_index, :]
del suffix_indexes
prediction = (a_input_condition, t_input_condition)
real_prefix = prefix
batch_of_traces['activities']['prefixes'][real_prefix] = prediction[0][:, :real_prefix, :].tolist()
batch_of_traces['times']['prefixes'][real_prefix] = prediction[1][:, :real_prefix, :].tolist()
batch_of_traces['activities']['suffixes']['prediction'][real_prefix] = prediction[0][:, real_prefix:, :].tolist()
batch_of_traces['times']['suffixes']['prediction'][real_prefix] = prediction[1][:, real_prefix:, :].tolist()
batch_of_traces['activities']['suffixes']['target'][real_prefix] = target[0][:, real_prefix:].tolist()
batch_of_traces['times']['suffixes']['target'][real_prefix] = target[1][:, real_prefix:, :].tolist()
# real ids:
batch_of_traces['ids'][real_prefix] = ids
del a_input_condition
del t_input_condition
del prediction
return batch_of_traces
# loop for transformer models:
def iterate_over_traces_transformer(log_with_traces,
model=None,
device=None,
subset=None):
# TODO prepare it for activity labels only
# TODO encode trace ids as integers then that could be tracked
predictions = {'activities': {'prefixes': {}, 'suffixes': {'target': {}, 'prediction': {}}},
'times': {'prefixes': {}, 'suffixes': {'target': {}, 'prediction': {}}},
'eos_token': log_with_traces['eos_token'],
'sos_token': log_with_traces['sos_token'],
'pad_token': log_with_traces['pad_token'],
'ids': {},
'max_time_value': log_with_traces['max_time_value'],
'min_time_value': log_with_traces['min_time_value']}
data_loader = log_with_traces[subset + '_torch_data_loaders']
i = 0
for mini_batch in iter(data_loader):
if device == 'GPU':
if model.architecture == 'GPT':
a_s_i = mini_batch[0].cuda()
t_s_i = mini_batch[1].cuda()
a_s_t = mini_batch[2]
t_s_t = mini_batch[3]
elif model.architecture == 'BERT':
a_s_t = mini_batch[2].cuda()
t_s_t = mini_batch[3].cuda()
else:
if model.architecture == 'GPT':
a_s_i = mini_batch[0]
t_s_i = mini_batch[1]
a_s_t = mini_batch[2]
t_s_t = mini_batch[3]
elif model.architecture == 'BERT':
a_s_t = mini_batch[2]
t_s_t = mini_batch[3]
if model.architecture == 'GPT':
prediction = gpt_predict(model=model,
inp=(a_s_i, t_s_i),
target=(a_s_t, t_s_t),
ids=log_with_traces[subset + '_augmented_traces']['ids'][i * mini_batch[0].size(0):(i+1) * mini_batch[0].size(0)])
elif model.architecture == 'BERT':
# The variable categorical target is an unsqueezed long so it has to be transformed into an unsqueezed float input:
prediction = bert_predict(model=model,
inp=(a_s_t.unsqueeze(2).float(), t_s_t),
target=(a_s_t.unsqueeze(2).float(), t_s_t),
ids=log_with_traces[subset + '_augmented_traces']['ids'][
i * mini_batch[0].size(0):(i + 1) * mini_batch[0].size(0)],
order=args.bert_order)
for prefix in prediction['activities']['prefixes'].keys():
if prefix not in predictions['activities']['prefixes'].keys():
predictions['activities']['prefixes'][prefix] = []
predictions['times']['prefixes'][prefix] = []
predictions['activities']['suffixes']['prediction'][prefix] = []
predictions['times']['suffixes']['prediction'][prefix] = []
predictions['activities']['suffixes']['target'][prefix] = []
predictions['times']['suffixes']['target'][prefix] = []
predictions['ids'][prefix] = []
predictions['activities']['prefixes'][prefix] += deepcopy(prediction['activities']['prefixes'][prefix])
predictions['times']['prefixes'][prefix] += deepcopy(prediction['times']['prefixes'][prefix])
predictions['activities']['suffixes']['prediction'][prefix] += deepcopy(prediction['activities']['suffixes']['prediction'][prefix])
predictions['times']['suffixes']['prediction'][prefix] += deepcopy(prediction['times']['suffixes']['prediction'][prefix])
predictions['activities']['suffixes']['target'][prefix] += deepcopy(prediction['activities']['suffixes']['target'][prefix])
predictions['times']['suffixes']['target'][prefix] += deepcopy(prediction['times']['suffixes']['target'][prefix])
predictions['ids'][prefix] += deepcopy(prediction['ids'][prefix])
del prediction
if model.architecture == 'GPT':
del a_s_i
del t_s_i
del a_s_t
del t_s_t
elif model.architecture == 'BERT':
del a_s_t
del t_s_t
del mini_batch
return predictions
def iterate_over_traces_wavenet(log_with_traces,
model=None,
device=None,
subset=None):
# TODO prepare it for activity labels only
# TODO encode trace ids as integers then that could be tracked
predictions = {'activities': {'prefixes': {}, 'suffixes': {'target': {}, 'prediction': {}}},
'times': {'prefixes': {}, 'suffixes': {'target': {}, 'prediction': {}}},
'eos_token': log_with_traces['eos_token'],
'sos_token': log_with_traces['sos_token'],
'pad_token': log_with_traces['pad_token'],
'ids': {},
'max_time_value': log_with_traces['max_time_value'],
'min_time_value': log_with_traces['min_time_value']}
data_loader = log_with_traces[subset + '_torch_data_loaders']
i = 0
for mini_batch in iter(data_loader):
if device == 'GPU':
if model.architecture == 'GPT':
a_s_i = mini_batch[0].cuda()
t_s_i = mini_batch[1].cuda()
a_s_t = mini_batch[2]
t_s_t = mini_batch[3]
elif model.architecture == 'BERT':
a_s_t = mini_batch[2].cuda()
t_s_t = mini_batch[3].cuda()
else:
if model.architecture == 'GPT':
a_s_i = mini_batch[0]
t_s_i = mini_batch[1]
a_s_t = mini_batch[2]
t_s_t = mini_batch[3]
elif model.architecture == 'BERT':
a_s_t = mini_batch[2]
t_s_t = mini_batch[3]
if model.architecture == 'GPT':
prediction = wavenet_predict(model=model,
inp=(a_s_i, t_s_i),
target=(a_s_t, t_s_t),
ids=log_with_traces[subset + '_augmented_traces']['ids'][i * mini_batch[0].size(0):(i+1) * mini_batch[0].size(0)])
for prefix in prediction['activities']['prefixes'].keys():
if prefix not in predictions['activities']['prefixes'].keys():
predictions['activities']['prefixes'][prefix] = []
predictions['times']['prefixes'][prefix] = []
predictions['activities']['suffixes']['prediction'][prefix] = []
predictions['times']['suffixes']['prediction'][prefix] = []
predictions['activities']['suffixes']['target'][prefix] = []
predictions['times']['suffixes']['target'][prefix] = []
predictions['ids'][prefix] = []
predictions['activities']['prefixes'][prefix] += deepcopy(prediction['activities']['prefixes'][prefix])
predictions['times']['prefixes'][prefix] += deepcopy(prediction['times']['prefixes'][prefix])
predictions['activities']['suffixes']['prediction'][prefix] += deepcopy(
prediction['activities']['suffixes']['prediction'][prefix])
predictions['times']['suffixes']['prediction'][prefix] += deepcopy(
prediction['times']['suffixes']['prediction'][prefix])
predictions['activities']['suffixes']['target'][prefix] += deepcopy(
prediction['activities']['suffixes']['target'][prefix])
predictions['times']['suffixes']['target'][prefix] += deepcopy(
prediction['times']['suffixes']['target'][prefix])
predictions['ids'][prefix] += deepcopy(prediction['ids'][prefix])
del prediction
if model.architecture == 'GPT':
del a_s_i
del t_s_i
del a_s_t
del t_s_t
elif model.architecture == 'BERT':
del a_s_t
del t_s_t
del mini_batch
return predictions
# loop for encoder-decoder models:
def iterate_over_prefixes_ae(log_with_prefixes,
model=None,
device=None,
subset=None,
to_wrap_into_torch_dataset=None):
# TODO prepare it for activity labels only
predictions = {'activities': {'prefixes': {}, 'suffixes': {'target': {}, 'prediction': {}}},
'times': {'prefixes': {}, 'suffixes': {'target': {}, 'prediction': {}}},
'ids': {},
'eos_token': log_with_prefixes['eos_token'],
'sos_token': log_with_prefixes['sos_token'],
'pad_token': log_with_prefixes['pad_token'],
'max_time_value': log_with_prefixes['max_time_value'],
'min_time_value': log_with_prefixes['min_time_value']}
if not to_wrap_into_torch_dataset:
# Not implemented
pass
else:
prefixes = list(log_with_prefixes[subset + '_torch_data_loaders'].keys())
for prefix in prefixes:
data_loader = log_with_prefixes[subset + '_torch_data_loaders'][prefix]
a_p_mini_batches = []
t_p_mini_batches = []
a_s_t_mini_batches = []
t_s_t_mini_batches = []
prediction_a_mini_batches = []
prediction_t_mini_batches = []
for mini_batch in iter(data_loader):
if device == 'GPU':
a_p = mini_batch[0].cuda()
t_p = mini_batch[1].cuda()
a_s_i = mini_batch[2].cuda()
t_s_i = mini_batch[3].cuda()
a_s_t = mini_batch[4]
t_s_t = mini_batch[5]
else:
a_p = mini_batch[0]
t_p = mini_batch[1]
a_s_i = mini_batch[2]
t_s_i = mini_batch[3]
a_s_t = mini_batch[4]
t_s_t = mini_batch[5]
prediction = seq_ae_predict(seq_ae_teacher_forcing_ratio=0.0,
model=model,
model_input_x=(a_p, t_p),
model_input_y=(a_s_i, t_s_i))
a_p_mini_batches += a_p.tolist()
t_p_mini_batches += t_p.tolist()
a_s_t_mini_batches += a_s_t.tolist()
t_s_t_mini_batches += t_s_t.tolist()
prediction_a_mini_batches += prediction[0].tolist()
prediction_t_mini_batches += prediction[1].tolist()
del a_p
del t_p
del a_s_i
del t_s_i
del a_s_t
del t_s_t
del mini_batch
del prediction
del data_loader
predictions['activities']['prefixes'][prefix] = a_p_mini_batches
predictions['times']['prefixes'][prefix] = t_p_mini_batches
predictions['activities']['suffixes']['target'][prefix] = a_s_t_mini_batches
predictions['times']['suffixes']['target'][prefix] = t_s_t_mini_batches
predictions['activities']['suffixes']['prediction'][prefix] = prediction_a_mini_batches
predictions['times']['suffixes']['prediction'][prefix] = prediction_t_mini_batches
predictions['ids'][prefix] = log_with_prefixes[subset + '_prefixes_and_suffixes']['ids'][prefix]
return predictions
# loop for transformer_full model:
def iterate_over_prefixes_transformer_full(log_with_prefixes,
model=None,
device=None,
subset=None,
to_wrap_into_torch_dataset=None):
# TODO prepare it for activity labels only
predictions = {'activities': {'prefixes': {}, 'suffixes': {'target': {}, 'prediction': {}}},
'times': {'prefixes': {}, 'suffixes': {'target': {}, 'prediction': {}}},
'ids': {},
'eos_token': log_with_prefixes['eos_token'],
'sos_token': log_with_prefixes['sos_token'],
'pad_token': log_with_prefixes['pad_token'],
'max_time_value': log_with_prefixes['max_time_value'],
'min_time_value': log_with_prefixes['min_time_value']}
if not to_wrap_into_torch_dataset:
# Not implemented
pass
else:
prefixes = list(log_with_prefixes[subset + '_torch_data_loaders'].keys())
for prefix in prefixes:
data_loader = log_with_prefixes[subset + '_torch_data_loaders'][prefix]
a_p_mini_batches = []
t_p_mini_batches = []
a_s_t_mini_batches = []
t_s_t_mini_batches = []
prediction_a_mini_batches = []
prediction_t_mini_batches = []
for mini_batch in iter(data_loader):
if device == 'GPU':
a_p = mini_batch[0].cuda()
t_p = mini_batch[1].cuda()
a_s_i = mini_batch[2].cuda()
t_s_i = mini_batch[3].cuda()
a_s_t = mini_batch[4]
t_s_t = mini_batch[5]
else:
a_p = mini_batch[0]
t_p = mini_batch[1]
a_s_i = mini_batch[2]
t_s_i = mini_batch[3]
a_s_t = mini_batch[4]
t_s_t = mini_batch[5]
prediction = transformer_full_predict(seq_ae_teacher_forcing_ratio=0.0,
model=model,
model_input_x=(a_p, t_p),
model_input_y=(a_s_i, t_s_i))
a_p_mini_batches += a_p.tolist()
t_p_mini_batches += t_p.tolist()
a_s_t_mini_batches += a_s_t.tolist()
t_s_t_mini_batches += t_s_t.tolist()
prediction_a_mini_batches += prediction[0].tolist()
prediction_t_mini_batches += prediction[1].tolist()
del a_p
del t_p
del a_s_i
del t_s_i
del a_s_t
del t_s_t
del mini_batch
del prediction
del data_loader
predictions['activities']['prefixes'][prefix] = a_p_mini_batches
predictions['times']['prefixes'][prefix] = t_p_mini_batches
predictions['activities']['suffixes']['target'][prefix] = a_s_t_mini_batches
predictions['times']['suffixes']['target'][prefix] = t_s_t_mini_batches
predictions['activities']['suffixes']['prediction'][prefix] = prediction_a_mini_batches
predictions['times']['suffixes']['prediction'][prefix] = prediction_t_mini_batches
predictions['ids'][prefix] = log_with_prefixes[subset + '_prefixes_and_suffixes']['ids'][prefix]
return predictions
# loop for the rnn model:
def iterate_over_prefixes_rnn(log_with_prefixes,
model=None,
device=None,
subset=None,
to_wrap_into_torch_dataset=None,
max_length=None):
# TODO prepare it for activity labels only
predictions = {'activities': {'prefixes': {}, 'suffixes': {'target': {}, 'prediction': {}}},
'times': {'prefixes': {}, 'suffixes': {'target': {}, 'prediction': {}}},
'ids': {},
'eos_token': log_with_prefixes['eos_token'],
'sos_token': log_with_prefixes['sos_token'],
'pad_token': log_with_prefixes['pad_token'],
'max_time_value': log_with_prefixes['max_time_value'],
'min_time_value': log_with_prefixes['min_time_value']}
if not to_wrap_into_torch_dataset:
# Not implemented
pass
else:
prefixes = list(log_with_prefixes[subset + '_torch_data_loaders'].keys())
for prefix in prefixes:
data_loader = log_with_prefixes[subset + '_torch_data_loaders'][prefix]
a_p_mini_batches = []
t_p_mini_batches = []
a_s_t_mini_batches = []
t_s_t_mini_batches = []
prediction_a_mini_batches = []
prediction_t_mini_batches = []
for mini_batch in iter(data_loader):
if device == 'GPU':
a_p = mini_batch[0].cuda()
t_p = mini_batch[1].cuda()
a_s_i = mini_batch[2].cuda()
t_s_i = mini_batch[3].cuda()
a_s_t = mini_batch[4]
t_s_t = mini_batch[5]
else:
a_p = mini_batch[0]
t_p = mini_batch[1]
a_s_i = mini_batch[2]
t_s_i = mini_batch[3]
a_s_t = mini_batch[4]
t_s_t = mini_batch[5]
prediction = rnn_predict(seq_ae_teacher_forcing_ratio=0.0,
model=model,
model_input_x=(a_p, t_p),
model_input_y=(a_s_i, t_s_i),
max_length=max_length)
a_p_mini_batches += a_p.tolist()
t_p_mini_batches += t_p.tolist()
a_s_t_mini_batches += a_s_t.tolist()
t_s_t_mini_batches += t_s_t.tolist()
prediction_a_mini_batches += prediction[0].tolist()
prediction_t_mini_batches += prediction[1].tolist()
del a_p
del t_p
del a_s_i
del t_s_i
del a_s_t
del t_s_t
del mini_batch
del prediction
del data_loader
predictions['activities']['prefixes'][prefix] = a_p_mini_batches
predictions['times']['prefixes'][prefix] = t_p_mini_batches
predictions['activities']['suffixes']['target'][prefix] = a_s_t_mini_batches
predictions['times']['suffixes']['target'][prefix] = t_s_t_mini_batches
predictions['activities']['suffixes']['prediction'][prefix] = prediction_a_mini_batches
predictions['times']['suffixes']['prediction'][prefix] = prediction_t_mini_batches
predictions['ids'][prefix] = log_with_prefixes[subset + '_prefixes_and_suffixes']['ids'][prefix]
return predictions
def generate_suffixes_ae(checkpoint_file, log_file, args, path):
log_with_prefixes = data_preprocessing.create_prefixes(log_file,
min_prefix=2,
create_tensors=True,
add_special_tokens=True,
pad_sequences=True,
pad_token=args.pad_token,
to_wrap_into_torch_dataset=args.to_wrap_into_torch_dataset,
training_batch_size=args.training_batch_size,
validation_batch_size=args.validation_batch_size,
single_position_target=False)
del log_with_prefixes['training_torch_data_loaders']
# [EOS], [SOS], [PAD]
nb_special_tokens = 3
attributes_meta = {
0: {'nb_special_tokens': nb_special_tokens, 'vocabulary_size': log_with_prefixes['vocabulary_size']},
1: {'min_value': 0.0, 'max_value': 1.0}}
vars(args)['sos_token'] = log_with_prefixes['sos_token']
vars(args)['eos_token'] = log_with_prefixes['eos_token']
vars(args)['nb_special_tokens'] = nb_special_tokens
vars(args)['vocabulary_size'] = log_with_prefixes['vocabulary_size']
vars(args)['longest_trace_length'] = log_with_prefixes['longest_trace_length']
# All traces are longer by one position due to the closing [EOS]:
max_length = log_with_prefixes['longest_trace_length'] + 1
vars(args)['max_length'] = max_length
with open(os.path.join(path, 'evaluation_parameters.json'), 'a') as fp:
json.dump(vars(args), fp)
fp.write('\n')
model = models.SequentialAutoEncoder(hidden_size=args.hidden_dim,
num_layers=args.n_layers,
dropout_prob=args.dropout_prob,
vocab_size=attributes_meta[0]['vocabulary_size'],
attributes_meta=attributes_meta,
time_attribute_concatenated=args.time_attribute_concatenated,
pad_token=args.pad_token,
nb_special_tokens=attributes_meta[0]['nb_special_tokens'])
device = torch.device('cpu')
model.load_state_dict(torch.load(checkpoint_file, map_location=device)['model_state_dict'])
if args.device == 'GPU':
model.cuda()
model.eval()
with torch.no_grad():
predictions = iterate_over_prefixes_ae(log_with_prefixes=log_with_prefixes,
model=model,
device=args.device,
subset='validation',
to_wrap_into_torch_dataset=args.to_wrap_into_torch_dataset)
return predictions
def generate_suffixes_transformer_full(checkpoint_file, log_file, args, path):
log_with_prefixes = data_preprocessing.create_prefixes(log_file,
min_prefix=2,
create_tensors=True,
add_special_tokens=True,
pad_sequences=True,
pad_token=args.pad_token,
to_wrap_into_torch_dataset=args.to_wrap_into_torch_dataset,
training_batch_size=args.training_batch_size,
validation_batch_size=args.validation_batch_size,
single_position_target=False)
del log_with_prefixes['training_torch_data_loaders']
# [EOS], [SOS], [PAD]
nb_special_tokens = 3
attributes_meta = {
0: {'nb_special_tokens': nb_special_tokens, 'vocabulary_size': log_with_prefixes['vocabulary_size']},
1: {'min_value': 0.0, 'max_value': 1.0}}
vars(args)['sos_token'] = log_with_prefixes['sos_token']
vars(args)['eos_token'] = log_with_prefixes['eos_token']
vars(args)['nb_special_tokens'] = nb_special_tokens
vars(args)['vocabulary_size'] = log_with_prefixes['vocabulary_size']
vars(args)['longest_trace_length'] = log_with_prefixes['longest_trace_length']
# All traces are longer by one position due to the closing [EOS]:
max_length = log_with_prefixes['longest_trace_length'] + 1
vars(args)['max_length'] = max_length
with open(os.path.join(path, 'evaluation_parameters.json'), 'a') as fp:
json.dump(vars(args), fp)
fp.write('\n')
model = models.TransformerAutoEncoder(d_model=args.hidden_dim,
sequence_length=max_length,
n_layers=args.n_layers,
n_heads=args.n_heads,
d_query=int(args.hidden_dim / args.n_heads),
dropout_prob=args.dropout_prob,
vocab_size=attributes_meta[0]['vocabulary_size'],
pad_token=args.pad_token,
attributes_meta=attributes_meta,
time_attribute_concatenated=args.time_attribute_concatenated,
nb_special_tokens=attributes_meta[0]['nb_special_tokens'])
device = torch.device('cpu')
model.load_state_dict(torch.load(checkpoint_file, map_location=device)['model_state_dict'])
if args.device == 'GPU':
model.cuda()
model.eval()
with torch.no_grad():
predictions = iterate_over_prefixes_transformer_full(log_with_prefixes=log_with_prefixes,
model=model,
device=args.device,
subset='validation',
to_wrap_into_torch_dataset=args.to_wrap_into_torch_dataset)
del log_with_prefixes
return predictions
def generate_suffixes_rnn(checkpoint_file, log_file, args, path):
log_with_prefixes = data_preprocessing.create_prefixes(log_file,
min_prefix=2,
create_tensors=True,
add_special_tokens=True,
pad_sequences=True,
pad_token=args.pad_token,
to_wrap_into_torch_dataset=args.to_wrap_into_torch_dataset,
training_batch_size=args.training_batch_size,
validation_batch_size=args.validation_batch_size,
single_position_target=False)
del log_with_prefixes['training_torch_data_loaders']
# [EOS], [SOS], [PAD]
nb_special_tokens = 3
attributes_meta = {
0: {'nb_special_tokens': nb_special_tokens, 'vocabulary_size': log_with_prefixes['vocabulary_size']},
1: {'min_value': 0.0, 'max_value': 1.0}}
vars(args)['sos_token'] = log_with_prefixes['sos_token']
vars(args)['eos_token'] = log_with_prefixes['eos_token']
vars(args)['nb_special_tokens'] = nb_special_tokens
vars(args)['vocabulary_size'] = log_with_prefixes['vocabulary_size']
vars(args)['longest_trace_length'] = log_with_prefixes['longest_trace_length']
# All traces are longer by one position due to the closing [EOS]:
max_length = log_with_prefixes['longest_trace_length'] + 1
vars(args)['max_length'] = max_length
with open(os.path.join(path, 'evaluation_parameters.json'), 'a') as fp:
json.dump(vars(args), fp)
fp.write('\n')
model = models.SequentialDecoder(hidden_size=args.hidden_dim,
num_layers=args.n_layers,
dropout_prob=args.dropout_prob,
vocab_size=attributes_meta[0]['vocabulary_size'],
attributes_meta=attributes_meta,
time_attribute_concatenated=args.time_attribute_concatenated,
pad_token=args.pad_token,
nb_special_tokens=attributes_meta[0]['nb_special_tokens'])
device = torch.device('cpu')
model.load_state_dict(torch.load(checkpoint_file, map_location=device)['model_state_dict'])
if args.device == 'GPU':
model.cuda()
model.eval()
with torch.no_grad():
predictions = iterate_over_prefixes_rnn(log_with_prefixes=log_with_prefixes,
model=model,
device=args.device,
subset='validation',