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,1427 @@
|
|
|
1
|
+
"""
|
|
2
|
+
SPIDER detection: score val/test edges using the fine-tuned model.
|
|
3
|
+
|
|
4
|
+
Replaces GNN training+inference for SPIDER. Loads the fine-tuned CLS, LP,
|
|
5
|
+
or TGN model, scores all edges in val/test graphs, and writes per-edge anomaly
|
|
6
|
+
scores as CSVs in the format expected by node_evaluation.py.
|
|
7
|
+
|
|
8
|
+
CSV format: loss,srcnode,dstnode,time,edge_type
|
|
9
|
+
Directory: {edge_losses_dir}/{split}/model_epoch_0/{time_interval}.csv
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import multiprocessing as mp
|
|
13
|
+
import os
|
|
14
|
+
from typing import List, Optional, Tuple
|
|
15
|
+
|
|
16
|
+
import networkx as nx
|
|
17
|
+
import numpy as np
|
|
18
|
+
import pandas as pd
|
|
19
|
+
import torch
|
|
20
|
+
import torch.nn.functional as F
|
|
21
|
+
|
|
22
|
+
from pidsmaker.utils.dataset_utils import get_rel2id
|
|
23
|
+
from pidsmaker.utils.utils import (
|
|
24
|
+
get_all_graphs_for_dates,
|
|
25
|
+
get_indexid2msg,
|
|
26
|
+
log,
|
|
27
|
+
log_tqdm,
|
|
28
|
+
ns_time_to_datetime_US,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
from .finetune import _collect_edges
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _build_context_graph(graph_paths: List[str]) -> nx.MultiDiGraph:
|
|
35
|
+
"""Merge multiple snapshot graphs into one for use as sampler context."""
|
|
36
|
+
merged = nx.MultiDiGraph()
|
|
37
|
+
for path in graph_paths:
|
|
38
|
+
g = torch.load(path, weights_only=False)
|
|
39
|
+
merged.add_nodes_from(g.nodes(data=True))
|
|
40
|
+
merged.add_edges_from(g.edges(data=True, keys=True))
|
|
41
|
+
return merged
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _group_paths_by_day(paths: List[str]) -> dict:
|
|
45
|
+
"""Group graph file paths by their parent directory (= day folder)."""
|
|
46
|
+
from collections import defaultdict
|
|
47
|
+
groups = defaultdict(list)
|
|
48
|
+
for p in paths:
|
|
49
|
+
day_folder = os.path.basename(os.path.dirname(p))
|
|
50
|
+
groups[day_folder].append(p)
|
|
51
|
+
return groups
|
|
52
|
+
from .models.bert import (
|
|
53
|
+
ProvenanceBERTFineTuneCLS,
|
|
54
|
+
ProvenanceBERTFineTuneLP,
|
|
55
|
+
get_bert_config,
|
|
56
|
+
)
|
|
57
|
+
from .models.modernbert import (
|
|
58
|
+
ProvenanceModernBERTFineTuneCLS,
|
|
59
|
+
ProvenanceModernBERTFineTuneLP,
|
|
60
|
+
get_modernbert_config,
|
|
61
|
+
)
|
|
62
|
+
from .models.ropebert import (
|
|
63
|
+
ProvenanceRoPEBERTFineTuneCLS,
|
|
64
|
+
ProvenanceRoPEBERTFineTuneLP,
|
|
65
|
+
get_ropebert_config,
|
|
66
|
+
)
|
|
67
|
+
from .data.sampler import ProvenanceWalkSampler
|
|
68
|
+
from .data.tokenizer_bpe import ProvenanceTokenizerBPE as ProvenanceTokenizer
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _load_finetuned_model(
|
|
72
|
+
pretrain_dir: str,
|
|
73
|
+
ft_dir: str,
|
|
74
|
+
tokenizer: ProvenanceTokenizer,
|
|
75
|
+
model_size: str,
|
|
76
|
+
model_type: str,
|
|
77
|
+
finetune_mode: str,
|
|
78
|
+
freeze_backbone: bool,
|
|
79
|
+
device: str,
|
|
80
|
+
pretrain_cfg=None,
|
|
81
|
+
):
|
|
82
|
+
"""Load the fine-tuned CLS or LP model, falling back to pretrained weights."""
|
|
83
|
+
if model_type == "ropebert":
|
|
84
|
+
rope_theta = pretrain_cfg.rope_theta
|
|
85
|
+
bert_config = get_ropebert_config(
|
|
86
|
+
tokenizer.vocab_size, model_size, tokenizer.max_seq_len,
|
|
87
|
+
rope_theta=rope_theta,
|
|
88
|
+
)
|
|
89
|
+
elif model_type == "modernbert":
|
|
90
|
+
bert_config = get_modernbert_config(
|
|
91
|
+
tokenizer.vocab_size, model_size, tokenizer.max_seq_len,
|
|
92
|
+
global_attn_every_n_layers=pretrain_cfg.global_attn_every_n_layers,
|
|
93
|
+
local_attention_window=pretrain_cfg.local_attention_window,
|
|
94
|
+
)
|
|
95
|
+
else:
|
|
96
|
+
bert_config = get_bert_config(tokenizer.vocab_size, model_size, tokenizer.max_seq_len)
|
|
97
|
+
|
|
98
|
+
# Try fine-tuned checkpoints first (in ft_dir), then pretrained (in pretrain_dir)
|
|
99
|
+
ft_best = os.path.join(ft_dir, f"finetune_{finetune_mode}_{model_size}_best.pt")
|
|
100
|
+
ft_last = os.path.join(ft_dir, f"finetune_{finetune_mode}_{model_size}.pt")
|
|
101
|
+
pt_last = os.path.join(pretrain_dir, f"pretrain_{model_size}.pt")
|
|
102
|
+
|
|
103
|
+
checkpoint_path = None
|
|
104
|
+
is_finetuned = False
|
|
105
|
+
for path in [ft_best, ft_last]:
|
|
106
|
+
if os.path.exists(path):
|
|
107
|
+
checkpoint_path = path
|
|
108
|
+
is_finetuned = True
|
|
109
|
+
break
|
|
110
|
+
|
|
111
|
+
if checkpoint_path is None:
|
|
112
|
+
if os.path.exists(pt_last):
|
|
113
|
+
checkpoint_path = pt_last
|
|
114
|
+
|
|
115
|
+
if checkpoint_path is None:
|
|
116
|
+
raise FileNotFoundError(
|
|
117
|
+
f"No checkpoint found in {ft_dir} or {pretrain_dir}"
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
log(f"Loading {model_type} checkpoint from {checkpoint_path}")
|
|
121
|
+
|
|
122
|
+
if is_finetuned:
|
|
123
|
+
# Fine-tuned: load full state dict into the fine-tune wrapper
|
|
124
|
+
sd = torch.load(checkpoint_path, weights_only=True, map_location="cpu")
|
|
125
|
+
|
|
126
|
+
# Extract backbone weights (strip 'fm.' prefix)
|
|
127
|
+
backbone_sd = {}
|
|
128
|
+
for k, v in sd.items():
|
|
129
|
+
if k.startswith("fm."):
|
|
130
|
+
backbone_sd[k[len("fm."):]] = v
|
|
131
|
+
|
|
132
|
+
if model_type == "ropebert":
|
|
133
|
+
if finetune_mode in ("cls", "cls_attack"):
|
|
134
|
+
model = ProvenanceRoPEBERTFineTuneCLS(
|
|
135
|
+
bert_config, backbone_sd or None, device=device, freeze_backbone=freeze_backbone,
|
|
136
|
+
)
|
|
137
|
+
else:
|
|
138
|
+
model = ProvenanceRoPEBERTFineTuneLP(
|
|
139
|
+
bert_config, backbone_sd or None, device=device, freeze_backbone=freeze_backbone,
|
|
140
|
+
)
|
|
141
|
+
elif model_type == "modernbert":
|
|
142
|
+
if finetune_mode in ("cls", "cls_attack"):
|
|
143
|
+
model = ProvenanceModernBERTFineTuneCLS(
|
|
144
|
+
bert_config, backbone_sd or None, device=device, freeze_backbone=freeze_backbone,
|
|
145
|
+
)
|
|
146
|
+
else:
|
|
147
|
+
model = ProvenanceModernBERTFineTuneLP(
|
|
148
|
+
bert_config, backbone_sd or None, device=device, freeze_backbone=freeze_backbone,
|
|
149
|
+
)
|
|
150
|
+
else:
|
|
151
|
+
if finetune_mode in ("cls", "cls_attack"):
|
|
152
|
+
model = ProvenanceBERTFineTuneCLS(
|
|
153
|
+
bert_config, backbone_sd or None, device=device, freeze_backbone=freeze_backbone,
|
|
154
|
+
)
|
|
155
|
+
else:
|
|
156
|
+
model = ProvenanceBERTFineTuneLP(
|
|
157
|
+
bert_config, backbone_sd or None, device=device, freeze_backbone=freeze_backbone,
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
# Load the full state dict (including classifier/head weights)
|
|
161
|
+
model.load_state_dict(sd)
|
|
162
|
+
else:
|
|
163
|
+
# Pretrained only: load backbone into fine-tune wrapper
|
|
164
|
+
sd = torch.load(checkpoint_path, weights_only=True, map_location="cpu")
|
|
165
|
+
if model_type == "ropebert":
|
|
166
|
+
if finetune_mode in ("cls", "cls_attack"):
|
|
167
|
+
model = ProvenanceRoPEBERTFineTuneCLS(
|
|
168
|
+
bert_config, sd, device=device, freeze_backbone=freeze_backbone,
|
|
169
|
+
)
|
|
170
|
+
else:
|
|
171
|
+
model = ProvenanceRoPEBERTFineTuneLP(
|
|
172
|
+
bert_config, sd, device=device, freeze_backbone=freeze_backbone,
|
|
173
|
+
)
|
|
174
|
+
elif model_type == "modernbert":
|
|
175
|
+
if finetune_mode in ("cls", "cls_attack"):
|
|
176
|
+
model = ProvenanceModernBERTFineTuneCLS(
|
|
177
|
+
bert_config, sd, device=device, freeze_backbone=freeze_backbone,
|
|
178
|
+
)
|
|
179
|
+
else:
|
|
180
|
+
model = ProvenanceModernBERTFineTuneLP(
|
|
181
|
+
bert_config, sd, device=device, freeze_backbone=freeze_backbone,
|
|
182
|
+
)
|
|
183
|
+
else:
|
|
184
|
+
if finetune_mode in ("cls", "cls_attack"):
|
|
185
|
+
model = ProvenanceBERTFineTuneCLS(
|
|
186
|
+
bert_config, sd, device=device, freeze_backbone=freeze_backbone,
|
|
187
|
+
)
|
|
188
|
+
else:
|
|
189
|
+
model = ProvenanceBERTFineTuneLP(
|
|
190
|
+
bert_config, sd, device=device, freeze_backbone=freeze_backbone,
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
model.eval()
|
|
194
|
+
return model
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _load_pretrained_model(
|
|
198
|
+
pretrain_dir: str,
|
|
199
|
+
tokenizer: ProvenanceTokenizer,
|
|
200
|
+
model_size: str,
|
|
201
|
+
device: str,
|
|
202
|
+
model_type: str = "bert",
|
|
203
|
+
pretrain_cfg=None,
|
|
204
|
+
):
|
|
205
|
+
"""Load the pretrained model wrapped in LP for scoring (no fine-tuning)."""
|
|
206
|
+
if model_type == "ropebert":
|
|
207
|
+
rope_theta = pretrain_cfg.rope_theta
|
|
208
|
+
bert_config = get_ropebert_config(
|
|
209
|
+
tokenizer.vocab_size, model_size, tokenizer.max_seq_len,
|
|
210
|
+
rope_theta=rope_theta,
|
|
211
|
+
)
|
|
212
|
+
elif model_type == "modernbert":
|
|
213
|
+
bert_config = get_modernbert_config(
|
|
214
|
+
tokenizer.vocab_size, model_size, tokenizer.max_seq_len,
|
|
215
|
+
global_attn_every_n_layers=pretrain_cfg.global_attn_every_n_layers,
|
|
216
|
+
local_attention_window=pretrain_cfg.local_attention_window,
|
|
217
|
+
)
|
|
218
|
+
else:
|
|
219
|
+
bert_config = get_bert_config(tokenizer.vocab_size, model_size, tokenizer.max_seq_len)
|
|
220
|
+
|
|
221
|
+
pt_last = os.path.join(pretrain_dir, f"pretrain_{model_size}.pt")
|
|
222
|
+
|
|
223
|
+
if not os.path.exists(pt_last):
|
|
224
|
+
raise FileNotFoundError(f"No pretrained checkpoint found in {pretrain_dir}")
|
|
225
|
+
checkpoint_path = pt_last
|
|
226
|
+
|
|
227
|
+
log(f"Loading {model_type} pretrained checkpoint from {checkpoint_path}")
|
|
228
|
+
sd = torch.load(checkpoint_path, weights_only=True, map_location="cpu")
|
|
229
|
+
if model_type == "ropebert":
|
|
230
|
+
model = ProvenanceRoPEBERTFineTuneLP(bert_config, sd, device=device)
|
|
231
|
+
elif model_type == "modernbert":
|
|
232
|
+
model = ProvenanceModernBERTFineTuneLP(bert_config, sd, device=device)
|
|
233
|
+
else:
|
|
234
|
+
model = ProvenanceBERTFineTuneLP(bert_config, sd, device=device)
|
|
235
|
+
model.eval()
|
|
236
|
+
return model
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _prepare_score_batch_cls(
|
|
241
|
+
edges: List[Tuple[str, str, str, float]],
|
|
242
|
+
sampler: ProvenanceWalkSampler,
|
|
243
|
+
tokenizer: ProvenanceTokenizer,
|
|
244
|
+
indexid2msg: dict,
|
|
245
|
+
walk_length: int,
|
|
246
|
+
):
|
|
247
|
+
"""Prepare a batch for CLS scoring (no negative sampling).
|
|
248
|
+
|
|
249
|
+
Returns:
|
|
250
|
+
input_ids: [B, L]
|
|
251
|
+
attention_mask: [B, L]
|
|
252
|
+
target_mask: [B, L]
|
|
253
|
+
"""
|
|
254
|
+
batch_input_ids = []
|
|
255
|
+
batch_attn = []
|
|
256
|
+
batch_target = []
|
|
257
|
+
|
|
258
|
+
for src, dst, etype, ts in edges:
|
|
259
|
+
walk_nodes, walk_edge_types = sampler.sample_bidirectional_walk(
|
|
260
|
+
src, max_ts=ts, walk_length=walk_length,
|
|
261
|
+
)
|
|
262
|
+
dst_walk_nodes, dst_walk_edge_types = sampler.sample_context_walk(
|
|
263
|
+
dst, max_ts=ts, walk_length=walk_length,
|
|
264
|
+
)
|
|
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
|
+
|
|
273
|
+
# Pad to max length
|
|
274
|
+
max_len = max(t.size(0) for t in batch_input_ids)
|
|
275
|
+
pad_id = tokenizer.pad_id
|
|
276
|
+
B = len(batch_input_ids)
|
|
277
|
+
|
|
278
|
+
input_ids = torch.full((B, max_len), pad_id, dtype=torch.long)
|
|
279
|
+
attention_mask = torch.zeros(B, max_len, dtype=torch.bool)
|
|
280
|
+
target_mask = torch.zeros(B, max_len, dtype=torch.bool)
|
|
281
|
+
|
|
282
|
+
for i in range(B):
|
|
283
|
+
L = batch_input_ids[i].size(0)
|
|
284
|
+
input_ids[i, :L] = batch_input_ids[i]
|
|
285
|
+
attention_mask[i, :L] = batch_attn[i]
|
|
286
|
+
target_mask[i, :L] = batch_target[i]
|
|
287
|
+
|
|
288
|
+
return input_ids, attention_mask, target_mask
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _prepare_score_batch_lp(
|
|
292
|
+
edges: List[Tuple[str, str, str, float]],
|
|
293
|
+
sampler: ProvenanceWalkSampler,
|
|
294
|
+
tokenizer: ProvenanceTokenizer,
|
|
295
|
+
indexid2msg: dict,
|
|
296
|
+
walk_length: int,
|
|
297
|
+
):
|
|
298
|
+
"""Prepare a batch for LP scoring (masked destination prediction).
|
|
299
|
+
|
|
300
|
+
Returns:
|
|
301
|
+
input_ids: [B, L]
|
|
302
|
+
attention_mask: [B, L]
|
|
303
|
+
target_mask: [B, L]
|
|
304
|
+
target_token_ids: [B, L]
|
|
305
|
+
"""
|
|
306
|
+
batch_input_ids = []
|
|
307
|
+
batch_attn = []
|
|
308
|
+
batch_target_mask = []
|
|
309
|
+
batch_target_ids = []
|
|
310
|
+
|
|
311
|
+
for src, dst, etype, ts in edges:
|
|
312
|
+
walk_nodes, walk_edge_types = sampler.sample_bidirectional_walk(
|
|
313
|
+
src, max_ts=ts, walk_length=walk_length,
|
|
314
|
+
)
|
|
315
|
+
|
|
316
|
+
# Get masked version
|
|
317
|
+
tok_ids_masked, attn_masked, tgt_mask = tokenizer.tokenize_for_finetune(
|
|
318
|
+
walk_nodes, walk_edge_types, dst, etype, indexid2msg, mode="lp",
|
|
319
|
+
)
|
|
320
|
+
|
|
321
|
+
# Build target: true token IDs where masked, -100 elsewhere
|
|
322
|
+
target_ids = torch.full_like(tok_ids_masked, -100)
|
|
323
|
+
mask_positions = tgt_mask.nonzero(as_tuple=True)[0]
|
|
324
|
+
|
|
325
|
+
if dst in indexid2msg:
|
|
326
|
+
dst_type, dst_label = indexid2msg[dst]
|
|
327
|
+
dst_tokens = tokenizer.tokenize_node(dst_type, dst_label)
|
|
328
|
+
for j, pos in enumerate(mask_positions):
|
|
329
|
+
if j < len(dst_tokens):
|
|
330
|
+
target_ids[pos] = dst_tokens[j]
|
|
331
|
+
|
|
332
|
+
batch_input_ids.append(tok_ids_masked)
|
|
333
|
+
batch_attn.append(attn_masked)
|
|
334
|
+
batch_target_mask.append(tgt_mask)
|
|
335
|
+
batch_target_ids.append(target_ids)
|
|
336
|
+
|
|
337
|
+
# Pad
|
|
338
|
+
max_len = max(t.size(0) for t in batch_input_ids)
|
|
339
|
+
pad_id = tokenizer.pad_id
|
|
340
|
+
B = len(batch_input_ids)
|
|
341
|
+
|
|
342
|
+
input_ids = torch.full((B, max_len), pad_id, dtype=torch.long)
|
|
343
|
+
attention_mask = torch.zeros(B, max_len, dtype=torch.bool)
|
|
344
|
+
target_mask = torch.zeros(B, max_len, dtype=torch.bool)
|
|
345
|
+
target_token_ids = torch.full((B, max_len), -100, dtype=torch.long)
|
|
346
|
+
|
|
347
|
+
for i in range(B):
|
|
348
|
+
L = batch_input_ids[i].size(0)
|
|
349
|
+
input_ids[i, :L] = batch_input_ids[i]
|
|
350
|
+
attention_mask[i, :L] = batch_attn[i]
|
|
351
|
+
target_mask[i, :L] = batch_target_mask[i]
|
|
352
|
+
target_token_ids[i, :L] = batch_target_ids[i]
|
|
353
|
+
|
|
354
|
+
return input_ids, attention_mask, target_mask, target_token_ids
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
# ── Parallel walk sampling ──────────────────────────────────────────────────
|
|
358
|
+
|
|
359
|
+
# Module-level globals inherited by forked worker processes (read-only, COW).
|
|
360
|
+
_mp_sampler: Optional[ProvenanceWalkSampler] = None
|
|
361
|
+
_mp_walk_length: int = 10
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def _walk_worker(edge_chunk: List[Tuple[str, str, str, float]]) -> list:
|
|
365
|
+
"""Sample src + dst walks for a chunk of edges (runs in forked child)."""
|
|
366
|
+
results = []
|
|
367
|
+
for src, dst, etype, ts in edge_chunk:
|
|
368
|
+
src_wn, src_we = _mp_sampler.sample_bidirectional_walk(
|
|
369
|
+
src, max_ts=ts, walk_length=_mp_walk_length,
|
|
370
|
+
)
|
|
371
|
+
dst_wn, dst_we = _mp_sampler.sample_context_walk(
|
|
372
|
+
dst, max_ts=ts, walk_length=_mp_walk_length,
|
|
373
|
+
)
|
|
374
|
+
results.append((src_wn, src_we, dst_wn, dst_we))
|
|
375
|
+
return results
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def _parallel_sample_walks(
|
|
379
|
+
edges: List[Tuple[str, str, str, float]],
|
|
380
|
+
sampler: ProvenanceWalkSampler,
|
|
381
|
+
walk_length: int,
|
|
382
|
+
num_workers: Optional[int] = None,
|
|
383
|
+
) -> list:
|
|
384
|
+
"""Pre-sample all walks using multiprocessing (fork, read-only COW)."""
|
|
385
|
+
global _mp_sampler, _mp_walk_length
|
|
386
|
+
_mp_sampler = sampler
|
|
387
|
+
_mp_walk_length = walk_length
|
|
388
|
+
|
|
389
|
+
if num_workers is None:
|
|
390
|
+
num_workers = min(mp.cpu_count(), 8)
|
|
391
|
+
|
|
392
|
+
# Fall back to sequential for small edge counts or single worker
|
|
393
|
+
if num_workers <= 1 or len(edges) < 2000:
|
|
394
|
+
return _walk_worker(edges)
|
|
395
|
+
|
|
396
|
+
chunk_size = max(1, (len(edges) + num_workers - 1) // num_workers)
|
|
397
|
+
chunks = [edges[i:i + chunk_size] for i in range(0, len(edges), chunk_size)]
|
|
398
|
+
|
|
399
|
+
ctx = mp.get_context("fork")
|
|
400
|
+
with ctx.Pool(num_workers) as pool:
|
|
401
|
+
result_chunks = pool.map(_walk_worker, chunks)
|
|
402
|
+
|
|
403
|
+
return [w for chunk in result_chunks for w in chunk]
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
@torch.no_grad()
|
|
407
|
+
def _score_edges_cls(
|
|
408
|
+
edges: List[Tuple[str, str, str, float]],
|
|
409
|
+
sampler: ProvenanceWalkSampler,
|
|
410
|
+
model: ProvenanceBERTFineTuneCLS,
|
|
411
|
+
tokenizer: ProvenanceTokenizer,
|
|
412
|
+
indexid2msg: dict,
|
|
413
|
+
walk_length: int,
|
|
414
|
+
batch_size: int,
|
|
415
|
+
device: str,
|
|
416
|
+
) -> List[float]:
|
|
417
|
+
"""Score edges using CLS mode: raw logit as anomaly score.
|
|
418
|
+
|
|
419
|
+
Walks are pre-sampled in parallel across CPU cores (fork-based
|
|
420
|
+
multiprocessing), then tokenized and scored in batched GPU passes.
|
|
421
|
+
"""
|
|
422
|
+
# Phase 1: parallel walk sampling on CPU
|
|
423
|
+
all_walks = _parallel_sample_walks(edges, sampler, walk_length)
|
|
424
|
+
|
|
425
|
+
# Phase 2: tokenize + GPU inference in batches
|
|
426
|
+
scores = []
|
|
427
|
+
for batch_start in range(0, len(edges), batch_size):
|
|
428
|
+
batch_edges = edges[batch_start:batch_start + batch_size]
|
|
429
|
+
batch_walks = all_walks[batch_start:batch_start + batch_size]
|
|
430
|
+
|
|
431
|
+
batch_input_ids = []
|
|
432
|
+
batch_attn = []
|
|
433
|
+
batch_target = []
|
|
434
|
+
for (src_wn, src_we, dst_wn, dst_we), (src, dst, etype, ts) in zip(batch_walks, batch_edges):
|
|
435
|
+
tok_ids, attn, tgt_mask = tokenizer.tokenize_for_finetune(
|
|
436
|
+
src_wn, src_we, dst, etype, indexid2msg, mode="cls",
|
|
437
|
+
dst_walk_nodes=dst_wn, dst_walk_edge_types=dst_we,
|
|
438
|
+
)
|
|
439
|
+
batch_input_ids.append(tok_ids)
|
|
440
|
+
batch_attn.append(attn)
|
|
441
|
+
batch_target.append(tgt_mask)
|
|
442
|
+
|
|
443
|
+
max_len = max(t.size(0) for t in batch_input_ids)
|
|
444
|
+
pad_id = tokenizer.pad_id
|
|
445
|
+
B = len(batch_input_ids)
|
|
446
|
+
input_ids = torch.full((B, max_len), pad_id, dtype=torch.long)
|
|
447
|
+
attention_mask = torch.zeros(B, max_len, dtype=torch.bool)
|
|
448
|
+
target_mask = torch.zeros(B, max_len, dtype=torch.bool)
|
|
449
|
+
for i in range(B):
|
|
450
|
+
L = batch_input_ids[i].size(0)
|
|
451
|
+
input_ids[i, :L] = batch_input_ids[i]
|
|
452
|
+
attention_mask[i, :L] = batch_attn[i]
|
|
453
|
+
target_mask[i, :L] = batch_target[i]
|
|
454
|
+
|
|
455
|
+
logits = model.predict(
|
|
456
|
+
input_ids.to(device),
|
|
457
|
+
attention_mask.to(device),
|
|
458
|
+
target_mask.to(device),
|
|
459
|
+
)
|
|
460
|
+
scores.extend(logits.squeeze(-1).cpu().numpy().tolist())
|
|
461
|
+
|
|
462
|
+
return scores
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
@torch.no_grad()
|
|
466
|
+
def _score_edges_lp(
|
|
467
|
+
edges: List[Tuple[str, str, str, float]],
|
|
468
|
+
sampler: ProvenanceWalkSampler,
|
|
469
|
+
model: ProvenanceBERTFineTuneLP,
|
|
470
|
+
tokenizer: ProvenanceTokenizer,
|
|
471
|
+
indexid2msg: dict,
|
|
472
|
+
walk_length: int,
|
|
473
|
+
batch_size: int,
|
|
474
|
+
device: str,
|
|
475
|
+
edge_score_weight: float = 0.0,
|
|
476
|
+
) -> List[float]:
|
|
477
|
+
"""Score edges: node CE + optional lambda * edge-type CE."""
|
|
478
|
+
scores = []
|
|
479
|
+
for batch_start in range(0, len(edges), batch_size):
|
|
480
|
+
batch_edges = edges[batch_start:batch_start + batch_size]
|
|
481
|
+
input_ids, attn_mask, tgt_mask, tgt_ids = _prepare_score_batch_lp(
|
|
482
|
+
batch_edges, sampler, tokenizer, indexid2msg, walk_length,
|
|
483
|
+
)
|
|
484
|
+
|
|
485
|
+
node_scores = model.anomaly_score(
|
|
486
|
+
input_ids.to(device),
|
|
487
|
+
attn_mask.to(device),
|
|
488
|
+
tgt_mask.to(device),
|
|
489
|
+
tgt_ids.to(device),
|
|
490
|
+
) # [B]
|
|
491
|
+
|
|
492
|
+
# Optional edge-type scoring
|
|
493
|
+
if edge_score_weight > 0:
|
|
494
|
+
e_input_ids, e_attn_mask, e_tgt_mask, e_tgt_ids = _prepare_score_batch_edge(
|
|
495
|
+
batch_edges, sampler, tokenizer, indexid2msg, walk_length,
|
|
496
|
+
)
|
|
497
|
+
e_scores = model.anomaly_score(
|
|
498
|
+
e_input_ids.to(device),
|
|
499
|
+
e_attn_mask.to(device),
|
|
500
|
+
e_tgt_mask.to(device),
|
|
501
|
+
e_tgt_ids.to(device),
|
|
502
|
+
)
|
|
503
|
+
node_scores = node_scores + edge_score_weight * e_scores
|
|
504
|
+
|
|
505
|
+
scores.extend(node_scores.cpu().numpy().tolist())
|
|
506
|
+
|
|
507
|
+
return scores
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
def _prepare_score_batch_edge(
|
|
511
|
+
edges: List[Tuple[str, str, str, float]],
|
|
512
|
+
sampler: ProvenanceWalkSampler,
|
|
513
|
+
tokenizer: ProvenanceTokenizer,
|
|
514
|
+
indexid2msg: dict,
|
|
515
|
+
walk_length: int,
|
|
516
|
+
):
|
|
517
|
+
"""Prepare batch with edge type masked, destination visible.
|
|
518
|
+
|
|
519
|
+
Returns:
|
|
520
|
+
input_ids: [B, L]
|
|
521
|
+
attention_mask: [B, L]
|
|
522
|
+
target_mask: [B, L]
|
|
523
|
+
target_token_ids: [B, L]
|
|
524
|
+
"""
|
|
525
|
+
batch_input_ids = []
|
|
526
|
+
batch_attn = []
|
|
527
|
+
batch_tgt_mask = []
|
|
528
|
+
batch_tgt_ids = []
|
|
529
|
+
|
|
530
|
+
for src, dst, etype, ts in edges:
|
|
531
|
+
walk_nodes, walk_edge_types = sampler.sample_bidirectional_walk(
|
|
532
|
+
src, max_ts=ts, walk_length=walk_length,
|
|
533
|
+
)
|
|
534
|
+
tok_ids, attn, edge_mask, edge_tgt = tokenizer.tokenize_for_edge_scoring(
|
|
535
|
+
walk_nodes, walk_edge_types, dst, etype, indexid2msg,
|
|
536
|
+
)
|
|
537
|
+
batch_input_ids.append(tok_ids)
|
|
538
|
+
batch_attn.append(attn)
|
|
539
|
+
batch_tgt_mask.append(edge_mask)
|
|
540
|
+
batch_tgt_ids.append(edge_tgt)
|
|
541
|
+
|
|
542
|
+
# Pad
|
|
543
|
+
max_len = max(t.size(0) for t in batch_input_ids)
|
|
544
|
+
pad_id = tokenizer.pad_id
|
|
545
|
+
B = len(batch_input_ids)
|
|
546
|
+
|
|
547
|
+
input_ids = torch.full((B, max_len), pad_id, dtype=torch.long)
|
|
548
|
+
attention_mask = torch.zeros(B, max_len, dtype=torch.bool)
|
|
549
|
+
target_mask = torch.zeros(B, max_len, dtype=torch.bool)
|
|
550
|
+
target_token_ids = torch.full((B, max_len), -100, dtype=torch.long)
|
|
551
|
+
|
|
552
|
+
for i in range(B):
|
|
553
|
+
L = batch_input_ids[i].size(0)
|
|
554
|
+
input_ids[i, :L] = batch_input_ids[i]
|
|
555
|
+
attention_mask[i, :L] = batch_attn[i]
|
|
556
|
+
target_mask[i, :L] = batch_tgt_mask[i]
|
|
557
|
+
target_token_ids[i, :L] = batch_tgt_ids[i]
|
|
558
|
+
|
|
559
|
+
return input_ids, attention_mask, target_mask, target_token_ids
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
def _score_graph(
|
|
565
|
+
graph,
|
|
566
|
+
model,
|
|
567
|
+
tokenizer: ProvenanceTokenizer,
|
|
568
|
+
indexid2msg: dict,
|
|
569
|
+
rel2id: dict,
|
|
570
|
+
finetune_mode: str,
|
|
571
|
+
walk_length: int,
|
|
572
|
+
batch_size: int,
|
|
573
|
+
time_weight: str,
|
|
574
|
+
half_life: float,
|
|
575
|
+
device: str,
|
|
576
|
+
num_walks: int = 1,
|
|
577
|
+
edge_score_weight: float = 2.0,
|
|
578
|
+
context_graph: Optional[nx.MultiDiGraph] = None,
|
|
579
|
+
prebuilt_sampler: Optional[ProvenanceWalkSampler] = None,
|
|
580
|
+
) -> pd.DataFrame:
|
|
581
|
+
"""Score all edges in a single graph and return a DataFrame.
|
|
582
|
+
|
|
583
|
+
prebuilt_sampler: if provided, reuse this sampler instead of constructing a
|
|
584
|
+
new one. Use this in day/all context modes to avoid rebuilding adjacency
|
|
585
|
+
lists (O(E)) for every snapshot graph.
|
|
586
|
+
context_graph: used only when prebuilt_sampler is None; builds a fresh
|
|
587
|
+
sampler from context_graph (or graph itself if context_graph is None).
|
|
588
|
+
"""
|
|
589
|
+
edges = _collect_edges(graph)
|
|
590
|
+
if not edges:
|
|
591
|
+
return pd.DataFrame(columns=["loss", "srcnode", "dstnode", "time", "edge_type"])
|
|
592
|
+
|
|
593
|
+
if prebuilt_sampler is not None:
|
|
594
|
+
sampler = prebuilt_sampler
|
|
595
|
+
else:
|
|
596
|
+
sampler = ProvenanceWalkSampler(
|
|
597
|
+
context_graph if context_graph is not None else graph,
|
|
598
|
+
walk_length=walk_length, num_walks=1,
|
|
599
|
+
time_weight=time_weight, half_life=half_life,
|
|
600
|
+
)
|
|
601
|
+
|
|
602
|
+
score_fn = {
|
|
603
|
+
"cls": _score_edges_cls,
|
|
604
|
+
"cls_attack": _score_edges_cls,
|
|
605
|
+
"lp": _score_edges_lp,
|
|
606
|
+
"mlm": _score_edges_lp,
|
|
607
|
+
}[finetune_mode]
|
|
608
|
+
|
|
609
|
+
common_args = (edges, sampler, model, tokenizer, indexid2msg,
|
|
610
|
+
walk_length, batch_size, device)
|
|
611
|
+
extra_args = (edge_score_weight,) if finetune_mode in ("lp", "mlm") else ()
|
|
612
|
+
|
|
613
|
+
if num_walks <= 1:
|
|
614
|
+
scores = score_fn(*common_args, *extra_args)
|
|
615
|
+
else:
|
|
616
|
+
# Average scores over multiple walks
|
|
617
|
+
all_scores = np.zeros(len(edges))
|
|
618
|
+
for _ in range(num_walks):
|
|
619
|
+
walk_scores = score_fn(*common_args, *extra_args)
|
|
620
|
+
all_scores += np.array(walk_scores)
|
|
621
|
+
scores = (all_scores / num_walks).tolist()
|
|
622
|
+
|
|
623
|
+
# Build DataFrame matching inference_loop.py format
|
|
624
|
+
rows = []
|
|
625
|
+
for (src, dst, etype, ts), score in zip(edges, scores):
|
|
626
|
+
edge_type_id = rel2id.get(etype, 0)
|
|
627
|
+
rows.append({
|
|
628
|
+
"loss": float(score),
|
|
629
|
+
"srcnode": int(src),
|
|
630
|
+
"dstnode": int(dst),
|
|
631
|
+
"time": int(ts),
|
|
632
|
+
"edge_type": int(edge_type_id),
|
|
633
|
+
})
|
|
634
|
+
|
|
635
|
+
return pd.DataFrame(rows)
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
# ── Edge classification detection ──────────────────────────────────────────────
|
|
639
|
+
|
|
640
|
+
def _detect_edge_cls(cfg):
|
|
641
|
+
"""Edge classification detection: score edges with static or event embeddings."""
|
|
642
|
+
|
|
643
|
+
from .models.tgn import EdgeTypeClassifier
|
|
644
|
+
|
|
645
|
+
pretrain_cfg = cfg.featurization.pretrained
|
|
646
|
+
detect_cfg = cfg.training.pretrained
|
|
647
|
+
model_size = pretrain_cfg.model_size
|
|
648
|
+
batch_size = detect_cfg.inference_batch_size
|
|
649
|
+
device = "cuda" if torch.cuda.is_available() and not cfg._use_cpu else "cpu"
|
|
650
|
+
|
|
651
|
+
ft_dir = cfg.training._trained_models_dir
|
|
652
|
+
edge_losses_dir = cfg.training._edge_losses_dir
|
|
653
|
+
|
|
654
|
+
# ── Run training first ────────────────────────────────────────
|
|
655
|
+
from .finetune import main as finetune_main
|
|
656
|
+
finetune_main(cfg)
|
|
657
|
+
|
|
658
|
+
# ── Load checkpoint ───────────────────────────────────────────
|
|
659
|
+
ckpt_path = os.path.join(ft_dir, f"finetune_edge_cls_{model_size}_best.pt")
|
|
660
|
+
if not os.path.exists(ckpt_path):
|
|
661
|
+
ckpt_path = os.path.join(ft_dir, f"finetune_edge_cls_{model_size}.pt")
|
|
662
|
+
if not os.path.exists(ckpt_path):
|
|
663
|
+
raise FileNotFoundError(f"No edge_cls checkpoint found in {ft_dir}")
|
|
664
|
+
|
|
665
|
+
ckpt = torch.load(ckpt_path, map_location="cpu")
|
|
666
|
+
ecfg = ckpt["edge_cls_config"]
|
|
667
|
+
node_to_idx = ckpt["node_to_idx"]
|
|
668
|
+
edge_type_to_id = ckpt["edge_type_to_id"]
|
|
669
|
+
|
|
670
|
+
model = EdgeTypeClassifier(
|
|
671
|
+
num_nodes=ckpt["num_nodes"],
|
|
672
|
+
num_edge_types=ckpt["num_edge_types"],
|
|
673
|
+
entity_emb_dim=ecfg["entity_emb_dim"],
|
|
674
|
+
hidden_dim=ecfg["hidden_dim"],
|
|
675
|
+
).to(device)
|
|
676
|
+
model.load_state_dict(ckpt["model_state_dict"])
|
|
677
|
+
model.eval()
|
|
678
|
+
log(f"EdgeTypeClassifier loaded ({sum(p.numel() for p in model.parameters()):,} params)")
|
|
679
|
+
|
|
680
|
+
# ── Load data ─────────────────────────────────────────────────
|
|
681
|
+
rel2id = get_rel2id(cfg)
|
|
682
|
+
indexid2msg = get_indexid2msg(cfg)
|
|
683
|
+
base_dir = cfg.transformation._graphs_dir
|
|
684
|
+
val_paths = get_all_graphs_for_dates(base_dir, cfg.dataset.val_dates)
|
|
685
|
+
test_paths = get_all_graphs_for_dates(base_dir, cfg.dataset.test_dates)
|
|
686
|
+
|
|
687
|
+
splits = {"val": val_paths, "test": test_paths}
|
|
688
|
+
model_epoch_dir = "model_epoch_0"
|
|
689
|
+
|
|
690
|
+
for split_name, graph_paths in splits.items():
|
|
691
|
+
log(f"Edge-cls scoring {split_name} ({len(graph_paths)} graphs)...")
|
|
692
|
+
|
|
693
|
+
for graph_path in graph_paths:
|
|
694
|
+
graph = torch.load(graph_path, weights_only=False)
|
|
695
|
+
edges = _collect_edges(graph)
|
|
696
|
+
if not edges:
|
|
697
|
+
continue
|
|
698
|
+
|
|
699
|
+
rows = []
|
|
700
|
+
for batch_start in range(0, len(edges), batch_size):
|
|
701
|
+
batch = edges[batch_start:batch_start + batch_size]
|
|
702
|
+
|
|
703
|
+
src_idx = torch.tensor(
|
|
704
|
+
[node_to_idx.get(e[0], 0) for e in batch],
|
|
705
|
+
dtype=torch.long, device=device)
|
|
706
|
+
dst_idx = torch.tensor(
|
|
707
|
+
[node_to_idx.get(e[1], 0) for e in batch],
|
|
708
|
+
dtype=torch.long, device=device)
|
|
709
|
+
etypes = torch.tensor(
|
|
710
|
+
[edge_type_to_id.get(e[2], 0) for e in batch],
|
|
711
|
+
dtype=torch.long, device=device)
|
|
712
|
+
|
|
713
|
+
with torch.no_grad():
|
|
714
|
+
logits = model.predict(src_idx, dst_idx)
|
|
715
|
+
scores = F.cross_entropy(
|
|
716
|
+
logits, etypes, reduction="none")
|
|
717
|
+
|
|
718
|
+
scores_cpu = scores.cpu().numpy().tolist()
|
|
719
|
+
for (src, dst, etype, ts), score in zip(batch, scores_cpu):
|
|
720
|
+
rows.append({
|
|
721
|
+
"loss": float(score),
|
|
722
|
+
"srcnode": int(src),
|
|
723
|
+
"dstnode": int(dst),
|
|
724
|
+
"time": int(ts),
|
|
725
|
+
"edge_type": int(rel2id.get(etype, 0)),
|
|
726
|
+
})
|
|
727
|
+
|
|
728
|
+
edge_df = pd.DataFrame(rows)
|
|
729
|
+
start_time = edge_df["time"].min()
|
|
730
|
+
end_time = edge_df["time"].max()
|
|
731
|
+
time_interval = (
|
|
732
|
+
ns_time_to_datetime_US(start_time, timezone=cfg.dataset.timezone)
|
|
733
|
+
+ "~"
|
|
734
|
+
+ ns_time_to_datetime_US(end_time, timezone=cfg.dataset.timezone)
|
|
735
|
+
)
|
|
736
|
+
|
|
737
|
+
csv_dir = os.path.join(edge_losses_dir, split_name, model_epoch_dir)
|
|
738
|
+
os.makedirs(csv_dir, exist_ok=True)
|
|
739
|
+
csv_file = os.path.join(csv_dir, time_interval + ".csv")
|
|
740
|
+
edge_df.to_csv(csv_file, sep=",", header=True, index=False, encoding="utf-8")
|
|
741
|
+
|
|
742
|
+
log(f" {split_name} CSVs written to {os.path.join(edge_losses_dir, split_name)}")
|
|
743
|
+
|
|
744
|
+
log("Edge classification detection complete.")
|
|
745
|
+
|
|
746
|
+
|
|
747
|
+
# ── TGN detection ──────────────────────────────────────────────────────────────
|
|
748
|
+
|
|
749
|
+
@torch.no_grad()
|
|
750
|
+
def _score_edges_tgn(
|
|
751
|
+
all_edges_by_graph: dict,
|
|
752
|
+
model,
|
|
753
|
+
node_to_idx: dict,
|
|
754
|
+
edge_type_to_id: dict,
|
|
755
|
+
rel2id: dict,
|
|
756
|
+
batch_size: int,
|
|
757
|
+
device: str,
|
|
758
|
+
objective: str = "contrastive",
|
|
759
|
+
event_src_embs: torch.Tensor = None,
|
|
760
|
+
event_dst_embs: torch.Tensor = None,
|
|
761
|
+
edge_to_pair_idx: torch.Tensor = None,
|
|
762
|
+
) -> dict:
|
|
763
|
+
"""Score all edges across multiple graphs in temporal order using TGN.
|
|
764
|
+
|
|
765
|
+
Unlike CLS/LP modes that score per-graph independently, TGN processes
|
|
766
|
+
ALL edges in temporal order because memory state is cumulative.
|
|
767
|
+
|
|
768
|
+
For contrastive objective: score = raw binary logit (higher = more anomalous).
|
|
769
|
+
For edge_pred objective: score = cross-entropy loss of true edge type.
|
|
770
|
+
For multi_edge_pred objective: score = binary CE of the true edge type
|
|
771
|
+
under the multi-label model (higher = more surprising).
|
|
772
|
+
For dist_edge_pred objective: score = -log P(true_type) under the predicted
|
|
773
|
+
distribution (higher = more surprising).
|
|
774
|
+
For edge_pred_emb objective: score = CE of true type + MSE between predicted
|
|
775
|
+
and actual edge embedding (higher = more anomalous).
|
|
776
|
+
|
|
777
|
+
Returns:
|
|
778
|
+
dict mapping graph_path -> pd.DataFrame with scores.
|
|
779
|
+
"""
|
|
780
|
+
# Flatten all edges with their graph origin, original index, and global index
|
|
781
|
+
flat_edges = []
|
|
782
|
+
global_idx = 0
|
|
783
|
+
for path, edges in all_edges_by_graph.items():
|
|
784
|
+
for i, edge in enumerate(edges):
|
|
785
|
+
flat_edges.append((edge, path, i, global_idx))
|
|
786
|
+
global_idx += 1
|
|
787
|
+
|
|
788
|
+
# Sort globally by timestamp
|
|
789
|
+
flat_edges.sort(key=lambda x: x[0][3])
|
|
790
|
+
|
|
791
|
+
# Pre-allocate score storage
|
|
792
|
+
scores_by_graph = {path: [None] * len(edges) for path, edges in all_edges_by_graph.items()}
|
|
793
|
+
|
|
794
|
+
for batch_start in range(0, len(flat_edges), batch_size):
|
|
795
|
+
batch = flat_edges[batch_start:batch_start + batch_size]
|
|
796
|
+
|
|
797
|
+
edges_batch = [x[0] for x in batch]
|
|
798
|
+
paths_batch = [x[1] for x in batch]
|
|
799
|
+
indices_batch = [x[2] for x in batch]
|
|
800
|
+
global_indices = [x[3] for x in batch]
|
|
801
|
+
|
|
802
|
+
src_idx = torch.tensor(
|
|
803
|
+
[node_to_idx.get(e[0], 0) for e in edges_batch], dtype=torch.long, device=device)
|
|
804
|
+
dst_idx = torch.tensor(
|
|
805
|
+
[node_to_idx.get(e[1], 0) for e in edges_batch], dtype=torch.long, device=device)
|
|
806
|
+
edge_types = torch.tensor(
|
|
807
|
+
[edge_type_to_id.get(e[2], 0) for e in edges_batch], dtype=torch.long, device=device)
|
|
808
|
+
timestamps = torch.tensor(
|
|
809
|
+
[e[3] for e in edges_batch], dtype=torch.long, device=device)
|
|
810
|
+
|
|
811
|
+
# Look up per-edge contextual embeddings for this batch (if available)
|
|
812
|
+
batch_event_src = None
|
|
813
|
+
batch_event_dst = None
|
|
814
|
+
if event_src_embs is not None and edge_to_pair_idx is not None:
|
|
815
|
+
gi = torch.tensor(global_indices, dtype=torch.long)
|
|
816
|
+
pair_idx = edge_to_pair_idx[gi]
|
|
817
|
+
batch_event_src = event_src_embs[pair_idx].to(device)
|
|
818
|
+
batch_event_dst = event_dst_embs[pair_idx].to(device)
|
|
819
|
+
|
|
820
|
+
if objective == "edge_pred":
|
|
821
|
+
logits = model.predict_edge_types(src_idx, dst_idx, timestamps,
|
|
822
|
+
event_src_emb=batch_event_src, event_dst_emb=batch_event_dst)
|
|
823
|
+
# Per-edge CE loss as anomaly score (higher = more surprising)
|
|
824
|
+
per_edge_scores = torch.nn.functional.cross_entropy(
|
|
825
|
+
logits, edge_types, reduction="none",
|
|
826
|
+
)
|
|
827
|
+
scores_cpu = per_edge_scores.cpu().numpy().tolist()
|
|
828
|
+
|
|
829
|
+
elif objective == "multi_edge_pred":
|
|
830
|
+
logits = model.predict_edge_types(src_idx, dst_idx, timestamps,
|
|
831
|
+
event_src_emb=batch_event_src, event_dst_emb=batch_event_dst)
|
|
832
|
+
# Per-edge binary CE: how surprising is this edge type under the
|
|
833
|
+
# multi-label model? Higher = more anomalous.
|
|
834
|
+
per_edge_logit = logits[
|
|
835
|
+
torch.arange(len(edges_batch), device=device), edge_types]
|
|
836
|
+
per_edge_scores = F.binary_cross_entropy_with_logits(
|
|
837
|
+
per_edge_logit, torch.ones_like(per_edge_logit),
|
|
838
|
+
reduction="none",
|
|
839
|
+
)
|
|
840
|
+
scores_cpu = per_edge_scores.cpu().numpy().tolist()
|
|
841
|
+
|
|
842
|
+
elif objective == "dist_edge_pred":
|
|
843
|
+
logits = model.predict_edge_types(src_idx, dst_idx, timestamps,
|
|
844
|
+
event_src_emb=batch_event_src, event_dst_emb=batch_event_dst)
|
|
845
|
+
# Per-edge NLL under predicted distribution: -log P(true_type)
|
|
846
|
+
log_probs = F.log_softmax(logits, dim=-1)
|
|
847
|
+
per_edge_scores = -log_probs[
|
|
848
|
+
torch.arange(len(edges_batch), device=device), edge_types]
|
|
849
|
+
scores_cpu = per_edge_scores.cpu().numpy().tolist()
|
|
850
|
+
|
|
851
|
+
elif objective == "edge_pred_emb":
|
|
852
|
+
logits = model.predict_edge_types(src_idx, dst_idx, timestamps,
|
|
853
|
+
event_src_emb=batch_event_src, event_dst_emb=batch_event_dst)
|
|
854
|
+
ce_scores = F.cross_entropy(
|
|
855
|
+
logits, edge_types, reduction="none")
|
|
856
|
+
pred_emb = model.predict_edge_embedding(src_idx, dst_idx, timestamps,
|
|
857
|
+
event_src_emb=batch_event_src, event_dst_emb=batch_event_dst)
|
|
858
|
+
target_emb = model.edge_emb(edge_types)
|
|
859
|
+
mse_scores = (pred_emb - target_emb).pow(2).mean(dim=-1)
|
|
860
|
+
per_edge_scores = ce_scores + mse_scores
|
|
861
|
+
scores_cpu = per_edge_scores.cpu().numpy().tolist()
|
|
862
|
+
|
|
863
|
+
elif objective == "node_pred":
|
|
864
|
+
logits = model.predict_node_types(src_idx, dst_idx, edge_types, timestamps,
|
|
865
|
+
event_src_emb=batch_event_src, event_dst_emb=batch_event_dst)
|
|
866
|
+
dst_types = model.node_types[dst_idx]
|
|
867
|
+
# Per-edge CE loss as anomaly score (higher = more surprising)
|
|
868
|
+
per_edge_scores = F.cross_entropy(
|
|
869
|
+
logits, dst_types, reduction="none")
|
|
870
|
+
scores_cpu = per_edge_scores.cpu().numpy().tolist()
|
|
871
|
+
|
|
872
|
+
else:
|
|
873
|
+
logits = model.classify_edges(src_idx, dst_idx, edge_types, timestamps,
|
|
874
|
+
event_src_emb=batch_event_src, event_dst_emb=batch_event_dst)
|
|
875
|
+
per_edge_scores = logits.squeeze(-1)
|
|
876
|
+
scores_cpu = per_edge_scores.cpu().numpy().tolist()
|
|
877
|
+
|
|
878
|
+
for score, path, idx in zip(scores_cpu, paths_batch, indices_batch):
|
|
879
|
+
scores_by_graph[path][idx] = score
|
|
880
|
+
|
|
881
|
+
# Update memories after scoring (with anomaly scores for score-gated memory)
|
|
882
|
+
model.update_memory(src_idx, dst_idx, edge_types, timestamps,
|
|
883
|
+
edge_scores=per_edge_scores)
|
|
884
|
+
|
|
885
|
+
# Build DataFrames
|
|
886
|
+
result = {}
|
|
887
|
+
for path, edges in all_edges_by_graph.items():
|
|
888
|
+
scores = scores_by_graph[path]
|
|
889
|
+
if not edges:
|
|
890
|
+
result[path] = pd.DataFrame(columns=["loss", "srcnode", "dstnode", "time", "edge_type"])
|
|
891
|
+
continue
|
|
892
|
+
rows = []
|
|
893
|
+
for (src, dst, etype, ts), score in zip(edges, scores):
|
|
894
|
+
rows.append({
|
|
895
|
+
"loss": float(score) if score is not None else 0.0,
|
|
896
|
+
"srcnode": int(src),
|
|
897
|
+
"dstnode": int(dst),
|
|
898
|
+
"time": int(ts),
|
|
899
|
+
"edge_type": int(rel2id.get(etype, 0)),
|
|
900
|
+
})
|
|
901
|
+
result[path] = pd.DataFrame(rows)
|
|
902
|
+
|
|
903
|
+
return result
|
|
904
|
+
|
|
905
|
+
|
|
906
|
+
def _detect_tgn(cfg):
|
|
907
|
+
"""TGN detection: score val/test edges with temporal entity memory."""
|
|
908
|
+
|
|
909
|
+
from .models.tgn import ProvenanceTGN
|
|
910
|
+
|
|
911
|
+
pretrain_cfg = cfg.featurization.pretrained
|
|
912
|
+
detect_cfg = cfg.training.pretrained
|
|
913
|
+
model_size = pretrain_cfg.model_size
|
|
914
|
+
batch_size = detect_cfg.inference_batch_size
|
|
915
|
+
device = "cuda" if torch.cuda.is_available() and not cfg._use_cpu else "cpu"
|
|
916
|
+
|
|
917
|
+
ft_dir = cfg.training._trained_models_dir
|
|
918
|
+
edge_losses_dir = cfg.training._edge_losses_dir
|
|
919
|
+
|
|
920
|
+
# ── Run training first (same pattern as existing detect.py) ────
|
|
921
|
+
from .finetune import main as finetune_main
|
|
922
|
+
finetune_main(cfg)
|
|
923
|
+
|
|
924
|
+
# ── Load checkpoint ────────────────────────────────────────────
|
|
925
|
+
ckpt_path = os.path.join(ft_dir, f"finetune_tgn_{model_size}_best.pt")
|
|
926
|
+
if not os.path.exists(ckpt_path):
|
|
927
|
+
ckpt_path = os.path.join(ft_dir, f"finetune_tgn_{model_size}.pt")
|
|
928
|
+
if not os.path.exists(ckpt_path):
|
|
929
|
+
raise FileNotFoundError(f"No TGN checkpoint found in {ft_dir}")
|
|
930
|
+
|
|
931
|
+
ckpt = torch.load(ckpt_path, map_location="cpu")
|
|
932
|
+
tgn_config = ckpt["tgn_config"]
|
|
933
|
+
node_to_idx = ckpt["node_to_idx"]
|
|
934
|
+
edge_type_to_id = ckpt["edge_type_to_id"]
|
|
935
|
+
objective = tgn_config.get("objective", "contrastive")
|
|
936
|
+
|
|
937
|
+
use_event_bert_emb = tgn_config.get("use_event_bert_emb", False)
|
|
938
|
+
event_bert_emb_dim = tgn_config.get("event_bert_emb_dim", 0)
|
|
939
|
+
|
|
940
|
+
model = ProvenanceTGN(
|
|
941
|
+
num_nodes=ckpt["num_nodes"],
|
|
942
|
+
num_edge_types=ckpt["num_edge_types"],
|
|
943
|
+
entity_emb_dim=tgn_config["entity_emb_dim"],
|
|
944
|
+
memory_dim=tgn_config["memory_dim"],
|
|
945
|
+
edge_emb_dim=tgn_config["edge_emb_dim"],
|
|
946
|
+
time_dim=tgn_config["time_dim"],
|
|
947
|
+
num_heads=tgn_config["num_heads"],
|
|
948
|
+
use_node_type_emb=tgn_config.get("use_node_type_emb", False),
|
|
949
|
+
use_time_emb=tgn_config.get("use_time_emb", True),
|
|
950
|
+
use_memory=tgn_config.get("use_memory", True),
|
|
951
|
+
use_entity_emb=tgn_config.get("use_entity_emb", True),
|
|
952
|
+
use_event_bert_emb=use_event_bert_emb,
|
|
953
|
+
event_bert_emb_dim=event_bert_emb_dim,
|
|
954
|
+
score_gated_memory=tgn_config.get("score_gated_memory", False),
|
|
955
|
+
temporal_decay=tgn_config.get("temporal_decay", False),
|
|
956
|
+
anomaly_accumulator=tgn_config.get("anomaly_accumulator", False),
|
|
957
|
+
device=device,
|
|
958
|
+
).to(device)
|
|
959
|
+
model.load_state_dict(ckpt["model_state_dict"])
|
|
960
|
+
model.eval()
|
|
961
|
+
log(f"TGN model loaded ({sum(p.numel() for p in model.parameters()):,} params)")
|
|
962
|
+
|
|
963
|
+
# ── Load data ──────────────────────────────────────────────────
|
|
964
|
+
rel2id = get_rel2id(cfg)
|
|
965
|
+
base_dir = cfg.transformation._graphs_dir
|
|
966
|
+
val_paths = get_all_graphs_for_dates(base_dir, cfg.dataset.val_dates)
|
|
967
|
+
test_paths = get_all_graphs_for_dates(base_dir, cfg.dataset.test_dates)
|
|
968
|
+
|
|
969
|
+
splits = {"val": val_paths, "test": test_paths}
|
|
970
|
+
model_epoch_dir = "model_epoch_0"
|
|
971
|
+
|
|
972
|
+
reset_memory = detect_cfg.tgn.reset_memory_on_inference
|
|
973
|
+
|
|
974
|
+
for split_name, graph_paths in splits.items():
|
|
975
|
+
log(f"TGN scoring {split_name} ({len(graph_paths)} graphs)...")
|
|
976
|
+
|
|
977
|
+
if reset_memory:
|
|
978
|
+
# Production mode: start with empty memory (no training history)
|
|
979
|
+
model.reset_memory()
|
|
980
|
+
log(f" Memory reset to zero (reset_memory_on_inference=True)")
|
|
981
|
+
else:
|
|
982
|
+
# Research mode: start from trained memory state (fresh per split)
|
|
983
|
+
trained_memory = ckpt["memory_state"]
|
|
984
|
+
model.load_memory_state({k: v.to(device) for k, v in trained_memory.items()})
|
|
985
|
+
|
|
986
|
+
# Collect all edges per graph
|
|
987
|
+
all_edges_by_graph = {}
|
|
988
|
+
total_edges = 0
|
|
989
|
+
for gp in graph_paths:
|
|
990
|
+
graph = torch.load(gp, weights_only=False)
|
|
991
|
+
edges = _collect_edges(graph)
|
|
992
|
+
all_edges_by_graph[gp] = edges
|
|
993
|
+
total_edges += len(edges)
|
|
994
|
+
log(f" {split_name}: {total_edges:,} edges across {len(graph_paths)} graphs")
|
|
995
|
+
|
|
996
|
+
# Score all edges in temporal order with memory updates
|
|
997
|
+
result_dfs = _score_edges_tgn(
|
|
998
|
+
all_edges_by_graph, model, node_to_idx, edge_type_to_id,
|
|
999
|
+
rel2id, batch_size, device, objective=objective,
|
|
1000
|
+
event_src_embs=None,
|
|
1001
|
+
event_dst_embs=None,
|
|
1002
|
+
edge_to_pair_idx=None,
|
|
1003
|
+
)
|
|
1004
|
+
|
|
1005
|
+
# Write CSVs (same format as existing detect.py)
|
|
1006
|
+
for graph_path in graph_paths:
|
|
1007
|
+
edge_df = result_dfs[graph_path]
|
|
1008
|
+
if edge_df.empty:
|
|
1009
|
+
continue
|
|
1010
|
+
|
|
1011
|
+
start_time = edge_df["time"].min()
|
|
1012
|
+
end_time = edge_df["time"].max()
|
|
1013
|
+
time_interval = (
|
|
1014
|
+
ns_time_to_datetime_US(start_time, timezone=cfg.dataset.timezone)
|
|
1015
|
+
+ "~"
|
|
1016
|
+
+ ns_time_to_datetime_US(end_time, timezone=cfg.dataset.timezone)
|
|
1017
|
+
)
|
|
1018
|
+
|
|
1019
|
+
csv_dir = os.path.join(edge_losses_dir, split_name, model_epoch_dir)
|
|
1020
|
+
os.makedirs(csv_dir, exist_ok=True)
|
|
1021
|
+
csv_file = os.path.join(csv_dir, time_interval + ".csv")
|
|
1022
|
+
edge_df.to_csv(csv_file, sep=",", header=True, index=False, encoding="utf-8")
|
|
1023
|
+
|
|
1024
|
+
log(f" {split_name} CSVs written to {os.path.join(edge_losses_dir, split_name)}")
|
|
1025
|
+
|
|
1026
|
+
log("TGN detection complete.")
|
|
1027
|
+
|
|
1028
|
+
|
|
1029
|
+
# ── Perplexity-based detection (decoder-only LLaMA) ────────────────────────────
|
|
1030
|
+
|
|
1031
|
+
@torch.no_grad()
|
|
1032
|
+
def _score_edges_perplexity(
|
|
1033
|
+
edges: List[Tuple[str, str, str, float]],
|
|
1034
|
+
sampler: ProvenanceWalkSampler,
|
|
1035
|
+
model,
|
|
1036
|
+
tokenizer: ProvenanceTokenizer,
|
|
1037
|
+
indexid2msg: dict,
|
|
1038
|
+
walk_length: int,
|
|
1039
|
+
batch_size: int,
|
|
1040
|
+
device: str,
|
|
1041
|
+
) -> List[float]:
|
|
1042
|
+
"""Score edges using causal LM perplexity: mean next-token prediction loss.
|
|
1043
|
+
|
|
1044
|
+
For each edge, samples a walk including the edge context, runs teacher-forced
|
|
1045
|
+
causal LM forward pass, and averages per-token cross-entropy as anomaly score.
|
|
1046
|
+
Higher score = model didn't expect this sequence = more anomalous.
|
|
1047
|
+
|
|
1048
|
+
Walks are pre-sampled in parallel across CPU cores.
|
|
1049
|
+
"""
|
|
1050
|
+
# Phase 1: parallel walk sampling on CPU
|
|
1051
|
+
all_walks = _parallel_sample_walks(edges, sampler, walk_length)
|
|
1052
|
+
|
|
1053
|
+
# Phase 2: tokenize + GPU inference in batches
|
|
1054
|
+
scores = []
|
|
1055
|
+
for batch_start in range(0, len(edges), batch_size):
|
|
1056
|
+
batch_edges = edges[batch_start:batch_start + batch_size]
|
|
1057
|
+
batch_walks = all_walks[batch_start:batch_start + batch_size]
|
|
1058
|
+
|
|
1059
|
+
batch_token_ids = []
|
|
1060
|
+
for (src_wn, src_we, dst_wn, dst_we), (src, dst, etype, ts) in zip(batch_walks, batch_edges):
|
|
1061
|
+
# Tokenize the walk with dst context (same as CLS mode but no masking)
|
|
1062
|
+
tok_ids, attn, _ = tokenizer.tokenize_for_finetune(
|
|
1063
|
+
src_wn, src_we, dst, etype, indexid2msg, mode="cls",
|
|
1064
|
+
dst_walk_nodes=dst_wn, dst_walk_edge_types=dst_we,
|
|
1065
|
+
)
|
|
1066
|
+
batch_token_ids.append(tok_ids)
|
|
1067
|
+
|
|
1068
|
+
if not batch_token_ids:
|
|
1069
|
+
continue
|
|
1070
|
+
|
|
1071
|
+
# Pad to max length
|
|
1072
|
+
max_len = max(t.size(0) for t in batch_token_ids)
|
|
1073
|
+
pad_id = tokenizer.pad_id
|
|
1074
|
+
B = len(batch_token_ids)
|
|
1075
|
+
input_ids = torch.full((B, max_len), pad_id, dtype=torch.long)
|
|
1076
|
+
attention_mask = torch.zeros(B, max_len, dtype=torch.bool)
|
|
1077
|
+
for i in range(B):
|
|
1078
|
+
L = batch_token_ids[i].size(0)
|
|
1079
|
+
input_ids[i, :L] = batch_token_ids[i]
|
|
1080
|
+
attention_mask[i, :L] = True
|
|
1081
|
+
|
|
1082
|
+
# Labels = input_ids; model shifts internally for next-token prediction.
|
|
1083
|
+
# Set padding to -100 so it's ignored in loss.
|
|
1084
|
+
labels = input_ids.clone()
|
|
1085
|
+
labels[~attention_mask] = -100
|
|
1086
|
+
|
|
1087
|
+
# Forward pass returns per-sample loss
|
|
1088
|
+
out = model.modified_fwd(
|
|
1089
|
+
input_ids.to(device),
|
|
1090
|
+
attention_mask.to(device),
|
|
1091
|
+
labels.to(device),
|
|
1092
|
+
return_loss=False,
|
|
1093
|
+
)
|
|
1094
|
+
logits = out.logits # [B, L, V]
|
|
1095
|
+
|
|
1096
|
+
# Compute per-token loss, then average per sample
|
|
1097
|
+
shift_logits = logits[:, :-1, :].contiguous()
|
|
1098
|
+
shift_labels = labels[:, 1:].to(device).contiguous()
|
|
1099
|
+
B, L, V = shift_logits.shape
|
|
1100
|
+
loss_fct = torch.nn.CrossEntropyLoss(reduction="none", ignore_index=-100)
|
|
1101
|
+
per_token_loss = loss_fct(
|
|
1102
|
+
shift_logits.view(-1, V), shift_labels.view(-1)
|
|
1103
|
+
).view(B, L)
|
|
1104
|
+
|
|
1105
|
+
# Average over valid (non-padding) positions
|
|
1106
|
+
valid = shift_labels != -100
|
|
1107
|
+
num_valid = valid.float().sum(dim=1).clamp(min=1)
|
|
1108
|
+
per_edge_scores = (per_token_loss * valid.float()).sum(dim=1) / num_valid
|
|
1109
|
+
scores.extend(per_edge_scores.cpu().numpy().tolist())
|
|
1110
|
+
|
|
1111
|
+
return scores
|
|
1112
|
+
|
|
1113
|
+
|
|
1114
|
+
def _detect_perplexity(cfg):
|
|
1115
|
+
"""Perplexity-based detection using decoder-only LLaMA model.
|
|
1116
|
+
|
|
1117
|
+
Loads the pretrained LLaMA model directly (no fine-tuning) and scores
|
|
1118
|
+
each edge by computing the mean next-token prediction loss over the
|
|
1119
|
+
walk containing that edge. Higher perplexity = more anomalous.
|
|
1120
|
+
"""
|
|
1121
|
+
|
|
1122
|
+
from .models.llama import ProvenanceLLaMA, get_llama_config
|
|
1123
|
+
|
|
1124
|
+
pretrain_cfg = cfg.featurization.pretrained
|
|
1125
|
+
detect_cfg = cfg.training.pretrained
|
|
1126
|
+
model_size = pretrain_cfg.model_size
|
|
1127
|
+
walk_length = detect_cfg.finetune_walk_len
|
|
1128
|
+
batch_size = detect_cfg.inference_batch_size
|
|
1129
|
+
num_walks = detect_cfg.num_inference_walks
|
|
1130
|
+
time_weight = pretrain_cfg.walks.time_weight
|
|
1131
|
+
half_life = pretrain_cfg.walks.half_life
|
|
1132
|
+
graph_context_mode = pretrain_cfg.graph_context_mode
|
|
1133
|
+
|
|
1134
|
+
device = "cuda" if torch.cuda.is_available() and not cfg._use_cpu else "cpu"
|
|
1135
|
+
|
|
1136
|
+
pretrain_dir = cfg.featurization._model_dir
|
|
1137
|
+
edge_losses_dir = cfg.training._edge_losses_dir
|
|
1138
|
+
|
|
1139
|
+
# ── Load tokenizer ──────────────────────────────────────────────────
|
|
1140
|
+
tokenizer = ProvenanceTokenizer(cfg)
|
|
1141
|
+
tokenizer.load(os.path.join(pretrain_dir, "tokenizer.pt"))
|
|
1142
|
+
log(f"Loaded tokenizer (vocab_size={tokenizer.vocab_size})")
|
|
1143
|
+
|
|
1144
|
+
# ── Load pretrained LLaMA model ─────────────────────────────────────
|
|
1145
|
+
rope_theta = pretrain_cfg.rope_theta
|
|
1146
|
+
llama_config = get_llama_config(
|
|
1147
|
+
tokenizer.vocab_size, model_size, tokenizer.max_seq_len,
|
|
1148
|
+
rope_theta=rope_theta,
|
|
1149
|
+
)
|
|
1150
|
+
|
|
1151
|
+
checkpoint_path = os.path.join(pretrain_dir, f"pretrain_{model_size}.pt")
|
|
1152
|
+
if not os.path.exists(checkpoint_path):
|
|
1153
|
+
raise FileNotFoundError(f"No pretrained checkpoint found in {pretrain_dir}")
|
|
1154
|
+
|
|
1155
|
+
log(f"Loading LLaMA checkpoint from {checkpoint_path}")
|
|
1156
|
+
sd = torch.load(checkpoint_path, weights_only=True, map_location="cpu")
|
|
1157
|
+
model = ProvenanceLLaMA(llama_config)
|
|
1158
|
+
model.load_state_dict(sd)
|
|
1159
|
+
model = model.to(device)
|
|
1160
|
+
model.eval()
|
|
1161
|
+
log(f"LLaMA model on {device} ({sum(p.numel() for p in model.parameters()):,} params)")
|
|
1162
|
+
|
|
1163
|
+
# ── Load data ───────────────────────────────────────────────────────
|
|
1164
|
+
indexid2msg = get_indexid2msg(cfg)
|
|
1165
|
+
rel2id = get_rel2id(cfg)
|
|
1166
|
+
base_dir = cfg.transformation._graphs_dir
|
|
1167
|
+
|
|
1168
|
+
val_paths = get_all_graphs_for_dates(base_dir, cfg.dataset.val_dates)
|
|
1169
|
+
test_paths = get_all_graphs_for_dates(base_dir, cfg.dataset.test_dates)
|
|
1170
|
+
|
|
1171
|
+
splits = {"val": val_paths, "test": test_paths}
|
|
1172
|
+
model_epoch_dir = "model_epoch_0"
|
|
1173
|
+
|
|
1174
|
+
log(f"Graph context mode: {graph_context_mode}")
|
|
1175
|
+
|
|
1176
|
+
for split_name, graph_paths in splits.items():
|
|
1177
|
+
log(f"Perplexity scoring {split_name} ({len(graph_paths)} graphs)...")
|
|
1178
|
+
|
|
1179
|
+
# Build context graph(s) — same logic as CLS/LP modes
|
|
1180
|
+
if graph_context_mode == "all":
|
|
1181
|
+
split_context = _build_context_graph(graph_paths)
|
|
1182
|
+
log(f" {split_name}: merged context — {split_context.number_of_nodes():,} nodes, "
|
|
1183
|
+
f"{split_context.number_of_edges():,} edges")
|
|
1184
|
+
split_sampler = ProvenanceWalkSampler(
|
|
1185
|
+
split_context, walk_length=walk_length, num_walks=1,
|
|
1186
|
+
time_weight=time_weight, half_life=half_life,
|
|
1187
|
+
)
|
|
1188
|
+
elif graph_context_mode == "day":
|
|
1189
|
+
day_groups = _group_paths_by_day(graph_paths)
|
|
1190
|
+
day_samplers = {
|
|
1191
|
+
day: ProvenanceWalkSampler(
|
|
1192
|
+
_build_context_graph(paths),
|
|
1193
|
+
walk_length=walk_length, num_walks=1,
|
|
1194
|
+
time_weight=time_weight, half_life=half_life,
|
|
1195
|
+
)
|
|
1196
|
+
for day, paths in day_groups.items()
|
|
1197
|
+
}
|
|
1198
|
+
|
|
1199
|
+
for graph_path in log_tqdm(graph_paths, desc=f"Detect ({split_name})"):
|
|
1200
|
+
graph = torch.load(graph_path, weights_only=False)
|
|
1201
|
+
edges = _collect_edges(graph)
|
|
1202
|
+
if not edges:
|
|
1203
|
+
continue
|
|
1204
|
+
|
|
1205
|
+
# Build or reuse sampler
|
|
1206
|
+
if graph_context_mode == "all":
|
|
1207
|
+
sampler = split_sampler
|
|
1208
|
+
elif graph_context_mode == "day":
|
|
1209
|
+
day_folder = os.path.basename(os.path.dirname(graph_path))
|
|
1210
|
+
sampler = day_samplers.get(day_folder)
|
|
1211
|
+
if sampler is None:
|
|
1212
|
+
sampler = ProvenanceWalkSampler(
|
|
1213
|
+
graph, walk_length=walk_length, num_walks=1,
|
|
1214
|
+
time_weight=time_weight, half_life=half_life,
|
|
1215
|
+
)
|
|
1216
|
+
else: # window
|
|
1217
|
+
sampler = ProvenanceWalkSampler(
|
|
1218
|
+
graph, walk_length=walk_length, num_walks=1,
|
|
1219
|
+
time_weight=time_weight, half_life=half_life,
|
|
1220
|
+
)
|
|
1221
|
+
|
|
1222
|
+
# Score with optional multi-walk averaging
|
|
1223
|
+
if num_walks <= 1:
|
|
1224
|
+
edge_scores = _score_edges_perplexity(
|
|
1225
|
+
edges, sampler, model, tokenizer, indexid2msg,
|
|
1226
|
+
walk_length, batch_size, device,
|
|
1227
|
+
)
|
|
1228
|
+
else:
|
|
1229
|
+
all_scores = np.zeros(len(edges))
|
|
1230
|
+
for _ in range(num_walks):
|
|
1231
|
+
walk_scores = _score_edges_perplexity(
|
|
1232
|
+
edges, sampler, model, tokenizer, indexid2msg,
|
|
1233
|
+
walk_length, batch_size, device,
|
|
1234
|
+
)
|
|
1235
|
+
all_scores += np.array(walk_scores)
|
|
1236
|
+
edge_scores = (all_scores / num_walks).tolist()
|
|
1237
|
+
|
|
1238
|
+
# Build DataFrame
|
|
1239
|
+
rows = []
|
|
1240
|
+
for (src, dst, etype, ts), score in zip(edges, edge_scores):
|
|
1241
|
+
rows.append({
|
|
1242
|
+
"loss": float(score),
|
|
1243
|
+
"srcnode": int(src),
|
|
1244
|
+
"dstnode": int(dst),
|
|
1245
|
+
"time": int(ts),
|
|
1246
|
+
"edge_type": int(rel2id.get(etype, 0)),
|
|
1247
|
+
})
|
|
1248
|
+
edge_df = pd.DataFrame(rows)
|
|
1249
|
+
|
|
1250
|
+
if edge_df.empty:
|
|
1251
|
+
continue
|
|
1252
|
+
|
|
1253
|
+
start_time = edge_df["time"].min()
|
|
1254
|
+
end_time = edge_df["time"].max()
|
|
1255
|
+
time_interval = (
|
|
1256
|
+
ns_time_to_datetime_US(start_time, timezone=cfg.dataset.timezone)
|
|
1257
|
+
+ "~"
|
|
1258
|
+
+ ns_time_to_datetime_US(end_time, timezone=cfg.dataset.timezone)
|
|
1259
|
+
)
|
|
1260
|
+
|
|
1261
|
+
csv_dir = os.path.join(edge_losses_dir, split_name, model_epoch_dir)
|
|
1262
|
+
os.makedirs(csv_dir, exist_ok=True)
|
|
1263
|
+
csv_file = os.path.join(csv_dir, time_interval + ".csv")
|
|
1264
|
+
edge_df.to_csv(csv_file, sep=",", header=True, index=False, encoding="utf-8")
|
|
1265
|
+
|
|
1266
|
+
log(f" {split_name} CSVs written to {os.path.join(edge_losses_dir, split_name)}")
|
|
1267
|
+
|
|
1268
|
+
log("Perplexity detection complete.")
|
|
1269
|
+
|
|
1270
|
+
|
|
1271
|
+
def main(cfg):
|
|
1272
|
+
"""Score val/test edges with SPIDER and write CSV files.
|
|
1273
|
+
|
|
1274
|
+
Modes:
|
|
1275
|
+
cls: CLS fine-tuning + sigmoid scoring
|
|
1276
|
+
lp: LP fine-tuning + mean cross-entropy scoring
|
|
1277
|
+
mlm: pretrained model only (no fine-tuning) + CE scoring
|
|
1278
|
+
tgn: TGN with attention-based entity memory
|
|
1279
|
+
edge_cls: edge type prediction from static BERT entity embeddings
|
|
1280
|
+
perplexity: decoder-only LLaMA, direct perplexity scoring (no fine-tuning)
|
|
1281
|
+
"""
|
|
1282
|
+
|
|
1283
|
+
pretrain_cfg = cfg.featurization.pretrained
|
|
1284
|
+
detect_cfg = cfg.training.pretrained
|
|
1285
|
+
model_type = pretrain_cfg.model_type
|
|
1286
|
+
model_size = pretrain_cfg.model_size
|
|
1287
|
+
finetune_mode = detect_cfg.finetune_mode
|
|
1288
|
+
|
|
1289
|
+
# TGN uses a completely different pipeline (temporal scoring with memory updates)
|
|
1290
|
+
if finetune_mode == "tgn":
|
|
1291
|
+
_detect_tgn(cfg)
|
|
1292
|
+
return
|
|
1293
|
+
|
|
1294
|
+
if finetune_mode == "edge_cls":
|
|
1295
|
+
_detect_edge_cls(cfg)
|
|
1296
|
+
return
|
|
1297
|
+
|
|
1298
|
+
if finetune_mode == "perplexity":
|
|
1299
|
+
_detect_perplexity(cfg)
|
|
1300
|
+
return
|
|
1301
|
+
|
|
1302
|
+
walk_length = detect_cfg.finetune_walk_len
|
|
1303
|
+
freeze_backbone = detect_cfg.freeze_backbone
|
|
1304
|
+
batch_size = detect_cfg.inference_batch_size
|
|
1305
|
+
num_walks = detect_cfg.num_inference_walks
|
|
1306
|
+
time_weight = pretrain_cfg.walks.time_weight
|
|
1307
|
+
half_life = pretrain_cfg.walks.half_life
|
|
1308
|
+
mask_edge_type = pretrain_cfg.mlm.mask_edge_type
|
|
1309
|
+
edge_score_weight = detect_cfg.edge_score_weight if mask_edge_type else 0.0
|
|
1310
|
+
graph_context_mode = pretrain_cfg.graph_context_mode
|
|
1311
|
+
log(f"Graph context mode: {graph_context_mode}")
|
|
1312
|
+
|
|
1313
|
+
device = "cuda" if torch.cuda.is_available() and not cfg._use_cpu else "cpu"
|
|
1314
|
+
|
|
1315
|
+
# ── Directories ────────────────────────────────────────────────────
|
|
1316
|
+
pretrain_dir = cfg.featurization._model_dir
|
|
1317
|
+
ft_dir = cfg.training._trained_models_dir
|
|
1318
|
+
|
|
1319
|
+
# ── Load tokenizer ──────────────────────────────────────────────────
|
|
1320
|
+
tokenizer = ProvenanceTokenizer(cfg)
|
|
1321
|
+
tokenizer.load(os.path.join(pretrain_dir, "tokenizer.pt"))
|
|
1322
|
+
log(f"Loaded tokenizer (vocab_size={tokenizer.vocab_size})")
|
|
1323
|
+
|
|
1324
|
+
# ── Load model ─────────────────────────────────────────────────────
|
|
1325
|
+
if finetune_mode == "mlm":
|
|
1326
|
+
model = _load_pretrained_model(pretrain_dir, tokenizer, model_size, device, model_type, pretrain_cfg)
|
|
1327
|
+
else:
|
|
1328
|
+
from .finetune import main as finetune_main
|
|
1329
|
+
finetune_main(cfg)
|
|
1330
|
+
model = _load_finetuned_model(
|
|
1331
|
+
pretrain_dir, ft_dir, tokenizer, model_size, model_type, finetune_mode, freeze_backbone, device, pretrain_cfg,
|
|
1332
|
+
)
|
|
1333
|
+
log(f"Model on {device} ({sum(p.numel() for p in model.parameters()):,} params)")
|
|
1334
|
+
|
|
1335
|
+
# ── Load data ───────────────────────────────────────────────────────
|
|
1336
|
+
indexid2msg = get_indexid2msg(cfg)
|
|
1337
|
+
rel2id = get_rel2id(cfg)
|
|
1338
|
+
base_dir = cfg.transformation._graphs_dir
|
|
1339
|
+
edge_losses_dir = cfg.training._edge_losses_dir
|
|
1340
|
+
|
|
1341
|
+
train_paths = get_all_graphs_for_dates(base_dir, cfg.dataset.train_dates)
|
|
1342
|
+
val_paths = get_all_graphs_for_dates(base_dir, cfg.dataset.val_dates)
|
|
1343
|
+
test_paths = get_all_graphs_for_dates(base_dir, cfg.dataset.test_dates)
|
|
1344
|
+
|
|
1345
|
+
splits = {
|
|
1346
|
+
"val": val_paths,
|
|
1347
|
+
"test": test_paths,
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
# ── Score edges and write CSVs ──────────────────────────────────────
|
|
1351
|
+
model_epoch_dir = "model_epoch_0"
|
|
1352
|
+
|
|
1353
|
+
for split_name, graph_paths in splits.items():
|
|
1354
|
+
log(f"Scoring {split_name} edges ({len(graph_paths)} graphs, context={graph_context_mode})...")
|
|
1355
|
+
|
|
1356
|
+
# Build context graph(s) for this split.
|
|
1357
|
+
# window: no merged context; sampler uses only the current snapshot.
|
|
1358
|
+
# day: one merged context graph per calendar day; walks can cross
|
|
1359
|
+
# windows within the same day but not across days.
|
|
1360
|
+
# all: one merged context graph from all snapshots in this split;
|
|
1361
|
+
# no training data is included, so no leakage across splits.
|
|
1362
|
+
if graph_context_mode == "all":
|
|
1363
|
+
split_context = _build_context_graph(graph_paths)
|
|
1364
|
+
log(f" {split_name}: merged context — {split_context.number_of_nodes():,} nodes, "
|
|
1365
|
+
f"{split_context.number_of_edges():,} edges")
|
|
1366
|
+
split_sampler = ProvenanceWalkSampler(
|
|
1367
|
+
split_context, walk_length=walk_length, num_walks=1,
|
|
1368
|
+
time_weight=time_weight, half_life=half_life,
|
|
1369
|
+
)
|
|
1370
|
+
log(f" {split_name}: sampler built (forward+backward adj ready)")
|
|
1371
|
+
elif graph_context_mode == "day":
|
|
1372
|
+
day_groups = _group_paths_by_day(graph_paths)
|
|
1373
|
+
day_contexts = {day: _build_context_graph(paths)
|
|
1374
|
+
for day, paths in day_groups.items()}
|
|
1375
|
+
day_samplers = {
|
|
1376
|
+
day: ProvenanceWalkSampler(
|
|
1377
|
+
ctx, walk_length=walk_length, num_walks=1,
|
|
1378
|
+
time_weight=time_weight, half_life=half_life,
|
|
1379
|
+
)
|
|
1380
|
+
for day, ctx in day_contexts.items()
|
|
1381
|
+
}
|
|
1382
|
+
log(f" {split_name}: {len(day_samplers)} day-level samplers built")
|
|
1383
|
+
|
|
1384
|
+
for graph_path in log_tqdm(graph_paths, desc=f"Detect ({split_name})"):
|
|
1385
|
+
graph = torch.load(graph_path)
|
|
1386
|
+
|
|
1387
|
+
if graph_context_mode == "window":
|
|
1388
|
+
prebuilt = None
|
|
1389
|
+
context = None
|
|
1390
|
+
elif graph_context_mode == "all":
|
|
1391
|
+
prebuilt = split_sampler
|
|
1392
|
+
context = None
|
|
1393
|
+
else: # day
|
|
1394
|
+
day_folder = os.path.basename(os.path.dirname(graph_path))
|
|
1395
|
+
prebuilt = day_samplers.get(day_folder)
|
|
1396
|
+
context = None
|
|
1397
|
+
|
|
1398
|
+
edge_df = _score_graph(
|
|
1399
|
+
graph, model, tokenizer, indexid2msg, rel2id,
|
|
1400
|
+
finetune_mode, walk_length, batch_size,
|
|
1401
|
+
time_weight, half_life, device, num_walks,
|
|
1402
|
+
edge_score_weight,
|
|
1403
|
+
context_graph=context,
|
|
1404
|
+
prebuilt_sampler=prebuilt,
|
|
1405
|
+
)
|
|
1406
|
+
|
|
1407
|
+
if edge_df.empty:
|
|
1408
|
+
continue
|
|
1409
|
+
|
|
1410
|
+
# Build time interval string for filename
|
|
1411
|
+
start_time = edge_df["time"].min()
|
|
1412
|
+
end_time = edge_df["time"].max()
|
|
1413
|
+
time_interval = (
|
|
1414
|
+
ns_time_to_datetime_US(start_time, timezone=cfg.dataset.timezone)
|
|
1415
|
+
+ "~"
|
|
1416
|
+
+ ns_time_to_datetime_US(end_time, timezone=cfg.dataset.timezone)
|
|
1417
|
+
)
|
|
1418
|
+
|
|
1419
|
+
# Write CSV
|
|
1420
|
+
csv_dir = os.path.join(edge_losses_dir, split_name, model_epoch_dir)
|
|
1421
|
+
os.makedirs(csv_dir, exist_ok=True)
|
|
1422
|
+
csv_file = os.path.join(csv_dir, time_interval + ".csv")
|
|
1423
|
+
edge_df.to_csv(csv_file, sep=",", header=True, index=False, encoding="utf-8")
|
|
1424
|
+
|
|
1425
|
+
log(f" {split_name} CSVs written to {os.path.join(edge_losses_dir, split_name)}")
|
|
1426
|
+
|
|
1427
|
+
log("Detection complete.")
|