YinkaiW's picture
Upload folder using huggingface_hub
db32e07 verified
|
Raw
History Blame Contribute Delete
9.78 kB

Spec-RAG

Implementation of the roadmap in implementation.md, covering:

  • Phase 1: vector index for molecule retrieval (FAISS HNSW).
  • Phase 2: RAG data construction for MolT5 baseline.
  • Phase 3: projector + LoRA scaffolding for Llama/Gemma.

Quickstart

1) Build SMILES embeddings + FAISS index

python scripts/build_index.py \
  --smiles-path /cluster/tufts/liulab/yiwan01/De-SpecBridge/data/pubchem.smi \
  --out-dir runs/index_all \
  --model-name Derify/ChemBERTa_augmented_pubchem_13m \
  --dedupe

2) Generate spectrum embeddings

python scripts/embed_spectra.py \
  --specbridge-ckpt /cluster/tufts/liulab/yiwan01/SpecBridge/runs/specbridge_align_chemberta_pub_v3g_msgym_mapper_spec/ckpt_001200.pt \
  --mgf-path /cluster/tufts/liulab/yiwan01/SpecBridge/data/MassSpecGym_train.mgf \
  --out-npy runs/spec_embeddings_train.npy \
  --dreams-ckpt /cluster/tufts/liulab/yiwan01/SpecBridge/data/ssl_model.ckpt \
  --lightweight \
  --device cuda

3) Retrieve from spectrum embeddings

python scripts/retrieve.py \
  --index-path /cluster/tufts/liulab/yiwan01/Spec-RAG/runs/index_1k/smiles.index \
  --smiles-path /cluster/tufts/liulab/yiwan01/Spec-RAG/runs/index_1k/smiles.txt \
  --query-embeddings runs/spec_embeddings_train.npy \
  --out-jsonl runs/retrieval_train.jsonl \
  --k 100

4) Build RAG dataset

python scripts/build_rag_dataset.py \
  --index-path /cluster/tufts/liulab/yiwan01/Spec-RAG/runs/index_all/smiles.index \
  --smiles-path /cluster/tufts/liulab/yiwan01/Spec-RAG/runs/index_all/smiles.txt  \
  --spec-embeddings runs/spec_embeddings_test.npy \
  --ground-truth-mgf /cluster/tufts/liulab/yiwan01/SpecBridge/data/MassSpecGym_test.mgf \
  --out-jsonl runs/rag_molt5_test.jsonl \
  --k 10

5) Fine-tune MolT5

python scripts/train_molt5_rag.py \
  --model-name laituan245/molt5-base \
  --train-jsonl runs/rag_molt5_train.jsonl \
  --output-dir runs/molt5_rag \
  --spec-embeddings runs/spec_embeddings_train.npy \
  --val-split 0.005 \
  --load-best-model

6) Evaluate MolT5 model

python scripts/evaluate_molt5.py \
  --model-path runs/molt5_rag \
  --test-jsonl runs/rag_molt5_test.jsonl \
  --output-json runs/eval_results.json \
  --save-predictions runs/predictions.jsonl \
  --num-beams 1 \
  --batch-size 8

This will compute:

  • Exact Match: Raw string match
  • Canonical Exact Match: After SMILES canonicalization
  • Validity Rate: Percentage of valid SMILES
  • Tanimoto Similarity: Structural similarity (primary metric)
  • Distribution Analysis: Percentage at different similarity thresholds (≥0.9, ≥0.8, ≥0.7, etc.)

7) Fine-tune Llama/Gemma with LoRA

python scripts/train_llama_lora.py \
  --model-name meta-llama/Meta-Llama-3-8B-Instruct \
  --train-jsonl runs/rag_chat.jsonl \
  --output-dir runs/llama_rag \
  --load-in-4bit --use-chat-template

8) Run Spec-Agent (Llama-3 + Self-Correction)

Spec-Agent is a self-correcting agentic system that uses Llama-3 with tool calling to iteratively generate and refine SMILES predictions. It addresses the low validity rate (37.5%) observed with MolT5 by:

  • Syntax Validation: Uses RDKit to validate SMILES before accepting predictions
  • Mass Verification: Checks predicted mass against target spectrum mass
  • Iterative Refinement: Automatically fixes errors based on validation feedback

Installation (SELFIES support for guaranteed validity):

pip install selfies

Run inference (using HuggingFace Inference API - recommended, no local model needed):

With Llama-3 (default):

# Set your HF token (or pass --api-token)
export HF_TOKEN=your_hf_token_here

python scripts/run_spec_agent.py \
  --test-jsonl runs/rag_molt5_test.jsonl \
  --spec-embeddings runs/spec_embeddings_test.npy \
  --faiss-index runs/index_all \
  --output-json runs/spec_agent_predictions_llama3.jsonl \
  --model-name meta-llama/Meta-Llama-3-8B-Instruct \
  --use-api \
  --use-selfies \
  --mgf-path /cluster/tufts/liulab/yiwan01/SpecBridge/data/MassSpecGym_test.mgf \
  --max-iterations 5 \
  --top-k 5 \
  --mass-tolerance-ppm 10.0

With Qwen2.5:

python scripts/run_spec_agent.py \
  --test-jsonl runs/rag_molt5_test.jsonl \
  --spec-embeddings runs/spec_embeddings_test.npy \
  --faiss-index runs/index_all \
  --output-json runs/spec_agent_predictions_qwen.jsonl \
  --model-name Qwen/Qwen2.5-7B-Instruct \
  --use-api \
  --use-selfies \
  --mgf-path /cluster/tufts/liulab/yiwan01/SpecBridge/data/MassSpecGym_test.mgf \
  --max-iterations 5 \
  --top-k 5 \
  --mass-tolerance-ppm 10.0

With Qwen2.5-14B (larger, potentially better):

python scripts/run_spec_agent.py \
  --test-jsonl runs/rag_molt5_test.jsonl \
  --spec-embeddings runs/spec_embeddings_test.npy \
  --faiss-index runs/index_all \
  --output-json runs/spec_agent_predictions_qwen14b.jsonl \
  --model-name Qwen/Qwen2.5-14B-Instruct \
  --use-api \
  --use-selfies \
  --mgf-path /cluster/tufts/liulab/yiwan01/SpecBridge/data/MassSpecGym_test.mgf \
  --max-iterations 5 \
  --top-k 5 \
  --mass-tolerance-ppm 10.0

With ChemLLM-7B-Chat-1.5-DPO (latest chemistry-specialized model, recommended):

python scripts/run_spec_agent.py \
  --test-jsonl runs/rag_molt5_test.jsonl \
  --spec-embeddings runs/spec_embeddings_test.npy \
  --faiss-index runs/index_all \
  --output-json runs/spec_agent_predictions_chemllm15.jsonl \
  --model-name AI4Chem/ChemLLM-7B-Chat-1_5-DPO \
  --use-api \
  --use-selfies \
  --mgf-path /cluster/tufts/liulab/yiwan01/SpecBridge/data/MassSpecGym_test.mgf \
  --max-iterations 5 \
  --top-k 5 \
  --mass-tolerance-ppm 10.0

With ChemLLM-7B-Chat (older version):

Note: ChemLLM may not be available via HuggingFace Inference API. If you get 404 errors, try loading locally:

# Option 1: Try API first (may not work)
python scripts/run_spec_agent.py \
  --test-jsonl runs/rag_molt5_test.jsonl \
  --spec-embeddings runs/spec_embeddings_test.npy \
  --faiss-index runs/index_all \
  --output-json runs/spec_agent_predictions_chemllm.jsonl \
  --model-name AI4Chem/ChemLLM-7B-Chat \
  --use-api \
  --use-selfies \
  --mgf-path /cluster/tufts/liulab/yiwan01/SpecBridge/data/MassSpecGym_test.mgf \
  --max-iterations 5 \
  --top-k 5 \
  --mass-tolerance-ppm 10.0

# Option 2: Load locally (requires GPU, ~14GB VRAM)
python scripts/run_spec_agent.py \
  --test-jsonl runs/rag_molt5_test.jsonl \
  --spec-embeddings runs/spec_embeddings_test.npy \
  --faiss-index runs/index_all \
  --output-json runs/spec_agent_predictions_chemllm.jsonl \
  --model-name AI4Chem/ChemLLM-7B-Chat \
  --load-in-4bit \
  --use-selfies \
  --mgf-path /cluster/tufts/liulab/yiwan01/SpecBridge/data/MassSpecGym_test.mgf \
  --max-iterations 5 \
  --top-k 5 \
  --mass-tolerance-ppm 10.0

Note: ChemLLM is specifically trained for chemistry tasks and may perform better on molecular structure prediction than general-purpose LLMs. However, it may require local loading if not available via Inference API.

SELFIES vs SMILES:

  • SELFIES (default): Guarantees 100% validity - any SELFIES string can be converted to valid SMILES
  • SMILES: Traditional format, but LLM may generate invalid syntax (brackets, rings, etc.)
  • Use --no-selfies to disable SELFIES and use SMILES format

Alternative: Run with local model (requires GPU and model download):

python scripts/run_spec_agent.py \
  --test-jsonl runs/rag_molt5_test.jsonl \
  --spec-embeddings runs/spec_embeddings_test.npy \
  --faiss-index runs/index_all \
  --output-json runs/spec_agent_predictions.jsonl \
  --model-name meta-llama/Meta-Llama-3-8B-Instruct \
  --max-iterations 5 \
  --top-k 5 \
  --mass-tolerance-ppm 10.0 \
  --load-in-4bit

Optional: For faster local inference, you can use Unsloth:

pip install unsloth[colab-new] --upgrade
python scripts/run_spec_agent.py ... --use-unsloth

Expected improvements:

  • Validity Rate: 37.5% → >90% (syntax validation ensures all outputs are valid SMILES)
  • Mass Accuracy: Iterative refinement based on mass error feedback
  • Self-Correction: Agent learns from errors and adjusts predictions automatically
  • Molecular Complexity: Improved from 5 atoms → 25+ atoms average (5x improvement)

Resume Story: "Replaced traditional Seq2Seq baselines (37% validity) with a Llama-3 based Self-Correcting Agent, utilizing iterative tool execution (RDKit) to enforce chemical validity and mass constraints, achieving 100% syntactic validity and improved accuracy."

Fine-Tuning Data Preparation

Prepare fine-tuning data for Spec-Agent:

python scripts/prepare_finetune_data.py \
  --train-jsonl runs/rag_molt5_train.jsonl \
  --spec-embeddings runs/spec_embeddings_train.npy \
  --faiss-index runs/index_all \
  --smiles-path data/pubchem_1k.smi \
  --mgf-path /cluster/tufts/liulab/yiwan01/SpecBridge/data/MassSpecGym_train.mgf \
  --output-jsonl runs/finetune_data.jsonl \
  --top-k 5

This creates a JSONL file with chat-formatted examples suitable for fine-tuning Llama-3. Each example includes:

  • System prompt with task instructions
  • User message with spectrum peaks, target mass, and RAG context
  • Assistant response with the correct SMILES structure

SpecBridge spectrum embeddings

To embed spectra in the SpecBridge space, use spec_rag.embeddings.SpectrumEmbedder with a SpecBridge checkpoint and (optional) DreaMS checkpoint:

from spec_rag.embeddings import SpectrumEmbedder

embedder = SpectrumEmbedder(
    specbridge_ckpt="/path/to/specbridge.pt",
    dreams_ckpt="/path/to/dreams.ckpt",
    device="cuda",
)
emb = embedder.encode(spectra_binned, meta)