pidsmaker 4.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of pidsmaker might be problematic. Click here for more details.
- pidsmaker/__init__.py +22 -0
- pidsmaker/cli.py +32 -0
- pidsmaker/config/__init__.py +2 -0
- pidsmaker/config/config.py +2100 -0
- pidsmaker/config/pipeline.py +1768 -0
- pidsmaker/config/schemas.py +1032 -0
- pidsmaker/datasets.py +222 -0
- pidsmaker/debug_tests.py +30 -0
- pidsmaker/decoders/__init__.py +5 -0
- pidsmaker/decoders/custom_edge_mlp_decoder.py +17 -0
- pidsmaker/decoders/custom_mlp_decoder.py +10 -0
- pidsmaker/decoders/edge_linear_decoder.py +16 -0
- pidsmaker/decoders/inner_product_decoder.py +18 -0
- pidsmaker/decoders/nodlink_decoder.py +56 -0
- pidsmaker/detection/__init__.py +0 -0
- pidsmaker/detection/evaluation_methods/__init__.py +9 -0
- pidsmaker/detection/evaluation_methods/edge_evaluation.py +259 -0
- pidsmaker/detection/evaluation_methods/evaluation_utils.py +1730 -0
- pidsmaker/detection/evaluation_methods/host_two_stage_evaluation.py +115 -0
- pidsmaker/detection/evaluation_methods/node_evaluation.py +463 -0
- pidsmaker/detection/evaluation_methods/node_tw_evaluation.py +196 -0
- pidsmaker/detection/evaluation_methods/plot.py +192 -0
- pidsmaker/detection/evaluation_methods/queue_evaluation.py +451 -0
- pidsmaker/detection/evaluation_methods/tw_evaluation.py +95 -0
- pidsmaker/detection/flash_detection.py +162 -0
- pidsmaker/detection/magic_knn.py +190 -0
- pidsmaker/detection/node_scoring.py +52 -0
- pidsmaker/detection/threatrace_detection.py +65 -0
- pidsmaker/detection/training_methods/__init__.py +1 -0
- pidsmaker/detection/training_methods/inference_loop.py +293 -0
- pidsmaker/detection/training_methods/ocrapt_early_stop.py +165 -0
- pidsmaker/detection/training_methods/threatrace_training.py +169 -0
- pidsmaker/detection/training_methods/training_loop.py +377 -0
- pidsmaker/encoders/__init__.py +22 -0
- pidsmaker/encoders/argus_encoder.py +69 -0
- pidsmaker/encoders/custom_mlp.py +75 -0
- pidsmaker/encoders/custom_mlp_encoder.py +10 -0
- pidsmaker/encoders/egraphsage_encoder.py +56 -0
- pidsmaker/encoders/gat.py +67 -0
- pidsmaker/encoders/gcn.py +27 -0
- pidsmaker/encoders/gin.py +48 -0
- pidsmaker/encoders/glstm.py +298 -0
- pidsmaker/encoders/graph_attention.py +63 -0
- pidsmaker/encoders/gru.py +29 -0
- pidsmaker/encoders/hetero/__init__.py +4 -0
- pidsmaker/encoders/hetero/ancestor_encoder.py +98 -0
- pidsmaker/encoders/hetero/entity_encoder.py +33 -0
- pidsmaker/encoders/hetero/event_encoder.py +81 -0
- pidsmaker/encoders/hetero/hetero_graph_transformer.py +40 -0
- pidsmaker/encoders/lares_encoder.py +68 -0
- pidsmaker/encoders/linear_encoder.py +16 -0
- pidsmaker/encoders/magic_encoder.py +161 -0
- pidsmaker/encoders/rcaid_encoder.py +81 -0
- pidsmaker/encoders/rgcn.py +75 -0
- pidsmaker/encoders/sage.py +51 -0
- pidsmaker/encoders/shadewatcher_encoder.py +149 -0
- pidsmaker/encoders/sum_aggregation.py +20 -0
- pidsmaker/encoders/temporal_wrappers.py +80 -0
- pidsmaker/encoders/textrcnn.py +82 -0
- pidsmaker/encoders/tgn_encoder.py +193 -0
- pidsmaker/experiments/tuning.py +102 -0
- pidsmaker/experiments/uncertainty.py +261 -0
- pidsmaker/factory.py +1456 -0
- pidsmaker/featurization/__init__.py +0 -0
- pidsmaker/featurization/feat_inference_methods/__init__.py +7 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_HFH.py +31 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_TRW.py +67 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_alacarte.py +16 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_doc2vec.py +54 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_fasttext.py +38 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_flash.py +70 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_graph2vec.py +85 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_ocrapt_features.py +95 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_pretrained.py +1729 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_word2vec.py +56 -0
- pidsmaker/featurization/featurization_methods/__init__.py +0 -0
- pidsmaker/featurization/featurization_methods/build_trw.py +67 -0
- pidsmaker/featurization/featurization_methods/featurization_alacarte.py +748 -0
- pidsmaker/featurization/featurization_methods/featurization_doc2vec.py +99 -0
- pidsmaker/featurization/featurization_methods/featurization_fasttext.py +75 -0
- pidsmaker/featurization/featurization_methods/featurization_flash.py +203 -0
- pidsmaker/featurization/featurization_methods/featurization_graph2vec.py +243 -0
- pidsmaker/featurization/featurization_methods/featurization_trw.py +115 -0
- pidsmaker/featurization/featurization_methods/featurization_word2vec.py +87 -0
- pidsmaker/featurization/featurization_utils.py +275 -0
- pidsmaker/featurization/utils/build_random_walks.py +68 -0
- pidsmaker/featurization/utils/trw.py +203 -0
- pidsmaker/hetero.py +81 -0
- pidsmaker/losses.py +170 -0
- pidsmaker/main.py +377 -0
- pidsmaker/mimicry.py +284 -0
- pidsmaker/model.py +382 -0
- pidsmaker/objectives/__init__.py +16 -0
- pidsmaker/objectives/autoencode_edge_emb.py +43 -0
- pidsmaker/objectives/deep_graph_infomax.py +94 -0
- pidsmaker/objectives/detect_few_shot.py +21 -0
- pidsmaker/objectives/one_class.py +75 -0
- pidsmaker/objectives/predict_edge_contrastive.py +165 -0
- pidsmaker/objectives/predict_edge_supervised.py +77 -0
- pidsmaker/objectives/predict_edge_type.py +28 -0
- pidsmaker/objectives/predict_masked_struct.py +49 -0
- pidsmaker/objectives/predict_node_type.py +36 -0
- pidsmaker/objectives/predict_process_tag.py +169 -0
- pidsmaker/objectives/predict_snapshot_embedding.py +97 -0
- pidsmaker/objectives/reconstruct_edge_emb.py +16 -0
- pidsmaker/objectives/reconstruct_masked_feat.py +51 -0
- pidsmaker/objectives/reconstruct_node_emb.py +13 -0
- pidsmaker/objectives/reconstruct_node_feat.py +13 -0
- pidsmaker/objectives/validation_wrapper.py +55 -0
- pidsmaker/preprocessing/__init__.py +0 -0
- pidsmaker/preprocessing/build_graph_methods/__init__.py +1 -0
- pidsmaker/preprocessing/build_graph_methods/build_default_graphs.py +830 -0
- pidsmaker/preprocessing/build_graph_methods/build_magic_graphs.py +220 -0
- pidsmaker/preprocessing/cleaning.py +258 -0
- pidsmaker/preprocessing/transformation_methods/__init__.py +2 -0
- pidsmaker/preprocessing/transformation_methods/attack_generation/synthetic_attack_naive.py +194 -0
- pidsmaker/preprocessing/transformation_methods/transformation_dag.py +28 -0
- pidsmaker/preprocessing/transformation_methods/transformation_merge_edges.py +136 -0
- pidsmaker/preprocessing/transformation_methods/transformation_rcaid_pseudo_graph.py +510 -0
- pidsmaker/preprocessing/transformation_methods/transformation_undirected.py +24 -0
- pidsmaker/preprocessing/transformation_methods/transformation_utils.py +36 -0
- pidsmaker/pretrained/__init__.py +5 -0
- pidsmaker/pretrained/data/__init__.py +4 -0
- pidsmaker/pretrained/data/behavior_signatures.py +548 -0
- pidsmaker/pretrained/data/canonical_tokens.py +1035 -0
- pidsmaker/pretrained/data/edge_filter.py +381 -0
- pidsmaker/pretrained/data/entity_classes.py +476 -0
- pidsmaker/pretrained/data/sampler.py +926 -0
- pidsmaker/pretrained/data/tokenizer_bpe.py +1659 -0
- pidsmaker/pretrained/detect.py +1432 -0
- pidsmaker/pretrained/embedding_generator.py +252 -0
- pidsmaker/pretrained/finetune.py +1437 -0
- pidsmaker/pretrained/models/__init__.py +20 -0
- pidsmaker/pretrained/models/behavior.py +348 -0
- pidsmaker/pretrained/models/bert.py +286 -0
- pidsmaker/pretrained/models/deepwalk.py +128 -0
- pidsmaker/pretrained/models/dgi.py +120 -0
- pidsmaker/pretrained/models/gae.py +114 -0
- pidsmaker/pretrained/models/gnn_distill.py +475 -0
- pidsmaker/pretrained/models/graphmae.py +373 -0
- pidsmaker/pretrained/models/hf_pretrained.py +213 -0
- pidsmaker/pretrained/models/llama.py +110 -0
- pidsmaker/pretrained/models/modernbert.py +567 -0
- pidsmaker/pretrained/models/roberta.py +147 -0
- pidsmaker/pretrained/models/rope_utils.py +99 -0
- pidsmaker/pretrained/models/ropebert.py +322 -0
- pidsmaker/pretrained/models/spider.py +204 -0
- pidsmaker/pretrained/models/tgn.py +770 -0
- pidsmaker/pretrained/pretrain/__init__.py +3 -0
- pidsmaker/pretrained/pretrain/pretrain_behavior_cluster.py +513 -0
- pidsmaker/pretrained/pretrain/pretrain_common.py +585 -0
- pidsmaker/pretrained/pretrain/pretrain_deepwalk.py +31 -0
- pidsmaker/pretrained/pretrain/pretrain_dgi.py +143 -0
- pidsmaker/pretrained/pretrain/pretrain_gae.py +143 -0
- pidsmaker/pretrained/pretrain/pretrain_gnn_distill.py +438 -0
- pidsmaker/pretrained/pretrain/pretrain_graphmae.py +151 -0
- pidsmaker/pretrained/pretrain/pretrain_hf.py +169 -0
- pidsmaker/pretrained/pretrain/pretrain_main.py +276 -0
- pidsmaker/pretrained/pretrain/pretrain_mlm.py +491 -0
- pidsmaker/pretrained/pretrain/pretrain_spider.py +502 -0
- pidsmaker/pretrained/training_utils.py +157 -0
- pidsmaker/process_reapr_gt.py +101 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-CADETS/node_Nginx_Backdoor_06.csv +8 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-CADETS/node_Nginx_Backdoor_11.csv +4 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-CADETS/node_Nginx_Backdoor_12.csv +43 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-CADETS/node_Nginx_Backdoor_13.csv +24 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0411.csv +41 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0412.csv +0 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_browser_0412.csv +1 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +63 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +56 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +61 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +58 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-TRACE/node_trace_e3_firefox_0410.csv +11 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +11 -0
- pidsmaker/resources/Ground_Truth/orthrus/E3-TRACE/node_trace_e3_pine_0413.csv +14 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT.csv +19 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT_17.csv +107 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_appstarter_0515.csv +26 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_firefox_0517.csv +1 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_lockwatch_0517.csv +17 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_tester_0517.csv +8 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_bits_0515.csv +54 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_copykatz_0509.csv +87 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_dns_0517.csv +11 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_drakon_0517.csv +6 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-THEIA/node_THEIA_1_Firefox_Drakon_APT_BinFmt_Elevate_Inject.csv +70 -0
- pidsmaker/resources/Ground_Truth/orthrus/E5-TRACE/node_Trace_Firefox_Drakon.csv +71 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m1.csv +1 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m2.csv +1 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m3.csv +1 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m4.csv +5 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m5.csv +23 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m6.csv +18 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_s1.csv +1 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_s2.csv +1 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_s3.csv +16 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_s4.csv +22 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m1.csv +126 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m2.csv +105 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m3.csv +94 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m4.csv +139 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m5.csv +228 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m6.csv +131 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_s1.csv +118 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_s2.csv +89 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_s3.csv +133 -0
- pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_s4.csv +135 -0
- pidsmaker/resources/Ground_Truth/orthrus/carbanakv2_edr/carbanakv2_edr.csv +2453 -0
- pidsmaker/resources/Ground_Truth/orthrus/h051/node_h051_0925.csv +114 -0
- pidsmaker/resources/Ground_Truth/orthrus/h201/node_h201_0923.csv +2905 -0
- pidsmaker/resources/Ground_Truth/orthrus/h501/node_h501_0924.csv +749 -0
- pidsmaker/resources/Ground_Truth/orthrus/readme.md +98 -0
- pidsmaker/resources/Ground_Truth/reapr/E3-CADETS/node_Nginx_Backdoor_06.csv +3 -0
- pidsmaker/resources/Ground_Truth/reapr/E3-CADETS/node_Nginx_Backdoor_12.csv +655 -0
- pidsmaker/resources/Ground_Truth/reapr/E3-CADETS/node_Nginx_Backdoor_13.csv +770 -0
- pidsmaker/resources/Ground_Truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +0 -0
- pidsmaker/resources/Ground_Truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +18 -0
- pidsmaker/resources/Ground_Truth/reapr/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +42 -0
- pidsmaker/resources/Ground_Truth/reapr/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +81 -0
- pidsmaker/resources/Ground_Truth/reapr/E3-TRACE/node_trace_e3_firefox_0410.csv +37 -0
- pidsmaker/resources/Ground_Truth/reapr/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +9 -0
- pidsmaker/resources/Ground_Truth/reapr/E3-TRACE/node_trace_e3_pine_0413.csv +40 -0
- pidsmaker/resources/Ground_Truth/threatrace/E3-CADETS/ground_truth.txt +12858 -0
- pidsmaker/resources/Ground_Truth/threatrace/E3-FIVEDIRECTIONS/ground_truth.txt +18420 -0
- pidsmaker/resources/Ground_Truth/threatrace/E3-THEIA/ground_truth.txt +25363 -0
- pidsmaker/resources/Ground_Truth/threatrace/E3-TRACE/ground_truth.txt +68265 -0
- pidsmaker/resources/Ground_Truth/threatrace/README.md +123 -0
- pidsmaker/resources/config/anomal_e.yml +25 -0
- pidsmaker/resources/config/argus.yml +56 -0
- pidsmaker/resources/config/attack_edges/cadets_e3.yml +435 -0
- pidsmaker/resources/config/attack_edges/cadets_e5.yml +407 -0
- pidsmaker/resources/config/attack_edges/theia_e3.yml +382 -0
- pidsmaker/resources/config/attack_edges/theia_e5.yml +387 -0
- pidsmaker/resources/config/attack_edges/trace_e3.yml +415 -0
- pidsmaker/resources/config/attack_edges/trace_e5.yml +417 -0
- pidsmaker/resources/config/default.yml +315 -0
- pidsmaker/resources/config/egraphsage.yml +95 -0
- pidsmaker/resources/config/euler.yml +104 -0
- pidsmaker/resources/config/eval/eval_set_clustering.json +3170 -0
- pidsmaker/resources/config/experiments/tuning/components/tuning_featurization_methods.yml +29 -0
- pidsmaker/resources/config/experiments/tuning/systems/clearscope_e5/tuning_orthrus.yml +14 -0
- pidsmaker/resources/config/experiments/tuning/systems/default/tuning_default_baselines.yml +13 -0
- pidsmaker/resources/config/experiments/tuning/systems/default/tuning_orthrus_fixed.yml +16 -0
- pidsmaker/resources/config/experiments/uncertainty/none.yml +5 -0
- pidsmaker/resources/config/experiments/uncertainty/run_n_times.yml +12 -0
- pidsmaker/resources/config/experiments/uncertainty/run_n_times_hyperparameters.yml +12 -0
- pidsmaker/resources/config/experiments/uncertainty/uncertainty.yml +22 -0
- pidsmaker/resources/config/flash.yml +79 -0
- pidsmaker/resources/config/jbeil.yml +65 -0
- pidsmaker/resources/config/kairos.yml +121 -0
- pidsmaker/resources/config/lares.yml +115 -0
- pidsmaker/resources/config/magic.yml +86 -0
- pidsmaker/resources/config/nodlink.yml +79 -0
- pidsmaker/resources/config/ocrapt.yml +91 -0
- pidsmaker/resources/config/orthrus.yml +120 -0
- pidsmaker/resources/config/orthrus_fixed.yml +17 -0
- pidsmaker/resources/config/orthrus_non_snooped.yml +17 -0
- pidsmaker/resources/config/pretrained/README.md +101 -0
- pidsmaker/resources/config/pretrained/cybergfm/cybergfm.yml +49 -0
- pidsmaker/resources/config/pretrained/pretrained.yml +190 -0
- pidsmaker/resources/config/pretrained/pretrained_flash.yml +9 -0
- pidsmaker/resources/config/pretrained/pretrained_kairos.yml +12 -0
- pidsmaker/resources/config/pretrained/pretrained_magic.yml +1 -0
- pidsmaker/resources/config/pretrained/pretrained_nodlink.yml +1 -0
- pidsmaker/resources/config/pretrained/pretrained_orthrus.yml +1 -0
- pidsmaker/resources/config/pretrained/pretrained_supervised.yml +13 -0
- pidsmaker/resources/config/pretrained/pretrained_threatrace.yml +8 -0
- pidsmaker/resources/config/pretrained/pretrained_velox.yml +14 -0
- pidsmaker/resources/config/prographer.yml +136 -0
- pidsmaker/resources/config/rcaid.yml +88 -0
- pidsmaker/resources/config/shadewatcher.yml +146 -0
- pidsmaker/resources/config/tests.yml +10 -0
- pidsmaker/resources/config/threatrace.yml +73 -0
- pidsmaker/resources/config/tuned_baselines/optc_net/tuned_argus.yml +4 -0
- pidsmaker/resources/config/tuned_baselines/optc_net/tuned_lares.yml +13 -0
- pidsmaker/resources/config/velox.yml +10 -0
- pidsmaker/resources/config/viz_config.yml +10 -0
- pidsmaker/tasks/__init__.py +10 -0
- pidsmaker/tasks/batching.py +49 -0
- pidsmaker/tasks/construction.py +31 -0
- pidsmaker/tasks/evaluation.py +232 -0
- pidsmaker/tasks/feat_inference.py +413 -0
- pidsmaker/tasks/featurization.py +43 -0
- pidsmaker/tasks/training.py +19 -0
- pidsmaker/tasks/transformation.py +308 -0
- pidsmaker/tasks/triage.py +143 -0
- pidsmaker/tgn.py +635 -0
- pidsmaker/tokenization/__init__.py +112 -0
- pidsmaker/tokenization/base.py +58 -0
- pidsmaker/tokenization/bpe_tokenizer.py +83 -0
- pidsmaker/tokenization/hf_tokenizer.py +61 -0
- pidsmaker/tokenization/hierarchical_tokenizer.py +44 -0
- pidsmaker/tokenization/label_tokenizer.py +24 -0
- pidsmaker/tokenization/nltk_tokenizer.py +84 -0
- pidsmaker/tokenization/substitution.py +295 -0
- pidsmaker/triage/__init__.py +0 -0
- pidsmaker/triage/tracing_methods/__init__.py +1 -0
- pidsmaker/triage/tracing_methods/depimpact.py +213 -0
- pidsmaker/triage/tracing_methods/depimpact_utils.py +537 -0
- pidsmaker/triage/tracing_methods/ocrapt_subgraph.py +267 -0
- pidsmaker/utils/__init__.py +0 -0
- pidsmaker/utils/cache_utils.py +256 -0
- pidsmaker/utils/data_utils.py +1742 -0
- pidsmaker/utils/database.py +204 -0
- pidsmaker/utils/dataset_utils.py +413 -0
- pidsmaker/utils/dataset_writer.py +1057 -0
- pidsmaker/utils/graph_store.py +634 -0
- pidsmaker/utils/labelling.py +447 -0
- pidsmaker/utils/loss_files.py +193 -0
- pidsmaker/utils/process_tags.py +44 -0
- pidsmaker/utils/utils.py +730 -0
- pidsmaker/vizgen/__init__.py +1 -0
- pidsmaker/vizgen/dimensionality_reduction.py +249 -0
- pidsmaker/vizgen/embed_exporter.py +467 -0
- pidsmaker/vizgen/exporter.py +493 -0
- pidsmaker/vizgen/html_builder.py +936 -0
- pidsmaker/vizgen/web/__init__.py +1 -0
- pidsmaker/vizgen/web/export.py +62 -0
- pidsmaker/vizgen/web/static/css/app.css +250 -0
- pidsmaker/vizgen/web/static/index.html +182 -0
- pidsmaker/vizgen/web/static/js/app.js +627 -0
- pidsmaker/vizgen/web/static/js/campaign.js +123 -0
- pidsmaker/vizgen/web/static/js/data.js +119 -0
- pidsmaker/vizgen/web/static/js/dialogs.js +240 -0
- pidsmaker/vizgen/web/static/js/jobs.js +75 -0
- pidsmaker/vizgen/web/static/js/scene.js +651 -0
- pidsmaker/vizgen/web/static/js/ui.js +370 -0
- pidsmaker/vizgen/web/static/vendor/OrbitControls.js +1045 -0
- pidsmaker/vizgen/web/static/vendor/d3.v4.min.js +2 -0
- pidsmaker/vizgen/web/static/vendor/three.min.js +6 -0
- pidsmaker/vizgen/web/viz_server.py +2176 -0
- pidsmaker-4.0.0.dist-info/METADATA +596 -0
- pidsmaker-4.0.0.dist-info/RECORD +338 -0
- pidsmaker-4.0.0.dist-info/WHEEL +5 -0
- pidsmaker-4.0.0.dist-info/entry_points.txt +2 -0
- pidsmaker-4.0.0.dist-info/licenses/LICENSE +201 -0
- pidsmaker-4.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,513 @@
|
|
|
1
|
+
"""Behavior Cluster pretraining branch for SPIDER."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import random
|
|
5
|
+
import time
|
|
6
|
+
from collections import defaultdict
|
|
7
|
+
|
|
8
|
+
import torch
|
|
9
|
+
from torch.optim import AdamW
|
|
10
|
+
|
|
11
|
+
import wandb
|
|
12
|
+
|
|
13
|
+
from pidsmaker.utils.utils import log
|
|
14
|
+
from ..training_utils import WarmupCosineScheduler, pad_token_id_lists, build_pk_batches
|
|
15
|
+
from ..data.tokenizer_bpe import ProvenanceTokenizerBPE as ProvenanceTokenizer
|
|
16
|
+
from .pretrain_common import _eval_knn_on_eval_set
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def pretrain_behavior_cluster(cfg, spider_cfg, sampler_pairs, combined_indexid2msg, out_dir, device,
|
|
20
|
+
model_size, max_seq_len, bpe_vocab_size, tokenizer_mode,
|
|
21
|
+
normalize_netflow_ips, canonicalize_neighbors, spider_path,
|
|
22
|
+
total_tokens, warmup_tokens, batch_size, lr):
|
|
23
|
+
from ..models.behavior import (
|
|
24
|
+
ProvenanceBehaviorModel,
|
|
25
|
+
get_behavior_encoder_config,
|
|
26
|
+
behavior_combined_loss,
|
|
27
|
+
)
|
|
28
|
+
from ..data.behavior_signatures import (
|
|
29
|
+
build_behavior_dataset,
|
|
30
|
+
BehaviorLabelVocab,
|
|
31
|
+
dump_entity_classifications,
|
|
32
|
+
dump_behavior_signatures,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
bc_cfg = spider_cfg.behavior_cluster
|
|
36
|
+
bc_proj_dim = bc_cfg.proj_dim
|
|
37
|
+
bc_bce_weight = bc_cfg.bce_weight
|
|
38
|
+
bc_contrastive_weight = bc_cfg.contrastive_weight
|
|
39
|
+
bc_temperature = bc_cfg.temperature
|
|
40
|
+
|
|
41
|
+
bc_min_sig_size = bc_cfg.min_signature_size
|
|
42
|
+
bc_filter_noisy = bc_cfg.filter_noisy_edges
|
|
43
|
+
bc_max_per_class = bc_cfg.max_entities_per_class
|
|
44
|
+
bc_min_per_class = bc_cfg.min_entities_per_class
|
|
45
|
+
bc_samples_per_class = bc_cfg.samples_per_class
|
|
46
|
+
bc_strip_entity_type = bc_cfg.strip_entity_type
|
|
47
|
+
bc_bce_mode = bc_cfg.bce_mode
|
|
48
|
+
bc_contrastive_target = bc_cfg.contrastive_target
|
|
49
|
+
|
|
50
|
+
# ── Build or load tokenizer ────────────────────────────────────
|
|
51
|
+
if spider_path:
|
|
52
|
+
tok_path = os.path.join(spider_path, "tokenizer.pt")
|
|
53
|
+
log(f"Loading tokenizer from {tok_path}")
|
|
54
|
+
tokenizer = ProvenanceTokenizer(cfg, max_seq_len=max_seq_len, bpe_vocab_size=bpe_vocab_size,
|
|
55
|
+
mode=tokenizer_mode, normalize_netflow_ips=normalize_netflow_ips,
|
|
56
|
+
canonicalize_neighbors=canonicalize_neighbors)
|
|
57
|
+
tokenizer.load(tok_path)
|
|
58
|
+
tokenizer.max_seq_len = max_seq_len
|
|
59
|
+
else:
|
|
60
|
+
walk_label_corpus = []
|
|
61
|
+
for sampler, ds_indexid2msg in sampler_pairs:
|
|
62
|
+
for node in sampler.nodes:
|
|
63
|
+
if node in ds_indexid2msg:
|
|
64
|
+
walk_label_corpus.append(ds_indexid2msg[node])
|
|
65
|
+
log(f"Behavior cluster: {len(walk_label_corpus):,} entity labels for tokenizer")
|
|
66
|
+
|
|
67
|
+
tokenizer = ProvenanceTokenizer(
|
|
68
|
+
cfg, max_seq_len=max_seq_len, bpe_vocab_size=bpe_vocab_size,
|
|
69
|
+
mode=tokenizer_mode, normalize_netflow_ips=normalize_netflow_ips,
|
|
70
|
+
canonicalize_neighbors=canonicalize_neighbors,
|
|
71
|
+
strip_entity_type=bc_strip_entity_type,
|
|
72
|
+
)
|
|
73
|
+
tokenizer.build_vocab(combined_indexid2msg, walk_label_corpus=walk_label_corpus)
|
|
74
|
+
log(f"Vocabulary size: {tokenizer.vocab_size}")
|
|
75
|
+
tokenizer.save(os.path.join(out_dir, "tokenizer.pt"))
|
|
76
|
+
|
|
77
|
+
# ── Build behavior signature dataset (always recomputed — depends on entity_classes.py) ──
|
|
78
|
+
log("Building behavior signature dataset (extracting full 1-hop signatures)...")
|
|
79
|
+
label_to_signature, label_to_entities_raw, vocab = build_behavior_dataset(
|
|
80
|
+
sampler_pairs, combined_indexid2msg,
|
|
81
|
+
filter_noisy=bc_filter_noisy,
|
|
82
|
+
min_signature_size=bc_min_sig_size,
|
|
83
|
+
)
|
|
84
|
+
log(f"Behavior signatures: {len(label_to_signature):,} unique entity labels, "
|
|
85
|
+
f"{vocab.size:,} behavior labels in vocabulary")
|
|
86
|
+
|
|
87
|
+
# Save for analysis
|
|
88
|
+
vocab.save(os.path.join(out_dir, "behavior_vocab.txt"))
|
|
89
|
+
|
|
90
|
+
# Dump reports
|
|
91
|
+
classifications_path = os.path.join(out_dir, "entity_classifications.txt")
|
|
92
|
+
dump_entity_classifications(
|
|
93
|
+
sampler_pairs, filter_noisy=bc_filter_noisy, output_path=classifications_path,
|
|
94
|
+
)
|
|
95
|
+
log(f"Entity classification report written to {classifications_path}")
|
|
96
|
+
|
|
97
|
+
signatures_path = os.path.join(out_dir, "behavior_signatures.txt")
|
|
98
|
+
dump_behavior_signatures(label_to_signature, output_path=signatures_path)
|
|
99
|
+
log(f"Behavior signatures report written to {signatures_path}")
|
|
100
|
+
|
|
101
|
+
# ── Tokenize all entities and attach token IDs ─────────────────
|
|
102
|
+
if bc_filter_noisy:
|
|
103
|
+
from ..data.edge_filter import _is_noisy_file, _is_noisy_process
|
|
104
|
+
|
|
105
|
+
label_to_entities = defaultdict(list)
|
|
106
|
+
for label_key, raw_entities in label_to_entities_raw.items():
|
|
107
|
+
ntype, nlabel = label_key
|
|
108
|
+
entity_ids = tokenizer.tokenize_node(ntype, nlabel)
|
|
109
|
+
if entity_ids:
|
|
110
|
+
for node_id, sidx in raw_entities:
|
|
111
|
+
label_to_entities[label_key].append((node_id, sidx, entity_ids))
|
|
112
|
+
|
|
113
|
+
n_before_dedup = len(label_to_entities)
|
|
114
|
+
|
|
115
|
+
# Track per-class counts before dedup
|
|
116
|
+
from ..data.entity_classes import classify_entity
|
|
117
|
+
pre_dedup_class_counts = defaultdict(int)
|
|
118
|
+
for label_key in label_to_entities:
|
|
119
|
+
ntype, nlabel = label_key
|
|
120
|
+
pre_dedup_class_counts[classify_entity(ntype, nlabel)] += 1
|
|
121
|
+
|
|
122
|
+
# ── Post-tokenization dedup: merge labels with identical token sequences ──
|
|
123
|
+
# e.g. /proc/123/stat and /proc/456/stat both tokenize to [PROC_FS] [NUMBER] stat
|
|
124
|
+
token_sig_to_label = {} # tuple(token_ids) → first label_key seen
|
|
125
|
+
merged_count = 0
|
|
126
|
+
for label_key in list(label_to_entities.keys()):
|
|
127
|
+
entity_ids = label_to_entities[label_key][0][2] # all entities share same token_ids
|
|
128
|
+
token_sig = tuple(entity_ids)
|
|
129
|
+
if token_sig in token_sig_to_label:
|
|
130
|
+
# Merge into existing: union signatures, combine entities
|
|
131
|
+
canonical = token_sig_to_label[token_sig]
|
|
132
|
+
label_to_signature[canonical] = label_to_signature[canonical] | label_to_signature[label_key]
|
|
133
|
+
label_to_entities[canonical].extend(label_to_entities[label_key])
|
|
134
|
+
del label_to_entities[label_key]
|
|
135
|
+
del label_to_signature[label_key]
|
|
136
|
+
merged_count += 1
|
|
137
|
+
else:
|
|
138
|
+
token_sig_to_label[token_sig] = label_key
|
|
139
|
+
|
|
140
|
+
n_total = sum(len(v) for v in label_to_entities.values())
|
|
141
|
+
log(f"Behavior cluster: {n_total:,} trainable entities, "
|
|
142
|
+
f"{len(label_to_entities):,} unique labels "
|
|
143
|
+
f"(deduped {merged_count:,} from {n_before_dedup:,})")
|
|
144
|
+
|
|
145
|
+
# Write per-class dedup report
|
|
146
|
+
post_dedup_class_counts = defaultdict(int)
|
|
147
|
+
for label_key in label_to_entities:
|
|
148
|
+
ntype, nlabel = label_key
|
|
149
|
+
post_dedup_class_counts[classify_entity(ntype, nlabel)] += 1
|
|
150
|
+
|
|
151
|
+
dedup_report_path = os.path.join(out_dir, "tokenization_dedup_report.txt")
|
|
152
|
+
all_classes = sorted(pre_dedup_class_counts.keys(), key=lambda c: -pre_dedup_class_counts[c])
|
|
153
|
+
with open(dedup_report_path, "w") as f:
|
|
154
|
+
f.write(f"{'CLASS':<28} {'PRE-DEDUP':>10} {'POST-DEDUP':>12} {'REDUCTION':>10}\n")
|
|
155
|
+
f.write("-" * 64 + "\n")
|
|
156
|
+
for cls in all_classes:
|
|
157
|
+
pre = pre_dedup_class_counts[cls]
|
|
158
|
+
post = post_dedup_class_counts.get(cls, 0)
|
|
159
|
+
reduction = 100 * (1 - post / pre) if pre > 0 else 0
|
|
160
|
+
f.write(f" {cls:<26} {pre:>10,} {post:>12,} {reduction:>9.1f}%\n")
|
|
161
|
+
total_pre = sum(pre_dedup_class_counts.values())
|
|
162
|
+
total_post = sum(post_dedup_class_counts.values())
|
|
163
|
+
total_red = 100 * (1 - total_post / total_pre) if total_pre > 0 else 0
|
|
164
|
+
f.write("-" * 64 + "\n")
|
|
165
|
+
f.write(f" {'TOTAL':<26} {total_pre:>10,} {total_post:>12,} {total_red:>9.1f}%\n")
|
|
166
|
+
log(f"Tokenization dedup report: {dedup_report_path}")
|
|
167
|
+
|
|
168
|
+
# ── Pre-compute target vectors and class IDs (done once, reused every epoch) ──
|
|
169
|
+
label_to_target = {}
|
|
170
|
+
for label_key, sig in label_to_signature.items():
|
|
171
|
+
if label_key in label_to_entities:
|
|
172
|
+
label_to_target[label_key] = vocab.signature_to_vector(sig)
|
|
173
|
+
|
|
174
|
+
# Assign class IDs: identical signatures → same class
|
|
175
|
+
sig_to_class_id = {}
|
|
176
|
+
label_to_class_id = {}
|
|
177
|
+
for label_key, sig in label_to_signature.items():
|
|
178
|
+
if label_key in label_to_target:
|
|
179
|
+
if sig not in sig_to_class_id:
|
|
180
|
+
sig_to_class_id[sig] = len(sig_to_class_id)
|
|
181
|
+
label_to_class_id[label_key] = sig_to_class_id[sig]
|
|
182
|
+
|
|
183
|
+
# Assign entity class IDs for bce_mode="class" (coarse functional classes)
|
|
184
|
+
entity_class_to_id = {}
|
|
185
|
+
label_to_entity_class_id = {}
|
|
186
|
+
for label_key in label_to_target:
|
|
187
|
+
ntype, nlabel = label_key
|
|
188
|
+
ecls = classify_entity(ntype, nlabel)
|
|
189
|
+
if ecls not in entity_class_to_id:
|
|
190
|
+
entity_class_to_id[ecls] = len(entity_class_to_id)
|
|
191
|
+
label_to_entity_class_id[label_key] = entity_class_to_id[ecls]
|
|
192
|
+
|
|
193
|
+
log(f"Pre-computed {len(label_to_target):,} target vectors, "
|
|
194
|
+
f"{len(sig_to_class_id):,} unique signature classes, "
|
|
195
|
+
f"{len(entity_class_to_id):,} entity classes")
|
|
196
|
+
|
|
197
|
+
# Contrastive grouping: determines P×K batching and contrastive positives
|
|
198
|
+
if bc_contrastive_target == "entity_class":
|
|
199
|
+
label_to_contrastive_id = label_to_entity_class_id
|
|
200
|
+
log(f"Contrastive target: entity_class ({len(entity_class_to_id)} classes)")
|
|
201
|
+
else:
|
|
202
|
+
label_to_contrastive_id = label_to_class_id
|
|
203
|
+
log(f"Contrastive target: signature ({len(sig_to_class_id)} classes)")
|
|
204
|
+
|
|
205
|
+
# ── Stratified train/val split ─────────────────────────────────
|
|
206
|
+
# Sample val from classes with enough examples (>=10 labels),
|
|
207
|
+
# taking 5% per class. Small classes go entirely to train.
|
|
208
|
+
class_to_label_keys = defaultdict(list)
|
|
209
|
+
for label_key in label_to_entities:
|
|
210
|
+
class_to_label_keys[label_to_contrastive_id[label_key]].append(label_key)
|
|
211
|
+
|
|
212
|
+
val_labels = set()
|
|
213
|
+
for class_id, class_label_keys in class_to_label_keys.items():
|
|
214
|
+
if len(class_label_keys) >= 10:
|
|
215
|
+
random.shuffle(class_label_keys)
|
|
216
|
+
n_val = max(1, int(len(class_label_keys) * 0.05))
|
|
217
|
+
val_labels.update(class_label_keys[:n_val])
|
|
218
|
+
|
|
219
|
+
train_label_to_entities = defaultdict(list)
|
|
220
|
+
val_label_to_entities = defaultdict(list)
|
|
221
|
+
for label_key, entities in label_to_entities.items():
|
|
222
|
+
if label_key in val_labels:
|
|
223
|
+
val_label_to_entities[label_key] = entities
|
|
224
|
+
else:
|
|
225
|
+
train_label_to_entities[label_key] = entities
|
|
226
|
+
|
|
227
|
+
n_val_classes = len({label_to_contrastive_id[lk] for lk in val_label_to_entities})
|
|
228
|
+
log(f"Behavior cluster: {len(train_label_to_entities):,} train / "
|
|
229
|
+
f"{len(val_label_to_entities):,} val unique labels "
|
|
230
|
+
f"(val covers {n_val_classes} classes)")
|
|
231
|
+
|
|
232
|
+
# Log class size distribution
|
|
233
|
+
train_class_sizes = defaultdict(int)
|
|
234
|
+
for lk in train_label_to_entities:
|
|
235
|
+
train_class_sizes[label_to_class_id[lk]] += 1
|
|
236
|
+
sorted_sizes = sorted(train_class_sizes.values(), reverse=True)
|
|
237
|
+
n_classes = len(sorted_sizes)
|
|
238
|
+
effective_total = sum(
|
|
239
|
+
max(bc_min_per_class, min(s, bc_max_per_class)) if bc_max_per_class > 0
|
|
240
|
+
else max(bc_min_per_class, s)
|
|
241
|
+
for s in sorted_sizes
|
|
242
|
+
)
|
|
243
|
+
log(f" Class sizes: {n_classes} classes, max={sorted_sizes[0]:,}, "
|
|
244
|
+
f"median={sorted_sizes[n_classes//2]:,}, min={sorted_sizes[-1]:,}")
|
|
245
|
+
log(f" Rebalancing: floor={bc_min_per_class}, cap={bc_max_per_class} "
|
|
246
|
+
f"→ {effective_total:,} entities/epoch (was {sum(sorted_sizes):,})")
|
|
247
|
+
log(f" P×K batching: K={bc_samples_per_class} samples/class, "
|
|
248
|
+
f"P={batch_size // bc_samples_per_class} classes/batch "
|
|
249
|
+
f"(grouped by {bc_contrastive_target})")
|
|
250
|
+
|
|
251
|
+
# ── Build model ────────────────────────────────────────────────
|
|
252
|
+
enc_config = get_behavior_encoder_config(tokenizer.vocab_size, model_size, max_seq_len)
|
|
253
|
+
n_entity_classes = len(entity_class_to_id)
|
|
254
|
+
model = ProvenanceBehaviorModel(
|
|
255
|
+
enc_config, num_labels=vocab.size, proj_dim=bc_proj_dim,
|
|
256
|
+
bce_mode=bc_bce_mode, num_classes=n_entity_classes,
|
|
257
|
+
).to(device)
|
|
258
|
+
bce_mode_desc = (f"{n_entity_classes} entity classes (CE)"
|
|
259
|
+
if bc_bce_mode == "class"
|
|
260
|
+
else f"{vocab.size} behavior labels (BCE)")
|
|
261
|
+
log(f"Model: BehaviorCluster-{model_size} (T5 encoder H={enc_config.d_model}, "
|
|
262
|
+
f"{bce_mode_desc}, proj_dim={bc_proj_dim})"
|
|
263
|
+
+ (", entity type stripped" if bc_strip_entity_type else ""))
|
|
264
|
+
log(f" Parameters: {sum(p.numel() for p in model.parameters()):,}")
|
|
265
|
+
|
|
266
|
+
# ── Optimizer & scheduler ──────────────────────────────────────
|
|
267
|
+
opt = AdamW(model.parameters(), lr=lr, betas=(0.9, 0.95), eps=1e-8, weight_decay=0.1)
|
|
268
|
+
scheduler = WarmupCosineScheduler(opt, warmup_tokens, total_tokens)
|
|
269
|
+
|
|
270
|
+
# ── Precompute validation batches (P×K grouped) ────────────────
|
|
271
|
+
val_batches_fixed = []
|
|
272
|
+
K = bc_samples_per_class
|
|
273
|
+
P = batch_size // K
|
|
274
|
+
if val_label_to_entities:
|
|
275
|
+
val_items = []
|
|
276
|
+
for label_key, entities in val_label_to_entities.items():
|
|
277
|
+
val_items.append((label_key, entities[0], label_to_contrastive_id[label_key]))
|
|
278
|
+
|
|
279
|
+
# Group by class for P×K batching
|
|
280
|
+
val_class_pools = defaultdict(list)
|
|
281
|
+
for item in val_items:
|
|
282
|
+
val_class_pools[item[2]].append(item)
|
|
283
|
+
|
|
284
|
+
val_ordered = []
|
|
285
|
+
val_class_ids_list = list(val_class_pools.keys())
|
|
286
|
+
random.shuffle(val_class_ids_list)
|
|
287
|
+
batch_buf = []
|
|
288
|
+
for cid in val_class_ids_list:
|
|
289
|
+
pool = val_class_pools[cid]
|
|
290
|
+
# Pad with duplicates to reach K so every sample has positives
|
|
291
|
+
padded = list(pool)
|
|
292
|
+
while len(padded) < K:
|
|
293
|
+
padded.append(random.choice(pool))
|
|
294
|
+
batch_buf.extend(padded[:K])
|
|
295
|
+
if len(batch_buf) >= batch_size:
|
|
296
|
+
val_ordered.extend(batch_buf[:batch_size])
|
|
297
|
+
batch_buf = batch_buf[batch_size:]
|
|
298
|
+
if batch_buf:
|
|
299
|
+
val_ordered.extend(batch_buf)
|
|
300
|
+
|
|
301
|
+
for vb_start in range(0, len(val_ordered), batch_size):
|
|
302
|
+
vb = val_ordered[vb_start:vb_start + batch_size]
|
|
303
|
+
vB = len(vb)
|
|
304
|
+
if vB == 0:
|
|
305
|
+
continue
|
|
306
|
+
|
|
307
|
+
v_enc_ids = [item[1][2] for item in vb]
|
|
308
|
+
v_input_ids, v_attn_mask = pad_token_id_lists(v_enc_ids, tokenizer.pad_id, tokenizer.max_seq_len)
|
|
309
|
+
|
|
310
|
+
v_targets = torch.stack([label_to_target[item[0]] for item in vb])
|
|
311
|
+
v_class_ids = torch.tensor([item[2] for item in vb], dtype=torch.long)
|
|
312
|
+
v_entity_class_ids = torch.tensor(
|
|
313
|
+
[label_to_entity_class_id[item[0]] for item in vb], dtype=torch.long,
|
|
314
|
+
)
|
|
315
|
+
|
|
316
|
+
val_batches_fixed.append((v_input_ids, v_attn_mask, v_targets, v_class_ids, v_entity_class_ids))
|
|
317
|
+
log(f"Precomputed {len(val_batches_fixed)} fixed val batches (P×K, K={K})")
|
|
318
|
+
|
|
319
|
+
# ── Training loop ──────────────────────────────────────────────
|
|
320
|
+
processed_tokens = 0
|
|
321
|
+
updates = 0
|
|
322
|
+
epoch = 0
|
|
323
|
+
best_val_loss = float("inf")
|
|
324
|
+
best_knn_acc = 0.0
|
|
325
|
+
|
|
326
|
+
log_path = os.path.join(out_dir, f"behavior_cluster_log_{model_size}.txt")
|
|
327
|
+
with open(log_path, "w") as f:
|
|
328
|
+
f.write("update,tokens,total_loss,bce_loss,contrastive_loss,lr,time\n")
|
|
329
|
+
|
|
330
|
+
while processed_tokens < total_tokens:
|
|
331
|
+
epoch += 1
|
|
332
|
+
epoch_st = time.time()
|
|
333
|
+
epoch_total_loss = 0.0
|
|
334
|
+
epoch_bce_loss = 0.0
|
|
335
|
+
epoch_con_loss = 0.0
|
|
336
|
+
epoch_batches = 0
|
|
337
|
+
|
|
338
|
+
# Group labels by signature class, apply floor/cap rebalancing
|
|
339
|
+
class_to_labels = defaultdict(list)
|
|
340
|
+
for label_key in train_label_to_entities:
|
|
341
|
+
class_to_labels[label_to_contrastive_id[label_key]].append(label_key)
|
|
342
|
+
|
|
343
|
+
epoch_entities_by_class = defaultdict(list)
|
|
344
|
+
for class_id, class_label_keys in class_to_labels.items():
|
|
345
|
+
n_class = len(class_label_keys)
|
|
346
|
+
# Cap per-class to avoid dominant classes flooding training
|
|
347
|
+
if bc_max_per_class > 0 and n_class > bc_max_per_class:
|
|
348
|
+
offset = (epoch - 1) * bc_max_per_class % n_class
|
|
349
|
+
indices = [(offset + i) % n_class for i in range(bc_max_per_class)]
|
|
350
|
+
class_label_keys = [class_label_keys[i] for i in indices]
|
|
351
|
+
# Floor per-class: oversample small classes by repeating labels
|
|
352
|
+
elif bc_min_per_class > 0 and n_class < bc_min_per_class:
|
|
353
|
+
repeats = (bc_min_per_class + n_class - 1) // n_class
|
|
354
|
+
class_label_keys = (class_label_keys * repeats)[:bc_min_per_class]
|
|
355
|
+
for label_key in class_label_keys:
|
|
356
|
+
entities = train_label_to_entities[label_key]
|
|
357
|
+
pick = entities[(epoch - 1) % len(entities)]
|
|
358
|
+
epoch_entities_by_class[class_id].append((label_key, pick, class_id))
|
|
359
|
+
|
|
360
|
+
# ── P×K batch construction ────────────────────────────────
|
|
361
|
+
# Each batch contains P classes × K samples per class,
|
|
362
|
+
# guaranteeing every entity has K-1 positives for contrastive loss.
|
|
363
|
+
for items in epoch_entities_by_class.values():
|
|
364
|
+
random.shuffle(items)
|
|
365
|
+
|
|
366
|
+
epoch_batches_list = build_pk_batches(epoch_entities_by_class, P, K)
|
|
367
|
+
|
|
368
|
+
for batch_items in epoch_batches_list:
|
|
369
|
+
B = len(batch_items)
|
|
370
|
+
if B == 0:
|
|
371
|
+
continue
|
|
372
|
+
|
|
373
|
+
# ── Pad encoder inputs ─────────────────────────────────
|
|
374
|
+
enc_ids_list = [item[1][2] for item in batch_items]
|
|
375
|
+
input_ids, attention_mask = pad_token_id_lists(enc_ids_list, tokenizer.pad_id, tokenizer.max_seq_len)
|
|
376
|
+
|
|
377
|
+
# ── Targets ────────────────────────────────────────────
|
|
378
|
+
target_vecs = torch.stack([label_to_target[item[0]] for item in batch_items])
|
|
379
|
+
class_ids = torch.tensor([item[2] for item in batch_items], dtype=torch.long)
|
|
380
|
+
entity_class_ids = torch.tensor(
|
|
381
|
+
[label_to_entity_class_id[item[0]] for item in batch_items], dtype=torch.long,
|
|
382
|
+
)
|
|
383
|
+
|
|
384
|
+
# ── Forward ────────────────────────────────────────────
|
|
385
|
+
model.train()
|
|
386
|
+
out = model.modified_fwd(input_ids.to(device), attention_mask.to(device))
|
|
387
|
+
|
|
388
|
+
total_loss, bce_loss_val, con_loss_val = behavior_combined_loss(
|
|
389
|
+
out.logits, target_vecs.to(device),
|
|
390
|
+
out.projection, class_ids.to(device),
|
|
391
|
+
bce_weight=bc_bce_weight,
|
|
392
|
+
contrastive_weight=bc_contrastive_weight,
|
|
393
|
+
temperature=bc_temperature,
|
|
394
|
+
bce_mode=bc_bce_mode,
|
|
395
|
+
entity_class_labels=entity_class_ids.to(device),
|
|
396
|
+
contrastive_target=bc_contrastive_target,
|
|
397
|
+
)
|
|
398
|
+
|
|
399
|
+
total_loss.backward()
|
|
400
|
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 5.0)
|
|
401
|
+
opt.step()
|
|
402
|
+
opt.zero_grad()
|
|
403
|
+
|
|
404
|
+
# ── Tracking ───────────────────────────────────────────
|
|
405
|
+
n_tokens = int(attention_mask.sum().item())
|
|
406
|
+
if n_tokens == 0:
|
|
407
|
+
continue
|
|
408
|
+
|
|
409
|
+
processed_tokens += n_tokens
|
|
410
|
+
scheduler.last_epoch = processed_tokens
|
|
411
|
+
scheduler.step()
|
|
412
|
+
updates += 1
|
|
413
|
+
|
|
414
|
+
tl = total_loss.item()
|
|
415
|
+
bl = bce_loss_val.item()
|
|
416
|
+
cl = con_loss_val.item()
|
|
417
|
+
epoch_total_loss += tl
|
|
418
|
+
epoch_bce_loss += bl
|
|
419
|
+
epoch_con_loss += cl
|
|
420
|
+
epoch_batches += 1
|
|
421
|
+
current_lr = scheduler.get_last_lr()[0]
|
|
422
|
+
|
|
423
|
+
if updates % 100 == 0:
|
|
424
|
+
elapsed = time.time() - epoch_st
|
|
425
|
+
log(
|
|
426
|
+
f"[{updates}|e{epoch}] loss={tl:.4f} (bce={bl:.4f} con={cl:.4f}) "
|
|
427
|
+
f"lr={current_lr:.2e} tokens={processed_tokens:.2e} ({elapsed:.1f}s)"
|
|
428
|
+
)
|
|
429
|
+
with open(log_path, "a") as f:
|
|
430
|
+
f.write(f"{updates},{processed_tokens},{tl:.6f},"
|
|
431
|
+
f"{bl:.6f},{cl:.6f},{current_lr:.2e},{elapsed:.1f}\n")
|
|
432
|
+
|
|
433
|
+
if processed_tokens >= total_tokens:
|
|
434
|
+
break
|
|
435
|
+
|
|
436
|
+
if processed_tokens >= total_tokens:
|
|
437
|
+
break
|
|
438
|
+
|
|
439
|
+
# Epoch-level logging
|
|
440
|
+
if epoch_batches > 0:
|
|
441
|
+
avg_tl = epoch_total_loss / epoch_batches
|
|
442
|
+
avg_bl = epoch_bce_loss / epoch_batches
|
|
443
|
+
avg_cl = epoch_con_loss / epoch_batches
|
|
444
|
+
elapsed = time.time() - epoch_st
|
|
445
|
+
log(f"Epoch {epoch} done | loss={avg_tl:.4f} (bce={avg_bl:.4f} con={avg_cl:.4f}) "
|
|
446
|
+
f"batches={epoch_batches} ({elapsed:.1f}s)")
|
|
447
|
+
|
|
448
|
+
# ── Validation ─────────────────────────────────────────────
|
|
449
|
+
epoch_metrics = {"pretrain/epoch": epoch, "pretrain/tokens": processed_tokens}
|
|
450
|
+
|
|
451
|
+
if val_batches_fixed:
|
|
452
|
+
model.eval()
|
|
453
|
+
val_losses = []
|
|
454
|
+
val_bce_losses = []
|
|
455
|
+
val_con_losses = []
|
|
456
|
+
|
|
457
|
+
for (v_input_ids, v_attn_mask, v_targets, v_class_ids, v_ecids) in val_batches_fixed:
|
|
458
|
+
with torch.no_grad():
|
|
459
|
+
v_out = model.modified_fwd(v_input_ids.to(device), v_attn_mask.to(device))
|
|
460
|
+
v_total, v_bce, v_con = behavior_combined_loss(
|
|
461
|
+
v_out.logits, v_targets.to(device),
|
|
462
|
+
v_out.projection, v_class_ids.to(device),
|
|
463
|
+
bce_weight=bc_bce_weight,
|
|
464
|
+
contrastive_weight=bc_contrastive_weight,
|
|
465
|
+
temperature=bc_temperature,
|
|
466
|
+
bce_mode=bc_bce_mode,
|
|
467
|
+
entity_class_labels=v_ecids.to(device),
|
|
468
|
+
contrastive_target=bc_contrastive_target,
|
|
469
|
+
)
|
|
470
|
+
val_losses.append(v_total.item())
|
|
471
|
+
val_bce_losses.append(v_bce.item())
|
|
472
|
+
val_con_losses.append(v_con.item())
|
|
473
|
+
|
|
474
|
+
avg_val = sum(val_losses) / len(val_losses)
|
|
475
|
+
avg_val_bce = sum(val_bce_losses) / len(val_bce_losses)
|
|
476
|
+
avg_val_con = sum(val_con_losses) / len(val_con_losses)
|
|
477
|
+
log(f"Epoch {epoch} val_loss={avg_val:.4f} (bce={avg_val_bce:.4f} con={avg_val_con:.4f})")
|
|
478
|
+
epoch_metrics["pretrain/val_loss"] = avg_val
|
|
479
|
+
epoch_metrics["pretrain/val_bce_loss"] = avg_val_bce
|
|
480
|
+
epoch_metrics["pretrain/val_contrastive_loss"] = avg_val_con
|
|
481
|
+
|
|
482
|
+
# ── KNN eval ───────────────────────────────────────────────
|
|
483
|
+
knn_results = _eval_knn_on_eval_set(model, tokenizer, device, "behavior_cluster", batch_size)
|
|
484
|
+
if knn_results:
|
|
485
|
+
knn_acc = knn_results['knn_accuracy_k5']
|
|
486
|
+
epoch_metrics["pretrain/knn_accuracy_k5"] = knn_acc
|
|
487
|
+
for cl, acc in knn_results['knn_accuracy_k5_per_cluster'].items():
|
|
488
|
+
epoch_metrics[f"pretrain/knn_k5/{cl}"] = acc
|
|
489
|
+
epoch_metrics["pretrain/ari"] = knn_results['ari']
|
|
490
|
+
epoch_metrics["pretrain/nmi"] = knn_results['nmi']
|
|
491
|
+
epoch_metrics["pretrain/silhouette"] = knn_results['silhouette']
|
|
492
|
+
epoch_metrics["pretrain/mAP"] = knn_results['mAP']
|
|
493
|
+
if knn_acc > best_knn_acc:
|
|
494
|
+
best_knn_acc = knn_acc
|
|
495
|
+
torch.save(model.state_dict(), os.path.join(out_dir, f"pretrain_{model_size}_best.pt"))
|
|
496
|
+
log(f"Epoch {epoch} knn_accuracy_k5={knn_acc:.4f} "
|
|
497
|
+
f"ARI={knn_results['ari']:.4f} NMI={knn_results['nmi']:.4f} "
|
|
498
|
+
f"silhouette={knn_results['silhouette']:.4f} mAP={knn_results['mAP']:.4f} "
|
|
499
|
+
f"*** new best ***")
|
|
500
|
+
else:
|
|
501
|
+
log(f"Epoch {epoch} knn_accuracy_k5={knn_acc:.4f} "
|
|
502
|
+
f"ARI={knn_results['ari']:.4f} NMI={knn_results['nmi']:.4f} "
|
|
503
|
+
f"silhouette={knn_results['silhouette']:.4f} mAP={knn_results['mAP']:.4f}")
|
|
504
|
+
epoch_metrics["pretrain/best_knn_acc"] = best_knn_acc
|
|
505
|
+
|
|
506
|
+
# Always save latest model
|
|
507
|
+
torch.save(model.state_dict(), os.path.join(out_dir, f"pretrain_{model_size}.pt"))
|
|
508
|
+
wandb.log(epoch_metrics)
|
|
509
|
+
|
|
510
|
+
# Final save
|
|
511
|
+
torch.save(model.state_dict(), os.path.join(out_dir, f"pretrain_{model_size}.pt"))
|
|
512
|
+
tokenizer.save(os.path.join(out_dir, "tokenizer.pt"))
|
|
513
|
+
log(f"Behavior cluster pretraining complete. {processed_tokens:,} tokens in {epoch} epochs.")
|