AI4deeperScience commited on
Commit
5b6aa09
·
verified ·
1 Parent(s): afce61c

Lazy-load model and heavy deps to avoid build-time installs

Browse files
Files changed (1) hide show
  1. app.py +51 -25
app.py CHANGED
@@ -13,7 +13,6 @@ import warnings
13
  from pathlib import Path
14
 
15
  import numpy as np
16
- import torch
17
  import yaml
18
  import matplotlib
19
  matplotlib.use('Agg')
@@ -34,32 +33,49 @@ except ImportError as _pyg_err:
34
  PYGEOMETRIC_AVAILABLE = False
35
  _pyg_err_msg = str(_pyg_err)
36
 
37
- from src.models.biointeract import BioInteract
38
- from src.data.mol_graph import smiles_to_graph
39
  from src.data.protein_feat import residue_physicochemical_features, residue_domain_labels
40
 
41
- # ============================================================
42
- # Global model loading
43
- # ============================================================
44
-
45
- DEVICE = torch.device('cpu')
46
  _CONFIG_PATH = ROOT / 'configs' / 'default.yaml'
47
  _CKPT_PATH = ROOT / 'checkpoints' / 'best.pt'
48
  _REPORT_PATH = ROOT / 'examples' / 'interpretability_report.json'
49
 
50
- print("[BioInteract] Loading model config …")
51
- with open(_CONFIG_PATH) as f:
52
- _CONFIG = yaml.safe_load(f)
53
-
54
- print("[BioInteract] Loading pretrained weights …")
55
- _model = BioInteract(_CONFIG['model']).to(DEVICE)
56
- _ckpt = torch.load(_CKPT_PATH, map_location='cpu', weights_only=False)
57
- _model.load_state_dict(_ckpt['model_state_dict'])
58
- _model.eval()
59
- print(f"[BioInteract] Model ready — epoch {_ckpt.get('epoch','?')}, "
60
- f"params = {sum(p.numel() for p in _model.parameters()):,}")
61
 
62
- # Load pre-computed case study report
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  with open(_REPORT_PATH) as f:
64
  _REPORT = json.load(f)
65
 
@@ -84,6 +100,7 @@ def _get_esm():
84
 
85
  def compute_esm2_embedding(sequence: str, max_len: int = 512) -> torch.Tensor:
86
  """Run ESM-2 and return per-residue embeddings (L, 640)."""
 
87
  seq = sequence[:max_len]
88
  tokenizer, esm = _get_esm()
89
  inputs = tokenizer(seq, return_tensors='pt', add_special_tokens=True)
@@ -299,6 +316,11 @@ def run_prediction(smiles: str, sequence: str, progress=gr.Progress()):
299
  if not sequence:
300
  return "Please enter a protein sequence (amino acids).", "", None, None
301
 
 
 
 
 
 
302
  if not PYGEOMETRIC_AVAILABLE:
303
  return (
304
  f"torch-geometric is not available in this environment: {_pyg_err_msg}. "
@@ -308,11 +330,15 @@ def run_prediction(smiles: str, sequence: str, progress=gr.Progress()):
308
 
309
  # --- Drug graph ---
310
  progress(0.1, desc="Parsing SMILES …")
 
 
311
  drug_graph = smiles_to_graph(smiles)
312
  if drug_graph is None:
313
  return "Invalid SMILES string — RDKit could not parse it.", "", None, None
314
 
315
- drug_batch = PyGBatch.from_data_list([drug_graph]).to(DEVICE)
 
 
316
 
317
  # --- Protein features ---
318
  seq = sequence[:MAX_SEQ_LEN]
@@ -326,10 +352,10 @@ def run_prediction(smiles: str, sequence: str, progress=gr.Progress()):
326
  except Exception as e:
327
  return f"ESM-2 error: {e}", "", None, None
328
 
329
- esm2_emb = esm2_emb.unsqueeze(0).to(DEVICE) # (1, L, 640)
330
- physchem = residue_physicochemical_features(seq).unsqueeze(0).to(DEVICE) # (1, L, 4)
331
- domain = residue_domain_labels(L).unsqueeze(0).to(DEVICE) # (1, L)
332
- prot_mask = torch.ones(1, L, dtype=torch.bool, device=DEVICE)
333
 
334
  # --- Model forward ---
335
  progress(0.85, desc="Running BioInteract model …")
 
13
  from pathlib import Path
14
 
15
  import numpy as np
 
16
  import yaml
17
  import matplotlib
18
  matplotlib.use('Agg')
 
33
  PYGEOMETRIC_AVAILABLE = False
34
  _pyg_err_msg = str(_pyg_err)
35
 
36
+ # protein features are pure-python and safe to import eagerly
 
37
  from src.data.protein_feat import residue_physicochemical_features, residue_domain_labels
38
 
39
+ # Model and heavy-dependency lazy loader
40
+ _model = None
41
+ _DEVICE = None
 
 
42
  _CONFIG_PATH = ROOT / 'configs' / 'default.yaml'
43
  _CKPT_PATH = ROOT / 'checkpoints' / 'best.pt'
44
  _REPORT_PATH = ROOT / 'examples' / 'interpretability_report.json'
45
 
46
+ def _load_model():
47
+ """Lazy-load the PyTorch model and return a ready-to-use instance.
48
+ This delays importing heavy packages (torch, torch_geometric, rdkit)
49
+ until a user requests a custom prediction.
50
+ """
51
+ global _model, _DEVICE
52
+ if _model is not None:
53
+ return _model
 
 
 
54
 
55
+ try:
56
+ import torch
57
+ except Exception as e:
58
+ raise RuntimeError(f"PyTorch not available: {e}")
59
+
60
+ # Import model code only when torch is available
61
+ from src.models.biointeract import BioInteract
62
+
63
+ print("[BioInteract] Loading model config …")
64
+ with open(_CONFIG_PATH) as f:
65
+ cfg = yaml.safe_load(f)
66
+
67
+ print("[BioInteract] Loading pretrained weights …")
68
+ device = torch.device('cpu')
69
+ model = BioInteract(cfg['model']).to(device)
70
+ ckpt = torch.load(_CKPT_PATH, map_location='cpu', weights_only=False)
71
+ model.load_state_dict(ckpt['model_state_dict'])
72
+ model.eval()
73
+ _model = model
74
+ _DEVICE = device
75
+ print(f"[BioInteract] Model ready — epoch {ckpt.get('epoch','?')}, params = {sum(p.numel() for p in _model.parameters()):,}")
76
+ return _model
77
+
78
+ # Load pre-computed case study report (safe, JSON-only)
79
  with open(_REPORT_PATH) as f:
80
  _REPORT = json.load(f)
81
 
 
100
 
101
  def compute_esm2_embedding(sequence: str, max_len: int = 512) -> torch.Tensor:
102
  """Run ESM-2 and return per-residue embeddings (L, 640)."""
103
+ import torch
104
  seq = sequence[:max_len]
105
  tokenizer, esm = _get_esm()
106
  inputs = tokenizer(seq, return_tensors='pt', add_special_tokens=True)
 
316
  if not sequence:
317
  return "Please enter a protein sequence (amino acids).", "", None, None
318
 
319
+ try:
320
+ _load_model()
321
+ except Exception as e:
322
+ return (f"Model not available: {e}", "", None, None)
323
+
324
  if not PYGEOMETRIC_AVAILABLE:
325
  return (
326
  f"torch-geometric is not available in this environment: {_pyg_err_msg}. "
 
330
 
331
  # --- Drug graph ---
332
  progress(0.1, desc="Parsing SMILES …")
333
+ # import heavy SMILES->graph conversion lazily
334
+ from src.data.mol_graph import smiles_to_graph
335
  drug_graph = smiles_to_graph(smiles)
336
  if drug_graph is None:
337
  return "Invalid SMILES string — RDKit could not parse it.", "", None, None
338
 
339
+ import torch
340
+ device = _DEVICE
341
+ drug_batch = PyGBatch.from_data_list([drug_graph]).to(device)
342
 
343
  # --- Protein features ---
344
  seq = sequence[:MAX_SEQ_LEN]
 
352
  except Exception as e:
353
  return f"ESM-2 error: {e}", "", None, None
354
 
355
+ esm2_emb = esm2_emb.unsqueeze(0).to(device) # (1, L, 640)
356
+ physchem = residue_physicochemical_features(seq).unsqueeze(0).to(device) # (1, L, 4)
357
+ domain = residue_domain_labels(L).unsqueeze(0).to(device) # (1, L)
358
+ prot_mask = torch.ones(1, L, dtype=torch.bool, device=device)
359
 
360
  # --- Model forward ---
361
  progress(0.85, desc="Running BioInteract model …")