HuggingMolecules

We envision models that are pre-trained on a vast range of domain-relevant tasks to become key for molecule propertyprediction. This repository aims to give easy access to state-of-the-art pre-trained models.

Quick tour

To quickly fine-tune a model on a dataset using the pytorch lightning package follow the below example based on the MAT

model and the freesolv dataset:

from huggingmolecules import MatModel, MatFeaturizer

# The following import works only from the source code directory:
from experiments.src import TrainingModule, get_data_loaders

from torch.nn import MSELoss
from torch.optim import Adam

from pytorch_lightning import Trainer
from pytorch_lightning.metrics import MeanSquaredError

# Build and load the pre-trained model and the appropriate featurizer:
model = MatModel.from_pretrained('mat_masking_20M')
featurizer = MatFeaturizer.from_pretrained('mat_masking_20M')

# Build the pytorch lightning training module:
pl_module = TrainingModule(model,
                           loss_fn=MSELoss(),
                           metric_cls=MeanSquaredError,
                           optimizer=Adam(model.parameters()))

# Build the data loader for the freesolv dataset:
train_dataloader, _, _ = get_data_loaders(featurizer,
                                          batch_size=32,
                                          task_name='ADME',
                                          dataset_name='hydrationfreeenergy_freesolv')

# Build the pytorch lightning trainer and fine-tune the module on the train dataset:
trainer = Trainer(max_epochs=100)
trainer.fit(pl_module, train_dataloader=train_dataloader)

# Make the prediction for the batch of SMILES strings:
batch = featurizer(['C/C=C/C', '[C]=O'])
output = pl_module.model(batch)

Installation

Create your conda environment and install the rdkit package:

conda create -n huggingmolecules python=3.8.5
conda activate huggingmolecules
conda install -c conda-forge rdkit==2020.09.1

Then install huggingmolecules from the cloned directory:

conda activate huggingmolecules
pip install -e ./src

Project Structure

The project consists of two main modules: src/ and experiments/ modules:

  • The src/ module contains abstract interfaces for pre-trained models along with their implementations based on the

pytorch library. This module makes configuring, downloading and running existing models easy and out-of-the-box.

  • The experiments/ module makes use of abstract interfaces defined in the src/ module and implements scripts based

on the pytorch lightning package for running various experiments. This module makes training, benchmarking and

hyper-tuning of models flawless and easily extensible.

Supported models architectures

Huggingmolecules currently provides the following models architectures:

  • MAT

  • GROVER

For ease of benchmarking, we also include wrappers in the experiments/ module for three other models architectures:

  • chemprop

  • ChemBERTa

  • MolBERT

The src/ module

The implementations of the models in the src/ module are divided into three modules: configuration, featurization and

models module. The relation between these modules is shown on the following examples based on the MAT model:

Configuration examples

from huggingmolecules import MatConfig

# Build the config with default parameters values, 
# except 'd_model' parameter, which is set to 1200:
config = MatConfig(d_model=1200)

# Build the pre-defined config:
config = MatConfig.from_pretrained('mat_masking_20M')

# Build the pre-defined config with 'init_type' parameter set to 'normal':
config = MatConfig.from_pretrained('mat_masking_20M', init_type='normal')

# Save the pre-defined config with the previous modification:
config.save_to_cache('mat_masking_20M_normal.json')

# Restore the previously saved config:
config = MatConfig.from_pretrained('mat_masking_20M_normal.json')

Featurization examples

from huggingmolecules import MatConfig, MatFeaturizer

# Build the featurizer with pre-defined config:
config = MatConfig.from_pretrained('mat_masking_20M')
featurizer = MatFeaturizer(config)

# Build the featurizer in one line:
featurizer = MatFeaturizer.from_pretrained('mat_masking_20M')

# Encode (featurize) the batch of two SMILES strings: 
batch = featurizer(['C/C=C/C', '[C]=O'])

Models examples

from huggingmolecules import MatConfig, MatFeaturizer, MatModel

# Build the model with the pre-defined config:
config = MatConfig.from_pretrained('mat_masking_20M')
model = MatModel(config)

# Load the pre-trained weights 
# (which do not include the last layer of the model)
model.load_weights('mat_masking_20M')

# Build the model and load the pre-trained weights in one line:
model = MatModel.from_pretrained('mat_masking_20M')

# Encode (featurize) the batch of two SMILES strings: 
featurizer = MatFeaturizer.from_pretrained('mat_masking_20M')
batch = featurizer(['C/C=C/C', '[C]=O'])

# Feed the model with the encoded batch:
output = model(batch)

# Save the weights of the model (usually after the fine-tuning process):
model.save_weights('tuned_mat_masking_20M.pt')

# Load the previously saved weights
# (which now includes all layers of the model):
model.load_weights('tuned_mat_masking_20M.pt')

# Load the previously saved weights, but without 
# the last layer of the model ('generator' in the case of the 'MatModel')
model.load_weights('tuned_mat_masking_20M.pt', excluded=['generator'])

# Build the model and load the previously saved weights:
config = MatConfig.from_pretrained('mat_masking_20M')
model = MatModel.from_pretrained('tuned_mat_masking_20M.pt',
                                 excluded=['generator'],
                                 config=config)

Running tests

To run base tests for src/ module, type:

pytest src/ --ignore=src/tests/downloading/

To additionally run tests for downloading module (which will download all models to your local computer and therefore

may be slow), type:

pytest src/tests/downloading

The experiments/ module

Requirements

In addition to dependencies defined in the src/ module, the experiments/ module goes along with few others. To

install them, run:

pip install -r experiments/requirements.txt

The following packages are crucial for functioning of the experiments/ module:

  • pytorch lightning

  • optuna

  • gin-config

  • TDC

Neptune.ai

In addition, we recommend installing the neptune.ai package:

    *

    Sign up to neptune.ai at https://neptune.ai/.

    Get your Neptune API token (see

    getting-started for help).

    Export your Neptune API token to NEPTUNE_API_TOKEN environment variable.

    Install neptune-client:

    pip install neptune-client.

    Enable neptune.ai in the experiments/configs/setup.gin file.

    Update neptune.project_name parameters in experiments/configs/bases/*.gin files.

Running scripts:

We recommend running experiments scripts from the source code. For the moment there are three scripts implemented:

  • experiments/scripts/train.py - for training with the pytorch lightning package

  • experiments/scripts/tune_hyper.py - for hyper-parameters tuning with the optuna package

  • experiments/scripts/benchmark.py - for benchmarking based on the hyper-parameters tuning (grid-search)

In general running scripts can be done with the following syntax:

python -m experiments.scripts.<script_name> /
       -d <dataset_name> / 
       -m <model_name> /
       -b <parameters_bindings>

Then the script <script_name>.py runs with functions/methods parameters values defined in the following gin-config

files:

    * `experiments/configs/bases/<script_name>.gin`
    • experiments/configs/datasets/&lt;dataset_name&gt;.gin

    • experiments/configs/models/&lt;model_name&gt;.gin

If the binding flag -b is used, then bindings defined in &lt;parameters_binding&gt; overrides corresponding

bindings defined in above gin-config files.

So for instance, to fine-tune the MAT model (pre-trained on masking_20M task) on the freesolv dataset using GPU 1,

simply run:

python -m experiments.scripts.train /
       -d freesolv / 
       -m mat /
       -b model.pretrained_name=\&quot;mat_masking_20M\&quot;#train.gpus=[1]

or equivalently:

python -m experiments.scripts.train /
       -d freesolv / 
       -m mat /
       --model.pretrained_name mat_masking_20M /
       --train.gpus [1]

Local dataset

To use a local dataset, create an appropriate gin-config file in the experiments/configs/datasets directory and

specify the data.data_path parameter within. For details see

the get_data_split

implementation.

Benchmarking

For the moment there is one benchmark available. It works as follows:

  • experiments/scripts/benchmark.py: on the given dataset we fine-tune the given model on 10 learning rates and 6

seeded data splits (60 fine-tunings in total). Then we choose that learning rate that minimizes an averaged (on 6 data

splits) validation metric (metric computed on the validation dataset, e.g. RMSE). The result is the averaged value of

test metric for the chosen learning rate.

Running a benchmark is essentially the same as running any other script from the experiments/ module. So for instance

to benchmark the vanilla MAT model (without pre-training) on the Caco-2 dataset using GPU 0, simply run:

python -m experiments.scripts.benchmark /
       -d caco2 / 
       -m mat /
       --model.pretrained_name None /
       --train.gpus [0]

However, the above script will only perform 60 fine-tunings. It won’t compute the final benchmark result. To do that wee

need to run:

python -m experiments.scripts.benchmark --results_only /
       -d caco2 / 
       -m mat

The above script won’t perform any fine-tuning, but will only compute the benchmark result. If we had neptune enabled

in experiments/configs/setup.gin, all data necessary to compute the result will be fetched from the neptune

server.

Benchmark results

We performed the benchmark described in Benchmarking as experiments/scripts/benchmark.py for

various models architectures and pre-training tasks.

Summary

We report mean/median ranks of tested models across all datasets (both regression and classification ones). For detailed

results see Regression and Classification sections.

modelmean rankrank std
MAT 200k5.63.5
MAT 2M5.33.4
MAT 20M4.12.2
GROVER Base3.82.7
GROVER Large3.62.4
ChemBERTa7.42.8
MolBERT5.92.9
D-MPNN6.32.3
D-MPNN 2d6.42.0
D-MPNN mc5.32.1

Regression

As the metric we used MAE for QM7 and RMSE for the rest of datasets.

modelFreeSolvCaco-2ClearanceQM7Mean rank
MAT 200k0.913 ± 0.1960.405 ± 0.0300.649 ± 0.34187.578 ± 15.3755.25
MAT 2M0.898 ± 0.1650.471 ± 0.0700.655 ± 0.32781.557 ± 5.0886.75
MAT 20M0.854 ± 0.1970.432 ± 0.0340.640 ± 0.33581.797 ± 4.1765.0
Grover Base0.917 ± 0.1950.419 ± 0.0290.629 ± 0.33562.266 ± 3.5783.25
Grover Large0.950 ± 0.2020.414 ± 0.0410.627 ± 0.34064.941 ± 3.6162.5
ChemBERTa1.218 ± 0.2450.430 ± 0.0130.647 ± 0.314177.242 ± 1.8198.0
MolBERT1.027 ± 0.2440.483 ± 0.0560.633 ± 0.332177.117 ± 1.7998.0
Chemprop1.061 ± 0.1680.446 ± 0.0640.628 ± 0.33974.831 ± 4.7925.5
Chemprop 2d 11.038 ± 0.2350.454 ± 0.0490.628 ± 0.33677.912 ± 10.2316.0
Chemprop mc 20.995 ± 0.1360.438 ± 0.0530.627 ± 0.33775.575 ± 4.6834.25

1 chemprop with additional rdkit_2d_normalized features generator

2 chemprop with additional morgan_count features generator

Classification

We used ROC AUC as the metric.

modelHIABioavailabilityPPBRTox21 (NR-AR)BBBPMean rank
MAT 200k0.943 ± 0.0150.660 ± 0.0520.896 ± 0.0270.775 ± 0.0350.709 ± 0.0225.8
MAT 2M0.941 ± 0.0130.712 ± 0.0760.905 ± 0.0190.779 ± 0.0560.713 ± 0.0224.2
MAT 20M0.935 ± 0.0170.732 ± 0.0820.891 ± 0.0190.779 ± 0.0560.735 ± 0.0063.4
Grover Base0.931 ± 0.0210.750 ± 0.0370.901 ± 0.0360.750 ± 0.0850.735 ± 0.0064.0
Grover Large0.932 ± 0.0230.747 ± 0.0620.901 ± 0.0330.757 ± 0.0570.757 ± 0.0574.2
ChemBERTa0.923 ± 0.0320.666 ± 0.0410.869 ± 0.0320.779 ± 0.0440.717 ± 0.0097.0
MolBERT0.942 ± 0.0110.737 ± 0.0850.889 ± 0.0390.761 ± 0.0580.742 ± 0.0204.6
Chemprop0.924 ± 0.0690.724 ± 0.0640.847 ± 0.0520.766 ± 0.0400.726 ± 0.0087.0
Chemprop 2d0.923 ± 0.0150.712 ± 0.0670.874 ± 0.0300.775 ± 0.0410.724 ± 0.0066.8
Chemprop mc0.924 ± 0.0820.740 ± 0.0600.869 ± 0.0330.772 ± 0.0410.722 ± 0.0086.2

GitHub

https://github.com/gmum/huggingmolecules

Source: https://pythonawesome.com/easy-access-to-state-of-the-art-pre-trained-models-with-python/