pidsmaker 5.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pidsmaker/__init__.py +1 -0
- pidsmaker/cli.py +81 -0
- pidsmaker/config/__init__.py +2 -0
- pidsmaker/config/config.py +2100 -0
- pidsmaker/config/pipeline.py +1824 -0
- pidsmaker/config/schemas.py +1032 -0
- pidsmaker/datasets.py +323 -0
- pidsmaker/debug_tests.py +30 -0
- pidsmaker/decoders/__init__.py +5 -0
- pidsmaker/decoders/custom_edge_mlp_decoder.py +17 -0
- pidsmaker/decoders/custom_mlp_decoder.py +10 -0
- pidsmaker/decoders/edge_linear_decoder.py +16 -0
- pidsmaker/decoders/inner_product_decoder.py +18 -0
- pidsmaker/decoders/nodlink_decoder.py +56 -0
- pidsmaker/detection/__init__.py +0 -0
- pidsmaker/detection/evaluation_methods/__init__.py +9 -0
- pidsmaker/detection/evaluation_methods/edge_evaluation.py +255 -0
- pidsmaker/detection/evaluation_methods/evaluation_utils.py +1788 -0
- pidsmaker/detection/evaluation_methods/host_two_stage_evaluation.py +115 -0
- pidsmaker/detection/evaluation_methods/node_evaluation.py +459 -0
- pidsmaker/detection/evaluation_methods/node_tw_evaluation.py +196 -0
- pidsmaker/detection/evaluation_methods/plot.py +192 -0
- pidsmaker/detection/evaluation_methods/queue_evaluation.py +456 -0
- pidsmaker/detection/evaluation_methods/tw_evaluation.py +93 -0
- pidsmaker/detection/flash_detection.py +162 -0
- pidsmaker/detection/magic_knn.py +190 -0
- pidsmaker/detection/node_scoring.py +52 -0
- pidsmaker/detection/threatrace_detection.py +65 -0
- pidsmaker/detection/training_methods/__init__.py +1 -0
- pidsmaker/detection/training_methods/inference_loop.py +287 -0
- pidsmaker/detection/training_methods/ocrapt_early_stop.py +165 -0
- pidsmaker/detection/training_methods/threatrace_training.py +168 -0
- pidsmaker/detection/training_methods/training_loop.py +383 -0
- pidsmaker/encoders/__init__.py +22 -0
- pidsmaker/encoders/argus_encoder.py +69 -0
- pidsmaker/encoders/custom_mlp.py +75 -0
- pidsmaker/encoders/custom_mlp_encoder.py +10 -0
- pidsmaker/encoders/egraphsage_encoder.py +56 -0
- pidsmaker/encoders/gat.py +67 -0
- pidsmaker/encoders/gcn.py +27 -0
- pidsmaker/encoders/gin.py +48 -0
- pidsmaker/encoders/glstm.py +298 -0
- pidsmaker/encoders/graph_attention.py +63 -0
- pidsmaker/encoders/gru.py +29 -0
- pidsmaker/encoders/hetero/__init__.py +4 -0
- pidsmaker/encoders/hetero/ancestor_encoder.py +98 -0
- pidsmaker/encoders/hetero/entity_encoder.py +33 -0
- pidsmaker/encoders/hetero/event_encoder.py +81 -0
- pidsmaker/encoders/hetero/hetero_graph_transformer.py +40 -0
- pidsmaker/encoders/lares_encoder.py +68 -0
- pidsmaker/encoders/linear_encoder.py +16 -0
- pidsmaker/encoders/magic_encoder.py +161 -0
- pidsmaker/encoders/rcaid_encoder.py +81 -0
- pidsmaker/encoders/rgcn.py +75 -0
- pidsmaker/encoders/sage.py +51 -0
- pidsmaker/encoders/shadewatcher_encoder.py +149 -0
- pidsmaker/encoders/sum_aggregation.py +20 -0
- pidsmaker/encoders/temporal_wrappers.py +80 -0
- pidsmaker/encoders/textrcnn.py +82 -0
- pidsmaker/encoders/tgn_encoder.py +193 -0
- pidsmaker/experiments/tuning.py +102 -0
- pidsmaker/experiments/uncertainty.py +261 -0
- pidsmaker/factory.py +1456 -0
- pidsmaker/featurization/__init__.py +0 -0
- pidsmaker/featurization/feat_inference_methods/__init__.py +7 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_HFH.py +30 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_TRW.py +65 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_alacarte.py +14 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_doc2vec.py +53 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_fasttext.py +37 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_flash.py +69 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_graph2vec.py +84 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_ocrapt_features.py +95 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_pretrained.py +1728 -0
- pidsmaker/featurization/feat_inference_methods/feat_inference_word2vec.py +55 -0
- pidsmaker/featurization/featurization_methods/__init__.py +0 -0
- pidsmaker/featurization/featurization_methods/build_trw.py +66 -0
- pidsmaker/featurization/featurization_methods/featurization_alacarte.py +747 -0
- pidsmaker/featurization/featurization_methods/featurization_doc2vec.py +98 -0
- pidsmaker/featurization/featurization_methods/featurization_fasttext.py +74 -0
- pidsmaker/featurization/featurization_methods/featurization_flash.py +201 -0
- pidsmaker/featurization/featurization_methods/featurization_graph2vec.py +242 -0
- pidsmaker/featurization/featurization_methods/featurization_trw.py +114 -0
- pidsmaker/featurization/featurization_methods/featurization_word2vec.py +89 -0
- pidsmaker/featurization/featurization_utils.py +275 -0
- pidsmaker/featurization/utils/build_random_walks.py +66 -0
- pidsmaker/featurization/utils/trw.py +203 -0
- pidsmaker/hetero.py +81 -0
- pidsmaker/losses.py +170 -0
- pidsmaker/main.py +478 -0
- pidsmaker/mimicry.py +284 -0
- pidsmaker/model.py +382 -0
- pidsmaker/objectives/__init__.py +16 -0
- pidsmaker/objectives/autoencode_edge_emb.py +43 -0
- pidsmaker/objectives/deep_graph_infomax.py +94 -0
- pidsmaker/objectives/detect_few_shot.py +21 -0
- pidsmaker/objectives/one_class.py +75 -0
- pidsmaker/objectives/predict_edge_contrastive.py +165 -0
- pidsmaker/objectives/predict_edge_supervised.py +77 -0
- pidsmaker/objectives/predict_edge_type.py +28 -0
- pidsmaker/objectives/predict_masked_struct.py +49 -0
- pidsmaker/objectives/predict_node_type.py +36 -0
- pidsmaker/objectives/predict_process_tag.py +169 -0
- pidsmaker/objectives/predict_snapshot_embedding.py +97 -0
- pidsmaker/objectives/reconstruct_edge_emb.py +16 -0
- pidsmaker/objectives/reconstruct_masked_feat.py +51 -0
- pidsmaker/objectives/reconstruct_node_emb.py +13 -0
- pidsmaker/objectives/reconstruct_node_feat.py +13 -0
- pidsmaker/objectives/validation_wrapper.py +55 -0
- pidsmaker/preprocessing/__init__.py +0 -0
- pidsmaker/preprocessing/build_graph_methods/__init__.py +1 -0
- pidsmaker/preprocessing/build_graph_methods/build_default_graphs.py +825 -0
- pidsmaker/preprocessing/build_graph_methods/build_magic_graphs.py +216 -0
- pidsmaker/preprocessing/cleaning.py +258 -0
- pidsmaker/preprocessing/transformation_methods/__init__.py +2 -0
- pidsmaker/preprocessing/transformation_methods/attack_generation/synthetic_attack_naive.py +194 -0
- pidsmaker/preprocessing/transformation_methods/transformation_dag.py +28 -0
- pidsmaker/preprocessing/transformation_methods/transformation_merge_edges.py +136 -0
- pidsmaker/preprocessing/transformation_methods/transformation_rcaid_pseudo_graph.py +510 -0
- pidsmaker/preprocessing/transformation_methods/transformation_undirected.py +24 -0
- pidsmaker/preprocessing/transformation_methods/transformation_utils.py +36 -0
- pidsmaker/pretrained/__init__.py +5 -0
- pidsmaker/pretrained/data/__init__.py +4 -0
- pidsmaker/pretrained/data/behavior_signatures.py +548 -0
- pidsmaker/pretrained/data/canonical_tokens.py +1035 -0
- pidsmaker/pretrained/data/edge_filter.py +381 -0
- pidsmaker/pretrained/data/entity_classes.py +476 -0
- pidsmaker/pretrained/data/sampler.py +926 -0
- pidsmaker/pretrained/data/tokenizer_bpe.py +1659 -0
- pidsmaker/pretrained/detect.py +1427 -0
- pidsmaker/pretrained/embedding_generator.py +252 -0
- pidsmaker/pretrained/finetune.py +1434 -0
- pidsmaker/pretrained/models/__init__.py +20 -0
- pidsmaker/pretrained/models/behavior.py +348 -0
- pidsmaker/pretrained/models/bert.py +286 -0
- pidsmaker/pretrained/models/deepwalk.py +128 -0
- pidsmaker/pretrained/models/dgi.py +120 -0
- pidsmaker/pretrained/models/gae.py +114 -0
- pidsmaker/pretrained/models/gnn_distill.py +475 -0
- pidsmaker/pretrained/models/graphmae.py +373 -0
- pidsmaker/pretrained/models/hf_pretrained.py +213 -0
- pidsmaker/pretrained/models/llama.py +110 -0
- pidsmaker/pretrained/models/modernbert.py +567 -0
- pidsmaker/pretrained/models/roberta.py +147 -0
- pidsmaker/pretrained/models/rope_utils.py +99 -0
- pidsmaker/pretrained/models/ropebert.py +322 -0
- pidsmaker/pretrained/models/spider.py +204 -0
- pidsmaker/pretrained/models/tgn.py +770 -0
- pidsmaker/pretrained/pretrain/__init__.py +3 -0
- pidsmaker/pretrained/pretrain/pretrain_behavior_cluster.py +513 -0
- pidsmaker/pretrained/pretrain/pretrain_common.py +585 -0
- pidsmaker/pretrained/pretrain/pretrain_deepwalk.py +31 -0
- pidsmaker/pretrained/pretrain/pretrain_dgi.py +143 -0
- pidsmaker/pretrained/pretrain/pretrain_gae.py +143 -0
- pidsmaker/pretrained/pretrain/pretrain_gnn_distill.py +438 -0
- pidsmaker/pretrained/pretrain/pretrain_graphmae.py +151 -0
- pidsmaker/pretrained/pretrain/pretrain_hf.py +169 -0
- pidsmaker/pretrained/pretrain/pretrain_main.py +275 -0
- pidsmaker/pretrained/pretrain/pretrain_mlm.py +491 -0
- pidsmaker/pretrained/pretrain/pretrain_spider.py +502 -0
- pidsmaker/pretrained/training_utils.py +157 -0
- pidsmaker/process_reapr_gt.py +101 -0
- pidsmaker/resources/config/anomal_e.yml +25 -0
- pidsmaker/resources/config/argus.yml +56 -0
- pidsmaker/resources/config/attack_edges/cadets_e3.yml +435 -0
- pidsmaker/resources/config/attack_edges/cadets_e5.yml +407 -0
- pidsmaker/resources/config/attack_edges/theia_e3.yml +382 -0
- pidsmaker/resources/config/attack_edges/theia_e5.yml +387 -0
- pidsmaker/resources/config/attack_edges/trace_e3.yml +415 -0
- pidsmaker/resources/config/attack_edges/trace_e5.yml +417 -0
- pidsmaker/resources/config/default.yml +315 -0
- pidsmaker/resources/config/egraphsage.yml +95 -0
- pidsmaker/resources/config/euler.yml +104 -0
- pidsmaker/resources/config/eval/eval_set_clustering.json +3170 -0
- pidsmaker/resources/config/experiments/tuning/components/tuning_featurization_methods.yml +29 -0
- pidsmaker/resources/config/experiments/tuning/systems/clearscope_e5/tuning_orthrus.yml +14 -0
- pidsmaker/resources/config/experiments/tuning/systems/default/tuning_default_baselines.yml +13 -0
- pidsmaker/resources/config/experiments/tuning/systems/default/tuning_orthrus_fixed.yml +16 -0
- pidsmaker/resources/config/experiments/uncertainty/none.yml +5 -0
- pidsmaker/resources/config/experiments/uncertainty/run_n_times.yml +12 -0
- pidsmaker/resources/config/experiments/uncertainty/run_n_times_hyperparameters.yml +12 -0
- pidsmaker/resources/config/experiments/uncertainty/uncertainty.yml +22 -0
- pidsmaker/resources/config/flash.yml +79 -0
- pidsmaker/resources/config/jbeil.yml +65 -0
- pidsmaker/resources/config/kairos.yml +121 -0
- pidsmaker/resources/config/lares.yml +115 -0
- pidsmaker/resources/config/magic.yml +86 -0
- pidsmaker/resources/config/nodlink.yml +79 -0
- pidsmaker/resources/config/ocrapt.yml +91 -0
- pidsmaker/resources/config/orthrus.yml +126 -0
- pidsmaker/resources/config/orthrus_fixed.yml +17 -0
- pidsmaker/resources/config/pretrained/README.md +101 -0
- pidsmaker/resources/config/pretrained/cybergfm/cybergfm.yml +49 -0
- pidsmaker/resources/config/pretrained/pretrained.yml +190 -0
- pidsmaker/resources/config/pretrained/pretrained_flash.yml +9 -0
- pidsmaker/resources/config/pretrained/pretrained_kairos.yml +12 -0
- pidsmaker/resources/config/pretrained/pretrained_magic.yml +1 -0
- pidsmaker/resources/config/pretrained/pretrained_nodlink.yml +1 -0
- pidsmaker/resources/config/pretrained/pretrained_orthrus.yml +1 -0
- pidsmaker/resources/config/pretrained/pretrained_supervised.yml +13 -0
- pidsmaker/resources/config/pretrained/pretrained_threatrace.yml +8 -0
- pidsmaker/resources/config/pretrained/pretrained_velox.yml +14 -0
- pidsmaker/resources/config/prographer.yml +136 -0
- pidsmaker/resources/config/rcaid.yml +88 -0
- pidsmaker/resources/config/shadewatcher.yml +146 -0
- pidsmaker/resources/config/tests.yml +10 -0
- pidsmaker/resources/config/threatrace.yml +73 -0
- pidsmaker/resources/config/tuned_baselines/optc_net/tuned_argus.yml +4 -0
- pidsmaker/resources/config/tuned_baselines/optc_net/tuned_lares.yml +13 -0
- pidsmaker/resources/config/velox.yml +10 -0
- pidsmaker/resources/config/viz_config.yml +10 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_06.csv +8 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_11.csv +4 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_12.csv +43 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CADETS/node_Nginx_Backdoor_13.csv +24 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0411.csv +41 -0
- pidsmaker/resources/ground_truth/orthrus/E3-CLEARSCOPE/node_clearscope_e3_firefox_0412.csv +0 -0
- pidsmaker/resources/ground_truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_browser_0412.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +63 -0
- pidsmaker/resources/ground_truth/orthrus/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +56 -0
- pidsmaker/resources/ground_truth/orthrus/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +61 -0
- pidsmaker/resources/ground_truth/orthrus/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +58 -0
- pidsmaker/resources/ground_truth/orthrus/E3-TRACE/node_trace_e3_firefox_0410.csv +11 -0
- pidsmaker/resources/ground_truth/orthrus/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +11 -0
- pidsmaker/resources/ground_truth/orthrus/E3-TRACE/node_trace_e3_pine_0413.csv +14 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT.csv +19 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CADETS/node_Nginx_Drakon_APT_17.csv +107 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_appstarter_0515.csv +26 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_firefox_0517.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_lockwatch_0517.csv +17 -0
- pidsmaker/resources/ground_truth/orthrus/E5-CLEARSCOPE/node_clearscope_e5_tester_0517.csv +8 -0
- pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_bits_0515.csv +54 -0
- pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_copykatz_0509.csv +87 -0
- pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_dns_0517.csv +11 -0
- pidsmaker/resources/ground_truth/orthrus/E5-FIVEDIRECTIONS/node_fivedirections_e5_drakon_0517.csv +6 -0
- pidsmaker/resources/ground_truth/orthrus/E5-THEIA/node_THEIA_1_Firefox_Drakon_APT_BinFmt_Elevate_Inject.csv +70 -0
- pidsmaker/resources/ground_truth/orthrus/E5-TRACE/node_Trace_Firefox_Drakon.csv +71 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m1.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m2.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m3.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m4.csv +5 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m5.csv +23 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_m6.csv +18 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s1.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s2.csv +1 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s3.csv +16 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_edr/atlasv2_edr_s4.csv +22 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m1.csv +126 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m2.csv +105 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m3.csv +94 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m4.csv +139 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m5.csv +228 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_m6.csv +131 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s1.csv +118 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s2.csv +89 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s3.csv +133 -0
- pidsmaker/resources/ground_truth/orthrus/atlasv2_h1/node_h1_s4.csv +135 -0
- pidsmaker/resources/ground_truth/orthrus/carbanakv2_edr/carbanakv2_edr.csv +2453 -0
- pidsmaker/resources/ground_truth/orthrus/h051/node_h051_0925.csv +114 -0
- pidsmaker/resources/ground_truth/orthrus/h201/node_h201_0923.csv +2905 -0
- pidsmaker/resources/ground_truth/orthrus/h501/node_h501_0924.csv +749 -0
- pidsmaker/resources/ground_truth/orthrus/readme.md +98 -0
- pidsmaker/resources/ground_truth/reapr/E3-CADETS/node_Nginx_Backdoor_06.csv +3 -0
- pidsmaker/resources/ground_truth/reapr/E3-CADETS/node_Nginx_Backdoor_12.csv +655 -0
- pidsmaker/resources/ground_truth/reapr/E3-CADETS/node_Nginx_Backdoor_13.csv +770 -0
- pidsmaker/resources/ground_truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_excel_0409.csv +0 -0
- pidsmaker/resources/ground_truth/reapr/E3-FIVEDIRECTIONS/node_fivedirections_e3_firefox_0411.csv +18 -0
- pidsmaker/resources/ground_truth/reapr/E3-THEIA/node_Browser_Extension_Drakon_Dropper.csv +42 -0
- pidsmaker/resources/ground_truth/reapr/E3-THEIA/node_Firefox_Backdoor_Drakon_In_Memory.csv +81 -0
- pidsmaker/resources/ground_truth/reapr/E3-TRACE/node_trace_e3_firefox_0410.csv +37 -0
- pidsmaker/resources/ground_truth/reapr/E3-TRACE/node_trace_e3_phishing_executable_0413.csv +9 -0
- pidsmaker/resources/ground_truth/reapr/E3-TRACE/node_trace_e3_pine_0413.csv +40 -0
- pidsmaker/resources/ground_truth/threatrace/E3-CADETS/ground_truth.txt +12858 -0
- pidsmaker/resources/ground_truth/threatrace/E3-FIVEDIRECTIONS/ground_truth.txt +18420 -0
- pidsmaker/resources/ground_truth/threatrace/E3-THEIA/ground_truth.txt +25363 -0
- pidsmaker/resources/ground_truth/threatrace/E3-TRACE/ground_truth.txt +68265 -0
- pidsmaker/resources/ground_truth/threatrace/README.md +123 -0
- pidsmaker/tasks/__init__.py +10 -0
- pidsmaker/tasks/batching.py +47 -0
- pidsmaker/tasks/construction.py +31 -0
- pidsmaker/tasks/evaluation.py +241 -0
- pidsmaker/tasks/feat_inference.py +413 -0
- pidsmaker/tasks/featurization.py +43 -0
- pidsmaker/tasks/training.py +17 -0
- pidsmaker/tasks/transformation.py +306 -0
- pidsmaker/tasks/triage.py +143 -0
- pidsmaker/tgn.py +635 -0
- pidsmaker/tokenization/__init__.py +112 -0
- pidsmaker/tokenization/base.py +58 -0
- pidsmaker/tokenization/bpe_tokenizer.py +83 -0
- pidsmaker/tokenization/hf_tokenizer.py +61 -0
- pidsmaker/tokenization/hierarchical_tokenizer.py +44 -0
- pidsmaker/tokenization/label_tokenizer.py +24 -0
- pidsmaker/tokenization/nltk_tokenizer.py +84 -0
- pidsmaker/tokenization/substitution.py +295 -0
- pidsmaker/triage/__init__.py +0 -0
- pidsmaker/triage/tracing_methods/__init__.py +1 -0
- pidsmaker/triage/tracing_methods/depimpact.py +213 -0
- pidsmaker/triage/tracing_methods/depimpact_utils.py +537 -0
- pidsmaker/triage/tracing_methods/ocrapt_subgraph.py +267 -0
- pidsmaker/utils/__init__.py +0 -0
- pidsmaker/utils/cache_utils.py +256 -0
- pidsmaker/utils/console.py +282 -0
- pidsmaker/utils/data_utils.py +1742 -0
- pidsmaker/utils/database.py +150 -0
- pidsmaker/utils/dataset_utils.py +413 -0
- pidsmaker/utils/dataset_writer.py +570 -0
- pidsmaker/utils/graph_store.py +634 -0
- pidsmaker/utils/labelling.py +445 -0
- pidsmaker/utils/loss_files.py +193 -0
- pidsmaker/utils/process_tags.py +44 -0
- pidsmaker/utils/utils.py +712 -0
- pidsmaker/vizgen/__init__.py +1 -0
- pidsmaker/vizgen/backfill_manifests.py +100 -0
- pidsmaker/vizgen/dimensionality_reduction.py +249 -0
- pidsmaker/vizgen/embed_exporter.py +467 -0
- pidsmaker/vizgen/exporter.py +493 -0
- pidsmaker/vizgen/html_builder.py +936 -0
- pidsmaker/vizgen/web/__init__.py +1 -0
- pidsmaker/vizgen/web/export.py +62 -0
- pidsmaker/vizgen/web/static/css/app.css +250 -0
- pidsmaker/vizgen/web/static/index.html +182 -0
- pidsmaker/vizgen/web/static/js/app.js +627 -0
- pidsmaker/vizgen/web/static/js/campaign.js +123 -0
- pidsmaker/vizgen/web/static/js/data.js +119 -0
- pidsmaker/vizgen/web/static/js/dialogs.js +240 -0
- pidsmaker/vizgen/web/static/js/jobs.js +75 -0
- pidsmaker/vizgen/web/static/js/scene.js +651 -0
- pidsmaker/vizgen/web/static/js/ui.js +370 -0
- pidsmaker/vizgen/web/static/vendor/OrbitControls.js +1045 -0
- pidsmaker/vizgen/web/static/vendor/d3.v4.min.js +2 -0
- pidsmaker/vizgen/web/static/vendor/three.min.js +6 -0
- pidsmaker/vizgen/web/viz_server.py +2176 -0
- pidsmaker-5.0.0.dist-info/METADATA +597 -0
- pidsmaker-5.0.0.dist-info/RECORD +339 -0
- pidsmaker-5.0.0.dist-info/WHEEL +5 -0
- pidsmaker-5.0.0.dist-info/entry_points.txt +2 -0
- pidsmaker-5.0.0.dist-info/licenses/LICENSE +201 -0
- pidsmaker-5.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,567 @@
|
|
|
1
|
+
"""
|
|
2
|
+
ModernBERT implementation for provenance graph pretraining.
|
|
3
|
+
|
|
4
|
+
Incorporates modern transformer improvements:
|
|
5
|
+
- RoPE (Rotary Position Embeddings) instead of absolute positional embeddings
|
|
6
|
+
- RMSNorm instead of LayerNorm
|
|
7
|
+
- GeGLU activation in MLP layers
|
|
8
|
+
- Pre-normalization architecture
|
|
9
|
+
- Alternating global/local sliding window attention
|
|
10
|
+
- No bias terms in linear layers (except decoder)
|
|
11
|
+
- Flash Attention 2 support for efficiency
|
|
12
|
+
|
|
13
|
+
Based on: "Smarter, Better, Faster, Longer: A Modern Bidirectional Encoder for Fast,
|
|
14
|
+
Memory Efficient, and Long Context Finetuning and Inference" (ACL 2025)
|
|
15
|
+
GitHub: https://github.com/AnswerDotAI/ModernBERT
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import math
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from typing import Optional, Tuple, Union
|
|
21
|
+
|
|
22
|
+
import torch
|
|
23
|
+
import torch.nn as nn
|
|
24
|
+
import torch.nn.functional as F
|
|
25
|
+
from torch.nn import CrossEntropyLoss
|
|
26
|
+
|
|
27
|
+
from .bert import MODEL_SIZES, FineTuneCLS, FineTuneLP
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class ModernBERTConfig:
|
|
33
|
+
"""Configuration for ModernBERT model.
|
|
34
|
+
|
|
35
|
+
Args:
|
|
36
|
+
vocab_size: Size of vocabulary
|
|
37
|
+
hidden_size: Hidden dimension (H)
|
|
38
|
+
num_hidden_layers: Number of transformer layers (L)
|
|
39
|
+
num_attention_heads: Number of attention heads (A)
|
|
40
|
+
intermediate_size: MLP intermediate dimension (I)
|
|
41
|
+
max_position_embeddings: Maximum sequence length
|
|
42
|
+
hidden_dropout_prob: Dropout probability
|
|
43
|
+
attention_probs_dropout_prob: Attention dropout
|
|
44
|
+
global_attn_every_n_layers: Use global attention every N layers (others use local)
|
|
45
|
+
local_attention_window: Sliding window size for local attention
|
|
46
|
+
global_rope_theta: RoPE base frequency for global attention layers
|
|
47
|
+
local_rope_theta: RoPE base frequency for local attention layers
|
|
48
|
+
rope_scaling: Optional RoPE scaling factor
|
|
49
|
+
use_flash_attention: Whether to use Flash Attention (if available)
|
|
50
|
+
"""
|
|
51
|
+
vocab_size: int = 30522
|
|
52
|
+
hidden_size: int = 768
|
|
53
|
+
num_hidden_layers: int = 12
|
|
54
|
+
num_attention_heads: int = 12
|
|
55
|
+
intermediate_size: int = 3072
|
|
56
|
+
max_position_embeddings: int = 512
|
|
57
|
+
hidden_dropout_prob: float = 0.1
|
|
58
|
+
attention_probs_dropout_prob: float = 0.1
|
|
59
|
+
global_attn_every_n_layers: int = 3
|
|
60
|
+
local_attention_window: int = 128
|
|
61
|
+
global_rope_theta: float = 160000.0
|
|
62
|
+
local_rope_theta: float = 10000.0
|
|
63
|
+
rope_scaling: Optional[float] = None
|
|
64
|
+
use_flash_attention: bool = True
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def head_dim(self):
|
|
68
|
+
return self.hidden_size // self.num_attention_heads
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
from .rope_utils import RMSNorm, RotaryEmbedding, GeGLU
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
# ============================================================================
|
|
75
|
+
# Multi-Head Attention with RoPE
|
|
76
|
+
# ============================================================================
|
|
77
|
+
|
|
78
|
+
class ModernBERTAttention(nn.Module):
|
|
79
|
+
"""Multi-head attention with RoPE and optional sliding window.
|
|
80
|
+
|
|
81
|
+
Args:
|
|
82
|
+
config: Model configuration
|
|
83
|
+
layer_id: Layer index (determines if global or local attention)
|
|
84
|
+
"""
|
|
85
|
+
|
|
86
|
+
def __init__(self, config: ModernBERTConfig, layer_id: int = 0):
|
|
87
|
+
super().__init__()
|
|
88
|
+
self.config = config
|
|
89
|
+
self.layer_id = layer_id
|
|
90
|
+
self.hidden_size = config.hidden_size
|
|
91
|
+
self.num_heads = config.num_attention_heads
|
|
92
|
+
self.head_dim = config.head_dim
|
|
93
|
+
self.dropout = config.attention_probs_dropout_prob
|
|
94
|
+
|
|
95
|
+
# Determine if this is a global or local attention layer
|
|
96
|
+
self.is_global = (layer_id % config.global_attn_every_n_layers == 0)
|
|
97
|
+
self.attention_window = None if self.is_global else config.local_attention_window
|
|
98
|
+
|
|
99
|
+
# QKV projection (no bias)
|
|
100
|
+
self.qkv = nn.Linear(self.hidden_size, 3 * self.hidden_size, bias=False)
|
|
101
|
+
|
|
102
|
+
# Output projection (no bias)
|
|
103
|
+
self.out_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
|
|
104
|
+
self.out_dropout = nn.Dropout(config.hidden_dropout_prob)
|
|
105
|
+
|
|
106
|
+
# RoPE embeddings (different base for global vs local)
|
|
107
|
+
rope_base = config.global_rope_theta if self.is_global else config.local_rope_theta
|
|
108
|
+
self.rotary_emb = RotaryEmbedding(
|
|
109
|
+
self.head_dim,
|
|
110
|
+
max_seq_len=config.max_position_embeddings,
|
|
111
|
+
base=rope_base
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
# Try to import flash attention
|
|
115
|
+
self.use_flash = config.use_flash_attention
|
|
116
|
+
if self.use_flash:
|
|
117
|
+
try:
|
|
118
|
+
from flash_attn import flash_attn_func
|
|
119
|
+
self.flash_attn_func = flash_attn_func
|
|
120
|
+
except ImportError:
|
|
121
|
+
self.use_flash = False
|
|
122
|
+
|
|
123
|
+
def forward(
|
|
124
|
+
self,
|
|
125
|
+
hidden_states: torch.Tensor,
|
|
126
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
127
|
+
) -> torch.Tensor:
|
|
128
|
+
"""Forward pass with optional sliding window attention.
|
|
129
|
+
|
|
130
|
+
Args:
|
|
131
|
+
hidden_states: [batch, seq_len, hidden_size]
|
|
132
|
+
attention_mask: [batch, seq_len] or [batch, 1, seq_len, seq_len]
|
|
133
|
+
|
|
134
|
+
Returns:
|
|
135
|
+
Output tensor [batch, seq_len, hidden_size]
|
|
136
|
+
"""
|
|
137
|
+
batch_size, seq_len, _ = hidden_states.shape
|
|
138
|
+
|
|
139
|
+
# Project to Q, K, V
|
|
140
|
+
qkv = self.qkv(hidden_states) # [batch, seq_len, 3 * hidden_size]
|
|
141
|
+
qkv = qkv.reshape(batch_size, seq_len, 3, self.num_heads, self.head_dim)
|
|
142
|
+
qkv = qkv.permute(2, 0, 3, 1, 4) # [3, batch, num_heads, seq_len, head_dim]
|
|
143
|
+
q, k, v = qkv[0], qkv[1], qkv[2]
|
|
144
|
+
|
|
145
|
+
# Apply RoPE to Q and K
|
|
146
|
+
q, k = self.rotary_emb(q, k, seq_len)
|
|
147
|
+
|
|
148
|
+
# Compute attention
|
|
149
|
+
if self.use_flash and self.training:
|
|
150
|
+
# Use Flash Attention if available (more efficient)
|
|
151
|
+
# Note: Flash Attention expects [batch, seq_len, num_heads, head_dim]
|
|
152
|
+
q = q.transpose(1, 2) # [batch, seq_len, num_heads, head_dim]
|
|
153
|
+
k = k.transpose(1, 2)
|
|
154
|
+
v = v.transpose(1, 2)
|
|
155
|
+
|
|
156
|
+
# Apply sliding window for local attention
|
|
157
|
+
window_size = (-1, -1) if self.is_global else (self.attention_window // 2, self.attention_window // 2)
|
|
158
|
+
|
|
159
|
+
attn_output = self.flash_attn_func(
|
|
160
|
+
q, k, v,
|
|
161
|
+
dropout_p=self.dropout if self.training else 0.0,
|
|
162
|
+
window_size=window_size,
|
|
163
|
+
causal=False, # BERT is bidirectional
|
|
164
|
+
)
|
|
165
|
+
attn_output = attn_output.reshape(batch_size, seq_len, self.hidden_size)
|
|
166
|
+
else:
|
|
167
|
+
# Standard scaled dot-product attention
|
|
168
|
+
attn_output = self._standard_attention(q, k, v, attention_mask)
|
|
169
|
+
|
|
170
|
+
# Output projection
|
|
171
|
+
attn_output = self.out_proj(attn_output)
|
|
172
|
+
attn_output = self.out_dropout(attn_output)
|
|
173
|
+
|
|
174
|
+
return attn_output
|
|
175
|
+
|
|
176
|
+
def _standard_attention(
|
|
177
|
+
self,
|
|
178
|
+
q: torch.Tensor,
|
|
179
|
+
k: torch.Tensor,
|
|
180
|
+
v: torch.Tensor,
|
|
181
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
182
|
+
) -> torch.Tensor:
|
|
183
|
+
"""Standard scaled dot-product attention with optional sliding window.
|
|
184
|
+
|
|
185
|
+
Args:
|
|
186
|
+
q: [batch, num_heads, seq_len, head_dim]
|
|
187
|
+
k: [batch, num_heads, seq_len, head_dim]
|
|
188
|
+
v: [batch, num_heads, seq_len, head_dim]
|
|
189
|
+
attention_mask: Optional mask
|
|
190
|
+
|
|
191
|
+
Returns:
|
|
192
|
+
Attention output [batch, seq_len, hidden_size]
|
|
193
|
+
"""
|
|
194
|
+
batch_size, num_heads, seq_len, head_dim = q.shape
|
|
195
|
+
|
|
196
|
+
# Scaled dot-product: Q @ K^T / sqrt(d_k)
|
|
197
|
+
scale = 1.0 / math.sqrt(head_dim)
|
|
198
|
+
attn_scores = torch.matmul(q, k.transpose(-2, -1)) * scale # [batch, num_heads, seq_len, seq_len]
|
|
199
|
+
|
|
200
|
+
# Apply sliding window mask for local attention
|
|
201
|
+
if not self.is_global and self.attention_window is not None:
|
|
202
|
+
# Create sliding window mask
|
|
203
|
+
window_mask = self._create_sliding_window_mask(seq_len, self.attention_window, q.device)
|
|
204
|
+
attn_scores = attn_scores.masked_fill(~window_mask, -1e9)
|
|
205
|
+
|
|
206
|
+
# Apply attention mask if provided
|
|
207
|
+
if attention_mask is not None:
|
|
208
|
+
if attention_mask.dim() == 2:
|
|
209
|
+
# [batch, seq_len] -> [batch, 1, 1, seq_len]
|
|
210
|
+
attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
|
|
211
|
+
# Use large negative value instead of -inf to prevent NaN
|
|
212
|
+
attn_scores = attn_scores.masked_fill(~attention_mask.bool(), -1e9)
|
|
213
|
+
|
|
214
|
+
# Softmax and apply to values (use float32 for stability)
|
|
215
|
+
attn_probs = F.softmax(attn_scores.float(), dim=-1).type_as(attn_scores)
|
|
216
|
+
# Replace any NaN with 0 (can happen if entire row is masked)
|
|
217
|
+
attn_probs = torch.nan_to_num(attn_probs, nan=0.0)
|
|
218
|
+
attn_probs = F.dropout(attn_probs, p=self.dropout, training=self.training)
|
|
219
|
+
|
|
220
|
+
attn_output = torch.matmul(attn_probs, v) # [batch, num_heads, seq_len, head_dim]
|
|
221
|
+
|
|
222
|
+
# Reshape back to [batch, seq_len, hidden_size]
|
|
223
|
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
|
224
|
+
attn_output = attn_output.reshape(batch_size, seq_len, self.hidden_size)
|
|
225
|
+
|
|
226
|
+
return attn_output
|
|
227
|
+
|
|
228
|
+
@staticmethod
|
|
229
|
+
def _create_sliding_window_mask(seq_len: int, window_size: int, device: torch.device) -> torch.Tensor:
|
|
230
|
+
"""Create a sliding window attention mask.
|
|
231
|
+
|
|
232
|
+
Args:
|
|
233
|
+
seq_len: Sequence length
|
|
234
|
+
window_size: Window size (tokens can attend to window_size // 2 on each side)
|
|
235
|
+
device: Device to create mask on
|
|
236
|
+
|
|
237
|
+
Returns:
|
|
238
|
+
Boolean mask [1, 1, seq_len, seq_len] where True means attend
|
|
239
|
+
"""
|
|
240
|
+
# Create position indices
|
|
241
|
+
positions = torch.arange(seq_len, device=device)
|
|
242
|
+
|
|
243
|
+
# Compute distance between all pairs of positions
|
|
244
|
+
distance = positions.unsqueeze(0) - positions.unsqueeze(1) # [seq_len, seq_len]
|
|
245
|
+
|
|
246
|
+
# Allow attention within window_size // 2 on each side
|
|
247
|
+
half_window = window_size // 2
|
|
248
|
+
mask = (distance.abs() <= half_window) # [seq_len, seq_len]
|
|
249
|
+
|
|
250
|
+
# Add batch and head dimensions
|
|
251
|
+
return mask.unsqueeze(0).unsqueeze(0) # [1, 1, seq_len, seq_len]
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
# ============================================================================
|
|
255
|
+
# Transformer Layer with Pre-Normalization
|
|
256
|
+
# ============================================================================
|
|
257
|
+
|
|
258
|
+
class ModernBERTLayer(nn.Module):
|
|
259
|
+
"""Transformer layer with pre-normalization architecture.
|
|
260
|
+
|
|
261
|
+
Pre-norm (used here):
|
|
262
|
+
x = x + Attention(Norm(x))
|
|
263
|
+
x = x + MLP(Norm(x))
|
|
264
|
+
|
|
265
|
+
This is more stable than post-norm and is standard in modern LLMs.
|
|
266
|
+
"""
|
|
267
|
+
|
|
268
|
+
def __init__(self, config: ModernBERTConfig, layer_id: int = 0):
|
|
269
|
+
super().__init__()
|
|
270
|
+
self.config = config
|
|
271
|
+
self.layer_id = layer_id
|
|
272
|
+
|
|
273
|
+
# Pre-normalization
|
|
274
|
+
self.attn_norm = RMSNorm(config.hidden_size)
|
|
275
|
+
self.mlp_norm = RMSNorm(config.hidden_size)
|
|
276
|
+
|
|
277
|
+
# Attention and MLP
|
|
278
|
+
self.attention = ModernBERTAttention(config, layer_id=layer_id)
|
|
279
|
+
self.mlp = GeGLU(config.hidden_size, config.intermediate_size, config.hidden_dropout_prob)
|
|
280
|
+
|
|
281
|
+
def forward(
|
|
282
|
+
self,
|
|
283
|
+
hidden_states: torch.Tensor,
|
|
284
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
285
|
+
) -> torch.Tensor:
|
|
286
|
+
"""Forward pass with pre-normalization.
|
|
287
|
+
|
|
288
|
+
Args:
|
|
289
|
+
hidden_states: [batch, seq_len, hidden_size]
|
|
290
|
+
attention_mask: Optional attention mask
|
|
291
|
+
|
|
292
|
+
Returns:
|
|
293
|
+
Output tensor [batch, seq_len, hidden_size]
|
|
294
|
+
"""
|
|
295
|
+
# Pre-norm attention with residual
|
|
296
|
+
normed = self.attn_norm(hidden_states)
|
|
297
|
+
attn_output = self.attention(normed, attention_mask)
|
|
298
|
+
hidden_states = hidden_states + attn_output
|
|
299
|
+
|
|
300
|
+
# Pre-norm MLP with residual
|
|
301
|
+
normed = self.mlp_norm(hidden_states)
|
|
302
|
+
mlp_output = self.mlp(normed)
|
|
303
|
+
hidden_states = hidden_states + mlp_output
|
|
304
|
+
|
|
305
|
+
return hidden_states
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
# ============================================================================
|
|
309
|
+
# ModernBERT Embeddings (no positional embeddings - using RoPE instead)
|
|
310
|
+
# ============================================================================
|
|
311
|
+
|
|
312
|
+
class ModernBERTEmbeddings(nn.Module):
|
|
313
|
+
"""Token embeddings without positional embeddings.
|
|
314
|
+
|
|
315
|
+
ModernBERT uses RoPE in the attention layers instead of adding
|
|
316
|
+
positional embeddings at the input.
|
|
317
|
+
"""
|
|
318
|
+
|
|
319
|
+
def __init__(self, config: ModernBERTConfig):
|
|
320
|
+
super().__init__()
|
|
321
|
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
|
|
322
|
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
|
323
|
+
|
|
324
|
+
# Layer norm after embeddings (as mentioned in ModernBERT paper)
|
|
325
|
+
self.norm = RMSNorm(config.hidden_size)
|
|
326
|
+
|
|
327
|
+
def forward(self, input_ids: torch.Tensor) -> torch.Tensor:
|
|
328
|
+
"""Embed input tokens.
|
|
329
|
+
|
|
330
|
+
Args:
|
|
331
|
+
input_ids: [batch, seq_len] token indices
|
|
332
|
+
|
|
333
|
+
Returns:
|
|
334
|
+
Embeddings [batch, seq_len, hidden_size]
|
|
335
|
+
"""
|
|
336
|
+
embeddings = self.word_embeddings(input_ids)
|
|
337
|
+
embeddings = self.norm(embeddings)
|
|
338
|
+
embeddings = self.dropout(embeddings)
|
|
339
|
+
return embeddings
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
# ============================================================================
|
|
343
|
+
# ModernBERT Encoder
|
|
344
|
+
# ============================================================================
|
|
345
|
+
|
|
346
|
+
class ModernBERTEncoder(nn.Module):
|
|
347
|
+
"""Stack of ModernBERT transformer layers."""
|
|
348
|
+
|
|
349
|
+
def __init__(self, config: ModernBERTConfig):
|
|
350
|
+
super().__init__()
|
|
351
|
+
self.config = config
|
|
352
|
+
self.layers = nn.ModuleList([
|
|
353
|
+
ModernBERTLayer(config, layer_id=i)
|
|
354
|
+
for i in range(config.num_hidden_layers)
|
|
355
|
+
])
|
|
356
|
+
|
|
357
|
+
def forward(
|
|
358
|
+
self,
|
|
359
|
+
hidden_states: torch.Tensor,
|
|
360
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
361
|
+
) -> torch.Tensor:
|
|
362
|
+
"""Forward pass through all layers.
|
|
363
|
+
|
|
364
|
+
Args:
|
|
365
|
+
hidden_states: [batch, seq_len, hidden_size]
|
|
366
|
+
attention_mask: Optional mask
|
|
367
|
+
|
|
368
|
+
Returns:
|
|
369
|
+
Final hidden states [batch, seq_len, hidden_size]
|
|
370
|
+
"""
|
|
371
|
+
for layer in self.layers:
|
|
372
|
+
hidden_states = layer(hidden_states, attention_mask)
|
|
373
|
+
|
|
374
|
+
return hidden_states
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
# ============================================================================
|
|
378
|
+
# ModernBERT Model for Masked Language Modeling
|
|
379
|
+
# ============================================================================
|
|
380
|
+
|
|
381
|
+
class ProvenanceModernBERT(nn.Module):
|
|
382
|
+
"""ModernBERT for masked language modeling on provenance graph walks.
|
|
383
|
+
|
|
384
|
+
Architecture:
|
|
385
|
+
1. Token embeddings (no positional embeddings)
|
|
386
|
+
2. Stack of transformer layers with:
|
|
387
|
+
- Pre-normalization (RMSNorm)
|
|
388
|
+
- RoPE in attention
|
|
389
|
+
- Alternating global/local attention
|
|
390
|
+
- GeGLU activation in MLP
|
|
391
|
+
3. Final layer norm
|
|
392
|
+
4. Prediction head for masked token prediction
|
|
393
|
+
"""
|
|
394
|
+
|
|
395
|
+
def __init__(self, config: ModernBERTConfig):
|
|
396
|
+
super().__init__()
|
|
397
|
+
self.config = config
|
|
398
|
+
|
|
399
|
+
# Embeddings
|
|
400
|
+
self.embeddings = ModernBERTEmbeddings(config)
|
|
401
|
+
|
|
402
|
+
# Transformer encoder
|
|
403
|
+
self.encoder = ModernBERTEncoder(config)
|
|
404
|
+
|
|
405
|
+
# Final layer norm (for pre-norm architecture)
|
|
406
|
+
self.final_norm = RMSNorm(config.hidden_size)
|
|
407
|
+
|
|
408
|
+
# Prediction head (with bias in final layer - only place with bias)
|
|
409
|
+
self.prediction_head = nn.Sequential(
|
|
410
|
+
nn.Linear(config.hidden_size, config.hidden_size, bias=False),
|
|
411
|
+
nn.GELU(),
|
|
412
|
+
RMSNorm(config.hidden_size),
|
|
413
|
+
)
|
|
414
|
+
self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
|
|
415
|
+
|
|
416
|
+
# Initialize weights FIRST
|
|
417
|
+
self.apply(self._init_weights)
|
|
418
|
+
|
|
419
|
+
# Tie weights between embeddings and decoder AFTER initialization
|
|
420
|
+
self.decoder.weight = self.embeddings.word_embeddings.weight
|
|
421
|
+
|
|
422
|
+
def _init_weights(self, module):
|
|
423
|
+
"""Initialize weights following ModernBERT guidelines."""
|
|
424
|
+
if isinstance(module, nn.Linear):
|
|
425
|
+
# Use Xavier/Glorot initialization for better gradient flow
|
|
426
|
+
# Scaled by 1/sqrt(2) for residual connections
|
|
427
|
+
std = (2.0 / (module.weight.shape[0] + module.weight.shape[1])) ** 0.5
|
|
428
|
+
torch.nn.init.normal_(module.weight, mean=0.0, std=std)
|
|
429
|
+
if module.bias is not None:
|
|
430
|
+
torch.nn.init.zeros_(module.bias)
|
|
431
|
+
elif isinstance(module, nn.Embedding):
|
|
432
|
+
# Smaller std for embeddings to prevent initial instability
|
|
433
|
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.01)
|
|
434
|
+
elif isinstance(module, RMSNorm):
|
|
435
|
+
torch.nn.init.ones_(module.weight)
|
|
436
|
+
|
|
437
|
+
def forward(
|
|
438
|
+
self,
|
|
439
|
+
input_ids: torch.Tensor,
|
|
440
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
441
|
+
labels: Optional[torch.Tensor] = None,
|
|
442
|
+
**kwargs,
|
|
443
|
+
) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
|
|
444
|
+
"""Forward pass.
|
|
445
|
+
|
|
446
|
+
Args:
|
|
447
|
+
input_ids: [batch, seq_len] token IDs (with [MASK] applied)
|
|
448
|
+
attention_mask: [batch, seq_len] mask (1 for real tokens, 0 for padding)
|
|
449
|
+
labels: [batch, seq_len] target token IDs (-100 for non-predicted positions)
|
|
450
|
+
|
|
451
|
+
Returns:
|
|
452
|
+
If labels provided: (loss, logits)
|
|
453
|
+
Otherwise: logits [batch, seq_len, vocab_size]
|
|
454
|
+
"""
|
|
455
|
+
# Embed tokens
|
|
456
|
+
hidden_states = self.embeddings(input_ids)
|
|
457
|
+
|
|
458
|
+
# Pass through encoder
|
|
459
|
+
hidden_states = self.encoder(hidden_states, attention_mask)
|
|
460
|
+
|
|
461
|
+
# Final normalization
|
|
462
|
+
hidden_states = self.final_norm(hidden_states)
|
|
463
|
+
|
|
464
|
+
# Prediction head
|
|
465
|
+
hidden_states = self.prediction_head(hidden_states)
|
|
466
|
+
logits = self.decoder(hidden_states)
|
|
467
|
+
|
|
468
|
+
# Compute loss if labels provided
|
|
469
|
+
if labels is not None:
|
|
470
|
+
loss_fct = CrossEntropyLoss() # -100 index = padding token
|
|
471
|
+
loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
|
|
472
|
+
return loss, logits
|
|
473
|
+
|
|
474
|
+
return logits
|
|
475
|
+
|
|
476
|
+
def modified_fwd(
|
|
477
|
+
self,
|
|
478
|
+
input_ids: torch.Tensor,
|
|
479
|
+
attention_mask: torch.Tensor,
|
|
480
|
+
labels: torch.Tensor,
|
|
481
|
+
return_loss: bool = True,
|
|
482
|
+
skip_cls: bool = False,
|
|
483
|
+
):
|
|
484
|
+
"""Convenience wrapper matching the original ProvenanceBERT interface.
|
|
485
|
+
|
|
486
|
+
Args:
|
|
487
|
+
input_ids: [B, L] token IDs (with [MASK] applied)
|
|
488
|
+
attention_mask: [B, L] bool, True for real tokens
|
|
489
|
+
labels: [B, L] target token IDs, -100 for non-predicted positions
|
|
490
|
+
return_loss: if True, return scalar loss; else return tuple
|
|
491
|
+
skip_cls: if True, return hidden states instead of prediction logits
|
|
492
|
+
|
|
493
|
+
Returns:
|
|
494
|
+
If skip_cls: hidden states [B, L, H]
|
|
495
|
+
If return_loss: scalar loss
|
|
496
|
+
Otherwise: tuple of (loss, logits)
|
|
497
|
+
"""
|
|
498
|
+
# Get embeddings and encode
|
|
499
|
+
hidden_states = self.embeddings(input_ids)
|
|
500
|
+
hidden_states = self.encoder(hidden_states, attention_mask)
|
|
501
|
+
encoder_hidden = self.final_norm(hidden_states)
|
|
502
|
+
|
|
503
|
+
if skip_cls:
|
|
504
|
+
return encoder_hidden
|
|
505
|
+
|
|
506
|
+
# Get predictions
|
|
507
|
+
pred_hidden = self.prediction_head(encoder_hidden)
|
|
508
|
+
logits = self.decoder(pred_hidden)
|
|
509
|
+
|
|
510
|
+
# Compute loss
|
|
511
|
+
loss_fct = CrossEntropyLoss()
|
|
512
|
+
loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
|
|
513
|
+
|
|
514
|
+
if return_loss:
|
|
515
|
+
return loss
|
|
516
|
+
|
|
517
|
+
# Return named tuple for compatibility
|
|
518
|
+
from collections import namedtuple
|
|
519
|
+
Output = namedtuple('Output', ['loss', 'logits'])
|
|
520
|
+
return Output(loss=loss, logits=logits)
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
# ============================================================================
|
|
524
|
+
# Model size presets (matching original BERT sizes)
|
|
525
|
+
# ============================================================================
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
def get_modernbert_config(
|
|
531
|
+
vocab_size: int,
|
|
532
|
+
model_size: str = "tiny",
|
|
533
|
+
max_position_embeddings: int = 512,
|
|
534
|
+
global_attn_every_n_layers: int = 3,
|
|
535
|
+
local_attention_window: int = 128,
|
|
536
|
+
) -> ModernBERTConfig:
|
|
537
|
+
"""Create ModernBERTConfig for a given model size.
|
|
538
|
+
|
|
539
|
+
Args:
|
|
540
|
+
vocab_size: Size of the tokenizer vocabulary
|
|
541
|
+
model_size: One of "tiny", "mini", "med", "baseline"
|
|
542
|
+
max_position_embeddings: Maximum sequence length
|
|
543
|
+
global_attn_every_n_layers: Use global attention every N layers
|
|
544
|
+
local_attention_window: Sliding window size for local attention
|
|
545
|
+
|
|
546
|
+
Returns:
|
|
547
|
+
ModernBERTConfig instance
|
|
548
|
+
"""
|
|
549
|
+
params = MODEL_SIZES[model_size]
|
|
550
|
+
|
|
551
|
+
return ModernBERTConfig(
|
|
552
|
+
vocab_size=vocab_size,
|
|
553
|
+
hidden_size=params.H,
|
|
554
|
+
num_hidden_layers=params.L,
|
|
555
|
+
num_attention_heads=params.A,
|
|
556
|
+
intermediate_size=params.I,
|
|
557
|
+
max_position_embeddings=max_position_embeddings,
|
|
558
|
+
global_attn_every_n_layers=global_attn_every_n_layers,
|
|
559
|
+
local_attention_window=local_attention_window,
|
|
560
|
+
)
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def ProvenanceModernBERTFineTuneCLS(config, pretrained_state_dict=None, device="cpu", freeze_backbone=True, margin=2.0):
|
|
564
|
+
return FineTuneCLS(ProvenanceModernBERT, config, pretrained_state_dict, device, freeze_backbone, margin)
|
|
565
|
+
|
|
566
|
+
def ProvenanceModernBERTFineTuneLP(config, pretrained_state_dict=None, device="cpu", freeze_backbone=False):
|
|
567
|
+
return FineTuneLP(ProvenanceModernBERT, config, pretrained_state_dict, device, freeze_backbone)
|