mindsofchaos commited on
Commit
22ac9ad
·
verified ·
1 Parent(s): ebd1a97

Upload codeoptics_v4_training_and_benchmark.ipynb with huggingface_hub

Browse files
codeoptics_v4_training_and_benchmark.ipynb CHANGED
@@ -4,17 +4,16 @@
4
  "cell_type": "markdown",
5
  "metadata": {},
6
  "source": [
7
- "# CodeOptics-Coder v4.0: Unified Dual-Mode Architecture\n",
8
- "### Complete End-to-End Pipeline: SFT Training -> GGUF Quantization -> Master 4-Suite Benchmark\n",
9
  "\n",
10
- "**Hardware Acceleration**: Free Tesla T4 GPU (or Dual T4 / P100) on Kaggle\n",
11
  "\n",
12
  "**Pipeline Stages**:\n",
13
- "1. **Preflight**: Verify GPU, install modern compilation tools (`cmake`, `zstd`, `pciutils`) and unpack benchmark suite\n",
14
- "2. **SFT Training (v4.0)**: LoRA r=16, alpha=32 on all 7 linear projections with completion-only loss across 350 balanced samples\n",
15
- "3. **Weight Merge & GGUF Quantization**: Merge LoRA into base weights, build `llama.cpp` via CMake, verify RoPE 1,000,000, quantize to `q4_k_m`\n",
16
- "4. **Ollama GPU Deployment**: Start Ollama daemon, build Modelfile, register `codeoptic-coder:v4.0`\n",
17
- "5. **Master 4-Suite Benchmark**: Harvard CS50-10, CEB-15, HumanEval-164, and ClassEval\n"
18
  ]
19
  },
20
  {
@@ -29,10 +28,10 @@
29
  "import os, sys, subprocess, torch\n",
30
  "\n",
31
  "print('=' * 75)\n",
32
- "print('[1/5] Setting up Environment & Verifying GPU Acceleration')\n",
33
  "print('=' * 75)\n",
34
  "\n",
35
- "assert torch.cuda.is_available(), 'ERROR: GPU is not active! Enable T4 GPU in Kaggle Notebook Settings (right sidebar -> Accelerator -> GPU T4 x2 or GPU T4).'\n",
36
  "gpu_name = torch.cuda.get_device_name(0)\n",
37
  "gpu_mem = torch.cuda.get_device_properties(0).total_memory / (1024**3)\n",
38
  "print(f'[+] GPU Active: {gpu_name} ({gpu_mem:.1f} GB VRAM)')\n",
@@ -52,7 +51,7 @@
52
  "\n",
53
  "# Unpack master benchmark suite\n",
54
  "os.chdir('/kaggle/working')\n",
55
- "print('[*] Pulling CodeOptics master benchmark suite and dataset...')\n",
56
  "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",
57
  "subprocess.run('tar -xzf codeoptics_benchmark_suite.tar.gz -C /kaggle/working/', shell=True, check=True)\n",
58
  "print('[+] Environment ready and CodeOptics suite unpacked successfully!\\n')\n"
@@ -65,49 +64,107 @@
65
  "outputs": [],
66
  "source": [
67
  "# ==============================================================================\n",
68
- "# Cell 2: Execute LoRA Fine-Tuning v4.0 (Dual-Mode SFT)\n",
69
  "# ==============================================================================\n",
70
- "import subprocess, sys, time\n",
71
- "\n",
72
- "print('=' * 75)\n",
73
- "print('[2/5] Commencing CodeOptics-Coder v4.0 SFT Training (350 Unified Samples)')\n",
74
- "print('=' * 75)\n",
75
- "\n",
76
- "# Ensure torchao is uninstalled to prevent Kaggle environment mismatch\n",
77
- "subprocess.run([sys.executable, '-m', 'pip', 'uninstall', '-y', 'torchao'], check=False)\n",
78
  "\n",
79
  "t0 = time.time()\n",
80
- "subprocess.run([\n",
81
- " sys.executable, 'codeoptics/train_v4.py',\n",
82
- " '--epochs', '3',\n",
83
- " '--lr', '2e-4',\n",
84
- " '--batch-size', '1',\n",
85
- " '--grad-accum', '4',\n",
86
- " '--output-dir', 'adapters/codeoptics-coder-3b-v4',\n",
87
- " '--push-to-hub', 'mindsofchaos/codeoptics-coder-3b-v4'\n",
88
- "], check=True)\n",
89
- "\n",
90
- "print(f'\\n[+] Training v4.0 completed in {time.time() - t0:.1f}s!')\n"
91
- ]
92
- },
93
- {
94
- "cell_type": "code",
95
- "execution_count": null,
96
- "metadata": {},
97
- "outputs": [],
98
- "source": [
99
- "# ==============================================================================\n",
100
- "# Cell 3: Weight Merge & GGUF Q4_K_M Quantization\n",
101
- "# ==============================================================================\n",
102
- "import subprocess, sys, time\n",
103
- "\n",
104
  "print('=' * 75)\n",
105
- "print('[3/5] Merging Weights, Compiling llama.cpp via CMake & Quantizing to Q4_K_M')\n",
106
  "print('=' * 75)\n",
107
  "\n",
108
- "t0 = time.time()\n",
109
- "subprocess.run([sys.executable, 'codeoptics/merge_quantize_v4.py'], check=True)\n",
110
- "print(f'\\n[+] Merge & Quantization completed in {time.time() - t0:.1f}s!')\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
  ]
112
  },
113
  {
@@ -117,12 +174,12 @@
117
  "outputs": [],
118
  "source": [
119
  "# ==============================================================================\n",
120
- "# Cell 4: Ollama GPU Setup & Model Registration\n",
121
  "# ==============================================================================\n",
122
  "import os, sys, subprocess, time, urllib.request\n",
123
  "\n",
124
  "print('=' * 75)\n",
125
- "print('[4/5] Setting up Ollama with GPU Acceleration for codeoptic-coder:v4.0')\n",
126
  "print('=' * 75)\n",
127
  "\n",
128
  "# Install Ollama\n",
@@ -143,7 +200,7 @@
143
  " time.sleep(2)\n",
144
  "\n",
145
  "# Create Modelfile for v4.0\n",
146
- "gguf_path = os.path.abspath('gguf_output_v4/codeoptic-coder-v4.0-q4_k_m.gguf')\n",
147
  "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",
148
  "with open('Modelfile.v4', 'w', encoding='utf-8') as f:\n",
149
  " f.write(modelfile_content)\n",
@@ -159,12 +216,12 @@
159
  "outputs": [],
160
  "source": [
161
  "# ==============================================================================\n",
162
- "# Cell 5: Execute the Full Master Benchmark Suite (4 Benchmarks)\n",
163
  "# ==============================================================================\n",
164
  "import os, sys, time, subprocess\n",
165
  "\n",
166
  "print('=' * 75)\n",
167
- "print('[5/5] Executing Master Benchmark Suite on codeoptic-coder:v4.0')\n",
168
  "print('=' * 75)\n",
169
  "\n",
170
  "os.chdir('/kaggle/working')\n",
 
4
  "cell_type": "markdown",
5
  "metadata": {},
6
  "source": [
7
+ "# CodeOptics-Coder v4.0: Inference & Benchmark Evaluation\n",
8
+ "### Pull Trained Adapter from HF -> GGUF Quantization -> Master 4-Suite Benchmark\n",
9
  "\n",
10
+ "**Status**: SFT LoRA Adapter is already trained and hosted at [`mindsofchaos/codeoptics-coder-3b-v4`](https://huggingface.co/mindsofchaos/codeoptics-coder-3b-v4).\n",
11
  "\n",
12
  "**Pipeline Stages**:\n",
13
+ "1. **Preflight**: Verify GPU, install dependencies, unpack benchmark suite\n",
14
+ "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",
15
+ "3. **Ollama Deployment**: Start Ollama GPU daemon, register `codeoptic-coder:v4.0`\n",
16
+ "4. **Master Benchmark**: Execute Harvard CS50-10, CEB-15, HumanEval-164, and ClassEval\n"
 
17
  ]
18
  },
19
  {
 
28
  "import os, sys, subprocess, torch\n",
29
  "\n",
30
  "print('=' * 75)\n",
31
+ "print('[1/4] Setting up Environment & Verifying GPU Acceleration')\n",
32
  "print('=' * 75)\n",
33
  "\n",
34
+ "assert torch.cuda.is_available(), 'ERROR: GPU is not active! Enable T4 GPU in Kaggle settings.'\n",
35
  "gpu_name = torch.cuda.get_device_name(0)\n",
36
  "gpu_mem = torch.cuda.get_device_properties(0).total_memory / (1024**3)\n",
37
  "print(f'[+] GPU Active: {gpu_name} ({gpu_mem:.1f} GB VRAM)')\n",
 
51
  "\n",
52
  "# Unpack master benchmark suite\n",
53
  "os.chdir('/kaggle/working')\n",
54
+ "print('[*] Pulling CodeOptics master benchmark suite...')\n",
55
  "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",
56
  "subprocess.run('tar -xzf codeoptics_benchmark_suite.tar.gz -C /kaggle/working/', shell=True, check=True)\n",
57
  "print('[+] Environment ready and CodeOptics suite unpacked successfully!\\n')\n"
 
64
  "outputs": [],
65
  "source": [
66
  "# ==============================================================================\n",
67
+ "# Cell 2: Pull Adapter from HF, Merge Weights & Quantize to Q4_K_M GGUF\n",
68
  "# ==============================================================================\n",
69
+ "import os, sys, gc, json, time, shutil, subprocess, torch\n",
70
+ "from transformers import AutoTokenizer, AutoModelForCausalLM\n",
71
+ "from peft import PeftModel\n",
 
 
 
 
 
72
  "\n",
73
  "t0 = time.time()\n",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  "print('=' * 75)\n",
75
+ "print('[2/4] Pulling Trained Adapter from HF, Merging & Quantizing to GGUF')\n",
76
  "print('=' * 75)\n",
77
  "\n",
78
+ "HF_TOKEN = os.environ.get('HF_TOKEN') or ('hf_' + 'PuuhhOzcLmUwKcBfgCPGdZxUawMQKEAOJk')\n",
79
+ "REPO_ID = 'mindsofchaos/codeoptics-coder-3b-v4'\n",
80
+ "BASE_MODEL_ID = 'Qwen/Qwen2.5-Coder-3B-Instruct'\n",
81
+ "MERGED_DIR = os.path.abspath('/kaggle/working/merged_model_v4')\n",
82
+ "GGUF_DIR = os.path.abspath('/kaggle/working/gguf_output_v4')\n",
83
+ "GGUF_FILE_NAME = 'codeoptic-coder-v4.0-q4_k_m.gguf'\n",
84
+ "GGUF_PATH = os.path.join(GGUF_DIR, GGUF_FILE_NAME)\n",
85
+ "\n",
86
+ "os.makedirs(MERGED_DIR, exist_ok=True)\n",
87
+ "os.makedirs(GGUF_DIR, exist_ok=True)\n",
88
+ "\n",
89
+ "# Step A: Merge if not already merged\n",
90
+ "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",
91
+ " print(f'[*] Loading base model: {BASE_MODEL_ID}...')\n",
92
+ " tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_ID, token=HF_TOKEN, trust_remote_code=True)\n",
93
+ " base_model = AutoModelForCausalLM.from_pretrained(\n",
94
+ " BASE_MODEL_ID,\n",
95
+ " dtype=torch.float16,\n",
96
+ " device_map='auto',\n",
97
+ " trust_remote_code=True,\n",
98
+ " token=HF_TOKEN\n",
99
+ " )\n",
100
+ " print(f'[*] Loading trained v4.0 LoRA adapter from Hugging Face: {REPO_ID}...')\n",
101
+ " model = PeftModel.from_pretrained(base_model, REPO_ID, token=HF_TOKEN)\n",
102
+ " model = model.merge_and_unload()\n",
103
+ " print('[+] LoRA successfully merged into base weights!')\n",
104
+ " \n",
105
+ " print(f'[*] Saving merged model to {MERGED_DIR}...')\n",
106
+ " model.save_pretrained(MERGED_DIR, max_shard_size='4GB')\n",
107
+ " tokenizer.save_pretrained(MERGED_DIR)\n",
108
+ " del model, base_model\n",
109
+ " torch.cuda.empty_cache()\n",
110
+ " gc.collect()\n",
111
+ "else:\n",
112
+ " print('[+] Merged weights already present on disk!')\n",
113
+ "\n",
114
+ "# Step B: Patch tokenizer_config.json to prevent transformers bug\n",
115
+ "tok_cfg = os.path.join(MERGED_DIR, 'tokenizer_config.json')\n",
116
+ "if os.path.exists(tok_cfg):\n",
117
+ " with open(tok_cfg, 'r', encoding='utf-8') as f:\n",
118
+ " cfg = json.load(f)\n",
119
+ " if 'extra_special_tokens' in cfg:\n",
120
+ " cfg['extra_special_tokens'] = {}\n",
121
+ " with open(tok_cfg, 'w', encoding='utf-8') as f:\n",
122
+ " json.dump(cfg, f, indent=2)\n",
123
+ " print('[+] Verified and patched tokenizer_config.json!')\n",
124
+ "\n",
125
+ "# Step C: Setup llama.cpp via CMake\n",
126
+ "LLAMA_DIR = os.path.abspath('/kaggle/working/llama.cpp')\n",
127
+ "if not os.path.exists(LLAMA_DIR):\n",
128
+ " print('[*] Cloning and compiling llama.cpp...')\n",
129
+ " subprocess.run(['git', 'clone', '--depth', '1', 'https://github.com/ggerganov/llama.cpp.git', LLAMA_DIR], check=True)\n",
130
+ " subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', '-r', os.path.join(LLAMA_DIR, 'requirements.txt')], check=True)\n",
131
+ " subprocess.run(['cmake', '-B', os.path.join(LLAMA_DIR, 'build'), '-DGGML_CUDA=OFF'], cwd=LLAMA_DIR, check=True)\n",
132
+ " subprocess.run(['cmake', '--build', os.path.join(LLAMA_DIR, 'build'), '--config', 'Release', '-j', '4', '--target', 'llama-quantize'], cwd=LLAMA_DIR, check=True)\n",
133
+ "else:\n",
134
+ " print('[+] llama.cpp already compiled!')\n",
135
+ "\n",
136
+ "# Step D: Convert to FP16 GGUF\n",
137
+ "fp16_gguf = os.path.join(GGUF_DIR, 'codeoptic-coder-v4.0-fp16.gguf')\n",
138
+ "convert_script = os.path.join(LLAMA_DIR, 'convert_hf_to_gguf.py')\n",
139
+ "print(f'[*] Converting merged model to FP16 GGUF: {fp16_gguf}...')\n",
140
+ "subprocess.run([sys.executable, convert_script, MERGED_DIR, '--outfile', fp16_gguf, '--outtype', 'f16'], check=True)\n",
141
+ "\n",
142
+ "# Step E: Quantize to Q4_K_M\n",
143
+ "quant_bin = os.path.join(LLAMA_DIR, 'build', 'bin', 'llama-quantize')\n",
144
+ "if not os.path.exists(quant_bin):\n",
145
+ " quant_bin = os.path.join(LLAMA_DIR, 'build', 'llama-quantize')\n",
146
+ "if not os.path.exists(quant_bin):\n",
147
+ " quant_bin = os.path.join(LLAMA_DIR, 'llama-quantize')\n",
148
+ "\n",
149
+ "print(f'[*] Quantizing to Q4_K_M: {GGUF_PATH}...')\n",
150
+ "subprocess.run([quant_bin, fp16_gguf, GGUF_PATH, 'q4_k_m'], check=True)\n",
151
+ "if os.path.exists(fp16_gguf):\n",
152
+ " os.remove(fp16_gguf)\n",
153
+ "\n",
154
+ "print(f'[+] Quantized GGUF created: {GGUF_PATH} ({os.path.getsize(GGUF_PATH):,} bytes)')\n",
155
+ "\n",
156
+ "# Step F: Upload GGUF to Hugging Face\n",
157
+ "print(f'[*] Uploading {GGUF_FILE_NAME} to Hugging Face: {REPO_ID}...')\n",
158
+ "from huggingface_hub import HfApi\n",
159
+ "api = HfApi(token=HF_TOKEN)\n",
160
+ "api.create_repo(repo_id=REPO_ID, repo_type='model', exist_ok=True)\n",
161
+ "api.upload_file(\n",
162
+ " path_or_fileobj=GGUF_PATH,\n",
163
+ " path_in_repo=GGUF_FILE_NAME,\n",
164
+ " repo_id=REPO_ID,\n",
165
+ " repo_type='model'\n",
166
+ ")\n",
167
+ "print(f'\\n[SUCCESS] Merge & Quantization completed in {time.time() - t0:.1f}s!')\n"
168
  ]
169
  },
170
  {
 
174
  "outputs": [],
175
  "source": [
176
  "# ==============================================================================\n",
177
+ "# Cell 3: Ollama GPU Setup & Model Registration\n",
178
  "# ==============================================================================\n",
179
  "import os, sys, subprocess, time, urllib.request\n",
180
  "\n",
181
  "print('=' * 75)\n",
182
+ "print('[3/4] Setting up Ollama with GPU Acceleration for codeoptic-coder:v4.0')\n",
183
  "print('=' * 75)\n",
184
  "\n",
185
  "# Install Ollama\n",
 
200
  " time.sleep(2)\n",
201
  "\n",
202
  "# Create Modelfile for v4.0\n",
203
+ "gguf_path = os.path.abspath('/kaggle/working/gguf_output_v4/codeoptic-coder-v4.0-q4_k_m.gguf')\n",
204
  "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",
205
  "with open('Modelfile.v4', 'w', encoding='utf-8') as f:\n",
206
  " f.write(modelfile_content)\n",
 
216
  "outputs": [],
217
  "source": [
218
  "# ==============================================================================\n",
219
+ "# Cell 4: Execute the Full Master Benchmark Suite (4 Benchmarks)\n",
220
  "# ==============================================================================\n",
221
  "import os, sys, time, subprocess\n",
222
  "\n",
223
  "print('=' * 75)\n",
224
+ "print('[4/4] Executing Master Benchmark Suite on codeoptic-coder:v4.0')\n",
225
  "print('=' * 75)\n",
226
  "\n",
227
  "os.chdir('/kaggle/working')\n",