pidsmaker 4.0.0__py3-none-any.whl

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

Potentially problematic release.


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

Files changed (338) hide show
  1. pidsmaker/__init__.py +22 -0
  2. pidsmaker/cli.py +32 -0
  3. pidsmaker/config/__init__.py +2 -0
  4. pidsmaker/config/config.py +2100 -0
  5. pidsmaker/config/pipeline.py +1768 -0
  6. pidsmaker/config/schemas.py +1032 -0
  7. pidsmaker/datasets.py +222 -0
  8. pidsmaker/debug_tests.py +30 -0
  9. pidsmaker/decoders/__init__.py +5 -0
  10. pidsmaker/decoders/custom_edge_mlp_decoder.py +17 -0
  11. pidsmaker/decoders/custom_mlp_decoder.py +10 -0
  12. pidsmaker/decoders/edge_linear_decoder.py +16 -0
  13. pidsmaker/decoders/inner_product_decoder.py +18 -0
  14. pidsmaker/decoders/nodlink_decoder.py +56 -0
  15. pidsmaker/detection/__init__.py +0 -0
  16. pidsmaker/detection/evaluation_methods/__init__.py +9 -0
  17. pidsmaker/detection/evaluation_methods/edge_evaluation.py +259 -0
  18. pidsmaker/detection/evaluation_methods/evaluation_utils.py +1730 -0
  19. pidsmaker/detection/evaluation_methods/host_two_stage_evaluation.py +115 -0
  20. pidsmaker/detection/evaluation_methods/node_evaluation.py +463 -0
  21. pidsmaker/detection/evaluation_methods/node_tw_evaluation.py +196 -0
  22. pidsmaker/detection/evaluation_methods/plot.py +192 -0
  23. pidsmaker/detection/evaluation_methods/queue_evaluation.py +451 -0
  24. pidsmaker/detection/evaluation_methods/tw_evaluation.py +95 -0
  25. pidsmaker/detection/flash_detection.py +162 -0
  26. pidsmaker/detection/magic_knn.py +190 -0
  27. pidsmaker/detection/node_scoring.py +52 -0
  28. pidsmaker/detection/threatrace_detection.py +65 -0
  29. pidsmaker/detection/training_methods/__init__.py +1 -0
  30. pidsmaker/detection/training_methods/inference_loop.py +293 -0
  31. pidsmaker/detection/training_methods/ocrapt_early_stop.py +165 -0
  32. pidsmaker/detection/training_methods/threatrace_training.py +169 -0
  33. pidsmaker/detection/training_methods/training_loop.py +377 -0
  34. pidsmaker/encoders/__init__.py +22 -0
  35. pidsmaker/encoders/argus_encoder.py +69 -0
  36. pidsmaker/encoders/custom_mlp.py +75 -0
  37. pidsmaker/encoders/custom_mlp_encoder.py +10 -0
  38. pidsmaker/encoders/egraphsage_encoder.py +56 -0
  39. pidsmaker/encoders/gat.py +67 -0
  40. pidsmaker/encoders/gcn.py +27 -0
  41. pidsmaker/encoders/gin.py +48 -0
  42. pidsmaker/encoders/glstm.py +298 -0
  43. pidsmaker/encoders/graph_attention.py +63 -0
  44. pidsmaker/encoders/gru.py +29 -0
  45. pidsmaker/encoders/hetero/__init__.py +4 -0
  46. pidsmaker/encoders/hetero/ancestor_encoder.py +98 -0
  47. pidsmaker/encoders/hetero/entity_encoder.py +33 -0
  48. pidsmaker/encoders/hetero/event_encoder.py +81 -0
  49. pidsmaker/encoders/hetero/hetero_graph_transformer.py +40 -0
  50. pidsmaker/encoders/lares_encoder.py +68 -0
  51. pidsmaker/encoders/linear_encoder.py +16 -0
  52. pidsmaker/encoders/magic_encoder.py +161 -0
  53. pidsmaker/encoders/rcaid_encoder.py +81 -0
  54. pidsmaker/encoders/rgcn.py +75 -0
  55. pidsmaker/encoders/sage.py +51 -0
  56. pidsmaker/encoders/shadewatcher_encoder.py +149 -0
  57. pidsmaker/encoders/sum_aggregation.py +20 -0
  58. pidsmaker/encoders/temporal_wrappers.py +80 -0
  59. pidsmaker/encoders/textrcnn.py +82 -0
  60. pidsmaker/encoders/tgn_encoder.py +193 -0
  61. pidsmaker/experiments/tuning.py +102 -0
  62. pidsmaker/experiments/uncertainty.py +261 -0
  63. pidsmaker/factory.py +1456 -0
  64. pidsmaker/featurization/__init__.py +0 -0
  65. pidsmaker/featurization/feat_inference_methods/__init__.py +7 -0
  66. pidsmaker/featurization/feat_inference_methods/feat_inference_HFH.py +31 -0
  67. pidsmaker/featurization/feat_inference_methods/feat_inference_TRW.py +67 -0
  68. pidsmaker/featurization/feat_inference_methods/feat_inference_alacarte.py +16 -0
  69. pidsmaker/featurization/feat_inference_methods/feat_inference_doc2vec.py +54 -0
  70. pidsmaker/featurization/feat_inference_methods/feat_inference_fasttext.py +38 -0
  71. pidsmaker/featurization/feat_inference_methods/feat_inference_flash.py +70 -0
  72. pidsmaker/featurization/feat_inference_methods/feat_inference_graph2vec.py +85 -0
  73. pidsmaker/featurization/feat_inference_methods/feat_inference_ocrapt_features.py +95 -0
  74. pidsmaker/featurization/feat_inference_methods/feat_inference_pretrained.py +1729 -0
  75. pidsmaker/featurization/feat_inference_methods/feat_inference_word2vec.py +56 -0
  76. pidsmaker/featurization/featurization_methods/__init__.py +0 -0
  77. pidsmaker/featurization/featurization_methods/build_trw.py +67 -0
  78. pidsmaker/featurization/featurization_methods/featurization_alacarte.py +748 -0
  79. pidsmaker/featurization/featurization_methods/featurization_doc2vec.py +99 -0
  80. pidsmaker/featurization/featurization_methods/featurization_fasttext.py +75 -0
  81. pidsmaker/featurization/featurization_methods/featurization_flash.py +203 -0
  82. pidsmaker/featurization/featurization_methods/featurization_graph2vec.py +243 -0
  83. pidsmaker/featurization/featurization_methods/featurization_trw.py +115 -0
  84. pidsmaker/featurization/featurization_methods/featurization_word2vec.py +87 -0
  85. pidsmaker/featurization/featurization_utils.py +275 -0
  86. pidsmaker/featurization/utils/build_random_walks.py +68 -0
  87. pidsmaker/featurization/utils/trw.py +203 -0
  88. pidsmaker/hetero.py +81 -0
  89. pidsmaker/losses.py +170 -0
  90. pidsmaker/main.py +377 -0
  91. pidsmaker/mimicry.py +284 -0
  92. pidsmaker/model.py +382 -0
  93. pidsmaker/objectives/__init__.py +16 -0
  94. pidsmaker/objectives/autoencode_edge_emb.py +43 -0
  95. pidsmaker/objectives/deep_graph_infomax.py +94 -0
  96. pidsmaker/objectives/detect_few_shot.py +21 -0
  97. pidsmaker/objectives/one_class.py +75 -0
  98. pidsmaker/objectives/predict_edge_contrastive.py +165 -0
  99. pidsmaker/objectives/predict_edge_supervised.py +77 -0
  100. pidsmaker/objectives/predict_edge_type.py +28 -0
  101. pidsmaker/objectives/predict_masked_struct.py +49 -0
  102. pidsmaker/objectives/predict_node_type.py +36 -0
  103. pidsmaker/objectives/predict_process_tag.py +169 -0
  104. pidsmaker/objectives/predict_snapshot_embedding.py +97 -0
  105. pidsmaker/objectives/reconstruct_edge_emb.py +16 -0
  106. pidsmaker/objectives/reconstruct_masked_feat.py +51 -0
  107. pidsmaker/objectives/reconstruct_node_emb.py +13 -0
  108. pidsmaker/objectives/reconstruct_node_feat.py +13 -0
  109. pidsmaker/objectives/validation_wrapper.py +55 -0
  110. pidsmaker/preprocessing/__init__.py +0 -0
  111. pidsmaker/preprocessing/build_graph_methods/__init__.py +1 -0
  112. pidsmaker/preprocessing/build_graph_methods/build_default_graphs.py +830 -0
  113. pidsmaker/preprocessing/build_graph_methods/build_magic_graphs.py +220 -0
  114. pidsmaker/preprocessing/cleaning.py +258 -0
  115. pidsmaker/preprocessing/transformation_methods/__init__.py +2 -0
  116. pidsmaker/preprocessing/transformation_methods/attack_generation/synthetic_attack_naive.py +194 -0
  117. pidsmaker/preprocessing/transformation_methods/transformation_dag.py +28 -0
  118. pidsmaker/preprocessing/transformation_methods/transformation_merge_edges.py +136 -0
  119. pidsmaker/preprocessing/transformation_methods/transformation_rcaid_pseudo_graph.py +510 -0
  120. pidsmaker/preprocessing/transformation_methods/transformation_undirected.py +24 -0
  121. pidsmaker/preprocessing/transformation_methods/transformation_utils.py +36 -0
  122. pidsmaker/pretrained/__init__.py +5 -0
  123. pidsmaker/pretrained/data/__init__.py +4 -0
  124. pidsmaker/pretrained/data/behavior_signatures.py +548 -0
  125. pidsmaker/pretrained/data/canonical_tokens.py +1035 -0
  126. pidsmaker/pretrained/data/edge_filter.py +381 -0
  127. pidsmaker/pretrained/data/entity_classes.py +476 -0
  128. pidsmaker/pretrained/data/sampler.py +926 -0
  129. pidsmaker/pretrained/data/tokenizer_bpe.py +1659 -0
  130. pidsmaker/pretrained/detect.py +1432 -0
  131. pidsmaker/pretrained/embedding_generator.py +252 -0
  132. pidsmaker/pretrained/finetune.py +1437 -0
  133. pidsmaker/pretrained/models/__init__.py +20 -0
  134. pidsmaker/pretrained/models/behavior.py +348 -0
  135. pidsmaker/pretrained/models/bert.py +286 -0
  136. pidsmaker/pretrained/models/deepwalk.py +128 -0
  137. pidsmaker/pretrained/models/dgi.py +120 -0
  138. pidsmaker/pretrained/models/gae.py +114 -0
  139. pidsmaker/pretrained/models/gnn_distill.py +475 -0
  140. pidsmaker/pretrained/models/graphmae.py +373 -0
  141. pidsmaker/pretrained/models/hf_pretrained.py +213 -0
  142. pidsmaker/pretrained/models/llama.py +110 -0
  143. pidsmaker/pretrained/models/modernbert.py +567 -0
  144. pidsmaker/pretrained/models/roberta.py +147 -0
  145. pidsmaker/pretrained/models/rope_utils.py +99 -0
  146. pidsmaker/pretrained/models/ropebert.py +322 -0
  147. pidsmaker/pretrained/models/spider.py +204 -0
  148. pidsmaker/pretrained/models/tgn.py +770 -0
  149. pidsmaker/pretrained/pretrain/__init__.py +3 -0
  150. pidsmaker/pretrained/pretrain/pretrain_behavior_cluster.py +513 -0
  151. pidsmaker/pretrained/pretrain/pretrain_common.py +585 -0
  152. pidsmaker/pretrained/pretrain/pretrain_deepwalk.py +31 -0
  153. pidsmaker/pretrained/pretrain/pretrain_dgi.py +143 -0
  154. pidsmaker/pretrained/pretrain/pretrain_gae.py +143 -0
  155. pidsmaker/pretrained/pretrain/pretrain_gnn_distill.py +438 -0
  156. pidsmaker/pretrained/pretrain/pretrain_graphmae.py +151 -0
  157. pidsmaker/pretrained/pretrain/pretrain_hf.py +169 -0
  158. pidsmaker/pretrained/pretrain/pretrain_main.py +276 -0
  159. pidsmaker/pretrained/pretrain/pretrain_mlm.py +491 -0
  160. pidsmaker/pretrained/pretrain/pretrain_spider.py +502 -0
  161. pidsmaker/pretrained/training_utils.py +157 -0
  162. pidsmaker/process_reapr_gt.py +101 -0
  163. pidsmaker/resources/Ground_Truth/orthrus/E3-CADETS/node_Nginx_Backdoor_06.csv +8 -0
  164. pidsmaker/resources/Ground_Truth/orthrus/E3-CADETS/node_Nginx_Backdoor_11.csv +4 -0
  165. pidsmaker/resources/Ground_Truth/orthrus/E3-CADETS/node_Nginx_Backdoor_12.csv +43 -0
  166. pidsmaker/resources/Ground_Truth/orthrus/E3-CADETS/node_Nginx_Backdoor_13.csv +24 -0
  167. pidsmaker/resources/Ground_Truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0411.csv +41 -0
  168. pidsmaker/resources/Ground_Truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0412.csv +0 -0
  169. pidsmaker/resources/Ground_Truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_browser_0412.csv +1 -0
  170. pidsmaker/resources/Ground_Truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +63 -0
  171. pidsmaker/resources/Ground_Truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +56 -0
  172. pidsmaker/resources/Ground_Truth/orthrus/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +61 -0
  173. pidsmaker/resources/Ground_Truth/orthrus/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +58 -0
  174. pidsmaker/resources/Ground_Truth/orthrus/E3-TRACE/node_trace_e3_firefox_0410.csv +11 -0
  175. pidsmaker/resources/Ground_Truth/orthrus/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +11 -0
  176. pidsmaker/resources/Ground_Truth/orthrus/E3-TRACE/node_trace_e3_pine_0413.csv +14 -0
  177. pidsmaker/resources/Ground_Truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT.csv +19 -0
  178. pidsmaker/resources/Ground_Truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT_17.csv +107 -0
  179. pidsmaker/resources/Ground_Truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_appstarter_0515.csv +26 -0
  180. pidsmaker/resources/Ground_Truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_firefox_0517.csv +1 -0
  181. pidsmaker/resources/Ground_Truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_lockwatch_0517.csv +17 -0
  182. pidsmaker/resources/Ground_Truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_tester_0517.csv +8 -0
  183. pidsmaker/resources/Ground_Truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_bits_0515.csv +54 -0
  184. pidsmaker/resources/Ground_Truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_copykatz_0509.csv +87 -0
  185. pidsmaker/resources/Ground_Truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_dns_0517.csv +11 -0
  186. pidsmaker/resources/Ground_Truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_drakon_0517.csv +6 -0
  187. pidsmaker/resources/Ground_Truth/orthrus/E5-THEIA/node_THEIA_1_Firefox_Drakon_APT_BinFmt_Elevate_Inject.csv +70 -0
  188. pidsmaker/resources/Ground_Truth/orthrus/E5-TRACE/node_Trace_Firefox_Drakon.csv +71 -0
  189. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m1.csv +1 -0
  190. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m2.csv +1 -0
  191. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m3.csv +1 -0
  192. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m4.csv +5 -0
  193. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m5.csv +23 -0
  194. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_m6.csv +18 -0
  195. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_s1.csv +1 -0
  196. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_s2.csv +1 -0
  197. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_s3.csv +16 -0
  198. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_edr/atlasv2_edr_s4.csv +22 -0
  199. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m1.csv +126 -0
  200. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m2.csv +105 -0
  201. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m3.csv +94 -0
  202. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m4.csv +139 -0
  203. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m5.csv +228 -0
  204. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_m6.csv +131 -0
  205. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_s1.csv +118 -0
  206. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_s2.csv +89 -0
  207. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_s3.csv +133 -0
  208. pidsmaker/resources/Ground_Truth/orthrus/atlasv2_h1/node_h1_s4.csv +135 -0
  209. pidsmaker/resources/Ground_Truth/orthrus/carbanakv2_edr/carbanakv2_edr.csv +2453 -0
  210. pidsmaker/resources/Ground_Truth/orthrus/h051/node_h051_0925.csv +114 -0
  211. pidsmaker/resources/Ground_Truth/orthrus/h201/node_h201_0923.csv +2905 -0
  212. pidsmaker/resources/Ground_Truth/orthrus/h501/node_h501_0924.csv +749 -0
  213. pidsmaker/resources/Ground_Truth/orthrus/readme.md +98 -0
  214. pidsmaker/resources/Ground_Truth/reapr/E3-CADETS/node_Nginx_Backdoor_06.csv +3 -0
  215. pidsmaker/resources/Ground_Truth/reapr/E3-CADETS/node_Nginx_Backdoor_12.csv +655 -0
  216. pidsmaker/resources/Ground_Truth/reapr/E3-CADETS/node_Nginx_Backdoor_13.csv +770 -0
  217. pidsmaker/resources/Ground_Truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +0 -0
  218. pidsmaker/resources/Ground_Truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +18 -0
  219. pidsmaker/resources/Ground_Truth/reapr/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +42 -0
  220. pidsmaker/resources/Ground_Truth/reapr/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +81 -0
  221. pidsmaker/resources/Ground_Truth/reapr/E3-TRACE/node_trace_e3_firefox_0410.csv +37 -0
  222. pidsmaker/resources/Ground_Truth/reapr/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +9 -0
  223. pidsmaker/resources/Ground_Truth/reapr/E3-TRACE/node_trace_e3_pine_0413.csv +40 -0
  224. pidsmaker/resources/Ground_Truth/threatrace/E3-CADETS/ground_truth.txt +12858 -0
  225. pidsmaker/resources/Ground_Truth/threatrace/E3-FIVEDIRECTIONS/ground_truth.txt +18420 -0
  226. pidsmaker/resources/Ground_Truth/threatrace/E3-THEIA/ground_truth.txt +25363 -0
  227. pidsmaker/resources/Ground_Truth/threatrace/E3-TRACE/ground_truth.txt +68265 -0
  228. pidsmaker/resources/Ground_Truth/threatrace/README.md +123 -0
  229. pidsmaker/resources/config/anomal_e.yml +25 -0
  230. pidsmaker/resources/config/argus.yml +56 -0
  231. pidsmaker/resources/config/attack_edges/cadets_e3.yml +435 -0
  232. pidsmaker/resources/config/attack_edges/cadets_e5.yml +407 -0
  233. pidsmaker/resources/config/attack_edges/theia_e3.yml +382 -0
  234. pidsmaker/resources/config/attack_edges/theia_e5.yml +387 -0
  235. pidsmaker/resources/config/attack_edges/trace_e3.yml +415 -0
  236. pidsmaker/resources/config/attack_edges/trace_e5.yml +417 -0
  237. pidsmaker/resources/config/default.yml +315 -0
  238. pidsmaker/resources/config/egraphsage.yml +95 -0
  239. pidsmaker/resources/config/euler.yml +104 -0
  240. pidsmaker/resources/config/eval/eval_set_clustering.json +3170 -0
  241. pidsmaker/resources/config/experiments/tuning/components/tuning_featurization_methods.yml +29 -0
  242. pidsmaker/resources/config/experiments/tuning/systems/clearscope_e5/tuning_orthrus.yml +14 -0
  243. pidsmaker/resources/config/experiments/tuning/systems/default/tuning_default_baselines.yml +13 -0
  244. pidsmaker/resources/config/experiments/tuning/systems/default/tuning_orthrus_fixed.yml +16 -0
  245. pidsmaker/resources/config/experiments/uncertainty/none.yml +5 -0
  246. pidsmaker/resources/config/experiments/uncertainty/run_n_times.yml +12 -0
  247. pidsmaker/resources/config/experiments/uncertainty/run_n_times_hyperparameters.yml +12 -0
  248. pidsmaker/resources/config/experiments/uncertainty/uncertainty.yml +22 -0
  249. pidsmaker/resources/config/flash.yml +79 -0
  250. pidsmaker/resources/config/jbeil.yml +65 -0
  251. pidsmaker/resources/config/kairos.yml +121 -0
  252. pidsmaker/resources/config/lares.yml +115 -0
  253. pidsmaker/resources/config/magic.yml +86 -0
  254. pidsmaker/resources/config/nodlink.yml +79 -0
  255. pidsmaker/resources/config/ocrapt.yml +91 -0
  256. pidsmaker/resources/config/orthrus.yml +120 -0
  257. pidsmaker/resources/config/orthrus_fixed.yml +17 -0
  258. pidsmaker/resources/config/orthrus_non_snooped.yml +17 -0
  259. pidsmaker/resources/config/pretrained/README.md +101 -0
  260. pidsmaker/resources/config/pretrained/cybergfm/cybergfm.yml +49 -0
  261. pidsmaker/resources/config/pretrained/pretrained.yml +190 -0
  262. pidsmaker/resources/config/pretrained/pretrained_flash.yml +9 -0
  263. pidsmaker/resources/config/pretrained/pretrained_kairos.yml +12 -0
  264. pidsmaker/resources/config/pretrained/pretrained_magic.yml +1 -0
  265. pidsmaker/resources/config/pretrained/pretrained_nodlink.yml +1 -0
  266. pidsmaker/resources/config/pretrained/pretrained_orthrus.yml +1 -0
  267. pidsmaker/resources/config/pretrained/pretrained_supervised.yml +13 -0
  268. pidsmaker/resources/config/pretrained/pretrained_threatrace.yml +8 -0
  269. pidsmaker/resources/config/pretrained/pretrained_velox.yml +14 -0
  270. pidsmaker/resources/config/prographer.yml +136 -0
  271. pidsmaker/resources/config/rcaid.yml +88 -0
  272. pidsmaker/resources/config/shadewatcher.yml +146 -0
  273. pidsmaker/resources/config/tests.yml +10 -0
  274. pidsmaker/resources/config/threatrace.yml +73 -0
  275. pidsmaker/resources/config/tuned_baselines/optc_net/tuned_argus.yml +4 -0
  276. pidsmaker/resources/config/tuned_baselines/optc_net/tuned_lares.yml +13 -0
  277. pidsmaker/resources/config/velox.yml +10 -0
  278. pidsmaker/resources/config/viz_config.yml +10 -0
  279. pidsmaker/tasks/__init__.py +10 -0
  280. pidsmaker/tasks/batching.py +49 -0
  281. pidsmaker/tasks/construction.py +31 -0
  282. pidsmaker/tasks/evaluation.py +232 -0
  283. pidsmaker/tasks/feat_inference.py +413 -0
  284. pidsmaker/tasks/featurization.py +43 -0
  285. pidsmaker/tasks/training.py +19 -0
  286. pidsmaker/tasks/transformation.py +308 -0
  287. pidsmaker/tasks/triage.py +143 -0
  288. pidsmaker/tgn.py +635 -0
  289. pidsmaker/tokenization/__init__.py +112 -0
  290. pidsmaker/tokenization/base.py +58 -0
  291. pidsmaker/tokenization/bpe_tokenizer.py +83 -0
  292. pidsmaker/tokenization/hf_tokenizer.py +61 -0
  293. pidsmaker/tokenization/hierarchical_tokenizer.py +44 -0
  294. pidsmaker/tokenization/label_tokenizer.py +24 -0
  295. pidsmaker/tokenization/nltk_tokenizer.py +84 -0
  296. pidsmaker/tokenization/substitution.py +295 -0
  297. pidsmaker/triage/__init__.py +0 -0
  298. pidsmaker/triage/tracing_methods/__init__.py +1 -0
  299. pidsmaker/triage/tracing_methods/depimpact.py +213 -0
  300. pidsmaker/triage/tracing_methods/depimpact_utils.py +537 -0
  301. pidsmaker/triage/tracing_methods/ocrapt_subgraph.py +267 -0
  302. pidsmaker/utils/__init__.py +0 -0
  303. pidsmaker/utils/cache_utils.py +256 -0
  304. pidsmaker/utils/data_utils.py +1742 -0
  305. pidsmaker/utils/database.py +204 -0
  306. pidsmaker/utils/dataset_utils.py +413 -0
  307. pidsmaker/utils/dataset_writer.py +1057 -0
  308. pidsmaker/utils/graph_store.py +634 -0
  309. pidsmaker/utils/labelling.py +447 -0
  310. pidsmaker/utils/loss_files.py +193 -0
  311. pidsmaker/utils/process_tags.py +44 -0
  312. pidsmaker/utils/utils.py +730 -0
  313. pidsmaker/vizgen/__init__.py +1 -0
  314. pidsmaker/vizgen/dimensionality_reduction.py +249 -0
  315. pidsmaker/vizgen/embed_exporter.py +467 -0
  316. pidsmaker/vizgen/exporter.py +493 -0
  317. pidsmaker/vizgen/html_builder.py +936 -0
  318. pidsmaker/vizgen/web/__init__.py +1 -0
  319. pidsmaker/vizgen/web/export.py +62 -0
  320. pidsmaker/vizgen/web/static/css/app.css +250 -0
  321. pidsmaker/vizgen/web/static/index.html +182 -0
  322. pidsmaker/vizgen/web/static/js/app.js +627 -0
  323. pidsmaker/vizgen/web/static/js/campaign.js +123 -0
  324. pidsmaker/vizgen/web/static/js/data.js +119 -0
  325. pidsmaker/vizgen/web/static/js/dialogs.js +240 -0
  326. pidsmaker/vizgen/web/static/js/jobs.js +75 -0
  327. pidsmaker/vizgen/web/static/js/scene.js +651 -0
  328. pidsmaker/vizgen/web/static/js/ui.js +370 -0
  329. pidsmaker/vizgen/web/static/vendor/OrbitControls.js +1045 -0
  330. pidsmaker/vizgen/web/static/vendor/d3.v4.min.js +2 -0
  331. pidsmaker/vizgen/web/static/vendor/three.min.js +6 -0
  332. pidsmaker/vizgen/web/viz_server.py +2176 -0
  333. pidsmaker-4.0.0.dist-info/METADATA +596 -0
  334. pidsmaker-4.0.0.dist-info/RECORD +338 -0
  335. pidsmaker-4.0.0.dist-info/WHEEL +5 -0
  336. pidsmaker-4.0.0.dist-info/entry_points.txt +2 -0
  337. pidsmaker-4.0.0.dist-info/licenses/LICENSE +201 -0
  338. pidsmaker-4.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,730 @@
1
+ """General utility functions for PIDSMaker.
2
+
3
+ Provides commonly used utilities including:
4
+ - Timestamp conversion (nanoseconds ↔ datetime)
5
+ - Hashing and string manipulation
6
+ - Database connection handling
7
+ - File I/O and path management
8
+ - Logging and progress tracking (log, log_tqdm)
9
+ - Statistical functions (mean, std, percentile)
10
+ - Random seed setting for reproducibility
11
+ """
12
+
13
+ import csv
14
+ import hashlib
15
+ import os
16
+ import random
17
+ import shutil
18
+ import sys
19
+ import time
20
+ from collections import defaultdict
21
+ from datetime import datetime
22
+ from time import mktime
23
+
24
+ import networkx as nx
25
+ import nltk
26
+ import numpy as np
27
+ import pytz
28
+ import torch
29
+ from tqdm import tqdm
30
+
31
+ try: # Only hit the network when the tokenizer data is actually missing
32
+ nltk.data.find("tokenizers/punkt")
33
+ except LookupError:
34
+ nltk.download("punkt", quiet=True)
35
+
36
+ from pidsmaker.config import update_cfg_for_multi_dataset
37
+ from pidsmaker.utils.database import events_order_sql
38
+
39
+
40
+ def stringtomd5(originstr):
41
+ """Convert string to MD5 hash (using SHA256).
42
+
43
+ Args:
44
+ originstr: String to hash
45
+
46
+ Returns:
47
+ str: Hexadecimal hash digest
48
+ """
49
+ originstr = originstr.encode("utf-8")
50
+ signaturemd5 = hashlib.sha256()
51
+ signaturemd5.update(originstr)
52
+ return signaturemd5.hexdigest()
53
+
54
+
55
+ def ns_time_to_datetime(ns):
56
+ """
57
+ :param ns: int nano timestamp
58
+ :return: datetime format: 2013-10-10 23:40:00.000000000
59
+ """
60
+ dt = datetime.fromtimestamp(int(ns) // 1000000000)
61
+ s = dt.strftime("%Y-%m-%d %H:%M:%S")
62
+ s += "." + str(int(int(ns) % 1000000000)).zfill(9)
63
+ return s
64
+
65
+
66
+ def ns_time_to_datetime_US(ns, timezone="US/Eastern"):
67
+ """
68
+ :param ns: int nano timestamp
69
+ :return: datetime format: 2013-10-10 23:40:00.000000000
70
+ """
71
+ tz = pytz.timezone(timezone)
72
+ dt = pytz.datetime.datetime.fromtimestamp(int(ns) // 1000000000, tz)
73
+ s = dt.strftime("%Y-%m-%d %H:%M:%S")
74
+ s += "." + str(int(int(ns) % 1000000000)).zfill(9)
75
+ return s
76
+
77
+
78
+ def time_to_datetime_US(s, timezone="US/Eastern"):
79
+ """
80
+ :param ns: int nano timestamp
81
+ :return: datetime format: 2013-10-10 23:40:00
82
+ """
83
+ tz = pytz.timezone(timezone)
84
+ dt = pytz.datetime.datetime.fromtimestamp(int(s), tz)
85
+ s = dt.strftime("%Y-%m-%d %H:%M:%S")
86
+
87
+ return s
88
+
89
+
90
+ def datetime_to_ns_time(date):
91
+ """
92
+ :param date: str format: %Y-%m-%d %H:%M:%S e.g. 2013-10-10 23:40:00
93
+ :return: nano timestamp
94
+ """
95
+ timeArray = time.strptime(date, "%Y-%m-%d %H:%M:%S")
96
+ timeStamp = int(time.mktime(timeArray))
97
+ timeStamp = timeStamp * 1000000000
98
+ return timeStamp
99
+
100
+
101
+ def datetime_to_ns_time_US(date, timezone="US/Eastern"):
102
+ """
103
+ :param date: str format: %Y-%m-%d %H:%M:%S e.g. 2013-10-10 23:40:00
104
+ :return: nano timestamp
105
+ """
106
+ tz = pytz.timezone(timezone)
107
+ timeArray = time.strptime(date, "%Y-%m-%d %H:%M:%S")
108
+ dt = datetime.fromtimestamp(mktime(timeArray))
109
+ timestamp = tz.localize(dt)
110
+ timestamp = timestamp.timestamp()
111
+ timeStamp = timestamp * 1000000000
112
+ return int(timeStamp)
113
+
114
+
115
+ def datetime_to_timestamp_US(date, timezone="US/Eastern"):
116
+ """
117
+ :param date: str format: %Y-%m-%d %H:%M:%S e.g. 2013-10-10 23:40:00
118
+ :return: nano timestamp
119
+ """
120
+ tz = pytz.timezone(timezone)
121
+ timeArray = time.strptime(date, "%Y-%m-%d %H:%M:%S")
122
+ dt = datetime.fromtimestamp(mktime(timeArray))
123
+ timestamp = tz.localize(dt)
124
+ timestamp = timestamp.timestamp()
125
+ timeStamp = timestamp
126
+ return int(timeStamp)
127
+
128
+
129
+ def OPTC_datetime_to_timestamp_US(date, timezone="Etc/GMT+4"):
130
+ """convert OPTC datetime string to timestamp in nanoseconds"""
131
+ date = date.replace("-04:00", "")
132
+ if "." in date:
133
+ date, ms = date.split(".")
134
+ else:
135
+ ms = 0
136
+ tz = pytz.timezone("Etc/GMT+4")
137
+ timeArray = time.strptime(date, "%Y-%m-%dT%H:%M:%S")
138
+ dt = datetime.fromtimestamp(mktime(timeArray))
139
+ timestamp = tz.localize(dt)
140
+ timestamp = timestamp.timestamp()
141
+ timeStamp = timestamp * 1000 + int(ms)
142
+ return int(timeStamp) * 1000000
143
+
144
+
145
+ def init_database_connection(cfg):
146
+ """(cursor, connection) of the database of the dataset (see `pidsmaker/utils/database.py`)."""
147
+ from pidsmaker.utils.database import init_database_connection as _init
148
+
149
+ return _init(cfg)
150
+
151
+
152
+ def std(t):
153
+ t = np.array(t)
154
+ return np.std(t)
155
+
156
+
157
+ def var(t):
158
+ t = np.array(t)
159
+ return np.var(t)
160
+
161
+
162
+ def mean(t):
163
+ t = np.array(t)
164
+ return np.mean(t)
165
+
166
+
167
+ def percentile_90(t):
168
+ sorted_data = np.sort(t)
169
+ Q = np.percentile(sorted_data, 90)
170
+ return Q
171
+
172
+
173
+ def gen_darpa_rw_file(walk_len, corpus_fd, adjfilename, overall_fd, num_walks=10):
174
+ adj_list = {}
175
+ back_adj_list = {}
176
+ with open(adjfilename, "r") as adj_file:
177
+ for line in log_tqdm(adj_file, desc="Creating adj list"):
178
+ line = line.strip().split(",")
179
+ srcID = line[0]
180
+ dstID = line[1]
181
+ edgeLabel = line[4]
182
+
183
+ if srcID not in adj_list:
184
+ adj_list[srcID] = {}
185
+
186
+ if dstID not in adj_list[srcID]:
187
+ adj_list[srcID][dstID] = set()
188
+
189
+ if dstID not in back_adj_list:
190
+ back_adj_list[dstID] = {}
191
+
192
+ if srcID not in back_adj_list[dstID]:
193
+ back_adj_list[dstID][srcID] = set()
194
+
195
+ adj_list[srcID][dstID].add(edgeLabel)
196
+ back_adj_list[dstID][srcID].add(edgeLabel)
197
+
198
+ if True:
199
+ lines_buffer = []
200
+
201
+ # Computing random neighbors for each iteration is extremely slow.
202
+ # We thus pre-compute a list of random indices for all unique numbers of neighbors.
203
+ # These indices can then be accessed given the length of the neighbors.
204
+ unique_neighbors_count = set(len(v) for v in adj_list.values()) | set(
205
+ len(v) for v in back_adj_list.values()
206
+ )
207
+ cache_size = 10 * len(adj_list) * num_walks * walk_len
208
+ random_cache = {
209
+ count: np.random.randint(0, count, size=cache_size) for count in unique_neighbors_count
210
+ }
211
+ random_idx = {count: 0 for count in unique_neighbors_count}
212
+
213
+ def get_rand(count):
214
+ if count not in random_cache:
215
+ return np.random.randint(0, count)
216
+ idx = random_idx[count]
217
+ val = random_cache[count][idx]
218
+ random_idx[count] = (idx + 1) % cache_size # Wrap-around cache
219
+ return val
220
+
221
+ for src in log_tqdm(adj_list, desc="Forward random walking"):
222
+ walk_num = len(adj_list[src]) * num_walks
223
+ for i in range(walk_num):
224
+ start = src
225
+ path_sentence = []
226
+ for j in range(walk_len):
227
+ start_keys = list(adj_list[start].keys())
228
+ dst = start_keys[get_rand(len(start_keys))]
229
+
230
+ start_dst = list(adj_list[start][dst])
231
+ edge_type = start_dst[get_rand(len(start_dst))]
232
+
233
+ if len(path_sentence) == 0:
234
+ # path_sentence.append(f"{graph.nodes[start]['label']},{edge_type},{graph.nodes[dst]['label']}")
235
+ path_sentence.append(f"{start},{edge_type},{dst}")
236
+ else:
237
+ # path_sentence.append(f"{edge_type},{graph.nodes[dst]['label']}")
238
+ path_sentence.append(f"{edge_type},{dst}")
239
+
240
+ if dst not in adj_list:
241
+ break
242
+ else:
243
+ start = dst
244
+
245
+ # We do not consider the nodes without any outgoing edges.
246
+ # We only record the paths.
247
+ if len(path_sentence) != 0:
248
+ path_str = ",".join(path_sentence)
249
+ lines_buffer.append(path_str)
250
+
251
+ # Run bidirectional random walking to ensure that every node appears in the corpus
252
+ # Missing sink nodes leads to issues when training A La Carte Matrix
253
+ for dst in log_tqdm(back_adj_list, desc="Backward random walking"):
254
+ walk_num = len(back_adj_list[dst]) * num_walks # NOTE: it seems a lot
255
+ for i in range(walk_num):
256
+ start = dst
257
+ path_sentence = []
258
+ for j in range(walk_len):
259
+ start_keys = list(back_adj_list[start].keys())
260
+ src = start_keys[get_rand(len(start_keys))]
261
+
262
+ start_src = list(back_adj_list[start][src])
263
+ edge_type = start_src[get_rand(len(start_src))]
264
+
265
+ if len(path_sentence) == 0:
266
+ # path_sentence.append(f"{graph.nodes[start]['label']},{edge_type},{graph.nodes[dst]['label']}")
267
+ path_sentence.append(f"{start},{edge_type},{src}")
268
+ else:
269
+ # path_sentence.append(f"{edge_type},{graph.nodes[dst]['label']}")
270
+ path_sentence.append(f"{edge_type},{src}")
271
+
272
+ if src not in back_adj_list:
273
+ break
274
+ else:
275
+ start = src
276
+
277
+ # We do not consider the nodes without any outgoing edges.
278
+ # We only record the paths.
279
+ if len(path_sentence) != 0:
280
+ path_str = ",".join(path_sentence)
281
+ lines_buffer.append(path_str)
282
+
283
+ lines = "\n".join(lines_buffer)
284
+ corpus_fd.write(lines)
285
+ overall_fd.write(lines)
286
+
287
+
288
+ def gen_darpa_adj_files(graph, filename):
289
+ with open(filename, "w") as f:
290
+ writer = csv.writer(f)
291
+ for u, v, k in graph.edges:
292
+ # srcID, dstID, srcLabel, dstLabel, edgeLabel
293
+ data = [
294
+ u,
295
+ v,
296
+ graph.nodes[u]["label"],
297
+ graph.nodes[v]["label"],
298
+ graph.edges[u, v, k]["label"] if "label" in graph.edges[u, v, k] else "",
299
+ graph.nodes[u]["node_type"],
300
+ graph.nodes[v]["node_type"],
301
+ ]
302
+ writer.writerow(data)
303
+ f.close()
304
+
305
+
306
+ def log_start(_file_: str):
307
+ log(f"======= START SUBTASK {os.path.basename(_file_)} =======")
308
+
309
+
310
+ def get_all_files_from_folders(base_dir: str, folders: list[str]):
311
+ paths = [
312
+ os.path.abspath(os.path.join(base_dir, sub, f))
313
+ for sub in os.listdir(base_dir)
314
+ if os.path.isdir(os.path.join(base_dir, sub)) and sub in folders
315
+ for f in os.listdir(os.path.join(base_dir, sub))
316
+ ]
317
+ paths.sort(key=lambda f: int("".join(filter(str.isdigit, f))))
318
+ return paths
319
+
320
+
321
+ def get_all_graphs_for_dates(base_dir: str, dates: list[str]):
322
+ return get_all_files_from_folders(base_dir, [f"graph_{date}" for date in dates])
323
+
324
+
325
+ def load_graphs_for_dates(base_dir: str, dates: list[str]):
326
+ """Loads all graph snapshots for a given list of dates."""
327
+ return [
328
+ torch.load(path) for date in dates for path in get_all_graphs_for_dates(base_dir, [date])
329
+ ]
330
+
331
+
332
+ def get_all_filelist(filepath):
333
+ """get all file paths under the given filepath recursively"""
334
+ file_paths = []
335
+ for root, dirs, files in os.walk(filepath):
336
+ for file in files:
337
+ full_path = os.path.join(root, file)
338
+ abs_path = os.path.abspath(full_path)
339
+ file_paths.append(abs_path)
340
+ return file_paths
341
+
342
+
343
+ def listdir_sorted(path: str):
344
+ files = os.listdir(path)
345
+ files.sort(key=lambda f: int("".join(filter(str.isdigit, f)))) # sorted by ascending number
346
+ return files
347
+
348
+
349
+ def remove_underscore_keys(data, keys_to_keep=[], keys_to_rm=[]):
350
+ for key in list(data.keys()):
351
+ if (key in keys_to_rm) or (key.startswith("_") and key not in keys_to_keep):
352
+ del data[key]
353
+ elif isinstance(data[key], dict):
354
+ data[key] = dict(data[key])
355
+ remove_underscore_keys(data[key], keys_to_keep, keys_to_rm)
356
+ return data
357
+
358
+
359
+ def log(msg: str, return_line=False, pre_return_line=False, *args, **kwargs):
360
+ if pre_return_line:
361
+ print("")
362
+
363
+ now = datetime.now()
364
+ timestamp = now.strftime("%Y-%m-%d %H:%M:%S")
365
+ # Flushed, so that logs redirected to a file (e.g. `nohup.out` of run.sh) are written as
366
+ # they come, instead of minutes later when the output buffer is full
367
+ kwargs.setdefault("flush", True)
368
+ print(f"{timestamp} - {msg}", *args, **kwargs)
369
+
370
+ if return_line:
371
+ print("", flush=True)
372
+
373
+
374
+ DISABLE_TQDM = True
375
+
376
+
377
+ def log_tqdm(iterator, desc="", logging=True, **kwargs):
378
+ now = datetime.now()
379
+ timestamp = now.strftime("%Y-%m-%d %H:%M:%S")
380
+ if DISABLE_TQDM and logging:
381
+ log(f"{desc}...")
382
+ return tqdm(iterator, desc=f"{timestamp} - {desc}", disable=DISABLE_TQDM, **kwargs)
383
+
384
+
385
+ LOW_MEMORY_GB = 16
386
+
387
+
388
+ def available_memory_gb():
389
+ """RAM usable by this process, in GB: the RAM of the machine (or of the Docker VM on macOS),
390
+ or the memory limit of the container if it is lower. None if it cannot be read."""
391
+ try:
392
+ import psutil
393
+
394
+ total = psutil.virtual_memory().total
395
+ except Exception:
396
+ return None
397
+ # Memory limit of the container (cgroup v2, then v1); "max" or a huge value means no limit
398
+ for path in ("/sys/fs/cgroup/memory.max", "/sys/fs/cgroup/memory/memory.limit_in_bytes"):
399
+ try:
400
+ with open(path) as f:
401
+ limit = f.read().strip()
402
+ if limit.isdigit():
403
+ total = min(total, int(limit))
404
+ break
405
+ except OSError:
406
+ continue
407
+ return total / (1024**3)
408
+
409
+
410
+ def warn_if_low_memory(min_gb=LOW_MEMORY_GB):
411
+ """Warns when less than `min_gb` of RAM are available, e.g. in Docker Desktop on macOS,
412
+ whose VM has 8 GB by default: runs killed by the kernel when they run out of memory
413
+ otherwise only print `Killed`."""
414
+ memory_gb = available_memory_gb()
415
+ if memory_gb is not None and memory_gb < min_gb:
416
+ log(
417
+ f"Warning: only {memory_gb:.1f} GB of RAM are available, runs on large datasets may "
418
+ f"be killed when they run out of memory. With Docker Desktop (macOS), give more "
419
+ f"memory to its VM: https://ubc-provenance.github.io/PIDSMaker/getting-started/"
420
+ f"installation/#macos"
421
+ )
422
+ return memory_gb
423
+
424
+
425
+ class PeakCPUMemory:
426
+ """Cheap peak resident memory (RSS) tracker, in GB.
427
+
428
+ Replaces `tracemalloc`, which slows down every Python allocation and does not see
429
+ the memory allocated by torch/numpy. On Linux, the RSS high-water mark is reset at
430
+ `start()` through `/proc/self/clear_refs`; elsewhere, the process lifetime peak is used.
431
+ """
432
+
433
+ def start(self):
434
+ try:
435
+ with open("/proc/self/clear_refs", "w") as f:
436
+ f.write("5")
437
+ except OSError:
438
+ pass
439
+ return self
440
+
441
+ @staticmethod
442
+ def peak_gb():
443
+ try:
444
+ with open("/proc/self/status") as f:
445
+ for line in f:
446
+ if line.startswith("VmHWM:"):
447
+ return int(line.split()[1]) / (1024**2) # kB -> GB
448
+ except OSError:
449
+ pass
450
+ import resource
451
+
452
+ # ru_maxrss is in bytes on macOS, and in kB on Linux
453
+ unit = 1 if sys.platform == "darwin" else 1024
454
+ return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss * unit / (1024**3)
455
+
456
+
457
+ def get_device(cfg):
458
+ if cfg._use_cpu:
459
+ return torch.device("cpu")
460
+
461
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
462
+ if device == torch.device("cpu"):
463
+ log("Warning: the device is CPU instead of CUDA")
464
+ return device
465
+
466
+ def copy_directory(src_path, dest_path):
467
+ if not os.path.isdir(src_path):
468
+ log(f"The source path '{src_path}' does not exist or is not a directory.")
469
+ return
470
+
471
+ if os.path.exists(dest_path):
472
+ log(f"The destination path '{dest_path}' already exists. Removing it for a fresh copy.")
473
+ shutil.rmtree(dest_path)
474
+
475
+ try:
476
+ shutil.copytree(src_path, dest_path)
477
+ log(f"Directory copied successfully from '{src_path}' to '{dest_path}'.")
478
+ except Exception as e:
479
+ log(f"An error occurred while copying the directory: {e}")
480
+
481
+
482
+ def symlink_directory(src_path, dest_path):
483
+ src_path = src_path.rstrip("/")
484
+ dest_path = dest_path.rstrip("/")
485
+
486
+ if not os.path.isdir(src_path):
487
+ log(f"The source path '{src_path}' does not exist or is not a directory.")
488
+ return
489
+
490
+ if os.path.islink(dest_path):
491
+ os.remove(dest_path)
492
+ elif os.path.exists(dest_path):
493
+ log(f"The destination path '{dest_path}' already exists. Removing it.")
494
+ shutil.rmtree(dest_path)
495
+
496
+ src_path = os.path.abspath(src_path)
497
+ os.makedirs(os.path.dirname(dest_path), exist_ok=True)
498
+ os.symlink(src_path, dest_path)
499
+ log(f"Symlinked '{dest_path}' -> '{src_path}'.")
500
+
501
+
502
+ def get_split_to_files(cfg, base_dir):
503
+ return {
504
+ "train": get_all_graphs_for_dates(base_dir, cfg.dataset.train_dates),
505
+ "val": get_all_graphs_for_dates(base_dir, cfg.dataset.val_dates),
506
+ "test": get_all_graphs_for_dates(base_dir, cfg.dataset.test_dates),
507
+ }
508
+
509
+
510
+ def gen_relation_onehot(rel2id):
511
+ num_rels = len(rel2id.keys()) // 2
512
+ max_id = max(v for v in rel2id.values() if type(v) is int)
513
+ relvec = torch.nn.functional.one_hot(
514
+ torch.arange(0, max_id), num_classes=max_id
515
+ )
516
+ rel2vec = {}
517
+ for i in rel2id.keys():
518
+ if type(i) is not int:
519
+ rel2vec[i] = relvec[rel2id[i] - 1]
520
+ rel2vec[relvec[rel2id[i] - 1]] = i
521
+ return rel2vec
522
+
523
+
524
+ def get_indexid2msg(cfg, gather_multi_dataset=False):
525
+ def load_file(cfg):
526
+ indexid2msg_file = os.path.join(cfg.construction._dicts_dir, "indexid2msg.pkl")
527
+ indexid2msg = torch.load(indexid2msg_file)
528
+ return indexid2msg
529
+
530
+ if gather_multi_dataset:
531
+ multi_datasets = get_multi_datasets(cfg)
532
+ log(f"Multi-dataset order: {multi_datasets}")
533
+
534
+ all_indexid2msg = {}
535
+ cumsum = 0
536
+ for dataset in multi_datasets:
537
+ cfg, _ = update_cfg_for_multi_dataset(cfg, dataset)
538
+
539
+ indexid2msg = load_file(cfg)
540
+ max_node = max(map(int, list(indexid2msg.keys())))
541
+ indexid2msg = {str(int(k) + cumsum): v for k, v in indexid2msg.items()}
542
+ cumsum += max_node
543
+
544
+ # Merge the cumsumed indices and original values from all datasets
545
+ all_indexid2msg = {**all_indexid2msg, **indexid2msg}
546
+ return all_indexid2msg
547
+
548
+ return load_file(cfg)
549
+
550
+
551
+ def get_split2nodes(cfg, gather_multi_dataset=False):
552
+ def load_file(cfg):
553
+ path = os.path.join(cfg.construction._dicts_dir, "split2nodes.pkl")
554
+ split2nodes = torch.load(path)
555
+ return split2nodes
556
+
557
+ multi_datasets = get_multi_datasets(cfg)
558
+ use_multi_dataset = "none" not in cfg.construction.multi_dataset
559
+
560
+ if gather_multi_dataset and use_multi_dataset:
561
+ all_split2nodes = defaultdict(set)
562
+ cumsum = 0
563
+ for dataset in multi_datasets:
564
+ cfg, _ = update_cfg_for_multi_dataset(cfg, dataset)
565
+
566
+ split2nodes = load_file(cfg)
567
+ indexid2msg = get_indexid2msg(cfg)
568
+ max_node = max(map(int, list(indexid2msg.keys())))
569
+ split2nodes = {k: {str(int(e) + cumsum) for e in v} for k, v in split2nodes.items()}
570
+ cumsum += max_node
571
+
572
+ for k, v in split2nodes.items():
573
+ all_split2nodes[k] |= v
574
+ return all_split2nodes
575
+
576
+ return load_file(cfg)
577
+
578
+
579
+ def compute_class_weights(labels, num_classes):
580
+ """
581
+ Compute balanced class weights for a given set of labels using PyTorch,
582
+ and pad the weights with 0s if some classes are missing in the batch.
583
+
584
+ Parameters:
585
+ labels (Tensor): A 1D tensor containing class indices for each sample.
586
+ num_classes (int): The number of unique classes.
587
+
588
+ Returns:
589
+ Tensor: A tensor containing the weight for each class, padded to num_classes.
590
+ """
591
+ # From 1-hot to label index
592
+ labels = labels.argmax(dim=-1)
593
+
594
+ # Count the number of instances for each class
595
+ class_counts = torch.bincount(labels, minlength=num_classes).float()
596
+ total_count = len(labels)
597
+
598
+ # Initialize weights with zeros for all classes
599
+ class_weights = torch.zeros(num_classes, device=labels.device)
600
+
601
+ # Avoid division by zero by checking for non-zero class counts
602
+ non_zero_classes = class_counts > 0
603
+ class_weights[non_zero_classes] = total_count / (num_classes * class_counts[non_zero_classes])
604
+
605
+ return class_weights
606
+
607
+
608
+ def calculate_average_from_file(filename):
609
+ numbers = []
610
+ try:
611
+ with open(filename, "r") as f:
612
+ for line in f:
613
+ numbers.append(float(line.strip()))
614
+ if numbers:
615
+ return sum(numbers) / len(numbers)
616
+ else:
617
+ return 1e-9
618
+ except FileNotFoundError:
619
+ log(f"{filename} does not exist")
620
+ return None
621
+
622
+
623
+ def get_events_between_GPs(cur, start_time, end_time, malicious_nodes: list):
624
+ malicious_nodes_str = ", ".join(f"'{node}'" for node in malicious_nodes)
625
+ sql = f"SELECT * FROM event_table WHERE timestamp_rec BETWEEN '{start_time}' AND '{end_time}' AND src_index_id IN ({malicious_nodes_str}) AND dst_index_id IN ({malicious_nodes_str}) {events_order_sql(cur)};"
626
+ cur.execute(sql)
627
+ rows = cur.fetchall()
628
+ return rows
629
+
630
+
631
+ def get_events_between_time_range(
632
+ cur,
633
+ start_time,
634
+ end_time,
635
+ ):
636
+ sql = f"SELECT * FROM event_table WHERE timestamp_rec BETWEEN '{start_time}' AND '{end_time}' {events_order_sql(cur)};"
637
+ cur.execute(sql)
638
+ rows = cur.fetchall()
639
+ return rows
640
+
641
+
642
+ def generate_DAG(edges):
643
+ node_version = {}
644
+ for u, v, t in edges:
645
+ if u not in node_version:
646
+ node_version[u] = 0
647
+ if v not in node_version:
648
+ node_version[v] = 0
649
+
650
+ sorted_edges = sorted(edges, key=lambda x: x[2])
651
+
652
+ new_nodes = set()
653
+ new_edges = []
654
+ visited = set()
655
+ for u, v, t in sorted_edges:
656
+ if u == v:
657
+ continue
658
+
659
+ src = str(u) + "-" + str(node_version[u])
660
+ visited.add(u)
661
+ new_nodes.add(src)
662
+
663
+ if v not in visited:
664
+ dst = str(v) + "-" + str(node_version[v])
665
+ visited.add(v)
666
+ new_nodes.add(dst)
667
+ new_edges.append((src, dst, {"time": int(t)}))
668
+ else:
669
+ dst_current = str(v) + "-" + str(node_version[v])
670
+ dst_new = str(v) + "-" + str(node_version[v] + 1)
671
+ node_version[v] += 1
672
+ new_nodes.add(dst_new)
673
+ new_edges.append((src, dst_new, {"time": int(t)}))
674
+ new_edges.append((dst_current, dst_new, {"time": int(t)}))
675
+
676
+ DAG = nx.DiGraph()
677
+ DAG.add_nodes_from(list(new_nodes))
678
+ DAG.add_edges_from(new_edges)
679
+
680
+ return DAG, node_version
681
+
682
+
683
+ def log_dataset_stats(datasets):
684
+ def log_helper(label, dataset):
685
+ edges = torch.tensor([d.src.shape[0] for d in dataset])
686
+ nodes = torch.tensor([torch.unique(d.edge_index).shape[0] for d in dataset])
687
+
688
+ log(f"{label} num graphs: {len(dataset)}")
689
+ log(
690
+ f"{label} edges | mean: {int(torch.mean(edges, dtype=torch.float))} | min: {int(torch.min(edges))} | max: {int(torch.max(edges))}"
691
+ )
692
+ log(
693
+ f"{label} nodes | mean: {int(torch.mean(nodes, dtype=torch.float))} | min: {int(torch.min(nodes))} | max: {int(torch.max(nodes))}"
694
+ )
695
+ log("")
696
+
697
+ train_data, val_data, test_data = datasets
698
+ log("")
699
+ log("Dataset statistics")
700
+ for train_graphs, val_graphs in zip(train_data, val_data):
701
+ for label, dataset in [("Train", train_graphs), ("Val", val_graphs)]:
702
+ log_helper(label, dataset)
703
+
704
+ for test_graphs in test_data:
705
+ for label, dataset in [("Test", test_graphs)]:
706
+ log_helper(label, dataset)
707
+
708
+
709
+ def set_seed(cfg, seed=None):
710
+ seed = seed or cfg.training.seed
711
+ random.seed(seed)
712
+ np.random.seed(seed)
713
+
714
+ torch.manual_seed(seed)
715
+ torch.cuda.manual_seed_all(seed)
716
+ torch.backends.cudnn.deterministic = True
717
+ torch.backends.cudnn.benchmark = False
718
+
719
+ if cfg.training.deterministic:
720
+ # NOTE: must do `export CUBLAS_WORKSPACE_CONFIG=:4096:8`
721
+ torch.use_deterministic_algorithms(True, warn_only=True)
722
+
723
+
724
+ def get_multi_datasets(cfg):
725
+ # The main dataset should be always the first one
726
+ multi_dataset = cfg.construction.multi_dataset
727
+ multi_datasets = list(
728
+ map(lambda x: x.strip(), multi_dataset.split("," if "," in multi_dataset else "-"))
729
+ )
730
+ return [cfg.dataset.name] + [d for d in multi_datasets if d != cfg.dataset.name]