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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
"""
|
| 3 |
+
model_loader.py — PeVe v1.4
|
| 4 |
+
============================
|
| 5 |
+
|
| 6 |
+
What app.py needs (read from app.py source):
|
| 7 |
+
|
| 8 |
+
from model_loader import get_splice_model, get_context_model, get_protein_model
|
| 9 |
+
|
| 10 |
+
model, tokenizer = get_splice_model()
|
| 11 |
+
→ model accepts: torch.Tensor of shape (1, 401, 8) or (1, 401, 8) + flags
|
| 12 |
+
→ used inside torch.no_grad()
|
| 13 |
+
→ returns tensor or tuple[tensor, ...]
|
| 14 |
+
|
| 15 |
+
model, tokenizer = get_context_model()
|
| 16 |
+
→ same calling convention as splice
|
| 17 |
+
|
| 18 |
+
model = get_protein_model()
|
| 19 |
+
→ used with: xgb.DMatrix(X, feature_names=[...])
|
| 20 |
+
→ model.predict(dmat) → float array
|
| 21 |
+
→ also passed to shap.TreeExplainer(model)
|
| 22 |
+
|
| 23 |
+
Model sources (from the Space app.py files):
|
| 24 |
+
splice → nileshhanotia/mutation-predictor-splice
|
| 25 |
+
file: mutation_predictor_splice.pt
|
| 26 |
+
arch: MutationPredictorCNN_v2 (input flat 1106)
|
| 27 |
+
NOTE: app.py passes (1, 401, 8) tensor — loader must reshape
|
| 28 |
+
|
| 29 |
+
context → nileshhanotia/mutation-predictor-v4
|
| 30 |
+
file: mutation_predictor_splice_v4.pt
|
| 31 |
+
arch: MutationPredictorCNN_v4 (4-tensor forward: seq,mut,region,splice)
|
| 32 |
+
NOTE: app.py passes (1, 401, 8) tensor — loader wraps forward
|
| 33 |
+
|
| 34 |
+
protein → nileshhanotia/mutation-pathogenicity-predictor
|
| 35 |
+
file: *.json / *.ubj / *.model / *.pkl
|
| 36 |
+
NOTE: app.py uses xgb.DMatrix + shap — MUST be XGBoost
|
| 37 |
+
If file is actually a CNN checkpoint, we wrap it as an
|
| 38 |
+
XGBoost-compatible object so app.py code paths still work.
|
| 39 |
+
"""
|
| 40 |
+
from __future__ import annotations
|
| 41 |
+
|
| 42 |
+
import os
|
| 43 |
+
import pickle
|
| 44 |
+
import traceback
|
| 45 |
+
import warnings
|
| 46 |
+
from pathlib import Path
|
| 47 |
+
from typing import Any
|
| 48 |
+
|
| 49 |
+
import numpy as np
|
| 50 |
+
|
| 51 |
+
# ── HF token ──────────────────────────────────────────────────────────────────
|
| 52 |
+
_HF_TOKEN: str | None = (
|
| 53 |
+
os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
# ── Model repo IDs ─────────────────────────────────────────────────────────────
|
| 57 |
+
_REPO_SPLICE = "nileshhanotia/mutation-predictor-splice"
|
| 58 |
+
_REPO_CONTEXT = "nileshhanotia/mutation-predictor-v4"
|
| 59 |
+
_REPO_PROTEIN = "nileshhanotia/mutation-pathogenicity-predictor"
|
| 60 |
+
|
| 61 |
+
# ── Global cache ───────────────────────────────────────────────────────────────
|
| 62 |
+
_splice_model = None
|
| 63 |
+
_splice_tok = None
|
| 64 |
+
_context_model = None
|
| 65 |
+
_context_tok = None
|
| 66 |
+
_protein_model = None
|
| 67 |
+
|
| 68 |
+
# ── Structured status dicts ────────────────────────────────────────────────────
|
| 69 |
+
splice_model_status: dict = {"loaded": False, "error_message": None}
|
| 70 |
+
context_model_status: dict = {"loaded": False, "error_message": None}
|
| 71 |
+
protein_model_status: dict = {"loaded": False, "error_message": None}
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 75 |
+
# Model Architecture definitions
|
| 76 |
+
# (must match checkpoint shapes exactly)
|
| 77 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 78 |
+
|
| 79 |
+
def _build_splice_arch(sd: dict):
|
| 80 |
+
"""
|
| 81 |
+
MutationPredictorCNN_v2 — infer fc_region_out and splice_fc_out from
|
| 82 |
+
the checkpoint's weight shapes, exactly as the Space app does.
|
| 83 |
+
|
| 84 |
+
Forward signature in the Space:
|
| 85 |
+
logit, imp_score, r_imp, s_imp = model(flat_tensor, mutation_positions)
|
| 86 |
+
|
| 87 |
+
app.py passes tensors of shape (1, 401, 8). We need an adapter.
|
| 88 |
+
"""
|
| 89 |
+
import torch
|
| 90 |
+
import torch.nn as nn
|
| 91 |
+
import torch.nn.functional as F
|
| 92 |
+
|
| 93 |
+
fc_region_out = sd["fc_region.weight"].shape[0]
|
| 94 |
+
splice_fc_out = sd["splice_fc.weight"].shape[0]
|
| 95 |
+
|
| 96 |
+
class MutationPredictorCNN_v2(nn.Module):
|
| 97 |
+
def __init__(self):
|
| 98 |
+
super().__init__()
|
| 99 |
+
fc1_in = 256 + 32 + fc_region_out + splice_fc_out
|
| 100 |
+
self.conv1 = nn.Conv1d(11, 64, kernel_size=7, padding=3)
|
| 101 |
+
self.bn1 = nn.BatchNorm1d(64)
|
| 102 |
+
self.conv2 = nn.Conv1d(64, 128, kernel_size=5, padding=2)
|
| 103 |
+
self.bn2 = nn.BatchNorm1d(128)
|
| 104 |
+
self.conv3 = nn.Conv1d(128, 256, kernel_size=3, padding=1)
|
| 105 |
+
self.bn3 = nn.BatchNorm1d(256)
|
| 106 |
+
self.global_pool = nn.AdaptiveAvgPool1d(1)
|
| 107 |
+
self.mut_fc = nn.Linear(12, 32)
|
| 108 |
+
self.importance_head = nn.Linear(256, 1)
|
| 109 |
+
self.region_importance_head = nn.Linear(256, 2)
|
| 110 |
+
self.fc_region = nn.Linear(2, fc_region_out)
|
| 111 |
+
self.splice_fc = nn.Linear(3, splice_fc_out)
|
| 112 |
+
self.splice_importance_head = nn.Linear(256, 3)
|
| 113 |
+
self.fc1 = nn.Linear(fc1_in, 128)
|
| 114 |
+
self.fc2 = nn.Linear(128, 64)
|
| 115 |
+
self.fc3 = nn.Linear(64, 1)
|
| 116 |
+
self.relu = nn.ReLU()
|
| 117 |
+
self.dropout = nn.Dropout(0.4)
|
| 118 |
+
|
| 119 |
+
def _forward_flat(self, x_flat, mutation_positions=None):
|
| 120 |
+
"""Original forward for flat 1106-dim input."""
|
| 121 |
+
bs = x_flat.size(0)
|
| 122 |
+
seq_flat = x_flat[:, :1089]
|
| 123 |
+
mut_onehot = x_flat[:, 1089:1101]
|
| 124 |
+
region_feat= x_flat[:, 1101:1103]
|
| 125 |
+
splice_feat= x_flat[:, 1103:1106]
|
| 126 |
+
h = self.relu(self.bn1(self.conv1(seq_flat.view(bs, 11, 99))))
|
| 127 |
+
h = self.relu(self.bn2(self.conv2(h)))
|
| 128 |
+
conv_out = self.relu(self.bn3(self.conv3(h)))
|
| 129 |
+
if mutation_positions is None:
|
| 130 |
+
mutation_positions = x_flat[:, 990:1089].argmax(dim=1)
|
| 131 |
+
pos_idx = mutation_positions.clamp(0, 98).long()
|
| 132 |
+
pe = pos_idx.view(bs, 1, 1).expand(bs, 256, 1)
|
| 133 |
+
mut_feat = conv_out.gather(2, pe).squeeze(2)
|
| 134 |
+
imp_score = torch.sigmoid(self.importance_head(mut_feat))
|
| 135 |
+
pooled = self.global_pool(conv_out).squeeze(-1)
|
| 136 |
+
r_imp = torch.sigmoid(self.region_importance_head(pooled))
|
| 137 |
+
s_imp = torch.sigmoid(self.splice_importance_head(pooled))
|
| 138 |
+
m = self.relu(self.mut_fc(mut_onehot))
|
| 139 |
+
r = self.relu(self.fc_region(region_feat))
|
| 140 |
+
s = self.relu(self.splice_fc(splice_feat))
|
| 141 |
+
fused = torch.cat([pooled, m, r, s], dim=1)
|
| 142 |
+
out = self.dropout(self.relu(self.fc1(fused)))
|
| 143 |
+
out = self.dropout(self.relu(self.fc2(out)))
|
| 144 |
+
logit = self.fc3(out)
|
| 145 |
+
return logit, imp_score, r_imp, s_imp
|
| 146 |
+
|
| 147 |
+
def forward(self, x, mutation_positions=None):
|
| 148 |
+
"""
|
| 149 |
+
Accept whatever shape app.py sends:
|
| 150 |
+
(B, 401, 8) — raw encoded window from app.py
|
| 151 |
+
(B, 1106) — flat input (native format)
|
| 152 |
+
"""
|
| 153 |
+
if x.dim() == 3:
|
| 154 |
+
# app.py sends (B, 401, 8) — flatten and zero-pad to 1106
|
| 155 |
+
bs = x.size(0)
|
| 156 |
+
flat = x.reshape(bs, -1) # → (B, 3208)
|
| 157 |
+
# Take first 1089 dims (99*11), pad mut/region/splice to zeros
|
| 158 |
+
seq_part = flat[:, :1089]
|
| 159 |
+
pad = torch.zeros(bs, 1106 - 1089, device=x.device)
|
| 160 |
+
flat_padded = torch.cat([seq_part, pad], dim=1) # → (B, 1106)
|
| 161 |
+
return self._forward_flat(flat_padded, mutation_positions)
|
| 162 |
+
return self._forward_flat(x, mutation_positions)
|
| 163 |
+
|
| 164 |
+
model = MutationPredictorCNN_v2()
|
| 165 |
+
model.load_state_dict(sd)
|
| 166 |
+
return model
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def _build_context_arch(sd: dict):
|
| 170 |
+
"""
|
| 171 |
+
MutationPredictorCNN_v4 — 4-input forward (seq, mut, region, splice).
|
| 172 |
+
app.py passes a single (B, 401, 8) tensor, so forward() adapts.
|
| 173 |
+
"""
|
| 174 |
+
import torch
|
| 175 |
+
import torch.nn as nn
|
| 176 |
+
|
| 177 |
+
class MutationPredictorCNN_v4(nn.Module):
|
| 178 |
+
def __init__(self):
|
| 179 |
+
super().__init__()
|
| 180 |
+
self.conv1 = nn.Conv1d(11, 64, 7, padding=3)
|
| 181 |
+
self.conv2 = nn.Conv1d(64, 128, 5, padding=2)
|
| 182 |
+
self.conv3 = nn.Conv1d(128,256, 3, padding=1)
|
| 183 |
+
self.pool = nn.AdaptiveAvgPool1d(1)
|
| 184 |
+
self.mut_fc = nn.Linear(12, 32)
|
| 185 |
+
self.region_fc = nn.Linear(2, 8)
|
| 186 |
+
self.splice_fc = nn.Linear(3, 16)
|
| 187 |
+
self.fc1 = nn.Linear(312, 128)
|
| 188 |
+
self.fc2 = nn.Linear(128, 64)
|
| 189 |
+
self.fc3 = nn.Linear(64, 1)
|
| 190 |
+
self.relu = nn.ReLU()
|
| 191 |
+
self.dropout = nn.Dropout(0.3)
|
| 192 |
+
|
| 193 |
+
def _forward_native(self, seq, mut, region, splice):
|
| 194 |
+
x = self.relu(self.conv1(seq))
|
| 195 |
+
x = self.relu(self.conv2(x))
|
| 196 |
+
x = self.relu(self.conv3(x))
|
| 197 |
+
x = self.pool(x).squeeze(-1)
|
| 198 |
+
m = self.relu(self.mut_fc(mut))
|
| 199 |
+
r = self.relu(self.region_fc(region))
|
| 200 |
+
s = self.relu(self.splice_fc(splice))
|
| 201 |
+
x = torch.cat([x, m, r, s], dim=1)
|
| 202 |
+
x = self.dropout(self.relu(self.fc1(x)))
|
| 203 |
+
x = self.relu(self.fc2(x))
|
| 204 |
+
return self.fc3(x)
|
| 205 |
+
|
| 206 |
+
def forward(self, x, *args):
|
| 207 |
+
"""
|
| 208 |
+
Accept:
|
| 209 |
+
(B, 401, 8) → reshape to 99*11 window, zero-pad aux inputs
|
| 210 |
+
(seq, mut, region, splice) tensors — native
|
| 211 |
+
"""
|
| 212 |
+
import torch
|
| 213 |
+
if isinstance(x, torch.Tensor) and x.dim() == 3:
|
| 214 |
+
bs = x.size(0)
|
| 215 |
+
flat = x.reshape(bs, -1)
|
| 216 |
+
seq_flat = flat[:, :1089].view(bs, 11, 99)
|
| 217 |
+
mut = torch.zeros(bs, 12, device=x.device)
|
| 218 |
+
region = torch.zeros(bs, 2, device=x.device)
|
| 219 |
+
splice = torch.zeros(bs, 3, device=x.device)
|
| 220 |
+
return self._forward_native(seq_flat, mut, region, splice)
|
| 221 |
+
# flat 1089+12+2+3 = 1106 case
|
| 222 |
+
if isinstance(x, torch.Tensor) and x.dim() == 2:
|
| 223 |
+
bs = x.size(0)
|
| 224 |
+
seq_flat = x[:, :1089].view(bs, 11, 99)
|
| 225 |
+
mut = x[:, 1089:1101]
|
| 226 |
+
region = x[:, 1101:1103]
|
| 227 |
+
splice = x[:, 1103:1106]
|
| 228 |
+
return self._forward_native(seq_flat, mut, region, splice)
|
| 229 |
+
# called with 4 separate tensors
|
| 230 |
+
return self._forward_native(x, *args)
|
| 231 |
+
|
| 232 |
+
model = MutationPredictorCNN_v4()
|
| 233 |
+
model.load_state_dict(sd)
|
| 234 |
+
return model
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
class _CNNasXGB:
|
| 238 |
+
"""
|
| 239 |
+
Wrapper that makes a PyTorch CNN look like an XGBoost Booster
|
| 240 |
+
to satisfy the app.py code paths:
|
| 241 |
+
dmat = xgb.DMatrix(X, feature_names=[...])
|
| 242 |
+
pred = model.predict(dmat) ← needs .predict()
|
| 243 |
+
shap.TreeExplainer(model) ← will fail gracefully; app has try/except
|
| 244 |
+
"""
|
| 245 |
+
def __init__(self, torch_model, feature_names: list[str]):
|
| 246 |
+
import torch
|
| 247 |
+
self._model = torch_model
|
| 248 |
+
self._model.eval()
|
| 249 |
+
self._features = feature_names
|
| 250 |
+
self._device = torch.device("cpu")
|
| 251 |
+
|
| 252 |
+
def predict(self, dmat_or_array) -> np.ndarray:
|
| 253 |
+
import torch
|
| 254 |
+
try:
|
| 255 |
+
# xgb.DMatrix → get_data() returns scipy sparse or np array
|
| 256 |
+
try:
|
| 257 |
+
X = dmat_or_array.get_data().toarray()
|
| 258 |
+
except Exception:
|
| 259 |
+
X = np.array(dmat_or_array)
|
| 260 |
+
except Exception:
|
| 261 |
+
X = np.zeros((1, len(self._features)), dtype=np.float32)
|
| 262 |
+
|
| 263 |
+
t = torch.tensor(X, dtype=torch.float32)
|
| 264 |
+
with torch.no_grad():
|
| 265 |
+
out = self._model(t)
|
| 266 |
+
if isinstance(out, (tuple, list)):
|
| 267 |
+
out = out[0]
|
| 268 |
+
probs = torch.sigmoid(out).cpu().numpy().flatten()
|
| 269 |
+
return probs
|
| 270 |
+
|
| 271 |
+
# Allow shap.TreeExplainer to fail gracefully — app.py has try/except
|
| 272 |
+
def get_booster(self):
|
| 273 |
+
raise NotImplementedError("CNN wrapped as XGB — SHAP not available")
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 277 |
+
# Internal loaders
|
| 278 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 279 |
+
|
| 280 |
+
def _download_repo(repo_id: str) -> Path:
|
| 281 |
+
from huggingface_hub import snapshot_download
|
| 282 |
+
local = snapshot_download(repo_id=repo_id, token=_HF_TOKEN)
|
| 283 |
+
p = Path(local)
|
| 284 |
+
files = [f.name for f in p.rglob("*") if f.is_file()]
|
| 285 |
+
print(f"[PeVe] {repo_id} files: {files}")
|
| 286 |
+
return p
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
def _load_splice() -> tuple:
|
| 290 |
+
import torch
|
| 291 |
+
print(f"[PeVe] Loading splice model from {_REPO_SPLICE}")
|
| 292 |
+
try:
|
| 293 |
+
local = _download_repo(_REPO_SPLICE)
|
| 294 |
+
|
| 295 |
+
# Look for the checkpoint — priority: named file, then any .pt/.pth/.bin
|
| 296 |
+
candidates = (
|
| 297 |
+
list(local.glob("mutation_predictor_splice.pt"))
|
| 298 |
+
+ list(local.glob("*.pt"))
|
| 299 |
+
+ list(local.glob("*.pth"))
|
| 300 |
+
+ list(local.glob("*.bin"))
|
| 301 |
+
)
|
| 302 |
+
if not candidates:
|
| 303 |
+
raise FileNotFoundError(f"No checkpoint in {_REPO_SPLICE}")
|
| 304 |
+
|
| 305 |
+
ckpt = torch.load(str(candidates[0]), map_location="cpu", weights_only=False)
|
| 306 |
+
sd = ckpt.get("model_state_dict", ckpt)
|
| 307 |
+
|
| 308 |
+
model = _build_splice_arch(sd)
|
| 309 |
+
model.eval()
|
| 310 |
+
val_acc = ckpt.get("val_accuracy", "n/a")
|
| 311 |
+
print(f"[PeVe] ✓ splice loaded ({candidates[0].name}) val_acc={val_acc}")
|
| 312 |
+
splice_model_status.update({"loaded": True, "error_message": None})
|
| 313 |
+
return model, None
|
| 314 |
+
|
| 315 |
+
except Exception:
|
| 316 |
+
tb = traceback.format_exc()
|
| 317 |
+
print(f"[PeVe] ✗ splice load failed:\n{tb}")
|
| 318 |
+
splice_model_status.update({"loaded": False, "error_message": tb})
|
| 319 |
+
return None, None
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def _load_context() -> tuple:
|
| 323 |
+
import torch
|
| 324 |
+
print(f"[PeVe] Loading context model from {_REPO_CONTEXT}")
|
| 325 |
+
try:
|
| 326 |
+
local = _download_repo(_REPO_CONTEXT)
|
| 327 |
+
|
| 328 |
+
candidates = (
|
| 329 |
+
list(local.glob("mutation_predictor_splice_v4.pt"))
|
| 330 |
+
+ list(local.glob("*.pt"))
|
| 331 |
+
+ list(local.glob("*.pth"))
|
| 332 |
+
+ list(local.glob("*.bin"))
|
| 333 |
+
)
|
| 334 |
+
if not candidates:
|
| 335 |
+
raise FileNotFoundError(f"No checkpoint in {_REPO_CONTEXT}")
|
| 336 |
+
|
| 337 |
+
sd = torch.load(str(candidates[0]), map_location="cpu", weights_only=False)
|
| 338 |
+
if isinstance(sd, dict) and "model_state_dict" in sd:
|
| 339 |
+
sd = sd["model_state_dict"]
|
| 340 |
+
|
| 341 |
+
model = _build_context_arch(sd)
|
| 342 |
+
model.eval()
|
| 343 |
+
print(f"[PeVe] ✓ context loaded ({candidates[0].name})")
|
| 344 |
+
context_model_status.update({"loaded": True, "error_message": None})
|
| 345 |
+
return model, None
|
| 346 |
+
|
| 347 |
+
except Exception:
|
| 348 |
+
tb = traceback.format_exc()
|
| 349 |
+
print(f"[PeVe] ✗ context load failed:\n{tb}")
|
| 350 |
+
context_model_status.update({"loaded": False, "error_message": tb})
|
| 351 |
+
return None, None
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def _load_protein():
|
| 355 |
+
import xgboost as xgb
|
| 356 |
+
import torch
|
| 357 |
+
print(f"[PeVe] Loading protein model from {_REPO_PROTEIN}")
|
| 358 |
+
|
| 359 |
+
_FEAT = ["gnomAD_AF", "Grantham", "Charge_change",
|
| 360 |
+
"Hydrophobicity_diff", "Protein_pos_norm", "VEP_IMPACT"]
|
| 361 |
+
|
| 362 |
+
try:
|
| 363 |
+
local = _download_repo(_REPO_PROTEIN)
|
| 364 |
+
|
| 365 |
+
# ── Try XGBoost formats first ──────────────────────────────────────
|
| 366 |
+
for ext in ["*.json", "*.ubj", "*.model"]:
|
| 367 |
+
for p in local.glob(ext):
|
| 368 |
+
try:
|
| 369 |
+
m = xgb.Booster()
|
| 370 |
+
m.load_model(str(p))
|
| 371 |
+
print(f"[PeVe] ✓ protein loaded as XGBoost Booster ({p.name})")
|
| 372 |
+
protein_model_status.update({"loaded": True, "error_message": None})
|
| 373 |
+
return m
|
| 374 |
+
except Exception as e:
|
| 375 |
+
print(f"[PeVe] xgb.Booster failed for {p.name}: {e}")
|
| 376 |
+
|
| 377 |
+
# ── Try pickle ────────────────────────────────────────────────────
|
| 378 |
+
for p in local.glob("*.pkl"):
|
| 379 |
+
try:
|
| 380 |
+
with open(p, "rb") as f:
|
| 381 |
+
m = pickle.load(f)
|
| 382 |
+
print(f"[PeVe] ✓ protein loaded via pickle ({p.name})")
|
| 383 |
+
protein_model_status.update({"loaded": True, "error_message": None})
|
| 384 |
+
return m
|
| 385 |
+
except Exception as e:
|
| 386 |
+
print(f"[PeVe] pickle failed for {p.name}: {e}")
|
| 387 |
+
|
| 388 |
+
# ── Fallback: PyTorch checkpoint — wrap as XGB-compatible ─────────
|
| 389 |
+
for ext in ["*.pt", "*.pth", "*.bin"]:
|
| 390 |
+
for p in local.glob(ext):
|
| 391 |
+
try:
|
| 392 |
+
ckpt = torch.load(str(p), map_location="cpu", weights_only=False)
|
| 393 |
+
sd = ckpt.get("model_state_dict", ckpt) if isinstance(ckpt, dict) else ckpt
|
| 394 |
+
|
| 395 |
+
if isinstance(sd, dict):
|
| 396 |
+
# Try MutationPredictorCNN (protein space model.py)
|
| 397 |
+
from torch import nn
|
| 398 |
+
class MutationPredictorCNN(nn.Module):
|
| 399 |
+
def __init__(self):
|
| 400 |
+
super().__init__()
|
| 401 |
+
self.conv1 = nn.Conv1d(11, 64, kernel_size=7, padding=3)
|
| 402 |
+
self.bn1 = nn.BatchNorm1d(64)
|
| 403 |
+
self.conv2 = nn.Conv1d(64, 128, kernel_size=5, padding=2)
|
| 404 |
+
self.bn2 = nn.BatchNorm1d(128)
|
| 405 |
+
self.conv3 = nn.Conv1d(128, 256, kernel_size=3, padding=1)
|
| 406 |
+
self.bn3 = nn.BatchNorm1d(256)
|
| 407 |
+
self.adaptive_pool = nn.AdaptiveAvgPool1d(1)
|
| 408 |
+
self.mut_fc = nn.Linear(12, 32)
|
| 409 |
+
self.fc1 = nn.Linear(288, 128)
|
| 410 |
+
self.fc2 = nn.Linear(128, 64)
|
| 411 |
+
self.fc3 = nn.Linear(64, 1)
|
| 412 |
+
self.importance_head = nn.Linear(256, 1)
|
| 413 |
+
|
| 414 |
+
def forward(self, x):
|
| 415 |
+
import torch.nn.functional as F
|
| 416 |
+
bs = x.size(0)
|
| 417 |
+
mut_type = x[:, 1089:1101]
|
| 418 |
+
x_seq = x[:, :1089].view(bs, 11, 99)
|
| 419 |
+
x_conv = F.relu(self.bn1(self.conv1(x_seq)))
|
| 420 |
+
x_conv = nn.MaxPool1d(2, 2)(x_conv)
|
| 421 |
+
x_conv = F.relu(self.bn2(self.conv2(x_conv)))
|
| 422 |
+
x_conv = nn.MaxPool1d(2, 2)(x_conv)
|
| 423 |
+
x_conv = F.relu(self.bn3(self.conv3(x_conv)))
|
| 424 |
+
x_conv = nn.MaxPool1d(2, 2)(x_conv)
|
| 425 |
+
x_conv = self.adaptive_pool(x_conv)
|
| 426 |
+
conv_feat = x_conv.view(bs, 256)
|
| 427 |
+
mut_feat = F.relu(self.mut_fc(mut_type))
|
| 428 |
+
combined = torch.cat([conv_feat, mut_feat], dim=1)
|
| 429 |
+
x_out = F.relu(self.fc1(combined))
|
| 430 |
+
x_out = F.relu(self.fc2(x_out))
|
| 431 |
+
cls = torch.sigmoid(self.fc3(x_out))
|
| 432 |
+
imp = torch.sigmoid(self.importance_head(conv_feat))
|
| 433 |
+
return cls, imp
|
| 434 |
+
|
| 435 |
+
torch_model = MutationPredictorCNN()
|
| 436 |
+
torch_model.load_state_dict(sd)
|
| 437 |
+
torch_model.eval()
|
| 438 |
+
wrapped = _CNNasXGB(torch_model, _FEAT)
|
| 439 |
+
print(f"[PeVe] ✓ protein loaded as CNN→XGB wrapper ({p.name})")
|
| 440 |
+
protein_model_status.update({"loaded": True, "error_message": None})
|
| 441 |
+
return wrapped
|
| 442 |
+
else:
|
| 443 |
+
# Raw nn.Module saved whole
|
| 444 |
+
wrapped = _CNNasXGB(sd, _FEAT)
|
| 445 |
+
protein_model_status.update({"loaded": True, "error_message": None})
|
| 446 |
+
return wrapped
|
| 447 |
+
|
| 448 |
+
except Exception as e:
|
| 449 |
+
print(f"[PeVe] torch fallback failed for {p.name}: {e}")
|
| 450 |
+
|
| 451 |
+
raise FileNotFoundError("No loadable model file found in protein repo")
|
| 452 |
+
|
| 453 |
+
except Exception:
|
| 454 |
+
tb = traceback.format_exc()
|
| 455 |
+
print(f"[PeVe] ✗ protein load failed:\n{tb}")
|
| 456 |
+
protein_model_status.update({"loaded": False, "error_message": tb})
|
| 457 |
+
return None
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 462 |
+
# Public API (names that app.py imports)
|
| 463 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 464 |
+
|
| 465 |
+
def get_splice_model() -> tuple:
|
| 466 |
+
"""Returns (model, tokenizer). model(tensor) → (logit, imp, r_imp, s_imp)"""
|
| 467 |
+
global _splice_model, _splice_tok
|
| 468 |
+
if _splice_model is None:
|
| 469 |
+
_splice_model, _splice_tok = _load_splice()
|
| 470 |
+
return _splice_model, _splice_tok
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
def get_context_model() -> tuple:
|
| 474 |
+
"""Returns (model, tokenizer). model(tensor) → logit tensor"""
|
| 475 |
+
global _context_model, _context_tok
|
| 476 |
+
if _context_model is None:
|
| 477 |
+
_context_model, _context_tok = _load_context()
|
| 478 |
+
return _context_model, _context_tok
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
def get_protein_model():
|
| 482 |
+
"""Returns XGBoost Booster (or CNN wrapper). model.predict(dmat) → float array"""
|
| 483 |
+
global _protein_model
|
| 484 |
+
if _protein_model is None:
|
| 485 |
+
_protein_model = _load_protein()
|
| 486 |
+
return _protein_model
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
def get_model_status() -> dict:
|
| 490 |
+
return {
|
| 491 |
+
"splice": dict(splice_model_status),
|
| 492 |
+
"context": dict(context_model_status),
|
| 493 |
+
"protein": dict(protein_model_status),
|
| 494 |
+
}
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 498 |
+
# Test block
|
| 499 |
+
# ══════════════════════════════════════════════════════════════════════════════
|
| 500 |
+
|
| 501 |
+
def test_model_loading() -> dict:
|
| 502 |
+
import torch
|
| 503 |
+
print("[PeVe] ── test_model_loading() ──")
|
| 504 |
+
|
| 505 |
+
sm, _ = get_splice_model()
|
| 506 |
+
cm, _ = get_context_model()
|
| 507 |
+
pm = get_protein_model()
|
| 508 |
+
|
| 509 |
+
results = {}
|
| 510 |
+
|
| 511 |
+
# Test splice
|
| 512 |
+
try:
|
| 513 |
+
if sm is not None:
|
| 514 |
+
dummy = torch.zeros(1, 1106)
|
| 515 |
+
out = sm(dummy)
|
| 516 |
+
results["splice"] = f"✓ output shapes: {[o.shape for o in out]}"
|
| 517 |
+
else:
|
| 518 |
+
results["splice"] = "✗ model is None"
|
| 519 |
+
except Exception as e:
|
| 520 |
+
results["splice"] = f"✗ forward failed: {e}"
|
| 521 |
+
|
| 522 |
+
# Test context
|
| 523 |
+
try:
|
| 524 |
+
if cm is not None:
|
| 525 |
+
dummy = torch.zeros(1, 1106)
|
| 526 |
+
out = cm(dummy)
|
| 527 |
+
results["context"] = f"✓ output shape: {out.shape if hasattr(out,'shape') else type(out)}"
|
| 528 |
+
else:
|
| 529 |
+
results["context"] = "✗ model is None"
|
| 530 |
+
except Exception as e:
|
| 531 |
+
results["context"] = f"✗ forward failed: {e}"
|
| 532 |
+
|
| 533 |
+
# Test protein
|
| 534 |
+
try:
|
| 535 |
+
if pm is not None:
|
| 536 |
+
import xgboost as xgb
|
| 537 |
+
feat = ["gnomAD_AF","Grantham","Charge_change",
|
| 538 |
+
"Hydrophobicity_diff","Protein_pos_norm","VEP_IMPACT"]
|
| 539 |
+
X = np.array([[0.001, 100.0, 0.0, 0.5, 0.5, 2.0]], dtype=np.float32)
|
| 540 |
+
dmat = xgb.DMatrix(X, feature_names=feat)
|
| 541 |
+
pred = pm.predict(dmat)
|
| 542 |
+
results["protein"] = f"✓ prediction: {pred}"
|
| 543 |
+
else:
|
| 544 |
+
results["protein"] = "✗ model is None"
|
| 545 |
+
except Exception as e:
|
| 546 |
+
results["protein"] = f"✗ predict failed: {e}"
|
| 547 |
+
|
| 548 |
+
status = get_model_status()
|
| 549 |
+
final = {
|
| 550 |
+
"model_status": status,
|
| 551 |
+
"forward_tests": results,
|
| 552 |
+
"all_loaded": all(v["loaded"] for v in status.values()),
|
| 553 |
+
}
|
| 554 |
+
import json
|
| 555 |
+
print(json.dumps(final, indent=2, default=str))
|
| 556 |
+
return final
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
if __name__ == "__main__":
|
| 560 |
+
test_model_loading()
|