Alterlab torchdrug

From AlterLab-IEU/AlterLab-Academic-Skills · View interactive version

Alterlab torchdrug is an AI agent skill from the GitHub repository AlterLab-IEU/AlterLab-Academic-Skills. Builds PyTorch-native graph neural networks with TorchDrug for molecules and proteins, exposing custom GNN architectures, task/dataset abstractions, molecular generation, retrosynthesis planning, and knowledge-graph reasoning. Use when a project specifically needs TorchDrug's datasets and tasks — Ge

How to use this skill

Skill file

TorchDrug

Overview

TorchDrug is a comprehensive PyTorch-based machine learning toolbox for drug discovery and molecular science. Apply graph neural networks, pre-trained models, and task definitions to molecules, proteins, and biological knowledge graphs, including molecular property prediction, protein modeling, knowledge graph reasoning, molecular generation, retrosynthesis planning, with 40+ curated datasets and 20+ model architectures.

When to Use This Skill

This skill should be used when working with:

Data Types:

Tasks:

Libraries and Integration:

Does NOT Trigger

| Scenario | Use Instead |

|----------|-------------|

| Building a general custom GNN today (active library, current Python/torch) | alterlab-torch-geometric |

| Ready-made featurizers, MoleculeNet benchmarks, and pretrained models with less code | alterlab-deepchem |

| Only turning molecules into feature matrices for your own models | alterlab-molfeat |

| Only sourcing a labeled benchmark dataset (ADMET/DTI) with official splits | alterlab-pytdc |

| Querying an existing biomedical knowledge graph rather than training a KG model | alterlab-primekg |

Hand-off rule. When the request matches a row above, open your answer by naming that skill by its exact id (for example alterlab-torch-geometric) and saying in one line why it fits better, then stop applying this skill's procedure. Name it even when you also need to ask for missing input. If only part of the request is out of scope, name the skill for that part and do only the in-scope part. A brief general pointer is fine; the named skill does the work.

Getting Started

Installation

# TorchDrug 0.2.1 (last release, Jul 2023) requires Python >=3.7,<3.11 and
# torch >=1.8. It will NOT solve on Python 3.11+ — pin an older interpreter:
uv venv --python 3.10
uv pip install torch                        # install torch first (see below)
# torch-scatter / torch-cluster ship only as sdists, so they compile against the
# installed torch — either install from the PyG wheel index or ensure a C++ toolchain:
uv pip install torch-scatter torch-cluster \
  --find-links "https://data.pyg.org/whl/torch-${TORCH_VERSION}+${CUDA}.html"  # e.g. cpu, cu121
uv pip install torchdrug==0.2.1

Gotchas:

Quick Example

import torch
from torchdrug import data, datasets, models, tasks

# Load molecular dataset. MoleculeNet-style datasets such as BBBP have no .split()
# method (only datasets with predefined splits do) — split explicitly:
dataset = datasets.BBBP("~/molecule-datasets/")
lengths = [int(0.8 * len(dataset)), int(0.1 * len(dataset))]
lengths += [len(dataset) - sum(lengths)]
train_set, valid_set, test_set = data.ordered_scaffold_split(dataset, lengths)
# (or torch.utils.data.random_split(dataset, lengths) for a random split)

# Define GNN model
model = models.GIN(
    input_dim=dataset.node_feature_dim,
    hidden_dims=[256, 256, 256],
    edge_input_dim=dataset.edge_feature_dim,
    batch_norm=True,
    readout="mean"
)

# Create property prediction task
task = tasks.PropertyPrediction(
    model,
    task=dataset.tasks,
    criterion="bce",
    metric=["auroc", "auprc"]
)

# Train with a native PyTorch loop.
# preprocess() builds the task's MLP prediction head (and label statistics) — core.Engine
# calls it for you; in a manual loop call it BEFORE creating the optimizer, or the head
# is missing and its parameters are never optimized.
task.preprocess(train_set, valid_set, test_set)
# NOTE: use torchdrug.data.DataLoader (NOT torch.utils.data.DataLoader) — its
# default graph_collate packs data.Graph objects; the stock PyTorch collate cannot.
optimizer = torch.optim.Adam(task.parameters(), lr=1e-3)
train_loader = data.DataLoader(train_set, batch_size=32, shuffle=True)

for epoch in range(100):
    for batch in train_loader:
        # task.forward returns (loss, metric), not a bare tensor.
        loss, metric = task(batch)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

For the standard (non-custom) path, core.Engine(task, train_set, valid_set, test_set, optimizer, batch_size=...) wraps this loop and handles batching/devices. Use the manual loop above when you need full control over the training step.

Core Capabilities

1. Molecular Property Prediction

Predict chemical, physical, and biological properties of molecules from structure.

Use Cases:

Key Components:

Reference: See references/molecular_property_prediction.md for:

2. Protein Modeling

Work with protein sequences, structures, and properties.

Use Cases:

Key Components:

Reference: See references/protein_modeling.md for:

3. Knowledge Graph Reasoning

Predict missing links and relationships in biological knowledge graphs.

Use Cases:

Key Components:

Reference: See references/knowledge_graphs.md for:

4. Molecular Generation

Generate novel molecular structures with desired properties.

Use Cases:

Key Components:

Reference: See references/molecular_generation.md for:

5. Retrosynthesis

Predict synthetic routes from target molecules to starting materials.

Use Cases:

Key Components:

Reference: See references/retrosynthesis.md for:

6. Graph Neural Network Models

Comprehensive catalog of GNN architectures for different data types and tasks.

Available Models:

Reference: See references/models_architectures.md for:

7. Datasets

40+ curated datasets spanning chemistry, biology, and knowledge graphs.

Categories:

Reference: See references/datasets.md for:

Common Workflows

Workflow 1: Molecular Property Prediction

Scenario: Predict blood-brain barrier penetration for drug candidates.

Steps:

  1. Load dataset: datasets.BBBP()
  2. Choose model: GIN for molecular graphs
  3. Define task: PropertyPrediction with binary classification
  4. Train with scaffold split for realistic evaluation
  5. Evaluate using AUROC and AUPRC

Navigation: references/molecular_property_prediction.md → Dataset selection → Model selection → Training

Workflow 2: Protein Function Prediction

Scenario: Predict enzyme function from sequence.

Steps:

  1. Load dataset: datasets.EnzymeCommission()
  2. Choose model: ESM (pre-trained) or GearNet (with structure)
  3. Define task: PropertyPrediction with multi-class classification
  4. Fine-tune pre-trained model or train from scratch
  5. Evaluate using accuracy and per-class metrics

Navigation: references/protein_modeling.md → Model selection (sequence vs structure) → Pre-training strategies

Workflow 3: Drug Repurposing via Knowledge Graphs

Scenario: Find new disease treatments in Hetionet.

Steps:

  1. Load dataset: datasets.Hetionet()
  2. Choose model: RotatE or ComplEx
  3. Define task: KnowledgeGraphCompletion
  4. Train with negative sampling
  5. Query for "Compound-treats-Disease" predictions
  6. Filter by plausibility and mechanism

Navigation: references/knowledge_graphs.md → Hetionet dataset → Model selection → Biomedical applications

Workflow 4: De Novo Molecule Generation

Scenario: Generate drug-like molecules optimized for target binding.

Steps:

  1. Train property predictor on activity data
  2. Choose generation approach: GCPN for RL-based optimization
  3. Define reward function combining affinity, drug-likeness, synthesizability
  4. Generate candidates with property constraints
  5. Validate chemistry and filter by drug-likeness
  6. Rank by multi-objective scoring

Navigation: references/molecular_generation.md → Conditional generation → Multi-objective optimization

Workflow 5: Retrosynthesis Planning

Scenario: Plan synthesis route for target molecule.

Steps:

  1. Load dataset: datasets.USPTO50k()
  2. Train center identification model (RGCN)
  3. Train synthon completion model (GIN)
  4. Combine into end-to-end retrosynthesis pipeline
  5. Apply recursively for multi-step planning
  6. Check commercial availability of building blocks

Navigation: references/retrosynthesis.md → Task types → Multi-step planning

Integration Patterns

With RDKit

Convert between TorchDrug molecules and RDKit:

from torchdrug import data
from rdkit import Chem

# SMILES → TorchDrug molecule
smiles = "CCO"
mol = data.Molecule.from_smiles(smiles)

# TorchDrug → RDKit
rdkit_mol = mol.to_molecule()

# RDKit → TorchDrug
rdkit_mol = Chem.MolFromSmiles(smiles)
mol = data.Molecule.from_molecule(rdkit_mol)

With AlphaFold/ESM

Use predicted structures:

from torchdrug import data, layers
from torchdrug.layers import geometry

# Load AlphaFold predicted structure
protein = data.Protein.from_pdb("AF-P12345-F1-model_v4.pdb")

# Build a residue-level graph with sequential + spatial edges
graph_construction_model = layers.GraphConstruction(
    node_layers=[geometry.AlphaCarbonNode()],
    edge_layers=[
        geometry.SpatialEdge(radius=10.0, min_distance=5),
        geometry.SequentialEdge(max_distance=2),
    ],
    edge_feature="gearnet",
)
# GraphConstruction operates on a packed protein batch, not a bare Protein.
graph = graph_construction_model(data.Protein.pack([protein]))

With PyTorch Lightning

Wrap tasks for Lightning training:

import torch
import pytorch_lightning as pl   # or: import lightning.pytorch as pl

class LightningTask(pl.LightningModule):
    def __init__(self, torchdrug_task):
        super().__init__()
        self.task = torchdrug_task      # call task.preprocess(...) before training

    def training_step(self, batch, batch_idx):
        loss, metric = self.task(batch)  # forward returns (loss, metric)
        return loss

    def validation_step(self, batch, batch_idx):
        pred = self.task.predict(batch)
        target = self.task.target(batch)
        return {"pred": pred, "target": target}

    def configure_optimizers(self):
        return torch.optim.Adam(self.parameters(), lr=1e-3)

Technical Details

For deep dives into TorchDrug's architecture:

Core Concepts: See references/core_concepts.md for:

Quick Reference Cheat Sheet

Choose Dataset:

Choose Model:

Common Tasks:

Understand Architecture:

Troubleshooting Common Issues

Issue: Dimension mismatch errors

→ Check model.input_dim matches dataset.node_feature_dim

→ See references/core_concepts.md → Essential Attributes

Issue: Poor performance on molecular tasks

→ Use scaffold splitting, not random

→ Try GIN instead of GCN

→ See references/molecular_property_prediction.md → Best Practices

Issue: Protein model not learning

→ Use pre-trained ESM for sequence tasks

→ Check edge construction for structure models

→ See references/protein_modeling.md → Training Workflows

Issue: Memory errors with large graphs

→ Reduce batch size

→ Use gradient accumulation

→ See references/core_concepts.md → Memory Efficiency

Issue: Generated molecules are invalid

→ Add validity constraints

→ Post-process with RDKit validation

→ See references/molecular_generation.md → Validation and Filtering

Resources

Official Documentation: https://torchdrug.ai/docs/

GitHub: https://github.com/DeepGraphLearning/torchdrug

Paper: TorchDrug: A Powerful and Flexible Machine Learning Platform for Drug Discovery

Summary

Navigate to the appropriate reference file based on your task:

  1. Molecular property prediction → molecular_property_prediction.md
  2. Protein modeling → protein_modeling.md
  3. Knowledge graphs → knowledge_graphs.md
  4. Molecular generation → molecular_generation.md
  5. Retrosynthesis → retrosynthesis.md
  6. Model selection → models_architectures.md
  7. Dataset selection → datasets.md
  8. Technical details → core_concepts.md

Each reference provides comprehensive coverage of its domain with examples, best practices, and common use cases.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.