nileshhanotia commited on
Commit
1d10606
·
verified ·
1 Parent(s): c367a28

Update model_loader.py

Browse files
Files changed (1) hide show
  1. model_loader.py +497 -382
model_loader.py CHANGED
@@ -1,443 +1,558 @@
1
  """
2
- model_loader.py — PeVe v1.3
3
- ===========================
4
- ARCHITECTURE CHANGE (correct approach):
5
- Models are NOT loaded as weights. They are already running as live
6
- Gradio Spaces on HuggingFace. We query them via their HTTP /predict
7
- (or /run/predict) Gradio API endpoints.
8
-
9
- Space URLs:
10
- splice : https://nileshhanotia-mutation-predictor-splice-app.hf.space
11
- context : https://nileshhanotia-mutation-predictor-v4-demo.hf.space
12
- protein : https://nileshhanotia-mutation-pathogenicity-app.hf.space
13
-
14
- The model_loader exposes three functions:
15
- query_splice_model(ref_seq, mut_seq, chrom, pos, exon_flag, intron_flag)
16
- query_context_model(chrom, pos, ref, alt)
17
- query_protein_model(feature_vector: list[float])
18
-
19
- Each returns a dict with:
20
- {
21
- "loaded": True/False,
22
- "error_message": None or str,
23
- ... model-specific output keys ...
24
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  """
26
  from __future__ import annotations
27
 
28
  import os
29
- import time
30
  import traceback
 
 
31
  from typing import Any
32
 
33
- import requests
34
-
35
- # ── Space base URLs ────────────────────────────────────────────────────────────
36
- # These are the standard HF Spaces inference URLs (Gradio 3/4 compatible)
37
- _SPLICE_SPACE = os.environ.get(
38
- "SPLICE_SPACE_URL",
39
- "https://nileshhanotia-mutation-predictor-splice-app.hf.space"
40
- )
41
- _CONTEXT_SPACE = os.environ.get(
42
- "CONTEXT_SPACE_URL",
43
- "https://nileshhanotia-mutation-predictor-v4-demo.hf.space"
44
- )
45
- _PROTEIN_SPACE = os.environ.get(
46
- "PROTEIN_SPACE_URL",
47
- "https://nileshhanotia-mutation-pathogenicity-app.hf.space"
48
- )
49
 
 
50
  _HF_TOKEN: str | None = (
51
  os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")
52
  )
53
 
54
- _TIMEOUT = int(os.environ.get("MODEL_TIMEOUT", "30")) # seconds per call
55
- _MAX_RETRIES = 2
 
 
56
 
57
- # ── Status dicts (updated on every call) ──────────────────────────────────────
58
- splice_model_status: dict = {"loaded": False, "error_message": "Not yet called"}
59
- context_model_status: dict = {"loaded": False, "error_message": "Not yet called"}
60
- protein_model_status: dict = {"loaded": False, "error_message": "Not yet called"}
 
 
61
 
 
 
 
 
62
 
63
- # ── Low-level HTTP helper ──────────────────────────────────────────────────────
64
 
65
- def _gradio_predict(space_url: str, payload: dict, status: dict,
66
- label: str) -> dict | None:
67
- """
68
- POST to a Gradio /run/predict endpoint.
69
- Gradio 3 payload shape: {"data": [...]}
70
- Returns the parsed response dict, or None on failure.
71
- Retries up to _MAX_RETRIES times with exponential back-off.
72
- Updates `status` in place.
73
- """
74
- endpoint = f"{space_url.rstrip('/')}/run/predict"
75
- headers = {"Content-Type": "application/json"}
76
- if _HF_TOKEN:
77
- headers["Authorization"] = f"Bearer {_HF_TOKEN}"
78
 
79
- last_err = ""
80
- for attempt in range(1, _MAX_RETRIES + 1):
81
- try:
82
- print(f"[PeVe] {label} POST {endpoint} (attempt {attempt})")
83
- resp = requests.post(
84
- endpoint,
85
- json=payload,
86
- headers=headers,
87
- timeout=_TIMEOUT,
88
- )
89
- resp.raise_for_status()
90
- data = resp.json()
91
- print(f"[PeVe] {label} ← HTTP 200, keys={list(data.keys())}")
92
- status["loaded"] = True
93
- status["error_message"] = None
94
- return data
95
-
96
- except requests.exceptions.HTTPError as e:
97
- last_err = f"HTTP {resp.status_code}: {resp.text[:300]}"
98
- print(f"[PeVe] {label} attempt {attempt} HTTPError: {last_err}")
99
- except requests.exceptions.Timeout:
100
- last_err = f"Timeout after {_TIMEOUT}s"
101
- print(f"[PeVe] {label} attempt {attempt} Timeout")
102
- except Exception:
103
- last_err = traceback.format_exc()
104
- print(f"[PeVe] {label} attempt {attempt} error:\n{last_err}")
105
-
106
- if attempt < _MAX_RETRIES:
107
- time.sleep(2 ** attempt) # 2s, 4s …
108
-
109
- status["loaded"] = False
110
- status["error_message"] = last_err
111
- return None
112
 
 
 
113
 
114
- def _wake_space(space_url: str, label: str) -> bool:
115
  """
116
- HF Spaces sleep after inactivity. A GET to / wakes them.
117
- Returns True if the Space responds with 200.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  """
119
- try:
120
- r = requests.get(space_url, timeout=15,
121
- headers={"Authorization": f"Bearer {_HF_TOKEN}"} if _HF_TOKEN else {})
122
- print(f"[PeVe] wake {label}: HTTP {r.status_code}")
123
- return r.status_code == 200
124
- except Exception as e:
125
- print(f"[PeVe] wake {label} failed: {e}")
126
- return False
127
-
128
-
129
- # ── Splice Space ───────────────────────────────────────────────────────────────
130
- # Space: mutation-predictor-splice-app
131
- # Model: MutationPredictorCNN_v2
132
- # Gradio fn: predict_variant_with_causal_analysis(ref_seq, mut_seq, chrom, pos,
133
- # exon_flag, intron_flag)
134
- # Inputs: 6 values → data: [str, str, str, int, int, int]
135
- # Outputs: [report_str, act_fig, splice_fig, percentile_str,
136
- # cf_text, cf_fig, grad_fig, ablation_fig, ablation_text]
137
-
138
- def query_splice_model(
139
- ref_seq: str,
140
- mut_seq: str,
141
- chrom: str = "17",
142
- pos: int = 0,
143
- exon_flag: int = 1,
144
- intron_flag: int = 0,
145
- ) -> dict:
146
  """
147
- Query the splice Space and return structured outputs.
148
-
149
- Returns
150
- -------
151
- {
152
- "loaded": bool,
153
- "error_message": str | None,
154
- "splice_prob": float, # sigmoid of logit from report text
155
- "splice_signal_strength": float,
156
- "counterfactual_delta": float,
157
- "raw_report": str,
158
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159
  """
160
- _wake_space(_SPLICE_SPACE, "splice")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
 
162
- payload = {
163
- "data": [ref_seq, mut_seq, str(chrom), int(pos),
164
- int(exon_flag), int(intron_flag)],
165
- "fn_index": 0, # predict_variant_with_causal_analysis is fn 0
166
- }
 
 
167
 
168
- result = _gradio_predict(_SPLICE_SPACE, payload, splice_model_status, "splice")
169
- if result is None:
170
- return {
171
- "loaded": False,
172
- "error_message": splice_model_status["error_message"],
173
- "splice_prob": 0.0,
174
- "splice_signal_strength": 0.0,
175
- "counterfactual_delta": 0.0,
176
- "raw_report": "",
177
- }
178
-
179
- # Gradio returns {"data": [output0, output1, ...]}
180
- outputs = result.get("data", [])
181
- report_str = outputs[0] if len(outputs) > 0 else ""
182
- cf_text = outputs[4] if len(outputs) > 4 else ""
183
- ablation_text = outputs[8] if len(outputs) > 8 else ""
184
-
185
- # Parse probability from the text report (format: "Probability : 0.XXXX")
186
- splice_prob = _parse_float_from_text(report_str, "Probability")
187
- cf_delta = _parse_float_from_text(cf_text, "Causal importance score")
188
 
189
- return {
190
- "loaded": True,
191
- "error_message": None,
192
- "splice_prob": splice_prob,
193
- "splice_signal_strength": splice_prob, # direct proxy
194
- "counterfactual_delta": cf_delta,
195
- "raw_report": report_str,
196
- }
197
 
 
 
 
198
 
199
- # ── Context Space ──────────────────────────────────────────────────────────────
200
- # Space: mutation-predictor-v4-demo
201
- # Model: MutationPredictorCNN_v4 (BUT currently runs predict_dummy → random float)
202
- # Gradio fn: predict_dummy(chr, pos, ref, alt)
203
- # Inputs: [str, int, str, str]
204
- # Outputs: [markdown_str]
205
- #
206
- # NOTE: This Space currently returns a dummy probability. The model IS loaded
207
- # (torch.load on "mutation_predictor_splice_v4.pt") but predict_dummy bypasses it.
208
- # Until the Space is updated to call the real model, we extract the dummy float
209
- # and surface it with a warning.
210
-
211
- def query_context_model(
212
- chrom: str,
213
- pos: int,
214
- ref: str,
215
- alt: str,
216
- ) -> dict:
217
- """
218
- Query the context/v4 Space.
219
-
220
- Returns
221
- -------
222
- {
223
- "loaded": bool,
224
- "error_message": str | None,
225
- "context_pathogenic_prob": float,
226
- "activation_norm": float,
227
- "activation_peak_position": int,
228
- "importance_score": float,
229
- "warning": str | None,
230
- }
231
- """
232
- _wake_space(_CONTEXT_SPACE, "context")
233
 
234
- payload = {
235
- "data": [str(chrom), int(pos), str(ref), str(alt)],
236
- "fn_index": 0,
237
- }
238
 
239
- result = _gradio_predict(_CONTEXT_SPACE, payload, context_model_status, "context")
240
- if result is None:
241
- return {
242
- "loaded": False,
243
- "error_message": context_model_status["error_message"],
244
- "context_pathogenic_prob": 0.0,
245
- "activation_norm": 0.0,
246
- "activation_peak_position": 200,
247
- "importance_score": 0.0,
248
- "warning": None,
249
- }
 
 
 
 
250
 
251
- outputs = result.get("data", [])
252
- text_out = outputs[0] if outputs else ""
253
 
254
- # Parse "Predicted probability: X.XXX" from markdown output
255
- prob = _parse_float_from_text(text_out, "Predicted probability")
 
 
 
 
256
 
257
- return {
258
- "loaded": True,
259
- "error_message": None,
260
- "context_pathogenic_prob": prob,
261
- "activation_norm": prob, # best proxy available
262
- "activation_peak_position": 200, # not exposed by this Space yet
263
- "importance_score": prob,
264
- "warning": (
265
- "context Space is running predict_dummy (placeholder). "
266
- "Probability is random. Update Space to call real model."
267
- if "placeholder" in text_out.lower() else None
268
- ),
269
- }
270
 
271
 
272
- # ── Protein / Pathogenicity Space ──────────────────────────────────────────────
273
- # Space: mutation-pathogenicity-app
274
- # Model: MutationPredictorCNN (model.py CNN with input dim 1101)
275
- # We need to know the Gradio fn signature. Since we couldn't fetch app.py,
276
- # we attempt /info first to discover the API, then call /run/predict.
277
-
278
- def query_protein_model(
279
- ref_seq: str,
280
- mut_seq: str,
281
- chrom: str = "17",
282
- pos: int = 0,
283
- exon_flag: int = 1,
284
- intron_flag: int = 0,
285
- ) -> dict:
286
- """
287
- Query the protein/pathogenicity Space.
288
-
289
- Returns
290
- -------
291
- {
292
- "loaded": bool,
293
- "error_message": str | None,
294
- "biochemical_risk_score": float,
295
- "feature_pathogenic_prob": float,
296
- "shap_feature_contributions": dict,
297
- }
298
- """
299
- _wake_space(_PROTEIN_SPACE, "protein")
300
-
301
- # Try to discover API shape first
302
- api_info = _get_space_api_info(_PROTEIN_SPACE)
303
- fn_index = 0
304
-
305
- # MutationPredictorCNN takes input dim 1101 — if the Space accepts
306
- # raw sequences, send them; fall back to numeric if it expects a vector.
307
- payload = {
308
- "data": [ref_seq, mut_seq, str(chrom), int(pos),
309
- int(exon_flag), int(intron_flag)],
310
- "fn_index": fn_index,
311
- }
312
 
313
- result = _gradio_predict(_PROTEIN_SPACE, payload, protein_model_status, "protein")
314
- if result is None:
315
- # Second attempt: maybe the Space expects only chr/pos/ref/alt
316
- payload2 = {
317
- "data": [str(chrom), int(pos), ref_seq[0] if ref_seq else "N",
318
- mut_seq[0] if mut_seq else "N"],
319
- "fn_index": fn_index,
320
- }
321
- result = _gradio_predict(_PROTEIN_SPACE, payload2, protein_model_status,
322
- "protein-fallback")
323
-
324
- if result is None:
325
- return {
326
- "loaded": False,
327
- "error_message": protein_model_status["error_message"],
328
- "biochemical_risk_score": 0.0,
329
- "feature_pathogenic_prob": 0.0,
330
- "shap_feature_contributions": {},
331
- }
332
-
333
- outputs = result.get("data", [])
334
- text_out = str(outputs[0]) if outputs else ""
335
-
336
- prob = _parse_float_from_text(text_out, "probability") or \
337
- _parse_float_from_text(text_out, "Probability") or \
338
- _parse_float_from_text(text_out, "score")
339
 
340
- return {
341
- "loaded": True,
342
- "error_message": None,
343
- "biochemical_risk_score": prob,
344
- "feature_pathogenic_prob": prob,
345
- "shap_feature_contributions": {}, # not exposed by this Space yet
346
- }
347
 
 
 
 
 
 
348
 
349
- # ── Utility helpers ────────────────────────────────────────────────────────────
 
 
 
 
350
 
351
- def _parse_float_from_text(text: str, keyword: str) -> float:
352
- """
353
- Extract a float after 'keyword' in text.
354
- e.g. "Probability : 0.8743" → 0.8743
355
- """
356
- import re
357
- pattern = re.compile(
358
- rf"{re.escape(keyword)}\s*[:\|=]?\s*([0-9]+\.?[0-9]*)",
359
- re.IGNORECASE,
360
- )
361
- m = pattern.search(text)
362
- if m:
363
- try:
364
- return float(m.group(1))
365
- except ValueError:
366
- pass
367
- return 0.0
368
 
 
 
 
 
 
 
 
369
 
370
- def _get_space_api_info(space_url: str) -> dict:
371
- """Fetch /info endpoint to understand Space API (Gradio 3.x+)."""
372
  try:
373
- r = requests.get(
374
- f"{space_url.rstrip('/')}/info",
375
- timeout=10,
376
- headers={"Authorization": f"Bearer {_HF_TOKEN}"} if _HF_TOKEN else {},
377
- )
378
- if r.status_code == 200:
379
- return r.json()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
380
  except Exception:
381
- pass
382
- return {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
383
 
 
 
 
 
 
 
384
 
385
- # ── Status accessors ───────────────────────────────────────────────────────────
386
 
387
  def get_model_status() -> dict:
388
- """Return last-call status for all three models."""
389
  return {
390
- "splice": splice_model_status,
391
- "context": context_model_status,
392
- "protein": protein_model_status,
393
  }
394
 
395
 
396
- # ── Test block ─────────────────────────────────────────────────────────────────
 
 
397
 
398
  def test_model_loading() -> dict:
399
- """
400
- Smoke-test all three Spaces with a real BRCA1 variant window.
401
- chr17:43092176 G>T (the variant from your JSON example).
402
- """
403
  print("[PeVe] ── test_model_loading() ──")
404
 
405
- # 99-bp window centred on BRCA1 position 43092176 (synthetic for test)
406
- ref_seq = ("ATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCG"
407
- "GCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGAT")[:99]
408
- mut_seq = (ref_seq[:49] + "T" + ref_seq[50:])[:99] # G→T at centre
409
-
410
- r_splice = query_splice_model(ref_seq, mut_seq, "17", 43092176, 1, 0)
411
- r_context = query_context_model("17", 43092176, "G", "T")
412
- r_protein = query_protein_model(ref_seq, mut_seq, "17", 43092176, 1, 0)
413
-
414
- result = {
415
- "model_status": {
416
- "splice": {"loaded": r_splice["loaded"],
417
- "error_message": r_splice["error_message"]},
418
- "context": {"loaded": r_context["loaded"],
419
- "error_message": r_context["error_message"]},
420
- "protein": {"loaded": r_protein["loaded"],
421
- "error_message": r_protein["error_message"]},
422
- },
423
- "sample_outputs": {
424
- "splice_prob": r_splice.get("splice_prob"),
425
- "counterfactual_delta": r_splice.get("counterfactual_delta"),
426
- "context_pathogenic_prob": r_context.get("context_pathogenic_prob"),
427
- "context_warning": r_context.get("warning"),
428
- "biochemical_risk_score": r_protein.get("biochemical_risk_score"),
429
- },
430
- "all_loaded": all([r_splice["loaded"],
431
- r_context["loaded"],
432
- r_protein["loaded"]]),
433
- }
434
 
435
- print(f"[PeVe] Result: {result}")
436
- return result
437
 
 
 
 
 
 
 
 
 
 
 
438
 
439
- if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
440
  import json
441
- report = test_model_loading()
442
- print(json.dumps(report, indent=2))
443
-
 
 
 
 
1
  """
2
+ model_loader.py — PeVe v1.4
3
+ ============================
4
+
5
+ What app.py needs (read from app.py source):
6
+
7
+ from model_loader import get_splice_model, get_context_model, get_protein_model
8
+
9
+ model, tokenizer = get_splice_model()
10
+ model accepts: torch.Tensor of shape (1, 401, 8) or (1, 401, 8) + flags
11
+ used inside torch.no_grad()
12
+ returns tensor or tuple[tensor, ...]
13
+
14
+ model, tokenizer = get_context_model()
15
+ same calling convention as splice
16
+
17
+ model = get_protein_model()
18
+ → used with: xgb.DMatrix(X, feature_names=[...])
19
+ → model.predict(dmat) float array
20
+ → also passed to shap.TreeExplainer(model)
21
+
22
+ Model sources (from the Space app.py files):
23
+ splice → nileshhanotia/mutation-predictor-splice
24
+ file: mutation_predictor_splice.pt
25
+ arch: MutationPredictorCNN_v2 (input flat 1106)
26
+ NOTE: app.py passes (1, 401, 8) tensor — loader must reshape
27
+
28
+ context → nileshhanotia/mutation-predictor-v4
29
+ file: mutation_predictor_splice_v4.pt
30
+ arch: MutationPredictorCNN_v4 (4-tensor forward: seq,mut,region,splice)
31
+ NOTE: app.py passes (1, 401, 8) tensor — loader wraps forward
32
+
33
+ protein → nileshhanotia/mutation-pathogenicity-predictor
34
+ file: *.json / *.ubj / *.model / *.pkl
35
+ NOTE: app.py uses xgb.DMatrix + shap — MUST be XGBoost
36
+ If file is actually a CNN checkpoint, we wrap it as an
37
+ XGBoost-compatible object so app.py code paths still work.
38
  """
39
  from __future__ import annotations
40
 
41
  import os
42
+ import pickle
43
  import traceback
44
+ import warnings
45
+ from pathlib import Path
46
  from typing import Any
47
 
48
+ import numpy as np
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
+ # ── HF token ──────────────────────────────────────────────────────────────────
51
  _HF_TOKEN: str | None = (
52
  os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")
53
  )
54
 
55
+ # ── Model repo IDs ─────────────────────────────────────────────────────────────
56
+ _REPO_SPLICE = "nileshhanotia/mutation-predictor-splice"
57
+ _REPO_CONTEXT = "nileshhanotia/mutation-predictor-v4"
58
+ _REPO_PROTEIN = "nileshhanotia/mutation-pathogenicity-predictor"
59
 
60
+ # ── Global cache ───────────────────────────────────────────────────────────────
61
+ _splice_model = None
62
+ _splice_tok = None
63
+ _context_model = None
64
+ _context_tok = None
65
+ _protein_model = None
66
 
67
+ # ── Structured status dicts ───────────────────────────────────────────────��────
68
+ splice_model_status: dict = {"loaded": False, "error_message": None}
69
+ context_model_status: dict = {"loaded": False, "error_message": None}
70
+ protein_model_status: dict = {"loaded": False, "error_message": None}
71
 
 
72
 
73
+ # ══════════════════════════════════════════════════════════════════════════════
74
+ # Model Architecture definitions
75
+ # (must match checkpoint shapes exactly)
76
+ # ══════════════════════════════════════════════════════════════════════════════
 
 
 
 
 
 
 
 
 
77
 
78
+ def _build_splice_arch(sd: dict):
79
+ """
80
+ MutationPredictorCNN_v2 — infer fc_region_out and splice_fc_out from
81
+ the checkpoint's weight shapes, exactly as the Space app does.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
+ Forward signature in the Space:
84
+ logit, imp_score, r_imp, s_imp = model(flat_tensor, mutation_positions)
85
 
86
+ app.py passes tensors of shape (1, 401, 8). We need an adapter.
87
  """
88
+ import torch
89
+ import torch.nn as nn
90
+ import torch.nn.functional as F
91
+
92
+ fc_region_out = sd["fc_region.weight"].shape[0]
93
+ splice_fc_out = sd["splice_fc.weight"].shape[0]
94
+
95
+ class MutationPredictorCNN_v2(nn.Module):
96
+ def __init__(self):
97
+ super().__init__()
98
+ fc1_in = 256 + 32 + fc_region_out + splice_fc_out
99
+ self.conv1 = nn.Conv1d(11, 64, kernel_size=7, padding=3)
100
+ self.bn1 = nn.BatchNorm1d(64)
101
+ self.conv2 = nn.Conv1d(64, 128, kernel_size=5, padding=2)
102
+ self.bn2 = nn.BatchNorm1d(128)
103
+ self.conv3 = nn.Conv1d(128, 256, kernel_size=3, padding=1)
104
+ self.bn3 = nn.BatchNorm1d(256)
105
+ self.global_pool = nn.AdaptiveAvgPool1d(1)
106
+ self.mut_fc = nn.Linear(12, 32)
107
+ self.importance_head = nn.Linear(256, 1)
108
+ self.region_importance_head = nn.Linear(256, 2)
109
+ self.fc_region = nn.Linear(2, fc_region_out)
110
+ self.splice_fc = nn.Linear(3, splice_fc_out)
111
+ self.splice_importance_head = nn.Linear(256, 3)
112
+ self.fc1 = nn.Linear(fc1_in, 128)
113
+ self.fc2 = nn.Linear(128, 64)
114
+ self.fc3 = nn.Linear(64, 1)
115
+ self.relu = nn.ReLU()
116
+ self.dropout = nn.Dropout(0.4)
117
+
118
+ def _forward_flat(self, x_flat, mutation_positions=None):
119
+ """Original forward for flat 1106-dim input."""
120
+ bs = x_flat.size(0)
121
+ seq_flat = x_flat[:, :1089]
122
+ mut_onehot = x_flat[:, 1089:1101]
123
+ region_feat= x_flat[:, 1101:1103]
124
+ splice_feat= x_flat[:, 1103:1106]
125
+ h = self.relu(self.bn1(self.conv1(seq_flat.view(bs, 11, 99))))
126
+ h = self.relu(self.bn2(self.conv2(h)))
127
+ conv_out = self.relu(self.bn3(self.conv3(h)))
128
+ if mutation_positions is None:
129
+ mutation_positions = x_flat[:, 990:1089].argmax(dim=1)
130
+ pos_idx = mutation_positions.clamp(0, 98).long()
131
+ pe = pos_idx.view(bs, 1, 1).expand(bs, 256, 1)
132
+ mut_feat = conv_out.gather(2, pe).squeeze(2)
133
+ imp_score = torch.sigmoid(self.importance_head(mut_feat))
134
+ pooled = self.global_pool(conv_out).squeeze(-1)
135
+ r_imp = torch.sigmoid(self.region_importance_head(pooled))
136
+ s_imp = torch.sigmoid(self.splice_importance_head(pooled))
137
+ m = self.relu(self.mut_fc(mut_onehot))
138
+ r = self.relu(self.fc_region(region_feat))
139
+ s = self.relu(self.splice_fc(splice_feat))
140
+ fused = torch.cat([pooled, m, r, s], dim=1)
141
+ out = self.dropout(self.relu(self.fc1(fused)))
142
+ out = self.dropout(self.relu(self.fc2(out)))
143
+ logit = self.fc3(out)
144
+ return logit, imp_score, r_imp, s_imp
145
+
146
+ def forward(self, x, mutation_positions=None):
147
+ """
148
+ Accept whatever shape app.py sends:
149
+ (B, 401, 8) — raw encoded window from app.py
150
+ (B, 1106) — flat input (native format)
151
+ """
152
+ if x.dim() == 3:
153
+ # app.py sends (B, 401, 8) — flatten and zero-pad to 1106
154
+ bs = x.size(0)
155
+ flat = x.reshape(bs, -1) # → (B, 3208)
156
+ # Take first 1089 dims (99*11), pad mut/region/splice to zeros
157
+ seq_part = flat[:, :1089]
158
+ pad = torch.zeros(bs, 1106 - 1089, device=x.device)
159
+ flat_padded = torch.cat([seq_part, pad], dim=1) # → (B, 1106)
160
+ return self._forward_flat(flat_padded, mutation_positions)
161
+ return self._forward_flat(x, mutation_positions)
162
+
163
+ model = MutationPredictorCNN_v2()
164
+ model.load_state_dict(sd)
165
+ return model
166
+
167
+
168
+ def _build_context_arch(sd: dict):
169
  """
170
+ MutationPredictorCNN_v4 — 4-input forward (seq, mut, region, splice).
171
+ app.py passes a single (B, 401, 8) tensor, so forward() adapts.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
  """
173
+ import torch
174
+ import torch.nn as nn
175
+
176
+ class MutationPredictorCNN_v4(nn.Module):
177
+ def __init__(self):
178
+ super().__init__()
179
+ self.conv1 = nn.Conv1d(11, 64, 7, padding=3)
180
+ self.conv2 = nn.Conv1d(64, 128, 5, padding=2)
181
+ self.conv3 = nn.Conv1d(128,256, 3, padding=1)
182
+ self.pool = nn.AdaptiveAvgPool1d(1)
183
+ self.mut_fc = nn.Linear(12, 32)
184
+ self.region_fc = nn.Linear(2, 8)
185
+ self.splice_fc = nn.Linear(3, 16)
186
+ self.fc1 = nn.Linear(312, 128)
187
+ self.fc2 = nn.Linear(128, 64)
188
+ self.fc3 = nn.Linear(64, 1)
189
+ self.relu = nn.ReLU()
190
+ self.dropout = nn.Dropout(0.3)
191
+
192
+ def _forward_native(self, seq, mut, region, splice):
193
+ x = self.relu(self.conv1(seq))
194
+ x = self.relu(self.conv2(x))
195
+ x = self.relu(self.conv3(x))
196
+ x = self.pool(x).squeeze(-1)
197
+ m = self.relu(self.mut_fc(mut))
198
+ r = self.relu(self.region_fc(region))
199
+ s = self.relu(self.splice_fc(splice))
200
+ x = torch.cat([x, m, r, s], dim=1)
201
+ x = self.dropout(self.relu(self.fc1(x)))
202
+ x = self.relu(self.fc2(x))
203
+ return self.fc3(x)
204
+
205
+ def forward(self, x, *args):
206
+ """
207
+ Accept:
208
+ (B, 401, 8) → reshape to 99*11 window, zero-pad aux inputs
209
+ (seq, mut, region, splice) tensors — native
210
+ """
211
+ import torch
212
+ if isinstance(x, torch.Tensor) and x.dim() == 3:
213
+ bs = x.size(0)
214
+ flat = x.reshape(bs, -1)
215
+ seq_flat = flat[:, :1089].view(bs, 11, 99)
216
+ mut = torch.zeros(bs, 12, device=x.device)
217
+ region = torch.zeros(bs, 2, device=x.device)
218
+ splice = torch.zeros(bs, 3, device=x.device)
219
+ return self._forward_native(seq_flat, mut, region, splice)
220
+ # flat 1089+12+2+3 = 1106 case
221
+ if isinstance(x, torch.Tensor) and x.dim() == 2:
222
+ bs = x.size(0)
223
+ seq_flat = x[:, :1089].view(bs, 11, 99)
224
+ mut = x[:, 1089:1101]
225
+ region = x[:, 1101:1103]
226
+ splice = x[:, 1103:1106]
227
+ return self._forward_native(seq_flat, mut, region, splice)
228
+ # called with 4 separate tensors
229
+ return self._forward_native(x, *args)
230
+
231
+ model = MutationPredictorCNN_v4()
232
+ model.load_state_dict(sd)
233
+ return model
234
+
235
+
236
+ class _CNNasXGB:
237
  """
238
+ Wrapper that makes a PyTorch CNN look like an XGBoost Booster
239
+ to satisfy the app.py code paths:
240
+ dmat = xgb.DMatrix(X, feature_names=[...])
241
+ pred = model.predict(dmat) ← needs .predict()
242
+ shap.TreeExplainer(model) ← will fail gracefully; app has try/except
243
+ """
244
+ def __init__(self, torch_model, feature_names: list[str]):
245
+ import torch
246
+ self._model = torch_model
247
+ self._model.eval()
248
+ self._features = feature_names
249
+ self._device = torch.device("cpu")
250
+
251
+ def predict(self, dmat_or_array) -> np.ndarray:
252
+ import torch
253
+ try:
254
+ # xgb.DMatrix → get_data() returns scipy sparse or np array
255
+ try:
256
+ X = dmat_or_array.get_data().toarray()
257
+ except Exception:
258
+ X = np.array(dmat_or_array)
259
+ except Exception:
260
+ X = np.zeros((1, len(self._features)), dtype=np.float32)
261
 
262
+ t = torch.tensor(X, dtype=torch.float32)
263
+ with torch.no_grad():
264
+ out = self._model(t)
265
+ if isinstance(out, (tuple, list)):
266
+ out = out[0]
267
+ probs = torch.sigmoid(out).cpu().numpy().flatten()
268
+ return probs
269
 
270
+ # Allow shap.TreeExplainer to fail gracefully — app.py has try/except
271
+ def get_booster(self):
272
+ raise NotImplementedError("CNN wrapped as XGB — SHAP not available")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
273
 
 
 
 
 
 
 
 
 
274
 
275
+ # ══════════════════════════════════════════════════════════════════════════════
276
+ # Internal loaders
277
+ # ══════════════════════════════════════════════════════════════════════════════
278
 
279
+ def _download_repo(repo_id: str) -> Path:
280
+ from huggingface_hub import snapshot_download
281
+ local = snapshot_download(repo_id=repo_id, token=_HF_TOKEN)
282
+ p = Path(local)
283
+ files = [f.name for f in p.rglob("*") if f.is_file()]
284
+ print(f"[PeVe] {repo_id} files: {files}")
285
+ return p
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
286
 
 
 
 
 
287
 
288
+ def _load_splice() -> tuple:
289
+ import torch
290
+ print(f"[PeVe] Loading splice model from {_REPO_SPLICE}")
291
+ try:
292
+ local = _download_repo(_REPO_SPLICE)
293
+
294
+ # Look for the checkpoint — priority: named file, then any .pt/.pth/.bin
295
+ candidates = (
296
+ list(local.glob("mutation_predictor_splice.pt"))
297
+ + list(local.glob("*.pt"))
298
+ + list(local.glob("*.pth"))
299
+ + list(local.glob("*.bin"))
300
+ )
301
+ if not candidates:
302
+ raise FileNotFoundError(f"No checkpoint in {_REPO_SPLICE}")
303
 
304
+ ckpt = torch.load(str(candidates[0]), map_location="cpu", weights_only=False)
305
+ sd = ckpt.get("model_state_dict", ckpt)
306
 
307
+ model = _build_splice_arch(sd)
308
+ model.eval()
309
+ val_acc = ckpt.get("val_accuracy", "n/a")
310
+ print(f"[PeVe] ✓ splice loaded ({candidates[0].name}) val_acc={val_acc}")
311
+ splice_model_status.update({"loaded": True, "error_message": None})
312
+ return model, None
313
 
314
+ except Exception:
315
+ tb = traceback.format_exc()
316
+ print(f"[PeVe] ✗ splice load failed:\n{tb}")
317
+ splice_model_status.update({"loaded": False, "error_message": tb})
318
+ return None, None
 
 
 
 
 
 
 
 
319
 
320
 
321
+ def _load_context() -> tuple:
322
+ import torch
323
+ print(f"[PeVe] Loading context model from {_REPO_CONTEXT}")
324
+ try:
325
+ local = _download_repo(_REPO_CONTEXT)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
326
 
327
+ candidates = (
328
+ list(local.glob("mutation_predictor_splice_v4.pt"))
329
+ + list(local.glob("*.pt"))
330
+ + list(local.glob("*.pth"))
331
+ + list(local.glob("*.bin"))
332
+ )
333
+ if not candidates:
334
+ raise FileNotFoundError(f"No checkpoint in {_REPO_CONTEXT}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
335
 
336
+ sd = torch.load(str(candidates[0]), map_location="cpu", weights_only=False)
337
+ if isinstance(sd, dict) and "model_state_dict" in sd:
338
+ sd = sd["model_state_dict"]
 
 
 
 
339
 
340
+ model = _build_context_arch(sd)
341
+ model.eval()
342
+ print(f"[PeVe] ✓ context loaded ({candidates[0].name})")
343
+ context_model_status.update({"loaded": True, "error_message": None})
344
+ return model, None
345
 
346
+ except Exception:
347
+ tb = traceback.format_exc()
348
+ print(f"[PeVe] ✗ context load failed:\n{tb}")
349
+ context_model_status.update({"loaded": False, "error_message": tb})
350
+ return None, None
351
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
352
 
353
+ def _load_protein():
354
+ import xgboost as xgb
355
+ import torch
356
+ print(f"[PeVe] Loading protein model from {_REPO_PROTEIN}")
357
+
358
+ _FEAT = ["gnomAD_AF", "Grantham", "Charge_change",
359
+ "Hydrophobicity_diff", "Protein_pos_norm", "VEP_IMPACT"]
360
 
 
 
361
  try:
362
+ local = _download_repo(_REPO_PROTEIN)
363
+
364
+ # ── Try XGBoost formats first ──────────────────────────────────────
365
+ for ext in ["*.json", "*.ubj", "*.model"]:
366
+ for p in local.glob(ext):
367
+ try:
368
+ m = xgb.Booster()
369
+ m.load_model(str(p))
370
+ print(f"[PeVe] ✓ protein loaded as XGBoost Booster ({p.name})")
371
+ protein_model_status.update({"loaded": True, "error_message": None})
372
+ return m
373
+ except Exception as e:
374
+ print(f"[PeVe] xgb.Booster failed for {p.name}: {e}")
375
+
376
+ # ── Try pickle ────────────────────────────────────────────────────
377
+ for p in local.glob("*.pkl"):
378
+ try:
379
+ with open(p, "rb") as f:
380
+ m = pickle.load(f)
381
+ print(f"[PeVe] ✓ protein loaded via pickle ({p.name})")
382
+ protein_model_status.update({"loaded": True, "error_message": None})
383
+ return m
384
+ except Exception as e:
385
+ print(f"[PeVe] pickle failed for {p.name}: {e}")
386
+
387
+ # ── Fallback: PyTorch checkpoint — wrap as XGB-compatible ─────────
388
+ for ext in ["*.pt", "*.pth", "*.bin"]:
389
+ for p in local.glob(ext):
390
+ try:
391
+ ckpt = torch.load(str(p), map_location="cpu", weights_only=False)
392
+ sd = ckpt.get("model_state_dict", ckpt) if isinstance(ckpt, dict) else ckpt
393
+
394
+ if isinstance(sd, dict):
395
+ # Try MutationPredictorCNN (protein space model.py)
396
+ from torch import nn
397
+ class MutationPredictorCNN(nn.Module):
398
+ def __init__(self):
399
+ super().__init__()
400
+ self.conv1 = nn.Conv1d(11, 64, kernel_size=7, padding=3)
401
+ self.bn1 = nn.BatchNorm1d(64)
402
+ self.conv2 = nn.Conv1d(64, 128, kernel_size=5, padding=2)
403
+ self.bn2 = nn.BatchNorm1d(128)
404
+ self.conv3 = nn.Conv1d(128, 256, kernel_size=3, padding=1)
405
+ self.bn3 = nn.BatchNorm1d(256)
406
+ self.adaptive_pool = nn.AdaptiveAvgPool1d(1)
407
+ self.mut_fc = nn.Linear(12, 32)
408
+ self.fc1 = nn.Linear(288, 128)
409
+ self.fc2 = nn.Linear(128, 64)
410
+ self.fc3 = nn.Linear(64, 1)
411
+ self.importance_head = nn.Linear(256, 1)
412
+
413
+ def forward(self, x):
414
+ import torch.nn.functional as F
415
+ bs = x.size(0)
416
+ mut_type = x[:, 1089:1101]
417
+ x_seq = x[:, :1089].view(bs, 11, 99)
418
+ x_conv = F.relu(self.bn1(self.conv1(x_seq)))
419
+ x_conv = nn.MaxPool1d(2, 2)(x_conv)
420
+ x_conv = F.relu(self.bn2(self.conv2(x_conv)))
421
+ x_conv = nn.MaxPool1d(2, 2)(x_conv)
422
+ x_conv = F.relu(self.bn3(self.conv3(x_conv)))
423
+ x_conv = nn.MaxPool1d(2, 2)(x_conv)
424
+ x_conv = self.adaptive_pool(x_conv)
425
+ conv_feat = x_conv.view(bs, 256)
426
+ mut_feat = F.relu(self.mut_fc(mut_type))
427
+ combined = torch.cat([conv_feat, mut_feat], dim=1)
428
+ x_out = F.relu(self.fc1(combined))
429
+ x_out = F.relu(self.fc2(x_out))
430
+ cls = torch.sigmoid(self.fc3(x_out))
431
+ imp = torch.sigmoid(self.importance_head(conv_feat))
432
+ return cls, imp
433
+
434
+ torch_model = MutationPredictorCNN()
435
+ torch_model.load_state_dict(sd)
436
+ torch_model.eval()
437
+ wrapped = _CNNasXGB(torch_model, _FEAT)
438
+ print(f"[PeVe] ✓ protein loaded as CNN→XGB wrapper ({p.name})")
439
+ protein_model_status.update({"loaded": True, "error_message": None})
440
+ return wrapped
441
+ else:
442
+ # Raw nn.Module saved whole
443
+ wrapped = _CNNasXGB(sd, _FEAT)
444
+ protein_model_status.update({"loaded": True, "error_message": None})
445
+ return wrapped
446
+
447
+ except Exception as e:
448
+ print(f"[PeVe] torch fallback failed for {p.name}: {e}")
449
+
450
+ raise FileNotFoundError("No loadable model file found in protein repo")
451
+
452
  except Exception:
453
+ tb = traceback.format_exc()
454
+ print(f"[PeVe] ✗ protein load failed:\n{tb}")
455
+ protein_model_status.update({"loaded": False, "error_message": tb})
456
+ return None
457
+
458
+
459
+ # ══════════════════════════════════════════════════════════════════════════════
460
+ # Public API (names that app.py imports)
461
+ # ══════════════════════════════════════════════════════════════════════════════
462
+
463
+ def get_splice_model() -> tuple:
464
+ """Returns (model, tokenizer). model(tensor) → (logit, imp, r_imp, s_imp)"""
465
+ global _splice_model, _splice_tok
466
+ if _splice_model is None:
467
+ _splice_model, _splice_tok = _load_splice()
468
+ return _splice_model, _splice_tok
469
+
470
+
471
+ def get_context_model() -> tuple:
472
+ """Returns (model, tokenizer). model(tensor) → logit tensor"""
473
+ global _context_model, _context_tok
474
+ if _context_model is None:
475
+ _context_model, _context_tok = _load_context()
476
+ return _context_model, _context_tok
477
+
478
 
479
+ def get_protein_model():
480
+ """Returns XGBoost Booster (or CNN wrapper). model.predict(dmat) → float array"""
481
+ global _protein_model
482
+ if _protein_model is None:
483
+ _protein_model = _load_protein()
484
+ return _protein_model
485
 
 
486
 
487
  def get_model_status() -> dict:
 
488
  return {
489
+ "splice": dict(splice_model_status),
490
+ "context": dict(context_model_status),
491
+ "protein": dict(protein_model_status),
492
  }
493
 
494
 
495
+ # ══════════════════════════════════════════════════════════════════════════════
496
+ # Test block
497
+ # ══════════════════════════════════════════════════════════════════════════════
498
 
499
  def test_model_loading() -> dict:
500
+ import torch
 
 
 
501
  print("[PeVe] ── test_model_loading() ──")
502
 
503
+ sm, _ = get_splice_model()
504
+ cm, _ = get_context_model()
505
+ pm = get_protein_model()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
506
 
507
+ results = {}
 
508
 
509
+ # Test splice
510
+ try:
511
+ if sm is not None:
512
+ dummy = torch.zeros(1, 1106)
513
+ out = sm(dummy)
514
+ results["splice"] = f"✓ output shapes: {[o.shape for o in out]}"
515
+ else:
516
+ results["splice"] = "✗ model is None"
517
+ except Exception as e:
518
+ results["splice"] = f"✗ forward failed: {e}"
519
 
520
+ # Test context
521
+ try:
522
+ if cm is not None:
523
+ dummy = torch.zeros(1, 1106)
524
+ out = cm(dummy)
525
+ results["context"] = f"✓ output shape: {out.shape if hasattr(out,'shape') else type(out)}"
526
+ else:
527
+ results["context"] = "✗ model is None"
528
+ except Exception as e:
529
+ results["context"] = f"✗ forward failed: {e}"
530
+
531
+ # Test protein
532
+ try:
533
+ if pm is not None:
534
+ import xgboost as xgb
535
+ feat = ["gnomAD_AF","Grantham","Charge_change",
536
+ "Hydrophobicity_diff","Protein_pos_norm","VEP_IMPACT"]
537
+ X = np.array([[0.001, 100.0, 0.0, 0.5, 0.5, 2.0]], dtype=np.float32)
538
+ dmat = xgb.DMatrix(X, feature_names=feat)
539
+ pred = pm.predict(dmat)
540
+ results["protein"] = f"✓ prediction: {pred}"
541
+ else:
542
+ results["protein"] = "✗ model is None"
543
+ except Exception as e:
544
+ results["protein"] = f"✗ predict failed: {e}"
545
+
546
+ status = get_model_status()
547
+ final = {
548
+ "model_status": status,
549
+ "forward_tests": results,
550
+ "all_loaded": all(v["loaded"] for v in status.values()),
551
+ }
552
  import json
553
+ print(json.dumps(final, indent=2, default=str))
554
+ return final
555
+
556
+
557
+ if __name__ == "__main__":
558
+ test_model_loading()