pidsmaker 5.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pidsmaker/__init__.py +1 -0
- pidsmaker/cli.py +81 -0
- pidsmaker/config/__init__.py +2 -0
- pidsmaker/config/config.py +2100 -0
- pidsmaker/config/pipeline.py +1824 -0
- pidsmaker/config/schemas.py +1032 -0
- pidsmaker/datasets.py +323 -0
- pidsmaker/debug_tests.py +30 -0
- pidsmaker/decoders/__init__.py +5 -0
- pidsmaker/decoders/custom_edge_mlp_decoder.py +17 -0
- pidsmaker/decoders/custom_mlp_decoder.py +10 -0
- pidsmaker/decoders/edge_linear_decoder.py +16 -0
- pidsmaker/decoders/inner_product_decoder.py +18 -0
- pidsmaker/decoders/nodlink_decoder.py +56 -0
- pidsmaker/detection/__init__.py +0 -0
- pidsmaker/detection/evaluation_methods/__init__.py +9 -0
- pidsmaker/detection/evaluation_methods/edge_evaluation.py +255 -0
- pidsmaker/detection/evaluation_methods/evaluation_utils.py +1788 -0
- pidsmaker/detection/evaluation_methods/host_two_stage_evaluation.py +115 -0
- pidsmaker/detection/evaluation_methods/node_evaluation.py +459 -0
- pidsmaker/detection/evaluation_methods/node_tw_evaluation.py +196 -0
- pidsmaker/detection/evaluation_methods/plot.py +192 -0
- pidsmaker/detection/evaluation_methods/queue_evaluation.py +456 -0
- pidsmaker/detection/evaluation_methods/tw_evaluation.py +93 -0
- pidsmaker/detection/flash_detection.py +162 -0
- pidsmaker/detection/magic_knn.py +190 -0
- pidsmaker/detection/node_scoring.py +52 -0
- pidsmaker/detection/threatrace_detection.py +65 -0
- pidsmaker/detection/training_methods/__init__.py +1 -0
- pidsmaker/detection/training_methods/inference_loop.py +287 -0
- pidsmaker/detection/training_methods/ocrapt_early_stop.py +165 -0
- pidsmaker/detection/training_methods/threatrace_training.py +168 -0
- pidsmaker/detection/training_methods/training_loop.py +383 -0
- pidsmaker/encoders/__init__.py +22 -0
- pidsmaker/encoders/argus_encoder.py +69 -0
- pidsmaker/encoders/custom_mlp.py +75 -0
- pidsmaker/encoders/custom_mlp_encoder.py +10 -0
- pidsmaker/encoders/egraphsage_encoder.py +56 -0
- pidsmaker/encoders/gat.py +67 -0
- pidsmaker/encoders/gcn.py +27 -0
- pidsmaker/encoders/gin.py +48 -0
- pidsmaker/encoders/glstm.py +298 -0
- pidsmaker/encoders/graph_attention.py +63 -0
- pidsmaker/encoders/gru.py +29 -0
- pidsmaker/encoders/hetero/__init__.py +4 -0
- pidsmaker/encoders/hetero/ancestor_encoder.py +98 -0
- pidsmaker/encoders/hetero/entity_encoder.py +33 -0
- pidsmaker/encoders/hetero/event_encoder.py +81 -0
- pidsmaker/encoders/hetero/hetero_graph_transformer.py +40 -0
- pidsmaker/encoders/lares_encoder.py +68 -0
- pidsmaker/encoders/linear_encoder.py +16 -0
- pidsmaker/encoders/magic_encoder.py +161 -0
- pidsmaker/encoders/rcaid_encoder.py +81 -0
- pidsmaker/encoders/rgcn.py +75 -0
- pidsmaker/encoders/sage.py +51 -0
- pidsmaker/encoders/shadewatcher_encoder.py +149 -0
- pidsmaker/encoders/sum_aggregation.py +20 -0
- pidsmaker/encoders/temporal_wrappers.py +80 -0
- pidsmaker/encoders/textrcnn.py +82 -0
- pidsmaker/encoders/tgn_encoder.py +193 -0
- pidsmaker/experiments/tuning.py +102 -0
- pidsmaker/experiments/uncertainty.py +261 -0
- pidsmaker/factory.py +1456 -0
- pidsmaker/featurization/__init__.py +0 -0
- pidsmaker/featurization/feat_inference_methods/__init__.py +7 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_HFH.py +30 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_TRW.py +65 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_alacarte.py +14 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_doc2vec.py +53 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_fasttext.py +37 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_flash.py +69 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_graph2vec.py +84 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_ocrapt_features.py +95 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_pretrained.py +1728 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_word2vec.py +55 -0
- pidsmaker/featurization/featurization_methods/__init__.py +0 -0
- pidsmaker/featurization/featurization_methods/build_trw.py +66 -0
- pidsmaker/featurization/featurization_methods/featurization_alacarte.py +747 -0
- pidsmaker/featurization/featurization_methods/featurization_doc2vec.py +98 -0
- pidsmaker/featurization/featurization_methods/featurization_fasttext.py +74 -0
- pidsmaker/featurization/featurization_methods/featurization_flash.py +201 -0
- pidsmaker/featurization/featurization_methods/featurization_graph2vec.py +242 -0
- pidsmaker/featurization/featurization_methods/featurization_trw.py +114 -0
- pidsmaker/featurization/featurization_methods/featurization_word2vec.py +89 -0
- pidsmaker/featurization/featurization_utils.py +275 -0
- pidsmaker/featurization/utils/build_random_walks.py +66 -0
- pidsmaker/featurization/utils/trw.py +203 -0
- pidsmaker/hetero.py +81 -0
- pidsmaker/losses.py +170 -0
- pidsmaker/main.py +478 -0
- pidsmaker/mimicry.py +284 -0
- pidsmaker/model.py +382 -0
- pidsmaker/objectives/__init__.py +16 -0
- pidsmaker/objectives/autoencode_edge_emb.py +43 -0
- pidsmaker/objectives/deep_graph_infomax.py +94 -0
- pidsmaker/objectives/detect_few_shot.py +21 -0
- pidsmaker/objectives/one_class.py +75 -0
- pidsmaker/objectives/predict_edge_contrastive.py +165 -0
- pidsmaker/objectives/predict_edge_supervised.py +77 -0
- pidsmaker/objectives/predict_edge_type.py +28 -0
- pidsmaker/objectives/predict_masked_struct.py +49 -0
- pidsmaker/objectives/predict_node_type.py +36 -0
- pidsmaker/objectives/predict_process_tag.py +169 -0
- pidsmaker/objectives/predict_snapshot_embedding.py +97 -0
- pidsmaker/objectives/reconstruct_edge_emb.py +16 -0
- pidsmaker/objectives/reconstruct_masked_feat.py +51 -0
- pidsmaker/objectives/reconstruct_node_emb.py +13 -0
- pidsmaker/objectives/reconstruct_node_feat.py +13 -0
- pidsmaker/objectives/validation_wrapper.py +55 -0
- pidsmaker/preprocessing/__init__.py +0 -0
- pidsmaker/preprocessing/build_graph_methods/__init__.py +1 -0
- pidsmaker/preprocessing/build_graph_methods/build_default_graphs.py +825 -0
- pidsmaker/preprocessing/build_graph_methods/build_magic_graphs.py +216 -0
- pidsmaker/preprocessing/cleaning.py +258 -0
- pidsmaker/preprocessing/transformation_methods/__init__.py +2 -0
- pidsmaker/preprocessing/transformation_methods/attack_generation/synthetic_attack_naive.py +194 -0
- pidsmaker/preprocessing/transformation_methods/transformation_dag.py +28 -0
- pidsmaker/preprocessing/transformation_methods/transformation_merge_edges.py +136 -0
- pidsmaker/preprocessing/transformation_methods/transformation_rcaid_pseudo_graph.py +510 -0
- pidsmaker/preprocessing/transformation_methods/transformation_undirected.py +24 -0
- pidsmaker/preprocessing/transformation_methods/transformation_utils.py +36 -0
- pidsmaker/pretrained/__init__.py +5 -0
- pidsmaker/pretrained/data/__init__.py +4 -0
- pidsmaker/pretrained/data/behavior_signatures.py +548 -0
- pidsmaker/pretrained/data/canonical_tokens.py +1035 -0
- pidsmaker/pretrained/data/edge_filter.py +381 -0
- pidsmaker/pretrained/data/entity_classes.py +476 -0
- pidsmaker/pretrained/data/sampler.py +926 -0
- pidsmaker/pretrained/data/tokenizer_bpe.py +1659 -0
- pidsmaker/pretrained/detect.py +1427 -0
- pidsmaker/pretrained/embedding_generator.py +252 -0
- pidsmaker/pretrained/finetune.py +1434 -0
- pidsmaker/pretrained/models/__init__.py +20 -0
- pidsmaker/pretrained/models/behavior.py +348 -0
- pidsmaker/pretrained/models/bert.py +286 -0
- pidsmaker/pretrained/models/deepwalk.py +128 -0
- pidsmaker/pretrained/models/dgi.py +120 -0
- pidsmaker/pretrained/models/gae.py +114 -0
- pidsmaker/pretrained/models/gnn_distill.py +475 -0
- pidsmaker/pretrained/models/graphmae.py +373 -0
- pidsmaker/pretrained/models/hf_pretrained.py +213 -0
- pidsmaker/pretrained/models/llama.py +110 -0
- pidsmaker/pretrained/models/modernbert.py +567 -0
- pidsmaker/pretrained/models/roberta.py +147 -0
- pidsmaker/pretrained/models/rope_utils.py +99 -0
- pidsmaker/pretrained/models/ropebert.py +322 -0
- pidsmaker/pretrained/models/spider.py +204 -0
- pidsmaker/pretrained/models/tgn.py +770 -0
- pidsmaker/pretrained/pretrain/__init__.py +3 -0
- pidsmaker/pretrained/pretrain/pretrain_behavior_cluster.py +513 -0
- pidsmaker/pretrained/pretrain/pretrain_common.py +585 -0
- pidsmaker/pretrained/pretrain/pretrain_deepwalk.py +31 -0
- pidsmaker/pretrained/pretrain/pretrain_dgi.py +143 -0
- pidsmaker/pretrained/pretrain/pretrain_gae.py +143 -0
- pidsmaker/pretrained/pretrain/pretrain_gnn_distill.py +438 -0
- pidsmaker/pretrained/pretrain/pretrain_graphmae.py +151 -0
- pidsmaker/pretrained/pretrain/pretrain_hf.py +169 -0
- pidsmaker/pretrained/pretrain/pretrain_main.py +275 -0
- pidsmaker/pretrained/pretrain/pretrain_mlm.py +491 -0
- pidsmaker/pretrained/pretrain/pretrain_spider.py +502 -0
- pidsmaker/pretrained/training_utils.py +157 -0
- pidsmaker/process_reapr_gt.py +101 -0
- pidsmaker/resources/config/anomal_e.yml +25 -0
- pidsmaker/resources/config/argus.yml +56 -0
- pidsmaker/resources/config/attack_edges/cadets_e3.yml +435 -0
- pidsmaker/resources/config/attack_edges/cadets_e5.yml +407 -0
- pidsmaker/resources/config/attack_edges/theia_e3.yml +382 -0
- pidsmaker/resources/config/attack_edges/theia_e5.yml +387 -0
- pidsmaker/resources/config/attack_edges/trace_e3.yml +415 -0
- pidsmaker/resources/config/attack_edges/trace_e5.yml +417 -0
- pidsmaker/resources/config/default.yml +315 -0
- pidsmaker/resources/config/egraphsage.yml +95 -0
- pidsmaker/resources/config/euler.yml +104 -0
- pidsmaker/resources/config/eval/eval_set_clustering.json +3170 -0
- pidsmaker/resources/config/experiments/tuning/components/tuning_featurization_methods.yml +29 -0
- pidsmaker/resources/config/experiments/tuning/systems/clearscope_e5/tuning_orthrus.yml +14 -0
- pidsmaker/resources/config/experiments/tuning/systems/default/tuning_default_baselines.yml +13 -0
- pidsmaker/resources/config/experiments/tuning/systems/default/tuning_orthrus_fixed.yml +16 -0
- pidsmaker/resources/config/experiments/uncertainty/none.yml +5 -0
- pidsmaker/resources/config/experiments/uncertainty/run_n_times.yml +12 -0
- pidsmaker/resources/config/experiments/uncertainty/run_n_times_hyperparameters.yml +12 -0
- pidsmaker/resources/config/experiments/uncertainty/uncertainty.yml +22 -0
- pidsmaker/resources/config/flash.yml +79 -0
- pidsmaker/resources/config/jbeil.yml +65 -0
- pidsmaker/resources/config/kairos.yml +121 -0
- pidsmaker/resources/config/lares.yml +115 -0
- pidsmaker/resources/config/magic.yml +86 -0
- pidsmaker/resources/config/nodlink.yml +79 -0
- pidsmaker/resources/config/ocrapt.yml +91 -0
- pidsmaker/resources/config/orthrus.yml +126 -0
- pidsmaker/resources/config/orthrus_fixed.yml +17 -0
- pidsmaker/resources/config/pretrained/README.md +101 -0
- pidsmaker/resources/config/pretrained/cybergfm/cybergfm.yml +49 -0
- pidsmaker/resources/config/pretrained/pretrained.yml +190 -0
- pidsmaker/resources/config/pretrained/pretrained_flash.yml +9 -0
- pidsmaker/resources/config/pretrained/pretrained_kairos.yml +12 -0
- pidsmaker/resources/config/pretrained/pretrained_magic.yml +1 -0
- pidsmaker/resources/config/pretrained/pretrained_nodlink.yml +1 -0
- pidsmaker/resources/config/pretrained/pretrained_orthrus.yml +1 -0
- pidsmaker/resources/config/pretrained/pretrained_supervised.yml +13 -0
- pidsmaker/resources/config/pretrained/pretrained_threatrace.yml +8 -0
- pidsmaker/resources/config/pretrained/pretrained_velox.yml +14 -0
- pidsmaker/resources/config/prographer.yml +136 -0
- pidsmaker/resources/config/rcaid.yml +88 -0
- pidsmaker/resources/config/shadewatcher.yml +146 -0
- pidsmaker/resources/config/tests.yml +10 -0
- pidsmaker/resources/config/threatrace.yml +73 -0
- pidsmaker/resources/config/tuned_baselines/optc_net/tuned_argus.yml +4 -0
- pidsmaker/resources/config/tuned_baselines/optc_net/tuned_lares.yml +13 -0
- pidsmaker/resources/config/velox.yml +10 -0
- pidsmaker/resources/config/viz_config.yml +10 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_06.csv +8 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_11.csv +4 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_12.csv +43 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_13.csv +24 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0411.csv +41 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0412.csv +0 -0
- pidsmaker/resources/ground_truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_browser_0412.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +63 -0
- pidsmaker/resources/ground_truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +56 -0
- pidsmaker/resources/ground_truth/orthrus/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +61 -0
- pidsmaker/resources/ground_truth/orthrus/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +58 -0
- pidsmaker/resources/ground_truth/orthrus/E3-TRACE/node_trace_e3_firefox_0410.csv +11 -0
- pidsmaker/resources/ground_truth/orthrus/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +11 -0
- pidsmaker/resources/ground_truth/orthrus/E3-TRACE/node_trace_e3_pine_0413.csv +14 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT.csv +19 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT_17.csv +107 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_appstarter_0515.csv +26 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_firefox_0517.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_lockwatch_0517.csv +17 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_tester_0517.csv +8 -0
- pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_bits_0515.csv +54 -0
- pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_copykatz_0509.csv +87 -0
- pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_dns_0517.csv +11 -0
- pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_drakon_0517.csv +6 -0
- pidsmaker/resources/ground_truth/orthrus/E5-THEIA/node_THEIA_1_Firefox_Drakon_APT_BinFmt_Elevate_Inject.csv +70 -0
- pidsmaker/resources/ground_truth/orthrus/E5-TRACE/node_Trace_Firefox_Drakon.csv +71 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m1.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m2.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m3.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m4.csv +5 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m5.csv +23 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m6.csv +18 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s1.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s2.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s3.csv +16 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s4.csv +22 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m1.csv +126 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m2.csv +105 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m3.csv +94 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m4.csv +139 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m5.csv +228 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m6.csv +131 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s1.csv +118 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s2.csv +89 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s3.csv +133 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s4.csv +135 -0
- pidsmaker/resources/ground_truth/orthrus/carbanakv2_edr/carbanakv2_edr.csv +2453 -0
- pidsmaker/resources/ground_truth/orthrus/h051/node_h051_0925.csv +114 -0
- pidsmaker/resources/ground_truth/orthrus/h201/node_h201_0923.csv +2905 -0
- pidsmaker/resources/ground_truth/orthrus/h501/node_h501_0924.csv +749 -0
- pidsmaker/resources/ground_truth/orthrus/readme.md +98 -0
- pidsmaker/resources/ground_truth/reapr/E3-CADETS/node_Nginx_Backdoor_06.csv +3 -0
- pidsmaker/resources/ground_truth/reapr/E3-CADETS/node_Nginx_Backdoor_12.csv +655 -0
- pidsmaker/resources/ground_truth/reapr/E3-CADETS/node_Nginx_Backdoor_13.csv +770 -0
- pidsmaker/resources/ground_truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +0 -0
- pidsmaker/resources/ground_truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +18 -0
- pidsmaker/resources/ground_truth/reapr/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +42 -0
- pidsmaker/resources/ground_truth/reapr/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +81 -0
- pidsmaker/resources/ground_truth/reapr/E3-TRACE/node_trace_e3_firefox_0410.csv +37 -0
- pidsmaker/resources/ground_truth/reapr/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +9 -0
- pidsmaker/resources/ground_truth/reapr/E3-TRACE/node_trace_e3_pine_0413.csv +40 -0
- pidsmaker/resources/ground_truth/threatrace/E3-CADETS/ground_truth.txt +12858 -0
- pidsmaker/resources/ground_truth/threatrace/E3-FIVEDIRECTIONS/ground_truth.txt +18420 -0
- pidsmaker/resources/ground_truth/threatrace/E3-THEIA/ground_truth.txt +25363 -0
- pidsmaker/resources/ground_truth/threatrace/E3-TRACE/ground_truth.txt +68265 -0
- pidsmaker/resources/ground_truth/threatrace/README.md +123 -0
- pidsmaker/tasks/__init__.py +10 -0
- pidsmaker/tasks/batching.py +47 -0
- pidsmaker/tasks/construction.py +31 -0
- pidsmaker/tasks/evaluation.py +241 -0
- pidsmaker/tasks/feat_inference.py +413 -0
- pidsmaker/tasks/featurization.py +43 -0
- pidsmaker/tasks/training.py +17 -0
- pidsmaker/tasks/transformation.py +306 -0
- pidsmaker/tasks/triage.py +143 -0
- pidsmaker/tgn.py +635 -0
- pidsmaker/tokenization/__init__.py +112 -0
- pidsmaker/tokenization/base.py +58 -0
- pidsmaker/tokenization/bpe_tokenizer.py +83 -0
- pidsmaker/tokenization/hf_tokenizer.py +61 -0
- pidsmaker/tokenization/hierarchical_tokenizer.py +44 -0
- pidsmaker/tokenization/label_tokenizer.py +24 -0
- pidsmaker/tokenization/nltk_tokenizer.py +84 -0
- pidsmaker/tokenization/substitution.py +295 -0
- pidsmaker/triage/__init__.py +0 -0
- pidsmaker/triage/tracing_methods/__init__.py +1 -0
- pidsmaker/triage/tracing_methods/depimpact.py +213 -0
- pidsmaker/triage/tracing_methods/depimpact_utils.py +537 -0
- pidsmaker/triage/tracing_methods/ocrapt_subgraph.py +267 -0
- pidsmaker/utils/__init__.py +0 -0
- pidsmaker/utils/cache_utils.py +256 -0
- pidsmaker/utils/console.py +282 -0
- pidsmaker/utils/data_utils.py +1742 -0
- pidsmaker/utils/database.py +150 -0
- pidsmaker/utils/dataset_utils.py +413 -0
- pidsmaker/utils/dataset_writer.py +570 -0
- pidsmaker/utils/graph_store.py +634 -0
- pidsmaker/utils/labelling.py +445 -0
- pidsmaker/utils/loss_files.py +193 -0
- pidsmaker/utils/process_tags.py +44 -0
- pidsmaker/utils/utils.py +712 -0
- pidsmaker/vizgen/__init__.py +1 -0
- pidsmaker/vizgen/backfill_manifests.py +100 -0
- pidsmaker/vizgen/dimensionality_reduction.py +249 -0
- pidsmaker/vizgen/embed_exporter.py +467 -0
- pidsmaker/vizgen/exporter.py +493 -0
- pidsmaker/vizgen/html_builder.py +936 -0
- pidsmaker/vizgen/web/__init__.py +1 -0
- pidsmaker/vizgen/web/export.py +62 -0
- pidsmaker/vizgen/web/static/css/app.css +250 -0
- pidsmaker/vizgen/web/static/index.html +182 -0
- pidsmaker/vizgen/web/static/js/app.js +627 -0
- pidsmaker/vizgen/web/static/js/campaign.js +123 -0
- pidsmaker/vizgen/web/static/js/data.js +119 -0
- pidsmaker/vizgen/web/static/js/dialogs.js +240 -0
- pidsmaker/vizgen/web/static/js/jobs.js +75 -0
- pidsmaker/vizgen/web/static/js/scene.js +651 -0
- pidsmaker/vizgen/web/static/js/ui.js +370 -0
- pidsmaker/vizgen/web/static/vendor/OrbitControls.js +1045 -0
- pidsmaker/vizgen/web/static/vendor/d3.v4.min.js +2 -0
- pidsmaker/vizgen/web/static/vendor/three.min.js +6 -0
- pidsmaker/vizgen/web/viz_server.py +2176 -0
- pidsmaker-5.0.0.dist-info/METADATA +597 -0
- pidsmaker-5.0.0.dist-info/RECORD +339 -0
- pidsmaker-5.0.0.dist-info/WHEEL +5 -0
- pidsmaker-5.0.0.dist-info/entry_points.txt +2 -0
- pidsmaker-5.0.0.dist-info/licenses/LICENSE +201 -0
- pidsmaker-5.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1434 @@
|
|
|
1
|
+
"""
|
|
2
|
+
SPIDER fine-tuning for anomaly detection on provenance graphs.
|
|
3
|
+
|
|
4
|
+
Supports multiple modes:
|
|
5
|
+
- CLS: Binary classification with [CLS] token
|
|
6
|
+
- CLS_ATTACK: Supervised binary classification with real attack walks
|
|
7
|
+
- LP: Link prediction via masked destination node likelihood
|
|
8
|
+
- TGN: Temporal Graph Network with attention-based entity memory (self-supervised)
|
|
9
|
+
|
|
10
|
+
Follows CyberGFM's cls_finetune.py and lp_finetune.py patterns.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import os
|
|
14
|
+
import pickle
|
|
15
|
+
import random
|
|
16
|
+
import time
|
|
17
|
+
from collections import defaultdict
|
|
18
|
+
from typing import List, Tuple
|
|
19
|
+
|
|
20
|
+
import numpy as np
|
|
21
|
+
import torch
|
|
22
|
+
import torch.nn.functional as F
|
|
23
|
+
from torch.optim import AdamW
|
|
24
|
+
from torch_geometric.utils import scatter
|
|
25
|
+
|
|
26
|
+
from .training_utils import (
|
|
27
|
+
WarmupLinearScheduler, WarmupCosineScheduler,
|
|
28
|
+
pad_token_id_lists, pad_tensor_batch,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
from pidsmaker.utils.utils import get_all_graphs_for_dates, get_indexid2msg, log
|
|
32
|
+
from pidsmaker.utils.labelling import get_GP_of_each_attack, get_ground_truth_edges
|
|
33
|
+
from pidsmaker.utils.dataset_utils import get_rel2id, ntype2id
|
|
34
|
+
|
|
35
|
+
from .models.bert import MODEL_SIZES, ProvenanceBERTFineTuneCLS, ProvenanceBERTFineTuneLP, get_bert_config
|
|
36
|
+
from .models.modernbert import ProvenanceModernBERTFineTuneCLS, ProvenanceModernBERTFineTuneLP, get_modernbert_config
|
|
37
|
+
from .models.ropebert import ProvenanceRoPEBERTFineTuneCLS, ProvenanceRoPEBERTFineTuneLP, get_ropebert_config
|
|
38
|
+
from .models.tgn import ProvenanceTGN
|
|
39
|
+
from .data.sampler import ProvenanceWalkSampler
|
|
40
|
+
from .data.tokenizer_bpe import ProvenanceTokenizerBPE as ProvenanceTokenizer
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _collect_edges(graph) -> List[Tuple[str, str, str, float]]:
|
|
44
|
+
"""Collect all edges as (src, dst, edge_type, time) from a NetworkX graph."""
|
|
45
|
+
edges = []
|
|
46
|
+
for src, dst, _, attrs in graph.edges(data=True, keys=True):
|
|
47
|
+
edges.append((
|
|
48
|
+
str(src), str(dst),
|
|
49
|
+
attrs.get("label", ""),
|
|
50
|
+
attrs.get("time", 0.0),
|
|
51
|
+
))
|
|
52
|
+
return edges
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _build_neg_index(indexid2msg: dict) -> dict:
|
|
56
|
+
"""Build node_type -> list of (label, node_id) pairs for negative sampling.
|
|
57
|
+
|
|
58
|
+
Grouping by (type, label) lets us efficiently exclude candidates whose
|
|
59
|
+
textual representation is identical to the positive destination.
|
|
60
|
+
"""
|
|
61
|
+
type_to_labeled: dict = defaultdict(list)
|
|
62
|
+
for node_id, (node_type, node_label) in indexid2msg.items():
|
|
63
|
+
type_to_labeled[node_type].append((node_label, str(node_id)))
|
|
64
|
+
return type_to_labeled
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _precompute_negatives(
|
|
68
|
+
edges: List[Tuple],
|
|
69
|
+
indexid2msg: dict,
|
|
70
|
+
type_to_labeled: dict,
|
|
71
|
+
real_edge_set: set,
|
|
72
|
+
max_tries: int = 20,
|
|
73
|
+
) -> dict:
|
|
74
|
+
"""Pre-compute one negative dst per unique (src, dst, etype) triple.
|
|
75
|
+
|
|
76
|
+
Each negative satisfies:
|
|
77
|
+
- Same node type as dst, but a *different* textual label (distinct tokens).
|
|
78
|
+
- (src, neg_dst, etype) does not exist in real_edge_set.
|
|
79
|
+
|
|
80
|
+
Returns a dict mapping (src, dst, etype) -> neg_dst string.
|
|
81
|
+
|
|
82
|
+
Speed: builds two O(V) lookup tables once, then uses rejection sampling
|
|
83
|
+
(random.choices, O(max_tries)) per triple — avoids the O(|type|) list
|
|
84
|
+
comprehension + shuffle that the naive approach does per unique key.
|
|
85
|
+
"""
|
|
86
|
+
all_node_ids = [str(n) for n in indexid2msg]
|
|
87
|
+
|
|
88
|
+
# type_to_all[node_type] -> flat list of all node_ids of that type
|
|
89
|
+
type_to_all: dict = {t: [n for _, n in nodes] for t, nodes in type_to_labeled.items()}
|
|
90
|
+
# same_label[(node_type, label)] -> set of node_ids sharing that label
|
|
91
|
+
# Used for O(1) exclusion instead of per-triple list filtering
|
|
92
|
+
same_label: dict = defaultdict(set)
|
|
93
|
+
for node_type, labeled_nodes in type_to_labeled.items():
|
|
94
|
+
for label, node_id in labeled_nodes:
|
|
95
|
+
same_label[(node_type, label)].add(node_id)
|
|
96
|
+
|
|
97
|
+
# Deduplicate keys upfront to skip repeated computation
|
|
98
|
+
unique_keys = dict.fromkeys(
|
|
99
|
+
(str(e[0]), str(e[1]), str(e[2])) for e in edges
|
|
100
|
+
)
|
|
101
|
+
neg_map: dict = {}
|
|
102
|
+
for src, dst, etype in unique_keys:
|
|
103
|
+
dst_info = indexid2msg.get(dst)
|
|
104
|
+
neg_dst = None
|
|
105
|
+
if dst_info:
|
|
106
|
+
dst_type, dst_label = dst_info
|
|
107
|
+
pool = type_to_all.get(dst_type, [])
|
|
108
|
+
excl = same_label.get((dst_type, dst_label), set())
|
|
109
|
+
if pool:
|
|
110
|
+
# Rejection sampling: O(max_tries), no large list construction
|
|
111
|
+
for c in random.choices(pool, k=min(max_tries, len(pool))):
|
|
112
|
+
if c not in excl and (src, c, etype) not in real_edge_set:
|
|
113
|
+
neg_dst = c
|
|
114
|
+
break
|
|
115
|
+
if neg_dst is None:
|
|
116
|
+
# Relax real-edge constraint, keep different-label guarantee
|
|
117
|
+
for c in random.choices(pool, k=min(max_tries, len(pool))):
|
|
118
|
+
if c not in excl:
|
|
119
|
+
neg_dst = c
|
|
120
|
+
break
|
|
121
|
+
if neg_dst is None:
|
|
122
|
+
neg_dst = random.choice(all_node_ids)
|
|
123
|
+
neg_map[(src, dst, etype)] = neg_dst
|
|
124
|
+
return neg_map
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
# ── Attack walk extraction (for cls_attack mode) ──────────────────────────────
|
|
128
|
+
|
|
129
|
+
def _extract_attack_walks(
|
|
130
|
+
cfg,
|
|
131
|
+
walk_length: int,
|
|
132
|
+
time_weight: str,
|
|
133
|
+
half_life: float,
|
|
134
|
+
num_walks: int,
|
|
135
|
+
) -> List[Tuple[List[str], List[str], str, str]]:
|
|
136
|
+
"""Extract backward context walks that terminate at malicious attack nodes
|
|
137
|
+
strictly within the attack time window for each node.
|
|
138
|
+
|
|
139
|
+
Uses get_GP_of_each_attack to obtain per-attack (node IDs, time_range) so
|
|
140
|
+
that only edges whose timestamp falls inside the known attack period are
|
|
141
|
+
considered. This prevents sampling walks from before or after the attack,
|
|
142
|
+
which would not carry attack-specific provenance patterns.
|
|
143
|
+
|
|
144
|
+
Returns:
|
|
145
|
+
List of (walk_nodes, walk_edge_types, dst_node_id, edge_type) tuples.
|
|
146
|
+
These are used as the positive (anomalous, label=1) class in cls_attack.
|
|
147
|
+
"""
|
|
148
|
+
attack_to_nids = get_GP_of_each_attack(cfg)
|
|
149
|
+
|
|
150
|
+
# Build: mal_node_str -> list of (start_ns, end_ns) attack windows
|
|
151
|
+
mal_node_to_windows: dict = defaultdict(list)
|
|
152
|
+
for attack_info in attack_to_nids.values():
|
|
153
|
+
start_ns, end_ns = attack_info["time_range"]
|
|
154
|
+
for nid in attack_info["nids"]:
|
|
155
|
+
mal_node_to_windows[str(nid)].append((start_ns, end_ns))
|
|
156
|
+
|
|
157
|
+
mal_nids_str = set(mal_node_to_windows.keys())
|
|
158
|
+
|
|
159
|
+
base_dir = cfg.transformation._graphs_dir
|
|
160
|
+
attack_graph_paths = (
|
|
161
|
+
get_all_graphs_for_dates(base_dir, cfg.dataset.val_dates)
|
|
162
|
+
+ get_all_graphs_for_dates(base_dir, cfg.dataset.test_dates)
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
attack_walks: List[Tuple[List[str], List[str], str, str]] = []
|
|
166
|
+
n_mal_edges = 0
|
|
167
|
+
|
|
168
|
+
for graph_path in attack_graph_paths:
|
|
169
|
+
graph = torch.load(graph_path, weights_only=False)
|
|
170
|
+
sampler = ProvenanceWalkSampler(
|
|
171
|
+
graph, walk_length=walk_length, num_walks=1,
|
|
172
|
+
time_weight=time_weight, half_life=half_life,
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
# First pass: collect unique (src, dst, etype) triples within the attack window.
|
|
176
|
+
# Keep the latest timestamp per triple so the backward walk has maximum context.
|
|
177
|
+
triple_to_ts: dict = {} # (src_str, dst_str, etype) -> latest ts
|
|
178
|
+
for src, dst, _, attrs in graph.edges(data=True, keys=True):
|
|
179
|
+
dst_str = str(dst)
|
|
180
|
+
if dst_str not in mal_nids_str:
|
|
181
|
+
continue
|
|
182
|
+
ts = attrs.get("time", 0.0)
|
|
183
|
+
if not any(start <= ts <= end for start, end in mal_node_to_windows[dst_str]):
|
|
184
|
+
continue
|
|
185
|
+
etype = attrs.get("label", "")
|
|
186
|
+
key = (str(src), dst_str, etype)
|
|
187
|
+
if key not in triple_to_ts or ts > triple_to_ts[key]:
|
|
188
|
+
triple_to_ts[key] = ts
|
|
189
|
+
|
|
190
|
+
n_mal_edges += len(triple_to_ts)
|
|
191
|
+
|
|
192
|
+
# Second pass: sample num_walks unique walks per unique triple.
|
|
193
|
+
for (src_str, dst_str, etype), ts in triple_to_ts.items():
|
|
194
|
+
# dst backward walk is deterministic (no randomness in sample_context_walk
|
|
195
|
+
# for the first hop) — sample once and reuse across all src walk variants.
|
|
196
|
+
dst_walk_nodes, dst_walk_edge_types = sampler.sample_context_walk(
|
|
197
|
+
dst_str, max_ts=ts, walk_length=walk_length,
|
|
198
|
+
)
|
|
199
|
+
seen_seqs: set = set()
|
|
200
|
+
n_tries = 0
|
|
201
|
+
max_tries = num_walks * 5
|
|
202
|
+
while len(seen_seqs) < num_walks and n_tries < max_tries:
|
|
203
|
+
n_tries += 1
|
|
204
|
+
walk_nodes, walk_edge_types = sampler.sample_bidirectional_walk(
|
|
205
|
+
src_str, max_ts=ts, walk_length=walk_length,
|
|
206
|
+
)
|
|
207
|
+
seq_key = tuple(walk_edge_types)
|
|
208
|
+
if seq_key not in seen_seqs:
|
|
209
|
+
seen_seqs.add(seq_key)
|
|
210
|
+
attack_walks.append((
|
|
211
|
+
walk_nodes, walk_edge_types,
|
|
212
|
+
dst_walk_nodes, dst_walk_edge_types,
|
|
213
|
+
dst_str, etype,
|
|
214
|
+
))
|
|
215
|
+
|
|
216
|
+
log(f"Extracted {len(attack_walks)} unique attack walks from {n_mal_edges} unique malicious triples "
|
|
217
|
+
f"({len(mal_nids_str)} malicious nodes)")
|
|
218
|
+
return attack_walks
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _save_attack_walks(walks: List[Tuple], path: str) -> None:
|
|
222
|
+
with open(path, "wb") as f:
|
|
223
|
+
pickle.dump(walks, f)
|
|
224
|
+
log(f"Saved {len(walks)} attack walks to {path}")
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _load_attack_walks(path: str) -> List[Tuple]:
|
|
228
|
+
with open(path, "rb") as f:
|
|
229
|
+
walks = pickle.load(f)
|
|
230
|
+
log(f"Loaded {len(walks)} attack walks from {path}")
|
|
231
|
+
return walks
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _prepare_finetune_batch_cls_attack(
|
|
235
|
+
benign_edges: List[Tuple[str, str, str, float]],
|
|
236
|
+
attack_walks_sample: List[Tuple[List[str], List[str], List[str], List[str], str, str]],
|
|
237
|
+
sampler: ProvenanceWalkSampler,
|
|
238
|
+
tokenizer: ProvenanceTokenizer,
|
|
239
|
+
indexid2msg: dict,
|
|
240
|
+
walk_length: int,
|
|
241
|
+
):
|
|
242
|
+
"""Prepare a CLS batch from real benign edges (label=0) and real attack walks (label=1).
|
|
243
|
+
|
|
244
|
+
Args:
|
|
245
|
+
benign_edges: edges from normal training graphs; provide context and destination.
|
|
246
|
+
attack_walks_sample: pre-extracted attack walks (same length as benign_edges).
|
|
247
|
+
Each element is (src_walk_nodes, src_walk_edge_types,
|
|
248
|
+
dst_walk_nodes, dst_walk_edge_types, dst, etype).
|
|
249
|
+
|
|
250
|
+
Returns:
|
|
251
|
+
input_ids, attention_mask, target_mask, labels — same format as
|
|
252
|
+
_prepare_finetune_batch_cls, ready to pass to model.forward().
|
|
253
|
+
"""
|
|
254
|
+
batch_input_ids = []
|
|
255
|
+
batch_attn = []
|
|
256
|
+
batch_target = []
|
|
257
|
+
batch_labels = []
|
|
258
|
+
|
|
259
|
+
for (src, dst, etype, ts), (
|
|
260
|
+
aw_nodes, aw_etypes, aw_dst_walk_nodes, aw_dst_walk_etypes, aw_dst, aw_etype
|
|
261
|
+
) in zip(benign_edges, attack_walks_sample):
|
|
262
|
+
# Benign example (label=0): sample src bidirectional walk + dst backward walk
|
|
263
|
+
walk_nodes, walk_edge_types = sampler.sample_bidirectional_walk(src, max_ts=ts, walk_length=walk_length)
|
|
264
|
+
dst_walk_nodes, dst_walk_edge_types = sampler.sample_context_walk(dst, max_ts=ts, walk_length=walk_length)
|
|
265
|
+
tok_ids, attn, tgt_mask = tokenizer.tokenize_for_finetune(
|
|
266
|
+
walk_nodes, walk_edge_types, dst, etype, indexid2msg, mode="cls",
|
|
267
|
+
dst_walk_nodes=dst_walk_nodes, dst_walk_edge_types=dst_walk_edge_types,
|
|
268
|
+
)
|
|
269
|
+
batch_input_ids.append(tok_ids)
|
|
270
|
+
batch_attn.append(attn)
|
|
271
|
+
batch_target.append(tgt_mask)
|
|
272
|
+
batch_labels.append(0.0)
|
|
273
|
+
|
|
274
|
+
# Attack example (label=1) — use pre-extracted src and dst walks
|
|
275
|
+
tok_ids, attn, tgt_mask = tokenizer.tokenize_for_finetune(
|
|
276
|
+
aw_nodes, aw_etypes, aw_dst, aw_etype, indexid2msg, mode="cls",
|
|
277
|
+
dst_walk_nodes=aw_dst_walk_nodes, dst_walk_edge_types=aw_dst_walk_etypes,
|
|
278
|
+
)
|
|
279
|
+
batch_input_ids.append(tok_ids)
|
|
280
|
+
batch_attn.append(attn)
|
|
281
|
+
batch_target.append(tgt_mask)
|
|
282
|
+
batch_labels.append(1.0)
|
|
283
|
+
|
|
284
|
+
# Pad to max length
|
|
285
|
+
input_ids = pad_tensor_batch(batch_input_ids, pad_value=tokenizer.pad_id)
|
|
286
|
+
attention_mask = pad_tensor_batch(batch_attn, pad_value=0)
|
|
287
|
+
target_mask = pad_tensor_batch(batch_target, pad_value=0)
|
|
288
|
+
labels = torch.zeros(len(batch_input_ids), 1)
|
|
289
|
+
for i in range(len(batch_labels)):
|
|
290
|
+
labels[i, 0] = batch_labels[i]
|
|
291
|
+
|
|
292
|
+
return input_ids, attention_mask, target_mask, labels
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def _prepare_finetune_batch_cls(
|
|
296
|
+
edges: List[Tuple[str, str, str, float]],
|
|
297
|
+
sampler: ProvenanceWalkSampler,
|
|
298
|
+
tokenizer: ProvenanceTokenizer,
|
|
299
|
+
indexid2msg: dict,
|
|
300
|
+
walk_length: int,
|
|
301
|
+
neg_map: dict = None,
|
|
302
|
+
neg_ratio: float = 1.0,
|
|
303
|
+
):
|
|
304
|
+
"""Prepare a batch for CLS fine-tuning: positive + negative edges.
|
|
305
|
+
|
|
306
|
+
Args:
|
|
307
|
+
neg_map: Pre-computed (src, dst, etype) -> neg_dst dict. When provided,
|
|
308
|
+
negatives are guaranteed to have a different label from dst and
|
|
309
|
+
not to be real edges. Falls back to random node otherwise.
|
|
310
|
+
|
|
311
|
+
Returns:
|
|
312
|
+
input_ids: [B, L]
|
|
313
|
+
attention_mask: [B, L]
|
|
314
|
+
target_mask: [B, L]
|
|
315
|
+
labels: [B, 1]
|
|
316
|
+
"""
|
|
317
|
+
all_nodes = list(sampler.nodes)
|
|
318
|
+
batch_input_ids = []
|
|
319
|
+
batch_attn = []
|
|
320
|
+
batch_target = []
|
|
321
|
+
batch_labels = []
|
|
322
|
+
|
|
323
|
+
for src, dst, etype, ts in edges:
|
|
324
|
+
# Positive edge
|
|
325
|
+
walk_nodes, walk_edge_types = sampler.sample_bidirectional_walk(src, max_ts=ts, walk_length=walk_length)
|
|
326
|
+
dst_walk_nodes, dst_walk_edge_types = sampler.sample_context_walk(dst, max_ts=ts, walk_length=walk_length)
|
|
327
|
+
tok_ids, attn, tgt_mask = tokenizer.tokenize_for_finetune(
|
|
328
|
+
walk_nodes, walk_edge_types, dst, etype, indexid2msg, mode="cls",
|
|
329
|
+
dst_walk_nodes=dst_walk_nodes, dst_walk_edge_types=dst_walk_edge_types,
|
|
330
|
+
)
|
|
331
|
+
batch_input_ids.append(tok_ids)
|
|
332
|
+
batch_attn.append(attn)
|
|
333
|
+
batch_target.append(tgt_mask)
|
|
334
|
+
batch_labels.append(0.0) # Normal
|
|
335
|
+
|
|
336
|
+
# Hard negative: pre-computed (different label, not a real edge) or random
|
|
337
|
+
if neg_map is not None:
|
|
338
|
+
neg_dst = neg_map.get((str(src), str(dst), str(etype)), str(random.choice(all_nodes)))
|
|
339
|
+
else:
|
|
340
|
+
neg_dst = str(random.choice(all_nodes))
|
|
341
|
+
neg_dst_walk_nodes, neg_dst_walk_edge_types = sampler.sample_context_walk(neg_dst, max_ts=ts, walk_length=walk_length)
|
|
342
|
+
tok_ids, attn, tgt_mask = tokenizer.tokenize_for_finetune(
|
|
343
|
+
walk_nodes, walk_edge_types, str(neg_dst), etype, indexid2msg, mode="cls",
|
|
344
|
+
dst_walk_nodes=neg_dst_walk_nodes, dst_walk_edge_types=neg_dst_walk_edge_types,
|
|
345
|
+
)
|
|
346
|
+
batch_input_ids.append(tok_ids)
|
|
347
|
+
batch_attn.append(attn)
|
|
348
|
+
batch_target.append(tgt_mask)
|
|
349
|
+
batch_labels.append(1.0) # Anomalous
|
|
350
|
+
|
|
351
|
+
# Pad to max length
|
|
352
|
+
input_ids = pad_tensor_batch(batch_input_ids, pad_value=tokenizer.pad_id)
|
|
353
|
+
attention_mask = pad_tensor_batch(batch_attn, pad_value=0)
|
|
354
|
+
target_mask = pad_tensor_batch(batch_target, pad_value=0)
|
|
355
|
+
|
|
356
|
+
labels = torch.tensor(batch_labels, dtype=torch.float32).unsqueeze(-1)
|
|
357
|
+
return input_ids, attention_mask, target_mask, labels
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _prepare_finetune_batch_lp(
|
|
361
|
+
edges: List[Tuple[str, str, str, float]],
|
|
362
|
+
sampler: ProvenanceWalkSampler,
|
|
363
|
+
tokenizer: ProvenanceTokenizer,
|
|
364
|
+
indexid2msg: dict,
|
|
365
|
+
walk_length: int,
|
|
366
|
+
):
|
|
367
|
+
"""Prepare a batch for LP fine-tuning: mask destination, predict tokens.
|
|
368
|
+
|
|
369
|
+
Returns:
|
|
370
|
+
input_ids: [B, L]
|
|
371
|
+
attention_mask: [B, L]
|
|
372
|
+
target_mask: [B, L]
|
|
373
|
+
target_token_ids: [B, L]
|
|
374
|
+
"""
|
|
375
|
+
batch_input_ids = []
|
|
376
|
+
batch_attn = []
|
|
377
|
+
batch_target_mask = []
|
|
378
|
+
batch_target_ids = []
|
|
379
|
+
|
|
380
|
+
for src, dst, etype, ts in edges:
|
|
381
|
+
walk_nodes, walk_edge_types = sampler.sample_bidirectional_walk(src, max_ts=ts, walk_length=walk_length)
|
|
382
|
+
|
|
383
|
+
# Get full tokenization (to know dst tokens)
|
|
384
|
+
tok_ids_full, attn_full, _ = tokenizer.tokenize_for_finetune(
|
|
385
|
+
walk_nodes, walk_edge_types, dst, etype, indexid2msg, mode="cls"
|
|
386
|
+
)
|
|
387
|
+
|
|
388
|
+
# Get masked version
|
|
389
|
+
tok_ids_masked, attn_masked, tgt_mask = tokenizer.tokenize_for_finetune(
|
|
390
|
+
walk_nodes, walk_edge_types, dst, etype, indexid2msg, mode="lp"
|
|
391
|
+
)
|
|
392
|
+
|
|
393
|
+
# Build target: true token IDs where masked, -100 elsewhere
|
|
394
|
+
target_ids = torch.full_like(tok_ids_masked, -100)
|
|
395
|
+
# The LP mask positions correspond to the destination tokens
|
|
396
|
+
mask_positions = tgt_mask.nonzero(as_tuple=True)[0]
|
|
397
|
+
|
|
398
|
+
# Get actual destination tokens for targets
|
|
399
|
+
if dst in indexid2msg:
|
|
400
|
+
dst_type, dst_label = indexid2msg[dst]
|
|
401
|
+
dst_tokens = tokenizer.tokenize_node(dst_type, dst_label)
|
|
402
|
+
for j, pos in enumerate(mask_positions):
|
|
403
|
+
if j < len(dst_tokens):
|
|
404
|
+
target_ids[pos] = dst_tokens[j]
|
|
405
|
+
|
|
406
|
+
batch_input_ids.append(tok_ids_masked)
|
|
407
|
+
batch_attn.append(attn_masked)
|
|
408
|
+
batch_target_mask.append(tgt_mask)
|
|
409
|
+
batch_target_ids.append(target_ids)
|
|
410
|
+
|
|
411
|
+
# Pad
|
|
412
|
+
input_ids = pad_tensor_batch(batch_input_ids, pad_value=tokenizer.pad_id)
|
|
413
|
+
attention_mask = pad_tensor_batch(batch_attn, pad_value=0)
|
|
414
|
+
target_mask = pad_tensor_batch(batch_target_mask, pad_value=0)
|
|
415
|
+
target_token_ids = pad_tensor_batch(batch_target_ids, pad_value=-100)
|
|
416
|
+
|
|
417
|
+
return input_ids, attention_mask, target_mask, target_token_ids
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
# ── TGN helpers ────────────────────────────────────────────────────────────────
|
|
421
|
+
|
|
422
|
+
def _build_node_to_idx(indexid2msg: dict) -> dict:
|
|
423
|
+
"""Build str(node_id) -> contiguous index mapping. Index 0 reserved for unknown."""
|
|
424
|
+
sorted_keys = sorted(indexid2msg.keys(), key=lambda x: int(x))
|
|
425
|
+
return {str(k): i + 1 for i, k in enumerate(sorted_keys)}
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def _precompute_cross_type_negatives(
|
|
429
|
+
edges: List[Tuple],
|
|
430
|
+
indexid2msg: dict,
|
|
431
|
+
node_to_idx: dict,
|
|
432
|
+
) -> dict:
|
|
433
|
+
"""Pre-compute cross-type negative dst per unique (src, dst, etype) triple.
|
|
434
|
+
|
|
435
|
+
Each negative is a node of a DIFFERENT type than dst (e.g. file -> subject,
|
|
436
|
+
subject -> netflow), creating structurally implausible edges that are
|
|
437
|
+
maximally separated from benign ones in feature space. This ensures the
|
|
438
|
+
classifier learns a wide decision boundary, minimizing false positives.
|
|
439
|
+
|
|
440
|
+
Returns: {(src, dst, etype): neg_dst_str}
|
|
441
|
+
"""
|
|
442
|
+
type_to_nodes: dict = defaultdict(list)
|
|
443
|
+
for node_id, (node_type, _) in indexid2msg.items():
|
|
444
|
+
nid_str = str(node_id)
|
|
445
|
+
if nid_str in node_to_idx:
|
|
446
|
+
type_to_nodes[node_type].append(nid_str)
|
|
447
|
+
|
|
448
|
+
all_types = list(type_to_nodes.keys())
|
|
449
|
+
all_node_ids = list(node_to_idx.keys())
|
|
450
|
+
|
|
451
|
+
unique_keys = dict.fromkeys(
|
|
452
|
+
(str(e[0]), str(e[1]), str(e[2])) for e in edges
|
|
453
|
+
)
|
|
454
|
+
|
|
455
|
+
neg_map: dict = {}
|
|
456
|
+
for src, dst, etype in unique_keys:
|
|
457
|
+
dst_info = indexid2msg.get(dst)
|
|
458
|
+
if dst_info:
|
|
459
|
+
dst_type = dst_info[0]
|
|
460
|
+
other_types = [t for t in all_types if t != dst_type]
|
|
461
|
+
if other_types:
|
|
462
|
+
neg_type = random.choice(other_types)
|
|
463
|
+
neg_map[(src, dst, etype)] = random.choice(type_to_nodes[neg_type])
|
|
464
|
+
continue
|
|
465
|
+
# Fallback: random node (only if dst type unknown or all nodes share one type)
|
|
466
|
+
neg_map[(src, dst, etype)] = random.choice(all_node_ids)
|
|
467
|
+
|
|
468
|
+
return neg_map
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
def _precompute_entity_embeddings(
|
|
472
|
+
cfg,
|
|
473
|
+
indexid2msg: dict,
|
|
474
|
+
node_to_idx: dict,
|
|
475
|
+
num_nodes: int,
|
|
476
|
+
entity_emb_dim: int,
|
|
477
|
+
device: str,
|
|
478
|
+
) -> torch.Tensor:
|
|
479
|
+
"""Pre-compute static BERT embeddings for all entities via mean pooling.
|
|
480
|
+
|
|
481
|
+
Runs each entity's (type, label) tokens through frozen pretrained BERT,
|
|
482
|
+
mean-pools over non-padding positions to get a single [H] vector.
|
|
483
|
+
|
|
484
|
+
Returns: [num_nodes, entity_emb_dim] tensor.
|
|
485
|
+
"""
|
|
486
|
+
pretrain_cfg = cfg.featurization.pretrained
|
|
487
|
+
model_type = pretrain_cfg.model_type
|
|
488
|
+
model_size = pretrain_cfg.model_size
|
|
489
|
+
pretrain_dir = cfg.featurization._model_dir
|
|
490
|
+
batch_size = pretrain_cfg.training.batch_size
|
|
491
|
+
|
|
492
|
+
# Use a large batch size since node labels are very short (~5 tokens vs 128 for walks)
|
|
493
|
+
emb_batch_size = batch_size * 16
|
|
494
|
+
|
|
495
|
+
# Load tokenizer
|
|
496
|
+
tokenizer = ProvenanceTokenizer(cfg)
|
|
497
|
+
tokenizer.load(os.path.join(pretrain_dir, "tokenizer.pt"))
|
|
498
|
+
|
|
499
|
+
# Load pretrained backbone
|
|
500
|
+
if model_type == "ropebert":
|
|
501
|
+
from .models.ropebert import ProvenanceRoPEBERT
|
|
502
|
+
rope_theta = getattr(pretrain_cfg, 'rope_theta', 10000.0)
|
|
503
|
+
bert_config = get_ropebert_config(
|
|
504
|
+
tokenizer.vocab_size, model_size, tokenizer.max_seq_len,
|
|
505
|
+
rope_theta=rope_theta,
|
|
506
|
+
)
|
|
507
|
+
bert = ProvenanceRoPEBERT(bert_config)
|
|
508
|
+
elif model_type == "modernbert":
|
|
509
|
+
from .models.modernbert import ProvenanceModernBERT
|
|
510
|
+
bert_config = get_modernbert_config(
|
|
511
|
+
tokenizer.vocab_size, model_size, tokenizer.max_seq_len,
|
|
512
|
+
global_attn_every_n_layers=pretrain_cfg.global_attn_every_n_layers,
|
|
513
|
+
local_attention_window=pretrain_cfg.local_attention_window,
|
|
514
|
+
)
|
|
515
|
+
bert = ProvenanceModernBERT(bert_config)
|
|
516
|
+
else:
|
|
517
|
+
from .models.bert import ProvenanceBERT
|
|
518
|
+
bert_config = get_bert_config(tokenizer.vocab_size, model_size, tokenizer.max_seq_len)
|
|
519
|
+
bert = ProvenanceBERT(bert_config)
|
|
520
|
+
|
|
521
|
+
pt_path = os.path.join(pretrain_dir, f"pretrain_{model_size}.pt")
|
|
522
|
+
|
|
523
|
+
sd = torch.load(pt_path, weights_only=True, map_location="cpu")
|
|
524
|
+
bert.load_state_dict(sd)
|
|
525
|
+
bert = bert.to(device)
|
|
526
|
+
bert.eval()
|
|
527
|
+
|
|
528
|
+
entity_embs = torch.zeros(num_nodes, entity_emb_dim)
|
|
529
|
+
|
|
530
|
+
# Build list sorted by contiguous index for deterministic batching
|
|
531
|
+
items = sorted(
|
|
532
|
+
((str(nid), ntype, nlabel) for nid, (ntype, nlabel) in indexid2msg.items()),
|
|
533
|
+
key=lambda x: node_to_idx.get(x[0], 0),
|
|
534
|
+
)
|
|
535
|
+
|
|
536
|
+
total_batches = (len(items) + emb_batch_size - 1) // emb_batch_size
|
|
537
|
+
for batch_idx, batch_start in enumerate(range(0, len(items), emb_batch_size)):
|
|
538
|
+
batch = items[batch_start:batch_start + emb_batch_size]
|
|
539
|
+
|
|
540
|
+
if batch_idx % 20 == 0:
|
|
541
|
+
log(f" Embedding batch {batch_idx+1}/{total_batches} ({batch_start:,}/{len(items):,} nodes)")
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
batch_token_ids = []
|
|
545
|
+
batch_indices = []
|
|
546
|
+
for nid_str, ntype, nlabel in batch:
|
|
547
|
+
idx = node_to_idx.get(nid_str)
|
|
548
|
+
if idx is None:
|
|
549
|
+
continue
|
|
550
|
+
tids = tokenizer.tokenize_node(ntype, nlabel)
|
|
551
|
+
if tids:
|
|
552
|
+
batch_token_ids.append(tids)
|
|
553
|
+
batch_indices.append(idx)
|
|
554
|
+
|
|
555
|
+
if not batch_token_ids:
|
|
556
|
+
continue
|
|
557
|
+
|
|
558
|
+
input_ids, attention_mask = pad_token_id_lists(batch_token_ids, tokenizer.pad_id, tokenizer.max_seq_len)
|
|
559
|
+
|
|
560
|
+
with torch.no_grad():
|
|
561
|
+
hidden = bert.modified_fwd(
|
|
562
|
+
input_ids.to(device),
|
|
563
|
+
attention_mask.to(device),
|
|
564
|
+
labels=torch.full_like(input_ids, -100).to(device),
|
|
565
|
+
skip_cls=True,
|
|
566
|
+
) # [B, max_len, H]
|
|
567
|
+
|
|
568
|
+
# Mean pool over non-padding positions
|
|
569
|
+
mask_f = attention_mask.to(device).unsqueeze(-1).float()
|
|
570
|
+
pooled = (hidden * mask_f).sum(dim=1) / mask_f.sum(dim=1).clamp(min=1)
|
|
571
|
+
|
|
572
|
+
for i, idx in enumerate(batch_indices):
|
|
573
|
+
entity_embs[idx] = pooled[i].cpu()
|
|
574
|
+
|
|
575
|
+
del bert
|
|
576
|
+
if torch.cuda.is_available():
|
|
577
|
+
torch.cuda.empty_cache()
|
|
578
|
+
|
|
579
|
+
log(f"Pre-computed entity embeddings: {entity_embs.shape}")
|
|
580
|
+
return entity_embs
|
|
581
|
+
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
def _train_edge_cls(cfg):
|
|
585
|
+
"""Edge type classification from BERT embeddings.
|
|
586
|
+
|
|
587
|
+
Path mode: static entity embeddings per node (existing behavior).
|
|
588
|
+
Event mode: per-edge contextual embeddings from masked-event BERT pass.
|
|
589
|
+
|
|
590
|
+
Predicts edge type given (src, dst) BERT embeddings. No temporal memory
|
|
591
|
+
or state — edges are shuffled each epoch. CE loss, anomaly score = CE of
|
|
592
|
+
true edge type.
|
|
593
|
+
"""
|
|
594
|
+
|
|
595
|
+
from .models.tgn import EdgeTypeClassifier
|
|
596
|
+
import torch.nn as nn
|
|
597
|
+
|
|
598
|
+
pretrain_cfg = cfg.featurization.pretrained
|
|
599
|
+
detect_cfg = cfg.training.pretrained
|
|
600
|
+
model_size = pretrain_cfg.model_size
|
|
601
|
+
finetune_epochs = detect_cfg.finetune_epochs
|
|
602
|
+
finetune_lr = detect_cfg.finetune_lr
|
|
603
|
+
scheduler_type = pretrain_cfg.training.scheduler
|
|
604
|
+
|
|
605
|
+
device = "cuda" if torch.cuda.is_available() and not cfg._use_cpu else "cpu"
|
|
606
|
+
ft_dir = cfg.training._trained_models_dir
|
|
607
|
+
os.makedirs(ft_dir, exist_ok=True)
|
|
608
|
+
|
|
609
|
+
H = MODEL_SIZES[model_size].H
|
|
610
|
+
tgn_cfg = detect_cfg.tgn
|
|
611
|
+
hidden_dim = tgn_cfg.edge_emb_dim
|
|
612
|
+
batch_size = tgn_cfg.batch_size
|
|
613
|
+
|
|
614
|
+
# ── Data loading ───────────────────────────────────────────────
|
|
615
|
+
indexid2msg = get_indexid2msg(cfg)
|
|
616
|
+
rel2id = get_rel2id(cfg)
|
|
617
|
+
base_dir = cfg.transformation._graphs_dir
|
|
618
|
+
train_graph_paths = get_all_graphs_for_dates(base_dir, cfg.dataset.train_dates)
|
|
619
|
+
|
|
620
|
+
node_to_idx = _build_node_to_idx(indexid2msg)
|
|
621
|
+
num_nodes = len(node_to_idx) + 1
|
|
622
|
+
|
|
623
|
+
edge_type_to_id = {k: v for k, v in rel2id.items() if isinstance(k, str)}
|
|
624
|
+
num_edge_types = max(edge_type_to_id.values()) + 1 if edge_type_to_id else 1
|
|
625
|
+
|
|
626
|
+
train_edges = []
|
|
627
|
+
for p in train_graph_paths:
|
|
628
|
+
g = torch.load(p, weights_only=False)
|
|
629
|
+
train_edges.extend(_collect_edges(g))
|
|
630
|
+
log(f"Training edges: {len(train_edges)}")
|
|
631
|
+
|
|
632
|
+
# ── Embeddings ─────────────────────────────────────────────────
|
|
633
|
+
entity_embs_path = os.path.join(ft_dir, "entity_embs_tgn.pt")
|
|
634
|
+
if os.path.exists(entity_embs_path):
|
|
635
|
+
entity_embs = torch.load(entity_embs_path, map_location="cpu")
|
|
636
|
+
log(f"Loaded cached entity embeddings: {entity_embs.shape}")
|
|
637
|
+
else:
|
|
638
|
+
log("Pre-computing entity BERT embeddings...")
|
|
639
|
+
entity_embs = _precompute_entity_embeddings(
|
|
640
|
+
cfg, indexid2msg, node_to_idx, num_nodes, H, device,
|
|
641
|
+
)
|
|
642
|
+
torch.save(entity_embs, entity_embs_path)
|
|
643
|
+
|
|
644
|
+
model = EdgeTypeClassifier(
|
|
645
|
+
num_nodes=num_nodes,
|
|
646
|
+
num_edge_types=num_edge_types,
|
|
647
|
+
entity_emb_dim=H,
|
|
648
|
+
hidden_dim=hidden_dim,
|
|
649
|
+
).to(device)
|
|
650
|
+
model.set_entity_embeddings(entity_embs)
|
|
651
|
+
|
|
652
|
+
log(f"EdgeTypeClassifier: {sum(p.numel() for p in model.parameters()):,} params, "
|
|
653
|
+
f"{num_nodes:,} entities, {num_edge_types} edge types")
|
|
654
|
+
|
|
655
|
+
opt = AdamW(model.parameters(), lr=finetune_lr, betas=(0.9, 0.99),
|
|
656
|
+
eps=1e-10, weight_decay=0.02)
|
|
657
|
+
updates_per_epoch = max(1, len(train_edges) // batch_size)
|
|
658
|
+
total_steps = updates_per_epoch * finetune_epochs
|
|
659
|
+
warmup_steps = max(1, total_steps // 20)
|
|
660
|
+
if scheduler_type == "cosine":
|
|
661
|
+
scheduler = WarmupCosineScheduler(opt, warmup_steps, total_steps)
|
|
662
|
+
else:
|
|
663
|
+
scheduler = WarmupLinearScheduler(opt, warmup_steps, total_steps)
|
|
664
|
+
|
|
665
|
+
log_path = os.path.join(ft_dir, f"finetune_edge_cls_{model_size}_log.txt")
|
|
666
|
+
with open(log_path, "w") as f:
|
|
667
|
+
f.write("epoch,update,loss,lr\n")
|
|
668
|
+
|
|
669
|
+
best_loss = float("inf")
|
|
670
|
+
updates = 0
|
|
671
|
+
|
|
672
|
+
for epoch in range(finetune_epochs):
|
|
673
|
+
model.train()
|
|
674
|
+
random.shuffle(train_edges)
|
|
675
|
+
|
|
676
|
+
epoch_loss = 0.0
|
|
677
|
+
n_batches = 0
|
|
678
|
+
st = time.time()
|
|
679
|
+
|
|
680
|
+
for batch_start in range(0, len(train_edges), batch_size):
|
|
681
|
+
batch_edges = train_edges[batch_start:batch_start + batch_size]
|
|
682
|
+
|
|
683
|
+
src_idx = torch.tensor(
|
|
684
|
+
[node_to_idx.get(e[0], 0) for e in batch_edges],
|
|
685
|
+
dtype=torch.long, device=device)
|
|
686
|
+
dst_idx = torch.tensor(
|
|
687
|
+
[node_to_idx.get(e[1], 0) for e in batch_edges],
|
|
688
|
+
dtype=torch.long, device=device)
|
|
689
|
+
etypes = torch.tensor(
|
|
690
|
+
[edge_type_to_id.get(e[2], 0) for e in batch_edges],
|
|
691
|
+
dtype=torch.long, device=device)
|
|
692
|
+
|
|
693
|
+
logits = model.predict(src_idx, dst_idx)
|
|
694
|
+
loss = F.cross_entropy(logits, etypes)
|
|
695
|
+
|
|
696
|
+
loss.backward()
|
|
697
|
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
|
698
|
+
opt.step()
|
|
699
|
+
opt.zero_grad()
|
|
700
|
+
scheduler.step()
|
|
701
|
+
|
|
702
|
+
epoch_loss += loss.item()
|
|
703
|
+
n_batches += 1
|
|
704
|
+
updates += 1
|
|
705
|
+
|
|
706
|
+
if updates % 50 == 0:
|
|
707
|
+
lr = scheduler.get_last_lr()[0]
|
|
708
|
+
log(f"[e{epoch+1}|u{updates}] loss={loss.item():.4f} lr={lr:.2e}")
|
|
709
|
+
|
|
710
|
+
avg_loss = epoch_loss / max(1, n_batches)
|
|
711
|
+
elapsed = time.time() - st
|
|
712
|
+
log(f"Epoch {epoch+1}/{finetune_epochs}: avg_loss={avg_loss:.4f} ({elapsed:.1f}s)")
|
|
713
|
+
|
|
714
|
+
with open(log_path, "a") as f:
|
|
715
|
+
f.write(f"{epoch+1},{updates},{avg_loss:.6f},{scheduler.get_last_lr()[0]:.2e}\n")
|
|
716
|
+
|
|
717
|
+
ckpt = {
|
|
718
|
+
"model_state_dict": model.state_dict(),
|
|
719
|
+
"node_to_idx": node_to_idx,
|
|
720
|
+
"edge_type_to_id": edge_type_to_id,
|
|
721
|
+
"num_nodes": num_nodes,
|
|
722
|
+
"num_edge_types": num_edge_types,
|
|
723
|
+
"pretrain_mode": "path",
|
|
724
|
+
"edge_cls_config": {
|
|
725
|
+
"entity_emb_dim": H,
|
|
726
|
+
"hidden_dim": hidden_dim,
|
|
727
|
+
},
|
|
728
|
+
}
|
|
729
|
+
save_path = os.path.join(ft_dir, f"finetune_edge_cls_{model_size}.pt")
|
|
730
|
+
torch.save(ckpt, save_path)
|
|
731
|
+
|
|
732
|
+
if avg_loss < best_loss:
|
|
733
|
+
best_loss = avg_loss
|
|
734
|
+
best_path = os.path.join(ft_dir, f"finetune_edge_cls_{model_size}_best.pt")
|
|
735
|
+
torch.save(ckpt, best_path)
|
|
736
|
+
|
|
737
|
+
log(f"Edge classification training complete. Best loss: {best_loss:.4f}")
|
|
738
|
+
|
|
739
|
+
|
|
740
|
+
def _train_tgn(cfg):
|
|
741
|
+
"""Self-supervised TGN training.
|
|
742
|
+
|
|
743
|
+
Five objectives are supported (tgn.objective):
|
|
744
|
+
contrastive — BCE loss with two-tier negative sampling (same-type +
|
|
745
|
+
cross-type corrupted dst). Score at inference = raw binary logit.
|
|
746
|
+
edge_pred — cross-entropy loss predicting the edge type from entity
|
|
747
|
+
memories and embeddings (no negative sampling needed). Score at
|
|
748
|
+
inference = per-edge CE loss of the true edge type.
|
|
749
|
+
multi_edge_pred — like edge_pred but groups edges by (src, dst) pair
|
|
750
|
+
within each batch and uses multi-hot BCE to predict ALL co-occurring
|
|
751
|
+
edge types. Score at inference = per-edge binary CE of the true type.
|
|
752
|
+
dist_edge_pred — groups edges by (src, dst) pair and predicts the
|
|
753
|
+
proportion of each edge type (count distribution). KL divergence
|
|
754
|
+
loss. Score at inference = -log P(true_type) under the predicted
|
|
755
|
+
distribution.
|
|
756
|
+
edge_pred_emb — predicts both the edge type (CE) and the edge embedding
|
|
757
|
+
vector (MSE). Score at inference = CE + MSE per edge.
|
|
758
|
+
|
|
759
|
+
No attack labels are used in any mode.
|
|
760
|
+
"""
|
|
761
|
+
|
|
762
|
+
pretrain_cfg = cfg.featurization.pretrained
|
|
763
|
+
detect_cfg = cfg.training.pretrained
|
|
764
|
+
model_size = pretrain_cfg.model_size
|
|
765
|
+
finetune_epochs = detect_cfg.finetune_epochs
|
|
766
|
+
finetune_lr = detect_cfg.finetune_lr
|
|
767
|
+
scheduler_type = pretrain_cfg.training.scheduler
|
|
768
|
+
|
|
769
|
+
device = "cuda" if torch.cuda.is_available() and not cfg._use_cpu else "cpu"
|
|
770
|
+
ft_dir = cfg.training._trained_models_dir
|
|
771
|
+
os.makedirs(ft_dir, exist_ok=True)
|
|
772
|
+
|
|
773
|
+
# ── TGN config ─────────────────────────────────────────────────
|
|
774
|
+
H = MODEL_SIZES[model_size].H
|
|
775
|
+
tgn_cfg = detect_cfg.tgn
|
|
776
|
+
memory_dim = tgn_cfg.memory_dim
|
|
777
|
+
edge_emb_dim = tgn_cfg.edge_emb_dim
|
|
778
|
+
time_dim = tgn_cfg.time_dim
|
|
779
|
+
num_heads = tgn_cfg.num_heads
|
|
780
|
+
tgn_batch_size = tgn_cfg.batch_size
|
|
781
|
+
use_node_type_emb = tgn_cfg.use_node_type_emb
|
|
782
|
+
use_time_emb = tgn_cfg.use_time_emb
|
|
783
|
+
use_memory = tgn_cfg.use_memory
|
|
784
|
+
use_entity_emb = tgn_cfg.use_entity_emb
|
|
785
|
+
score_gated_memory = tgn_cfg.score_gated_memory
|
|
786
|
+
temporal_decay = tgn_cfg.temporal_decay
|
|
787
|
+
anomaly_accumulator = tgn_cfg.anomaly_accumulator
|
|
788
|
+
objective = tgn_cfg.objective # "contrastive" / "edge_pred" / "multi_edge_pred"
|
|
789
|
+
|
|
790
|
+
use_event_bert_emb = False
|
|
791
|
+
|
|
792
|
+
# ── Data loading ───────────────────────────────────────────────
|
|
793
|
+
indexid2msg = get_indexid2msg(cfg)
|
|
794
|
+
rel2id = get_rel2id(cfg)
|
|
795
|
+
base_dir = cfg.transformation._graphs_dir
|
|
796
|
+
train_graph_paths = get_all_graphs_for_dates(base_dir, cfg.dataset.train_dates)
|
|
797
|
+
|
|
798
|
+
node_to_idx = _build_node_to_idx(indexid2msg)
|
|
799
|
+
num_nodes = len(node_to_idx) + 1 # +1 for index-0 unknown sentinel
|
|
800
|
+
|
|
801
|
+
# Build node type tensor: [num_nodes] mapping contiguous idx -> type ID
|
|
802
|
+
node_types_tensor = torch.zeros(num_nodes, dtype=torch.long)
|
|
803
|
+
for nid_str, (ntype, _) in indexid2msg.items():
|
|
804
|
+
idx = node_to_idx.get(str(nid_str))
|
|
805
|
+
if idx is not None:
|
|
806
|
+
node_types_tensor[idx] = ntype2id.get(ntype, 0)
|
|
807
|
+
|
|
808
|
+
edge_type_to_id = {k: v for k, v in rel2id.items() if isinstance(k, str)}
|
|
809
|
+
num_edge_types = max(edge_type_to_id.values()) + 1 if edge_type_to_id else 1
|
|
810
|
+
|
|
811
|
+
# Collect and sort all training edges by timestamp
|
|
812
|
+
train_edges = []
|
|
813
|
+
for p in train_graph_paths:
|
|
814
|
+
g = torch.load(p, weights_only=False)
|
|
815
|
+
train_edges.extend(_collect_edges(g))
|
|
816
|
+
train_edges.sort(key=lambda e: e[3])
|
|
817
|
+
log(f"Training edges: {len(train_edges)} (sorted by time)")
|
|
818
|
+
|
|
819
|
+
# ── Negative sampling (contrastive only) ─────────────────────
|
|
820
|
+
if objective == "contrastive":
|
|
821
|
+
type_to_labeled = _build_neg_index(indexid2msg)
|
|
822
|
+
real_edge_set: set = set()
|
|
823
|
+
for p in train_graph_paths:
|
|
824
|
+
g = torch.load(p, weights_only=False)
|
|
825
|
+
for src, dst, _, attrs in g.edges(data=True, keys=True):
|
|
826
|
+
real_edge_set.add((str(src), str(dst), attrs.get("label", "")))
|
|
827
|
+
neg_map_same = _precompute_negatives(train_edges, indexid2msg, type_to_labeled, real_edge_set)
|
|
828
|
+
neg_map_cross = _precompute_cross_type_negatives(train_edges, indexid2msg, node_to_idx)
|
|
829
|
+
log(f"Pre-computed negatives for {len(neg_map_same)} unique triples "
|
|
830
|
+
f"(same-type + cross-type, 2 per benign edge)")
|
|
831
|
+
else:
|
|
832
|
+
log(f"Objective: {objective} (no negative sampling needed)")
|
|
833
|
+
|
|
834
|
+
# ── Entity embeddings ──────────────────────────────────────────
|
|
835
|
+
entity_embs_path = os.path.join(ft_dir, "entity_embs_tgn.pt")
|
|
836
|
+
if os.path.exists(entity_embs_path):
|
|
837
|
+
entity_embs = torch.load(entity_embs_path, map_location="cpu")
|
|
838
|
+
log(f"Loaded cached entity embeddings: {entity_embs.shape}")
|
|
839
|
+
else:
|
|
840
|
+
log("Pre-computing entity BERT embeddings...")
|
|
841
|
+
entity_embs = _precompute_entity_embeddings(
|
|
842
|
+
cfg, indexid2msg, node_to_idx, num_nodes, H, device,
|
|
843
|
+
)
|
|
844
|
+
torch.save(entity_embs, entity_embs_path)
|
|
845
|
+
|
|
846
|
+
edge_to_pair_idx = None
|
|
847
|
+
event_src_embs_gpu = None
|
|
848
|
+
event_dst_embs_gpu = None
|
|
849
|
+
event_bert_emb_dim = 0
|
|
850
|
+
|
|
851
|
+
# ── Build model ────────────────────────────────────────────────
|
|
852
|
+
model = ProvenanceTGN(
|
|
853
|
+
num_nodes=num_nodes,
|
|
854
|
+
num_edge_types=num_edge_types,
|
|
855
|
+
entity_emb_dim=H,
|
|
856
|
+
memory_dim=memory_dim,
|
|
857
|
+
edge_emb_dim=edge_emb_dim,
|
|
858
|
+
time_dim=time_dim,
|
|
859
|
+
num_heads=num_heads,
|
|
860
|
+
use_node_type_emb=use_node_type_emb,
|
|
861
|
+
use_time_emb=use_time_emb,
|
|
862
|
+
use_memory=use_memory,
|
|
863
|
+
use_entity_emb=use_entity_emb,
|
|
864
|
+
use_event_bert_emb=use_event_bert_emb,
|
|
865
|
+
event_bert_emb_dim=event_bert_emb_dim,
|
|
866
|
+
score_gated_memory=score_gated_memory,
|
|
867
|
+
temporal_decay=temporal_decay,
|
|
868
|
+
anomaly_accumulator=anomaly_accumulator,
|
|
869
|
+
device=device,
|
|
870
|
+
).to(device)
|
|
871
|
+
model.set_entity_embeddings(entity_embs)
|
|
872
|
+
model.set_node_types(node_types_tensor)
|
|
873
|
+
log(f"TGN model: {sum(p.numel() for p in model.parameters()):,} trainable params, "
|
|
874
|
+
f"{num_nodes:,} entities, {num_edge_types} edge types, "
|
|
875
|
+
f"use_memory={use_memory}, use_entity_emb={use_entity_emb}, "
|
|
876
|
+
f"use_event_bert_emb={use_event_bert_emb}, "
|
|
877
|
+
f"score_gated={score_gated_memory}, decay={temporal_decay}, accum={anomaly_accumulator}")
|
|
878
|
+
|
|
879
|
+
# ── Optimizer & scheduler ──────────────────────────────────────
|
|
880
|
+
opt = AdamW(model.parameters(), lr=finetune_lr, betas=(0.9, 0.99), eps=1e-10, weight_decay=0.02)
|
|
881
|
+
updates_per_epoch = max(1, len(train_edges) // tgn_batch_size)
|
|
882
|
+
total_steps = updates_per_epoch * finetune_epochs
|
|
883
|
+
warmup_steps = max(1, total_steps // 20)
|
|
884
|
+
if scheduler_type == "cosine":
|
|
885
|
+
scheduler = WarmupCosineScheduler(opt, warmup_steps, total_steps)
|
|
886
|
+
else:
|
|
887
|
+
scheduler = WarmupLinearScheduler(opt, warmup_steps, total_steps)
|
|
888
|
+
|
|
889
|
+
# ── Training loop ──────────────────────────────────────────────
|
|
890
|
+
log_path = os.path.join(ft_dir, f"finetune_tgn_{model_size}_log.txt")
|
|
891
|
+
with open(log_path, "w") as f:
|
|
892
|
+
f.write("epoch,update,loss,lr\n")
|
|
893
|
+
|
|
894
|
+
all_node_keys = list(node_to_idx.keys())
|
|
895
|
+
best_loss = float("inf")
|
|
896
|
+
updates = 0
|
|
897
|
+
|
|
898
|
+
for epoch in range(finetune_epochs):
|
|
899
|
+
model.train()
|
|
900
|
+
model.reset_memory()
|
|
901
|
+
|
|
902
|
+
epoch_loss = 0.0
|
|
903
|
+
n_batches = 0
|
|
904
|
+
st = time.time()
|
|
905
|
+
|
|
906
|
+
# Process edges in TEMPORAL order (no shuffling)
|
|
907
|
+
for batch_start in range(0, len(train_edges), tgn_batch_size):
|
|
908
|
+
batch_edges = train_edges[batch_start:batch_start + tgn_batch_size]
|
|
909
|
+
|
|
910
|
+
src_idx = torch.tensor(
|
|
911
|
+
[node_to_idx.get(e[0], 0) for e in batch_edges], dtype=torch.long, device=device)
|
|
912
|
+
dst_idx = torch.tensor(
|
|
913
|
+
[node_to_idx.get(e[1], 0) for e in batch_edges], dtype=torch.long, device=device)
|
|
914
|
+
etypes = torch.tensor(
|
|
915
|
+
[edge_type_to_id.get(e[2], 0) for e in batch_edges], dtype=torch.long, device=device)
|
|
916
|
+
ts = torch.tensor(
|
|
917
|
+
[e[3] for e in batch_edges], dtype=torch.long, device=device)
|
|
918
|
+
|
|
919
|
+
# Look up precomputed per-edge contextual embeddings for this batch
|
|
920
|
+
if event_src_embs_gpu is not None:
|
|
921
|
+
batch_pair_idx = edge_to_pair_idx[batch_start:batch_start + len(batch_edges)]
|
|
922
|
+
batch_event_src = event_src_embs_gpu[batch_pair_idx]
|
|
923
|
+
batch_event_dst = event_dst_embs_gpu[batch_pair_idx]
|
|
924
|
+
else:
|
|
925
|
+
batch_event_src = None
|
|
926
|
+
batch_event_dst = None
|
|
927
|
+
|
|
928
|
+
if objective == "edge_pred":
|
|
929
|
+
# ── Edge type prediction: predict edge type from memories ──
|
|
930
|
+
logits = model.predict_edge_types(src_idx, dst_idx, ts,
|
|
931
|
+
event_src_emb=batch_event_src, event_dst_emb=batch_event_dst) # [B, num_edge_classes]
|
|
932
|
+
loss = torch.nn.CrossEntropyLoss()(logits, etypes)
|
|
933
|
+
# Per-edge anomaly scores for score-gated memory (detached)
|
|
934
|
+
if score_gated_memory:
|
|
935
|
+
with torch.no_grad():
|
|
936
|
+
edge_scores = torch.nn.functional.cross_entropy(
|
|
937
|
+
logits, etypes, reduction="none")
|
|
938
|
+
else:
|
|
939
|
+
edge_scores = None
|
|
940
|
+
|
|
941
|
+
elif objective == "multi_edge_pred":
|
|
942
|
+
# ── Multi-label edge type prediction ──
|
|
943
|
+
# Group by (src, dst) pair; predict ALL co-occurring edge types
|
|
944
|
+
pair_keys = torch.stack([src_idx, dst_idx], dim=1) # [B, 2]
|
|
945
|
+
unique_pairs, inverse = torch.unique(
|
|
946
|
+
pair_keys, dim=0, return_inverse=True) # [P, 2], [B]
|
|
947
|
+
num_pairs = unique_pairs.size(0)
|
|
948
|
+
num_classes = num_edge_types + 1 # match edge_predictor output
|
|
949
|
+
|
|
950
|
+
# Multi-hot target: which edge types occur for each pair
|
|
951
|
+
multi_hot = torch.zeros(num_pairs, num_classes, device=device)
|
|
952
|
+
multi_hot[inverse, etypes] = 1.0
|
|
953
|
+
|
|
954
|
+
# Use latest timestamp per pair for prediction
|
|
955
|
+
pair_ts = scatter(
|
|
956
|
+
ts, inverse, dim=0, dim_size=num_pairs, reduce="max")
|
|
957
|
+
|
|
958
|
+
# For multi/dist_edge_pred with event embeddings, aggregate per pair
|
|
959
|
+
if batch_event_src is not None:
|
|
960
|
+
pair_event_src = scatter(
|
|
961
|
+
batch_event_src, inverse, dim=0, dim_size=num_pairs, reduce="mean")
|
|
962
|
+
pair_event_dst = scatter(
|
|
963
|
+
batch_event_dst, inverse, dim=0, dim_size=num_pairs, reduce="mean")
|
|
964
|
+
else:
|
|
965
|
+
pair_event_src = None
|
|
966
|
+
pair_event_dst = None
|
|
967
|
+
|
|
968
|
+
logits = model.predict_edge_types(
|
|
969
|
+
unique_pairs[:, 0], unique_pairs[:, 1], pair_ts,
|
|
970
|
+
event_src_emb=pair_event_src, event_dst_emb=pair_event_dst,
|
|
971
|
+
) # [P, num_classes]
|
|
972
|
+
loss = F.binary_cross_entropy_with_logits(logits, multi_hot)
|
|
973
|
+
|
|
974
|
+
# Per-edge anomaly scores for score-gated memory
|
|
975
|
+
if score_gated_memory:
|
|
976
|
+
with torch.no_grad():
|
|
977
|
+
edge_logits = logits[inverse] # [B, num_classes]
|
|
978
|
+
per_edge_logit = edge_logits[
|
|
979
|
+
torch.arange(len(batch_edges), device=device), etypes]
|
|
980
|
+
edge_scores = F.binary_cross_entropy_with_logits(
|
|
981
|
+
per_edge_logit, torch.ones_like(per_edge_logit),
|
|
982
|
+
reduction="none")
|
|
983
|
+
else:
|
|
984
|
+
edge_scores = None
|
|
985
|
+
|
|
986
|
+
elif objective == "dist_edge_pred":
|
|
987
|
+
# ── Edge type distribution prediction ──
|
|
988
|
+
# Group by (src, dst) pair; predict the proportion of each type
|
|
989
|
+
pair_keys = torch.stack([src_idx, dst_idx], dim=1) # [B, 2]
|
|
990
|
+
unique_pairs, inverse = torch.unique(
|
|
991
|
+
pair_keys, dim=0, return_inverse=True) # [P, 2], [B]
|
|
992
|
+
num_pairs = unique_pairs.size(0)
|
|
993
|
+
num_classes = num_edge_types + 1 # match edge_predictor output
|
|
994
|
+
|
|
995
|
+
# Count edge types per pair → normalize to distribution
|
|
996
|
+
one_hot = torch.zeros(len(batch_edges), num_classes, device=device)
|
|
997
|
+
one_hot[torch.arange(len(batch_edges), device=device), etypes] = 1.0
|
|
998
|
+
counts = scatter(
|
|
999
|
+
one_hot, inverse, dim=0, dim_size=num_pairs, reduce="sum")
|
|
1000
|
+
target_dist = counts / counts.sum(dim=1, keepdim=True).clamp(min=1)
|
|
1001
|
+
|
|
1002
|
+
# Use latest timestamp per pair for prediction
|
|
1003
|
+
pair_ts = scatter(
|
|
1004
|
+
ts, inverse, dim=0, dim_size=num_pairs, reduce="max")
|
|
1005
|
+
|
|
1006
|
+
if batch_event_src is not None:
|
|
1007
|
+
pair_event_src = scatter(
|
|
1008
|
+
batch_event_src, inverse, dim=0, dim_size=num_pairs, reduce="mean")
|
|
1009
|
+
pair_event_dst = scatter(
|
|
1010
|
+
batch_event_dst, inverse, dim=0, dim_size=num_pairs, reduce="mean")
|
|
1011
|
+
else:
|
|
1012
|
+
pair_event_src = None
|
|
1013
|
+
pair_event_dst = None
|
|
1014
|
+
|
|
1015
|
+
logits = model.predict_edge_types(
|
|
1016
|
+
unique_pairs[:, 0], unique_pairs[:, 1], pair_ts,
|
|
1017
|
+
event_src_emb=pair_event_src, event_dst_emb=pair_event_dst,
|
|
1018
|
+
) # [P, num_classes]
|
|
1019
|
+
log_probs = F.log_softmax(logits, dim=-1)
|
|
1020
|
+
loss = F.kl_div(log_probs, target_dist, reduction="batchmean")
|
|
1021
|
+
|
|
1022
|
+
# Per-edge anomaly scores for score-gated memory
|
|
1023
|
+
if score_gated_memory:
|
|
1024
|
+
with torch.no_grad():
|
|
1025
|
+
edge_log_probs = log_probs[inverse] # [B, num_classes]
|
|
1026
|
+
edge_scores = -edge_log_probs[
|
|
1027
|
+
torch.arange(len(batch_edges), device=device), etypes]
|
|
1028
|
+
else:
|
|
1029
|
+
edge_scores = None
|
|
1030
|
+
|
|
1031
|
+
elif objective == "edge_pred_emb":
|
|
1032
|
+
# ── Edge type + embedding prediction ──
|
|
1033
|
+
# CE loss on edge type + MSE loss on edge embedding vector
|
|
1034
|
+
logits = model.predict_edge_types(src_idx, dst_idx, ts,
|
|
1035
|
+
event_src_emb=batch_event_src, event_dst_emb=batch_event_dst)
|
|
1036
|
+
ce_loss = F.cross_entropy(logits, etypes)
|
|
1037
|
+
|
|
1038
|
+
pred_emb = model.predict_edge_embedding(src_idx, dst_idx, ts,
|
|
1039
|
+
event_src_emb=batch_event_src, event_dst_emb=batch_event_dst)
|
|
1040
|
+
target_emb = model.edge_emb(etypes).detach()
|
|
1041
|
+
mse_loss = F.mse_loss(pred_emb, target_emb)
|
|
1042
|
+
|
|
1043
|
+
loss = ce_loss + mse_loss
|
|
1044
|
+
|
|
1045
|
+
# Per-edge anomaly scores for score-gated memory
|
|
1046
|
+
if score_gated_memory:
|
|
1047
|
+
with torch.no_grad():
|
|
1048
|
+
edge_scores = F.cross_entropy(
|
|
1049
|
+
logits, etypes, reduction="none")
|
|
1050
|
+
else:
|
|
1051
|
+
edge_scores = None
|
|
1052
|
+
|
|
1053
|
+
elif objective == "node_pred":
|
|
1054
|
+
# ── Node type prediction: predict dst node type ──
|
|
1055
|
+
logits = model.predict_node_types(src_idx, dst_idx, etypes, ts,
|
|
1056
|
+
event_src_emb=batch_event_src, event_dst_emb=batch_event_dst) # [B, NUM_NODE_TYPES]
|
|
1057
|
+
dst_types = model.node_types[dst_idx] # [B] ground truth
|
|
1058
|
+
loss = F.cross_entropy(logits, dst_types)
|
|
1059
|
+
|
|
1060
|
+
# Per-edge anomaly scores for score-gated memory
|
|
1061
|
+
if score_gated_memory:
|
|
1062
|
+
with torch.no_grad():
|
|
1063
|
+
edge_scores = F.cross_entropy(
|
|
1064
|
+
logits, dst_types, reduction="none")
|
|
1065
|
+
else:
|
|
1066
|
+
edge_scores = None
|
|
1067
|
+
|
|
1068
|
+
else:
|
|
1069
|
+
# ── Contrastive: benign vs negatives ──
|
|
1070
|
+
logits_benign = model.classify_edges(src_idx, dst_idx, etypes, ts,
|
|
1071
|
+
event_src_emb=batch_event_src, event_dst_emb=batch_event_dst)
|
|
1072
|
+
labels_benign = torch.zeros(len(batch_edges), 1, device=device)
|
|
1073
|
+
|
|
1074
|
+
# Tier 1: same-type negative (label=1)
|
|
1075
|
+
neg_same_strs = [
|
|
1076
|
+
neg_map_same.get((e[0], e[1], e[2]), random.choice(all_node_keys))
|
|
1077
|
+
for e in batch_edges
|
|
1078
|
+
]
|
|
1079
|
+
neg_same_idx = torch.tensor(
|
|
1080
|
+
[node_to_idx.get(n, 0) for n in neg_same_strs], dtype=torch.long, device=device)
|
|
1081
|
+
logits_neg_same = model.classify_edges(src_idx, neg_same_idx, etypes, ts,
|
|
1082
|
+
event_src_emb=batch_event_src, event_dst_emb=batch_event_dst)
|
|
1083
|
+
|
|
1084
|
+
# Tier 2: cross-type negative (label=1)
|
|
1085
|
+
neg_cross_strs = [
|
|
1086
|
+
neg_map_cross.get((e[0], e[1], e[2]), random.choice(all_node_keys))
|
|
1087
|
+
for e in batch_edges
|
|
1088
|
+
]
|
|
1089
|
+
neg_cross_idx = torch.tensor(
|
|
1090
|
+
[node_to_idx.get(n, 0) for n in neg_cross_strs], dtype=torch.long, device=device)
|
|
1091
|
+
logits_neg_cross = model.classify_edges(src_idx, neg_cross_idx, etypes, ts,
|
|
1092
|
+
event_src_emb=batch_event_src, event_dst_emb=batch_event_dst)
|
|
1093
|
+
|
|
1094
|
+
labels_neg = torch.ones(len(batch_edges) * 2, 1, device=device)
|
|
1095
|
+
|
|
1096
|
+
loss = torch.nn.BCEWithLogitsLoss()(
|
|
1097
|
+
torch.cat([logits_benign, logits_neg_same, logits_neg_cross], dim=0),
|
|
1098
|
+
torch.cat([labels_benign, labels_neg], dim=0),
|
|
1099
|
+
)
|
|
1100
|
+
# Per-edge anomaly scores for score-gated memory (detached)
|
|
1101
|
+
if score_gated_memory:
|
|
1102
|
+
with torch.no_grad():
|
|
1103
|
+
edge_scores = logits_benign.squeeze(-1).clone()
|
|
1104
|
+
else:
|
|
1105
|
+
edge_scores = None
|
|
1106
|
+
|
|
1107
|
+
loss.backward()
|
|
1108
|
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
|
1109
|
+
opt.step()
|
|
1110
|
+
opt.zero_grad()
|
|
1111
|
+
scheduler.step()
|
|
1112
|
+
|
|
1113
|
+
# ── Sync differentiable memory to buffer, then update ──
|
|
1114
|
+
# detach_memory() breaks the graph from the previous batch (truncated
|
|
1115
|
+
# BPTT depth 1), then update_memory() creates a fresh _diff_memory
|
|
1116
|
+
# overlay that the NEXT batch's predict/classify will read from.
|
|
1117
|
+
model.detach_memory()
|
|
1118
|
+
model.update_memory(src_idx, dst_idx, etypes, ts, edge_scores=edge_scores)
|
|
1119
|
+
|
|
1120
|
+
epoch_loss += loss.item()
|
|
1121
|
+
n_batches += 1
|
|
1122
|
+
updates += 1
|
|
1123
|
+
|
|
1124
|
+
if updates % 50 == 0:
|
|
1125
|
+
lr = scheduler.get_last_lr()[0]
|
|
1126
|
+
log(f"[e{epoch+1}|u{updates}] loss={loss.item():.4f} lr={lr:.2e}")
|
|
1127
|
+
|
|
1128
|
+
avg_loss = epoch_loss / max(1, n_batches)
|
|
1129
|
+
elapsed = time.time() - st
|
|
1130
|
+
log(f"Epoch {epoch+1}/{finetune_epochs}: avg_loss={avg_loss:.4f} ({elapsed:.1f}s)")
|
|
1131
|
+
|
|
1132
|
+
with open(log_path, "a") as f:
|
|
1133
|
+
f.write(f"{epoch+1},{updates},{avg_loss:.6f},{scheduler.get_last_lr()[0]:.2e}\n")
|
|
1134
|
+
|
|
1135
|
+
# ── Save checkpoint ────────────────────────────────────────
|
|
1136
|
+
ckpt = {
|
|
1137
|
+
"model_state_dict": model.state_dict(),
|
|
1138
|
+
"memory_state": model.get_memory_state(),
|
|
1139
|
+
"node_to_idx": node_to_idx,
|
|
1140
|
+
"edge_type_to_id": edge_type_to_id,
|
|
1141
|
+
"num_nodes": num_nodes,
|
|
1142
|
+
"num_edge_types": num_edge_types,
|
|
1143
|
+
"tgn_config": {
|
|
1144
|
+
"memory_dim": memory_dim,
|
|
1145
|
+
"edge_emb_dim": edge_emb_dim,
|
|
1146
|
+
"time_dim": time_dim,
|
|
1147
|
+
"entity_emb_dim": H,
|
|
1148
|
+
"num_heads": num_heads,
|
|
1149
|
+
"use_node_type_emb": use_node_type_emb,
|
|
1150
|
+
"use_time_emb": use_time_emb,
|
|
1151
|
+
"use_memory": use_memory,
|
|
1152
|
+
"use_entity_emb": use_entity_emb,
|
|
1153
|
+
"score_gated_memory": score_gated_memory,
|
|
1154
|
+
"temporal_decay": temporal_decay,
|
|
1155
|
+
"anomaly_accumulator": anomaly_accumulator,
|
|
1156
|
+
"objective": objective,
|
|
1157
|
+
"use_event_bert_emb": use_event_bert_emb,
|
|
1158
|
+
"event_bert_emb_dim": event_bert_emb_dim,
|
|
1159
|
+
},
|
|
1160
|
+
}
|
|
1161
|
+
save_path = os.path.join(ft_dir, f"finetune_tgn_{model_size}.pt")
|
|
1162
|
+
torch.save(ckpt, save_path)
|
|
1163
|
+
|
|
1164
|
+
if avg_loss < best_loss:
|
|
1165
|
+
best_loss = avg_loss
|
|
1166
|
+
best_path = os.path.join(ft_dir, f"finetune_tgn_{model_size}_best.pt")
|
|
1167
|
+
torch.save(ckpt, best_path)
|
|
1168
|
+
|
|
1169
|
+
log(f"TGN fine-tuning complete. Best loss: {best_loss:.4f}")
|
|
1170
|
+
|
|
1171
|
+
|
|
1172
|
+
def main(cfg):
|
|
1173
|
+
|
|
1174
|
+
pretrain_cfg = cfg.featurization.pretrained
|
|
1175
|
+
detect_cfg = cfg.training.pretrained
|
|
1176
|
+
model_type = pretrain_cfg.model_type
|
|
1177
|
+
model_size = pretrain_cfg.model_size
|
|
1178
|
+
finetune_mode = detect_cfg.finetune_mode
|
|
1179
|
+
|
|
1180
|
+
# TGN uses a completely different pipeline (no walks, no BERT sequence classification)
|
|
1181
|
+
if finetune_mode == "tgn":
|
|
1182
|
+
_train_tgn(cfg)
|
|
1183
|
+
return
|
|
1184
|
+
|
|
1185
|
+
if finetune_mode == "edge_cls":
|
|
1186
|
+
_train_edge_cls(cfg)
|
|
1187
|
+
return
|
|
1188
|
+
|
|
1189
|
+
if finetune_mode == "perplexity":
|
|
1190
|
+
log("Perplexity mode: no fine-tuning needed (pretrained model used directly)")
|
|
1191
|
+
return
|
|
1192
|
+
|
|
1193
|
+
finetune_epochs = detect_cfg.finetune_epochs
|
|
1194
|
+
finetune_walk_len = detect_cfg.finetune_walk_len
|
|
1195
|
+
finetune_lr = detect_cfg.finetune_lr
|
|
1196
|
+
finetune_margin = detect_cfg.finetune_margin
|
|
1197
|
+
freeze_backbone = detect_cfg.freeze_backbone
|
|
1198
|
+
if finetune_mode == "lp" and freeze_backbone:
|
|
1199
|
+
freeze_backbone = False # LP has no extra parameters; must train the backbone
|
|
1200
|
+
batch_size = pretrain_cfg.training.batch_size
|
|
1201
|
+
num_walks = detect_cfg.num_inference_walks
|
|
1202
|
+
time_weight = pretrain_cfg.walks.time_weight
|
|
1203
|
+
half_life = pretrain_cfg.walks.half_life
|
|
1204
|
+
scheduler_type = pretrain_cfg.training.scheduler
|
|
1205
|
+
|
|
1206
|
+
device = "cuda" if torch.cuda.is_available() and not cfg._use_cpu else "cpu"
|
|
1207
|
+
|
|
1208
|
+
# ── Directories ────────────────────────────────────────────────────
|
|
1209
|
+
pretrain_dir = cfg.featurization._model_dir
|
|
1210
|
+
ft_dir = cfg.training._trained_models_dir
|
|
1211
|
+
os.makedirs(ft_dir, exist_ok=True)
|
|
1212
|
+
|
|
1213
|
+
# ── Load tokenizer ──────────────────────────────────────────────────
|
|
1214
|
+
tokenizer = ProvenanceTokenizer(cfg)
|
|
1215
|
+
tokenizer.load(os.path.join(pretrain_dir, "tokenizer.pt"))
|
|
1216
|
+
log(f"Loaded tokenizer (vocab_size={tokenizer.vocab_size})")
|
|
1217
|
+
|
|
1218
|
+
# ── Load pretrained model ───────────────────────────────────────────
|
|
1219
|
+
if model_type == "ropebert":
|
|
1220
|
+
rope_theta = getattr(pretrain_cfg, 'rope_theta', 10000.0)
|
|
1221
|
+
bert_config = get_ropebert_config(
|
|
1222
|
+
tokenizer.vocab_size, model_size, tokenizer.max_seq_len,
|
|
1223
|
+
rope_theta=rope_theta,
|
|
1224
|
+
)
|
|
1225
|
+
log(f"Using RoPEBERT architecture (theta={rope_theta})")
|
|
1226
|
+
elif model_type == "modernbert":
|
|
1227
|
+
bert_config = get_modernbert_config(
|
|
1228
|
+
tokenizer.vocab_size, model_size, tokenizer.max_seq_len,
|
|
1229
|
+
global_attn_every_n_layers=pretrain_cfg.global_attn_every_n_layers,
|
|
1230
|
+
local_attention_window=pretrain_cfg.local_attention_window,
|
|
1231
|
+
)
|
|
1232
|
+
log(f"Using ModernBERT architecture (global every {pretrain_cfg.global_attn_every_n_layers}, "
|
|
1233
|
+
f"window {pretrain_cfg.local_attention_window})")
|
|
1234
|
+
else:
|
|
1235
|
+
bert_config = get_bert_config(tokenizer.vocab_size, model_size, tokenizer.max_seq_len)
|
|
1236
|
+
log(f"Using traditional BERT architecture")
|
|
1237
|
+
|
|
1238
|
+
pretrained_path = os.path.join(pretrain_dir, f"pretrain_{model_size}.pt")
|
|
1239
|
+
|
|
1240
|
+
sd = torch.load(pretrained_path, weights_only=True, map_location="cpu")
|
|
1241
|
+
log(f"Loaded pretrained weights from {pretrained_path}")
|
|
1242
|
+
|
|
1243
|
+
# cls_attack uses BCE (margin=0); cls uses the configured ranking margin
|
|
1244
|
+
cls_margin = 0 if finetune_mode == "cls_attack" else finetune_margin
|
|
1245
|
+
|
|
1246
|
+
if model_type == "ropebert":
|
|
1247
|
+
if finetune_mode in ("cls", "cls_attack"):
|
|
1248
|
+
model = ProvenanceRoPEBERTFineTuneCLS(bert_config, sd, device=device, freeze_backbone=freeze_backbone, margin=cls_margin)
|
|
1249
|
+
elif finetune_mode == "lp":
|
|
1250
|
+
model = ProvenanceRoPEBERTFineTuneLP(bert_config, sd, device=device, freeze_backbone=freeze_backbone)
|
|
1251
|
+
else:
|
|
1252
|
+
raise ValueError(f"Unknown finetune mode: {finetune_mode}")
|
|
1253
|
+
elif model_type == "modernbert":
|
|
1254
|
+
if finetune_mode in ("cls", "cls_attack"):
|
|
1255
|
+
model = ProvenanceModernBERTFineTuneCLS(bert_config, sd, device=device, freeze_backbone=freeze_backbone, margin=cls_margin)
|
|
1256
|
+
elif finetune_mode == "lp":
|
|
1257
|
+
model = ProvenanceModernBERTFineTuneLP(bert_config, sd, device=device, freeze_backbone=freeze_backbone)
|
|
1258
|
+
else:
|
|
1259
|
+
raise ValueError(f"Unknown finetune mode: {finetune_mode}")
|
|
1260
|
+
else:
|
|
1261
|
+
if finetune_mode in ("cls", "cls_attack"):
|
|
1262
|
+
model = ProvenanceBERTFineTuneCLS(bert_config, sd, device=device, freeze_backbone=freeze_backbone, margin=cls_margin)
|
|
1263
|
+
elif finetune_mode == "lp":
|
|
1264
|
+
model = ProvenanceBERTFineTuneLP(bert_config, sd, device=device, freeze_backbone=freeze_backbone)
|
|
1265
|
+
else:
|
|
1266
|
+
raise ValueError(f"Unknown finetune mode: {finetune_mode}")
|
|
1267
|
+
|
|
1268
|
+
log(f"Fine-tuning {model_type} in {finetune_mode} mode (freeze={freeze_backbone})")
|
|
1269
|
+
|
|
1270
|
+
# ── Load data ───────────────────────────────────────────────────────
|
|
1271
|
+
indexid2msg = get_indexid2msg(cfg)
|
|
1272
|
+
base_dir = cfg.transformation._graphs_dir
|
|
1273
|
+
train_graph_paths = get_all_graphs_for_dates(base_dir, cfg.dataset.train_dates)
|
|
1274
|
+
|
|
1275
|
+
log(f"Loading training graphs...")
|
|
1276
|
+
train_graphs = [torch.load(p) for p in train_graph_paths]
|
|
1277
|
+
train_samplers = [
|
|
1278
|
+
ProvenanceWalkSampler(g, walk_length=finetune_walk_len, num_walks=num_walks, time_weight=time_weight, half_life=half_life)
|
|
1279
|
+
for g in train_graphs
|
|
1280
|
+
]
|
|
1281
|
+
|
|
1282
|
+
# Collect all training edges
|
|
1283
|
+
train_edges = []
|
|
1284
|
+
for g in train_graphs:
|
|
1285
|
+
train_edges.extend(_collect_edges(g))
|
|
1286
|
+
log(f"Training edges: {len(train_edges)}")
|
|
1287
|
+
|
|
1288
|
+
# ── Negative sampling pre-computation (cls mode only) ───────────────
|
|
1289
|
+
# Build once before training. Groups nodes by (type, label) so each
|
|
1290
|
+
# negative has the same node type as dst but a different textual label
|
|
1291
|
+
# (different tokens). Also checks against the real edge set so we never
|
|
1292
|
+
# use an edge that already exists in the training graphs.
|
|
1293
|
+
train_neg_map = None
|
|
1294
|
+
if finetune_mode == "cls":
|
|
1295
|
+
type_to_labeled = _build_neg_index(indexid2msg)
|
|
1296
|
+
real_edge_set: set = set()
|
|
1297
|
+
for g in train_graphs:
|
|
1298
|
+
for src, dst, _, attrs in g.edges(data=True, keys=True):
|
|
1299
|
+
real_edge_set.add((str(src), str(dst), attrs.get("label", "")))
|
|
1300
|
+
train_neg_map = _precompute_negatives(
|
|
1301
|
+
train_edges, indexid2msg, type_to_labeled, real_edge_set
|
|
1302
|
+
)
|
|
1303
|
+
log(f"Pre-computed negatives for {len(train_neg_map)} unique train edge triples")
|
|
1304
|
+
|
|
1305
|
+
# ── Attack walk corpus (cls_attack mode only) ────────────────────────
|
|
1306
|
+
attack_walks = None
|
|
1307
|
+
if finetune_mode == "cls_attack":
|
|
1308
|
+
num_attack_walks = detect_cfg.num_attack_walks
|
|
1309
|
+
# Curated file (hand-validated, node-filtered) takes priority when present
|
|
1310
|
+
curated_path = os.path.join(ft_dir, "attack_walks_curated.pkl")
|
|
1311
|
+
attack_walks_path = os.path.join(ft_dir, "attack_walks.pkl")
|
|
1312
|
+
if os.path.exists(curated_path):
|
|
1313
|
+
attack_walks = _load_attack_walks(curated_path)
|
|
1314
|
+
log("Using curated attack walks (hand-filtered)")
|
|
1315
|
+
elif os.path.exists(attack_walks_path):
|
|
1316
|
+
attack_walks = _load_attack_walks(attack_walks_path)
|
|
1317
|
+
# Re-extract if cached file has old 4-tuple format (need 6-tuple with dst walks)
|
|
1318
|
+
if attack_walks and len(attack_walks[0]) != 6:
|
|
1319
|
+
log("Stale cache (4-tuple format), re-extracting with dst walks...")
|
|
1320
|
+
attack_walks = None
|
|
1321
|
+
if attack_walks is None and not os.path.exists(curated_path):
|
|
1322
|
+
log("Extracting attack walks from val/test graphs...")
|
|
1323
|
+
attack_walks = _extract_attack_walks(
|
|
1324
|
+
cfg, finetune_walk_len, time_weight, half_life, num_attack_walks,
|
|
1325
|
+
)
|
|
1326
|
+
_save_attack_walks(attack_walks, attack_walks_path)
|
|
1327
|
+
log(f"Attack walk corpus: {len(attack_walks)} sequences")
|
|
1328
|
+
if not attack_walks:
|
|
1329
|
+
raise ValueError(
|
|
1330
|
+
"No attack walks found — check ground_truth_relative_path and "
|
|
1331
|
+
"attack_to_time_window in the dataset config"
|
|
1332
|
+
)
|
|
1333
|
+
|
|
1334
|
+
# ── Optimizer ───────────────────────────────────────────────────────
|
|
1335
|
+
opt = AdamW(
|
|
1336
|
+
filter(lambda p: p.requires_grad, model.parameters()),
|
|
1337
|
+
lr=finetune_lr,
|
|
1338
|
+
betas=(0.9, 0.99),
|
|
1339
|
+
eps=1e-10,
|
|
1340
|
+
weight_decay=0.02,
|
|
1341
|
+
)
|
|
1342
|
+
updates_per_epoch = len(train_edges) // batch_size
|
|
1343
|
+
total_steps = updates_per_epoch * finetune_epochs
|
|
1344
|
+
warmup_steps = max(1, total_steps // 20) # 5% warmup
|
|
1345
|
+
if scheduler_type == "cosine":
|
|
1346
|
+
scheduler = WarmupCosineScheduler(opt, warmup_steps, total_steps)
|
|
1347
|
+
else:
|
|
1348
|
+
scheduler = WarmupLinearScheduler(opt, warmup_steps, total_steps)
|
|
1349
|
+
|
|
1350
|
+
# ── Training loop ───────────────────────────────────────────────────
|
|
1351
|
+
log_path = os.path.join(ft_dir, f"finetune_{finetune_mode}_{model_size}_log.txt")
|
|
1352
|
+
with open(log_path, "w") as f:
|
|
1353
|
+
f.write("epoch,update,loss,lr\n")
|
|
1354
|
+
|
|
1355
|
+
best_val_loss = float("inf")
|
|
1356
|
+
updates = 0
|
|
1357
|
+
|
|
1358
|
+
for epoch in range(finetune_epochs):
|
|
1359
|
+
random.shuffle(train_edges)
|
|
1360
|
+
epoch_loss = 0
|
|
1361
|
+
n_batches = 0
|
|
1362
|
+
st = time.time()
|
|
1363
|
+
|
|
1364
|
+
for batch_start in range(0, len(train_edges), batch_size):
|
|
1365
|
+
batch_edges = train_edges[batch_start : batch_start + batch_size]
|
|
1366
|
+
|
|
1367
|
+
# Use sampler from first graph (or pick randomly)
|
|
1368
|
+
sampler = random.choice(train_samplers)
|
|
1369
|
+
|
|
1370
|
+
model.train()
|
|
1371
|
+
if finetune_mode == "cls":
|
|
1372
|
+
input_ids, attn_mask, tgt_mask, labels = _prepare_finetune_batch_cls(
|
|
1373
|
+
batch_edges, sampler, tokenizer, indexid2msg, finetune_walk_len,
|
|
1374
|
+
neg_map=train_neg_map,
|
|
1375
|
+
)
|
|
1376
|
+
loss = model(
|
|
1377
|
+
input_ids.to(device),
|
|
1378
|
+
attn_mask.to(device),
|
|
1379
|
+
tgt_mask.to(device),
|
|
1380
|
+
labels.to(device),
|
|
1381
|
+
)
|
|
1382
|
+
elif finetune_mode == "cls_attack":
|
|
1383
|
+
attack_batch = random.choices(attack_walks, k=len(batch_edges))
|
|
1384
|
+
input_ids, attn_mask, tgt_mask, labels = _prepare_finetune_batch_cls_attack(
|
|
1385
|
+
batch_edges, attack_batch, sampler, tokenizer, indexid2msg, finetune_walk_len,
|
|
1386
|
+
)
|
|
1387
|
+
loss = model(
|
|
1388
|
+
input_ids.to(device),
|
|
1389
|
+
attn_mask.to(device),
|
|
1390
|
+
tgt_mask.to(device),
|
|
1391
|
+
labels.to(device),
|
|
1392
|
+
)
|
|
1393
|
+
elif finetune_mode == "lp":
|
|
1394
|
+
input_ids, attn_mask, tgt_mask, tgt_ids = _prepare_finetune_batch_lp(
|
|
1395
|
+
batch_edges, sampler, tokenizer, indexid2msg, finetune_walk_len
|
|
1396
|
+
)
|
|
1397
|
+
loss = model(
|
|
1398
|
+
input_ids.to(device),
|
|
1399
|
+
attn_mask.to(device),
|
|
1400
|
+
tgt_mask.to(device),
|
|
1401
|
+
tgt_ids.to(device),
|
|
1402
|
+
)
|
|
1403
|
+
|
|
1404
|
+
loss.backward()
|
|
1405
|
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
|
1406
|
+
opt.step()
|
|
1407
|
+
opt.zero_grad()
|
|
1408
|
+
scheduler.step()
|
|
1409
|
+
|
|
1410
|
+
epoch_loss += loss.item()
|
|
1411
|
+
n_batches += 1
|
|
1412
|
+
updates += 1
|
|
1413
|
+
|
|
1414
|
+
if updates % 50 == 0:
|
|
1415
|
+
lr = scheduler.get_last_lr()[0]
|
|
1416
|
+
log(f"[e{epoch+1}|u{updates}] loss={loss.item():.4f} lr={lr:.2e}")
|
|
1417
|
+
|
|
1418
|
+
avg_loss = epoch_loss / max(1, n_batches)
|
|
1419
|
+
elapsed = time.time() - st
|
|
1420
|
+
log(f"Epoch {epoch+1}/{finetune_epochs}: avg_loss={avg_loss:.4f} ({elapsed:.1f}s)")
|
|
1421
|
+
|
|
1422
|
+
with open(log_path, "a") as f:
|
|
1423
|
+
f.write(f"{epoch+1},{updates},{avg_loss:.6f},{scheduler.get_last_lr()[0]:.2e}\n")
|
|
1424
|
+
|
|
1425
|
+
# Save checkpoint
|
|
1426
|
+
save_path = os.path.join(ft_dir, f"finetune_{finetune_mode}_{model_size}.pt")
|
|
1427
|
+
torch.save(model.state_dict(), save_path)
|
|
1428
|
+
|
|
1429
|
+
if avg_loss < best_val_loss:
|
|
1430
|
+
best_val_loss = avg_loss
|
|
1431
|
+
best_path = os.path.join(ft_dir, f"finetune_{finetune_mode}_{model_size}_best.pt")
|
|
1432
|
+
torch.save(model.state_dict(), best_path)
|
|
1433
|
+
|
|
1434
|
+
log(f"Fine-tuning complete. Best loss: {best_val_loss:.4f}")
|