Latent-Space Retrosynthesis with Dynamic Pathway Unrolling
This model implements a Dynamic Mechanism-Aware Retrosynthesis that operates in a continuous latent space.
Model Overview
The architecture is designed for high-performance chemical reasoning. It utilizes a hybrid vector representation of molecules to achieve zero-truncation and rapid inference.
Key Architectural Features
- Dynamic Thinking Loop: Uses a GRU-based recurrent unit to resolve reaction pathways with variable complexity via a learned halting mechanism.
- Contrastive Latent Space: Molecules are mapped to a 256-dimensional unit hypersphere using InfoNCE loss, allowing for robust retrieval-based prediction.
- Hybrid Featurization: Combines 1024-bit Morgan Fingerprints (radius=2) with 16 physicochemical descriptors (MW, LogP, TPSA, etc.) for a total input dimension of 1040.
Usage
Using the Model
import torch
import numpy as np
import safetensors.torch
from rdkit import Chem
from rdkit.Chem import rdFingerprintGenerator, Descriptors
from huggingface_hub import hf_hub_download
from train import DynamicMolecularProjector, DynamicThinkingRetroModel
class MechanismAwareRetrosynthesis:
def __init__(self, repo_id="kssrikar4/Mechanism-aware-retrosynthesis", device=None):
self.device = device or torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.repo_id = repo_id
# 1. Load Model Architecture
self.projector = DynamicMolecularProjector(in_dim=1040, latent_dim=256).to(self.device)
self.retro_model = DynamicThinkingRetroModel(latent_dim=256).to(self.device)
# 2. Download and Load Weights from HF
model_path = hf_hub_download(repo_id=self.repo_id, filename="model.safetensors")
weights = safetensors.torch.load_file(model_path)
self.projector.load_state_dict({k.replace('projector.', ''): v for k, v in weights.items() if k.startswith('projector.')})
self.retro_model.load_state_dict({k.replace('retro_model.', ''): v for k, v in weights.items() if k.startswith('retro_model.')})
self.projector.eval()
self.retro_model.eval()
# 3. Initialize Fingerprint Generator
self.fp_gen = rdFingerprintGenerator.GetMorganGenerator(radius=2, fpSize=1024)
# 4. Load Candidate Database (Required for Retrieval)
# The model predicts a vector; we must find the closest molecule in our database.
print("Loading candidate molecule database...")
cache_path = hf_hub_download(repo_id=self.repo_id, filename="preprocessed_routes_cache.npz")
cache_data = np.load(cache_path, allow_pickle=True)
self.unique_smiles = cache_data["unique_smiles"]
lookup_fps = cache_data["lookup_fps"]
lookup_descs = cache_data["lookup_descs"]
# Pre-compute GPU table for fast retrieval
unpacked_fps = np.unpackbits(lookup_fps, axis=-1).astype(np.float32)
full_table_np = np.concatenate([unpacked_fps, lookup_descs], axis=-1)
self.candidate_table = torch.tensor(full_table_np, dtype=torch.float32, device=self.device)
# Pre-compute latent vectors for all candidates to speed up search
print("Pre-computing latent space for candidate retrieval...")
with torch.no_grad():
self.candidate_latents = self.projector(self.candidate_table)
def _smiles_to_tensor(self, smiles: str) -> torch.Tensor:
"""Converts a SMILES string into the 1040-dim input tensor."""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
raise ValueError(f"Invalid SMILES: {smiles}")
# 1. Morgan Fingerprint (1024 bits)
fp = self.fp_gen.GetFingerprint(mol)
arr = np.zeros(1024, dtype=np.uint8)
arr[list(fp.GetOnBits())] = 1
# 2. Physicochemical Descriptors (16 floats)
descs = np.array([
Descriptors.MolWt(mol) / 500.0,
Descriptors.MolLogP(mol) / 5.0,
Descriptors.TPSA(mol) / 150.0,
Descriptors.NumHDonors(mol) / 10.0,
Descriptors.NumHAcceptors(mol) / 10.0,
Descriptors.NumRotatableBonds(mol) / 15.0,
Descriptors.FractionCSP3(mol),
Descriptors.RingCount(mol) / 8.0,
Descriptors.NumAromaticRings(mol) / 6.0,
Descriptors.NumHeteroatoms(mol) / 15.0,
Descriptors.LabuteASA(mol) / 200.0,
Descriptors.HeavyAtomCount(mol) / 50.0,
Descriptors.NHOHCount(mol) / 10.0,
Descriptors.NOCount(mol) / 15.0,
Descriptors.NumAliphaticRings(mol) / 6.0,
Descriptors.NumSaturatedRings(mol) / 6.0
], dtype=np.float32)
# Combine and convert to tensor
input_vec = np.concatenate([arr, descs])
return torch.tensor(input_vec, dtype=torch.float32, device=self.device).unsqueeze(0)
def predict_precursors(self, product_smiles: str, top_k: int = 5) -> list[dict]:
"""
Predicts precursor SMILES for a given product SMILES.
Args:
product_smiles: The SMILES string of the target molecule.
top_k: Number of candidate precursor sets to return.
Returns:
A list of dictionaries containing 'precursor_smiles' and 'similarity_score'.
"""
# 1. Featurize Input
input_tensor = self._smiles_to_tensor(product_smiles)
# 2. Project to Latent Space
with torch.no_grad():
z_p = self.projector(input_tensor)
# 3. Dynamic Thinking (Unroll intermediates)
# We use max_steps=6 as defined in the architecture
thought_states, halt_probs, z_r_pred = self.retro_model.forward_dynamic(z_p, max_steps=6)
# 4. Retrieve Candidates via Cosine Similarity
# Compare predicted precursor vector against all pre-computed candidate vectors
similarities = torch.mm(z_r_pred, self.candidate_latents.t()).squeeze(0)
# Get top-k indices
top_values, top_indices = torch.topk(similarities, top_k)
results = []
for idx, score in zip(top_indices.cpu().numpy(), top_values.cpu().numpy()):
precursor_smiles = self.unique_smiles[idx]
results.append({
"precursor_smiles": precursor_smiles,
"similarity_score": float(score)
})
return results
# --- Example Usage ---
if __name__ == "__main__":
# Initialize the model (downloads weights and cache on first run)
model = MechanismAwareRetrosynthesis()
# Example Product: Aspirin
target = "CC(=O)OC1=CC=CC=C1C(=O)O"
print(f"\nTarget Product: {target}")
print("Predicting precursors...")
predictions = model.predict_precursors(target, top_k=3)
for i, pred in enumerate(predictions):
print(f"\n{i+1}. Precursor Set: {pred['precursor_smiles']}")
print(f" Confidence (Cosine Sim): {pred['similarity_score']:.4f}")
Featurization
The model expects a 1040-dimensional input vector:
- 1024 bits: Morgan Fingerprint (Radius 2), bit-packed.
- 16 floats: Normalized physicochemical descriptors (MolWt, MolLogP, TPSA, etc.).
Evaluation Results
The model was evaluated on a held-out test set from the PaRoutes and USPTO datasets. Below are the performance metrics and visualizations.
Retrieval Accuracy
| Metric | Value |
|---|---|
| Top-1 Accuracy | 93.1 % |
| Top-5 Accuracy | 99.2 % |
| Mean Reciprocal Rank (MRR) | 0.9581 |
| Mean Tanimoto Similarity | 0.9680 |
Training Convergence

Figure 1: Contrastive Loss and Cosine Similarity convergence over 15 epochs.
Candidate Retrieval Performance

Figure 2: Precursor candidate retrieval accuracy across different Top-K values.
Physicochemical Parity

Figure 3: Parity plots for Molecular Weight, LogP, TPSA, and Heavy Atom Count between true and predicted precursors.
Similarity Distributions

Figure 4: Distribution of Morgan Fingerprint Tanimoto similarities and Latent Cosine similarities.
Dynamic Thinking Analysis

Figure 5: Concordance between ground-truth pathway steps and model-predicted halting steps.

Figure 6: PCA projection of the latent "thinking" trajectory from Product -> Intermediate -> Precursor.
Chemical Structure Examples

Figure 7: Visual comparison of Target Products, Ground Truth Precursors, and Model Predictions for diverse chemical classes.
License
This project is licensed under the GNU General Public License v3.0. See the LICENSE file for details.