MIT License

项目介绍

liugangcode/torch-molecule 是一个托管在 GitHub 上的开源项目,主要使用 Python 编写,采用 MIT License 许可证,目前获得 339 个 Star、42 次 Fork。

仓库全名
liugangcode/torch-molecule
开源许可证
MIT License
Star 数
339
Fork 数
42
未关闭 Issue
5

README 摘要

Deep learning for molecular discovery with a simple sklearn-style interface torch-molecule is a package that facilitates molecular discovery through deep learning, featuring a user-friendly, sklearn-style interface. It includes model checkpoints for efficient deployment and benchmarking across a range of molecular tasks. The package focuses on three main components: Predictive Models, Generative Models, and…

完整内容见 GitHub 原始 README 或本页 。

常见问题

torch-molecule 用什么语言开发?

主要使用 Python 编写,采用 MIT License 许可证,目前有 339 个 Star。

torch-molecule 可以免费商用吗?

仓库采用 MIT License 许可证,可免费使用与修改,商业使用请遵守许可证条款(例如保留版权声明与许可声明)。

如何获取 torch-molecule 的源码?

可以直接克隆仓库:git clone https://github.com/liugangcode/torch-molecule.git,默认分支为 main;安装与运行步骤见仓库 README。

torch-molecule 最近还在维护吗?

仓库最近一次更新为 1 周前,当前有 5 个未关闭 Issue;Star 数为 339,可作为社区活跃度的参考。

关于

GitHub 原始描述(英文)

torch-molecule is a deep learning package for molecular discovery, designed with an sklearn-style interface for property prediction, inverse design and representation learning.

描述取自 GitHub 官方 API,保持仓库作者书写的原文。

简要分析

热度分
429
价值分
216
活跃状态
活跃

语言占比

Edge
Python
Ring

Release

README

torch-molecule logo

GitHub Repository Documentation

Deep learning for molecular discovery with a simple sklearn-style interface


torch-molecule is a package that facilitates molecular discovery through deep learning, featuring a user-friendly, sklearn-style interface. It includes model checkpoints for efficient deployment and benchmarking across a range of molecular tasks. The package focuses on three main components: Predictive Models, Generative Models, and Representation Models, which make molecular AI models easy to implement and deploy.

scikit-learn vs torch-molecule comparison

See the List of Supported Models section for all available models.

Installation

Python 3.10 or newer is required; GenMol and Molexar require Python 3.11 or newer.

  1. Create a mamba environment:

    micromamba create --name torch-molecule --channel conda-forge python=3.12 pip
    eval "$(micromamba shell hook --shell bash)"
    micromamba activate torch-molecule
    
  2. Install using pip:

    pip install torch-molecule
    
  3. Install from source for the latest version:

    Clone the repository:

    git clone https://github.com/liugangcode/torch-molecule
    cd torch-molecule
    

    Install:

    pip install .
    

Additional Packages

Optional model requirements install as pip extras, e.g. pip install "torch-molecule[molgen]" (or pip install ".[molgen]" from a source checkout):

Extra Installs For
hf torch>=2.6, transformers HFPretrainedMolecularEncoder, HFPretrainedMolecularGenerator
molgen torch>=2.6, transformers, selfies>=2.1 MolGen
molexar torch>=2.6, transformers>=5.8, loguru Molexar (Python 3.11+); also install Fragment-SELFIES and Molexar from source
safe torch>=2.6, transformers, safe-mol SAFE-GPT
genmol transformers==4.57.1, safe-mol>=0.2.1,<0.3 GenMol (Python 3.11+)
scatter torch-scatter BFGNN, GRIN
grin torch-scatter, CombineMols GRIN with repetition_augmentation=True

Hugging Face pretrained generators require PyTorch 2.6 or newer.

Use separate environments for GenMol and Molexar: GenMol requires transformers==4.57.1, while Molexar requires transformers>=5.8.

After installing the molexar extra, install its source packages:

python -m pip install git+https://github.com/yiyanliao/Fragment-SELFIES.git git+https://github.com/yiyanliao/Molexar.git

Install a torch-scatter wheel matching your PyTorch and CUDA versions using the PyTorch Geometric installation guide.

from torch_molecule import HFPretrainedMolecularGenerator

model = HFPretrainedMolecularGenerator(
    repo_id="datamol-io/safe-gpt",
)
model.fit()
print(model.generate(n_samples=5))
print(model.generate(n_samples=5, scaffold="c1ccccc1"))

Usage

More examples can be found in the examples folder.

Datasets

Explore small-molecule and polymer datasets in the molecular dataset hub, with original sources, licenses, units, source splits, and quality tags.

See the dataset documentation for dataset selection, caching, target columns, and train/test splits.

Open the Molecular Dataset Hub for current dataset counts, Hugging Face coverage, source rows, tasks, and the interactive map.

Current counts follow the hub’s published metadata. Hugging Face entries include public and gated datasets and files without SMILES tables. Source rows may repeat structures; each dataset retains its own license.

Load published SMILES tables by their original dataset name:

from torch_molecule.datasets import list_datasets, load_dataset

list_datasets(category="adme", grade="ready")      # browse by category, quality grade, or license

data = load_dataset("qm9", targets=["homo", "lumo", "gap"], local_dir="torchmol_data")
smiles_list, property_np_array = data.data, data.target   # 133,885 molecules, shape (133885, 3)
data.info["targets"]["gap"]["units"]                        # 'Hartree'

train = load_dataset("moleculeace_chembl204_ki", split="train")   # source splits where defined;
test = load_dataset("moleculeace_chembl204_ki", split="test")     # test drops molecules seen in train

zinc = load_dataset("zinc250k", targets=[])                 # structures only: target is None

load_qm9, load_chembl2k, load_broad6k, load_toxcast, load_admet, load_gasperm, and load_zinc250k still work but are deprecated aliases of load_dataset and will be removed.

(We are actively adding more datasets. We welcome your suggestions and contributions on your datasets!)

Fit a Model

After preparing the dataset, split it, then fit a model with an sklearn-style API (no extra SMILES featurization is required):

from torch_molecule.datasets import load_dataset
from torch_molecule import GREAMolecularPredictor

data = load_dataset("qm9", targets=["gap"], local_dir="torchmol_data")
# "random" | "scaffold" | "butina" | "size"
# scaffold: unseen Bemis-Murcko scaffolds; butina: Tanimoto clusters; size: heavy-atom count
train, val = data.train_test_split(test_size=0.2, method="scaffold", seed=42)

grea = GREAMolecularPredictor(
    num_task=1,
    task_type="regression",
    evaluate_higher_better=False,
    verbose="progress_bar" #or "print_statement" recommended for jupyter notebooks, or "none"
)

# Fit with automatic hyperparameter tuning with 10 attempts, or implement .fit() with the default/manual hyperparameters
grea.autofit(
    X_train=train.data,
    y_train=train.target,
    X_val=val.data,
    y_val=val.target,
    n_trials=10,
)

Random splitting assigns individual rows, so repeated structures can occur in both splits. The splitters preserve data.groups metadata but do not use it to assign rows. Use scaffold or butina, or split by group yourself, when repeated measurements must stay together.

Checkpoints

torch-molecule provides checkpoint functions that can be interacted with on Hugging Face:

from torch_molecule import GREAMolecularPredictor

repo_id = "user/repo_id"  # replace with your own Hugging Face username and repo_id

# Save the trained model to Hugging Face
grea.save_to_hf(
    repo_id=repo_id,
    task_id="qm9_grea",
    commit_message="Upload qm9_grea",
    private=False
)

# Load a pretrained checkpoint from Hugging Face
model = GREAMolecularPredictor()
model.load_from_hf(repo_id=repo_id, local_cache="GREAMolecularPredictor.pt")

# Adjust model parameters and make predictions
model.set_params(verbose='none')
predictions = model.predict(smiles_list)

Or you can save the model to a local path:

grea.save_to_local("qm9_grea.pt")

new_model = GREAMolecularPredictor()
new_model.load_from_local("qm9_grea.pt")

List of Supported Models

Predictive Models

Model Reference
GRIN Learning Repetition-Invariant Representations for Polymer Informatics. NeurIPS 2025.
BFGNN Graph neural networks extrapolate out-of-distribution for shortest paths. March 2025
SGIR Semi-Supervised Graph Imbalanced Regression. KDD 2023
GREA Graph Rationalization with Environment-based Augmentations. KDD 2022
DIR Discovering Invariant Rationales for Graph Neural Networks. ICLR 2022
SSR SizeShiftReg: a Regularization Method for Improving Size-Generalization in Graph Neural Networks. NeurIPS 2022
IRM Invariant Risk Minimization (2019)
RPGNN Relational Pooling for Graph Representations. ICML 2019
GNNs Graph Convolutional Networks. ICLR 2017 and Graph Isomorphism Network. ICLR 2019
Transformer (SMILES) Transformer (Attention is All You Need. NeurIPS 2017) based on SMILES strings
LSTM (SMILES) Long short-term memory (Neural Computation 1997) based on SMILES strings

Generative Models

Model Reference
DemoDiff Graph Diffusion Transformers are In-Context Molecular Designers. ICLR 2026
GenMol GenMol: A Drug Discovery Generalist with Discrete Diffusion. ICML 2025
DeFoG DeFoG: Discrete Flow Matching for Graph Generation. ICML 2025
Graph DiT Graph Diffusion Transformers for Multi-Conditional Molecular Generation. NeurIPS 2024
DiGress DiGress: Discrete Denoising Diffusion for Graph Generation. ICLR 2023
GDSS Score-based Generative Modeling of Graphs via the System of Stochastic Differential Equations. ICML 2022
MolGPT MolGPT: Molecular Generation Using a Transformer-Decoder Model. Journal of Chemical Information and Modeling 2021
JTVAE Junction Tree Variational Autoencoder for Molecular Graph Generation. ICML 2018.
GraphGA A Graph-Based Genetic Algorithm and Its Application to the Multiobjective Evolution of Median Molecules. Journal of Chemical Information and Computer Sciences 2004
LSTM (SMILES) Long short-term memory (Neural Computation 1997) based on SMILES strings
Pretrained NovoMolGen: Causal LM pretrained on ZINC-22 for de novo SMILES generation.
MolGen-large: Seq2Seq SELFIES generator with high chemical validity.
MolGen-large-opt: MolGen-large fine-tuned for QED / p-logP optimization.
Molexar-10M-base: Fragment-SELFIES de novo and fragment-constrained generation.
Molexar-10M-omni: Multi-condition Molexar model for property-guided generation.
SAFE-GPT: GPT-2 causal LM pretrained on SAFE strings for de novo generation and scaffold-prefix completion.

Representation Models

Model Reference
SAND Learning Compressed Shape-Aware Molecular Representations for Virtual Screening. ICML 2026
MoAMa Motif-aware Attribute Masking for Molecular Graph Pre-training. LoG 2024
GraphMAE GraphMAE: Self-Supervised Masked Graph Autoencoders. KDD 2022
AttrMasking Strategies for Pre-training Graph Neural Networks. ICLR 2020
ContextPred Strategies for Pre-training Graph Neural Networks. ICLR 2020
EdgePred Strategies for Pre-training Graph Neural Networks. ICLR 2020
InfoGraph InfoGraph: Unsupervised and Semi-supervised Graph-Level Representation Learning via Mutual Information Maximization. ICLR 2020
Supervised Supervised pretraining
Pretrained GPT2-ZINC-87M: GPT-2 based model (87M parameters) pretrained on ZINC dataset with ~480M SMILES strings.
RoBERTa-ZINC-480M: RoBERTa based model (102M parameters) pretrained on ZINC dataset with ~480M SMILES strings.
UniKi/bert-base-smiles: BERT model pretrained on SMILES strings.
ChemBERTa-zinc-base-v1: RoBERTa model pretrained on ZINC dataset with ~100k SMILES strings.
ChemBERTa series: Available in multiple sizes and training objectives (MLM/MTR). ChemBERTa-5M-MLM, ChemBERTa-5M-MTR, ChemBERTa-10M-MLM, ChemBERTa-10M-MTR, ChemBERTa-77M-MLM, ChemBERTa-77M-MTR.
ChemGPT series: GPT-Neo based models pretrained on PubChem10M dataset with SELFIES strings. ChemGPT-1.2B, ChemGPT-4.7M, ChemGPT-19M.

Acknowledgements

The project template was adapted from https://github.com/lwaekfjlk/python-project-template. We thank the authors for their contribution to the open-source community.

This project is initiated and maintained by Gang Liu and Meng Jiang, and would not be possible without the valuable contributions from the open-source community, including the following members:

Man Hei Matthew Thom
Man Hei Matthew Thom

Integrating Pretrained Generator (NovoMolGen, MolGen, Molexar, SAFE-GPT), dataset splitting modules
Eric Inae
Eric Inae

Integrating MoAMa, GraphMAE, AttrMasking, ContextPred, EdgePred
Yihan Zhu
Yihan Zhu

Integrating DeFoG, GRIN, BFGNN, RPGNN, Transformer (SMILES)
Monica C. S
Monica C. S

Debugging and integrating training logs (#19)

评论

暂无评论