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,438 @@
1
+ """GNN Distillation pretraining branch for SPIDER."""
2
+
3
+ import os
4
+ import random
5
+ import time
6
+ from collections import defaultdict
7
+
8
+ import torch
9
+ from torch.optim import AdamW
10
+
11
+ import wandb
12
+
13
+ from pidsmaker.utils.utils import log
14
+ from ..training_utils import WarmupCosineScheduler, pad_token_id_lists, update_ema
15
+ from ..data.tokenizer_bpe import ProvenanceTokenizerBPE as ProvenanceTokenizer
16
+ from .pretrain_common import _eval_knn_on_eval_set, _dump_gnn_distill_corpus_to_txt
17
+
18
+
19
+ def pretrain_gnn_distill(cfg, spider_cfg, sampler_pairs, combined_indexid2msg, out_dir, device,
20
+ model_size, max_seq_len, bpe_vocab_size, tokenizer_mode,
21
+ normalize_netflow_ips, canonicalize_neighbors, spider_path,
22
+ total_tokens, warmup_tokens, batch_size, lr):
23
+ from copy import deepcopy
24
+ from ..models.gnn_distill import (
25
+ ProvenanceGNNDistill, NeighborhoodGNNTeacher,
26
+ build_gnn_distill_batch, build_edge_type_encoder,
27
+ get_gnn_distill_encoder_config,
28
+ )
29
+ from ..models.graphmae import sce_loss
30
+
31
+ distill_cfg = spider_cfg.gnn_distill
32
+ gnn_edge_emb_dim = distill_cfg.emb_dim
33
+ gnn_hidden_dim = distill_cfg.hidden_dim
34
+ gnn_num_layers = distill_cfg.num_layers
35
+ gnn_num_heads = distill_cfg.num_heads
36
+ gnn_n_neighbors_min = distill_cfg.n_neighbors_min
37
+ gnn_n_neighbors_max = distill_cfg.n_neighbors_max
38
+ gnn_diverse_neighbors = distill_cfg.diverse_neighbors
39
+ distill_lambda = distill_cfg.loss_weight
40
+ gnn_loss_lambda = distill_cfg.gnn_loss_weight
41
+ gnn_lr = distill_cfg.gnn_lr
42
+ ema_momentum = distill_cfg.ema_momentum
43
+
44
+ # ── Build or load tokenizer ────────────────────────────────────
45
+ if spider_path:
46
+ tok_path = os.path.join(spider_path, "tokenizer.pt")
47
+ log(f"Loading tokenizer from {tok_path}")
48
+ tokenizer = ProvenanceTokenizer(cfg)
49
+ tokenizer.load(tok_path)
50
+ tokenizer.max_seq_len = max_seq_len
51
+ log(f" Overriding max_seq_len to {max_seq_len} (from config)")
52
+ else:
53
+ walk_label_corpus = []
54
+ for sampler, ds_indexid2msg in sampler_pairs:
55
+ for node in sampler.nodes:
56
+ if node in ds_indexid2msg:
57
+ walk_label_corpus.append(ds_indexid2msg[node])
58
+ log(f"GNN distill: {len(walk_label_corpus):,} entity labels for tokenizer")
59
+
60
+ tokenizer = ProvenanceTokenizer(cfg, max_seq_len=max_seq_len, bpe_vocab_size=bpe_vocab_size, mode=tokenizer_mode,
61
+ normalize_netflow_ips=normalize_netflow_ips,
62
+ canonicalize_neighbors=canonicalize_neighbors)
63
+ tokenizer.build_vocab(combined_indexid2msg, walk_label_corpus=walk_label_corpus)
64
+ log(f"Vocabulary size: {tokenizer.vocab_size}")
65
+ tokenizer.save(os.path.join(out_dir, "tokenizer.pt"))
66
+
67
+ # ── Build edge type encoder for GNN ───────────────────────────
68
+ gnn_edge_type2idx = build_edge_type_encoder(sampler_pairs)
69
+ log(f"GNN distill: {len(gnn_edge_type2idx)} directed edge types")
70
+
71
+ # ── Build models ──────────────────────────────────────────────
72
+ enc_config = get_gnn_distill_encoder_config(tokenizer.vocab_size, model_size, max_seq_len)
73
+ t5_hidden_dim = enc_config.d_model # H dimension of T5 encoder
74
+ model = ProvenanceGNNDistill(enc_config, gnn_hidden_dim).to(device)
75
+ log(f"Model: GNNDistill-{model_size} (T5 encoder H={t5_hidden_dim} → {gnn_hidden_dim}d GNN space)")
76
+ log(f" Student params: {sum(p.numel() for p in model.parameters()):,}")
77
+
78
+ # EMA teacher: a slow-moving copy of the student T5 encoder
79
+ ema_teacher = deepcopy(model).to(device)
80
+ ema_teacher.requires_grad_(False)
81
+ ema_teacher.eval()
82
+ log(f" EMA teacher: copy of student (momentum={ema_momentum})")
83
+
84
+ gnn_filter_noisy = distill_cfg.filter_noisy_edges
85
+ if gnn_filter_noisy:
86
+ log("GNN distill: edge noise filtering ENABLED")
87
+ gnn_edge_projection = distill_cfg.edge_projection
88
+ gnn_teacher = NeighborhoodGNNTeacher(
89
+ node_dim=t5_hidden_dim,
90
+ num_edge_types=max(len(gnn_edge_type2idx), 1),
91
+ edge_emb_dim=gnn_edge_emb_dim,
92
+ hidden_dim=gnn_hidden_dim,
93
+ num_layers=gnn_num_layers,
94
+ num_heads=gnn_num_heads,
95
+ edge_projection=gnn_edge_projection,
96
+ ).to(device)
97
+ log(f" GNN teacher params: {sum(p.numel() for p in gnn_teacher.parameters()):,}")
98
+ log(f" n_neighbors=[{gnn_n_neighbors_min}, {gnn_n_neighbors_max}], "
99
+ f"distill_weight={distill_lambda}, gnn_weight={gnn_loss_lambda}")
100
+
101
+ # ── Optimizer ─────────────────────────────────────────────────
102
+ opt = AdamW([
103
+ {"params": model.parameters(), "lr": lr},
104
+ {"params": gnn_teacher.parameters(), "lr": gnn_lr},
105
+ ], betas=(0.9, 0.95), eps=1e-8, weight_decay=0.1)
106
+
107
+ # ── Collect all trainable entities, grouped by label ──────────
108
+ if gnn_filter_noisy:
109
+ from ..data.edge_filter import _is_noisy_file, _is_noisy_process
110
+ n_skipped_centers = 0
111
+ label_to_entities = defaultdict(list)
112
+ for sidx, (sampler, ds_indexid2msg) in enumerate(sampler_pairs):
113
+ for node in sampler.nodes:
114
+ if node in ds_indexid2msg:
115
+ ntype, nlabel = ds_indexid2msg[node]
116
+ # Skip noisy center entities
117
+ if gnn_filter_noisy:
118
+ if ntype == "file" and _is_noisy_file(nlabel):
119
+ n_skipped_centers += 1
120
+ continue
121
+ if ntype == "subject" and _is_noisy_process(nlabel):
122
+ n_skipped_centers += 1
123
+ continue
124
+ entity_ids = tokenizer.tokenize_node(ntype, nlabel)
125
+ if entity_ids:
126
+ label_key = (ntype, nlabel)
127
+ label_to_entities[label_key].append((node, sidx, entity_ids))
128
+ n_total = sum(len(v) for v in label_to_entities.values())
129
+ skip_msg = f", skipped {n_skipped_centers:,} noisy centers" if n_skipped_centers else ""
130
+ log(f"GNN distill: {n_total:,} trainable entities, "
131
+ f"{len(label_to_entities):,} unique labels across {len(sampler_pairs)} graph(s){skip_msg}")
132
+
133
+ # ── Dump neighborhood corpus for analysis ─────────────────
134
+ _dump_gnn_distill_corpus_to_txt(
135
+ sampler_pairs, combined_indexid2msg, out_dir,
136
+ filter_noisy=gnn_filter_noisy,
137
+ )
138
+
139
+ # ── Split into train/val (2% of unique labels) ───────────
140
+ total_labels = len(label_to_entities)
141
+ n_val_target = max(1, int(total_labels * 0.02))
142
+ # Distribute proportionally across datasets
143
+ val_labels = set()
144
+ all_labels_shuffled = list(label_to_entities.keys())
145
+ random.shuffle(all_labels_shuffled)
146
+ for lk in all_labels_shuffled[:n_val_target]:
147
+ val_labels.add(lk)
148
+
149
+ train_label_to_entities = defaultdict(list)
150
+ val_label_to_entities = defaultdict(list)
151
+ for label_key, entities in label_to_entities.items():
152
+ if label_key in val_labels:
153
+ val_label_to_entities[label_key] = entities
154
+ else:
155
+ train_label_to_entities[label_key] = entities
156
+
157
+ n_train_labels = len(train_label_to_entities)
158
+ n_val_labels = len(val_label_to_entities)
159
+ log(f"GNN distill: {n_train_labels:,} train / {n_val_labels:,} val unique labels "
160
+ f"(2% held out for validation)")
161
+
162
+ scheduler = WarmupCosineScheduler(opt, warmup_tokens, total_tokens)
163
+
164
+ # ── Precompute fixed val neighborhoods (for consistent eval) ──
165
+ val_batches_fixed = []
166
+ if val_label_to_entities:
167
+ val_entities = []
168
+ for label_key, entities in val_label_to_entities.items():
169
+ val_entities.append(entities[0]) # always first node
170
+
171
+ for vb_start in range(0, len(val_entities), batch_size):
172
+ vb_ents = val_entities[vb_start:vb_start + batch_size]
173
+ vB = len(vb_ents)
174
+ if vB == 0:
175
+ continue
176
+
177
+ # Pad encoder inputs
178
+ v_enc_ids = [ent[2] for ent in vb_ents]
179
+ v_input_ids, v_attn_mask = pad_token_id_lists(v_enc_ids, tokenizer.pad_id, tokenizer.max_seq_len)
180
+
181
+ # Build GNN neighborhood batch (fixed neighborhoods)
182
+ v_entity_nodes = [ent[0] for ent in vb_ents]
183
+ v_sampler_idxs = [ent[1] for ent in vb_ents]
184
+
185
+ v_gnn_batch = build_gnn_distill_batch(
186
+ v_entity_nodes, v_sampler_idxs, sampler_pairs,
187
+ combined_indexid2msg, gnn_edge_type2idx,
188
+ n_neighbors_min=gnn_n_neighbors_min, n_neighbors_max=gnn_n_neighbors_max,
189
+ diverse=gnn_diverse_neighbors, device=device,
190
+ filter_noisy=gnn_filter_noisy,
191
+ )
192
+ if v_gnn_batch is None:
193
+ continue
194
+
195
+ v_node_labels, v_edge_index, v_edge_types, v_batch_vec, v_center_idx, v_valid_mask = v_gnn_batch
196
+ if v_valid_mask.sum().item() == 0:
197
+ continue
198
+
199
+ val_batches_fixed.append((
200
+ v_input_ids, v_attn_mask, v_node_labels,
201
+ v_edge_index, v_edge_types, v_batch_vec,
202
+ v_center_idx, v_valid_mask,
203
+ ))
204
+ log(f"Precomputed {len(val_batches_fixed)} fixed val batches")
205
+
206
+ # ── Training loop ─────────────────────────────────────────────
207
+ processed_tokens = 0
208
+ updates = 0
209
+ epoch = 0
210
+ best_knn_acc = -1.0
211
+
212
+ log_path = os.path.join(out_dir, f"gnn_distill_log_{model_size}.txt")
213
+ with open(log_path, "w") as f:
214
+ f.write("update,tokens,distill_loss,gnn_loss,lr,time\n")
215
+
216
+ # EMA embedding cache: refreshed every N steps since EMA changes slowly
217
+ ema_cache = {} # label → embedding tensor (detached, on device)
218
+ ema_cache_refresh_interval = 50 # refresh every 50 updates
219
+ ema_cache_last_refresh = -ema_cache_refresh_interval # force first refresh
220
+
221
+ while processed_tokens < total_tokens:
222
+ epoch += 1
223
+ epoch_st = time.time()
224
+ epoch_d_loss = 0.0
225
+ epoch_g_loss = 0.0
226
+ epoch_batches = 0
227
+
228
+ # Pick one node per label, rotating across epochs
229
+ epoch_entities = []
230
+ for label_key, entities in train_label_to_entities.items():
231
+ pick = entities[(epoch - 1) % len(entities)]
232
+ epoch_entities.append(pick)
233
+ random.shuffle(epoch_entities)
234
+
235
+ for batch_start in range(0, len(epoch_entities), batch_size):
236
+ batch_ents = epoch_entities[batch_start:batch_start + batch_size]
237
+ B = len(batch_ents)
238
+ if B == 0:
239
+ continue
240
+
241
+ # ── Pad encoder inputs for student (center entity tokens) ──
242
+ enc_ids_list = [ent[2] for ent in batch_ents]
243
+ input_ids, attention_mask = pad_token_id_lists(enc_ids_list, tokenizer.pad_id, tokenizer.max_seq_len)
244
+
245
+ # ── Build GNN neighborhood batch ──────────────────────
246
+ entity_nodes = [ent[0] for ent in batch_ents]
247
+ sampler_idxs = [ent[1] for ent in batch_ents]
248
+
249
+ gnn_batch = build_gnn_distill_batch(
250
+ entity_nodes, sampler_idxs, sampler_pairs,
251
+ combined_indexid2msg, gnn_edge_type2idx,
252
+ n_neighbors_min=gnn_n_neighbors_min, n_neighbors_max=gnn_n_neighbors_max,
253
+ diverse=gnn_diverse_neighbors, device=device,
254
+ filter_noisy=gnn_filter_noisy,
255
+ )
256
+ if gnn_batch is None:
257
+ continue
258
+
259
+ node_labels, edge_index, edge_types, batch_vec, center_idx, valid_mask = gnn_batch
260
+ n_valid = valid_mask.sum().item()
261
+ if n_valid == 0:
262
+ continue
263
+
264
+ # ── Encode neighbor nodes with EMA teacher (cached) ────
265
+ # Refresh cache periodically since EMA changes slowly
266
+ need_refresh = (updates - ema_cache_last_refresh) >= ema_cache_refresh_interval
267
+ uncached_labels = [lbl for lbl in set(node_labels) if lbl not in ema_cache]
268
+
269
+ if need_refresh:
270
+ # Full refresh: re-encode all labels seen so far
271
+ all_labels_to_encode = list(set(node_labels))
272
+ ema_cache_last_refresh = updates
273
+ elif uncached_labels:
274
+ # Only encode new labels not yet in cache
275
+ all_labels_to_encode = uncached_labels
276
+ else:
277
+ all_labels_to_encode = []
278
+
279
+ if all_labels_to_encode:
280
+ ema_token_ids = []
281
+ for ntype, nlabel in all_labels_to_encode:
282
+ tids = tokenizer.tokenize_node(ntype, nlabel)
283
+ ema_token_ids.append(tids if tids else [tokenizer.pad_id])
284
+
285
+ ema_input_ids, ema_attn_mask = pad_token_id_lists(ema_token_ids, tokenizer.pad_id, tokenizer.max_seq_len)
286
+
287
+ ema_teacher.eval()
288
+ with torch.no_grad():
289
+ ema_embeddings = ema_teacher.mean_pool(ema_input_ids, ema_attn_mask)
290
+
291
+ for i, lbl in enumerate(all_labels_to_encode):
292
+ ema_cache[lbl] = ema_embeddings[i]
293
+
294
+ # Assemble node embeddings from cache
295
+ node_embeddings = torch.stack([ema_cache[lbl] for lbl in node_labels]) # [N, d_model]
296
+
297
+ # ── Forward passes ────────────────────────────────────
298
+ model.train()
299
+ gnn_teacher.train()
300
+
301
+ # Student: T5 encoder → mean-pool → project to GNN space
302
+ out = model.modified_fwd(input_ids.to(device), attention_mask.to(device))
303
+ t5_projected = out.projected # [B, gnn_hidden_dim]
304
+
305
+ # GNN teacher: mask center nodes, encode, reconstruct EMA embeddings
306
+ gnn_recon_loss, gnn_encoded = gnn_teacher(
307
+ node_embeddings, edge_index, edge_types, batch_vec, center_idx,
308
+ )
309
+
310
+ # Extract center node embeddings with STOP GRADIENT
311
+ gnn_targets = gnn_encoded[center_idx].detach()
312
+
313
+ # Distillation loss (SCE) on valid entities only
314
+ distill_loss = sce_loss(t5_projected[valid_mask], gnn_targets)
315
+
316
+ # Combined loss
317
+ total_loss = distill_lambda * distill_loss + gnn_loss_lambda * gnn_recon_loss
318
+
319
+ total_loss.backward()
320
+ torch.nn.utils.clip_grad_norm_(model.parameters(), 5.0)
321
+ torch.nn.utils.clip_grad_norm_(gnn_teacher.parameters(), 5.0)
322
+ opt.step()
323
+ opt.zero_grad()
324
+
325
+ # ── EMA update ────────────────────────────────────────
326
+ update_ema(ema_teacher, model, ema_momentum)
327
+
328
+ # ── Tracking ──────────────────────────────────────────
329
+ n_tokens = int(attention_mask.sum().item())
330
+ if n_tokens == 0:
331
+ continue
332
+
333
+ processed_tokens += n_tokens
334
+ scheduler.last_epoch = processed_tokens
335
+ scheduler.step()
336
+ updates += 1
337
+
338
+ d_loss_val = distill_loss.item()
339
+ g_loss_val = gnn_recon_loss.item()
340
+ epoch_d_loss += d_loss_val
341
+ epoch_g_loss += g_loss_val
342
+ epoch_batches += 1
343
+ current_lr = scheduler.get_last_lr()[0]
344
+
345
+ if updates % 100 == 0:
346
+ elapsed = time.time() - epoch_st
347
+ log(
348
+ f"[{updates}|e{epoch}] d_loss={d_loss_val:.4f} g_loss={g_loss_val:.4f} "
349
+ f"valid={n_valid}/{B} lr={current_lr:.2e} "
350
+ f"tokens={processed_tokens:.2e} ({elapsed:.1f}s)"
351
+ )
352
+ with open(log_path, "a") as f:
353
+ f.write(f"{updates},{processed_tokens},{d_loss_val:.6f},"
354
+ f"{g_loss_val:.6f},{current_lr:.2e},{elapsed:.1f}\n")
355
+
356
+ if processed_tokens >= total_tokens:
357
+ break
358
+
359
+ if processed_tokens >= total_tokens:
360
+ break
361
+
362
+ # Epoch-level logging
363
+ if epoch_batches > 0:
364
+ avg_d_loss = epoch_d_loss / epoch_batches
365
+ avg_g_loss = epoch_g_loss / epoch_batches
366
+ elapsed = time.time() - epoch_st
367
+ log(f"Epoch {epoch} done | avg_d_loss={avg_d_loss:.4f} avg_g_loss={avg_g_loss:.4f} "
368
+ f"batches={epoch_batches} ({elapsed:.1f}s)")
369
+
370
+ # ── Validation on precomputed fixed val batches ──────────
371
+ if val_batches_fixed:
372
+ model.eval()
373
+ gnn_teacher.eval()
374
+ val_d_losses = []
375
+
376
+ for (v_input_ids, v_attn_mask, v_node_labels,
377
+ v_edge_index, v_edge_types, v_batch_vec,
378
+ v_center_idx, v_valid_mask) in val_batches_fixed:
379
+
380
+ # Encode neighbor nodes with EMA teacher (embeddings evolve)
381
+ v_unique_labels = list(set(v_node_labels))
382
+ v_label_to_uidx = {lbl: i for i, lbl in enumerate(v_unique_labels)}
383
+ v_ema_tids = []
384
+ for ntype, nlabel in v_unique_labels:
385
+ tids = tokenizer.tokenize_node(ntype, nlabel)
386
+ v_ema_tids.append(tids if tids else [tokenizer.pad_id])
387
+ v_ema_ids, v_ema_mask = pad_token_id_lists(v_ema_tids, tokenizer.pad_id, tokenizer.max_seq_len)
388
+
389
+ with torch.no_grad():
390
+ v_ema_emb = ema_teacher.mean_pool(v_ema_ids, v_ema_mask)
391
+ v_node_emb_idx = [v_label_to_uidx[lbl] for lbl in v_node_labels]
392
+ v_node_emb = v_ema_emb[torch.tensor(v_node_emb_idx, dtype=torch.long)]
393
+
394
+ with torch.no_grad():
395
+ v_out = model.modified_fwd(v_input_ids.to(device), v_attn_mask.to(device))
396
+ v_t5_proj = v_out.projected
397
+ _, v_gnn_enc = gnn_teacher(
398
+ v_node_emb, v_edge_index, v_edge_types, v_batch_vec, v_center_idx,
399
+ )
400
+ v_gnn_tgt = v_gnn_enc[v_center_idx]
401
+ v_dloss = sce_loss(v_t5_proj[v_valid_mask], v_gnn_tgt)
402
+ val_d_losses.append(v_dloss.item())
403
+
404
+ epoch_metrics = {"pretrain/epoch": epoch, "pretrain/tokens": processed_tokens}
405
+
406
+ if val_batches_fixed and val_d_losses:
407
+ val_distill_loss = sum(val_d_losses) / len(val_d_losses)
408
+ log(f"Epoch {epoch} val_distill_loss={val_distill_loss:.4f}")
409
+ epoch_metrics["pretrain/val_distill_loss"] = val_distill_loss
410
+
411
+ # ── KNN eval on eval set ──────────────────────────────────
412
+ knn_results = _eval_knn_on_eval_set(model, tokenizer, device, "gnn_distill", batch_size)
413
+ if knn_results:
414
+ knn_acc = knn_results['knn_accuracy_k5']
415
+ epoch_metrics["pretrain/knn_accuracy_k5"] = knn_acc
416
+ for cl, acc in knn_results['knn_accuracy_k5_per_cluster'].items():
417
+ epoch_metrics[f"pretrain/knn_k5/{cl}"] = acc
418
+ epoch_metrics["pretrain/ari"] = knn_results['ari']
419
+ epoch_metrics["pretrain/nmi"] = knn_results['nmi']
420
+ epoch_metrics["pretrain/silhouette"] = knn_results['silhouette']
421
+ epoch_metrics["pretrain/mAP"] = knn_results['mAP']
422
+ log(f"Epoch {epoch} knn_accuracy_k5={knn_acc:.4f} "
423
+ f"ARI={knn_results['ari']:.4f} NMI={knn_results['nmi']:.4f} "
424
+ f"silhouette={knn_results['silhouette']:.4f} mAP={knn_results['mAP']:.4f}")
425
+
426
+ if knn_acc > best_knn_acc:
427
+ best_knn_acc = knn_acc
428
+ log(f" New best KNN accuracy: {knn_acc:.4f}")
429
+ epoch_metrics["pretrain/best_knn_accuracy_k5"] = best_knn_acc
430
+
431
+ # Always save latest model (last epoch wins)
432
+ torch.save(model.state_dict(), os.path.join(out_dir, f"pretrain_{model_size}.pt"))
433
+
434
+ wandb.log(epoch_metrics)
435
+
436
+ # Final save (tokenizer)
437
+ tokenizer.save(os.path.join(out_dir, "tokenizer.pt"))
438
+ log(f"GNN distill pretraining complete. {processed_tokens:,} tokens in {epoch} epochs.")
@@ -0,0 +1,151 @@
1
+ """GraphMAE pretraining branch for SPIDER."""
2
+
3
+ import os
4
+ import random
5
+ import time
6
+
7
+ import torch
8
+
9
+ from pidsmaker.utils.utils import log
10
+ from ..data.tokenizer_bpe import ProvenanceTokenizerBPE as ProvenanceTokenizer
11
+
12
+
13
+ def pretrain_graphmae(cfg, spider_cfg, sampler_pairs, combined_indexid2msg, out_dir, device, batch_size,
14
+ model_size, max_seq_len, bpe_vocab_size, tokenizer_mode,
15
+ normalize_netflow_ips, canonicalize_neighbors, spider_path):
16
+ from ..models.graphmae import (
17
+ GraphMAE, T5NodeEncoder, neighborhoods_to_pyg_batch, save_graphmae,
18
+ )
19
+ from ..models.gnn_distill import get_gnn_distill_encoder_config
20
+
21
+ emb_dim = cfg.featurization.emb_dim
22
+ gm_cfg = spider_cfg.graphmae
23
+ gm_num_layers = gm_cfg.num_layers
24
+ gm_num_heads = gm_cfg.num_heads
25
+ gm_decoder_layers = gm_cfg.decoder_num_layers
26
+ gm_mask_rate = gm_cfg.mask_rate
27
+ gm_replace_rate = gm_cfg.replace_rate
28
+ gm_n_min = gm_cfg.neighborhood_min
29
+ gm_n_max = gm_cfg.neighborhood_max
30
+ gm_epochs = gm_cfg.epochs
31
+ gm_lr = gm_cfg.lr
32
+
33
+ # ── Build or load tokenizer ────────────────────────────────────
34
+ if spider_path:
35
+ tok_path = os.path.join(spider_path, "tokenizer.pt")
36
+ log(f"Loading tokenizer from {tok_path}")
37
+ tokenizer = ProvenanceTokenizer(cfg)
38
+ tokenizer.load(tok_path)
39
+ tokenizer.max_seq_len = max_seq_len
40
+ else:
41
+ walk_label_corpus = []
42
+ for sampler, ds_indexid2msg in sampler_pairs:
43
+ for node in sampler.nodes:
44
+ if node in ds_indexid2msg:
45
+ walk_label_corpus.append(ds_indexid2msg[node])
46
+
47
+ tokenizer = ProvenanceTokenizer(cfg, max_seq_len=max_seq_len, bpe_vocab_size=bpe_vocab_size, mode=tokenizer_mode,
48
+ normalize_netflow_ips=normalize_netflow_ips,
49
+ canonicalize_neighbors=canonicalize_neighbors)
50
+ tokenizer.build_vocab(combined_indexid2msg, walk_label_corpus=walk_label_corpus)
51
+ log(f"Vocabulary size: {tokenizer.vocab_size}")
52
+ tokenizer.save(os.path.join(out_dir, "tokenizer.pt"))
53
+
54
+ # ── Build T5 node encoder ──────────────────────────────────────
55
+ t5_config = get_gnn_distill_encoder_config(tokenizer.vocab_size, model_size, max_seq_len)
56
+ t5_hidden_dim = t5_config.d_model
57
+ t5_encoder = T5NodeEncoder(t5_config).to(device)
58
+ log(f"T5 node encoder: d_model={t5_hidden_dim}, layers={t5_config.num_layers}")
59
+
60
+ # Use T5 hidden dim as GNN input dim
61
+ in_dim = t5_hidden_dim
62
+
63
+ # Build model
64
+ model = GraphMAE(
65
+ in_dim=in_dim,
66
+ hidden_dim=emb_dim,
67
+ num_encoder_layers=gm_num_layers,
68
+ num_decoder_layers=gm_decoder_layers,
69
+ num_heads=gm_num_heads,
70
+ mask_rate=gm_mask_rate,
71
+ replace_rate=gm_replace_rate,
72
+ ).to(device)
73
+ log(f"GraphMAE model: {gm_num_layers} encoder layers, {gm_decoder_layers} decoder layers, "
74
+ f"{gm_num_heads} heads, mask={gm_mask_rate}, replace={gm_replace_rate}")
75
+ log(f"Parameters: GNN={sum(p.numel() for p in model.parameters()):,}, "
76
+ f"T5={sum(p.numel() for p in t5_encoder.parameters()):,}")
77
+
78
+ opt = torch.optim.Adam(
79
+ list(model.parameters()) + list(t5_encoder.parameters()),
80
+ lr=gm_lr,
81
+ )
82
+
83
+ # Collect all nodes across all samplers
84
+ all_nodes_per_sampler = []
85
+ for sampler, ds_indexid2msg in sampler_pairs:
86
+ nodes_with_backward = [n for n in sampler.nodes if n in sampler.backward_adj]
87
+ all_nodes_per_sampler.append((sampler, ds_indexid2msg, nodes_with_backward))
88
+ total_nodes = sum(len(ns) for _, _, ns in all_nodes_per_sampler)
89
+ log(f"GraphMAE: {total_nodes:,} nodes with backward neighbors across {len(sampler_pairs)} graph(s)")
90
+
91
+ # Training loop
92
+ log_path = os.path.join(out_dir, "graphmae_pretrain_log.txt")
93
+ with open(log_path, "w") as f:
94
+ f.write("epoch,loss,time\n")
95
+
96
+ for epoch in range(1, gm_epochs + 1):
97
+ epoch_st = time.time()
98
+ model.train()
99
+ t5_encoder.eval() # T5 encoder in eval mode (used as frozen featurizer per batch)
100
+ epoch_loss = 0.0
101
+ n_batches = 0
102
+ label_cache = {} # Reset label cache each epoch
103
+
104
+ # Shuffle nodes each epoch
105
+ for sampler, ds_indexid2msg, nodes in all_nodes_per_sampler:
106
+ random.shuffle(nodes)
107
+
108
+ # Sample neighborhoods and batch them
109
+ batch_neighborhoods = []
110
+ for node in nodes:
111
+ nh = sampler.sample_temporal_neighborhood(node, n_min=gm_n_min, n_max=gm_n_max)
112
+ if nh is not None:
113
+ batch_neighborhoods.append(nh)
114
+
115
+ if len(batch_neighborhoods) >= batch_size:
116
+ x, edge_index, batch_idx, node_ids = neighborhoods_to_pyg_batch(
117
+ batch_neighborhoods, ds_indexid2msg, t5_encoder, tokenizer, label_cache, device,
118
+ )
119
+ if x is not None and edge_index.size(1) > 0:
120
+ loss = model(x, edge_index)
121
+ opt.zero_grad()
122
+ loss.backward()
123
+ opt.step()
124
+ epoch_loss += loss.item()
125
+ n_batches += 1
126
+ batch_neighborhoods = []
127
+
128
+ # Remaining neighborhoods
129
+ if batch_neighborhoods:
130
+ x, edge_index, batch_idx, node_ids = neighborhoods_to_pyg_batch(
131
+ batch_neighborhoods, ds_indexid2msg, t5_encoder, tokenizer, label_cache, device,
132
+ )
133
+ if x is not None and edge_index.size(1) > 0:
134
+ loss = model(x, edge_index)
135
+ opt.zero_grad()
136
+ loss.backward()
137
+ opt.step()
138
+ epoch_loss += loss.item()
139
+ n_batches += 1
140
+
141
+ avg_loss = epoch_loss / max(n_batches, 1)
142
+ elapsed = time.time() - epoch_st
143
+
144
+ with open(log_path, "a") as f:
145
+ f.write(f"{epoch},{avg_loss:.6f},{elapsed:.1f}\n")
146
+
147
+ log(f"Epoch {epoch}/{gm_epochs} | loss={avg_loss:.4f} | {elapsed:.1f}s")
148
+ if epoch % 10 == 0 or epoch == gm_epochs:
149
+ save_graphmae(model, t5_encoder, out_dir)
150
+
151
+ log(f"GraphMAE pretraining complete. Final loss: {avg_loss:.4f}")