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,1824 @@
1
+ import argparse
2
+ import hashlib
3
+ import os
4
+ import pathlib
5
+ import sys
6
+ import uuid
7
+ from collections import OrderedDict
8
+ from copy import deepcopy
9
+
10
+ import yaml
11
+ from yacs.config import CfgNode as CN
12
+
13
+ from .config import (
14
+ CLEANING_METHODS,
15
+ DATASET_DEFAULT_CONFIG,
16
+ DECODERS_EDGE_LEVEL,
17
+ DECODERS_NODE_LEVEL,
18
+ ENCODER_WRAPPERS,
19
+ ENCODERS_CFG,
20
+ EXPERIMENTS_CONFIG,
21
+ FEATURIZATION_TOKENIZATIONS,
22
+ OBJECTIVES_EDGE_LEVEL,
23
+ OBJECTIVES_NODE_LEVEL,
24
+ PRETRAINED_DEFAULT_TOKENIZATION,
25
+ PRETRAINED_TOKENIZATIONS,
26
+ REQUIRE_HETERO_FEATURES_ENCODERS,
27
+ REQUIRE_NON_REVERSED_EDGES_ENCODERS,
28
+ SUBSTITUTION_METHODS,
29
+ SYNTHETIC_ATTACKS,
30
+ TASK_ARGS,
31
+ TASK_DEPENDENCIES,
32
+ UNCERTAINTY_EXP_YML_FOLDER,
33
+ Arg,
34
+ )
35
+ from .schemas import benign_training, drops_noise_events, get_schema, get_schema_by_name
36
+
37
+
38
+ def _resources_root():
39
+ """Folder of `config/` and `ground_truth/`: `pidsmaker/resources/` when PIDSMaker is
40
+ installed from a wheel (see setup.py), else the root of the repository (source checkout or
41
+ editable install)."""
42
+ package_resources = pathlib.Path(__file__).parent.parent / "resources"
43
+ if (package_resources / "config").is_dir():
44
+ return package_resources.resolve()
45
+ return pathlib.Path(__file__).parent.parent.parent.resolve()
46
+
47
+
48
+ ROOT_PROJECT_PATH = _resources_root()
49
+ ROOT_GROUND_TRUTH_DIR = os.path.join(ROOT_PROJECT_PATH, "ground_truth/")
50
+ DEFAULT_ARTIFACT_DIR = "/home/artifacts/"
51
+
52
+
53
+ def default_artifact_dir():
54
+ """$PIDSMAKER_ARTIFACT_DIR, else /home/artifacts/ if it exists (e.g. on servers), else
55
+ `artifacts/` in the working directory."""
56
+ if os.environ.get("PIDSMAKER_ARTIFACT_DIR"):
57
+ return os.environ["PIDSMAKER_ARTIFACT_DIR"]
58
+ if os.path.isdir(DEFAULT_ARTIFACT_DIR):
59
+ return DEFAULT_ARTIFACT_DIR
60
+ return os.path.join(os.getcwd(), "artifacts", "")
61
+
62
+ # ================================================================================
63
+
64
+
65
+ def get_default_cfg(args):
66
+ """
67
+ Inits the shared cfg object with default configurations.
68
+ """
69
+ cfg = CN()
70
+ cfg._artifact_dir = args.artifact_dir
71
+
72
+ cfg._test_mode = args.test_mode
73
+ cfg._debug = not args.wandb
74
+ cfg._is_running_mc_dropout = False
75
+
76
+ # Split off the special 'viz' keyword so the task validator doesn't choke on it
77
+ force_restart_parts = [t.strip() for t in args.force_restart.split(",") if t.strip()]
78
+ cfg._force_restart_viz = "viz" in force_restart_parts
79
+ cfg._force_restart = ",".join(t for t in force_restart_parts if t != "viz")
80
+ cfg._use_cpu = args.cpu
81
+ # Opt-in: whether to persist the extra (large) artifacts the embedding
82
+ # visualizer needs. Underscore-prefixed so it never enters the task hashes.
83
+ cfg._save_for_viz = getattr(args, "save_for_viz", False)
84
+ cfg._model = args.model
85
+ cfg._tuning_mode = args.tuning_mode
86
+ cfg._experiment = args.experiment
87
+ cfg._tuning_file_path = args.tuning_file_path
88
+ cfg._include_yml = None
89
+ cfg._exp = args.exp
90
+ cfg._tasks_set_from_cli = []
91
+ cfg._save_graph_preprocessing = args.save_graph_preprocessing
92
+ # Underscore-prefixed: parallelism does not change results, so it is not hashed
93
+ cfg._num_workers = getattr(args, "num_workers", None)
94
+ cfg._keep_best_epoch_only = getattr(args, "keep_best_epoch_only", False)
95
+ cfg._shared_node_features = not getattr(args, "no_shared_node_features", False)
96
+ cfg._from_weights = args.from_weights
97
+ cfg._from_weights_path = os.path.join(ROOT_PROJECT_PATH, "weights", args.model, args.dataset)
98
+
99
+ cfg._restart_from_scratch = args.restart_from_scratch
100
+ if cfg._restart_from_scratch:
101
+ cfg._run_random_seed = str(uuid.uuid4())
102
+
103
+ # Datasets (see pidsmaker/utils/database.py)
104
+ cfg.database = CN()
105
+ cfg.database.datasets_dir = getattr(args, "datasets_dir", None)
106
+
107
+ # Dataset: we simply create variables for all configurations described in the dict
108
+ set_dataset_cfg(cfg, args.dataset)
109
+
110
+ # Tasks: we create nested None variables for all arguments
111
+ def create_cfg_recursive(cfg, task_args_dict: dict):
112
+ for task, subtasks in task_args_dict.items():
113
+ if isinstance(subtasks, dict):
114
+ setattr(cfg, task, CN())
115
+ task_cfg = getattr(cfg, task)
116
+ create_cfg_recursive(task_cfg, dict(subtasks.items()))
117
+ else:
118
+ setattr(cfg, task, None)
119
+
120
+ create_cfg_recursive(cfg, TASK_ARGS)
121
+
122
+ # Experiments
123
+ create_cfg_recursive(cfg, EXPERIMENTS_CONFIG)
124
+
125
+ return cfg
126
+
127
+
128
+ def set_dataset_cfg(cfg, dataset):
129
+ cfg.dataset = CN()
130
+ cfg.dataset.name = dataset
131
+ for attr, value in DATASET_DEFAULT_CONFIG[cfg.dataset.name].items():
132
+ setattr(cfg.dataset, attr, value)
133
+ # Number of node and edge types, from the dataset's schema (see `schemas.py`)
134
+ schema = get_schema_by_name(cfg.dataset.schema)
135
+ cfg.dataset.num_node_types = schema.num_node_types
136
+ cfg.dataset.num_edge_types = schema.num_edge_types
137
+
138
+
139
+ def get_runtime_required_args(return_unknown_args=False, args=None):
140
+ parser = argparse.ArgumentParser()
141
+ parser.add_argument("model", type=str, help="Name of the model")
142
+ parser.add_argument("dataset", type=str, help="Name of the dataset")
143
+ parser.add_argument(
144
+ "--force_restart",
145
+ type=str,
146
+ default="",
147
+ help="The subtask or subtasks from which to restart",
148
+ )
149
+ parser.add_argument(
150
+ "--restart_from_scratch",
151
+ action="store_true",
152
+ help="Starts pipeline in a fresh new task path",
153
+ )
154
+ parser.add_argument(
155
+ "--save_for_viz",
156
+ action="store_true",
157
+ help="Persist the extra artifacts the embedding visualizer needs (per-epoch "
158
+ "model checkpoints and a cached copy of the test graphs). Off by default because "
159
+ "these are large and most runs never open the visualizer; enable it on the runs "
160
+ "you intend to explore in the viewer.",
161
+ )
162
+ parser.add_argument("--wandb", action="store_true", help="Whether to submit logs to wandb")
163
+ parser.add_argument(
164
+ "--project", type=str, default="PIDSMaker", help="Name of the wandb project"
165
+ )
166
+ parser.add_argument("--exp", type=str, default="", help="Name of the experiment")
167
+ parser.add_argument(
168
+ "--tags",
169
+ type=str,
170
+ default="",
171
+ help="Name of the tag to use. Tags are used to group runs together",
172
+ )
173
+ parser.add_argument(
174
+ "--cpu", action="store_true", help="Whether to run the framework on CPU rather than GPU"
175
+ )
176
+ parser.add_argument(
177
+ "--experiment", type=str, default="none", help="The experiment yml config file"
178
+ )
179
+ parser.add_argument(
180
+ "--tuning_mode",
181
+ type=str,
182
+ default="none",
183
+ help="Name of the tuning mode to run the pipeline with wandb sweeps",
184
+ )
185
+ parser.add_argument(
186
+ "--tuned", action="store_true", help="Whether to load the best fine-tuned hyperparameters"
187
+ )
188
+ parser.add_argument(
189
+ "--tuning_file_path", default="", help="If set, use the given YML path for tuning"
190
+ )
191
+ parser.add_argument(
192
+ "--datasets_dir",
193
+ default=os.environ.get("PIDSMAKER_DATASETS_DIR"),
194
+ help="Folder of the datasets (Parquet files, read with DuckDB), one subfolder per "
195
+ "database. Default: $PIDSMAKER_DATASETS_DIR, else ~/.cache/pidsmaker/datasets",
196
+ )
197
+ parser.add_argument("--sweep_id", default="", help="ID of a wandb sweep for multi-agent runs")
198
+ parser.add_argument(
199
+ "--artifact_dir",
200
+ default=default_artifact_dir(),
201
+ help="Destination folder for generated files. Default: $PIDSMAKER_ARTIFACT_DIR, else "
202
+ "/home/artifacts/ if it exists, else ./artifacts/",
203
+ )
204
+ parser.add_argument(
205
+ "--num_workers",
206
+ type=int,
207
+ default=None,
208
+ help="Number of processes for CPU-bound preprocessing such as graph construction "
209
+ "(default: min(8, #CPUs)). Results do not depend on it.",
210
+ )
211
+ parser.add_argument(
212
+ "--no_shared_node_features",
213
+ action="store_true",
214
+ help="Stores node features per edge/batch instead of in a shared table rebuilt per "
215
+ "batch (uses much more memory, for debugging; results are identical).",
216
+ )
217
+ parser.add_argument(
218
+ "--keep_best_epoch_only",
219
+ action="store_true",
220
+ help="At the end of the pipeline, deletes the loss files, evaluation pickles and weights "
221
+ "of all epochs except the best one (stats and plots are kept). Saves disk space, but "
222
+ "re-running evaluation afterwards only considers the kept epoch.",
223
+ )
224
+ parser.add_argument(
225
+ "--save_graph_preprocessing", action="store_true", help="Saves `graph_preprocessing` task on disk (heavy)."
226
+ )
227
+ parser.add_argument('--from_weights', action="store_true", help="Whether to load from pkl weights")
228
+ parser.add_argument(
229
+ "--test_mode",
230
+ action="store_true",
231
+ help="Whether to run the framework as in functional tests.",
232
+ )
233
+
234
+ # Script-specific args
235
+ parser.add_argument("--show_attack", type=int, help="Number of attack for plotting", default=0)
236
+ parser.add_argument("--plot_gt", type=bool, help="If we plot ground truth", default=False)
237
+
238
+ # All args in the cfg can be also set in the arg parser from CLI
239
+ all_args = {
240
+ **TASK_ARGS,
241
+ **EXPERIMENTS_CONFIG,
242
+ }
243
+ parser = add_cfg_args_to_parser(all_args, parser)
244
+
245
+ try:
246
+ args, unknown_args = parser.parse_known_args(args)
247
+ except:
248
+ parser.print_help()
249
+ sys.exit(1)
250
+
251
+ if return_unknown_args:
252
+ return args, unknown_args
253
+ return args
254
+
255
+
256
+ def overwrite_cfg_with_args(cfg, args):
257
+ """
258
+ The framework can be also parametrized using the CLI args.
259
+ These args are priorited compared to yml file parameters.
260
+ This function simply overwrites the cfg with the parameters
261
+ given within args.
262
+
263
+ To override a parameter in cfg, use a dotted style:
264
+ ```python pidsmaker/main.py --training.seed=42```
265
+ """
266
+ tasks_set_from_cli = set()
267
+ for arg, value in args.__dict__.items():
268
+ if "." in arg and value is not None:
269
+ tasks_set_from_cli.add(arg.split(".")[0])
270
+ cfg_ptr = cfg
271
+ dots = arg.split(".")
272
+ path, attr_name = dots[:-1], dots[-1]
273
+
274
+ for attr in path:
275
+ cfg_ptr = getattr(cfg_ptr, attr)
276
+ setattr(cfg_ptr, attr_name, value)
277
+
278
+ # Tasks with args given in the CLI, which are run even if absent from the yml file
279
+ cfg._tasks_set_from_cli = sorted(t for t in tasks_set_from_cli if t in TASK_ARGS)
280
+
281
+
282
+ def set_shortcut_variables(cfg):
283
+ decoders = cfg.training.decoder.used_methods
284
+ encoders = cfg.training.encoder.used_methods
285
+
286
+ cfg._is_node_level = decoders is not None and any(
287
+ [
288
+ method
289
+ for method in OBJECTIVES_NODE_LEVEL
290
+ if method in decoders
291
+ ]
292
+ )
293
+
294
+ cfg._is_hetero = encoders is not None and any(
295
+ [
296
+ method
297
+ for method in REQUIRE_HETERO_FEATURES_ENCODERS
298
+ if method in encoders
299
+ ]
300
+ )
301
+
302
+ cfg._require_non_reversed_edges = encoders is not None and any(
303
+ [
304
+ method
305
+ for method in REQUIRE_NON_REVERSED_EDGES_ENCODERS
306
+ if method in encoders
307
+ ]
308
+ )
309
+
310
+ # Node-level and edge-level objectives are combined at the edge level
311
+ objectives = [o.strip() for o in decoders.split(",")] if decoders else []
312
+ cfg._is_hybrid_loss = any(o in OBJECTIVES_NODE_LEVEL for o in objectives) and any(
313
+ o in OBJECTIVES_EDGE_LEVEL for o in objectives
314
+ )
315
+
316
+
317
+
318
+ def set_immutable_cfg(cfg):
319
+ # In some hetero encoders, the reversed edges created by the TGN loader must be removed, or
320
+ # invalid src, dst, edge triplets will exist
321
+ if cfg._require_non_reversed_edges:
322
+ tgn_loader_cfg = cfg.batching.intra_graph_batching.tgn_last_neighbor
323
+ tgn_loader_cfg.fix_buggy_orthrus_TGN = True
324
+ tgn_loader_cfg.directed = True
325
+
326
+ def get_cleaning_methods_from_cfg(cfg):
327
+ cleaning = getattr(cfg.construction, "cleaning", None)
328
+ used_methods = getattr(cleaning, "used_methods", None) if cleaning is not None else None
329
+ if used_methods is None:
330
+ return []
331
+ methods = [m.strip() for m in str(used_methods).split(",") if m.strip()]
332
+ return [m for m in methods if m != "none"]
333
+
334
+
335
+ # Args added after the first releases, by task: they are removed from the hash of their task
336
+ # while they have their default value, so that the artifacts computed before they existed are
337
+ # reused. Keys are paths in the task's config: a leaf arg is removed if its value is None or the
338
+ # given default, a group of args (default `None`) if all its values are None.
339
+ UNHASHED_DEFAULT_ARGS = {
340
+ # `drop_noise_events` is hashed only when it drops events (see `get_hashed_construction_cfg`)
341
+ # `benign_training` only drops events of datasets with labelled attacks in train/val dates
342
+ "construction": {
343
+ "edge_type": "operation",
344
+ "operations": "default",
345
+ "drop_noise_events": False,
346
+ "benign_training": True,
347
+ },
348
+ "transformation": {"merge_edges": None, "merge_edges.aggregate_attributes": False},
349
+ # ProGrapher
350
+ "featurization": {
351
+ "graph2vec": {
352
+ "wl_iterations": 4, "negative": 15, "min_count": 1, "alpha": 0.025,
353
+ "infer_epochs": 100, "num_workers": 1,
354
+ },
355
+ },
356
+ "feat_inference": {"edge_attributes": "all"},
357
+ "batching": {
358
+ "intra_graph_batching.tgn_last_neighbor.negative_destinations": False,
359
+ "compact_node_ids": False,
360
+ },
361
+ "evaluation": {
362
+ "save_figures": True,
363
+ "evaluate_selected_epoch_only": False,
364
+ "host_two_stage_evaluation": {"alpha": 3, "beta": 350, "root_attack_nodes": "", "test_end": ""},
365
+ },
366
+ "training": {
367
+ # Defaults of default.yml (configs that don't include it leave them unset)
368
+ "encoder.gcn": {"activation": "relu", "num_layers": 2},
369
+ "encoder.node_id_embedding": {"dim": 32, "all_nodes": False},
370
+ "encoder.snapshot_gru": {"hidden_dim": 0, "dropout": 0.0},
371
+ "encoder.lares": {"flow": "target_to_source", "use_node_features": False},
372
+ "encoder.argus": {"num_layers": 2},
373
+ "encoder.egraphsage": {"activation": "relu", "num_layers": 2, "undirected": True},
374
+ "decoder.predict_edge_contrastive.loss": "bce",
375
+ "decoder.predict_edge_contrastive.ap_margin": 0.8,
376
+ "decoder.predict_edge_contrastive.neg_sampling": "shuffle_dst",
377
+ "decoder.predict_edge_contrastive.neg_ratio": 1.0,
378
+ "decoder.few_shot.decoder.predict_edge_contrastive.loss": "bce",
379
+ "decoder.few_shot.decoder.predict_edge_contrastive.ap_margin": 0.8,
380
+ "decoder.few_shot.decoder.predict_edge_contrastive.neg_sampling": "shuffle_dst",
381
+ "decoder.few_shot.decoder.predict_edge_contrastive.neg_ratio": 1.0,
382
+ "decoder.deep_graph_infomax": {"decoder": "none", "pca_components": 8},
383
+ "decoder.autoencode_edge_embeddings": {"decoder": "none", "use_edge_feats": True},
384
+ "decoder.few_shot.decoder.autoencode_edge_embeddings": {"decoder": "none", "use_edge_feats": True},
385
+ "decoder.few_shot.decoder.deep_graph_infomax": {"decoder": "none", "pca_components": 8},
386
+ # ShadeWatcher
387
+ "encoder.shadewatcher": {"hidden_dims": (32, 16), "kg_dim": 32, "kg_neg_ratio": 2, "kg_margin": 1.0},
388
+ "decoder.predict_edge_contrastive.inner_product.negate": False,
389
+ "decoder.few_shot.decoder.predict_edge_contrastive.inner_product.negate": False,
390
+ # ProGrapher
391
+ "encoder.textrcnn": {"sequence_length": 128, "num_layers": 5, "rnn_type": "lstm"},
392
+ "decoder.predict_snapshot_embedding": {"decoder": "none", "top_k": 0},
393
+ "decoder.few_shot.decoder.predict_snapshot_embedding": None,
394
+ },
395
+ }
396
+
397
+
398
+ def _all_none(value):
399
+ if isinstance(value, dict):
400
+ return all(_all_none(v) for v in value.values())
401
+ return value is None
402
+
403
+
404
+ def _is_default(value, default):
405
+ """Whether an arg (or a group of args) is unset or at its default value."""
406
+ if isinstance(value, dict):
407
+ if _all_none(value):
408
+ return True
409
+ if not isinstance(default, dict):
410
+ return False
411
+ return all(
412
+ _is_default(v, default[k]) if k in default else _all_none(v) for k, v in value.items()
413
+ )
414
+ return value is None or str(value).strip() == str(default)
415
+
416
+
417
+ def strip_unhashed_defaults(task, task_cfg):
418
+ """Copy of a task's config without the args of `UNHASHED_DEFAULT_ARGS` at their default."""
419
+ args = UNHASHED_DEFAULT_ARGS.get(task)
420
+ if not args:
421
+ return task_cfg
422
+ task_cfg = deepcopy(dict(task_cfg))
423
+ for path, default in args.items():
424
+ *parents, key = path.split(".")
425
+ node = task_cfg
426
+ for parent in parents:
427
+ node = node.get(parent) if isinstance(node, dict) else None
428
+ if not isinstance(node, dict) or key not in node:
429
+ continue
430
+ if _is_default(node[key], default):
431
+ del node[key]
432
+ return task_cfg
433
+
434
+
435
+ def get_hashed_construction_cfg(cfg):
436
+ """Construction args that define the hash of its folder.
437
+
438
+ Without cleaning, `construction.cleaning` is ignored so that graphs built before cleaning
439
+ existed are reused. Otherwise, only the args of the used cleaning methods are hashed, sorted
440
+ as their order has no effect.
441
+ """
442
+ hashed = {k: v for k, v in cfg.construction.items() if k != "cleaning"}
443
+ # Only the labels of the dataset's node types have an effect
444
+ node_types = set(get_schema(cfg).node_type_names)
445
+ hashed["node_label_features"] = {
446
+ k: v for k, v in cfg.construction.node_label_features.items() if k in node_types
447
+ }
448
+ # Only datasets with noise events (e.g. OPTC_NET) are affected by `drop_noise_events`
449
+ hashed["drop_noise_events"] = drops_noise_events(cfg.construction) and bool(
450
+ get_schema(cfg).noise_events_sql
451
+ )
452
+ # Only datasets with event labels are affected by `benign_training`
453
+ hashed["benign_training"] = benign_training(cfg.construction) or not get_schema(cfg).label_column
454
+ methods = sorted(set(get_cleaning_methods_from_cfg(cfg)))
455
+ if methods:
456
+ cleaning = cfg.construction.cleaning
457
+ hashed["cleaning"] = {"used_methods": ",".join(methods)}
458
+ for method in methods:
459
+ method_args = getattr(cleaning, method, None)
460
+ if isinstance(method_args, dict) and len(method_args) > 0:
461
+ hashed["cleaning"][method] = {f"{method}.{k}": v for k, v in method_args.items()}
462
+ return hashed
463
+
464
+
465
+ # Args logged when a task starts: its main choices, which differ between systems and runs (not
466
+ # the args that never change, nor those specific to a method). Rows of (name, path) pairs, where
467
+ # `{arg}` in a path stands for each of the methods used by `arg` (e.g. each objective).
468
+ TASK_SUMMARY_ARGS = {
469
+ "construction": [[("time_window_size", "time_window_size")]],
470
+ "transformation": [[("used_methods", "used_methods")]],
471
+ "featurization": [
472
+ [
473
+ ("used_method", "used_method"),
474
+ ("emb_dim", "emb_dim"),
475
+ ("epochs", "epochs"),
476
+ ("tokenization", "tokenization.used_method"),
477
+ ]
478
+ ],
479
+ "feat_inference": [],
480
+ "batching": [
481
+ [("node_features", "node_features"), ("edge_features", "edge_features")],
482
+ [
483
+ ("global_batching", "global_batching.used_method"),
484
+ ("intra_graph_batching", "intra_graph_batching.used_methods"),
485
+ ("inter_graph_batching", "inter_graph_batching.used_method"),
486
+ ],
487
+ ],
488
+ "training": [
489
+ [
490
+ ("num_epochs", "num_epochs"),
491
+ ("patience", "patience"),
492
+ ("lr", "lr"),
493
+ ("weight_decay", "weight_decay"),
494
+ ("node_hid_dim", "node_hid_dim"),
495
+ ("node_out_dim", "node_out_dim"),
496
+ ("grad_accumulation", "grad_accumulation"),
497
+ ],
498
+ [
499
+ ("encoder", "encoder.used_methods"),
500
+ ("objective", "decoder.used_methods"),
501
+ ("decoder", "decoder.{decoder.used_methods}.decoder"),
502
+ ],
503
+ ],
504
+ "evaluation": [
505
+ [("best_model_selection", "best_model_selection"), ("used_method", "used_method")],
506
+ [("threshold_method", "{used_method}.threshold_method")],
507
+ ],
508
+ "triage": [[("used_method", "used_method")]],
509
+ }
510
+
511
+
512
+ def summarize_task_args(cfg, task):
513
+ """Rows of (name, value) of the main args of `task` (see `TASK_SUMMARY_ARGS`), among those
514
+ that define its hash, so that the args of the methods that are not used are not shown."""
515
+ task_cfg = get_hashed_construction_cfg(cfg) if task == "construction" else getattr(cfg, task)
516
+ task_cfg = strip_unhashed_defaults(task, task_cfg)
517
+
518
+ def get(path):
519
+ node = task_cfg
520
+ for key in path.split("."):
521
+ node = node.get(key) if isinstance(node, dict) else None
522
+ return node
523
+
524
+ def values(path):
525
+ """Values of `path`, for each method of its `{arg}` (e.g. one per objective)."""
526
+ if "{" not in path:
527
+ return [get(path)]
528
+ start, end = path.index("{"), path.index("}")
529
+ methods = get(path[start + 1 : end])
530
+ if not isinstance(methods, str):
531
+ return []
532
+ return [
533
+ value
534
+ for method in methods.split(",")
535
+ for value in values(path[:start] + method.strip() + path[end + 1 :])
536
+ ]
537
+
538
+ rows = []
539
+ for row in TASK_SUMMARY_ARGS.get(task, []):
540
+ items = []
541
+ for name, path in row:
542
+ found = [v for v in values(path) if v is not None and not isinstance(v, dict)]
543
+ if found:
544
+ parts = [p.strip() for v in found for p in str(v).split(",")]
545
+ items.append((name, ", ".join(dict.fromkeys(parts))))
546
+ if items:
547
+ rows.append(items)
548
+ return rows
549
+
550
+
551
+ def set_task_paths(cfg, subtask_concat_value=None):
552
+ subtask_to_hash = {}
553
+ # Directories common to all tasks
554
+ for task in TASK_ARGS:
555
+ task_cfg = getattr(cfg, task)
556
+ if task == "construction":
557
+ task_cfg = get_hashed_construction_cfg(cfg)
558
+ task_cfg = strip_unhashed_defaults(task, task_cfg)
559
+ restart_values = flatten_arg_values(task_cfg)
560
+
561
+ _spider_pretrain_datasets = (
562
+ cfg.featurization.used_method == "pretrained"
563
+ and getattr(cfg.featurization.pretrained, "pretrain_datasets", None)
564
+ )
565
+
566
+ # Normalize pretrain_datasets order so the hash is the same
567
+ # regardless of how the user lists the datasets in the config.
568
+ if task == "featurization":
569
+ restart_values = [
570
+ f"pretrain_datasets={','.join(sorted(v.split('=', 1)[1].split(',')))}"
571
+ if isinstance(v, str) and v.startswith("pretrain_datasets=")
572
+ else v
573
+ for v in restart_values
574
+ ]
575
+
576
+ # For featurization tasks downstream of featurization (e.g. feat_inference),
577
+ # all input datasets share the same directory (the pretrain_datasets path),
578
+ # so the hash must encode which input dataset was used to avoid collisions.
579
+ if _spider_pretrain_datasets and task == "feat_inference":
580
+ restart_values = [f"input_dataset={cfg.dataset.name}"] + restart_values
581
+
582
+ if task == "construction": # to restart from beginning if train dates are changed
583
+ restart_values += cfg.dataset.train_dates
584
+ if (
585
+ cfg._restart_from_scratch
586
+ ): # to start from a brand new folder, we generate a random id to add to the hash
587
+ restart_values += [cfg._run_random_seed]
588
+ if subtask_concat_value is not None:
589
+ if task == subtask_concat_value["subtask"]:
590
+ restart_values += [subtask_concat_value["concat_value"]]
591
+
592
+ clean_hash_args = [
593
+ "".join([c for c in str(arg) if c not in set(" []\"'")])
594
+ for arg in restart_values
595
+ if not arg.startswith("_")
596
+ ]
597
+ final_hash_string = ",".join(clean_hash_args)
598
+ final_hash_string = hashlib.sha256(final_hash_string.encode("utf-8")).hexdigest()
599
+
600
+ subtask_to_hash[task] = final_hash_string
601
+
602
+ # Then, for each subtask, we want its unique hash to also depend from its previous dependencies' hashes.
603
+ # For example, if I run the same subtask A two times, with two different subtasks B and C, the results
604
+ # would be different and would be stored in the same folder A if we don't consider the hash of B and C.
605
+ for task in TASK_ARGS:
606
+ task_cfg = getattr(cfg, task)
607
+ deps = sorted(list(get_dependees(task, TASK_DEPENDENCIES, set())))
608
+
609
+ # When pretrain_datasets is set for SPIDER, the pretrained model is
610
+ # independent of the input dataset. The only truly dataset-specific entry in
611
+ # subtask_to_hash is "construction" (it includes cfg.dataset.train_dates).
612
+ # Exclude it from featurization so the pretrained model is shared across input
613
+ # datasets. Downstream tasks (feat_inference, batching, ...) embed and train on
614
+ # the graphs of the input dataset, so they keep it: otherwise, graphs built with
615
+ # other construction args (cleaning, time windows, ...) would reuse stale results.
616
+ if (
617
+ cfg.featurization.used_method == "pretrained"
618
+ and getattr(cfg.featurization.pretrained, "pretrain_datasets", None)
619
+ and task == "featurization"
620
+ ):
621
+ deps = [d for d in deps if d != "construction"]
622
+
623
+ deps_hash = "".join([subtask_to_hash[dep] for dep in deps])
624
+
625
+ final_hash_string = deps_hash + subtask_to_hash[task]
626
+ final_hash_string = hashlib.sha256(final_hash_string.encode("utf-8")).hexdigest()
627
+
628
+ if task in ["construction", "transformation", "featurization", "feat_inference"]:
629
+ # When pretrain_datasets is set for SPIDER, featurization and feat_inference
630
+ # are grouped under a shared directory named after the sorted pretrain_datasets
631
+ # (instead of cfg.dataset.name). featurization itself has no input-dataset
632
+ # component in its hash. feat_inference encodes the input dataset in its hash
633
+ # (added above), so different inputs remain distinct.
634
+ dataset_dir = cfg.dataset.name
635
+ if (
636
+ cfg.featurization.used_method == "pretrained"
637
+ and getattr(cfg.featurization.pretrained, "pretrain_datasets", None)
638
+ and (task == "featurization" or "featurization" in deps)
639
+ ):
640
+ datasets = sorted(
641
+ d.strip()
642
+ for d in cfg.featurization.pretrained.pretrain_datasets.split(",")
643
+ )
644
+ dataset_dir = "+".join(datasets)
645
+
646
+ task_cfg._task_path = os.path.join(
647
+ cfg._artifact_dir, task, dataset_dir, task, final_hash_string
648
+ )
649
+ else:
650
+ task_cfg._task_path = os.path.join(
651
+ cfg._artifact_dir, task, task, final_hash_string, cfg.dataset.name
652
+ )
653
+
654
+ # The directory to save logs related to the preprocessing task
655
+ task_cfg._logs_dir = os.path.join(task_cfg._task_path, "logs/")
656
+ os.makedirs(task_cfg._logs_dir, exist_ok=True)
657
+
658
+ # Preprocessing paths
659
+ cfg.construction._graphs_dir = os.path.join(cfg.construction._task_path, "nx/")
660
+ cfg.construction._tw_labels = os.path.join(cfg.construction._task_path, "tw_labels/")
661
+ cfg.construction._node_id_to_path = os.path.join(
662
+ cfg.construction._task_path, "node_id_to_path/"
663
+ )
664
+ cfg.construction._dicts_dir = os.path.join(cfg.construction._task_path, "indexid2msg/")
665
+ cfg.construction._mimicry_dir = os.path.join(cfg.construction._task_path, "mimicry/")
666
+ cfg.construction._magic_dir = os.path.join(cfg.construction._task_path, "magic/")
667
+ cfg.construction._magic_graphs_dir = os.path.join(cfg.construction._magic_dir, "dgl_graphs/")
668
+
669
+ cfg.transformation._graphs_dir = os.path.join(cfg.transformation._task_path, "nx/")
670
+
671
+ # Featurization paths
672
+ cfg.featurization._model_dir = os.path.join(cfg.featurization._task_path, "stored_models/")
673
+ cfg.featurization.temporal_rw._random_walk_dir = os.path.join(
674
+ cfg.featurization._task_path, "random_walks/"
675
+ )
676
+ cfg.featurization.temporal_rw._random_walk_corpus_dir = os.path.join(
677
+ cfg.featurization.temporal_rw._random_walk_dir, "random_walk_corpus/"
678
+ )
679
+ cfg.featurization.alacarte._random_walk_dir = os.path.join(
680
+ cfg.featurization._task_path, "random_walks/"
681
+ )
682
+ cfg.featurization.alacarte._random_walk_corpus_dir = os.path.join(
683
+ cfg.featurization.alacarte._random_walk_dir, "random_walk_corpus/"
684
+ )
685
+ cfg.featurization.alacarte._vec_graphs_dir = os.path.join(
686
+ cfg.featurization._task_path, "vectorized/"
687
+ )
688
+
689
+ cfg.feat_inference._edge_embeds_dir = os.path.join(
690
+ cfg.feat_inference._task_path, "edge_embeds/"
691
+ )
692
+ cfg.feat_inference._model_dir = os.path.join(cfg.feat_inference._task_path, "stored_models/")
693
+
694
+ # Detection paths
695
+ cfg.batching._preprocessed_graphs_dir = os.path.join(
696
+ cfg.batching._task_path, "preprocessed_graphs/"
697
+ )
698
+
699
+ cfg.training._trained_models_dir = os.path.join(cfg.training._task_path, "trained_models/")
700
+ cfg.training._edge_losses_dir = os.path.join(cfg.training._task_path, "edge_losses/")
701
+ cfg.training._magic_dir = os.path.join(cfg.training._task_path, "magic/")
702
+ cfg.evaluation._precision_recall_dir = os.path.join(
703
+ cfg.evaluation._task_path, "precision_recall_dir/"
704
+ )
705
+ cfg.evaluation._uncertainty_exp_dir = os.path.join(
706
+ cfg.evaluation._task_path, "uncertainty_exp/"
707
+ )
708
+ cfg.evaluation.queue_evaluation._precision_recall_dir = os.path.join(
709
+ cfg.evaluation._task_path, "precision_recall_dir/"
710
+ )
711
+ cfg.evaluation.queue_evaluation._queues_dir = os.path.join(
712
+ cfg.evaluation._task_path, "queues_dir/"
713
+ )
714
+ cfg.evaluation.queue_evaluation._predicted_queues_dir = os.path.join(
715
+ cfg.evaluation._task_path, "predicted_queues_dir/"
716
+ )
717
+ cfg.evaluation.queue_evaluation._kairos_dir = os.path.join(
718
+ cfg.evaluation._task_path, "kairos_dir/"
719
+ )
720
+ cfg.evaluation._results_dir = os.path.join(cfg.evaluation._task_path, "results/")
721
+
722
+ # Ground Truth paths
723
+ cfg._ground_truth_dir = os.path.join(
724
+ ROOT_GROUND_TRUTH_DIR, cfg.evaluation.ground_truth_version + "/"
725
+ )
726
+
727
+ # Triage paths
728
+ cfg.triage._tracing_graph_dir = os.path.join(cfg.triage._task_path, "tracing_graphs")
729
+
730
+
731
+ def validate_yml_file(yml_file: str, dictionary: dict):
732
+ with open(yml_file, "r") as file:
733
+ user_config = yaml.safe_load(file)
734
+
735
+ def validate_config(user_config, tasks, path=None):
736
+ if path is None:
737
+ path = []
738
+ if not user_config:
739
+ raise ValueError(f"Config at {' > '.join(path)} is empty but should not be.")
740
+
741
+ for key, sub_tasks in tasks.items():
742
+ if key in user_config:
743
+ sub_config = user_config[key]
744
+ if isinstance(sub_tasks, dict):
745
+ validate_config(sub_config, sub_tasks, path + [key])
746
+ else:
747
+ if sub_config is None:
748
+ raise ValueError(
749
+ f"Parameter '{' > '.join(path + [key])}' should not be None."
750
+ )
751
+ expected_type = sub_tasks.type
752
+
753
+ if not isinstance(sub_config, expected_type):
754
+ raise TypeError(
755
+ f"Parameter '{' > '.join(path + [key])}' should be of type {expected_type.__name__}, found {type(sub_config)}."
756
+ )
757
+
758
+ expected_vals = sub_tasks.vals
759
+ if expected_vals is not None:
760
+ user_literal_str = list(map(lambda x: x.strip(), sub_config.split(",")))
761
+ for e in user_literal_str:
762
+ if e not in expected_vals:
763
+ raise ValueError(
764
+ f"Invalid argument {key} with value {e}. Expected values: {expected_vals}"
765
+ )
766
+
767
+ validate_config(user_config, dictionary)
768
+
769
+
770
+ def check_args(args):
771
+ config_root = os.path.join(ROOT_PROJECT_PATH, "config")
772
+ available_models = set()
773
+ for root, _, files in os.walk(config_root):
774
+ for f in files:
775
+ if f.endswith(".yml"):
776
+ available_models.add(f[:-4])
777
+ if args.model not in available_models:
778
+ raise ValueError(
779
+ f"Unknown model {args.model}. Available models are {sorted(available_models)}"
780
+ )
781
+
782
+ available_datasets = DATASET_DEFAULT_CONFIG.keys()
783
+ if args.dataset not in available_datasets:
784
+ raise ValueError(
785
+ f"Unknown dataset {args.dataset}. Available datasets are {available_datasets}"
786
+ )
787
+
788
+
789
+ def get_yml_file(filename, folder=""):
790
+ # Explicit folder, or a relative path embedded in filename → use as-is.
791
+ if folder or "/" in filename:
792
+ return os.path.join(ROOT_PROJECT_PATH, "config", folder, f"{filename}.yml")
793
+
794
+ # Bare name → prefer config/<filename>.yml, otherwise search recursively
795
+ # so files organized into subfolders (e.g. config/pretrained/cybergfm/) are
796
+ # invokable by name alone.
797
+ config_root = os.path.join(ROOT_PROJECT_PATH, "config")
798
+ top_level = os.path.join(config_root, f"{filename}.yml")
799
+ if os.path.exists(top_level):
800
+ return top_level
801
+
802
+ target = f"{filename}.yml"
803
+ matches = []
804
+ for root, _, files in os.walk(config_root):
805
+ if target in files:
806
+ matches.append(os.path.join(root, target))
807
+ if len(matches) == 1:
808
+ return matches[0]
809
+ if len(matches) > 1:
810
+ rels = sorted(os.path.relpath(m, config_root) for m in matches)
811
+ raise ValueError(
812
+ f"Ambiguous yml name '{filename}': found in {rels}. "
813
+ f"Disambiguate by passing the path (e.g. 'subfolder/{filename}')."
814
+ )
815
+ return top_level # not found — caller will raise FileNotFoundError with this path
816
+
817
+
818
+ def merge_cfg_and_check_syntax(cfg, yml_file, syntax_check=TASK_ARGS):
819
+ user_config = CN(load_yml_file_recursive(yml_file, syntax_check=syntax_check))
820
+ cfg.merge_from_other_cfg(user_config)
821
+ return cfg
822
+
823
+
824
+ # {(yml_file, id(syntax_check)): (syntax_check, [(file, mtime) of yml_file and its includes], config)}
825
+ _YML_CACHE = {}
826
+
827
+
828
+ def load_yml_file_recursive(yml_file, syntax_check=TASK_ARGS):
829
+ """Loads and validates a yml config file, merged with the files it includes.
830
+
831
+ The config is loaded again before each task (to check which tasks should restart), so results
832
+ are cached until one of the files is modified. A copy is returned, which callers can modify.
833
+ """
834
+ key = (os.path.abspath(yml_file), id(syntax_check))
835
+ cached = _YML_CACHE.get(key)
836
+ if cached is not None:
837
+ check, files, config = cached
838
+ if check is syntax_check and all(os.path.getmtime(f) == mtime for f, mtime in files):
839
+ return deepcopy(config)
840
+
841
+ files = []
842
+ config = _load_yml_file_recursive(yml_file, syntax_check, files)
843
+ _YML_CACHE[key] = (syntax_check, files, config)
844
+ return deepcopy(config)
845
+
846
+
847
+ def _load_yml_file_recursive(yml_file, syntax_check, files):
848
+ files.append((os.path.abspath(yml_file), os.path.getmtime(yml_file)))
849
+ validate_yml_file(yml_file, syntax_check)
850
+ with open(yml_file, "r") as file:
851
+ user_config = yaml.safe_load(file)
852
+ if "_include_yml" in user_config:
853
+ includes = user_config["_include_yml"]
854
+ if isinstance(includes, str):
855
+ includes = [includes]
856
+ merged_base = {}
857
+ for inc in includes:
858
+ inc_config = _load_yml_file_recursive(get_yml_file(inc), syntax_check, files) or {}
859
+ merged_base = deep_merge_dicts(merged_base, inc_config)
860
+ user_config = deep_merge_dicts(merged_base, user_config)
861
+ return user_config
862
+
863
+
864
+ def deep_merge_dicts(target, source):
865
+ for k, v in source.items():
866
+ target[k] = (
867
+ deep_merge_dicts(target[k], v)
868
+ if isinstance(v, dict) and isinstance(target.get(k), dict)
869
+ else v
870
+ )
871
+ return target
872
+
873
+
874
+ def get_yml_cfg(args):
875
+ # Checks that CLI args are OK
876
+ check_args(args)
877
+
878
+ # Inits with default configurations
879
+ cfg = get_default_cfg(args)
880
+
881
+ # Checks that all configurations are valid and merge yml file to cfg
882
+ yml_file = get_yml_file(args.model)
883
+ merge_cfg_and_check_syntax(cfg, yml_file)
884
+
885
+ # Overrides with best hyperparameters
886
+ if args.tuned:
887
+ tuning_file = "orthrus" if args.model == "orthrus_fixed" else args.model
888
+ if args.model == "orthrus_fixed" and args.dataset == "CLEARSCOPE_E3": # speciifc case
889
+ tuning_file = args.model
890
+ tuned_yml_file = get_yml_file(
891
+ f"tuned_{tuning_file}", folder=f"tuned_baselines/{cfg.dataset.name.lower()}/"
892
+ )
893
+ merge_cfg_and_check_syntax(cfg, tuned_yml_file)
894
+
895
+ # Same for experiments
896
+ exp_yml_file = get_yml_file(os.path.join(UNCERTAINTY_EXP_YML_FOLDER, args.experiment))
897
+ merge_cfg_and_check_syntax(cfg, exp_yml_file, syntax_check=EXPERIMENTS_CONFIG)
898
+
899
+ # Overwrites args to the cfg
900
+ overwrite_cfg_with_args(cfg, args)
901
+
902
+ # Here we create some variables based on parameters for easier usage
903
+ set_shortcut_variables(cfg)
904
+
905
+ # In some cases, we want some parameters to be fixed and unchanged
906
+ set_immutable_cfg(cfg)
907
+
908
+ # Based on the defined restart args, computes a unique path on disk
909
+ # to store the files of each task
910
+ set_task_paths(cfg)
911
+
912
+ # Calculates which subtasks have to be re-executed
913
+ set_subtasks_to_restart(yml_file, cfg)
914
+
915
+ # Yield errors if some combinations of parameters are not possible
916
+ check_edge_cases(cfg)
917
+
918
+ # Fail fast if the selected ground truth has no file for this dataset
919
+ from pidsmaker.utils.labelling import ensure_ground_truth_available
920
+
921
+ ensure_ground_truth_available(cfg)
922
+
923
+ return cfg
924
+
925
+
926
+ def check_edge_cases(cfg):
927
+ """
928
+ We want to check all errors prior to running the framework here.
929
+ Yield EnvironmentError to be handled in tests.
930
+ """
931
+ decoders = cfg.training.decoder.used_methods
932
+ use_tgn_neigh_loader = "tgn_last_neighbor" in cfg.batching.intra_graph_batching.used_methods
933
+ use_tgn = "tgn" in cfg.training.encoder.used_methods
934
+ use_rcaid_pseudo_graph = "rcaid_pseudo_graph" in cfg.transformation.used_methods
935
+
936
+ if use_tgn_neigh_loader:
937
+ if use_rcaid_pseudo_graph:
938
+ raise ValueError(
939
+ "Cannot use TGN with RCaid pseudo graph transformation. Edge timestamps are ignored with this transformation."
940
+ )
941
+ if not use_tgn:
942
+ raise ValueError("Couldn't use `tgn_last_neighbor` without `tgn` as encoder.")
943
+
944
+ edge_features = [f.strip() for f in (cfg.batching.edge_features or "").split(",")]
945
+ edge_type = (cfg.construction.edge_type or "operation").strip()
946
+ base_schema = get_schema_by_name(cfg.dataset.schema)
947
+ if edge_type not in base_schema.edge_type_choices:
948
+ raise ValueError(
949
+ f"Invalid `construction.edge_type={edge_type}` for {cfg.dataset.name}: expected one of "
950
+ f"{base_schema.edge_type_choices} (schema `{base_schema.name}`)."
951
+ )
952
+ schema = get_schema(cfg)
953
+ encoders = cfg.training.encoder.used_methods
954
+ if use_tgn and ("node_id_embedding" in encoders or "snapshot_gru" in encoders):
955
+ raise ValueError("Encoders `node_id_embedding` and `snapshot_gru` cannot be used with `tgn`.")
956
+ if "node_id_embedding" in encoders and cfg.training.encoder.node_id_embedding.all_nodes:
957
+ objectives = [o.strip() for o in decoders.split(",")]
958
+ node_level = [o for o in objectives if o in OBJECTIVES_NODE_LEVEL]
959
+ if node_level or cfg.training.fuse_duplicate_edges_training:
960
+ raise ValueError(
961
+ "`node_id_embedding.all_nodes` embeds all the nodes of the dataset in every graph: it "
962
+ f"requires edge-level objectives (got {node_level}) and no `fuse_duplicate_edges_training`."
963
+ )
964
+ if "predict_node_type" in decoders:
965
+ from pidsmaker.utils.data_utils import get_selected_node_features
966
+
967
+ if "node_type" in get_selected_node_features(cfg):
968
+ raise ValueError(
969
+ "Objective `predict_node_type` predicts the node type, so the node type cannot be a "
970
+ "node feature (the label would be given as input). Remove `node_type` from "
971
+ "`batching.node_features` (with `featurization.used_method: only_type`, select "
972
+ "another feature such as `edges_distribution`)."
973
+ )
974
+ if "predict_node_type" in decoders and schema.num_node_types < 2:
975
+ raise ValueError(
976
+ f"Objective `predict_node_type` needs at least two node types, but {cfg.dataset.name} "
977
+ f"has a single node type ({schema.node_type_names[0]}). Use an edge-level objective "
978
+ "(e.g. `predict_edge_type` with `construction.edge_type`)."
979
+ )
980
+ if "predict_process_tag" in decoders and "subject" not in schema.node_type_names:
981
+ raise ValueError(
982
+ f"Objective `predict_process_tag` predicts the executable of processes (`subject` nodes), "
983
+ f"but {cfg.dataset.name} has none (node types: {', '.join(schema.node_type_names)})."
984
+ )
985
+ if "edge_type_triplet" in edge_features and not schema.supports_edge_type_triplets:
986
+ raise ValueError(
987
+ f"Edge feature `edge_type_triplet` is not implemented for {cfg.dataset.name} "
988
+ f"(schema `{schema.name}`)."
989
+ )
990
+ if cfg._is_hetero and not schema.supports_hetero:
991
+ raise ValueError(
992
+ f"Hetero encoders are not implemented for {cfg.dataset.name} (schema `{schema.name}`)."
993
+ )
994
+
995
+ if cfg._require_non_reversed_edges and "undirected" in cfg.transformation.used_methods:
996
+ used = [e for e in REQUIRE_NON_REVERSED_EDGES_ENCODERS if e in cfg.training.encoder.used_methods]
997
+ raise ValueError(
998
+ f"Encoder(s) {used} do not support the `undirected` transformation: reversed edges "
999
+ "create (source type, edge type, destination type) triplets unknown to the encoder."
1000
+ )
1001
+
1002
+ if cfg._is_hetero and "edge_type_triplet" in edge_features:
1003
+ raise ValueError("Hetero encoders do not support the `edge_type_triplet` edge feature.")
1004
+
1005
+ global_batching = cfg.batching.global_batching
1006
+ if (global_batching.used_method or "none").strip() == "minutes":
1007
+ step = global_batching.global_batching_batch_size or global_batching.global_batching_batch_size_inference
1008
+ if step and step > cfg.construction.time_window_size:
1009
+ raise ValueError(
1010
+ f"With `global_batching.used_method=minutes`, graphs of `construction.time_window_size` "
1011
+ f"({cfg.construction.time_window_size}) minutes are built every `global_batching_batch_size` "
1012
+ f"({step}) minutes: a step larger than the window drops the events between windows."
1013
+ )
1014
+
1015
+ if "time_encoding" in edge_features and not use_tgn:
1016
+ raise ValueError("Edge feature `time_encoding` is only available if `tgn` is used as encoder.")
1017
+
1018
+ if use_tgn:
1019
+ if not use_tgn_neigh_loader:
1020
+ raise ValueError("Couldn't use `tgn` as encoder without `tgn_last_neighbor` as loader.")
1021
+ if cfg.batching.inter_graph_batching.used_method != "none":
1022
+ raise ValueError("TGN-based encoders do not support inter graph batching yet.")
1023
+
1024
+ transformations = [t.strip() for t in cfg.transformation.used_methods.split(",")]
1025
+ if "undirected" in transformations and "dag" in transformations[transformations.index("undirected"):]:
1026
+ raise ValueError(
1027
+ "Cannot apply the `dag` transformation after `undirected`: all edges of undirected graphs "
1028
+ "are in cycles and would be removed."
1029
+ )
1030
+
1031
+ if cfg.training_loop.run_evaluation == "best_epoch" and not cfg.training.decoder.use_few_shot:
1032
+ raise ValueError(
1033
+ "`training_loop.run_evaluation=best_epoch` requires `training.decoder.use_few_shot=True`, "
1034
+ "as the best epoch is selected with the few-shot validation score. Use `each_epoch`."
1035
+ )
1036
+
1037
+ if use_rcaid_pseudo_graph:
1038
+ if cfg.featurization.used_method.strip() == "flash":
1039
+ raise ValueError(
1040
+ "Cannot use the `flash` featurization with the `rcaid_pseudo_graph` transformation, "
1041
+ "as edge labels are removed in the pseudo graph."
1042
+ )
1043
+ if "predict_edge_type" in decoders:
1044
+ raise ValueError(
1045
+ "Cannot predict edge type as it is removed in the pseudo graph transformation"
1046
+ )
1047
+
1048
+ check_tokenization(cfg)
1049
+ check_cleaning(cfg)
1050
+
1051
+ if cfg.featurization.used_method == "fasttext":
1052
+ if cfg.featurization.fasttext.use_pretrained_fb_model:
1053
+ emb_dim = cfg.featurization.emb_dim
1054
+ if emb_dim != 300:
1055
+ raise ValueError(
1056
+ f"Invalid `emb_dim={emb_dim}`, should be set to 300 if `use_pretrained_fb_model=True`."
1057
+ )
1058
+
1059
+ if "reconstruct_masked_features" in decoders or "predict_masked_struct" in decoders:
1060
+ if cfg.evaluation.node_evaluation.threshold_method != "magic":
1061
+ raise ValueError("These decoders are only working with magic thresholding yet.")
1062
+
1063
+ if cfg.training.decoder.use_few_shot:
1064
+ if cfg.transformation.used_methods not in SYNTHETIC_ATTACKS.keys():
1065
+ raise ValueError(
1066
+ "Few-shot mode requires an attack generation method within `transformation.used_methods`"
1067
+ )
1068
+
1069
+ multi_dataset = cfg.construction.multi_dataset
1070
+ use_multi_dataset = multi_dataset and ("none" not in multi_dataset)
1071
+ if cfg.featurization.multi_dataset_training and use_multi_dataset:
1072
+ method = cfg.featurization.used_method.strip()
1073
+ if method not in ["word2vec", "fasttext", "hierarchical_hashing", "only_type", "pretrained"]:
1074
+ raise NotImplementedError(f"Multi-dataset mode not implemented for method {method}")
1075
+ if cfg.featurization.multi_dataset_training or cfg.batching.multi_dataset_training:
1076
+ if not use_multi_dataset:
1077
+ raise ValueError(
1078
+ "Using multi-dataset mode requires setting `preprocessing.construction.multi_dataset`"
1079
+ )
1080
+
1081
+ if cfg.evaluation.used_method == "edge_evaluation":
1082
+ if cfg._is_node_level and not cfg._is_hybrid_loss:
1083
+ raise ValueError("Edge evaluation not implemented for node-level detection.")
1084
+
1085
+ check_featurization(cfg)
1086
+ check_batching(cfg)
1087
+ check_encoders(cfg)
1088
+ check_objectives(cfg)
1089
+ check_evaluation(cfg)
1090
+ check_triage(cfg)
1091
+
1092
+
1093
+ # Featurization methods whose args are checked, with the args that are not read
1094
+ FEATURIZATION_UNUSED_ARGS = {
1095
+ "word2vec": ["epochs", "alpha"],
1096
+ "doc2vec": ["epochs"],
1097
+ "fasttext": [],
1098
+ "alacarte": ["epochs"],
1099
+ "temporal_rw": ["epochs"],
1100
+ "flash": [],
1101
+ }
1102
+
1103
+
1104
+ def check_featurization(cfg):
1105
+ """Checks that the args of the used featurization method are set."""
1106
+ method = cfg.featurization.used_method.strip()
1107
+ if method not in FEATURIZATION_UNUSED_ARGS:
1108
+ return
1109
+ method_cfg = getattr(cfg.featurization, method)
1110
+ missing = [
1111
+ arg
1112
+ for arg, value in method_cfg.items()
1113
+ if not arg.startswith("_")
1114
+ and value is None
1115
+ and arg not in FEATURIZATION_UNUSED_ARGS[method]
1116
+ ]
1117
+ if missing:
1118
+ raise ValueError(
1119
+ f"Missing arguments of the `{method}` featurization: "
1120
+ + ", ".join(f"featurization.{method}.{arg}" for arg in missing)
1121
+ + ". Set them in the config (default values are in default.yml) or in the CLI."
1122
+ )
1123
+
1124
+
1125
+ def check_batching(cfg):
1126
+ """Checks that the args of the used batching methods are set."""
1127
+ batching = cfg.batching
1128
+ required = []
1129
+ intra = [m.strip() for m in (batching.intra_graph_batching.used_methods or "none").split(",")]
1130
+ if "edges" in intra:
1131
+ required.append("intra_graph_batching.edges.intra_graph_batch_size")
1132
+ if "tgn_last_neighbor" in intra:
1133
+ required += [
1134
+ "intra_graph_batching.tgn_last_neighbor.tgn_neighbor_size",
1135
+ "intra_graph_batching.tgn_last_neighbor.tgn_neighbor_n_hop",
1136
+ ]
1137
+ if (batching.inter_graph_batching.used_method or "none").strip() != "none":
1138
+ required.append("inter_graph_batching.inter_graph_batch_size")
1139
+
1140
+ missing = []
1141
+ for arg in required:
1142
+ ptr = batching
1143
+ for attr in arg.split("."):
1144
+ ptr = getattr(ptr, attr, None)
1145
+ if ptr is None:
1146
+ missing.append(arg)
1147
+ if missing:
1148
+ raise ValueError(
1149
+ "Missing arguments of the batching: "
1150
+ + ", ".join(f"batching.{arg}" for arg in missing)
1151
+ + ". Set them in the config (default values are in default.yml) or in the CLI."
1152
+ )
1153
+
1154
+
1155
+ # Encoder args that are not read by the encoders
1156
+ UNUSED_ENCODER_ARGS = {
1157
+ "tgn": ["mode"],
1158
+ "gat": ["flow"],
1159
+ "magic_gat": ["alpha_l"],
1160
+ "hetero_graph_transformer": ["activation"],
1161
+ }
1162
+
1163
+
1164
+ def check_encoders(cfg):
1165
+ """Checks that the args of the encoders in `training.encoder.used_methods` are set.
1166
+ Boolean args are optional (unset means False)."""
1167
+ encoders = cfg.training.encoder.used_methods
1168
+ if encoders is None:
1169
+ raise ValueError("Missing `training.encoder.used_methods`.")
1170
+
1171
+ methods = [e.strip() for e in encoders.replace("-", ",").split(",")]
1172
+ base_encoders = [m for m in methods if m not in ENCODER_WRAPPERS]
1173
+ if len(base_encoders) != 1:
1174
+ raise ValueError(
1175
+ f"`training.encoder.used_methods={encoders}` should contain exactly one encoder "
1176
+ f"(found {base_encoders}), optionally combined with {ENCODER_WRAPPERS}. "
1177
+ "Use `none` for a single linear layer."
1178
+ )
1179
+
1180
+ tgn_cfg = cfg.training.encoder.tgn
1181
+ if "tgn" in methods and tgn_cfg.use_memory and tgn_cfg.use_node_feats_in_gnn:
1182
+ if not cfg.batching.intra_graph_batching.tgn_last_neighbor.fix_buggy_orthrus_TGN:
1183
+ raise ValueError(
1184
+ "`training.encoder.tgn.use_memory` with `use_node_feats_in_gnn` requires "
1185
+ "`batching.intra_graph_batching.tgn_last_neighbor.fix_buggy_orthrus_TGN=True`: "
1186
+ "otherwise, node features are not aligned with the memory of the TGN nodes."
1187
+ )
1188
+ if "tgn" in methods and tgn_cfg.use_residual_norm and tgn_cfg.use_memory and not tgn_cfg.use_node_feats_in_gnn:
1189
+ raise ValueError(
1190
+ "`training.encoder.tgn.use_residual_norm` adds the projected node features to the output "
1191
+ "of the GNN and requires `use_node_feats_in_gnn=True` when `use_memory=True`."
1192
+ )
1193
+
1194
+ for encoder in methods:
1195
+ if encoder not in ENCODERS_CFG:
1196
+ continue # e.g. inner encoders not exposed in the config, checked in the factory
1197
+ unused = UNUSED_ENCODER_ARGS.get(encoder, [])
1198
+ missing = [
1199
+ arg
1200
+ for arg, arg_def in ENCODERS_CFG[encoder].items()
1201
+ if arg_def.type is not bool
1202
+ and arg not in unused
1203
+ and getattr(getattr(cfg.training.encoder, encoder), arg, None) is None
1204
+ ]
1205
+ if missing:
1206
+ raise ValueError(
1207
+ f"Missing arguments of the `{encoder}` encoder: "
1208
+ + ", ".join(f"training.encoder.{encoder}.{arg}" for arg in missing)
1209
+ + ". Set them in the config (default values are in default.yml) or in the CLI."
1210
+ )
1211
+
1212
+
1213
+ def check_triage(cfg):
1214
+ """Checks that the args of the used `triage.used_method` are set."""
1215
+ method = cfg.triage.used_method
1216
+ if method is None:
1217
+ return
1218
+ method = method.strip()
1219
+ if method == "depimpact":
1220
+ evaluation = cfg.evaluation.used_method.strip()
1221
+ if evaluation not in ["node_evaluation", "node_tw_evaluation"]:
1222
+ raise ValueError(
1223
+ "Triage `depimpact` requires `evaluation.used_method` to be `node_evaluation` "
1224
+ f"or `node_tw_evaluation`, found `{evaluation}`."
1225
+ )
1226
+ method_cfg, required = cfg.triage.depimpact, ["used_method", "score_method", "workers"]
1227
+ elif method == "ocrapt_subgraph":
1228
+ if cfg.evaluation.used_method.strip() != "node_evaluation":
1229
+ raise ValueError(
1230
+ "Triage `ocrapt_subgraph` requires `evaluation.used_method=node_evaluation`."
1231
+ )
1232
+ method_cfg = cfg.triage.ocrapt
1233
+ required = ["num_hops", "top_k", "min_nodes", "max_edges", "abnormality_level"]
1234
+ else:
1235
+ raise ValueError(f"Invalid `triage.used_method={method}`.")
1236
+
1237
+ missing = [arg for arg in required if getattr(method_cfg, arg, None) is None]
1238
+ if missing:
1239
+ prefix = "depimpact" if method == "depimpact" else "ocrapt"
1240
+ raise ValueError(
1241
+ f"Missing arguments of the `{method}` triage: "
1242
+ + ", ".join(f"triage.{prefix}.{arg}" for arg in missing)
1243
+ + ". Set them in the config or in the CLI."
1244
+ )
1245
+
1246
+
1247
+ # Args of each decoder, read when the decoder is used by an objective
1248
+ DECODER_REQUIRED_ARGS = {
1249
+ "edge_mlp": ["architecture_str", "src_dst_projection_coef"],
1250
+ "node_mlp": ["architecture_str"],
1251
+ "magic_gat": ["num_layers", "num_heads", "negative_slope"],
1252
+ }
1253
+ # Args of each objective, read when the objective is used
1254
+ OBJECTIVE_REQUIRED_ARGS = {
1255
+ "reconstruct_node_features": ["loss"],
1256
+ "reconstruct_node_embeddings": ["loss"],
1257
+ "reconstruct_edge_embeddings": ["loss"],
1258
+ "reconstruct_masked_features": ["loss", "mask_rate"],
1259
+ "predict_masked_struct": ["loss"],
1260
+ "one_class": ["beta", "eps"],
1261
+ }
1262
+
1263
+
1264
+ def check_objectives(cfg):
1265
+ """Checks that the objectives in `training.decoder.used_methods` and their decoders are set."""
1266
+ decoder_cfg = cfg.training.decoder
1267
+ if decoder_cfg.used_methods is None:
1268
+ raise ValueError("Missing `training.decoder.used_methods`.")
1269
+
1270
+ for objective in [o.strip() for o in decoder_cfg.used_methods.split(",")]:
1271
+ objective_cfg = getattr(decoder_cfg, objective, None)
1272
+ if objective_cfg is None or not isinstance(objective_cfg, dict):
1273
+ raise ValueError(f"Invalid objective `{objective}` in `training.decoder.used_methods`.")
1274
+
1275
+ decoder = objective_cfg.get("decoder")
1276
+ if decoder is None:
1277
+ raise ValueError(
1278
+ f"Missing `training.decoder.{objective}.decoder`. Set it in the config "
1279
+ "(default values are in default.yml) or in the CLI."
1280
+ )
1281
+ decoder = decoder.strip()
1282
+ if objective == "reconstruct_masked_features" and decoder != "magic_gat":
1283
+ raise ValueError(
1284
+ "Objective `reconstruct_masked_features` only supports the `magic_gat` decoder."
1285
+ )
1286
+ if decoder == "magic_gat" and objective != "reconstruct_masked_features":
1287
+ raise ValueError(
1288
+ "Decoder `magic_gat` is a graph decoder only supported by objective "
1289
+ f"`reconstruct_masked_features`, found objective `{objective}`."
1290
+ )
1291
+ if decoder == "inner_product" and objective != "predict_edge_contrastive":
1292
+ raise ValueError(
1293
+ "Decoder `inner_product` is only supported by objective `predict_edge_contrastive`."
1294
+ )
1295
+
1296
+ required = [f"{decoder}.{arg}" for arg in DECODER_REQUIRED_ARGS.get(decoder, [])]
1297
+ required += OBJECTIVE_REQUIRED_ARGS.get(objective, [])
1298
+ missing = []
1299
+ for arg in required:
1300
+ ptr = objective_cfg
1301
+ for attr in arg.split("."):
1302
+ ptr = ptr.get(attr) if isinstance(ptr, dict) else None
1303
+ if ptr is None:
1304
+ missing.append(arg)
1305
+ if missing:
1306
+ raise ValueError(
1307
+ f"Missing arguments of the `{objective}` objective: "
1308
+ + ", ".join(f"training.decoder.{objective}.{arg}" for arg in missing)
1309
+ + ". Set them in the config (default values are in default.yml) or in the CLI."
1310
+ )
1311
+
1312
+
1313
+ # Args read by each evaluation method, that should be set in the config
1314
+ EVALUATION_REQUIRED_ARGS = {
1315
+ "node_evaluation": ["threshold_method"],
1316
+ "tw_evaluation": ["threshold_method"],
1317
+ "node_tw_evaluation": ["threshold_method"],
1318
+ "queue_evaluation": ["used_method", "queue_threshold"],
1319
+ "edge_evaluation": ["threshold_method", "malicious_edge_selection"],
1320
+ "host_two_stage_evaluation": ["alpha", "beta"],
1321
+ }
1322
+
1323
+
1324
+ def check_evaluation(cfg):
1325
+ """Checks that the args of the used `evaluation.used_method` are set."""
1326
+ method = cfg.evaluation.used_method
1327
+ if method is None:
1328
+ raise ValueError("Missing `evaluation.used_method`.")
1329
+ method = method.strip()
1330
+ if method not in EVALUATION_REQUIRED_ARGS:
1331
+ raise ValueError(
1332
+ f"Invalid `evaluation.used_method={method}`. "
1333
+ f"Expected values: {list(EVALUATION_REQUIRED_ARGS.keys())}"
1334
+ )
1335
+
1336
+ method_cfg = getattr(cfg.evaluation, method)
1337
+ required = list(EVALUATION_REQUIRED_ARGS[method])
1338
+ if getattr(method_cfg, "use_kmeans", None):
1339
+ required.append("kmeans_top_K")
1340
+
1341
+ missing = [arg for arg in required if getattr(method_cfg, arg, None) is None]
1342
+ if missing:
1343
+ raise ValueError(
1344
+ f"Missing arguments of the `{method}` evaluation: "
1345
+ + ", ".join(f"evaluation.{method}.{arg}" for arg in missing)
1346
+ + ". Set them in the config (default values are in default.yml) or in the CLI."
1347
+ )
1348
+
1349
+ # Some threshold methods rely on scores only computed by node-level objectives
1350
+ is_node_level = cfg._is_node_level and not cfg._is_hybrid_loss
1351
+ threshold_method = (getattr(method_cfg, "threshold_method", None) or "").strip()
1352
+ if threshold_method == "magic" and not (method == "node_evaluation" and is_node_level):
1353
+ raise ValueError(
1354
+ "Threshold method `magic` is only supported by `node_evaluation` with node-level objectives."
1355
+ )
1356
+ # With node-level objectives, the inference computes these scores based on `node_evaluation`
1357
+ node_threshold_method = (cfg.evaluation.node_evaluation.threshold_method or "").strip()
1358
+ if is_node_level and node_threshold_method in ["threatrace", "flash"]:
1359
+ if "predict_node_type" not in cfg.training.decoder.used_methods:
1360
+ raise ValueError(
1361
+ f"Threshold method `{node_threshold_method}` requires the `predict_node_type` objective."
1362
+ )
1363
+ if is_node_level and node_threshold_method == "threatrace":
1364
+ ratio = cfg.training.threatrace.ratio_threshold
1365
+ if ratio is None or ratio < 1.0:
1366
+ raise ValueError(
1367
+ "Threshold method `threatrace` requires `training.threatrace.ratio_threshold` >= 1 "
1368
+ f"(got {ratio})."
1369
+ )
1370
+
1371
+ if method == "queue_evaluation" and cfg._is_node_level and not cfg._is_hybrid_loss:
1372
+ raise ValueError(
1373
+ "Queue evaluation requires edge-level losses. It cannot be used with node-level objectives."
1374
+ )
1375
+
1376
+
1377
+ def check_cleaning(cfg):
1378
+ """Checks that the args of the used `construction.cleaning` methods are set."""
1379
+ methods = get_cleaning_methods_from_cfg(cfg)
1380
+ if not methods:
1381
+ return
1382
+ invalid = [m for m in methods if m not in CLEANING_METHODS]
1383
+ if invalid:
1384
+ raise ValueError(
1385
+ f"Invalid `construction.cleaning.used_methods`: {invalid}. "
1386
+ f"Use `none` or a comma-separated list among {CLEANING_METHODS}."
1387
+ )
1388
+ if cfg.construction.used_method.strip() not in ("default", "magic"):
1389
+ raise ValueError("`construction.cleaning` is only supported by the default construction.")
1390
+ for method in methods:
1391
+ method_args = getattr(cfg.construction.cleaning, method, None) or {}
1392
+ missing = [k for k, v in method_args.items() if v is None]
1393
+ if missing:
1394
+ raise ValueError(
1395
+ f"Missing arguments of the `{method}` cleaning: "
1396
+ + ", ".join(f"construction.cleaning.{method}.{k}" for k in missing)
1397
+ + ". Set them in the config (default values are in default.yml) or in the CLI."
1398
+ )
1399
+ if "remove_noisy_netflows" in methods:
1400
+ categories = [
1401
+ c.strip()
1402
+ for c in str(cfg.construction.cleaning.remove_noisy_netflows.ip_categories).split(",")
1403
+ if c.strip()
1404
+ ]
1405
+ if not categories:
1406
+ raise ValueError(
1407
+ "`construction.cleaning.remove_noisy_netflows.ip_categories` is empty."
1408
+ )
1409
+ if "dedup_window_edges" in methods and cfg.construction.fuse_edge is False:
1410
+ print(
1411
+ "Note: `dedup_window_edges` keeps one event per (source, destination, type) in each "
1412
+ "time window, which removes most of the events kept by `fuse_edge=False`."
1413
+ )
1414
+
1415
+
1416
+ def check_tokenization(cfg):
1417
+ """Checks that `featurization.tokenization` can be used by the featurization method."""
1418
+ method = cfg.featurization.used_method.strip()
1419
+ tokenization = cfg.featurization.tokenization.used_method
1420
+ if tokenization is None:
1421
+ raise ValueError(
1422
+ "Missing `featurization.tokenization.used_method`. Set it to `none` if the "
1423
+ "featurization method does not tokenize node labels."
1424
+ )
1425
+ tokenization = tokenization.strip()
1426
+
1427
+ def check_missing_args():
1428
+ # e.g. a tokenization set from the CLI in a config that does not include default.yml
1429
+ tokenization_args = getattr(cfg.featurization.tokenization, tokenization)
1430
+ missing = [k for k, v in tokenization_args.items() if v is None]
1431
+ if missing:
1432
+ raise ValueError(
1433
+ f"Missing arguments of the `{tokenization}` tokenization: "
1434
+ + ", ".join(f"featurization.tokenization.{tokenization}.{k}" for k in missing)
1435
+ + ". Set them in the config (default values are in default.yml) or in the CLI."
1436
+ )
1437
+ substitutions = tokenization_args.get("substitutions")
1438
+ if substitutions is not None:
1439
+ names = [n.strip() for n in str(substitutions).split(",") if n.strip()]
1440
+ invalid = [n for n in names if n not in SUBSTITUTION_METHODS + ["none"]]
1441
+ if invalid or not names or ("none" in names and len(names) > 1):
1442
+ raise ValueError(
1443
+ f"Invalid `featurization.tokenization.{tokenization}.substitutions={substitutions}`: "
1444
+ f"use `none` or a comma-separated list among {SUBSTITUTION_METHODS}."
1445
+ )
1446
+
1447
+ if method == "pretrained":
1448
+ model_type = cfg.featurization.pretrained.model_type
1449
+ expected = PRETRAINED_TOKENIZATIONS.get(model_type, PRETRAINED_DEFAULT_TOKENIZATION)
1450
+ if tokenization != expected:
1451
+ raise ValueError(
1452
+ f"Pretrained model `{model_type}` uses the `{expected}` tokenization, "
1453
+ f"found `featurization.tokenization.used_method={tokenization}`."
1454
+ )
1455
+ check_missing_args()
1456
+ return
1457
+
1458
+ allowed = FEATURIZATION_TOKENIZATIONS.get(method)
1459
+ if allowed is None or tokenization in allowed:
1460
+ check_missing_args()
1461
+ return
1462
+ if allowed == ["none"]:
1463
+ # The method does not read labels as text: the tokenization has no effect.
1464
+ print(
1465
+ f"Note: featurization method `{method}` does not tokenize node labels, "
1466
+ f"`featurization.tokenization.used_method={tokenization}` is ignored."
1467
+ )
1468
+ return
1469
+ raise ValueError(
1470
+ f"Featurization method `{method}` requires a tokenization among {allowed}, "
1471
+ f"found `featurization.tokenization.used_method={tokenization}`."
1472
+ )
1473
+
1474
+
1475
+ def set_subtasks_to_restart(yml_file: str, cfg):
1476
+ """
1477
+ Given a cfg, returns a boolean for each subtask, being `True` if
1478
+ the subtask requires to be restarted and `False` if the current arguments
1479
+ do not require a restart.
1480
+ In practice, we restart a subtask if there is no TASK_FINISHED_FILE in its `_task_path`.
1481
+ """
1482
+ user_config = load_yml_file_recursive(yml_file)
1483
+ tasks_in_yml_file = set([task for task in user_config if not task.startswith("_")])
1484
+
1485
+ # A task absent from the yml file can still be configured from the CLI (e.g. `--triage.used_method`)
1486
+ tasks_set_from_cli = set(getattr(cfg, "_tasks_set_from_cli", None) or [])
1487
+
1488
+ should_restart = OrderedDict()
1489
+ for task in TASK_ARGS:
1490
+ if task in tasks_in_yml_file or task in tasks_set_from_cli:
1491
+ task_cfg = getattr(cfg, task)
1492
+ existing_files = [files for _, _, files in os.walk(task_cfg._task_path)]
1493
+ has_finished = any(
1494
+ [files for files in existing_files for f in files if f.endswith(TASK_FINISHED_FILE)]
1495
+ )
1496
+ should_restart[task] = not has_finished
1497
+ else:
1498
+ should_restart[task] = False
1499
+
1500
+ should_restart_with_deps = get_subtasks_to_restart_with_dependencies(
1501
+ should_restart, TASK_DEPENDENCIES, cfg._force_restart
1502
+ )
1503
+
1504
+ # Dicts are not accepted in the cfg
1505
+ should_restart = [(subtask, restart) for subtask, restart in should_restart.items()]
1506
+ should_restart_with_deps = [
1507
+ (subtask, restart) for subtask, restart in should_restart_with_deps.items()
1508
+ ]
1509
+
1510
+ cfg._subtasks_should_restart = should_restart
1511
+ cfg._subtasks_should_restart_with_deps = should_restart_with_deps
1512
+
1513
+
1514
+ def update_task_paths_to_restart(cfg, subtask_concat_value=None):
1515
+ """Simply recomputes if tasks should be restarted."""
1516
+ yml_file = get_yml_file(cfg._model)
1517
+ set_dataset_cfg(cfg, cfg.dataset.name)
1518
+ set_shortcut_variables(cfg)
1519
+ set_immutable_cfg(cfg)
1520
+ set_task_paths(cfg, subtask_concat_value=subtask_concat_value)
1521
+ set_subtasks_to_restart(yml_file, cfg)
1522
+ should_restart = {
1523
+ subtask: restart for subtask, restart in cfg._subtasks_should_restart_with_deps
1524
+ }
1525
+ check_edge_cases(cfg)
1526
+ return should_restart
1527
+
1528
+
1529
+ def update_cfg_for_multi_dataset(cfg, dataset):
1530
+ cfg = deepcopy(cfg)
1531
+ cfg.dataset.name = dataset
1532
+ # cfg.construction.multi_dataset = "none"
1533
+ should_restart = update_task_paths_to_restart(cfg)
1534
+ return cfg, should_restart
1535
+
1536
+
1537
+ def get_dependencies(sub: str, dependencies: dict, result_set: set):
1538
+ """
1539
+ Returns the set of the subtasks happening after `sub`.
1540
+ """
1541
+
1542
+ def helper(sub):
1543
+ for subtask, deps in dependencies.items():
1544
+ if sub in deps:
1545
+ result_set.add(subtask)
1546
+ helper(subtask)
1547
+
1548
+ helper(sub)
1549
+ return result_set
1550
+
1551
+
1552
+ def get_dependees(sub: str, dependencies: dict, result_set: set):
1553
+ """
1554
+ Returns the set of the subtasks happening before `sub`.
1555
+ """
1556
+ dependencies = OrderedDict(sorted(dependencies.items(), reverse=True))
1557
+
1558
+ def helper(sub):
1559
+ for subtask, deps in dependencies.items():
1560
+ if sub == subtask:
1561
+ if len(deps) > 0:
1562
+ dep = deps[0]
1563
+ result_set.add(dep)
1564
+ helper(dep)
1565
+
1566
+ helper(sub)
1567
+ return result_set
1568
+
1569
+
1570
+ def get_subtasks_to_restart_with_dependencies(
1571
+ should_restart: dict, dependencies: dict, force_restart: str
1572
+ ):
1573
+ subtasks_to_restart = set([subtask for subtask, restart in should_restart.items() if restart])
1574
+
1575
+ # The last task requires to be a dependency too
1576
+ last_subtask = next(reversed(dependencies))
1577
+ dependencies["_end"] = last_subtask
1578
+
1579
+ deps_set = set()
1580
+ for sub_to_restart in subtasks_to_restart:
1581
+ deps_set = get_dependencies(sub_to_restart, dependencies, deps_set)
1582
+
1583
+ should_restart_with_deps = subtasks_to_restart | deps_set
1584
+ if "_end" in should_restart_with_deps:
1585
+ should_restart_with_deps.remove("_end")
1586
+
1587
+ # Adds the subtasks to force restart
1588
+ # NOTE: 'viz' is a special keyword handled in main.py, strip it here to avoid ValueError
1589
+ if len(force_restart) > 0:
1590
+ for subtask in force_restart.split(","):
1591
+ subtask = subtask.strip()
1592
+ if not subtask or subtask == "viz":
1593
+ continue
1594
+ if subtask not in TASK_ARGS:
1595
+ raise ValueError(
1596
+ f"Invalid subtask name `{subtask}` given to `--force_restart`. "
1597
+ f"Valid tasks: {list(TASK_ARGS.keys())} + 'viz'"
1598
+ )
1599
+ force_restart_deps = get_dependencies(subtask, dependencies, set())
1600
+ if "_end" in force_restart_deps:
1601
+ force_restart_deps.remove("_end")
1602
+ force_restart_deps.add(subtask)
1603
+ should_restart_with_deps = should_restart_with_deps | force_restart_deps
1604
+
1605
+ should_restart_with_deps = {task: (task in should_restart_with_deps) for task in TASK_ARGS}
1606
+
1607
+ return should_restart_with_deps
1608
+
1609
+
1610
+ def flatten_arg_values(cfg):
1611
+ def helper(dict_or_val, flatten_list):
1612
+ if isinstance(dict_or_val, dict):
1613
+ for key, value in dict_or_val.items():
1614
+ if isinstance(value, dict):
1615
+ helper(value, flatten_list)
1616
+ else:
1617
+ helper(f"{key}={value}", flatten_list)
1618
+ else:
1619
+ flatten_list.append(dict_or_val)
1620
+
1621
+ flatten_list = []
1622
+ helper(cfg, flatten_list)
1623
+ return flatten_list
1624
+
1625
+
1626
+ def add_cfg_args_to_parser(cfg, parser):
1627
+ def str2bool(v):
1628
+ if isinstance(v, bool):
1629
+ return v
1630
+ elif v == "None":
1631
+ return None
1632
+ if v.lower() in ("true"):
1633
+ return True
1634
+ elif v.lower() in ("false"):
1635
+ return False
1636
+ else:
1637
+ raise argparse.ArgumentTypeError("Boolean value expected.")
1638
+
1639
+ def nested_dict_to_separator_dict(nested_dict, separator="."):
1640
+ def _create_separator_dict(x, key="", separator_dict={}, keys_to_ignore=[]):
1641
+ if isinstance(x, dict):
1642
+ for k, v in x.items():
1643
+ kk = f"{key}{separator}{k}" if key else k
1644
+ _create_separator_dict(x[k], kk, keys_to_ignore=keys_to_ignore)
1645
+ else:
1646
+ if not any([ignore in key for ignore in keys_to_ignore]):
1647
+ separator_dict[key] = x
1648
+ return separator_dict
1649
+
1650
+ return _create_separator_dict(deepcopy(nested_dict))
1651
+
1652
+ separator_dict = nested_dict_to_separator_dict(cfg)
1653
+
1654
+ for k, v in separator_dict.items():
1655
+ assert isinstance(v, Arg), f"Arguments should have type `Arg`, seen {type(v)} instead."
1656
+ v = v.type
1657
+ is_bool = v == type(True)
1658
+ dtype = str2bool if is_bool else v
1659
+ parser.add_argument(f"--{k}", type=dtype)
1660
+
1661
+ return parser
1662
+
1663
+
1664
+ def get_node_feats_from_cfg(cfg):
1665
+ """{node type: [attributes used in labels]} for the node types of the dataset's schema.
1666
+
1667
+ Node types are in id order. `["auto"]` means the type-specific default label.
1668
+ """
1669
+ features = cfg.construction.node_label_features
1670
+ result = {}
1671
+ for key in get_schema(cfg).node_type_names:
1672
+ raw = (getattr(features, key, None) or "auto").strip()
1673
+ result[key] = ["auto"] if raw == "auto" else [x.strip() for x in raw.split(",")]
1674
+ return result
1675
+
1676
+
1677
+ TASK_FINISHED_FILE = "done.txt"
1678
+ VIZ_MANIFEST_FILE = "viz_manifest.json"
1679
+
1680
+
1681
+ def write_viz_manifest(task_path: str):
1682
+ """Write a viz_manifest.json alongside done.txt in evaluation task paths.
1683
+
1684
+ Records exact file paths so the visualizer never needs to glob or guess
1685
+ file extensions (.pkl vs .pth). Only fires for evaluation directories.
1686
+ """
1687
+ import json as _json
1688
+
1689
+ pr_dir = os.path.join(task_path, "precision_recall_dir")
1690
+ if not os.path.isdir(pr_dir):
1691
+ return # Not an evaluation task — nothing to do
1692
+
1693
+ epochs = []
1694
+ for fname in sorted(os.listdir(pr_dir)):
1695
+ if fname.startswith("stats_model_epoch_") and not fname.endswith(".png"):
1696
+ epoch_str = fname.replace("stats_model_epoch_", "").rsplit(".", 1)[0]
1697
+ stats_path = os.path.join(pr_dir, fname)
1698
+ ext = os.path.splitext(fname)[1] # .pth or .pkl — captured, not guessed
1699
+
1700
+ scores_path = os.path.join(pr_dir, f"scores_model_epoch_{epoch_str}.pkl")
1701
+ result_path = os.path.join(pr_dir, f"result_model_epoch_{epoch_str}{ext}")
1702
+ import torch
1703
+ adp = 0.0
1704
+ disc_score = 0.0
1705
+ try:
1706
+ d = torch.load(stats_path, map_location="cpu")
1707
+ adp = float(d.get("adp_score", 0.0))
1708
+ disc_score = float(d.get("discrimination", 0.0))
1709
+ except Exception:
1710
+ pass
1711
+
1712
+ entry = {
1713
+ "epoch": epoch_str,
1714
+ "stats_path": stats_path,
1715
+ "scores_path": scores_path if os.path.exists(scores_path) else None,
1716
+ "result_path": result_path if os.path.exists(result_path) else None,
1717
+ "adp": adp,
1718
+ "disc_score": disc_score
1719
+ }
1720
+ epochs.append(entry)
1721
+
1722
+ # Resolve training dir (sibling hash structure)
1723
+ # evaluation task_path looks like: <artifacts>/evaluation/evaluation/<hash>/<dataset>
1724
+ # training counterpart: <artifacts>/training/training/<hash>/<dataset>
1725
+ dataset = os.path.basename(task_path)
1726
+ artifacts_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(task_path))))
1727
+ training_base = os.path.join(artifacts_root, "training", "training")
1728
+
1729
+ edge_losses_dir = None
1730
+ trained_models_dir = None
1731
+ if os.path.isdir(training_base):
1732
+ # Find the training hash whose done.txt was written closest in time
1733
+ # to OUR evaluation done.txt — this ensures we get the correct
1734
+ # architecture's weights even when multiple models run back-to-back.
1735
+ eval_done = os.path.join(task_path, TASK_FINISHED_FILE)
1736
+ eval_mtime = os.path.getmtime(eval_done) if os.path.exists(eval_done) else None
1737
+
1738
+ candidates = []
1739
+ for h in os.listdir(training_base):
1740
+ ds_dir = os.path.join(training_base, h, dataset)
1741
+ train_done = os.path.join(ds_dir, TASK_FINISHED_FILE)
1742
+ if os.path.isdir(ds_dir) and os.path.exists(train_done):
1743
+ t_mtime = os.path.getmtime(train_done)
1744
+ # Training must have finished BEFORE evaluation
1745
+ if eval_mtime is not None and t_mtime <= eval_mtime:
1746
+ time_diff = eval_mtime - t_mtime
1747
+ candidates.append((time_diff, h, ds_dir))
1748
+ else:
1749
+ # Fallback: just use directory mtime
1750
+ candidates.append((float('inf'), h, ds_dir))
1751
+ if candidates:
1752
+ candidates.sort() # Smallest time_diff first = closest match
1753
+ best_train_dir = candidates[0][2]
1754
+ el = os.path.join(best_train_dir, "edge_losses")
1755
+ if os.path.isdir(el):
1756
+ edge_losses_dir = el
1757
+ tm = os.path.join(best_train_dir, "trained_models")
1758
+ if os.path.isdir(tm):
1759
+ trained_models_dir = tm
1760
+
1761
+ batching_base = os.path.join(artifacts_root, "batching", "batching")
1762
+ preprocessed_graphs_dir = None
1763
+ if os.path.isdir(batching_base):
1764
+ candidates = []
1765
+ for h in os.listdir(batching_base):
1766
+ ds_dir = os.path.join(batching_base, h, dataset)
1767
+ if os.path.isdir(ds_dir):
1768
+ candidates.append((os.path.getmtime(ds_dir), h, ds_dir))
1769
+ if candidates:
1770
+ candidates.sort(reverse=True)
1771
+ best_batching_dir = candidates[0][2]
1772
+ pg = os.path.join(best_batching_dir, "preprocessed_graphs")
1773
+ if os.path.isdir(pg):
1774
+ preprocessed_graphs_dir = pg
1775
+
1776
+ manifest = {
1777
+ "eval_task_path": task_path,
1778
+ "dataset": dataset,
1779
+ "edge_losses_dir": edge_losses_dir,
1780
+ "trained_models_dir": trained_models_dir,
1781
+ "preprocessed_graphs_dir": preprocessed_graphs_dir,
1782
+ "epochs": epochs,
1783
+ }
1784
+
1785
+ manifest_path = os.path.join(task_path, VIZ_MANIFEST_FILE)
1786
+ with open(manifest_path, "w") as f:
1787
+ _json.dump(manifest, f, indent=2)
1788
+
1789
+
1790
+ def set_task_to_done(task_path: str):
1791
+ with open(os.path.join(task_path, TASK_FINISHED_FILE), "w") as f:
1792
+ f.write("Task done")
1793
+
1794
+ # If this is an evaluation directory, write the viz manifest
1795
+ write_viz_manifest(task_path)
1796
+
1797
+
1798
+ def get_dates_from_cfg(cfg):
1799
+ if cfg._test_mode:
1800
+ # Get the day number of the first day in each set
1801
+ dates = [
1802
+ dates[0]
1803
+ for dates in [cfg.dataset.train_dates, cfg.dataset.val_dates, cfg.dataset.test_dates]
1804
+ ]
1805
+ else:
1806
+ dates = cfg.dataset.train_dates + cfg.dataset.val_dates + cfg.dataset.test_dates
1807
+
1808
+ return dates
1809
+
1810
+
1811
+ def get_uncertainty_methods_to_run(cfg):
1812
+ yml_file = get_yml_file(os.path.join(UNCERTAINTY_EXP_YML_FOLDER, cfg._experiment))
1813
+ validate_yml_file(yml_file, TASK_ARGS)
1814
+ with open(yml_file, "r") as file:
1815
+ uncertainty_cfg = yaml.safe_load(file)
1816
+ methods = list(uncertainty_cfg["experiment"]["uncertainty"].keys())
1817
+ return methods
1818
+
1819
+
1820
+ def decoder_matches_objective(decoder: str, objective: str):
1821
+ return not (
1822
+ (decoder in DECODERS_EDGE_LEVEL and objective in OBJECTIVES_NODE_LEVEL)
1823
+ or (decoder in DECODERS_NODE_LEVEL and objective in OBJECTIVES_EDGE_LEVEL)
1824
+ )