Spaces:
Runtime error

kaksha / model_runtime.py
camphor5's picture
initial upload
a3b68cd verified
Raw History Blame Contribute Delete
7.95 kB
# ============================================================
# model_runtime.py
# ============================================================
import json
import os
import pickle
import sys
import threading
from pathlib import Path
import numpy as np
from scipy.special import expit
from config import TF_DEVICE
from data_store import STORE
def multiplicity_boost(probability, n_other_signals):
p = float(np.clip(probability, 0.0, 1.0))
if n_other_signals <= 0:
return p
boost = 25.0 if n_other_signals == 1 else 50.0
return float(p * boost / (p * boost + 1.0 - p))
class ModelRuntime:
def __init__(self):
self._lock = threading.Lock()
self.loaded = False
self.root = None
self.members = []
self.xgb_models = []
self.norm = None
self.fusion_json = None
self.fusion_pickle = None
self.tf = None
self.keras = None
self.xgb = None
def load(self):
if self.loaded:
return self
with self._lock:
if self.loaded:
return self
root = STORE.ensure_models()
self.root = Path(root)
code_dir = self.root / "code"
if code_dir.exists() and str(code_dir) not in sys.path:
sys.path.insert(0, str(code_dir))
# ZeroGPU currently has its strongest compatibility guarantees for
# PyTorch. The Kaksha Keras ensemble is therefore CPU-first.
if TF_DEVICE == "cpu":
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
os.environ.setdefault("TF_CPP_MIN_LOG_LEVEL", "2")
import tensorflow as tf
import keras
import xgboost as xgb
self.tf = tf
self.keras = keras
self.xgb = xgb
if TF_DEVICE == "cpu":
try:
tf.config.set_visible_devices([], "GPU")
except Exception:
pass
else:
for gpu in tf.config.list_physical_devices("GPU"):
try:
tf.config.experimental.set_memory_growth(gpu, True)
except Exception:
pass
dnn_paths = sorted(
(self.root / "models" / "dnn_ensemble").glob("member_fold*.keras")
)
if not dnn_paths:
raise RuntimeError("No DNN ensemble members were found.")
self.members = [
keras.models.load_model(path, compile=False, safe_mode=True)
for path in dnn_paths
]
xgb_paths = sorted(
(self.root / "models" / "xgb").glob("xgb_fold*.json")
)
if not xgb_paths:
raise RuntimeError("No XGBoost fold models were found.")
for path in xgb_paths:
model = xgb.XGBClassifier()
model.load_model(path)
try:
model.set_params(device="cpu")
except Exception:
pass
self.xgb_models.append(model)
with (self.root / "models" / "scalar_norm.json").open() as f:
self.norm = json.load(f)
portable = self.root / "models" / "fusion_runtime.json"
if portable.exists():
with portable.open() as f:
self.fusion_json = json.load(f)
else:
fallback = self.root / "models" / "fusion.pkl"
if not fallback.exists():
raise RuntimeError(
"Neither fusion_runtime.json nor fusion.pkl was found."
)
with fallback.open("rb") as f:
self.fusion_pickle = pickle.load(f)
self.loaded = True
return self
@property
def feature_columns(self):
self.load()
return list(self.norm["cols"])
def _prepare_scalars(self, scalar_dict):
cols = self.feature_columns
raw = np.array(
[[scalar_dict.get(col, np.nan) for col in cols]],
dtype=np.float32,
)
raw[~np.isfinite(raw)] = np.nan
med = np.asarray(self.norm["median"], dtype=np.float32)
raw = np.where(np.isnan(raw), med[None, :], raw)
mu = np.asarray(self.norm["mu"], dtype=np.float32)
sd = np.asarray(self.norm["sd"], dtype=np.float32)
standardized = (raw - mu[None, :]) / sd[None, :]
return raw.astype(np.float32), standardized.astype(np.float32)
def _fuse(self, dnn_score, xgb_score):
if self.fusion_json is not None:
coef = np.asarray(self.fusion_json["coef"], dtype=float)
intercept = float(self.fusion_json["intercept"])
raw = float(expit(intercept + np.dot(coef, [dnn_score, xgb_score])))
calibration = self.fusion_json.get("calibration", {})
if calibration.get("method") == "isotonic":
x = np.asarray(calibration["x_thresholds"], dtype=float)
y = np.asarray(calibration["y_thresholds"], dtype=float)
calibrated = float(np.interp(raw, x, y))
else:
calibrated = raw
return raw, calibrated
stacker = self.fusion_pickle["stacker"]
isotonic = self.fusion_pickle["isotonic"]
raw = float(
stacker.predict_proba([[dnn_score, xgb_score]])[0, 1]
)
calibrated = float(isotonic.predict([raw])[0])
return raw, calibrated
def score(self, signal, n_other_signals=0):
self.load()
raw_scalars, standardized = self._prepare_scalars(signal["scalars"])
model_inputs = {
name: np.asarray(signal[name], dtype=np.float32)[None, :, None]
for name in [
"global_view",
"local_view",
"secondary_view",
"odd_view",
"even_view",
]
}
model_inputs["scalars"] = standardized
dnn_scores = np.array(
[
float(model.predict(model_inputs, verbose=0).reshape(-1)[0])
for model in self.members
],
dtype=float,
)
xgb_scores = np.array(
[
float(model.predict_proba(raw_scalars)[0, 1])
for model in self.xgb_models
],
dtype=float,
)
dnn_mean = float(dnn_scores.mean())
dnn_spread = float(dnn_scores.std())
xgb_mean = float(xgb_scores.mean())
fused_raw, calibrated = self._fuse(dnn_mean, xgb_mean)
booster = self.xgb_models[0].get_booster()
contributions = booster.predict(
self.xgb.DMatrix(raw_scalars),
pred_contribs=True,
)[0, :-1]
order = np.argsort(-np.abs(contributions))[:3]
shap_top3 = [
{
"feature": self.feature_columns[i],
"value": float(raw_scalars[0, i]),
"shap": float(contributions[i]),
}
for i in order
]
return {
"dnn_score": dnn_mean,
"dnn_spread": dnn_spread,
"dnn_members": dnn_scores.tolist(),
"xgb_score": xgb_mean,
"fused_raw": fused_raw,
"confidence": calibrated,
"confidence_boosted": multiplicity_boost(
calibrated, n_other_signals
),
"n_other_signals": int(n_other_signals),
"shap_top3": shap_top3,
}
RUNTIME = ModelRuntime()