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,377 @@
1
+ """Training loop for PIDS models.
2
+
3
+ Handles model training with:
4
+ - Self-supervised pretraining with multiple objectives
5
+ - Optional few-shot fine-tuning for attack detection
6
+ - Gradient accumulation for large graphs
7
+ - Early stopping with patience
8
+ - Memory tracking (GPU and CPU)
9
+ - Validation-based model selection
10
+ """
11
+
12
+ import copy
13
+ import os
14
+ from time import perf_counter as timer
15
+
16
+ import numpy as np
17
+ import torch
18
+ import wandb
19
+
20
+ from pidsmaker.detection.flash_detection import flash_snapshot_ensemble
21
+ from pidsmaker.factory import (
22
+ build_model,
23
+ early_stop_tracker_factory,
24
+ optimizer_factory,
25
+ optimizer_few_shot_factory,
26
+ )
27
+ from pidsmaker.objectives.predict_node_type import NODE_LOSS_MASK_KEY
28
+ from pidsmaker.tasks.batching import get_preprocessed_graphs
29
+ from pidsmaker.utils.data_utils import batch_to_device, save_model
30
+ from pidsmaker.utils.utils import PeakCPUMemory, get_device, log, log_start, log_tqdm, set_seed
31
+
32
+ from . import inference_loop
33
+
34
+
35
+ def main(cfg):
36
+ """Main training loop executing self-supervised pretraining and optional few-shot fine-tuning.
37
+
38
+ Training process:
39
+ 1. Self-supervised pretraining on reconstruction/prediction objectives
40
+ 2. Optional few-shot fine-tuning on labeled attack data
41
+ 3. Validation-based model selection (best epoch or each epoch)
42
+ 4. Early stopping with configurable patience
43
+
44
+ Args:
45
+ cfg: Configuration with training hyperparameters (epochs, lr, patience, etc.)
46
+
47
+ Returns:
48
+ float: Best validation score achieved during training
49
+ """
50
+ log_start(__file__)
51
+ device = get_device(cfg)
52
+ use_cuda = device == torch.device("cuda")
53
+
54
+ # Reset the peak memory usage counter
55
+ if use_cuda:
56
+ torch.cuda.reset_peak_memory_stats(device=device)
57
+ cpu_mem = PeakCPUMemory()
58
+
59
+ train_data, val_data, test_data, max_node_num = get_preprocessed_graphs(cfg)
60
+ log("Graph data loaded.")
61
+ # Seed must be after `get_preprocessed_graphs` as this function may perform random operations
62
+ set_seed(cfg, seed=cfg.training.seed)
63
+
64
+ # Opt-in (`--save_for_viz`): cache the test graphs so the embedding visualizer
65
+ # can reload them instead of recomputing the whole batching pipeline. Off by
66
+ # default — the cache is large and most runs never open the viewer; when it is
67
+ # absent the exporter recomputes the graphs on demand. Only test_data is ever
68
+ # read back, so there is no need to persist the train/val graphs too.
69
+ if cfg._save_for_viz:
70
+ viz_cache_dir = cfg.batching._preprocessed_graphs_dir
71
+ os.makedirs(viz_cache_dir, exist_ok=True)
72
+ viz_cache_file = os.path.join(viz_cache_dir, "viz_test_graphs.pkl")
73
+ if not os.path.exists(viz_cache_file):
74
+ log("Caching test graphs to disk for visualization reuse...")
75
+ torch.save((test_data, max_node_num), viz_cache_file)
76
+
77
+ model = build_model(
78
+ data_sample=train_data[0][0], device=device, cfg=cfg, max_node_num=max_node_num,
79
+ all_data=(val_data, test_data),
80
+ )
81
+ if cfg._from_weights:
82
+ model.load_state_dict(torch.load(os.path.join(cfg._from_weights_path, "state_dict.pkl")))
83
+ optimizer = optimizer_factory(cfg, parameters=set(model.parameters()))
84
+ stable_optim = cfg.training.stable_optim
85
+
86
+ run_evaluation = cfg.training_loop.run_evaluation
87
+ assert run_evaluation in ["best_epoch", "each_epoch"], (
88
+ f"Invalid run evaluation {run_evaluation}"
89
+ )
90
+ best_epoch_mode = run_evaluation == "best_epoch"
91
+
92
+ num_epochs = 1 if cfg._from_weights else cfg.training.num_epochs
93
+ tot_loss = 0.0
94
+ epoch_times = []
95
+ peak_train_cpu_mem = 0
96
+ peak_train_gpu_mem = 0
97
+ test_stats = None
98
+ patience = cfg.training.patience
99
+ patience_counter = 0
100
+ all_test_stats = []
101
+ global_best_val_score = float("-inf")
102
+ use_few_shot = cfg.training.decoder.use_few_shot
103
+ grad_acc = cfg.training.grad_accumulation
104
+
105
+ es_tracker = early_stop_tracker_factory(cfg)
106
+ # Stable optim: warmup cosine scheduler (computed over total training steps)
107
+ scheduler = None
108
+ if stable_optim:
109
+ total_graphs = sum(len(ds) for ds in train_data)
110
+ steps_per_epoch = max(1, total_graphs // grad_acc)
111
+ total_steps = steps_per_epoch * num_epochs
112
+ warmup_steps = max(1, total_steps // 20)
113
+ from pidsmaker.pretrained.training_utils import WarmupCosineScheduler
114
+
115
+ scheduler = WarmupCosineScheduler(optimizer, warmup_steps, total_steps)
116
+
117
+ if use_few_shot:
118
+ num_epochs += 1 # in few-shot, the first epoch is without ssl training
119
+
120
+ # FLASH: a sequence of GNN snapshots, each trained on the nodes still misclassified
121
+ model.flash_ensemble = flash_snapshot_ensemble(cfg)
122
+
123
+ for epoch in range(0, num_epochs):
124
+ best_val_score, best_model, best_epoch = float("-inf"), None, None
125
+
126
+ if not cfg._from_weights and (not use_few_shot or (use_few_shot and epoch > 0)):
127
+ start = timer()
128
+ cpu_mem.start()
129
+
130
+ # Before each epoch, we reset the memory
131
+ model.reset_state()
132
+ model.to_fine_tuning(False)
133
+
134
+ # Sum of the losses of the batches since the last optimizer step (without autograd
135
+ # graph). Each batch is backpropagated right away and its gradients accumulate in
136
+ # `.grad` until the step: the gradients are those of the summed losses, while only
137
+ # the autograd graph of one batch is kept in memory (with `grad_accumulation` = N,
138
+ # backpropagating the sum kept the graphs of N batches, e.g. of all the graphs of
139
+ # the training set with OCR-APT).
140
+ loss_acc = torch.zeros(1, device=device)
141
+ # Accumulated on device to avoid a GPU->CPU sync at each batch
142
+ tot_loss = torch.zeros((), dtype=torch.float64, device=device)
143
+ model.train()
144
+ optimizer.zero_grad()
145
+ for dataset in train_data:
146
+ for i, g in enumerate(log_tqdm(dataset, "Training")):
147
+ node_loss_mask = getattr(g, NODE_LOSS_MASK_KEY, None)
148
+ if node_loss_mask is not None and not node_loss_mask.any():
149
+ continue # No node left to train on (FLASH: all learned by the snapshots)
150
+ g = to_device_without_attacks(g, cfg, device)
151
+
152
+ results = model(g)
153
+ loss = results["loss"]
154
+ # A batch without any trainable output (e.g. a graph of OCR-APT with no
155
+ # node to predict) gives a constant loss, which contributes no gradient
156
+ if loss.requires_grad:
157
+ loss.sum().backward()
158
+ loss_acc += loss.detach()
159
+ tot_loss += loss.detach().sum().double()
160
+
161
+ if (i + 1) % grad_acc == 0:
162
+ if stable_optim:
163
+ torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
164
+ optimizer.step()
165
+ if scheduler is not None:
166
+ scheduler.step()
167
+ optimizer.zero_grad()
168
+ loss_acc = torch.zeros(1, device=device)
169
+
170
+ del g, results, loss
171
+
172
+ # Last batch
173
+ if loss_acc > 0:
174
+ if stable_optim:
175
+ torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
176
+ optimizer.step()
177
+ if scheduler is not None:
178
+ scheduler.step()
179
+
180
+ if model.flash_ensemble is not None:
181
+ model.flash_ensemble.after_epoch(model, train_data, device)
182
+
183
+ tot_loss = tot_loss.item() / sum(len(dataset) for dataset in train_data)
184
+ epoch_times.append(timer() - start)
185
+
186
+ peak_train_cpu_mem = max(peak_train_cpu_mem, cpu_mem.peak_gb())
187
+
188
+ if use_cuda:
189
+ peak_inference_gpu_memory = torch.cuda.max_memory_allocated(device=device) / (
190
+ 1024**3
191
+ )
192
+ peak_train_gpu_mem = max(peak_train_gpu_mem, peak_inference_gpu_memory)
193
+ torch.cuda.reset_peak_memory_stats(device=device)
194
+
195
+ log(
196
+ f"[@epoch{epoch:02d}] Training finished - GPU memory: {peak_train_gpu_mem:.2f} GB | CPU memory: {peak_train_cpu_mem:.2f} GB | Mean Loss: {tot_loss:.4f}",
197
+ return_line=True,
198
+ )
199
+
200
+ # Few-shot learning fine tuning
201
+ if use_few_shot:
202
+ model.to_fine_tuning(True)
203
+ optimizer = optimizer_few_shot_factory(cfg, parameters=set(model.parameters()))
204
+
205
+ num_epochs_few_shot = cfg.training.decoder.few_shot.num_epochs_few_shot
206
+ patience_few_shot = cfg.training.decoder.few_shot.patience_few_shot
207
+
208
+ for tuning_epoch in range(0, num_epochs_few_shot):
209
+ model.reset_state()
210
+
211
+ loss_acc = torch.zeros(1, device=device)
212
+ tot_loss = 0
213
+ for dataset in train_data:
214
+ for i, g in enumerate(log_tqdm(dataset, "Fine-tuning")):
215
+ if 1 in g.y:
216
+ g = batch_to_device(g, device)
217
+
218
+ model.train()
219
+ optimizer.zero_grad()
220
+
221
+ results = model(g)
222
+ loss = results["loss"]
223
+ loss_acc += loss
224
+ tot_loss += loss.item()
225
+
226
+ if (i + 1) % grad_acc == 0:
227
+ loss_acc.backward()
228
+ optimizer.step()
229
+ loss_acc = torch.zeros(1, device=device)
230
+
231
+ # Last batch
232
+ if loss_acc > 0:
233
+ loss_acc.backward()
234
+ optimizer.step()
235
+
236
+ tot_loss /= sum(len(dataset) for dataset in train_data)
237
+
238
+ # Validation
239
+ val_stats = inference_loop.main(
240
+ cfg=cfg,
241
+ model=model,
242
+ val_data=val_data,
243
+ test_data=test_data,
244
+ epoch=epoch,
245
+ split="val",
246
+ logging=False,
247
+ )
248
+ val_loss = val_stats["val_loss"]
249
+ val_score = val_stats["val_score"]
250
+
251
+ if val_score > best_val_score:
252
+ best_val_score = val_score
253
+ best_model = copy.deepcopy({k: v.cpu() for k, v in model.state_dict().items()})
254
+ patience_counter = 0
255
+ else:
256
+ patience_counter += 1
257
+
258
+ if val_score > global_best_val_score:
259
+ global_best_val_score = val_score
260
+ best_epoch = epoch
261
+
262
+ log(
263
+ f"[@epoch{tuning_epoch:02d}] Fine-tuning - Train Loss: {tot_loss:.5f} | Val Loss: {val_loss:.4f}",
264
+ return_line=True,
265
+ )
266
+
267
+ if patience_counter >= patience_few_shot:
268
+ log(f"Early stopping: best few-shot loss is {best_val_score:.4f}")
269
+ break
270
+
271
+ model.load_state_dict(best_model)
272
+ model.to_device(device)
273
+
274
+ # Per-epoch checkpoints are only needed by the visualizer's epoch selector.
275
+ # Opt-in via `--save_for_viz`; otherwise skip — the pipeline evaluates from
276
+ # the in-memory best model and never reloads these from disk.
277
+ if cfg._save_for_viz:
278
+ gnn_models_dir = cfg.training._trained_models_dir
279
+ model_path = os.path.join(gnn_models_dir, f"model_epoch_{epoch}")
280
+ save_model(model, model_path)
281
+
282
+ # Test
283
+ if (epoch + 1) % 2 == 0 or epoch == 0:
284
+ test_stats = inference_loop.main(
285
+ cfg=cfg,
286
+ model=model,
287
+ val_data=val_data,
288
+ test_data=test_data,
289
+ train_data=train_data,
290
+ epoch=epoch,
291
+ split="all",
292
+ )
293
+ all_test_stats.append(test_stats)
294
+
295
+ wandb.log(
296
+ {
297
+ "epoch": epoch,
298
+ "train_epoch": epoch,
299
+ "train_loss": round(tot_loss, 4),
300
+ "val_score": round(test_stats["val_score"], 4),
301
+ "val_loss": round(test_stats["val_loss"], 4),
302
+ "test_loss": round(test_stats["test_loss"], 4),
303
+ }
304
+ )
305
+ if es_tracker is not None and es_tracker.after_eval_epoch(cfg, model, train_data, epoch):
306
+ break
307
+
308
+ # After training
309
+ if best_epoch_mode:
310
+ model.load_state_dict(best_model)
311
+ test_stats = inference_loop.main(
312
+ cfg=cfg,
313
+ model=model,
314
+ val_data=val_data,
315
+ test_data=test_data,
316
+ train_data=train_data,
317
+ epoch=best_epoch,
318
+ split="test",
319
+ )
320
+
321
+ wandb.log(
322
+ {
323
+ "best_epoch": best_epoch,
324
+ "train_epoch_time": round(np.mean(epoch_times), 2),
325
+ "val_score": round(best_val_score, 5),
326
+ "peak_train_cpu_memory": round(peak_train_cpu_mem, 3),
327
+ "peak_train_gpu_memory": round(peak_train_gpu_mem, 3),
328
+ "peak_inference_cpu_memory": round(
329
+ np.max([d["peak_inference_cpu_memory"] for d in all_test_stats]), 3
330
+ ),
331
+ "peak_inference_gpu_memory": round(
332
+ np.max([d["peak_inference_gpu_memory"] for d in all_test_stats]), 3
333
+ ),
334
+ "time_per_batch_inference": round(
335
+ np.mean([d["time_per_batch_inference"] for d in all_test_stats]), 3
336
+ ),
337
+ }
338
+ )
339
+
340
+ return best_val_score
341
+
342
+
343
+ def to_device_without_attacks(graph, cfg, device):
344
+ """Copies `graph` to `device`, without its attack edges if they are excluded from the
345
+ self-supervised training (see `remove_attacks_if_needed`).
346
+
347
+ The CPU graph is not mutated, and whether it has attacks to remove is checked on it, to
348
+ avoid a GPU sync at each batch.
349
+ """
350
+ has_attacks_to_remove = needs_attack_removal(graph, cfg)
351
+ graph = batch_to_device(graph, device)
352
+ if has_attacks_to_remove:
353
+ graph = remove_attacks_if_needed(graph, cfg)
354
+ return graph
355
+
356
+
357
+ def needs_attack_removal(graph, cfg):
358
+ """Whether `remove_attacks_if_needed` would remove edges from `graph`."""
359
+ return (not cfg.training.decoder.few_shot.include_attacks_in_ssl_training) and bool(
360
+ (graph.y == 1).any()
361
+ )
362
+
363
+
364
+ def remove_attacks_if_needed(graph, cfg):
365
+ """Remove attack edges from graph for self-supervised training if configured.
366
+
367
+ Args:
368
+ graph: Graph batch with labels in graph.y
369
+ cfg: Configuration with few_shot.include_attacks_in_ssl_training setting
370
+
371
+ Returns:
372
+ graph: Original graph or filtered graph without attacks (y=1)
373
+ """
374
+ if not cfg.training.decoder.few_shot.include_attacks_in_ssl_training:
375
+ if 1 in graph.y:
376
+ return graph.clone()[graph.y != 1]
377
+ return graph
@@ -0,0 +1,22 @@
1
+ from .argus_encoder import ArgusEncoder
2
+ from .custom_mlp import CustomMLPAsbtract, CustomModel
3
+ from .custom_mlp_encoder import CustomMLPAsbtract, CustomMLPEncoder
4
+ from .egraphsage_encoder import EGraphSAGE
5
+ from .gat import GAT
6
+ from .gcn import GCN
7
+ from .gin import GIN
8
+ from .glstm import GLSTM
9
+ from .graph_attention import GraphAttentionEmbedding
10
+ from .gru import GRU
11
+ from .hetero import *
12
+ from .lares_encoder import LaresEncoder
13
+ from .linear_encoder import LinearEncoder
14
+ from .magic_encoder import MagicGAT
15
+ from .rcaid_encoder import RCaidGAT
16
+ from .rgcn import RGCN, PerTypeRGCN
17
+ from .sage import SAGE
18
+ from .shadewatcher_encoder import ShadeWatcherEncoder
19
+ from .sum_aggregation import SumAggregation
20
+ from .temporal_wrappers import NodeIdEmbedding, SnapshotGRU
21
+ from .textrcnn import TextRCNN
22
+ from .tgn_encoder import TGNEncoder
@@ -0,0 +1,69 @@
1
+ """Encoder of Argus (Xu et al., IEEE S&P 2024): "Understanding and Bridging the Gap Between
2
+ Unsupervised Network Representation Learning and Security Analytics".
3
+
4
+ GCN layers with edge weights (`batch.edge_weight`, see the `merge_edges` transformation),
5
+ followed by an edge-conditioned convolution (NNConv) using the edge features
6
+ (`batch.edge_feats`, e.g. `edge_attrs`) when available. Argus runs a GRU over the successive
7
+ embeddings of nodes, which is added with the `snapshot_gru` encoder wrapper.
8
+ """
9
+
10
+ import torch
11
+ import torch.nn as nn
12
+ from torch_geometric.nn import GCNConv, NNConv
13
+ from torch_geometric.utils import scatter
14
+
15
+
16
+ def _edge_conditioned_conv(conv, x, edge_index, edge_attr):
17
+ """Output of the NNConv `conv` (mean aggregation, edge network ending with a linear layer
18
+ `conv.nn[-1]`), without building its (E, in, out) per-edge weight matrices.
19
+
20
+ The weights of an edge are W(e) = sum_k h_k(e) A_k + B, with h(e) the input of the last
21
+ linear layer of the edge network (its weight holds the A_k, its bias B). The message of
22
+ an edge (j, i) is then x_j W(e) = sum_k h_k(e) (x_j A_k) + x_j B, where the x A_k and x B
23
+ are computed once per node: (E, hidden, out) values instead of (E, in, out), which do not
24
+ fit in memory for graphs with millions of edges.
25
+ """
26
+ last = conv.nn[-1]
27
+ hidden, in_dim, out_dim = last.in_features, conv.in_channels_l, conv.out_channels
28
+ h = conv.nn[:-1](edge_attr) # (E, hidden)
29
+ # A[i, o, k] = weight[i * out + o, k]: (in, out * hidden), then (N, out, hidden) per node
30
+ a = last.weight.view(in_dim, out_dim, hidden).reshape(in_dim, out_dim * hidden)
31
+ xa = (x @ a).view(-1, out_dim, hidden)
32
+ xb = x @ last.bias.view(in_dim, out_dim) if last.bias is not None else None
33
+ src, dst = edge_index
34
+ msg = torch.einsum("eok,ek->eo", xa[src], h)
35
+ if xb is not None:
36
+ msg = msg + xb[src]
37
+ out = scatter(msg, dst, dim=0, dim_size=x.size(0), reduce="mean")
38
+ if conv.root_weight:
39
+ out = out + conv.lin(x)
40
+ if conv.bias is not None:
41
+ out = out + conv.bias
42
+ return out
43
+
44
+
45
+ class ArgusEncoder(nn.Module):
46
+ def __init__(self, in_dim, hid_dim, out_dim, edge_dim, num_layers, dropout):
47
+ super().__init__()
48
+ self.dropout = nn.Dropout(dropout)
49
+ dims = [in_dim] + [hid_dim] * (num_layers - 1)
50
+ self.gcns = nn.ModuleList([GCNConv(dims[i], dims[i + 1]) for i in range(num_layers - 1)])
51
+ if edge_dim:
52
+ # As Argus, the weights of the convolution are computed by a small MLP of the edge features
53
+ edge_nn = nn.Sequential(
54
+ nn.Linear(edge_dim, 8), nn.ReLU(), nn.Linear(8, dims[-1] * out_dim)
55
+ )
56
+ self.last = NNConv(dims[-1], out_dim, edge_nn, aggr="mean")
57
+ else:
58
+ self.last = GCNConv(dims[-1], out_dim)
59
+ self.use_edge_feats = bool(edge_dim)
60
+
61
+ def forward(self, x, edge_index, batch=None, edge_feats=None, **kwargs):
62
+ edge_weight = getattr(batch, "edge_weight", None) if batch is not None else None
63
+ for conv in self.gcns:
64
+ x = self.dropout(torch.relu(conv(x, edge_index, edge_weight=edge_weight)))
65
+ if self.use_edge_feats:
66
+ x = _edge_conditioned_conv(self.last, x, edge_index, edge_feats)
67
+ else:
68
+ x = self.last(x, edge_index, edge_weight=edge_weight)
69
+ return {"h": x}
@@ -0,0 +1,75 @@
1
+ import torch.nn as nn
2
+
3
+
4
+ class CustomMLPAsbtract(nn.Module):
5
+ def __init__(self, in_dim, out_dim, architecture, dropout):
6
+ super().__init__()
7
+ self.mlp = build_mlp_from_string(architecture, in_dim, out_dim, dropout)
8
+
9
+ @property
10
+ def in_dim(self):
11
+ return self.mlp.in_dim
12
+
13
+ @property
14
+ def out_dim(self):
15
+ return self.mlp.out_dim
16
+
17
+
18
+ class CustomModel(nn.Module):
19
+ def __init__(self, in_dim, out_dim, mlp):
20
+ super().__init__()
21
+ self.in_dim = in_dim
22
+ self.out_dim = out_dim
23
+ self.mlp = mlp
24
+
25
+ def forward(self, *args, **kwargs):
26
+ return self.mlp(*args, **kwargs)
27
+
28
+
29
+ def build_mlp_from_string(arch_str, in_dim, out_dim, dropout):
30
+ def parse_layer(layer_str, in_dim):
31
+ layers = []
32
+ parts = layer_str.lower().split(",")
33
+
34
+ for part in parts:
35
+ if part.startswith("linear"):
36
+ _, coeff_out = part.split("(")
37
+ coeff_out = float(coeff_out.strip(")"))
38
+ out_dim = int(in_dim * coeff_out)
39
+ layers.append(nn.Linear(in_dim, out_dim))
40
+ in_dim = out_dim # Update in_dim for the next layer
41
+
42
+ elif part.startswith("dropout"):
43
+ # `dropout(p)` sets the rate of this layer, `dropout` uses `training.encoder.dropout`
44
+ rate = float(part[len("dropout(") : -1]) if part.startswith("dropout(") else dropout
45
+ layers.append(nn.Dropout(rate))
46
+
47
+ elif part == "tanh":
48
+ layers.append(nn.Tanh())
49
+
50
+ elif part == "relu":
51
+ layers.append(nn.ReLU())
52
+
53
+ elif part == "leaky_relu":
54
+ layers.append(nn.LeakyReLU())
55
+
56
+ elif part == "none":
57
+ pass
58
+
59
+ else:
60
+ raise ValueError(f"Invalid layer {part}")
61
+
62
+ return layers, in_dim
63
+
64
+ original_in_dim = in_dim
65
+ arch_str = arch_str.strip().lower().replace(" ", "")
66
+ layer_groups = arch_str.split("|")
67
+
68
+ layers = []
69
+ for group in layer_groups:
70
+ group_layers, in_dim = parse_layer(group, in_dim)
71
+ layers.extend(group_layers)
72
+ layers.append(nn.Linear(in_dim, out_dim))
73
+
74
+ model = CustomModel(in_dim=original_in_dim, out_dim=out_dim, mlp=nn.Sequential(*layers))
75
+ return model
@@ -0,0 +1,10 @@
1
+ from pidsmaker.encoders.custom_mlp import CustomMLPAsbtract
2
+
3
+
4
+ class CustomMLPEncoder(CustomMLPAsbtract):
5
+ def __init__(self, in_dim, out_dim, architecture, dropout):
6
+ super().__init__(in_dim, out_dim, architecture, dropout)
7
+
8
+ def forward(self, x, **kwargs):
9
+ h = self.mlp(x)
10
+ return {"h": h}
@@ -0,0 +1,56 @@
1
+ """Encoder of E-GraphSAGE (Lo et al., NOMS 2022): "E-GraphSAGE: A Graph Neural Network based
2
+ Intrusion Detection System for IoT".
3
+
4
+ GraphSAGE layers whose messages are the concatenation of the neighbor embedding and the features
5
+ of the edge (`batch.edge_feats`, e.g. `edge_attrs`), averaged over the edges of each node:
6
+
7
+ h_v' = act(W_self h_v + W_neigh mean_{u ~ v} [h_u || e_uv])
8
+
9
+ With `undirected` (as E-GraphSAGE and Anomal-E, whose graphs are undirected multigraphs), each
10
+ edge is aggregated in both directions; otherwise, only over incoming edges.
11
+ """
12
+
13
+ import torch
14
+ import torch.nn as nn
15
+ from torch_geometric.nn import MessagePassing
16
+
17
+
18
+ class EGraphSAGELayer(MessagePassing):
19
+ def __init__(self, in_dim, out_dim, edge_dim):
20
+ super().__init__(aggr="mean")
21
+ self.lin_neigh = nn.Linear(in_dim + edge_dim, out_dim)
22
+ self.lin_self = nn.Linear(in_dim, out_dim)
23
+ self.edge_dim = edge_dim
24
+
25
+ def forward(self, x, edge_index, edge_feats):
26
+ return self.lin_self(x) + self.lin_neigh(self.propagate(edge_index, x=x, edge_feats=edge_feats))
27
+
28
+ def message(self, x_j, edge_feats):
29
+ if edge_feats is None:
30
+ return x_j
31
+ return torch.cat([x_j, edge_feats], dim=-1)
32
+
33
+
34
+ class EGraphSAGE(nn.Module):
35
+ def __init__(self, in_dim, hid_dim, out_dim, edge_dim, activation, dropout, num_layers, undirected=True):
36
+ super().__init__()
37
+ self.undirected = undirected
38
+ self.activation = activation
39
+ self.dropout = nn.Dropout(dropout)
40
+ edge_dim = edge_dim or 0
41
+ dims = [in_dim] + [hid_dim] * (num_layers - 1) + [out_dim]
42
+ self.layers = nn.ModuleList(
43
+ [EGraphSAGELayer(dims[i], dims[i + 1], edge_dim) for i in range(num_layers)]
44
+ )
45
+ self.use_edge_feats = edge_dim > 0
46
+
47
+ def forward(self, x, edge_index, edge_feats=None, **kwargs):
48
+ edge_feats = edge_feats if self.use_edge_feats else None
49
+ if self.undirected:
50
+ edge_index = torch.cat([edge_index, edge_index.flip(0)], dim=1)
51
+ edge_feats = torch.cat([edge_feats, edge_feats]) if edge_feats is not None else None
52
+ for i, layer in enumerate(self.layers):
53
+ x = layer(x, edge_index, edge_feats)
54
+ if i < len(self.layers) - 1:
55
+ x = self.dropout(self.activation(x))
56
+ return {"h": x}
@@ -0,0 +1,67 @@
1
+ """Graph Attention Network (GAT) encoder.
2
+
3
+ GAT uses attention mechanisms to weight neighbor contributions dynamically during
4
+ aggregation. Multi-head attention provides different representation subspaces.
5
+ """
6
+
7
+ import torch.nn as nn
8
+ from torch_geometric.nn import GATConv
9
+
10
+
11
+ class GAT(nn.Module):
12
+ """GAT encoder with multi-head attention layers.
13
+
14
+ Applies attention-based aggregation where each node attends to its neighbors
15
+ with learned attention weights. Supports multi-head attention for richer representations.
16
+ """
17
+
18
+ def __init__(
19
+ self, in_dim, hid_dim, out_dim, activation, dropout, num_heads, concat, num_layers
20
+ ):
21
+ super().__init__()
22
+ self.activation = activation
23
+ self.dropout = nn.Dropout(dropout)
24
+
25
+ self.convs = nn.ModuleList()
26
+
27
+ current_dim = in_dim
28
+ for _ in range(num_layers - 1):
29
+ out_channels = hid_dim
30
+ conv = GATConv(
31
+ current_dim,
32
+ out_channels,
33
+ heads=num_heads,
34
+ dropout=dropout,
35
+ concat=concat,
36
+ )
37
+ self.convs.append(conv)
38
+ current_dim = hid_dim * num_heads if concat else hid_dim
39
+
40
+ self.convs.append(
41
+ GATConv(
42
+ current_dim,
43
+ out_dim,
44
+ heads=1,
45
+ concat=False,
46
+ dropout=dropout,
47
+ )
48
+ )
49
+
50
+ def forward(self, x, edge_index, **kwargs):
51
+ """Forward pass through GAT layers.
52
+
53
+ Args:
54
+ x: Node features (N, in_dim)
55
+ edge_index: Edge indices (2, E)
56
+ **kwargs: Additional arguments (unused)
57
+
58
+ Returns:
59
+ dict: {'h': node embeddings (N, out_dim)}
60
+ """
61
+ for conv in self.convs[:-1]:
62
+ x = conv(x, edge_index)
63
+ x = self.activation(x)
64
+ x = self.dropout(x)
65
+
66
+ x = self.convs[-1](x, edge_index)
67
+ return {"h": x}