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