{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [], "gpuType": "T4" }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "accelerator": "GPU" }, "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# \ud83d\udc51 MOG \u2014 Smart Contract Security Auditor", "", "QLoRA fine-tuning of **Qwen3-8B-Instruct** on `aissacas/solidity-rekt-dataset`", "", "**Runtime \u2192 Change runtime type \u2192 T4 GPU**", "", "- Base: Qwen3-8B-Instruct", "- LoRA rank: 32", "- Dataset: 34,664 samples", "- Epochs: 2", "- Time: ~2 hours on T4" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Step 1: Install Dependencies" ] }, { "cell_type": "code", "metadata": { "id": "install" }, "source": [ "%%capture", "!pip install unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git@main", "!pip install --no-deps trl==0.15.0 datasets huggingface_hub bitsandbytes accelerate peft", "import torch", "print(f'GPU: {torch.cuda.get_device_name(0)}')", "print(f'VRAM: {torch.cuda.get_device_properties(0).total_mem / 1e9:.1f} GB')" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Step 2: Set HF Token" ] }, { "cell_type": "code", "metadata": { "id": "token" }, "source": [ "HF_TOKEN = '' # @param {type:\"string\"}", "import os", "if HF_TOKEN:", " os.environ['HF_TOKEN'] = HF_TOKEN", " from huggingface_hub import login", " login(token=HF_TOKEN)", " print('\u2705 Logged in')", "else:", " print('\u26a0\ufe0f No token \u2014 saves locally only')" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Step 3: Load Model + LoRA" ] }, { "cell_type": "code", "metadata": { "id": "model" }, "source": [ "from unsloth import FastLanguageModel", "import torch", "", "model, tokenizer = FastLanguageModel.from_pretrained(", " model_name='unsloth/Qwen3-8B-Instruct',", " max_seq_length=8192,", " load_in_4bit=True,", " dtype=None,", " trust_remote_code=True,", ")", "", "model = FastLanguageModel.get_peft_model(", " model,", " r=32,", " lora_alpha=64,", " lora_dropout=0,", " bias='none',", " use_gradient_checkpointing='unsloth',", " random_state=42,", " target_modules=['q_proj','k_proj','v_proj','o_proj','gate_proj','up_proj','down_proj'],", ")", "model.print_trainable_parameters()" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Step 4: Load Dataset" ] }, { "cell_type": "code", "metadata": { "id": "data" }, "source": [ "from datasets import load_dataset", "", "ds = load_dataset('aissacas/solidity-rekt-dataset', data_files='mog_train.jsonl', split='train')", "print(f'\u2705 {len(ds)} samples loaded')" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Step 5: Train \ud83d\ude80" ] }, { "cell_type": "code", "metadata": { "id": "train" }, "source": [ "from trl import SFTTrainer", "from transformers import TrainingArguments", "", "trainer = SFTTrainer(", " model=model,", " tokenizer=tokenizer,", " train_dataset=ds,", " max_seq_length=8192,", " packing=True,", " args=TrainingArguments(", " per_device_train_batch_size=2,", " gradient_accumulation_steps=8,", " warmup_ratio=0.1,", " num_train_epochs=2,", " learning_rate=1.5e-4,", " fp16=not torch.cuda.is_bf16_supported(),", " bf16=torch.cuda.is_bf16_supported(),", " logging_steps=25,", " save_steps=500,", " output_dir='mog-checkpoints',", " seed=42,", " report_to='none',", " ),", ")", "", "trainer.train()", "print('\u2705 MOG training complete!')" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Step 6: Save + Push" ] }, { "cell_type": "code", "metadata": { "id": "save" }, "source": [ "model.save_pretrained_merged('mog_merged', tokenizer, save_method='merged_16bit')", "print('\u2705 Merged model saved')", "", "if os.environ.get('HF_TOKEN'):", " model.push_to_hub_merged('aissacas/mog-qwen3-8b-solidity-rekt', tokenizer, save_method='merged_16bit')", " print('\u2705 Pushed to Hub')", "", "model.save_pretrained_gguf('mog_gguf', tokenizer, quantization_method='q4_k_m')", "print('\u2705 GGUF saved \u2014 download from Files tab')" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Step 7: Test MOG" ] }, { "cell_type": "code", "metadata": { "id": "test" }, "source": [ "FastLanguageModel.for_inference(model)", "", "test_code = '''", "// SPDX-License-Identifier: MIT", "pragma solidity ^0.8.0;", "", "contract VulnerableBank {", " mapping(address => uint) public balances;", " function deposit() public payable { balances[msg.sender] += msg.value; }", " function withdraw(uint amount) public {", " require(balances[msg.sender] >= amount);", " (bool sent, ) = msg.sender.call{value: amount}(\\\"\\\");", " require(sent);", " balances[msg.sender] -= amount;", " }", "}", "'''", "", "messages = [", " {'role': 'system', 'content': 'You are MOG, a smart contract security auditor. Analyze the vulnerable Solidity code, explain the vulnerability, and provide a secure patched version.'},", " {'role': 'user', 'content': f'Audit this Solidity contract:\\n```solidity\\n{test_code.strip()}\\n```'},", "]", "ids = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors='pt').to('cuda')", "out = model.generate(ids, max_new_tokens=512, temperature=0.1)", "print('\ud83d\udc51 MOG says:', tokenizer.decode(out[0][ids.shape[1]:], skip_special_tokens=True))" ], "execution_count": null, "outputs": [] } ] }