pidsmaker 5.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pidsmaker/__init__.py +1 -0
- pidsmaker/cli.py +81 -0
- pidsmaker/config/__init__.py +2 -0
- pidsmaker/config/config.py +2100 -0
- pidsmaker/config/pipeline.py +1824 -0
- pidsmaker/config/schemas.py +1032 -0
- pidsmaker/datasets.py +323 -0
- pidsmaker/debug_tests.py +30 -0
- pidsmaker/decoders/__init__.py +5 -0
- pidsmaker/decoders/custom_edge_mlp_decoder.py +17 -0
- pidsmaker/decoders/custom_mlp_decoder.py +10 -0
- pidsmaker/decoders/edge_linear_decoder.py +16 -0
- pidsmaker/decoders/inner_product_decoder.py +18 -0
- pidsmaker/decoders/nodlink_decoder.py +56 -0
- pidsmaker/detection/__init__.py +0 -0
- pidsmaker/detection/evaluation_methods/__init__.py +9 -0
- pidsmaker/detection/evaluation_methods/edge_evaluation.py +255 -0
- pidsmaker/detection/evaluation_methods/evaluation_utils.py +1788 -0
- pidsmaker/detection/evaluation_methods/host_two_stage_evaluation.py +115 -0
- pidsmaker/detection/evaluation_methods/node_evaluation.py +459 -0
- pidsmaker/detection/evaluation_methods/node_tw_evaluation.py +196 -0
- pidsmaker/detection/evaluation_methods/plot.py +192 -0
- pidsmaker/detection/evaluation_methods/queue_evaluation.py +456 -0
- pidsmaker/detection/evaluation_methods/tw_evaluation.py +93 -0
- pidsmaker/detection/flash_detection.py +162 -0
- pidsmaker/detection/magic_knn.py +190 -0
- pidsmaker/detection/node_scoring.py +52 -0
- pidsmaker/detection/threatrace_detection.py +65 -0
- pidsmaker/detection/training_methods/__init__.py +1 -0
- pidsmaker/detection/training_methods/inference_loop.py +287 -0
- pidsmaker/detection/training_methods/ocrapt_early_stop.py +165 -0
- pidsmaker/detection/training_methods/threatrace_training.py +168 -0
- pidsmaker/detection/training_methods/training_loop.py +383 -0
- pidsmaker/encoders/__init__.py +22 -0
- pidsmaker/encoders/argus_encoder.py +69 -0
- pidsmaker/encoders/custom_mlp.py +75 -0
- pidsmaker/encoders/custom_mlp_encoder.py +10 -0
- pidsmaker/encoders/egraphsage_encoder.py +56 -0
- pidsmaker/encoders/gat.py +67 -0
- pidsmaker/encoders/gcn.py +27 -0
- pidsmaker/encoders/gin.py +48 -0
- pidsmaker/encoders/glstm.py +298 -0
- pidsmaker/encoders/graph_attention.py +63 -0
- pidsmaker/encoders/gru.py +29 -0
- pidsmaker/encoders/hetero/__init__.py +4 -0
- pidsmaker/encoders/hetero/ancestor_encoder.py +98 -0
- pidsmaker/encoders/hetero/entity_encoder.py +33 -0
- pidsmaker/encoders/hetero/event_encoder.py +81 -0
- pidsmaker/encoders/hetero/hetero_graph_transformer.py +40 -0
- pidsmaker/encoders/lares_encoder.py +68 -0
- pidsmaker/encoders/linear_encoder.py +16 -0
- pidsmaker/encoders/magic_encoder.py +161 -0
- pidsmaker/encoders/rcaid_encoder.py +81 -0
- pidsmaker/encoders/rgcn.py +75 -0
- pidsmaker/encoders/sage.py +51 -0
- pidsmaker/encoders/shadewatcher_encoder.py +149 -0
- pidsmaker/encoders/sum_aggregation.py +20 -0
- pidsmaker/encoders/temporal_wrappers.py +80 -0
- pidsmaker/encoders/textrcnn.py +82 -0
- pidsmaker/encoders/tgn_encoder.py +193 -0
- pidsmaker/experiments/tuning.py +102 -0
- pidsmaker/experiments/uncertainty.py +261 -0
- pidsmaker/factory.py +1456 -0
- pidsmaker/featurization/__init__.py +0 -0
- pidsmaker/featurization/feat_inference_methods/__init__.py +7 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_HFH.py +30 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_TRW.py +65 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_alacarte.py +14 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_doc2vec.py +53 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_fasttext.py +37 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_flash.py +69 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_graph2vec.py +84 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_ocrapt_features.py +95 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_pretrained.py +1728 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_word2vec.py +55 -0
- pidsmaker/featurization/featurization_methods/__init__.py +0 -0
- pidsmaker/featurization/featurization_methods/build_trw.py +66 -0
- pidsmaker/featurization/featurization_methods/featurization_alacarte.py +747 -0
- pidsmaker/featurization/featurization_methods/featurization_doc2vec.py +98 -0
- pidsmaker/featurization/featurization_methods/featurization_fasttext.py +74 -0
- pidsmaker/featurization/featurization_methods/featurization_flash.py +201 -0
- pidsmaker/featurization/featurization_methods/featurization_graph2vec.py +242 -0
- pidsmaker/featurization/featurization_methods/featurization_trw.py +114 -0
- pidsmaker/featurization/featurization_methods/featurization_word2vec.py +89 -0
- pidsmaker/featurization/featurization_utils.py +275 -0
- pidsmaker/featurization/utils/build_random_walks.py +66 -0
- pidsmaker/featurization/utils/trw.py +203 -0
- pidsmaker/hetero.py +81 -0
- pidsmaker/losses.py +170 -0
- pidsmaker/main.py +478 -0
- pidsmaker/mimicry.py +284 -0
- pidsmaker/model.py +382 -0
- pidsmaker/objectives/__init__.py +16 -0
- pidsmaker/objectives/autoencode_edge_emb.py +43 -0
- pidsmaker/objectives/deep_graph_infomax.py +94 -0
- pidsmaker/objectives/detect_few_shot.py +21 -0
- pidsmaker/objectives/one_class.py +75 -0
- pidsmaker/objectives/predict_edge_contrastive.py +165 -0
- pidsmaker/objectives/predict_edge_supervised.py +77 -0
- pidsmaker/objectives/predict_edge_type.py +28 -0
- pidsmaker/objectives/predict_masked_struct.py +49 -0
- pidsmaker/objectives/predict_node_type.py +36 -0
- pidsmaker/objectives/predict_process_tag.py +169 -0
- pidsmaker/objectives/predict_snapshot_embedding.py +97 -0
- pidsmaker/objectives/reconstruct_edge_emb.py +16 -0
- pidsmaker/objectives/reconstruct_masked_feat.py +51 -0
- pidsmaker/objectives/reconstruct_node_emb.py +13 -0
- pidsmaker/objectives/reconstruct_node_feat.py +13 -0
- pidsmaker/objectives/validation_wrapper.py +55 -0
- pidsmaker/preprocessing/__init__.py +0 -0
- pidsmaker/preprocessing/build_graph_methods/__init__.py +1 -0
- pidsmaker/preprocessing/build_graph_methods/build_default_graphs.py +825 -0
- pidsmaker/preprocessing/build_graph_methods/build_magic_graphs.py +216 -0
- pidsmaker/preprocessing/cleaning.py +258 -0
- pidsmaker/preprocessing/transformation_methods/__init__.py +2 -0
- pidsmaker/preprocessing/transformation_methods/attack_generation/synthetic_attack_naive.py +194 -0
- pidsmaker/preprocessing/transformation_methods/transformation_dag.py +28 -0
- pidsmaker/preprocessing/transformation_methods/transformation_merge_edges.py +136 -0
- pidsmaker/preprocessing/transformation_methods/transformation_rcaid_pseudo_graph.py +510 -0
- pidsmaker/preprocessing/transformation_methods/transformation_undirected.py +24 -0
- pidsmaker/preprocessing/transformation_methods/transformation_utils.py +36 -0
- pidsmaker/pretrained/__init__.py +5 -0
- pidsmaker/pretrained/data/__init__.py +4 -0
- pidsmaker/pretrained/data/behavior_signatures.py +548 -0
- pidsmaker/pretrained/data/canonical_tokens.py +1035 -0
- pidsmaker/pretrained/data/edge_filter.py +381 -0
- pidsmaker/pretrained/data/entity_classes.py +476 -0
- pidsmaker/pretrained/data/sampler.py +926 -0
- pidsmaker/pretrained/data/tokenizer_bpe.py +1659 -0
- pidsmaker/pretrained/detect.py +1427 -0
- pidsmaker/pretrained/embedding_generator.py +252 -0
- pidsmaker/pretrained/finetune.py +1434 -0
- pidsmaker/pretrained/models/__init__.py +20 -0
- pidsmaker/pretrained/models/behavior.py +348 -0
- pidsmaker/pretrained/models/bert.py +286 -0
- pidsmaker/pretrained/models/deepwalk.py +128 -0
- pidsmaker/pretrained/models/dgi.py +120 -0
- pidsmaker/pretrained/models/gae.py +114 -0
- pidsmaker/pretrained/models/gnn_distill.py +475 -0
- pidsmaker/pretrained/models/graphmae.py +373 -0
- pidsmaker/pretrained/models/hf_pretrained.py +213 -0
- pidsmaker/pretrained/models/llama.py +110 -0
- pidsmaker/pretrained/models/modernbert.py +567 -0
- pidsmaker/pretrained/models/roberta.py +147 -0
- pidsmaker/pretrained/models/rope_utils.py +99 -0
- pidsmaker/pretrained/models/ropebert.py +322 -0
- pidsmaker/pretrained/models/spider.py +204 -0
- pidsmaker/pretrained/models/tgn.py +770 -0
- pidsmaker/pretrained/pretrain/__init__.py +3 -0
- pidsmaker/pretrained/pretrain/pretrain_behavior_cluster.py +513 -0
- pidsmaker/pretrained/pretrain/pretrain_common.py +585 -0
- pidsmaker/pretrained/pretrain/pretrain_deepwalk.py +31 -0
- pidsmaker/pretrained/pretrain/pretrain_dgi.py +143 -0
- pidsmaker/pretrained/pretrain/pretrain_gae.py +143 -0
- pidsmaker/pretrained/pretrain/pretrain_gnn_distill.py +438 -0
- pidsmaker/pretrained/pretrain/pretrain_graphmae.py +151 -0
- pidsmaker/pretrained/pretrain/pretrain_hf.py +169 -0
- pidsmaker/pretrained/pretrain/pretrain_main.py +275 -0
- pidsmaker/pretrained/pretrain/pretrain_mlm.py +491 -0
- pidsmaker/pretrained/pretrain/pretrain_spider.py +502 -0
- pidsmaker/pretrained/training_utils.py +157 -0
- pidsmaker/process_reapr_gt.py +101 -0
- pidsmaker/resources/config/anomal_e.yml +25 -0
- pidsmaker/resources/config/argus.yml +56 -0
- pidsmaker/resources/config/attack_edges/cadets_e3.yml +435 -0
- pidsmaker/resources/config/attack_edges/cadets_e5.yml +407 -0
- pidsmaker/resources/config/attack_edges/theia_e3.yml +382 -0
- pidsmaker/resources/config/attack_edges/theia_e5.yml +387 -0
- pidsmaker/resources/config/attack_edges/trace_e3.yml +415 -0
- pidsmaker/resources/config/attack_edges/trace_e5.yml +417 -0
- pidsmaker/resources/config/default.yml +315 -0
- pidsmaker/resources/config/egraphsage.yml +95 -0
- pidsmaker/resources/config/euler.yml +104 -0
- pidsmaker/resources/config/eval/eval_set_clustering.json +3170 -0
- pidsmaker/resources/config/experiments/tuning/components/tuning_featurization_methods.yml +29 -0
- pidsmaker/resources/config/experiments/tuning/systems/clearscope_e5/tuning_orthrus.yml +14 -0
- pidsmaker/resources/config/experiments/tuning/systems/default/tuning_default_baselines.yml +13 -0
- pidsmaker/resources/config/experiments/tuning/systems/default/tuning_orthrus_fixed.yml +16 -0
- pidsmaker/resources/config/experiments/uncertainty/none.yml +5 -0
- pidsmaker/resources/config/experiments/uncertainty/run_n_times.yml +12 -0
- pidsmaker/resources/config/experiments/uncertainty/run_n_times_hyperparameters.yml +12 -0
- pidsmaker/resources/config/experiments/uncertainty/uncertainty.yml +22 -0
- pidsmaker/resources/config/flash.yml +79 -0
- pidsmaker/resources/config/jbeil.yml +65 -0
- pidsmaker/resources/config/kairos.yml +121 -0
- pidsmaker/resources/config/lares.yml +115 -0
- pidsmaker/resources/config/magic.yml +86 -0
- pidsmaker/resources/config/nodlink.yml +79 -0
- pidsmaker/resources/config/ocrapt.yml +91 -0
- pidsmaker/resources/config/orthrus.yml +126 -0
- pidsmaker/resources/config/orthrus_fixed.yml +17 -0
- pidsmaker/resources/config/pretrained/README.md +101 -0
- pidsmaker/resources/config/pretrained/cybergfm/cybergfm.yml +49 -0
- pidsmaker/resources/config/pretrained/pretrained.yml +190 -0
- pidsmaker/resources/config/pretrained/pretrained_flash.yml +9 -0
- pidsmaker/resources/config/pretrained/pretrained_kairos.yml +12 -0
- pidsmaker/resources/config/pretrained/pretrained_magic.yml +1 -0
- pidsmaker/resources/config/pretrained/pretrained_nodlink.yml +1 -0
- pidsmaker/resources/config/pretrained/pretrained_orthrus.yml +1 -0
- pidsmaker/resources/config/pretrained/pretrained_supervised.yml +13 -0
- pidsmaker/resources/config/pretrained/pretrained_threatrace.yml +8 -0
- pidsmaker/resources/config/pretrained/pretrained_velox.yml +14 -0
- pidsmaker/resources/config/prographer.yml +136 -0
- pidsmaker/resources/config/rcaid.yml +88 -0
- pidsmaker/resources/config/shadewatcher.yml +146 -0
- pidsmaker/resources/config/tests.yml +10 -0
- pidsmaker/resources/config/threatrace.yml +73 -0
- pidsmaker/resources/config/tuned_baselines/optc_net/tuned_argus.yml +4 -0
- pidsmaker/resources/config/tuned_baselines/optc_net/tuned_lares.yml +13 -0
- pidsmaker/resources/config/velox.yml +10 -0
- pidsmaker/resources/config/viz_config.yml +10 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_06.csv +8 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_11.csv +4 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_12.csv +43 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_13.csv +24 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0411.csv +41 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0412.csv +0 -0
- pidsmaker/resources/ground_truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_browser_0412.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +63 -0
- pidsmaker/resources/ground_truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +56 -0
- pidsmaker/resources/ground_truth/orthrus/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +61 -0
- pidsmaker/resources/ground_truth/orthrus/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +58 -0
- pidsmaker/resources/ground_truth/orthrus/E3-TRACE/node_trace_e3_firefox_0410.csv +11 -0
- pidsmaker/resources/ground_truth/orthrus/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +11 -0
- pidsmaker/resources/ground_truth/orthrus/E3-TRACE/node_trace_e3_pine_0413.csv +14 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT.csv +19 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT_17.csv +107 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_appstarter_0515.csv +26 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_firefox_0517.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_lockwatch_0517.csv +17 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_tester_0517.csv +8 -0
- pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_bits_0515.csv +54 -0
- pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_copykatz_0509.csv +87 -0
- pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_dns_0517.csv +11 -0
- pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_drakon_0517.csv +6 -0
- pidsmaker/resources/ground_truth/orthrus/E5-THEIA/node_THEIA_1_Firefox_Drakon_APT_BinFmt_Elevate_Inject.csv +70 -0
- pidsmaker/resources/ground_truth/orthrus/E5-TRACE/node_Trace_Firefox_Drakon.csv +71 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m1.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m2.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m3.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m4.csv +5 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m5.csv +23 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m6.csv +18 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s1.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s2.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s3.csv +16 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s4.csv +22 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m1.csv +126 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m2.csv +105 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m3.csv +94 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m4.csv +139 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m5.csv +228 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m6.csv +131 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s1.csv +118 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s2.csv +89 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s3.csv +133 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s4.csv +135 -0
- pidsmaker/resources/ground_truth/orthrus/carbanakv2_edr/carbanakv2_edr.csv +2453 -0
- pidsmaker/resources/ground_truth/orthrus/h051/node_h051_0925.csv +114 -0
- pidsmaker/resources/ground_truth/orthrus/h201/node_h201_0923.csv +2905 -0
- pidsmaker/resources/ground_truth/orthrus/h501/node_h501_0924.csv +749 -0
- pidsmaker/resources/ground_truth/orthrus/readme.md +98 -0
- pidsmaker/resources/ground_truth/reapr/E3-CADETS/node_Nginx_Backdoor_06.csv +3 -0
- pidsmaker/resources/ground_truth/reapr/E3-CADETS/node_Nginx_Backdoor_12.csv +655 -0
- pidsmaker/resources/ground_truth/reapr/E3-CADETS/node_Nginx_Backdoor_13.csv +770 -0
- pidsmaker/resources/ground_truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +0 -0
- pidsmaker/resources/ground_truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +18 -0
- pidsmaker/resources/ground_truth/reapr/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +42 -0
- pidsmaker/resources/ground_truth/reapr/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +81 -0
- pidsmaker/resources/ground_truth/reapr/E3-TRACE/node_trace_e3_firefox_0410.csv +37 -0
- pidsmaker/resources/ground_truth/reapr/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +9 -0
- pidsmaker/resources/ground_truth/reapr/E3-TRACE/node_trace_e3_pine_0413.csv +40 -0
- pidsmaker/resources/ground_truth/threatrace/E3-CADETS/ground_truth.txt +12858 -0
- pidsmaker/resources/ground_truth/threatrace/E3-FIVEDIRECTIONS/ground_truth.txt +18420 -0
- pidsmaker/resources/ground_truth/threatrace/E3-THEIA/ground_truth.txt +25363 -0
- pidsmaker/resources/ground_truth/threatrace/E3-TRACE/ground_truth.txt +68265 -0
- pidsmaker/resources/ground_truth/threatrace/README.md +123 -0
- pidsmaker/tasks/__init__.py +10 -0
- pidsmaker/tasks/batching.py +47 -0
- pidsmaker/tasks/construction.py +31 -0
- pidsmaker/tasks/evaluation.py +241 -0
- pidsmaker/tasks/feat_inference.py +413 -0
- pidsmaker/tasks/featurization.py +43 -0
- pidsmaker/tasks/training.py +17 -0
- pidsmaker/tasks/transformation.py +306 -0
- pidsmaker/tasks/triage.py +143 -0
- pidsmaker/tgn.py +635 -0
- pidsmaker/tokenization/__init__.py +112 -0
- pidsmaker/tokenization/base.py +58 -0
- pidsmaker/tokenization/bpe_tokenizer.py +83 -0
- pidsmaker/tokenization/hf_tokenizer.py +61 -0
- pidsmaker/tokenization/hierarchical_tokenizer.py +44 -0
- pidsmaker/tokenization/label_tokenizer.py +24 -0
- pidsmaker/tokenization/nltk_tokenizer.py +84 -0
- pidsmaker/tokenization/substitution.py +295 -0
- pidsmaker/triage/__init__.py +0 -0
- pidsmaker/triage/tracing_methods/__init__.py +1 -0
- pidsmaker/triage/tracing_methods/depimpact.py +213 -0
- pidsmaker/triage/tracing_methods/depimpact_utils.py +537 -0
- pidsmaker/triage/tracing_methods/ocrapt_subgraph.py +267 -0
- pidsmaker/utils/__init__.py +0 -0
- pidsmaker/utils/cache_utils.py +256 -0
- pidsmaker/utils/console.py +282 -0
- pidsmaker/utils/data_utils.py +1742 -0
- pidsmaker/utils/database.py +150 -0
- pidsmaker/utils/dataset_utils.py +413 -0
- pidsmaker/utils/dataset_writer.py +570 -0
- pidsmaker/utils/graph_store.py +634 -0
- pidsmaker/utils/labelling.py +445 -0
- pidsmaker/utils/loss_files.py +193 -0
- pidsmaker/utils/process_tags.py +44 -0
- pidsmaker/utils/utils.py +712 -0
- pidsmaker/vizgen/__init__.py +1 -0
- pidsmaker/vizgen/backfill_manifests.py +100 -0
- pidsmaker/vizgen/dimensionality_reduction.py +249 -0
- pidsmaker/vizgen/embed_exporter.py +467 -0
- pidsmaker/vizgen/exporter.py +493 -0
- pidsmaker/vizgen/html_builder.py +936 -0
- pidsmaker/vizgen/web/__init__.py +1 -0
- pidsmaker/vizgen/web/export.py +62 -0
- pidsmaker/vizgen/web/static/css/app.css +250 -0
- pidsmaker/vizgen/web/static/index.html +182 -0
- pidsmaker/vizgen/web/static/js/app.js +627 -0
- pidsmaker/vizgen/web/static/js/campaign.js +123 -0
- pidsmaker/vizgen/web/static/js/data.js +119 -0
- pidsmaker/vizgen/web/static/js/dialogs.js +240 -0
- pidsmaker/vizgen/web/static/js/jobs.js +75 -0
- pidsmaker/vizgen/web/static/js/scene.js +651 -0
- pidsmaker/vizgen/web/static/js/ui.js +370 -0
- pidsmaker/vizgen/web/static/vendor/OrbitControls.js +1045 -0
- pidsmaker/vizgen/web/static/vendor/d3.v4.min.js +2 -0
- pidsmaker/vizgen/web/static/vendor/three.min.js +6 -0
- pidsmaker/vizgen/web/viz_server.py +2176 -0
- pidsmaker-5.0.0.dist-info/METADATA +597 -0
- pidsmaker-5.0.0.dist-info/RECORD +339 -0
- pidsmaker-5.0.0.dist-info/WHEEL +5 -0
- pidsmaker-5.0.0.dist-info/entry_points.txt +2 -0
- pidsmaker-5.0.0.dist-info/licenses/LICENSE +201 -0
- pidsmaker-5.0.0.dist-info/top_level.txt +1 -0
pidsmaker/utils/utils.py
ADDED
|
@@ -0,0 +1,712 @@
|
|
|
1
|
+
"""General utility functions for PIDSMaker.
|
|
2
|
+
|
|
3
|
+
Provides commonly used utilities including:
|
|
4
|
+
- Timestamp conversion (nanoseconds ↔ datetime)
|
|
5
|
+
- Hashing and string manipulation
|
|
6
|
+
- Database connection handling
|
|
7
|
+
- File I/O and path management
|
|
8
|
+
- Logging and progress tracking (log, log_tqdm)
|
|
9
|
+
- Statistical functions (mean, std, percentile)
|
|
10
|
+
- Random seed setting for reproducibility
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import csv
|
|
14
|
+
import hashlib
|
|
15
|
+
import os
|
|
16
|
+
import random
|
|
17
|
+
import shutil
|
|
18
|
+
import sys
|
|
19
|
+
import time
|
|
20
|
+
from collections import defaultdict
|
|
21
|
+
from datetime import datetime
|
|
22
|
+
from time import mktime
|
|
23
|
+
|
|
24
|
+
import networkx as nx
|
|
25
|
+
import nltk
|
|
26
|
+
import numpy as np
|
|
27
|
+
import pytz
|
|
28
|
+
import torch
|
|
29
|
+
|
|
30
|
+
try: # Only hit the network when the tokenizer data is actually missing
|
|
31
|
+
nltk.data.find("tokenizers/punkt")
|
|
32
|
+
except LookupError:
|
|
33
|
+
nltk.download("punkt", quiet=True)
|
|
34
|
+
|
|
35
|
+
from pidsmaker.config import update_cfg_for_multi_dataset
|
|
36
|
+
from pidsmaker.utils import console
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def stringtomd5(originstr):
|
|
40
|
+
"""Convert string to MD5 hash (using SHA256).
|
|
41
|
+
|
|
42
|
+
Args:
|
|
43
|
+
originstr: String to hash
|
|
44
|
+
|
|
45
|
+
Returns:
|
|
46
|
+
str: Hexadecimal hash digest
|
|
47
|
+
"""
|
|
48
|
+
originstr = originstr.encode("utf-8")
|
|
49
|
+
signaturemd5 = hashlib.sha256()
|
|
50
|
+
signaturemd5.update(originstr)
|
|
51
|
+
return signaturemd5.hexdigest()
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def ns_time_to_datetime(ns):
|
|
55
|
+
"""
|
|
56
|
+
:param ns: int nano timestamp
|
|
57
|
+
:return: datetime format: 2013-10-10 23:40:00.000000000
|
|
58
|
+
"""
|
|
59
|
+
dt = datetime.fromtimestamp(int(ns) // 1000000000)
|
|
60
|
+
s = dt.strftime("%Y-%m-%d %H:%M:%S")
|
|
61
|
+
s += "." + str(int(int(ns) % 1000000000)).zfill(9)
|
|
62
|
+
return s
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def ns_time_to_datetime_US(ns, timezone="US/Eastern"):
|
|
66
|
+
"""
|
|
67
|
+
:param ns: int nano timestamp
|
|
68
|
+
:return: datetime format: 2013-10-10 23:40:00.000000000
|
|
69
|
+
"""
|
|
70
|
+
tz = pytz.timezone(timezone)
|
|
71
|
+
dt = pytz.datetime.datetime.fromtimestamp(int(ns) // 1000000000, tz)
|
|
72
|
+
s = dt.strftime("%Y-%m-%d %H:%M:%S")
|
|
73
|
+
s += "." + str(int(int(ns) % 1000000000)).zfill(9)
|
|
74
|
+
return s
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def time_to_datetime_US(s, timezone="US/Eastern"):
|
|
78
|
+
"""
|
|
79
|
+
:param ns: int nano timestamp
|
|
80
|
+
:return: datetime format: 2013-10-10 23:40:00
|
|
81
|
+
"""
|
|
82
|
+
tz = pytz.timezone(timezone)
|
|
83
|
+
dt = pytz.datetime.datetime.fromtimestamp(int(s), tz)
|
|
84
|
+
s = dt.strftime("%Y-%m-%d %H:%M:%S")
|
|
85
|
+
|
|
86
|
+
return s
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def datetime_to_ns_time(date):
|
|
90
|
+
"""
|
|
91
|
+
:param date: str format: %Y-%m-%d %H:%M:%S e.g. 2013-10-10 23:40:00
|
|
92
|
+
:return: nano timestamp
|
|
93
|
+
"""
|
|
94
|
+
timeArray = time.strptime(date, "%Y-%m-%d %H:%M:%S")
|
|
95
|
+
timeStamp = int(time.mktime(timeArray))
|
|
96
|
+
timeStamp = timeStamp * 1000000000
|
|
97
|
+
return timeStamp
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def datetime_to_ns_time_US(date, timezone="US/Eastern"):
|
|
101
|
+
"""
|
|
102
|
+
:param date: str format: %Y-%m-%d %H:%M:%S e.g. 2013-10-10 23:40:00
|
|
103
|
+
:return: nano timestamp
|
|
104
|
+
"""
|
|
105
|
+
tz = pytz.timezone(timezone)
|
|
106
|
+
timeArray = time.strptime(date, "%Y-%m-%d %H:%M:%S")
|
|
107
|
+
dt = datetime.fromtimestamp(mktime(timeArray))
|
|
108
|
+
timestamp = tz.localize(dt)
|
|
109
|
+
timestamp = timestamp.timestamp()
|
|
110
|
+
timeStamp = timestamp * 1000000000
|
|
111
|
+
return int(timeStamp)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def datetime_to_timestamp_US(date, timezone="US/Eastern"):
|
|
115
|
+
"""
|
|
116
|
+
:param date: str format: %Y-%m-%d %H:%M:%S e.g. 2013-10-10 23:40:00
|
|
117
|
+
:return: nano timestamp
|
|
118
|
+
"""
|
|
119
|
+
tz = pytz.timezone(timezone)
|
|
120
|
+
timeArray = time.strptime(date, "%Y-%m-%d %H:%M:%S")
|
|
121
|
+
dt = datetime.fromtimestamp(mktime(timeArray))
|
|
122
|
+
timestamp = tz.localize(dt)
|
|
123
|
+
timestamp = timestamp.timestamp()
|
|
124
|
+
timeStamp = timestamp
|
|
125
|
+
return int(timeStamp)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def OPTC_datetime_to_timestamp_US(date, timezone="Etc/GMT+4"):
|
|
129
|
+
"""convert OPTC datetime string to timestamp in nanoseconds"""
|
|
130
|
+
date = date.replace("-04:00", "")
|
|
131
|
+
if "." in date:
|
|
132
|
+
date, ms = date.split(".")
|
|
133
|
+
else:
|
|
134
|
+
ms = 0
|
|
135
|
+
tz = pytz.timezone("Etc/GMT+4")
|
|
136
|
+
timeArray = time.strptime(date, "%Y-%m-%dT%H:%M:%S")
|
|
137
|
+
dt = datetime.fromtimestamp(mktime(timeArray))
|
|
138
|
+
timestamp = tz.localize(dt)
|
|
139
|
+
timestamp = timestamp.timestamp()
|
|
140
|
+
timeStamp = timestamp * 1000 + int(ms)
|
|
141
|
+
return int(timeStamp) * 1000000
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def init_database_connection(cfg):
|
|
145
|
+
"""(cursor, connection) of the database of the dataset (see `pidsmaker/utils/database.py`)."""
|
|
146
|
+
from pidsmaker.utils.database import init_database_connection as _init
|
|
147
|
+
|
|
148
|
+
return _init(cfg)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def std(t):
|
|
152
|
+
t = np.array(t)
|
|
153
|
+
return np.std(t)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def var(t):
|
|
157
|
+
t = np.array(t)
|
|
158
|
+
return np.var(t)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def mean(t):
|
|
162
|
+
t = np.array(t)
|
|
163
|
+
return np.mean(t)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def percentile_90(t):
|
|
167
|
+
sorted_data = np.sort(t)
|
|
168
|
+
Q = np.percentile(sorted_data, 90)
|
|
169
|
+
return Q
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def gen_darpa_rw_file(walk_len, corpus_fd, adjfilename, overall_fd, num_walks=10):
|
|
173
|
+
adj_list = {}
|
|
174
|
+
back_adj_list = {}
|
|
175
|
+
with open(adjfilename, "r") as adj_file:
|
|
176
|
+
for line in log_tqdm(adj_file, desc="Creating adj list"):
|
|
177
|
+
line = line.strip().split(",")
|
|
178
|
+
srcID = line[0]
|
|
179
|
+
dstID = line[1]
|
|
180
|
+
edgeLabel = line[4]
|
|
181
|
+
|
|
182
|
+
if srcID not in adj_list:
|
|
183
|
+
adj_list[srcID] = {}
|
|
184
|
+
|
|
185
|
+
if dstID not in adj_list[srcID]:
|
|
186
|
+
adj_list[srcID][dstID] = set()
|
|
187
|
+
|
|
188
|
+
if dstID not in back_adj_list:
|
|
189
|
+
back_adj_list[dstID] = {}
|
|
190
|
+
|
|
191
|
+
if srcID not in back_adj_list[dstID]:
|
|
192
|
+
back_adj_list[dstID][srcID] = set()
|
|
193
|
+
|
|
194
|
+
adj_list[srcID][dstID].add(edgeLabel)
|
|
195
|
+
back_adj_list[dstID][srcID].add(edgeLabel)
|
|
196
|
+
|
|
197
|
+
if True:
|
|
198
|
+
lines_buffer = []
|
|
199
|
+
|
|
200
|
+
# Computing random neighbors for each iteration is extremely slow.
|
|
201
|
+
# We thus pre-compute a list of random indices for all unique numbers of neighbors.
|
|
202
|
+
# These indices can then be accessed given the length of the neighbors.
|
|
203
|
+
unique_neighbors_count = set(len(v) for v in adj_list.values()) | set(
|
|
204
|
+
len(v) for v in back_adj_list.values()
|
|
205
|
+
)
|
|
206
|
+
cache_size = 10 * len(adj_list) * num_walks * walk_len
|
|
207
|
+
random_cache = {
|
|
208
|
+
count: np.random.randint(0, count, size=cache_size) for count in unique_neighbors_count
|
|
209
|
+
}
|
|
210
|
+
random_idx = {count: 0 for count in unique_neighbors_count}
|
|
211
|
+
|
|
212
|
+
def get_rand(count):
|
|
213
|
+
if count not in random_cache:
|
|
214
|
+
return np.random.randint(0, count)
|
|
215
|
+
idx = random_idx[count]
|
|
216
|
+
val = random_cache[count][idx]
|
|
217
|
+
random_idx[count] = (idx + 1) % cache_size # Wrap-around cache
|
|
218
|
+
return val
|
|
219
|
+
|
|
220
|
+
for src in log_tqdm(adj_list, desc="Forward random walking"):
|
|
221
|
+
walk_num = len(adj_list[src]) * num_walks
|
|
222
|
+
for i in range(walk_num):
|
|
223
|
+
start = src
|
|
224
|
+
path_sentence = []
|
|
225
|
+
for j in range(walk_len):
|
|
226
|
+
start_keys = list(adj_list[start].keys())
|
|
227
|
+
dst = start_keys[get_rand(len(start_keys))]
|
|
228
|
+
|
|
229
|
+
start_dst = list(adj_list[start][dst])
|
|
230
|
+
edge_type = start_dst[get_rand(len(start_dst))]
|
|
231
|
+
|
|
232
|
+
if len(path_sentence) == 0:
|
|
233
|
+
# path_sentence.append(f"{graph.nodes[start]['label']},{edge_type},{graph.nodes[dst]['label']}")
|
|
234
|
+
path_sentence.append(f"{start},{edge_type},{dst}")
|
|
235
|
+
else:
|
|
236
|
+
# path_sentence.append(f"{edge_type},{graph.nodes[dst]['label']}")
|
|
237
|
+
path_sentence.append(f"{edge_type},{dst}")
|
|
238
|
+
|
|
239
|
+
if dst not in adj_list:
|
|
240
|
+
break
|
|
241
|
+
else:
|
|
242
|
+
start = dst
|
|
243
|
+
|
|
244
|
+
# We do not consider the nodes without any outgoing edges.
|
|
245
|
+
# We only record the paths.
|
|
246
|
+
if len(path_sentence) != 0:
|
|
247
|
+
path_str = ",".join(path_sentence)
|
|
248
|
+
lines_buffer.append(path_str)
|
|
249
|
+
|
|
250
|
+
# Run bidirectional random walking to ensure that every node appears in the corpus
|
|
251
|
+
# Missing sink nodes leads to issues when training A La Carte Matrix
|
|
252
|
+
for dst in log_tqdm(back_adj_list, desc="Backward random walking"):
|
|
253
|
+
walk_num = len(back_adj_list[dst]) * num_walks # NOTE: it seems a lot
|
|
254
|
+
for i in range(walk_num):
|
|
255
|
+
start = dst
|
|
256
|
+
path_sentence = []
|
|
257
|
+
for j in range(walk_len):
|
|
258
|
+
start_keys = list(back_adj_list[start].keys())
|
|
259
|
+
src = start_keys[get_rand(len(start_keys))]
|
|
260
|
+
|
|
261
|
+
start_src = list(back_adj_list[start][src])
|
|
262
|
+
edge_type = start_src[get_rand(len(start_src))]
|
|
263
|
+
|
|
264
|
+
if len(path_sentence) == 0:
|
|
265
|
+
# path_sentence.append(f"{graph.nodes[start]['label']},{edge_type},{graph.nodes[dst]['label']}")
|
|
266
|
+
path_sentence.append(f"{start},{edge_type},{src}")
|
|
267
|
+
else:
|
|
268
|
+
# path_sentence.append(f"{edge_type},{graph.nodes[dst]['label']}")
|
|
269
|
+
path_sentence.append(f"{edge_type},{src}")
|
|
270
|
+
|
|
271
|
+
if src not in back_adj_list:
|
|
272
|
+
break
|
|
273
|
+
else:
|
|
274
|
+
start = src
|
|
275
|
+
|
|
276
|
+
# We do not consider the nodes without any outgoing edges.
|
|
277
|
+
# We only record the paths.
|
|
278
|
+
if len(path_sentence) != 0:
|
|
279
|
+
path_str = ",".join(path_sentence)
|
|
280
|
+
lines_buffer.append(path_str)
|
|
281
|
+
|
|
282
|
+
lines = "\n".join(lines_buffer)
|
|
283
|
+
corpus_fd.write(lines)
|
|
284
|
+
overall_fd.write(lines)
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def gen_darpa_adj_files(graph, filename):
|
|
288
|
+
with open(filename, "w") as f:
|
|
289
|
+
writer = csv.writer(f)
|
|
290
|
+
for u, v, k in graph.edges:
|
|
291
|
+
# srcID, dstID, srcLabel, dstLabel, edgeLabel
|
|
292
|
+
data = [
|
|
293
|
+
u,
|
|
294
|
+
v,
|
|
295
|
+
graph.nodes[u]["label"],
|
|
296
|
+
graph.nodes[v]["label"],
|
|
297
|
+
graph.edges[u, v, k]["label"] if "label" in graph.edges[u, v, k] else "",
|
|
298
|
+
graph.nodes[u]["node_type"],
|
|
299
|
+
graph.nodes[v]["node_type"],
|
|
300
|
+
]
|
|
301
|
+
writer.writerow(data)
|
|
302
|
+
f.close()
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def get_all_files_from_folders(base_dir: str, folders: list[str]):
|
|
306
|
+
paths = [
|
|
307
|
+
os.path.abspath(os.path.join(base_dir, sub, f))
|
|
308
|
+
for sub in os.listdir(base_dir)
|
|
309
|
+
if os.path.isdir(os.path.join(base_dir, sub)) and sub in folders
|
|
310
|
+
for f in os.listdir(os.path.join(base_dir, sub))
|
|
311
|
+
]
|
|
312
|
+
paths.sort(key=lambda f: int("".join(filter(str.isdigit, f))))
|
|
313
|
+
return paths
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def get_all_graphs_for_dates(base_dir: str, dates: list[str]):
|
|
317
|
+
return get_all_files_from_folders(base_dir, [f"graph_{date}" for date in dates])
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def load_graphs_for_dates(base_dir: str, dates: list[str]):
|
|
321
|
+
"""Loads all graph snapshots for a given list of dates."""
|
|
322
|
+
return [
|
|
323
|
+
torch.load(path) for date in dates for path in get_all_graphs_for_dates(base_dir, [date])
|
|
324
|
+
]
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def get_all_filelist(filepath):
|
|
328
|
+
"""get all file paths under the given filepath recursively"""
|
|
329
|
+
file_paths = []
|
|
330
|
+
for root, dirs, files in os.walk(filepath):
|
|
331
|
+
for file in files:
|
|
332
|
+
full_path = os.path.join(root, file)
|
|
333
|
+
abs_path = os.path.abspath(full_path)
|
|
334
|
+
file_paths.append(abs_path)
|
|
335
|
+
return file_paths
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def listdir_sorted(path: str):
|
|
339
|
+
files = os.listdir(path)
|
|
340
|
+
files.sort(key=lambda f: int("".join(filter(str.isdigit, f)))) # sorted by ascending number
|
|
341
|
+
return files
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def remove_underscore_keys(data, keys_to_keep=[], keys_to_rm=[]):
|
|
345
|
+
for key in list(data.keys()):
|
|
346
|
+
if (key in keys_to_rm) or (key.startswith("_") and key not in keys_to_keep):
|
|
347
|
+
del data[key]
|
|
348
|
+
elif isinstance(data[key], dict):
|
|
349
|
+
data[key] = dict(data[key])
|
|
350
|
+
remove_underscore_keys(data[key], keys_to_keep, keys_to_rm)
|
|
351
|
+
return data
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def log(msg: str = "", return_line=False, pre_return_line=False, *args, **kwargs):
|
|
355
|
+
"""Prints `msg` after the time of day (see `pidsmaker.utils.console`)."""
|
|
356
|
+
if pre_return_line:
|
|
357
|
+
print(flush=True)
|
|
358
|
+
console.log(msg, *args, **kwargs)
|
|
359
|
+
if return_line:
|
|
360
|
+
print(flush=True)
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def log_tqdm(iterator, desc="", logging=True, **kwargs):
|
|
364
|
+
"""Progress bar of a loop in a terminal; in log files, `desc` is logged once per task
|
|
365
|
+
(unless not `logging`)."""
|
|
366
|
+
if not console.INTERACTIVE and not logging:
|
|
367
|
+
return iterator
|
|
368
|
+
return console.progress(iterator, desc=desc, **kwargs)
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
LOW_MEMORY_GB = 16
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def available_memory_gb():
|
|
375
|
+
"""RAM usable by this process, in GB: the RAM of the machine, or the memory limit of its
|
|
376
|
+
cgroup (e.g. of a container or of an HPC job) if it is lower. None if it cannot be read."""
|
|
377
|
+
try:
|
|
378
|
+
import psutil
|
|
379
|
+
|
|
380
|
+
total = psutil.virtual_memory().total
|
|
381
|
+
except Exception:
|
|
382
|
+
return None
|
|
383
|
+
# Memory limit of the cgroup (v2, then v1); "max" or a huge value means no limit
|
|
384
|
+
for path in ("/sys/fs/cgroup/memory.max", "/sys/fs/cgroup/memory/memory.limit_in_bytes"):
|
|
385
|
+
try:
|
|
386
|
+
with open(path) as f:
|
|
387
|
+
limit = f.read().strip()
|
|
388
|
+
if limit.isdigit():
|
|
389
|
+
total = min(total, int(limit))
|
|
390
|
+
break
|
|
391
|
+
except OSError:
|
|
392
|
+
continue
|
|
393
|
+
return total / (1024**3)
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def warn_if_low_memory(min_gb=LOW_MEMORY_GB):
|
|
397
|
+
"""Warns when less than `min_gb` of RAM are available: runs killed by the kernel when they
|
|
398
|
+
run out of memory otherwise only print `Killed`."""
|
|
399
|
+
memory_gb = available_memory_gb()
|
|
400
|
+
if memory_gb is not None and memory_gb < min_gb:
|
|
401
|
+
log(
|
|
402
|
+
f"Warning: only {memory_gb:.1f} GB of RAM are available, runs on large datasets may "
|
|
403
|
+
f"be killed when they run out of memory."
|
|
404
|
+
)
|
|
405
|
+
return memory_gb
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
class PeakCPUMemory:
|
|
409
|
+
"""Cheap peak resident memory (RSS) tracker, in GB.
|
|
410
|
+
|
|
411
|
+
Replaces `tracemalloc`, which slows down every Python allocation and does not see
|
|
412
|
+
the memory allocated by torch/numpy. On Linux, the RSS high-water mark is reset at
|
|
413
|
+
`start()` through `/proc/self/clear_refs`; elsewhere, the process lifetime peak is used.
|
|
414
|
+
"""
|
|
415
|
+
|
|
416
|
+
def start(self):
|
|
417
|
+
try:
|
|
418
|
+
with open("/proc/self/clear_refs", "w") as f:
|
|
419
|
+
f.write("5")
|
|
420
|
+
except OSError:
|
|
421
|
+
pass
|
|
422
|
+
return self
|
|
423
|
+
|
|
424
|
+
@staticmethod
|
|
425
|
+
def peak_gb():
|
|
426
|
+
try:
|
|
427
|
+
with open("/proc/self/status") as f:
|
|
428
|
+
for line in f:
|
|
429
|
+
if line.startswith("VmHWM:"):
|
|
430
|
+
return int(line.split()[1]) / (1024**2) # kB -> GB
|
|
431
|
+
except OSError:
|
|
432
|
+
pass
|
|
433
|
+
import resource
|
|
434
|
+
|
|
435
|
+
# ru_maxrss is in bytes on macOS, and in kB on Linux
|
|
436
|
+
unit = 1 if sys.platform == "darwin" else 1024
|
|
437
|
+
return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss * unit / (1024**3)
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def get_device(cfg):
|
|
441
|
+
if cfg._use_cpu:
|
|
442
|
+
return torch.device("cpu")
|
|
443
|
+
|
|
444
|
+
# The device is shown at the start of the run
|
|
445
|
+
return torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
446
|
+
|
|
447
|
+
def copy_directory(src_path, dest_path):
|
|
448
|
+
if not os.path.isdir(src_path):
|
|
449
|
+
log(f"The source path '{src_path}' does not exist or is not a directory.")
|
|
450
|
+
return
|
|
451
|
+
|
|
452
|
+
if os.path.exists(dest_path):
|
|
453
|
+
log(f"The destination path '{dest_path}' already exists. Removing it for a fresh copy.")
|
|
454
|
+
shutil.rmtree(dest_path)
|
|
455
|
+
|
|
456
|
+
try:
|
|
457
|
+
shutil.copytree(src_path, dest_path)
|
|
458
|
+
log(f"Directory copied successfully from '{src_path}' to '{dest_path}'.")
|
|
459
|
+
except Exception as e:
|
|
460
|
+
log(f"An error occurred while copying the directory: {e}")
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def symlink_directory(src_path, dest_path):
|
|
464
|
+
src_path = src_path.rstrip("/")
|
|
465
|
+
dest_path = dest_path.rstrip("/")
|
|
466
|
+
|
|
467
|
+
if not os.path.isdir(src_path):
|
|
468
|
+
log(f"The source path '{src_path}' does not exist or is not a directory.")
|
|
469
|
+
return
|
|
470
|
+
|
|
471
|
+
if os.path.islink(dest_path):
|
|
472
|
+
os.remove(dest_path)
|
|
473
|
+
elif os.path.exists(dest_path):
|
|
474
|
+
log(f"The destination path '{dest_path}' already exists. Removing it.")
|
|
475
|
+
shutil.rmtree(dest_path)
|
|
476
|
+
|
|
477
|
+
src_path = os.path.abspath(src_path)
|
|
478
|
+
os.makedirs(os.path.dirname(dest_path), exist_ok=True)
|
|
479
|
+
os.symlink(src_path, dest_path)
|
|
480
|
+
log(console.style(f"Linked {console.short_path(dest_path)} -> {console.short_path(src_path)}", "dim"))
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
def get_split_to_files(cfg, base_dir):
|
|
484
|
+
return {
|
|
485
|
+
"train": get_all_graphs_for_dates(base_dir, cfg.dataset.train_dates),
|
|
486
|
+
"val": get_all_graphs_for_dates(base_dir, cfg.dataset.val_dates),
|
|
487
|
+
"test": get_all_graphs_for_dates(base_dir, cfg.dataset.test_dates),
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
def gen_relation_onehot(rel2id):
|
|
492
|
+
num_rels = len(rel2id.keys()) // 2
|
|
493
|
+
max_id = max(v for v in rel2id.values() if type(v) is int)
|
|
494
|
+
relvec = torch.nn.functional.one_hot(
|
|
495
|
+
torch.arange(0, max_id), num_classes=max_id
|
|
496
|
+
)
|
|
497
|
+
rel2vec = {}
|
|
498
|
+
for i in rel2id.keys():
|
|
499
|
+
if type(i) is not int:
|
|
500
|
+
rel2vec[i] = relvec[rel2id[i] - 1]
|
|
501
|
+
rel2vec[relvec[rel2id[i] - 1]] = i
|
|
502
|
+
return rel2vec
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def get_indexid2msg(cfg, gather_multi_dataset=False):
|
|
506
|
+
def load_file(cfg):
|
|
507
|
+
indexid2msg_file = os.path.join(cfg.construction._dicts_dir, "indexid2msg.pkl")
|
|
508
|
+
indexid2msg = torch.load(indexid2msg_file)
|
|
509
|
+
return indexid2msg
|
|
510
|
+
|
|
511
|
+
if gather_multi_dataset:
|
|
512
|
+
multi_datasets = get_multi_datasets(cfg)
|
|
513
|
+
log(f"Multi-dataset order: {multi_datasets}")
|
|
514
|
+
|
|
515
|
+
all_indexid2msg = {}
|
|
516
|
+
cumsum = 0
|
|
517
|
+
for dataset in multi_datasets:
|
|
518
|
+
cfg, _ = update_cfg_for_multi_dataset(cfg, dataset)
|
|
519
|
+
|
|
520
|
+
indexid2msg = load_file(cfg)
|
|
521
|
+
max_node = max(map(int, list(indexid2msg.keys())))
|
|
522
|
+
indexid2msg = {str(int(k) + cumsum): v for k, v in indexid2msg.items()}
|
|
523
|
+
cumsum += max_node
|
|
524
|
+
|
|
525
|
+
# Merge the cumsumed indices and original values from all datasets
|
|
526
|
+
all_indexid2msg = {**all_indexid2msg, **indexid2msg}
|
|
527
|
+
return all_indexid2msg
|
|
528
|
+
|
|
529
|
+
return load_file(cfg)
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
def get_split2nodes(cfg, gather_multi_dataset=False):
|
|
533
|
+
def load_file(cfg):
|
|
534
|
+
path = os.path.join(cfg.construction._dicts_dir, "split2nodes.pkl")
|
|
535
|
+
split2nodes = torch.load(path)
|
|
536
|
+
return split2nodes
|
|
537
|
+
|
|
538
|
+
multi_datasets = get_multi_datasets(cfg)
|
|
539
|
+
use_multi_dataset = "none" not in cfg.construction.multi_dataset
|
|
540
|
+
|
|
541
|
+
if gather_multi_dataset and use_multi_dataset:
|
|
542
|
+
all_split2nodes = defaultdict(set)
|
|
543
|
+
cumsum = 0
|
|
544
|
+
for dataset in multi_datasets:
|
|
545
|
+
cfg, _ = update_cfg_for_multi_dataset(cfg, dataset)
|
|
546
|
+
|
|
547
|
+
split2nodes = load_file(cfg)
|
|
548
|
+
indexid2msg = get_indexid2msg(cfg)
|
|
549
|
+
max_node = max(map(int, list(indexid2msg.keys())))
|
|
550
|
+
split2nodes = {k: {str(int(e) + cumsum) for e in v} for k, v in split2nodes.items()}
|
|
551
|
+
cumsum += max_node
|
|
552
|
+
|
|
553
|
+
for k, v in split2nodes.items():
|
|
554
|
+
all_split2nodes[k] |= v
|
|
555
|
+
return all_split2nodes
|
|
556
|
+
|
|
557
|
+
return load_file(cfg)
|
|
558
|
+
|
|
559
|
+
|
|
560
|
+
def compute_class_weights(labels, num_classes):
|
|
561
|
+
"""
|
|
562
|
+
Compute balanced class weights for a given set of labels using PyTorch,
|
|
563
|
+
and pad the weights with 0s if some classes are missing in the batch.
|
|
564
|
+
|
|
565
|
+
Parameters:
|
|
566
|
+
labels (Tensor): A 1D tensor containing class indices for each sample.
|
|
567
|
+
num_classes (int): The number of unique classes.
|
|
568
|
+
|
|
569
|
+
Returns:
|
|
570
|
+
Tensor: A tensor containing the weight for each class, padded to num_classes.
|
|
571
|
+
"""
|
|
572
|
+
# From 1-hot to label index
|
|
573
|
+
labels = labels.argmax(dim=-1)
|
|
574
|
+
|
|
575
|
+
# Count the number of instances for each class
|
|
576
|
+
class_counts = torch.bincount(labels, minlength=num_classes).float()
|
|
577
|
+
total_count = len(labels)
|
|
578
|
+
|
|
579
|
+
# Initialize weights with zeros for all classes
|
|
580
|
+
class_weights = torch.zeros(num_classes, device=labels.device)
|
|
581
|
+
|
|
582
|
+
# Avoid division by zero by checking for non-zero class counts
|
|
583
|
+
non_zero_classes = class_counts > 0
|
|
584
|
+
class_weights[non_zero_classes] = total_count / (num_classes * class_counts[non_zero_classes])
|
|
585
|
+
|
|
586
|
+
return class_weights
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
def calculate_average_from_file(filename):
|
|
590
|
+
numbers = []
|
|
591
|
+
try:
|
|
592
|
+
with open(filename, "r") as f:
|
|
593
|
+
for line in f:
|
|
594
|
+
numbers.append(float(line.strip()))
|
|
595
|
+
if numbers:
|
|
596
|
+
return sum(numbers) / len(numbers)
|
|
597
|
+
else:
|
|
598
|
+
return 1e-9
|
|
599
|
+
except FileNotFoundError:
|
|
600
|
+
log(f"{filename} does not exist")
|
|
601
|
+
return None
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
def get_events_between_GPs(cur, start_time, end_time, malicious_nodes: list):
|
|
605
|
+
malicious_nodes_str = ", ".join(f"'{node}'" for node in malicious_nodes)
|
|
606
|
+
sql = f"SELECT * FROM event_table WHERE timestamp_rec BETWEEN '{start_time}' AND '{end_time}' AND src_index_id IN ({malicious_nodes_str}) AND dst_index_id IN ({malicious_nodes_str});"
|
|
607
|
+
cur.execute(sql)
|
|
608
|
+
rows = cur.fetchall()
|
|
609
|
+
return rows
|
|
610
|
+
|
|
611
|
+
|
|
612
|
+
def get_events_between_time_range(
|
|
613
|
+
cur,
|
|
614
|
+
start_time,
|
|
615
|
+
end_time,
|
|
616
|
+
):
|
|
617
|
+
sql = f"SELECT * FROM event_table WHERE timestamp_rec BETWEEN '{start_time}' AND '{end_time}';"
|
|
618
|
+
cur.execute(sql)
|
|
619
|
+
rows = cur.fetchall()
|
|
620
|
+
return rows
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
def generate_DAG(edges):
|
|
624
|
+
node_version = {}
|
|
625
|
+
for u, v, t in edges:
|
|
626
|
+
if u not in node_version:
|
|
627
|
+
node_version[u] = 0
|
|
628
|
+
if v not in node_version:
|
|
629
|
+
node_version[v] = 0
|
|
630
|
+
|
|
631
|
+
sorted_edges = sorted(edges, key=lambda x: x[2])
|
|
632
|
+
|
|
633
|
+
new_nodes = set()
|
|
634
|
+
new_edges = []
|
|
635
|
+
visited = set()
|
|
636
|
+
for u, v, t in sorted_edges:
|
|
637
|
+
if u == v:
|
|
638
|
+
continue
|
|
639
|
+
|
|
640
|
+
src = str(u) + "-" + str(node_version[u])
|
|
641
|
+
visited.add(u)
|
|
642
|
+
new_nodes.add(src)
|
|
643
|
+
|
|
644
|
+
if v not in visited:
|
|
645
|
+
dst = str(v) + "-" + str(node_version[v])
|
|
646
|
+
visited.add(v)
|
|
647
|
+
new_nodes.add(dst)
|
|
648
|
+
new_edges.append((src, dst, {"time": int(t)}))
|
|
649
|
+
else:
|
|
650
|
+
dst_current = str(v) + "-" + str(node_version[v])
|
|
651
|
+
dst_new = str(v) + "-" + str(node_version[v] + 1)
|
|
652
|
+
node_version[v] += 1
|
|
653
|
+
new_nodes.add(dst_new)
|
|
654
|
+
new_edges.append((src, dst_new, {"time": int(t)}))
|
|
655
|
+
new_edges.append((dst_current, dst_new, {"time": int(t)}))
|
|
656
|
+
|
|
657
|
+
DAG = nx.DiGraph()
|
|
658
|
+
DAG.add_nodes_from(list(new_nodes))
|
|
659
|
+
DAG.add_edges_from(new_edges)
|
|
660
|
+
|
|
661
|
+
return DAG, node_version
|
|
662
|
+
|
|
663
|
+
|
|
664
|
+
def log_dataset_stats(datasets):
|
|
665
|
+
"""Logs the number of graphs, and of edges and nodes per graph, of each split."""
|
|
666
|
+
|
|
667
|
+
def row(label, dataset):
|
|
668
|
+
if len(dataset) == 0:
|
|
669
|
+
return [label, 0, "-", "-"]
|
|
670
|
+
edges = torch.tensor([d.src.shape[0] for d in dataset], dtype=torch.float)
|
|
671
|
+
nodes = torch.tensor(
|
|
672
|
+
[torch.unique(d.edge_index).shape[0] for d in dataset], dtype=torch.float
|
|
673
|
+
)
|
|
674
|
+
|
|
675
|
+
def fmt(t):
|
|
676
|
+
return f"{int(t.mean())} [{int(t.min())}, {int(t.max())}]"
|
|
677
|
+
|
|
678
|
+
return [label, len(dataset), fmt(edges), fmt(nodes)]
|
|
679
|
+
|
|
680
|
+
train_data, val_data, test_data = datasets
|
|
681
|
+
multi = max(len(train_data), len(test_data)) > 1
|
|
682
|
+
rows = []
|
|
683
|
+
for i, (train_graphs, val_graphs) in enumerate(zip(train_data, val_data)):
|
|
684
|
+
suffix = f" {i}" if multi else ""
|
|
685
|
+
rows += [row(f"train{suffix}", train_graphs), row(f"val{suffix}", val_graphs)]
|
|
686
|
+
for i, test_graphs in enumerate(test_data):
|
|
687
|
+
rows.append(row(f"test{f' {i}' if multi else ''}", test_graphs))
|
|
688
|
+
console.table(["split", "graphs", "edges/graph [min, max]", "nodes/graph [min, max]"], rows)
|
|
689
|
+
|
|
690
|
+
|
|
691
|
+
def set_seed(cfg, seed=None):
|
|
692
|
+
seed = seed or cfg.training.seed
|
|
693
|
+
random.seed(seed)
|
|
694
|
+
np.random.seed(seed)
|
|
695
|
+
|
|
696
|
+
torch.manual_seed(seed)
|
|
697
|
+
torch.cuda.manual_seed_all(seed)
|
|
698
|
+
torch.backends.cudnn.deterministic = True
|
|
699
|
+
torch.backends.cudnn.benchmark = False
|
|
700
|
+
|
|
701
|
+
if cfg.training.deterministic:
|
|
702
|
+
# Needs CUBLAS_WORKSPACE_CONFIG=:4096:8 on CUDA, set by the `pidsmaker` command (cli.py)
|
|
703
|
+
torch.use_deterministic_algorithms(True, warn_only=True)
|
|
704
|
+
|
|
705
|
+
|
|
706
|
+
def get_multi_datasets(cfg):
|
|
707
|
+
# The main dataset should be always the first one
|
|
708
|
+
multi_dataset = cfg.construction.multi_dataset
|
|
709
|
+
multi_datasets = list(
|
|
710
|
+
map(lambda x: x.strip(), multi_dataset.split("," if "," in multi_dataset else "-"))
|
|
711
|
+
)
|
|
712
|
+
return [cfg.dataset.name] + [d for d in multi_datasets if d != cfg.dataset.name]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Embedding visualization generation package."""
|