{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "cell-01",
   "metadata": {},
   "source": [
    "# 12b · Train a fast encoder decision model\n",
    "\n",
    "A recorded trace ends before the expected outcome was verified. Should the desk classify it as a premature stop, a missing verification step, or another kind of failure? Compare a few-shot encoder, hard supervision, teacher distributions and a hybrid repair. Treat tool calls as recorded data throughout.\n",
    "\n",
    "[Open the lesson](https://docs.recohut.com/courses/advanced-llm-fine-tuning/3-adapt-models/12b-train-a-fast-encoder-decision-model)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-02",
   "metadata": {},
   "source": [
    "## Which environment runs the comparison?\n",
    "\n",
    "Use a single T4. The encoder arms use FP16 automatic mixed precision and the generative comparator uses FP16 weights. The T4 lacks native BF16 Tensor Cores. BF16 performance is outside this comparison."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-03",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import subprocess\n",
    "import sys\n",
    "\n",
    "os.environ[\"USE_TF\"] = \"0\"\n",
    "subprocess.run([sys.executable, \"-m\", \"pip\", \"install\", \"-q\",\n",
    "    \"transformers==4.57.1\", \"sentence-transformers==5.1.2\",\n",
    "    \"scikit-learn==1.7.2\", \"huggingface-hub==0.36.0\", \"pyarrow==20.0.0\"], check=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-04",
   "metadata": {},
   "source": [
    "## Which functions define the experiment?\n",
    "\n",
    "Keep data preparation, class definitions, model heads, training and scoring explicit. Teacher and reference labels use the same option order."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-05",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"Data preparation, training and scoring for the trace triage experiment.\"\"\"\n",
    "\n",
    "import hashlib\n",
    "import json\n",
    "import math\n",
    "import random\n",
    "import re\n",
    "from collections import Counter\n",
    "from pathlib import Path\n",
    "from time import perf_counter\n",
    "\n",
    "import numpy as np\n",
    "import torch\n",
    "from sklearn.feature_extraction.text import TfidfVectorizer\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "from sklearn.metrics import confusion_matrix, f1_score\n",
    "from sklearn.pipeline import make_pipeline\n",
    "from torch import nn\n",
    "from torch.nn import functional as F\n",
    "\n",
    "SEED = 42\n",
    "FAILURES = {\n",
    "    \"incorrect_tool_selection\": \"The selected tool does a different job than the current step requires.\",\n",
    "    \"invalid_tool_arguments\": \"A supplied argument has an invalid type or value.\",\n",
    "    \"missing_required_arguments\": \"A required argument is absent from the call.\",\n",
    "    \"hallucinated_tool_output\": \"A claim invents a result that the tool never returned.\",\n",
    "    \"failure_to_follow_constraints\": \"An action violates an explicit request constraint.\",\n",
    "    \"premature_completion\": \"The workflow stops while required work remains.\",\n",
    "    \"failure_to_recover\": \"A recoverable tool error is present and the workflow fails to handle it.\",\n",
    "    \"failure_to_verify_completion\": \"The workflow skips a needed check that the intended outcome happened.\",\n",
    "    \"incorrect_final_answer\": \"The final answer gives a wrong result despite the available information.\",\n",
    "}\n",
    "OPTIONS = {\n",
    "    **FAILURES,\n",
    "    \"clean\": \"The recorded workflow completed without an annotated failure.\",\n",
    "    \"out_of_scope\": \"A standalone request falls outside the trace-triage queue.\",\n",
    "}\n",
    "CLASSES = tuple(OPTIONS)\n",
    "BLIND_SPOTS = {\"failure_to_verify_completion\": \"premature_completion\",\n",
    "               \"hallucinated_tool_output\": \"incorrect_final_answer\"}\n",
    "SPLITS = (\"train\", \"gold_val\", \"gold_calibration\", \"gold_test\")\n",
    "COUNTS = {\"train\": 32, \"gold_val\": 12, \"gold_calibration\": 12, \"gold_test\": 16}\n",
    "MAX_LENGTH = 384\n",
    "\n",
    "\n",
    "def norm(text):\n",
    "    return \" \".join(re.findall(r\"\\w+\", text.casefold()))\n",
    "\n",
    "\n",
    "def stable_id(value):\n",
    "    return hashlib.sha256(value.encode()).hexdigest()\n",
    "\n",
    "\n",
    "def trace_example(row):\n",
    "    category = row[\"failure_category\"] or \"clean\"\n",
    "    if category not in OPTIONS:\n",
    "        return None\n",
    "    # Inputs available in an ordinary replay. Omit all diagnosis and correction fields.\n",
    "    steps = [\n",
    "        {\"call\": step.get(\"tool_call\"), \"result\": step.get(\"tool_output\")}\n",
    "        for step in row[\"agent_trajectory\"]\n",
    "    ]\n",
    "    body = {\"request\": row[\"task_description\"], \"constraints\": row[\"user_constraints\"],\n",
    "            \"observations\": steps, \"reply\": row[\"final_answer\"]}\n",
    "    text = json.dumps(body, ensure_ascii=False, sort_keys=True)\n",
    "    return {\"id\": row[\"task_id\"], \"group\": row[\"scenario_id\"],\n",
    "            \"domain\": row[\"domain\"], \"text\": text, \"label\": category,\n",
    "            \"source\": \"AgentFailureBench\"}\n",
    "\n",
    "\n",
    "def prepare_splits(trace_rows, oos):\n",
    "    traces = [item for row in trace_rows if (item := trace_example(row)) is not None]\n",
    "    # The card reports one canonical task template per domain. Keep domains intact.\n",
    "    domains = sorted({item[\"domain\"] for item in traces})\n",
    "    assert len(domains) >= 7, domains\n",
    "    random.Random(SEED).shuffle(domains)\n",
    "    assignment = dict(zip(SPLITS, (domains[4:], domains[:1], domains[1:2], domains[2:4])))\n",
    "    groups, unique_texts, ids = set(), set(), set()\n",
    "    splits = {}\n",
    "    for split, domains_for_split in assignment.items():\n",
    "        pools = [item for item in traces if item[\"domain\"] in domains_for_split]\n",
    "        pools += [{\"id\": \"oos:\" + stable_id(norm(text)), \"group\": \"oos:\" + stable_id(norm(text)),\n",
    "                   \"domain\": \"none\", \"text\": text, \"label\": \"out_of_scope\",\n",
    "                   \"source\": \"CLINC150\"} for text in oos[split]]\n",
    "        selected, counts = [], Counter()\n",
    "        for row in sorted(pools, key=lambda row: stable_id(str(SEED) + split + row[\"id\"])):\n",
    "            signature = norm(row[\"text\"])\n",
    "            if counts[row[\"label\"]] >= COUNTS[split]:\n",
    "                continue\n",
    "            if signature in unique_texts or row[\"group\"] in groups or row[\"id\"] in ids:\n",
    "                continue\n",
    "            selected.append(row)\n",
    "            counts[row[\"label\"]] += 1\n",
    "            unique_texts.add(signature)\n",
    "            groups.add(row[\"group\"])\n",
    "            ids.add(row[\"id\"])\n",
    "        splits[split] = selected\n",
    "    return splits, assignment\n",
    "\n",
    "\n",
    "def label_ids(rows):\n",
    "    return torch.tensor([CLASSES.index(row[\"label\"]) for row in rows], dtype=torch.long)\n",
    "\n",
    "\n",
    "def macro_score(labels, predictions):\n",
    "    return float(f1_score(labels, predictions, labels=range(len(CLASSES)), average=\"macro\", zero_division=0))\n",
    "\n",
    "\n",
    "def teacher_fit(train):\n",
    "    # A weak, lexical teacher. We collapse two classes to represent known gaps in its rubric.\n",
    "    teacher = make_pipeline(TfidfVectorizer(ngram_range=(1, 2), max_features=10000),\n",
    "                            LogisticRegression(max_iter=500, random_state=SEED))\n",
    "    teacher.fit([r[\"text\"] for r in train], [BLIND_SPOTS.get(r[\"label\"], r[\"label\"]) for r in train])\n",
    "    return teacher\n",
    "\n",
    "\n",
    "def teacher_probs(teacher, rows):\n",
    "    raw = teacher.predict_proba([r[\"text\"] for r in rows])\n",
    "    out = np.zeros((len(rows), len(CLASSES)), dtype=np.float32)\n",
    "    for j, name in enumerate(teacher.classes_):\n",
    "        out[:, CLASSES.index(name)] = raw[:, j]\n",
    "    return torch.tensor(out)\n",
    "\n",
    "\n",
    "def per_class(labels, predictions):\n",
    "    matrix = confusion_matrix(labels, predictions, labels=range(len(CLASSES)))\n",
    "    return {\"confusion\": matrix.tolist(), \"macro_f1\": macro_score(labels, predictions),\n",
    "            \"recall\": {name: float(matrix[i, i] / matrix[i].sum()) if matrix[i].sum() else None\n",
    "                       for i, name in enumerate(CLASSES)},\n",
    "            \"counts\": {name: int(matrix[i].sum()) for i, name in enumerate(CLASSES)}}\n",
    "\n",
    "\n",
    "def soft_ce(target, logits):\n",
    "    return -(target * torch.log_softmax(logits.float(), -1)).sum(-1).mean()\n",
    "\n",
    "\n",
    "def hybrid_targets(target, labels, overrides):\n",
    "    mask = torch.isin(labels, torch.tensor(overrides, dtype=labels.dtype, device=labels.device))\n",
    "    gold = F.one_hot(labels, num_classes=target.shape[-1]).float()\n",
    "    return torch.where(mask.unsqueeze(-1), gold, target)\n",
    "\n",
    "\n",
    "def reliability(logits, labels, temperature=1.0, bins=10):\n",
    "    confidence, predictions = (logits.float() / temperature).softmax(-1).max(-1)\n",
    "    correct = predictions.eq(labels).float()\n",
    "    groups = torch.clamp((confidence * bins).long(), max=bins - 1)\n",
    "    rows = []\n",
    "    for i in range(bins):\n",
    "        mask = groups.eq(i)\n",
    "        n = int(mask.sum())\n",
    "        rows.append(dict(count=n, low=i / bins, high=(i + 1) / bins,\n",
    "                         confidence=float(confidence[mask].mean()) if n else None,\n",
    "                         accuracy=float(correct[mask].mean()) if n else None))\n",
    "    ece = sum(r[\"count\"] / len(labels) * abs(r[\"confidence\"] - r[\"accuracy\"]) for r in rows if r[\"count\"])\n",
    "    return {\"ece\": ece, \"nll\": float(F.cross_entropy(logits.float() / temperature, labels)), \"bins\": rows}\n",
    "\n",
    "\n",
    "def fit_temperature(logits, labels):\n",
    "    # The optimisation can never see the gold test labels.\n",
    "    lower, upper = math.log(0.05), math.log(20.0)\n",
    "    for _ in range(40):\n",
    "        left = (2 * lower + upper) / 3\n",
    "        right = (lower + 2 * upper) / 3\n",
    "        if F.cross_entropy(logits / math.exp(left), labels) <= F.cross_entropy(logits / math.exp(right), labels):\n",
    "            upper = right\n",
    "        else:\n",
    "            lower = left\n",
    "    return math.exp((lower + upper) / 2)\n",
    "\n",
    "\n",
    "class OptionScorer(nn.Module):\n",
    "    def __init__(self, encoder):\n",
    "        super().__init__()\n",
    "        self.encoder = encoder\n",
    "        hidden = encoder.config.hidden_size\n",
    "        self.head = nn.Sequential(nn.Linear(hidden * 4, hidden), nn.GELU(), nn.Linear(hidden, 1))\n",
    "\n",
    "    def encode(self, features):\n",
    "        last = self.encoder(**features).last_hidden_state\n",
    "        mask = features[\"attention_mask\"].unsqueeze(-1).to(last.dtype)\n",
    "        return (last * mask).sum(1) / mask.sum(1).clamp_min(1)\n",
    "\n",
    "    def forward(self, input_features, options_features):\n",
    "        inputs = self.encode(input_features)\n",
    "        options = self.encode(options_features)\n",
    "        inputs = inputs[:, None, :].expand(-1, len(options), -1)\n",
    "        options = options[None, :, :].expand(len(inputs), -1, -1)\n",
    "        return self.head(torch.cat((inputs, options, inputs * options, (inputs - options).abs()), dim=-1)).squeeze(-1)\n",
    "\n",
    "\n",
    "def encode_features(tokenizer, texts, max_length=MAX_LENGTH):\n",
    "    tokenizer.truncation_side = \"left\"\n",
    "    return tokenizer(texts, truncation=True, max_length=max_length,\n",
    "                     padding=True, pad_to_multiple_of=8, return_token_type_ids=False, return_tensors=\"pt\")\n",
    "\n",
    "\n",
    "def device_features(features, device, indices=None):\n",
    "    return {key: (value if indices is None else value[indices]).to(device)\n",
    "            for key, value in features.items()}\n",
    "\n",
    "\n",
    "def evaluate_options(model, features, options, device, batch_size=8):\n",
    "    model.eval()\n",
    "    batched = []\n",
    "    with torch.inference_mode(), torch.autocast(\"cuda\", dtype=torch.float16, enabled=device.type == \"cuda\"):\n",
    "        for ids in torch.arange(len(features[\"input_ids\"])).split(batch_size):\n",
    "            logits = model(device_features(features, device, ids), options).float()\n",
    "            assert torch.isfinite(logits).all()\n",
    "            batched.append(logits.cpu())\n",
    "    return torch.cat(batched)\n",
    "\n",
    "\n",
    "def choose_checkpoints(history):\n",
    "    gold_epoch = max(history, key=lambda row: (row[\"val_gold_macro_f1\"], -row[\"epoch\"]))[\"epoch\"]\n",
    "    teacher_epoch = max(history, key=lambda row: (row[\"val_teacher_agreement\"], -row[\"epoch\"]))[\"epoch\"]\n",
    "    return gold_epoch, teacher_epoch\n",
    "\n",
    "\n",
    "def fit_options(new_encoder, features, options, labels, target, teacher_val, device, *, epochs=4, batch_size=8):\n",
    "    # Reset model, batch order and head seed for every arm.\n",
    "    torch.manual_seed(SEED)\n",
    "    model = OptionScorer(new_encoder()).to(device)\n",
    "    optimizer = torch.optim.AdamW([{\"params\": model.encoder.parameters(), \"lr\": 2e-5},\n",
    "                                  {\"params\": model.head.parameters(), \"lr\": 1e-4}])\n",
    "    scaler = torch.amp.GradScaler(\"cuda\", init_scale=128, enabled=device.type == \"cuda\")\n",
    "    order = torch.Generator().manual_seed(SEED)\n",
    "    history = []\n",
    "    best = {}\n",
    "    for epoch in range(1, epochs + 1):\n",
    "        model.train()\n",
    "        updates = 0\n",
    "        for ids in torch.randperm(len(target), generator=order).split(batch_size):\n",
    "            optimizer.zero_grad(set_to_none=True)\n",
    "            with torch.autocast(\"cuda\", dtype=torch.float16, enabled=device.type == \"cuda\"):\n",
    "                logits = model(device_features(features[\"train\"], device, ids), options)\n",
    "                loss = soft_ce(target[ids].to(device), logits)\n",
    "            assert torch.isfinite(loss)\n",
    "            prev_scale = scaler.get_scale()\n",
    "            scaler.scale(loss).backward()\n",
    "            scaler.unscale_(optimizer)\n",
    "            nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n",
    "            scaler.step(optimizer)\n",
    "            scaler.update()\n",
    "            updates += int(scaler.get_scale() >= prev_scale)\n",
    "        assert updates > 0, \"Every optimiser step was skipped\"\n",
    "        val = evaluate_options(model, features[\"gold_val\"], options, device).argmax(-1)\n",
    "        history.append({\"epoch\": epoch, \"attempted_updates\": math.ceil(len(target) / batch_size),\n",
    "                        \"updates\": updates, \"val_gold_macro_f1\": macro_score(labels[\"gold_val\"], val),\n",
    "                        \"val_teacher_agreement\": float(val.eq(teacher_val).float().mean())})\n",
    "        for name, selected in zip((\"gold\", \"teacher\"), choose_checkpoints(history)):\n",
    "            if selected == epoch:\n",
    "                best[name] = {key: value.detach().cpu().clone() for key, value in model.state_dict().items()}\n",
    "    return model, history, best\n",
    "\n",
    "\n",
    "def tune_sentence_embedder(model, rows, device, *, n_per_class=12, pairs_per_class=16):\n",
    "    # SetFit's contrastive sentence-pair task with a logistic head.\n",
    "    pools = [[r[\"text\"] for r in rows if r[\"label\"] == name][:n_per_class] for name in CLASSES]\n",
    "    assert all(len(pool) >= 8 for pool in pools)\n",
    "    rng = random.Random(SEED)\n",
    "    pairs = []\n",
    "    for i, pool in enumerate(pools):\n",
    "        negatives = [item for j, other in enumerate(pools) if j != i for item in other]\n",
    "        for _ in range(pairs_per_class):\n",
    "            a, b = rng.sample(pool, 2)\n",
    "            pairs.extend(((a, b, 1.0), (a, rng.choice(negatives), 0.0)))\n",
    "    rng.shuffle(pairs)\n",
    "    optimiser = torch.optim.AdamW(model.parameters(), lr=2e-5)\n",
    "    scaler = torch.amp.GradScaler(\"cuda\", init_scale=128, enabled=device.type == \"cuda\")\n",
    "    model.train()\n",
    "    updates = 0\n",
    "    for start in range(0, len(pairs), 16):\n",
    "        left, right, targets = zip(*pairs[start:start + 16])\n",
    "        optimiser.zero_grad(set_to_none=True)\n",
    "        with torch.autocast(\"cuda\", dtype=torch.float16, enabled=device.type == \"cuda\"):\n",
    "            first = model(device_features(model.tokenize(list(left)), device))[\"sentence_embedding\"]\n",
    "            second = model(device_features(model.tokenize(list(right)), device))[\"sentence_embedding\"]\n",
    "            cosine = F.cosine_similarity(first.float(), second.float())\n",
    "            loss = F.mse_loss(cosine, torch.tensor(targets, device=device))\n",
    "        assert torch.isfinite(loss)\n",
    "        prev_scale = scaler.get_scale()\n",
    "        scaler.scale(loss).backward()\n",
    "        scaler.step(optimiser)\n",
    "        scaler.update()\n",
    "        updates += int(scaler.get_scale() >= prev_scale)\n",
    "    assert updates > 0, \"SetFit skipped every optimiser step\"\n",
    "    model.eval()\n",
    "    x = [text for pool in pools for text in pool]\n",
    "    y = [i for i, pool in enumerate(pools) for _ in pool]\n",
    "    return LogisticRegression(max_iter=500, random_state=SEED).fit(model.encode(x), y)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-06",
   "metadata": {},
   "source": [
    "## Which benchmark rows can reach each split?\n",
    "\n",
    "Use the publisher's synthetic trace annotations as reference labels. Keep entire trace domains apart because the publisher uses one request template per domain. Take CLINC150's published out-of-scope rows only and keep its original test separate. The CLINC validation pool supplies two disjoint slices. The course selects nine of the trace dataset's failure categories plus clean and out-of-scope."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-07",
   "metadata": {},
   "outputs": [],
   "source": [
    "import gc\n",
    "import importlib.metadata\n",
    "import pandas as pd\n",
    "from huggingface_hub import hf_hub_download\n",
    "from sentence_transformers import SentenceTransformer\n",
    "from transformers import AutoModel, AutoModelForCausalLM, AutoTokenizer\n",
    "\n",
    "assert torch.cuda.is_available() and \"T4\" in torch.cuda.get_device_name()\n",
    "device = torch.device(\"cuda\")\n",
    "torch.manual_seed(SEED)\n",
    "torch.set_num_threads(4)\n",
    "out = Path(\"results\")\n",
    "out.mkdir(exist_ok=True)\n",
    "\n",
    "TRACE = \"fahadhafeezofficial/agent-failure-bench\"\n",
    "TRACE_REV = \"93257fb35460ed2916189467491e153d9f5844b2\"\n",
    "OOS = \"clinc/clinc_oos\"\n",
    "OOS_REV = \"155b9c710419136e17307b80d0a13e68cd46b4ec\"\n",
    "MODERN = \"answerdotai/ModernBERT-base\"\n",
    "MODERN_REV = \"8949b909ec900327062f0ebf497f51aef5e6f0c8\"\n",
    "MINILM = \"sentence-transformers/all-MiniLM-L6-v2\"\n",
    "MINILM_REV = \"1110a243fdf4706b3f48f1d95db1a4f5529b4d41\"\n",
    "LLM = \"Qwen/Qwen2.5-0.5B-Instruct\"\n",
    "LLM_REV = \"7ae557604adf67be50417f59c2c2f167def9a775\"\n",
    "\n",
    "def save(name, value):\n",
    "    (out / name).write_text(json.dumps(value, ensure_ascii=False, indent=2) + \"\\n\")\n",
    "\n",
    "def stream_trace():\n",
    "    for split in (\"train\", \"validation\", \"test\"):\n",
    "        path = hf_hub_download(TRACE, f\"dataset/{split}.jsonl\", revision=TRACE_REV, repo_type=\"dataset\")\n",
    "        with open(path, encoding=\"utf-8\") as stream:\n",
    "            for line in stream:\n",
    "                yield json.loads(line)\n",
    "\n",
    "def read_oos(split):\n",
    "    path = hf_hub_download(OOS, f\"plus/{split}-00000-of-00001.parquet\", revision=OOS_REV, repo_type=\"dataset\")\n",
    "    rows = pd.read_parquet(path)\n",
    "    return list(rows.loc[rows[\"intent\"] == 42, \"text\"])\n",
    "\n",
    "oos_val = sorted(read_oos(\"validation\"), key=lambda text: stable_id(norm(text)))\n",
    "val_pool, calibration_pool = oos_val[::2], oos_val[1::2]\n",
    "slices, domain_assignment = prepare_splits(stream_trace(), {\n",
    "    \"train\": read_oos(\"train\"), \"gold_val\": val_pool,\n",
    "    \"gold_calibration\": calibration_pool, \"gold_test\": read_oos(\"test\"),\n",
    "})\n",
    "coverage = {key: dict(Counter(r[\"label\"] for r in rows)) for key, rows in slices.items()}\n",
    "missing = {key: sorted(set(CLASSES) - set(counts)) for key, counts in coverage.items()}\n",
    "save(\"split-audit.json\", {\"domains\": domain_assignment, \"counts\": coverage, \"missing\": missing,\n",
    "                        \"ids\": {k: [r[\"id\"] for r in rows] for k, rows in slices.items()},\n",
    "                        \"exact_input_hashes\": {k: [stable_id(norm(r[\"text\"])) for r in rows] for k, rows in slices.items()},\n",
    "                        \"sources\": {TRACE: TRACE_REV, OOS: OOS_REV}})\n",
    "print(\"Class counts\", coverage, \"missing\", missing)\n",
    "assert not any(missing.values()), \"A split lacks reference class coverage\"\n",
    "assert min(coverage[\"train\"].values()) >= 8, \"SetFit needs at least eight options per class\"\n",
    "all_rows = [r for rows in slices.values() for r in rows]\n",
    "for key, values in {\n",
    "    \"ids\": [r[\"id\"] for r in all_rows],\n",
    "    \"groups\": [r[\"group\"] for r in all_rows],\n",
    "    \"normalised inputs\": [norm(r[\"text\"]) for r in all_rows],\n",
    "}.items():\n",
    "    assert len(values) == len(set(values)), f\"Leakage in {key}\"\n",
    "labels = {key: label_ids(rows) for key, rows in slices.items()}\n",
    "texts = {key: [r[\"text\"] for r in rows] for key, rows in slices.items()}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-08",
   "metadata": {},
   "source": [
    "## Where does the teacher disagree with the reference labels?\n",
    "\n",
    "The local teacher learns lexical features and uses a deliberately incomplete rubric. It groups two adjacent failure categories with broader classes. Its probabilities still distinguish the remaining options. This controlled teacher makes an audit and a targeted repair possible without calling a commercial model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-09",
   "metadata": {},
   "outputs": [],
   "source": [
    "teacher = teacher_fit(slices[\"train\"])\n",
    "teacher_targets = {key: teacher_probs(teacher, rows) for key, rows in slices.items()}\n",
    "audit = per_class(labels[\"gold_val\"], teacher_targets[\"gold_val\"].argmax(-1))\n",
    "override_names = [name for name in BLIND_SPOTS if audit[\"recall\"][name] == 0.0]\n",
    "assert override_names and set(override_names) == set(BLIND_SPOTS)\n",
    "overrides = [CLASSES.index(name) for name in override_names]\n",
    "save(\"teacher-audit.json\", {\"class_order\": CLASSES, \"val\": audit, \"hybrid_overrides\": override_names})\n",
    "print(\"Teacher validation audit\", audit)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-10",
   "metadata": {},
   "source": [
    "## Can a few examples teach the decision?\n",
    "\n",
    "Use SetFit's two stages. Train the sentence embedder to bring same-class pairs closer and push different-class pairs apart, then fit a logistic classifier on the sampled sentences. Each option contributes the same labelled-example budget."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-11",
   "metadata": {},
   "outputs": [],
   "source": [
    "setfit_model = SentenceTransformer(MINILM, revision=MINILM_REV, device=str(device))\n",
    "setfit_model.max_seq_length = MAX_LENGTH\n",
    "setfit_head = tune_sentence_embedder(setfit_model, slices[\"train\"], device)\n",
    "setfit_model.half()\n",
    "def setfit_batch(text):\n",
    "    return setfit_head.predict_proba(setfit_model.encode(text, show_progress_bar=False))\n",
    "\n",
    "setfit_test = setfit_batch(texts[\"gold_test\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-12",
   "metadata": {},
   "source": [
    "## How is milliseconds per trace measured?\n",
    "\n",
    "Warm up each model, synchronise the device around every request, and time the same held-out rows in the same order at batch size one. Include tokenisation and classifier or option scoring. Exclude download and model loading. Compare with one forced-choice next-token decision from a generative checkpoint."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-13",
   "metadata": {},
   "outputs": [],
   "source": [
    "def measure_latency(read):\n",
    "    roster = texts[\"gold_test\"][:24]\n",
    "    for text in roster[:4]:\n",
    "        read(text)\n",
    "    durations = []\n",
    "    for text in roster:\n",
    "        torch.cuda.synchronize()\n",
    "        start = perf_counter()\n",
    "        read(text)\n",
    "        torch.cuda.synchronize()\n",
    "        durations.append((perf_counter() - start) * 1000)\n",
    "    ordered = sorted(durations)\n",
    "    return {\"n\": len(roster), \"ms\": durations, \"median_ms\": float(np.median(durations)),\n",
    "            \"p95_nearest_rank_ms\": ordered[math.ceil(0.95 * len(ordered)) - 1]}\n",
    "\n",
    "latency = {\"setfit\": measure_latency(lambda text: setfit_batch([text]))}\n",
    "del setfit_model\n",
    "gc.collect()\n",
    "torch.cuda.empty_cache()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-14",
   "metadata": {},
   "source": [
    "## What changes between hard, soft and hybrid training?\n",
    "\n",
    "A shared encoder embeds each trace and each option description. A two-layer head scores their interaction. Only the target distribution changes across these arms. The hybrid keeps gold labels where the audit found a teacher blind spot. It uses teacher probabilities on the other examples."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-15",
   "metadata": {},
   "outputs": [],
   "source": [
    "tokenizer = AutoTokenizer.from_pretrained(MODERN, revision=MODERN_REV)\n",
    "def new_encoder():\n",
    "    return AutoModel.from_pretrained(MODERN, revision=MODERN_REV,\n",
    "                                     attn_implementation=\"sdpa\", reference_compile=False)\n",
    "\n",
    "features = {key: encode_features(tokenizer, values) for key, values in texts.items()}\n",
    "input_width = {key: [len(tokens) for tokens in tokenizer(values, truncation=False)[\"input_ids\"]]\n",
    "               for key, values in texts.items()}\n",
    "save(\"input-budget.json\", {\"max_tokens\": MAX_LENGTH, \"side\": \"left\",\n",
    "                           \"truncated\": {key: sum(n > MAX_LENGTH for n in values)\n",
    "                                         for key, values in input_width.items()},\n",
    "                           \"maximum\": {key: max(values) for key, values in input_width.items()}})\n",
    "options = device_features(encode_features(tokenizer, list(OPTIONS.values()), max_length=72), device)\n",
    "gold = F.one_hot(labels[\"train\"], num_classes=len(CLASSES)).float()\n",
    "targets = {\"hard_gold\": gold, \"soft_teacher\": teacher_targets[\"train\"],\n",
    "           \"hybrid\": hybrid_targets(teacher_targets[\"train\"], labels[\"train\"], overrides)}\n",
    "assert all(torch.allclose(values.sum(-1), torch.ones(len(values))) for values in targets.values())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-16",
   "metadata": {},
   "source": [
    "## Which checkpoint would each selection rule keep?\n",
    "\n",
    "At every epoch record agreement with the teacher and macro-F1 against the reference validation labels. Choose each encoder's main checkpoint by reference validation macro-F1. For the soft-target arm also select a checkpoint by teacher agreement and score it on the locked reference test. The rules may select the same epoch. Read their test errors even when they agree."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-17",
   "metadata": {},
   "outputs": [],
   "source": [
    "histories, scores, predictions = {}, {}, {}\n",
    "scores[\"setfit\"] = per_class(labels[\"gold_test\"], setfit_test.argmax(-1))\n",
    "predictions[\"setfit\"] = setfit_test.tolist()\n",
    "for name, arm_targets in targets.items():\n",
    "    model, history, checkpoints = fit_options(\n",
    "        new_encoder, features, options, labels, arm_targets,\n",
    "        teacher_targets[\"gold_val\"].argmax(-1), device)\n",
    "    histories[name] = {\"epochs\": history, \"chosen_gold_teacher\": choose_checkpoints(history)}\n",
    "    model.load_state_dict(checkpoints[\"gold\"])\n",
    "    test_logits = evaluate_options(model, features[\"gold_test\"], options, device)\n",
    "    scores[name] = per_class(labels[\"gold_test\"], test_logits.argmax(-1))\n",
    "    predictions[name] = test_logits.softmax(-1).tolist()\n",
    "    if name == \"soft_teacher\":\n",
    "        model.load_state_dict(checkpoints[\"teacher\"])\n",
    "        other = evaluate_options(model, features[\"gold_test\"], options, device)\n",
    "        scores[\"soft_selected_by_teacher\"] = per_class(labels[\"gold_test\"], other.argmax(-1))\n",
    "        predictions[\"soft_selected_by_teacher\"] = other.softmax(-1).tolist()\n",
    "    if name == \"hybrid\":\n",
    "        with torch.inference_mode():\n",
    "            latency[name] = measure_latency(lambda text: evaluate_options(\n",
    "                model, encode_features(tokenizer, [text]), options, device))\n",
    "        calibration_logits = evaluate_options(model, features[\"gold_calibration\"], options, device)\n",
    "        temperature = fit_temperature(calibration_logits, labels[\"gold_calibration\"])\n",
    "        calibration = {\"temperature\": temperature, \"test_before\": reliability(test_logits, labels[\"gold_test\"]),\n",
    "                       \"test_after\": reliability(test_logits, labels[\"gold_test\"], temperature),\n",
    "                       \"fit_count\": len(calibration_logits)}\n",
    "        assert torch.equal(test_logits.argmax(-1), (test_logits / temperature).argmax(-1))\n",
    "        predictions[\"hybrid_scaled\"] = (test_logits / temperature).softmax(-1).tolist()\n",
    "    del model, checkpoints\n",
    "    gc.collect()\n",
    "    torch.cuda.empty_cache()\n",
    "\n",
    "save(\"encoder-results.json\", {\"class_order\": CLASSES, \"histories\": histories, \"scores\": scores,\n",
    "                              \"calibration\": calibration, \"reference\": slices[\"gold_test\"],\n",
    "                              \"probabilities\": predictions})\n",
    "print(\"Gold test macro-F1\", {name: score[\"macro_f1\"] for name, score in scores.items()})\n",
    "print(\"Calibration\", calibration)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-18",
   "metadata": {},
   "source": [
    "## How fast is a generative forced-choice comparison?\n",
    "\n",
    "Score only the next-token options from the same request and option catalogue. There is no tool execution and no free-form generation. Report the generative baseline as a separate inference comparison."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-19",
   "metadata": {},
   "outputs": [],
   "source": [
    "llm_tokenizer = AutoTokenizer.from_pretrained(LLM, revision=LLM_REV)\n",
    "llm = AutoModelForCausalLM.from_pretrained(LLM, revision=LLM_REV,\n",
    "                                         dtype=torch.float16).to(device).eval()\n",
    "letters = [chr(65 + i) for i in range(len(CLASSES))]\n",
    "letter_ids = [llm_tokenizer.encode(letter, add_special_tokens=False) for letter in letters]\n",
    "assert all(len(tokens) == 1 for tokens in letter_ids)\n",
    "token_ids = [tokens[0] for tokens in letter_ids]\n",
    "catalogue = \"\\n\".join(f\"{letter}. {description}\" for letter, description in zip(letters, OPTIONS.values()))\n",
    "\n",
    "@torch.inference_mode()\n",
    "def llm_choose(text):\n",
    "    # The raw trace is quoted data, and the only permissible output is an option token.\n",
    "    trace_ids = llm_tokenizer.encode(text, add_special_tokens=False)[-MAX_LENGTH:]\n",
    "    trace = llm_tokenizer.decode(trace_ids, skip_special_tokens=True)\n",
    "    prompt = f\"Classify this recorded trace or request. Choose one option letter.\\n{catalogue}\\nRecord: {trace}\\nChoice:\"\n",
    "    values = llm_tokenizer(prompt, return_tensors=\"pt\").to(device)\n",
    "    return int(llm(**values, use_cache=False, logits_to_keep=1).logits[0, -1, token_ids].argmax())\n",
    "\n",
    "latency[\"qwen_forced_choice\"] = measure_latency(llm_choose)\n",
    "scores[\"qwen_forced_choice_latency_roster\"] = per_class(\n",
    "    labels[\"gold_test\"][:24], [llm_choose(text) for text in texts[\"gold_test\"][:24]])\n",
    "save(\"latency.json\", {\"hardware\": torch.cuda.get_device_name(), \"model_revisions\": {\n",
    "    MODERN: MODERN_REV, MINILM: MINILM_REV, LLM: LLM_REV},\n",
    "    \"packages\": {name: importlib.metadata.version(name) for name in\n",
    "                 (\"torch\", \"transformers\", \"sentence-transformers\", \"scikit-learn\", \"pyarrow\", \"huggingface-hub\")},\n",
    "    \"roster\": [r[\"id\"] for r in slices[\"gold_test\"][:24]], \"measurements\": latency,\n",
    "    \"qwen_latency_roster_scores\": scores[\"qwen_forced_choice_latency_roster\"]})\n",
    "print(\"Median milliseconds per trace\", {name: stats[\"median_ms\"] for name, stats in latency.items()})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-20",
   "metadata": {},
   "source": [
    "## Read the result\n",
    "\n",
    "Check reference coverage before reading aggregate scores. Compare the teacher confusion matrix with the held-out gains or regressions for each student. Read the validation epoch choices separately from their test results. Temperature is fitted on reference calibration data, then evaluated on reference test.\n",
    "\n",
    "[AgentFailureBench dataset card](https://huggingface.co/datasets/fahadhafeezofficial/agent-failure-bench) · [CLINC150](https://huggingface.co/datasets/clinc/clinc_oos) · [ModernBERT](https://arxiv.org/abs/2412.13663) · [SetFit](https://arxiv.org/abs/2209.11055) · [Calibration](https://arxiv.org/abs/1706.04599) · [Course lesson](https://docs.recohut.com/courses/advanced-llm-fine-tuning/3-adapt-models/12b-train-a-fast-encoder-decision-model)."
   ]
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
