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,1437 @@
1
+ """
2
+ SPIDER fine-tuning for anomaly detection on provenance graphs.
3
+
4
+ Supports multiple modes:
5
+ - CLS: Binary classification with [CLS] token
6
+ - CLS_ATTACK: Supervised binary classification with real attack walks
7
+ - LP: Link prediction via masked destination node likelihood
8
+ - TGN: Temporal Graph Network with attention-based entity memory (self-supervised)
9
+
10
+ Follows CyberGFM's cls_finetune.py and lp_finetune.py patterns.
11
+ """
12
+
13
+ import os
14
+ import pickle
15
+ import random
16
+ import time
17
+ from collections import defaultdict
18
+ from typing import List, Tuple
19
+
20
+ import numpy as np
21
+ import torch
22
+ import torch.nn.functional as F
23
+ from torch.optim import AdamW
24
+ from torch_geometric.utils import scatter
25
+
26
+ from .training_utils import (
27
+ WarmupLinearScheduler, WarmupCosineScheduler,
28
+ pad_token_id_lists, pad_tensor_batch,
29
+ )
30
+
31
+ from pidsmaker.utils.utils import get_all_graphs_for_dates, get_indexid2msg, log, log_start
32
+ from pidsmaker.utils.labelling import get_GP_of_each_attack, get_ground_truth_edges
33
+ from pidsmaker.utils.dataset_utils import get_rel2id, ntype2id
34
+
35
+ from .models.bert import MODEL_SIZES, ProvenanceBERTFineTuneCLS, ProvenanceBERTFineTuneLP, get_bert_config
36
+ from .models.modernbert import ProvenanceModernBERTFineTuneCLS, ProvenanceModernBERTFineTuneLP, get_modernbert_config
37
+ from .models.ropebert import ProvenanceRoPEBERTFineTuneCLS, ProvenanceRoPEBERTFineTuneLP, get_ropebert_config
38
+ from .models.tgn import ProvenanceTGN
39
+ from .data.sampler import ProvenanceWalkSampler
40
+ from .data.tokenizer_bpe import ProvenanceTokenizerBPE as ProvenanceTokenizer
41
+
42
+
43
+ def _collect_edges(graph) -> List[Tuple[str, str, str, float]]:
44
+ """Collect all edges as (src, dst, edge_type, time) from a NetworkX graph."""
45
+ edges = []
46
+ for src, dst, _, attrs in graph.edges(data=True, keys=True):
47
+ edges.append((
48
+ str(src), str(dst),
49
+ attrs.get("label", ""),
50
+ attrs.get("time", 0.0),
51
+ ))
52
+ return edges
53
+
54
+
55
+ def _build_neg_index(indexid2msg: dict) -> dict:
56
+ """Build node_type -> list of (label, node_id) pairs for negative sampling.
57
+
58
+ Grouping by (type, label) lets us efficiently exclude candidates whose
59
+ textual representation is identical to the positive destination.
60
+ """
61
+ type_to_labeled: dict = defaultdict(list)
62
+ for node_id, (node_type, node_label) in indexid2msg.items():
63
+ type_to_labeled[node_type].append((node_label, str(node_id)))
64
+ return type_to_labeled
65
+
66
+
67
+ def _precompute_negatives(
68
+ edges: List[Tuple],
69
+ indexid2msg: dict,
70
+ type_to_labeled: dict,
71
+ real_edge_set: set,
72
+ max_tries: int = 20,
73
+ ) -> dict:
74
+ """Pre-compute one negative dst per unique (src, dst, etype) triple.
75
+
76
+ Each negative satisfies:
77
+ - Same node type as dst, but a *different* textual label (distinct tokens).
78
+ - (src, neg_dst, etype) does not exist in real_edge_set.
79
+
80
+ Returns a dict mapping (src, dst, etype) -> neg_dst string.
81
+
82
+ Speed: builds two O(V) lookup tables once, then uses rejection sampling
83
+ (random.choices, O(max_tries)) per triple — avoids the O(|type|) list
84
+ comprehension + shuffle that the naive approach does per unique key.
85
+ """
86
+ all_node_ids = [str(n) for n in indexid2msg]
87
+
88
+ # type_to_all[node_type] -> flat list of all node_ids of that type
89
+ type_to_all: dict = {t: [n for _, n in nodes] for t, nodes in type_to_labeled.items()}
90
+ # same_label[(node_type, label)] -> set of node_ids sharing that label
91
+ # Used for O(1) exclusion instead of per-triple list filtering
92
+ same_label: dict = defaultdict(set)
93
+ for node_type, labeled_nodes in type_to_labeled.items():
94
+ for label, node_id in labeled_nodes:
95
+ same_label[(node_type, label)].add(node_id)
96
+
97
+ # Deduplicate keys upfront to skip repeated computation
98
+ unique_keys = dict.fromkeys(
99
+ (str(e[0]), str(e[1]), str(e[2])) for e in edges
100
+ )
101
+ neg_map: dict = {}
102
+ for src, dst, etype in unique_keys:
103
+ dst_info = indexid2msg.get(dst)
104
+ neg_dst = None
105
+ if dst_info:
106
+ dst_type, dst_label = dst_info
107
+ pool = type_to_all.get(dst_type, [])
108
+ excl = same_label.get((dst_type, dst_label), set())
109
+ if pool:
110
+ # Rejection sampling: O(max_tries), no large list construction
111
+ for c in random.choices(pool, k=min(max_tries, len(pool))):
112
+ if c not in excl and (src, c, etype) not in real_edge_set:
113
+ neg_dst = c
114
+ break
115
+ if neg_dst is None:
116
+ # Relax real-edge constraint, keep different-label guarantee
117
+ for c in random.choices(pool, k=min(max_tries, len(pool))):
118
+ if c not in excl:
119
+ neg_dst = c
120
+ break
121
+ if neg_dst is None:
122
+ neg_dst = random.choice(all_node_ids)
123
+ neg_map[(src, dst, etype)] = neg_dst
124
+ return neg_map
125
+
126
+
127
+ # ── Attack walk extraction (for cls_attack mode) ──────────────────────────────
128
+
129
+ def _extract_attack_walks(
130
+ cfg,
131
+ walk_length: int,
132
+ time_weight: str,
133
+ half_life: float,
134
+ num_walks: int,
135
+ ) -> List[Tuple[List[str], List[str], str, str]]:
136
+ """Extract backward context walks that terminate at malicious attack nodes
137
+ strictly within the attack time window for each node.
138
+
139
+ Uses get_GP_of_each_attack to obtain per-attack (node IDs, time_range) so
140
+ that only edges whose timestamp falls inside the known attack period are
141
+ considered. This prevents sampling walks from before or after the attack,
142
+ which would not carry attack-specific provenance patterns.
143
+
144
+ Returns:
145
+ List of (walk_nodes, walk_edge_types, dst_node_id, edge_type) tuples.
146
+ These are used as the positive (anomalous, label=1) class in cls_attack.
147
+ """
148
+ attack_to_nids = get_GP_of_each_attack(cfg)
149
+
150
+ # Build: mal_node_str -> list of (start_ns, end_ns) attack windows
151
+ mal_node_to_windows: dict = defaultdict(list)
152
+ for attack_info in attack_to_nids.values():
153
+ start_ns, end_ns = attack_info["time_range"]
154
+ for nid in attack_info["nids"]:
155
+ mal_node_to_windows[str(nid)].append((start_ns, end_ns))
156
+
157
+ mal_nids_str = set(mal_node_to_windows.keys())
158
+
159
+ base_dir = cfg.transformation._graphs_dir
160
+ attack_graph_paths = (
161
+ get_all_graphs_for_dates(base_dir, cfg.dataset.val_dates)
162
+ + get_all_graphs_for_dates(base_dir, cfg.dataset.test_dates)
163
+ )
164
+
165
+ attack_walks: List[Tuple[List[str], List[str], str, str]] = []
166
+ n_mal_edges = 0
167
+
168
+ for graph_path in attack_graph_paths:
169
+ graph = torch.load(graph_path, weights_only=False)
170
+ sampler = ProvenanceWalkSampler(
171
+ graph, walk_length=walk_length, num_walks=1,
172
+ time_weight=time_weight, half_life=half_life,
173
+ )
174
+
175
+ # First pass: collect unique (src, dst, etype) triples within the attack window.
176
+ # Keep the latest timestamp per triple so the backward walk has maximum context.
177
+ triple_to_ts: dict = {} # (src_str, dst_str, etype) -> latest ts
178
+ for src, dst, _, attrs in graph.edges(data=True, keys=True):
179
+ dst_str = str(dst)
180
+ if dst_str not in mal_nids_str:
181
+ continue
182
+ ts = attrs.get("time", 0.0)
183
+ if not any(start <= ts <= end for start, end in mal_node_to_windows[dst_str]):
184
+ continue
185
+ etype = attrs.get("label", "")
186
+ key = (str(src), dst_str, etype)
187
+ if key not in triple_to_ts or ts > triple_to_ts[key]:
188
+ triple_to_ts[key] = ts
189
+
190
+ n_mal_edges += len(triple_to_ts)
191
+
192
+ # Second pass: sample num_walks unique walks per unique triple.
193
+ for (src_str, dst_str, etype), ts in triple_to_ts.items():
194
+ # dst backward walk is deterministic (no randomness in sample_context_walk
195
+ # for the first hop) — sample once and reuse across all src walk variants.
196
+ dst_walk_nodes, dst_walk_edge_types = sampler.sample_context_walk(
197
+ dst_str, max_ts=ts, walk_length=walk_length,
198
+ )
199
+ seen_seqs: set = set()
200
+ n_tries = 0
201
+ max_tries = num_walks * 5
202
+ while len(seen_seqs) < num_walks and n_tries < max_tries:
203
+ n_tries += 1
204
+ walk_nodes, walk_edge_types = sampler.sample_bidirectional_walk(
205
+ src_str, max_ts=ts, walk_length=walk_length,
206
+ )
207
+ seq_key = tuple(walk_edge_types)
208
+ if seq_key not in seen_seqs:
209
+ seen_seqs.add(seq_key)
210
+ attack_walks.append((
211
+ walk_nodes, walk_edge_types,
212
+ dst_walk_nodes, dst_walk_edge_types,
213
+ dst_str, etype,
214
+ ))
215
+
216
+ log(f"Extracted {len(attack_walks)} unique attack walks from {n_mal_edges} unique malicious triples "
217
+ f"({len(mal_nids_str)} malicious nodes)")
218
+ return attack_walks
219
+
220
+
221
+ def _save_attack_walks(walks: List[Tuple], path: str) -> None:
222
+ with open(path, "wb") as f:
223
+ pickle.dump(walks, f)
224
+ log(f"Saved {len(walks)} attack walks to {path}")
225
+
226
+
227
+ def _load_attack_walks(path: str) -> List[Tuple]:
228
+ with open(path, "rb") as f:
229
+ walks = pickle.load(f)
230
+ log(f"Loaded {len(walks)} attack walks from {path}")
231
+ return walks
232
+
233
+
234
+ def _prepare_finetune_batch_cls_attack(
235
+ benign_edges: List[Tuple[str, str, str, float]],
236
+ attack_walks_sample: List[Tuple[List[str], List[str], List[str], List[str], str, str]],
237
+ sampler: ProvenanceWalkSampler,
238
+ tokenizer: ProvenanceTokenizer,
239
+ indexid2msg: dict,
240
+ walk_length: int,
241
+ ):
242
+ """Prepare a CLS batch from real benign edges (label=0) and real attack walks (label=1).
243
+
244
+ Args:
245
+ benign_edges: edges from normal training graphs; provide context and destination.
246
+ attack_walks_sample: pre-extracted attack walks (same length as benign_edges).
247
+ Each element is (src_walk_nodes, src_walk_edge_types,
248
+ dst_walk_nodes, dst_walk_edge_types, dst, etype).
249
+
250
+ Returns:
251
+ input_ids, attention_mask, target_mask, labels — same format as
252
+ _prepare_finetune_batch_cls, ready to pass to model.forward().
253
+ """
254
+ batch_input_ids = []
255
+ batch_attn = []
256
+ batch_target = []
257
+ batch_labels = []
258
+
259
+ for (src, dst, etype, ts), (
260
+ aw_nodes, aw_etypes, aw_dst_walk_nodes, aw_dst_walk_etypes, aw_dst, aw_etype
261
+ ) in zip(benign_edges, attack_walks_sample):
262
+ # Benign example (label=0): sample src bidirectional walk + dst backward walk
263
+ walk_nodes, walk_edge_types = sampler.sample_bidirectional_walk(src, max_ts=ts, walk_length=walk_length)
264
+ dst_walk_nodes, dst_walk_edge_types = sampler.sample_context_walk(dst, max_ts=ts, walk_length=walk_length)
265
+ tok_ids, attn, tgt_mask = tokenizer.tokenize_for_finetune(
266
+ walk_nodes, walk_edge_types, dst, etype, indexid2msg, mode="cls",
267
+ dst_walk_nodes=dst_walk_nodes, dst_walk_edge_types=dst_walk_edge_types,
268
+ )
269
+ batch_input_ids.append(tok_ids)
270
+ batch_attn.append(attn)
271
+ batch_target.append(tgt_mask)
272
+ batch_labels.append(0.0)
273
+
274
+ # Attack example (label=1) — use pre-extracted src and dst walks
275
+ tok_ids, attn, tgt_mask = tokenizer.tokenize_for_finetune(
276
+ aw_nodes, aw_etypes, aw_dst, aw_etype, indexid2msg, mode="cls",
277
+ dst_walk_nodes=aw_dst_walk_nodes, dst_walk_edge_types=aw_dst_walk_etypes,
278
+ )
279
+ batch_input_ids.append(tok_ids)
280
+ batch_attn.append(attn)
281
+ batch_target.append(tgt_mask)
282
+ batch_labels.append(1.0)
283
+
284
+ # Pad to max length
285
+ input_ids = pad_tensor_batch(batch_input_ids, pad_value=tokenizer.pad_id)
286
+ attention_mask = pad_tensor_batch(batch_attn, pad_value=0)
287
+ target_mask = pad_tensor_batch(batch_target, pad_value=0)
288
+ labels = torch.zeros(len(batch_input_ids), 1)
289
+ for i in range(len(batch_labels)):
290
+ labels[i, 0] = batch_labels[i]
291
+
292
+ return input_ids, attention_mask, target_mask, labels
293
+
294
+
295
+ def _prepare_finetune_batch_cls(
296
+ edges: List[Tuple[str, str, str, float]],
297
+ sampler: ProvenanceWalkSampler,
298
+ tokenizer: ProvenanceTokenizer,
299
+ indexid2msg: dict,
300
+ walk_length: int,
301
+ neg_map: dict = None,
302
+ neg_ratio: float = 1.0,
303
+ ):
304
+ """Prepare a batch for CLS fine-tuning: positive + negative edges.
305
+
306
+ Args:
307
+ neg_map: Pre-computed (src, dst, etype) -> neg_dst dict. When provided,
308
+ negatives are guaranteed to have a different label from dst and
309
+ not to be real edges. Falls back to random node otherwise.
310
+
311
+ Returns:
312
+ input_ids: [B, L]
313
+ attention_mask: [B, L]
314
+ target_mask: [B, L]
315
+ labels: [B, 1]
316
+ """
317
+ all_nodes = list(sampler.nodes)
318
+ batch_input_ids = []
319
+ batch_attn = []
320
+ batch_target = []
321
+ batch_labels = []
322
+
323
+ for src, dst, etype, ts in edges:
324
+ # Positive edge
325
+ walk_nodes, walk_edge_types = sampler.sample_bidirectional_walk(src, max_ts=ts, walk_length=walk_length)
326
+ dst_walk_nodes, dst_walk_edge_types = sampler.sample_context_walk(dst, max_ts=ts, walk_length=walk_length)
327
+ tok_ids, attn, tgt_mask = tokenizer.tokenize_for_finetune(
328
+ walk_nodes, walk_edge_types, dst, etype, indexid2msg, mode="cls",
329
+ dst_walk_nodes=dst_walk_nodes, dst_walk_edge_types=dst_walk_edge_types,
330
+ )
331
+ batch_input_ids.append(tok_ids)
332
+ batch_attn.append(attn)
333
+ batch_target.append(tgt_mask)
334
+ batch_labels.append(0.0) # Normal
335
+
336
+ # Hard negative: pre-computed (different label, not a real edge) or random
337
+ if neg_map is not None:
338
+ neg_dst = neg_map.get((str(src), str(dst), str(etype)), str(random.choice(all_nodes)))
339
+ else:
340
+ neg_dst = str(random.choice(all_nodes))
341
+ neg_dst_walk_nodes, neg_dst_walk_edge_types = sampler.sample_context_walk(neg_dst, max_ts=ts, walk_length=walk_length)
342
+ tok_ids, attn, tgt_mask = tokenizer.tokenize_for_finetune(
343
+ walk_nodes, walk_edge_types, str(neg_dst), etype, indexid2msg, mode="cls",
344
+ dst_walk_nodes=neg_dst_walk_nodes, dst_walk_edge_types=neg_dst_walk_edge_types,
345
+ )
346
+ batch_input_ids.append(tok_ids)
347
+ batch_attn.append(attn)
348
+ batch_target.append(tgt_mask)
349
+ batch_labels.append(1.0) # Anomalous
350
+
351
+ # Pad to max length
352
+ input_ids = pad_tensor_batch(batch_input_ids, pad_value=tokenizer.pad_id)
353
+ attention_mask = pad_tensor_batch(batch_attn, pad_value=0)
354
+ target_mask = pad_tensor_batch(batch_target, pad_value=0)
355
+
356
+ labels = torch.tensor(batch_labels, dtype=torch.float32).unsqueeze(-1)
357
+ return input_ids, attention_mask, target_mask, labels
358
+
359
+
360
+ def _prepare_finetune_batch_lp(
361
+ edges: List[Tuple[str, str, str, float]],
362
+ sampler: ProvenanceWalkSampler,
363
+ tokenizer: ProvenanceTokenizer,
364
+ indexid2msg: dict,
365
+ walk_length: int,
366
+ ):
367
+ """Prepare a batch for LP fine-tuning: mask destination, predict tokens.
368
+
369
+ Returns:
370
+ input_ids: [B, L]
371
+ attention_mask: [B, L]
372
+ target_mask: [B, L]
373
+ target_token_ids: [B, L]
374
+ """
375
+ batch_input_ids = []
376
+ batch_attn = []
377
+ batch_target_mask = []
378
+ batch_target_ids = []
379
+
380
+ for src, dst, etype, ts in edges:
381
+ walk_nodes, walk_edge_types = sampler.sample_bidirectional_walk(src, max_ts=ts, walk_length=walk_length)
382
+
383
+ # Get full tokenization (to know dst tokens)
384
+ tok_ids_full, attn_full, _ = tokenizer.tokenize_for_finetune(
385
+ walk_nodes, walk_edge_types, dst, etype, indexid2msg, mode="cls"
386
+ )
387
+
388
+ # Get masked version
389
+ tok_ids_masked, attn_masked, tgt_mask = tokenizer.tokenize_for_finetune(
390
+ walk_nodes, walk_edge_types, dst, etype, indexid2msg, mode="lp"
391
+ )
392
+
393
+ # Build target: true token IDs where masked, -100 elsewhere
394
+ target_ids = torch.full_like(tok_ids_masked, -100)
395
+ # The LP mask positions correspond to the destination tokens
396
+ mask_positions = tgt_mask.nonzero(as_tuple=True)[0]
397
+
398
+ # Get actual destination tokens for targets
399
+ if dst in indexid2msg:
400
+ dst_type, dst_label = indexid2msg[dst]
401
+ dst_tokens = tokenizer.tokenize_node(dst_type, dst_label)
402
+ for j, pos in enumerate(mask_positions):
403
+ if j < len(dst_tokens):
404
+ target_ids[pos] = dst_tokens[j]
405
+
406
+ batch_input_ids.append(tok_ids_masked)
407
+ batch_attn.append(attn_masked)
408
+ batch_target_mask.append(tgt_mask)
409
+ batch_target_ids.append(target_ids)
410
+
411
+ # Pad
412
+ input_ids = pad_tensor_batch(batch_input_ids, pad_value=tokenizer.pad_id)
413
+ attention_mask = pad_tensor_batch(batch_attn, pad_value=0)
414
+ target_mask = pad_tensor_batch(batch_target_mask, pad_value=0)
415
+ target_token_ids = pad_tensor_batch(batch_target_ids, pad_value=-100)
416
+
417
+ return input_ids, attention_mask, target_mask, target_token_ids
418
+
419
+
420
+ # ── TGN helpers ────────────────────────────────────────────────────────────────
421
+
422
+ def _build_node_to_idx(indexid2msg: dict) -> dict:
423
+ """Build str(node_id) -> contiguous index mapping. Index 0 reserved for unknown."""
424
+ sorted_keys = sorted(indexid2msg.keys(), key=lambda x: int(x))
425
+ return {str(k): i + 1 for i, k in enumerate(sorted_keys)}
426
+
427
+
428
+ def _precompute_cross_type_negatives(
429
+ edges: List[Tuple],
430
+ indexid2msg: dict,
431
+ node_to_idx: dict,
432
+ ) -> dict:
433
+ """Pre-compute cross-type negative dst per unique (src, dst, etype) triple.
434
+
435
+ Each negative is a node of a DIFFERENT type than dst (e.g. file -> subject,
436
+ subject -> netflow), creating structurally implausible edges that are
437
+ maximally separated from benign ones in feature space. This ensures the
438
+ classifier learns a wide decision boundary, minimizing false positives.
439
+
440
+ Returns: {(src, dst, etype): neg_dst_str}
441
+ """
442
+ type_to_nodes: dict = defaultdict(list)
443
+ for node_id, (node_type, _) in indexid2msg.items():
444
+ nid_str = str(node_id)
445
+ if nid_str in node_to_idx:
446
+ type_to_nodes[node_type].append(nid_str)
447
+
448
+ all_types = list(type_to_nodes.keys())
449
+ all_node_ids = list(node_to_idx.keys())
450
+
451
+ unique_keys = dict.fromkeys(
452
+ (str(e[0]), str(e[1]), str(e[2])) for e in edges
453
+ )
454
+
455
+ neg_map: dict = {}
456
+ for src, dst, etype in unique_keys:
457
+ dst_info = indexid2msg.get(dst)
458
+ if dst_info:
459
+ dst_type = dst_info[0]
460
+ other_types = [t for t in all_types if t != dst_type]
461
+ if other_types:
462
+ neg_type = random.choice(other_types)
463
+ neg_map[(src, dst, etype)] = random.choice(type_to_nodes[neg_type])
464
+ continue
465
+ # Fallback: random node (only if dst type unknown or all nodes share one type)
466
+ neg_map[(src, dst, etype)] = random.choice(all_node_ids)
467
+
468
+ return neg_map
469
+
470
+
471
+ def _precompute_entity_embeddings(
472
+ cfg,
473
+ indexid2msg: dict,
474
+ node_to_idx: dict,
475
+ num_nodes: int,
476
+ entity_emb_dim: int,
477
+ device: str,
478
+ ) -> torch.Tensor:
479
+ """Pre-compute static BERT embeddings for all entities via mean pooling.
480
+
481
+ Runs each entity's (type, label) tokens through frozen pretrained BERT,
482
+ mean-pools over non-padding positions to get a single [H] vector.
483
+
484
+ Returns: [num_nodes, entity_emb_dim] tensor.
485
+ """
486
+ pretrain_cfg = cfg.featurization.pretrained
487
+ model_type = pretrain_cfg.model_type
488
+ model_size = pretrain_cfg.model_size
489
+ pretrain_dir = cfg.featurization._model_dir
490
+ batch_size = pretrain_cfg.training.batch_size
491
+
492
+ # Use a large batch size since node labels are very short (~5 tokens vs 128 for walks)
493
+ emb_batch_size = batch_size * 16
494
+
495
+ # Load tokenizer
496
+ tokenizer = ProvenanceTokenizer(cfg)
497
+ tokenizer.load(os.path.join(pretrain_dir, "tokenizer.pt"))
498
+
499
+ # Load pretrained backbone
500
+ if model_type == "ropebert":
501
+ from .models.ropebert import ProvenanceRoPEBERT
502
+ rope_theta = getattr(pretrain_cfg, 'rope_theta', 10000.0)
503
+ bert_config = get_ropebert_config(
504
+ tokenizer.vocab_size, model_size, tokenizer.max_seq_len,
505
+ rope_theta=rope_theta,
506
+ )
507
+ bert = ProvenanceRoPEBERT(bert_config)
508
+ elif model_type == "modernbert":
509
+ from .models.modernbert import ProvenanceModernBERT
510
+ bert_config = get_modernbert_config(
511
+ tokenizer.vocab_size, model_size, tokenizer.max_seq_len,
512
+ global_attn_every_n_layers=pretrain_cfg.global_attn_every_n_layers,
513
+ local_attention_window=pretrain_cfg.local_attention_window,
514
+ )
515
+ bert = ProvenanceModernBERT(bert_config)
516
+ else:
517
+ from .models.bert import ProvenanceBERT
518
+ bert_config = get_bert_config(tokenizer.vocab_size, model_size, tokenizer.max_seq_len)
519
+ bert = ProvenanceBERT(bert_config)
520
+
521
+ pt_path = os.path.join(pretrain_dir, f"pretrain_{model_size}.pt")
522
+
523
+ sd = torch.load(pt_path, weights_only=True, map_location="cpu")
524
+ bert.load_state_dict(sd)
525
+ bert = bert.to(device)
526
+ bert.eval()
527
+
528
+ entity_embs = torch.zeros(num_nodes, entity_emb_dim)
529
+
530
+ # Build list sorted by contiguous index for deterministic batching
531
+ items = sorted(
532
+ ((str(nid), ntype, nlabel) for nid, (ntype, nlabel) in indexid2msg.items()),
533
+ key=lambda x: node_to_idx.get(x[0], 0),
534
+ )
535
+
536
+ total_batches = (len(items) + emb_batch_size - 1) // emb_batch_size
537
+ for batch_idx, batch_start in enumerate(range(0, len(items), emb_batch_size)):
538
+ batch = items[batch_start:batch_start + emb_batch_size]
539
+
540
+ if batch_idx % 20 == 0:
541
+ log(f" Embedding batch {batch_idx+1}/{total_batches} ({batch_start:,}/{len(items):,} nodes)")
542
+
543
+
544
+ batch_token_ids = []
545
+ batch_indices = []
546
+ for nid_str, ntype, nlabel in batch:
547
+ idx = node_to_idx.get(nid_str)
548
+ if idx is None:
549
+ continue
550
+ tids = tokenizer.tokenize_node(ntype, nlabel)
551
+ if tids:
552
+ batch_token_ids.append(tids)
553
+ batch_indices.append(idx)
554
+
555
+ if not batch_token_ids:
556
+ continue
557
+
558
+ input_ids, attention_mask = pad_token_id_lists(batch_token_ids, tokenizer.pad_id, tokenizer.max_seq_len)
559
+
560
+ with torch.no_grad():
561
+ hidden = bert.modified_fwd(
562
+ input_ids.to(device),
563
+ attention_mask.to(device),
564
+ labels=torch.full_like(input_ids, -100).to(device),
565
+ skip_cls=True,
566
+ ) # [B, max_len, H]
567
+
568
+ # Mean pool over non-padding positions
569
+ mask_f = attention_mask.to(device).unsqueeze(-1).float()
570
+ pooled = (hidden * mask_f).sum(dim=1) / mask_f.sum(dim=1).clamp(min=1)
571
+
572
+ for i, idx in enumerate(batch_indices):
573
+ entity_embs[idx] = pooled[i].cpu()
574
+
575
+ del bert
576
+ if torch.cuda.is_available():
577
+ torch.cuda.empty_cache()
578
+
579
+ log(f"Pre-computed entity embeddings: {entity_embs.shape}")
580
+ return entity_embs
581
+
582
+
583
+
584
+ def _train_edge_cls(cfg):
585
+ """Edge type classification from BERT embeddings.
586
+
587
+ Path mode: static entity embeddings per node (existing behavior).
588
+ Event mode: per-edge contextual embeddings from masked-event BERT pass.
589
+
590
+ Predicts edge type given (src, dst) BERT embeddings. No temporal memory
591
+ or state — edges are shuffled each epoch. CE loss, anomaly score = CE of
592
+ true edge type.
593
+ """
594
+ log_start(__file__)
595
+
596
+ from .models.tgn import EdgeTypeClassifier
597
+ import torch.nn as nn
598
+
599
+ pretrain_cfg = cfg.featurization.pretrained
600
+ detect_cfg = cfg.training.pretrained
601
+ model_size = pretrain_cfg.model_size
602
+ finetune_epochs = detect_cfg.finetune_epochs
603
+ finetune_lr = detect_cfg.finetune_lr
604
+ scheduler_type = pretrain_cfg.training.scheduler
605
+
606
+ device = "cuda" if torch.cuda.is_available() and not cfg._use_cpu else "cpu"
607
+ ft_dir = cfg.training._trained_models_dir
608
+ os.makedirs(ft_dir, exist_ok=True)
609
+
610
+ H = MODEL_SIZES[model_size].H
611
+ tgn_cfg = detect_cfg.tgn
612
+ hidden_dim = tgn_cfg.edge_emb_dim
613
+ batch_size = tgn_cfg.batch_size
614
+
615
+ # ── Data loading ───────────────────────────────────────────────
616
+ indexid2msg = get_indexid2msg(cfg)
617
+ rel2id = get_rel2id(cfg)
618
+ base_dir = cfg.transformation._graphs_dir
619
+ train_graph_paths = get_all_graphs_for_dates(base_dir, cfg.dataset.train_dates)
620
+
621
+ node_to_idx = _build_node_to_idx(indexid2msg)
622
+ num_nodes = len(node_to_idx) + 1
623
+
624
+ edge_type_to_id = {k: v for k, v in rel2id.items() if isinstance(k, str)}
625
+ num_edge_types = max(edge_type_to_id.values()) + 1 if edge_type_to_id else 1
626
+
627
+ train_edges = []
628
+ for p in train_graph_paths:
629
+ g = torch.load(p, weights_only=False)
630
+ train_edges.extend(_collect_edges(g))
631
+ log(f"Training edges: {len(train_edges)}")
632
+
633
+ # ── Embeddings ─────────────────────────────────────────────────
634
+ entity_embs_path = os.path.join(ft_dir, "entity_embs_tgn.pt")
635
+ if os.path.exists(entity_embs_path):
636
+ entity_embs = torch.load(entity_embs_path, map_location="cpu")
637
+ log(f"Loaded cached entity embeddings: {entity_embs.shape}")
638
+ else:
639
+ log("Pre-computing entity BERT embeddings...")
640
+ entity_embs = _precompute_entity_embeddings(
641
+ cfg, indexid2msg, node_to_idx, num_nodes, H, device,
642
+ )
643
+ torch.save(entity_embs, entity_embs_path)
644
+
645
+ model = EdgeTypeClassifier(
646
+ num_nodes=num_nodes,
647
+ num_edge_types=num_edge_types,
648
+ entity_emb_dim=H,
649
+ hidden_dim=hidden_dim,
650
+ ).to(device)
651
+ model.set_entity_embeddings(entity_embs)
652
+
653
+ log(f"EdgeTypeClassifier: {sum(p.numel() for p in model.parameters()):,} params, "
654
+ f"{num_nodes:,} entities, {num_edge_types} edge types")
655
+
656
+ opt = AdamW(model.parameters(), lr=finetune_lr, betas=(0.9, 0.99),
657
+ eps=1e-10, weight_decay=0.02)
658
+ updates_per_epoch = max(1, len(train_edges) // batch_size)
659
+ total_steps = updates_per_epoch * finetune_epochs
660
+ warmup_steps = max(1, total_steps // 20)
661
+ if scheduler_type == "cosine":
662
+ scheduler = WarmupCosineScheduler(opt, warmup_steps, total_steps)
663
+ else:
664
+ scheduler = WarmupLinearScheduler(opt, warmup_steps, total_steps)
665
+
666
+ log_path = os.path.join(ft_dir, f"finetune_edge_cls_{model_size}_log.txt")
667
+ with open(log_path, "w") as f:
668
+ f.write("epoch,update,loss,lr\n")
669
+
670
+ best_loss = float("inf")
671
+ updates = 0
672
+
673
+ for epoch in range(finetune_epochs):
674
+ model.train()
675
+ random.shuffle(train_edges)
676
+
677
+ epoch_loss = 0.0
678
+ n_batches = 0
679
+ st = time.time()
680
+
681
+ for batch_start in range(0, len(train_edges), batch_size):
682
+ batch_edges = train_edges[batch_start:batch_start + batch_size]
683
+
684
+ src_idx = torch.tensor(
685
+ [node_to_idx.get(e[0], 0) for e in batch_edges],
686
+ dtype=torch.long, device=device)
687
+ dst_idx = torch.tensor(
688
+ [node_to_idx.get(e[1], 0) for e in batch_edges],
689
+ dtype=torch.long, device=device)
690
+ etypes = torch.tensor(
691
+ [edge_type_to_id.get(e[2], 0) for e in batch_edges],
692
+ dtype=torch.long, device=device)
693
+
694
+ logits = model.predict(src_idx, dst_idx)
695
+ loss = F.cross_entropy(logits, etypes)
696
+
697
+ loss.backward()
698
+ torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
699
+ opt.step()
700
+ opt.zero_grad()
701
+ scheduler.step()
702
+
703
+ epoch_loss += loss.item()
704
+ n_batches += 1
705
+ updates += 1
706
+
707
+ if updates % 50 == 0:
708
+ lr = scheduler.get_last_lr()[0]
709
+ log(f"[e{epoch+1}|u{updates}] loss={loss.item():.4f} lr={lr:.2e}")
710
+
711
+ avg_loss = epoch_loss / max(1, n_batches)
712
+ elapsed = time.time() - st
713
+ log(f"Epoch {epoch+1}/{finetune_epochs}: avg_loss={avg_loss:.4f} ({elapsed:.1f}s)")
714
+
715
+ with open(log_path, "a") as f:
716
+ f.write(f"{epoch+1},{updates},{avg_loss:.6f},{scheduler.get_last_lr()[0]:.2e}\n")
717
+
718
+ ckpt = {
719
+ "model_state_dict": model.state_dict(),
720
+ "node_to_idx": node_to_idx,
721
+ "edge_type_to_id": edge_type_to_id,
722
+ "num_nodes": num_nodes,
723
+ "num_edge_types": num_edge_types,
724
+ "pretrain_mode": "path",
725
+ "edge_cls_config": {
726
+ "entity_emb_dim": H,
727
+ "hidden_dim": hidden_dim,
728
+ },
729
+ }
730
+ save_path = os.path.join(ft_dir, f"finetune_edge_cls_{model_size}.pt")
731
+ torch.save(ckpt, save_path)
732
+
733
+ if avg_loss < best_loss:
734
+ best_loss = avg_loss
735
+ best_path = os.path.join(ft_dir, f"finetune_edge_cls_{model_size}_best.pt")
736
+ torch.save(ckpt, best_path)
737
+
738
+ log(f"Edge classification training complete. Best loss: {best_loss:.4f}")
739
+
740
+
741
+ def _train_tgn(cfg):
742
+ """Self-supervised TGN training.
743
+
744
+ Five objectives are supported (tgn.objective):
745
+ contrastive — BCE loss with two-tier negative sampling (same-type +
746
+ cross-type corrupted dst). Score at inference = raw binary logit.
747
+ edge_pred — cross-entropy loss predicting the edge type from entity
748
+ memories and embeddings (no negative sampling needed). Score at
749
+ inference = per-edge CE loss of the true edge type.
750
+ multi_edge_pred — like edge_pred but groups edges by (src, dst) pair
751
+ within each batch and uses multi-hot BCE to predict ALL co-occurring
752
+ edge types. Score at inference = per-edge binary CE of the true type.
753
+ dist_edge_pred — groups edges by (src, dst) pair and predicts the
754
+ proportion of each edge type (count distribution). KL divergence
755
+ loss. Score at inference = -log P(true_type) under the predicted
756
+ distribution.
757
+ edge_pred_emb — predicts both the edge type (CE) and the edge embedding
758
+ vector (MSE). Score at inference = CE + MSE per edge.
759
+
760
+ No attack labels are used in any mode.
761
+ """
762
+ log_start(__file__)
763
+
764
+ pretrain_cfg = cfg.featurization.pretrained
765
+ detect_cfg = cfg.training.pretrained
766
+ model_size = pretrain_cfg.model_size
767
+ finetune_epochs = detect_cfg.finetune_epochs
768
+ finetune_lr = detect_cfg.finetune_lr
769
+ scheduler_type = pretrain_cfg.training.scheduler
770
+
771
+ device = "cuda" if torch.cuda.is_available() and not cfg._use_cpu else "cpu"
772
+ ft_dir = cfg.training._trained_models_dir
773
+ os.makedirs(ft_dir, exist_ok=True)
774
+
775
+ # ── TGN config ─────────────────────────────────────────────────
776
+ H = MODEL_SIZES[model_size].H
777
+ tgn_cfg = detect_cfg.tgn
778
+ memory_dim = tgn_cfg.memory_dim
779
+ edge_emb_dim = tgn_cfg.edge_emb_dim
780
+ time_dim = tgn_cfg.time_dim
781
+ num_heads = tgn_cfg.num_heads
782
+ tgn_batch_size = tgn_cfg.batch_size
783
+ use_node_type_emb = tgn_cfg.use_node_type_emb
784
+ use_time_emb = tgn_cfg.use_time_emb
785
+ use_memory = tgn_cfg.use_memory
786
+ use_entity_emb = tgn_cfg.use_entity_emb
787
+ score_gated_memory = tgn_cfg.score_gated_memory
788
+ temporal_decay = tgn_cfg.temporal_decay
789
+ anomaly_accumulator = tgn_cfg.anomaly_accumulator
790
+ objective = tgn_cfg.objective # "contrastive" / "edge_pred" / "multi_edge_pred"
791
+
792
+ use_event_bert_emb = False
793
+
794
+ # ── Data loading ───────────────────────────────────────────────
795
+ indexid2msg = get_indexid2msg(cfg)
796
+ rel2id = get_rel2id(cfg)
797
+ base_dir = cfg.transformation._graphs_dir
798
+ train_graph_paths = get_all_graphs_for_dates(base_dir, cfg.dataset.train_dates)
799
+
800
+ node_to_idx = _build_node_to_idx(indexid2msg)
801
+ num_nodes = len(node_to_idx) + 1 # +1 for index-0 unknown sentinel
802
+
803
+ # Build node type tensor: [num_nodes] mapping contiguous idx -> type ID
804
+ node_types_tensor = torch.zeros(num_nodes, dtype=torch.long)
805
+ for nid_str, (ntype, _) in indexid2msg.items():
806
+ idx = node_to_idx.get(str(nid_str))
807
+ if idx is not None:
808
+ node_types_tensor[idx] = ntype2id.get(ntype, 0)
809
+
810
+ edge_type_to_id = {k: v for k, v in rel2id.items() if isinstance(k, str)}
811
+ num_edge_types = max(edge_type_to_id.values()) + 1 if edge_type_to_id else 1
812
+
813
+ # Collect and sort all training edges by timestamp
814
+ train_edges = []
815
+ for p in train_graph_paths:
816
+ g = torch.load(p, weights_only=False)
817
+ train_edges.extend(_collect_edges(g))
818
+ train_edges.sort(key=lambda e: e[3])
819
+ log(f"Training edges: {len(train_edges)} (sorted by time)")
820
+
821
+ # ── Negative sampling (contrastive only) ─────────────────────
822
+ if objective == "contrastive":
823
+ type_to_labeled = _build_neg_index(indexid2msg)
824
+ real_edge_set: set = set()
825
+ for p in train_graph_paths:
826
+ g = torch.load(p, weights_only=False)
827
+ for src, dst, _, attrs in g.edges(data=True, keys=True):
828
+ real_edge_set.add((str(src), str(dst), attrs.get("label", "")))
829
+ neg_map_same = _precompute_negatives(train_edges, indexid2msg, type_to_labeled, real_edge_set)
830
+ neg_map_cross = _precompute_cross_type_negatives(train_edges, indexid2msg, node_to_idx)
831
+ log(f"Pre-computed negatives for {len(neg_map_same)} unique triples "
832
+ f"(same-type + cross-type, 2 per benign edge)")
833
+ else:
834
+ log(f"Objective: {objective} (no negative sampling needed)")
835
+
836
+ # ── Entity embeddings ──────────────────────────────────────────
837
+ entity_embs_path = os.path.join(ft_dir, "entity_embs_tgn.pt")
838
+ if os.path.exists(entity_embs_path):
839
+ entity_embs = torch.load(entity_embs_path, map_location="cpu")
840
+ log(f"Loaded cached entity embeddings: {entity_embs.shape}")
841
+ else:
842
+ log("Pre-computing entity BERT embeddings...")
843
+ entity_embs = _precompute_entity_embeddings(
844
+ cfg, indexid2msg, node_to_idx, num_nodes, H, device,
845
+ )
846
+ torch.save(entity_embs, entity_embs_path)
847
+
848
+ edge_to_pair_idx = None
849
+ event_src_embs_gpu = None
850
+ event_dst_embs_gpu = None
851
+ event_bert_emb_dim = 0
852
+
853
+ # ── Build model ────────────────────────────────────────────────
854
+ model = ProvenanceTGN(
855
+ num_nodes=num_nodes,
856
+ num_edge_types=num_edge_types,
857
+ entity_emb_dim=H,
858
+ memory_dim=memory_dim,
859
+ edge_emb_dim=edge_emb_dim,
860
+ time_dim=time_dim,
861
+ num_heads=num_heads,
862
+ use_node_type_emb=use_node_type_emb,
863
+ use_time_emb=use_time_emb,
864
+ use_memory=use_memory,
865
+ use_entity_emb=use_entity_emb,
866
+ use_event_bert_emb=use_event_bert_emb,
867
+ event_bert_emb_dim=event_bert_emb_dim,
868
+ score_gated_memory=score_gated_memory,
869
+ temporal_decay=temporal_decay,
870
+ anomaly_accumulator=anomaly_accumulator,
871
+ device=device,
872
+ ).to(device)
873
+ model.set_entity_embeddings(entity_embs)
874
+ model.set_node_types(node_types_tensor)
875
+ log(f"TGN model: {sum(p.numel() for p in model.parameters()):,} trainable params, "
876
+ f"{num_nodes:,} entities, {num_edge_types} edge types, "
877
+ f"use_memory={use_memory}, use_entity_emb={use_entity_emb}, "
878
+ f"use_event_bert_emb={use_event_bert_emb}, "
879
+ f"score_gated={score_gated_memory}, decay={temporal_decay}, accum={anomaly_accumulator}")
880
+
881
+ # ── Optimizer & scheduler ──────────────────────────────────────
882
+ opt = AdamW(model.parameters(), lr=finetune_lr, betas=(0.9, 0.99), eps=1e-10, weight_decay=0.02)
883
+ updates_per_epoch = max(1, len(train_edges) // tgn_batch_size)
884
+ total_steps = updates_per_epoch * finetune_epochs
885
+ warmup_steps = max(1, total_steps // 20)
886
+ if scheduler_type == "cosine":
887
+ scheduler = WarmupCosineScheduler(opt, warmup_steps, total_steps)
888
+ else:
889
+ scheduler = WarmupLinearScheduler(opt, warmup_steps, total_steps)
890
+
891
+ # ── Training loop ──────────────────────────────────────────────
892
+ log_path = os.path.join(ft_dir, f"finetune_tgn_{model_size}_log.txt")
893
+ with open(log_path, "w") as f:
894
+ f.write("epoch,update,loss,lr\n")
895
+
896
+ all_node_keys = list(node_to_idx.keys())
897
+ best_loss = float("inf")
898
+ updates = 0
899
+
900
+ for epoch in range(finetune_epochs):
901
+ model.train()
902
+ model.reset_memory()
903
+
904
+ epoch_loss = 0.0
905
+ n_batches = 0
906
+ st = time.time()
907
+
908
+ # Process edges in TEMPORAL order (no shuffling)
909
+ for batch_start in range(0, len(train_edges), tgn_batch_size):
910
+ batch_edges = train_edges[batch_start:batch_start + tgn_batch_size]
911
+
912
+ src_idx = torch.tensor(
913
+ [node_to_idx.get(e[0], 0) for e in batch_edges], dtype=torch.long, device=device)
914
+ dst_idx = torch.tensor(
915
+ [node_to_idx.get(e[1], 0) for e in batch_edges], dtype=torch.long, device=device)
916
+ etypes = torch.tensor(
917
+ [edge_type_to_id.get(e[2], 0) for e in batch_edges], dtype=torch.long, device=device)
918
+ ts = torch.tensor(
919
+ [e[3] for e in batch_edges], dtype=torch.long, device=device)
920
+
921
+ # Look up precomputed per-edge contextual embeddings for this batch
922
+ if event_src_embs_gpu is not None:
923
+ batch_pair_idx = edge_to_pair_idx[batch_start:batch_start + len(batch_edges)]
924
+ batch_event_src = event_src_embs_gpu[batch_pair_idx]
925
+ batch_event_dst = event_dst_embs_gpu[batch_pair_idx]
926
+ else:
927
+ batch_event_src = None
928
+ batch_event_dst = None
929
+
930
+ if objective == "edge_pred":
931
+ # ── Edge type prediction: predict edge type from memories ──
932
+ logits = model.predict_edge_types(src_idx, dst_idx, ts,
933
+ event_src_emb=batch_event_src, event_dst_emb=batch_event_dst) # [B, num_edge_classes]
934
+ loss = torch.nn.CrossEntropyLoss()(logits, etypes)
935
+ # Per-edge anomaly scores for score-gated memory (detached)
936
+ if score_gated_memory:
937
+ with torch.no_grad():
938
+ edge_scores = torch.nn.functional.cross_entropy(
939
+ logits, etypes, reduction="none")
940
+ else:
941
+ edge_scores = None
942
+
943
+ elif objective == "multi_edge_pred":
944
+ # ── Multi-label edge type prediction ──
945
+ # Group by (src, dst) pair; predict ALL co-occurring edge types
946
+ pair_keys = torch.stack([src_idx, dst_idx], dim=1) # [B, 2]
947
+ unique_pairs, inverse = torch.unique(
948
+ pair_keys, dim=0, return_inverse=True) # [P, 2], [B]
949
+ num_pairs = unique_pairs.size(0)
950
+ num_classes = num_edge_types + 1 # match edge_predictor output
951
+
952
+ # Multi-hot target: which edge types occur for each pair
953
+ multi_hot = torch.zeros(num_pairs, num_classes, device=device)
954
+ multi_hot[inverse, etypes] = 1.0
955
+
956
+ # Use latest timestamp per pair for prediction
957
+ pair_ts = scatter(
958
+ ts, inverse, dim=0, dim_size=num_pairs, reduce="max")
959
+
960
+ # For multi/dist_edge_pred with event embeddings, aggregate per pair
961
+ if batch_event_src is not None:
962
+ pair_event_src = scatter(
963
+ batch_event_src, inverse, dim=0, dim_size=num_pairs, reduce="mean")
964
+ pair_event_dst = scatter(
965
+ batch_event_dst, inverse, dim=0, dim_size=num_pairs, reduce="mean")
966
+ else:
967
+ pair_event_src = None
968
+ pair_event_dst = None
969
+
970
+ logits = model.predict_edge_types(
971
+ unique_pairs[:, 0], unique_pairs[:, 1], pair_ts,
972
+ event_src_emb=pair_event_src, event_dst_emb=pair_event_dst,
973
+ ) # [P, num_classes]
974
+ loss = F.binary_cross_entropy_with_logits(logits, multi_hot)
975
+
976
+ # Per-edge anomaly scores for score-gated memory
977
+ if score_gated_memory:
978
+ with torch.no_grad():
979
+ edge_logits = logits[inverse] # [B, num_classes]
980
+ per_edge_logit = edge_logits[
981
+ torch.arange(len(batch_edges), device=device), etypes]
982
+ edge_scores = F.binary_cross_entropy_with_logits(
983
+ per_edge_logit, torch.ones_like(per_edge_logit),
984
+ reduction="none")
985
+ else:
986
+ edge_scores = None
987
+
988
+ elif objective == "dist_edge_pred":
989
+ # ── Edge type distribution prediction ──
990
+ # Group by (src, dst) pair; predict the proportion of each type
991
+ pair_keys = torch.stack([src_idx, dst_idx], dim=1) # [B, 2]
992
+ unique_pairs, inverse = torch.unique(
993
+ pair_keys, dim=0, return_inverse=True) # [P, 2], [B]
994
+ num_pairs = unique_pairs.size(0)
995
+ num_classes = num_edge_types + 1 # match edge_predictor output
996
+
997
+ # Count edge types per pair → normalize to distribution
998
+ one_hot = torch.zeros(len(batch_edges), num_classes, device=device)
999
+ one_hot[torch.arange(len(batch_edges), device=device), etypes] = 1.0
1000
+ counts = scatter(
1001
+ one_hot, inverse, dim=0, dim_size=num_pairs, reduce="sum")
1002
+ target_dist = counts / counts.sum(dim=1, keepdim=True).clamp(min=1)
1003
+
1004
+ # Use latest timestamp per pair for prediction
1005
+ pair_ts = scatter(
1006
+ ts, inverse, dim=0, dim_size=num_pairs, reduce="max")
1007
+
1008
+ if batch_event_src is not None:
1009
+ pair_event_src = scatter(
1010
+ batch_event_src, inverse, dim=0, dim_size=num_pairs, reduce="mean")
1011
+ pair_event_dst = scatter(
1012
+ batch_event_dst, inverse, dim=0, dim_size=num_pairs, reduce="mean")
1013
+ else:
1014
+ pair_event_src = None
1015
+ pair_event_dst = None
1016
+
1017
+ logits = model.predict_edge_types(
1018
+ unique_pairs[:, 0], unique_pairs[:, 1], pair_ts,
1019
+ event_src_emb=pair_event_src, event_dst_emb=pair_event_dst,
1020
+ ) # [P, num_classes]
1021
+ log_probs = F.log_softmax(logits, dim=-1)
1022
+ loss = F.kl_div(log_probs, target_dist, reduction="batchmean")
1023
+
1024
+ # Per-edge anomaly scores for score-gated memory
1025
+ if score_gated_memory:
1026
+ with torch.no_grad():
1027
+ edge_log_probs = log_probs[inverse] # [B, num_classes]
1028
+ edge_scores = -edge_log_probs[
1029
+ torch.arange(len(batch_edges), device=device), etypes]
1030
+ else:
1031
+ edge_scores = None
1032
+
1033
+ elif objective == "edge_pred_emb":
1034
+ # ── Edge type + embedding prediction ──
1035
+ # CE loss on edge type + MSE loss on edge embedding vector
1036
+ logits = model.predict_edge_types(src_idx, dst_idx, ts,
1037
+ event_src_emb=batch_event_src, event_dst_emb=batch_event_dst)
1038
+ ce_loss = F.cross_entropy(logits, etypes)
1039
+
1040
+ pred_emb = model.predict_edge_embedding(src_idx, dst_idx, ts,
1041
+ event_src_emb=batch_event_src, event_dst_emb=batch_event_dst)
1042
+ target_emb = model.edge_emb(etypes).detach()
1043
+ mse_loss = F.mse_loss(pred_emb, target_emb)
1044
+
1045
+ loss = ce_loss + mse_loss
1046
+
1047
+ # Per-edge anomaly scores for score-gated memory
1048
+ if score_gated_memory:
1049
+ with torch.no_grad():
1050
+ edge_scores = F.cross_entropy(
1051
+ logits, etypes, reduction="none")
1052
+ else:
1053
+ edge_scores = None
1054
+
1055
+ elif objective == "node_pred":
1056
+ # ── Node type prediction: predict dst node type ──
1057
+ logits = model.predict_node_types(src_idx, dst_idx, etypes, ts,
1058
+ event_src_emb=batch_event_src, event_dst_emb=batch_event_dst) # [B, NUM_NODE_TYPES]
1059
+ dst_types = model.node_types[dst_idx] # [B] ground truth
1060
+ loss = F.cross_entropy(logits, dst_types)
1061
+
1062
+ # Per-edge anomaly scores for score-gated memory
1063
+ if score_gated_memory:
1064
+ with torch.no_grad():
1065
+ edge_scores = F.cross_entropy(
1066
+ logits, dst_types, reduction="none")
1067
+ else:
1068
+ edge_scores = None
1069
+
1070
+ else:
1071
+ # ── Contrastive: benign vs negatives ──
1072
+ logits_benign = model.classify_edges(src_idx, dst_idx, etypes, ts,
1073
+ event_src_emb=batch_event_src, event_dst_emb=batch_event_dst)
1074
+ labels_benign = torch.zeros(len(batch_edges), 1, device=device)
1075
+
1076
+ # Tier 1: same-type negative (label=1)
1077
+ neg_same_strs = [
1078
+ neg_map_same.get((e[0], e[1], e[2]), random.choice(all_node_keys))
1079
+ for e in batch_edges
1080
+ ]
1081
+ neg_same_idx = torch.tensor(
1082
+ [node_to_idx.get(n, 0) for n in neg_same_strs], dtype=torch.long, device=device)
1083
+ logits_neg_same = model.classify_edges(src_idx, neg_same_idx, etypes, ts,
1084
+ event_src_emb=batch_event_src, event_dst_emb=batch_event_dst)
1085
+
1086
+ # Tier 2: cross-type negative (label=1)
1087
+ neg_cross_strs = [
1088
+ neg_map_cross.get((e[0], e[1], e[2]), random.choice(all_node_keys))
1089
+ for e in batch_edges
1090
+ ]
1091
+ neg_cross_idx = torch.tensor(
1092
+ [node_to_idx.get(n, 0) for n in neg_cross_strs], dtype=torch.long, device=device)
1093
+ logits_neg_cross = model.classify_edges(src_idx, neg_cross_idx, etypes, ts,
1094
+ event_src_emb=batch_event_src, event_dst_emb=batch_event_dst)
1095
+
1096
+ labels_neg = torch.ones(len(batch_edges) * 2, 1, device=device)
1097
+
1098
+ loss = torch.nn.BCEWithLogitsLoss()(
1099
+ torch.cat([logits_benign, logits_neg_same, logits_neg_cross], dim=0),
1100
+ torch.cat([labels_benign, labels_neg], dim=0),
1101
+ )
1102
+ # Per-edge anomaly scores for score-gated memory (detached)
1103
+ if score_gated_memory:
1104
+ with torch.no_grad():
1105
+ edge_scores = logits_benign.squeeze(-1).clone()
1106
+ else:
1107
+ edge_scores = None
1108
+
1109
+ loss.backward()
1110
+ torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
1111
+ opt.step()
1112
+ opt.zero_grad()
1113
+ scheduler.step()
1114
+
1115
+ # ── Sync differentiable memory to buffer, then update ──
1116
+ # detach_memory() breaks the graph from the previous batch (truncated
1117
+ # BPTT depth 1), then update_memory() creates a fresh _diff_memory
1118
+ # overlay that the NEXT batch's predict/classify will read from.
1119
+ model.detach_memory()
1120
+ model.update_memory(src_idx, dst_idx, etypes, ts, edge_scores=edge_scores)
1121
+
1122
+ epoch_loss += loss.item()
1123
+ n_batches += 1
1124
+ updates += 1
1125
+
1126
+ if updates % 50 == 0:
1127
+ lr = scheduler.get_last_lr()[0]
1128
+ log(f"[e{epoch+1}|u{updates}] loss={loss.item():.4f} lr={lr:.2e}")
1129
+
1130
+ avg_loss = epoch_loss / max(1, n_batches)
1131
+ elapsed = time.time() - st
1132
+ log(f"Epoch {epoch+1}/{finetune_epochs}: avg_loss={avg_loss:.4f} ({elapsed:.1f}s)")
1133
+
1134
+ with open(log_path, "a") as f:
1135
+ f.write(f"{epoch+1},{updates},{avg_loss:.6f},{scheduler.get_last_lr()[0]:.2e}\n")
1136
+
1137
+ # ── Save checkpoint ────────────────────────────────────────
1138
+ ckpt = {
1139
+ "model_state_dict": model.state_dict(),
1140
+ "memory_state": model.get_memory_state(),
1141
+ "node_to_idx": node_to_idx,
1142
+ "edge_type_to_id": edge_type_to_id,
1143
+ "num_nodes": num_nodes,
1144
+ "num_edge_types": num_edge_types,
1145
+ "tgn_config": {
1146
+ "memory_dim": memory_dim,
1147
+ "edge_emb_dim": edge_emb_dim,
1148
+ "time_dim": time_dim,
1149
+ "entity_emb_dim": H,
1150
+ "num_heads": num_heads,
1151
+ "use_node_type_emb": use_node_type_emb,
1152
+ "use_time_emb": use_time_emb,
1153
+ "use_memory": use_memory,
1154
+ "use_entity_emb": use_entity_emb,
1155
+ "score_gated_memory": score_gated_memory,
1156
+ "temporal_decay": temporal_decay,
1157
+ "anomaly_accumulator": anomaly_accumulator,
1158
+ "objective": objective,
1159
+ "use_event_bert_emb": use_event_bert_emb,
1160
+ "event_bert_emb_dim": event_bert_emb_dim,
1161
+ },
1162
+ }
1163
+ save_path = os.path.join(ft_dir, f"finetune_tgn_{model_size}.pt")
1164
+ torch.save(ckpt, save_path)
1165
+
1166
+ if avg_loss < best_loss:
1167
+ best_loss = avg_loss
1168
+ best_path = os.path.join(ft_dir, f"finetune_tgn_{model_size}_best.pt")
1169
+ torch.save(ckpt, best_path)
1170
+
1171
+ log(f"TGN fine-tuning complete. Best loss: {best_loss:.4f}")
1172
+
1173
+
1174
+ def main(cfg):
1175
+ log_start(__file__)
1176
+
1177
+ pretrain_cfg = cfg.featurization.pretrained
1178
+ detect_cfg = cfg.training.pretrained
1179
+ model_type = pretrain_cfg.model_type
1180
+ model_size = pretrain_cfg.model_size
1181
+ finetune_mode = detect_cfg.finetune_mode
1182
+
1183
+ # TGN uses a completely different pipeline (no walks, no BERT sequence classification)
1184
+ if finetune_mode == "tgn":
1185
+ _train_tgn(cfg)
1186
+ return
1187
+
1188
+ if finetune_mode == "edge_cls":
1189
+ _train_edge_cls(cfg)
1190
+ return
1191
+
1192
+ if finetune_mode == "perplexity":
1193
+ log("Perplexity mode: no fine-tuning needed (pretrained model used directly)")
1194
+ return
1195
+
1196
+ finetune_epochs = detect_cfg.finetune_epochs
1197
+ finetune_walk_len = detect_cfg.finetune_walk_len
1198
+ finetune_lr = detect_cfg.finetune_lr
1199
+ finetune_margin = detect_cfg.finetune_margin
1200
+ freeze_backbone = detect_cfg.freeze_backbone
1201
+ if finetune_mode == "lp" and freeze_backbone:
1202
+ freeze_backbone = False # LP has no extra parameters; must train the backbone
1203
+ batch_size = pretrain_cfg.training.batch_size
1204
+ num_walks = detect_cfg.num_inference_walks
1205
+ time_weight = pretrain_cfg.walks.time_weight
1206
+ half_life = pretrain_cfg.walks.half_life
1207
+ scheduler_type = pretrain_cfg.training.scheduler
1208
+
1209
+ device = "cuda" if torch.cuda.is_available() and not cfg._use_cpu else "cpu"
1210
+
1211
+ # ── Directories ────────────────────────────────────────────────────
1212
+ pretrain_dir = cfg.featurization._model_dir
1213
+ ft_dir = cfg.training._trained_models_dir
1214
+ os.makedirs(ft_dir, exist_ok=True)
1215
+
1216
+ # ── Load tokenizer ──────────────────────────────────────────────────
1217
+ tokenizer = ProvenanceTokenizer(cfg)
1218
+ tokenizer.load(os.path.join(pretrain_dir, "tokenizer.pt"))
1219
+ log(f"Loaded tokenizer (vocab_size={tokenizer.vocab_size})")
1220
+
1221
+ # ── Load pretrained model ───────────────────────────────────────────
1222
+ if model_type == "ropebert":
1223
+ rope_theta = getattr(pretrain_cfg, 'rope_theta', 10000.0)
1224
+ bert_config = get_ropebert_config(
1225
+ tokenizer.vocab_size, model_size, tokenizer.max_seq_len,
1226
+ rope_theta=rope_theta,
1227
+ )
1228
+ log(f"Using RoPEBERT architecture (theta={rope_theta})")
1229
+ elif model_type == "modernbert":
1230
+ bert_config = get_modernbert_config(
1231
+ tokenizer.vocab_size, model_size, tokenizer.max_seq_len,
1232
+ global_attn_every_n_layers=pretrain_cfg.global_attn_every_n_layers,
1233
+ local_attention_window=pretrain_cfg.local_attention_window,
1234
+ )
1235
+ log(f"Using ModernBERT architecture (global every {pretrain_cfg.global_attn_every_n_layers}, "
1236
+ f"window {pretrain_cfg.local_attention_window})")
1237
+ else:
1238
+ bert_config = get_bert_config(tokenizer.vocab_size, model_size, tokenizer.max_seq_len)
1239
+ log(f"Using traditional BERT architecture")
1240
+
1241
+ pretrained_path = os.path.join(pretrain_dir, f"pretrain_{model_size}.pt")
1242
+
1243
+ sd = torch.load(pretrained_path, weights_only=True, map_location="cpu")
1244
+ log(f"Loaded pretrained weights from {pretrained_path}")
1245
+
1246
+ # cls_attack uses BCE (margin=0); cls uses the configured ranking margin
1247
+ cls_margin = 0 if finetune_mode == "cls_attack" else finetune_margin
1248
+
1249
+ if model_type == "ropebert":
1250
+ if finetune_mode in ("cls", "cls_attack"):
1251
+ model = ProvenanceRoPEBERTFineTuneCLS(bert_config, sd, device=device, freeze_backbone=freeze_backbone, margin=cls_margin)
1252
+ elif finetune_mode == "lp":
1253
+ model = ProvenanceRoPEBERTFineTuneLP(bert_config, sd, device=device, freeze_backbone=freeze_backbone)
1254
+ else:
1255
+ raise ValueError(f"Unknown finetune mode: {finetune_mode}")
1256
+ elif model_type == "modernbert":
1257
+ if finetune_mode in ("cls", "cls_attack"):
1258
+ model = ProvenanceModernBERTFineTuneCLS(bert_config, sd, device=device, freeze_backbone=freeze_backbone, margin=cls_margin)
1259
+ elif finetune_mode == "lp":
1260
+ model = ProvenanceModernBERTFineTuneLP(bert_config, sd, device=device, freeze_backbone=freeze_backbone)
1261
+ else:
1262
+ raise ValueError(f"Unknown finetune mode: {finetune_mode}")
1263
+ else:
1264
+ if finetune_mode in ("cls", "cls_attack"):
1265
+ model = ProvenanceBERTFineTuneCLS(bert_config, sd, device=device, freeze_backbone=freeze_backbone, margin=cls_margin)
1266
+ elif finetune_mode == "lp":
1267
+ model = ProvenanceBERTFineTuneLP(bert_config, sd, device=device, freeze_backbone=freeze_backbone)
1268
+ else:
1269
+ raise ValueError(f"Unknown finetune mode: {finetune_mode}")
1270
+
1271
+ log(f"Fine-tuning {model_type} in {finetune_mode} mode (freeze={freeze_backbone})")
1272
+
1273
+ # ── Load data ───────────────────────────────────────────────────────
1274
+ indexid2msg = get_indexid2msg(cfg)
1275
+ base_dir = cfg.transformation._graphs_dir
1276
+ train_graph_paths = get_all_graphs_for_dates(base_dir, cfg.dataset.train_dates)
1277
+
1278
+ log(f"Loading training graphs...")
1279
+ train_graphs = [torch.load(p) for p in train_graph_paths]
1280
+ train_samplers = [
1281
+ ProvenanceWalkSampler(g, walk_length=finetune_walk_len, num_walks=num_walks, time_weight=time_weight, half_life=half_life)
1282
+ for g in train_graphs
1283
+ ]
1284
+
1285
+ # Collect all training edges
1286
+ train_edges = []
1287
+ for g in train_graphs:
1288
+ train_edges.extend(_collect_edges(g))
1289
+ log(f"Training edges: {len(train_edges)}")
1290
+
1291
+ # ── Negative sampling pre-computation (cls mode only) ───────────────
1292
+ # Build once before training. Groups nodes by (type, label) so each
1293
+ # negative has the same node type as dst but a different textual label
1294
+ # (different tokens). Also checks against the real edge set so we never
1295
+ # use an edge that already exists in the training graphs.
1296
+ train_neg_map = None
1297
+ if finetune_mode == "cls":
1298
+ type_to_labeled = _build_neg_index(indexid2msg)
1299
+ real_edge_set: set = set()
1300
+ for g in train_graphs:
1301
+ for src, dst, _, attrs in g.edges(data=True, keys=True):
1302
+ real_edge_set.add((str(src), str(dst), attrs.get("label", "")))
1303
+ train_neg_map = _precompute_negatives(
1304
+ train_edges, indexid2msg, type_to_labeled, real_edge_set
1305
+ )
1306
+ log(f"Pre-computed negatives for {len(train_neg_map)} unique train edge triples")
1307
+
1308
+ # ── Attack walk corpus (cls_attack mode only) ────────────────────────
1309
+ attack_walks = None
1310
+ if finetune_mode == "cls_attack":
1311
+ num_attack_walks = detect_cfg.num_attack_walks
1312
+ # Curated file (hand-validated, node-filtered) takes priority when present
1313
+ curated_path = os.path.join(ft_dir, "attack_walks_curated.pkl")
1314
+ attack_walks_path = os.path.join(ft_dir, "attack_walks.pkl")
1315
+ if os.path.exists(curated_path):
1316
+ attack_walks = _load_attack_walks(curated_path)
1317
+ log("Using curated attack walks (hand-filtered)")
1318
+ elif os.path.exists(attack_walks_path):
1319
+ attack_walks = _load_attack_walks(attack_walks_path)
1320
+ # Re-extract if cached file has old 4-tuple format (need 6-tuple with dst walks)
1321
+ if attack_walks and len(attack_walks[0]) != 6:
1322
+ log("Stale cache (4-tuple format), re-extracting with dst walks...")
1323
+ attack_walks = None
1324
+ if attack_walks is None and not os.path.exists(curated_path):
1325
+ log("Extracting attack walks from val/test graphs...")
1326
+ attack_walks = _extract_attack_walks(
1327
+ cfg, finetune_walk_len, time_weight, half_life, num_attack_walks,
1328
+ )
1329
+ _save_attack_walks(attack_walks, attack_walks_path)
1330
+ log(f"Attack walk corpus: {len(attack_walks)} sequences")
1331
+ if not attack_walks:
1332
+ raise ValueError(
1333
+ "No attack walks found — check ground_truth_relative_path and "
1334
+ "attack_to_time_window in the dataset config"
1335
+ )
1336
+
1337
+ # ── Optimizer ───────────────────────────────────────────────────────
1338
+ opt = AdamW(
1339
+ filter(lambda p: p.requires_grad, model.parameters()),
1340
+ lr=finetune_lr,
1341
+ betas=(0.9, 0.99),
1342
+ eps=1e-10,
1343
+ weight_decay=0.02,
1344
+ )
1345
+ updates_per_epoch = len(train_edges) // batch_size
1346
+ total_steps = updates_per_epoch * finetune_epochs
1347
+ warmup_steps = max(1, total_steps // 20) # 5% warmup
1348
+ if scheduler_type == "cosine":
1349
+ scheduler = WarmupCosineScheduler(opt, warmup_steps, total_steps)
1350
+ else:
1351
+ scheduler = WarmupLinearScheduler(opt, warmup_steps, total_steps)
1352
+
1353
+ # ── Training loop ───────────────────────────────────────────────────
1354
+ log_path = os.path.join(ft_dir, f"finetune_{finetune_mode}_{model_size}_log.txt")
1355
+ with open(log_path, "w") as f:
1356
+ f.write("epoch,update,loss,lr\n")
1357
+
1358
+ best_val_loss = float("inf")
1359
+ updates = 0
1360
+
1361
+ for epoch in range(finetune_epochs):
1362
+ random.shuffle(train_edges)
1363
+ epoch_loss = 0
1364
+ n_batches = 0
1365
+ st = time.time()
1366
+
1367
+ for batch_start in range(0, len(train_edges), batch_size):
1368
+ batch_edges = train_edges[batch_start : batch_start + batch_size]
1369
+
1370
+ # Use sampler from first graph (or pick randomly)
1371
+ sampler = random.choice(train_samplers)
1372
+
1373
+ model.train()
1374
+ if finetune_mode == "cls":
1375
+ input_ids, attn_mask, tgt_mask, labels = _prepare_finetune_batch_cls(
1376
+ batch_edges, sampler, tokenizer, indexid2msg, finetune_walk_len,
1377
+ neg_map=train_neg_map,
1378
+ )
1379
+ loss = model(
1380
+ input_ids.to(device),
1381
+ attn_mask.to(device),
1382
+ tgt_mask.to(device),
1383
+ labels.to(device),
1384
+ )
1385
+ elif finetune_mode == "cls_attack":
1386
+ attack_batch = random.choices(attack_walks, k=len(batch_edges))
1387
+ input_ids, attn_mask, tgt_mask, labels = _prepare_finetune_batch_cls_attack(
1388
+ batch_edges, attack_batch, sampler, tokenizer, indexid2msg, finetune_walk_len,
1389
+ )
1390
+ loss = model(
1391
+ input_ids.to(device),
1392
+ attn_mask.to(device),
1393
+ tgt_mask.to(device),
1394
+ labels.to(device),
1395
+ )
1396
+ elif finetune_mode == "lp":
1397
+ input_ids, attn_mask, tgt_mask, tgt_ids = _prepare_finetune_batch_lp(
1398
+ batch_edges, sampler, tokenizer, indexid2msg, finetune_walk_len
1399
+ )
1400
+ loss = model(
1401
+ input_ids.to(device),
1402
+ attn_mask.to(device),
1403
+ tgt_mask.to(device),
1404
+ tgt_ids.to(device),
1405
+ )
1406
+
1407
+ loss.backward()
1408
+ torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
1409
+ opt.step()
1410
+ opt.zero_grad()
1411
+ scheduler.step()
1412
+
1413
+ epoch_loss += loss.item()
1414
+ n_batches += 1
1415
+ updates += 1
1416
+
1417
+ if updates % 50 == 0:
1418
+ lr = scheduler.get_last_lr()[0]
1419
+ log(f"[e{epoch+1}|u{updates}] loss={loss.item():.4f} lr={lr:.2e}")
1420
+
1421
+ avg_loss = epoch_loss / max(1, n_batches)
1422
+ elapsed = time.time() - st
1423
+ log(f"Epoch {epoch+1}/{finetune_epochs}: avg_loss={avg_loss:.4f} ({elapsed:.1f}s)")
1424
+
1425
+ with open(log_path, "a") as f:
1426
+ f.write(f"{epoch+1},{updates},{avg_loss:.6f},{scheduler.get_last_lr()[0]:.2e}\n")
1427
+
1428
+ # Save checkpoint
1429
+ save_path = os.path.join(ft_dir, f"finetune_{finetune_mode}_{model_size}.pt")
1430
+ torch.save(model.state_dict(), save_path)
1431
+
1432
+ if avg_loss < best_val_loss:
1433
+ best_val_loss = avg_loss
1434
+ best_path = os.path.join(ft_dir, f"finetune_{finetune_mode}_{model_size}_best.pt")
1435
+ torch.save(model.state_dict(), best_path)
1436
+
1437
+ log(f"Fine-tuning complete. Best loss: {best_val_loss:.4f}")