| """ |
| 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 |
| |
| 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 |
|
|