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,1742 @@
|
|
|
1
|
+
"""Data utilities for graph batching and temporal data handling.
|
|
2
|
+
|
|
3
|
+
Provides custom PyTorch Geometric data structures and utilities for:
|
|
4
|
+
- Temporal graph data collation and batching
|
|
5
|
+
- Graph reindexing for mini-batch training
|
|
6
|
+
- TGN memory and neighbor sampling integration
|
|
7
|
+
- Multi-dataset handling and preprocessing
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import copy
|
|
11
|
+
import math
|
|
12
|
+
import os
|
|
13
|
+
import pickle
|
|
14
|
+
from collections import defaultdict
|
|
15
|
+
from functools import cached_property
|
|
16
|
+
|
|
17
|
+
import torch
|
|
18
|
+
import torch.nn.functional as F
|
|
19
|
+
from torch_geometric.data import Data, TemporalData
|
|
20
|
+
from torch_geometric.data.collate import collate
|
|
21
|
+
from torch_geometric.data.data import size_repr
|
|
22
|
+
from torch_geometric.data.temporal import prepare_idx
|
|
23
|
+
from torch_geometric.loader import TemporalDataLoader
|
|
24
|
+
|
|
25
|
+
try:
|
|
26
|
+
from torch_scatter import scatter
|
|
27
|
+
except ImportError:
|
|
28
|
+
# torch_scatter has no prebuilt wheels for some platforms (e.g. Apple Silicon, Linux aarch64)
|
|
29
|
+
# and fails to compile with recent compilers. Only its "sum" and "mean" reductions are used,
|
|
30
|
+
# which torch_scatter implements in Python on top of `scatter_add_`: same code here, so that
|
|
31
|
+
# results are identical (including the accumulation into an existing `out`).
|
|
32
|
+
def _broadcast(src, other, dim):
|
|
33
|
+
if dim < 0:
|
|
34
|
+
dim = other.dim() + dim
|
|
35
|
+
if src.dim() == 1:
|
|
36
|
+
for _ in range(0, dim):
|
|
37
|
+
src = src.unsqueeze(0)
|
|
38
|
+
for _ in range(src.dim(), other.dim()):
|
|
39
|
+
src = src.unsqueeze(-1)
|
|
40
|
+
return src.expand(other.size())
|
|
41
|
+
|
|
42
|
+
def _scatter_sum(src, index, dim=-1, out=None, dim_size=None):
|
|
43
|
+
index = _broadcast(index, src, dim)
|
|
44
|
+
if out is None:
|
|
45
|
+
size = list(src.size())
|
|
46
|
+
if dim_size is not None:
|
|
47
|
+
size[dim] = dim_size
|
|
48
|
+
elif index.numel() == 0:
|
|
49
|
+
size[dim] = 0
|
|
50
|
+
else:
|
|
51
|
+
size[dim] = int(index.max()) + 1
|
|
52
|
+
out = torch.zeros(size, dtype=src.dtype, device=src.device)
|
|
53
|
+
return out.scatter_add_(dim, index, src)
|
|
54
|
+
|
|
55
|
+
def scatter(src, index, dim=-1, out=None, dim_size=None, reduce="sum"):
|
|
56
|
+
if reduce in ("sum", "add"):
|
|
57
|
+
return _scatter_sum(src, index, dim, out, dim_size)
|
|
58
|
+
if reduce != "mean":
|
|
59
|
+
raise NotImplementedError(f"reduce={reduce} requires torch_scatter")
|
|
60
|
+
out = _scatter_sum(src, index, dim, out, dim_size)
|
|
61
|
+
dim_size = out.size(dim)
|
|
62
|
+
index_dim = dim
|
|
63
|
+
if index_dim < 0:
|
|
64
|
+
index_dim = index_dim + src.dim()
|
|
65
|
+
if index.dim() <= index_dim:
|
|
66
|
+
index_dim = index.dim() - 1
|
|
67
|
+
ones = torch.ones(index.size(), dtype=src.dtype, device=src.device)
|
|
68
|
+
count = _scatter_sum(ones, index, index_dim, None, dim_size)
|
|
69
|
+
count[count < 1] = 1
|
|
70
|
+
count = _broadcast(count, out, dim)
|
|
71
|
+
if out.is_floating_point():
|
|
72
|
+
out.true_divide_(count)
|
|
73
|
+
else:
|
|
74
|
+
out.div_(count, rounding_mode="floor")
|
|
75
|
+
return out
|
|
76
|
+
|
|
77
|
+
from pidsmaker.config import update_cfg_for_multi_dataset
|
|
78
|
+
from pidsmaker.debug_tests import debug_test_batching
|
|
79
|
+
from pidsmaker.hetero import compute_hetero_features
|
|
80
|
+
from pidsmaker.tgn import LastNeighborLoader
|
|
81
|
+
from pidsmaker.utils.dataset_utils import (
|
|
82
|
+
get_node_map,
|
|
83
|
+
get_num_edge_type,
|
|
84
|
+
get_possible_events,
|
|
85
|
+
get_rel2id,
|
|
86
|
+
)
|
|
87
|
+
from pidsmaker.utils.utils import (
|
|
88
|
+
get_multi_datasets,
|
|
89
|
+
log,
|
|
90
|
+
log_dataset_stats,
|
|
91
|
+
log_tqdm,
|
|
92
|
+
ns_time_to_datetime_US,
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class CollatableTemporalData(TemporalData):
|
|
97
|
+
"""
|
|
98
|
+
We use this class instead of TemporalData in order to easily concatenate data
|
|
99
|
+
objects together without any batching behavior.
|
|
100
|
+
Normal TemporalData doesn't support edge_index so we define it here.
|
|
101
|
+
"""
|
|
102
|
+
|
|
103
|
+
def __init__(
|
|
104
|
+
self,
|
|
105
|
+
src=None,
|
|
106
|
+
dst=None,
|
|
107
|
+
t=None,
|
|
108
|
+
msg=None,
|
|
109
|
+
**kwargs,
|
|
110
|
+
):
|
|
111
|
+
super().__init__(src=src, dst=dst, t=t, msg=msg, **kwargs)
|
|
112
|
+
self.tgn_mode = False
|
|
113
|
+
|
|
114
|
+
def __inc__(self, key: str, value, *args, **kwargs):
|
|
115
|
+
if key == "original_edge_index": # used to retrieve original node IDs during evaluation
|
|
116
|
+
return 0
|
|
117
|
+
if "edge_index" in key or key in ["src", "dst", "reindexed_original_n_id_tgn"]:
|
|
118
|
+
if self.tgn_mode:
|
|
119
|
+
return torch.unique(self.n_id_tgn).numel()
|
|
120
|
+
return self.num_nodes
|
|
121
|
+
return 0
|
|
122
|
+
|
|
123
|
+
def __cat_dim__(self, key: str, value, *args, **kwargs):
|
|
124
|
+
return 1 if "edge_index" in key else 0
|
|
125
|
+
|
|
126
|
+
def __repr__(self) -> str:
|
|
127
|
+
cls = self.__class__.__name__
|
|
128
|
+
info = ", ".join([size_repr(k, v) for k, v in self._store.items()])
|
|
129
|
+
info += ", " + size_repr("edge_index", self.edge_index)
|
|
130
|
+
return f"{cls}({info})"
|
|
131
|
+
|
|
132
|
+
def index_select(self, idx):
|
|
133
|
+
""" "Indexing to handle (2, E) index attributes"""
|
|
134
|
+
idx = prepare_idx(idx)
|
|
135
|
+
data = copy.copy(self)
|
|
136
|
+
for key, value in data._store.items():
|
|
137
|
+
if not isinstance(value, torch.Tensor):
|
|
138
|
+
continue
|
|
139
|
+
if value.size(0) == self.num_events:
|
|
140
|
+
data[key] = value[idx]
|
|
141
|
+
elif value.ndim == 2 and value.size(1) == self.num_events and "index" in key:
|
|
142
|
+
data[key] = value[:, idx]
|
|
143
|
+
return data
|
|
144
|
+
|
|
145
|
+
@property
|
|
146
|
+
def num_nodes(self):
|
|
147
|
+
if "original_n_id" in self:
|
|
148
|
+
return self.original_n_id.numel()
|
|
149
|
+
return self.edge_index.unique().numel()
|
|
150
|
+
|
|
151
|
+
@cached_property
|
|
152
|
+
def node_type_argmax(self):
|
|
153
|
+
return self.node_type.max(dim=1).indices
|
|
154
|
+
|
|
155
|
+
@cached_property
|
|
156
|
+
def node_type_src_argmax(self):
|
|
157
|
+
return self.node_type_src.max(dim=1).indices
|
|
158
|
+
|
|
159
|
+
@cached_property
|
|
160
|
+
def edge_type_argmax(self):
|
|
161
|
+
return self.edge_type.max(dim=1).indices
|
|
162
|
+
|
|
163
|
+
@cached_property
|
|
164
|
+
def node_type_dst_argmax(self):
|
|
165
|
+
return self.node_type_dst.max(dim=1).indices
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def batch_to_device(data, device):
|
|
169
|
+
"""Returns a copy of `data` on `device`, leaving `data` untouched.
|
|
170
|
+
|
|
171
|
+
`Data.to()` is in-place: moving a CPU graph to the GPU and back to the CPU costs
|
|
172
|
+
two transfers per batch. Moving a shallow copy only costs the host-to-device one;
|
|
173
|
+
the GPU copy is released by the caching allocator once no longer referenced.
|
|
174
|
+
Tensors already on `device` are not copied.
|
|
175
|
+
|
|
176
|
+
Batches using a shared node feature table get their features rebuilt on `device`
|
|
177
|
+
(see `SharedNodeFeatures`).
|
|
178
|
+
"""
|
|
179
|
+
device = torch.device(device)
|
|
180
|
+
if device.type == "cuda":
|
|
181
|
+
if device.index is None: # `cuda:0` != `cuda`, so tensors on the GPU would be copied
|
|
182
|
+
device = torch.device("cuda", torch.cuda.current_device())
|
|
183
|
+
out = copy.copy(data)
|
|
184
|
+
tensors = {k: v for k, v in data.items() if isinstance(v, torch.Tensor) and v.device != device}
|
|
185
|
+
keys = [k for k, v in tensors.items() if v.device.type == "cpu"]
|
|
186
|
+
for k, v in zip(keys, _PACKED_TRANSFER([tensors[k] for k in keys], device)):
|
|
187
|
+
out[k] = v
|
|
188
|
+
for k, v in tensors.items(): # on another GPU
|
|
189
|
+
if v.device.type != "cpu":
|
|
190
|
+
out[k] = v.to(device, non_blocking=True)
|
|
191
|
+
else:
|
|
192
|
+
out = copy.copy(data).to(device, non_blocking=True)
|
|
193
|
+
if SHARED_FEATS_KEY in out:
|
|
194
|
+
shared = out[SHARED_FEATS_KEY]
|
|
195
|
+
del out[SHARED_FEATS_KEY]
|
|
196
|
+
shared.materialize(out, device)
|
|
197
|
+
return out
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
class _PackedTransfer:
|
|
201
|
+
"""Copies CPU tensors to the GPU at once: they are packed into a pinned buffer, copied with
|
|
202
|
+
a single transfer, and the GPU tensors are views of their bytes in the copied buffer.
|
|
203
|
+
|
|
204
|
+
A copy from pageable memory waits for the kernels queued before it, so moving the ~15
|
|
205
|
+
tensors of a batch one by one waited ~15 times for the GPU per batch. Two pinned buffers
|
|
206
|
+
are used in turn: one is filled while the transfer of the previous batch may be running."""
|
|
207
|
+
|
|
208
|
+
ALIGN = 16 # bytes, so that every tensor can be viewed with its dtype
|
|
209
|
+
|
|
210
|
+
def __init__(self):
|
|
211
|
+
self.buffers = [None, None]
|
|
212
|
+
self.events = [None, None]
|
|
213
|
+
self.turn = 0
|
|
214
|
+
|
|
215
|
+
def __call__(self, tensors, device):
|
|
216
|
+
if not tensors:
|
|
217
|
+
return []
|
|
218
|
+
tensors = [t.contiguous() for t in tensors]
|
|
219
|
+
offsets, total = [], 0
|
|
220
|
+
for t in tensors:
|
|
221
|
+
offsets.append(total)
|
|
222
|
+
nbytes = t.numel() * t.element_size()
|
|
223
|
+
total += (nbytes + self.ALIGN - 1) // self.ALIGN * self.ALIGN
|
|
224
|
+
|
|
225
|
+
i = self.turn
|
|
226
|
+
self.turn = 1 - i
|
|
227
|
+
if self.events[i] is not None:
|
|
228
|
+
self.events[i].synchronize() # the previous transfer from this buffer is done
|
|
229
|
+
if self.buffers[i] is None or self.buffers[i].numel() < total:
|
|
230
|
+
self.buffers[i] = torch.empty(int(total * 1.5) + 1024, dtype=torch.uint8).pin_memory()
|
|
231
|
+
staging = self.buffers[i]
|
|
232
|
+
# Single-threaded copies with numpy: `Tensor.copy_` splits copies across the intra-op
|
|
233
|
+
# threads, whose synchronization costs more than these small copies on a busy machine
|
|
234
|
+
staging_np = staging.numpy()
|
|
235
|
+
for t, off in zip(tensors, offsets):
|
|
236
|
+
n = t.numel() * t.element_size()
|
|
237
|
+
if n:
|
|
238
|
+
staging_np[off : off + n] = t.view(-1).view(torch.uint8).numpy()
|
|
239
|
+
|
|
240
|
+
packed = staging[:total].to(device, non_blocking=True)
|
|
241
|
+
if self.events[i] is None:
|
|
242
|
+
self.events[i] = torch.cuda.Event()
|
|
243
|
+
self.events[i].record()
|
|
244
|
+
|
|
245
|
+
out = []
|
|
246
|
+
for t, off in zip(tensors, offsets):
|
|
247
|
+
n = t.numel() * t.element_size()
|
|
248
|
+
out.append(packed[off : off + n].view(t.dtype).view(t.shape))
|
|
249
|
+
return out
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
_PACKED_TRANSFER = _PackedTransfer()
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
# Sorted original node IDs of the compacted node IDs (`batching.compact_node_ids`), or None
|
|
256
|
+
_ORIGINAL_NODE_IDS = None
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def set_original_node_ids(node_ids):
|
|
260
|
+
global _ORIGINAL_NODE_IDS
|
|
261
|
+
_ORIGINAL_NODE_IDS = node_ids
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def get_original_node_ids():
|
|
265
|
+
return _ORIGINAL_NODE_IDS
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def to_original_node_ids(ids):
|
|
269
|
+
"""Node IDs of the database of (compacted) node IDs `ids` (unchanged without compaction)."""
|
|
270
|
+
if _ORIGINAL_NODE_IDS is None:
|
|
271
|
+
return ids
|
|
272
|
+
return _ORIGINAL_NODE_IDS.to(ids.device)[ids.long()].to(ids.dtype)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def compact_node_ids(dataset_groups, shared=None):
|
|
276
|
+
"""Renumbers in place the `src` and `dst` of all graphs to the rank of their ID among the
|
|
277
|
+
sorted IDs of the nodes in the graphs (`batching.compact_node_ids`). The order of the nodes
|
|
278
|
+
is kept (sorting, `unique`, ... give the same results), while tensors indexed by node ID are
|
|
279
|
+
sized by the number of nodes in the graphs instead of the largest database ID.
|
|
280
|
+
|
|
281
|
+
Returns the sorted original IDs, also kept for `to_original_node_ids`.
|
|
282
|
+
"""
|
|
283
|
+
graphs = [data for group in dataset_groups for dataset in group for data in dataset]
|
|
284
|
+
node_ids = torch.cat([torch.cat([g.src, g.dst]).unique() for g in graphs]).unique()
|
|
285
|
+
for g in graphs:
|
|
286
|
+
g.src = torch.searchsorted(node_ids, g.src).to(g.src.dtype)
|
|
287
|
+
g.dst = torch.searchsorted(node_ids, g.dst).to(g.dst.dtype)
|
|
288
|
+
if shared is not None:
|
|
289
|
+
shared.node_row = shared.node_row[node_ids]
|
|
290
|
+
shared.num_nodes = len(node_ids)
|
|
291
|
+
set_original_node_ids(node_ids)
|
|
292
|
+
return node_ids
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def load_all_datasets(cfg, device, only_keep=None):
|
|
296
|
+
multi_dataset = cfg.batching.multi_dataset_training
|
|
297
|
+
shared = None
|
|
298
|
+
if _shared_node_features_supported(cfg):
|
|
299
|
+
try:
|
|
300
|
+
builder = _NodeTableBuilder()
|
|
301
|
+
path = cfg.feat_inference._edge_embeds_dir
|
|
302
|
+
train_data = [_load_data_list_shared(path, "train", cfg, builder)]
|
|
303
|
+
val_data = [_load_data_list_shared(path, "val", cfg, builder)]
|
|
304
|
+
test_data = [_load_data_list_shared(path, "test", cfg, builder)]
|
|
305
|
+
shared = SharedNodeFeatures(builder, cfg)
|
|
306
|
+
shared.has_edge_attrs = any("edge_attr_feats" in g for g in train_data[0][:1])
|
|
307
|
+
del builder
|
|
308
|
+
log(f"Node features stored once in a shared table ({shared.nbytes() / 1e9:.2f} GB)")
|
|
309
|
+
except _SharedFeaturesUnsupported as e:
|
|
310
|
+
log(f"Shared node feature table not used ({e}).")
|
|
311
|
+
shared = None
|
|
312
|
+
if shared is None:
|
|
313
|
+
train_data = load_data_set(cfg, split="train", multi_dataset=multi_dataset)
|
|
314
|
+
val_data = load_data_set(cfg, split="val", multi_dataset=multi_dataset)
|
|
315
|
+
test_data = load_data_set(cfg, split="test", multi_dataset=False)
|
|
316
|
+
|
|
317
|
+
if only_keep is not None:
|
|
318
|
+
train_data = train_data[:only_keep]
|
|
319
|
+
val_data = val_data[:only_keep]
|
|
320
|
+
test_data = test_data[:only_keep]
|
|
321
|
+
|
|
322
|
+
use_tgn_intra = (
|
|
323
|
+
"tgn_last_neighbor" in cfg.batching.intra_graph_batching.used_methods
|
|
324
|
+
)
|
|
325
|
+
|
|
326
|
+
if getattr(cfg.batching, "compact_node_ids", False):
|
|
327
|
+
node_ids = compact_node_ids([train_data, val_data, test_data], shared=shared)
|
|
328
|
+
log(f"Node IDs compacted: {len(node_ids)} nodes in the graphs, max ID {int(node_ids[-1])}")
|
|
329
|
+
else:
|
|
330
|
+
set_original_node_ids(None)
|
|
331
|
+
|
|
332
|
+
max_node = max(
|
|
333
|
+
max(data.src.max().item(), data.dst.max().item())
|
|
334
|
+
for dataset_group in [train_data, val_data, test_data]
|
|
335
|
+
for dataset in dataset_group
|
|
336
|
+
for data in dataset
|
|
337
|
+
) + 1
|
|
338
|
+
log(f"Max node in {cfg.dataset.name}: {max_node}")
|
|
339
|
+
|
|
340
|
+
graph_reindexer = GraphReindexer(
|
|
341
|
+
device=device,
|
|
342
|
+
num_nodes=max_node,
|
|
343
|
+
fix_buggy_graph_reindexer=cfg.batching.fix_buggy_graph_reindexer,
|
|
344
|
+
)
|
|
345
|
+
|
|
346
|
+
# Global batching (unique edge type batches, fixed-size edge length)
|
|
347
|
+
datasets = run_global_batching(train_data, val_data, test_data, cfg, device)
|
|
348
|
+
|
|
349
|
+
# full_data must be built AFTER global batching so its row count matches the
|
|
350
|
+
# edges actually fed into the TGN neighbor loader. The "minutes" batch_mode
|
|
351
|
+
# duplicates edges across overlapping sliding windows; building full_data
|
|
352
|
+
# from the pre-batched data would leave it shorter than the loader's e_id range.
|
|
353
|
+
full_data = None
|
|
354
|
+
if use_tgn_intra:
|
|
355
|
+
# Only the attributes gathered by `compute_tgn_graphs` are concatenated
|
|
356
|
+
edge_features = _edge_features_list(cfg)
|
|
357
|
+
keys = ["src", "dst", "edge_type"]
|
|
358
|
+
if "time_encoding" in edge_features:
|
|
359
|
+
keys.append("t")
|
|
360
|
+
if "msg" in edge_features:
|
|
361
|
+
keys.append("msg")
|
|
362
|
+
if "edge_attrs" in edge_features or "msg" in edge_features:
|
|
363
|
+
# Edge features of the TGN, and part of msg_tgn rebuilt from the shared table
|
|
364
|
+
keys.append("edge_attr_feats")
|
|
365
|
+
full_data = get_full_data(datasets, keys=keys)
|
|
366
|
+
|
|
367
|
+
# Intra graph batching (TGN 1024 batches, last neighbor loader)
|
|
368
|
+
datasets = run_intra_graph_batching(
|
|
369
|
+
datasets, full_data, device, max_node, cfg, graph_reindexer, shared=shared
|
|
370
|
+
)
|
|
371
|
+
del full_data
|
|
372
|
+
|
|
373
|
+
# Reindexing stuff (create node-level attributes)
|
|
374
|
+
datasets = run_reindexing_preprocessing(datasets, graph_reindexer, device, cfg, shared=shared)
|
|
375
|
+
|
|
376
|
+
# Inter graph batching (actual mini-batching of very small graphs)
|
|
377
|
+
datasets = run_inter_graph_batching(datasets, cfg)
|
|
378
|
+
|
|
379
|
+
if shared is not None:
|
|
380
|
+
for dataset in datasets:
|
|
381
|
+
for data_list in dataset:
|
|
382
|
+
for batch in data_list:
|
|
383
|
+
batch[SHARED_FEATS_KEY] = shared
|
|
384
|
+
|
|
385
|
+
train_data, val_data, test_data = datasets
|
|
386
|
+
return train_data, val_data, test_data, max_node
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
# Compact storage of the edge messages written by feat_inference (see `expand_compact_msg`)
|
|
390
|
+
COMPACT_MSG_KEYS = (
|
|
391
|
+
"msg_node_feats", # (N, F) features of each node of the graph: [node_type | node_emb]
|
|
392
|
+
"msg_src_row", # (E,) row of each edge's source in msg_node_feats
|
|
393
|
+
"msg_dst_row", # (E,) row of each edge's destination in msg_node_feats
|
|
394
|
+
"msg_edge_type_table", # (K + 1, T) one-hot of each edge type (last row: no type)
|
|
395
|
+
"msg_edge_type_row", # (E,) row of each edge's type in msg_edge_type_table
|
|
396
|
+
)
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def expand_compact_msg(data):
|
|
400
|
+
"""Rebuilds the (E, D) edge messages `msg` = [src_feats | edge_type | dst_feats] from
|
|
401
|
+
their compact storage, in place. Data saved with a materialized `msg` is left as is."""
|
|
402
|
+
if COMPACT_MSG_KEYS[0] not in data:
|
|
403
|
+
return data
|
|
404
|
+
node_feats, src_row, dst_row, etype_table, etype_row = (data[k] for k in COMPACT_MSG_KEYS)
|
|
405
|
+
data.msg = torch.cat(
|
|
406
|
+
[node_feats[src_row.long()], etype_table[etype_row.long()], node_feats[dst_row.long()]],
|
|
407
|
+
dim=1,
|
|
408
|
+
)
|
|
409
|
+
for k in COMPACT_MSG_KEYS:
|
|
410
|
+
del data[k]
|
|
411
|
+
return data
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def load_data_list(path, split, cfg):
|
|
415
|
+
data_list = []
|
|
416
|
+
for f in sorted(os.listdir(os.path.join(path, split))):
|
|
417
|
+
filepath = os.path.join(path, split, f)
|
|
418
|
+
data = expand_compact_msg(torch.load(filepath).to("cpu"))
|
|
419
|
+
data_list.append(data)
|
|
420
|
+
|
|
421
|
+
data_list = extract_msg_from_data(data_list, cfg)
|
|
422
|
+
return data_list
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def load_data_set(cfg, split: str, multi_dataset=False) -> list[CollatableTemporalData]:
|
|
426
|
+
"""
|
|
427
|
+
Returns a list of time window graphs for a given `split` (train/val/test set).
|
|
428
|
+
"""
|
|
429
|
+
if multi_dataset:
|
|
430
|
+
multi_datasets = get_multi_datasets(cfg)
|
|
431
|
+
all_data_lists = []
|
|
432
|
+
for dataset in multi_datasets:
|
|
433
|
+
updated_cfg, _ = update_cfg_for_multi_dataset(cfg, dataset)
|
|
434
|
+
path = updated_cfg.feat_inference._edge_embeds_dir
|
|
435
|
+
all_data_lists.append(load_data_list(path, split, cfg))
|
|
436
|
+
return all_data_lists
|
|
437
|
+
|
|
438
|
+
else:
|
|
439
|
+
path = cfg.feat_inference._edge_embeds_dir
|
|
440
|
+
return [load_data_list(path, split, cfg)]
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def get_selected_node_features(cfg) -> list[str]:
|
|
444
|
+
"""Node features (`batching.node_features`) actually used as GNN input.
|
|
445
|
+
|
|
446
|
+
Featurizations without embeddings (`only_type`, `only_ones`) have no `node_emb`, so it is
|
|
447
|
+
dropped. `only_ones` replaces every feature by ones. With `only_type`, the features that do
|
|
448
|
+
not need embeddings (e.g. `edges_distribution`) are kept, and `node_type` is the fallback
|
|
449
|
+
when nothing else is selected.
|
|
450
|
+
"""
|
|
451
|
+
method = cfg.featurization.used_method.strip()
|
|
452
|
+
if method == "only_ones":
|
|
453
|
+
return ["only_ones"]
|
|
454
|
+
feats = [f.strip() for f in cfg.batching.node_features.replace("-", ",").split(",") if f.strip()]
|
|
455
|
+
if method == "only_type":
|
|
456
|
+
feats = [f for f in feats if f != "node_emb"] or ["node_type"]
|
|
457
|
+
return feats
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def extract_msg_from_data(
|
|
461
|
+
data_set: list[CollatableTemporalData], cfg
|
|
462
|
+
) -> list[CollatableTemporalData]:
|
|
463
|
+
"""
|
|
464
|
+
Initializes the attributes of a `Data` object based on the `msg`
|
|
465
|
+
computed in previous tasks.
|
|
466
|
+
"""
|
|
467
|
+
emb_dim = cfg.featurization.emb_dim
|
|
468
|
+
method = cfg.featurization.used_method.strip()
|
|
469
|
+
only_type = method == "only_type"
|
|
470
|
+
only_ones = method == "only_ones"
|
|
471
|
+
# graph2vec embeds whole graphs (`graph_emb`), not nodes
|
|
472
|
+
if only_type or only_ones or method == "graph2vec" or emb_dim is None:
|
|
473
|
+
emb_dim = 0
|
|
474
|
+
node_type_dim = cfg.dataset.num_node_types
|
|
475
|
+
# msg holds the plain (possibly OpTC-consistent) edge types; triplet types are derived later
|
|
476
|
+
edge_type_dim = (
|
|
477
|
+
cfg.dataset.num_edge_types
|
|
478
|
+
if "edge_type_triplet" in cfg.batching.edge_features
|
|
479
|
+
else get_num_edge_type(cfg)
|
|
480
|
+
)
|
|
481
|
+
|
|
482
|
+
if method == "ocrapt_features":
|
|
483
|
+
# in-histogram + out-histogram (L2-normalized together) + idle min/max/avg,
|
|
484
|
+
# plus one extra dim each for the optional lifespan/cumulative-active-time
|
|
485
|
+
oc = cfg.featurization.ocrapt_features
|
|
486
|
+
emb_dim = 2 * edge_type_dim + 3 + int(oc.use_lifespan) + int(oc.use_cumulative_active_time)
|
|
487
|
+
|
|
488
|
+
selected_node_feats = get_selected_node_features(cfg)
|
|
489
|
+
|
|
490
|
+
msg_len = data_set[0].msg.shape[1]
|
|
491
|
+
expected_msg_len = (emb_dim * 2) + (node_type_dim * 2) + edge_type_dim
|
|
492
|
+
if msg_len != expected_msg_len:
|
|
493
|
+
raise ValueError(
|
|
494
|
+
f"The msg has an invalid shape, found {msg_len} instead of {expected_msg_len} (Is your num_edge_types correct?)"
|
|
495
|
+
)
|
|
496
|
+
|
|
497
|
+
field_to_size = {
|
|
498
|
+
"src_type": node_type_dim,
|
|
499
|
+
"src_emb": emb_dim,
|
|
500
|
+
"edge_type": edge_type_dim,
|
|
501
|
+
"dst_type": node_type_dim,
|
|
502
|
+
"dst_emb": emb_dim,
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
if "edges_distribution" in selected_node_feats:
|
|
506
|
+
distrib_scaling = (getattr(cfg.batching, "edges_distribution_scaling", None) or "max").strip()
|
|
507
|
+
max_num_nodes = max([torch.cat([g.src, g.dst]).max().item() for g in data_set]) + 1
|
|
508
|
+
x_distrib = torch.zeros(max_num_nodes, edge_type_dim * 2, dtype=torch.float)
|
|
509
|
+
|
|
510
|
+
edge_features = list(
|
|
511
|
+
map(lambda x: x.strip(), cfg.batching.edge_features.split(","))
|
|
512
|
+
)
|
|
513
|
+
if "edge_type_triplet" in edge_features:
|
|
514
|
+
possible_triplets = get_possible_triplets(cfg)
|
|
515
|
+
else:
|
|
516
|
+
possible_triplets = None
|
|
517
|
+
|
|
518
|
+
for g in data_set:
|
|
519
|
+
fields = {}
|
|
520
|
+
idx = 0
|
|
521
|
+
for field, size in field_to_size.items():
|
|
522
|
+
fields[field] = g.msg[:, idx : idx + size]
|
|
523
|
+
idx += size
|
|
524
|
+
|
|
525
|
+
# Selects only the node features we want
|
|
526
|
+
x_src, x_dst = [], []
|
|
527
|
+
for feat in selected_node_feats:
|
|
528
|
+
if feat == "node_emb":
|
|
529
|
+
x_src.append(fields["src_emb"])
|
|
530
|
+
x_dst.append(fields["dst_emb"])
|
|
531
|
+
|
|
532
|
+
elif feat == "node_type":
|
|
533
|
+
x_src.append(fields["src_type"])
|
|
534
|
+
x_dst.append(fields["dst_type"])
|
|
535
|
+
|
|
536
|
+
elif feat == "edges_distribution": # as in ThreaTrace
|
|
537
|
+
x_distrib.scatter_add_(
|
|
538
|
+
0, g.src.unsqueeze(1).expand(-1, edge_type_dim), fields["edge_type"]
|
|
539
|
+
)
|
|
540
|
+
x_distrib[:, edge_type_dim:].scatter_add_(
|
|
541
|
+
0, g.dst.unsqueeze(1).expand(-1, edge_type_dim), fields["edge_type"]
|
|
542
|
+
)
|
|
543
|
+
|
|
544
|
+
# Indexing copies the rows, scaled below. ThreaTrace uses the raw counts (`none`)
|
|
545
|
+
rows_src, rows_dst = x_distrib[g.src], x_distrib[g.dst]
|
|
546
|
+
if distrib_scaling == "max": # divided by the max count of the time window
|
|
547
|
+
max_count = x_distrib.max() + 1e-12
|
|
548
|
+
rows_src, rows_dst = rows_src / max_count, rows_dst / max_count
|
|
549
|
+
elif distrib_scaling == "log1p":
|
|
550
|
+
rows_src, rows_dst = torch.log1p(rows_src), torch.log1p(rows_dst)
|
|
551
|
+
|
|
552
|
+
x_src.append(rows_src)
|
|
553
|
+
x_dst.append(rows_dst)
|
|
554
|
+
|
|
555
|
+
x_distrib.fill_(0)
|
|
556
|
+
|
|
557
|
+
elif feat == "only_ones":
|
|
558
|
+
x_src.append(fields["src_type"].clone().fill_(1))
|
|
559
|
+
x_dst.append(fields["dst_type"].clone().fill_(1))
|
|
560
|
+
|
|
561
|
+
else:
|
|
562
|
+
raise ValueError(f"Node feature {feat} is invalid.")
|
|
563
|
+
|
|
564
|
+
x_src = torch.cat(x_src, dim=-1)
|
|
565
|
+
x_dst = torch.cat(x_dst, dim=-1)
|
|
566
|
+
|
|
567
|
+
if _msg_has_edge_type(cfg):
|
|
568
|
+
msg = torch.cat([x_src, x_dst, fields["edge_type"]], dim=-1)
|
|
569
|
+
else:
|
|
570
|
+
msg = torch.cat([x_src, x_dst], dim=-1)
|
|
571
|
+
|
|
572
|
+
# Edge attributes of the dataset (e.g. ports, protocols, logon types) are part of
|
|
573
|
+
# the message describing the event, and optionally used as edge features
|
|
574
|
+
edge_attrs = getattr(g, "edge_attr_feats", None)
|
|
575
|
+
if edge_attrs is not None:
|
|
576
|
+
msg = torch.cat([msg, edge_attrs], dim=-1)
|
|
577
|
+
fields["edge_attrs"] = edge_attrs
|
|
578
|
+
elif "edge_attrs" in edge_features:
|
|
579
|
+
raise ValueError(
|
|
580
|
+
f"Edge feature `edge_attrs` requires a dataset with edge attributes "
|
|
581
|
+
f"(none in {cfg.dataset.name})."
|
|
582
|
+
)
|
|
583
|
+
|
|
584
|
+
num_edge_types = get_num_edge_type(cfg)
|
|
585
|
+
edge_feats = build_edge_feats(fields, msg, edge_features, possible_triplets, num_edge_types)
|
|
586
|
+
|
|
587
|
+
if "edge_type_triplet" in edge_features:
|
|
588
|
+
edge_type = get_triplet_edge_types(
|
|
589
|
+
fields["src_type"],
|
|
590
|
+
fields["dst_type"],
|
|
591
|
+
fields["edge_type"],
|
|
592
|
+
possible_triplets,
|
|
593
|
+
num_edge_types,
|
|
594
|
+
)
|
|
595
|
+
else:
|
|
596
|
+
edge_type = fields["edge_type"]
|
|
597
|
+
|
|
598
|
+
g.x_src = x_src
|
|
599
|
+
g.x_dst = x_dst
|
|
600
|
+
g.edge_feats = edge_feats
|
|
601
|
+
# fields are views (slices) of g.msg. Clone them so that deleting
|
|
602
|
+
# g.msg actually frees the underlying storage.
|
|
603
|
+
g.edge_type = edge_type.clone()
|
|
604
|
+
g.node_type_src = fields["src_type"].clone()
|
|
605
|
+
g.node_type_dst = fields["dst_type"].clone()
|
|
606
|
+
|
|
607
|
+
if _needs_raw_msg(cfg):
|
|
608
|
+
g.msg = msg
|
|
609
|
+
else:
|
|
610
|
+
del g.msg
|
|
611
|
+
|
|
612
|
+
# NOTE: do not add edge_index as it is already within `CollatableTemporalData`
|
|
613
|
+
# g.edge_index = ...
|
|
614
|
+
|
|
615
|
+
return data_set
|
|
616
|
+
|
|
617
|
+
def _msg_has_edge_type(cfg):
|
|
618
|
+
"""Whether the edge messages `msg` = [src | dst | edge type] hold the edge type.
|
|
619
|
+
|
|
620
|
+
With `predict_edge_type`, the edge type is removed from the messages unless
|
|
621
|
+
`predict_edge_type.edge_type_in_msg` is set. The messages of an edge only reach the TGN
|
|
622
|
+
after its type is predicted (memory update, and edge features of the next batches), so
|
|
623
|
+
keeping it does not leak the predicted type: Kairos' messages are (src, edge type, dst).
|
|
624
|
+
"""
|
|
625
|
+
if "predict_edge_type" not in cfg.training.decoder.used_methods:
|
|
626
|
+
return True
|
|
627
|
+
return bool(cfg.training.decoder.predict_edge_type.edge_type_in_msg)
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
def _edge_features_list(cfg):
|
|
631
|
+
return [x.strip() for x in cfg.batching.edge_features.split(",")]
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
def _needs_raw_msg(cfg):
|
|
635
|
+
"""Whether the edge-level `msg` is consumed downstream.
|
|
636
|
+
|
|
637
|
+
Only the TGN encoder reads it: as raw message of the TGN memory, or as edge
|
|
638
|
+
feature (`msg_tgn`). It also sizes the TGN modules when `msg` is an edge feature.
|
|
639
|
+
"""
|
|
640
|
+
use_tgn = "tgn" in cfg.training.encoder.used_methods
|
|
641
|
+
if not use_tgn:
|
|
642
|
+
return False
|
|
643
|
+
return cfg.training.encoder.tgn.use_memory or "msg" in _edge_features_list(cfg)
|
|
644
|
+
|
|
645
|
+
|
|
646
|
+
def get_possible_triplets(cfg):
|
|
647
|
+
entity_map = get_node_map(cfg, from_zero=True)
|
|
648
|
+
event_map = get_rel2id(cfg, from_zero=True)
|
|
649
|
+
possible_events = get_possible_events(cfg)
|
|
650
|
+
|
|
651
|
+
possible_triplets = [
|
|
652
|
+
[entity_map[src_type], entity_map[dst_type], event_map[event]]
|
|
653
|
+
for (src_type, dst_type), events in possible_events.items()
|
|
654
|
+
for event in events
|
|
655
|
+
]
|
|
656
|
+
return torch.tensor(possible_triplets, dtype=torch.long)
|
|
657
|
+
|
|
658
|
+
|
|
659
|
+
def get_triplet_edge_types(src_type, dst_type, edge_type, possible_triplets, num_edge_types):
|
|
660
|
+
triplets = torch.stack(
|
|
661
|
+
(src_type.max(dim=1).indices, dst_type.max(dim=1).indices, edge_type.max(dim=1).indices),
|
|
662
|
+
dim=1,
|
|
663
|
+
)
|
|
664
|
+
matches = (triplets.unsqueeze(1) == possible_triplets.unsqueeze(0)).all(dim=2)
|
|
665
|
+
return F.one_hot(matches.long().argmax(dim=1), num_classes=num_edge_types).to(torch.float)
|
|
666
|
+
|
|
667
|
+
|
|
668
|
+
def build_edge_feats(fields, msg, edge_features, possible_triplets, num_edge_types):
|
|
669
|
+
edge_feats = []
|
|
670
|
+
if "edge_type" in edge_features:
|
|
671
|
+
edge_feats.append(fields["edge_type"])
|
|
672
|
+
if "edge_type_triplet" in edge_features:
|
|
673
|
+
triplets = get_triplet_edge_types(
|
|
674
|
+
fields["src_type"],
|
|
675
|
+
fields["dst_type"],
|
|
676
|
+
fields["edge_type"],
|
|
677
|
+
possible_triplets,
|
|
678
|
+
num_edge_types,
|
|
679
|
+
)
|
|
680
|
+
edge_feats.append(triplets)
|
|
681
|
+
if "msg" in edge_features:
|
|
682
|
+
edge_feats.append(msg)
|
|
683
|
+
if "edge_attrs" in edge_features:
|
|
684
|
+
edge_feats.append(fields["edge_attrs"])
|
|
685
|
+
if len(edge_feats) == 0:
|
|
686
|
+
return None
|
|
687
|
+
if len(edge_feats) == 1 and edge_feats[0] is msg:
|
|
688
|
+
# `msg` is a standalone tensor: share it rather than storing a copy. Other single
|
|
689
|
+
# features are views of the raw msg and are copied so that it can be freed.
|
|
690
|
+
return msg
|
|
691
|
+
return torch.cat(edge_feats, dim=-1)
|
|
692
|
+
|
|
693
|
+
|
|
694
|
+
def get_full_data(datasets, keys=("t", "edge_type", "src", "dst", "msg")):
|
|
695
|
+
"""Concatenates the given edge-level attributes of all graphs (missing ones are skipped)."""
|
|
696
|
+
sample = datasets[0][0][0]
|
|
697
|
+
keys = [k for k in keys if hasattr(sample, k)]
|
|
698
|
+
all_data = {k: [] for k in keys}
|
|
699
|
+
for dataset_group in datasets:
|
|
700
|
+
for dataset in dataset_group:
|
|
701
|
+
for data in dataset:
|
|
702
|
+
for k in all_data:
|
|
703
|
+
all_data[k].append(getattr(data, k))
|
|
704
|
+
|
|
705
|
+
full_data = Data(**{k: torch.cat(v) for k, v in all_data.items()})
|
|
706
|
+
return full_data
|
|
707
|
+
|
|
708
|
+
|
|
709
|
+
def custom_temporal_data_loader(data: CollatableTemporalData, batch_size: int, *args, **kwargs):
|
|
710
|
+
"""
|
|
711
|
+
A simple `TemporalDataLoader` which also update the edge_index with the
|
|
712
|
+
sampled edges of size `batch_size`. By default, only attributes of shape (E, d)
|
|
713
|
+
are updated, `edge_index` is thus not updated automatically.
|
|
714
|
+
"""
|
|
715
|
+
loader = TemporalDataLoader(data, batch_size=batch_size, *args, **kwargs)
|
|
716
|
+
for batch in loader:
|
|
717
|
+
yield batch
|
|
718
|
+
|
|
719
|
+
|
|
720
|
+
def temporal_data_to_data(data: CollatableTemporalData) -> Data:
|
|
721
|
+
"""
|
|
722
|
+
NeighborLoader requires a `Data` object.
|
|
723
|
+
We need to convert `CollatableTemporalData` to `Data` before using it.
|
|
724
|
+
"""
|
|
725
|
+
data = Data(num_nodes=data.x_src.shape[0], **{k: v for k, v in data._store.items()})
|
|
726
|
+
del data.num_nodes
|
|
727
|
+
return data
|
|
728
|
+
|
|
729
|
+
|
|
730
|
+
def collate_temporal_data(data_list: list[CollatableTemporalData]) -> CollatableTemporalData:
|
|
731
|
+
"""
|
|
732
|
+
Concatenates attributes from data ojects into a single data object.
|
|
733
|
+
Do not use with `Data` directly because it will use batching when collating.
|
|
734
|
+
"""
|
|
735
|
+
assert all([not isinstance(data, Data) for data in data_list]), (
|
|
736
|
+
"Concatenating Data objects result in batching."
|
|
737
|
+
)
|
|
738
|
+
|
|
739
|
+
data = collate(CollatableTemporalData, data_list, increment=False)[0]
|
|
740
|
+
del data.ptr
|
|
741
|
+
del data.batch
|
|
742
|
+
# `tgn_mode` is a flag, not a per-event attribute: collate turns it into a tensor
|
|
743
|
+
data.tgn_mode = bool(data_list[0].tgn_mode) if len(data_list) > 0 else False
|
|
744
|
+
|
|
745
|
+
return data
|
|
746
|
+
|
|
747
|
+
|
|
748
|
+
def batch_temporal_data(
|
|
749
|
+
data: CollatableTemporalData, batch_size: int, batch_mode: str, cfg, device
|
|
750
|
+
) -> list[CollatableTemporalData]:
|
|
751
|
+
if batch_mode == "edges":
|
|
752
|
+
num_batches = math.ceil(
|
|
753
|
+
len(data.src) / batch_size
|
|
754
|
+
) # NOTE: the last batch won't have the same number of edges as the batch
|
|
755
|
+
|
|
756
|
+
data_list = [
|
|
757
|
+
data[int(i * batch_size) : int((i + 1) * batch_size)] for i in range(num_batches)
|
|
758
|
+
]
|
|
759
|
+
return data_list
|
|
760
|
+
|
|
761
|
+
elif batch_mode == "minutes":
|
|
762
|
+
window_length_ns = int(cfg.construction.time_window_size * 60_000_000_000)
|
|
763
|
+
sliding_ns = int(batch_size * 60_000_000_000) # min to ns
|
|
764
|
+
|
|
765
|
+
t0 = data.t.min()
|
|
766
|
+
t0_aligned = (t0 // sliding_ns) * sliding_ns
|
|
767
|
+
|
|
768
|
+
# Window indices [i0, i1] of each event: an event belongs to all sliding
|
|
769
|
+
# windows of length `window_length_ns` that contain its timestamp
|
|
770
|
+
t = data.t
|
|
771
|
+
i0 = (((t - window_length_ns - t0_aligned) + sliding_ns - 1) // sliding_ns).clamp(min=0)
|
|
772
|
+
i1 = (t - t0_aligned) // sliding_ns
|
|
773
|
+
counts = (i1 - i0 + 1).clamp(min=0)
|
|
774
|
+
|
|
775
|
+
# One (window, event) pair per membership, grouped by window with events in order
|
|
776
|
+
event_idx = torch.arange(t.numel(), device=t.device).repeat_interleave(counts)
|
|
777
|
+
offsets = torch.cumsum(counts, 0) - counts
|
|
778
|
+
window_idx = i0.repeat_interleave(counts) + (
|
|
779
|
+
torch.arange(event_idx.numel(), device=t.device) - offsets.repeat_interleave(counts)
|
|
780
|
+
)
|
|
781
|
+
window_idx, perm = torch.sort(window_idx, stable=True)
|
|
782
|
+
event_idx = event_idx[perm]
|
|
783
|
+
|
|
784
|
+
windows = []
|
|
785
|
+
_, sizes = torch.unique_consecutive(window_idx, return_counts=True)
|
|
786
|
+
for idx in event_idx.split(sizes.tolist()):
|
|
787
|
+
windows.append(data.index_select(idx))
|
|
788
|
+
return windows
|
|
789
|
+
|
|
790
|
+
elif batch_mode == "unique_edge_types":
|
|
791
|
+
partitions = []
|
|
792
|
+
seen_edges = defaultdict(set)
|
|
793
|
+
data.to(device)
|
|
794
|
+
|
|
795
|
+
partitions = []
|
|
796
|
+
src_list = data.src.tolist()
|
|
797
|
+
dst_list = data.dst.tolist()
|
|
798
|
+
type_list = data.edge_type.max(dim=1).indices.tolist()
|
|
799
|
+
start, end = 0, 0
|
|
800
|
+
|
|
801
|
+
for i, (src, dst, edge_type) in log_tqdm(
|
|
802
|
+
enumerate(zip(src_list, dst_list, type_list)),
|
|
803
|
+
desc="Generating unique edge type batches",
|
|
804
|
+
):
|
|
805
|
+
if (src, dst) in seen_edges:
|
|
806
|
+
# Conflict: (src, dst) already exists with a different edge_type
|
|
807
|
+
partitions.append(data[start:end])
|
|
808
|
+
start = end
|
|
809
|
+
end += 1
|
|
810
|
+
seen_edges = defaultdict(set)
|
|
811
|
+
else:
|
|
812
|
+
end += 1
|
|
813
|
+
|
|
814
|
+
seen_edges[(src, dst)].add(edge_type)
|
|
815
|
+
|
|
816
|
+
# Add the last partition if not empty
|
|
817
|
+
if end > start:
|
|
818
|
+
partitions.append(data[start:end])
|
|
819
|
+
|
|
820
|
+
data.to("cpu")
|
|
821
|
+
return partitions
|
|
822
|
+
|
|
823
|
+
raise ValueError(f"Invalid or missing batch mode {batch_mode}")
|
|
824
|
+
|
|
825
|
+
|
|
826
|
+
def run_global_batching(train_data, val_data, test_data, cfg, device):
|
|
827
|
+
# Concatenates all data into a single data so that iterating over batches
|
|
828
|
+
# of edges is more consistent with TGN
|
|
829
|
+
global_batching_cfg = cfg.batching.global_batching
|
|
830
|
+
batch_mode = global_batching_cfg.used_method
|
|
831
|
+
bs = global_batching_cfg.global_batching_batch_size
|
|
832
|
+
bs_inference = global_batching_cfg.global_batching_batch_size_inference
|
|
833
|
+
if batch_mode != "none":
|
|
834
|
+
if (bs not in [None, 0]) or batch_mode == "unique_edge_types":
|
|
835
|
+
train_data = [
|
|
836
|
+
batch_temporal_data(collate_temporal_data(graphs), bs, batch_mode, cfg, device)
|
|
837
|
+
for graphs in train_data
|
|
838
|
+
]
|
|
839
|
+
val_data = [
|
|
840
|
+
batch_temporal_data(collate_temporal_data(graphs), bs, batch_mode, cfg, device)
|
|
841
|
+
for graphs in val_data
|
|
842
|
+
]
|
|
843
|
+
test_data = [
|
|
844
|
+
batch_temporal_data(collate_temporal_data(graphs), bs, batch_mode, cfg, device)
|
|
845
|
+
for graphs in test_data
|
|
846
|
+
]
|
|
847
|
+
|
|
848
|
+
elif bs_inference not in [None, 0]:
|
|
849
|
+
test_data = [
|
|
850
|
+
batch_temporal_data(
|
|
851
|
+
collate_temporal_data(graphs), bs_inference, batch_mode, cfg, device
|
|
852
|
+
)
|
|
853
|
+
for graphs in test_data
|
|
854
|
+
]
|
|
855
|
+
|
|
856
|
+
return train_data, val_data, test_data
|
|
857
|
+
|
|
858
|
+
|
|
859
|
+
def run_reindexing_preprocessing(datasets, graph_reindexer, device, cfg, shared=None):
|
|
860
|
+
use_unique_edge_types = "unique_edge_types" in cfg.batching.global_batching.used_method
|
|
861
|
+
if not use_unique_edge_types:
|
|
862
|
+
log_dataset_stats(datasets)
|
|
863
|
+
# By default we only have x_src and x_dst of shape (E, d), here we create x of shape (N, d)
|
|
864
|
+
use_tgn = "tgn" in cfg.training.encoder.used_methods
|
|
865
|
+
# x_src/x_dst (E, d) are only needed after reindexing by specific encoders/decoders.
|
|
866
|
+
# When not needed, reindex_graph deletes them after folding into x (N, d).
|
|
867
|
+
encoder_methods = cfg.training.encoder.used_methods
|
|
868
|
+
decoder_methods = cfg.training.decoder.used_methods
|
|
869
|
+
keep_edge_level_features = (
|
|
870
|
+
"tgn" in encoder_methods
|
|
871
|
+
or "predict_edge_supervised" in decoder_methods
|
|
872
|
+
)
|
|
873
|
+
if shared is not None:
|
|
874
|
+
# Only the node IDs are reindexed here, features are reindexed per batch
|
|
875
|
+
reindex_graph_ids(datasets, graph_reindexer, device, use_tgn)
|
|
876
|
+
shared.reindex = {
|
|
877
|
+
"x_is_tuple": cfg.training.encoder.x_is_tuple,
|
|
878
|
+
"keep_edge_level_features": keep_edge_level_features,
|
|
879
|
+
}
|
|
880
|
+
else:
|
|
881
|
+
reindex_graphs(
|
|
882
|
+
datasets,
|
|
883
|
+
graph_reindexer,
|
|
884
|
+
device,
|
|
885
|
+
use_tgn,
|
|
886
|
+
keep_edge_level_features=keep_edge_level_features,
|
|
887
|
+
x_is_tuple=cfg.training.encoder.x_is_tuple,
|
|
888
|
+
)
|
|
889
|
+
|
|
890
|
+
use_tgn_loader = (
|
|
891
|
+
"tgn_last_neighbor" in cfg.batching.intra_graph_batching.used_methods
|
|
892
|
+
)
|
|
893
|
+
if cfg._is_hetero and not use_tgn_loader: # If TGN, we compute hetero feats in the encoder
|
|
894
|
+
compute_hetero_graphs(datasets, device, cfg)
|
|
895
|
+
|
|
896
|
+
return datasets
|
|
897
|
+
|
|
898
|
+
|
|
899
|
+
def run_intra_graph_batching(datasets, full_data, device, max_node, cfg, graph_reindexer, shared=None):
|
|
900
|
+
def standard_intra_batching(dataset, method):
|
|
901
|
+
result = []
|
|
902
|
+
for data_list in dataset:
|
|
903
|
+
result.append([])
|
|
904
|
+
for batch in log_tqdm(data_list, desc="Creating TGN batches"):
|
|
905
|
+
# Use temporal batch loader used in TGN
|
|
906
|
+
if method == "edges":
|
|
907
|
+
batch_size = cfg.batching.intra_graph_batching.edges.intra_graph_batch_size
|
|
908
|
+
batch_loader = custom_temporal_data_loader(batch, batch_size=batch_size)
|
|
909
|
+
elif method == "neighbor_sampling":
|
|
910
|
+
raise NotImplementedError
|
|
911
|
+
else:
|
|
912
|
+
raise ValueError(f"Invalid sampling method {method}")
|
|
913
|
+
|
|
914
|
+
for small_batch in batch_loader:
|
|
915
|
+
result[-1].append(small_batch)
|
|
916
|
+
return result
|
|
917
|
+
|
|
918
|
+
methods = map(
|
|
919
|
+
lambda x: x.strip(),
|
|
920
|
+
cfg.batching.intra_graph_batching.used_methods.split(","),
|
|
921
|
+
)
|
|
922
|
+
for method in methods:
|
|
923
|
+
if method == "none":
|
|
924
|
+
continue
|
|
925
|
+
|
|
926
|
+
elif method in ["edges", "neighbor_sampling"]:
|
|
927
|
+
datasets = [standard_intra_batching(dataset, method) for dataset in datasets]
|
|
928
|
+
|
|
929
|
+
elif method == "tgn_last_neighbor":
|
|
930
|
+
tgn_loader_cfg = cfg.batching.intra_graph_batching.tgn_last_neighbor
|
|
931
|
+
sample = datasets[0][0][0]
|
|
932
|
+
if shared is not None:
|
|
933
|
+
shared.tgn = {
|
|
934
|
+
"fix_buggy_orthrus_TGN": tgn_loader_cfg.fix_buggy_orthrus_TGN,
|
|
935
|
+
"msg": "msg" in _edge_features_list(cfg),
|
|
936
|
+
}
|
|
937
|
+
# Edges of the TGN graphs are rebuilt from their IDs in the full data
|
|
938
|
+
shared.full_src, shared.full_dst = full_data.src, full_data.dst
|
|
939
|
+
shared.full_edge_type = full_data.edge_type
|
|
940
|
+
if shared.tgn_msg_has_edge_attrs:
|
|
941
|
+
shared.full_edge_attrs = full_data.edge_attr_feats
|
|
942
|
+
datasets = compute_tgn_graphs(
|
|
943
|
+
datasets=datasets,
|
|
944
|
+
full_data=full_data,
|
|
945
|
+
graph_reindexer=graph_reindexer,
|
|
946
|
+
device=device,
|
|
947
|
+
max_node=max_node,
|
|
948
|
+
tgn_loader_cfg=tgn_loader_cfg,
|
|
949
|
+
node_feat_dim=None if shared is not None else sample.x_src.shape[1],
|
|
950
|
+
node_type_dim=None if shared is not None else sample.node_type_src.shape[1],
|
|
951
|
+
shared=shared,
|
|
952
|
+
edge_attrs_feature="edge_attrs" in _edge_features_list(cfg),
|
|
953
|
+
timezone=cfg.dataset.timezone,
|
|
954
|
+
)
|
|
955
|
+
|
|
956
|
+
else:
|
|
957
|
+
raise ValueError(f"Invalid sampling method {method}")
|
|
958
|
+
|
|
959
|
+
return datasets
|
|
960
|
+
|
|
961
|
+
|
|
962
|
+
def _to_cpu_at_once(tensors):
|
|
963
|
+
"""`[t.cpu() for t in tensors]` with one transfer (the tensors must have the same dtype)."""
|
|
964
|
+
if tensors[0].device.type == "cpu":
|
|
965
|
+
return [t.cpu() for t in tensors]
|
|
966
|
+
flat = torch.cat([t.reshape(-1) for t in tensors]).cpu()
|
|
967
|
+
return [
|
|
968
|
+
part.view(t.shape) for part, t in zip(flat.split([t.numel() for t in tensors]), tensors)
|
|
969
|
+
]
|
|
970
|
+
|
|
971
|
+
|
|
972
|
+
def compute_tgn_graphs(
|
|
973
|
+
datasets,
|
|
974
|
+
full_data,
|
|
975
|
+
graph_reindexer,
|
|
976
|
+
device,
|
|
977
|
+
max_node,
|
|
978
|
+
tgn_loader_cfg,
|
|
979
|
+
node_feat_dim,
|
|
980
|
+
node_type_dim,
|
|
981
|
+
shared=None,
|
|
982
|
+
edge_attrs_feature=False,
|
|
983
|
+
timezone="US/Eastern",
|
|
984
|
+
):
|
|
985
|
+
"""`datasets` is the [train, val, test] list of graph lists. With
|
|
986
|
+
`tgn_loader_cfg.negative_destinations`, a negative destination is drawn for each edge (see
|
|
987
|
+
`predict_edge_contrastive.neg_sampling=tgn`) and added to the nodes of its TGN graph."""
|
|
988
|
+
tgn_neighbor_n_hop = tgn_loader_cfg.tgn_neighbor_n_hop
|
|
989
|
+
fix_tgn_neighbor_loader = tgn_loader_cfg.fix_tgn_neighbor_loader
|
|
990
|
+
fix_buggy_orthrus_TGN = tgn_loader_cfg.fix_buggy_orthrus_TGN
|
|
991
|
+
insert_neighbors_before = tgn_loader_cfg.insert_neighbors_before
|
|
992
|
+
neighbor_size = tgn_loader_cfg.tgn_neighbor_size
|
|
993
|
+
directed = tgn_loader_cfg.directed
|
|
994
|
+
|
|
995
|
+
neighbor_loader = LastNeighborLoader(
|
|
996
|
+
max_node, size=neighbor_size, directed=directed, device=device
|
|
997
|
+
)
|
|
998
|
+
# As Kairos, which trains and tests on one graph per day: the neighbors (here) and the
|
|
999
|
+
# TGN memory (`TGNEncoder`, from the `reset_tgn_state` flag) are reset at each new day
|
|
1000
|
+
reset_state_every_day = bool(getattr(tgn_loader_cfg, "reset_state_every_day", False))
|
|
1001
|
+
prev_day = None
|
|
1002
|
+
|
|
1003
|
+
# With a shared node feature table, only the graph structure is computed here and the
|
|
1004
|
+
# features are gathered per batch (see `SharedNodeFeatures.materialize`)
|
|
1005
|
+
if shared is None:
|
|
1006
|
+
node_feat_cache = torch.zeros((max_node, node_feat_dim), device=device)
|
|
1007
|
+
node_type_cache = torch.zeros((max_node, node_type_dim), device=device)
|
|
1008
|
+
assoc = torch.empty(max_node, dtype=torch.long, device=device)
|
|
1009
|
+
|
|
1010
|
+
# TGN/Jbeil negatives: for each edge, a destination drawn uniformly among the destinations
|
|
1011
|
+
# of the training graphs (training) or of all graphs (validation and test), embedded by the
|
|
1012
|
+
# TGN like the nodes of the graph
|
|
1013
|
+
negative_destinations = bool(getattr(tgn_loader_cfg, "negative_destinations", False))
|
|
1014
|
+
if negative_destinations:
|
|
1015
|
+
neg_generator = torch.Generator(device="cpu").manual_seed(0)
|
|
1016
|
+
train_pool = torch.unique(torch.cat([b.dst for dl in datasets[0] for b in dl]))
|
|
1017
|
+
all_pool = torch.unique(torch.cat([b.dst for ds in datasets for dl in ds for b in dl]))
|
|
1018
|
+
|
|
1019
|
+
for split_idx, dataset in enumerate(datasets):
|
|
1020
|
+
for data_list in dataset:
|
|
1021
|
+
for batch in log_tqdm(data_list, desc="Computing TGN last neighbor graphs"):
|
|
1022
|
+
# Only the inputs are moved to the device and only the outputs are moved
|
|
1023
|
+
# back: transferring the whole batch both ways dominated this step.
|
|
1024
|
+
batch_edge_index = torch.stack([batch.src, batch.dst], dim=0).to(device)
|
|
1025
|
+
src, dst = batch_edge_index[0], batch_edge_index[1]
|
|
1026
|
+
|
|
1027
|
+
if reset_state_every_day:
|
|
1028
|
+
day = ns_time_to_datetime_US(int(batch.t[0]), timezone=timezone)[:10]
|
|
1029
|
+
batch.reset_tgn_state = day != prev_day
|
|
1030
|
+
if batch.reset_tgn_state:
|
|
1031
|
+
neighbor_loader.clear()
|
|
1032
|
+
prev_day = day
|
|
1033
|
+
|
|
1034
|
+
if insert_neighbors_before:
|
|
1035
|
+
neighbor_loader.insert(src, dst)
|
|
1036
|
+
|
|
1037
|
+
original_n_id = batch_edge_index.unique()
|
|
1038
|
+
if negative_destinations:
|
|
1039
|
+
pool = train_pool if split_idx == 0 else all_pool
|
|
1040
|
+
neg_dst = pool[
|
|
1041
|
+
torch.randint(0, len(pool), (src.numel(),), generator=neg_generator)
|
|
1042
|
+
].to(device)
|
|
1043
|
+
original_n_id = torch.cat([original_n_id, neg_dst]).unique()
|
|
1044
|
+
n_id = original_n_id
|
|
1045
|
+
for _ in range(tgn_neighbor_n_hop):
|
|
1046
|
+
n_id, edge_index, e_id = neighbor_loader(n_id)
|
|
1047
|
+
|
|
1048
|
+
if fix_tgn_neighbor_loader:
|
|
1049
|
+
# NOTE: TGN's loader wrongly index edges (less than 1% in the returned e_id and edge_index)
|
|
1050
|
+
# https://github.com/pyg-team/pytorch_geometric/issues/10100
|
|
1051
|
+
# Should be replaced by an actual fix when available
|
|
1052
|
+
real_src = full_data.src[e_id.cpu()].to(device)
|
|
1053
|
+
real_dst = full_data.dst[e_id.cpu()].to(device)
|
|
1054
|
+
|
|
1055
|
+
loader_src = n_id[edge_index[0]]
|
|
1056
|
+
loader_dst = n_id[edge_index[1]]
|
|
1057
|
+
|
|
1058
|
+
match_dir1 = real_src.eq(loader_src) & real_dst.eq(loader_dst)
|
|
1059
|
+
match_dir2 = real_src.eq(loader_dst) & real_dst.eq(loader_src)
|
|
1060
|
+
|
|
1061
|
+
valid_edges = match_dir1 | match_dir2
|
|
1062
|
+
edge_index = edge_index[:, valid_edges]
|
|
1063
|
+
e_id = e_id[valid_edges]
|
|
1064
|
+
|
|
1065
|
+
num_nodes = n_id.size(
|
|
1066
|
+
0
|
|
1067
|
+
) # Important, this one is used as __inc__ when batching graphs
|
|
1068
|
+
assoc[n_id] = torch.arange(num_nodes, device=device)
|
|
1069
|
+
if shared is None:
|
|
1070
|
+
src_dst = torch.cat([src, dst])
|
|
1071
|
+
node_type_cache[src_dst] = torch.cat(
|
|
1072
|
+
[batch.node_type_src, batch.node_type_dst]
|
|
1073
|
+
).to(device)
|
|
1074
|
+
|
|
1075
|
+
x_src_dev = batch.x_src.to(device)
|
|
1076
|
+
x_dst_dev = batch.x_dst.to(device)
|
|
1077
|
+
if fix_buggy_orthrus_TGN:
|
|
1078
|
+
node_feat_cache[src_dst] = torch.cat([x_src_dev, x_dst_dev])
|
|
1079
|
+
x_src = torch.zeros((num_nodes, node_feat_dim), device=device)
|
|
1080
|
+
x_dst = x_src.clone()
|
|
1081
|
+
src_id, dst_id = edge_index[0].unique(), edge_index[1].unique()
|
|
1082
|
+
x_src[src_id] = node_feat_cache[n_id[src_id]]
|
|
1083
|
+
x_dst[dst_id] = node_feat_cache[n_id[dst_id]]
|
|
1084
|
+
new_x = node_feat_cache[n_id]
|
|
1085
|
+
batch.x_from_tgn = x_src.cpu() # (N, d)
|
|
1086
|
+
batch.x_to_tgn = x_dst.cpu() # (N, d)
|
|
1087
|
+
batch.x_tgn = new_x.cpu() # (N, d)
|
|
1088
|
+
|
|
1089
|
+
else:
|
|
1090
|
+
(x_src, x_dst), *_ = graph_reindexer._reindex_graph(
|
|
1091
|
+
batch_edge_index,
|
|
1092
|
+
x_src_dev,
|
|
1093
|
+
x_dst_dev,
|
|
1094
|
+
max_num_node=num_nodes,
|
|
1095
|
+
x_is_tuple=True,
|
|
1096
|
+
)
|
|
1097
|
+
batch.x_from_tgn = x_src.cpu()
|
|
1098
|
+
batch.x_to_tgn = x_dst.cpu()
|
|
1099
|
+
batch.x_tgn = batch.x_from_tgn # same tensor, stored once
|
|
1100
|
+
del x_src_dev, x_dst_dev
|
|
1101
|
+
|
|
1102
|
+
batch.tgn_mode = True
|
|
1103
|
+
# A single device->host transfer (each one waits for the GPU)
|
|
1104
|
+
outputs = {
|
|
1105
|
+
"original_edge_index": batch_edge_index,
|
|
1106
|
+
"original_n_id": original_n_id,
|
|
1107
|
+
"reindexed_original_n_id_tgn": assoc[original_n_id],
|
|
1108
|
+
"n_id_tgn": n_id,
|
|
1109
|
+
"edge_index_tgn": edge_index,
|
|
1110
|
+
"reindexed_edge_index_tgn": assoc[batch_edge_index],
|
|
1111
|
+
"e_id": e_id,
|
|
1112
|
+
}
|
|
1113
|
+
if negative_destinations:
|
|
1114
|
+
outputs["neg_dst_tgn"] = assoc[neg_dst]
|
|
1115
|
+
outputs = dict(zip(outputs, _to_cpu_at_once(list(outputs.values()))))
|
|
1116
|
+
e_id_cpu = outputs.pop("e_id")
|
|
1117
|
+
for key, value in outputs.items():
|
|
1118
|
+
batch[key] = value
|
|
1119
|
+
# msg_tgn and t_tgn are only read by the TGN encoder with the
|
|
1120
|
+
# `msg` and `time_encoding` edge features (see `run_global_batching`)
|
|
1121
|
+
if "t" in full_data:
|
|
1122
|
+
batch.t_tgn = full_data.t[e_id_cpu]
|
|
1123
|
+
# Edge attributes used as TGN edge features (see `TGNEncoder`)
|
|
1124
|
+
if edge_attrs_feature and "edge_attr_feats" in full_data:
|
|
1125
|
+
batch.edge_attr_feats_tgn = full_data.edge_attr_feats[e_id_cpu]
|
|
1126
|
+
if shared is not None:
|
|
1127
|
+
batch.e_id_tgn = e_id_cpu # msg_tgn, node_type_tgn, edge_type_tgn
|
|
1128
|
+
else:
|
|
1129
|
+
if "msg" in full_data:
|
|
1130
|
+
batch.msg_tgn = full_data.msg[e_id_cpu]
|
|
1131
|
+
batch.node_type_tgn = node_type_cache[n_id].cpu()
|
|
1132
|
+
batch.edge_type_tgn = full_data.edge_type[e_id_cpu]
|
|
1133
|
+
|
|
1134
|
+
if not insert_neighbors_before:
|
|
1135
|
+
neighbor_loader.insert(src, dst)
|
|
1136
|
+
|
|
1137
|
+
return datasets
|
|
1138
|
+
|
|
1139
|
+
|
|
1140
|
+
def run_inter_graph_batching(datasets, cfg):
|
|
1141
|
+
def inter_batching(dataset, method):
|
|
1142
|
+
if method == "none":
|
|
1143
|
+
return dataset
|
|
1144
|
+
|
|
1145
|
+
elif method == "graph_batching":
|
|
1146
|
+
bs = cfg.batching.inter_graph_batching.inter_graph_batch_size
|
|
1147
|
+
result = []
|
|
1148
|
+
for data_list in dataset:
|
|
1149
|
+
result.append([])
|
|
1150
|
+
for i in log_tqdm(
|
|
1151
|
+
range(0, len(data_list), bs),
|
|
1152
|
+
total=math.ceil(len(data_list) / bs),
|
|
1153
|
+
desc="Mini-batching",
|
|
1154
|
+
):
|
|
1155
|
+
batch = data_list[i : i + bs]
|
|
1156
|
+
data = collate(CollatableTemporalData, data_list=batch)[0]
|
|
1157
|
+
|
|
1158
|
+
use_tgn = "tgn" in cfg.training.encoder.used_methods
|
|
1159
|
+
if cfg._debug and use_tgn:
|
|
1160
|
+
debug_test_batching(batch, data, cfg)
|
|
1161
|
+
result[-1].append(data)
|
|
1162
|
+
return result
|
|
1163
|
+
|
|
1164
|
+
raise ValueError(f"Invalid inter-graph batching method {method}")
|
|
1165
|
+
|
|
1166
|
+
method = cfg.batching.inter_graph_batching.used_method
|
|
1167
|
+
datasets = [inter_batching(dataset, method) for dataset in datasets]
|
|
1168
|
+
return datasets
|
|
1169
|
+
|
|
1170
|
+
|
|
1171
|
+
class _Cache:
|
|
1172
|
+
def __init__(self, shape, device):
|
|
1173
|
+
self._cache = torch.zeros(shape, device=device)
|
|
1174
|
+
|
|
1175
|
+
@property
|
|
1176
|
+
def cache(self):
|
|
1177
|
+
return self._cache
|
|
1178
|
+
|
|
1179
|
+
def detach(self):
|
|
1180
|
+
self._cache = self._cache.detach()
|
|
1181
|
+
|
|
1182
|
+
def to(self, device):
|
|
1183
|
+
self._cache = self._cache.to(device)
|
|
1184
|
+
return self
|
|
1185
|
+
|
|
1186
|
+
|
|
1187
|
+
class GraphReindexer:
|
|
1188
|
+
"""
|
|
1189
|
+
Simply transforms an edge_index and its src/dst node features of shape (E, d)
|
|
1190
|
+
to a reindexed edge_index with node IDs starting from 0 and src/dst node features of shape
|
|
1191
|
+
(max_num_node + 1, d).
|
|
1192
|
+
This reindexing is essential for the graph to be computed by a standard GNN model with PyG.
|
|
1193
|
+
"""
|
|
1194
|
+
|
|
1195
|
+
def __init__(self, device, num_nodes=None, fix_buggy_graph_reindexer=True):
|
|
1196
|
+
self.num_nodes = num_nodes
|
|
1197
|
+
self.device = device
|
|
1198
|
+
self.fix_buggy_graph_reindexer = fix_buggy_graph_reindexer
|
|
1199
|
+
|
|
1200
|
+
self.assoc = None
|
|
1201
|
+
self.cache = {}
|
|
1202
|
+
self.is_warning = False
|
|
1203
|
+
|
|
1204
|
+
def node_features_reshape(self, edge_index, x_src, x_dst, max_num_node=None, x_is_tuple=False):
|
|
1205
|
+
"""
|
|
1206
|
+
Converts node features in shape (E, d) to a shape (N, d).
|
|
1207
|
+
Returns x as a tuple (x_src, x_dst).
|
|
1208
|
+
"""
|
|
1209
|
+
# Only checked at the first call: `.min()` forces a GPU sync
|
|
1210
|
+
if not self.is_warning:
|
|
1211
|
+
self.is_warning = True
|
|
1212
|
+
if edge_index.min() != 0:
|
|
1213
|
+
print(
|
|
1214
|
+
"Warning: reshaping features with non-reindexed edge index leads to large cache stored in GPU memory."
|
|
1215
|
+
)
|
|
1216
|
+
|
|
1217
|
+
max_num_node = max_num_node + 1 if max_num_node else edge_index.max() + 1
|
|
1218
|
+
feature_dim = x_src.size(1)
|
|
1219
|
+
|
|
1220
|
+
if feature_dim not in self.cache or self.cache[feature_dim].cache.shape[0] <= max_num_node:
|
|
1221
|
+
self.cache[feature_dim] = _Cache((max_num_node, feature_dim), self.device)
|
|
1222
|
+
self.cache[feature_dim].detach()
|
|
1223
|
+
|
|
1224
|
+
# To avoid storing gradients from all nodes, we detach() BEFORE caching. If we detach()
|
|
1225
|
+
# after storing, we loose the gradient for all operations happening before the reindexing.
|
|
1226
|
+
output = self.cache[feature_dim].cache
|
|
1227
|
+
output.detach()
|
|
1228
|
+
output.zero_()
|
|
1229
|
+
|
|
1230
|
+
# The cache may be larger than needed (it only grows): only its first `max_num_node`
|
|
1231
|
+
# rows are used (all indices are lower), and the returned tensors are compact copies.
|
|
1232
|
+
# Returning views of the cache would keep its whole storage alive and alias the
|
|
1233
|
+
# results of consecutive calls (the cache is zeroed at each call).
|
|
1234
|
+
output = output[:max_num_node]
|
|
1235
|
+
|
|
1236
|
+
if x_is_tuple:
|
|
1237
|
+
scatter(x_src, edge_index[0], out=output, dim=0, reduce="mean")
|
|
1238
|
+
x_src_result = output.clone()
|
|
1239
|
+
output.zero_()
|
|
1240
|
+
|
|
1241
|
+
scatter(x_dst, edge_index[1], out=output, dim=0, reduce="mean")
|
|
1242
|
+
x_dst_result = output.clone()
|
|
1243
|
+
return (x_src_result, x_dst_result)
|
|
1244
|
+
else:
|
|
1245
|
+
if self.fix_buggy_graph_reindexer:
|
|
1246
|
+
output = output.clone()
|
|
1247
|
+
scatter(
|
|
1248
|
+
torch.cat([x_src, x_dst]),
|
|
1249
|
+
torch.cat([edge_index[0], edge_index[1]]),
|
|
1250
|
+
out=output,
|
|
1251
|
+
dim=0,
|
|
1252
|
+
reduce="mean",
|
|
1253
|
+
)
|
|
1254
|
+
return output
|
|
1255
|
+
else:
|
|
1256
|
+
# NOTE: this one, used in orthrus and velox is buggy because it does the mean twice, which can double
|
|
1257
|
+
# the value of features if duplicates exist
|
|
1258
|
+
scatter(x_src, edge_index[0], out=output, dim=0, reduce="mean")
|
|
1259
|
+
scatter(x_dst, edge_index[1], out=output, dim=0, reduce="mean")
|
|
1260
|
+
return output.clone()
|
|
1261
|
+
|
|
1262
|
+
def reindex_graph(self, data, x_is_tuple=False, use_tgn=False, keep_edge_level_features=True):
|
|
1263
|
+
"""
|
|
1264
|
+
Reindexes edge_index from 0 + reshapes node features.
|
|
1265
|
+
The original edge_index and node IDs are also kept.
|
|
1266
|
+
|
|
1267
|
+
When keep_edge_level_features=False, x_src/x_dst and node_type_src/node_type_dst
|
|
1268
|
+
are deleted after being folded into x and node_type, saving ~4*E*d bytes per graph.
|
|
1269
|
+
"""
|
|
1270
|
+
data.original_edge_index = data.edge_index
|
|
1271
|
+
x, edge_index, n_id = self._reindex_graph(
|
|
1272
|
+
data.edge_index, data.x_src, data.x_dst, x_is_tuple=x_is_tuple
|
|
1273
|
+
)
|
|
1274
|
+
data.original_n_id = n_id
|
|
1275
|
+
data.x = x
|
|
1276
|
+
|
|
1277
|
+
if not use_tgn:
|
|
1278
|
+
data.src, data.dst = edge_index[0], edge_index[1]
|
|
1279
|
+
|
|
1280
|
+
if x_is_tuple:
|
|
1281
|
+
data.x_src, data.x_dst = x
|
|
1282
|
+
else:
|
|
1283
|
+
data.x = x
|
|
1284
|
+
if not keep_edge_level_features:
|
|
1285
|
+
del data.x_src, data.x_dst
|
|
1286
|
+
|
|
1287
|
+
|
|
1288
|
+
data.node_type, *_ = self._reindex_graph(
|
|
1289
|
+
data.edge_index, data.node_type_src, data.node_type_dst, x_is_tuple=False
|
|
1290
|
+
)
|
|
1291
|
+
if not keep_edge_level_features:
|
|
1292
|
+
del data.node_type_src, data.node_type_dst
|
|
1293
|
+
|
|
1294
|
+
return data
|
|
1295
|
+
|
|
1296
|
+
def _reindex_graph(
|
|
1297
|
+
self, edge_index, x_src=None, x_dst=None, x_is_tuple=False, max_num_node=None
|
|
1298
|
+
):
|
|
1299
|
+
"""
|
|
1300
|
+
Reindexes edge_index with indices starting from 0.
|
|
1301
|
+
Also reshapes the node features.
|
|
1302
|
+
"""
|
|
1303
|
+
if self.num_nodes is None:
|
|
1304
|
+
raise ValueError(f"Graph reindexing requires `num_nodes`.")
|
|
1305
|
+
|
|
1306
|
+
if self.assoc is None:
|
|
1307
|
+
self.assoc = torch.empty((self.num_nodes,), dtype=torch.long, device=self.device)
|
|
1308
|
+
|
|
1309
|
+
n_id = edge_index.unique()
|
|
1310
|
+
self.assoc[n_id] = torch.arange(n_id.size(0), device=self.assoc.device)
|
|
1311
|
+
edge_index = self.assoc[edge_index]
|
|
1312
|
+
|
|
1313
|
+
if None not in [x_src, x_dst]:
|
|
1314
|
+
# Associates each feature vector to each reindexed node ID
|
|
1315
|
+
x = self.node_features_reshape(
|
|
1316
|
+
edge_index, x_src, x_dst, x_is_tuple=x_is_tuple, max_num_node=max_num_node
|
|
1317
|
+
)
|
|
1318
|
+
else:
|
|
1319
|
+
x = None
|
|
1320
|
+
|
|
1321
|
+
return x, edge_index, n_id
|
|
1322
|
+
|
|
1323
|
+
def clear_cache(self):
|
|
1324
|
+
"""Free cached tensors to reclaim memory after reindexing is done."""
|
|
1325
|
+
self.cache.clear()
|
|
1326
|
+
self.assoc = None
|
|
1327
|
+
|
|
1328
|
+
def to(self, device):
|
|
1329
|
+
self.device = device
|
|
1330
|
+
if self.assoc is not None:
|
|
1331
|
+
self.assoc = self.assoc.to(device)
|
|
1332
|
+
|
|
1333
|
+
for k, v in self.cache.items():
|
|
1334
|
+
self.cache[k] = v.to(device)
|
|
1335
|
+
return self
|
|
1336
|
+
|
|
1337
|
+
|
|
1338
|
+
def save_model(model, path: str):
|
|
1339
|
+
"""
|
|
1340
|
+
Saves weights on disk.
|
|
1341
|
+
"""
|
|
1342
|
+
os.makedirs(path, exist_ok=True)
|
|
1343
|
+
|
|
1344
|
+
torch.save(
|
|
1345
|
+
model.state_dict(),
|
|
1346
|
+
os.path.join(path, "state_dict.pkl"),
|
|
1347
|
+
pickle_protocol=pickle.HIGHEST_PROTOCOL,
|
|
1348
|
+
)
|
|
1349
|
+
|
|
1350
|
+
|
|
1351
|
+
def load_model(model, path: str):
|
|
1352
|
+
"""
|
|
1353
|
+
Loads weights and tensors from disk into a model.
|
|
1354
|
+
"""
|
|
1355
|
+
model.load_state_dict(torch.load(os.path.join(path, "state_dict.pkl")))
|
|
1356
|
+
|
|
1357
|
+
return model
|
|
1358
|
+
|
|
1359
|
+
|
|
1360
|
+
_REINDEX_INPUTS = ("src", "dst", "x_src", "x_dst", "node_type_src", "node_type_dst")
|
|
1361
|
+
|
|
1362
|
+
|
|
1363
|
+
def _to_cpu_shared(value, copies):
|
|
1364
|
+
"""Moves tensors (possibly nested in tuples/lists/dicts) to CPU, copying each tensor once."""
|
|
1365
|
+
if isinstance(value, torch.Tensor):
|
|
1366
|
+
key = id(value)
|
|
1367
|
+
if key not in copies:
|
|
1368
|
+
copies[key] = (value, value.cpu()) # keeps `value` alive so that its id stays unique
|
|
1369
|
+
return copies[key][1]
|
|
1370
|
+
if isinstance(value, (tuple, list)):
|
|
1371
|
+
return type(value)(_to_cpu_shared(v, copies) for v in value)
|
|
1372
|
+
if isinstance(value, dict):
|
|
1373
|
+
return {k: _to_cpu_shared(v, copies) for k, v in value.items()}
|
|
1374
|
+
return value
|
|
1375
|
+
|
|
1376
|
+
|
|
1377
|
+
def reindex_graph_ids(datasets, graph_reindexer, device, use_tgn):
|
|
1378
|
+
"""The structural part of `reindex_graphs` (node IDs only, features are not reindexed)."""
|
|
1379
|
+
for dataset in datasets:
|
|
1380
|
+
for data_list in dataset:
|
|
1381
|
+
for batch in log_tqdm(data_list, desc="Reindexing graphs"):
|
|
1382
|
+
edge_index = batch.edge_index
|
|
1383
|
+
_, reindexed, n_id = graph_reindexer._reindex_graph(edge_index.to(device))
|
|
1384
|
+
batch.original_edge_index = edge_index
|
|
1385
|
+
batch.original_n_id = n_id.cpu()
|
|
1386
|
+
if not use_tgn:
|
|
1387
|
+
reindexed = reindexed.cpu()
|
|
1388
|
+
batch.src, batch.dst = reindexed[0], reindexed[1]
|
|
1389
|
+
graph_reindexer.clear_cache()
|
|
1390
|
+
|
|
1391
|
+
|
|
1392
|
+
def reindex_graphs(datasets, graph_reindexer, device, use_tgn, keep_edge_level_features=True, x_is_tuple=False):
|
|
1393
|
+
for dataset in datasets:
|
|
1394
|
+
for data_list in dataset:
|
|
1395
|
+
for batch in log_tqdm(data_list, desc="Reindexing graphs"):
|
|
1396
|
+
# Reindexing runs on a device copy holding only its inputs; only the
|
|
1397
|
+
# new/updated attributes are copied back (and the deleted ones removed).
|
|
1398
|
+
tmp = copy.copy(batch)
|
|
1399
|
+
for key in list(tmp.keys()):
|
|
1400
|
+
if isinstance(tmp[key], torch.Tensor) and key not in _REINDEX_INPUTS:
|
|
1401
|
+
del tmp[key]
|
|
1402
|
+
tmp = tmp.to(device)
|
|
1403
|
+
inputs = dict(tmp._store.items())
|
|
1404
|
+
|
|
1405
|
+
graph_reindexer.reindex_graph(
|
|
1406
|
+
tmp,
|
|
1407
|
+
use_tgn=use_tgn,
|
|
1408
|
+
keep_edge_level_features=keep_edge_level_features,
|
|
1409
|
+
x_is_tuple=x_is_tuple,
|
|
1410
|
+
)
|
|
1411
|
+
|
|
1412
|
+
copies = {} # id(device tensor) -> CPU copy, to keep aliased outputs aliased
|
|
1413
|
+
for key, value in tmp._store.items():
|
|
1414
|
+
if key in inputs and value is inputs[key]:
|
|
1415
|
+
continue
|
|
1416
|
+
batch[key] = _to_cpu_shared(value, copies)
|
|
1417
|
+
for key in inputs:
|
|
1418
|
+
if key not in tmp._store:
|
|
1419
|
+
del batch[key]
|
|
1420
|
+
graph_reindexer.clear_cache()
|
|
1421
|
+
|
|
1422
|
+
def compute_hetero_graphs(datasets, device, cfg):
|
|
1423
|
+
node_map = get_node_map(cfg, from_zero=True)
|
|
1424
|
+
edge_map = get_rel2id(cfg, from_zero=True)
|
|
1425
|
+
|
|
1426
|
+
for dataset in datasets:
|
|
1427
|
+
for data_list in log_tqdm(dataset, desc="Computing heterogeneous graphs"):
|
|
1428
|
+
for g in data_list:
|
|
1429
|
+
g.to(device)
|
|
1430
|
+
x_dict, edge_index_dict = compute_hetero_features(
|
|
1431
|
+
g, node_map=node_map, edge_map=edge_map
|
|
1432
|
+
)
|
|
1433
|
+
g.x_dict = x_dict
|
|
1434
|
+
g.edge_index_dict = edge_index_dict
|
|
1435
|
+
g.to("cpu")
|
|
1436
|
+
|
|
1437
|
+
|
|
1438
|
+
# --------------------------------------------------------------------------------------
|
|
1439
|
+
# Shared node feature table
|
|
1440
|
+
# --------------------------------------------------------------------------------------
|
|
1441
|
+
#
|
|
1442
|
+
# Node features (embedding and type) only depend on the node, but the batches used to
|
|
1443
|
+
# store several per-edge or per-batch copies of them: x_src/x_dst and node_type_src/dst
|
|
1444
|
+
# (E, d), the raw msg (E, 2d + k), x (N, d) after reindexing, and x_tgn/x_from_tgn/
|
|
1445
|
+
# x_to_tgn, msg_tgn, node_type_tgn, edge_type_tgn for TGN. These copies were by far the
|
|
1446
|
+
# largest part of the memory used by training.
|
|
1447
|
+
#
|
|
1448
|
+
# Instead, a single table holds the features of each node, and batches only keep integer
|
|
1449
|
+
# IDs. When a batch is moved to its device (`batch_to_device`), its features are
|
|
1450
|
+
# rebuilt by `SharedNodeFeatures.materialize` with the same operations as the former
|
|
1451
|
+
# preprocessing (same gathers, same reindexing/scatter functions), so the model receives
|
|
1452
|
+
# exactly the same tensors. Configurations where features are not static per node fall
|
|
1453
|
+
# back to the eager path (see `_shared_node_features_supported`).
|
|
1454
|
+
|
|
1455
|
+
SHARED_FEATS_KEY = "shared_node_features"
|
|
1456
|
+
|
|
1457
|
+
# Attributes rebuilt from the table, removed from the stored batches
|
|
1458
|
+
_SHARED_EDGE_ATTRS = ("x_src", "x_dst", "node_type_src", "node_type_dst", "msg")
|
|
1459
|
+
|
|
1460
|
+
|
|
1461
|
+
class _SharedFeaturesUnsupported(Exception):
|
|
1462
|
+
pass
|
|
1463
|
+
|
|
1464
|
+
|
|
1465
|
+
def _selected_node_feats(cfg):
|
|
1466
|
+
return get_selected_node_features(cfg)
|
|
1467
|
+
|
|
1468
|
+
|
|
1469
|
+
def _edge_feats_is_msg(cfg):
|
|
1470
|
+
"""Whether `edge_feats` is exactly the raw msg (`build_edge_feats` returns msg itself)."""
|
|
1471
|
+
feats = ("edge_type", "edge_type_triplet", "msg", "edge_attrs")
|
|
1472
|
+
return [f for f in _edge_features_list(cfg) if f in feats] == ["msg"]
|
|
1473
|
+
|
|
1474
|
+
|
|
1475
|
+
def _shared_node_features_supported(cfg):
|
|
1476
|
+
if not getattr(cfg, "_shared_node_features", True):
|
|
1477
|
+
return False
|
|
1478
|
+
if not set(_selected_node_feats(cfg)) <= {"node_emb", "node_type"}:
|
|
1479
|
+
return False # edges_distribution / only_ones depend on the graph
|
|
1480
|
+
if cfg.batching.multi_dataset_training:
|
|
1481
|
+
return False # node IDs of different datasets overlap
|
|
1482
|
+
if cfg.batching.inter_graph_batching.used_method != "none":
|
|
1483
|
+
return False
|
|
1484
|
+
if cfg._is_hetero:
|
|
1485
|
+
return False
|
|
1486
|
+
edge_features = _edge_features_list(cfg)
|
|
1487
|
+
uses_msg = _needs_raw_msg(cfg) or "msg" in edge_features
|
|
1488
|
+
if uses_msg and "edge_type_triplet" in edge_features:
|
|
1489
|
+
return False # msg would hold the raw edge types, not stored in the batches
|
|
1490
|
+
if "msg" in edge_features and not _edge_feats_is_msg(cfg):
|
|
1491
|
+
return False # edge_feats would be a concatenation including msg
|
|
1492
|
+
return True
|
|
1493
|
+
|
|
1494
|
+
|
|
1495
|
+
class _NodeTableBuilder:
|
|
1496
|
+
"""Collects the feature row of each node ID, checking that it never changes."""
|
|
1497
|
+
|
|
1498
|
+
def __init__(self):
|
|
1499
|
+
self.rows = None
|
|
1500
|
+
self.known = None
|
|
1501
|
+
|
|
1502
|
+
def add(self, ids, feats):
|
|
1503
|
+
if ids.numel() == 0:
|
|
1504
|
+
return
|
|
1505
|
+
size = int(ids.max()) + 1
|
|
1506
|
+
if self.rows is None:
|
|
1507
|
+
self.rows = torch.zeros((size, feats.shape[1]), dtype=feats.dtype)
|
|
1508
|
+
self.known = torch.zeros(size, dtype=torch.bool)
|
|
1509
|
+
elif feats.shape[1] != self.rows.shape[1] or feats.dtype != self.rows.dtype:
|
|
1510
|
+
raise _SharedFeaturesUnsupported("inconsistent feature shapes")
|
|
1511
|
+
elif size > self.rows.shape[0]:
|
|
1512
|
+
cap = max(size, int(self.rows.shape[0] * 1.5))
|
|
1513
|
+
rows = torch.zeros((cap, self.rows.shape[1]), dtype=self.rows.dtype)
|
|
1514
|
+
rows[: self.rows.shape[0]] = self.rows
|
|
1515
|
+
known = torch.zeros(cap, dtype=torch.bool)
|
|
1516
|
+
known[: self.known.shape[0]] = self.known
|
|
1517
|
+
self.rows, self.known = rows, known
|
|
1518
|
+
|
|
1519
|
+
was_known = self.known[ids]
|
|
1520
|
+
prev = self.rows[ids[was_known]]
|
|
1521
|
+
self.rows[ids] = feats
|
|
1522
|
+
self.known[ids] = True
|
|
1523
|
+
if not torch.equal(self.rows[ids], feats) or not torch.equal(prev, feats[was_known]):
|
|
1524
|
+
raise _SharedFeaturesUnsupported("a node has different features in different graphs")
|
|
1525
|
+
|
|
1526
|
+
|
|
1527
|
+
class _DeviceState:
|
|
1528
|
+
def __init__(self, shared, device):
|
|
1529
|
+
self.node_row = shared.node_row.to(device)
|
|
1530
|
+
self.x = shared.x.to(device)
|
|
1531
|
+
self.node_type = shared.node_type.to(device)
|
|
1532
|
+
self.full_src = shared.full_src.to(device) if shared.full_src is not None else None
|
|
1533
|
+
self.full_dst = shared.full_dst.to(device) if shared.full_dst is not None else None
|
|
1534
|
+
self.full_edge_type = (
|
|
1535
|
+
shared.full_edge_type.to(device) if shared.full_edge_type is not None else None
|
|
1536
|
+
)
|
|
1537
|
+
self.full_edge_attrs = (
|
|
1538
|
+
shared.full_edge_attrs.to(device) if shared.full_edge_attrs is not None else None
|
|
1539
|
+
)
|
|
1540
|
+
self.reindexer = GraphReindexer(
|
|
1541
|
+
device=device,
|
|
1542
|
+
num_nodes=shared.num_nodes,
|
|
1543
|
+
fix_buggy_graph_reindexer=shared.fix_buggy_graph_reindexer,
|
|
1544
|
+
)
|
|
1545
|
+
|
|
1546
|
+
|
|
1547
|
+
class SharedNodeFeatures:
|
|
1548
|
+
"""Node feature table shared by all batches, and the recipe to rebuild their features."""
|
|
1549
|
+
|
|
1550
|
+
def __init__(self, builder, cfg):
|
|
1551
|
+
node_type_dim = cfg.dataset.num_node_types
|
|
1552
|
+
used = builder.known.nonzero().squeeze(1)
|
|
1553
|
+
self.num_nodes = builder.rows.shape[0]
|
|
1554
|
+
# node ID -> row in the tables (the IDs are sparse)
|
|
1555
|
+
self.node_row = torch.full((self.num_nodes,), -1, dtype=torch.long)
|
|
1556
|
+
self.node_row[used] = torch.arange(used.numel())
|
|
1557
|
+
raw = builder.rows[used] # [node_type | node_emb], as in the edge messages
|
|
1558
|
+
fields = {"node_type": raw[:, :node_type_dim], "node_emb": raw[:, node_type_dim:]}
|
|
1559
|
+
self.x = torch.cat([fields[f] for f in _selected_node_feats(cfg)], dim=-1)
|
|
1560
|
+
self.node_type = fields["node_type"].clone()
|
|
1561
|
+
|
|
1562
|
+
self.needs_msg = _needs_raw_msg(cfg)
|
|
1563
|
+
self.edge_feats_is_msg = _edge_feats_is_msg(cfg)
|
|
1564
|
+
self.edge_features = _edge_features_list(cfg)
|
|
1565
|
+
self.msg_has_edge_type = _msg_has_edge_type(cfg)
|
|
1566
|
+
self.fix_buggy_graph_reindexer = cfg.batching.fix_buggy_graph_reindexer
|
|
1567
|
+
self.tgn_node_feats_used, self.node_feats_used = _per_batch_node_feats_used(cfg)
|
|
1568
|
+
|
|
1569
|
+
# Dataset edge attributes are appended to msg (they stay stored per edge)
|
|
1570
|
+
self.has_edge_attrs = False
|
|
1571
|
+
|
|
1572
|
+
# Set by the preprocessing steps whose features are rebuilt
|
|
1573
|
+
self.tgn = None # {"fix_buggy_orthrus_TGN": bool, "msg": bool}
|
|
1574
|
+
self.reindex = None # {"x_is_tuple": bool, "keep_edge_level_features": bool}
|
|
1575
|
+
self.full_src = self.full_dst = self.full_edge_type = self.full_edge_attrs = None
|
|
1576
|
+
|
|
1577
|
+
self._devices = {}
|
|
1578
|
+
|
|
1579
|
+
@property
|
|
1580
|
+
def tgn_msg_has_edge_attrs(self):
|
|
1581
|
+
"""Whether msg_tgn (gathered from the full msg) includes the edge attributes."""
|
|
1582
|
+
return self.has_edge_attrs and "msg" in self.edge_features
|
|
1583
|
+
|
|
1584
|
+
def __repr__(self):
|
|
1585
|
+
return f"SharedNodeFeatures(nodes={self.x.shape[0]}, dim={self.x.shape[1]})"
|
|
1586
|
+
|
|
1587
|
+
def __getstate__(self):
|
|
1588
|
+
state = self.__dict__.copy()
|
|
1589
|
+
state["_devices"] = {}
|
|
1590
|
+
return state
|
|
1591
|
+
|
|
1592
|
+
def nbytes(self):
|
|
1593
|
+
tensors = [
|
|
1594
|
+
self.node_row, self.x, self.node_type,
|
|
1595
|
+
self.full_src, self.full_dst, self.full_edge_type, self.full_edge_attrs,
|
|
1596
|
+
]
|
|
1597
|
+
return sum(t.numel() * t.element_size() for t in tensors if t is not None)
|
|
1598
|
+
|
|
1599
|
+
def _state(self, device):
|
|
1600
|
+
key = str(torch.device(device))
|
|
1601
|
+
if key not in self._devices:
|
|
1602
|
+
self._devices[key] = _DeviceState(self, device)
|
|
1603
|
+
return self._devices[key]
|
|
1604
|
+
|
|
1605
|
+
def materialize(self, g, device):
|
|
1606
|
+
"""Adds to `g` (already on `device`) the attributes the eager preprocessing stored."""
|
|
1607
|
+
st = self._state(device)
|
|
1608
|
+
if "original_edge_index" in g:
|
|
1609
|
+
ids_src, ids_dst = g.original_edge_index[0], g.original_edge_index[1]
|
|
1610
|
+
else:
|
|
1611
|
+
ids_src, ids_dst = g.src, g.dst
|
|
1612
|
+
rows_src, rows_dst = st.node_row[ids_src], st.node_row[ids_dst]
|
|
1613
|
+
|
|
1614
|
+
# `extract_msg_from_data`
|
|
1615
|
+
g.x_src = st.x[rows_src]
|
|
1616
|
+
g.x_dst = st.x[rows_dst]
|
|
1617
|
+
g.node_type_src = st.node_type[rows_src]
|
|
1618
|
+
g.node_type_dst = st.node_type[rows_dst]
|
|
1619
|
+
if self.needs_msg or self.edge_feats_is_msg:
|
|
1620
|
+
parts = [g.x_src, g.x_dst] + ([g.edge_type] if self.msg_has_edge_type else [])
|
|
1621
|
+
if "edge_attr_feats" in g:
|
|
1622
|
+
parts.append(g.edge_attr_feats)
|
|
1623
|
+
msg = torch.cat(parts, dim=-1)
|
|
1624
|
+
if self.needs_msg:
|
|
1625
|
+
g.msg = msg
|
|
1626
|
+
if self.edge_feats_is_msg:
|
|
1627
|
+
g.edge_feats = msg
|
|
1628
|
+
|
|
1629
|
+
# `compute_tgn_graphs`
|
|
1630
|
+
if self.tgn is not None and g.tgn_mode:
|
|
1631
|
+
n_id = g.n_id_tgn
|
|
1632
|
+
n_rows = st.node_row[n_id]
|
|
1633
|
+
if not self.tgn_node_feats_used:
|
|
1634
|
+
pass
|
|
1635
|
+
elif self.tgn["fix_buggy_orthrus_TGN"]:
|
|
1636
|
+
num_nodes = n_id.size(0)
|
|
1637
|
+
x_src = torch.zeros((num_nodes, st.x.shape[1]), device=st.x.device)
|
|
1638
|
+
x_dst = x_src.clone()
|
|
1639
|
+
src_id, dst_id = g.edge_index_tgn[0].unique(), g.edge_index_tgn[1].unique()
|
|
1640
|
+
x_src[src_id] = st.x[n_rows[src_id]]
|
|
1641
|
+
x_dst[dst_id] = st.x[n_rows[dst_id]]
|
|
1642
|
+
g.x_from_tgn = x_src
|
|
1643
|
+
g.x_to_tgn = x_dst
|
|
1644
|
+
g.x_tgn = st.x[n_rows]
|
|
1645
|
+
else:
|
|
1646
|
+
(x_src, x_dst), *_ = st.reindexer._reindex_graph(
|
|
1647
|
+
g.original_edge_index,
|
|
1648
|
+
g.x_src,
|
|
1649
|
+
g.x_dst,
|
|
1650
|
+
max_num_node=n_id.size(0),
|
|
1651
|
+
x_is_tuple=True,
|
|
1652
|
+
)
|
|
1653
|
+
g.x_from_tgn = x_src
|
|
1654
|
+
g.x_to_tgn = x_dst
|
|
1655
|
+
g.x_tgn = x_src
|
|
1656
|
+
g.node_type_tgn = st.node_type[n_rows]
|
|
1657
|
+
|
|
1658
|
+
e_id = g.e_id_tgn
|
|
1659
|
+
del g.e_id_tgn
|
|
1660
|
+
g.edge_type_tgn = st.full_edge_type[e_id]
|
|
1661
|
+
if self.tgn["msg"]:
|
|
1662
|
+
e_src, e_dst = st.node_row[st.full_src[e_id]], st.node_row[st.full_dst[e_id]]
|
|
1663
|
+
parts = [st.x[e_src], st.x[e_dst]]
|
|
1664
|
+
if self.msg_has_edge_type:
|
|
1665
|
+
parts.append(g.edge_type_tgn)
|
|
1666
|
+
if st.full_edge_attrs is not None:
|
|
1667
|
+
parts.append(st.full_edge_attrs[e_id])
|
|
1668
|
+
g.msg_tgn = torch.cat(parts, dim=-1)
|
|
1669
|
+
|
|
1670
|
+
# `GraphReindexer.reindex_graph`
|
|
1671
|
+
if self.reindex is not None and self.node_feats_used:
|
|
1672
|
+
edge_index = g.original_edge_index
|
|
1673
|
+
x, *_ = st.reindexer._reindex_graph(
|
|
1674
|
+
edge_index, g.x_src, g.x_dst, x_is_tuple=self.reindex["x_is_tuple"]
|
|
1675
|
+
)
|
|
1676
|
+
g.x = x
|
|
1677
|
+
keep = self.reindex["keep_edge_level_features"]
|
|
1678
|
+
if self.reindex["x_is_tuple"]:
|
|
1679
|
+
g.x_src, g.x_dst = x
|
|
1680
|
+
elif not keep:
|
|
1681
|
+
del g.x_src, g.x_dst
|
|
1682
|
+
g.node_type, *_ = st.reindexer._reindex_graph(
|
|
1683
|
+
edge_index, g.node_type_src, g.node_type_dst, x_is_tuple=False
|
|
1684
|
+
)
|
|
1685
|
+
if not keep:
|
|
1686
|
+
del g.node_type_src, g.node_type_dst
|
|
1687
|
+
return g
|
|
1688
|
+
|
|
1689
|
+
|
|
1690
|
+
def materialize_batch(data):
|
|
1691
|
+
"""Returns `data` with all its features, on the device it is stored on."""
|
|
1692
|
+
if SHARED_FEATS_KEY not in data:
|
|
1693
|
+
return data
|
|
1694
|
+
return batch_to_device(data, data.src.device)
|
|
1695
|
+
|
|
1696
|
+
|
|
1697
|
+
# Objectives that only read the embeddings of the edges' nodes (not the batch's node features)
|
|
1698
|
+
_OBJECTIVES_WITHOUT_NODE_FEATS = {"predict_edge_type", "predict_edge_contrastive"}
|
|
1699
|
+
|
|
1700
|
+
|
|
1701
|
+
def _per_batch_node_feats_used(cfg):
|
|
1702
|
+
"""Whether the features rebuilt per batch by `SharedNodeFeatures.materialize` are read:
|
|
1703
|
+
(x_from_tgn, x_to_tgn, x_tgn) by the TGN encoder, and the node-level (x, node_type).
|
|
1704
|
+
|
|
1705
|
+
The TGN encoder only reads its node features without memory or with
|
|
1706
|
+
`use_node_feats_in_gnn` (it embeds the memory otherwise), and reads none of the node-level
|
|
1707
|
+
features, which are then only read by some objectives. Skipping the unused ones saves
|
|
1708
|
+
their computation at each batch, including a `torch.unique` that waits for the GPU."""
|
|
1709
|
+
methods = [m.strip() for m in cfg.training.encoder.used_methods.replace("-", ",").split(",")]
|
|
1710
|
+
if "tgn" not in methods:
|
|
1711
|
+
return True, True
|
|
1712
|
+
tgn = cfg.training.encoder.tgn
|
|
1713
|
+
tgn_node_feats_used = (not tgn.use_memory) or bool(tgn.use_node_feats_in_gnn)
|
|
1714
|
+
objectives = {o.strip() for o in cfg.training.decoder.used_methods.split(",")}
|
|
1715
|
+
node_feats_used = (
|
|
1716
|
+
not objectives <= _OBJECTIVES_WITHOUT_NODE_FEATS
|
|
1717
|
+
or bool(cfg.training.decoder.use_few_shot)
|
|
1718
|
+
)
|
|
1719
|
+
return tgn_node_feats_used, node_feats_used
|
|
1720
|
+
|
|
1721
|
+
|
|
1722
|
+
def _load_data_list_shared(path, split, cfg, builder):
|
|
1723
|
+
"""Like `load_data_list`, but node features go to `builder` instead of the graphs."""
|
|
1724
|
+
data_list = []
|
|
1725
|
+
edge_feats_is_msg = _edge_feats_is_msg(cfg)
|
|
1726
|
+
for f in sorted(os.listdir(os.path.join(path, split))):
|
|
1727
|
+
data = torch.load(os.path.join(path, split, f)).to("cpu")
|
|
1728
|
+
if COMPACT_MSG_KEYS[0] not in data:
|
|
1729
|
+
raise _SharedFeaturesUnsupported("edge messages are not stored compactly")
|
|
1730
|
+
rows = torch.cat([data.msg_src_row, data.msg_dst_row]).long()
|
|
1731
|
+
builder.add(torch.cat([data.src, data.dst]), data.msg_node_feats[rows])
|
|
1732
|
+
|
|
1733
|
+
# Same attributes as the eager path, then the ones rebuilt from the table are dropped
|
|
1734
|
+
expand_compact_msg(data)
|
|
1735
|
+
extract_msg_from_data([data], cfg)
|
|
1736
|
+
for key in _SHARED_EDGE_ATTRS:
|
|
1737
|
+
if key in data:
|
|
1738
|
+
del data[key]
|
|
1739
|
+
if edge_feats_is_msg and "edge_feats" in data:
|
|
1740
|
+
del data["edge_feats"]
|
|
1741
|
+
data_list.append(data)
|
|
1742
|
+
return data_list
|