Auroraventures commited on
Commit
30c9bde
·
verified ·
1 Parent(s): faea26e

Upload cipher-simpo-train.ipynb with huggingface_hub

Browse files
Files changed (1) hide show
  1. cipher-simpo-train.ipynb +238 -0
cipher-simpo-train.ipynb ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Cipher Stage 2 — SimPO Anti-Slop Training (Self-Contained)\n",
8
+ "\n",
9
+ "Pulls SFT-merged model from HF, generates preference pairs, trains SimPO, pushes result.\n",
10
+ "\n",
11
+ "**Runtime needed:** A100 (Colab Pro+). ~45-90 min total.\n",
12
+ "**Output:** `Auroraventures/cipher-simpo-merged` on HuggingFace.\n",
13
+ "\n",
14
+ "Best-in-class params (paper-optimal): beta=10, gamma=2.5, grad_accum=128"
15
+ ]
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "execution_count": null,
21
+ "outputs": [],
22
+ "source": "# Cell 1 — Install\n!pip install -U unsloth trl datasets huggingface_hub -q\n!pip install --no-deps git+https://github.com/unslothai/unsloth.git@nightly -q\nimport os\nfrom google.colab import userdata\ntry:\n os.environ['HF_TOKEN'] = userdata.get('HF_TOKEN')\nexcept Exception:\n raise RuntimeError('Add HF_TOKEN to Colab Secrets (left sidebar key icon).')\nos.environ['WANDB_DISABLED'] = 'true'\nfrom huggingface_hub import login\nlogin(token=os.environ['HF_TOKEN'])\nprint('Setup done')"
23
+ },
24
+ {
25
+ "cell_type": "code",
26
+ "metadata": {},
27
+ "execution_count": null,
28
+ "outputs": [],
29
+ "source": [
30
+ "# Cell 2 — Load SFT-merged model from HF (~5 min, 62GB)\n",
31
+ "import torch\n",
32
+ "from unsloth import FastLanguageModel\n",
33
+ "\n",
34
+ "MODEL_ID = 'Auroraventures/cipher-sft-merged'\n",
35
+ "MAX_SEQ = 8192\n",
36
+ "\n",
37
+ "model, tokenizer = FastLanguageModel.from_pretrained(\n",
38
+ " model_name=MODEL_ID,\n",
39
+ " max_seq_length=MAX_SEQ,\n",
40
+ " load_in_4bit=True,\n",
41
+ " dtype=None,\n",
42
+ ")\n",
43
+ "print(f'Loaded: VRAM {torch.cuda.max_memory_allocated()/1e9:.1f}GB')"
44
+ ]
45
+ },
46
+ {
47
+ "cell_type": "code",
48
+ "metadata": {},
49
+ "execution_count": null,
50
+ "outputs": [],
51
+ "source": [
52
+ "# Cell 3 — Apply fresh LoRA for SimPO\n",
53
+ "model = FastLanguageModel.get_peft_model(\n",
54
+ " model,\n",
55
+ " r=64, # paper-optimal for 31B with rsLoRA\n",
56
+ " lora_alpha=64,\n",
57
+ " target_modules=['q_proj','k_proj','v_proj','o_proj','gate_proj','up_proj','down_proj'],\n",
58
+ " use_gradient_checkpointing='unsloth',\n",
59
+ " use_rslora=True, # critical for r=64 stability\n",
60
+ " random_state=42,\n",
61
+ ")\n",
62
+ "model.print_trainable_parameters()"
63
+ ]
64
+ },
65
+ {
66
+ "cell_type": "code",
67
+ "metadata": {},
68
+ "execution_count": null,
69
+ "outputs": [],
70
+ "source": [
71
+ "# Cell 4 — Pull training data + slop tools from kr8tiv-training\n",
72
+ "import subprocess, sys\n",
73
+ "subprocess.run('rm -rf /content/kr8tiv-training && git clone --depth 1 https://github.com/kr8tiv-ai/kr8tiv-training.git /content/kr8tiv-training', shell=True, check=True)\n",
74
+ "sys.path.insert(0, '/content/kr8tiv-training')\n",
75
+ "from scripts.slop_detector import slop_score\n",
76
+ "from scripts.rejected_generator import generate_rejected\n",
77
+ "print('Tools loaded')"
78
+ ]
79
+ },
80
+ {
81
+ "cell_type": "code",
82
+ "metadata": {},
83
+ "execution_count": null,
84
+ "outputs": [],
85
+ "source": [
86
+ "# Cell 5 — Generate SimPO preference pairs from existing SFT data\n",
87
+ "import json\n",
88
+ "from pathlib import Path\n",
89
+ "\n",
90
+ "SFT_DATA = '/content/kr8tiv-training/data/prompts/awwwards-sft.jsonl'\n",
91
+ "PAIRS_OUT = '/content/simpo_pairs.jsonl'\n",
92
+ "\n",
93
+ "examples = []\n",
94
+ "with open(SFT_DATA) as f:\n",
95
+ " for line in f:\n",
96
+ " if line.strip():\n",
97
+ " try: examples.append(json.loads(line))\n",
98
+ " except: pass\n",
99
+ "\n",
100
+ "print(f'Loaded {len(examples)} SFT examples')\n",
101
+ "\n",
102
+ "# Build preference pairs\n",
103
+ "pairs = []\n",
104
+ "skipped = 0\n",
105
+ "for ex in examples:\n",
106
+ " msgs = ex.get('messages', [])\n",
107
+ " user_msg = next((m['content'] for m in msgs if m['role']=='user'), '')\n",
108
+ " chosen = next((m['content'] for m in msgs if m['role']=='assistant'), '')\n",
109
+ " if not user_msg or not chosen or len(chosen) < 200:\n",
110
+ " skipped += 1; continue\n",
111
+ " try:\n",
112
+ " rejected = generate_rejected(chosen)\n",
113
+ " if not rejected or rejected == chosen or len(rejected) < 100:\n",
114
+ " skipped += 1; continue\n",
115
+ " pairs.append({'prompt': user_msg, 'chosen': chosen, 'rejected': rejected})\n",
116
+ " except Exception as e:\n",
117
+ " skipped += 1\n",
118
+ "\n",
119
+ "with open(PAIRS_OUT, 'w') as f:\n",
120
+ " for p in pairs: f.write(json.dumps(p) + '\\n')\n",
121
+ "\n",
122
+ "print(f'Generated {len(pairs)} pairs, skipped {skipped}')\n",
123
+ "if pairs:\n",
124
+ " s = pairs[0]\n",
125
+ " print(f'\\nSample chosen: {len(s[\"chosen\"])} chars, rejected: {len(s[\"rejected\"])} chars')"
126
+ ]
127
+ },
128
+ {
129
+ "cell_type": "code",
130
+ "metadata": {},
131
+ "execution_count": null,
132
+ "outputs": [],
133
+ "source": [
134
+ "# Cell 6 — Load preference dataset\n",
135
+ "from datasets import load_dataset\n",
136
+ "ds = load_dataset('json', data_files=PAIRS_OUT)\n",
137
+ "print(f'Dataset: {len(ds[\"train\"])} pairs')"
138
+ ]
139
+ },
140
+ {
141
+ "cell_type": "code",
142
+ "metadata": {},
143
+ "execution_count": null,
144
+ "outputs": [],
145
+ "source": [
146
+ "# Cell 7 — Train SimPO (paper-optimal params)\n",
147
+ "from trl import CPOTrainer, CPOConfig\n",
148
+ "\n",
149
+ "config = CPOConfig(\n",
150
+ " output_dir='/content/cipher-simpo-out',\n",
151
+ " loss_type='simpo',\n",
152
+ " cpo_alpha=0.0, # pure SimPO\n",
153
+ " simpo_gamma=2.5, # paper-optimal\n",
154
+ " beta=10.0, # paper-optimal\n",
155
+ " per_device_train_batch_size=1,\n",
156
+ " gradient_accumulation_steps=128, # effective batch 128 — #1 quality lever\n",
157
+ " num_train_epochs=1,\n",
158
+ " learning_rate=5e-6,\n",
159
+ " bf16=True,\n",
160
+ " max_length=4096,\n",
161
+ " max_prompt_length=512,\n",
162
+ " logging_steps=5,\n",
163
+ " report_to='none',\n",
164
+ " save_strategy='no',\n",
165
+ ")\n",
166
+ "\n",
167
+ "trainer = CPOTrainer(\n",
168
+ " model=model,\n",
169
+ " tokenizer=tokenizer,\n",
170
+ " train_dataset=ds['train'],\n",
171
+ " args=config,\n",
172
+ ")\n",
173
+ "\n",
174
+ "print(f'Pre-train VRAM: {torch.cuda.max_memory_allocated()/1e9:.1f}GB')\n",
175
+ "trainer.train()\n",
176
+ "print('SimPO training complete!')"
177
+ ]
178
+ },
179
+ {
180
+ "cell_type": "code",
181
+ "metadata": {},
182
+ "execution_count": null,
183
+ "outputs": [],
184
+ "source": [
185
+ "# Cell 8 — Merge + save + push to HF\n",
186
+ "MERGED_DIR = '/content/cipher-simpo-merged'\n",
187
+ "model.save_pretrained_merged(MERGED_DIR, tokenizer, save_method='merged_16bit')\n",
188
+ "print(f'Saved to {MERGED_DIR}')\n",
189
+ "\n",
190
+ "# Push to HF\n",
191
+ "from huggingface_hub import HfApi\n",
192
+ "api = HfApi()\n",
193
+ "api.create_repo('Auroraventures/cipher-simpo-merged', exist_ok=True)\n",
194
+ "api.upload_folder(\n",
195
+ " folder_path=MERGED_DIR,\n",
196
+ " repo_id='Auroraventures/cipher-simpo-merged',\n",
197
+ " commit_message='Cipher SimPO merged - Stage 2 anti-slop',\n",
198
+ ")\n",
199
+ "print('Pushed to https://huggingface.co/Auroraventures/cipher-simpo-merged')"
200
+ ]
201
+ },
202
+ {
203
+ "cell_type": "code",
204
+ "metadata": {},
205
+ "execution_count": null,
206
+ "outputs": [],
207
+ "source": [
208
+ "# Cell 9 — Quick comparison test\n",
209
+ "FastLanguageModel.for_inference(model)\n",
210
+ "\n",
211
+ "test = 'Build a hero section with a Three.js particle system that responds to mouse movement.'\n",
212
+ "msgs = [{'role':'user','content':test}]\n",
213
+ "inputs = tokenizer.apply_chat_template(msgs, tokenize=True, add_generation_prompt=True, return_tensors='pt').to('cuda')\n",
214
+ "out = model.generate(input_ids=inputs, max_new_tokens=2048, temperature=0.7)\n",
215
+ "response = tokenizer.decode(out[0], skip_special_tokens=True)\n",
216
+ "\n",
217
+ "score = slop_score(response)\n",
218
+ "print(f'Slop score: {score[\"score\"]:.1f} (is_slop: {score[\"is_slop\"]})')\n",
219
+ "print(f'Signals: {score[\"signals\"]}')\n",
220
+ "print(f'Response length: {len(response)} chars')\n",
221
+ "print(f'Tailwind: {\"YES (BAD)\" if \"tailwindcss\" in response else \"no\"}')"
222
+ ]
223
+ }
224
+ ],
225
+ "metadata": {
226
+ "kernelspec": {
227
+ "display_name": "Python 3",
228
+ "language": "python",
229
+ "name": "python3"
230
+ },
231
+ "accelerator": "GPU",
232
+ "colab": {
233
+ "gpuType": "A100"
234
+ }
235
+ },
236
+ "nbformat": 4,
237
+ "nbformat_minor": 4
238
+ }