File size: 4,867 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
#!/usr/bin/env python
"""
Self-retrieval sanity check: build a tiny FAISS index from test molecules only,
query with the same true molecule embeddings. Expected Recall@1 ≈ 1.0.

Run separately for ChemBERTa and SMI-TED. If either fails, that embedding pipeline is broken.
If both pass, the main issue is likely library coverage / eval mismatch.
"""
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

from spec_rag.embeddings import SMILESEmbedder, l2_normalize
from spec_rag.faiss_index import build_hnsw_index, index_search
from spec_rag.smited_encoder import load_smited_encoder


def parse_args():
    p = argparse.ArgumentParser(
        description="Self-retrieval: index test molecules, query with same embeddings; expect Recall@1 ≈ 1.0"
    )
    p.add_argument("--pred-jsonl", required=True, help="JSONL with smiles_gt (e.g. candidates_*.jsonl)")
    p.add_argument("--despecbridge-path", default=None, help="De-SpecBridge path for SMI-TED")
    p.add_argument("--chemberta-model", default="Derify/ChemBERTa_augmented_pubchem_13m")
    p.add_argument("--batch-size", type=int, default=64)
    p.add_argument("--device", default="cuda")
    p.add_argument("--report", default=None, help="Write metrics JSON here")
    return p.parse_args()


def main():
    args = parse_args()
    rows = []
    with open(args.pred_jsonl) as f:
        for line in f:
            if line.strip():
                rows.append(json.loads(line))
    smiles_list = [r.get("smiles_gt", "") for r in rows]
    n = len(smiles_list)
    if n == 0:
        raise SystemExit("No rows in pred-jsonl")

    device = args.device
    if device == "cuda":
        try:
            import torch
            if not torch.cuda.is_available():
                device = "cpu"
        except Exception:
            device = "cpu"

    results = {"n": n, "chemberta": None, "smited": None}

    # --- ChemBERTa self-retrieval ---
    print("ChemBERTa: encoding test SMILES...")
    embedder = SMILESEmbedder(
        model_name=args.chemberta_model,
        device=device,
        batch_size=args.batch_size,
        normalize=False,
    )
    v_chem = embedder.encode(smiles_list)
    v_chem = l2_normalize(v_chem).astype(np.float32)
    print("ChemBERTa: building FAISS index from test vectors...")
    index_chem = build_hnsw_index(v_chem, m=16, ef_construction=100, ef_search=64, metric="cosine")
    scores_chem, indices_chem = index_search(index_chem, v_chem, k=1)
    r1_chem = sum(
        1 for i in range(n)
        if indices_chem[i, 0] < n and smiles_list[indices_chem[i, 0]] == smiles_list[i]
    ) / n
    results["chemberta"] = {"Recall@1": r1_chem}
    print(f"ChemBERTa self-retrieval Recall@1: {r1_chem:.4f} (expected ≈ 1.0)")

    # --- SMI-TED self-retrieval ---
    encode_smi = load_smited_encoder(despecbridge_path=args.despecbridge_path, device=device)
    if encode_smi is None:
        print("SMI-TED not available; skipping SMI-TED self-retrieval.")
    else:
        print("SMI-TED: encoding test SMILES...")
        v_smi = encode_smi(smiles_list, batch_size=args.batch_size)
        v_smi = l2_normalize(v_smi).astype(np.float32)
        print("SMI-TED: building FAISS index from test vectors...")
        index_smi = build_hnsw_index(v_smi, m=16, ef_construction=100, ef_search=64, metric="cosine")
        scores_smi, indices_smi = index_search(index_smi, v_smi, k=1)
        r1_smi = sum(
            1 for i in range(n)
            if indices_smi[i, 0] < n and smiles_list[indices_smi[i, 0]] == smiles_list[i]
        ) / n
        results["smited"] = {"Recall@1": r1_smi}
        print(f"SMI-TED self-retrieval Recall@1: {r1_smi:.4f} (expected ≈ 1.0)")

    # Interpretation
    print("\nInterpretation:")
    if results["chemberta"] is not None and results["chemberta"]["Recall@1"] < 0.99:
        print("  - ChemBERTa Recall@1 << 1.0 → embedding/index pipeline may be broken.")
    elif results["chemberta"] is not None:
        print("  - ChemBERTa passed (Recall@1 ≈ 1.0).")
    if results["smited"] is not None:
        if results["smited"]["Recall@1"] < 0.99:
            print("  - SMI-TED Recall@1 << 1.0 → SMI-TED embedding construction may be the issue.")
        else:
            print("  - SMI-TED passed (Recall@1 ≈ 1.0).")
    if (results["chemberta"] and results["chemberta"]["Recall@1"] >= 0.99 and
            results["smited"] and results["smited"]["Recall@1"] >= 0.99):
        print("  - Both passed → main issue is likely library coverage / eval mismatch.")

    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()