Coverage for lab/architectures.py: 100%

237 statements  

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

1"""The production networks (moved unchanged from train.py in V6.7.1 so the library can build and export them): 

2the baseline `AetherNet`, the multitask and multi-horizon heads, the causal-TCN sequence encoders, their head specs, 

3and the JSON exporters the numpy forward pass reads. `train.py` re-exports every name. 

4""" 

5 

6from __future__ import annotations 

7 

8from typing import Any 

9 

10import torch 

11from torch import nn 

12 

13 

14class AetherNet(nn.Module): 

15 """The baseline feed-forward network: hidden layers with an activation, optional normalization and dropout, one logit out.""" 

16 def __init__( 

17 self, 

18 input_dim: int, 

19 hidden_layers: list[int], 

20 dropout: float, 

21 activation: str = "relu", 

22 normalization: str = "none", 

23 ) -> None: 

24 super().__init__() 

25 layers: list[nn.Module] = [] 

26 current_dim = input_dim 

27 for hidden_dim in hidden_layers: 

28 layers.append(nn.Linear(current_dim, hidden_dim)) 

29 norm_layer = build_normalization(normalization, hidden_dim) 

30 if norm_layer is not None: 

31 layers.append(norm_layer) 

32 layers.append(build_activation(activation)) 

33 if dropout > 0: 

34 layers.append(nn.Dropout(dropout)) 

35 current_dim = hidden_dim 

36 layers.append(nn.Linear(current_dim, 1)) 

37 self.network = nn.Sequential(*layers) 

38 

39 def forward(self, features: torch.Tensor) -> torch.Tensor: 

40 return self.network(features).squeeze(-1) 

41 

42 

43def build_activation(name: str) -> nn.Module: 

44 """The activation module a config name names (relu, gelu, silu, ...).""" 

45 normalized = name.lower() 

46 if normalized == "relu": 

47 return nn.ReLU() 

48 if normalized == "gelu": 

49 return nn.GELU() 

50 if normalized == "silu": 

51 return nn.SiLU() 

52 raise ValueError(f"Unsupported activation: {name}") 

53 

54 

55def build_normalization(name: str, hidden_dim: int) -> nn.Module | None: 

56 """The normalization module a config name names, for a layer of `hidden_dim` units; None for "none" or "off".""" 

57 normalized = name.lower() 

58 if normalized in {"none", "off"}: 

59 return None 

60 if normalized == "layernorm": 

61 return nn.LayerNorm(hidden_dim) 

62 if normalized == "batchnorm": 

63 return nn.BatchNorm1d(hidden_dim) 

64 raise ValueError(f"Unsupported normalization: {name}") 

65 

66 

67class AetherNetMultiTask(nn.Module): 

68 """Shared-trunk, three-head variant of AetherNet: direction (binary 

69 logit), magnitude (raw regression) and volatility (Softplus, always 

70 non-negative). The trunk is identical in shape to AetherNet's own 

71 hidden-layer stack (same build_activation/build_normalization reuse) - 

72 only the single output Linear(., 1) is replaced with three independent 

73 small heads sharing the trunk's representation. See 

74 inference/exported_model.py::run_exported_multitask_model() for the 

75 matching interpreter and export_multitask_architecture() below for the 

76 matching exporter.""" 

77 

78 def __init__( 

79 self, 

80 input_dim: int, 

81 hidden_layers: list[int], 

82 dropout: float, 

83 activation: str = "relu", 

84 normalization: str = "none", 

85 ) -> None: 

86 super().__init__() 

87 layers: list[nn.Module] = [] 

88 current_dim = input_dim 

89 for hidden_dim in hidden_layers: 

90 layers.append(nn.Linear(current_dim, hidden_dim)) 

91 norm_layer = build_normalization(normalization, hidden_dim) 

92 if norm_layer is not None: 

93 layers.append(norm_layer) 

94 layers.append(build_activation(activation)) 

95 if dropout > 0: 

96 layers.append(nn.Dropout(dropout)) 

97 current_dim = hidden_dim 

98 self.trunk = nn.Sequential(*layers) 

99 self.head_direction = nn.Linear(current_dim, 1) 

100 self.head_magnitude = nn.Linear(current_dim, 1) 

101 self.head_volatility = nn.Linear(current_dim, 1) 

102 

103 def forward(self, features: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: 

104 trunk_output = self.trunk(features) 

105 direction_logit = self.head_direction(trunk_output).squeeze(-1) 

106 magnitude = self.head_magnitude(trunk_output).squeeze(-1) 

107 volatility = nn.functional.softplus(self.head_volatility(trunk_output).squeeze(-1)) 

108 return direction_logit, magnitude, volatility 

109 

110 

111class AetherNetMultiTaskHorizons(nn.Module): 

112 """Extends AetherNetMultiTask with 4 additional heads: direction_5d/ 

113 direction_20d (longer-horizon direction - the highest-leverage change 

114 this codebase's root-cause investigation identified, since next-day 

115 binary direction on liquid daily bars is close to efficient-market 

116 noise, and longer horizons give momentum/mean-reversion more room to 

117 show up) and rank_5d/rank_20d (cross-sectional percentile-rank of 

118 forward return across the universe on the same date - typically far 

119 more learnable than absolute direction, and maps directly onto a 

120 long/short portfolio). 

121 

122 A NEW sibling class, not a modification of AetherNetMultiTask - 

123 train.py::_train_expert_multitask() (the 4 regime experts' own 

124 multitask heads) keeps using the original 3-head class completely 

125 unchanged, by design (experts/baseline/gating stay 1d-direction-only, 

126 see development/Changelog.md). Same trunk-building logic as 

127 AetherNetMultiTask; all 7 heads share it. 

128 

129 forward() returns a dict, not AetherNetMultiTask's fixed 3-tuple - one 

130 raw (pre-activation, except volatility which applies softplus 

131 internally same as AetherNetMultiTask) tensor per head. This naming 

132 maps 1:1 onto the export's "heads" dict keys (see 

133 export_multitask_horizons_architecture()), which 

134 inference/exported_model.py::run_exported_multitask_model() already 

135 iterates generically - no interpreter changes needed for the new 

136 heads.""" 

137 

138 def __init__( 

139 self, 

140 input_dim: int, 

141 hidden_layers: list[int], 

142 dropout: float, 

143 activation: str = "relu", 

144 normalization: str = "none", 

145 extra_heads: tuple[str, ...] = (), 

146 ) -> None: 

147 super().__init__() 

148 layers: list[nn.Module] = [] 

149 current_dim = input_dim 

150 for hidden_dim in hidden_layers: 

151 layers.append(nn.Linear(current_dim, hidden_dim)) 

152 norm_layer = build_normalization(normalization, hidden_dim) 

153 if norm_layer is not None: 

154 layers.append(norm_layer) 

155 layers.append(build_activation(activation)) 

156 if dropout > 0: 

157 layers.append(nn.Dropout(dropout)) 

158 current_dim = hidden_dim 

159 self.trunk = nn.Sequential(*layers) 

160 self.head_direction = nn.Linear(current_dim, 1) 

161 self.head_magnitude = nn.Linear(current_dim, 1) 

162 self.head_volatility = nn.Linear(current_dim, 1) 

163 self.head_direction_5d = nn.Linear(current_dim, 1) 

164 self.head_direction_20d = nn.Linear(current_dim, 1) 

165 self.head_rank_5d = nn.Linear(current_dim, 1) 

166 self.head_rank_20d = nn.Linear(current_dim, 1) 

167 # Phase 5 of the 5/10 -> 9/10 roadmap: a NEW sibling head, not a 

168 # modification of head_rank_20d - every existing consumer of 

169 # rank_20d (rank_sizing_multiplier(), etc.) is unaffected until/ 

170 # unless someone deliberately switches to this sector-demeaned 

171 # variant. See build_cross_sectional_rank_targets()'s docstring. 

172 self.head_sector_neutral_rank_20d = nn.Linear(current_dim, 1) 

173 # V5.1 Phase 2 (item 5 of the roadmap) - see 

174 # train.py::build_residual_rank_targets()'s docstring for what 

175 # these targets are. beta_neutral_rank_20d ships DISABLED by 

176 # default (HORIZON_HEAD_SPECS/DEFAULT_HORIZON_HEAD_CONFIG) - 

177 # strictly dominated by the combined residual_rank_20d above it, 

178 # registered only so it stops being fully dead code (the target 

179 # column itself is computed unconditionally by 

180 # build_cross_sectional_rank_targets() and previously consumed by 

181 # no head at all). 

182 self.head_residual_rank_5d = nn.Linear(current_dim, 1) 

183 self.head_residual_rank_20d = nn.Linear(current_dim, 1) 

184 self.head_beta_neutral_rank_20d = nn.Linear(current_dim, 1) 

185 # V6.0.0: heads from EXTRA_HORIZON_HEAD_SPECS, built last so the default model's parameters (and their random 

186 # initialisation order) are unchanged when none is enabled. 

187 self.extra_heads = tuple(extra_heads) 

188 for name in self.extra_heads: 

189 setattr(self, f"head_{name}", nn.Linear(current_dim, 1)) 

190 

191 def forward(self, features: torch.Tensor) -> dict[str, torch.Tensor]: 

192 trunk_output = self.trunk(features) 

193 extra = {name: getattr(self, f"head_{name}")(trunk_output).squeeze(-1) for name in self.extra_heads} 

194 return extra | { 

195 "direction": self.head_direction(trunk_output).squeeze(-1), 

196 "magnitude": self.head_magnitude(trunk_output).squeeze(-1), 

197 "volatility": nn.functional.softplus(self.head_volatility(trunk_output).squeeze(-1)), 

198 "direction_5d": self.head_direction_5d(trunk_output).squeeze(-1), 

199 "direction_20d": self.head_direction_20d(trunk_output).squeeze(-1), 

200 "rank_5d": self.head_rank_5d(trunk_output).squeeze(-1), 

201 "rank_20d": self.head_rank_20d(trunk_output).squeeze(-1), 

202 "sector_neutral_rank_20d": self.head_sector_neutral_rank_20d(trunk_output).squeeze(-1), 

203 "residual_rank_5d": self.head_residual_rank_5d(trunk_output).squeeze(-1), 

204 "residual_rank_20d": self.head_residual_rank_20d(trunk_output).squeeze(-1), 

205 "beta_neutral_rank_20d": self.head_beta_neutral_rank_20d(trunk_output).squeeze(-1), 

206 } 

207 

208 

209class AetherNetSequenceMultiTask(nn.Module): 

210 """Phase 2: a causal TCN (temporal convolutional network) trunk over a 

211 rolling window of already-computed flat model_input vectors, replacing 

212 AetherNetMultiTask's flat-MLP trunk with genuine temporal structure - 

213 the root limitation the original root-cause investigation flagged 

214 ("AetherNet is a plain feedforward MLP with zero temporal structure"). 

215 

216 A stack of causal, dilated Conv1d layers (dilation doubling each layer: 

217 1, 2, 4, ... - the standard WaveNet/TCN receptive-field-growth idiom), 

218 each left-padded by (kernel_size-1)*dilation timesteps before the conv 

219 so output[t] never depends on input[>t] (no lookahead, same invariant 

220 every other feature in this codebase already respects) - matching 

221 inference/exported_model.py::_conv1d_causal()'s exact convention. 

222 Pools to the trunk's most-recent (causal) timestep, then the same 

223 three direction/magnitude/volatility heads AetherNetMultiTask already 

224 uses. 

225 

226 Chosen over a Transformer encoder block for this first real Phase 2 

227 model specifically because a causal conv stack is simpler to verify 

228 bit-for-bit end-to-end (see 

229 inference/exported_model.py::run_exported_sequence_multitask_model()) - 

230 _multihead_attention() is implemented and independently tested as 

231 interpreter infrastructure for a future attention-based model, not 

232 wired to a trained model in this pass; see train_sequence.py's module 

233 docstring for the fuller scope note. 

234 """ 

235 

236 def __init__( 

237 self, 

238 input_dim: int, 

239 channels: list[int], 

240 kernel_size: int, 

241 dropout: float, 

242 ) -> None: 

243 super().__init__() 

244 if not channels: 

245 raise ValueError("AetherNetSequenceMultiTask requires at least one trunk channel size.") 

246 self.kernel_size = int(kernel_size) 

247 self.conv_layers = nn.ModuleList() 

248 current_channels = input_dim 

249 for layer_index, out_channels in enumerate(channels): 

250 dilation = 2**layer_index 

251 self.conv_layers.append(nn.Conv1d(current_channels, out_channels, self.kernel_size, dilation=dilation)) 

252 current_channels = out_channels 

253 self.activation = nn.ReLU() 

254 self.dropout = nn.Dropout(dropout) if dropout > 0 else nn.Identity() 

255 self.head_direction = nn.Linear(current_channels, 1) 

256 self.head_magnitude = nn.Linear(current_channels, 1) 

257 self.head_volatility = nn.Linear(current_channels, 1) 

258 

259 def forward(self, sequence: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: 

260 # sequence: (batch, window, input_dim) -> Conv1d wants channels-first. 

261 current = sequence.transpose(1, 2) # (batch, input_dim, window) 

262 for _layer_index, conv in enumerate(self.conv_layers): 

263 dilation = conv.dilation[0] 

264 pad_left = (self.kernel_size - 1) * dilation 

265 current = nn.functional.pad(current, (pad_left, 0)) 

266 current = conv(current) 

267 current = self.dropout(self.activation(current)) 

268 

269 pooled = current[:, :, -1] # (batch, channels[-1]) - most-recent timestep 

270 direction_logit = self.head_direction(pooled).squeeze(-1) 

271 magnitude = self.head_magnitude(pooled).squeeze(-1) 

272 volatility = nn.functional.softplus(self.head_volatility(pooled).squeeze(-1)) 

273 return direction_logit, magnitude, volatility 

274 

275 

276class AetherNetSequenceMultiTaskHorizons(nn.Module): 

277 """Sequence-encoder sibling of AetherNetMultiTaskHorizons: the same 

278 causal TCN trunk as AetherNetSequenceMultiTask, extended with the same 

279 4 additional heads (direction_5d/20d, rank_5d/20d). A NEW class, not a 

280 modification of AetherNetSequenceMultiTask - same reasoning as 

281 AetherNetMultiTaskHorizons above (experts never use the sequence 

282 model at all, so there is no shared-code risk here, but the 

283 new-sibling-class convention stays consistent across both trainers). 

284 forward() returns a dict, matching AetherNetMultiTaskHorizons and the 

285 export's "heads" dict shape.""" 

286 

287 def __init__( 

288 self, 

289 input_dim: int, 

290 channels: list[int], 

291 kernel_size: int, 

292 dropout: float, 

293 normalization: str = "none", 

294 ) -> None: 

295 super().__init__() 

296 if not channels: 

297 raise ValueError("AetherNetSequenceMultiTaskHorizons requires at least one trunk channel size.") 

298 self.kernel_size = int(kernel_size) 

299 # V5.1 Phase 3 (item 10) - the TCN trunk previously had NO 

300 # normalization at all (Conv1d -> ReLU -> Dropout only), unlike 

301 # AetherNetMultiTaskHorizons' MLP trunk (which already supports 

302 # LayerNorm). normalization="none" is the FUNCTION default - 

303 # byte-identical to every existing caller/checkpoint when this 

304 # param is omitted. "layernorm" inserts an nn.LayerNorm(out_channels) 

305 # after each Conv1d->ReLU, normalizing over the CHANNEL axis per 

306 # timestep - see forward()'s transpose comment for why, and 

307 # export_sequence_multitask_horizons_architecture()/ 

308 # _export_conv1d_trunk() for the matching "layernorm_axis" export 

309 # layer (already supported by inference/exported_model.py with 

310 # zero interpreter changes - see that module's own docstring). 

311 self.normalization = str(normalization) 

312 self.conv_layers = nn.ModuleList() 

313 self.layer_norms = nn.ModuleList() 

314 current_channels = input_dim 

315 for layer_index, out_channels in enumerate(channels): 

316 dilation = 2**layer_index 

317 self.conv_layers.append(nn.Conv1d(current_channels, out_channels, self.kernel_size, dilation=dilation)) 

318 self.layer_norms.append(nn.LayerNorm(out_channels) if self.normalization == "layernorm" else nn.Identity()) 

319 current_channels = out_channels 

320 self.activation = nn.ReLU() 

321 self.dropout = nn.Dropout(dropout) if dropout > 0 else nn.Identity() 

322 self.head_direction = nn.Linear(current_channels, 1) 

323 self.head_magnitude = nn.Linear(current_channels, 1) 

324 self.head_volatility = nn.Linear(current_channels, 1) 

325 self.head_direction_5d = nn.Linear(current_channels, 1) 

326 self.head_direction_20d = nn.Linear(current_channels, 1) 

327 self.head_rank_5d = nn.Linear(current_channels, 1) 

328 self.head_rank_20d = nn.Linear(current_channels, 1) 

329 # Phase 5 of the 5/10 -> 9/10 roadmap - see 

330 # AetherNetMultiTaskHorizons.head_sector_neutral_rank_20d's 

331 # identical docstring. 

332 self.head_sector_neutral_rank_20d = nn.Linear(current_channels, 1) 

333 # V5.1 Phase 2 (item 5 of the roadmap) - see 

334 # AetherNetMultiTaskHorizons's identical new-heads docstring above. 

335 self.head_residual_rank_5d = nn.Linear(current_channels, 1) 

336 self.head_residual_rank_20d = nn.Linear(current_channels, 1) 

337 self.head_beta_neutral_rank_20d = nn.Linear(current_channels, 1) 

338 

339 def forward(self, sequence: torch.Tensor) -> dict[str, torch.Tensor]: 

340 current = sequence.transpose(1, 2) # (batch, input_dim, window) 

341 for conv, layer_norm in zip(self.conv_layers, self.layer_norms, strict=False): 

342 dilation = conv.dilation[0] 

343 pad_left = (self.kernel_size - 1) * dilation 

344 current = nn.functional.pad(current, (pad_left, 0)) 

345 current = self.activation(conv(current)) 

346 if self.normalization == "layernorm": 

347 # nn.LayerNorm(out_channels) normalizes over its last dim - 

348 # current is (batch, channels, window) (PyTorch's own 

349 # Conv1d convention), so transpose to (batch, window, 

350 # channels) first (normalize each timestep's channel 

351 # vector independently), then back. Matches 

352 # inference/exported_model.py's _layernorm_axis(axis=-1) 

353 # on a (window, channels) array exactly - same per- 

354 # timestep, per-channel-axis normalization, just with an 

355 # extra leading batch dim here. 

356 current = layer_norm(current.transpose(1, 2)).transpose(1, 2) 

357 current = self.dropout(current) 

358 

359 pooled = current[:, :, -1] # (batch, channels[-1]) - most-recent timestep 

360 return { 

361 "direction": self.head_direction(pooled).squeeze(-1), 

362 "magnitude": self.head_magnitude(pooled).squeeze(-1), 

363 "volatility": nn.functional.softplus(self.head_volatility(pooled).squeeze(-1)), 

364 "direction_5d": self.head_direction_5d(pooled).squeeze(-1), 

365 "direction_20d": self.head_direction_20d(pooled).squeeze(-1), 

366 "rank_5d": self.head_rank_5d(pooled).squeeze(-1), 

367 "rank_20d": self.head_rank_20d(pooled).squeeze(-1), 

368 "sector_neutral_rank_20d": self.head_sector_neutral_rank_20d(pooled).squeeze(-1), 

369 "residual_rank_5d": self.head_residual_rank_5d(pooled).squeeze(-1), 

370 "residual_rank_20d": self.head_residual_rank_20d(pooled).squeeze(-1), 

371 "beta_neutral_rank_20d": self.head_beta_neutral_rank_20d(pooled).squeeze(-1), 

372 } 

373 

374 

375def _export_conv1d_trunk(model) -> list[dict]: 

376 """Shared by export_sequence_multitask_architecture() and 

377 export_sequence_multitask_horizons_architecture() - both models build 

378 their causal TCN trunk identically (AetherNetSequenceMultiTask/ 

379 AetherNetSequenceMultiTaskHorizons.__init__ are the same conv-stack 

380 loop), only their heads differ. 

381 

382 V5.1 Phase 3 (item 10): AetherNetSequenceMultiTask (the older sibling) 

383 has no `normalization`/`layer_norms` attribute at all - 

384 getattr(..., "none")/getattr(..., None) below degrade it to the 

385 pre-Phase-3 trunk shape exactly (no layernorm_axis entries), so this 

386 stays a true shared helper rather than needing two near-duplicate 

387 versions.""" 

388 trunk: list[dict] = [] 

389 use_layernorm = getattr(model, "normalization", "none") == "layernorm" 

390 layer_norms = getattr(model, "layer_norms", None) 

391 for layer_index, conv in enumerate(model.conv_layers): 

392 trunk.append( 

393 { 

394 "type": "conv1d_causal", 

395 "weight_key": f"conv_layers.{layer_index}.weight", 

396 "bias_key": f"conv_layers.{layer_index}.bias", 

397 "dilation": conv.dilation[0], 

398 "in_channels": conv.in_channels, 

399 "out_channels": conv.out_channels, 

400 "kernel_size": conv.kernel_size[0], 

401 } 

402 ) 

403 trunk.append({"type": "relu"}) 

404 if use_layernorm and layer_norms is not None: 

405 layer_norm = layer_norms[layer_index] 

406 trunk.append( 

407 { 

408 "type": "layernorm_axis", 

409 "weight_key": f"layer_norms.{layer_index}.weight", 

410 "bias_key": f"layer_norms.{layer_index}.bias", 

411 "eps": layer_norm.eps, 

412 } 

413 ) 

414 trunk.append({"type": "dropout", "p": model.dropout.p if isinstance(model.dropout, nn.Dropout) else 0.0}) 

415 return trunk 

416 

417 

418def export_sequence_multitask_architecture(model: AetherNetSequenceMultiTask) -> dict[str, Any]: 

419 """Branching export for AetherNetSequenceMultiTask - same {"trunk": 

420 [...], "heads": {...}} shape export_multitask_architecture() produces, 

421 but trunk entries are "conv1d_causal" layers (each carrying its own 

422 dilation, doubling per layer to match __init__'s dilation=2**layer_index) 

423 instead of "linear". Consumed by 

424 inference/exported_model.py::run_exported_sequence_multitask_model().""" 

425 return { 

426 "trunk": _export_conv1d_trunk(model), 

427 "heads": { 

428 "direction": _export_head(model.head_direction, "head_direction", "sigmoid"), 

429 "magnitude": _export_head(model.head_magnitude, "head_magnitude", None), 

430 "volatility": _export_head(model.head_volatility, "head_volatility", "softplus"), 

431 }, 

432 } 

433 

434 

435def export_sequence_multitask_horizons_architecture(model: AetherNetSequenceMultiTaskHorizons) -> dict[str, Any]: 

436 """Branching export for AetherNetSequenceMultiTaskHorizons - same 

437 {"trunk", "heads"} shape export_sequence_multitask_architecture() 

438 produces for the original 3-head sequence model, extended with 4 more 

439 head entries (direction_5d/20d, rank_5d/20d). 

440 inference/exported_model.py::run_exported_sequence_multitask_model() 

441 already iterates export["heads"] generically, so no interpreter change 

442 is needed to support the extra heads. 

443 

444 V5.1 Phase 1 (development/Problems.md #73): rank_5d/rank_20d/ 

445 sector_neutral_rank_20d export with NO final activation (was 

446 "sigmoid") - these heads are trained as raw linear regression against a 

447 [0,1] percentile-rank target (masked_mse_loss() in 

448 compute_combined_multitask_loss()), never through a sigmoid, so 

449 exporting one applied a transform inference never trained through: 

450 live predicted_rank_20d compressed into roughly [0.5, 0.7] instead of 

451 spanning [0,1] (sigmoid'(0.5)~=0.235 shrinks dispersion ~4x). Rank-IC 

452 (this project's own promotion-gate metric) is invariant under any 

453 monotone transform, which is exactly why no rank-IC-based gate ever 

454 caught it - it took building an offline net-of-cost simulator 

455 (evaluation/rank_book_simulator.py) sensitive to the ACTUAL 

456 dispersion to surface it. The fix pairs with 

457 portfolio/rank_signal.py::cross_sectional_rank_scores() (main.py), 

458 which re-derives a true [0,1] percentile per bar regardless of 

459 whatever raw scale a head happens to export at - so this export 

460 change is safe even for a stale artifact still carrying the old 

461 "sigmoid" entry (monotone-invariant either way).""" 

462 return { 

463 "trunk": _export_conv1d_trunk(model), 

464 "heads": { 

465 "direction": _export_head(model.head_direction, "head_direction", "sigmoid"), 

466 "magnitude": _export_head(model.head_magnitude, "head_magnitude", None), 

467 "volatility": _export_head(model.head_volatility, "head_volatility", "softplus"), 

468 "direction_5d": _export_head(model.head_direction_5d, "head_direction_5d", "sigmoid"), 

469 "direction_20d": _export_head(model.head_direction_20d, "head_direction_20d", "sigmoid"), 

470 "rank_5d": _export_head(model.head_rank_5d, "head_rank_5d", None), 

471 "rank_20d": _export_head(model.head_rank_20d, "head_rank_20d", None), 

472 "sector_neutral_rank_20d": _export_head( 

473 model.head_sector_neutral_rank_20d, "head_sector_neutral_rank_20d", None 

474 ), 

475 # V5.1 Phase 2 (item 5) - activation None, same reasoning as 

476 # rank_5d/rank_20d/sector_neutral_rank_20d above: trained as 

477 # raw linear regression against a [0,1] percentile target, 

478 # never through a sigmoid. 

479 "residual_rank_5d": _export_head(model.head_residual_rank_5d, "head_residual_rank_5d", None), 

480 "residual_rank_20d": _export_head(model.head_residual_rank_20d, "head_residual_rank_20d", None), 

481 "beta_neutral_rank_20d": _export_head( 

482 model.head_beta_neutral_rank_20d, "head_beta_neutral_rank_20d", None 

483 ), 

484 }, 

485 } 

486 

487 

488# Head name -> (target column, "binary"/"rank", non_overlapping_stride for 

489# rank-IC's non-overlapping subsample - unused by binary heads). Shared by 

490# train_multitask.py/train_sequence.py - both trainers' Horizons model 

491# variants expose identically-named heads (see 

492# AetherNetMultiTaskHorizons/AetherNetSequenceMultiTaskHorizons docstrings). 

493HORIZON_HEAD_SPECS = { 

494 "direction_5d": ("target_direction_5d", "binary", None), 

495 "direction_20d": ("target_direction_20d", "binary", None), 

496 "rank_5d": ("target_rank_5d", "rank", 5), 

497 "rank_20d": ("target_rank_20d", "rank", 20), 

498 # Phase 5 of the 5/10 -> 9/10 roadmap - a "rank"-kind head like rank_20d, 

499 # so it automatically gets the exact same masked-MSE loss, rank-IC 

500 # metrics, AND assess_ranking_quality_from_predictions() promotion-gate 

501 # assessment as rank_20d, with zero extra wiring beyond this entry - 

502 # every consumer of HORIZON_HEAD_SPECS (compute_combined_multitask_loss(), 

503 # compute_multitask_metrics()/compute_sequence_multitask_metrics()) is 

504 # already fully generic over this dict. 

505 "sector_neutral_rank_20d": ("target_sector_neutral_rank_20d", "rank", 20), 

506 # V5.1 Phase 2 (item 5 of the roadmap) - see 

507 # train.py::build_residual_rank_targets()'s docstring. Same "rank"-kind 

508 # generic wiring as sector_neutral_rank_20d above - zero extra plumbing 

509 # beyond these entries. 

510 "residual_rank_5d": ("target_residual_rank_5d", "rank", 5), 

511 "residual_rank_20d": ("target_residual_rank_20d", "rank", 20), 

512 # Computed by build_cross_sectional_rank_targets() (a single whole- 

513 # history per-asset market beta, simpler than residual_rank_20d's 

514 # combined market+sector+size regression) but ships with NO active 

515 # head by default (see DEFAULT_HORIZON_HEAD_CONFIG below) - strictly 

516 # dominated by residual_rank_20d, registered only so it stops being 

517 # fully dead code and gets full metrics on a one-key config flip. 

518 "beta_neutral_rank_20d": ("target_beta_neutral_rank_20d", "rank", 20), 

519} 

520# V6.0.0: heads that exist only when a trainer's horizon_heads block enables them (and the dataset carries the target, 

521# phase1.target.ranking.extra_horizon_days); never part of the default model, export or metrics. 

522EXTRA_HORIZON_HEAD_SPECS = { 

523 "rank_60d": ("target_rank_60d", "rank", 60), 

524} 

525 

526 

527def enabled_extra_heads(horizon_head_config: dict[str, Any]) -> tuple[str, ...]: 

528 """The extra horizon heads a horizon-head config switches on, in a fixed order.""" 

529 return tuple(name for name in EXTRA_HORIZON_HEAD_SPECS if horizon_head_config.get(name, {}).get("enabled", False)) 

530 

531 

532def horizon_head_specs(horizon_head_config: dict[str, Any]) -> dict[str, Any]: 

533 """HORIZON_HEAD_SPECS plus every enabled extra head (identical to HORIZON_HEAD_SPECS when none is).""" 

534 return HORIZON_HEAD_SPECS | {name: EXTRA_HORIZON_HEAD_SPECS[name] for name in enabled_extra_heads(horizon_head_config)} 

535 

536 

537DEFAULT_HORIZON_HEAD_CONFIG = { 

538 "direction_5d": {"enabled": True, "loss_weight": 1.0}, 

539 "direction_20d": {"enabled": True, "loss_weight": 0.5}, 

540 "rank_5d": {"enabled": True, "loss_weight": 1.0}, 

541 "rank_20d": {"enabled": True, "loss_weight": 0.5}, 

542 # Lighter weight than rank_20d - the newest, least-validated head; 

543 # doesn't dominate training until its own promotion criteria clear. 

544 "sector_neutral_rank_20d": {"enabled": True, "loss_weight": 0.3}, 

545 # V5.1 Phase 2 (item 5) - residual_rank_20d is meant to become the 

546 # cleanest live signal once validated (market+sector+size already 

547 # factored out), so it trains at rank_20d's own original weight; 

548 # residual_rank_5d lighter, matching rank_5d/rank_20d's own 1.0/0.5 

549 # split convention. beta_neutral_rank_20d disabled/zero-weight - see 

550 # HORIZON_HEAD_SPECS's own comment for why. 

551 "residual_rank_5d": {"enabled": True, "loss_weight": 0.5}, 

552 "residual_rank_20d": {"enabled": True, "loss_weight": 1.0}, 

553 "beta_neutral_rank_20d": {"enabled": False, "loss_weight": 0.0}, 

554} 

555 

556 

557def resolve_horizon_head_config(training_config: dict[str, Any]) -> dict[str, Any]: 

558 """Merges a trainer's own config.json horizon_heads block (e.g. 

559 phase_v2.retraining.multitask_training.horizon_heads or 

560 ...sequence_training.horizon_heads) over DEFAULT_HORIZON_HEAD_CONFIG - 

561 an older config missing this key entirely (or missing one head's 

562 entry) still gets sane defaults for every head, rather than silently 

563 treating an absent head as disabled.""" 

564 configured = training_config.get("horizon_heads", {}) 

565 resolved = {} 

566 for head_name, defaults in DEFAULT_HORIZON_HEAD_CONFIG.items(): 

567 head_config = {**defaults, **configured.get(head_name, {})} 

568 resolved[head_name] = head_config 

569 for head_name in EXTRA_HORIZON_HEAD_SPECS: 

570 if head_name in configured: 

571 resolved[head_name] = {"enabled": False, "loss_weight": 0.0, **configured[head_name]} 

572 return resolved 

573 

574 

575def export_state_dict(model: nn.Module) -> dict[str, Any]: 

576 """A model's weights as nested lists, the JSON the numpy forward pass reads.""" 

577 exported = {} 

578 for key, value in model.state_dict().items(): 

579 exported[key] = value.detach().cpu().tolist() 

580 return exported 

581 

582 

583def _export_sequential_layers(sequential_module: nn.Sequential, key_prefix: str) -> list[dict]: 

584 """Per-layer export walk shared by export_architecture() (prefix 

585 "network") and export_multitask_architecture()'s trunk (prefix "trunk") 

586 below - extracted verbatim from the original export_architecture() body, 

587 a behavior-preserving refactor (same dict shapes, same key naming).""" 

588 architecture: list[dict] = [] 

589 for index, module in enumerate(sequential_module): 

590 if isinstance(module, nn.Linear): 

591 architecture.append( 

592 { 

593 "type": "linear", 

594 "weight_key": f"{key_prefix}.{index}.weight", 

595 "bias_key": f"{key_prefix}.{index}.bias", 

596 "in_features": module.in_features, 

597 "out_features": module.out_features, 

598 } 

599 ) 

600 elif isinstance(module, nn.LayerNorm): 

601 architecture.append( 

602 { 

603 "type": "layernorm", 

604 "weight_key": f"{key_prefix}.{index}.weight", 

605 "bias_key": f"{key_prefix}.{index}.bias", 

606 "normalized_shape": list(module.normalized_shape), 

607 "eps": module.eps, 

608 } 

609 ) 

610 elif isinstance(module, nn.BatchNorm1d): 

611 architecture.append( 

612 { 

613 "type": "batchnorm1d", 

614 "weight_key": f"{key_prefix}.{index}.weight", 

615 "bias_key": f"{key_prefix}.{index}.bias", 

616 "running_mean_key": f"{key_prefix}.{index}.running_mean", 

617 "running_var_key": f"{key_prefix}.{index}.running_var", 

618 "num_features": module.num_features, 

619 "eps": module.eps, 

620 } 

621 ) 

622 elif isinstance(module, nn.ReLU): 

623 architecture.append({"type": "relu"}) 

624 elif isinstance(module, nn.GELU): 

625 architecture.append({"type": "gelu"}) 

626 elif isinstance(module, nn.SiLU): 

627 architecture.append({"type": "silu"}) 

628 elif isinstance(module, nn.Dropout): 

629 architecture.append({"type": "dropout", "p": module.p}) 

630 else: 

631 architecture.append({"type": module.__class__.__name__.lower()}) 

632 return architecture 

633 

634 

635def export_architecture(model: AetherNet) -> list[dict]: 

636 """The baseline network's layers as the JSON the numpy forward pass reads.""" 

637 architecture = _export_sequential_layers(model.network, "network") 

638 architecture.append({"type": "sigmoid"}) 

639 return architecture 

640 

641 

642def _export_head(module: nn.Linear, key_prefix: str, final_activation: str | None) -> list[dict]: 

643 """A single head's export: one Linear layer plus its final activation 

644 (or none, for the raw-regression magnitude head). Heads are 

645 deliberately restricted to a single Linear - inference/exported_model.py:: 

646 run_exported_multitask_model() and AetherNetMultiTask both assume this 

647 shape; a deeper head would need matching changes in both places.""" 

648 head: list[dict] = [ 

649 { 

650 "type": "linear", 

651 "weight_key": f"{key_prefix}.weight", 

652 "bias_key": f"{key_prefix}.bias", 

653 "in_features": module.in_features, 

654 "out_features": module.out_features, 

655 } 

656 ] 

657 if final_activation is not None: 

658 head.append({"type": final_activation}) 

659 return head 

660 

661 

662def export_multitask_architecture(model: AetherNetMultiTask) -> dict[str, Any]: 

663 """Branching export for AetherNetMultiTask - a {"trunk": [...], "heads": 

664 {"direction": [...], "magnitude": [...], "volatility": [...]}} structure 

665 instead of export_architecture()'s single flat list. Consumed by 

666 inference/exported_model.py::run_exported_multitask_model(), never by 

667 run_exported_model() (which only understands a flat "architecture" list 

668 and would KeyError on this shape - the two exports are not 

669 interchangeable, matching the two different interpreter entry points).""" 

670 return { 

671 "trunk": _export_sequential_layers(model.trunk, "trunk"), 

672 "heads": { 

673 "direction": _export_head(model.head_direction, "head_direction", "sigmoid"), 

674 "magnitude": _export_head(model.head_magnitude, "head_magnitude", None), 

675 "volatility": _export_head(model.head_volatility, "head_volatility", "softplus"), 

676 }, 

677 } 

678 

679 

680def export_multitask_horizons_architecture(model: AetherNetMultiTaskHorizons) -> dict[str, Any]: 

681 """Branching export for AetherNetMultiTaskHorizons - same {"trunk", 

682 "heads"} shape export_multitask_architecture() produces for the 

683 original 3-head model, extended with 4 more head entries (direction_5d/ 

684 20d, rank_5d/20d). inference/exported_model.py::run_exported_multitask_model() 

685 already iterates export["heads"] generically, so no interpreter change 

686 is needed to support the extra heads. 

687 

688 V5.1 Phase 1 (development/Problems.md #73): rank_5d/rank_20d/ 

689 sector_neutral_rank_20d export with NO final activation (was 

690 "sigmoid") - see export_sequence_multitask_horizons_architecture()'s 

691 matching docstring for the full writeup (same bug, same fix, both 

692 model families).""" 

693 return { 

694 "trunk": _export_sequential_layers(model.trunk, "trunk"), 

695 "heads": { 

696 "direction": _export_head(model.head_direction, "head_direction", "sigmoid"), 

697 "magnitude": _export_head(model.head_magnitude, "head_magnitude", None), 

698 "volatility": _export_head(model.head_volatility, "head_volatility", "softplus"), 

699 "direction_5d": _export_head(model.head_direction_5d, "head_direction_5d", "sigmoid"), 

700 "direction_20d": _export_head(model.head_direction_20d, "head_direction_20d", "sigmoid"), 

701 "rank_5d": _export_head(model.head_rank_5d, "head_rank_5d", None), 

702 "rank_20d": _export_head(model.head_rank_20d, "head_rank_20d", None), 

703 "sector_neutral_rank_20d": _export_head( 

704 model.head_sector_neutral_rank_20d, "head_sector_neutral_rank_20d", None 

705 ), 

706 # V5.1 Phase 2 (item 5) - activation None, same reasoning as 

707 # rank_5d/rank_20d/sector_neutral_rank_20d above. 

708 "residual_rank_5d": _export_head(model.head_residual_rank_5d, "head_residual_rank_5d", None), 

709 "residual_rank_20d": _export_head(model.head_residual_rank_20d, "head_residual_rank_20d", None), 

710 "beta_neutral_rank_20d": _export_head( 

711 model.head_beta_neutral_rank_20d, "head_beta_neutral_rank_20d", None 

712 ), 

713 } 

714 | { 

715 name: _export_head(getattr(model, f"head_{name}"), f"head_{name}", None) 

716 for name in getattr(model, "extra_heads", ()) 

717 }, 

718 }