Coverage for evaluation/model_predictions.py: 100%
116 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"""Loads an exported model (ml/{multitask,sequence}_model.json) plus the
2active dataset, and runs every row through inference/exported_model.py -
3the EXACT torch-free interpreter main.py's live decision path uses - to
4produce a predicted-<head> column. Deliberately its own module, not
5train.py: train.py imports torch, and `aq evaluate` must stay fast to
6start for commands that never need training-time code (this package's
7torch-free contract - see evaluation/__init__.py's docstring).
9Because this reuses inference/exported_model.py verbatim (not a
10re-derived approximation), `aq evaluate --rank-book` reports the SAME
11numbers a live/backtest run would produce from the same artifacts -
12including any live quirk in those artifacts (e.g. Problems.md #73's
13sigmoid-vs-raw mismatch), which is the point: this is meant to be an
14offline mirror of live behavior, not a separate idealized model.
15"""
17from __future__ import annotations
19import numpy as np
20import pandas as pd
22from inference.exported_model import (
23 export_input_names,
24 resolve_sequence_window_size,
25 run_exported_multitask_model,
26 run_exported_multitask_model_rows,
27 run_exported_sequence_multitask_model,
28 run_exported_sequence_multitask_model_batched,
29)
31BATCH_CHUNK_ROWS = 256
34def build_sequence_windows(
35 dataset: pd.DataFrame,
36 model_input_names: list[str],
37 window_size: int,
38 ticker_column: str = "ticker",
39 row_positions: np.ndarray | None = None,
40) -> np.ndarray:
41 """Torch-free port of train.py::build_sequence_tensor_dataset() - same
42 algorithm (each ticker's own trailing window, left-padded with zeros
43 for rows with fewer than window_size preceding rows, row-order-aligned
44 with `dataset`), deliberately duplicated rather than imported since
45 train.py pulls in torch and this module must stay import-light.
46 `dataset` must already be sorted the way build_feature_dataset() leaves
47 it (each ticker's own rows in chronological order) - the same
48 precondition train.py's version documents.
50 float32, not float64 (V5.1 Phase 5, Problems.md #83) - halves peak
51 memory for no correctness cost: every consumer (run_exported_sequence_
52 multitask_model()) takes `sequence: list[list[float]]` and converts via
53 .tolist() before use, so the underlying numpy dtype is invisible to it
54 either way. Matches train.py::build_sequence_tensor_dataset()'s own
55 dtype, which was already float32.
57 `row_positions` (V5.6.0): build windows ONLY for these row positions (output row i is the window of
58 `dataset` row `row_positions[i]`, still drawn from every preceding row of that ticker) - a
59 reconciliation that needs ~8k of 100k+ context rows allocates 8k windows, not 100k (~0.8 GB)."""
60 feature_matrix = dataset[model_input_names].to_numpy(dtype=np.float32)
61 tickers = dataset[ticker_column].to_numpy()
63 wanted = None if row_positions is None else {int(position): slot for slot, position in enumerate(row_positions)}
64 windows = np.zeros(
65 (len(dataset) if wanted is None else len(wanted), window_size, len(model_input_names)), dtype=np.float32
66 )
67 positions_by_ticker: dict[object, list[int]] = {}
68 for position, ticker in enumerate(tickers):
69 positions_by_ticker.setdefault(ticker, []).append(position)
71 for positions in positions_by_ticker.values():
72 for index_within_ticker, position in enumerate(positions):
73 if wanted is None:
74 slot = position
75 elif position in wanted:
76 slot = wanted[position]
77 else:
78 continue
79 window_start = max(0, index_within_ticker + 1 - window_size)
80 window_positions = positions[window_start : index_within_ticker + 1]
81 window_values = feature_matrix[window_positions]
82 windows[slot, -len(window_values) :, :] = window_values
84 return windows
87def select_context_date_range(
88 dataset: pd.DataFrame,
89 recorded_dates: list[str],
90 *,
91 window_size: int,
92 ticker_column: str = "ticker",
93 date_column: str = "date",
94) -> tuple[str, str]:
95 """V5.2.2 (development/Problems.md) - computes the inclusive
96 `(min_date, max_date)` date-string bounds a caller must keep every
97 row for (per ticker, in `dataset`'s own row order) before restricting
98 the dataset to a specific set of `recorded_dates` and still getting
99 CORRECT `build_sequence_windows()` output for those dates.
101 GUARDRAIL: `build_sequence_windows()` builds each ticker's trailing
102 window from ORDINAL ROW POSITION within whatever frame it's given,
103 not from calendar dates - it has no way to know rows were dropped.
104 Naively filtering `dataset` down to only `recorded_dates` before
105 calling it does not raise; it silently builds each window from
106 whichever OTHER kept rows happen to be ordinally adjacent (e.g. 10
107 calendar days apart instead of 1), producing wrong predictions with
108 no error. This function exists so a caller can safely narrow a large
109 dataset to just the date range a reconciliation actually needs
110 (`aq evaluate --reconcile-book-history`'s whole reason for existing)
111 without corrupting sequence-model context: keep every row inside
112 `[min(recorded_dates), max(recorded_dates)]` UNCHANGED, plus enough
113 additional rows per ticker immediately preceding that span (by row
114 position, not calendar-day subtraction, since non-trading days never
115 appear in `dataset` to begin with) to fully support a `window_size`
116 trailing window for the earliest recorded date. Only rows entirely
117 outside the returned bounds may be safely dropped.
119 Per ticker: finds the first row at/after `min(recorded_dates)`, then
120 walks back `window_size` positions (mirroring `build_sequence_windows()`'s
121 own `max(0, index_within_ticker + 1 - window_size)` formula exactly)
122 to find that ticker's own earliest-needed date. The overall
123 `min_date` returned is the EARLIEST such date across all tickers, so
124 every ticker's window is fully supported, not just the first one
125 encountered. A ticker with no rows at/after `min(recorded_dates)` at
126 all is skipped (nothing to support for it).
128 Raises `ValueError` if `recorded_dates` is empty - there is no
129 context range to compute without at least one target date."""
130 if not recorded_dates:
131 raise ValueError("select_context_date_range() requires at least one recorded date")
133 target_min = min(recorded_dates)
134 target_max = max(recorded_dates)
136 earliest_needed_dates: list[str] = []
137 for _ticker, ticker_frame in dataset.groupby(ticker_column, sort=False):
138 ticker_dates = ticker_frame[date_column].tolist()
139 boundary_index = next((i for i, d in enumerate(ticker_dates) if d >= target_min), None)
140 if boundary_index is None:
141 continue
142 lookback_start = max(0, boundary_index + 1 - window_size)
143 earliest_needed_dates.append(ticker_dates[lookback_start])
145 min_date = min(earliest_needed_dates) if earliest_needed_dates else target_min
146 return min_date, target_max
149def predict_multitask_head(
150 dataset: pd.DataFrame, model_export: dict, feature_names: list[str], head: str, row_mask: np.ndarray | None = None
151) -> np.ndarray:
152 """One run_exported_multitask_model() call per row - the flat-MLP
153 trunk needs no windowing, unlike the sequence model below. `row_mask`
154 (bool, optional): predict only these rows; the rest stay NaN."""
155 predictions = np.full(len(dataset), np.nan, dtype=np.float64)
156 feature_matrix = dataset[feature_names].to_numpy(dtype=np.float64)
157 for row_index in range(len(dataset)) if row_mask is None else np.flatnonzero(row_mask):
158 outputs = run_exported_multitask_model(model_export, feature_matrix[row_index].tolist())
159 predictions[row_index] = outputs.get(head, np.nan)
160 return predictions
163def predict_sequence_head(
164 dataset: pd.DataFrame,
165 model_export: dict,
166 feature_names: list[str],
167 head: str,
168 *,
169 sequence_feature_schema: dict | None = None,
170 configured_window_size: int = 30,
171 ticker_column: str = "ticker",
172 row_mask: np.ndarray | None = None,
173) -> np.ndarray:
174 """Builds each row's trailing window via build_sequence_windows() then
175 runs run_exported_sequence_multitask_model() per row. window_size comes
176 from resolve_sequence_window_size() - the trained model's OWN schema
177 wins over any configured default, the same shape-mismatch-avoidance
178 contract main.py's live sequence-model path already follows."""
179 window_size = resolve_sequence_window_size(sequence_feature_schema, configured_window_size)
180 predictions = np.full(len(dataset), np.nan, dtype=np.float64)
181 if row_mask is None:
182 windows = build_sequence_windows(dataset, feature_names, window_size, ticker_column)
183 for row_index in range(len(dataset)):
184 outputs = run_exported_sequence_multitask_model(model_export, windows[row_index].tolist())
185 predictions[row_index] = outputs.get(head, np.nan)
186 return predictions
187 row_positions = np.flatnonzero(row_mask)
188 windows = build_sequence_windows(dataset, feature_names, window_size, ticker_column, row_positions=row_positions)
189 for slot, row_index in enumerate(row_positions):
190 outputs = run_exported_sequence_multitask_model(model_export, windows[slot].tolist())
191 predictions[row_index] = outputs.get(head, np.nan)
192 return predictions
195def predict_heads(
196 dataset: pd.DataFrame,
197 model_export: dict,
198 feature_names: list[str],
199 heads: list[str],
200 *,
201 model_kind: str,
202 sequence_feature_schema: dict | None = None,
203 configured_window_size: int = 30,
204 ticker_column: str = "ticker",
205 row_mask: np.ndarray | None = None,
206 batched: bool = False,
207) -> dict[str, np.ndarray]:
208 """Every requested head from ONE interpreter pass per row. predict_head() re-runs the whole model for each head
209 (the interpreter returns all heads per call and one is kept), so N heads cost N passes; this costs one, with
210 bit-identical values. Same conventions: unknown head -> NaN, `row_mask` rows only (rest NaN)."""
211 if model_kind not in {"multitask", "sequence"}:
212 raise ValueError(f"unknown model_kind {model_kind!r} - expected 'multitask' or 'sequence'")
213 # V6.2.0: the export's own input list wins (a feature-subset model), as main.py's model_input_index does live
214 feature_names = export_input_names(model_export, feature_names)
215 predictions = {head: np.full(len(dataset), np.nan, dtype=np.float64) for head in heads}
216 if batched:
217 return _predict_heads_batched(
218 dataset, model_export, feature_names, heads, predictions, model_kind=model_kind,
219 sequence_feature_schema=sequence_feature_schema, configured_window_size=configured_window_size,
220 ticker_column=ticker_column, row_mask=row_mask,
221 )
222 if model_kind == "multitask":
223 feature_matrix = dataset[feature_names].to_numpy(dtype=np.float64)
224 row_indices = np.arange(len(dataset)) if row_mask is None else np.flatnonzero(row_mask)
225 for row_index in row_indices:
226 outputs = run_exported_multitask_model(model_export, feature_matrix[row_index].tolist())
227 for head in heads:
228 predictions[head][row_index] = outputs.get(head, np.nan)
229 return predictions
230 window_size = resolve_sequence_window_size(sequence_feature_schema, configured_window_size)
231 row_indices = np.arange(len(dataset)) if row_mask is None else np.flatnonzero(row_mask)
232 windows = build_sequence_windows(
233 dataset, feature_names, window_size, ticker_column, row_positions=None if row_mask is None else row_indices
234 )
235 for slot, row_index in enumerate(row_indices):
236 outputs = run_exported_sequence_multitask_model(model_export, windows[slot].tolist())
237 for head in heads:
238 predictions[head][row_index] = outputs.get(head, np.nan)
239 return predictions
242def _predict_heads_batched(
243 dataset, model_export, feature_names, heads, predictions, *, model_kind, sequence_feature_schema,
244 configured_window_size, ticker_column, row_mask,
245) -> dict[str, np.ndarray]:
246 """V5.8.0: predict_heads() through the batched interpreters in chunks of BATCH_CHUNK_ROWS rows. Values equal the
247 per-row path to ~1e-15 (matmul summation order); memory is one chunk of windows, not the whole split's
248 (rows, window, features) tensor (~0.6 GB for a 2-year split), and the interpreter runs once per layer per chunk
249 instead of once per row, which is what made an as-live scoring pass take ten minutes."""
250 row_indices = np.arange(len(dataset)) if row_mask is None else np.flatnonzero(row_mask)
251 if model_kind == "multitask":
252 feature_matrix = dataset[feature_names].to_numpy(dtype=np.float64)
253 for start in range(0, len(row_indices), BATCH_CHUNK_ROWS):
254 chunk = row_indices[start : start + BATCH_CHUNK_ROWS]
255 outputs = run_exported_multitask_model_rows(model_export, feature_matrix[chunk].tolist())
256 for row_index, row_outputs in zip(chunk, outputs, strict=False):
257 for head in heads:
258 predictions[head][row_index] = row_outputs.get(head, np.nan)
259 return predictions
260 window_size = resolve_sequence_window_size(sequence_feature_schema, configured_window_size)
261 for start in range(0, len(row_indices), BATCH_CHUNK_ROWS):
262 chunk = row_indices[start : start + BATCH_CHUNK_ROWS]
263 windows = build_sequence_windows(dataset, feature_names, window_size, ticker_column, row_positions=chunk)
264 outputs = run_exported_sequence_multitask_model_batched(model_export, windows.tolist())
265 for row_index, row_outputs in zip(chunk, outputs, strict=False):
266 for head in heads:
267 predictions[head][row_index] = (row_outputs or {}).get(head, np.nan)
268 return predictions
271def predict_head(
272 dataset: pd.DataFrame,
273 model_export: dict,
274 feature_names: list[str],
275 head: str,
276 *,
277 model_kind: str,
278 sequence_feature_schema: dict | None = None,
279 configured_window_size: int = 30,
280 ticker_column: str = "ticker",
281 row_mask: np.ndarray | None = None,
282) -> np.ndarray:
283 """Single dispatch point for `aq evaluate` - model_kind in
284 {"multitask", "sequence"} picks the right predictor above. Any other
285 value raises ValueError (a genuinely programmer-facing error, not a
286 runtime degradation case - unlike every other function in this
287 package, this one is not on main.py's live path)."""
288 if model_kind == "multitask":
289 return predict_multitask_head(dataset, model_export, feature_names, head, row_mask=row_mask)
290 if model_kind == "sequence":
291 return predict_sequence_head(
292 dataset, model_export, feature_names, head,
293 sequence_feature_schema=sequence_feature_schema,
294 configured_window_size=configured_window_size,
295 ticker_column=ticker_column,
296 row_mask=row_mask,
297 )
298 raise ValueError(f"unknown model_kind {model_kind!r} - expected 'multitask' or 'sequence'")
301def predict_heads_ensemble(dataset: pd.DataFrame, model_exports: list[dict], feature_names: list[str], heads: list[str],
302 **kwargs) -> dict[str, np.ndarray]:
303 """predict_heads() averaged over the members of a seed ensemble (V6.1.0): the elementwise mean of each head's raw
304 output, NaN where any member is NaN - the array form of inference.exported_model.average_head_outputs."""
305 if not model_exports:
306 raise ValueError("predict_heads_ensemble needs at least one member export")
307 per_member = [predict_heads(dataset, export, feature_names, heads, **kwargs) for export in model_exports]
308 return {head: np.mean(np.stack([member[head] for member in per_member]), axis=0) for head in heads}