YinkaiW's picture
Upload folder using huggingface_hub
db32e07 verified
Raw
History Blame Contribute Delete
11.1 kB
from __future__ import annotations
from dataclasses import dataclass
from typing import Iterable, List, Optional
import numpy as np
from tqdm import tqdm
from .io import chunked
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)
@dataclass
class SMILESEmbedder:
model_name: str
device: str = "cpu"
pooling: str = "cls" # "cls" or "mean"
batch_size: int = 64
max_length: int = 256
normalize: bool = True
def _load(self):
from transformers import AutoModel, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained(self.model_name)
# Use safetensors to avoid torch.load CVE (CVE-2025-32434) when torch < 2.6
try:
model = AutoModel.from_pretrained(self.model_name, use_safetensors=True)
except Exception as e:
raise RuntimeError(
"Loading ChemBERTa failed (transformers require torch>=2.6 or safetensors). "
"Upgrade with: pip install 'torch>=2.6', or ensure the model has .safetensors on the Hub."
) from e
import torch
if self.device == "cuda" and torch.cuda.device_count() > 1:
model = torch.nn.DataParallel(model, device_ids=list(range(torch.cuda.device_count())))
model.to(self.device)
model.eval()
return tokenizer, model
def encode(self, smiles: Iterable[str]) -> np.ndarray:
smiles_list = list(smiles)
if not smiles_list:
return np.zeros((0, 0), dtype=np.float32)
tokenizer, model = self._load()
outputs: List[np.ndarray] = []
import torch
n_batches = (len(smiles_list) + self.batch_size - 1) // self.batch_size
with torch.no_grad():
for _, batch in tqdm(
chunked(smiles_list, self.batch_size),
total=n_batches,
desc="Encoding SMILES",
unit="batch",
):
toks = tokenizer(
batch,
padding=True,
truncation=True,
max_length=self.max_length,
return_tensors="pt",
).to(self.device)
h = model(**toks).last_hidden_state
if self.pooling == "mean":
mask = toks["attention_mask"].unsqueeze(-1).float()
pooled = (h * mask).sum(dim=1) / mask.sum(dim=1).clamp(min=1.0)
else:
pooled = h[:, 0]
outputs.append(pooled.detach().cpu().numpy())
arr = np.concatenate(outputs, axis=0).astype(np.float32)
if self.normalize:
arr = l2_normalize(arr)
return arr
@dataclass
class SpectrumEmbedder:
specbridge_ckpt: str
dreams_ckpt: Optional[str] = None
d_out: int = 512
mapper_hidden: int = 512
n_blocks: int = 4
chemberta_model: str = "seyonec/ChemBERTa-zinc-base-v1"
device: str = "cpu"
normalize: bool = True
use_lightweight: bool = False
def _load(self):
import torch
from argparse import Namespace
from pathlib import PosixPath
from pathlib import Path
import sys
import types
specbridge_root = Path(__file__).resolve().parents[2] / "SpecBridge"
dreams_root = specbridge_root / "DreaMS"
for p in (specbridge_root, dreams_root):
if p.exists() and str(p) not in sys.path:
sys.path.insert(0, str(p))
try:
torch.serialization.add_safe_globals([Namespace, PosixPath])
except Exception:
pass
from specbridge.adapters.dreams_adapter import load_dreams_encoder
try:
state = torch.load(self.specbridge_ckpt, map_location="cpu", weights_only=False)
except TypeError:
state = torch.load(self.specbridge_ckpt, map_location="cpu")
model_state = state.get("model", state)
ckpt_args = state.get("args", {}) if isinstance(state, dict) else {}
d_out = self.d_out
mapper_hidden = self.mapper_hidden
n_blocks = self.n_blocks
chemberta_model = self.chemberta_model
spec_bins = 2048
if isinstance(ckpt_args, dict):
if ckpt_args.get("cond_dim") is not None:
d_out = int(ckpt_args["cond_dim"])
if ckpt_args.get("mapper_hidden") is not None:
mapper_hidden = int(ckpt_args["mapper_hidden"])
if ckpt_args.get("n_blocks") is not None:
n_blocks = int(ckpt_args["n_blocks"])
if ckpt_args.get("chemberta_model"):
chemberta_model = str(ckpt_args["chemberta_model"])
if ckpt_args.get("spec_bins") is not None:
spec_bins = int(ckpt_args["spec_bins"])
dreams_d_out = 1024
if isinstance(model_state, dict) and "spec.proj.0.0.weight" in model_state:
dreams_d_out = int(model_state["spec.proj.0.0.weight"].shape[1])
dreams = load_dreams_encoder(self.dreams_ckpt, d_in=spec_bins, d_out=dreams_d_out)
self._dreams_is_dummy = dreams.__class__.__name__ == "DummyDreams"
if self.use_lightweight:
if isinstance(model_state, dict):
if "spec.proj.0.0.weight" in model_state:
d_out = int(model_state["spec.proj.0.0.weight"].shape[0])
elif "mapB.W.weight" in model_state:
d_out = int(model_state["mapB.W.weight"].shape[1])
if "mapB.blocks.0.fc1.weight" in model_state:
mapper_hidden = int(model_state["mapB.blocks.0.fc1.weight"].shape[0])
block_ids = set()
for key in model_state.keys():
if key.startswith("mapB.blocks."):
parts = key.split(".")
if len(parts) > 2 and parts[2].isdigit():
block_ids.add(int(parts[2]))
if block_ids:
n_blocks = max(block_ids) + 1
from transformers import AutoConfig
from specbridge.adapters.dreams_adapter import DreamsAdapter
from specbridge.models.mapper import ProcrustesResidualMapper
hid = int(AutoConfig.from_pretrained(chemberta_model).hidden_size)
spec = DreamsAdapter(
dreams_encoder=dreams,
d_out=d_out,
hidden=mapper_hidden,
freeze_backbone=True,
)
mapB = ProcrustesResidualMapper(
d_in=d_out,
d_out=hid,
n_blocks=n_blocks,
hidden=mapper_hidden,
gaussian=True,
random_init=False,
)
class _LightSpecBridge(torch.nn.Module):
def __init__(self, spec, mapB):
super().__init__()
self.spec = spec
self.mapB = mapB
model = _LightSpecBridge(spec, mapB)
model._dreams_is_dummy = self._dreams_is_dummy
model.load_state_dict(model_state, strict=False)
model.to(self.device)
model.eval()
return model
from specbridge.models.mapper import DreamsToMolCondition
model = DreamsToMolCondition(
dreams_encoder=dreams,
d_out=d_out,
mapper_hidden=mapper_hidden,
gaussian=True,
mol_space="chemberta",
chemberta_model=chemberta_model,
args=type("Args", (), {"n_blocks": n_blocks, "random_mapper_init": False})(),
freeze_backbone=True,
)
model.load_state_dict(model_state, strict=False)
model._dreams_is_dummy = self._dreams_is_dummy
model.to(self.device)
model.eval()
return model
def encode(self, spectra_binned, meta: dict, batch_size: int | None = None) -> np.ndarray:
import torch
model = self._load()
if not isinstance(spectra_binned, torch.Tensor):
spectra_binned = torch.tensor(spectra_binned, dtype=torch.float32)
total = spectra_binned.shape[0]
if batch_size is None or batch_size <= 0:
batch_size = total
outputs = []
use_peaks = not getattr(model, "_dreams_is_dummy", False)
with torch.no_grad():
for start in tqdm(range(0, total, batch_size)):
end = min(total, start + batch_size)
batch = spectra_binned[start:end].to(self.device)
batch_meta = meta
if isinstance(meta, dict):
batch_meta = {}
for k, v in meta.items():
if k == "peaks" and not use_peaks:
continue
if isinstance(v, torch.Tensor) and v.shape[0] == total:
batch_meta[k] = v[start:end].to(self.device)
else:
batch_meta[k] = v
z_s = model.spec(batch, batch_meta)
mu_s, _ = model.mapB(z_s)
outputs.append(mu_s.detach().cpu().numpy().astype(np.float32))
emb = np.concatenate(outputs, axis=0) if outputs else np.zeros((0, 0), dtype=np.float32)
if self.normalize:
emb = l2_normalize(emb)
return emb
def encode_spec_only(
self, spectra_binned, meta: dict, batch_size: int | None = None
) -> np.ndarray:
"""Return E_mist(spec): spectrum embedding before mapper (d_spec), for mapper training."""
import torch
model = self._load()
if not isinstance(spectra_binned, torch.Tensor):
spectra_binned = torch.tensor(spectra_binned, dtype=torch.float32)
total = spectra_binned.shape[0]
if batch_size is None or batch_size <= 0:
batch_size = total
outputs = []
use_peaks = not getattr(model, "_dreams_is_dummy", False)
with torch.no_grad():
for start in range(0, total, batch_size):
end = min(total, start + batch_size)
batch = spectra_binned[start:end].to(self.device)
batch_meta = meta
if isinstance(meta, dict):
batch_meta = {}
for k, v in meta.items():
if k == "peaks" and not use_peaks:
continue
if isinstance(v, torch.Tensor) and v.shape[0] == total:
batch_meta[k] = v[start:end].to(self.device)
else:
batch_meta[k] = v
z_s = model.spec(batch, batch_meta)
outputs.append(z_s.detach().cpu().numpy().astype(np.float32))
return (
np.concatenate(outputs, axis=0)
if outputs
else np.zeros((0, 0), dtype=np.float32)
)