| |
| """ |
| Prepare fine-tuning data for Spec-Agent from RAG dataset. |
| |
| This script converts the RAG dataset into a format suitable for fine-tuning |
| Llama-3 on molecular structure prediction tasks. |
| """ |
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import sys |
| from pathlib import Path |
| from typing import List, Dict, Any |
|
|
| ROOT = Path(__file__).resolve().parents[1] |
| if str(ROOT) not in sys.path: |
| sys.path.insert(0, str(ROOT)) |
|
|
| from spec_rag.io import load_embeddings, load_smiles |
| from spec_rag.faiss_index import load_index |
| from spec_rag.retrieval import search_index |
|
|
|
|
| def parse_args() -> argparse.Namespace: |
| parser = argparse.ArgumentParser(description="Prepare fine-tuning data for Spec-Agent") |
| parser.add_argument( |
| "--train-jsonl", |
| type=Path, |
| required=True, |
| help="Training JSONL file (from build_rag_dataset.py)", |
| ) |
| parser.add_argument( |
| "--spec-embeddings", |
| type=Path, |
| help="Path to spectrum embeddings .npy file (only needed if RAG context not in input_text)", |
| ) |
| parser.add_argument( |
| "--faiss-index", |
| type=Path, |
| help="Path to FAISS index directory (only needed if RAG context not in input_text)", |
| ) |
| parser.add_argument( |
| "--smiles-path", |
| type=Path, |
| help="Path to SMILES file used for indexing (only needed if RAG context not in input_text)", |
| ) |
| parser.add_argument( |
| "--mgf-path", |
| type=Path, |
| help="Path to MGF file for extracting peaks", |
| ) |
| parser.add_argument( |
| "--output-jsonl", |
| type=Path, |
| required=True, |
| help="Output JSONL file for fine-tuning", |
| ) |
| parser.add_argument( |
| "--top-k", |
| type=int, |
| default=5, |
| help="Number of RAG references to include (default: 5)", |
| ) |
| parser.add_argument( |
| "--max-examples", |
| type=int, |
| help="Maximum number of examples to process (for testing)", |
| ) |
| return parser.parse_args() |
|
|
|
|
| def load_all_mgf_peaks(mgf_path: Path) -> Dict[int, List[tuple[float, float]]]: |
| """Load all spectrum peaks from MGF file into memory (indexed by spectrum index).""" |
| peaks_dict = {} |
| |
| print(f"Loading all peaks from MGF file: {mgf_path}") |
| with open(mgf_path, "r") as f: |
| spec_count = -1 |
| current_peaks = [] |
| in_spec = False |
| |
| for line in f: |
| line_stripped = line.strip() |
| if line_stripped.startswith("BEGIN IONS"): |
| |
| if in_spec and current_peaks: |
| peaks_dict[spec_count] = sorted(current_peaks, key=lambda x: x[1], reverse=True) |
| spec_count += 1 |
| in_spec = True |
| current_peaks = [] |
| elif in_spec: |
| if line_stripped.startswith("END IONS"): |
| if current_peaks: |
| peaks_dict[spec_count] = sorted(current_peaks, key=lambda x: x[1], reverse=True) |
| in_spec = False |
| current_peaks = [] |
| 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: |
| current_peaks.append((mz, intensity)) |
| except ValueError: |
| continue |
| |
| |
| if in_spec and current_peaks: |
| peaks_dict[spec_count] = sorted(current_peaks, key=lambda x: x[1], reverse=True) |
| |
| print(f"Loaded {len(peaks_dict)} spectra from MGF file") |
| return peaks_dict |
|
|
|
|
| def calculate_target_mass(smiles: str) -> float | None: |
| """Calculate molecular mass from SMILES.""" |
| try: |
| from rdkit import Chem |
| from rdkit.Chem import Descriptors |
| mol = Chem.MolFromSmiles(smiles) |
| if mol: |
| return Descriptors.ExactMolWt(mol) |
| except: |
| pass |
| return None |
|
|
|
|
| def build_finetune_prompt( |
| spectrum_peaks: List[tuple[float, float]] | None, |
| rag_context: List[str], |
| target_mass: float | None, |
| target_smiles: str, |
| ) -> Dict[str, Any]: |
| """Build a fine-tuning prompt in chat format.""" |
| |
| |
| system_content = """You are an expert mass spectrometrist and computational chemist specializing in de novo molecular structure elucidation from mass spectrometry data. |
| |
| TASK: Predict the complete molecular structure (SMILES) from mass spectrum data. |
| |
| CRITICAL REQUIREMENTS: |
| 1. Generate COMPLEX molecules (30-100 atoms), NOT simple molecules |
| 2. Use reference molecules as structural templates |
| 3. Match target molecular mass within 10 Da |
| 4. Output ONLY valid SMILES strings |
| |
| WORKFLOW: |
| 1. Analyze target mass to estimate atom count |
| 2. Select best reference molecule as template |
| 3. Modify template to match target mass |
| 4. Validate structure""" |
| |
| |
| user_parts = [] |
| |
| if target_mass: |
| estimated_atoms = int(target_mass / 14) |
| user_parts.append(f"Target molecular mass: {target_mass:.4f} Da (estimated {estimated_atoms} atoms)") |
| |
| if spectrum_peaks and len(spectrum_peaks) > 0: |
| peaks_str = ', '.join(f'{mz:.2f} (intensity: {intensity:.3f})' for mz, intensity in spectrum_peaks[:20]) |
| user_parts.append(f"Major spectrum peaks (m/z with intensity): {peaks_str}") |
| |
| if rag_context: |
| user_parts.append("\nReference molecules (structural templates):") |
| for i, smiles in enumerate(rag_context[:5], 1): |
| user_parts.append(f" {i}. {smiles}") |
| user_parts.append("\nPredict the molecular structure (SMILES) matching the target mass.") |
| |
| user_content = "\n".join(user_parts) |
| |
| |
| assistant_content = target_smiles |
| |
| return { |
| "messages": [ |
| {"role": "system", "content": system_content}, |
| {"role": "user", "content": user_content}, |
| {"role": "assistant", "content": assistant_content}, |
| ] |
| } |
|
|
|
|
| def extract_rag_context_from_input(input_text: str) -> List[str]: |
| """Extract RAG context SMILES from input_text field.""" |
| import re |
| rag_smiles = [] |
| |
| |
| if "Context: Reference Molecules:" in input_text: |
| context_part = input_text.split("Context: Reference Molecules:")[1] |
| if "Target:" in context_part: |
| context_part = context_part.split("Target:")[0] |
| |
| |
| smiles_pattern = r'\[([^\]]+)\]' |
| matches = re.findall(smiles_pattern, context_part) |
| rag_smiles = [s.strip() for s in matches if s.strip()] |
| |
| return rag_smiles |
|
|
|
|
| def main() -> None: |
| args = parse_args() |
| |
| |
| print("Loading data...") |
| train_data = [] |
| with open(args.train_jsonl, "r") as f: |
| for line in f: |
| if line.strip(): |
| train_data.append(json.loads(line)) |
| |
| if args.max_examples: |
| train_data = train_data[:args.max_examples] |
| |
| print(f"Loaded {len(train_data)} training examples") |
| |
| |
| use_existing_context = False |
| if train_data and "input_text" in train_data[0]: |
| |
| sample_input = train_data[0].get("input_text", "") |
| if "Context: Reference Molecules:" in sample_input: |
| use_existing_context = True |
| print("Found RAG context in input_text, will extract directly (no need to retrieve)") |
| else: |
| print("No RAG context in input_text, will retrieve from index") |
| |
| |
| index = None |
| smiles_list = None |
| spec_embeddings = None |
| |
| if not use_existing_context: |
| print("Loading embeddings and index for retrieval...") |
| spec_embeddings = load_embeddings(args.spec_embeddings) |
| |
| |
| index_path = Path(args.faiss_index) |
| index_file = None |
| if index_path.is_dir(): |
| |
| for name in ["smiles.index", "index.faiss", "index", "faiss.index"]: |
| candidate = index_path / name |
| if candidate.exists(): |
| index_file = candidate |
| break |
| if index_file is None: |
| 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: |
| index_file = index_path |
| |
| index = load_index(index_file) |
| smiles_list = load_smiles(args.smiles_path) |
| |
| print(f"Index has {index.ntotal} vectors") |
| print(f"SMILES list has {len(smiles_list)} molecules") |
| |
| |
| mgf_peaks_dict = {} |
| if args.mgf_path: |
| mgf_peaks_dict = load_all_mgf_peaks(args.mgf_path) |
| |
| |
| finetune_examples = [] |
| |
| for i, example in enumerate(train_data): |
| if i % 1000 == 0: |
| print(f"Processing example {i}/{len(train_data)}... ({len(finetune_examples)} created so far)") |
| |
| spectrum_id = example.get("spectrum_id", str(i)) |
| target_smiles = example.get("target_text", "") |
| input_text = example.get("input_text", "") |
| |
| if not target_smiles: |
| continue |
| |
| |
| target_mass = calculate_target_mass(target_smiles) |
| if not target_mass: |
| continue |
| |
| |
| rag_smiles = [] |
| if use_existing_context: |
| |
| rag_smiles = extract_rag_context_from_input(input_text) |
| if not rag_smiles: |
| continue |
| |
| rag_smiles = rag_smiles[:args.top_k] |
| else: |
| |
| try: |
| spec_idx = int(spectrum_id) |
| if spec_idx >= len(spec_embeddings): |
| continue |
| |
| query_embedding = spec_embeddings[spec_idx:spec_idx+1] |
| scores, indices = search_index(index, query_embedding, k=args.top_k) |
| |
| for idx_row in indices: |
| for idx in idx_row: |
| if 0 <= idx < len(smiles_list): |
| rag_smiles.append(smiles_list[idx]) |
| |
| if not rag_smiles: |
| continue |
| except (ValueError, IndexError): |
| continue |
| |
| |
| spectrum_peaks = None |
| if mgf_peaks_dict: |
| try: |
| spec_idx = int(spectrum_id) |
| spectrum_peaks = mgf_peaks_dict.get(spec_idx) |
| except (ValueError, IndexError): |
| pass |
| |
| |
| finetune_example = build_finetune_prompt( |
| spectrum_peaks=spectrum_peaks, |
| rag_context=rag_smiles, |
| target_mass=target_mass, |
| target_smiles=target_smiles, |
| ) |
| |
| finetune_examples.append(finetune_example) |
| |
| |
| print(f"\nSaving {len(finetune_examples)} fine-tuning examples to {args.output_jsonl}...") |
| with open(args.output_jsonl, "w") as f: |
| for example in finetune_examples: |
| f.write(json.dumps(example) + "\n") |
| |
| print(f"Done! Created {len(finetune_examples)} fine-tuning examples.") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|