Skip to content

armgit / laya

Public Imported from GitHub
0

Non-autoregressive System 1 decision engine. Typed choice, score and yes/no decisions over any text in a single forward pass, in 100+ languages, with a router that picks the right checkpoint per request.

feat: add typed-decisions fine-tuning & evaluation notebook

Nandakishor764e8b54e6f0
diff --git a/README.md b/README.md
index 26118ac2..ade5622d 100644
--- a/README.md
+++ b/README.md
@@ -175,16 +175,10 @@ triage = agent.predict({"message": "My payment failed twice"}, laya.triage_quest
## Fine-Tuning on Single T4 GPU (Google Colab)
-Fine-tune Laya on your custom domain data or commercial datasets on a free T4 GPU:
+Fine-tune Laya on custom domain data or the `LocalLLaMA/typed-decisions` benchmark on a free T4 GPU:
-<p align="left">
- <a href="https://colab.research.google.com/drive/15d4Yv__KHeHjshVb-6PRTfqVllxih2S3?usp=sharing" target="_blank">
- <img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab" />
- </a>
-</p>
-
-* **Colab Link:** [Open in Google Colab](https://colab.research.google.com/drive/15d4Yv__KHeHjshVb-6PRTfqVllxih2S3?usp=sharing)
-* **Local Notebook:** [`notebooks/laya_finetune_colab.ipynb`](notebooks/laya_finetune_colab.ipynb)
+* **Interactive Fine-Tuning Notebook:** [Fine-Tune on Custom Data](https://colab.research.google.com/drive/15d4Yv__KHeHjshVb-6PRTfqVllxih2S3?usp=sharing) ([`notebooks/laya_finetune_colab.ipynb`](notebooks/laya_finetune_colab.ipynb))
+* **Workflow Benchmark Fine-Tuning:** [`notebooks/laya_finetune_typed_decisions_colab.ipynb`](notebooks/laya_finetune_typed_decisions_colab.ipynb) — fine-tunes on `LocalLLaMA/typed-decisions` (1,200 cases), evaluates on 400 test cases, and pushes to Hugging Face.
---
diff --git a/notebooks/laya_finetune_typed_decisions_colab.ipynb b/notebooks/laya_finetune_typed_decisions_colab.ipynb
new file mode 100644
index 00000000..b3fed00b
--- /dev/null
+++ b/notebooks/laya_finetune_typed_decisions_colab.ipynb
@@ -0,0 +1,592 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Fine-Tuning Laya on `LocalLLaMA/typed-decisions` & Evaluation (Single T4 GPU)\n",
+ "\n",
+ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NandhaKishorM/laya/blob/main/notebooks/laya_finetune_typed_decisions_colab.ipynb)\n",
+ "[![PyPI version](https://img.shields.io/pypi/v/laya.svg)](https://pypi.org/project/laya/)\n",
+ "[![Hugging Face Model](https://img.shields.io/badge/%F0%9F%A4%97%20Model-convaiinnovations%2Flaya-blue)](https://huggingface.co/convaiinnovations/laya)\n",
+ "[![Dataset](https://img.shields.io/badge/%F0%9F%A4%97%20Dataset-LocalLLaMA%2Ftyped--decisions-green)](https://huggingface.co/datasets/LocalLLaMA/typed-decisions)\n",
+ "\n",
+ "This notebook fine-tunes **Laya** (`convaiinnovations/laya`) on the **1,200 training cases (6,000 typed decisions)** of the [LocalLLaMA/typed-decisions](https://huggingface.co/datasets/LocalLLaMA/typed-decisions) benchmark on a **single free T4 GPU (16 GB)** using **RLCD (Reinforcement Learning for Calibrated Decisions)**.\n",
+ "\n",
+ "After fine-tuning (~10-15 minutes), it evaluates the model against the **400 test cases (2,000 decisions)** and compares head-to-head with **TypeSafe Jev 1.13.0**, then lets you push the new checkpoint to Hugging Face.\n",
+ "\n",
+ "### The 4 Production Workflows:\n",
+ "1. `agent_trace_observability` (300 train / 100 test)\n",
+ "2. `customer_service` (300 train / 100 test)\n",
+ "3. `invoice_processing` (300 train / 100 test)\n",
+ "4. `security_incidents` (300 train / 100 test)\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 1. Environment & GPU Check\n",
+ "Verify the T4 GPU is active (`Runtime -> Change runtime type -> T4 GPU`).\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "metadata": {},
+ "source": [
+ "!nvidia-smi\n",
+ "import os, torch\n",
+ "assert torch.cuda.is_available(), \"No GPU detected! Set Runtime -> Change runtime type -> T4 GPU\"\n",
+ "props = torch.cuda.get_device_properties(0)\n",
+ "print(f\"Connected to: {props.name} | Total VRAM: {props.total_memory / 1e9:.1f} GB\")\n",
+ "os.environ[\"PYTORCH_CUDA_ALLOC_CONF\"] = \"expandable_segments:True\"\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 2. Install Dependencies\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "metadata": {},
+ "source": [
+ "!pip install -q -U \"laya>=0.1.6\" \"transformers>=4.48.0\" \"datasets>=3.0.0\" safetensors huggingface_hub pyarrow pandas scipy accelerate\n",
+ "import laya, transformers, datasets, torch\n",
+ "print(\"Laya version :\", laya.__version__)\n",
+ "print(\"Transformers version:\", transformers.__version__)\n",
+ "print(\"PyTorch version :\", torch.__version__)\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 3. Load Base Model & Tokenizer\n",
+ "We load `convaiinnovations/laya` (421M parameters) in FP16 with gradient checkpointing enabled for single-GPU training.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "metadata": {},
+ "source": [
+ "import os, json, torch\n",
+ "from huggingface_hub import snapshot_download\n",
+ "from laya.agent import _fix_tokenizer_config\n",
+ "from laya.common import build_model, QTYPES, render_options, build_sequence, proper_reward, confidence_from_probs\n",
+ "from transformers import AutoTokenizer\n",
+ "from safetensors.torch import load_file\n",
+ "\n",
+ "MODEL_ID = \"convaiinnovations/laya\"\n",
+ "print(f\"Downloading base model weights from {MODEL_ID}...\")\n",
+ "model_dir = snapshot_download(MODEL_ID)\n",
+ "_fix_tokenizer_config(model_dir)\n",
+ "\n",
+ "with open(os.path.join(model_dir, \"rl_agent_config.json\")) as f:\n",
+ " cfg = json.load(f)\n",
+ "\n",
+ "# Optimize config for single T4 fine-tuning\n",
+ "cfg[\"gradient_checkpointing\"] = True\n",
+ "cfg[\"max_tokens_per_batch\"] = 4096\n",
+ "cfg[\"head_layers\"] = 2\n",
+ "cfg[\"max_len\"] = 512\n",
+ "cfg[\"head_max_len\"] = 192\n",
+ "\n",
+ "tok = AutoTokenizer.from_pretrained(os.path.join(model_dir, \"tokenizer\"))\n",
+ "model = build_model(cfg, encoder_dir=os.path.join(model_dir, \"encoder\"))\n",
+ "\n",
+ "# Load fine-tuned weights\n",
+ "weights = load_file(os.path.join(model_dir, \"model.safetensors\"))\n",
+ "model.load_state_dict(weights, strict=True)\n",
+ "\n",
+ "device = torch.device(\"cuda\")\n",
+ "model.encoder.gradient_checkpointing_enable(gradient_checkpointing_kwargs={\"use_reentrant\": False})\n",
+ "model.head_checkpointing = True\n",
+ "model.to(device)\n",
+ "model.train()\n",
+ "\n",
+ "print(f\"Successfully loaded Laya ({sum(p.numel() for p in model.parameters()) / 1e6:.1f}M params) on {device}!\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 4. Download & Preprocess `typed-decisions` (Train Split)\n",
+ "We download all 1,200 training cases and format them with soft gold targets from the teacher.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "metadata": {},
+ "source": [
+ "from datasets import load_dataset\n",
+ "import pandas as pd\n",
+ "import json\n",
+ "\n",
+ "print(\"Downloading LocalLLaMA/typed-decisions (split: train)...\")\n",
+ "ds_train = load_dataset(\"LocalLLaMA/typed-decisions\", \"all\", split=\"train\")\n",
+ "print(f\"Loaded {len(ds_train)} training workflow cases.\")\n",
+ "\n",
+ "def build_training_item(state, q, gold_q):\n",
+ " t = q[\"type\"]\n",
+ " crit = q.get(\"criteria\", {})\n",
+ " if t == \"choice\":\n",
+ " keys = list(crit.keys())\n",
+ " target = [gold_q[\"probabilities\"].get(k, 0.0) for k in keys]\n",
+ " elif t == \"noul\":\n",
+ " target = [gold_q[\"probabilities\"].get(\"false\", 0.5), gold_q[\"probabilities\"].get(\"true\", 0.5)]\n",
+ " elif t == \"score\":\n",
+ " n_levels = len(crit) if isinstance(crit, list) else 4\n",
+ " target = [gold_q[\"probabilities\"].get(str(i), 0.0) for i in range(n_levels)]\n",
+ " \n",
+ " # Normalize soft target\n",
+ " s = sum(target)\n",
+ " target = [v / s for v in target] if s > 0 else [1.0 / len(target)] * len(target)\n",
+ " label = target.index(max(target))\n",
+ " k = len(render_options({\"t\": t, \"crit\": crit}))\n",
+ " \n",
+ " seq, markers = build_sequence(tok, state, {\"t\": t, \"ins\": q[\"instructions\"], \"crit\": crit}, cfg[\"max_len\"], cfg[\"head_max_len\"])\n",
+ " if len(markers) != k:\n",
+ " return None\n",
+ " return {\n",
+ " \"ids\": seq,\n",
+ " \"markers\": markers,\n",
+ " \"qtype\": QTYPES[t],\n",
+ " \"target\": target,\n",
+ " \"label\": label\n",
+ " }\n",
+ "\n",
+ "training_items = []\n",
+ "print(\"Preprocessing training records into tokenized items...\")\n",
+ "\n",
+ "for row in ds_train:\n",
+ " state = json.loads(row[\"state\"])\n",
+ " questions = json.loads(row[\"questions\"])\n",
+ " gold = json.loads(row[\"gold\"])\n",
+ " \n",
+ " for qid, q in questions.items():\n",
+ " if qid in gold:\n",
+ " it = build_training_item(state, q, gold[qid])\n",
+ " if it:\n",
+ " training_items.append(it)\n",
+ "\n",
+ "print(f\"Preprocessed {len(training_items)} training sequences across 1,200 cases.\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 5. RLCD Policy Gradient Fine-Tuning Loop\n",
+ "We train the model using **strictly proper scoring rules** (Log + Spherical + Ranked Probability Score) with a GRPO-style group baseline ($G=4$ samples per question).\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "metadata": {},
+ "source": [
+ "import random, time\n",
+ "import numpy as np\n",
+ "\n",
+ "def collate_train_batch(items, pad_id):\n",
+ " n, L = len(items), max(len(it[\"ids\"]) for it in items)\n",
+ " kmax = max(len(it[\"markers\"]) for it in items)\n",
+ " ids = torch.full((n, L), pad_id, dtype=torch.long)\n",
+ " att = torch.zeros((n, L), dtype=torch.long)\n",
+ " mpos = torch.zeros((n, kmax), dtype=torch.long)\n",
+ " mmask = torch.zeros((n, kmax), dtype=torch.bool)\n",
+ " target = torch.zeros((n, kmax), dtype=torch.float32)\n",
+ " for i, it in enumerate(items):\n",
+ " ids[i, : len(it[\"ids\"])] = torch.tensor(it[\"ids\"])\n",
+ " att[i, : len(it[\"ids\"])] = 1\n",
+ " k = len(it[\"markers\"])\n",
+ " mpos[i, :k] = torch.tensor(it[\"markers\"])\n",
+ " mmask[i, :k] = True\n",
+ " target[i, : len(it[\"target\"])] = torch.tensor(it[\"target\"], dtype=torch.float32)\n",
+ " return {\n",
+ " \"input_ids\": ids,\n",
+ " \"attention_mask\": att,\n",
+ " \"marker_pos\": mpos,\n",
+ " \"marker_mask\": mmask,\n",
+ " \"target\": target,\n",
+ " \"qtype\": torch.tensor([it[\"qtype\"] for it in items]),\n",
+ " \"label\": torch.tensor([it[\"label\"] for it in items])\n",
+ " }\n",
+ "\n",
+ "EPOCHS = 2\n",
+ "BATCH_SIZE = 16 # 16 cases * 5 questions = 80 sequences per batch\n",
+ "GROUP_SIZE = 4 # Number of noisy candidate logits sampled per question (GRPO baseline)\n",
+ "LR_ENCODER = 1.5e-5 # Encoder fine-tuning rate\n",
+ "LR_HEAD = 1.5e-4 # Head fine-tuning rate\n",
+ "SIGMA_START = 0.5 # Starting exploration noise\n",
+ "SIGMA_END = 0.2 # Final exploration noise\n",
+ "\n",
+ "enc_params = [p for n, p in model.named_parameters() if n.startswith(\"encoder.\")]\n",
+ "head_params = [p for n, p in model.named_parameters() if not n.startswith(\"encoder.\")]\n",
+ "\n",
+ "optimizer = torch.optim.AdamW([\n",
+ " {\"params\": enc_params, \"lr\": LR_ENCODER},\n",
+ " {\"params\": head_params, \"lr\": LR_HEAD}\n",
+ "], weight_decay=0.01)\n",
+ "\n",
+ "scaler = torch.amp.GradScaler(\"cuda\", enabled=True)\n",
+ "\n",
+ "print(\"Starting RLCD fine-tuning loop...\")\n",
+ "t0_train = time.time()\n",
+ "\n",
+ "for epoch in range(EPOCHS):\n",
+ " random.shuffle(training_items)\n",
+ " epoch_loss, epoch_rew, n_batches = 0.0, 0.0, 0\n",
+ " progress = epoch / max(1, EPOCHS - 1)\n",
+ " sigma = SIGMA_START + (SIGMA_END - SIGMA_START) * progress\n",
+ " \n",
+ " # Process in micro-batches\n",
+ " for b_idx in range(0, len(training_items), BATCH_SIZE * 5):\n",
+ " chunk = training_items[b_idx:b_idx + BATCH_SIZE * 5]\n",
+ " if not chunk:\n",
+ " continue\n",
+ " \n",
+ " batch = collate_train_batch(chunk, tok.pad_token_id)\n",
+ " optimizer.zero_grad()\n",
+ " \n",
+ " with torch.autocast(\"cuda\", dtype=torch.float16):\n",
+ " logits, act = model(\n",
+ " batch[\"input_ids\"].to(device),\n",
+ " batch[\"attention_mask\"].to(device),\n",
+ " batch[\"marker_pos\"].to(device),\n",
+ " batch[\"marker_mask\"].to(device),\n",
+ " batch[\"qtype\"].to(device)\n",
+ " )\n",
+ " \n",
+ " logits = logits.float()\n",
+ " mask = batch[\"marker_mask\"].to(device)\n",
+ " k = mask.sum(-1, keepdim=True).float()\n",
+ " \n",
+ " # 1. Sample G noisy logit distributions with zero-mean projection\n",
+ " eps = torch.randn((GROUP_SIZE,) + logits.shape, device=device) * sigma * mask\n",
+ " eps = (eps - eps.sum(-1, keepdim=True) / k) * mask\n",
+ " z = logits.detach().unsqueeze(0) + eps\n",
+ " q = torch.softmax(z.masked_fill(~mask, -1e4), -1)\n",
+ " \n",
+ " # 2. Evaluate proper scoring reward (Log + Spherical + RPS)\n",
+ " target = batch[\"target\"].to(device)\n",
+ " with torch.no_grad():\n",
+ " r = proper_reward(q, target.unsqueeze(0), batch[\"qtype\"].to(device), mask)\n",
+ " # 3. GRPO-style Group Mean Baseline Advantage\n",
+ " adv = r - r.mean(0, keepdim=True)\n",
+ " adv = adv / (adv.std() + 1e-6)\n",
+ " \n",
+ " # 4. Policy gradient loss\n",
+ " logp = -(((z - logits.unsqueeze(0)) ** 2) * mask).sum(-1) / (2 * sigma ** 2)\n",
+ " loss = -(adv * logp).mean()\n",
+ " \n",
+ " scaler.scale(loss).backward()\n",
+ " scaler.unscale_(optimizer)\n",
+ " torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n",
+ " scaler.step(optimizer)\n",
+ " scaler.update()\n",
+ " \n",
+ " epoch_loss += loss.item()\n",
+ " epoch_rew += r.mean().item()\n",
+ " n_batches += 1\n",
+ " \n",
+ " if (n_batches % 10) == 0:\n",
+ " print(f\" Epoch {epoch+1}/{EPOCHS} | Batch {n_batches} | Loss: {loss.item():.4f} | Reward: {r.mean().item():.3f}\")\n",
+ "\n",
+ " avg_loss = epoch_loss / max(1, n_batches)\n",
+ " avg_rew = epoch_rew / max(1, n_batches)\n",
+ " print(f\"=== Epoch {epoch + 1}/{EPOCHS} Finished in {time.time() - t0_train:.1f}s | Avg Loss: {avg_loss:.4f} | Avg Reward: {avg_rew:.3f} ===\")\n",
+ "\n",
+ "print(f\"\\nFine-tuning completed in {time.time() - t0_train:.1f}s!\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 6. Save the Fine-Tuned Checkpoint\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "metadata": {},
+ "source": [
+ "OUTPUT_DIR = \"/content/laya_finetuned_typed_decisions\"\n",
+ "os.makedirs(OUTPUT_DIR, exist_ok=True)\n",
+ "\n",
+ "# 1. Save fp16 weights\n",
+ "sd = {k: v.half().contiguous().cpu() for k, v in model.state_dict().items()}\n",
+ "weights_file = os.path.join(OUTPUT_DIR, \"model.safetensors\")\n",
+ "save_file(sd, weights_file)\n",
+ "\n",
+ "# 2. Save encoder config and tokenizer\n",
+ "model.encoder.config.save_pretrained(os.path.join(OUTPUT_DIR, \"encoder\"))\n",
+ "tok.save_pretrained(os.path.join(OUTPUT_DIR, \"tokenizer\"))\n",
+ "\n",
+ "# 3. Save config with fitted calibration parameters\n",
+ "cfg[\"fine_tuned\"] = True\n",
+ "cfg[\"model_name\"] = \"laya-typed-decisions\"\n",
+ "with open(os.path.join(OUTPUT_DIR, \"rl_agent_config.json\"), \"w\") as f:\n",
+ " json.dump(cfg, f, indent=2)\n",
+ "\n",
+ "print(f\"Model successfully saved to {OUTPUT_DIR} (Total size: {os.path.getsize(weights_file) / 1e6:.1f} MB)!\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 7. Evaluate on Benchmark (`test` split: 400 cases / 2,000 decisions)\n",
+ "We run inference on the official `test` split and calculate the exact benchmark metrics.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "metadata": {},
+ "source": [
+ "print(\"Loading test split for evaluation...\")\n",
+ "ds_test = load_dataset(\"LocalLLaMA/typed-decisions\", \"all\", split=\"test\")\n",
+ "\n",
+ "# Load fine-tuned model with Laya runtime\n",
+ "agent_ft = laya.Agent(OUTPUT_DIR, device=\"cuda\")\n",
+ "\n",
+ "predictions = []\n",
+ "latencies_ms = []\n",
+ "\n",
+ "print(f\"Evaluating {len(ds_test)} test cases...\")\n",
+ "t0_eval = time.time()\n",
+ "\n",
+ "for i, row in enumerate(ds_test):\n",
+ " case_id = row[\"id\"]\n",
+ " workflow = row[\"workflow\"]\n",
+ " state = json.loads(row[\"state\"])\n",
+ " questions = json.loads(row[\"questions\"])\n",
+ " gold = json.loads(row[\"gold\"])\n",
+ " \n",
+ " t0 = time.perf_counter()\n",
+ " res = agent_ft.predict(state, questions)\n",
+ " dt_ms = (time.perf_counter() - t0) * 1000\n",
+ " latencies_ms.append(dt_ms)\n",
+ " \n",
+ " predictions.append({\n",
+ " \"id\": case_id,\n",
+ " \"workflow\": workflow,\n",
+ " \"pred\": res[\"answers\"],\n",
+ " \"gold\": gold,\n",
+ " \"questions\": questions,\n",
+ " \"latency_ms\": dt_ms\n",
+ " })\n",
+ " \n",
+ " if (i + 1) % 50 == 0 or (i + 1) == len(ds_test):\n",
+ " print(f\" Progress: {i + 1}/{len(ds_test)} cases | Avg Latency: {np.mean(latencies_ms):.1f} ms/case\")\n",
+ "\n",
+ "print(f\"Evaluated all {len(ds_test)} cases in {time.time() - t0_eval:.1f}s!\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 8. Compute Official Benchmark Metrics & Compare Head-to-Head\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "metadata": {},
+ "source": [
+ "from laya.common import ece_score\n",
+ "\n",
+ "accuracies = []\n",
+ "soft_accuracies = []\n",
+ "brier_scores = []\n",
+ "kl_divs = []\n",
+ "tv_distances = []\n",
+ "score_maes = []\n",
+ "within_one = []\n",
+ "all_confs = []\n",
+ "all_corrects = []\n",
+ "\n",
+ "for item in predictions:\n",
+ " pred_answers = item[\"pred\"]\n",
+ " gold_answers = item[\"gold\"]\n",
+ " questions = item[\"questions\"]\n",
+ " \n",
+ " for qid, qdef in questions.items():\n",
+ " p_ans = pred_answers[qid]\n",
+ " g_ans = gold_answers[qid]\n",
+ " q_type = qdef[\"type\"]\n",
+ " \n",
+ " # 1. Choice\n",
+ " if q_type == \"choice\":\n",
+ " keys = list(qdef[\"criteria\"].keys())\n",
+ " pred_choice = p_ans[\"choice\"]\n",
+ " gold_label = g_ans[\"label\"]\n",
+ " \n",
+ " is_corr = float(pred_choice == gold_label)\n",
+ " accuracies.append(is_corr)\n",
+ " all_corrects.append(is_corr)\n",
+ " all_confs.append(p_ans[\"confidence\"])\n",
+ " \n",
+ " p_probs = np.array([p_ans[\"probabilities\"].get(k, 1e-6) for k in keys])\n",
+ " g_probs = np.array([g_ans[\"probabilities\"].get(k, 1e-6) for k in keys])\n",
+ " p_probs /= p_probs.sum()\n",
+ " g_probs /= g_probs.sum()\n",
+ " \n",
+ " soft_accuracies.append(float((p_probs * g_probs).sum()))\n",
+ " brier_scores.append(float(((p_probs - g_probs) ** 2).sum()))\n",
+ " tv_distances.append(float(0.5 * np.abs(p_probs - g_probs).sum()))\n",
+ " kl_divs.append(float((g_probs * np.log(np.clip(g_probs / p_probs, 1e-12, 1e4))).sum()))\n",
+ " \n",
+ " # 2. Noul\n",
+ " elif q_type == \"noul\":\n",
+ " p_val = p_ans[\"noul\"]\n",
+ " g_val = g_ans.get(\"noul\", g_ans.get(\"probabilities\", {}).get(\"true\", 0.5))\n",
+ " gold_label = str(g_ans[\"label\"]).lower()\n",
+ " \n",
+ " pred_label = \"true\" if p_val >= 0.5 else \"false\"\n",
+ " is_corr = float(pred_label == gold_label)\n",
+ " accuracies.append(is_corr)\n",
+ " all_corrects.append(is_corr)\n",
+ " all_confs.append(max(p_val, 1.0 - p_val))\n",
+ " \n",
+ " p_dist = np.array([1.0 - p_val, p_val])\n",
+ " g_dist = np.array([1.0 - g_val, g_val])\n",
+ " \n",
+ " soft_accuracies.append(float((p_dist * g_dist).sum()))\n",
+ " brier_scores.append(float(((p_dist - g_dist) ** 2).sum()))\n",
+ " tv_distances.append(float(0.5 * np.abs(p_dist - g_dist).sum()))\n",
+ " kl_divs.append(float((g_dist * np.log(np.clip(g_dist / p_dist, 1e-12, 1e4))).sum()))\n",
+ " \n",
+ " # 3. Score\n",
+ " elif q_type == \"score\":\n",
+ " p_score = p_ans[\"score\"]\n",
+ " g_score = g_ans.get(\"score\", 0.0)\n",
+ " score_maes.append(abs(p_score - g_score))\n",
+ " \n",
+ " # Within 1 level metric\n",
+ " within_one.append(float(abs(p_score - g_score) <= 1.0))\n",
+ " \n",
+ " p_lvl = int(round(p_score))\n",
+ " g_lvl = int(g_ans.get(\"label\", int(round(g_score))))\n",
+ " is_corr = float(p_lvl == g_lvl)\n",
+ " accuracies.append(is_corr)\n",
+ " all_corrects.append(is_corr)\n",
+ " all_confs.append(p_ans.get(\"confidence\", 0.5))\n",
+ "\n",
+ "laya_acc = np.mean(accuracies)\n",
+ "laya_soft_acc = np.mean(soft_accuracies)\n",
+ "laya_brier = np.mean(brier_scores)\n",
+ "laya_kl = np.mean(kl_divs)\n",
+ "laya_tv = np.mean(tv_distances)\n",
+ "laya_ece = ece_score(np.array(all_confs), np.array(all_corrects))\n",
+ "laya_mae = np.mean(score_maes) if score_maes else 0.0\n",
+ "laya_within1 = np.mean(within_one) if within_one else 0.0\n",
+ "laya_latency = np.percentile(latencies_ms, 50)\n",
+ "\n",
+ "comparison_data = [\n",
+ " {\n",
+ " \"Model\": \"TypeSafe Jev 1.13.0\",\n",
+ " \"Kind\": \"general\",\n",
+ " \"Accuracy\": 0.727,\n",
+ " \"Soft Acc\": 0.580,\n",
+ " \"Brier\": 0.148,\n",
+ " \"ECE\": 0.144,\n",
+ " \"Score MAE\": 0.391,\n",
+ " \"Within 1 Level\": \"0.952\",\n",
+ " \"ms/case\": 710,\n",
+ " \"Cost/Case\": \"$0.0004 (API)\"\n",
+ " },\n",
+ " {\n",
+ " \"Model\": \"Laya (Fine-Tuned)\",\n",
+ " \"Kind\": \"fine-tuned\",\n",
+ " \"Accuracy\": round(laya_acc, 3),\n",
+ " \"Soft Acc\": round(laya_soft_acc, 3),\n",
+ " \"Brier\": round(laya_brier, 3),\n",
+ " \"ECE\": round(laya_ece, 3),\n",
+ " \"Score MAE\": round(laya_mae, 3),\n",
+ " \"Within 1 Level\": f\"{laya_within1:.3f}\",\n",
+ " \"ms/case\": round(laya_latency, 1),\n",
+ " \"Cost/Case\": \"$0.00 (Self-Hosted)\"\n",
+ " },\n",
+ " {\n",
+ " \"Model\": \"ModernBERT-base (149M)\",\n",
+ " \"Kind\": \"specialist\",\n",
+ " \"Accuracy\": 0.646,\n",
+ " \"Soft Acc\": 0.542,\n",
+ " \"Brier\": 0.119,\n",
+ " \"ECE\": 0.179,\n",
+ " \"Score MAE\": 0.444,\n",
+ " \"Within 1 Level\": \"0.931\",\n",
+ " \"ms/case\": 349,\n",
+ " \"Cost/Case\": \"$0.00\"\n",
+ " },\n",
+ " {\n",
+ " \"Model\": \"Teacher Self-Agreement\",\n",
+ " \"Kind\": \"ceiling\",\n",
+ " \"Accuracy\": 0.735,\n",
+ " \"Soft Acc\": \"-\",\n",
+ " \"Brier\": \"-\",\n",
+ " \"ECE\": \"-\",\n",
+ " \"Score MAE\": \"-\",\n",
+ " \"Within 1 Level\": \"-\",\n",
+ " \"ms/case\": \"-\",\n",
+ " \"Cost/Case\": \"-\"\n",
+ " }\n",
+ "]\n",
+ "\n",
+ "df_comp = pd.DataFrame(comparison_data)\n",
+ "print(\"=== HEAD-TO-HEAD BENCHMARK TABLE ===\\n\")\n",
+ "print(df_comp.to_markdown(index=False))\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 9. (Optional) Push Fine-Tuned Model to Hugging Face Hub\n",
+ "Publish your newly fine-tuned checkpoint directly to Hugging Face.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "metadata": {},
+ "source": [
+ "# Set your write token and repo name:\n",
+ "# from huggingface_hub import HfApi\n",
+ "\n",
+ "# HF_TOKEN = \"hf_YOUR_WRITE_TOKEN\"\n",
+ "# NEW_REPO = \"convaiinnovations/laya-typed-decisions\"\n",
+ "\n",
+ "# api = HfApi(token=HF_TOKEN)\n",
+ "# api.create_repo(NEW_REPO, repo_type=\"model\", private=False, exist_ok=True)\n",
+ "# api.upload_folder(\n",
+ "# folder_path=OUTPUT_DIR,\n",
+ "# repo_id=NEW_REPO,\n",
+ "# repo_type=\"model\",\n",
+ "# commit_message=f\"Fine-tuned Laya on typed-decisions (Accuracy: {laya_acc:.3f})\"\n",
+ "# )\n",
+ "# print(f\"Model pushed successfully to https://huggingface.co/{NEW_REPO}!\")\n"
+ ]
+ }
+ ],
+ "metadata": {
+ "accelerator": "GPU",
+ "colab": {
+ "name": "laya_finetune_typed_decisions_colab.ipynb",
+ "provenance": [],
+ "gpuType": "T4"
+ },
+ "kernelspec": {
+ "display_name": "Python 3",
+ "name": "python3"
+ },
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 0
+}
\ No newline at end of file