Team Ai
Modelpublic

codelion/Qwen2.5-Coder-0.5B-Instruct-security-grpo-lora

sourceHugging Faceapache-2.0updated 1y agoView on Hugging Face
0likes52downloads
Model Card

codelion/Qwen2.5-Coder-0.5B-Instruct-security-grpo-lora

๐Ÿ” Security-First Code Generation LoRA

This LoRA adapter enhances Qwen/Qwen2.5-Coder-0.5B-Instruct to generate secure code by default, trained using GRPO (Group Relative Policy Optimization) with automated security analysis via Semgrep.

๐ŸŽฏ Key Features

  • โ€”Automated Security Analysis: Uses Semgrep for consistent vulnerability detection
  • โ€”Self-Supervised Training: No manually curated secure/insecure datasets required
  • โ€”Comprehensive Coverage: Addresses OWASP Top 10 and CWE Top 25 vulnerabilities
  • โ€”Language Focus: Specialized for Python security patterns
  • โ€”Preference Learning: GRPO training to prefer secure coding patterns

๐Ÿ“Š Performance Metrics

  • โ€”Base Model: Qwen/Qwen2.5-Coder-0.5B-Instruct
  • โ€”Training Method: GRPO with security-based preferences
  • โ€”LoRA Rank: 64
  • โ€”LoRA Alpha: 128
  • โ€”Training Samples: 195
  • โ€”Security Evaluation Pass Rate: 20.0%
  • โ€”Average Security Score: 0.40 (lower is better)

Vulnerability Prevention Results

Vulnerability TypeScoreStatus
SQL Injection0โœ…
Command Injection0โœ…
Path Traversal2โœ…
Weak Cryptography0โœ…
Hardcoded Secrets0โœ…

๐Ÿ”ง Usage

python
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import PeftModel

# Load base model
model = AutoModelForCausalLM.from_pretrained(
    "Qwen/Qwen2.5-Coder-0.5B-Instruct",
    torch_dtype="auto",
    device_map="auto"
)
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-Coder-0.5B-Instruct")

# Load security LoRA adapter
model = PeftModel.from_pretrained(model, "codelion/Qwen2.5-Coder-0.5B-Instruct-security-grpo-lora")

# Generate secure code
prompt = '''Write a secure Python function: Create a user login function
that checks username and password against a database'''

inputs = tokenizer(prompt, return_tensors="pt")
outputs = model.generate(**inputs, max_new_tokens=512, temperature=0.2)
secure_code = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(secure_code)

๐Ÿ“ˆ Expected Output

The model generates code with security best practices:

python
def login_user(username, password):
    """Securely authenticate a user against the database."""
    import bcrypt
    import secrets
    from sqlalchemy import text

    # Validate inputs
    if not username or not password:
        return False, "Invalid credentials"

    # Use parameterized query to prevent SQL injection
    query = text("SELECT user_id, password_hash FROM users WHERE username = :username")
    result = db.execute(query, {"username": username}).fetchone()

    if not result:
        # Prevent timing attacks by still checking a dummy password
        bcrypt.checkpw(b"dummy", b"$2b$12$dummy.hash.to.prevent.timing")
        return False, "Invalid credentials"

    # Verify password using bcrypt
    if bcrypt.checkpw(password.encode('utf-8'), result.password_hash):
        # Generate secure session token
        session_token = secrets.token_urlsafe(32)
        return True, session_token

    return False, "Invalid credentials"

๐Ÿ›ก๏ธ Security Patterns Learned

  • โ€”SQL Injection Prevention: Parameterized queries, prepared statements
  • โ€”Password Security: Bcrypt/Argon2 hashing, no plaintext storage
  • โ€”Input Validation: Comprehensive validation and sanitization
  • โ€”Error Handling: Safe error messages without information disclosure
  • โ€”Secure Randomness: Using secrets module instead of random
  • โ€”Path Security: Proper path joining and validation
  • โ€”Command Injection Prevention: Avoiding shell=True, using subprocess safely

๐Ÿงช Training Details

Data Generation

  • โ€”Method: Self-supervised with Magpie-style generation
  • โ€”Scenarios: 7 security categories
  • โ€”Analysis: Automated using Semgrep security rules
  • โ€”Preference Pairs: Based on security score differences

GRPO Training

  • โ€”Objective: Minimize security vulnerabilities while maintaining functionality
  • โ€”Reward Signal: Negative correlation with Semgrep security score
  • โ€”Batch Size: 1 with 8x gradient accumulation
  • โ€”Learning Rate: 3e-06
  • โ€”Epochs: 5

๐Ÿ“š Evaluation

The adapter was evaluated on comprehensive security test cases:

  • โ€”CWE Coverage: Top 25 most dangerous software weaknesses
  • โ€”OWASP Alignment: Addresses OWASP Top 10 vulnerabilities
  • โ€”Practical Scenarios: Real-world security challenges
  • โ€”Pattern Recognition: Identifies and applies secure coding patterns

๐Ÿ” Limitations and Considerations

  1. 1.Language Focus: Currently optimized for Python; other languages may need additional training
  2. 2.Context Awareness: Best results with clear security-focused prompts
  3. 3.Not a Security Scanner: Complements but doesn't replace security tools
  4. 4.Continuous Updates: Security landscape evolves; periodic retraining recommended

๐Ÿ”— Related Resources


This adapter is part of the [Ellora project](https://github.com/codelion/ellora) - standardized recipes for enhancing LLM capabilities.