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/factory.py
ADDED
|
@@ -0,0 +1,1456 @@
|
|
|
1
|
+
"""Model factory for building PIDS components.
|
|
2
|
+
|
|
3
|
+
This module creates encoder, decoder, and objective components based on configuration.
|
|
4
|
+
Supports multiple encoder architectures (SAGE, GAT, GIN, GLSTM, etc.) and objectives
|
|
5
|
+
(reconstruction, prediction, contrastive learning, few-shot detection).
|
|
6
|
+
"""
|
|
7
|
+
import os
|
|
8
|
+
|
|
9
|
+
import torch
|
|
10
|
+
import torch.nn as nn
|
|
11
|
+
|
|
12
|
+
from pidsmaker.config import (
|
|
13
|
+
ENCODER_WRAPPERS,
|
|
14
|
+
OBJECTIVES_NODE_LEVEL,
|
|
15
|
+
OBJECTIVES_WITHOUT_DECODER,
|
|
16
|
+
decoder_matches_objective,
|
|
17
|
+
)
|
|
18
|
+
from pidsmaker.decoders import *
|
|
19
|
+
from pidsmaker.detection.flash_detection import FlashScorer
|
|
20
|
+
from pidsmaker.detection.magic_knn import MagicScorer
|
|
21
|
+
from pidsmaker.detection.node_scoring import NodeScorer
|
|
22
|
+
from pidsmaker.detection.threatrace_detection import ThreaTraceScorer
|
|
23
|
+
from pidsmaker.encoders import *
|
|
24
|
+
from pidsmaker.experiments.uncertainty import add_dropout_to_model
|
|
25
|
+
from pidsmaker.losses import *
|
|
26
|
+
from pidsmaker.model import Model
|
|
27
|
+
from pidsmaker.objectives import *
|
|
28
|
+
from pidsmaker.tgn import IdentityMessage, LastAggregator, TGNMemory, TimeEncodingMemory
|
|
29
|
+
from pidsmaker.utils.data_utils import GraphReindexer, materialize_batch, to_original_node_ids
|
|
30
|
+
from pidsmaker.utils.dataset_utils import (
|
|
31
|
+
get_node_map,
|
|
32
|
+
get_num_edge_type,
|
|
33
|
+
get_edge_attrs_dim,
|
|
34
|
+
get_possible_events,
|
|
35
|
+
get_rel2id,
|
|
36
|
+
)
|
|
37
|
+
from pidsmaker.hetero import get_metadata
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def build_model(data_sample, device, cfg, max_node_num, all_data=None):
|
|
41
|
+
"""
|
|
42
|
+
Builds and loads the initial model into memory.
|
|
43
|
+
The `data_sample` is required to infer the shape of the layers.
|
|
44
|
+
`all_data` is an optional tuple (val_data, test_data) used by the
|
|
45
|
+
predict_edge_supervised objective to extract attack edge features.
|
|
46
|
+
"""
|
|
47
|
+
msg_dim, edge_dim, in_dim = get_dimensions_from_data_sample(materialize_batch(data_sample))
|
|
48
|
+
|
|
49
|
+
graph_reindexer = GraphReindexer(
|
|
50
|
+
device=device,
|
|
51
|
+
num_nodes=max_node_num,
|
|
52
|
+
fix_buggy_graph_reindexer=cfg.batching.fix_buggy_graph_reindexer,
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
encoder = encoder_factory(
|
|
56
|
+
cfg,
|
|
57
|
+
msg_dim=msg_dim,
|
|
58
|
+
in_dim=in_dim,
|
|
59
|
+
edge_dim=edge_dim,
|
|
60
|
+
device=device,
|
|
61
|
+
max_node_num=max_node_num,
|
|
62
|
+
graph_reindexer=graph_reindexer,
|
|
63
|
+
)
|
|
64
|
+
objectives = objective_factory(
|
|
65
|
+
cfg, in_dim=in_dim, graph_reindexer=graph_reindexer, device=device,
|
|
66
|
+
all_data=all_data, edge_dim=edge_dim,
|
|
67
|
+
)
|
|
68
|
+
objective_few_shot = few_shot_decoder_factory(
|
|
69
|
+
cfg, device=device, graph_reindexer=graph_reindexer
|
|
70
|
+
)
|
|
71
|
+
model = model_factory(encoder, objectives, objective_few_shot, cfg, device=device)
|
|
72
|
+
|
|
73
|
+
if cfg._is_running_mc_dropout:
|
|
74
|
+
dropout = cfg.experiment.uncertainty.mc_dropout.dropout
|
|
75
|
+
add_dropout_to_model(model, p=dropout)
|
|
76
|
+
|
|
77
|
+
return model
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def model_factory(encoder, objectives, objective_few_shot, cfg, device):
|
|
81
|
+
"""Create Model instance combining encoder with objectives.
|
|
82
|
+
|
|
83
|
+
Args:
|
|
84
|
+
encoder: Neural encoder module (SAGE, GAT, TGN, etc.)
|
|
85
|
+
objectives: List of training objectives (reconstruction, prediction, etc.)
|
|
86
|
+
objective_few_shot: Few-shot detection objective (optional)
|
|
87
|
+
cfg: Configuration object
|
|
88
|
+
device: PyTorch device (cuda/cpu)
|
|
89
|
+
|
|
90
|
+
Returns:
|
|
91
|
+
Model: Complete model moved to specified device
|
|
92
|
+
"""
|
|
93
|
+
return Model(
|
|
94
|
+
encoder=encoder,
|
|
95
|
+
objectives=objectives,
|
|
96
|
+
objective_few_shot=objective_few_shot,
|
|
97
|
+
device=device,
|
|
98
|
+
is_running_mc_dropout=cfg._is_running_mc_dropout,
|
|
99
|
+
use_few_shot=cfg.training.decoder.use_few_shot,
|
|
100
|
+
freeze_encoder=cfg.training.decoder.few_shot.freeze_encoder,
|
|
101
|
+
fuse_duplicate_edges_training=cfg.training.fuse_duplicate_edges_training,
|
|
102
|
+
is_hybrid_loss=cfg._is_hybrid_loss,
|
|
103
|
+
).to(device)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def encoder_block_factory(cfg, msg_dim, in_dim, edge_dim, device, max_node_num):
|
|
107
|
+
node_hid_dim = cfg.training.node_hid_dim
|
|
108
|
+
node_out_dim = cfg.training.node_out_dim
|
|
109
|
+
dropout = cfg.training.encoder.dropout
|
|
110
|
+
tgn_memory_dim = cfg.training.encoder.tgn.tgn_memory_dim
|
|
111
|
+
tgn_time_dim = cfg.training.encoder.tgn.tgn_time_dim
|
|
112
|
+
use_tgn = "tgn" in cfg.training.encoder.used_methods
|
|
113
|
+
use_event_type_encoding = (
|
|
114
|
+
"event_type_encoding" in cfg.training.encoder.used_methods
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
node_map = get_node_map(cfg, from_zero=True)
|
|
118
|
+
|
|
119
|
+
# If edge features are used, we set them here
|
|
120
|
+
# edge_dim = 0
|
|
121
|
+
# edge_features = list(
|
|
122
|
+
# map(lambda x: x.strip(), cfg.batching.edge_features.split(","))
|
|
123
|
+
# )
|
|
124
|
+
# for edge_feat in edge_features:
|
|
125
|
+
# if edge_feat in ["edge_type", "edge_type_triplet"]:
|
|
126
|
+
# edge_dim += get_num_edge_type(cfg)
|
|
127
|
+
# elif edge_feat == "msg":
|
|
128
|
+
# edge_dim += msg_dim
|
|
129
|
+
# elif edge_feat == "time_encoding":
|
|
130
|
+
# if not use_tgn:
|
|
131
|
+
# raise TypeError("Edge feature `time_encoding` is only available if TGN is used.")
|
|
132
|
+
# edge_dim += tgn_memory_dim
|
|
133
|
+
# elif edge_feat == "none":
|
|
134
|
+
# pass
|
|
135
|
+
# else:
|
|
136
|
+
# raise ValueError(f"Invalid edge feature {edge_feat}")
|
|
137
|
+
|
|
138
|
+
if use_tgn:
|
|
139
|
+
in_dim = tgn_memory_dim
|
|
140
|
+
|
|
141
|
+
if use_event_type_encoding:
|
|
142
|
+
edge_dim = in_dim
|
|
143
|
+
|
|
144
|
+
edge_features = cfg.batching.edge_features
|
|
145
|
+
if "time_encoding" in edge_features:
|
|
146
|
+
edge_dim = (edge_dim or 0) + tgn_time_dim
|
|
147
|
+
|
|
148
|
+
# `check_encoders` ensures that a single base encoder is used, with optional wrappers
|
|
149
|
+
methods = [m.strip() for m in cfg.training.encoder.used_methods.replace("-", ",").split(",")]
|
|
150
|
+
for method in methods:
|
|
151
|
+
if method in ENCODER_WRAPPERS:
|
|
152
|
+
pass
|
|
153
|
+
|
|
154
|
+
# Basic GNN encoders
|
|
155
|
+
elif method == "graph_attention":
|
|
156
|
+
encoder = GraphAttentionEmbedding(
|
|
157
|
+
in_dim=in_dim,
|
|
158
|
+
hid_dim=node_hid_dim,
|
|
159
|
+
out_dim=node_out_dim,
|
|
160
|
+
edge_dim=edge_dim or None,
|
|
161
|
+
activation=activation_fn_factory(cfg.training.encoder.graph_attention.activation),
|
|
162
|
+
dropout=dropout,
|
|
163
|
+
num_heads=cfg.training.encoder.graph_attention.num_heads,
|
|
164
|
+
concat=cfg.training.encoder.graph_attention.concat,
|
|
165
|
+
flow=cfg.training.encoder.graph_attention.flow,
|
|
166
|
+
num_layers=cfg.training.encoder.graph_attention.num_layers,
|
|
167
|
+
final_activation=bool(cfg.training.encoder.graph_attention.final_activation),
|
|
168
|
+
)
|
|
169
|
+
elif method == "hetero_graph_transformer":
|
|
170
|
+
node_map = get_node_map(cfg, from_zero=True)
|
|
171
|
+
metadata = get_metadata(get_possible_events(cfg), node_map)
|
|
172
|
+
|
|
173
|
+
encoder = HeteroGraphTransformer(
|
|
174
|
+
in_dim=in_dim,
|
|
175
|
+
out_dim=node_out_dim,
|
|
176
|
+
num_heads=cfg.training.encoder.hetero_graph_transformer.num_heads,
|
|
177
|
+
num_layers=cfg.training.encoder.hetero_graph_transformer.num_layers,
|
|
178
|
+
metadata=metadata,
|
|
179
|
+
device=device,
|
|
180
|
+
node_map=node_map,
|
|
181
|
+
)
|
|
182
|
+
elif method == "egraphsage":
|
|
183
|
+
encoder = EGraphSAGE(
|
|
184
|
+
in_dim=in_dim,
|
|
185
|
+
hid_dim=node_hid_dim,
|
|
186
|
+
out_dim=node_out_dim,
|
|
187
|
+
edge_dim=edge_dim or None,
|
|
188
|
+
activation=activation_fn_factory(cfg.training.encoder.egraphsage.activation),
|
|
189
|
+
dropout=dropout,
|
|
190
|
+
num_layers=cfg.training.encoder.egraphsage.num_layers,
|
|
191
|
+
undirected=cfg.training.encoder.egraphsage.undirected is not False,
|
|
192
|
+
)
|
|
193
|
+
elif method == "argus":
|
|
194
|
+
encoder = ArgusEncoder(
|
|
195
|
+
in_dim=in_dim,
|
|
196
|
+
hid_dim=node_hid_dim,
|
|
197
|
+
out_dim=node_out_dim,
|
|
198
|
+
edge_dim=edge_dim or None,
|
|
199
|
+
num_layers=cfg.training.encoder.argus.num_layers,
|
|
200
|
+
dropout=dropout,
|
|
201
|
+
)
|
|
202
|
+
elif method == "lares":
|
|
203
|
+
lares_cfg = cfg.training.encoder.lares
|
|
204
|
+
encoder = LaresEncoder(
|
|
205
|
+
in_dim=in_dim,
|
|
206
|
+
out_dim=node_out_dim,
|
|
207
|
+
num_nodes=max_node_num,
|
|
208
|
+
edge_dim=edge_dim or None,
|
|
209
|
+
dropout=dropout,
|
|
210
|
+
flow=(lares_cfg.flow or "target_to_source").strip(),
|
|
211
|
+
use_node_features=bool(lares_cfg.use_node_features),
|
|
212
|
+
)
|
|
213
|
+
elif method == "gcn":
|
|
214
|
+
encoder = GCN(
|
|
215
|
+
in_dim=in_dim,
|
|
216
|
+
hid_dim=node_hid_dim,
|
|
217
|
+
out_dim=node_out_dim,
|
|
218
|
+
activation=activation_fn_factory(cfg.training.encoder.gcn.activation),
|
|
219
|
+
dropout=dropout,
|
|
220
|
+
num_layers=cfg.training.encoder.gcn.num_layers,
|
|
221
|
+
)
|
|
222
|
+
elif method == "sage":
|
|
223
|
+
encoder = SAGE(
|
|
224
|
+
in_dim=in_dim,
|
|
225
|
+
hid_dim=node_hid_dim,
|
|
226
|
+
out_dim=node_out_dim,
|
|
227
|
+
activation=activation_fn_factory(cfg.training.encoder.sage.activation),
|
|
228
|
+
dropout=dropout,
|
|
229
|
+
num_layers=cfg.training.encoder.sage.num_layers,
|
|
230
|
+
)
|
|
231
|
+
elif method == "gat":
|
|
232
|
+
encoder = GAT(
|
|
233
|
+
in_dim=in_dim,
|
|
234
|
+
hid_dim=node_hid_dim,
|
|
235
|
+
out_dim=node_out_dim,
|
|
236
|
+
activation=activation_fn_factory(cfg.training.encoder.gat.activation),
|
|
237
|
+
dropout=dropout,
|
|
238
|
+
num_heads=cfg.training.encoder.gat.num_heads,
|
|
239
|
+
concat=cfg.training.encoder.gat.concat,
|
|
240
|
+
num_layers=cfg.training.encoder.gat.num_layers,
|
|
241
|
+
)
|
|
242
|
+
elif method == "gin":
|
|
243
|
+
encoder = GIN(
|
|
244
|
+
in_dim=in_dim,
|
|
245
|
+
hid_dim=node_hid_dim,
|
|
246
|
+
out_dim=node_out_dim,
|
|
247
|
+
edge_dim=edge_dim or None,
|
|
248
|
+
dropout=dropout,
|
|
249
|
+
activation=activation_fn_factory(cfg.training.encoder.gin.activation),
|
|
250
|
+
num_layers=cfg.training.encoder.gin.num_layers,
|
|
251
|
+
)
|
|
252
|
+
elif method == "sum_aggregation":
|
|
253
|
+
encoder = SumAggregation(
|
|
254
|
+
in_dim=in_dim,
|
|
255
|
+
hid_dim=node_hid_dim,
|
|
256
|
+
out_dim=node_out_dim,
|
|
257
|
+
)
|
|
258
|
+
elif method == "rgcn":
|
|
259
|
+
encoder = RGCN(
|
|
260
|
+
in_dim=in_dim,
|
|
261
|
+
out_dim=node_out_dim,
|
|
262
|
+
num_relations=get_num_edge_type(cfg),
|
|
263
|
+
num_layers=cfg.training.encoder.rgcn.num_layers,
|
|
264
|
+
activation=activation_fn_factory(cfg.training.encoder.rgcn.activation),
|
|
265
|
+
dropout=dropout,
|
|
266
|
+
)
|
|
267
|
+
elif method == "rgcn_per_type":
|
|
268
|
+
act_name = cfg.training.encoder.rgcn_per_type.activation
|
|
269
|
+
encoder = PerTypeRGCN(
|
|
270
|
+
in_dim=in_dim,
|
|
271
|
+
out_dim=node_out_dim,
|
|
272
|
+
num_relations=get_num_edge_type(cfg),
|
|
273
|
+
num_layers=cfg.training.encoder.rgcn_per_type.num_layers,
|
|
274
|
+
activation_factory=lambda: activation_fn_factory(act_name),
|
|
275
|
+
dropout=dropout,
|
|
276
|
+
num_node_types=cfg.dataset.num_node_types,
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
# System-specific encoders
|
|
280
|
+
elif method == "shadewatcher":
|
|
281
|
+
sw_cfg = cfg.training.encoder.shadewatcher
|
|
282
|
+
encoder = ShadeWatcherEncoder(
|
|
283
|
+
in_dim=in_dim,
|
|
284
|
+
emb_dim=node_hid_dim,
|
|
285
|
+
out_dim=node_out_dim,
|
|
286
|
+
num_edge_types=get_num_edge_type(cfg),
|
|
287
|
+
hidden_dims=parse_int_list(sw_cfg.hidden_dims),
|
|
288
|
+
kg_dim=sw_cfg.kg_dim,
|
|
289
|
+
kg_neg_ratio=sw_cfg.kg_neg_ratio,
|
|
290
|
+
kg_margin=sw_cfg.kg_margin,
|
|
291
|
+
dropout=dropout,
|
|
292
|
+
)
|
|
293
|
+
elif method == "glstm":
|
|
294
|
+
encoder = GLSTM(
|
|
295
|
+
in_features=in_dim,
|
|
296
|
+
out_features=node_out_dim,
|
|
297
|
+
cell_clip=None,
|
|
298
|
+
type_specific_decoding=False,
|
|
299
|
+
exclude_file=True,
|
|
300
|
+
exclude_ip=True,
|
|
301
|
+
typed_hidden_rep=False,
|
|
302
|
+
edge_dim=None,
|
|
303
|
+
full_param=False,
|
|
304
|
+
# TODO: we should use 10 here; edge type indices start from 1
|
|
305
|
+
num_edge_type=max(15, get_num_edge_type(cfg) + 1),
|
|
306
|
+
).to(device)
|
|
307
|
+
elif method == "rcaid_gat":
|
|
308
|
+
rcaid_cfg = cfg.training.encoder.rcaid_gat
|
|
309
|
+
encoder = RCaidGAT(
|
|
310
|
+
in_dim=in_dim,
|
|
311
|
+
hid_dim=node_hid_dim,
|
|
312
|
+
out_dim=node_out_dim,
|
|
313
|
+
dropout=dropout,
|
|
314
|
+
num_layers=getattr(rcaid_cfg, "num_layers", None) or 2,
|
|
315
|
+
num_heads=getattr(rcaid_cfg, "num_heads", None) or 1,
|
|
316
|
+
)
|
|
317
|
+
elif method == "sum_aggregation":
|
|
318
|
+
encoder = SumAggregation(
|
|
319
|
+
in_dim=in_dim,
|
|
320
|
+
hid_dim=node_hid_dim,
|
|
321
|
+
out_dim=node_out_dim,
|
|
322
|
+
)
|
|
323
|
+
elif method == "magic_gat":
|
|
324
|
+
encoder = MagicGAT(
|
|
325
|
+
in_dim=in_dim,
|
|
326
|
+
hid_dim=node_hid_dim,
|
|
327
|
+
out_dim=node_out_dim,
|
|
328
|
+
n_layers=cfg.training.encoder.magic_gat.num_layers,
|
|
329
|
+
n_heads=cfg.training.encoder.magic_gat.num_heads,
|
|
330
|
+
feat_drop=0.1,
|
|
331
|
+
attn_drop=0.0,
|
|
332
|
+
negative_slope=cfg.training.encoder.magic_gat.negative_slope,
|
|
333
|
+
residual=True,
|
|
334
|
+
activation=activation_fn_factory(cfg.training.encoder.magic_gat.activation),
|
|
335
|
+
is_decoder=False,
|
|
336
|
+
edge_dim=edge_dim or None,
|
|
337
|
+
)
|
|
338
|
+
|
|
339
|
+
# Sequence model over the graph2vec embeddings of the last snapshots (ProGrapher)
|
|
340
|
+
elif method == "textrcnn":
|
|
341
|
+
check_snapshot_batching(cfg)
|
|
342
|
+
textrcnn_cfg = cfg.training.encoder.textrcnn
|
|
343
|
+
encoder = TextRCNN(
|
|
344
|
+
emb_dim=cfg.featurization.emb_dim,
|
|
345
|
+
hid_dim=node_hid_dim,
|
|
346
|
+
num_layers=textrcnn_cfg.num_layers,
|
|
347
|
+
sequence_length=textrcnn_cfg.sequence_length,
|
|
348
|
+
dropout=dropout,
|
|
349
|
+
rnn_type=textrcnn_cfg.rnn_type.strip(),
|
|
350
|
+
)
|
|
351
|
+
|
|
352
|
+
# MLP encoders
|
|
353
|
+
elif method == "none":
|
|
354
|
+
encoder = LinearEncoder(in_dim, node_out_dim)
|
|
355
|
+
elif method == "custom_mlp":
|
|
356
|
+
encoder = CustomMLPEncoder(
|
|
357
|
+
in_dim=in_dim,
|
|
358
|
+
out_dim=node_out_dim,
|
|
359
|
+
architecture=cfg.training.encoder.custom_mlp.architecture_str,
|
|
360
|
+
dropout=dropout,
|
|
361
|
+
)
|
|
362
|
+
else:
|
|
363
|
+
raise ValueError(f"Invalid encoder {method}")
|
|
364
|
+
|
|
365
|
+
return encoder
|
|
366
|
+
|
|
367
|
+
def inner_encoder_factory(cfg, in_dim, encoder, original_edge_dim, node_map, edge_map, max_node_num, device):
|
|
368
|
+
use_ancestor_encoding = "ancestor_encoding" in cfg.training.encoder.used_methods
|
|
369
|
+
use_entity_type_encoding = (
|
|
370
|
+
"entity_type_encoding" in cfg.training.encoder.used_methods
|
|
371
|
+
)
|
|
372
|
+
use_event_type_encoding = (
|
|
373
|
+
"event_type_encoding" in cfg.training.encoder.used_methods
|
|
374
|
+
)
|
|
375
|
+
if use_entity_type_encoding:
|
|
376
|
+
encoder = EntityLinearEncoder(
|
|
377
|
+
in_dim=in_dim,
|
|
378
|
+
out_dim=in_dim,
|
|
379
|
+
encoder=encoder,
|
|
380
|
+
activation=True,
|
|
381
|
+
num_node_types=cfg.dataset.num_node_types,
|
|
382
|
+
)
|
|
383
|
+
|
|
384
|
+
if use_event_type_encoding:
|
|
385
|
+
encoder = EventLinearEncoder(
|
|
386
|
+
in_dim=original_edge_dim,
|
|
387
|
+
out_dim=in_dim,
|
|
388
|
+
possible_events=get_possible_events(cfg),
|
|
389
|
+
node_map=node_map,
|
|
390
|
+
edge_map=edge_map,
|
|
391
|
+
encoder=encoder,
|
|
392
|
+
activation=True,
|
|
393
|
+
)
|
|
394
|
+
|
|
395
|
+
if use_ancestor_encoding:
|
|
396
|
+
encoder = AncestorEncoder(
|
|
397
|
+
in_dim=in_dim,
|
|
398
|
+
out_dim=in_dim, # try in_dim*2 ou out_dim
|
|
399
|
+
edge_dim=original_edge_dim,
|
|
400
|
+
encoder=encoder,
|
|
401
|
+
num_nodes=max_node_num,
|
|
402
|
+
device=device,
|
|
403
|
+
)
|
|
404
|
+
|
|
405
|
+
return encoder
|
|
406
|
+
|
|
407
|
+
def encoder_factory(cfg, msg_dim, in_dim, edge_dim, device, max_node_num, graph_reindexer):
|
|
408
|
+
node_out_dim = cfg.training.node_out_dim
|
|
409
|
+
dropout = cfg.training.encoder.dropout
|
|
410
|
+
use_tgn = "tgn" in cfg.training.encoder.used_methods
|
|
411
|
+
node_map = get_node_map(cfg, from_zero=True)
|
|
412
|
+
edge_map = get_rel2id(cfg, from_zero=True)
|
|
413
|
+
|
|
414
|
+
# Learned node ID embeddings are concatenated to the input node features
|
|
415
|
+
use_node_id_embedding = "node_id_embedding" in cfg.training.encoder.used_methods
|
|
416
|
+
node_id_dim = cfg.training.encoder.node_id_embedding.dim if use_node_id_embedding else 0
|
|
417
|
+
encoder_in_dim = in_dim + node_id_dim
|
|
418
|
+
|
|
419
|
+
encoder = encoder_block_factory(cfg, msg_dim, encoder_in_dim, edge_dim, device, max_node_num)
|
|
420
|
+
tgn_pre_encoder = None
|
|
421
|
+
|
|
422
|
+
encoder = inner_encoder_factory(cfg, encoder_in_dim, encoder, edge_dim, node_map, edge_map, max_node_num, device)
|
|
423
|
+
|
|
424
|
+
if use_node_id_embedding:
|
|
425
|
+
encoder = NodeIdEmbedding(
|
|
426
|
+
encoder,
|
|
427
|
+
num_nodes=max_node_num,
|
|
428
|
+
dim=node_id_dim,
|
|
429
|
+
all_nodes=bool(cfg.training.encoder.node_id_embedding.all_nodes),
|
|
430
|
+
)
|
|
431
|
+
if "snapshot_gru" in cfg.training.encoder.used_methods:
|
|
432
|
+
gru_cfg = cfg.training.encoder.snapshot_gru
|
|
433
|
+
encoder = SnapshotGRU(
|
|
434
|
+
encoder,
|
|
435
|
+
num_nodes=max_node_num,
|
|
436
|
+
in_dim=node_out_dim,
|
|
437
|
+
out_dim=node_out_dim,
|
|
438
|
+
hidden_dim=gru_cfg.hidden_dim,
|
|
439
|
+
dropout=gru_cfg.dropout or 0.0,
|
|
440
|
+
)
|
|
441
|
+
|
|
442
|
+
tgn_cfg = cfg.training.encoder.tgn
|
|
443
|
+
time_dim = tgn_cfg.tgn_time_dim
|
|
444
|
+
use_node_feats_in_gnn = tgn_cfg.use_node_feats_in_gnn
|
|
445
|
+
use_memory = tgn_cfg.use_memory
|
|
446
|
+
use_time_order_encoding = tgn_cfg.use_time_order_encoding
|
|
447
|
+
project_src_dst = tgn_cfg.project_src_dst
|
|
448
|
+
tgn_memory_dim = tgn_cfg.tgn_memory_dim
|
|
449
|
+
edge_features = cfg.batching.edge_features
|
|
450
|
+
use_time_enc = "time_encoding" in edge_features
|
|
451
|
+
|
|
452
|
+
tgn_in_dim = in_dim
|
|
453
|
+
|
|
454
|
+
memory = None
|
|
455
|
+
if use_tgn:
|
|
456
|
+
if use_memory:
|
|
457
|
+
memory = TGNMemory(
|
|
458
|
+
max_node_num,
|
|
459
|
+
msg_dim,
|
|
460
|
+
tgn_memory_dim,
|
|
461
|
+
time_dim,
|
|
462
|
+
message_module=IdentityMessage(msg_dim, tgn_memory_dim, time_dim),
|
|
463
|
+
aggregator_module=LastAggregator(),
|
|
464
|
+
device=device,
|
|
465
|
+
)
|
|
466
|
+
elif use_time_enc:
|
|
467
|
+
memory = TimeEncodingMemory(
|
|
468
|
+
max_node_num,
|
|
469
|
+
time_dim,
|
|
470
|
+
device=device,
|
|
471
|
+
)
|
|
472
|
+
|
|
473
|
+
# Standard TGN
|
|
474
|
+
if use_tgn:
|
|
475
|
+
encoder = TGNEncoder(
|
|
476
|
+
encoder=encoder,
|
|
477
|
+
memory=memory,
|
|
478
|
+
time_encoder=memory.time_enc if memory else None,
|
|
479
|
+
in_dim=tgn_in_dim,
|
|
480
|
+
memory_dim=tgn_memory_dim,
|
|
481
|
+
out_dim=node_out_dim,
|
|
482
|
+
use_node_feats_in_gnn=use_node_feats_in_gnn,
|
|
483
|
+
edge_features=edge_features,
|
|
484
|
+
device=device,
|
|
485
|
+
use_memory=use_memory,
|
|
486
|
+
use_time_enc=use_time_enc,
|
|
487
|
+
edge_dim=edge_dim,
|
|
488
|
+
use_time_order_encoding=use_time_order_encoding,
|
|
489
|
+
project_src_dst=project_src_dst,
|
|
490
|
+
is_hetero=cfg._is_hetero,
|
|
491
|
+
node_map=node_map,
|
|
492
|
+
edge_map=edge_map,
|
|
493
|
+
tgn_pre_encoder=tgn_pre_encoder,
|
|
494
|
+
dropout=dropout,
|
|
495
|
+
use_residual_norm=tgn_cfg.use_residual_norm,
|
|
496
|
+
)
|
|
497
|
+
|
|
498
|
+
return encoder
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
def decoder_factory(
|
|
502
|
+
method, objective, cfg, in_dim, out_dim, device, objective_cfg=None, edge_dim=None
|
|
503
|
+
):
|
|
504
|
+
"""Build decoder for specified objective and method.
|
|
505
|
+
|
|
506
|
+
Args:
|
|
507
|
+
method: Decoder type (edge_mlp, node_mlp, nodlink, magic_gat, none)
|
|
508
|
+
objective: Objective name (for config lookup)
|
|
509
|
+
cfg: Global configuration
|
|
510
|
+
in_dim: Input dimension (encoder output)
|
|
511
|
+
out_dim: Output dimension (target task dimension)
|
|
512
|
+
device: PyTorch device
|
|
513
|
+
objective_cfg: Objective-specific config (defaults to cfg.training.decoder)
|
|
514
|
+
|
|
515
|
+
Returns:
|
|
516
|
+
decoder: Decoder module or identity function
|
|
517
|
+
"""
|
|
518
|
+
if objective_cfg is None:
|
|
519
|
+
objective_cfg = cfg.training.decoder
|
|
520
|
+
decoder_cfg = getattr(getattr(objective_cfg, objective), method, None)
|
|
521
|
+
|
|
522
|
+
if method == "edge_mlp":
|
|
523
|
+
return CustomEdgeMLP(
|
|
524
|
+
in_dim=in_dim,
|
|
525
|
+
out_dim=out_dim,
|
|
526
|
+
architecture=decoder_cfg.architecture_str,
|
|
527
|
+
dropout=cfg.training.encoder.dropout,
|
|
528
|
+
src_dst_projection_coef=decoder_cfg.src_dst_projection_coef,
|
|
529
|
+
)
|
|
530
|
+
elif method == "node_mlp":
|
|
531
|
+
return CustomMLPDecoder(
|
|
532
|
+
in_dim=in_dim,
|
|
533
|
+
out_dim=out_dim,
|
|
534
|
+
architecture=decoder_cfg.architecture_str,
|
|
535
|
+
dropout=cfg.training.encoder.dropout,
|
|
536
|
+
)
|
|
537
|
+
elif method == "nodlink":
|
|
538
|
+
return NodLinkDecoder(
|
|
539
|
+
in_dim=in_dim,
|
|
540
|
+
out_dim=out_dim,
|
|
541
|
+
device=device,
|
|
542
|
+
)
|
|
543
|
+
elif method == "magic_gat":
|
|
544
|
+
# MAGIC's feature decoder: the concatenated encoder layers (`in_dim`) are projected to
|
|
545
|
+
# `node_out_dim` (`encoder_to_decoder`), then decoded by a GAT without final activation
|
|
546
|
+
return MagicGAT(
|
|
547
|
+
in_dim=in_dim,
|
|
548
|
+
hid_dim=cfg.training.node_hid_dim,
|
|
549
|
+
out_dim=out_dim,
|
|
550
|
+
n_layers=decoder_cfg.num_layers,
|
|
551
|
+
n_heads=decoder_cfg.num_heads,
|
|
552
|
+
feat_drop=0.1,
|
|
553
|
+
attn_drop=0.0,
|
|
554
|
+
negative_slope=decoder_cfg.negative_slope,
|
|
555
|
+
residual=True,
|
|
556
|
+
activation=activation_fn_factory(
|
|
557
|
+
decoder_cfg.activation or cfg.training.encoder.magic_gat.activation
|
|
558
|
+
),
|
|
559
|
+
is_decoder=True,
|
|
560
|
+
edge_dim=edge_dim,
|
|
561
|
+
in_proj_dim=cfg.training.node_out_dim,
|
|
562
|
+
)
|
|
563
|
+
elif method == "none":
|
|
564
|
+
if in_dim != out_dim:
|
|
565
|
+
raise ValueError(
|
|
566
|
+
f"Decoder `none` of objective `{objective}` requires the input of the decoder to have "
|
|
567
|
+
f"the expected output size ({out_dim}), found size {in_dim}. Use another decoder "
|
|
568
|
+
f"or set the encoder's output size (e.g. `training.node_out_dim`) to {out_dim}."
|
|
569
|
+
)
|
|
570
|
+
return lambda x: x
|
|
571
|
+
else:
|
|
572
|
+
raise ValueError(f"Invalid decoder {method}")
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
def _load_attack_features(cfg, edge_scores_path, top_n, all_data):
|
|
576
|
+
"""Extract x_src and x_dst tensors for the top-N highest-loss attack edges.
|
|
577
|
+
|
|
578
|
+
Matches edges from the edge_scores pickle (srcnode, dstnode, time) against
|
|
579
|
+
the already-preprocessed val+test graph data using original node IDs.
|
|
580
|
+
all_data is a tuple (val_data, test_data) where each element is a list of
|
|
581
|
+
dataset lists (list[list[CollatableTemporalData]]).
|
|
582
|
+
"""
|
|
583
|
+
import pandas as pd
|
|
584
|
+
from pidsmaker.utils.utils import log
|
|
585
|
+
|
|
586
|
+
edge_scores = torch.load(edge_scores_path, map_location="cpu")
|
|
587
|
+
top_attacks = edge_scores.nlargest(top_n, "loss")[["srcnode", "dstnode", "time"]]
|
|
588
|
+
attack_keys = set(
|
|
589
|
+
zip(top_attacks["srcnode"].tolist(),
|
|
590
|
+
top_attacks["dstnode"].tolist(),
|
|
591
|
+
top_attacks["time"].tolist())
|
|
592
|
+
)
|
|
593
|
+
|
|
594
|
+
atk_x_src_list, atk_x_dst_list, atk_edge_type_list = [], [], []
|
|
595
|
+
found_keys = set()
|
|
596
|
+
n_graphs_scanned = 0
|
|
597
|
+
|
|
598
|
+
for split_data in all_data: # (val_data, test_data)
|
|
599
|
+
for dataset in split_data: # list of datasets (multi-dataset)
|
|
600
|
+
for g in dataset: # individual time-window batches
|
|
601
|
+
g = materialize_batch(g)
|
|
602
|
+
# original_edge_index holds global IDs (before reindexing);
|
|
603
|
+
# g.src/g.dst have been overwritten with local 0..N-1 indices.
|
|
604
|
+
orig_ei = to_original_node_ids(g.original_edge_index).cpu()
|
|
605
|
+
src_np = orig_ei[0].numpy()
|
|
606
|
+
dst_np = orig_ei[1].numpy()
|
|
607
|
+
t_np = g.t.cpu().numpy()
|
|
608
|
+
n_graphs_scanned += 1
|
|
609
|
+
|
|
610
|
+
for i, (s, d, t) in enumerate(zip(src_np, dst_np, t_np)):
|
|
611
|
+
key = (int(s), int(d), int(t))
|
|
612
|
+
if key in attack_keys and key not in found_keys:
|
|
613
|
+
atk_x_src_list.append(g.x_src[i].cpu())
|
|
614
|
+
atk_x_dst_list.append(g.x_dst[i].cpu())
|
|
615
|
+
atk_edge_type_list.append(g.edge_type[i].cpu())
|
|
616
|
+
found_keys.add(key)
|
|
617
|
+
|
|
618
|
+
if not atk_x_src_list:
|
|
619
|
+
# Diagnostic: show sample values from both sides to help identify the mismatch
|
|
620
|
+
sample_attack = list(attack_keys)[:3]
|
|
621
|
+
sample_data = []
|
|
622
|
+
for split_data in all_data:
|
|
623
|
+
for dataset in split_data:
|
|
624
|
+
for g in dataset:
|
|
625
|
+
s0 = int(g.original_edge_index[0, 0].item())
|
|
626
|
+
d0 = int(g.original_edge_index[1, 0].item())
|
|
627
|
+
t0 = int(g.t[0].item())
|
|
628
|
+
sample_data.append((s0, d0, t0))
|
|
629
|
+
if len(sample_data) >= 3:
|
|
630
|
+
break
|
|
631
|
+
if len(sample_data) >= 3:
|
|
632
|
+
break
|
|
633
|
+
if len(sample_data) >= 3:
|
|
634
|
+
break
|
|
635
|
+
raise ValueError(
|
|
636
|
+
f"predict_edge_supervised: no attack edges found after scanning {n_graphs_scanned} graph batches.\n"
|
|
637
|
+
f" Attack keys (srcnode, dstnode, time) sample: {sample_attack}\n"
|
|
638
|
+
f" Graph data (src, dst, t) sample: {sample_data}\n"
|
|
639
|
+
"Check that the edge_scores_path matches the dataset being trained on."
|
|
640
|
+
)
|
|
641
|
+
|
|
642
|
+
log(
|
|
643
|
+
f"predict_edge_supervised: loaded {len(atk_x_src_list)}/{len(attack_keys)} "
|
|
644
|
+
f"attack edge features from '{edge_scores_path}'"
|
|
645
|
+
)
|
|
646
|
+
return torch.stack(atk_x_src_list), torch.stack(atk_x_dst_list), torch.stack(atk_edge_type_list)
|
|
647
|
+
|
|
648
|
+
|
|
649
|
+
def _load_attack_features_from_patterns(cfg, attack_patterns, max_edges_per_pattern, all_data):
|
|
650
|
+
"""Collect attack edge feature tensors by matching hand-crafted TTP patterns.
|
|
651
|
+
|
|
652
|
+
Each pattern is a dict with any subset of:
|
|
653
|
+
src_type : "file" | "subject" | "netflow"
|
|
654
|
+
src_label_contains : substring that must appear in the src node path/cmd
|
|
655
|
+
dst_type : "file" | "subject" | "netflow"
|
|
656
|
+
dst_label_contains : substring that must appear in the dst node path/cmd
|
|
657
|
+
edge_type : event name string, e.g. "EVENT_EXECUTE"
|
|
658
|
+
|
|
659
|
+
Omitting a field means "match any". At most `max_edges_per_pattern` edges
|
|
660
|
+
are collected per pattern. Duplicates across patterns are de-duplicated.
|
|
661
|
+
|
|
662
|
+
all_data is (val_data, test_data) — same structure as in _load_attack_features.
|
|
663
|
+
"""
|
|
664
|
+
from pidsmaker.utils.utils import get_indexid2msg, log
|
|
665
|
+
|
|
666
|
+
# node_id (int or str) -> [node_type_str, label_str]
|
|
667
|
+
indexid2msg = get_indexid2msg(cfg)
|
|
668
|
+
# Normalise keys to int for fast lookup
|
|
669
|
+
indexid2msg_int = {int(k): v for k, v in indexid2msg.items()}
|
|
670
|
+
|
|
671
|
+
rel2id_zero = get_rel2id(cfg, from_zero=True) # event_name -> 0-based index
|
|
672
|
+
|
|
673
|
+
atk_x_src_list, atk_x_dst_list, atk_edge_type_list = [], [], []
|
|
674
|
+
seen = set()
|
|
675
|
+
|
|
676
|
+
for pat_idx, pattern in enumerate(attack_patterns):
|
|
677
|
+
src_type = pattern.get("src_type")
|
|
678
|
+
src_contains = pattern.get("src_label_contains")
|
|
679
|
+
dst_type = pattern.get("dst_type")
|
|
680
|
+
dst_contains = pattern.get("dst_label_contains")
|
|
681
|
+
etype_name = pattern.get("edge_type")
|
|
682
|
+
etype_idx = rel2id_zero.get(etype_name) if etype_name else None
|
|
683
|
+
|
|
684
|
+
collected = 0
|
|
685
|
+
for split_data in all_data:
|
|
686
|
+
for dataset in split_data:
|
|
687
|
+
for g in dataset:
|
|
688
|
+
if collected >= max_edges_per_pattern:
|
|
689
|
+
break
|
|
690
|
+
g = materialize_batch(g)
|
|
691
|
+
|
|
692
|
+
orig_ei = to_original_node_ids(g.original_edge_index).cpu()
|
|
693
|
+
src_ids = orig_ei[0].tolist()
|
|
694
|
+
dst_ids = orig_ei[1].tolist()
|
|
695
|
+
etypes = g.edge_type # (E, num_edge_types)
|
|
696
|
+
|
|
697
|
+
for i, (s_id, d_id) in enumerate(zip(src_ids, dst_ids)):
|
|
698
|
+
if collected >= max_edges_per_pattern:
|
|
699
|
+
break
|
|
700
|
+
uid = (int(s_id), int(d_id), int(g.t[i].item()))
|
|
701
|
+
if uid in seen:
|
|
702
|
+
continue
|
|
703
|
+
|
|
704
|
+
s_info = indexid2msg_int.get(int(s_id))
|
|
705
|
+
d_info = indexid2msg_int.get(int(d_id))
|
|
706
|
+
if s_info is None or d_info is None:
|
|
707
|
+
continue
|
|
708
|
+
|
|
709
|
+
s_ntype, s_label = s_info[0], s_info[1]
|
|
710
|
+
d_ntype, d_label = d_info[0], d_info[1]
|
|
711
|
+
|
|
712
|
+
if src_type and s_ntype != src_type: continue
|
|
713
|
+
if src_contains and src_contains not in s_label: continue
|
|
714
|
+
if dst_type and d_ntype != dst_type: continue
|
|
715
|
+
if dst_contains and dst_contains not in d_label: continue
|
|
716
|
+
if etype_idx is not None:
|
|
717
|
+
if etypes[i].argmax().item() != etype_idx: continue
|
|
718
|
+
|
|
719
|
+
atk_x_src_list.append(g.x_src[i].cpu())
|
|
720
|
+
atk_x_dst_list.append(g.x_dst[i].cpu())
|
|
721
|
+
atk_edge_type_list.append(etypes[i].cpu())
|
|
722
|
+
seen.add(uid)
|
|
723
|
+
collected += 1
|
|
724
|
+
|
|
725
|
+
log(f" pattern[{pat_idx}] ({pattern}): collected {collected} edges")
|
|
726
|
+
|
|
727
|
+
if not atk_x_src_list:
|
|
728
|
+
raise ValueError(
|
|
729
|
+
"predict_edge_supervised (patterns mode): no edges matched any attack_patterns. "
|
|
730
|
+
"Check that pattern fields match the node types and labels in this dataset."
|
|
731
|
+
)
|
|
732
|
+
|
|
733
|
+
log(f"predict_edge_supervised: {len(atk_x_src_list)} attack edges collected from {len(attack_patterns)} patterns")
|
|
734
|
+
return torch.stack(atk_x_src_list), torch.stack(atk_x_dst_list), torch.stack(atk_edge_type_list)
|
|
735
|
+
|
|
736
|
+
|
|
737
|
+
def _load_attack_features_from_synthetic(cfg, attack_edges_path):
|
|
738
|
+
"""Build attack edge feature tensors from pre-computed synthetic node embeddings.
|
|
739
|
+
|
|
740
|
+
During feat_inference, feat_inference_pretrained embeds the synthetic attack node
|
|
741
|
+
labels (which may not exist in the real dataset) and writes them to
|
|
742
|
+
{model_dir}/synthetic_attack_node_embeddings.pt as {(ntype, label): np.ndarray}.
|
|
743
|
+
|
|
744
|
+
This function loads that file and constructs x_src, x_dst, edge_type tensors
|
|
745
|
+
with the same format as batch.x_src / batch.x_dst / batch.edge_type, so that
|
|
746
|
+
PredictEdgeSupervised can use them directly for 1:1 oversampling training.
|
|
747
|
+
"""
|
|
748
|
+
import yaml
|
|
749
|
+
from pidsmaker.config.pipeline import ROOT_PROJECT_PATH
|
|
750
|
+
from pidsmaker.utils.utils import gen_relation_onehot, log
|
|
751
|
+
|
|
752
|
+
if not os.path.isabs(attack_edges_path):
|
|
753
|
+
attack_edges_path = os.path.join(ROOT_PROJECT_PATH, attack_edges_path)
|
|
754
|
+
|
|
755
|
+
with open(attack_edges_path) as f:
|
|
756
|
+
data = yaml.safe_load(f)
|
|
757
|
+
attack_edges = data.get("attack_edges", [])
|
|
758
|
+
|
|
759
|
+
synth_emb_path = os.path.join(
|
|
760
|
+
cfg.featurization._model_dir, "synthetic_attack_node_embeddings.pt"
|
|
761
|
+
)
|
|
762
|
+
if not os.path.exists(synth_emb_path):
|
|
763
|
+
raise FileNotFoundError(
|
|
764
|
+
f"predict_edge_supervised (synthetic mode): embeddings file not found: {synth_emb_path}\n"
|
|
765
|
+
"Re-run feat_inference so that synthetic attack node embeddings are computed first."
|
|
766
|
+
)
|
|
767
|
+
synth_embs = torch.load(synth_emb_path, map_location="cpu") # {(ntype, label): np.ndarray}
|
|
768
|
+
|
|
769
|
+
ntype2oh = gen_relation_onehot(get_node_map(cfg)) # {type_str -> 1-D LongTensor}
|
|
770
|
+
etype2oh = gen_relation_onehot(get_rel2id(cfg)) # {event_str -> 1-D LongTensor}
|
|
771
|
+
|
|
772
|
+
node_feats_str = cfg.batching.node_features
|
|
773
|
+
selected_node_feats = [f.strip() for f in node_feats_str.replace("-", ",").split(",")]
|
|
774
|
+
|
|
775
|
+
atk_x_src_list, atk_x_dst_list, atk_edge_type_list = [], [], []
|
|
776
|
+
|
|
777
|
+
for edge in attack_edges:
|
|
778
|
+
src_type = edge["src_type"]
|
|
779
|
+
src_label = edge["src_label"]
|
|
780
|
+
etype_str = edge["edge_type"]
|
|
781
|
+
dst_type = edge["dst_type"]
|
|
782
|
+
dst_label = edge["dst_label"]
|
|
783
|
+
|
|
784
|
+
src_key = (src_type, src_label)
|
|
785
|
+
dst_key = (dst_type, dst_label)
|
|
786
|
+
|
|
787
|
+
if src_key not in synth_embs:
|
|
788
|
+
raise KeyError(
|
|
789
|
+
f"predict_edge_supervised (synthetic mode): no embedding for src node {src_key}. "
|
|
790
|
+
"Re-run feat_inference."
|
|
791
|
+
)
|
|
792
|
+
if dst_key not in synth_embs:
|
|
793
|
+
raise KeyError(
|
|
794
|
+
f"predict_edge_supervised (synthetic mode): no embedding for dst node {dst_key}. "
|
|
795
|
+
"Re-run feat_inference."
|
|
796
|
+
)
|
|
797
|
+
|
|
798
|
+
src_emb = torch.from_numpy(synth_embs[src_key]).float()
|
|
799
|
+
dst_emb = torch.from_numpy(synth_embs[dst_key]).float()
|
|
800
|
+
|
|
801
|
+
x_src_parts, x_dst_parts = [], []
|
|
802
|
+
for feat in selected_node_feats:
|
|
803
|
+
if feat == "node_emb":
|
|
804
|
+
x_src_parts.append(src_emb)
|
|
805
|
+
x_dst_parts.append(dst_emb)
|
|
806
|
+
elif feat == "node_type":
|
|
807
|
+
x_src_parts.append(ntype2oh[src_type].float())
|
|
808
|
+
x_dst_parts.append(ntype2oh[dst_type].float())
|
|
809
|
+
elif feat in ("only_ones", "edges_distribution"):
|
|
810
|
+
raise ValueError(
|
|
811
|
+
f"predict_edge_supervised (synthetic mode): node feature '{feat}' "
|
|
812
|
+
"is not supported for synthetic edges."
|
|
813
|
+
)
|
|
814
|
+
|
|
815
|
+
atk_x_src_list.append(torch.cat(x_src_parts))
|
|
816
|
+
atk_x_dst_list.append(torch.cat(x_dst_parts))
|
|
817
|
+
atk_edge_type_list.append(etype2oh[etype_str].float())
|
|
818
|
+
|
|
819
|
+
log(f"predict_edge_supervised: {len(atk_x_src_list)} synthetic attack edges loaded from '{attack_edges_path}'")
|
|
820
|
+
return torch.stack(atk_x_src_list), torch.stack(atk_x_dst_list), torch.stack(atk_edge_type_list)
|
|
821
|
+
|
|
822
|
+
|
|
823
|
+
def encoder_out_dim(cfg):
|
|
824
|
+
"""Size of the node embeddings `h` returned by the encoder."""
|
|
825
|
+
if "magic_gat" in cfg.training.encoder.used_methods:
|
|
826
|
+
# MAGIC's encoder returns the concatenation of all its layers
|
|
827
|
+
n_layers = cfg.training.encoder.magic_gat.num_layers
|
|
828
|
+
return (n_layers - 1) * cfg.training.node_hid_dim + cfg.training.node_out_dim
|
|
829
|
+
return cfg.training.node_out_dim
|
|
830
|
+
|
|
831
|
+
|
|
832
|
+
def objective_factory(cfg, in_dim, graph_reindexer, device, objective_cfg=None, all_data=None, edge_dim=None):
|
|
833
|
+
if objective_cfg is None:
|
|
834
|
+
objective_cfg = cfg.training.decoder
|
|
835
|
+
# Size of the node embeddings `h` given to the decoders
|
|
836
|
+
node_out_dim = encoder_out_dim(cfg)
|
|
837
|
+
node_hid_dim = cfg.training.node_hid_dim
|
|
838
|
+
|
|
839
|
+
entity_map = get_node_map(cfg, from_zero=True)
|
|
840
|
+
event_map = get_rel2id(cfg, from_zero=True)
|
|
841
|
+
|
|
842
|
+
objectives = []
|
|
843
|
+
for objective in map(lambda x: x.strip(), objective_cfg.used_methods.split(",")):
|
|
844
|
+
method = getattr(getattr(objective_cfg, objective.strip()), "decoder")
|
|
845
|
+
|
|
846
|
+
if objective not in OBJECTIVES_WITHOUT_DECODER and not decoder_matches_objective(
|
|
847
|
+
decoder=method, objective=objective
|
|
848
|
+
):
|
|
849
|
+
raise ValueError(f"Decoder {method} doesn't match with objective {objective}")
|
|
850
|
+
|
|
851
|
+
if objective == "reconstruct_node_features":
|
|
852
|
+
loss_fn = recon_loss_fn_factory(objective_cfg.reconstruct_node_features.loss)
|
|
853
|
+
|
|
854
|
+
decoder = decoder_factory(
|
|
855
|
+
method, objective, cfg, in_dim=node_out_dim, out_dim=in_dim, device=device
|
|
856
|
+
)
|
|
857
|
+
objectives.append(NodeFeatReconstruction(decoder=decoder, loss_fn=loss_fn))
|
|
858
|
+
|
|
859
|
+
elif objective == "reconstruct_node_embeddings":
|
|
860
|
+
loss_fn = recon_loss_fn_factory(objective_cfg.reconstruct_node_embeddings.loss)
|
|
861
|
+
|
|
862
|
+
decoder = decoder_factory(
|
|
863
|
+
method, objective, cfg, in_dim=node_out_dim, out_dim=node_out_dim, device=device
|
|
864
|
+
)
|
|
865
|
+
objectives.append(NodeEmbReconstruction(decoder=decoder, loss_fn=loss_fn))
|
|
866
|
+
|
|
867
|
+
elif objective == "reconstruct_edge_embeddings":
|
|
868
|
+
loss_fn = recon_loss_fn_factory(objective_cfg.reconstruct_edge_embeddings.loss)
|
|
869
|
+
|
|
870
|
+
decoder = decoder_factory(
|
|
871
|
+
method, objective, cfg, in_dim=node_out_dim, out_dim=node_out_dim * 2, device=device
|
|
872
|
+
)
|
|
873
|
+
objectives.append(
|
|
874
|
+
EdgeEmbReconstruction(
|
|
875
|
+
decoder=decoder,
|
|
876
|
+
loss_fn=loss_fn,
|
|
877
|
+
)
|
|
878
|
+
)
|
|
879
|
+
|
|
880
|
+
elif objective == "predict_edge_type":
|
|
881
|
+
loss = objective_cfg.predict_edge_type.loss or "cross_entropy"
|
|
882
|
+
version = objective_cfg.predict_edge_type.AMS.version
|
|
883
|
+
margin = objective_cfg.predict_edge_type.AMS.margin
|
|
884
|
+
scale = objective_cfg.predict_edge_type.AMS.scale
|
|
885
|
+
|
|
886
|
+
num_edge_types = get_num_edge_type(cfg)
|
|
887
|
+
decoder_out_dim = node_out_dim if loss =="AMS" else num_edge_types
|
|
888
|
+
|
|
889
|
+
multi_edge = False
|
|
890
|
+
loss_fn = categorical_loss_fn_factory("BCE") if multi_edge else \
|
|
891
|
+
special_categorical_loss_fn_factory(
|
|
892
|
+
loss, out_dim=decoder_out_dim, num_classes=num_edge_types, version=version, margin=margin, scale=scale)
|
|
893
|
+
|
|
894
|
+
balanced_loss = objective_cfg.predict_edge_type.balanced_loss
|
|
895
|
+
decoder = decoder_factory(
|
|
896
|
+
method, objective, cfg, in_dim=node_out_dim, out_dim=decoder_out_dim, device=device
|
|
897
|
+
)
|
|
898
|
+
objectives.append(
|
|
899
|
+
EdgeTypePrediction(
|
|
900
|
+
decoder=decoder,
|
|
901
|
+
loss_fn=loss_fn,
|
|
902
|
+
balanced_loss=balanced_loss,
|
|
903
|
+
edge_type_dim=num_edge_types,
|
|
904
|
+
# BCE is computed on the one-hot edge types, not on class indices
|
|
905
|
+
multi_edge=multi_edge or loss == "BCE",
|
|
906
|
+
)
|
|
907
|
+
)
|
|
908
|
+
|
|
909
|
+
elif objective == "predict_node_type":
|
|
910
|
+
loss_fn = categorical_loss_fn_factory("cross_entropy")
|
|
911
|
+
balanced_loss = objective_cfg.predict_node_type.balanced_loss
|
|
912
|
+
|
|
913
|
+
# The decoder predicts one logit per node type
|
|
914
|
+
decoder = decoder_factory(
|
|
915
|
+
method,
|
|
916
|
+
objective,
|
|
917
|
+
cfg,
|
|
918
|
+
in_dim=node_out_dim,
|
|
919
|
+
out_dim=cfg.dataset.num_node_types,
|
|
920
|
+
device=device,
|
|
921
|
+
)
|
|
922
|
+
objectives.append(
|
|
923
|
+
NodeTypePrediction(
|
|
924
|
+
decoder=decoder,
|
|
925
|
+
loss_fn=loss_fn,
|
|
926
|
+
balanced_loss=balanced_loss,
|
|
927
|
+
node_type_dim=cfg.dataset.num_node_types,
|
|
928
|
+
)
|
|
929
|
+
)
|
|
930
|
+
|
|
931
|
+
elif objective == "predict_process_tag":
|
|
932
|
+
node_classes, num_known = process_tag_classes_from_cfg(cfg)
|
|
933
|
+
# One logit per process tag seen in training, plus one for the unknown tags
|
|
934
|
+
decoder = decoder_factory(
|
|
935
|
+
method, objective, cfg, in_dim=node_out_dim, out_dim=num_known + 1, device=device
|
|
936
|
+
)
|
|
937
|
+
objectives.append(
|
|
938
|
+
ProcessTagPrediction(
|
|
939
|
+
decoder=decoder,
|
|
940
|
+
node_classes=node_classes,
|
|
941
|
+
num_known=num_known,
|
|
942
|
+
balanced_loss=objective_cfg.predict_process_tag.balanced_loss,
|
|
943
|
+
detection=(objective_cfg.predict_process_tag.detection or "loss").strip(),
|
|
944
|
+
)
|
|
945
|
+
)
|
|
946
|
+
|
|
947
|
+
elif objective == "reconstruct_masked_features":
|
|
948
|
+
mask_rate = objective_cfg.reconstruct_masked_features.mask_rate
|
|
949
|
+
|
|
950
|
+
loss_fn = recon_loss_fn_factory(objective_cfg.reconstruct_masked_features.loss)
|
|
951
|
+
|
|
952
|
+
decoder = decoder_factory(
|
|
953
|
+
method,
|
|
954
|
+
objective,
|
|
955
|
+
cfg,
|
|
956
|
+
in_dim=node_out_dim,
|
|
957
|
+
out_dim=in_dim,
|
|
958
|
+
device=device,
|
|
959
|
+
edge_dim=edge_dim,
|
|
960
|
+
)
|
|
961
|
+
objectives.append(
|
|
962
|
+
GMAEFeatReconstruction(
|
|
963
|
+
decoder=decoder,
|
|
964
|
+
loss_fn=loss_fn,
|
|
965
|
+
mask_rate=mask_rate,
|
|
966
|
+
embed_dim=in_dim, # Node feature dimension for mask_token
|
|
967
|
+
)
|
|
968
|
+
)
|
|
969
|
+
|
|
970
|
+
elif objective == "predict_masked_struct":
|
|
971
|
+
loss_fn = categorical_loss_fn_factory(objective_cfg.predict_masked_struct.loss)
|
|
972
|
+
|
|
973
|
+
decoder = decoder_factory(
|
|
974
|
+
method, objective, cfg, in_dim=node_out_dim * 2, out_dim=1, device=device
|
|
975
|
+
)
|
|
976
|
+
objectives.append(
|
|
977
|
+
GMAEStructPrediction(
|
|
978
|
+
decoder=decoder,
|
|
979
|
+
loss_fn=loss_fn,
|
|
980
|
+
max_samples=objective_cfg.predict_masked_struct.max_samples,
|
|
981
|
+
)
|
|
982
|
+
)
|
|
983
|
+
|
|
984
|
+
elif objective == "one_class":
|
|
985
|
+
oc = objective_cfg.one_class
|
|
986
|
+
decoder = decoder_factory(
|
|
987
|
+
method, objective, cfg, in_dim=node_out_dim, out_dim=node_out_dim, device=device
|
|
988
|
+
)
|
|
989
|
+
objectives.append(
|
|
990
|
+
OneClass(
|
|
991
|
+
decoder=decoder,
|
|
992
|
+
embed_dim=node_out_dim,
|
|
993
|
+
beta=oc.beta,
|
|
994
|
+
eps=oc.eps,
|
|
995
|
+
warmup=oc.warmup,
|
|
996
|
+
num_node_types=cfg.dataset.num_node_types,
|
|
997
|
+
)
|
|
998
|
+
)
|
|
999
|
+
|
|
1000
|
+
elif objective == "detect_edge_few_shot":
|
|
1001
|
+
classes = 2
|
|
1002
|
+
decoder = decoder_factory(
|
|
1003
|
+
method,
|
|
1004
|
+
objective,
|
|
1005
|
+
cfg,
|
|
1006
|
+
in_dim=node_out_dim,
|
|
1007
|
+
out_dim=classes,
|
|
1008
|
+
device=device,
|
|
1009
|
+
objective_cfg=objective_cfg,
|
|
1010
|
+
)
|
|
1011
|
+
|
|
1012
|
+
objectives.append(
|
|
1013
|
+
FewShotEdgeDetection(
|
|
1014
|
+
decoder=decoder,
|
|
1015
|
+
loss_fn=categorical_loss_fn_factory("cross_entropy"),
|
|
1016
|
+
)
|
|
1017
|
+
)
|
|
1018
|
+
|
|
1019
|
+
elif objective == "autoencode_edge_embeddings":
|
|
1020
|
+
use_edge_feats = bool(objective_cfg.autoencode_edge_embeddings.use_edge_feats)
|
|
1021
|
+
if use_edge_feats and not edge_dim:
|
|
1022
|
+
raise ValueError(
|
|
1023
|
+
"autoencode_edge_embeddings.use_edge_feats requires edge features "
|
|
1024
|
+
"(`batching.edge_features`)."
|
|
1025
|
+
)
|
|
1026
|
+
objectives.append(
|
|
1027
|
+
EdgeEmbAutoencoder(
|
|
1028
|
+
node_dim=node_out_dim,
|
|
1029
|
+
hid_dim=node_hid_dim,
|
|
1030
|
+
edge_dim=edge_dim or 0,
|
|
1031
|
+
use_edge_feats=use_edge_feats,
|
|
1032
|
+
)
|
|
1033
|
+
)
|
|
1034
|
+
|
|
1035
|
+
elif objective == "deep_graph_infomax":
|
|
1036
|
+
objectives.append(
|
|
1037
|
+
DeepGraphInfomax(
|
|
1038
|
+
embed_dim=node_out_dim,
|
|
1039
|
+
pca_components=objective_cfg.deep_graph_infomax.pca_components or 8,
|
|
1040
|
+
)
|
|
1041
|
+
)
|
|
1042
|
+
|
|
1043
|
+
elif objective == "predict_edge_contrastive":
|
|
1044
|
+
predict_edge_method = objective_cfg.predict_edge_contrastive.decoder.strip()
|
|
1045
|
+
|
|
1046
|
+
if predict_edge_method == "inner_product":
|
|
1047
|
+
edge_decoder = EdgeInnerProductDecoder(
|
|
1048
|
+
dropout=objective_cfg.predict_edge_contrastive.inner_product.dropout,
|
|
1049
|
+
negate=bool(objective_cfg.predict_edge_contrastive.inner_product.negate),
|
|
1050
|
+
)
|
|
1051
|
+
|
|
1052
|
+
else:
|
|
1053
|
+
edge_decoder = decoder_factory(
|
|
1054
|
+
method,
|
|
1055
|
+
objective,
|
|
1056
|
+
cfg,
|
|
1057
|
+
in_dim=node_out_dim,
|
|
1058
|
+
out_dim=1,
|
|
1059
|
+
device=device,
|
|
1060
|
+
objective_cfg=objective_cfg,
|
|
1061
|
+
)
|
|
1062
|
+
|
|
1063
|
+
loss_name = (objective_cfg.predict_edge_contrastive.loss or "bce").strip()
|
|
1064
|
+
if loss_name == "ap":
|
|
1065
|
+
margin = objective_cfg.predict_edge_contrastive.ap_margin or 0.8
|
|
1066
|
+
loss_fn = lambda pos, neg, **kw: ap_contrastive(pos, neg, margin=margin, **kw)
|
|
1067
|
+
elif loss_name == "bpr":
|
|
1068
|
+
loss_fn = bpr_contrastive
|
|
1069
|
+
else:
|
|
1070
|
+
loss_fn = bce_contrastive
|
|
1071
|
+
|
|
1072
|
+
objectives.append(
|
|
1073
|
+
EdgeContrastivePrediction(
|
|
1074
|
+
decoder=edge_decoder,
|
|
1075
|
+
loss_fn=loss_fn,
|
|
1076
|
+
graph_reindexer=graph_reindexer,
|
|
1077
|
+
neg_sampling=(objective_cfg.predict_edge_contrastive.neg_sampling or "shuffle_dst").strip(),
|
|
1078
|
+
neg_ratio=objective_cfg.predict_edge_contrastive.neg_ratio or 1.0,
|
|
1079
|
+
)
|
|
1080
|
+
)
|
|
1081
|
+
|
|
1082
|
+
elif objective == "predict_edge_supervised":
|
|
1083
|
+
obj_cfg = objective_cfg.predict_edge_supervised
|
|
1084
|
+
|
|
1085
|
+
mode = obj_cfg.mode.strip()
|
|
1086
|
+
if mode == "synthetic":
|
|
1087
|
+
atk_x_src, atk_x_dst, atk_edge_type = _load_attack_features_from_synthetic(
|
|
1088
|
+
cfg,
|
|
1089
|
+
attack_edges_path=obj_cfg.attack_edges_path,
|
|
1090
|
+
)
|
|
1091
|
+
else:
|
|
1092
|
+
if all_data is None:
|
|
1093
|
+
raise ValueError(
|
|
1094
|
+
f"predict_edge_supervised (mode='{mode}') requires val/test data. "
|
|
1095
|
+
"Pass all_data=(val_data, test_data) to build_model()."
|
|
1096
|
+
)
|
|
1097
|
+
if mode == "scores":
|
|
1098
|
+
atk_x_src, atk_x_dst, atk_edge_type = _load_attack_features(
|
|
1099
|
+
cfg,
|
|
1100
|
+
edge_scores_path=obj_cfg.edge_scores_path,
|
|
1101
|
+
top_n=obj_cfg.top_n_attacks,
|
|
1102
|
+
all_data=all_data,
|
|
1103
|
+
)
|
|
1104
|
+
elif mode == "patterns":
|
|
1105
|
+
atk_x_src, atk_x_dst, atk_edge_type = _load_attack_features_from_patterns(
|
|
1106
|
+
cfg,
|
|
1107
|
+
attack_patterns=obj_cfg.attack_patterns,
|
|
1108
|
+
max_edges_per_pattern=obj_cfg.max_edges_per_pattern,
|
|
1109
|
+
all_data=all_data,
|
|
1110
|
+
)
|
|
1111
|
+
else:
|
|
1112
|
+
raise ValueError(
|
|
1113
|
+
f"predict_edge_supervised: unknown mode '{mode}'. Use 'scores', 'patterns', or 'synthetic'."
|
|
1114
|
+
)
|
|
1115
|
+
|
|
1116
|
+
# Decoder input = [x_src | edge_type] and [x_dst | edge_type]
|
|
1117
|
+
edge_type_dim = get_num_edge_type(cfg)
|
|
1118
|
+
supervised_in_dim = in_dim + edge_type_dim
|
|
1119
|
+
decoder = decoder_factory(
|
|
1120
|
+
method, objective, cfg, in_dim=supervised_in_dim, out_dim=1, device=device
|
|
1121
|
+
)
|
|
1122
|
+
objectives.append(
|
|
1123
|
+
PredictEdgeSupervised(
|
|
1124
|
+
decoder=decoder,
|
|
1125
|
+
atk_x_src=atk_x_src.to(device),
|
|
1126
|
+
atk_x_dst=atk_x_dst.to(device),
|
|
1127
|
+
atk_edge_type=atk_edge_type.to(device),
|
|
1128
|
+
pos_weight=obj_cfg.pos_weight,
|
|
1129
|
+
)
|
|
1130
|
+
)
|
|
1131
|
+
|
|
1132
|
+
elif objective == "predict_snapshot_embedding":
|
|
1133
|
+
objectives.append(
|
|
1134
|
+
SnapshotEmbeddingPrediction(
|
|
1135
|
+
rsg_vectors=load_graph2vec_rsg_vectors(cfg),
|
|
1136
|
+
top_k=objective_cfg.predict_snapshot_embedding.top_k or 0,
|
|
1137
|
+
)
|
|
1138
|
+
)
|
|
1139
|
+
|
|
1140
|
+
else:
|
|
1141
|
+
raise ValueError(f"Invalid objective {objective}")
|
|
1142
|
+
|
|
1143
|
+
# We wrap objectives into this class to calculate some metrics on validation set easily
|
|
1144
|
+
# This is useful only if use_few_shot is True
|
|
1145
|
+
is_edge_type_prediction = objective_cfg.used_methods.strip() == "predict_edge_type"
|
|
1146
|
+
objective_names = [o.strip() for o in objective_cfg.used_methods.split(",")]
|
|
1147
|
+
objectives = [
|
|
1148
|
+
ValidationWrapper(
|
|
1149
|
+
objective,
|
|
1150
|
+
graph_reindexer,
|
|
1151
|
+
is_edge_type_prediction,
|
|
1152
|
+
use_few_shot=cfg.training.decoder.use_few_shot,
|
|
1153
|
+
)
|
|
1154
|
+
for objective in objectives
|
|
1155
|
+
]
|
|
1156
|
+
for name, objective in zip(objective_names, objectives):
|
|
1157
|
+
objective.is_node_level = name in OBJECTIVES_NODE_LEVEL
|
|
1158
|
+
|
|
1159
|
+
return objectives
|
|
1160
|
+
|
|
1161
|
+
|
|
1162
|
+
def check_snapshot_batching(cfg):
|
|
1163
|
+
"""Snapshot-level components (ProGrapher) need one graph per time window."""
|
|
1164
|
+
batching = cfg.batching
|
|
1165
|
+
methods = {
|
|
1166
|
+
"global_batching.used_method": batching.global_batching.used_method,
|
|
1167
|
+
"intra_graph_batching.used_methods": batching.intra_graph_batching.used_methods,
|
|
1168
|
+
"inter_graph_batching.used_method": batching.inter_graph_batching.used_method,
|
|
1169
|
+
}
|
|
1170
|
+
batched = [f"batching.{k}={v}" for k, v in methods.items() if (v or "none").strip() != "none"]
|
|
1171
|
+
if batched:
|
|
1172
|
+
raise ValueError(
|
|
1173
|
+
"The `textrcnn` encoder embeds each time window as a whole (one snapshot per graph): "
|
|
1174
|
+
f"set {', '.join(batched)} to `none`."
|
|
1175
|
+
)
|
|
1176
|
+
if cfg.featurization.used_method.strip() != "graph2vec":
|
|
1177
|
+
raise ValueError(
|
|
1178
|
+
"The `textrcnn` encoder predicts graph2vec snapshot embeddings: it requires "
|
|
1179
|
+
"`featurization.used_method=graph2vec`."
|
|
1180
|
+
)
|
|
1181
|
+
|
|
1182
|
+
|
|
1183
|
+
def load_graph2vec_rsg_vectors(cfg):
|
|
1184
|
+
"""(V, d) output vectors of the rooted subgraphs of the graph2vec model (ProGrapher)."""
|
|
1185
|
+
from gensim.models.doc2vec import Doc2Vec
|
|
1186
|
+
|
|
1187
|
+
from pidsmaker.featurization.featurization_methods.featurization_graph2vec import MODEL_FILE
|
|
1188
|
+
|
|
1189
|
+
if cfg.featurization.used_method.strip() != "graph2vec":
|
|
1190
|
+
raise ValueError(
|
|
1191
|
+
"The `predict_snapshot_embedding` objective requires `featurization.used_method=graph2vec`."
|
|
1192
|
+
)
|
|
1193
|
+
model = Doc2Vec.load(os.path.join(cfg.featurization._model_dir, MODEL_FILE))
|
|
1194
|
+
return torch.from_numpy(model.syn1neg.copy())
|
|
1195
|
+
|
|
1196
|
+
|
|
1197
|
+
def few_shot_decoder_factory(cfg, graph_reindexer, device, objective_cfg=None):
|
|
1198
|
+
"""Build few-shot detection decoder if enabled.
|
|
1199
|
+
|
|
1200
|
+
Args:
|
|
1201
|
+
cfg: Configuration object
|
|
1202
|
+
graph_reindexer: Graph reindexing utility
|
|
1203
|
+
device: PyTorch device
|
|
1204
|
+
objective_cfg: Objective-specific config (optional)
|
|
1205
|
+
|
|
1206
|
+
Returns:
|
|
1207
|
+
nn.ModuleList or None: Few-shot objectives if enabled, else None
|
|
1208
|
+
"""
|
|
1209
|
+
if not cfg.training.decoder.use_few_shot:
|
|
1210
|
+
return None
|
|
1211
|
+
|
|
1212
|
+
node_out_dim = encoder_out_dim(cfg)
|
|
1213
|
+
objective_cfg = cfg.training.decoder.few_shot.decoder
|
|
1214
|
+
|
|
1215
|
+
objective = objective_factory(
|
|
1216
|
+
cfg,
|
|
1217
|
+
in_dim=node_out_dim,
|
|
1218
|
+
graph_reindexer=graph_reindexer,
|
|
1219
|
+
device=device,
|
|
1220
|
+
objective_cfg=objective_cfg,
|
|
1221
|
+
)
|
|
1222
|
+
return nn.ModuleList(objective)
|
|
1223
|
+
|
|
1224
|
+
|
|
1225
|
+
def edge_decoder_factory(edge_decoder, in_dim):
|
|
1226
|
+
"""Build edge decoder (MLP or none).
|
|
1227
|
+
|
|
1228
|
+
Args:
|
|
1229
|
+
edge_decoder: Decoder type string
|
|
1230
|
+
in_dim: Input dimension
|
|
1231
|
+
|
|
1232
|
+
Returns:
|
|
1233
|
+
nn.Module or None: Edge decoder module
|
|
1234
|
+
"""
|
|
1235
|
+
if edge_decoder == "MLP":
|
|
1236
|
+
return nn.Sequential(
|
|
1237
|
+
nn.Linear(in_dim, in_dim * 2),
|
|
1238
|
+
nn.ReLU(),
|
|
1239
|
+
nn.Linear(in_dim * 2, in_dim),
|
|
1240
|
+
)
|
|
1241
|
+
elif edge_decoder == "none":
|
|
1242
|
+
return None
|
|
1243
|
+
|
|
1244
|
+
raise ValueError(f"Invalid edge decoder {edge_decoder}")
|
|
1245
|
+
|
|
1246
|
+
|
|
1247
|
+
def recon_loss_fn_factory(loss: str):
|
|
1248
|
+
"""Create reconstruction loss function (SCE, MSE, MAE, etc.).
|
|
1249
|
+
|
|
1250
|
+
Args:
|
|
1251
|
+
loss: Loss function name
|
|
1252
|
+
|
|
1253
|
+
Returns:
|
|
1254
|
+
Loss function
|
|
1255
|
+
|
|
1256
|
+
Raises:
|
|
1257
|
+
ValueError: If loss function name is invalid
|
|
1258
|
+
"""
|
|
1259
|
+
if loss == "SCE":
|
|
1260
|
+
return sce_loss
|
|
1261
|
+
if loss == "MSE":
|
|
1262
|
+
return mse_loss
|
|
1263
|
+
if loss == "MSE_sum":
|
|
1264
|
+
return mse_loss_sum
|
|
1265
|
+
if loss == "MAE":
|
|
1266
|
+
return mae_loss
|
|
1267
|
+
if loss == "none":
|
|
1268
|
+
return nn.Identity()
|
|
1269
|
+
raise ValueError(f"Invalid loss function {loss}")
|
|
1270
|
+
|
|
1271
|
+
|
|
1272
|
+
def categorical_loss_fn_factory(loss: str):
|
|
1273
|
+
"""Create categorical loss function (cross_entropy or BCE).
|
|
1274
|
+
|
|
1275
|
+
Args:
|
|
1276
|
+
loss: Loss function name
|
|
1277
|
+
|
|
1278
|
+
Returns:
|
|
1279
|
+
Loss function
|
|
1280
|
+
|
|
1281
|
+
Raises:
|
|
1282
|
+
ValueError: If loss function name is invalid
|
|
1283
|
+
"""
|
|
1284
|
+
if loss == "cross_entropy":
|
|
1285
|
+
return cross_entropy
|
|
1286
|
+
if loss == "BCE":
|
|
1287
|
+
return binary_cross_entropy
|
|
1288
|
+
raise ValueError(f"Invalid loss function {loss}")
|
|
1289
|
+
|
|
1290
|
+
def special_categorical_loss_fn_factory(loss: str, out_dim: int, num_classes: int, version, margin, scale):
|
|
1291
|
+
if loss == "AMS":
|
|
1292
|
+
if version == 1:
|
|
1293
|
+
return AdMSoftmaxLoss(emb_dim=out_dim, num_classes=num_classes, margin=margin, scale=scale)
|
|
1294
|
+
elif version == 2:
|
|
1295
|
+
return AMSoftmax(emb_dim=out_dim, num_classes=num_classes, margin=margin, scale=scale)
|
|
1296
|
+
raise ValueError(f"Invalid version {version}")
|
|
1297
|
+
|
|
1298
|
+
return categorical_loss_fn_factory(loss)
|
|
1299
|
+
|
|
1300
|
+
def parse_int_list(value):
|
|
1301
|
+
"""Parses a list of integers given as `32,16` (read as a tuple by the config), `32` or a list."""
|
|
1302
|
+
if isinstance(value, (list, tuple)):
|
|
1303
|
+
return [int(v) for v in value]
|
|
1304
|
+
return [int(v) for v in str(value).strip("()[] ").split(",") if v.strip()]
|
|
1305
|
+
|
|
1306
|
+
|
|
1307
|
+
def activation_fn_factory(activation: str):
|
|
1308
|
+
"""Create activation function (sigmoid, relu, tanh, prelu, etc.).
|
|
1309
|
+
|
|
1310
|
+
Args:
|
|
1311
|
+
activation: Activation function name
|
|
1312
|
+
|
|
1313
|
+
Returns:
|
|
1314
|
+
nn.Module: Activation function
|
|
1315
|
+
|
|
1316
|
+
Raises:
|
|
1317
|
+
ValueError: If activation function name is invalid
|
|
1318
|
+
"""
|
|
1319
|
+
if activation == "sigmoid":
|
|
1320
|
+
return nn.Sigmoid()
|
|
1321
|
+
if activation == "relu":
|
|
1322
|
+
return nn.ReLU()
|
|
1323
|
+
if activation == "tanh":
|
|
1324
|
+
return nn.Tanh()
|
|
1325
|
+
if activation == "prelu":
|
|
1326
|
+
return nn.PReLU()
|
|
1327
|
+
if activation == "none":
|
|
1328
|
+
return nn.Identity()
|
|
1329
|
+
raise ValueError(f"Invalid activation function {activation}")
|
|
1330
|
+
|
|
1331
|
+
|
|
1332
|
+
def optimizer_factory(cfg, parameters):
|
|
1333
|
+
lr = cfg.training.lr
|
|
1334
|
+
weight_decay = cfg.training.weight_decay
|
|
1335
|
+
stable = cfg.training.stable_optim
|
|
1336
|
+
|
|
1337
|
+
if stable:
|
|
1338
|
+
return torch.optim.AdamW(
|
|
1339
|
+
parameters, lr=lr, betas=(0.9, 0.99), eps=1e-10,
|
|
1340
|
+
weight_decay=0.02,
|
|
1341
|
+
)
|
|
1342
|
+
return torch.optim.Adam(parameters, lr=lr, weight_decay=weight_decay)
|
|
1343
|
+
|
|
1344
|
+
|
|
1345
|
+
def optimizer_few_shot_factory(cfg, parameters):
|
|
1346
|
+
"""Create Adam optimizer for few-shot learning with separate hyperparameters.
|
|
1347
|
+
|
|
1348
|
+
Args:
|
|
1349
|
+
cfg: Configuration with few-shot specific lr and weight_decay
|
|
1350
|
+
parameters: Few-shot decoder parameters to optimize
|
|
1351
|
+
|
|
1352
|
+
Returns:
|
|
1353
|
+
torch.optim.Adam: Configured optimizer
|
|
1354
|
+
"""
|
|
1355
|
+
lr = cfg.training.decoder.few_shot.lr_few_shot
|
|
1356
|
+
weight_decay = cfg.training.decoder.few_shot.weight_decay_few_shot
|
|
1357
|
+
|
|
1358
|
+
return torch.optim.Adam(parameters, lr=lr, weight_decay=weight_decay)
|
|
1359
|
+
|
|
1360
|
+
|
|
1361
|
+
def early_stop_tracker_factory(cfg):
|
|
1362
|
+
"""Build the per-type validation early-stop tracker used by the training loop.
|
|
1363
|
+
|
|
1364
|
+
Returns None when no such tracker is configured. OCR-APT's is currently the only
|
|
1365
|
+
implementation; imported locally to avoid a cycle with `detection.training_methods`.
|
|
1366
|
+
|
|
1367
|
+
Args:
|
|
1368
|
+
cfg: Configuration, checked for `training.ocrapt_early_stop.enabled`
|
|
1369
|
+
|
|
1370
|
+
Returns:
|
|
1371
|
+
A tracker exposing `after_eval_epoch(cfg, model, train_data, epoch) -> bool`, or None
|
|
1372
|
+
"""
|
|
1373
|
+
from pidsmaker.detection.training_methods.ocrapt_early_stop import OCRAPTEarlyStop
|
|
1374
|
+
|
|
1375
|
+
ocrapt_cfg = getattr(cfg.training, "ocrapt_early_stop", None)
|
|
1376
|
+
if ocrapt_cfg is None or not ocrapt_cfg.enabled:
|
|
1377
|
+
return None
|
|
1378
|
+
|
|
1379
|
+
return OCRAPTEarlyStop(
|
|
1380
|
+
num_node_types=cfg.dataset.num_node_types,
|
|
1381
|
+
patience=ocrapt_cfg.patience,
|
|
1382
|
+
min_delta=ocrapt_cfg.min_delta,
|
|
1383
|
+
max_delta=ocrapt_cfg.max_delta,
|
|
1384
|
+
)
|
|
1385
|
+
|
|
1386
|
+
|
|
1387
|
+
def node_scorer_factory(cfg):
|
|
1388
|
+
"""Build the scorer of the nodes of node-level objectives, at inference and evaluation.
|
|
1389
|
+
|
|
1390
|
+
ThreaTrace, FLASH and MAGIC threshold scores of their own, computed at inference (see
|
|
1391
|
+
`pidsmaker.detection.node_scoring`); the other threshold methods threshold the node losses.
|
|
1392
|
+
|
|
1393
|
+
Args:
|
|
1394
|
+
cfg: Configuration, checked for `evaluation.node_evaluation.threshold_method`
|
|
1395
|
+
|
|
1396
|
+
Returns:
|
|
1397
|
+
A `NodeScorer`
|
|
1398
|
+
"""
|
|
1399
|
+
scorers = {"threatrace": ThreaTraceScorer, "flash": FlashScorer, "magic": MagicScorer}
|
|
1400
|
+
return scorers.get(cfg.evaluation.node_evaluation.threshold_method, NodeScorer)(cfg)
|
|
1401
|
+
|
|
1402
|
+
|
|
1403
|
+
def get_dimensions_from_data_sample(data):
|
|
1404
|
+
"""Extract dimensions from data sample for model initialization.
|
|
1405
|
+
|
|
1406
|
+
Args:
|
|
1407
|
+
data: Data batch sample with node and edge features
|
|
1408
|
+
|
|
1409
|
+
Returns:
|
|
1410
|
+
tuple: (msg_dim, edge_dim, in_dim) dimensions
|
|
1411
|
+
"""
|
|
1412
|
+
edge_dim = data.edge_feats.shape[1] if hasattr(data, "edge_feats") else None
|
|
1413
|
+
msg_dim = data.msg.shape[1] if hasattr(data, "msg") else edge_dim
|
|
1414
|
+
in_dim = data.x_src.shape[1] if hasattr(data, "x_src") else data.x.shape[1]
|
|
1415
|
+
|
|
1416
|
+
return msg_dim, edge_dim, in_dim
|
|
1417
|
+
|
|
1418
|
+
|
|
1419
|
+
def get_edge_dim(cfg, msg_dim):
|
|
1420
|
+
"""Calculate edge feature dimension based on configured edge features.
|
|
1421
|
+
|
|
1422
|
+
Edge features can include: edge_type, edge_type_triplet, msg, time_encoding.
|
|
1423
|
+
|
|
1424
|
+
Args:
|
|
1425
|
+
cfg: Configuration with batching.edge_features specification
|
|
1426
|
+
msg_dim: Message dimension
|
|
1427
|
+
|
|
1428
|
+
Returns:
|
|
1429
|
+
int: Total edge feature dimension
|
|
1430
|
+
|
|
1431
|
+
Raises:
|
|
1432
|
+
TypeError: If time_encoding used without TGN
|
|
1433
|
+
ValueError: If invalid edge feature specified
|
|
1434
|
+
"""
|
|
1435
|
+
edge_dim = 0
|
|
1436
|
+
edge_features = list(map(lambda x: x.strip(), cfg.batching.edge_features.split(",")))
|
|
1437
|
+
use_tgn = "tgn" in cfg.training.encoder.used_methods
|
|
1438
|
+
tgn_memory_dim = cfg.training.encoder.tgn.tgn_memory_dim
|
|
1439
|
+
|
|
1440
|
+
for edge_feat in edge_features:
|
|
1441
|
+
if edge_feat in ["edge_type", "edge_type_triplet"]:
|
|
1442
|
+
edge_dim += get_num_edge_type(cfg)
|
|
1443
|
+
elif edge_feat == "msg":
|
|
1444
|
+
edge_dim += msg_dim
|
|
1445
|
+
elif edge_feat == "time_encoding":
|
|
1446
|
+
if not use_tgn:
|
|
1447
|
+
raise TypeError("Edge feature `time_encoding` is only available if TGN is used.")
|
|
1448
|
+
edge_dim += tgn_memory_dim
|
|
1449
|
+
elif edge_feat == "edge_attrs":
|
|
1450
|
+
edge_dim += get_edge_attrs_dim(cfg)
|
|
1451
|
+
elif edge_feat == "none":
|
|
1452
|
+
pass
|
|
1453
|
+
else:
|
|
1454
|
+
raise ValueError(f"Invalid edge feature {edge_feat}")
|
|
1455
|
+
|
|
1456
|
+
return edge_dim
|