Delete ai_risk_engine.py
Browse files- ai_risk_engine.py +0 -97
ai_risk_engine.py
DELETED
|
@@ -1,97 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Bayesian risk engine with hyperpriors (hierarchical Beta‑binomial).
|
| 3 |
-
Uses Pyro for variational inference.
|
| 4 |
-
"""
|
| 5 |
-
import logging
|
| 6 |
-
import pyro
|
| 7 |
-
import pyro.distributions as dist
|
| 8 |
-
from pyro.infer import SVI, Trace_ELBO, Predictive
|
| 9 |
-
import torch
|
| 10 |
-
import numpy as np
|
| 11 |
-
from typing import Dict, Optional, List, Tuple
|
| 12 |
-
|
| 13 |
-
logger = logging.getLogger(__name__)
|
| 14 |
-
|
| 15 |
-
class AIRiskEngine:
|
| 16 |
-
"""
|
| 17 |
-
Hierarchical Bayesian model for task‑specific risk.
|
| 18 |
-
Each task category has its own Beta parameters, but they share a common hyperprior.
|
| 19 |
-
"""
|
| 20 |
-
|
| 21 |
-
def __init__(self, num_categories: int = 10):
|
| 22 |
-
self.num_categories = num_categories
|
| 23 |
-
self.category_names = ["chat", "code", "summary", "image", "audio", "iot", "switch", "server", "service", "unknown"]
|
| 24 |
-
self._history: List[Tuple[int, float]] = [] # (category_idx, success)
|
| 25 |
-
self._init_model()
|
| 26 |
-
|
| 27 |
-
def _init_model(self):
|
| 28 |
-
# Hyperpriors (Gamma for alpha, beta)
|
| 29 |
-
self.alpha0 = pyro.param("alpha0", torch.tensor(2.0), constraint=dist.constraints.positive)
|
| 30 |
-
self.beta0 = pyro.param("beta0", torch.tensor(2.0), constraint=dist.constraints.positive)
|
| 31 |
-
# Category‑specific parameters
|
| 32 |
-
self.p_alpha = pyro.param("p_alpha", torch.ones(self.num_categories) * 2.0, constraint=dist.constraints.positive)
|
| 33 |
-
self.p_beta = pyro.param("p_beta", torch.ones(self.num_categories) * 2.0, constraint=dist.constraints.positive)
|
| 34 |
-
|
| 35 |
-
def model(self, observations=None):
|
| 36 |
-
# Global hyperprior (concentration parameters)
|
| 37 |
-
alpha0 = pyro.sample("alpha0", dist.Gamma(2.0, 1.0))
|
| 38 |
-
beta0 = pyro.sample("beta0", dist.Gamma(2.0, 1.0))
|
| 39 |
-
|
| 40 |
-
with pyro.plate("categories", self.num_categories):
|
| 41 |
-
# Category‑specific success probabilities drawn from Beta(alpha0, beta0)
|
| 42 |
-
p = pyro.sample("p", dist.Beta(alpha0, beta0))
|
| 43 |
-
|
| 44 |
-
if observations is not None:
|
| 45 |
-
cat_idx = torch.tensor([obs[0] for obs in observations])
|
| 46 |
-
successes = torch.tensor([obs[1] for obs in observations])
|
| 47 |
-
with pyro.plate("data", len(observations)):
|
| 48 |
-
pyro.sample("obs", dist.Bernoulli(p[cat_idx]), obs=successes)
|
| 49 |
-
|
| 50 |
-
def guide(self, observations=None):
|
| 51 |
-
# Variational parameters for hyperpriors
|
| 52 |
-
alpha0_q = pyro.param("alpha0_q", torch.tensor(2.0), constraint=dist.constraints.positive)
|
| 53 |
-
beta0_q = pyro.param("beta0_q", torch.tensor(2.0), constraint=dist.constraints.positive)
|
| 54 |
-
pyro.sample("alpha0", dist.Gamma(alpha0_q, 1.0))
|
| 55 |
-
pyro.sample("beta0", dist.Gamma(beta0_q, 1.0))
|
| 56 |
-
|
| 57 |
-
with pyro.plate("categories", self.num_categories):
|
| 58 |
-
p_alpha = pyro.param("p_alpha", torch.ones(self.num_categories) * 2.0, constraint=dist.constraints.positive)
|
| 59 |
-
p_beta = pyro.param("p_beta", torch.ones(self.num_categories) * 2.0, constraint=dist.constraints.positive)
|
| 60 |
-
pyro.sample("p", dist.Beta(p_alpha, p_beta))
|
| 61 |
-
|
| 62 |
-
def update_outcome(self, category: str, success: bool):
|
| 63 |
-
"""Store observation and optionally trigger a learning step."""
|
| 64 |
-
cat_idx = self.category_names.index(category) if category in self.category_names else -1
|
| 65 |
-
if cat_idx == -1:
|
| 66 |
-
logger.warning(f"Unknown category: {category}")
|
| 67 |
-
return
|
| 68 |
-
self._history.append((cat_idx, 1.0 if success else 0.0))
|
| 69 |
-
# Run a few steps of SVI
|
| 70 |
-
if len(self._history) > 5:
|
| 71 |
-
self._run_svi(steps=10)
|
| 72 |
-
|
| 73 |
-
def _run_svi(self, steps=50):
|
| 74 |
-
if len(self._history) == 0:
|
| 75 |
-
return
|
| 76 |
-
optimizer = pyro.optim.Adam({"lr": 0.01})
|
| 77 |
-
svi = SVI(self.model, self.guide, optimizer, loss=Trace_ELBO())
|
| 78 |
-
for step in range(steps):
|
| 79 |
-
loss = svi.step(self._history)
|
| 80 |
-
if step % 10 == 0:
|
| 81 |
-
logger.debug(f"SVI step {step}, loss: {loss}")
|
| 82 |
-
|
| 83 |
-
def risk_score(self, category: str) -> Dict[str, float]:
|
| 84 |
-
"""Return posterior predictive risk metrics for a category."""
|
| 85 |
-
cat_idx = self.category_names.index(category) if category in self.category_names else -1
|
| 86 |
-
if cat_idx == -1 or len(self._history) == 0:
|
| 87 |
-
return {"mean": 0.5, "p5": 0.1, "p50": 0.5, "p95": 0.9}
|
| 88 |
-
# Generate posterior samples for p[cat_idx]
|
| 89 |
-
predictive = Predictive(self.model, guide=self.guide, num_samples=500)
|
| 90 |
-
samples = predictive(self._history)
|
| 91 |
-
p_samples = samples["p"][:, cat_idx].detach().numpy()
|
| 92 |
-
return {
|
| 93 |
-
"mean": float(p_samples.mean()),
|
| 94 |
-
"p5": float(np.percentile(p_samples, 5)),
|
| 95 |
-
"p50": float(np.percentile(p_samples, 50)),
|
| 96 |
-
"p95": float(np.percentile(p_samples, 95))
|
| 97 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|