engrsakib
5,431 hrs
Live WakaTime Coding Metric

Repository Workspace

LLM-Prompt-Injection-Threat-Detection-Using-Deep-Learning

Comparative evaluation of deep learning classifiers for detecting and categorizing prompt injection and jailbreak attacks against LLM-integrated applications.

★ 0 stars⑂ 0 forksDefault · main

Source viewer

Select a file from the tree

Configuration files and source modules stream through the secure API proxy and render with the active theme accent.

README.md

<div align="center">

LLM Prompt Injection Threat Detection Using Deep Learning

Comparative evaluation of 16 deep-learning classifiers for detecting and categorizing prompt injection and jailbreak attacks against LLM-integrated applications.

<br/>

Author: Md. Nazmus Sakib · Co-Author: Kazi Omar Faruq

<br/>

License: MIT Dataset License: CC BY-NC 4.0

<br/>

Python PyTorch Hugging Face

Thesis Institution Domain Status

</div>

Table of Contents


Overview

This repository supports a capstone thesis on LLM security, focused on prompt injection detection. The objective is to train, compare and benchmark multiple deep learning architectures on the Threat Matrix dataset, extending beyond binary classification toward 7-class intent recognition and technique-aware analysis.

The research is grounded in recent work on prompt injection taxonomies, LLM agent security and adversarial NLP, including ARGUS, AgentSentry, CLAWGUARD, MetaSecAlign and systematic reviews of LLM defence mechanisms. Full PDFs are available in papers/.


Status at a glance

AreaStateEvidence
Data Phases 1-3 (clean, dedup, enrich, augment, audit)implemented, executeddata/processed/ + reports
Phase 3.5 group-aware leakage-free re-splitimplemented, executed (v1_leakfree, audit passed)data/processed/splits/v1_leakfree/manifest.json
16-model registry + shared classifier interfaceimplementedsrc/models/, docs/MODEL_REGISTRY.md
Trainer (resume, early stop, history), per-model configsimplementedsrc/training/ , configs/models/*.yaml
Metrics, per-example predictions, tables, 17 figure typesimplementedsrc/eval/
Resumable Kaggle sweep + notebookimplemented. End-to-end Kaggle verification pendingsrc/training/sweep.py, notebooks/kaggle_train.ipynb
CPU smoke runs (TextCNN, DistilBERT, 300 train rows)executed locallyoutputs/smoke/ (not publication results)
Full training of the 16 models (3 seeds)not executed (requires GPU; see Kaggle workflow)-
Llama-3.1-8Bblocked (gated checkpoint; needs approved HF_TOKEN)registry

Run the unit tests with python -m pytest -q (tiny synthetic fixtures, no network).


Technology Stack

TechnologyVersion used locallyRole
Python3.13.7 (CI: 3.11)Primary language
PyTorch2.13 (CPU build locally)Deep learning backend
Transformers5.22 (>= 4.51 required for Qwen3)Pre-trained model loading & fine-tuning
PEFT0.21LoRA / QLoRA for 7B-8B decoders
Datasets / Hub5.1 / 2.4Dataset snapshot + checkpoint metadata
scikit-learn1.5+Metrics
pandas / pyarrow2.2+Data processing, Parquet
datasketch1.6+MinHash LSH near-duplicate detection
Matplotlib3.9+Figures (Okabe-Ito colour-blind-safe palette)
DVC / MLflow3.x / 2.xPipeline + experiment tracking

Install:

pip install -r requirements.txt          # runtime
pip install -r requirements-dev.txt      # pytest, ruff, mypy
# Kaggle sessions: pip install -r requirements-kaggle.txt (pinned, no torch re-pin)

Dataset

PropertyValue
Upstreamneuralchemy/prompt-injection-Threat-Matrix, config multiclass
Local snapshotdata/raw/{train,validation,test}.jsonl + snapshot_metadata.json (id tm-4e7fede7adba) - the pipeline never re-downloads
Raw rows (measured)25,856 / 3,232 / 3,232 = 32,320
LicenceCC BY-NC 4.0 according to the local snapshot metadata; the upstream page could not be re-verified at build time
LanguageEnglish

Intent classes (intent_label; logits column order everywhere)

LabelIntentDescription
0benignNormal user input
1direct_injectionExplicit instruction override
2system_extractionAttempts to leak system prompt
3role_hijackPersona or role manipulation
4obfuscationEncoded or disguised attacks
5tool_abuseMalicious tool/function calls
6indirect_injectionContext-based injection

Schema (as measured on the local snapshot)

FieldTypeMeasured facts
textstringprompt
label / intent_labelintidentical for every row
binary_labelintequals intent_label != 0 for every row
severityintvalues {1, 2, 3} only (not 1-10 as documented upstream)
techniquestringattack technique
surfacestringconstant user_input - carries no information
sourcestringhackaprompt, core, synthetic_threat, synthetic_benign, synthetic_short
ambiguityboolborderline flag

Synthetic share (source starts with synthetic): 37.9% / 37.5% / 38.6% per raw split. Synthetic rows are kept; results are additionally reported for synthetic vs non-synthetic subsets (src/eval/tables.py::subgroup_table).

Full data card: docs/DATA_CARD.md.


Data Engineering (Phases 1-3)

python -m src.data.prepare --config configs/data.yaml --phase all   # or: dvc repro prepare enrich finalize
PhaseModulesOutputs (data/processed/)
1 Ingest / clean / dedup / validateingest.py, cleaning.py, dedup.py, validation.py`train
2 Obfuscation features, balancing, augmentation, subsetsobfuscation.py, analysis.py, balancing.py, augment.pytrain_balanced.parquet, train_augmented.parquet, subsets/ambiguity_*
3 Technique subsets, adversarial paraphrase, leakage audit, Kaggle ziptechnique_subsets.py, adversarial_paraphrase.py, leakage.py, kaggle_package.pytrain_adversarial.parquet, kaggle_package.zip, reports/leakage_report.json

Important: the Phase 3 audit of these upstream-split artifacts reports cross-split overlap (reports/leakage_report.json, passed: false: 127 exact + 125 near pairs after processing; on the raw files: 14 / 20 / 4 exact duplicates train-val / train-test / val-test and 198 benign (example N) template families spanning splits). These historical files are kept for traceability but must not be used for model evaluation - use Phase 3.5.


Phase 3.5: Leakage-aware re-split

python -m src.data.phase35 --config configs/data.yaml      # ~90 s on CPU; or: dvc repro resplit

Policy (group-aware re-split, chosen with the supervisor's approval): all raw rows are pooled, grouped into families, and whole families are assigned to one split with a stratified greedy placement (~80/10/10) that uses the upstream split as tie-break.

StepRule
Family linksexact normalised fingerprint or template stem ((example N) suffix removed) or MinHash-LSH word-3-gram Jaccard >= 0.85 (configurable). Rows without shingles are never linked. A source category alone is never a family key.
Within-split dedupexact + near (same threshold) inside each split only
Auditfull (not sampled) raw / normalised / near / family checks across all split pairs; the run fails unless it passes
Train variantstrain_balanced, train_augmented, train_adversarial regenerated from the new train split only; each is audited against the new validation/test (all passed, 0 overlaps)
Manifestmanifest.json with frozen: true, SHA-256 of every artifact, before/after counts, moved-row matrix, dropped-row log, thresholds, licence caveat

Measured result (data/processed/splits/v1_leakfree/manifest.json, 2026-11-07):

trainvalidationtest
rows after group split (before dedup)25,8533,2323,235
exact / near removed within split327 / 3,43351 / 40132 / 401
final rows22,0932,7802,802
families18,8262,3862,385
synthetic rows7,388 (33.4%)909 (32.7%)910 (32.5%)

32,320 rows -> 23,597 families (22,390 singletons, largest 664); 3,508 rows changed split; 4,645 rows dropped as within-split duplicates; cross-split raw/exact/near/family overlaps after re-split: 0 / 0 / 0 / 0. All 7 classes present in every split. Train variants: balanced 22,984, augmented 26,116, adversarial 46,801 rows.

Passing these heuristic checks does not prove zero statistical leakage (paraphrases below the Jaccard threshold, shared templates with different wording, etc.). Raw-file numbers (14/20/4) and processed-file numbers (127/125) are different measurements and must never be combined.

Every training / evaluation entrypoint loads manifest.json, refuses non-frozen or failed-audit splits and re-verifies artifact hashes (src/data/phase35.py::load_frozen_manifest).


Model Registry (16 backbones)

Full table with checkpoints, revisions, licences, parameter counts and evidence: docs/MODEL_REGISTRY.md (regenerate with python -m src.models.registry; --check --online verifies Hub metadata without downloading weights).

#model_idModelCheckpointTierStatus (2026-11-07)
1distilbertDistilBERTdistilbert-base-uncasedcpu_oksmoke-tested
2bertBERTbert-base-uncasedgpu_smallimplemented
3robertaRoBERTaroberta-basegpu_smallimplemented
4deberta_v3DeBERTa-v3microsoft/deberta-v3-basegpu_smallimplemented
5securebertSecureBERTehsanaghaei/SecureBERT @ 3a47918d (corrected: ehsanaul/securebert-base returns 401)gpu_smallimplemented
6albertALBERTalbert-base-v2cpu_okimplemented
7electra_smallELECTRA-smallgoogle/electra-small-discriminatorcpu_okimplemented
8textcnnTextCNNcustom, train-only vocabcpu_oksmoke-tested
9bilstm_attentionBiLSTM + Attentioncustom, train-only vocabcpu_okimplemented
10cnn_bilstmCNN-BiLSTMcustom, train-only vocabcpu_okimplemented
11distilrobertaDistilRoBERTadistilroberta-basecpu_okimplemented
12xlnetXLNetxlnet-base-casedgpu_smallimplemented
13modernbert_largeModernBERT-large (experimental)answerdotai/ModernBERT-large @ 45bb4654gpu_mediumimplemented
14mistral_7bMistral-7B v0.3 base + QLoRA (experimental)mistralai/Mistral-7B-v0.3 @ caa1feb0gpu_large_qloraimplemented
15qwen3_8bQwen3-8B + QLoRA (experimental; post-trained release, base is Qwen3-8B-Base)Qwen/Qwen3-8B @ b968826dgpu_large_qloraimplemented
16llama31_8bLlama-3.1-8B + QLoRA (experimental)meta-llama/Llama-3.1-8B @ d04e592bgpu_large_qlorablocked (gated)

"implemented" means the code path exists and unit tests cover the interface; it does not mean the model has been trained. Decoder models were verified only with a random tiny Llama config (padding invariance + adapter/head save-reload); no 7B/8B weights were loaded locally.

Shared interface (src/models/base.py): every model consumes input_ids/attention_mask, returns 7 logits in LABEL_ORDER, saves/loads from a directory; custom models fit their vocabulary on the training split only; decoders use LoRA (peft, TaskType.SEQ_CLS) with the score head trained and saved, right padding and last-non-pad-token pooling, 4-bit QLoRA when bitsandbytes + CUDA exist (fallback recorded in load_info).

Excluded by design: GPT-4 Attack Validator, Lakera Guard, MetaSecAlign (external / paid / generative; no data leaves the machine).


Training

One job = one model x one seed. Validation is used only for early stopping (macro-F1) and binary-threshold selection; test predictions are produced once from the best validation checkpoint.

# CPU smoke test (300 stratified train rows, 100 val/test rows, 1 epoch, max_length 64) -> outputs/smoke/
python -m src.training.train_cli --model textcnn    --seed 42 --smoke
python -m src.training.train_cli --model distilbert --seed 42 --smoke

# Full run (GPU) -> outputs/runs/<model>/seed_<seed>/
python -m src.training.train_cli --model roberta --seed 42 --config configs/experiment.yaml
python -m src.training.train_cli --model roberta --seed 42 --resume          # continue after interruption
python -m src.training.train_cli --model roberta --seed 42 --train-file train_adversarial.parquet   # ablation variant

# Resumable sweep (models x seeds, manifest in outputs/sweep/manifest.json)
python -m src.training.sweep --config configs/experiment.yaml --models textcnn distilbert --seeds 42 43 44

Configuration precedence: registry defaults -> configs/models/<model_id>.yaml -> configs/experiment.yaml: training_overrides -> CLI flags (--epochs --batch-size --learning-rate --max-length --grad-accum --precision). Common max-length policy: 256 tokens; truncation rates per split are logged in run_summary.json. Default seeds: 42, 43, 44.

Each run writes config.json, history.jsonl (step/epoch loss, lr, val metrics), checkpoint/ (best), last/ (resume state incl. optimizer/scheduler/RNG; deleted after success unless --keep-last), threshold.json, metrics_{validation,test}.json, predictions_{validation,test}.parquet, run_summary.json (wall time, hardware, parameter counts, truncation rates).


Evaluation, tables and figures

src/eval/evaluate.py validates probabilities (shape N x 7, finite, rows sum to 1) and computes: accuracy, balanced accuracy, macro/micro/weighted precision/recall/F1, per-class P/R/F1/support, MCC, one-vs-rest AUROC and AP (per class + macro + weighted), raw and row-normalised confusion matrices, per-class TP/TN/FP/FN, calibration (top-label ECE, multiclass Brier, NLL, reliability bins), and binary attack metrics with p_attack = sum(p[1:7]) and a threshold chosen on validation only (precision, recall, F1, specificity, FPR, FNR, MCC, AUROC, AP, TP/TN/FP/FN). Metrics that cannot be computed (e.g. AUROC for a class absent from the gold labels) are null with a reason under unavailable.

python -m src.eval.tables --runs outputs/runs --out outputs/tables            # runs_test.csv, seed_summary_test.csv (mean/std over seeds),
                                                                              # per_class_test.csv, subgroups_test.csv (source/technique/ambiguity/severity/synthetic),
                                                                              # bootstrap_ci_test.json (group-aware percentile CI over families)
python -m src.eval.plots  --runs outputs/runs --out outputs/figures            # 17 figure types, PNG 300 DPI + PDF + SVG, skipped.json for missing prerequisites

Seed variance (mean/std over seeds) and sampling uncertainty (family-level bootstrap CI of one run) are always reported separately. Figures: confusion counts, normalised confusion, binary TP/TN/FP/FN, per-class OvR counts, dataset distribution (labelled DATASET), loss curves, val macro-F1 curves, cross-model bars (+ separate bootstrap-CI figure), model x class F1 heatmap, OvR ROC + macro/binary ROC, PR curves with prevalence baselines, AUROC/AP comparison, subset performance with n, train-variant ablation, reliability diagram, efficiency vs F1, confidence/error histograms.


Kaggle workflow

Follow the Kaggle run guide with the training notebook.

  1. Build the code-only bundle from the updated repository and attach it as a private Kaggle dataset. The notebook can also use a complete checkout.
  2. Package the existing frozen splits with python -m src.data.kaggle_package or bash scripts/package_kaggle.sh. Extract data/processed/splits/v1_leakfree/kaggle_upload_v1_leakfree.zip and attach the files as a separate private dataset.
  3. Select a CUDA GPU such as T4 x2 and enable Internet for package and uncached checkpoint downloads. Run the notebook in order and verify REPOSITORY IMPORT VERIFIED and LOCAL FROZEN MANIFEST VALIDATED.
  4. Use configs/kaggle_debug.yaml for TextCNN and DistilBERT with seed 42. After both succeed, use configs/experiment.yaml for full runs with seeds 42, 43, and 44.
  5. Save and download /kaggle/working/outputs. Debug artifacts and their sweep manifest live in outputs/debug/. Full-study artifacts use the root outputs/ layout.

Artifact map

data/raw/                                 # local snapshot (never modified)
data/processed/                           # Phases 1-3 on upstream splits (historical; audit FAILED - do not evaluate on these)
data/processed/splits/v1_leakfree/        # Phase 3.5 (frozen; audit PASSED)
  train|validation|test.parquet, train_balanced|augmented|adversarial.parquet
  manifest.json, dropped_rows.jsonl, family_assignments.parquet
  reports/leakage_report*.json, subsets/, kaggle_package/, kaggle_package_v1_leakfree.zip
  kaggle_upload_v1_leakfree.zip             # upload bundle from the canonical frozen artifacts
outputs/smoke/<model>_seed<seed>/         # CPU smoke runs (not publication results)
outputs/runs/<model>/seed_<seed>/         # production runs (none yet)
outputs/sweep/manifest.json               # sweep state
outputs/tables/, outputs/figures/         # aggregated tables and figures
docs/registry.json, docs/MODEL_REGISTRY.md

Project Structure

model/
├── papers/                  # Reference literature (PDF)
├── configs/                 # data.yaml, experiment.yaml, kaggle_debug.yaml, models/<model_id>.yaml (16)
├── docs/                    # DATA_CARD, MODEL_REGISTRY, REPRODUCIBILITY, registry.json
├── notebooks/               # kaggle_train.ipynb (thin), kaggle_run.md
├── src/
│   ├── data/                # Phases 1-3 + families.py, resplit.py, phase35.py, leakage.py
│   ├── models/              # base.py, vocab.py, textcnn.py, bilstm_attention.py, cnn_bilstm.py,
│   │                        # hf_encoder.py, decoder_classifier.py, registry.py
│   ├── training/            # data.py, trainer.py, train_cli.py, sweep.py
│   ├── eval/                # evaluate.py, predict.py, tables.py, plots.py
│   └── kaggle/              # env.py
├── scripts/                 # download_data.py, kaggle_run.sh, package_kaggle.sh
├── tests/                   # 42 tests (data pipeline, study modules, smoke)
├── data/, outputs/, mlruns/ # gitignored artifacts
├── dvc.yaml, params.yaml, pyproject.toml, requirements*.txt
└── README.md

Getting Started

git clone <repository-url> && cd model
python -m venv .venv && .venv\Scripts\activate      # Windows; use source .venv/bin/activate on Linux/macOS
pip install -r requirements.txt -r requirements-dev.txt

python -m compileall -q src tests && pytest -q          # 42 passed
python -m src.data.phase35 --config configs/data.yaml   # needs data/raw/*.jsonl (local snapshot)
python -m src.training.train_cli --model textcnn --seed 42 --smoke
python -m src.eval.tables --runs outputs/smoke --out outputs/smoke/tables
python -m src.eval.plots  --runs outputs/smoke --out outputs/smoke/figures --tag "SMOKE"
python -m src.models.registry --check

Docker (CPU): docker build -t prompt-injection-model -f docker/Dockerfile . then docker run --rm -v %cd%/data:/app/data -v %cd%/outputs:/app/outputs prompt-injection-model --model textcnn --seed 42 --smoke.


Troubleshooting

SymptomCause / fix
LeakageError: ... not frozen or audit failedCheck the selected split directory. For a stale Kaggle package, rebuild the archive from the existing canonical frozen split with python -m src.data.kaggle_package.
Model 'llama31_8b' is registered as BLOCKEDGated checkpoint. Export HF_TOKEN with approved access (env var / Kaggle Secret) and pass --force-blocked.
bitsandbytes import error / QLoRA fallback recordedbitsandbytes needs Linux + CUDA. The decoder loads without quantization (needs more VRAM) and records fallback_reason in load_info.
Qwen3 "model type not recognised"transformers >= 4.51 required (requirements.txt pins >= 4.51).
Sweep job blocked: compute tier ... not availablepython -m src.kaggle.env shows the detected VRAM; choose a GPU session or smaller models.
Kaggle session killed mid-runRestore the saved output tree and rerun with the same profile. The sweep requeues stale running jobs and the trainer resumes from last/ when present.
Smoke metrics look poorExpected: 300 train rows, 1 epoch. Smoke runs only verify the pipeline.

Limitations and honesty notes

  • No production training has been executed. All 16 models are implemented and unit-tested; only TextCNN and DistilBERT were run as CPU smoke tests on 300-row subsets. No thesis-level performance numbers exist yet.
  • Decoder (7B/8B) paths were validated with a tiny random Llama config; real weights were never loaded locally (no CUDA on the development machine).
  • Leakage checks are heuristic (exact, template, Jaccard >= 0.85 word-3-gram, family). Semantic paraphrases below the threshold can still cross splits.
  • The dataset licence/provenance relies on the local snapshot metadata; the upstream page was inaccessible. Do not redistribute the data without verified permission.
  • severity has only three values in the snapshot; severity-regression experiments described in earlier drafts are not meaningful on this data and are not implemented.
  • Historical Phase 1-3 outputs (data/processed/*.parquet, kaggle_package.zip) are kept but are not valid evaluation data.

Reference Papers

Local copies in papers/ · Google Drive collection

PaperFocus Area
1.pdfEffectiveness of existing detection methods
4.pdf - 6.pdfReal-world LLM compromise, AgentSentry, indirect injection
7.pdf, 10.pdfNetwork intrusion & malicious traffic classification
8.pdf - 9.pdf, 11.pdfARGUS - LLM agent defence
12.pdfCLAWGUARD - runtime agent security
13.pdf - 15.pdfHybrid defence, threat taxonomy, injection attacks
16.pdfFederated learning poisoning detection
17.pdf - 18.pdfMetaSecAlign - secure foundation LLM
19.pdfSystematic literature review on LLM defences
20.pdf - 21.pdfRetrieval barrier, TaintP2X injection detection

Citation

@dataset{jajoo2026threatmatrix,
  author    = {Sanskar Jajoo},
  title     = {Neuralchemy Prompt Injection Threat Matrix},
  year      = {2026},
  publisher = {Hugging Face},
  url       = {https://huggingface.co/datasets/neuralchemy/prompt-injection-Threat-Matrix}
}

License

See LICENSE for the full MIT license text.

ComponentLicenseHolder
This repositoryMIT LicenseMd. Nazmus Sakib · Kazi Omar Faruq
Threat Matrix datasetCC BY-NC 4.0 (per local snapshot metadata)Sanskar Jajoo / Neuralchemy
Pre-trained modelsRespective Hugging Face model licences (see docs/MODEL_REGISTRY.md)Model authors

The dataset is not covered by MIT: it is Creative Commons Attribution-NonCommercial 4.0. Attribute the authors, do not use it commercially, and do not redistribute it without verified permission. Full legal code: https://creativecommons.org/licenses/by-nc/4.0/legalcode

Copyright © 2026 Md. Nazmus Sakib (engrskib.com) and Kazi Omar Faruq.


<div align="center">

Daffodil International University · 7th Capstone Design · 2026

LLM Security · Prompt Injection Detection · Deep Learning

</div>

Back online.