File size: 20,885 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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 | #!/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()
|