pidsmaker 4.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of pidsmaker might be problematic. Click here for more details.
- pidsmaker/__init__.py +22 -0
- pidsmaker/cli.py +32 -0
- pidsmaker/config/__init__.py +2 -0
- pidsmaker/config/config.py +2100 -0
- pidsmaker/config/pipeline.py +1768 -0
- pidsmaker/config/schemas.py +1032 -0
- pidsmaker/datasets.py +222 -0
- pidsmaker/debug_tests.py +30 -0
- pidsmaker/decoders/__init__.py +5 -0
- pidsmaker/decoders/custom_edge_mlp_decoder.py +17 -0
- pidsmaker/decoders/custom_mlp_decoder.py +10 -0
- pidsmaker/decoders/edge_linear_decoder.py +16 -0
- pidsmaker/decoders/inner_product_decoder.py +18 -0
- pidsmaker/decoders/nodlink_decoder.py +56 -0
- pidsmaker/detection/__init__.py +0 -0
- pidsmaker/detection/evaluation_methods/__init__.py +9 -0
- pidsmaker/detection/evaluation_methods/edge_evaluation.py +259 -0
- pidsmaker/detection/evaluation_methods/evaluation_utils.py +1730 -0
- pidsmaker/detection/evaluation_methods/host_two_stage_evaluation.py +115 -0
- pidsmaker/detection/evaluation_methods/node_evaluation.py +463 -0
- pidsmaker/detection/evaluation_methods/node_tw_evaluation.py +196 -0
- pidsmaker/detection/evaluation_methods/plot.py +192 -0
- pidsmaker/detection/evaluation_methods/queue_evaluation.py +451 -0
- pidsmaker/detection/evaluation_methods/tw_evaluation.py +95 -0
- pidsmaker/detection/flash_detection.py +162 -0
- pidsmaker/detection/magic_knn.py +190 -0
- pidsmaker/detection/node_scoring.py +52 -0
- pidsmaker/detection/threatrace_detection.py +65 -0
- pidsmaker/detection/training_methods/__init__.py +1 -0
- pidsmaker/detection/training_methods/inference_loop.py +293 -0
- pidsmaker/detection/training_methods/ocrapt_early_stop.py +165 -0
- pidsmaker/detection/training_methods/threatrace_training.py +169 -0
- pidsmaker/detection/training_methods/training_loop.py +377 -0
- pidsmaker/encoders/__init__.py +22 -0
- pidsmaker/encoders/argus_encoder.py +69 -0
- pidsmaker/encoders/custom_mlp.py +75 -0
- pidsmaker/encoders/custom_mlp_encoder.py +10 -0
- pidsmaker/encoders/egraphsage_encoder.py +56 -0
- pidsmaker/encoders/gat.py +67 -0
- pidsmaker/encoders/gcn.py +27 -0
- pidsmaker/encoders/gin.py +48 -0
- pidsmaker/encoders/glstm.py +298 -0
- pidsmaker/encoders/graph_attention.py +63 -0
- pidsmaker/encoders/gru.py +29 -0
- pidsmaker/encoders/hetero/__init__.py +4 -0
- pidsmaker/encoders/hetero/ancestor_encoder.py +98 -0
- pidsmaker/encoders/hetero/entity_encoder.py +33 -0
- pidsmaker/encoders/hetero/event_encoder.py +81 -0
- pidsmaker/encoders/hetero/hetero_graph_transformer.py +40 -0
- pidsmaker/encoders/lares_encoder.py +68 -0
- pidsmaker/encoders/linear_encoder.py +16 -0
- pidsmaker/encoders/magic_encoder.py +161 -0
- pidsmaker/encoders/rcaid_encoder.py +81 -0
- pidsmaker/encoders/rgcn.py +75 -0
- pidsmaker/encoders/sage.py +51 -0
- pidsmaker/encoders/shadewatcher_encoder.py +149 -0
- pidsmaker/encoders/sum_aggregation.py +20 -0
- pidsmaker/encoders/temporal_wrappers.py +80 -0
- pidsmaker/encoders/textrcnn.py +82 -0
- pidsmaker/encoders/tgn_encoder.py +193 -0
- pidsmaker/experiments/tuning.py +102 -0
- pidsmaker/experiments/uncertainty.py +261 -0
- pidsmaker/factory.py +1456 -0
- pidsmaker/featurization/__init__.py +0 -0
- pidsmaker/featurization/feat_inference_methods/__init__.py +7 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_HFH.py +31 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_TRW.py +67 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_alacarte.py +16 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_doc2vec.py +54 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_fasttext.py +38 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_flash.py +70 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_graph2vec.py +85 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_ocrapt_features.py +95 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_pretrained.py +1729 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_word2vec.py +56 -0
- pidsmaker/featurization/featurization_methods/__init__.py +0 -0
- pidsmaker/featurization/featurization_methods/build_trw.py +67 -0
- pidsmaker/featurization/featurization_methods/featurization_alacarte.py +748 -0
- pidsmaker/featurization/featurization_methods/featurization_doc2vec.py +99 -0
- pidsmaker/featurization/featurization_methods/featurization_fasttext.py +75 -0
- pidsmaker/featurization/featurization_methods/featurization_flash.py +203 -0
- pidsmaker/featurization/featurization_methods/featurization_graph2vec.py +243 -0
- pidsmaker/featurization/featurization_methods/featurization_trw.py +115 -0
- pidsmaker/featurization/featurization_methods/featurization_word2vec.py +87 -0
- pidsmaker/featurization/featurization_utils.py +275 -0
- pidsmaker/featurization/utils/build_random_walks.py +68 -0
- pidsmaker/featurization/utils/trw.py +203 -0
- pidsmaker/hetero.py +81 -0
- pidsmaker/losses.py +170 -0
- pidsmaker/main.py +377 -0
- pidsmaker/mimicry.py +284 -0
- pidsmaker/model.py +382 -0
- pidsmaker/objectives/__init__.py +16 -0
- pidsmaker/objectives/autoencode_edge_emb.py +43 -0
- pidsmaker/objectives/deep_graph_infomax.py +94 -0
- pidsmaker/objectives/detect_few_shot.py +21 -0
- pidsmaker/objectives/one_class.py +75 -0
- pidsmaker/objectives/predict_edge_contrastive.py +165 -0
- pidsmaker/objectives/predict_edge_supervised.py +77 -0
- pidsmaker/objectives/predict_edge_type.py +28 -0
- pidsmaker/objectives/predict_masked_struct.py +49 -0
- pidsmaker/objectives/predict_node_type.py +36 -0
- pidsmaker/objectives/predict_process_tag.py +169 -0
- pidsmaker/objectives/predict_snapshot_embedding.py +97 -0
- pidsmaker/objectives/reconstruct_edge_emb.py +16 -0
- pidsmaker/objectives/reconstruct_masked_feat.py +51 -0
- pidsmaker/objectives/reconstruct_node_emb.py +13 -0
- pidsmaker/objectives/reconstruct_node_feat.py +13 -0
- pidsmaker/objectives/validation_wrapper.py +55 -0
- pidsmaker/preprocessing/__init__.py +0 -0
- pidsmaker/preprocessing/build_graph_methods/__init__.py +1 -0
- pidsmaker/preprocessing/build_graph_methods/build_default_graphs.py +830 -0
- pidsmaker/preprocessing/build_graph_methods/build_magic_graphs.py +220 -0
- pidsmaker/preprocessing/cleaning.py +258 -0
- pidsmaker/preprocessing/transformation_methods/__init__.py +2 -0
- pidsmaker/preprocessing/transformation_methods/attack_generation/synthetic_attack_naive.py +194 -0
- pidsmaker/preprocessing/transformation_methods/transformation_dag.py +28 -0
- pidsmaker/preprocessing/transformation_methods/transformation_merge_edges.py +136 -0
- pidsmaker/preprocessing/transformation_methods/transformation_rcaid_pseudo_graph.py +510 -0
- pidsmaker/preprocessing/transformation_methods/transformation_undirected.py +24 -0
- pidsmaker/preprocessing/transformation_methods/transformation_utils.py +36 -0
- pidsmaker/pretrained/__init__.py +5 -0
- pidsmaker/pretrained/data/__init__.py +4 -0
- pidsmaker/pretrained/data/behavior_signatures.py +548 -0
- pidsmaker/pretrained/data/canonical_tokens.py +1035 -0
- pidsmaker/pretrained/data/edge_filter.py +381 -0
- pidsmaker/pretrained/data/entity_classes.py +476 -0
- pidsmaker/pretrained/data/sampler.py +926 -0
- pidsmaker/pretrained/data/tokenizer_bpe.py +1659 -0
- pidsmaker/pretrained/detect.py +1432 -0
- pidsmaker/pretrained/embedding_generator.py +252 -0
- pidsmaker/pretrained/finetune.py +1437 -0
- pidsmaker/pretrained/models/__init__.py +20 -0
- pidsmaker/pretrained/models/behavior.py +348 -0
- pidsmaker/pretrained/models/bert.py +286 -0
- pidsmaker/pretrained/models/deepwalk.py +128 -0
- pidsmaker/pretrained/models/dgi.py +120 -0
- pidsmaker/pretrained/models/gae.py +114 -0
- pidsmaker/pretrained/models/gnn_distill.py +475 -0
- pidsmaker/pretrained/models/graphmae.py +373 -0
- pidsmaker/pretrained/models/hf_pretrained.py +213 -0
- pidsmaker/pretrained/models/llama.py +110 -0
- pidsmaker/pretrained/models/modernbert.py +567 -0
- pidsmaker/pretrained/models/roberta.py +147 -0
- pidsmaker/pretrained/models/rope_utils.py +99 -0
- pidsmaker/pretrained/models/ropebert.py +322 -0
- pidsmaker/pretrained/models/spider.py +204 -0
- pidsmaker/pretrained/models/tgn.py +770 -0
- pidsmaker/pretrained/pretrain/__init__.py +3 -0
- pidsmaker/pretrained/pretrain/pretrain_behavior_cluster.py +513 -0
- pidsmaker/pretrained/pretrain/pretrain_common.py +585 -0
- pidsmaker/pretrained/pretrain/pretrain_deepwalk.py +31 -0
- pidsmaker/pretrained/pretrain/pretrain_dgi.py +143 -0
- pidsmaker/pretrained/pretrain/pretrain_gae.py +143 -0
- pidsmaker/pretrained/pretrain/pretrain_gnn_distill.py +438 -0
- pidsmaker/pretrained/pretrain/pretrain_graphmae.py +151 -0
- pidsmaker/pretrained/pretrain/pretrain_hf.py +169 -0
- pidsmaker/pretrained/pretrain/pretrain_main.py +276 -0
- pidsmaker/pretrained/pretrain/pretrain_mlm.py +491 -0
- pidsmaker/pretrained/pretrain/pretrain_spider.py +502 -0
- pidsmaker/pretrained/training_utils.py +157 -0
- pidsmaker/process_reapr_gt.py +101 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-CADETS/node_Nginx_Backdoor_06.csv +8 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-CADETS/node_Nginx_Backdoor_11.csv +4 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-CADETS/node_Nginx_Backdoor_12.csv +43 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-CADETS/node_Nginx_Backdoor_13.csv +24 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0411.csv +41 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0412.csv +0 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_browser_0412.csv +1 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +63 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +56 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +61 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +58 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-TRACE/node_trace_e3_firefox_0410.csv +11 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +11 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-TRACE/node_trace_e3_pine_0413.csv +14 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT.csv +19 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT_17.csv +107 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_appstarter_0515.csv +26 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_firefox_0517.csv +1 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_lockwatch_0517.csv +17 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_tester_0517.csv +8 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_bits_0515.csv +54 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_copykatz_0509.csv +87 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_dns_0517.csv +11 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_drakon_0517.csv +6 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-THEIA/node_THEIA_1_Firefox_Drakon_APT_BinFmt_Elevate_Inject.csv +70 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-TRACE/node_Trace_Firefox_Drakon.csv +71 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m1.csv +1 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m2.csv +1 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m3.csv +1 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m4.csv +5 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m5.csv +23 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m6.csv +18 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_s1.csv +1 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_s2.csv +1 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_s3.csv +16 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_s4.csv +22 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m1.csv +126 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m2.csv +105 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m3.csv +94 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m4.csv +139 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m5.csv +228 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m6.csv +131 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_s1.csv +118 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_s2.csv +89 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_s3.csv +133 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_s4.csv +135 -0
- pidsmaker/resources/Ground_Truth/orthrus/carbanakv2_edr/carbanakv2_edr.csv +2453 -0
- pidsmaker/resources/Ground_Truth/orthrus/h051/node_h051_0925.csv +114 -0
- pidsmaker/resources/Ground_Truth/orthrus/h201/node_h201_0923.csv +2905 -0
- pidsmaker/resources/Ground_Truth/orthrus/h501/node_h501_0924.csv +749 -0
- pidsmaker/resources/Ground_Truth/orthrus/readme.md +98 -0
- pidsmaker/resources/Ground_Truth/reapr/E3-CADETS/node_Nginx_Backdoor_06.csv +3 -0
- pidsmaker/resources/Ground_Truth/reapr/E3-CADETS/node_Nginx_Backdoor_12.csv +655 -0
- pidsmaker/resources/Ground_Truth/reapr/E3-CADETS/node_Nginx_Backdoor_13.csv +770 -0
- pidsmaker/resources/Ground_Truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +0 -0
- pidsmaker/resources/Ground_Truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +18 -0
- pidsmaker/resources/Ground_Truth/reapr/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +42 -0
- pidsmaker/resources/Ground_Truth/reapr/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +81 -0
- pidsmaker/resources/Ground_Truth/reapr/E3-TRACE/node_trace_e3_firefox_0410.csv +37 -0
- pidsmaker/resources/Ground_Truth/reapr/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +9 -0
- pidsmaker/resources/Ground_Truth/reapr/E3-TRACE/node_trace_e3_pine_0413.csv +40 -0
- pidsmaker/resources/Ground_Truth/threatrace/E3-CADETS/ground_truth.txt +12858 -0
- pidsmaker/resources/Ground_Truth/threatrace/E3-FIVEDIRECTIONS/ground_truth.txt +18420 -0
- pidsmaker/resources/Ground_Truth/threatrace/E3-THEIA/ground_truth.txt +25363 -0
- pidsmaker/resources/Ground_Truth/threatrace/E3-TRACE/ground_truth.txt +68265 -0
- pidsmaker/resources/Ground_Truth/threatrace/README.md +123 -0
- pidsmaker/resources/config/anomal_e.yml +25 -0
- pidsmaker/resources/config/argus.yml +56 -0
- pidsmaker/resources/config/attack_edges/cadets_e3.yml +435 -0
- pidsmaker/resources/config/attack_edges/cadets_e5.yml +407 -0
- pidsmaker/resources/config/attack_edges/theia_e3.yml +382 -0
- pidsmaker/resources/config/attack_edges/theia_e5.yml +387 -0
- pidsmaker/resources/config/attack_edges/trace_e3.yml +415 -0
- pidsmaker/resources/config/attack_edges/trace_e5.yml +417 -0
- pidsmaker/resources/config/default.yml +315 -0
- pidsmaker/resources/config/egraphsage.yml +95 -0
- pidsmaker/resources/config/euler.yml +104 -0
- pidsmaker/resources/config/eval/eval_set_clustering.json +3170 -0
- pidsmaker/resources/config/experiments/tuning/components/tuning_featurization_methods.yml +29 -0
- pidsmaker/resources/config/experiments/tuning/systems/clearscope_e5/tuning_orthrus.yml +14 -0
- pidsmaker/resources/config/experiments/tuning/systems/default/tuning_default_baselines.yml +13 -0
- pidsmaker/resources/config/experiments/tuning/systems/default/tuning_orthrus_fixed.yml +16 -0
- pidsmaker/resources/config/experiments/uncertainty/none.yml +5 -0
- pidsmaker/resources/config/experiments/uncertainty/run_n_times.yml +12 -0
- pidsmaker/resources/config/experiments/uncertainty/run_n_times_hyperparameters.yml +12 -0
- pidsmaker/resources/config/experiments/uncertainty/uncertainty.yml +22 -0
- pidsmaker/resources/config/flash.yml +79 -0
- pidsmaker/resources/config/jbeil.yml +65 -0
- pidsmaker/resources/config/kairos.yml +121 -0
- pidsmaker/resources/config/lares.yml +115 -0
- pidsmaker/resources/config/magic.yml +86 -0
- pidsmaker/resources/config/nodlink.yml +79 -0
- pidsmaker/resources/config/ocrapt.yml +91 -0
- pidsmaker/resources/config/orthrus.yml +120 -0
- pidsmaker/resources/config/orthrus_fixed.yml +17 -0
- pidsmaker/resources/config/orthrus_non_snooped.yml +17 -0
- pidsmaker/resources/config/pretrained/README.md +101 -0
- pidsmaker/resources/config/pretrained/cybergfm/cybergfm.yml +49 -0
- pidsmaker/resources/config/pretrained/pretrained.yml +190 -0
- pidsmaker/resources/config/pretrained/pretrained_flash.yml +9 -0
- pidsmaker/resources/config/pretrained/pretrained_kairos.yml +12 -0
- pidsmaker/resources/config/pretrained/pretrained_magic.yml +1 -0
- pidsmaker/resources/config/pretrained/pretrained_nodlink.yml +1 -0
- pidsmaker/resources/config/pretrained/pretrained_orthrus.yml +1 -0
- pidsmaker/resources/config/pretrained/pretrained_supervised.yml +13 -0
- pidsmaker/resources/config/pretrained/pretrained_threatrace.yml +8 -0
- pidsmaker/resources/config/pretrained/pretrained_velox.yml +14 -0
- pidsmaker/resources/config/prographer.yml +136 -0
- pidsmaker/resources/config/rcaid.yml +88 -0
- pidsmaker/resources/config/shadewatcher.yml +146 -0
- pidsmaker/resources/config/tests.yml +10 -0
- pidsmaker/resources/config/threatrace.yml +73 -0
- pidsmaker/resources/config/tuned_baselines/optc_net/tuned_argus.yml +4 -0
- pidsmaker/resources/config/tuned_baselines/optc_net/tuned_lares.yml +13 -0
- pidsmaker/resources/config/velox.yml +10 -0
- pidsmaker/resources/config/viz_config.yml +10 -0
- pidsmaker/tasks/__init__.py +10 -0
- pidsmaker/tasks/batching.py +49 -0
- pidsmaker/tasks/construction.py +31 -0
- pidsmaker/tasks/evaluation.py +232 -0
- pidsmaker/tasks/feat_inference.py +413 -0
- pidsmaker/tasks/featurization.py +43 -0
- pidsmaker/tasks/training.py +19 -0
- pidsmaker/tasks/transformation.py +308 -0
- pidsmaker/tasks/triage.py +143 -0
- pidsmaker/tgn.py +635 -0
- pidsmaker/tokenization/__init__.py +112 -0
- pidsmaker/tokenization/base.py +58 -0
- pidsmaker/tokenization/bpe_tokenizer.py +83 -0
- pidsmaker/tokenization/hf_tokenizer.py +61 -0
- pidsmaker/tokenization/hierarchical_tokenizer.py +44 -0
- pidsmaker/tokenization/label_tokenizer.py +24 -0
- pidsmaker/tokenization/nltk_tokenizer.py +84 -0
- pidsmaker/tokenization/substitution.py +295 -0
- pidsmaker/triage/__init__.py +0 -0
- pidsmaker/triage/tracing_methods/__init__.py +1 -0
- pidsmaker/triage/tracing_methods/depimpact.py +213 -0
- pidsmaker/triage/tracing_methods/depimpact_utils.py +537 -0
- pidsmaker/triage/tracing_methods/ocrapt_subgraph.py +267 -0
- pidsmaker/utils/__init__.py +0 -0
- pidsmaker/utils/cache_utils.py +256 -0
- pidsmaker/utils/data_utils.py +1742 -0
- pidsmaker/utils/database.py +204 -0
- pidsmaker/utils/dataset_utils.py +413 -0
- pidsmaker/utils/dataset_writer.py +1057 -0
- pidsmaker/utils/graph_store.py +634 -0
- pidsmaker/utils/labelling.py +447 -0
- pidsmaker/utils/loss_files.py +193 -0
- pidsmaker/utils/process_tags.py +44 -0
- pidsmaker/utils/utils.py +730 -0
- pidsmaker/vizgen/__init__.py +1 -0
- pidsmaker/vizgen/dimensionality_reduction.py +249 -0
- pidsmaker/vizgen/embed_exporter.py +467 -0
- pidsmaker/vizgen/exporter.py +493 -0
- pidsmaker/vizgen/html_builder.py +936 -0
- pidsmaker/vizgen/web/__init__.py +1 -0
- pidsmaker/vizgen/web/export.py +62 -0
- pidsmaker/vizgen/web/static/css/app.css +250 -0
- pidsmaker/vizgen/web/static/index.html +182 -0
- pidsmaker/vizgen/web/static/js/app.js +627 -0
- pidsmaker/vizgen/web/static/js/campaign.js +123 -0
- pidsmaker/vizgen/web/static/js/data.js +119 -0
- pidsmaker/vizgen/web/static/js/dialogs.js +240 -0
- pidsmaker/vizgen/web/static/js/jobs.js +75 -0
- pidsmaker/vizgen/web/static/js/scene.js +651 -0
- pidsmaker/vizgen/web/static/js/ui.js +370 -0
- pidsmaker/vizgen/web/static/vendor/OrbitControls.js +1045 -0
- pidsmaker/vizgen/web/static/vendor/d3.v4.min.js +2 -0
- pidsmaker/vizgen/web/static/vendor/three.min.js +6 -0
- pidsmaker/vizgen/web/viz_server.py +2176 -0
- pidsmaker-4.0.0.dist-info/METADATA +596 -0
- pidsmaker-4.0.0.dist-info/RECORD +338 -0
- pidsmaker-4.0.0.dist-info/WHEEL +5 -0
- pidsmaker-4.0.0.dist-info/entry_points.txt +2 -0
- pidsmaker-4.0.0.dist-info/licenses/LICENSE +201 -0
- pidsmaker-4.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
|
|
4
|
+
import wandb
|
|
5
|
+
|
|
6
|
+
from pidsmaker.detection.evaluation_methods import (
|
|
7
|
+
edge_evaluation,
|
|
8
|
+
host_two_stage_evaluation,
|
|
9
|
+
node_evaluation,
|
|
10
|
+
node_tw_evaluation,
|
|
11
|
+
queue_evaluation,
|
|
12
|
+
tw_evaluation,
|
|
13
|
+
)
|
|
14
|
+
from pidsmaker.detection.evaluation_methods.evaluation_utils import (
|
|
15
|
+
compute_tw_labels,
|
|
16
|
+
listdir_sorted,
|
|
17
|
+
load_losses_per_time_window,
|
|
18
|
+
)
|
|
19
|
+
from pidsmaker.utils.utils import log
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _select_epoch_without_labels(cfg, epoch_dirs):
|
|
23
|
+
"""Epoch selected by a label-free `best_model_selection` (`last_epoch`, `best_val_score`)."""
|
|
24
|
+
method = cfg.evaluation.best_model_selection
|
|
25
|
+
by_epoch = sorted(epoch_dirs, key=lambda d: int(d.split("_")[-1]))
|
|
26
|
+
if method == "last_epoch":
|
|
27
|
+
return by_epoch[-1]
|
|
28
|
+
if method == "best_val_score":
|
|
29
|
+
scores = {}
|
|
30
|
+
for d in by_epoch:
|
|
31
|
+
path = os.path.join(cfg.training._edge_losses_dir, "val_scores", f"{d}.json")
|
|
32
|
+
if os.path.exists(path):
|
|
33
|
+
with open(path) as f:
|
|
34
|
+
scores[d] = json.load(f)["val_score"]
|
|
35
|
+
if not scores:
|
|
36
|
+
raise ValueError("No validation scores found to select the best epoch.")
|
|
37
|
+
return max(scores, key=scores.get)
|
|
38
|
+
raise ValueError(
|
|
39
|
+
f"evaluate_selected_epoch_only requires a label-free best_model_selection "
|
|
40
|
+
f"(last_epoch or best_val_score), got {method}"
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def standard_evaluation(cfg, evaluation_fn, group_by_time_window=False):
|
|
45
|
+
test_losses_dir = os.path.join(cfg.training._edge_losses_dir, "test")
|
|
46
|
+
val_losses_dir = os.path.join(cfg.training._edge_losses_dir, "val")
|
|
47
|
+
|
|
48
|
+
if not os.path.exists(test_losses_dir) or cfg._from_weights:
|
|
49
|
+
sorted_files = ["model_epoch_0"]
|
|
50
|
+
else:
|
|
51
|
+
sorted_files = listdir_sorted(test_losses_dir)
|
|
52
|
+
if cfg.evaluation.evaluate_selected_epoch_only:
|
|
53
|
+
sorted_files = [_select_epoch_without_labels(cfg, sorted_files)]
|
|
54
|
+
|
|
55
|
+
# Pass the first epoch's CSV directory so compute_tw_labels enumerates the
|
|
56
|
+
# same files as node_evaluation, avoiding TW index mismatch when
|
|
57
|
+
# intra-graph batching splits graphs into multiple sub-batches.
|
|
58
|
+
first_epoch_losses_dir = os.path.join(test_losses_dir, sorted_files[0])
|
|
59
|
+
if group_by_time_window:
|
|
60
|
+
# TW-level evaluations re-group the loss files into the original time windows
|
|
61
|
+
tw_names, _ = load_losses_per_time_window(first_epoch_losses_dir, cfg)
|
|
62
|
+
tw_to_malicious_nodes = compute_tw_labels(cfg, tw_names=tw_names)
|
|
63
|
+
else:
|
|
64
|
+
tw_to_malicious_nodes = compute_tw_labels(cfg, losses_dir=first_epoch_losses_dir)
|
|
65
|
+
|
|
66
|
+
best_metrics = {
|
|
67
|
+
"val_score": float("-inf"),
|
|
68
|
+
"adp_score": float("-inf"),
|
|
69
|
+
"discrimination": float("-inf"),
|
|
70
|
+
"ap@10": float("-inf"),
|
|
71
|
+
"ap": float("-inf"),
|
|
72
|
+
"stats": None,
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
out_dir = cfg.evaluation._precision_recall_dir
|
|
76
|
+
|
|
77
|
+
save_files_to_wandb = cfg._experiment != "uncertainty"
|
|
78
|
+
|
|
79
|
+
for model_epoch_dir in sorted_files:
|
|
80
|
+
log(f"[@{model_epoch_dir}] - Test Evaluation", pre_return_line=True)
|
|
81
|
+
|
|
82
|
+
test_tw_path = os.path.join(test_losses_dir, model_epoch_dir)
|
|
83
|
+
val_tw_path = os.path.join(val_losses_dir, model_epoch_dir)
|
|
84
|
+
|
|
85
|
+
stats = evaluation_fn(
|
|
86
|
+
val_tw_path,
|
|
87
|
+
test_tw_path,
|
|
88
|
+
model_epoch_dir,
|
|
89
|
+
cfg,
|
|
90
|
+
tw_to_malicious_nodes=tw_to_malicious_nodes,
|
|
91
|
+
)
|
|
92
|
+
val_score_file = os.path.join(
|
|
93
|
+
cfg.training._edge_losses_dir, "val_scores", f"{model_epoch_dir}.json"
|
|
94
|
+
)
|
|
95
|
+
if os.path.exists(val_score_file):
|
|
96
|
+
with open(val_score_file) as f:
|
|
97
|
+
stats["val_score"] = json.load(f)["val_score"]
|
|
98
|
+
|
|
99
|
+
log(f"[@{model_epoch_dir}] - Stats")
|
|
100
|
+
for k, v in stats.items():
|
|
101
|
+
log(f"{k}: {v}")
|
|
102
|
+
|
|
103
|
+
stats["epoch"] = int(model_epoch_dir.split("_")[-1])
|
|
104
|
+
|
|
105
|
+
if save_files_to_wandb:
|
|
106
|
+
# stats["simple_scores_img"] = wandb.Image(os.path.join(out_dir, f"simple_scores_{model_epoch_dir}.png"))
|
|
107
|
+
|
|
108
|
+
scores = os.path.join(out_dir, f"scores_{model_epoch_dir}.png")
|
|
109
|
+
if os.path.exists(scores):
|
|
110
|
+
stats["scores_img"] = wandb.Image(scores)
|
|
111
|
+
|
|
112
|
+
# pr = os.path.join(out_dir, f"pr_curve_{model_epoch_dir}.png")
|
|
113
|
+
# if os.path.exists(pr):
|
|
114
|
+
# stats["precision_recall_img"] = wandb.Image(pr)
|
|
115
|
+
|
|
116
|
+
adp = os.path.join(out_dir, f"adp_curve_{model_epoch_dir}.png")
|
|
117
|
+
if os.path.exists(adp):
|
|
118
|
+
stats["adp_img"] = wandb.Image(adp)
|
|
119
|
+
|
|
120
|
+
# seen_scores = os.path.join(out_dir, f"seen_score_{model_epoch_dir}.png")
|
|
121
|
+
# if os.path.exists(seen_scores):
|
|
122
|
+
# stats["seen_scores_img"] = wandb.Image(seen_scores)
|
|
123
|
+
|
|
124
|
+
discrim = os.path.join(out_dir, f"discrim_curve_{model_epoch_dir}.png")
|
|
125
|
+
if os.path.exists(discrim):
|
|
126
|
+
stats["discrim_img"] = wandb.Image(discrim)
|
|
127
|
+
|
|
128
|
+
distrib = os.path.join(out_dir, f"distrib_{model_epoch_dir}.png")
|
|
129
|
+
if os.path.exists(distrib):
|
|
130
|
+
stats["distrib_img"] = wandb.Image(distrib)
|
|
131
|
+
|
|
132
|
+
wandb.log(stats)
|
|
133
|
+
|
|
134
|
+
best_metrics = best_metric_pick_best_epoch(stats, best_metrics, cfg)
|
|
135
|
+
|
|
136
|
+
if save_files_to_wandb and "neat_scores_img_file" in best_metrics["stats"]:
|
|
137
|
+
# We only store the scores for the best run
|
|
138
|
+
# wandb.save(best_metrics["stats"]["scores_file"], out_dir)
|
|
139
|
+
wandb.save(best_metrics["stats"]["neat_scores_img_file"], out_dir)
|
|
140
|
+
|
|
141
|
+
log(f"Best scores file: {best_metrics['stats'].get('scores_file')}")
|
|
142
|
+
log(f"Best model path: {best_metrics['stats'].get('model_path')}")
|
|
143
|
+
|
|
144
|
+
return best_metrics["stats"]
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def best_metric_pick_best_epoch(stats, best_metrics, cfg):
|
|
148
|
+
best_model_selection = cfg.evaluation.best_model_selection
|
|
149
|
+
|
|
150
|
+
# Last evaluated epoch (epochs are evaluated in increasing order)
|
|
151
|
+
if best_model_selection == "last_epoch":
|
|
152
|
+
if best_metrics["stats"] is None or stats["epoch"] >= best_metrics["stats"]["epoch"]:
|
|
153
|
+
best_metrics["stats"] = stats
|
|
154
|
+
return best_metrics
|
|
155
|
+
|
|
156
|
+
# Selection on the MCC of the predictions on the test set (as the code of LARES)
|
|
157
|
+
if best_model_selection == "best_mcc":
|
|
158
|
+
mcc = stats.get("mcc", float("-inf"))
|
|
159
|
+
mcc = float("-inf") if mcc != mcc else mcc
|
|
160
|
+
if best_metrics["stats"] is None or mcc > best_metrics.get("mcc", float("-inf")):
|
|
161
|
+
best_metrics["mcc"] = mcc
|
|
162
|
+
best_metrics["stats"] = stats
|
|
163
|
+
return best_metrics
|
|
164
|
+
|
|
165
|
+
# Selection on validation data only (e.g. link prediction AUC + AP of the validation edges)
|
|
166
|
+
if best_model_selection == "best_val_score":
|
|
167
|
+
if "val_score" not in stats:
|
|
168
|
+
raise ValueError(
|
|
169
|
+
"best_model_selection=best_val_score requires an objective computing a validation "
|
|
170
|
+
"score (e.g. predict_edge_contrastive)."
|
|
171
|
+
)
|
|
172
|
+
if best_metrics["stats"] is None or stats["val_score"] > best_metrics["val_score"]:
|
|
173
|
+
best_metrics["val_score"] = stats["val_score"]
|
|
174
|
+
best_metrics["stats"] = stats
|
|
175
|
+
return best_metrics
|
|
176
|
+
|
|
177
|
+
# ADP and discrimination are only computed by node/edge-level evaluations.
|
|
178
|
+
# Other evaluations (tw, node_tw) fall back to selecting the epoch with best AP.
|
|
179
|
+
if "adp_score" not in stats or "discrimination" not in stats:
|
|
180
|
+
stats_ap = stats.get("ap", float("nan"))
|
|
181
|
+
stats_ap = float("-inf") if stats_ap != stats_ap else stats_ap # nan => -inf
|
|
182
|
+
if best_metrics["stats"] is None or stats_ap > best_metrics["ap"]:
|
|
183
|
+
best_metrics["ap"] = stats_ap
|
|
184
|
+
best_metrics["stats"] = stats
|
|
185
|
+
return best_metrics
|
|
186
|
+
|
|
187
|
+
if best_model_selection == "best_adp":
|
|
188
|
+
condition = (stats["adp_score"] > best_metrics["adp_score"]) or (
|
|
189
|
+
stats["adp_score"] == best_metrics["adp_score"]
|
|
190
|
+
and stats["discrimination"] > best_metrics["discrimination"]
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
elif best_model_selection == "best_discrimination":
|
|
194
|
+
condition = stats["discrimination"] > best_metrics["discrimination"]
|
|
195
|
+
|
|
196
|
+
elif best_model_selection == "best_ap@10":
|
|
197
|
+
condition = (stats["ap@10"] > best_metrics["ap@10"]) or (
|
|
198
|
+
stats["ap@10"] == best_metrics["ap@10"]
|
|
199
|
+
and stats["discrimination"] > best_metrics["discrimination"]
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
else:
|
|
203
|
+
raise ValueError(f"Invalid best model selection {best_model_selection}")
|
|
204
|
+
|
|
205
|
+
if condition:
|
|
206
|
+
best_metrics["adp_score"] = stats["adp_score"]
|
|
207
|
+
best_metrics["discrimination"] = stats["discrimination"]
|
|
208
|
+
best_metrics["ap@10"] = stats.get("ap@10", float("-inf"))
|
|
209
|
+
best_metrics["stats"] = stats
|
|
210
|
+
return best_metrics
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def main(cfg):
|
|
214
|
+
method = cfg.evaluation.used_method.strip()
|
|
215
|
+
if method == "node_evaluation":
|
|
216
|
+
return standard_evaluation(cfg, evaluation_fn=node_evaluation.main)
|
|
217
|
+
elif method == "tw_evaluation":
|
|
218
|
+
return standard_evaluation(
|
|
219
|
+
cfg, evaluation_fn=tw_evaluation.main, group_by_time_window=True
|
|
220
|
+
)
|
|
221
|
+
elif method == "node_tw_evaluation":
|
|
222
|
+
return standard_evaluation(
|
|
223
|
+
cfg, evaluation_fn=node_tw_evaluation.main, group_by_time_window=True
|
|
224
|
+
)
|
|
225
|
+
elif method == "queue_evaluation":
|
|
226
|
+
return queue_evaluation.main(cfg)
|
|
227
|
+
elif method == "edge_evaluation":
|
|
228
|
+
return standard_evaluation(cfg, evaluation_fn=edge_evaluation.main)
|
|
229
|
+
elif method == "host_two_stage_evaluation":
|
|
230
|
+
return standard_evaluation(cfg, evaluation_fn=host_two_stage_evaluation.main)
|
|
231
|
+
else:
|
|
232
|
+
raise ValueError(f"Invalid evaluation method {cfg.evaluation.used_method}")
|
|
@@ -0,0 +1,413 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import torch
|
|
5
|
+
|
|
6
|
+
from pidsmaker.config import update_cfg_for_multi_dataset
|
|
7
|
+
from pidsmaker.featurization.feat_inference_methods import (
|
|
8
|
+
feat_inference_alacarte,
|
|
9
|
+
feat_inference_pretrained,
|
|
10
|
+
feat_inference_doc2vec,
|
|
11
|
+
feat_inference_fasttext,
|
|
12
|
+
feat_inference_flash,
|
|
13
|
+
feat_inference_graph2vec,
|
|
14
|
+
feat_inference_HFH,
|
|
15
|
+
feat_inference_ocrapt_features,
|
|
16
|
+
feat_inference_TRW,
|
|
17
|
+
feat_inference_word2vec,
|
|
18
|
+
)
|
|
19
|
+
from pidsmaker.featurization.feat_inference_methods.feat_inference_pretrained import GraphBasedEncoder
|
|
20
|
+
from pidsmaker.utils.data_utils import COMPACT_MSG_KEYS, CollatableTemporalData
|
|
21
|
+
from pidsmaker.utils.dataset_utils import (
|
|
22
|
+
aggregated_edge_attribute_columns,
|
|
23
|
+
encode_aggregated_edge_attributes,
|
|
24
|
+
encode_edge_attributes,
|
|
25
|
+
get_input_edge_attributes,
|
|
26
|
+
uses_aggregated_edge_attributes,
|
|
27
|
+
get_node_map,
|
|
28
|
+
get_rel2id,
|
|
29
|
+
)
|
|
30
|
+
from pidsmaker.utils.graph_store import load_graph_columns
|
|
31
|
+
from pidsmaker.utils.utils import (
|
|
32
|
+
gen_relation_onehot,
|
|
33
|
+
get_multi_datasets,
|
|
34
|
+
get_split_to_files,
|
|
35
|
+
log_tqdm,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _onehot_table(type2oh):
|
|
40
|
+
"""Stacks the one-hot vectors of a `gen_relation_onehot` mapping into a matrix.
|
|
41
|
+
|
|
42
|
+
Returns the (num_types + 1, d) matrix, whose last row is all zeros (missing type),
|
|
43
|
+
and the mapping {type_name: row}.
|
|
44
|
+
"""
|
|
45
|
+
names = [k for k in type2oh if isinstance(k, str)]
|
|
46
|
+
table = torch.stack([type2oh[k] for k in names] + [torch.zeros_like(type2oh[names[0]])])
|
|
47
|
+
return table, {name: i for i, name in enumerate(names)}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _edge_columns_from_graph(graph):
|
|
51
|
+
"""(nodes, node types, src rows, dst rows, times, labels, edge labels) in `graph.edges` order."""
|
|
52
|
+
src, dst, t, y, labels = [], [], [], [], []
|
|
53
|
+
for u, v, attr in graph.edges(data=True):
|
|
54
|
+
src.append(u)
|
|
55
|
+
dst.append(v)
|
|
56
|
+
t.append(int(attr["time"]))
|
|
57
|
+
y.append(int(attr.get("y", 0)))
|
|
58
|
+
labels.append(attr.get("label"))
|
|
59
|
+
|
|
60
|
+
# Map each node to a local row index, so that lookups are done once per node
|
|
61
|
+
nodes = list(graph.nodes)
|
|
62
|
+
node2row = {n: i for i, n in enumerate(nodes)}
|
|
63
|
+
src_rows = torch.tensor([node2row[u] for u in src], dtype=torch.long)
|
|
64
|
+
dst_rows = torch.tensor([node2row[v] for v in dst], dtype=torch.long)
|
|
65
|
+
node_attrs = graph.nodes
|
|
66
|
+
node_types = [node_attrs[n]["node_type"] for n in nodes]
|
|
67
|
+
return nodes, node_types, src_rows, dst_rows, t, y, labels
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _edge_columns_from_store(cols):
|
|
71
|
+
"""Same as `_edge_columns_from_graph`, from the stored columns (no networkx graph)."""
|
|
72
|
+
m = len(cols.src)
|
|
73
|
+
t = [int(x) for x in cols.edge_attrs["time"]]
|
|
74
|
+
y = [int(x) for x in cols.edge_attrs["y"]] if "y" in cols.edge_attrs else [0] * m
|
|
75
|
+
labels = cols.edge_attrs["label"] if "label" in cols.edge_attrs else [None] * m
|
|
76
|
+
src_rows = torch.from_numpy(cols.src.astype(np.int64))
|
|
77
|
+
dst_rows = torch.from_numpy(cols.dst.astype(np.int64))
|
|
78
|
+
return cols.node_ids, cols.node_attrs["node_type"], src_rows, dst_rows, t, y, labels
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _edge_attr_features(cfg, path, graph=None, cols=None):
|
|
82
|
+
"""Edge attribute features of the graph at `path`, in `graph.edges` order (None without
|
|
83
|
+
attributes). `graph` or its stored columns `cols` are used when already loaded."""
|
|
84
|
+
names = [a.name for a in get_input_edge_attributes(cfg)]
|
|
85
|
+
if not names:
|
|
86
|
+
return None
|
|
87
|
+
if uses_aggregated_edge_attributes(cfg):
|
|
88
|
+
# Attributes aggregated over the events of merged edges (see `merge_edges`)
|
|
89
|
+
agg = [c for cols in aggregated_edge_attribute_columns(cfg).values() for c, _ in cols]
|
|
90
|
+
if cols is not None and all(c in cols.edge_attrs for c in agg):
|
|
91
|
+
columns = {c: list(cols.edge_attrs[c]) for c in agg}
|
|
92
|
+
else:
|
|
93
|
+
if graph is None:
|
|
94
|
+
graph = torch.load(path)
|
|
95
|
+
columns = {c: [] for c in agg}
|
|
96
|
+
for _, _, attr in graph.edges(data=True):
|
|
97
|
+
for c in agg:
|
|
98
|
+
columns[c].append(attr.get(c))
|
|
99
|
+
return encode_aggregated_edge_attributes(cfg, columns)
|
|
100
|
+
# Edges added by transformations (e.g. R-Caid's pseudo-graph) may have no attributes:
|
|
101
|
+
# their missing attributes are null (OTHER for categorical, 0 for numeric attributes)
|
|
102
|
+
if cols is not None and all(name in cols.edge_attrs for name in names):
|
|
103
|
+
columns = {name: list(cols.edge_attrs[name]) for name in names}
|
|
104
|
+
else:
|
|
105
|
+
if graph is None:
|
|
106
|
+
graph = torch.load(path)
|
|
107
|
+
columns = {name: [] for name in names}
|
|
108
|
+
for _, _, attr in graph.edges(data=True):
|
|
109
|
+
for name in names:
|
|
110
|
+
columns[name].append(attr.get(name))
|
|
111
|
+
return encode_edge_attributes(cfg, columns)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _edge_weights(path, graph=None, cols=None):
|
|
115
|
+
"""(E,) float tensor of the `weight` attribute of the edges, None if edges have no weight."""
|
|
116
|
+
if cols is not None:
|
|
117
|
+
if "weight" not in cols.edge_attrs:
|
|
118
|
+
return None
|
|
119
|
+
return torch.tensor([float(w) for w in cols.edge_attrs["weight"]], dtype=torch.float)
|
|
120
|
+
if graph is None:
|
|
121
|
+
graph = torch.load(path)
|
|
122
|
+
weights = [attr.get("weight") for _, _, attr in graph.edges(data=True)]
|
|
123
|
+
if not weights or any(w is None for w in weights):
|
|
124
|
+
return None
|
|
125
|
+
return torch.tensor(weights, dtype=torch.float)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _vectorized_edge_msg(edge_columns, indexid2vec, etype2oh, ntype2oh):
|
|
129
|
+
"""Builds the edge messages of a graph with per-node (not per-edge) lookups.
|
|
130
|
+
|
|
131
|
+
Equivalent to concatenating, for each edge in `graph.edges` order,
|
|
132
|
+
[src_type_onehot, src_emb, edge_type_onehot, dst_type_onehot, dst_emb].
|
|
133
|
+
"""
|
|
134
|
+
nodes, node_type_list, src_rows, dst_rows, t, y, labels = edge_columns
|
|
135
|
+
|
|
136
|
+
# Edge endpoints in the original node order, before restricting the rows below
|
|
137
|
+
node_ids = [int(n) for n in nodes]
|
|
138
|
+
src = [node_ids[r] for r in src_rows.tolist()]
|
|
139
|
+
dst = [node_ids[r] for r in dst_rows.tolist()]
|
|
140
|
+
|
|
141
|
+
# Only nodes with edges get features: like the former per-edge lookups, isolated nodes
|
|
142
|
+
# are never looked up (they may have no embedding, e.g. with edge-based featurizations)
|
|
143
|
+
used = torch.unique(torch.cat([src_rows, dst_rows]))
|
|
144
|
+
remap = torch.full((len(nodes),), -1, dtype=torch.long)
|
|
145
|
+
remap[used] = torch.arange(used.numel())
|
|
146
|
+
src_rows, dst_rows = remap[src_rows], remap[dst_rows]
|
|
147
|
+
used = used.tolist()
|
|
148
|
+
nodes = [nodes[i] for i in used]
|
|
149
|
+
node_type_list = [node_type_list[i] for i in used]
|
|
150
|
+
|
|
151
|
+
ntype_table, ntype2row = _onehot_table(ntype2oh)
|
|
152
|
+
node_type_rows = torch.tensor([ntype2row[nt] for nt in node_type_list], dtype=torch.long)
|
|
153
|
+
node_types = ntype_table[node_type_rows]
|
|
154
|
+
|
|
155
|
+
etype_table, etype2row = _onehot_table(etype2oh)
|
|
156
|
+
missing = etype_table.shape[0] - 1
|
|
157
|
+
edge_type_rows = torch.tensor(
|
|
158
|
+
[missing if l is None else etype2row[l] for l in labels], dtype=torch.long
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
if indexid2vec is None:
|
|
162
|
+
node_feats = node_types
|
|
163
|
+
else:
|
|
164
|
+
# indexid2vec may use string keys (word2vec) or int keys;
|
|
165
|
+
# graph node IDs are cast to int, so try both.
|
|
166
|
+
def _lookup(nid):
|
|
167
|
+
nid = int(nid)
|
|
168
|
+
try:
|
|
169
|
+
return indexid2vec[nid]
|
|
170
|
+
except KeyError:
|
|
171
|
+
return indexid2vec[str(nid)]
|
|
172
|
+
|
|
173
|
+
node_embs = torch.from_numpy(np.stack([_lookup(n) for n in nodes])).float()
|
|
174
|
+
node_feats = torch.cat([node_types, node_embs], dim=1)
|
|
175
|
+
|
|
176
|
+
# The message of an edge is [src_feats | edge_type | dst_feats], where a node's feats
|
|
177
|
+
# are [node_type | node_emb]. Instead of materializing it (E x D, with each node's
|
|
178
|
+
# embedding repeated for each of its edges), each node's feats are stored once with
|
|
179
|
+
# the row of each edge's src/dst/type: see `expand_compact_msg`.
|
|
180
|
+
compact = {
|
|
181
|
+
COMPACT_MSG_KEYS[0]: node_feats.to(torch.float),
|
|
182
|
+
COMPACT_MSG_KEYS[1]: src_rows.to(torch.int32),
|
|
183
|
+
COMPACT_MSG_KEYS[2]: dst_rows.to(torch.int32),
|
|
184
|
+
COMPACT_MSG_KEYS[3]: etype_table.to(torch.float),
|
|
185
|
+
COMPACT_MSG_KEYS[4]: edge_type_rows.to(torch.int32),
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
return compact, src, dst, t, y
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def feat_inference(indexid2vec, etype2oh, ntype2oh, sorted_paths, out_dir, cfg, bert_generator=None, indexid2msg=None):
|
|
192
|
+
"""Generate edge embeddings from node embeddings or a SPIDER encoder.
|
|
193
|
+
|
|
194
|
+
Args:
|
|
195
|
+
indexid2vec: Pre-computed node embeddings (None for spider or only_type methods)
|
|
196
|
+
etype2oh: Edge type one-hot encodings
|
|
197
|
+
ntype2oh: Node type one-hot encodings
|
|
198
|
+
sorted_paths: Paths to graph files
|
|
199
|
+
out_dir: Output directory for edge embeddings
|
|
200
|
+
cfg: Configuration object
|
|
201
|
+
bert_generator: Optional SpiderEmbeddingGenerator for temporal embeddings
|
|
202
|
+
indexid2msg: Optional node label mapping for SPIDER
|
|
203
|
+
"""
|
|
204
|
+
for i, path in enumerate(log_tqdm(sorted_paths, desc="Computing edge embeddings")):
|
|
205
|
+
# The standard path only needs the graph's columns, not a networkx graph
|
|
206
|
+
cols = load_graph_columns(path) if bert_generator is None else None
|
|
207
|
+
graph = torch.load(path) if cols is None else None
|
|
208
|
+
|
|
209
|
+
src, dst, msg, t, y = [], [], [], [], []
|
|
210
|
+
|
|
211
|
+
# For SPIDER: batch process edges to avoid memory issues with millions of edges
|
|
212
|
+
if bert_generator is not None:
|
|
213
|
+
# Collect all edge data first
|
|
214
|
+
all_edge_data = []
|
|
215
|
+
for u, v, k, attr in graph.edges(data=True, keys=True):
|
|
216
|
+
src.append(int(u))
|
|
217
|
+
dst.append(int(v))
|
|
218
|
+
timestamp = int(attr["time"])
|
|
219
|
+
t.append(timestamp)
|
|
220
|
+
y.append(int(attr.get("y", 0)))
|
|
221
|
+
|
|
222
|
+
if "label" in attr:
|
|
223
|
+
edge_label = etype2oh[attr["label"]]
|
|
224
|
+
else:
|
|
225
|
+
edge_label = torch.zeros_like(etype2oh[list(etype2oh.keys())[0]])
|
|
226
|
+
|
|
227
|
+
all_edge_data.append({
|
|
228
|
+
'src': u,
|
|
229
|
+
'dst': v,
|
|
230
|
+
'timestamp': timestamp,
|
|
231
|
+
'src_type': ntype2oh[graph.nodes[u]["node_type"]],
|
|
232
|
+
'dst_type': ntype2oh[graph.nodes[v]["node_type"]],
|
|
233
|
+
'edge_label': edge_label,
|
|
234
|
+
})
|
|
235
|
+
|
|
236
|
+
# Process edges in batches to avoid memory issues
|
|
237
|
+
edge_batch_size = cfg.feat_inference.edge_batch_size
|
|
238
|
+
|
|
239
|
+
for batch_start in range(0, len(all_edge_data), edge_batch_size):
|
|
240
|
+
batch_edges = all_edge_data[batch_start : batch_start + edge_batch_size]
|
|
241
|
+
|
|
242
|
+
# Prepare nodes and timestamps for this batch
|
|
243
|
+
batch_nodes = []
|
|
244
|
+
batch_timestamps = []
|
|
245
|
+
for e in batch_edges:
|
|
246
|
+
batch_nodes.extend([e['src'], e['dst']])
|
|
247
|
+
batch_timestamps.extend([e['timestamp'], e['timestamp']])
|
|
248
|
+
|
|
249
|
+
# Generate embeddings for this batch (handles src+dst together)
|
|
250
|
+
batch_embeddings_list = bert_generator.get_batch_embeddings(
|
|
251
|
+
nodes=batch_nodes, graph=graph, indexid2msg=indexid2msg, timestamps=batch_timestamps
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
# Build messages for this batch vectorized
|
|
255
|
+
# Embeddings are ordered as: [src0, dst0, src1, dst1, ...]
|
|
256
|
+
src_embs = torch.from_numpy(
|
|
257
|
+
np.stack([batch_embeddings_list[idx * 2] for idx in range(len(batch_edges))])
|
|
258
|
+
).float()
|
|
259
|
+
dst_embs = torch.from_numpy(
|
|
260
|
+
np.stack([batch_embeddings_list[idx * 2 + 1] for idx in range(len(batch_edges))])
|
|
261
|
+
).float()
|
|
262
|
+
src_types = torch.stack([e['src_type'] for e in batch_edges])
|
|
263
|
+
dst_types = torch.stack([e['dst_type'] for e in batch_edges])
|
|
264
|
+
edge_labels = torch.stack([e['edge_label'] for e in batch_edges])
|
|
265
|
+
msg.append(torch.cat([src_types, src_embs, edge_labels, dst_types, dst_embs], dim=1))
|
|
266
|
+
|
|
267
|
+
# Standard processing (pre-computed embeddings or types only)
|
|
268
|
+
else:
|
|
269
|
+
num_edges = graph.number_of_edges() if cols is None else len(cols.src)
|
|
270
|
+
if num_edges == 0:
|
|
271
|
+
continue # skip empty graphs (no edges in this time window)
|
|
272
|
+
|
|
273
|
+
edge_columns = (
|
|
274
|
+
_edge_columns_from_graph(graph) if cols is None else _edge_columns_from_store(cols)
|
|
275
|
+
)
|
|
276
|
+
compact, src, dst, t, y = _vectorized_edge_msg(edge_columns, indexid2vec, etype2oh, ntype2oh)
|
|
277
|
+
|
|
278
|
+
data = CollatableTemporalData(
|
|
279
|
+
src=torch.tensor(src).to(torch.long),
|
|
280
|
+
dst=torch.tensor(dst).to(torch.long),
|
|
281
|
+
t=torch.tensor(t).to(torch.long),
|
|
282
|
+
msg=torch.vstack(msg).to(torch.float) if bert_generator is not None else None,
|
|
283
|
+
y=torch.tensor(y).to(torch.long),
|
|
284
|
+
)
|
|
285
|
+
if bert_generator is None:
|
|
286
|
+
for key, value in compact.items():
|
|
287
|
+
data[key] = value
|
|
288
|
+
edge_attrs = _edge_attr_features(cfg, path, graph=graph, cols=cols)
|
|
289
|
+
if edge_attrs is not None:
|
|
290
|
+
data.edge_attr_feats = edge_attrs
|
|
291
|
+
# Weights of the edges merged by the `merge_edges` transformation
|
|
292
|
+
edge_weight = _edge_weights(path, graph=graph, cols=cols)
|
|
293
|
+
if edge_weight is not None:
|
|
294
|
+
data.edge_weight = edge_weight
|
|
295
|
+
|
|
296
|
+
os.makedirs(out_dir, exist_ok=True)
|
|
297
|
+
file = path.split("/")[-1]
|
|
298
|
+
torch.save(data, os.path.join(out_dir, f"{file}.TemporalData.simple"))
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def get_indexid2vec(cfg):
|
|
302
|
+
method = cfg.featurization.used_method.strip()
|
|
303
|
+
if method in ["only_type", "only_ones"]:
|
|
304
|
+
return None
|
|
305
|
+
if method == "graph2vec": # nodes get their type, snapshots their graph2vec embedding
|
|
306
|
+
return None
|
|
307
|
+
if method == "alacarte":
|
|
308
|
+
return feat_inference_alacarte.main(cfg)
|
|
309
|
+
if method == "doc2vec":
|
|
310
|
+
return feat_inference_doc2vec.main(cfg)
|
|
311
|
+
if method == "hierarchical_hashing":
|
|
312
|
+
return feat_inference_HFH.main(cfg)
|
|
313
|
+
if method == "word2vec":
|
|
314
|
+
return feat_inference_word2vec.main(cfg)
|
|
315
|
+
if method == "ocrapt_features":
|
|
316
|
+
return feat_inference_ocrapt_features.main(cfg)
|
|
317
|
+
if method == "temporal_rw":
|
|
318
|
+
return feat_inference_TRW.main(cfg)
|
|
319
|
+
if method == "flash":
|
|
320
|
+
return feat_inference_flash.main(cfg)
|
|
321
|
+
if method == "fasttext":
|
|
322
|
+
return feat_inference_fasttext.main(cfg)
|
|
323
|
+
if method == "pretrained":
|
|
324
|
+
return feat_inference_pretrained.main(cfg)
|
|
325
|
+
|
|
326
|
+
raise ValueError(f"Invalid node embedding method {method}")
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def main_from_config(cfg):
|
|
330
|
+
# When gnn_training uses spider, detection reads raw graphs directly
|
|
331
|
+
# and never consumes the .TemporalData.simple files produced here.
|
|
332
|
+
if cfg.training.used_method.strip() == "pretrained":
|
|
333
|
+
from pidsmaker.utils.utils import log
|
|
334
|
+
log("feat_inference: skipping edge embedding computation — "
|
|
335
|
+
"gnn_training.used_method=spider reads raw graphs directly.")
|
|
336
|
+
return
|
|
337
|
+
|
|
338
|
+
rel2id = get_rel2id(cfg)
|
|
339
|
+
ntype2id = get_node_map(cfg)
|
|
340
|
+
etype2onehot = gen_relation_onehot(rel2id=rel2id)
|
|
341
|
+
ntype2onehot = gen_relation_onehot(rel2id=ntype2id)
|
|
342
|
+
|
|
343
|
+
base_dir = cfg.transformation._graphs_dir
|
|
344
|
+
split_to_files = get_split_to_files(cfg, base_dir)
|
|
345
|
+
|
|
346
|
+
# Here we get either:
|
|
347
|
+
# - a mapping {node_id => embedding vector} for non-graph methods
|
|
348
|
+
# - a GraphBasedEncoder for graph-based methods (GraphMAE/GAE/DGI),
|
|
349
|
+
# which computes per-graph embeddings to avoid cross-graph data snooping
|
|
350
|
+
indexid2vec_or_encoder = get_indexid2vec(cfg)
|
|
351
|
+
|
|
352
|
+
graph_encoder = None
|
|
353
|
+
if isinstance(indexid2vec_or_encoder, GraphBasedEncoder):
|
|
354
|
+
graph_encoder = indexid2vec_or_encoder
|
|
355
|
+
indexid2vec = None # will be computed per-graph
|
|
356
|
+
else:
|
|
357
|
+
indexid2vec = indexid2vec_or_encoder
|
|
358
|
+
|
|
359
|
+
bert_generator = None
|
|
360
|
+
indexid2msg = None
|
|
361
|
+
|
|
362
|
+
# Create edges for Train, Val, Test sets
|
|
363
|
+
for split, sorted_paths in split_to_files.items():
|
|
364
|
+
if graph_encoder is not None:
|
|
365
|
+
# Per-graph encoding: each graph gets embeddings from its own structure only
|
|
366
|
+
for path in log_tqdm(sorted_paths, desc=f"Computing edge embeddings ({split})"):
|
|
367
|
+
per_graph_indexid2vec = graph_encoder.encode_graph(path)
|
|
368
|
+
feat_inference(
|
|
369
|
+
indexid2vec=per_graph_indexid2vec,
|
|
370
|
+
etype2oh=etype2onehot,
|
|
371
|
+
ntype2oh=ntype2onehot,
|
|
372
|
+
sorted_paths=[path],
|
|
373
|
+
out_dir=os.path.join(cfg.feat_inference._edge_embeds_dir, f"{split}/"),
|
|
374
|
+
cfg=cfg,
|
|
375
|
+
bert_generator=bert_generator,
|
|
376
|
+
indexid2msg=indexid2msg,
|
|
377
|
+
)
|
|
378
|
+
else:
|
|
379
|
+
feat_inference(
|
|
380
|
+
indexid2vec=indexid2vec,
|
|
381
|
+
etype2oh=etype2onehot,
|
|
382
|
+
ntype2oh=ntype2onehot,
|
|
383
|
+
sorted_paths=sorted_paths,
|
|
384
|
+
out_dir=os.path.join(cfg.feat_inference._edge_embeds_dir, f"{split}/"),
|
|
385
|
+
cfg=cfg,
|
|
386
|
+
bert_generator=bert_generator,
|
|
387
|
+
indexid2msg=indexid2msg,
|
|
388
|
+
)
|
|
389
|
+
# Whole-graph embedding of each snapshot (ProGrapher)
|
|
390
|
+
if cfg.featurization.used_method.strip() == "graph2vec":
|
|
391
|
+
out_dir = os.path.join(cfg.feat_inference._edge_embeds_dir, f"{split}/")
|
|
392
|
+
feat_inference_graph2vec.main(cfg, sorted_paths, out_dir)
|
|
393
|
+
|
|
394
|
+
# Release GPU memory if using graph encoder
|
|
395
|
+
if graph_encoder is not None:
|
|
396
|
+
graph_encoder.cleanup()
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def main(cfg):
|
|
400
|
+
multi_dataset_training = cfg.batching.multi_dataset_training
|
|
401
|
+
if not multi_dataset_training:
|
|
402
|
+
main_from_config(cfg)
|
|
403
|
+
|
|
404
|
+
# Multi-dataset mode
|
|
405
|
+
else:
|
|
406
|
+
trained_model_dir = cfg.featurization._model_dir
|
|
407
|
+
multi_datasets = get_multi_datasets(cfg)
|
|
408
|
+
for dataset in multi_datasets:
|
|
409
|
+
updated_cfg, should_restart = update_cfg_for_multi_dataset(cfg, dataset)
|
|
410
|
+
updated_cfg.featurization._model_dir = trained_model_dir
|
|
411
|
+
|
|
412
|
+
if should_restart["feat_inference"]:
|
|
413
|
+
main_from_config(updated_cfg)
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
from pidsmaker.featurization.featurization_methods import (
|
|
2
|
+
build_trw,
|
|
3
|
+
featurization_fasttext,
|
|
4
|
+
featurization_alacarte,
|
|
5
|
+
featurization_doc2vec,
|
|
6
|
+
featurization_flash,
|
|
7
|
+
featurization_graph2vec,
|
|
8
|
+
featurization_trw,
|
|
9
|
+
featurization_word2vec,
|
|
10
|
+
)
|
|
11
|
+
from pidsmaker.featurization.utils import build_random_walks
|
|
12
|
+
from pidsmaker.utils.utils import set_seed
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def main(cfg):
|
|
16
|
+
set_seed(cfg, seed=cfg.featurization.seed)
|
|
17
|
+
|
|
18
|
+
method = cfg.featurization.used_method.strip()
|
|
19
|
+
if method == "alacarte":
|
|
20
|
+
build_random_walks.main(cfg)
|
|
21
|
+
featurization_alacarte.main(cfg)
|
|
22
|
+
elif method == "doc2vec":
|
|
23
|
+
featurization_doc2vec.main(cfg)
|
|
24
|
+
elif method == "graph2vec":
|
|
25
|
+
featurization_graph2vec.main(cfg)
|
|
26
|
+
elif method in ["hierarchical_hashing", "only_type", "magic", "only_ones", "ocrapt_features"]:
|
|
27
|
+
# these methods don't need to build or train any model
|
|
28
|
+
# so we do nothing here and generate vectorized graphs directly in feat_inference.py
|
|
29
|
+
pass
|
|
30
|
+
elif method == "word2vec":
|
|
31
|
+
featurization_word2vec.main(cfg)
|
|
32
|
+
elif method == "temporal_rw":
|
|
33
|
+
build_trw.main(cfg)
|
|
34
|
+
featurization_trw.main(cfg)
|
|
35
|
+
elif method == "flash":
|
|
36
|
+
featurization_flash.main(cfg)
|
|
37
|
+
elif method == "fasttext":
|
|
38
|
+
featurization_fasttext.main(cfg)
|
|
39
|
+
elif method == "pretrained":
|
|
40
|
+
from pidsmaker.pretrained import pretrain
|
|
41
|
+
pretrain.main(cfg)
|
|
42
|
+
else:
|
|
43
|
+
raise ValueError(f"Invalid node embedding method {method}")
|