CoolFace
Datasetpublic

ChamaraVishwajithRajapaksha/Code-Vulnerability-Balanced

Code Vulnerability Balanced β€” CWE-Enriched Conversation Dataset πŸ“Œ Overview This dataset is a balanced and shuffled version of ChamaraVishwajithRajapaksha/Code-Vulnerability-FineTune, which itself was derived from the original 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… See the full description on the dataset page: https://huggingface.co/datasets/ChamaraVishwajithRajapaksha/Code-Vulnerability-Balanced.

sourceHugging Facemitupdated 5mo agoView on Hugging Face
0likes58downloads
Dataset Card

Code Vulnerability Balanced β€” CWE-Enriched Conversation Dataset

πŸ“Œ Overview

This dataset is a balanced and shuffled version of ChamaraVishwajithRajapaksha/Code-Vulnerability-FineTune, which itself was derived from the original 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

PropertyValue
Source DatasetChamaraVishwajithRajapaksha/Code-Vulnerability-FineTune
Balancing StrategyUndersample majority class to match minority class
ShuffledYes (random seed 42)
FormatShareGPT (conversations)
LanguagesC, C++
Splitstrain (90%) Β· test (10%)
LicenseMIT

πŸ”„ What Changed From the Source Dataset

ChangeDescription
BalancingThe source dataset had an unequal number of Vulnerable vs Safe samples. This dataset undersamples the majority class so both are equal in count.
ShufflingAll rows are randomly shuffled (seed 42) before splitting, preventing the model from learning ordering patterns.
Same formatThe 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

FieldTypeDescription
conversationslistList of 2 conversation turns
conversations[0].fromstrAlways "human"
conversations[0].valuestrInstruction + C/C++ code block
conversations[1].fromstrAlways "gpt"
conversations[1].valuestrStructured vulnerability analysis
sourcestrAlways "code_vulnerability_cwe"
scorefloatQuality 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 IDVulnerability Type
CWE-787Out-of-bounds Write
CWE-416Use After Free
CWE-125Out-of-bounds Read
CWE-476NULL Pointer Dereference
CWE-119Improper Buffer Restriction
CWE-284Improper Access Control
CWE-20Improper Input Validation
CWE-78OS Command Injection
CWE-327Broken Cryptographic Algorithm
CWE-835Infinite Loop
CWE-122Heap-based Buffer Overflow
CWE-362Race Condition
CWE-22Path Traversal
CWE-287Improper Authentication
CWE-319Cleartext 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