Coverage for train_multitask.py: 100%

300 statements  

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

1"""Offline trainer for the multi-task model: direction + return magnitude + 

2volatility + longer-horizon direction (5d/20d) + cross-sectional rank 

3(5d/20d) predicted jointly from one shared trunk (AetherNetMultiTaskHorizons, 

4train.py). 

5 

6Separate script from train.py, same convention as train_gating.py/ 

7train_topology.py: reads the already-built active dataset 

8(ml/datasets/full_dataset.csv) and the active feature_schema.json rather 

9than rebuilding the dataset itself, so this never touches train.py's own 

10CLI flow or its baseline/expert artifacts. Uses the exact same 

11model_input_names as the baseline model (scaled features + asset context) - 

12this phase does not change what the input feature set is, only what the 

13model predicts from it (see development/Changelog.md for why regime/ 

14liquidity/topology-as-inputs was scoped out of an earlier pass). 

15 

16Loss is BCEWithLogitsLoss(direction) + magnitude_loss_weight * MSE(magnitude) 

17+ volatility_loss_weight * MSE(volatility) + a masked BCE/MSE term per 

18enabled horizon head (direction_5d/20d, rank_5d/20d - see 

19train.py::masked_bce_with_logits_loss()/masked_mse_loss()), each row-masked 

20since these targets are NaN for the trailing rows of an asset's history 

21that don't yet have a full forward window (not dropped from the dataset - 

22see train.py::engineer_features()'s docstring). Early stopping and 

23threshold tuning both operate on the combined validation loss / direction 

24logits respectively - magnitude/volatility/rank heads are evaluated with 

25plain MAE/RMSE (train.py::compute_regression_metrics()), direction_5d/20d 

26with MCC/F1 (train.py::compute_masked_binary_metrics()), and rank_5d/20d 

27additionally get a rank-IC block (train.py::compute_rank_ic()) - the 

28cross-sectional signal's actual win condition, not MCC (meaningless for a 

29continuous/rank target). 

30 

31Usage: 

32 python train_multitask.py --version-id <uuid> [--config-path config.json] [--dataset-path ml/datasets/full_dataset.csv] 

33 

34Writes ml/versions/<version_id>/multitask_model.json, multitask_feature_schema.json 

35and multitask_training_metrics.json. Exits 0 (not an error) when there isn't 

36enough data yet - "skipped" must never look like "failed" to the caller, 

37mirroring train_gating.py/train_topology.py. 

38""" 

39 

40from __future__ import annotations 

41 

42import argparse 

43import copy 

44import json 

45import logging 

46import sys 

47from datetime import datetime, timezone 

48from pathlib import Path 

49 

50import numpy as np 

51import pandas as pd 

52import torch 

53import torch.nn as nn 

54from torch.utils.data import DataLoader, TensorDataset 

55 

56from features.cross_sectional_inputs import apply_cross_sectional_inputs, expand_input_names, settings_from_config 

57from retraining.slicing import PROFILES, log_peak, memory_profile 

58from train import ( 

59 HORIZON_HEAD_SPECS, 

60 AetherNetMultiTaskHorizons, 

61 add_rank_label_noise, 

62 assess_net_performance_quality, 

63 assess_ranking_quality_from_predictions, 

64 assess_regression_quality, 

65 build_cross_sectional_date_batches, 

66 build_date_group_ids, 

67 build_lr_scheduler, 

68 build_optimizer, 

69 compute_binary_metrics, 

70 compute_combined_multitask_loss, 

71 compute_gate_friendliness_weight_by_date, 

72 compute_masked_binary_metrics, 

73 compute_masked_regression_metrics, 

74 compute_purged_cv_rank_ic_diagnostic, 

75 compute_rank_ic, 

76 compute_regression_metrics, 

77 enabled_extra_heads, 

78 export_multitask_horizons_architecture, 

79 export_state_dict, 

80 find_optimal_masked_threshold, 

81 find_optimal_threshold, 

82 horizon_head_specs, 

83 is_new_best_epoch, 

84 load_sector_mapping, 

85 resolve_horizon_head_config, 

86 run_net_performance_simulation, 

87 set_seed, 

88 smoothed_metric, 

89 swa_accumulate, 

90 swa_finalize, 

91) 

92 

93LOGGER = logging.getLogger("aether_quant.train_multitask") 

94ROOT = Path(__file__).resolve().parent 

95ML_DIR = ROOT / "ml" 

96CONFIG_PATH = ROOT / "config.json" 

97DATASET_PATH = ML_DIR / "datasets" / "full_dataset.csv" 

98FEATURE_SCHEMA_PATH = ML_DIR / "feature_schema.json" 

99 

100 

101def parse_args() -> argparse.Namespace: 

102 parser = argparse.ArgumentParser(description="Aether Quant multi-task (direction+magnitude+volatility+horizons) trainer") 

103 parser.add_argument("--version-id", type=str, required=True, help="Candidate model_version_id (UUID)") 

104 parser.add_argument("--config-path", type=str, default=str(CONFIG_PATH)) 

105 parser.add_argument("--dataset-path", type=str, default=str(DATASET_PATH)) 

106 # V5.1 Phase 4 (item 4) - previously FEATURE_SCHEMA_PATH was a hardcoded 

107 # module constant with no override, which meant this trainer could only 

108 # ever read the ACTIVE ml/feature_schema.json - fine for the normal 

109 # candidate-retraining path (which shares that active dataset/schema), 

110 # but a hard blocker for train.py::_run_walk_forward()'s per-window 

111 # subprocess calls, where each window has its own schema that does NOT 

112 # match the active one. Defaults to the module constant - a no-op for 

113 # 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): 

116 # seed-ensembling support. Overrides config.json's multitask_training.seed 

117 # for THIS invocation only (never mutates config.json) - run this script 

118 # once per seed (e.g. --seed 42/43/44), each with its own --version-id, 

119 # writing independent candidates under ml/versions/. Combine their 

120 # backtest rank_20d predictions afterward with 

121 # train.py::aggregate_seed_ensemble_rank_ic() (average_ensemble_predictions() 

122 # is prediction-averaging, not weight-averaging - see its docstring for 

123 # why that's the only statistically valid form here). Defaults to None 

124 # (use config.json's seed unchanged) - zero behavior change for anyone 

125 # not passing this flag. 

126 parser.add_argument("--seed", type=int, default=None, help="Override config.json's seed for this run (seed-ensembling)") 

127 # V5.1 Phase 3 (item 1) - one-run A/B override without editing config.json, 

128 # same precedent as --seed immediately above. None (default) leaves 

129 # training_config["ranking_loss"]["objective"] unchanged. 

130 parser.add_argument( 

131 "--ranking-objective", 

132 type=str, 

133 default=None, 

134 choices=["mse", "soft_spearman", "listnet"], 

135 help="Override config.json's ranking_loss.objective for this run only (A/B testing)", 

136 ) 

137 # V6.6.10: `low` reads the dataset in float32 chunks and keeps no second copy of the eligible rows (about 0.3 GB instead of 

138 # 2 GB for the 825 MB dataset); `standard` is unchanged. 

139 parser.add_argument("--memory-profile", choices=sorted(PROFILES), default="standard", help="standard (default) or low: train on a small machine") 

140 parser.add_argument("--log-peak-memory", type=str, default=None, help="append this run's peak memory to this JSONL file") 

141 return parser.parse_args() 

142 

143 

144def load_multitask_training_config(config_path: Path = CONFIG_PATH) -> dict: 

145 with Path(config_path).open("r", encoding="utf-8") as f: 

146 config = json.load(f) 

147 return config.get("phase_v2", {}).get("retraining", {}).get("multitask_training", {}) 

148 

149 

150def multitask_candidate_output_paths(version_id: str) -> dict[str, Path]: 

151 """Own local helper mirroring train_gating.py's gating_candidate_output_paths() 

152 - kept independent of train.py's own candidate_output_paths() since the 

153 two write disjoint filenames.""" 

154 version_dir = ML_DIR / "versions" / version_id 

155 return { 

156 "version_dir": version_dir, 

157 "multitask_model": version_dir / "multitask_model.json", 

158 "multitask_feature_schema": version_dir / "multitask_feature_schema.json", 

159 "multitask_training_metrics": version_dir / "multitask_training_metrics.json", 

160 } 

161 

162 

163def frame_to_multitask_tensors( 

164 frame: pd.DataFrame, feature_names: list[str], head_specs: dict | None = None 

165) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: 

166 """Returns (features, targets) where targets is a dict keyed by head 

167 name - direction/magnitude/volatility are never NaN (engineer_features()'s 

168 required_columns dropna already guarantees this), the 4 horizon heads 

169 may be NaN for a trailing few rows per asset (see 

170 HORIZON_HEAD_SPECS/masked_bce_with_logits_loss()'s docstring).""" 

171 features = torch.tensor(frame[feature_names].to_numpy(dtype=np.float32), dtype=torch.float32) 

172 targets = { 

173 "direction": torch.tensor(frame["target_direction"].to_numpy(dtype=np.float32), dtype=torch.float32), 

174 "magnitude": torch.tensor(frame["target_return_1d"].to_numpy(dtype=np.float32), dtype=torch.float32), 

175 "volatility": torch.tensor(frame["target_volatility_next_day"].to_numpy(dtype=np.float32), dtype=torch.float32), 

176 } 

177 for head_name, (column, _kind, _stride) in (head_specs or HORIZON_HEAD_SPECS).items(): 

178 targets[head_name] = torch.tensor(frame[column].to_numpy(dtype=np.float32), dtype=torch.float32) 

179 return features, targets 

180 

181 

182def compute_multitask_metrics( 

183 model: AetherNetMultiTaskHorizons, 

184 features: torch.Tensor, 

185 targets: dict[str, torch.Tensor], 

186 dates: pd.Series, 

187 direction_criterion: nn.Module, 

188 threshold: float, 

189 head_thresholds: dict[str, float], 

190 horizon_head_config: dict, 

191 ranking_promotion_config: dict | None = None, 

192 net_performance_context: dict | None = None, 

193) -> dict: 

194 """net_performance_context (V5.1 Phase 4, items 7/12), only passed by 

195 the BACKTEST split call site (same convention as ranking_promotion_config 

196 above): {"raw_frame": pd.DataFrame with ticker/date/target_return_1d, 

197 row-aligned with `features`/`dates`; "net_performance_config": dict; 

198 "sector_by_ticker": dict; "head": str - which HORIZON_HEAD_SPECS head 

199 to run the simulation for; "full_config": the full config.json, for 

200 assess_net_performance_quality()'s promotion_gate lookup}. Writes 

201 metrics[f"{head}_net_performance"] via train.py:: 

202 run_net_performance_simulation()/assess_net_performance_quality() - the 

203 same simulator train.py::_run_walk_forward()'s per-window evaluation 

204 and `aq evaluate --rank-book` both use, so this number is directly 

205 comparable to those, not a re-derived approximation.""" 

206 model.eval() 

207 with torch.no_grad(): 

208 outputs = model(features) 

209 metrics = { 

210 "direction": compute_binary_metrics(outputs["direction"], targets["direction"], direction_criterion, threshold), 

211 "magnitude": compute_regression_metrics(outputs["magnitude"], targets["magnitude"]), 

212 "volatility": compute_regression_metrics(outputs["volatility"], targets["volatility"]), 

213 } 

214 for head_name, (_column, kind, stride) in horizon_head_specs(horizon_head_config).items(): 

215 if not horizon_head_config[head_name].get("enabled", True): 

216 metrics[head_name] = None 

217 continue 

218 if kind == "binary": 

219 metrics[head_name] = compute_masked_binary_metrics( 

220 outputs[head_name], targets[head_name], direction_criterion, head_thresholds.get(head_name, 0.5) 

221 ) 

222 else: 

223 metrics[head_name] = compute_masked_regression_metrics(outputs[head_name], targets[head_name]) 

224 metrics[f"{head_name}_ic"] = compute_rank_ic(outputs[head_name], targets[head_name], dates) 

225 metrics[f"{head_name}_ic_non_overlapping"] = compute_rank_ic( 

226 outputs[head_name], targets[head_name], dates, non_overlapping_stride=stride 

227 ) 

228 # Phase 2 of the 5/10 -> 9/10 roadmap: the code-enforced 

229 # promotion-gate verdict, only computed for the BACKTEST split 

230 # (ranking_promotion_config passed only by that call site) - 

231 # see train_sequence.py::compute_sequence_multitask_metrics()'s 

232 # identical wiring and train.py::assess_ranking_quality_from_predictions()'s 

233 # docstring. 

234 if ranking_promotion_config is not None: 

235 mask = ~torch.isnan(targets[head_name]) 

236 dates_masked = np.asarray(dates)[mask.detach().cpu().numpy()] 

237 metrics[f"{head_name}_ranking_quality"] = assess_ranking_quality_from_predictions( 

238 outputs[head_name][mask], 

239 targets[head_name][mask], 

240 dates_masked, 

241 non_overlapping_stride=stride, 

242 config=ranking_promotion_config, 

243 ) 

244 if net_performance_context is not None and net_performance_context.get("head") == head_name: 

245 raw_frame = net_performance_context["raw_frame"].copy() 

246 raw_frame["_predicted_head"] = outputs[head_name].detach().cpu().numpy() 

247 net_performance_result = run_net_performance_simulation( 

248 raw_frame, "_predicted_head", 

249 net_performance_context["net_performance_config"], 

250 net_performance_context["sector_by_ticker"], 

251 net_performance_context.get("full_config"), 

252 ) 

253 if net_performance_result is not None: 

254 metrics[f"{head_name}_net_performance"] = assess_net_performance_quality( 

255 net_performance_result["simulation"], 

256 net_performance_result["capacity"], 

257 net_performance_result["stress"], 

258 net_performance_context["full_config"], 

259 ) 

260 return metrics 

261 

262 

263def main() -> int: 

264 logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s") 

265 args = parse_args() 

266 profile = memory_profile(args.memory_profile) 

267 

268 try: 

269 training_config = load_multitask_training_config(Path(args.config_path)) 

270 # Phase 2 of the 5/10 -> 9/10 roadmap: assess_ranking_quality_from_predictions() 

271 # needs phase1.target.ranking.promotion_gate, which lives in the 

272 # FULL config.json, not the narrow multitask_training sub-dict - 

273 # see train.py::assess_ranking_quality_from_predictions()'s docstring. 

274 full_config = json.loads(Path(args.config_path).read_text(encoding="utf-8")) 

275 if not bool(training_config.get("enabled", True)): 

276 LOGGER.info("train_multitask: disabled via config - skipping.") 

277 return 0 

278 

279 min_train_rows = int(training_config.get("min_train_rows", 100)) 

280 min_validation_rows = int(training_config.get("min_validation_rows", 20)) 

281 min_backtest_rows = int(training_config.get("min_backtest_rows", 20)) 

282 hidden_layers = list(training_config.get("hidden_layers", [64, 32])) 

283 dropout = float(training_config.get("dropout", 0.15)) 

284 activation = str(training_config.get("activation", "relu")) 

285 normalization = str(training_config.get("normalization", "layernorm")) 

286 _learning_rate = float(training_config.get("learning_rate", 0.0007)) 

287 _weight_decay = float(training_config.get("weight_decay", 0.0001)) 

288 batch_size = int(training_config.get("batch_size", 64)) 

289 max_epochs = int(training_config.get("epochs", 120)) 

290 patience = int(training_config.get("patience", 18)) 

291 decision_threshold = float(training_config.get("decision_threshold", 0.5)) 

292 threshold_metric = str(training_config.get("optimize_threshold_metric", "mcc")) 

293 threshold_min = float(training_config.get("threshold_search_min", 0.35)) 

294 threshold_max = float(training_config.get("threshold_search_max", 0.65)) 

295 threshold_steps = int(training_config.get("threshold_search_steps", 61)) 

296 magnitude_loss_weight = float(training_config.get("magnitude_loss_weight", 1.0)) 

297 volatility_loss_weight = float(training_config.get("volatility_loss_weight", 1.0)) 

298 # Stage 4 of the rank-pivot roadmap - see 

299 # compute_combined_multitask_loss()'s docstring for why this 

300 # defaults to 1.0 (fully backward-compatible) but config.json sets 

301 # it low for this trainer specifically: the primary "direction" head 

302 # is a near-noise 1-day objective main.py never reads. 

303 direction_loss_weight = float(training_config.get("direction_loss_weight", 1.0)) 

304 # Stage 4 of the rank-pivot roadmap - see 

305 # compute_horizon_consistency_loss()'s docstring. Defaults to 0.0 

306 # (fully backward-compatible - a zero weight adds zero gradient); 

307 # config.json sets this to a small positive value for this trainer. 

308 consistency_loss_weight = float(training_config.get("consistency_loss_weight", 0.0)) 

309 horizon_head_config = resolve_horizon_head_config(training_config) 

310 # --seed (if passed) wins over config.json for this invocation only - 

311 # see parse_args()'s docstring for the seed-ensembling workflow. 

312 seed = int(args.seed) if args.seed is not None else int(training_config.get("seed", 42)) 

313 

314 # V5.1 Phase 3 (items 1, 10, 11) - "random"/"none"/"adam" are every 

315 # FUNCTION default below (build_optimizer/build_lr_scheduler/ 

316 # batch construction), so an older config.json missing this whole 

317 # block reproduces today's training run byte-for-byte. 

318 batch_mode = str(training_config.get("batch_mode", "random")) 

319 cross_sectional_batch_dates = int(training_config.get("cross_sectional_batch_dates", 4)) 

320 min_cross_sectional_group_size = int(training_config.get("min_cross_sectional_group_size", 20)) 

321 ranking_loss_config = training_config.get("ranking_loss") if batch_mode == "cross_sectional" else None 

322 if ranking_loss_config is not None and args.ranking_objective is not None: 

323 ranking_loss_config = {**ranking_loss_config, "objective": args.ranking_objective} 

324 # V5.2.8 (development/Problems.md #94) - opt-in, default-off gate- 

325 # aware ranking weight (see compute_gate_friendliness_weight_by_date()'s 

326 # own docstring). Same "nested under this trainer's own config 

327 # block" convention as ranking_loss immediately above, not a 

328 # separate shared namespace. Only meaningful when a ranking loss 

329 # is actually active - byte-identical to before this existed 

330 # whenever disabled or ranking_loss_config is None. 

331 gate_aware_ranking_weights_enabled = ( 

332 ranking_loss_config is not None 

333 and bool(training_config.get("gate_aware_ranking_weights", {}).get("enabled", False)) 

334 ) 

335 risk_off_override_min_severity = float( 

336 full_config.get("phase_v2", {}).get("regime_detection", {}).get("risk_off_override_min_severity") or 0.0 

337 ) 

338 swa_config = training_config.get("swa", {}) 

339 swa_enabled = bool(swa_config.get("enabled", False)) 

340 swa_start_epoch_fraction = float(swa_config.get("start_epoch_fraction", 0.7)) 

341 early_stop_head = str(training_config.get("early_stop_head", "rank_20d")) 

342 early_stop_smoothing_epochs = int(training_config.get("early_stop_smoothing_epochs", 1)) 

343 label_noise_std = float(training_config.get("label_noise_std", 0.0)) 

344 

345 feature_schema_path = Path(args.feature_schema_path) 

346 if not feature_schema_path.exists(): 

347 LOGGER.info("train_multitask: missing feature schema at %s - skipping.", feature_schema_path) 

348 return 0 

349 with feature_schema_path.open("r", encoding="utf-8") as f: 

350 feature_schema = json.load(f) 

351 feature_names = list(feature_schema["model_input_names"]) 

352 

353 dataset_path = Path(args.dataset_path) 

354 if not dataset_path.exists(): 

355 LOGGER.info("train_multitask: dataset not found at %s - skipping.", dataset_path) 

356 return 0 

357 if profile.name == "low": 

358 from train_sequence import read_dataset_compact 

359 

360 dataset = read_dataset_compact(dataset_path, chunk_rows=profile.read_chunk_rows) 

361 else: 

362 dataset = pd.read_csv(dataset_path) 

363 # V6.4.4: ranked inputs (phase1.features.cross_sectional_inputs, default off) - the same transform main.py and 

364 # the offline scorer apply; "append" mode adds `<name>_csr` inputs to the schema this run writes. 

365 cross_sectional_settings = settings_from_config(full_config) 

366 if cross_sectional_settings is not None: 

367 feature_names = expand_input_names(feature_names, cross_sectional_settings) 

368 dataset = apply_cross_sectional_inputs(dataset, full_config, feature_names) 

369 LOGGER.info("train_multitask: cross-sectionally ranked inputs %s", cross_sectional_settings) 

370 

371 # Horizon target columns are NOT required here the way the core 3 

372 # are - an older dataset built before Phase 3/4 shipped simply 

373 # won't have them, in which case every horizon head trains on an 

374 # all-NaN column (masked loss/metrics degrade to a true no-op, see 

375 # masked_bce_with_logits_loss()'s docstring), same graceful 

376 # backward-compatibility contract as every other optional stage in 

377 # this pipeline. 

378 required_columns = set(feature_names) | { 

379 "target_direction", 

380 "target_return_1d", 

381 "target_volatility_next_day", 

382 "split", 

383 "date", 

384 } 

385 missing_columns = required_columns - set(dataset.columns) 

386 if missing_columns: 

387 LOGGER.info("train_multitask: dataset missing columns %s - skipping.", sorted(missing_columns)) 

388 return 0 

389 head_specs = horizon_head_specs(horizon_head_config) 

390 for head_name, (column, _kind, _stride) in head_specs.items(): 

391 if column not in dataset.columns: 

392 dataset[column] = np.nan 

393 horizon_head_config[head_name] = {**horizon_head_config[head_name], "enabled": False} 

394 LOGGER.info("train_multitask: dataset missing %s - disabling %s head.", column, head_name) 

395 

396 eligible = dataset 

397 if "training_eligible" in dataset.columns: 

398 eligible = dataset[dataset["training_eligible"]] 

399 eligible = eligible if profile.name == "low" else eligible.copy() # a boolean mask already copies; `low` keeps that one copy 

400 del dataset 

401 

402 train_frame = eligible[eligible["split"] == "train"].reset_index(drop=True) 

403 validation_frame = eligible[eligible["split"] == "validation"].reset_index(drop=True) 

404 backtest_frame = eligible[eligible["split"] == "backtest"].reset_index(drop=True) 

405 

406 if len(train_frame) < min_train_rows or len(validation_frame) < min_validation_rows or len(backtest_frame) < min_backtest_rows: 

407 LOGGER.info( 

408 "train_multitask: only %d train / %d validation / %d backtest rows " 

409 "(need >= %d / %d / %d) - skipping, not writing artifacts.", 

410 len(train_frame), 

411 len(validation_frame), 

412 len(backtest_frame), 

413 min_train_rows, 

414 min_validation_rows, 

415 min_backtest_rows, 

416 ) 

417 return 0 

418 

419 set_seed(seed) 

420 label_noise_generator = torch.Generator().manual_seed(seed + 7919) if label_noise_std > 0.0 else None 

421 device = torch.device("cpu") 

422 

423 train_features, train_targets = frame_to_multitask_tensors(train_frame, feature_names, head_specs) 

424 validation_features, validation_targets = frame_to_multitask_tensors(validation_frame, feature_names, head_specs) 

425 validation_features = validation_features.to(device) 

426 validation_targets = {name: tensor.to(device) for name, tensor in validation_targets.items()} 

427 

428 target_names_sorted = sorted(train_targets) 

429 # V5.1 Phase 3 (item 1) - "random" (default) reproduces today's 

430 # DataLoader byte-for-byte; "cross_sectional" batches are built 

431 # fresh per epoch further down (needs a fresh seed+epoch shuffle, 

432 # see build_cross_sectional_date_batches()'s docstring), and 

433 # train_date_group_ids is only computed when a ranking loss is 

434 # actually configured to use it. 

435 if batch_mode == "cross_sectional": 

436 train_loader = None 

437 else: 

438 train_loader = DataLoader( 

439 TensorDataset( 

440 train_features, 

441 *[train_targets[name] for name in target_names_sorted], 

442 ), 

443 batch_size=batch_size, 

444 shuffle=True, 

445 ) 

446 train_dates_array = train_frame["date"].to_numpy() 

447 train_date_group_ids = build_date_group_ids(train_dates_array) if ranking_loss_config is not None else None 

448 validation_date_group_ids = ( 

449 torch.as_tensor(build_date_group_ids(validation_frame["date"].to_numpy()), dtype=torch.int64, device=device) 

450 if ranking_loss_config is not None 

451 else None 

452 ) 

453 # V5.2.8 (development/Problems.md #94) - per-ROW weight tensor 

454 # aligned to train_date_group_ids (each row gets its date's own 

455 # weight), built once here rather than per-batch/per-epoch since 

456 # neither the dataset nor the config changes during training. 

457 # None whenever the feature is disabled - byte-identical training 

458 # loop below in that case. 

459 if gate_aware_ranking_weights_enabled: 

460 weight_by_date = compute_gate_friendliness_weight_by_date(train_frame, risk_off_override_min_severity) 

461 train_date_weights = torch.as_tensor( 

462 [weight_by_date.get(str(date), 1.0) for date in train_dates_array], dtype=torch.float32 

463 ) 

464 else: 

465 train_date_weights = None 

466 

467 model = AetherNetMultiTaskHorizons( 

468 input_dim=len(feature_names), 

469 hidden_layers=hidden_layers, 

470 dropout=dropout, 

471 activation=activation, 

472 normalization=normalization, 

473 extra_heads=enabled_extra_heads(horizon_head_config), 

474 ).to(device) 

475 

476 # V5.1 Phase 3 (item 11) - "adam" is build_optimizer()'s own 

477 # FUNCTION default (byte-identical to the plain torch.optim.Adam 

478 # call this replaces, when training_config has no "optimizer" key). 

479 optimizer = build_optimizer(model, training_config) 

480 scheduler = build_lr_scheduler(optimizer, training_config, max_epochs) 

481 swa_state: dict | None = None 

482 swa_count = 0 

483 swa_start_epoch = max(1, int(round(max_epochs * swa_start_epoch_fraction))) if swa_enabled else None 

484 positive_count = max(float(train_frame["target_direction"].sum()), 1.0) 

485 negative_count = max(float(len(train_frame) - train_frame["target_direction"].sum()), 1.0) 

486 pos_weight = torch.tensor(negative_count / positive_count, dtype=torch.float32, device=device) 

487 direction_criterion = nn.BCEWithLogitsLoss(pos_weight=pos_weight) 

488 

489 best_state = None 

490 best_epoch = 0 

491 best_validation_metric = float("-inf") 

492 epochs_without_improvement = 0 

493 history: list[dict] = [] 

494 min_best_epoch = int(training_config.get("min_best_epoch", 3)) 

495 # Stage 4 of the rank-pivot roadmap (development/Problems.md#43): the 

496 # comment this replaces documented an EARLIER attempt at fixing this 

497 # same untrained-init bug by monitoring direction balanced-accuracy 

498 # instead of loss - that measurably improved direction MCC but 

499 # DEGRADED the sibling sequence model's rank_20d backtest signal 

500 # (non-overlapping t-stat 2.90 -> 2.21, confirmed by direct 

501 # comparison). This model's actual downstream consumer is 

502 # main.py's portfolio_book (predicted_rank_20d), not the direction 

503 # head at all - monitoring validation rank_20d mean IC directly is a 

504 # third, previously-untried option (not a repeat of the balanced- 

505 # accuracy regression above), so it's config-gated 

506 # (early_stop_metric) rather than a silent hardcoded switch: revert 

507 # to the previous "validation_loss" behavior in one config edit if a 

508 # future comparison shows the same kind of regression. Falls back to 

509 # "validation_loss" automatically if the rank_20d head itself is 

510 # disabled/missing - monitoring an IC that doesn't exist is not a 

511 # valid choice regardless of what this key says. 

512 # early_stop_head/early_stop_smoothing_epochs (V5.1 Phase 3): 

513 # generalizes the rank_20d-only monitor above to any HORIZON_HEAD_SPECS 

514 # head, and smooths the monitored value over the last N epochs 

515 # before comparing - a 365-day validation split at stride 20 gives 

516 # only ~18 non-overlapping IC observations, so early-stopping on 

517 # the RAW per-epoch value reliably picks a lucky epoch. 

518 # early_stop_smoothing_epochs defaults to 1 (smoothed_metric()'s 

519 # own byte-identical-to-"raw value" case), and early_stop_head 

520 # defaults to "rank_20d" - together, an old config.json with 

521 # neither key reproduces the exact "rank_20d" monitoring behavior 

522 # this block replaces. 

523 early_stop_metric = str(training_config.get("early_stop_metric", "rank_ic")) 

524 monitor_rank_ic = ( 

525 early_stop_metric in ("rank_ic", "rank_ic_non_overlapping") 

526 and early_stop_head in horizon_head_config 

527 and early_stop_head in head_specs 

528 and horizon_head_config[early_stop_head].get("enabled", True) 

529 ) 

530 monitored_metric_key = f"validation_{early_stop_head}_mean_ic" 

531 if early_stop_metric == "rank_ic_non_overlapping": 

532 monitored_metric_key = f"validation_{early_stop_head}_non_overlapping_mean_ic" 

533 

534 for epoch in range(1, max_epochs + 1): 

535 model.train() 

536 running_loss = 0.0 

537 sample_count = 0 

538 

539 if batch_mode == "cross_sectional": 

540 epoch_batches = build_cross_sectional_date_batches( 

541 train_dates_array, 

542 batch_dates=cross_sectional_batch_dates, 

543 min_group_size=min_cross_sectional_group_size, 

544 shuffle=True, 

545 seed=seed + epoch, 

546 ) 

547 batch_source = ( 

548 ( 

549 train_features[torch.as_tensor(row_indices, dtype=torch.long)].to(device), 

550 { 

551 name: train_targets[name][torch.as_tensor(row_indices, dtype=torch.long)].to(device) 

552 for name in target_names_sorted 

553 }, 

554 torch.as_tensor(train_date_group_ids[row_indices], dtype=torch.int64, device=device) 

555 if train_date_group_ids is not None 

556 else None, 

557 train_date_weights[torch.as_tensor(row_indices, dtype=torch.long)].to(device) 

558 if train_date_weights is not None 

559 else None, 

560 ) 

561 for row_indices in epoch_batches 

562 ) 

563 else: 

564 batch_source = ( 

565 ( 

566 batch[0].to(device), 

567 {name: tensor.to(device) for name, tensor in zip(target_names_sorted, batch[1:], strict=False)}, 

568 None, 

569 None, 

570 ) 

571 for batch in train_loader 

572 ) 

573 

574 for batch_features, batch_targets, batch_group_ids, batch_date_weights in batch_source: 

575 optimizer.zero_grad() 

576 batch_targets = add_rank_label_noise(batch_targets, head_specs, label_noise_std, label_noise_generator) 

577 outputs = model(batch_features) 

578 loss = compute_combined_multitask_loss( 

579 outputs, 

580 batch_targets, 

581 direction_criterion, 

582 magnitude_loss_weight, 

583 volatility_loss_weight, 

584 horizon_head_config, 

585 direction_loss_weight, 

586 consistency_loss_weight, 

587 date_group_ids=batch_group_ids, 

588 ranking_loss_config=ranking_loss_config, 

589 date_weights=batch_date_weights, 

590 ) 

591 loss.backward() 

592 optimizer.step() 

593 

594 running_loss += float(loss.item()) * len(batch_features) 

595 sample_count += len(batch_features) 

596 

597 if scheduler is not None and sample_count: # an epoch with no batch made no optimizer step (torch warns) 

598 scheduler.step() 

599 

600 model.eval() 

601 with torch.no_grad(): 

602 validation_outputs = model(validation_features) 

603 validation_loss = compute_combined_multitask_loss( 

604 validation_outputs, 

605 validation_targets, 

606 direction_criterion, 

607 magnitude_loss_weight, 

608 volatility_loss_weight, 

609 horizon_head_config, 

610 direction_loss_weight, 

611 consistency_loss_weight, 

612 date_group_ids=validation_date_group_ids, 

613 ranking_loss_config=ranking_loss_config, 

614 ) 

615 # validation_direction_metrics is always computed and recorded 

616 # for diagnostics regardless of what's actually monitored below 

617 # (see monitor_rank_ic's assignment above for the monitoring 

618 # decision itself). 

619 validation_direction_metrics = compute_binary_metrics( 

620 validation_outputs["direction"], validation_targets["direction"], direction_criterion, decision_threshold 

621 ) 

622 

623 validation_head_ic = None 

624 if monitor_rank_ic: 

625 _column, _kind, head_stride = head_specs[early_stop_head] 

626 non_overlapping_stride = head_stride if early_stop_metric == "rank_ic_non_overlapping" else 1 

627 validation_head_ic = compute_rank_ic( 

628 validation_outputs[early_stop_head], 

629 validation_targets[early_stop_head], 

630 validation_frame["date"], 

631 non_overlapping_stride=non_overlapping_stride, 

632 ) 

633 

634 history_entry = { 

635 "epoch": epoch, 

636 "train_loss": running_loss / max(sample_count, 1), 

637 "validation_loss": float(validation_loss.item()), 

638 "validation_direction_balanced_accuracy": validation_direction_metrics["balanced_accuracy"], 

639 } 

640 if validation_head_ic is not None: 

641 history_entry[monitored_metric_key] = validation_head_ic["mean_ic"] 

642 # Backward-compat key, kept exactly as before, for any 

643 # existing dashboard/consumer reading this specific name 

644 # when monitoring rank_20d via the original "rank_ic" mode. 

645 if early_stop_metric == "rank_ic" and early_stop_head == "rank_20d": 

646 history_entry["validation_rank_20d_mean_ic"] = validation_head_ic["mean_ic"] 

647 history.append(history_entry) 

648 

649 if monitor_rank_ic: 

650 smoothed = smoothed_metric(history, monitored_metric_key, early_stop_smoothing_epochs) 

651 candidate_metric = smoothed if smoothed is not None else -float(validation_loss.item()) 

652 else: 

653 candidate_metric = -float(validation_loss.item()) 

654 

655 if swa_enabled and swa_start_epoch is not None and epoch >= swa_start_epoch: 

656 swa_state, swa_count = swa_accumulate(swa_state, model.state_dict(), swa_count) 

657 

658 if is_new_best_epoch(candidate_metric, best_validation_metric, epoch, min_best_epoch): 

659 best_validation_metric = candidate_metric 

660 best_epoch = epoch 

661 best_state = copy.deepcopy(model.state_dict()) 

662 epochs_without_improvement = 0 

663 else: 

664 epochs_without_improvement += 1 

665 

666 if epoch >= min_best_epoch and epochs_without_improvement >= patience: 

667 break 

668 

669 # V5.1 Phase 3 (item 10) - SWA (when enabled and at least one epoch 

670 # was accumulated) REPLACES the single best-validation-epoch 

671 # checkpoint with the averaged tail-of-training weights - see 

672 # swa_accumulate()'s docstring for why this is a valid, different 

673 # technique from the ensemble-averaging this codebase already 

674 # rejects. best_epoch is left as whatever epoch loop variable value 

675 # it last held (informational only in this branch - "best_epoch" 

676 # stops meaning "the single checkpoint used" once SWA is active, 

677 # see the swa metrics block below for the authoritative record). 

678 if swa_enabled and swa_state is not None: 

679 best_state = swa_finalize(swa_state) 

680 elif best_state is None: 

681 best_state = copy.deepcopy(model.state_dict()) 

682 best_epoch = len(history) 

683 

684 model.load_state_dict(best_state) 

685 model.eval() 

686 with torch.no_grad(): 

687 validation_outputs_for_threshold = model(validation_features) 

688 tuned_threshold, tuned_validation_direction_metrics = find_optimal_threshold( 

689 validation_outputs_for_threshold["direction"], 

690 validation_targets["direction"], 

691 direction_criterion, 

692 threshold_metric, 

693 threshold_min, 

694 threshold_max, 

695 threshold_steps, 

696 ) 

697 # Each binary horizon head gets its OWN tuned threshold from its own 

698 # validation logit distribution - see find_optimal_masked_threshold()'s 

699 # docstring for why reusing the primary head's threshold is wrong. 

700 head_thresholds = {"direction": tuned_threshold} 

701 for head_name, (_column, kind, _stride) in head_specs.items(): 

702 if kind != "binary" or not horizon_head_config[head_name].get("enabled", True): 

703 continue 

704 head_threshold, _head_metrics = find_optimal_masked_threshold( 

705 validation_outputs_for_threshold[head_name], 

706 validation_targets[head_name], 

707 direction_criterion, 

708 threshold_metric, 

709 threshold_min, 

710 threshold_max, 

711 threshold_steps, 

712 ) 

713 head_thresholds[head_name] = head_threshold if head_threshold is not None else 0.5 

714 

715 train_features_device = train_features.to(device) 

716 train_targets_device = {name: tensor.to(device) for name, tensor in train_targets.items()} 

717 backtest_features, backtest_targets = frame_to_multitask_tensors(backtest_frame, feature_names, head_specs) 

718 backtest_features = backtest_features.to(device) 

719 backtest_targets = {name: tensor.to(device) for name, tensor in backtest_targets.items()} 

720 

721 trained_at = datetime.now(timezone.utc).isoformat() 

722 # V5.1 Phase 4 (items 7, 12) - net-performance simulation context, 

723 # only meaningful for the BACKTEST split (same convention as 

724 # ranking_promotion_config below). Config-gated: an absent/disabled 

725 # phase1.target.ranking.net_performance block leaves 

726 # net_performance_context None, and compute_multitask_metrics() 

727 # then writes no *_net_performance key at all - zero behavior 

728 # change for anyone not opting in. 

729 net_performance_config = full_config.get("phase1", {}).get("target", {}).get("ranking", {}).get( 

730 "net_performance", {} 

731 ) 

732 net_performance_context = ( 

733 { 

734 "raw_frame": backtest_frame, 

735 "net_performance_config": net_performance_config, 

736 "sector_by_ticker": load_sector_mapping(full_config), 

737 "head": str(net_performance_config.get("head", "rank_20d")), 

738 "full_config": full_config, 

739 } 

740 if net_performance_config.get("enabled", False) 

741 else None 

742 ) 

743 

744 metrics = { 

745 "project": "aether_quant", 

746 "phase": "multitask_direction_magnitude_volatility_horizons", 

747 "version_id": args.version_id, 

748 "trained_at": trained_at, 

749 "row_counts": { 

750 "train": int(len(train_frame)), 

751 "validation": int(len(validation_frame)), 

752 "backtest": int(len(backtest_frame)), 

753 }, 

754 "seed": seed, 

755 "best_epoch": best_epoch, 

756 "early_stop_metric": f"{early_stop_head}_ic" if monitor_rank_ic else "validation_loss", 

757 "epochs_ran": len(history), 

758 "loss_weights": { 

759 "magnitude_loss_weight": magnitude_loss_weight, 

760 "volatility_loss_weight": volatility_loss_weight, 

761 }, 

762 # V5.1 Phase 3 (items 1, 10, 11) - the training recipe actually 

763 # used for this candidate, so "which model am I looking at" is 

764 # answerable from the artifact alone (see 

765 # src/components/neuralnet/TrainingRecipePanel.tsx). 

766 "training_recipe": { 

767 "optimizer": str(training_config.get("optimizer", "adam")), 

768 "lr_schedule": str(training_config.get("lr_schedule", "none")), 

769 "batch_mode": batch_mode, 

770 "ranking_loss": ranking_loss_config, 

771 "swa": {"enabled": swa_enabled, "epochs_averaged": swa_count if swa_enabled else 0}, 

772 "early_stop_metric": early_stop_metric, 

773 "early_stop_head": early_stop_head, 

774 "early_stop_smoothing_epochs": early_stop_smoothing_epochs, 

775 }, 

776 "horizon_heads": horizon_head_config, 

777 "threshold_optimization": { 

778 "metric": threshold_metric, 

779 "default_threshold": decision_threshold, 

780 "selected_threshold": tuned_threshold, 

781 "selected_validation_metrics": tuned_validation_direction_metrics, 

782 "head_thresholds": head_thresholds, 

783 }, 

784 "train": compute_multitask_metrics( 

785 model, train_features_device, train_targets_device, train_frame["date"], 

786 direction_criterion, tuned_threshold, head_thresholds, horizon_head_config, 

787 ), 

788 "validation": compute_multitask_metrics( 

789 model, validation_features, validation_targets, validation_frame["date"], 

790 direction_criterion, tuned_threshold, head_thresholds, horizon_head_config, 

791 ), 

792 "backtest": compute_multitask_metrics( 

793 model, backtest_features, backtest_targets, backtest_frame["date"], 

794 direction_criterion, tuned_threshold, head_thresholds, horizon_head_config, 

795 ranking_promotion_config=full_config, 

796 net_performance_context=net_performance_context, 

797 ), 

798 "history": history, 

799 } 

800 # Stage 5 of the rank-pivot roadmap (development/Problems.md#43): 

801 # actually invokes purged_embargoed_folds() via 

802 # compute_purged_cv_rank_ic_diagnostic() - see that function's 

803 # docstring for why phase1.target.ranking.purged_cv.enabled was 

804 # previously dead configuration (zero call sites). Evaluates the 

805 # SAME already-trained model over the TRAIN split's own purged/ 

806 # embargoed folds - no extra training. Only runs when the rank_20d 

807 # head itself is enabled (an IC diagnostic for a disabled head is 

808 # meaningless). 

809 purged_cv_config = full_config.get("phase1", {}).get("target", {}).get("ranking", {}).get("purged_cv", {}) 

810 if purged_cv_config.get("enabled", False) and horizon_head_config["rank_20d"].get("enabled", True): 

811 model.eval() 

812 with torch.no_grad(): 

813 train_outputs_for_purged_cv = model(train_features_device) 

814 metrics["purged_cv_rank_20d"] = compute_purged_cv_rank_ic_diagnostic( 

815 train_outputs_for_purged_cv["rank_20d"], 

816 train_targets_device["rank_20d"], 

817 train_frame["date"], 

818 n_folds=int(purged_cv_config.get("n_folds", 5)), 

819 horizon_days=20, 

820 embargo_days=int(purged_cv_config.get("embargo_days", 5)), 

821 ) 

822 metrics["magnitude_quality"] = assess_regression_quality( 

823 { 

824 "train": metrics["train"]["magnitude"], 

825 "validation": metrics["validation"]["magnitude"], 

826 "backtest": metrics["backtest"]["magnitude"], 

827 }, 

828 training_config, 

829 ) 

830 metrics["volatility_quality"] = assess_regression_quality( 

831 { 

832 "train": metrics["train"]["volatility"], 

833 "validation": metrics["validation"]["volatility"], 

834 "backtest": metrics["backtest"]["volatility"], 

835 }, 

836 training_config, 

837 ) 

838 

839 model_payload = { 

840 "project": "Aether Quant", 

841 "phase": "v2_multitask_horizons_model", 

842 "version_id": args.version_id, 

843 "status": "trained", 

844 "trained_at": trained_at, 

845 "model": { 

846 "type": "multitask_direction_magnitude_volatility_horizons", 

847 "model_input_features": feature_names, 

848 "hidden_layers": hidden_layers, 

849 "dropout": dropout, 

850 "activation": activation, 

851 "normalization": normalization, 

852 "decision_threshold": tuned_threshold, 

853 }, 

854 "export": export_multitask_horizons_architecture(model) | {"state_dict": export_state_dict(model)}, 

855 } 

856 feature_schema_payload = {"model_input_names": feature_names} 

857 if cross_sectional_settings is not None: 

858 feature_schema_payload["cross_sectional_inputs"] = cross_sectional_settings 

859 

860 paths = multitask_candidate_output_paths(args.version_id) 

861 paths["version_dir"].mkdir(parents=True, exist_ok=True) 

862 paths["multitask_model"].write_text(json.dumps(model_payload, indent=2), encoding="utf-8") 

863 paths["multitask_feature_schema"].write_text(json.dumps(feature_schema_payload, indent=2), encoding="utf-8") 

864 paths["multitask_training_metrics"].write_text(json.dumps(metrics, indent=2), encoding="utf-8") 

865 if args.log_peak_memory: 

866 log_peak(Path(args.log_peak_memory), "multitask", profile=profile.name) 

867 

868 rank_5d_ic = metrics["backtest"].get("rank_5d_ic") or {} 

869 LOGGER.info( 

870 "train_multitask: wrote multitask artifacts for version %s " 

871 "(backtest direction mcc=%.4f, magnitude mae=%.6f [%s], volatility mae=%.6f [%s], " 

872 "rank_5d mean_ic=%.4f t_stat=%.2f).", 

873 args.version_id, 

874 metrics["backtest"]["direction"]["mcc"], 

875 metrics["backtest"]["magnitude"]["mae"], 

876 metrics["magnitude_quality"]["quality_status"], 

877 metrics["backtest"]["volatility"]["mae"], 

878 metrics["volatility_quality"]["quality_status"], 

879 rank_5d_ic.get("mean_ic", 0.0), 

880 rank_5d_ic.get("t_stat", 0.0), 

881 ) 

882 return 0 

883 except Exception as exc: # never let an unexpected failure look ambiguous to the caller 

884 LOGGER.error("train_multitask: unexpected failure - %s", exc) 

885 return 1 

886 

887 

888if __name__ == "__main__": 

889 sys.exit(main())