Coverage for scripts/lowmem_proof.py: 100%

79 statements  

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

1"""Proof that the stack trains on a small machine (V6.6.10): a synthetic dataset the size of the real one, the multitask and sequence 

2trainers under `--memory-profile low`, and each one's measured peak memory against a budget. 

3 

4 python scripts/lowmem_proof.py # 280k rows x 254 columns, one epoch each, budget 2.6 GB 

5 python scripts/lowmem_proof.py --rows 2000 --budget-gb 2.6 

6 

7CI's `lowmem-proof` job runs it on a free runner; a peak above the budget, or a trainer that fails, exits 1. The data is random: this 

8proves memory, not skill. Nothing outside `--work` and `ml/versions/lowmem_proof_*` is written, and those versions are removed after. 

9""" 

10 

11from __future__ import annotations 

12 

13import argparse 

14import json 

15import shutil 

16import subprocess 

17import sys 

18import tempfile 

19from collections.abc import Callable, Sequence 

20from pathlib import Path 

21 

22import numpy as np 

23 

24ROOT = Path(__file__).resolve().parents[1] 

25TARGETS = ("target_direction", "target_return_1d", "target_volatility_next_day", "target_direction_5d", "target_direction_20d", "target_rank_5d", "target_rank_20d", 

26 "target_sector_neutral_rank_20d", "target_residual_rank_5d", "target_residual_rank_20d", "target_beta_neutral_rank_20d", "target_return_5d", "target_return_20d") 

27STAGES = ("multitask", "sequence") 

28 

29 

30def write_dataset(path: Path, *, rows: int, features: int, columns: int, tickers: int, seed: int = 0) -> list[str]: 

31 """Writes the CSV one date at a time (never the whole frame) and returns the model input names. Splits by date: 62% train, 

32 15% validation, 15% backtest, the rest holdout.""" 

33 import pandas as pd 

34 

35 rng = np.random.default_rng(seed) 

36 names = [f"f{i:03d}" for i in range(features)] 

37 fillers = [f"x{i:03d}" for i in range(max(0, columns - features - len(TARGETS) - 5))] 

38 dates = max(2, rows // tickers) 

39 ticker_names = [f"T{i:03d}" for i in range(tickers)] 

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

41 for day in range(dates): 

42 fraction = day / dates 

43 split = "train" if fraction < 0.62 else "validation" if fraction < 0.77 else "backtest" if fraction < 0.92 else "holdout" 

44 block = {"date": str(np.datetime64("2014-01-01") + np.timedelta64(day, "D")), "ticker": ticker_names, "split": split, "training_eligible": True, "security_type": "equity"} 

45 block.update({name: rng.normal(size=tickers).astype(np.float32) for name in [*names, *fillers]}) 

46 ranks = rng.permutation(tickers) / max(tickers - 1, 1) 

47 for target in TARGETS: 

48 block[target] = (rng.random(tickers) > 0.5).astype(float) if "direction" in target else (ranks if "rank" in target else rng.normal(0, 0.02, tickers)) 

49 pd.DataFrame(block).to_csv(path, mode="a", header=day == 0, index=False) 

50 return names 

51 

52 

53def write_config(path: Path, *, epochs: int) -> None: 

54 config = json.loads((ROOT / "config.json").read_text(encoding="utf-8")) 

55 retraining = config["phase_v2"]["retraining"] 

56 for block in ("multitask_training", "sequence_training"): 

57 retraining[block].update({"epochs": epochs, "patience": epochs, "min_best_epoch": 1}) 

58 retraining["multitask_training"]["swa"] = {"enabled": False} 

59 retraining["sequence_training"]["swa"] = {"enabled": False} 

60 config["phase1"]["features"]["cross_sectional_inputs"] = {"enabled": False} 

61 config["phase1"]["target"]["ranking"]["net_performance"] = {"enabled": False} 

62 config["phase1"]["target"]["ranking"]["purged_cv"] = {"enabled": False} 

63 path.write_text(json.dumps(config), encoding="utf-8") 

64 

65 

66def stage_command(stage: str, *, work: Path, version: str, python: str = sys.executable) -> list[str]: 

67 return [python, str(ROOT / f"train_{stage}.py"), "--version-id", version, "--config-path", str(work / "config.json"), "--dataset-path", str(work / "dataset.csv"), 

68 "--feature-schema-path", str(work / "feature_schema.json"), "--memory-profile", "low", "--log-peak-memory", str(work / "peaks.jsonl")] 

69 

70 

71def verdict(peaks: Sequence[dict], codes: dict[str, int], budget_gb: float) -> dict: 

72 """Every stage ran (exit 0), wrote its peak, and stayed within the budget; a peak that can't be read fails rather than passes.""" 

73 by_stage = {row["stage"]: row.get("peak_gb") for row in peaks} 

74 failed = {stage: f"exit {code}" for stage, code in codes.items() if code != 0} 

75 for stage in codes: 

76 peak = by_stage.get(stage) 

77 if stage not in failed and (peak is None or peak > budget_gb): 

78 failed[stage] = "no peak recorded" if peak is None else f"peak {peak} GB > {budget_gb} GB" 

79 return {"ok": not failed, "budget_gb": budget_gb, "peaks_gb": by_stage, "failed": failed} 

80 

81 

82def main(argv: list[str] | None = None, *, runner: Callable = subprocess.run) -> int: 

83 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) 

84 parser.add_argument("--rows", type=int, default=280_000) 

85 parser.add_argument("--features", type=int, default=66) 

86 parser.add_argument("--columns", type=int, default=254) 

87 parser.add_argument("--tickers", type=int, default=104) 

88 parser.add_argument("--epochs", type=int, default=1) 

89 parser.add_argument("--budget-gb", type=float, default=2.6) 

90 parser.add_argument("--work", default=None, help="working folder (default: a temporary one, removed after)") 

91 args = parser.parse_args(argv) 

92 work = Path(args.work) if args.work else Path(tempfile.mkdtemp(prefix="aq_lowmem_")) 

93 version = f"lowmem_proof_{work.name}" 

94 try: 

95 names = write_dataset(work / "dataset.csv", rows=args.rows, features=args.features, columns=args.columns, tickers=args.tickers) 

96 (work / "feature_schema.json").write_text(json.dumps({"model_input_names": names, "feature_names": names, "scaled_feature_names": names}), encoding="utf-8") 

97 write_config(work / "config.json", epochs=args.epochs) 

98 codes = {stage: runner(stage_command(stage, work=work, version=version), cwd=str(ROOT), check=False).returncode for stage in STAGES} 

99 peaks_path = work / "peaks.jsonl" 

100 peaks = [json.loads(line) for line in peaks_path.read_text(encoding="utf-8").splitlines()] if peaks_path.exists() else [] 

101 result = verdict(peaks, codes, args.budget_gb) 

102 finally: 

103 shutil.rmtree(ROOT / "ml" / "versions" / version, ignore_errors=True) 

104 if not args.work: 

105 shutil.rmtree(work, ignore_errors=True) 

106 print(json.dumps(result, indent=1)) 

107 return 0 if result["ok"] else 1 

108 

109 

110if __name__ == "__main__": 

111 raise SystemExit(main())