pubchem-faiss-library / code /spec_rag /flare_encoder.py
YinkaiW's picture
Upload folder using huggingface_hub
db32e07 verified
Raw
History Blame Contribute Delete
8.91 kB
from __future__ import annotations
import ctypes
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable, List
import numpy as np
from numpy.lib.format import open_memmap
from tqdm import tqdm
from .embeddings import l2_normalize
@dataclass
class FLAREMolEmbedder:
flare_repo: str
hparams_pth: str
checkpoint_pth: str
device: str = "cpu"
batch_size: int = 256
normalize: bool = True
def _load(self):
libstdcpp = Path(sys.executable).resolve().parent.parent / "lib" / "libstdc++.so.6"
if libstdcpp.exists():
ctypes.CDLL(str(libstdcpp), mode=ctypes.RTLD_GLOBAL)
import dgl
import torch
import yaml
flare_repo = Path(self.flare_repo).resolve()
if str(flare_repo) not in sys.path:
sys.path.insert(0, str(flare_repo))
from flare.data.transforms import MolToGraph
from flare.utils.models import get_model
with open(self.hparams_pth) as f:
params = yaml.load(f, Loader=yaml.FullLoader)
params["checkpoint_pth"] = str(self.checkpoint_pth)
params["df_test_path"] = ""
params["accelerator"] = "cpu"
params["devices"] = 1
device = self.device
if device == "cuda":
if not torch.cuda.is_available():
device = "cpu"
else:
try:
dgl.graph(([0], [0])).to("cuda")
except Exception:
device = "cpu"
model = get_model(params["model"], params)
model = model.to(device)
model.eval()
mol_transform = MolToGraph(
atom_feature=params["atom_feature"],
bond_feature=params["bond_feature"],
element_list=params["element_list"],
)
return model.mol_enc_model, mol_transform, device
def encode(self, smiles: Iterable[str]) -> np.ndarray:
import dgl
import torch
smiles_list = list(smiles)
if not smiles_list:
return np.zeros((0, 0), dtype=np.float32)
mol_encoder, mol_transform, device = self._load()
outputs: List[np.ndarray] = []
total_batches = (len(smiles_list) + self.batch_size - 1) // self.batch_size
with torch.no_grad():
for start in tqdm(range(0, len(smiles_list), self.batch_size), total=total_batches, desc="Encoding FLARE", unit="batch"):
batch_smiles = smiles_list[start:start + self.batch_size]
graphs = [mol_transform(smi) for smi in batch_smiles]
batched = dgl.batch(graphs)
if device != "cpu":
batched = batched.to(device)
node_embeddings = mol_encoder(batched)
pooled = mol_encoder.pool(batched, node_embeddings)
outputs.append(pooled.detach().cpu().numpy().astype(np.float32))
arr = np.concatenate(outputs, axis=0).astype(np.float32)
if self.normalize:
arr = l2_normalize(arr)
return arr
def encode_to_npy(self, smiles: Iterable[str], out_path: str | Path) -> Path:
import dgl
import torch
smiles_list = list(smiles)
out_path = Path(out_path)
if not smiles_list:
np.save(out_path, np.zeros((0, 0), dtype=np.float32))
return out_path
mol_encoder, mol_transform, device = self._load()
total_batches = (len(smiles_list) + self.batch_size - 1) // self.batch_size
mm = None
offset = 0
with torch.no_grad():
for start in tqdm(range(0, len(smiles_list), self.batch_size), total=total_batches, desc="Encoding FLARE", unit="batch"):
batch_smiles = smiles_list[start:start + self.batch_size]
graphs = [mol_transform(smi) for smi in batch_smiles]
batched = dgl.batch(graphs)
if device != "cpu":
batched = batched.to(device)
node_embeddings = mol_encoder(batched)
pooled = mol_encoder.pool(batched, node_embeddings)
chunk = pooled.detach().cpu().numpy().astype(np.float32)
if mm is None:
mm = open_memmap(out_path, mode="w+", dtype=np.float32, shape=(len(smiles_list), chunk.shape[1]))
mm[offset:offset + chunk.shape[0]] = chunk
offset += chunk.shape[0]
if mm is None:
np.save(out_path, np.zeros((0, 0), dtype=np.float32))
return out_path
del mm
if self.normalize:
arr = np.load(out_path, mmap_mode="r+")
norms = np.linalg.norm(arr, axis=1, keepdims=True)
arr[:] = arr[:] / np.clip(norms, 1e-8, None)
del arr
return out_path
@dataclass
class FLARESpecEmbedder:
flare_repo: str
hparams_pth: str
checkpoint_pth: str
dataset_pth: str
subformula_dir_pth: str
fold: str = "test"
device: str = "cpu"
batch_size: int = 128
normalize: bool = True
def _load(self):
libstdcpp = Path(sys.executable).resolve().parent.parent / "lib" / "libstdc++.so.6"
if libstdcpp.exists():
ctypes.CDLL(str(libstdcpp), mode=ctypes.RTLD_GLOBAL)
import dgl
import torch
import yaml
flare_repo = Path(self.flare_repo).resolve()
if str(flare_repo) not in sys.path:
sys.path.insert(0, str(flare_repo))
from massspecgym.models.base import Stage
from flare.data.datasets import MassSpecDataset_PeakFormulas
from flare.utils.data import get_spec_featurizer
from flare.utils.models import get_model
with open(self.hparams_pth) as f:
params = yaml.load(f, Loader=yaml.FullLoader)
params["checkpoint_pth"] = str(self.checkpoint_pth)
params["df_test_path"] = ""
params["accelerator"] = "cpu"
params["devices"] = 1
device = self.device
if device == "cuda":
if not torch.cuda.is_available():
device = "cpu"
else:
try:
dgl.graph(([0], [0])).to("cuda")
except Exception:
device = "cpu"
model = get_model(params["model"], params)
model = model.to(device)
model.eval()
spec_transform = get_spec_featurizer(params["spectra_view"], params)
dataset = MassSpecDataset_PeakFormulas(
spectra_view=params["spectra_view"],
spec_transform=spec_transform,
mol_transform=None,
pth=self.dataset_pth,
subformula_dir_pth=self.subformula_dir_pth,
formula_source=params.get("formula_source", "default"),
return_mol_freq=False,
return_identifier=True,
stage=Stage.TEST,
)
return model.spec_enc_model, params["spectra_view"], dataset, device
def encode(self):
import torch
spec_encoder, spectra_view, dataset, device = self._load()
metadata = dataset.metadata
if "fold" in metadata.columns and self.fold:
metadata = metadata[metadata["fold"].astype(str) == str(self.fold)]
indices = metadata.index.to_list()
if not indices:
return np.zeros((0, 0), dtype=np.float32), [], []
outputs: List[np.ndarray] = []
out_smiles: List[str] = []
out_ids: List[str] = []
with torch.no_grad():
for start in tqdm(range(0, len(indices), self.batch_size), desc="Encoding FLARE spectra", unit="batch"):
batch_idx = indices[start:start + self.batch_size]
specs = []
n_peaks = []
for idx in batch_idx:
item = dataset.__getitem__(idx, transform_mol=False)
spec = item[spectra_view]
specs.append(spec)
n_peaks.append(int(spec.shape[0]))
row = dataset.metadata.loc[idx]
out_smiles.append(str(row["smiles"]))
out_ids.append(str(row["identifier"]))
batch = torch.nn.utils.rnn.pad_sequence(specs, batch_first=True, padding_value=-5)
batch = batch.to(device)
enc = spec_encoder(batch, n_peaks)
if enc.ndim == 3:
mask = (batch != -5).any(dim=-1).float()
pooled = (enc * mask.unsqueeze(-1)).sum(dim=1) / mask.sum(dim=1, keepdim=True).clamp(min=1.0)
else:
pooled = enc
outputs.append(pooled.detach().cpu().numpy().astype(np.float32))
arr = np.concatenate(outputs, axis=0).astype(np.float32)
if self.normalize:
arr = l2_normalize(arr)
return arr, out_smiles, out_ids