File size: 13,190 Bytes
3d6a9e6 dc0b1ad 3d6a9e6 dc0b1ad 3d6a9e6 dc0b1ad 3d6a9e6 dc0b1ad 3d6a9e6 dc0b1ad 3d6a9e6 dc0b1ad 3d6a9e6 | 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 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 | {
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# π Multi-Model Ethical Hacking Fine-Tuning β Pick Your Model\n",
"\n",
"This notebook lets you choose between multiple models for cybersecurity fine-tuning on Google Colab Free Tier (T4 GPU, ~16GB VRAM).\n",
"\n",
"**All models tested with Unsloth for 2Γ faster training + 70% less VRAM.**\n",
"\n",
"---\n",
"\n",
"## π Model Comparison Matrix (T4 16GB)\n",
"\n",
"| Model | 4-bit Size | T4 Fit | Coding Score | Unsloth | β
/β | Why |\n",
"|-------|-----------|--------|-------------|---------|------|-----|\n",
"| **Qwen3-4B-Instruct-2507** π₯ | 3.3 GB | β
β
β
Excellent | LiveCodeBench 35.1 | β
Confirmed | β
**USE THIS** | Best coding/reasoning under 10B |\n",
"| Qwen3-8B | 7.0 GB | β
β
Good | Strong base | β
Confirmed | β
Viable | More capacity, tighter VRAM |\n",
"| Gemma-3-4B-it | ~2.5 GB | β
β
β
Excellent | Decent | β
Confirmed | β
Alternative | Good for multimodal tasks |\n",
"| Gemma-4-E2B-it | ~7.6 GB | β
β
Good | Unverified | β οΈ Limited | β οΈ Experimental | Very new, may have issues |\n",
"| Bonsai-4B | ~0.5 GB | β
β
β
Excellent | Weak (~30% MMLU) | β No | β **AVOID** | Ternary weights, NOT for coding |\n",
"| LFM2-2.6B | ~2.5 GB | β
β
Good | **Not for programming** | β No | β **AVOID** | Officially disclaimed by Liquid AI |\n",
"\n",
"---\n",
"\n",
"## π― Quick Pick\n",
"\n",
"```python\n",
"MODEL_CHOICE = \"qwen3-4b\" # Options: qwen3-4b | qwen3-8b | gemma-3-4b\n",
"```\n",
"\n",
"> β οΈ **Disclaimer:** This trains on **defensive cybersecurity** datasets only. For ethical hacking education and security research."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1οΈβ£ Install Dependencies"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%%capture\n",
"!pip install -q unsloth trl datasets accelerate transformers bitsandbytes huggingface_hub"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 2οΈβ£ Choose Your Model (Edit This Cell)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# ======================== PICK YOUR MODEL ========================\n",
"MODEL_CHOICE = \"qwen3-4b\" # Change this to: \"qwen3-4b\" | \"qwen3-8b\" | \"gemma-3-4b\"\n",
"# ================================================================\n",
"\n",
"MODEL_CONFIGS = {\n",
" \"qwen3-4b\": {\n",
" \"name\": \"unsloth/Qwen3-4B-Instruct-2507-unsloth-bnb-4bit\",\n",
" \"max_seq_length\": 4096,\n",
" \"lora_r\": 64,\n",
" \"lora_alpha\": 64,\n",
" \"batch_size\": 2,\n",
" \"grad_accum\": 4,\n",
" \"description\": \"Best coding/reasoning under 10B. Massive VRAM headroom on T4.\",\n",
" },\n",
" \"qwen3-8b\": {\n",
" \"name\": \"unsloth/Qwen3-8B-unsloth-bnb-4bit\",\n",
" \"max_seq_length\": 2048,\n",
" \"lora_r\": 16,\n",
" \"lora_alpha\": 16,\n",
" \"batch_size\": 1,\n",
" \"grad_accum\": 4,\n",
" \"description\": \"More capacity for complex exploits. Tighter VRAM on T4.\",\n",
" },\n",
" \"gemma-3-4b\": {\n",
" \"name\": \"unsloth/gemma-3-4b-it-unsloth-bnb-4bit\",\n",
" \"max_seq_length\": 2048,\n",
" \"lora_r\": 32,\n",
" \"lora_alpha\": 32,\n",
" \"batch_size\": 2,\n",
" \"grad_accum\": 4,\n",
" \"description\": \"Google's Gemma 3. Good alternative with different tokenizer.\",\n",
" },\n",
"}\n",
"\n",
"cfg = MODEL_CONFIGS[MODEL_CHOICE]\n",
"print(f\"π― Model: {MODEL_CHOICE}\")\n",
"print(f\" HF ID: {cfg['name']}\")\n",
"print(f\" {cfg['description']}\")\n",
"print(f\" MAX_SEQ_LENGTH={cfg['max_seq_length']}, LoRA r={cfg['lora_r']}, batch={cfg['batch_size']}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3οΈβ£ Load Model with Unsloth"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from unsloth import FastLanguageModel\n",
"import torch\n",
"\n",
"MAX_SEQ_LENGTH = cfg[\"max_seq_length\"]\n",
"LORA_R = cfg[\"lora_r\"]\n",
"LORA_ALPHA = cfg[\"lora_alpha\"]\n",
"BATCH_SIZE = cfg[\"batch_size\"]\n",
"GRAD_ACCUM = cfg[\"grad_accum\"]\n",
"LEARNING_RATE = 2e-4\n",
"NUM_EPOCHS = 1\n",
"WARMUP_STEPS = 10\n",
"LOGGING_STEPS = 5\n",
"\n",
"model, tokenizer = FastLanguageModel.from_pretrained(\n",
" model_name=cfg[\"name\"],\n",
" max_seq_length=MAX_SEQ_LENGTH,\n",
" dtype=None, # auto-detect\n",
" load_in_4bit=True,\n",
")\n",
"\n",
"model = FastLanguageModel.get_peft_model(\n",
" model,\n",
" r=LORA_R,\n",
" target_modules=[\"q_proj\", \"k_proj\", \"v_proj\", \"o_proj\",\n",
" \"gate_proj\", \"up_proj\", \"down_proj\"],\n",
" lora_alpha=LORA_ALPHA,\n",
" lora_dropout=0,\n",
" bias=\"none\",\n",
" use_gradient_checkpointing=\"unsloth\",\n",
" random_state=3407,\n",
" use_rslora=False,\n",
")\n",
"\n",
"trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
"total = sum(p.numel() for p in model.parameters())\n",
"print(f\"β
Model loaded. Trainable: {trainable:,} / {total:,} ({100*trainable/total:.2f}%)\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4οΈβ£ Load & Prepare Cybersecurity Datasets\n",
"\n",
"Pre-process to `text` format using chat template. This avoids Unsloth `formatting_func` issues entirely."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from datasets import load_dataset, concatenate_datasets\n",
"\n",
"ds1 = load_dataset(\"AlicanKiraz0/Cybersecurity-Dataset-Fenrir-v2.1\", split=\"train\")\n",
"ds2 = load_dataset(\"Trendyol/Trendyol-Cybersecurity-Instruction-Tuning-Dataset\", split=\"train\")\n",
"\n",
"def to_messages(example):\n",
" return {\"messages\": [\n",
" {\"role\": \"system\", \"content\": example[\"system\"]},\n",
" {\"role\": \"user\", \"content\": example[\"user\"]},\n",
" {\"role\": \"assistant\", \"content\": example[\"assistant\"]},\n",
" ]}\n",
"\n",
"ds1 = ds1.map(to_messages, remove_columns=ds1.column_names, batched=False)\n",
"ds2 = ds2.map(to_messages, remove_columns=ds2.column_names, batched=False)\n",
"train_dataset = concatenate_datasets([ds1, ds2])\n",
"print(f\"β
Messages dataset: {len(train_dataset)} rows\")\n",
"\n",
"# ========== PRE-PROCESS: messages β text with chat template ==========\n",
"def convert_messages_to_text(examples):\n",
" \"\"\"Convert batched messages to formatted text strings.\"\"\"\n",
" texts = []\n",
" for msgs in examples[\"messages\"]:\n",
" text = tokenizer.apply_chat_template(\n",
" msgs,\n",
" tokenize=False,\n",
" add_generation_prompt=False,\n",
" )\n",
" texts.append(text)\n",
" return {\"text\": texts}\n",
"\n",
"print(\"π Converting messages to text with chat template...\")\n",
"train_dataset = train_dataset.map(\n",
" convert_messages_to_text,\n",
" batched=True,\n",
" remove_columns=[\"messages\"],\n",
" batch_size=100,\n",
")\n",
"print(f\"β
Dataset ready with columns: {train_dataset.column_names}\")\n",
"print(f\"π Sample length: {len(train_dataset[0]['text'])} chars\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 5οΈβ£ Configure SFTTrainer (dataset_text_field=\"text\" β no formatting_func!)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from trl import SFTTrainer\n",
"from transformers import TrainingArguments\n",
"\n",
"trainer = SFTTrainer(\n",
" model=model,\n",
" tokenizer=tokenizer,\n",
" train_dataset=train_dataset,\n",
" dataset_text_field=\"text\", # β standard text format, no formatting_func needed!\n",
" max_seq_length=MAX_SEQ_LENGTH,\n",
" dataset_num_proc=2,\n",
" packing=False,\n",
" args=TrainingArguments(\n",
" output_dir=f\"./outputs_{MODEL_CHOICE}\",\n",
" per_device_train_batch_size=BATCH_SIZE,\n",
" gradient_accumulation_steps=GRAD_ACCUM,\n",
" warmup_steps=WARMUP_STEPS,\n",
" num_train_epochs=NUM_EPOCHS,\n",
" learning_rate=LEARNING_RATE,\n",
" fp16=True,\n",
" logging_steps=LOGGING_STEPS,\n",
" optim=\"adamw_8bit\",\n",
" weight_decay=0.01,\n",
" lr_scheduler_type=\"linear\",\n",
" seed=3407,\n",
" save_strategy=\"epoch\",\n",
" report_to=\"none\",\n",
" ),\n",
")\n",
"\n",
"steps_per_epoch = len(train_dataset) // (BATCH_SIZE * GRAD_ACCUM)\n",
"print(f\"β
Trainer ready. Steps per epoch: ~{steps_per_epoch}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 6οΈβ£ Train π"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"if torch.cuda.is_available():\n",
" print(f\"VRAM before: {torch.cuda.memory_allocated()/1e9:.2f} GB / {torch.cuda.get_device_properties(0).total_memory/1e9:.2f} GB\")\n",
"\n",
"trainer_stats = trainer.train()\n",
"print(\"\\nπ Training complete!\")\n",
"print(trainer_stats)\n",
"\n",
"if torch.cuda.is_available():\n",
" print(f\"VRAM after: {torch.cuda.memory_allocated()/1e9:.2f} GB\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 7οΈβ£ Save & Inference"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Save LoRA adapter\n",
"save_path = f\"./cyber-lora-{MODEL_CHOICE}\"\n",
"model.save_pretrained(save_path)\n",
"tokenizer.save_pretrained(save_path)\n",
"print(f\"β
Adapter saved to {save_path}\")\n",
"\n",
"# Quick inference test\n",
"FastLanguageModel.for_inference(model)\n",
"\n",
"test_msgs = [\n",
" {\"role\": \"system\", \"content\": \"You are a cybersecurity expert.\"},\n",
" {\"role\": \"user\", \"content\": \"List the phases of a responsible web app penetration test.\"},\n",
"]\n",
"\n",
"inputs = tokenizer.apply_chat_template(\n",
" test_msgs,\n",
" tokenize=True,\n",
" add_generation_prompt=True,\n",
" return_tensors=\"pt\",\n",
").to(model.device)\n",
"\n",
"outputs = model.generate(\n",
" input_ids=inputs,\n",
" max_new_tokens=256,\n",
" temperature=0.7,\n",
" top_p=0.9,\n",
" do_sample=True,\n",
" pad_token_id=tokenizer.pad_token_id,\n",
" eos_token_id=tokenizer.eos_token_id,\n",
")\n",
"\n",
"response = tokenizer.decode(outputs[0], skip_special_tokens=True)\n",
"reply = response.split(\"assistant\")[-1].strip()[:500]\n",
"print(f\"\\nπ Test Response:\\n{reply}...\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"## π§ Model-Specific Notes\n",
"\n",
"### Qwen3-4B / Qwen3-8B\n",
"- Has `enable_thinking=True/False` toggle for deep vs fast reasoning\n",
"- Best coding scores among sub-10B models\n",
"- Apache 2.0 license\n",
"\n",
"### Gemma-3-4B\n",
"- Google's Gemma 3 series\n",
"- Different tokenizer than Qwen β results may vary\n",
"- Good multimodal capabilities (text + vision)\n",
"\n",
"### β οΈ NOT Recommended\n",
"\n",
"| Model | Why Avoid |\n",
"|-------|-----------|\n",
"| **Bonsai** (prism-ml) | Ternary weights (1-bit), custom architecture, no Unsloth support. MMLU ~30% β too weak for cybersecurity. |\n",
"| **LFM2** (Liquid AI) | Official disclaimer: \"not recommended for programming tasks.\" No Unsloth support. |\n",
"| Gemma-4-E2B | Too new, Unsloth support unverified for small sizes. Large variants (26B+) won't fit T4. |\n",
"\n",
"---\n",
"*Built with β€οΈ for the cybersecurity community. Use responsibly.*"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"name": "python",
"version": "3.10.12"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
|