File size: 9,881 Bytes
3efa7f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7ba8ea
 
 
 
 
 
 
 
 
 
 
 
e51a237
b7ba8ea
 
 
3efa7f7
b7ba8ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
---
dataset_info:
  features:
  - name: conversations
    list:
    - name: from
      dtype: string
    - name: value
      dtype: string
  - name: source
    dtype: string
  - name: score
    dtype: float64
  splits:
  - name: train
    num_bytes: 93911454
    num_examples: 26296
  - name: test
    num_bytes: 10913928
    num_examples: 2922
  download_size: 34387789
  dataset_size: 104825382
configs:
- config_name: default
  data_files:
  - split: train
    path: data/train-*
  - split: test
    path: data/test-*
license: mit
task_categories:
- text-generation
- question-answering
language:
- en
tags:
- code
- code vulnerability
- C
- C++
- cpp
- en
pretty_name: Code Vulnerability Balanced  CWE-Enriched Conversation Dataset
size_categories:
- 10K<n<100K
---
# Code Vulnerability Balanced — CWE-Enriched Conversation Dataset

## 📌 Overview

This dataset is a **balanced and shuffled** version of
[ChamaraVishwajithRajapaksha/Code-Vulnerability-FineTune](https://huggingface.co/datasets/ChamaraVishwajithRajapaksha/Code-Vulnerability-FineTune),
which itself was derived from the original
[ChamaraVishwajithRajapaksha/Code_Vulnerability_Dataset](https://huggingface.co/datasets/ChamaraVishwajithRajapaksha/Code_Vulnerability_Dataset)
(330k rows, sourced from DiverseVul + MITRE CWE enrichment).

The original fine-tuning dataset was **imbalanced** — the number of **Vulnerable** and **Safe**
samples were not equal — and the samples were **not shuffled**. This dataset addresses both issues:

-**Balanced** — Equal number of Vulnerable and Safe (patched) samples
-**Shuffled** — Samples are randomly shuffled to prevent ordering bias during training
-**ShareGPT / FineTome format** — Ready for fine-tuning with Unsloth, TRL, and similar frameworks

---

## 🎯 Use Cases

- Fine-tuning LLMs for security code review
- Training vulnerability detection models
- Building code-aware security assistants
- Research in automated static analysis and secure coding

---

## 📊 Dataset Statistics

| Property | Value |
|---|---|
| Source Dataset | ChamaraVishwajithRajapaksha/Code-Vulnerability-FineTune |
| Balancing Strategy | Undersample majority class to match minority class |
| Shuffled | Yes (random seed 42) |
| Format | ShareGPT (conversations) |
| Languages | C, C++ |
| Splits | train (90%) · test (10%) |
| License | MIT |

---

## 🔄 What Changed From the Source Dataset

| Change | Description |
|---|---|
| **Balancing** | The source dataset had an unequal number of Vulnerable vs Safe samples. This dataset undersamples the majority class so both are equal in count. |
| **Shuffling** | All rows are randomly shuffled (seed 42) before splitting, preventing the model from learning ordering patterns. |
| **Same format** | The ShareGPT conversation structure is preserved exactly as in the source dataset. |

---

## 🗂️ Data Format

Each row follows the ShareGPT conversation format with two turns:

```json
{
  "conversations": [
    {
      "from": "human",
      "value": "Analyze the following code snippet and identify any security vulnerabilities...\n\n```c\n<source code>\n```"
    },
    {
      "from": "gpt",
      "value": "## Security Vulnerability Analysis\n\n⚠️ This code sample is marked as **Vulnerable**.\n\n### 🔍 Vulnerability Classification\n- **CWE ID**: CWE-787\n- **Type**: Out-of-bounds Write\n- **Severity**: High\n..."
    }
  ],
  "source": "code_vulnerability_cwe",
  "score": 4.8
}
```

### Fields

| Field | Type | Description |
|---|---|---|
| `conversations` | list | List of 2 conversation turns |
| `conversations[0].from` | str | Always `"human"` |
| `conversations[0].value` | str | Instruction + C/C++ code block |
| `conversations[1].from` | str | Always `"gpt"` |
| `conversations[1].value` | str | Structured vulnerability analysis |
| `source` | str | Always `"code_vulnerability_cwe"` |
| `score` | float | Quality score (4.8) |

---

## 🔄 Preprocessing Pipeline

### Step 1 — Load
Load the source dataset from Hugging Face Hub
(`ChamaraVishwajithRajapaksha/Code-Vulnerability-FineTune`).

### Step 2 — Separate by Label
Split all rows into two groups:
- **Vulnerable** samples
- **Safe** (patched) samples

### Step 3 — Balance
Undersample the larger group so that both groups have an equal number of rows,
resulting in a 50/50 class distribution.

### Step 4 — Shuffle
Combine the two balanced groups and shuffle the entire dataset with a fixed
random seed (42) for reproducibility.

### Step 5 — Split & Push
- 90% / 10% train-test split (random seed 42)
- Pushed to Hugging Face Hub in Parquet format

---

## 📋 CWE Categories Covered

The dataset covers a wide range of Common Weakness Enumeration types including:

| CWE ID | Vulnerability Type |
|---|---|
| CWE-787 | Out-of-bounds Write |
| CWE-416 | Use After Free |
| CWE-125 | Out-of-bounds Read |
| CWE-476 | NULL Pointer Dereference |
| CWE-119 | Improper Buffer Restriction |
| CWE-284 | Improper Access Control |
| CWE-20 | Improper Input Validation |
| CWE-78 | OS Command Injection |
| CWE-327 | Broken Cryptographic Algorithm |
| CWE-835 | Infinite Loop |
| CWE-122 | Heap-based Buffer Overflow |
| CWE-362 | Race Condition |
| CWE-22 | Path Traversal |
| CWE-287 | Improper Authentication |
| CWE-319 | Cleartext Transmission |
| ... | 30+ more CWE types |

---

## 🧪 Sample Example

### Human Turn

```
Analyze the following code snippet and identify any security vulnerabilities.
Provide a detailed explanation of the vulnerability type, its severity,
potential impact, and the CWE classification.

static boolean ReadICCProfile(j_decompress_ptr jpeg_info) {
  char magick[12];
  ErrorManager *error_manager;
  ExceptionInfo *exception;
  Image *image;
  ...
}
```

### Assistant Turn

```markdown
## Security Vulnerability Analysis

⚠️ This code sample is marked as **Vulnerable**.

### 🔍 Vulnerability Classification
- **CWE ID**: CWE-416
- **Type**: Use After Free
- **Severity**: High
- **Category**: Memory Corruption
- **Affected Languages**: C, C++

### 📋 Description
The product reuses or references memory after it has been freed. At some point
afterward, the memory may be allocated again and saved in another pointer, while
the original pointer references a location somewhere within the new allocation.

### 💥 Potential Impact
  - Execute Unauthorized Code or Commands
  - Read Memory
  - Modify Memory
  - DoS: Crash, Exit, or Restart

### 🛡️ Recommendation
Review the code for Use After Free patterns. Ensure proper bounds checking,
input validation, and memory management practices are applied as recommended
by the CWE guidelines for CWE-416.
```

---

## 🚀 Usage

### Load with 🤗 Datasets

```python
from datasets import load_dataset

dataset = load_dataset("ChamaraVishwajithRajapaksha/Code-Vulnerability-Balanced")
print(dataset)
# DatasetDict({
#     train: Dataset({features: ['conversations', 'source', 'score'], num_rows: ...}),
#     test:  Dataset({features: ['conversations', 'source', 'score'], num_rows: ...})
# })
```

### Access a Sample

```python
sample = dataset['train'][0]

# Print the human question (code to analyze)
print(sample['conversations'][0]['value'])

# Print the assistant answer (vulnerability analysis)
print(sample['conversations'][1]['value'])
```

### Fine-tuning with Unsloth / TRL

```python
from trl import SFTTrainer
from unsloth import FastLanguageModel

# The dataset is already in ShareGPT format — compatible with
# most fine-tuning frameworks that support conversation datasets.
trainer = SFTTrainer(
    model=model,
    tokenizer=tokenizer,
    train_dataset=dataset['train'],
    dataset_text_field="conversations",  # adjust per framework
    ...
)
```

---

## 📁 Dataset Lineage

```
bstee615/diversevul
    └──> ChamaraVishwajithRajapaksha/Code_Vulnerability_Dataset
              (330k rows, CWE-enriched via MITRE API)
         └──> ChamaraVishwajithRajapaksha/Code-Vulnerability-FineTune
                   (ShareGPT format, unbalanced, unshuffled)
              └──> ChamaraVishwajithRajapaksha/Code-Vulnerability-Balanced
                        (balanced + shuffled — this dataset)
```

---

## ⚠️ Limitations

- Code samples are primarily in C and C++ — limited coverage of other languages
- Balancing is achieved by **undersampling** the majority class, so total row count is reduced compared to the source dataset
- The Safe samples represent patched/fixed versions, not inherently safe code — context matters
- CWE details describe the class of vulnerability, not a precise analysis of each individual function
- This dataset is intended for research and educational purposes

---

## 📜 License

This dataset is released under the **MIT License**, consistent with the source dataset license.

---

## 🙏 Citation

If you use this dataset in your research, please cite the original source and this dataset:

```bibtex
@dataset{code_vulnerability_balanced,
  title        = {Code Vulnerability Balanced: CWE-Enriched Conversation Dataset},
  author       = {ChamaraVishwajithRajapaksha},
  year         = {2025},
  publisher    = {Hugging Face},
  url          = {https://huggingface.co/datasets/ChamaraVishwajithRajapaksha/Code-Vulnerability-Balanced},
  note         = {Balanced and shuffled version of Code-Vulnerability-FineTune, in ShareGPT format}
}
```

---

## 🔗 Related Resources

- [MITRE CWE Database](https://cwe.mitre.org/)
- [DiverseVul Paper](https://github.com/bstee615/diversevul)
- [Source: Code-Vulnerability-FineTune](https://huggingface.co/datasets/ChamaraVishwajithRajapaksha/Code-Vulnerability-FineTune)
- [FineTome-100k Format Reference](https://huggingface.co/datasets/mlabonne/FineTome-100k)
- [Unsloth Fine-tuning](https://github.com/unslothai/unsloth)
- [TRL SFTTrainer](https://huggingface.co/docs/trl/sft_trainer)