Coverage for lab/model_export.py: 100%

55 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""`aq lab export`: package a lab run in the `aq models` zip format, so `aq models install --from ZIP` and `aq models score` 

2work on it with the numpy forward pass (no torch). 

3 

4The zip holds the exported network (`multitask_model.json`, `sequence_model.json` or `baseline_model.json`) or the linear 

5coefficients (`linear_model.json`), the feature schema, `lab_features.json` (which registry features, ranked within each 

6date, the model reads), the model card and a sha256 manifest, written with fixed entry times so the same run gives the same 

7bytes. 

8""" 

9 

10from __future__ import annotations 

11 

12import hashlib 

13import json 

14import zipfile 

15from pathlib import Path 

16from typing import Any 

17 

18from lab import run_registry, trainer 

19 

20FIXED_TIME = (2026, 1, 1, 0, 0, 0) 

21EXPORTABLE = ("multitask", "tcn", "mlp", "linear") 

22 

23 

24def write_zip(path: Path, files: dict[str, bytes]) -> str: 

25 """`files` plus a manifest of their sha256, with fixed entry times; returns the zip's sha256.""" 

26 manifest = {"files": {name: hashlib.sha256(data).hexdigest() for name, data in sorted(files.items())}, "source": "lab"} 

27 path.parent.mkdir(parents=True, exist_ok=True) 

28 with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED) as archive: 

29 for name, data in [*sorted(files.items()), ("manifest.json", json.dumps(manifest, indent=1, sort_keys=True).encode("utf-8"))]: 

30 archive.writestr(zipfile.ZipInfo(name, date_time=FIXED_TIME), data) 

31 return hashlib.sha256(path.read_bytes()).hexdigest() 

32 

33 

34def _json(data: object) -> bytes: 

35 return json.dumps(data, indent=1, sort_keys=True).encode("utf-8") 

36 

37 

38def export_files(run_dir: Path, *, card: str) -> dict[str, bytes]: 

39 """{zip entry: bytes} for the run's first seed and last fold.""" 

40 record = run_registry.read_run(run_dir) 

41 template = record["template"] 

42 if template not in EXPORTABLE: 

43 raise ValueError(f"export supports the {', '.join(EXPORTABLE)} templates, not {template!r}") 

44 features = list(record["features"]) 

45 seed = record["seeds"][0] 

46 head = trainer.head_of(record["target"]) 

47 files = {"lab_features.json": _json({"features": features, "inputs": "within-date percentile rank minus 0.5, missing = 0", "head": head}), 

48 "card.md": card.encode("utf-8")} 

49 if template == "linear": 

50 coefficients = json.loads(sorted(run_dir.glob(f"linear_*_seed_{seed}.json"))[-1].read_text(encoding="utf-8")) 

51 files["linear_model.json"] = _json({"kind": "linear", "head": head, "features": features, "coefficients": coefficients["coefficients"]}) 

52 files["linear_feature_schema.json"] = _json({"model_input_names": features}) 

53 return files 

54 torch = trainer.require_torch() 

55 from lab import architectures 

56 

57 spec = json.loads((run_dir / "config.json").read_text(encoding="utf-8")) 

58 module = trainer.load_model_module(run_dir.parent.parent / "models" / record["model"]) 

59 hparams = {key: value for key, value in spec["model"].items() if key not in {"template", "name"}} 

60 model = module.build(len(features), [head], **hparams) 

61 model.load_state_dict(torch.load(sorted(run_dir.glob(f"model_*_seed_{seed}.pt"))[-1], weights_only=True)) 

62 model.eval() 

63 state = architectures.export_state_dict(model) 

64 if template == "tcn": 

65 window = int(spec["model"]["window"]) 

66 files["sequence_model.json"] = _json({"model": {"type": "lab_sequence", "window_size": window, "model_input_features": features, "head": head}, 

67 "export": architectures.export_sequence_multitask_horizons_architecture(model) | {"state_dict": state}}) 

68 files["sequence_feature_schema.json"] = _json({"model_input_names": features, "window_size": window}) 

69 elif template == "multitask": 

70 files["multitask_model.json"] = _json({"model": {"type": "lab_multitask", "model_input_features": features, "head": head}, 

71 "export": architectures.export_multitask_horizons_architecture(model) | {"state_dict": state}}) 

72 files["multitask_feature_schema.json"] = _json({"model_input_names": features}) 

73 else: 

74 files["baseline_model.json"] = _json({"model": {"type": "lab_mlp", "model_input_features": features, "head": head}, 

75 "export": {"architecture": architectures.export_architecture(model), "state_dict": state}}) 

76 files["baseline_feature_schema.json"] = _json({"model_input_names": features}) 

77 return files 

78 

79 

80def export_run(run_dir: Path, out: Path, *, card: str) -> dict[str, Any]: 

81 """A lab run as an `aq models` zip: the exported model, its feature schema and features, the card and a sha256 manifest.""" 

82 files = export_files(run_dir, card=card) 

83 digest = write_zip(out, files) 

84 return {"zip": str(out), "sha256": digest, "files": sorted([*files, "manifest.json"])}