File size: 11,046 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 | #!/usr/bin/env python
"""
Mapped-embedding self-retrieval sanity check: index = spectrum→mapper embeddings of test set,
query = same embeddings. Expected Recall@1 ≈ 1.0.
Tests (1) spectrum→ChemBERTa-mapped (SpecBridge) and (2) spectrum→SMI-TED-mapped (DreamsToSmiTed or M_smi).
If either fails, the spectrum→mapped-embedding pipeline is broken.
"""
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, l2_normalize
from spec_rag.faiss_index import build_hnsw_index, index_search
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):
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", {})
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)
peaks = [[float(m), float(i)] for m, i in zip(mz, inten)]
if max_peaks and peaks:
peaks = sorted(peaks, key=lambda x: x[1], reverse=True)[:max_peaks]
out.append({"binned": binned, "peaks": peaks})
return out
def build_meta_peaks(records, max_peaks: int):
if not records or "peaks" not in records[0]:
return {}
peaks_list = [r["peaks"] for r in records]
max_len = min(max(len(p) for p in peaks_list), max_peaks) if max_peaks else 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[:max_len]):
arr[i, j, 0] = pair[0]
arr[i, j, 1] = pair[1]
return {"peaks": torch.tensor(arr)}
def parse_args():
p = argparse.ArgumentParser(
description="Mapped self-retrieval: index = spectrum→mapper embeddings, query = same; expect Recall@1 ≈ 1.0"
)
p.add_argument("--mgf-path", required=True, help="Test MGF (e.g. MassSpecGym_test.mgf)")
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 (e.g. mapper_best.pt)")
p.add_argument("--despecbridge-path", default=None)
p.add_argument("--mapper-dir", default=None, help="Spec-RAG mappers.pt dir (for SMI-TED when not using smited-mapper-ckpt)")
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("--device", default="cuda")
p.add_argument("--limit", type=int, default=None)
p.add_argument("--report", default=None)
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)
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")
spectra_binned = np.stack([r["binned"] for r in records], axis=0).astype(np.float32)
meta = build_meta_peaks(records, args.max_peaks)
results = {"n": n, "mapped_chem": None, "mapped_smi": None}
# --- Mapped ChemBERTa (spectrum → SpecBridge → q_chem) ---
print("Mapped ChemBERTa: loading SpectrumEmbedder and encoding test spectra...")
spec_embedder = SpectrumEmbedder(
specbridge_ckpt=args.specbridge_ckpt,
dreams_ckpt=args.dreams_ckpt,
device=args.device,
normalize=False,
use_lightweight=False,
)
q_chem = spec_embedder.encode(spectra_binned, meta, batch_size=32)
q_chem = l2_normalize(q_chem).astype(np.float32)
index_chem = build_hnsw_index(q_chem, m=16, ef_construction=100, ef_search=64, metric="cosine")
scores_chem, idx_chem = index_search(index_chem, q_chem, k=1)
# Match if top-1 is self (or duplicate: inner product ≈ 1.0 for normalized vectors)
r1_chem = sum(1 for i in range(n) if idx_chem[i, 0] == i or scores_chem[i, 0] >= 0.9999) / n
results["mapped_chem"] = {"Recall@1": r1_chem}
print(f"Mapped ChemBERTa self-retrieval Recall@1: {r1_chem:.4f} (expected ≈ 1.0)")
spec_embedder_for_smi = spec_embedder # reuse for Spec-RAG M_smi path if needed
# --- Mapped SMI-TED ---
use_pretrained_smited = args.smited_mapper_ckpt is not None
q_smi = 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(f"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()
batch_size = 32
all_latents = []
total = spectra_binned.shape[0]
with torch.no_grad():
for start in range(0, total, batch_size):
end = min(total, start + 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_for_smi.encode_spec_only(spectra_binned, meta, batch_size=32)
with torch.no_grad():
x = torch.tensor(x_spec, dtype=torch.float32, device=device)
q_smi = M_smi(x).cpu().numpy().astype(np.float32)
else:
print("Mapped SMI-TED: skipped (provide --smited-mapper-ckpt + --despecbridge-path or --mapper-dir)")
if q_smi is not None:
q_smi = l2_normalize(q_smi).astype(np.float32)
index_smi = build_hnsw_index(q_smi, m=16, ef_construction=100, ef_search=64, metric="cosine")
scores_smi, idx_smi = index_search(index_smi, q_smi, k=1)
r1_smi = sum(1 for i in range(n) if idx_smi[i, 0] == i or scores_smi[i, 0] >= 0.9999) / n
results["mapped_smi"] = {"Recall@1": r1_smi}
print(f"Mapped SMI-TED self-retrieval Recall@1: {r1_smi:.4f} (expected ≈ 1.0)")
print("\nInterpretation:")
if results["mapped_chem"] and results["mapped_chem"]["Recall@1"] < 0.99:
print(" - Mapped ChemBERTa Recall@1 << 1.0 → spectrum→ChemBERTa pipeline may be broken.")
elif results["mapped_chem"]:
print(" - Mapped ChemBERTa passed (Recall@1 ≈ 1.0).")
if results["mapped_smi"] is not None:
if results["mapped_smi"]["Recall@1"] < 0.99:
print(" - Mapped SMI-TED Recall@1 << 1.0 → spectrum→SMI-TED pipeline may be broken.")
else:
print(" - Mapped SMI-TED passed (Recall@1 ≈ 1.0).")
elif not use_pretrained_smited and not args.mapper_dir:
print(" - Mapped SMI-TED skipped (no mapper provided).")
if args.report:
with open(args.report, "w") as f:
json.dump(results, f, indent=2)
print(f"\nWrote {args.report}")
if __name__ == "__main__":
main()
|