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>
6.8 KiB
6.8 KiB
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__)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])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")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)})")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)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")