File size: 13,230 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
#!/usr/bin/env python
"""
Build molecule library: compute v_smi (E_smi), v_chem (E_chem), meta.parquet.
Plan §1: vectors_smi, vectors_chem, meta (SMILES, formula, mass).
"""
from __future__ import annotations

import argparse
import json
import os
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 tqdm import tqdm

from spec_rag.embeddings import SMILESEmbedder
from spec_rag.flare_encoder import FLAREMolEmbedder
from spec_rag.io import ensure_dir, load_smiles
from spec_rag.smited_encoder import load_smited_encoder


def _chem_worker_encode_chunk(args_tuple):
    """Worker for multi-GPU ChemBERTa: (gpu_id, smiles_chunk, model_name, batch_size, max_length, out_path)."""
    gpu_id, smiles_chunk, model_name, batch_size, max_length, out_path = args_tuple
    os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_id)
    if str(ROOT) not in sys.path:
        sys.path.insert(0, str(ROOT))
    Path(out_path).parent.mkdir(parents=True, exist_ok=True)
    if not smiles_chunk:
        np.save(out_path, np.zeros((0, 0), dtype=np.float32))
        return out_path
    from spec_rag.embeddings import SMILESEmbedder
    embedder = SMILESEmbedder(
        model_name=model_name,
        device="cuda",
        batch_size=batch_size,
        max_length=max_length,
        normalize=False,
    )
    arr = embedder.encode(smiles_chunk)
    np.save(out_path, arr.astype(np.float32))
    return out_path


def _smited_worker_encode_chunk(args_tuple):
    """Worker for multi-GPU SMI-TED: (gpu_id, smiles_chunk, despecbridge_path, batch_size, out_path)."""
    gpu_id, smiles_chunk, despecbridge_path, batch_size, out_path = args_tuple
    os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_id)
    if str(ROOT) not in sys.path:
        sys.path.insert(0, str(ROOT))
    Path(out_path).parent.mkdir(parents=True, exist_ok=True)
    if not smiles_chunk:
        np.save(out_path, np.zeros((0, 0), dtype=np.float32))
        return out_path
    from spec_rag.smited_encoder import load_smited_encoder
    encode_smi = load_smited_encoder(despecbridge_path=despecbridge_path, device="cuda")
    if encode_smi is None:
        raise RuntimeError("SMI-TED failed to load in worker")
    arr = encode_smi(smiles_chunk, batch_size=batch_size, desc="SMI-TED")
    np.save(out_path, arr.astype(np.float32))
    return out_path


def get_formula_and_mass(smiles: str):
    try:
        from rdkit import Chem
        from rdkit.Chem import Descriptors
        mol = Chem.MolFromSmiles(smiles)
        if mol is None:
            return "", float("nan")
        formula = Chem.rdMolDescriptors.CalcMolFormula(mol)
        mass = Descriptors.ExactMolWt(mol)
        return formula, mass
    except Exception:
        return "", float("nan")


def parse_args():
    p = argparse.ArgumentParser(description="Build library: v_smi, v_chem, meta.parquet")
    p.add_argument("--smiles-path", required=True, help="SMILES list (one per line) or path to molecules")
    p.add_argument("--out-dir", required=True, help="Output directory")
    p.add_argument("--despecbridge-path", default=None, help="Path to De-SpecBridge for SMI-TED (optional)")
    p.add_argument("--chemberta-model", default="Derify/ChemBERTa_augmented_pubchem_13m")
    p.add_argument("--batch-size", type=int, default=640)
    p.add_argument("--max-length", type=int, default=256)
    p.add_argument("--no-chem", action="store_true", help="Skip ChemBERTa (useful for FLARE-only library builds)")
    p.add_argument("--no-smi", action="store_true", help="Skip SMI-TED (only compute v_chem)")
    p.add_argument("--with-flare", action="store_true", help="Also compute FLARE molecule embeddings as vectors_flare.npy")
    p.add_argument("--flare-repo", default=str(ROOT / "FLARE"))
    p.add_argument("--flare-hparams", default=str(ROOT / "FLARE" / "experiments" / "20250913_optimized_filip-model" / "lightning_logs" / "version_0" / "hparams.yaml"))
    p.add_argument("--flare-checkpoint", default=str(ROOT / "FLARE" / "pretrained_models" / "flare.ckpt"))
    p.add_argument("--flare-batch-size", type=int, default=256)
    p.add_argument("--flare-device", default="cuda")
    p.add_argument("--device", default="cuda")
    p.add_argument("--limit", type=int, default=None, help="Max molecules (for debugging)")
    p.add_argument("--dedupe", action="store_true", help="Deduplicate SMILES after loading input")
    return p.parse_args()


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

    out_dir = ensure_dir(args.out_dir)
    complete_marker = out_dir / "library_build.complete"
    loaded_existing_meta = False

    # Load meta if already processed; otherwise compute from --smiles-path
    meta_parquet = out_dir / "meta.parquet"
    meta_jsonl = out_dir / "meta.jsonl"
    if complete_marker.exists() and meta_parquet.exists():
        import pandas as pd
        df = pd.read_parquet(meta_parquet)
        smiles = df["smiles"].astype(str).tolist()
        if smiles:
            print(f"Loaded existing meta from {meta_parquet} ({len(smiles)} molecules)")
            loaded_existing_meta = True
    elif complete_marker.exists() and meta_jsonl.exists():
        meta_rows = []
        with open(meta_jsonl) as f:
            for line in f:
                if line.strip():
                    meta_rows.append(json.loads(line))
        smiles = [r["smiles"] for r in meta_rows]
        if smiles:
            print(f"Loaded existing meta from {meta_jsonl} ({len(smiles)} molecules)")
            loaded_existing_meta = True
    if not loaded_existing_meta:
        if meta_parquet.exists() or meta_jsonl.exists() or complete_marker.exists():
            print("Ignoring incomplete existing library artifacts and rebuilding from source.")
        smiles = load_smiles(args.smiles_path)
        if args.dedupe:
            seen = set()
            smiles = [s for s in smiles if not (s in seen or seen.add(s))]
        if args.limit:
            smiles = smiles[: args.limit]
        stream_meta = len(smiles) > 1_000_000
        if stream_meta:
            with open(out_dir / "meta.jsonl", "w", encoding="utf-8") as f:
                for i, smi in enumerate(tqdm(smiles, desc="Meta")):
                    formula, mass = get_formula_and_mass(smi)
                    row = {"id": i, "smiles": smi, "formula": formula, "mass": mass}
                    f.write(json.dumps(row) + "\n")
        else:
            meta_rows = []
            for i, smi in enumerate(tqdm(smiles, desc="Meta")):
                formula, mass = get_formula_and_mass(smi)
                meta_rows.append({"id": i, "smiles": smi, "formula": formula, "mass": mass})
            try:
                import pandas as pd
                pd.DataFrame(meta_rows).to_parquet(out_dir / "meta.parquet", index=False)
            except ImportError:
                with open(out_dir / "meta.jsonl", "w", encoding="utf-8") as f:
                    for r in meta_rows:
                        f.write(json.dumps(r) + "\n")

    if args.dedupe and (meta_parquet.exists() or meta_jsonl.exists()):
        seen = set()
        smiles = [s for s in smiles if not (s in seen or seen.add(s))]
    if args.limit and (meta_parquet.exists() or meta_jsonl.exists()):
        smiles = smiles[: args.limit]

    n_gpus = 0
    if args.device == "cuda":
        try:
            import torch
            n_gpus = torch.cuda.device_count()
        except Exception:
            pass

    # E_chem (ChemBERTa): skip if already computed
    if args.no_chem:
        print("Skipping ChemBERTa (--no-chem).")
    elif (out_dir / "vectors_chem.npy").exists():
        print(f"Using existing {out_dir / 'vectors_chem.npy'} (skip ChemBERTa)")
    elif n_gpus > 1:
        import multiprocessing as mp
        ctx = mp.get_context("spawn")
        chunks = np.array_split(smiles, min(n_gpus, len(smiles)))
        temp_paths = [str(out_dir / f".vectors_chem_part_{i}.npy") for i in range(len(chunks))]
        worker_args = [
            (i, list(chunks[i]), args.chemberta_model, args.batch_size, args.max_length, temp_paths[i])
            for i in range(len(chunks))
        ]
        print(f"ChemBERTa: encoding on {len(chunks)} GPUs (batch_size={args.batch_size} per GPU)")
        processes = []
        for i in range(len(chunks)):
            os.environ["CUDA_VISIBLE_DEVICES"] = str(i)
            p = ctx.Process(target=_chem_worker_encode_chunk, args=(worker_args[i],))
            p.start()
            processes.append(p)
        for p in tqdm(processes, desc="ChemBERTa", unit="GPU"):
            p.join()
        parts = [np.load(p) for p in temp_paths if os.path.isfile(p)]
        v_chem = np.concatenate([x for x in parts if x.size > 0], axis=0).astype(np.float32)
        for p in temp_paths:
            if os.path.isfile(p):
                os.remove(p)
        np.save(out_dir / "vectors_chem.npy", v_chem)
    else:
        embedder_chem = SMILESEmbedder(
            model_name=args.chemberta_model,
            device=args.device,
            batch_size=args.batch_size,
            max_length=args.max_length,
            normalize=False,
        )
        v_chem = embedder_chem.encode(smiles)
        np.save(out_dir / "vectors_chem.npy", v_chem.astype(np.float32))

    # E_smi (SMI-TED) optional; use all GPUs via multiprocessing when n_gpus > 1
    if not args.no_smi:
        encode_smi = load_smited_encoder(
            despecbridge_path=args.despecbridge_path, device=args.device
        )
        if encode_smi is not None and n_gpus > 1:
            import multiprocessing as mp
            ctx = mp.get_context("spawn")
            chunks = np.array_split(smiles, min(n_gpus, len(smiles)))
            temp_paths = [str(out_dir / f".vectors_smi_part_{i}.npy") for i in range(len(chunks))]
            worker_args = [
                (i, list(chunks[i]), args.despecbridge_path, args.batch_size, temp_paths[i])
                for i in range(len(chunks))
            ]
            # Set CUDA_VISIBLE_DEVICES in parent before each Process.start() so the spawned
            # child inherits it and only sees one GPU (avoids all 4 jobs on same GPU).
            processes = []
            for i in range(len(chunks)):
                os.environ["CUDA_VISIBLE_DEVICES"] = str(i)
                p = ctx.Process(target=_smited_worker_encode_chunk, args=(worker_args[i],))
                p.start()
                processes.append(p)
            for p in tqdm(processes, desc="SMI-TED", unit="GPU"):
                p.join()
            parts = [np.load(p) for p in temp_paths if os.path.isfile(p)]
            valid = [x for x in parts if x.size > 0]
            if not valid:
                for p in temp_paths:
                    if os.path.isfile(p):
                        os.remove(p)
                raise RuntimeError("SMI-TED workers produced no output (all failed). Check tracebacks above.")
            v_smi = np.concatenate(valid, axis=0).astype(np.float32)
            for p in temp_paths:
                if os.path.isfile(p):
                    os.remove(p)
            np.save(out_dir / "vectors_smi.npy", v_smi)
            print(f"SMI-TED encoded on {len(chunks)} GPUs")
        elif encode_smi is not None:
            v_smi = encode_smi(smiles, batch_size=args.batch_size)
            np.save(out_dir / "vectors_smi.npy", v_smi.astype(np.float32))
        else:
            print("SMI-TED not available (set DESPECBRIDGE_PATH or --despecbridge-path). Skipping vectors_smi.")
    else:
        print("Skipping SMI-TED (--no-smi).")

    if args.with_flare:
        flare_path = out_dir / "vectors_flare.npy"
        reuse_flare = False
        if loaded_existing_meta and flare_path.exists():
            try:
                existing = np.load(flare_path, mmap_mode="r")
                reuse_flare = existing.shape[0] == len(smiles) and existing.shape[0] > 0
            except Exception:
                reuse_flare = False
        if reuse_flare:
            print(f"Using existing {flare_path} (skip FLARE)")
        else:
            embedder_flare = FLAREMolEmbedder(
                flare_repo=args.flare_repo,
                hparams_pth=args.flare_hparams,
                checkpoint_pth=args.flare_checkpoint,
                device=args.flare_device,
                batch_size=args.flare_batch_size,
                normalize=False,
            )
            embedder_flare.encode_to_npy(smiles, flare_path)
            print(f"Saved {flare_path}")

    saved = ["meta.parquet"]
    if not args.no_chem and (out_dir / "vectors_chem.npy").exists():
        saved.append("vectors_chem.npy")
    if not args.no_smi and (out_dir / "vectors_smi.npy").exists():
        saved.append("vectors_smi.npy")
    if args.with_flare and (out_dir / "vectors_flare.npy").exists():
        saved.append("vectors_flare.npy")
    complete_marker.write_text("ok\n", encoding="utf-8")
    print(f"Saved to {out_dir}: {', '.join(saved)}")


if __name__ == "__main__":
    main()