mahdin70 commited on
Commit
c46e1f5
·
verified ·
1 Parent(s): 47ea49d

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +181 -3
README.md CHANGED
@@ -1,3 +1,181 @@
1
- ---
2
- license: mit
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ datasets:
4
+ - mahdin70/balanced_merged_bigvul_primevul
5
+ metrics:
6
+ - accuracy
7
+ - f1
8
+ - recall
9
+ - precision
10
+ base_model:
11
+ - microsoft/codebert-base
12
+ pipeline_tag: text-classification
13
+ library_name: transformers
14
+ ---
15
+
16
+ # CodeBERT-Primevul-BigVul Model Card
17
+
18
+ ## Model Overview
19
+
20
+ `CodeBERT-Primevul-BigVul` is a multi-task model based on Microsoft's `codebert-base`, fine-tuned to detect vulnerabilities (`vul`) and classify Common Weakness Enumeration (CWE) types in code snippets. It was developed by [mahdin70](https://huggingface.co/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.
21
+
22
+ - **Model Repository**: [mahdin70/CodeBERT-Primevul-BigVul](https://huggingface.co/mahdin70/CodeBERT-Primevul-BigVul)
23
+ - **Base Model**: [microsoft/codebert-base](https://huggingface.co/microsoft/codebert-base)
24
+ - **Tasks**: Vulnerability Detection (Binary), CWE Classification (Multi-class)
25
+ - **License**: MIT (assumed; adjust if different)
26
+ - **Date**: Trained and uploaded as of April 22, 2025
27
+
28
+ ## Model Architecture
29
+
30
+ The model extends `codebert-base` with two task-specific heads:
31
+ - **Vulnerability Head**: A linear layer mapping 768-dimensional hidden states to 2 classes (vulnerable or not).
32
+ - **CWE Head**: A linear layer mapping 768-dimensional hidden states to 135 classes (134 CWE types + 1 for "no CWE").
33
+
34
+ The architecture is implemented as a custom `MultiTaskCodeBERT` class in PyTorch, with the loss computed as the sum of cross-entropy losses for both tasks.
35
+
36
+ ## Training Dataset
37
+
38
+ The model was trained on the `mahdin70/balanced_merged_bigvul_primevul` dataset, which combines:
39
+ - **BigVul**: A dataset of real-world vulnerabilities from open-source projects.
40
+ - **PrimeVul**: A dataset focused on prime vulnerabilities in code.
41
+
42
+ ### Dataset Details
43
+ - **Splits**:
44
+ - Train: 124,780 samples
45
+ - Validation: 26,740 samples
46
+ - Test: 26,738 samples
47
+
48
+ - **Features**:
49
+ - `func`: Code snippet (text)
50
+ - `vul`: Binary label (0 = non-vulnerable, 1 = vulnerable)
51
+ - `CWE ID`: CWE identifier (e.g., CWE-89) or None for non-vulnerable samples
52
+
53
+ - **Preprocessing**:
54
+ - CWE labels were encoded using a `LabelEncoder` with 134 unique CWE classes identified across the dataset.
55
+ - Non-vulnerable samples assigned a CWE label of -1 (mapped to 0 in the model).
56
+
57
+ 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.
58
+
59
+ ## Training Details
60
+
61
+ ### Training Arguments
62
+ The model was trained using the Hugging Face `Trainer` API with the following arguments:
63
+ - **Evaluation Strategy**: Per epoch
64
+ - **Save Strategy**: Per epoch
65
+ - **Learning Rate**: 2e-5
66
+ - **Batch Size**: 8 (per device, train and eval)
67
+ - **Epochs**: 3
68
+ - **Weight Decay**: 0.01
69
+ - **Logging**: Every 10 steps, logged to `./logs`
70
+
71
+ ### Training Environment
72
+ - **Hardware**: 2x NVIDIA Tesla T4 GPU
73
+ - **Framework**: PyTorch 2.5.1+cu121, Transformers 4.47.0
74
+ - **Duration**: ~6 hours, 23 minutes, 18 seconds (23,397 steps)
75
+
76
+ ### Training Metrics
77
+ Validation metrics across epochs:
78
+
79
+ | Epoch | Training Loss | Validation Loss | Vul Accuracy | Vul Precision | Vul Recall | Vul F1 | CWE Accuracy |
80
+ |-------|---------------|-----------------|--------------|---------------|------------|----------|--------------|
81
+ | 1 | 0.4275 | 0.5737 | 0.9519 | 0.7753 | 0.4795 | 0.5925 | 0.0656 |
82
+ | 2 | 0.7608 | 0.5450 | 0.9537 | 0.7766 | 0.5133 | 0.6181 | 0.1349 |
83
+ | 3 | 0.5624 | 0.5443 | 0.9545 | 0.7669 | 0.5400 | 0.6338 | 0.1749 |
84
+
85
+
86
+ ## Usage
87
+
88
+ ### Installation
89
+ Install the required libraries:
90
+ ```bash
91
+ pip install transformers torch datasets huggingface_hub
92
+ ```
93
+
94
+ ### Sample Code Snippet
95
+ Below is an example of how to use the model for inference on a code snippet:
96
+
97
+ ```python
98
+ from transformers import AutoTokenizer, AutoModel
99
+ import torch
100
+
101
+ # Load tokenizer and model
102
+ tokenizer = AutoTokenizer.from_pretrained("microsoft/codebert-base")
103
+ model = AutoModel.from_pretrained("mahdin70/CodeBERT-Primevul-BigVul", trust_remote_code=True)
104
+ model.eval()
105
+
106
+ # Example code snippet
107
+ code = """
108
+ bool DebuggerFunction::InitTabContents() {
109
+ Value* debuggee;
110
+ EXTENSION_FUNCTION_VALIDATE(args_->Get(0, &debuggee));
111
+
112
+ DictionaryValue* dict = static_cast<DictionaryValue*>(debuggee);
113
+ EXTENSION_FUNCTION_VALIDATE(dict->GetInteger(keys::kTabIdKey, &tab_id_));
114
+
115
+ contents_ = NULL;
116
+ TabContentsWrapper* wrapper = NULL;
117
+ bool result = ExtensionTabUtil::GetTabById(
118
+ tab_id_, profile(), include_incognito(), NULL, NULL, &wrapper, NULL);
119
+ if (!result || !wrapper) {
120
+ error_ = ExtensionErrorUtils::FormatErrorMessage(
121
+ keys::kNoTabError,
122
+ base::IntToString(tab_id_));
123
+ return false;
124
+ }
125
+ contents_ = wrapper->web_contents();
126
+
127
+ if (ChromeWebUIControllerFactory::GetInstance()->HasWebUIScheme(
128
+ contents_->GetURL())) {
129
+ error_ = ExtensionErrorUtils::FormatErrorMessage(
130
+ keys::kAttachToWebUIError,
131
+ contents_->GetURL().scheme());
132
+ return false;
133
+ }
134
+
135
+ return true;
136
+ }
137
+ """
138
+
139
+ # Tokenize input
140
+ inputs = tokenizer(code, return_tensors="pt", padding="max_length", truncation=True, max_length=512)
141
+
142
+ # Move to GPU if available
143
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
144
+ model.to(device)
145
+ inputs = {k: v.to(device) for k, v in inputs.items()}
146
+
147
+ # Get predictions
148
+ with torch.no_grad():
149
+ outputs = model(**inputs)
150
+ vul_logits = outputs["vul_logits"]
151
+ cwe_logits = outputs["cwe_logits"]
152
+
153
+ # Vulnerability prediction
154
+ vul_pred = torch.argmax(vul_logits, dim=1).item()
155
+ print(f"Vulnerability: {'Vulnerable' if vul_pred == 1 else 'Not Vulnerable'}")
156
+
157
+ # CWE prediction (if vulnerable)
158
+ if vul_pred == 1:
159
+ cwe_pred = torch.argmax(cwe_logits, dim=1).item() - 1 # Subtract 1 as -1 is "no CWE"
160
+ print(f"Predicted CWE: {cwe_pred if cwe_pred >= 0 else 'None'}")
161
+ ```
162
+
163
+ ### Output Example:
164
+ ```bash
165
+ Vulnerability: Vulnerable
166
+ Predicted CWE: 120 # Maps to CWE-120 (Buffer Overflow), depending on encoder
167
+ ```
168
+
169
+ ## Notes
170
+ - 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.
171
+ - Ensure `trust_remote_code=True` as the model uses custom code from the repository.
172
+
173
+ ## Limitations
174
+ - **CWE Accuracy**: The model has low CWE classification accuracy (17.49%), likely due to class imbalance or complexity in distinguishing similar CWE types.
175
+ - **Recall**: Moderate recall (54.00%) for vulnerability detection suggests some vulnerable samples may be missed.
176
+ - **Generalization**: Trained on BigVul and PrimeVul, performance may vary on out-of-domain codebases.
177
+
178
+ ## Future Improvements
179
+ - Increase training epochs or dataset size to improve CWE accuracy.
180
+ - Experiment with class weighting to address CWE imbalance.
181
+ - Fine-tune on additional datasets for broader generalization.