{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# BTL-1 Colab Training Notebook\n", "\n", "This notebook is the release-check companion for BTL-1.\n", "\n", "It should keep us aligned on the real ambition:\n", "- open weights\n", "- published dataset\n", "- reproducible training\n", "- local multi-tool execution on consumer hardware\n", "- a clean handoff from data to adapter to eval to publish" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import subprocess\n", "import sys\n", "from pathlib import Path\n", "\n", "def pip_install(*packages: str) -> None:\n", " cmd = [sys.executable, \"-m\", \"pip\", \"install\", \"-q\", *packages]\n", " subprocess.check_call(cmd)\n", "\n", "pip_install(\n", " \"datasets\",\n", " \"transformers\",\n", " \"accelerate\",\n", " \"peft\",\n", " \"trl\",\n", " \"bitsandbytes\",\n", " \"sentencepiece\",\n", ")\n", "\n", "try:\n", " from google.colab import drive\n", " drive.mount(\"/content/drive\")\n", "except Exception as exc:\n", " print(f\"drive mount skipped: {exc}\")\n", "\n", "print(\"Colab stack ready.\")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## What Success Looks Like\n", "\n", "By the end of the run, we want to be able to say:\n", "\n", "- the dataset is clean and reproducible\n", "- the training recipe is fixed, not hand-wavy\n", "- the adapter exports cleanly\n", "- the quantized model still follows tool-chain format\n", "- the eval numbers can be reproduced by someone else without a tour guide" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from pathlib import Path\n", "\n", "def locate_btl_root() -> Path:\n", " here = Path.cwd().resolve()\n", " for candidate in [here, *here.parents]:\n", " if (candidate / \"BTL-1.md\").exists():\n", " return candidate\n", " for child in candidate.iterdir():\n", " if child.is_dir() and (child / \"BTL-1.md\").exists():\n", " return child\n", " raise FileNotFoundError(\"Could not find BTL-1.md in or above the current workspace\")\n", "\n", "project = locate_btl_root()\n", "data_dir = project / \"data\"\n", "\n", "print(f\"project root: {project}\")\n", "print(\"key artifacts:\")\n", "for rel in [\n", " \"BTL-1.md\",\n", " \"data/raw/train.jsonl\",\n", " \"data/raw/eval.jsonl\",\n", " \"data/final/train.jsonl\",\n", " \"data/final/eval.jsonl\",\n", " \"data/templates\",\n", " \"data/generators/template-generator.mjs\",\n", "]:\n", " path = project / rel\n", " status = \"ok\" if path.exists() else \"missing\"\n", " print(f\"- {rel}: {status}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from datasets import load_dataset\n", "\n", "train_ds = load_dataset(\"json\", data_files=str(project / \"data\" / \"final\" / \"train.jsonl\"), split=\"train\")\n", "eval_ds = load_dataset(\"json\", data_files=str(project / \"data\" / \"final\" / \"eval.jsonl\"), split=\"train\")\n", "\n", "print(f\"train rows: {len(train_ds)}\")\n", "print(f\"eval rows: {len(eval_ds)}\")\n", "print(f\"columns: {train_ds.column_names}\")\n", "print(train_ds[0][\"messages\"][0][\"content\"][:120])\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## QLoRA Training\n", "\n", "This is the part that turns the cleaned corpus into something we can actually ship.\n", "\n", "The defaults below are tuned for Colab A100 runs, but the `smoke_rows` switch lets us do a short sanity pass before burning the full budget.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, DataCollatorForLanguageModeling, TrainingArguments, Trainer\n", "from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training, PeftModel\n", "import torch\n", "\n", "base_model_name = \"Qwen/Qwen2.5-7B-Instruct\"\n", "artifact_dir = project / \"artifacts\" / \"qlora-adapter\"\n", "artifact_dir.mkdir(parents=True, exist_ok=True)\n", "\n", "# Set this to a small integer for a cheap Colab smoke test. Leave it None for the full run.\n", "smoke_rows = None\n", "# Keep periodic eval small so the full run stays inside a sane budget.\n", "eval_rows = 500\n", "max_seq_length = 4096\n", "train_batch_size = 4\n", "eval_batch_size = 16\n", "grad_accum = 2\n", "epochs = 1\n", "learning_rate = 2e-4\n", "\n", "tokenizer = AutoTokenizer.from_pretrained(base_model_name, trust_remote_code=True, use_fast=True)\n", "if tokenizer.pad_token is None:\n", " tokenizer.pad_token = tokenizer.eos_token\n", "tokenizer.padding_side = \"right\"\n", "\n", "bnb_config = BitsAndBytesConfig(\n", " load_in_4bit=True,\n", " bnb_4bit_quant_type=\"nf4\",\n", " bnb_4bit_use_double_quant=True,\n", " bnb_4bit_compute_dtype=torch.bfloat16,\n", ")\n", "model = AutoModelForCausalLM.from_pretrained(\n", " base_model_name,\n", " trust_remote_code=True,\n", " quantization_config=bnb_config,\n", " device_map=\"auto\",\n", ")\n", "model = prepare_model_for_kbit_training(model)\n", "model.config.use_cache = False\n", "model.gradient_checkpointing_enable()\n", "\n", "lora_config = LoraConfig(\n", " r=64,\n", " lora_alpha=128,\n", " lora_dropout=0.05,\n", " bias=\"none\",\n", " task_type=\"CAUSAL_LM\",\n", " target_modules=[\"q_proj\", \"k_proj\", \"v_proj\", \"o_proj\", \"gate_proj\", \"up_proj\", \"down_proj\"],\n", ")\n", "model = get_peft_model(model, lora_config)\n", "model.print_trainable_parameters()\n", "\n", "def trim_rows(ds):\n", " if smoke_rows is None:\n", " return ds\n", " return ds.select(range(min(smoke_rows, len(ds))))\n", "\n", "train_slice = trim_rows(train_ds)\n", "eval_slice = trim_rows(eval_ds)\n", "eval_monitor_slice = eval_slice.select(range(min(eval_rows, len(eval_slice))))\n", "\n", "def render_messages(messages):\n", " return tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=False)\n", "\n", "def to_text(batch):\n", " return {\"text\": [render_messages(messages) for messages in batch[\"messages\"]]}\n", "\n", "train_text = train_slice.map(to_text, batched=True, remove_columns=train_slice.column_names)\n", "eval_text = eval_monitor_slice.map(to_text, batched=True, remove_columns=eval_monitor_slice.column_names)\n", "\n", "print(train_text[0][\"text\"][:240])\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def tokenize_batch(batch):\n", " return tokenizer(batch[\"text\"], truncation=True, max_length=max_seq_length, padding=False)\n", "\n", "train_tok = train_text.map(tokenize_batch, batched=True, remove_columns=train_text.column_names)\n", "eval_tok = eval_text.map(tokenize_batch, batched=True, remove_columns=eval_text.column_names)\n", "collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False)\n", "\n", "training_args = TrainingArguments(\n", " output_dir=str(artifact_dir / \"trainer\"),\n", " num_train_epochs=epochs,\n", " per_device_train_batch_size=train_batch_size,\n", " per_device_eval_batch_size=eval_batch_size,\n", " gradient_accumulation_steps=grad_accum,\n", " eval_strategy=\"steps\",\n", " eval_steps=500,\n", " save_strategy=\"steps\",\n", " save_steps=500,\n", " load_best_model_at_end=True,\n", " metric_for_best_model=\"eval_loss\",\n", "\n", " learning_rate=learning_rate,\n", " warmup_ratio=0.03,\n", " lr_scheduler_type=\"cosine\",\n", " logging_steps=10,\n", " save_total_limit=2,\n", " bf16=torch.cuda.is_available(),\n", " fp16=False,\n", " optim=\"paged_adamw_8bit\",\n", " report_to=\"none\",\n", " gradient_checkpointing=True,\n", " remove_unused_columns=False,\n", ")\n", "\n", "trainer = Trainer(\n", " model=model,\n", " args=training_args,\n", " train_dataset=train_tok,\n", " eval_dataset=eval_tok,\n", " data_collator=collator,\n", ")\n", "\n", "train_result = trainer.train()\n", "trainer.save_state()\n", "print(train_result)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Adapter Export\n", "\n", "This is the artifact we hand off after training: the LoRA adapter, tokenizer files, and a quick reload check so we do not ship a busted checkpoint.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "adapter_dir = artifact_dir / \"adapter\"\n", "adapter_dir.mkdir(parents=True, exist_ok=True)\n", "\n", "model.save_pretrained(adapter_dir)\n", "tokenizer.save_pretrained(adapter_dir)\n", "\n", "reloaded_base = AutoModelForCausalLM.from_pretrained(\n", " base_model_name,\n", " trust_remote_code=True,\n", " quantization_config=bnb_config,\n", " device_map=\"auto\",\n", ")\n", "reloaded = PeftModel.from_pretrained(reloaded_base, adapter_dir)\n", "\n", "print(\"adapter files:\")\n", "for item in sorted(adapter_dir.iterdir()):\n", " print(\"-\", item.name)\n", "\n", "print(\"reload ok:\", type(reloaded).__name__)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Release Gates\n", "\n", "The notebook is not just a scratchpad. It is supposed to answer a few hard questions before we call a run shippable:\n", "\n", "1. Does the raw corpus parse cleanly?\n", "2. Does the final corpus stay distinct from raw?\n", "3. Do the templates match the cleaned schema?\n", "4. Can we summarize the exact training recipe without guessing?\n", "5. Could another person rerun the same flow from a fresh checkout?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import hashlib\n", "import json\n", "import re\n", "\n", "allowed_tools = {\n", " \"file_search\", \"read_file\", \"write_file\", \"email\", \"web_search\",\n", " \"browse\", \"clipboard\", \"shell_command\", \"notes\", \"reasoning\",\n", "}\n", "\n", "def sha256(path: Path) -> str:\n", " return hashlib.sha256(path.read_bytes()).hexdigest()\n", "\n", "def audit_jsonl(path: Path) -> dict:\n", " lines = 0\n", " malformed = 0\n", " email_missing_body = 0\n", " file_search_name = 0\n", " write_ppt = 0\n", " unknown_tools = 0\n", " multi_tool = 0\n", "\n", " with path.open(\"r\", encoding=\"utf-8\") as handle:\n", " for raw_line in handle:\n", " line = raw_line.strip()\n", " if not line:\n", " continue\n", " lines += 1\n", " try:\n", " row = json.loads(line)\n", " except json.JSONDecodeError:\n", " malformed += 1\n", " continue\n", "\n", " assistant = next((msg for msg in row.get(\"messages\", []) if msg.get(\"role\") == \"assistant\"), None)\n", " if not assistant:\n", " malformed += 1\n", " continue\n", "\n", " content_clean = re.sub(r'.*?\\s*', '', assistant[\"content\"], flags=re.DOTALL).strip()\n", " payload = json.loads(content_clean)\n", " if isinstance(payload, list) and len(payload) > 1:\n", " multi_tool += 1\n", "\n", " for step in payload:\n", " if step.get(\"tool\") not in allowed_tools:\n", " unknown_tools += 1\n", " params = step.get(\"params\") or {}\n", " if step.get(\"tool\") == \"email\" and \"body\" not in params:\n", " email_missing_body += 1\n", " if step.get(\"tool\") == \"file_search\" and \"name\" in params:\n", " file_search_name += 1\n", " if step.get(\"tool\") == \"write_file\" and isinstance(params.get(\"path\"), str) and params[\"path\"].endswith((\".ppt\", \".pptx\")):\n", " write_ppt += 1\n", "\n", " return {\n", " \"lines\": lines,\n", " \"malformed\": malformed,\n", " \"unknown_tools\": unknown_tools,\n", " \"email_missing_body\": email_missing_body,\n", " \"file_search_name\": file_search_name,\n", " \"write_ppt\": write_ppt,\n", " \"multi_tool_pct\": round((multi_tool / lines) * 100, 2) if lines else 0.0,\n", " \"sha256\": sha256(path)[:16],\n", " }\n", "\n", "for label, rel in {\n", " \"raw/train\": \"data/raw/train.jsonl\",\n", " \"raw/eval\": \"data/raw/eval.jsonl\",\n", " \"final/train\": \"data/final/train.jsonl\",\n", " \"final/eval\": \"data/final/eval.jsonl\",\n", "}.items():\n", " report = audit_jsonl(project / rel)\n", " print(f\"{label:11} lines={report['lines']:7} multi={report['multi_tool_pct']:5.2f}% sha={report['sha256']}\")\n", " print(f\" malformed={report['malformed']} unknown={report['unknown_tools']} email_missing_body={report['email_missing_body']} file_search_name={report['file_search_name']} write_ppt={report['write_ppt']}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Training Recipe\n", "\n", "The notebook should mirror the actual plan from `BTL-1.md`:\n", "\n", "- base model: Qwen 2.5 7B\n", "- method: QLoRA\n", "- LoRA shape: rank 64, alpha 128\n", "- platform: Colab A100\n", "- output: adapter first, then GGUF for local inference\n", "- goal: a model that can keep the JSON tool-chain format intact under pressure\n", "\n", "The important part is not the marketing line. It is the repeatable sequence: data check, train, export, quantize, smoke test, eval, publish." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "training_plan = {\n", " \"base_model\": \"Qwen 2.5 7B\",\n", " \"method\": \"QLoRA\",\n", " \"lora_rank\": 64,\n", " \"lora_alpha\": 128,\n", " \"epochs\": 1,\n", " \"platform\": \"Colab A100\",\n", " \"target_outputs\": [\"LoRA adapter\", \"Q4_K_M GGUF\"],\n", " \"success_metric\": \"tool-chain accuracy stays stable after export\",\n", "}\n", "\n", "for key, value in training_plan.items():\n", " print(f\"{key}: {value}\")\n", "\n", "print(\"\\nrun order:\")\n", "print(\"1. validate data and templates\")\n", "print(\"2. train adapter\")\n", "print(\"3. export and quantize\")\n", "print(\"4. smoke test the local agent wrapper\")\n", "print(\"5. run tool-chain and reasoning evals\")\n", "print(\"6. package weights, data, recipe, and notes for publish\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Handoff Standard\n", "\n", "When this notebook gets used in anger, the handoff should include:\n", "\n", "- what was changed\n", "- where the artifacts live\n", "- what validation ran\n", "- what still needs human judgment\n", "\n", "If the run is not ready to publish, say why in one sentence and name the next unblocker." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Adapter Eval\n", "\n", "Run the trained adapter against held-out eval examples. Measures:\n", "- exact tool match (right tool in right order)\n", "- param field presence (required params exist)\n", "- JSON parsability (model outputs valid JSON)\n", "\n", "This is the gate before GGUF export. If accuracy is below 80%, investigate before shipping." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import json\n", "import re\n", "\n", "eval_samples = eval_slice.select(range(min(200, len(eval_slice))))\n", "results = []\n", "\n", "for i, sample in enumerate(eval_samples):\n", " messages = sample[\"messages\"]\n", " prompt = tokenizer.apply_chat_template(messages[:-1], tokenize=False, add_generation_prompt=True)\n", " expected_raw = re.sub(r'.*?\\s*', '', messages[-1][\"content\"], flags=re.DOTALL).strip()\n", " expected = json.loads(expected_raw)\n", "\n", " inputs = tokenizer(prompt, return_tensors=\"pt\", truncation=True, max_length=max_seq_length).to(model.device)\n", " with torch.no_grad():\n", " outputs = model.generate(**inputs, max_new_tokens=512, temperature=0.0, do_sample=False)\n", " decoded = tokenizer.decode(outputs[0][inputs.input_ids.shape[1]:], skip_special_tokens=True).strip()\n", "\n", " try:\n", " predicted_raw = re.sub(r'.*?\\s*', '', decoded, flags=re.DOTALL).strip()\n", " predicted = json.loads(predicted_raw)\n", " is_valid_json = True\n", " except (json.JSONDecodeError, ValueError):\n", " predicted = []\n", " is_valid_json = False\n", "\n", " if not isinstance(predicted, list):\n", " predicted = [predicted] if isinstance(predicted, dict) else []\n", " is_valid_json = True\n", "\n", " correct_tools = len(expected) == len(predicted) and all(\n", " e[\"tool\"] == p.get(\"tool\") for e, p in zip(expected, predicted)\n", " )\n", " param_fields_ok = all(\n", " p.get(\"params\") is not None and len(p[\"params\"]) > 0\n", " for p in predicted\n", " ) if predicted else False\n", "\n", " results.append({\n", " \"valid_json\": is_valid_json,\n", " \"correct_tools\": correct_tools,\n", " \"param_fields_ok\": param_fields_ok,\n", " \"expected\": expected,\n", " \"predicted\": predicted,\n", " \"raw_output\": decoded[:240],\n", " })\n", "\n", "json_ok = sum(1 for r in results if r[\"valid_json\"])\n", "tool_ok = sum(1 for r in results if r[\"correct_tools\"])\n", "param_ok = sum(1 for r in results if r[\"param_fields_ok\"])\n", "total = len(results)\n", "\n", "print(f\"eval samples: {total}\")\n", "print(f\"valid JSON: {json_ok}/{total} ({100*json_ok//total}%)\")\n", "print(f\"tool match: {tool_ok}/{total} ({100*tool_ok//total}%)\")\n", "print(f\"params ok: {param_ok}/{total} ({100*param_ok//total}%)\")\n", "print()\n", "for r in results[:3]:\n", " print(\"EXP:\", json.dumps(r[\"expected\"]))\n", " print(\"GOT:\", json.dumps(r[\"predicted\"]))\n", " print()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## GGUF Export\n", "\n", "Convert the merged model to Q4_K_M GGUF for local inference via llama.cpp.\n", "\n", "Requires `llama.cpp` to be installed. We clone it briefly, build the quantize tool, and export.\n", "The output GGUF goes to `artifacts/btl-1-q4_k_m.gguf`.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "import subprocess\n", "import shutil\n", "\n", "gguf_dir = project / \"artifacts\" / \"gguf\"\n", "gguf_dir.mkdir(parents=True, exist_ok=True)\n", "\n", "# Step 1: merge LoRA into base model\n", "merge_dir = project / \"artifacts\" / \"merged\"\n", "merge_dir.mkdir(parents=True, exist_ok=True)\n", "\n", "merged_model = reloaded.merge_and_unload()\n", "merged_model.save_pretrained(merge_dir)\n", "tokenizer.save_pretrained(merge_dir)\n", "print(\"merged model saved to\", merge_dir)\n", "\n", "# Step 2: convert to FP16 GGUF using llama.cpp convert script\n", "llama_cpp_dir = project / \"artifacts\" / \"llama.cpp\"\n", "if not llama_cpp_dir.exists():\n", " subprocess.check_call([\"git\", \"clone\", \"--depth\", \"1\", \"https://github.com/ggml-org/llama.cpp.git\", str(llama_cpp_dir)])\n", "\n", "convert_py = llama_cpp_dir / \"convert_hf_to_gguf.py\"\n", "fp16_gguf = gguf_dir / \"btl-1-fp16.gguf\"\n", "\n", "subprocess.check_call([\n", " sys.executable, str(convert_py),\n", " str(merge_dir),\n", " \"--outfile\", str(fp16_gguf),\n", " \"--outtype\", \"f16\",\n", "])\n", "print(\"FP16 GGUF:\", fp16_gguf)\n", "\n", "# Step 3: quantize to Q4_K_M\n", "q4_gguf = gguf_dir / \"btl-1-q4_k_m.gguf\"\n", "quantize_bin = llama_cpp_dir / \"build\" / \"bin\" / \"quantize\"\n", "\n", "if quantize_bin.exists():\n", " subprocess.check_call([str(quantize_bin), str(fp16_gguf), str(q4_gguf), \"Q4_K_M\"])\n", " print(\"Q4_K_M GGUF:\", q4_gguf)\n", " print(\"size MB:\", round(q4_gguf.stat().st_size / 1e6, 1))\n", "else:\n", " print(\"quantize binary not found, building llama.cpp...\")\n", " build_dir = llama_cpp_dir / \"build\"\n", " subprocess.check_call([\"cmake\", \"-B\", str(build_dir), \"-S\", str(llama_cpp_dir), \"-DLLAMA_CUDA=ON\"], cwd=str(llama_cpp_dir))\n", " subprocess.check_call([\"cmake\", \"--build\", str(build_dir), \"--config\", \"Release\", \"--target\", \"quantize\"], cwd=str(llama_cpp_dir))\n", " subprocess.check_call([str(quantize_bin), str(fp16_gguf), str(q4_gguf), \"Q4_K_M\"])\n", " print(\"Q4_K_M GGUF:\", q4_gguf)\n", " print(\"size MB:\", round(q4_gguf.stat().st_size / 1e6, 1))\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Final Benchmark Suite\n", "\n", "Run the saved adapter against BTL-1 held-out eval and any external benchmark JSONL files we have mounted. Missing files are skipped, which keeps the notebook usable in Colab without extra setup.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import sys\n", "import os\n", "\n", "sys.path.insert(0, str(project))\n", "from eval.run_all import run_suite, render_suite\n", "\n", "def generate_text(prompt: str, max_new_tokens: int = 512) -> str:\n", " inputs = tokenizer(prompt, return_tensors=\"pt\", truncation=True, max_length=max_seq_length).to(reloaded.device)\n", " with torch.no_grad():\n", " outputs = reloaded.generate(**inputs, max_new_tokens=max_new_tokens, temperature=0.0, do_sample=False)\n", " return tokenizer.decode(outputs[0][inputs.input_ids.shape[1]:], skip_special_tokens=True).strip()\n", "\n", "suite_limit = int(os.environ.get(\"BTL_EVAL_LIMIT\", \"0\")) or None\n", "suite = run_suite(generate_text, project_root=project, tokenizer=tokenizer, limit=suite_limit)\n", "print(render_suite(suite))\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.11" } }, "nbformat": 4, "nbformat_minor": 5 }