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,491 @@
1
+ """MLM / Causal LM pretraining branch for SPIDER.
2
+
3
+ Handles BERT, RoBERTa, ModernBERT, RoPEBERT, LLaMA, and LogBERT model types.
4
+ """
5
+
6
+ import os
7
+ import random
8
+ import time
9
+
10
+ import torch
11
+ from torch.optim import AdamW
12
+
13
+ import wandb
14
+
15
+ from pidsmaker.utils.utils import log
16
+ from ..training_utils import (
17
+ WarmupLinearScheduler, WarmupCosineScheduler,
18
+ pad_token_id_lists,
19
+ )
20
+ from ..models.bert import ProvenanceBERT, get_bert_config
21
+ from ..models.roberta import ProvenanceRoBERTa, get_roberta_config
22
+ from ..models.modernbert import ProvenanceModernBERT, get_modernbert_config
23
+ from ..models.ropebert import ProvenanceRoPEBERT, get_ropebert_config
24
+ from ..models.llama import ProvenanceLLaMA, get_llama_config
25
+ from ..data.tokenizer_bpe import ProvenanceTokenizerBPE as ProvenanceTokenizer
26
+ from ..data.sampler import ProvenanceWalkSampler
27
+ from .pretrain_common import (
28
+ _extract_walk_label_corpus,
29
+ _dump_corpus_to_txt,
30
+ _eval_knn_on_eval_set,
31
+ )
32
+
33
+
34
+ def _build_pretokenized_val_corpus(val_data, tokenizer, walk_length, num_walks,
35
+ time_weight, half_life, model_type, mask_edge_type,
36
+ max_val_nodes_per_dataset=5000):
37
+ """Pre-tokenize validation walks once to avoid repeated sampling/tokenization each epoch.
38
+
39
+ Loads each validation graph, samples walks from all nodes, and pre-tokenizes them.
40
+ Returns pre-tokenized examples in the same format as the training corpus.
41
+
42
+ To keep the val set small and balanced across N datasets, each dataset contributes
43
+ at most min(total_nodes/N, max_val_nodes_per_dataset) nodes (randomly sampled),
44
+ so the val set stays bounded regardless of dataset count or size.
45
+ """
46
+ pretok_val = []
47
+ seen_sigs: set = set()
48
+ total_nodes = 0
49
+
50
+ for graph_paths, ds_indexid2msg in val_data:
51
+ # Distribute the per-dataset budget proportionally across files so we
52
+ # don't need to hold all graph samplers in memory simultaneously.
53
+ n_files = len(graph_paths)
54
+ k_per_file = max(1, max_val_nodes_per_dataset // n_files)
55
+ budget = max_val_nodes_per_dataset
56
+
57
+ for path in graph_paths:
58
+ if budget <= 0:
59
+ break
60
+ graph = torch.load(path)
61
+ sampler = ProvenanceWalkSampler(
62
+ graph, walk_length=walk_length, num_walks=num_walks,
63
+ time_weight=time_weight, half_life=half_life,
64
+ )
65
+ all_nodes = list(sampler.nodes)
66
+ k = min(k_per_file, len(all_nodes), budget)
67
+ sampled_nodes = random.sample(all_nodes, k)
68
+ budget -= k
69
+ total_nodes += k
70
+
71
+ # Process inline while sampler is alive (graph can be GC'd after this loop)
72
+ for node in sampled_nodes:
73
+ walk_nodes, walk_edge_types, _, entity_pos = sampler._single_walk(node)
74
+ if len(walk_nodes) <= 1:
75
+ continue
76
+
77
+ token_ids, node_boundaries, edge_boundaries = tokenizer.tokenize_walk(
78
+ walk_nodes, walk_edge_types, ds_indexid2msg
79
+ )
80
+ if not token_ids:
81
+ continue
82
+ sig = tuple(token_ids)
83
+ if sig not in seen_sigs:
84
+ seen_sigs.add(sig)
85
+ pretok_val.append((token_ids, node_boundaries, edge_boundaries))
86
+
87
+ log(f"Val corpus: {len(pretok_val):,} unique examples from {total_nodes:,} nodes")
88
+ return pretok_val
89
+
90
+
91
+ @torch.no_grad()
92
+ def _evaluate(model, pretok_val, tokenizer, device, batch_size, model_type, mask_edge_type=True):
93
+ """Evaluate prediction loss on pre-tokenized validation examples."""
94
+ model.eval()
95
+ total_loss = 0
96
+ n_batches = 0
97
+ is_causal_lm = model_type == "llama"
98
+
99
+ for batch_start in range(0, len(pretok_val), batch_size):
100
+ batch = pretok_val[batch_start:batch_start + batch_size]
101
+ if not batch:
102
+ continue
103
+
104
+ if is_causal_lm:
105
+ batch_token_ids = [tok for tok, _, _ in batch]
106
+ B = len(batch)
107
+ input_ids, attn_mask = pad_token_id_lists(batch_token_ids, tokenizer.pad_id, tokenizer.max_seq_len)
108
+ labels = input_ids.clone()
109
+ labels[~attn_mask] = -100
110
+
111
+ else:
112
+ # MLM: evaluate with fixed masking (no stochastic mask here — use same rate)
113
+ batch_masked = []
114
+ batch_targets = []
115
+ for token_ids, node_boundaries, edge_boundaries in batch:
116
+ if mask_edge_type and edge_boundaries:
117
+ masked_ids, targets, p_mask = tokenizer.mask_walk(
118
+ token_ids, node_boundaries, edge_boundaries
119
+ )
120
+ else:
121
+ masked_ids, targets, p_mask = tokenizer.mask_nodes(
122
+ token_ids, node_boundaries
123
+ )
124
+ batch_masked.append(masked_ids)
125
+ batch_targets.append((targets, p_mask))
126
+
127
+ input_ids, attn_mask = pad_token_id_lists(batch_masked, tokenizer.pad_id, tokenizer.max_seq_len)
128
+ B, max_len = input_ids.shape
129
+ labels = torch.full((B, max_len), -100, dtype=torch.long)
130
+ predict_tensor = torch.zeros(B, max_len, dtype=torch.bool)
131
+ for i in range(B):
132
+ seq_len = min(len(batch_masked[i]), max_len)
133
+ targets, p_mask = batch_targets[i]
134
+ t_idx = 0
135
+ for pos in range(seq_len):
136
+ if p_mask[pos]:
137
+ labels[i, pos] = targets[t_idx]
138
+ predict_tensor[i, pos] = True
139
+ t_idx += 1
140
+ if predict_tensor.sum() == 0:
141
+ continue
142
+
143
+ loss = model.modified_fwd(
144
+ input_ids.to(device),
145
+ attn_mask.to(device),
146
+ labels.to(device),
147
+ )
148
+ total_loss += loss.item()
149
+ n_batches += 1
150
+
151
+ return total_loss / max(1, n_batches)
152
+
153
+
154
+ def pretrain_mlm(cfg, spider_cfg, walk_corpus, sampler_pairs, combined_indexid2msg, all_val_data,
155
+ out_dir, device, model_type, model_size, max_seq_len, bpe_vocab_size, tokenizer_mode,
156
+ normalize_netflow_ips, canonicalize_neighbors, spider_path,
157
+ total_tokens, warmup_tokens, batch_size, lr, scheduler_type):
158
+ # ── MLM-specific config (only meaningful for this branch) ───────────
159
+ mlm_cfg = spider_cfg.mlm
160
+ mask_rate_fixed = mlm_cfg.mask_rate_fixed
161
+ mask_rate_min = mlm_cfg.mask_rate_min
162
+ mask_edge_type = mlm_cfg.mask_edge_type
163
+ hvm_weight = mlm_cfg.logbert.hvm_weight if model_type == "logbert" else 0.0
164
+
165
+ # ── Build or load tokenizer ─────────────────────────────────────────
166
+ if spider_path:
167
+ tok_path = os.path.join(spider_path, "tokenizer.pt")
168
+ log(f"Loading tokenizer from {tok_path}")
169
+ tokenizer = ProvenanceTokenizer(cfg)
170
+ tokenizer.load(tok_path)
171
+ # Override max_seq_len with the current config value (the saved tokenizer
172
+ # may have been trained with a different max_seq_len)
173
+ tokenizer.max_seq_len = max_seq_len
174
+ log(f" Overriding max_seq_len to {max_seq_len} (from config)")
175
+ tokenizer.set_mask_rate(0, fixed_rate=mask_rate_fixed, min_rate=mask_rate_min)
176
+ else:
177
+ walk_label_corpus = _extract_walk_label_corpus(walk_corpus)
178
+ log(f"Walk label corpus: {len(walk_label_corpus):,} (node_type, label) pairs "
179
+ f"from {len(walk_corpus):,} unique walks")
180
+
181
+ log("Building tokenizer...")
182
+ tokenizer = ProvenanceTokenizer(cfg, max_seq_len=max_seq_len, bpe_vocab_size=bpe_vocab_size, mode=tokenizer_mode,
183
+ normalize_netflow_ips=normalize_netflow_ips,
184
+ canonicalize_neighbors=canonicalize_neighbors)
185
+ tokenizer.build_vocab(combined_indexid2msg, walk_label_corpus=walk_label_corpus)
186
+ tokenizer.set_mask_rate(0, fixed_rate=mask_rate_fixed, min_rate=mask_rate_min)
187
+ log(f"Vocabulary size: {tokenizer.vocab_size}")
188
+ tokenizer.save(os.path.join(out_dir, "tokenizer.pt"))
189
+ vocab_dump_path = os.path.join(out_dir, "vocab.txt")
190
+ tokenizer.dump_vocab(vocab_dump_path)
191
+ log(f"Vocab dumped to {vocab_dump_path}")
192
+
193
+ # ── Dump corpus for inspection ──────────────────────────────────────
194
+ _CORPUS_DUMP_LIMIT = 2_000_000
195
+ if len(walk_corpus) > _CORPUS_DUMP_LIMIT:
196
+ log(f"Skipping walk corpus dump ({len(walk_corpus):,} walks > {_CORPUS_DUMP_LIMIT:,} limit)")
197
+ else:
198
+ log(f"Dumping walk corpus ({len(walk_corpus):,} walks)...")
199
+ _dump_corpus_to_txt(walk_corpus, tokenizer, out_dir)
200
+
201
+ # ── Pre-tokenize validation corpus (once, reused every epoch) ────────
202
+ walk_length = spider_cfg.walks.walk_length
203
+ num_walks = spider_cfg.walks.num_walks
204
+ time_weight = spider_cfg.walks.time_weight
205
+ half_life = spider_cfg.walks.half_life
206
+
207
+ pretok_val = []
208
+ if all_val_data:
209
+ log("Pre-tokenizing validation corpus...")
210
+ val_st = time.time()
211
+ pretok_val = _build_pretokenized_val_corpus(
212
+ all_val_data, tokenizer, walk_length, num_walks,
213
+ time_weight, half_life, model_type, mask_edge_type,
214
+ )
215
+ log(f"Val corpus pre-tokenized in {time.time() - val_st:.1f}s")
216
+
217
+ # ── Build model ─────────────────────────────────────────────────────
218
+ if model_type == "ropebert":
219
+ rope_theta = spider_cfg.mlm.ropebert.rope_theta
220
+ bert_config = get_ropebert_config(
221
+ tokenizer.vocab_size, model_size, max_seq_len,
222
+ rope_theta=rope_theta,
223
+ )
224
+ model = ProvenanceRoPEBERT(bert_config).to(device)
225
+ log(f"Model: RoPEBERT-{model_size} (theta={rope_theta})")
226
+ elif model_type == "llama":
227
+ rope_theta = spider_cfg.mlm.llama.rope_theta
228
+ llama_config = get_llama_config(
229
+ tokenizer.vocab_size, model_size, max_seq_len,
230
+ rope_theta=rope_theta,
231
+ )
232
+ model = ProvenanceLLaMA(llama_config).to(device)
233
+ log(f"Model: LLaMA-{model_size} (theta={rope_theta})")
234
+ elif model_type == "modernbert":
235
+ mb_cfg = spider_cfg.mlm.modernbert
236
+ bert_config = get_modernbert_config(
237
+ tokenizer.vocab_size, model_size, max_seq_len,
238
+ global_attn_every_n_layers=mb_cfg.global_attn_every_n_layers,
239
+ local_attention_window=mb_cfg.local_attention_window
240
+ )
241
+ model = ProvenanceModernBERT(bert_config).to(device)
242
+ log(f"Model: ModernBERT-{model_size} (global every {mb_cfg.global_attn_every_n_layers}, "
243
+ f"window {mb_cfg.local_attention_window})")
244
+ elif model_type == "roberta":
245
+ bert_config = get_roberta_config(tokenizer.vocab_size, model_size, max_seq_len)
246
+ model = ProvenanceRoBERTa(bert_config).to(device)
247
+ log(f"Model: RoBERTa-{model_size}")
248
+ elif model_type == "logbert":
249
+ bert_config = get_bert_config(tokenizer.vocab_size, model_size, max_seq_len)
250
+ model = ProvenanceBERT(bert_config).to(device)
251
+ log(f"Model: LogBERT-{model_size} (HVM weight={hvm_weight})")
252
+ else:
253
+ bert_config = get_bert_config(tokenizer.vocab_size, model_size, max_seq_len)
254
+ model = ProvenanceBERT(bert_config).to(device)
255
+ log(f"Model: BERT-{model_size}")
256
+
257
+ # LogBERT: initialize hypersphere center for volume minimization
258
+ hvm_center = None
259
+ if model_type == "logbert":
260
+ hvm_center = torch.zeros(bert_config.hidden_size, device=device)
261
+
262
+ log(f"Parameters: {sum(p.numel() for p in model.parameters()):,}")
263
+
264
+ # ── Optimizer and scheduler ─────────────────────────────────────────
265
+ opt = AdamW(
266
+ model.parameters(),
267
+ lr=lr,
268
+ betas=(0.9, 0.95),
269
+ eps=1e-8,
270
+ weight_decay=0.1,
271
+ )
272
+ if scheduler_type == "cosine":
273
+ scheduler = WarmupCosineScheduler(opt, warmup_tokens, total_tokens)
274
+ else:
275
+ scheduler = WarmupLinearScheduler(opt, warmup_tokens, total_tokens)
276
+
277
+ # ── Training loop ───────────────────────────────────────────────────
278
+ processed_tokens = 0
279
+ updates = 0
280
+ epoch = 0
281
+ best_knn_acc = -1.0
282
+
283
+ log_path = os.path.join(out_dir, f"pretrain_log_{model_size}.txt")
284
+ with open(log_path, "w") as f:
285
+ f.write("update,tokens,loss,lr,mask_rate,time\n")
286
+
287
+ # ── Pre-tokenize walk corpus ──────────────────────────────────────────
288
+ # Tokenization is deterministic (needs indexid2msg), only masking is
289
+ # stochastic. Pre-tokenize once to avoid per-batch repeated BPE encoding.
290
+ log("Pre-tokenizing walk corpus...")
291
+ pt_st = time.time()
292
+
293
+ # Tokenize + deduplicate on tokenized sequence.
294
+ # Prelabel dedup already removed most duplicates; this catches the remainder
295
+ # where distinct labels collapse to the same tokens after normalization
296
+ # (e.g. two walks differing only in a hash value or numeric ID).
297
+ pretokenized_walks = []
298
+ seen_tok_sigs: set = set()
299
+ n_prelabel = len(walk_corpus)
300
+ for walk_nodes, walk_edge_types, ds_indexid2msg, _epos in walk_corpus:
301
+ token_ids, node_boundaries, edge_boundaries = tokenizer.tokenize_walk(
302
+ walk_nodes, walk_edge_types, ds_indexid2msg
303
+ )
304
+ if token_ids:
305
+ sig = tuple(token_ids)
306
+ if sig not in seen_tok_sigs:
307
+ seen_tok_sigs.add(sig)
308
+ pretokenized_walks.append((token_ids, node_boundaries, edge_boundaries))
309
+ log(f"Pre-tokenized {len(pretokenized_walks):,} walks "
310
+ f"(deduped from {n_prelabel:,} prelabel-unique, {time.time() - pt_st:.1f}s)")
311
+
312
+ corpus_len = len(pretokenized_walks or walk_corpus)
313
+ log(f"Starting pretraining with {corpus_len:,} unique examples...")
314
+ is_causal_lm = model_type == "llama"
315
+ uses_masking = not is_causal_lm
316
+
317
+ while processed_tokens < total_tokens:
318
+ epoch += 1
319
+ epoch_st = time.time()
320
+
321
+ # Shuffle corpus for this epoch (provides randomness across epochs)
322
+ random.shuffle(pretokenized_walks)
323
+
324
+ # Process walks in batches
325
+ for batch_start in range(0, corpus_len, batch_size):
326
+ if is_causal_lm:
327
+ # ── Causal LM (LLaMA): no masking, next-token prediction ──
328
+ batch_pretok = pretokenized_walks[batch_start:batch_start + batch_size]
329
+ B = len(batch_pretok)
330
+ if B == 0:
331
+ continue
332
+
333
+ batch_token_ids = [token_ids for token_ids, _, _ in batch_pretok]
334
+ input_ids, attention_mask = pad_token_id_lists(batch_token_ids, tokenizer.pad_id, tokenizer.max_seq_len)
335
+
336
+ # Labels = input_ids; the model shifts internally for next-token prediction.
337
+ # Set padding positions to -100 so they're ignored in loss.
338
+ labels = input_ids.clone()
339
+ labels[~attention_mask] = -100
340
+ else:
341
+ # ── MLM (BERT variants): apply masking ──
342
+ batch_pretok = pretokenized_walks[batch_start:batch_start + batch_size]
343
+ B = len(batch_pretok)
344
+ if B == 0:
345
+ continue
346
+
347
+ batch_masked = []
348
+ batch_targets = []
349
+ for token_ids, node_boundaries, edge_boundaries in batch_pretok:
350
+ if mask_edge_type and edge_boundaries:
351
+ masked_ids, targets, p_mask = tokenizer.mask_walk(
352
+ token_ids, node_boundaries, edge_boundaries
353
+ )
354
+ else:
355
+ masked_ids, targets, p_mask = tokenizer.mask_nodes(
356
+ token_ids, node_boundaries
357
+ )
358
+ batch_masked.append(masked_ids)
359
+ batch_targets.append((targets, p_mask))
360
+
361
+ input_ids, attention_mask = pad_token_id_lists(batch_masked, tokenizer.pad_id, tokenizer.max_seq_len)
362
+ max_len = input_ids.shape[1]
363
+ labels = torch.full((B, max_len), -100, dtype=torch.long)
364
+ predict_tensor = torch.zeros(B, max_len, dtype=torch.bool)
365
+
366
+ for i in range(B):
367
+ seq_len = min(len(batch_masked[i]), max_len)
368
+ targets, p_mask = batch_targets[i]
369
+ t_idx = 0
370
+ for pos in range(seq_len):
371
+ if p_mask[pos]:
372
+ labels[i, pos] = targets[t_idx]
373
+ predict_tensor[i, pos] = True
374
+ t_idx += 1
375
+
376
+ if predict_tensor.sum() == 0:
377
+ continue
378
+
379
+ # Forward + backward
380
+ model.train()
381
+ if updates == 0:
382
+ log(f" First batch shapes: input_ids={input_ids.shape}, labels={labels.shape}")
383
+ _input_ids = input_ids.to(device)
384
+ _attention_mask = attention_mask.to(device)
385
+ _labels = labels.to(device)
386
+
387
+ # LogBERT: get hidden states, compute MLM loss + HVM from single forward
388
+ if hvm_center is not None:
389
+ hidden = model.modified_fwd(
390
+ _input_ids, _attention_mask, _labels, skip_cls=True,
391
+ ) # [B, L, H]
392
+ # MLM loss: project hidden → vocab and compute cross-entropy
393
+ prediction_scores = model.cls(hidden)
394
+ mlm_loss = torch.nn.functional.cross_entropy(
395
+ prediction_scores.view(-1, model.config.vocab_size),
396
+ _labels.view(-1),
397
+ ignore_index=-100,
398
+ )
399
+ # HVM loss: mean-pool hidden states → distance to hypersphere center
400
+ mask_f = _attention_mask.unsqueeze(-1).float()
401
+ pooled = (hidden * mask_f).sum(dim=1) / mask_f.sum(dim=1).clamp(min=1) # [B, H]
402
+ hvm_loss = ((pooled - hvm_center) ** 2).sum(dim=-1).mean()
403
+ loss = mlm_loss + hvm_weight * hvm_loss
404
+ # Update center with exponential moving average (detached)
405
+ with torch.no_grad():
406
+ hvm_center = 0.99 * hvm_center + 0.01 * pooled.mean(dim=0)
407
+ else:
408
+ loss = model.modified_fwd(_input_ids, _attention_mask, _labels)
409
+
410
+ loss.backward()
411
+ torch.nn.utils.clip_grad_norm_(model.parameters(), 5.0)
412
+ opt.step()
413
+ opt.zero_grad()
414
+ loss = loss.item()
415
+
416
+ n_tokens = int(attention_mask.sum().item())
417
+
418
+ # ── Track tokens + logging (shared) ──
419
+ if n_tokens == 0:
420
+ continue
421
+
422
+ processed_tokens += n_tokens
423
+ scheduler.last_epoch = processed_tokens
424
+ scheduler.step()
425
+
426
+ if uses_masking:
427
+ # Update mask rate (MLM only)
428
+ progress = min(1.0, processed_tokens / warmup_tokens)
429
+ tokenizer.set_mask_rate(progress, fixed_rate=mask_rate_fixed, min_rate=mask_rate_min)
430
+
431
+ updates += 1
432
+ current_lr = scheduler.get_last_lr()[0]
433
+
434
+ if updates % 100 == 0:
435
+ elapsed = time.time() - epoch_st
436
+ mask_info = f" mask={tokenizer.mask_rate:.3f}" if uses_masking else ""
437
+ log(
438
+ f"[{updates}|e{epoch}] loss={loss:.4f} "
439
+ f"lr={current_lr:.2e}{mask_info} "
440
+ f"tokens={processed_tokens:.2e} ({elapsed:.1f}s)"
441
+ )
442
+ with open(log_path, "a") as f:
443
+ mask_val = tokenizer.mask_rate if uses_masking else 0.0
444
+ f.write(f"{updates},{processed_tokens},{loss:.6f},{current_lr:.2e},{mask_val:.4f},{elapsed:.1f}\n")
445
+
446
+ if processed_tokens >= total_tokens:
447
+ break
448
+
449
+ if processed_tokens >= total_tokens:
450
+ break
451
+
452
+ # ── Validation ──────────────────────────────────────────────────
453
+ epoch_metrics = {"pretrain/epoch": epoch, "pretrain/tokens": processed_tokens}
454
+ if pretok_val:
455
+ val_loss = _evaluate(model, pretok_val, tokenizer, device, batch_size, model_type, mask_edge_type)
456
+ log(f"Epoch {epoch} val_loss={val_loss:.4f}")
457
+ epoch_metrics["pretrain/val_loss"] = val_loss
458
+
459
+ # ── KNN eval on eval set ──────────────────────────────────────
460
+ knn_results = _eval_knn_on_eval_set(model, tokenizer, device, model_type, batch_size)
461
+ if knn_results:
462
+ knn_acc = knn_results['knn_accuracy_k5']
463
+ epoch_metrics["pretrain/knn_accuracy_k5"] = knn_acc
464
+ for cl, acc in knn_results['knn_accuracy_k5_per_cluster'].items():
465
+ epoch_metrics[f"pretrain/knn_k5/{cl}"] = acc
466
+ epoch_metrics["pretrain/ari"] = knn_results['ari']
467
+ epoch_metrics["pretrain/nmi"] = knn_results['nmi']
468
+ epoch_metrics["pretrain/silhouette"] = knn_results['silhouette']
469
+ epoch_metrics["pretrain/mAP"] = knn_results['mAP']
470
+ log(f"Epoch {epoch} knn_accuracy_k5={knn_acc:.4f} "
471
+ f"ARI={knn_results['ari']:.4f} NMI={knn_results['nmi']:.4f} "
472
+ f"silhouette={knn_results['silhouette']:.4f} mAP={knn_results['mAP']:.4f}")
473
+
474
+ if knn_acc > best_knn_acc:
475
+ best_knn_acc = knn_acc
476
+ log(f" New best KNN accuracy: {knn_acc:.4f}")
477
+ epoch_metrics["pretrain/best_knn_accuracy_k5"] = best_knn_acc
478
+
479
+ # Always save latest model (last epoch wins)
480
+ torch.save(model.state_dict(), os.path.join(out_dir, f"pretrain_{model_size}.pt"))
481
+ if hvm_center is not None:
482
+ torch.save(hvm_center.cpu(), os.path.join(out_dir, f"hvm_center_{model_size}.pt"))
483
+
484
+ wandb.log(epoch_metrics)
485
+
486
+ # Final save (ensures checkpoint is written even when token budget breaks mid-epoch)
487
+ torch.save(model.state_dict(), os.path.join(out_dir, f"pretrain_{model_size}.pt"))
488
+ if hvm_center is not None:
489
+ torch.save(hvm_center.cpu(), os.path.join(out_dir, f"hvm_center_{model_size}.pt"))
490
+ tokenizer.save(os.path.join(out_dir, "tokenizer.pt"))
491
+ log(f"Pretraining complete. {processed_tokens} tokens processed in {epoch} epochs.")