Files
s41r4j-dama/code/colab/DAMA_Colab.ipynb
T
s41r4jandClaude Opus 5.5 e3944811d4 Rewrite DAMA as a model-only package under code/
Drop the CLI, packaging, bootstrap scripts, fixtures and tests. The Colab
notebook now calls dama.data, dama.training, dama.evaluate and
dama.inference directly. The model gets learned metadata embeddings, a
separate recent-context item, a raw cosine pair feature, a span head
conditioned on the event vector, and learned ARCHIVE. Training adds
warmup/decay and best-dev-epoch export; the data generator holds out
templates and values per split.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 20:04:41 +05:30

6.8 KiB

DAMA — memory decision model

One forward pass of a small encoder + decision heads turns a message and candidate memories into a typed decision: ADD / NOOP / UPDATE / ARCHIVE, memory type, update target, the exact evidence span, retrieval relevance and a fallback flag.

Run top to bottom on a GPU runtime (Runtime → Change runtime type → T4 or better).

1. Setup

In [ ]:
import subprocess, sys
from pathlib import Path

REPO, SOURCE = "https://github.com/s41r4j/dama.git", Path("/content/dama")
if SOURCE.exists():
    subprocess.run(["git", "-C", str(SOURCE), "pull", "--ff-only"], check=True)
else:
    subprocess.run(["git", "clone", "--depth", "1", REPO, str(SOURCE)], check=True)
subprocess.run([sys.executable, "-m", "pip", "install", "-q", "-r", str(SOURCE / "code/requirements.txt")], check=True)
sys.path.insert(0, str(SOURCE / "code"))

import torch
assert torch.cuda.is_available(), "Select a GPU runtime first"
print(torch.cuda.get_device_name(), "| torch", torch.__version__)

2. Generate the dataset

Synthetic but varied: ~10k examples over 16 memory slots and 14 behaviours (add, duplicate, update, archive, hedged, hearsay, chatter, assistant text, contextual answers, current/historical/missing/type retrieval). Dev and test use message templates and entity values never seen in training, so their scores measure generalisation rather than memorisation.

In [ ]:
import json
from dama.data import generate, load_split

DATA = Path("/content/dama-data")
manifest = generate(DATA)
print({k: v["count"] for k, v in manifest["files"].items()})
example = load_split(DATA, "train")[0]
print(json.dumps(example.model_dump(), indent=1)[:1500])

3. Train

minilm-frozen is the fast baseline (~23M parameters, ~1M trainable). Compare minilm-lora, bge-frozen and bge-lora on the same data; pick the fastest one that meets your dev accuracy target. SMOKE = True runs 3 steps to check the pipeline. The best dev epoch is exported to RUN/export.

In [ ]:
from datetime import datetime
from dama.training import train

CONFIG_NAME = "minilm-frozen"   # minilm-frozen | minilm-lora | bge-frozen | bge-lora
SMOKE = False
RUN = Path("/content/dama-runs") / f"{CONFIG_NAME}-{datetime.now():%Y%m%d-%H%M%S}"
model, tokenizer, summary = train(SOURCE / f"code/configs/{CONFIG_NAME}.json", DATA, RUN, smoke=SMOKE)
print("best dev score:", summary["best_dev_score"], "| export:", RUN / "export")

4. Held-out test evaluation

Run once you are done choosing configs on dev.

In [ ]:
from collections import defaultdict
from dama.evaluate import evaluate
from dama.inference import Predictor

predictor = Predictor(model, tokenizer, device="cuda")
test = load_split(DATA, "test")
metrics = evaluate(predictor, test, output=RUN / "test-eval")
print(json.dumps({k: v for k, v in metrics.items() if k != "confusion"}, indent=1))

# Per-behaviour accuracy: did the decision match the label on the field that matters for that family?
rows = [json.loads(l) for l in (RUN / "test-eval/predictions.jsonl").read_text().splitlines()]
by_family = defaultdict(list)
for r in rows:
    d, y = r["decision"], r["label"]
    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"])
    by_family[r["family"]].append(ok)
for family, oks in sorted(by_family.items()):
    print(f"{family:18s} {sum(oks)/len(oks):.3f}  (n={len(oks)})")

5. Try it

In [ ]:
from dama.contracts import Candidate, ModelInput

x = ModelInput(task="write", text="Heads up: we moved the API from Heroku to Fly.io last week. Can you update the docs?",
               candidates=[Candidate(id="host", text="The app is hosted on Heroku."),
                           Candidate(id="theme", text="The user prefers dark mode.", memory_type="preference")])
decision, timing = predictor.predict(x)
print(json.dumps(decision.model_dump(), indent=1), timing)

6. Keep the model

The export is self-contained (weights, configs, tokenizer, hashes). Copy it to Drive or download it.

In [ ]:
SAVE_TO_DRIVE = False
if SAVE_TO_DRIVE:
    import shutil
    from google.colab import drive
    drive.mount("/content/drive")
    shutil.copytree(RUN, Path("/content/drive/MyDrive/DAMA/runs") / RUN.name)
# Later, anywhere:  from dama.artifacts import load_model; model, tokenizer, manifest = load_model("path/to/export")