torchdrug
PyTorch-based ML platform for drug discovery: graph molecular representation learning, property prediction (ADMET, activity), retrosynthesis, drug-target interaction (DTI), and pretraining on large molecular datasets.
Install / Use
npx skills add jaechang-hits/SciAgent-Skills --skill torchdrugInstalls into whichever agent you are using.
SKILL.md
Installable skill definition
Quality Score
Category
AI & Machine LearningSupported Platforms
Tags
Our assessment of torchdrug
torchdrug scores 91/100 on our quality scale, 345th of 944 AI & Machine Learning skills we index (top 37%).
Its SKILL.md is 18 KB long, well organised into 52 sections with 16 code examples: a thorough specification that gives an agent plenty to work with.
It has 367 GitHub stars, a meaningful sign that others use it.
Maintenance, license and trust
- The repository was last updated about 3 months ago, so torchdrug is actively maintained.
- Our last check on 2026-11-20 found the source still online.
- No license is declared. By default that means all rights are reserved: you can read it, but reusing or redistributing it is not clearly permitted. Ask the author before building on it commercially.
- Its trust signals score 88/100, with 1 caution from licensing, adoption, age or documentation. These come from repository metadata, not a code audit — read the skill file before letting an agent act on it.
Safety scan
No issues foundOur scan of the whole file found no instruction hijacking, hidden characters, credential access, data exfiltration or destructive commands. An AI review of the same text found nothing harmful.
AI review by kimi-k2.7-code on 2026-10-05. Automated pattern scan on 2026-10-05. It catches known dangerous patterns, not every risk — read a skill before letting an agent act on it.
torchdrug compared with similar skills
All 4 of these similar skills score higher than torchdrug; compare them before choosing.
| Skill | Score | Stars | Updated | Format |
|---|---|---|---|---|
| torchdrug (this skill)by jaechang-hits | 91 | 367 | 3mo ago | SKILL.md |
| claude-memby thedotmack | 100 | 118.5k | today | CLAUDE.md |
| Understand-Anythingby Egonex-AI | 100 | 93.3k | 1d ago | CLAUDE.md |
| headroomby headroomlabs-ai | 100 | 80.2k | today | CLAUDE.md |
| CowAgentby zhayujie | 100 | 48.0k | today | CLAUDE.md |
Frequently asked questions
- How do I install torchdrug?
- Run
npx skills add jaechang-hits/SciAgent-Skills --skill torchdrug. The install tabs above show the steps for each supported agent. - Which AI agents does torchdrug work with?
- It is written for Universal, as a SKILL.md file. Other agents that read the same format can often use it too.
- Is torchdrug safe to use?
- Our scan of the whole file found no instruction hijacking, hidden characters, credential access, data exfiltration or destructive commands. An AI review of the same text found nothing harmful. It declares no license and scores 88/100 on trust signals. Skills are instructions an agent will follow, so read the file before installing it and do not approve commands you do not understand.
- Is torchdrug still maintained?
- The repository was last updated about 3 months ago, so torchdrug is actively maintained.
Skill content
View source on GitHubname: "torchdrug" description: "PyTorch-based ML platform for drug discovery: graph molecular representation learning, property prediction (ADMET, activity), retrosynthesis, drug-target interaction (DTI), and pretraining on large molecular datasets. Provides GNN layers (GraphConv, GAT, MPNN), pretrained models, and benchmark datasets." license: "Apache-2.0"
torchdrug
Overview
TorchDrug is a comprehensive machine learning framework for drug discovery built on PyTorch. It provides graph-based molecular representations (atoms as nodes, bonds as edges), a library of graph neural network (GNN) architectures, benchmark datasets, and pretrained models for tasks including molecular property prediction, drug-target interaction, retrosynthesis, and generative molecular design. TorchDrug integrates with PyTorch Lightning and standard ML tooling, making it accessible to both computational chemists and ML practitioners.
When to Use
- Molecular property prediction: Training or fine-tuning GNN models to predict ADMET properties (solubility, toxicity, permeability) or bioactivity (IC50, Ki) from molecular graphs.
- Drug-target interaction (DTI) prediction: Building models that predict binding affinity between a compound (SMILES) and a protein (sequence or structure).
- Retrosynthesis prediction: Identifying plausible synthetic routes for a target molecule using template-based or template-free models.
- Pretraining on large molecular datasets: Leveraging pretrained GNN representations on ChEMBL or ZINC for transfer learning to small datasets.
- Molecular generation: Training graph-based generative models (GCPN, GraphAF) to design novel molecules with desired properties.
- Benchmarking GNN architectures: Comparing GraphConv, MPNN, GAT, AttentiveFP on standard MoleculeNet tasks.
- For fast fingerprint-based property prediction without deep learning, use RDKit + scikit-learn instead.
- For protein structure tasks (folding, docking), use ESMFold or DiffDock rather than TorchDrug.
Prerequisites
- Python packages:
torchdrug,torch,torch-geometric,rdkit - Environment: Python 3.8+, CUDA-compatible GPU recommended for training
- Data requirements: SMILES strings or molecular SDF files; protein sequences for DTI tasks
pip install torch torchvision --extra-index-url https://download.pytorch.org/whl/cu118
pip install torch-geometric
pip install torchdrug
pip install rdkit
Quick Start
import torch
from torchdrug import data, datasets, models, tasks, core
# Load a benchmark dataset and train a GNN for property prediction
dataset = datasets.BBBP("~/data/bbbp", node_feature="default", edge_feature="default")
print(f"Dataset: {len(dataset)} molecules, task: BBBP (blood-brain barrier penetration)")
# Define model: GIN encoder
model = models.GIN(
input_dim=dataset.node_feature_dim,
hidden_dims=[256, 256],
short_cut=True,
batch_norm=True,
concat_hidden=True,
)
# Define training task
task = tasks.PropertyPrediction(
model, task=dataset.tasks,
criterion="bce", metric=("auprc", "auroc"),
)
# Train with the Solver
optimizer = torch.optim.Adam(task.parameters(), lr=1e-3)
solver = core.Engine(task, dataset, None, None, optimizer, gpus=[0])
solver.train(num_epoch=50)
print("Training complete")
Core API
Module 1: Molecular Graph Representation
TorchDrug represents molecules as typed graphs. data.Molecule is the core data structure.
from torchdrug import data
from rdkit import Chem
# Create a molecule from SMILES
smiles = "CC(=O)Oc1ccccc1C(=O)O" # aspirin
mol = data.Molecule.from_smiles(smiles, node_feature="default", edge_feature="default")
print(f"Atoms: {mol.num_node}")
print(f"Bonds: {mol.num_edge}")
print(f"Node feature dim: {mol.node_feature.shape}") # (N_atoms, feature_dim)
print(f"Edge feature dim: {mol.edge_feature.shape}") # (N_bonds*2, feature_dim)
# Convert a MoleculeNet / custom SMILES list to a dataset
from torchdrug import data as td_data
import pandas as pd
df = pd.read_csv("compounds.csv") # columns: smiles, label
molecules = [td_data.Molecule.from_smiles(s) for s in df["smiles"] if s]
print(f"Loaded {len(molecules)} valid molecules")
# Check feature dimensions
print(f"Default atom feature dim: {molecules[0].node_feature.shape[1]}")
Module 2: GNN Architectures
TorchDrug provides GIN, RGCN, GraphSAGE, GAT, MPNN, AttentiveFP, and more.
from torchdrug import models, datasets
dataset = datasets.ESOL("~/data/esol", node_feature="default", edge_feature="default")
feature_dim = dataset.node_feature_dim
# Graph Isomorphism Network (GIN) — good default for property prediction
gin = models.GIN(
input_dim=feature_dim,
hidden_dims=[256, 256, 256],
short_cut=True,
batch_norm=True,
concat_hidden=True, # concatenate layer representations
)
print(f"GIN output_dim: {gin.output_dim}")
from torchdrug import models
# Message Passing Neural Network (MPNN) — captures edge features
mpnn = models.MPNN(
input_dim=feature_dim,
hidden_dim=256,
edge_input_dim=16, # edge feature dimension
num_layer=4,
num_gru_layer=1,
)
# Graph Attention Network (GAT) — attention-weighted neighbors
gat = models.GAT(
input_dim=feature_dim,
hidden_dims=[256, 256],
edge_input_dim=16,
num_head=8,
batch_norm=True,
)
print(f"MPNN output_dim: {mpnn.output_dim}, GAT output_dim: {gat.output_dim}")
Module 3: Molecular Property Prediction
Wrap a GNN encoder with a prediction head for classification or regression.
import torch
from torchdrug import datasets, models, tasks, core
# Regression example: ESOL aqueous solubility
dataset = datasets.ESOL("~/data/esol", node_feature="default", edge_feature="default")
train, val, test = dataset.split()
print(f"Train: {len(train)}, Val: {len(val)}, Test: {len(test)}")
model = models.GIN(
input_dim=dataset.node_feature_dim,
hidden_dims=[300, 300],
short_cut=True,
batch_norm=True,
concat_hidden=True,
)
task = tasks.PropertyPrediction(
model,
task=dataset.tasks, # list of property names
criterion="mse", # "mse" for regression, "bce" for classification
metric=("mae", "rmse"),
num_mlp_layer=2,
)
optimizer = torch.optim.Adam(task.parameters(), lr=1e-3, weight_decay=1e-5)
solver = core.Engine(task, train, val, test, optimizer,
batch_size=32, log_interval=50)
solver.train(num_epoch=100)
# Evaluate on test set
metrics = solver.evaluate("test")
print(f"Test RMSE: {metrics['rmse']:.4f}")
print(f"Test MAE: {metrics['mae']:.4f}")
Module 4: Drug-Target Interaction (DTI) Prediction
Predict binding affinity between molecules and protein sequences.
from torchdrug import datasets, models, tasks, core
import torch
# Load a DTI dataset (e.g., Davis kinase binding affinities)
dataset = datasets.Davis("~/data/davis",
mol_node_feature="default",
mol_edge_feature="default")
train, val, test = dataset.split()
# Molecule encoder
mol_model = models.GIN(
input_dim=dataset.mol_node_feature_dim,
hidden_dims=[256, 256],
short_cut=True,
batch_norm=True,
concat_hidden=True,
)
# Protein encoder (CNN on sequence)
prot_model = models.ProteinCNN(
input_dim=21, # amino acid vocabulary size
hidden_dims=[128, 128, 128],
kernel_size=3,
)
task = tasks.InteractionPrediction(
mol_model, prot_model,
task=dataset.tasks,
criterion="mse",
metric=("rmse", "pearsonr"),
)
optimizer = torch.optim.Adam(task.parameters(), lr=1e-3)
solver = core.Engine(task, train, val, test, optimizer,
batch_size=64, log_interval=100)
solver.train(num_epoch=50)
metrics = solver.evaluate("test")
print(f"DTI Test RMSE: {metrics['rmse']:.4f}")
print(f"DTI Pearson r: {metrics['pearsonr']:.4f}")
Module 5: Retrosynthesis Prediction
Predict one-step retrosynthetic disconnections to find plausible building blocks.
from torchdrug import datasets, models, tasks, core
import torch
# USPTO-50k retrosynthesis benchmark
dataset = datasets.USPTO50k("~/data/uspto50k",
as_synthon=False,
atom_feature="default",
bond_feature="default")
train, val, test = dataset.split()
# Reaction-predicting GNN
model = models.RGCN(
input_dim=dataset.node_feature_dim,
hidden_dims=[256, 256, 256],
num_relation=dataset.num_bond_type,
batch_norm=True,
)
task = tasks.CenterIdentification(
model,
feature=("graph", "atom", "bond"),
)
optimizer = torch.optim.Adam(task.parameters(), lr=1e-4)
solver = core.Engine(task, train, val, test, optimizer,
batch_size=64, log_interval=100)
solver.train(num_epoch=50)
metrics = solver.evaluate("test")
print(f"Retrosynthesis top-1 accuracy: {metrics.get('accuracy', 'N/A')}")
Module 6: Pretrained Models and Transfer Learning
Use TorchDrug's pretrained GNN representations as features for downstream tasks.
from torchdrug import models
# Load a GNN pretrained on ChEMBL with context-prediction self-supervised learning
pretrained_gin = models.GIN(
input_dim=39,
hidden_dims=[300, 300, 300, 300, 300],
short_cut=False,
batch_norm=True,
concat_hidden=False,
)
# Load pretrained weights (download from TorchDrug model zoo)
import torch
ckpt = torch.load("gin_supervised_contextpred.pth", map_location="cpu")
pretrained_gin.load_state_dict(ckpt)
pretrained_gin.eval()
print(f"Pretrained GIN loaded, output_dim={pretrained_gin.output_dim}")
print("Use as encoder in PropertyPrediction task for transfer learning")
Key Concepts
Graph-Based Molecular Representation
Molecules are represented as attributed graphs: atoms are nodes with features (atomic number, degree, charge, aromaticity) and bonds are edges with features (bond type, ring membership). All TorchDrug models operate on these graph representations rather than SMILES strings or fingerprints.
from torchdrug import data
mol = data.Molecule.from_smiles("c1ccccc1") # benzene
print(f"Atoms: {mol.num_node}, Bonds: {mol.num_edge // 2}")
print(f"Atom features (first atom): {mol.node_feature[0]}")
Engine and Solver Pattern
TorchDrug uses a core.Engine (also called Solver) to handle the training loop, logging, checkpointing, and multi-GPU setup. Pass the task, train/val/test splits, and optimizer to the Engine rather than writing a manual training loop.
# Engine handles: batch iteration, loss backward, logging, checkpointing
solver = core.Engine(
task, train_set, valid_set, test_set, optimizer,
batch_size=32,
log_interval=100,
gpus=[0, 1], # multi-GPU support
)
solver.train(num_epoch=100)
solver.save("checkpoint.pth")
Common Workflows
Workflow 1: End-to-End ADMET Property Prediction
Goal: Train a GIN model to predict blood-brain barrier penetration from SMILES, then predict on new compounds.
import torch
import pandas as pd
from torchdrug import data, datasets, models, tasks, core
# 1. Load dataset
dataset = datasets.BBBP("~/data/bbbp", node_feature="default", edge_feature="default")
train, val, test = dataset.split()
print(f"BBBP: {len(train)} train, {len(val)} val, {len(test)} test molecules")
# 2. Build model
model = models.GIN(
input_dim=dataset.node_feature_dim,
hidden_dims=[256, 256],
short_cut=True, batch_norm=True, concat_hidden=True,
)
task = tasks.PropertyPrediction(
model, task=dataset.tasks,
criterion="bce", metric=("auroc", "auprc"),
)
# 3. Train
optimizer = torch.optim.Adam(task.parameters(), lr=1e-3)
solver = core.Engine(task, train, val, test, optimizer,
batch_size=32, log_interval=50)
solver.train(num_epoch=100)
metrics = solver.
Truncated for display — read the full file on GitHub.
Related Skills
claude-mem
118.5kPersistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More
Understand-Anything
93.3kGraphs that teach > graphs that impress. Turn any code into an interactive knowledge graph you can explore, search, and ask questions about. Works with Claude Code, Codex, Cursor, Copilot, Gemini CLI, and more.
headroom
80.2kCompress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
CowAgent
48.0kOpen-source personal AI assistant & Agent Harness. Plans tasks, runs tools and skills, self-evolves with memory and knowledge. Multi-agent, multi-model, multi-channel. Lightweight, extensible, one-line install.
Languages
Trust signals
From repository metadata: license, adoption, age and documentation. Not a code audit — see the Safety scan above for what the skill file itself contains.
