Downloads · 30 days
17
3% of all-time downloads
mahdin70/UnixCoder-Primevul-BigVul
UnixCoder-Primevul-BigVul is a text classification model from mahdin70. Use it when you need a label for a piece of text. It is set up for transformers. The card lists the license as mit.
UnixCoder-Primevul-BigVul is a multi-task model based on Microsoft's unixcoder-base, fine-tuned to detect vulnerabilities (vul) and classify Common Weakness Enumeration (CWE) types in code snippets. It was developed b…
Downloads · 30 days
17
3% of all-time downloads
All-time downloads
488
Public
Parameters
126M
504 MB on disk
Likes
0
Public
Click a slice to open those files.
.safetensors504 MB · 100%
From the Hugging Face model README
UnixCoder-Primevul-BigVul is a multi-task model based on Microsoft's unixcoder-base, fine-tuned to detect vulnerabilities (vul) and classify Common Weakness Enumeration (CWE) types in code snippets. It was developed by mahdin70 and trained on a balanced dataset combining BigVul and PrimeVul datasets. The model performs binary classification for vulnerability detection and multi-class classification for CWE identification.
The model extends unixcoder-base with two task-specific heads:
The architecture is implemented as a custom MultiTaskUnixCoder class in PyTorch, with the loss computed as the sum of cross-entropy losses for both tasks.
The model was trained on the mahdin70/balanced_merged_bigvul_primevul dataset, which combines:
Splits:
Features:
func: Code snippet (text)vul: Binary label (0 = non-vulnerable, 1 = vulnerable)CWE ID: CWE identifier (e.g., CWE-89) or None for non-vulnerable samplesPreprocessing:
LabelEncoder with 134 unique CWE classes identified across the dataset.The dataset is balanced to ensure a fair representation of vulnerable and non-vulnerable samples, with a maximum of 10 samples per commit where applicable.
The model was trained using the Hugging Face Trainer API with the following arguments:
./unixcoder_multitask./logsValidation metrics across epochs:
| Epoch | Training Loss | Validation Loss | Vul Accuracy | Vul Precision | Vul Recall | Vul F1 | CWE Accuracy |
|---|---|---|---|---|---|---|---|
| 1 | 0.3038 | 0.4997 | 0.9570 | 0.8082 | 0.5379 | 0.6459 | 0.1887 |
| 2 | 0.6092 | 0.4859 | 0.9587 | 0.8118 | 0.5641 | 0.6657 | 0.2964 |
| 3 | 0.4261 | 0.5090 | 0.9585 | 0.8114 | 0.5605 | 0.6630 | 0.3323 |
The model was evaluated on the test split (26,738 samples) with the following metrics:
The model excels at identifying non-vulnerable code (high accuracy) but has moderate recall for vulnerabilities and lower CWE classification accuracy, indicating room for improvement in CWE prediction.
Install the required libraries:
pip install transformers torch datasets huggingface_hub
Below is an example of how to use the model for inference on a code snippet:
from transformers import AutoTokenizer, AutoModel
import torch
# Load tokenizer and model
tokenizer = AutoTokenizer.from_pretrained("microsoft/unixcoder-base")
model = AutoModel.from_pretrained("mahdin70/UnixCoder-Primevul-BigVul", trust_remote_code=True)
model.eval()
# Example code snippet
code = """
bool DebuggerFunction::InitTabContents() {
Value* debuggee;
EXTENSION_FUNCTION_VALIDATE(args_->Get(0, &debuggee));
DictionaryValue* dict = static_cast<DictionaryValue*>(debuggee);
EXTENSION_FUNCTION_VALIDATE(dict->GetInteger(keys::kTabIdKey, &tab_id_));
contents_ = NULL;
TabContentsWrapper* wrapper = NULL;
bool result = ExtensionTabUtil::GetTabById(
tab_id_, profile(), include_incognito(), NULL, NULL, &wrapper, NULL);
if (!result || !wrapper) {
error_ = ExtensionErrorUtils::FormatErrorMessage(
keys::kNoTabError,
base::IntToString(tab_id_));
return false;
}
contents_ = wrapper->web_contents();
if (ChromeWebUIControllerFactory::GetInstance()->HasWebUIScheme(
contents_->GetURL())) {
error_ = ExtensionErrorUtils::FormatErrorMessage(
keys::kAttachToWebUIError,
contents_->GetURL().scheme());
return false;
}
return true;
}
"""
# Tokenize input
inputs = tokenizer(code, return_tensors="pt", padding="max_length", truncation=True, max_length=512)
# Move to GPU if available
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
inputs = {k: v.to(device) for k, v in inputs.items()}
# Get predictions
with torch.no_grad():
outputs = model(**inputs)
vul_logits = outputs["vul_logits"]
cwe_logits = outputs["cwe_logits"]
# Vulnerability prediction
vul_pred = torch.argmax(vul_logits, dim=1).item()
print(f"Vulnerability: {'Vulnerable' if vul_pred == 1 else 'Not Vulnerable'}")
# CWE prediction (if vulnerable)
if vul_pred == 1:
cwe_pred = torch.argmax(cwe_logits, dim=1).item() - 1 # Subtract 1 as -1 is "no CWE"
print(f"Predicted CWE: {cwe_pred if cwe_pred >= 0 else 'None'}")
Vulnerability: Vulnerable
Predicted CWE: 120 # Maps to CWE-120 (Buffer Overflow), depending on encoder
The CWE prediction is an integer index (0 to 133). To map it to a specific CWE ID (e.g., CWE-120), you need the LabelEncoder used during training, available in the dataset preprocessing step. Ensure trust_remote_code=True as the model uses custom code from the repository.