462 lines
21 KiB
Plaintext
462 lines
21 KiB
Plaintext
{
|
|
"cells": [
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"# DAMA Tier-1 training — free Google Colab or Kaggle\n",
|
|
"\n",
|
|
"Trains the two small models the DAMA Memory Agent uses on its fast path, then calibrates them and exports\n",
|
|
"int8 ONNX files that run on a CPU:\n",
|
|
"\n",
|
|
"| Model | Starts from | Decides |\n",
|
|
"|---|---|---|\n",
|
|
"| **Decision** (22.7M params) | `cross-encoder/ms-marco-MiniLM-L6-v2` | `rel` is this stored turn relevant to the request · `sal` is this new turn worth storing · `need` does the request need memory at all · `route` which stores to query (episodic / facts / timeline / expand) |\n",
|
|
"| **Op** (70.8M params) | `cross-encoder/nli-deberta-v3-xsmall` | `ADD` / `UPDATE` / `DELETE` / `NOOP` for (existing memory, new statement) |\n",
|
|
"\n",
|
|
"**Before you run**\n",
|
|
"\n",
|
|
"* **Colab:** *Runtime → Change runtime type → T4 GPU*. Allow the Google Drive prompt — data and checkpoints go to `MyDrive/DAMA` so a disconnect loses nothing (needs ~3 GB of free Drive space).\n",
|
|
"* **Kaggle:** *Settings → Accelerator → GPU T4 x2* (not P100: current PyTorch builds no longer support it) and *Settings → Internet → On* (needs a phone-verified account). For an unattended run use *Save Version → Save & Run All*; results appear under *Output*.\n",
|
|
"\n",
|
|
"**Checkpoints.** Every run is one checkpoint (L1.0, L1.1, ...) kept on Kaggle, not downloaded: each saved notebook\n",
|
|
"version keeps its own *Output* (`dama/` = data manifest, trained models, logs, report, CPU bundle, plus\n",
|
|
"`CHECKPOINT.json` and `code_snapshot.zip`), and the attached `dama-code` dataset keeps one version per checkpoint.\n",
|
|
"The label comes from `dama_train.config.CHECKPOINT`; describe the change in `CHECKPOINT_NOTES` below.\n",
|
|
"\n",
|
|
"Then *Run all*. **If the session dies, reconnect and Run all again** — every stage skips finished work and training resumes from its last checkpoint."
|
|
],
|
|
"id": "cell00"
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"metadata": {},
|
|
"execution_count": null,
|
|
"outputs": [],
|
|
"source": [
|
|
"# ---- settings -------------------------------------------------------------------------------------\n",
|
|
"REPO_URL = \"\" # optional: git URL of the repo holding this code, e.g. \"https://github.com/<you>/dama.git\"\n",
|
|
"REPO_SUBDIR = \"\" # folder inside that repo that contains dama_train/ (\"\" = repo root)\n",
|
|
"MAX_MINUTES = 150 # per training stage; it checkpoints and stops cleanly after this, re-run to continue\n",
|
|
"USE_LME_S = True # LongMemEval_S full haystacks (277 MB): realistic hard negatives. False = smaller/faster\n",
|
|
"USE_DENSE = True # hybrid BM25 + bge-small candidate pools for calibration (False = BM25 only)\n",
|
|
"RUN_SMOKE = True # 2-3 min offline check with tiny random models before the real run (fails fast on a broken install)\n",
|
|
"CHECKPOINT_NOTES = \"L1.2: retriever trained on negatives mined by the dense model + previous-turn keys; fused reranker graph if faster\"\n",
|
|
"MODEL_HANDLE = \"s41r4j/dama-tier1/other/tier1\" # Kaggle: also register the checkpoint as a private Model version (\"\" = skip)\n",
|
|
"CLEANUP = True # Kaggle: delete raw downloads and optimizer checkpoints at the end so the saved output stays small\n"
|
|
],
|
|
"id": "cell01"
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"### 1 · Find the code\n",
|
|
"Looks in this order: an existing copy, Google Drive `MyDrive/DAMA/code`, an attached Kaggle dataset, `REPO_URL`,\n",
|
|
"and finally (Colab only) asks you to upload `dama_code.zip`."
|
|
],
|
|
"id": "cell02"
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"metadata": {},
|
|
"execution_count": null,
|
|
"outputs": [],
|
|
"source": [
|
|
"import glob, importlib.util, os, shutil, subprocess, sys, zipfile\n",
|
|
"ON_KAGGLE = os.path.isdir(\"/kaggle/working\")\n",
|
|
"# Kaggle images also ship the google.colab package, so check Kaggle first\n",
|
|
"ON_COLAB = not ON_KAGGLE and importlib.util.find_spec(\"google.colab\") is not None\n",
|
|
"if ON_COLAB:\n",
|
|
" from google.colab import drive\n",
|
|
" drive.mount(\"/content/drive\")\n",
|
|
"BASE = \"/kaggle/working\" if ON_KAGGLE else \"/content\" if ON_COLAB else os.getcwd()\n",
|
|
"CODE = os.path.join(BASE, \"dama_code\")\n",
|
|
"WORK = (\"/kaggle/working/dama\" if ON_KAGGLE else\n",
|
|
" \"/content/drive/MyDrive/DAMA\" if os.path.isdir(\"/content/drive/MyDrive\") else os.path.join(BASE, \"dama_work\"))\n",
|
|
"\n",
|
|
"def has_code(d):\n",
|
|
" return d and os.path.isfile(os.path.join(d, \"dama_train\", \"__init__.py\"))\n",
|
|
"\n",
|
|
"def find_code():\n",
|
|
" for d in [CODE, os.getcwd(), \"/content/drive/MyDrive/DAMA/code\"]:\n",
|
|
" if has_code(d):\n",
|
|
" return d\n",
|
|
" for hit in glob.glob(\"/kaggle/input/**/dama_train/__init__.py\", recursive=True):\n",
|
|
" return os.path.dirname(os.path.dirname(hit))\n",
|
|
" for z in glob.glob(\"/kaggle/input/**/*.zip\", recursive=True) + glob.glob(os.path.join(BASE, \"*.zip\")):\n",
|
|
" return unzip(z)\n",
|
|
" if REPO_URL:\n",
|
|
" dest = os.path.join(BASE, \"dama_repo\")\n",
|
|
" if not os.path.isdir(dest):\n",
|
|
" subprocess.run([\"git\", \"clone\", \"--depth\", \"1\", REPO_URL, dest], check=True)\n",
|
|
" else:\n",
|
|
" subprocess.run([\"git\", \"-C\", dest, \"pull\", \"--ff-only\"], check=False)\n",
|
|
" return os.path.join(dest, REPO_SUBDIR)\n",
|
|
" if ON_COLAB:\n",
|
|
" from google.colab import files\n",
|
|
" print(\"Upload dama_code.zip (the zipped code folder) ...\")\n",
|
|
" name = next(iter(files.upload()))\n",
|
|
" return unzip(os.path.join(os.getcwd(), name))\n",
|
|
" raise SystemExit(\"Code not found: set REPO_URL, attach the code as a Kaggle dataset, or upload dama_code.zip\")\n",
|
|
"\n",
|
|
"def unzip(path):\n",
|
|
" dest = os.path.join(BASE, \"dama_unzipped\")\n",
|
|
" with zipfile.ZipFile(path) as z:\n",
|
|
" z.extractall(dest)\n",
|
|
" hits = glob.glob(os.path.join(dest, \"**\", \"dama_train\", \"__init__.py\"), recursive=True)\n",
|
|
" if not hits:\n",
|
|
" raise SystemExit(f\"{path} does not contain dama_train/\")\n",
|
|
" return os.path.dirname(os.path.dirname(min(hits, key=len)))\n",
|
|
"\n",
|
|
"src = find_code()\n",
|
|
"if os.path.abspath(src) != os.path.abspath(CODE): # work on a writable local copy (Kaggle inputs are read-only)\n",
|
|
" shutil.copytree(src, CODE, dirs_exist_ok=True, ignore=shutil.ignore_patterns(\"__pycache__\", \"dama_work\"))\n",
|
|
"os.makedirs(WORK, exist_ok=True)\n",
|
|
"print(\"code:\", CODE, \"\\nwork dir:\", WORK)"
|
|
],
|
|
"id": "cell03"
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"### 2 · Install and check the GPU"
|
|
],
|
|
"id": "cell04"
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"metadata": {},
|
|
"execution_count": null,
|
|
"outputs": [],
|
|
"source": [
|
|
"%cd {CODE}\n",
|
|
"import socket, torch\n",
|
|
"if ON_KAGGLE: # Kaggle silently drops internet and GPU for accounts that are not phone-verified\n",
|
|
" try:\n",
|
|
" socket.create_connection((\"pypi.org\", 443), timeout=10).close()\n",
|
|
" except OSError:\n",
|
|
" raise SystemExit(\"No internet on this Kaggle session: verify your phone number (kaggle.com/settings), then turn Internet on.\")\n",
|
|
" if not torch.cuda.is_available():\n",
|
|
" raise SystemExit(\"No GPU on this Kaggle session: verify your phone number (kaggle.com/settings) and pick GPU T4.\")\n",
|
|
"subprocess.run([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"-r\", \"requirements.txt\"], check=True)\n",
|
|
"\n",
|
|
"def run(*args):\n",
|
|
" \"\"\"Run one pipeline stage and stop the notebook if it fails (a failing `!python` line would not).\"\"\"\n",
|
|
" cmd = [sys.executable, \"-m\", \"dama_train\", *[a for a in args if a]]\n",
|
|
" print(\"$\", \" \".join(cmd), flush=True)\n",
|
|
" proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1)\n",
|
|
" for line in proc.stdout:\n",
|
|
" print(line, end=\"\", flush=True)\n",
|
|
" if proc.wait():\n",
|
|
" raise RuntimeError(f\"stage failed (exit {proc.returncode}): {' '.join(args)}\")\n",
|
|
"\n",
|
|
"run(\"env\")\n",
|
|
"if RUN_SMOKE:\n",
|
|
" run(\"smoke\", \"--work\", os.path.join(\"/tmp\" if ON_KAGGLE else BASE, \"dama_smoke\"))\n"
|
|
],
|
|
"id": "cell05"
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"### 3 · Download and build the training data\n",
|
|
"LoCoMo (GitHub), LongMemEval (Hugging Face), a 40k MNLI sample and a 6k Dolly sample. Splits are by conversation,\n",
|
|
"so the test conversations are never seen during training or calibration. Takes a few minutes."
|
|
],
|
|
"id": "cell06"
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"metadata": {},
|
|
"execution_count": null,
|
|
"outputs": [],
|
|
"source": [
|
|
"lme_flag = \"\" if USE_LME_S else \"--no-lme-s\"\n",
|
|
"run(\"download\", \"--work\", WORK, lme_flag)\n",
|
|
"run(\"build\", \"--work\", WORK, lme_flag)\n"
|
|
],
|
|
"id": "cell07"
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"### 4 · Train the first-stage retriever, then the decision model (rel / sal / need / route)\n",
|
|
"The retriever (bge-small) is fine-tuned on the train split and kept only if it beats the base model on validation coverage.\n",
|
|
"The decision model prints rows/s and an ETA every 30 s, evaluates on the validation split, keeps the best model in\n",
|
|
"`runs/decision/best`. Re-running this cell after a disconnect resumes from `runs/decision/checkpoint.pt`.\n"
|
|
],
|
|
"id": "cell08"
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"metadata": {},
|
|
"execution_count": null,
|
|
"outputs": [],
|
|
"source": [
|
|
"run(\"train-retriever\", \"--work\", WORK)\n",
|
|
"run(\"train-decision\", \"--work\", WORK, \"--max-minutes\", str(MAX_MINUTES))\n"
|
|
],
|
|
"id": "cell09"
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"### 5 · Train the op model (ADD / UPDATE / DELETE / NOOP)"
|
|
],
|
|
"id": "cell10"
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"metadata": {},
|
|
"execution_count": null,
|
|
"outputs": [],
|
|
"source": [
|
|
"run(\"train-ops\", \"--work\", WORK, \"--max-minutes\", str(MAX_MINUTES))\n"
|
|
],
|
|
"id": "cell11"
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"### 6 · Calibrate and test\n",
|
|
"Picks the first-stage source (BM25, bge-small, fine-tuned bge-small, or a fusion) on the *calib* split, fits calibration,\n",
|
|
"picks the conformal threshold, and reports everything on the untouched *test* split: first-stage coverage per source,\n",
|
|
"retrieval recall before/after the `rel` head, packet coverage vs. target, head AUC/F1/ECE, the op model's confusion\n",
|
|
"matrix, and the hand-written behaviour probes.\n"
|
|
],
|
|
"id": "cell12"
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"metadata": {},
|
|
"execution_count": null,
|
|
"outputs": [],
|
|
"source": [
|
|
"dense_flag = \"\" if USE_DENSE else \"--no-dense\"\n",
|
|
"run(\"calibrate\", \"--work\", WORK, dense_flag)\n"
|
|
],
|
|
"id": "cell13"
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"### 7 · Export int8 ONNX for CPU and download"
|
|
],
|
|
"id": "cell14"
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"metadata": {},
|
|
"execution_count": null,
|
|
"outputs": [],
|
|
"source": [
|
|
"run(\"export\", \"--work\", WORK)\n",
|
|
"bundle = os.path.join(WORK, \"export\", \"dama_tier1.zip\")\n",
|
|
"print(\"bundle:\", bundle, f\"({os.path.getsize(bundle) / 2**20:.0f} MB)\")\n",
|
|
"if ON_COLAB:\n",
|
|
" from google.colab import files\n",
|
|
" files.download(bundle)\n",
|
|
"elif ON_KAGGLE:\n",
|
|
" print(\"Kaggle: the bundle stays in this version's Output (dama/export/); nothing needs downloading.\")"
|
|
],
|
|
"id": "cell15"
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"### 8 · Try the exported models (CPU only, no PyTorch) and run the probes on what ships\n"
|
|
],
|
|
"id": "cell16"
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"metadata": {},
|
|
"execution_count": null,
|
|
"outputs": [],
|
|
"source": [
|
|
"import sys\n",
|
|
"sys.path.insert(0, os.path.join(WORK, \"export\", \"dama_tier1\"))\n",
|
|
"from runtime import Tier1\n",
|
|
"t1 = Tier1(os.path.join(WORK, \"export\", \"dama_tier1\"))\n",
|
|
"memories = [\"[2023/03/02] user: I moved to Pune for the new job.\", \"[2023/01/10] user: My cat is called Miso.\",\n",
|
|
" \"[2023/02/14] assistant: Here is a pasta recipe.\"]\n",
|
|
"print(\"need \", round(t1.need(\"Where do I live these days?\"), 3))\n",
|
|
"print(\"route \", {k: round(v, 3) for k, v in t1.route(\"Where do I live these days?\").items()})\n",
|
|
"print(\"rel \", t1.relevance(\"Where do I live these days?\", memories).round(3))\n",
|
|
"print(\"select\", t1.select(\"Where do I live these days?\", memories, alpha=0.1)) # memories in first-stage order\n",
|
|
"print(\"op \", {k: round(v, 3) for k, v in t1.op(\"The user lives in Berlin.\", \"I moved to Pune last month\").items()})\n",
|
|
"sys.path.insert(0, CODE)\n",
|
|
"from dama_train.probes import run_runtime\n",
|
|
"runtime_probes = run_runtime(t1)\n",
|
|
"for name, r in runtime_probes.items():\n",
|
|
" print(f\"probes {name}: accuracy {r['accuracy']:.3f} ({len(r['failures'])} failures)\")\n",
|
|
" for f in r[\"failures\"]:\n",
|
|
" print(\" \", f)\n"
|
|
],
|
|
"id": "cell17"
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "ckpt-md",
|
|
"metadata": {},
|
|
"source": [
|
|
"### 9 · Record this checkpoint\n",
|
|
"Writes `dama/CHECKPOINT.json` (label, notes, code hash, headline metrics) and `dama/code_snapshot.zip` (the exact code\n",
|
|
"that produced this output), so every saved version is self-describing.\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"id": "ckpt-code",
|
|
"metadata": {},
|
|
"execution_count": null,
|
|
"outputs": [],
|
|
"source": [
|
|
"import hashlib, json, time\n",
|
|
"from dama_train.config import CHECKPOINT\n",
|
|
"digest = hashlib.sha256()\n",
|
|
"for root, _, names in sorted(os.walk(CODE)):\n",
|
|
" for n in sorted(names):\n",
|
|
" if n.endswith((\".py\", \".ipynb\", \".txt\", \".md\")) and \"__pycache__\" not in root:\n",
|
|
" with open(os.path.join(root, n), \"rb\") as f:\n",
|
|
" digest.update(n.encode() + f.read())\n",
|
|
"if os.path.isdir(CODE):\n",
|
|
" shutil.make_archive(os.path.join(WORK, \"code_snapshot\"), \"zip\", root_dir=CODE)\n",
|
|
"report = json.load(open(os.path.join(WORK, \"runs\", \"calibration\", \"report.json\")))\n",
|
|
"bundle_meta = json.load(open(os.path.join(WORK, \"export\", \"dama_tier1\", \"dama_tier1.json\")))\n",
|
|
"r, k = report[\"retrieval\"], str(report[\"default_rerank_k\"])\n",
|
|
"summary = {\n",
|
|
" \"first_stage\": report[\"pool_source\"],\n",
|
|
" \"all_gold_in_top_k\": r[\"all_gold_in_top_k\"],\n",
|
|
" \"recall@5\": {\"retriever\": r[\"recall@5_retriever\"], \"rel_head\": r[\"recall@5_dama_rel\"]},\n",
|
|
" \"mrr\": {\"retriever\": r[\"mrr_retriever\"], \"rel_head\": r[\"mrr_dama_rel\"]},\n",
|
|
" \"conformal_at_default_k\": {\"k\": int(k), **{a: v[\"test_coverage\"] for a, v in report[\"conformal_test_by_k\"][k][\"alphas\"].items()}},\n",
|
|
" \"heads\": {n: h.get(\"auc\", h.get(\"f1_per_route\")) for n, h in report[\"decision_heads\"].items()},\n",
|
|
" \"ops\": {\"accuracy\": report[\"ops\"][\"accuracy\"], \"macro_f1\": report[\"ops\"][\"macro_f1\"],\n",
|
|
" \"by_source\": {s: v[\"accuracy\"] for s, v in report[\"ops\"][\"by_source\"].items()}},\n",
|
|
" \"probes_torch\": {n: p[\"accuracy\"] for n, p in report.get(\"probes\", {}).items()},\n",
|
|
" \"probes_shipped_bundle\": {n: p[\"accuracy\"] for n, p in runtime_probes.items()},\n",
|
|
" \"export\": bundle_meta[\"export_checks\"],\n",
|
|
"}\n",
|
|
"checkpoint = {\"label\": CHECKPOINT, \"notes\": CHECKPOINT_NOTES, \"created\": time.strftime(\"%Y-%m-%d %H:%M:%S\"),\n",
|
|
" \"code_sha256\": digest.hexdigest(), \"platform\": \"kaggle\" if ON_KAGGLE else \"colab\" if ON_COLAB else \"local\",\n",
|
|
" \"summary\": summary}\n",
|
|
"with open(os.path.join(WORK, \"CHECKPOINT.json\"), \"w\") as f:\n",
|
|
" json.dump(checkpoint, f, indent=1)\n",
|
|
"print(json.dumps(checkpoint, indent=1)[:6000])\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "model-md",
|
|
"metadata": {},
|
|
"source": [
|
|
"### 10 · Register the checkpoint as private Kaggle Model versions\n",
|
|
"Two variations of `s41r4j/dama-tier1`, each getting a new version with the checkpoint label as version notes:\n",
|
|
"* `other/tier1`: the CPU bundle (ONNX + tokenizers + `runtime.py`), `CHECKPOINT.json`, report, calibration, code snapshot.\n",
|
|
" This is what the Memory Agent loads.\n",
|
|
"* `transformers/tier1-pytorch`: the trained PyTorch models (`retriever/`, `decision/`, `ops/`) for further training\n",
|
|
" without retraining from scratch.\n",
|
|
"Uses the notebook's own Kaggle login (or the secret `KAGGLE_API_TOKEN` when attached). A failed upload only prints a\n",
|
|
"message: everything is still in this version's Output.\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"id": "model-code",
|
|
"metadata": {},
|
|
"execution_count": null,
|
|
"outputs": [],
|
|
"source": [
|
|
"if ON_KAGGLE and MODEL_HANDLE:\n",
|
|
" try:\n",
|
|
" from kaggle_secrets import UserSecretsClient\n",
|
|
" os.environ[\"KAGGLE_API_TOKEN\"] = UserSecretsClient().get_secret(\"KAGGLE_API_TOKEN\").strip()\n",
|
|
" except Exception as e:\n",
|
|
" print(f\"no KAGGLE_API_TOKEN secret ({type(e).__name__}); using the notebook's own credentials\")\n",
|
|
" try:\n",
|
|
" import kagglehub\n",
|
|
" except ImportError:\n",
|
|
" subprocess.run([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"kagglehub\"], check=True)\n",
|
|
" import kagglehub\n",
|
|
" owner_model = MODEL_HANDLE.rsplit(\"/\", 2)[0]\n",
|
|
" stage = os.path.join(BASE, \"model_upload\")\n",
|
|
" uploads = {\n",
|
|
" MODEL_HANDLE: [(os.path.join(WORK, \"export\", \"dama_tier1\"), \".\")] + [(os.path.join(WORK, n), os.path.basename(n)) for n in\n",
|
|
" (\"CHECKPOINT.json\", \"code_snapshot.zip\", \"runs/calibration/report.json\", \"runs/calibration/calibration.json\")],\n",
|
|
" f\"{owner_model}/transformers/tier1-pytorch\": [(os.path.join(WORK, \"runs\", m, \"best\"), m) for m in (\"retriever\", \"decision\", \"ops\")]\n",
|
|
" + [(os.path.join(WORK, \"CHECKPOINT.json\"), \"CHECKPOINT.json\")],\n",
|
|
" }\n",
|
|
" for handle, items in uploads.items():\n",
|
|
" shutil.rmtree(stage, ignore_errors=True)\n",
|
|
" os.makedirs(stage)\n",
|
|
" for src, dst in items:\n",
|
|
" if os.path.isdir(src):\n",
|
|
" shutil.copytree(src, os.path.join(stage, dst), dirs_exist_ok=True, ignore=shutil.ignore_patterns(\"__pycache__\", \"checkpoint.pt\"))\n",
|
|
" elif os.path.exists(src):\n",
|
|
" shutil.copy(src, os.path.join(stage, dst))\n",
|
|
" try:\n",
|
|
" kagglehub.model_upload(handle, stage, version_notes=f\"{CHECKPOINT}: {CHECKPOINT_NOTES}\")\n",
|
|
" print(f\"registered {CHECKPOINT} as a new version of {handle}\")\n",
|
|
" except Exception as e:\n",
|
|
" print(f\"model upload failed for {handle} ({type(e).__name__}: {str(e)[:300]}); the outputs are still in this notebook version\")\n",
|
|
" shutil.rmtree(stage, ignore_errors=True)\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"### 11 · Clean up (Kaggle)\n",
|
|
"Keeps the trained models (`runs/*/best`), the calibration and test report, the training logs, the built data, the\n",
|
|
"CPU bundle, `CHECKPOINT.json` and `code_snapshot.zip`. Deletes the raw downloads and the optimizer checkpoints, which are only needed to resume a run.\n"
|
|
],
|
|
"id": "7bfd4a0e"
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"metadata": {},
|
|
"execution_count": null,
|
|
"outputs": [],
|
|
"source": [
|
|
"if ON_KAGGLE and CLEANUP:\n",
|
|
" shutil.rmtree(os.path.join(WORK, \"raw\"), ignore_errors=True)\n",
|
|
" for ckpt in glob.glob(os.path.join(WORK, \"runs\", \"*\", \"checkpoint.pt\")):\n",
|
|
" os.remove(ckpt)\n",
|
|
" shutil.rmtree(CODE, ignore_errors=True)\n",
|
|
" shutil.rmtree(os.path.join(BASE, \"dama_unzipped\"), ignore_errors=True)\n",
|
|
"for root, _, files in os.walk(WORK):\n",
|
|
" size = sum(os.path.getsize(os.path.join(root, f)) for f in files) / 2**20\n",
|
|
" if size > 1:\n",
|
|
" print(f\"{size:8.1f} MB {root}\")\n"
|
|
],
|
|
"id": "e52844f9"
|
|
}
|
|
],
|
|
"metadata": {
|
|
"accelerator": "GPU",
|
|
"colab": {
|
|
"provenance": [],
|
|
"gpuType": "T4"
|
|
},
|
|
"kernelspec": {
|
|
"display_name": "Python 3",
|
|
"language": "python",
|
|
"name": "python3"
|
|
},
|
|
"language_info": {
|
|
"name": "python"
|
|
}
|
|
},
|
|
"nbformat": 4,
|
|
"nbformat_minor": 5
|
|
}
|