Coverage for scripts/build_example_models.py: 100%
80 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"""Builds the example models anyone can install (V6.6.10): two small networks trained on the library's bundled public sample only.
3 python scripts/build_example_models.py --out dist/example_models
5Writes `<name>.zip` for each example (the exported model, its schema, a model card and a manifest of their sha256) and
6`example_models_manifest.json` (each zip's sha256 and size), the files the release job attaches. It reads the sample, the repo's
7`config.json` (for the training defaults) and, under `ml/`, only the tracked `artifact_pins.json` (hashes) to refuse publishing an
8installed model; the trainers write into a temporary folder.
9"""
11from __future__ import annotations
13import argparse
14import copy
15import hashlib
16import json
17import sys
18import tempfile
19import zipfile
20from pathlib import Path
22ROOT = Path(__file__).resolve().parents[1]
23sys.path.insert(0, str(ROOT))
25from retraining import model_catalog as catalog # noqa: E402
27FIXED_TIME = (2026, 1, 1, 0, 0, 0) # every zip entry carries this time, so the same files give the same zip
28SMALL = {
29 "epochs": 30, "patience": 6, "min_best_epoch": 3, "hidden_layers": [16], "batch_size": 64, "batch_mode": "random", "ranking_loss": None,
30 "min_train_rows": 200, "min_validation_rows": 30, "min_backtest_rows": 30, "swa": {"enabled": False}, "seed": 0, "label_noise_std": 0.0,
31 "gate_aware_ranking_weights": {"enabled": False},
32}
35def training_config(base: dict) -> dict:
36 """The repo's config with the multitask and sequence trainers cut down to a small, seeded, plain run."""
37 config = copy.deepcopy(base)
38 retraining = config["phase_v2"]["retraining"]
39 retraining["multitask_training"].update(SMALL)
40 retraining["sequence_training"].update({**SMALL, "window_size": 20, "channels": [8, 8]})
41 config["phase1"]["features"]["cross_sectional_inputs"] = {"enabled": False}
42 config["phase1"]["target"]["ranking"]["net_performance"] = {"enabled": False}
43 config["phase1"]["target"]["ranking"]["purged_cv"] = {"enabled": False}
44 return config
47def card(name: str, entry: dict, metrics: dict) -> str:
48 backtest = metrics.get("backtest", {}).get("rank_20d_ic") or {}
49 return (
50 f"# {name}\n\n{entry['summary']}\n\n"
51 "An example, not a trading model: it shows the format, the forward pass and `aq models score`. The project's own models are not published.\n\n"
52 f"- Data: the 11 coins of `aether_quant/_sample/coinbase_daily.csv.gz` (Coinbase public daily candles), train to {catalog.SPLITS['train_end']}, "
53 f"validation to {catalog.SPLITS['validation_end']}, backtest to {catalog.SPLITS['backtest_end']}.\n"
54 f"- Inputs: {', '.join(catalog.FEATURES)}, each z-scored across the coins of its date.\n"
55 f"- Backtest rank IC (20 sessions): {backtest.get('mean_ic')}\n"
56 )
59def write_zip(path: Path, files: dict[str, bytes]) -> str:
60 """The zip of `files` plus a manifest of their sha256, with fixed entry times; returns its sha256."""
61 manifest = {"files": {name: hashlib.sha256(data).hexdigest() for name, data in sorted(files.items())}}
62 path.parent.mkdir(parents=True, exist_ok=True)
63 with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED) as archive:
64 for name, data in [*sorted(files.items()), ("manifest.json", json.dumps(manifest, indent=1, sort_keys=True).encode("utf-8"))]:
65 archive.writestr(zipfile.ZipInfo(name, date_time=FIXED_TIME), data)
66 return hashlib.sha256(path.read_bytes()).hexdigest()
69def train(kind: str, *, work: Path, config_path: Path, dataset: Path, schema: Path) -> Path:
70 """Runs one trainer's `main()` in this process with its model folder moved into `work`, so nothing lands in the repo's `ml/`."""
71 import train_multitask
72 import train_sequence
74 module = train_sequence if kind == "sequence" else train_multitask
75 ml_dir, argv = module.ML_DIR, sys.argv
76 module.ML_DIR = work / "ml"
77 sys.argv = [module.__name__, "--version-id", kind, "--config-path", str(config_path), "--dataset-path", str(dataset), "--feature-schema-path", str(schema),
78 "--memory-profile", "low"]
79 try:
80 if module.main() != 0:
81 raise RuntimeError(f"the {kind} trainer failed")
82 finally:
83 # Restored: a later in-process trainer would otherwise write into this (deleted) work folder
84 module.ML_DIR, sys.argv = ml_dir, argv
85 return work / "ml" / "versions" / kind
88def build(out: Path, *, work: Path) -> dict:
89 from aether_quant.samples import load_sample_prices
91 frame = catalog.example_dataset(load_sample_prices())
92 dataset = work / "dataset.csv"
93 frame.to_csv(dataset, index=False)
94 schema = work / "feature_schema.json"
95 schema.write_text(json.dumps({"model_input_names": list(catalog.FEATURES), "feature_names": list(catalog.FEATURES)}), encoding="utf-8")
96 config_path = work / "config.json"
97 config_path.write_text(json.dumps(training_config(json.loads((ROOT / "config.json").read_text(encoding="utf-8")))), encoding="utf-8")
98 manifest: dict = {"models": {}}
99 pins = ROOT / "ml" / "artifact_pins.json" # tracked: hashes only, read to refuse publishing an installed model
100 pinned = json.loads(pins.read_text(encoding="utf-8")).get("files", {}) if pins.exists() else {}
101 for name, entry in catalog.EXAMPLES.items():
102 version = train(entry["kind"], work=work, config_path=config_path, dataset=dataset, schema=schema)
103 metrics_name = "sequence_training_metrics.json" if entry["kind"] == "sequence" else "multitask_training_metrics.json"
104 metrics = json.loads((version / metrics_name).read_text(encoding="utf-8"))
105 files = {entry["model"]: (version / entry["model"]).read_bytes(), entry["schema"]: (version / entry["schema"]).read_bytes(),
106 "card.md": card(name, entry, metrics).encode("utf-8")}
107 collisions = catalog.production_collisions(files, pinned)
108 if collisions:
109 raise RuntimeError(f"{name}: {collisions} match an installed model's pinned hash; a production model is never published")
110 sha = write_zip(out / f"{name}.zip", files)
111 manifest["models"][name] = {"sha256": sha, "size": (out / f"{name}.zip").stat().st_size, "kind": entry["kind"]}
112 (out / catalog.MANIFEST_ASSET).write_text(json.dumps(manifest, indent=1, sort_keys=True) + "\n", encoding="utf-8")
113 return manifest
116def main(argv: list[str] | None = None) -> int:
117 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
118 parser.add_argument("--out", default="dist/example_models")
119 args = parser.parse_args(argv)
120 out = Path(args.out) if Path(args.out).is_absolute() else ROOT / args.out
121 with tempfile.TemporaryDirectory(prefix="aq_examples_") as work:
122 manifest = build(out, work=Path(work))
123 print(json.dumps(manifest, indent=1))
124 return 0
127if __name__ == "__main__":
128 raise SystemExit(main())