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,267 @@
|
|
|
1
|
+
"""OCR-APT anomalous-subgraph triage (arXiv:2510.15188, Sec 5.2, Algorithm 1)."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
import os
|
|
5
|
+
from collections import defaultdict
|
|
6
|
+
|
|
7
|
+
import networkx as nx
|
|
8
|
+
import numpy as np
|
|
9
|
+
import pandas as pd
|
|
10
|
+
import scipy.sparse as sp
|
|
11
|
+
import torch
|
|
12
|
+
|
|
13
|
+
from pidsmaker.utils.labelling import get_ground_truth
|
|
14
|
+
from pidsmaker.utils.dataset_utils import get_node_to_path_and_type
|
|
15
|
+
from pidsmaker.utils.loss_files import is_loss_file, read_losses
|
|
16
|
+
from pidsmaker.utils.utils import get_split_to_files, listdir_sorted, log
|
|
17
|
+
|
|
18
|
+
# Seed-eligible node types
|
|
19
|
+
SHORT_TYPES = {"process", "flow", "net", "netflowobject", "file", "module",
|
|
20
|
+
"netflow", "subject"}
|
|
21
|
+
SEVERITY_ORDER = ["Negligible", "Minor", "Moderate", "Significant", "Critical"]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _classify(score):
|
|
25
|
+
if score <= 1:
|
|
26
|
+
return "Negligible"
|
|
27
|
+
if score <= 10:
|
|
28
|
+
return "Minor"
|
|
29
|
+
if score <= 100:
|
|
30
|
+
return "Moderate"
|
|
31
|
+
if score <= 1000:
|
|
32
|
+
return "Significant"
|
|
33
|
+
return "Critical"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _node_type_order(nt):
|
|
37
|
+
low = str(nt).lower()
|
|
38
|
+
if low in ("flow", "net", "netflowobject", "netflow"):
|
|
39
|
+
return 1
|
|
40
|
+
if low.split("_")[-1] == "process" or low == "subject":
|
|
41
|
+
return 2
|
|
42
|
+
if low.split("_")[0] == "file":
|
|
43
|
+
return 3
|
|
44
|
+
return 4
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _load_graphs(cfg):
|
|
48
|
+
base_dir = cfg.transformation._graphs_dir
|
|
49
|
+
split_to_files = get_split_to_files(cfg, base_dir)
|
|
50
|
+
graphs = {}
|
|
51
|
+
for split, paths in split_to_files.items():
|
|
52
|
+
graphs[split] = [torch.load(p, weights_only=False) for p in paths]
|
|
53
|
+
log(f" [{split}] loaded {len(graphs[split])} graph files")
|
|
54
|
+
return graphs
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _best_epoch(cfg):
|
|
58
|
+
in_dir = cfg.evaluation._precision_recall_dir
|
|
59
|
+
stats_files = [f for f in os.listdir(in_dir) if f.startswith("stats_") and f.endswith(".pth")]
|
|
60
|
+
if not stats_files:
|
|
61
|
+
raise FileNotFoundError(f"No stats_*.pth found under {in_dir}. Run evaluation first.")
|
|
62
|
+
best_mcc, best_epoch = float("-inf"), None
|
|
63
|
+
for f in stats_files:
|
|
64
|
+
model_epoch_dir = f[len("stats_"):-len(".pth")]
|
|
65
|
+
stats = torch.load(os.path.join(in_dir, f), weights_only=False)
|
|
66
|
+
mcc = stats.get("mcc", float("-inf"))
|
|
67
|
+
if isinstance(mcc, float) and math.isnan(mcc):
|
|
68
|
+
mcc = float("-inf") # NaN mcc still counts as a candidate, just the worst one
|
|
69
|
+
if best_epoch is None or mcc > best_mcc:
|
|
70
|
+
best_mcc, best_epoch = mcc, model_epoch_dir
|
|
71
|
+
return best_epoch
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _train_reference_range_by_type(cfg, best_epoch, node_to_type):
|
|
75
|
+
train_dir = os.path.join(cfg.training._edge_losses_dir, "train", best_epoch)
|
|
76
|
+
if not os.path.isdir(train_dir):
|
|
77
|
+
return {}
|
|
78
|
+
dfs = [read_losses(os.path.join(train_dir, f)) for f in listdir_sorted(train_dir)
|
|
79
|
+
if is_loss_file(f)]
|
|
80
|
+
if not dfs:
|
|
81
|
+
return {}
|
|
82
|
+
df = pd.concat(dfs, ignore_index=True)
|
|
83
|
+
by_type = defaultdict(list)
|
|
84
|
+
for nid, loss in zip(df["node"], df["loss"]):
|
|
85
|
+
t = node_to_type.get(int(nid))
|
|
86
|
+
if t is not None:
|
|
87
|
+
by_type[t].append(loss)
|
|
88
|
+
return {t: (min(v), max(v)) for t, v in by_type.items()}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def main(cfg):
|
|
92
|
+
o = cfg.triage.ocrapt
|
|
93
|
+
max_edges = o.max_edges
|
|
94
|
+
|
|
95
|
+
best_epoch = _best_epoch(cfg)
|
|
96
|
+
scores_file = os.path.join(cfg.evaluation._precision_recall_dir, f"scores_{best_epoch}.pkl")
|
|
97
|
+
d = torch.load(scores_file, weights_only=False)
|
|
98
|
+
nodes = [int(n) for n in d["nodes"]]
|
|
99
|
+
pred_scores = np.asarray(d["pred_scores"], dtype=np.float64)
|
|
100
|
+
y_preds = np.asarray(d["y_preds"])
|
|
101
|
+
|
|
102
|
+
testing = set(nodes)
|
|
103
|
+
anomalies = {n for n, y in zip(nodes, y_preds) if y}
|
|
104
|
+
log(f" anomalies (node_evaluation, threshold_method=ocrapt): {len(anomalies)} / testing {len(testing)}")
|
|
105
|
+
|
|
106
|
+
pids2type = {nid: info["type"] for nid, info in get_node_to_path_and_type(cfg).items()}
|
|
107
|
+
range_by_type = _train_reference_range_by_type(cfg, best_epoch, pids2type)
|
|
108
|
+
|
|
109
|
+
node_types = np.array([pids2type.get(n) for n in nodes])
|
|
110
|
+
prob = np.zeros(len(nodes), dtype=np.float64)
|
|
111
|
+
for t, (lo, hi) in range_by_type.items():
|
|
112
|
+
mask = node_types == t
|
|
113
|
+
if not mask.any() or hi <= lo:
|
|
114
|
+
continue
|
|
115
|
+
prob[mask] = np.clip((pred_scores[mask] - lo) / (hi - lo), 0.0, 1.0)
|
|
116
|
+
prob_by_pid = dict(zip(nodes, prob.tolist()))
|
|
117
|
+
score_by_pid = dict(zip(nodes, pred_scores.tolist()))
|
|
118
|
+
|
|
119
|
+
gt_nids, _, _ = get_ground_truth(cfg)
|
|
120
|
+
malicious = set(int(n) for n in gt_nids) & testing
|
|
121
|
+
log(f" malicious (GT in test): {len(malicious)}")
|
|
122
|
+
|
|
123
|
+
# load graphs
|
|
124
|
+
graphs_by_split = _load_graphs(cfg)
|
|
125
|
+
subgraph_obj = nx.MultiDiGraph()
|
|
126
|
+
rows, cols, all_nodes = [], [], set()
|
|
127
|
+
for split, graphs in graphs_by_split.items():
|
|
128
|
+
is_test = split == "test"
|
|
129
|
+
for g in graphs:
|
|
130
|
+
for u, v, attr in g.edges(data=True):
|
|
131
|
+
u, v = int(u), int(v)
|
|
132
|
+
all_nodes.add(u); all_nodes.add(v)
|
|
133
|
+
rows.append(u); cols.append(v)
|
|
134
|
+
if is_test and u in testing and v in testing and (u in anomalies or v in anomalies):
|
|
135
|
+
subgraph_obj.add_edge(u, v, action=attr.get("label", "NA"))
|
|
136
|
+
subgraph_obj.add_nodes_from(anomalies)
|
|
137
|
+
del graphs_by_split
|
|
138
|
+
log(f" subgraph_obj: {subgraph_obj.number_of_nodes()} nodes, "
|
|
139
|
+
f"{subgraph_obj.number_of_edges()} edges")
|
|
140
|
+
|
|
141
|
+
# full undirected adjacency for 2-hop
|
|
142
|
+
node_list = sorted(all_nodes)
|
|
143
|
+
idx = {n: i for i, n in enumerate(node_list)}
|
|
144
|
+
N = len(node_list)
|
|
145
|
+
r = np.fromiter((idx[x] for x in rows), dtype=np.int64, count=len(rows))
|
|
146
|
+
c = np.fromiter((idx[x] for x in cols), dtype=np.int64, count=len(cols))
|
|
147
|
+
A = sp.csr_matrix((np.ones(len(r), np.float32), (r, c)), shape=(N, N))
|
|
148
|
+
A = (A + A.T).tocsr()
|
|
149
|
+
del rows, cols, r, c
|
|
150
|
+
|
|
151
|
+
# subgraph construction
|
|
152
|
+
correlated = set()
|
|
153
|
+
|
|
154
|
+
def filt(neighbours, visited):
|
|
155
|
+
s = neighbours & anomalies
|
|
156
|
+
if o.correlate_anomalous_once:
|
|
157
|
+
s = s - correlated
|
|
158
|
+
return s - visited
|
|
159
|
+
|
|
160
|
+
def sample_by_edge_type(sg):
|
|
161
|
+
df = nx.to_pandas_edgelist(sg, edge_key="ekey")
|
|
162
|
+
actions = df["action"].unique().tolist()
|
|
163
|
+
w = {}
|
|
164
|
+
for et in actions:
|
|
165
|
+
n_et = len(df[df["action"] == et])
|
|
166
|
+
w[et] = int(n_et / len(df) * max_edges) if n_et > int(max_edges / len(actions)) else int(n_et)
|
|
167
|
+
sample = pd.concat([df.loc[df["action"] == et].sample(w[et], random_state=0) for et in actions])
|
|
168
|
+
edges = [tuple(e) for e in sample[["source", "target", "ekey"]].values]
|
|
169
|
+
sampled = sg.edge_subgraph(edges).copy()
|
|
170
|
+
out = [sampled.subgraph(n).copy() for n in nx.weakly_connected_components(sampled) if len(n) > 1]
|
|
171
|
+
sg.remove_nodes_from(set(sampled.nodes()))
|
|
172
|
+
out.extend([sg.subgraph(n).copy() for n in nx.weakly_connected_components(sg)
|
|
173
|
+
if len(n) > 1 and 0 < sg.subgraph(n).number_of_edges() <= max_edges])
|
|
174
|
+
return out
|
|
175
|
+
|
|
176
|
+
def partition(big):
|
|
177
|
+
comms = nx.community.louvain_communities(big, resolution=1, seed=0)
|
|
178
|
+
tmp = [big.subgraph(n).copy() for n in comms if len(n) >= o.min_nodes]
|
|
179
|
+
tmp = [s for s in tmp if s.number_of_edges() > 2]
|
|
180
|
+
if not tmp:
|
|
181
|
+
tmp = [big]
|
|
182
|
+
res = []
|
|
183
|
+
for s in tmp:
|
|
184
|
+
res.extend(sample_by_edge_type(s) if s.number_of_edges() > max_edges else [s])
|
|
185
|
+
return res
|
|
186
|
+
|
|
187
|
+
def expand(seed):
|
|
188
|
+
conn = {n for n, _ in subgraph_obj.in_edges(seed) if n != seed}
|
|
189
|
+
conn.update({n for _, n in subgraph_obj.out_edges(seed) if n != seed})
|
|
190
|
+
if not conn:
|
|
191
|
+
yield None; return
|
|
192
|
+
nodes_ = {seed}
|
|
193
|
+
nodes_ |= filt(conn, {seed})
|
|
194
|
+
visited = {seed} | nodes_
|
|
195
|
+
if o.num_hops >= 1:
|
|
196
|
+
for cn in sorted(conn):
|
|
197
|
+
nb = {n for n, _ in subgraph_obj.in_edges(cn)}
|
|
198
|
+
a1 = filt(nb, visited)
|
|
199
|
+
nb = {n for _, n in subgraph_obj.out_edges(cn)}
|
|
200
|
+
a1 |= filt(nb, visited)
|
|
201
|
+
if a1:
|
|
202
|
+
nodes_ |= a1; nodes_.add(cn); visited |= nodes_
|
|
203
|
+
if len(nodes_) >= o.min_nodes:
|
|
204
|
+
sg = subgraph_obj.subgraph(nodes_).copy()
|
|
205
|
+
lst = partition(sg) if (sg.number_of_edges() > max_edges and max_edges != 0) else [sg]
|
|
206
|
+
for s in lst:
|
|
207
|
+
correlated.update(s.nodes())
|
|
208
|
+
yield s
|
|
209
|
+
else:
|
|
210
|
+
yield None
|
|
211
|
+
|
|
212
|
+
def remove_identical(lst):
|
|
213
|
+
rm = set()
|
|
214
|
+
for i1, s1 in enumerate(lst):
|
|
215
|
+
for i2, s2 in enumerate(lst):
|
|
216
|
+
if i1 != i2 and i2 not in rm and s1.number_of_nodes() == s2.number_of_nodes() \
|
|
217
|
+
and s1.number_of_edges() == s2.number_of_edges():
|
|
218
|
+
if nx.to_pandas_edgelist(s1, edge_key="ekey").equals(
|
|
219
|
+
nx.to_pandas_edgelist(s2, edge_key="ekey")):
|
|
220
|
+
rm.add(i1); break
|
|
221
|
+
return [s for i, s in enumerate(lst) if i not in rm]
|
|
222
|
+
|
|
223
|
+
# top-K per type by score, then sort by percentile severity
|
|
224
|
+
init_disc = {next(iter(comp)) for comp in nx.weakly_connected_components(subgraph_obj) if len(comp) == 1}
|
|
225
|
+
init_corr = [a for a in anomalies if a not in init_disc]
|
|
226
|
+
by_type = defaultdict(list)
|
|
227
|
+
for a in init_corr:
|
|
228
|
+
by_type[pids2type.get(a, "?")].append(a)
|
|
229
|
+
seeds = []
|
|
230
|
+
for t, members in by_type.items():
|
|
231
|
+
if str(t).split("_")[-1].lower() not in SHORT_TYPES:
|
|
232
|
+
continue
|
|
233
|
+
members.sort(key=lambda a: score_by_pid.get(a, 0.0), reverse=True)
|
|
234
|
+
seeds.extend(members[: o.top_k])
|
|
235
|
+
seeds.sort(key=lambda a: (-prob_by_pid.get(a, 0.0), _node_type_order(pids2type.get(a, "?"))))
|
|
236
|
+
n_mal_seed = sum(1 for s in seeds if s in malicious)
|
|
237
|
+
log(f" seeds: {len(seeds)} ({n_mal_seed} malicious)")
|
|
238
|
+
|
|
239
|
+
subgraphs = []
|
|
240
|
+
unvisited = set(init_corr)
|
|
241
|
+
for s in seeds:
|
|
242
|
+
subgraphs.extend([sg for sg in expand(s) if sg is not None])
|
|
243
|
+
unvisited -= correlated
|
|
244
|
+
if not unvisited:
|
|
245
|
+
break
|
|
246
|
+
if o.remove_duplicated_subgraph:
|
|
247
|
+
subgraphs = remove_identical(subgraphs)
|
|
248
|
+
log(f" constructed {len(subgraphs)} subgraphs, correlated {len(correlated & anomalies)} anomalies")
|
|
249
|
+
|
|
250
|
+
# severity filter
|
|
251
|
+
keep_levels = set(SEVERITY_ORDER[SEVERITY_ORDER.index(o.abnormality_level):])
|
|
252
|
+
def sev(sg):
|
|
253
|
+
return float(sum(prob_by_pid.get(n, 0.0) for n in (set(sg.nodes()) & anomalies)))
|
|
254
|
+
kept = [sg for sg in subgraphs if _classify(sev(sg)) in keep_levels]
|
|
255
|
+
mp = set()
|
|
256
|
+
for sg in kept:
|
|
257
|
+
mp |= set(sg.nodes())
|
|
258
|
+
mp &= testing
|
|
259
|
+
log(f" kept {len(kept)}/{len(subgraphs)} severe subgraphs, predicted-malicious={len(mp)}")
|
|
260
|
+
|
|
261
|
+
# 2-hop-relaxed node metric
|
|
262
|
+
from pidsmaker.detection.evaluation_methods.evaluation_utils import two_hop_relaxed_metrics
|
|
263
|
+
GP = np.zeros(N, dtype=bool); GP[[idx[n] for n in malicious if n in idx]] = True
|
|
264
|
+
MP = np.zeros(N, dtype=bool); MP[[idx[n] for n in mp if n in idx]] = True
|
|
265
|
+
stats = two_hop_relaxed_metrics(MP, GP, A)
|
|
266
|
+
stats["subgraphs_kept"] = len(kept)
|
|
267
|
+
return stats
|
|
File without changes
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
"""Generic artifact caching system for pipeline tasks.
|
|
2
|
+
|
|
3
|
+
Provides deterministic hash-based caching for any intermediate artifacts
|
|
4
|
+
(tokenizers, walk corpora, embeddings, etc.) with automatic parameter tracking.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import hashlib
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import pickle
|
|
11
|
+
from typing import Any, Callable, Dict, Optional
|
|
12
|
+
|
|
13
|
+
from pidsmaker.utils.utils import log
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ArtifactCache:
|
|
17
|
+
"""Hash-based cache for pipeline artifacts with automatic versioning.
|
|
18
|
+
|
|
19
|
+
Example:
|
|
20
|
+
# Cache a walk corpus
|
|
21
|
+
cache = ArtifactCache(name="walk_corpus", output_dir=model_dir)
|
|
22
|
+
corpus_params = {'walk_length': 10, 'num_walks': 5, 'datasets': ['train']}
|
|
23
|
+
|
|
24
|
+
corpus = cache.load(params=corpus_params)
|
|
25
|
+
if corpus is None:
|
|
26
|
+
corpus = build_corpus(...)
|
|
27
|
+
cache.save(data=corpus, params=corpus_params)
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
def __init__(self, name: str, output_dir: str, hash_length: int = 12):
|
|
31
|
+
"""Initialize artifact cache.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
name: Artifact name (e.g., 'tokenizer', 'walk_corpus')
|
|
35
|
+
output_dir: Directory to store cached artifacts
|
|
36
|
+
hash_length: Length of hash string (default 12)
|
|
37
|
+
"""
|
|
38
|
+
self.name = name
|
|
39
|
+
self.output_dir = output_dir
|
|
40
|
+
self.hash_length = hash_length
|
|
41
|
+
os.makedirs(output_dir, exist_ok=True)
|
|
42
|
+
|
|
43
|
+
def compute_hash(self, params: Dict[str, Any]) -> str:
|
|
44
|
+
"""Compute deterministic hash from parameters.
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
params: Dictionary of parameters that define this artifact
|
|
48
|
+
|
|
49
|
+
Returns:
|
|
50
|
+
Hexadecimal hash string of specified length
|
|
51
|
+
"""
|
|
52
|
+
# Ensure deterministic ordering
|
|
53
|
+
params_str = json.dumps(params, sort_keys=True)
|
|
54
|
+
full_hash = hashlib.md5(params_str.encode()).hexdigest()
|
|
55
|
+
return full_hash[:self.hash_length]
|
|
56
|
+
|
|
57
|
+
def get_paths(self, cache_hash: str) -> tuple[str, str]:
|
|
58
|
+
"""Get artifact and config file paths for a given hash.
|
|
59
|
+
|
|
60
|
+
Args:
|
|
61
|
+
cache_hash: Hash string identifying the artifact
|
|
62
|
+
|
|
63
|
+
Returns:
|
|
64
|
+
(artifact_path, config_path)
|
|
65
|
+
"""
|
|
66
|
+
artifact_path = os.path.join(self.output_dir, f"{self.name}_{cache_hash}.pkl")
|
|
67
|
+
config_path = os.path.join(self.output_dir, f"{self.name}_config_{cache_hash}.json")
|
|
68
|
+
return artifact_path, config_path
|
|
69
|
+
|
|
70
|
+
def load(
|
|
71
|
+
self,
|
|
72
|
+
params: Dict[str, Any],
|
|
73
|
+
loader_fn: Optional[Callable[[str], Any]] = None
|
|
74
|
+
) -> Optional[Any]:
|
|
75
|
+
"""Try to load cached artifact if it exists.
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
params: Parameters that define this artifact
|
|
79
|
+
loader_fn: Optional custom loader function. If None, uses pickle.
|
|
80
|
+
Function signature: (file_path: str) -> artifact
|
|
81
|
+
|
|
82
|
+
Returns:
|
|
83
|
+
Loaded artifact if cache exists, None otherwise
|
|
84
|
+
"""
|
|
85
|
+
cache_hash = self.compute_hash(params)
|
|
86
|
+
artifact_path, config_path = self.get_paths(cache_hash)
|
|
87
|
+
|
|
88
|
+
if not os.path.exists(artifact_path) or not os.path.exists(config_path):
|
|
89
|
+
return None
|
|
90
|
+
|
|
91
|
+
try:
|
|
92
|
+
log(f"Found cached {self.name}: {artifact_path}")
|
|
93
|
+
|
|
94
|
+
# Load artifact using custom loader or pickle
|
|
95
|
+
if loader_fn:
|
|
96
|
+
artifact = loader_fn(artifact_path)
|
|
97
|
+
else:
|
|
98
|
+
with open(artifact_path, 'rb') as f:
|
|
99
|
+
artifact = pickle.load(f)
|
|
100
|
+
|
|
101
|
+
log(f"Loaded cached {self.name} (hash: {cache_hash})")
|
|
102
|
+
return artifact
|
|
103
|
+
|
|
104
|
+
except Exception as e:
|
|
105
|
+
log(f"Failed to load cached {self.name}: {e}")
|
|
106
|
+
return None
|
|
107
|
+
|
|
108
|
+
def save(
|
|
109
|
+
self,
|
|
110
|
+
data: Any,
|
|
111
|
+
params: Dict[str, Any],
|
|
112
|
+
saver_fn: Optional[Callable[[Any, str], None]] = None
|
|
113
|
+
) -> str:
|
|
114
|
+
"""Save artifact with its configuration.
|
|
115
|
+
|
|
116
|
+
Args:
|
|
117
|
+
data: Artifact data to save
|
|
118
|
+
params: Parameters that define this artifact
|
|
119
|
+
saver_fn: Optional custom saver function. If None, uses pickle.
|
|
120
|
+
Function signature: (artifact, file_path: str) -> None
|
|
121
|
+
|
|
122
|
+
Returns:
|
|
123
|
+
Cache hash identifying the saved artifact
|
|
124
|
+
"""
|
|
125
|
+
cache_hash = self.compute_hash(params)
|
|
126
|
+
artifact_path, config_path = self.get_paths(cache_hash)
|
|
127
|
+
|
|
128
|
+
# Save artifact using custom saver or pickle
|
|
129
|
+
if saver_fn:
|
|
130
|
+
saver_fn(data, artifact_path)
|
|
131
|
+
else:
|
|
132
|
+
with open(artifact_path, 'wb') as f:
|
|
133
|
+
pickle.dump(data, f)
|
|
134
|
+
|
|
135
|
+
log(f"Saved {self.name} cache: {artifact_path}")
|
|
136
|
+
|
|
137
|
+
# Save configuration for debugging/reproducibility
|
|
138
|
+
with open(config_path, 'w') as f:
|
|
139
|
+
json.dump(params, f, indent=2)
|
|
140
|
+
|
|
141
|
+
log(f"Saved {self.name} config: {config_path}")
|
|
142
|
+
|
|
143
|
+
return cache_hash
|
|
144
|
+
|
|
145
|
+
def exists(self, params: Dict[str, Any]) -> bool:
|
|
146
|
+
"""Check if cached artifact exists for given parameters.
|
|
147
|
+
|
|
148
|
+
Args:
|
|
149
|
+
params: Parameters that define this artifact
|
|
150
|
+
|
|
151
|
+
Returns:
|
|
152
|
+
True if cache exists, False otherwise
|
|
153
|
+
"""
|
|
154
|
+
cache_hash = self.compute_hash(params)
|
|
155
|
+
artifact_path, config_path = self.get_paths(cache_hash)
|
|
156
|
+
return os.path.exists(artifact_path) and os.path.exists(config_path)
|
|
157
|
+
|
|
158
|
+
def clear(self, params: Optional[Dict[str, Any]] = None):
|
|
159
|
+
"""Clear cached artifacts.
|
|
160
|
+
|
|
161
|
+
Args:
|
|
162
|
+
params: If provided, only clears artifact with these params.
|
|
163
|
+
If None, clears all artifacts with this name.
|
|
164
|
+
"""
|
|
165
|
+
if params:
|
|
166
|
+
cache_hash = self.compute_hash(params)
|
|
167
|
+
artifact_path, config_path = self.get_paths(cache_hash)
|
|
168
|
+
for path in [artifact_path, config_path]:
|
|
169
|
+
if os.path.exists(path):
|
|
170
|
+
os.remove(path)
|
|
171
|
+
log(f"Cleared cache: {path}")
|
|
172
|
+
else:
|
|
173
|
+
# Clear all artifacts with this name
|
|
174
|
+
for file in os.listdir(self.output_dir):
|
|
175
|
+
if file.startswith(f"{self.name}_"):
|
|
176
|
+
path = os.path.join(self.output_dir, file)
|
|
177
|
+
os.remove(path)
|
|
178
|
+
log(f"Cleared cache: {path}")
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def extract_cache_params(cfg_section, param_keys: list[str]) -> Dict[str, Any]:
|
|
182
|
+
"""Extract caching parameters from config section.
|
|
183
|
+
|
|
184
|
+
Useful helper to extract only cache-relevant params from a config object.
|
|
185
|
+
|
|
186
|
+
Args:
|
|
187
|
+
cfg_section: Config section (e.g., cfg.featurization.pretrained.walks)
|
|
188
|
+
param_keys: List of parameter names to extract
|
|
189
|
+
|
|
190
|
+
Returns:
|
|
191
|
+
Dictionary of extracted parameters
|
|
192
|
+
"""
|
|
193
|
+
params = {}
|
|
194
|
+
for key in param_keys:
|
|
195
|
+
if hasattr(cfg_section, key):
|
|
196
|
+
value = getattr(cfg_section, key)
|
|
197
|
+
# Convert to JSON-serializable types
|
|
198
|
+
if hasattr(value, 'tolist'): # numpy array
|
|
199
|
+
value = value.tolist()
|
|
200
|
+
params[key] = value
|
|
201
|
+
return params
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def config_to_params(cfg_section, exclude_private: bool = True) -> Dict[str, Any]:
|
|
205
|
+
"""Automatically extract all parameters from a config section.
|
|
206
|
+
|
|
207
|
+
Dynamically extracts all attributes from a config object, filtering out
|
|
208
|
+
private attributes (starting with _) and methods by default.
|
|
209
|
+
|
|
210
|
+
Args:
|
|
211
|
+
cfg_section: Config section (e.g., cfg.featurization.pretrained.walks)
|
|
212
|
+
exclude_private: If True, exclude attributes starting with '_'
|
|
213
|
+
|
|
214
|
+
Returns:
|
|
215
|
+
Dictionary of all extracted parameters
|
|
216
|
+
|
|
217
|
+
Example:
|
|
218
|
+
# Instead of manually building params dict:
|
|
219
|
+
corpus_params = {
|
|
220
|
+
'walk_length': cfg.corpus.walk_length,
|
|
221
|
+
'num_walks': cfg.corpus.num_walks,
|
|
222
|
+
...
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
# Simply do:
|
|
226
|
+
corpus_params = config_to_params(cfg.featurization.pretrained.walks)
|
|
227
|
+
"""
|
|
228
|
+
params = {}
|
|
229
|
+
|
|
230
|
+
# Try to use config's built-in conversion if available (OmegaConf, etc.)
|
|
231
|
+
if hasattr(cfg_section, 'to_dict'):
|
|
232
|
+
return cfg_section.to_dict()
|
|
233
|
+
|
|
234
|
+
# Fallback: extract attributes manually
|
|
235
|
+
for key in dir(cfg_section):
|
|
236
|
+
# Skip private attributes and methods
|
|
237
|
+
if exclude_private and key.startswith('_'):
|
|
238
|
+
continue
|
|
239
|
+
|
|
240
|
+
# Skip methods and special attributes
|
|
241
|
+
try:
|
|
242
|
+
value = getattr(cfg_section, key)
|
|
243
|
+
if callable(value):
|
|
244
|
+
continue
|
|
245
|
+
|
|
246
|
+
# Convert to JSON-serializable types
|
|
247
|
+
if hasattr(value, 'tolist'): # numpy array
|
|
248
|
+
value = value.tolist()
|
|
249
|
+
elif hasattr(value, 'to_dict'): # nested config
|
|
250
|
+
value = value.to_dict()
|
|
251
|
+
|
|
252
|
+
params[key] = value
|
|
253
|
+
except (AttributeError, TypeError):
|
|
254
|
+
continue
|
|
255
|
+
|
|
256
|
+
return params
|