File size: 12,257 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 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 | #!/usr/bin/env python
"""
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"):
# Save previous spectrum if exists
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
# Handle last spectrum if file doesn't end with END IONS
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."""
# Build system message
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"""
# Build user message
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 response
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 = []
# Try to extract from "Context: Reference Molecules: [...]" format
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]
# Extract SMILES from [SMILES] format
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()
# Load data
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")
# Check if we need to retrieve RAG context or extract from input_text
use_existing_context = False
if train_data and "input_text" in train_data[0]:
# Check if input_text contains RAG context
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")
# Load index only if we need to retrieve
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)
# Find FAISS index file
index_path = Path(args.faiss_index)
index_file = None
if index_path.is_dir():
# Try different possible file names
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")
# Pre-load all MGF peaks if MGF path is provided
mgf_peaks_dict = {}
if args.mgf_path:
mgf_peaks_dict = load_all_mgf_peaks(args.mgf_path)
# Process examples
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
# Calculate target mass
target_mass = calculate_target_mass(target_smiles)
if not target_mass:
continue
# Get RAG context
rag_smiles = []
if use_existing_context:
# Extract from input_text
rag_smiles = extract_rag_context_from_input(input_text)
if not rag_smiles:
continue
# Limit to top_k
rag_smiles = rag_smiles[:args.top_k]
else:
# Retrieve from index
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
# Get spectrum peaks from pre-loaded dict
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
# Build fine-tuning example
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)
# Save fine-tuning data
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()
|