Coverage for lab/trainer.py: 100%

265 statements  

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

1"""`aq lab train`: fit a lab model on a dataset's train split, early-stop on validation, score every out-of-sample row, 

2and record the run, its scores, weights and pins, and one trial per seed in the lab's ledger. 

3 

4The networks, losses and training mechanics are the production ones (`lab.architectures`, `lab.losses`, 

5`lab.training_utils`), so a lab model trains the way the shipped models do. The inputs are within-date percentile ranks, 

6which need no fitted scaler and so carry no scaler look-ahead. Sealed holdout rows never reach a fit or a score. 

7 

8Folds: `split` trains on `train`, stops on `validation` and scores `validation` and `backtest`; `annual` retrains each 

9year on everything up to 21 days before it (an expanding walk-forward) and scores that year. 

10""" 

11 

12from __future__ import annotations 

13 

14import datetime as _datetime 

15import hashlib 

16import importlib.util 

17import json 

18import platform 

19import sys 

20import time 

21import types 

22import warnings 

23from collections.abc import Callable, Mapping, Sequence 

24from pathlib import Path 

25from typing import Any 

26 

27import numpy as np 

28import pandas as pd 

29 

30from evaluation.rank_ic_core import rank_ic_from_arrays 

31from json_safety import atomic_write_json 

32from lab import lab_dataset, run_registry 

33from lab import spec as lab_spec 

34 

35LEDGER = "trials.jsonl" 

36TRACK = "lab" 

37 

38 

39class TorchMissing(RuntimeError): 

40 """A neural template without torch installed.""" 

41 

42 

43 

44def progress(message: str) -> None: 

45 """Progress lines go to stderr, so a --json result on stdout stays parseable.""" 

46 print(message, file=sys.stderr) 

47 

48def head_of(target: str) -> str: 

49 """target_rank_20d -> rank_20d (the production head that predicts it).""" 

50 return target.removeprefix("target_") 

51 

52 

53def load_model_module(model_dir: Path) -> types.ModuleType: 

54 """The model's own `model.py` (its `build(n_features, heads, **hparams)`), imported from its file.""" 

55 path = model_dir / "model.py" 

56 if not path.exists(): 

57 raise FileNotFoundError(f"{path} is missing: aq lab new {model_dir.name} --template ...") 

58 module_spec = importlib.util.spec_from_file_location(f"aq_lab_model_{model_dir.name}", path) 

59 module = importlib.util.module_from_spec(module_spec) 

60 try: 

61 module_spec.loader.exec_module(module) 

62 except ModuleNotFoundError as error: 

63 if error.name == "torch": 

64 require_torch() # raises TorchMissing with the install line 

65 raise 

66 return module 

67 

68 

69def require_torch() -> types.ModuleType: 

70 """torch, or TorchMissing with the install line.""" 

71 try: 

72 import torch 

73 except ImportError as error: 

74 raise TorchMissing('the neural templates need torch: pip install "aether-quant[train]" (the linear template runs without it)') from error 

75 return torch 

76 

77 

78# --------------------------------------------------------------------------- 

79# folds 

80# --------------------------------------------------------------------------- 

81 

82 

83def make_folds(frame: pd.DataFrame, kind: str) -> list[dict]: 

84 """[{name, fit: bool mask, stop: bool mask, score: bool mask}] over `frame`'s rows.""" 

85 split = frame["split"].astype(str) 

86 if kind == "split": 

87 return [{"name": "split", "fit": (split == "train").to_numpy(), "stop": (split == "validation").to_numpy(), 

88 "score": split.isin(["validation", "backtest"]).to_numpy()}] 

89 if kind != "annual": 

90 raise ValueError(f"folds must be split or annual, not {kind!r}") 

91 from features.training_splits import annual_windows 

92 

93 dates = frame["date"].astype(str) 

94 years = sorted({date[:4] for date in dates}) 

95 windows = annual_windows(sorted(set(dates)), first_test_year=int(years[1]) if len(years) > 1 else int(years[0])) 

96 folds = [] 

97 for window in windows: 

98 fit = ((dates <= window["train_end"]) & (frame["split"].astype(str) != "purged")).to_numpy() 

99 score = ((dates >= window["test_start"]) & (dates <= window["test_end"])).to_numpy() 

100 if fit.sum() and score.sum(): 

101 cut = np.quantile(np.flatnonzero(fit), 0.8).astype(int) 

102 stop = fit & (np.arange(len(frame)) > cut) 

103 folds.append({"name": window["test_start"][:4], "fit": fit & ~stop, "stop": stop, "score": score}) 

104 if not folds: 

105 raise ValueError("annual folds need at least two calendar years of rows") 

106 return folds 

107 

108 

109# --------------------------------------------------------------------------- 

110# the linear template (numpy only) 

111# --------------------------------------------------------------------------- 

112 

113 

114def fit_linear(x: np.ndarray, y: np.ndarray, ridge: float) -> np.ndarray: 

115 """Ridge regression of `y` on `x` with an intercept (intercept unpenalised); returns [intercept, coefficients...].""" 

116 keep = np.isfinite(y) 

117 design = np.column_stack([np.ones(int(keep.sum())), x[keep]]) 

118 penalty = np.eye(design.shape[1]) * float(ridge) 

119 penalty[0, 0] = 0.0 

120 return np.linalg.solve(design.T @ design + penalty, design.T @ y[keep]) 

121 

122 

123def predict_linear(x: np.ndarray, coefficients: np.ndarray) -> np.ndarray: 

124 """A linear model's scores: its coefficients applied to the ranked inputs.""" 

125 return coefficients[0] + x @ coefficients[1:] 

126 

127 

128# --------------------------------------------------------------------------- 

129# the torch templates 

130# --------------------------------------------------------------------------- 

131 

132 

133def model_outputs(output: Any, head: str) -> Any: 

134 """The tensor for `head` from a model's output: a dict's head, a tuple's first item, or the tensor itself.""" 

135 if isinstance(output, dict): 

136 if head not in output: 

137 raise KeyError(f"the model has no {head!r} head (it has {', '.join(output)})") 

138 return output[head] 

139 if isinstance(output, (tuple, list)): 

140 return output[0] 

141 return output 

142 

143 

144def _inputs(x: np.ndarray, rows: np.ndarray, windows: np.ndarray | None): 

145 from retraining.slicing import gather_windows 

146 

147 torch = require_torch() 

148 if windows is None: 

149 return torch.from_numpy(np.ascontiguousarray(x[rows])) 

150 return torch.from_numpy(gather_windows(x, windows[rows])) 

151 

152 

153def fit_torch(module: types.ModuleType, x: np.ndarray, y: np.ndarray, dates: np.ndarray, folds_fit: np.ndarray, folds_stop: np.ndarray, *, spec: Mapping[str, Any], 

154 seed: int, head: str, windows: np.ndarray | None, log: Callable[[str], None] = progress, checkpoint: Path | None = None) -> tuple[Any, list[dict[str, Any]]]: 

155 """Train `module.build(...)` on the fit rows with whole-date batches and the chosen ranking loss; keep the epoch with the best 

156 smoothed validation rank IC. Returns (model, history).""" 

157 torch = require_torch() 

158 from lab.losses import compute_cross_sectional_ranking_loss 

159 from lab.training_utils import ( 

160 build_cross_sectional_date_batches, 

161 build_date_group_ids, 

162 build_lr_scheduler, 

163 build_optimizer, 

164 is_new_best_epoch, 

165 select_device, 

166 set_seed, 

167 smoothed_metric, 

168 ) 

169 

170 train, model_spec = spec["train"], spec["model"] 

171 set_seed(seed) 

172 device = select_device(train["device"]) 

173 hparams = {key: value for key, value in model_spec.items() if key not in {"template", "name"}} 

174 model = module.build(x.shape[1], [head], **hparams).to(device) 

175 optimizer = build_optimizer(model, {"optimizer": train["optimizer"], "learning_rate": train["lr"], "weight_decay": train["weight_decay"]}) 

176 scheduler = build_lr_scheduler(optimizer, {"lr_schedule": train["lr_schedule"]}, train["epochs"]) 

177 fit_rows, stop_rows = np.flatnonzero(folds_fit & np.isfinite(y)), np.flatnonzero(folds_stop & np.isfinite(y)) 

178 loss_config = {"objective": train["loss"], "temperature": train["temperature"]} 

179 history: list[dict] = [] 

180 best_state, best_epoch, best_smoothed = None, -1, None 

181 start_epoch = 0 

182 if checkpoint is not None and checkpoint.exists(): 

183 saved = torch.load(checkpoint, weights_only=False) 

184 model.load_state_dict(saved["model"]) 

185 optimizer.load_state_dict(saved["optimizer"]) 

186 history, best_state, best_epoch, start_epoch = saved["history"], saved["best_state"], saved["best_epoch"], saved["epoch"] + 1 

187 best_smoothed = saved["best_smoothed"] 

188 for epoch in range(start_epoch, train["epochs"]): 

189 model.train() 

190 batches = build_cross_sectional_date_batches(dates[fit_rows], batch_dates=train["batch_dates"], min_group_size=2, shuffle=True, seed=seed + epoch) 

191 losses = [] 

192 for batch in batches: 

193 rows = fit_rows[batch] 

194 group_ids = torch.from_numpy(build_date_group_ids(dates[rows]).astype(np.int64)).to(device) 

195 prediction = model_outputs(model(_inputs(x, rows, windows).to(device)), head) 

196 loss = compute_cross_sectional_ranking_loss(prediction, torch.from_numpy(y[rows].astype(np.float32)).to(device), group_ids, loss_config) 

197 optimizer.zero_grad() 

198 loss.backward() 

199 optimizer.step() 

200 losses.append(float(loss.detach())) 

201 if scheduler is not None: 

202 scheduler.step() 

203 ic = rank_ic_from_arrays(predict_torch(model, x, stop_rows, windows, head), y[stop_rows], dates[stop_rows])["mean_ic"] if len(stop_rows) else None 

204 history.append({"epoch": epoch, "train_loss": float(np.mean(losses)) if losses else None, "validation_rank_ic": ic}) 

205 smoothed = smoothed_metric(history, "validation_rank_ic", train["early_stop_smoothing_epochs"]) 

206 history[-1]["smoothed"] = smoothed 

207 improved = smoothed is not None and (best_smoothed is None or is_new_best_epoch(smoothed, best_smoothed, epoch, train["min_best_epoch"])) 

208 if best_state is None or improved or smoothed is None: # without validation rows the last epoch is kept 

209 best_state = {key: value.detach().clone() for key, value in model.state_dict().items()} 

210 best_epoch, best_smoothed = epoch, smoothed if improved else best_smoothed 

211 log(f" epoch {epoch + 1}/{train['epochs']}: loss {history[-1]['train_loss']:.4f}, validation rank IC " + ("-" if ic is None else f"{ic:+.4f}")) 

212 if checkpoint is not None: 

213 torch.save({"model": model.state_dict(), "optimizer": optimizer.state_dict(), "history": history, "best_state": best_state, 

214 "best_epoch": best_epoch, "best_smoothed": best_smoothed, "epoch": epoch}, checkpoint) 

215 if epoch - best_epoch >= train["patience"]: 

216 log(f" early stop: no better validation IC for {train['patience']} epochs (best epoch {best_epoch + 1})") 

217 break 

218 model.load_state_dict(best_state) 

219 return model, history 

220 

221 

222def predict_torch(model: Any, x: np.ndarray, rows: np.ndarray, windows: np.ndarray | None, head: str, chunk: int = 4096) -> np.ndarray: 

223 """A network's scores for the given rows (with their windows for a sequence model), in batches, without gradients.""" 

224 torch = require_torch() 

225 device = next(model.parameters()).device 

226 model.eval() 

227 out = [] 

228 with torch.no_grad(): 

229 for start in range(0, len(rows), chunk): 

230 out.append(model_outputs(model(_inputs(x, rows[start:start + chunk], windows).to(device)), head).float().cpu().numpy().reshape(-1)) 

231 return np.concatenate(out) if out else np.array([], dtype=np.float32) 

232 

233 

234# --------------------------------------------------------------------------- 

235# one run 

236# --------------------------------------------------------------------------- 

237 

238 

239def sha256_file(path: Path) -> str: 

240 """A file's sha256 hex digest.""" 

241 digest = hashlib.sha256() 

242 with path.open("rb") as handle: 

243 for block in iter(lambda: handle.read(1 << 20), b""): 

244 digest.update(block) 

245 return digest.hexdigest() 

246 

247 

248def spread_sharpe(scores: pd.Series, frame: pd.DataFrame, *, quantile: float = 0.2) -> tuple[float | None, int]: 

249 """The annualised Sharpe of a daily top-minus-bottom quintile book on `target_return_1d` (252 sessions, 365 if weekends 

250 trade), and its number of days: the series a trial is counted by.""" 

251 data = frame.assign(_score=scores.to_numpy()).dropna(subset=["_score", "target_return_1d"]) 

252 daily = [] 

253 for _, group in data.groupby("date"): 

254 if len(group) < 4: 

255 continue 

256 ranked = group["_score"].rank(pct=True) 

257 daily.append(group.loc[ranked > 1 - quantile, "target_return_1d"].mean() - group.loc[ranked <= quantile, "target_return_1d"].mean()) 

258 series = np.asarray(daily, dtype=float) 

259 if len(series) < 2 or float(series.std(ddof=1)) == 0.0: 

260 return None, int(len(series)) 

261 weekends = pd.to_datetime(data["date"].unique()).day_of_week.max() >= 5 

262 return float(series.mean() / series.std(ddof=1) * np.sqrt(365.0 if weekends else 252.0)), int(len(series)) 

263 

264 

265def ledger_count(lab_dir: Path, project_ledger: Path | None = None) -> int: 

266 """N: every candidate trial in the lab's ledger (and the project's, when the run is filed there).""" 

267 from evaluation.trial_ledger import candidate_ids, read_ledger 

268 

269 ids = set() 

270 for path in [lab_dir / LEDGER, *( [project_ledger] if project_ledger else [])]: 

271 if path.exists(): 

272 ids |= candidate_ids(read_ledger(path)) 

273 return len(ids) 

274 

275 

276def train_run(lab_dir: Path, model_name: str, *, overrides: Mapping[str, Any] | None = None, seeds: Sequence[int] | None = None, folds: str = "split", 

277 resume: str | None = None, dry_run: bool = False, project_ledger: Path | None = None, project_config: Path | None = None, 

278 log: Callable[[str], None] = progress) -> dict[str, Any]: 

279 """Train one lab model for each seed and record the run; returns its run.json record.""" 

280 from retraining import run_resume 

281 

282 model_dir = lab_dir / "models" / model_name 

283 if not model_dir.is_dir(): 

284 raise FileNotFoundError(f"no model {model_name!r} in {lab_dir / 'models'}: aq lab new {model_name} --template multitask") 

285 spec = lab_spec.load_spec(model_dir, lab_dir=lab_dir, overrides=overrides) 

286 if seeds: 

287 spec["train"]["seeds"] = list(seeds) 

288 dataset_path = Path(spec["data"]["dataset"]) 

289 dataset_path = dataset_path if dataset_path.is_absolute() else lab_dir / dataset_path 

290 if not dataset_path.exists(): 

291 raise FileNotFoundError(f"no dataset at {dataset_path}: aq dataset build --prices closes.csv --out {dataset_path}") 

292 frame = lab_dataset.load_dataset(dataset_path, project_config=project_config).sort_values(["ticker", "date"]).reset_index(drop=True) 

293 target = spec["data"]["target"] 

294 if target not in frame.columns: 

295 raise ValueError(f"the dataset has no {target} column (it has {', '.join(lab_dataset.target_columns(frame))})") 

296 features = lab_dataset.feature_columns(frame) if spec["data"]["features"] == "all" else [name for name in spec["data"]["features"] if name in frame.columns] 

297 template = spec["model"]["template"] 

298 plan = {"model": model_name, "template": template, "dataset": str(dataset_path), "rows": len(frame), "features": features, "target": target, 

299 "loss": spec["train"]["loss"], "seeds": spec["train"]["seeds"], "folds": folds} 

300 if dry_run: 

301 return {"dry_run": True, **plan} 

302 module = None if template == "linear" else load_model_module(model_dir) 

303 if module is not None: 

304 require_torch() 

305 runs_root = lab_dir / "runs" 

306 if resume: 

307 run_dir = run_resume.find_resumable(runs_root, "", None if resume == "latest" else resume) 

308 if run_dir is None: 

309 raise FileNotFoundError("no stopped lab run to resume (aq lab runs)") 

310 else: 

311 run_dir = runs_root / run_registry.new_run_id(model_name) 

312 run_resume.start_record(run_dir, {"settings": {"model": model_name, "seeds": spec["train"]["seeds"], "folds": folds, "overrides": dict(overrides or {})}}) 

313 started = time.time() 

314 run_registry.write_run(run_dir, {**plan, "status": "running", "started": _datetime.datetime.now(_datetime.timezone.utc).isoformat(timespec="seconds")}) 

315 atomic_write_json(run_dir / "config.json", spec, indent=2) 

316 x = lab_dataset.rank_features(frame, features) 

317 y = frame[target].to_numpy(dtype=float) 

318 dates = frame["date"].astype(str).to_numpy() 

319 windows = None 

320 if template == "tcn": 

321 from retraining.slicing import sequence_window_index 

322 

323 windows = sequence_window_index(frame["ticker"].to_numpy(), int(spec["model"]["window"])) 

324 fold_list = make_folds(frame, folds) 

325 head = head_of(target) 

326 done = set(run_resume.done_steps(run_dir)) 

327 seed_scores: dict[int, np.ndarray] = {} 

328 fold_metrics: list[dict] = [] 

329 for seed in spec["train"]["seeds"]: 

330 step = f"seed_{seed}" 

331 scores_path = run_dir / f"scores_seed_{seed}.npy" 

332 if step in done and scores_path.exists(): 

333 seed_scores[seed] = np.load(scores_path) 

334 log(f"seed {seed}: done earlier, loaded") 

335 continue 

336 log(f"seed {seed}: {template} on {len(features)} features, {len(fold_list)} fold(s)") 

337 scores = np.full(len(frame), np.nan) 

338 for fold in fold_list: 

339 if template == "linear": 

340 coefficients = fit_linear(x[fold["fit"]], y[fold["fit"]], float(spec["model"]["ridge"])) 

341 scores[fold["score"]] = predict_linear(x[fold["score"]], coefficients) 

342 atomic_write_json(run_dir / f"linear_{fold['name']}_seed_{seed}.json", {"features": features, "coefficients": coefficients.tolist(), "target": target}) 

343 history = [] 

344 else: 

345 torch = require_torch() 

346 model, history = fit_torch(module, x, y, dates, fold["fit"], fold["stop"], spec=spec, seed=seed, head=head, windows=windows, log=log, 

347 checkpoint=run_dir / f"checkpoint_{fold['name']}_seed_{seed}.pt") 

348 rows = np.flatnonzero(fold["score"]) 

349 scores[rows] = predict_torch(model, x, rows, windows, head) 

350 torch.save(model.state_dict(), run_dir / f"model_{fold['name']}_seed_{seed}.pt") 

351 score_rows = np.flatnonzero(fold["score"]) 

352 ic = rank_ic_from_arrays(scores[score_rows], y[score_rows], dates[score_rows]) 

353 fold_metrics.append({"seed": seed, "fold": fold["name"], "oof_ic": ic["mean_ic"], "t_stat": ic["t_stat"], "dates": ic["num_dates"], 

354 "epochs": len(history), "best_validation_ic": max((row["validation_rank_ic"] for row in history if row["validation_rank_ic"] is not None), default=None)}) 

355 np.save(scores_path, scores) 

356 seed_scores[seed] = scores 

357 sharpe, n_obs = spread_sharpe(pd.Series(scores), frame) 

358 from evaluation.trial_ledger import append_trial 

359 

360 for ledger in [lab_dir / LEDGER, *([project_ledger] if project_ledger else [])]: 

361 append_trial(ledger, trial_id=f"{run_dir.name}:seed_{seed}", track=TRACK, window="lab_oof", role="candidate", 

362 annualised_sharpe=sharpe if sharpe is not None else 0.0, n_obs=n_obs, config_sha=hashlib.sha256(json.dumps(spec, sort_keys=True).encode()).hexdigest()[:16], 

363 engine="aq lab train", detail={"model": model_name, "template": template, "seed": seed}) 

364 run_resume.mark_done(run_dir, step, {"sharpe": sharpe}) 

365 with warnings.catch_warnings(): # a row no fold scored (purged, train-only) stays NaN without a warning 

366 warnings.simplefilter("ignore", RuntimeWarning) 

367 mean_scores = np.nanmean(np.vstack(list(seed_scores.values())), axis=0) if seed_scores else np.array([]) 

368 out = frame[["date", "ticker", "split"]].assign(**{f"score_{head}": mean_scores}) 

369 out = out[np.isfinite(mean_scores)] 

370 out.to_csv(run_dir / "scores.csv", index=False) 

371 per_seed = [rank_ic_from_arrays(scores[np.isfinite(scores)], y[np.isfinite(scores)], dates[np.isfinite(scores)])["mean_ic"] for scores in seed_scores.values()] 

372 metrics = {"oof_ic_mean": float(np.mean(per_seed)) if per_seed else None, "oof_ic_seed_std": float(np.std(per_seed)) if len(per_seed) > 1 else None, 

373 "per_seed_ic": dict(zip([str(seed) for seed in seed_scores], per_seed, strict=False)), "folds": fold_metrics} 

374 pins = {path.name: sha256_file(path) for path in sorted(run_dir.glob("*")) if path.suffix in {".pt", ".json", ".csv", ".npy"} and path.name != "run.json"} 

375 record = run_registry.write_run(run_dir, { 

376 "status": "finished", "metrics": metrics, "trials_n": ledger_count(lab_dir, project_ledger), "duration_s": round(time.time() - started, 1), 

377 "pins": pins, "environment": {"python": platform.python_version(), "numpy": np.__version__, "pandas": pd.__version__, 

378 "torch": sys.modules["torch"].__version__ if "torch" in sys.modules else None}, 

379 }) 

380 run_resume.mark_done(run_dir, "report", None) 

381 run_resume.update_record(run_dir, finished=True) 

382 return {"id": run_dir.name, **record}