21 KiB
21 KiB
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
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)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"))
In [ ]:
lme_flag = "" if USE_LME_S else "--no-lme-s"
run("download", "--work", WORK, lme_flag)
run("build", "--work", WORK, lme_flag)
In [ ]:
run("train-retriever", "--work", WORK)
run("train-decision", "--work", WORK, "--max-minutes", str(MAX_MINUTES))
In [ ]:
run("train-ops", "--work", WORK, "--max-minutes", str(MAX_MINUTES))
In [ ]:
dense_flag = "" if USE_DENSE else "--no-dense"
run("calibrate", "--work", WORK, dense_flag)
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.")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)
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])
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)
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}")