Upload esm3bedding.py with huggingface_hub
Browse files- esm3bedding.py +86 -0
esm3bedding.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# esm3bedding.py
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import torch
|
| 5 |
+
from esm.models.esmc import ESMC
|
| 6 |
+
from esm.sdk.api import ESMProtein, LogitsConfig
|
| 7 |
+
from huggingface_hub import login
|
| 8 |
+
from utils import get_logger
|
| 9 |
+
from base import Featurizer
|
| 10 |
+
|
| 11 |
+
logg = get_logger()
|
| 12 |
+
|
| 13 |
+
class ESM3Featurizer(Featurizer):
|
| 14 |
+
def __init__(self, save_dir: str, api_key: str, per_tok: bool = True):
|
| 15 |
+
super().__init__("ESM3", 1152, save_dir=save_dir)
|
| 16 |
+
self.per_tok = per_tok
|
| 17 |
+
self._device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 18 |
+
self.client = None
|
| 19 |
+
|
| 20 |
+
self._login(api_key)
|
| 21 |
+
self._initialize_model()
|
| 22 |
+
|
| 23 |
+
def _login(self, api_key: str):
|
| 24 |
+
try:
|
| 25 |
+
login(api_key)
|
| 26 |
+
logg.info("Successfully logged into Hugging Face Hub.")
|
| 27 |
+
except Exception as e:
|
| 28 |
+
logg.error(f"Failed to log in to Hugging Face Hub: {e}")
|
| 29 |
+
raise RuntimeError("Hugging Face login failed. Check your API key.")
|
| 30 |
+
|
| 31 |
+
def _initialize_model(self):
|
| 32 |
+
try:
|
| 33 |
+
logg.info("Initializing ESMC model (esmc_600m)...")
|
| 34 |
+
|
| 35 |
+
# First try normal online loading
|
| 36 |
+
try:
|
| 37 |
+
self.client = ESMC.from_pretrained("esmc_600m")
|
| 38 |
+
self.client.to(self._device)
|
| 39 |
+
logg.info("ESMC model loaded.")
|
| 40 |
+
return
|
| 41 |
+
except Exception as online_error:
|
| 42 |
+
logg.warning(f"Online model loading failed: {online_error}")
|
| 43 |
+
logg.info("Attempting offline mode (using local cache)...")
|
| 44 |
+
|
| 45 |
+
# Fallback: Try offline mode using cached files
|
| 46 |
+
import os
|
| 47 |
+
os.environ["HF_HUB_OFFLINE"] = "1"
|
| 48 |
+
os.environ["TRANSFORMERS_OFFLINE"] = "1"
|
| 49 |
+
|
| 50 |
+
try:
|
| 51 |
+
self.client = ESMC.from_pretrained("esmc_600m", local_files_only=True)
|
| 52 |
+
self.client.to(self._device)
|
| 53 |
+
logg.info("ESMC model loaded from local cache (offline mode).")
|
| 54 |
+
except Exception as offline_error:
|
| 55 |
+
logg.error(f"Offline loading also failed: {offline_error}")
|
| 56 |
+
logg.error("="*60)
|
| 57 |
+
logg.error("ESMC MODEL NOT FOUND IN CACHE!")
|
| 58 |
+
logg.error("Run this on a node with internet access to cache the model:")
|
| 59 |
+
logg.error(" python -c \"from esm.models.esmc import ESMC; ESMC.from_pretrained('esmc_600m')\"")
|
| 60 |
+
logg.error("="*60)
|
| 61 |
+
raise RuntimeError("ESMC model not available. See error messages above.")
|
| 62 |
+
|
| 63 |
+
except Exception as e:
|
| 64 |
+
logg.error(f"Failed to load ESMC model: {e}")
|
| 65 |
+
raise RuntimeError("ESMC model initialization failed.")
|
| 66 |
+
|
| 67 |
+
def _transform(self, sequence: str) -> torch.Tensor:
|
| 68 |
+
try:
|
| 69 |
+
# REPLACE (not remove) invalid chars to preserve sequence length
|
| 70 |
+
valid_aa = set('ACDEFGHIKLMNPQRSTVWY')
|
| 71 |
+
clean_sequence = ''.join(c if c in valid_aa else 'A' for c in sequence.upper())
|
| 72 |
+
|
| 73 |
+
protein = ESMProtein(sequence=clean_sequence)
|
| 74 |
+
protein_tensor = self.client.encode(protein)
|
| 75 |
+
logits_config = LogitsConfig(sequence=True, return_embeddings=True)
|
| 76 |
+
output = self.client.logits(protein_tensor, logits_config)
|
| 77 |
+
embeddings = output.embeddings # shape => [1, L, D] or [L, D]
|
| 78 |
+
if embeddings.dim() == 3 and embeddings.shape[0] == 1:
|
| 79 |
+
embeddings = embeddings.squeeze(0) # => [L, D]
|
| 80 |
+
|
| 81 |
+
if not self.per_tok:
|
| 82 |
+
embeddings = embeddings.mean(dim=0) # => [D]
|
| 83 |
+
return embeddings
|
| 84 |
+
except Exception as e:
|
| 85 |
+
logg.error(f"Error generating embeddings for sequence: {e}")
|
| 86 |
+
return None
|