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,1659 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Improved provenance graph tokenizer: domain-specific normalization + BPE.
|
|
3
|
+
|
|
4
|
+
Key improvements over a plain whitespace tokenizer:
|
|
5
|
+
1. '/' is embedded in path component tokens: /usr/lib -> [ROOT][/USR][/LIB].
|
|
6
|
+
For unknown dirs the '/' is prepended to the first BPE word (/traceback ...),
|
|
7
|
+
so BPE fragments of one component never look like a new component.
|
|
8
|
+
2. Intra-component separators emitted as distinct tokens: x86_64-linux -> x86[SEP_UNDERSCORE]64[SEP_DASH]linux
|
|
9
|
+
3. BPE subword encoding - handles rare words by decomposing into known subwords
|
|
10
|
+
4. Entropy-based random string detection - hashes, UUIDs, random names -> canonical tokens
|
|
11
|
+
5. Semantic port categories - not one token per port number
|
|
12
|
+
6. No [DOT] tokens in IPs - octets alone carry the information
|
|
13
|
+
7. Flags preserve their content: -sh -> [FLAG] sh, --no-verify -> [FLAG] no[SEP_DASH]verify
|
|
14
|
+
8. Versioned shared objects: libfoo.so.1.2 -> libfoo [EXT_so] 1 2
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import os
|
|
18
|
+
import re
|
|
19
|
+
from collections import Counter
|
|
20
|
+
from typing import Dict, List, Optional, Set, Tuple
|
|
21
|
+
|
|
22
|
+
import torch
|
|
23
|
+
|
|
24
|
+
from pidsmaker.utils.dataset_utils import get_rel2id
|
|
25
|
+
from pidsmaker.utils.utils import log
|
|
26
|
+
from .canonical_tokens import (
|
|
27
|
+
ALL_CATEGORY_TOKENS,
|
|
28
|
+
match_file_category,
|
|
29
|
+
match_proc_category,
|
|
30
|
+
)
|
|
31
|
+
# Placeholder tokens and patterns of the configurable substitutions
|
|
32
|
+
from pidsmaker.tokenization.substitution import ( # noqa: F401 (re-exported)
|
|
33
|
+
ENV_VAR,
|
|
34
|
+
GUID,
|
|
35
|
+
HASH,
|
|
36
|
+
LOCALHOST_IP,
|
|
37
|
+
MAX_KEPT_NUMBER,
|
|
38
|
+
NUM,
|
|
39
|
+
PORT_EPH,
|
|
40
|
+
PORT_LOW,
|
|
41
|
+
PORT_REG,
|
|
42
|
+
PRIVATE_IP,
|
|
43
|
+
PUBLIC_IP,
|
|
44
|
+
RANDOM,
|
|
45
|
+
RE_ENV,
|
|
46
|
+
RE_GUID,
|
|
47
|
+
RE_GUID_INNER,
|
|
48
|
+
RE_HASH,
|
|
49
|
+
RE_IP,
|
|
50
|
+
RE_IPV6,
|
|
51
|
+
RE_SID,
|
|
52
|
+
RE_TIMESTAMP,
|
|
53
|
+
RE_VERSION,
|
|
54
|
+
SUBSTITUTION_METHODS,
|
|
55
|
+
TIMESTAMP,
|
|
56
|
+
VER,
|
|
57
|
+
WELL_KNOWN_PORTS,
|
|
58
|
+
Substitutor,
|
|
59
|
+
classify_ip,
|
|
60
|
+
classify_ipv6,
|
|
61
|
+
classify_port,
|
|
62
|
+
get_substitutions,
|
|
63
|
+
is_random_string,
|
|
64
|
+
parse_substitutions,
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
# ── Label sanitization ───────────────────────────────────────────────────────
|
|
69
|
+
# Keep only printable ASCII (space through tilde). Provenance labels are file
|
|
70
|
+
# paths, command lines, and IP addresses — all ASCII. Everything else is noise:
|
|
71
|
+
# control chars, Latin-1 supplement, obscure Unicode punctuation, zero-width
|
|
72
|
+
# chars, CJK descriptors, BOM, replacement chars, etc.
|
|
73
|
+
_BINARY_GARBAGE_RE = re.compile(r"[^\x20-\x7e]+")
|
|
74
|
+
|
|
75
|
+
# ── Special tokens ───────────────────────────────────────────────────────────
|
|
76
|
+
|
|
77
|
+
PAD = "[PAD]"
|
|
78
|
+
MASK = "[MASK]"
|
|
79
|
+
CLS = "[CLS]"
|
|
80
|
+
SEP = "[SEP]"
|
|
81
|
+
UNK = "[UNK]"
|
|
82
|
+
FORWARD = "[FORWARD]"
|
|
83
|
+
BACKWARD = "[BACKWARD]"
|
|
84
|
+
FORWARD_NEIGH = "[FORWARD_NEIGH]"
|
|
85
|
+
BACKWARD_NEIGH = "[BACKWARD_NEIGH]"
|
|
86
|
+
SPECIAL_TOKENS = [PAD, MASK, CLS, SEP, UNK, FORWARD, BACKWARD, FORWARD_NEIGH, BACKWARD_NEIGH]
|
|
87
|
+
|
|
88
|
+
NODE_TYPE_TOKENS = {
|
|
89
|
+
"subject": "[PROC]",
|
|
90
|
+
"file": "[FILE]",
|
|
91
|
+
"netflow": "[SOCK]",
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
# ── Provenance graph schema (DARPA TC) ───────────────────────────────────────
|
|
95
|
+
# Empirically derived from 2.7M walks across CADETS E3/E5, THEIA E3/E5, TRACE E3.
|
|
96
|
+
|
|
97
|
+
ENTITY_TYPES = {"[PROC]", "[FILE]", "[SOCK]"}
|
|
98
|
+
|
|
99
|
+
EVENT_TYPES = {
|
|
100
|
+
"EVENT_CLONE",
|
|
101
|
+
"EVENT_CONNECT",
|
|
102
|
+
"EVENT_EXECUTE",
|
|
103
|
+
"EVENT_OPEN",
|
|
104
|
+
"EVENT_READ",
|
|
105
|
+
"EVENT_RECVFROM",
|
|
106
|
+
"EVENT_RECVMSG",
|
|
107
|
+
"EVENT_SENDMSG",
|
|
108
|
+
"EVENT_SENDTO",
|
|
109
|
+
"EVENT_WRITE",
|
|
110
|
+
# Windows registry edge types (consistent vocabulary)
|
|
111
|
+
"REG_READ",
|
|
112
|
+
"REG_WRITE",
|
|
113
|
+
"REG_CREATEKEY",
|
|
114
|
+
"REG_DELETEKEY",
|
|
115
|
+
"REG_DELETEVALUE",
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
# (src_entity_token, event_name, dst_entity_token)
|
|
119
|
+
VALID_TRIPLETS = {
|
|
120
|
+
("[FILE]", "EVENT_EXECUTE", "[PROC]"),
|
|
121
|
+
("[FILE]", "EVENT_OPEN", "[PROC]"),
|
|
122
|
+
("[FILE]", "EVENT_READ", "[PROC]"),
|
|
123
|
+
("[FILE]", "EVENT_RECVFROM","[PROC]"),
|
|
124
|
+
("[FILE]", "EVENT_RECVMSG", "[PROC]"),
|
|
125
|
+
("[PROC]", "EVENT_CLONE", "[PROC]"),
|
|
126
|
+
("[PROC]", "EVENT_CONNECT", "[FILE]"),
|
|
127
|
+
("[PROC]", "EVENT_CONNECT", "[SOCK]"),
|
|
128
|
+
("[PROC]", "EVENT_EXECUTE", "[PROC]"),
|
|
129
|
+
("[PROC]", "EVENT_SENDMSG", "[FILE]"),
|
|
130
|
+
("[PROC]", "EVENT_SENDMSG", "[SOCK]"),
|
|
131
|
+
("[PROC]", "EVENT_SENDTO", "[FILE]"),
|
|
132
|
+
("[PROC]", "EVENT_SENDTO", "[SOCK]"),
|
|
133
|
+
("[PROC]", "EVENT_WRITE", "[FILE]"),
|
|
134
|
+
("[PROC]", "EVENT_WRITE", "[SOCK]"),
|
|
135
|
+
("[SOCK]", "EVENT_READ", "[PROC]"),
|
|
136
|
+
("[SOCK]", "EVENT_RECVFROM","[PROC]"),
|
|
137
|
+
("[SOCK]", "EVENT_RECVMSG", "[PROC]"),
|
|
138
|
+
# Windows registry triplets (registry paths are [FILE] nodes)
|
|
139
|
+
("[FILE]", "REG_READ", "[PROC]"),
|
|
140
|
+
("[PROC]", "REG_WRITE", "[FILE]"),
|
|
141
|
+
("[PROC]", "REG_CREATEKEY", "[FILE]"),
|
|
142
|
+
("[PROC]", "REG_DELETEKEY", "[FILE]"),
|
|
143
|
+
("[PROC]", "REG_DELETEVALUE","[FILE]"),
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
# ── Domain tokens ────────────────────────────────────────────────────────────
|
|
147
|
+
|
|
148
|
+
FLAG = "[FLAG]"
|
|
149
|
+
ROOT = "[ROOT]"
|
|
150
|
+
WIN_ROOT = "[WIN_ROOT]"
|
|
151
|
+
NO_CMD = "[NO_CMD]"
|
|
152
|
+
NO_PATH = "[NO_PATH]"
|
|
153
|
+
NO_IP = "[NO_IP]"
|
|
154
|
+
|
|
155
|
+
# Intra-component separator tokens
|
|
156
|
+
SEP_DASH = "[SEP_DASH]" # '-' separator within a name/component
|
|
157
|
+
SEP_UNDERSCORE = "[SEP_UNDERSCORE]" # '_' separator within a name/component
|
|
158
|
+
SEP_DOT = "[SEP_DOT]" # '.' separator within a name (non-extension context)
|
|
159
|
+
SEP_PLUS = "[SEP_PLUS]" # '+' separator within a name (e.g. lost+found)
|
|
160
|
+
SEP_AMP = "[SEP_AMP]" # '&' separator between URL query parameters
|
|
161
|
+
|
|
162
|
+
IPV6 = "[IPV6]"
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
# Well-known Unix directories
|
|
166
|
+
UNIX_DIRS = {
|
|
167
|
+
"etc": "[ETC]", "bin": "[BIN]", "sbin": "[SBIN]", "usr": "[USR]",
|
|
168
|
+
"var": "[VAR]", "tmp": "[TMP]", "dev": "[DEV]", "proc": "[PROC_DIR]",
|
|
169
|
+
"sys": "[SYS]", "lib": "[LIB]", "lib64": "[LIB]", "home": "[HOME]",
|
|
170
|
+
"root": "[ROOT_DIR]", "boot": "[BOOT]", "opt": "[OPT]", "mnt": "[MNT]",
|
|
171
|
+
"media": "[MEDIA]", "run": "[RUN]", "srv": "[SRV]",
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
# Well-known Windows directories
|
|
175
|
+
WIN_DIRS = {
|
|
176
|
+
"windows": "[WINDOWS]", "system32": "[SYS32]", "syswow64": "[SYSWOW64]",
|
|
177
|
+
"programdata": "[PROGDATA]", "users": "[USERS]", "appdata": "[APPDATA]",
|
|
178
|
+
"device": "[DEVICE]", "harddiskvolume1": "[DISK_VOL]",
|
|
179
|
+
"harddiskvolume2": "[DISK_VOL]", "harddiskvolume3": "[DISK_VOL]",
|
|
180
|
+
"program files": "[PROGFILES]", "program files (x86)": "[PROGFILES_X86]",
|
|
181
|
+
"winsxs": "[WINSXS]", "temp": "[TMP]", "microsoft": "[MSFT]",
|
|
182
|
+
"assembly": "[ASSEMBLY]", "microsoft.net": "[DOTNET]",
|
|
183
|
+
"local": "[LOCAL]", "roaming": "[ROAMING]",
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
# Windows registry hive tokens (registry paths treated as file nodes)
|
|
187
|
+
REG_HKLM = "[REG_HKLM]"
|
|
188
|
+
REG_HKCU = "[REG_HKCU]"
|
|
189
|
+
REG_HKCR = "[REG_HKCR]"
|
|
190
|
+
REG_SOFTWARE = "[REG_SOFTWARE]"
|
|
191
|
+
REG_SYSTEM = "[REG_SYSTEM]"
|
|
192
|
+
REG_SERVICES = "[REG_SERVICES]"
|
|
193
|
+
|
|
194
|
+
# Registry hive prefix mapping
|
|
195
|
+
REG_HIVE_MAP = {
|
|
196
|
+
"registry\\machine": REG_HKLM,
|
|
197
|
+
"hkey_local_machine": REG_HKLM,
|
|
198
|
+
"registry\\user": REG_HKCU,
|
|
199
|
+
"hkey_current_user": REG_HKCU,
|
|
200
|
+
"hkey_classes_root": REG_HKCR,
|
|
201
|
+
}
|
|
202
|
+
REG_SUBKEY_MAP = {
|
|
203
|
+
"software": REG_SOFTWARE,
|
|
204
|
+
"system": REG_SYSTEM,
|
|
205
|
+
"services": REG_SERVICES,
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
# Path-context variants: / is embedded in the token so BPE fragments of one
|
|
209
|
+
# component (e.g. /trac + eback) are unambiguous vs separate components.
|
|
210
|
+
# Used only for absolute paths; e.g. /usr/lib -> [/USR] [/LIB].
|
|
211
|
+
UNIX_DIRS_PATH = {k: f"[/{v[1:-1]}]" for k, v in UNIX_DIRS.items()}
|
|
212
|
+
WIN_DIRS_PATH = {k: f"[/{v[1:-1]}]" for k, v in WIN_DIRS.items()}
|
|
213
|
+
|
|
214
|
+
# Common file extensions that get dedicated tokens
|
|
215
|
+
KNOWN_EXTENSIONS = {
|
|
216
|
+
# Binaries / libraries
|
|
217
|
+
"exe", "dll", "so", "dylib", "bin", "msi", "jar", "war", "apk", "obj", "la",
|
|
218
|
+
# Source code
|
|
219
|
+
"c", "h", "cc", "hh", "cpp", "hpp", "py", "pyc", "js", "ts", "sh", "bash",
|
|
220
|
+
"bat", "cmd", "ps1", "rb", "pl", "cs", "mm", "asm", "qml", "ui",
|
|
221
|
+
# Build / project
|
|
222
|
+
"pro", "pri", "prl", "prf", "cmake", "gn", "gni", "gyp", "in",
|
|
223
|
+
# Config / data
|
|
224
|
+
"conf", "cfg", "ini", "yaml", "yml", "json", "xml", "toml", "dtd",
|
|
225
|
+
"idl", "proto", "mojom", "qdoc", "qrc", "qm", "qmlc",
|
|
226
|
+
# Documents / text
|
|
227
|
+
"log", "txt", "csv", "md", "html", "htm", "css", "svg",
|
|
228
|
+
# Database
|
|
229
|
+
"db", "sqlite", "sql",
|
|
230
|
+
# Archives
|
|
231
|
+
"zip", "tar", "gz", "bz2", "xz", "7z", "rar",
|
|
232
|
+
# Security
|
|
233
|
+
"pem", "key", "crt", "cert", "pub", "sha1",
|
|
234
|
+
# System / runtime
|
|
235
|
+
"sys", "ko", "o", "pid", "lock", "sock", "tmp", "cache", "pc",
|
|
236
|
+
# Media
|
|
237
|
+
"png", "jpg", "gif", "ico", "wav", "webp", "ttf",
|
|
238
|
+
# Misc
|
|
239
|
+
"dat", "data", "patch", "test", "tests", "ref", "out", "inc", "def",
|
|
240
|
+
"pset", "stat", "xtb", "scxml", "tmpl", "ucm", "ent", "frag", "vert",
|
|
241
|
+
"orth", "td", "xq", "d", "n", "new",
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
# ── Regex patterns ───────────────────────────────────────────────────────────
|
|
245
|
+
|
|
246
|
+
RE_FLAG = re.compile(r"^--?[a-zA-Z][a-zA-Z0-9-]*$")
|
|
247
|
+
RE_EXT = re.compile(
|
|
248
|
+
r"^(.+?)\.({})$".format(
|
|
249
|
+
"|".join(re.escape(e) for e in sorted(KNOWN_EXTENSIONS, key=len, reverse=True))
|
|
250
|
+
),
|
|
251
|
+
re.IGNORECASE,
|
|
252
|
+
)
|
|
253
|
+
RE_SEPARATORS = re.compile(r"[-_.]")
|
|
254
|
+
RE_SEPARATORS_CAPTURE = re.compile(r"([-_.+])")
|
|
255
|
+
RE_SO_VERSIONED = re.compile(r"^(.+)\.so(\.\d+)+$", re.IGNORECASE)
|
|
256
|
+
|
|
257
|
+
# Maps raw separator characters to their dedicated tokens
|
|
258
|
+
SEP_TOKEN_MAP = {"-": SEP_DASH, "_": SEP_UNDERSCORE, ".": SEP_DOT, "+": SEP_PLUS}
|
|
259
|
+
|
|
260
|
+
RE_QUERY_STRING = re.compile(r"^[^=&\s]+=.*&[^=&\s]+=.*$|^[^=&\s]*&[^=&\s]+=.*$")
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
# ── Tokenizer ────────────────────────────────────────────────────────────────
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
class ProvenanceTokenizerBPE:
|
|
267
|
+
"""Two-phase provenance graph tokenizer: domain normalization + BPE.
|
|
268
|
+
|
|
269
|
+
Phase 1 (domain-specific):
|
|
270
|
+
- Paths split into components without slash tokens
|
|
271
|
+
- Well-known directories -> semantic tokens
|
|
272
|
+
- Hashes, GUIDs, random strings -> canonical tokens
|
|
273
|
+
- Ports -> semantic categories
|
|
274
|
+
- IPs -> octets without dot tokens
|
|
275
|
+
|
|
276
|
+
Phase 2 (BPE):
|
|
277
|
+
- Remaining words decomposed into learned subwords
|
|
278
|
+
- Guarantees no OOV (falls back to character level)
|
|
279
|
+
|
|
280
|
+
Drop-in compatible with ProvenanceTokenizer.
|
|
281
|
+
"""
|
|
282
|
+
|
|
283
|
+
def __init__(self, cfg, max_seq_len: int = 512, bpe_vocab_size: int = 8000, mode: str = "domain_bpe",
|
|
284
|
+
normalize_netflow_ips: Optional[bool] = None, canonicalize_neighbors: bool = False,
|
|
285
|
+
strip_entity_type: bool = False, substitutions=None):
|
|
286
|
+
"""
|
|
287
|
+
Args:
|
|
288
|
+
substitutions: patterns replaced by placeholder tokens (see
|
|
289
|
+
pidsmaker.tokenization.substitution). Defaults to
|
|
290
|
+
`featurization.tokenization.bpe.substitutions`, or to all patterns if unset.
|
|
291
|
+
normalize_netflow_ips: if not None, enables or disables the `ip` substitution.
|
|
292
|
+
"""
|
|
293
|
+
self.cfg = cfg
|
|
294
|
+
self.max_seq_len = max_seq_len
|
|
295
|
+
self.bpe_vocab_size = bpe_vocab_size
|
|
296
|
+
self.mode = mode # "domain_bpe" or "bpe_only"
|
|
297
|
+
if substitutions is None:
|
|
298
|
+
substitutions = self._substitutions_from_cfg(cfg)
|
|
299
|
+
substitutions = set(parse_substitutions(substitutions) if isinstance(substitutions, str) else substitutions)
|
|
300
|
+
if normalize_netflow_ips is not None:
|
|
301
|
+
(substitutions.add if normalize_netflow_ips else substitutions.discard)("ip")
|
|
302
|
+
self._set_substitutions(substitutions)
|
|
303
|
+
self.canonicalize_neighbors = canonicalize_neighbors
|
|
304
|
+
self.strip_entity_type = strip_entity_type
|
|
305
|
+
self.expand_netflow_ips = False # When True, emit [CATEGORY] + raw IP tokens
|
|
306
|
+
self.mask_rate = 0.15
|
|
307
|
+
|
|
308
|
+
# Edge tokens from dataset config
|
|
309
|
+
rel2id = get_rel2id(cfg)
|
|
310
|
+
self.edge_tokens = {k: f"[EDGE_{k}]" for k in rel2id if isinstance(k, str)}
|
|
311
|
+
|
|
312
|
+
# BPE state
|
|
313
|
+
self.merges: List[Tuple[str, str]] = []
|
|
314
|
+
|
|
315
|
+
# Vocabulary
|
|
316
|
+
self.token2id: Dict[str, int] = {}
|
|
317
|
+
self.id2token: Dict[int, str] = {}
|
|
318
|
+
self.vocab_size: int = 0
|
|
319
|
+
|
|
320
|
+
# ── Substitutions ─────────────────────────────────────────────────────
|
|
321
|
+
|
|
322
|
+
@staticmethod
|
|
323
|
+
def _substitutions_from_cfg(cfg):
|
|
324
|
+
try:
|
|
325
|
+
return get_substitutions(cfg, "bpe")
|
|
326
|
+
except (AttributeError, ValueError):
|
|
327
|
+
return SUBSTITUTION_METHODS # all patterns, as before they were configurable
|
|
328
|
+
|
|
329
|
+
def _set_substitutions(self, substitutions):
|
|
330
|
+
self.substitutions = frozenset(substitutions)
|
|
331
|
+
self.normalize_netflow_ips = "ip" in self.substitutions
|
|
332
|
+
self.substitutor = Substitutor(self.substitutions) # used in bpe_only mode
|
|
333
|
+
|
|
334
|
+
def _sub(self, name: str) -> bool:
|
|
335
|
+
return name in self.substitutions
|
|
336
|
+
|
|
337
|
+
def _number(self, digits: str) -> str:
|
|
338
|
+
"""Large numbers become [NUM] when the `number` substitution is enabled."""
|
|
339
|
+
return NUM if self._sub("number") and int(digits) > MAX_KEPT_NUMBER else digits
|
|
340
|
+
|
|
341
|
+
# ── Properties ────────────────────────────────────────────────────────
|
|
342
|
+
|
|
343
|
+
@property
|
|
344
|
+
def pad_id(self) -> int:
|
|
345
|
+
return self.token2id[PAD]
|
|
346
|
+
|
|
347
|
+
@property
|
|
348
|
+
def mask_id(self) -> int:
|
|
349
|
+
return self.token2id[MASK]
|
|
350
|
+
|
|
351
|
+
@property
|
|
352
|
+
def cls_id(self) -> int:
|
|
353
|
+
return self.token2id[CLS]
|
|
354
|
+
|
|
355
|
+
@property
|
|
356
|
+
def sep_id(self) -> int:
|
|
357
|
+
return self.token2id[SEP]
|
|
358
|
+
|
|
359
|
+
# ── Phase 1: Domain-specific pre-tokenization ─────────────────────────
|
|
360
|
+
|
|
361
|
+
_is_random_string = staticmethod(is_random_string)
|
|
362
|
+
_classify_port = staticmethod(classify_port)
|
|
363
|
+
|
|
364
|
+
def _normalize_part(self, part: str) -> List[str]:
|
|
365
|
+
"""Normalize a sub-part from compound name or extension base split.
|
|
366
|
+
|
|
367
|
+
Handles hashes, random strings, numbers, and camelCase.
|
|
368
|
+
Unlike _pretokenize_segment, does NOT match directory names
|
|
369
|
+
(e.g. 'dev' stays as 'dev', not [DEV]).
|
|
370
|
+
"""
|
|
371
|
+
if not part:
|
|
372
|
+
return []
|
|
373
|
+
if self._sub("hash") and RE_HASH.match(part):
|
|
374
|
+
return [HASH]
|
|
375
|
+
if part.isdigit():
|
|
376
|
+
return [self._number(part)]
|
|
377
|
+
if self._sub("random") and self._is_random_string(part):
|
|
378
|
+
return [RANDOM]
|
|
379
|
+
if any(c.isupper() for c in part[1:]):
|
|
380
|
+
camel = re.split(r"(?<=[a-z])(?=[A-Z])", part)
|
|
381
|
+
if len(camel) > 1:
|
|
382
|
+
return [p.lower() for p in camel]
|
|
383
|
+
return [part.lower()]
|
|
384
|
+
|
|
385
|
+
def _split_with_sep_tokens(self, s: str) -> List[str]:
|
|
386
|
+
"""Split a string by separators (-, _, ., +) emitting separator tokens between parts.
|
|
387
|
+
|
|
388
|
+
Leading/trailing separators are dropped. Consecutive separators collapse to
|
|
389
|
+
the last separator type encountered before a non-empty part.
|
|
390
|
+
|
|
391
|
+
Examples:
|
|
392
|
+
"x86_64-linux-gnu" -> ["x86", SEP_UNDERSCORE, "64", SEP_DASH, "linux", SEP_DASH, "gnu"]
|
|
393
|
+
"traceback.cpython" -> ["traceback", SEP_DOT, "cpython"]
|
|
394
|
+
"__pycache__" -> ["pycache"] (leading/trailing underscores ignored)
|
|
395
|
+
"lost+found" -> ["lost", SEP_PLUS, "found"]
|
|
396
|
+
"""
|
|
397
|
+
raw = RE_SEPARATORS_CAPTURE.split(s)
|
|
398
|
+
result: List[str] = []
|
|
399
|
+
current_sep: Optional[str] = None
|
|
400
|
+
for piece in raw:
|
|
401
|
+
if piece in SEP_TOKEN_MAP:
|
|
402
|
+
current_sep = SEP_TOKEN_MAP[piece]
|
|
403
|
+
elif piece: # non-empty, non-separator content
|
|
404
|
+
if result and current_sep is not None:
|
|
405
|
+
result.append(current_sep)
|
|
406
|
+
result.extend(self._normalize_part(piece))
|
|
407
|
+
current_sep = None
|
|
408
|
+
# empty pieces from leading/trailing/consecutive separators: just skip
|
|
409
|
+
return result
|
|
410
|
+
|
|
411
|
+
def _pretokenize_query_string(self, qs: str) -> List[str]:
|
|
412
|
+
"""Normalize a URL query string into structured tokens.
|
|
413
|
+
|
|
414
|
+
Splits on '&' into individual key=value pairs. Keys are tokenized as
|
|
415
|
+
words; values are normalized (numbers -> [NUM], hashes -> [HASH],
|
|
416
|
+
random strings -> [RANDOM], semantic words -> BPE candidates).
|
|
417
|
+
Pairs are separated by [SEP_AMP].
|
|
418
|
+
|
|
419
|
+
Examples:
|
|
420
|
+
"detail=detail&id=5457" -> ["detail", "detail", SEP_AMP, "id", NUM]
|
|
421
|
+
"para1=leftnav&type=show" -> ["para1", "leftnav", SEP_AMP, "type", "show"]
|
|
422
|
+
"calendar&date=7" -> ["calendar", SEP_AMP, "date", "7"]
|
|
423
|
+
"action=view&hash=a3f9..." -> ["action", "view", SEP_AMP, "hash", HASH]
|
|
424
|
+
"""
|
|
425
|
+
tokens = []
|
|
426
|
+
pairs = qs.split("&")
|
|
427
|
+
for i, pair in enumerate(pairs):
|
|
428
|
+
if not pair:
|
|
429
|
+
continue
|
|
430
|
+
if i > 0:
|
|
431
|
+
tokens.append(SEP_AMP)
|
|
432
|
+
if "=" in pair:
|
|
433
|
+
k, _, v = pair.partition("=")
|
|
434
|
+
if k:
|
|
435
|
+
tokens.extend(self._split_with_sep_tokens(k) or [k.lower()])
|
|
436
|
+
if v:
|
|
437
|
+
if v.isdigit():
|
|
438
|
+
tokens.append(self._number(v))
|
|
439
|
+
elif self._sub("hash") and RE_HASH.match(v):
|
|
440
|
+
tokens.append(HASH)
|
|
441
|
+
elif self._sub("random") and self._is_random_string(v):
|
|
442
|
+
tokens.append(RANDOM)
|
|
443
|
+
else:
|
|
444
|
+
tokens.extend(self._split_with_sep_tokens(v) or [v.lower()])
|
|
445
|
+
else:
|
|
446
|
+
tokens.extend(self._split_with_sep_tokens(pair) or [pair.lower()])
|
|
447
|
+
return tokens
|
|
448
|
+
|
|
449
|
+
def _pretokenize_segment(self, seg: str) -> List[str]:
|
|
450
|
+
"""Pre-tokenize a single path component or word.
|
|
451
|
+
|
|
452
|
+
Returns a mix of domain tokens (e.g. [ETC], [HASH]) and raw words
|
|
453
|
+
that will later go through BPE.
|
|
454
|
+
"""
|
|
455
|
+
if not seg:
|
|
456
|
+
return []
|
|
457
|
+
|
|
458
|
+
lower = seg.lower()
|
|
459
|
+
|
|
460
|
+
# Well-known directories
|
|
461
|
+
if lower in UNIX_DIRS:
|
|
462
|
+
return [UNIX_DIRS[lower]]
|
|
463
|
+
if lower in WIN_DIRS:
|
|
464
|
+
return [WIN_DIRS[lower]]
|
|
465
|
+
|
|
466
|
+
# Hash (MD5/SHA1/SHA256)
|
|
467
|
+
if self._sub("hash") and RE_HASH.match(seg):
|
|
468
|
+
return [HASH]
|
|
469
|
+
|
|
470
|
+
# GUID / UUID (standalone)
|
|
471
|
+
if self._sub("guid") and RE_GUID.match(seg):
|
|
472
|
+
return [GUID]
|
|
473
|
+
|
|
474
|
+
# Embedded GUID (e.g. "Processid:{E10F6C3A-...}")
|
|
475
|
+
guid_search = RE_GUID_INNER.search(seg) if self._sub("guid") else None
|
|
476
|
+
if guid_search:
|
|
477
|
+
tokens = []
|
|
478
|
+
prefix = seg[: guid_search.start()].rstrip(":{")
|
|
479
|
+
if prefix:
|
|
480
|
+
tokens.extend(self._pretokenize_segment(prefix))
|
|
481
|
+
tokens.append(GUID)
|
|
482
|
+
suffix = seg[guid_search.end() :].lstrip("}")
|
|
483
|
+
if suffix:
|
|
484
|
+
tokens.extend(self._pretokenize_segment(suffix))
|
|
485
|
+
return tokens
|
|
486
|
+
|
|
487
|
+
# Windows SID
|
|
488
|
+
if self._sub("random") and RE_SID.match(seg):
|
|
489
|
+
return [RANDOM]
|
|
490
|
+
|
|
491
|
+
# Version string
|
|
492
|
+
if self._sub("version") and RE_VERSION.match(seg):
|
|
493
|
+
return [VER]
|
|
494
|
+
|
|
495
|
+
# Timestamp
|
|
496
|
+
if self._sub("timestamp") and RE_TIMESTAMP.match(seg):
|
|
497
|
+
return [TIMESTAMP]
|
|
498
|
+
|
|
499
|
+
# Environment variable
|
|
500
|
+
if self._sub("env_var") and RE_ENV.match(seg):
|
|
501
|
+
return [ENV_VAR]
|
|
502
|
+
|
|
503
|
+
# Pure number: keep small numbers (IP octets, exit codes), collapse large
|
|
504
|
+
if seg.isdigit():
|
|
505
|
+
return [self._number(seg)]
|
|
506
|
+
|
|
507
|
+
# File extension extraction (e.g. traceback.cpython-34.pyc -> base + [EXT_pyc])
|
|
508
|
+
# Must come before _is_random_string so that compound names like
|
|
509
|
+
# "build-a1b2c3d.o" are split into base + ext before entropy is measured.
|
|
510
|
+
ext_match = RE_EXT.match(seg) # match original case (regex is IGNORECASE)
|
|
511
|
+
if ext_match:
|
|
512
|
+
base, ext = ext_match.group(1), ext_match.group(2).lower()
|
|
513
|
+
tokens = self._split_with_sep_tokens(base)
|
|
514
|
+
tokens.append(f"[EXT_{ext}]")
|
|
515
|
+
return tokens
|
|
516
|
+
|
|
517
|
+
# Versioned shared object: libfoo.so.1.2 -> libfoo [EXT_so] 1 2
|
|
518
|
+
so_match = RE_SO_VERSIONED.match(seg)
|
|
519
|
+
if so_match:
|
|
520
|
+
base = so_match.group(1)
|
|
521
|
+
tokens = self._split_with_sep_tokens(base)
|
|
522
|
+
tokens.append("[EXT_so]")
|
|
523
|
+
remainder = seg[len(base) + 3:] # skip ".so"
|
|
524
|
+
for v in remainder.split("."):
|
|
525
|
+
if v.isdigit():
|
|
526
|
+
tokens.append(self._number(v))
|
|
527
|
+
return tokens
|
|
528
|
+
|
|
529
|
+
# URL query string (e.g. "detail=detail&id=5457", "calendar&date=7")
|
|
530
|
+
if "&" in seg and RE_QUERY_STRING.match(seg):
|
|
531
|
+
return self._pretokenize_query_string(seg)
|
|
532
|
+
|
|
533
|
+
# Compound name with separators (e.g. x86_64-linux-gnu, lost+found).
|
|
534
|
+
# Must come before _is_random_string: separators inflate the char-type
|
|
535
|
+
# transition rate, causing legitimate hash-bearing names like
|
|
536
|
+
# "gk-0f1fc345" to be wrongly flagged as random. Each sub-part is
|
|
537
|
+
# evaluated independently by _normalize_part which has its own check.
|
|
538
|
+
if RE_SEPARATORS_CAPTURE.search(seg):
|
|
539
|
+
result = self._split_with_sep_tokens(seg)
|
|
540
|
+
if result:
|
|
541
|
+
return result
|
|
542
|
+
|
|
543
|
+
# Random string (high entropy + mixed char types).
|
|
544
|
+
# Reached only by bare words with no separators or known extension —
|
|
545
|
+
# keeping it before camelCase prevents random strings like "pEja72mA"
|
|
546
|
+
# from being wrongly split on case boundaries.
|
|
547
|
+
if self._sub("random") and self._is_random_string(seg):
|
|
548
|
+
return [RANDOM]
|
|
549
|
+
|
|
550
|
+
# camelCase splitting (e.g. networkHistory -> network, history)
|
|
551
|
+
if any(c.isupper() for c in seg[1:]):
|
|
552
|
+
camel_parts = re.split(r"(?<=[a-z])(?=[A-Z])", seg)
|
|
553
|
+
if len(camel_parts) > 1:
|
|
554
|
+
return [p.lower() for p in camel_parts]
|
|
555
|
+
|
|
556
|
+
# Single word -> BPE candidate
|
|
557
|
+
return [lower]
|
|
558
|
+
|
|
559
|
+
def _pretokenize_path_component(self, seg: str) -> List[str]:
|
|
560
|
+
"""Tokenize one path component for an absolute path.
|
|
561
|
+
|
|
562
|
+
Well-known directories use a '/'-prefixed domain token ([/USR], [/LIB], …)
|
|
563
|
+
so each component is a single, unambiguous token. For all other segments
|
|
564
|
+
the '/' is prepended to the first raw BPE word so that even if BPE splits
|
|
565
|
+
the word later (e.g. /traceback -> /trac + eback), every split piece except
|
|
566
|
+
the first lacks a leading '/' and is recognisable as a continuation.
|
|
567
|
+
|
|
568
|
+
Domain tokens (HASH, GUID, VER, …) already carry enough identity and are
|
|
569
|
+
left without a '/' prefix.
|
|
570
|
+
"""
|
|
571
|
+
lower = seg.lower()
|
|
572
|
+
if lower in UNIX_DIRS_PATH:
|
|
573
|
+
return [UNIX_DIRS_PATH[lower]]
|
|
574
|
+
if lower in WIN_DIRS_PATH:
|
|
575
|
+
return [WIN_DIRS_PATH[lower]]
|
|
576
|
+
|
|
577
|
+
seg_toks = self._pretokenize_segment(seg)
|
|
578
|
+
if not seg_toks:
|
|
579
|
+
return seg_toks
|
|
580
|
+
|
|
581
|
+
first = seg_toks[0]
|
|
582
|
+
if first.startswith("[") and first.endswith("]"):
|
|
583
|
+
# Domain token (HASH, GUID, VER, EXT_*, …) – keep as-is
|
|
584
|
+
return seg_toks
|
|
585
|
+
return ["/" + first] + seg_toks[1:]
|
|
586
|
+
|
|
587
|
+
def _pretokenize_path(self, path_str: str) -> List[str]:
|
|
588
|
+
"""Pre-tokenize a path: root marker + slash-prefixed component tokens.
|
|
589
|
+
|
|
590
|
+
For absolute paths each component token embeds the leading '/':
|
|
591
|
+
/usr/lib/traceback.cpython-34.pyc
|
|
592
|
+
-> [ROOT] [/USR] [/LIB] /traceback [SEP_DOT] cpython [SEP_DASH] 34 [EXT_pyc]
|
|
593
|
+
|
|
594
|
+
BPE fragments of one component are distinguishable from new components
|
|
595
|
+
because only the first fragment starts with '/'. Relative paths fall back
|
|
596
|
+
to the same plain token representation as before.
|
|
597
|
+
"""
|
|
598
|
+
tokens = []
|
|
599
|
+
path = path_str.replace("\\", "/").strip().strip('"').strip("'")
|
|
600
|
+
|
|
601
|
+
# Windows device path prefix: \\?\C:\... or //?/C:/...
|
|
602
|
+
if re.match(r"^/+\?/+", path):
|
|
603
|
+
path = re.sub(r"^/+\?/+", "", path)
|
|
604
|
+
|
|
605
|
+
# Windows registry path detection (e.g. "registry/machine/software/...")
|
|
606
|
+
path_lower = path.lower()
|
|
607
|
+
for hive_prefix, hive_token in REG_HIVE_MAP.items():
|
|
608
|
+
hive_slash = hive_prefix.replace("\\", "/")
|
|
609
|
+
if path_lower.startswith(hive_slash):
|
|
610
|
+
tokens.append(hive_token)
|
|
611
|
+
path = path[len(hive_slash):].lstrip("/")
|
|
612
|
+
# Tokenize remaining registry subkeys as path components
|
|
613
|
+
for seg in path.split("/"):
|
|
614
|
+
if seg:
|
|
615
|
+
seg_lower = seg.lower()
|
|
616
|
+
if seg_lower in REG_SUBKEY_MAP:
|
|
617
|
+
tokens.append(REG_SUBKEY_MAP[seg_lower])
|
|
618
|
+
else:
|
|
619
|
+
tokens.extend(self._pretokenize_path_component(seg))
|
|
620
|
+
return tokens
|
|
621
|
+
|
|
622
|
+
is_absolute = False
|
|
623
|
+
if len(path) >= 2 and path[0].isalpha() and path[1] == ":":
|
|
624
|
+
tokens.append(WIN_ROOT)
|
|
625
|
+
path = path[2:].lstrip("/")
|
|
626
|
+
is_absolute = True
|
|
627
|
+
elif path.startswith("/"):
|
|
628
|
+
tokens.append(ROOT)
|
|
629
|
+
path = path.lstrip("/")
|
|
630
|
+
is_absolute = True
|
|
631
|
+
|
|
632
|
+
for seg in path.split("/"):
|
|
633
|
+
if seg:
|
|
634
|
+
if is_absolute:
|
|
635
|
+
tokens.extend(self._pretokenize_path_component(seg))
|
|
636
|
+
else:
|
|
637
|
+
tokens.extend(self._pretokenize_segment(seg))
|
|
638
|
+
|
|
639
|
+
return tokens
|
|
640
|
+
|
|
641
|
+
@staticmethod
|
|
642
|
+
def _pretokenize_ip(ip_str: str) -> List[str]:
|
|
643
|
+
"""Pre-tokenize an IP address: octets only, no dots."""
|
|
644
|
+
match = RE_IP.match(ip_str)
|
|
645
|
+
if match:
|
|
646
|
+
return [match.group(i) for i in range(1, 5)]
|
|
647
|
+
return [ip_str.lower()]
|
|
648
|
+
|
|
649
|
+
@staticmethod
|
|
650
|
+
def _pretokenize_ipv6(ip_str: str) -> List[str]:
|
|
651
|
+
"""Pre-tokenize an IPv6 address: [IPV6] prefix + hex groups."""
|
|
652
|
+
groups = [g for g in ip_str.split(":") if g]
|
|
653
|
+
return [IPV6] + [g.lower() for g in groups]
|
|
654
|
+
|
|
655
|
+
_classify_ip = staticmethod(classify_ip)
|
|
656
|
+
_classify_ipv6 = staticmethod(classify_ipv6)
|
|
657
|
+
|
|
658
|
+
@staticmethod
|
|
659
|
+
def _looks_like_path(s: str) -> bool:
|
|
660
|
+
return "/" in s or "\\" in s or (len(s) >= 2 and s[1] == ":")
|
|
661
|
+
|
|
662
|
+
def _tokenize_flag(self, flag_str: str) -> List[str]:
|
|
663
|
+
"""Tokenize a CLI flag, preserving its content after [FLAG].
|
|
664
|
+
|
|
665
|
+
Emits [FLAG] followed by the flag name/letters so the model retains
|
|
666
|
+
flag semantics rather than losing them in a single [FLAG] token.
|
|
667
|
+
|
|
668
|
+
Examples:
|
|
669
|
+
"-sh" -> [[FLAG], "sh"]
|
|
670
|
+
"-idrc" -> [[FLAG], "idrc"]
|
|
671
|
+
"--verbose" -> [[FLAG], "verbose"]
|
|
672
|
+
"--no-verify" -> [[FLAG], "no", SEP_DASH, "verify"]
|
|
673
|
+
"""
|
|
674
|
+
content = flag_str.lstrip("-")
|
|
675
|
+
tokens = [FLAG]
|
|
676
|
+
if content:
|
|
677
|
+
# Split long flags by '-', emitting SEP_DASH between parts.
|
|
678
|
+
# Use _normalize_part (not _pretokenize_segment) to avoid mapping
|
|
679
|
+
# flag words like "lib" to directory tokens like [LIB].
|
|
680
|
+
sub_parts = content.split("-")
|
|
681
|
+
for i, sp in enumerate(sub_parts):
|
|
682
|
+
if sp:
|
|
683
|
+
if i > 0:
|
|
684
|
+
tokens.append(SEP_DASH)
|
|
685
|
+
tokens.extend(self._normalize_part(sp))
|
|
686
|
+
return tokens
|
|
687
|
+
|
|
688
|
+
def _pretokenize_node_simple(self, _node_type: str, label_str: str) -> List[str]:
|
|
689
|
+
"""Minimal pre-tokenization for bpe_only mode: just lowercase and split on whitespace."""
|
|
690
|
+
parts = label_str.split()
|
|
691
|
+
if parts and parts[0] in ("subject", "file", "netflow"):
|
|
692
|
+
parts = parts[1:]
|
|
693
|
+
words = []
|
|
694
|
+
for p in parts:
|
|
695
|
+
if p and p != "None":
|
|
696
|
+
placeholder = self.substitutor.substitute_word(p, _node_type) if self.substitutor else None
|
|
697
|
+
words.append(placeholder or p.lower())
|
|
698
|
+
return words
|
|
699
|
+
|
|
700
|
+
def _pretokenize_node(self, node_type: str, label_str: str) -> List[str]:
|
|
701
|
+
"""Pre-tokenize a node label based on its type."""
|
|
702
|
+
parts = label_str.split()
|
|
703
|
+
|
|
704
|
+
# Strip type prefix if present (e.g. "subject", "file", "netflow")
|
|
705
|
+
if parts and parts[0] in ("subject", "file", "netflow"):
|
|
706
|
+
parts = parts[1:]
|
|
707
|
+
|
|
708
|
+
if not parts:
|
|
709
|
+
return []
|
|
710
|
+
|
|
711
|
+
# ── Netflow ──
|
|
712
|
+
if node_type == "netflow":
|
|
713
|
+
tokens = []
|
|
714
|
+
normalize_ips = self.normalize_netflow_ips
|
|
715
|
+
|
|
716
|
+
def _tokenize_ip(ip_str):
|
|
717
|
+
"""Tokenize an IP: category token if normalizing, octets otherwise.
|
|
718
|
+
If expand_netflow_ips is set, emit both category + octets."""
|
|
719
|
+
if normalize_ips:
|
|
720
|
+
cat = [self._classify_ip(ip_str)]
|
|
721
|
+
if self.expand_netflow_ips:
|
|
722
|
+
return cat + self._pretokenize_ip(ip_str)
|
|
723
|
+
return cat
|
|
724
|
+
return self._pretokenize_ip(ip_str)
|
|
725
|
+
|
|
726
|
+
def _tokenize_port(port_str):
|
|
727
|
+
"""Port category token, or the raw port without the `port` substitution."""
|
|
728
|
+
return self._classify_port(port_str) if self._sub("port") else port_str.lower()
|
|
729
|
+
|
|
730
|
+
for part in parts:
|
|
731
|
+
if "->" in part:
|
|
732
|
+
# Format: "IP:port->IP:port"
|
|
733
|
+
for endpoint in part.split("->"):
|
|
734
|
+
ip_port = endpoint.rsplit(":", 1)
|
|
735
|
+
if len(ip_port) == 2 and RE_IP.match(ip_port[0]):
|
|
736
|
+
tokens.extend(_tokenize_ip(ip_port[0]))
|
|
737
|
+
tokens.append(_tokenize_port(ip_port[1]))
|
|
738
|
+
else:
|
|
739
|
+
tokens.extend(self._pretokenize_segment(endpoint))
|
|
740
|
+
elif RE_IP.match(part):
|
|
741
|
+
tokens.extend(_tokenize_ip(part))
|
|
742
|
+
elif RE_IPV6.match(part):
|
|
743
|
+
if normalize_ips:
|
|
744
|
+
tokens.append(self._classify_ipv6(part))
|
|
745
|
+
if self.expand_netflow_ips:
|
|
746
|
+
tokens.extend(self._pretokenize_ipv6(part))
|
|
747
|
+
else:
|
|
748
|
+
tokens.extend(self._pretokenize_ipv6(part))
|
|
749
|
+
elif part.isdigit():
|
|
750
|
+
tokens.append(_tokenize_port(part))
|
|
751
|
+
elif ":" in part:
|
|
752
|
+
ip_port = part.rsplit(":", 1)
|
|
753
|
+
if RE_IP.match(ip_port[0]):
|
|
754
|
+
tokens.extend(_tokenize_ip(ip_port[0]))
|
|
755
|
+
tokens.append(_tokenize_port(ip_port[1]))
|
|
756
|
+
else:
|
|
757
|
+
tokens.extend(self._pretokenize_segment(part))
|
|
758
|
+
else:
|
|
759
|
+
tokens.extend(self._pretokenize_segment(part))
|
|
760
|
+
return tokens
|
|
761
|
+
|
|
762
|
+
# ── File / Subject ──
|
|
763
|
+
tokens = []
|
|
764
|
+
for part in parts:
|
|
765
|
+
if not part or part == "None":
|
|
766
|
+
continue
|
|
767
|
+
if self._looks_like_path(part):
|
|
768
|
+
tokens.extend(self._pretokenize_path(part))
|
|
769
|
+
elif RE_FLAG.match(part):
|
|
770
|
+
tokens.extend(self._tokenize_flag(part))
|
|
771
|
+
elif "&" in part and RE_QUERY_STRING.match(part):
|
|
772
|
+
# Full URL query string (e.g. "detail=detail&id=5457&type=show")
|
|
773
|
+
tokens.extend(self._pretokenize_query_string(part))
|
|
774
|
+
elif "=" in part and not part.startswith("="):
|
|
775
|
+
# key=value argument (e.g. --channel=123, --output=/tmp/f)
|
|
776
|
+
k, _, v = part.partition("=")
|
|
777
|
+
if RE_FLAG.match(k):
|
|
778
|
+
tokens.extend(self._tokenize_flag(k))
|
|
779
|
+
else:
|
|
780
|
+
tokens.extend(self._pretokenize_segment(k))
|
|
781
|
+
if v:
|
|
782
|
+
if self._looks_like_path(v):
|
|
783
|
+
tokens.extend(self._pretokenize_path(v))
|
|
784
|
+
else:
|
|
785
|
+
tokens.extend(self._pretokenize_segment(v))
|
|
786
|
+
else:
|
|
787
|
+
tokens.extend(self._pretokenize_segment(part))
|
|
788
|
+
return tokens
|
|
789
|
+
|
|
790
|
+
# ── Category token matching ──────────────────────────────────────────
|
|
791
|
+
|
|
792
|
+
@staticmethod
|
|
793
|
+
def _get_category_token(node_type: str, label_str: str) -> Optional[str]:
|
|
794
|
+
"""Return the canonical category token for a node, or None if no match.
|
|
795
|
+
|
|
796
|
+
For processes: extracts binary name and looks up in PROC_CATEGORIES.
|
|
797
|
+
For files: matches path against FILE_DIR_CATEGORIES (most-specific-first).
|
|
798
|
+
For sockets: no additional category (already have IP/port categories).
|
|
799
|
+
"""
|
|
800
|
+
if node_type == "subject":
|
|
801
|
+
return match_proc_category(label_str)
|
|
802
|
+
elif node_type == "file":
|
|
803
|
+
return match_file_category(label_str)
|
|
804
|
+
return None
|
|
805
|
+
|
|
806
|
+
def _pretokenize_node_with_category(self, node_type: str, label_str: str) -> List[str]:
|
|
807
|
+
"""Pre-tokenize a node and prepend any matching category token.
|
|
808
|
+
|
|
809
|
+
Used for encoder input (full detail + category signal) and for
|
|
810
|
+
continue-pretrain decoder targets (same: full tokens + category).
|
|
811
|
+
"""
|
|
812
|
+
tokens = self._pretokenize_node(node_type, label_str)
|
|
813
|
+
cat = self._get_category_token(node_type, label_str)
|
|
814
|
+
if cat:
|
|
815
|
+
tokens = [cat] + tokens
|
|
816
|
+
return tokens
|
|
817
|
+
|
|
818
|
+
@staticmethod
|
|
819
|
+
def _is_canonical_token(tok: str) -> bool:
|
|
820
|
+
"""Return True if tok is a token to keep in canonical neighbor targets.
|
|
821
|
+
|
|
822
|
+
Kept: category tokens ([CAT_*], [FCAT_*]), port tokens ([PORT_*]),
|
|
823
|
+
IP category tokens, [IPV6], file extension tokens ([EXT_*]),
|
|
824
|
+
null-label tokens ([NO_CMD], [NO_PATH], [NO_IP]).
|
|
825
|
+
|
|
826
|
+
Stripped: path structure ([ROOT], [/USR], [/LIB], …), separators
|
|
827
|
+
([SEP_*]), value tokens ([HASH], [GUID], [RANDOM], [NUM], [VER],
|
|
828
|
+
[TIMESTAMP], [ENV], [FLAG]), and all other domain tokens.
|
|
829
|
+
"""
|
|
830
|
+
if not (tok.startswith("[") and tok.endswith("]")):
|
|
831
|
+
return False
|
|
832
|
+
return (
|
|
833
|
+
tok.startswith("[CAT_")
|
|
834
|
+
or tok.startswith("[FCAT_")
|
|
835
|
+
or tok.startswith("[PORT_")
|
|
836
|
+
or tok.startswith("[EXT_")
|
|
837
|
+
or tok in (PRIVATE_IP, PUBLIC_IP, LOCALHOST_IP, IPV6,
|
|
838
|
+
PORT_LOW, PORT_REG, PORT_EPH,
|
|
839
|
+
NO_CMD, NO_PATH, NO_IP)
|
|
840
|
+
)
|
|
841
|
+
|
|
842
|
+
def _canonicalize_pretokens(self, tokens: List[str], category_token: Optional[str] = None) -> List[str]:
|
|
843
|
+
"""Filter pre-tokens to keep only canonical tokens.
|
|
844
|
+
|
|
845
|
+
Used for decoder reconstruction targets during main pretraining:
|
|
846
|
+
strips dataset-specific words AND structural noise (paths, flags,
|
|
847
|
+
separators), keeping only category tokens, port/IP categories,
|
|
848
|
+
file extensions, and null-label markers.
|
|
849
|
+
"""
|
|
850
|
+
canonical = []
|
|
851
|
+
if category_token:
|
|
852
|
+
canonical.append(category_token)
|
|
853
|
+
for tok in tokens:
|
|
854
|
+
if self._is_canonical_token(tok):
|
|
855
|
+
canonical.append(tok)
|
|
856
|
+
return canonical
|
|
857
|
+
|
|
858
|
+
def tokenize_node_canonical(self, node_type: str, label_str: str) -> List[int]:
|
|
859
|
+
"""Tokenize a node keeping only special tokens + category token.
|
|
860
|
+
|
|
861
|
+
Used for neighbor nodes in decoder targets during main pretraining.
|
|
862
|
+
The node type prefix is always included, then the canonical tokens.
|
|
863
|
+
"""
|
|
864
|
+
label_str = _BINARY_GARBAGE_RE.sub("", label_str).strip()
|
|
865
|
+
|
|
866
|
+
ids = []
|
|
867
|
+
|
|
868
|
+
# Node type prefix (skip when strip_entity_type is active)
|
|
869
|
+
if not self.strip_entity_type:
|
|
870
|
+
type_tok = NODE_TYPE_TOKENS.get(node_type)
|
|
871
|
+
if type_tok and type_tok in self.token2id:
|
|
872
|
+
ids.append(self.token2id[type_tok])
|
|
873
|
+
|
|
874
|
+
# Get category token
|
|
875
|
+
cat = self._get_category_token(node_type, label_str)
|
|
876
|
+
|
|
877
|
+
# Pre-tokenize normally, then filter to special tokens only
|
|
878
|
+
pretok_fn = self._pretokenize_node if self.mode == "domain_bpe" else self._pretokenize_node_simple
|
|
879
|
+
raw_tokens = pretok_fn(node_type, label_str)
|
|
880
|
+
canonical = self._canonicalize_pretokens(raw_tokens, cat)
|
|
881
|
+
|
|
882
|
+
for tok in canonical:
|
|
883
|
+
if tok in self.token2id:
|
|
884
|
+
ids.append(self.token2id[tok])
|
|
885
|
+
|
|
886
|
+
return ids
|
|
887
|
+
|
|
888
|
+
# ── Phase 2: BPE ─────────────────────────────────────────────────────
|
|
889
|
+
|
|
890
|
+
def _collect_bpe_words(self, corpus: List[List[str]]) -> Counter:
|
|
891
|
+
"""Count word frequencies for BPE training.
|
|
892
|
+
|
|
893
|
+
Skips special tokens, words already registered in vocab, and words
|
|
894
|
+
containing non-ASCII characters (non-ASCII base chars are still
|
|
895
|
+
registered individually in _train_bpe, but we don't want BPE to learn
|
|
896
|
+
merges of garbage Unicode sequences from malformed labels).
|
|
897
|
+
"""
|
|
898
|
+
freq = Counter()
|
|
899
|
+
for tokens in corpus:
|
|
900
|
+
for tok in tokens:
|
|
901
|
+
if tok in self.token2id:
|
|
902
|
+
continue
|
|
903
|
+
if tok.startswith("[") and tok.endswith("]"):
|
|
904
|
+
continue
|
|
905
|
+
if not tok.isascii():
|
|
906
|
+
continue
|
|
907
|
+
freq[tok] += 1
|
|
908
|
+
return freq
|
|
909
|
+
|
|
910
|
+
def _train_bpe(self, corpus: List[List[str]]):
|
|
911
|
+
"""Train BPE merges on pre-tokenized corpus."""
|
|
912
|
+
# Pre-seed all printable ASCII as base character tokens.
|
|
913
|
+
# This ensures BPE can encode any word, even with chars not in training.
|
|
914
|
+
for i in range(32, 127):
|
|
915
|
+
c = chr(i)
|
|
916
|
+
if c not in self.token2id:
|
|
917
|
+
self.token2id[c] = len(self.token2id)
|
|
918
|
+
|
|
919
|
+
word_freqs = self._collect_bpe_words(corpus)
|
|
920
|
+
if not word_freqs:
|
|
921
|
+
return
|
|
922
|
+
|
|
923
|
+
# Initialize: split each word into characters
|
|
924
|
+
word_splits = {w: list(w) for w in word_freqs}
|
|
925
|
+
|
|
926
|
+
# Add any non-ASCII characters found in corpus
|
|
927
|
+
for chars in word_splits.values():
|
|
928
|
+
for c in chars:
|
|
929
|
+
if c not in self.token2id:
|
|
930
|
+
self.token2id[c] = len(self.token2id)
|
|
931
|
+
|
|
932
|
+
n_merges = max(0, self.bpe_vocab_size - len(self.token2id))
|
|
933
|
+
self.merges = []
|
|
934
|
+
|
|
935
|
+
for _ in range(n_merges):
|
|
936
|
+
# Count pair frequencies
|
|
937
|
+
pair_freq = Counter()
|
|
938
|
+
for word, freq in word_freqs.items():
|
|
939
|
+
chars = word_splits[word]
|
|
940
|
+
for i in range(len(chars) - 1):
|
|
941
|
+
pair_freq[(chars[i], chars[i + 1])] += freq
|
|
942
|
+
|
|
943
|
+
if not pair_freq:
|
|
944
|
+
break
|
|
945
|
+
|
|
946
|
+
best_pair, best_count = pair_freq.most_common(1)[0]
|
|
947
|
+
if best_count < 2:
|
|
948
|
+
break
|
|
949
|
+
|
|
950
|
+
self.merges.append(best_pair)
|
|
951
|
+
merged_tok = best_pair[0] + best_pair[1]
|
|
952
|
+
if merged_tok not in self.token2id:
|
|
953
|
+
self.token2id[merged_tok] = len(self.token2id)
|
|
954
|
+
|
|
955
|
+
# Apply merge across all words
|
|
956
|
+
a, b = best_pair
|
|
957
|
+
new_splits = {}
|
|
958
|
+
for word, chars in word_splits.items():
|
|
959
|
+
new_chars = []
|
|
960
|
+
i = 0
|
|
961
|
+
while i < len(chars):
|
|
962
|
+
if i < len(chars) - 1 and chars[i] == a and chars[i + 1] == b:
|
|
963
|
+
new_chars.append(merged_tok)
|
|
964
|
+
i += 2
|
|
965
|
+
else:
|
|
966
|
+
new_chars.append(chars[i])
|
|
967
|
+
i += 1
|
|
968
|
+
new_splits[word] = new_chars
|
|
969
|
+
word_splits = new_splits
|
|
970
|
+
|
|
971
|
+
def _apply_bpe(self, word: str) -> List[str]:
|
|
972
|
+
"""Apply learned BPE merges to a word -> list of subword tokens."""
|
|
973
|
+
if not word:
|
|
974
|
+
return []
|
|
975
|
+
|
|
976
|
+
chars = list(word)
|
|
977
|
+
for a, b in self.merges:
|
|
978
|
+
i = 0
|
|
979
|
+
while i < len(chars) - 1:
|
|
980
|
+
if chars[i] == a and chars[i + 1] == b:
|
|
981
|
+
chars = chars[:i] + [a + b] + chars[i + 2:]
|
|
982
|
+
else:
|
|
983
|
+
i += 1
|
|
984
|
+
return chars
|
|
985
|
+
|
|
986
|
+
def _token_to_id(self, tok: str) -> int:
|
|
987
|
+
"""Convert a token to its ID, using UNK for unknown."""
|
|
988
|
+
return self.token2id.get(tok, self.token2id.get(UNK, 0))
|
|
989
|
+
|
|
990
|
+
# ── Vocabulary management ─────────────────────────────────────────────
|
|
991
|
+
|
|
992
|
+
def build_vocab(
|
|
993
|
+
self,
|
|
994
|
+
indexid2msg: Dict[str, list],
|
|
995
|
+
nodes_to_include: Optional[Set] = None,
|
|
996
|
+
walk_label_corpus: Optional[List[Tuple[str, str]]] = None,
|
|
997
|
+
):
|
|
998
|
+
"""Build vocabulary: special tokens + domain tokens + BPE from training data.
|
|
999
|
+
|
|
1000
|
+
Args:
|
|
1001
|
+
indexid2msg: node ID → (node_type, label_str) mapping (used as fallback).
|
|
1002
|
+
nodes_to_include: if set, only include these node IDs (only used with indexid2msg).
|
|
1003
|
+
walk_label_corpus: if provided, use this walk-frequency-weighted list of
|
|
1004
|
+
(node_type, label_str) pairs instead of iterating over indexid2msg.
|
|
1005
|
+
Each entry corresponds to one node occurrence in a unique (prelabel-deduped)
|
|
1006
|
+
walk, so common nodes in many distinct walks get higher frequency weight.
|
|
1007
|
+
"""
|
|
1008
|
+
self.token2id = {}
|
|
1009
|
+
|
|
1010
|
+
# Special tokens (fixed positions)
|
|
1011
|
+
for tok in SPECIAL_TOKENS:
|
|
1012
|
+
self.token2id[tok] = len(self.token2id)
|
|
1013
|
+
|
|
1014
|
+
# Node type tokens
|
|
1015
|
+
for tok in NODE_TYPE_TOKENS.values():
|
|
1016
|
+
if tok not in self.token2id:
|
|
1017
|
+
self.token2id[tok] = len(self.token2id)
|
|
1018
|
+
|
|
1019
|
+
# Edge type tokens
|
|
1020
|
+
for tok in sorted(self.edge_tokens.values()):
|
|
1021
|
+
if tok not in self.token2id:
|
|
1022
|
+
self.token2id[tok] = len(self.token2id)
|
|
1023
|
+
|
|
1024
|
+
# Domain-specific tokens (skipped in bpe_only mode)
|
|
1025
|
+
if self.mode == "domain_bpe":
|
|
1026
|
+
domain_toks = [
|
|
1027
|
+
HASH, GUID, RANDOM, TIMESTAMP, VER, NUM, ENV_VAR, FLAG,
|
|
1028
|
+
ROOT, WIN_ROOT, NO_CMD, NO_PATH, NO_IP,
|
|
1029
|
+
SEP_DASH, SEP_UNDERSCORE, SEP_DOT, SEP_PLUS, SEP_AMP,
|
|
1030
|
+
PORT_LOW, PORT_REG, PORT_EPH, IPV6,
|
|
1031
|
+
PRIVATE_IP, PUBLIC_IP, LOCALHOST_IP,
|
|
1032
|
+
]
|
|
1033
|
+
domain_toks.extend(sorted(WELL_KNOWN_PORTS.values()))
|
|
1034
|
+
domain_toks.extend(sorted(set(UNIX_DIRS.values())))
|
|
1035
|
+
domain_toks.extend(sorted(set(WIN_DIRS.values())))
|
|
1036
|
+
domain_toks.extend(sorted(set(UNIX_DIRS_PATH.values()))) # [/USR], [/LIB], …
|
|
1037
|
+
domain_toks.extend(sorted(set(WIN_DIRS_PATH.values()))) # [/WINDOWS], …
|
|
1038
|
+
domain_toks.extend(f"[EXT_{e}]" for e in sorted(KNOWN_EXTENSIONS))
|
|
1039
|
+
|
|
1040
|
+
# Canonical category tokens (process + file categories)
|
|
1041
|
+
if self.canonicalize_neighbors:
|
|
1042
|
+
domain_toks.extend(ALL_CATEGORY_TOKENS)
|
|
1043
|
+
|
|
1044
|
+
for tok in domain_toks:
|
|
1045
|
+
if tok not in self.token2id:
|
|
1046
|
+
self.token2id[tok] = len(self.token2id)
|
|
1047
|
+
|
|
1048
|
+
if self.canonicalize_neighbors and self.mode == "domain_bpe":
|
|
1049
|
+
pretok_fn = self._pretokenize_node_with_category
|
|
1050
|
+
elif self.mode == "domain_bpe":
|
|
1051
|
+
pretok_fn = self._pretokenize_node
|
|
1052
|
+
else:
|
|
1053
|
+
pretok_fn = self._pretokenize_node_simple
|
|
1054
|
+
|
|
1055
|
+
# Pre-tokenize training corpus
|
|
1056
|
+
corpus = []
|
|
1057
|
+
if walk_label_corpus is not None:
|
|
1058
|
+
# Walk-frequency-weighted: each unique walk contributes one entry per node,
|
|
1059
|
+
# so labels that appear in many distinct walks get proportionally higher weight.
|
|
1060
|
+
for node_type, label_str in walk_label_corpus:
|
|
1061
|
+
label_str = _BINARY_GARBAGE_RE.sub("", label_str).strip()
|
|
1062
|
+
corpus.append(pretok_fn(node_type, label_str))
|
|
1063
|
+
else:
|
|
1064
|
+
# Fallback: one entry per unique entity in indexid2msg (entity-count weighted).
|
|
1065
|
+
for node_id, (node_type, label_str) in indexid2msg.items():
|
|
1066
|
+
if nodes_to_include is not None and node_id not in nodes_to_include:
|
|
1067
|
+
continue
|
|
1068
|
+
label_str = _BINARY_GARBAGE_RE.sub("", label_str).strip()
|
|
1069
|
+
corpus.append(pretok_fn(node_type, label_str))
|
|
1070
|
+
|
|
1071
|
+
# Pre-register frequently-seen words as direct vocab entries.
|
|
1072
|
+
# Cap at half the BPE budget to leave room for BPE merges.
|
|
1073
|
+
word_freq = Counter(
|
|
1074
|
+
tok for tokens in corpus for tok in tokens
|
|
1075
|
+
if not (tok.startswith("[") and tok.endswith("]"))
|
|
1076
|
+
)
|
|
1077
|
+
max_direct = self.bpe_vocab_size // 2
|
|
1078
|
+
for word, _count in word_freq.most_common():
|
|
1079
|
+
if len(self.token2id) >= max_direct + len(SPECIAL_TOKENS) + 50:
|
|
1080
|
+
break
|
|
1081
|
+
if _count >= 2 and word not in self.token2id:
|
|
1082
|
+
self.token2id[word] = len(self.token2id)
|
|
1083
|
+
|
|
1084
|
+
pre_bpe_size = len(self.token2id)
|
|
1085
|
+
self.pre_bpe_size = pre_bpe_size
|
|
1086
|
+
|
|
1087
|
+
# Train BPE on remaining rare words (also adds character + merge tokens)
|
|
1088
|
+
self._train_bpe(corpus)
|
|
1089
|
+
|
|
1090
|
+
self.id2token = {v: k for k, v in self.token2id.items()}
|
|
1091
|
+
self.vocab_size = len(self.token2id)
|
|
1092
|
+
|
|
1093
|
+
source = "walk-based" if walk_label_corpus is not None else "entity-based"
|
|
1094
|
+
log(f"Tokenizer ({source}): {len(corpus)} corpus entries, "
|
|
1095
|
+
f"{len(word_freq)} unique words, "
|
|
1096
|
+
f"pre-BPE vocab={pre_bpe_size}, "
|
|
1097
|
+
f"BPE merges={len(self.merges)}, "
|
|
1098
|
+
f"final vocab={self.vocab_size}")
|
|
1099
|
+
|
|
1100
|
+
def save(self, path: str):
|
|
1101
|
+
"""Save tokenizer state."""
|
|
1102
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
1103
|
+
torch.save(
|
|
1104
|
+
{
|
|
1105
|
+
"token2id": self.token2id,
|
|
1106
|
+
"vocab_size": self.vocab_size,
|
|
1107
|
+
"max_seq_len": self.max_seq_len,
|
|
1108
|
+
"merges": self.merges,
|
|
1109
|
+
"mode": self.mode,
|
|
1110
|
+
"normalize_netflow_ips": self.normalize_netflow_ips,
|
|
1111
|
+
"substitutions": sorted(self.substitutions),
|
|
1112
|
+
"canonicalize_neighbors": self.canonicalize_neighbors,
|
|
1113
|
+
},
|
|
1114
|
+
path,
|
|
1115
|
+
)
|
|
1116
|
+
|
|
1117
|
+
def dump_vocab(self, path: str):
|
|
1118
|
+
"""Write vocab to a human-readable text file, split by step."""
|
|
1119
|
+
pre_bpe_size = getattr(self, "pre_bpe_size", None)
|
|
1120
|
+
sorted_tokens = sorted(self.token2id.items(), key=lambda x: x[1])
|
|
1121
|
+
with open(path, "w") as f:
|
|
1122
|
+
f.write(f"# Vocabulary: {self.vocab_size} tokens\n")
|
|
1123
|
+
if pre_bpe_size is not None:
|
|
1124
|
+
f.write(f"# Step 1 (direct): tokens 0–{pre_bpe_size - 1} ({pre_bpe_size} tokens)\n")
|
|
1125
|
+
f.write(f"# Step 2 (BPE): tokens {pre_bpe_size}–{self.vocab_size - 1} ({self.vocab_size - pre_bpe_size} tokens)\n")
|
|
1126
|
+
f.write("\n")
|
|
1127
|
+
current_section = None
|
|
1128
|
+
for token, idx in sorted_tokens:
|
|
1129
|
+
if pre_bpe_size is not None:
|
|
1130
|
+
section = 1 if idx < pre_bpe_size else 2
|
|
1131
|
+
if section != current_section:
|
|
1132
|
+
current_section = section
|
|
1133
|
+
if section == 1:
|
|
1134
|
+
f.write("# ── Step 1: special + domain + frequent words ──\n")
|
|
1135
|
+
else:
|
|
1136
|
+
f.write("\n# ── Step 2: BPE subwords ──\n")
|
|
1137
|
+
f.write(f"{idx}\t{token}\n")
|
|
1138
|
+
|
|
1139
|
+
def load(self, path: str):
|
|
1140
|
+
"""Load tokenizer state."""
|
|
1141
|
+
state = torch.load(path)
|
|
1142
|
+
self.token2id = state["token2id"]
|
|
1143
|
+
self.vocab_size = state["vocab_size"]
|
|
1144
|
+
self.max_seq_len = state["max_seq_len"]
|
|
1145
|
+
self.merges = state["merges"]
|
|
1146
|
+
self.mode = state["mode"]
|
|
1147
|
+
substitutions = state.get("substitutions")
|
|
1148
|
+
if substitutions is None:
|
|
1149
|
+
# Saved before substitutions were configurable: all of them in domain_bpe mode
|
|
1150
|
+
# (IPs per the old flag), none in bpe_only mode
|
|
1151
|
+
substitutions = []
|
|
1152
|
+
if state["mode"] == "domain_bpe":
|
|
1153
|
+
substitutions = [m for m in SUBSTITUTION_METHODS if m != "ip"]
|
|
1154
|
+
if state["normalize_netflow_ips"]:
|
|
1155
|
+
substitutions.append("ip")
|
|
1156
|
+
self._set_substitutions(substitutions)
|
|
1157
|
+
self.canonicalize_neighbors = state["canonicalize_neighbors"]
|
|
1158
|
+
self.id2token = {v: k for k, v in self.token2id.items()}
|
|
1159
|
+
|
|
1160
|
+
# ── Tokenization ──────────────────────────────────────────────────────
|
|
1161
|
+
|
|
1162
|
+
def tokenize_node(self, node_type: str, label_str: str) -> List[int]:
|
|
1163
|
+
"""Tokenize a node: [type_prefix] + domain_tokens / BPE_subwords.
|
|
1164
|
+
|
|
1165
|
+
When canonicalize_neighbors is enabled, a matching category token
|
|
1166
|
+
is prepended after the type prefix (for encoder input: full detail
|
|
1167
|
+
+ category signal).
|
|
1168
|
+
"""
|
|
1169
|
+
# Sanitize binary garbage before tokenization
|
|
1170
|
+
label_str = _BINARY_GARBAGE_RE.sub("", label_str).strip()
|
|
1171
|
+
|
|
1172
|
+
ids = []
|
|
1173
|
+
|
|
1174
|
+
# Node type prefix (skip when strip_entity_type is active)
|
|
1175
|
+
if (not hasattr(self, "strip_entity_type")) or (not self.strip_entity_type):
|
|
1176
|
+
type_tok = NODE_TYPE_TOKENS.get(node_type)
|
|
1177
|
+
if type_tok and type_tok in self.token2id:
|
|
1178
|
+
ids.append(self.token2id[type_tok])
|
|
1179
|
+
|
|
1180
|
+
# Prepend category token when canonicalization is active
|
|
1181
|
+
if self.canonicalize_neighbors:
|
|
1182
|
+
cat = self._get_category_token(node_type, label_str)
|
|
1183
|
+
if cat and cat in self.token2id:
|
|
1184
|
+
ids.append(self.token2id[cat])
|
|
1185
|
+
|
|
1186
|
+
# Pre-tokenize, then convert to IDs
|
|
1187
|
+
pretok_fn = self._pretokenize_node if self.mode == "domain_bpe" else self._pretokenize_node_simple
|
|
1188
|
+
for tok in pretok_fn(node_type, label_str):
|
|
1189
|
+
if tok in self.token2id:
|
|
1190
|
+
ids.append(self.token2id[tok])
|
|
1191
|
+
else:
|
|
1192
|
+
# BPE fallback for unknown words
|
|
1193
|
+
for sub in self._apply_bpe(tok):
|
|
1194
|
+
ids.append(self._token_to_id(sub))
|
|
1195
|
+
|
|
1196
|
+
return ids
|
|
1197
|
+
|
|
1198
|
+
def tokenize_edge(self, edge_type: str) -> List[int]:
|
|
1199
|
+
"""Tokenize an edge type into a single token ID."""
|
|
1200
|
+
tok = self.edge_tokens.get(edge_type)
|
|
1201
|
+
if tok and tok in self.token2id:
|
|
1202
|
+
return [self.token2id[tok]]
|
|
1203
|
+
return []
|
|
1204
|
+
|
|
1205
|
+
@property
|
|
1206
|
+
def forward_id(self) -> int:
|
|
1207
|
+
"""Token ID for [FORWARD] direction token."""
|
|
1208
|
+
return self.token2id[FORWARD]
|
|
1209
|
+
|
|
1210
|
+
@property
|
|
1211
|
+
def backward_id(self) -> int:
|
|
1212
|
+
"""Token ID for [BACKWARD] direction token."""
|
|
1213
|
+
return self.token2id[BACKWARD]
|
|
1214
|
+
|
|
1215
|
+
@property
|
|
1216
|
+
def forward_neigh_id(self) -> int:
|
|
1217
|
+
"""Token ID for [FORWARD_NEIGH] direction token."""
|
|
1218
|
+
return self.token2id[FORWARD_NEIGH]
|
|
1219
|
+
|
|
1220
|
+
@property
|
|
1221
|
+
def backward_neigh_id(self) -> int:
|
|
1222
|
+
"""Token ID for [BACKWARD_NEIGH] direction token."""
|
|
1223
|
+
return self.token2id[BACKWARD_NEIGH]
|
|
1224
|
+
|
|
1225
|
+
def tokenize_context_segment(
|
|
1226
|
+
self,
|
|
1227
|
+
edge_types: List[str],
|
|
1228
|
+
node_ids: List[str],
|
|
1229
|
+
indexid2msg: Dict[str, list],
|
|
1230
|
+
canonical: Optional[bool] = None,
|
|
1231
|
+
) -> List[int]:
|
|
1232
|
+
"""Tokenize an edge-first walk segment for T5 decoder targets.
|
|
1233
|
+
|
|
1234
|
+
Produces: [edge0_token] [node0_tokens] [edge1_token] [node1_tokens] ...
|
|
1235
|
+
|
|
1236
|
+
Used for forward/backward context segments split from a walk at the
|
|
1237
|
+
entity position. Each segment starts with an edge (the edge connecting
|
|
1238
|
+
the entity to its neighbor) followed by the neighbor node, then the
|
|
1239
|
+
next edge, etc.
|
|
1240
|
+
|
|
1241
|
+
Args:
|
|
1242
|
+
edge_types: list of edge type strings (same length as node_ids)
|
|
1243
|
+
node_ids: list of node IDs (one per edge)
|
|
1244
|
+
indexid2msg: node ID to (node_type, label_str) mapping
|
|
1245
|
+
canonical: if True, neighbor nodes are canonicalized (only special
|
|
1246
|
+
tokens + category tokens). If False, full tokenization with
|
|
1247
|
+
category tokens prepended. If None (default), uses
|
|
1248
|
+
self.canonicalize_neighbors.
|
|
1249
|
+
|
|
1250
|
+
Returns:
|
|
1251
|
+
token_ids: flat list of token IDs (truncated to max_seq_len)
|
|
1252
|
+
"""
|
|
1253
|
+
use_canonical = canonical if canonical is not None else self.canonicalize_neighbors
|
|
1254
|
+
token_ids = []
|
|
1255
|
+
for etype, nid in zip(edge_types, node_ids):
|
|
1256
|
+
token_ids.extend(self.tokenize_edge(etype))
|
|
1257
|
+
if nid in indexid2msg:
|
|
1258
|
+
ntype, nlabel = indexid2msg[nid]
|
|
1259
|
+
if use_canonical:
|
|
1260
|
+
token_ids.extend(self.tokenize_node_canonical(ntype, nlabel))
|
|
1261
|
+
else:
|
|
1262
|
+
token_ids.extend(self.tokenize_node(ntype, nlabel))
|
|
1263
|
+
return token_ids[:self.max_seq_len]
|
|
1264
|
+
|
|
1265
|
+
def tokenize_walk(
|
|
1266
|
+
self,
|
|
1267
|
+
walk_nodes: List[str],
|
|
1268
|
+
walk_edge_types: List[str],
|
|
1269
|
+
indexid2msg: Dict[str, list],
|
|
1270
|
+
) -> Tuple[List[int], List[Tuple[int, int]], List[Tuple[int, int]]]:
|
|
1271
|
+
"""Tokenize a walk into a flat token sequence with node and edge boundaries.
|
|
1272
|
+
|
|
1273
|
+
Returns:
|
|
1274
|
+
token_ids: flat list of token IDs
|
|
1275
|
+
node_boundaries: list of (start, end) for each node's tokens
|
|
1276
|
+
edge_boundaries: list of (start, end) for each edge's tokens.
|
|
1277
|
+
edge_boundaries[j] is the edge added after node_boundaries[j].
|
|
1278
|
+
"""
|
|
1279
|
+
token_ids = []
|
|
1280
|
+
node_boundaries = []
|
|
1281
|
+
edge_boundaries = []
|
|
1282
|
+
|
|
1283
|
+
for i, node_id in enumerate(walk_nodes):
|
|
1284
|
+
if node_id not in indexid2msg:
|
|
1285
|
+
continue
|
|
1286
|
+
|
|
1287
|
+
node_type, label_str = indexid2msg[node_id]
|
|
1288
|
+
node_tokens = self.tokenize_node(node_type, label_str)
|
|
1289
|
+
if not node_tokens:
|
|
1290
|
+
continue
|
|
1291
|
+
|
|
1292
|
+
start = len(token_ids)
|
|
1293
|
+
token_ids.extend(node_tokens)
|
|
1294
|
+
node_boundaries.append((start, len(token_ids)))
|
|
1295
|
+
|
|
1296
|
+
if i < len(walk_edge_types):
|
|
1297
|
+
edge_toks = self.tokenize_edge(walk_edge_types[i])
|
|
1298
|
+
if edge_toks:
|
|
1299
|
+
edge_start = len(token_ids)
|
|
1300
|
+
token_ids.extend(edge_toks)
|
|
1301
|
+
edge_boundaries.append((edge_start, len(token_ids)))
|
|
1302
|
+
|
|
1303
|
+
if len(token_ids) > self.max_seq_len:
|
|
1304
|
+
token_ids = token_ids[: self.max_seq_len]
|
|
1305
|
+
node_boundaries = [
|
|
1306
|
+
(s, min(e, self.max_seq_len))
|
|
1307
|
+
for s, e in node_boundaries
|
|
1308
|
+
if s < self.max_seq_len
|
|
1309
|
+
]
|
|
1310
|
+
edge_boundaries = [
|
|
1311
|
+
(s, min(e, self.max_seq_len))
|
|
1312
|
+
for s, e in edge_boundaries
|
|
1313
|
+
if s < self.max_seq_len
|
|
1314
|
+
]
|
|
1315
|
+
|
|
1316
|
+
return token_ids, node_boundaries, edge_boundaries
|
|
1317
|
+
|
|
1318
|
+
# ── Masking ───────────────────────────────────────────────────────────
|
|
1319
|
+
|
|
1320
|
+
def set_mask_rate(self, percent_done: float, fixed_rate: float = 0.7, min_rate: float = 0.15):
|
|
1321
|
+
"""Polynomial annealing of mask rate (same as CyberGFM)."""
|
|
1322
|
+
anneal = 1 - (percent_done ** 2)
|
|
1323
|
+
self.mask_rate = max(anneal * fixed_rate, min_rate)
|
|
1324
|
+
|
|
1325
|
+
def mask_nodes(
|
|
1326
|
+
self,
|
|
1327
|
+
token_ids: List[int],
|
|
1328
|
+
node_boundaries: List[Tuple[int, int]],
|
|
1329
|
+
) -> Tuple[List[int], List[int], List[bool]]:
|
|
1330
|
+
"""Node-level masking: 80% [MASK], 10% random, 10% keep."""
|
|
1331
|
+
seq_len = len(token_ids)
|
|
1332
|
+
masked_ids = list(token_ids)
|
|
1333
|
+
targets = []
|
|
1334
|
+
predict_mask = [False] * seq_len
|
|
1335
|
+
|
|
1336
|
+
n_nodes = len(node_boundaries)
|
|
1337
|
+
if n_nodes == 0:
|
|
1338
|
+
return masked_ids, targets, predict_mask
|
|
1339
|
+
|
|
1340
|
+
mask_flags = torch.rand(n_nodes) < self.mask_rate
|
|
1341
|
+
if not mask_flags.any():
|
|
1342
|
+
mask_flags[torch.randint(0, n_nodes, (1,))] = True
|
|
1343
|
+
|
|
1344
|
+
for idx in range(n_nodes):
|
|
1345
|
+
if not mask_flags[idx]:
|
|
1346
|
+
continue
|
|
1347
|
+
|
|
1348
|
+
start, end = node_boundaries[idx]
|
|
1349
|
+
for pos in range(start, min(end, seq_len)):
|
|
1350
|
+
predict_mask[pos] = True
|
|
1351
|
+
targets.append(token_ids[pos])
|
|
1352
|
+
|
|
1353
|
+
r = torch.rand(1).item()
|
|
1354
|
+
if r < 0.8:
|
|
1355
|
+
masked_ids[pos] = self.mask_id
|
|
1356
|
+
elif r < 0.9:
|
|
1357
|
+
masked_ids[pos] = torch.randint(0, self.vocab_size, (1,)).item()
|
|
1358
|
+
# else: keep original
|
|
1359
|
+
|
|
1360
|
+
return masked_ids, targets, predict_mask
|
|
1361
|
+
|
|
1362
|
+
def mask_walk(
|
|
1363
|
+
self,
|
|
1364
|
+
token_ids: List[int],
|
|
1365
|
+
node_boundaries: List[Tuple[int, int]],
|
|
1366
|
+
edge_boundaries: List[Tuple[int, int]],
|
|
1367
|
+
) -> Tuple[List[int], List[int], List[bool]]:
|
|
1368
|
+
"""Structured masking: mask nodes and edges, never adjacent pairs.
|
|
1369
|
+
|
|
1370
|
+
When a node is masked, its adjacent edges stay visible so the model
|
|
1371
|
+
can use edge types as context for node prediction. When an edge is
|
|
1372
|
+
masked, its adjacent nodes stay visible so the model can use node
|
|
1373
|
+
identities to predict the relationship.
|
|
1374
|
+
|
|
1375
|
+
Edge j is adjacent to node j (before) and node j+1 (after).
|
|
1376
|
+
"""
|
|
1377
|
+
seq_len = len(token_ids)
|
|
1378
|
+
masked_ids = list(token_ids)
|
|
1379
|
+
targets = []
|
|
1380
|
+
predict_mask = [False] * seq_len
|
|
1381
|
+
|
|
1382
|
+
n_nodes = len(node_boundaries)
|
|
1383
|
+
n_edges = len(edge_boundaries)
|
|
1384
|
+
|
|
1385
|
+
if n_nodes == 0:
|
|
1386
|
+
return masked_ids, targets, predict_mask
|
|
1387
|
+
|
|
1388
|
+
# Step 1: Select nodes to mask
|
|
1389
|
+
node_mask_flags = torch.rand(n_nodes) < self.mask_rate
|
|
1390
|
+
|
|
1391
|
+
# Step 2: Find protected edges (adjacent to any masked node)
|
|
1392
|
+
# edge j is adjacent to node j and node j+1
|
|
1393
|
+
protected_edges = set()
|
|
1394
|
+
for ni in range(n_nodes):
|
|
1395
|
+
if not node_mask_flags[ni]:
|
|
1396
|
+
continue
|
|
1397
|
+
if ni - 1 >= 0 and ni - 1 < n_edges:
|
|
1398
|
+
protected_edges.add(ni - 1)
|
|
1399
|
+
if ni < n_edges:
|
|
1400
|
+
protected_edges.add(ni)
|
|
1401
|
+
|
|
1402
|
+
# Step 3: Select unprotected edges to mask
|
|
1403
|
+
edge_mask_flags = torch.zeros(n_edges, dtype=torch.bool)
|
|
1404
|
+
for ei in range(n_edges):
|
|
1405
|
+
if ei not in protected_edges and torch.rand(1).item() < self.mask_rate:
|
|
1406
|
+
edge_mask_flags[ei] = True
|
|
1407
|
+
|
|
1408
|
+
# Ensure at least one position is masked
|
|
1409
|
+
if not node_mask_flags.any() and not edge_mask_flags.any():
|
|
1410
|
+
node_mask_flags[torch.randint(0, n_nodes, (1,))] = True
|
|
1411
|
+
|
|
1412
|
+
# Step 4: Apply masking to selected nodes
|
|
1413
|
+
for idx in range(n_nodes):
|
|
1414
|
+
if not node_mask_flags[idx]:
|
|
1415
|
+
continue
|
|
1416
|
+
start, end = node_boundaries[idx]
|
|
1417
|
+
for pos in range(start, min(end, seq_len)):
|
|
1418
|
+
predict_mask[pos] = True
|
|
1419
|
+
targets.append(token_ids[pos])
|
|
1420
|
+
r = torch.rand(1).item()
|
|
1421
|
+
if r < 0.8:
|
|
1422
|
+
masked_ids[pos] = self.mask_id
|
|
1423
|
+
elif r < 0.9:
|
|
1424
|
+
masked_ids[pos] = torch.randint(0, self.vocab_size, (1,)).item()
|
|
1425
|
+
|
|
1426
|
+
# Step 5: Apply masking to selected edges
|
|
1427
|
+
for idx in range(n_edges):
|
|
1428
|
+
if not edge_mask_flags[idx]:
|
|
1429
|
+
continue
|
|
1430
|
+
start, end = edge_boundaries[idx]
|
|
1431
|
+
for pos in range(start, min(end, seq_len)):
|
|
1432
|
+
predict_mask[pos] = True
|
|
1433
|
+
targets.append(token_ids[pos])
|
|
1434
|
+
r = torch.rand(1).item()
|
|
1435
|
+
if r < 0.8:
|
|
1436
|
+
masked_ids[pos] = self.mask_id
|
|
1437
|
+
elif r < 0.9:
|
|
1438
|
+
masked_ids[pos] = torch.randint(0, self.vocab_size, (1,)).item()
|
|
1439
|
+
|
|
1440
|
+
return masked_ids, targets, predict_mask
|
|
1441
|
+
|
|
1442
|
+
def batch_tokenize(
|
|
1443
|
+
self,
|
|
1444
|
+
walks: List[Tuple[List[str], List[str]]],
|
|
1445
|
+
indexid2msg: Dict[str, list],
|
|
1446
|
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
|
1447
|
+
"""Tokenize a batch of walks without masking -> padded tensors.
|
|
1448
|
+
|
|
1449
|
+
Used by causal LM models (LLaMA) that don't need masking.
|
|
1450
|
+
|
|
1451
|
+
Returns:
|
|
1452
|
+
input_ids: [B, L] padded token IDs
|
|
1453
|
+
attention_mask: [B, L] True for real tokens
|
|
1454
|
+
"""
|
|
1455
|
+
batch_token_ids = []
|
|
1456
|
+
for walk_nodes, walk_edge_types in walks:
|
|
1457
|
+
token_ids, _, _ = self.tokenize_walk(
|
|
1458
|
+
walk_nodes, walk_edge_types, indexid2msg
|
|
1459
|
+
)
|
|
1460
|
+
if token_ids:
|
|
1461
|
+
batch_token_ids.append(token_ids)
|
|
1462
|
+
|
|
1463
|
+
if not batch_token_ids:
|
|
1464
|
+
return torch.zeros(0, 1, dtype=torch.long), torch.zeros(0, 1, dtype=torch.bool)
|
|
1465
|
+
|
|
1466
|
+
max_len = min(max(len(s) for s in batch_token_ids), self.max_seq_len)
|
|
1467
|
+
B = len(batch_token_ids)
|
|
1468
|
+
|
|
1469
|
+
input_ids = torch.full((B, max_len), self.pad_id, dtype=torch.long)
|
|
1470
|
+
attention_mask = torch.zeros(B, max_len, dtype=torch.bool)
|
|
1471
|
+
|
|
1472
|
+
for i in range(B):
|
|
1473
|
+
seq_len = min(len(batch_token_ids[i]), max_len)
|
|
1474
|
+
input_ids[i, :seq_len] = torch.tensor(batch_token_ids[i][:seq_len])
|
|
1475
|
+
attention_mask[i, :seq_len] = True
|
|
1476
|
+
|
|
1477
|
+
return input_ids, attention_mask
|
|
1478
|
+
|
|
1479
|
+
def batch_tokenize_and_mask(
|
|
1480
|
+
self,
|
|
1481
|
+
walks: List[Tuple[List[str], List[str]]],
|
|
1482
|
+
indexid2msg: Dict[str, list],
|
|
1483
|
+
mask_edges: bool = True,
|
|
1484
|
+
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
|
1485
|
+
"""Tokenize and mask a batch of walks -> padded tensors.
|
|
1486
|
+
|
|
1487
|
+
Args:
|
|
1488
|
+
mask_edges: if True, use structured masking (nodes + edges,
|
|
1489
|
+
never adjacent). If False, mask only nodes (original behavior).
|
|
1490
|
+
|
|
1491
|
+
Returns:
|
|
1492
|
+
input_ids: [B, L] padded token IDs with masks applied
|
|
1493
|
+
attention_mask: [B, L] True for real tokens
|
|
1494
|
+
target_ids: [B, L] -100 for non-predicted, token_id for predicted
|
|
1495
|
+
predict_mask: [B, L] True at positions to predict
|
|
1496
|
+
"""
|
|
1497
|
+
batch_masked = []
|
|
1498
|
+
batch_targets = []
|
|
1499
|
+
|
|
1500
|
+
for walk_nodes, walk_edge_types in walks:
|
|
1501
|
+
token_ids, node_boundaries, edge_boundaries = self.tokenize_walk(
|
|
1502
|
+
walk_nodes, walk_edge_types, indexid2msg
|
|
1503
|
+
)
|
|
1504
|
+
if mask_edges and edge_boundaries:
|
|
1505
|
+
masked_ids, targets, predict_mask = self.mask_walk(
|
|
1506
|
+
token_ids, node_boundaries, edge_boundaries
|
|
1507
|
+
)
|
|
1508
|
+
else:
|
|
1509
|
+
masked_ids, targets, predict_mask = self.mask_nodes(
|
|
1510
|
+
token_ids, node_boundaries
|
|
1511
|
+
)
|
|
1512
|
+
batch_masked.append(masked_ids)
|
|
1513
|
+
batch_targets.append((targets, predict_mask))
|
|
1514
|
+
|
|
1515
|
+
max_len = min(max((len(s) for s in batch_masked), default=1), self.max_seq_len)
|
|
1516
|
+
B = len(batch_masked)
|
|
1517
|
+
|
|
1518
|
+
input_ids = torch.full((B, max_len), self.pad_id, dtype=torch.long)
|
|
1519
|
+
attention_mask = torch.zeros(B, max_len, dtype=torch.bool)
|
|
1520
|
+
target_tensor = torch.full((B, max_len), -100, dtype=torch.long)
|
|
1521
|
+
predict_tensor = torch.zeros(B, max_len, dtype=torch.bool)
|
|
1522
|
+
|
|
1523
|
+
for i in range(B):
|
|
1524
|
+
seq_len = min(len(batch_masked[i]), max_len)
|
|
1525
|
+
input_ids[i, :seq_len] = torch.tensor(batch_masked[i][:seq_len])
|
|
1526
|
+
attention_mask[i, :seq_len] = True
|
|
1527
|
+
|
|
1528
|
+
targets, p_mask = batch_targets[i]
|
|
1529
|
+
t_idx = 0
|
|
1530
|
+
for pos in range(seq_len):
|
|
1531
|
+
if p_mask[pos]:
|
|
1532
|
+
target_tensor[i, pos] = targets[t_idx]
|
|
1533
|
+
predict_tensor[i, pos] = True
|
|
1534
|
+
t_idx += 1
|
|
1535
|
+
|
|
1536
|
+
return input_ids, attention_mask, target_tensor, predict_tensor
|
|
1537
|
+
|
|
1538
|
+
# ── Fine-tuning tokenization ──────────────────────────────────────────
|
|
1539
|
+
|
|
1540
|
+
def tokenize_for_finetune(
|
|
1541
|
+
self,
|
|
1542
|
+
walk_nodes: List[str],
|
|
1543
|
+
walk_edge_types: List[str],
|
|
1544
|
+
dst_node_id: str,
|
|
1545
|
+
edge_type: str,
|
|
1546
|
+
indexid2msg: Dict[str, list],
|
|
1547
|
+
mode: str = "cls",
|
|
1548
|
+
dst_walk_nodes: List[str] = None,
|
|
1549
|
+
dst_walk_edge_types: List[str] = None,
|
|
1550
|
+
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
|
1551
|
+
"""Tokenize a walk for fine-tuning (CLS or LP mode).
|
|
1552
|
+
|
|
1553
|
+
CLS: src_walk + edge + dst_walk + [CLS] -> classify at [CLS] position
|
|
1554
|
+
LP: src_walk + edge + [MASK]... -> predict masked destination tokens
|
|
1555
|
+
|
|
1556
|
+
dst_walk_nodes / dst_walk_edge_types: when provided (CLS mode only),
|
|
1557
|
+
the backward walk ending at dst is tokenized and appended after the
|
|
1558
|
+
edge token. The dst node itself is the last node in this walk, so its
|
|
1559
|
+
tokens are naturally the final context before [CLS]. When absent the
|
|
1560
|
+
behaviour falls back to bare dst identity tokens.
|
|
1561
|
+
|
|
1562
|
+
Truncation is applied from the LEFT so that the target token(s) at the
|
|
1563
|
+
end of the sequence are always preserved.
|
|
1564
|
+
"""
|
|
1565
|
+
src_ctx_ids, _, _ = self.tokenize_walk(walk_nodes, walk_edge_types, indexid2msg)
|
|
1566
|
+
src_ctx_ids.extend(self.tokenize_edge(edge_type))
|
|
1567
|
+
|
|
1568
|
+
if mode == "cls":
|
|
1569
|
+
if dst_walk_nodes and len(dst_walk_nodes) > 1:
|
|
1570
|
+
dst_ctx_ids, _, _ = self.tokenize_walk(
|
|
1571
|
+
dst_walk_nodes, dst_walk_edge_types, indexid2msg
|
|
1572
|
+
)
|
|
1573
|
+
else:
|
|
1574
|
+
# Fallback: bare dst identity tokens
|
|
1575
|
+
if dst_node_id in indexid2msg:
|
|
1576
|
+
dst_type, dst_label = indexid2msg[dst_node_id]
|
|
1577
|
+
dst_ctx_ids = self.tokenize_node(dst_type, dst_label)
|
|
1578
|
+
else:
|
|
1579
|
+
dst_ctx_ids = []
|
|
1580
|
+
|
|
1581
|
+
token_ids = src_ctx_ids + dst_ctx_ids + [self.cls_id]
|
|
1582
|
+
target_mask = [False] * (len(src_ctx_ids) + len(dst_ctx_ids)) + [True]
|
|
1583
|
+
|
|
1584
|
+
elif mode == "lp":
|
|
1585
|
+
if dst_node_id in indexid2msg:
|
|
1586
|
+
dst_type, dst_label = indexid2msg[dst_node_id]
|
|
1587
|
+
dst_tokens = self.tokenize_node(dst_type, dst_label)
|
|
1588
|
+
else:
|
|
1589
|
+
dst_tokens = []
|
|
1590
|
+
|
|
1591
|
+
token_ids = src_ctx_ids + [self.mask_id] * len(dst_tokens)
|
|
1592
|
+
target_mask = [False] * len(src_ctx_ids) + [True] * len(dst_tokens)
|
|
1593
|
+
|
|
1594
|
+
else:
|
|
1595
|
+
raise ValueError(f"Unknown finetune mode: {mode}")
|
|
1596
|
+
|
|
1597
|
+
# Truncate from the LEFT to always preserve the target at the end
|
|
1598
|
+
if len(token_ids) > self.max_seq_len:
|
|
1599
|
+
excess = len(token_ids) - self.max_seq_len
|
|
1600
|
+
token_ids = token_ids[excess:]
|
|
1601
|
+
target_mask = target_mask[excess:]
|
|
1602
|
+
|
|
1603
|
+
return (
|
|
1604
|
+
torch.tensor(token_ids, dtype=torch.long),
|
|
1605
|
+
torch.ones(len(token_ids), dtype=torch.bool),
|
|
1606
|
+
torch.tensor(target_mask, dtype=torch.bool),
|
|
1607
|
+
)
|
|
1608
|
+
|
|
1609
|
+
def tokenize_for_edge_scoring(
|
|
1610
|
+
self,
|
|
1611
|
+
walk_nodes: List[str],
|
|
1612
|
+
walk_edge_types: List[str],
|
|
1613
|
+
dst_node_id: str,
|
|
1614
|
+
edge_type: str,
|
|
1615
|
+
indexid2msg: Dict[str, list],
|
|
1616
|
+
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
|
1617
|
+
"""Tokenize walk + masked edge + visible destination for edge-type scoring.
|
|
1618
|
+
|
|
1619
|
+
The edge token is masked; the model must predict it given the walk
|
|
1620
|
+
context and the (visible) destination node.
|
|
1621
|
+
|
|
1622
|
+
Returns:
|
|
1623
|
+
input_ids: [L] token IDs with edge masked
|
|
1624
|
+
attention_mask: [L] all True
|
|
1625
|
+
edge_mask: [L] True at masked edge position(s)
|
|
1626
|
+
edge_target_ids: [L] true edge token IDs at masked positions, -100 elsewhere
|
|
1627
|
+
"""
|
|
1628
|
+
token_ids, _, _ = self.tokenize_walk(walk_nodes, walk_edge_types, indexid2msg)
|
|
1629
|
+
|
|
1630
|
+
edge_tokens = self.tokenize_edge(edge_type)
|
|
1631
|
+
edge_mask = [False] * len(token_ids)
|
|
1632
|
+
edge_target_ids = [-100] * len(token_ids)
|
|
1633
|
+
|
|
1634
|
+
# Mask the edge token(s)
|
|
1635
|
+
for tok in edge_tokens:
|
|
1636
|
+
edge_mask.append(True)
|
|
1637
|
+
edge_target_ids.append(tok)
|
|
1638
|
+
token_ids.append(self.mask_id)
|
|
1639
|
+
|
|
1640
|
+
# Append visible destination
|
|
1641
|
+
if dst_node_id in indexid2msg:
|
|
1642
|
+
dst_type, dst_label = indexid2msg[dst_node_id]
|
|
1643
|
+
dst_tokens = self.tokenize_node(dst_type, dst_label)
|
|
1644
|
+
token_ids.extend(dst_tokens)
|
|
1645
|
+
edge_mask.extend([False] * len(dst_tokens))
|
|
1646
|
+
edge_target_ids.extend([-100] * len(dst_tokens))
|
|
1647
|
+
|
|
1648
|
+
# Truncate
|
|
1649
|
+
if len(token_ids) > self.max_seq_len:
|
|
1650
|
+
token_ids = token_ids[: self.max_seq_len]
|
|
1651
|
+
edge_mask = edge_mask[: self.max_seq_len]
|
|
1652
|
+
edge_target_ids = edge_target_ids[: self.max_seq_len]
|
|
1653
|
+
|
|
1654
|
+
return (
|
|
1655
|
+
torch.tensor(token_ids, dtype=torch.long),
|
|
1656
|
+
torch.ones(len(token_ids), dtype=torch.bool),
|
|
1657
|
+
torch.tensor(edge_mask, dtype=torch.bool),
|
|
1658
|
+
torch.tensor(edge_target_ids, dtype=torch.long),
|
|
1659
|
+
)
|