{ "nbformat": 4, "nbformat_minor": 5, "metadata": { "accelerator": "GPU", "colab": { "provenance": [] }, "kernelspec": { "display_name": "Python 3", "name": "python3" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# DAMA \u2014 memory decision model\n", "\n", "One forward pass of a small encoder + decision heads turns a message and candidate memories into a typed decision:\n", "**ADD / NOOP / UPDATE / ARCHIVE**, memory type, update target, the exact evidence span, retrieval relevance and a fallback flag.\n", "\n", "Run top to bottom on a **GPU runtime** (Runtime \u2192 Change runtime type \u2192 T4 or better)." ], "id": "dama-00" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. Setup" ], "id": "dama-01" }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "import subprocess, sys\n", "from pathlib import Path\n", "\n", "REPO, SOURCE = \"https://github.com/s41r4j/dama.git\", Path(\"/content/dama\")\n", "if SOURCE.exists():\n", " subprocess.run([\"git\", \"-C\", str(SOURCE), \"pull\", \"--ff-only\"], check=True)\n", "else:\n", " subprocess.run([\"git\", \"clone\", \"--depth\", \"1\", REPO, str(SOURCE)], check=True)\n", "subprocess.run([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"-r\", str(SOURCE / \"code/requirements.txt\")], check=True)\n", "sys.path.insert(0, str(SOURCE / \"code\"))\n", "\n", "import torch\n", "assert torch.cuda.is_available(), \"Select a GPU runtime first\"\n", "print(torch.cuda.get_device_name(), \"| torch\", torch.__version__)" ], "id": "dama-02" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2. Generate the dataset\n", "Synthetic but varied: ~10k examples over 16 memory slots and 14 behaviours (add, duplicate, update, archive, hedged, hearsay,\n", "chatter, assistant text, contextual answers, current/historical/missing/type retrieval). **Dev and test use message templates and\n", "entity values never seen in training**, so their scores measure generalisation rather than memorisation." ], "id": "dama-03" }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "import json\n", "from dama.data import generate, load_split\n", "\n", "DATA = Path(\"/content/dama-data\")\n", "manifest = generate(DATA)\n", "print({k: v[\"count\"] for k, v in manifest[\"files\"].items()})\n", "example = load_split(DATA, \"train\")[0]\n", "print(json.dumps(example.model_dump(), indent=1)[:1500])" ], "id": "dama-04" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3. Train\n", "`minilm-frozen` is the fast baseline (~23M parameters, ~1M trainable). Compare `minilm-lora`, `bge-frozen` and `bge-lora` on the\n", "same data; pick the fastest one that meets your dev accuracy target. `SMOKE = True` runs 3 steps to check the pipeline.\n", "The best dev epoch is exported to `RUN/export`." ], "id": "dama-05" }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "from datetime import datetime\n", "from dama.training import train\n", "\n", "CONFIG_NAME = \"minilm-frozen\" # minilm-frozen | minilm-lora | bge-frozen | bge-lora\n", "SMOKE = False\n", "RUN = Path(\"/content/dama-runs\") / f\"{CONFIG_NAME}-{datetime.now():%Y%m%d-%H%M%S}\"\n", "model, tokenizer, summary = train(SOURCE / f\"code/configs/{CONFIG_NAME}.json\", DATA, RUN, smoke=SMOKE)\n", "print(\"best dev score:\", summary[\"best_dev_score\"], \"| export:\", RUN / \"export\")" ], "id": "dama-06" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4. Held-out test evaluation\n", "Run once you are done choosing configs on dev." ], "id": "dama-07" }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "from collections import defaultdict\n", "from dama.evaluate import evaluate\n", "from dama.inference import Predictor\n", "\n", "predictor = Predictor(model, tokenizer, device=\"cuda\")\n", "test = load_split(DATA, \"test\")\n", "metrics = evaluate(predictor, test, output=RUN / \"test-eval\")\n", "print(json.dumps({k: v for k, v in metrics.items() if k != \"confusion\"}, indent=1))\n", "\n", "# Per-behaviour accuracy: did the decision match the label on the field that matters for that family?\n", "rows = [json.loads(l) for l in (RUN / \"test-eval/predictions.jsonl\").read_text().splitlines()]\n", "by_family = defaultdict(list)\n", "for r in rows:\n", " d, y = r[\"decision\"], r[\"label\"]\n", " ok = sorted(d[\"selected_ids\"]) == sorted(y[\"relevant_ids\"]) if y[\"operation\"] is None else (d[\"operation\"], d[\"target_id\"]) == (y[\"operation\"], y[\"target_id\"])\n", " by_family[r[\"family\"]].append(ok)\n", "for family, oks in sorted(by_family.items()):\n", " print(f\"{family:18s} {sum(oks)/len(oks):.3f} (n={len(oks)})\")" ], "id": "dama-08" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5. Try it" ], "id": "dama-09" }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "from dama.contracts import Candidate, ModelInput\n", "\n", "x = ModelInput(task=\"write\", text=\"Heads up: we moved the API from Heroku to Fly.io last week. Can you update the docs?\",\n", " candidates=[Candidate(id=\"host\", text=\"The app is hosted on Heroku.\"),\n", " Candidate(id=\"theme\", text=\"The user prefers dark mode.\", memory_type=\"preference\")])\n", "decision, timing = predictor.predict(x)\n", "print(json.dumps(decision.model_dump(), indent=1), timing)" ], "id": "dama-10" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6. Keep the model\n", "The export is self-contained (weights, configs, tokenizer, hashes). Copy it to Drive or download it." ], "id": "dama-11" }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "SAVE_TO_DRIVE = False\n", "if SAVE_TO_DRIVE:\n", " import shutil\n", " from google.colab import drive\n", " drive.mount(\"/content/drive\")\n", " shutil.copytree(RUN, Path(\"/content/drive/MyDrive/DAMA/runs\") / RUN.name)\n", "# Later, anywhere: from dama.artifacts import load_model; model, tokenizer, manifest = load_model(\"path/to/export\")" ], "id": "dama-12" } ] }