Coverage for inference/exported_model.py: 100%

537 statements  

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

1"""Forward-pass inference over a JSON-exported model architecture. 

2 

3Extracted from `main.py`'s `_run_exported_model()`/`_linear()`/ 

4`_layernorm()`/`_sigmoid()` methods (Part C of the latency-optimization 

5pass) - those were already pure (no `self.*` state, only calling sibling 

6methods), just not free functions yet. Mirrors the existing pure-module 

7pattern in `risk/position_sizing.py`/`regime/market_regime.py`: free 

8functions, no class, package `__init__.py` re-export. 

9 

10Vectorized with numpy (the extraction was step 1; this is step 2) - this 

11ran once per symbol per bar, 5x (baseline + 4 experts), in plain Python 

12nested loops. `tests/test_exported_model.py` is the parity net: the same 

13hand-computed reference values from the pure-Python version must still 

14match within tolerance. 

15 

16Consumes the same `{"architecture": [...], "state_dict": {...}}` shape that 

17`monitoring/neural_network_state.py` independently parses for a different 

18purpose (layer/node/edge counts vs. an actual forward pass here). 

19""" 

20 

21from __future__ import annotations 

22 

23import math 

24from pathlib import Path 

25from typing import Any 

26 

27import numpy as np 

28 

29# Optional C++/pybind11 accelerator for _linear_batched() below (see 

30# cpp_inference/README.md and development/Problems.md #32) - never a hard 

31# dependency. Deferred import, same convention as ib_insync 

32# (data_pipeline/ib_backfill.py): absent/unbuilt on most machines, and 

33# _linear_batched() falls back to the NumPy einsum path on any 

34# import/call failure below, not just at this import site. 

35try: 

36 import cpp_inference as _cpp_inference 

37except ImportError: 

38 _cpp_inference = None 

39 

40 

41def run_exported_model(model_export: dict[str, Any], inputs: list[float]) -> float: 

42 """The exported network's forward pass in numpy (the torch-free path main.py uses): one input vector to one output.""" 

43 current = np.asarray(inputs, dtype=np.float64) 

44 for layer in model_export["export"]["architecture"]: 

45 layer_type = layer["type"] 

46 if layer_type == "linear": 

47 weights = model_export["export"]["state_dict"][layer["weight_key"]] 

48 bias = model_export["export"]["state_dict"][layer["bias_key"]] 

49 current = _linear(current, weights, bias) 

50 elif layer_type == "layernorm": 

51 weights = model_export["export"]["state_dict"][layer["weight_key"]] 

52 bias = model_export["export"]["state_dict"][layer["bias_key"]] 

53 current = _layernorm(current, weights, bias, float(layer.get("eps", 1e-5))) 

54 elif layer_type == "relu": 

55 current = np.maximum(current, 0.0) 

56 elif layer_type == "dropout": 

57 continue 

58 elif layer_type == "sigmoid": 

59 current = _sigmoid(current) 

60 else: 

61 raise ValueError(f"Unsupported layer type in export: {layer_type}") 

62 

63 return float(current[0]) 

64 

65 

66def run_exported_model_rows(model_export: dict[str, Any], rows: list[list[float]]) -> list[float]: 

67 """V5.8.0 (latency): run_exported_model() for N input rows of ONE shared model in a single matmul per layer 

68 (the per-symbol loop paid NumPy's per-call dispatch ~57 times a tick). Same layer set and the same result per row 

69 as run_exported_model() up to BLAS summation order (~1e-16); an empty list returns []. 

70 

71 Per-row semantics are kept for the layers that are not row-wise elementwise: layernorm normalises each row by its 

72 own mean/variance (axis=-1) with the one shared weight/bias.""" 

73 if not rows: 

74 return [] 

75 export = model_export["export"] 

76 current = _run_layer_stack_shared_batched(export["architecture"], export["state_dict"], np.asarray(rows, dtype=np.float64)) 

77 return [float(value) for value in current[:, 0]] 

78 

79 

80def run_exported_multitask_model_rows(model_export: dict[str, Any], rows: list[list[float]]) -> list[dict[str, float]]: 

81 """V5.8.0 (latency): run_exported_multitask_model() for N rows of ONE shared model — the trunk once for all rows, 

82 then each head once for all rows. Returns one {head: value} dict per row, same keys as the per-row function.""" 

83 if not rows: 

84 return [] 

85 export = model_export["export"] 

86 state_dict = export["state_dict"] 

87 trunk_output = _run_layer_stack_shared_batched(export["trunk"], state_dict, np.asarray(rows, dtype=np.float64)) 

88 head_outputs = { 

89 head_name: _run_layer_stack_shared_batched(head_layers, state_dict, trunk_output.copy())[:, 0] 

90 for head_name, head_layers in export["heads"].items() 

91 } 

92 return [{head_name: float(values[index]) for head_name, values in head_outputs.items()} for index in range(len(rows))] 

93 

94 

95def convert_state_dict_arrays(export: dict[str, Any]) -> None: 

96 """Converts every value in export["export"]["state_dict"] from a plain 

97 Python list to a np.float64 ndarray, IN PLACE - call this ONCE, right 

98 after a model export is loaded from JSON (see main.py's various 

99 `_load_*` methods), not on every inference call. 

100 

101 Every `_linear`/`_layernorm`/`_layernorm_axis`/`_conv1d_causal`/ 

102 `_run_batched_layer_stack` call below still runs `np.asarray(value, 

103 dtype=np.float64)` on state_dict values - that line is NOT removed, 

104 since `tests/test_exported_model.py` passes raw Python lists directly 

105 and must keep working. What changes is the cost: `np.asarray()` on an 

106 ndarray that already has the right dtype is a documented no-op (same 

107 object returned, no copy) - so calling this once at load time turns 

108 every later `np.asarray()` call on that export's weights into a cheap 

109 identity check instead of a real list-to-array conversion, which 

110 profiling (`scripts/profile_inference.py`) found was the single 

111 largest remaining cost in the per-bar inference hot path after the 

112 expert-batching/conv1d-vectorization pass (116.9s of 290.6s - see 

113 development/Problems.md). 

114 

115 Safe to call on any export shape this module consumes: flat 

116 (`{"architecture": [...], "state_dict": {...}}`), branching multitask 

117 (`{"trunk": [...], "heads": {...}, "state_dict": {...}}`), and 

118 sequence (same branching shape, `state_dict` may hold conv1d weight 

119 tensors - `np.asarray` on those still round-trips through the same 

120 no-op-when-already-array path). Never raises on a missing/malformed 

121 "state_dict" key - degrades to a no-op, since main.py's loaders 

122 already handle malformed exports via their own try/except.""" 

123 state_dict = export.get("export", {}).get("state_dict") 

124 if not isinstance(state_dict, dict): 

125 return 

126 for key, value in state_dict.items(): 

127 if not isinstance(value, np.ndarray): 

128 state_dict[key] = np.asarray(value, dtype=np.float64) 

129 

130 

131def _linear(inputs, weights: list[list[float]], bias: list[float]) -> np.ndarray: 

132 inputs_array = np.asarray(inputs, dtype=np.float64) 

133 weights_array = np.asarray(weights, dtype=np.float64) 

134 bias_array = np.asarray(bias, dtype=np.float64) 

135 return weights_array @ inputs_array + bias_array 

136 

137 

138def _layernorm(values, weights: list[float], bias: list[float], eps: float) -> np.ndarray: 

139 values_array = np.asarray(values, dtype=np.float64) 

140 mean_value = values_array.mean() 

141 variance = values_array.var() 

142 denominator = np.sqrt(variance + eps) 

143 normalized = (values_array - mean_value) / denominator 

144 return normalized * np.asarray(weights, dtype=np.float64) + np.asarray(bias, dtype=np.float64) 

145 

146 

147def _sigmoid(value): 

148 clipped = np.clip(value, -60.0, 60.0) 

149 return 1.0 / (1.0 + np.exp(-clipped)) 

150 

151 

152def _softplus(value): 

153 """Numerically stable softplus: log(1+e^x) = log1p(e^-|x|) + max(x, 0). 

154 Used only by the volatility head below - guarantees a strictly 

155 non-negative volatility prediction without the overflow risk of a 

156 naive log(1 + exp(x)) for large positive x.""" 

157 array = np.asarray(value, dtype=np.float64) 

158 return np.log1p(np.exp(-np.abs(array))) + np.maximum(array, 0.0) 

159 

160 

161def _run_layer_stack(layers: list[dict], state_dict: dict[str, Any], current: np.ndarray) -> np.ndarray: 

162 """Shared per-layer forward pass, used only by run_exported_multitask_model() 

163 below - run_exported_model() above stays untouched (same layer-loop shape, 

164 duplicated rather than shared, so the original interpreter carries zero 

165 risk from this addition). Supports the same layer set as run_exported_model() 

166 plus "softplus" for the volatility head; trunks/heads are deliberately 

167 restricted to relu/layernorm/dropout/sigmoid/softplus (never gelu/silu/ 

168 batchnorm1d), mirroring train_gating.py's existing restriction for the 

169 same reason - this interpreter cannot run those layer types.""" 

170 for layer in layers: 

171 layer_type = layer["type"] 

172 if layer_type == "linear": 

173 weights = state_dict[layer["weight_key"]] 

174 bias = state_dict[layer["bias_key"]] 

175 current = _linear(current, weights, bias) 

176 elif layer_type == "layernorm": 

177 weights = state_dict[layer["weight_key"]] 

178 bias = state_dict[layer["bias_key"]] 

179 current = _layernorm(current, weights, bias, float(layer.get("eps", 1e-5))) 

180 elif layer_type == "relu": 

181 current = np.maximum(current, 0.0) 

182 elif layer_type == "dropout": 

183 continue 

184 elif layer_type == "sigmoid": 

185 current = _sigmoid(current) 

186 elif layer_type == "softplus": 

187 current = _softplus(current) 

188 else: 

189 raise ValueError(f"Unsupported layer type in export: {layer_type}") 

190 return current 

191 

192 

193# --------------------------------------------------------------------------- 

194# Batched inference across multiple SAME-ARCHITECTURE models sharing one 

195# input (main.py's 4-expert loop / 4-multitask-expert loop) - one NumPy call 

196# per layer across all N stacked models instead of N separate 

197# run_exported_model()/run_exported_multitask_model() calls. Added after 

198# scripts/profile_inference.py's cProfile run showed Python/NumPy per-call 

199# dispatch overhead dominating this hot path's cost, not FLOPs (see 

200# development/Problems.md) - the models involved (85->24->1, 4 of them) are 

201# too small for raw matmul throughput to matter; call-count is what matters. 

202# --------------------------------------------------------------------------- 

203 

204 

205def _architectures_match(architectures: list[list[dict]]) -> bool: 

206 """True iff every model's layer-type-and-key sequence is identical - 

207 the precondition for batching. Compares type/weight_key/bias_key per 

208 layer, not weight shapes - a shape mismatch despite matching keys would 

209 be a genuinely corrupt export and is left to surface as a numpy error, 

210 caught by run_exported_models_batched()'s own try/except fallback.""" 

211 if len(architectures) < 2: 

212 return True 

213 first = [(layer["type"], layer.get("weight_key"), layer.get("bias_key")) for layer in architectures[0]] 

214 return all( 

215 [(layer["type"], layer.get("weight_key"), layer.get("bias_key")) for layer in arch] == first 

216 for arch in architectures[1:] 

217 ) 

218 

219 

220def _linear_batched(current: np.ndarray, weights_stack: np.ndarray, bias_stack: np.ndarray) -> np.ndarray: 

221 """Batched sibling of _linear() - one einsum across all N stacked 

222 models instead of N separate `weights @ input + bias` calls. 

223 current: (N, in_features); weights_stack: (N, out_features, 

224 in_features); bias_stack: (N, out_features). 

225 

226 Uses the optional cpp_inference accelerator (see module-level import 

227 above) when it's built and importable - falls back to the always- 

228 correct NumPy einsum path on ANY failure (missing extension, a call 

229 raising for any reason), never a hard dependency and never a crash 

230 risk. This is the hottest, most call-heavy primitive in the batched 

231 inference path (see development/Problems.md #32's profiling), which 

232 is why it's the one primitive this pass wired an accelerator for.""" 

233 if _cpp_inference is not None: 

234 try: 

235 return _cpp_inference.linear_batched(weights_stack, current, bias_stack) 

236 except Exception: 

237 pass # fall through to the NumPy path below 

238 return np.einsum("noi,ni->no", weights_stack, current) + bias_stack 

239 

240 

241def _layernorm_batched(current: np.ndarray, weights_stack: np.ndarray, bias_stack: np.ndarray, eps: float) -> np.ndarray: 

242 """Batched sibling of _layernorm() - each row (model) normalized 

243 independently using its OWN mean/variance along the feature axis, then 

244 scaled/shifted by that row's own separately-trained weight/bias. 

245 Unlike _layernorm_axis() (one shared weight/bias broadcast across every 

246 row, used by the sequence encoder's single-model timestep axis), every 

247 stacked model here has its own weights - genuinely different from a 

248 plain broadcast.""" 

249 mean_value = current.mean(axis=-1, keepdims=True) 

250 variance = current.var(axis=-1, keepdims=True) 

251 normalized = (current - mean_value) / np.sqrt(variance + eps) 

252 return normalized * weights_stack + bias_stack 

253 

254 

255def build_layer_stacks(layers: list[dict], state_dicts: list[dict]) -> list[tuple[np.ndarray, np.ndarray] | None]: 

256 """Precomputes each linear/layernorm layer's weights_stack/bias_stack 

257 ONCE - the same np.stack([...]) construction _run_batched_layer_stack() 

258 below otherwise rebuilds from scratch on every single call, even though 

259 the underlying weights never change once a model's loaded (this was 

260 profiling's second-largest finding after the raw asarray cost - 

261 stacking itself still copies data into a new array every call). None 

262 for layer types that carry no weights (relu/dropout/sigmoid/softplus) - 

263 kept as an explicit placeholder so the returned list stays index- 

264 aligned with `layers`, letting _run_batched_layer_stack() zip them 

265 together directly.""" 

266 stacks: list[tuple[np.ndarray, np.ndarray] | None] = [] 

267 for layer in layers: 

268 if layer["type"] in ("linear", "layernorm"): 

269 weights_stack = np.stack([np.asarray(sd[layer["weight_key"]], dtype=np.float64) for sd in state_dicts]) 

270 bias_stack = np.stack([np.asarray(sd[layer["bias_key"]], dtype=np.float64) for sd in state_dicts]) 

271 stacks.append((weights_stack, bias_stack)) 

272 else: 

273 stacks.append(None) 

274 return stacks 

275 

276 

277def _run_batched_layer_stack( 

278 layers: list[dict], 

279 state_dicts: list[dict], 

280 current: np.ndarray, 

281 precomputed_stacks: list[tuple[np.ndarray, np.ndarray] | None] | None = None, 

282) -> np.ndarray: 

283 """Batched sibling of _run_layer_stack() - current starts as (N, 

284 features) instead of (features,), one row per stacked model, and each 

285 linear/layernorm layer pulls that layer's weights from every model's 

286 own state_dict rather than one shared state_dict. 

287 

288 `precomputed_stacks`, when given (see build_layer_stacks() above), is 

289 used instead of rebuilding weights_stack/bias_stack via np.stack() on 

290 this call - callers with a stable model set (main.py, once experts are 

291 loaded) should build this once and reuse it every bar. None (the 

292 default) reproduces the exact original behavior - every existing 

293 caller/test that doesn't pass it is unaffected.""" 

294 for index, layer in enumerate(layers): 

295 layer_type = layer["type"] 

296 cached = precomputed_stacks[index] if precomputed_stacks is not None else None 

297 if layer_type == "linear": 

298 if cached is not None: 

299 weights_stack, bias_stack = cached 

300 else: 

301 weights_stack = np.stack([np.asarray(sd[layer["weight_key"]], dtype=np.float64) for sd in state_dicts]) 

302 bias_stack = np.stack([np.asarray(sd[layer["bias_key"]], dtype=np.float64) for sd in state_dicts]) 

303 current = _linear_batched(current, weights_stack, bias_stack) 

304 elif layer_type == "layernorm": 

305 if cached is not None: 

306 weights_stack, bias_stack = cached 

307 else: 

308 weights_stack = np.stack([np.asarray(sd[layer["weight_key"]], dtype=np.float64) for sd in state_dicts]) 

309 bias_stack = np.stack([np.asarray(sd[layer["bias_key"]], dtype=np.float64) for sd in state_dicts]) 

310 current = _layernorm_batched(current, weights_stack, bias_stack, float(layer.get("eps", 1e-5))) 

311 elif layer_type == "relu": 

312 current = np.maximum(current, 0.0) 

313 elif layer_type == "dropout": 

314 continue 

315 elif layer_type == "sigmoid": 

316 current = _sigmoid(current) 

317 elif layer_type == "softplus": 

318 current = _softplus(current) 

319 else: 

320 raise ValueError(f"Unsupported layer type in export: {layer_type}") 

321 return current 

322 

323 

324def _run_models_individually_with_fallback(model_exports: list[dict | None], inputs: list[float]) -> list[float | None]: 

325 """Exactly today's pre-batching behavior: one run_exported_model() call 

326 per present entry, None preserved for missing entries, one failed 

327 model degrading to None WITHOUT taking any other entry down with it - 

328 the same per-expert graceful-degradation contract 

329 main.py::_run_expert_models() has always had. Used as the batching 

330 functions' fallback whenever batching isn't safe/possible, so that 

331 fallback path is never a behavior change, only a performance one.""" 

332 results: list[float | None] = [] 

333 for export in model_exports: 

334 if not export: 

335 results.append(None) 

336 continue 

337 try: 

338 results.append(run_exported_model(export, inputs)) 

339 except Exception: 

340 results.append(None) 

341 return results 

342 

343 

344class BatchedLayerStackCache: 

345 """Precomputed run_exported_models_batched() weight/bias stacks for a 

346 FIXED set of models sharing one architecture - build once (e.g. in 

347 main.py::_ensure_ready(), right after experts are loaded) via 

348 build_models_batched_cache() below, then pass into every bar's 

349 run_exported_models_batched() call instead of letting it rebuild the 

350 stacks from scratch every time. `present_indices` records exactly 

351 which model_exports slots this cache applies to; the caller 

352 (run_exported_models_batched()) verifies its own freshly computed 

353 present_indices matches before using it - a mismatch (which should 

354 never happen in practice, since main.py's expert exports are loaded 

355 once and never change mid-run) just means falling back to an on-the- 

356 fly rebuild, always safe.""" 

357 

358 def __init__(self, present_indices: list[int], layer_stacks: list[tuple[np.ndarray, np.ndarray] | None]): 

359 self.present_indices = present_indices 

360 self.layer_stacks = layer_stacks 

361 

362 

363def build_models_batched_cache(model_exports: list[dict | None]) -> BatchedLayerStackCache | None: 

364 """Precomputes run_exported_models_batched()'s per-layer weight/bias 

365 stacks once, returning None whenever batching wouldn't apply anyway 

366 (fewer than 2 present, architectures don't match) - the exact same 

367 applicability check run_exported_models_batched() runs itself every 

368 call, so a non-None cache this returns is always exactly the one that 

369 call would build on its own, just computed once instead of every bar.""" 

370 present_indices = [i for i, export in enumerate(model_exports) if export] 

371 if len(present_indices) < 2: 

372 return None 

373 architectures = [model_exports[i]["export"]["architecture"] for i in present_indices] 

374 if not _architectures_match(architectures): 

375 return None 

376 try: 

377 state_dicts = [model_exports[i]["export"]["state_dict"] for i in present_indices] 

378 layer_stacks = build_layer_stacks(architectures[0], state_dicts) 

379 except Exception: 

380 return None 

381 return BatchedLayerStackCache(present_indices, layer_stacks) 

382 

383 

384def run_exported_models_batched( 

385 model_exports: list[dict | None], 

386 inputs: list[float], 

387 stack_cache: BatchedLayerStackCache | None = None, 

388) -> list[float | None]: 

389 """Batched sibling of calling run_exported_model() once per entry in a 

390 loop (main.py::_run_expert_models()'s previous shape, still available 

391 via _run_models_individually_with_fallback() above). Stacks every 

392 PRESENT model's per-layer weights into one leading batch axis and runs 

393 one _linear_batched()/_layernorm_batched() call per layer instead of N 

394 separate run_exported_model() calls. 

395 

396 `stack_cache` (see BatchedLayerStackCache/build_models_batched_cache() 

397 above), when given AND its present_indices matches this call's own, 

398 skips rebuilding the weight/bias stacks from scratch - the default 

399 None reproduces the exact original behavior, so every existing caller/ 

400 test that doesn't pass it is unaffected. 

401 

402 Falls back to the individually-with-fallback path - never raises, 

403 never silently produces a wrong answer - whenever fewer than 2 models 

404 are present, their architectures don't match closely enough to batch, 

405 or the batched computation itself raises for any reason (e.g. a shape 

406 mismatch a type/key match didn't catch - a real safety net, not just a 

407 defensive habit: a retrained single expert with a different hidden 

408 width would otherwise silently corrupt every other expert's output via 

409 a numpy broadcast if this fell through to batching anyway). 

410 

411 Returns one float per entry in model_exports, None preserved at any 

412 index whose export was None/falsy - same shape contract 

413 main.py::_run_expert_models() already depends on.""" 

414 present_indices = [i for i, export in enumerate(model_exports) if export] 

415 if len(present_indices) < 2: 

416 return _run_models_individually_with_fallback(model_exports, inputs) 

417 

418 architectures = [model_exports[i]["export"]["architecture"] for i in present_indices] 

419 if not _architectures_match(architectures): 

420 return _run_models_individually_with_fallback(model_exports, inputs) 

421 

422 try: 

423 state_dicts = [model_exports[i]["export"]["state_dict"] for i in present_indices] 

424 current = np.tile(np.asarray(inputs, dtype=np.float64), (len(present_indices), 1)) 

425 precomputed_stacks = ( 

426 stack_cache.layer_stacks if stack_cache is not None and stack_cache.present_indices == present_indices else None 

427 ) 

428 current = _run_batched_layer_stack(architectures[0], state_dicts, current, precomputed_stacks=precomputed_stacks) 

429 except Exception: 

430 return _run_models_individually_with_fallback(model_exports, inputs) 

431 

432 results: list[float | None] = [None] * len(model_exports) 

433 for row, original_index in enumerate(present_indices): 

434 results[original_index] = float(current[row, 0]) 

435 return results 

436 

437 

438def _run_multitask_models_individually_with_fallback( 

439 model_exports: list[dict | None], inputs: list[float] 

440) -> list[dict[str, float] | None]: 

441 """Multitask sibling of _run_models_individually_with_fallback() - 

442 same per-expert graceful-degradation contract 

443 main.py::_run_expert_multitask_models() has always had.""" 

444 results: list[dict[str, float] | None] = [] 

445 for export in model_exports: 

446 if not export: 

447 results.append(None) 

448 continue 

449 try: 

450 results.append(run_exported_multitask_model(export, inputs)) 

451 except Exception: 

452 results.append(None) 

453 return results 

454 

455 

456class BatchedMultitaskLayerStackCache: 

457 """Multitask sibling of BatchedLayerStackCache - one precomputed stack 

458 set for the shared trunk plus one per head, all tied to the same 

459 `present_indices`. Build once via build_multitask_models_batched_cache() 

460 below.""" 

461 

462 def __init__( 

463 self, 

464 present_indices: list[int], 

465 trunk_stacks: list[tuple[np.ndarray, np.ndarray] | None], 

466 head_stacks_by_name: dict[str, list[tuple[np.ndarray, np.ndarray] | None]], 

467 ): 

468 self.present_indices = present_indices 

469 self.trunk_stacks = trunk_stacks 

470 self.head_stacks_by_name = head_stacks_by_name 

471 

472 

473def build_multitask_models_batched_cache( 

474 model_exports: list[dict | None], 

475) -> BatchedMultitaskLayerStackCache | None: 

476 """Multitask sibling of build_models_batched_cache() - same 

477 applicability check run_exported_multitask_models_batched() runs 

478 itself every call (trunk architectures match, head name sets match, 

479 every head's own architecture matches), returning None whenever that 

480 check would fail anyway.""" 

481 present_indices = [i for i, export in enumerate(model_exports) if export] 

482 if len(present_indices) < 2: 

483 return None 

484 

485 exports = [model_exports[i]["export"] for i in present_indices] 

486 trunk_architectures = [export["trunk"] for export in exports] 

487 head_name_sets = [tuple(sorted(export["heads"].keys())) for export in exports] 

488 if not _architectures_match(trunk_architectures) or len(set(head_name_sets)) != 1: 

489 return None 

490 

491 head_names = head_name_sets[0] 

492 head_architectures_by_name = {name: [export["heads"][name] for export in exports] for name in head_names} 

493 if any(not _architectures_match(archs) for archs in head_architectures_by_name.values()): 

494 return None 

495 

496 try: 

497 state_dicts = [export["state_dict"] for export in exports] 

498 trunk_stacks = build_layer_stacks(trunk_architectures[0], state_dicts) 

499 head_stacks_by_name = { 

500 name: build_layer_stacks(head_architectures_by_name[name][0], state_dicts) for name in head_names 

501 } 

502 except Exception: 

503 return None 

504 return BatchedMultitaskLayerStackCache(present_indices, trunk_stacks, head_stacks_by_name) 

505 

506 

507def run_exported_multitask_models_batched( 

508 model_exports: list[dict | None], 

509 inputs: list[float], 

510 stack_cache: BatchedMultitaskLayerStackCache | None = None, 

511) -> list[dict[str, float] | None]: 

512 """Batched sibling of run_exported_multitask_model(), for 

513 main.py::_run_expert_multitask_models()'s per-expert loop. Batches the 

514 shared trunk across all N present models first, then batches each head 

515 (direction/magnitude/volatility) across the same N models starting 

516 from the trunk's own per-model output - correct only when every 

517 present model shares the same trunk AND the same head names/ 

518 architectures, checked the same way run_exported_models_batched() 

519 checks its flat models. Same graceful-degradation contract and 

520 same-shape fallback safety net as run_exported_models_batched(). 

521 

522 `stack_cache` (see BatchedMultitaskLayerStackCache/ 

523 build_multitask_models_batched_cache() above), when given AND its 

524 present_indices matches this call's own, skips rebuilding every 

525 weight/bias stack from scratch - default None reproduces the exact 

526 original behavior.""" 

527 present_indices = [i for i, export in enumerate(model_exports) if export] 

528 if len(present_indices) < 2: 

529 return _run_multitask_models_individually_with_fallback(model_exports, inputs) 

530 

531 exports = [model_exports[i]["export"] for i in present_indices] 

532 trunk_architectures = [export["trunk"] for export in exports] 

533 head_name_sets = [tuple(sorted(export["heads"].keys())) for export in exports] 

534 if not _architectures_match(trunk_architectures) or len(set(head_name_sets)) != 1: 

535 return _run_multitask_models_individually_with_fallback(model_exports, inputs) 

536 

537 head_names = head_name_sets[0] 

538 head_architectures_by_name = { 

539 name: [export["heads"][name] for export in exports] for name in head_names 

540 } 

541 if any(not _architectures_match(archs) for archs in head_architectures_by_name.values()): 

542 return _run_multitask_models_individually_with_fallback(model_exports, inputs) 

543 

544 cache_applies = stack_cache is not None and stack_cache.present_indices == present_indices 

545 

546 try: 

547 state_dicts = [export["state_dict"] for export in exports] 

548 trunk_current = np.tile(np.asarray(inputs, dtype=np.float64), (len(present_indices), 1)) 

549 trunk_output = _run_batched_layer_stack( 

550 trunk_architectures[0], state_dicts, trunk_current, 

551 precomputed_stacks=stack_cache.trunk_stacks if cache_applies else None, 

552 ) 

553 

554 head_outputs: dict[str, np.ndarray] = {} 

555 for head_name in head_names: 

556 head_outputs[head_name] = _run_batched_layer_stack( 

557 head_architectures_by_name[head_name][0], state_dicts, trunk_output.copy(), 

558 precomputed_stacks=stack_cache.head_stacks_by_name.get(head_name) if cache_applies else None, 

559 ) 

560 except Exception: 

561 return _run_multitask_models_individually_with_fallback(model_exports, inputs) 

562 

563 results: list[dict[str, float] | None] = [None] * len(model_exports) 

564 for row, original_index in enumerate(present_indices): 

565 results[original_index] = {head_name: float(head_outputs[head_name][row, 0]) for head_name in head_names} 

566 return results 

567 

568 

569def _tiled_stacks( 

570 layer_stacks: list[tuple[np.ndarray, np.ndarray] | None], symbol_count: int 

571) -> list[tuple[np.ndarray, np.ndarray] | None]: 

572 """Each layer's (E, ...) weight/bias stacks repeated for `symbol_count` symbols, symbol-major: row s * E + e is expert e 

573 of symbol s. Pure copies of the same numbers, so every row computes exactly what the per-symbol call would.""" 

574 tiled: list[tuple[np.ndarray, np.ndarray] | None] = [] 

575 for stacks in layer_stacks: 

576 if stacks is None: 

577 tiled.append(None) 

578 continue 

579 weights, bias = stacks 

580 tiled.append((np.tile(weights, (symbol_count,) + (1,) * (weights.ndim - 1)), 

581 np.tile(bias, (symbol_count,) + (1,) * (bias.ndim - 1)))) 

582 return tiled 

583 

584 

585def _tiled_cache_for(stack_cache, key: str, build, symbol_count: int): 

586 """`stack_cache.tiled[(key, symbol_count)]`, built once per distinct symbol count (an equity tick, the crypto tick and the 

587 forex tick each have their own), or built fresh when there is no cache object.""" 

588 if stack_cache is None: 

589 return build() 

590 store = stack_cache.__dict__.setdefault("tiled", {}) 

591 cache_key = (key, symbol_count) 

592 if cache_key not in store: 

593 if len(store) >= 16: 

594 store.clear() 

595 store[cache_key] = build() 

596 return store[cache_key] 

597 

598 

599def run_exported_models_across_symbols( 

600 model_exports: list[dict | None], 

601 input_rows: list[list[float]], 

602 stack_cache: BatchedLayerStackCache | None = None, 

603) -> list[list[float | None]]: 

604 """The experts of `run_exported_models_batched` for EVERY symbol in one pass (V6.0.0, latency: 16 ms of per-symbol expert 

605 calls per equity tick). Returns `[symbol][expert]`, None for a missing expert, exactly the numbers the per-symbol call 

606 returns (the rows are the same matmuls; `tests/test_v600_across_symbols.py` pins them to 1e-12). Falls back to the 

607 per-symbol path whenever batching does not apply.""" 

608 if not input_rows: 

609 return [] 

610 present = [i for i, export in enumerate(model_exports) if export] 

611 if len(present) < 2: 

612 return [_run_models_individually_with_fallback(model_exports, row) for row in input_rows] 

613 architectures = [model_exports[i]["export"]["architecture"] for i in present] 

614 if not _architectures_match(architectures): 

615 return [_run_models_individually_with_fallback(model_exports, row) for row in input_rows] 

616 try: 

617 state_dicts = [model_exports[i]["export"]["state_dict"] for i in present] 

618 symbols, experts = len(input_rows), len(present) 

619 usable = stack_cache if stack_cache is not None and stack_cache.present_indices == present else None 

620 base = usable.layer_stacks if usable is not None else build_layer_stacks(architectures[0], state_dicts) 

621 stacks = _tiled_cache_for(usable, "flat", lambda: _tiled_stacks(base, symbols), symbols) 

622 current = np.repeat(np.asarray(input_rows, dtype=np.float64), experts, axis=0) 

623 current = _run_batched_layer_stack(architectures[0], state_dicts * symbols, current, precomputed_stacks=stacks) 

624 except Exception: 

625 return [run_exported_models_batched(model_exports, row, stack_cache=stack_cache) for row in input_rows] 

626 results: list[list[float | None]] = [] 

627 for symbol_index in range(symbols): 

628 row: list[float | None] = [None] * len(model_exports) 

629 for position, original_index in enumerate(present): 

630 row[original_index] = float(current[symbol_index * experts + position, 0]) 

631 results.append(row) 

632 return results 

633 

634 

635def run_exported_multitask_models_across_symbols( 

636 model_exports: list[dict | None], 

637 input_rows: list[list[float]], 

638 stack_cache: BatchedMultitaskLayerStackCache | None = None, 

639) -> list[list[dict[str, float] | None]]: 

640 """Multitask experts for every symbol in one pass (`[symbol][expert] -> {head: value}`), the sibling of 

641 `run_exported_models_across_symbols`; falls back to the per-symbol path under the same conditions.""" 

642 if not input_rows: 

643 return [] 

644 present = [i for i, export in enumerate(model_exports) if export] 

645 if len(present) < 2: 

646 return [_run_multitask_models_individually_with_fallback(model_exports, row) for row in input_rows] 

647 exports = [model_exports[i]["export"] for i in present] 

648 trunk_architectures = [export["trunk"] for export in exports] 

649 head_name_sets = [tuple(sorted(export["heads"].keys())) for export in exports] 

650 if not _architectures_match(trunk_architectures) or len(set(head_name_sets)) != 1: 

651 return [_run_multitask_models_individually_with_fallback(model_exports, row) for row in input_rows] 

652 head_names = head_name_sets[0] 

653 head_architectures = {name: [export["heads"][name] for export in exports] for name in head_names} 

654 if any(not _architectures_match(archs) for archs in head_architectures.values()): 

655 return [_run_multitask_models_individually_with_fallback(model_exports, row) for row in input_rows] 

656 try: 

657 state_dicts = [export["state_dict"] for export in exports] 

658 symbols, experts = len(input_rows), len(present) 

659 usable = stack_cache if stack_cache is not None and stack_cache.present_indices == present else None 

660 trunk_base = usable.trunk_stacks if usable is not None else build_layer_stacks(trunk_architectures[0], state_dicts) 

661 trunk_stacks = _tiled_cache_for(usable, "trunk", lambda: _tiled_stacks(trunk_base, symbols), symbols) 

662 tiled_states = state_dicts * symbols 

663 current = np.repeat(np.asarray(input_rows, dtype=np.float64), experts, axis=0) 

664 trunk_output = _run_batched_layer_stack(trunk_architectures[0], tiled_states, current, precomputed_stacks=trunk_stacks) 

665 head_outputs: dict[str, np.ndarray] = {} 

666 for name in head_names: 

667 head_base = usable.head_stacks_by_name.get(name) if usable is not None else build_layer_stacks(head_architectures[name][0], state_dicts) 

668 head_stacks = _tiled_cache_for(usable, f"head:{name}", lambda base=head_base: _tiled_stacks(base, symbols), symbols) 

669 head_outputs[name] = _run_batched_layer_stack(head_architectures[name][0], tiled_states, trunk_output.copy(), precomputed_stacks=head_stacks) 

670 except Exception: 

671 return [run_exported_multitask_models_batched(model_exports, row, stack_cache=stack_cache) for row in input_rows] 

672 results: list[list[dict[str, float] | None]] = [] 

673 for symbol_index in range(symbols): 

674 row: list[dict[str, float] | None] = [None] * len(model_exports) 

675 for position, original_index in enumerate(present): 

676 row[original_index] = {name: float(head_outputs[name][symbol_index * experts + position, 0]) for name in head_names} 

677 results.append(row) 

678 return results 

679 

680 

681def _softmax(values, axis: int = -1): 

682 """Numerically stable softmax along `axis` (subtracts the per-axis max 

683 before exponentiating). Phase 2 primitive - used by 

684 _multihead_attention() below, and available standalone for any future 

685 export that needs it.""" 

686 array = np.asarray(values, dtype=np.float64) 

687 shifted = array - np.max(array, axis=axis, keepdims=True) 

688 exponentiated = np.exp(shifted) 

689 return exponentiated / np.sum(exponentiated, axis=axis, keepdims=True) 

690 

691 

692def _layernorm_axis(values, weights: list[float], bias: list[float], eps: float, axis: int = -1) -> np.ndarray: 

693 """Axis-aware generalization of _layernorm() above - Phase 2 needs to 

694 normalize a (window, features) sequence independently per timestep 

695 (matching PyTorch's nn.LayerNorm(features) applied to a (window, 

696 features) tensor: mean/variance computed over the feature axis only, 

697 never across timesteps), where the original _layernorm() normalizes a 

698 single flat vector as one whole. 

699 

700 A new function, not a modification of _layernorm() - run_exported_model() 

701 and run_exported_multitask_model() both call the original with no axis 

702 concept, and changing its signature would be a needless behavior risk 

703 to code already shipped. Reduces to the same result as _layernorm() 

704 when given a 1D array (axis=-1 is the only axis).""" 

705 values_array = np.asarray(values, dtype=np.float64) 

706 mean_value = values_array.mean(axis=axis, keepdims=True) 

707 variance = values_array.var(axis=axis, keepdims=True) 

708 denominator = np.sqrt(variance + eps) 

709 normalized = (values_array - mean_value) / denominator 

710 return normalized * np.asarray(weights, dtype=np.float64) + np.asarray(bias, dtype=np.float64) 

711 

712 

713def _conv1d_causal(sequence, weights, bias, dilation: int = 1) -> np.ndarray: 

714 """Causal dilated 1D convolution over a (window, in_channels) sequence, 

715 matching PyTorch's nn.Conv1d(in_channels, out_channels, kernel_size, 

716 dilation=dilation) applied to a left-zero-padded input so output[t] 

717 depends only on input[<=t] (no lookahead - same invariant every other 

718 feature in this codebase already respects). 

719 

720 `weights` has PyTorch's own nn.Conv1d.weight shape: 

721 (out_channels, in_channels, kernel_size). Left-pads with 

722 (kernel_size-1)*dilation zero timesteps so the output has the same 

723 number of timesteps as the input (PyTorch's own causal-conv idiom - 

724 "pad left by the receptive field, then run a valid/no-padding conv"). 

725 

726 Returns a (window, out_channels) array (channels-last, matching every 

727 other array shape in this module - the transpose to/from PyTorch's own 

728 channels-first (channels, window) convention happens once, here, not 

729 scattered across callers). 

730 """ 

731 sequence_array = np.asarray(sequence, dtype=np.float64) # (window, in_channels) 

732 weights_array = np.asarray(weights, dtype=np.float64) # (out_channels, in_channels, kernel_size) 

733 bias_array = np.asarray(bias, dtype=np.float64) # (out_channels,) 

734 

735 window, in_channels = sequence_array.shape 

736 _out_channels, weight_in_channels, kernel_size = weights_array.shape 

737 if weight_in_channels != in_channels: 

738 raise ValueError(f"_conv1d_causal: in_channels mismatch ({in_channels} vs weight's {weight_in_channels})") 

739 

740 pad_left = (kernel_size - 1) * dilation 

741 padded = np.zeros((window + pad_left, in_channels), dtype=np.float64) 

742 padded[pad_left:, :] = sequence_array 

743 

744 # Vectorized sibling of the original `for timestep in range(window):` 

745 # loop below (kept only as a reference in git history) - profiling this 

746 # hot path (scripts/profile_inference.py) showed this Python loop, 

747 # 30 iterations here to match the trained sequence model's window_size 

748 # but re-run once per symbol per bar, was the single largest cost in 

749 # main.py's entire per-bar inference path (bigger than the 4-expert 

750 # loop this same pass also batched - see run_exported_models_batched() 

751 # above). Builds every timestep's kernel_size dilated tap indices at 

752 # once (tap_indices: (window, kernel_size)), gathers them in one fancy- 

753 # index op (window_slices: (window, kernel_size, in_channels)), then 

754 # runs ONE einsum across every timestep instead of `window` separate 

755 # ones. Same math, same output - tests/test_exported_model.py's 

756 # existing hand-computed/causality/mismatch tests are the parity net, 

757 # unchanged by this rewrite (same function signature and output 

758 # contract, no new call sites needed). 

759 offsets = np.arange(kernel_size - 1, -1, -1) * dilation # (kernel_size,) 

760 tap_indices = np.arange(window)[:, None] + pad_left - offsets[None, :] # (window, kernel_size) 

761 window_slices = padded[tap_indices, :] # (window, kernel_size, in_channels) 

762 return np.einsum("oik,tki->to", weights_array, window_slices) + bias_array 

763 

764 

765def _multihead_attention( 

766 sequence, 

767 query_weights, query_bias, 

768 key_weights, key_bias, 

769 value_weights, value_bias, 

770 output_weights, output_bias, 

771 num_heads: int, 

772 causal: bool = True, 

773) -> np.ndarray: 

774 """Standard scaled dot-product multi-head self-attention over a 

775 (window, d_model) sequence - Phase 2 infrastructure for a future 

776 attention-based sequence encoder (the first real Phase 2 sequence 

777 model shipped this pass, AetherNetSequenceEncoder in train.py, uses a 

778 causal TCN trunk instead - simpler to verify bit-for-bit end-to-end; 

779 see train.py's module docstring for that scope decision). Hand- 

780 verified against a small synthetic single-head example 

781 (tests/test_exported_model.py). No real trained export of this 

782 model exists, so it has only run on that example. 

783 

784 `causal=True` (default) masks each position from attending to any 

785 future position - same no-lookahead invariant _conv1d_causal() above 

786 enforces, since any sequence model in this codebase must never see 

787 ahead of the bar it's predicting for. 

788 

789 query/key/value/output weights follow PyTorch's nn.Linear.weight shape 

790 (out_features, in_features); d_model must be divisible by num_heads. 

791 """ 

792 sequence_array = np.asarray(sequence, dtype=np.float64) # (window, d_model) 

793 window, d_model = sequence_array.shape 

794 if d_model % num_heads != 0: 

795 raise ValueError(f"_multihead_attention: d_model={d_model} not divisible by num_heads={num_heads}") 

796 head_dim = d_model // num_heads 

797 

798 def project(weights, bias): 

799 return sequence_array @ np.asarray(weights, dtype=np.float64).T + np.asarray(bias, dtype=np.float64) 

800 

801 query = project(query_weights, query_bias).reshape(window, num_heads, head_dim).transpose(1, 0, 2) 

802 key = project(key_weights, key_bias).reshape(window, num_heads, head_dim).transpose(1, 0, 2) 

803 value = project(value_weights, value_bias).reshape(window, num_heads, head_dim).transpose(1, 0, 2) 

804 

805 scores = np.matmul(query, key.transpose(0, 2, 1)) / np.sqrt(head_dim) # (num_heads, window, window) 

806 if causal: 

807 causal_mask = np.triu(np.ones((window, window), dtype=bool), k=1) 

808 scores = np.where(causal_mask[None, :, :], -np.inf, scores) 

809 

810 attention_weights = _softmax(scores, axis=-1) 

811 context = np.matmul(attention_weights, value) # (num_heads, window, head_dim) 

812 context = context.transpose(1, 0, 2).reshape(window, d_model) 

813 

814 output_weights_array = np.asarray(output_weights, dtype=np.float64) 

815 output_bias_array = np.asarray(output_bias, dtype=np.float64) 

816 return context @ output_weights_array.T + output_bias_array 

817 

818 

819def run_exported_multitask_model(model_export: dict[str, Any], inputs: list[float]) -> dict[str, float]: 

820 """Forward pass over a branching {"trunk": [...], "heads": {name: [...]}} 

821 export (train.py::export_multitask_architecture()/AetherNetMultiTask) - 

822 the shared trunk runs once, then each head runs independently starting 

823 from the trunk's output. Returns one scalar per head, e.g. 

824 {"direction": <sigmoid prob>, "magnitude": <raw regression>, 

825 "volatility": <softplus, always >= 0>}. 

826 

827 Deliberately a new function alongside run_exported_model(), not a 

828 generalization of it - the existing flat-architecture interpreter and 

829 its 5 call sites (main.py, moe/gating.py, train_gating.py) are untouched, 

830 zero regression risk to anything already shipped.""" 

831 export = model_export["export"] 

832 state_dict = export["state_dict"] 

833 trunk_output = _run_layer_stack(export["trunk"], state_dict, np.asarray(inputs, dtype=np.float64)) 

834 

835 outputs: dict[str, float] = {} 

836 for head_name, head_layers in export["heads"].items(): 

837 head_output = _run_layer_stack(head_layers, state_dict, trunk_output.copy()) 

838 outputs[head_name] = float(head_output[0]) 

839 return outputs 

840 

841 

842def run_exported_sequence_multitask_model(model_export: dict[str, Any], sequence: list[list[float]]) -> dict[str, float]: 

843 """Phase 2: forward pass over a sequence-encoder export - a causal TCN 

844 trunk (train.py::AetherNetSequenceMultiTask/export_sequence_multitask_architecture()) 

845 consuming a (window, features) matrix instead of run_exported_multitask_model()'s 

846 flat feature vector, pooled to its last (most-recent, causal) timestep, 

847 then the same {"direction", "magnitude", "volatility"} head shape 

848 run_exported_multitask_model() already uses. 

849 

850 `sequence` must be ordered oldest-to-newest (sequence[-1] is the 

851 current bar) - main.py's rolling per-symbol buffer of already-computed 

852 flat model_inputs vectors (see main.py::_build_sequence_model_input()) 

853 is built in that order. 

854 

855 A new function alongside run_exported_model()/run_exported_multitask_model(), 

856 not a generalization of either - zero regression risk to the flat-vector 

857 interpreters both call sites already depend on.""" 

858 export = model_export["export"] 

859 state_dict = export["state_dict"] 

860 current = np.asarray(sequence, dtype=np.float64) 

861 

862 for layer in export["trunk"]: 

863 layer_type = layer["type"] 

864 if layer_type == "conv1d_causal": 

865 weights = state_dict[layer["weight_key"]] 

866 bias = state_dict[layer["bias_key"]] 

867 current = _conv1d_causal(current, weights, bias, dilation=int(layer.get("dilation", 1))) 

868 elif layer_type == "relu": 

869 current = np.maximum(current, 0.0) 

870 elif layer_type == "layernorm_axis": 

871 weights = state_dict[layer["weight_key"]] 

872 bias = state_dict[layer["bias_key"]] 

873 current = _layernorm_axis(current, weights, bias, float(layer.get("eps", 1e-5)), axis=-1) 

874 elif layer_type == "dropout": 

875 continue 

876 else: 

877 raise ValueError(f"Unsupported sequence trunk layer type in export: {layer_type}") 

878 

879 pooled = current[-1, :] # most-recent timestep - the causal trunk's "as-of-now" representation 

880 

881 outputs: dict[str, float] = {} 

882 for head_name, head_layers in export["heads"].items(): 

883 head_output = _run_layer_stack(head_layers, state_dict, pooled.copy()) 

884 outputs[head_name] = float(head_output[0]) 

885 return outputs 

886 

887 

888# --------------------------------------------------------------------------- 

889# Batched inference for the sequence encoder across MULTIPLE SYMBOLS sharing 

890# ONE model (V4.9 Priority 1, development/Problems.md #21) - the opposite 

891# shape from the run_exported_models_batched()/run_exported_multitask_models_batched() 

892# section above (which batch N DIFFERENT models sharing one input). Here 

893# there is exactly one trained sequence model, called once per symbol per 

894# bar in main.py's on_data() loop with each symbol's own (window, features) 

895# rolling buffer as input - profiling (Problems.md #21) found this call the 

896# single largest remaining cost in per-bar inference (~48-58% of profiled 

897# time), almost entirely Python/NumPy per-call dispatch overhead across 

898# `_conv1d_causal()`'s einsum, not FLOPs, the same "call-count is what 

899# matters, not raw throughput" finding _linear_batched() above already 

900# established for the flat/multitask experts. 

901# --------------------------------------------------------------------------- 

902 

903 

904def _linear_shared_batched(current: np.ndarray, weights, bias) -> np.ndarray: 

905 """Batched sibling of _linear() for ONE shared model's weights applied 

906 to N stacked input rows - the opposite of _linear_batched() above, 

907 which stacks N DIFFERENT models' own weights over one shared input. 

908 Here there is one sequence model, N symbols' own pooled trunk outputs 

909 stacked as rows. 

910 

911 current: (N, in_features); weights: (out_features, in_features) (same 

912 single shared matrix for every row); bias: (out_features,). Returns 

913 (N, out_features).""" 

914 weights_array = np.asarray(weights, dtype=np.float64) 

915 bias_array = np.asarray(bias, dtype=np.float64) 

916 return current @ weights_array.T + bias_array 

917 

918 

919def _run_layer_stack_shared_batched(layers: list[dict], state_dict: dict[str, Any], current: np.ndarray) -> np.ndarray: 

920 """Batched sibling of _run_layer_stack() for ONE shared model applied to 

921 N stacked rows (current starts as (N, features)) - used below for the 

922 sequence encoder's head layers, once N symbols' pooled trunk outputs 

923 are stacked. `_layernorm_axis()` (already axis-aware, Phase 2) is reused 

924 as-is for the "layernorm" layer type here: with axis=-1 it normalizes 

925 each row independently by its own mean/variance while still applying 

926 the one shared weight/bias, exactly the semantics needed - no new 

927 layernorm primitive required. relu/dropout/sigmoid/softplus are all 

928 already elementwise and need no batching change.""" 

929 for layer in layers: 

930 layer_type = layer["type"] 

931 if layer_type == "linear": 

932 weights = state_dict[layer["weight_key"]] 

933 bias = state_dict[layer["bias_key"]] 

934 current = _linear_shared_batched(current, weights, bias) 

935 elif layer_type == "layernorm": 

936 weights = state_dict[layer["weight_key"]] 

937 bias = state_dict[layer["bias_key"]] 

938 current = _layernorm_axis(current, weights, bias, float(layer.get("eps", 1e-5)), axis=-1) 

939 elif layer_type == "relu": 

940 current = np.maximum(current, 0.0) 

941 elif layer_type == "dropout": 

942 continue 

943 elif layer_type == "sigmoid": 

944 current = _sigmoid(current) 

945 elif layer_type == "softplus": 

946 current = _softplus(current) 

947 else: 

948 raise ValueError(f"Unsupported layer type in export: {layer_type}") 

949 return current 

950 

951 

952def _conv1d_causal_batched(sequence_batch, weights, bias, dilation: int = 1) -> np.ndarray: 

953 """Batched sibling of _conv1d_causal() - sequence_batch: (N, window, 

954 in_channels), ONE shared model's conv weights applied to N symbols' own 

955 sequences at once. Same left-zero-pad-then-gather-then-einsum 

956 construction as _conv1d_causal(), with a leading N axis carried through 

957 untouched (the padding and tap-gather are per-row independent; only the 

958 final einsum sums over the shared weight tensor, contracting the same 

959 in_channels/kernel_size axes _conv1d_causal() contracts, plus the new 

960 leading N axis passed straight through to the output).""" 

961 sequence_array = np.asarray(sequence_batch, dtype=np.float64) # (N, window, in_channels) 

962 weights_array = np.asarray(weights, dtype=np.float64) # (out_channels, in_channels, kernel_size) 

963 bias_array = np.asarray(bias, dtype=np.float64) # (out_channels,) 

964 

965 num_symbols, window, in_channels = sequence_array.shape 

966 _out_channels, weight_in_channels, kernel_size = weights_array.shape 

967 if weight_in_channels != in_channels: 

968 raise ValueError(f"_conv1d_causal_batched: in_channels mismatch ({in_channels} vs weight's {weight_in_channels})") 

969 

970 pad_left = (kernel_size - 1) * dilation 

971 padded = np.zeros((num_symbols, window + pad_left, in_channels), dtype=np.float64) 

972 padded[:, pad_left:, :] = sequence_array 

973 

974 offsets = np.arange(kernel_size - 1, -1, -1) * dilation # (kernel_size,) 

975 tap_indices = np.arange(window)[:, None] + pad_left - offsets[None, :] # (window, kernel_size) 

976 window_slices = padded[:, tap_indices, :] # (N, window, kernel_size, in_channels) 

977 return np.einsum("oik,ntki->nto", weights_array, window_slices) + bias_array 

978 

979 

980def _run_sequence_models_individually_with_fallback( 

981 model_export: dict[str, Any], sequences: list[list[list[float]] | None] 

982) -> list[dict[str, float] | None]: 

983 """Exactly today's pre-batching behavior: one 

984 run_exported_sequence_multitask_model() call per present entry, None 

985 preserved for missing entries (a symbol whose rolling sequence buffer 

986 hasn't warmed up yet), one symbol's failure degrading to None WITHOUT 

987 taking any other symbol down with it - same per-symbol graceful- 

988 degradation contract as _run_models_individually_with_fallback() above. 

989 Used as run_exported_sequence_multitask_model_batched()'s fallback 

990 whenever batching isn't safe/possible, so that fallback path is never a 

991 behavior change, only a performance one.""" 

992 results: list[dict[str, float] | None] = [] 

993 for sequence in sequences: 

994 if not sequence: 

995 results.append(None) 

996 continue 

997 try: 

998 results.append(run_exported_sequence_multitask_model(model_export, sequence)) 

999 except Exception: 

1000 results.append(None) 

1001 return results 

1002 

1003 

1004def run_exported_sequence_multitask_model_batched( 

1005 model_export: dict[str, Any], sequences: list[list[list[float]] | None] 

1006) -> list[dict[str, float] | None]: 

1007 """Batched sibling of run_exported_sequence_multitask_model() - ONE 

1008 trained sequence model, N symbols' own (window, features) sequences 

1009 stacked into a single (N, window, features) batch, the causal-conv 

1010 trunk run once across all N, pooled to each symbol's own last timestep, 

1011 then each head run once across all N pooled rows - instead of N 

1012 separate run_exported_sequence_multitask_model() calls each re-entering 

1013 the same Python/NumPy dispatch path with the same model weights. 

1014 

1015 `sequences` entries may be None (symbol has no sequence buffer yet) - 

1016 preserved as None in the output at the same index. Falls back to 

1017 calling run_exported_sequence_multitask_model() once per present entry 

1018 - never raises, never silently produces a wrong answer - whenever 

1019 fewer than 2 sequences are present, or the batched computation itself 

1020 raises for any reason (e.g. symbols with inconsistent window lengths, 

1021 which np.asarray() on a ragged list would itself raise on, or a 

1022 malformed export).""" 

1023 present_indices = [i for i, sequence in enumerate(sequences) if sequence] 

1024 if len(present_indices) < 2: 

1025 return _run_sequence_models_individually_with_fallback(model_export, sequences) 

1026 

1027 export = model_export["export"] 

1028 state_dict = export["state_dict"] 

1029 

1030 try: 

1031 current = np.asarray([sequences[i] for i in present_indices], dtype=np.float64) 

1032 for layer in export["trunk"]: 

1033 layer_type = layer["type"] 

1034 if layer_type == "conv1d_causal": 

1035 weights = state_dict[layer["weight_key"]] 

1036 bias = state_dict[layer["bias_key"]] 

1037 current = _conv1d_causal_batched(current, weights, bias, dilation=int(layer.get("dilation", 1))) 

1038 elif layer_type == "relu": 

1039 current = np.maximum(current, 0.0) 

1040 elif layer_type == "layernorm_axis": 

1041 weights = state_dict[layer["weight_key"]] 

1042 bias = state_dict[layer["bias_key"]] 

1043 current = _layernorm_axis(current, weights, bias, float(layer.get("eps", 1e-5)), axis=-1) 

1044 elif layer_type == "dropout": 

1045 continue 

1046 else: 

1047 raise ValueError(f"Unsupported sequence trunk layer type in export: {layer_type}") 

1048 

1049 pooled_batch = current[:, -1, :] # (N, out_channels) - each symbol's own most-recent timestep 

1050 

1051 head_outputs: dict[str, np.ndarray] = {} 

1052 for head_name, head_layers in export["heads"].items(): 

1053 head_outputs[head_name] = _run_layer_stack_shared_batched(head_layers, state_dict, pooled_batch.copy()) 

1054 except Exception: 

1055 return _run_sequence_models_individually_with_fallback(model_export, sequences) 

1056 

1057 results: list[dict[str, float] | None] = [None] * len(sequences) 

1058 for row, original_index in enumerate(present_indices): 

1059 results[original_index] = {head_name: float(head_outputs[head_name][row, 0]) for head_name in head_outputs} 

1060 return results 

1061 

1062 

1063def resolve_sequence_window_size(sequence_feature_schema: dict[str, Any] | None, configured_window_size: int) -> int: 

1064 """The trained model's OWN window_size (sequence_feature_schema.json, 

1065 written by train_sequence.py) wins over config.json's - a retrained 

1066 candidate with a different window_size used to silently disable the 

1067 sequence signal (main.py built a rolling buffer sized for the old/ 

1068 configured window, then fed it into run_exported_sequence_multitask_model()'s 

1069 Conv1d stack sized for the new one - a shape mismatch caught by 

1070 main.py::_run_sequence_model()'s blanket except, never surfaced). 

1071 Falls back to configured_window_size only when no schema loaded at all 

1072 (missing/malformed model file - see main.py::_load_sequence_model()'s 

1073 graceful-fallback contract). Lives here (not main.py) so it's 

1074 unit-testable without a Lean QCAlgorithm environment.""" 

1075 return int((sequence_feature_schema or {}).get("window_size", configured_window_size)) 

1076 

1077 

1078def average_head_outputs(outputs: list[dict | None]) -> dict[str, Any] | None: 

1079 """Seed-ensemble prediction (V6.1.0): the plain mean of each head's raw output across members, taken before any 

1080 cross-sectional normalisation (train.average_ensemble_predictions averages the same way). A head is kept only when 

1081 every member returned a finite value for it, so a member that failed cannot silently reweight the others; None when 

1082 no member returned anything.""" 

1083 members = [output for output in outputs if output] 

1084 if not members: 

1085 return None 

1086 averaged: dict = {} 

1087 for head in members[0]: 

1088 values = [member.get(head) for member in members] 

1089 if all(isinstance(value, (int, float)) and math.isfinite(value) for value in values): 

1090 averaged[head] = float(sum(values) / len(values)) 

1091 else: 

1092 averaged[head] = None 

1093 return averaged 

1094 

1095 

1096def export_input_names(model_export: dict[str, Any] | None, default_names: list[str]) -> list[str]: 

1097 """The input features a model was trained on (`model.model_input_features` of its export); `default_names` when the 

1098 export does not record them (an older export trained on the full schema).""" 

1099 names = ((model_export or {}).get("model") or {}).get("model_input_features") 

1100 return list(names) if names else list(default_names) 

1101 

1102 

1103def model_input_index(model_export: dict[str, Any] | None, full_names: list[str]) -> list[int] | None: 

1104 """V6.2.0: positions of a model's own inputs inside the full live vector (`ml/feature_schema.json` order), so a model 

1105 trained on a feature subset gets exactly its inputs. None when they are the full vector in the same order (the 

1106 caller passes the vector through untouched); ValueError when the model needs a feature live never builds.""" 

1107 names = export_input_names(model_export, full_names) 

1108 if names == list(full_names): 

1109 return None 

1110 position = {name: slot for slot, name in enumerate(full_names)} 

1111 missing = [name for name in names if name not in position] 

1112 if missing: 

1113 raise ValueError(f"model inputs not in the live feature vector: {missing[:5]}") 

1114 return [position[name] for name in names] 

1115 

1116 

1117def select_model_inputs(inputs: list[float], index: list[int] | None) -> list[float]: 

1118 """`inputs` itself when `index` is None (no copy), else the model's own subset in its own order.""" 

1119 return inputs if index is None else [inputs[slot] for slot in index] 

1120 

1121 

1122def select_sequence_inputs(sequence: list[list[float]], index: list[int] | None) -> list[list[float]]: 

1123 """select_model_inputs on every bar of a (window, features) sequence.""" 

1124 return sequence if index is None else [[row[slot] for slot in index] for row in sequence] 

1125 

1126 

1127def load_ensemble_member_exports(ensemble_dir: Path) -> list[dict]: 

1128 """Every member export (`*.json`, sorted by name) of an ensemble directory; [] when the directory is missing.""" 

1129 import json 

1130 

1131 directory = Path(ensemble_dir) 

1132 if not directory.is_dir(): 

1133 return [] 

1134 return [json.loads(path.read_text(encoding="utf-8")) for path in sorted(directory.glob("*.json"))] 

1135 

1136 

1137def resolve_model_ensemble_config(config: dict[str, Any]) -> dict[str, Any]: 

1138 """`phase_v2.model_ensemble` with defaults: off, members under ml/multitask_ensemble and ml/sequence_ensemble.""" 

1139 raw = (config or {}).get("phase_v2", {}).get("model_ensemble", {}) or {} 

1140 return { 

1141 "enabled": bool(raw.get("enabled", False)), 

1142 "multitask_dir": str(raw.get("multitask_dir", "multitask_ensemble")), 

1143 "sequence_dir": str(raw.get("sequence_dir", "sequence_ensemble")), 

1144 }