| |
| """ |
| Run Spec-Agent inference on test data. |
| |
| Usage: |
| python scripts/run_spec_agent.py \ |
| --test-jsonl runs/rag_molt5_test.jsonl \ |
| --spec-embeddings runs/spec_embeddings_test.npy \ |
| --faiss-index runs/index \ |
| --output-json runs/spec_agent_predictions.jsonl \ |
| --model-name unsloth/Llama-3.1-8B-Instruct-bnb-4bit \ |
| --max-iterations 5 |
| """ |
|
|
| 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 tqdm import tqdm |
|
|
| from spec_rag.spec_agent import SpecAgent |
| from spec_rag.faiss_index import load_index |
| from spec_rag.io import load_jsonl |
|
|
|
|
| def parse_args() -> argparse.Namespace: |
| parser = argparse.ArgumentParser(description="Run Spec-Agent inference") |
| parser.add_argument("--test-jsonl", required=True, help="Test JSONL file") |
| parser.add_argument("--spec-embeddings", required=True, help="Spectrum embeddings .npy file") |
| parser.add_argument("--faiss-index", required=True, help="FAISS index directory") |
| parser.add_argument("--output-json", required=True, help="Output predictions JSONL") |
| parser.add_argument( |
| "--model-name", |
| default="meta-llama/Meta-Llama-3-8B-Instruct", |
| help="HuggingFace model name. Examples:\n" |
| " - meta-llama/Meta-Llama-3-8B-Instruct (default)\n" |
| " - Qwen/Qwen2.5-7B-Instruct\n" |
| " - Qwen/Qwen2.5-14B-Instruct\n" |
| " - AI4Chem/ChemLLM-7B-Chat-1_5-DPO (latest chemistry model, recommended)\n" |
| " - AI4Chem/ChemLLM-7B-Chat (older chemistry model)\n" |
| " - microsoft/phi-3-medium-4k-instruct\n" |
| " - Any other HuggingFace chat model", |
| ) |
| parser.add_argument( |
| "--use-api", |
| action="store_true", |
| help="Use HuggingFace Inference API (no local model download needed)", |
| ) |
| parser.add_argument( |
| "--api-token", |
| default=None, |
| help="HuggingFace API token (or set HF_TOKEN env var)", |
| ) |
| parser.add_argument( |
| "--use-unsloth", |
| action="store_true", |
| help="Use Unsloth for fast inference (requires unsloth package, local only)", |
| ) |
| parser.add_argument( |
| "--load-in-4bit", |
| action="store_true", |
| default=True, |
| help="Load model in 4-bit quantization (requires bitsandbytes, local only)", |
| ) |
| parser.add_argument("--max-iterations", type=int, default=5, help="Max agent iterations") |
| parser.add_argument("--top-k", type=int, default=5, help="Top-K RAG retrieval") |
| parser.add_argument("--batch-size", type=int, default=1, help="Batch size (usually 1 for agent)") |
| parser.add_argument("--device", default="cuda", help="Device (cuda/cpu)") |
| parser.add_argument("--mass-tolerance-ppm", type=float, default=10.0, help="Mass tolerance in ppm") |
| parser.add_argument("--use-selfies", action="store_true", default=True, help="Use SELFIES format (guarantees validity)") |
| parser.add_argument("--no-selfies", dest="use_selfies", action="store_false", help="Disable SELFIES, use SMILES") |
| parser.add_argument("--mgf-path", default=None, help="MGF file path to extract peaks (optional)") |
| return parser.parse_args() |
|
|
|
|
| def load_mgf_peaks(mgf_path: Path, spectrum_id: str) -> list[tuple[float, float]]: |
| """Load spectrum peaks from MGF file for a given spectrum_id. |
| |
| spectrum_id can be: |
| - An integer index (0-based) into the MGF file |
| - A string matching NAME= field in MGF |
| - A string matching any part of TITLE= field |
| """ |
| peaks = [] |
| |
| |
| try: |
| spec_idx = int(spectrum_id) |
| |
| with open(mgf_path, "r") as f: |
| lines = f.readlines() |
| spec_count = -1 |
| peaks = [] |
| in_target_spec = False |
| |
| for i, line in enumerate(lines): |
| line_stripped = line.strip() |
| if line_stripped.startswith("BEGIN IONS"): |
| spec_count += 1 |
| if spec_count == spec_idx: |
| in_target_spec = True |
| peaks = [] |
| elif in_target_spec: |
| if line_stripped.startswith("END IONS"): |
| if peaks: |
| |
| peaks_sorted = sorted(peaks, key=lambda x: x[1], reverse=True) |
| return peaks_sorted |
| break |
| elif line_stripped and not line_stripped.startswith(("PEPMASS", "CHARGE", "RTINSECONDS", "TITLE", "SCANS", "NAME", "SMILES", "INCHIKEY", "FORMULA", "PRECURSOR", "ADDUCT", "INSTRUMENT", "COLLISION", "FOLD", "SIMULATION")): |
| |
| parts = line_stripped.split() |
| if len(parts) >= 2: |
| try: |
| mz = float(parts[0]) |
| intensity = float(parts[1]) |
| if intensity > 0: |
| peaks.append((mz, intensity)) |
| except ValueError: |
| continue |
| return [] |
| except (ValueError, IndexError): |
| pass |
| |
| |
| with open(mgf_path, "r") as f: |
| in_spec = False |
| current_name = None |
| current_title = None |
| peaks = [] |
| |
| for line in f: |
| line_stripped = line.strip() |
| if line_stripped.startswith("BEGIN IONS"): |
| in_spec = True |
| current_name = None |
| current_title = None |
| peaks = [] |
| elif in_spec: |
| if line_stripped.startswith("NAME="): |
| current_name = line_stripped.split("=", 1)[1].strip() if "=" in line_stripped else "" |
| elif line_stripped.startswith("TITLE="): |
| current_title = line_stripped.split("=", 1)[1].strip() if "=" in line_stripped else "" |
| elif line_stripped.startswith("END IONS"): |
| |
| if (current_name and spectrum_id in current_name) or \ |
| (current_title and spectrum_id in current_title) or \ |
| (str(spectrum_id) in (current_name or "")) or \ |
| (str(spectrum_id) in (current_title or "")): |
| if peaks: |
| |
| peaks_sorted = sorted(peaks, key=lambda x: x[1], reverse=True) |
| return peaks_sorted |
| in_spec = False |
| current_name = None |
| current_title = None |
| peaks = [] |
| elif line_stripped and not line_stripped.startswith(("PEPMASS", "CHARGE", "RTINSECONDS", "SCANS", "SMILES", "INCHIKEY", "FORMULA", "PRECURSOR", "ADDUCT", "INSTRUMENT", "COLLISION", "FOLD", "SIMULATION")): |
| |
| parts = line_stripped.split() |
| if len(parts) >= 2: |
| try: |
| mz = float(parts[0]) |
| intensity = float(parts[1]) |
| if intensity > 0: |
| peaks.append((mz, intensity)) |
| except ValueError: |
| continue |
| |
| return [] |
|
|
|
|
| def main() -> None: |
| args = parse_args() |
| |
| |
| print(f"Loading test data from {args.test_jsonl}") |
| test_data = load_jsonl(Path(args.test_jsonl)) |
| print(f"Loaded {len(test_data)} examples") |
| |
| |
| print(f"Loading spectrum embeddings from {args.spec_embeddings}") |
| spec_embeddings = np.load(args.spec_embeddings) |
| print(f"Loaded embeddings shape: {spec_embeddings.shape}") |
| |
| |
| print(f"Loading FAISS index from {args.faiss_index}") |
| index_path = Path(args.faiss_index) |
| |
| |
| index_file = None |
| for name in ["smiles.index", "index.faiss", "index", "faiss.index"]: |
| candidate = index_path / name if index_path.is_dir() else index_path |
| if candidate.exists(): |
| index_file = candidate |
| break |
| |
| if index_file is None: |
| |
| if index_path.is_dir(): |
| available = list(index_path.glob("*")) |
| raise FileNotFoundError( |
| f"Could not find FAISS index in {index_path}. " |
| f"Available files: {[f.name for f in available]}" |
| ) |
| else: |
| raise FileNotFoundError(f"Could not find FAISS index at {index_path}") |
| |
| index = load_index(index_file) |
| |
| |
| id_to_smiles = {} |
| mapping_file = index_path / "id_to_smiles.pkl" if index_path.is_dir() else index_path.parent / "id_to_smiles.pkl" |
| if mapping_file.exists(): |
| import pickle |
| with open(mapping_file, "rb") as f: |
| id_to_smiles = pickle.load(f) |
| print(f"Loaded {len(id_to_smiles)} SMILES mappings") |
| else: |
| |
| smiles_file = index_path / "smiles.txt" if index_path.is_dir() else index_path.parent / "pubchem_1k.smi" |
| if smiles_file.exists(): |
| from spec_rag.io import load_smiles |
| smiles_list = load_smiles(smiles_file) |
| id_to_smiles = {i: smi for i, smi in enumerate(smiles_list)} |
| print(f"Loaded {len(id_to_smiles)} SMILES from {smiles_file}") |
| |
| print(f"Index loaded with {index.ntotal} vectors") |
| |
| |
| print(f"Initializing Spec-Agent with model: {args.model_name}") |
| if args.use_api: |
| print("Using HuggingFace Inference API (no local model download)") |
| else: |
| print("Using local model loading") |
| |
| agent = SpecAgent( |
| model_name=args.model_name, |
| use_api=args.use_api, |
| api_token=args.api_token, |
| use_unsloth=args.use_unsloth, |
| max_iterations=args.max_iterations, |
| mass_tolerance_ppm=args.mass_tolerance_ppm, |
| device=args.device, |
| load_in_4bit=args.load_in_4bit, |
| use_selfies=args.use_selfies, |
| ) |
| print("✓ Agent initialized") |
| |
| |
| predictions = [] |
| |
| for i, example in enumerate(tqdm(test_data[:100], desc="Running Spec-Agent")): |
| spectrum_id = example.get("spectrum_id", str(i)) |
| |
| |
| spec_idx = int(spectrum_id) if str(spectrum_id).isdigit() else i |
| if spec_idx >= len(spec_embeddings): |
| spec_idx = i % len(spec_embeddings) |
| |
| spec_emb = spec_embeddings[spec_idx] |
| |
| |
| from spec_rag.faiss_index import index_search |
| distances, indices = index_search(index, spec_emb.reshape(1, -1), args.top_k) |
| rag_smiles = [id_to_smiles.get(int(idx), "") for idx in indices[0] if int(idx) in id_to_smiles] |
| rag_smiles = [smi for smi in rag_smiles if smi] |
| |
| |
| target_mass = example.get("precursor_mz") |
| if target_mass is None: |
| |
| input_text = example.get("input_text", "") |
| |
| import re |
| mass_match = re.search(r'(\d+\.\d+)\s*(?:Da|m/z|M\+)', input_text) |
| if mass_match: |
| target_mass = float(mass_match.group(1)) |
| |
| |
| spectrum_peaks = None |
| |
| |
| if "peaks" in example: |
| peaks_data = example["peaks"] |
| |
| if isinstance(peaks_data, list) and len(peaks_data) > 0: |
| if isinstance(peaks_data[0], (list, tuple)) and len(peaks_data[0]) >= 2: |
| |
| spectrum_peaks = [(float(p[0]), float(p[1])) for p in peaks_data if len(p) >= 2] |
| elif isinstance(peaks_data[0], (int, float)): |
| |
| spectrum_peaks = [float(p) for p in peaks_data] |
| elif "spectrum_peaks" in example: |
| peaks_data = example["spectrum_peaks"] |
| if isinstance(peaks_data, list): |
| |
| if peaks_data and isinstance(peaks_data[0], (list, tuple)) and len(peaks_data[0]) >= 2: |
| spectrum_peaks = [(float(p[0]), float(p[1])) for p in peaks_data if len(p) >= 2] |
| else: |
| spectrum_peaks = [float(p) for p in peaks_data if isinstance(p, (int, float))] |
| |
| |
| if (spectrum_peaks is None or len(spectrum_peaks) == 0) and args.mgf_path: |
| mgf_path = Path(args.mgf_path) |
| if mgf_path.exists(): |
| spectrum_peaks = load_mgf_peaks(mgf_path, spectrum_id) |
| if spectrum_peaks: |
| if i < 3: |
| print(f" ✓ Loaded {len(spectrum_peaks)} peaks from MGF for spectrum {spectrum_id}") |
| |
| |
| if spectrum_peaks is None or len(spectrum_peaks) == 0: |
| input_text = example.get("input_text", "") |
| import re |
| |
| |
| peak_matches = [] |
| |
| |
| peak_matches.extend(re.findall(r'(?:m/z|mz|Da)[:\s]+(\d+\.?\d*)', input_text, re.IGNORECASE)) |
| peak_matches.extend(re.findall(r'(\d+\.?\d*)\s*(?:m/z|mz|Da)', input_text, re.IGNORECASE)) |
| |
| |
| all_numbers = re.findall(r'\b(\d{2,4}\.?\d*)\b', input_text) |
| peak_matches.extend([n for n in all_numbers if 50 <= float(n) <= 2000]) |
| |
| if peak_matches: |
| |
| spectrum_peaks = sorted(set(float(p) for p in peak_matches), reverse=True) |
| if spectrum_peaks and i < 3: |
| print(f" ✓ Extracted {len(spectrum_peaks)} peaks from input_text for spectrum {spectrum_id} (no intensity)") |
| |
| |
| if (spectrum_peaks is None or len(spectrum_peaks) == 0) and i < 3: |
| print(f" ⚠ No peaks found for spectrum {spectrum_id} (mgf_path={args.mgf_path})") |
| |
| |
| result = agent.predict( |
| spectrum_peaks=spectrum_peaks, |
| rag_context=rag_smiles, |
| target_mass=target_mass, |
| ) |
| |
| |
| pred_entry = { |
| "spectrum_id": spectrum_id, |
| "predicted_smiles": result["smiles"], |
| "status": result["status"], |
| "iterations": result["iterations"], |
| "ground_truth": example.get("target_text", ""), |
| "rag_context": rag_smiles, |
| } |
| |
| predictions.append(pred_entry) |
| |
| |
| output_path = Path(args.output_json) |
| output_path.parent.mkdir(parents=True, exist_ok=True) |
| |
| with open(output_path, "w") as f: |
| for pred in predictions: |
| f.write(json.dumps(pred) + "\n") |
| |
| print(f"\n✓ Saved {len(predictions)} predictions to {output_path}") |
| |
| |
| success_count = sum(1 for p in predictions if p["status"] == "success") |
| print(f"\nSummary:") |
| print(f" Total: {len(predictions)}") |
| print(f" Success: {success_count} ({100*success_count/len(predictions):.1f}%)") |
| print(f" Failed/Max iterations: {len(predictions) - success_count}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|