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,634 @@
1
+ """Compact on-disk storage of the networkx graphs built by construction/transformation.
2
+
3
+ Graphs used to be saved as pickled networkx objects, which store every node/edge as
4
+ Python dicts of Python objects (e.g. each edge holds a 36-char UUID string, a label
5
+ string and two ints). They are now saved as typed column arrays:
6
+
7
+ - string columns are dictionary-encoded when values repeat (node types, labels,
8
+ edge operations), packed as 16-byte UUIDs when they are canonical UUIDs, stored as
9
+ integers when they are canonical decimal integers (node IDs), or as one UTF-8 blob;
10
+ - int/float columns as int64/float64 arrays (np.int64 scalars too, e.g. the random timestamps
11
+ of R-Caid, loaded back as np.int64), anything else as a pickled list;
12
+ - the adjacency order (successors and predecessors) is recorded so that the rebuilt
13
+ graph is identical to the original one: same nodes, edges, keys, attributes, Python
14
+ types and iteration orders (nodes, edges, in_edges, predecessors).
15
+
16
+ The file stays a `torch.save` file whose unpickling rebuilds the networkx graph, so
17
+ `torch.load(path)` still returns the graph and every reader works unchanged. Old
18
+ pickled graphs remain readable. Unsupported graphs (undirected, subclasses,
19
+ heterogeneous attribute keys) are saved as plain pickles, as before.
20
+
21
+ `load_graph_columns(path)` returns the decoded columns without building networkx
22
+ objects, for readers that only need arrays.
23
+ """
24
+
25
+ import gc
26
+ import pickle
27
+ import threading
28
+ import uuid as _uuid
29
+ import zlib
30
+ from collections.abc import Mapping
31
+
32
+ import networkx as nx
33
+ import numpy as np
34
+ import pandas as pd
35
+ import torch
36
+
37
+ FORMAT_VERSION = 1
38
+
39
+ _SUPPORTED_CLASSES = {nx.MultiDiGraph: "MultiDiGraph", nx.DiGraph: "DiGraph"}
40
+ _CLASS_BY_NAME = {v: k for k, v in _SUPPORTED_CLASSES.items()}
41
+
42
+ _I32 = np.iinfo(np.int32)
43
+
44
+
45
+ # --------------------------------------------------------------------------------------
46
+ # Arrays
47
+ # --------------------------------------------------------------------------------------
48
+
49
+
50
+ def _pack_array(a):
51
+ a = np.ascontiguousarray(a)
52
+ return (a.dtype.str, a.shape, zlib.compress(a.tobytes(), 1))
53
+
54
+
55
+ def _unpack_array(packed):
56
+ dtype, shape, data = packed
57
+ return np.frombuffer(zlib.decompress(data), dtype=np.dtype(dtype)).reshape(shape)
58
+
59
+
60
+ def _smallest_index_dtype(n):
61
+ if n < 2**7:
62
+ return np.int8
63
+ if n < 2**15:
64
+ return np.int16
65
+ return np.int32
66
+
67
+
68
+ # --------------------------------------------------------------------------------------
69
+ # Columns
70
+ # --------------------------------------------------------------------------------------
71
+
72
+
73
+ def _all_type(values, t):
74
+ return all(type(v) is t for v in values)
75
+
76
+
77
+ def _try_uuid(values):
78
+ """Packs canonical UUID strings (all upper or all lower case) as 16 bytes each."""
79
+ if not values or not all(len(v) == 36 for v in values):
80
+ return None
81
+ upper = values[0].upper() == values[0]
82
+ try:
83
+ raw = [_uuid.UUID(v).bytes for v in values]
84
+ except ValueError:
85
+ return None
86
+ blob = b"".join(raw)
87
+ if _decode_uuids(np.frombuffer(blob, dtype=np.uint8), len(values), upper) != values:
88
+ return None
89
+ return ("uuid", _pack_array(np.frombuffer(blob, dtype=np.uint8)), upper)
90
+
91
+
92
+ def _decode_uuids(arr, n, upper):
93
+ h = arr.tobytes().hex()
94
+ if upper:
95
+ h = h.upper()
96
+ out = []
97
+ for i in range(n):
98
+ s = h[32 * i : 32 * i + 32]
99
+ out.append(f"{s[:8]}-{s[8:12]}-{s[12:16]}-{s[16:20]}-{s[20:]}")
100
+ return out
101
+
102
+
103
+ def _try_int_strings(values):
104
+ try:
105
+ ints = [int(v) for v in values]
106
+ except ValueError:
107
+ return None
108
+ if any(str(i) != v for i, v in zip(ints, values)):
109
+ return None
110
+ try:
111
+ return ("intstr", _pack_array(np.array(ints, dtype=np.int64)))
112
+ except OverflowError:
113
+ return None
114
+
115
+
116
+ def _encode_column(values):
117
+ # Types of the values in one pass (an empty column is an int column)
118
+ types = set(map(type, values)) if len(values) else {int}
119
+ if types == {int}:
120
+ try:
121
+ return ("int", _pack_array(np.array(values, dtype=np.int64)))
122
+ except OverflowError:
123
+ return ("obj", values)
124
+ if types == {float}:
125
+ return ("float", _pack_array(np.array(values, dtype=np.float64)))
126
+ if types == {np.int64}:
127
+ # numpy scalars (e.g. drawn by np.random), decoded as numpy scalars
128
+ return ("npint64", _pack_array(np.array(values, dtype=np.int64)))
129
+ if types == {str}:
130
+ if len(set(values)) <= max(1, len(values) // 2):
131
+ # Values numbered in order of first appearance (same as a dict of the values)
132
+ codes, vocab = pd.factorize(np.array(values, dtype=object))
133
+ codes = codes.astype(_smallest_index_dtype(len(vocab)))
134
+ return ("strdict", vocab.tolist(), _pack_array(codes))
135
+ for attempt in (_try_uuid, _try_int_strings):
136
+ col = attempt(values)
137
+ if col is not None:
138
+ return col
139
+ blobs = [v.encode("utf-8", "surrogatepass") for v in values]
140
+ offsets = np.cumsum([0] + [len(b) for b in blobs], dtype=np.int64)
141
+ return ("strblob", zlib.compress(b"".join(blobs), 1), _pack_array(offsets))
142
+ return ("obj", values)
143
+
144
+
145
+ def _decode_column(col, n):
146
+ kind = col[0]
147
+ if kind in ("int", "float"):
148
+ return _unpack_array(col[1]).tolist()
149
+ if kind == "npint64":
150
+ return list(_unpack_array(col[1]))
151
+ if kind == "strdict":
152
+ vocab = col[1]
153
+ return [vocab[i] for i in _unpack_array(col[2]).tolist()]
154
+ if kind == "uuid":
155
+ return _decode_uuids(_unpack_array(col[1]), n, col[2])
156
+ if kind == "intstr":
157
+ return [str(i) for i in _unpack_array(col[1]).tolist()]
158
+ if kind == "strblob":
159
+ blob = zlib.decompress(col[1])
160
+ offsets = _unpack_array(col[2]).tolist()
161
+ return [
162
+ blob[offsets[i] : offsets[i + 1]].decode("utf-8", "surrogatepass") for i in range(n)
163
+ ]
164
+ if kind == "obj":
165
+ return list(col[1])
166
+ raise ValueError(f"Unknown column kind {kind}")
167
+
168
+
169
+ def _encode_attr_dicts(dicts):
170
+ """Encodes a list of attribute dicts sharing the same keys (in the same order)."""
171
+ if not dicts:
172
+ return (), []
173
+ keys = tuple(dicts[0])
174
+ for d in dicts:
175
+ if len(d) != len(keys) or tuple(d) != keys:
176
+ return None
177
+ return keys, [_encode_column([d[k] for d in dicts]) for k in keys]
178
+
179
+
180
+ def encode_attr_dicts(dicts):
181
+ """(keys, encoded columns) of a list of attribute dicts, or None if they do not all have the
182
+ same keys in the same order (such graphs are saved as pickles)."""
183
+ return _encode_attr_dicts(dicts)
184
+
185
+
186
+ def _decode_attr_dicts(keys, cols, n):
187
+ if not keys:
188
+ return [{} for _ in range(n)]
189
+ values = [_decode_column(c, n) for c in cols]
190
+ return [dict(zip(keys, row)) for row in zip(*values)]
191
+
192
+
193
+ # --------------------------------------------------------------------------------------
194
+ # Graphs
195
+ # --------------------------------------------------------------------------------------
196
+
197
+
198
+ def encode_graph(graph):
199
+ """Returns the compact payload of a graph, or None if it is not supported."""
200
+ cls_name = _SUPPORTED_CLASSES.get(type(graph))
201
+ if cls_name is None:
202
+ return None
203
+ multi = graph.is_multigraph()
204
+
205
+ nodes = list(graph._node)
206
+ if list(graph._succ) != nodes or list(graph._pred) != nodes:
207
+ return None
208
+ node_pos = {n: i for i, n in enumerate(nodes)}
209
+
210
+ node_attrs = _encode_attr_dicts(list(graph._node.values()))
211
+ if node_attrs is None:
212
+ return None
213
+
214
+ # Edges in successor order: for u, for v in succ[u], for key in succ[u][v]
215
+ src, dst, keys, edge_dicts = [], [], [], []
216
+ pair_pos = {}
217
+ for u, nbrs in graph._succ.items():
218
+ ui = node_pos[u]
219
+ for v, inner in nbrs.items():
220
+ vi = node_pos[v]
221
+ pair_pos[(u, v)] = len(pair_pos)
222
+ # The predecessor adjacency must share the successor inner dicts
223
+ if graph._pred[v].get(u) is not inner:
224
+ return None
225
+ if multi:
226
+ if len(inner) == 0:
227
+ return None
228
+ for k, d in inner.items():
229
+ src.append(ui)
230
+ dst.append(vi)
231
+ keys.append(k)
232
+ edge_dicts.append(d)
233
+ else:
234
+ src.append(ui)
235
+ dst.append(vi)
236
+ edge_dicts.append(inner)
237
+
238
+ # Order of each node's predecessors, as indices of (u, v) pairs in successor order
239
+ pred_order = []
240
+ for v, preds in graph._pred.items():
241
+ for u in preds:
242
+ pred_order.append(pair_pos[(u, v)])
243
+ if len(pred_order) != len(pair_pos):
244
+ return None
245
+
246
+ edge_attrs = _encode_attr_dicts(edge_dicts)
247
+ if edge_attrs is None:
248
+ return None
249
+
250
+ return _payload(
251
+ cls_name, dict(graph.graph), nodes, node_attrs, src, dst,
252
+ _encode_column(keys) if multi else None, edge_attrs, len(pair_pos), pred_order,
253
+ )
254
+
255
+
256
+ def _payload(cls_name, graph_attrs, nodes, node_attrs, src, dst, keys, edge_attrs, num_pairs, pred_order):
257
+ """Payload of a graph: `node_attrs` and `edge_attrs` are (keys, encoded columns), `src`
258
+ and `dst` the node positions of the edges in successor order, `keys` the encoded edge keys
259
+ (None for simple graphs) and `pred_order` the predecessor order of the (u, v) pairs."""
260
+ idx_dtype = np.int32 if len(nodes) <= _I32.max else np.int64
261
+ return {
262
+ "version": FORMAT_VERSION,
263
+ "class": cls_name,
264
+ "graph_attrs": graph_attrs,
265
+ "num_nodes": len(nodes),
266
+ "num_edges": len(src),
267
+ "num_pairs": num_pairs,
268
+ "node_ids": _encode_column(list(nodes)),
269
+ "node_attr_keys": node_attrs[0],
270
+ "node_attr_cols": node_attrs[1],
271
+ "src": _pack_array(np.asarray(src).astype(idx_dtype)),
272
+ "dst": _pack_array(np.asarray(dst).astype(idx_dtype)),
273
+ "keys": keys,
274
+ "edge_attr_keys": edge_attrs[0],
275
+ "edge_attr_cols": edge_attrs[1],
276
+ "pred_order": _pack_array(np.asarray(pred_order, dtype=np.int64)),
277
+ }
278
+
279
+
280
+ def encode_edge_list(nodes, node_attrs, src, dst, edge_attrs):
281
+ """Payload of the MultiDiGraph built by adding the nodes `nodes` (in this order, with the
282
+ attributes {key: list of values} `node_attrs`) and then the edges (src[i], dst[i]) with the
283
+ attributes {key: list of values} `edge_attrs`, in this order.
284
+
285
+ Same result as `encode_graph` on that graph, without building it: networkx graphs store
286
+ each edge as a dict, which is slow to build and to encode for millions of edges.
287
+ """
288
+ num_nodes, num_edges = len(nodes), len(src)
289
+ node_pos = {n: i for i, n in enumerate(nodes)}
290
+ if len(node_pos) != num_nodes:
291
+ raise ValueError("Duplicate nodes")
292
+
293
+ src_pos = np.fromiter((node_pos[u] for u in src), dtype=np.int64, count=num_edges)
294
+ dst_pos = np.fromiter((node_pos[v] for v in dst), dtype=np.int64, count=num_edges)
295
+ node_cols = (tuple(node_attrs), [_encode_column(list(v)) for v in node_attrs.values()]) if num_nodes else ((), [])
296
+ return encode_multi_edge_positions(nodes, node_cols, src_pos, dst_pos, edge_attrs)
297
+
298
+
299
+ def encode_multi_edge_positions(nodes, node_cols, src_pos, dst_pos, edge_attrs):
300
+ """Same as `encode_edge_list`, with the edges given as node positions, the node attributes as
301
+ encoded columns (as returned by `encode_attr_dicts`) and the edge attributes as lists or int64
302
+ arrays (whose values are stored as Python ints)."""
303
+ num_nodes, num_edges = len(nodes), len(src_pos)
304
+ src_pos = np.asarray(src_pos, dtype=np.int64)
305
+ dst_pos = np.asarray(dst_pos, dtype=np.int64)
306
+ # Pairs (u, v) numbered in order of first appearance: the order of the successors of u
307
+ # (and of the predecessors of v) in the networkx adjacency dicts
308
+ pair_id, _ = pd.factorize(src_pos * max(num_nodes, 1) + dst_pos)
309
+ pair_id = pair_id.astype(np.int64)
310
+ num_pairs = int(pair_id.max()) + 1 if num_edges else 0
311
+
312
+ # Edges in successor order: for u, for v in succ[u], for key in succ[u][v]
313
+ order = np.lexsort((np.arange(num_edges), pair_id, src_pos))
314
+ sorted_pairs = pair_id[order]
315
+ starts = np.r_[True, sorted_pairs[1:] != sorted_pairs[:-1]] if num_edges else np.zeros(0, bool)
316
+ start_idx = np.flatnonzero(starts)
317
+ keys = np.arange(num_edges) - np.repeat(start_idx, np.diff(np.append(start_idx, num_edges)))
318
+
319
+ # Index of each pair in successor order, and pairs in predecessor order
320
+ pair_src = np.empty(num_pairs, dtype=np.int64)
321
+ pair_dst = np.empty(num_pairs, dtype=np.int64)
322
+ pair_src[pair_id], pair_dst[pair_id] = src_pos, dst_pos
323
+ succ_pairs = np.lexsort((np.arange(num_pairs), pair_src))
324
+ pair_rank = np.empty(num_pairs, dtype=np.int64)
325
+ pair_rank[succ_pairs] = np.arange(num_pairs)
326
+ pred_pairs = np.lexsort((np.arange(num_pairs), pair_dst))
327
+
328
+ if num_edges:
329
+ take = order.tolist()
330
+ edge_cols = (
331
+ tuple(edge_attrs),
332
+ [
333
+ _encode_values(values[order], scalars=False)
334
+ if isinstance(values, np.ndarray)
335
+ else _encode_column([values[i] for i in take])
336
+ for values in edge_attrs.values()
337
+ ],
338
+ )
339
+ else:
340
+ edge_cols = ((), [])
341
+ return _payload(
342
+ "MultiDiGraph", {}, nodes, node_cols, src_pos[order], dst_pos[order],
343
+ _encode_values(keys.astype(np.int64), scalars=False), edge_cols, num_pairs,
344
+ pair_rank[pred_pairs],
345
+ )
346
+
347
+
348
+ def encode_edge_positions(nodes, node_cols, src_pos, dst_pos, edge_attrs):
349
+ """Payload of the MultiDiGraph built by adding the nodes `nodes` (in this order, with the
350
+ attribute columns `node_cols`, as returned by `encode_attr_dicts`) and then the edges
351
+ (nodes[src_pos[i]], nodes[dst_pos[i]]) with the attributes {key: list of values, or int64
352
+ array standing for its list of numpy scalars} `edge_attrs`, in this order, given that each (src, dst) pair appears once and that `src_pos`
353
+ is sorted (edges already in successor order, all with key 0)."""
354
+ src_pos = np.asarray(src_pos, dtype=np.int64)
355
+ dst_pos = np.asarray(dst_pos, dtype=np.int64)
356
+ num_edges = len(src_pos)
357
+ if num_edges and np.any(src_pos[1:] < src_pos[:-1]):
358
+ raise ValueError("Edges are not sorted by source node")
359
+ if num_edges and len(np.unique(src_pos * max(len(nodes), 1) + dst_pos)) != num_edges:
360
+ raise ValueError("Duplicate edges")
361
+ # Predecessors of each node in the order their edges were added
362
+ pred_order = np.argsort(dst_pos, kind="stable")
363
+ edge_cols = (
364
+ (tuple(edge_attrs), [_encode_values(v) for v in edge_attrs.values()])
365
+ if num_edges
366
+ else ((), [])
367
+ )
368
+ keys = _encode_values(np.zeros(num_edges, dtype=np.int64), scalars=False)
369
+ return _payload(
370
+ "MultiDiGraph", {}, nodes, node_cols, src_pos, dst_pos, keys, edge_cols, num_edges,
371
+ pred_order,
372
+ )
373
+
374
+
375
+ def _encode_values(values, scalars=True):
376
+ """`_encode_column` of a list, or of the elements of an int64 array without building them:
377
+ numpy scalars (`list(values)`) or Python ints (`values.tolist()`) if not `scalars`."""
378
+ if isinstance(values, np.ndarray) and values.dtype == np.int64 and values.ndim == 1 and len(values):
379
+ return ("npint64" if scalars else "int", _pack_array(values))
380
+ return _encode_column(list(values) if scalars else values.tolist())
381
+
382
+
383
+ def save_edge_positions(path, nodes, node_cols, src_pos, dst_pos, edge_attrs):
384
+ """Saves the graph described by `encode_edge_positions`, as `save_graph` would save it."""
385
+ obj = _CompactGraph(encode_edge_positions(nodes, node_cols, src_pos, dst_pos, edge_attrs))
386
+ torch.save(obj, path, pickle_protocol=pickle.HIGHEST_PROTOCOL)
387
+
388
+
389
+ def save_multi_edge_positions(path, nodes, node_cols, src_pos, dst_pos, edge_attrs):
390
+ """Saves the graph described by `encode_multi_edge_positions`, as `save_graph` would save it."""
391
+ obj = _CompactGraph(encode_multi_edge_positions(nodes, node_cols, src_pos, dst_pos, edge_attrs))
392
+ torch.save(obj, path, pickle_protocol=pickle.HIGHEST_PROTOCOL)
393
+
394
+
395
+ def save_edge_list(path, nodes, node_attrs, src, dst, edge_attrs):
396
+ """Saves the graph described by `encode_edge_list`, as `save_graph` would save it."""
397
+ obj = _CompactGraph(encode_edge_list(nodes, node_attrs, src, dst, edge_attrs))
398
+ torch.save(obj, path, pickle_protocol=pickle.HIGHEST_PROTOCOL)
399
+
400
+
401
+ def decode_graph(payload):
402
+ """Rebuilds the networkx graph of a payload, identical to the encoded one."""
403
+ # Building many containers triggers costly cyclic GC passes that cannot free anything
404
+ gc_enabled = gc.isenabled()
405
+ gc.disable()
406
+ try:
407
+ return _decode_graph(payload)
408
+ finally:
409
+ if gc_enabled:
410
+ gc.enable()
411
+
412
+
413
+ def _decode_graph(payload):
414
+ if payload["version"] != FORMAT_VERSION:
415
+ raise ValueError(f"Unsupported graph format version {payload['version']}")
416
+ graph = _CLASS_BY_NAME[payload["class"]]()
417
+ multi = graph.is_multigraph()
418
+ graph.graph.update(payload["graph_attrs"])
419
+
420
+ n, m = payload["num_nodes"], payload["num_edges"]
421
+ nodes = _decode_column(payload["node_ids"], n)
422
+ node_dicts = _decode_attr_dicts(payload["node_attr_keys"], payload["node_attr_cols"], n)
423
+ node_store, succ, pred = graph._node, graph._succ, graph._pred
424
+ for node, d in zip(nodes, node_dicts):
425
+ node_store[node] = d
426
+ succ[node] = {}
427
+ pred[node] = {}
428
+
429
+ src = _unpack_array(payload["src"])
430
+ dst = _unpack_array(payload["dst"])
431
+ edge_dicts = _decode_attr_dicts(payload["edge_attr_keys"], payload["edge_attr_cols"], m)
432
+
433
+ # Edges of a (u, v) pair are contiguous: find where each pair starts
434
+ if m > 0:
435
+ starts = np.flatnonzero(
436
+ np.concatenate(([True], (src[1:] != src[:-1]) | (dst[1:] != dst[:-1])))
437
+ )
438
+ else:
439
+ starts = np.zeros(0, dtype=np.int64)
440
+ node_arr = np.empty(n, dtype=object)
441
+ node_arr[:] = nodes
442
+ pair_u = node_arr[src[starts]].tolist()
443
+ pair_v = node_arr[dst[starts]].tolist()
444
+
445
+ if multi:
446
+ keys = _decode_column(payload["keys"], m)
447
+ counts = np.diff(np.append(starts, m)).tolist()
448
+ inners = []
449
+ e = 0
450
+ for u, v, c in zip(pair_u, pair_v, counts):
451
+ if c == 1:
452
+ inner = {keys[e]: edge_dicts[e]}
453
+ else:
454
+ inner = dict(zip(keys[e : e + c], edge_dicts[e : e + c]))
455
+ e += c
456
+ succ[u][v] = inner
457
+ inners.append(inner)
458
+ else:
459
+ inners = edge_dicts
460
+ for u, v, d in zip(pair_u, pair_v, edge_dicts):
461
+ succ[u][v] = d
462
+
463
+ for p in _unpack_array(payload["pred_order"]).tolist():
464
+ pred[pair_v[p]][pair_u[p]] = inners[p]
465
+ return graph
466
+
467
+
468
+ def _take_column(col, n, idx):
469
+ """Values of a column at the positions `idx` (same as `_decode_column(col, n)[i]`)."""
470
+ kind = col[0]
471
+ idx = np.asarray(idx, dtype=np.int64)
472
+ if kind in ("int", "float"):
473
+ return _unpack_array(col[1])[idx].tolist()
474
+ if kind == "npint64":
475
+ return list(_unpack_array(col[1])[idx])
476
+ if kind == "strdict":
477
+ vocab = col[1]
478
+ return [vocab[i] for i in _unpack_array(col[2])[idx].tolist()]
479
+ if kind == "uuid":
480
+ arr = _unpack_array(col[1]).reshape(n, 16)[idx]
481
+ return _decode_uuids(arr, len(idx), col[2])
482
+ if kind == "intstr":
483
+ return [str(i) for i in _unpack_array(col[1])[idx].tolist()]
484
+ if kind == "strblob":
485
+ blob = zlib.decompress(col[1])
486
+ offsets = _unpack_array(col[2])
487
+ starts, ends = offsets[idx].tolist(), offsets[idx + 1].tolist()
488
+ return [blob[s:e].decode("utf-8", "surrogatepass") for s, e in zip(starts, ends)]
489
+ if kind == "obj":
490
+ values = col[1]
491
+ return [values[i] for i in idx.tolist()]
492
+ raise ValueError(f"Unknown column kind {kind}")
493
+
494
+
495
+ def _factorize_column(col, n):
496
+ """(codes, uniques) of a column: `uniques[codes[i]]` is its i-th value."""
497
+ kind = col[0]
498
+ if kind == "strdict":
499
+ return _unpack_array(col[2]).astype(np.int64), list(col[1])
500
+ if kind in ("int", "float", "intstr", "npint64"):
501
+ codes, uniques = pd.factorize(_unpack_array(col[1]), use_na_sentinel=False)
502
+ uniques = list(uniques) if kind == "npint64" else uniques.tolist()
503
+ if kind == "intstr":
504
+ uniques = [str(u) for u in uniques]
505
+ return codes.astype(np.int64), uniques
506
+ values = _decode_column(col, n)
507
+ try:
508
+ # Exact values (pandas would turn None into NaN)
509
+ index = {}
510
+ codes = np.fromiter((index.setdefault(v, len(index)) for v in values), np.int64, count=n)
511
+ return codes, list(index)
512
+ except TypeError: # unhashable values
513
+ codes, uniques = pd.factorize(pd.Series(values, dtype=object), use_na_sentinel=False)
514
+ return codes.astype(np.int64), list(uniques)
515
+
516
+
517
+ class LazyColumns(Mapping):
518
+ """{name: column values (list)}, each column being decoded on first access."""
519
+
520
+ def __init__(self, keys, cols, n):
521
+ self._cols = dict(zip(keys, cols))
522
+ self._n = n
523
+ self._decoded = {}
524
+
525
+ def __getitem__(self, key):
526
+ if key not in self._decoded:
527
+ self._decoded[key] = _decode_column(self._cols[key], self._n)
528
+ return self._decoded[key]
529
+
530
+ def __iter__(self):
531
+ return iter(self._cols)
532
+
533
+ def __len__(self):
534
+ return len(self._cols)
535
+
536
+ def __contains__(self, key):
537
+ return key in self._cols
538
+
539
+ def take(self, key, idx):
540
+ """Values of a column at the positions `idx`, without decoding the whole column."""
541
+ if key in self._decoded:
542
+ values = self._decoded[key]
543
+ return [values[i] for i in np.asarray(idx).tolist()]
544
+ return _take_column(self._cols[key], self._n, idx)
545
+
546
+ def encoded(self):
547
+ """(keys, encoded columns), as stored."""
548
+ return tuple(self._cols), list(self._cols.values())
549
+
550
+ def factorize(self, key):
551
+ """(codes array, unique values) of a column, without building one object per value
552
+ when the column is stored as integers or a dictionary."""
553
+ return _factorize_column(self._cols[key], self._n)
554
+
555
+ def array(self, key, dtype):
556
+ """A numeric column as a numpy array."""
557
+ col = self._cols[key]
558
+ if col[0] in ("int", "float", "npint64"):
559
+ return _unpack_array(col[1]).astype(dtype, copy=False)
560
+ return np.asarray(self[key], dtype=dtype)
561
+
562
+
563
+ class GraphColumns:
564
+ """Columns of a stored graph (see `load_graph_columns`). Node and edge attributes are
565
+ `LazyColumns`, decoded on first access."""
566
+
567
+ def __init__(self, payload):
568
+ n, m = payload["num_nodes"], payload["num_edges"]
569
+ self.multi = payload["class"] == "MultiDiGraph"
570
+ self.graph_attrs = payload["graph_attrs"]
571
+ self.node_ids = _decode_column(payload["node_ids"], n)
572
+ self.node_attrs = LazyColumns(payload["node_attr_keys"], payload["node_attr_cols"], n)
573
+ # Edges in `graph.edges` order, as node positions in `node_ids`
574
+ self.src = _unpack_array(payload["src"])
575
+ self.dst = _unpack_array(payload["dst"])
576
+ self.edge_attrs = LazyColumns(payload["edge_attr_keys"], payload["edge_attr_cols"], m)
577
+
578
+
579
+ _LOAD_STATE = threading.local()
580
+
581
+
582
+ def _rebuild(payload):
583
+ if getattr(_LOAD_STATE, "columns", False):
584
+ return GraphColumns(payload)
585
+ return decode_graph(payload)
586
+
587
+
588
+ class _CompactGraph:
589
+ """Pickled in place of the graph: unpickling it calls `_rebuild`."""
590
+
591
+ def __init__(self, payload):
592
+ self.payload = payload
593
+
594
+ def __reduce__(self):
595
+ return (_rebuild, (self.payload,))
596
+
597
+
598
+ def save_graph(graph, path):
599
+ """Saves a networkx graph compactly (or as a plain pickle if not supported)."""
600
+ payload = encode_graph(graph)
601
+ obj = graph if payload is None else _CompactGraph(payload)
602
+ torch.save(obj, path, pickle_protocol=pickle.HIGHEST_PROTOCOL)
603
+
604
+
605
+ def load_graph(path):
606
+ """Loads a graph saved by `save_graph` or a legacy pickled graph."""
607
+ return torch.load(path)
608
+
609
+
610
+ def graph_columns(graph):
611
+ """`GraphColumns` of a networkx graph (as if it was saved and loaded with
612
+ `load_graph_columns`). Graphs that cannot be stored compactly (e.g. edges with different
613
+ attributes) are not supported."""
614
+ payload = encode_graph(graph)
615
+ if payload is None:
616
+ raise ValueError(
617
+ "Unsupported graph: only directed (multi)graphs whose nodes and edges all have the "
618
+ "same attributes are supported"
619
+ )
620
+ return GraphColumns(payload)
621
+
622
+
623
+ def load_graph_columns(path):
624
+ """Loads a stored graph as `GraphColumns`, without building networkx objects.
625
+
626
+ Returns None for graphs stored as plain pickles (legacy or unsupported), in which
627
+ case `load_graph` should be used.
628
+ """
629
+ _LOAD_STATE.columns = True
630
+ try:
631
+ obj = torch.load(path)
632
+ finally:
633
+ _LOAD_STATE.columns = False
634
+ return obj if isinstance(obj, GraphColumns) else None