File size: 2,807 Bytes
db32e07 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | """
Optional SMI-TED encoder for molecule embeddings (E_smi).
Uses De-SpecBridge's load_smited when DESPECBRIDGE_PATH is set or --despecbridge-path is given.
"""
from __future__ import annotations
import os
import sys
from pathlib import Path
from typing import List, Optional
import numpy as np
def _l2_normalize(x: np.ndarray, eps: float = 1e-8) -> np.ndarray:
norm = np.linalg.norm(x, axis=-1, keepdims=True)
return (x / (norm + eps)).astype(np.float32)
def load_smited_encoder(
despecbridge_path: Optional[str] = None,
model_name: str = "ibm-research/materials.smi-ted",
device: Optional[str] = None,
):
"""
Load SMI-TED encoder. If despecbridge_path is set, prepend to sys.path and import
load_smited from despecbridge.models.smited_decoder.
Returns a callable encode(smiles_list) -> np.ndarray (normalized), or None if unavailable.
"""
path = despecbridge_path or os.environ.get("DESPECBRIDGE_PATH")
if path:
path = str(Path(path).resolve())
if path not in sys.path:
sys.path.insert(0, path)
try:
from despecbridge.models.smited_decoder import load_smited
except ImportError:
return None
import torch
dev = device or ("cuda" if torch.cuda.is_available() else "cpu")
wrapper = load_smited(model_name=model_name, device=torch.device(dev))
wrapper.eval()
def encode(smiles: List[str], batch_size: int = 32, desc: Optional[str] = None) -> np.ndarray:
from tqdm import tqdm
out = []
n_batches = (len(smiles) + batch_size - 1) // batch_size
it = range(0, len(smiles), batch_size)
if desc:
it = tqdm(it, total=n_batches, desc=desc, unit="batch")
for i in it:
batch = smiles[i : i + batch_size]
if not batch:
continue
# Use encode_mean_pool for [B, D] tensor; .encode() returns a dict.
if hasattr(wrapper, "encode_mean_pool"):
with torch.no_grad():
h = wrapper.encode_mean_pool(batch)
else:
with torch.no_grad():
raw = wrapper.encode(batch)
h = raw["last_hidden_state"] if isinstance(raw, dict) else raw
if h.dim() == 3:
h = h.mean(dim=1)
if isinstance(h, torch.Tensor):
h = h.cpu().numpy()
h = np.asarray(h, dtype=np.float32)
if h.ndim == 0:
h = np.expand_dims(np.expand_dims(h, 0), 0)
elif h.ndim == 1:
h = h.reshape(1, -1)
out.append(h)
if not out:
return np.zeros((0, 0), dtype=np.float32)
arr = np.concatenate(out, axis=0).astype(np.float32)
return arr
return encode
|