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,502 @@
1
+ """SPIDER pretraining branch: GNN teacher distilled into a T5 student."""
2
+
3
+ import json
4
+ import os
5
+ import random
6
+ import time
7
+ from collections import defaultdict
8
+
9
+ import torch
10
+ import torch.nn.functional as F
11
+ from torch.optim import AdamW
12
+
13
+ import wandb
14
+
15
+ from pidsmaker.utils.utils import log
16
+ from ..training_utils import WarmupCosineScheduler, pad_token_id_lists, update_ema, build_pk_batches
17
+ from ..data.tokenizer_bpe import ProvenanceTokenizerBPE as ProvenanceTokenizer
18
+ from .pretrain_common import _eval_knn_on_eval_set
19
+
20
+
21
+ def pretrain_spider(cfg, spider_cfg, sampler_pairs, combined_indexid2msg, out_dir, device,
22
+ model_size, max_seq_len, bpe_vocab_size, tokenizer_mode,
23
+ normalize_netflow_ips, canonicalize_neighbors, spider_path,
24
+ total_tokens, warmup_tokens, batch_size, lr):
25
+ from copy import deepcopy
26
+ from ..models.spider import (
27
+ ProvenanceGNNCluster, GNNClusterTeacher,
28
+ get_spider_encoder_config,
29
+ build_gnn_distill_batch, build_edge_type_encoder,
30
+ supervised_contrastive_loss, sce_loss,
31
+ StudentSignatureHead, StudentClassHead, TeacherClassHead,
32
+ )
33
+ from ..data.behavior_signatures import build_behavior_dataset, BehaviorLabelVocab
34
+ from ..data.entity_classes import classify_entity
35
+
36
+ gc_cfg = spider_cfg.spider
37
+ gc_edge_emb_dim = gc_cfg.emb_dim
38
+ gc_hidden_dim = gc_cfg.hidden_dim
39
+ gc_proj_dim = gc_cfg.proj_dim
40
+ gc_num_heads = gc_cfg.num_heads
41
+ gc_n_neighbors_min = gc_cfg.n_neighbors_min
42
+ gc_n_neighbors_max = gc_cfg.n_neighbors_max
43
+ gc_diverse = gc_cfg.diverse_neighbors
44
+ gc_filter_noisy = gc_cfg.filter_noisy_edges
45
+ gc_ema_momentum = gc_cfg.ema_momentum
46
+ gc_supcon_weight = gc_cfg.supcon_weight
47
+ gc_distill_weight = gc_cfg.distill_weight
48
+ gc_temperature = gc_cfg.temperature
49
+ gc_min_sig_size = gc_cfg.min_signature_size
50
+ gc_min_per_class = gc_cfg.min_entities_per_class
51
+ gc_max_per_class = gc_cfg.max_entities_per_class
52
+ gc_samples_per_class = gc_cfg.samples_per_class
53
+ gc_strip_entity_type = gc_cfg.strip_entity_type
54
+ gc_distill_loss = getattr(gc_cfg, 'distill_loss', 'sce')
55
+ gc_teacher_loss = getattr(gc_cfg, 'teacher_loss', 'contrastive')
56
+ gc_teacher_data = getattr(gc_cfg, 'teacher_data', 'signature,gnn_emb')
57
+ gc_student_only_mode = getattr(gc_cfg, 'student_only_mode', 'none')
58
+
59
+ # ── Build or load tokenizer ────────────────────────────────────
60
+ if spider_path:
61
+ tok_path = os.path.join(spider_path, "tokenizer.pt")
62
+ log(f"Loading tokenizer from {tok_path}")
63
+ tokenizer = ProvenanceTokenizer(cfg, max_seq_len=max_seq_len, bpe_vocab_size=bpe_vocab_size,
64
+ mode=tokenizer_mode, normalize_netflow_ips=normalize_netflow_ips,
65
+ canonicalize_neighbors=canonicalize_neighbors)
66
+ tokenizer.load(tok_path)
67
+ tokenizer.max_seq_len = max_seq_len
68
+ else:
69
+ walk_label_corpus = []
70
+ for sampler, ds_indexid2msg in sampler_pairs:
71
+ for node in sampler.nodes:
72
+ if node in ds_indexid2msg:
73
+ walk_label_corpus.append(ds_indexid2msg[node])
74
+ log(f"GNN cluster: {len(walk_label_corpus):,} entity labels for tokenizer")
75
+ tokenizer = ProvenanceTokenizer(
76
+ cfg, max_seq_len=max_seq_len, bpe_vocab_size=bpe_vocab_size,
77
+ mode=tokenizer_mode, normalize_netflow_ips=normalize_netflow_ips,
78
+ canonicalize_neighbors=canonicalize_neighbors,
79
+ strip_entity_type=gc_strip_entity_type,
80
+ )
81
+ tokenizer.build_vocab(combined_indexid2msg, walk_label_corpus=walk_label_corpus)
82
+ log(f"Vocabulary size: {tokenizer.vocab_size}")
83
+ tokenizer.save(os.path.join(out_dir, "tokenizer.pt"))
84
+
85
+ # ── Build edge type encoder for GNN ───────────────────────────
86
+ gnn_edge_type2idx = build_edge_type_encoder(sampler_pairs)
87
+ log(f"GNN cluster: {len(gnn_edge_type2idx)} directed edge types")
88
+ with open(os.path.join(out_dir, "edge_type2idx.json"), "w") as f:
89
+ json.dump(gnn_edge_type2idx, f)
90
+
91
+ # ── Build behavior dataset (for entity class assignment) ──────
92
+ log("Building behavior signatures for entity class assignment...")
93
+ label_to_signature, label_to_entities_raw, vocab = build_behavior_dataset(
94
+ sampler_pairs, combined_indexid2msg,
95
+ filter_noisy=gc_filter_noisy, min_signature_size=gc_min_sig_size,
96
+ )
97
+ log(f"Behavior signatures: {len(label_to_signature):,} unique entity labels")
98
+ vocab.save(os.path.join(out_dir, "behavior_vocab.txt"))
99
+
100
+ # ── Tokenize entities and assign entity class IDs ─────────────
101
+ if gc_filter_noisy:
102
+ from ..data.edge_filter import _is_noisy_file, _is_noisy_process
103
+
104
+ label_to_entities = defaultdict(list)
105
+ for label_key, raw_entities in label_to_entities_raw.items():
106
+ ntype, nlabel = label_key
107
+ entity_ids = tokenizer.tokenize_node(ntype, nlabel)
108
+ if entity_ids:
109
+ for node_id, sidx in raw_entities:
110
+ label_to_entities[label_key].append((node_id, sidx, entity_ids))
111
+
112
+ # Post-tokenization dedup (same as behavior_cluster)
113
+ token_sig_to_label = {}
114
+ merged_count = 0
115
+ for label_key in list(label_to_entities.keys()):
116
+ entity_ids = label_to_entities[label_key][0][2]
117
+ token_sig = tuple(entity_ids)
118
+ if token_sig in token_sig_to_label:
119
+ canonical = token_sig_to_label[token_sig]
120
+ label_to_signature[canonical] = label_to_signature[canonical] | label_to_signature[label_key]
121
+ label_to_entities[canonical].extend(label_to_entities[label_key])
122
+ del label_to_entities[label_key]
123
+ del label_to_signature[label_key]
124
+ merged_count += 1
125
+ else:
126
+ token_sig_to_label[token_sig] = label_key
127
+
128
+ # Entity class IDs (~70 coarse functional classes)
129
+ entity_class_to_id = {}
130
+ label_to_entity_class_id = {}
131
+ for label_key in label_to_entities:
132
+ ntype, nlabel = label_key
133
+ ecls = classify_entity(ntype, nlabel)
134
+ if ecls not in entity_class_to_id:
135
+ entity_class_to_id[ecls] = len(entity_class_to_id)
136
+ label_to_entity_class_id[label_key] = entity_class_to_id[ecls]
137
+
138
+ # Pre-compute signature target vectors (binary multilabel)
139
+ label_to_target = {}
140
+ for label_key, sig in label_to_signature.items():
141
+ if label_key in label_to_entities:
142
+ label_to_target[label_key] = vocab.signature_to_vector(sig)
143
+
144
+ n_entity_classes = len(entity_class_to_id)
145
+ n_total = sum(len(v) for v in label_to_entities.values())
146
+ log(f"GNN cluster: {n_total:,} trainable entities, "
147
+ f"{len(label_to_entities):,} unique labels "
148
+ f"(deduped {merged_count:,}), {n_entity_classes} entity classes, "
149
+ f"{vocab.size} behavior labels")
150
+
151
+ # ── Stratified train/val split by entity class ────────────────
152
+ class_to_label_keys = defaultdict(list)
153
+ for label_key in label_to_entities:
154
+ class_to_label_keys[label_to_entity_class_id[label_key]].append(label_key)
155
+
156
+ val_labels = set()
157
+ for class_id, class_label_keys in class_to_label_keys.items():
158
+ if len(class_label_keys) >= 10:
159
+ random.shuffle(class_label_keys)
160
+ n_val = max(1, int(len(class_label_keys) * 0.05))
161
+ val_labels.update(class_label_keys[:n_val])
162
+
163
+ train_label_to_entities = defaultdict(list)
164
+ val_label_to_entities = defaultdict(list)
165
+ for label_key, entities in label_to_entities.items():
166
+ if label_key in val_labels:
167
+ val_label_to_entities[label_key] = entities
168
+ else:
169
+ train_label_to_entities[label_key] = entities
170
+
171
+ n_val_classes = len({label_to_entity_class_id[lk] for lk in val_label_to_entities})
172
+ log(f"GNN cluster: {len(train_label_to_entities):,} train / "
173
+ f"{len(val_label_to_entities):,} val unique labels "
174
+ f"(val covers {n_val_classes} classes)")
175
+
176
+ K = gc_samples_per_class
177
+ P = batch_size // K
178
+ log(f" P×K batching: K={K} samples/class, P={P} classes/batch")
179
+
180
+ # ── Build models ──────────────────────────────────────────────
181
+ enc_config = get_spider_encoder_config(tokenizer.vocab_size, model_size, max_seq_len)
182
+ t5_hidden_dim = enc_config.d_model
183
+ use_teacher = gc_student_only_mode == "none"
184
+
185
+ model = ProvenanceGNNCluster(enc_config, gc_hidden_dim).to(device)
186
+ log(f"Model: GNNCluster-{model_size} (T5 encoder H={t5_hidden_dim} → {gc_hidden_dim}d GNN space)")
187
+ log(f" Student params: {sum(p.numel() for p in model.parameters()):,}")
188
+
189
+ # Student-only ablation heads
190
+ student_sig_head = None
191
+ student_cls_head = None
192
+ if gc_student_only_mode == "student_signature":
193
+ student_sig_head = StudentSignatureHead(gc_hidden_dim, vocab.size).to(device)
194
+ log(f" Student-only ablation: predict signature ({vocab.size} labels)")
195
+ elif gc_student_only_mode == "student_class":
196
+ student_cls_head = StudentClassHead(gc_hidden_dim, n_entity_classes).to(device)
197
+ log(f" Student-only ablation: predict entity class ({n_entity_classes} classes)")
198
+
199
+ # Teacher components (only when not in student-only mode)
200
+ ema_teacher = None
201
+ gnn_teacher = None
202
+ teacher_cls_head = None
203
+ if use_teacher:
204
+ ema_teacher = deepcopy(model).to(device)
205
+ ema_teacher.requires_grad_(False)
206
+ ema_teacher.eval()
207
+ log(f" EMA teacher: copy of student (momentum={gc_ema_momentum})")
208
+
209
+ gnn_teacher = GNNClusterTeacher(
210
+ node_dim=t5_hidden_dim,
211
+ num_edge_types=max(len(gnn_edge_type2idx), 1),
212
+ edge_emb_dim=gc_edge_emb_dim,
213
+ hidden_dim=gc_hidden_dim,
214
+ num_labels=vocab.size,
215
+ proj_dim=gc_proj_dim,
216
+ num_heads=gc_num_heads,
217
+ teacher_data=gc_teacher_data,
218
+ ).to(device)
219
+ log(f" GNN teacher params: {sum(p.numel() for p in gnn_teacher.parameters()):,}")
220
+ log(f" teacher_data={gc_teacher_data}, teacher_loss={gc_teacher_loss}, "
221
+ f"distill_loss={gc_distill_loss}")
222
+ log(f" supcon_weight={gc_supcon_weight}, distill_weight={gc_distill_weight}, τ={gc_temperature}")
223
+
224
+ if gc_teacher_loss == "bce":
225
+ teacher_cls_head = TeacherClassHead(gc_proj_dim, n_entity_classes).to(device)
226
+ log(f" Teacher BCE head: {gc_proj_dim} → {n_entity_classes} classes")
227
+
228
+ # ── Optimizer ─────────────────────────────────────────────────
229
+ all_params = list(model.parameters())
230
+ if gnn_teacher is not None:
231
+ all_params += list(gnn_teacher.parameters())
232
+ if teacher_cls_head is not None:
233
+ all_params += list(teacher_cls_head.parameters())
234
+ if student_sig_head is not None:
235
+ all_params += list(student_sig_head.parameters())
236
+ if student_cls_head is not None:
237
+ all_params += list(student_cls_head.parameters())
238
+ opt = AdamW(
239
+ all_params,
240
+ lr=lr, betas=(0.9, 0.95), eps=1e-8, weight_decay=0.1,
241
+ )
242
+ scheduler = WarmupCosineScheduler(opt, warmup_tokens, total_tokens)
243
+
244
+ # ── Training loop ─────────────────────────────────────────────
245
+ processed_tokens = 0
246
+ updates = 0
247
+ epoch = 0
248
+ best_knn_acc = -1.0
249
+
250
+ log_path = os.path.join(out_dir, f"spider_log_{model_size}.txt")
251
+ with open(log_path, "w") as f:
252
+ f.write("update,tokens,loss1,loss2,lr,time\n")
253
+
254
+ # EMA embedding cache
255
+ ema_cache = {}
256
+ ema_cache_refresh_interval = 50
257
+ ema_cache_last_refresh = -ema_cache_refresh_interval
258
+
259
+ while processed_tokens < total_tokens:
260
+ epoch += 1
261
+ epoch_st = time.time()
262
+ epoch_supcon = 0.0
263
+ epoch_distill = 0.0
264
+ epoch_batches = 0
265
+
266
+ # ── P×K batch construction by entity class ────────────────
267
+ class_to_labels = defaultdict(list)
268
+ for label_key in train_label_to_entities:
269
+ class_to_labels[label_to_entity_class_id[label_key]].append(label_key)
270
+
271
+ epoch_entities_by_class = defaultdict(list)
272
+ for class_id, class_label_keys in class_to_labels.items():
273
+ n_class = len(class_label_keys)
274
+ if gc_max_per_class > 0 and n_class > gc_max_per_class:
275
+ offset = (epoch - 1) * gc_max_per_class % n_class
276
+ indices = [(offset + i) % n_class for i in range(gc_max_per_class)]
277
+ class_label_keys = [class_label_keys[i] for i in indices]
278
+ elif gc_min_per_class > 0 and n_class < gc_min_per_class:
279
+ repeats = (gc_min_per_class + n_class - 1) // n_class
280
+ class_label_keys = (class_label_keys * repeats)[:gc_min_per_class]
281
+ for label_key in class_label_keys:
282
+ entities = train_label_to_entities[label_key]
283
+ pick = entities[(epoch - 1) % len(entities)]
284
+ epoch_entities_by_class[class_id].append((label_key, pick, class_id))
285
+
286
+ for items in epoch_entities_by_class.values():
287
+ random.shuffle(items)
288
+
289
+ epoch_batches_list = build_pk_batches(epoch_entities_by_class, P, K)
290
+
291
+ for batch_items in epoch_batches_list:
292
+ B = len(batch_items)
293
+ if B == 0:
294
+ continue
295
+
296
+ # ── Pad encoder inputs ────────────────────────────────
297
+ enc_ids_list = [item[1][2] for item in batch_items]
298
+ input_ids, attention_mask = pad_token_id_lists(enc_ids_list, tokenizer.pad_id, tokenizer.max_seq_len)
299
+
300
+ entity_class_ids = torch.tensor(
301
+ [label_to_entity_class_id[item[0]] for item in batch_items], dtype=torch.long,
302
+ )
303
+
304
+ # ── Build GNN neighborhood batch ──────────────────────
305
+ entity_nodes = [item[1][0] for item in batch_items]
306
+ sampler_idxs = [item[1][1] for item in batch_items]
307
+
308
+ gnn_batch = build_gnn_distill_batch(
309
+ entity_nodes, sampler_idxs, sampler_pairs,
310
+ combined_indexid2msg, gnn_edge_type2idx,
311
+ n_neighbors_min=gc_n_neighbors_min, n_neighbors_max=gc_n_neighbors_max,
312
+ diverse=gc_diverse, device=device,
313
+ filter_noisy=gc_filter_noisy,
314
+ )
315
+ if gnn_batch is None:
316
+ continue
317
+
318
+ node_labels, edge_index, edge_types, batch_vec, center_idx, valid_mask = gnn_batch
319
+ n_valid = valid_mask.sum().item()
320
+ if n_valid == 0:
321
+ continue
322
+
323
+ # ── Encode neighbor nodes with EMA teacher (cached) ───
324
+ if use_teacher:
325
+ need_refresh = (updates - ema_cache_last_refresh) >= ema_cache_refresh_interval
326
+ uncached_labels = [lbl for lbl in set(node_labels) if lbl not in ema_cache]
327
+
328
+ if need_refresh:
329
+ all_labels_to_encode = list(set(node_labels))
330
+ ema_cache_last_refresh = updates
331
+ elif uncached_labels:
332
+ all_labels_to_encode = uncached_labels
333
+ else:
334
+ all_labels_to_encode = []
335
+
336
+ if all_labels_to_encode:
337
+ ema_token_ids = []
338
+ for ntype, nlabel in all_labels_to_encode:
339
+ tids = tokenizer.tokenize_node(ntype, nlabel)
340
+ ema_token_ids.append(tids if tids else [tokenizer.pad_id])
341
+
342
+ ema_input_ids, ema_attn_mask = pad_token_id_lists(ema_token_ids, tokenizer.pad_id, tokenizer.max_seq_len)
343
+
344
+ ema_teacher.eval()
345
+ with torch.no_grad():
346
+ ema_embeddings = ema_teacher.mean_pool(ema_input_ids, ema_attn_mask)
347
+ for i, lbl in enumerate(all_labels_to_encode):
348
+ ema_cache[lbl] = ema_embeddings[i]
349
+
350
+ node_embeddings = torch.stack([ema_cache[lbl] for lbl in node_labels])
351
+
352
+ # ── Forward passes ────────────────────────────────────
353
+ model.train()
354
+
355
+ # Student: T5 encoder → project to GNN space
356
+ out = model.modified_fwd(input_ids.to(device), attention_mask.to(device))
357
+ t5_projected = out.projected # [B, hidden_dim]
358
+
359
+ valid_mask_cpu = valid_mask.cpu()
360
+ valid_class_ids = entity_class_ids[valid_mask_cpu].to(device)
361
+
362
+ if use_teacher:
363
+ # ── Teacher-student mode ──────────────────────────
364
+ gnn_teacher.train()
365
+ if teacher_cls_head is not None:
366
+ teacher_cls_head.train()
367
+
368
+ # Build signature vectors for valid entities
369
+ valid_label_keys = [batch_items[i][0] for i in range(B) if valid_mask_cpu[i]]
370
+ sig_vecs = torch.stack([label_to_target[lk] for lk in valid_label_keys]).to(device)
371
+
372
+ # GNN teacher: encode neighborhood + fuse
373
+ teacher_proj = gnn_teacher(
374
+ node_embeddings, edge_index, edge_types, center_idx,
375
+ signature_vectors=sig_vecs,
376
+ )
377
+
378
+ # L_teacher: SupCon or BCE on entity class
379
+ if gc_teacher_loss == "bce":
380
+ cls_logits = teacher_cls_head(teacher_proj)
381
+ supcon_loss = F.cross_entropy(cls_logits, valid_class_ids)
382
+ else:
383
+ supcon_loss = supervised_contrastive_loss(
384
+ teacher_proj, valid_class_ids, temperature=gc_temperature,
385
+ )
386
+
387
+ # L_distill: SCE or MSE
388
+ if gc_distill_loss == "mse":
389
+ distill_loss = F.mse_loss(t5_projected[valid_mask], teacher_proj.detach())
390
+ else:
391
+ distill_loss = sce_loss(t5_projected[valid_mask], teacher_proj.detach())
392
+
393
+ total_loss = gc_supcon_weight * supcon_loss + gc_distill_weight * distill_loss
394
+ else:
395
+ # ── Student-only ablation modes ───────────────────
396
+ valid_label_keys = [batch_items[i][0] for i in range(B) if valid_mask_cpu[i]]
397
+
398
+ if gc_student_only_mode == "student_signature":
399
+ student_sig_head.train()
400
+ sig_logits = student_sig_head(t5_projected[valid_mask])
401
+ sig_targets = torch.stack([label_to_target[lk] for lk in valid_label_keys]).to(device)
402
+ supcon_loss = F.binary_cross_entropy_with_logits(sig_logits, sig_targets)
403
+ distill_loss = torch.tensor(0.0, device=device)
404
+ elif gc_student_only_mode == "student_class":
405
+ student_cls_head.train()
406
+ cls_logits = student_cls_head(t5_projected[valid_mask])
407
+ supcon_loss = F.cross_entropy(cls_logits, valid_class_ids)
408
+ distill_loss = torch.tensor(0.0, device=device)
409
+
410
+ total_loss = supcon_loss
411
+
412
+ total_loss.backward()
413
+ torch.nn.utils.clip_grad_norm_(model.parameters(), 5.0)
414
+ if gnn_teacher is not None:
415
+ torch.nn.utils.clip_grad_norm_(gnn_teacher.parameters(), 5.0)
416
+ opt.step()
417
+ opt.zero_grad()
418
+
419
+ # ── EMA update ────────────────────────────────────────
420
+ if ema_teacher is not None:
421
+ update_ema(ema_teacher, model, gc_ema_momentum)
422
+
423
+ # ── Tracking ──────────────────────────────────────────
424
+ n_tokens = int(attention_mask.sum().item())
425
+ if n_tokens == 0:
426
+ continue
427
+
428
+ processed_tokens += n_tokens
429
+ scheduler.last_epoch = processed_tokens
430
+ scheduler.step()
431
+ updates += 1
432
+
433
+ sc_val = supcon_loss.item()
434
+ dl_val = distill_loss.item()
435
+ epoch_supcon += sc_val
436
+ epoch_distill += dl_val
437
+ epoch_batches += 1
438
+ current_lr = scheduler.get_last_lr()[0]
439
+
440
+ if updates % 100 == 0:
441
+ elapsed = time.time() - epoch_st
442
+ log(
443
+ f"[{updates}|e{epoch}] supcon={sc_val:.4f} distill={dl_val:.4f} "
444
+ f"valid={n_valid}/{B} lr={current_lr:.2e} "
445
+ f"tokens={processed_tokens:.2e} ({elapsed:.1f}s)"
446
+ )
447
+ with open(log_path, "a") as f:
448
+ f.write(f"{updates},{processed_tokens},{sc_val:.6f},"
449
+ f"{dl_val:.6f},{current_lr:.2e},{elapsed:.1f}\n")
450
+
451
+ if processed_tokens >= total_tokens:
452
+ break
453
+
454
+ if processed_tokens >= total_tokens:
455
+ break
456
+
457
+ # Epoch-level logging
458
+ if epoch_batches > 0:
459
+ avg_sc = epoch_supcon / epoch_batches
460
+ avg_dl = epoch_distill / epoch_batches
461
+ elapsed = time.time() - epoch_st
462
+ log(f"Epoch {epoch} done | supcon={avg_sc:.4f} distill={avg_dl:.4f} "
463
+ f"batches={epoch_batches} ({elapsed:.1f}s)")
464
+
465
+ # ── KNN eval ──────────────────────────────────────────────
466
+ epoch_metrics = {"pretrain/epoch": epoch, "pretrain/tokens": processed_tokens}
467
+ knn_results = _eval_knn_on_eval_set(model, tokenizer, device, "spider", batch_size)
468
+ if knn_results:
469
+ knn_acc = knn_results['knn_accuracy_k5']
470
+ epoch_metrics["pretrain/knn_accuracy_k5"] = knn_acc
471
+ for cl, acc in knn_results['knn_accuracy_k5_per_cluster'].items():
472
+ epoch_metrics[f"pretrain/knn_k5/{cl}"] = acc
473
+ epoch_metrics["pretrain/ari"] = knn_results['ari']
474
+ epoch_metrics["pretrain/nmi"] = knn_results['nmi']
475
+ epoch_metrics["pretrain/silhouette"] = knn_results['silhouette']
476
+ epoch_metrics["pretrain/mAP"] = knn_results['mAP']
477
+ if knn_acc > best_knn_acc:
478
+ best_knn_acc = knn_acc
479
+ torch.save(model.state_dict(), os.path.join(out_dir, f"pretrain_{model_size}_best.pt"))
480
+ if gnn_teacher is not None:
481
+ torch.save(gnn_teacher.state_dict(), os.path.join(out_dir, f"gnn_teacher_{model_size}_best.pt"))
482
+ log(f"Epoch {epoch} knn_accuracy_k5={knn_acc:.4f} "
483
+ f"ARI={knn_results['ari']:.4f} NMI={knn_results['nmi']:.4f} "
484
+ f"silhouette={knn_results['silhouette']:.4f} mAP={knn_results['mAP']:.4f} "
485
+ f"*** new best ***")
486
+ else:
487
+ log(f"Epoch {epoch} knn_accuracy_k5={knn_acc:.4f} "
488
+ f"ARI={knn_results['ari']:.4f} NMI={knn_results['nmi']:.4f} "
489
+ f"silhouette={knn_results['silhouette']:.4f} mAP={knn_results['mAP']:.4f}")
490
+ epoch_metrics["pretrain/best_knn_acc"] = best_knn_acc
491
+
492
+ torch.save(model.state_dict(), os.path.join(out_dir, f"pretrain_{model_size}.pt"))
493
+ if gnn_teacher is not None:
494
+ torch.save(gnn_teacher.state_dict(), os.path.join(out_dir, f"gnn_teacher_{model_size}.pt"))
495
+ wandb.log(epoch_metrics)
496
+
497
+ # Final save
498
+ torch.save(model.state_dict(), os.path.join(out_dir, f"pretrain_{model_size}.pt"))
499
+ if gnn_teacher is not None:
500
+ torch.save(gnn_teacher.state_dict(), os.path.join(out_dir, f"gnn_teacher_{model_size}.pt"))
501
+ tokenizer.save(os.path.join(out_dir, "tokenizer.pt"))
502
+ log(f"GNN cluster pretraining complete. {processed_tokens:,} tokens in {epoch} epochs.")
@@ -0,0 +1,157 @@
1
+ """Shared training utilities for SPIDER pretraining and fine-tuning.
2
+
3
+ Extracts common patterns: LR schedulers, batch padding, EMA updates,
4
+ P×K batch construction.
5
+ """
6
+
7
+ import math
8
+ import random
9
+ from collections import defaultdict
10
+
11
+ import torch
12
+ from torch.optim.lr_scheduler import LRScheduler
13
+
14
+
15
+ # ── Learning rate schedulers ──────────────────────────────────────────────────
16
+
17
+ class WarmupLinearScheduler(LRScheduler):
18
+ """Warmup + linear decay scheduler (matching CyberGFM)."""
19
+
20
+ def __init__(self, optimizer, warmup_steps, total_steps, last_epoch=-1):
21
+ self.warmup_steps = warmup_steps
22
+ self.total_steps = total_steps
23
+ super().__init__(optimizer, last_epoch)
24
+
25
+ def get_lr(self):
26
+ if self.last_epoch < self.warmup_steps:
27
+ scale = self.last_epoch / max(1, self.warmup_steps)
28
+ else:
29
+ scale = max(
30
+ 1e-8,
31
+ 1 - (self.last_epoch - self.warmup_steps) / (self.total_steps - self.warmup_steps),
32
+ )
33
+ return [group["initial_lr"] * scale for group in self.optimizer.param_groups]
34
+
35
+
36
+ class WarmupCosineScheduler(LRScheduler):
37
+ """Warmup + cosine annealing scheduler."""
38
+
39
+ def __init__(self, optimizer, warmup_steps, total_steps, min_lr_ratio=0.1, last_epoch=-1):
40
+ self.warmup_steps = warmup_steps
41
+ self.total_steps = total_steps
42
+ self.min_lr_ratio = min_lr_ratio
43
+ super().__init__(optimizer, last_epoch)
44
+
45
+ def get_lr(self):
46
+ if self.last_epoch < self.warmup_steps:
47
+ scale = self.last_epoch / max(1, self.warmup_steps)
48
+ else:
49
+ progress = (self.last_epoch - self.warmup_steps) / max(1, self.total_steps - self.warmup_steps)
50
+ scale = self.min_lr_ratio + 0.5 * (1 - self.min_lr_ratio) * (1 + math.cos(math.pi * progress))
51
+ return [group["initial_lr"] * scale for group in self.optimizer.param_groups]
52
+
53
+
54
+ # ── Batch padding ─────────────────────────────────────────────────────────────
55
+
56
+ def pad_token_id_lists(token_id_lists, pad_id, max_seq_len=None):
57
+ """Pad a list of variable-length token ID lists into a batch.
58
+
59
+ Args:
60
+ token_id_lists: List[List[int]] — raw token ID sequences.
61
+ pad_id: Padding token ID.
62
+ max_seq_len: Optional cap on sequence length.
63
+
64
+ Returns:
65
+ input_ids: [B, L] LongTensor, padded with pad_id.
66
+ attention_mask: [B, L] BoolTensor, True for real tokens.
67
+ """
68
+ if max_seq_len is not None:
69
+ max_len = min(max(len(s) for s in token_id_lists), max_seq_len)
70
+ else:
71
+ max_len = max(len(s) for s in token_id_lists)
72
+ B = len(token_id_lists)
73
+ input_ids = torch.full((B, max_len), pad_id, dtype=torch.long)
74
+ attention_mask = torch.zeros(B, max_len, dtype=torch.bool)
75
+ for i, tids in enumerate(token_id_lists):
76
+ seq_len = min(len(tids), max_len)
77
+ input_ids[i, :seq_len] = torch.tensor(tids[:seq_len])
78
+ attention_mask[i, :seq_len] = True
79
+ return input_ids, attention_mask
80
+
81
+
82
+ def pad_tensor_batch(tensors, pad_value=0):
83
+ """Pad a list of 1-D tensors to the same length.
84
+
85
+ Args:
86
+ tensors: List[Tensor] of shape [Li].
87
+ pad_value: Fill value for padding positions.
88
+
89
+ Returns:
90
+ Tensor of shape [B, max_L] with the same dtype as the input tensors.
91
+ """
92
+ max_len = max(t.size(0) for t in tensors)
93
+ B = len(tensors)
94
+ out = torch.full((B, max_len), pad_value, dtype=tensors[0].dtype)
95
+ for i, t in enumerate(tensors):
96
+ L = t.size(0)
97
+ out[i, :L] = t
98
+ return out
99
+
100
+
101
+ # ── EMA ───────────────────────────────────────────────────────────────────────
102
+
103
+ @torch.no_grad()
104
+ def update_ema(ema_model, student_model, momentum):
105
+ """Exponential moving average update: ema = momentum * ema + (1-momentum) * student."""
106
+ for ema_p, student_p in zip(ema_model.parameters(), student_model.parameters()):
107
+ ema_p.data.mul_(momentum).add_(student_p.data, alpha=1.0 - momentum)
108
+
109
+
110
+ # ── P×K batch construction ───────────────────────────────────────────────────
111
+
112
+ def build_pk_batches(epoch_entities_by_class, P, K):
113
+ """Construct P×K batches from per-class entity pools.
114
+
115
+ Iterates through available classes, picking P classes per batch and K samples
116
+ per class. When a class has fewer than K remaining items, pads with random
117
+ duplicates from that class's full pool. Exhausted classes are removed.
118
+ Both the class iteration order and the final batch list are shuffled.
119
+
120
+ Expects per-class items to already be shuffled by the caller.
121
+
122
+ Args:
123
+ epoch_entities_by_class: dict mapping class_id -> list of items.
124
+ P: Number of classes per batch.
125
+ K: Number of samples per class.
126
+
127
+ Returns:
128
+ List of batches, each batch a flat list of items.
129
+ """
130
+ class_ids_avail = list(epoch_entities_by_class.keys())
131
+ random.shuffle(class_ids_avail)
132
+ class_cursors = {cid: 0 for cid in class_ids_avail}
133
+
134
+ epoch_batches_list = []
135
+ while class_ids_avail:
136
+ batch_items = []
137
+ classes_this_batch = class_ids_avail[:P]
138
+ for cid in classes_this_batch:
139
+ pool = epoch_entities_by_class[cid]
140
+ cursor = class_cursors[cid]
141
+ remaining = len(pool) - cursor
142
+ if remaining >= K:
143
+ batch_items.extend(pool[cursor:cursor + K])
144
+ class_cursors[cid] = cursor + K
145
+ else:
146
+ taken = list(pool[cursor:])
147
+ while len(taken) < K:
148
+ taken.append(random.choice(pool))
149
+ batch_items.extend(taken)
150
+ class_cursors[cid] = len(pool)
151
+ class_ids_avail = [cid for cid in class_ids_avail
152
+ if class_cursors[cid] < len(epoch_entities_by_class[cid])]
153
+ random.shuffle(class_ids_avail)
154
+ epoch_batches_list.append(batch_items)
155
+
156
+ random.shuffle(epoch_batches_list)
157
+ return epoch_batches_list