Coverage for moe/gating.py: 100%
199 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"""Gating logic for Aether Quant V2 Mixture-of-Experts."""
3from __future__ import annotations
5from dataclasses import asdict, dataclass
6from typing import Any
8from inference import run_exported_model
10EXPERT_NAMES = ("bullish", "bearish", "sideways", "volatility")
12# Fixed order, 26 dims - every value is already a bounded probability
13# [0,1] or a one-hot flag, so (unlike topology/learned_topology.py's
14# z-scored prototypes) no scaler/feature_stats is needed for this model.
15GATING_MODEL_FEATURE_KEYS = (
16 "bullish_probability_up", "bullish_quality_multiplier", "bullish_performance_score", "bullish_regime_alignment",
17 "bearish_probability_up", "bearish_quality_multiplier", "bearish_performance_score", "bearish_regime_alignment",
18 "sideways_probability_up", "sideways_quality_multiplier", "sideways_performance_score", "sideways_regime_alignment",
19 "volatility_probability_up", "volatility_quality_multiplier", "volatility_performance_score", "volatility_regime_alignment",
20 "baseline_probability_up",
21 "trend_regime_bullish", "trend_regime_bearish", "trend_regime_sideways",
22 "volatility_regime_low_volatility", "volatility_regime_normal_volatility", "volatility_regime_high_volatility",
23 "risk_regime_risk_on", "risk_regime_risk_off", "risk_regime_risk_neutral",
24)
27@dataclass(frozen=True)
28class ExpertGateWeight:
29 """One expert's weight in the gated blend, with its raw score."""
30 expert: str
31 weight: float
32 raw_score: float
33 probability_up: float | None
34 quality_status: str
35 quality_multiplier: float
36 gating_eligible: bool
37 regime_alignment: float
38 performance_score: float
39 reason: str
40 magnitude: float | None = None
41 volatility: float | None = None
43 def to_dict(self) -> dict[str, Any]:
44 return asdict(self)
47@dataclass(frozen=True)
48class GatingDecision:
49 """The gated probability of an up move, the baseline and expert inputs, and each expert's weight."""
50 final_probability_up: float
51 baseline_probability_up: float | None
52 expert_probability_up: float | None
53 active_experts: list[str]
54 disabled_experts: list[str]
55 weights: list[ExpertGateWeight]
56 decision_source: str
57 final_magnitude: float | None = None
58 final_volatility: float | None = None
59 sequence_blended: bool = False
61 def to_dict(self) -> dict[str, Any]:
62 payload = asdict(self)
63 payload["weights"] = [weight.to_dict() for weight in self.weights]
64 return payload
67def _clamp(value: float, lower: float = 0.0, upper: float = 1.0) -> float:
68 return max(lower, min(float(value), upper))
71def _expert_metrics(expert_training_metrics: dict[str, Any], expert_name: str) -> dict[str, Any]:
72 return dict(expert_training_metrics.get("experts", {}).get(expert_name, {}))
75def _quality_multiplier(metrics: dict[str, Any]) -> tuple[float, str, bool]:
76 quality_gate = metrics.get("quality_gate", {})
77 quality_status = str(quality_gate.get("quality_status", metrics.get("quality_status", "unknown")))
78 gating_eligible = bool(quality_gate.get("gating_eligible", metrics.get("gating_eligible", False)))
79 if not gating_eligible or quality_status == "disabled_for_gating":
80 return 0.0, quality_status, False
81 if quality_status == "stable":
82 return 1.0, quality_status, True
83 if quality_status == "watchlist":
84 return 0.55, quality_status, True
85 return 0.35, quality_status, True
88def _performance_score(metrics: dict[str, Any]) -> float:
89 validation = metrics.get("validation", {})
90 backtest = metrics.get("backtest", {})
92 def _metric(source: dict[str, Any], key: str, default: float) -> float:
93 # V5.4.7 (#121): `or default` coerced a legitimate stored 0.0
94 # (a real measured value) into the neutral default; only a MISSING
95 # key should take the default.
96 value = source.get(key)
97 return float(default if value is None else value)
99 validation_balanced_accuracy = _metric(validation, "balanced_accuracy", 0.5)
100 backtest_balanced_accuracy = _metric(backtest, "balanced_accuracy", 0.5)
101 backtest_mcc = _metric(backtest, "mcc", 0.0)
103 # Skill floor (development/Problems.md): the old unconditional 0.25
104 # floor meant EVERY expert - even one with backtest balanced-accuracy at
105 # or below a coin flip and non-positive MCC, i.e. no measured skill at
106 # all - still contributed at least 0.25 of weight to the blend. Since
107 # the blend is a weighted AVERAGE of several experts, several
108 # simultaneously near-0.5 predictors mathematically pull the combined
109 # output toward 0.5 regardless of what any single expert says
110 # (confirmed: the live blended probability_up clustered 0.46-0.49,
111 # matching this exactly). An expert with no measured skill on either
112 # metric now scores exactly 0.0 - normalize_weights() (below) then
113 # excludes it from the blend entirely, rather than diluting it, so
114 # only experts that clear a basic skill bar can move the final
115 # prediction away from the baseline.
116 if backtest_balanced_accuracy <= 0.5 and backtest_mcc <= 0.0:
117 return 0.0
119 score = 0.25
120 score += max(0.0, validation_balanced_accuracy - 0.48) * 2.0
121 score += max(0.0, backtest_balanced_accuracy - 0.48) * 3.0
122 score += max(0.0, backtest_mcc) * 1.5
123 return _clamp(score, 0.05, 1.0)
126def _regime_alignment(expert_name: str, regime: dict[str, Any]) -> tuple[float, str]:
127 trend_regime = str(regime.get("trend_regime", "unknown"))
128 volatility_regime = str(regime.get("volatility_regime", "unknown"))
129 risk_regime = str(regime.get("risk_regime", "unknown"))
131 if expert_name == "bullish":
132 if trend_regime == "bullish" and risk_regime != "risk_off":
133 return 1.0, "bullish_trend_match"
134 if trend_regime == "bullish":
135 return 0.65, "bullish_but_risk_off"
136 return 0.15, "trend_mismatch"
138 if expert_name == "bearish":
139 if trend_regime == "bearish":
140 return 1.0, "bearish_trend_match"
141 if risk_regime == "risk_off":
142 return 0.60, "risk_off_support"
143 return 0.15, "trend_mismatch"
145 if expert_name == "sideways":
146 if trend_regime == "sideways":
147 return 1.0, "sideways_trend_match"
148 if volatility_regime == "low_volatility":
149 return 0.55, "low_volatility_support"
150 return 0.20, "trend_mismatch"
152 if expert_name == "volatility":
153 if volatility_regime == "high_volatility":
154 return 1.0, "high_volatility_match"
155 if risk_regime == "risk_off":
156 return 0.70, "risk_off_volatility_support"
157 return 0.25, "volatility_not_elevated"
159 return 0.0, "unknown_expert"
162def build_gating_model_features(
163 regime: dict[str, Any],
164 baseline_probability_up: float | None,
165 weights: list[ExpertGateWeight],
166) -> list[float]:
167 """Pure feature-vector builder for the optional learned gating model -
168 same fixed order as GATING_MODEL_FEATURE_KEYS. `weights` must contain
169 exactly one ExpertGateWeight per EXPERT_NAMES entry, which
170 build_gating_decision() always guarantees."""
171 weight_by_expert = {weight.expert: weight for weight in weights}
172 features: list[float] = []
173 for expert_name in EXPERT_NAMES:
174 expert_weight = weight_by_expert[expert_name]
175 features.append(0.5 if expert_weight.probability_up is None else expert_weight.probability_up)
176 features.append(expert_weight.quality_multiplier)
177 features.append(expert_weight.performance_score)
178 features.append(expert_weight.regime_alignment)
179 features.append(0.5 if baseline_probability_up is None else _clamp(baseline_probability_up))
181 trend_regime = str(regime.get("trend_regime", "unknown"))
182 volatility_regime = str(regime.get("volatility_regime", "unknown"))
183 risk_regime = str(regime.get("risk_regime", "unknown"))
184 for label in ("bullish", "bearish", "sideways"):
185 features.append(1.0 if trend_regime == label else 0.0)
186 for label in ("low_volatility", "normal_volatility", "high_volatility"):
187 features.append(1.0 if volatility_regime == label else 0.0)
188 for label in ("risk_on", "risk_off", "risk_neutral"):
189 features.append(1.0 if risk_regime == label else 0.0)
190 return features
193def _weighted_blend(weights: list[ExpertGateWeight], attribute: str) -> float | None:
194 """Same weighted-average pattern expert_probability already uses
195 (weight.weight * value, summed over experts with a non-None value) -
196 generalized here for magnitude/volatility so per-expert multitask
197 heads (train.py::_train_expert_multitask(), optional/best-effort) can
198 blend the same way per-expert direction probabilities already do.
199 Returns None (not 0.0) when no expert has a value at all - a
200 spurious 0.0 would misrepresent "no data" as "predicted zero
201 magnitude/volatility".
203 V5.4.7 (development/Problems.md #121): the sum was previously taken
204 over contributors only, while `weight.weight` values are normalized
205 across ALL experts (sum = 1). Any expert whose multitask head was
206 missing silently contributed w*0, deflating the blended
207 magnitude/volatility toward zero by exactly the missing weight mass -
208 and an underestimated volatility feeds risk/position_sizing.py's vol
209 targeting, OVERSIZING positions. The blend is now renormalized over
210 the contributing experts' weights."""
211 contributions = [
212 (weight.weight, getattr(weight, attribute))
213 for weight in weights
214 if getattr(weight, attribute) is not None
215 ]
216 if not contributions:
217 return None
218 total_weight = sum(w for w, _ in contributions)
219 if total_weight <= 0.0:
220 return None
221 return sum(w * v for w, v in contributions) / total_weight
224def build_gating_decision(
225 regime: dict[str, Any],
226 expert_training_metrics: dict[str, Any],
227 expert_probabilities: dict[str, float | None],
228 baseline_probability_up: float | None = None,
229 baseline_weight: float = 0.25,
230 gating_model: dict[str, Any] | None = None,
231 gating_feature_schema: dict[str, Any] | None = None,
232 expert_magnitudes: dict[str, float | None] | None = None,
233 expert_volatilities: dict[str, float | None] | None = None,
234 baseline_magnitude: float | None = None,
235 baseline_volatility: float | None = None,
236 sequence_prediction: dict[str, Any] | None = None,
237 sequence_weight: float = 0.0,
238 excluded_experts: tuple[str, ...] | frozenset[str] = (),
239) -> GatingDecision:
240 """`excluded_experts` (V6.4.0, `phase_v2.gating_network.disabled_experts`, default none): experts treated as having no
241 probability, so the others renormalise - the expert-ablation switch (lead L8)."""
242 expert_magnitudes = expert_magnitudes or {}
243 expert_volatilities = expert_volatilities or {}
244 weights: list[ExpertGateWeight] = []
245 disabled_experts = []
247 for expert_name in EXPERT_NAMES:
248 probability = None if expert_name in excluded_experts else expert_probabilities.get(expert_name)
249 metrics = _expert_metrics(expert_training_metrics, expert_name)
250 quality_multiplier, quality_status, gating_eligible = _quality_multiplier(metrics)
251 performance_score = _performance_score(metrics)
252 alignment, alignment_reason = _regime_alignment(expert_name, regime)
254 if probability is None:
255 raw_score = 0.0
256 reason = "missing_probability"
257 elif not gating_eligible:
258 raw_score = 0.0
259 reason = "quality_gate_disabled"
260 else:
261 raw_score = quality_multiplier * performance_score * alignment
262 reason = alignment_reason
264 if raw_score <= 0.0:
265 disabled_experts.append(expert_name)
267 weights.append(
268 ExpertGateWeight(
269 expert=expert_name,
270 weight=0.0,
271 raw_score=raw_score,
272 probability_up=None if probability is None else _clamp(probability),
273 quality_status=quality_status,
274 quality_multiplier=quality_multiplier,
275 gating_eligible=gating_eligible,
276 regime_alignment=alignment,
277 performance_score=performance_score,
278 reason=reason,
279 magnitude=expert_magnitudes.get(expert_name),
280 volatility=expert_volatilities.get(expert_name),
281 )
282 )
284 total_score = sum(weight.raw_score for weight in weights)
285 if total_score <= 0.0:
286 normalized_weights = weights
287 expert_probability = None
288 final_probability = baseline_probability_up if baseline_probability_up is not None else 0.5
289 final_magnitude = baseline_magnitude
290 final_volatility = baseline_volatility
291 decision_source = "baseline_fallback"
292 else:
293 normalized_weights = [
294 ExpertGateWeight(
295 expert=weight.expert,
296 weight=weight.raw_score / total_score,
297 raw_score=weight.raw_score,
298 probability_up=weight.probability_up,
299 quality_status=weight.quality_status,
300 quality_multiplier=weight.quality_multiplier,
301 gating_eligible=weight.gating_eligible,
302 regime_alignment=weight.regime_alignment,
303 performance_score=weight.performance_score,
304 reason=weight.reason,
305 magnitude=weight.magnitude,
306 volatility=weight.volatility,
307 )
308 for weight in weights
309 ]
310 expert_probability = sum(
311 weight.weight * float(weight.probability_up)
312 for weight in normalized_weights
313 if weight.probability_up is not None
314 )
315 expert_magnitude = _weighted_blend(normalized_weights, "magnitude")
316 expert_volatility = _weighted_blend(normalized_weights, "volatility")
318 clamped_baseline_weight = _clamp(baseline_weight, 0.0, 0.90)
319 if baseline_probability_up is None:
320 final_probability = expert_probability
321 decision_source = "experts_only"
322 else:
323 final_probability = (
324 clamped_baseline_weight * _clamp(baseline_probability_up)
325 + (1.0 - clamped_baseline_weight) * expert_probability
326 )
327 decision_source = "baseline_and_experts"
329 # Magnitude/volatility blend mirrors the probability blend above -
330 # same baseline_weight, same "baseline anchor + expert average"
331 # shape - but falls back to whichever single side actually has a
332 # value instead of a hardcoded default (0.5 makes sense as a
333 # "no-signal" probability; it does not for a return magnitude or a
334 # volatility estimate).
335 if baseline_magnitude is None:
336 final_magnitude = expert_magnitude
337 elif expert_magnitude is None:
338 final_magnitude = baseline_magnitude
339 else:
340 final_magnitude = clamped_baseline_weight * baseline_magnitude + (1.0 - clamped_baseline_weight) * expert_magnitude
342 if baseline_volatility is None:
343 final_volatility = expert_volatility
344 elif expert_volatility is None:
345 final_volatility = baseline_volatility
346 else:
347 final_volatility = clamped_baseline_weight * baseline_volatility + (1.0 - clamped_baseline_weight) * expert_volatility
349 # Optional, additive, always-falls-back learned override - see
350 # development/Problems.md and moe/README.md. The hardcoded blend above
351 # is always computed first and is what ships whenever no learned model
352 # is present/enabled, or if scoring it fails for any reason (mirrors
353 # topology/learned_topology.py's per-node fallback isolation: a
354 # degraded/missing learned model must never crash a bar or block a
355 # decision, only silently forfeit the improvement it would have added).
356 # Deliberately direction-only: the learned gating model
357 # (train_gating.py) predicts a single probability, not
358 # magnitude/volatility, so final_magnitude/final_volatility are
359 # unaffected by this override regardless of decision_source.
360 if gating_model and gating_feature_schema:
361 try:
362 feature_vector = build_gating_model_features(regime, baseline_probability_up, normalized_weights)
363 final_probability = run_exported_model(gating_model, feature_vector)
364 decision_source = "learned_gating"
365 except Exception:
366 pass
368 # Optional Phase 2 sequence-encoder blend (causal TCN, see
369 # inference/README.md) - applied last, on top of whichever
370 # final_probability/final_magnitude/final_volatility the blend above
371 # (hardcoded or learned_gating) already produced, so it works
372 # regardless of decision_source. Same "anchor blend" shape
373 # baseline_weight already uses (weight * new_value + (1 - weight) *
374 # existing_value), clamped to [0, 1] so it can only interpolate toward
375 # the sequence model's prediction, never overshoot past it. Off by
376 # default (sequence_weight=0.0) - byte-identical to pre-existing
377 # behavior until phase_v2.gating_network.sequence_weight is set above
378 # zero, matching risk/position_sizing.py's use_predicted_volatility
379 # convention for a new signal that changes a real trading decision
380 # (final_probability_up), not just a shrink-only sizing multiplier.
381 sequence_blended = False
382 if sequence_prediction and sequence_weight > 0.0:
383 clamped_sequence_weight = _clamp(sequence_weight, 0.0, 1.0)
384 sequence_direction = sequence_prediction.get("direction")
385 if sequence_direction is not None:
386 final_probability = (
387 clamped_sequence_weight * _clamp(sequence_direction)
388 + (1.0 - clamped_sequence_weight) * final_probability
389 )
390 sequence_blended = True
391 sequence_magnitude = sequence_prediction.get("magnitude")
392 if sequence_magnitude is not None:
393 final_magnitude = (
394 sequence_magnitude
395 if final_magnitude is None
396 else clamped_sequence_weight * sequence_magnitude + (1.0 - clamped_sequence_weight) * final_magnitude
397 )
398 sequence_blended = True
399 sequence_volatility = sequence_prediction.get("volatility")
400 if sequence_volatility is not None:
401 final_volatility = (
402 sequence_volatility
403 if final_volatility is None
404 else clamped_sequence_weight * sequence_volatility + (1.0 - clamped_sequence_weight) * final_volatility
405 )
406 sequence_blended = True
408 return GatingDecision(
409 final_probability_up=_clamp(final_probability),
410 baseline_probability_up=None if baseline_probability_up is None else _clamp(baseline_probability_up),
411 expert_probability_up=None if expert_probability is None else _clamp(expert_probability),
412 active_experts=[weight.expert for weight in normalized_weights if weight.weight > 0.0],
413 disabled_experts=disabled_experts,
414 weights=normalized_weights,
415 decision_source=decision_source,
416 final_magnitude=final_magnitude,
417 final_volatility=final_volatility,
418 sequence_blended=sequence_blended,
419 )