File size: 4,821 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
#!/usr/bin/env python
"""
Inference with optional Grammar-Constrained Decoding (GCD) for valid SMILES.
Load encoder + LLM (with LoRA), run on spectra (JSONL or single), output SMILES.
"""
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 torch

from spec_rag.spectra_reason_encoder import build_spectra_reason_encoder
from spec_rag.gcd_inference import predict_smiles_from_spectrum, get_smiles_constraint


def parse_args() -> argparse.Namespace:
    p = argparse.ArgumentParser(description="Generate SMILES from spectra (with optional GCD).")
    p.add_argument("--input-jsonl", default=None, help="JSONL with 'peaks' per line")
    p.add_argument("--output-jsonl", default=None, help="Same + 'predicted_smiles'")
    p.add_argument("--encoder-dir", default=None, help="Dir with encoder state (perceiver.pt, etc.)")
    p.add_argument("--model-dir", required=True, help="Dir with LoRA + tokenizer (from Stage 2)")
    p.add_argument("--llm-name", default="meta-llama/Meta-Llama-3-8B-Instruct", help="Base LLM (for loading LoRA)")
    p.add_argument("--dreams-ckpt", default=None)
    p.add_argument("--specbridge-ckpt", default=None)
    p.add_argument("--max-peaks", type=int, default=60)
    p.add_argument("--max-new-tokens", type=int, default=200)
    p.add_argument("--no-gcd", action="store_true", help="Disable grammar constraint")
    p.add_argument("--grammar", default=None, help="Path to smiles.ebnf")
    p.add_argument("--device", default="cuda")
    p.add_argument("--batch-size", type=int, default=1)
    return p.parse_args()


def load_encoder(args, device: torch.device):
    encoder = build_spectra_reason_encoder(
        llm_dim=4096,
        num_latents=64,
        dreams_ckpt=args.dreams_ckpt,
        specbridge_ckpt=args.specbridge_ckpt,
        device=str(device),
    )
    if args.encoder_dir:
        p = Path(args.encoder_dir)
        if (p / "perceiver.pt").exists():
            encoder.perceiver.load_state_dict(
                torch.load(p / "perceiver.pt", map_location=device),
            )
        if (p / "encoder_last.pt").exists():
            encoder.load_state_dict(
                torch.load(p / "encoder_last.pt", map_location=device),
                strict=False,
            )
    return encoder.to(device).eval()


def main() -> None:
    args = parse_args()
    if args.device == "cuda" and not torch.cuda.is_available():
        args.device = "cpu"
    device = torch.device(args.device)
    grammar_path = Path(args.grammar) if args.grammar else (ROOT / "grammars" / "smiles.ebnf")

    from transformers import AutoModelForCausalLM, AutoTokenizer
    tokenizer = AutoTokenizer.from_pretrained(args.model_dir)
    if tokenizer.pad_token is None:
        tokenizer.pad_token = tokenizer.eos_token
    base = AutoModelForCausalLM.from_pretrained(
        args.llm_name,
        torch_dtype=torch.float16 if device.type == "cuda" else torch.float32,
        device_map=str(device),
    )
    try:
        from peft import PeftModel
        model = PeftModel.from_pretrained(base, args.model_dir)
    except Exception:
        model = base
    model.eval()

    encoder = load_encoder(args, device)

    if not args.input_jsonl:
        print("No --input-jsonl; run with --input-jsonl and --output-jsonl to process a file.")
        return

    results = []
    with open(args.input_jsonl) as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            obj = json.loads(line)
            peaks_list = obj.get("peaks", [])
            peaks_list = sorted(peaks_list, key=lambda x: float(x[1]), reverse=True)[:args.max_peaks]
            arr = torch.zeros(args.max_peaks, 2, dtype=torch.float32)
            for j, (mz, i) in enumerate(peaks_list):
                arr[j, 0] = float(mz)
                arr[j, 1] = float(i)
            arr = arr.unsqueeze(0).to(device)
            pred = predict_smiles_from_spectrum(
                encoder,
                model,
                tokenizer,
                arr,
                device,
                max_new_tokens=args.max_new_tokens,
                use_gcd=not args.no_gcd,
                grammar_path=grammar_path if grammar_path.exists() else None,
            )
            obj["predicted_smiles"] = pred
            results.append(obj)

    if args.output_jsonl:
        with open(args.output_jsonl, "w") as out:
            for obj in results:
                out.write(json.dumps(obj) + "\n")
        print(f"Wrote {len(results)} predictions to {args.output_jsonl}")
    else:
        for obj in results:
            print(json.dumps(obj))


if __name__ == "__main__":
    main()