pidsmaker 4.0.0__py3-none-any.whl

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

Potentially problematic release.


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

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