Coverage for monitoring/neural_network_state.py: 100%
165 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Neural-network layer/node/edge state for Aether Quant V2's webui (V2-20).
3Reads the JSON-exported weights train.py already produces for the baseline
4model and the 4 MoE experts (ml/model_weights.json,
5ml/expert_models/<name>/model_weights.json), plus the optional learned
6gating blend (ml/gating_model.json, see moe/gating.py's
7GATING_MODEL_FEATURE_KEYS/build_gating_model_features()) when
8train_gating.py has produced one - and reshapes all of them into a
9network-agnostic layer/node/edge summary the webui renders as an
10interactive 3D diagram. Pure, read-only - never trains anything, never
11touches the binary ml/model.pt checkpoints, only the JSON exports meant for
12non-PyTorch consumers (same exports main.py's own _run_exported_model
13interpreter reads).
15Also reads the 6 optional multitask/sequence networks added in the
16multitask/sequence pass: ml/multitask_model.json (baseline_multitask),
17ml/expert_models/<name>/multitask_model.json (<name>_multitask, one per
18expert) and ml/sequence_model.json (sequence, the Phase 2 causal-TCN
19encoder). These use a branching `{"trunk": [...], "heads": {"direction":
20[...], "magnitude": [...], "volatility": [...]}}` export shape instead of
21the flat `architecture` list the baseline/expert/gating networks use -
22_parse_network_export() dispatches between the two shapes automatically.
23`sequence`'s trunk also has conv1d_causal layers (in_channels/out_channels
24instead of linear's in_features/out_features, and a 3D weight matrix) -
25see _flatten()/_weight_stats() below.
27The gating network degrades to status="not_trained" (same as any other
28network here) until a gating model has actually been trained - see `aq
29train --gating-only` or the retraining pipeline's best-effort
30train_gating() stage. Before a learned gating model exists, moe/gating.py
31still runs its deterministic hardcoded blend at runtime; that fallback
32path has no weight matrix and is not itself represented as a network here.
34The learned-topology KMeans prototypes (topology/learned_topology.py) are
35deliberately excluded - it's cluster centroids, not a layered network, so
36there is nothing to lay out as layers/nodes/edges. Its absence is reported
37explicitly via `excluded` rather than left silent.
38"""
40from __future__ import annotations
42import itertools
43from dataclasses import asdict, dataclass, field
44from datetime import datetime, timezone
45from pathlib import Path
47from json_safety import load_json_lenient
49EXPERT_NAMES = ("bullish", "bearish", "sideways", "volatility")
51DEFAULT_ML_DIR = Path(__file__).resolve().parent.parent / "ml"
53EXCLUDED_NON_NETWORKS = [
54 {
55 "name": "learned_topology",
56 "reason": (
57 "KMeans cluster prototype centroids (topology/learned_topology.py), "
58 "not a layered network"
59 ),
60 },
61]
64@dataclass(frozen=True)
65class NetworkLayer:
66 index: int
67 type: str
68 in_features: int | None
69 out_features: int | None
70 weight_abs_mean: float | None
71 weight_abs_max: float | None
72 head: str | None = None
74 def to_dict(self) -> dict:
75 return asdict(self)
78@dataclass(frozen=True)
79class NetworkSummary:
80 name: str
81 label: str
82 role: str
83 status: str
84 quality_status: str | None
85 node_layers: list[int]
86 layers: list[NetworkLayer]
87 total_layers: int
88 total_nodes: int
89 total_edges: int
90 last_modified: str | None
91 heads: dict[str, list[int]] = field(default_factory=dict)
92 # Multi-horizon/ranking evaluation (Phase 3/4/6) - only populated for
93 # baseline_multitask/sequence (the two networks with horizon_5d/20d and
94 # rank_5d/20d heads; experts/expert_multitask stay 1d-direction-only by
95 # design, see development/Changelog.md). None when the network has no
96 # such heads or hasn't been retrained since these metrics existed -
97 # graceful degradation, same contract as quality_status above.
98 horizon_mcc: dict | None = None
99 rank_ic: dict | None = None
100 # Phase 2's per-head promotion-gate verdict (quality_status/
101 # promotion_eligible/observed CI/eras) - see _extract_horizon_evaluation_summary().
102 ranking_quality: dict | None = None
103 # V5.1 Phase 4 (items 7, 12) - assess_net_performance_quality()'s
104 # verdict (net Sharpe/turnover/capacity, double-cost stress), only
105 # populated for whichever ONE head net_performance is configured for.
106 net_performance: dict | None = None
107 regression_quality: dict | None = None
108 # V5.1 Phase 3 (items 1, 10, 11) - the actual optimizer/schedule/batch-
109 # mode/ranking-loss/SWA recipe THIS candidate trained with (written by
110 # train_multitask.py/train_sequence.py's own "training_recipe" metrics
111 # field) - makes "which model am I looking at" answerable from the UI.
112 # None for baseline/expert/gating (no such field in their metrics) or
113 # an older artifact trained before this existed.
114 training_recipe: dict | None = None
116 def to_dict(self) -> dict:
117 payload = asdict(self)
118 payload["layers"] = [layer.to_dict() for layer in self.layers]
119 return payload
122def _flatten(value) -> list[float]:
123 """Flattens an arbitrarily-nested list of numbers. linear weights are
124 2D ([out][in]); conv1d_causal weights are 3D ([out_channels]
125 [in_channels][kernel_size]) - this handles both without needing to
126 know the layer type in advance."""
127 if isinstance(value, list):
128 flat: list[float] = []
129 for item in value:
130 flat.extend(_flatten(item))
131 return flat
132 return [float(value)]
135def _weight_stats(state_dict: dict, weight_key: str) -> tuple[float, float]:
136 matrix = state_dict.get(weight_key)
137 if not matrix:
138 return 0.0, 0.0
139 flat = [abs(value) for value in _flatten(matrix)]
140 if not flat:
141 return 0.0, 0.0
142 return sum(flat) / len(flat), max(flat)
145# Layer types whose weight is 2D and keyed by in_features/out_features.
146_LINEAR_LAYER_TYPES = {"linear"}
147# Layer types whose weight is 3D and keyed by in_channels/out_channels.
148_CONV_LAYER_TYPES = {"conv1d_causal"}
151def _append_layer_specs(
152 layer_specs: list[dict],
153 state_dict: dict,
154 start_index: int,
155 head: str | None,
156) -> tuple[list[NetworkLayer], list[int]]:
157 """Shared per-layer-type dispatch used by both the flat `architecture`
158 parse path and the branching `trunk`/`heads` parse path, so a linear or
159 conv1d_causal layer is handled identically regardless of which export
160 shape it came from."""
161 layers: list[NetworkLayer] = []
162 node_layers: list[int] = []
164 for offset, layer_spec in enumerate(layer_specs):
165 layer_type = layer_spec.get("type", "unknown")
166 weighted = layer_type in _LINEAR_LAYER_TYPES or layer_type in _CONV_LAYER_TYPES
167 if layer_type in _LINEAR_LAYER_TYPES:
168 in_features = layer_spec.get("in_features")
169 out_features = layer_spec.get("out_features")
170 elif layer_type in _CONV_LAYER_TYPES:
171 in_features = layer_spec.get("in_channels")
172 out_features = layer_spec.get("out_channels")
173 else:
174 in_features = layer_spec.get("in_features")
175 out_features = layer_spec.get("out_features")
177 weight_abs_mean = weight_abs_max = None
178 if weighted:
179 weight_abs_mean, weight_abs_max = _weight_stats(state_dict, layer_spec["weight_key"])
180 if not node_layers:
181 node_layers.append(int(in_features))
182 node_layers.append(int(out_features))
184 layers.append(
185 NetworkLayer(
186 index=start_index + offset,
187 type=layer_type,
188 in_features=in_features,
189 out_features=out_features,
190 weight_abs_mean=weight_abs_mean,
191 weight_abs_max=weight_abs_max,
192 head=head,
193 )
194 )
195 return layers, node_layers
198def _parse_flat_network_export(export: dict) -> tuple[list[NetworkLayer], list[int], dict[str, list[int]]]:
199 architecture = export.get("architecture", [])
200 state_dict = export.get("state_dict", {})
201 layers, node_layers = _append_layer_specs(architecture, state_dict, start_index=0, head=None)
202 return layers, node_layers, {}
205def _parse_branching_network_export(export: dict) -> tuple[list[NetworkLayer], list[int], dict[str, list[int]]]:
206 """Parses the multitask/sequence `{"trunk": [...], "heads": {"direction":
207 [...], "magnitude": [...], "volatility": [...]}}` export shape - a
208 shared trunk feeding 3 independent output heads, instead of one flat
209 layer list. Trunk and each head's node_layers are kept separate (a head
210 is a branch off the trunk's output, not a continuation of the same
211 layer stack) so the webui can render each head as its own labeled
212 mini-network sharing the trunk."""
213 state_dict = export.get("state_dict", {})
214 trunk_specs = export.get("trunk", [])
215 head_specs = export.get("heads", {})
217 layers, trunk_node_layers = _append_layer_specs(trunk_specs, state_dict, start_index=0, head=None)
219 heads_node_layers: dict[str, list[int]] = {}
220 next_index = len(layers)
221 for head_name, layer_specs in head_specs.items():
222 head_layers, head_node_layers = _append_layer_specs(
223 layer_specs, state_dict, start_index=next_index, head=head_name
224 )
225 layers.extend(head_layers)
226 heads_node_layers[head_name] = head_node_layers
227 next_index += len(head_layers)
229 return layers, trunk_node_layers, heads_node_layers
232def _parse_network_export(export: dict) -> tuple[list[NetworkLayer], list[int], dict[str, list[int]]]:
233 if "trunk" in export or "heads" in export:
234 return _parse_branching_network_export(export)
235 return _parse_flat_network_export(export)
238def _load_json(path: Path) -> dict | None:
239 # V5.4.7 (Problems.md #120): a file being rewritten mid-request (train.py
240 # refreshing *_training_metrics.json) previously raised JSONDecodeError
241 # -> /api/neural-network 500. Degrade to None like every sibling reader.
242 return load_json_lenient(path)
245def _last_modified(path: Path) -> str | None:
246 if not path.exists():
247 return None
248 return datetime.fromtimestamp(path.stat().st_mtime, tz=timezone.utc).isoformat()
251def _extract_horizon_evaluation_summary(training_metrics: dict | None) -> dict:
252 """Extracts horizon_mcc/rank_ic/regression_quality from a
253 *_training_metrics.json payload (train_multitask.py/train_sequence.py's
254 output shape) for NetworkSummary. Returns a dict of all-None values
255 when `training_metrics` is None or predates Phase 3/4 (an older
256 artifact with no horizon/rank heads at all) - the webui already treats
257 None as "not available" the same way it already does for
258 quality_status, no separate "unsupported" state needed."""
259 backtest_metrics = (training_metrics or {}).get("backtest", {})
261 horizon_mcc = {}
262 for head_name in ("direction_5d", "direction_20d"):
263 head_metrics = backtest_metrics.get(head_name)
264 horizon_mcc[head_name] = head_metrics.get("mcc") if head_metrics else None
266 rank_ic = {}
267 ranking_quality = {}
268 # sector_neutral_rank_20d (Phase 5 of the 5/10 -> 9/10 roadmap) and
269 # residual_rank_5d/20d + beta_neutral_rank_20d (V5.1 Phase 2, item 5):
270 # same rank-IC shape as rank_5d/20d, appended rather than replacing any
271 # of them - deliberately NOT sourced from train.py::HORIZON_HEAD_SPECS
272 # (this module must stay torch-free, see monitoring/README.md), so a
273 # future new rank head needs one name added here too.
274 # beta_neutral_rank_20d ships with no active head by default (see
275 # train.py::DEFAULT_HORIZON_HEAD_CONFIG) - included here anyway so it
276 # gets full webui visibility the moment someone flips it on, same
277 # "registered, not dead code" reasoning as the head itself.
278 for head_name in (
279 "rank_5d", "rank_20d", "sector_neutral_rank_20d",
280 "residual_rank_5d", "residual_rank_20d", "beta_neutral_rank_20d",
281 ):
282 ic_metrics = backtest_metrics.get(f"{head_name}_ic")
283 rank_ic[head_name] = ic_metrics if ic_metrics else None
284 # Phase 2's code-enforced promotion-gate verdict
285 # (train.py::assess_ranking_quality()) - a distinct concept from the
286 # `quality_status` field on NetworkSummary itself (that one is the
287 # older stable/watchlist/disabled_for_gating/learned direction-model
288 # gate). Only present when train_multitask.py/train_sequence.py's
289 # ranking_promotion_config was supplied for this backtest run.
290 quality_metrics = backtest_metrics.get(f"{head_name}_ranking_quality")
291 ranking_quality[head_name] = quality_metrics if quality_metrics else None
293 # V5.1 Phase 4 (items 7, 12) - assess_net_performance_quality()'s
294 # verdict, written alongside {head}_ranking_quality above by the same
295 # compute_multitask_metrics()/compute_sequence_multitask_metrics() call
296 # site, only for whichever ONE head phase1.target.ranking.net_performance.head
297 # is configured for (default rank_20d) - every other head's entry stays
298 # None, same "not computed for this head" convention ranking_quality
299 # already follows.
300 net_performance = {}
301 for head_name in (
302 "rank_5d", "rank_20d", "sector_neutral_rank_20d",
303 "residual_rank_5d", "residual_rank_20d", "beta_neutral_rank_20d",
304 ):
305 net_performance_metrics = backtest_metrics.get(f"{head_name}_net_performance")
306 net_performance[head_name] = net_performance_metrics if net_performance_metrics else None
308 regression_quality = {}
309 for quality_name in ("magnitude_quality", "volatility_quality"):
310 quality = (training_metrics or {}).get(quality_name)
311 regression_quality[quality_name.removesuffix("_quality")] = quality.get("quality_status") if quality else None
313 has_any_value = (
314 any(horizon_mcc.values())
315 or any(rank_ic.values())
316 or any(ranking_quality.values())
317 or any(net_performance.values())
318 or any(regression_quality.values())
319 )
320 if not has_any_value:
321 return {
322 "horizon_mcc": None, "rank_ic": None, "ranking_quality": None,
323 "net_performance": None, "regression_quality": None,
324 }
325 return {
326 "horizon_mcc": horizon_mcc,
327 "rank_ic": rank_ic,
328 "ranking_quality": ranking_quality,
329 "net_performance": net_performance,
330 "regression_quality": regression_quality,
331 }
334def _build_network_summary(
335 name: str,
336 label: str,
337 role: str,
338 weights_path: Path,
339 quality_status: str | None,
340 training_metrics: dict | None = None,
341) -> NetworkSummary:
342 evaluation_summary = _extract_horizon_evaluation_summary(training_metrics)
343 training_recipe = (training_metrics or {}).get("training_recipe")
344 payload = _load_json(weights_path)
345 if payload is None or "export" not in payload:
346 return NetworkSummary(
347 name=name,
348 label=label,
349 role=role,
350 status="not_trained",
351 quality_status=quality_status,
352 node_layers=[],
353 layers=[],
354 total_layers=0,
355 total_nodes=0,
356 total_edges=0,
357 last_modified=None,
358 heads={},
359 training_recipe=training_recipe,
360 **evaluation_summary,
361 )
363 layers, node_layers, heads_node_layers = _parse_network_export(payload["export"])
364 total_edges = sum(a * b for a, b in itertools.pairwise(node_layers))
365 total_edges += sum(
366 a * b for head_layers in heads_node_layers.values() for a, b in itertools.pairwise(head_layers)
367 )
369 return NetworkSummary(
370 name=name,
371 label=label,
372 role=role,
373 status="trained",
374 quality_status=quality_status,
375 node_layers=node_layers,
376 layers=layers,
377 total_layers=len(node_layers) + sum(len(head_layers) for head_layers in heads_node_layers.values()),
378 total_nodes=sum(node_layers) + sum(sum(head_layers) for head_layers in heads_node_layers.values()),
379 total_edges=total_edges,
380 last_modified=_last_modified(weights_path),
381 heads=heads_node_layers,
382 training_recipe=training_recipe,
383 **evaluation_summary,
384 )
387def build_neural_network_state(ml_dir: Path | None = None) -> dict:
388 """Reads ml/model_weights.json + ml/expert_models/*/model_weights.json +
389 the optional ml/gating_model.json and reshapes them into a
390 network-agnostic layer/node/edge summary. A missing export file
391 degrades that one network to status="not_trained" - never raises,
392 mirroring main.py's own optional-model loading."""
393 ml_dir = ml_dir or DEFAULT_ML_DIR
395 expert_metrics = _load_json(ml_dir / "expert_training_metrics.json") or {}
396 experts_metrics_block = expert_metrics.get("experts", {})
398 networks = [
399 _build_network_summary(
400 name="baseline",
401 label="Baseline Model",
402 role="baseline",
403 weights_path=ml_dir / "model_weights.json",
404 quality_status=None,
405 )
406 ]
408 for expert_name in EXPERT_NAMES:
409 quality_gate = experts_metrics_block.get(expert_name, {}).get("quality_gate", {})
410 quality_status = quality_gate.get("quality_status")
411 networks.append(
412 _build_network_summary(
413 name=expert_name,
414 label=f"{expert_name.capitalize()} Expert",
415 role="expert",
416 weights_path=ml_dir / "expert_models" / expert_name / "model_weights.json",
417 quality_status=quality_status,
418 )
419 )
421 # Learned gating blend (train_gating.py) - optional, same graceful
422 # degrade-to-not_trained contract as every other network here. Reuses
423 # the webui's existing "learned" badge tone (already used for the
424 # topology overlay) once a gating model file is actually present.
425 gating_weights_path = ml_dir / "gating_model.json"
426 networks.append(
427 _build_network_summary(
428 name="gating",
429 label="Gating Network",
430 role="gating",
431 weights_path=gating_weights_path,
432 quality_status="learned" if gating_weights_path.exists() else None,
433 )
434 )
436 # Multitask (direction + magnitude + volatility) networks - optional,
437 # same graceful degrade-to-not_trained contract. Branching trunk/heads
438 # export shape (see _parse_branching_network_export()), sharing the
439 # exact same file existence check as every other network here.
440 networks.append(
441 _build_network_summary(
442 name="baseline_multitask",
443 label="Baseline Multitask",
444 role="multitask",
445 weights_path=ml_dir / "multitask_model.json",
446 quality_status=None,
447 training_metrics=_load_json(ml_dir / "multitask_training_metrics.json"),
448 )
449 )
451 for expert_name in EXPERT_NAMES:
452 quality_gate = experts_metrics_block.get(expert_name, {}).get("quality_gate", {})
453 quality_status = quality_gate.get("quality_status")
454 networks.append(
455 _build_network_summary(
456 name=f"{expert_name}_multitask",
457 label=f"{expert_name.capitalize()} Expert Multitask",
458 role="expert_multitask",
459 weights_path=ml_dir / "expert_models" / expert_name / "multitask_model.json",
460 quality_status=quality_status,
461 )
462 )
464 # Phase 2 sequence encoder (causal TCN) - optional, informational only
465 # in main.py (never feeds gating/analyzer/sizing), but still a real
466 # trained network worth visualizing here like every other one.
467 networks.append(
468 _build_network_summary(
469 name="sequence",
470 label="Sequence Encoder (Phase 2)",
471 role="sequence",
472 weights_path=ml_dir / "sequence_model.json",
473 quality_status=None,
474 training_metrics=_load_json(ml_dir / "sequence_training_metrics.json"),
475 )
476 )
478 totals = {
479 "total_networks": len(networks),
480 "total_layers": sum(network.total_layers for network in networks),
481 "total_nodes": sum(network.total_nodes for network in networks),
482 "total_edges": sum(network.total_edges for network in networks),
483 "trained_count": sum(1 for network in networks if network.status == "trained"),
484 }
486 return {
487 "generated_at": datetime.now(timezone.utc).isoformat(),
488 "networks": [network.to_dict() for network in networks],
489 "totals": totals,
490 "excluded": EXCLUDED_NON_NETWORKS,
491 }