Coverage for train_gating.py: 100%
228 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"""Offline trainer for the learned gating model (real weights for
2moe/gating.py's blend, replacing/augmenting the hardcoded
3quality*performance*regime_alignment scoring).
5Separate script from train.py: trains a *second-stage* model over the
6outputs of the already-trained baseline+expert models, not over raw OHLCV
7features. Free to use torch/pandas/numpy, unlike moe/gating.py's pure-Python
8runtime path: this script never runs inside the Lean container, only as a
9retraining-pipeline subprocess (see retraining/orchestrator.py::train_gating())
10or a manual/`aq train --gating-only` CLI call.
12Train/validation/backtest split discipline (avoids stacking circularity):
13baseline+experts are already fit on the `train` split, so replaying `train`
14rows here would just teach this model to correct their training-set
15overfit. Instead this trainer replays the `validation` split (held out from
16baseline/expert fitting, the right size and held-out status to become this
17model's *own* training data) through the exported baseline+expert models,
18building the exact 26-dim feature vector moe/gating.py::build_gating_model_features()
19would have produced live, paired with the known target_direction label.
20Those replayed rows are further shuffle-split into a fit/early-stop pair
21(this trainer's own internal early stopping, distinct from the dataset's
22`split` column) since `validation` rows now serve as this model's training
23data and no longer double as a held-out check. The `backtest` split is
24never touched by any fitting anywhere in the pipeline and is replayed only
25once, at the end, purely to report a trustworthy number.
27Known asymmetry, inherited from the existing system, not introduced here:
28train.py's `--candidate` path only versions the baseline model, never
29re-trains experts per-candidate - so this trainer always reads expert
30exports from the *active* ml/expert_models/, even when training a gating
31blend for a candidate baseline version-id.
33Model is deliberately restricted to relu/layernorm (never gelu/silu/
34batchnorm1d) since inference/exported_model.py::run_exported_model() -
35the same interpreter used both here for replay and by moe/gating.py at
36runtime - cannot interpret those layer types.
38Usage:
39 python train_gating.py --version-id <uuid> [--config-path config.json] [--dataset-path ml/datasets/full_dataset.csv]
41Writes ml/versions/<version_id>/gating_model.json, gating_feature_schema.json
42and gating_training_metrics.json. Exits 0 (not an error) when there isn't
43enough data or no upstream models are available yet - "skipped" must never
44look like "failed" to the caller.
45"""
47from __future__ import annotations
49import argparse
50import copy
51import json
52import logging
53import sys
54from datetime import datetime, timezone
55from pathlib import Path
57import pandas as pd
58import torch
59import torch.nn as nn
60from torch.utils.data import DataLoader, TensorDataset
62from evaluation.dataset_io import read_dataset_rows
63from inference import run_exported_model
64from moe.gating import EXPERT_NAMES, GATING_MODEL_FEATURE_KEYS, build_gating_decision, build_gating_model_features
65from regime import build_market_regime_vector
66from retraining.slicing import PROFILES, log_peak, memory_profile
67from train import (
68 AetherNet,
69 compute_binary_metrics,
70 export_architecture,
71 export_state_dict,
72 find_optimal_threshold,
73 frame_to_tensors,
74 is_new_best_epoch,
75 set_seed,
76)
78LOGGER = logging.getLogger("aether_quant.train_gating")
79ROOT = Path(__file__).resolve().parent
80ML_DIR = ROOT / "ml"
81CONFIG_PATH = ROOT / "config.json"
82DATASET_PATH = ML_DIR / "datasets" / "full_dataset.csv"
83FEATURE_SCHEMA_PATH = ML_DIR / "feature_schema.json"
84EXPERT_TRAINING_METRICS_PATH = ML_DIR / "expert_training_metrics.json"
85EXPERT_MODEL_DIR = ML_DIR / "expert_models"
86ACTIVE_BASELINE_MODEL_PATH = ML_DIR / "model_weights.json"
89def parse_args() -> argparse.Namespace:
90 parser = argparse.ArgumentParser(description="Aether Quant learned-gating trainer")
91 parser.add_argument("--version-id", type=str, required=True, help="Candidate model_version_id (UUID)")
92 parser.add_argument("--config-path", type=str, default=str(CONFIG_PATH))
93 parser.add_argument("--dataset-path", type=str, default=str(DATASET_PATH))
94 parser.add_argument("--memory-profile", choices=sorted(PROFILES), default="standard", help="standard (default) or low: read only the validation and backtest rows")
95 parser.add_argument("--log-peak-memory", type=str, default=None, help="append this run's peak memory to this JSONL file")
96 return parser.parse_args()
99def load_gating_training_config(config_path: Path = CONFIG_PATH) -> dict:
100 with Path(config_path).open("r", encoding="utf-8") as f:
101 config = json.load(f)
102 return config.get("phase_v2", {}).get("retraining", {}).get("gating_training", {})
105def gating_candidate_output_paths(version_id: str) -> dict[str, Path]:
106 """Own local helper mirroring train_topology.py's
107 topology_candidate_output_paths(), kept independent of train.py's own
108 candidate_output_paths() since the two write disjoint filenames."""
109 version_dir = ML_DIR / "versions" / version_id
110 return {
111 "version_dir": version_dir,
112 "gating_model": version_dir / "gating_model.json",
113 "gating_feature_schema": version_dir / "gating_feature_schema.json",
114 "gating_training_metrics": version_dir / "gating_training_metrics.json",
115 }
118def load_baseline_export(version_id: str) -> dict | None:
119 """Prefers this candidate's own versioned baseline export (written by
120 `python train.py --candidate --version-id <id>`) if present; falls back
121 to the active baseline export otherwise."""
122 versioned_path = ML_DIR / "versions" / version_id / "model_weights.json"
123 for path in (versioned_path, ACTIVE_BASELINE_MODEL_PATH):
124 if path.exists():
125 with path.open("r", encoding="utf-8") as f:
126 return json.load(f)
127 return None
130def load_expert_exports() -> dict[str, dict]:
131 exports: dict[str, dict] = {}
132 for expert_name in EXPERT_NAMES:
133 path = EXPERT_MODEL_DIR / expert_name / "model_weights.json"
134 if path.exists():
135 with path.open("r", encoding="utf-8") as f:
136 exports[expert_name] = json.load(f)
137 return exports
140def build_gating_training_rows(
141 frame: pd.DataFrame,
142 feature_schema: dict,
143 expert_training_metrics: dict,
144 baseline_export: dict | None,
145 expert_exports: dict[str, dict],
146) -> tuple[list[list[float]], list[float]]:
147 """Replays each dataset row through the exported baseline+expert models
148 (run_exported_model(), the same interpreter moe/gating.py uses at
149 runtime) to reconstruct the exact feature vector
150 build_gating_model_features() would have produced live, paired with the
151 already-known target_direction label.
153 average_correlation (development/Problems.md #71, Phase 4.12) is now
154 this row's real topology_correlation_strength, read straight out of
155 raw_features (feature_schema["feature_names"] already includes it,
156 the same real value train.py::_encode_regime_row() now uses) -
157 train.py's dataset already has this column populated by
158 build_topology_features_by_date() before this trainer ever reads a
159 row, so no additional plumbing was needed here beyond reading the key.
160 portfolio_drawdown=0.0 remains an honest, documented simplification -
161 no live account-drawdown state exists at offline dataset-build time.
162 The two regime keys _regime_alignment() actually branches on
163 (trend_regime, volatility_regime) are unaffected by either default."""
164 model_input_names = feature_schema["model_input_names"]
165 feature_names = feature_schema["feature_names"]
167 rows: list[list[float]] = []
168 labels: list[float] = []
170 for _, row in frame.iterrows():
171 model_inputs = [float(row[name]) for name in model_input_names]
172 raw_features = {name: float(row[name]) for name in feature_names}
174 expert_probabilities: dict[str, float | None] = {}
175 for expert_name in EXPERT_NAMES:
176 export = expert_exports.get(expert_name)
177 if export is None:
178 expert_probabilities[expert_name] = None
179 continue
180 try:
181 expert_probabilities[expert_name] = run_exported_model(export, model_inputs)
182 except Exception:
183 expert_probabilities[expert_name] = None
185 baseline_probability_up = None
186 if baseline_export is not None:
187 try:
188 baseline_probability_up = run_exported_model(baseline_export, model_inputs)
189 except Exception:
190 baseline_probability_up = None
192 regime = build_market_regime_vector(
193 raw_features,
194 portfolio_drawdown=0.0,
195 average_correlation=raw_features.get("topology_correlation_strength", 0.0),
196 ).to_dict()
198 decision = build_gating_decision(
199 regime=regime,
200 expert_training_metrics=expert_training_metrics,
201 expert_probabilities=expert_probabilities,
202 baseline_probability_up=baseline_probability_up,
203 )
204 feature_vector = build_gating_model_features(regime, baseline_probability_up, decision.weights)
205 rows.append(feature_vector)
206 labels.append(float(row["target_direction"]))
208 return rows, labels
211def rows_to_frame(rows: list[list[float]], labels: list[float]) -> pd.DataFrame:
212 frame = pd.DataFrame(rows, columns=list(GATING_MODEL_FEATURE_KEYS))
213 frame["target_direction"] = labels
214 return frame
217def shuffle_split(frame: pd.DataFrame, holdout_fraction: float, seed: int) -> tuple[pd.DataFrame, pd.DataFrame]:
218 """Internal fit/early-stop split of the replayed `validation`-split
219 rows - distinct from the dataset's own `split` column, needed because
220 those rows are this model's training data here, not a held-out check."""
221 shuffled = frame.sample(frac=1.0, random_state=seed).reset_index(drop=True)
222 holdout_size = max(1, int(len(shuffled) * holdout_fraction))
223 holdout = shuffled.iloc[:holdout_size].reset_index(drop=True)
224 fit = shuffled.iloc[holdout_size:].reset_index(drop=True)
225 return fit, holdout
228def main() -> int:
229 logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
230 args = parse_args()
232 try:
233 training_config = load_gating_training_config(Path(args.config_path))
234 min_train_rows = int(training_config.get("min_train_rows", 100))
235 min_backtest_rows = int(training_config.get("min_backtest_rows", 20))
236 holdout_fraction = float(training_config.get("early_stop_holdout_fraction", 0.15))
237 hidden_layers = list(training_config.get("hidden_layers", [16]))
238 dropout = float(training_config.get("dropout", 0.2))
239 learning_rate = float(training_config.get("learning_rate", 0.001))
240 weight_decay = float(training_config.get("weight_decay", 0.001))
241 batch_size = int(training_config.get("batch_size", 64))
242 max_epochs = int(training_config.get("epochs", 60))
243 patience = int(training_config.get("patience", 8))
244 decision_threshold = float(training_config.get("decision_threshold", 0.5))
245 threshold_metric = str(training_config.get("optimize_threshold_metric", "mcc"))
246 threshold_min = float(training_config.get("threshold_search_min", 0.35))
247 threshold_max = float(training_config.get("threshold_search_max", 0.65))
248 threshold_steps = int(training_config.get("threshold_search_steps", 61))
249 seed = int(training_config.get("seed", 42))
251 if not FEATURE_SCHEMA_PATH.exists() or not EXPERT_TRAINING_METRICS_PATH.exists():
252 LOGGER.info("train_gating: missing feature schema or expert training metrics - skipping.")
253 return 0
255 with FEATURE_SCHEMA_PATH.open("r", encoding="utf-8") as f:
256 feature_schema = json.load(f)
257 with EXPERT_TRAINING_METRICS_PATH.open("r", encoding="utf-8") as f:
258 expert_training_metrics = json.load(f)
260 expert_exports = load_expert_exports()
261 baseline_export = load_baseline_export(args.version_id)
262 if not expert_exports and baseline_export is None:
263 LOGGER.info("train_gating: no baseline or expert exports available yet - skipping.")
264 return 0
266 dataset_path = Path(args.dataset_path)
267 if not dataset_path.exists():
268 LOGGER.info("train_gating: dataset not found at %s - skipping.", dataset_path)
269 return 0
270 if args.memory_profile == "low":
271 # only the two splits the gate replays, in chunks; the values are a plain read's (V6.6.10)
272 dataset = read_dataset_rows(dataset_path, split=("validation", "backtest"), chunk_rows=memory_profile("low").read_chunk_rows)
273 else:
274 dataset = pd.read_csv(dataset_path)
276 validation_frame = dataset[dataset["split"] == "validation"].reset_index(drop=True)
277 backtest_frame = dataset[dataset["split"] == "backtest"].reset_index(drop=True)
279 if len(validation_frame) < min_train_rows or len(backtest_frame) < min_backtest_rows:
280 LOGGER.info(
281 "train_gating: only %d validation / %d backtest rows (need >= %d / %d) - skipping, not writing artifacts.",
282 len(validation_frame),
283 len(backtest_frame),
284 min_train_rows,
285 min_backtest_rows,
286 )
287 return 0
289 set_seed(seed)
291 LOGGER.info("train_gating: replaying %d validation rows through baseline+experts...", len(validation_frame))
292 train_rows, train_labels = build_gating_training_rows(
293 validation_frame, feature_schema, expert_training_metrics, baseline_export, expert_exports
294 )
295 LOGGER.info("train_gating: replaying %d backtest rows through baseline+experts...", len(backtest_frame))
296 backtest_rows, backtest_labels = build_gating_training_rows(
297 backtest_frame, feature_schema, expert_training_metrics, baseline_export, expert_exports
298 )
300 full_train_frame = rows_to_frame(train_rows, train_labels)
301 backtest_gating_frame = rows_to_frame(backtest_rows, backtest_labels)
302 fit_frame, early_stop_frame = shuffle_split(full_train_frame, holdout_fraction, seed)
304 device = torch.device("cpu")
305 feature_names = list(GATING_MODEL_FEATURE_KEYS)
307 fit_features, fit_targets = frame_to_tensors(fit_frame, feature_names)
308 early_stop_features, early_stop_targets = frame_to_tensors(early_stop_frame, feature_names)
309 early_stop_features = early_stop_features.to(device)
310 early_stop_targets = early_stop_targets.to(device)
312 train_loader = DataLoader(
313 TensorDataset(fit_features, fit_targets),
314 batch_size=batch_size,
315 shuffle=True,
316 )
318 model = AetherNet(
319 input_dim=len(feature_names),
320 hidden_layers=hidden_layers,
321 dropout=dropout,
322 activation="relu",
323 normalization="layernorm",
324 ).to(device)
326 optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate, weight_decay=weight_decay)
327 positive_count = max(float(fit_frame["target_direction"].sum()), 1.0)
328 negative_count = max(float(len(fit_frame) - fit_frame["target_direction"].sum()), 1.0)
329 pos_weight = torch.tensor(negative_count / positive_count, dtype=torch.float32, device=device)
330 criterion = nn.BCEWithLogitsLoss(pos_weight=pos_weight)
332 best_state = None
333 best_epoch = 0
334 best_early_stop_balanced_accuracy = float("-inf")
335 epochs_without_improvement = 0
336 history: list[dict] = []
337 min_best_epoch = int(training_config.get("min_best_epoch", 3))
339 for epoch in range(1, max_epochs + 1):
340 model.train()
341 running_loss = 0.0
342 sample_count = 0
343 for batch_features, batch_targets in train_loader:
344 batch_features = batch_features.to(device)
345 batch_targets = batch_targets.to(device)
347 optimizer.zero_grad()
348 logits = model(batch_features)
349 loss = criterion(logits, batch_targets)
350 loss.backward()
351 optimizer.step()
353 running_loss += float(loss.item()) * len(batch_targets)
354 sample_count += len(batch_targets)
356 model.eval()
357 with torch.no_grad():
358 early_stop_logits = model(early_stop_features)
359 early_stop_metrics = compute_binary_metrics(early_stop_logits, early_stop_targets, criterion, decision_threshold)
360 history.append(
361 {
362 "epoch": epoch,
363 "train_loss": running_loss / max(sample_count, 1),
364 "early_stop_loss": early_stop_metrics["loss"],
365 "early_stop_balanced_accuracy": early_stop_metrics["balanced_accuracy"],
366 }
367 )
369 # See train.py::is_new_best_epoch()'s docstring - monitors
370 # skill (balanced-accuracy), not the loss already computed
371 # above into early_stop_metrics (development/Problems.md).
372 if is_new_best_epoch(
373 early_stop_metrics["balanced_accuracy"], best_early_stop_balanced_accuracy, epoch, min_best_epoch
374 ):
375 best_early_stop_balanced_accuracy = early_stop_metrics["balanced_accuracy"]
376 best_epoch = epoch
377 best_state = copy.deepcopy(model.state_dict())
378 epochs_without_improvement = 0
379 else:
380 epochs_without_improvement += 1
382 if epoch >= min_best_epoch and epochs_without_improvement >= patience:
383 break
385 if best_state is None:
386 best_state = copy.deepcopy(model.state_dict())
387 best_epoch = len(history)
389 model.load_state_dict(best_state)
390 model.eval()
391 with torch.no_grad():
392 early_stop_logits = model(early_stop_features)
393 tuned_threshold, tuned_early_stop_metrics = find_optimal_threshold(
394 early_stop_logits,
395 early_stop_targets,
396 criterion,
397 threshold_metric,
398 threshold_min,
399 threshold_max,
400 threshold_steps,
401 )
403 backtest_features, backtest_targets = frame_to_tensors(backtest_gating_frame, feature_names)
404 backtest_features = backtest_features.to(device)
405 backtest_targets = backtest_targets.to(device)
406 with torch.no_grad():
407 backtest_logits = model(backtest_features)
408 backtest_metrics = compute_binary_metrics(backtest_logits, backtest_targets, criterion, tuned_threshold)
410 trained_at = datetime.now(timezone.utc).isoformat()
411 model_payload = {
412 "version_id": args.version_id,
413 "trained_at": trained_at,
414 "export": {
415 "architecture": export_architecture(model),
416 "state_dict": export_state_dict(model),
417 },
418 }
419 feature_schema_payload = {"feature_keys": feature_names}
420 training_metrics_payload = {
421 "project": "aether_quant",
422 "phase": "gating_network_learned_weights",
423 "version_id": args.version_id,
424 "trained_at": trained_at,
425 "row_counts": {
426 "gating_train_fit": int(len(fit_frame)),
427 "gating_train_early_stop": int(len(early_stop_frame)),
428 "backtest": int(len(backtest_gating_frame)),
429 },
430 "best_epoch": best_epoch,
431 "epochs_ran": len(history),
432 "threshold_optimization": {
433 "metric": threshold_metric,
434 "default_threshold": decision_threshold,
435 "selected_threshold": tuned_threshold,
436 "selected_early_stop_metrics": tuned_early_stop_metrics,
437 },
438 "backtest": backtest_metrics,
439 "history": history,
440 }
442 paths = gating_candidate_output_paths(args.version_id)
443 paths["version_dir"].mkdir(parents=True, exist_ok=True)
444 paths["gating_model"].write_text(json.dumps(model_payload, indent=2), encoding="utf-8")
445 paths["gating_feature_schema"].write_text(json.dumps(feature_schema_payload, indent=2), encoding="utf-8")
446 paths["gating_training_metrics"].write_text(json.dumps(training_metrics_payload, indent=2), encoding="utf-8")
447 if args.log_peak_memory:
448 log_peak(Path(args.log_peak_memory), "gating", profile=args.memory_profile)
450 LOGGER.info(
451 "train_gating: wrote gating artifacts for version %s (backtest balanced_accuracy=%.4f, mcc=%.4f).",
452 args.version_id,
453 backtest_metrics["balanced_accuracy"],
454 backtest_metrics["mcc"],
455 )
456 return 0
457 except Exception as exc: # never let an unexpected failure look ambiguous to the caller
458 LOGGER.error("train_gating: unexpected failure - %s", exc)
459 return 1
462if __name__ == "__main__":
463 sys.exit(main())