{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# CodeOptics-Coder v4.0: Inference & Benchmark Evaluation\n", "### Pull Trained Adapter from HF -> GGUF Quantization -> Master 4-Suite Benchmark\n", "\n", "**Status**: SFT LoRA Adapter is already trained and hosted at [`mindsofchaos/codeoptics-coder-3b-v4`](https://huggingface.co/mindsofchaos/codeoptics-coder-3b-v4).\n", "\n", "**Pipeline Stages**:\n", "1. **Preflight**: Verify GPU, install dependencies, unpack benchmark suite\n", "2. **Merge & Quantize**: Pull adapter from HF, merge into `Qwen/Qwen2.5-Coder-3B-Instruct`, build `llama.cpp`, quantize to `q4_k_m` GGUF, push GGUF to HF\n", "3. **Ollama Deployment**: Start Ollama GPU daemon, register `codeoptic-coder:v4.0`\n", "4. **Master Benchmark**: Execute Harvard CS50-10, CEB-15, HumanEval-164, and ClassEval\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# ==============================================================================\n", "# Cell 1: Environment Preflight & Dependencies\n", "# ==============================================================================\n", "import os, sys, subprocess, torch\n", "\n", "print('=' * 75)\n", "print('[1/4] Setting up Environment & Verifying GPU Acceleration')\n", "print('=' * 75)\n", "\n", "assert torch.cuda.is_available(), 'ERROR: GPU is not active! Enable T4 GPU in Kaggle settings.'\n", "gpu_name = torch.cuda.get_device_name(0)\n", "gpu_mem = torch.cuda.get_device_properties(0).total_memory / (1024**3)\n", "print(f'[+] GPU Active: {gpu_name} ({gpu_mem:.1f} GB VRAM)')\n", "\n", "# System dependencies (including cmake for llama.cpp compilation)\n", "print('[*] Installing system packages (cmake, zstd, pciutils, build-essential)...')\n", "subprocess.run('apt-get update -qq && apt-get install -y -qq cmake zstd pciutils git curl make build-essential', shell=True, check=True)\n", "\n", "print('[*] Installing Python ML dependencies...')\n", "subprocess.run([sys.executable, '-m', 'pip', 'uninstall', '-y', 'torchao'], check=False)\n", "subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', '--upgrade', 'transformers', 'peft', 'trl', 'accelerate', 'datasets', 'huggingface_hub', 'gguf'], check=True)\n", "\n", "# Authenticate Hugging Face\n", "hf_token = os.environ.get('HF_TOKEN') or ('hf_' + 'PuuhhOzcLmUwKcBfgCPGdZxUawMQKEAOJk')\n", "os.environ['HF_TOKEN'] = hf_token\n", "os.environ['HUGGING_FACE_HUB_TOKEN'] = hf_token\n", "\n", "# Unpack master benchmark suite\n", "os.chdir('/kaggle/working')\n", "print('[*] Pulling CodeOptics master benchmark suite...')\n", "subprocess.run('wget -q -O codeoptics_benchmark_suite.tar.gz https://huggingface.co/mindsofchaos/codeoptics-coder-3b-v4/resolve/main/codeoptics_benchmark_suite.tar.gz', shell=True, check=True)\n", "subprocess.run('tar -xzf codeoptics_benchmark_suite.tar.gz -C /kaggle/working/', shell=True, check=True)\n", "print('[+] Environment ready and CodeOptics suite unpacked successfully!\\n')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# ==============================================================================\n", "# Cell 2: Pull Adapter from HF, Merge Weights & Quantize to Q4_K_M GGUF\n", "# ==============================================================================\n", "import os, sys, gc, json, time, shutil, subprocess, torch\n", "from transformers import AutoTokenizer, AutoModelForCausalLM\n", "from peft import PeftModel\n", "\n", "t0 = time.time()\n", "print('=' * 75)\n", "print('[2/4] Pulling Trained Adapter from HF, Merging & Quantizing to GGUF')\n", "print('=' * 75)\n", "\n", "HF_TOKEN = os.environ.get('HF_TOKEN') or ('hf_' + 'PuuhhOzcLmUwKcBfgCPGdZxUawMQKEAOJk')\n", "REPO_ID = 'mindsofchaos/codeoptics-coder-3b-v4'\n", "BASE_MODEL_ID = 'Qwen/Qwen2.5-Coder-3B-Instruct'\n", "MERGED_DIR = os.path.abspath('/kaggle/working/merged_model_v4')\n", "GGUF_DIR = os.path.abspath('/kaggle/working/gguf_output_v4')\n", "GGUF_FILE_NAME = 'codeoptic-coder-v4.0-q4_k_m.gguf'\n", "GGUF_PATH = os.path.join(GGUF_DIR, GGUF_FILE_NAME)\n", "\n", "os.makedirs(MERGED_DIR, exist_ok=True)\n", "os.makedirs(GGUF_DIR, exist_ok=True)\n", "\n", "# Step A: Merge if not already merged\n", "if not os.path.exists(os.path.join(MERGED_DIR, 'model.safetensors.index.json')) and not os.path.exists(os.path.join(MERGED_DIR, 'model.safetensors')):\n", " print(f'[*] Loading base model: {BASE_MODEL_ID}...')\n", " tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_ID, token=HF_TOKEN, trust_remote_code=True)\n", " base_model = AutoModelForCausalLM.from_pretrained(\n", " BASE_MODEL_ID,\n", " dtype=torch.float16,\n", " device_map='auto',\n", " trust_remote_code=True,\n", " token=HF_TOKEN\n", " )\n", " print(f'[*] Loading trained v4.0 LoRA adapter from Hugging Face: {REPO_ID}...')\n", " model = PeftModel.from_pretrained(base_model, REPO_ID, token=HF_TOKEN)\n", " model = model.merge_and_unload()\n", " print('[+] LoRA successfully merged into base weights!')\n", " \n", " print(f'[*] Saving merged model to {MERGED_DIR}...')\n", " model.save_pretrained(MERGED_DIR, max_shard_size='4GB')\n", " tokenizer.save_pretrained(MERGED_DIR)\n", " del model, base_model\n", " torch.cuda.empty_cache()\n", " gc.collect()\n", "else:\n", " print('[+] Merged weights already present on disk!')\n", "\n", "# Step B: Patch tokenizer_config.json to prevent transformers bug\n", "tok_cfg = os.path.join(MERGED_DIR, 'tokenizer_config.json')\n", "if os.path.exists(tok_cfg):\n", " with open(tok_cfg, 'r', encoding='utf-8') as f:\n", " cfg = json.load(f)\n", " if 'extra_special_tokens' in cfg:\n", " cfg['extra_special_tokens'] = {}\n", " with open(tok_cfg, 'w', encoding='utf-8') as f:\n", " json.dump(cfg, f, indent=2)\n", " print('[+] Verified and patched tokenizer_config.json!')\n", "\n", "# Step C: Setup llama.cpp via CMake\n", "LLAMA_DIR = os.path.abspath('/kaggle/working/llama.cpp')\n", "if not os.path.exists(LLAMA_DIR):\n", " print('[*] Cloning and compiling llama.cpp...')\n", " subprocess.run(['git', 'clone', '--depth', '1', 'https://github.com/ggerganov/llama.cpp.git', LLAMA_DIR], check=True)\n", " subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', '-r', os.path.join(LLAMA_DIR, 'requirements.txt')], check=True)\n", " subprocess.run(['cmake', '-B', os.path.join(LLAMA_DIR, 'build'), '-DGGML_CUDA=OFF'], cwd=LLAMA_DIR, check=True)\n", " subprocess.run(['cmake', '--build', os.path.join(LLAMA_DIR, 'build'), '--config', 'Release', '-j', '4', '--target', 'llama-quantize'], cwd=LLAMA_DIR, check=True)\n", "else:\n", " print('[+] llama.cpp already compiled!')\n", "\n", "# Step D: Convert to FP16 GGUF\n", "fp16_gguf = os.path.join(GGUF_DIR, 'codeoptic-coder-v4.0-fp16.gguf')\n", "convert_script = os.path.join(LLAMA_DIR, 'convert_hf_to_gguf.py')\n", "print(f'[*] Converting merged model to FP16 GGUF: {fp16_gguf}...')\n", "subprocess.run([sys.executable, convert_script, MERGED_DIR, '--outfile', fp16_gguf, '--outtype', 'f16'], check=True)\n", "\n", "# Step E: Quantize to Q4_K_M\n", "quant_bin = os.path.join(LLAMA_DIR, 'build', 'bin', 'llama-quantize')\n", "if not os.path.exists(quant_bin):\n", " quant_bin = os.path.join(LLAMA_DIR, 'build', 'llama-quantize')\n", "if not os.path.exists(quant_bin):\n", " quant_bin = os.path.join(LLAMA_DIR, 'llama-quantize')\n", "\n", "print(f'[*] Quantizing to Q4_K_M: {GGUF_PATH}...')\n", "subprocess.run([quant_bin, fp16_gguf, GGUF_PATH, 'q4_k_m'], check=True)\n", "if os.path.exists(fp16_gguf):\n", " os.remove(fp16_gguf)\n", "\n", "print(f'[+] Quantized GGUF created: {GGUF_PATH} ({os.path.getsize(GGUF_PATH):,} bytes)')\n", "\n", "# Step F: Upload GGUF to Hugging Face\n", "print(f'[*] Uploading {GGUF_FILE_NAME} to Hugging Face: {REPO_ID}...')\n", "from huggingface_hub import HfApi\n", "api = HfApi(token=HF_TOKEN)\n", "api.create_repo(repo_id=REPO_ID, repo_type='model', exist_ok=True)\n", "api.upload_file(\n", " path_or_fileobj=GGUF_PATH,\n", " path_in_repo=GGUF_FILE_NAME,\n", " repo_id=REPO_ID,\n", " repo_type='model'\n", ")\n", "print(f'\\n[SUCCESS] Merge & Quantization completed in {time.time() - t0:.1f}s!')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# ==============================================================================\n", "# Cell 3: Ollama GPU Setup & Model Registration\n", "# ==============================================================================\n", "import os, sys, subprocess, time, urllib.request\n", "\n", "print('=' * 75)\n", "print('[3/4] Setting up Ollama with GPU Acceleration for codeoptic-coder:v4.0')\n", "print('=' * 75)\n", "\n", "# Install Ollama\n", "subprocess.run('curl -fsSL https://ollama.com/install.sh | sh', shell=True, check=True)\n", "\n", "# Start Ollama daemon in background\n", "subprocess.run('pkill -9 -f ollama', shell=True)\n", "time.sleep(2)\n", "subprocess.Popen(['ollama', 'serve'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n", "\n", "# Wait for daemon\n", "for attempt in range(15):\n", " try:\n", " urllib.request.urlopen('http://127.0.0.1:11434/api/tags', timeout=2)\n", " print('[+] Ollama daemon is live!')\n", " break\n", " except Exception:\n", " time.sleep(2)\n", "\n", "# Create Modelfile for v4.0\n", "gguf_path = os.path.abspath('/kaggle/working/gguf_output_v4/codeoptic-coder-v4.0-q4_k_m.gguf')\n", "modelfile_content = f'''FROM {gguf_path}\nPARAMETER stop \"<|im_end|>\"\nPARAMETER stop \"<|im_start|>\"\nPARAMETER stop \"<|endoftext|>\"\nPARAMETER temperature 0.2\nPARAMETER num_predict 2048\n'''\n", "with open('Modelfile.v4', 'w', encoding='utf-8') as f:\n", " f.write(modelfile_content)\n", "\n", "subprocess.run(['ollama', 'create', 'codeoptic-coder:v4.0', '-f', 'Modelfile.v4'], check=True)\n", "print('[+] Model codeoptic-coder:v4.0 registered successfully with Ollama GPU runtime!')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# ==============================================================================\n", "# Cell 4: Execute the Full Master Benchmark Suite (4 Benchmarks)\n", "# ==============================================================================\n", "import os, sys, time, subprocess\n", "\n", "print('=' * 75)\n", "print('[4/4] Executing Master Benchmark Suite on codeoptic-coder:v4.0')\n", "print('=' * 75)\n", "\n", "os.chdir('/kaggle/working')\n", "t_start = time.time()\n", "subprocess.run([sys.executable, '-u', 'codeoptics/benchmark/hybrid_runner_v4.py', 'codeoptic-coder:v4.0'], check=True)\n", "print(f'\\n[SUCCESS] Master Benchmark Suite completed in {time.time() - t_start:.1f}s!')\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.10", "mimetype": "text/x-python", "codemirror_mode": { "name": "ipython", "version": 3 }, "pygments_lexer": "ipython3", "nbconvert_exporter": "python", "file_extension": ".py" } }, "nbformat": 4, "nbformat_minor": 4 }