pubchem-faiss-library / code /scripts /sanity_check_true_index_mapped_query.py
YinkaiW's picture
Upload folder using huggingface_hub
db32e07 verified
Raw
History Blame Contribute Delete
20.9 kB
#!/usr/bin/env python
"""
Sanity check: Index = TRUE molecule embeddings (ChemBERTa/SMI-TED of test SMILES).
Query = MAPPED embeddings (spectrum → mapper → q_chem / q_smi).
We build an index from true mol embeddings, then query with spectrum→mapper
embeddings. Report Recall@1/10/50 over the FULL test set (each query ranked
against all N molecules).
Note: SpecBridge eval uses a per-query candidate set from cand_dict (e.g.
cand_dict_large_form.pkl) where candidates have the SAME FORMULA as the true
molecule (isomers). So the task is "pick the right isomer" among similar
molecules. This script ranks each query against the whole test set (arbitrary
molecules), which is a much harder setting. Low R@1 here does not contradict
SpecBridge ~70% R@1 over same-formula candidates.
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
import numpy as np
import torch
from spec_rag.embeddings import SpectrumEmbedder
from spec_rag.faiss_index import build_hnsw_index, index_search
def _tanimoto_smiles(smi_a: str, smi_b: str, radius: int = 2, n_bits: int = 2048):
"""Morgan fingerprint Tanimoto between two SMILES. Returns None if RDKit missing or invalid mol."""
try:
from rdkit import Chem
from rdkit.Chem import DataStructs
from rdkit.Chem.AllChem import GetMorganFingerprintAsBitVect
except ImportError:
return None
if not smi_a or not smi_b:
return None
mol_a = Chem.MolFromSmiles(str(smi_a).strip())
mol_b = Chem.MolFromSmiles(str(smi_b).strip())
if mol_a is None or mol_b is None:
return None
fp_a = GetMorganFingerprintAsBitVect(mol_a, radius, nBits=n_bits)
fp_b = GetMorganFingerprintAsBitVect(mol_b, radius, nBits=n_bits)
return DataStructs.TanimotoSimilarity(fp_a, fp_b)
def _tanimoto_at_k(indices_2d: np.ndarray, smiles_list: list, k: int, at_1: bool = True):
"""For each query i: Tanimoto(gt_i, retrieved at rank 1 or max over top-k). Returns (mean, median, count)."""
n = indices_2d.shape[0]
vals = []
for i in range(n):
gt = smiles_list[i]
if at_1:
j = int(indices_2d[i, 0])
t = _tanimoto_smiles(gt, smiles_list[j])
else:
best = None
for pos in range(min(k, indices_2d.shape[1])):
j = int(indices_2d[i, pos])
t = _tanimoto_smiles(gt, smiles_list[j])
if t is not None and (best is None or t > best):
best = t
t = best
if t is not None:
vals.append(t)
if not vals:
return None, None, 0
return float(np.mean(vals)), float(np.median(vals)), len(vals)
def _bin_peaks(mz, intensity, num_bins: int, max_mz: float):
if not isinstance(mz, torch.Tensor):
mz = torch.tensor(mz, dtype=torch.float32)
if not isinstance(intensity, torch.Tensor):
intensity = torch.tensor(intensity, dtype=torch.float32)
bins = torch.zeros(num_bins, dtype=torch.float32)
if mz.numel() == 0:
return bins.numpy()
idx = torch.clamp((mz / max_mz) * num_bins, min=0, max=num_bins - 1e-6).long()
idx = torch.clamp(idx, max=num_bins - 1)
bins.index_add_(0, idx, intensity)
return bins.numpy()
def load_mgf_spectra(mgf_path: str, spec_bins: int = 2048, max_mz: float = 2000.0, max_peaks: int = 60):
"""Load MGF; keep peaks in original MGF order (no sort) to match SpecBridge MassSpecGymDataset + collate."""
try:
from pyteomics import mgf
except ImportError:
raise ImportError("pyteomics required")
out = []
with mgf.MGF(mgf_path) as reader:
for spec in reader:
params = spec.get("params", {})
smi_gt = (params.get("SMILES") or params.get("smiles") or "").strip()
mz = spec.get("m/z array", [])
inten = spec.get("intensity array", [])
if len(mz) == 0 or len(inten) == 0:
continue
binned = _bin_peaks(mz, inten, num_bins=spec_bins, max_mz=max_mz)
# Keep original MGF order (no sort) so DreaMS/DreamsAdapter gets same input as SpecBridge eval
peaks = [[float(m), float(i)] for m, i in zip(mz, inten)]
out.append({"binned": binned, "peaks": peaks, "smiles_gt": smi_gt})
return out
def build_meta_peaks(records, max_peaks: int = 0):
"""Build meta['peaks'] [N, max_len, 2] matching SpecBridge pad_sequence(peaks_list, batch_first=True, padding_value=0.0)."""
if not records or "peaks" not in records[0]:
return {}
peaks_list = [r["peaks"] for r in records]
max_len = max(len(p) for p in peaks_list)
arr = np.zeros((len(peaks_list), max_len, 2), dtype=np.float32)
for i, p in enumerate(peaks_list):
for j, pair in enumerate(p):
arr[i, j, 0] = pair[0]
arr[i, j, 1] = pair[1]
return {"peaks": torch.tensor(arr)}
def parse_args():
p = argparse.ArgumentParser(
description="Index = true mol embeddings, Query = mapped (spectrum→mapper) embeddings; report Recall@1/10/50"
)
p.add_argument("--mgf-path", required=True, help="Test MGF (spectra + smiles_gt in params)")
p.add_argument("--specbridge-ckpt", required=True)
p.add_argument("--dreams-ckpt", default=None)
p.add_argument("--smited-mapper-ckpt", default=None, help="De-SpecBridge SMI-TED mapper")
p.add_argument("--despecbridge-path", default=None)
p.add_argument("--mapper-dir", default=None, help="Spec-RAG mappers.pt (for SMI-TED when not using smited-mapper-ckpt)")
p.add_argument("--chemberta-model", default="Derify/ChemBERTa_augmented_pubchem_13m")
p.add_argument("--spec-bins", type=int, default=2048)
p.add_argument("--max-mz", type=float, default=2000.0)
p.add_argument("--max-peaks", type=int, default=60)
p.add_argument("--batch-size", type=int, default=32)
p.add_argument("--device", default="cuda")
p.add_argument("--limit", type=int, default=None)
p.add_argument("--K", type=int, default=50, help="Retrieve top-K for Recall@10/50")
p.add_argument("--report", default=None)
p.add_argument("--use-specbridge-dataset", action="store_true", help="Load data via SpecBridge MassSpecGymDataset+collate (exact same input as SpecBridge eval)")
return p.parse_args()
def main():
args = parse_args()
if args.device == "cuda" and not torch.cuda.is_available():
args.device = "cpu"
device = torch.device(args.device)
K = max(args.K, 50)
if getattr(args, "use_specbridge_dataset", False):
# Load via SpecBridge dataset + collate so input is byte-identical to SpecBridge eval
specbridge_root = Path(__file__).resolve().parents[2] / "SpecBridge" # sibling of Spec-RAG
if not specbridge_root.exists():
specbridge_root = Path("/cluster/tufts/liulab/yiwan01/SpecBridge")
if str(specbridge_root) not in sys.path:
sys.path.insert(0, str(specbridge_root))
from specbridge.data.massspecgym import MassSpecGymDataset, collate_massspecgym
ds = MassSpecGymDataset(args.mgf_path)
n = len(ds)
if args.limit:
n = min(n, args.limit)
formula_vocab = max(2, getattr(ds, "_formula_vocab", 0) or 32)
adduct_vocab = max(2, getattr(ds, "_adduct_vocab", 0) or 16)
charge_vocab = max(2, getattr(ds, "_charge_vocab", 0) or 8)
collate_fn = lambda b: collate_massspecgym(b, args.spec_bins, formula_vocab, adduct_vocab, charge_vocab, 2048)
batch = collate_fn([ds[i] for i in range(n)])
spectra_binned = batch["spectra"].numpy().astype(np.float32)
meta = {"peaks": batch["meta"]["peaks"]}
smiles_gt_list = list(batch["meta"]["smi_key"])
print(f"Loaded {n} spectra via SpecBridge MassSpecGymDataset+collate (exact eval input)")
else:
records = load_mgf_spectra(
args.mgf_path, spec_bins=args.spec_bins, max_mz=args.max_mz, max_peaks=args.max_peaks
)
if args.limit:
records = records[: args.limit]
n = len(records)
if n == 0:
raise SystemExit("No spectra in MGF")
smiles_gt_list = [r["smiles_gt"] for r in records]
spectra_binned = np.stack([r["binned"] for r in records], axis=0).astype(np.float32)
meta = build_meta_peaks(records, args.max_peaks)
# ---- ChemBERTa: use the SAME SpecBridge model for index and query ----
# Index = model._chemberta_embed(smiles_gt); Query = mapB(spec(spectra)). Same space as SpecBridge eval.
print("Loading SpecBridge model (one model for both index and query)...")
spec_embedder = SpectrumEmbedder(
specbridge_ckpt=args.specbridge_ckpt,
dreams_ckpt=args.dreams_ckpt,
device=args.device,
normalize=False,
use_lightweight=False,
)
spec_model = spec_embedder._load()
spec_model.eval()
use_peaks = not getattr(spec_model, "_dreams_is_dummy", False)
print("Building ChemBERTa index from TRUE mol embeddings (same model's _chemberta_embed)...")
v_chem_list = []
with torch.no_grad():
for start in range(0, n, args.batch_size):
chunk = smiles_gt_list[start : start + args.batch_size]
h = spec_model._chemberta_embed(chunk, device)
v_chem_list.append(h.cpu().numpy())
v_chem = np.concatenate(v_chem_list, axis=0).astype(np.float32)
index_chem = build_hnsw_index(v_chem, m=16, ef_construction=100, ef_search=64, metric="cosine")
print("Computing MAPPED query (spectrum → mapB) with same model...")
q_chem_list = []
total = spectra_binned.shape[0]
with torch.no_grad():
for start in range(0, total, args.batch_size):
end = min(total, start + args.batch_size)
batch = torch.tensor(spectra_binned[start:end], dtype=torch.float32, device=device)
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(device)
else:
batch_meta[k] = v
z_s = spec_model.spec(batch, batch_meta)
mu_s, _ = spec_model.mapB(z_s)
q_chem_list.append(mu_s.cpu().numpy())
q_chem = np.concatenate(q_chem_list, axis=0).astype(np.float32)
# ---- SMI-TED: use the SAME DreamsToSmiTed model for index and query ----
index_smi = None
q_smi = None
use_pretrained_smited = args.smited_mapper_ckpt is not None
if use_pretrained_smited:
despec_root = Path(args.despecbridge_path or "").resolve()
if not despec_root.exists():
raise SystemExit("--despecbridge-path required when using --smited-mapper-ckpt")
if str(despec_root) not in sys.path:
sys.path.insert(0, str(despec_root))
from despecbridge.models.dreams_to_smited import (
build_dreams_adapter_for_smited,
build_mapper,
DreamsToSmiTed,
)
from despecbridge.models.smited_decoder import load_smited
mapper_ckpt_path = Path(args.smited_mapper_ckpt)
ckpt = torch.load(mapper_ckpt_path, map_location="cpu")
ckpt_args = ckpt.get("args", {})
if not ckpt_args:
raise SystemExit("Mapper checkpoint missing 'args' dict.")
cond_dim = int(ckpt_args.get("cond_dim", 512))
spec_bins_ckpt = int(ckpt_args.get("spec_bins", 2048))
dreams_ckpt = ckpt_args.get("dreams_ckpt", args.dreams_ckpt)
spec_encoder = build_dreams_adapter_for_smited(
dreams_ckpt=dreams_ckpt,
cond_dim=cond_dim,
spec_bins=spec_bins_ckpt,
)
if "spec_encoder" in ckpt:
spec_encoder.load_state_dict(ckpt["spec_encoder"], strict=False)
d_smited = int(ckpt_args.get("d_smited", 768))
mapper = build_mapper(
cond_dim,
d_smited,
n_blocks=int(ckpt_args.get("mapper_blocks", 2)),
hidden=int(ckpt_args.get("mapper_hidden", 512)),
)
mapper_state = ckpt["mapper"]
if mapper_state and list(mapper_state.keys())[0].startswith("module."):
mapper_state = {k.replace("module.", ""): v for k, v in mapper_state.items()}
mapper.load_state_dict(mapper_state, strict=True)
smited_wrapper = load_smited(
model_name=ckpt_args.get("smited_model", "ibm-research/materials.smi-ted"),
device=device,
use_original_weights=bool(ckpt_args.get("use_original_weights", False)),
)
smited_wrapper.eval()
smited_mapper_model = DreamsToSmiTed(
spec_encoder=spec_encoder,
mapper=mapper,
smited=smited_wrapper,
freeze_spec=True,
freeze_decoder=True,
).to(device)
smited_mapper_model.eval()
# Index = same model's SMI-TED encoder (true mol embeddings)
print("Building SMI-TED index from TRUE mol embeddings (same model's smited.encode_mean_pool)...")
v_smi_list = []
with torch.no_grad():
for start in range(0, n, args.batch_size):
chunk = smiles_gt_list[start : start + args.batch_size]
h = smited_mapper_model.smited.encode_mean_pool(chunk, device=device)
v_smi_list.append(h.cpu().numpy())
v_smi = np.concatenate(v_smi_list, axis=0).astype(np.float32)
index_smi = build_hnsw_index(v_smi, m=16, ef_construction=100, ef_search=64, metric="cosine")
# Query = mapped (spectrum → same model)
print("Computing MAPPED query (spectrum → same DreamsToSmiTed)...")
total = spectra_binned.shape[0]
all_latents = []
with torch.no_grad():
for start in range(0, total, args.batch_size):
end = min(total, start + args.batch_size)
spectra_t = torch.tensor(spectra_binned[start:end], dtype=torch.float32, device=device)
meta_t = {}
for k, v in meta.items():
if isinstance(v, torch.Tensor) and v.shape[0] == total:
meta_t[k] = v[start:end].to(device)
else:
meta_t[k] = v
z = smited_mapper_model(spectra_t, meta_t)
all_latents.append(z.detach().cpu().numpy().astype(np.float32))
q_smi = np.concatenate(all_latents, axis=0)
elif args.mapper_dir:
mapper_dir = Path(args.mapper_dir)
ckpt = torch.load(mapper_dir / "mappers.pt", map_location="cpu", weights_only=False)
d_spec = ckpt["d_spec"]
d_smi = ckpt["d_smi"]
class MapperHead(torch.nn.Module):
def __init__(self, d_in, d_out):
super().__init__()
self.proj = torch.nn.Linear(d_in, d_out)
def forward(self, x):
return self.proj(x)
M_smi = MapperHead(d_spec, d_smi).to(device).eval()
M_smi.load_state_dict(ckpt["M_smi"])
x_spec = spec_embedder.encode_spec_only(spectra_binned, meta, batch_size=args.batch_size)
with torch.no_grad():
x = torch.tensor(x_spec, dtype=torch.float32, device=device)
q_smi = M_smi(x).cpu().numpy().astype(np.float32)
if q_smi is not None:
q_smi = q_smi.astype(np.float32) # keep unnormalized to match SpecBridge eval (inner product)
# ---- Diagnostic: raw dot and COSINE (query[i] · true_mol[i]) ----
# Expected: ChemBERTa mapper ~0.8+ cosine, SMI-TED mapper ~0.99. If much lower → bug.
def _cosine(a: np.ndarray, b: np.ndarray, eps: float = 1e-8) -> np.ndarray:
# a,b [n,d] -> [n] cosine per row
dot = np.sum(a * b, axis=1)
na = np.linalg.norm(a, axis=1) + eps
nb = np.linalg.norm(b, axis=1) + eps
return (dot / (na * nb)).astype(np.float64)
self_dot_chem = np.array([np.dot(q_chem[i], v_chem[i]) for i in range(n)], dtype=np.float64)
cos_chem = _cosine(q_chem, v_chem)
print(f"ChemBERTa (query·true_mol): dot mean={self_dot_chem.mean():.2f} cosine mean={cos_chem.mean():.4f} std={cos_chem.std():.4f} min={cos_chem.min():.4f} max={cos_chem.max():.4f}")
# Exact rank: how many j have score(i,j) > score(i,i)? (ranking by inner product, same as cosine for normalized index)
all_scores_chem = np.dot(q_chem, v_chem.T) # [n, n]
rank_chem = np.sum(all_scores_chem > all_scores_chem.diagonal()[:, None], axis=1) + 1
print(f"ChemBERTa exact rank of true mol: mean={rank_chem.mean():.1f} median={np.median(rank_chem):.0f} (1=best)")
# ---- Retrieve: query with mapped embedding, check if top-k contains self (index i) ----
def recall_at_k(indices_2d, k: int) -> float:
return sum(1 for i in range(n) if any(int(indices_2d[i, j]) == i for j in range(min(k, indices_2d.shape[1])))) / n
results = {"n": n, "true_index_mapped_query_chem": None, "true_index_mapped_query_smi": None}
scores_chem, idx_chem = index_search(index_chem, q_chem, K)
tan1_chem_mean, tan1_chem_med, tan1_chem_count = _tanimoto_at_k(idx_chem, smiles_gt_list, 1, at_1=True)
tan10_chem_mean, tan10_chem_med, _ = _tanimoto_at_k(idx_chem, smiles_gt_list, 10, at_1=False)
results["true_index_mapped_query_chem"] = {
"Recall@1": recall_at_k(idx_chem, 1),
"Recall@10": recall_at_k(idx_chem, 10),
"Recall@50": recall_at_k(idx_chem, 50),
"cosine_mean": float(cos_chem.mean()),
"cosine_std": float(cos_chem.std()),
"dot_mean": float(self_dot_chem.mean()),
"mean_rank": float(rank_chem.mean()),
"median_rank": float(np.median(rank_chem)),
"Tanimoto@1_mean": tan1_chem_mean,
"Tanimoto@1_median": tan1_chem_med,
"Tanimoto@1_count": tan1_chem_count,
"Tanimoto@10_mean": tan10_chem_mean,
"Tanimoto@10_median": tan10_chem_med,
}
print("True-index + Mapped-query (ChemBERTa):", results["true_index_mapped_query_chem"])
if tan1_chem_mean is not None:
print(f" Tanimoto (fp) @1: mean={tan1_chem_mean:.4f} median={tan1_chem_med:.4f} (n={tan1_chem_count}) @10 max: mean={tan10_chem_mean:.4f}")
else:
print(" Tanimoto: N/A (install rdkit for fingerprint similarity)")
print("(SpecBridge ~70% R@1 is over same-formula candidates (isomers), not over full test set.)")
if index_smi is not None and q_smi is not None:
self_dot_smi = np.array([np.dot(q_smi[i], v_smi[i]) for i in range(n)], dtype=np.float64)
cos_smi = _cosine(q_smi, v_smi)
print(f"SMI-TED (query·true_mol): dot mean={self_dot_smi.mean():.2f} cosine mean={cos_smi.mean():.4f} std={cos_smi.std():.4f} min={cos_smi.min():.4f} max={cos_smi.max():.4f}")
all_scores_smi = np.dot(q_smi, v_smi.T)
rank_smi = np.sum(all_scores_smi > all_scores_smi.diagonal()[:, None], axis=1) + 1
print(f"SMI-TED exact rank of true mol: mean={rank_smi.mean():.1f} median={np.median(rank_smi):.0f} (1=best)")
scores_smi, idx_smi = index_search(index_smi, q_smi, K)
tan1_smi_mean, tan1_smi_med, tan1_smi_count = _tanimoto_at_k(idx_smi, smiles_gt_list, 1, at_1=True)
tan10_smi_mean, tan10_smi_med, _ = _tanimoto_at_k(idx_smi, smiles_gt_list, 10, at_1=False)
results["true_index_mapped_query_smi"] = {
"Recall@1": recall_at_k(idx_smi, 1),
"Recall@10": recall_at_k(idx_smi, 10),
"Recall@50": recall_at_k(idx_smi, 50),
"cosine_mean": float(cos_smi.mean()),
"cosine_std": float(cos_smi.std()),
"dot_mean": float(self_dot_smi.mean()),
"mean_rank": float(rank_smi.mean()),
"median_rank": float(np.median(rank_smi)),
"Tanimoto@1_mean": tan1_smi_mean,
"Tanimoto@1_median": tan1_smi_med,
"Tanimoto@1_count": tan1_smi_count,
"Tanimoto@10_mean": tan10_smi_mean,
"Tanimoto@10_median": tan10_smi_med,
}
print("True-index + Mapped-query (SMI-TED):", results["true_index_mapped_query_smi"])
if tan1_smi_mean is not None:
print(f" Tanimoto (fp) @1: mean={tan1_smi_mean:.4f} median={tan1_smi_med:.4f} (n={tan1_smi_count}) @10 max: mean={tan10_smi_mean:.4f}")
else:
print(" Tanimoto: N/A (install rdkit for fingerprint similarity)")
else:
print("True-index + Mapped-query (SMI-TED): skipped (no SMI-TED index or mapped q_smi)")
if args.report:
with open(args.report, "w") as f:
json.dump(results, f, indent=2)
print(f"Wrote {args.report}")
if __name__ == "__main__":
main()