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.

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

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

Author

Ayesha Javed, BS Software Engineering, COMSATS University Islamabad (Lahore). Feedback and issues are welcome in the Community tab.

Downloads last month
46
Safetensors
Model size
0.1B params
Tensor type
F32
Β·
Inference Providers NEW
This model isn't deployed by any Inference Provider. πŸ™‹ Ask for provider support

Model tree for ayshajavd/graphcodebert-vuln-classifier

Finetuned
(57)
this model

Datasets used to train ayshajavd/graphcodebert-vuln-classifier

Spaces using ayshajavd/graphcodebert-vuln-classifier 2

Evaluation results