/ Модель

Характеристики

Лицензия
GPL 3.0
Архитектура
latent-thinking-retrosynthesis · dense
Опубликована
2 ноя 2026

Latent-Space-Retrosynthesis

ЭмбеддингиТекст → embedding3 профессии

Модель кодирует молекулы в латентные векторы для извлечения кандидатов-предшественников в ретросинтетическом поиске.

132скачиваний за 30 дней0лайковвеса обновлены8 ноя 2026

Бенчмарки

Как модель справилась с задачами пользователей ailist и что о ней публикуют открытые лидерборды

Тесты пользователейпока нет

Никто ещё не опубликовал тест этой модели. Соберите бенчмарк из своих задач — результат появится здесь.

  1. Добавьте модель в бенчмарк

    Вместе с другими моделями категории «Эмбеддинги» — сравнение идёт внутри одной категории.

  2. Опишите свои задачи

    Напишите запросы, при необходимости приложите файлы и эталонные ответы.

  3. Запустите и опубликуйте

    Модели ответят на каждую задачу, судья оценит ответы. Опубликованный результат появится на этой странице.

Публичные оценки

Из открытых лидербордов. Сравнивайте результаты одного теста при одинаковых условиях — отсутствие оценки не значит, что модель хуже.

В подключённых источниках результатов для этой модели пока нет.

Что умеет модель

Описание составлено по карточке модели и метаданным Hugging Face

Latent-Space Retrosynthesis with Dynamic Pathway Unrolling — модель для поиска кандидатов в предшественники химических реакций, представленная пользователем kssrikar4. Она использует плотную архитектуру DynamicLatentThinkingRetroModel с циклом рассуждения на основе GRU и обучаемым механизмом остановки для обработки путей разной сложности. Молекулы кодируются 256-мерными векторами в контрастивном латентном пространстве; входная векторизация объединяет 1024-битные отпечатки Моргана радиуса 2 и 16 физико-химических дескрипторов. Модель оценивалась на PaRoutes и USPTO; в README заявлены точность поиска 93,1% для Top-1 и 99,2% для Top-5.

Модель предназначена для ретросинтетического поиска и ранжирования кандидатов-предшественников по представлению целевой молекулы. Она принимает вектор признаков размерности 1040 и выдаёт латентные признаки для извлечения кандидатов. Веса опубликованы в форматах PyTorch и Safetensors под лицензией GPL-3.0. В описании приведены результаты на тестовых данных, но не раскрыты независимое сравнение с базовыми методами или детали переноса качества на другие наборы реакций.

Сценарии применения

  • поиск кандидатов-предшественников для целевой молекулы
  • ранжирование возможных химических предшественников по близости в латентном пространстве
  • извлечение похожих реакционных путей из базы химических реакций

Ограничения

Заявленные метрики получены на тестовых данных PaRoutes и USPTO; в карточке не приведены независимая проверка результатов и оценка переноса на другие наборы данных. Для входа требуется заранее подготовленный вектор из 1024-битного отпечатка Моргана и 16 нормализованных дескрипторов.

Для каких профессий подходит3

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

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:

  1. 1024 bits: Morgan Fingerprint (Radius 2), bit-packed.
  2. 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

MetricValue
Top-1 Accuracy93.1 %
Top-5 Accuracy99.2 %
Mean Reciprocal Rank (MRR)0.9581
Mean Tanimoto Similarity0.9680

Training Convergence

final_loss_convergence

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

Candidate Retrieval Performance

precursor_candidate_topk_curve

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

Physicochemical Parity

true_vs_pred_properties_parity

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

Similarity Distributions

true_vs_pred_similarity_distribution

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

Dynamic Thinking Analysis

true_vs_pred_step_parity

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

latent_thought_trajectories_pca

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

Chemical Structure Examples

chemical_structures_5_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.

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм

Можно запустить

Подбираем GPU…

Класс архитектуры
DynamicLatentThinkingRetroModel
Ревизия весов
e09ccd1

0 моделей