pidsmaker 4.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.
Potentially problematic release.
This version of pidsmaker might be problematic. Click here for more details.
- pidsmaker/__init__.py +22 -0
- pidsmaker/cli.py +32 -0
- pidsmaker/config/__init__.py +2 -0
- pidsmaker/config/config.py +2100 -0
- pidsmaker/config/pipeline.py +1768 -0
- pidsmaker/config/schemas.py +1032 -0
- pidsmaker/datasets.py +222 -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 +259 -0
- pidsmaker/detection/evaluation_methods/evaluation_utils.py +1730 -0
- pidsmaker/detection/evaluation_methods/host_two_stage_evaluation.py +115 -0
- pidsmaker/detection/evaluation_methods/node_evaluation.py +463 -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 +451 -0
- pidsmaker/detection/evaluation_methods/tw_evaluation.py +95 -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 +293 -0
- pidsmaker/detection/training_methods/ocrapt_early_stop.py +165 -0
- pidsmaker/detection/training_methods/threatrace_training.py +169 -0
- pidsmaker/detection/training_methods/training_loop.py +377 -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 +31 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_TRW.py +67 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_alacarte.py +16 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_doc2vec.py +54 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_fasttext.py +38 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_flash.py +70 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_graph2vec.py +85 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_ocrapt_features.py +95 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_pretrained.py +1729 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_word2vec.py +56 -0
- pidsmaker/featurization/featurization_methods/__init__.py +0 -0
- pidsmaker/featurization/featurization_methods/build_trw.py +67 -0
- pidsmaker/featurization/featurization_methods/featurization_alacarte.py +748 -0
- pidsmaker/featurization/featurization_methods/featurization_doc2vec.py +99 -0
- pidsmaker/featurization/featurization_methods/featurization_fasttext.py +75 -0
- pidsmaker/featurization/featurization_methods/featurization_flash.py +203 -0
- pidsmaker/featurization/featurization_methods/featurization_graph2vec.py +243 -0
- pidsmaker/featurization/featurization_methods/featurization_trw.py +115 -0
- pidsmaker/featurization/featurization_methods/featurization_word2vec.py +87 -0
- pidsmaker/featurization/featurization_utils.py +275 -0
- pidsmaker/featurization/utils/build_random_walks.py +68 -0
- pidsmaker/featurization/utils/trw.py +203 -0
- pidsmaker/hetero.py +81 -0
- pidsmaker/losses.py +170 -0
- pidsmaker/main.py +377 -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 +830 -0
- pidsmaker/preprocessing/build_graph_methods/build_magic_graphs.py +220 -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 +1432 -0
- pidsmaker/pretrained/embedding_generator.py +252 -0
- pidsmaker/pretrained/finetune.py +1437 -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 +276 -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/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/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 +120 -0
- pidsmaker/resources/config/orthrus_fixed.yml +17 -0
- pidsmaker/resources/config/orthrus_non_snooped.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/tasks/__init__.py +10 -0
- pidsmaker/tasks/batching.py +49 -0
- pidsmaker/tasks/construction.py +31 -0
- pidsmaker/tasks/evaluation.py +232 -0
- pidsmaker/tasks/feat_inference.py +413 -0
- pidsmaker/tasks/featurization.py +43 -0
- pidsmaker/tasks/training.py +19 -0
- pidsmaker/tasks/transformation.py +308 -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/data_utils.py +1742 -0
- pidsmaker/utils/database.py +204 -0
- pidsmaker/utils/dataset_utils.py +413 -0
- pidsmaker/utils/dataset_writer.py +1057 -0
- pidsmaker/utils/graph_store.py +634 -0
- pidsmaker/utils/labelling.py +447 -0
- pidsmaker/utils/loss_files.py +193 -0
- pidsmaker/utils/process_tags.py +44 -0
- pidsmaker/utils/utils.py +730 -0
- pidsmaker/vizgen/__init__.py +1 -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-4.0.0.dist-info/METADATA +596 -0
- pidsmaker-4.0.0.dist-info/RECORD +338 -0
- pidsmaker-4.0.0.dist-info/WHEEL +5 -0
- pidsmaker-4.0.0.dist-info/entry_points.txt +2 -0
- pidsmaker-4.0.0.dist-info/licenses/LICENSE +201 -0
- pidsmaker-4.0.0.dist-info/top_level.txt +1 -0
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
|
|
@@ -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}
|