pidsmaker 5.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pidsmaker/__init__.py +1 -0
- pidsmaker/cli.py +81 -0
- pidsmaker/config/__init__.py +2 -0
- pidsmaker/config/config.py +2100 -0
- pidsmaker/config/pipeline.py +1824 -0
- pidsmaker/config/schemas.py +1032 -0
- pidsmaker/datasets.py +323 -0
- pidsmaker/debug_tests.py +30 -0
- pidsmaker/decoders/__init__.py +5 -0
- pidsmaker/decoders/custom_edge_mlp_decoder.py +17 -0
- pidsmaker/decoders/custom_mlp_decoder.py +10 -0
- pidsmaker/decoders/edge_linear_decoder.py +16 -0
- pidsmaker/decoders/inner_product_decoder.py +18 -0
- pidsmaker/decoders/nodlink_decoder.py +56 -0
- pidsmaker/detection/__init__.py +0 -0
- pidsmaker/detection/evaluation_methods/__init__.py +9 -0
- pidsmaker/detection/evaluation_methods/edge_evaluation.py +255 -0
- pidsmaker/detection/evaluation_methods/evaluation_utils.py +1788 -0
- pidsmaker/detection/evaluation_methods/host_two_stage_evaluation.py +115 -0
- pidsmaker/detection/evaluation_methods/node_evaluation.py +459 -0
- pidsmaker/detection/evaluation_methods/node_tw_evaluation.py +196 -0
- pidsmaker/detection/evaluation_methods/plot.py +192 -0
- pidsmaker/detection/evaluation_methods/queue_evaluation.py +456 -0
- pidsmaker/detection/evaluation_methods/tw_evaluation.py +93 -0
- pidsmaker/detection/flash_detection.py +162 -0
- pidsmaker/detection/magic_knn.py +190 -0
- pidsmaker/detection/node_scoring.py +52 -0
- pidsmaker/detection/threatrace_detection.py +65 -0
- pidsmaker/detection/training_methods/__init__.py +1 -0
- pidsmaker/detection/training_methods/inference_loop.py +287 -0
- pidsmaker/detection/training_methods/ocrapt_early_stop.py +165 -0
- pidsmaker/detection/training_methods/threatrace_training.py +168 -0
- pidsmaker/detection/training_methods/training_loop.py +383 -0
- pidsmaker/encoders/__init__.py +22 -0
- pidsmaker/encoders/argus_encoder.py +69 -0
- pidsmaker/encoders/custom_mlp.py +75 -0
- pidsmaker/encoders/custom_mlp_encoder.py +10 -0
- pidsmaker/encoders/egraphsage_encoder.py +56 -0
- pidsmaker/encoders/gat.py +67 -0
- pidsmaker/encoders/gcn.py +27 -0
- pidsmaker/encoders/gin.py +48 -0
- pidsmaker/encoders/glstm.py +298 -0
- pidsmaker/encoders/graph_attention.py +63 -0
- pidsmaker/encoders/gru.py +29 -0
- pidsmaker/encoders/hetero/__init__.py +4 -0
- pidsmaker/encoders/hetero/ancestor_encoder.py +98 -0
- pidsmaker/encoders/hetero/entity_encoder.py +33 -0
- pidsmaker/encoders/hetero/event_encoder.py +81 -0
- pidsmaker/encoders/hetero/hetero_graph_transformer.py +40 -0
- pidsmaker/encoders/lares_encoder.py +68 -0
- pidsmaker/encoders/linear_encoder.py +16 -0
- pidsmaker/encoders/magic_encoder.py +161 -0
- pidsmaker/encoders/rcaid_encoder.py +81 -0
- pidsmaker/encoders/rgcn.py +75 -0
- pidsmaker/encoders/sage.py +51 -0
- pidsmaker/encoders/shadewatcher_encoder.py +149 -0
- pidsmaker/encoders/sum_aggregation.py +20 -0
- pidsmaker/encoders/temporal_wrappers.py +80 -0
- pidsmaker/encoders/textrcnn.py +82 -0
- pidsmaker/encoders/tgn_encoder.py +193 -0
- pidsmaker/experiments/tuning.py +102 -0
- pidsmaker/experiments/uncertainty.py +261 -0
- pidsmaker/factory.py +1456 -0
- pidsmaker/featurization/__init__.py +0 -0
- pidsmaker/featurization/feat_inference_methods/__init__.py +7 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_HFH.py +30 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_TRW.py +65 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_alacarte.py +14 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_doc2vec.py +53 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_fasttext.py +37 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_flash.py +69 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_graph2vec.py +84 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_ocrapt_features.py +95 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_pretrained.py +1728 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_word2vec.py +55 -0
- pidsmaker/featurization/featurization_methods/__init__.py +0 -0
- pidsmaker/featurization/featurization_methods/build_trw.py +66 -0
- pidsmaker/featurization/featurization_methods/featurization_alacarte.py +747 -0
- pidsmaker/featurization/featurization_methods/featurization_doc2vec.py +98 -0
- pidsmaker/featurization/featurization_methods/featurization_fasttext.py +74 -0
- pidsmaker/featurization/featurization_methods/featurization_flash.py +201 -0
- pidsmaker/featurization/featurization_methods/featurization_graph2vec.py +242 -0
- pidsmaker/featurization/featurization_methods/featurization_trw.py +114 -0
- pidsmaker/featurization/featurization_methods/featurization_word2vec.py +89 -0
- pidsmaker/featurization/featurization_utils.py +275 -0
- pidsmaker/featurization/utils/build_random_walks.py +66 -0
- pidsmaker/featurization/utils/trw.py +203 -0
- pidsmaker/hetero.py +81 -0
- pidsmaker/losses.py +170 -0
- pidsmaker/main.py +478 -0
- pidsmaker/mimicry.py +284 -0
- pidsmaker/model.py +382 -0
- pidsmaker/objectives/__init__.py +16 -0
- pidsmaker/objectives/autoencode_edge_emb.py +43 -0
- pidsmaker/objectives/deep_graph_infomax.py +94 -0
- pidsmaker/objectives/detect_few_shot.py +21 -0
- pidsmaker/objectives/one_class.py +75 -0
- pidsmaker/objectives/predict_edge_contrastive.py +165 -0
- pidsmaker/objectives/predict_edge_supervised.py +77 -0
- pidsmaker/objectives/predict_edge_type.py +28 -0
- pidsmaker/objectives/predict_masked_struct.py +49 -0
- pidsmaker/objectives/predict_node_type.py +36 -0
- pidsmaker/objectives/predict_process_tag.py +169 -0
- pidsmaker/objectives/predict_snapshot_embedding.py +97 -0
- pidsmaker/objectives/reconstruct_edge_emb.py +16 -0
- pidsmaker/objectives/reconstruct_masked_feat.py +51 -0
- pidsmaker/objectives/reconstruct_node_emb.py +13 -0
- pidsmaker/objectives/reconstruct_node_feat.py +13 -0
- pidsmaker/objectives/validation_wrapper.py +55 -0
- pidsmaker/preprocessing/__init__.py +0 -0
- pidsmaker/preprocessing/build_graph_methods/__init__.py +1 -0
- pidsmaker/preprocessing/build_graph_methods/build_default_graphs.py +825 -0
- pidsmaker/preprocessing/build_graph_methods/build_magic_graphs.py +216 -0
- pidsmaker/preprocessing/cleaning.py +258 -0
- pidsmaker/preprocessing/transformation_methods/__init__.py +2 -0
- pidsmaker/preprocessing/transformation_methods/attack_generation/synthetic_attack_naive.py +194 -0
- pidsmaker/preprocessing/transformation_methods/transformation_dag.py +28 -0
- pidsmaker/preprocessing/transformation_methods/transformation_merge_edges.py +136 -0
- pidsmaker/preprocessing/transformation_methods/transformation_rcaid_pseudo_graph.py +510 -0
- pidsmaker/preprocessing/transformation_methods/transformation_undirected.py +24 -0
- pidsmaker/preprocessing/transformation_methods/transformation_utils.py +36 -0
- pidsmaker/pretrained/__init__.py +5 -0
- pidsmaker/pretrained/data/__init__.py +4 -0
- pidsmaker/pretrained/data/behavior_signatures.py +548 -0
- pidsmaker/pretrained/data/canonical_tokens.py +1035 -0
- pidsmaker/pretrained/data/edge_filter.py +381 -0
- pidsmaker/pretrained/data/entity_classes.py +476 -0
- pidsmaker/pretrained/data/sampler.py +926 -0
- pidsmaker/pretrained/data/tokenizer_bpe.py +1659 -0
- pidsmaker/pretrained/detect.py +1427 -0
- pidsmaker/pretrained/embedding_generator.py +252 -0
- pidsmaker/pretrained/finetune.py +1434 -0
- pidsmaker/pretrained/models/__init__.py +20 -0
- pidsmaker/pretrained/models/behavior.py +348 -0
- pidsmaker/pretrained/models/bert.py +286 -0
- pidsmaker/pretrained/models/deepwalk.py +128 -0
- pidsmaker/pretrained/models/dgi.py +120 -0
- pidsmaker/pretrained/models/gae.py +114 -0
- pidsmaker/pretrained/models/gnn_distill.py +475 -0
- pidsmaker/pretrained/models/graphmae.py +373 -0
- pidsmaker/pretrained/models/hf_pretrained.py +213 -0
- pidsmaker/pretrained/models/llama.py +110 -0
- pidsmaker/pretrained/models/modernbert.py +567 -0
- pidsmaker/pretrained/models/roberta.py +147 -0
- pidsmaker/pretrained/models/rope_utils.py +99 -0
- pidsmaker/pretrained/models/ropebert.py +322 -0
- pidsmaker/pretrained/models/spider.py +204 -0
- pidsmaker/pretrained/models/tgn.py +770 -0
- pidsmaker/pretrained/pretrain/__init__.py +3 -0
- pidsmaker/pretrained/pretrain/pretrain_behavior_cluster.py +513 -0
- pidsmaker/pretrained/pretrain/pretrain_common.py +585 -0
- pidsmaker/pretrained/pretrain/pretrain_deepwalk.py +31 -0
- pidsmaker/pretrained/pretrain/pretrain_dgi.py +143 -0
- pidsmaker/pretrained/pretrain/pretrain_gae.py +143 -0
- pidsmaker/pretrained/pretrain/pretrain_gnn_distill.py +438 -0
- pidsmaker/pretrained/pretrain/pretrain_graphmae.py +151 -0
- pidsmaker/pretrained/pretrain/pretrain_hf.py +169 -0
- pidsmaker/pretrained/pretrain/pretrain_main.py +275 -0
- pidsmaker/pretrained/pretrain/pretrain_mlm.py +491 -0
- pidsmaker/pretrained/pretrain/pretrain_spider.py +502 -0
- pidsmaker/pretrained/training_utils.py +157 -0
- pidsmaker/process_reapr_gt.py +101 -0
- pidsmaker/resources/config/anomal_e.yml +25 -0
- pidsmaker/resources/config/argus.yml +56 -0
- pidsmaker/resources/config/attack_edges/cadets_e3.yml +435 -0
- pidsmaker/resources/config/attack_edges/cadets_e5.yml +407 -0
- pidsmaker/resources/config/attack_edges/theia_e3.yml +382 -0
- pidsmaker/resources/config/attack_edges/theia_e5.yml +387 -0
- pidsmaker/resources/config/attack_edges/trace_e3.yml +415 -0
- pidsmaker/resources/config/attack_edges/trace_e5.yml +417 -0
- pidsmaker/resources/config/default.yml +315 -0
- pidsmaker/resources/config/egraphsage.yml +95 -0
- pidsmaker/resources/config/euler.yml +104 -0
- pidsmaker/resources/config/eval/eval_set_clustering.json +3170 -0
- pidsmaker/resources/config/experiments/tuning/components/tuning_featurization_methods.yml +29 -0
- pidsmaker/resources/config/experiments/tuning/systems/clearscope_e5/tuning_orthrus.yml +14 -0
- pidsmaker/resources/config/experiments/tuning/systems/default/tuning_default_baselines.yml +13 -0
- pidsmaker/resources/config/experiments/tuning/systems/default/tuning_orthrus_fixed.yml +16 -0
- pidsmaker/resources/config/experiments/uncertainty/none.yml +5 -0
- pidsmaker/resources/config/experiments/uncertainty/run_n_times.yml +12 -0
- pidsmaker/resources/config/experiments/uncertainty/run_n_times_hyperparameters.yml +12 -0
- pidsmaker/resources/config/experiments/uncertainty/uncertainty.yml +22 -0
- pidsmaker/resources/config/flash.yml +79 -0
- pidsmaker/resources/config/jbeil.yml +65 -0
- pidsmaker/resources/config/kairos.yml +121 -0
- pidsmaker/resources/config/lares.yml +115 -0
- pidsmaker/resources/config/magic.yml +86 -0
- pidsmaker/resources/config/nodlink.yml +79 -0
- pidsmaker/resources/config/ocrapt.yml +91 -0
- pidsmaker/resources/config/orthrus.yml +126 -0
- pidsmaker/resources/config/orthrus_fixed.yml +17 -0
- pidsmaker/resources/config/pretrained/README.md +101 -0
- pidsmaker/resources/config/pretrained/cybergfm/cybergfm.yml +49 -0
- pidsmaker/resources/config/pretrained/pretrained.yml +190 -0
- pidsmaker/resources/config/pretrained/pretrained_flash.yml +9 -0
- pidsmaker/resources/config/pretrained/pretrained_kairos.yml +12 -0
- pidsmaker/resources/config/pretrained/pretrained_magic.yml +1 -0
- pidsmaker/resources/config/pretrained/pretrained_nodlink.yml +1 -0
- pidsmaker/resources/config/pretrained/pretrained_orthrus.yml +1 -0
- pidsmaker/resources/config/pretrained/pretrained_supervised.yml +13 -0
- pidsmaker/resources/config/pretrained/pretrained_threatrace.yml +8 -0
- pidsmaker/resources/config/pretrained/pretrained_velox.yml +14 -0
- pidsmaker/resources/config/prographer.yml +136 -0
- pidsmaker/resources/config/rcaid.yml +88 -0
- pidsmaker/resources/config/shadewatcher.yml +146 -0
- pidsmaker/resources/config/tests.yml +10 -0
- pidsmaker/resources/config/threatrace.yml +73 -0
- pidsmaker/resources/config/tuned_baselines/optc_net/tuned_argus.yml +4 -0
- pidsmaker/resources/config/tuned_baselines/optc_net/tuned_lares.yml +13 -0
- pidsmaker/resources/config/velox.yml +10 -0
- pidsmaker/resources/config/viz_config.yml +10 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_06.csv +8 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_11.csv +4 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_12.csv +43 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_13.csv +24 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0411.csv +41 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0412.csv +0 -0
- pidsmaker/resources/ground_truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_browser_0412.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +63 -0
- pidsmaker/resources/ground_truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +56 -0
- pidsmaker/resources/ground_truth/orthrus/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +61 -0
- pidsmaker/resources/ground_truth/orthrus/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +58 -0
- pidsmaker/resources/ground_truth/orthrus/E3-TRACE/node_trace_e3_firefox_0410.csv +11 -0
- pidsmaker/resources/ground_truth/orthrus/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +11 -0
- pidsmaker/resources/ground_truth/orthrus/E3-TRACE/node_trace_e3_pine_0413.csv +14 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT.csv +19 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT_17.csv +107 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_appstarter_0515.csv +26 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_firefox_0517.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_lockwatch_0517.csv +17 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_tester_0517.csv +8 -0
- pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_bits_0515.csv +54 -0
- pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_copykatz_0509.csv +87 -0
- pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_dns_0517.csv +11 -0
- pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_drakon_0517.csv +6 -0
- pidsmaker/resources/ground_truth/orthrus/E5-THEIA/node_THEIA_1_Firefox_Drakon_APT_BinFmt_Elevate_Inject.csv +70 -0
- pidsmaker/resources/ground_truth/orthrus/E5-TRACE/node_Trace_Firefox_Drakon.csv +71 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m1.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m2.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m3.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m4.csv +5 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m5.csv +23 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m6.csv +18 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s1.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s2.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s3.csv +16 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s4.csv +22 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m1.csv +126 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m2.csv +105 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m3.csv +94 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m4.csv +139 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m5.csv +228 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m6.csv +131 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s1.csv +118 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s2.csv +89 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s3.csv +133 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s4.csv +135 -0
- pidsmaker/resources/ground_truth/orthrus/carbanakv2_edr/carbanakv2_edr.csv +2453 -0
- pidsmaker/resources/ground_truth/orthrus/h051/node_h051_0925.csv +114 -0
- pidsmaker/resources/ground_truth/orthrus/h201/node_h201_0923.csv +2905 -0
- pidsmaker/resources/ground_truth/orthrus/h501/node_h501_0924.csv +749 -0
- pidsmaker/resources/ground_truth/orthrus/readme.md +98 -0
- pidsmaker/resources/ground_truth/reapr/E3-CADETS/node_Nginx_Backdoor_06.csv +3 -0
- pidsmaker/resources/ground_truth/reapr/E3-CADETS/node_Nginx_Backdoor_12.csv +655 -0
- pidsmaker/resources/ground_truth/reapr/E3-CADETS/node_Nginx_Backdoor_13.csv +770 -0
- pidsmaker/resources/ground_truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +0 -0
- pidsmaker/resources/ground_truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +18 -0
- pidsmaker/resources/ground_truth/reapr/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +42 -0
- pidsmaker/resources/ground_truth/reapr/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +81 -0
- pidsmaker/resources/ground_truth/reapr/E3-TRACE/node_trace_e3_firefox_0410.csv +37 -0
- pidsmaker/resources/ground_truth/reapr/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +9 -0
- pidsmaker/resources/ground_truth/reapr/E3-TRACE/node_trace_e3_pine_0413.csv +40 -0
- pidsmaker/resources/ground_truth/threatrace/E3-CADETS/ground_truth.txt +12858 -0
- pidsmaker/resources/ground_truth/threatrace/E3-FIVEDIRECTIONS/ground_truth.txt +18420 -0
- pidsmaker/resources/ground_truth/threatrace/E3-THEIA/ground_truth.txt +25363 -0
- pidsmaker/resources/ground_truth/threatrace/E3-TRACE/ground_truth.txt +68265 -0
- pidsmaker/resources/ground_truth/threatrace/README.md +123 -0
- pidsmaker/tasks/__init__.py +10 -0
- pidsmaker/tasks/batching.py +47 -0
- pidsmaker/tasks/construction.py +31 -0
- pidsmaker/tasks/evaluation.py +241 -0
- pidsmaker/tasks/feat_inference.py +413 -0
- pidsmaker/tasks/featurization.py +43 -0
- pidsmaker/tasks/training.py +17 -0
- pidsmaker/tasks/transformation.py +306 -0
- pidsmaker/tasks/triage.py +143 -0
- pidsmaker/tgn.py +635 -0
- pidsmaker/tokenization/__init__.py +112 -0
- pidsmaker/tokenization/base.py +58 -0
- pidsmaker/tokenization/bpe_tokenizer.py +83 -0
- pidsmaker/tokenization/hf_tokenizer.py +61 -0
- pidsmaker/tokenization/hierarchical_tokenizer.py +44 -0
- pidsmaker/tokenization/label_tokenizer.py +24 -0
- pidsmaker/tokenization/nltk_tokenizer.py +84 -0
- pidsmaker/tokenization/substitution.py +295 -0
- pidsmaker/triage/__init__.py +0 -0
- pidsmaker/triage/tracing_methods/__init__.py +1 -0
- pidsmaker/triage/tracing_methods/depimpact.py +213 -0
- pidsmaker/triage/tracing_methods/depimpact_utils.py +537 -0
- pidsmaker/triage/tracing_methods/ocrapt_subgraph.py +267 -0
- pidsmaker/utils/__init__.py +0 -0
- pidsmaker/utils/cache_utils.py +256 -0
- pidsmaker/utils/console.py +282 -0
- pidsmaker/utils/data_utils.py +1742 -0
- pidsmaker/utils/database.py +150 -0
- pidsmaker/utils/dataset_utils.py +413 -0
- pidsmaker/utils/dataset_writer.py +570 -0
- pidsmaker/utils/graph_store.py +634 -0
- pidsmaker/utils/labelling.py +445 -0
- pidsmaker/utils/loss_files.py +193 -0
- pidsmaker/utils/process_tags.py +44 -0
- pidsmaker/utils/utils.py +712 -0
- pidsmaker/vizgen/__init__.py +1 -0
- pidsmaker/vizgen/backfill_manifests.py +100 -0
- pidsmaker/vizgen/dimensionality_reduction.py +249 -0
- pidsmaker/vizgen/embed_exporter.py +467 -0
- pidsmaker/vizgen/exporter.py +493 -0
- pidsmaker/vizgen/html_builder.py +936 -0
- pidsmaker/vizgen/web/__init__.py +1 -0
- pidsmaker/vizgen/web/export.py +62 -0
- pidsmaker/vizgen/web/static/css/app.css +250 -0
- pidsmaker/vizgen/web/static/index.html +182 -0
- pidsmaker/vizgen/web/static/js/app.js +627 -0
- pidsmaker/vizgen/web/static/js/campaign.js +123 -0
- pidsmaker/vizgen/web/static/js/data.js +119 -0
- pidsmaker/vizgen/web/static/js/dialogs.js +240 -0
- pidsmaker/vizgen/web/static/js/jobs.js +75 -0
- pidsmaker/vizgen/web/static/js/scene.js +651 -0
- pidsmaker/vizgen/web/static/js/ui.js +370 -0
- pidsmaker/vizgen/web/static/vendor/OrbitControls.js +1045 -0
- pidsmaker/vizgen/web/static/vendor/d3.v4.min.js +2 -0
- pidsmaker/vizgen/web/static/vendor/three.min.js +6 -0
- pidsmaker/vizgen/web/viz_server.py +2176 -0
- pidsmaker-5.0.0.dist-info/METADATA +597 -0
- pidsmaker-5.0.0.dist-info/RECORD +339 -0
- pidsmaker-5.0.0.dist-info/WHEEL +5 -0
- pidsmaker-5.0.0.dist-info/entry_points.txt +2 -0
- pidsmaker-5.0.0.dist-info/licenses/LICENSE +201 -0
- pidsmaker-5.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,770 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TGN (Temporal Graph Network) model for provenance graph attack detection.
|
|
3
|
+
|
|
4
|
+
Maintains per-entity state vectors (memories) updated via attention when entities
|
|
5
|
+
participate in events. For each edge, classifies attack/benign using:
|
|
6
|
+
[mem_src, mem_dst, bert_emb_src, bert_emb_dst, edge_emb, time_enc_src, time_enc_dst]
|
|
7
|
+
|
|
8
|
+
Memory updates use self-attention over 4 feature tokens (no GRU/LSTM):
|
|
9
|
+
[current_memory, interaction_message, entity_embedding, time_encoding]
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import torch
|
|
13
|
+
import torch.nn as nn
|
|
14
|
+
from torch_geometric.utils import scatter
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class TGNTimeEncoder(nn.Module):
|
|
18
|
+
"""Encode time deltas: log1p(delta_seconds) -> Linear -> cos()."""
|
|
19
|
+
|
|
20
|
+
def __init__(self, time_dim: int):
|
|
21
|
+
super().__init__()
|
|
22
|
+
self.lin = nn.Linear(1, time_dim)
|
|
23
|
+
|
|
24
|
+
def forward(self, delta_ns: torch.Tensor) -> torch.Tensor:
|
|
25
|
+
"""
|
|
26
|
+
Args:
|
|
27
|
+
delta_ns: [N] raw timestamp deltas in nanoseconds (int64 or float).
|
|
28
|
+
Returns:
|
|
29
|
+
[N, time_dim] encoded time features.
|
|
30
|
+
"""
|
|
31
|
+
delta_sec = delta_ns.float() / 1e9
|
|
32
|
+
x = torch.log1p(delta_sec.abs()).unsqueeze(-1) # [N, 1]
|
|
33
|
+
return self.lin(x).cos() # [N, time_dim]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class TGNMessageFunction(nn.Module):
|
|
37
|
+
"""Compute interaction message from node memories, embeddings, edge type, and time.
|
|
38
|
+
|
|
39
|
+
Input: concat(self_mem, other_mem, self_emb, other_emb, edge_emb, time_enc)
|
|
40
|
+
Output: [N, memory_dim] message vector.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
def __init__(self, memory_dim: int, entity_emb_dim: int, edge_emb_dim: int, time_dim: int):
|
|
44
|
+
super().__init__()
|
|
45
|
+
input_dim = 2 * memory_dim + 2 * entity_emb_dim + edge_emb_dim + time_dim
|
|
46
|
+
self.proj = nn.Sequential(
|
|
47
|
+
nn.Linear(input_dim, memory_dim),
|
|
48
|
+
nn.ReLU(),
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
def forward(self, self_mem, other_mem, self_emb, other_emb, edge_emb, time_enc):
|
|
52
|
+
"""All inputs: [N, respective_dim]. Returns: [N, memory_dim]."""
|
|
53
|
+
return self.proj(torch.cat([self_mem, other_mem, self_emb, other_emb, edge_emb, time_enc], dim=-1))
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class AttentionMemoryUpdater(nn.Module):
|
|
57
|
+
"""Update entity memory via self-attention over 4 feature tokens.
|
|
58
|
+
|
|
59
|
+
Tokens:
|
|
60
|
+
0: current entity memory (output here = updated memory)
|
|
61
|
+
1: aggregated interaction message
|
|
62
|
+
2: entity's static BERT embedding (identity)
|
|
63
|
+
3: time delta encoding (temporal context)
|
|
64
|
+
|
|
65
|
+
Each token is projected to memory_dim, augmented with learned token-type
|
|
66
|
+
embeddings, then processed by a TransformerEncoderLayer (self-attention +
|
|
67
|
+
FFN with pre-norm and GELU). Output at position 0 is the new memory.
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
NUM_TOKEN_TYPES = 4
|
|
71
|
+
|
|
72
|
+
def __init__(self, memory_dim: int, entity_emb_dim: int, time_dim: int,
|
|
73
|
+
num_heads: int = 4, dropout: float = 0.1):
|
|
74
|
+
super().__init__()
|
|
75
|
+
|
|
76
|
+
# Project heterogeneous features to uniform memory_dim
|
|
77
|
+
self.proj_mem = nn.Linear(memory_dim, memory_dim)
|
|
78
|
+
self.proj_msg = nn.Linear(memory_dim, memory_dim) # message is already memory_dim
|
|
79
|
+
self.proj_emb = nn.Linear(entity_emb_dim, memory_dim)
|
|
80
|
+
self.proj_time = nn.Linear(time_dim, memory_dim)
|
|
81
|
+
|
|
82
|
+
# Token-type embeddings so the model distinguishes the 4 slots
|
|
83
|
+
self.token_type_emb = nn.Embedding(self.NUM_TOKEN_TYPES, memory_dim)
|
|
84
|
+
|
|
85
|
+
# Self-attention encoder (1 layer, pre-norm)
|
|
86
|
+
encoder_layer = nn.TransformerEncoderLayer(
|
|
87
|
+
d_model=memory_dim,
|
|
88
|
+
nhead=num_heads,
|
|
89
|
+
dim_feedforward=memory_dim * 4,
|
|
90
|
+
dropout=dropout,
|
|
91
|
+
activation="gelu",
|
|
92
|
+
batch_first=True,
|
|
93
|
+
norm_first=True,
|
|
94
|
+
)
|
|
95
|
+
self.encoder = nn.TransformerEncoder(encoder_layer, num_layers=1)
|
|
96
|
+
self.out_norm = nn.LayerNorm(memory_dim)
|
|
97
|
+
|
|
98
|
+
def forward(self, memory, message, entity_emb, time_enc):
|
|
99
|
+
"""
|
|
100
|
+
Args:
|
|
101
|
+
memory: [B, memory_dim]
|
|
102
|
+
message: [B, memory_dim]
|
|
103
|
+
entity_emb: [B, entity_emb_dim]
|
|
104
|
+
time_enc: [B, time_dim]
|
|
105
|
+
Returns:
|
|
106
|
+
[B, memory_dim] updated memory.
|
|
107
|
+
"""
|
|
108
|
+
B = memory.size(0)
|
|
109
|
+
device = memory.device
|
|
110
|
+
|
|
111
|
+
# Project each feature to memory_dim
|
|
112
|
+
tok0 = self.proj_mem(memory) # [B, D]
|
|
113
|
+
tok1 = self.proj_msg(message) # [B, D]
|
|
114
|
+
tok2 = self.proj_emb(entity_emb) # [B, D]
|
|
115
|
+
tok3 = self.proj_time(time_enc) # [B, D]
|
|
116
|
+
|
|
117
|
+
tokens = torch.stack([tok0, tok1, tok2, tok3], dim=1) # [B, 4, D]
|
|
118
|
+
|
|
119
|
+
# Add token-type embeddings
|
|
120
|
+
type_ids = torch.arange(self.NUM_TOKEN_TYPES, device=device) # [4]
|
|
121
|
+
tokens = tokens + self.token_type_emb(type_ids).unsqueeze(0) # broadcast [1, 4, D]
|
|
122
|
+
|
|
123
|
+
# Self-attention
|
|
124
|
+
out = self.encoder(tokens) # [B, 4, D]
|
|
125
|
+
return self.out_norm(out[:, 0]) # [B, D] — position 0 = updated memory
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class EdgeTypeClassifier(nn.Module):
|
|
129
|
+
"""Static edge type classifier from pre-computed entity embeddings.
|
|
130
|
+
|
|
131
|
+
Given a (src, dst) pair, predicts the edge type from concatenated BERT
|
|
132
|
+
entity embeddings. No temporal memory, no state — each edge is scored
|
|
133
|
+
independently.
|
|
134
|
+
|
|
135
|
+
Training: CE loss on predicted edge type.
|
|
136
|
+
Inference: per-edge CE loss as anomaly score.
|
|
137
|
+
"""
|
|
138
|
+
|
|
139
|
+
def __init__(
|
|
140
|
+
self,
|
|
141
|
+
num_nodes: int,
|
|
142
|
+
num_edge_types: int,
|
|
143
|
+
entity_emb_dim: int,
|
|
144
|
+
hidden_dim: int = 128,
|
|
145
|
+
):
|
|
146
|
+
super().__init__()
|
|
147
|
+
self.num_nodes = num_nodes
|
|
148
|
+
self.entity_emb_dim = entity_emb_dim
|
|
149
|
+
|
|
150
|
+
self.register_buffer("entity_embs", torch.zeros(num_nodes, entity_emb_dim))
|
|
151
|
+
|
|
152
|
+
num_classes = num_edge_types + 1
|
|
153
|
+
self.classifier = nn.Sequential(
|
|
154
|
+
nn.Linear(2 * entity_emb_dim, hidden_dim),
|
|
155
|
+
nn.ReLU(),
|
|
156
|
+
nn.Dropout(0.1),
|
|
157
|
+
nn.Linear(hidden_dim, num_classes),
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
def set_entity_embeddings(self, embs: torch.Tensor):
|
|
161
|
+
self.entity_embs.copy_(embs.to(self.entity_embs.device))
|
|
162
|
+
|
|
163
|
+
def predict(self, src_idx: torch.Tensor, dst_idx: torch.Tensor) -> torch.Tensor:
|
|
164
|
+
"""Predict edge type logits.
|
|
165
|
+
|
|
166
|
+
Args:
|
|
167
|
+
src_idx: [B] int64 contiguous node indices.
|
|
168
|
+
dst_idx: [B] int64 contiguous node indices.
|
|
169
|
+
Returns:
|
|
170
|
+
[B, num_classes] raw logits.
|
|
171
|
+
"""
|
|
172
|
+
features = torch.cat([
|
|
173
|
+
self.entity_embs[src_idx],
|
|
174
|
+
self.entity_embs[dst_idx],
|
|
175
|
+
], dim=-1)
|
|
176
|
+
return self.classifier(features)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
class ProvenanceTGN(nn.Module):
|
|
180
|
+
"""TGN-based anomaly detector for provenance graphs.
|
|
181
|
+
|
|
182
|
+
Components:
|
|
183
|
+
entity_embs: [N, H] pre-computed frozen BERT embeddings (buffer)
|
|
184
|
+
memory: [N, memory_dim] evolving entity state vectors (buffer)
|
|
185
|
+
last_update: [N] last-update timestamps in nanoseconds (buffer)
|
|
186
|
+
node_types: [N] int node type IDs (buffer, optional)
|
|
187
|
+
edge_emb: Embedding(num_edge_types+1, edge_emb_dim)
|
|
188
|
+
time_enc: TGNTimeEncoder(time_dim)
|
|
189
|
+
message_fn: TGNMessageFunction → message vectors for memory update
|
|
190
|
+
memory_updater: AttentionMemoryUpdater (self-attention, no GRU)
|
|
191
|
+
classifier: MLP → binary anomaly logit
|
|
192
|
+
|
|
193
|
+
Optional classifier inputs (controlled by flags):
|
|
194
|
+
use_node_type_emb: include learned src/dst node-type embeddings so the
|
|
195
|
+
classifier can learn type-specific score baselines.
|
|
196
|
+
use_time_emb: include src/dst time-delta encodings in the classifier.
|
|
197
|
+
"""
|
|
198
|
+
|
|
199
|
+
NUM_NODE_TYPES = 4 # 0=unknown, 1=subject, 2=file, 3=netflow
|
|
200
|
+
|
|
201
|
+
def __init__(
|
|
202
|
+
self,
|
|
203
|
+
num_nodes: int,
|
|
204
|
+
num_edge_types: int,
|
|
205
|
+
entity_emb_dim: int,
|
|
206
|
+
memory_dim: int = 128,
|
|
207
|
+
edge_emb_dim: int = 128,
|
|
208
|
+
time_dim: int = 16,
|
|
209
|
+
num_heads: int = 4,
|
|
210
|
+
use_node_type_emb: bool = False,
|
|
211
|
+
use_time_emb: bool = True,
|
|
212
|
+
use_memory: bool = True,
|
|
213
|
+
use_entity_emb: bool = True,
|
|
214
|
+
use_event_bert_emb: bool = False,
|
|
215
|
+
event_bert_emb_dim: int = 0,
|
|
216
|
+
score_gated_memory: bool = False,
|
|
217
|
+
temporal_decay: bool = False,
|
|
218
|
+
anomaly_accumulator: bool = False,
|
|
219
|
+
device: str = "cpu",
|
|
220
|
+
):
|
|
221
|
+
super().__init__()
|
|
222
|
+
self.num_nodes = num_nodes
|
|
223
|
+
self.memory_dim = memory_dim
|
|
224
|
+
self.entity_emb_dim = entity_emb_dim
|
|
225
|
+
self.use_node_type_emb = use_node_type_emb
|
|
226
|
+
self.use_time_emb = use_time_emb
|
|
227
|
+
self.use_memory = use_memory
|
|
228
|
+
self.use_entity_emb = use_entity_emb
|
|
229
|
+
self.use_event_bert_emb = use_event_bert_emb
|
|
230
|
+
self.event_bert_emb_dim = event_bert_emb_dim
|
|
231
|
+
self.score_gated_memory = score_gated_memory
|
|
232
|
+
self.temporal_decay = temporal_decay
|
|
233
|
+
self.anomaly_accumulator = anomaly_accumulator
|
|
234
|
+
self.device = device
|
|
235
|
+
|
|
236
|
+
# ── Buffers (non-parameter state) ──────────────────────────
|
|
237
|
+
self.register_buffer("entity_embs", torch.zeros(num_nodes, entity_emb_dim))
|
|
238
|
+
self.register_buffer("memory", torch.zeros(num_nodes, memory_dim))
|
|
239
|
+
self.register_buffer("last_update", torch.zeros(num_nodes, dtype=torch.long))
|
|
240
|
+
self.register_buffer("node_types", torch.zeros(num_nodes, dtype=torch.long))
|
|
241
|
+
if anomaly_accumulator:
|
|
242
|
+
self.register_buffer("anomaly_accum", torch.zeros(num_nodes))
|
|
243
|
+
|
|
244
|
+
# Differentiable memory overlay for training (truncated BPTT depth 1).
|
|
245
|
+
# When set, predict/classify read from this instead of the buffer.
|
|
246
|
+
self._diff_memory = None
|
|
247
|
+
|
|
248
|
+
# ── Learnable modules ──────────────────────────────────────
|
|
249
|
+
self.edge_emb = nn.Embedding(num_edge_types + 1, edge_emb_dim, padding_idx=0)
|
|
250
|
+
self.time_enc = TGNTimeEncoder(time_dim)
|
|
251
|
+
|
|
252
|
+
self.message_fn = TGNMessageFunction(
|
|
253
|
+
memory_dim, entity_emb_dim, edge_emb_dim, time_dim,
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
self.memory_updater = AttentionMemoryUpdater(
|
|
257
|
+
memory_dim, entity_emb_dim, time_dim, num_heads=num_heads,
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
# ── Score-gated memory: learned gate from anomaly score ───
|
|
261
|
+
if score_gated_memory:
|
|
262
|
+
self.score_gate = nn.Sequential(
|
|
263
|
+
nn.Linear(1, memory_dim),
|
|
264
|
+
nn.Sigmoid(),
|
|
265
|
+
)
|
|
266
|
+
|
|
267
|
+
# ── Temporal decay: learned base decay rate ───────────────
|
|
268
|
+
if temporal_decay:
|
|
269
|
+
self.decay_rate = nn.Parameter(torch.zeros(1))
|
|
270
|
+
|
|
271
|
+
# ── Optional node-type embeddings ──────────────────────────
|
|
272
|
+
type_emb_dim = edge_emb_dim # reuse edge_emb_dim for consistency
|
|
273
|
+
if use_node_type_emb:
|
|
274
|
+
self.node_type_emb = nn.Embedding(self.NUM_NODE_TYPES, type_emb_dim)
|
|
275
|
+
else:
|
|
276
|
+
type_emb_dim = 0
|
|
277
|
+
|
|
278
|
+
# ── Classifier (contrastive objective) ─────────────────────
|
|
279
|
+
# Input: [emb_src, emb_dst, edge_emb] + optional [mem, time, type, event_bert]
|
|
280
|
+
cls_input_dim = edge_emb_dim
|
|
281
|
+
if use_entity_emb:
|
|
282
|
+
cls_input_dim += 2 * entity_emb_dim
|
|
283
|
+
if use_memory:
|
|
284
|
+
cls_input_dim += 2 * memory_dim
|
|
285
|
+
if use_time_emb:
|
|
286
|
+
cls_input_dim += 2 * time_dim
|
|
287
|
+
if use_node_type_emb:
|
|
288
|
+
cls_input_dim += 2 * type_emb_dim
|
|
289
|
+
if use_event_bert_emb:
|
|
290
|
+
cls_input_dim += 2 * event_bert_emb_dim # paired src + dst
|
|
291
|
+
self.classifier = nn.Sequential(
|
|
292
|
+
nn.Linear(cls_input_dim, memory_dim),
|
|
293
|
+
nn.ReLU(),
|
|
294
|
+
nn.Dropout(0.1),
|
|
295
|
+
nn.Linear(memory_dim, 1),
|
|
296
|
+
)
|
|
297
|
+
|
|
298
|
+
# ── Edge type predictor (edge_pred objective) ─────────────
|
|
299
|
+
# Same features as classifier but WITHOUT edge_emb (that's the target).
|
|
300
|
+
pred_input_dim = 0
|
|
301
|
+
if use_entity_emb:
|
|
302
|
+
pred_input_dim += 2 * entity_emb_dim
|
|
303
|
+
if use_memory:
|
|
304
|
+
pred_input_dim += 2 * memory_dim
|
|
305
|
+
if use_time_emb:
|
|
306
|
+
pred_input_dim += 2 * time_dim
|
|
307
|
+
if use_node_type_emb:
|
|
308
|
+
pred_input_dim += 2 * type_emb_dim
|
|
309
|
+
if use_event_bert_emb:
|
|
310
|
+
pred_input_dim += 2 * event_bert_emb_dim # paired src + dst
|
|
311
|
+
if pred_input_dim == 0:
|
|
312
|
+
raise ValueError(
|
|
313
|
+
"Edge predictor has 0 input features. Enable at least one of: "
|
|
314
|
+
"use_memory, use_entity_emb, use_time_emb, use_node_type_emb, use_event_bert_emb"
|
|
315
|
+
)
|
|
316
|
+
num_edge_classes = num_edge_types + 1 # match edge_emb vocabulary
|
|
317
|
+
self.edge_predictor = nn.Sequential(
|
|
318
|
+
nn.Linear(pred_input_dim, memory_dim),
|
|
319
|
+
nn.ReLU(),
|
|
320
|
+
nn.Dropout(0.1),
|
|
321
|
+
nn.Linear(memory_dim, num_edge_classes),
|
|
322
|
+
)
|
|
323
|
+
|
|
324
|
+
# ── Edge embedding predictor (edge_pred_emb objective) ─────
|
|
325
|
+
# Same input features as edge_predictor, but predicts the continuous
|
|
326
|
+
# edge embedding vector instead of the discrete type.
|
|
327
|
+
self.edge_emb_predictor = nn.Sequential(
|
|
328
|
+
nn.Linear(pred_input_dim, memory_dim),
|
|
329
|
+
nn.ReLU(),
|
|
330
|
+
nn.Dropout(0.1),
|
|
331
|
+
nn.Linear(memory_dim, edge_emb_dim),
|
|
332
|
+
)
|
|
333
|
+
|
|
334
|
+
# ── Node type predictor (node_pred objective) ─────────────
|
|
335
|
+
# Predicts dst node type from edge_emb + memory + entity_emb + time_emb.
|
|
336
|
+
# Excludes node_type_emb (that's the prediction target).
|
|
337
|
+
# Only uses event_src_emb (NOT event_dst_emb) because the dst span
|
|
338
|
+
# directly contains the dst_type token which IS the prediction target.
|
|
339
|
+
node_pred_input_dim = edge_emb_dim # always include edge embedding
|
|
340
|
+
if use_entity_emb:
|
|
341
|
+
node_pred_input_dim += 2 * entity_emb_dim
|
|
342
|
+
if use_memory:
|
|
343
|
+
node_pred_input_dim += 2 * memory_dim
|
|
344
|
+
if use_time_emb:
|
|
345
|
+
node_pred_input_dim += 2 * time_dim
|
|
346
|
+
if use_event_bert_emb:
|
|
347
|
+
node_pred_input_dim += event_bert_emb_dim # src only (dst leaks target)
|
|
348
|
+
self.node_predictor = nn.Sequential(
|
|
349
|
+
nn.Linear(node_pred_input_dim, memory_dim),
|
|
350
|
+
nn.ReLU(),
|
|
351
|
+
nn.Dropout(0.1),
|
|
352
|
+
nn.Linear(memory_dim, self.NUM_NODE_TYPES),
|
|
353
|
+
)
|
|
354
|
+
|
|
355
|
+
def _get_memory(self):
|
|
356
|
+
"""Return current effective memory: differentiable overlay if set, else buffer."""
|
|
357
|
+
return self._diff_memory if self._diff_memory is not None else self.memory
|
|
358
|
+
|
|
359
|
+
# ── State management ───────────────────────────────────────────
|
|
360
|
+
|
|
361
|
+
def set_entity_embeddings(self, embs: torch.Tensor):
|
|
362
|
+
"""Set pre-computed BERT entity embeddings (called once before training)."""
|
|
363
|
+
self.entity_embs.copy_(embs.to(self.entity_embs.device))
|
|
364
|
+
|
|
365
|
+
def set_node_types(self, types: torch.Tensor):
|
|
366
|
+
"""Set node type IDs (0=unknown, 1=subject, 2=file, 3=netflow)."""
|
|
367
|
+
self.node_types.copy_(types.to(self.node_types.device))
|
|
368
|
+
|
|
369
|
+
def reset_memory(self):
|
|
370
|
+
"""Zero all entity memories and last-update timestamps."""
|
|
371
|
+
self.memory.zero_()
|
|
372
|
+
self.last_update.zero_()
|
|
373
|
+
self._diff_memory = None
|
|
374
|
+
if self.anomaly_accumulator:
|
|
375
|
+
self.anomaly_accum.zero_()
|
|
376
|
+
|
|
377
|
+
def get_memory_state(self) -> dict:
|
|
378
|
+
"""Return a detached copy of current memory state for checkpointing."""
|
|
379
|
+
mem = self._get_memory()
|
|
380
|
+
state = {
|
|
381
|
+
"memory": mem.detach().clone().cpu(),
|
|
382
|
+
"last_update": self.last_update.detach().clone().cpu(),
|
|
383
|
+
}
|
|
384
|
+
if self.anomaly_accumulator:
|
|
385
|
+
state["anomaly_accum"] = self.anomaly_accum.detach().clone().cpu()
|
|
386
|
+
return state
|
|
387
|
+
|
|
388
|
+
def load_memory_state(self, state: dict):
|
|
389
|
+
"""Restore memory state from a saved dict."""
|
|
390
|
+
self.memory.copy_(state["memory"].to(self.memory.device))
|
|
391
|
+
self.last_update.copy_(state["last_update"].to(self.last_update.device))
|
|
392
|
+
self._diff_memory = None
|
|
393
|
+
if self.anomaly_accumulator and "anomaly_accum" in state:
|
|
394
|
+
self.anomaly_accum.copy_(state["anomaly_accum"].to(self.anomaly_accum.device))
|
|
395
|
+
|
|
396
|
+
# ── Classification ─────────────────────────────────────────────
|
|
397
|
+
|
|
398
|
+
def classify_edges(
|
|
399
|
+
self,
|
|
400
|
+
src_idx: torch.Tensor,
|
|
401
|
+
dst_idx: torch.Tensor,
|
|
402
|
+
edge_types: torch.Tensor,
|
|
403
|
+
timestamps: torch.Tensor,
|
|
404
|
+
event_src_emb: torch.Tensor = None,
|
|
405
|
+
event_dst_emb: torch.Tensor = None,
|
|
406
|
+
) -> torch.Tensor:
|
|
407
|
+
"""Compute anomaly logits for a batch of edges using current memories.
|
|
408
|
+
|
|
409
|
+
Args:
|
|
410
|
+
src_idx: [B] int64 contiguous node indices
|
|
411
|
+
dst_idx: [B] int64 contiguous node indices
|
|
412
|
+
edge_types: [B] int64 edge type IDs
|
|
413
|
+
timestamps: [B] int64 timestamps in nanoseconds
|
|
414
|
+
event_src_emb: [B, H] optional per-edge contextual src embeddings
|
|
415
|
+
event_dst_emb: [B, H] optional per-edge contextual dst embeddings
|
|
416
|
+
|
|
417
|
+
Returns:
|
|
418
|
+
[B, 1] raw logits (before sigmoid).
|
|
419
|
+
"""
|
|
420
|
+
e_emb = self.edge_emb(edge_types)
|
|
421
|
+
parts = [e_emb]
|
|
422
|
+
|
|
423
|
+
if self.use_entity_emb:
|
|
424
|
+
parts.extend([self.entity_embs[src_idx], self.entity_embs[dst_idx]])
|
|
425
|
+
|
|
426
|
+
if self.use_memory:
|
|
427
|
+
mem = self._get_memory()
|
|
428
|
+
parts.extend([mem[src_idx], mem[dst_idx]])
|
|
429
|
+
|
|
430
|
+
if self.use_time_emb:
|
|
431
|
+
src_dt = timestamps - self.last_update[src_idx]
|
|
432
|
+
dst_dt = timestamps - self.last_update[dst_idx]
|
|
433
|
+
parts.extend([self.time_enc(src_dt), self.time_enc(dst_dt)])
|
|
434
|
+
|
|
435
|
+
if self.use_node_type_emb:
|
|
436
|
+
parts.extend([
|
|
437
|
+
self.node_type_emb(self.node_types[src_idx]),
|
|
438
|
+
self.node_type_emb(self.node_types[dst_idx]),
|
|
439
|
+
])
|
|
440
|
+
|
|
441
|
+
if self.use_event_bert_emb and self.event_bert_emb_dim > 0 and event_src_emb is not None:
|
|
442
|
+
parts.extend([event_src_emb, event_dst_emb])
|
|
443
|
+
|
|
444
|
+
return self.classifier(torch.cat(parts, dim=-1))
|
|
445
|
+
|
|
446
|
+
# ── Edge type prediction ─────────────────────────────────────
|
|
447
|
+
|
|
448
|
+
def predict_edge_types(
|
|
449
|
+
self,
|
|
450
|
+
src_idx: torch.Tensor,
|
|
451
|
+
dst_idx: torch.Tensor,
|
|
452
|
+
timestamps: torch.Tensor,
|
|
453
|
+
event_src_emb: torch.Tensor = None,
|
|
454
|
+
event_dst_emb: torch.Tensor = None,
|
|
455
|
+
) -> torch.Tensor:
|
|
456
|
+
"""Predict edge type logits from memories and embeddings (no edge type input).
|
|
457
|
+
|
|
458
|
+
Args:
|
|
459
|
+
src_idx: [B] int64 contiguous node indices
|
|
460
|
+
dst_idx: [B] int64 contiguous node indices
|
|
461
|
+
timestamps: [B] int64 timestamps in nanoseconds
|
|
462
|
+
event_src_emb: [B, H] optional per-edge contextual src embeddings
|
|
463
|
+
event_dst_emb: [B, H] optional per-edge contextual dst embeddings
|
|
464
|
+
|
|
465
|
+
Returns:
|
|
466
|
+
[B, num_edge_classes] raw logits.
|
|
467
|
+
"""
|
|
468
|
+
parts = []
|
|
469
|
+
|
|
470
|
+
if self.use_entity_emb:
|
|
471
|
+
parts.extend([self.entity_embs[src_idx], self.entity_embs[dst_idx]])
|
|
472
|
+
|
|
473
|
+
if self.use_memory:
|
|
474
|
+
mem = self._get_memory()
|
|
475
|
+
parts.extend([mem[src_idx], mem[dst_idx]])
|
|
476
|
+
|
|
477
|
+
if self.use_time_emb:
|
|
478
|
+
src_dt = timestamps - self.last_update[src_idx]
|
|
479
|
+
dst_dt = timestamps - self.last_update[dst_idx]
|
|
480
|
+
parts.extend([self.time_enc(src_dt), self.time_enc(dst_dt)])
|
|
481
|
+
|
|
482
|
+
if self.use_node_type_emb:
|
|
483
|
+
parts.extend([
|
|
484
|
+
self.node_type_emb(self.node_types[src_idx]),
|
|
485
|
+
self.node_type_emb(self.node_types[dst_idx]),
|
|
486
|
+
])
|
|
487
|
+
|
|
488
|
+
if self.use_event_bert_emb and self.event_bert_emb_dim > 0 and event_src_emb is not None:
|
|
489
|
+
parts.extend([event_src_emb, event_dst_emb])
|
|
490
|
+
|
|
491
|
+
return self.edge_predictor(torch.cat(parts, dim=-1))
|
|
492
|
+
|
|
493
|
+
# ── Edge embedding prediction ─────────────────────────────────
|
|
494
|
+
|
|
495
|
+
def predict_edge_embedding(
|
|
496
|
+
self,
|
|
497
|
+
src_idx: torch.Tensor,
|
|
498
|
+
dst_idx: torch.Tensor,
|
|
499
|
+
timestamps: torch.Tensor,
|
|
500
|
+
event_src_emb: torch.Tensor = None,
|
|
501
|
+
event_dst_emb: torch.Tensor = None,
|
|
502
|
+
) -> torch.Tensor:
|
|
503
|
+
"""Predict edge embedding vector from memories and embeddings.
|
|
504
|
+
|
|
505
|
+
Uses the same input features as predict_edge_types but outputs a
|
|
506
|
+
continuous embedding vector [B, edge_emb_dim] instead of class logits.
|
|
507
|
+
"""
|
|
508
|
+
parts = []
|
|
509
|
+
|
|
510
|
+
if self.use_entity_emb:
|
|
511
|
+
parts.extend([self.entity_embs[src_idx], self.entity_embs[dst_idx]])
|
|
512
|
+
|
|
513
|
+
if self.use_memory:
|
|
514
|
+
mem = self._get_memory()
|
|
515
|
+
parts.extend([mem[src_idx], mem[dst_idx]])
|
|
516
|
+
|
|
517
|
+
if self.use_time_emb:
|
|
518
|
+
src_dt = timestamps - self.last_update[src_idx]
|
|
519
|
+
dst_dt = timestamps - self.last_update[dst_idx]
|
|
520
|
+
parts.extend([self.time_enc(src_dt), self.time_enc(dst_dt)])
|
|
521
|
+
|
|
522
|
+
if self.use_node_type_emb:
|
|
523
|
+
parts.extend([
|
|
524
|
+
self.node_type_emb(self.node_types[src_idx]),
|
|
525
|
+
self.node_type_emb(self.node_types[dst_idx]),
|
|
526
|
+
])
|
|
527
|
+
|
|
528
|
+
if self.use_event_bert_emb and self.event_bert_emb_dim > 0 and event_src_emb is not None:
|
|
529
|
+
parts.extend([event_src_emb, event_dst_emb])
|
|
530
|
+
|
|
531
|
+
return self.edge_emb_predictor(torch.cat(parts, dim=-1))
|
|
532
|
+
|
|
533
|
+
# ── Node type prediction ──────────────────────────────────────
|
|
534
|
+
|
|
535
|
+
def predict_node_types(
|
|
536
|
+
self,
|
|
537
|
+
src_idx: torch.Tensor,
|
|
538
|
+
dst_idx: torch.Tensor,
|
|
539
|
+
edge_types: torch.Tensor,
|
|
540
|
+
timestamps: torch.Tensor,
|
|
541
|
+
event_src_emb: torch.Tensor = None,
|
|
542
|
+
event_dst_emb: torch.Tensor = None,
|
|
543
|
+
) -> torch.Tensor:
|
|
544
|
+
"""Predict destination node type logits.
|
|
545
|
+
|
|
546
|
+
Uses edge_emb + memory + entity_emb + time_emb (no node_type_emb,
|
|
547
|
+
since node type is the prediction target).
|
|
548
|
+
|
|
549
|
+
Args:
|
|
550
|
+
src_idx: [B] int64 contiguous node indices
|
|
551
|
+
dst_idx: [B] int64 contiguous node indices
|
|
552
|
+
edge_types: [B] int64 edge type IDs
|
|
553
|
+
timestamps: [B] int64 timestamps in nanoseconds
|
|
554
|
+
event_src_emb: [B, H] optional per-edge contextual src embeddings
|
|
555
|
+
event_dst_emb: [B, H] optional per-edge contextual dst embeddings
|
|
556
|
+
|
|
557
|
+
Returns:
|
|
558
|
+
[B, NUM_NODE_TYPES] raw logits for destination node type.
|
|
559
|
+
"""
|
|
560
|
+
e_emb = self.edge_emb(edge_types)
|
|
561
|
+
parts = [e_emb]
|
|
562
|
+
|
|
563
|
+
if self.use_entity_emb:
|
|
564
|
+
parts.extend([self.entity_embs[src_idx], self.entity_embs[dst_idx]])
|
|
565
|
+
|
|
566
|
+
if self.use_memory:
|
|
567
|
+
mem = self._get_memory()
|
|
568
|
+
parts.extend([mem[src_idx], mem[dst_idx]])
|
|
569
|
+
|
|
570
|
+
if self.use_time_emb:
|
|
571
|
+
src_dt = timestamps - self.last_update[src_idx]
|
|
572
|
+
dst_dt = timestamps - self.last_update[dst_idx]
|
|
573
|
+
parts.extend([self.time_enc(src_dt), self.time_enc(dst_dt)])
|
|
574
|
+
|
|
575
|
+
if self.use_event_bert_emb and self.event_bert_emb_dim > 0 and event_src_emb is not None:
|
|
576
|
+
# Only event_src_emb — event_dst_emb encodes dst_type (the target)
|
|
577
|
+
parts.append(event_src_emb)
|
|
578
|
+
|
|
579
|
+
return self.node_predictor(torch.cat(parts, dim=-1))
|
|
580
|
+
|
|
581
|
+
# ── Memory update ──────────────────────────────────────────────
|
|
582
|
+
|
|
583
|
+
def _compute_update(
|
|
584
|
+
self,
|
|
585
|
+
mem: torch.Tensor,
|
|
586
|
+
src_idx: torch.Tensor,
|
|
587
|
+
dst_idx: torch.Tensor,
|
|
588
|
+
edge_types: torch.Tensor,
|
|
589
|
+
timestamps: torch.Tensor,
|
|
590
|
+
edge_scores: torch.Tensor = None,
|
|
591
|
+
):
|
|
592
|
+
"""Core memory update computation (shared by diff and inplace paths).
|
|
593
|
+
|
|
594
|
+
Steps:
|
|
595
|
+
1. Compute asymmetric messages for src and dst.
|
|
596
|
+
2. (score_gated_memory) Weight messages by learned gate on edge_scores.
|
|
597
|
+
3. Scatter-mean aggregate per unique node.
|
|
598
|
+
4. (temporal_decay) Decay old memory toward zero based on time elapsed.
|
|
599
|
+
If anomaly_accumulator is also active, nodes with high accumulated
|
|
600
|
+
anomaly decay slower (stickier memory).
|
|
601
|
+
5. Run attention memory updater on (decayed) memory + aggregated messages.
|
|
602
|
+
6. (anomaly_accumulator) Update per-node anomaly EMA under no_grad.
|
|
603
|
+
|
|
604
|
+
Returns: (new_mem, unique_nodes, all_idx, all_ts)
|
|
605
|
+
"""
|
|
606
|
+
e_emb = self.edge_emb(edge_types)
|
|
607
|
+
|
|
608
|
+
src_dt = timestamps - self.last_update[src_idx]
|
|
609
|
+
dst_dt = timestamps - self.last_update[dst_idx]
|
|
610
|
+
src_time = self.time_enc(src_dt)
|
|
611
|
+
dst_time = self.time_enc(dst_dt)
|
|
612
|
+
|
|
613
|
+
# Messages: asymmetric (self, other) perspective
|
|
614
|
+
src_msg = self.message_fn(
|
|
615
|
+
mem[src_idx], mem[dst_idx],
|
|
616
|
+
self.entity_embs[src_idx], self.entity_embs[dst_idx],
|
|
617
|
+
e_emb, src_time,
|
|
618
|
+
)
|
|
619
|
+
dst_msg = self.message_fn(
|
|
620
|
+
mem[dst_idx], mem[src_idx],
|
|
621
|
+
self.entity_embs[dst_idx], self.entity_embs[src_idx],
|
|
622
|
+
e_emb, dst_time,
|
|
623
|
+
)
|
|
624
|
+
|
|
625
|
+
# Score-gated messages: weight by anomaly score before aggregation
|
|
626
|
+
if self.score_gated_memory and edge_scores is not None:
|
|
627
|
+
gate = self.score_gate(edge_scores.unsqueeze(-1)) # [B, memory_dim]
|
|
628
|
+
src_msg = src_msg * gate
|
|
629
|
+
dst_msg = dst_msg * gate
|
|
630
|
+
|
|
631
|
+
# Scatter-mean aggregate per unique node
|
|
632
|
+
all_idx = torch.cat([src_idx, dst_idx]) # [2B]
|
|
633
|
+
all_msg = torch.cat([src_msg, dst_msg]) # [2B, memory_dim]
|
|
634
|
+
all_time_enc = torch.cat([src_time, dst_time]) # [2B, time_dim]
|
|
635
|
+
all_ts = torch.cat([timestamps, timestamps]) # [2B]
|
|
636
|
+
|
|
637
|
+
aggr_msg = scatter(all_msg, all_idx, dim=0,
|
|
638
|
+
dim_size=self.num_nodes, reduce="mean")
|
|
639
|
+
aggr_time = scatter(all_time_enc, all_idx, dim=0,
|
|
640
|
+
dim_size=self.num_nodes, reduce="mean")
|
|
641
|
+
|
|
642
|
+
unique_nodes = all_idx.unique()
|
|
643
|
+
|
|
644
|
+
# Temporal decay: shrink old memory toward zero based on time elapsed
|
|
645
|
+
if self.temporal_decay:
|
|
646
|
+
node_max_ts = scatter(all_ts, all_idx, dim=0,
|
|
647
|
+
dim_size=self.num_nodes, reduce="max")
|
|
648
|
+
node_dt = node_max_ts[unique_nodes] - self.last_update[unique_nodes]
|
|
649
|
+
dt_sec = node_dt.float() / 1e9
|
|
650
|
+
base_rate = torch.nn.functional.softplus(self.decay_rate)
|
|
651
|
+
|
|
652
|
+
if self.anomaly_accumulator:
|
|
653
|
+
# High accumulated anomaly → slower decay (stickier memory)
|
|
654
|
+
accum = self.anomaly_accum[unique_nodes].unsqueeze(-1)
|
|
655
|
+
effective_rate = base_rate / (1.0 + accum)
|
|
656
|
+
else:
|
|
657
|
+
effective_rate = base_rate
|
|
658
|
+
|
|
659
|
+
decay = torch.exp(-effective_rate * torch.log1p(dt_sec.abs()).unsqueeze(-1))
|
|
660
|
+
node_mem = mem[unique_nodes] * decay
|
|
661
|
+
else:
|
|
662
|
+
node_mem = mem[unique_nodes]
|
|
663
|
+
|
|
664
|
+
new_mem = self.memory_updater(
|
|
665
|
+
node_mem,
|
|
666
|
+
aggr_msg[unique_nodes],
|
|
667
|
+
self.entity_embs[unique_nodes],
|
|
668
|
+
aggr_time[unique_nodes],
|
|
669
|
+
)
|
|
670
|
+
|
|
671
|
+
# Update anomaly accumulator (always non-differentiable)
|
|
672
|
+
if self.anomaly_accumulator and edge_scores is not None:
|
|
673
|
+
with torch.no_grad():
|
|
674
|
+
all_scores = torch.cat([edge_scores, edge_scores])
|
|
675
|
+
node_scores = scatter(all_scores.float(), all_idx, dim=0,
|
|
676
|
+
dim_size=self.num_nodes, reduce="mean")
|
|
677
|
+
self.anomaly_accum[unique_nodes] = (
|
|
678
|
+
0.95 * self.anomaly_accum[unique_nodes]
|
|
679
|
+
+ 0.05 * node_scores[unique_nodes]
|
|
680
|
+
)
|
|
681
|
+
|
|
682
|
+
return new_mem, unique_nodes, all_idx, all_ts
|
|
683
|
+
|
|
684
|
+
def update_memory(
|
|
685
|
+
self,
|
|
686
|
+
src_idx: torch.Tensor,
|
|
687
|
+
dst_idx: torch.Tensor,
|
|
688
|
+
edge_types: torch.Tensor,
|
|
689
|
+
timestamps: torch.Tensor,
|
|
690
|
+
edge_scores: torch.Tensor = None,
|
|
691
|
+
):
|
|
692
|
+
"""Update memories for nodes involved in edges.
|
|
693
|
+
|
|
694
|
+
Args:
|
|
695
|
+
edge_scores: [B] per-edge anomaly scores (detached). Used by
|
|
696
|
+
score_gated_memory to weight messages. Ignored if None.
|
|
697
|
+
"""
|
|
698
|
+
if self.training:
|
|
699
|
+
self._update_memory_diff(src_idx, dst_idx, edge_types, timestamps, edge_scores)
|
|
700
|
+
else:
|
|
701
|
+
self._update_memory_inplace(src_idx, dst_idx, edge_types, timestamps, edge_scores)
|
|
702
|
+
|
|
703
|
+
def _update_memory_diff(
|
|
704
|
+
self,
|
|
705
|
+
src_idx: torch.Tensor,
|
|
706
|
+
dst_idx: torch.Tensor,
|
|
707
|
+
edge_types: torch.Tensor,
|
|
708
|
+
timestamps: torch.Tensor,
|
|
709
|
+
edge_scores: torch.Tensor = None,
|
|
710
|
+
):
|
|
711
|
+
"""Differentiable memory update for training (creates _diff_memory overlay)."""
|
|
712
|
+
device = src_idx.device
|
|
713
|
+
mem = self._get_memory()
|
|
714
|
+
|
|
715
|
+
new_mem, unique_nodes, all_idx, all_ts = self._compute_update(
|
|
716
|
+
mem, src_idx, dst_idx, edge_types, timestamps, edge_scores,
|
|
717
|
+
)
|
|
718
|
+
|
|
719
|
+
# Build differentiable overlay: new_mem at updated positions,
|
|
720
|
+
# detached buffer elsewhere.
|
|
721
|
+
new_mem_full = scatter(new_mem, unique_nodes, dim=0,
|
|
722
|
+
dim_size=self.num_nodes, reduce="sum")
|
|
723
|
+
mask = torch.zeros(self.num_nodes, 1, device=device)
|
|
724
|
+
mask[unique_nodes] = 1.0
|
|
725
|
+
self._diff_memory = new_mem_full + self.memory.detach() * (1 - mask)
|
|
726
|
+
|
|
727
|
+
# Update last_update timestamps (non-differentiable)
|
|
728
|
+
with torch.no_grad():
|
|
729
|
+
max_ts = scatter(all_ts, all_idx, dim=0,
|
|
730
|
+
dim_size=self.num_nodes, reduce="max")
|
|
731
|
+
new_ts = max_ts[unique_nodes]
|
|
732
|
+
ts_mask = new_ts > self.last_update[unique_nodes]
|
|
733
|
+
self.last_update[unique_nodes] = torch.where(
|
|
734
|
+
ts_mask, new_ts, self.last_update[unique_nodes],
|
|
735
|
+
)
|
|
736
|
+
|
|
737
|
+
def _update_memory_inplace(
|
|
738
|
+
self,
|
|
739
|
+
src_idx: torch.Tensor,
|
|
740
|
+
dst_idx: torch.Tensor,
|
|
741
|
+
edge_types: torch.Tensor,
|
|
742
|
+
timestamps: torch.Tensor,
|
|
743
|
+
edge_scores: torch.Tensor = None,
|
|
744
|
+
):
|
|
745
|
+
"""In-place memory update for inference (no gradient tracking)."""
|
|
746
|
+
with torch.no_grad():
|
|
747
|
+
new_mem, unique_nodes, all_idx, all_ts = self._compute_update(
|
|
748
|
+
self.memory, src_idx, dst_idx, edge_types, timestamps, edge_scores,
|
|
749
|
+
)
|
|
750
|
+
|
|
751
|
+
self.memory[unique_nodes] = new_mem.detach()
|
|
752
|
+
|
|
753
|
+
max_ts = scatter(all_ts, all_idx, dim=0,
|
|
754
|
+
dim_size=self.num_nodes, reduce="max")
|
|
755
|
+
new_ts = max_ts[unique_nodes]
|
|
756
|
+
mask = new_ts > self.last_update[unique_nodes]
|
|
757
|
+
self.last_update[unique_nodes] = torch.where(
|
|
758
|
+
mask, new_ts, self.last_update[unique_nodes],
|
|
759
|
+
)
|
|
760
|
+
|
|
761
|
+
def detach_memory(self):
|
|
762
|
+
"""Sync differentiable memory overlay to buffer and clear it.
|
|
763
|
+
|
|
764
|
+
Call after loss.backward() + opt.step() and before update_memory()
|
|
765
|
+
during training. This breaks the computation graph between batches,
|
|
766
|
+
implementing truncated BPTT (depth 1).
|
|
767
|
+
"""
|
|
768
|
+
if self._diff_memory is not None:
|
|
769
|
+
self.memory.copy_(self._diff_memory.detach())
|
|
770
|
+
self._diff_memory = None
|