Publish CUDA and restart verification before execution
Browse filesFiles changed (5)
2 unmodified lines3456678991011122 unmodified linesInstall Python 3.12 and [uv](https://docs.astral.sh/uv/). The lock targets Windows AMD64 and Linux x86_64 with an NVIDIA driver supporting the CUDA 13.2 PyTorch wheel. The default scratch model and adapter math use float32. Make a project-local environment and install all locked dependencies with `uv sync --locked`. Copy `.env.example` to `.env` and optionally set `THIRDLOSS_STORAGE` to a directory with room for corpora, CUDA checkpoints and Hub downloads. Use the existing GitHub CLI and Hugging Face login for publication.
```sh
uv run pytest -q
uv run thirdloss verify
uv run thirdloss prepare --stage stories
uv run thirdloss train --stage stories --method third --phase pilot --seed 0 --ratio 0.03
uv run thirdloss dashboard --port 8765
uv run thirdloss dashboard --port 18765
```
In another terminal, open the printed dashboard URL. The public explorer reads the last published results. The local dashboard reads running records. Accuracy is top-one token accuracy and NLL is in nats per target token. The training-time column excludes data preparation, checks, validation, checkpoint serialization and publication.33 unmodified lines343536373738394022 unmodified lines63646566676869707133 unmodified lines p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--project",type=Path,default=Path.cwd())
parsers = p.add_subparsers(dest="action",required=True)
for action in ("prepare","train","study","freeze","evaluate","report","dashboard","publish","progress"):
for action in ("prepare","train","study","freeze","evaluate","report","dashboard","publish","progress","verify"):
sub = parsers.add_parser(action)
if action in {"prepare","study"}:
sub.add_argument("--stage",choices=(*HORIZONS,"both"),default="both")22 unmodified lines args = parser().parse_args(argv)
project = args.project.resolve()
storage = storage_root(project)
if args.action=="verify":
from .verification import verify
return verify(project)
if args.action=="dashboard":
return dashboard(project,args.port)
if args.action in {"report","progress","publish"}:12345678910111213141516171819202122232425"""Persist a portable verification record from pytest's machine-readable JUnit output."""
import subprocessimport sysimport xml.etree.ElementTree as ET
from .records import time_now, write_json
def verify(project): directory = project/"tmp"/"verification" directory.mkdir(parents=True,exist_ok=True) xml = directory/"pytest.xml" completed = subprocess.run([sys.executable,"-m","pytest","-q","--junitxml",str(xml)],cwd=project) records = [] for case in ET.parse(xml).iter("testcase"): outcome = next((name for name in ("error","failure","skipped") if case.find(name) is not None),"passed") records.append({"test":f"{case.get('classname')}.{case.get('name')}", "seconds":float(case.get("time","0")),"outcome":outcome}) write_json(project/"results"/"verification"/"tests.json",{ "checked_at":time_now(), "git_revision":subprocess.check_output( ["git","rev-parse","HEAD"],cwd=project,text=True).strip(), "exit_code":completed.returncode,"cases":records}) if completed.returncode: raise SystemExit(completed.returncode)13 unmodified lines141516171819202122232425262728293031323334353637383940414213 unmodified linesfrom thirdloss.penalties import estimate
@pytest.mark.skipif(not torch.cuda.is_available(),reason="CUDA hardware unavailable")
def test_gpu_production_decoder_third_order_update_matches_cpu():
"""Verify the same fourth derivative on the actual eager CUDA kernels and CPU FP64."""
from copy import deepcopy
from thirdloss.models import StoryConfig, StoryTransformer, token_loss
torch.manual_seed(7)
cpu = StoryTransformer(StoryConfig(vocab_size=7,width=8,heads=2,layers=1,hidden=12,context=4)).double()
gpu = deepcopy(cpu).cuda()
ids = torch.tensor([[2,3,1,0],[4,2,5,3]])
u = tuple(torch.randint(2,p.shape).double()*2-1 for p in cpu.parameters())
v = tuple(torch.randint(2,p.shape).double()*2-1 for p in cpu.parameters())
def calculate(model,device):
parameters = tuple(model.parameters())
loss = token_loss(model(ids.to(device)),((ids+1)%7).to(device))
term = estimate(loss,parameters,"third",tuple(p.to(device) for p in u),tuple(p.to(device) for p in v))
gradient = torch.autograd.grad(term,parameters)
return term.detach().cpu(),torch.cat([g.flatten() for g in gradient]).detach().cpu()
expected = calculate(cpu,"cpu")
actual = calculate(gpu,"cuda")
for reference,observed in zip(expected,actual,strict=True):
torch.testing.assert_close(observed,reference,rtol=2e-8,atol=1e-5)
@pytest.fixture(scope="module", autouse=True)
def small_cpu_tensors():
"""Keep the tiny reference calculations deterministic and inexpensive on a CPU."""8 unmodified lines910111213121314151660 unmodified lines7778798081828384808182838485868 unmodified linesfrom thirdloss import train
from thirdloss.models import StoryConfig, StoryTransformer
from thirdloss.objectives import add_penalty
from thirdloss.records import read_json, write_json
from thirdloss.windows import TrainingWindows, gate, generator
from thirdloss.records import write_json
from thirdloss.windows import gate
def small_model(stage, seed, device, storage):60 unmodified lines store2 = tmp_path/"store2"
shutil.copytree(root/"data",store2/"data")
normal = train.run_one(reference,store2,"stories","third","smoke",seed,0.03,torch.device("cpu"))
for path, other in [(root,store2)]:
rel = f"checkpoints/{normal['id']}/export/model.safetensors"
first, second = load_file(str(path/rel)),load_file(str(other/rel))
for name in first:
torch.testing.assert_close(first[name],second[name],rtol=0,atol=0)
rel = f"checkpoints/{normal['id']}/export/model.safetensors"
first, second = load_file(str(root/rel)),load_file(str(store2/rel))
for name in first:
torch.testing.assert_close(first[name],second[name],rtol=0,atol=0)
assert normal["dev_nll"]==resumed["dev_nll"]
finally:
torch.set_num_threads(prior_threads)research/docs/runbook.md+2-2
research/src/thirdloss/cli.py+4-1
research/src/thirdloss/verification.pyAdded+25
research/tests/test_derivatives.py+23
research/tests/test_training.py+6-7