{ "nbformat": 4, "nbformat_minor": 5, "metadata": { "kernelspec": { "name": "python3", "display_name": "Python 3", "language": "python" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Lab 5.4 · From predictor to assistant\n", "\n", "**Goal:** see what instruction tuning changes in a real model, then do it yourself. You will put the\n", "same prompts to a base model and its instruction-tuned sibling, print the chat template as tokens,\n", "build the loss mask that trains only on the answer, write LoRA by hand on `nn.Linear`, fine-tune a\n", "0.5 B-parameter model on a small instruction set that **you** (the book's author) wrote, measure what\n", "full fine-tuning and LoRA at three ranks cost in memory and time, run a tiny DPO step, and break\n", "fine-tuning three ways.\n", "\n", "**The model.** `Qwen/Qwen2.5-0.5B-Instruct` and its base model `Qwen/Qwen2.5-0.5B`: both Apache-2.0,\n", "no login needed, 494,032,768 parameters, the same tokenizer and architecture. Revisions are pinned\n", "below so everybody loads the same weights.\n", "\n", "**The data.** A narrow task, support-ticket triage, with 160 training and 48 held-out examples that\n", "are generated from sentences written for this book (no copyrighted or scraped text; see the data cell).\n", "The DPO pairs (20 training, 8 held-out) are also written for the book.\n", "\n", "**Runs on:** a CUDA GPU with 12 GB or more (reference run: the book's RTX 3060 12 GB). A free Colab or\n", "Kaggle T4 (16 GB) should also fit everything except possibly the full fine-tuning row, which the code\n", "catches if it runs out of memory; the T4 has no bfloat16, so the code falls back to float16 with a loss\n", "scaler (that path was **not** run on a T4 for this book). There is no CPU variant: a 0.5 B model on a\n", "CPU takes far too long.\n", "\n", "**Versions tested:** printed by the last cell." ], "id": "lab-5-4-finetune-00" }, { "cell_type": "code", "metadata": {}, "source": [ "import csv\n", "import gc\n", "import json\n", "import math\n", "import os\n", "import pathlib\n", "import platform\n", "import random\n", "import re\n", "import statistics\n", "import sys\n", "import time\n", "\n", "import torch\n", "import torch.nn as nn\n", "import torch.nn.functional as F\n", "import transformers\n", "from transformers import AutoModelForCausalLM, AutoTokenizer\n", "\n", "SMOKE = bool(os.environ.get(\"LAB54_SMOKE\")) # set to 1 for a very short run that checks the code only\n", "assert torch.cuda.is_available(), \"this lab needs a CUDA GPU (see the Runs-on note above)\"\n", "DEVICE = \"cuda\"\n", "cc_major = torch.cuda.get_device_capability()[0]\n", "AMP_DTYPE = torch.bfloat16 if cc_major >= 8 else torch.float16 # Ampere (RTX 3060) has bfloat16, a T4 does not\n", "if os.environ.get(\"LAB54_DTYPE\") == \"float16\":\n", " AMP_DTYPE = torch.float16 # to test the T4 path on any card\n", "GPU_NAME = torch.cuda.get_device_name(0)\n", "print(\"GPU:\", GPU_NAME, \"| compute dtype:\", AMP_DTYPE, \"| smoke run:\", SMOKE)\n", "\n", "INSTRUCT = (\"Qwen/Qwen2.5-0.5B-Instruct\", \"7ae557604adf67be50417f59c2c2f167def9a775\")\n", "BASE = (\"Qwen/Qwen2.5-0.5B\", \"060db6499f32faf8b98477b0a26969ef7d8b9987\")\n", "\n", "\n", "def out_dir():\n", " for candidate in (pathlib.Path(\"data\"), pathlib.Path(\"../data\")):\n", " if candidate.is_dir():\n", " d = candidate / \"lab-5-4-finetune\"\n", " d.mkdir(parents=True, exist_ok=True)\n", " return d\n", " return pathlib.Path(\".\")\n", "\n", "\n", "def save_csv(name, header, rows):\n", " path = out_dir() / name\n", " with open(path, \"w\", newline=\"\") as f:\n", " w = csv.writer(f, lineterminator=\"\\n\")\n", " w.writerow(header)\n", " w.writerows(rows)\n", " print(f\"saved {path} ({len(rows)} rows)\")\n", "\n", "\n", "def load_model(spec, dtype):\n", " repo, rev = spec\n", " m = AutoModelForCausalLM.from_pretrained(repo, revision=rev, dtype=dtype).to(DEVICE)\n", " m.config.use_cache = True\n", " return m\n", "\n", "\n", "def free():\n", " \"\"\"Call after you dropped your last reference (x = None): give the GPU memory back.\"\"\"\n", " gc.collect()\n", " torch.cuda.empty_cache()\n", "\n", "\n", "tok = AutoTokenizer.from_pretrained(INSTRUCT[0], revision=INSTRUCT[1])\n", "tok_base = AutoTokenizer.from_pretrained(BASE[0], revision=BASE[1])\n", "tok.padding_side = \"left\" # generation pads on the left; training pads on the right by hand\n", "IM_START = tok.convert_tokens_to_ids(\"<|im_start|>\")\n", "IM_END = tok.convert_tokens_to_ids(\"<|im_end|>\")\n", "EOT = tok.convert_tokens_to_ids(\"<|endoftext|>\")\n", "EOS_IDS = [IM_END, EOT]\n", "PAD_ID = tok.pad_token_id\n", "print(\"special ids: <|im_start|>\", IM_START, \"| <|im_end|>\", IM_END, \"| <|endoftext|>\", EOT, \"| pad\", PAD_ID)\n", "print(\"same vocabulary in base and instruct:\", tok.get_vocab() == tok_base.get_vocab())\n", "print(\"same chat template in base and instruct:\", tok.chat_template == tok_base.chat_template)\n", "print(\"end-of-sequence token: base\", tok_base.eos_token, \"| instruct\", tok.eos_token)\n", "probe_msg = [{\"role\": \"user\", \"content\": \"hi\"}]\n", "print(\"base template :\", repr(tok_base.apply_chat_template(probe_msg, tokenize=False, add_generation_prompt=True)))\n", "print(\"instruct template:\", repr(tok.apply_chat_template(probe_msg, tokenize=False, add_generation_prompt=True)))" ], "execution_count": null, "outputs": [], "id": "lab-5-4-finetune-01" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1 · Predict first\n", "\n", "Write your answers down before you run anything.\n", "\n", "1. A pretrained model **continues** text. Give it the question \"What is the capital of France?\" with\n", " no template. Will the base model answer it, or continue it somehow else? What will the\n", " instruction-tuned model do with the same raw text?\n", "2. A training example is ` `: about 60 tokens of prompt and 10 of\n", " answer. If you compute the loss on **every** token, what fraction of the loss comes from the answer?\n", "3. Qwen2.5-0.5B has 24 layers and hidden size 896. One `q_proj` layer is an `896 × 896` matrix. How many\n", " numbers does a LoRA update of rank `r = 8` add for that one layer? What fraction of the layer is\n", " that?\n", "4. Full fine-tuning with AdamW in mixed precision needs about 16 bytes per parameter (Ch 5.1). For\n", " 494 M parameters, how many GB is that, before any activation? Will it fit in 12 GB?\n", "5. LoRA freezes the weights. Roughly how much memory should it need, compared with full fine-tuning?\n", " Which part of the bill disappears?\n", "6. You fine-tune on 160 examples of one task. Will the model get **worse** at anything? How would you\n", " notice?" ], "id": "lab-5-4-finetune-02" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2 · Base model against instruction-tuned model\n", "\n", "Same prompts, same greedy decoding, two models. We first send the **raw text** (what a pure\n", "predictor sees), then the same question wrapped in the **chat template** (what an assistant sees)." ], "id": "lab-5-4-finetune-03" }, { "cell_type": "code", "metadata": {}, "source": [ "PROMPTS = [\n", " \"What is the capital of France?\",\n", " \"Write a haiku about rain.\",\n", " \"Explain what a GPU is in one sentence.\",\n", " \"Give me three tips for sleeping better.\",\n", " \"Translate 'good morning' into Indonesian.\",\n", "]\n", "\n", "\n", "def chat_text(user, system=None):\n", " \"\"\"The prompt the model sees: the chat template applied, ending where the assistant starts talking.\"\"\"\n", " msgs = ([{\"role\": \"system\", \"content\": system}] if system else []) + [{\"role\": \"user\", \"content\": user}]\n", " return tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)\n", "\n", "\n", "@torch.no_grad()\n", "def generate(model, prompts, max_new_tokens=32, bs=24, sample=False, seed=0):\n", " \"\"\"Greedy (or sampled at temperature 1) continuation. Returns [(text, stopped_by_end_token)].\"\"\"\n", " if sample:\n", " torch.manual_seed(seed)\n", " results = []\n", " for i in range(0, len(prompts), bs):\n", " chunk = prompts[i:i + bs]\n", " enc = tok(chunk, return_tensors=\"pt\", padding=True, add_special_tokens=False).to(DEVICE)\n", " kw = dict(do_sample=True, temperature=1.0, top_k=0, top_p=1.0) if sample else dict(do_sample=False)\n", " with torch.autocast(\"cuda\", dtype=AMP_DTYPE):\n", " o = model.generate(**enc, max_new_tokens=max_new_tokens, eos_token_id=EOS_IDS,\n", " pad_token_id=PAD_ID, repetition_penalty=1.0, **kw)\n", " L = enc[\"input_ids\"].shape[1]\n", " for j in range(len(chunk)):\n", " toks = o[j, L:].tolist()\n", " stop = next((k for k, t in enumerate(toks) if t in EOS_IDS), None)\n", " text = tok.decode(toks[:stop] if stop is not None else toks, skip_special_tokens=False)\n", " results.append((text, stop is not None))\n", " return results\n", "\n", "\n", "m_inst = load_model(INSTRUCT, torch.bfloat16)\n", "m_base = load_model(BASE, torch.bfloat16)\n", "print(\"parameters:\", sum(p.numel() for p in m_inst.parameters()), sum(p.numel() for p in m_base.parameters()))\n", "\n", "compare_rows = []\n", "for mode, build in ((\"raw text\", lambda p: p), (\"chat template\", chat_text)):\n", " prompts = [build(p) for p in PROMPTS]\n", " res = {\"base\": generate(m_base, prompts, 40), \"instruct\": generate(m_inst, prompts, 40)}\n", " for i, p in enumerate(PROMPTS):\n", " for name in (\"base\", \"instruct\"):\n", " text, stopped = res[name][i]\n", " compare_rows.append([mode, p, name, text, int(stopped)])\n", " print(f\"--- [{mode}] {p}\")\n", " for name in (\"base\", \"instruct\"):\n", " text, stopped = res[name][i]\n", " print(f\" {name:8s} {'(stops)' if stopped else '(keeps going)'}: {text!r}\")\n", "save_csv(\"base-vs-instruct.csv\", [\"input_mode\", \"prompt\", \"model\", \"output\", \"stopped_by_end_token\"], compare_rows)" ], "execution_count": null, "outputs": [], "id": "lab-5-4-finetune-04" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Questions: which of the four combinations behaves like an assistant? Which of them *stops* by itself\n", "(a model stops only when it writes an end token)? What does the base model do with the template?" ], "id": "lab-5-4-finetune-05" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3 · The chat template, as tokens\n", "\n", "A chat model never sees \"roles\". It sees one long string with **special tokens** that mark where each\n", "turn starts and ends. The template is a small program that builds that string from a list of messages." ], "id": "lab-5-4-finetune-06" }, { "cell_type": "code", "metadata": {}, "source": [ "msgs = [{\"role\": \"user\", \"content\": \"What is the capital of France?\"}]\n", "text = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)\n", "print(text)\n", "print(\"---- the same string with its newlines visible:\")\n", "print(repr(text))\n", "ids = tok(text, add_special_tokens=False)[\"input_ids\"]\n", "print(f\"\\n{len(ids)} tokens:\")\n", "for pos, i in enumerate(ids):\n", " print(f\"{pos:3d} {i:7d} {tok.decode([i])!r}\")\n", "print(\"\\nspecial tokens used:\", {t: tok.convert_tokens_to_ids(t) for t in (\"<|im_start|>\", \"<|im_end|>\")})" ], "execution_count": null, "outputs": [], "id": "lab-5-4-finetune-07" }, { "cell_type": "markdown", "metadata": {}, "source": [ "The prompt ends with `<|im_start|>assistant\\n`: that is the cue \"now you speak\". During training the\n", "answer follows, then `<|im_end|>`, which teaches the model to **stop**. Without that last token a model\n", "keeps writing until the length limit." ], "id": "lab-5-4-finetune-08" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4 · Loss masking: train only on the answer\n", "\n", "Supervised fine-tuning (SFT) is the pretraining loss again, next-token cross-entropy, on prompt/response\n", "pairs. One change: we compute the loss only on the **response** tokens. Positions we skip get the label\n", "`-100`, which PyTorch's `cross_entropy` ignores." ], "id": "lab-5-4-finetune-09" }, { "cell_type": "code", "metadata": {}, "source": [ "TASK = \"Triage this support message.\\n\\nMessage: {msg}\"\n", "\n", "\n", "def encode_example(user, response):\n", " \"\"\"token ids of prompt + response (+ end token), and where the response starts.\"\"\"\n", " prompt_ids = tok(chat_text(user), add_special_tokens=False)[\"input_ids\"]\n", " resp_ids = tok(response + \"<|im_end|>\", add_special_tokens=False)[\"input_ids\"]\n", " ids = prompt_ids + resp_ids\n", " # where the user's own text starts and ends (used later to measure the loss on prompt tokens)\n", " marker = \"<|im_start|>user\\n\"\n", " prefix = chat_text(user)\n", " ustart = len(tok(prefix[:prefix.index(marker) + len(marker)], add_special_tokens=False)[\"input_ids\"])\n", " uend = len(prompt_ids) - 5 # the prompt ends with <|im_end|> \\n <|im_start|> assistant \\n\n", " assert ids[uend] == IM_END\n", " return {\"user\": user, \"response\": response, \"ids\": ids, \"plen\": len(prompt_ids),\n", " \"ustart\": ustart, \"uend\": uend}\n", "\n", "\n", "demo = encode_example(TASK.format(msg=\"Hello, I was charged twice for my March subscription. This is urgent.\"),\n", " \"category=billing; urgency=high\")\n", "joint = tok(chat_text(demo[\"user\"]) + demo[\"response\"] + \"<|im_end|>\", add_special_tokens=False)[\"input_ids\"]\n", "print(\"tokenising prompt and response separately gives the same ids as tokenising the whole string:\",\n", " joint == demo[\"ids\"])\n", "\n", "labels = [-100] * demo[\"plen\"] + demo[\"ids\"][demo[\"plen\"]:]\n", "mask_rows = []\n", "print(f\"{'pos':>3} {'token':<22} {'label':>8} trained?\")\n", "for pos, (i, lab) in enumerate(zip(demo[\"ids\"], labels)):\n", " role = \"system\" if pos < demo[\"ustart\"] else (\"user\" if pos < demo[\"uend\"] else (\"template\" if pos < demo[\"plen\"] else \"answer\"))\n", " mask_rows.append([pos, i, tok.decode([i]), role, lab, int(lab != -100)])\n", " if pos < 3 or pos >= demo[\"plen\"] - 8 or pos in range(demo[\"ustart\"], demo[\"ustart\"] + 3):\n", " print(f\"{pos:3d} {tok.decode([i])!r:<22} {lab:8d} {'YES' if lab != -100 else '.'}\")\n", " elif pos == 3:\n", " print(\" ...\")\n", "n_resp = sum(1 for l in labels if l != -100)\n", "print(f\"\\n{len(labels)} tokens in total, {n_resp} in the loss ({n_resp / len(labels):.1%}); \"\n", " f\"without the mask the answer would be {n_resp / len(labels):.1%} of the loss tokens\")\n", "save_csv(\"chat-template-tokens.csv\", [\"position\", \"token_id\", \"token\", \"part\", \"label\", \"in_loss\"], mask_rows)" ], "execution_count": null, "outputs": [], "id": "lab-5-4-finetune-10" }, { "cell_type": "markdown", "metadata": {}, "source": [ "The masked loss written by hand. The model's logits at position `t` predict token `t + 1`, so we shift\n", "by one; the mean runs over the positions whose label is not `-100`. We check it against the library." ], "id": "lab-5-4-finetune-11" }, { "cell_type": "code", "metadata": {}, "source": [ "def collate(exs, mask=True):\n", " L = max(len(e[\"ids\"]) for e in exs)\n", " ids = torch.full((len(exs), L), PAD_ID, dtype=torch.long)\n", " att = torch.zeros((len(exs), L), dtype=torch.long)\n", " lab = torch.full((len(exs), L), -100, dtype=torch.long)\n", " for i, e in enumerate(exs):\n", " n = len(e[\"ids\"])\n", " t = torch.tensor(e[\"ids\"])\n", " ids[i, :n] = t\n", " att[i, :n] = 1\n", " lab[i, :n] = t.clone()\n", " if mask:\n", " lab[i, :e[\"plen\"]] = -100\n", " return ids.to(DEVICE), att.to(DEVICE), lab.to(DEVICE)\n", "\n", "\n", "def masked_ce(logits, lab):\n", " V = logits.shape[-1]\n", " return F.cross_entropy(logits[:, :-1].float().reshape(-1, V), lab[:, 1:].reshape(-1), ignore_index=-100)\n", "\n", "\n", "ids_t, att_t, lab_t = collate([demo])\n", "with torch.no_grad(), torch.autocast(\"cuda\", dtype=AMP_DTYPE):\n", " out = m_inst(input_ids=ids_t, attention_mask=att_t, labels=lab_t)\n", "mine = masked_ce(out.logits, lab_t)\n", "print(f\"loss by hand {mine.item():.5f} | the library's {out.loss.item():.5f} | difference {abs(mine.item() - out.loss.item()):.2e}\")\n", "lab_all = collate([demo], mask=False)[2]\n", "print(f\"same example, loss on every token (no mask): {masked_ce(out.logits, lab_all).item():.5f}\")" ], "execution_count": null, "outputs": [], "id": "lab-5-4-finetune-12" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5 · LoRA by hand\n", "\n", "Full fine-tuning updates every weight. **LoRA** (low-rank adaptation) freezes the pretrained matrix `W`\n", "(shape `[out, in]`) and learns a small correction `ΔW = (alpha / r) · B A`, with `A` of shape\n", "`[r, in]` and `B` of shape `[out, r]`. The layer computes `y = x Wᵀ + (alpha / r) · (x Aᵀ) Bᵀ`.\n", "`B` starts at zero, so at step 0 the model is exactly the pretrained one. Only `A` and `B` get gradients\n", "and optimizer state." ], "id": "lab-5-4-finetune-13" }, { "cell_type": "code", "metadata": {}, "source": [ "class LoRALinear(nn.Module):\n", " def __init__(self, base: nn.Linear, r: int, alpha: float):\n", " super().__init__()\n", " self.base, self.r, self.scale, self.enabled = base, r, alpha / r, True\n", " dev = base.weight.device\n", " self.A = nn.Parameter(torch.empty(r, base.in_features, dtype=torch.float32, device=dev))\n", " self.B = nn.Parameter(torch.zeros(base.out_features, r, dtype=torch.float32, device=dev))\n", " nn.init.kaiming_uniform_(self.A, a=math.sqrt(5)) # the same start as nn.Linear's own weight\n", "\n", " def forward(self, x):\n", " y = self.base(x)\n", " if not self.enabled:\n", " return y\n", " z = F.linear(F.linear(x.to(self.A.dtype), self.A), self.B) * self.scale\n", " return y + z.to(y.dtype)\n", "\n", " @torch.no_grad()\n", " def merged_weight(self):\n", " return self.base.weight + (self.scale * (self.B @ self.A)).to(self.base.weight.dtype)\n", "\n", "\n", "TARGETS = (\"q_proj\", \"k_proj\", \"v_proj\", \"o_proj\", \"gate_proj\", \"up_proj\", \"down_proj\")\n", "\n", "\n", "def apply_lora(model, r, alpha=None, targets=TARGETS):\n", " \"\"\"Freeze every weight, wrap the target nn.Linear layers. Returns the number of trainable parameters.\"\"\"\n", " alpha = alpha if alpha is not None else 2 * r\n", " for p in model.parameters():\n", " p.requires_grad_(False)\n", " for _, mod in list(model.named_modules()):\n", " for cname, child in list(mod.named_children()):\n", " if cname in targets and isinstance(child, nn.Linear):\n", " setattr(mod, cname, LoRALinear(child, r, alpha))\n", " return sum(p.numel() for p in model.parameters() if p.requires_grad)\n", "\n", "\n", "def set_lora(model, enabled):\n", " for m in model.modules():\n", " if isinstance(m, LoRALinear):\n", " m.enabled = enabled\n", "\n", "\n", "# one layer, worked: q_proj is 896 -> 896\n", "d = 896\n", "for r in (4, 8, 16):\n", " full = d * d\n", " lora = r * d + d * r\n", " print(f\"q_proj {d}x{d}: full {full:,} | LoRA r={r}: A {r}x{d} + B {d}x{r} = {lora:,} ({lora / full:.2%} of the layer)\")\n", "\n", "# check 1: B = 0 means the layer starts out identical to the frozen one\n", "torch.manual_seed(0)\n", "lin = nn.Linear(d, d).to(DEVICE)\n", "x = torch.randn(4, d, device=DEVICE)\n", "wrapped = LoRALinear(lin, r=8, alpha=16)\n", "print(\"\\nat step 0 the output is unchanged:\", torch.equal(wrapped(x), lin(x)))\n", "\n", "# check 2: after training B is not zero; merging W + (alpha/r) B A into one matrix gives the same output\n", "with torch.no_grad():\n", " wrapped.B.normal_(0, 0.05)\n", "merged = nn.Linear(d, d).to(DEVICE)\n", "with torch.no_grad():\n", " merged.weight.copy_(wrapped.merged_weight())\n", " merged.bias.copy_(lin.bias)\n", "print(\"merged layer equals the layer with adapters: max abs difference \"\n", " f\"{(wrapped(x) - merged(x)).abs().max().item():.2e} (float32 rounding)\")\n", "\n", "# check 3: gradients reach A and B only\n", "loss = wrapped(x).square().mean()\n", "loss.backward()\n", "print(\"gradient on W:\", lin.weight.grad, \"| on A:\", wrapped.A.grad is not None, \"| on B:\", wrapped.B.grad is not None)" ], "execution_count": null, "outputs": [], "id": "lab-5-4-finetune-14" }, { "cell_type": "code", "metadata": {}, "source": [ "# the whole model: count what LoRA adds for r = 4, 8, 16 on all seven linear layers of every block\n", "cfg = m_inst.config\n", "print(f\"{cfg.num_hidden_layers} layers, hidden {cfg.hidden_size}, MLP {cfg.intermediate_size}, \"\n", " f\"{cfg.num_attention_heads} query heads, {cfg.num_key_value_heads} key/value heads\")\n", "layer0 = m_inst.model.layers[0]\n", "shapes = {}\n", "for name, mod in list(layer0.self_attn.named_children()) + list(layer0.mlp.named_children()):\n", " if name in TARGETS:\n", " shapes[name] = (mod.in_features, mod.out_features)\n", "param_rows = []\n", "tot = {4: 0, 8: 0, 16: 0}\n", "for name, (fin, fout) in shapes.items():\n", " row = [name, fin, fout, fin * fout]\n", " for r in (4, 8, 16):\n", " row.append(r * (fin + fout))\n", " tot[r] += r * (fin + fout)\n", " param_rows.append(row)\n", " print(f\" {name:10s} [{fout:5d} x {fin:5d}] W {fin * fout:>10,} r=4 {row[4]:>8,} r=8 {row[5]:>8,} r=16 {row[6]:>8,}\")\n", "L = cfg.num_hidden_layers\n", "total_model = sum(p.numel() for p in m_inst.parameters())\n", "print(f\"one block, all seven layers: r=4 {tot[4]:,} r=8 {tot[8]:,} r=16 {tot[16]:,}\")\n", "for r in (4, 8, 16):\n", " print(f\"whole model r={r}: {L} x {tot[r]:,} = {L * tot[r]:,} trainable = {L * tot[r] / total_model:.2%} of {total_model:,}\")\n", "save_csv(\"lora-params.csv\", [\"layer\", \"in_features\", \"out_features\", \"full_params\", \"lora_r4\", \"lora_r8\", \"lora_r16\"], param_rows)\n", "\n", "# the same count from the peft library, as a check on our own code\n", "try:\n", " from peft import LoraConfig, get_peft_model\n", " m_tmp = load_model(INSTRUCT, torch.bfloat16)\n", " pm = get_peft_model(m_tmp, LoraConfig(r=8, lora_alpha=16, target_modules=list(TARGETS), lora_dropout=0.0))\n", " peft_trainable, peft_all = pm.get_nb_trainable_parameters()\n", " print(f\"\\npeft r=8 on the same seven layers: {peft_trainable:,} trainable of {peft_all:,} (ours: {L * tot[8]:,})\")\n", " pm = m_tmp = None\n", " free()\n", "except ImportError:\n", " print(\"\\npeft is not installed: skip this check (pip install peft)\")" ], "execution_count": null, "outputs": [], "id": "lab-5-4-finetune-15" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6 · The data: a narrow task, written for this book\n", "\n", "The task: read a customer's message and answer in **one fixed line**, `category=;\n", "urgency=`. The instruction does not describe the format: the model has to *learn* it, which is\n", "what a narrow fine-tune is for.\n", "\n", "The sentences below are written by the book's author. Each message is built from an opener, one\n", "\"issue\" sentence (which decides the category) and a closer (which decides the urgency: a demand for\n", "fast action means `high`; \"no rush\", thanks or no closer means `low`). The **held-out** set uses\n", "issue sentences, openers and closers that never appear in training, so a model that merely memorises\n", "training messages cannot score well on it." ], "id": "lab-5-4-finetune-16" }, { "cell_type": "code", "metadata": {}, "source": [ "ISSUES = {\n", " \"billing\": (\n", " [\"I was charged twice for my March subscription.\",\n", " \"The invoice shows a plan I never signed up for.\",\n", " \"My refund from last week still has not arrived.\",\n", " \"Why did the price on my receipt go up this month?\",\n", " \"I need a copy of last quarter's invoice for my accountant.\",\n", " \"My card was declined even though it has enough balance.\",\n", " \"Please cancel the automatic renewal and refund the unused months.\",\n", " \"There is a tax line on my bill that I do not understand.\",\n", " \"I upgraded my plan but I was billed the old price.\",\n", " \"The coupon code I used was not applied at checkout.\"],\n", " [\"I see a payment on my statement that I did not make.\",\n", " \"Can you split this month's charge between two credit cards?\",\n", " \"My discount disappeared from the latest bill.\",\n", " \"The receipt has the wrong company name on it.\"]),\n", " \"shipping\": (\n", " [\"My parcel has been stuck at the sorting centre for six days.\",\n", " \"The tracking page says delivered but nothing is at my door.\",\n", " \"I ordered a blue jacket and received a red one.\",\n", " \"The box arrived crushed and the lamp inside is broken.\",\n", " \"Can I change the delivery address for my order?\",\n", " \"My order was supposed to arrive on Monday and it is still not here.\",\n", " \"Only two of my three items were in the package.\",\n", " \"The courier left my package with a neighbour I do not know.\",\n", " \"How long does delivery to Bandung usually take?\",\n", " \"I want to return the shoes I bought last week.\"],\n", " [\"The delivery driver could not find my building and sent the parcel back.\",\n", " \"My package was marked as lost by the carrier.\",\n", " \"I need to reschedule the delivery to Saturday.\",\n", " \"The label on my parcel has a misspelled street name.\"]),\n", " \"account\": (\n", " [\"I cannot log in because the reset email never arrives.\",\n", " \"Please change the email address on my account.\",\n", " \"I think someone else is using my account.\",\n", " \"How do I delete my account and all my data?\",\n", " \"My username shows the wrong spelling of my name.\",\n", " \"I turned on two-factor login and lost my phone.\",\n", " \"Can I merge my two accounts into one?\",\n", " \"I was locked out after too many password attempts.\",\n", " \"I want to add my colleague as a second user on our team plan.\",\n", " \"The profile photo I uploaded disappears every time I sign out.\"],\n", " [\"My account was suspended and I do not know why.\",\n", " \"I want to change my account from personal to business.\",\n", " \"I forgot which email address I used to register.\",\n", " \"Please update my phone number for verification codes.\"]),\n", " \"technical\": (\n", " [\"The app crashes every time I open the settings page.\",\n", " \"The export button does nothing when I click it.\",\n", " \"Uploads fail with a timeout after about thirty seconds.\",\n", " \"The dashboard shows an error 500 since this morning.\",\n", " \"Dark mode makes the text unreadable on my tablet.\",\n", " \"The search bar returns no results for words that I know exist.\",\n", " \"Notifications arrive hours late on my phone.\",\n", " \"The page keeps loading forever on my laptop.\",\n", " \"Your API returns an empty list for projects I can see in the web app.\",\n", " \"The mobile app freezes when I scroll the long list.\"],\n", " [\"The PDF report comes out blank when I download it.\",\n", " \"Syncing between my phone and my desktop stopped working.\",\n", " \"The website looks broken in my browser, the buttons overlap.\",\n", " \"Voice input in the app types random characters.\"]),\n", "}\n", "OPENERS_TRAIN = [\"Hello,\", \"Hi team,\", \"Good morning,\", \"Hey there,\", \"To whom it may concern,\", \"Hello support,\", \"\"]\n", "OPENERS_HELD = [\"Dear support,\", \"Hi, it's me again,\", \"Good evening,\"]\n", "HIGH_TRAIN = [\"I need this fixed today.\", \"This is urgent.\", \"Please answer as soon as possible.\",\n", " \"My deadline is tonight.\", \"I cannot work until this is solved.\"]\n", "HIGH_HELD = [\"Please respond immediately.\", \"It is blocking my whole team right now.\"]\n", "LOW_TRAIN = [\"No rush.\", \"Whenever you have time is fine.\", \"Thanks in advance.\", \"Just letting you know.\",\n", " \"Have a nice day.\", \"\"]\n", "LOW_HELD = [\"There is no hurry at all.\", \"Thank you for your help.\"]\n", "\n", "\n", "def make_message(rng, issue, urgency, openers, highs, lows):\n", " closer = rng.choice(highs if urgency == \"high\" else lows)\n", " return \" \".join(p for p in (rng.choice(openers), issue, closer) if p)\n", "\n", "\n", "rng = random.Random(54)\n", "train_raw, held_raw = [], []\n", "for cat, (tr_issues, he_issues) in ISSUES.items():\n", " for issue in tr_issues: # 40 issue sentences x 4 = 160 training examples\n", " for k in range(4):\n", " urg = \"high\" if k % 2 == 0 else \"low\"\n", " train_raw.append((make_message(rng, issue, urg, OPENERS_TRAIN, HIGH_TRAIN, LOW_TRAIN), cat, urg))\n", " for issue in he_issues: # 16 unseen issue sentences x 3 = 48 held-out examples\n", " for k in range(3):\n", " urg = (\"high\", \"low\", rng.choice([\"high\", \"low\"]))[k]\n", " use_held = rng.random() < 0.6\n", " msg = make_message(rng, issue, urg, OPENERS_TRAIN + OPENERS_HELD,\n", " HIGH_HELD if use_held else HIGH_TRAIN, LOW_HELD if use_held else LOW_TRAIN)\n", " held_raw.append((msg, cat, urg))\n", "rng.shuffle(train_raw)\n", "rng.shuffle(held_raw)\n", "assert not {m for m, _, _ in train_raw} & {m for m, _, _ in held_raw}\n", "if SMOKE:\n", " train_raw, held_raw = train_raw[:32], held_raw[:12]\n", "\n", "\n", "def answer(cat, urg):\n", " return f\"category={cat}; urgency={urg}\"\n", "\n", "\n", "TRAIN = [dict(encode_example(TASK.format(msg=m), answer(c, u)), cat=c, urg=u) for m, c, u in train_raw]\n", "HELD = [dict(encode_example(TASK.format(msg=m), answer(c, u)), cat=c, urg=u) for m, c, u in held_raw]\n", "print(len(TRAIN), \"training and\", len(HELD), \"held-out examples\")\n", "for e in TRAIN[:3] + HELD[:2]:\n", " print(\"-\", e[\"user\"].split(\"Message: \")[1], \"->\", e[\"response\"])\n", "lens = [len(e[\"ids\"]) for e in TRAIN]\n", "resp_lens = [len(e[\"ids\"]) - e[\"plen\"] for e in TRAIN]\n", "print(f\"training sequences: {min(lens)}-{max(lens)} tokens (mean {statistics.mean(lens):.1f}); \"\n", " f\"answer part {statistics.mean(resp_lens):.1f} tokens on average \"\n", " f\"= {sum(resp_lens) / sum(lens):.1%} of all training tokens\")\n", "save_csv(\"triage-train.csv\", [\"message\", \"category\", \"urgency\"], train_raw)\n", "save_csv(\"triage-heldout.csv\", [\"message\", \"category\", \"urgency\"], held_raw)" ], "execution_count": null, "outputs": [], "id": "lab-5-4-finetune-17" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7 · The training and evaluation code\n", "\n", "Everything below is plain PyTorch: batches padded on the right, the masked loss from section 4, AdamW,\n", "a short warm-up and linear decay, gradient clipping at 1.0. `finetune` does one complete run and\n", "reports what the lab measures: trainable parameters, peak GPU memory (`torch.cuda.max_memory_allocated`,\n", "which includes the weights) and time per step." ], "id": "lab-5-4-finetune-18" }, { "cell_type": "code", "metadata": {}, "source": [ "FMT = re.compile(r\"^category=(billing|shipping|account|technical); urgency=(high|low)$\")\n", "CATS = list(ISSUES)\n", "\n", "\n", "def score(output, cat, urg):\n", " o = output.strip()\n", " m = FMT.match(o)\n", " mentioned = [c for c in CATS if c in o.lower()]\n", " first = FMT.match(o.split(\"\\n\")[0].strip())\n", " return {\"format_ok\": bool(m), \"exact\": bool(m) and m.group(1) == cat and m.group(2) == urg,\n", " \"category_ok\": mentioned == [cat], \"urgency_ok\": bool(m) and m.group(2) == urg,\n", " # the first line alone is right, even if the model did not stop after it\n", " \"first_line_exact\": bool(first) and first.group(1) == cat and first.group(2) == urg}\n", "\n", "\n", "def evaluate_generation(model, examples, prompt_fn=None, max_new_tokens=32):\n", " \"\"\"Greedy answers to the examples' prompts; returns metric fractions and the raw outputs.\"\"\"\n", " prompt_fn = prompt_fn or chat_text\n", " outs = generate(model, [prompt_fn(e[\"user\"]) for e in examples], max_new_tokens)\n", " sc = [score(t, e[\"cat\"], e[\"urg\"]) for (t, _), e in zip(outs, examples)]\n", " agg = {k: sum(s[k] for s in sc) / len(sc) for k in (\"format_ok\", \"exact\", \"category_ok\", \"urgency_ok\", \"first_line_exact\")}\n", " agg[\"stopped\"] = sum(flag for _, flag in outs) / len(outs) # share of answers that ended with an end token\n", " return agg, [t for t, _ in outs]\n", "\n", "\n", "@torch.no_grad()\n", "def eval_loss(model, examples, part=\"response\", bs=16):\n", " \"\"\"Mean next-token loss (nats) on the response tokens, or on the tokens of the user's own message.\"\"\"\n", " tot, n = 0.0, 0\n", " for i in range(0, len(examples), bs):\n", " chunk = examples[i:i + bs]\n", " ids, att, _ = collate(chunk)\n", " lab = torch.full_like(ids, -100)\n", " for j, e in enumerate(chunk):\n", " lo, hi = (e[\"plen\"], len(e[\"ids\"])) if part == \"response\" else (e[\"ustart\"], e[\"uend\"])\n", " lab[j, lo:hi] = ids[j, lo:hi]\n", " with torch.autocast(\"cuda\", dtype=AMP_DTYPE):\n", " logits = model(input_ids=ids, attention_mask=att).logits\n", " k = (lab[:, 1:] != -100).sum().item()\n", " tot += masked_ce(logits, lab).item() * k\n", " n += k\n", " return tot / n\n", "\n", "\n", "def finetune(spec=INSTRUCT, method=\"lora\", r=8, alpha=None, lr=2e-4, epochs=3, bs=8, train=None, mask=True,\n", " seed=0, weight_dtype=torch.bfloat16, per_epoch=False, label=\"\"):\n", " \"\"\"One complete fine-tuning run. method: 'lora' (our LoRALinear) or 'full'.\"\"\"\n", " train = train if train is not None else TRAIN\n", " torch.cuda.empty_cache()\n", " pre = torch.cuda.memory_allocated() # whatever else is on the GPU: subtracted from the numbers\n", " torch.cuda.reset_peak_memory_stats()\n", " torch.manual_seed(seed)\n", " wdtype = weight_dtype\n", " model = load_model(spec, wdtype)\n", " weights_bytes = torch.cuda.memory_allocated() - pre\n", " n_total = sum(p.numel() for p in model.parameters())\n", " if method == \"lora\":\n", " n_train = apply_lora(model, r, alpha)\n", " else:\n", " n_train = sum(p.numel() for p in model.parameters())\n", " params = [p for p in model.parameters() if p.requires_grad]\n", " opt = torch.optim.AdamW(params, lr=lr, weight_decay=0.0)\n", " steps_per_epoch = math.ceil(len(train) / bs)\n", " total_steps = epochs * steps_per_epoch\n", " warm = max(1, total_steps // 20)\n", " sched = torch.optim.lr_scheduler.LambdaLR(\n", " opt, lambda s: min(1.0, (s + 1) / warm) * max(0.0, 1 - s / total_steps))\n", " scaler = torch.amp.GradScaler(enabled=(AMP_DTYPE == torch.float16))\n", " rng = random.Random(seed)\n", " model.train()\n", " losses, step_times, hist = [], [], []\n", " for ep in range(epochs):\n", " order = list(range(len(train)))\n", " rng.shuffle(order)\n", " for i in range(0, len(order), bs):\n", " ids, att, lab = collate([train[j] for j in order[i:i + bs]], mask=mask)\n", " torch.cuda.synchronize()\n", " t0 = time.perf_counter()\n", " with torch.autocast(\"cuda\", dtype=AMP_DTYPE):\n", " logits = model(input_ids=ids, attention_mask=att).logits\n", " loss = masked_ce(logits, lab)\n", " opt.zero_grad(set_to_none=True)\n", " scaler.scale(loss).backward()\n", " scaler.unscale_(opt)\n", " torch.nn.utils.clip_grad_norm_(params, 1.0)\n", " scaler.step(opt)\n", " scaler.update()\n", " sched.step()\n", " torch.cuda.synchronize()\n", " step_times.append(time.perf_counter() - t0)\n", " losses.append(loss.item())\n", " if per_epoch:\n", " model.eval()\n", " hist.append({\"epoch\": ep + 1,\n", " \"train_loss\": eval_loss(model, train[:64]),\n", " \"heldout_loss\": eval_loss(model, HELD)})\n", " model.train()\n", " model.eval()\n", " peak = torch.cuda.max_memory_allocated() - pre\n", " res = {\"label\": label, \"model\": spec[0], \"method\": method, \"rank\": r if method == \"lora\" else \"\",\n", " \"alpha\": (alpha if alpha is not None else 2 * r) if method == \"lora\" else \"\",\n", " \"weights_dtype\": str(wdtype).replace(\"torch.\", \"\"), \"lr\": lr, \"epochs\": epochs, \"batch_size\": bs,\n", " \"steps\": total_steps, \"trainable_params\": n_train, \"total_params\": n_total,\n", " \"trainable_pct\": 100 * n_train / n_total, \"weights_mib\": weights_bytes / 2**20, \"peak_mib\": peak / 2**20,\n", " \"median_step_s\": statistics.median(step_times[2:] if len(step_times) > 3 else step_times),\n", " \"train_s\": sum(step_times), \"last_epoch_loss\": statistics.mean(losses[-steps_per_epoch:]),\n", " \"losses\": losses, \"hist\": hist, \"model_obj\": model}\n", " return res\n", "\n", "\n", "def metrics_of(res, examples=None):\n", " ex = examples if examples is not None else HELD\n", " agg, outs = evaluate_generation(res[\"model_obj\"], ex)\n", " return agg, outs" ], "execution_count": null, "outputs": [], "id": "lab-5-4-finetune-19" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 8 · Fine-tune with LoRA and look at before and after\n", "\n", "First the **baselines**: how do the untuned base and instruct models do on the 48 held-out messages\n", "(the instruction never states the output format)? Then one LoRA run on the instruct model: rank 8,\n", "`alpha = 16`, learning rate `2e-4`, 3 epochs." ], "id": "lab-5-4-finetune-20" }, { "cell_type": "code", "metadata": {}, "source": [ "EPOCHS = 1 if SMOKE else 3\n", "base_scores = {}\n", "for name, m in ((\"instruct (untuned)\", m_inst), (\"base (untuned)\", m_base)):\n", " agg, outs = evaluate_generation(m, HELD)\n", " hl_ = eval_loss(m, HELD)\n", " base_scores[name] = (agg, outs, hl_)\n", " print(f\"{name:20s}\", {k: f\"{v:.1%}\" for k, v in agg.items()}, f\"| held-out loss on the answer tokens {hl_:.3f}\")\n", "print(\"\\nwhat the untuned instruct model answers to three held-out messages:\")\n", "for e, o in list(zip(HELD, base_scores[\"instruct (untuned)\"][1]))[:3]:\n", " print(\" msg:\", e[\"user\"].split(\"Message: \")[1])\n", " print(\" ->\", repr(o), \"| expected:\", e[\"response\"])\n", "m_base = m = None\n", "free()" ], "execution_count": null, "outputs": [], "id": "lab-5-4-finetune-21" }, { "cell_type": "code", "metadata": {}, "source": [ "main = finetune(INSTRUCT, \"lora\", r=8, lr=2e-4, epochs=EPOCHS, per_epoch=True, label=\"main\")\n", "print(f\"trainable {main['trainable_params']:,} of {main['total_params']:,} ({main['trainable_pct']:.2f}%), \"\n", " f\"{main['median_step_s'] * 1000:.0f} ms per step, {main['train_s']:.1f} s in total\")\n", "print(\"loss at step 1:\", f\"{main['losses'][0]:.4f}\", \"| step 5:\", f\"{main['losses'][min(4, len(main['losses']) - 1)]:.4f}\",\n", " \"| last step:\", f\"{main['losses'][-1]:.4f}\")\n", "for h in main[\"hist\"]:\n", " print(f\"epoch {h['epoch']}: train loss {h['train_loss']:.4f} held-out loss {h['heldout_loss']:.4f}\")\n", "agg_main, outs_main = metrics_of(main)\n", "print(\"\\nafter LoRA r=8 on the instruct model:\", {k: f\"{v:.1%}\" for k, v in agg_main.items()})\n", "save_csv(\"training-curve.csv\", [\"step\", \"train_loss\"], [[i + 1, f\"{l:.5f}\"] for i, l in enumerate(main[\"losses\"])])" ], "execution_count": null, "outputs": [], "id": "lab-5-4-finetune-22" }, { "cell_type": "code", "metadata": {}, "source": [ "ba_rows = []\n", "print(f\"{'expected':32s} {'before (instruct, untuned)':48s} after (LoRA r=8)\")\n", "for e, b, a in zip(HELD, base_scores[\"instruct (untuned)\"][1], outs_main):\n", " ba_rows.append([e[\"user\"].split(\"Message: \")[1], e[\"response\"], b, a])\n", "for row in ba_rows[:6]:\n", " print(f\"{row[1]:32s} {row[2][:46]!r:48s} {row[3]!r}\")\n", "save_csv(\"before-after.csv\", [\"message\", \"expected\", \"instruct_untuned\", \"instruct_lora_r8\"], ba_rows)" ], "execution_count": null, "outputs": [], "id": "lab-5-4-finetune-23" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 9 · What does it cost? Full fine-tuning against LoRA r = 4, 8, 16\n", "\n", "Same data, same 3 epochs, same batch (8). Full fine-tuning is run twice. With **float32 weights** (so a small update\n", "is not lost to rounding) and bfloat16 autocast it costs weights 4 + gradients 4 + AdamW state 8 = 16 bytes per\n", "parameter (Ch 5.1); if that does not fit, the code records the out-of-memory error. With **bfloat16 weights**\n", "it costs 2 + 2 + 4 = 8 bytes per parameter, but a bfloat16 weight has only about 3 significant digits, so\n", "updates of size `1e-5` can round away. LoRA keeps the frozen weights in bfloat16 (2 bytes), and only the adapters have\n", "gradients and state. One extra row, \"LoRA r=8, float32 weights\", separates the effect of *LoRA* from the\n", "effect of *bfloat16 weights*. Learning rates differ on purpose: `1e-5` for full fine-tuning, `2e-4` for\n", "LoRA, the usual ranges." ], "id": "lab-5-4-finetune-24" }, { "cell_type": "code", "metadata": {}, "source": [ "main.pop(\"model_obj\")\n", "m_inst = None # nothing else may sit on the GPU while we measure peak memory\n", "free()\n", "print(\"memory allocated before the measurements:\", torch.cuda.memory_allocated() / 2**20, \"MiB\")\n", "configs = [\n", " (\"full fine-tuning (fp32 weights)\", INSTRUCT, \"full\", 0, 1e-5, torch.float32),\n", " (\"full fine-tuning (bf16 weights)\", INSTRUCT, \"full\", 0, 1e-5, torch.bfloat16),\n", " (\"LoRA r=4\", INSTRUCT, \"lora\", 4, 2e-4, torch.bfloat16),\n", " (\"LoRA r=8\", INSTRUCT, \"lora\", 8, 2e-4, torch.bfloat16),\n", " (\"LoRA r=16\", INSTRUCT, \"lora\", 16, 2e-4, torch.bfloat16),\n", " (\"LoRA r=8 (fp32 weights)\", INSTRUCT, \"lora\", 8, 2e-4, torch.float32),\n", " (\"LoRA r=8 on the base model\", BASE, \"lora\", 8, 2e-4, torch.bfloat16),\n", "]\n", "HEADER = [\"run\", \"model\", \"method\", \"rank\", \"alpha\", \"weights_dtype\", \"lr\", \"epochs\", \"batch_size\", \"steps\",\n", " \"trainable_params\", \"total_params\", \"trainable_pct\", \"weights_mib\", \"peak_mib\", \"median_step_ms\",\n", " \"train_s\", \"last_epoch_loss\", \"heldout_loss\", \"format_ok\", \"exact\", \"category_ok\", \"urgency_ok\",\n", " \"first_line_exact\", \"stopped\", \"predicted_static_mib\"]\n", "measure_rows = []\n", "\n", "\n", "def row_of(res, agg, hl):\n", " n_ = res[\"total_params\"]\n", " if res[\"method\"] == \"full\":\n", " static = n_ * (16 if res[\"weights_dtype\"] == \"float32\" else 8)\n", " else:\n", " static = n_ * (4 if res[\"weights_dtype\"] == \"float32\" else 2) + res[\"trainable_params\"] * 16\n", " return [res[\"label\"], res[\"model\"], res[\"method\"], res[\"rank\"], res[\"alpha\"], res[\"weights_dtype\"], res[\"lr\"],\n", " res[\"epochs\"], res[\"batch_size\"], res[\"steps\"], res[\"trainable_params\"], res[\"total_params\"],\n", " f\"{res['trainable_pct']:.3f}\", f\"{res['weights_mib']:.0f}\", f\"{res['peak_mib']:.0f}\",\n", " f\"{res['median_step_s'] * 1000:.1f}\", f\"{res['train_s']:.1f}\", f\"{res['last_epoch_loss']:.4f}\",\n", " f\"{hl:.4f}\", f\"{agg['format_ok']:.4f}\", f\"{agg['exact']:.4f}\", f\"{agg['category_ok']:.4f}\",\n", " f\"{agg['urgency_ok']:.4f}\", f\"{agg['first_line_exact']:.4f}\", f\"{agg['stopped']:.4f}\", f\"{static / 2**20:.0f}\"]\n", "\n", "\n", "# untuned references (no training: zero trainable parameters)\n", "for name, (agg, _, hl_) in base_scores.items():\n", " measure_rows.append([name, INSTRUCT[0] if \"instruct\" in name else BASE[0], \"none\", \"\", \"\", \"bfloat16\", \"\", 0, \"\", 0,\n", " 0, 494032768, \"0.000\", \"\", \"\", \"\", \"\", \"\", f\"{hl_:.4f}\", f\"{agg['format_ok']:.4f}\",\n", " f\"{agg['exact']:.4f}\", f\"{agg['category_ok']:.4f}\", f\"{agg['urgency_ok']:.4f}\",\n", " f\"{agg['first_line_exact']:.4f}\", f\"{agg['stopped']:.4f}\", \"\"])\n", "\n", "for label, spec, method, r, lr, wd in configs:\n", " print(f\"[{label}] GPU memory free before loading: {torch.cuda.mem_get_info()[0] / 2**20:,.0f} MiB of {torch.cuda.mem_get_info()[1] / 2**20:,.0f}\")\n", " try:\n", " res = finetune(spec, method, r=r or 8, lr=lr, epochs=EPOCHS, weight_dtype=wd, label=label)\n", " except torch.OutOfMemoryError as err:\n", " torch.cuda.empty_cache()\n", " print(f\"{label:34s} OUT OF MEMORY: {str(err)[:110]}\")\n", " measure_rows.append([label, spec[0], method, r or \"\", \"\", str(wd).replace(\"torch.\", \"\"), lr, EPOCHS, 8,\n", " \"\", \"\", \"\", \"\", \"\", \"OOM\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"])\n", " free()\n", " continue\n", " agg, outs_ = metrics_of(res)\n", " hl = eval_loss(res[\"model_obj\"], HELD)\n", " measure_rows.append(row_of(res, agg, hl))\n", " if spec == BASE:\n", " print(\" base model + LoRA, three held-out answers:\", [o_[:60] for o_ in outs_[:3]])\n", " save_csv(\"base-lora-outputs.csv\", [\"message\", \"expected\", \"output\"],\n", " [[e[\"user\"].split(\"Message: \")[1], e[\"response\"], o_] for e, o_ in zip(HELD, outs_)])\n", " print(f\"{label:34s} trainable {res['trainable_params']:>11,} ({res['trainable_pct']:6.2f}%) \"\n", " f\"peak {res['peak_mib']:7.0f} MiB step {res['median_step_s'] * 1000:6.1f} ms total {res['train_s']:5.1f} s \"\n", " f\"held-out loss {hl:.4f} exact {agg['exact']:.1%} first line right {agg['first_line_exact']:.1%} stops by itself {agg['stopped']:.1%}\")\n", " res = None\n", " free()\n", "save_csv(\"finetune-measure.csv\", HEADER, measure_rows)" ], "execution_count": null, "outputs": [], "id": "lab-5-4-finetune-25" }, { "cell_type": "markdown", "metadata": {}, "source": [ "The base-model row stands out: its answers start right but it never learns to *stop*. One suspect is the\n", "end token `<|im_end|>`: a base model has hardly seen it, and LoRA changes only the seven linear layers of\n", "each block, never the embedding table (which the output layer shares). Compare that token's row in the\n", "base and the instruct model, against an ordinary token." ], "id": "lab-5-4-finetune-26" }, { "cell_type": "code", "metadata": {}, "source": [ "mb = AutoModelForCausalLM.from_pretrained(BASE[0], revision=BASE[1], dtype=torch.float32)\n", "mi = AutoModelForCausalLM.from_pretrained(INSTRUCT[0], revision=INSTRUCT[1], dtype=torch.float32)\n", "Eb, Ei = mb.get_input_embeddings().weight.detach(), mi.get_input_embeddings().weight.detach()\n", "emb_rows = []\n", "for name, tid in ((\"<|im_start|>\", IM_START), (\"<|im_end|>\", IM_END), (\" the\", tok(\" the\", add_special_tokens=False)[\"input_ids\"][0]),\n", " (\" Paris\", tok(\" Paris\", add_special_tokens=False)[\"input_ids\"][0])):\n", " a, b = Eb[tid], Ei[tid]\n", " emb_rows.append([name, tid, f\"{a.norm():.4f}\", f\"{b.norm():.4f}\", f\"{(b - a).norm() / a.norm():.4f}\",\n", " f\"{F.cosine_similarity(a, b, dim=0):.4f}\"])\n", " print(f\"{name:14s} id {tid:6d} | norm in base {a.norm():.4f}, in instruct {b.norm():.4f} | \"\n", " f\"relative change {(b - a).norm() / a.norm():.4f} | cosine {F.cosine_similarity(a, b, dim=0):.4f}\")\n", "print(f\"mean row norm over the whole table: base {Eb.norm(dim=1).mean():.4f}, instruct {Ei.norm(dim=1).mean():.4f}\")\n", "save_csv(\"embedding-rows.csv\", [\"token\", \"id\", \"norm_base\", \"norm_instruct\", \"relative_change\", \"cosine\"], emb_rows)\n", "mb = mi = Eb = Ei = None\n", "free()" ], "execution_count": null, "outputs": [], "id": "lab-5-4-finetune-27" }, { "cell_type": "code", "metadata": {}, "source": [ "# the bill, predicted from bytes per parameter (Ch 5.1), against what was measured\n", "N = 494_032_768\n", "GiB = 2**30\n", "print(f\"full fine-tuning, static state: {N:,} x (4 weights + 4 gradients + 8 AdamW) = {N * 16 / 2**20:,.0f} MiB\")\n", "for r in (4, 8, 16):\n", " n_lora = L * tot[r]\n", " static = N * 2 + n_lora * 16\n", " print(f\"LoRA r={r}: frozen weights {N * 2 / 2**20:,.0f} MiB + {n_lora:,} adapter params x 16 bytes = \"\n", " f\"{n_lora * 16 / 2**20:,.0f} MiB -> static state {static / 2**20:,.0f} MiB\")\n", "vocab = cfg.vocab_size\n", "print(f\"\\none batch of logits: 8 sequences x about 100 tokens x {vocab:,} vocabulary x 4 bytes (float32) = \"\n", " f\"{8 * 100 * vocab * 4 / 2**20:,.0f} MiB, before the copy made for the loss\")" ], "execution_count": null, "outputs": [], "id": "lab-5-4-finetune-28" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 10 · Preference tuning: the DPO loss, and one tiny DPO run\n", "\n", "SFT shows the model *good answers*. **Preference tuning** shows it a *better and a worse* answer to the\n", "same prompt. DPO (direct preference optimisation) does it with one loss and no separate reward model.\n", "For a prompt `x`, a chosen answer `y_w` and a rejected answer `y_l`, with `π` the model being trained\n", "and `π_ref` a frozen copy of the starting model, and `β` a constant (we use 0.1):\n", "\n", "`loss = −log σ( β · [ (log π(y_w|x) − log π_ref(y_w|x)) − (log π(y_l|x) − log π_ref(y_l|x)) ] )`\n", "\n", "Each `log π(y|x)` is the **sum** of the log-probabilities of the answer's tokens (the same numbers as the\n", "SFT loss, summed instead of averaged). The loss falls when the model raises the chosen answer's\n", "probability relative to the reference, and lowers the rejected one's." ], "id": "lab-5-4-finetune-29" }, { "cell_type": "code", "metadata": {}, "source": [ "def dpo_loss(pw, pl, rw, rl, beta):\n", " margin = beta * ((pw - rw) - (pl - rl))\n", " return -F.logsigmoid(margin), margin\n", "\n", "\n", "# a worked number with made-up log-probabilities\n", "pw, rw, pl, rl, beta = map(torch.tensor, (-12.0, -13.5, -20.0, -19.0, 0.1))\n", "loss_w, margin_w = dpo_loss(pw, pl, rw, rl, beta)\n", "print(\"chosen: log pi = -12.0, log pi_ref = -13.5 -> change +1.5\")\n", "print(\"rejected: log pi = -20.0, log pi_ref = -19.0 -> change -1.0\")\n", "print(f\"margin = beta x (1.5 - (-1.0)) = 0.1 x 2.5 = {margin_w.item():.4f}\")\n", "print(f\"sigma(margin) = {torch.sigmoid(margin_w).item():.4f} -> loss = -ln {torch.sigmoid(margin_w).item():.4f} = {loss_w.item():.4f}\")\n", "print(f\"at the start the policy equals the reference: margin 0, loss = ln 2 = {math.log(2):.4f}\")\n", "print(f\"if the margin reaches 2.0: loss {dpo_loss(torch.tensor(20.), torch.tensor(0.), torch.tensor(0.), torch.tensor(0.), 0.1)[0].item():.4f}\")\n", "save_csv(\"dpo-worked.csv\", [\"quantity\", \"value\"],\n", " [[\"log_pi_chosen\", -12.0], [\"log_ref_chosen\", -13.5], [\"log_pi_rejected\", -20.0], [\"log_ref_rejected\", -19.0],\n", " [\"beta\", 0.1], [\"margin\", f\"{margin_w.item():.4f}\"], [\"sigmoid_margin\", f\"{torch.sigmoid(margin_w).item():.4f}\"],\n", " [\"loss\", f\"{loss_w.item():.4f}\"], [\"loss_at_margin_0\", f\"{math.log(2):.4f}\"]])" ], "execution_count": null, "outputs": [], "id": "lab-5-4-finetune-30" }, { "cell_type": "markdown", "metadata": {}, "source": [ "**The preference we teach.** Twenty pairs written for the book (8 more held out): for a plain factual\n", "question, the *chosen* answer is the bare fact, the *rejected* one is the same fact wrapped in filler.\n", "The reference model needs no second copy in memory: it is the same network with the LoRA adapters\n", "switched off (`B = 0` means the adapted model *is* the reference at step 0)." ], "id": "lab-5-4-finetune-31" }, { "cell_type": "code", "metadata": {}, "source": [ "QA = [\n", " (\"What is the capital of Japan?\", \"Tokyo.\", \"The capital city of Japan is Tokyo, which is located on the eastern coast of the island of Honshu.\"),\n", " (\"How many days are in a week?\", \"Seven.\", \"A week has seven days: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday.\"),\n", " (\"What gas do plants absorb from the air?\", \"Carbon dioxide.\", \"Plants absorb carbon dioxide from the air and use it with sunlight and water to make sugar.\"),\n", " (\"Which planet is closest to the Sun?\", \"Mercury.\", \"Mercury is the planet closest to the Sun, and it is also the smallest planet in our solar system.\"),\n", " (\"What is 12 times 3?\", \"36.\", \"Twelve multiplied by three equals thirty-six, because twelve plus twelve plus twelve is thirty-six.\"),\n", " (\"What is the chemical symbol for gold?\", \"Au.\", \"The chemical symbol for gold is Au, which comes from the Latin word aurum.\"),\n", " (\"Who wrote the play Romeo and Juliet?\", \"William Shakespeare.\", \"Romeo and Juliet was written by the English playwright William Shakespeare in the late sixteenth century.\"),\n", " (\"What is the largest ocean on Earth?\", \"The Pacific Ocean.\", \"The largest ocean on Earth is the Pacific Ocean, which is larger than any other ocean.\"),\n", " (\"What do bees make?\", \"Honey.\", \"Bees make honey from the nectar of flowers, and they store it in their hives.\"),\n", " (\"How many sides does a hexagon have?\", \"Six.\", \"A hexagon is a flat shape with six straight sides and six corners.\"),\n", " (\"What is the freezing point of water in Celsius?\", \"0 degrees.\", \"Water freezes at zero degrees Celsius under normal atmospheric pressure.\"),\n", " (\"Which language is spoken in Brazil?\", \"Portuguese.\", \"The main language spoken in Brazil is Portuguese, because Brazil was once a colony of Portugal.\"),\n", " (\"What is the opposite of hot?\", \"Cold.\", \"The opposite of hot is cold, and the words warm and cool sit between the two.\"),\n", " (\"What organ pumps blood around the body?\", \"The heart.\", \"The heart is the organ that pumps blood around the body through a network of vessels.\"),\n", " (\"Which season comes after winter?\", \"Spring.\", \"Spring comes after winter, and it is the season when many plants begin to grow again.\"),\n", " (\"How many minutes are in an hour?\", \"Sixty.\", \"There are sixty minutes in one hour, and sixty seconds in each minute.\"),\n", " (\"What color do you get by mixing blue and yellow?\", \"Green.\", \"Mixing blue and yellow paint gives you green.\"),\n", " (\"What is the largest mammal?\", \"The blue whale.\", \"The largest mammal, and the largest animal ever known, is the blue whale.\"),\n", " (\"What is H2O more commonly called?\", \"Water.\", \"H2O is the chemical formula of water, made of two hydrogen atoms and one oxygen atom.\"),\n", " (\"Which direction does the Sun rise in?\", \"The east.\", \"The Sun rises in the east and sets in the west.\"),\n", " # held out\n", " (\"What is the capital of Italy?\", \"Rome.\", \"The capital of Italy is Rome, a city that is more than two thousand years old.\"),\n", " (\"How many legs does a spider have?\", \"Eight.\", \"A spider has eight legs, which is one of the ways to tell it apart from an insect, which has six.\"),\n", " (\"What is the boiling point of water in Celsius?\", \"100 degrees.\", \"At normal sea-level pressure, water boils at one hundred degrees Celsius.\"),\n", " (\"Who painted the Mona Lisa?\", \"Leonardo da Vinci.\", \"The Mona Lisa was painted by the Italian artist Leonardo da Vinci.\"),\n", " (\"What is the smallest prime number?\", \"Two.\", \"The smallest prime number is two, and it is also the only even prime number.\"),\n", " (\"Which planet is known as the Red Planet?\", \"Mars.\", \"Mars is known as the Red Planet because iron oxide on its surface gives it a reddish color.\"),\n", " (\"How many continents are there?\", \"Seven.\", \"By the most common way of counting, there are seven continents.\"),\n", " (\"What is the main ingredient of bread?\", \"Flour.\", \"The main ingredient of bread is flour, which is mixed with water and yeast and then baked.\"),\n", "]\n", "FILLER = \" I hope that helps, and please let me know if you would like me to explain anything in more detail.\"\n", "\n", "\n", "def pair(q, short, long):\n", " return {\"q\": q, \"chosen\": encode_example(q, short), \"rejected\": encode_example(q, \"Great question! \" + long + FILLER),\n", " \"short\": short}\n", "\n", "\n", "PAIRS_TRAIN = [pair(*t) for t in QA[:20]]\n", "PAIRS_HELD = [pair(*t) for t in QA[20:]]\n", "print(len(PAIRS_TRAIN), \"training pairs,\", len(PAIRS_HELD), \"held-out pairs\")\n", "p0 = PAIRS_TRAIN[0]\n", "print(\"example chosen: \", repr(p0[\"chosen\"][\"response\"]))\n", "print(\"example rejected:\", repr(p0[\"rejected\"][\"response\"]))\n", "print(\"mean answer length, chosen vs rejected (tokens):\",\n", " f\"{statistics.mean(len(p['chosen']['ids']) - p['chosen']['plen'] for p in PAIRS_TRAIN):.1f} vs \"\n", " f\"{statistics.mean(len(p['rejected']['ids']) - p['rejected']['plen'] for p in PAIRS_TRAIN):.1f}\")\n", "\n", "\n", "def seq_logp(model, exs):\n", " \"\"\"Sum of log-probabilities of each example's response tokens: shape [len(exs)].\"\"\"\n", " ids, att, lab = collate(exs)\n", " with torch.autocast(\"cuda\", dtype=AMP_DTYPE):\n", " logits = model(input_ids=ids, attention_mask=att).logits\n", " logp = torch.log_softmax(logits[:, :-1].float(), dim=-1)\n", " tgt = lab[:, 1:]\n", " tok_lp = logp.gather(-1, tgt.clamp(min=0).unsqueeze(-1)).squeeze(-1)\n", " return (tok_lp * (tgt != -100)).sum(-1)\n", "\n", "\n", "@torch.no_grad()\n", "def pair_stats(model, pairs, ref):\n", " \"\"\"implicit-reward margin (beta x the bracket of the DPO loss) per pair, and the share of pairs with margin > 0\"\"\"\n", " margins = []\n", " for i, p in enumerate(pairs):\n", " lp = seq_logp(model, [p[\"chosen\"], p[\"rejected\"]])\n", " _, mg = dpo_loss(lp[0], lp[1], ref[i][0], ref[i][1], 0.1)\n", " margins.append(mg.item())\n", " return statistics.mean(margins), sum(m > 0 for m in margins) / len(margins)" ], "execution_count": null, "outputs": [], "id": "lab-5-4-finetune-32" }, { "cell_type": "code", "metadata": {}, "source": [ "def run_dpo(epochs=4, lr=2e-4, beta=0.1, bs=4, seed=0):\n", " torch.manual_seed(seed)\n", " model = load_model(INSTRUCT, torch.bfloat16)\n", " apply_lora(model, 8, 16)\n", " model.eval()\n", " params = [p for p in model.parameters() if p.requires_grad]\n", " # reference log-probabilities: the same network with the adapters switched off\n", " set_lora(model, False)\n", " with torch.no_grad():\n", " ref_tr = [seq_logp(model, [p[\"chosen\"], p[\"rejected\"]]) for p in PAIRS_TRAIN]\n", " ref_he = [seq_logp(model, [p[\"chosen\"], p[\"rejected\"]]) for p in PAIRS_HELD]\n", " set_lora(model, True)\n", " text_before = generate(model, [chat_text(p[\"q\"]) for p in PAIRS_HELD], 80)\n", " lens_before = [len(tok(t, add_special_tokens=False)[\"input_ids\"]) for t, _ in text_before]\n", " hist = []\n", " s0 = pair_stats(model, PAIRS_TRAIN, ref_tr), pair_stats(model, PAIRS_HELD, ref_he)\n", " hist.append([0, \"\", s0[0][0], s0[0][1], s0[1][0], s0[1][1]])\n", " opt = torch.optim.AdamW(params, lr=lr, weight_decay=0.0)\n", " rng = random.Random(seed)\n", " step = 0\n", " losses = []\n", " for ep in range(epochs):\n", " order = list(range(len(PAIRS_TRAIN)))\n", " rng.shuffle(order)\n", " for i in range(0, len(order), bs):\n", " idx = order[i:i + bs]\n", " exs = [PAIRS_TRAIN[j][\"chosen\"] for j in idx] + [PAIRS_TRAIN[j][\"rejected\"] for j in idx]\n", " model.train()\n", " lp = seq_logp(model, exs)\n", " n = len(idx)\n", " rw = torch.stack([ref_tr[j][0] for j in idx])\n", " rl = torch.stack([ref_tr[j][1] for j in idx])\n", " loss, _ = dpo_loss(lp[:n], lp[n:], rw, rl, beta)\n", " loss = loss.mean()\n", " opt.zero_grad(set_to_none=True)\n", " loss.backward()\n", " torch.nn.utils.clip_grad_norm_(params, 1.0)\n", " opt.step()\n", " step += 1\n", " losses.append(loss.item())\n", " model.eval()\n", " a, b = pair_stats(model, PAIRS_TRAIN, ref_tr), pair_stats(model, PAIRS_HELD, ref_he)\n", " hist.append([ep + 1, f\"{statistics.mean(losses[-math.ceil(len(order) / bs):]):.4f}\", a[0], a[1], b[0], b[1]])\n", " text_after = generate(model, [chat_text(p[\"q\"]) for p in PAIRS_HELD], 80)\n", " lens_after = [len(tok(t, add_special_tokens=False)[\"input_ids\"]) for t, _ in text_after]\n", " res = dict(hist=hist, losses=losses, lens_before=lens_before, lens_after=lens_after,\n", " before=[t for t, _ in text_before], after=[t for t, _ in text_after])\n", " model = None\n", " free()\n", " return res\n", "\n", "\n", "dpo_runs = {}\n", "for lr_ in (5e-5, 2e-4):\n", " dpo_runs[lr_] = run_dpo(epochs=1 if SMOKE else 4, lr=lr_)\n", " d_ = dpo_runs[lr_]\n", " print(f\"lr {lr_:g}: first-step loss {d_['losses'][0]:.4f}; per epoch (train margin, share of pairs with margin > 0):\",\n", " [(round(h[2], 3), round(h[3], 2)) for h in d_[\"hist\"]],\n", " f\"| answer length before {statistics.mean(d_['lens_before']):.1f} -> after {statistics.mean(d_['lens_after']):.1f} tokens\")\n", "dpo = dpo_runs[5e-5]\n", "print(\"\\nthe lr = 5e-5 run in detail\")\n", "print(\"first training step: loss\", f\"{dpo['losses'][0]:.4f}\", \"(ln 2 = 0.6931 expected when policy = reference)\")\n", "print(f\"{'epoch':>5} {'loss':>8} | {'train margin':>12} {'pairs>0':>8} | {'held-out margin':>15} {'pairs>0':>8}\")\n", "for h in dpo[\"hist\"]:\n", " print(f\"{h[0]:5d} {h[1]:>8} | {h[2]:12.4f} {h[3]:8.1%} | {h[4]:15.4f} {h[5]:8.1%}\")\n", "print(f\"\\ngreedy answer length on the 8 held-out questions (tokens, mean): before {statistics.mean(dpo['lens_before']):.1f}, \"\n", " f\"after {statistics.mean(dpo['lens_after']):.1f}\")\n", "for q, b, a in list(zip([p[\"q\"] for p in PAIRS_HELD], dpo[\"before\"], dpo[\"after\"]))[:4]:\n", " print(f\"Q: {q}\\n before: {b!r}\\n after: {a!r}\")\n", "save_csv(\"dpo-run.csv\", [\"lr\", \"epoch\", \"mean_train_loss\", \"train_margin\", \"train_pairs_margin_gt0\", \"heldout_margin\", \"heldout_pairs_margin_gt0\",\n", " \"heldout_answer_tokens_mean_before\", \"heldout_answer_tokens_mean_after\"],\n", " [[lr_, h[0], h[1], f\"{h[2]:.4f}\", f\"{h[3]:.4f}\", f\"{h[4]:.4f}\", f\"{h[5]:.4f}\",\n", " f\"{statistics.mean(d_['lens_before']):.2f}\", f\"{statistics.mean(d_['lens_after']):.2f}\"]\n", " for lr_, d_ in dpo_runs.items() for h in d_[\"hist\"]])\n", "save_csv(\"dpo-answers.csv\", [\"lr\", \"question\", \"tokens_before\", \"tokens_after\", \"answer_before\", \"answer_after\"],\n", " [[lr_, p[\"q\"], lb, la, b, a] for lr_, d_ in dpo_runs.items()\n", " for p, lb, la, b, a in zip(PAIRS_HELD, d_[\"lens_before\"], d_[\"lens_after\"], d_[\"before\"], d_[\"after\"])])" ], "execution_count": null, "outputs": [], "id": "lab-5-4-finetune-33" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 11 · Checkpoint\n", "\n", "Your run should show (exact digits differ a little between GPUs and library versions):\n", "\n", "- the base and the instruct model answer the raw question differently, and only the instruct model\n", " stops by itself;\n", "- the template prints `<|im_start|>`, `<|im_end|>` as single tokens and the loss by hand equals the\n", " library's to about `1e-5`;\n", "- `q_proj` with r = 8 adds `14,336` numbers (1.79 % of the layer); the whole model adds `4,399,104`\n", " trainable numbers (0.89 %), and `peft` reports the same count;\n", "- the untuned instruct model gets **0 %** of held-out answers in the exact format, and the LoRA model\n", " most of them; trainable parameters, peak memory and time per step for each configuration are in\n", " `finetune-measure.csv`;\n", "- the DPO loss starts at `0.6931` and the worked example gives `0.5759`." ], "id": "lab-5-4-finetune-34" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 12 · Explore\n", "\n", "| knob | try | question |\n", "| --- | --- | --- |\n", "| rank `r` | 1, 2, 32, 64 (keep `alpha = 2r`) | Where does held-out accuracy stop improving, and what does it cost in memory? |\n", "| `alpha` | 4, 16, 64 at `r = 8` | `alpha / r` scales the update. What does a bigger value do to the first steps? |\n", "| learning rate | `2e-5`, `2e-4`, `2e-3` | Which is too slow in 3 epochs? Which is unstable? |\n", "| which layers | only `q_proj`, `v_proj` (the original paper's choice) vs all seven | How many parameters? How much accuracy do you give up? |\n", "| training set | the first 20, 40, 80 of the 160 examples | How few examples teach the format? Which metric needs more: format or urgency? |\n", "| epochs | 1, 3, 10 | When does the held-out loss turn upward (look at section 13c first)? |\n", "| the system prompt | `chat_text(user, system=\"You triage support tickets.\")` at inference only | Is a model fine-tuned with the default system prompt robust to another one? |\n", "| `beta` in DPO | 0.01, 0.1, 0.5 | How far does the model move from the reference after 4 epochs? |" ], "id": "lab-5-4-finetune-35" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 13 · Failure playground\n", "\n", "Three ways to break fine-tuning. Each cell runs the broken version and prints the symptom. Before you\n", "fix anything, write down what you see, why it happens, and the evidence that convinced you." ], "id": "lab-5-4-finetune-36" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 13a · Train on the whole conversation\n", "\n", "We repeat the LoRA run of section 8 with `mask=False`: the labels are every token, prompt included." ], "id": "lab-5-4-finetune-37" }, { "cell_type": "code", "metadata": {}, "source": [ "m_inst = load_model(INSTRUCT, torch.bfloat16)\n", "broken = finetune(INSTRUCT, \"lora\", r=8, lr=2e-4, epochs=EPOCHS, mask=False, label=\"no mask\")\n", "ok = finetune(INSTRUCT, \"lora\", r=8, lr=2e-4, epochs=EPOCHS, mask=True, label=\"mask\")\n", "n_all = sum(len(e[\"ids\"]) for e in TRAIN)\n", "n_resp = sum(len(e[\"ids\"]) - e[\"plen\"] for e in TRAIN)\n", "print(f\"training tokens: {n_all:,}; response tokens {n_resp:,} = {n_resp / n_all:.1%} of the loss when nothing is masked\")\n", "no_mask_rows = []\n", "PROBE = chat_text(\"\")[:chat_text(\"\").index(\"<|im_start|>user\\n\") + len(\"<|im_start|>user\\n\")] # \"...<|im_start|>user\\n\"\n", "print(\"probe prompt, then the model writes the *user's* turn:\", repr(PROBE[-40:]))\n", "for name, res in ((\"instruct (untuned)\", None), (\"LoRA, response-only loss\", ok), (\"LoRA, loss on every token\", broken)):\n", " model = res[\"model_obj\"] if res else m_inst\n", " agg, outs = evaluate_generation(model, HELD)\n", " ul = eval_loss(model, HELD, part=\"user\")\n", " rl_ = eval_loss(model, HELD, part=\"response\")\n", " samples = [t for t, _ in generate(model, [PROBE] * 20, 24, sample=True, seed=1)]\n", " rate = sum(s.lstrip().startswith(\"Triage this support message\") for s in samples) / len(samples)\n", " greedy = generate(model, [PROBE], 24)[0][0]\n", " no_mask_rows.append([name, f\"{agg['exact']:.4f}\", f\"{agg['format_ok']:.4f}\", f\"{rl_:.4f}\", f\"{ul:.4f}\", f\"{rate:.2f}\", greedy])\n", " print(f\"{name:28s} exact {agg['exact']:6.1%} | response loss {rl_:.3f} | loss on the user's tokens {ul:.3f} | \"\n", " f\"writes the instruction by itself {rate:.0%} of 20 samples\")\n", " print(f\"{'':28s} greedy continuation of the probe: {greedy!r}\")\n", "save_csv(\"failure-no-mask.csv\", [\"run\", \"heldout_exact\", \"heldout_format_ok\", \"heldout_response_loss\", \"heldout_user_token_loss\",\n", " \"prompt_writing_rate_of_20\", \"greedy_probe_continuation\"], no_mask_rows)\n", "ok.pop(\"model_obj\"), broken.pop(\"model_obj\")\n", "model = res = None\n", "free()" ], "execution_count": null, "outputs": [], "id": "lab-5-4-finetune-38" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: both models give answers in the right format, yet one of them has learned something nobody asked\n", "for. Compare the two **loss on the user's tokens** values and the probe row. What is the second model now\n", "able to do? Which tokens carry the training signal in each run? Fix the run and make the two numbers\n", "behave the way you expect." ], "id": "lab-5-4-finetune-39" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 13b · The wrong chat template at inference\n", "\n", "We train correctly (section 8's LoRA model), then ask the same 48 held-out questions in seven formats.\n", "Only the first is what the model was trained on." ], "id": "lab-5-4-finetune-40" }, { "cell_type": "code", "metadata": {}, "source": [ "VARIANTS = {\n", " \"as trained (chat template)\": lambda u: chat_text(u),\n", " \"no system block\": lambda u: f\"<|im_start|>user\\n{u}<|im_end|>\\n<|im_start|>assistant\\n\",\n", " \"forgot the assistant cue\": lambda u: chat_text(u)[:chat_text(u).rindex(\"<|im_start|>assistant\")],\n", " \"plain text, no template\": lambda u: u,\n", " \"[INST] style (another family)\": lambda u: f\"[INST] {u} [/INST]\",\n", " \"### Instruction style\": lambda u: f\"### Instruction:\\n{u}\\n\\n### Response:\\n\",\n", " \"wrong role names\": lambda u: f\"<|im_start|>human\\n{u}<|im_end|>\\n<|im_start|>bot\\n\",\n", "}\n", "tuned = finetune(INSTRUCT, \"lora\", r=8, lr=2e-4, epochs=EPOCHS, label=\"tuned for 13b\")\n", "tmpl_rows = []\n", "for name, fn in VARIANTS.items():\n", " agg, outs = evaluate_generation(tuned[\"model_obj\"], HELD, prompt_fn=fn)\n", " ex_out = outs[0].replace(\"\\n\", \"\\\\n\")\n", " tmpl_rows.append([name, f\"{agg['format_ok']:.4f}\", f\"{agg['exact']:.4f}\", f\"{agg['category_ok']:.4f}\",\n", " f\"{agg['first_line_exact']:.4f}\", f\"{agg['stopped']:.4f}\", ex_out[:70]])\n", " print(f\"{name:32s} exact {agg['exact']:6.1%} first line right {agg['first_line_exact']:6.1%} stops by itself {agg['stopped']:6.1%} \"\n", " f\"category word only {agg['category_ok']:6.1%} first answer: {ex_out[:60]!r}\")\n", "# the untuned instruct model, on one general question, under the same formats\n", "gen_rows = []\n", "for name, fn in VARIANTS.items():\n", " t, stopped = generate(m_inst, [fn(\"What is the capital of France?\")], 30)[0]\n", " gen_rows.append([name, t.replace(\"\\n\", \"\\\\n\"), int(stopped)])\n", " print(f\" untuned instruct, {name:32s} -> {t!r}\")\n", "save_csv(\"failure-template.csv\", [\"format\", \"heldout_format_ok\", \"heldout_exact\", \"heldout_category_ok\", \"heldout_first_line_exact\",\n", " \"heldout_stopped_by_end_token\", \"first_answer\"], tmpl_rows)\n", "save_csv(\"failure-template-untuned.csv\", [\"format\", \"answer_to_capital_of_France\", \"stopped_by_end_token\"], gen_rows)\n", "tuned.pop(\"model_obj\")\n", "m_inst = None\n", "free()" ], "execution_count": null, "outputs": [], "id": "lab-5-4-finetune-41" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: the same weights, the same questions, very different answers. Which formats still work, which\n", "fail, and *how* do they fail (wrong content, wrong format, no stop)? Why does the model care about\n", "tokens that are \"only formatting\"? What does the training data teach about what follows\n", "`<|im_start|>assistant\\n`? How would you check which template a downloaded model expects?" ], "id": "lab-5-4-finetune-42" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 13c · A rank and a learning rate that are too high\n", "\n", "Now only **24** training examples, many epochs, and three settings: a small adapter with a small\n", "learning rate, a bigger adapter with the same rate, and a big adapter with a 10 x higher rate. We record\n", "the loss on the training examples and on the 48 held-out ones after every epoch." ], "id": "lab-5-4-finetune-43" }, { "cell_type": "code", "metadata": {}, "source": [ "small = TRAIN[:24]\n", "OVER = [(\"r=4, lr=1e-4\", 4, 1e-4), (\"r=64, lr=1e-4\", 64, 1e-4), (\"r=64, lr=1e-3\", 64, 1e-3)]\n", "over_rows = []\n", "ep_n = 2 if SMOKE else 30\n", "for name, r, lr in OVER:\n", " res = finetune(INSTRUCT, \"lora\", r=r, lr=lr, epochs=ep_n, train=small, per_epoch=True, label=name)\n", " agg, _ = metrics_of(res)\n", " for h in res[\"hist\"]:\n", " over_rows.append([name, r, lr, h[\"epoch\"], f\"{h['train_loss']:.4f}\", f\"{h['heldout_loss']:.4f}\"])\n", " best = min(res[\"hist\"], key=lambda h: h[\"heldout_loss\"])\n", " last = res[\"hist\"][-1]\n", " print(f\"{name:16s} trainable {res['trainable_params']:>10,} | epoch {last['epoch']}: train loss {last['train_loss']:.4f}, \"\n", " f\"held-out loss {last['heldout_loss']:.4f} | lowest held-out loss {best['heldout_loss']:.4f} at epoch {best['epoch']} | \"\n", " f\"held-out exact {agg['exact']:.1%}\")\n", " res.pop(\"model_obj\")\n", " free()\n", "save_csv(\"failure-overfit.csv\", [\"run\", \"rank\", \"lr\", \"epoch\", \"train_loss\", \"heldout_loss\"], over_rows)" ], "execution_count": null, "outputs": [], "id": "lab-5-4-finetune-44" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: the training loss keeps falling, yet something else does not. Plot (or read) train and held-out\n", "loss per epoch for the three runs. Where does each run's held-out loss stop improving? What is the model\n", "doing with the extra capacity? What are three cheap ways to find the best epoch and avoid the damage\n", "(hint: look at what you recorded)? Which of the three is the safest default for 24 examples?" ], "id": "lab-5-4-finetune-45" }, { "cell_type": "code", "metadata": {}, "source": [ "print(\"Versions tested:\",\n", " f\"Python {platform.python_version()}, torch {torch.__version__} (CUDA {torch.version.cuda}),\",\n", " f\"transformers {transformers.__version__},\", end=\" \")\n", "try:\n", " import peft\n", " print(f\"peft {peft.__version__},\", end=\" \")\n", "except ImportError:\n", " print(\"peft not installed,\", end=\" \")\n", "print(f\"on {GPU_NAME} ({platform.system()} {platform.machine()})\")\n", "print(\"models:\", INSTRUCT[0], INSTRUCT[1][:8], \"|\", BASE[0], BASE[1][:8])" ], "execution_count": null, "outputs": [], "id": "lab-5-4-finetune-46" } ] }