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.
Files changed (339) hide show
  1. pidsmaker/__init__.py +1 -0
  2. pidsmaker/cli.py +81 -0
  3. pidsmaker/config/__init__.py +2 -0
  4. pidsmaker/config/config.py +2100 -0
  5. pidsmaker/config/pipeline.py +1824 -0
  6. pidsmaker/config/schemas.py +1032 -0
  7. pidsmaker/datasets.py +323 -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 +255 -0
  18. pidsmaker/detection/evaluation_methods/evaluation_utils.py +1788 -0
  19. pidsmaker/detection/evaluation_methods/host_two_stage_evaluation.py +115 -0
  20. pidsmaker/detection/evaluation_methods/node_evaluation.py +459 -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 +456 -0
  24. pidsmaker/detection/evaluation_methods/tw_evaluation.py +93 -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 +287 -0
  31. pidsmaker/detection/training_methods/ocrapt_early_stop.py +165 -0
  32. pidsmaker/detection/training_methods/threatrace_training.py +168 -0
  33. pidsmaker/detection/training_methods/training_loop.py +383 -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 +30 -0
  67. pidsmaker/featurization/feat_inference_methods/feat_inference_TRW.py +65 -0
  68. pidsmaker/featurization/feat_inference_methods/feat_inference_alacarte.py +14 -0
  69. pidsmaker/featurization/feat_inference_methods/feat_inference_doc2vec.py +53 -0
  70. pidsmaker/featurization/feat_inference_methods/feat_inference_fasttext.py +37 -0
  71. pidsmaker/featurization/feat_inference_methods/feat_inference_flash.py +69 -0
  72. pidsmaker/featurization/feat_inference_methods/feat_inference_graph2vec.py +84 -0
  73. pidsmaker/featurization/feat_inference_methods/feat_inference_ocrapt_features.py +95 -0
  74. pidsmaker/featurization/feat_inference_methods/feat_inference_pretrained.py +1728 -0
  75. pidsmaker/featurization/feat_inference_methods/feat_inference_word2vec.py +55 -0
  76. pidsmaker/featurization/featurization_methods/__init__.py +0 -0
  77. pidsmaker/featurization/featurization_methods/build_trw.py +66 -0
  78. pidsmaker/featurization/featurization_methods/featurization_alacarte.py +747 -0
  79. pidsmaker/featurization/featurization_methods/featurization_doc2vec.py +98 -0
  80. pidsmaker/featurization/featurization_methods/featurization_fasttext.py +74 -0
  81. pidsmaker/featurization/featurization_methods/featurization_flash.py +201 -0
  82. pidsmaker/featurization/featurization_methods/featurization_graph2vec.py +242 -0
  83. pidsmaker/featurization/featurization_methods/featurization_trw.py +114 -0
  84. pidsmaker/featurization/featurization_methods/featurization_word2vec.py +89 -0
  85. pidsmaker/featurization/featurization_utils.py +275 -0
  86. pidsmaker/featurization/utils/build_random_walks.py +66 -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 +478 -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 +825 -0
  113. pidsmaker/preprocessing/build_graph_methods/build_magic_graphs.py +216 -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 +1427 -0
  131. pidsmaker/pretrained/embedding_generator.py +252 -0
  132. pidsmaker/pretrained/finetune.py +1434 -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 +275 -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/config/anomal_e.yml +25 -0
  164. pidsmaker/resources/config/argus.yml +56 -0
  165. pidsmaker/resources/config/attack_edges/cadets_e3.yml +435 -0
  166. pidsmaker/resources/config/attack_edges/cadets_e5.yml +407 -0
  167. pidsmaker/resources/config/attack_edges/theia_e3.yml +382 -0
  168. pidsmaker/resources/config/attack_edges/theia_e5.yml +387 -0
  169. pidsmaker/resources/config/attack_edges/trace_e3.yml +415 -0
  170. pidsmaker/resources/config/attack_edges/trace_e5.yml +417 -0
  171. pidsmaker/resources/config/default.yml +315 -0
  172. pidsmaker/resources/config/egraphsage.yml +95 -0
  173. pidsmaker/resources/config/euler.yml +104 -0
  174. pidsmaker/resources/config/eval/eval_set_clustering.json +3170 -0
  175. pidsmaker/resources/config/experiments/tuning/components/tuning_featurization_methods.yml +29 -0
  176. pidsmaker/resources/config/experiments/tuning/systems/clearscope_e5/tuning_orthrus.yml +14 -0
  177. pidsmaker/resources/config/experiments/tuning/systems/default/tuning_default_baselines.yml +13 -0
  178. pidsmaker/resources/config/experiments/tuning/systems/default/tuning_orthrus_fixed.yml +16 -0
  179. pidsmaker/resources/config/experiments/uncertainty/none.yml +5 -0
  180. pidsmaker/resources/config/experiments/uncertainty/run_n_times.yml +12 -0
  181. pidsmaker/resources/config/experiments/uncertainty/run_n_times_hyperparameters.yml +12 -0
  182. pidsmaker/resources/config/experiments/uncertainty/uncertainty.yml +22 -0
  183. pidsmaker/resources/config/flash.yml +79 -0
  184. pidsmaker/resources/config/jbeil.yml +65 -0
  185. pidsmaker/resources/config/kairos.yml +121 -0
  186. pidsmaker/resources/config/lares.yml +115 -0
  187. pidsmaker/resources/config/magic.yml +86 -0
  188. pidsmaker/resources/config/nodlink.yml +79 -0
  189. pidsmaker/resources/config/ocrapt.yml +91 -0
  190. pidsmaker/resources/config/orthrus.yml +126 -0
  191. pidsmaker/resources/config/orthrus_fixed.yml +17 -0
  192. pidsmaker/resources/config/pretrained/README.md +101 -0
  193. pidsmaker/resources/config/pretrained/cybergfm/cybergfm.yml +49 -0
  194. pidsmaker/resources/config/pretrained/pretrained.yml +190 -0
  195. pidsmaker/resources/config/pretrained/pretrained_flash.yml +9 -0
  196. pidsmaker/resources/config/pretrained/pretrained_kairos.yml +12 -0
  197. pidsmaker/resources/config/pretrained/pretrained_magic.yml +1 -0
  198. pidsmaker/resources/config/pretrained/pretrained_nodlink.yml +1 -0
  199. pidsmaker/resources/config/pretrained/pretrained_orthrus.yml +1 -0
  200. pidsmaker/resources/config/pretrained/pretrained_supervised.yml +13 -0
  201. pidsmaker/resources/config/pretrained/pretrained_threatrace.yml +8 -0
  202. pidsmaker/resources/config/pretrained/pretrained_velox.yml +14 -0
  203. pidsmaker/resources/config/prographer.yml +136 -0
  204. pidsmaker/resources/config/rcaid.yml +88 -0
  205. pidsmaker/resources/config/shadewatcher.yml +146 -0
  206. pidsmaker/resources/config/tests.yml +10 -0
  207. pidsmaker/resources/config/threatrace.yml +73 -0
  208. pidsmaker/resources/config/tuned_baselines/optc_net/tuned_argus.yml +4 -0
  209. pidsmaker/resources/config/tuned_baselines/optc_net/tuned_lares.yml +13 -0
  210. pidsmaker/resources/config/velox.yml +10 -0
  211. pidsmaker/resources/config/viz_config.yml +10 -0
  212. pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_06.csv +8 -0
  213. pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_11.csv +4 -0
  214. pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_12.csv +43 -0
  215. pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_13.csv +24 -0
  216. pidsmaker/resources/ground_truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0411.csv +41 -0
  217. pidsmaker/resources/ground_truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0412.csv +0 -0
  218. pidsmaker/resources/ground_truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_browser_0412.csv +1 -0
  219. pidsmaker/resources/ground_truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +63 -0
  220. pidsmaker/resources/ground_truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +56 -0
  221. pidsmaker/resources/ground_truth/orthrus/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +61 -0
  222. pidsmaker/resources/ground_truth/orthrus/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +58 -0
  223. pidsmaker/resources/ground_truth/orthrus/E3-TRACE/node_trace_e3_firefox_0410.csv +11 -0
  224. pidsmaker/resources/ground_truth/orthrus/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +11 -0
  225. pidsmaker/resources/ground_truth/orthrus/E3-TRACE/node_trace_e3_pine_0413.csv +14 -0
  226. pidsmaker/resources/ground_truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT.csv +19 -0
  227. pidsmaker/resources/ground_truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT_17.csv +107 -0
  228. pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_appstarter_0515.csv +26 -0
  229. pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_firefox_0517.csv +1 -0
  230. pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_lockwatch_0517.csv +17 -0
  231. pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_tester_0517.csv +8 -0
  232. pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_bits_0515.csv +54 -0
  233. pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_copykatz_0509.csv +87 -0
  234. pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_dns_0517.csv +11 -0
  235. pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_drakon_0517.csv +6 -0
  236. pidsmaker/resources/ground_truth/orthrus/E5-THEIA/node_THEIA_1_Firefox_Drakon_APT_BinFmt_Elevate_Inject.csv +70 -0
  237. pidsmaker/resources/ground_truth/orthrus/E5-TRACE/node_Trace_Firefox_Drakon.csv +71 -0
  238. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m1.csv +1 -0
  239. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m2.csv +1 -0
  240. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m3.csv +1 -0
  241. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m4.csv +5 -0
  242. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m5.csv +23 -0
  243. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m6.csv +18 -0
  244. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s1.csv +1 -0
  245. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s2.csv +1 -0
  246. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s3.csv +16 -0
  247. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s4.csv +22 -0
  248. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m1.csv +126 -0
  249. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m2.csv +105 -0
  250. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m3.csv +94 -0
  251. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m4.csv +139 -0
  252. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m5.csv +228 -0
  253. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m6.csv +131 -0
  254. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s1.csv +118 -0
  255. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s2.csv +89 -0
  256. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s3.csv +133 -0
  257. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s4.csv +135 -0
  258. pidsmaker/resources/ground_truth/orthrus/carbanakv2_edr/carbanakv2_edr.csv +2453 -0
  259. pidsmaker/resources/ground_truth/orthrus/h051/node_h051_0925.csv +114 -0
  260. pidsmaker/resources/ground_truth/orthrus/h201/node_h201_0923.csv +2905 -0
  261. pidsmaker/resources/ground_truth/orthrus/h501/node_h501_0924.csv +749 -0
  262. pidsmaker/resources/ground_truth/orthrus/readme.md +98 -0
  263. pidsmaker/resources/ground_truth/reapr/E3-CADETS/node_Nginx_Backdoor_06.csv +3 -0
  264. pidsmaker/resources/ground_truth/reapr/E3-CADETS/node_Nginx_Backdoor_12.csv +655 -0
  265. pidsmaker/resources/ground_truth/reapr/E3-CADETS/node_Nginx_Backdoor_13.csv +770 -0
  266. pidsmaker/resources/ground_truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +0 -0
  267. pidsmaker/resources/ground_truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +18 -0
  268. pidsmaker/resources/ground_truth/reapr/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +42 -0
  269. pidsmaker/resources/ground_truth/reapr/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +81 -0
  270. pidsmaker/resources/ground_truth/reapr/E3-TRACE/node_trace_e3_firefox_0410.csv +37 -0
  271. pidsmaker/resources/ground_truth/reapr/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +9 -0
  272. pidsmaker/resources/ground_truth/reapr/E3-TRACE/node_trace_e3_pine_0413.csv +40 -0
  273. pidsmaker/resources/ground_truth/threatrace/E3-CADETS/ground_truth.txt +12858 -0
  274. pidsmaker/resources/ground_truth/threatrace/E3-FIVEDIRECTIONS/ground_truth.txt +18420 -0
  275. pidsmaker/resources/ground_truth/threatrace/E3-THEIA/ground_truth.txt +25363 -0
  276. pidsmaker/resources/ground_truth/threatrace/E3-TRACE/ground_truth.txt +68265 -0
  277. pidsmaker/resources/ground_truth/threatrace/README.md +123 -0
  278. pidsmaker/tasks/__init__.py +10 -0
  279. pidsmaker/tasks/batching.py +47 -0
  280. pidsmaker/tasks/construction.py +31 -0
  281. pidsmaker/tasks/evaluation.py +241 -0
  282. pidsmaker/tasks/feat_inference.py +413 -0
  283. pidsmaker/tasks/featurization.py +43 -0
  284. pidsmaker/tasks/training.py +17 -0
  285. pidsmaker/tasks/transformation.py +306 -0
  286. pidsmaker/tasks/triage.py +143 -0
  287. pidsmaker/tgn.py +635 -0
  288. pidsmaker/tokenization/__init__.py +112 -0
  289. pidsmaker/tokenization/base.py +58 -0
  290. pidsmaker/tokenization/bpe_tokenizer.py +83 -0
  291. pidsmaker/tokenization/hf_tokenizer.py +61 -0
  292. pidsmaker/tokenization/hierarchical_tokenizer.py +44 -0
  293. pidsmaker/tokenization/label_tokenizer.py +24 -0
  294. pidsmaker/tokenization/nltk_tokenizer.py +84 -0
  295. pidsmaker/tokenization/substitution.py +295 -0
  296. pidsmaker/triage/__init__.py +0 -0
  297. pidsmaker/triage/tracing_methods/__init__.py +1 -0
  298. pidsmaker/triage/tracing_methods/depimpact.py +213 -0
  299. pidsmaker/triage/tracing_methods/depimpact_utils.py +537 -0
  300. pidsmaker/triage/tracing_methods/ocrapt_subgraph.py +267 -0
  301. pidsmaker/utils/__init__.py +0 -0
  302. pidsmaker/utils/cache_utils.py +256 -0
  303. pidsmaker/utils/console.py +282 -0
  304. pidsmaker/utils/data_utils.py +1742 -0
  305. pidsmaker/utils/database.py +150 -0
  306. pidsmaker/utils/dataset_utils.py +413 -0
  307. pidsmaker/utils/dataset_writer.py +570 -0
  308. pidsmaker/utils/graph_store.py +634 -0
  309. pidsmaker/utils/labelling.py +445 -0
  310. pidsmaker/utils/loss_files.py +193 -0
  311. pidsmaker/utils/process_tags.py +44 -0
  312. pidsmaker/utils/utils.py +712 -0
  313. pidsmaker/vizgen/__init__.py +1 -0
  314. pidsmaker/vizgen/backfill_manifests.py +100 -0
  315. pidsmaker/vizgen/dimensionality_reduction.py +249 -0
  316. pidsmaker/vizgen/embed_exporter.py +467 -0
  317. pidsmaker/vizgen/exporter.py +493 -0
  318. pidsmaker/vizgen/html_builder.py +936 -0
  319. pidsmaker/vizgen/web/__init__.py +1 -0
  320. pidsmaker/vizgen/web/export.py +62 -0
  321. pidsmaker/vizgen/web/static/css/app.css +250 -0
  322. pidsmaker/vizgen/web/static/index.html +182 -0
  323. pidsmaker/vizgen/web/static/js/app.js +627 -0
  324. pidsmaker/vizgen/web/static/js/campaign.js +123 -0
  325. pidsmaker/vizgen/web/static/js/data.js +119 -0
  326. pidsmaker/vizgen/web/static/js/dialogs.js +240 -0
  327. pidsmaker/vizgen/web/static/js/jobs.js +75 -0
  328. pidsmaker/vizgen/web/static/js/scene.js +651 -0
  329. pidsmaker/vizgen/web/static/js/ui.js +370 -0
  330. pidsmaker/vizgen/web/static/vendor/OrbitControls.js +1045 -0
  331. pidsmaker/vizgen/web/static/vendor/d3.v4.min.js +2 -0
  332. pidsmaker/vizgen/web/static/vendor/three.min.js +6 -0
  333. pidsmaker/vizgen/web/viz_server.py +2176 -0
  334. pidsmaker-5.0.0.dist-info/METADATA +597 -0
  335. pidsmaker-5.0.0.dist-info/RECORD +339 -0
  336. pidsmaker-5.0.0.dist-info/WHEEL +5 -0
  337. pidsmaker-5.0.0.dist-info/entry_points.txt +2 -0
  338. pidsmaker-5.0.0.dist-info/licenses/LICENSE +201 -0
  339. pidsmaker-5.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,98 @@
1
+ """Doc2Vec-based node featurization with neighborhood awareness.
2
+
3
+ Doc2Vec learns representations considering node neighborhoods, capturing both node
4
+ identity and local graph structure. Used by systems like Orthrus and R-Caid for
5
+ context-aware embeddings in provenance graphs.
6
+ """
7
+
8
+ import os
9
+
10
+ from gensim.models.doc2vec import Doc2Vec
11
+
12
+ from pidsmaker.featurization.featurization_utils import (
13
+ get_corpus,
14
+ get_corpus_using_neighbors_features,
15
+ )
16
+ from pidsmaker.utils.process_tags import truncate_process_name
17
+ from pidsmaker.utils.utils import log
18
+
19
+
20
+ def doc2vec_label_fn(cfg):
21
+ """Function replacing the label of a node before computing its features, or None."""
22
+ if not getattr(cfg.featurization.doc2vec, "truncate_process_name", None):
23
+ return None
24
+
25
+ def label_fn(node_type, label):
26
+ return truncate_process_name(label) if node_type == "subject" else label
27
+
28
+ return label_fn
29
+
30
+
31
+ def doc2vec(
32
+ cfg,
33
+ tagged_data,
34
+ model_save_path: str,
35
+ epochs: int,
36
+ emb_dim: int,
37
+ alpha: float,
38
+ dm: int = 1,
39
+ workers: int = 3,
40
+ ):
41
+ """Train Doc2Vec model on graph corpus.
42
+
43
+ Args:
44
+ cfg: Configuration object
45
+ tagged_data: Tagged documents (walks with node identifiers), a list or a re-iterable
46
+ corpus (iterated once to build the vocabulary, then once per epoch)
47
+ model_save_path: Path to save model
48
+ epochs: Training epochs
49
+ emb_dim: Embedding dimension
50
+ alpha: Learning rate
51
+ dm: 1 for PV-DM, 0 for PV-DBOW
52
+
53
+ Returns:
54
+ Doc2Vec: Trained model
55
+ """
56
+ SEED = 0
57
+ model = Doc2Vec(
58
+ vector_size=emb_dim, alpha=alpha, min_count=1, dm=dm, compute_loss=True, seed=SEED,
59
+ workers=workers,
60
+ )
61
+ model.build_vocab(tagged_data)
62
+
63
+ log("Training Doc2vec...")
64
+ model.train(tagged_data, total_examples=model.corpus_count, epochs=epochs, compute_loss=True)
65
+
66
+ log(f"Saving Doc2Vec model to {model_save_path}")
67
+ os.makedirs(model_save_path, exist_ok=True)
68
+ model.save(os.path.join(model_save_path, "doc2vec_model.model"))
69
+ return model
70
+
71
+
72
+ def main(cfg):
73
+ model_save_path = cfg.featurization._model_dir
74
+
75
+ # Context-aware Doc2vec embedding that considers the neighbors when creating embedding (like in Rcaid)
76
+ if cfg.featurization.doc2vec.include_neighbors:
77
+ if doc2vec_label_fn(cfg) is not None:
78
+ raise ValueError("`truncate_process_name` is not supported with `include_neighbors`")
79
+ tagged_data = get_corpus_using_neighbors_features(cfg, doc2vec_format=True)
80
+
81
+ # Standard token-level Doc2vec
82
+ else:
83
+ tagged_data = get_corpus(cfg, doc2vec_format=True, label_fn=doc2vec_label_fn(cfg))
84
+
85
+ epochs = cfg.featurization.epochs
86
+ emb_dim = cfg.featurization.emb_dim
87
+ alpha = cfg.featurization.doc2vec.alpha
88
+
89
+ log("Start building and training Doc2Vec model...")
90
+ doc2vec(
91
+ tagged_data=tagged_data,
92
+ model_save_path=model_save_path,
93
+ epochs=epochs,
94
+ emb_dim=emb_dim,
95
+ alpha=alpha,
96
+ workers=cfg.featurization.doc2vec.workers,
97
+ cfg=cfg,
98
+ )
@@ -0,0 +1,74 @@
1
+ import os
2
+
3
+ import wget
4
+ from gensim.models import FastText
5
+ from gensim.models.fasttext import load_facebook_model
6
+
7
+ from pidsmaker.featurization.featurization_utils import get_corpus
8
+ from pidsmaker.utils.utils import log
9
+
10
+
11
+ def download_facebook_weights(out_dir):
12
+ url = "https://dl.fbaipublicfiles.com/fasttext/vectors-crawl/cc.en.300.bin.gz"
13
+
14
+ if not os.path.exists(out_dir):
15
+ wget.download(url, out_dir)
16
+
17
+
18
+ def train_fasttext(corpus, cfg):
19
+ emb_dim = cfg.featurization.emb_dim
20
+ epochs = cfg.featurization.epochs
21
+ window_size = cfg.featurization.fasttext.window_size
22
+ alpha = cfg.featurization.fasttext.alpha
23
+ min_count = cfg.featurization.fasttext.min_count
24
+ num_workers = cfg.featurization.fasttext.num_workers
25
+ negative = cfg.featurization.fasttext.negative
26
+ SEED = cfg.featurization.seed
27
+
28
+ use_pretrained_fb_model = cfg.featurization.fasttext.use_pretrained_fb_model
29
+
30
+ if use_pretrained_fb_model:
31
+ out_dir = os.path.join(cfg._artifact_dir, "fasttext_facebook_cc.en.300.bin.gz")
32
+
33
+ log("Downloading Facebook's FastText model...")
34
+ download_facebook_weights(out_dir)
35
+ log("Loading Facebook's FastText model...")
36
+ model = load_facebook_model(out_dir)
37
+
38
+ else:
39
+ model = FastText(
40
+ min_count=min_count,
41
+ vector_size=emb_dim,
42
+ workers=num_workers,
43
+ alpha=alpha,
44
+ window=window_size,
45
+ negative=negative,
46
+ seed=SEED,
47
+ )
48
+
49
+ model.build_vocab(corpus, update=use_pretrained_fb_model)
50
+ if len(model.wv) == 0:
51
+ raise ValueError(
52
+ f"FastText: no token of the node labels appears at least min_count={min_count} times. "
53
+ "This happens when labels are unique identifiers (e.g. host names in network datasets): "
54
+ "lower `featurization.fasttext.min_count` or use another featurization."
55
+ )
56
+ model.train(corpus, epochs=epochs, total_examples=len(corpus))
57
+
58
+ return model
59
+
60
+
61
+ def main(cfg):
62
+
63
+ multi_dataset_training = cfg.featurization.multi_dataset_training
64
+ corpus = get_corpus(cfg, gather_multi_dataset=multi_dataset_training)
65
+
66
+ log("Training FastText model...")
67
+ model = train_fasttext(
68
+ corpus=corpus,
69
+ cfg=cfg,
70
+ )
71
+
72
+ model_save_path = cfg.featurization._model_dir
73
+ os.makedirs(model_save_path, exist_ok=True)
74
+ model.save(os.path.join(model_save_path, "fasttext.pkl"))
@@ -0,0 +1,201 @@
1
+ import os
2
+ from collections import defaultdict
3
+ from itertools import chain
4
+
5
+ import numpy as np
6
+ import torch
7
+ from gensim.models import Word2Vec
8
+
9
+ from pidsmaker.featurization.featurization_utils import get_splits_to_train_featurization
10
+ from pidsmaker.tokenization import fit_tokenizer, load_tokenizer
11
+ from pidsmaker.utils.graph_store import load_graph_columns
12
+ from pidsmaker.utils.utils import (
13
+ get_all_graphs_for_dates,
14
+ get_indexid2msg,
15
+ log,
16
+ log_tqdm,
17
+ )
18
+
19
+
20
+ # Each edge gives 3 texts to its source and destination nodes; a node keeps the texts of its
21
+ # first edges (in time order) of each graph, up to this number of texts
22
+ MAX_TEXTS_PER_NODE = 300
23
+
24
+
25
+ def _edge_columns(file_path):
26
+ """(node IDs, src and dst node positions, edge labels, edge times) of a stored graph, in
27
+ `graph.edges` order."""
28
+ cols = load_graph_columns(file_path)
29
+ if cols is not None:
30
+ return (
31
+ cols.node_ids,
32
+ cols.src.astype(np.int64),
33
+ cols.dst.astype(np.int64),
34
+ cols.edge_attrs["label"] if len(cols.src) else [],
35
+ cols.edge_attrs["time"] if len(cols.src) else [],
36
+ )
37
+ graph = torch.load(file_path)
38
+ nodes = list(graph.nodes)
39
+ pos = {n: i for i, n in enumerate(nodes)}
40
+ src, dst, labels, times = [], [], [], []
41
+ for u, v, key, attr in graph.edges(data=True, keys=True):
42
+ src.append(pos[u])
43
+ dst.append(pos[v])
44
+ labels.append(attr["label"])
45
+ times.append(attr["time"])
46
+ return nodes, np.array(src, dtype=np.int64), np.array(dst, dtype=np.int64), labels, times
47
+
48
+
49
+ def _time_order(times):
50
+ """Edge indices sorted by `int(time)` (stable, as `sorted`)."""
51
+ times = [int(t) for t in times]
52
+ try:
53
+ return np.argsort(np.array(times, dtype=np.int64), kind="stable")
54
+ except OverflowError:
55
+ return np.array(sorted(range(len(times)), key=times.__getitem__), dtype=np.int64)
56
+
57
+
58
+ def _graph_texts(file_path, indexid2msg, text_ids):
59
+ """Texts of the nodes of one graph.
60
+
61
+ Returns (node IDs, edges, triplets): the nodes in order of first appearance in
62
+ the edges sorted by time; for each node, the (time-sorted) indices of the edges whose texts
63
+ it keeps (its first MAX_TEXTS_PER_NODE / 3 edges, a self-loop counting twice); and for each
64
+ edge the IDs in `text_ids` of its 3 texts (src, edge type, dst). `text_ids` maps each text
65
+ (node type or None, label) to an ID, and is extended with the new texts.
66
+ """
67
+ nodes, src, dst, labels, times = _edge_columns(file_path)
68
+ m = len(src)
69
+ order = _time_order(times)
70
+ src, dst = src[order], dst[order]
71
+ labels = [labels[i] for i in order.tolist()]
72
+
73
+ # Texts: (node type, label) of the endpoints, (None, edge type) of the edges
74
+ used = np.unique(np.concatenate([src, dst])).tolist()
75
+ node_text = np.zeros(len(nodes), dtype=np.int64)
76
+ for i in used:
77
+ node_type, msg = indexid2msg[nodes[i]]
78
+ node_text[i] = text_ids.setdefault((node_type, msg), len(text_ids))
79
+ op_text = np.array(
80
+ [text_ids.setdefault((None, op), len(text_ids)) for op in labels], dtype=np.int64
81
+ )
82
+ triplets = np.stack([node_text[src], op_text, node_text[dst]], axis=1).reshape(m, 3)
83
+
84
+ # Incidences of the nodes: (src of edge 0, dst of edge 0, src of edge 1, ...). A node keeps
85
+ # the texts of its first incidences
86
+ inc = np.empty(2 * m, dtype=np.int64)
87
+ inc[0::2], inc[1::2] = src, dst
88
+ by_node = np.argsort(inc, kind="stable")
89
+ sorted_nodes = inc[by_node]
90
+ starts = np.flatnonzero(np.r_[m > 0, sorted_nodes[1:] != sorted_nodes[:-1]])
91
+ sizes = np.diff(np.append(starts, 2 * m))
92
+ rank = np.arange(2 * m) - np.repeat(starts, sizes)
93
+ max_edges = -(-MAX_TEXTS_PER_NODE // 3) # texts are added 3 by 3 while there are fewer than MAX
94
+ kept = rank < max_edges
95
+ kept_edges = by_node[kept] // 2
96
+ kept_sizes = np.minimum(sizes, max_edges)
97
+
98
+ # Nodes in order of first incidence
99
+ node_order = np.argsort(by_node[starts], kind="stable")
100
+ group_nodes = sorted_nodes[starts].tolist()
101
+ bounds = np.r_[0, np.cumsum(kept_sizes)].tolist()
102
+ node_ids, node_edges = [], []
103
+ for g in node_order.tolist():
104
+ node_ids.append(nodes[group_nodes[g]])
105
+ node_edges.append(kept_edges[bounds[g] : bounds[g + 1]])
106
+ return node_ids, node_edges, triplets
107
+
108
+
109
+ def get_node2corpus(cfg, splits, fit=False):
110
+ """
111
+ Returns for each node the tokens of the (src label, edge type, dst label) triplets
112
+ of its edges. With `fit=True`, the tokenizer is fitted on these texts (featurization),
113
+ otherwise the tokenizer fitted during featurization is loaded (feat_inference).
114
+ """
115
+ indexid2msg = get_indexid2msg(cfg)
116
+
117
+ dates = list(chain.from_iterable([getattr(cfg.dataset, f"{split}_dates") for split in splits]))
118
+ sorted_paths = get_all_graphs_for_dates(cfg.transformation._graphs_dir, dates)
119
+
120
+ # Texts, numbered in order of first appearance in the graphs
121
+ text_ids = {}
122
+ data_of_graphs = []
123
+ for file_path in log_tqdm(sorted_paths, desc=f"Loading training data for {str(splits)}"):
124
+ data_of_graphs.append(_graph_texts(file_path, indexid2msg, text_ids))
125
+ texts = list(text_ids)
126
+ del text_ids
127
+
128
+ # Texts in order of first appearance in the nodes' texts (graph by graph, node by node)
129
+ seen = np.zeros(len(texts), dtype=bool)
130
+ text_order = []
131
+ for _, node_edges, triplets in data_of_graphs:
132
+ if not node_edges:
133
+ continue
134
+ seq = triplets[np.concatenate(node_edges)].ravel()
135
+ uniq, first = np.unique(seq, return_index=True)
136
+ uniq = uniq[np.argsort(first, kind="stable")]
137
+ uniq = uniq[~seen[uniq]]
138
+ seen[uniq] = True
139
+ text_order.extend(uniq.tolist())
140
+
141
+ if fit:
142
+ tokenizer = fit_tokenizer(cfg, [texts[i] for i in text_order])
143
+ else:
144
+ tokenizer = load_tokenizer(cfg)
145
+
146
+ # Tokens of each text, tokenized in order of first appearance
147
+ tokens_of = [None] * len(texts)
148
+ for i in log_tqdm(text_order, desc="Tokenizing corpus"):
149
+ text_type, sentence = texts[i]
150
+ tokens_of[i] = tokenizer.tokenize(sentence, text_type)
151
+
152
+ node2corpus = defaultdict(list)
153
+ triplet_tokens = {}
154
+ for node_ids, node_edges, triplets in data_of_graphs:
155
+ if not node_ids:
156
+ continue
157
+ # Tokens of the distinct (src, edge type, dst) text triplets of the graph
158
+ uniq, inverse = np.unique(triplets, axis=0, return_inverse=True)
159
+ inverse = inverse.reshape(-1)
160
+ uniq_tokens = []
161
+ for a, b, c in uniq.tolist():
162
+ key = (a, b, c)
163
+ tokens = triplet_tokens.get(key)
164
+ if tokens is None:
165
+ tokens = triplet_tokens[key] = tokens_of[a] + tokens_of[b] + tokens_of[c]
166
+ uniq_tokens.append(tokens)
167
+ for node_id, edges in zip(node_ids, node_edges):
168
+ extend = node2corpus[node_id].extend
169
+ for t in inverse[edges].tolist():
170
+ extend(uniq_tokens[t])
171
+
172
+ return node2corpus
173
+
174
+
175
+ class RepeatableIterator:
176
+ def __init__(self, data):
177
+ self.data = data
178
+
179
+ def __iter__(self):
180
+ for phrases in self.data:
181
+ yield phrases
182
+
183
+
184
+ def main(cfg):
185
+
186
+ training_files = get_splits_to_train_featurization(cfg)
187
+ all_phrases = list(get_node2corpus(cfg=cfg, splits=training_files, fit=True).values())
188
+
189
+ emb_dim = cfg.featurization.emb_dim
190
+ epochs = cfg.featurization.epochs
191
+ min_count = cfg.featurization.flash.min_count
192
+ workers = cfg.featurization.flash.workers
193
+
194
+ log("Training word2vec model...")
195
+ model = Word2Vec(vector_size=emb_dim, min_count=min_count, workers=workers, epochs=epochs)
196
+ model.build_vocab(RepeatableIterator(all_phrases), progress_per=10000)
197
+ model.train(RepeatableIterator(all_phrases), total_examples=model.corpus_count, epochs=epochs)
198
+
199
+ model_save_dir = cfg.featurization._model_dir
200
+ os.makedirs(model_save_dir, exist_ok=True)
201
+ model.save(os.path.join(model_save_dir, "word2vec_model_final.model"))
@@ -0,0 +1,242 @@
1
+ """graph2vec embedding of whole time-window graphs (snapshots), as in ProGrapher.
2
+
3
+ Each snapshot is a "document" whose "words" are the rooted subgraphs (RSGs) of all its nodes,
4
+ extracted with the Weisfeiler-Lehman (WL) relabeling of ProGrapher (Algorithm 2 of the paper):
5
+ the RSG of a node at depth 0 is its type; at depth d, it combines its RSG at depth d-1 with the
6
+ set of RSGs at depth d-1 of its neighbors and the set of types of its edges. The graph is
7
+ considered undirected, and only node and edge types are used (no textual labels).
8
+
9
+ A doc2vec model (PV-DBOW with negative sampling) learns one vector per snapshot that predicts
10
+ its RSGs. The RSGs act as output vectors (`syn1neg`), later used to rank the RSGs of an anomalous
11
+ snapshot (key indicators, see `objectives/predict_snapshot_embedding.py`).
12
+
13
+ gensim truncates documents to 10,000 words, whereas snapshots have `(depth + 1)` words per node:
14
+ documents are therefore split into chunks of 10,000 words that share the same tag in training,
15
+ and the embedding of a snapshot is inferred over all its chunks (`infer_snapshot_embedding`).
16
+ """
17
+
18
+ import hashlib
19
+ import os
20
+ from concurrent.futures import ProcessPoolExecutor
21
+ from itertools import chain
22
+
23
+ import numpy as np
24
+ import torch
25
+ from gensim.models.doc2vec import Doc2Vec, TaggedDocument
26
+ from gensim.models.doc2vec_inner import train_document_dbow
27
+ from gensim.models.keyedvectors import pseudorandom_weak_vector
28
+
29
+ from pidsmaker.featurization.featurization_utils import get_splits_to_train_featurization
30
+ from pidsmaker.utils.graph_store import load_graph_columns
31
+ from pidsmaker.utils.utils import get_all_graphs_for_dates, log, log_tqdm
32
+
33
+ # Maximum number of words of a document processed by gensim (`MAX_DOCUMENT_LEN`)
34
+ GENSIM_MAX_DOCUMENT_LEN = 10000
35
+ MODEL_FILE = "graph2vec.model"
36
+
37
+
38
+ def snapshot_columns(path):
39
+ """Node IDs (sorted), node types, edge endpoints (as rows of the node IDs) and edge types
40
+ of the graph stored at `path`."""
41
+ cols = load_graph_columns(path)
42
+ if cols is not None:
43
+ node_ids = np.asarray([int(n) for n in cols.node_ids], dtype=np.int64)
44
+ node_types = [str(t) for t in cols.node_attrs["node_type"]]
45
+ src = np.asarray(cols.src, dtype=np.int64)
46
+ dst = np.asarray(cols.dst, dtype=np.int64)
47
+ edge_types = [str(e) for e in cols.edge_attrs["label"]]
48
+ else: # legacy graphs stored as pickled networkx graphs
49
+ graph = torch.load(path)
50
+ nodes = list(graph.nodes)
51
+ node2row = {n: i for i, n in enumerate(nodes)}
52
+ node_ids = np.asarray([int(n) for n in nodes], dtype=np.int64)
53
+ node_types = [str(graph.nodes[n]["node_type"]) for n in nodes]
54
+ src, dst, edge_types = [], [], []
55
+ for u, v, attr in graph.edges(data=True):
56
+ src.append(node2row[u])
57
+ dst.append(node2row[v])
58
+ edge_types.append(str(attr.get("label")))
59
+ src, dst = np.asarray(src, dtype=np.int64), np.asarray(dst, dtype=np.int64)
60
+
61
+ # Nodes sorted by ID, so that they can be found with a binary search
62
+ order = np.argsort(node_ids, kind="stable")
63
+ rank = np.empty_like(order)
64
+ rank[order] = np.arange(len(order))
65
+ node_types = [node_types[i] for i in order]
66
+ return node_ids[order], node_types, rank[src], rank[dst], edge_types
67
+
68
+
69
+ def _group_strings(rows, codes, strings, num_nodes):
70
+ """For each node, the ","-joined `strings[codes]` of its unique (row, code) pairs, in the
71
+ order of the codes (the strings are sorted, so this is the sorted set of strings)."""
72
+ pairs = np.unique(np.stack([rows, codes], axis=1), axis=0) if len(rows) else np.zeros((0, 2), int)
73
+ out = [""] * num_nodes
74
+ if len(pairs) == 0:
75
+ return out
76
+ bounds = np.flatnonzero(np.diff(pairs[:, 0])) + 1
77
+ starts = np.concatenate([[0], bounds])
78
+ ends = np.concatenate([bounds, [len(pairs)]])
79
+ values = strings[pairs[:, 1]]
80
+ for s, e in zip(starts, ends):
81
+ out[pairs[s, 0]] = ",".join(values[s:e])
82
+ return out
83
+
84
+
85
+ def _hash(label: str) -> str:
86
+ return hashlib.blake2b(label.encode("utf-8"), digest_size=8).hexdigest()
87
+
88
+
89
+ def rooted_subgraphs(node_types, src, dst, edge_types, depth):
90
+ """RSG labels of all nodes at depths 0..`depth` (Algorithm 2 of ProGrapher).
91
+
92
+ Args:
93
+ node_types: type of each node (n,)
94
+ src, dst: rows of the endpoints of each edge (E,)
95
+ edge_types: type of each edge (E,)
96
+ depth: maximum depth D of the WL relabeling
97
+
98
+ Returns:
99
+ np.ndarray: (D + 1, n) array of string labels. Labels of depth 0 are the node types,
100
+ labels of higher depths are hashes of the (sorted, deduplicated) labels they combine.
101
+ """
102
+ n = len(node_types)
103
+ labels = np.asarray(node_types, dtype=object)
104
+ all_labels = [labels]
105
+ if depth == 0 or n == 0:
106
+ return np.stack(all_labels)
107
+
108
+ # The graph is undirected: each edge links both endpoints
109
+ rows = np.concatenate([src, dst])
110
+ nbrs = np.concatenate([dst, src])
111
+ etype_strings, etype_codes = np.unique(np.asarray(edge_types, dtype=object), return_inverse=True)
112
+ edge_part = _group_strings(rows, np.concatenate([etype_codes, etype_codes]), etype_strings, n)
113
+
114
+ for _ in range(depth):
115
+ label_strings, label_codes = np.unique(labels, return_inverse=True)
116
+ nbr_part = _group_strings(rows, label_codes[nbrs], label_strings, n)
117
+ labels = np.asarray(
118
+ [_hash(f"{labels[i]}|{nbr_part[i]}|{edge_part[i]}") for i in range(n)], dtype=object
119
+ )
120
+ all_labels.append(labels)
121
+ return np.stack(all_labels)
122
+
123
+
124
+ def snapshot_rsgs(path, depth):
125
+ """(sorted node IDs, (D + 1, n) RSG labels) of the snapshot stored at `path`."""
126
+ node_ids, node_types, src, dst, edge_types = snapshot_columns(path)
127
+ return node_ids, rooted_subgraphs(node_types, src, dst, edge_types, depth)
128
+
129
+
130
+ def snapshot_words(labels):
131
+ """The words of a snapshot document: the RSGs of each node at all depths (with duplicates,
132
+ i.e. n x (D + 1) words, as ProGrapher)."""
133
+ return labels.T.ravel().tolist()
134
+
135
+
136
+ def chunks(words, size=GENSIM_MAX_DOCUMENT_LEN):
137
+ return [words[i : i + size] for i in range(0, len(words), size)]
138
+
139
+
140
+ def infer_snapshot_embedding(model, words, epochs, seed):
141
+ """Embedding of a new snapshot, as `Doc2Vec.infer_vector` (PV-DBOW), but trained over all
142
+ the chunks of the document instead of its first 10,000 words. RSGs absent from the
143
+ vocabulary are ignored.
144
+
145
+ Args:
146
+ model: trained graph2vec (Doc2Vec) model
147
+ words: words of the snapshot
148
+ epochs: number of inference epochs
149
+ seed: integer seed, making the inferred vector independent of other inferences
150
+ """
151
+ dim = model.dv.vector_size
152
+ model.random = np.random.RandomState(seed)
153
+ # gensim seeds this vector with Python's `hash` of the string by default, which is randomized
154
+ # per process: the integer seed is used directly so the inferred vectors are reproducible.
155
+ doctag_vectors = pseudorandom_weak_vector(
156
+ dim, seed_string=str(seed), hashfxn=lambda _: seed
157
+ ).reshape(1, dim)
158
+ doctags_lockf = np.ones(1, dtype=np.float32)
159
+ work = np.zeros(model.layer1_size, dtype=np.float32)
160
+
161
+ alpha, min_alpha = model.alpha, model.min_alpha
162
+ alpha_delta = (alpha - min_alpha) / max(epochs - 1, 1)
163
+ doc_chunks = chunks(words)
164
+ for _ in range(epochs):
165
+ for chunk in doc_chunks:
166
+ train_document_dbow(
167
+ model, chunk, [0], alpha, work,
168
+ learn_words=False, learn_hidden=False,
169
+ doctag_vectors=doctag_vectors, doctags_lockf=doctags_lockf,
170
+ )
171
+ alpha -= alpha_delta
172
+ return doctag_vectors[0].copy()
173
+
174
+
175
+ def snapshot_seed(path):
176
+ """Deterministic seed of a snapshot, from its file name."""
177
+ return int(hashlib.md5(os.path.basename(path).encode("utf-8")).hexdigest()[:8], 16)
178
+
179
+
180
+ def _compact_rsgs(args):
181
+ """Worker: the RSGs of a snapshot as (unique labels, codes) to limit pickling."""
182
+ path, depth = args
183
+ _, labels = snapshot_rsgs(path, depth)
184
+ uniq, codes = np.unique(np.asarray(snapshot_words(labels), dtype=object), return_inverse=True)
185
+ return uniq.tolist(), codes.astype(np.int32)
186
+
187
+
188
+ def get_graph2vec_corpus(cfg):
189
+ """One tagged document per snapshot of the training splits, split into chunks of 10,000
190
+ words. Strings are interned, so that each RSG is stored once in memory."""
191
+ splits = get_splits_to_train_featurization(cfg)
192
+ dates = list(chain.from_iterable(getattr(cfg.dataset, f"{split}_dates") for split in splits))
193
+ paths = get_all_graphs_for_dates(cfg.transformation._graphs_dir, dates)
194
+ depth = cfg.featurization.graph2vec.wl_iterations
195
+ workers = max(1, cfg.featurization.graph2vec.num_workers)
196
+
197
+ interned = {}
198
+ corpus = []
199
+ num_words = 0
200
+ with ProcessPoolExecutor(max_workers=workers) as pool:
201
+ results = pool.map(_compact_rsgs, [(p, depth) for p in paths], chunksize=1)
202
+ for path, (uniq, codes) in zip(log_tqdm(paths, desc="Extracting rooted subgraphs"), results):
203
+ uniq = [interned.setdefault(w, w) for w in uniq]
204
+ words = [uniq[c] for c in codes]
205
+ num_words += len(words)
206
+ tag = os.path.basename(path)
207
+ corpus.extend(TaggedDocument(words=chunk, tags=[tag]) for chunk in chunks(words))
208
+ log(f"graph2vec corpus: {len(paths)} snapshots, {num_words} RSGs, {len(interned)} unique RSGs")
209
+ return corpus
210
+
211
+
212
+ def train_graph2vec(cfg, corpus):
213
+ g2v_cfg = cfg.featurization.graph2vec
214
+ model = Doc2Vec(
215
+ vector_size=cfg.featurization.emb_dim,
216
+ dm=0, # PV-DBOW, as graph2vec
217
+ dbow_words=0, # RSG output vectors only, no word vectors
218
+ negative=g2v_cfg.negative,
219
+ hs=0,
220
+ min_count=g2v_cfg.min_count,
221
+ sample=0,
222
+ alpha=g2v_cfg.alpha,
223
+ workers=max(1, g2v_cfg.num_workers),
224
+ seed=cfg.featurization.seed,
225
+ )
226
+ model.build_vocab(corpus)
227
+ log(f"Training graph2vec ({cfg.featurization.epochs} epochs, {len(model.wv)} RSGs)...")
228
+ model.train(corpus, total_examples=model.corpus_count, epochs=cfg.featurization.epochs)
229
+ return model
230
+
231
+
232
+ def main(cfg):
233
+ if cfg.featurization.multi_dataset_training:
234
+ raise NotImplementedError("graph2vec does not support multi-dataset training.")
235
+
236
+ corpus = get_graph2vec_corpus(cfg)
237
+ model = train_graph2vec(cfg, corpus)
238
+
239
+ model_dir = cfg.featurization._model_dir
240
+ os.makedirs(model_dir, exist_ok=True)
241
+ log(f"Saving graph2vec model to {model_dir}")
242
+ model.save(os.path.join(model_dir, MODEL_FILE))