--- license: apache-2.0 library_name: transformers base_model: microsoft/graphcodebert-base tags: - security - vulnerability-detection - code-analysis - multi-label-classification - graphcodebert - owasp - cwe - static-analysis language: - en - code pipeline_tag: text-classification datasets: - ayshajavd/code-security-vulnerability-dataset - bstee615/bigvul - CyberNative/Code_Vulnerability_Security_DPO - lemon42-ai/Code_Vulnerability_Labeled_Dataset model-index: - name: graphcodebert-vuln-classifier results: - task: type: text-classification name: Multi-label Vulnerability Classification dataset: type: ayshajavd/code-security-vulnerability-dataset name: Code Security Vulnerability Dataset split: test metrics: - type: f1 value: 0.4758 name: Macro F1 - type: f1 value: 0.9426 name: Micro F1 - type: f1 value: 0.9454 name: Weighted F1 - type: f1 value: 0.982 name: F1 (safe class) - type: precision value: 0.4825 name: Macro Precision - type: recall value: 0.5278 name: Macro Recall --- # GraphCodeBERT Vulnerability Classifier (v2) A multi-label model that flags **30 CWE vulnerability types** (plus a `safe` label) in source code and maps them to the **OWASP Top 10 (2021)**. It is the detection stage of **Out of Harm's Way**, a research project on learning-based vulnerability detection and repair. - **Base model:** [microsoft/graphcodebert-base](https://huggingface.co/microsoft/graphcodebert-base) (12 layers, ~125M parameters) - **Training data:** [ayshajavd/code-security-vulnerability-dataset](https://huggingface.co/datasets/ayshajavd/code-security-vulnerability-dataset) (175,419 samples from BigVul, PrimeVul, Code Vulnerability Labeled and CyberNative DPO pairs; several languages) - **Training code:** [ayshajavd/vuln-classifier-training-notebooks](https://huggingface.co/ayshajavd/vuln-classifier-training-notebooks) - **Project write-up:** [github.com/ayshajaved/out-of-harms-way-vuln-detection](https://github.com/ayshajaved/out-of-harms-way-vuln-detection) - **Demo:** [Code Security Risk Analyzer](https://huggingface.co/spaces/ayshajavd/code-security-analyzer) - **Companion fix model:** [ayshajavd/codet5p-vuln-fixer](https://huggingface.co/ayshajavd/codet5p-vuln-fixer) > **Version note.** v1 of this repository (April 2026) was a CodeBERTa-small model trained with class-weighted BCE (test macro-F1 0.116). The weights here are **v2**, described below. The repository name was kept for compatibility with the demo. ## Results (test split) Per-class thresholds were tuned on the **validation** split; all numbers below are on the held-out **test** split. | Metric | v1 (CodeBERTa-small, weighted BCE) | **v2 (this model)** | |---|---|---| | Macro F1 (31 labels) | 0.116 | **0.476** | | Micro F1 | – | **0.943** | | Weighted F1 | – | **0.945** | | F1, `safe` | – | **0.982** | | Macro precision / recall | – | **0.482 / 0.528** | Selected per-class F1: CWE-89 SQL injection 0.79 · CWE-190 integer overflow 0.77 · CWE-94 code injection 0.71 · CWE-119 buffer errors 0.71 · CWE-200 information exposure 0.70 · CWE-362 race condition 0.70 · CWE-79 XSS 0.59 · CWE-20 input validation 0.57. ### Known limitations (honest reading of the numbers) - **Strong class imbalance.** The test split has 15,655 `safe` labels but only a handful of examples for many CWEs: 3 classes (CWE-276, CWE-434, CWE-918) have **no** test examples, and several others (e.g. CWE-269, CWE-327, CWE-352, CWE-798) have 1–2. Seven classes score F1 = 0, and zero-support classes pull the macro average down, so macro-F1 over 31 labels understates performance on well-represented classes and overstates confidence on rare ones. - Micro and weighted F1 are dominated by the `safe` class and should not be read as overall vulnerability-detection quality. - Inputs are truncated to 512 tokens; long functions lose context. - Labels come from public datasets with known label noise and possible near-duplicates between splits; results may not transfer to unseen codebases. - This is a research prototype, **not** a replacement for code review or SAST tools. Studying the rare-class problem (better evaluation for zero/low-support classes, cross-dataset generalisation, duplicate checks) is the next step of this project. ## What changed from v1 to v2 1. **Base model:** GraphCodeBERT-base (12 layers) instead of CodeBERTa-small (6 layers). 2. **Asymmetric Loss (ASL)** for multi-label imbalance: `gamma_neg=4`, `gamma_pos=0`, `clip=0.05`. 3. **Two-phase training:** phase 1 freezes the embeddings and bottom 8 of 12 layers (4 epochs, lr 1e-4, cosine schedule, 6% warmup); phase 2 fine-tunes all layers (up to 9 epochs, lr 2e-5, early stopping with patience 3). Effective batch size 32, fp16, best checkpoint by validation macro-F1. 4. **Classification-head bias initialisation** for imbalanced classes. 5. **Per-class decision thresholds** optimised on the validation split. 6. **Temperature scaling** for calibration (T = 0.6163). Thresholds, temperature, CWE names, OWASP mapping and full metrics are stored in `label_config.json`. ## How to use ```python import json, torch from huggingface_hub import hf_hub_download from transformers import AutoTokenizer, AutoModelForSequenceClassification model_id = "ayshajavd/graphcodebert-vuln-classifier" tokenizer = AutoTokenizer.from_pretrained(model_id) model = AutoModelForSequenceClassification.from_pretrained(model_id).eval() cfg = json.load(open(hf_hub_download(model_id, "label_config.json"))) code = ''' def get_user(conn, username): query = f"SELECT * FROM users WHERE username = '{username}'" return conn.execute(query).fetchone() ''' inputs = tokenizer(code, return_tensors="pt", max_length=512, truncation=True) with torch.no_grad(): probs = torch.sigmoid(model(**inputs).logits / cfg["temperature"])[0] for i, label in enumerate(cfg["target_cwes"]): if label != "safe" and probs[i] > cfg["optimized_thresholds"][label]: print(label, cfg["cwe_names"].get(label, ""), round(float(probs[i]), 3)) ``` ## Training setup - Hardware: Kaggle GPU (NVIDIA T4) - Max sequence length: 512 tokens - Notebooks: phase 1, phase 2, threshold optimisation + calibration + evaluation, and the fixer model, all in [vuln-classifier-training-notebooks](https://huggingface.co/ayshajavd/vuln-classifier-training-notebooks) ## Author Ayesha Javed, BS Software Engineering, COMSATS University Islamabad (Lahore). Feedback and issues are welcome in the Community tab.