pidsmaker 4.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of pidsmaker might be problematic. Click here for more details.

Files changed (338) hide show
  1. pidsmaker/__init__.py +22 -0
  2. pidsmaker/cli.py +32 -0
  3. pidsmaker/config/__init__.py +2 -0
  4. pidsmaker/config/config.py +2100 -0
  5. pidsmaker/config/pipeline.py +1768 -0
  6. pidsmaker/config/schemas.py +1032 -0
  7. pidsmaker/datasets.py +222 -0
  8. pidsmaker/debug_tests.py +30 -0
  9. pidsmaker/decoders/__init__.py +5 -0
  10. pidsmaker/decoders/custom_edge_mlp_decoder.py +17 -0
  11. pidsmaker/decoders/custom_mlp_decoder.py +10 -0
  12. pidsmaker/decoders/edge_linear_decoder.py +16 -0
  13. pidsmaker/decoders/inner_product_decoder.py +18 -0
  14. pidsmaker/decoders/nodlink_decoder.py +56 -0
  15. pidsmaker/detection/__init__.py +0 -0
  16. pidsmaker/detection/evaluation_methods/__init__.py +9 -0
  17. pidsmaker/detection/evaluation_methods/edge_evaluation.py +259 -0
  18. pidsmaker/detection/evaluation_methods/evaluation_utils.py +1730 -0
  19. pidsmaker/detection/evaluation_methods/host_two_stage_evaluation.py +115 -0
  20. pidsmaker/detection/evaluation_methods/node_evaluation.py +463 -0
  21. pidsmaker/detection/evaluation_methods/node_tw_evaluation.py +196 -0
  22. pidsmaker/detection/evaluation_methods/plot.py +192 -0
  23. pidsmaker/detection/evaluation_methods/queue_evaluation.py +451 -0
  24. pidsmaker/detection/evaluation_methods/tw_evaluation.py +95 -0
  25. pidsmaker/detection/flash_detection.py +162 -0
  26. pidsmaker/detection/magic_knn.py +190 -0
  27. pidsmaker/detection/node_scoring.py +52 -0
  28. pidsmaker/detection/threatrace_detection.py +65 -0
  29. pidsmaker/detection/training_methods/__init__.py +1 -0
  30. pidsmaker/detection/training_methods/inference_loop.py +293 -0
  31. pidsmaker/detection/training_methods/ocrapt_early_stop.py +165 -0
  32. pidsmaker/detection/training_methods/threatrace_training.py +169 -0
  33. pidsmaker/detection/training_methods/training_loop.py +377 -0
  34. pidsmaker/encoders/__init__.py +22 -0
  35. pidsmaker/encoders/argus_encoder.py +69 -0
  36. pidsmaker/encoders/custom_mlp.py +75 -0
  37. pidsmaker/encoders/custom_mlp_encoder.py +10 -0
  38. pidsmaker/encoders/egraphsage_encoder.py +56 -0
  39. pidsmaker/encoders/gat.py +67 -0
  40. pidsmaker/encoders/gcn.py +27 -0
  41. pidsmaker/encoders/gin.py +48 -0
  42. pidsmaker/encoders/glstm.py +298 -0
  43. pidsmaker/encoders/graph_attention.py +63 -0
  44. pidsmaker/encoders/gru.py +29 -0
  45. pidsmaker/encoders/hetero/__init__.py +4 -0
  46. pidsmaker/encoders/hetero/ancestor_encoder.py +98 -0
  47. pidsmaker/encoders/hetero/entity_encoder.py +33 -0
  48. pidsmaker/encoders/hetero/event_encoder.py +81 -0
  49. pidsmaker/encoders/hetero/hetero_graph_transformer.py +40 -0
  50. pidsmaker/encoders/lares_encoder.py +68 -0
  51. pidsmaker/encoders/linear_encoder.py +16 -0
  52. pidsmaker/encoders/magic_encoder.py +161 -0
  53. pidsmaker/encoders/rcaid_encoder.py +81 -0
  54. pidsmaker/encoders/rgcn.py +75 -0
  55. pidsmaker/encoders/sage.py +51 -0
  56. pidsmaker/encoders/shadewatcher_encoder.py +149 -0
  57. pidsmaker/encoders/sum_aggregation.py +20 -0
  58. pidsmaker/encoders/temporal_wrappers.py +80 -0
  59. pidsmaker/encoders/textrcnn.py +82 -0
  60. pidsmaker/encoders/tgn_encoder.py +193 -0
  61. pidsmaker/experiments/tuning.py +102 -0
  62. pidsmaker/experiments/uncertainty.py +261 -0
  63. pidsmaker/factory.py +1456 -0
  64. pidsmaker/featurization/__init__.py +0 -0
  65. pidsmaker/featurization/feat_inference_methods/__init__.py +7 -0
  66. pidsmaker/featurization/feat_inference_methods/feat_inference_HFH.py +31 -0
  67. pidsmaker/featurization/feat_inference_methods/feat_inference_TRW.py +67 -0
  68. pidsmaker/featurization/feat_inference_methods/feat_inference_alacarte.py +16 -0
  69. pidsmaker/featurization/feat_inference_methods/feat_inference_doc2vec.py +54 -0
  70. pidsmaker/featurization/feat_inference_methods/feat_inference_fasttext.py +38 -0
  71. pidsmaker/featurization/feat_inference_methods/feat_inference_flash.py +70 -0
  72. pidsmaker/featurization/feat_inference_methods/feat_inference_graph2vec.py +85 -0
  73. pidsmaker/featurization/feat_inference_methods/feat_inference_ocrapt_features.py +95 -0
  74. pidsmaker/featurization/feat_inference_methods/feat_inference_pretrained.py +1729 -0
  75. pidsmaker/featurization/feat_inference_methods/feat_inference_word2vec.py +56 -0
  76. pidsmaker/featurization/featurization_methods/__init__.py +0 -0
  77. pidsmaker/featurization/featurization_methods/build_trw.py +67 -0
  78. pidsmaker/featurization/featurization_methods/featurization_alacarte.py +748 -0
  79. pidsmaker/featurization/featurization_methods/featurization_doc2vec.py +99 -0
  80. pidsmaker/featurization/featurization_methods/featurization_fasttext.py +75 -0
  81. pidsmaker/featurization/featurization_methods/featurization_flash.py +203 -0
  82. pidsmaker/featurization/featurization_methods/featurization_graph2vec.py +243 -0
  83. pidsmaker/featurization/featurization_methods/featurization_trw.py +115 -0
  84. pidsmaker/featurization/featurization_methods/featurization_word2vec.py +87 -0
  85. pidsmaker/featurization/featurization_utils.py +275 -0
  86. pidsmaker/featurization/utils/build_random_walks.py +68 -0
  87. pidsmaker/featurization/utils/trw.py +203 -0
  88. pidsmaker/hetero.py +81 -0
  89. pidsmaker/losses.py +170 -0
  90. pidsmaker/main.py +377 -0
  91. pidsmaker/mimicry.py +284 -0
  92. pidsmaker/model.py +382 -0
  93. pidsmaker/objectives/__init__.py +16 -0
  94. pidsmaker/objectives/autoencode_edge_emb.py +43 -0
  95. pidsmaker/objectives/deep_graph_infomax.py +94 -0
  96. pidsmaker/objectives/detect_few_shot.py +21 -0
  97. pidsmaker/objectives/one_class.py +75 -0
  98. pidsmaker/objectives/predict_edge_contrastive.py +165 -0
  99. pidsmaker/objectives/predict_edge_supervised.py +77 -0
  100. pidsmaker/objectives/predict_edge_type.py +28 -0
  101. pidsmaker/objectives/predict_masked_struct.py +49 -0
  102. pidsmaker/objectives/predict_node_type.py +36 -0
  103. pidsmaker/objectives/predict_process_tag.py +169 -0
  104. pidsmaker/objectives/predict_snapshot_embedding.py +97 -0
  105. pidsmaker/objectives/reconstruct_edge_emb.py +16 -0
  106. pidsmaker/objectives/reconstruct_masked_feat.py +51 -0
  107. pidsmaker/objectives/reconstruct_node_emb.py +13 -0
  108. pidsmaker/objectives/reconstruct_node_feat.py +13 -0
  109. pidsmaker/objectives/validation_wrapper.py +55 -0
  110. pidsmaker/preprocessing/__init__.py +0 -0
  111. pidsmaker/preprocessing/build_graph_methods/__init__.py +1 -0
  112. pidsmaker/preprocessing/build_graph_methods/build_default_graphs.py +830 -0
  113. pidsmaker/preprocessing/build_graph_methods/build_magic_graphs.py +220 -0
  114. pidsmaker/preprocessing/cleaning.py +258 -0
  115. pidsmaker/preprocessing/transformation_methods/__init__.py +2 -0
  116. pidsmaker/preprocessing/transformation_methods/attack_generation/synthetic_attack_naive.py +194 -0
  117. pidsmaker/preprocessing/transformation_methods/transformation_dag.py +28 -0
  118. pidsmaker/preprocessing/transformation_methods/transformation_merge_edges.py +136 -0
  119. pidsmaker/preprocessing/transformation_methods/transformation_rcaid_pseudo_graph.py +510 -0
  120. pidsmaker/preprocessing/transformation_methods/transformation_undirected.py +24 -0
  121. pidsmaker/preprocessing/transformation_methods/transformation_utils.py +36 -0
  122. pidsmaker/pretrained/__init__.py +5 -0
  123. pidsmaker/pretrained/data/__init__.py +4 -0
  124. pidsmaker/pretrained/data/behavior_signatures.py +548 -0
  125. pidsmaker/pretrained/data/canonical_tokens.py +1035 -0
  126. pidsmaker/pretrained/data/edge_filter.py +381 -0
  127. pidsmaker/pretrained/data/entity_classes.py +476 -0
  128. pidsmaker/pretrained/data/sampler.py +926 -0
  129. pidsmaker/pretrained/data/tokenizer_bpe.py +1659 -0
  130. pidsmaker/pretrained/detect.py +1432 -0
  131. pidsmaker/pretrained/embedding_generator.py +252 -0
  132. pidsmaker/pretrained/finetune.py +1437 -0
  133. pidsmaker/pretrained/models/__init__.py +20 -0
  134. pidsmaker/pretrained/models/behavior.py +348 -0
  135. pidsmaker/pretrained/models/bert.py +286 -0
  136. pidsmaker/pretrained/models/deepwalk.py +128 -0
  137. pidsmaker/pretrained/models/dgi.py +120 -0
  138. pidsmaker/pretrained/models/gae.py +114 -0
  139. pidsmaker/pretrained/models/gnn_distill.py +475 -0
  140. pidsmaker/pretrained/models/graphmae.py +373 -0
  141. pidsmaker/pretrained/models/hf_pretrained.py +213 -0
  142. pidsmaker/pretrained/models/llama.py +110 -0
  143. pidsmaker/pretrained/models/modernbert.py +567 -0
  144. pidsmaker/pretrained/models/roberta.py +147 -0
  145. pidsmaker/pretrained/models/rope_utils.py +99 -0
  146. pidsmaker/pretrained/models/ropebert.py +322 -0
  147. pidsmaker/pretrained/models/spider.py +204 -0
  148. pidsmaker/pretrained/models/tgn.py +770 -0
  149. pidsmaker/pretrained/pretrain/__init__.py +3 -0
  150. pidsmaker/pretrained/pretrain/pretrain_behavior_cluster.py +513 -0
  151. pidsmaker/pretrained/pretrain/pretrain_common.py +585 -0
  152. pidsmaker/pretrained/pretrain/pretrain_deepwalk.py +31 -0
  153. pidsmaker/pretrained/pretrain/pretrain_dgi.py +143 -0
  154. pidsmaker/pretrained/pretrain/pretrain_gae.py +143 -0
  155. pidsmaker/pretrained/pretrain/pretrain_gnn_distill.py +438 -0
  156. pidsmaker/pretrained/pretrain/pretrain_graphmae.py +151 -0
  157. pidsmaker/pretrained/pretrain/pretrain_hf.py +169 -0
  158. pidsmaker/pretrained/pretrain/pretrain_main.py +276 -0
  159. pidsmaker/pretrained/pretrain/pretrain_mlm.py +491 -0
  160. pidsmaker/pretrained/pretrain/pretrain_spider.py +502 -0
  161. pidsmaker/pretrained/training_utils.py +157 -0
  162. pidsmaker/process_reapr_gt.py +101 -0
  163. pidsmaker/resources/Ground_Truth/orthrus/E3-CADETS/node_Nginx_Backdoor_06.csv +8 -0
  164. pidsmaker/resources/Ground_Truth/orthrus/E3-CADETS/node_Nginx_Backdoor_11.csv +4 -0
  165. pidsmaker/resources/Ground_Truth/orthrus/E3-CADETS/node_Nginx_Backdoor_12.csv +43 -0
  166. pidsmaker/resources/Ground_Truth/orthrus/E3-CADETS/node_Nginx_Backdoor_13.csv +24 -0
  167. pidsmaker/resources/Ground_Truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0411.csv +41 -0
  168. pidsmaker/resources/Ground_Truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0412.csv +0 -0
  169. pidsmaker/resources/Ground_Truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_browser_0412.csv +1 -0
  170. pidsmaker/resources/Ground_Truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +63 -0
  171. pidsmaker/resources/Ground_Truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +56 -0
  172. pidsmaker/resources/Ground_Truth/orthrus/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +61 -0
  173. pidsmaker/resources/Ground_Truth/orthrus/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +58 -0
  174. pidsmaker/resources/Ground_Truth/orthrus/E3-TRACE/node_trace_e3_firefox_0410.csv +11 -0
  175. pidsmaker/resources/Ground_Truth/orthrus/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +11 -0
  176. pidsmaker/resources/Ground_Truth/orthrus/E3-TRACE/node_trace_e3_pine_0413.csv +14 -0
  177. pidsmaker/resources/Ground_Truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT.csv +19 -0
  178. pidsmaker/resources/Ground_Truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT_17.csv +107 -0
  179. pidsmaker/resources/Ground_Truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_appstarter_0515.csv +26 -0
  180. pidsmaker/resources/Ground_Truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_firefox_0517.csv +1 -0
  181. pidsmaker/resources/Ground_Truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_lockwatch_0517.csv +17 -0
  182. pidsmaker/resources/Ground_Truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_tester_0517.csv +8 -0
  183. pidsmaker/resources/Ground_Truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_bits_0515.csv +54 -0
  184. pidsmaker/resources/Ground_Truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_copykatz_0509.csv +87 -0
  185. pidsmaker/resources/Ground_Truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_dns_0517.csv +11 -0
  186. pidsmaker/resources/Ground_Truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_drakon_0517.csv +6 -0
  187. pidsmaker/resources/Ground_Truth/orthrus/E5-THEIA/node_THEIA_1_Firefox_Drakon_APT_BinFmt_Elevate_Inject.csv +70 -0
  188. pidsmaker/resources/Ground_Truth/orthrus/E5-TRACE/node_Trace_Firefox_Drakon.csv +71 -0
  189. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m1.csv +1 -0
  190. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m2.csv +1 -0
  191. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m3.csv +1 -0
  192. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m4.csv +5 -0
  193. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m5.csv +23 -0
  194. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m6.csv +18 -0
  195. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_s1.csv +1 -0
  196. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_s2.csv +1 -0
  197. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_s3.csv +16 -0
  198. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_s4.csv +22 -0
  199. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m1.csv +126 -0
  200. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m2.csv +105 -0
  201. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m3.csv +94 -0
  202. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m4.csv +139 -0
  203. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m5.csv +228 -0
  204. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m6.csv +131 -0
  205. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_s1.csv +118 -0
  206. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_s2.csv +89 -0
  207. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_s3.csv +133 -0
  208. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_s4.csv +135 -0
  209. pidsmaker/resources/Ground_Truth/orthrus/carbanakv2_edr/carbanakv2_edr.csv +2453 -0
  210. pidsmaker/resources/Ground_Truth/orthrus/h051/node_h051_0925.csv +114 -0
  211. pidsmaker/resources/Ground_Truth/orthrus/h201/node_h201_0923.csv +2905 -0
  212. pidsmaker/resources/Ground_Truth/orthrus/h501/node_h501_0924.csv +749 -0
  213. pidsmaker/resources/Ground_Truth/orthrus/readme.md +98 -0
  214. pidsmaker/resources/Ground_Truth/reapr/E3-CADETS/node_Nginx_Backdoor_06.csv +3 -0
  215. pidsmaker/resources/Ground_Truth/reapr/E3-CADETS/node_Nginx_Backdoor_12.csv +655 -0
  216. pidsmaker/resources/Ground_Truth/reapr/E3-CADETS/node_Nginx_Backdoor_13.csv +770 -0
  217. pidsmaker/resources/Ground_Truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +0 -0
  218. pidsmaker/resources/Ground_Truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +18 -0
  219. pidsmaker/resources/Ground_Truth/reapr/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +42 -0
  220. pidsmaker/resources/Ground_Truth/reapr/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +81 -0
  221. pidsmaker/resources/Ground_Truth/reapr/E3-TRACE/node_trace_e3_firefox_0410.csv +37 -0
  222. pidsmaker/resources/Ground_Truth/reapr/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +9 -0
  223. pidsmaker/resources/Ground_Truth/reapr/E3-TRACE/node_trace_e3_pine_0413.csv +40 -0
  224. pidsmaker/resources/Ground_Truth/threatrace/E3-CADETS/ground_truth.txt +12858 -0
  225. pidsmaker/resources/Ground_Truth/threatrace/E3-FIVEDIRECTIONS/ground_truth.txt +18420 -0
  226. pidsmaker/resources/Ground_Truth/threatrace/E3-THEIA/ground_truth.txt +25363 -0
  227. pidsmaker/resources/Ground_Truth/threatrace/E3-TRACE/ground_truth.txt +68265 -0
  228. pidsmaker/resources/Ground_Truth/threatrace/README.md +123 -0
  229. pidsmaker/resources/config/anomal_e.yml +25 -0
  230. pidsmaker/resources/config/argus.yml +56 -0
  231. pidsmaker/resources/config/attack_edges/cadets_e3.yml +435 -0
  232. pidsmaker/resources/config/attack_edges/cadets_e5.yml +407 -0
  233. pidsmaker/resources/config/attack_edges/theia_e3.yml +382 -0
  234. pidsmaker/resources/config/attack_edges/theia_e5.yml +387 -0
  235. pidsmaker/resources/config/attack_edges/trace_e3.yml +415 -0
  236. pidsmaker/resources/config/attack_edges/trace_e5.yml +417 -0
  237. pidsmaker/resources/config/default.yml +315 -0
  238. pidsmaker/resources/config/egraphsage.yml +95 -0
  239. pidsmaker/resources/config/euler.yml +104 -0
  240. pidsmaker/resources/config/eval/eval_set_clustering.json +3170 -0
  241. pidsmaker/resources/config/experiments/tuning/components/tuning_featurization_methods.yml +29 -0
  242. pidsmaker/resources/config/experiments/tuning/systems/clearscope_e5/tuning_orthrus.yml +14 -0
  243. pidsmaker/resources/config/experiments/tuning/systems/default/tuning_default_baselines.yml +13 -0
  244. pidsmaker/resources/config/experiments/tuning/systems/default/tuning_orthrus_fixed.yml +16 -0
  245. pidsmaker/resources/config/experiments/uncertainty/none.yml +5 -0
  246. pidsmaker/resources/config/experiments/uncertainty/run_n_times.yml +12 -0
  247. pidsmaker/resources/config/experiments/uncertainty/run_n_times_hyperparameters.yml +12 -0
  248. pidsmaker/resources/config/experiments/uncertainty/uncertainty.yml +22 -0
  249. pidsmaker/resources/config/flash.yml +79 -0
  250. pidsmaker/resources/config/jbeil.yml +65 -0
  251. pidsmaker/resources/config/kairos.yml +121 -0
  252. pidsmaker/resources/config/lares.yml +115 -0
  253. pidsmaker/resources/config/magic.yml +86 -0
  254. pidsmaker/resources/config/nodlink.yml +79 -0
  255. pidsmaker/resources/config/ocrapt.yml +91 -0
  256. pidsmaker/resources/config/orthrus.yml +120 -0
  257. pidsmaker/resources/config/orthrus_fixed.yml +17 -0
  258. pidsmaker/resources/config/orthrus_non_snooped.yml +17 -0
  259. pidsmaker/resources/config/pretrained/README.md +101 -0
  260. pidsmaker/resources/config/pretrained/cybergfm/cybergfm.yml +49 -0
  261. pidsmaker/resources/config/pretrained/pretrained.yml +190 -0
  262. pidsmaker/resources/config/pretrained/pretrained_flash.yml +9 -0
  263. pidsmaker/resources/config/pretrained/pretrained_kairos.yml +12 -0
  264. pidsmaker/resources/config/pretrained/pretrained_magic.yml +1 -0
  265. pidsmaker/resources/config/pretrained/pretrained_nodlink.yml +1 -0
  266. pidsmaker/resources/config/pretrained/pretrained_orthrus.yml +1 -0
  267. pidsmaker/resources/config/pretrained/pretrained_supervised.yml +13 -0
  268. pidsmaker/resources/config/pretrained/pretrained_threatrace.yml +8 -0
  269. pidsmaker/resources/config/pretrained/pretrained_velox.yml +14 -0
  270. pidsmaker/resources/config/prographer.yml +136 -0
  271. pidsmaker/resources/config/rcaid.yml +88 -0
  272. pidsmaker/resources/config/shadewatcher.yml +146 -0
  273. pidsmaker/resources/config/tests.yml +10 -0
  274. pidsmaker/resources/config/threatrace.yml +73 -0
  275. pidsmaker/resources/config/tuned_baselines/optc_net/tuned_argus.yml +4 -0
  276. pidsmaker/resources/config/tuned_baselines/optc_net/tuned_lares.yml +13 -0
  277. pidsmaker/resources/config/velox.yml +10 -0
  278. pidsmaker/resources/config/viz_config.yml +10 -0
  279. pidsmaker/tasks/__init__.py +10 -0
  280. pidsmaker/tasks/batching.py +49 -0
  281. pidsmaker/tasks/construction.py +31 -0
  282. pidsmaker/tasks/evaluation.py +232 -0
  283. pidsmaker/tasks/feat_inference.py +413 -0
  284. pidsmaker/tasks/featurization.py +43 -0
  285. pidsmaker/tasks/training.py +19 -0
  286. pidsmaker/tasks/transformation.py +308 -0
  287. pidsmaker/tasks/triage.py +143 -0
  288. pidsmaker/tgn.py +635 -0
  289. pidsmaker/tokenization/__init__.py +112 -0
  290. pidsmaker/tokenization/base.py +58 -0
  291. pidsmaker/tokenization/bpe_tokenizer.py +83 -0
  292. pidsmaker/tokenization/hf_tokenizer.py +61 -0
  293. pidsmaker/tokenization/hierarchical_tokenizer.py +44 -0
  294. pidsmaker/tokenization/label_tokenizer.py +24 -0
  295. pidsmaker/tokenization/nltk_tokenizer.py +84 -0
  296. pidsmaker/tokenization/substitution.py +295 -0
  297. pidsmaker/triage/__init__.py +0 -0
  298. pidsmaker/triage/tracing_methods/__init__.py +1 -0
  299. pidsmaker/triage/tracing_methods/depimpact.py +213 -0
  300. pidsmaker/triage/tracing_methods/depimpact_utils.py +537 -0
  301. pidsmaker/triage/tracing_methods/ocrapt_subgraph.py +267 -0
  302. pidsmaker/utils/__init__.py +0 -0
  303. pidsmaker/utils/cache_utils.py +256 -0
  304. pidsmaker/utils/data_utils.py +1742 -0
  305. pidsmaker/utils/database.py +204 -0
  306. pidsmaker/utils/dataset_utils.py +413 -0
  307. pidsmaker/utils/dataset_writer.py +1057 -0
  308. pidsmaker/utils/graph_store.py +634 -0
  309. pidsmaker/utils/labelling.py +447 -0
  310. pidsmaker/utils/loss_files.py +193 -0
  311. pidsmaker/utils/process_tags.py +44 -0
  312. pidsmaker/utils/utils.py +730 -0
  313. pidsmaker/vizgen/__init__.py +1 -0
  314. pidsmaker/vizgen/dimensionality_reduction.py +249 -0
  315. pidsmaker/vizgen/embed_exporter.py +467 -0
  316. pidsmaker/vizgen/exporter.py +493 -0
  317. pidsmaker/vizgen/html_builder.py +936 -0
  318. pidsmaker/vizgen/web/__init__.py +1 -0
  319. pidsmaker/vizgen/web/export.py +62 -0
  320. pidsmaker/vizgen/web/static/css/app.css +250 -0
  321. pidsmaker/vizgen/web/static/index.html +182 -0
  322. pidsmaker/vizgen/web/static/js/app.js +627 -0
  323. pidsmaker/vizgen/web/static/js/campaign.js +123 -0
  324. pidsmaker/vizgen/web/static/js/data.js +119 -0
  325. pidsmaker/vizgen/web/static/js/dialogs.js +240 -0
  326. pidsmaker/vizgen/web/static/js/jobs.js +75 -0
  327. pidsmaker/vizgen/web/static/js/scene.js +651 -0
  328. pidsmaker/vizgen/web/static/js/ui.js +370 -0
  329. pidsmaker/vizgen/web/static/vendor/OrbitControls.js +1045 -0
  330. pidsmaker/vizgen/web/static/vendor/d3.v4.min.js +2 -0
  331. pidsmaker/vizgen/web/static/vendor/three.min.js +6 -0
  332. pidsmaker/vizgen/web/viz_server.py +2176 -0
  333. pidsmaker-4.0.0.dist-info/METADATA +596 -0
  334. pidsmaker-4.0.0.dist-info/RECORD +338 -0
  335. pidsmaker-4.0.0.dist-info/WHEEL +5 -0
  336. pidsmaker-4.0.0.dist-info/entry_points.txt +2 -0
  337. pidsmaker-4.0.0.dist-info/licenses/LICENSE +201 -0
  338. pidsmaker-4.0.0.dist-info/top_level.txt +1 -0
pidsmaker/tgn.py ADDED
@@ -0,0 +1,635 @@
1
+ import copy
2
+ from typing import Callable, Dict, Tuple
3
+
4
+ import torch
5
+ from torch import Tensor
6
+ from torch.nn import GRUCell, Linear
7
+ from torch_geometric.nn.inits import zeros
8
+ from torch_geometric.utils import scatter
9
+ from torch_geometric.utils._scatter import scatter_argmax
10
+
11
+ TGNMessageStoreType = Dict[int, Tuple[Tensor, Tensor, Tensor, Tensor]]
12
+
13
+
14
+ class MessageStore:
15
+ """Vectorized per-node message store of TGN.
16
+
17
+ For each node `i`, it holds the events `(src, dst, t, msg)` of the last
18
+ `update()` call where `i` appeared in `src`, like the original PyG store
19
+ `{i: (src, dst, t, msg)}`, but without a Python dict of `num_nodes` entries and
20
+ without per-node Python loops: events are appended to growable buffers and each
21
+ node points to its contiguous slice. Stale slices are compacted lazily.
22
+ `get(n_id)` returns the concatenation of the slices of `n_id`, in the same
23
+ order as the original implementation.
24
+ """
25
+
26
+ def __init__(self, num_nodes: int, msg_dim: int = None, device=None):
27
+ self.num_nodes = num_nodes
28
+ self.msg_dim = msg_dim
29
+ self.device = device
30
+ self.reset()
31
+
32
+ def reset(self, device=None):
33
+ if device is not None:
34
+ self.device = device
35
+ d = self.device
36
+ self.start = torch.zeros(self.num_nodes, dtype=torch.long, device=d)
37
+ self.count = torch.zeros(self.num_nodes, dtype=torch.long, device=d)
38
+ self.size = 0 # number of used rows in the buffers
39
+ self.live = 0 # number of rows referenced by a node
40
+ self._alloc(1024)
41
+
42
+ def _alloc(self, capacity):
43
+ d = self.device
44
+ self.src = torch.empty(capacity, dtype=torch.long, device=d)
45
+ self.dst = torch.empty(capacity, dtype=torch.long, device=d)
46
+ self.t = torch.empty(capacity, dtype=torch.long, device=d)
47
+ self.msg = (
48
+ torch.empty((capacity, self.msg_dim), device=d) if self.msg_dim is not None else None
49
+ )
50
+
51
+ def _to(self, device):
52
+ if self.start.device != device:
53
+ self.device = device
54
+ for k in ["start", "count", "src", "dst", "t", "msg"]:
55
+ v = getattr(self, k)
56
+ if v is not None:
57
+ setattr(self, k, v.to(device))
58
+
59
+ def _compact_and_reserve(self, extra):
60
+ """Keeps only live rows and ensures room for `extra` more rows."""
61
+ if self.size + extra <= self.src.numel():
62
+ return
63
+ if self.live + extra <= self.src.numel() // 2:
64
+ capacity = self.src.numel() # compacting is enough
65
+ else:
66
+ capacity = max(2 * (self.live + extra), 1024)
67
+
68
+ idx, starts = self._gather_index(torch.nonzero(self.count).view(-1))
69
+ src, dst, t = self.src[idx], self.dst[idx], self.t[idx]
70
+ msg = self.msg[idx] if self.msg is not None else None
71
+ nodes = torch.nonzero(self.count).view(-1)
72
+
73
+ self._alloc(capacity)
74
+ n = idx.numel()
75
+ self.src[:n], self.dst[:n], self.t[:n] = src, dst, t
76
+ if msg is not None:
77
+ self.msg[:n] = msg
78
+ self.start[nodes] = starts
79
+ self.size = self.live = n
80
+
81
+ def _gather_index(self, n_id):
82
+ """Returns the buffer rows of the slices of `n_id` (concatenated) and their new starts."""
83
+ counts = self.count[n_id]
84
+ offsets = torch.cumsum(counts, 0) - counts
85
+ total = int(counts.sum())
86
+ # Row k of node j's slice is at `start_j + k`, i.e. `position + (start_j - offset_j)`
87
+ shift = torch.repeat_interleave(self.start[n_id] - offsets, counts, output_size=total)
88
+ idx = torch.arange(total, device=counts.device) + shift
89
+ return idx, offsets
90
+
91
+ def update(self, src: Tensor, dst: Tensor, t: Tensor, raw_msg: Tensor = None):
92
+ self._to(src.device)
93
+ n_id, perm = src.sort()
94
+ n_id, count = n_id.unique_consecutive(return_counts=True)
95
+ num = src.numel()
96
+
97
+ # Rows of the nodes being overwritten become stale
98
+ self.live -= int(self.count[n_id].sum())
99
+ self.count[n_id] = 0
100
+ self._compact_and_reserve(num)
101
+
102
+ lo, hi = self.size, self.size + num
103
+ self.src[lo:hi] = src[perm]
104
+ self.dst[lo:hi] = dst[perm]
105
+ self.t[lo:hi] = t[perm]
106
+ if self.msg is not None:
107
+ self.msg[lo:hi] = raw_msg[perm]
108
+ self.start[n_id] = lo + torch.cumsum(count, 0) - count
109
+ self.count[n_id] = count
110
+ self.size = hi
111
+ self.live += num
112
+
113
+ def get(self, n_id: Tensor):
114
+ self._to(n_id.device)
115
+ idx, _ = self._gather_index(n_id)
116
+ msg = self.msg[idx] if self.msg is not None else None
117
+ return self.src[idx], self.dst[idx], self.t[idx], msg
118
+
119
+
120
+ class LastMessageStore(torch.nn.Module):
121
+ """Message store of TGN for the `LastAggregator`, as dense per-node tensors.
122
+
123
+ `MessageStore` keeps, for each node, all the events of the last `update()` where the node
124
+ was a source, and the `LastAggregator` then only uses the most recent of them (and of the
125
+ events of the other store). This store only keeps that event: for each node, the event with
126
+ the largest timestamp among those of its last `update()` (the last one in order on ties).
127
+ It needs no data-dependent shapes, hence no GPU->CPU synchronization, which dominated the
128
+ time of the TGN on the GPU (a few ms of GPU work per batch of 1024 edges).
129
+
130
+ The tensors are non-persistent buffers: they follow the module's device and are not saved.
131
+ """
132
+
133
+ def __init__(self, num_nodes: int, msg_dim: int):
134
+ super().__init__()
135
+ self.register_buffer("msg", torch.zeros(num_nodes, msg_dim), persistent=False)
136
+ self.register_buffer("other", torch.zeros(num_nodes, dtype=torch.long), persistent=False)
137
+ self.register_buffer("t", torch.zeros(num_nodes, dtype=torch.long), persistent=False)
138
+ self.register_buffer("valid", torch.zeros(num_nodes, dtype=torch.bool), persistent=False)
139
+ # Scratch space of `update`
140
+ self.register_buffer("_best", torch.zeros(num_nodes, dtype=torch.long), persistent=False)
141
+
142
+ def reset(self):
143
+ self.valid.fill_(False)
144
+
145
+ def update(self, node: Tensor, other: Tensor, t: Tensor, raw_msg: Tensor):
146
+ """Stores, for each node of `node`, its event (node, other, t, raw_msg) with the largest
147
+ timestamp (the last one on ties), replacing the previous one."""
148
+ if node.numel() == 0:
149
+ return
150
+ pos = torch.arange(node.numel(), device=node.device)
151
+ best = self._best
152
+ best.scatter_reduce_(0, node, t, reduce="amax", include_self=False)
153
+ is_max = t == best[node]
154
+ best.scatter_reduce_(
155
+ 0, node, torch.where(is_max, pos, -1), reduce="amax", include_self=False
156
+ )
157
+ chosen = best[node] # position of the chosen event of the node of each event
158
+ # Duplicate indices all write the values of the same event
159
+ self.msg[node] = raw_msg[chosen].to(self.msg.dtype)
160
+ self.other[node] = other[chosen]
161
+ self.t[node] = t[chosen]
162
+ # Not `valid[node] = True`: the value would be copied from the host, waiting for the GPU
163
+ self.valid.index_fill_(0, node, True)
164
+
165
+
166
+ class TGNMemory(torch.nn.Module):
167
+ r"""The Temporal Graph Network (TGN) memory model from the
168
+ `"Temporal Graph Networks for Deep Learning on Dynamic Graphs"
169
+ <https://arxiv.org/abs/2006.10637>`_ paper.
170
+
171
+ .. note::
172
+
173
+ For an example of using TGN, see `examples/tgn.py
174
+ <https://github.com/pyg-team/pytorch_geometric/blob/master/examples/
175
+ tgn.py>`_.
176
+
177
+ Args:
178
+ num_nodes (int): The number of nodes to save memories for.
179
+ raw_msg_dim (int): The raw message dimensionality.
180
+ memory_dim (int): The hidden memory dimensionality.
181
+ time_dim (int): The time encoding dimensionality.
182
+ message_module (torch.nn.Module): The message function which
183
+ combines source and destination node memory embeddings, the raw
184
+ message and the time encoding.
185
+ aggregator_module (torch.nn.Module): The message aggregator function
186
+ which aggregates messages to the same destination into a single
187
+ representation.
188
+ """
189
+
190
+ def __init__(
191
+ self,
192
+ num_nodes: int,
193
+ raw_msg_dim: int,
194
+ memory_dim: int,
195
+ time_dim: int,
196
+ message_module: Callable,
197
+ aggregator_module: Callable,
198
+ device,
199
+ dense_last_messages: bool = None,
200
+ ):
201
+ super().__init__()
202
+
203
+ self.num_nodes = num_nodes
204
+ self.raw_msg_dim = raw_msg_dim
205
+ self.memory_dim = memory_dim
206
+ self.time_dim = time_dim
207
+ self.device = device
208
+
209
+ self.msg_s_module = message_module
210
+ self.msg_d_module = copy.deepcopy(message_module)
211
+ self.aggr_module = aggregator_module
212
+ self.time_enc = TimeEncoder(time_dim)
213
+ self.gru = GRUCell(message_module.out_channels, memory_dim)
214
+
215
+ self.register_buffer("memory", torch.empty(num_nodes, memory_dim))
216
+ last_update = torch.empty(self.num_nodes, dtype=torch.long)
217
+ self.register_buffer("last_update", last_update)
218
+ self.register_buffer("_assoc", torch.empty(num_nodes, dtype=torch.long))
219
+
220
+ # With the `LastAggregator`, only the last message of each node is kept (see
221
+ # `LastMessageStore`): same memory, without GPU synchronizations
222
+ if dense_last_messages is None:
223
+ dense_last_messages = isinstance(aggregator_module, LastAggregator)
224
+ self.dense_last_messages = dense_last_messages
225
+ if dense_last_messages:
226
+ if not isinstance(aggregator_module, LastAggregator):
227
+ raise ValueError("`dense_last_messages` requires the `LastAggregator`")
228
+ self.last_msg_s = LastMessageStore(num_nodes, raw_msg_dim)
229
+ self.last_msg_d = LastMessageStore(num_nodes, raw_msg_dim)
230
+ else:
231
+ self.msg_s_store = MessageStore(num_nodes, raw_msg_dim, device)
232
+ self.msg_d_store = MessageStore(num_nodes, raw_msg_dim, device)
233
+
234
+ self.reset_parameters()
235
+
236
+ def reset_parameters(self):
237
+ r"""Resets all learnable parameters of the module."""
238
+ if hasattr(self.msg_s_module, "reset_parameters"):
239
+ self.msg_s_module.reset_parameters()
240
+ if hasattr(self.msg_d_module, "reset_parameters"):
241
+ self.msg_d_module.reset_parameters()
242
+ if hasattr(self.aggr_module, "reset_parameters"):
243
+ self.aggr_module.reset_parameters()
244
+ self.time_enc.reset_parameters()
245
+ self.gru.reset_parameters()
246
+ self.reset_state()
247
+
248
+ def reset_state(self):
249
+ """Resets the memory to its initial state."""
250
+ zeros(self.memory)
251
+ zeros(self.last_update)
252
+ self._reset_message_store()
253
+
254
+ def detach(self):
255
+ """Detaches the memory from gradient computation."""
256
+ self.memory.detach_()
257
+
258
+ def forward(self, n_id: Tensor) -> Tuple[Tensor, Tensor]:
259
+ """Returns, for all nodes :obj:`n_id`, their current memory and their
260
+ last updated timestamp.
261
+ """
262
+ if self.training:
263
+ memory, last_update = self._get_updated_memory(n_id)
264
+ else:
265
+ memory, last_update = self.memory[n_id], self.last_update[n_id]
266
+
267
+ return memory, last_update
268
+
269
+ def update_state(self, src: Tensor, dst: Tensor, t: Tensor, raw_msg: Tensor, n_id=None):
270
+ """Updates the memory with newly encountered interactions
271
+ :obj:`(src, dst, t, raw_msg)`. `n_id`, if given, is `torch.cat([src, dst]).unique()`.
272
+ """
273
+ if n_id is None:
274
+ n_id = torch.cat([src, dst]).unique()
275
+
276
+ if self.training:
277
+ self._update_memory(n_id)
278
+ self._store_messages(src, dst, t, raw_msg)
279
+ else:
280
+ self._store_messages(src, dst, t, raw_msg)
281
+ self._update_memory(n_id)
282
+
283
+ def _store_messages(self, src, dst, t, raw_msg):
284
+ if self.dense_last_messages:
285
+ self.last_msg_s.update(src, dst, t, raw_msg)
286
+ self.last_msg_d.update(dst, src, t, raw_msg)
287
+ else:
288
+ self._update_msg_store(src, dst, t, raw_msg, self.msg_s_store)
289
+ self._update_msg_store(dst, src, t, raw_msg, self.msg_d_store)
290
+
291
+ def _reset_message_store(self):
292
+ if self.dense_last_messages:
293
+ self.last_msg_s.reset()
294
+ self.last_msg_d.reset()
295
+ return
296
+ # Message store format: (src, dst, t, msg)
297
+ self.msg_s_store.reset(self.memory.device)
298
+ self.msg_d_store.reset(self.memory.device)
299
+
300
+ def _update_memory(self, n_id: Tensor):
301
+ memory, last_update = self._get_updated_memory(n_id)
302
+ self.memory[n_id] = memory
303
+ self.last_update[n_id] = last_update
304
+
305
+ def _get_updated_memory(self, n_id: Tensor) -> Tuple[Tensor, Tensor]:
306
+ if self.dense_last_messages:
307
+ return self._get_updated_memory_dense(n_id)
308
+ self._assoc[n_id] = torch.arange(n_id.size(0), device=n_id.device)
309
+
310
+ # Compute messages (src -> dst).
311
+ msg_s, t_s, src_s, dst_s = self._compute_msg(n_id, self.msg_s_store, self.msg_s_module)
312
+
313
+ # Compute messages (dst -> src).
314
+ msg_d, t_d, src_d, dst_d = self._compute_msg(n_id, self.msg_d_store, self.msg_d_module)
315
+
316
+ # Aggregate messages.
317
+ idx = torch.cat([src_s, src_d], dim=0)
318
+ msg = torch.cat([msg_s, msg_d], dim=0)
319
+ t = torch.cat([t_s, t_d], dim=0)
320
+ aggr = self.aggr_module(msg, self._assoc[idx], t, n_id.size(0))
321
+
322
+ # Get local copy of updated memory.
323
+ memory = self.gru(aggr, self.memory[n_id])
324
+
325
+ # Get local copy of updated `last_update`.
326
+ dim_size = self.last_update.size(0)
327
+ last_update = scatter(t, idx, 0, dim_size, reduce="max")[n_id]
328
+
329
+ return memory, last_update
330
+
331
+ def _get_updated_memory_dense(self, n_id: Tensor) -> Tuple[Tensor, Tensor]:
332
+ """`_get_updated_memory` with the `LastMessageStore`: the aggregated message of a node is
333
+ its most recent message (the one of the dst store on ties, which comes last), zeros if
334
+ it has none, and its `last_update` the timestamp of that message (0 if none)."""
335
+ s, d = self.last_msg_s, self.last_msg_d
336
+ memory = self.memory[n_id]
337
+ last_update = self.last_update[n_id]
338
+ valid_s, valid_d = s.valid[n_id], d.valid[n_id]
339
+ t_s, t_d = s.t[n_id], d.t[n_id]
340
+
341
+ def message(store, msg_module, t):
342
+ t_enc = self.time_enc((t - last_update).to(store.msg.dtype))
343
+ return msg_module(memory, self.memory[store.other[n_id]], store.msg[n_id], t_enc)
344
+
345
+ msg_s = message(s, self.msg_s_module, t_s)
346
+ msg_d = message(d, self.msg_d_module, t_d)
347
+
348
+ use_d = valid_d & (~valid_s | (t_d >= t_s))
349
+ has_msg = valid_s | valid_d
350
+ aggr = torch.where(use_d.unsqueeze(1), msg_d, msg_s)
351
+ aggr = torch.where(has_msg.unsqueeze(1), aggr, torch.zeros_like(aggr))
352
+
353
+ new_memory = self.gru(aggr, memory)
354
+ new_last_update = torch.where(use_d, t_d, torch.where(valid_s, t_s, torch.zeros_like(t_s)))
355
+ return new_memory, new_last_update
356
+
357
+ def _update_msg_store(
358
+ self, src: Tensor, dst: Tensor, t: Tensor, raw_msg: Tensor, msg_store: MessageStore
359
+ ):
360
+ msg_store.update(src, dst, t, raw_msg)
361
+
362
+ def _compute_msg(self, n_id: Tensor, msg_store: MessageStore, msg_module: Callable):
363
+ src, dst, t, raw_msg = msg_store.get(n_id)
364
+ t_rel = t - self.last_update[src]
365
+ t_enc = self.time_enc(t_rel.to(raw_msg.dtype))
366
+
367
+ msg = msg_module(self.memory[src], self.memory[dst], raw_msg, t_enc)
368
+
369
+ return msg, t, src, dst
370
+
371
+ def train(self, mode: bool = True):
372
+ """Sets the module in training mode."""
373
+ if self.training and not mode:
374
+ # Flush message store to memory in case we just entered eval mode.
375
+ # NOTE: this line below was originaly here. However, it is called when calling model.eval()
376
+ # during inference and generates a memory overflow on large datasets like CADETS_E5.
377
+ # As we load directly the memory from a pkl file, I don't think we need this line anymore so we
378
+ # removed it. If results become strange in the future, try to add this line back to ensure it
379
+ # doen't affect performance.
380
+ self._flush_all_memory()
381
+ self._reset_message_store()
382
+ super().train(mode)
383
+
384
+ # Nodes whose memory is updated at once when flushing the message store: the aggregated
385
+ # messages of all the nodes of TRACE_E3 (44.5M) take 56 GB of GPU memory, and the update
386
+ # of 2M nodes peaks at 12 GB with Kairos (250K nodes: 1.5 GB, at a similar speed).
387
+ flush_chunk_size = 250_000
388
+
389
+ def _flush_all_memory(self):
390
+ """Updates the memory of all nodes, as `_update_memory` on all nodes, in chunks of nodes.
391
+ Every chunk reads the memory before the update, so the new memory of all chunks is
392
+ computed first (and kept on CPU) before any is written."""
393
+ n_id = torch.arange(self.num_nodes, device=self.memory.device)
394
+ if self.num_nodes <= self.flush_chunk_size:
395
+ self._update_memory(n_id)
396
+ return
397
+ updates = []
398
+ for chunk in n_id.split(self.flush_chunk_size):
399
+ memory, last_update = self._get_updated_memory(chunk)
400
+ updates.append((chunk, memory.detach().cpu(), last_update.cpu()))
401
+ del memory, last_update
402
+ for chunk, memory, last_update in updates:
403
+ self.memory[chunk] = memory.to(self.memory.device)
404
+ self.last_update[chunk] = last_update.to(self.last_update.device)
405
+
406
+
407
+ class TimeEncodingMemory(torch.nn.Module):
408
+ """Custom lightweight class to only memorize past timestamps."""
409
+
410
+ def __init__(self, num_nodes: int, time_dim: int, device):
411
+ super().__init__()
412
+
413
+ self.num_nodes = num_nodes
414
+ self.device = device
415
+ self.time_enc = TimeEncoder(time_dim)
416
+ self.device = device
417
+
418
+ last_update = torch.empty(self.num_nodes, dtype=torch.long)
419
+ self.register_buffer("last_update", last_update)
420
+ self.register_buffer("_assoc", torch.empty(num_nodes, dtype=torch.long))
421
+
422
+ self.msg_s_store = MessageStore(num_nodes, None, device)
423
+ self.msg_d_store = MessageStore(num_nodes, None, device)
424
+
425
+ self.reset_parameters()
426
+
427
+ def reset_parameters(self):
428
+ r"""Resets all learnable parameters of the module."""
429
+ self.time_enc.reset_parameters()
430
+ self.reset_state()
431
+
432
+ def reset_state(self):
433
+ """Resets the memory to its initial state."""
434
+ zeros(self.last_update)
435
+ self._reset_message_store()
436
+
437
+ def update_state(self, src: Tensor, dst: Tensor, t: Tensor, raw_msg: Tensor, n_id=None):
438
+ """Updates the memory with newly encountered interactions
439
+ :obj:`(src, dst, t, raw_msg)`. `n_id`, if given, is `torch.cat([src, dst]).unique()`.
440
+ """
441
+ if n_id is None:
442
+ n_id = torch.cat([src, dst]).unique()
443
+
444
+ if self.training:
445
+ self._update_memory(n_id)
446
+ self._update_msg_store(src, dst, t, raw_msg, self.msg_s_store)
447
+ self._update_msg_store(dst, src, t, raw_msg, self.msg_d_store)
448
+ else:
449
+ self._update_msg_store(src, dst, t, raw_msg, self.msg_s_store)
450
+ self._update_msg_store(dst, src, t, raw_msg, self.msg_d_store)
451
+ self._update_memory(n_id)
452
+
453
+ def _reset_message_store(self):
454
+ # Message store format: (src, dst, t)
455
+ self.msg_s_store.reset(self.last_update.device)
456
+ self.msg_d_store.reset(self.last_update.device)
457
+
458
+ def _update_memory(self, n_id: Tensor):
459
+ last_update = self.get_last_update(n_id)
460
+ self.last_update[n_id] = last_update
461
+
462
+ def _compute_last_update(self, n_id: Tensor, msg_store: MessageStore):
463
+ src, dst, t, _ = msg_store.get(n_id)
464
+ return t, src, dst
465
+
466
+ def get_last_update(self, n_id: Tensor) -> Tensor:
467
+ self._assoc[n_id] = torch.arange(n_id.size(0), device=n_id.device)
468
+
469
+ t_s, src_s, dst_s = self._compute_last_update(n_id, self.msg_s_store)
470
+ t_d, src_d, dst_d = self._compute_last_update(n_id, self.msg_d_store)
471
+
472
+ idx = torch.cat([src_s, src_d], dim=0)
473
+ t = torch.cat([t_s, t_d], dim=0)
474
+ dim_size = self.last_update.size(0)
475
+
476
+ last_update = scatter(t, idx, 0, dim_size, reduce="max")[n_id]
477
+ return last_update
478
+
479
+ def _update_msg_store(
480
+ self, src: Tensor, dst: Tensor, t: Tensor, raw_msg: Tensor, msg_store: MessageStore
481
+ ):
482
+ msg_store.update(src, dst, t)
483
+
484
+ def train(self, mode: bool = True):
485
+ """Sets the module in training mode."""
486
+ if self.training and not mode:
487
+ # Flush message store to memory in case we just entered eval mode.
488
+ # NOTE: this line below was originaly here. However, it is called when calling model.eval()
489
+ # during inference and generates a memory overflow on large datasets like CADETS_E5.
490
+ # As we load directly the memory from a pkl file, I don't think we need this line anymore so we
491
+ # removed it. If results become strange in the future, try to add this line back to ensure it
492
+ # doen't affect performance.
493
+ self._update_memory(torch.arange(self.num_nodes, device=self.device))
494
+ self._reset_message_store()
495
+ super().train(mode)
496
+
497
+
498
+ class IdentityMessage(torch.nn.Module):
499
+ def __init__(self, raw_msg_dim: int, memory_dim: int, time_dim: int):
500
+ super().__init__()
501
+ self.out_channels = raw_msg_dim + 2 * memory_dim + time_dim
502
+
503
+ def forward(self, z_src: Tensor, z_dst: Tensor, raw_msg: Tensor, t_enc: Tensor):
504
+ return torch.cat([z_src, z_dst, raw_msg, t_enc], dim=-1)
505
+
506
+
507
+ class LastAggregator(torch.nn.Module):
508
+ def forward(self, msg: Tensor, index: Tensor, t: Tensor, dim_size: int):
509
+ argmax = scatter_argmax(t, index, dim=0, dim_size=dim_size)
510
+ out = msg.new_zeros((dim_size, msg.size(-1)))
511
+ # Items with at least one entry. Not `argmax < msg.size(0)`: that holds for the argmax of
512
+ # empty items with torch_scatter (`msg.size(0)`), not with the fallback of PyG without it
513
+ # (`dim_size - 1`, the index of another item's message)
514
+ mask = torch.zeros(dim_size, dtype=torch.bool, device=index.device)
515
+ mask.index_fill_(0, index, True)
516
+ out[mask] = msg[argmax[mask]]
517
+ return out
518
+
519
+
520
+ class MeanAggregator(torch.nn.Module):
521
+ def forward(self, msg: Tensor, index: Tensor, t: Tensor, dim_size: int):
522
+ return scatter(msg, index, dim=0, dim_size=dim_size, reduce="mean")
523
+
524
+
525
+ class TimeEncoder(torch.nn.Module):
526
+ def __init__(self, out_channels: int):
527
+ super().__init__()
528
+ self.out_channels = out_channels
529
+ self.lin = Linear(1, out_channels)
530
+
531
+ def reset_parameters(self):
532
+ self.lin.reset_parameters()
533
+
534
+ def forward(self, t: Tensor) -> Tensor:
535
+ return self.lin(t.view(-1, 1)).cos()
536
+
537
+
538
+ class LastNeighborLoader:
539
+ def __init__(self, num_nodes: int, size: int, directed=False, device=None):
540
+ self.size = size
541
+ self.directed = directed
542
+
543
+ self.neighbors = torch.empty((num_nodes, size), dtype=torch.long, device=device)
544
+ self.e_id = torch.empty((num_nodes, size), dtype=torch.long, device=device)
545
+ self._assoc = torch.empty(num_nodes, dtype=torch.long, device=device)
546
+
547
+ self.reset_state()
548
+
549
+ def to(self, device):
550
+ self.neighbors = self.neighbors.to(device)
551
+ self.e_id = self.e_id.to(device)
552
+ self._assoc = self._assoc.to(device)
553
+ return self
554
+
555
+ def __call__(self, n_id: Tensor) -> Tuple[Tensor, Tensor, Tensor]:
556
+ neighbors = self.neighbors[n_id]
557
+ nodes = n_id.view(-1, 1).repeat(1, self.size)
558
+ e_id = self.e_id[n_id]
559
+
560
+ # Filter invalid neighbors (identified by `e_id < 0`).
561
+ mask = e_id >= 0
562
+ neighbors, nodes, e_id = neighbors[mask], nodes[mask], e_id[mask]
563
+
564
+ # Relabel node indices.
565
+ n_id = torch.cat([n_id, neighbors]).unique()
566
+ self._assoc[n_id] = torch.arange(n_id.size(0), device=n_id.device)
567
+ neighbors, nodes = self._assoc[neighbors], self._assoc[nodes]
568
+
569
+ return n_id, torch.stack([neighbors, nodes]), e_id
570
+
571
+ def insert(self, src: Tensor, dst: Tensor):
572
+ # Inserts newly encountered interactions into an ever-growing temporal graph.
573
+
574
+ # Collect central nodes, their neighbors and the current event ids.
575
+ if self.directed:
576
+ # New version: the graph is directed
577
+ nodes = dst
578
+ neighbors = src
579
+ e_id = torch.arange(self.cur_e_id, self.cur_e_id + src.size(0), device=src.device)
580
+ else:
581
+ # Default version: the graph is undirected
582
+ neighbors = torch.cat([src, dst], dim=0)
583
+ nodes = torch.cat([dst, src], dim=0)
584
+ e_id = torch.arange(
585
+ self.cur_e_id, self.cur_e_id + src.size(0), device=src.device
586
+ ).repeat(2)
587
+
588
+ self.cur_e_id += src.numel()
589
+
590
+ # Sort nodes for consistent processing (preserves time order within nodes)
591
+ nodes, perm = nodes.sort()
592
+ neighbors, e_id = neighbors[perm], e_id[perm]
593
+
594
+ # Map nodes to dense indices
595
+ n_id = nodes.unique()
596
+ self._assoc[n_id] = torch.arange(n_id.numel(), device=n_id.device)
597
+
598
+ # Compute the maximum number of edges for any node in the batch
599
+ edge_counts = torch.bincount(self._assoc[nodes], minlength=n_id.numel())
600
+ temp_size = edge_counts.max().item() if edge_counts.numel() > 0 else 1
601
+
602
+ # Compute cumulative start indices
603
+ cum_edge_counts = torch.cat([torch.tensor([0], device=nodes.device), edge_counts.cumsum(0)])
604
+
605
+ # Compute local slot indices per node
606
+ local_slots = torch.arange(nodes.size(0), device=nodes.device) - cum_edge_counts[self._assoc[nodes]]
607
+
608
+ # Compute dense_id
609
+ dense_id = local_slots + (self._assoc[nodes] * temp_size)
610
+
611
+ # Initialize dense tensors with temporary size
612
+ dense_e_id = e_id.new_full((n_id.numel() * temp_size,), -1)
613
+ dense_e_id[dense_id] = e_id
614
+ dense_e_id = dense_e_id.view(-1, temp_size)
615
+
616
+ dense_neighbors = e_id.new_full((n_id.numel() * temp_size,), -1)
617
+ dense_neighbors[dense_id] = neighbors
618
+ dense_neighbors = dense_neighbors.view(-1, temp_size)
619
+
620
+ # Collect new and old interactions
621
+ e_id = torch.cat([self.e_id[n_id, : self.size], dense_e_id], dim=-1)
622
+ neighbors = torch.cat([self.neighbors[n_id, : self.size], dense_neighbors], dim=-1)
623
+
624
+ # Sort by e_id to keep the `size` most recent neighbors
625
+ e_id, perm = e_id.topk(self.size, dim=-1)
626
+ self.e_id[n_id] = e_id
627
+ self.neighbors[n_id] = torch.gather(neighbors, 1, perm)
628
+
629
+ def reset_state(self):
630
+ self.cur_e_id = 0
631
+ self.e_id.fill_(-1)
632
+
633
+ def clear(self):
634
+ """Removes all neighbors, while new edges keep their IDs counting from the last ones."""
635
+ self.e_id.fill_(-1)