Files
s41r4j-dama/code/notebooks/DAMA_train.ipynb
T

21 KiB

DAMA Tier-1 training — free Google Colab or Kaggle

Trains the two small models the DAMA Memory Agent uses on its fast path, then calibrates them and exports int8 ONNX files that run on a CPU:

Model Starts from Decides
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)
Op (70.8M params) cross-encoder/nli-deberta-v3-xsmall ADD / UPDATE / DELETE / NOOP for (existing memory, new statement)

Before you run

  • 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).
  • 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.

Checkpoints. Every run is one checkpoint (L1.0, L1.1, ...) kept on Kaggle, not downloaded: each saved notebook version keeps its own Output (dama/ = data manifest, trained models, logs, report, CPU bundle, plus CHECKPOINT.json and code_snapshot.zip), and the attached dama-code dataset keeps one version per checkpoint. The label comes from dama_train.config.CHECKPOINT; describe the change in CHECKPOINT_NOTES below.

Then Run all. If the session dies, reconnect and Run all again — every stage skips finished work and training resumes from its last checkpoint.

In [ ]:
# ---- settings -------------------------------------------------------------------------------------
REPO_URL = ""          # optional: git URL of the repo holding this code, e.g. "https://github.com/<you>/dama.git"
REPO_SUBDIR = ""       # folder inside that repo that contains dama_train/ ("" = repo root)
MAX_MINUTES = 150      # per training stage; it checkpoints and stops cleanly after this, re-run to continue
USE_LME_S = True       # LongMemEval_S full haystacks (277 MB): realistic hard negatives. False = smaller/faster
USE_DENSE = True       # hybrid BM25 + bge-small candidate pools for calibration (False = BM25 only)
RUN_SMOKE = True       # 2-3 min offline check with tiny random models before the real run (fails fast on a broken install)
CHECKPOINT_NOTES = "L1.2: retriever trained on negatives mined by the dense model + previous-turn keys; fused reranker graph if faster"
MODEL_HANDLE = "s41r4j/dama-tier1/other/tier1"   # Kaggle: also register the checkpoint as a private Model version ("" = skip)
CLEANUP = True         # Kaggle: delete raw downloads and optimizer checkpoints at the end so the saved output stays small

1 · Find the code

Looks in this order: an existing copy, Google Drive MyDrive/DAMA/code, an attached Kaggle dataset, REPO_URL, and finally (Colab only) asks you to upload dama_code.zip.

In [ ]:
import glob, importlib.util, os, shutil, subprocess, sys, zipfile
ON_KAGGLE = os.path.isdir("/kaggle/working")
# Kaggle images also ship the google.colab package, so check Kaggle first
ON_COLAB = not ON_KAGGLE and importlib.util.find_spec("google.colab") is not None
if ON_COLAB:
    from google.colab import drive
    drive.mount("/content/drive")
BASE = "/kaggle/working" if ON_KAGGLE else "/content" if ON_COLAB else os.getcwd()
CODE = os.path.join(BASE, "dama_code")
WORK = ("/kaggle/working/dama" if ON_KAGGLE else
        "/content/drive/MyDrive/DAMA" if os.path.isdir("/content/drive/MyDrive") else os.path.join(BASE, "dama_work"))

def has_code(d):
    return d and os.path.isfile(os.path.join(d, "dama_train", "__init__.py"))

def find_code():
    for d in [CODE, os.getcwd(), "/content/drive/MyDrive/DAMA/code"]:
        if has_code(d):
            return d
    for hit in glob.glob("/kaggle/input/**/dama_train/__init__.py", recursive=True):
        return os.path.dirname(os.path.dirname(hit))
    for z in glob.glob("/kaggle/input/**/*.zip", recursive=True) + glob.glob(os.path.join(BASE, "*.zip")):
        return unzip(z)
    if REPO_URL:
        dest = os.path.join(BASE, "dama_repo")
        if not os.path.isdir(dest):
            subprocess.run(["git", "clone", "--depth", "1", REPO_URL, dest], check=True)
        else:
            subprocess.run(["git", "-C", dest, "pull", "--ff-only"], check=False)
        return os.path.join(dest, REPO_SUBDIR)
    if ON_COLAB:
        from google.colab import files
        print("Upload dama_code.zip (the zipped code folder) ...")
        name = next(iter(files.upload()))
        return unzip(os.path.join(os.getcwd(), name))
    raise SystemExit("Code not found: set REPO_URL, attach the code as a Kaggle dataset, or upload dama_code.zip")

def unzip(path):
    dest = os.path.join(BASE, "dama_unzipped")
    with zipfile.ZipFile(path) as z:
        z.extractall(dest)
    hits = glob.glob(os.path.join(dest, "**", "dama_train", "__init__.py"), recursive=True)
    if not hits:
        raise SystemExit(f"{path} does not contain dama_train/")
    return os.path.dirname(os.path.dirname(min(hits, key=len)))

src = find_code()
if os.path.abspath(src) != os.path.abspath(CODE):   # work on a writable local copy (Kaggle inputs are read-only)
    shutil.copytree(src, CODE, dirs_exist_ok=True, ignore=shutil.ignore_patterns("__pycache__", "dama_work"))
os.makedirs(WORK, exist_ok=True)
print("code:", CODE, "\nwork dir:", WORK)

2 · Install and check the GPU

In [ ]:
%cd {CODE}
import socket, torch
if ON_KAGGLE:  # Kaggle silently drops internet and GPU for accounts that are not phone-verified
    try:
        socket.create_connection(("pypi.org", 443), timeout=10).close()
    except OSError:
        raise SystemExit("No internet on this Kaggle session: verify your phone number (kaggle.com/settings), then turn Internet on.")
    if not torch.cuda.is_available():
        raise SystemExit("No GPU on this Kaggle session: verify your phone number (kaggle.com/settings) and pick GPU T4.")
subprocess.run([sys.executable, "-m", "pip", "install", "-q", "-r", "requirements.txt"], check=True)

def run(*args):
    """Run one pipeline stage and stop the notebook if it fails (a failing `!python` line would not)."""
    cmd = [sys.executable, "-m", "dama_train", *[a for a in args if a]]
    print("$", " ".join(cmd), flush=True)
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1)
    for line in proc.stdout:
        print(line, end="", flush=True)
    if proc.wait():
        raise RuntimeError(f"stage failed (exit {proc.returncode}): {' '.join(args)}")

run("env")
if RUN_SMOKE:
    run("smoke", "--work", os.path.join("/tmp" if ON_KAGGLE else BASE, "dama_smoke"))

3 · Download and build the training data

LoCoMo (GitHub), LongMemEval (Hugging Face), a 40k MNLI sample and a 6k Dolly sample. Splits are by conversation, so the test conversations are never seen during training or calibration. Takes a few minutes.

In [ ]:
lme_flag = "" if USE_LME_S else "--no-lme-s"
run("download", "--work", WORK, lme_flag)
run("build", "--work", WORK, lme_flag)

4 · Train the first-stage retriever, then the decision model (rel / sal / need / route)

The retriever (bge-small) is fine-tuned on the train split and kept only if it beats the base model on validation coverage. The decision model prints rows/s and an ETA every 30 s, evaluates on the validation split, keeps the best model in runs/decision/best. Re-running this cell after a disconnect resumes from runs/decision/checkpoint.pt.

In [ ]:
run("train-retriever", "--work", WORK)
run("train-decision", "--work", WORK, "--max-minutes", str(MAX_MINUTES))

5 · Train the op model (ADD / UPDATE / DELETE / NOOP)

In [ ]:
run("train-ops", "--work", WORK, "--max-minutes", str(MAX_MINUTES))

6 · Calibrate and test

Picks the first-stage source (BM25, bge-small, fine-tuned bge-small, or a fusion) on the calib split, fits calibration, picks the conformal threshold, and reports everything on the untouched test split: first-stage coverage per source, retrieval recall before/after the rel head, packet coverage vs. target, head AUC/F1/ECE, the op model's confusion matrix, and the hand-written behaviour probes.

In [ ]:
dense_flag = "" if USE_DENSE else "--no-dense"
run("calibrate", "--work", WORK, dense_flag)

7 · Export int8 ONNX for CPU and download

In [ ]:
run("export", "--work", WORK)
bundle = os.path.join(WORK, "export", "dama_tier1.zip")
print("bundle:", bundle, f"({os.path.getsize(bundle) / 2**20:.0f} MB)")
if ON_COLAB:
    from google.colab import files
    files.download(bundle)
elif ON_KAGGLE:
    print("Kaggle: the bundle stays in this version's Output (dama/export/); nothing needs downloading.")

8 · Try the exported models (CPU only, no PyTorch) and run the probes on what ships

In [ ]:
import sys
sys.path.insert(0, os.path.join(WORK, "export", "dama_tier1"))
from runtime import Tier1
t1 = Tier1(os.path.join(WORK, "export", "dama_tier1"))
memories = ["[2023/03/02] user: I moved to Pune for the new job.", "[2023/01/10] user: My cat is called Miso.",
            "[2023/02/14] assistant: Here is a pasta recipe."]
print("need  ", round(t1.need("Where do I live these days?"), 3))
print("route ", {k: round(v, 3) for k, v in t1.route("Where do I live these days?").items()})
print("rel   ", t1.relevance("Where do I live these days?", memories).round(3))
print("select", t1.select("Where do I live these days?", memories, alpha=0.1))   # memories in first-stage order
print("op    ", {k: round(v, 3) for k, v in t1.op("The user lives in Berlin.", "I moved to Pune last month").items()})
sys.path.insert(0, CODE)
from dama_train.probes import run_runtime
runtime_probes = run_runtime(t1)
for name, r in runtime_probes.items():
    print(f"probes {name}: accuracy {r['accuracy']:.3f} ({len(r['failures'])} failures)")
    for f in r["failures"]:
        print("   ", f)

9 · Record this checkpoint

Writes dama/CHECKPOINT.json (label, notes, code hash, headline metrics) and dama/code_snapshot.zip (the exact code that produced this output), so every saved version is self-describing.

In [ ]:
import hashlib, json, time
from dama_train.config import CHECKPOINT
digest = hashlib.sha256()
for root, _, names in sorted(os.walk(CODE)):
    for n in sorted(names):
        if n.endswith((".py", ".ipynb", ".txt", ".md")) and "__pycache__" not in root:
            with open(os.path.join(root, n), "rb") as f:
                digest.update(n.encode() + f.read())
if os.path.isdir(CODE):
    shutil.make_archive(os.path.join(WORK, "code_snapshot"), "zip", root_dir=CODE)
report = json.load(open(os.path.join(WORK, "runs", "calibration", "report.json")))
bundle_meta = json.load(open(os.path.join(WORK, "export", "dama_tier1", "dama_tier1.json")))
r, k = report["retrieval"], str(report["default_rerank_k"])
summary = {
    "first_stage": report["pool_source"],
    "all_gold_in_top_k": r["all_gold_in_top_k"],
    "recall@5": {"retriever": r["recall@5_retriever"], "rel_head": r["recall@5_dama_rel"]},
    "mrr": {"retriever": r["mrr_retriever"], "rel_head": r["mrr_dama_rel"]},
    "conformal_at_default_k": {"k": int(k), **{a: v["test_coverage"] for a, v in report["conformal_test_by_k"][k]["alphas"].items()}},
    "heads": {n: h.get("auc", h.get("f1_per_route")) for n, h in report["decision_heads"].items()},
    "ops": {"accuracy": report["ops"]["accuracy"], "macro_f1": report["ops"]["macro_f1"],
            "by_source": {s: v["accuracy"] for s, v in report["ops"]["by_source"].items()}},
    "probes_torch": {n: p["accuracy"] for n, p in report.get("probes", {}).items()},
    "probes_shipped_bundle": {n: p["accuracy"] for n, p in runtime_probes.items()},
    "export": bundle_meta["export_checks"],
}
checkpoint = {"label": CHECKPOINT, "notes": CHECKPOINT_NOTES, "created": time.strftime("%Y-%m-%d %H:%M:%S"),
              "code_sha256": digest.hexdigest(), "platform": "kaggle" if ON_KAGGLE else "colab" if ON_COLAB else "local",
              "summary": summary}
with open(os.path.join(WORK, "CHECKPOINT.json"), "w") as f:
    json.dump(checkpoint, f, indent=1)
print(json.dumps(checkpoint, indent=1)[:6000])

10 · Register the checkpoint as private Kaggle Model versions

Two variations of s41r4j/dama-tier1, each getting a new version with the checkpoint label as version notes:

  • other/tier1: the CPU bundle (ONNX + tokenizers + runtime.py), CHECKPOINT.json, report, calibration, code snapshot. This is what the Memory Agent loads.
  • transformers/tier1-pytorch: the trained PyTorch models (retriever/, decision/, ops/) for further training without retraining from scratch. Uses the notebook's own Kaggle login (or the secret KAGGLE_API_TOKEN when attached). A failed upload only prints a message: everything is still in this version's Output.
In [ ]:
if ON_KAGGLE and MODEL_HANDLE:
    try:
        from kaggle_secrets import UserSecretsClient
        os.environ["KAGGLE_API_TOKEN"] = UserSecretsClient().get_secret("KAGGLE_API_TOKEN").strip()
    except Exception as e:
        print(f"no KAGGLE_API_TOKEN secret ({type(e).__name__}); using the notebook's own credentials")
    try:
        import kagglehub
    except ImportError:
        subprocess.run([sys.executable, "-m", "pip", "install", "-q", "kagglehub"], check=True)
        import kagglehub
    owner_model = MODEL_HANDLE.rsplit("/", 2)[0]
    stage = os.path.join(BASE, "model_upload")
    uploads = {
        MODEL_HANDLE: [(os.path.join(WORK, "export", "dama_tier1"), ".")] + [(os.path.join(WORK, n), os.path.basename(n)) for n in
                      ("CHECKPOINT.json", "code_snapshot.zip", "runs/calibration/report.json", "runs/calibration/calibration.json")],
        f"{owner_model}/transformers/tier1-pytorch": [(os.path.join(WORK, "runs", m, "best"), m) for m in ("retriever", "decision", "ops")]
                                                      + [(os.path.join(WORK, "CHECKPOINT.json"), "CHECKPOINT.json")],
    }
    for handle, items in uploads.items():
        shutil.rmtree(stage, ignore_errors=True)
        os.makedirs(stage)
        for src, dst in items:
            if os.path.isdir(src):
                shutil.copytree(src, os.path.join(stage, dst), dirs_exist_ok=True, ignore=shutil.ignore_patterns("__pycache__", "checkpoint.pt"))
            elif os.path.exists(src):
                shutil.copy(src, os.path.join(stage, dst))
        try:
            kagglehub.model_upload(handle, stage, version_notes=f"{CHECKPOINT}: {CHECKPOINT_NOTES}")
            print(f"registered {CHECKPOINT} as a new version of {handle}")
        except Exception as e:
            print(f"model upload failed for {handle} ({type(e).__name__}: {str(e)[:300]}); the outputs are still in this notebook version")
    shutil.rmtree(stage, ignore_errors=True)

11 · Clean up (Kaggle)

Keeps the trained models (runs/*/best), the calibration and test report, the training logs, the built data, the CPU bundle, CHECKPOINT.json and code_snapshot.zip. Deletes the raw downloads and the optimizer checkpoints, which are only needed to resume a run.

In [ ]:
if ON_KAGGLE and CLEANUP:
    shutil.rmtree(os.path.join(WORK, "raw"), ignore_errors=True)
    for ckpt in glob.glob(os.path.join(WORK, "runs", "*", "checkpoint.pt")):
        os.remove(ckpt)
    shutil.rmtree(CODE, ignore_errors=True)
    shutil.rmtree(os.path.join(BASE, "dama_unzipped"), ignore_errors=True)
for root, _, files in os.walk(WORK):
    size = sum(os.path.getsize(os.path.join(root, f)) for f in files) / 2**20
    if size > 1:
        print(f"{size:8.1f} MB  {root}")