Coverage for scripts/prepare_v610_candidates.py: 100%

91 statements  

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

1"""Assemble the R-MODEL9 candidates for scripts/v610_research.py (V6.1.0). 

2 

3From scripts/model_candidate_research.py's `model_ic.json` this writes, for every candidate: 

4- a model directory the as-live harness can score (`ml/versions/v610_cand_<name>/`: the first member's exports, schemas 

5 and training metrics, `model_weights.json` for the legacy signal's threshold, and `multitask_ensemble/` / 

6 `sequence_ensemble/` with every member's export - `phase_v2.model_ensemble` reads them as main.py will), 

7- R-HEAD for the decision heads (`rank_signal.heads` with a positive weight): a head passes when at least half of the 

8 candidate's members rate it `promotable` or `watchlist` on their backtest promotion gate (the installed models keep 

9 the owner's 2026-10-13 watchlist decision for their rank heads, Problems.md #162), 

10- the heads that pass R-HEAD on the model of each kind (R-HEAD2's H1 candidates), 

11- the inference latency ratio against the installed single models (the members' batched forward passes on the same 

12 rows; R-MODEL9 clause 5), 

13- whether R-MODEL9's IC clauses pass (only those candidates get book scores and a legacy-probability file). 

14 

15 python scripts/prepare_v610_candidates.py --model-ic ml/evaluation/v610/model_ic.json --dataset ml/datasets/validation_dataset.csv 

16 [--out ml/evaluation/v610/candidates.json] [--rule r-model10 --prefix v620_cand_] 

17 

18V6.2.0: `--rule r-model10` applies R-MODEL10's IC clauses (scripts/v620_research.model10_checks: the resampled-ensemble 

19yardstick from model_candidate_research --bootstrap) instead of R-MODEL9's; `--prefix` names the candidate directories. 

20""" 

21 

22from __future__ import annotations 

23 

24import argparse 

25import json 

26import shutil 

27import sys 

28import time 

29from pathlib import Path 

30 

31ROOT_DIR = Path(__file__).resolve().parents[1] 

32sys.path.insert(0, str(ROOT_DIR)) 

33sys.path.insert(0, str(Path(__file__).resolve().parent)) 

34 

35PASSING = {"promotable", "watchlist"} 

36OWNER_WATCHLIST_HEADS = {"rank_5d", "rank_20d", "residual_rank_5d", "residual_rank_20d"} 

37RANK_HEADS = ("rank_5d", "rank_20d", "sector_neutral_rank_20d", "residual_rank_5d", "residual_rank_20d") 

38FILES = { 

39 "multitask": ("multitask_model.json", "multitask_feature_schema.json", "multitask_training_metrics.json"), 

40 "sequence": ("sequence_model.json", "sequence_feature_schema.json", "sequence_training_metrics.json"), 

41} 

42 

43 

44def head_status(member_dirs: list[Path], kind: str, head: str) -> bool: 

45 statuses = [] 

46 for directory in member_dirs: 

47 path = directory / FILES[kind][2] 

48 metrics = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {} 

49 quality = (metrics.get("backtest", {}) or {}).get(f"{head}_ranking_quality") or {} 

50 statuses.append(quality.get("quality_status") in PASSING) 

51 return bool(statuses) and sum(statuses) * 2 >= len(statuses) 

52 

53 

54def build_candidate_dir(name: str, members: dict[str, list[str]], prefix: str = "v610_cand_") -> Path: 

55 target = ROOT_DIR / "ml" / "versions" / f"{prefix}{name}" 

56 if target.exists(): 

57 shutil.rmtree(target) 

58 target.mkdir(parents=True) 

59 shutil.copy2(ROOT_DIR / "ml" / "model_weights.json", target / "model_weights.json") 

60 for kind, dirs in members.items(): 

61 first = ROOT_DIR / dirs[0] 

62 for filename in FILES[kind]: 

63 if (first / filename).exists(): 

64 shutil.copy2(first / filename, target / filename) 

65 ensemble = target / f"{kind}_ensemble" 

66 ensemble.mkdir() 

67 for index, directory in enumerate(dirs): 

68 shutil.copy2(ROOT_DIR / directory / FILES[kind][0], ensemble / f"member_{index:02d}.json") 

69 return target 

70 

71 

72def latency_ratio(members: dict[str, list[str]], frame, window: int) -> float: 

73 """Batched forward-pass time of the members against the installed single models on the same rows.""" 

74 from evaluation.model_predictions import predict_heads_ensemble 

75 

76 def timed(kind: str, dirs: list[Path]) -> float: 

77 schema = json.loads((dirs[0] / FILES[kind][1]).read_text(encoding="utf-8")) 

78 exports = [json.loads((directory / FILES[kind][0]).read_text(encoding="utf-8")) for directory in dirs] 

79 started = time.perf_counter() 

80 predict_heads_ensemble(frame, exports, schema["model_input_names"], ["rank_20d"], model_kind=kind, 

81 sequence_feature_schema=schema if kind == "sequence" else None, configured_window_size=window, 

82 batched=True) 

83 return time.perf_counter() - started 

84 

85 ml = ROOT_DIR / "ml" 

86 base = sum(timed(kind, [ml]) for kind in members) 

87 candidate = sum(timed(kind, [ROOT_DIR / item for item in dirs]) for kind, dirs in members.items()) 

88 return candidate / base if base > 0 else 1.0 

89 

90 

91def main() -> int: 

92 import pandas as pd 

93 from v610_research import model_ic_checks 

94 

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

96 parser.add_argument("--model-ic", default=str(ROOT_DIR / "ml" / "evaluation" / "v610" / "model_ic.json")) 

97 parser.add_argument("--dataset", default=str(ROOT_DIR / "ml" / "datasets" / "validation_dataset.csv")) 

98 parser.add_argument("--out", default=str(ROOT_DIR / "ml" / "evaluation" / "v610" / "candidates.json")) 

99 parser.add_argument("--rule", choices=("r-model9", "r-model10"), default="r-model9") 

100 parser.add_argument("--prefix", default="v610_cand_") 

101 args = parser.parse_args() 

102 config = json.loads((ROOT_DIR / "config.json").read_text(encoding="utf-8")) 

103 model_ic = json.loads(Path(args.model_ic).read_text(encoding="utf-8")) 

104 window = int(config.get("phase_v2", {}).get("sequence_model", {}).get("window_size", 30)) 

105 decision_heads = [head for head, weight in config["phase_v2"]["rank_signal"]["heads"].items() if weight > 0] 

106 sample = pd.read_csv(args.dataset, nrows=3000) 

107 out: dict = {} 

108 for name, entry in model_ic["candidates"].items(): 

109 members = entry["members"] 

110 if name == "installed": 

111 passing = sorted(OWNER_WATCHLIST_HEADS | {h for h in RANK_HEADS if head_status([ROOT_DIR / "ml"], "multitask", h)}) 

112 out[name] = {"ml_dir": None, "ensemble": False, "passing_heads": passing, "decision_heads_pass_r_head": True} 

113 continue 

114 member_dirs = {kind: [ROOT_DIR / item for item in dirs] for kind, dirs in members.items()} 

115 passing = sorted({ 

116 head for head in RANK_HEADS if any(head_status(dirs, kind, head) for kind, dirs in member_dirs.items()) 

117 }) 

118 if args.rule == "r-model10": 

119 from v620_research import model10_checks 

120 

121 ic = model10_checks(model_ic, name) 

122 else: 

123 ic = model_ic_checks(model_ic, name) # every retrained candidate, the control's seed ensemble included, vs installed 

124 spec = { 

125 "members": members, "passing_heads": passing, 

126 "decision_heads_pass_r_head": all(head in passing for head in decision_heads), 

127 "ic_checks": ic, "ic_pass": bool(ic) and all(value for key, value in ic.items() if key != "yardstick"), 

128 } 

129 if spec["ic_pass"]: 

130 spec["ml_dir"] = str(build_candidate_dir(name, members, args.prefix).relative_to(ROOT_DIR)).replace("\\", "/") 

131 spec["ensemble"] = any(len(dirs) > 1 for dirs in members.values()) 

132 spec["latency_ratio"] = latency_ratio(members, sample, window) 

133 out[name] = spec 

134 print(name, json.dumps({k: v for k, v in spec.items() if k != "members"}), flush=True) 

135 Path(args.out).parent.mkdir(parents=True, exist_ok=True) 

136 Path(args.out).write_text(json.dumps(out, indent=1), encoding="utf-8") 

137 print(f"written {args.out}") 

138 return 0 

139 

140 

141if __name__ == "__main__": 

142 raise SystemExit(main())