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,293 @@
1
+ import json
2
+ import os
3
+ import time
4
+ from concurrent.futures import ThreadPoolExecutor
5
+
6
+ import numpy as np
7
+ import torch
8
+
9
+ from pidsmaker.factory import node_scorer_factory
10
+ from pidsmaker.utils.data_utils import batch_to_device, to_original_node_ids
11
+ from pidsmaker.utils.labelling import has_event_labels
12
+ from pidsmaker.utils.loss_files import write_losses
13
+ from pidsmaker.utils.utils import (
14
+ PeakCPUMemory,
15
+ get_device,
16
+ log,
17
+ log_tqdm,
18
+ ns_time_to_datetime_US,
19
+ set_seed,
20
+ )
21
+
22
+
23
+ class EdgeLossWriter:
24
+ """Writes the edge losses of the batches (one file per batch, see `write_losses`).
25
+
26
+ The columns of the batches stay on the device and are moved to the host every
27
+ `flush_every` batches with a single transfer, and the files are compressed and written
28
+ by threads, instead of a transfer (waiting for the GPU) and a write at each batch.
29
+ The files are the same."""
30
+
31
+ def __init__(self, cfg, logs_dir, flush_every=256, num_threads=4):
32
+ self.cfg = cfg
33
+ self.logs_dir = logs_dir
34
+ self.flush_every = flush_every
35
+ self.pending = []
36
+ self.losses = []
37
+ self.pool = ThreadPoolExecutor(num_threads)
38
+ self.futures = {}
39
+ os.makedirs(logs_dir, exist_ok=True)
40
+
41
+ def add(self, int_cols, losses, y=None):
42
+ """`int_cols`: (4, E) tensor of (src, dst, time, edge type), `losses`: (E,)."""
43
+ self.pending.append((int_cols, losses, y))
44
+ if len(self.pending) >= self.flush_every:
45
+ self.flush()
46
+
47
+ def flush(self):
48
+ if not self.pending:
49
+ return
50
+ sizes = [losses.numel() for _, losses, _ in self.pending]
51
+ int_cols = torch.cat([c for c, _, _ in self.pending], dim=1).cpu().numpy()
52
+ losses = torch.cat([l.float() for _, l, _ in self.pending]).cpu().numpy()
53
+ has_y = self.pending[0][2] is not None
54
+ ys = torch.cat([y for _, _, y in self.pending]).cpu().numpy() if has_y else None
55
+ self.pending = []
56
+
57
+ start = 0
58
+ for size in sizes:
59
+ end = start + size
60
+ srcnodes, dstnodes, t_vars, edge_types = int_cols[:, start:end]
61
+ batch_losses = losses[start:end]
62
+ self.losses.append(batch_losses)
63
+ edge_cols = {
64
+ "loss": batch_losses.astype(float),
65
+ "srcnode": srcnodes.astype(int),
66
+ "dstnode": dstnodes.astype(int),
67
+ "time": t_vars.astype(int),
68
+ "edge_type": edge_types.astype(int),
69
+ }
70
+ if has_y:
71
+ edge_cols["y"] = ys[start:end].astype(int)
72
+ # Here is a checkpoint, which records all edge losses in the current time window
73
+ tz = self.cfg.dataset.timezone
74
+ time_interval = (
75
+ ns_time_to_datetime_US(int(t_vars[0]), timezone=tz)
76
+ + "~"
77
+ + ns_time_to_datetime_US(edge_cols["time"].max(), timezone=tz)
78
+ )
79
+ # Batches with the same time interval write the same file: the last one is kept
80
+ previous = self.futures.get(time_interval)
81
+ if previous is not None:
82
+ previous.result()
83
+ self.futures[time_interval] = self.pool.submit(
84
+ write_losses, self.logs_dir, time_interval, edge_cols
85
+ )
86
+ start = end
87
+
88
+ def close(self):
89
+ """Writes the remaining batches and returns the losses of all the batches."""
90
+ self.flush()
91
+ for f in self.futures.values():
92
+ f.result()
93
+ self.pool.shutdown()
94
+ return self.losses
95
+
96
+
97
+ @torch.no_grad()
98
+ def test_edge_level(
99
+ data,
100
+ model,
101
+ split,
102
+ model_epoch_file,
103
+ cfg,
104
+ device,
105
+ writer=None,
106
+ ):
107
+ model.eval()
108
+
109
+ validation = split == "val"
110
+
111
+ results = model(data, inference=True, validation=validation)
112
+ each_edge_loss = results["loss"]
113
+
114
+ # If the data has been reindexed in the loader or batched, we retrieve original node IDs
115
+ # to later find the labels
116
+ edge_index = to_original_node_ids(data.original_edge_index)
117
+
118
+ edge_types = data.edge_type.max(dim=1).indices + 1
119
+ int_cols = torch.stack(
120
+ [edge_index[0], edge_index[1], data.t.to(edge_index.dtype), edge_types.to(edge_index.dtype)]
121
+ )
122
+ # Datasets with event-level labels: the label of each edge is kept for the evaluation
123
+ y = data.y if has_event_labels(cfg) else None
124
+
125
+ if writer is None:
126
+ logs_dir = os.path.join(cfg.training._edge_losses_dir, split, model_epoch_file)
127
+ writer = EdgeLossWriter(cfg, logs_dir)
128
+ writer.add(int_cols, each_edge_loss, y)
129
+ return writer.close()[0]
130
+ writer.add(int_cols, each_edge_loss, y)
131
+ return None
132
+
133
+
134
+ @torch.no_grad()
135
+ def test_node_level(
136
+ data,
137
+ model,
138
+ split,
139
+ model_epoch_file,
140
+ cfg,
141
+ device,
142
+ scorer,
143
+ ):
144
+ model.eval()
145
+
146
+ start_time = int(data.t[0])
147
+ end_time = int(data.t[-1])
148
+
149
+ validation = split == "val"
150
+
151
+ data = batch_to_device(data, device)
152
+
153
+ results = model(data, inference=True, validation=validation)
154
+ loss = results["loss"]
155
+ losses = loss.float().cpu().numpy()
156
+ n_id = to_original_node_ids(getattr(data, "original_n_id_tgn", getattr(data, "original_n_id")))
157
+ n_id_np = n_id.cpu().numpy()
158
+
159
+ node_list = scorer.columns(model, data, results, split, n_id_np, losses.astype(float))
160
+
161
+ time_interval = (
162
+ ns_time_to_datetime_US(start_time, timezone=cfg.dataset.timezone)
163
+ + "~"
164
+ + ns_time_to_datetime_US(end_time, timezone=cfg.dataset.timezone)
165
+ )
166
+
167
+ logs_dir = os.path.join(cfg.training._edge_losses_dir, split, model_epoch_file)
168
+ os.makedirs(logs_dir, exist_ok=True)
169
+ write_losses(logs_dir, time_interval, node_list)
170
+ return losses
171
+
172
+
173
+ def main(cfg, model, val_data, test_data, epoch, split, logging=True, train_data=None):
174
+ set_seed(cfg)
175
+
176
+ if split == "all":
177
+ splits = [(val_data, "val"), (test_data, "test")]
178
+ elif split == "val":
179
+ splits = [(val_data, "val")]
180
+ elif split == "test":
181
+ splits = [(test_data, "test")]
182
+ elif split == "train":
183
+ splits = [(train_data, "train")]
184
+ else:
185
+ raise ValueError(f"Invalid split {split}")
186
+
187
+ inference_device = cfg.training.inference_device
188
+ if inference_device is not None:
189
+ if inference_device not in ["cpu", "cuda"]:
190
+ raise ValueError(f"Invalid inference device {inference_device}")
191
+ device = torch.device(inference_device)
192
+ else:
193
+ device = get_device(cfg)
194
+ use_cuda = device == torch.device("cuda")
195
+ model.to_device(device)
196
+
197
+ model_epoch_file = f"model_epoch_{epoch}"
198
+ if use_cuda:
199
+ torch.cuda.reset_peak_memory_stats(device=device)
200
+
201
+ scorer = node_scorer_factory(cfg)
202
+ scorer.prepare(model, train_data, [name for _, name in splits], device)
203
+
204
+ val_score = 0.0
205
+ peak_inference_cpu_mem = 0
206
+ peak_inference_gpu_mem = 0
207
+ tpb = []
208
+ split2loss = {}
209
+
210
+ for dataset, split_name in splits:
211
+ desc = "Validation" if split_name == "val" else "Testing"
212
+
213
+ cpu_mem = PeakCPUMemory().start()
214
+
215
+ all_losses = []
216
+ is_node_level = cfg._is_node_level and not cfg._is_hybrid_loss
217
+ writer = None
218
+ if not is_node_level:
219
+ writer = EdgeLossWriter(
220
+ cfg, os.path.join(cfg.training._edge_losses_dir, split_name, model_epoch_file)
221
+ )
222
+ for graphs in dataset:
223
+ for g in log_tqdm(graphs, desc=desc, logging=logging):
224
+ g = batch_to_device(g, device)
225
+
226
+ s = time.time()
227
+ if is_node_level:
228
+ losses = test_node_level(
229
+ data=g,
230
+ model=model,
231
+ split=split_name,
232
+ model_epoch_file=model_epoch_file,
233
+ cfg=cfg,
234
+ device=device,
235
+ scorer=scorer,
236
+ )
237
+ all_losses.append(np.asarray(losses, dtype=np.float64).ravel())
238
+ else:
239
+ test_edge_level(
240
+ data=g,
241
+ model=model,
242
+ split=split_name,
243
+ model_epoch_file=model_epoch_file,
244
+ cfg=cfg,
245
+ device=device,
246
+ writer=writer,
247
+ )
248
+ tpb.append(time.time() - s)
249
+ del g
250
+ if writer is not None:
251
+ all_losses += [np.asarray(l, dtype=np.float64).ravel() for l in writer.close()]
252
+
253
+ peak_inference_cpu_mem = max(peak_inference_cpu_mem, cpu_mem.peak_gb())
254
+
255
+ if use_cuda:
256
+ peak_inference_gpu_memory = torch.cuda.max_memory_allocated(device=device) / (1024**3)
257
+ peak_inference_gpu_mem = max(peak_inference_gpu_mem, peak_inference_gpu_memory)
258
+ torch.cuda.reset_peak_memory_stats(device=device)
259
+
260
+ mean_loss = np.mean(np.concatenate(all_losses)) if all_losses else np.nan
261
+ split2loss[split_name] = mean_loss
262
+
263
+ if split_name == "val":
264
+ val_score = model.get_val_ap()
265
+ # Read by the evaluation to select the best epoch on validation data
266
+ # (`best_model_selection: best_val_score`)
267
+ val_scores_dir = os.path.join(cfg.training._edge_losses_dir, "val_scores")
268
+ os.makedirs(val_scores_dir, exist_ok=True)
269
+ with open(os.path.join(val_scores_dir, f"{model_epoch_file}.json"), "w") as f:
270
+ json.dump({"val_score": float(val_score)}, f)
271
+ if logging:
272
+ log(
273
+ f"[@epoch{epoch:02d}] Validation finished - Val Loss: {mean_loss:.4f}",
274
+ return_line=True,
275
+ )
276
+ else:
277
+ if logging:
278
+ log(
279
+ f"[@epoch{epoch:02d}] Test finished - Test Loss: {mean_loss:.4f}",
280
+ return_line=True,
281
+ )
282
+
283
+ del model
284
+
285
+ stats = {
286
+ "val_score": val_score,
287
+ "val_loss": split2loss.get("val", None),
288
+ "test_loss": split2loss.get("test", None),
289
+ "peak_inference_cpu_memory": peak_inference_cpu_mem,
290
+ "peak_inference_gpu_memory": peak_inference_gpu_mem,
291
+ "time_per_batch_inference": np.mean(tpb),
292
+ }
293
+ return stats
@@ -0,0 +1,165 @@
1
+ import os
2
+
3
+ import numpy as np
4
+ import pandas as pd
5
+ from sklearn.metrics import f1_score, roc_auc_score
6
+
7
+ from pidsmaker.utils.dataset_utils import get_node_map
8
+ from pidsmaker.utils.labelling import get_ground_truth
9
+ from pidsmaker.utils.dataset_utils import get_node_to_path_and_type
10
+ from pidsmaker.utils.loss_files import is_loss_file, read_losses
11
+ from pidsmaker.utils.utils import listdir_sorted, log
12
+
13
+ from . import inference_loop
14
+
15
+
16
+ class OCRAPTEarlyStop:
17
+ """Per-node-type validation early stopping (arXiv:2510.15188 Sec 5.1.2): F1-based if a
18
+ type's validation set has >5% malicious nodes, AUC-based if some are present, else TNR-based.
19
+ Once a type plateaus, its encoder/objective sub-module is frozen for the rest of training.
20
+ """
21
+
22
+ def __init__(self, num_node_types, patience=5, min_delta=0.01, max_delta=0.2):
23
+ self.num_node_types = num_node_types
24
+ self.patience = patience
25
+ self.max_delta = max_delta
26
+ self._first_epoch = [True] * num_node_types
27
+ self._malicious_pct = [0.0] * num_node_types
28
+ self._f1_baseline = [0.0] * num_node_types
29
+ self._max_f1 = [0.0] * num_node_types
30
+ self._max_auc = [0.0] * num_node_types
31
+ self._max_tnr = [0.0] * num_node_types
32
+ self._counter = [0] * num_node_types
33
+ self._stopped = [False] * num_node_types
34
+
35
+ def _update_one_type(self, nt, scores, labels, thr):
36
+ if self._stopped[nt] or len(scores) == 0:
37
+ return
38
+
39
+ if self._first_epoch[nt]:
40
+ self._malicious_pct[nt] = float(labels.mean())
41
+ self._f1_baseline[nt] = (self._malicious_pct[nt] * 2) / (self._malicious_pct[nt] + 1)
42
+ self._first_epoch[nt] = False
43
+
44
+ pred = (scores > thr).astype(int)
45
+ f1 = f1_score(labels, pred, zero_division=0)
46
+ auc = roc_auc_score(labels, scores) if labels.sum() > 0 else None
47
+ tn = int(((pred == 0) & (labels == 0)).sum())
48
+ fp = int(((pred == 1) & (labels == 0)).sum())
49
+ tnr = tn / (tn + fp) if (tn + fp) > 0 else None
50
+
51
+ max_delta = self.max_delta
52
+ if self._malicious_pct[nt] > 0.05:
53
+ if f1 > self._max_f1[nt]:
54
+ self._max_f1[nt] = f1
55
+ self._counter[nt] = 0
56
+ elif (f1 < self._f1_baseline[nt]) or (f1 < self._max_f1[nt] - max_delta):
57
+ self._counter[nt] = 0
58
+ elif f1 <= self._max_f1[nt]:
59
+ self._counter[nt] += 1
60
+ if self._counter[nt] >= self.patience:
61
+ self._stopped[nt] = True
62
+ elif self._malicious_pct[nt] > 0:
63
+ if auc is None:
64
+ return
65
+ if auc > self._max_auc[nt]:
66
+ self._max_auc[nt] = auc
67
+ self._counter[nt] = 0
68
+ elif (auc <= 0.5) or (auc < self._max_auc[nt] - max_delta):
69
+ self._counter[nt] = 0
70
+ elif auc <= self._max_auc[nt]:
71
+ self._counter[nt] += 1
72
+ if self._counter[nt] >= self.patience:
73
+ self._stopped[nt] = True
74
+ else:
75
+ if tnr is None:
76
+ return
77
+ if tnr > self._max_tnr[nt]:
78
+ self._max_tnr[nt] = tnr
79
+ self._counter[nt] = 0
80
+ elif (tnr <= 0.01) or (tnr < self._max_tnr[nt] - max_delta):
81
+ self._counter[nt] = 0
82
+ elif tnr <= self._max_tnr[nt]:
83
+ self._counter[nt] += 1
84
+ if self._counter[nt] >= self.patience:
85
+ self._stopped[nt] = True
86
+
87
+ def _scores_by_type(self, edge_losses_dir, split, epoch, node_to_type, type_to_idx, gt_nids):
88
+ d = os.path.join(edge_losses_dir, split, f"model_epoch_{epoch}")
89
+ if not os.path.isdir(d):
90
+ return None
91
+ dfs = [read_losses(os.path.join(d, f)) for f in listdir_sorted(d) if is_loss_file(f)]
92
+ if not dfs:
93
+ return None
94
+ node_score = pd.concat(dfs, ignore_index=True).groupby("node")["loss"].max()
95
+
96
+ scores_by_type = [[] for _ in range(self.num_node_types)]
97
+ labels_by_type = [[] for _ in range(self.num_node_types)]
98
+ for nid, score in node_score.items():
99
+ nt = type_to_idx.get(node_to_type.get(int(nid)))
100
+ if nt is None:
101
+ continue
102
+ scores_by_type[nt].append(score)
103
+ labels_by_type[nt].append(int(int(nid) in gt_nids))
104
+ return scores_by_type, labels_by_type
105
+
106
+ def check(self, cfg, epoch, min_contamination=0.001, max_contamination=0.05):
107
+ gt_nids, _, _ = get_ground_truth(cfg)
108
+ gt_nids = set(int(n) for n in gt_nids)
109
+ node_to_type = {nid: info["type"] for nid, info in get_node_to_path_and_type(cfg).items()}
110
+ # must match the type index the model itself uses (node_type_argmax), not an
111
+ # independent ordering, otherwise freeze_type() would freeze the wrong type.
112
+ type_to_idx = {t: i for t, i in get_node_map(cfg, from_zero=True).items() if isinstance(t, str)}
113
+
114
+ # threshold from train scores (calibration), evaluated against val labels
115
+ train = self._scores_by_type(cfg.training._edge_losses_dir, "train", epoch, node_to_type, type_to_idx, gt_nids)
116
+ val = self._scores_by_type(cfg.training._edge_losses_dir, "val", epoch, node_to_type, type_to_idx, gt_nids)
117
+ if train is None or val is None:
118
+ return False
119
+ train_scores_by_type, _ = train
120
+ val_scores_by_type, val_labels_by_type = val
121
+
122
+ for nt in range(self.num_node_types):
123
+ train_scores = np.asarray(train_scores_by_type[nt], dtype=np.float64)
124
+ val_scores = np.asarray(val_scores_by_type[nt], dtype=np.float64)
125
+ val_labels = np.asarray(val_labels_by_type[nt], dtype=np.int64)
126
+ if len(train_scores) == 0 or len(val_scores) == 0:
127
+ continue
128
+ # same per-type contamination as the final detection threshold
129
+ # (data_statistics_contamination): val malicious fraction, clamped.
130
+ contamination = min(max(float(val_labels.mean()), min_contamination), max_contamination)
131
+ thr = float(np.percentile(train_scores, 100 * (1 - contamination)))
132
+ self._update_one_type(nt, val_scores, val_labels, thr)
133
+
134
+ all_stopped = all(self._stopped)
135
+ if all_stopped:
136
+ log(f"OCR-APT validation early stop triggered at epoch {epoch}")
137
+ return all_stopped
138
+
139
+ def after_eval_epoch(self, cfg, model, train_data, epoch):
140
+ """Call once per evaluated epoch. Computes this epoch's per-type validation stats,
141
+ freezes the sub-modules of any type that has plateaued, and returns whether every
142
+ type has stopped (i.e. training can end).
143
+ """
144
+ inference_loop.main(
145
+ cfg=cfg, model=model, val_data=None, test_data=None,
146
+ train_data=train_data, epoch=epoch, split="train", logging=False,
147
+ )
148
+ all_stopped = self.check(
149
+ cfg, epoch,
150
+ min_contamination=cfg.evaluation.node_evaluation.ocrapt_min_contamination,
151
+ max_contamination=cfg.evaluation.node_evaluation.ocrapt_contamination,
152
+ )
153
+ for nt in range(self.num_node_types):
154
+ if self._stopped[nt]:
155
+ self._freeze_type(model, nt)
156
+ return all_stopped
157
+
158
+ @staticmethod
159
+ def _freeze_type(model, nt):
160
+ if hasattr(model.encoder, "freeze_type"):
161
+ model.encoder.freeze_type(nt)
162
+ for obj in model.objectives:
163
+ inner = getattr(obj, "objective", obj) # unwrap ValidationWrapper
164
+ if hasattr(inner, "freeze_type"):
165
+ inner.freeze_type(nt)
@@ -0,0 +1,169 @@
1
+ """ThreaTrace's multi-model training (Wang et al., TIFS 2022, `train_darpatc.py`).
2
+
3
+ A first GraphSAGE node-type classifier is trained on all the training nodes. Then, in rounds:
4
+ the nodes the current model explains (type predicted with a top-1 / top-2 probability ratio of
5
+ at least `ratio_threshold`) are removed from the training set and the model is saved as a
6
+ submodel; the model then keeps training on the remaining nodes only, until its mean loss is
7
+ below `retrain_loss_threshold`. Training stops when all nodes are explained, or after
8
+ `max_rounds_without_progress` consecutive rounds that explain no new node.
9
+
10
+ At inference, a node is anomalous when no submodel explains it (see
11
+ `threatrace_detection.threatrace_anomaly_score`).
12
+
13
+ Training nodes are the (time window, node) pairs of the training graphs.
14
+ """
15
+
16
+ import copy
17
+ from time import perf_counter as timer
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+
22
+ from pidsmaker.detection.threatrace_detection import threatrace_log_ratio
23
+ from pidsmaker.factory import build_model, optimizer_factory
24
+ from pidsmaker.objectives.predict_node_type import NODE_LOSS_MASK_KEY
25
+ from pidsmaker.tasks.batching import get_preprocessed_graphs
26
+ from pidsmaker.utils.utils import PeakCPUMemory, get_device, log, log_start, log_tqdm, set_seed
27
+
28
+ from . import inference_loop
29
+ from .training_loop import to_device_without_attacks
30
+
31
+
32
+ class ThreaTraceEnsemble(nn.Module):
33
+ """Runs the model with the weights of each submodel. Returns the outputs of all the
34
+ submodels in `outs` (the other results are those of the first submodel)."""
35
+
36
+ def __init__(self, model, state_dicts):
37
+ super().__init__()
38
+ self.model = model
39
+ self.state_dicts = state_dicts
40
+
41
+ def forward(self, batch, inference=False, validation=False):
42
+ results, outs = None, []
43
+ for state_dict in self.state_dicts:
44
+ self.model.load_state_dict(state_dict)
45
+ res = self.model(batch, inference=inference, validation=validation)
46
+ outs.append(res["out"])
47
+ results = results or res
48
+ results["outs"] = outs
49
+ return results
50
+
51
+ def get_val_ap(self):
52
+ return self.model.get_val_ap()
53
+
54
+ def to_device(self, device):
55
+ self.model.to_device(device)
56
+ self.state_dicts = [{k: v.to(device) for k, v in sd.items()} for sd in self.state_dicts]
57
+ return self
58
+
59
+
60
+ def train_epoch(model, optimizer, graphs, masks, cfg, device):
61
+ """One epoch on the graphs with nodes left to explain. Returns the mean loss per node."""
62
+ model.train()
63
+ tot_loss, tot_nodes = 0.0, 0
64
+ for g, mask in log_tqdm(list(zip(graphs, masks)), "Training"):
65
+ num_nodes = int(mask.sum())
66
+ if num_nodes == 0:
67
+ continue
68
+ g = to_device_without_attacks(g, cfg, device)
69
+ setattr(g, NODE_LOSS_MASK_KEY, mask.to(device))
70
+ optimizer.zero_grad()
71
+ loss = model(g)["loss"]
72
+ loss.backward()
73
+ optimizer.step()
74
+ tot_loss += loss.item() * num_nodes
75
+ tot_nodes += num_nodes
76
+ return tot_loss / max(tot_nodes, 1)
77
+
78
+
79
+ @torch.no_grad()
80
+ def explained_nodes(model, graphs, masks, cfg, device):
81
+ """For each graph, the nodes still to explain that the model explains."""
82
+ model.eval()
83
+ log_thr = torch.log(torch.tensor(cfg.training.threatrace.ratio_threshold)).item()
84
+ explained = []
85
+ for g, mask in zip(graphs, masks):
86
+ if not mask.any():
87
+ explained.append(torch.zeros_like(mask))
88
+ continue
89
+ g = to_device_without_attacks(g, cfg, device)
90
+ out = model(g, inference=True)["out"]
91
+ log_ratio = threatrace_log_ratio(out, g.node_type.argmax(1))
92
+ explained.append((log_ratio >= log_thr).cpu() & mask)
93
+ return explained
94
+
95
+
96
+ def train_submodels(model, optimizer, graphs, cfg, device):
97
+ """Trains the successive submodels. Returns their state dicts."""
98
+ tt_cfg = cfg.training.threatrace
99
+ masks = [torch.ones(g.node_type.shape[0], dtype=torch.bool) for g in graphs]
100
+ total = sum(int(m.sum()) for m in masks)
101
+
102
+ for epoch in range(cfg.training.num_epochs):
103
+ loss = train_epoch(model, optimizer, graphs, masks, cfg, device)
104
+ log(f"[submodel 0 | epoch {epoch:02d}] Mean loss: {loss:.4f}")
105
+
106
+ submodels, rounds_without_progress = [], 0
107
+ while len(submodels) < tt_cfg.max_submodels:
108
+ explained = explained_nodes(model, graphs, masks, cfg, device)
109
+ num_explained = sum(int(e.sum()) for e in explained)
110
+ masks = [m & ~e for m, e in zip(masks, explained)]
111
+ num_left = sum(int(m.sum()) for m in masks)
112
+ log(
113
+ f"Submodel {len(submodels)}: explains {num_explained} nodes, "
114
+ f"{num_left}/{total} training nodes left"
115
+ )
116
+
117
+ rounds_without_progress = 0 if num_explained > 0 else rounds_without_progress + 1
118
+ if rounds_without_progress >= tt_cfg.max_rounds_without_progress:
119
+ break
120
+ if num_explained > 0:
121
+ submodels.append(copy.deepcopy({k: v.detach().cpu() for k, v in model.state_dict().items()}))
122
+ if num_left == 0 or len(submodels) >= tt_cfg.max_submodels:
123
+ break
124
+
125
+ for epoch in range(tt_cfg.max_retrain_epochs):
126
+ loss = train_epoch(model, optimizer, graphs, masks, cfg, device)
127
+ log(f"[submodel {len(submodels)} | epoch {epoch:02d}] Mean loss on nodes left: {loss:.4f}")
128
+ if loss < tt_cfg.retrain_loss_threshold:
129
+ break
130
+
131
+ if not submodels: # no node explained at all: keep the last model
132
+ submodels.append(copy.deepcopy({k: v.detach().cpu() for k, v in model.state_dict().items()}))
133
+ log(f"Trained {len(submodels)} submodels")
134
+ return submodels
135
+
136
+
137
+ def main(cfg):
138
+ log_start(__file__)
139
+ device = get_device(cfg)
140
+ use_cuda = device == torch.device("cuda")
141
+ if use_cuda:
142
+ torch.cuda.reset_peak_memory_stats(device=device)
143
+ cpu_mem = PeakCPUMemory().start()
144
+
145
+ train_data, val_data, test_data, max_node_num = get_preprocessed_graphs(cfg)
146
+ log("Graph data loaded.")
147
+ set_seed(cfg, seed=cfg.training.seed)
148
+
149
+ model = build_model(
150
+ data_sample=train_data[0][0], device=device, cfg=cfg, max_node_num=max_node_num,
151
+ all_data=(val_data, test_data),
152
+ )
153
+ optimizer = optimizer_factory(cfg, parameters=set(model.parameters()))
154
+ graphs = [g for dataset in train_data for g in dataset]
155
+
156
+ start = timer()
157
+ submodels = train_submodels(model, optimizer, graphs, cfg, device)
158
+ gpu_mem = torch.cuda.max_memory_allocated(device=device) / (1024**3) if use_cuda else 0.0
159
+ log(
160
+ f"Training finished in {timer() - start:.1f}s - GPU memory: {gpu_mem:.2f} GB | "
161
+ f"CPU memory: {cpu_mem.peak_gb():.2f} GB"
162
+ )
163
+
164
+ # The evaluation selects among the evaluated epochs: only the final ensemble is evaluated
165
+ ensemble = ThreaTraceEnsemble(model, submodels)
166
+ test_stats = inference_loop.main(
167
+ cfg=cfg, model=ensemble, val_data=val_data, test_data=test_data, epoch=0, split="all",
168
+ )
169
+ return test_stats["val_score"]