-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.py
3087 lines (2769 loc) · 103 KB
/
functions.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 sys
import math
import torch
import shutil
import sklearn
import warnings
import argparse
import itertools
import numpy as np
from time import time
import seaborn as sns
from datetime import timedelta
from sklearn.manifold import TSNE
from nltk import ngrams
from nltk.lm import NgramCounter
import matplotlib as mpl
mpl.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.offsetbox import AnchoredText
from mpl_toolkits.axes_grid1 import make_axes_locatable
from matplotlib.patches import Patch
import torch.distributed as dist
from torch.utils.data import DataLoader
from torch.nn.parallel import DistributedDataParallel as DDP
from ranger import Ranger
from torch.cuda.amp import autocast
from torch.cuda.amp import GradScaler
from torch.nn import CrossEntropyLoss
from models import LabelSmoothingCrossEntropy
from models import LSTM
from models import Transformer
from models import MyLongformer
mpl.use("Agg")
###############################################################################
# Arguments
###############################################################################
def get_arguments():
"""Parse the arguments and check their values.
Returns:
argparse.ArgumentParser: Arguments.
"""
# Create parser
parser = argparse.ArgumentParser()
# Misc
parser.add_argument("--seed", type=int, default=0, help="random seed")
parser.add_argument(
"--log_folder",
type=str,
default=None,
help="name of the log folder (optional)",
)
parser.add_argument(
"--gpu",
type=str,
default=None,
help="id of GPUs to use seperated by commas",
)
# Data
parser.add_argument(
"--data_path",
type=str,
help="path to the folder that contains the datasets",
)
parser.add_argument(
"--train_folder",
type=str,
help="name of the folder that contains the training set "
"(format: 'Name to display:folder')",
)
parser.add_argument(
"--valid_id_folder",
type=str,
help="name of the folder that contains the in-distribution "
"validation set (format: 'Name to display:folder')",
)
parser.add_argument(
"--valid_ood_folders",
type=str,
help="name of the folders that contains the out-of-distribution "
"validation sets (format: 'Name to display:folder1,"
"Name to display:folder2,')",
)
parser.add_argument(
"--test_id_folder",
type=str,
help="name of the folder that contains the in-distribution "
"test set (format: 'Name to display:folder1,"
"Name to display:folder2,')",
)
parser.add_argument(
"--test_ood_folders",
type=str,
help="name of the folders that contains the out-of-distribution "
"test sets (format: 'Name to display:folder1,"
"Name to display:folder2,')",
)
parser.add_argument(
"--generate_dataset",
action="store_true",
help="generate the dataset in the data folder",
)
parser.add_argument(
"--max_sample",
type=int,
default=None,
help="maximum number of sequences to load",
)
parser.add_argument(
"--max_token", type=int, default=None, help="maximum sequence lengths"
)
# Model
parser.add_argument(
"--model",
type=str,
default="transformer",
choices=["ngram", "lstm", "transformer", "longformer"],
help="model to use",
)
parser.add_argument(
"--load_model",
type=int,
default=None,
help="load the model from the load_model log folder",
)
parser.add_argument(
"--order", type=int, default=None, help="ngram order (value of n)"
)
parser.add_argument(
"--dim_sys",
type=int,
default=None,
help="embedding dimension of system call name",
)
parser.add_argument(
"--dim_entry",
type=int,
default=None,
help="embedding dimension of the entry or exit",
)
parser.add_argument(
"--dim_ret",
type=int,
default=None,
help="embedding dimension of the return value",
)
parser.add_argument(
"--dim_proc",
type=int,
default=None,
help="embedding dimension of process names",
)
parser.add_argument(
"--dim_pid",
type=int,
default=None,
help="embedding dimension of the process id",
)
parser.add_argument(
"--dim_tid",
type=int,
default=None,
help="embedding dimension of the thread id",
)
parser.add_argument(
"--dim_time",
type=int,
default=None,
help="embedding dimension of the elapsed time between events",
)
parser.add_argument(
"--dim_order",
type=int,
default=None,
help="embedding dimension of the ordering",
)
parser.add_argument(
"--n_head",
type=int,
default=None,
help="number of attention heads (d_k = d/h)",
)
parser.add_argument(
"--n_hidden",
type=int,
default=None,
help="number of hidden units of each encoder MLP",
)
parser.add_argument(
"--n_layer", type=int, default=None, help="number of layers"
)
parser.add_argument(
"--dropout",
type=float,
default=None,
help="model dropout rate (embedding & encoder)",
)
parser.add_argument(
"--activation",
type=str,
default=None,
choices=["relu", "gelu", "swiglu"],
help="activation function",
)
parser.add_argument(
"--tfixup",
action="store_true",
help="uses T-fixup initialization and removes the layer normalization",
)
parser.add_argument(
"--window",
type=str,
default=None,
help="LongSelfAttention window size for each layer in the encoder "
"(format: '3,3,5')",
)
parser.add_argument(
"--dilatation",
type=str,
default=None,
help="Dilatation for each LongSelfAttention layer in the encoder, "
"with 1 meaning no dilatation (format: '1, 1, 2')",
)
parser.add_argument(
"--global_att",
type=str,
default=None,
help="Token indexes to apply global attention in all "
"LongSelfAttention layer in the encoder (format: '0, 1').",
)
# Training
parser.add_argument(
"--batch", type=int, default=None, help="batch size per GPU"
)
parser.add_argument(
"--n_update", type=int, default=None, help="number of updates"
)
parser.add_argument(
"--eval",
type=int,
default=None,
help="number of updates before evaluating the model "
"(impact early stopping)",
)
parser.add_argument("--lr", type=float, default=None, help="learning rate")
parser.add_argument(
"--warmup_steps",
type=int,
default=None,
help="increase the learning rate linearly for the first warmup_steps "
"training steps, and decrease it thereafter proportionally to the "
"inverse square root of the step number",
)
parser.add_argument(
"--optimizer",
type=str,
default=None,
choices=["adam", "ranger"],
help="Optimizer algorithm used for training the chosen model",
)
parser.add_argument(
"--clip",
type=float,
default=None,
help="maximum norm of the gradients",
)
parser.add_argument(
"--ls", type=float, default=None, help="label smoothing [0,1]"
)
parser.add_argument(
"--reduce_lr_patience",
type=int,
default=None,
help="number of iterations before dividing the learning rate by 10 "
"if the validation loss did not improve in the last (args.patience/2) "
"evaluations by at least 0.001",
)
parser.add_argument(
"--early_stopping_patience",
type=int,
default=None,
help="number of iterations before early stopping",
)
parser.add_argument(
"--chk", action="store_true", help="use gradient checkpointing"
)
parser.add_argument(
"--amp", action="store_true", help="use automatic mixed-precision"
)
# Analysis
parser.add_argument(
"--dataset_stat",
action="store_true",
help="display data information and plot distributions",
)
parser.add_argument(
"--analysis", action="store_true", help="analyze the model"
)
args = parser.parse_args()
# Assertions
assert os.path.exists(
os.path.join(args.data_path, args.train_folder.split(":")[1])
), f"{os.path.join(args.data_path, args.train_folder.split(':')[1])} "
"does not exist"
assert os.path.exists(
os.path.join(args.data_path, args.valid_id_folder.split(":")[1])
), f"{os.path.join(args.data_path, args.valid_id_folder.split(':')[1])} "
"does not exist"
assert os.path.exists(
os.path.join(args.data_path, args.test_id_folder.split(":")[1])
), f"{os.path.join(args.data_path, args.test_id_folder.split(':')[1])} "
"does not exist"
for f in args.valid_ood_folders.split(","):
assert os.path.exists(
os.path.join(args.data_path, f.split(":")[1])
), f"{os.path.join(args.data_path, f.split(':')[1])} does not exist"
for f in args.test_ood_folders.split(","):
assert os.path.exists(
os.path.join(args.data_path, f.split(":")[1])
), f"{os.path.join(args.data_path, f.split(':')[1])} does not exist"
assert (
args.max_sample is None or args.max_sample > 0
), "The number of samples must be greater than 0"
assert (
args.max_token is None or args.max_token > 0
), "The number of samples must be greater than 0"
assert (
args.order is None or args.order > 1
), "The n-gram order must be greater than 1"
assert (
args.dim_sys is None or args.dim_sys > 0
), "The embedding dimensions must be greater than or equal to 0"
assert (
args.dim_entry is None or args.dim_entry > 0
), "The embedding dimensions must be greater than or equal to 0"
assert (
args.dim_ret is None or args.dim_ret > 0
), "The embedding dimensions must be greater than or equal to 0"
assert (
args.dim_proc is None or args.dim_proc > 0
), "The embedding dimensions must be greater than or equal to 0"
assert (
args.dim_pid is None or args.dim_pid > 0
), "The embedding dimensions must be greater than or equal to 0"
assert (
args.dim_tid is None or args.dim_tid > 0
), "The embedding dimensions must be greater than or equal to 0"
assert (
args.dim_time is None or args.dim_time > 0
), "The embedding dimensions must be greater than or equal to 0"
assert (
args.dim_order is None or args.dim_order > 0
), "The embedding dimensions must be greater than or equal to 0"
assert (
args.n_head is None or args.n_head > 0
), "The number of heads must be greater than 0"
assert (
args.n_hidden is None or args.n_hidden > 0
), "The number of units must be greater than 0"
assert (
args.n_layer is None or args.n_layer > 0
), "The number of layers must be greater than 0"
assert (
args.dropout is None or args.dropout >= 0 and args.dropout <= 1
), "The dropout probability must be greater than 0 and lower than 1"
assert args.window is None or all(
int(x) > 0 for x in args.window.split(",")
), "The window size must be greater than 0"
assert args.dilatation is None or all(
int(x) > 0 for x in args.dilatation.split(",")
), "The dilatation must be greater than 0 (1 = no dilatation)"
assert args.global_att is None or all(
int(x) >= 0 for x in args.global_att.split(",")
), "The global attention(s) must be greater or equal to 0"
assert (
args.batch is None or args.batch > 0
), "The number of sample per batch must be greater than 0"
assert (
args.n_update is None or args.n_update > 0
), "The number of updates must be greater than 0"
assert (
args.eval is None or args.eval > 0
), "The number of updates before evaluating the model must be greater "
"than 0"
assert (
args.n_layer is None or args.n_layer > 0
), "The learning rate must be greater than 0"
assert (
args.warmup_steps is None or args.warmup_steps >= 0
), "The number of warmup steps must be greater than 0"
assert (
args.clip is None or args.clip > 0
), "The gradients' maximum norm must be greater than 0"
assert args.ls is None or (
args.ls >= 0 and args.ls <= 1
), "The label smoothing coefficient must be greater than 0 and lower "
"than 1"
assert (
args.early_stopping_patience is None
or args.early_stopping_patience > 0
), "The number of updates before early stopping must be greater than 0"
assert (
args.reduce_lr_patience is None or args.reduce_lr_patience > 0
), "The number of updates before reducing the learning rate must be "
"greater than 0"
if args.model != "ngram":
assert args.gpu is not None, "Neural networks require a GPU"
assert (
len(args.gpu.split(",")) <= torch.cuda.device_count()
), f"Only {torch.cuda.device_count()} GPU available"
if args.model == "lstm":
if args.chk:
args.chk = False
print("Checkpoint is not implemented for the LSTM")
if args.tfixup:
args.tfixup = False
print("T-fixup is not defined for the LSTM")
if args.activation is not None:
args.activation = None
print("The activation functions are fixed for the LSTM")
if args.model != "longformer":
if args.window is not None:
args.window = None
print("The window attention is only defined for the Longformer")
if args.dilatation is not None:
args.dilatation = None
print("The dilation is only defined for the Longformer")
if args.global_att is not None:
args.global_att = None
print("The global attention is only defined for the Longformer")
if os.path.exists(args.log_folder):
print(f"{args.log_folder} already exists")
return args
###############################################################################
# Data
###############################################################################
def load_trace(file_path):
"""Load the trace located in path.
Args:
file_path (str): Path to the LTTng trace folder.
Returns:
babeltrace.TraceCollection: A collection of one trace.
"""
# Load babeltrace in the function to remove the import if the dataset
# has already been generated (babeltrace not available on Compute Canada)
try:
import bt2
except ImportError:
raise ImportError(
"Library bt2 is not available (https://babeltrace.org)"
)
return bt2.TraceCollectionMessageIterator(file_path)
def get_events(trace_collection, keys=None):
"""Return a generator of events. An event is a dict with the key the
arguement's name.
Args:
trace_collection (babeltrace.TraceCollection): Trace from which
to read the events.
keys (dict, optional): Dictionary of the multiple ways of the arguments
to consider in addition to name and elapsed time between events.
Returns:
generator: A generator of events.
"""
# Load babeltrace in the function to remove the import if the dataset
# has already been generated (babeltrace not available on Compute Canada)
try:
import bt2
except ImportError:
raise ImportError(
"Library bt2 is not available " "(https://babeltrace.org)"
)
for msg in trace_collection:
if type(msg) is not bt2._EventMessageConst:
continue
if (
"syscall" not in msg.event.name
and "event_handler" not in msg.event.name
):
continue
event = dict()
event["name"] = msg.event.name
event["timestamp"] = msg.default_clock_snapshot.ns_from_origin
if (
event["name"] == "httpd:enter_event_handler"
or event["name"] == "httpd:exit_event_handler"
):
if msg.event.payload_field["connection_state"] is None:
event["connection_state"] = -1
else:
event["connection_state"] = int(
msg.event.payload_field["connection_state"]
)
else:
event["connection_state"] = -1
for k, v in keys.items():
try:
event[v] = msg.event[k]
except KeyError:
continue
yield event
def get_requests(events):
"""Split individual requests from Apache. Note that this implementation
is not the fastest, but requires very little memory.
Args:
events (generator): Generator of event.
Yields:
list: A list of events corresponding to a request.
"""
# Dictionary of active threads
threads = {}
for event in events:
# Start the request for a specific thread
if event["name"] == "httpd:enter_event_handler":
# Filter connections that lingers (not real requests)
if event["connection_state"] not in [6, 7]:
threads[event["tid"]] = []
# End the request for a specific thread
elif event["name"] == "httpd:exit_event_handler":
if event["tid"] in threads:
if threads[event["tid"]]:
yield threads[event["tid"]]
del threads[event["tid"]]
# Add the system calls in all currently recording thread
else:
for request in threads.values():
request.append(event)
def generate_dataset(file_path, dict_sys, dict_proc, train=False):
"""Generate the dataset and write it iteratively into a file
that will be iteratively read by the Dataloader.
Args:
file_path (str): Path to the file to load.
dict_sys (dataset.Dictionary): Vocabulary of system call names.
dict_proc (dataset.Dictionary): Vocabulary of process names.
train (bool): Whether to update the dictionaries.
"""
# Open the trace
trace = load_trace(file_path)
# Open the file
f = open(f"{file_path}/data.txt", "w")
# Mapping to consider the multiple way of denoting each argument
# (e.g., the tid may be stored as 'tid' or 'vtid')
keys = {
"vtid": "tid",
"tid": "tid",
"vpid": "pid",
"pid": "pid",
"procname": "procname",
"ret": "ret",
}
start = time()
# Skip the first 1,000 requests as issues may occur when tracing starts.
# Note that 1,000 requests per second were sent, so it amounts to skipping
# the first second (which is on the cautious side)
# MUST BE CHANGED TO 100 FOR THE TOY DATASETS (#TODO)
for i, request in enumerate(
itertools.islice(get_requests(get_events(trace, keys)), 1000, None)
):
print(
f"\rReading {file_path:40s}: {i:9d} "
f"({timedelta(seconds=round(time() - start))})",
file=sys.stderr,
end="",
)
# Start a sequence with the token [START] with no argument (0s)
call = [dict_sys.get_idx("[START]")]
proc = [dict_proc.get_idx("[START]")]
entry, duration, pid, tid, ret = [0], [0], [0], [0], [0]
prev_timestp = None
for event in request:
# Get system call and process names
sysname = event["name"].replace("syscall_", "")
sysname = sysname.replace("entry_", "").replace("exit_", "")
procname = str(event["procname"])
# If it is the train set
if train:
# Add system call name to dictionary
dict_sys.add_word(sysname)
# Add process name to dicitonary
dict_proc.add_word(procname)
# Append system call name
call.append(dict_sys.get_idx(sysname))
# Append entry (1), exit (2), or none (0)
if "entry" in event["name"]:
entry.append(1)
elif "exit" in event["name"]:
entry.append(2)
else:
entry.append(0)
# Append elapsed time between events
if prev_timestp is not None:
duration.append(event["timestamp"] - prev_timestp)
else:
duration.append(0)
prev_timestp = event["timestamp"]
# Append process name
proc.append(dict_proc.get_idx(procname))
# Append pid
pid.append(event["pid"])
# Append tid
tid.append(event["tid"])
# Append return value
if "entry" in event["name"]:
ret.append(0) # start event (no return value)
elif event["ret"] >= 0:
ret.append(1) # success
else:
ret.append(2) # failure
# End the sequence with the token [END] with no argument (0s)
call.append(dict_sys.get_idx("[END]"))
proc.append(dict_proc.get_idx("[END]"))
entry.append(0)
duration.append(0)
pid.append(0)
tid.append(0)
ret.append(0)
f.write(",".join(map(str, call)) + ";")
f.write(",".join(map(str, entry)) + ";")
f.write(",".join(map(str, duration)) + ";")
f.write(",".join(map(str, proc)) + ";")
f.write(",".join(map(str, pid)) + ";")
f.write(",".join(map(str, tid)) + ";")
f.write(",".join(map(str, ret)) + ";")
# Add the duration in ms
f.write(str(sum(duration) / 1e6) + "\n")
# Close the file
f.close()
print(
f"\rReading {file_path:40s}: {i:9d} "
f"({timedelta(seconds=round(time() - start))})",
file=sys.stderr,
)
def dataset_stat(file_path, dict_sys, dict_proc, name, log_folder):
"""Load a dataset from the file given in argument and print its
statistics.
Args:
file_path (str): Path to the file to load.
dict_sys (dataset.Dictionary): Vocabulary of system call names.
dict_proc (dataset.Dictionary): Vocabulary of process names.
name (str): Name of the dataset.
it (int): Iteration number (log folder).
"""
# Create directories if necessary
if not os.path.exists(f"{log_folder}/datasets/{name}"):
os.makedirs(f"{log_folder}/datasets/{name}")
# Request length
length, duration, call, proc = [], [], [], []
with open(file_path, "r") as f:
for line in f:
line = line.split(";")
length.append(len(line[0].split(",")))
duration.append(float(line[-1]))
call.append(list(map(int, (line[0].split(",")))))
proc.append(list(map(int, (line[3].split(",")))))
print("=" * 100 + f"\n{f'{name} Set':^100s}\n" + "=" * 100)
print(f"{'Number of requests':30}: {len(length):68,}")
print(f"{'Min requests length':30}: {min(length):68,}")
print(
f"{'Mean requests length':30}: "
f"{np.mean(length):57.1f} ± {np.std(length):8.1f}"
)
print(f"{'Max requests length':30}: {max(length):68,}")
print(f"{'Min request duration':30}: {min(duration):66.2f}ms")
print(
f"{'Mean request duration':30}: "
f"{np.mean(duration):57.2f} ± {np.std(duration):6.2f}ms"
)
print(f"{'Max request duration':30}: {max(duration):66.2f}ms")
# Plot the duration distribution and syscall/process names histograms
plot_duration(duration, name, log_folder)
plot_length(length, name, log_folder)
plot_hist(call, dict_sys.idx2word, name, "System Call", log_folder)
plot_hist(proc, dict_proc.idx2word, name, "Process", log_folder)
def collate_fn(data):
"""Construct a batch by padding the sequence.
Args:
data (tuple): Tensors to pad.
Returns:
tuple: Padded tensors.
"""
data = list(zip(*data))
data, req_duration = data[:-1], data[-1]
size = list(map(len, data[0]))
pad_data = [
torch.zeros(len(size), max(size), dtype=torch.int64) for _ in data
]
for i, args in enumerate(data):
for j, sample in enumerate(args):
pad_data[i][j][: size[j]] = torch.tensor(sample)
pad_data = [args.type(torch.int64) for args in pad_data]
pad_mask = (pad_data[0] == 0).type(torch.bool)
return pad_data, pad_mask, req_duration
###############################################################################
# n-gram
###############################################################################
# Add n-1 padding at the start and end. Since there is already one START and
# END token, only add n-2 padding (2 = token START) and end (3 = token END)
def nltk_ngram(file_path, n, max_sample):
"""Extract n-grams from the data in the file given in parameter.
Args:
file_path (str): File path of the dataset
n (int): Order of the n-gram.
Returns:
nltk.lm.NgramCounter: NLTK n-gram counter.
"""
start = time()
with open(file_path, "r") as f:
counter = NgramCounter(
(
ngrams(
[2] * (n - 2)
+ list(map(int, line.split(";")[0].split(",")))[:-1],
n,
)
for line in itertools.islice(f, max_sample)
)
)
print(
f"{n}-grams extraction done in "
f"{timedelta(seconds=round(time() - start))}"
)
return counter
def ngram_eval(file_path, counter, n, name, max_sample):
"""Evaluate the n-gram.
Args:
file_path (str): File path of the dataset
counter (nltk.lm.NgramCounter): NLTK n-gram counter
n (int): Order of the n-gram
name (string, optional): Name of the dataset. Defaults to None.
"""
correct, total = 0, 0
with open(file_path, "r") as f:
for line in itertools.islice(f, max_sample):
seq = [2] * (n - 2) + list(
map(int, line.split(";")[0].split(","))
)[:-1]
pred = [
seq[i + n - 1]
== counter[tuple(seq[i : i + n - 1])].most_common()[0][0]
if counter[tuple(seq[i : i + n - 1])]
else False
for i in range(len(seq) - n + 1)
]
total += len(pred)
correct += sum(pred)
print(f"{name:30}: {f'acc {correct / total:.1%}':>68}")
def ood_detection_ngram(
counter,
n,
epsilon,
path_valid_id,
paths_valid_ood,
val_ood_to_test,
path_test_id,
paths_test_ood,
log_folder,
max_sample,
):
# Create directories if necessary
if not os.path.exists(f"{log_folder}/evaluation/ood"):
os.makedirs(f"{log_folder}/evaluation/ood")
# Validation ID
ppl_id = []
with open(path_valid_id[1], "r") as f:
for line in itertools.islice(f, max_sample):
seq = [2] * (n - 2) + list(
map(int, line.split(";")[0].split(","))
)[:-1]
log_likelihood = sum(
math.log(
counter[tuple(seq[i : i + n - 1])][seq[i + n - 1]]
/ counter[tuple(seq[i : i + n - 1])].N()
if (
counter[tuple(seq[i : i + n - 1])]
and counter[tuple(seq[i : i + n - 1])][seq[i + n - 1]]
> 0
)
else epsilon
)
for i in range(len(seq) - n + 1)
)
ppl_id.append(math.exp(-log_likelihood / (len(seq) - n + 1)))
# Test ID
ppl_id_test = []
with open(path_test_id[1], "r") as f:
for line in itertools.islice(f, max_sample):
seq = [2] * (n - 2) + list(
map(int, line.split(";")[0].split(","))
)[:-1]
log_likelihood = sum(
math.log(
counter[tuple(seq[i : i + n - 1])][seq[i + n - 1]]
/ counter[tuple(seq[i : i + n - 1])].N()
if (
counter[tuple(seq[i : i + n - 1])]
and counter[tuple(seq[i : i + n - 1])][seq[i + n - 1]]
> 0
)
else epsilon
)
for i in range(len(seq) - n + 1)
)
ppl_id_test.append(math.exp(-log_likelihood / (len(seq) - n + 1)))
for name, path in paths_valid_ood.items():
# FOR VALIDATION SET:
ppl_ood = []
with open(path, "r") as f:
for line in itertools.islice(f, max_sample):
seq = [2] * (n - 2) + list(
map(int, line.split(";")[0].split(","))
)[:-1]
log_likelihood = sum(
math.log(
counter[tuple(seq[i : i + n - 1])][seq[i + n - 1]]
/ counter[tuple(seq[i : i + n - 1])].N()
if (
counter[tuple(seq[i : i + n - 1])]
and counter[tuple(seq[i : i + n - 1])][
seq[i + n - 1]
]
> 0
)
else epsilon
)
for i in range(len(seq) - n + 1)
)
ppl_ood.append(math.exp(-log_likelihood / (len(seq) - n + 1)))
ppl = ppl_id + ppl_ood
y_true = [0] * len(ppl_id) + [1] * len(ppl_ood)
accuracy, precision, recall, fscore = [], [], [], []
thresholds = np.arange(
min(ppl), max(ppl), step=(max(ppl) - min(ppl)) / 100,
)
for t in thresholds:
y_pred = [1 if p > t else 0 for p in ppl]
precision.append(sklearn.metrics.precision_score(y_true, y_pred))
recall.append(sklearn.metrics.recall_score(y_true, y_pred))
accuracy.append(sklearn.metrics.accuracy_score(y_true, y_pred))
fscore.append(sklearn.metrics.f1_score(y_true, y_pred))
# Get best score based on the validation set
# and use it to evaluate the test set
id_best_threshold = np.argmax(fscore)
best_threhold_value = thresholds[id_best_threshold]
############
# Log
############
auroc = sklearn.metrics.roc_auc_score(y_true, ppl)
print(f"{name}:")
print(f"{' AUROC':30}: {auroc:68.2%}")
print(f"{' Recall':30}: {recall[id_best_threshold]:68.2%}")
print(f"{' Precision':30}: {precision[id_best_threshold]:68.2%}")
print(f"{' F-score':30}: {np.max(fscore):68.2%}")
print(f"{' Accuracy':30}: {accuracy[id_best_threshold]:68.2%}")
############
# ROC curve
############
# Create figure
fig = plt.figure(figsize=(10, 6), tight_layout=True)
ax = fig.add_subplot(111)
# Set colors
dark_gray = "#808080"
# Hide the right and top spines
ax.spines["right"].set_visible(False)
ax.spines["top"].set_visible(False)
# Change axes and tick color
ax.spines["bottom"].set_color(dark_gray)
ax.tick_params(axis="x", colors=dark_gray)
ax.spines["left"].set_color(dark_gray)
ax.tick_params(axis="y", colors=dark_gray)
ax.xaxis.label.set_color(dark_gray)
ax.yaxis.label.set_color(dark_gray)
# Plot
fpr, tpr, _ = sklearn.metrics.roc_curve(y_true, ppl)
plt.plot(fpr, tpr)
plt.plot([0, 1], [0, 1], color=dark_gray, lw=1)
# Labels
plt.xlabel("False Positive Rate")
plt.ylabel("True Positive Rate")
# Make title the length of the graph
divider = make_axes_locatable(ax)
cax = divider.append_axes("top", size="11%", pad=0)
cax.get_xaxis().set_visible(False)
cax.get_yaxis().set_visible(False)
for x in cax.spines:
cax.spines[x].set_visible(False)
cax.spines["top"].set_visible(False)
cax.set_facecolor(dark_gray)
at = AnchoredText(
f"Receiver Operating Characteristic (AUROC: {auroc:.2f})",
loc=6,
pad=0,
prop=dict(backgroundcolor=dark_gray, size=18, color="w"),
)
at.patch.set_edgecolor("none")
cax.add_artist(at)
# Save figure
plt.savefig(f"{log_folder}/evaluation/ood/ROC_{name}.png", dpi=300)
plt.close("all")
# FOR TEST SET:
# Get respective test set and its path
name_test = val_ood_to_test[name]
path_test = paths_test_ood[val_ood_to_test[name]]
ppl_ood_test = []
with open(path_test, "r") as f:
for line in itertools.islice(f, max_sample):