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,1728 @@
|
|
|
1
|
+
"""Compute static node embeddings with a pretrained SPIDER model.
|
|
2
|
+
|
|
3
|
+
For each node, tokenizes its (type, label) pair, runs through the frozen pretrained
|
|
4
|
+
encoder, and mean-pools over non-padding positions to produce a single embedding
|
|
5
|
+
vector. This allows SPIDER to be used as a drop-in replacement for
|
|
6
|
+
word2vec or other featurization methods in the standard GNN pipeline.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
import torch
|
|
13
|
+
|
|
14
|
+
from pidsmaker.utils.utils import get_indexid2msg, get_split_to_files, log
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class GraphBasedEncoder:
|
|
18
|
+
"""Wraps a pretrained GNN encoder (GraphMAE/GAE/DGI) for per-graph inference.
|
|
19
|
+
|
|
20
|
+
Instead of pre-computing a single averaged embedding per node across all
|
|
21
|
+
graphs (which causes data snooping on test sets), this encoder is called
|
|
22
|
+
once per graph to produce embeddings using only that graph's structure.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
def __init__(self, model, t5_encoder, tokenizer, indexid2msg, emb_dim, device):
|
|
26
|
+
self.model = model
|
|
27
|
+
self.t5_encoder = t5_encoder
|
|
28
|
+
self.tokenizer = tokenizer
|
|
29
|
+
self.indexid2msg = indexid2msg
|
|
30
|
+
self.emb_dim = emb_dim
|
|
31
|
+
self.device = device
|
|
32
|
+
self.label_cache = {} # Persists across graphs (labels are deterministic)
|
|
33
|
+
|
|
34
|
+
def encode_graph(self, graph_path):
|
|
35
|
+
"""Encode nodes using only the given graph's structure.
|
|
36
|
+
|
|
37
|
+
Returns:
|
|
38
|
+
dict: {node_id (int): embedding (np.ndarray)} for all nodes in
|
|
39
|
+
this graph. Nodes not present in this graph are NOT included.
|
|
40
|
+
"""
|
|
41
|
+
import torch as _torch
|
|
42
|
+
|
|
43
|
+
g = _torch.load(graph_path)
|
|
44
|
+
graph_nodes = list(g.nodes())
|
|
45
|
+
if not graph_nodes:
|
|
46
|
+
return {}
|
|
47
|
+
|
|
48
|
+
# Collect node labels for T5 encoding
|
|
49
|
+
node_labels = []
|
|
50
|
+
valid_nodes = []
|
|
51
|
+
for n in graph_nodes:
|
|
52
|
+
if n in self.indexid2msg:
|
|
53
|
+
lbl = self.indexid2msg[n]
|
|
54
|
+
lbl = tuple(lbl) if isinstance(lbl, list) else lbl
|
|
55
|
+
else:
|
|
56
|
+
lbl = ("subject", "unknown")
|
|
57
|
+
node_labels.append(lbl)
|
|
58
|
+
valid_nodes.append(n)
|
|
59
|
+
|
|
60
|
+
# Encode uncached labels via T5
|
|
61
|
+
uncached = [lbl for lbl in set(node_labels) if lbl not in self.label_cache]
|
|
62
|
+
if uncached:
|
|
63
|
+
with _torch.no_grad():
|
|
64
|
+
new_embs = self.t5_encoder.encode_labels(uncached, self.tokenizer, self.device)
|
|
65
|
+
for i, lbl in enumerate(uncached):
|
|
66
|
+
self.label_cache[lbl] = new_embs[i]
|
|
67
|
+
|
|
68
|
+
x = _torch.stack([self.label_cache[lbl] for lbl in node_labels])
|
|
69
|
+
|
|
70
|
+
# Build bidirectional edge_index from graph
|
|
71
|
+
node2local = {n: i for i, n in enumerate(valid_nodes)}
|
|
72
|
+
edge_src, edge_dst = [], []
|
|
73
|
+
for src, dst, _, attrs in g.edges(data=True, keys=True):
|
|
74
|
+
if src in node2local and dst in node2local:
|
|
75
|
+
edge_src.append(node2local[src])
|
|
76
|
+
edge_dst.append(node2local[dst])
|
|
77
|
+
edge_src.append(node2local[dst])
|
|
78
|
+
edge_dst.append(node2local[src])
|
|
79
|
+
|
|
80
|
+
if not edge_src:
|
|
81
|
+
# No edges: return T5-only embeddings (no GNN context)
|
|
82
|
+
indexid2vec = {}
|
|
83
|
+
x_np = x.cpu().numpy()
|
|
84
|
+
for i, n in enumerate(valid_nodes):
|
|
85
|
+
emb = x_np[i].astype(np.float32)
|
|
86
|
+
norm = np.linalg.norm(emb)
|
|
87
|
+
if norm > 1e-12:
|
|
88
|
+
emb = emb / norm
|
|
89
|
+
indexid2vec[int(n)] = emb
|
|
90
|
+
return indexid2vec
|
|
91
|
+
|
|
92
|
+
edge_index = _torch.tensor([edge_src, edge_dst], dtype=_torch.long, device=self.device)
|
|
93
|
+
|
|
94
|
+
with _torch.no_grad():
|
|
95
|
+
encoded = self.model.encode(x, edge_index)
|
|
96
|
+
|
|
97
|
+
encoded_np = encoded.cpu().numpy()
|
|
98
|
+
indexid2vec = {}
|
|
99
|
+
for i, n in enumerate(valid_nodes):
|
|
100
|
+
emb = encoded_np[i].astype(np.float32)
|
|
101
|
+
norm = np.linalg.norm(emb)
|
|
102
|
+
if norm > 1e-12:
|
|
103
|
+
emb = emb / norm
|
|
104
|
+
indexid2vec[int(n)] = emb
|
|
105
|
+
|
|
106
|
+
return indexid2vec
|
|
107
|
+
|
|
108
|
+
def cleanup(self):
|
|
109
|
+
"""Release GPU memory."""
|
|
110
|
+
del self.model, self.t5_encoder
|
|
111
|
+
if torch.cuda.is_available():
|
|
112
|
+
torch.cuda.empty_cache()
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _embed_labels(bert, tokenizer, keys, hidden_size, device, batch_size=512):
|
|
116
|
+
"""Embed a list of (ntype, label) keys using frozen BERT. Returns {key: np.ndarray}."""
|
|
117
|
+
unique_keys = list(dict.fromkeys(keys)) # deduplicate, preserve order
|
|
118
|
+
result = {}
|
|
119
|
+
|
|
120
|
+
for batch_start in range(0, len(unique_keys), batch_size):
|
|
121
|
+
batch_keys = unique_keys[batch_start:batch_start + batch_size]
|
|
122
|
+
batch_token_ids, batch_keys_valid = [], []
|
|
123
|
+
for key in batch_keys:
|
|
124
|
+
ntype, nlabel = key
|
|
125
|
+
tids = tokenizer.tokenize_node(ntype, nlabel)
|
|
126
|
+
if tids:
|
|
127
|
+
batch_token_ids.append(tids)
|
|
128
|
+
batch_keys_valid.append(key)
|
|
129
|
+
else:
|
|
130
|
+
result[key] = np.zeros(hidden_size, dtype=np.float32)
|
|
131
|
+
|
|
132
|
+
if not batch_token_ids:
|
|
133
|
+
continue
|
|
134
|
+
|
|
135
|
+
max_len = min(max(len(t) for t in batch_token_ids), tokenizer.max_seq_len)
|
|
136
|
+
B = len(batch_token_ids)
|
|
137
|
+
input_ids = torch.full((B, max_len), tokenizer.pad_id, dtype=torch.long)
|
|
138
|
+
attention_mask = torch.zeros(B, max_len, dtype=torch.bool)
|
|
139
|
+
for i, tids in enumerate(batch_token_ids):
|
|
140
|
+
L = min(len(tids), max_len)
|
|
141
|
+
input_ids[i, :L] = torch.tensor(tids[:L])
|
|
142
|
+
attention_mask[i, :L] = True
|
|
143
|
+
|
|
144
|
+
with torch.no_grad():
|
|
145
|
+
hidden = bert.modified_fwd(
|
|
146
|
+
input_ids.to(device),
|
|
147
|
+
attention_mask.to(device),
|
|
148
|
+
labels=torch.full_like(input_ids, -100).to(device),
|
|
149
|
+
skip_cls=True,
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
mask_f = attention_mask.to(device).unsqueeze(-1).float()
|
|
153
|
+
pooled = (hidden * mask_f).sum(dim=1) / mask_f.sum(dim=1).clamp(min=1)
|
|
154
|
+
pooled_np = pooled.cpu().numpy()
|
|
155
|
+
|
|
156
|
+
for i, key in enumerate(batch_keys_valid):
|
|
157
|
+
emb = pooled_np[i]
|
|
158
|
+
norm = np.linalg.norm(emb)
|
|
159
|
+
if norm > 1e-12:
|
|
160
|
+
emb = emb / norm
|
|
161
|
+
result[key] = emb.astype(np.float32)
|
|
162
|
+
|
|
163
|
+
return result
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _apply_rename_attack(cfg, indexid2vec, indexid2msg, bert, tokenizer, output_dim, device):
|
|
167
|
+
"""Renaming/mimicry attack at inference time.
|
|
168
|
+
|
|
169
|
+
For each test-set node whose `(ntype, nlabel)` matches one of the user-supplied
|
|
170
|
+
base names — either as an exact label match (`nlabel == base`) or as a path
|
|
171
|
+
suffix match (`nlabel.endswith('/' + base)`) — overwrite its embedding with
|
|
172
|
+
the embedding produced for a benign target label.
|
|
173
|
+
|
|
174
|
+
Two target-selection modes:
|
|
175
|
+
• Auto (top_k > 0): build a benign-target pool from the top-K most frequent
|
|
176
|
+
BARE labels (no '/') of `target_node_type` seen in the training split.
|
|
177
|
+
Shuffle by `seed`, then assign one target to each attack entity (cycled
|
|
178
|
+
if entities > pool). When the matched node was a path-style label
|
|
179
|
+
(`/<dir>/<base>`), the target preserves the prefix: the swap label
|
|
180
|
+
becomes `/<dir>/<assigned-target>`.
|
|
181
|
+
• Manual (top_k == 0): every attack entity uses the single `target_label`,
|
|
182
|
+
with the same prefix-preservation rule for path-style matches.
|
|
183
|
+
|
|
184
|
+
The target embedding is computed by the same model+tokenizer used for every
|
|
185
|
+
other node, so any continue-pretraining adaptation flows through. Train and
|
|
186
|
+
val embeddings are untouched (matches the inference-time threat model).
|
|
187
|
+
"""
|
|
188
|
+
import random
|
|
189
|
+
|
|
190
|
+
ra_cfg = getattr(cfg.feat_inference, "rename_attack", None)
|
|
191
|
+
if ra_cfg is None or not getattr(ra_cfg, "enabled", False):
|
|
192
|
+
return indexid2vec
|
|
193
|
+
|
|
194
|
+
raw_entities = getattr(ra_cfg, "entities", "") or ""
|
|
195
|
+
entity_list = [e.strip() for e in raw_entities.split(",") if e.strip()]
|
|
196
|
+
if not entity_list:
|
|
197
|
+
log("rename_attack enabled but `entities` is empty — skipping.")
|
|
198
|
+
return indexid2vec
|
|
199
|
+
|
|
200
|
+
target_ntype = ra_cfg.target_node_type
|
|
201
|
+
top_k = int(getattr(ra_cfg, "top_k", 0) or 0)
|
|
202
|
+
seed = int(getattr(ra_cfg, "seed", 0) or 0)
|
|
203
|
+
target_label_manual = (getattr(ra_cfg, "target_label", "") or "").strip()
|
|
204
|
+
|
|
205
|
+
# Guard against the one model variant whose embedding dim diverges from the
|
|
206
|
+
# raw-encoder mean-pool path used by _embed_labels.
|
|
207
|
+
pretrain_cfg = cfg.featurization.pretrained
|
|
208
|
+
if (
|
|
209
|
+
pretrain_cfg.model_type == "behavior_cluster"
|
|
210
|
+
and getattr(pretrain_cfg.behavior_cluster, "use_contrastive_head", False)
|
|
211
|
+
):
|
|
212
|
+
log("rename_attack: not supported with behavior_cluster + use_contrastive_head=True; skipping.")
|
|
213
|
+
return indexid2vec
|
|
214
|
+
|
|
215
|
+
# ── Build target pool / assignment ─────────────────────────────────
|
|
216
|
+
base_dir = cfg.transformation._graphs_dir
|
|
217
|
+
split_to_files = get_split_to_files(cfg, base_dir)
|
|
218
|
+
|
|
219
|
+
if top_k > 0:
|
|
220
|
+
# Auto mode: count BARE labels of `target_ntype` in the train split.
|
|
221
|
+
train_paths = split_to_files.get("train", [])
|
|
222
|
+
if not train_paths:
|
|
223
|
+
log("rename_attack: top_k>0 but no training graphs found — skipping.")
|
|
224
|
+
return indexid2vec
|
|
225
|
+
attack_set = set(entity_list)
|
|
226
|
+
label_counts = {}
|
|
227
|
+
for path in train_paths:
|
|
228
|
+
try:
|
|
229
|
+
g = torch.load(path)
|
|
230
|
+
except Exception as e:
|
|
231
|
+
log(f"rename_attack: could not load train graph {path}: {e}")
|
|
232
|
+
continue
|
|
233
|
+
for n in g.nodes():
|
|
234
|
+
nid = str(n)
|
|
235
|
+
if nid not in indexid2msg:
|
|
236
|
+
continue
|
|
237
|
+
ntype, nlabel = indexid2msg[nid]
|
|
238
|
+
nlabel = nlabel or ""
|
|
239
|
+
if ntype != target_ntype:
|
|
240
|
+
continue
|
|
241
|
+
# Want bare names only, so suffix-match swaps can preserve the prefix
|
|
242
|
+
if "/" in nlabel:
|
|
243
|
+
continue
|
|
244
|
+
if nlabel in attack_set:
|
|
245
|
+
continue
|
|
246
|
+
label_counts[nlabel] = label_counts.get(nlabel, 0) + 1
|
|
247
|
+
ranked = sorted(label_counts.items(), key=lambda kv: (-kv[1], kv[0]))
|
|
248
|
+
pool = [lbl for lbl, _ in ranked[:top_k]]
|
|
249
|
+
if not pool:
|
|
250
|
+
log("rename_attack: no benign target candidates in train — skipping.")
|
|
251
|
+
return indexid2vec
|
|
252
|
+
rng = random.Random(seed)
|
|
253
|
+
shuffled_pool = list(pool)
|
|
254
|
+
rng.shuffle(shuffled_pool)
|
|
255
|
+
targets_by_entity = {
|
|
256
|
+
e: shuffled_pool[i % len(shuffled_pool)] for i, e in enumerate(entity_list)
|
|
257
|
+
}
|
|
258
|
+
log(
|
|
259
|
+
f"rename_attack (auto): pool of {len(pool)} benign targets from train top-{top_k} "
|
|
260
|
+
f"(target_ntype={target_ntype}, seed={seed})"
|
|
261
|
+
)
|
|
262
|
+
log(f" per-entity target assignment: {targets_by_entity}")
|
|
263
|
+
else:
|
|
264
|
+
if not target_label_manual:
|
|
265
|
+
log("rename_attack: top_k=0 and target_label is empty — skipping.")
|
|
266
|
+
return indexid2vec
|
|
267
|
+
targets_by_entity = {e: target_label_manual for e in entity_list}
|
|
268
|
+
log(f"rename_attack (manual): target_label={target_label_manual!r} applied to all entities.")
|
|
269
|
+
|
|
270
|
+
# ── Test-set node IDs ──────────────────────────────────────────────
|
|
271
|
+
test_paths = split_to_files.get("test", [])
|
|
272
|
+
test_node_ids = set()
|
|
273
|
+
for path in test_paths:
|
|
274
|
+
try:
|
|
275
|
+
g = torch.load(path)
|
|
276
|
+
except Exception as e:
|
|
277
|
+
log(f"rename_attack: could not load test graph {path}: {e}")
|
|
278
|
+
continue
|
|
279
|
+
for n in g.nodes():
|
|
280
|
+
test_node_ids.add(int(n))
|
|
281
|
+
if not test_node_ids:
|
|
282
|
+
log("rename_attack: no test-graph node IDs found — skipping rename.")
|
|
283
|
+
return indexid2vec
|
|
284
|
+
|
|
285
|
+
# ── Target embedding cache: computed lazily via the same model+tokenizer ──
|
|
286
|
+
target_emb_cache = {}
|
|
287
|
+
def _get_target_emb(swap_label):
|
|
288
|
+
key = (target_ntype, swap_label)
|
|
289
|
+
if key in target_emb_cache:
|
|
290
|
+
return target_emb_cache[key]
|
|
291
|
+
emb_dict = _embed_labels(bert, tokenizer, [key], output_dim, device)
|
|
292
|
+
emb = emb_dict.get(key)
|
|
293
|
+
if emb is None or float(np.linalg.norm(emb)) < 1e-12:
|
|
294
|
+
target_emb_cache[key] = None
|
|
295
|
+
return None
|
|
296
|
+
target_emb_cache[key] = emb
|
|
297
|
+
return emb
|
|
298
|
+
|
|
299
|
+
# Pre-build suffix patterns once.
|
|
300
|
+
suffixes = [(e, "/" + e) for e in entity_list]
|
|
301
|
+
|
|
302
|
+
# ── Walk indexid2msg, match, and swap ──────────────────────────────
|
|
303
|
+
renamed = 0
|
|
304
|
+
skipped_non_test = 0
|
|
305
|
+
skipped_wrong_ntype = 0
|
|
306
|
+
skipped_zero_target = 0
|
|
307
|
+
per_entity_counts = {e: 0 for e in entity_list}
|
|
308
|
+
matched_examples = []
|
|
309
|
+
|
|
310
|
+
for node_id, (ntype, nlabel) in indexid2msg.items():
|
|
311
|
+
nlabel = nlabel or ""
|
|
312
|
+
# Find which attack entity this label corresponds to (if any).
|
|
313
|
+
matched_entity, match_kind = None, None
|
|
314
|
+
for e in entity_list:
|
|
315
|
+
if nlabel == e:
|
|
316
|
+
matched_entity, match_kind = e, "exact"
|
|
317
|
+
break
|
|
318
|
+
if matched_entity is None:
|
|
319
|
+
for e, suffix in suffixes:
|
|
320
|
+
if nlabel.endswith(suffix):
|
|
321
|
+
matched_entity, match_kind = e, "suffix"
|
|
322
|
+
break
|
|
323
|
+
if matched_entity is None:
|
|
324
|
+
continue
|
|
325
|
+
|
|
326
|
+
if ntype != target_ntype:
|
|
327
|
+
skipped_wrong_ntype += 1
|
|
328
|
+
continue
|
|
329
|
+
int_id = int(node_id)
|
|
330
|
+
if int_id not in test_node_ids:
|
|
331
|
+
skipped_non_test += 1
|
|
332
|
+
continue
|
|
333
|
+
if int_id not in indexid2vec:
|
|
334
|
+
continue
|
|
335
|
+
|
|
336
|
+
# Build the swap label, preserving prefix on suffix matches.
|
|
337
|
+
base_target = targets_by_entity[matched_entity]
|
|
338
|
+
if match_kind == "exact":
|
|
339
|
+
swap_label = base_target
|
|
340
|
+
else:
|
|
341
|
+
prefix = nlabel[:-len(matched_entity)] # ends with "/"
|
|
342
|
+
swap_label = prefix + base_target
|
|
343
|
+
|
|
344
|
+
emb = _get_target_emb(swap_label)
|
|
345
|
+
if emb is None:
|
|
346
|
+
skipped_zero_target += 1
|
|
347
|
+
continue
|
|
348
|
+
|
|
349
|
+
indexid2vec[int_id] = emb
|
|
350
|
+
renamed += 1
|
|
351
|
+
per_entity_counts[matched_entity] += 1
|
|
352
|
+
if len(matched_examples) < 8:
|
|
353
|
+
matched_examples.append(f"({ntype}, {nlabel!r}) -> {swap_label!r}")
|
|
354
|
+
|
|
355
|
+
log(
|
|
356
|
+
f"rename_attack: renamed {renamed:,} test-set node embeddings | "
|
|
357
|
+
f"skipped {skipped_non_test:,} outside test | "
|
|
358
|
+
f"skipped {skipped_wrong_ntype:,} wrong ntype | "
|
|
359
|
+
f"skipped {skipped_zero_target:,} zero-target-emb"
|
|
360
|
+
)
|
|
361
|
+
if matched_examples:
|
|
362
|
+
log(" examples: " + " ; ".join(matched_examples))
|
|
363
|
+
log(" per-entity rename counts: " + ", ".join(f"{e}={n}" for e, n in per_entity_counts.items()))
|
|
364
|
+
|
|
365
|
+
return indexid2vec
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def _maybe_embed_synthetic_nodes(cfg, bert, tokenizer, hidden_size, device):
|
|
369
|
+
"""Compute and save T5 embeddings for synthetic attack node labels if configured."""
|
|
370
|
+
import yaml
|
|
371
|
+
from pidsmaker.config.pipeline import ROOT_PROJECT_PATH
|
|
372
|
+
|
|
373
|
+
try:
|
|
374
|
+
obj_cfg = cfg.training.decoder.predict_edge_supervised
|
|
375
|
+
mode = getattr(obj_cfg, "mode", "").strip()
|
|
376
|
+
attack_edges_path = getattr(obj_cfg, "attack_edges_path", None)
|
|
377
|
+
except AttributeError:
|
|
378
|
+
return
|
|
379
|
+
|
|
380
|
+
if mode != "synthetic" or not attack_edges_path or attack_edges_path == "none":
|
|
381
|
+
return
|
|
382
|
+
|
|
383
|
+
if not os.path.isabs(attack_edges_path):
|
|
384
|
+
attack_edges_path = os.path.join(ROOT_PROJECT_PATH, attack_edges_path)
|
|
385
|
+
|
|
386
|
+
if not os.path.exists(attack_edges_path):
|
|
387
|
+
raise FileNotFoundError(
|
|
388
|
+
f"predict_edge_supervised (synthetic mode): attack_edges_path not found: {attack_edges_path}"
|
|
389
|
+
)
|
|
390
|
+
|
|
391
|
+
with open(attack_edges_path) as f:
|
|
392
|
+
data = yaml.safe_load(f)
|
|
393
|
+
attack_edges = data.get("attack_edges", [])
|
|
394
|
+
|
|
395
|
+
keys = []
|
|
396
|
+
for edge in attack_edges:
|
|
397
|
+
keys.append((edge["src_type"], edge["src_label"]))
|
|
398
|
+
keys.append((edge["dst_type"], edge["dst_label"]))
|
|
399
|
+
|
|
400
|
+
log(f"Embedding {len(set(keys))} unique synthetic attack node labels ...")
|
|
401
|
+
synth_embs = _embed_labels(bert, tokenizer, keys, hidden_size, device)
|
|
402
|
+
|
|
403
|
+
out_path = os.path.join(cfg.featurization._model_dir, "synthetic_attack_node_embeddings.pt")
|
|
404
|
+
torch.save(synth_embs, out_path)
|
|
405
|
+
log(f"Saved synthetic attack node embeddings -> {out_path}")
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def _continue_pretrain_gnn_distill(cfg, model, tokenizer, pretrain_cfg, inference_cfg, device):
|
|
409
|
+
"""Continue pretraining the GNN distillation model on the target dataset.
|
|
410
|
+
|
|
411
|
+
Builds a sampler from the target dataset's graphs, then runs additional
|
|
412
|
+
GNN distillation training (same loss as pretraining) to adapt the model
|
|
413
|
+
to the specific dataset before inference.
|
|
414
|
+
"""
|
|
415
|
+
import random
|
|
416
|
+
import time
|
|
417
|
+
from collections import defaultdict
|
|
418
|
+
from copy import deepcopy
|
|
419
|
+
|
|
420
|
+
from torch.optim import AdamW
|
|
421
|
+
|
|
422
|
+
from pidsmaker.pretrained.models.gnn_distill import (
|
|
423
|
+
NeighborhoodGNNTeacher, build_edge_type_encoder,
|
|
424
|
+
build_gnn_distill_batch,
|
|
425
|
+
)
|
|
426
|
+
from pidsmaker.pretrained.models.graphmae import sce_loss
|
|
427
|
+
from pidsmaker.pretrained.data.sampler import ProvenanceWalkSampler
|
|
428
|
+
from pidsmaker.utils.utils import get_all_graphs_for_dates, get_indexid2msg
|
|
429
|
+
|
|
430
|
+
distill_cfg = pretrain_cfg.gnn_distill
|
|
431
|
+
continue_epochs = inference_cfg.continue_pretrain_epochs
|
|
432
|
+
lr_factor = inference_cfg.continue_pretrain_lr_factor
|
|
433
|
+
gnn_edge_emb_dim = distill_cfg.emb_dim
|
|
434
|
+
gnn_hidden_dim = distill_cfg.hidden_dim
|
|
435
|
+
gnn_num_layers = distill_cfg.num_layers
|
|
436
|
+
gnn_num_heads = distill_cfg.num_heads
|
|
437
|
+
gnn_n_neighbors_min = distill_cfg.n_neighbors_min
|
|
438
|
+
gnn_n_neighbors_max = distill_cfg.n_neighbors_max
|
|
439
|
+
gnn_diverse = distill_cfg.diverse_neighbors
|
|
440
|
+
distill_lambda = distill_cfg.loss_weight
|
|
441
|
+
gnn_loss_lambda = distill_cfg.gnn_loss_weight
|
|
442
|
+
gnn_lr = distill_cfg.gnn_lr
|
|
443
|
+
ema_momentum = distill_cfg.ema_momentum
|
|
444
|
+
batch_size = pretrain_cfg.training.batch_size
|
|
445
|
+
|
|
446
|
+
log("Continue-pretraining (gnn_distill) on target dataset ...")
|
|
447
|
+
|
|
448
|
+
# Expand IPs for domain adaptation: keep [PRIVATE_IP]/[PUBLIC_IP] + add raw IPs
|
|
449
|
+
if tokenizer.normalize_netflow_ips:
|
|
450
|
+
tokenizer.expand_netflow_ips = True
|
|
451
|
+
log(" Enabled IP expansion for continue-pretraining ([CATEGORY] + raw IP)")
|
|
452
|
+
|
|
453
|
+
# Load target dataset graphs
|
|
454
|
+
base_dir = cfg.transformation._graphs_dir
|
|
455
|
+
train_files = get_all_graphs_for_dates(base_dir, cfg.dataset.train_dates)
|
|
456
|
+
if not train_files:
|
|
457
|
+
log(" No graph files found for continue-pretraining, skipping")
|
|
458
|
+
return model
|
|
459
|
+
|
|
460
|
+
import torch as _torch
|
|
461
|
+
from pidsmaker.pretrained.pretrain.pretrain_common import _load_and_merge_graphs
|
|
462
|
+
graph_context_mode = getattr(pretrain_cfg, "graph_context_mode", "single")
|
|
463
|
+
graphs = _load_and_merge_graphs(train_files, graph_context_mode)
|
|
464
|
+
log(f" Loaded {len(graphs)} graph(s) from {len(train_files)} files")
|
|
465
|
+
|
|
466
|
+
ds_indexid2msg = get_indexid2msg(cfg)
|
|
467
|
+
# Build samplers
|
|
468
|
+
sampler_pairs = []
|
|
469
|
+
for g in graphs:
|
|
470
|
+
sampler = ProvenanceWalkSampler(g, walk_length=30, num_walks=10)
|
|
471
|
+
sampler_pairs.append((sampler, ds_indexid2msg))
|
|
472
|
+
|
|
473
|
+
# Build edge type encoder
|
|
474
|
+
edge_type2idx = build_edge_type_encoder(sampler_pairs)
|
|
475
|
+
|
|
476
|
+
# Build GNN teacher
|
|
477
|
+
t5_hidden_dim = model.config.d_model
|
|
478
|
+
gnn_teacher = NeighborhoodGNNTeacher(
|
|
479
|
+
node_dim=t5_hidden_dim,
|
|
480
|
+
num_edge_types=max(len(edge_type2idx), 1),
|
|
481
|
+
edge_emb_dim=gnn_edge_emb_dim,
|
|
482
|
+
hidden_dim=gnn_hidden_dim,
|
|
483
|
+
num_layers=gnn_num_layers,
|
|
484
|
+
num_heads=gnn_num_heads,
|
|
485
|
+
edge_projection=distill_cfg.edge_projection,
|
|
486
|
+
).to(device)
|
|
487
|
+
|
|
488
|
+
# EMA teacher
|
|
489
|
+
ema_teacher = deepcopy(model).to(device)
|
|
490
|
+
ema_teacher.requires_grad_(False)
|
|
491
|
+
ema_teacher.eval()
|
|
492
|
+
|
|
493
|
+
# Collect entities grouped by label
|
|
494
|
+
combined_indexid2msg = {}
|
|
495
|
+
label_to_entities = defaultdict(list)
|
|
496
|
+
for sidx, (sampler, im) in enumerate(sampler_pairs):
|
|
497
|
+
for node in sampler.nodes:
|
|
498
|
+
if node in im:
|
|
499
|
+
ntype, nlabel = im[node]
|
|
500
|
+
entity_ids = tokenizer.tokenize_node(ntype, nlabel)
|
|
501
|
+
if entity_ids:
|
|
502
|
+
label_key = (ntype, nlabel)
|
|
503
|
+
label_to_entities[label_key].append((node, sidx, entity_ids))
|
|
504
|
+
combined_indexid2msg[node] = (ntype, nlabel)
|
|
505
|
+
|
|
506
|
+
n_labels = len(label_to_entities)
|
|
507
|
+
log(f" {n_labels:,} unique labels for continue-pretraining")
|
|
508
|
+
|
|
509
|
+
if n_labels == 0:
|
|
510
|
+
log(" No trainable entities, skipping")
|
|
511
|
+
return model
|
|
512
|
+
|
|
513
|
+
# Optimizer — reduced LR with short linear warmup
|
|
514
|
+
model.train()
|
|
515
|
+
base_lr = pretrain_cfg.training.lr * lr_factor
|
|
516
|
+
gnn_continue_lr = gnn_lr * lr_factor
|
|
517
|
+
opt = AdamW([
|
|
518
|
+
{"params": model.parameters(), "lr": base_lr},
|
|
519
|
+
{"params": gnn_teacher.parameters(), "lr": gnn_continue_lr},
|
|
520
|
+
], betas=(0.9, 0.95), eps=1e-8, weight_decay=0.01)
|
|
521
|
+
# Store initial LRs for warmup
|
|
522
|
+
for pg in opt.param_groups:
|
|
523
|
+
pg["initial_lr"] = pg["lr"]
|
|
524
|
+
|
|
525
|
+
# Linear warmup over 10% of first epoch
|
|
526
|
+
warmup_steps = max(1, n_labels // batch_size // 10)
|
|
527
|
+
total_steps = (n_labels // batch_size + 1) * continue_epochs
|
|
528
|
+
|
|
529
|
+
processed_tokens = 0
|
|
530
|
+
updates = 0
|
|
531
|
+
epoch = 0
|
|
532
|
+
st = time.time()
|
|
533
|
+
|
|
534
|
+
while epoch < continue_epochs:
|
|
535
|
+
epoch += 1
|
|
536
|
+
epoch_entities = []
|
|
537
|
+
for label_key, entities in label_to_entities.items():
|
|
538
|
+
pick = entities[(epoch - 1) % len(entities)]
|
|
539
|
+
epoch_entities.append(pick)
|
|
540
|
+
random.shuffle(epoch_entities)
|
|
541
|
+
|
|
542
|
+
for batch_start in range(0, len(epoch_entities), batch_size):
|
|
543
|
+
batch_ents = epoch_entities[batch_start:batch_start + batch_size]
|
|
544
|
+
B = len(batch_ents)
|
|
545
|
+
if B == 0:
|
|
546
|
+
continue
|
|
547
|
+
|
|
548
|
+
enc_ids_list = [ent[2] for ent in batch_ents]
|
|
549
|
+
max_enc = min(max(len(e) for e in enc_ids_list), tokenizer.max_seq_len)
|
|
550
|
+
input_ids = _torch.full((B, max_enc), tokenizer.pad_id, dtype=_torch.long)
|
|
551
|
+
attention_mask = _torch.zeros(B, max_enc, dtype=_torch.bool)
|
|
552
|
+
for i, enc in enumerate(enc_ids_list):
|
|
553
|
+
seq_len = min(len(enc), max_enc)
|
|
554
|
+
input_ids[i, :seq_len] = _torch.tensor(enc[:seq_len])
|
|
555
|
+
attention_mask[i, :seq_len] = True
|
|
556
|
+
|
|
557
|
+
entity_nodes = [ent[0] for ent in batch_ents]
|
|
558
|
+
sampler_idxs = [ent[1] for ent in batch_ents]
|
|
559
|
+
|
|
560
|
+
gnn_batch = build_gnn_distill_batch(
|
|
561
|
+
entity_nodes, sampler_idxs, sampler_pairs,
|
|
562
|
+
combined_indexid2msg, edge_type2idx,
|
|
563
|
+
n_neighbors_min=gnn_n_neighbors_min, n_neighbors_max=gnn_n_neighbors_max,
|
|
564
|
+
diverse=gnn_diverse, device=device,
|
|
565
|
+
)
|
|
566
|
+
if gnn_batch is None:
|
|
567
|
+
continue
|
|
568
|
+
|
|
569
|
+
node_labels, edge_index, edge_types, batch_vec, center_idx, valid_mask = gnn_batch
|
|
570
|
+
n_valid = valid_mask.sum().item()
|
|
571
|
+
if n_valid == 0:
|
|
572
|
+
continue
|
|
573
|
+
|
|
574
|
+
# EMA encode neighbors
|
|
575
|
+
unique_labels = list(set(node_labels))
|
|
576
|
+
label_to_uidx = {lbl: i for i, lbl in enumerate(unique_labels)}
|
|
577
|
+
ema_tids = []
|
|
578
|
+
for ntype, nlabel in unique_labels:
|
|
579
|
+
tids = tokenizer.tokenize_node(ntype, nlabel)
|
|
580
|
+
ema_tids.append(tids if tids else [tokenizer.pad_id])
|
|
581
|
+
max_ema_len = min(max(len(t) for t in ema_tids), tokenizer.max_seq_len)
|
|
582
|
+
N_unique = len(ema_tids)
|
|
583
|
+
ema_input_ids = _torch.full((N_unique, max_ema_len), tokenizer.pad_id, dtype=_torch.long)
|
|
584
|
+
ema_attn_mask = _torch.zeros(N_unique, max_ema_len, dtype=_torch.bool)
|
|
585
|
+
for i, tids in enumerate(ema_tids):
|
|
586
|
+
L = min(len(tids), max_ema_len)
|
|
587
|
+
ema_input_ids[i, :L] = _torch.tensor(tids[:L])
|
|
588
|
+
ema_attn_mask[i, :L] = True
|
|
589
|
+
|
|
590
|
+
with _torch.no_grad():
|
|
591
|
+
ema_embeddings = ema_teacher.mean_pool(ema_input_ids, ema_attn_mask)
|
|
592
|
+
node_emb_idx = [label_to_uidx[lbl] for lbl in node_labels]
|
|
593
|
+
node_embeddings = ema_embeddings[_torch.tensor(node_emb_idx, dtype=_torch.long)]
|
|
594
|
+
|
|
595
|
+
# Forward
|
|
596
|
+
model.train()
|
|
597
|
+
gnn_teacher.train()
|
|
598
|
+
out = model.modified_fwd(input_ids.to(device), attention_mask.to(device))
|
|
599
|
+
t5_projected = out.projected
|
|
600
|
+
|
|
601
|
+
gnn_recon_loss, gnn_encoded = gnn_teacher(
|
|
602
|
+
node_embeddings, edge_index, edge_types, batch_vec, center_idx,
|
|
603
|
+
)
|
|
604
|
+
gnn_targets = gnn_encoded[center_idx].detach()
|
|
605
|
+
distill_loss = sce_loss(t5_projected[valid_mask], gnn_targets)
|
|
606
|
+
total_loss = distill_lambda * distill_loss + gnn_loss_lambda * gnn_recon_loss
|
|
607
|
+
|
|
608
|
+
total_loss.backward()
|
|
609
|
+
_torch.nn.utils.clip_grad_norm_(model.parameters(), 5.0)
|
|
610
|
+
_torch.nn.utils.clip_grad_norm_(gnn_teacher.parameters(), 5.0)
|
|
611
|
+
opt.step()
|
|
612
|
+
opt.zero_grad()
|
|
613
|
+
|
|
614
|
+
# Linear warmup
|
|
615
|
+
updates += 1
|
|
616
|
+
if updates <= warmup_steps:
|
|
617
|
+
warmup_scale = updates / warmup_steps
|
|
618
|
+
for pg in opt.param_groups:
|
|
619
|
+
pg["lr"] = pg["initial_lr"] * warmup_scale if "initial_lr" in pg else pg["lr"]
|
|
620
|
+
|
|
621
|
+
# EMA update
|
|
622
|
+
with _torch.no_grad():
|
|
623
|
+
for ema_p, student_p in zip(ema_teacher.parameters(), model.parameters()):
|
|
624
|
+
ema_p.data.mul_(ema_momentum).add_(student_p.data, alpha=1.0 - ema_momentum)
|
|
625
|
+
|
|
626
|
+
n_tokens = int(attention_mask.sum().item())
|
|
627
|
+
processed_tokens += n_tokens
|
|
628
|
+
|
|
629
|
+
if updates % 50 == 0:
|
|
630
|
+
log(f" [continue] e{epoch}/{continue_epochs} step={updates} "
|
|
631
|
+
f"d_loss={distill_loss.item():.4f} g_loss={gnn_recon_loss.item():.4f} "
|
|
632
|
+
f"({time.time()-st:.1f}s)")
|
|
633
|
+
|
|
634
|
+
model.eval()
|
|
635
|
+
elapsed = time.time() - st
|
|
636
|
+
log(f" Continue-pretraining done: {updates} steps, {epoch} epochs, "
|
|
637
|
+
f"{processed_tokens:,} tokens ({elapsed:.1f}s)")
|
|
638
|
+
|
|
639
|
+
# Restore tokenizer for inference
|
|
640
|
+
tokenizer.expand_netflow_ips = False
|
|
641
|
+
|
|
642
|
+
# Clean up
|
|
643
|
+
del gnn_teacher, ema_teacher, opt
|
|
644
|
+
if _torch.cuda.is_available():
|
|
645
|
+
_torch.cuda.empty_cache()
|
|
646
|
+
|
|
647
|
+
return model
|
|
648
|
+
|
|
649
|
+
|
|
650
|
+
def _load_target_graphs_and_samplers(cfg, pretrain_cfg):
|
|
651
|
+
"""Load target dataset graphs and build walk samplers. Shared by all continue-pretrain functions."""
|
|
652
|
+
from pidsmaker.pretrained.data.sampler import ProvenanceWalkSampler
|
|
653
|
+
from pidsmaker.utils.utils import get_all_graphs_for_dates, get_indexid2msg
|
|
654
|
+
|
|
655
|
+
base_dir = cfg.transformation._graphs_dir
|
|
656
|
+
train_files = get_all_graphs_for_dates(base_dir, cfg.dataset.train_dates)
|
|
657
|
+
if not train_files:
|
|
658
|
+
return None, None, None
|
|
659
|
+
|
|
660
|
+
from pidsmaker.pretrained.pretrain.pretrain_common import _load_and_merge_graphs
|
|
661
|
+
graph_context_mode = getattr(pretrain_cfg, "graph_context_mode", "single")
|
|
662
|
+
graphs = _load_and_merge_graphs(train_files, graph_context_mode)
|
|
663
|
+
log(f" Loaded {len(graphs)} graph(s) from {len(train_files)} files")
|
|
664
|
+
|
|
665
|
+
ds_indexid2msg = get_indexid2msg(cfg)
|
|
666
|
+
walks_cfg = pretrain_cfg.walks
|
|
667
|
+
walk_length = walks_cfg.walk_length
|
|
668
|
+
num_walks = walks_cfg.num_walks
|
|
669
|
+
|
|
670
|
+
sampler_pairs = []
|
|
671
|
+
for g in graphs:
|
|
672
|
+
sampler = ProvenanceWalkSampler(g, walk_length=walk_length, num_walks=num_walks)
|
|
673
|
+
sampler_pairs.append((sampler, ds_indexid2msg))
|
|
674
|
+
|
|
675
|
+
return sampler_pairs, ds_indexid2msg, graphs
|
|
676
|
+
|
|
677
|
+
|
|
678
|
+
def _continue_pretrain_spider(cfg, model, tokenizer, pretrain_cfg, inference_cfg, device):
|
|
679
|
+
"""Continue pretraining a spider model on the target dataset.
|
|
680
|
+
|
|
681
|
+
Rebuilds behavior signatures and entity classes from the target graph,
|
|
682
|
+
then fine-tunes using the same SupCon + distillation loss as pretraining
|
|
683
|
+
at a reduced LR.
|
|
684
|
+
"""
|
|
685
|
+
import random
|
|
686
|
+
import time
|
|
687
|
+
from collections import defaultdict
|
|
688
|
+
from copy import deepcopy
|
|
689
|
+
|
|
690
|
+
import torch as _torch
|
|
691
|
+
from torch.optim import AdamW
|
|
692
|
+
|
|
693
|
+
from pidsmaker.pretrained.models.spider import (
|
|
694
|
+
GNNClusterTeacher,
|
|
695
|
+
build_gnn_distill_batch, build_edge_type_encoder,
|
|
696
|
+
supervised_contrastive_loss, sce_loss,
|
|
697
|
+
StudentSignatureHead, StudentClassHead, TeacherClassHead,
|
|
698
|
+
)
|
|
699
|
+
from pidsmaker.pretrained.data.behavior_signatures import (
|
|
700
|
+
build_behavior_dataset,
|
|
701
|
+
BehaviorLabelVocab,
|
|
702
|
+
)
|
|
703
|
+
from pidsmaker.pretrained.data.entity_classes import classify_entity
|
|
704
|
+
from pidsmaker.pretrained.training_utils import build_pk_batches
|
|
705
|
+
|
|
706
|
+
gc_cfg = pretrain_cfg.spider
|
|
707
|
+
continue_epochs = inference_cfg.continue_pretrain_epochs
|
|
708
|
+
lr_factor = inference_cfg.continue_pretrain_lr_factor
|
|
709
|
+
batch_size = pretrain_cfg.training.batch_size
|
|
710
|
+
|
|
711
|
+
gc_edge_emb_dim = gc_cfg.emb_dim
|
|
712
|
+
gc_hidden_dim = gc_cfg.hidden_dim
|
|
713
|
+
gc_proj_dim = gc_cfg.proj_dim
|
|
714
|
+
gc_num_heads = gc_cfg.num_heads
|
|
715
|
+
gc_n_neighbors_min = gc_cfg.n_neighbors_min
|
|
716
|
+
gc_n_neighbors_max = gc_cfg.n_neighbors_max
|
|
717
|
+
gc_diverse = gc_cfg.diverse_neighbors
|
|
718
|
+
gc_filter_noisy = gc_cfg.filter_noisy_edges
|
|
719
|
+
gc_ema_momentum = gc_cfg.ema_momentum
|
|
720
|
+
gc_supcon_weight = gc_cfg.supcon_weight
|
|
721
|
+
gc_distill_weight = gc_cfg.distill_weight
|
|
722
|
+
gc_temperature = gc_cfg.temperature
|
|
723
|
+
gc_min_sig_size = gc_cfg.min_signature_size
|
|
724
|
+
gc_min_per_class = gc_cfg.min_entities_per_class
|
|
725
|
+
gc_max_per_class = gc_cfg.max_entities_per_class
|
|
726
|
+
gc_samples_per_class = gc_cfg.samples_per_class
|
|
727
|
+
gc_distill_loss = getattr(gc_cfg, 'distill_loss', 'sce')
|
|
728
|
+
gc_teacher_loss = getattr(gc_cfg, 'teacher_loss', 'contrastive')
|
|
729
|
+
gc_teacher_data = getattr(gc_cfg, 'teacher_data', 'signature,gnn_emb')
|
|
730
|
+
gc_student_only_mode = getattr(gc_cfg, 'student_only_mode', 'none')
|
|
731
|
+
use_teacher = gc_student_only_mode == "none"
|
|
732
|
+
|
|
733
|
+
log("Continue-pretraining (spider) on target dataset ...")
|
|
734
|
+
|
|
735
|
+
# Expand IPs for domain adaptation
|
|
736
|
+
if tokenizer.normalize_netflow_ips:
|
|
737
|
+
tokenizer.expand_netflow_ips = True
|
|
738
|
+
log(" Enabled IP expansion for continue-pretraining ([CATEGORY] + raw IP)")
|
|
739
|
+
|
|
740
|
+
result = _load_target_graphs_and_samplers(cfg, pretrain_cfg)
|
|
741
|
+
if result[0] is None:
|
|
742
|
+
log(" No graph files found, skipping")
|
|
743
|
+
return model
|
|
744
|
+
sampler_pairs, ds_indexid2msg, _ = result
|
|
745
|
+
|
|
746
|
+
combined_indexid2msg = {}
|
|
747
|
+
for _, im in sampler_pairs:
|
|
748
|
+
combined_indexid2msg.update(im)
|
|
749
|
+
|
|
750
|
+
# Resolve pretrained model directory (needed for edge_type2idx + vocab)
|
|
751
|
+
pretrain_dir = cfg.featurization._model_dir
|
|
752
|
+
_pmp = getattr(pretrain_cfg, 'weights_path', None)
|
|
753
|
+
if _pmp:
|
|
754
|
+
pretrain_dir = _pmp
|
|
755
|
+
|
|
756
|
+
# Load edge type encoder from pretrained checkpoint to keep indices consistent
|
|
757
|
+
import json as _json
|
|
758
|
+
edge_type2idx_path = os.path.join(pretrain_dir, "edge_type2idx.json")
|
|
759
|
+
if os.path.exists(edge_type2idx_path):
|
|
760
|
+
with open(edge_type2idx_path) as f:
|
|
761
|
+
edge_type2idx = _json.load(f)
|
|
762
|
+
# Add any new edge types from the target dataset
|
|
763
|
+
local_edge_type2idx = build_edge_type_encoder(sampler_pairs)
|
|
764
|
+
for et in local_edge_type2idx:
|
|
765
|
+
if et not in edge_type2idx:
|
|
766
|
+
edge_type2idx[et] = len(edge_type2idx)
|
|
767
|
+
log(f" Loaded {len(edge_type2idx)} edge types from pretrained checkpoint "
|
|
768
|
+
f"({len(local_edge_type2idx)} in target dataset)")
|
|
769
|
+
else:
|
|
770
|
+
edge_type2idx = build_edge_type_encoder(sampler_pairs)
|
|
771
|
+
|
|
772
|
+
# Build behavior signatures from target graph
|
|
773
|
+
label_to_signature, label_to_entities_raw, vocab = build_behavior_dataset(
|
|
774
|
+
sampler_pairs, combined_indexid2msg,
|
|
775
|
+
filter_noisy=gc_filter_noisy,
|
|
776
|
+
min_signature_size=gc_min_sig_size,
|
|
777
|
+
)
|
|
778
|
+
log(f" {len(label_to_signature):,} unique entity labels, "
|
|
779
|
+
f"{vocab.size:,} behavior labels")
|
|
780
|
+
|
|
781
|
+
if not label_to_signature:
|
|
782
|
+
log(" No signatures, skipping")
|
|
783
|
+
return model
|
|
784
|
+
|
|
785
|
+
# Load pretrained vocab for target vectors (must match model's num_labels)
|
|
786
|
+
pretrain_vocab = BehaviorLabelVocab()
|
|
787
|
+
bvocab_path = os.path.join(pretrain_dir, "behavior_vocab.txt")
|
|
788
|
+
if os.path.exists(bvocab_path):
|
|
789
|
+
pretrain_vocab.load(bvocab_path)
|
|
790
|
+
else:
|
|
791
|
+
log(" No pretrained behavior_vocab.txt found, skipping")
|
|
792
|
+
return model
|
|
793
|
+
|
|
794
|
+
# Tokenize entities
|
|
795
|
+
label_to_entities = defaultdict(list)
|
|
796
|
+
for label_key, raw_entities in label_to_entities_raw.items():
|
|
797
|
+
ntype, nlabel = label_key
|
|
798
|
+
entity_ids = tokenizer.tokenize_node(ntype, nlabel)
|
|
799
|
+
if entity_ids:
|
|
800
|
+
for node_id, sidx in raw_entities:
|
|
801
|
+
label_to_entities[label_key].append((node_id, sidx, entity_ids))
|
|
802
|
+
|
|
803
|
+
# Build signature target vectors using pretrained vocab
|
|
804
|
+
label_to_target = {}
|
|
805
|
+
for label_key, sig in label_to_signature.items():
|
|
806
|
+
if label_key in label_to_entities:
|
|
807
|
+
label_to_target[label_key] = pretrain_vocab.signature_to_vector(sig)
|
|
808
|
+
|
|
809
|
+
# Entity class IDs (coarse functional classes)
|
|
810
|
+
entity_class_to_id = {}
|
|
811
|
+
label_to_entity_class_id = {}
|
|
812
|
+
for label_key in label_to_target:
|
|
813
|
+
ntype, nlabel = label_key
|
|
814
|
+
ecls = classify_entity(ntype, nlabel)
|
|
815
|
+
if ecls not in entity_class_to_id:
|
|
816
|
+
entity_class_to_id[ecls] = len(entity_class_to_id)
|
|
817
|
+
label_to_entity_class_id[label_key] = entity_class_to_id[ecls]
|
|
818
|
+
|
|
819
|
+
n_labels = len(label_to_target)
|
|
820
|
+
log(f" {n_labels:,} trainable labels, {len(entity_class_to_id):,} entity classes")
|
|
821
|
+
|
|
822
|
+
if n_labels == 0:
|
|
823
|
+
log(" No trainable entities, skipping")
|
|
824
|
+
return model
|
|
825
|
+
|
|
826
|
+
# P×K batching
|
|
827
|
+
K = gc_samples_per_class
|
|
828
|
+
P = batch_size // K
|
|
829
|
+
|
|
830
|
+
# Build models
|
|
831
|
+
t5_hidden_dim = model.config.d_model
|
|
832
|
+
n_entity_classes = len(entity_class_to_id)
|
|
833
|
+
|
|
834
|
+
# Student-only ablation heads
|
|
835
|
+
student_sig_head = None
|
|
836
|
+
student_cls_head = None
|
|
837
|
+
if gc_student_only_mode == "student_signature":
|
|
838
|
+
student_sig_head = StudentSignatureHead(gc_hidden_dim, pretrain_vocab.size).to(device)
|
|
839
|
+
elif gc_student_only_mode == "student_class":
|
|
840
|
+
student_cls_head = StudentClassHead(gc_hidden_dim, n_entity_classes).to(device)
|
|
841
|
+
|
|
842
|
+
# Teacher components
|
|
843
|
+
gnn_teacher = None
|
|
844
|
+
ema_teacher = None
|
|
845
|
+
teacher_cls_head = None
|
|
846
|
+
model_size = pretrain_cfg.model_size
|
|
847
|
+
|
|
848
|
+
if use_teacher:
|
|
849
|
+
gnn_teacher = GNNClusterTeacher(
|
|
850
|
+
node_dim=t5_hidden_dim,
|
|
851
|
+
num_edge_types=max(len(edge_type2idx), 1),
|
|
852
|
+
edge_emb_dim=gc_edge_emb_dim,
|
|
853
|
+
hidden_dim=gc_hidden_dim,
|
|
854
|
+
num_labels=pretrain_vocab.size,
|
|
855
|
+
proj_dim=gc_proj_dim,
|
|
856
|
+
num_heads=gc_num_heads,
|
|
857
|
+
teacher_data=gc_teacher_data,
|
|
858
|
+
).to(device)
|
|
859
|
+
|
|
860
|
+
# Load pretrained GNN teacher weights
|
|
861
|
+
teacher_pt_path = os.path.join(pretrain_dir, f"gnn_teacher_{model_size}_best.pt")
|
|
862
|
+
teacher_sd = torch.load(teacher_pt_path, weights_only=True, map_location="cpu")
|
|
863
|
+
gnn_teacher.load_state_dict(teacher_sd, strict=False)
|
|
864
|
+
log(f" Loaded pretrained GNN teacher from {teacher_pt_path}")
|
|
865
|
+
|
|
866
|
+
if gc_teacher_loss == "bce":
|
|
867
|
+
teacher_cls_head = TeacherClassHead(gc_proj_dim, n_entity_classes).to(device)
|
|
868
|
+
|
|
869
|
+
# EMA teacher
|
|
870
|
+
ema_teacher = deepcopy(model).to(device)
|
|
871
|
+
ema_teacher.requires_grad_(False)
|
|
872
|
+
ema_teacher.eval()
|
|
873
|
+
|
|
874
|
+
# Optimizer — reduced LR with short linear warmup
|
|
875
|
+
model.train()
|
|
876
|
+
base_lr = pretrain_cfg.training.lr * lr_factor
|
|
877
|
+
all_params = list(model.parameters())
|
|
878
|
+
if gnn_teacher is not None:
|
|
879
|
+
all_params += list(gnn_teacher.parameters())
|
|
880
|
+
if teacher_cls_head is not None:
|
|
881
|
+
all_params += list(teacher_cls_head.parameters())
|
|
882
|
+
if student_sig_head is not None:
|
|
883
|
+
all_params += list(student_sig_head.parameters())
|
|
884
|
+
if student_cls_head is not None:
|
|
885
|
+
all_params += list(student_cls_head.parameters())
|
|
886
|
+
opt = AdamW(
|
|
887
|
+
all_params,
|
|
888
|
+
lr=base_lr, betas=(0.9, 0.95), eps=1e-8, weight_decay=0.01,
|
|
889
|
+
)
|
|
890
|
+
for pg in opt.param_groups:
|
|
891
|
+
pg["initial_lr"] = pg["lr"]
|
|
892
|
+
|
|
893
|
+
warmup_steps = max(1, n_labels // batch_size // 10)
|
|
894
|
+
|
|
895
|
+
processed_tokens = 0
|
|
896
|
+
updates = 0
|
|
897
|
+
epoch = 0
|
|
898
|
+
st = time.time()
|
|
899
|
+
|
|
900
|
+
# EMA embedding cache
|
|
901
|
+
ema_cache = {}
|
|
902
|
+
ema_cache_refresh_interval = 50
|
|
903
|
+
ema_cache_last_refresh = -ema_cache_refresh_interval
|
|
904
|
+
|
|
905
|
+
while epoch < continue_epochs:
|
|
906
|
+
epoch += 1
|
|
907
|
+
|
|
908
|
+
# P×K batch construction by entity class
|
|
909
|
+
class_to_labels = defaultdict(list)
|
|
910
|
+
for label_key in label_to_target:
|
|
911
|
+
class_to_labels[label_to_entity_class_id[label_key]].append(label_key)
|
|
912
|
+
|
|
913
|
+
epoch_entities_by_class = defaultdict(list)
|
|
914
|
+
for class_id, class_label_keys in class_to_labels.items():
|
|
915
|
+
n_class = len(class_label_keys)
|
|
916
|
+
if gc_max_per_class > 0 and n_class > gc_max_per_class:
|
|
917
|
+
offset = (epoch - 1) * gc_max_per_class % n_class
|
|
918
|
+
indices = [(offset + i) % n_class for i in range(gc_max_per_class)]
|
|
919
|
+
class_label_keys = [class_label_keys[i] for i in indices]
|
|
920
|
+
elif gc_min_per_class > 0 and n_class < gc_min_per_class:
|
|
921
|
+
repeats = (gc_min_per_class + n_class - 1) // n_class
|
|
922
|
+
class_label_keys = (class_label_keys * repeats)[:gc_min_per_class]
|
|
923
|
+
for label_key in class_label_keys:
|
|
924
|
+
entities = label_to_entities[label_key]
|
|
925
|
+
pick = entities[(epoch - 1) % len(entities)]
|
|
926
|
+
epoch_entities_by_class[class_id].append((label_key, pick, class_id))
|
|
927
|
+
|
|
928
|
+
for items in epoch_entities_by_class.values():
|
|
929
|
+
random.shuffle(items)
|
|
930
|
+
|
|
931
|
+
epoch_batches_list = build_pk_batches(epoch_entities_by_class, P, K)
|
|
932
|
+
|
|
933
|
+
epoch_supcon = 0.0
|
|
934
|
+
epoch_distill = 0.0
|
|
935
|
+
epoch_batches = 0
|
|
936
|
+
|
|
937
|
+
for batch_items in epoch_batches_list:
|
|
938
|
+
B = len(batch_items)
|
|
939
|
+
if B == 0:
|
|
940
|
+
continue
|
|
941
|
+
|
|
942
|
+
enc_ids_list = [item[1][2] for item in batch_items]
|
|
943
|
+
max_enc = min(max(len(e) for e in enc_ids_list), tokenizer.max_seq_len)
|
|
944
|
+
input_ids = _torch.full((B, max_enc), tokenizer.pad_id, dtype=_torch.long)
|
|
945
|
+
attention_mask = _torch.zeros(B, max_enc, dtype=_torch.bool)
|
|
946
|
+
for i, enc in enumerate(enc_ids_list):
|
|
947
|
+
seq_len = min(len(enc), max_enc)
|
|
948
|
+
input_ids[i, :seq_len] = _torch.tensor(enc[:seq_len])
|
|
949
|
+
attention_mask[i, :seq_len] = True
|
|
950
|
+
|
|
951
|
+
entity_class_ids = _torch.tensor(
|
|
952
|
+
[label_to_entity_class_id[item[0]] for item in batch_items], dtype=_torch.long,
|
|
953
|
+
)
|
|
954
|
+
|
|
955
|
+
# Build GNN neighborhood batch
|
|
956
|
+
entity_nodes = [item[1][0] for item in batch_items]
|
|
957
|
+
sampler_idxs = [item[1][1] for item in batch_items]
|
|
958
|
+
|
|
959
|
+
gnn_batch = build_gnn_distill_batch(
|
|
960
|
+
entity_nodes, sampler_idxs, sampler_pairs,
|
|
961
|
+
combined_indexid2msg, edge_type2idx,
|
|
962
|
+
n_neighbors_min=gc_n_neighbors_min, n_neighbors_max=gc_n_neighbors_max,
|
|
963
|
+
diverse=gc_diverse, device=device,
|
|
964
|
+
filter_noisy=gc_filter_noisy,
|
|
965
|
+
)
|
|
966
|
+
if gnn_batch is None:
|
|
967
|
+
continue
|
|
968
|
+
|
|
969
|
+
node_labels, edge_index, edge_types, batch_vec, center_idx, valid_mask = gnn_batch
|
|
970
|
+
n_valid = valid_mask.sum().item()
|
|
971
|
+
if n_valid == 0:
|
|
972
|
+
continue
|
|
973
|
+
|
|
974
|
+
# Encode neighbor nodes with EMA teacher (cached)
|
|
975
|
+
if use_teacher:
|
|
976
|
+
need_refresh = (updates - ema_cache_last_refresh) >= ema_cache_refresh_interval
|
|
977
|
+
uncached_labels = [lbl for lbl in set(node_labels) if lbl not in ema_cache]
|
|
978
|
+
|
|
979
|
+
if need_refresh:
|
|
980
|
+
all_labels_to_encode = list(set(node_labels))
|
|
981
|
+
ema_cache_last_refresh = updates
|
|
982
|
+
elif uncached_labels:
|
|
983
|
+
all_labels_to_encode = uncached_labels
|
|
984
|
+
else:
|
|
985
|
+
all_labels_to_encode = []
|
|
986
|
+
|
|
987
|
+
if all_labels_to_encode:
|
|
988
|
+
ema_token_ids = []
|
|
989
|
+
for ntype, nlabel in all_labels_to_encode:
|
|
990
|
+
tids = tokenizer.tokenize_node(ntype, nlabel)
|
|
991
|
+
ema_token_ids.append(tids if tids else [tokenizer.pad_id])
|
|
992
|
+
|
|
993
|
+
max_ema_len = min(max(len(t) for t in ema_token_ids), tokenizer.max_seq_len)
|
|
994
|
+
N_unique = len(ema_token_ids)
|
|
995
|
+
ema_input_ids = _torch.full((N_unique, max_ema_len), tokenizer.pad_id, dtype=_torch.long)
|
|
996
|
+
ema_attn_mask = _torch.zeros(N_unique, max_ema_len, dtype=_torch.bool)
|
|
997
|
+
for i, tids in enumerate(ema_token_ids):
|
|
998
|
+
L = min(len(tids), max_ema_len)
|
|
999
|
+
ema_input_ids[i, :L] = _torch.tensor(tids[:L])
|
|
1000
|
+
ema_attn_mask[i, :L] = True
|
|
1001
|
+
|
|
1002
|
+
ema_teacher.eval()
|
|
1003
|
+
with _torch.no_grad():
|
|
1004
|
+
ema_embeddings = ema_teacher.mean_pool(ema_input_ids, ema_attn_mask)
|
|
1005
|
+
for i, lbl in enumerate(all_labels_to_encode):
|
|
1006
|
+
ema_cache[lbl] = ema_embeddings[i]
|
|
1007
|
+
|
|
1008
|
+
node_embeddings = _torch.stack([ema_cache[lbl] for lbl in node_labels])
|
|
1009
|
+
|
|
1010
|
+
# Forward passes
|
|
1011
|
+
model.train()
|
|
1012
|
+
|
|
1013
|
+
out = model.modified_fwd(input_ids.to(device), attention_mask.to(device))
|
|
1014
|
+
t5_projected = out.projected
|
|
1015
|
+
|
|
1016
|
+
valid_mask_cpu = valid_mask.cpu()
|
|
1017
|
+
valid_class_ids = entity_class_ids[valid_mask_cpu].to(device)
|
|
1018
|
+
|
|
1019
|
+
if use_teacher:
|
|
1020
|
+
gnn_teacher.train()
|
|
1021
|
+
if teacher_cls_head is not None:
|
|
1022
|
+
teacher_cls_head.train()
|
|
1023
|
+
|
|
1024
|
+
valid_label_keys = [batch_items[i][0] for i in range(B) if valid_mask_cpu[i]]
|
|
1025
|
+
sig_vecs = _torch.stack([label_to_target[lk] for lk in valid_label_keys]).to(device)
|
|
1026
|
+
|
|
1027
|
+
teacher_proj = gnn_teacher(
|
|
1028
|
+
node_embeddings, edge_index, edge_types, center_idx,
|
|
1029
|
+
signature_vectors=sig_vecs,
|
|
1030
|
+
)
|
|
1031
|
+
|
|
1032
|
+
# L_teacher: SupCon or BCE
|
|
1033
|
+
if gc_teacher_loss == "bce":
|
|
1034
|
+
import torch.nn.functional as _F
|
|
1035
|
+
cls_logits = teacher_cls_head(teacher_proj)
|
|
1036
|
+
supcon_loss = _F.cross_entropy(cls_logits, valid_class_ids)
|
|
1037
|
+
else:
|
|
1038
|
+
supcon_loss = supervised_contrastive_loss(
|
|
1039
|
+
teacher_proj, valid_class_ids, temperature=gc_temperature,
|
|
1040
|
+
)
|
|
1041
|
+
|
|
1042
|
+
# L_distill: SCE or MSE
|
|
1043
|
+
if gc_distill_loss == "mse":
|
|
1044
|
+
import torch.nn.functional as _F
|
|
1045
|
+
distill_loss = _F.mse_loss(t5_projected[valid_mask], teacher_proj.detach())
|
|
1046
|
+
else:
|
|
1047
|
+
distill_loss = sce_loss(t5_projected[valid_mask], teacher_proj.detach())
|
|
1048
|
+
|
|
1049
|
+
total_loss = gc_supcon_weight * supcon_loss + gc_distill_weight * distill_loss
|
|
1050
|
+
else:
|
|
1051
|
+
import torch.nn.functional as _F
|
|
1052
|
+
valid_label_keys = [batch_items[i][0] for i in range(B) if valid_mask_cpu[i]]
|
|
1053
|
+
|
|
1054
|
+
if gc_student_only_mode == "student_signature":
|
|
1055
|
+
student_sig_head.train()
|
|
1056
|
+
sig_logits = student_sig_head(t5_projected[valid_mask])
|
|
1057
|
+
sig_targets = _torch.stack([label_to_target[lk] for lk in valid_label_keys]).to(device)
|
|
1058
|
+
supcon_loss = _F.binary_cross_entropy_with_logits(sig_logits, sig_targets)
|
|
1059
|
+
distill_loss = _torch.tensor(0.0, device=device)
|
|
1060
|
+
elif gc_student_only_mode == "student_class":
|
|
1061
|
+
student_cls_head.train()
|
|
1062
|
+
cls_logits = student_cls_head(t5_projected[valid_mask])
|
|
1063
|
+
supcon_loss = _F.cross_entropy(cls_logits, valid_class_ids)
|
|
1064
|
+
distill_loss = _torch.tensor(0.0, device=device)
|
|
1065
|
+
|
|
1066
|
+
total_loss = supcon_loss
|
|
1067
|
+
|
|
1068
|
+
total_loss.backward()
|
|
1069
|
+
_torch.nn.utils.clip_grad_norm_(model.parameters(), 5.0)
|
|
1070
|
+
if gnn_teacher is not None:
|
|
1071
|
+
_torch.nn.utils.clip_grad_norm_(gnn_teacher.parameters(), 5.0)
|
|
1072
|
+
opt.step()
|
|
1073
|
+
opt.zero_grad()
|
|
1074
|
+
|
|
1075
|
+
# EMA update
|
|
1076
|
+
if ema_teacher is not None:
|
|
1077
|
+
with _torch.no_grad():
|
|
1078
|
+
for ema_p, student_p in zip(ema_teacher.parameters(), model.parameters()):
|
|
1079
|
+
ema_p.data.mul_(gc_ema_momentum).add_(student_p.data, alpha=1.0 - gc_ema_momentum)
|
|
1080
|
+
|
|
1081
|
+
# Linear warmup
|
|
1082
|
+
updates += 1
|
|
1083
|
+
if updates <= warmup_steps:
|
|
1084
|
+
warmup_scale = updates / warmup_steps
|
|
1085
|
+
for pg in opt.param_groups:
|
|
1086
|
+
pg["lr"] = pg["initial_lr"] * warmup_scale
|
|
1087
|
+
|
|
1088
|
+
n_tokens = int(attention_mask.sum().item())
|
|
1089
|
+
processed_tokens += n_tokens
|
|
1090
|
+
|
|
1091
|
+
sc_val = supcon_loss.item()
|
|
1092
|
+
dl_val = distill_loss.item()
|
|
1093
|
+
epoch_supcon += sc_val
|
|
1094
|
+
epoch_distill += dl_val
|
|
1095
|
+
epoch_batches += 1
|
|
1096
|
+
|
|
1097
|
+
if updates % 50 == 0:
|
|
1098
|
+
log(f" [continue] e{epoch}/{continue_epochs} step={updates} "
|
|
1099
|
+
f"supcon={sc_val:.4f} distill={dl_val:.4f} "
|
|
1100
|
+
f"valid={n_valid}/{B} ({time.time()-st:.1f}s)")
|
|
1101
|
+
|
|
1102
|
+
if epoch_batches > 0:
|
|
1103
|
+
avg_sc = epoch_supcon / epoch_batches
|
|
1104
|
+
avg_dl = epoch_distill / epoch_batches
|
|
1105
|
+
log(f" Epoch {epoch}/{continue_epochs} | supcon={avg_sc:.4f} distill={avg_dl:.4f} | "
|
|
1106
|
+
f"{time.time()-st:.1f}s")
|
|
1107
|
+
|
|
1108
|
+
model.eval()
|
|
1109
|
+
log(f" Continue-pretraining (spider) done: {updates} steps, {epoch} epochs, "
|
|
1110
|
+
f"{processed_tokens:,} tokens ({time.time()-st:.1f}s)")
|
|
1111
|
+
|
|
1112
|
+
# Restore tokenizer for inference
|
|
1113
|
+
tokenizer.expand_netflow_ips = False
|
|
1114
|
+
|
|
1115
|
+
del gnn_teacher, ema_teacher, opt, ema_cache
|
|
1116
|
+
if _torch.cuda.is_available():
|
|
1117
|
+
_torch.cuda.empty_cache()
|
|
1118
|
+
return model
|
|
1119
|
+
|
|
1120
|
+
|
|
1121
|
+
def _continue_pretrain_behavior_cluster(cfg, model, tokenizer, pretrain_cfg, inference_cfg, device):
|
|
1122
|
+
"""Continue pretraining a behavior_cluster model on the target dataset.
|
|
1123
|
+
|
|
1124
|
+
Rebuilds behavior signatures from the target graph and fine-tunes the
|
|
1125
|
+
model using the same BCE + SupCon loss as pretraining, at a reduced LR.
|
|
1126
|
+
"""
|
|
1127
|
+
import random
|
|
1128
|
+
import time
|
|
1129
|
+
from collections import defaultdict
|
|
1130
|
+
|
|
1131
|
+
import torch as _torch
|
|
1132
|
+
from torch.optim import AdamW
|
|
1133
|
+
|
|
1134
|
+
from pidsmaker.pretrained.models.behavior import behavior_combined_loss
|
|
1135
|
+
from pidsmaker.pretrained.data.behavior_signatures import (
|
|
1136
|
+
build_behavior_dataset,
|
|
1137
|
+
BehaviorLabelVocab,
|
|
1138
|
+
)
|
|
1139
|
+
|
|
1140
|
+
bc_cfg = pretrain_cfg.behavior_cluster
|
|
1141
|
+
continue_epochs = inference_cfg.continue_pretrain_epochs
|
|
1142
|
+
lr_factor = inference_cfg.continue_pretrain_lr_factor
|
|
1143
|
+
batch_size = pretrain_cfg.training.batch_size
|
|
1144
|
+
bc_bce_weight = bc_cfg.bce_weight
|
|
1145
|
+
bc_contrastive_weight = bc_cfg.contrastive_weight
|
|
1146
|
+
bc_temperature = bc_cfg.temperature
|
|
1147
|
+
bc_min_sig_size = bc_cfg.min_signature_size
|
|
1148
|
+
bc_filter_noisy = bc_cfg.filter_noisy_edges
|
|
1149
|
+
bc_bce_mode = bc_cfg.bce_mode
|
|
1150
|
+
bc_contrastive_target = bc_cfg.contrastive_target
|
|
1151
|
+
|
|
1152
|
+
log("Continue-pretraining (behavior_cluster) on target dataset ...")
|
|
1153
|
+
|
|
1154
|
+
result = _load_target_graphs_and_samplers(cfg, pretrain_cfg)
|
|
1155
|
+
if result[0] is None:
|
|
1156
|
+
log(" No graph files found, skipping")
|
|
1157
|
+
return model
|
|
1158
|
+
sampler_pairs, ds_indexid2msg, _ = result
|
|
1159
|
+
|
|
1160
|
+
# Build behavior signatures from target graph
|
|
1161
|
+
combined_indexid2msg = {}
|
|
1162
|
+
for _, im in sampler_pairs:
|
|
1163
|
+
combined_indexid2msg.update(im)
|
|
1164
|
+
|
|
1165
|
+
label_to_signature, label_to_entities_raw, vocab = build_behavior_dataset(
|
|
1166
|
+
sampler_pairs, combined_indexid2msg,
|
|
1167
|
+
filter_noisy=bc_filter_noisy,
|
|
1168
|
+
min_signature_size=bc_min_sig_size,
|
|
1169
|
+
)
|
|
1170
|
+
log(f" {len(label_to_signature):,} unique entity labels, "
|
|
1171
|
+
f"{vocab.size:,} behavior labels")
|
|
1172
|
+
|
|
1173
|
+
if not label_to_signature:
|
|
1174
|
+
log(" No signatures, skipping")
|
|
1175
|
+
return model
|
|
1176
|
+
|
|
1177
|
+
# Load pretrained vocab for target vectors (must match model's num_labels)
|
|
1178
|
+
pretrain_dir = cfg.featurization._model_dir
|
|
1179
|
+
_pmp = getattr(pretrain_cfg, 'weights_path', None)
|
|
1180
|
+
if _pmp:
|
|
1181
|
+
pretrain_dir = _pmp
|
|
1182
|
+
pretrain_vocab = BehaviorLabelVocab()
|
|
1183
|
+
bvocab_path = os.path.join(pretrain_dir, "behavior_vocab.txt")
|
|
1184
|
+
if os.path.exists(bvocab_path):
|
|
1185
|
+
pretrain_vocab.load(bvocab_path)
|
|
1186
|
+
else:
|
|
1187
|
+
log(" No pretrained behavior_vocab.txt found, skipping")
|
|
1188
|
+
return model
|
|
1189
|
+
|
|
1190
|
+
# Tokenize entities and build targets using pretrained vocab
|
|
1191
|
+
label_to_entities = defaultdict(list)
|
|
1192
|
+
for label_key, raw_entities in label_to_entities_raw.items():
|
|
1193
|
+
ntype, nlabel = label_key
|
|
1194
|
+
entity_ids = tokenizer.tokenize_node(ntype, nlabel)
|
|
1195
|
+
if entity_ids:
|
|
1196
|
+
for node_id, sidx in raw_entities:
|
|
1197
|
+
label_to_entities[label_key].append((node_id, sidx, entity_ids))
|
|
1198
|
+
|
|
1199
|
+
label_to_target = {}
|
|
1200
|
+
for label_key, sig in label_to_signature.items():
|
|
1201
|
+
if label_key in label_to_entities:
|
|
1202
|
+
label_to_target[label_key] = pretrain_vocab.signature_to_vector(sig)
|
|
1203
|
+
|
|
1204
|
+
# Assign class IDs (identical signatures → same class)
|
|
1205
|
+
sig_to_class_id = {}
|
|
1206
|
+
label_to_class_id = {}
|
|
1207
|
+
for label_key, sig in label_to_signature.items():
|
|
1208
|
+
if label_key in label_to_target:
|
|
1209
|
+
if sig not in sig_to_class_id:
|
|
1210
|
+
sig_to_class_id[sig] = len(sig_to_class_id)
|
|
1211
|
+
label_to_class_id[label_key] = sig_to_class_id[sig]
|
|
1212
|
+
|
|
1213
|
+
# Assign entity class IDs (coarse functional classes)
|
|
1214
|
+
from pidsmaker.pretrained.data.entity_classes import classify_entity
|
|
1215
|
+
entity_class_to_id = {}
|
|
1216
|
+
label_to_entity_class_id = {}
|
|
1217
|
+
for label_key in label_to_target:
|
|
1218
|
+
ntype, nlabel = label_key
|
|
1219
|
+
ecls = classify_entity(ntype, nlabel)
|
|
1220
|
+
if ecls not in entity_class_to_id:
|
|
1221
|
+
entity_class_to_id[ecls] = len(entity_class_to_id)
|
|
1222
|
+
label_to_entity_class_id[label_key] = entity_class_to_id[ecls]
|
|
1223
|
+
|
|
1224
|
+
# Contrastive grouping
|
|
1225
|
+
if bc_contrastive_target == "entity_class":
|
|
1226
|
+
label_to_contrastive_id = label_to_entity_class_id
|
|
1227
|
+
else:
|
|
1228
|
+
label_to_contrastive_id = label_to_class_id
|
|
1229
|
+
|
|
1230
|
+
n_labels = len(label_to_target)
|
|
1231
|
+
log(f" {n_labels:,} trainable labels, {len(sig_to_class_id):,} signature classes, "
|
|
1232
|
+
f"{len(entity_class_to_id):,} entity classes")
|
|
1233
|
+
|
|
1234
|
+
if n_labels == 0:
|
|
1235
|
+
log(" No trainable entities, skipping")
|
|
1236
|
+
return model
|
|
1237
|
+
|
|
1238
|
+
# Optimizer — reduced LR with short linear warmup
|
|
1239
|
+
model.train()
|
|
1240
|
+
base_lr = pretrain_cfg.training.lr * lr_factor
|
|
1241
|
+
opt = AdamW(model.parameters(), lr=base_lr, betas=(0.9, 0.95), weight_decay=0.01)
|
|
1242
|
+
for pg in opt.param_groups:
|
|
1243
|
+
pg["initial_lr"] = pg["lr"]
|
|
1244
|
+
|
|
1245
|
+
warmup_steps = max(1, n_labels // batch_size // 10)
|
|
1246
|
+
|
|
1247
|
+
processed_tokens = 0
|
|
1248
|
+
updates = 0
|
|
1249
|
+
epoch = 0
|
|
1250
|
+
st = time.time()
|
|
1251
|
+
|
|
1252
|
+
while epoch < continue_epochs:
|
|
1253
|
+
epoch += 1
|
|
1254
|
+
|
|
1255
|
+
# Group by contrastive class for pairing
|
|
1256
|
+
class_to_labels = defaultdict(list)
|
|
1257
|
+
for label_key in label_to_target:
|
|
1258
|
+
class_to_labels[label_to_contrastive_id[label_key]].append(label_key)
|
|
1259
|
+
|
|
1260
|
+
epoch_entities = []
|
|
1261
|
+
for class_id, class_label_keys in class_to_labels.items():
|
|
1262
|
+
for label_key in class_label_keys:
|
|
1263
|
+
entities = label_to_entities[label_key]
|
|
1264
|
+
pick = entities[(epoch - 1) % len(entities)]
|
|
1265
|
+
epoch_entities.append((label_key, pick, class_id))
|
|
1266
|
+
|
|
1267
|
+
# Sort by class_id so same-class entities are adjacent in batches
|
|
1268
|
+
epoch_entities.sort(key=lambda x: x[2])
|
|
1269
|
+
chunks = [epoch_entities[i:i + batch_size] for i in range(0, len(epoch_entities), batch_size)]
|
|
1270
|
+
random.shuffle(chunks)
|
|
1271
|
+
epoch_entities = [item for chunk in chunks for item in chunk]
|
|
1272
|
+
|
|
1273
|
+
epoch_loss = 0.0
|
|
1274
|
+
epoch_batches = 0
|
|
1275
|
+
|
|
1276
|
+
for batch_start in range(0, len(epoch_entities), batch_size):
|
|
1277
|
+
batch_items = epoch_entities[batch_start:batch_start + batch_size]
|
|
1278
|
+
B = len(batch_items)
|
|
1279
|
+
if B == 0:
|
|
1280
|
+
continue
|
|
1281
|
+
|
|
1282
|
+
enc_ids_list = [item[1][2] for item in batch_items]
|
|
1283
|
+
max_enc = min(max(len(e) for e in enc_ids_list), tokenizer.max_seq_len)
|
|
1284
|
+
input_ids = _torch.full((B, max_enc), tokenizer.pad_id, dtype=_torch.long)
|
|
1285
|
+
attention_mask = _torch.zeros(B, max_enc, dtype=_torch.bool)
|
|
1286
|
+
for i, enc in enumerate(enc_ids_list):
|
|
1287
|
+
seq_len = min(len(enc), max_enc)
|
|
1288
|
+
input_ids[i, :seq_len] = _torch.tensor(enc[:seq_len])
|
|
1289
|
+
attention_mask[i, :seq_len] = True
|
|
1290
|
+
|
|
1291
|
+
target_vecs = _torch.stack([label_to_target[item[0]] for item in batch_items])
|
|
1292
|
+
class_ids = _torch.tensor([item[2] for item in batch_items], dtype=_torch.long)
|
|
1293
|
+
entity_class_ids = _torch.tensor(
|
|
1294
|
+
[label_to_entity_class_id[item[0]] for item in batch_items], dtype=_torch.long,
|
|
1295
|
+
)
|
|
1296
|
+
|
|
1297
|
+
out = model.modified_fwd(input_ids.to(device), attention_mask.to(device))
|
|
1298
|
+
total_loss, bce_val, con_val = behavior_combined_loss(
|
|
1299
|
+
out.logits, target_vecs.to(device),
|
|
1300
|
+
out.projection, class_ids.to(device),
|
|
1301
|
+
bce_weight=bc_bce_weight,
|
|
1302
|
+
contrastive_weight=bc_contrastive_weight,
|
|
1303
|
+
temperature=bc_temperature,
|
|
1304
|
+
bce_mode=bc_bce_mode,
|
|
1305
|
+
entity_class_labels=entity_class_ids.to(device),
|
|
1306
|
+
contrastive_target=bc_contrastive_target,
|
|
1307
|
+
)
|
|
1308
|
+
|
|
1309
|
+
total_loss.backward()
|
|
1310
|
+
_torch.nn.utils.clip_grad_norm_(model.parameters(), 5.0)
|
|
1311
|
+
opt.step()
|
|
1312
|
+
opt.zero_grad()
|
|
1313
|
+
|
|
1314
|
+
epoch_loss += total_loss.item()
|
|
1315
|
+
epoch_batches += 1
|
|
1316
|
+
|
|
1317
|
+
# Linear warmup
|
|
1318
|
+
updates += 1
|
|
1319
|
+
if updates <= warmup_steps:
|
|
1320
|
+
warmup_scale = updates / warmup_steps
|
|
1321
|
+
for pg in opt.param_groups:
|
|
1322
|
+
pg["lr"] = pg["initial_lr"] * warmup_scale
|
|
1323
|
+
|
|
1324
|
+
processed_tokens += int(attention_mask.sum().item())
|
|
1325
|
+
|
|
1326
|
+
avg_loss = epoch_loss / max(epoch_batches, 1)
|
|
1327
|
+
elapsed = time.time() - st
|
|
1328
|
+
log(f" Epoch {epoch}/{continue_epochs} | loss={avg_loss:.4f} | "
|
|
1329
|
+
f"lr={opt.param_groups[0]['lr']:.2e} | {elapsed:.1f}s")
|
|
1330
|
+
|
|
1331
|
+
model.eval()
|
|
1332
|
+
log(f" Continue-pretraining (behavior_cluster) done: {updates} steps, {epoch} epochs, "
|
|
1333
|
+
f"{processed_tokens:,} tokens ({time.time()-st:.1f}s)")
|
|
1334
|
+
|
|
1335
|
+
del opt
|
|
1336
|
+
if _torch.cuda.is_available():
|
|
1337
|
+
_torch.cuda.empty_cache()
|
|
1338
|
+
return model
|
|
1339
|
+
|
|
1340
|
+
|
|
1341
|
+
def main(cfg):
|
|
1342
|
+
|
|
1343
|
+
pretrain_cfg = cfg.featurization.pretrained
|
|
1344
|
+
model_type = pretrain_cfg.model_type
|
|
1345
|
+
model_size = pretrain_cfg.model_size
|
|
1346
|
+
pretrain_dir = cfg.featurization._model_dir
|
|
1347
|
+
# spider_path overrides pretrain_dir for loading artifacts
|
|
1348
|
+
_spider_path = getattr(pretrain_cfg, 'weights_path', None)
|
|
1349
|
+
if _spider_path:
|
|
1350
|
+
pretrain_dir = _spider_path
|
|
1351
|
+
emb_dim = cfg.featurization.emb_dim
|
|
1352
|
+
|
|
1353
|
+
# ── GraphMAE: return per-graph encoder (avoids cross-graph data snooping) ──
|
|
1354
|
+
if model_type == "graphmae":
|
|
1355
|
+
from pidsmaker.pretrained.models.graphmae import load_graphmae, T5NodeEncoder
|
|
1356
|
+
from pidsmaker.pretrained.data.tokenizer_bpe import ProvenanceTokenizerBPE as ProvenanceTokenizer
|
|
1357
|
+
|
|
1358
|
+
gm_cfg = pretrain_cfg.graphmae
|
|
1359
|
+
gm_num_layers = gm_cfg.num_layers
|
|
1360
|
+
gm_num_heads = gm_cfg.num_heads
|
|
1361
|
+
gm_decoder_layers = gm_cfg.decoder_num_layers
|
|
1362
|
+
gm_mask_rate = gm_cfg.mask_rate
|
|
1363
|
+
gm_replace_rate = gm_cfg.replace_rate
|
|
1364
|
+
|
|
1365
|
+
device = "cuda" if torch.cuda.is_available() and not getattr(cfg, '_use_cpu', False) else "cpu"
|
|
1366
|
+
|
|
1367
|
+
tokenizer = ProvenanceTokenizer(cfg)
|
|
1368
|
+
tokenizer.load(os.path.join(pretrain_dir, "tokenizer.pt"))
|
|
1369
|
+
|
|
1370
|
+
from pidsmaker.pretrained.models.gnn_distill import get_gnn_distill_encoder_config
|
|
1371
|
+
t5_config = get_gnn_distill_encoder_config(tokenizer.vocab_size, model_size, tokenizer.max_seq_len)
|
|
1372
|
+
t5_hidden_dim = t5_config.d_model
|
|
1373
|
+
|
|
1374
|
+
gm_model, t5_encoder = load_graphmae(
|
|
1375
|
+
pretrain_dir, in_dim=t5_hidden_dim, hidden_dim=emb_dim,
|
|
1376
|
+
num_encoder_layers=gm_num_layers, num_decoder_layers=gm_decoder_layers,
|
|
1377
|
+
num_heads=gm_num_heads, mask_rate=gm_mask_rate, replace_rate=gm_replace_rate,
|
|
1378
|
+
vocab_size=tokenizer.vocab_size, model_size=model_size,
|
|
1379
|
+
max_seq_len=tokenizer.max_seq_len,
|
|
1380
|
+
)
|
|
1381
|
+
gm_model = gm_model.to(device).eval()
|
|
1382
|
+
t5_encoder = t5_encoder.to(device).eval()
|
|
1383
|
+
indexid2msg = get_indexid2msg(cfg)
|
|
1384
|
+
|
|
1385
|
+
log(f"GraphMAE encoder ready (dim={emb_dim}) — embeddings will be computed per-graph")
|
|
1386
|
+
return GraphBasedEncoder(gm_model, t5_encoder, tokenizer, indexid2msg, emb_dim, device)
|
|
1387
|
+
|
|
1388
|
+
# ── GAE: return per-graph encoder (avoids cross-graph data snooping) ──
|
|
1389
|
+
if model_type == "gae":
|
|
1390
|
+
from pidsmaker.pretrained.models.gae import load_gae
|
|
1391
|
+
from pidsmaker.pretrained.models.graphmae import T5NodeEncoder
|
|
1392
|
+
from pidsmaker.pretrained.models.gnn_distill import get_gnn_distill_encoder_config
|
|
1393
|
+
from pidsmaker.pretrained.data.tokenizer_bpe import ProvenanceTokenizerBPE as ProvenanceTokenizer
|
|
1394
|
+
|
|
1395
|
+
gae_cfg = pretrain_cfg.gae
|
|
1396
|
+
gae_num_layers = gae_cfg.num_layers
|
|
1397
|
+
gae_num_heads = gae_cfg.num_heads
|
|
1398
|
+
|
|
1399
|
+
device = "cuda" if torch.cuda.is_available() and not getattr(cfg, '_use_cpu', False) else "cpu"
|
|
1400
|
+
|
|
1401
|
+
tokenizer = ProvenanceTokenizer(cfg)
|
|
1402
|
+
tokenizer.load(os.path.join(pretrain_dir, "tokenizer.pt"))
|
|
1403
|
+
|
|
1404
|
+
t5_config = get_gnn_distill_encoder_config(tokenizer.vocab_size, model_size, tokenizer.max_seq_len)
|
|
1405
|
+
t5_hidden_dim = t5_config.d_model
|
|
1406
|
+
|
|
1407
|
+
gae_model, t5_encoder = load_gae(
|
|
1408
|
+
pretrain_dir, in_dim=t5_hidden_dim, hidden_dim=emb_dim,
|
|
1409
|
+
num_encoder_layers=gae_num_layers, num_heads=gae_num_heads,
|
|
1410
|
+
vocab_size=tokenizer.vocab_size, model_size=model_size,
|
|
1411
|
+
max_seq_len=tokenizer.max_seq_len,
|
|
1412
|
+
)
|
|
1413
|
+
gae_model = gae_model.to(device).eval()
|
|
1414
|
+
t5_encoder = t5_encoder.to(device).eval()
|
|
1415
|
+
indexid2msg = get_indexid2msg(cfg)
|
|
1416
|
+
|
|
1417
|
+
log(f"GAE encoder ready (dim={emb_dim}) — embeddings will be computed per-graph")
|
|
1418
|
+
return GraphBasedEncoder(gae_model, t5_encoder, tokenizer, indexid2msg, emb_dim, device)
|
|
1419
|
+
|
|
1420
|
+
# ── DGI: return per-graph encoder (avoids cross-graph data snooping) ──
|
|
1421
|
+
if model_type == "dgi":
|
|
1422
|
+
from pidsmaker.pretrained.models.dgi import load_dgi
|
|
1423
|
+
from pidsmaker.pretrained.models.graphmae import T5NodeEncoder
|
|
1424
|
+
from pidsmaker.pretrained.models.gnn_distill import get_gnn_distill_encoder_config
|
|
1425
|
+
from pidsmaker.pretrained.data.tokenizer_bpe import ProvenanceTokenizerBPE as ProvenanceTokenizer
|
|
1426
|
+
|
|
1427
|
+
dgi_cfg = pretrain_cfg.dgi
|
|
1428
|
+
dgi_num_layers = dgi_cfg.num_layers
|
|
1429
|
+
dgi_num_heads = dgi_cfg.num_heads
|
|
1430
|
+
|
|
1431
|
+
device = "cuda" if torch.cuda.is_available() and not getattr(cfg, '_use_cpu', False) else "cpu"
|
|
1432
|
+
|
|
1433
|
+
tokenizer = ProvenanceTokenizer(cfg)
|
|
1434
|
+
tokenizer.load(os.path.join(pretrain_dir, "tokenizer.pt"))
|
|
1435
|
+
|
|
1436
|
+
t5_config = get_gnn_distill_encoder_config(tokenizer.vocab_size, model_size, tokenizer.max_seq_len)
|
|
1437
|
+
t5_hidden_dim = t5_config.d_model
|
|
1438
|
+
|
|
1439
|
+
dgi_model, t5_encoder = load_dgi(
|
|
1440
|
+
pretrain_dir, in_dim=t5_hidden_dim, hidden_dim=emb_dim,
|
|
1441
|
+
num_encoder_layers=dgi_num_layers, num_heads=dgi_num_heads,
|
|
1442
|
+
vocab_size=tokenizer.vocab_size, model_size=model_size,
|
|
1443
|
+
max_seq_len=tokenizer.max_seq_len,
|
|
1444
|
+
)
|
|
1445
|
+
dgi_model = dgi_model.to(device).eval()
|
|
1446
|
+
t5_encoder = t5_encoder.to(device).eval()
|
|
1447
|
+
indexid2msg = get_indexid2msg(cfg)
|
|
1448
|
+
|
|
1449
|
+
log(f"DGI encoder ready (dim={emb_dim}) — embeddings will be computed per-graph")
|
|
1450
|
+
return GraphBasedEncoder(dgi_model, t5_encoder, tokenizer, indexid2msg, emb_dim, device)
|
|
1451
|
+
|
|
1452
|
+
# ── DeepWalk: load Word2Vec model and map labels directly ──────────
|
|
1453
|
+
if model_type in ("deepwalk", "node2vec"):
|
|
1454
|
+
from pidsmaker.pretrained.models.deepwalk import load_deepwalk, deepwalk_embeddings
|
|
1455
|
+
from pidsmaker.tokenization import build_tokenizer
|
|
1456
|
+
dw_model = load_deepwalk(pretrain_dir)
|
|
1457
|
+
if emb_dim != dw_model.wv.vector_size:
|
|
1458
|
+
raise ValueError(
|
|
1459
|
+
f"featurization.emb_dim ({emb_dim}) does not match "
|
|
1460
|
+
f"DeepWalk vector_size ({dw_model.wv.vector_size}). "
|
|
1461
|
+
f"Set emb_dim: {dw_model.wv.vector_size} in your config."
|
|
1462
|
+
)
|
|
1463
|
+
indexid2msg = get_indexid2msg(cfg)
|
|
1464
|
+
indexid2vec = deepwalk_embeddings(dw_model, indexid2msg, tokenizer=build_tokenizer(cfg))
|
|
1465
|
+
log(f"Computed {len(indexid2vec):,} DeepWalk node embeddings (dim={emb_dim})")
|
|
1466
|
+
return indexid2vec
|
|
1467
|
+
|
|
1468
|
+
# ── HF pretrained models: load fine-tuned model + HF tokenizer ───────
|
|
1469
|
+
from pidsmaker.pretrained.models.hf_pretrained import HF_MODEL_TYPES
|
|
1470
|
+
if model_type in HF_MODEL_TYPES:
|
|
1471
|
+
from transformers import AutoModelForCausalLM
|
|
1472
|
+
from pidsmaker.tokenization import get_hf_substitutor, load_hf_tokenizer
|
|
1473
|
+
from pidsmaker.pretrained.models.hf_pretrained import (
|
|
1474
|
+
embed_nodes_hf, get_hf_hidden_size,
|
|
1475
|
+
)
|
|
1476
|
+
|
|
1477
|
+
hidden_size = get_hf_hidden_size(model_type, model_size)
|
|
1478
|
+
if emb_dim != hidden_size:
|
|
1479
|
+
log(f"Overriding emb_dim {emb_dim} → {hidden_size} to match "
|
|
1480
|
+
f"{model_type} hidden size")
|
|
1481
|
+
emb_dim = hidden_size
|
|
1482
|
+
|
|
1483
|
+
hf_model_dir = os.path.join(pretrain_dir, "hf_model")
|
|
1484
|
+
hf_tok_dir = os.path.join(pretrain_dir, "hf_tokenizer")
|
|
1485
|
+
if not os.path.isdir(hf_model_dir):
|
|
1486
|
+
raise FileNotFoundError(
|
|
1487
|
+
f"No fine-tuned HF model found at {hf_model_dir}. "
|
|
1488
|
+
f"Run featurization first."
|
|
1489
|
+
)
|
|
1490
|
+
|
|
1491
|
+
device = "cuda" if torch.cuda.is_available() and not getattr(cfg, '_use_cpu', False) else "cpu"
|
|
1492
|
+
hf_tokenizer = load_hf_tokenizer(hf_tok_dir) # saved by pretraining
|
|
1493
|
+
model = AutoModelForCausalLM.from_pretrained(
|
|
1494
|
+
hf_model_dir, torch_dtype=torch.float32,
|
|
1495
|
+
).to(device)
|
|
1496
|
+
|
|
1497
|
+
model.eval()
|
|
1498
|
+
indexid2msg = get_indexid2msg(cfg)
|
|
1499
|
+
hf_max_seq_len = cfg.featurization.tokenization.huggingface.max_seq_len
|
|
1500
|
+
indexid2vec = embed_nodes_hf(
|
|
1501
|
+
model, hf_tokenizer, indexid2msg, emb_dim, device,
|
|
1502
|
+
batch_size=64, max_seq_len=hf_max_seq_len, substitutor=get_hf_substitutor(cfg),
|
|
1503
|
+
)
|
|
1504
|
+
log(f"Computed {len(indexid2vec):,} {model_type} node embeddings (dim={emb_dim})")
|
|
1505
|
+
return indexid2vec
|
|
1506
|
+
|
|
1507
|
+
# Node labels are very short (~5 tokens), so use a large batch size
|
|
1508
|
+
batch_size = min(pretrain_cfg.training.batch_size * 16, 8192)
|
|
1509
|
+
|
|
1510
|
+
# ── Load tokenizer ────────────────────────────────────────────────
|
|
1511
|
+
from pidsmaker.pretrained.data.tokenizer_bpe import ProvenanceTokenizerBPE as ProvenanceTokenizer
|
|
1512
|
+
|
|
1513
|
+
tokenizer = ProvenanceTokenizer(cfg)
|
|
1514
|
+
tokenizer.load(os.path.join(pretrain_dir, "tokenizer.pt"))
|
|
1515
|
+
|
|
1516
|
+
# ── Load pretrained BERT backbone ─────────────────────────────────
|
|
1517
|
+
if model_type == "ropebert":
|
|
1518
|
+
from pidsmaker.pretrained.models.ropebert import ProvenanceRoPEBERT, get_ropebert_config
|
|
1519
|
+
rope_theta = getattr(pretrain_cfg, 'rope_theta', 10000.0)
|
|
1520
|
+
bert_config = get_ropebert_config(
|
|
1521
|
+
tokenizer.vocab_size, model_size, tokenizer.max_seq_len,
|
|
1522
|
+
rope_theta=rope_theta,
|
|
1523
|
+
)
|
|
1524
|
+
bert = ProvenanceRoPEBERT(bert_config)
|
|
1525
|
+
elif model_type == "gnn_distill":
|
|
1526
|
+
from pidsmaker.pretrained.models.gnn_distill import ProvenanceGNNDistill, get_gnn_distill_encoder_config
|
|
1527
|
+
bert_config = get_gnn_distill_encoder_config(tokenizer.vocab_size, model_size, tokenizer.max_seq_len)
|
|
1528
|
+
gnn_hidden_dim = pretrain_cfg.gnn_distill.hidden_dim
|
|
1529
|
+
bert = ProvenanceGNNDistill(bert_config, gnn_hidden_dim)
|
|
1530
|
+
elif model_type == "spider":
|
|
1531
|
+
from pidsmaker.pretrained.models.spider import ProvenanceGNNCluster, get_spider_encoder_config
|
|
1532
|
+
bert_config = get_spider_encoder_config(tokenizer.vocab_size, model_size, tokenizer.max_seq_len)
|
|
1533
|
+
gnn_hidden_dim = pretrain_cfg.spider.hidden_dim
|
|
1534
|
+
bert = ProvenanceGNNCluster(bert_config, gnn_hidden_dim)
|
|
1535
|
+
elif model_type == "behavior_cluster":
|
|
1536
|
+
from pidsmaker.pretrained.models.behavior import ProvenanceBehaviorModel, get_behavior_encoder_config
|
|
1537
|
+
from pidsmaker.pretrained.data.behavior_signatures import BehaviorLabelVocab
|
|
1538
|
+
bert_config = get_behavior_encoder_config(tokenizer.vocab_size, model_size, tokenizer.max_seq_len)
|
|
1539
|
+
# Load behavior vocab to get num_labels
|
|
1540
|
+
bvocab_path = os.path.join(pretrain_dir, "behavior_vocab.txt")
|
|
1541
|
+
bvocab = BehaviorLabelVocab()
|
|
1542
|
+
if os.path.exists(bvocab_path):
|
|
1543
|
+
bvocab.load(bvocab_path)
|
|
1544
|
+
bc_cfg = pretrain_cfg.behavior_cluster
|
|
1545
|
+
bc_proj_dim = bc_cfg.proj_dim
|
|
1546
|
+
bc_bce_mode = bc_cfg.bce_mode
|
|
1547
|
+
# For bce_mode="class", we need num_classes; infer from checkpoint keys
|
|
1548
|
+
bc_num_classes = 0
|
|
1549
|
+
if bc_bce_mode == "class":
|
|
1550
|
+
sd_peek = torch.load(
|
|
1551
|
+
os.path.join(pretrain_dir, f"pretrain_{model_size}.pt"),
|
|
1552
|
+
weights_only=True, map_location="cpu",
|
|
1553
|
+
)
|
|
1554
|
+
for k, v in sd_peek.items():
|
|
1555
|
+
if k == "classification_head.classifier.3.weight":
|
|
1556
|
+
bc_num_classes = v.shape[0]
|
|
1557
|
+
break
|
|
1558
|
+
del sd_peek
|
|
1559
|
+
bert = ProvenanceBehaviorModel(
|
|
1560
|
+
bert_config, num_labels=max(bvocab.size, 1), proj_dim=bc_proj_dim,
|
|
1561
|
+
bce_mode=bc_bce_mode, num_classes=bc_num_classes,
|
|
1562
|
+
)
|
|
1563
|
+
elif model_type == "modernbert":
|
|
1564
|
+
from pidsmaker.pretrained.models.modernbert import ProvenanceModernBERT, get_modernbert_config
|
|
1565
|
+
bert_config = get_modernbert_config(
|
|
1566
|
+
tokenizer.vocab_size, model_size, tokenizer.max_seq_len,
|
|
1567
|
+
global_attn_every_n_layers=getattr(pretrain_cfg, 'global_attn_every_n_layers', 3),
|
|
1568
|
+
local_attention_window=getattr(pretrain_cfg, 'local_attention_window', 128),
|
|
1569
|
+
)
|
|
1570
|
+
bert = ProvenanceModernBERT(bert_config)
|
|
1571
|
+
elif model_type == "llama":
|
|
1572
|
+
from pidsmaker.pretrained.models.llama import ProvenanceLLaMA, get_llama_config
|
|
1573
|
+
rope_theta = getattr(pretrain_cfg, 'llama', None)
|
|
1574
|
+
rope_theta = rope_theta.rope_theta if rope_theta else 10000.0
|
|
1575
|
+
bert_config = get_llama_config(
|
|
1576
|
+
tokenizer.vocab_size, model_size, tokenizer.max_seq_len,
|
|
1577
|
+
rope_theta=rope_theta,
|
|
1578
|
+
)
|
|
1579
|
+
bert = ProvenanceLLaMA(bert_config)
|
|
1580
|
+
elif model_type == "roberta":
|
|
1581
|
+
from pidsmaker.pretrained.models.roberta import ProvenanceRoBERTa, get_roberta_config
|
|
1582
|
+
bert_config = get_roberta_config(tokenizer.vocab_size, model_size, tokenizer.max_seq_len)
|
|
1583
|
+
bert = ProvenanceRoBERTa(bert_config)
|
|
1584
|
+
else:
|
|
1585
|
+
from pidsmaker.pretrained.models.bert import ProvenanceBERT, get_bert_config
|
|
1586
|
+
bert_config = get_bert_config(tokenizer.vocab_size, model_size, tokenizer.max_seq_len)
|
|
1587
|
+
bert = ProvenanceBERT(bert_config)
|
|
1588
|
+
|
|
1589
|
+
# Validate emb_dim matches model hidden size
|
|
1590
|
+
hidden_size = bert_config.d_model if model_type in ("gnn_distill", "spider", "behavior_cluster") else bert_config.hidden_size
|
|
1591
|
+
if emb_dim != hidden_size:
|
|
1592
|
+
raise ValueError(
|
|
1593
|
+
f"featurization.emb_dim ({emb_dim}) does not match "
|
|
1594
|
+
f"SPIDER encoder hidden size ({hidden_size}) for model_size='{model_size}'. "
|
|
1595
|
+
f"Set emb_dim: {hidden_size} in your config."
|
|
1596
|
+
)
|
|
1597
|
+
|
|
1598
|
+
# Load pretrained weights (prefer best checkpoint)
|
|
1599
|
+
pt_path = os.path.join(pretrain_dir, f"pretrain_{model_size}_best.pt")
|
|
1600
|
+
if not os.path.exists(pt_path):
|
|
1601
|
+
pt_path = os.path.join(pretrain_dir, f"pretrain_{model_size}.pt")
|
|
1602
|
+
if not os.path.exists(pt_path):
|
|
1603
|
+
raise FileNotFoundError(f"No pretrained SPIDER checkpoint found in {pretrain_dir}")
|
|
1604
|
+
|
|
1605
|
+
device = "cuda" if torch.cuda.is_available() and not getattr(cfg, '_use_cpu', False) else "cpu"
|
|
1606
|
+
|
|
1607
|
+
sd = torch.load(pt_path, weights_only=True, map_location="cpu")
|
|
1608
|
+
bert.load_state_dict(sd)
|
|
1609
|
+
bert = bert.to(device)
|
|
1610
|
+
bert.eval()
|
|
1611
|
+
log(f"Loaded {model_type} pretrained BERT ({model_size}, H={hidden_size}) from {pt_path}")
|
|
1612
|
+
|
|
1613
|
+
# ── Continue pretraining on target dataset (optional) ─────────────
|
|
1614
|
+
inference_cfg = cfg.feat_inference
|
|
1615
|
+
if inference_cfg.continue_pretrain:
|
|
1616
|
+
if model_type == "gnn_distill":
|
|
1617
|
+
bert = _continue_pretrain_gnn_distill(cfg, bert, tokenizer, pretrain_cfg, inference_cfg, device)
|
|
1618
|
+
elif model_type == "spider":
|
|
1619
|
+
bert = _continue_pretrain_spider(cfg, bert, tokenizer, pretrain_cfg, inference_cfg, device)
|
|
1620
|
+
elif model_type == "behavior_cluster":
|
|
1621
|
+
bert = _continue_pretrain_behavior_cluster(cfg, bert, tokenizer, pretrain_cfg, inference_cfg, device)
|
|
1622
|
+
else:
|
|
1623
|
+
log(f" continue_pretrain not supported for model_type={model_type}, skipping")
|
|
1624
|
+
|
|
1625
|
+
# ── Determine embedding mode for behavior_cluster ──────────────────
|
|
1626
|
+
use_contrastive_head = (
|
|
1627
|
+
model_type == "behavior_cluster"
|
|
1628
|
+
and getattr(pretrain_cfg.behavior_cluster, "use_contrastive_head", False)
|
|
1629
|
+
)
|
|
1630
|
+
if use_contrastive_head:
|
|
1631
|
+
output_dim = pretrain_cfg.behavior_cluster.proj_dim
|
|
1632
|
+
log(f" behavior_cluster: using contrastive head for inference (dim={output_dim})")
|
|
1633
|
+
else:
|
|
1634
|
+
output_dim = hidden_size
|
|
1635
|
+
|
|
1636
|
+
# ── Compute embeddings for all nodes ──────────────────────────────
|
|
1637
|
+
indexid2msg = get_indexid2msg(cfg)
|
|
1638
|
+
sorted_items = sorted(indexid2msg.items(), key=lambda x: int(x[0]))
|
|
1639
|
+
|
|
1640
|
+
# Deduplicate: group node IDs by their unique (ntype, nlabel) text key
|
|
1641
|
+
text_key_to_node_ids = {}
|
|
1642
|
+
for node_id, (ntype, nlabel) in sorted_items:
|
|
1643
|
+
key = (ntype, nlabel)
|
|
1644
|
+
text_key_to_node_ids.setdefault(key, []).append(node_id)
|
|
1645
|
+
|
|
1646
|
+
unique_items = list(text_key_to_node_ids.keys())
|
|
1647
|
+
n_nodes = len(sorted_items)
|
|
1648
|
+
n_unique = len(unique_items)
|
|
1649
|
+
|
|
1650
|
+
indexid2vec = {}
|
|
1651
|
+
total_batches = (n_unique + batch_size - 1) // batch_size
|
|
1652
|
+
|
|
1653
|
+
for batch_idx in range(0, n_unique, batch_size):
|
|
1654
|
+
batch_keys = unique_items[batch_idx:batch_idx + batch_size]
|
|
1655
|
+
batch_num = batch_idx // batch_size
|
|
1656
|
+
|
|
1657
|
+
if batch_num % 20 == 0:
|
|
1658
|
+
log(f" Embedding batch {batch_num+1}/{total_batches} "
|
|
1659
|
+
f"({batch_idx:,}/{n_unique:,} unique labels)")
|
|
1660
|
+
|
|
1661
|
+
# Tokenize all unique labels in batch
|
|
1662
|
+
batch_token_ids = []
|
|
1663
|
+
batch_keys_valid = []
|
|
1664
|
+
for key in batch_keys:
|
|
1665
|
+
ntype, nlabel = key
|
|
1666
|
+
tids = tokenizer.tokenize_node(ntype, nlabel)
|
|
1667
|
+
if tids:
|
|
1668
|
+
batch_token_ids.append(tids)
|
|
1669
|
+
batch_keys_valid.append(key)
|
|
1670
|
+
else:
|
|
1671
|
+
zero_emb = np.zeros(output_dim, dtype=np.float32)
|
|
1672
|
+
for node_id in text_key_to_node_ids[key]:
|
|
1673
|
+
indexid2vec[int(node_id)] = zero_emb
|
|
1674
|
+
|
|
1675
|
+
if not batch_token_ids:
|
|
1676
|
+
continue
|
|
1677
|
+
|
|
1678
|
+
# Pad and encode
|
|
1679
|
+
max_len = min(max(len(t) for t in batch_token_ids), tokenizer.max_seq_len)
|
|
1680
|
+
B = len(batch_token_ids)
|
|
1681
|
+
input_ids = torch.full((B, max_len), tokenizer.pad_id, dtype=torch.long)
|
|
1682
|
+
attention_mask = torch.zeros(B, max_len, dtype=torch.bool)
|
|
1683
|
+
for i, tids in enumerate(batch_token_ids):
|
|
1684
|
+
L = min(len(tids), max_len)
|
|
1685
|
+
input_ids[i, :L] = torch.tensor(tids[:L])
|
|
1686
|
+
attention_mask[i, :L] = True
|
|
1687
|
+
|
|
1688
|
+
with torch.no_grad():
|
|
1689
|
+
if use_contrastive_head:
|
|
1690
|
+
# Use full forward: encoder → mean pool → contrastive projection
|
|
1691
|
+
out = bert.modified_fwd(
|
|
1692
|
+
input_ids.to(device),
|
|
1693
|
+
attention_mask.to(device),
|
|
1694
|
+
)
|
|
1695
|
+
pooled_np = out.projection.cpu().numpy() # [B, proj_dim], already L2-normalized
|
|
1696
|
+
else:
|
|
1697
|
+
# Use raw encoder hidden states → mean pool
|
|
1698
|
+
hidden = bert.modified_fwd(
|
|
1699
|
+
input_ids.to(device),
|
|
1700
|
+
attention_mask.to(device),
|
|
1701
|
+
labels=torch.full_like(input_ids, -100).to(device),
|
|
1702
|
+
skip_cls=True,
|
|
1703
|
+
) # [B, max_len, H]
|
|
1704
|
+
mask_f = attention_mask.to(device).unsqueeze(-1).float()
|
|
1705
|
+
pooled = (hidden * mask_f).sum(dim=1) / mask_f.sum(dim=1).clamp(min=1) # [B, H]
|
|
1706
|
+
pooled_np = pooled.cpu().numpy()
|
|
1707
|
+
|
|
1708
|
+
# Normalize and assign to all nodes sharing the same text label
|
|
1709
|
+
for i, key in enumerate(batch_keys_valid):
|
|
1710
|
+
emb = pooled_np[i]
|
|
1711
|
+
norm = np.linalg.norm(emb)
|
|
1712
|
+
if norm > 1e-12:
|
|
1713
|
+
emb = emb / norm
|
|
1714
|
+
for node_id in text_key_to_node_ids[key]:
|
|
1715
|
+
indexid2vec[int(node_id)] = emb
|
|
1716
|
+
|
|
1717
|
+
_maybe_embed_synthetic_nodes(cfg, bert, tokenizer, hidden_size, device)
|
|
1718
|
+
|
|
1719
|
+
indexid2vec = _apply_rename_attack(
|
|
1720
|
+
cfg, indexid2vec, indexid2msg, bert, tokenizer, output_dim, device,
|
|
1721
|
+
)
|
|
1722
|
+
|
|
1723
|
+
del bert
|
|
1724
|
+
if torch.cuda.is_available():
|
|
1725
|
+
torch.cuda.empty_cache()
|
|
1726
|
+
|
|
1727
|
+
log(f"Computed {len(indexid2vec):,} static BERT node embeddings (dim={output_dim})")
|
|
1728
|
+
return indexid2vec
|