Coverage for lab/training_utils.py: 100%
92 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"""Training mechanics shared by the trainers and the lab (moved unchanged from train.py in V6.7.1): seeding, optimizer
2and scheduler, weight averaging, early stopping, whole-date batches. `train.py` re-exports every name.
3"""
5from __future__ import annotations
7import random
8from typing import Any
10import numpy as np
11import pandas as pd
12import torch
13from torch import nn
14from torch.utils.data import Sampler
17def set_seed(seed: int) -> None:
18 """Seed Python, numpy and torch (CPU and CUDA) for a reproducible run."""
19 random.seed(seed)
20 np.random.seed(seed)
21 torch.manual_seed(seed)
22 if torch.cuda.is_available():
23 torch.cuda.manual_seed_all(seed)
26# ---------------------------------------------------------------------------
27# V5.1 Phase 3 (items 10, 11) - optimizer/schedule/SWA/smoothing helpers
28# shared by train_multitask.py and train_sequence.py (the train.py-as-
29# master-module convention every other trainer utility in this file
30# already follows).
31# ---------------------------------------------------------------------------
34def build_optimizer(model: nn.Module, training_config: dict[str, Any]) -> torch.optim.Optimizer:
35 """Dispatches on training_config["optimizer"] in {"adam", "adamw"} -
36 "adam" is the FUNCTION default (preserving every existing caller's
37 behavior byte-for-byte when the config key is absent), "adamw" is
38 config.json's new default for the multitask/sequence trainers
39 specifically.
41 GUARDRAIL: weight_decay under AdamW is DECOUPLED from the learning
42 rate (Loshchilov & Hutter 2019) - not comparable to the same numeric
43 value under plain Adam (coupled, effectively scaled by lr).
44 config.json's weight_decay was re-tuned upward (1e-4 -> 1e-2)
45 specifically alongside this switch - never carry the old Adam-tuned
46 value over to AdamW unchanged."""
47 optimizer_name = str(training_config.get("optimizer", "adam")).lower()
48 learning_rate = float(training_config.get("learning_rate", 0.0007))
49 weight_decay = float(training_config.get("weight_decay", 0.0001))
50 if optimizer_name == "adamw":
51 return torch.optim.AdamW(model.parameters(), lr=learning_rate, weight_decay=weight_decay)
52 return torch.optim.Adam(model.parameters(), lr=learning_rate, weight_decay=weight_decay)
55def build_lr_scheduler(optimizer: torch.optim.Optimizer, training_config: dict[str, Any], max_epochs: int) -> torch.optim.lr_scheduler.LRScheduler | None:
56 """Dispatches on training_config["lr_schedule"] in {"none", "cosine"} -
57 "none" is the FUNCTION default (returns None - a caller that never
58 calls scheduler.step() is completely unaffected by this function
59 existing). "cosine" is config.json's new default: CosineAnnealingLR
60 decaying the optimizer's current LR down to lr * lr_min_factor over
61 max_epochs."""
62 schedule_name = str(training_config.get("lr_schedule", "none")).lower()
63 if schedule_name != "cosine":
64 return None
65 lr_min_factor = float(training_config.get("lr_min_factor", 0.05))
66 base_lr = float(optimizer.param_groups[0]["lr"])
67 return torch.optim.lr_scheduler.CosineAnnealingLR(
68 optimizer, T_max=max(int(max_epochs), 1), eta_min=base_lr * lr_min_factor
69 )
72def swa_accumulate(averaged_state: dict[str, Any] | None, model_state: dict[str, Any], count: int) -> tuple[dict, int]:
73 """Elementwise running mean over state_dict()s - a plain, from-scratch
74 accumulator, deliberately NOT torch.optim.swa_utils.AveragedModel.
76 GUARDRAIL: AveragedModel wraps the model with a `module.`-prefixed
77 state_dict, which would silently break export_state_dict()/
78 export_*_architecture() (both read the raw module's own keys). No
79 update_bn() pass is needed either - neither model has any BatchNorm
80 (LayerNorm only, which carries no running statistics to recompute).
82 GUARDRAIL (pre-empting the obvious objection): this is WITHIN-RUN
83 averaging of late-training checkpoints along a SINGLE SGD trajectory -
84 the weights are aligned by construction (same init, same optimizer
85 path, different epochs), which is the valid case (Izmailov et al.
86 2018, Stochastic Weight Averaging). This is NOT the CROSS-SEED weight
87 averaging average_ensemble_predictions()'s own docstring correctly
88 rejects on permutation-symmetry grounds (two independently-seeded
89 runs' hidden units are not aligned, so averaging THEIR weights is
90 invalid) - averaging one run's own late-epoch weights against itself
91 is a different, well-established technique. Do not conflate the two,
92 and do not "fix" this into calling average_ensemble_predictions()'s
93 machinery instead.
95 averaged_state=None (first call) seeds the accumulator with
96 model_state verbatim (count becomes 1, an exact copy - not yet an
97 "average" of anything). Returns (new_averaged_state, new_count)."""
98 if averaged_state is None:
99 return {key: value.clone() for key, value in model_state.items()}, 1
100 new_count = count + 1
101 new_averaged_state = {key: (averaged_state[key] * count + model_state[key]) / new_count for key in averaged_state}
102 return new_averaged_state, new_count
105def swa_finalize(averaged_state: dict[str, Any]) -> dict[str, Any]:
106 """No-op passthrough today, kept as a named step pairing with
107 swa_accumulate() in case a future normalization-recompute pass is ever
108 needed here (there is none currently - see swa_accumulate()'s own
109 docstring on why no update_bn() equivalent is needed)."""
110 return averaged_state
113def smoothed_metric(history: list[dict], key: str, window: int) -> float | None:
114 """Mean of the last `window` non-None values of history[i][key] - the
115 early-stopping monitor for a noisy per-epoch metric. A 365-day
116 validation split at stride 20 gives ~18 non-overlapping rank-IC
117 observations, so epoch-to-epoch that metric is noisy enough that
118 early-stopping on the RAW value reliably picks a lucky epoch rather
119 than a genuinely-better one. window=1 reproduces "monitor the raw
120 latest value" exactly (today's behavior, byte-for-byte).
122 Returns None (never 0.0 - a missing metric must not look like a
123 genuine zero) when no history entry has this key with a non-None
124 value yet."""
125 values = [entry[key] for entry in history if entry.get(key) is not None]
126 if not values:
127 return None
128 window = max(int(window), 1)
129 recent = values[-window:]
130 return sum(recent) / len(recent)
133def is_new_best_epoch(
134 candidate_metric: float,
135 best_metric_so_far: float,
136 epoch: int,
137 min_epoch: int = 3,
138) -> bool:
139 """Shared early-stopping decision for every direction-classification
140 trainer (train_model/_train_expert_classifier here; train_multitask.py/
141 train_sequence.py/train_gating.py call this too). Monitors a SKILL
142 metric (validation balanced_accuracy - higher is better), not raw
143 validation loss.
145 Root cause this fixes (development/Problems.md): with near-flat logits,
146 validation BCE loss was observed lowest at epoch 1 and rising every
147 epoch after - so the old "epoch with min validation loss" rule shipped
148 best_epoch=1 for the baseline, multitask AND sequence models alike: the
149 checkpoint shipped was essentially the random initialization. Loss and
150 balanced-accuracy are not the same surface - the network can still
151 improve its decision boundary (balanced-accuracy) for a few epochs even
152 while its calibration (BCE loss) degrades, which is exactly what a
153 near-noise label produces. `min_epoch` additionally refuses to
154 ship an epoch-1/2 checkpoint at all (returns False for epoch <
155 min_epoch), forcing at least a few real gradient updates before any
156 checkpoint becomes eligible, so a network that never improves past its
157 initialization is at least given the chance to."""
158 if epoch < min_epoch:
159 return False
160 return candidate_metric > best_metric_so_far
163# ---------------------------------------------------------------------------
164# V5.1 Phase 3 (items 1, 10, 11) - cross-sectional date batching, so a
165# training batch is a set of WHOLE dates (every asset trading that day)
166# rather than a random row sample - the ranking losses below need this to
167# compute a per-date rank/softmax, exactly the same grouping
168# build_cross_sectional_rank_targets()/_rank_ic_from_arrays() already use
169# offline. Pure numpy, no torch - fully unit-testable without a model.
170# ---------------------------------------------------------------------------
173def build_cross_sectional_date_batches(
174 dates: np.ndarray, *, batch_dates: int, min_group_size: int, shuffle: bool, seed: int
175) -> list[np.ndarray]:
176 """Groups row indices by date, drops dates with fewer than
177 min_group_size rows (same "too few names is meaningless" rationale as
178 build_cross_sectional_rank_targets()'s min_universe_size), then packs
179 `batch_dates` whole dates per batch. Returns a list of row-index arrays
180 (dtype int64) - each array is one training batch's row selection into
181 the ORIGINAL `dates` array (and, by extension, into a parallel
182 features/targets tensor built in the same row order).
184 shuffle=True shuffles the DATE order (not rows within a date - every
185 row of a kept date always lands in the same batch as its peers) with a
186 seeded RNG, so batch composition is reproducible per (seed, epoch).
187 shuffle=False keeps dates in their natural sorted order - deterministic,
188 used by validation/backtest passes that iterate the whole split once.
190 batch_dates <= 0 is treated as 1 (never an empty/negative batch)."""
191 batch_dates = max(int(batch_dates), 1)
192 frame = pd.DataFrame({"date": np.asarray(dates), "row": np.arange(len(dates))})
193 group_sizes = frame.groupby("date")["row"].transform("size")
194 eligible = frame[group_sizes >= min_group_size]
196 unique_dates = eligible["date"].unique().tolist()
197 if shuffle:
198 rng = np.random.default_rng(seed)
199 rng.shuffle(unique_dates)
200 else:
201 unique_dates = sorted(unique_dates)
203 rows_by_date = {date_value: group["row"].to_numpy(dtype=np.int64) for date_value, group in eligible.groupby("date")}
205 batches: list[np.ndarray] = []
206 for start in range(0, len(unique_dates), batch_dates):
207 chunk_dates = unique_dates[start : start + batch_dates]
208 batch_rows = np.concatenate([rows_by_date[date_value] for date_value in chunk_dates])
209 batches.append(batch_rows)
210 return batches
213class CrossSectionalDateBatchSampler(Sampler[list[int]]):
214 """torch Sampler wrapper around build_cross_sectional_date_batches() -
215 yields one list[int] (row indices) per whole-date batch, for use as
216 DataLoader's `batch_sampler`. set_epoch() re-derives the shuffle seed
217 per epoch (seed + epoch) so batch composition varies epoch to epoch
218 the same way a random-sampling DataLoader's shuffle=True already does,
219 while every batch still contains only whole dates."""
221 def __init__(self, dates: np.ndarray, *, batch_dates: int, min_group_size: int, shuffle: bool, seed: int) -> None:
222 self.dates = np.asarray(dates)
223 self.batch_dates = batch_dates
224 self.min_group_size = min_group_size
225 self.shuffle = shuffle
226 self.seed = seed
227 self.epoch = 0
229 def set_epoch(self, epoch: int) -> None:
230 self.epoch = epoch
232 def _batches(self) -> list[np.ndarray]:
233 return build_cross_sectional_date_batches(
234 self.dates,
235 batch_dates=self.batch_dates,
236 min_group_size=self.min_group_size,
237 shuffle=self.shuffle,
238 seed=self.seed + self.epoch,
239 )
241 def __iter__(self):
242 for batch in self._batches():
243 yield batch.tolist()
245 def __len__(self) -> int:
246 return len(self._batches())
249def build_date_group_ids(dates: np.ndarray) -> np.ndarray:
250 """Dense integer group id per row (0, 1, 2, ... one id per unique date,
251 in sorted-date order) - the ranking losses below scatter/loop by this
252 id rather than the raw date value (a torch.Tensor of ids is simpler to
253 index with than a tensor of dates/strings). Pure numpy, int64."""
254 _, inverse = np.unique(np.asarray(dates), return_inverse=True)
255 return inverse.astype(np.int64)
258def select_device(prefer: str = "auto") -> str:
259 """'cuda' when asked for (or 'auto') and available, else 'cpu'. The production trainers stay on CPU; the lab may use a GPU."""
260 if prefer == "cpu":
261 return "cpu"
262 if prefer in {"auto", "cuda"} and torch.cuda.is_available():
263 return "cuda"
264 if prefer == "cuda":
265 raise RuntimeError("train.device = cuda, but torch sees no CUDA device")
266 return "cpu"