Coverage for lab/model_templates.py: 100%
27 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""`aq lab new`: a model folder from a template (`aether_quant/_templates/lab/<template>/`): `model.py` with its
2`build(n_features, heads, **hparams)`, `config.toml`, and a test that checks the network's shapes and gradients.
3"""
5from __future__ import annotations
7import re
8from pathlib import Path
10from lab.spec import TEMPLATES, TORCH_TEMPLATES
12TEMPLATE_ROOT = Path(__file__).resolve().parents[1] / "aether_quant" / "_templates" / "lab"
14TEST_TEXT = '''"""{name}: the network builds, gives one finite score per row for its head, and its input layer gets a gradient from that head."""
16import importlib.util
17from pathlib import Path
19import pytest
21torch = pytest.importorskip("torch")
22HERE = Path(__file__).resolve().parent
25def _module():
26 spec = importlib.util.spec_from_file_location("{name}_model", HERE / "model.py")
27 module = importlib.util.module_from_spec(spec)
28 spec.loader.exec_module(module)
29 return module
32def test_shapes_and_gradients():
33 model = _module().build(6, ["rank_20d"])
34 rows = torch.randn({batch_shape})
35 output = model(rows)
36 scores = output["rank_20d"] if isinstance(output, dict) else output[0] if isinstance(output, tuple) else output
37 assert scores.shape[0] == 8 and torch.isfinite(scores).all()
38 scores.sum().backward()
39 first = next(parameter for parameter in model.parameters() if parameter.requires_grad)
40 assert first.grad is not None and torch.isfinite(first.grad).all() and first.grad.abs().sum() > 0, "the input layer learns from the head"
41'''
44def valid_name(name: str) -> bool:
45 """Whether a model name is safe as a folder and a module name: a letter, then up to 40 letters, digits or `_`."""
46 return bool(re.fullmatch(r"[A-Za-z][A-Za-z0-9_]{0,40}", name))
49def new_model(lab_dir: Path, name: str, template: str, *, force: bool = False) -> list[str]:
50 """Write models/<name>/ from `template`; returns the files written. Refuses an existing folder unless `force`."""
51 if template not in TEMPLATES:
52 raise ValueError(f"template must be one of {', '.join(TEMPLATES)}")
53 if not valid_name(name):
54 raise ValueError("a model name starts with a letter and holds letters, digits and _ only")
55 folder = lab_dir / "models" / name
56 if folder.exists() and any(folder.iterdir()) and not force:
57 raise FileExistsError(f"{folder} exists (pass --force to overwrite it)")
58 folder.mkdir(parents=True, exist_ok=True)
59 written = []
60 for source, target in (("model.py.tmpl", "model.py"), ("config.toml.tmpl", "config.toml")):
61 text = (TEMPLATE_ROOT / template / source).read_text(encoding="utf-8").replace("{name}", name)
62 (folder / target).write_text(text, encoding="utf-8", newline="\n")
63 written.append(f"models/{name}/{target}")
64 if template in TORCH_TEMPLATES:
65 batch = "8, 20, 6" if template == "tcn" else "8, 6"
66 (folder / f"test_{name}_model.py").write_text(TEST_TEXT.replace("{name}", name).replace("{batch_shape}", batch), encoding="utf-8", newline="\n")
67 written.append(f"models/{name}/test_{name}_model.py")
68 return written