Coverage for train_sequence.py: 100%
373 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 Phase 2 sequence-encoder multitask model:
2direction + return magnitude + volatility + longer-horizon direction
3(5d/20d) + cross-sectional rank (5d/20d) predicted from a causal TCN trunk
4over a rolling window of bars, instead of Phase 1's flat-MLP trunk
5(AetherNetMultiTaskHorizons/train_multitask.py) collapsing each bar into
6one row.
8This is the "genuinely new temporal structure" step the original root-
9cause investigation called out as still missing after Phase 1 shipped
10(direction+magnitude+volatility prediction, but still zero temporal
11structure in the trunk itself). See train.py::AetherNetSequenceMultiTask's
12docstring for why a causal TCN was chosen over a Transformer encoder block
13for this first real sequence model (interpreter support for attention -
14inference/exported_model.py::_multihead_attention() - already exists and
15is tested, just not wired to a trained export yet).
17Same convention as train_multitask.py: reads the already-built active
18dataset (ml/datasets/full_dataset.csv) and feature_schema.json's
19model_input_names, needs no new feature engineering - train.py::
20build_sequence_tensor_dataset() only windows over the same model_input
21vector the flat multitask model already consumes, using each row's own
22trailing history within its ticker. Shares train.py's horizon-head
23machinery (HORIZON_HEAD_SPECS/resolve_horizon_head_config()/
24compute_combined_multitask_loss()/find_optimal_masked_threshold()) with
25train_multitask.py - both trainers' Horizons model variants expose
26identically-named heads, so the loss/threshold/config logic is
27genuinely shared, not duplicated (see train.py's docstrings for why this
28codebase's usual "new sibling function" convention doesn't apply here).
30Usage:
31 python train_sequence.py --version-id <uuid> [--config-path config.json] [--dataset-path ml/datasets/full_dataset.csv]
33Writes ml/versions/<version_id>/sequence_model.json, sequence_feature_schema.json
34and sequence_training_metrics.json. Exits 0 (not an error) when there isn't
35enough data yet - "skipped" must never look like "failed" to the caller,
36mirroring train_multitask.py/train_gating.py/train_topology.py.
37"""
39from __future__ import annotations
41import argparse
42import copy
43import gc
44import json
45import logging
46import os
47import random
48import sys
49from datetime import datetime, timezone
50from pathlib import Path
52import numpy as np
53import pandas as pd
54import torch
55import torch.nn as nn
57from performance_probe import install_sigterm_witness
58from retraining.slicing import PROFILES, gather_windows, log_peak, memory_profile, read_csv_float32, sequence_window_index
59from train import (
60 CONTEXT_OBJECTIVES,
61 HORIZON_HEAD_SPECS,
62 RANKING_OBJECTIVES,
63 AetherNetSequenceMultiTaskHorizons,
64 add_rank_label_noise,
65 assess_net_performance_quality,
66 assess_ranking_quality_from_predictions,
67 assess_regression_quality,
68 build_cross_sectional_date_batches,
69 build_date_group_ids,
70 build_lr_scheduler,
71 build_optimizer,
72 build_sequence_tensor_dataset,
73 compute_binary_metrics,
74 compute_combined_multitask_loss,
75 compute_gate_friendliness_weight_by_date,
76 compute_masked_binary_metrics,
77 compute_masked_regression_metrics,
78 compute_purged_cv_rank_ic_diagnostic,
79 compute_rank_ic,
80 compute_regression_metrics,
81 export_sequence_multitask_horizons_architecture,
82 export_state_dict,
83 find_optimal_masked_threshold,
84 find_optimal_threshold,
85 is_new_best_epoch,
86 load_sector_mapping,
87 resolve_horizon_head_config,
88 row_context_targets,
89 run_net_performance_simulation,
90 set_seed,
91 smoothed_metric,
92 swa_accumulate,
93 swa_finalize,
94)
96LOGGER = logging.getLogger("aether_quant.train_sequence")
97ROOT = Path(__file__).resolve().parent
98ML_DIR = ROOT / "ml"
99CONFIG_PATH = ROOT / "config.json"
100DATASET_PATH = ML_DIR / "datasets" / "full_dataset.csv"
101FEATURE_SCHEMA_PATH = ML_DIR / "feature_schema.json"
104def parse_args() -> argparse.Namespace:
105 parser = argparse.ArgumentParser(description="Aether Quant Phase 2 sequence-encoder trainer")
106 parser.add_argument("--version-id", type=str, required=True, help="Candidate model_version_id (UUID)")
107 parser.add_argument("--config-path", type=str, default=str(CONFIG_PATH))
108 parser.add_argument("--dataset-path", type=str, default=str(DATASET_PATH))
109 # V5.1 Phase 4 (item 4) - see train_multitask.py::parse_args()'s
110 # identical flag docstring: needed by train.py::_run_walk_forward()'s
111 # per-window subprocess calls, which have their own schema that does
112 # not match the active ml/feature_schema.json. Defaults to the module
113 # constant - a no-op for every existing caller.
114 parser.add_argument("--feature-schema-path", type=str, default=str(FEATURE_SCHEMA_PATH))
115 # Stage 4 of the rank-pivot roadmap (development/Problems.md#43) - see
116 # train_multitask.py::parse_args()'s identical flag for the full
117 # seed-ensembling workflow (train once per seed, combine backtest
118 # rank_20d predictions afterward with
119 # train.py::aggregate_seed_ensemble_rank_ic()).
120 parser.add_argument("--seed", type=int, default=None, help="Override config.json's seed for this run (seed-ensembling)")
121 # V5.1 Phase 3 (item 1) - one-run A/B override without editing
122 # config.json, same precedent as --seed immediately above and
123 # train_multitask.py's identical flag. None (default) leaves
124 # training_config["ranking_loss"]["objective"] unchanged.
125 parser.add_argument(
126 "--ranking-objective",
127 type=str,
128 default=None,
129 choices=list(RANKING_OBJECTIVES),
130 help="Override config.json's ranking_loss.objective for this run only (A/B testing; V6.6.10 adds R-LOSS1's ic_pearson, ls_sharpe, class_balanced, cost_aware)",
131 )
132 # V6.6.10: `low` gathers each batch's windows from one row matrix instead of a dense per-split array, evaluates in
133 # smaller chunks and checkpoints every epoch, so the stack trains on a 4 GB machine. `standard` is unchanged.
134 parser.add_argument("--memory-profile", choices=sorted(PROFILES), default="standard", help="standard (default) or low: train on a small machine")
135 parser.add_argument("--resume", action="store_true", help="continue from the version's checkpoint.pt (the low profile writes one per epoch)")
136 parser.add_argument("--log-peak-memory", type=str, default=None, help="append this run's peak memory to this JSONL file")
137 return parser.parse_args()
140def load_sequence_training_config(config_path: Path = CONFIG_PATH) -> dict:
141 with Path(config_path).open("r", encoding="utf-8") as f:
142 config = json.load(f)
143 return config.get("phase_v2", {}).get("retraining", {}).get("sequence_training", {})
146def sequence_candidate_output_paths(version_id: str) -> dict[str, Path]:
147 """Own local helper mirroring train_multitask.py's
148 multitask_candidate_output_paths() - kept independent since the two
149 write disjoint filenames."""
150 version_dir = ML_DIR / "versions" / version_id
151 return {
152 "version_dir": version_dir,
153 "sequence_model": version_dir / "sequence_model.json",
154 "sequence_feature_schema": version_dir / "sequence_feature_schema.json",
155 "sequence_training_metrics": version_dir / "sequence_training_metrics.json",
156 }
159def read_dataset_compact(path: Path, chunk_rows: int = 40_000) -> pd.DataFrame:
160 """pd.read_csv() as float32 (V5.8.0): the V5.8.0 dataset has 280k rows x 251 float64 columns (~560 MB, twice that while
161 pandas parses and again for the filtered copy), which with the sequence windows pushed the 8 GB Codespace into the
162 kernel's memory-pressure SIGTERM. The model path converts every feature and target to float32 anyway; dates, tickers
163 and the boolean flags keep their types."""
164 return read_csv_float32(path, chunk_rows=chunk_rows)
167def rng_state(generator: torch.Generator | None) -> dict:
168 """Every random stream a training epoch draws from, so a resumed run continues the interrupted one's draws."""
169 return {
170 "torch": torch.get_rng_state(), "numpy": np.random.get_state(), "python": random.getstate(),
171 "generator": generator.get_state() if generator is not None else None,
172 }
175def restore_rng_state(state: dict, generator: torch.Generator | None) -> None:
176 torch.set_rng_state(state["torch"])
177 np.random.set_state(state["numpy"])
178 random.setstate(state["python"])
179 if generator is not None and state["generator"] is not None:
180 generator.set_state(state["generator"])
183def save_checkpoint(path: Path, state: dict) -> None:
184 """Writes the checkpoint beside its final name and renames it into place: an interrupted save never leaves a torn file to resume from."""
185 path.parent.mkdir(parents=True, exist_ok=True)
186 partial = path.with_suffix(".pt.partial")
187 torch.save(state, partial)
188 os.replace(partial, path)
191class LazySequenceWindows:
192 """One split's sequence windows, gathered when indexed (V6.6.10, the low memory profile). `windows[rows]` is the float32 tensor
193 the dense split tensor holds at those rows (retraining/slicing.py proves the gather equal to build_sequence_tensor_dataset), so
194 the training loop, `forward_in_batches` and the metrics index it exactly as they index a tensor."""
196 def __init__(self, matrix: np.ndarray, index: np.ndarray):
197 self.matrix = matrix
198 self.index = index
200 def __len__(self) -> int:
201 return len(self.index)
203 def __getitem__(self, key) -> torch.Tensor:
204 if isinstance(key, torch.Tensor):
205 key = key.cpu().numpy()
206 return torch.from_numpy(gather_windows(self.matrix, self.index[key]))
208 def to(self, device) -> LazySequenceWindows:
209 return self
212def _split_sequence_tensors(
213 dataset: pd.DataFrame, sequences: np.ndarray | None, split_name: str, *, feature_names: list[str] | None = None,
214 window_size: int | None = None, matrix: np.ndarray | None = None, context: bool = False,
215) -> tuple[torch.Tensor | LazySequenceWindows, dict[str, torch.Tensor], pd.Series]:
216 """Returns (features, targets, dates) for one split - targets is a dict
217 keyed by head name, same shape as train_multitask.py::frame_to_multitask_tensors()'s
218 return, so compute_sequence_multitask_metrics() below can share its
219 structure with train_multitask.py's compute_multitask_metrics().
221 V5.8.0: with `sequences=None` the split's windows are built directly (build_sequence_tensor_dataset(row_mask=...))
222 and wrapped without a copy, so the full-dataset array and its two copies never exist at once."""
223 mask = (dataset["split"] == split_name).to_numpy()
224 if matrix is not None:
225 features = LazySequenceWindows(matrix, sequence_window_index(dataset["ticker"].to_numpy(), window_size, row_mask=mask))
226 else:
227 if sequences is None:
228 split_sequences = build_sequence_tensor_dataset(dataset, feature_names, window_size, row_mask=mask)
229 else:
230 split_sequences = sequences[mask]
231 features = torch.from_numpy(np.ascontiguousarray(split_sequences, dtype=np.float32))
232 split_frame = dataset[mask]
233 targets = {
234 "direction": torch.tensor(split_frame["target_direction"].to_numpy(dtype=np.float32), dtype=torch.float32),
235 "magnitude": torch.tensor(split_frame["target_return_1d"].to_numpy(dtype=np.float32), dtype=torch.float32),
236 "volatility": torch.tensor(
237 split_frame["target_volatility_next_day"].to_numpy(dtype=np.float32), dtype=torch.float32
238 ),
239 }
240 for head_name, (column, _kind, _stride) in HORIZON_HEAD_SPECS.items():
241 targets[head_name] = torch.tensor(split_frame[column].to_numpy(dtype=np.float32), dtype=torch.float32)
242 if context:
243 targets.update(row_context_targets(dataset, np.flatnonzero(mask)))
244 return features, targets, split_frame["date"]
247FORWARD_BATCH_ROWS = 4096
250def forward_in_batches(model: nn.Module, features: torch.Tensor, batch_rows: int | None = None) -> dict[str, torch.Tensor]:
251 """model(features) for a whole split without materialising the whole split's activations (V5.8.0). The final
252 evaluation ran the 170k-row train tensor through the causal-conv stack in one call - several GB of intermediate
253 activations on top of the 3 GB already resident, which the 8 GB Codespace answered with SIGTERM at the end of every
254 attempt. The model is in eval mode there (no dropout, per-row layernorm), so chunking is exact up to float
255 summation order. Returns the same {head: tensor} dict, rows in the original order."""
256 batch_rows = int(batch_rows or FORWARD_BATCH_ROWS)
257 with torch.no_grad():
258 if len(features) <= batch_rows:
259 return model(features[0 : len(features)]) # a slice: a tensor's own view, or a lazy split's gathered windows
260 pieces: dict[str, list[torch.Tensor]] = {}
261 for start in range(0, len(features), batch_rows):
262 for head, value in model(features[start : start + batch_rows]).items():
263 pieces.setdefault(head, []).append(value)
264 return {head: torch.cat(values, dim=0) for head, values in pieces.items()}
267def compute_sequence_multitask_metrics(
268 model: AetherNetSequenceMultiTaskHorizons,
269 features: torch.Tensor,
270 targets: dict[str, torch.Tensor],
271 dates: pd.Series,
272 direction_criterion: nn.Module,
273 threshold: float,
274 head_thresholds: dict[str, float],
275 horizon_head_config: dict,
276 ranking_promotion_config: dict | None = None,
277 net_performance_context: dict | None = None,
278) -> dict:
279 """net_performance_context - see train_multitask.py::compute_multitask_metrics()'s
280 identical docstring (V5.1 Phase 4, items 7/12)."""
281 model.eval()
282 outputs = forward_in_batches(model, features)
283 metrics = {
284 "direction": compute_binary_metrics(outputs["direction"], targets["direction"], direction_criterion, threshold),
285 "magnitude": compute_regression_metrics(outputs["magnitude"], targets["magnitude"]),
286 "volatility": compute_regression_metrics(outputs["volatility"], targets["volatility"]),
287 }
288 for head_name, (_column, kind, stride) in HORIZON_HEAD_SPECS.items():
289 if not horizon_head_config[head_name].get("enabled", True):
290 metrics[head_name] = None
291 continue
292 if kind == "binary":
293 metrics[head_name] = compute_masked_binary_metrics(
294 outputs[head_name], targets[head_name], direction_criterion, head_thresholds.get(head_name, 0.5)
295 )
296 else:
297 metrics[head_name] = compute_masked_regression_metrics(outputs[head_name], targets[head_name])
298 metrics[f"{head_name}_ic"] = compute_rank_ic(outputs[head_name], targets[head_name], dates)
299 metrics[f"{head_name}_ic_non_overlapping"] = compute_rank_ic(
300 outputs[head_name], targets[head_name], dates, non_overlapping_stride=stride
301 )
302 # Phase 2 of the 5/10 -> 9/10 roadmap: the code-enforced
303 # promotion-gate verdict (purged/embargoed CV validation rigor,
304 # bootstrap CI, cross-era stability), only computed for the
305 # BACKTEST split (ranking_promotion_config passed only by that
306 # call site below) - never on train/validation, matching how
307 # assess_regression_quality() above only ever gates on backtest
308 # RMSE/MAE.
309 if ranking_promotion_config is not None:
310 mask = ~torch.isnan(targets[head_name])
311 dates_masked = np.asarray(dates)[mask.detach().cpu().numpy()]
312 metrics[f"{head_name}_ranking_quality"] = assess_ranking_quality_from_predictions(
313 outputs[head_name][mask],
314 targets[head_name][mask],
315 dates_masked,
316 non_overlapping_stride=stride,
317 config=ranking_promotion_config,
318 )
319 if net_performance_context is not None and net_performance_context.get("head") == head_name:
320 raw_frame = net_performance_context["raw_frame"].copy()
321 raw_frame["_predicted_head"] = outputs[head_name].detach().cpu().numpy()
322 net_performance_result = run_net_performance_simulation(
323 raw_frame, "_predicted_head",
324 net_performance_context["net_performance_config"],
325 net_performance_context["sector_by_ticker"],
326 net_performance_context.get("full_config"),
327 )
328 if net_performance_result is not None:
329 metrics[f"{head_name}_net_performance"] = assess_net_performance_quality(
330 net_performance_result["simulation"],
331 net_performance_result["capacity"],
332 net_performance_result["stress"],
333 net_performance_context["full_config"],
334 )
335 return metrics
338def main() -> int:
339 install_sigterm_witness(LOGGER)
340 logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
341 args = parse_args()
342 profile = memory_profile(args.memory_profile)
344 try:
345 training_config = load_sequence_training_config(Path(args.config_path))
346 # Phase 2 of the 5/10 -> 9/10 roadmap: assess_ranking_quality_from_predictions()
347 # needs phase1.target.ranking.promotion_gate, which lives in the
348 # FULL config.json, not the narrow sequence_training sub-dict
349 # load_sequence_training_config() returns - see that function's
350 # docstring for why the promotion gate deliberately isn't
351 # duplicated per-model.
352 full_config = json.loads(Path(args.config_path).read_text(encoding="utf-8"))
353 if not bool(training_config.get("enabled", True)):
354 LOGGER.info("train_sequence: disabled via config - skipping.")
355 return 0
357 min_train_rows = int(training_config.get("min_train_rows", 200))
358 min_validation_rows = int(training_config.get("min_validation_rows", 30))
359 min_backtest_rows = int(training_config.get("min_backtest_rows", 30))
360 window_size = int(training_config.get("window_size", 30))
361 channels = list(training_config.get("channels", [32, 32]))
362 kernel_size = int(training_config.get("kernel_size", 3))
363 dropout = float(training_config.get("dropout", 0.15))
364 _learning_rate = float(training_config.get("learning_rate", 0.0007))
365 _weight_decay = float(training_config.get("weight_decay", 0.0001))
366 batch_size = int(training_config.get("batch_size", 64))
367 max_epochs = int(training_config.get("epochs", 60))
368 patience = int(training_config.get("patience", 10))
369 decision_threshold = float(training_config.get("decision_threshold", 0.5))
370 threshold_metric = str(training_config.get("optimize_threshold_metric", "mcc"))
371 threshold_min = float(training_config.get("threshold_search_min", 0.35))
372 threshold_max = float(training_config.get("threshold_search_max", 0.65))
373 threshold_steps = int(training_config.get("threshold_search_steps", 61))
374 magnitude_loss_weight = float(training_config.get("magnitude_loss_weight", 1.0))
375 volatility_loss_weight = float(training_config.get("volatility_loss_weight", 1.0))
376 # Stage 4 of the rank-pivot roadmap - see
377 # compute_combined_multitask_loss()'s docstring for why this
378 # defaults to 1.0 (fully backward-compatible) but config.json sets
379 # it low for this trainer specifically: the primary "direction" head
380 # is a near-noise 1-day objective main.py never reads (it collapsed
381 # to a constant during training - positive_rate 0.0002).
382 direction_loss_weight = float(training_config.get("direction_loss_weight", 1.0))
383 # Stage 4 of the rank-pivot roadmap - see
384 # compute_horizon_consistency_loss()'s docstring. Defaults to 0.0
385 # (fully backward-compatible - a zero weight adds zero gradient);
386 # config.json sets this to a small positive value for this trainer.
387 consistency_loss_weight = float(training_config.get("consistency_loss_weight", 0.0))
388 horizon_head_config = resolve_horizon_head_config(training_config)
389 # --seed (if passed) wins over config.json for this invocation only -
390 # see parse_args()'s docstring for the seed-ensembling workflow.
391 seed = int(args.seed) if args.seed is not None else int(training_config.get("seed", 42))
392 # V5.1 Phase 3 (item 10) - "none" is the FUNCTION default on
393 # AetherNetSequenceMultiTaskHorizons.__init__ (byte-identical to
394 # today's no-normalization trunk) - see that class's docstring.
395 normalization = str(training_config.get("normalization", "none"))
397 # V5.1 Phase 3 (items 1, 10, 11) - see train_multitask.py's
398 # identical block for the full rationale; every default here
399 # reproduces today's training run byte-for-byte.
400 batch_mode = str(training_config.get("batch_mode", "random"))
401 cross_sectional_batch_dates = int(training_config.get("cross_sectional_batch_dates", 4))
402 min_cross_sectional_group_size = int(training_config.get("min_cross_sectional_group_size", 20))
403 ranking_loss_config = training_config.get("ranking_loss") if batch_mode == "cross_sectional" else None
404 if ranking_loss_config is not None and args.ranking_objective is not None:
405 ranking_loss_config = {**ranking_loss_config, "objective": args.ranking_objective}
406 # V5.2.8 (development/Problems.md #94) - see train_multitask.py's
407 # identical block for the full rationale.
408 gate_aware_ranking_weights_enabled = (
409 ranking_loss_config is not None
410 and bool(training_config.get("gate_aware_ranking_weights", {}).get("enabled", False))
411 )
412 risk_off_override_min_severity = float(
413 full_config.get("phase_v2", {}).get("regime_detection", {}).get("risk_off_override_min_severity") or 0.0
414 )
415 swa_config = training_config.get("swa", {})
416 swa_enabled = bool(swa_config.get("enabled", False))
417 swa_start_epoch_fraction = float(swa_config.get("start_epoch_fraction", 0.7))
418 early_stop_head = str(training_config.get("early_stop_head", "rank_20d"))
419 early_stop_smoothing_epochs = int(training_config.get("early_stop_smoothing_epochs", 1))
420 label_noise_std = float(training_config.get("label_noise_std", 0.0))
422 feature_schema_path = Path(args.feature_schema_path)
423 if not feature_schema_path.exists():
424 LOGGER.info("train_sequence: missing feature schema at %s - skipping.", feature_schema_path)
425 return 0
426 with feature_schema_path.open("r", encoding="utf-8") as f:
427 feature_schema = json.load(f)
428 feature_names = list(feature_schema["model_input_names"])
430 dataset_path = Path(args.dataset_path)
431 if not dataset_path.exists():
432 LOGGER.info("train_sequence: dataset not found at %s - skipping.", dataset_path)
433 return 0
434 dataset = read_dataset_compact(dataset_path, chunk_rows=profile.read_chunk_rows)
436 required_columns = set(feature_names) | {
437 "target_direction",
438 "target_return_1d",
439 "target_volatility_next_day",
440 "split",
441 "ticker",
442 "date",
443 }
444 missing_columns = required_columns - set(dataset.columns)
445 if missing_columns:
446 LOGGER.info("train_sequence: dataset missing columns %s - skipping.", sorted(missing_columns))
447 return 0
448 # Horizon target columns are NOT required the way the core 3 are -
449 # an older dataset built before Phase 3/4 shipped simply won't have
450 # them, in which case every horizon head trains on an all-NaN
451 # column (masked loss/metrics degrade to a true no-op), same
452 # graceful backward-compatibility contract as train_multitask.py.
453 for head_name, (column, _kind, _stride) in HORIZON_HEAD_SPECS.items():
454 if column not in dataset.columns:
455 dataset[column] = np.nan
456 horizon_head_config[head_name] = {**horizon_head_config[head_name], "enabled": False}
457 LOGGER.info("train_sequence: dataset missing %s - disabling %s head.", column, head_name)
459 eligible = dataset
460 if "training_eligible" in dataset.columns:
461 eligible = dataset[dataset["training_eligible"]].reset_index(drop=True)
462 else:
463 eligible = dataset.reset_index(drop=True)
464 del dataset # V5.8.0: the unfiltered frame is not needed again (280k rows x 251 columns)
465 gc.collect()
467 train_rows = int((eligible["split"] == "train").sum())
468 validation_rows = int((eligible["split"] == "validation").sum())
469 backtest_rows = int((eligible["split"] == "backtest").sum())
470 if train_rows < min_train_rows or validation_rows < min_validation_rows or backtest_rows < min_backtest_rows:
471 LOGGER.info(
472 "train_sequence: only %d train / %d validation / %d backtest rows "
473 "(need >= %d / %d / %d) - skipping, not writing artifacts.",
474 train_rows,
475 validation_rows,
476 backtest_rows,
477 min_train_rows,
478 min_validation_rows,
479 min_backtest_rows,
480 )
481 return 0
483 set_seed(seed)
484 label_noise_generator = torch.Generator().manual_seed(seed + 7919) if label_noise_std > 0.0 else None
485 device = torch.device("cpu")
487 LOGGER.info("train_sequence: building (rows=%d, window=%d, features=%d) sequence tensor...", len(eligible), window_size, len(feature_names))
488 sequences = None # V5.8.0: each split builds its own windows (no full-dataset array, no copies)
489 split_kwargs = {"feature_names": feature_names, "window_size": window_size}
490 if profile.lazy_windows:
491 split_kwargs["matrix"] = eligible[feature_names].to_numpy(dtype=np.float32)
492 if ranking_loss_config is not None and ranking_loss_config.get("objective") in CONTEXT_OBJECTIVES:
493 split_kwargs["context"] = True
495 train_features, train_targets, train_dates = _split_sequence_tensors(eligible, sequences, "train", **split_kwargs)
496 validation_features, validation_targets, validation_dates = _split_sequence_tensors(
497 eligible, sequences, "validation", **split_kwargs
498 )
499 validation_features = validation_features.to(device)
500 validation_targets = {name: tensor.to(device) for name, tensor in validation_targets.items()}
501 backtest_features, backtest_targets, backtest_dates = _split_sequence_tensors(
502 eligible, sequences, "backtest", **split_kwargs
503 )
504 backtest_features = backtest_features.to(device)
505 backtest_targets = {name: tensor.to(device) for name, tensor in backtest_targets.items()}
506 # V5.1 Phase 5 (Problems.md #83) - `sequences` (the full-dataset
507 # dense (rows, window, features) array, easily 1GB+ on a large
508 # walk-forward window) is not needed again once all three splits
509 # are sliced out of it above. It was previously kept alive by
510 # Python's own reference tracking all the way through the entire
511 # training loop, because backtest extraction used to happen ~250
512 # lines later, right before backtest evaluation - meaning it sat
513 # resident in memory for the full multi-minute training run for no
514 # reason, on a Codespace machine type with no swap. Freeing it here
515 # (plus train.py::_run_walk_forward()'s matching fix for its own
516 # per-window `dataset`) is what let a previously-OOM-killed 130,738
517 # row window succeed on retry.
518 del sequences
519 gc.collect()
521 target_names_sorted = sorted(train_targets)
522 if batch_mode == "cross_sectional":
523 train_loader = None
524 elif profile.lazy_windows:
525 # the same shuffle a TensorDataset loader draws (one RandomSampler over len rows), as row indices into the lazy split
526 train_loader = torch.utils.data.DataLoader(range(len(train_features)), batch_size=batch_size, shuffle=True)
527 else:
528 train_loader = torch.utils.data.DataLoader(
529 torch.utils.data.TensorDataset(
530 train_features,
531 *[train_targets[name] for name in target_names_sorted],
532 ),
533 batch_size=batch_size,
534 shuffle=True,
535 )
536 train_dates_array = train_dates.to_numpy() if hasattr(train_dates, "to_numpy") else np.asarray(train_dates)
537 train_date_group_ids = build_date_group_ids(train_dates_array) if ranking_loss_config is not None else None
538 # V5.2.8 (development/Problems.md #94) - see train_multitask.py's
539 # identical block for the full rationale. `eligible` (not
540 # train_features/train_dates, which are already sequence-tensor
541 # shaped) still carries the per-row topology/regime columns this
542 # needs - filtered the same way _split_sequence_tensors() itself
543 # filters by split internally.
544 if gate_aware_ranking_weights_enabled:
545 weight_by_date = compute_gate_friendliness_weight_by_date(
546 eligible[eligible["split"] == "train"], risk_off_override_min_severity
547 )
548 train_date_weights = torch.as_tensor(
549 [weight_by_date.get(str(date), 1.0) for date in train_dates_array], dtype=torch.float32
550 )
551 else:
552 train_date_weights = None
553 validation_date_group_ids = (
554 torch.as_tensor(build_date_group_ids(np.asarray(validation_dates)), dtype=torch.int64, device=device)
555 if ranking_loss_config is not None
556 else None
557 )
559 model = AetherNetSequenceMultiTaskHorizons(
560 input_dim=len(feature_names),
561 channels=channels,
562 kernel_size=kernel_size,
563 dropout=dropout,
564 normalization=normalization,
565 ).to(device)
567 # V5.1 Phase 3 (item 11) - "adam" is build_optimizer()'s own
568 # FUNCTION default (byte-identical to the plain torch.optim.Adam
569 # call this replaces, when training_config has no "optimizer" key).
570 optimizer = build_optimizer(model, training_config)
571 scheduler = build_lr_scheduler(optimizer, training_config, max_epochs)
572 swa_state: dict | None = None
573 swa_count = 0
574 swa_start_epoch = max(1, int(round(max_epochs * swa_start_epoch_fraction))) if swa_enabled else None
575 train_split_frame = eligible[eligible["split"] == "train"]
576 positive_count = max(float(train_split_frame["target_direction"].sum()), 1.0)
577 negative_count = max(float(len(train_split_frame) - train_split_frame["target_direction"].sum()), 1.0)
578 pos_weight = torch.tensor(negative_count / positive_count, dtype=torch.float32, device=device)
579 direction_criterion = nn.BCEWithLogitsLoss(pos_weight=pos_weight)
581 best_state = None
582 best_epoch = 0
583 best_validation_metric = float("-inf")
584 epochs_without_improvement = 0
585 history: list[dict] = []
586 min_best_epoch = int(training_config.get("min_best_epoch", 3))
587 # Stage 4 of the rank-pivot roadmap (development/Problems.md#43): the
588 # comment this replaces documented an EARLIER attempt at fixing this
589 # same untrained-init bug by monitoring direction balanced-accuracy
590 # instead of loss - that measurably IMPROVED direction MCC but
591 # DEGRADED this exact model's own rank_20d backtest signal
592 # (non-overlapping t-stat 2.90 -> 2.21, confirmed by direct
593 # comparison). This model's actual downstream consumer is
594 # main.py's portfolio_book (predicted_rank_20d), not the direction
595 # head at all - monitoring validation rank_20d mean IC directly is a
596 # third, previously-untried option (not a repeat of the balanced-
597 # accuracy regression above), so it's config-gated
598 # (early_stop_metric) rather than a silent hardcoded switch: revert
599 # to the previous "validation_loss" behavior in one config edit if a
600 # future comparison shows the same kind of regression. Falls back to
601 # "validation_loss" automatically if the rank_20d head itself is
602 # disabled/missing - monitoring an IC that doesn't exist is not a
603 # valid choice regardless of what this key says.
604 # See train_multitask.py's identical block for the full rationale
605 # on early_stop_head/early_stop_smoothing_epochs.
606 early_stop_metric = str(training_config.get("early_stop_metric", "rank_ic"))
607 monitor_rank_ic = (
608 early_stop_metric in ("rank_ic", "rank_ic_non_overlapping")
609 and early_stop_head in horizon_head_config
610 and early_stop_head in HORIZON_HEAD_SPECS
611 and horizon_head_config[early_stop_head].get("enabled", True)
612 )
613 monitored_metric_key = f"validation_{early_stop_head}_mean_ic"
614 if early_stop_metric == "rank_ic_non_overlapping":
615 monitored_metric_key = f"validation_{early_stop_head}_non_overlapping_mean_ic"
617 checkpoint_path = sequence_candidate_output_paths(args.version_id)["version_dir"] / "checkpoint.pt" if profile.checkpoint_every else None
618 start_epoch, stopped = 1, False
619 if args.resume and checkpoint_path is not None and checkpoint_path.exists():
620 saved = torch.load(checkpoint_path, weights_only=False)
621 model.load_state_dict(saved["model"])
622 optimizer.load_state_dict(saved["optimizer"])
623 if scheduler is not None and saved["scheduler"] is not None:
624 scheduler.load_state_dict(saved["scheduler"])
625 best_state, best_epoch, best_validation_metric = saved["best_state"], saved["best_epoch"], saved["best_validation_metric"]
626 epochs_without_improvement, history = saved["epochs_without_improvement"], saved["history"]
627 swa_state, swa_count = saved["swa_state"], saved["swa_count"]
628 restore_rng_state(saved["rng"], label_noise_generator)
629 start_epoch, stopped = int(saved["epoch"]) + 1, bool(saved["stopped"])
630 LOGGER.info("train_sequence: resumed from %s after epoch %d", checkpoint_path, start_epoch - 1)
632 for epoch in range(start_epoch, max_epochs + 1) if not stopped else ():
633 model.train()
634 running_loss = 0.0
635 sample_count = 0
637 if batch_mode == "cross_sectional":
638 epoch_batches = build_cross_sectional_date_batches(
639 train_dates_array,
640 batch_dates=cross_sectional_batch_dates,
641 min_group_size=min_cross_sectional_group_size,
642 shuffle=True,
643 seed=seed + epoch,
644 )
645 batch_source = (
646 (
647 train_features[torch.as_tensor(row_indices, dtype=torch.long)].to(device),
648 {
649 name: train_targets[name][torch.as_tensor(row_indices, dtype=torch.long)].to(device)
650 for name in target_names_sorted
651 },
652 torch.as_tensor(train_date_group_ids[row_indices], dtype=torch.int64, device=device)
653 if train_date_group_ids is not None
654 else None,
655 train_date_weights[torch.as_tensor(row_indices, dtype=torch.long)].to(device)
656 if train_date_weights is not None
657 else None,
658 )
659 for row_indices in epoch_batches
660 )
661 elif profile.lazy_windows:
662 batch_source = (
663 (train_features[rows].to(device), {name: train_targets[name][rows].to(device) for name in target_names_sorted}, None, None)
664 for rows in train_loader
665 )
666 else:
667 batch_source = (
668 (
669 batch[0].to(device),
670 {name: tensor.to(device) for name, tensor in zip(target_names_sorted, batch[1:], strict=False)},
671 None,
672 None,
673 )
674 for batch in train_loader
675 )
677 for batch_features, batch_targets, batch_group_ids, batch_date_weights in batch_source:
678 optimizer.zero_grad()
679 batch_targets = add_rank_label_noise(batch_targets, HORIZON_HEAD_SPECS, label_noise_std, label_noise_generator)
680 outputs = model(batch_features)
681 loss = compute_combined_multitask_loss(
682 outputs,
683 batch_targets,
684 direction_criterion,
685 magnitude_loss_weight,
686 volatility_loss_weight,
687 horizon_head_config,
688 direction_loss_weight,
689 consistency_loss_weight,
690 date_group_ids=batch_group_ids,
691 ranking_loss_config=ranking_loss_config,
692 date_weights=batch_date_weights,
693 )
694 loss.backward()
695 optimizer.step()
697 running_loss += float(loss.item()) * len(batch_features)
698 sample_count += len(batch_features)
700 if scheduler is not None and sample_count: # an epoch with no batch made no optimizer step (torch warns)
701 scheduler.step()
703 model.eval()
704 validation_outputs = forward_in_batches(model, validation_features)
705 with torch.no_grad():
706 validation_loss = compute_combined_multitask_loss(
707 validation_outputs,
708 validation_targets,
709 direction_criterion,
710 magnitude_loss_weight,
711 volatility_loss_weight,
712 horizon_head_config,
713 direction_loss_weight,
714 consistency_loss_weight,
715 date_group_ids=validation_date_group_ids,
716 ranking_loss_config=ranking_loss_config,
717 )
718 # validation_direction_metrics is always computed and recorded
719 # for diagnostics regardless of what's actually monitored below
720 # (see monitor_rank_ic's assignment above for the monitoring
721 # decision itself).
722 validation_direction_metrics = compute_binary_metrics(
723 validation_outputs["direction"], validation_targets["direction"], direction_criterion, decision_threshold
724 )
726 validation_head_ic = None
727 if monitor_rank_ic:
728 _column, _kind, head_stride = HORIZON_HEAD_SPECS[early_stop_head]
729 non_overlapping_stride = head_stride if early_stop_metric == "rank_ic_non_overlapping" else 1
730 validation_head_ic = compute_rank_ic(
731 validation_outputs[early_stop_head],
732 validation_targets[early_stop_head],
733 validation_dates,
734 non_overlapping_stride=non_overlapping_stride,
735 )
737 history_entry = {
738 "epoch": epoch,
739 "train_loss": running_loss / max(sample_count, 1),
740 "validation_loss": float(validation_loss.item()),
741 "validation_direction_balanced_accuracy": validation_direction_metrics["balanced_accuracy"],
742 }
743 if validation_head_ic is not None:
744 history_entry[monitored_metric_key] = validation_head_ic["mean_ic"]
745 if early_stop_metric == "rank_ic" and early_stop_head == "rank_20d":
746 history_entry["validation_rank_20d_mean_ic"] = validation_head_ic["mean_ic"]
747 history.append(history_entry)
749 if monitor_rank_ic:
750 smoothed = smoothed_metric(history, monitored_metric_key, early_stop_smoothing_epochs)
751 candidate_metric = smoothed if smoothed is not None else -float(validation_loss.item())
752 else:
753 candidate_metric = -float(validation_loss.item())
755 if swa_enabled and swa_start_epoch is not None and epoch >= swa_start_epoch:
756 swa_state, swa_count = swa_accumulate(swa_state, model.state_dict(), swa_count)
758 if is_new_best_epoch(candidate_metric, best_validation_metric, epoch, min_best_epoch):
759 best_validation_metric = candidate_metric
760 best_epoch = epoch
761 best_state = copy.deepcopy(model.state_dict())
762 epochs_without_improvement = 0
763 else:
764 epochs_without_improvement += 1
766 stop = epoch >= min_best_epoch and epochs_without_improvement >= patience
767 if checkpoint_path is not None and epoch % profile.checkpoint_every == 0:
768 save_checkpoint(checkpoint_path, {
769 "epoch": epoch, "stopped": stop, "model": model.state_dict(), "optimizer": optimizer.state_dict(),
770 "scheduler": scheduler.state_dict() if scheduler is not None else None, "best_state": best_state, "best_epoch": best_epoch,
771 "best_validation_metric": best_validation_metric, "epochs_without_improvement": epochs_without_improvement, "history": history,
772 "swa_state": swa_state, "swa_count": swa_count, "rng": rng_state(label_noise_generator),
773 })
774 if stop:
775 break
777 if swa_enabled and swa_state is not None:
778 best_state = swa_finalize(swa_state)
780 if best_state is None:
781 best_state = copy.deepcopy(model.state_dict())
782 best_epoch = len(history)
784 model.load_state_dict(best_state)
785 model.eval()
786 validation_outputs_for_threshold = forward_in_batches(model, validation_features)
787 tuned_threshold, tuned_validation_direction_metrics = find_optimal_threshold(
788 validation_outputs_for_threshold["direction"],
789 validation_targets["direction"],
790 direction_criterion,
791 threshold_metric,
792 threshold_min,
793 threshold_max,
794 threshold_steps,
795 )
796 head_thresholds = {"direction": tuned_threshold}
797 for head_name, (_column, kind, _stride) in HORIZON_HEAD_SPECS.items():
798 if kind != "binary" or not horizon_head_config[head_name].get("enabled", True):
799 continue
800 head_threshold, _head_metrics = find_optimal_masked_threshold(
801 validation_outputs_for_threshold[head_name],
802 validation_targets[head_name],
803 direction_criterion,
804 threshold_metric,
805 threshold_min,
806 threshold_max,
807 threshold_steps,
808 )
809 head_thresholds[head_name] = head_threshold if head_threshold is not None else 0.5
811 train_features_device = train_features.to(device)
812 train_targets_device = {name: tensor.to(device) for name, tensor in train_targets.items()}
814 trained_at = datetime.now(timezone.utc).isoformat()
815 # V5.1 Phase 4 (items 7, 12) - see train_multitask.py's identical
816 # block. `eligible[eligible["split"] == "backtest"]` reconstructs
817 # the exact same frame _split_sequence_tensors() already built
818 # internally for backtest_features/backtest_targets/backtest_dates
819 # above (same mask, same source object, same row order) - the raw
820 # ticker/date/target_return_1d columns that function doesn't return.
821 backtest_raw_frame = eligible[eligible["split"] == "backtest"]
822 net_performance_config = full_config.get("phase1", {}).get("target", {}).get("ranking", {}).get(
823 "net_performance", {}
824 )
825 net_performance_context = (
826 {
827 "raw_frame": backtest_raw_frame,
828 "net_performance_config": net_performance_config,
829 "sector_by_ticker": load_sector_mapping(full_config),
830 "head": str(net_performance_config.get("head", "rank_20d")),
831 "full_config": full_config,
832 }
833 if net_performance_config.get("enabled", False)
834 else None
835 )
837 metrics = {
838 "project": "aether_quant",
839 "phase": "sequence_multitask_horizons_phase2",
840 "version_id": args.version_id,
841 "trained_at": trained_at,
842 "window_size": window_size,
843 "channels": channels,
844 "kernel_size": kernel_size,
845 "row_counts": {"train": train_rows, "validation": validation_rows, "backtest": backtest_rows},
846 "seed": seed,
847 "best_epoch": best_epoch,
848 "early_stop_metric": f"{early_stop_head}_ic" if monitor_rank_ic else "validation_loss",
849 "epochs_ran": len(history),
850 "loss_weights": {
851 "magnitude_loss_weight": magnitude_loss_weight,
852 "volatility_loss_weight": volatility_loss_weight,
853 },
854 # V5.1 Phase 3 (items 1, 10, 11) - see train_multitask.py's
855 # identical field.
856 "training_recipe": {
857 "optimizer": str(training_config.get("optimizer", "adam")),
858 "lr_schedule": str(training_config.get("lr_schedule", "none")),
859 "normalization": normalization,
860 "batch_mode": batch_mode,
861 "ranking_loss": ranking_loss_config,
862 "swa": {"enabled": swa_enabled, "epochs_averaged": swa_count if swa_enabled else 0},
863 "early_stop_metric": early_stop_metric,
864 "early_stop_head": early_stop_head,
865 "early_stop_smoothing_epochs": early_stop_smoothing_epochs,
866 },
867 "horizon_heads": horizon_head_config,
868 "threshold_optimization": {
869 "metric": threshold_metric,
870 "default_threshold": decision_threshold,
871 "selected_threshold": tuned_threshold,
872 "selected_validation_metrics": tuned_validation_direction_metrics,
873 "head_thresholds": head_thresholds,
874 },
875 "train": compute_sequence_multitask_metrics(
876 model, train_features_device, train_targets_device, train_dates,
877 direction_criterion, tuned_threshold, head_thresholds, horizon_head_config,
878 ),
879 "validation": compute_sequence_multitask_metrics(
880 model, validation_features, validation_targets, validation_dates,
881 direction_criterion, tuned_threshold, head_thresholds, horizon_head_config,
882 ),
883 "backtest": compute_sequence_multitask_metrics(
884 model, backtest_features, backtest_targets, backtest_dates,
885 direction_criterion, tuned_threshold, head_thresholds, horizon_head_config,
886 ranking_promotion_config=full_config,
887 net_performance_context=net_performance_context,
888 ),
889 "history": history,
890 }
891 # Stage 5 of the rank-pivot roadmap (development/Problems.md#43) -
892 # see train_multitask.py's identical wiring and
893 # compute_purged_cv_rank_ic_diagnostic()'s docstring for why
894 # phase1.target.ranking.purged_cv.enabled was previously dead
895 # configuration. Evaluates the SAME already-trained model over the
896 # TRAIN split's own purged/embargoed folds - no extra training.
897 purged_cv_config = full_config.get("phase1", {}).get("target", {}).get("ranking", {}).get("purged_cv", {})
898 if purged_cv_config.get("enabled", False) and horizon_head_config["rank_20d"].get("enabled", True):
899 model.eval()
900 train_outputs_for_purged_cv = forward_in_batches(model, train_features_device)
901 metrics["purged_cv_rank_20d"] = compute_purged_cv_rank_ic_diagnostic(
902 train_outputs_for_purged_cv["rank_20d"],
903 train_targets_device["rank_20d"],
904 train_dates,
905 n_folds=int(purged_cv_config.get("n_folds", 5)),
906 horizon_days=20,
907 embargo_days=int(purged_cv_config.get("embargo_days", 5)),
908 )
909 metrics["magnitude_quality"] = assess_regression_quality(
910 {
911 "train": metrics["train"]["magnitude"],
912 "validation": metrics["validation"]["magnitude"],
913 "backtest": metrics["backtest"]["magnitude"],
914 },
915 training_config,
916 )
917 metrics["volatility_quality"] = assess_regression_quality(
918 {
919 "train": metrics["train"]["volatility"],
920 "validation": metrics["validation"]["volatility"],
921 "backtest": metrics["backtest"]["volatility"],
922 },
923 training_config,
924 )
926 model_payload = {
927 "project": "Aether Quant",
928 "phase": "v2_sequence_multitask_horizons_model",
929 "version_id": args.version_id,
930 "status": "trained",
931 "trained_at": trained_at,
932 "model": {
933 "type": "sequence_multitask_direction_magnitude_volatility_horizons",
934 "model_input_features": feature_names,
935 "window_size": window_size,
936 "channels": channels,
937 "kernel_size": kernel_size,
938 "dropout": dropout,
939 # V5.1 Phase 3 (item 10) - was missing here even though the
940 # model was already constructed with this value (found while
941 # writing a seed-ensemble evaluation script that needs to
942 # reconstruct the exact architecture from model.json alone,
943 # without also reading training_metrics.json).
944 "normalization": normalization,
945 "decision_threshold": tuned_threshold,
946 },
947 "export": export_sequence_multitask_horizons_architecture(model) | {"state_dict": export_state_dict(model)},
948 }
949 feature_schema_payload = {"model_input_names": feature_names, "window_size": window_size}
951 paths = sequence_candidate_output_paths(args.version_id)
952 paths["version_dir"].mkdir(parents=True, exist_ok=True)
953 paths["sequence_model"].write_text(json.dumps(model_payload, indent=2), encoding="utf-8")
954 paths["sequence_feature_schema"].write_text(json.dumps(feature_schema_payload, indent=2), encoding="utf-8")
955 paths["sequence_training_metrics"].write_text(json.dumps(metrics, indent=2), encoding="utf-8")
956 if checkpoint_path is not None:
957 checkpoint_path.unlink(missing_ok=True)
958 if args.log_peak_memory:
959 log_peak(Path(args.log_peak_memory), "sequence", profile=profile.name)
961 rank_5d_ic = metrics["backtest"].get("rank_5d_ic") or {}
962 LOGGER.info(
963 "train_sequence: wrote sequence artifacts for version %s "
964 "(backtest direction mcc=%.4f, magnitude mae=%.6f rmse=%.6f [%s], volatility mae=%.6f [%s], "
965 "rank_5d mean_ic=%.4f t_stat=%.2f).",
966 args.version_id,
967 metrics["backtest"]["direction"]["mcc"],
968 metrics["backtest"]["magnitude"]["mae"],
969 metrics["backtest"]["magnitude"]["rmse"],
970 metrics["magnitude_quality"]["quality_status"],
971 metrics["backtest"]["volatility"]["mae"],
972 metrics["volatility_quality"]["quality_status"],
973 rank_5d_ic.get("mean_ic", 0.0),
974 rank_5d_ic.get("t_stat", 0.0),
975 )
976 return 0
977 except Exception as exc: # never let an unexpected failure look ambiguous to the caller
978 LOGGER.error("train_sequence: unexpected failure - %s", exc)
979 return 1
982if __name__ == "__main__":
983 sys.exit(main())