Files
s41r4j-dama/notebooks/DAMA_System_One_Colab.ipynb
T

11 KiB

DAMA — System One decision model

Train a shared pretrained encoder + parallel decision heads. No agent framework, Primary Agent, database or generative decoder is involved.

Status: model implementation and local forward-only tests exist; CUDA training has not run. Shipped synthetic data only validates training mechanics. Nothing in this notebook starts a real run without changing the explicit gate below.

1. Fetch updates, install and check

Select a GPU runtime, then run this cell. Rerun it after code fixes are pushed. It uses the current Python (3.10–3.13), installs DAMA separately from the notebook kernel, and runs config/data checks and software tests. No ZIP upload, Drive mount or training. Setup output is saved to /content/dama-setup.log. CUDA validation must pass here.

In [ ]:
# Paste this entire file into one Colab code cell. Rerun after code updates.
# Setup and software checks only; no training or Drive mount.
from pathlib import Path
import json
import os
import platform
import subprocess
import sys

def run(command):
    # Capturing subprocess output makes it visible through notebook Python stdout.
    with subprocess.Popen(list(map(str, command)), stdout=subprocess.PIPE,
                          stderr=subprocess.STDOUT, text=True) as process:
        for line in process.stdout:
            print(line, end="", flush=True)
        if process.wait():
            raise RuntimeError("Command failed: " + " ".join(map(str, command)))

if platform.system() != "Linux":
    raise RuntimeError("Run this cell in the Colab Linux GPU runtime")
if not ((3, 10) <= sys.version_info[:2] <= (3, 13)):
    raise RuntimeError("Python 3.10–3.13 required; newer versions need validation")
print("Notebook Python:", sys.version, flush=True)
run(["nvidia-smi"])
SOURCE = Path("/content/dama")
REPO = "https://github.com/s41r4j/dama.git"
if SOURCE.exists():
    origin = subprocess.check_output(
        ["git", "-C", str(SOURCE), "remote", "get-url", "origin"], text=True
    ).strip()
    if origin != REPO:
        raise RuntimeError("/content/dama belongs to another repository")
    changes = subprocess.check_output(
        ["git", "-C", str(SOURCE), "status", "--porcelain"], text=True
    )
    if changes.strip():
        raise RuntimeError("Save local checkout edits before fetching updates:\n" + changes)
    run(["git", "-C", str(SOURCE), "pull", "--ff-only", "origin", "main"])
else:
    run(["git", "clone", "--depth", "1", "--branch", "main", REPO, str(SOURCE)])
run(["git", "-C", str(SOURCE), "log", "-1", "--oneline"])
os.chdir(SOURCE)
os.environ["TOKENIZERS_PARALLELISM"] = "false"
run([sys.executable, str(SOURCE / "scripts/bootstrap_colab.py"),
     "--source", str(SOURCE)])
DAMA_PYTHON = Path("/content/dama-env/bin/python")
def dama(*args):
    run([str(DAMA_PYTHON), "-m", "dama", *map(str, args)])
CONFIG = SOURCE / "configs/heads.json"
DATA = SOURCE / "fixtures/model-v1"
dama("validate-config", "--config", CONFIG)
dama("validate-data", "--input", DATA)
dama("test")
print("DAMA READY. Setup and tests passed; training has not started.", flush=True)

2. Persistent storage and explicit training smoke

Only run this cell when ready to perform up to three CUDA optimizer steps. It checks mechanics, not memory-model capability. Choose a new SMOKE_RUN name when repeating so earlier outputs remain reviewable.

In [ ]:
from google.colab import drive
drive.mount("/content/drive")
RUNS = Path("/content/drive/MyDrive/DAMA/model-runs")
RUNS.mkdir(parents=True, exist_ok=True)
SMOKE_RUN = RUNS / "smoke-v1"
RUN_SMOKE = False  # Change to True to explicitly run the cloud smoke test.
if RUN_SMOKE:
    dama("train", "--config", CONFIG, "--data", DATA, "--output", SMOKE_RUN, "--smoke")
else:
    print("Smoke test is gated. Set RUN_SMOKE=True when ready.")
In [ ]:
if (SMOKE_RUN / "metrics.json").exists():
    print(json.loads((SMOKE_RUN / "metrics.json").read_text()))
    print(json.loads((SMOKE_RUN / "run_manifest.json").read_text()))
else:
    print("No cloud training results yet.")

Start with frozen encoder + heads (heads.json). Compare accuracy-frozen.json and accuracy.json for a stronger BGE-base candidate (frozen/LoRA). Select the fastest model satisfying the held-out accuracy constraint; no configuration has proven superior. Review labels and peak VRAM first. The synthetic fixture gate needs a separate explicit override.

In [ ]:
RUN_REAL_TRAINING = False
ALLOW_SYNTHETIC_EXPERIMENT = False
REAL_DATA = DATA  # Replace with reviewed dataset path before research training.
REAL_CONFIG = CONFIG
REAL_RUN = RUNS / "heads-v1"
if RUN_REAL_TRAINING:
    manifest = json.loads((REAL_DATA / "manifest.json").read_text())
    if manifest.get("synthetic") and not ALLOW_SYNTHETIC_EXPERIMENT:
        raise ValueError("Replace fixtures with reviewed data, or explicitly opt into a synthetic experiment")
    extra = ["--allow-synthetic"] if ALLOW_SYNTHETIC_EXPERIMENT else []
    dama("train", "--config", REAL_CONFIG, "--data", REAL_DATA, "--output", REAL_RUN, *extra)
else:
    print("Real training is gated. Set RUN_REAL_TRAINING=True only when ready.")

4. Resume safely

Only completed checkpoints may resume. Fingerprints must match the original config and dataset. Changing total-step/epoch limits requires a new experiment. The checkpoint stores RNG, optimizer, scaler and exact next microbatch position.

In [ ]:
RUN_RESUME = False
RESUME_CHECKPOINT = REAL_RUN / "checkpoint-000050"
if RUN_RESUME:
    if not (RESUME_CHECKPOINT / "COMPLETE").exists():
        raise ValueError("Choose a completed checkpoint")
    extra = ["--allow-synthetic"] if ALLOW_SYNTHETIC_EXPERIMENT else []
    dama("train", "--config", REAL_CONFIG, "--data", REAL_DATA, "--output", REAL_RUN,
         "--resume", RESUME_CHECKPOINT, *extra)
else:
    print("Resume is gated. Select checkpoint, then set RUN_RESUME=True.")

5. Held-out evaluation and export

Freeze model and thresholds using dev before accessing test. This measures the standalone model, not downstream answer quality. All confidences are uncalibrated. The trainer automatically exports a self-contained encoder + heads; a checkpoint can also be exported with dama export --checkpoint ... --output ....

In [ ]:
RUN_HELD_OUT_EVALUATION = False
if RUN_HELD_OUT_EVALUATION:
    dama("evaluate", "--artifact", REAL_RUN / "export", "--input", REAL_DATA / "test.jsonl",
         "--output", REAL_RUN / "test-eval", "--device", "cuda", "--repeats", 3)
else:
    print("Test remains held out. Freeze decisions before enabling this cell.")
In [ ]:
DOWNLOAD_EXPORT = False
if DOWNLOAD_EXPORT:
    import shutil
    export = REAL_RUN / "export"
    if not (export / "manifest.json").exists():
        raise ValueError("No trained export exists yet")
    archive = shutil.make_archive("/content/dama-trained-model", "zip", root_dir=export.parent, base_dir="export")
    from google.colab import files
    files.download(archive)
else:
    print("Download is gated. The export identifies exact encoder revision and file hashes.")

6. Later local loading

dama predict --artifact downloaded/export --input fixtures/inputs/correction.json --device cpu

CPU inference is supported. No training is permitted on the Mac. An optional LoRA export includes the full model state, not a decoder/GGUF adapter. No quality, calibration, speed or cost reduction has been established until measured on reviewed held-out data and an actual trained artifact.