jacobmahon commited on
Commit
e664669
·
verified ·
1 Parent(s): d670e1a

Add training script for zero-day exploit scanner & fixer model

Browse files
Files changed (1) hide show
  1. train.py +455 -0
train.py ADDED
@@ -0,0 +1,455 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Zero-Day Exploit Scanner & Fixer Model
3
+ =======================================
4
+ Fine-tunes Qwen2.5-Coder-7B-Instruct on vulnerability detection + repair data
5
+ using SFT with QLoRA (4-bit quantization).
6
+
7
+ Datasets: MegaVul (C/C++ CVE pairs) + TitanVul (multi-lang) + CleanVul (filtered)
8
+ Base model: Qwen/Qwen2.5-Coder-7B-Instruct
9
+ Method: QLoRA SFT with structured instruction format
10
+
11
+ References:
12
+ - R2Vul (arxiv:2504.04699): structured reasoning for vuln detection
13
+ - MSIVD (arxiv:2406.05892): multi-task instruction tuning
14
+ - SecRepair (arxiv:2401.03374): combined detection + repair
15
+ - SecureCode: QLoRA r=16, alpha=32, lr=2e-4, 3 epochs
16
+
17
+ Usage:
18
+ pip install transformers trl torch datasets trackio accelerate peft bitsandbytes
19
+ python train.py
20
+
21
+ Hardware: Requires GPU with 24GB+ VRAM (A10G, A100, etc.)
22
+ Estimated time: ~6-8 hours on A10G for 3 epochs on ~90K samples
23
+ """
24
+
25
+ import os
26
+ import torch
27
+ import trackio
28
+ from datasets import load_dataset, concatenate_datasets, Dataset
29
+ from peft import LoraConfig
30
+ from trl import SFTTrainer, SFTConfig
31
+ from transformers import BitsAndBytesConfig
32
+
33
+ # ============================================================================
34
+ # Configuration
35
+ # ============================================================================
36
+ MODEL_NAME = "Qwen/Qwen2.5-Coder-7B-Instruct"
37
+ OUTPUT_DIR = "./vuln-scanner-fixer"
38
+ HUB_MODEL_ID = "jacobmahon/zero-day-exploit-scanner-fixer"
39
+
40
+ # Training hyperparameters (paper-backed from SecureCode + SecRepair + MSIVD)
41
+ LEARNING_RATE = 2e-4 # Higher LR for LoRA (SecureCode: 2e-4)
42
+ NUM_EPOCHS = 3 # SecureCode: 3 epochs
43
+ BATCH_SIZE = 2 # Per device
44
+ GRAD_ACCUM = 8 # Effective batch = 16
45
+ MAX_LENGTH = 2048 # Vuln functions can be long
46
+ WARMUP_STEPS = 100
47
+ LORA_R = 16 # SecureCode: rank=16
48
+ LORA_ALPHA = 32 # SecureCode: alpha=32
49
+ LORA_DROPOUT = 0.05
50
+
51
+ # ============================================================================
52
+ # Trackio Monitoring
53
+ # ============================================================================
54
+ trackio.init(
55
+ project="zero-day-exploit-scanner",
56
+ name="qwen2.5-coder-7b-vulnfix-qlora",
57
+ )
58
+
59
+ # ============================================================================
60
+ # Dataset Preparation
61
+ # ============================================================================
62
+ print("=" * 60)
63
+ print("Loading datasets...")
64
+ print("=" * 60)
65
+
66
+ # 1. MegaVul - C/C++ vulnerability pairs with CVE/CWE labels (17K)
67
+ megavul = load_dataset("hitoshura25/megavul", split="train")
68
+ print(f"MegaVul: {len(megavul)} samples")
69
+
70
+ # 2. TitanVul - Multi-language aggregated vulnerability pairs (38K)
71
+ titanvul = load_dataset("yikun-li/TitanVul", split="train")
72
+ print(f"TitanVul: {len(titanvul)} samples")
73
+
74
+ # 3. CleanVul - Filtered high-quality vulnerability pairs
75
+ cleanvul = load_dataset("yikun-li/CleanVul", split="train")
76
+ print(f"CleanVul raw: {len(cleanvul)} samples")
77
+
78
+ # Filter CleanVul: score >= 1 means likely real vulnerability fix
79
+ cleanvul = cleanvul.filter(lambda x: x["vulnerability_score"] is not None and x["vulnerability_score"] >= 1)
80
+ print(f"CleanVul filtered (score >= 1): {len(cleanvul)} samples")
81
+
82
+ # ============================================================================
83
+ # Format datasets into unified instruction format
84
+ # ============================================================================
85
+
86
+ SYSTEM_PROMPT = """You are a world-class security expert specializing in zero-day vulnerability detection and remediation. When given code, you will:
87
+ 1. SCAN: Determine if the code contains a security vulnerability
88
+ 2. IDENTIFY: If vulnerable, identify the CWE type and CVE ID if known
89
+ 3. EXPLAIN: Provide a clear explanation of the vulnerability mechanism, attack vector, and potential impact
90
+ 4. FIX: Provide the corrected code that patches the vulnerability
91
+
92
+ Always respond in the following structured format:
93
+ ## SCAN RESULT
94
+ [VULNERABLE / SAFE]
95
+
96
+ ## VULNERABILITY DETAILS
97
+ - **CWE**: [CWE ID and name]
98
+ - **CVE**: [CVE ID if known, otherwise "N/A"]
99
+ - **Severity**: [CRITICAL / HIGH / MEDIUM / LOW]
100
+
101
+ ## EXPLANATION
102
+ [Detailed explanation of the vulnerability]
103
+
104
+ ## VULNERABLE LINES
105
+ [Specific lines or patterns that are vulnerable]
106
+
107
+ ## FIXED CODE
108
+ ```
109
+ [Corrected code]
110
+ ```
111
+
112
+ ## FIX EXPLANATION
113
+ [What was changed and why]"""
114
+
115
+
116
+ def format_megavul(example):
117
+ """Format MegaVul samples into instruction format."""
118
+ vuln_code = example.get("vulnerable_code")
119
+ fixed_code = example.get("fixed_code")
120
+ cwe_id = example.get("cwe_id", "Unknown")
121
+ cve_id = example.get("cve_id", "N/A")
122
+ cve_desc = example.get("cve_description", "")
123
+ commit_msg = example.get("commit_message", "")
124
+ language = example.get("language", "C")
125
+
126
+ if not vuln_code or not fixed_code:
127
+ return {"messages": None}
128
+
129
+ explanation = cve_desc if cve_desc else commit_msg
130
+ if not explanation:
131
+ explanation = f"Security vulnerability identified as {cwe_id}"
132
+
133
+ assistant_response = f"""## SCAN RESULT
134
+ VULNERABLE
135
+
136
+ ## VULNERABILITY DETAILS
137
+ - **CWE**: {cwe_id}
138
+ - **CVE**: {cve_id}
139
+ - **Severity**: HIGH
140
+
141
+ ## EXPLANATION
142
+ {explanation}
143
+
144
+ ## FIX EXPLANATION
145
+ {commit_msg if commit_msg else "Applied security patch to remediate the vulnerability."}
146
+
147
+ ## FIXED CODE
148
+ ```{language.lower()}
149
+ {fixed_code}
150
+ ```"""
151
+
152
+ messages = [
153
+ {"role": "system", "content": SYSTEM_PROMPT},
154
+ {"role": "user", "content": f"Analyze the following {language} code for security vulnerabilities and provide a fix if needed:\n\n```{language.lower()}\n{vuln_code}\n```"},
155
+ {"role": "assistant", "content": assistant_response},
156
+ ]
157
+
158
+ return {"messages": messages}
159
+
160
+
161
+ def format_titanvul(example):
162
+ """Format TitanVul samples into instruction format."""
163
+ func_before = example.get("func_before")
164
+ func_after = example.get("func_after")
165
+ cwe_id = example.get("cwe_id", "Unknown")
166
+ cve_id = example.get("cve_id", "N/A")
167
+ cve_desc = example.get("cve_description", "")
168
+ commit_msg = example.get("commit_message", "")
169
+ extension = example.get("extension", "")
170
+
171
+ if not func_before or not func_after:
172
+ return {"messages": None}
173
+
174
+ lang_map = {"c": "C", "cpp": "C++", "h": "C", "java": "Java",
175
+ "py": "Python", "js": "JavaScript", "ts": "TypeScript",
176
+ "rb": "Ruby", "go": "Go", "rs": "Rust", "php": "PHP"}
177
+ language = lang_map.get(extension, extension if extension else "code")
178
+
179
+ explanation = cve_desc if cve_desc else commit_msg
180
+ if not explanation:
181
+ explanation = f"Security vulnerability identified as {cwe_id}" if cwe_id else "Security vulnerability detected in code"
182
+
183
+ cwe_display = cwe_id if cwe_id else "Unknown"
184
+ cve_display = cve_id if cve_id else "N/A"
185
+
186
+ assistant_response = f"""## SCAN RESULT
187
+ VULNERABLE
188
+
189
+ ## VULNERABILITY DETAILS
190
+ - **CWE**: {cwe_display}
191
+ - **CVE**: {cve_display}
192
+ - **Severity**: HIGH
193
+
194
+ ## EXPLANATION
195
+ {explanation}
196
+
197
+ ## FIX EXPLANATION
198
+ {commit_msg if commit_msg else "Applied security patch to remediate the vulnerability."}
199
+
200
+ ## FIXED CODE
201
+ ```{language.lower()}
202
+ {func_after}
203
+ ```"""
204
+
205
+ messages = [
206
+ {"role": "system", "content": SYSTEM_PROMPT},
207
+ {"role": "user", "content": f"Analyze the following {language} code for security vulnerabilities and provide a fix if needed:\n\n```{language.lower()}\n{func_before}\n```"},
208
+ {"role": "assistant", "content": assistant_response},
209
+ ]
210
+
211
+ return {"messages": messages}
212
+
213
+
214
+ def format_cleanvul(example):
215
+ """Format CleanVul samples into instruction format."""
216
+ func_before = example.get("func_before")
217
+ func_after = example.get("func_after")
218
+ cwe_id = example.get("cwe_id")
219
+ cve_id = example.get("cve_id", "N/A")
220
+ commit_msg = example.get("commit_msg", "")
221
+ extension = example.get("extension", "")
222
+
223
+ if not func_before or not func_after:
224
+ return {"messages": None}
225
+
226
+ lang_map = {"c": "C", "cpp": "C++", "h": "C", "java": "Java",
227
+ "py": "Python", "js": "JavaScript", "ts": "TypeScript",
228
+ "rb": "Ruby", "go": "Go", "rs": "Rust", "php": "PHP"}
229
+ language = lang_map.get(extension, extension if extension else "code")
230
+
231
+ if isinstance(cwe_id, list) and len(cwe_id) > 0:
232
+ cwe_display = ", ".join(cwe_id)
233
+ elif cwe_id:
234
+ cwe_display = str(cwe_id)
235
+ else:
236
+ cwe_display = "Unknown"
237
+
238
+ cve_display = cve_id if cve_id else "N/A"
239
+
240
+ explanation = commit_msg if commit_msg else f"Security vulnerability ({cwe_display}) detected and patched."
241
+
242
+ assistant_response = f"""## SCAN RESULT
243
+ VULNERABLE
244
+
245
+ ## VULNERABILITY DETAILS
246
+ - **CWE**: {cwe_display}
247
+ - **CVE**: {cve_display}
248
+ - **Severity**: HIGH
249
+
250
+ ## EXPLANATION
251
+ {explanation}
252
+
253
+ ## FIX EXPLANATION
254
+ {commit_msg if commit_msg else "Applied security patch to remediate the vulnerability."}
255
+
256
+ ## FIXED CODE
257
+ ```{language.lower()}
258
+ {func_after}
259
+ ```"""
260
+
261
+ messages = [
262
+ {"role": "system", "content": SYSTEM_PROMPT},
263
+ {"role": "user", "content": f"Analyze the following {language} code for security vulnerabilities and provide a fix if needed:\n\n```{language.lower()}\n{func_before}\n```"},
264
+ {"role": "assistant", "content": assistant_response},
265
+ ]
266
+
267
+ return {"messages": messages}
268
+
269
+
270
+ print("\nFormatting datasets into instruction format...")
271
+
272
+ megavul_formatted = megavul.map(format_megavul, remove_columns=megavul.column_names, num_proc=4)
273
+ megavul_formatted = megavul_formatted.filter(lambda x: x["messages"] is not None)
274
+ print(f"MegaVul formatted: {len(megavul_formatted)} samples")
275
+
276
+ titanvul_formatted = titanvul.map(format_titanvul, remove_columns=titanvul.column_names, num_proc=4)
277
+ titanvul_formatted = titanvul_formatted.filter(lambda x: x["messages"] is not None)
278
+ print(f"TitanVul formatted: {len(titanvul_formatted)} samples")
279
+
280
+ cleanvul_formatted = cleanvul.map(format_cleanvul, remove_columns=cleanvul.column_names, num_proc=4)
281
+ cleanvul_formatted = cleanvul_formatted.filter(lambda x: x["messages"] is not None)
282
+ print(f"CleanVul formatted: {len(cleanvul_formatted)} samples")
283
+
284
+ # Combine all datasets
285
+ combined = concatenate_datasets([megavul_formatted, titanvul_formatted, cleanvul_formatted])
286
+ combined = combined.shuffle(seed=42)
287
+ print(f"\nTotal combined dataset: {len(combined)} samples")
288
+
289
+ # ============================================================================
290
+ # Add SAFE code examples to reduce false positives
291
+ # ============================================================================
292
+ print("\nCreating safe code examples (negative samples)...")
293
+
294
+
295
+ def create_safe_sample(example):
296
+ """Use fixed code as safe example to reduce false positives."""
297
+ func_after = example.get("func_after")
298
+ extension = example.get("extension", "")
299
+
300
+ if not func_after:
301
+ return {"messages": None}
302
+
303
+ lang_map = {"c": "C", "cpp": "C++", "h": "C", "java": "Java",
304
+ "py": "Python", "js": "JavaScript", "ts": "TypeScript",
305
+ "rb": "Ruby", "go": "Go", "rs": "Rust", "php": "PHP"}
306
+ language = lang_map.get(extension, extension if extension else "code")
307
+
308
+ assistant_response = """## SCAN RESULT
309
+ SAFE
310
+
311
+ ## VULNERABILITY DETAILS
312
+ No security vulnerabilities detected in this code.
313
+
314
+ ## EXPLANATION
315
+ The code follows secure coding practices. No known vulnerability patterns (buffer overflows, injection flaws, authentication bypasses, race conditions, etc.) were identified in this code segment."""
316
+
317
+ messages = [
318
+ {"role": "system", "content": SYSTEM_PROMPT},
319
+ {"role": "user", "content": f"Analyze the following {language} code for security vulnerabilities and provide a fix if needed:\n\n```{language.lower()}\n{func_after}\n```"},
320
+ {"role": "assistant", "content": assistant_response},
321
+ ]
322
+
323
+ return {"messages": messages}
324
+
325
+
326
+ # Take subset of TitanVul fixed code as safe examples (~15% of vulnerable samples)
327
+ safe_subset = titanvul.shuffle(seed=123).select(range(min(12000, len(titanvul))))
328
+ safe_formatted = safe_subset.map(create_safe_sample, remove_columns=titanvul.column_names, num_proc=4)
329
+ safe_formatted = safe_formatted.filter(lambda x: x["messages"] is not None)
330
+ print(f"Safe (negative) samples: {len(safe_formatted)}")
331
+
332
+ # Combine all data
333
+ all_data = concatenate_datasets([combined, safe_formatted]).shuffle(seed=42)
334
+ print(f"Total dataset (vuln + safe): {len(all_data)} samples")
335
+
336
+ # Create train/eval split (95/5)
337
+ split = all_data.train_test_split(test_size=0.05, seed=42)
338
+ train_dataset = split["train"]
339
+ eval_dataset = split["test"]
340
+ print(f"Train: {len(train_dataset)}, Eval: {len(eval_dataset)}")
341
+
342
+ # ============================================================================
343
+ # Model + QLoRA Setup
344
+ # ============================================================================
345
+ print("\n" + "=" * 60)
346
+ print("Setting up model with QLoRA...")
347
+ print("=" * 60)
348
+
349
+ bnb_config = BitsAndBytesConfig(
350
+ load_in_4bit=True,
351
+ bnb_4bit_use_double_quant=True,
352
+ bnb_4bit_quant_type="nf4",
353
+ bnb_4bit_compute_dtype=torch.bfloat16,
354
+ )
355
+
356
+ peft_config = LoraConfig(
357
+ r=LORA_R,
358
+ lora_alpha=LORA_ALPHA,
359
+ lora_dropout=LORA_DROPOUT,
360
+ bias="none",
361
+ task_type="CAUSAL_LM",
362
+ target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
363
+ )
364
+
365
+ # ============================================================================
366
+ # Training Configuration
367
+ # ============================================================================
368
+ training_args = SFTConfig(
369
+ output_dir=OUTPUT_DIR,
370
+ hub_model_id=HUB_MODEL_ID,
371
+ push_to_hub=True,
372
+
373
+ # Training hyperparameters
374
+ num_train_epochs=NUM_EPOCHS,
375
+ per_device_train_batch_size=BATCH_SIZE,
376
+ per_device_eval_batch_size=BATCH_SIZE,
377
+ gradient_accumulation_steps=GRAD_ACCUM,
378
+ learning_rate=LEARNING_RATE,
379
+ lr_scheduler_type="cosine",
380
+ warmup_steps=WARMUP_STEPS,
381
+
382
+ # Precision & memory
383
+ bf16=True,
384
+ gradient_checkpointing=True,
385
+ max_length=MAX_LENGTH,
386
+
387
+ # Logging
388
+ logging_steps=10,
389
+ logging_first_step=True,
390
+ disable_tqdm=True,
391
+ report_to="none",
392
+
393
+ # Evaluation
394
+ eval_strategy="steps",
395
+ eval_steps=500,
396
+
397
+ # Saving
398
+ save_strategy="steps",
399
+ save_steps=500,
400
+ save_total_limit=3,
401
+ load_best_model_at_end=True,
402
+ metric_for_best_model="eval_loss",
403
+
404
+ # SFT specific
405
+ packing=False,
406
+ assistant_only_loss=True,
407
+
408
+ # Model loading kwargs
409
+ model_init_kwargs={
410
+ "quantization_config": bnb_config,
411
+ "torch_dtype": torch.bfloat16,
412
+ "attn_implementation": "eager",
413
+ },
414
+ )
415
+
416
+ # ============================================================================
417
+ # Initialize Trainer
418
+ # ============================================================================
419
+ print("Initializing SFTTrainer...")
420
+
421
+ trainer = SFTTrainer(
422
+ model=MODEL_NAME,
423
+ args=training_args,
424
+ train_dataset=train_dataset,
425
+ eval_dataset=eval_dataset,
426
+ peft_config=peft_config,
427
+ )
428
+
429
+ print(f"Model parameters: {trainer.model.num_parameters():,}")
430
+ print(f"Trainable parameters: {sum(p.numel() for p in trainer.model.parameters() if p.requires_grad):,}")
431
+
432
+ # ============================================================================
433
+ # Train!
434
+ # ============================================================================
435
+ print("\n" + "=" * 60)
436
+ print("Starting training...")
437
+ print("=" * 60)
438
+
439
+ trainer.train()
440
+
441
+ # ============================================================================
442
+ # Save & Push to Hub
443
+ # ============================================================================
444
+ print("\n" + "=" * 60)
445
+ print("Saving model and pushing to Hub...")
446
+ print("=" * 60)
447
+
448
+ trainer.save_model()
449
+ trainer.push_to_hub(commit_message="Train zero-day exploit scanner & fixer (QLoRA on Qwen2.5-Coder-7B)")
450
+
451
+ print("\n" + "=" * 60)
452
+ print(f"Model saved to Hub: https://huggingface.co/{HUB_MODEL_ID}")
453
+ print("=" * 60)
454
+
455
+ trackio.log({"status": "training_complete"})