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,20 @@
|
|
|
1
|
+
"""SPIDER model architectures."""
|
|
2
|
+
|
|
3
|
+
from .bert import (
|
|
4
|
+
ProvenanceBERT, ProvenanceBERTFineTuneCLS, ProvenanceBERTFineTuneLP,
|
|
5
|
+
FineTuneCLS, FineTuneLP,
|
|
6
|
+
get_bert_config, compute_cls_loss, MODEL_SIZES,
|
|
7
|
+
)
|
|
8
|
+
from .roberta import ProvenanceRoBERTa, ProvenanceRoBERTaFineTuneCLS, ProvenanceRoBERTaFineTuneLP, get_roberta_config
|
|
9
|
+
from .modernbert import ProvenanceModernBERT, ProvenanceModernBERTFineTuneCLS, ProvenanceModernBERTFineTuneLP, get_modernbert_config
|
|
10
|
+
from .ropebert import ProvenanceRoPEBERT, ProvenanceRoPEBERTFineTuneCLS, ProvenanceRoPEBERTFineTuneLP, get_ropebert_config
|
|
11
|
+
from .llama import ProvenanceLLaMA, get_llama_config
|
|
12
|
+
from .behavior import ProvenanceBehaviorModel, get_behavior_encoder_config, behavior_combined_loss
|
|
13
|
+
from .gnn_distill import ProvenanceGNNDistill, NeighborhoodGNNTeacher, get_gnn_distill_encoder_config, build_gnn_distill_batch, build_edge_type_encoder
|
|
14
|
+
from .spider import ProvenanceGNNCluster, GNNClusterTeacher, get_spider_encoder_config, supervised_contrastive_loss, StudentSignatureHead, StudentClassHead, TeacherClassHead
|
|
15
|
+
from .graphmae import GraphMAE, sce_loss, T5NodeEncoder, neighborhoods_to_pyg_batch, save_graphmae, load_graphmae
|
|
16
|
+
from .gae import GAE, save_gae, load_gae
|
|
17
|
+
from .dgi import DGI, save_dgi, load_dgi
|
|
18
|
+
from .tgn import ProvenanceTGN, EdgeTypeClassifier
|
|
19
|
+
from .deepwalk import walks_to_label_sentences, train_deepwalk, save_deepwalk, load_deepwalk, deepwalk_embeddings
|
|
20
|
+
from .hf_pretrained import HF_MODEL_TYPES, get_hf_model_name, get_hf_hidden_size, pretokenize_walks_hf
|
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Behavioral Embedding model for provenance graph entities.
|
|
3
|
+
|
|
4
|
+
Architecture:
|
|
5
|
+
┌────────────────┐
|
|
6
|
+
Entity text ─────────→ │ T5 Encoder │──→ embedding (emb_dim)
|
|
7
|
+
└────────────────┘
|
|
8
|
+
│
|
|
9
|
+
┌──────────┴──────────┐
|
|
10
|
+
↓ ↓
|
|
11
|
+
┌─────────────┐ ┌──────────────┐
|
|
12
|
+
│ Multi-Label │ │ Contrastive │
|
|
13
|
+
│ Classifier │ │ Head │
|
|
14
|
+
└─────────────┘ └──────────────┘
|
|
15
|
+
|
|
16
|
+
Training objective:
|
|
17
|
+
Loss = λ₁ × BCE_loss + λ₂ × contrastive_loss
|
|
18
|
+
|
|
19
|
+
Task 1 (bce_mode="multilabel"): Multi-label BCE — predict the behavior
|
|
20
|
+
signature binary vector.
|
|
21
|
+
Task 1 (bce_mode="class"): Cross-entropy — predict the signature class ID
|
|
22
|
+
directly (one-of-N classification over unique signatures).
|
|
23
|
+
Task 2: Contrastive — pull entities with similar Jaccard signatures close,
|
|
24
|
+
push dissimilar ones apart (NT-Xent / InfoNCE).
|
|
25
|
+
|
|
26
|
+
At inference, only the T5 encoder is used.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from collections import namedtuple
|
|
30
|
+
|
|
31
|
+
import torch
|
|
32
|
+
import torch.nn as nn
|
|
33
|
+
import torch.nn.functional as F
|
|
34
|
+
from transformers import T5Config, T5EncoderModel
|
|
35
|
+
|
|
36
|
+
from .bert import MODEL_SIZES
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
# ── T5 Config ────────────────────────────────────────────────────────────
|
|
40
|
+
|
|
41
|
+
def get_behavior_encoder_config(
|
|
42
|
+
vocab_size: int,
|
|
43
|
+
model_size: str = "mini",
|
|
44
|
+
max_length: int = 512,
|
|
45
|
+
) -> T5Config:
|
|
46
|
+
"""Create T5Config for encoder-only behavior embedding model."""
|
|
47
|
+
params = MODEL_SIZES[model_size]
|
|
48
|
+
return T5Config(
|
|
49
|
+
vocab_size=vocab_size,
|
|
50
|
+
d_model=params.H,
|
|
51
|
+
d_ff=params.I,
|
|
52
|
+
num_heads=params.A,
|
|
53
|
+
num_layers=params.L,
|
|
54
|
+
num_decoder_layers=0,
|
|
55
|
+
relative_attention_num_buckets=32,
|
|
56
|
+
relative_attention_max_distance=128,
|
|
57
|
+
is_encoder_decoder=False,
|
|
58
|
+
use_cache=False,
|
|
59
|
+
pad_token_id=0,
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
# ── Multi-Label Classifier Head ──────────────────────────────────────────
|
|
64
|
+
|
|
65
|
+
class MultiLabelHead(nn.Module):
|
|
66
|
+
"""Linear head: embedding → sigmoid over N behavior labels."""
|
|
67
|
+
|
|
68
|
+
def __init__(self, emb_dim: int, num_labels: int):
|
|
69
|
+
super().__init__()
|
|
70
|
+
self.classifier = nn.Sequential(
|
|
71
|
+
nn.Linear(emb_dim, emb_dim),
|
|
72
|
+
nn.GELU(),
|
|
73
|
+
nn.Dropout(0.1),
|
|
74
|
+
nn.Linear(emb_dim, num_labels),
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
def forward(self, embeddings: torch.Tensor) -> torch.Tensor:
|
|
78
|
+
"""Returns logits [B, num_labels] (pre-sigmoid)."""
|
|
79
|
+
return self.classifier(embeddings)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
# ── Classification Head (cross-entropy over signature classes) ────────
|
|
83
|
+
|
|
84
|
+
class ClassificationHead(nn.Module):
|
|
85
|
+
"""Linear head: embedding → logits over N signature classes."""
|
|
86
|
+
|
|
87
|
+
def __init__(self, emb_dim: int, num_classes: int):
|
|
88
|
+
super().__init__()
|
|
89
|
+
self.classifier = nn.Sequential(
|
|
90
|
+
nn.Linear(emb_dim, emb_dim),
|
|
91
|
+
nn.GELU(),
|
|
92
|
+
nn.Dropout(0.1),
|
|
93
|
+
nn.Linear(emb_dim, num_classes),
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
def forward(self, embeddings: torch.Tensor) -> torch.Tensor:
|
|
97
|
+
"""Returns logits [B, num_classes] (pre-softmax)."""
|
|
98
|
+
return self.classifier(embeddings)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
# ── Contrastive Head (projection to unit sphere) ─────────────────────────
|
|
102
|
+
|
|
103
|
+
class ContrastiveHead(nn.Module):
|
|
104
|
+
"""Projects embeddings to a lower-dim space for contrastive learning."""
|
|
105
|
+
|
|
106
|
+
def __init__(self, emb_dim: int, proj_dim: int = 128):
|
|
107
|
+
super().__init__()
|
|
108
|
+
self.projector = nn.Sequential(
|
|
109
|
+
nn.Linear(emb_dim, emb_dim),
|
|
110
|
+
nn.GELU(),
|
|
111
|
+
nn.Linear(emb_dim, proj_dim),
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
def forward(self, embeddings: torch.Tensor) -> torch.Tensor:
|
|
115
|
+
"""Returns L2-normalized projections [B, proj_dim]."""
|
|
116
|
+
return F.normalize(self.projector(embeddings), p=2, dim=-1)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
# ── Main Model ───────────────────────────────────────────────────────────
|
|
120
|
+
|
|
121
|
+
class ProvenanceBehaviorModel(nn.Module):
|
|
122
|
+
"""T5 encoder + multi-label classifier + contrastive head.
|
|
123
|
+
|
|
124
|
+
At inference, only the T5 encoder is needed — call with skip_cls=True
|
|
125
|
+
to get mean-pooled embeddings.
|
|
126
|
+
"""
|
|
127
|
+
|
|
128
|
+
def __init__(self, config: T5Config, num_labels: int, proj_dim: int = 128,
|
|
129
|
+
bce_mode: str = "multilabel", num_classes: int = 0):
|
|
130
|
+
super().__init__()
|
|
131
|
+
self.config = config
|
|
132
|
+
self.encoder = T5EncoderModel(config)
|
|
133
|
+
self.num_labels = num_labels
|
|
134
|
+
self.emb_dim = config.d_model
|
|
135
|
+
self.bce_mode = bce_mode
|
|
136
|
+
|
|
137
|
+
# Training heads
|
|
138
|
+
if bce_mode == "class":
|
|
139
|
+
assert num_classes > 0, "num_classes required for bce_mode='class'"
|
|
140
|
+
self.classification_head = ClassificationHead(config.d_model, num_classes)
|
|
141
|
+
self.multilabel_head = None
|
|
142
|
+
else:
|
|
143
|
+
self.multilabel_head = MultiLabelHead(config.d_model, num_labels)
|
|
144
|
+
self.classification_head = None
|
|
145
|
+
self.contrastive_head = ContrastiveHead(config.d_model, proj_dim)
|
|
146
|
+
|
|
147
|
+
@property
|
|
148
|
+
def device(self):
|
|
149
|
+
return next(self.parameters()).device
|
|
150
|
+
|
|
151
|
+
def _mean_pool(
|
|
152
|
+
self,
|
|
153
|
+
hidden_states: torch.Tensor,
|
|
154
|
+
attention_mask: torch.Tensor,
|
|
155
|
+
) -> torch.Tensor:
|
|
156
|
+
"""Mean-pool encoder output over non-padding tokens."""
|
|
157
|
+
mask_exp = attention_mask.unsqueeze(-1).float()
|
|
158
|
+
return (hidden_states * mask_exp).sum(dim=1) / mask_exp.sum(dim=1).clamp(min=1)
|
|
159
|
+
|
|
160
|
+
def modified_fwd(
|
|
161
|
+
self,
|
|
162
|
+
input_ids: torch.Tensor,
|
|
163
|
+
attention_mask: torch.Tensor,
|
|
164
|
+
labels: torch.Tensor = None,
|
|
165
|
+
return_loss: bool = True,
|
|
166
|
+
skip_cls: bool = False,
|
|
167
|
+
):
|
|
168
|
+
"""Unified forward interface.
|
|
169
|
+
|
|
170
|
+
skip_cls=True: return raw encoder hidden states [B, L, H]
|
|
171
|
+
(for embedding extraction at inference).
|
|
172
|
+
skip_cls=False: return (embedding, multilabel_logits, contrastive_proj).
|
|
173
|
+
"""
|
|
174
|
+
input_ids = input_ids.to(self.device)
|
|
175
|
+
attention_mask = attention_mask.to(self.device)
|
|
176
|
+
|
|
177
|
+
enc_out = self.encoder(
|
|
178
|
+
input_ids=input_ids,
|
|
179
|
+
attention_mask=attention_mask,
|
|
180
|
+
)
|
|
181
|
+
hidden_states = enc_out.last_hidden_state # [B, L, H]
|
|
182
|
+
|
|
183
|
+
if skip_cls:
|
|
184
|
+
return hidden_states
|
|
185
|
+
|
|
186
|
+
# Mean-pool
|
|
187
|
+
embedding = self._mean_pool(hidden_states, attention_mask) # [B, H]
|
|
188
|
+
|
|
189
|
+
# Classification logits (multi-label or class)
|
|
190
|
+
if self.bce_mode == "class":
|
|
191
|
+
logits = self.classification_head(embedding) # [B, num_classes]
|
|
192
|
+
else:
|
|
193
|
+
logits = self.multilabel_head(embedding) # [B, num_labels]
|
|
194
|
+
|
|
195
|
+
# Contrastive projection
|
|
196
|
+
proj = self.contrastive_head(embedding) # [B, proj_dim]
|
|
197
|
+
|
|
198
|
+
Output = namedtuple("Output", ["embedding", "logits", "projection"])
|
|
199
|
+
return Output(embedding=embedding, logits=logits, projection=proj)
|
|
200
|
+
|
|
201
|
+
@torch.no_grad()
|
|
202
|
+
def encode(
|
|
203
|
+
self,
|
|
204
|
+
input_ids: torch.Tensor,
|
|
205
|
+
attention_mask: torch.Tensor,
|
|
206
|
+
) -> torch.Tensor:
|
|
207
|
+
"""Inference: mean-pooled encoder embeddings (no training heads)."""
|
|
208
|
+
input_ids = input_ids.to(self.device)
|
|
209
|
+
attention_mask = attention_mask.to(self.device)
|
|
210
|
+
enc_out = self.encoder(input_ids=input_ids, attention_mask=attention_mask)
|
|
211
|
+
return self._mean_pool(enc_out.last_hidden_state, attention_mask)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
# ═══════════════════════════════════════════════════════════════════════════
|
|
215
|
+
# LOSS FUNCTIONS
|
|
216
|
+
# ═══════════════════════════════════════════════════════════════════════════
|
|
217
|
+
|
|
218
|
+
def behavior_bce_loss(
|
|
219
|
+
logits: torch.Tensor,
|
|
220
|
+
targets: torch.Tensor,
|
|
221
|
+
) -> torch.Tensor:
|
|
222
|
+
"""Binary cross-entropy loss for multi-label behavior prediction.
|
|
223
|
+
|
|
224
|
+
Args:
|
|
225
|
+
logits: [B, N] raw logits from multi-label head.
|
|
226
|
+
targets: [B, N] binary target vectors.
|
|
227
|
+
|
|
228
|
+
Returns:
|
|
229
|
+
Scalar BCE loss.
|
|
230
|
+
"""
|
|
231
|
+
return F.binary_cross_entropy_with_logits(logits, targets)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def behavior_ce_loss(
|
|
235
|
+
logits: torch.Tensor,
|
|
236
|
+
class_labels: torch.Tensor,
|
|
237
|
+
) -> torch.Tensor:
|
|
238
|
+
"""Cross-entropy loss for direct signature class prediction.
|
|
239
|
+
|
|
240
|
+
Args:
|
|
241
|
+
logits: [B, num_classes] raw logits from classification head.
|
|
242
|
+
class_labels: [B] integer class IDs.
|
|
243
|
+
|
|
244
|
+
Returns:
|
|
245
|
+
Scalar cross-entropy loss.
|
|
246
|
+
"""
|
|
247
|
+
return F.cross_entropy(logits, class_labels)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def behavior_contrastive_loss(
|
|
251
|
+
projections: torch.Tensor,
|
|
252
|
+
class_labels: torch.Tensor,
|
|
253
|
+
temperature: float = 0.07,
|
|
254
|
+
) -> torch.Tensor:
|
|
255
|
+
"""Supervised contrastive loss (SupCon) using class identity.
|
|
256
|
+
|
|
257
|
+
Positives = entities sharing the same behavioral class (identical
|
|
258
|
+
signature). Negatives = entities from different classes.
|
|
259
|
+
|
|
260
|
+
Args:
|
|
261
|
+
projections: [B, D] L2-normalized embeddings from contrastive head.
|
|
262
|
+
class_labels: [B] integer class IDs (same ID = same behavioral class).
|
|
263
|
+
temperature: temperature for cosine similarity scaling.
|
|
264
|
+
|
|
265
|
+
Returns:
|
|
266
|
+
Scalar contrastive loss.
|
|
267
|
+
"""
|
|
268
|
+
B = projections.size(0)
|
|
269
|
+
if B <= 1:
|
|
270
|
+
return torch.tensor(0.0, device=projections.device)
|
|
271
|
+
|
|
272
|
+
# Cosine similarity matrix (already L2-normalized)
|
|
273
|
+
cos_sim = torch.mm(projections, projections.t()) / temperature # [B, B]
|
|
274
|
+
|
|
275
|
+
# Mask out self-similarities
|
|
276
|
+
mask_self = torch.eye(B, dtype=torch.bool, device=projections.device)
|
|
277
|
+
|
|
278
|
+
# Positive mask: same class, excluding self
|
|
279
|
+
positive_mask = (class_labels.unsqueeze(0) == class_labels.unsqueeze(1)) & ~mask_self
|
|
280
|
+
|
|
281
|
+
# If no positives exist in this batch, skip
|
|
282
|
+
if not positive_mask.any():
|
|
283
|
+
return torch.tensor(0.0, device=projections.device)
|
|
284
|
+
|
|
285
|
+
# Log-sum-exp over all non-self pairs (denominator)
|
|
286
|
+
cos_sim_masked = cos_sim.masked_fill(mask_self, float("-inf"))
|
|
287
|
+
log_denom = torch.logsumexp(cos_sim_masked, dim=1) # [B]
|
|
288
|
+
|
|
289
|
+
# For each anchor with positives: mean of log(exp(sim_pos) / denom)
|
|
290
|
+
# = mean of (sim_pos - log_denom) over positive pairs
|
|
291
|
+
has_positives = positive_mask.any(dim=1)
|
|
292
|
+
if not has_positives.any():
|
|
293
|
+
return torch.tensor(0.0, device=projections.device)
|
|
294
|
+
|
|
295
|
+
# Per-anchor: mean log-prob over its positives
|
|
296
|
+
# Mask out non-positives with -inf before computing mean
|
|
297
|
+
pos_sim = cos_sim_masked.masked_fill(~positive_mask, float("-inf"))
|
|
298
|
+
# For each anchor, compute mean over its positive pairs
|
|
299
|
+
n_positives = positive_mask.float().sum(dim=1).clamp(min=1) # [B]
|
|
300
|
+
# sum of (sim_pos_j - log_denom) for each positive j
|
|
301
|
+
loss_per_anchor = -(pos_sim.masked_fill(~positive_mask, 0.0).sum(dim=1) / n_positives - log_denom)
|
|
302
|
+
|
|
303
|
+
return loss_per_anchor[has_positives].mean()
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def behavior_combined_loss(
|
|
307
|
+
logits: torch.Tensor,
|
|
308
|
+
targets: torch.Tensor,
|
|
309
|
+
projections: torch.Tensor,
|
|
310
|
+
class_labels: torch.Tensor,
|
|
311
|
+
bce_weight: float = 1.0,
|
|
312
|
+
contrastive_weight: float = 0.5,
|
|
313
|
+
temperature: float = 0.07,
|
|
314
|
+
bce_mode: str = "multilabel",
|
|
315
|
+
entity_class_labels: torch.Tensor = None,
|
|
316
|
+
contrastive_target: str = "signature",
|
|
317
|
+
) -> tuple:
|
|
318
|
+
"""Combined BCE/CE + contrastive loss.
|
|
319
|
+
|
|
320
|
+
Args:
|
|
321
|
+
bce_mode: "multilabel" for BCE over binary vectors,
|
|
322
|
+
"class" for cross-entropy over entity class IDs.
|
|
323
|
+
entity_class_labels: [B] integer entity class IDs (coarse
|
|
324
|
+
functional classes, ~70).
|
|
325
|
+
contrastive_target: "signature" uses fine-grained signature class IDs
|
|
326
|
+
for contrastive positives; "entity_class" uses
|
|
327
|
+
coarse entity class IDs instead, clustering
|
|
328
|
+
entities by functional class.
|
|
329
|
+
|
|
330
|
+
Returns:
|
|
331
|
+
(total_loss, bce_loss_val, contrastive_loss_val)
|
|
332
|
+
"""
|
|
333
|
+
if bce_mode == "class":
|
|
334
|
+
bce = behavior_ce_loss(logits, entity_class_labels)
|
|
335
|
+
else:
|
|
336
|
+
bce = behavior_bce_loss(logits, targets)
|
|
337
|
+
|
|
338
|
+
if contrastive_target == "entity_class":
|
|
339
|
+
con_labels = entity_class_labels
|
|
340
|
+
else:
|
|
341
|
+
con_labels = class_labels
|
|
342
|
+
|
|
343
|
+
contrastive = behavior_contrastive_loss(
|
|
344
|
+
projections, con_labels,
|
|
345
|
+
temperature=temperature,
|
|
346
|
+
)
|
|
347
|
+
total = bce_weight * bce + contrastive_weight * contrastive
|
|
348
|
+
return total, bce, contrastive
|
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
"""
|
|
2
|
+
BERT models for provenance graph pretraining and fine-tuning.
|
|
3
|
+
|
|
4
|
+
Follows CyberGFM's architecture: HuggingFace BertForMaskedLM for pretraining,
|
|
5
|
+
with CLS and LP fine-tuning heads for anomaly detection.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from types import SimpleNamespace
|
|
9
|
+
from typing import Optional, Tuple, Union
|
|
10
|
+
|
|
11
|
+
import torch
|
|
12
|
+
import torch.nn.functional as F
|
|
13
|
+
from torch import nn
|
|
14
|
+
from torch.nn import CrossEntropyLoss
|
|
15
|
+
from transformers import BertConfig
|
|
16
|
+
from transformers.models.bert.modeling_bert import (
|
|
17
|
+
BertModel,
|
|
18
|
+
BertOnlyMLMHead,
|
|
19
|
+
BertPreTrainedModel,
|
|
20
|
+
)
|
|
21
|
+
from transformers.modeling_outputs import MaskedLMOutput
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
# Model size presets (matching CyberGFM)
|
|
25
|
+
MODEL_SIZES = {
|
|
26
|
+
"tiny": SimpleNamespace(H=128, L=2, A=2, I=512),
|
|
27
|
+
"mini": SimpleNamespace(H=256, L=4, A=4, I=1024),
|
|
28
|
+
"med": SimpleNamespace(H=512, L=8, A=8, I=2048),
|
|
29
|
+
"baseline": SimpleNamespace(H=768, L=12, A=12, I=3072),
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def get_bert_config(vocab_size: int, model_size: str = "tiny", max_position_embeddings: int = 512) -> BertConfig:
|
|
34
|
+
"""Create BertConfig for a given model size."""
|
|
35
|
+
params = MODEL_SIZES[model_size]
|
|
36
|
+
return BertConfig(
|
|
37
|
+
vocab_size=vocab_size,
|
|
38
|
+
hidden_size=params.H,
|
|
39
|
+
num_hidden_layers=params.L,
|
|
40
|
+
num_attention_heads=params.A,
|
|
41
|
+
intermediate_size=params.I,
|
|
42
|
+
max_position_embeddings=max_position_embeddings,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class ProvenanceBERT(BertPreTrainedModel):
|
|
47
|
+
"""BERT for masked language modeling on provenance graph walks.
|
|
48
|
+
|
|
49
|
+
Directly follows CyberGFM's GraphBertForMaskedLM pattern:
|
|
50
|
+
BertModel (encoder) + BertOnlyMLMHead (prediction head).
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
_tied_weights_keys = ["predictions.decoder.bias", "cls.predictions.decoder.weight"]
|
|
54
|
+
|
|
55
|
+
def __init__(self, config: BertConfig):
|
|
56
|
+
super().__init__(config)
|
|
57
|
+
self.bert = BertModel(config, add_pooling_layer=False)
|
|
58
|
+
self.cls = BertOnlyMLMHead(config)
|
|
59
|
+
self.post_init()
|
|
60
|
+
|
|
61
|
+
def get_output_embeddings(self):
|
|
62
|
+
return self.cls.predictions.decoder
|
|
63
|
+
|
|
64
|
+
def set_output_embeddings(self, new_embeddings):
|
|
65
|
+
self.cls.predictions.decoder = new_embeddings
|
|
66
|
+
|
|
67
|
+
def modified_fwd(
|
|
68
|
+
self,
|
|
69
|
+
input_ids: torch.Tensor,
|
|
70
|
+
attention_mask: torch.Tensor,
|
|
71
|
+
labels: torch.Tensor,
|
|
72
|
+
return_loss: bool = True,
|
|
73
|
+
skip_cls: bool = False,
|
|
74
|
+
):
|
|
75
|
+
"""Convenience wrapper matching CyberGFM's modified_fwd interface.
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
input_ids: [B, L] token IDs (with [MASK] applied)
|
|
79
|
+
attention_mask: [B, L] bool, True for real tokens
|
|
80
|
+
labels: [B, L] target token IDs, -100 for non-predicted positions
|
|
81
|
+
return_loss: if True, return scalar loss; else return full output
|
|
82
|
+
skip_cls: if True, return hidden states instead of prediction logits
|
|
83
|
+
"""
|
|
84
|
+
input_ids = input_ids.to(self.device)
|
|
85
|
+
attention_mask = attention_mask.to(self.device)
|
|
86
|
+
labels = labels.to(self.device)
|
|
87
|
+
|
|
88
|
+
position_ids = torch.arange(
|
|
89
|
+
input_ids.size(1), device=self.device
|
|
90
|
+
).unsqueeze(0).expand(input_ids.size(0), -1)
|
|
91
|
+
|
|
92
|
+
out = self.forward(
|
|
93
|
+
input_ids=input_ids,
|
|
94
|
+
attention_mask=attention_mask,
|
|
95
|
+
labels=labels,
|
|
96
|
+
position_ids=position_ids,
|
|
97
|
+
return_dict=True,
|
|
98
|
+
skip_cls=skip_cls,
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
if skip_cls:
|
|
102
|
+
return out # hidden states [B,L,H]
|
|
103
|
+
if return_loss:
|
|
104
|
+
return out.loss
|
|
105
|
+
return out
|
|
106
|
+
|
|
107
|
+
def forward(
|
|
108
|
+
self,
|
|
109
|
+
input_ids: Optional[torch.Tensor] = None,
|
|
110
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
111
|
+
token_type_ids: Optional[torch.Tensor] = None,
|
|
112
|
+
position_ids: Optional[torch.Tensor] = None,
|
|
113
|
+
head_mask: Optional[torch.Tensor] = None,
|
|
114
|
+
inputs_embeds: Optional[torch.Tensor] = None,
|
|
115
|
+
labels: Optional[torch.Tensor] = None,
|
|
116
|
+
output_attentions: Optional[bool] = None,
|
|
117
|
+
output_hidden_states: Optional[bool] = None,
|
|
118
|
+
return_dict: Optional[bool] = None,
|
|
119
|
+
skip_cls: bool = False,
|
|
120
|
+
) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
|
|
121
|
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
|
122
|
+
|
|
123
|
+
outputs = self.bert(
|
|
124
|
+
input_ids,
|
|
125
|
+
attention_mask=attention_mask,
|
|
126
|
+
token_type_ids=token_type_ids,
|
|
127
|
+
position_ids=position_ids,
|
|
128
|
+
head_mask=head_mask,
|
|
129
|
+
inputs_embeds=inputs_embeds,
|
|
130
|
+
output_attentions=output_attentions,
|
|
131
|
+
output_hidden_states=output_hidden_states,
|
|
132
|
+
return_dict=return_dict,
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
sequence_output = outputs[0]
|
|
136
|
+
if skip_cls:
|
|
137
|
+
return sequence_output
|
|
138
|
+
|
|
139
|
+
prediction_scores = self.cls(sequence_output)
|
|
140
|
+
|
|
141
|
+
masked_lm_loss = None
|
|
142
|
+
if labels is not None:
|
|
143
|
+
loss_fct = CrossEntropyLoss() # -100 index = padding token
|
|
144
|
+
masked_lm_loss = loss_fct(
|
|
145
|
+
prediction_scores.view(-1, self.config.vocab_size),
|
|
146
|
+
labels.view(-1),
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
if not return_dict:
|
|
150
|
+
output = (prediction_scores,) + outputs[2:]
|
|
151
|
+
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
|
|
152
|
+
|
|
153
|
+
return MaskedLMOutput(
|
|
154
|
+
loss=masked_lm_loss,
|
|
155
|
+
logits=prediction_scores,
|
|
156
|
+
hidden_states=outputs.hidden_states,
|
|
157
|
+
attentions=outputs.attentions,
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def compute_cls_loss(pred: torch.Tensor, labels: torch.Tensor, margin: float, device) -> torch.Tensor:
|
|
162
|
+
"""Compute CLS fine-tuning loss (shared by BERT and ModernBERT heads).
|
|
163
|
+
|
|
164
|
+
If margin > 0: margin ranking loss — anomalous logit must exceed the normal
|
|
165
|
+
logit by at least `margin`. Produces an unbounded score range at inference.
|
|
166
|
+
If margin <= 0: standard BCE with logits loss.
|
|
167
|
+
|
|
168
|
+
Args:
|
|
169
|
+
pred: [B, 1] anomaly logits from the classifier head
|
|
170
|
+
labels: [B, 1] float, 1 for anomalous, 0 for normal
|
|
171
|
+
margin: ranking margin threshold (use BCE when <= 0)
|
|
172
|
+
device: torch device
|
|
173
|
+
"""
|
|
174
|
+
if margin > 0:
|
|
175
|
+
pred = pred.squeeze(-1) # [B]
|
|
176
|
+
labels_1d = labels.squeeze(-1).to(device) # [B]
|
|
177
|
+
pred_pos = pred[labels_1d == 0] # normal edges: want low score
|
|
178
|
+
pred_neg = pred[labels_1d == 1] # anomalous edges: want high score
|
|
179
|
+
min_len = min(len(pred_pos), len(pred_neg))
|
|
180
|
+
return F.relu(margin - (pred_neg[:min_len] - pred_pos[:min_len])).mean()
|
|
181
|
+
else:
|
|
182
|
+
return nn.BCEWithLogitsLoss()(pred, labels.float().to(device))
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
class FineTuneCLS(nn.Module):
|
|
186
|
+
"""Classification-based fine-tuning for anomaly detection.
|
|
187
|
+
|
|
188
|
+
Backbone-agnostic: wraps any model that exposes `modified_fwd(...)`.
|
|
189
|
+
Appends [CLS] token to walk+edge+dst sequence,
|
|
190
|
+
uses the [CLS] representation for binary classification.
|
|
191
|
+
|
|
192
|
+
Subclass or use directly by passing backbone_cls:
|
|
193
|
+
model = FineTuneCLS(ProvenanceBERT, config, ...)
|
|
194
|
+
"""
|
|
195
|
+
|
|
196
|
+
def __init__(self, backbone_cls, config, pretrained_state_dict=None, device="cpu", freeze_backbone=True, margin=2.0):
|
|
197
|
+
super().__init__()
|
|
198
|
+
self.fm = backbone_cls(config)
|
|
199
|
+
if pretrained_state_dict is not None:
|
|
200
|
+
self.fm.load_state_dict(pretrained_state_dict)
|
|
201
|
+
self.fm = self.fm.to(device)
|
|
202
|
+
|
|
203
|
+
if freeze_backbone:
|
|
204
|
+
for param in self.fm.parameters():
|
|
205
|
+
param.requires_grad = False
|
|
206
|
+
|
|
207
|
+
self.classifier = nn.Sequential(
|
|
208
|
+
nn.Linear(config.hidden_size, config.hidden_size, device=device),
|
|
209
|
+
nn.ReLU(),
|
|
210
|
+
nn.Linear(config.hidden_size, 1, device=device),
|
|
211
|
+
)
|
|
212
|
+
self.device = device
|
|
213
|
+
self.margin = margin
|
|
214
|
+
|
|
215
|
+
def predict(self, input_ids, attention_mask, target_mask):
|
|
216
|
+
"""Get anomaly scores for the [CLS] positions."""
|
|
217
|
+
hidden = self.fm.modified_fwd(
|
|
218
|
+
input_ids, attention_mask,
|
|
219
|
+
labels=torch.full_like(input_ids, -100),
|
|
220
|
+
return_loss=False, skip_cls=True,
|
|
221
|
+
)
|
|
222
|
+
cls_hidden = hidden[target_mask] # [B, H]
|
|
223
|
+
return self.classifier(cls_hidden)
|
|
224
|
+
|
|
225
|
+
def forward(self, input_ids, attention_mask, target_mask, labels):
|
|
226
|
+
pred = self.predict(input_ids, attention_mask, target_mask)
|
|
227
|
+
return compute_cls_loss(pred, labels, self.margin, self.device)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
class FineTuneLP(nn.Module):
|
|
231
|
+
"""Link prediction fine-tuning for anomaly detection.
|
|
232
|
+
|
|
233
|
+
Backbone-agnostic: wraps any model that exposes `modified_fwd(...)`.
|
|
234
|
+
Uses masked destination node prediction. Anomaly score is
|
|
235
|
+
1 - P(true destination | context walk + edge type).
|
|
236
|
+
|
|
237
|
+
Subclass or use directly by passing backbone_cls:
|
|
238
|
+
model = FineTuneLP(ProvenanceBERT, config, ...)
|
|
239
|
+
"""
|
|
240
|
+
|
|
241
|
+
def __init__(self, backbone_cls, config, pretrained_state_dict=None, device="cpu", freeze_backbone=False):
|
|
242
|
+
super().__init__()
|
|
243
|
+
self.fm = backbone_cls(config)
|
|
244
|
+
if pretrained_state_dict is not None:
|
|
245
|
+
self.fm.load_state_dict(pretrained_state_dict)
|
|
246
|
+
self.fm = self.fm.to(device)
|
|
247
|
+
|
|
248
|
+
if freeze_backbone:
|
|
249
|
+
for param in self.fm.parameters():
|
|
250
|
+
param.requires_grad = False
|
|
251
|
+
|
|
252
|
+
self.config = config
|
|
253
|
+
self.device = device
|
|
254
|
+
|
|
255
|
+
def forward(self, input_ids, attention_mask, target_mask, target_token_ids):
|
|
256
|
+
return self.fm.modified_fwd(
|
|
257
|
+
input_ids, attention_mask, labels=target_token_ids, return_loss=True
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
@torch.no_grad()
|
|
261
|
+
def anomaly_score(self, input_ids, attention_mask, target_mask, target_token_ids):
|
|
262
|
+
"""Compute per-edge anomaly scores via mean cross-entropy on masked tokens."""
|
|
263
|
+
out = self.fm.modified_fwd(
|
|
264
|
+
input_ids, attention_mask,
|
|
265
|
+
labels=torch.full_like(input_ids, -100),
|
|
266
|
+
return_loss=False,
|
|
267
|
+
)
|
|
268
|
+
logits = out.logits # [B, L, V]
|
|
269
|
+
B, L, V = logits.shape
|
|
270
|
+
|
|
271
|
+
loss_fct = torch.nn.CrossEntropyLoss(reduction="none", ignore_index=-100)
|
|
272
|
+
per_pos_loss = loss_fct(logits.view(-1, V), target_token_ids.view(-1)).view(B, L)
|
|
273
|
+
|
|
274
|
+
valid = (target_token_ids >= 0) & target_mask
|
|
275
|
+
num_valid = valid.float().sum(dim=1).clamp(min=1)
|
|
276
|
+
scores = (per_pos_loss * valid.float()).sum(dim=1) / num_valid
|
|
277
|
+
|
|
278
|
+
return scores
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
# Backwards-compatible aliases
|
|
282
|
+
def ProvenanceBERTFineTuneCLS(config, pretrained_state_dict=None, device="cpu", freeze_backbone=True, margin=2.0):
|
|
283
|
+
return FineTuneCLS(ProvenanceBERT, config, pretrained_state_dict, device, freeze_backbone, margin)
|
|
284
|
+
|
|
285
|
+
def ProvenanceBERTFineTuneLP(config, pretrained_state_dict=None, device="cpu", freeze_backbone=False):
|
|
286
|
+
return FineTuneLP(ProvenanceBERT, config, pretrained_state_dict, device, freeze_backbone)
|