pubchem-faiss-library / code /scripts /evaluate_molt5.py
YinkaiW's picture
Upload folder using huggingface_hub
db32e07 verified
Raw
History Blame Contribute Delete
14.7 kB
#!/usr/bin/env python
"""
Comprehensive evaluation script for MolT5 RAG model.
Computes multiple metrics including Tanimoto similarity, validity, exact match, etc.
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
from typing import Dict, List, Tuple
import numpy as np
import torch
from tqdm import tqdm
ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
from spec_rag.io import load_embeddings
from spec_rag.molt5_with_embeddings import MolT5WithEmbeddings
def load_jsonl(path: Path) -> List[dict]:
"""Load JSONL file."""
data = []
with open(path, "r") as f:
for line in f:
line = line.strip()
if line:
data.append(json.loads(line))
return data
def compute_molecular_metrics(
predictions: List[str],
ground_truths: List[str]
) -> Dict[str, float]:
"""
Compute comprehensive molecular generation metrics.
Returns:
Dictionary with metrics:
- exact_match: Raw string exact match
- canonical_exact_match: After canonicalization
- validity_rate: Percentage of valid SMILES
- tanimoto_similarity: Mean Tanimoto similarity
- tanimoto_similarity_valid: Mean Tanimoto (only valid predictions)
- top1_tanimoto: Mean max Tanimoto in top-1
- top10_tanimoto: Mean max Tanimoto in top-10 (if multiple predictions)
"""
try:
from rdkit import Chem
from rdkit.Chem import AllChem, DataStructs
from rdkit import rdBase
rdBase.DisableLog("rdApp.*")
except ImportError:
raise ImportError("RDKit is required for molecular metrics. Install with: conda install -c conda-forge rdkit")
if len(predictions) != len(ground_truths):
raise ValueError(f"Mismatch: {len(predictions)} predictions vs {len(ground_truths)} ground truths")
exact_matches = 0
canonical_matches = 0
valid_count = 0
tanimoto_sum = 0.0
tanimoto_valid_sum = 0.0
valid_predictions = []
valid_ground_truths = []
# For detailed analysis
tanimoto_scores = []
validity_flags = []
for pred, gt in zip(predictions, ground_truths):
pred = pred.strip()
gt = gt.strip()
# Exact match (raw string)
if pred == gt:
exact_matches += 1
# Try to parse as molecules
try:
mol_pred = Chem.MolFromSmiles(pred)
mol_gt = Chem.MolFromSmiles(gt)
if mol_pred is not None:
valid_count += 1
validity_flags.append(1)
pred_canon = Chem.MolToSmiles(mol_pred, canonical=True)
valid_predictions.append(mol_pred)
else:
validity_flags.append(0)
pred_canon = None
if mol_gt is not None:
gt_canon = Chem.MolToSmiles(mol_gt, canonical=True)
valid_ground_truths.append(mol_gt)
else:
gt_canon = None
# Canonical exact match
if pred_canon and gt_canon and pred_canon == gt_canon:
canonical_matches += 1
# Tanimoto similarity
if mol_pred is not None and mol_gt is not None:
fp_pred = AllChem.GetMorganFingerprintAsBitVect(mol_pred, radius=2, nBits=2048)
fp_gt = AllChem.GetMorganFingerprintAsBitVect(mol_gt, radius=2, nBits=2048)
tanimoto = DataStructs.TanimotoSimilarity(fp_pred, fp_gt)
tanimoto_sum += tanimoto
tanimoto_scores.append(tanimoto)
if mol_pred is not None:
tanimoto_valid_sum += tanimoto
else:
tanimoto_scores.append(0.0)
except Exception as e:
# Invalid SMILES or parsing error
validity_flags.append(0)
tanimoto_scores.append(0.0)
continue
n = len(predictions)
metrics = {
"exact_match": exact_matches / n if n > 0 else 0.0,
"canonical_exact_match": canonical_matches / n if n > 0 else 0.0,
"validity_rate": valid_count / n if n > 0 else 0.0,
"tanimoto_similarity": tanimoto_sum / n if n > 0 else 0.0,
"tanimoto_similarity_valid": tanimoto_valid_sum / valid_count if valid_count > 0 else 0.0,
"n_total": n,
"n_valid": valid_count,
}
# Additional statistics
if tanimoto_scores:
metrics["tanimoto_mean"] = np.mean(tanimoto_scores)
metrics["tanimoto_std"] = np.std(tanimoto_scores)
metrics["tanimoto_median"] = np.median(tanimoto_scores)
metrics["tanimoto_min"] = np.min(tanimoto_scores)
metrics["tanimoto_max"] = np.max(tanimoto_scores)
# Distribution analysis
metrics["tanimoto_ge_0.9"] = sum(1 for t in tanimoto_scores if t >= 0.9) / n
metrics["tanimoto_ge_0.8"] = sum(1 for t in tanimoto_scores if t >= 0.8) / n
metrics["tanimoto_ge_0.7"] = sum(1 for t in tanimoto_scores if t >= 0.7) / n
metrics["tanimoto_ge_0.5"] = sum(1 for t in tanimoto_scores if t >= 0.5) / n
metrics["tanimoto_ge_0.3"] = sum(1 for t in tanimoto_scores if t >= 0.3) / n
return metrics
def generate_predictions(
model,
tokenizer,
inputs: List[str],
spectrum_embeddings: torch.Tensor | None = None,
max_length: int = 512,
num_beams: int = 1,
batch_size: int = 8,
) -> List[str]:
"""Generate predictions in batches with spectrum embeddings."""
predictions = []
for i in tqdm(range(0, len(inputs), batch_size), desc="Generating predictions"):
batch = inputs[i:i + batch_size]
batch_embeddings = None
if spectrum_embeddings is not None:
batch_embeddings = spectrum_embeddings[i:i + batch_size].to(model.device)
# Tokenize inputs
encoded = tokenizer(
batch,
return_tensors="pt",
padding=True,
truncation=True,
max_length=max_length,
).to(model.device)
# Generate
with torch.no_grad():
if batch_embeddings is not None:
# Use model's generate with embeddings
outputs = model.generate(
**encoded,
spectrum_embeddings=batch_embeddings,
max_length=max_length,
num_beams=num_beams,
do_sample=(num_beams == 1),
pad_token_id=tokenizer.pad_token_id,
)
else:
outputs = model.generate(
**encoded,
max_length=max_length,
num_beams=num_beams,
do_sample=(num_beams == 1),
pad_token_id=tokenizer.pad_token_id,
)
# Decode
batch_preds = tokenizer.batch_decode(outputs, skip_special_tokens=True)
predictions.extend(batch_preds)
return predictions
def main():
parser = argparse.ArgumentParser(description="Evaluate MolT5 RAG model")
parser.add_argument("--model-path", required=True, help="Path to trained model directory")
parser.add_argument("--test-jsonl", required=True, help="Test JSONL file")
parser.add_argument("--output-json", default=None, help="Output JSON file for results")
parser.add_argument("--max-length", type=int, default=512, help="Max generation length")
parser.add_argument("--num-beams", type=int, default=1, help="Beam search size (1=greedy)")
parser.add_argument("--batch-size", type=int, default=8, help="Batch size for generation")
parser.add_argument("--device", default="cuda", help="Device (cuda/cpu)")
parser.add_argument("--save-predictions", default=None, help="Save predictions to JSONL file")
parser.add_argument("--spec-embeddings", required=True, help="Path to spectrum embeddings .npy file (required for generation)")
parser.add_argument("--prompt-len", type=int, default=10, help="Number of soft prompt tokens (must match training)")
args = parser.parse_args()
print("=" * 60)
print("MolT5 RAG Model Evaluation")
print("=" * 60)
# Load spectrum embeddings (required)
print(f"\nLoading spectrum embeddings from {args.spec_embeddings}...")
spec_embeddings = load_embeddings(args.spec_embeddings)
print(f"Loaded {len(spec_embeddings)} spectrum embeddings (shape: {spec_embeddings.shape})")
embedding_dim = spec_embeddings.shape[1]
# Load model and tokenizer
print(f"\nLoading model from {args.model_path}...")
base_model = AutoModelForSeq2SeqLM.from_pretrained(args.model_path)
tokenizer = AutoTokenizer.from_pretrained(args.model_path)
# Wrap model with embedding injection
print(f"Wrapping model with spectrum embedding injection (dim={embedding_dim}, prompt_len={args.prompt_len})")
model = MolT5WithEmbeddings(
base_model=base_model,
embedding_dim=embedding_dim,
prompt_len=args.prompt_len,
freeze_base=True, # Freeze during evaluation
)
model.to(args.device)
model.eval()
print(f"Model loaded on {args.device}")
# Load test data
print(f"\nLoading test data from {args.test_jsonl}...")
test_data = load_jsonl(Path(args.test_jsonl))
print(f"Loaded {len(test_data)} test examples")
# Extract inputs, ground truths, and spectrum IDs
# Remove "Target: ..." from input_text if present (data leakage prevention)
inputs = []
ground_truths = []
spectrum_ids = []
for item in test_data[:1000]:
input_text = item["input_text"]
# Remove target if present
if "\nTarget:" in input_text:
input_text = input_text.split("\nTarget:")[0].rstrip()
inputs.append(input_text)
ground_truths.append(item["target_text"])
# Get spectrum_id
spectrum_id = item.get("spectrum_id", len(spectrum_ids)) # Default to index if missing
spectrum_ids.append(spectrum_id)
# Map spectrum_ids to embeddings
print(f"\nMapping spectrum IDs to embeddings...")
try:
indices = [int(sid) if isinstance(sid, (int, str)) and str(sid).isdigit() else i
for i, sid in enumerate(spectrum_ids)]
indices = [min(i, len(spec_embeddings) - 1) for i in indices]
eval_embeddings = torch.tensor([spec_embeddings[i] for i in indices], dtype=torch.float32)
print(f" Mapped {len(eval_embeddings)} embeddings (shape: {eval_embeddings.shape})")
except Exception as e:
raise ValueError(f"Failed to map spectrum IDs to embeddings: {e}")
print(f"\nGenerating predictions with spectrum embeddings...")
print(f" Batch size: {args.batch_size}")
print(f" Max length: {args.max_length}")
print(f" Num beams: {args.num_beams}")
print(f" Prompt length: {args.prompt_len}")
print(f" Embedding dimension: {embedding_dim}")
predictions = generate_predictions(
model,
tokenizer,
inputs,
spectrum_embeddings=eval_embeddings,
max_length=args.max_length,
num_beams=args.num_beams,
batch_size=args.batch_size,
)
# Save predictions if requested
if args.save_predictions:
print(f"\nSaving predictions to {args.save_predictions}...")
with open(args.save_predictions, "w") as f:
for inp, pred, gt in zip(inputs, predictions, ground_truths):
f.write(json.dumps({
"input": inp,
"prediction": pred,
"ground_truth": gt,
}, ensure_ascii=False) + "\n")
# Compute metrics
print(f"\nComputing metrics...")
metrics = compute_molecular_metrics(predictions, ground_truths)
# Print results
print("\n" + "=" * 60)
print("EVALUATION RESULTS")
print("=" * 60)
print(f"\nDataset: {len(test_data)} examples")
print(f"\nBasic Metrics:")
print(f" Exact Match (raw): {metrics['exact_match']:.4f} ({metrics['exact_match']*100:.2f}%)")
print(f" Canonical Exact Match: {metrics['canonical_exact_match']:.4f} ({metrics['canonical_exact_match']*100:.2f}%)")
print(f" Validity Rate: {metrics['validity_rate']:.4f} ({metrics['validity_rate']*100:.2f}%)")
print(f" Valid Predictions: {metrics['n_valid']}/{metrics['n_total']}")
print(f"\nTanimoto Similarity:")
print(f" Mean (all): {metrics['tanimoto_similarity']:.4f}")
print(f" Mean (valid only): {metrics['tanimoto_similarity_valid']:.4f}")
if 'tanimoto_mean' in metrics:
print(f" Median: {metrics['tanimoto_median']:.4f}")
print(f" Std Dev: {metrics['tanimoto_std']:.4f}")
print(f" Min: {metrics['tanimoto_min']:.4f}")
print(f" Max: {metrics['tanimoto_max']:.4f}")
print(f"\nTanimoto Similarity Distribution:")
if 'tanimoto_ge_0.9' in metrics:
print(f" ≥ 0.9 (excellent): {metrics['tanimoto_ge_0.9']:.4f} ({metrics['tanimoto_ge_0.9']*100:.2f}%)")
print(f" ≥ 0.8 (very good): {metrics['tanimoto_ge_0.8']:.4f} ({metrics['tanimoto_ge_0.8']*100:.2f}%)")
print(f" ≥ 0.7 (good): {metrics['tanimoto_ge_0.7']:.4f} ({metrics['tanimoto_ge_0.7']*100:.2f}%)")
print(f" ≥ 0.5 (moderate): {metrics['tanimoto_ge_0.5']:.4f} ({metrics['tanimoto_ge_0.5']*100:.2f}%)")
print(f" ≥ 0.3 (low): {metrics['tanimoto_ge_0.3']:.4f} ({metrics['tanimoto_ge_0.3']*100:.2f}%)")
# Save results
if args.output_json:
print(f"\nSaving results to {args.output_json}...")
with open(args.output_json, "w") as f:
json.dump({
"model_path": args.model_path,
"test_file": args.test_jsonl,
"n_examples": len(test_data),
"metrics": metrics,
"config": {
"max_length": args.max_length,
"num_beams": args.num_beams,
"batch_size": args.batch_size,
}
}, f, indent=2)
print("Results saved!")
print("\n" + "=" * 60)
print("Evaluation complete!")
print("=" * 60)
if __name__ == "__main__":
main()