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/mimicry.py
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
import csv
|
|
2
|
+
import os
|
|
3
|
+
import random
|
|
4
|
+
from collections import defaultdict
|
|
5
|
+
|
|
6
|
+
import networkx as nx
|
|
7
|
+
|
|
8
|
+
from pidsmaker.config import *
|
|
9
|
+
from pidsmaker.utils.dataset_utils import get_rel2id
|
|
10
|
+
from pidsmaker.utils.utils import *
|
|
11
|
+
from pidsmaker.utils.utils import datetime_to_ns_time_US
|
|
12
|
+
|
|
13
|
+
possible_structure = [
|
|
14
|
+
["EVENT_OPEN", "EVENT_READ"],
|
|
15
|
+
["EVENT_OPEN", "EVENT_WRITE"],
|
|
16
|
+
["EVENT_OPEN", "EVENT_READ", "EVENT_WRITE"],
|
|
17
|
+
["EVENT_OPEN", "EVENT_WRITE", "EVENT_READ"],
|
|
18
|
+
["EVENT_OPEN", "EVENT_READ", "EVENT_WRITE", "EVENT_READ", "EVENT_WRITE"],
|
|
19
|
+
["EVENT_OPEN", "EVENT_WRITE", "EVENT_READ", "EVENT_WRITE", "EVENT_READ"],
|
|
20
|
+
["EVENT_OPEN", "EVENT_READ", "EVENT_WRITE", "EVENT_WRITE", "EVENT_READ"],
|
|
21
|
+
["EVENT_OPEN", "EVENT_WRITE", "EVENT_READ", "EVENT_WRITE", "EVENT_WRITE"],
|
|
22
|
+
[
|
|
23
|
+
"EVENT_OPEN",
|
|
24
|
+
"EVENT_READ",
|
|
25
|
+
"EVENT_WRITE",
|
|
26
|
+
"EVENT_READ",
|
|
27
|
+
"EVENT_WRITE",
|
|
28
|
+
"EVENT_WRITE",
|
|
29
|
+
"EVENT_WRITE",
|
|
30
|
+
],
|
|
31
|
+
[
|
|
32
|
+
"EVENT_OPEN",
|
|
33
|
+
"EVENT_WRITE",
|
|
34
|
+
"EVENT_READ",
|
|
35
|
+
"EVENT_READ",
|
|
36
|
+
"EVENT_READ",
|
|
37
|
+
"EVENT_WRITE",
|
|
38
|
+
"EVENT_READ",
|
|
39
|
+
],
|
|
40
|
+
[
|
|
41
|
+
"EVENT_OPEN",
|
|
42
|
+
"EVENT_READ",
|
|
43
|
+
"EVENT_READ",
|
|
44
|
+
"EVENT_READ",
|
|
45
|
+
"EVENT_WRITE",
|
|
46
|
+
"EVENT_WRITE",
|
|
47
|
+
"EVENT_READ",
|
|
48
|
+
],
|
|
49
|
+
[
|
|
50
|
+
"EVENT_OPEN",
|
|
51
|
+
"EVENT_WRITE",
|
|
52
|
+
"EVENT_WRITE",
|
|
53
|
+
"EVENT_WRITE",
|
|
54
|
+
"EVENT_READ",
|
|
55
|
+
"EVENT_WRITE",
|
|
56
|
+
"EVENT_WRITE",
|
|
57
|
+
],
|
|
58
|
+
["EVENT_OPEN", "EVENT_READ", "EVENT_READ", "EVENT_READ", "EVENT_READ"],
|
|
59
|
+
[
|
|
60
|
+
"EVENT_OPEN",
|
|
61
|
+
"EVENT_WRITE",
|
|
62
|
+
"EVENT_WRITE",
|
|
63
|
+
"EVENT_WRITE",
|
|
64
|
+
"EVENT_WRITE",
|
|
65
|
+
],
|
|
66
|
+
]
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def get_uuid2nids2type(cur):
|
|
70
|
+
queries = {
|
|
71
|
+
"file": "SELECT index_id, node_uuid FROM file_node_table;",
|
|
72
|
+
"netflow": "SELECT index_id, node_uuid FROM netflow_node_table;",
|
|
73
|
+
"subject": "SELECT index_id, node_uuid FROM subject_node_table;",
|
|
74
|
+
}
|
|
75
|
+
uuid2nids = {}
|
|
76
|
+
nid2uuid = {}
|
|
77
|
+
nid2type = {}
|
|
78
|
+
for node_type, query in queries.items():
|
|
79
|
+
cur.execute(query)
|
|
80
|
+
rows = cur.fetchall()
|
|
81
|
+
for row in rows:
|
|
82
|
+
uuid2nids[row[1]] = row[0]
|
|
83
|
+
nid2uuid[row[0]] = row[1]
|
|
84
|
+
nid2type[row[0]] = node_type
|
|
85
|
+
return uuid2nids, nid2uuid, nid2type
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def obtain_all_files(cur):
|
|
89
|
+
sql = "SELECT index_id, node_uuid FROM file_node_table;"
|
|
90
|
+
cur.execute(sql)
|
|
91
|
+
rows = cur.fetchall()
|
|
92
|
+
|
|
93
|
+
file_set = set()
|
|
94
|
+
for row in rows:
|
|
95
|
+
file_set.add(row[0])
|
|
96
|
+
return file_set
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def divide_integer(a, b):
|
|
100
|
+
base_size = a // b
|
|
101
|
+
remainder = a % b
|
|
102
|
+
result = [base_size + 1 if i < remainder else base_size for i in range(b)]
|
|
103
|
+
return result
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def random_timestamp(start_ns, end_ns):
|
|
107
|
+
if start_ns > end_ns:
|
|
108
|
+
start_ns, end_ns = end_ns, start_ns
|
|
109
|
+
return random.randint(start_ns, end_ns)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def save_mimicry_nodes(cfg, cur, nodes, attack):
|
|
113
|
+
os.makedirs(cfg.construction._mimicry_dir, exist_ok=True)
|
|
114
|
+
save_dir = os.path.join(cfg.construction._mimicry_dir, attack.split("/")[-1])
|
|
115
|
+
|
|
116
|
+
data = []
|
|
117
|
+
sql1 = "SELECT node_uuid, index_id, path FROM file_node_table;"
|
|
118
|
+
sql2 = "SELECT node_uuid, index_id, path, cmd FROM subject_node_table;"
|
|
119
|
+
|
|
120
|
+
cur.execute(sql1)
|
|
121
|
+
rows = cur.fetchall()
|
|
122
|
+
for row in rows:
|
|
123
|
+
node_uuid = row[0]
|
|
124
|
+
index_id = int(row[1])
|
|
125
|
+
path = row[2] if row[2] is not None else "None"
|
|
126
|
+
if index_id in nodes:
|
|
127
|
+
data.append((node_uuid, {"file": path}, index_id))
|
|
128
|
+
|
|
129
|
+
cur.execute(sql2)
|
|
130
|
+
rows = cur.fetchall()
|
|
131
|
+
for row in rows:
|
|
132
|
+
node_uuid = row[0]
|
|
133
|
+
index_id = int(row[1])
|
|
134
|
+
path = row[2] if row[2] is not None else "None"
|
|
135
|
+
cmd = row[3] if row[3] is not None else "None"
|
|
136
|
+
if index_id in nodes:
|
|
137
|
+
data.append((node_uuid, {"subject": path + " " + cmd}, index_id))
|
|
138
|
+
|
|
139
|
+
with open(save_dir, "w") as f:
|
|
140
|
+
csv_writer = csv.writer(f)
|
|
141
|
+
for line in data:
|
|
142
|
+
csv_writer.writerow(line)
|
|
143
|
+
|
|
144
|
+
log(f"{len(data)} mimicry nodes saved into {save_dir}.")
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def gen_mimicry_edges(cfg):
|
|
148
|
+
cur, connect = init_database_connection(cfg)
|
|
149
|
+
uuid2nids, nid2uuid, nid2type = get_uuid2nids2type(cur)
|
|
150
|
+
|
|
151
|
+
rel2id = get_rel2id(cfg)
|
|
152
|
+
|
|
153
|
+
mimicry_edge_num = cfg.construction.mimicry_edge_num
|
|
154
|
+
attack_num = len(cfg.dataset.ground_truth_relative_path)
|
|
155
|
+
num_each_att = divide_integer(mimicry_edge_num, attack_num)
|
|
156
|
+
|
|
157
|
+
attack_index = 0
|
|
158
|
+
attack_GPs = {}
|
|
159
|
+
attack_mimicry_events = {}
|
|
160
|
+
for attack_tuple in cfg.dataset.attack_to_time_window:
|
|
161
|
+
attack = attack_tuple[0]
|
|
162
|
+
start_time = datetime_to_ns_time_US(attack_tuple[1], timezone=cfg.dataset.timezone)
|
|
163
|
+
end_time = datetime_to_ns_time_US(attack_tuple[2], timezone=cfg.dataset.timezone)
|
|
164
|
+
|
|
165
|
+
# Obtain mimicry-connected nodes as new malicious nodes
|
|
166
|
+
mimicry_GPs = set()
|
|
167
|
+
|
|
168
|
+
# Find attack root and descendant process
|
|
169
|
+
ground_truth_nids = []
|
|
170
|
+
with open(os.path.join(cfg._ground_truth_dir, attack), "r") as f:
|
|
171
|
+
reader = csv.reader(f)
|
|
172
|
+
for row in reader:
|
|
173
|
+
node_uuid, node_labels, _ = row[0], row[1], row[2]
|
|
174
|
+
node_id = uuid2nids[node_uuid]
|
|
175
|
+
ground_truth_nids.append(int(node_id))
|
|
176
|
+
|
|
177
|
+
attack_GPs[attack] = set(ground_truth_nids)
|
|
178
|
+
|
|
179
|
+
# Create graph and obtain root nodes
|
|
180
|
+
rows = get_events_between_GPs(cur, start_time, end_time, ground_truth_nids)
|
|
181
|
+
|
|
182
|
+
edges = []
|
|
183
|
+
for row in rows:
|
|
184
|
+
src_id = row[1]
|
|
185
|
+
operation = row[2]
|
|
186
|
+
dst_id = row[4]
|
|
187
|
+
t = int(row[6])
|
|
188
|
+
if operation in rel2id:
|
|
189
|
+
edges.append((str(src_id), str(dst_id), int(t)))
|
|
190
|
+
|
|
191
|
+
dag_between_GPs, _ = generate_DAG(edges)
|
|
192
|
+
root_nodes = set(
|
|
193
|
+
[node for node, in_degree in dag_between_GPs.in_degree() if in_degree == 0]
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
# create graph and obtain all descendants
|
|
197
|
+
rows = get_events_between_time_range(cur, start_time, end_time)
|
|
198
|
+
edges = []
|
|
199
|
+
process2times = defaultdict(list)
|
|
200
|
+
for row in rows:
|
|
201
|
+
src_id = row[1]
|
|
202
|
+
operation = row[2]
|
|
203
|
+
dst_id = row[4]
|
|
204
|
+
t = int(row[6])
|
|
205
|
+
if operation in rel2id:
|
|
206
|
+
edges.append((str(src_id), str(dst_id), int(t)))
|
|
207
|
+
|
|
208
|
+
if nid2type[int(src_id)] == "subject":
|
|
209
|
+
process2times[src_id].append(t)
|
|
210
|
+
if nid2type[int(dst_id)] == "subject":
|
|
211
|
+
process2times[dst_id].append(t)
|
|
212
|
+
|
|
213
|
+
dag_of_attack, node_version = generate_DAG(edges)
|
|
214
|
+
|
|
215
|
+
all_descendants = set()
|
|
216
|
+
for root in root_nodes:
|
|
217
|
+
descendants = nx.descendants(dag_of_attack, root)
|
|
218
|
+
desc = set([v.split("-")[0] for v in descendants])
|
|
219
|
+
all_descendants |= desc
|
|
220
|
+
all_descendants |= set([v.split("-")[0] for v in root_nodes])
|
|
221
|
+
|
|
222
|
+
possible_process = set()
|
|
223
|
+
for nid in all_descendants:
|
|
224
|
+
if nid2type[int(nid)] == "subject":
|
|
225
|
+
possible_process.add(nid)
|
|
226
|
+
|
|
227
|
+
possible_file = obtain_all_files(cur)
|
|
228
|
+
|
|
229
|
+
possible_process = list(possible_process)
|
|
230
|
+
possible_file = list(possible_file)
|
|
231
|
+
|
|
232
|
+
# Generate mimicry events
|
|
233
|
+
mimicry_events = []
|
|
234
|
+
events_needed = num_each_att[attack_index]
|
|
235
|
+
while len(mimicry_events) < events_needed:
|
|
236
|
+
random_subject = random.choice(possible_process)
|
|
237
|
+
random_file = random.choice(possible_file)
|
|
238
|
+
random_time = random.choice(process2times[random_subject])
|
|
239
|
+
random_structure = random.choice(possible_structure)
|
|
240
|
+
|
|
241
|
+
mimicry_GPs.add(int(random_subject))
|
|
242
|
+
mimicry_GPs.add(int(random_file))
|
|
243
|
+
|
|
244
|
+
current_time = int(random_time)
|
|
245
|
+
|
|
246
|
+
for ope in random_structure:
|
|
247
|
+
time_bias = random.randint(0, int(3 * 1e9))
|
|
248
|
+
event_time = current_time + time_bias
|
|
249
|
+
current_time = event_time
|
|
250
|
+
event_uuid = stringtomd5(str(random_subject) + str(random_file) + str(current_time))
|
|
251
|
+
if ope == "EVENT_OPEN" or ope == "EVENT_WRITE":
|
|
252
|
+
event = (
|
|
253
|
+
nid2uuid[int(random_subject)],
|
|
254
|
+
str(random_subject),
|
|
255
|
+
ope,
|
|
256
|
+
nid2uuid[int(random_file)],
|
|
257
|
+
str(random_file),
|
|
258
|
+
event_uuid,
|
|
259
|
+
event_time,
|
|
260
|
+
0,
|
|
261
|
+
)
|
|
262
|
+
elif ope == "EVENT_READ":
|
|
263
|
+
event = (
|
|
264
|
+
nid2uuid[int(random_file)],
|
|
265
|
+
str(random_file),
|
|
266
|
+
ope,
|
|
267
|
+
nid2uuid[int(random_subject)],
|
|
268
|
+
str(random_subject),
|
|
269
|
+
event_uuid,
|
|
270
|
+
event_time,
|
|
271
|
+
0,
|
|
272
|
+
)
|
|
273
|
+
else:
|
|
274
|
+
log(f"Undefined event type {ope}")
|
|
275
|
+
|
|
276
|
+
mimicry_events.append(event)
|
|
277
|
+
|
|
278
|
+
save_mimicry_nodes(cfg, cur, mimicry_GPs, attack)
|
|
279
|
+
|
|
280
|
+
attack_mimicry_events[attack_index] = mimicry_events
|
|
281
|
+
log(f"For attack {attack_index}, {len(mimicry_events)} mimicry events are generated")
|
|
282
|
+
attack_index += 1
|
|
283
|
+
|
|
284
|
+
return attack_mimicry_events
|
pidsmaker/model.py
ADDED
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
"""PIDS Model combining encoder with multiple training objectives.
|
|
2
|
+
|
|
3
|
+
The Model class orchestrates encoder execution and applies multiple objectives
|
|
4
|
+
(reconstruction, prediction, contrastive learning) for joint training. Supports
|
|
5
|
+
few-shot learning mode and MC Dropout uncertainty quantification.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import copy
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
import torch
|
|
12
|
+
import torch.nn as nn
|
|
13
|
+
|
|
14
|
+
from pidsmaker.encoders import TGNEncoder
|
|
15
|
+
from pidsmaker.experiments.uncertainty import activate_dropout_inference
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Model(nn.Module):
|
|
19
|
+
"""Main PIDS model combining graph encoder with training objectives.
|
|
20
|
+
|
|
21
|
+
Attributes:
|
|
22
|
+
encoder: Neural network encoder (SAGE, GAT, TGN, etc.)
|
|
23
|
+
objectives: List of training objectives (reconstruction, prediction, etc.)
|
|
24
|
+
objective_few_shot: Few-shot detection objective (optional)
|
|
25
|
+
device: PyTorch device (cuda/cpu)
|
|
26
|
+
few_shot_mode: Whether currently in few-shot fine-tuning mode
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def __init__(
|
|
30
|
+
self,
|
|
31
|
+
encoder: nn.Module,
|
|
32
|
+
objectives: list[nn.Module],
|
|
33
|
+
objective_few_shot: nn.Module,
|
|
34
|
+
device,
|
|
35
|
+
is_running_mc_dropout,
|
|
36
|
+
use_few_shot,
|
|
37
|
+
freeze_encoder,
|
|
38
|
+
fuse_duplicate_edges_training,
|
|
39
|
+
is_hybrid_loss,
|
|
40
|
+
):
|
|
41
|
+
super(Model, self).__init__()
|
|
42
|
+
|
|
43
|
+
self.encoder = encoder
|
|
44
|
+
self.objectives = nn.ModuleList(objectives)
|
|
45
|
+
self.device = device
|
|
46
|
+
self.is_running_mc_dropout = is_running_mc_dropout
|
|
47
|
+
|
|
48
|
+
self.objective_few_shot = objective_few_shot
|
|
49
|
+
self.use_few_shot = use_few_shot
|
|
50
|
+
self.few_shot_mode = False
|
|
51
|
+
self.freeze_encoder = freeze_encoder
|
|
52
|
+
self.fuse_duplicate_edges_training = fuse_duplicate_edges_training
|
|
53
|
+
self.is_hybrid_loss = is_hybrid_loss
|
|
54
|
+
|
|
55
|
+
def embed(self, batch, inference=False, **kwargs):
|
|
56
|
+
"""Generate node embeddings for batch using encoder.
|
|
57
|
+
|
|
58
|
+
Args:
|
|
59
|
+
batch: Data batch with edge_index, node features, timestamps, etc.
|
|
60
|
+
inference: If True, run in inference mode (no gradients)
|
|
61
|
+
**kwargs: Additional arguments passed to encoder
|
|
62
|
+
|
|
63
|
+
Returns:
|
|
64
|
+
tuple: (h, h_src, h_dst) where:
|
|
65
|
+
- h: All node embeddings (N, d) or tuple of (src_nodes, dst_nodes)
|
|
66
|
+
- h_src: Source node embeddings for edges (E, d)
|
|
67
|
+
- h_dst: Destination node embeddings for edges (E, d)
|
|
68
|
+
"""
|
|
69
|
+
train_mode = not inference
|
|
70
|
+
edge_index = batch.edge_index
|
|
71
|
+
with torch.set_grad_enabled(train_mode):
|
|
72
|
+
res = self.encoder(
|
|
73
|
+
edge_index=edge_index,
|
|
74
|
+
t=batch.t,
|
|
75
|
+
x_src=getattr(batch, "x_src", None),
|
|
76
|
+
x_dst=getattr(batch, "x_dst", None),
|
|
77
|
+
msg=getattr(batch, "msg", None),
|
|
78
|
+
edge_feats=getattr(batch, "edge_feats", None),
|
|
79
|
+
inference=inference,
|
|
80
|
+
edge_types=batch.edge_type,
|
|
81
|
+
node_type_src=getattr(batch, "node_type_src", None),
|
|
82
|
+
node_type_dst=getattr(batch, "node_type_dst", None),
|
|
83
|
+
batch=batch,
|
|
84
|
+
# Reindexing attr
|
|
85
|
+
x=getattr(batch, "x", None),
|
|
86
|
+
original_n_id=getattr(batch, "original_n_id", None),
|
|
87
|
+
node_type=getattr(batch, "node_type", None),
|
|
88
|
+
node_type_argmax=getattr(batch, "node_type_argmax", None),
|
|
89
|
+
# Hetero attr
|
|
90
|
+
edge_index_dict=getattr(batch, "edge_index_dict", None),
|
|
91
|
+
x_dict=getattr(batch, "x_dict", None),
|
|
92
|
+
)
|
|
93
|
+
h, h_src, h_dst = self.gather_h(batch, res)
|
|
94
|
+
# Edges in the node space of `h` (the batch's edges, unless the encoder embeds other
|
|
95
|
+
# nodes, e.g. all the nodes of the dataset, see `NodeIdEmbedding`)
|
|
96
|
+
self._h_edge_index = res.get("edge_index", batch.edge_index) if isinstance(res, dict) else batch.edge_index
|
|
97
|
+
# Loss of the encoder's own parameters (e.g. TransR of ShadeWatcher), added to the loss
|
|
98
|
+
# of the objectives during training
|
|
99
|
+
self._encoder_aux_loss = res.get("aux_loss") if isinstance(res, dict) else None
|
|
100
|
+
return h, h_src, h_dst
|
|
101
|
+
|
|
102
|
+
def _embed_nodes(self, batch, inference):
|
|
103
|
+
"""Runs the encoder, optionally applying input masking for reconstruction objectives."""
|
|
104
|
+
train_mode = not inference
|
|
105
|
+
mask_nodes = None
|
|
106
|
+
x_for_encoding = getattr(batch, "x", None)
|
|
107
|
+
|
|
108
|
+
if train_mode and x_for_encoding is not None:
|
|
109
|
+
# Check if we have a GMAEFeatReconstruction objective
|
|
110
|
+
for objective in self.objectives:
|
|
111
|
+
# ValidationWrapper hides the underlying objective's methods (like mask_input).
|
|
112
|
+
# We need to access the inner objective to find and call mask_input if it exists.
|
|
113
|
+
# TODO: make ValidationWrapper transparently proxy method calls or use a more generic unwrapping approach.
|
|
114
|
+
actual_objective = objective
|
|
115
|
+
if hasattr(objective, "objective"):
|
|
116
|
+
actual_objective = objective.objective
|
|
117
|
+
|
|
118
|
+
if hasattr(actual_objective, "mask_input"):
|
|
119
|
+
x_for_encoding, mask_nodes = actual_objective.mask_input(x_for_encoding)
|
|
120
|
+
break # Only mask once
|
|
121
|
+
|
|
122
|
+
with torch.set_grad_enabled(train_mode):
|
|
123
|
+
# Pass masked input to encoder if masking was applied
|
|
124
|
+
if mask_nodes is not None and hasattr(batch, "x") and x_for_encoding is not None:
|
|
125
|
+
# Temporarily replace batch.x with masked version
|
|
126
|
+
original_x = batch.x
|
|
127
|
+
batch.x = x_for_encoding
|
|
128
|
+
h, h_src, h_dst = self.embed(batch, inference=inference)
|
|
129
|
+
batch.x = original_x # Restore original for objectives
|
|
130
|
+
else:
|
|
131
|
+
h, h_src, h_dst = self.embed(batch, inference=inference)
|
|
132
|
+
|
|
133
|
+
return h, h_src, h_dst, mask_nodes
|
|
134
|
+
|
|
135
|
+
def forward(self, batch, inference=False, validation=False):
|
|
136
|
+
"""Forward pass: embed nodes and compute loss/scores across all objectives.
|
|
137
|
+
|
|
138
|
+
Args:
|
|
139
|
+
batch: Data batch with graph structure and features
|
|
140
|
+
inference: If True, return anomaly scores; if False, return training loss
|
|
141
|
+
validation: If True, compute validation metrics
|
|
142
|
+
|
|
143
|
+
Returns:
|
|
144
|
+
dict: Contains 'loss' key with:
|
|
145
|
+
- Training mode: scalar loss (sum of all objective losses)
|
|
146
|
+
- Inference mode: per-edge anomaly scores (E,)
|
|
147
|
+
"""
|
|
148
|
+
h, h_src, h_dst, mask_nodes = self._embed_nodes(batch, inference)
|
|
149
|
+
h_edge_index = self._h_edge_index
|
|
150
|
+
encoder_aux_loss = self._encoder_aux_loss
|
|
151
|
+
train_mode = not inference
|
|
152
|
+
|
|
153
|
+
# Objectives contrasting the graph with a corrupted version of it (e.g. Deep Graph
|
|
154
|
+
# Infomax) receive the embeddings of the corrupted graph during training
|
|
155
|
+
corrupted = {}
|
|
156
|
+
if train_mode and any(
|
|
157
|
+
getattr(self._unwrap(o), "needs_corrupted_embeddings", False) for o in self.objectives
|
|
158
|
+
):
|
|
159
|
+
from pidsmaker.objectives.deep_graph_infomax import corrupt_batch
|
|
160
|
+
|
|
161
|
+
_, h_src_c, h_dst_c = self.embed(corrupt_batch(batch), inference=False)
|
|
162
|
+
corrupted = {"h_src_corrupted": h_src_c, "h_dst_corrupted": h_dst_c}
|
|
163
|
+
|
|
164
|
+
with torch.set_grad_enabled(train_mode):
|
|
165
|
+
if self.fuse_duplicate_edges_training:
|
|
166
|
+
if not (inference or validation):
|
|
167
|
+
edge_index = batch.edge_index # Shape: [2, num_edges]
|
|
168
|
+
edge_type = batch.edge_type # Shape: [num_edges, d], one-hot encoded
|
|
169
|
+
num_edges, d = edge_type.shape
|
|
170
|
+
|
|
171
|
+
# Create edge tuple and find unique edges
|
|
172
|
+
edges_tuple = torch.stack([edge_index[0], edge_index[1]], dim=1) # Shape: [num_edges, 2]
|
|
173
|
+
unique_edges, inverse_indices = torch.unique(edges_tuple, dim=0, return_inverse=True)
|
|
174
|
+
|
|
175
|
+
# Convert unique_edges to edge_index format
|
|
176
|
+
unique_edge_index = unique_edges.t() # Shape: [2, num_unique_edges]
|
|
177
|
+
|
|
178
|
+
# Merge edge_type values for duplicate edges
|
|
179
|
+
# num_unique_edges = unique_edge_index.shape[1]
|
|
180
|
+
# new_y = torch.zeros(num_unique_edges, d, dtype=edge_type.dtype, device=edge_type.device)
|
|
181
|
+
# new_y.scatter_add_(0, inverse_indices.view(-1, 1).expand(-1, d), edge_type)
|
|
182
|
+
# new_y = (new_y > 0).float() # Ensure one-hot
|
|
183
|
+
|
|
184
|
+
# Get indices of first occurrence of each unique edge
|
|
185
|
+
indices = torch.unique(inverse_indices, return_counts=False)
|
|
186
|
+
|
|
187
|
+
# Update batch
|
|
188
|
+
batch = batch[indices]
|
|
189
|
+
batch.edge_index = unique_edge_index
|
|
190
|
+
# batch.edge_type = new_y
|
|
191
|
+
h_src, h_dst = h_src[indices], h_dst[indices]
|
|
192
|
+
|
|
193
|
+
# Train mode: loss | Inference mode: scores
|
|
194
|
+
loss_or_scores = None
|
|
195
|
+
|
|
196
|
+
for objective in self.objectives:
|
|
197
|
+
results = objective(
|
|
198
|
+
h_src=h_src, # shape (E, d)
|
|
199
|
+
h_dst=h_dst, # shape (E, d)
|
|
200
|
+
h=h, # shape (N, d)
|
|
201
|
+
edge_index=h_edge_index, # edges in the node space of h
|
|
202
|
+
edge_type=batch.edge_type,
|
|
203
|
+
y_edge=batch.y,
|
|
204
|
+
inference=inference,
|
|
205
|
+
x=getattr(batch, "x", None),
|
|
206
|
+
node_type=getattr(batch, "node_type", None),
|
|
207
|
+
node_type_src=getattr(batch, "node_type_src", None),
|
|
208
|
+
node_type_dst=getattr(batch, "node_type_dst", None),
|
|
209
|
+
validation=validation,
|
|
210
|
+
batch=batch,
|
|
211
|
+
mask_nodes=mask_nodes, # Pass mask_nodes to objectives
|
|
212
|
+
**corrupted,
|
|
213
|
+
)
|
|
214
|
+
loss = results["loss"]
|
|
215
|
+
|
|
216
|
+
# With both node- and edge-level objectives, node scores are converted to edge
|
|
217
|
+
# scores at inference, whatever the order of the objectives
|
|
218
|
+
if inference and self.is_hybrid_loss and getattr(objective, "is_node_level", False):
|
|
219
|
+
loss = self.node_to_edge_loss(batch, loss)
|
|
220
|
+
|
|
221
|
+
if loss_or_scores is None:
|
|
222
|
+
# Allocated on the device (a copy from the host would wait for the GPU)
|
|
223
|
+
device = batch.edge_index.device
|
|
224
|
+
loss_or_scores = (
|
|
225
|
+
torch.zeros(1, device=device)
|
|
226
|
+
if train_mode
|
|
227
|
+
else torch.zeros(loss.shape[0], dtype=torch.float, device=device)
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
if loss.numel() != loss_or_scores.numel():
|
|
231
|
+
raise TypeError(
|
|
232
|
+
f"Shapes of loss/score do not match ({loss.numel()} vs {loss_or_scores.numel()})"
|
|
233
|
+
)
|
|
234
|
+
loss_or_scores = loss_or_scores + loss
|
|
235
|
+
|
|
236
|
+
if train_mode and encoder_aux_loss is not None:
|
|
237
|
+
loss_or_scores = loss_or_scores + encoder_aux_loss
|
|
238
|
+
|
|
239
|
+
results["loss"] = loss_or_scores
|
|
240
|
+
return results
|
|
241
|
+
|
|
242
|
+
def get_val_ap(self):
|
|
243
|
+
"""Get average validation score across all objectives.
|
|
244
|
+
|
|
245
|
+
Returns:
|
|
246
|
+
float: Mean validation score (average precision)
|
|
247
|
+
"""
|
|
248
|
+
return np.mean([d.get_val_score() for d in self.objectives])
|
|
249
|
+
|
|
250
|
+
def to_device(self, device):
|
|
251
|
+
"""Move model and associated components to specified device.
|
|
252
|
+
|
|
253
|
+
Handles special device migration for TGN memory and graph reindexer.
|
|
254
|
+
|
|
255
|
+
Args:
|
|
256
|
+
device: Target PyTorch device
|
|
257
|
+
|
|
258
|
+
Returns:
|
|
259
|
+
Model: Self for chaining
|
|
260
|
+
"""
|
|
261
|
+
if self.device == device:
|
|
262
|
+
return self
|
|
263
|
+
|
|
264
|
+
for objective in self.objectives:
|
|
265
|
+
objective.graph_reindexer.to(device)
|
|
266
|
+
|
|
267
|
+
if isinstance(self.encoder, TGNEncoder):
|
|
268
|
+
self.encoder.to_device(device)
|
|
269
|
+
|
|
270
|
+
self.device = device
|
|
271
|
+
return self.to(device)
|
|
272
|
+
|
|
273
|
+
def eval(self):
|
|
274
|
+
"""Set model to evaluation mode.
|
|
275
|
+
|
|
276
|
+
Overrides default eval() to keep dropout active for MC Dropout uncertainty.
|
|
277
|
+
"""
|
|
278
|
+
super().eval()
|
|
279
|
+
|
|
280
|
+
if self.is_running_mc_dropout:
|
|
281
|
+
activate_dropout_inference(self)
|
|
282
|
+
|
|
283
|
+
def gather_h(self, batch, res):
|
|
284
|
+
"""Extract source and destination node embeddings from encoder output.
|
|
285
|
+
|
|
286
|
+
Handles different encoder output formats:
|
|
287
|
+
- Single tensor h (N, d): index by edge_index to get h_src, h_dst
|
|
288
|
+
- Tuple (h_src_nodes, h_dst_nodes): separate embeddings for src/dst nodes
|
|
289
|
+
- Pre-computed (h_src, h_dst): already indexed for edges
|
|
290
|
+
|
|
291
|
+
Args:
|
|
292
|
+
batch: Data batch with edge_index
|
|
293
|
+
res: Encoder output dict with 'h', optionally 'h_src', 'h_dst'
|
|
294
|
+
|
|
295
|
+
Returns:
|
|
296
|
+
tuple: (h, h_src, h_dst) node embeddings
|
|
297
|
+
"""
|
|
298
|
+
h = res["h"]
|
|
299
|
+
h_src = res.get("h_src", None)
|
|
300
|
+
h_dst = res.get("h_dst", None)
|
|
301
|
+
edge_index = res.get("edge_index", batch.edge_index)
|
|
302
|
+
|
|
303
|
+
if None in [h_src, h_dst]:
|
|
304
|
+
if isinstance(h, torch.Tensor):
|
|
305
|
+
# h is a single tensor with node embeddings - index by edge_index
|
|
306
|
+
h_src, h_dst = h[edge_index[0]], h[edge_index[1]]
|
|
307
|
+
elif isinstance(h, (tuple, list)):
|
|
308
|
+
# h is (h_src_nodes, h_dst_nodes) with separate node embeddings - index each
|
|
309
|
+
h_src, h_dst = h[0][edge_index[0]], h[1][edge_index[1]]
|
|
310
|
+
else:
|
|
311
|
+
h_src, h_dst = h
|
|
312
|
+
|
|
313
|
+
return h, h_src, h_dst
|
|
314
|
+
|
|
315
|
+
def to_fine_tuning(self, do: bool):
|
|
316
|
+
"""Switch between self-supervised pretraining and few-shot fine-tuning.
|
|
317
|
+
|
|
318
|
+
When entering few-shot mode:
|
|
319
|
+
- Optionally freezes encoder weights
|
|
320
|
+
- Replaces pretraining objectives with few-shot detection objective
|
|
321
|
+
|
|
322
|
+
When exiting few-shot mode:
|
|
323
|
+
- Unfreezes encoder
|
|
324
|
+
- Restores pretraining objectives
|
|
325
|
+
|
|
326
|
+
Args:
|
|
327
|
+
do: True to enter few-shot mode, False to exit
|
|
328
|
+
"""
|
|
329
|
+
if not self.use_few_shot:
|
|
330
|
+
return
|
|
331
|
+
if do and not self.few_shot_mode:
|
|
332
|
+
if self.freeze_encoder:
|
|
333
|
+
self.encoder.eval()
|
|
334
|
+
for param in self.encoder.parameters(): # freeze the encoder
|
|
335
|
+
param.requires_grad = False
|
|
336
|
+
|
|
337
|
+
# the objective is replaced by a copy of the objective_few_shot + the old objective is saved for later switch
|
|
338
|
+
ssl_objective = (
|
|
339
|
+
self.objectives
|
|
340
|
+
) # switch the pretext objective and fine-tuning objective
|
|
341
|
+
self.objectives = copy.deepcopy(self.objective_few_shot)
|
|
342
|
+
self.ssl_objective = ssl_objective
|
|
343
|
+
self.few_shot_mode = True
|
|
344
|
+
|
|
345
|
+
if not do and self.few_shot_mode:
|
|
346
|
+
self.encoder.train()
|
|
347
|
+
for param in self.encoder.parameters():
|
|
348
|
+
param.requires_grad = True
|
|
349
|
+
|
|
350
|
+
# the ssl objective is set back
|
|
351
|
+
self.objectives = self.ssl_objective
|
|
352
|
+
self.few_shot_mode = False
|
|
353
|
+
|
|
354
|
+
def reset_state(self):
|
|
355
|
+
"""Reset the state of the encoder (e.g., TGN memory) and of objectives (e.g. statistics
|
|
356
|
+
of training embeddings) before each training epoch."""
|
|
357
|
+
if hasattr(self.encoder, "reset_state"):
|
|
358
|
+
self.encoder.reset_state()
|
|
359
|
+
for objective in self.objectives:
|
|
360
|
+
objective = self._unwrap(objective)
|
|
361
|
+
if hasattr(objective, "reset_state"):
|
|
362
|
+
objective.reset_state()
|
|
363
|
+
|
|
364
|
+
@staticmethod
|
|
365
|
+
def _unwrap(objective):
|
|
366
|
+
"""The objective wrapped by a `ValidationWrapper`."""
|
|
367
|
+
return getattr(objective, "objective", objective)
|
|
368
|
+
|
|
369
|
+
def node_to_edge_loss(self, batch, loss):
|
|
370
|
+
n_id = batch.original_n_id
|
|
371
|
+
edge_index = batch.original_edge_index
|
|
372
|
+
|
|
373
|
+
sorted_ids, perm = torch.sort(n_id)
|
|
374
|
+
src_pos = torch.searchsorted(sorted_ids, edge_index[0])
|
|
375
|
+
dst_pos = torch.searchsorted(sorted_ids, edge_index[1])
|
|
376
|
+
|
|
377
|
+
src_idx = perm[src_pos]
|
|
378
|
+
dst_idx = perm[dst_pos]
|
|
379
|
+
|
|
380
|
+
edge_sums = loss.index_select(0, src_idx) + loss.index_select(0, dst_idx)
|
|
381
|
+
|
|
382
|
+
return edge_sums
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
from .autoencode_edge_emb import EdgeEmbAutoencoder
|
|
2
|
+
from .deep_graph_infomax import DeepGraphInfomax
|
|
3
|
+
from .detect_few_shot import FewShotEdgeDetection
|
|
4
|
+
from .one_class import OneClass
|
|
5
|
+
from .predict_edge_contrastive import EdgeContrastivePrediction
|
|
6
|
+
from .predict_edge_supervised import PredictEdgeSupervised
|
|
7
|
+
from .predict_edge_type import EdgeTypePrediction
|
|
8
|
+
from .predict_masked_struct import GMAEStructPrediction
|
|
9
|
+
from .predict_node_type import NodeTypePrediction
|
|
10
|
+
from .predict_process_tag import ProcessTagPrediction, process_tag_classes_from_cfg
|
|
11
|
+
from .predict_snapshot_embedding import SnapshotEmbeddingPrediction
|
|
12
|
+
from .reconstruct_edge_emb import EdgeEmbReconstruction
|
|
13
|
+
from .reconstruct_masked_feat import GMAEFeatReconstruction
|
|
14
|
+
from .reconstruct_node_emb import NodeEmbReconstruction
|
|
15
|
+
from .reconstruct_node_feat import NodeFeatReconstruction
|
|
16
|
+
from .validation_wrapper import ValidationWrapper
|