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
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Edge embedding autoencoder of LARES (Bilot et al., ACSAC 2026).
|
|
2
|
+
|
|
3
|
+
Each edge gets an embedding computed from the embeddings of its endpoints and, through a gated
|
|
4
|
+
skip connection, from its own features:
|
|
5
|
+
|
|
6
|
+
g = sigmoid(Lin([h_src, h_dst, e]))
|
|
7
|
+
z = MLP([h_src, h_dst, g * e])
|
|
8
|
+
|
|
9
|
+
and an autoencoder (out -> out/2 -> out, with a sigmoid output) reconstructs z. The model is
|
|
10
|
+
trained to minimize the mean squared reconstruction error, and edges are scored by the sum of
|
|
11
|
+
their squared errors: edges whose embedding is unusual are badly reconstructed.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import torch
|
|
15
|
+
import torch.nn as nn
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class EdgeEmbAutoencoder(nn.Module):
|
|
19
|
+
def __init__(self, node_dim, hid_dim, edge_dim=0, use_edge_feats=True):
|
|
20
|
+
super().__init__()
|
|
21
|
+
self.edge_dim = edge_dim if use_edge_feats else 0
|
|
22
|
+
in_dim = 2 * node_dim + self.edge_dim
|
|
23
|
+
self.edge_mlp = nn.Sequential(
|
|
24
|
+
nn.Linear(in_dim, hid_dim), nn.ReLU(), nn.Linear(hid_dim, node_dim)
|
|
25
|
+
)
|
|
26
|
+
self.gate = (
|
|
27
|
+
nn.Sequential(nn.Linear(in_dim, self.edge_dim), nn.Sigmoid()) if self.edge_dim else None
|
|
28
|
+
)
|
|
29
|
+
self.autoencoder = nn.Sequential(
|
|
30
|
+
nn.Linear(node_dim, max(1, node_dim // 2)),
|
|
31
|
+
nn.ReLU(),
|
|
32
|
+
nn.Linear(max(1, node_dim // 2), node_dim),
|
|
33
|
+
nn.Sigmoid(),
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
def forward(self, h_src, h_dst, inference, batch=None, **kwargs):
|
|
37
|
+
x = torch.cat([h_src, h_dst], dim=-1)
|
|
38
|
+
if self.gate is not None:
|
|
39
|
+
e = batch.edge_feats
|
|
40
|
+
x = torch.cat([x, self.gate(torch.cat([x, e], dim=-1)) * e], dim=-1)
|
|
41
|
+
z = self.edge_mlp(x)
|
|
42
|
+
err = (self.autoencoder(z) - z) ** 2
|
|
43
|
+
return {"loss": err.sum(dim=-1) if inference else err.mean()}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""Deep Graph Infomax on edge embeddings, with PCA anomaly scores, as in Anomal-E.
|
|
2
|
+
|
|
3
|
+
Anomal-E (Caville et al., Knowledge-Based Systems 2022): "Anomal-E: A self-supervised network
|
|
4
|
+
intrusion detection system based on graph neural networks". The encoder (E-GraphSAGE) is trained
|
|
5
|
+
with Deep Graph Infomax (DGI): the embeddings of the edges of a graph, z_e = [h_src || h_dst],
|
|
6
|
+
should agree with the summary of the graph s = sigmoid(mean(z_e)), whereas the embeddings of a
|
|
7
|
+
corrupted graph (whose edge features are shuffled) should not. A bilinear discriminator
|
|
8
|
+
D(z, s) = z^T W s is trained with binary cross-entropy.
|
|
9
|
+
|
|
10
|
+
Edges are then scored by an unsupervised anomaly detector fitted on the embeddings of benign
|
|
11
|
+
training edges. Here, the detector is a PCA: its mean and covariance are accumulated over the
|
|
12
|
+
training edges of the last epoch, and the score of an edge is the reconstruction error of its
|
|
13
|
+
embedding from the top principal components.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import torch
|
|
17
|
+
import torch.nn as nn
|
|
18
|
+
import torch.nn.functional as F
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def corrupt_batch(batch):
|
|
22
|
+
"""Copy of a batch whose node features and edge features are shuffled (DGI corruption)."""
|
|
23
|
+
corrupted = batch.clone()
|
|
24
|
+
if getattr(corrupted, "edge_feats", None) is not None:
|
|
25
|
+
perm = torch.randperm(corrupted.edge_feats.shape[0], device=corrupted.edge_feats.device)
|
|
26
|
+
corrupted.edge_feats = corrupted.edge_feats[perm]
|
|
27
|
+
if getattr(corrupted, "x", None) is not None and isinstance(corrupted.x, torch.Tensor):
|
|
28
|
+
perm = torch.randperm(corrupted.x.shape[0], device=corrupted.x.device)
|
|
29
|
+
corrupted.x = corrupted.x[perm]
|
|
30
|
+
return corrupted
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class DeepGraphInfomax(nn.Module):
|
|
34
|
+
needs_corrupted_embeddings = True
|
|
35
|
+
|
|
36
|
+
def __init__(self, embed_dim, pca_components):
|
|
37
|
+
super().__init__()
|
|
38
|
+
edge_dim = 2 * embed_dim
|
|
39
|
+
self.discriminator = nn.Bilinear(edge_dim, edge_dim, 1)
|
|
40
|
+
self.pca_components = pca_components
|
|
41
|
+
self.register_buffer("count", torch.zeros(()))
|
|
42
|
+
self.register_buffer("sum", torch.zeros(edge_dim))
|
|
43
|
+
self.register_buffer("outer", torch.zeros(edge_dim, edge_dim))
|
|
44
|
+
self._pca = None
|
|
45
|
+
|
|
46
|
+
def reset_state(self):
|
|
47
|
+
"""Called before each training epoch: the PCA is fitted on the last epoch only."""
|
|
48
|
+
self.count.zero_()
|
|
49
|
+
self.sum.zero_()
|
|
50
|
+
self.outer.zero_()
|
|
51
|
+
self._pca = None
|
|
52
|
+
|
|
53
|
+
def _discriminate(self, z, summary):
|
|
54
|
+
# Bilinear score z^T W s + b with the same summary s for all edges, computed as
|
|
55
|
+
# z @ (W s) + b: `nn.Bilinear` on the expanded summary materializes an (E, d, d) tensor
|
|
56
|
+
# in its backward pass (tens of GB on graphs with ~10^5 edges)
|
|
57
|
+
ws = self.discriminator.weight[0] @ summary.reshape(-1)
|
|
58
|
+
return z @ ws + self.discriminator.bias
|
|
59
|
+
|
|
60
|
+
def _fit_pca(self):
|
|
61
|
+
mean = self.sum / self.count.clamp(min=1)
|
|
62
|
+
cov = self.outer / self.count.clamp(min=1) - torch.outer(mean, mean)
|
|
63
|
+
_, eigvecs = torch.linalg.eigh(cov) # ascending eigenvalues
|
|
64
|
+
components = eigvecs[:, -self.pca_components :]
|
|
65
|
+
self._pca = (mean, components)
|
|
66
|
+
|
|
67
|
+
def forward(self, h_src, h_dst, inference, h_src_corrupted=None, h_dst_corrupted=None, **kwargs):
|
|
68
|
+
z = torch.cat([h_src, h_dst], dim=-1)
|
|
69
|
+
|
|
70
|
+
if inference:
|
|
71
|
+
if self._pca is None:
|
|
72
|
+
if self.count == 0:
|
|
73
|
+
raise RuntimeError("Deep Graph Infomax: the PCA has no training edge to fit on.")
|
|
74
|
+
self._fit_pca()
|
|
75
|
+
mean, components = self._pca
|
|
76
|
+
centered = z - mean
|
|
77
|
+
recon = centered @ components @ components.T
|
|
78
|
+
return {"loss": ((centered - recon) ** 2).sum(dim=-1)}
|
|
79
|
+
|
|
80
|
+
# Embeddings of benign training edges used to fit the PCA
|
|
81
|
+
z_detached = z.detach()
|
|
82
|
+
self.count += z_detached.shape[0]
|
|
83
|
+
self.sum += z_detached.sum(dim=0)
|
|
84
|
+
self.outer += z_detached.T @ z_detached
|
|
85
|
+
self._pca = None
|
|
86
|
+
|
|
87
|
+
summary = torch.sigmoid(z.mean(dim=0, keepdim=True))
|
|
88
|
+
pos = self._discriminate(z, summary)
|
|
89
|
+
z_corrupted = torch.cat([h_src_corrupted, h_dst_corrupted], dim=-1)
|
|
90
|
+
neg = self._discriminate(z_corrupted, summary)
|
|
91
|
+
loss = F.binary_cross_entropy_with_logits(
|
|
92
|
+
pos, torch.ones_like(pos)
|
|
93
|
+
) + F.binary_cross_entropy_with_logits(neg, torch.zeros_like(neg))
|
|
94
|
+
return {"loss": loss}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
import torch.nn as nn
|
|
3
|
+
import torch.nn.functional as F
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class FewShotEdgeDetection(nn.Module):
|
|
7
|
+
def __init__(self, decoder, loss_fn):
|
|
8
|
+
super(FewShotEdgeDetection, self).__init__()
|
|
9
|
+
self.decoder = decoder
|
|
10
|
+
self.loss_fn = loss_fn
|
|
11
|
+
|
|
12
|
+
def forward(self, h_src, h_dst, y_edge, inference, **kwargs):
|
|
13
|
+
y_edge_hat = self.decoder(h_src=h_src, h_dst=h_dst)
|
|
14
|
+
|
|
15
|
+
if inference:
|
|
16
|
+
# To get an anomaly score instead of a loss, we get the complement of the softmax normalized score
|
|
17
|
+
return {"loss": 1 - F.softmax(y_edge_hat, dim=1)[torch.arange(y_edge.shape[0]), y_edge]}
|
|
18
|
+
|
|
19
|
+
return {
|
|
20
|
+
"loss": self.loss_fn(y_edge_hat, y_edge, inference=inference)
|
|
21
|
+
} # weight=torch.tensor([1.0, 20000.0]).to(h_src.device))
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Per-node-type Deep-SVDD hypersphere"""
|
|
2
|
+
|
|
3
|
+
import torch
|
|
4
|
+
import torch.nn as nn
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class OneClass(nn.Module):
|
|
8
|
+
def __init__(self, decoder, embed_dim, beta=0.5, eps=1e-3, warmup=2, num_node_types=1):
|
|
9
|
+
super().__init__()
|
|
10
|
+
self.decoder = decoder
|
|
11
|
+
self.beta = beta
|
|
12
|
+
self.eps = eps
|
|
13
|
+
del warmup # unused, matches OCRGCNBase's own dead arg
|
|
14
|
+
self.num_node_types = num_node_types
|
|
15
|
+
self.register_buffer("c", torch.zeros(num_node_types, embed_dim))
|
|
16
|
+
self.register_buffer("r", torch.zeros(num_node_types))
|
|
17
|
+
self._frozen = set()
|
|
18
|
+
|
|
19
|
+
def freeze_type(self, t):
|
|
20
|
+
self._frozen.add(t)
|
|
21
|
+
|
|
22
|
+
def _node_type_idx(self, h, batch):
|
|
23
|
+
node_type_argmax = getattr(batch, "node_type_argmax", None) if batch is not None else None
|
|
24
|
+
if node_type_argmax is None:
|
|
25
|
+
if self.num_node_types > 1:
|
|
26
|
+
raise ValueError(
|
|
27
|
+
"OneClass needs `node_type_argmax` on the batch when num_node_types > 1, "
|
|
28
|
+
"otherwise every node silently shares a single hypersphere."
|
|
29
|
+
)
|
|
30
|
+
return torch.zeros(h.size(0), dtype=torch.long, device=h.device)
|
|
31
|
+
return node_type_argmax
|
|
32
|
+
|
|
33
|
+
def forward(self, h, inference, batch=None, **kwargs):
|
|
34
|
+
h = self.decoder(h)
|
|
35
|
+
node_type_idx = self._node_type_idx(h, batch)
|
|
36
|
+
|
|
37
|
+
if not inference:
|
|
38
|
+
with torch.no_grad():
|
|
39
|
+
for nt in range(self.num_node_types):
|
|
40
|
+
if nt in self._frozen:
|
|
41
|
+
continue
|
|
42
|
+
mask = node_type_idx == nt
|
|
43
|
+
if not mask.any():
|
|
44
|
+
continue
|
|
45
|
+
c = h[mask].mean(0)
|
|
46
|
+
c[(c.abs() < self.eps) & (c < 0)] = -self.eps
|
|
47
|
+
c[(c.abs() < self.eps) & (c > 0)] = self.eps
|
|
48
|
+
self.c[nt] = c
|
|
49
|
+
|
|
50
|
+
c_batch = self.c[node_type_idx]
|
|
51
|
+
r_batch = self.r[node_type_idx]
|
|
52
|
+
dist = torch.sum((h - c_batch) ** 2, dim=1)
|
|
53
|
+
score = dist - r_batch ** 2
|
|
54
|
+
|
|
55
|
+
if inference:
|
|
56
|
+
return {"loss": score}
|
|
57
|
+
|
|
58
|
+
if self._frozen:
|
|
59
|
+
frozen_types = torch.tensor(sorted(self._frozen), device=h.device)
|
|
60
|
+
active = ~torch.isin(node_type_idx, frozen_types)
|
|
61
|
+
else:
|
|
62
|
+
active = torch.ones_like(node_type_idx, dtype=torch.bool)
|
|
63
|
+
loss = torch.mean(r_batch[active] ** 2 + (1.0 / self.beta) * torch.relu(score[active]))
|
|
64
|
+
|
|
65
|
+
with torch.no_grad():
|
|
66
|
+
for nt in range(self.num_node_types):
|
|
67
|
+
if nt in self._frozen:
|
|
68
|
+
continue
|
|
69
|
+
mask = node_type_idx == nt
|
|
70
|
+
if not mask.any():
|
|
71
|
+
continue
|
|
72
|
+
d_nt = dist[mask].detach()
|
|
73
|
+
self.r[nt].copy_(torch.quantile(torch.sqrt(d_nt), 1 - self.beta))
|
|
74
|
+
|
|
75
|
+
return {"loss": loss}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import torch
|
|
3
|
+
import torch.nn as nn
|
|
4
|
+
from sklearn.metrics import average_precision_score, roc_auc_score
|
|
5
|
+
|
|
6
|
+
NEG_SAMPLING_METHODS = ["shuffle_dst", "uniform", "uniform_dst", "tgn"]
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class EdgeContrastivePrediction(nn.Module):
|
|
10
|
+
"""Link prediction: edges of the graph (positives) are contrasted with random negative edges.
|
|
11
|
+
|
|
12
|
+
Negative sampling (`neg_sampling`):
|
|
13
|
+
- `shuffle_dst`: each source is paired with the destination of another edge, so negatives
|
|
14
|
+
keep the degree distribution of destinations. On graphs where most edges go to a few
|
|
15
|
+
hubs (e.g. authentications to domain controllers in LANL), negatives never contain
|
|
16
|
+
edges to other nodes, which the model then learns to consider likely.
|
|
17
|
+
- `uniform`: sources and destinations are drawn uniformly among the nodes embedded by the
|
|
18
|
+
encoder (all the nodes of the dataset when the encoder embeds them all, see
|
|
19
|
+
`node_id_embedding.all_nodes`), `neg_ratio` negatives per positive, as in Euler and Argus.
|
|
20
|
+
- `uniform_dst`: the source of each positive edge is paired with destinations drawn uniformly
|
|
21
|
+
among the embedded nodes (`neg_ratio` per positive).
|
|
22
|
+
- `tgn`: the source of each edge is paired with a destination drawn uniformly among the
|
|
23
|
+
destinations of the dataset and embedded by the TGN with the edges of the batch, as in TGN
|
|
24
|
+
and Jbeil (requires `tgn_last_neighbor.negative_destinations`).
|
|
25
|
+
|
|
26
|
+
Each negative edge is paired with a positive edge (that of its source, except with `uniform`),
|
|
27
|
+
which pairwise losses such as `bpr` (ShadeWatcher) compare it to.
|
|
28
|
+
|
|
29
|
+
At validation, the AUC and AP of validation edges against uniform negatives measure how well
|
|
30
|
+
the model predicts links (`get_val_score`, used by `best_model_selection: best_val_score`).
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
def __init__(self, decoder, loss_fn, graph_reindexer, neg_sampling="shuffle_dst", neg_ratio=1.0):
|
|
34
|
+
super().__init__()
|
|
35
|
+
|
|
36
|
+
if neg_sampling not in NEG_SAMPLING_METHODS:
|
|
37
|
+
raise ValueError(f"Invalid neg_sampling {neg_sampling}, expected one of {NEG_SAMPLING_METHODS}")
|
|
38
|
+
self.decoder = decoder
|
|
39
|
+
self.loss_fn = loss_fn
|
|
40
|
+
self.graph_reindexer = graph_reindexer
|
|
41
|
+
self.neg_sampling = neg_sampling
|
|
42
|
+
self.neg_ratio = neg_ratio
|
|
43
|
+
self._val_pos, self._val_neg = [], []
|
|
44
|
+
|
|
45
|
+
def _node_tables(self, edge_index, h, h_src, h_dst):
|
|
46
|
+
"""Node embedding tables (src, dst) indexed by `edge_index`."""
|
|
47
|
+
if isinstance(h, torch.Tensor) and h.dim() == 2 and int(edge_index.max()) < h.size(0):
|
|
48
|
+
return h, h, edge_index
|
|
49
|
+
(h_src, h_dst), edge_index, _ = self.graph_reindexer._reindex_graph(
|
|
50
|
+
edge_index, h_src, h_dst, x_is_tuple=True
|
|
51
|
+
)
|
|
52
|
+
return h_src, h_dst, edge_index
|
|
53
|
+
|
|
54
|
+
def _uniform_negative_sampling(
|
|
55
|
+
self, edge_index, h, h_src, h_dst, ratio, keep_src=False, return_pos_index=False
|
|
56
|
+
):
|
|
57
|
+
table_src, table_dst, edge_index = self._node_tables(edge_index, h, h_src, h_dst)
|
|
58
|
+
num_nodes = table_src.size(0)
|
|
59
|
+
num_neg = max(1, int(round(edge_index.size(1) * ratio)))
|
|
60
|
+
if keep_src:
|
|
61
|
+
idx = torch.arange(num_neg, device=edge_index.device) % edge_index.size(1)
|
|
62
|
+
src = edge_index[0, idx].long()
|
|
63
|
+
else:
|
|
64
|
+
src = torch.randint(0, num_nodes, (num_neg,), device=edge_index.device)
|
|
65
|
+
dst = torch.randint(0, num_nodes, (num_neg,), device=edge_index.device)
|
|
66
|
+
pos_hash = edge_index[0].long() * num_nodes + edge_index[1].long()
|
|
67
|
+
keep = (src != dst) & ~torch.isin(src * num_nodes + dst, pos_hash)
|
|
68
|
+
if not keep.any(): # e.g. tiny graphs: keep the drawn edges rather than no negative
|
|
69
|
+
keep = torch.ones_like(keep)
|
|
70
|
+
neg_h_src, neg_h_dst = table_src[src[keep]], table_dst[dst[keep]]
|
|
71
|
+
if not return_pos_index:
|
|
72
|
+
return neg_h_src, neg_h_dst
|
|
73
|
+
# Positive edge paired with each negative (that of its source with `keep_src`)
|
|
74
|
+
pos_index = torch.arange(num_neg, device=edge_index.device) % edge_index.size(1)
|
|
75
|
+
return neg_h_src, neg_h_dst, pos_index[keep]
|
|
76
|
+
|
|
77
|
+
def _fast_negative_sampling(self, edge_index, h_src, h_dst, aug_coef=1.0, return_pos_index=False):
|
|
78
|
+
(h_src, h_dst), edge_index, _ = self.graph_reindexer._reindex_graph(
|
|
79
|
+
edge_index, h_src, h_dst, x_is_tuple=True
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
neg_dst_idx = torch.randperm(
|
|
83
|
+
len(edge_index[0])
|
|
84
|
+
) # TODO: we may want to try also putting source nodes in the neg dst nodes
|
|
85
|
+
neg_dst = edge_index[1, neg_dst_idx]
|
|
86
|
+
neg_ei = torch.stack([edge_index[0], neg_dst])
|
|
87
|
+
|
|
88
|
+
num_nodes = (edge_index.max() + 1).item()
|
|
89
|
+
el_hash = lambda x: x[0, :] + x[1, :] * num_nodes
|
|
90
|
+
el1d = el_hash(edge_index)
|
|
91
|
+
|
|
92
|
+
# Positive edge paired with each negative (that of its source)
|
|
93
|
+
pos_index = torch.arange(neg_ei.size(1), device=neg_ei.device)
|
|
94
|
+
no_loop = neg_ei[0] != neg_ei[1]
|
|
95
|
+
neg_ei, pos_index = neg_ei[:, no_loop], pos_index[no_loop] # remove self-loops
|
|
96
|
+
neg_hash = el_hash(neg_ei)
|
|
97
|
+
|
|
98
|
+
no_collision = ~torch.isin(neg_hash, el1d) # remove collision edges in positive edges
|
|
99
|
+
neg_samples, pos_index = neg_ei[:, no_collision], pos_index[no_collision]
|
|
100
|
+
|
|
101
|
+
neg_h_src = h_src[neg_samples[0]]
|
|
102
|
+
neg_h_dst = h_dst[neg_samples[1]]
|
|
103
|
+
|
|
104
|
+
if not return_pos_index:
|
|
105
|
+
return neg_h_src, neg_h_dst
|
|
106
|
+
return neg_h_src, neg_h_dst, pos_index
|
|
107
|
+
|
|
108
|
+
def forward(self, h_src, h_dst, edge_index, inference, h=None, validation=False, batch=None, **kwargs):
|
|
109
|
+
pos_scores = self.decoder(h_src=h_src, h_dst=h_dst)
|
|
110
|
+
h_neg = getattr(batch, "h_neg_tgn", None) if batch is not None else None
|
|
111
|
+
if self.neg_sampling == "tgn" and h_neg is None:
|
|
112
|
+
raise ValueError(
|
|
113
|
+
"neg_sampling=tgn requires the TGN negatives of "
|
|
114
|
+
"`batching.intra_graph_batching.tgn_last_neighbor.negative_destinations`."
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
# Positive edge paired with each negative edge (by default, the edge of the same index)
|
|
118
|
+
pos_index = None
|
|
119
|
+
if not inference:
|
|
120
|
+
if self.neg_sampling == "tgn":
|
|
121
|
+
neg_h_src, neg_h_dst = h_src, h_neg
|
|
122
|
+
elif self.neg_sampling in ("uniform", "uniform_dst"):
|
|
123
|
+
neg_h_src, neg_h_dst, pos_index = self._uniform_negative_sampling(
|
|
124
|
+
edge_index, h, h_src, h_dst, self.neg_ratio,
|
|
125
|
+
keep_src=self.neg_sampling == "uniform_dst",
|
|
126
|
+
return_pos_index=True,
|
|
127
|
+
)
|
|
128
|
+
else:
|
|
129
|
+
neg_h_src, neg_h_dst, pos_index = self._fast_negative_sampling(
|
|
130
|
+
edge_index, h_src, h_dst, return_pos_index=True
|
|
131
|
+
)
|
|
132
|
+
neg_scores = self.decoder(h_src=neg_h_src, h_dst=neg_h_dst)
|
|
133
|
+
else:
|
|
134
|
+
neg_scores = None
|
|
135
|
+
if validation:
|
|
136
|
+
# Link prediction quality: validation edges vs as many negatives
|
|
137
|
+
if self.neg_sampling == "tgn":
|
|
138
|
+
neg_h_src, neg_h_dst = h_src, h_neg
|
|
139
|
+
else:
|
|
140
|
+
neg_h_src, neg_h_dst = self._uniform_negative_sampling(edge_index, h, h_src, h_dst, 1.0)
|
|
141
|
+
self._val_pos.append(pos_scores.detach().reshape(-1).float().cpu())
|
|
142
|
+
self._val_neg.append(
|
|
143
|
+
self.decoder(h_src=neg_h_src, h_dst=neg_h_dst).detach().reshape(-1).float().cpu()
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
# class_weights = compute_class_weights(node_type, num_classes=self.node_type_dim) \
|
|
147
|
+
# if self.balanced_loss else None
|
|
148
|
+
|
|
149
|
+
pairing = {} if pos_index is None else {"pos_index": pos_index}
|
|
150
|
+
loss = self.loss_fn(pos_scores, neg_scores, inference=inference, **pairing)
|
|
151
|
+
if inference:
|
|
152
|
+
# One loss per edge, also for batches of a single edge (`squeeze` would return a scalar)
|
|
153
|
+
loss = loss.reshape(pos_scores.shape[0], -1)
|
|
154
|
+
return {"loss": loss.squeeze(1) if loss.shape[1] == 1 else loss}
|
|
155
|
+
return {"loss": loss.squeeze()}
|
|
156
|
+
|
|
157
|
+
def get_val_score(self):
|
|
158
|
+
"""AUC + AP of the validation edges against uniform negatives (reset after each call)."""
|
|
159
|
+
if not self._val_pos:
|
|
160
|
+
return 0.0
|
|
161
|
+
pos, neg = torch.cat(self._val_pos).numpy(), torch.cat(self._val_neg).numpy()
|
|
162
|
+
self._val_pos, self._val_neg = [], []
|
|
163
|
+
labels = np.r_[np.ones(len(pos)), np.zeros(len(neg))]
|
|
164
|
+
scores = np.r_[pos, neg]
|
|
165
|
+
return float(roc_auc_score(labels, scores) + average_precision_score(labels, scores))
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
import torch.nn as nn
|
|
3
|
+
import torch.nn.functional as F
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class PredictEdgeSupervised(nn.Module):
|
|
7
|
+
"""Binary supervised edge classification: benign (0) vs attack (1).
|
|
8
|
+
|
|
9
|
+
Input to the decoder per edge: [x_src | edge_type | x_dst | edge_type]
|
|
10
|
+
(edge_type one-hot appended to both node embeddings symmetrically).
|
|
11
|
+
|
|
12
|
+
Uses raw SPIDER node embeddings (batch.x_src, batch.x_dst) directly,
|
|
13
|
+
bypassing the GNN encoder, so that attack features extracted from val/test
|
|
14
|
+
graphs and benign features from training graphs share the same embedding
|
|
15
|
+
space.
|
|
16
|
+
|
|
17
|
+
During training, attack edges are oversampled 1:1 with replacement to match
|
|
18
|
+
the benign batch size. This counters the extreme class imbalance (typically
|
|
19
|
+
O(20) attacks vs O(millions) benign edges) without any modification to the
|
|
20
|
+
data loading pipeline.
|
|
21
|
+
|
|
22
|
+
At inference time, per-edge BCE losses are returned as anomaly scores.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
decoder: nn.Module,
|
|
28
|
+
atk_x_src: torch.Tensor,
|
|
29
|
+
atk_x_dst: torch.Tensor,
|
|
30
|
+
atk_edge_type: torch.Tensor,
|
|
31
|
+
pos_weight: float = 1.0,
|
|
32
|
+
):
|
|
33
|
+
super().__init__()
|
|
34
|
+
self.decoder = decoder
|
|
35
|
+
self.register_buffer("atk_x_src", atk_x_src)
|
|
36
|
+
self.register_buffer("atk_x_dst", atk_x_dst)
|
|
37
|
+
self.register_buffer("atk_edge_type", atk_edge_type)
|
|
38
|
+
self.pos_weight_val = pos_weight
|
|
39
|
+
|
|
40
|
+
@staticmethod
|
|
41
|
+
def _augment(x_src, x_dst, edge_type):
|
|
42
|
+
"""Append edge_type one-hot to both node embeddings."""
|
|
43
|
+
return (
|
|
44
|
+
torch.cat([x_src, edge_type], dim=-1),
|
|
45
|
+
torch.cat([x_dst, edge_type], dim=-1),
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
def forward(self, edge_type, inference: bool, batch, **kwargs):
|
|
49
|
+
x_src, x_dst = self._augment(batch.x_src, batch.x_dst, batch.edge_type)
|
|
50
|
+
device = x_src.device
|
|
51
|
+
|
|
52
|
+
if inference:
|
|
53
|
+
logits = self.decoder(h_src=x_src, h_dst=x_dst).squeeze(-1)
|
|
54
|
+
scores = F.binary_cross_entropy_with_logits(
|
|
55
|
+
logits, batch.y.float(), reduction="none"
|
|
56
|
+
)
|
|
57
|
+
return {"loss": scores}
|
|
58
|
+
|
|
59
|
+
# Training: oversample attack edges 1:1 with replacement
|
|
60
|
+
n = x_src.shape[0]
|
|
61
|
+
n_atk = self.atk_x_src.shape[0]
|
|
62
|
+
idx = torch.randint(0, n_atk, (n,), device=device)
|
|
63
|
+
atk_src, atk_dst = self._augment(
|
|
64
|
+
self.atk_x_src[idx], self.atk_x_dst[idx], self.atk_edge_type[idx]
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
all_src = torch.cat([x_src, atk_src], dim=0)
|
|
68
|
+
all_dst = torch.cat([x_dst, atk_dst], dim=0)
|
|
69
|
+
labels = torch.cat([
|
|
70
|
+
torch.zeros(n, device=device),
|
|
71
|
+
torch.ones(n, device=device),
|
|
72
|
+
])
|
|
73
|
+
|
|
74
|
+
logits = self.decoder(h_src=all_src, h_dst=all_dst).squeeze(-1)
|
|
75
|
+
pw = torch.tensor([self.pos_weight_val], device=device)
|
|
76
|
+
loss = F.binary_cross_entropy_with_logits(logits, labels, pos_weight=pw)
|
|
77
|
+
return {"loss": loss}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import torch.nn as nn
|
|
2
|
+
|
|
3
|
+
from pidsmaker.utils.utils import compute_class_weights
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class EdgeTypePrediction(nn.Module):
|
|
7
|
+
def __init__(self, decoder, loss_fn, balanced_loss, edge_type_dim, multi_edge):
|
|
8
|
+
super(EdgeTypePrediction, self).__init__()
|
|
9
|
+
self.decoder = decoder
|
|
10
|
+
self.loss_fn = loss_fn
|
|
11
|
+
self.balanced_loss = balanced_loss
|
|
12
|
+
self.edge_type_dim = edge_type_dim
|
|
13
|
+
self.multi_edge = multi_edge
|
|
14
|
+
|
|
15
|
+
def forward(self, h_src, h_dst, edge_type, inference, **kwargs):
|
|
16
|
+
h = self.decoder(h_src=h_src, h_dst=h_dst)
|
|
17
|
+
|
|
18
|
+
class_weights = (
|
|
19
|
+
compute_class_weights(edge_type, num_classes=self.edge_type_dim)
|
|
20
|
+
if self.balanced_loss
|
|
21
|
+
else None
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
if not self.multi_edge:
|
|
25
|
+
edge_type = edge_type.argmax(dim=1)
|
|
26
|
+
|
|
27
|
+
loss = self.loss_fn(h, edge_type, inference=inference, weight=class_weights)
|
|
28
|
+
return {"loss": loss}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
import torch.nn as nn
|
|
3
|
+
from torch_geometric.utils import negative_sampling
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class GMAEStructPrediction(nn.Module):
|
|
7
|
+
"""MAGIC's structure reconstruction: an MLP predicts whether node pairs are linked.
|
|
8
|
+
|
|
9
|
+
As in MAGIC, `min(max_samples, num_nodes)` existing edges are sampled uniformly as positives,
|
|
10
|
+
with as many uniform negative pairs. `max_samples=None` (or 0) uses all the edges.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
def __init__(self, decoder, loss_fn, max_samples=None):
|
|
14
|
+
super(GMAEStructPrediction, self).__init__()
|
|
15
|
+
self.edge_recon_fc = decoder
|
|
16
|
+
self.loss_fn = loss_fn
|
|
17
|
+
self.max_samples = max_samples
|
|
18
|
+
|
|
19
|
+
def sample_positive_edges(self, edge_index, num_nodes):
|
|
20
|
+
num_edges = edge_index.shape[1]
|
|
21
|
+
if not self.max_samples:
|
|
22
|
+
return edge_index
|
|
23
|
+
n = min(self.max_samples, num_nodes, num_edges)
|
|
24
|
+
if n == num_edges:
|
|
25
|
+
return edge_index
|
|
26
|
+
idx = torch.randperm(num_edges, device=edge_index.device)[:n]
|
|
27
|
+
return edge_index[:, idx]
|
|
28
|
+
|
|
29
|
+
def forward(self, h, edge_index, inference, **kwargs):
|
|
30
|
+
# The structure loss is a training signal only: it does not score nodes
|
|
31
|
+
if inference:
|
|
32
|
+
return {"loss": torch.zeros((h.shape[0],), device=h.device)}
|
|
33
|
+
|
|
34
|
+
pos_edge_index = self.sample_positive_edges(edge_index, h.shape[0])
|
|
35
|
+
neg_edge_index = negative_sampling(
|
|
36
|
+
edge_index, num_nodes=h.shape[0], num_neg_samples=pos_edge_index.shape[1]
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
pos_samples = torch.cat([h[pos_edge_index[0]], h[pos_edge_index[1]]], dim=-1)
|
|
40
|
+
neg_samples = torch.cat([h[neg_edge_index[0]], h[neg_edge_index[1]]], dim=-1)
|
|
41
|
+
|
|
42
|
+
y_pred_pos = self.edge_recon_fc(pos_samples).squeeze(-1)
|
|
43
|
+
y_pred_neg = self.edge_recon_fc(neg_samples).squeeze(-1)
|
|
44
|
+
|
|
45
|
+
y_true = torch.cat([torch.ones_like(y_pred_pos), torch.zeros_like(y_pred_neg)])
|
|
46
|
+
y_pred = torch.cat([y_pred_pos, y_pred_neg])
|
|
47
|
+
|
|
48
|
+
loss = self.loss_fn(y_pred, y_true, inference=inference)
|
|
49
|
+
return {"loss": loss}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import torch.nn as nn
|
|
2
|
+
import torch.nn.functional as F
|
|
3
|
+
|
|
4
|
+
from pidsmaker.utils.utils import compute_class_weights
|
|
5
|
+
|
|
6
|
+
# Attribute of a batch holding the boolean mask of the nodes that contribute to the training loss
|
|
7
|
+
NODE_LOSS_MASK_KEY = "node_loss_mask"
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class NodeTypePrediction(nn.Module):
|
|
11
|
+
def __init__(self, decoder, loss_fn, balanced_loss, node_type_dim):
|
|
12
|
+
super(NodeTypePrediction, self).__init__()
|
|
13
|
+
self.decoder = decoder
|
|
14
|
+
self.loss_fn = loss_fn
|
|
15
|
+
self.balanced_loss = balanced_loss
|
|
16
|
+
self.node_type_dim = node_type_dim
|
|
17
|
+
|
|
18
|
+
def forward(self, h, node_type, inference, batch=None, **kwargs):
|
|
19
|
+
h_hat = self.decoder(h)
|
|
20
|
+
|
|
21
|
+
# During training, the loss can be restricted to some nodes: those that ThreaTrace's
|
|
22
|
+
# previous submodels do not explain yet, or that FLASH still misclassifies
|
|
23
|
+
node_loss_mask = getattr(batch, NODE_LOSS_MASK_KEY, None) if not inference else None
|
|
24
|
+
h_loss, node_type_loss = h_hat, node_type
|
|
25
|
+
if node_loss_mask is not None:
|
|
26
|
+
h_loss, node_type_loss = h_hat[node_loss_mask], node_type[node_loss_mask]
|
|
27
|
+
|
|
28
|
+
class_weights = (
|
|
29
|
+
compute_class_weights(node_type_loss, num_classes=self.node_type_dim)
|
|
30
|
+
if self.balanced_loss
|
|
31
|
+
else None
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
node_type_classes = node_type_loss.argmax(dim=1)
|
|
35
|
+
loss = self.loss_fn(h_loss, node_type_classes, inference=inference, weight=class_weights)
|
|
36
|
+
return {"loss": loss, "out": F.log_softmax(h_hat, dim=1)}
|