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,114 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
from gensim.models import Word2Vec
|
|
4
|
+
|
|
5
|
+
from pidsmaker.tokenization import fit_tokenizer
|
|
6
|
+
from pidsmaker.utils.utils import (
|
|
7
|
+
get_all_files_from_folders,
|
|
8
|
+
get_indexid2msg,
|
|
9
|
+
log,
|
|
10
|
+
log_tqdm,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def tokenize_corpus(corpus, indexid2msg, tokenizer):
|
|
15
|
+
"""Tokenizes walks given as lines of comma-separated node ids.
|
|
16
|
+
Empty tokens are dropped: nodes with an empty label add no word to the walk."""
|
|
17
|
+
tokenized_corpus = []
|
|
18
|
+
for line in corpus:
|
|
19
|
+
line = line.strip()
|
|
20
|
+
tokenized_line = []
|
|
21
|
+
for node in line.split(","):
|
|
22
|
+
node_type, node_label = indexid2msg[node]
|
|
23
|
+
tokenized_line.extend(t for t in tokenizer.tokenize(node_label, node_type) if t)
|
|
24
|
+
tokenized_corpus.append(tokenized_line)
|
|
25
|
+
return tokenized_corpus
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def train_word2vec(corpus, model_save_path, cfg):
|
|
29
|
+
emb_dim = cfg.featurization.emb_dim
|
|
30
|
+
window_size = cfg.featurization.temporal_rw.window_size
|
|
31
|
+
min_count = cfg.featurization.temporal_rw.min_count
|
|
32
|
+
use_skip_gram = cfg.featurization.temporal_rw.use_skip_gram
|
|
33
|
+
num_workers = cfg.featurization.temporal_rw.wv_workers
|
|
34
|
+
epochs = cfg.featurization.epochs
|
|
35
|
+
compute_loss = cfg.featurization.temporal_rw.compute_loss
|
|
36
|
+
negative = cfg.featurization.temporal_rw.negative
|
|
37
|
+
SEED = cfg.featurization.seed
|
|
38
|
+
|
|
39
|
+
model = Word2Vec(
|
|
40
|
+
corpus,
|
|
41
|
+
vector_size=emb_dim,
|
|
42
|
+
window=window_size,
|
|
43
|
+
min_count=min_count,
|
|
44
|
+
sg=use_skip_gram,
|
|
45
|
+
workers=num_workers,
|
|
46
|
+
epochs=1,
|
|
47
|
+
compute_loss=compute_loss,
|
|
48
|
+
negative=negative,
|
|
49
|
+
seed=SEED,
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
epoch_loss = model.get_latest_training_loss()
|
|
53
|
+
log_every = max(1, epochs // 10) # About 10 lines of logs
|
|
54
|
+
if log_every == 1:
|
|
55
|
+
log(f"epoch 1/{epochs} loss {epoch_loss:.1f}")
|
|
56
|
+
|
|
57
|
+
for epoch in range(epochs - 1):
|
|
58
|
+
model.train(corpus, epochs=1, total_examples=len(corpus), compute_loss=compute_loss)
|
|
59
|
+
epoch_loss = model.get_latest_training_loss()
|
|
60
|
+
if (epoch + 2) % log_every == 0 or epoch + 2 == epochs:
|
|
61
|
+
log(f"epoch {epoch + 2}/{epochs} loss {epoch_loss:.1f}")
|
|
62
|
+
|
|
63
|
+
model.init_sims(replace=True)
|
|
64
|
+
model.save(os.path.join(model_save_path, "trw_word2vec.model"))
|
|
65
|
+
log(f"Save word2vec to {os.path.join(model_save_path, 'trw_word2vec.model')}")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def update_word2vec(corpus, model_save_path, cfg):
|
|
69
|
+
epochs = cfg.featurization.epochs
|
|
70
|
+
compute_loss = cfg.featurization.temporal_rw.compute_loss
|
|
71
|
+
|
|
72
|
+
log(f"Loading word2vec from {model_save_path}")
|
|
73
|
+
model = Word2Vec.load(os.path.join(model_save_path, "trw_word2vec.model"))
|
|
74
|
+
model.build_vocab(corpus, update=True)
|
|
75
|
+
|
|
76
|
+
for epoch in range(epochs):
|
|
77
|
+
model.train(corpus, epochs=1, total_examples=len(corpus), compute_loss=compute_loss)
|
|
78
|
+
epoch_loss = model.get_latest_training_loss()
|
|
79
|
+
if (epoch + 1) % max(1, epochs // 10) == 0 or epoch + 1 == epochs:
|
|
80
|
+
log(f"epoch {epoch + 1}/{epochs} loss {epoch_loss:.1f}")
|
|
81
|
+
|
|
82
|
+
model.init_sims(replace=True)
|
|
83
|
+
model.save(os.path.join(model_save_path, "trw_word2vec.model"))
|
|
84
|
+
log(f"Save word2vec to {os.path.join(model_save_path, 'trw_word2vec.model')}")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def main(cfg):
|
|
88
|
+
model_save_path = cfg.featurization._model_dir
|
|
89
|
+
os.makedirs(model_save_path, exist_ok=True)
|
|
90
|
+
|
|
91
|
+
log(f"Building TRW based word2vec model and save model to {model_save_path}")
|
|
92
|
+
|
|
93
|
+
log("Get indexid2msg from database...")
|
|
94
|
+
indexid2msg = get_indexid2msg(cfg)
|
|
95
|
+
|
|
96
|
+
# Walks run over all splits, so the tokenizer is fitted on the labels of all nodes
|
|
97
|
+
tokenizer = fit_tokenizer(cfg, [tuple(msg) for msg in indexid2msg.values()])
|
|
98
|
+
|
|
99
|
+
corpus_base_dir = cfg.featurization.temporal_rw._random_walk_corpus_dir
|
|
100
|
+
corpus_folders = ["train", "val", "test", "unused"]
|
|
101
|
+
corpus_file_list = get_all_files_from_folders(corpus_base_dir, corpus_folders)
|
|
102
|
+
for i in log_tqdm(
|
|
103
|
+
list(range(len(corpus_file_list))), desc="Train Word2Vec based on TRW corpus:"
|
|
104
|
+
):
|
|
105
|
+
with open(corpus_file_list[i], "r") as f:
|
|
106
|
+
corpus = f.readlines()
|
|
107
|
+
log(f"\n{len(corpus)} lines read from {corpus_file_list[i]}")
|
|
108
|
+
|
|
109
|
+
tokenized_corpus = tokenize_corpus(corpus, indexid2msg, tokenizer)
|
|
110
|
+
|
|
111
|
+
if i == 0:
|
|
112
|
+
train_word2vec(corpus=tokenized_corpus, model_save_path=model_save_path, cfg=cfg)
|
|
113
|
+
else:
|
|
114
|
+
update_word2vec(corpus=tokenized_corpus, model_save_path=model_save_path, cfg=cfg)
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""Word2Vec-based node featurization.
|
|
2
|
+
|
|
3
|
+
Learns distributed representations of node labels using Word2Vec on random walks
|
|
4
|
+
through the provenance graph. Supports skip-gram and CBOW architectures for
|
|
5
|
+
capturing structural and semantic relationships between nodes.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
|
|
10
|
+
from gensim.models import Word2Vec
|
|
11
|
+
|
|
12
|
+
from pidsmaker.featurization.featurization_utils import (
|
|
13
|
+
get_corpus,
|
|
14
|
+
get_corpus_from_pretrain_datasets,
|
|
15
|
+
)
|
|
16
|
+
from pidsmaker.utils.utils import log
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def train_word2vec(corpus, cfg, model_save_path):
|
|
20
|
+
"""Train Word2Vec model on graph corpus (random walks).
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
corpus: List of walks (sequences of node labels)
|
|
24
|
+
cfg: Configuration with Word2Vec hyperparameters
|
|
25
|
+
model_save_path: Path to save trained model
|
|
26
|
+
|
|
27
|
+
Returns:
|
|
28
|
+
Word2Vec: Trained model
|
|
29
|
+
"""
|
|
30
|
+
if cfg._from_weights:
|
|
31
|
+
path = os.path.join(cfg._from_weights_path, "word2vec.model")
|
|
32
|
+
model = Word2Vec.load(path)
|
|
33
|
+
|
|
34
|
+
else:
|
|
35
|
+
emb_dim = cfg.featurization.emb_dim
|
|
36
|
+
window_size = cfg.featurization.word2vec.window_size
|
|
37
|
+
min_count = cfg.featurization.word2vec.min_count
|
|
38
|
+
use_skip_gram = cfg.featurization.word2vec.use_skip_gram
|
|
39
|
+
num_workers = cfg.featurization.word2vec.num_workers
|
|
40
|
+
epochs = cfg.featurization.epochs
|
|
41
|
+
compute_loss = cfg.featurization.word2vec.compute_loss
|
|
42
|
+
negative = cfg.featurization.word2vec.negative
|
|
43
|
+
seed = cfg.featurization.seed
|
|
44
|
+
|
|
45
|
+
model = Word2Vec(corpus,
|
|
46
|
+
vector_size=emb_dim,
|
|
47
|
+
window=window_size,
|
|
48
|
+
min_count=min_count,
|
|
49
|
+
sg=use_skip_gram,
|
|
50
|
+
workers=num_workers,
|
|
51
|
+
epochs=1,
|
|
52
|
+
compute_loss=compute_loss,
|
|
53
|
+
negative=negative,
|
|
54
|
+
seed=seed)
|
|
55
|
+
|
|
56
|
+
epoch_loss = model.get_latest_training_loss()
|
|
57
|
+
log_every = max(1, epochs // 10) # About 10 lines of logs
|
|
58
|
+
if log_every == 1:
|
|
59
|
+
log(f"epoch 1/{epochs} loss {epoch_loss:.1f}")
|
|
60
|
+
|
|
61
|
+
for epoch in range(epochs - 1):
|
|
62
|
+
model.train(corpus, epochs=1, total_examples=len(corpus), compute_loss=compute_loss)
|
|
63
|
+
epoch_loss = model.get_latest_training_loss()
|
|
64
|
+
if (epoch + 2) % log_every == 0 or epoch + 2 == epochs:
|
|
65
|
+
log(f"epoch {epoch + 2}/{epochs} loss {epoch_loss:.1f}")
|
|
66
|
+
|
|
67
|
+
model.init_sims(replace=True)
|
|
68
|
+
|
|
69
|
+
model.save(os.path.join(model_save_path, 'word2vec.model'), sep_limit=10**10) # force to save in a single file
|
|
70
|
+
log(f"Save word2vec to {os.path.join(model_save_path, 'word2vec.model')}")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def main(cfg):
|
|
74
|
+
model_save_path = cfg.featurization._model_dir
|
|
75
|
+
os.makedirs(model_save_path, exist_ok=True)
|
|
76
|
+
|
|
77
|
+
log("Loading and tokenizing corpus from database...")
|
|
78
|
+
pretrain_datasets = cfg.featurization.pretrain_datasets
|
|
79
|
+
multi_dataset_training = cfg.featurization.multi_dataset_training
|
|
80
|
+
|
|
81
|
+
if cfg._from_weights:
|
|
82
|
+
corpus = None
|
|
83
|
+
elif pretrain_datasets:
|
|
84
|
+
corpus = get_corpus_from_pretrain_datasets(cfg)
|
|
85
|
+
else:
|
|
86
|
+
corpus = get_corpus(cfg, gather_multi_dataset=multi_dataset_training)
|
|
87
|
+
|
|
88
|
+
log(f"Building feature word2vec model and save model to {model_save_path}")
|
|
89
|
+
train_word2vec(corpus=corpus, cfg=cfg, model_save_path=model_save_path)
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
from itertools import chain
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import pandas as pd
|
|
5
|
+
import torch
|
|
6
|
+
from gensim.models.doc2vec import TaggedDocument
|
|
7
|
+
|
|
8
|
+
from pidsmaker.config.pipeline import update_cfg_for_multi_dataset
|
|
9
|
+
from pidsmaker.tokenization import fit_tokenizer
|
|
10
|
+
from pidsmaker.utils.graph_store import load_graph_columns
|
|
11
|
+
from pidsmaker.utils.utils import (
|
|
12
|
+
get_all_graphs_for_dates,
|
|
13
|
+
get_indexid2msg,
|
|
14
|
+
get_split2nodes,
|
|
15
|
+
log,
|
|
16
|
+
log_tqdm,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def get_splits_to_train_featurization(cfg):
|
|
21
|
+
"""
|
|
22
|
+
Returns the splits on which train the embedding method.
|
|
23
|
+
"""
|
|
24
|
+
training_split = cfg.featurization.training_split.strip()
|
|
25
|
+
if training_split == "all":
|
|
26
|
+
return ["train", "val", "test"]
|
|
27
|
+
|
|
28
|
+
if training_split == "train":
|
|
29
|
+
return ["train"]
|
|
30
|
+
|
|
31
|
+
raise ValueError(f"Invalid training split {training_split}")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def get_corpus(cfg, doc2vec_format=False, gather_multi_dataset=False, label_fn=None):
|
|
35
|
+
"""
|
|
36
|
+
Returns the tokenized labels of all nodes within a specific split.
|
|
37
|
+
For training, the train split can be used to get only the corpus of train set.
|
|
38
|
+
Labels are tokenized with `featurization.tokenization`, fitted on these labels.
|
|
39
|
+
`label_fn(node_type, label)`, if given, replaces each label beforehand.
|
|
40
|
+
"""
|
|
41
|
+
splits = get_splits_to_train_featurization(cfg)
|
|
42
|
+
split2nodes = get_split2nodes(cfg, gather_multi_dataset=gather_multi_dataset)
|
|
43
|
+
nodes_to_include = set().union(*(split2nodes[split] for split in splits))
|
|
44
|
+
|
|
45
|
+
entries, tags = [], []
|
|
46
|
+
node_labels = set()
|
|
47
|
+
indexid2msg = get_indexid2msg(cfg, gather_multi_dataset=gather_multi_dataset)
|
|
48
|
+
|
|
49
|
+
for node, msg in indexid2msg.items():
|
|
50
|
+
node_type, node_label = msg
|
|
51
|
+
if label_fn is not None:
|
|
52
|
+
node_label = label_fn(node_type, node_label)
|
|
53
|
+
|
|
54
|
+
if (node in nodes_to_include) and (node_label not in node_labels):
|
|
55
|
+
node_labels.add(node_label)
|
|
56
|
+
tags.append(node)
|
|
57
|
+
entries.append((node_type, node_label))
|
|
58
|
+
|
|
59
|
+
tokenizer = fit_tokenizer(cfg, entries)
|
|
60
|
+
words = [tokenizer.tokenize(node_label, node_type) for node_type, node_label in entries]
|
|
61
|
+
|
|
62
|
+
if doc2vec_format:
|
|
63
|
+
words = [
|
|
64
|
+
TaggedDocument(words=word_list, tags=[str(tag)]) for word_list, tag in zip(words, tags)
|
|
65
|
+
]
|
|
66
|
+
|
|
67
|
+
return words
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def get_corpus_from_pretrain_datasets(cfg):
|
|
71
|
+
"""
|
|
72
|
+
Like get_corpus, but iterates over pretrain_datasets, merging tokenized node labels
|
|
73
|
+
from all of them. Deduplicates across datasets by (node_type, node_label).
|
|
74
|
+
"""
|
|
75
|
+
pretrain_datasets_str = cfg.featurization.pretrain_datasets
|
|
76
|
+
datasets = [d.strip() for d in pretrain_datasets_str.split(",")]
|
|
77
|
+
log(f"Loading corpus from pretrain_datasets: {datasets}")
|
|
78
|
+
|
|
79
|
+
splits = get_splits_to_train_featurization(cfg)
|
|
80
|
+
entries = []
|
|
81
|
+
seen_labels = set()
|
|
82
|
+
|
|
83
|
+
for dataset in datasets:
|
|
84
|
+
dataset_cfg, _ = update_cfg_for_multi_dataset(cfg, dataset)
|
|
85
|
+
split2nodes = get_split2nodes(dataset_cfg)
|
|
86
|
+
nodes_to_include = set().union(*(split2nodes[split] for split in splits))
|
|
87
|
+
indexid2msg = get_indexid2msg(dataset_cfg)
|
|
88
|
+
|
|
89
|
+
for node, msg in indexid2msg.items():
|
|
90
|
+
node_type, node_label = msg
|
|
91
|
+
label_key = (node_type, node_label)
|
|
92
|
+
if (node in nodes_to_include) and (label_key not in seen_labels):
|
|
93
|
+
seen_labels.add(label_key)
|
|
94
|
+
entries.append(label_key)
|
|
95
|
+
|
|
96
|
+
tokenizer = fit_tokenizer(cfg, entries)
|
|
97
|
+
all_words = [tokenizer.tokenize(node_label, node_type) for node_type, node_label in entries]
|
|
98
|
+
|
|
99
|
+
log(f"Pretrain corpus: {len(all_words)} unique (node_type, label) entries")
|
|
100
|
+
return all_words
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
# Number of document entries built at once from a graph (bounds the memory used per graph)
|
|
104
|
+
_ENTRIES_CHUNK = 1 << 22
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _neighbor_columns(path):
|
|
108
|
+
"""What `get_corpus_using_neighbors_features` reads from a stored graph G.
|
|
109
|
+
|
|
110
|
+
Returns (node_ids, node_entries, entries, bounds, succ): `node_ids` are the nodes in
|
|
111
|
+
`G.nodes` order, `entries` the distinct (node_type, label) pairs of the nodes, and
|
|
112
|
+
`entries[node_entries[i]]` the pair of node i. The neighbors of node i (`G.neighbors`, i.e.
|
|
113
|
+
its distinct successors in adjacency order) are the node positions
|
|
114
|
+
`succ[bounds[i]:bounds[i + 1]]`.
|
|
115
|
+
"""
|
|
116
|
+
cols = load_graph_columns(path)
|
|
117
|
+
if cols is None:
|
|
118
|
+
return _neighbor_columns_of_graph(torch.load(path))
|
|
119
|
+
node_ids = cols.node_ids
|
|
120
|
+
n = len(node_ids)
|
|
121
|
+
if n == 0:
|
|
122
|
+
return node_ids, np.zeros(0, dtype=np.int64), [], np.zeros(1, dtype=np.int64), cols.dst
|
|
123
|
+
type_codes, type_values = cols.node_attrs.factorize("node_type")
|
|
124
|
+
label_codes, label_values = cols.node_attrs.factorize("label")
|
|
125
|
+
num_labels = max(len(label_values), 1)
|
|
126
|
+
pair_codes, node_entries = np.unique(type_codes * num_labels + label_codes, return_inverse=True)
|
|
127
|
+
entries = [
|
|
128
|
+
(type_values[c // num_labels], label_values[c % num_labels]) for c in pair_codes.tolist()
|
|
129
|
+
]
|
|
130
|
+
|
|
131
|
+
# Edges are in `G.edges` order: grouped by source (in node order), then by destination (in
|
|
132
|
+
# adjacency order), so the parallel edges to a neighbor are consecutive
|
|
133
|
+
src, dst = cols.src, cols.dst
|
|
134
|
+
del cols
|
|
135
|
+
if len(src) > 1:
|
|
136
|
+
parallel = src[1:] == src[:-1]
|
|
137
|
+
parallel &= dst[1:] == dst[:-1]
|
|
138
|
+
if parallel.any():
|
|
139
|
+
first = np.empty(len(src), dtype=bool)
|
|
140
|
+
first[0] = True
|
|
141
|
+
np.logical_not(parallel, out=first[1:])
|
|
142
|
+
src, dst = src[first], dst[first]
|
|
143
|
+
del parallel
|
|
144
|
+
bounds = np.zeros(n + 1, dtype=np.int64)
|
|
145
|
+
np.cumsum(np.bincount(src, minlength=n), out=bounds[1:])
|
|
146
|
+
return node_ids, node_entries.reshape(-1), entries, bounds, dst
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _neighbor_columns_of_graph(G):
|
|
150
|
+
"""`_neighbor_columns` of a networkx graph (graphs stored as plain pickles)."""
|
|
151
|
+
node_ids = list(G.nodes())
|
|
152
|
+
pos = {node: i for i, node in enumerate(node_ids)}
|
|
153
|
+
index = {}
|
|
154
|
+
node_entries = np.fromiter(
|
|
155
|
+
(
|
|
156
|
+
index.setdefault((G.nodes[node]["node_type"], G.nodes[node]["label"]), len(index))
|
|
157
|
+
for node in node_ids
|
|
158
|
+
),
|
|
159
|
+
dtype=np.int64,
|
|
160
|
+
count=len(node_ids),
|
|
161
|
+
)
|
|
162
|
+
sizes, succ = [], []
|
|
163
|
+
for node in node_ids:
|
|
164
|
+
neighbors = [pos[neighbor] for neighbor in G.neighbors(node)]
|
|
165
|
+
sizes.append(len(neighbors))
|
|
166
|
+
succ.extend(neighbors)
|
|
167
|
+
bounds = np.zeros(len(node_ids) + 1, dtype=np.int64)
|
|
168
|
+
np.cumsum(sizes, out=bounds[1:])
|
|
169
|
+
return node_ids, node_entries, list(index), bounds, np.array(succ, dtype=np.int64)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _graph_documents(columns, new_nodes, entry_ids):
|
|
173
|
+
"""Documents of the nodes at positions `new_nodes` of a graph (given by its
|
|
174
|
+
`_neighbor_columns`): the (node_type, label) pair of the node, then those of its neighbors.
|
|
175
|
+
|
|
176
|
+
The pairs are given as IDs in `entry_ids`, which maps each pair to an ID and is extended with
|
|
177
|
+
the new pairs, numbered in order of first appearance in the documents. Yields chunks of
|
|
178
|
+
about _ENTRIES_CHUNK entries, as (entries, bounds): document i of a chunk is
|
|
179
|
+
`entries[bounds[i]:bounds[i + 1]]` (int32 IDs).
|
|
180
|
+
"""
|
|
181
|
+
_, node_entries, entries, bounds, succ = columns
|
|
182
|
+
local2id = np.full(len(entries), -1, dtype=np.int64)
|
|
183
|
+
num_neighbors = bounds[new_nodes + 1] - bounds[new_nodes]
|
|
184
|
+
doc_ends = np.cumsum(1 + num_neighbors)
|
|
185
|
+
start = 0
|
|
186
|
+
while start < len(new_nodes):
|
|
187
|
+
# Documents start:stop, of about _ENTRIES_CHUNK entries (at least one document)
|
|
188
|
+
offset = doc_ends[start - 1] if start else 0
|
|
189
|
+
stop = max(start + 1, int(np.searchsorted(doc_ends, offset + _ENTRIES_CHUNK, "right")))
|
|
190
|
+
nodes, counts = new_nodes[start:stop], num_neighbors[start:stop]
|
|
191
|
+
# Positions in `succ` of the neighbors of these nodes, in order
|
|
192
|
+
neighbor_starts = np.cumsum(counts) - counts
|
|
193
|
+
neighbors = np.arange(counts.sum()) + np.repeat(bounds[nodes] - neighbor_starts, counts)
|
|
194
|
+
doc_bounds = np.zeros(len(nodes) + 1, dtype=np.int64)
|
|
195
|
+
doc_bounds[1:] = doc_ends[start:stop] - offset
|
|
196
|
+
heads = np.zeros(doc_bounds[-1], dtype=bool)
|
|
197
|
+
heads[doc_bounds[:-1]] = True
|
|
198
|
+
seq = np.empty(len(heads), dtype=np.int64)
|
|
199
|
+
seq[heads] = node_entries[nodes]
|
|
200
|
+
seq[~heads] = node_entries[succ[neighbors]]
|
|
201
|
+
del heads, neighbors
|
|
202
|
+
for e in pd.unique(seq).tolist(): # in order of first appearance
|
|
203
|
+
if local2id[e] < 0:
|
|
204
|
+
local2id[e] = entry_ids.setdefault(entries[e], len(entry_ids))
|
|
205
|
+
yield local2id[seq].astype(np.int32), doc_bounds
|
|
206
|
+
start = stop
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
class NeighborsCorpus:
|
|
210
|
+
"""The documents of `get_corpus_using_neighbors_features`, stored compactly: each document
|
|
211
|
+
is kept as the IDs (int32) of its (node_type, label) entries, each distinct entry being
|
|
212
|
+
tokenized once, and its tokens are only concatenated when the corpus is iterated.
|
|
213
|
+
|
|
214
|
+
Iterating gives the same documents as the list returned before (same tokens, tags and
|
|
215
|
+
order), so Doc2Vec trained on it learns the same model; `len()` is the number of documents.
|
|
216
|
+
"""
|
|
217
|
+
|
|
218
|
+
def __init__(self, chunks, tags, entry_tokens, doc2vec_format):
|
|
219
|
+
self.chunks = chunks # (entries, bounds) of consecutive documents
|
|
220
|
+
self.tags = tags
|
|
221
|
+
self.entry_tokens = entry_tokens
|
|
222
|
+
self.doc2vec_format = doc2vec_format
|
|
223
|
+
|
|
224
|
+
def __len__(self):
|
|
225
|
+
return len(self.tags)
|
|
226
|
+
|
|
227
|
+
def __iter__(self):
|
|
228
|
+
tokens_of = self.entry_tokens.__getitem__
|
|
229
|
+
tags = iter(self.tags)
|
|
230
|
+
for entries, bounds in self.chunks:
|
|
231
|
+
bounds = bounds.tolist()
|
|
232
|
+
for i in range(len(bounds) - 1):
|
|
233
|
+
doc_entries = entries[bounds[i] : bounds[i + 1]].tolist()
|
|
234
|
+
words = list(chain.from_iterable(map(tokens_of, doc_entries)))
|
|
235
|
+
if self.doc2vec_format:
|
|
236
|
+
yield TaggedDocument(words=words, tags=[next(tags)])
|
|
237
|
+
else:
|
|
238
|
+
yield words
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
# Used in Rcaid
|
|
242
|
+
def get_corpus_using_neighbors_features(cfg, doc2vec_format=False):
|
|
243
|
+
"""
|
|
244
|
+
Same but also adds the tokens of neighbors in the final tokens: the document of each node
|
|
245
|
+
(in the graphs of the training dates, the first time it appears) is the (node_type, label)
|
|
246
|
+
pairs of the node and of its neighbors (`G.neighbors`), tokenized.
|
|
247
|
+
|
|
248
|
+
The graphs are read one at a time, and the documents are returned as a `NeighborsCorpus`
|
|
249
|
+
(4 bytes per (node_type, label) entry of a document) instead of a list of token lists.
|
|
250
|
+
"""
|
|
251
|
+
splits = get_splits_to_train_featurization(cfg)
|
|
252
|
+
dates = list(chain.from_iterable([getattr(cfg.dataset, f"{split}_dates") for split in splits]))
|
|
253
|
+
sorted_paths = get_all_graphs_for_dates(cfg.transformation._graphs_dir, dates)
|
|
254
|
+
|
|
255
|
+
# Ordered deduplication of the entries keeps the fitting of trainable tokenizers deterministic
|
|
256
|
+
chunks, tags, entry_ids = [], [], {}
|
|
257
|
+
nodes = set()
|
|
258
|
+
for path in log_tqdm(sorted_paths, desc="Get corpus with neighbors"):
|
|
259
|
+
columns = _neighbor_columns(path)
|
|
260
|
+
node_ids = columns[0]
|
|
261
|
+
new_nodes = [i for i, node in enumerate(node_ids) if node not in nodes]
|
|
262
|
+
nodes.update(node_ids)
|
|
263
|
+
tags.extend(node_ids[i] for i in new_nodes)
|
|
264
|
+
new_nodes = np.array(new_nodes, dtype=np.int64)
|
|
265
|
+
chunks.extend(_graph_documents(columns, new_nodes, entry_ids))
|
|
266
|
+
del columns, node_ids, new_nodes
|
|
267
|
+
del nodes
|
|
268
|
+
|
|
269
|
+
entries = list(entry_ids)
|
|
270
|
+
del entry_ids
|
|
271
|
+
tokenizer = fit_tokenizer(cfg, entries)
|
|
272
|
+
entry_tokens = [tokenizer.tokenize(label, node_type) for node_type, label in entries]
|
|
273
|
+
del entries
|
|
274
|
+
|
|
275
|
+
return NeighborsCorpus(chunks, tags, entry_tokens, doc2vec_format)
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import csv
|
|
2
|
+
import os
|
|
3
|
+
from typing import Literal
|
|
4
|
+
|
|
5
|
+
import torch
|
|
6
|
+
|
|
7
|
+
from pidsmaker.utils.utils import (
|
|
8
|
+
gen_darpa_adj_files,
|
|
9
|
+
gen_darpa_rw_file,
|
|
10
|
+
get_all_graphs_for_dates,
|
|
11
|
+
log,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def preprocess_split(split: Literal["train", "val", "test"], dates: list[str], cfg):
|
|
16
|
+
# Concatenates all files from all folders from this set and flattens in a single list
|
|
17
|
+
base_dir = cfg.transformation._graphs_dir
|
|
18
|
+
num_walks = cfg.featurization.alacarte.num_walks
|
|
19
|
+
|
|
20
|
+
sorted_paths = get_all_graphs_for_dates(base_dir, dates)
|
|
21
|
+
|
|
22
|
+
g = []
|
|
23
|
+
graph_info = open(f"{cfg.featurization.alacarte._random_walk_dir}/graph_info.csv", "w")
|
|
24
|
+
writer = csv.writer(graph_info)
|
|
25
|
+
random_walks_file = os.path.join(
|
|
26
|
+
cfg.featurization.alacarte._random_walk_corpus_dir, f"{split}.csv"
|
|
27
|
+
)
|
|
28
|
+
random_walks_file_fd = open(random_walks_file, "w")
|
|
29
|
+
adjacency_path = os.path.join(cfg.featurization.alacarte._random_walk_dir, f"{split}-adj")
|
|
30
|
+
|
|
31
|
+
corpus_file = os.path.join(
|
|
32
|
+
cfg.featurization.alacarte._random_walk_dir, f"{split}_set_corpus.csv"
|
|
33
|
+
)
|
|
34
|
+
corpus_file_fd = open(corpus_file, "w")
|
|
35
|
+
|
|
36
|
+
for path in sorted_paths:
|
|
37
|
+
file = path.split("/")[-1]
|
|
38
|
+
adjacency_file = os.path.join(adjacency_path, f"{split}-{file}.csv")
|
|
39
|
+
os.makedirs(adjacency_path, exist_ok=True)
|
|
40
|
+
|
|
41
|
+
log(f"load file: {path}")
|
|
42
|
+
graph = torch.load(path)
|
|
43
|
+
gen_darpa_adj_files(graph, adjacency_file)
|
|
44
|
+
g.append(graph)
|
|
45
|
+
writer.writerow([adjacency_file, len(graph.nodes)])
|
|
46
|
+
|
|
47
|
+
gen_darpa_rw_file(
|
|
48
|
+
walk_len=cfg.featurization.alacarte.walk_length,
|
|
49
|
+
corpus_fd=corpus_file_fd,
|
|
50
|
+
adjfilename=adjacency_file,
|
|
51
|
+
overall_fd=random_walks_file_fd,
|
|
52
|
+
num_walks=num_walks,
|
|
53
|
+
)
|
|
54
|
+
graph_info.close()
|
|
55
|
+
random_walks_file_fd.close()
|
|
56
|
+
corpus_file_fd.close()
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def main(cfg):
|
|
60
|
+
|
|
61
|
+
os.makedirs(cfg.featurization.alacarte._random_walk_dir, exist_ok=True)
|
|
62
|
+
os.makedirs(cfg.featurization.alacarte._random_walk_corpus_dir, exist_ok=True)
|
|
63
|
+
|
|
64
|
+
preprocess_split(split="train", dates=cfg.dataset.train_dates, cfg=cfg)
|
|
65
|
+
preprocess_split(split="val", dates=cfg.dataset.val_dates, cfg=cfg)
|
|
66
|
+
preprocess_split(split="test", dates=cfg.dataset.test_dates, cfg=cfg)
|