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,1432 @@
1
+ """
2
+ SPIDER detection: score val/test edges using the fine-tuned model.
3
+
4
+ Replaces GNN training+inference for SPIDER. Loads the fine-tuned CLS, LP,
5
+ or TGN model, scores all edges in val/test graphs, and writes per-edge anomaly
6
+ scores as CSVs in the format expected by node_evaluation.py.
7
+
8
+ CSV format: loss,srcnode,dstnode,time,edge_type
9
+ Directory: {edge_losses_dir}/{split}/model_epoch_0/{time_interval}.csv
10
+ """
11
+
12
+ import multiprocessing as mp
13
+ import os
14
+ from typing import List, Optional, Tuple
15
+
16
+ import networkx as nx
17
+ import numpy as np
18
+ import pandas as pd
19
+ import torch
20
+ import torch.nn.functional as F
21
+
22
+ from pidsmaker.utils.dataset_utils import get_rel2id
23
+ from pidsmaker.utils.utils import (
24
+ get_all_graphs_for_dates,
25
+ get_indexid2msg,
26
+ log,
27
+ log_start,
28
+ log_tqdm,
29
+ ns_time_to_datetime_US,
30
+ )
31
+
32
+ from .finetune import _collect_edges
33
+
34
+
35
+ def _build_context_graph(graph_paths: List[str]) -> nx.MultiDiGraph:
36
+ """Merge multiple snapshot graphs into one for use as sampler context."""
37
+ merged = nx.MultiDiGraph()
38
+ for path in graph_paths:
39
+ g = torch.load(path, weights_only=False)
40
+ merged.add_nodes_from(g.nodes(data=True))
41
+ merged.add_edges_from(g.edges(data=True, keys=True))
42
+ return merged
43
+
44
+
45
+ def _group_paths_by_day(paths: List[str]) -> dict:
46
+ """Group graph file paths by their parent directory (= day folder)."""
47
+ from collections import defaultdict
48
+ groups = defaultdict(list)
49
+ for p in paths:
50
+ day_folder = os.path.basename(os.path.dirname(p))
51
+ groups[day_folder].append(p)
52
+ return groups
53
+ from .models.bert import (
54
+ ProvenanceBERTFineTuneCLS,
55
+ ProvenanceBERTFineTuneLP,
56
+ get_bert_config,
57
+ )
58
+ from .models.modernbert import (
59
+ ProvenanceModernBERTFineTuneCLS,
60
+ ProvenanceModernBERTFineTuneLP,
61
+ get_modernbert_config,
62
+ )
63
+ from .models.ropebert import (
64
+ ProvenanceRoPEBERTFineTuneCLS,
65
+ ProvenanceRoPEBERTFineTuneLP,
66
+ get_ropebert_config,
67
+ )
68
+ from .data.sampler import ProvenanceWalkSampler
69
+ from .data.tokenizer_bpe import ProvenanceTokenizerBPE as ProvenanceTokenizer
70
+
71
+
72
+ def _load_finetuned_model(
73
+ pretrain_dir: str,
74
+ ft_dir: str,
75
+ tokenizer: ProvenanceTokenizer,
76
+ model_size: str,
77
+ model_type: str,
78
+ finetune_mode: str,
79
+ freeze_backbone: bool,
80
+ device: str,
81
+ pretrain_cfg=None,
82
+ ):
83
+ """Load the fine-tuned CLS or LP model, falling back to pretrained weights."""
84
+ if model_type == "ropebert":
85
+ rope_theta = pretrain_cfg.rope_theta
86
+ bert_config = get_ropebert_config(
87
+ tokenizer.vocab_size, model_size, tokenizer.max_seq_len,
88
+ rope_theta=rope_theta,
89
+ )
90
+ elif model_type == "modernbert":
91
+ bert_config = get_modernbert_config(
92
+ tokenizer.vocab_size, model_size, tokenizer.max_seq_len,
93
+ global_attn_every_n_layers=pretrain_cfg.global_attn_every_n_layers,
94
+ local_attention_window=pretrain_cfg.local_attention_window,
95
+ )
96
+ else:
97
+ bert_config = get_bert_config(tokenizer.vocab_size, model_size, tokenizer.max_seq_len)
98
+
99
+ # Try fine-tuned checkpoints first (in ft_dir), then pretrained (in pretrain_dir)
100
+ ft_best = os.path.join(ft_dir, f"finetune_{finetune_mode}_{model_size}_best.pt")
101
+ ft_last = os.path.join(ft_dir, f"finetune_{finetune_mode}_{model_size}.pt")
102
+ pt_last = os.path.join(pretrain_dir, f"pretrain_{model_size}.pt")
103
+
104
+ checkpoint_path = None
105
+ is_finetuned = False
106
+ for path in [ft_best, ft_last]:
107
+ if os.path.exists(path):
108
+ checkpoint_path = path
109
+ is_finetuned = True
110
+ break
111
+
112
+ if checkpoint_path is None:
113
+ if os.path.exists(pt_last):
114
+ checkpoint_path = pt_last
115
+
116
+ if checkpoint_path is None:
117
+ raise FileNotFoundError(
118
+ f"No checkpoint found in {ft_dir} or {pretrain_dir}"
119
+ )
120
+
121
+ log(f"Loading {model_type} checkpoint from {checkpoint_path}")
122
+
123
+ if is_finetuned:
124
+ # Fine-tuned: load full state dict into the fine-tune wrapper
125
+ sd = torch.load(checkpoint_path, weights_only=True, map_location="cpu")
126
+
127
+ # Extract backbone weights (strip 'fm.' prefix)
128
+ backbone_sd = {}
129
+ for k, v in sd.items():
130
+ if k.startswith("fm."):
131
+ backbone_sd[k[len("fm."):]] = v
132
+
133
+ if model_type == "ropebert":
134
+ if finetune_mode in ("cls", "cls_attack"):
135
+ model = ProvenanceRoPEBERTFineTuneCLS(
136
+ bert_config, backbone_sd or None, device=device, freeze_backbone=freeze_backbone,
137
+ )
138
+ else:
139
+ model = ProvenanceRoPEBERTFineTuneLP(
140
+ bert_config, backbone_sd or None, device=device, freeze_backbone=freeze_backbone,
141
+ )
142
+ elif model_type == "modernbert":
143
+ if finetune_mode in ("cls", "cls_attack"):
144
+ model = ProvenanceModernBERTFineTuneCLS(
145
+ bert_config, backbone_sd or None, device=device, freeze_backbone=freeze_backbone,
146
+ )
147
+ else:
148
+ model = ProvenanceModernBERTFineTuneLP(
149
+ bert_config, backbone_sd or None, device=device, freeze_backbone=freeze_backbone,
150
+ )
151
+ else:
152
+ if finetune_mode in ("cls", "cls_attack"):
153
+ model = ProvenanceBERTFineTuneCLS(
154
+ bert_config, backbone_sd or None, device=device, freeze_backbone=freeze_backbone,
155
+ )
156
+ else:
157
+ model = ProvenanceBERTFineTuneLP(
158
+ bert_config, backbone_sd or None, device=device, freeze_backbone=freeze_backbone,
159
+ )
160
+
161
+ # Load the full state dict (including classifier/head weights)
162
+ model.load_state_dict(sd)
163
+ else:
164
+ # Pretrained only: load backbone into fine-tune wrapper
165
+ sd = torch.load(checkpoint_path, weights_only=True, map_location="cpu")
166
+ if model_type == "ropebert":
167
+ if finetune_mode in ("cls", "cls_attack"):
168
+ model = ProvenanceRoPEBERTFineTuneCLS(
169
+ bert_config, sd, device=device, freeze_backbone=freeze_backbone,
170
+ )
171
+ else:
172
+ model = ProvenanceRoPEBERTFineTuneLP(
173
+ bert_config, sd, device=device, freeze_backbone=freeze_backbone,
174
+ )
175
+ elif model_type == "modernbert":
176
+ if finetune_mode in ("cls", "cls_attack"):
177
+ model = ProvenanceModernBERTFineTuneCLS(
178
+ bert_config, sd, device=device, freeze_backbone=freeze_backbone,
179
+ )
180
+ else:
181
+ model = ProvenanceModernBERTFineTuneLP(
182
+ bert_config, sd, device=device, freeze_backbone=freeze_backbone,
183
+ )
184
+ else:
185
+ if finetune_mode in ("cls", "cls_attack"):
186
+ model = ProvenanceBERTFineTuneCLS(
187
+ bert_config, sd, device=device, freeze_backbone=freeze_backbone,
188
+ )
189
+ else:
190
+ model = ProvenanceBERTFineTuneLP(
191
+ bert_config, sd, device=device, freeze_backbone=freeze_backbone,
192
+ )
193
+
194
+ model.eval()
195
+ return model
196
+
197
+
198
+ def _load_pretrained_model(
199
+ pretrain_dir: str,
200
+ tokenizer: ProvenanceTokenizer,
201
+ model_size: str,
202
+ device: str,
203
+ model_type: str = "bert",
204
+ pretrain_cfg=None,
205
+ ):
206
+ """Load the pretrained model wrapped in LP for scoring (no fine-tuning)."""
207
+ if model_type == "ropebert":
208
+ rope_theta = pretrain_cfg.rope_theta
209
+ bert_config = get_ropebert_config(
210
+ tokenizer.vocab_size, model_size, tokenizer.max_seq_len,
211
+ rope_theta=rope_theta,
212
+ )
213
+ elif model_type == "modernbert":
214
+ bert_config = get_modernbert_config(
215
+ tokenizer.vocab_size, model_size, tokenizer.max_seq_len,
216
+ global_attn_every_n_layers=pretrain_cfg.global_attn_every_n_layers,
217
+ local_attention_window=pretrain_cfg.local_attention_window,
218
+ )
219
+ else:
220
+ bert_config = get_bert_config(tokenizer.vocab_size, model_size, tokenizer.max_seq_len)
221
+
222
+ pt_last = os.path.join(pretrain_dir, f"pretrain_{model_size}.pt")
223
+
224
+ if not os.path.exists(pt_last):
225
+ raise FileNotFoundError(f"No pretrained checkpoint found in {pretrain_dir}")
226
+ checkpoint_path = pt_last
227
+
228
+ log(f"Loading {model_type} pretrained checkpoint from {checkpoint_path}")
229
+ sd = torch.load(checkpoint_path, weights_only=True, map_location="cpu")
230
+ if model_type == "ropebert":
231
+ model = ProvenanceRoPEBERTFineTuneLP(bert_config, sd, device=device)
232
+ elif model_type == "modernbert":
233
+ model = ProvenanceModernBERTFineTuneLP(bert_config, sd, device=device)
234
+ else:
235
+ model = ProvenanceBERTFineTuneLP(bert_config, sd, device=device)
236
+ model.eval()
237
+ return model
238
+
239
+
240
+
241
+ def _prepare_score_batch_cls(
242
+ edges: List[Tuple[str, str, str, float]],
243
+ sampler: ProvenanceWalkSampler,
244
+ tokenizer: ProvenanceTokenizer,
245
+ indexid2msg: dict,
246
+ walk_length: int,
247
+ ):
248
+ """Prepare a batch for CLS scoring (no negative sampling).
249
+
250
+ Returns:
251
+ input_ids: [B, L]
252
+ attention_mask: [B, L]
253
+ target_mask: [B, L]
254
+ """
255
+ batch_input_ids = []
256
+ batch_attn = []
257
+ batch_target = []
258
+
259
+ for src, dst, etype, ts in edges:
260
+ walk_nodes, walk_edge_types = sampler.sample_bidirectional_walk(
261
+ src, max_ts=ts, walk_length=walk_length,
262
+ )
263
+ dst_walk_nodes, dst_walk_edge_types = sampler.sample_context_walk(
264
+ dst, max_ts=ts, walk_length=walk_length,
265
+ )
266
+ tok_ids, attn, tgt_mask = tokenizer.tokenize_for_finetune(
267
+ walk_nodes, walk_edge_types, dst, etype, indexid2msg, mode="cls",
268
+ dst_walk_nodes=dst_walk_nodes, dst_walk_edge_types=dst_walk_edge_types,
269
+ )
270
+ batch_input_ids.append(tok_ids)
271
+ batch_attn.append(attn)
272
+ batch_target.append(tgt_mask)
273
+
274
+ # Pad to max length
275
+ max_len = max(t.size(0) for t in batch_input_ids)
276
+ pad_id = tokenizer.pad_id
277
+ B = len(batch_input_ids)
278
+
279
+ input_ids = torch.full((B, max_len), pad_id, dtype=torch.long)
280
+ attention_mask = torch.zeros(B, max_len, dtype=torch.bool)
281
+ target_mask = torch.zeros(B, max_len, dtype=torch.bool)
282
+
283
+ for i in range(B):
284
+ L = batch_input_ids[i].size(0)
285
+ input_ids[i, :L] = batch_input_ids[i]
286
+ attention_mask[i, :L] = batch_attn[i]
287
+ target_mask[i, :L] = batch_target[i]
288
+
289
+ return input_ids, attention_mask, target_mask
290
+
291
+
292
+ def _prepare_score_batch_lp(
293
+ edges: List[Tuple[str, str, str, float]],
294
+ sampler: ProvenanceWalkSampler,
295
+ tokenizer: ProvenanceTokenizer,
296
+ indexid2msg: dict,
297
+ walk_length: int,
298
+ ):
299
+ """Prepare a batch for LP scoring (masked destination prediction).
300
+
301
+ Returns:
302
+ input_ids: [B, L]
303
+ attention_mask: [B, L]
304
+ target_mask: [B, L]
305
+ target_token_ids: [B, L]
306
+ """
307
+ batch_input_ids = []
308
+ batch_attn = []
309
+ batch_target_mask = []
310
+ batch_target_ids = []
311
+
312
+ for src, dst, etype, ts in edges:
313
+ walk_nodes, walk_edge_types = sampler.sample_bidirectional_walk(
314
+ src, max_ts=ts, walk_length=walk_length,
315
+ )
316
+
317
+ # Get masked version
318
+ tok_ids_masked, attn_masked, tgt_mask = tokenizer.tokenize_for_finetune(
319
+ walk_nodes, walk_edge_types, dst, etype, indexid2msg, mode="lp",
320
+ )
321
+
322
+ # Build target: true token IDs where masked, -100 elsewhere
323
+ target_ids = torch.full_like(tok_ids_masked, -100)
324
+ mask_positions = tgt_mask.nonzero(as_tuple=True)[0]
325
+
326
+ if dst in indexid2msg:
327
+ dst_type, dst_label = indexid2msg[dst]
328
+ dst_tokens = tokenizer.tokenize_node(dst_type, dst_label)
329
+ for j, pos in enumerate(mask_positions):
330
+ if j < len(dst_tokens):
331
+ target_ids[pos] = dst_tokens[j]
332
+
333
+ batch_input_ids.append(tok_ids_masked)
334
+ batch_attn.append(attn_masked)
335
+ batch_target_mask.append(tgt_mask)
336
+ batch_target_ids.append(target_ids)
337
+
338
+ # Pad
339
+ max_len = max(t.size(0) for t in batch_input_ids)
340
+ pad_id = tokenizer.pad_id
341
+ B = len(batch_input_ids)
342
+
343
+ input_ids = torch.full((B, max_len), pad_id, dtype=torch.long)
344
+ attention_mask = torch.zeros(B, max_len, dtype=torch.bool)
345
+ target_mask = torch.zeros(B, max_len, dtype=torch.bool)
346
+ target_token_ids = torch.full((B, max_len), -100, dtype=torch.long)
347
+
348
+ for i in range(B):
349
+ L = batch_input_ids[i].size(0)
350
+ input_ids[i, :L] = batch_input_ids[i]
351
+ attention_mask[i, :L] = batch_attn[i]
352
+ target_mask[i, :L] = batch_target_mask[i]
353
+ target_token_ids[i, :L] = batch_target_ids[i]
354
+
355
+ return input_ids, attention_mask, target_mask, target_token_ids
356
+
357
+
358
+ # ── Parallel walk sampling ──────────────────────────────────────────────────
359
+
360
+ # Module-level globals inherited by forked worker processes (read-only, COW).
361
+ _mp_sampler: Optional[ProvenanceWalkSampler] = None
362
+ _mp_walk_length: int = 10
363
+
364
+
365
+ def _walk_worker(edge_chunk: List[Tuple[str, str, str, float]]) -> list:
366
+ """Sample src + dst walks for a chunk of edges (runs in forked child)."""
367
+ results = []
368
+ for src, dst, etype, ts in edge_chunk:
369
+ src_wn, src_we = _mp_sampler.sample_bidirectional_walk(
370
+ src, max_ts=ts, walk_length=_mp_walk_length,
371
+ )
372
+ dst_wn, dst_we = _mp_sampler.sample_context_walk(
373
+ dst, max_ts=ts, walk_length=_mp_walk_length,
374
+ )
375
+ results.append((src_wn, src_we, dst_wn, dst_we))
376
+ return results
377
+
378
+
379
+ def _parallel_sample_walks(
380
+ edges: List[Tuple[str, str, str, float]],
381
+ sampler: ProvenanceWalkSampler,
382
+ walk_length: int,
383
+ num_workers: Optional[int] = None,
384
+ ) -> list:
385
+ """Pre-sample all walks using multiprocessing (fork, read-only COW)."""
386
+ global _mp_sampler, _mp_walk_length
387
+ _mp_sampler = sampler
388
+ _mp_walk_length = walk_length
389
+
390
+ if num_workers is None:
391
+ num_workers = min(mp.cpu_count(), 8)
392
+
393
+ # Fall back to sequential for small edge counts or single worker
394
+ if num_workers <= 1 or len(edges) < 2000:
395
+ return _walk_worker(edges)
396
+
397
+ chunk_size = max(1, (len(edges) + num_workers - 1) // num_workers)
398
+ chunks = [edges[i:i + chunk_size] for i in range(0, len(edges), chunk_size)]
399
+
400
+ ctx = mp.get_context("fork")
401
+ with ctx.Pool(num_workers) as pool:
402
+ result_chunks = pool.map(_walk_worker, chunks)
403
+
404
+ return [w for chunk in result_chunks for w in chunk]
405
+
406
+
407
+ @torch.no_grad()
408
+ def _score_edges_cls(
409
+ edges: List[Tuple[str, str, str, float]],
410
+ sampler: ProvenanceWalkSampler,
411
+ model: ProvenanceBERTFineTuneCLS,
412
+ tokenizer: ProvenanceTokenizer,
413
+ indexid2msg: dict,
414
+ walk_length: int,
415
+ batch_size: int,
416
+ device: str,
417
+ ) -> List[float]:
418
+ """Score edges using CLS mode: raw logit as anomaly score.
419
+
420
+ Walks are pre-sampled in parallel across CPU cores (fork-based
421
+ multiprocessing), then tokenized and scored in batched GPU passes.
422
+ """
423
+ # Phase 1: parallel walk sampling on CPU
424
+ all_walks = _parallel_sample_walks(edges, sampler, walk_length)
425
+
426
+ # Phase 2: tokenize + GPU inference in batches
427
+ scores = []
428
+ for batch_start in range(0, len(edges), batch_size):
429
+ batch_edges = edges[batch_start:batch_start + batch_size]
430
+ batch_walks = all_walks[batch_start:batch_start + batch_size]
431
+
432
+ batch_input_ids = []
433
+ batch_attn = []
434
+ batch_target = []
435
+ for (src_wn, src_we, dst_wn, dst_we), (src, dst, etype, ts) in zip(batch_walks, batch_edges):
436
+ tok_ids, attn, tgt_mask = tokenizer.tokenize_for_finetune(
437
+ src_wn, src_we, dst, etype, indexid2msg, mode="cls",
438
+ dst_walk_nodes=dst_wn, dst_walk_edge_types=dst_we,
439
+ )
440
+ batch_input_ids.append(tok_ids)
441
+ batch_attn.append(attn)
442
+ batch_target.append(tgt_mask)
443
+
444
+ max_len = max(t.size(0) for t in batch_input_ids)
445
+ pad_id = tokenizer.pad_id
446
+ B = len(batch_input_ids)
447
+ input_ids = torch.full((B, max_len), pad_id, dtype=torch.long)
448
+ attention_mask = torch.zeros(B, max_len, dtype=torch.bool)
449
+ target_mask = torch.zeros(B, max_len, dtype=torch.bool)
450
+ for i in range(B):
451
+ L = batch_input_ids[i].size(0)
452
+ input_ids[i, :L] = batch_input_ids[i]
453
+ attention_mask[i, :L] = batch_attn[i]
454
+ target_mask[i, :L] = batch_target[i]
455
+
456
+ logits = model.predict(
457
+ input_ids.to(device),
458
+ attention_mask.to(device),
459
+ target_mask.to(device),
460
+ )
461
+ scores.extend(logits.squeeze(-1).cpu().numpy().tolist())
462
+
463
+ return scores
464
+
465
+
466
+ @torch.no_grad()
467
+ def _score_edges_lp(
468
+ edges: List[Tuple[str, str, str, float]],
469
+ sampler: ProvenanceWalkSampler,
470
+ model: ProvenanceBERTFineTuneLP,
471
+ tokenizer: ProvenanceTokenizer,
472
+ indexid2msg: dict,
473
+ walk_length: int,
474
+ batch_size: int,
475
+ device: str,
476
+ edge_score_weight: float = 0.0,
477
+ ) -> List[float]:
478
+ """Score edges: node CE + optional lambda * edge-type CE."""
479
+ scores = []
480
+ for batch_start in range(0, len(edges), batch_size):
481
+ batch_edges = edges[batch_start:batch_start + batch_size]
482
+ input_ids, attn_mask, tgt_mask, tgt_ids = _prepare_score_batch_lp(
483
+ batch_edges, sampler, tokenizer, indexid2msg, walk_length,
484
+ )
485
+
486
+ node_scores = model.anomaly_score(
487
+ input_ids.to(device),
488
+ attn_mask.to(device),
489
+ tgt_mask.to(device),
490
+ tgt_ids.to(device),
491
+ ) # [B]
492
+
493
+ # Optional edge-type scoring
494
+ if edge_score_weight > 0:
495
+ e_input_ids, e_attn_mask, e_tgt_mask, e_tgt_ids = _prepare_score_batch_edge(
496
+ batch_edges, sampler, tokenizer, indexid2msg, walk_length,
497
+ )
498
+ e_scores = model.anomaly_score(
499
+ e_input_ids.to(device),
500
+ e_attn_mask.to(device),
501
+ e_tgt_mask.to(device),
502
+ e_tgt_ids.to(device),
503
+ )
504
+ node_scores = node_scores + edge_score_weight * e_scores
505
+
506
+ scores.extend(node_scores.cpu().numpy().tolist())
507
+
508
+ return scores
509
+
510
+
511
+ def _prepare_score_batch_edge(
512
+ edges: List[Tuple[str, str, str, float]],
513
+ sampler: ProvenanceWalkSampler,
514
+ tokenizer: ProvenanceTokenizer,
515
+ indexid2msg: dict,
516
+ walk_length: int,
517
+ ):
518
+ """Prepare batch with edge type masked, destination visible.
519
+
520
+ Returns:
521
+ input_ids: [B, L]
522
+ attention_mask: [B, L]
523
+ target_mask: [B, L]
524
+ target_token_ids: [B, L]
525
+ """
526
+ batch_input_ids = []
527
+ batch_attn = []
528
+ batch_tgt_mask = []
529
+ batch_tgt_ids = []
530
+
531
+ for src, dst, etype, ts in edges:
532
+ walk_nodes, walk_edge_types = sampler.sample_bidirectional_walk(
533
+ src, max_ts=ts, walk_length=walk_length,
534
+ )
535
+ tok_ids, attn, edge_mask, edge_tgt = tokenizer.tokenize_for_edge_scoring(
536
+ walk_nodes, walk_edge_types, dst, etype, indexid2msg,
537
+ )
538
+ batch_input_ids.append(tok_ids)
539
+ batch_attn.append(attn)
540
+ batch_tgt_mask.append(edge_mask)
541
+ batch_tgt_ids.append(edge_tgt)
542
+
543
+ # Pad
544
+ max_len = max(t.size(0) for t in batch_input_ids)
545
+ pad_id = tokenizer.pad_id
546
+ B = len(batch_input_ids)
547
+
548
+ input_ids = torch.full((B, max_len), pad_id, dtype=torch.long)
549
+ attention_mask = torch.zeros(B, max_len, dtype=torch.bool)
550
+ target_mask = torch.zeros(B, max_len, dtype=torch.bool)
551
+ target_token_ids = torch.full((B, max_len), -100, dtype=torch.long)
552
+
553
+ for i in range(B):
554
+ L = batch_input_ids[i].size(0)
555
+ input_ids[i, :L] = batch_input_ids[i]
556
+ attention_mask[i, :L] = batch_attn[i]
557
+ target_mask[i, :L] = batch_tgt_mask[i]
558
+ target_token_ids[i, :L] = batch_tgt_ids[i]
559
+
560
+ return input_ids, attention_mask, target_mask, target_token_ids
561
+
562
+
563
+
564
+
565
+ def _score_graph(
566
+ graph,
567
+ model,
568
+ tokenizer: ProvenanceTokenizer,
569
+ indexid2msg: dict,
570
+ rel2id: dict,
571
+ finetune_mode: str,
572
+ walk_length: int,
573
+ batch_size: int,
574
+ time_weight: str,
575
+ half_life: float,
576
+ device: str,
577
+ num_walks: int = 1,
578
+ edge_score_weight: float = 2.0,
579
+ context_graph: Optional[nx.MultiDiGraph] = None,
580
+ prebuilt_sampler: Optional[ProvenanceWalkSampler] = None,
581
+ ) -> pd.DataFrame:
582
+ """Score all edges in a single graph and return a DataFrame.
583
+
584
+ prebuilt_sampler: if provided, reuse this sampler instead of constructing a
585
+ new one. Use this in day/all context modes to avoid rebuilding adjacency
586
+ lists (O(E)) for every snapshot graph.
587
+ context_graph: used only when prebuilt_sampler is None; builds a fresh
588
+ sampler from context_graph (or graph itself if context_graph is None).
589
+ """
590
+ edges = _collect_edges(graph)
591
+ if not edges:
592
+ return pd.DataFrame(columns=["loss", "srcnode", "dstnode", "time", "edge_type"])
593
+
594
+ if prebuilt_sampler is not None:
595
+ sampler = prebuilt_sampler
596
+ else:
597
+ sampler = ProvenanceWalkSampler(
598
+ context_graph if context_graph is not None else graph,
599
+ walk_length=walk_length, num_walks=1,
600
+ time_weight=time_weight, half_life=half_life,
601
+ )
602
+
603
+ score_fn = {
604
+ "cls": _score_edges_cls,
605
+ "cls_attack": _score_edges_cls,
606
+ "lp": _score_edges_lp,
607
+ "mlm": _score_edges_lp,
608
+ }[finetune_mode]
609
+
610
+ common_args = (edges, sampler, model, tokenizer, indexid2msg,
611
+ walk_length, batch_size, device)
612
+ extra_args = (edge_score_weight,) if finetune_mode in ("lp", "mlm") else ()
613
+
614
+ if num_walks <= 1:
615
+ scores = score_fn(*common_args, *extra_args)
616
+ else:
617
+ # Average scores over multiple walks
618
+ all_scores = np.zeros(len(edges))
619
+ for _ in range(num_walks):
620
+ walk_scores = score_fn(*common_args, *extra_args)
621
+ all_scores += np.array(walk_scores)
622
+ scores = (all_scores / num_walks).tolist()
623
+
624
+ # Build DataFrame matching inference_loop.py format
625
+ rows = []
626
+ for (src, dst, etype, ts), score in zip(edges, scores):
627
+ edge_type_id = rel2id.get(etype, 0)
628
+ rows.append({
629
+ "loss": float(score),
630
+ "srcnode": int(src),
631
+ "dstnode": int(dst),
632
+ "time": int(ts),
633
+ "edge_type": int(edge_type_id),
634
+ })
635
+
636
+ return pd.DataFrame(rows)
637
+
638
+
639
+ # ── Edge classification detection ──────────────────────────────────────────────
640
+
641
+ def _detect_edge_cls(cfg):
642
+ """Edge classification detection: score edges with static or event embeddings."""
643
+ log_start(__file__)
644
+
645
+ from .models.tgn import EdgeTypeClassifier
646
+
647
+ pretrain_cfg = cfg.featurization.pretrained
648
+ detect_cfg = cfg.training.pretrained
649
+ model_size = pretrain_cfg.model_size
650
+ batch_size = detect_cfg.inference_batch_size
651
+ device = "cuda" if torch.cuda.is_available() and not cfg._use_cpu else "cpu"
652
+
653
+ ft_dir = cfg.training._trained_models_dir
654
+ edge_losses_dir = cfg.training._edge_losses_dir
655
+
656
+ # ── Run training first ────────────────────────────────────────
657
+ from .finetune import main as finetune_main
658
+ finetune_main(cfg)
659
+
660
+ # ── Load checkpoint ───────────────────────────────────────────
661
+ ckpt_path = os.path.join(ft_dir, f"finetune_edge_cls_{model_size}_best.pt")
662
+ if not os.path.exists(ckpt_path):
663
+ ckpt_path = os.path.join(ft_dir, f"finetune_edge_cls_{model_size}.pt")
664
+ if not os.path.exists(ckpt_path):
665
+ raise FileNotFoundError(f"No edge_cls checkpoint found in {ft_dir}")
666
+
667
+ ckpt = torch.load(ckpt_path, map_location="cpu")
668
+ ecfg = ckpt["edge_cls_config"]
669
+ node_to_idx = ckpt["node_to_idx"]
670
+ edge_type_to_id = ckpt["edge_type_to_id"]
671
+
672
+ model = EdgeTypeClassifier(
673
+ num_nodes=ckpt["num_nodes"],
674
+ num_edge_types=ckpt["num_edge_types"],
675
+ entity_emb_dim=ecfg["entity_emb_dim"],
676
+ hidden_dim=ecfg["hidden_dim"],
677
+ ).to(device)
678
+ model.load_state_dict(ckpt["model_state_dict"])
679
+ model.eval()
680
+ log(f"EdgeTypeClassifier loaded ({sum(p.numel() for p in model.parameters()):,} params)")
681
+
682
+ # ── Load data ─────────────────────────────────────────────────
683
+ rel2id = get_rel2id(cfg)
684
+ indexid2msg = get_indexid2msg(cfg)
685
+ base_dir = cfg.transformation._graphs_dir
686
+ val_paths = get_all_graphs_for_dates(base_dir, cfg.dataset.val_dates)
687
+ test_paths = get_all_graphs_for_dates(base_dir, cfg.dataset.test_dates)
688
+
689
+ splits = {"val": val_paths, "test": test_paths}
690
+ model_epoch_dir = "model_epoch_0"
691
+
692
+ for split_name, graph_paths in splits.items():
693
+ log(f"Edge-cls scoring {split_name} ({len(graph_paths)} graphs)...")
694
+
695
+ for graph_path in graph_paths:
696
+ graph = torch.load(graph_path, weights_only=False)
697
+ edges = _collect_edges(graph)
698
+ if not edges:
699
+ continue
700
+
701
+ rows = []
702
+ for batch_start in range(0, len(edges), batch_size):
703
+ batch = edges[batch_start:batch_start + batch_size]
704
+
705
+ src_idx = torch.tensor(
706
+ [node_to_idx.get(e[0], 0) for e in batch],
707
+ dtype=torch.long, device=device)
708
+ dst_idx = torch.tensor(
709
+ [node_to_idx.get(e[1], 0) for e in batch],
710
+ dtype=torch.long, device=device)
711
+ etypes = torch.tensor(
712
+ [edge_type_to_id.get(e[2], 0) for e in batch],
713
+ dtype=torch.long, device=device)
714
+
715
+ with torch.no_grad():
716
+ logits = model.predict(src_idx, dst_idx)
717
+ scores = F.cross_entropy(
718
+ logits, etypes, reduction="none")
719
+
720
+ scores_cpu = scores.cpu().numpy().tolist()
721
+ for (src, dst, etype, ts), score in zip(batch, scores_cpu):
722
+ rows.append({
723
+ "loss": float(score),
724
+ "srcnode": int(src),
725
+ "dstnode": int(dst),
726
+ "time": int(ts),
727
+ "edge_type": int(rel2id.get(etype, 0)),
728
+ })
729
+
730
+ edge_df = pd.DataFrame(rows)
731
+ start_time = edge_df["time"].min()
732
+ end_time = edge_df["time"].max()
733
+ time_interval = (
734
+ ns_time_to_datetime_US(start_time, timezone=cfg.dataset.timezone)
735
+ + "~"
736
+ + ns_time_to_datetime_US(end_time, timezone=cfg.dataset.timezone)
737
+ )
738
+
739
+ csv_dir = os.path.join(edge_losses_dir, split_name, model_epoch_dir)
740
+ os.makedirs(csv_dir, exist_ok=True)
741
+ csv_file = os.path.join(csv_dir, time_interval + ".csv")
742
+ edge_df.to_csv(csv_file, sep=",", header=True, index=False, encoding="utf-8")
743
+
744
+ log(f" {split_name} CSVs written to {os.path.join(edge_losses_dir, split_name)}")
745
+
746
+ log("Edge classification detection complete.")
747
+
748
+
749
+ # ── TGN detection ──────────────────────────────────────────────────────────────
750
+
751
+ @torch.no_grad()
752
+ def _score_edges_tgn(
753
+ all_edges_by_graph: dict,
754
+ model,
755
+ node_to_idx: dict,
756
+ edge_type_to_id: dict,
757
+ rel2id: dict,
758
+ batch_size: int,
759
+ device: str,
760
+ objective: str = "contrastive",
761
+ event_src_embs: torch.Tensor = None,
762
+ event_dst_embs: torch.Tensor = None,
763
+ edge_to_pair_idx: torch.Tensor = None,
764
+ ) -> dict:
765
+ """Score all edges across multiple graphs in temporal order using TGN.
766
+
767
+ Unlike CLS/LP modes that score per-graph independently, TGN processes
768
+ ALL edges in temporal order because memory state is cumulative.
769
+
770
+ For contrastive objective: score = raw binary logit (higher = more anomalous).
771
+ For edge_pred objective: score = cross-entropy loss of true edge type.
772
+ For multi_edge_pred objective: score = binary CE of the true edge type
773
+ under the multi-label model (higher = more surprising).
774
+ For dist_edge_pred objective: score = -log P(true_type) under the predicted
775
+ distribution (higher = more surprising).
776
+ For edge_pred_emb objective: score = CE of true type + MSE between predicted
777
+ and actual edge embedding (higher = more anomalous).
778
+
779
+ Returns:
780
+ dict mapping graph_path -> pd.DataFrame with scores.
781
+ """
782
+ # Flatten all edges with their graph origin, original index, and global index
783
+ flat_edges = []
784
+ global_idx = 0
785
+ for path, edges in all_edges_by_graph.items():
786
+ for i, edge in enumerate(edges):
787
+ flat_edges.append((edge, path, i, global_idx))
788
+ global_idx += 1
789
+
790
+ # Sort globally by timestamp
791
+ flat_edges.sort(key=lambda x: x[0][3])
792
+
793
+ # Pre-allocate score storage
794
+ scores_by_graph = {path: [None] * len(edges) for path, edges in all_edges_by_graph.items()}
795
+
796
+ for batch_start in range(0, len(flat_edges), batch_size):
797
+ batch = flat_edges[batch_start:batch_start + batch_size]
798
+
799
+ edges_batch = [x[0] for x in batch]
800
+ paths_batch = [x[1] for x in batch]
801
+ indices_batch = [x[2] for x in batch]
802
+ global_indices = [x[3] for x in batch]
803
+
804
+ src_idx = torch.tensor(
805
+ [node_to_idx.get(e[0], 0) for e in edges_batch], dtype=torch.long, device=device)
806
+ dst_idx = torch.tensor(
807
+ [node_to_idx.get(e[1], 0) for e in edges_batch], dtype=torch.long, device=device)
808
+ edge_types = torch.tensor(
809
+ [edge_type_to_id.get(e[2], 0) for e in edges_batch], dtype=torch.long, device=device)
810
+ timestamps = torch.tensor(
811
+ [e[3] for e in edges_batch], dtype=torch.long, device=device)
812
+
813
+ # Look up per-edge contextual embeddings for this batch (if available)
814
+ batch_event_src = None
815
+ batch_event_dst = None
816
+ if event_src_embs is not None and edge_to_pair_idx is not None:
817
+ gi = torch.tensor(global_indices, dtype=torch.long)
818
+ pair_idx = edge_to_pair_idx[gi]
819
+ batch_event_src = event_src_embs[pair_idx].to(device)
820
+ batch_event_dst = event_dst_embs[pair_idx].to(device)
821
+
822
+ if objective == "edge_pred":
823
+ logits = model.predict_edge_types(src_idx, dst_idx, timestamps,
824
+ event_src_emb=batch_event_src, event_dst_emb=batch_event_dst)
825
+ # Per-edge CE loss as anomaly score (higher = more surprising)
826
+ per_edge_scores = torch.nn.functional.cross_entropy(
827
+ logits, edge_types, reduction="none",
828
+ )
829
+ scores_cpu = per_edge_scores.cpu().numpy().tolist()
830
+
831
+ elif objective == "multi_edge_pred":
832
+ logits = model.predict_edge_types(src_idx, dst_idx, timestamps,
833
+ event_src_emb=batch_event_src, event_dst_emb=batch_event_dst)
834
+ # Per-edge binary CE: how surprising is this edge type under the
835
+ # multi-label model? Higher = more anomalous.
836
+ per_edge_logit = logits[
837
+ torch.arange(len(edges_batch), device=device), edge_types]
838
+ per_edge_scores = F.binary_cross_entropy_with_logits(
839
+ per_edge_logit, torch.ones_like(per_edge_logit),
840
+ reduction="none",
841
+ )
842
+ scores_cpu = per_edge_scores.cpu().numpy().tolist()
843
+
844
+ elif objective == "dist_edge_pred":
845
+ logits = model.predict_edge_types(src_idx, dst_idx, timestamps,
846
+ event_src_emb=batch_event_src, event_dst_emb=batch_event_dst)
847
+ # Per-edge NLL under predicted distribution: -log P(true_type)
848
+ log_probs = F.log_softmax(logits, dim=-1)
849
+ per_edge_scores = -log_probs[
850
+ torch.arange(len(edges_batch), device=device), edge_types]
851
+ scores_cpu = per_edge_scores.cpu().numpy().tolist()
852
+
853
+ elif objective == "edge_pred_emb":
854
+ logits = model.predict_edge_types(src_idx, dst_idx, timestamps,
855
+ event_src_emb=batch_event_src, event_dst_emb=batch_event_dst)
856
+ ce_scores = F.cross_entropy(
857
+ logits, edge_types, reduction="none")
858
+ pred_emb = model.predict_edge_embedding(src_idx, dst_idx, timestamps,
859
+ event_src_emb=batch_event_src, event_dst_emb=batch_event_dst)
860
+ target_emb = model.edge_emb(edge_types)
861
+ mse_scores = (pred_emb - target_emb).pow(2).mean(dim=-1)
862
+ per_edge_scores = ce_scores + mse_scores
863
+ scores_cpu = per_edge_scores.cpu().numpy().tolist()
864
+
865
+ elif objective == "node_pred":
866
+ logits = model.predict_node_types(src_idx, dst_idx, edge_types, timestamps,
867
+ event_src_emb=batch_event_src, event_dst_emb=batch_event_dst)
868
+ dst_types = model.node_types[dst_idx]
869
+ # Per-edge CE loss as anomaly score (higher = more surprising)
870
+ per_edge_scores = F.cross_entropy(
871
+ logits, dst_types, reduction="none")
872
+ scores_cpu = per_edge_scores.cpu().numpy().tolist()
873
+
874
+ else:
875
+ logits = model.classify_edges(src_idx, dst_idx, edge_types, timestamps,
876
+ event_src_emb=batch_event_src, event_dst_emb=batch_event_dst)
877
+ per_edge_scores = logits.squeeze(-1)
878
+ scores_cpu = per_edge_scores.cpu().numpy().tolist()
879
+
880
+ for score, path, idx in zip(scores_cpu, paths_batch, indices_batch):
881
+ scores_by_graph[path][idx] = score
882
+
883
+ # Update memories after scoring (with anomaly scores for score-gated memory)
884
+ model.update_memory(src_idx, dst_idx, edge_types, timestamps,
885
+ edge_scores=per_edge_scores)
886
+
887
+ # Build DataFrames
888
+ result = {}
889
+ for path, edges in all_edges_by_graph.items():
890
+ scores = scores_by_graph[path]
891
+ if not edges:
892
+ result[path] = pd.DataFrame(columns=["loss", "srcnode", "dstnode", "time", "edge_type"])
893
+ continue
894
+ rows = []
895
+ for (src, dst, etype, ts), score in zip(edges, scores):
896
+ rows.append({
897
+ "loss": float(score) if score is not None else 0.0,
898
+ "srcnode": int(src),
899
+ "dstnode": int(dst),
900
+ "time": int(ts),
901
+ "edge_type": int(rel2id.get(etype, 0)),
902
+ })
903
+ result[path] = pd.DataFrame(rows)
904
+
905
+ return result
906
+
907
+
908
+ def _detect_tgn(cfg):
909
+ """TGN detection: score val/test edges with temporal entity memory."""
910
+ log_start(__file__)
911
+
912
+ from .models.tgn import ProvenanceTGN
913
+
914
+ pretrain_cfg = cfg.featurization.pretrained
915
+ detect_cfg = cfg.training.pretrained
916
+ model_size = pretrain_cfg.model_size
917
+ batch_size = detect_cfg.inference_batch_size
918
+ device = "cuda" if torch.cuda.is_available() and not cfg._use_cpu else "cpu"
919
+
920
+ ft_dir = cfg.training._trained_models_dir
921
+ edge_losses_dir = cfg.training._edge_losses_dir
922
+
923
+ # ── Run training first (same pattern as existing detect.py) ────
924
+ from .finetune import main as finetune_main
925
+ finetune_main(cfg)
926
+
927
+ # ── Load checkpoint ────────────────────────────────────────────
928
+ ckpt_path = os.path.join(ft_dir, f"finetune_tgn_{model_size}_best.pt")
929
+ if not os.path.exists(ckpt_path):
930
+ ckpt_path = os.path.join(ft_dir, f"finetune_tgn_{model_size}.pt")
931
+ if not os.path.exists(ckpt_path):
932
+ raise FileNotFoundError(f"No TGN checkpoint found in {ft_dir}")
933
+
934
+ ckpt = torch.load(ckpt_path, map_location="cpu")
935
+ tgn_config = ckpt["tgn_config"]
936
+ node_to_idx = ckpt["node_to_idx"]
937
+ edge_type_to_id = ckpt["edge_type_to_id"]
938
+ objective = tgn_config.get("objective", "contrastive")
939
+
940
+ use_event_bert_emb = tgn_config.get("use_event_bert_emb", False)
941
+ event_bert_emb_dim = tgn_config.get("event_bert_emb_dim", 0)
942
+
943
+ model = ProvenanceTGN(
944
+ num_nodes=ckpt["num_nodes"],
945
+ num_edge_types=ckpt["num_edge_types"],
946
+ entity_emb_dim=tgn_config["entity_emb_dim"],
947
+ memory_dim=tgn_config["memory_dim"],
948
+ edge_emb_dim=tgn_config["edge_emb_dim"],
949
+ time_dim=tgn_config["time_dim"],
950
+ num_heads=tgn_config["num_heads"],
951
+ use_node_type_emb=tgn_config.get("use_node_type_emb", False),
952
+ use_time_emb=tgn_config.get("use_time_emb", True),
953
+ use_memory=tgn_config.get("use_memory", True),
954
+ use_entity_emb=tgn_config.get("use_entity_emb", True),
955
+ use_event_bert_emb=use_event_bert_emb,
956
+ event_bert_emb_dim=event_bert_emb_dim,
957
+ score_gated_memory=tgn_config.get("score_gated_memory", False),
958
+ temporal_decay=tgn_config.get("temporal_decay", False),
959
+ anomaly_accumulator=tgn_config.get("anomaly_accumulator", False),
960
+ device=device,
961
+ ).to(device)
962
+ model.load_state_dict(ckpt["model_state_dict"])
963
+ model.eval()
964
+ log(f"TGN model loaded ({sum(p.numel() for p in model.parameters()):,} params)")
965
+
966
+ # ── Load data ──────────────────────────────────────────────────
967
+ rel2id = get_rel2id(cfg)
968
+ base_dir = cfg.transformation._graphs_dir
969
+ val_paths = get_all_graphs_for_dates(base_dir, cfg.dataset.val_dates)
970
+ test_paths = get_all_graphs_for_dates(base_dir, cfg.dataset.test_dates)
971
+
972
+ splits = {"val": val_paths, "test": test_paths}
973
+ model_epoch_dir = "model_epoch_0"
974
+
975
+ reset_memory = detect_cfg.tgn.reset_memory_on_inference
976
+
977
+ for split_name, graph_paths in splits.items():
978
+ log(f"TGN scoring {split_name} ({len(graph_paths)} graphs)...")
979
+
980
+ if reset_memory:
981
+ # Production mode: start with empty memory (no training history)
982
+ model.reset_memory()
983
+ log(f" Memory reset to zero (reset_memory_on_inference=True)")
984
+ else:
985
+ # Research mode: start from trained memory state (fresh per split)
986
+ trained_memory = ckpt["memory_state"]
987
+ model.load_memory_state({k: v.to(device) for k, v in trained_memory.items()})
988
+
989
+ # Collect all edges per graph
990
+ all_edges_by_graph = {}
991
+ total_edges = 0
992
+ for gp in graph_paths:
993
+ graph = torch.load(gp, weights_only=False)
994
+ edges = _collect_edges(graph)
995
+ all_edges_by_graph[gp] = edges
996
+ total_edges += len(edges)
997
+ log(f" {split_name}: {total_edges:,} edges across {len(graph_paths)} graphs")
998
+
999
+ # Score all edges in temporal order with memory updates
1000
+ result_dfs = _score_edges_tgn(
1001
+ all_edges_by_graph, model, node_to_idx, edge_type_to_id,
1002
+ rel2id, batch_size, device, objective=objective,
1003
+ event_src_embs=None,
1004
+ event_dst_embs=None,
1005
+ edge_to_pair_idx=None,
1006
+ )
1007
+
1008
+ # Write CSVs (same format as existing detect.py)
1009
+ for graph_path in graph_paths:
1010
+ edge_df = result_dfs[graph_path]
1011
+ if edge_df.empty:
1012
+ continue
1013
+
1014
+ start_time = edge_df["time"].min()
1015
+ end_time = edge_df["time"].max()
1016
+ time_interval = (
1017
+ ns_time_to_datetime_US(start_time, timezone=cfg.dataset.timezone)
1018
+ + "~"
1019
+ + ns_time_to_datetime_US(end_time, timezone=cfg.dataset.timezone)
1020
+ )
1021
+
1022
+ csv_dir = os.path.join(edge_losses_dir, split_name, model_epoch_dir)
1023
+ os.makedirs(csv_dir, exist_ok=True)
1024
+ csv_file = os.path.join(csv_dir, time_interval + ".csv")
1025
+ edge_df.to_csv(csv_file, sep=",", header=True, index=False, encoding="utf-8")
1026
+
1027
+ log(f" {split_name} CSVs written to {os.path.join(edge_losses_dir, split_name)}")
1028
+
1029
+ log("TGN detection complete.")
1030
+
1031
+
1032
+ # ── Perplexity-based detection (decoder-only LLaMA) ────────────────────────────
1033
+
1034
+ @torch.no_grad()
1035
+ def _score_edges_perplexity(
1036
+ edges: List[Tuple[str, str, str, float]],
1037
+ sampler: ProvenanceWalkSampler,
1038
+ model,
1039
+ tokenizer: ProvenanceTokenizer,
1040
+ indexid2msg: dict,
1041
+ walk_length: int,
1042
+ batch_size: int,
1043
+ device: str,
1044
+ ) -> List[float]:
1045
+ """Score edges using causal LM perplexity: mean next-token prediction loss.
1046
+
1047
+ For each edge, samples a walk including the edge context, runs teacher-forced
1048
+ causal LM forward pass, and averages per-token cross-entropy as anomaly score.
1049
+ Higher score = model didn't expect this sequence = more anomalous.
1050
+
1051
+ Walks are pre-sampled in parallel across CPU cores.
1052
+ """
1053
+ # Phase 1: parallel walk sampling on CPU
1054
+ all_walks = _parallel_sample_walks(edges, sampler, walk_length)
1055
+
1056
+ # Phase 2: tokenize + GPU inference in batches
1057
+ scores = []
1058
+ for batch_start in range(0, len(edges), batch_size):
1059
+ batch_edges = edges[batch_start:batch_start + batch_size]
1060
+ batch_walks = all_walks[batch_start:batch_start + batch_size]
1061
+
1062
+ batch_token_ids = []
1063
+ for (src_wn, src_we, dst_wn, dst_we), (src, dst, etype, ts) in zip(batch_walks, batch_edges):
1064
+ # Tokenize the walk with dst context (same as CLS mode but no masking)
1065
+ tok_ids, attn, _ = tokenizer.tokenize_for_finetune(
1066
+ src_wn, src_we, dst, etype, indexid2msg, mode="cls",
1067
+ dst_walk_nodes=dst_wn, dst_walk_edge_types=dst_we,
1068
+ )
1069
+ batch_token_ids.append(tok_ids)
1070
+
1071
+ if not batch_token_ids:
1072
+ continue
1073
+
1074
+ # Pad to max length
1075
+ max_len = max(t.size(0) for t in batch_token_ids)
1076
+ pad_id = tokenizer.pad_id
1077
+ B = len(batch_token_ids)
1078
+ input_ids = torch.full((B, max_len), pad_id, dtype=torch.long)
1079
+ attention_mask = torch.zeros(B, max_len, dtype=torch.bool)
1080
+ for i in range(B):
1081
+ L = batch_token_ids[i].size(0)
1082
+ input_ids[i, :L] = batch_token_ids[i]
1083
+ attention_mask[i, :L] = True
1084
+
1085
+ # Labels = input_ids; model shifts internally for next-token prediction.
1086
+ # Set padding to -100 so it's ignored in loss.
1087
+ labels = input_ids.clone()
1088
+ labels[~attention_mask] = -100
1089
+
1090
+ # Forward pass returns per-sample loss
1091
+ out = model.modified_fwd(
1092
+ input_ids.to(device),
1093
+ attention_mask.to(device),
1094
+ labels.to(device),
1095
+ return_loss=False,
1096
+ )
1097
+ logits = out.logits # [B, L, V]
1098
+
1099
+ # Compute per-token loss, then average per sample
1100
+ shift_logits = logits[:, :-1, :].contiguous()
1101
+ shift_labels = labels[:, 1:].to(device).contiguous()
1102
+ B, L, V = shift_logits.shape
1103
+ loss_fct = torch.nn.CrossEntropyLoss(reduction="none", ignore_index=-100)
1104
+ per_token_loss = loss_fct(
1105
+ shift_logits.view(-1, V), shift_labels.view(-1)
1106
+ ).view(B, L)
1107
+
1108
+ # Average over valid (non-padding) positions
1109
+ valid = shift_labels != -100
1110
+ num_valid = valid.float().sum(dim=1).clamp(min=1)
1111
+ per_edge_scores = (per_token_loss * valid.float()).sum(dim=1) / num_valid
1112
+ scores.extend(per_edge_scores.cpu().numpy().tolist())
1113
+
1114
+ return scores
1115
+
1116
+
1117
+ def _detect_perplexity(cfg):
1118
+ """Perplexity-based detection using decoder-only LLaMA model.
1119
+
1120
+ Loads the pretrained LLaMA model directly (no fine-tuning) and scores
1121
+ each edge by computing the mean next-token prediction loss over the
1122
+ walk containing that edge. Higher perplexity = more anomalous.
1123
+ """
1124
+ log_start(__file__)
1125
+
1126
+ from .models.llama import ProvenanceLLaMA, get_llama_config
1127
+
1128
+ pretrain_cfg = cfg.featurization.pretrained
1129
+ detect_cfg = cfg.training.pretrained
1130
+ model_size = pretrain_cfg.model_size
1131
+ walk_length = detect_cfg.finetune_walk_len
1132
+ batch_size = detect_cfg.inference_batch_size
1133
+ num_walks = detect_cfg.num_inference_walks
1134
+ time_weight = pretrain_cfg.walks.time_weight
1135
+ half_life = pretrain_cfg.walks.half_life
1136
+ graph_context_mode = pretrain_cfg.graph_context_mode
1137
+
1138
+ device = "cuda" if torch.cuda.is_available() and not cfg._use_cpu else "cpu"
1139
+
1140
+ pretrain_dir = cfg.featurization._model_dir
1141
+ edge_losses_dir = cfg.training._edge_losses_dir
1142
+
1143
+ # ── Load tokenizer ──────────────────────────────────────────────────
1144
+ tokenizer = ProvenanceTokenizer(cfg)
1145
+ tokenizer.load(os.path.join(pretrain_dir, "tokenizer.pt"))
1146
+ log(f"Loaded tokenizer (vocab_size={tokenizer.vocab_size})")
1147
+
1148
+ # ── Load pretrained LLaMA model ─────────────────────────────────────
1149
+ rope_theta = pretrain_cfg.rope_theta
1150
+ llama_config = get_llama_config(
1151
+ tokenizer.vocab_size, model_size, tokenizer.max_seq_len,
1152
+ rope_theta=rope_theta,
1153
+ )
1154
+
1155
+ checkpoint_path = os.path.join(pretrain_dir, f"pretrain_{model_size}.pt")
1156
+ if not os.path.exists(checkpoint_path):
1157
+ raise FileNotFoundError(f"No pretrained checkpoint found in {pretrain_dir}")
1158
+
1159
+ log(f"Loading LLaMA checkpoint from {checkpoint_path}")
1160
+ sd = torch.load(checkpoint_path, weights_only=True, map_location="cpu")
1161
+ model = ProvenanceLLaMA(llama_config)
1162
+ model.load_state_dict(sd)
1163
+ model = model.to(device)
1164
+ model.eval()
1165
+ log(f"LLaMA model on {device} ({sum(p.numel() for p in model.parameters()):,} params)")
1166
+
1167
+ # ── Load data ───────────────────────────────────────────────────────
1168
+ indexid2msg = get_indexid2msg(cfg)
1169
+ rel2id = get_rel2id(cfg)
1170
+ base_dir = cfg.transformation._graphs_dir
1171
+
1172
+ val_paths = get_all_graphs_for_dates(base_dir, cfg.dataset.val_dates)
1173
+ test_paths = get_all_graphs_for_dates(base_dir, cfg.dataset.test_dates)
1174
+
1175
+ splits = {"val": val_paths, "test": test_paths}
1176
+ model_epoch_dir = "model_epoch_0"
1177
+
1178
+ log(f"Graph context mode: {graph_context_mode}")
1179
+
1180
+ for split_name, graph_paths in splits.items():
1181
+ log(f"Perplexity scoring {split_name} ({len(graph_paths)} graphs)...")
1182
+
1183
+ # Build context graph(s) — same logic as CLS/LP modes
1184
+ if graph_context_mode == "all":
1185
+ split_context = _build_context_graph(graph_paths)
1186
+ log(f" {split_name}: merged context — {split_context.number_of_nodes():,} nodes, "
1187
+ f"{split_context.number_of_edges():,} edges")
1188
+ split_sampler = ProvenanceWalkSampler(
1189
+ split_context, walk_length=walk_length, num_walks=1,
1190
+ time_weight=time_weight, half_life=half_life,
1191
+ )
1192
+ elif graph_context_mode == "day":
1193
+ day_groups = _group_paths_by_day(graph_paths)
1194
+ day_samplers = {
1195
+ day: ProvenanceWalkSampler(
1196
+ _build_context_graph(paths),
1197
+ walk_length=walk_length, num_walks=1,
1198
+ time_weight=time_weight, half_life=half_life,
1199
+ )
1200
+ for day, paths in day_groups.items()
1201
+ }
1202
+
1203
+ for graph_path in log_tqdm(graph_paths, desc=f"Detect ({split_name})"):
1204
+ graph = torch.load(graph_path, weights_only=False)
1205
+ edges = _collect_edges(graph)
1206
+ if not edges:
1207
+ continue
1208
+
1209
+ # Build or reuse sampler
1210
+ if graph_context_mode == "all":
1211
+ sampler = split_sampler
1212
+ elif graph_context_mode == "day":
1213
+ day_folder = os.path.basename(os.path.dirname(graph_path))
1214
+ sampler = day_samplers.get(day_folder)
1215
+ if sampler is None:
1216
+ sampler = ProvenanceWalkSampler(
1217
+ graph, walk_length=walk_length, num_walks=1,
1218
+ time_weight=time_weight, half_life=half_life,
1219
+ )
1220
+ else: # window
1221
+ sampler = ProvenanceWalkSampler(
1222
+ graph, walk_length=walk_length, num_walks=1,
1223
+ time_weight=time_weight, half_life=half_life,
1224
+ )
1225
+
1226
+ # Score with optional multi-walk averaging
1227
+ if num_walks <= 1:
1228
+ edge_scores = _score_edges_perplexity(
1229
+ edges, sampler, model, tokenizer, indexid2msg,
1230
+ walk_length, batch_size, device,
1231
+ )
1232
+ else:
1233
+ all_scores = np.zeros(len(edges))
1234
+ for _ in range(num_walks):
1235
+ walk_scores = _score_edges_perplexity(
1236
+ edges, sampler, model, tokenizer, indexid2msg,
1237
+ walk_length, batch_size, device,
1238
+ )
1239
+ all_scores += np.array(walk_scores)
1240
+ edge_scores = (all_scores / num_walks).tolist()
1241
+
1242
+ # Build DataFrame
1243
+ rows = []
1244
+ for (src, dst, etype, ts), score in zip(edges, edge_scores):
1245
+ rows.append({
1246
+ "loss": float(score),
1247
+ "srcnode": int(src),
1248
+ "dstnode": int(dst),
1249
+ "time": int(ts),
1250
+ "edge_type": int(rel2id.get(etype, 0)),
1251
+ })
1252
+ edge_df = pd.DataFrame(rows)
1253
+
1254
+ if edge_df.empty:
1255
+ continue
1256
+
1257
+ start_time = edge_df["time"].min()
1258
+ end_time = edge_df["time"].max()
1259
+ time_interval = (
1260
+ ns_time_to_datetime_US(start_time, timezone=cfg.dataset.timezone)
1261
+ + "~"
1262
+ + ns_time_to_datetime_US(end_time, timezone=cfg.dataset.timezone)
1263
+ )
1264
+
1265
+ csv_dir = os.path.join(edge_losses_dir, split_name, model_epoch_dir)
1266
+ os.makedirs(csv_dir, exist_ok=True)
1267
+ csv_file = os.path.join(csv_dir, time_interval + ".csv")
1268
+ edge_df.to_csv(csv_file, sep=",", header=True, index=False, encoding="utf-8")
1269
+
1270
+ log(f" {split_name} CSVs written to {os.path.join(edge_losses_dir, split_name)}")
1271
+
1272
+ log("Perplexity detection complete.")
1273
+
1274
+
1275
+ def main(cfg):
1276
+ """Score val/test edges with SPIDER and write CSV files.
1277
+
1278
+ Modes:
1279
+ cls: CLS fine-tuning + sigmoid scoring
1280
+ lp: LP fine-tuning + mean cross-entropy scoring
1281
+ mlm: pretrained model only (no fine-tuning) + CE scoring
1282
+ tgn: TGN with attention-based entity memory
1283
+ edge_cls: edge type prediction from static BERT entity embeddings
1284
+ perplexity: decoder-only LLaMA, direct perplexity scoring (no fine-tuning)
1285
+ """
1286
+ log_start(__file__)
1287
+
1288
+ pretrain_cfg = cfg.featurization.pretrained
1289
+ detect_cfg = cfg.training.pretrained
1290
+ model_type = pretrain_cfg.model_type
1291
+ model_size = pretrain_cfg.model_size
1292
+ finetune_mode = detect_cfg.finetune_mode
1293
+
1294
+ # TGN uses a completely different pipeline (temporal scoring with memory updates)
1295
+ if finetune_mode == "tgn":
1296
+ _detect_tgn(cfg)
1297
+ return
1298
+
1299
+ if finetune_mode == "edge_cls":
1300
+ _detect_edge_cls(cfg)
1301
+ return
1302
+
1303
+ if finetune_mode == "perplexity":
1304
+ _detect_perplexity(cfg)
1305
+ return
1306
+
1307
+ walk_length = detect_cfg.finetune_walk_len
1308
+ freeze_backbone = detect_cfg.freeze_backbone
1309
+ batch_size = detect_cfg.inference_batch_size
1310
+ num_walks = detect_cfg.num_inference_walks
1311
+ time_weight = pretrain_cfg.walks.time_weight
1312
+ half_life = pretrain_cfg.walks.half_life
1313
+ mask_edge_type = pretrain_cfg.mlm.mask_edge_type
1314
+ edge_score_weight = detect_cfg.edge_score_weight if mask_edge_type else 0.0
1315
+ graph_context_mode = pretrain_cfg.graph_context_mode
1316
+ log(f"Graph context mode: {graph_context_mode}")
1317
+
1318
+ device = "cuda" if torch.cuda.is_available() and not cfg._use_cpu else "cpu"
1319
+
1320
+ # ── Directories ────────────────────────────────────────────────────
1321
+ pretrain_dir = cfg.featurization._model_dir
1322
+ ft_dir = cfg.training._trained_models_dir
1323
+
1324
+ # ── Load tokenizer ──────────────────────────────────────────────────
1325
+ tokenizer = ProvenanceTokenizer(cfg)
1326
+ tokenizer.load(os.path.join(pretrain_dir, "tokenizer.pt"))
1327
+ log(f"Loaded tokenizer (vocab_size={tokenizer.vocab_size})")
1328
+
1329
+ # ── Load model ─────────────────────────────────────────────────────
1330
+ if finetune_mode == "mlm":
1331
+ model = _load_pretrained_model(pretrain_dir, tokenizer, model_size, device, model_type, pretrain_cfg)
1332
+ else:
1333
+ from .finetune import main as finetune_main
1334
+ finetune_main(cfg)
1335
+ model = _load_finetuned_model(
1336
+ pretrain_dir, ft_dir, tokenizer, model_size, model_type, finetune_mode, freeze_backbone, device, pretrain_cfg,
1337
+ )
1338
+ log(f"Model on {device} ({sum(p.numel() for p in model.parameters()):,} params)")
1339
+
1340
+ # ── Load data ───────────────────────────────────────────────────────
1341
+ indexid2msg = get_indexid2msg(cfg)
1342
+ rel2id = get_rel2id(cfg)
1343
+ base_dir = cfg.transformation._graphs_dir
1344
+ edge_losses_dir = cfg.training._edge_losses_dir
1345
+
1346
+ train_paths = get_all_graphs_for_dates(base_dir, cfg.dataset.train_dates)
1347
+ val_paths = get_all_graphs_for_dates(base_dir, cfg.dataset.val_dates)
1348
+ test_paths = get_all_graphs_for_dates(base_dir, cfg.dataset.test_dates)
1349
+
1350
+ splits = {
1351
+ "val": val_paths,
1352
+ "test": test_paths,
1353
+ }
1354
+
1355
+ # ── Score edges and write CSVs ──────────────────────────────────────
1356
+ model_epoch_dir = "model_epoch_0"
1357
+
1358
+ for split_name, graph_paths in splits.items():
1359
+ log(f"Scoring {split_name} edges ({len(graph_paths)} graphs, context={graph_context_mode})...")
1360
+
1361
+ # Build context graph(s) for this split.
1362
+ # window: no merged context; sampler uses only the current snapshot.
1363
+ # day: one merged context graph per calendar day; walks can cross
1364
+ # windows within the same day but not across days.
1365
+ # all: one merged context graph from all snapshots in this split;
1366
+ # no training data is included, so no leakage across splits.
1367
+ if graph_context_mode == "all":
1368
+ split_context = _build_context_graph(graph_paths)
1369
+ log(f" {split_name}: merged context — {split_context.number_of_nodes():,} nodes, "
1370
+ f"{split_context.number_of_edges():,} edges")
1371
+ split_sampler = ProvenanceWalkSampler(
1372
+ split_context, walk_length=walk_length, num_walks=1,
1373
+ time_weight=time_weight, half_life=half_life,
1374
+ )
1375
+ log(f" {split_name}: sampler built (forward+backward adj ready)")
1376
+ elif graph_context_mode == "day":
1377
+ day_groups = _group_paths_by_day(graph_paths)
1378
+ day_contexts = {day: _build_context_graph(paths)
1379
+ for day, paths in day_groups.items()}
1380
+ day_samplers = {
1381
+ day: ProvenanceWalkSampler(
1382
+ ctx, walk_length=walk_length, num_walks=1,
1383
+ time_weight=time_weight, half_life=half_life,
1384
+ )
1385
+ for day, ctx in day_contexts.items()
1386
+ }
1387
+ log(f" {split_name}: {len(day_samplers)} day-level samplers built")
1388
+
1389
+ for graph_path in log_tqdm(graph_paths, desc=f"Detect ({split_name})"):
1390
+ graph = torch.load(graph_path)
1391
+
1392
+ if graph_context_mode == "window":
1393
+ prebuilt = None
1394
+ context = None
1395
+ elif graph_context_mode == "all":
1396
+ prebuilt = split_sampler
1397
+ context = None
1398
+ else: # day
1399
+ day_folder = os.path.basename(os.path.dirname(graph_path))
1400
+ prebuilt = day_samplers.get(day_folder)
1401
+ context = None
1402
+
1403
+ edge_df = _score_graph(
1404
+ graph, model, tokenizer, indexid2msg, rel2id,
1405
+ finetune_mode, walk_length, batch_size,
1406
+ time_weight, half_life, device, num_walks,
1407
+ edge_score_weight,
1408
+ context_graph=context,
1409
+ prebuilt_sampler=prebuilt,
1410
+ )
1411
+
1412
+ if edge_df.empty:
1413
+ continue
1414
+
1415
+ # Build time interval string for filename
1416
+ start_time = edge_df["time"].min()
1417
+ end_time = edge_df["time"].max()
1418
+ time_interval = (
1419
+ ns_time_to_datetime_US(start_time, timezone=cfg.dataset.timezone)
1420
+ + "~"
1421
+ + ns_time_to_datetime_US(end_time, timezone=cfg.dataset.timezone)
1422
+ )
1423
+
1424
+ # Write CSV
1425
+ csv_dir = os.path.join(edge_losses_dir, split_name, model_epoch_dir)
1426
+ os.makedirs(csv_dir, exist_ok=True)
1427
+ csv_file = os.path.join(csv_dir, time_interval + ".csv")
1428
+ edge_df.to_csv(csv_file, sep=",", header=True, index=False, encoding="utf-8")
1429
+
1430
+ log(f" {split_name} CSVs written to {os.path.join(edge_losses_dir, split_name)}")
1431
+
1432
+ log("Detection complete.")