{"cells":[{"cell_type":"markdown","metadata":{},"source":["# VQ Colab LoRA Fine-Tune — your business's own AI\n","\n","**What this is:** the Applied Compute pattern at demo scale. Take a free\n","open-source base model (Qwen2.5-0.5B, or 1.5B on a bigger GPU) and train\n","it on ONE business's private data (FAQs, docs, call scripts) with LoRA.\n","The result is that business's own AI — it answers in that business's\n","words, prices and policies — served as an OpenAI-compatible API your\n","agents call through the `colab-ft` provider in `llm_providers.py`.\n","\n","**Honest limits — read before you trust it:**\n","- LoRA on a 0.5B model is a **demo-grade fine-tune**, not a $4.5B\n","  product. It teaches the model your facts and your phrasing; it does\n","  not make a small model smart. Real business use wants 50–500+ quality\n","  pairs, 1–3 epochs, and a human eval pass before any customer sees it.\n","- Colab runtimes **expire**: ~12 h max, ~90 min idle. The fine-tuned\n","  model lives only while this runtime + tunnel are up, unless you export\n","  the adapter (last section). Anything that must stay up uses Groq /\n","  Gemini / Pollinations (already in `llm_providers.py`).\n","- GPU varies: free Colab gives a T4; AI Pro accounts get priority for\n","  L4/A100 (not guaranteed). 0.5B trains on any of them; 1.5B wants an\n","  L4/A100. Compute units: ~200/month per Google AI Pro account.\n","- The public URL changes on every run. Copy the fresh URL each time and\n","  set `COLAB_FT_API_BASE` on the agent host.\n","\n","**Accounts with Google AI Pro (verified 28 Nov 2026):**\n","`mr.shivaaysinghrajput@gmail.com` (receipt-verified), plus\n","`ssrmrecordslabel@gmail.com` and `dhumalsanskruti040@gmail.com`\n","(user-confirmed; verify in Colab → Settings → plan + compute units).\n","Run this notebook from one of those three accounts with a **GPU**\n","runtime (Runtime → Change runtime type → T4 GPU).\n","Do NOT run it from any other account, and never use\n","`dhumalsanskruti040@gmail.com` for VQ sign-ins — this notebook only."]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# 1 — Install deps + confirm the GPU\n","!pip install -q transformers accelerate peft trl datasets\n","import torch\n","print('torch', torch.__version__)\n","print('cuda available:', torch.cuda.is_available())\n","if torch.cuda.is_available():\n","    print('GPU:', torch.cuda.get_device_name(0))\n","    print('VRAM GB:', round(torch.cuda.get_device_properties(0).total_memory / 1e9, 1))\n","else:\n","    print('NO GPU — set Runtime → Change runtime type → T4 GPU, then re-run.')"]},{"cell_type":"markdown","metadata":{},"source":["## 2 — Your business data (JSONL)\n","\n","One pair per line, exact format:\n","\n","```json\n","{\"instruction\": \"How much does the AI receptionist cost?\", \"response\": \"The AI receptionist is $99 for the first 3 founding customers, plus $25 per month locked for life.\"}\n","```\n","\n","- `instruction` = what a customer asks (their words).\n","- `response` = the answer in the business's words (facts only — never\n","  invent prices, hours or policies; if it is not in your docs, do not\n","  put it in the data).\n","- 12 pairs (below) is a smoke test. A real business fine-tune wants\n","  50–500+ pairs covering every question customers actually ask.\n","- Have FAQs/docs instead? Cell 4 converts JSON FAQs or Markdown FAQs\n","  into this format. The full converter script lives in the repo:\n","  `colab-ft/convert_business_data.py`."]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# 3 — Sample data: VisionQuantech's own AI receptionist (12 pairs)\n","# Replace this file with YOUR business's data to fine-tune for them:\n","# upload a .jsonl in this format (Files panel, left) and set DATA below.\n","import json\n","SAMPLE = [\n"," (\"How much does the VisionQuantech AI receptionist cost?\", \"The AI receptionist is $99 for the first 3 founding customers, plus $25 per month locked for life. After the 3 founding spots fill, the public rate card is $2,500 to $12,500.\"),\n"," (\"What does the VisionQuantech AI receptionist do?\", \"It answers your business calls 24/7, books appointments, answers common questions, takes messages, and handles after-hours callers so you never miss a customer.\"),\n"," (\"How do I book a demo of the AI receptionist?\", \"Book a 15-minute live setup call on visionquantech.com. We set the receptionist up live on the call, on your real business number.\"),\n"," (\"Who is the founder of VisionQuantech?\", \"Shivam Kumar is the Founder and CEO of VisionQuantech.\"),\n"," (\"What is VisionQuantech?\", \"VisionQuantech is an AI company that builds AI agents, apps, tools and custom software for businesses, plus free tools anyone can use.\"),\n"," (\"What is the WhatsApp number for VisionQuantech?\", \"You can reach VisionQuantech on WhatsApp at +91 75630 04275.\"),\n"," (\"Does VisionQuantech offer free tools?\", \"Yes. Free tools like the PDF tools suite, CGPA to percentage calculator and image compressors are live at apps.visionquantech.com.\"),\n"," (\"Which businesses is the AI receptionist for?\", \"It is built for clinics, real estate agencies, salons, hotels and other local businesses that lose customers on missed calls.\"),\n"," (\"Does the AI receptionist work on WhatsApp?\", \"Yes, there is a WhatsApp AI agent as well. It answers customer messages, books appointments and takes details on WhatsApp.\"),\n"," (\"Is the AI receptionist available 24 hours a day?\", \"Yes. The AI receptionist answers calls 24/7, including nights and weekends, so no call goes unanswered.\"),\n"," (\"How long does setup take?\", \"Setup takes 15 minutes, live on a call. We configure it for your business and test it with you on the same call.\"),\n"," (\"Who are you?\", \"I am the VisionQuantech AI receptionist, built by VisionQuantech to answer calls and book appointments for your business.\"),\n","]\n","DATA = 'business_data.jsonl'\n","with open(DATA, 'w') as f:\n","    for q, a in SAMPLE:\n","        f.write(json.dumps({'instruction': q, 'response': a}, ensure_ascii=False) + '\\n')\n","print(f'wrote {len(SAMPLE)} pairs to {DATA}')"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# 4 — Converter: JSON FAQs or Markdown FAQs -> the JSONL format above\n","# (Skip this cell if you already uploaded a .jsonl file.)\n","import re\n","def faqs_to_jsonl(faqs, out_path):\n","    n = 0\n","    with open(out_path, 'w') as f:\n","        for item in faqs:\n","            q = (item.get('question') or item.get('q') or '').strip()\n","            a = (item.get('answer') or item.get('a') or '').strip()\n","            if q and a:\n","                f.write(json.dumps({'instruction': q, 'response': a}, ensure_ascii=False) + '\\n')\n","                n += 1\n","    return n\n","\n","# Example: paste a business's real FAQs here as a Python list and run.\n","# MY_FAQS = [{'question': '...', 'answer': '...'}, ...]\n","# print('converted:', faqs_to_jsonl(MY_FAQS, 'business_data.jsonl'), 'pairs')\n","print('converter ready — define MY_FAQS above and uncomment to use it.')\n","print('validating', DATA, '...')\n","rows = [json.loads(l) for l in open(DATA) if l.strip()]\n","assert all(set(r) == {'instruction', 'response'} for r in rows), 'bad row format'\n","print(f'OK: {len(rows)} valid pairs')"]},{"cell_type":"markdown","metadata":{},"source":["## 5 — Train (LoRA, r=8)\n","\n","- Base model: `Qwen/Qwen2.5-0.5B-Instruct` (~1 GB, any Colab GPU).\n","  Got an L4/A100? Switch `MODEL` to `Qwen/Qwen2.5-1.5B-Instruct`.\n","- `MAX_STEPS = 30` is the demo default (12 pairs, ~2–3 min on a T4).\n","  For a real business dataset use epochs instead: 50 pairs → ~60 steps,\n","  200 pairs → ~200 steps. More steps on tiny data = memorisation, not\n","  learning — stop when the loss curve flattens.\n","- Loss is computed on the answer only (the question tokens are masked),\n","  so the model learns the business's answers, not how to parrot questions."]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# 5 — LoRA fine-tune (same code as repo colab-ft/train_lora.py)\n","from datasets import Dataset\n","from peft import LoraConfig\n","from transformers import AutoModelForCausalLM, AutoTokenizer\n","from trl import SFTConfig, SFTTrainer\n","\n","MODEL = 'Qwen/Qwen2.5-0.5B-Instruct'  # or 'Qwen/Qwen2.5-1.5B-Instruct'\n","MAX_STEPS = 30\n","OUTPUT_DIR = './vq-ft'\n","\n","tok = AutoTokenizer.from_pretrained(MODEL)\n","if tok.pad_token is None:\n","    tok.pad_token = tok.eos_token\n","\n","rows = [json.loads(l) for l in open(DATA) if l.strip()]\n","prompts, completions = [], []\n","for r in rows:\n","    prompts.append(tok.apply_chat_template([{'role': 'user', 'content': r['instruction']}], tokenize=False, add_generation_prompt=True))\n","    completions.append(r['response'] + tok.eos_token)\n","ds = Dataset.from_dict({'prompt': prompts, 'completion': completions})\n","print(f'training pairs: {len(rows)}')\n","\n","model = AutoModelForCausalLM.from_pretrained(MODEL, dtype=torch.bfloat16, trust_remote_code=False)\n","model.config.use_cache = False\n","\n","peft_config = LoraConfig(r=8, lora_alpha=16, lora_dropout=0.05, bias='none',\n","                         task_type='CAUSAL_LM',\n","                         target_modules=['q_proj', 'k_proj', 'v_proj', 'o_proj',\n","                                       'gate_proj', 'up_proj', 'down_proj'])\n","sft_config = SFTConfig(output_dir=OUTPUT_DIR, per_device_train_batch_size=1,\n","                       gradient_accumulation_steps=4, max_steps=MAX_STEPS,\n","                       learning_rate=2e-4, logging_steps=1, save_strategy='no',\n","                       report_to='none', packing=False, max_length=256,\n","                       bf16=False, dataset_num_proc=1, seed=42)\n","trainer = SFTTrainer(model=model, args=sft_config, train_dataset=ds, peft_config=peft_config)\n","trainer.train()\n","trainer.save_model(OUTPUT_DIR + '/adapter')\n","tok.save_pretrained(OUTPUT_DIR + '/adapter')\n","print('adapter saved:', OUTPUT_DIR + '/adapter')"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# 6 — Merge LoRA into the base model + save (adapter stays separate too)\n","merged = trainer.model.merge_and_unload()\n","merged.save_pretrained(OUTPUT_DIR + '/merged')\n","tok.save_pretrained(OUTPUT_DIR + '/merged')\n","print('merged model saved:', OUTPUT_DIR + '/merged')\n","!du -sh vq-ft/adapter vq-ft/merged\n","# Keep a copy: mount Drive first (uncomment) or download the adapter zip.\n","# from google.colab import drive; drive.mount('/content/drive')\n","# !cp -r vq-ft/adapter '/content/drive/MyDrive/vq-ft-adapter'\n","# !cp -r vq-ft/merged '/content/drive/MyDrive/vq-ft-merged'  # ~1GB (0.5B)"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# 7 — Serve the FINE-TUNED model: OpenAI-compatible API on :8000\n","import threading, time\n","from fastapi import FastAPI\n","import uvicorn\n","\n","FT_MODEL = OUTPUT_DIR + '/merged'\n","ft_tok = AutoTokenizer.from_pretrained(FT_MODEL)\n","ft_model = AutoModelForCausalLM.from_pretrained(FT_MODEL, dtype=torch.bfloat16, trust_remote_code=False)\n","ft_model.eval()\n","print('fine-tuned model loaded:', FT_MODEL)\n","\n","app = FastAPI(title='VQ Colab FT LLM')\n","\n","@app.get('/health')\n","def health():\n","    return {'ok': True, 'model': 'vq-ft', 'fine_tuned': True,\n","            'gpu': torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'cpu'}\n","\n","@app.get('/v1/models')\n","def models():\n","    return {'object': 'list', 'data': [{'id': 'vq-ft', 'object': 'model', 'owned_by': 'vq-colab-ft'}]}\n","\n","@app.post('/v1/chat/completions')\n","def chat_completions(payload: dict):\n","    msgs = payload.get('messages', [])\n","    max_tokens = int(payload.get('max_tokens', 300))\n","    temp = float(payload.get('temperature', 0.7))\n","    text = ft_tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)\n","    inputs = ft_tok(text, return_tensors='pt').to(ft_model.device)\n","    with torch.no_grad():\n","        out = ft_model.generate(**inputs, max_new_tokens=max_tokens,\n","                              temperature=temp if temp > 0 else None,\n","                              do_sample=temp > 0, pad_token_id=ft_tok.eos_token_id)\n","    reply = ft_tok.decode(out[0][inputs['input_ids'].shape[1]:], skip_special_tokens=True).strip()\n","    return {'id': 'chatcmpl-colab-ft', 'object': 'chat.completion', 'model': 'vq-ft',\n","            'choices': [{'index': 0, 'message': {'role': 'assistant', 'content': reply}, 'finish_reason': 'stop'}]}\n","\n","threading.Thread(target=lambda: uvicorn.run(app, host='127.0.0.1', port=8000, log_level='error'), daemon=True).start()\n","time.sleep(3)\n","import urllib.request\n","print(urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=10).read().decode())\n","print('FT API up on :8000')"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# 8 — Public URL via Cloudflare quick tunnel (no account, no token)\n","!curl -fsSL https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb -o /tmp/cloudflared.deb\n","!dpkg -i /tmp/cloudflared.deb 2>/dev/null || (apt-get install -f -y >/dev/null 2>&1)\n","import subprocess, re, time as _t\n","proc = subprocess.Popen(['cloudflared', 'tunnel', '--url', 'http://127.0.0.1:8000'],\n","                       stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)\n","url = None\n","for _ in range(60):\n","    line = proc.stdout.readline()\n","    m = re.search(r'https://[a-z0-9.-]*trycloudflare\\.com', line or '')\n","    if m:\n","        url = m.group(0); break\n","    _t.sleep(1)\n","print('PUBLIC URL:', url)\n","print('Set on the agent host:  export COLAB_FT_API_BASE=' + str(url) + '/v1')\n","print('Test: curl -s $COLAB_FT_API_BASE/models')"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# 9 — Live test through the public URL: the fine-tuned fact must come back\n","import urllib.request, json as _json\n","def ask(question):\n","    body = _json.dumps({'model': 'vq-ft', 'messages': [\n","        {'role': 'user', 'content': question}], 'max_tokens': 60, 'temperature': 0}).encode()  # short replies stay cleaner: 0.5B rambles past ~60 tokens (verified 28 Nov)\n","    req = urllib.request.Request(url + '/v1/chat/completions', data=body,\n","                               headers={'Content-Type': 'application/json'}, method='POST')\n","    return _json.loads(urllib.request.urlopen(req, timeout=120).read().decode())['choices'][0]['message']['content']\n","\n","r1 = ask('How much does the VisionQuantech AI receptionist cost?')\n","print('Q: How much does the AI receptionist cost?')\n","print('FT REPLY:', r1)\n","print('CHECK $99 in reply:', '$99' in r1, ' (True = the fine-tune taught the business fact)')\n","print()\n","r2 = ask('How long does setup take?')\n","print('Q: How long does setup take?')\n","print('FT REPLY:', r2)\n","print('CHECK 15 min in reply:', '15' in r2)"]},{"cell_type":"markdown","metadata":{},"source":["## Using it from the agents\n","\n","On the agent host (A1 #1 or anywhere `llm_providers.py` runs):\n","\n","```bash\n","export COLAB_FT_API_BASE=\"https://<your-tunnel>.trycloudflare.com/v1\"\n","python3 -c \"from llm_providers import chat; print(chat('You are the VisionQuantech AI receptionist.', 'How much does it cost?'))\"\n","```\n","\n","`chat()` tries `colab-ft` first while `COLAB_FT_API_BASE` is set, then\n","the base `colab` endpoint, then Groq → Gemini → Pollinations. When\n","the Colab runtime dies, unset the variable and the chain behaves exactly\n","as before.\n","\n","## Exporting the fine-tune so it survives the runtime (do this before disconnecting)\n","\n","The adapter is the only thing you must keep — ~10–20 MB.\n","\n","1. **Drive** (easiest): uncomment the `cp -r` lines in cell 6.\n","2. **To the VM** (A1 #1, 129.154.234.213): zip the adapter, `scp` it to\n","   the VM, then serve it there with the repo script:\n","   `python3 serve_ft.py --model <adapter-unpacked-over-base>` — or\n","   load base + adapter with PEFT (`PeftModel.from_pretrained`) and serve\n","   the same FastAPI app. No GPU needed on the VM for 0.5B (CPU works,\n","   just slower). This export step is documented, not automatic — run\n","   it only when you want the fine-tune to outlive the Colab session.\n","3. **Ollama (optional):** create a Modelfile from the merged model\n","   (`FROM ./vq-ft/merged`) and `ollama create vq-ft -f Modelfile` on a\n","   machine with Ollama. 0.5B runs on CPU RAM.\n","\n","## Stopping\n","\n","Runtime → Disconnect and delete runtime. The tunnel URL dies with\n","it. Without the exported adapter, the fine-tune is gone — the base\n","model re-downloads (~1 GB) and training re-runs (~3 min) on the next run."]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.11"}},"nbformat":4,"nbformat_minor":5}