pidsmaker 5.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (339) hide show
  1. pidsmaker/__init__.py +1 -0
  2. pidsmaker/cli.py +81 -0
  3. pidsmaker/config/__init__.py +2 -0
  4. pidsmaker/config/config.py +2100 -0
  5. pidsmaker/config/pipeline.py +1824 -0
  6. pidsmaker/config/schemas.py +1032 -0
  7. pidsmaker/datasets.py +323 -0
  8. pidsmaker/debug_tests.py +30 -0
  9. pidsmaker/decoders/__init__.py +5 -0
  10. pidsmaker/decoders/custom_edge_mlp_decoder.py +17 -0
  11. pidsmaker/decoders/custom_mlp_decoder.py +10 -0
  12. pidsmaker/decoders/edge_linear_decoder.py +16 -0
  13. pidsmaker/decoders/inner_product_decoder.py +18 -0
  14. pidsmaker/decoders/nodlink_decoder.py +56 -0
  15. pidsmaker/detection/__init__.py +0 -0
  16. pidsmaker/detection/evaluation_methods/__init__.py +9 -0
  17. pidsmaker/detection/evaluation_methods/edge_evaluation.py +255 -0
  18. pidsmaker/detection/evaluation_methods/evaluation_utils.py +1788 -0
  19. pidsmaker/detection/evaluation_methods/host_two_stage_evaluation.py +115 -0
  20. pidsmaker/detection/evaluation_methods/node_evaluation.py +459 -0
  21. pidsmaker/detection/evaluation_methods/node_tw_evaluation.py +196 -0
  22. pidsmaker/detection/evaluation_methods/plot.py +192 -0
  23. pidsmaker/detection/evaluation_methods/queue_evaluation.py +456 -0
  24. pidsmaker/detection/evaluation_methods/tw_evaluation.py +93 -0
  25. pidsmaker/detection/flash_detection.py +162 -0
  26. pidsmaker/detection/magic_knn.py +190 -0
  27. pidsmaker/detection/node_scoring.py +52 -0
  28. pidsmaker/detection/threatrace_detection.py +65 -0
  29. pidsmaker/detection/training_methods/__init__.py +1 -0
  30. pidsmaker/detection/training_methods/inference_loop.py +287 -0
  31. pidsmaker/detection/training_methods/ocrapt_early_stop.py +165 -0
  32. pidsmaker/detection/training_methods/threatrace_training.py +168 -0
  33. pidsmaker/detection/training_methods/training_loop.py +383 -0
  34. pidsmaker/encoders/__init__.py +22 -0
  35. pidsmaker/encoders/argus_encoder.py +69 -0
  36. pidsmaker/encoders/custom_mlp.py +75 -0
  37. pidsmaker/encoders/custom_mlp_encoder.py +10 -0
  38. pidsmaker/encoders/egraphsage_encoder.py +56 -0
  39. pidsmaker/encoders/gat.py +67 -0
  40. pidsmaker/encoders/gcn.py +27 -0
  41. pidsmaker/encoders/gin.py +48 -0
  42. pidsmaker/encoders/glstm.py +298 -0
  43. pidsmaker/encoders/graph_attention.py +63 -0
  44. pidsmaker/encoders/gru.py +29 -0
  45. pidsmaker/encoders/hetero/__init__.py +4 -0
  46. pidsmaker/encoders/hetero/ancestor_encoder.py +98 -0
  47. pidsmaker/encoders/hetero/entity_encoder.py +33 -0
  48. pidsmaker/encoders/hetero/event_encoder.py +81 -0
  49. pidsmaker/encoders/hetero/hetero_graph_transformer.py +40 -0
  50. pidsmaker/encoders/lares_encoder.py +68 -0
  51. pidsmaker/encoders/linear_encoder.py +16 -0
  52. pidsmaker/encoders/magic_encoder.py +161 -0
  53. pidsmaker/encoders/rcaid_encoder.py +81 -0
  54. pidsmaker/encoders/rgcn.py +75 -0
  55. pidsmaker/encoders/sage.py +51 -0
  56. pidsmaker/encoders/shadewatcher_encoder.py +149 -0
  57. pidsmaker/encoders/sum_aggregation.py +20 -0
  58. pidsmaker/encoders/temporal_wrappers.py +80 -0
  59. pidsmaker/encoders/textrcnn.py +82 -0
  60. pidsmaker/encoders/tgn_encoder.py +193 -0
  61. pidsmaker/experiments/tuning.py +102 -0
  62. pidsmaker/experiments/uncertainty.py +261 -0
  63. pidsmaker/factory.py +1456 -0
  64. pidsmaker/featurization/__init__.py +0 -0
  65. pidsmaker/featurization/feat_inference_methods/__init__.py +7 -0
  66. pidsmaker/featurization/feat_inference_methods/feat_inference_HFH.py +30 -0
  67. pidsmaker/featurization/feat_inference_methods/feat_inference_TRW.py +65 -0
  68. pidsmaker/featurization/feat_inference_methods/feat_inference_alacarte.py +14 -0
  69. pidsmaker/featurization/feat_inference_methods/feat_inference_doc2vec.py +53 -0
  70. pidsmaker/featurization/feat_inference_methods/feat_inference_fasttext.py +37 -0
  71. pidsmaker/featurization/feat_inference_methods/feat_inference_flash.py +69 -0
  72. pidsmaker/featurization/feat_inference_methods/feat_inference_graph2vec.py +84 -0
  73. pidsmaker/featurization/feat_inference_methods/feat_inference_ocrapt_features.py +95 -0
  74. pidsmaker/featurization/feat_inference_methods/feat_inference_pretrained.py +1728 -0
  75. pidsmaker/featurization/feat_inference_methods/feat_inference_word2vec.py +55 -0
  76. pidsmaker/featurization/featurization_methods/__init__.py +0 -0
  77. pidsmaker/featurization/featurization_methods/build_trw.py +66 -0
  78. pidsmaker/featurization/featurization_methods/featurization_alacarte.py +747 -0
  79. pidsmaker/featurization/featurization_methods/featurization_doc2vec.py +98 -0
  80. pidsmaker/featurization/featurization_methods/featurization_fasttext.py +74 -0
  81. pidsmaker/featurization/featurization_methods/featurization_flash.py +201 -0
  82. pidsmaker/featurization/featurization_methods/featurization_graph2vec.py +242 -0
  83. pidsmaker/featurization/featurization_methods/featurization_trw.py +114 -0
  84. pidsmaker/featurization/featurization_methods/featurization_word2vec.py +89 -0
  85. pidsmaker/featurization/featurization_utils.py +275 -0
  86. pidsmaker/featurization/utils/build_random_walks.py +66 -0
  87. pidsmaker/featurization/utils/trw.py +203 -0
  88. pidsmaker/hetero.py +81 -0
  89. pidsmaker/losses.py +170 -0
  90. pidsmaker/main.py +478 -0
  91. pidsmaker/mimicry.py +284 -0
  92. pidsmaker/model.py +382 -0
  93. pidsmaker/objectives/__init__.py +16 -0
  94. pidsmaker/objectives/autoencode_edge_emb.py +43 -0
  95. pidsmaker/objectives/deep_graph_infomax.py +94 -0
  96. pidsmaker/objectives/detect_few_shot.py +21 -0
  97. pidsmaker/objectives/one_class.py +75 -0
  98. pidsmaker/objectives/predict_edge_contrastive.py +165 -0
  99. pidsmaker/objectives/predict_edge_supervised.py +77 -0
  100. pidsmaker/objectives/predict_edge_type.py +28 -0
  101. pidsmaker/objectives/predict_masked_struct.py +49 -0
  102. pidsmaker/objectives/predict_node_type.py +36 -0
  103. pidsmaker/objectives/predict_process_tag.py +169 -0
  104. pidsmaker/objectives/predict_snapshot_embedding.py +97 -0
  105. pidsmaker/objectives/reconstruct_edge_emb.py +16 -0
  106. pidsmaker/objectives/reconstruct_masked_feat.py +51 -0
  107. pidsmaker/objectives/reconstruct_node_emb.py +13 -0
  108. pidsmaker/objectives/reconstruct_node_feat.py +13 -0
  109. pidsmaker/objectives/validation_wrapper.py +55 -0
  110. pidsmaker/preprocessing/__init__.py +0 -0
  111. pidsmaker/preprocessing/build_graph_methods/__init__.py +1 -0
  112. pidsmaker/preprocessing/build_graph_methods/build_default_graphs.py +825 -0
  113. pidsmaker/preprocessing/build_graph_methods/build_magic_graphs.py +216 -0
  114. pidsmaker/preprocessing/cleaning.py +258 -0
  115. pidsmaker/preprocessing/transformation_methods/__init__.py +2 -0
  116. pidsmaker/preprocessing/transformation_methods/attack_generation/synthetic_attack_naive.py +194 -0
  117. pidsmaker/preprocessing/transformation_methods/transformation_dag.py +28 -0
  118. pidsmaker/preprocessing/transformation_methods/transformation_merge_edges.py +136 -0
  119. pidsmaker/preprocessing/transformation_methods/transformation_rcaid_pseudo_graph.py +510 -0
  120. pidsmaker/preprocessing/transformation_methods/transformation_undirected.py +24 -0
  121. pidsmaker/preprocessing/transformation_methods/transformation_utils.py +36 -0
  122. pidsmaker/pretrained/__init__.py +5 -0
  123. pidsmaker/pretrained/data/__init__.py +4 -0
  124. pidsmaker/pretrained/data/behavior_signatures.py +548 -0
  125. pidsmaker/pretrained/data/canonical_tokens.py +1035 -0
  126. pidsmaker/pretrained/data/edge_filter.py +381 -0
  127. pidsmaker/pretrained/data/entity_classes.py +476 -0
  128. pidsmaker/pretrained/data/sampler.py +926 -0
  129. pidsmaker/pretrained/data/tokenizer_bpe.py +1659 -0
  130. pidsmaker/pretrained/detect.py +1427 -0
  131. pidsmaker/pretrained/embedding_generator.py +252 -0
  132. pidsmaker/pretrained/finetune.py +1434 -0
  133. pidsmaker/pretrained/models/__init__.py +20 -0
  134. pidsmaker/pretrained/models/behavior.py +348 -0
  135. pidsmaker/pretrained/models/bert.py +286 -0
  136. pidsmaker/pretrained/models/deepwalk.py +128 -0
  137. pidsmaker/pretrained/models/dgi.py +120 -0
  138. pidsmaker/pretrained/models/gae.py +114 -0
  139. pidsmaker/pretrained/models/gnn_distill.py +475 -0
  140. pidsmaker/pretrained/models/graphmae.py +373 -0
  141. pidsmaker/pretrained/models/hf_pretrained.py +213 -0
  142. pidsmaker/pretrained/models/llama.py +110 -0
  143. pidsmaker/pretrained/models/modernbert.py +567 -0
  144. pidsmaker/pretrained/models/roberta.py +147 -0
  145. pidsmaker/pretrained/models/rope_utils.py +99 -0
  146. pidsmaker/pretrained/models/ropebert.py +322 -0
  147. pidsmaker/pretrained/models/spider.py +204 -0
  148. pidsmaker/pretrained/models/tgn.py +770 -0
  149. pidsmaker/pretrained/pretrain/__init__.py +3 -0
  150. pidsmaker/pretrained/pretrain/pretrain_behavior_cluster.py +513 -0
  151. pidsmaker/pretrained/pretrain/pretrain_common.py +585 -0
  152. pidsmaker/pretrained/pretrain/pretrain_deepwalk.py +31 -0
  153. pidsmaker/pretrained/pretrain/pretrain_dgi.py +143 -0
  154. pidsmaker/pretrained/pretrain/pretrain_gae.py +143 -0
  155. pidsmaker/pretrained/pretrain/pretrain_gnn_distill.py +438 -0
  156. pidsmaker/pretrained/pretrain/pretrain_graphmae.py +151 -0
  157. pidsmaker/pretrained/pretrain/pretrain_hf.py +169 -0
  158. pidsmaker/pretrained/pretrain/pretrain_main.py +275 -0
  159. pidsmaker/pretrained/pretrain/pretrain_mlm.py +491 -0
  160. pidsmaker/pretrained/pretrain/pretrain_spider.py +502 -0
  161. pidsmaker/pretrained/training_utils.py +157 -0
  162. pidsmaker/process_reapr_gt.py +101 -0
  163. pidsmaker/resources/config/anomal_e.yml +25 -0
  164. pidsmaker/resources/config/argus.yml +56 -0
  165. pidsmaker/resources/config/attack_edges/cadets_e3.yml +435 -0
  166. pidsmaker/resources/config/attack_edges/cadets_e5.yml +407 -0
  167. pidsmaker/resources/config/attack_edges/theia_e3.yml +382 -0
  168. pidsmaker/resources/config/attack_edges/theia_e5.yml +387 -0
  169. pidsmaker/resources/config/attack_edges/trace_e3.yml +415 -0
  170. pidsmaker/resources/config/attack_edges/trace_e5.yml +417 -0
  171. pidsmaker/resources/config/default.yml +315 -0
  172. pidsmaker/resources/config/egraphsage.yml +95 -0
  173. pidsmaker/resources/config/euler.yml +104 -0
  174. pidsmaker/resources/config/eval/eval_set_clustering.json +3170 -0
  175. pidsmaker/resources/config/experiments/tuning/components/tuning_featurization_methods.yml +29 -0
  176. pidsmaker/resources/config/experiments/tuning/systems/clearscope_e5/tuning_orthrus.yml +14 -0
  177. pidsmaker/resources/config/experiments/tuning/systems/default/tuning_default_baselines.yml +13 -0
  178. pidsmaker/resources/config/experiments/tuning/systems/default/tuning_orthrus_fixed.yml +16 -0
  179. pidsmaker/resources/config/experiments/uncertainty/none.yml +5 -0
  180. pidsmaker/resources/config/experiments/uncertainty/run_n_times.yml +12 -0
  181. pidsmaker/resources/config/experiments/uncertainty/run_n_times_hyperparameters.yml +12 -0
  182. pidsmaker/resources/config/experiments/uncertainty/uncertainty.yml +22 -0
  183. pidsmaker/resources/config/flash.yml +79 -0
  184. pidsmaker/resources/config/jbeil.yml +65 -0
  185. pidsmaker/resources/config/kairos.yml +121 -0
  186. pidsmaker/resources/config/lares.yml +115 -0
  187. pidsmaker/resources/config/magic.yml +86 -0
  188. pidsmaker/resources/config/nodlink.yml +79 -0
  189. pidsmaker/resources/config/ocrapt.yml +91 -0
  190. pidsmaker/resources/config/orthrus.yml +126 -0
  191. pidsmaker/resources/config/orthrus_fixed.yml +17 -0
  192. pidsmaker/resources/config/pretrained/README.md +101 -0
  193. pidsmaker/resources/config/pretrained/cybergfm/cybergfm.yml +49 -0
  194. pidsmaker/resources/config/pretrained/pretrained.yml +190 -0
  195. pidsmaker/resources/config/pretrained/pretrained_flash.yml +9 -0
  196. pidsmaker/resources/config/pretrained/pretrained_kairos.yml +12 -0
  197. pidsmaker/resources/config/pretrained/pretrained_magic.yml +1 -0
  198. pidsmaker/resources/config/pretrained/pretrained_nodlink.yml +1 -0
  199. pidsmaker/resources/config/pretrained/pretrained_orthrus.yml +1 -0
  200. pidsmaker/resources/config/pretrained/pretrained_supervised.yml +13 -0
  201. pidsmaker/resources/config/pretrained/pretrained_threatrace.yml +8 -0
  202. pidsmaker/resources/config/pretrained/pretrained_velox.yml +14 -0
  203. pidsmaker/resources/config/prographer.yml +136 -0
  204. pidsmaker/resources/config/rcaid.yml +88 -0
  205. pidsmaker/resources/config/shadewatcher.yml +146 -0
  206. pidsmaker/resources/config/tests.yml +10 -0
  207. pidsmaker/resources/config/threatrace.yml +73 -0
  208. pidsmaker/resources/config/tuned_baselines/optc_net/tuned_argus.yml +4 -0
  209. pidsmaker/resources/config/tuned_baselines/optc_net/tuned_lares.yml +13 -0
  210. pidsmaker/resources/config/velox.yml +10 -0
  211. pidsmaker/resources/config/viz_config.yml +10 -0
  212. pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_06.csv +8 -0
  213. pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_11.csv +4 -0
  214. pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_12.csv +43 -0
  215. pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_13.csv +24 -0
  216. pidsmaker/resources/ground_truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0411.csv +41 -0
  217. pidsmaker/resources/ground_truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0412.csv +0 -0
  218. pidsmaker/resources/ground_truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_browser_0412.csv +1 -0
  219. pidsmaker/resources/ground_truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +63 -0
  220. pidsmaker/resources/ground_truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +56 -0
  221. pidsmaker/resources/ground_truth/orthrus/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +61 -0
  222. pidsmaker/resources/ground_truth/orthrus/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +58 -0
  223. pidsmaker/resources/ground_truth/orthrus/E3-TRACE/node_trace_e3_firefox_0410.csv +11 -0
  224. pidsmaker/resources/ground_truth/orthrus/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +11 -0
  225. pidsmaker/resources/ground_truth/orthrus/E3-TRACE/node_trace_e3_pine_0413.csv +14 -0
  226. pidsmaker/resources/ground_truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT.csv +19 -0
  227. pidsmaker/resources/ground_truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT_17.csv +107 -0
  228. pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_appstarter_0515.csv +26 -0
  229. pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_firefox_0517.csv +1 -0
  230. pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_lockwatch_0517.csv +17 -0
  231. pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_tester_0517.csv +8 -0
  232. pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_bits_0515.csv +54 -0
  233. pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_copykatz_0509.csv +87 -0
  234. pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_dns_0517.csv +11 -0
  235. pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_drakon_0517.csv +6 -0
  236. pidsmaker/resources/ground_truth/orthrus/E5-THEIA/node_THEIA_1_Firefox_Drakon_APT_BinFmt_Elevate_Inject.csv +70 -0
  237. pidsmaker/resources/ground_truth/orthrus/E5-TRACE/node_Trace_Firefox_Drakon.csv +71 -0
  238. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m1.csv +1 -0
  239. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m2.csv +1 -0
  240. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m3.csv +1 -0
  241. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m4.csv +5 -0
  242. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m5.csv +23 -0
  243. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m6.csv +18 -0
  244. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s1.csv +1 -0
  245. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s2.csv +1 -0
  246. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s3.csv +16 -0
  247. pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s4.csv +22 -0
  248. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m1.csv +126 -0
  249. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m2.csv +105 -0
  250. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m3.csv +94 -0
  251. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m4.csv +139 -0
  252. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m5.csv +228 -0
  253. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m6.csv +131 -0
  254. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s1.csv +118 -0
  255. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s2.csv +89 -0
  256. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s3.csv +133 -0
  257. pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s4.csv +135 -0
  258. pidsmaker/resources/ground_truth/orthrus/carbanakv2_edr/carbanakv2_edr.csv +2453 -0
  259. pidsmaker/resources/ground_truth/orthrus/h051/node_h051_0925.csv +114 -0
  260. pidsmaker/resources/ground_truth/orthrus/h201/node_h201_0923.csv +2905 -0
  261. pidsmaker/resources/ground_truth/orthrus/h501/node_h501_0924.csv +749 -0
  262. pidsmaker/resources/ground_truth/orthrus/readme.md +98 -0
  263. pidsmaker/resources/ground_truth/reapr/E3-CADETS/node_Nginx_Backdoor_06.csv +3 -0
  264. pidsmaker/resources/ground_truth/reapr/E3-CADETS/node_Nginx_Backdoor_12.csv +655 -0
  265. pidsmaker/resources/ground_truth/reapr/E3-CADETS/node_Nginx_Backdoor_13.csv +770 -0
  266. pidsmaker/resources/ground_truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +0 -0
  267. pidsmaker/resources/ground_truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +18 -0
  268. pidsmaker/resources/ground_truth/reapr/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +42 -0
  269. pidsmaker/resources/ground_truth/reapr/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +81 -0
  270. pidsmaker/resources/ground_truth/reapr/E3-TRACE/node_trace_e3_firefox_0410.csv +37 -0
  271. pidsmaker/resources/ground_truth/reapr/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +9 -0
  272. pidsmaker/resources/ground_truth/reapr/E3-TRACE/node_trace_e3_pine_0413.csv +40 -0
  273. pidsmaker/resources/ground_truth/threatrace/E3-CADETS/ground_truth.txt +12858 -0
  274. pidsmaker/resources/ground_truth/threatrace/E3-FIVEDIRECTIONS/ground_truth.txt +18420 -0
  275. pidsmaker/resources/ground_truth/threatrace/E3-THEIA/ground_truth.txt +25363 -0
  276. pidsmaker/resources/ground_truth/threatrace/E3-TRACE/ground_truth.txt +68265 -0
  277. pidsmaker/resources/ground_truth/threatrace/README.md +123 -0
  278. pidsmaker/tasks/__init__.py +10 -0
  279. pidsmaker/tasks/batching.py +47 -0
  280. pidsmaker/tasks/construction.py +31 -0
  281. pidsmaker/tasks/evaluation.py +241 -0
  282. pidsmaker/tasks/feat_inference.py +413 -0
  283. pidsmaker/tasks/featurization.py +43 -0
  284. pidsmaker/tasks/training.py +17 -0
  285. pidsmaker/tasks/transformation.py +306 -0
  286. pidsmaker/tasks/triage.py +143 -0
  287. pidsmaker/tgn.py +635 -0
  288. pidsmaker/tokenization/__init__.py +112 -0
  289. pidsmaker/tokenization/base.py +58 -0
  290. pidsmaker/tokenization/bpe_tokenizer.py +83 -0
  291. pidsmaker/tokenization/hf_tokenizer.py +61 -0
  292. pidsmaker/tokenization/hierarchical_tokenizer.py +44 -0
  293. pidsmaker/tokenization/label_tokenizer.py +24 -0
  294. pidsmaker/tokenization/nltk_tokenizer.py +84 -0
  295. pidsmaker/tokenization/substitution.py +295 -0
  296. pidsmaker/triage/__init__.py +0 -0
  297. pidsmaker/triage/tracing_methods/__init__.py +1 -0
  298. pidsmaker/triage/tracing_methods/depimpact.py +213 -0
  299. pidsmaker/triage/tracing_methods/depimpact_utils.py +537 -0
  300. pidsmaker/triage/tracing_methods/ocrapt_subgraph.py +267 -0
  301. pidsmaker/utils/__init__.py +0 -0
  302. pidsmaker/utils/cache_utils.py +256 -0
  303. pidsmaker/utils/console.py +282 -0
  304. pidsmaker/utils/data_utils.py +1742 -0
  305. pidsmaker/utils/database.py +150 -0
  306. pidsmaker/utils/dataset_utils.py +413 -0
  307. pidsmaker/utils/dataset_writer.py +570 -0
  308. pidsmaker/utils/graph_store.py +634 -0
  309. pidsmaker/utils/labelling.py +445 -0
  310. pidsmaker/utils/loss_files.py +193 -0
  311. pidsmaker/utils/process_tags.py +44 -0
  312. pidsmaker/utils/utils.py +712 -0
  313. pidsmaker/vizgen/__init__.py +1 -0
  314. pidsmaker/vizgen/backfill_manifests.py +100 -0
  315. pidsmaker/vizgen/dimensionality_reduction.py +249 -0
  316. pidsmaker/vizgen/embed_exporter.py +467 -0
  317. pidsmaker/vizgen/exporter.py +493 -0
  318. pidsmaker/vizgen/html_builder.py +936 -0
  319. pidsmaker/vizgen/web/__init__.py +1 -0
  320. pidsmaker/vizgen/web/export.py +62 -0
  321. pidsmaker/vizgen/web/static/css/app.css +250 -0
  322. pidsmaker/vizgen/web/static/index.html +182 -0
  323. pidsmaker/vizgen/web/static/js/app.js +627 -0
  324. pidsmaker/vizgen/web/static/js/campaign.js +123 -0
  325. pidsmaker/vizgen/web/static/js/data.js +119 -0
  326. pidsmaker/vizgen/web/static/js/dialogs.js +240 -0
  327. pidsmaker/vizgen/web/static/js/jobs.js +75 -0
  328. pidsmaker/vizgen/web/static/js/scene.js +651 -0
  329. pidsmaker/vizgen/web/static/js/ui.js +370 -0
  330. pidsmaker/vizgen/web/static/vendor/OrbitControls.js +1045 -0
  331. pidsmaker/vizgen/web/static/vendor/d3.v4.min.js +2 -0
  332. pidsmaker/vizgen/web/static/vendor/three.min.js +6 -0
  333. pidsmaker/vizgen/web/viz_server.py +2176 -0
  334. pidsmaker-5.0.0.dist-info/METADATA +597 -0
  335. pidsmaker-5.0.0.dist-info/RECORD +339 -0
  336. pidsmaker-5.0.0.dist-info/WHEEL +5 -0
  337. pidsmaker-5.0.0.dist-info/entry_points.txt +2 -0
  338. pidsmaker-5.0.0.dist-info/licenses/LICENSE +201 -0
  339. pidsmaker-5.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,493 @@
1
+ #!/usr/bin/env python3
2
+ """CLI entry point for interactive 3D embedding visualization.
3
+
4
+ Usage:
5
+ python -m pidsmaker.vizgen.web.export <model> <dataset> [options]
6
+
7
+ Examples:
8
+ # Word2Vec raw embeddings (default)
9
+ python -m pidsmaker.vizgen.web.export orthrus CADETS_E3
10
+
11
+ # GNN encoder embeddings
12
+ python -m pidsmaker.vizgen.web.export orthrus CADETS_E3 --embeddings encoder
13
+
14
+ # Both views
15
+ python -m pidsmaker.vizgen.web.export orthrus CADETS_E3 --embeddings both
16
+
17
+ # Custom sampling
18
+ python -m pidsmaker.vizgen.web.export orthrus CADETS_E3 --max_benign 10000 --max_attack all
19
+
20
+ # t-SNE instead of UMAP
21
+ python -m pidsmaker.vizgen.web.export orthrus CADETS_E3 --method tsne
22
+ """
23
+
24
+ import argparse
25
+ import gc
26
+ import glob
27
+ import json
28
+ import os
29
+ import sys
30
+
31
+ import numpy as np
32
+ import torch
33
+ import yaml
34
+ from yacs.config import CfgNode as CN
35
+
36
+ from pidsmaker.config import get_runtime_required_args, get_yml_cfg
37
+ from pidsmaker.utils.dataset_utils import get_node_to_path_and_type
38
+ from pidsmaker.utils.utils import get_device, log
39
+ from pidsmaker.vizgen.dimensionality_reduction import reduce_to_3d
40
+ from pidsmaker.vizgen.embed_exporter import (
41
+ extract_encoder_embeddings,
42
+ extract_word2vec_embeddings,
43
+ smart_sample,
44
+ )
45
+ from pidsmaker.vizgen.html_builder import build_html
46
+
47
+
48
+ def load_viz_config():
49
+ """Load viz_config.yml defaults."""
50
+ from pidsmaker.config.pipeline import ROOT_PROJECT_PATH
51
+
52
+ config_path = os.path.join(ROOT_PROJECT_PATH, "config", "viz_config.yml")
53
+ if os.path.exists(config_path):
54
+ with open(config_path, encoding="utf-8") as f:
55
+ return yaml.safe_load(f).get("embedding_viz", {})
56
+ return {}
57
+
58
+
59
+ def _get_artifacts_root():
60
+ """Return the artifacts root: $PIDS_ARTIFACTS_DIR, else the default of --artifact_dir."""
61
+ from pidsmaker.config.pipeline import default_artifact_dir
62
+
63
+ return os.environ.get("PIDS_ARTIFACTS_DIR") or default_artifact_dir()
64
+
65
+
66
+ def _find_manifests(dataset):
67
+ """Locate all viz_manifest.json files for a given dataset."""
68
+ artifacts_root = _get_artifacts_root()
69
+ manifests = []
70
+ for base in ("evaluation/evaluation", "detection/evaluation"):
71
+ pattern = os.path.join(artifacts_root, base, "*", dataset, "viz_manifest.json")
72
+ manifests.extend(glob.glob(pattern))
73
+ return manifests
74
+
75
+
76
+ def find_models(dataset="CADETS_E3", run_dir=None):
77
+ """Discover evaluated model epochs for visualization.
78
+
79
+ Reads viz_manifest.json (written by set_task_to_done) for exact artifact
80
+ paths. Falls back to glob-based discovery if no manifest exists yet.
81
+
82
+ If *run_dir* is given (a specific run's eval task dir or its
83
+ viz_manifest.json), that run is used directly instead of the latest one
84
+ found for the dataset — lets the user export a chosen run from artifacts.
85
+ """
86
+ if run_dir:
87
+ mp = run_dir if run_dir.endswith(".json") else os.path.join(run_dir, "viz_manifest.json")
88
+ if not os.path.exists(mp):
89
+ raise FileNotFoundError(f"viz_manifest.json not found for --run {run_dir}")
90
+ print(f" Using run manifest: {mp}")
91
+ with open(mp, "r", encoding="utf-8") as f:
92
+ manifest = json.load(f)
93
+ return _models_from_manifest(manifest)
94
+
95
+ print(f"Scanning for best models for dataset: {dataset}...")
96
+ manifests = _find_manifests(dataset)
97
+
98
+ if manifests:
99
+ # Pick the most recently modified manifest
100
+ manifests.sort(key=os.path.getmtime, reverse=True)
101
+ manifest_path = manifests[0]
102
+ print(f" Using manifest: {manifest_path}")
103
+ with open(manifest_path, "r", encoding="utf-8") as f:
104
+ manifest = json.load(f)
105
+ return _models_from_manifest(manifest)
106
+
107
+ # --- Fallback: glob-based discovery (backward compat) ---
108
+ print(" WARNING: No viz_manifest.json found — falling back to glob discovery.")
109
+ print(" WARNING: Encoder embeddings may fail (no trained_models_dir or preprocessed_graphs_dir available).")
110
+ return _models_from_glob(dataset)
111
+
112
+
113
+ def _models_from_manifest(manifest):
114
+ """Build a models list from a viz_manifest.json."""
115
+ models = []
116
+ for entry in manifest.get("epochs", []):
117
+ stats_path = entry["stats_path"]
118
+ if not os.path.exists(stats_path):
119
+ continue
120
+ try:
121
+ stats = torch.load(stats_path, map_location="cpu")
122
+ except Exception:
123
+ continue
124
+
125
+ adp = stats.get("adp_score", 0)
126
+ epoch_str = entry["epoch"]
127
+
128
+ model_path = None
129
+ tm_dir = manifest.get("trained_models_dir")
130
+ if tm_dir and os.path.exists(tm_dir):
131
+ mp = os.path.join(tm_dir, f"model_epoch_{epoch_str}")
132
+ if os.path.exists(mp):
133
+ model_path = mp
134
+
135
+ models.append({
136
+ "name": f"Epoch_{epoch_str}_ADP_{adp:.3f}",
137
+ "path": model_path,
138
+ "adp": adp,
139
+ "epoch": epoch_str,
140
+ "stats_path": stats_path,
141
+ "scores_path": entry.get("scores_path"),
142
+ "edge_scores_path": entry.get("scores_path"), # compat alias
143
+ "edge_losses_dir": manifest.get("edge_losses_dir"),
144
+ "trained_models_dir": tm_dir,
145
+ "preprocessed_graphs_dir": manifest.get("preprocessed_graphs_dir"),
146
+ "eval_task_path": manifest.get("eval_task_path"),
147
+ })
148
+
149
+ models.sort(key=lambda x: x["adp"], reverse=True)
150
+ return models[:6]
151
+
152
+
153
+ def _models_from_glob(dataset):
154
+ """Legacy glob-based model discovery."""
155
+ artifacts_root = _get_artifacts_root()
156
+ eval_patterns = [
157
+ os.path.join(artifacts_root, "detection/evaluation/*", dataset,
158
+ "precision_recall_dir/stats_model_epoch_*.*"),
159
+ os.path.join(artifacts_root, "evaluation/evaluation/*", dataset,
160
+ "precision_recall_dir/stats_model_epoch_*.*"),
161
+ ]
162
+ models_found = []
163
+ for pattern in eval_patterns:
164
+ for f in glob.glob(pattern):
165
+ if f.endswith(".png"):
166
+ continue
167
+ try:
168
+ s = torch.load(f, map_location="cpu")
169
+ adp = s.get("adp_score", 0)
170
+ epoch_str = os.path.basename(f).replace("stats_model_epoch_", "").rsplit(".", 1)[0]
171
+ models_found.append({
172
+ "name": f"Epoch_{epoch_str}_ADP_{adp:.3f}",
173
+ "path": None,
174
+ "adp": adp,
175
+ "epoch": epoch_str,
176
+ "stats_path": f,
177
+ "edge_scores_path": f.replace("stats_", "scores_"),
178
+ })
179
+ except Exception:
180
+ continue
181
+
182
+ models_found.sort(key=lambda x: x["adp"], reverse=True)
183
+ return models_found[:6]
184
+
185
+ def get_malicious_node_ids(cfg):
186
+ """Get ground-truth malicious node IDs."""
187
+ from pidsmaker.utils.labelling import get_ground_truth
188
+
189
+ gt_nids, _, _ = get_ground_truth(cfg)
190
+ log(f"Ground truth: {len(gt_nids)} malicious nodes")
191
+ return gt_nids
192
+
193
+
194
+ def run_visualization(args, cfg):
195
+ """Main visualization pipeline."""
196
+ viz_cfg = load_viz_config()
197
+
198
+ # CLI args override config
199
+ embeddings = args.embeddings or viz_cfg.get("embeddings", "word2vec")
200
+ method = args.method or viz_cfg.get("method", "umap")
201
+ max_benign = args.max_benign or viz_cfg.get("max_benign_nodes", "all")
202
+ max_attack = args.max_attack or viz_cfg.get("max_attack_nodes", "all")
203
+ default_hops = int(viz_cfg.get("default_hops", 0))
204
+
205
+ # Output directory logic — use manifest eval_task_path if available
206
+ models = find_models(cfg.dataset.name, run_dir=getattr(args, "run", None))
207
+ artifacts_root = _get_artifacts_root()
208
+
209
+ eval_task_path = None
210
+ if models and models[0].get("eval_task_path"):
211
+ eval_task_path = models[0]["eval_task_path"]
212
+
213
+ if eval_task_path:
214
+ out_dir = os.path.join(eval_task_path, "viz")
215
+ else:
216
+ out_dir = os.path.join(artifacts_root, "viz")
217
+
218
+ os.makedirs(out_dir, exist_ok=True)
219
+ log(f"Saving visualization artifacts to {out_dir}")
220
+
221
+ # Get ground truth
222
+ malicious_ids = get_malicious_node_ids(cfg)
223
+
224
+ modes = []
225
+ if embeddings in ("word2vec", "both"):
226
+ modes.append({"type": "word2vec", "suffix": "word2vec", "title": f"{cfg.dataset.name} — Word2Vec Raw Embeddings"})
227
+ if embeddings in ("encoder", "both"):
228
+ if not models:
229
+ raise ValueError(f"No trained models found for dataset {cfg.dataset.name}")
230
+ if hasattr(args, 'epoch') and args.epoch is not None:
231
+ # Single-epoch mode: filter to the requested epoch
232
+ models_to_run = [m for m in models if str(m.get('epoch')) == str(args.epoch)]
233
+ if not models_to_run:
234
+ raise ValueError(f"Epoch {args.epoch} not found in available models")
235
+ elif args.all_epochs:
236
+ models_to_run = models
237
+ else:
238
+ models_to_run = [models[0]]
239
+ for m_info in models_to_run:
240
+ ep = m_info.get("epoch", "latest")
241
+ # For the default/latest model, keep the standard suffix for compatibility
242
+ # unless --all_epochs is passed, in which case we append the epoch.
243
+ if not args.all_epochs and m_info == models[0]:
244
+ suffix = "encoder"
245
+ else:
246
+ suffix = f"encoder_epoch_{ep}"
247
+ modes.append({
248
+ "type": "encoder",
249
+ "suffix": suffix,
250
+ "title": f"{cfg.dataset.name} — GNN Encoder (Epoch {ep})",
251
+ "model_info": m_info
252
+ })
253
+
254
+ cached_graph_data = None
255
+
256
+ encoder_jobs = [j for j in modes if j["type"] == "encoder"]
257
+ last_encoder_suffix = encoder_jobs[-1]["suffix"] if encoder_jobs else None
258
+
259
+ for job in modes:
260
+ mode_type = job["type"]
261
+ log(f"{'='*60}", pre_return_line=True)
262
+ log(f"Running {job['suffix']} embedding extraction...")
263
+ log(f"{'='*60}")
264
+
265
+ if mode_type == "word2vec":
266
+ result = extract_word2vec_embeddings(cfg, malicious_ids)
267
+ title = job["title"]
268
+ else:
269
+ # Load model and data (only once)
270
+ if cached_graph_data is None:
271
+
272
+ # Try loading from disk cache first (saved by training_loop.py)
273
+ # This avoids recomputing the entire TGN batching pipeline from scratch
274
+ _cache_dir = cfg.batching._preprocessed_graphs_dir
275
+ if job.get("model_info", {}).get("preprocessed_graphs_dir"):
276
+ _cache_dir = job["model_info"]["preprocessed_graphs_dir"]
277
+ _cache_file = os.path.join(_cache_dir, "torch_graphs.pkl")
278
+ _viz_cache_file = os.path.join(_cache_dir, "viz_test_graphs.pkl")
279
+
280
+ if os.path.exists(_viz_cache_file):
281
+ log(f"Loading preprocessed test graphs from viz cache: {_viz_cache_file}")
282
+ test_data, max_node_num = torch.load(_viz_cache_file)
283
+ elif os.path.exists(_cache_file):
284
+ log(f"Loading preprocessed graphs from cache: {_cache_file}")
285
+ _, _, test_data, max_node_num = torch.load(_cache_file)
286
+ else:
287
+ log("No cached graphs found, recomputing...")
288
+ try:
289
+ from pidsmaker.tasks.batching import get_preprocessed_graphs
290
+ except ImportError:
291
+ from pidsmaker.detection.graph_preprocessing import get_preprocessed_graphs
292
+
293
+ tmp_train, tmp_val, test_data, max_node_num = get_preprocessed_graphs(cfg)
294
+ del tmp_train
295
+ del tmp_val
296
+ gc.collect()
297
+
298
+ gc.collect()
299
+ cached_graph_data = (test_data, max_node_num)
300
+
301
+ device = get_device(cfg)
302
+ test_data, max_node_num = cached_graph_data
303
+
304
+ from pidsmaker.factory import build_model
305
+
306
+ m_info = job["model_info"]
307
+ try:
308
+ model = build_model(
309
+ data_sample=test_data[0][0],
310
+ device=device,
311
+ cfg=cfg,
312
+ max_node_num=max_node_num,
313
+ )
314
+ sd_path = m_info.get('path')
315
+ if sd_path and os.path.isdir(sd_path):
316
+ sd_path = os.path.join(sd_path, "state_dict.pkl")
317
+ if sd_path:
318
+ model.load_state_dict(
319
+ torch.load(sd_path, map_location=device, weights_only=False)
320
+ )
321
+ log(f"Loaded model weights from {sd_path}")
322
+ else:
323
+ log(f"Warning: No valid model path found for epoch {m_info.get('epoch')}. Using uninitialized weights.")
324
+ except Exception as e:
325
+ log(f"ERROR: could not build/load the encoder for epoch {m_info.get('epoch')}: "
326
+ f"the saved checkpoint does not match the model architecture this config builds. "
327
+ f"This run was likely trained with a different config (and has no saved run_config.yml to "
328
+ f"reconstruct it). Skipping encoder export — word2vec, if requested, is unaffected. "
329
+ f"[{type(e).__name__}: {str(e).splitlines()[0][:160]}]")
330
+ continue
331
+
332
+ epoch_str = m_info.get("epoch", "0")
333
+ detected_nodes = None
334
+ node_anomaly_info = None
335
+ try:
336
+ scores_path = m_info.get("scores_path") or m_info.get("edge_scores_path")
337
+ if scores_path and os.path.exists(scores_path):
338
+ from pidsmaker.vizgen.embed_exporter import parse_scores_file
339
+ detected_nodes, _, node_anomaly_info = parse_scores_file(scores_path, malicious_ids)
340
+ log(f"Evaluation Stats: Found {len(detected_nodes)} detected nodes for epoch {epoch_str}.")
341
+ except Exception as e:
342
+ log(f"Warning: Failed to parse evaluation stats for coloring: {e}")
343
+
344
+ result = extract_encoder_embeddings(
345
+ model, test_data, device, malicious_ids,
346
+ detected_node_ids=detected_nodes,
347
+ node_anomaly_info=node_anomaly_info
348
+ )
349
+ title = job["title"]
350
+
351
+ # Sample
352
+ result = smart_sample(result, max_benign, max_attack)
353
+
354
+ # Dimensionality reduction (GPU-accelerated if available)
355
+ device = get_device(cfg)
356
+ points = reduce_to_3d(result, method=method, device=device)
357
+
358
+ # Free massive embeddings array immediately
359
+ result.embeddings = []
360
+ gc.collect()
361
+
362
+ # Node metadata
363
+ log("Loading node metadata from database...")
364
+ node_meta = get_node_to_path_and_type(cfg)
365
+
366
+ # Define output path
367
+ suffix = job["suffix"]
368
+ out_path = os.path.join(
369
+ out_dir,
370
+ f"embedding_viz_{cfg.dataset.name}_{suffix}.html",
371
+ )
372
+ if hasattr(args, "output") and args.output:
373
+ out_path = args.output
374
+
375
+ # Resolve edge-type ids -> relation names (e.g. EVENT_READ) for the viewer
376
+ from pidsmaker.utils.dataset_utils import get_rel2id
377
+
378
+ rel = get_rel2id(cfg, from_zero=True)
379
+ id2name = {k: v for k, v in rel.items() if isinstance(k, int)}
380
+ typed_edges = [
381
+ (e[0], e[1], e[2], id2name.get(e[3], "") if len(e) > 3 else "")
382
+ for e in result.edges
383
+ ]
384
+
385
+ # Build HTML
386
+ log("Building interactive HTML viewer...")
387
+ html = build_html(
388
+ points=points,
389
+ edges=typed_edges,
390
+ node_metadata=node_meta,
391
+ title=title,
392
+ default_hops=default_hops,
393
+ out_path=out_path,
394
+ )
395
+
396
+ with open(out_path, "w", encoding="utf-8") as f:
397
+ f.write(html)
398
+
399
+ log(f"Saved visualization to: {out_path}")
400
+ log(f"File size: {os.path.getsize(out_path) / (1024*1024):.1f} MB")
401
+
402
+ # Free memory at the end of loop iteration
403
+ del html
404
+ del points
405
+ del result
406
+ del node_meta
407
+
408
+ # Free massive cached graphs if this was the last encoder job
409
+ if mode_type == "encoder" and job["suffix"] == last_encoder_suffix:
410
+ if cached_graph_data is not None:
411
+ del cached_graph_data
412
+ cached_graph_data = None
413
+
414
+ gc.collect()
415
+
416
+
417
+ def _prune_unknown_keys(loaded, base, path=""):
418
+ """Drop keys from `loaded` not present in `base`'s schema, so the rest of
419
+ the config can still merge. Returns the dropped dotted key names."""
420
+ dropped = []
421
+ for key in list(loaded.keys()):
422
+ full_key = f"{path}.{key}" if path else key
423
+ if key not in base:
424
+ dropped.append(full_key)
425
+ del loaded[key]
426
+ elif isinstance(loaded[key], dict) and isinstance(base[key], dict):
427
+ dropped += _prune_unknown_keys(loaded[key], base[key], full_key)
428
+ return dropped
429
+
430
+
431
+ def main():
432
+ parser = argparse.ArgumentParser(description="Interactive 3D Embedding Visualization")
433
+ parser.add_argument("model", type=str, help="Model config name (e.g. orthrus, velox)")
434
+ parser.add_argument("dataset", type=str, help="Dataset name (e.g. CADETS_E3)")
435
+ parser.add_argument("--embeddings", type=str, choices=["word2vec", "encoder", "both"],
436
+ default=None, help="Embedding source (default: from viz_config.yml)")
437
+ parser.add_argument("--method", type=str, choices=["umap", "tsne"],
438
+ default=None, help="DR method (default: from viz_config.yml)")
439
+ parser.add_argument("--max_benign", type=str, default=None,
440
+ help="Max benign nodes or 'all'")
441
+ parser.add_argument("--max_attack", type=str, default=None,
442
+ help="Max attack nodes or 'all'")
443
+ parser.add_argument("--output", type=str, default=None,
444
+ help="Custom output path for the HTML file")
445
+ parser.add_argument("--all_epochs", action="store_true",
446
+ help="Export embeddings for all available training epochs")
447
+ parser.add_argument("--epoch", type=str, default=None,
448
+ help="Export embeddings for a specific epoch only (used for memory-safe per-epoch runs)")
449
+ parser.add_argument("--run", type=str, default=None,
450
+ help="Path to a specific run's eval task dir (or its viz_manifest.json) "
451
+ "in the artifacts folder to export, instead of the latest for the dataset")
452
+
453
+ args, unknown = parser.parse_known_args()
454
+
455
+ # Build pipeline args for get_yml_cfg (positional: model dataset)
456
+ sys.argv = [
457
+ sys.argv[0],
458
+ args.model,
459
+ args.dataset,
460
+ ] + unknown
461
+
462
+ pipeline_args, _ = get_runtime_required_args(return_unknown_args=True)
463
+ cfg = get_yml_cfg(pipeline_args)
464
+
465
+ # If exporting a specific run that saved its config, reconstruct cfg from it
466
+ # so build_model rebuilds the exact trained architecture (the repo defaults
467
+ # may have diverged since the run was trained).
468
+ if getattr(args, "run", None):
469
+ run_dir = args.run[: -len("/viz_manifest.json")] if args.run.endswith(".json") else args.run
470
+ for rc in (os.path.join(run_dir, "run_config.yml"),
471
+ os.path.join(os.path.dirname(run_dir), "run_config.yml")):
472
+ if os.path.exists(rc):
473
+ try:
474
+ with open(rc) as f:
475
+ loaded = CN.load_cfg(f)
476
+ dropped = _prune_unknown_keys(loaded, cfg)
477
+ if dropped:
478
+ log(f"Warning: {rc} has config key(s) no longer in the "
479
+ f"schema (likely trained with an older version); "
480
+ f"dropped and using current defaults for: "
481
+ f"{', '.join(dropped)}")
482
+ cfg.merge_from_other_cfg(loaded)
483
+ log(f"Reconstructed config from run's run_config.yml: {rc}")
484
+ except Exception as e:
485
+ log(f"Warning: could not merge {rc} ({type(e).__name__}: {e}); "
486
+ f"using default '{args.model}' config.")
487
+ break
488
+
489
+ run_visualization(args, cfg)
490
+
491
+
492
+ if __name__ == "__main__":
493
+ main()