GraphAF: a Flow-based Autoregressive Model for Molecular Graph Generation

Molecular graph generation is a fundamental problem for drug discovery and has been attracting growing attention. The problem is challenging since it requires not only generating chemically valid molecular structures but also optimizing their chemical properties in the meantime. Inspired by the recent progress in deep generative models, in this paper we propose a flow-based autoregressive model for graph generation called GraphAF. GraphAF combines the advantages of both autoregressive and flow-based approaches and enjoys: (1) high model flexibility for data density estimation; (2) efficient parallel computation for training; (3) an iterative sampling process, which allows leveraging chemical domain knowledge for valency checking. Experimental results show that GraphAF is able to generate 68 without chemical knowledge rules and 100 The training process of GraphAF is two times faster than the existing state-of-the-art approach GCPN. After fine-tuning the model for goal-directed property optimization with reinforcement learning, GraphAF achieves state-of-the-art performance on both chemical property optimization and constrained property optimization.


page 1

page 2

page 3

page 4


MoFlow: An Invertible Flow Model for Generating Molecular Graphs

Generating molecular graphs with desired chemical properties driven by d...

Gated Graph Recursive Neural Networks for Molecular Property Prediction

Molecule property prediction is a fundamental problem for computer-aided...

Learning To Navigate The Synthetically Accessible Chemical Space Using Reinforcement Learning

Over the last decade, there has been significant progress in the field o...

Constrained Bayesian Optimization for Automatic Chemical Design

Automatic Chemical Design leverages recent advances in deep generative m...

Graph Residual Flow for Molecular Graph Generation

Statistical generative models for molecular graphs attract attention fro...

Controlled Molecule Generator for Optimizing Multiple Chemical Properties

Generating a novel and optimized molecule with desired chemical properti...

Spatial Graph Attention and Curiosity-driven Policy for Antiviral Drug Discovery

We developed Distilled Graph Attention Policy Networks (DGAPNs), a curio...

Code Repositories


Research repo for AI aided drug discovery, de novo drug development and related topics

view repo


An alternative notation for describing molecules. Wheras SMILES is DFS-based, this is BFS-based.

view repo

1 Introduction

Designing novel molecular structures with desired properties is a fundamental problem in a variety of applications such as drug discovery and material science. The problem is very challenging, since the chemical space is discrete by nature, and the entire search space is huge, which is believed to be as large as  (Polishchuk et al., 2013)

. Machine learning techniques have seen a big opportunity in molecular design thanks to the large amount of data in these domains. Recently, there are increasing efforts in developing machine learning algorithms that can automatically generate chemically valid molecular structures and meanwhile optimize their properties.

Specifically, significant progress has been achieved by representing molecular structures as graphs and generating graph structures with deep generative models, e.g.

, Variational Autoencoders (VAEs) 

(Kingma and Welling, 2013), Generative Adversarial Networks (GANs) (Goodfellow et al., 2014) and Autoregressive Models (Van Oord et al., 2016). For example, Jin et al. (2018) proposed a Junction Tree VAE (JT-VAE) for molecular structure encoding and decoding. De Cao and Kipf (2018) studied how to use GANs for molecular graph generation. You et al. (2018a) proposed an approach called Graph Convolutional Policy Network (GCPN), which formulated molecular graph generation as a sequential decision process and dynamically generates the nodes and edges based on the existing graph substructures. They used reinforcement learning to optimize the properties of generated graph structures. Recently, another very related work called MolecularRNN (MRNN) (Popova et al., 2019) proposed to use an autoregressive model for molecular graph generation. The autoregressive based approaches including both GCPN and MRNN have demonstrated very competitive performance in a variety of tasks on molecular graph generation.

Recently, besides the aforementioned three types of generative models, normalizing flows have made significant progress and have been successfully applied to a variety of tasks including density estimation (Dinh et al., 2016; Papamakarios et al., 2017), variational inference (Kingma et al., 2016; Louizos and Welling, 2017; Rezende and Mohamed, 2015), and image generation (Kingma and Dhariwal, 2018). Flow-based approaches define invertible transformations between a latent base distribution (e.g.Gaussian distribution) and real-world high-dimensional data (e.g.

 images and speech). Such an invertible mapping allows the calculation of the exact data likelihood. Meanwhile, by using multiple layers of non-linear transformation between the hidden space and observation space, flows have a high capacity to model the data density. Moreover, different architectures can be designed to promote fast training 

(Papamakarios et al., 2017) or fast sampling (Kingma et al., 2016) depending on the requirement of different applications.

Inspired by existing work on autoregressive models and recent progress of deep generative models with normalizing flows, we propose a flow-based autoregressive model called GraphAF for molecular graph generation. GraphAF effectively combines the advantages of autoregressive and flow-based approaches. It has a high model capacity and hence is capable of modeling the density of real-world molecule data. The sampling process of GraphAF is designed as an autoregressive model, which dynamically generates the nodes and edges based on existing sub-graph structures. Similar to existing models such as GCPN and MRNN, such a sequential generation process allows leveraging chemical domain knowledge and valency checking in each generation step, which guarantees the validity of generated molecular structures. Meanwhile, different from GCPN and MRNN as an autoregressive model during training, GraphAF defines a feedforward neural network from molecular graph structures to the base distribution and is therefore able to compute the exact data likelihood in parallel. As a result, the training process of GraphAF is very efficient.

We conduct extensive experiments on the standard ZINC (Irwin et al., 2012) dataset. Results show that the training of GraphAF is significantly efficient, which is two times faster than the state-of-the-art model GCPN. The generated molecules are 100% valid by incorporating the chemical rules during generation. We are also surprised to find that even without using the chemical rules for valency checking during generation, the percentage of valid molecules generated by GraphAF can be still as high as 68%, which is significantly higher than existing state-of-the-art GCPN. This shows that GraphAF indeed has the high model capability to learn the data distribution of molecule structures. We further fine-tune the generation process with reinforcement learning to optimize the chemical properties of generated molecules. Results show that GraphAF significantly outperforms previous state-of-the-art GCPN on both property optimization and constrained property optimization tasks.

2 Related Work

Name Generative Model Sampling Process Training Process
VAE GAN RNN Flow One-shot Iterative Sequential Parallel
JT-VAE - - - - - -
RVAE - - - - - -
GCPN - - - - -
MRNN - - - - -
GraphNVP - - - - - -
GraphAF - - - - -
Table 1: Previous state-of-the-art algorithms for molecular graph generation. The comparison of training is only conducted between autoregressive models.

A variety of deep generative models have been proposed for molecular graph generation recently (Segler et al., 2017; Olivecrona et al., 2017; Samanta et al., 2018; Neil et al., 2018). The RVAE model (Ma et al., 2018) used a variational autoencoder for molecule generation, and proposed a novel regularization framework to ensure semantic validity. Jin et al. (2018) proposed to represent a molecule as a junction tree of chemical scaffolds and proposed the JT-VAE model for molecule generation. For the VAE-based approaches, the optimization of chemical properties is usually done by searching in the latent space with Bayesian Optimization (Jin et al., 2018). De Cao and Kipf (2018) used Generative Adversarial Networks for molecule generation. The state-of-the-art models are built on autoregressive based approaches (You et al., 2018b; Popova et al., 2019). (You et al., 2018b) formulated the problem as a sequential decision process by dynamically adding new nodes and edges based on current sub-graph structures, and the generation policy network is trained by a reinforcement learning framework. Recently, Popova et al. (2019) proposed an autoregressive model called MolecularRNN to generate new nodes and edges based on the generated nodes and edge sequences. The iterative nature of autoregressive model allows effectively leveraging chemical rules for valency checking during generation and hence the proportion of valid molecules generated by these models is very high. However, due to the sequential generation nature, the training process is usually slow. Our GraphAF approach enjoys the advantage of iterative generation process like autoregressive models (the mapping from latent space to observation space) and meanwhile calculates the exact likelihood corresponding to a feedforward neural network (the mapping from observation space to latent space), which can be implemented efficiently through parallel computation.

Two recent work—Graph Normalizing Flows (GNF) (Liu et al., 2019) and GraphNVP (Madhawa et al., 2019)—are also flow-based approaches for graph generation. However, our work is fundamentally different from their work. GNF defines a normalizing flow from a base distribution to the hidden node representations of a pretrained Graph Autoencoders. The generation scheme is done through two separate stages by first generating the node embeddings with the normalizing flow and then generate the graphs based on the generated node embeddings in the first stage. By contrast, in GraphAF, we define an autoregressive flow from a base distribution directly to the molecular graph structures, which can be trained end-to-end. GraphNVP also defines a normalizing flow from a base distribution to the molecular graph structures. However, the generation process of GraphNVP is one-shot, which cannot effectively capture graph structures and also cannot guarantee the validity of generated molecules. In our GraphAF, we formulate the generation process as a sequential decision process and effectively capture the sub-graph structures via graph neural networks, based on which we define a policy function to generate the nodes and edges. The sequential generation process also allows incorporating the chemical rules. As a result, the validity of the generated molecules can be guaranteed. We summarize existing approaches in Table 1.

3 Preliminaries

3.1 Autoregressive Flow

A normalizing flow (Kobyzev et al., 2019) defines a parameterized invertible deterministic transformation from a base distribution (the latent space, e.g., Gaussian distribution) to real-world observational space (e.g. images and speech). Let be an invertible transformation where is the base distribution, then we can compute the density function of real-world data , i.e., , via the change-of-variables formula:


Now considering two key processes of normalizing flows as a generative model: (1) Calculating Data Likelihood: given a datapoint , the exact density can be calculated by inverting the transformation , ; (2) Sampling: can be sampled from the distribution by first sample and then perform the feedforward transformation . To efficiently perform the above mentioned operations, is required to be invertible with an easily computable Jacobian determinant. Autoregressive flows (AF), originally proposed in Papamakarios et al. (2017), is a variant that satisfies these criteria, which holds a triangular Jacobian matrix, and the determinant can be computed linearly. Formally, given (

is the dimension of observation data), the autoregressive conditional probabilities can be parameterized as Gaussian distributions:


where and are unconstrained and positive scalar functions of respectively to compute the mean and deviation. In practice, these functions can be implemented as neural networks. The affine transformation of AF can be written as:


The Jacobian matrix in AF is triangular, since is non-zero only for . Therefore, the determinant can be efficiently computed through . Specifically, to perform density estimation, we can apply all individual scalar affine transformations in parallel to compute the base density, each of which depends on previous variables ; to sample , we can first sample and compute through the affine transformation, and then each subsequent can be computed sequentially based on previously observed .

3.2 Graph Representation Learning

Following existing work, we also represent a molecule as a graph , where

is the adjacency tensor and

is the node feature matrix. Assuming there are nodes in the graph, and are the number of different types of nodes and edges respectively, then and . if there exists a bond with type between and nodes.

Graph Convolutional Networks (GCN) (Duvenaud et al., 2015; Gilmer et al., 2017; Kearnes et al., 2016; Kipf and Welling, 2016; Schütt et al., 2017) are a family of neural network architectures for learning representations of graphs. In this paper, we use a variant of Relational GCN (R-GCN) (Schlichtkrull et al., 2018) to learn the node representations (i.e., atoms) of graphs with categorical edge types. Let denote the embedding dimension. We compute the node embeddings at the layer of R-GCN by aggregating messages from different edge types:


where denotes the slice of edge-conditioned adjacency tensor, , and . is a trainable weight matrix for the edge type. denotes an aggregation function such as mean pooling or summation. The initial hidden node representation is set as the original node feature matrix . After

message passing layers, we use the the final hidden representation

as the node representations. Meanwhile, the whole graph representations can be defined by aggregating the whole node representations using a readout function (Hamilton et al., 2017), e.g., summation.

4 Proposed Method

(a) Sampling Phases
(b) Framework
Figure 1:

Overview of the proposed GraphAF model. (a) Illustration of the generative procedure. New nodes or edges are marked in red. Starting from an empty graph and iteratively sample random variables to map them to atom/bond features. The numbered first three steps correspond to the maps in the bottom figure of Fig. 

1(b). (b) Computation graph of GraphAF. The left side are the nodes and edges and the right are latent variables.

4.1 GraphAF Framework

Similar to existing works like GCPN (You et al., 2018a) and MolecularRNN (Popova et al., 2019), we formalize the problem of molecular graph generation as a sequential decision process. Let denote a molecular graph structure. Starting from an empty graph , in each step a new node is generated based on the current sub-graph structure , i.e., . Afterwards, the edges between this new node and existing nodes are sequentially generated according to the current graph structure, i.e., . This process is repeated until all the nodes and edges are generated. An illustrative example is given in Fig. 1(a).

GraphAF is aimed at defining an invertible transformation from a base distribution (e.g. multivariate Gaussian) to a molecular graph structure . Note that we add one additional type of edge between two nodes, which corresponds to no edge between two nodes, i.e., . Since both the node type and the edge type are discrete, which do not fit into a flow-based model, a standard approach is to use Dequantization technique (Dinh et al., 2016; Kingma and Dhariwal, 2018) to convert discrete data into continuous data by adding real-valued noise. We follow this approach to preprocess a discrete graph into continuous data :


We present further discussions on dequantization techniques in Appendix A. Formally, we define the conditional distributions for the generation as:


where , and ,

are parameterized neural networks for defining the mean and standard deviation of a Gaussian distribution. More specifically, given the current sub-graph structure

, we use a -layer of Relational GCN (defined in Section 3.2) to learn the node embeddings , and the embedding of entire sub-graph , based on which we define the mean and standard deviations of Gaussian distributions to generate the nodes and edges respectively:


where denotes the sum-pooling operation, and denotes the embedding of the -th node in the embeddings . ,

are Multi-Layer Perceptrons (MLP) that predict the node types according to the current sub-graph embedding. and

, are MLPs that predict the types of edges according to the current sub-graph embedding and node embeddings.

To generate a new node and its edges connected to existing nodes, we just sample random variables and from the base Gaussian distribution and convert it to discrete features. More specifically,


where is the element-wise multiplication. In practice, a real molecular graph is generated by taking the

of generated continuous vectors,

i.e., and , where denotes a dimensional one-hot vector with dimension equal to 1.

Let , where is the number of atoms in the given molecule, GraphAF defines an invertible mapping between the base Gaussian distribution and the molecule structures . According to Eq. 9, the inverse process from to can be easily calculated as:


where and denote element-wise reciprocals of and respectively.

4.2 Efficient Parallel Training

In GraphAF, since is autoregressive, the Jacobian matrix of the inverse process is a triangular matrix, and its determinant can be calculated very efficiently. Given a mini-batch of training data , the exact density of each molecule under a given order can be efficiently computed by the change-of-variables formula in Eq. 1. Our objective is to maximize the likelihood of training data.

During training, we are able to perform parallel computation by defining a feedforward neural network between the input molecule graph and the output latent variable by using masking. The mask drops out some connections from inputs to ensure that R-GCN is only connected to the sub-graph when inferring the hidden variable of node , i.e., , and connected to sub-graph when inferring the hidden variable of edge , i.e., . This is similar to the approaches used in MADE (Germain et al., 2015) and MAF (Papamakarios et al., 2017). With the masking technique, GraphAF satisfies the autoregressive property, and at the same time can be efficiently calculated in just one forward pass by computing all the conditionals in parallel.

To further accelerate the training process, the nodes and edges of a training graph are re-ordered according to the breadth-first search (BFS) order, which is widely adopted by existing approaches for graph generation  (You et al., 2018b; Popova et al., 2019). Due to the nature of BFS, bonds can only be present between nodes within the same or consecutive BFS depths. Therefore, the maximum dependency distance between nodes is bounded by the largest number of nodes in a single BFS depth. In our data sets, any single BFS depth contains no more than 12 nodes, which means we only need to model the edges between current atom and the latest generated 12 atoms.

Due to space limitation, we summarize the detailed training algorithm into Appendix B.

4.3 Validity Constrained Sampling

In chemistry, there exist many chemical rules, which can help to generate valid molecules. Thanks to the sequential generation process, GraphAF can leverage these rules in each generation step. Specifically, we can explicitly apply a valency constraint during sampling to check whether current bonds have exceeded the allowed valency, which has been widely adopted in previous models (You et al., 2018a; Popova et al., 2019). Let denote the order of the chemical bond . In each edge generation step of , we check the following valency constraint for the and atoms:


If the newly added bond breaks the valency constraint, we just reject the bond , sample a new in the latent space and generate another new bond type. The generation process will terminate if one of the following conditions is satisfied: 1) the graph size reaches the max-size , 2) no bond is generated between the newly generated atom and previous sub-graph. Finally, hydrogens are added to the atoms that have not filled up their valencies.

4.4 Goal-directed Molecule Generation with Reinforcement Learning

So far, we have introduced how to use GraphAF to model the data density of molecular graph structures and generate valid molecules. Nonetheless, for drug discovery, we also need to optimize the chemical properties of generated molecules. In this part, we introduce how to fine-tune our generation process with reinforcement learning to optimize the properties of generated molecules.

State and Policy Network. The state is the current sub-graph, and the initial state is an empty graph. The policy network is the same as the autoregressive model defined in Section 4.1, which includes the process of generating a new atom based on the current sub-graph and generating the edges between the new atom and existing atoms, i.e., and . The policy network itself defines a distribution of molecular graphs . If there are no edges between the newly generated atom and current sub-graph, the generation process terminates. For the state transition dynamics, we also incorporate the valency check constraint.

Reward design. Similar to GCPN You et al. (2018a), we also incorporate both intermediate and final rewards for training the policy network. A small penalization will be introduced as the intermediate reward if the edge predictions violate the valency check. The final rewards include both the score of targeted-properties of generated molecules such as octanol-water partition coefficient (logP) or drug-likeness (QED) (Bickerton et al., 2012) and the chemical validity reward such as penalties for molecules with excessive steric strain and or functional groups that violate ZINC functional group filters (Irwin et al., 2012). The final reward is distributed to all intermediate steps with a discounting factor to stabilize the training.

In practice, we adopt Proximal Policy Optimization (PPO) (Schulman et al., 2017), an advanced policy gradient algorithm to train GraphAF in the above defined environment. Let be the shorthand notation of sub-graph

. Formally, in the RL process of training GraphAF, the loss function of PPO is written as:


where and are ratios of probabilities output by old and new policies, and

is the estimated advantage function with a moving average baseline to reduce the variance of estimation. More specifically, we treat generating a node and all its edges with existing nodes as one step and maintain a moving average baseline for each step. The clipped surrogate objective prevents the policy network from being updated to collapse for some extreme rewards.

5 Experiments

5.1 Experiment Setup

Evaluation Tasks. Following existing works on molecule generation (Jin et al., 2018; You et al., 2018a; Popova et al., 2019), we conduct experiments by comparing with the state-of-the-art approaches on three standard tasks. Density Modeling and Generation evaluates the model’s capacity to learn the data distribution and generate realistic and diverse molecules. Property Optimization concentrates on generating novel molecules with optimized chemical properties. For this task, we fine-tune our network pretrained from the density modeling task to maximize the desired properties. Constrained Property Optimization is first proposed in Jin et al. (2018), which is aimed at modifying the given molecule to improve desired properties while satisfying a similarity constraint.

Data. We use the ZINC250k molecular dataset (Irwin et al., 2012) for training. The dataset contains

drug-like molecules with a maximum atom number of 38. It has 9 atom types and 3 edge types. We use the open-source chemical software RDkit 

(Landrum, 2016) to preprocess molecules. All molecules are presented in kekulized form with hydrogen removed.

Baselines. We compare GraphAF with the following state-of-the-art approaches for molecule generation. JT-VAE (Jin et al., 2018) is a VAE-based model which generates molecules by first decoding a tree structure of scaffolds and then assembling them into molecules. JT-VAE has been shown to outperform other previous VAE-based models (Kusner et al., 2017; Gómez-Bombarelli et al., 2018; Simonovsky and Komodakis, 2018). GCPN is a state-of-the-art approach which combines reinforcement learning and graph representation learning methods to explore the vast chemical space. MolecularRNN (MRNN), another autoregressive model, uses RNN to generate molecules in a sequential manner. We also compare our model with GraphNVP (Madhawa et al., 2019), a recently proposed flow-based model. Results of baselines are taken from original papers unless stated.

Implementation Details.

GraphAF is implemented in PyTorch 

(Paszke et al., 2017)

. The R-GCN is implemented with 3 layers, and the embedding dimension is set as 128. The max graph size is set as 48 empirically. For density modeling, we train our model for 10 epochs with a batch size of 32 and a learning rate of 0.001. For property optimization, we perform a grid search on the hyperparameters and select the best setting according to the chemical scoring performance. We use Adam 

(Kingma and Ba, 2014) to optimize our model. Full training details can be found in Appendix C.

Method Validity Validity w/o check Uniqueness Novelty Reconstruction
JT-VAE 100% 100% 100% 76.7%
GCPN 100% 20% 99.97% 100%
MRNN 100% 65% 99.89% 100%
GraphNVP 42.60% 94.80% 100% 100%
GraphAF 100% 68% 99.10% 100% 100%
Table 2: Comparison of different models on density modeling and generation. Reconstruction is only evaluated on latent variable models. Validity w/o check is only evaluated on models with valency constraints. Result with is obtained by running GCPN’s open-source code. Results with are taken from Popova et al. (2019).
Method Validity Validity w/o check Uniqueness Novelty Reconstruction
ZINC250k 100% 68% 99.10% 100% 100%
QM9 100% 67% 94.51% 88.83% 100%
MOSES 100% 71% 99.99% 100% 100%
Table 3: Results of density modeling and generation on three different datasets.

5.2 Numerical Results

Density Modeling and Generation.

We evaluate the ability of the proposed method to model real molecules by utilizing the widely-used metrics: Validity is the percentage of valid molecules among all the generated graphs. Uniqueness is the percentage of unique molecules among all the generated molecules. Novelty is the percentage of generated molecules not appearing in training set. Reconstruction is the percentage of the molecules that can be reconstructed from latent vectors. We calculate the above metrics from 10,000 randomly generated molecules.

Table 2 shows that GraphAF achieves competitive results on all four metrics. As a flow-based model, GraphAF holds perfect reconstruction ability compared with VAE approaches. Our model also achieves a 100% validity rate since we can leverage the valency check during sequential generation. By contrast, the validity rate of another flow-based approach GraphNVP is only 42.60% due to its one-shot sampling process. An interesting result is that even without the valency check during generation, GraphAF can still achieve a validity rate as high as 68%, while previous state-of-the-art approach GCPN only achieves 20%. This indicates the strong flexibility of GraphAF to model the data density and capture the domain knowledge from unsupervised training on the large chemical dataset. We also compare the efficiency of different methods on the same computation environment, a machine with 1 Tesla V100 GPU and 32 CPU cores. To achieve the results in Table 2, JT-VAE and GCPN take around 24 and 8 hours, respectively, while GraphAF only takes 4 hours.

To show that GraphAF is not overfitted to the specific data set ZINC250k, we also conduct experiments on two other molecule datasets, QM9 (Ramakrishnan et al., 2014) and MOSES (Polykovskiy et al., 2018). QM9 contains 134k molecules with up to 9 heavy atoms, and MOSES is much larger and more challenging, which contains 1.9M molecules with up to 30 heavy atoms. Table 3 shows that GraphAF can always generate valid, unique and novel molecules even on the more complicated data set MOSES.

Degree Cluster Orbit Degree Cluster Orbit
GraphVAE 0.35 0.98 0.54 0.13 0.17 0.05
DEEPGMG 0.22 0.95 0.4 0.04 0.10 0.02
GraphRNN 0.08 0.12 0.04 0.09 0.22 0.003
GNF 0.20 0.20 0.11 0.03 0.10 0.001
GraphAF 0.18 0.20 0.02 0.03 0.11 0.001

0.03 0.01 0.01 0.04 0.05 0.06
GNF(1024) 0.12 0.15 0.02 0.01 0.03 0.0008
GraphAF(1024) 0.06 0.10 0.015 0.04 0.04 0.008

Table 4: Comparison between different graph generative models on general graphs with MMD metrics. We follow the evaluation scheme of GNF (Liu et al., 2019). Results of baselines are also taken from GNF.

Furthermore, though GraphAF is originally designed for molecular graph generation, it is actually very general and can be used to model different types of graphs by simply modifying the node and edge generating functions Edge-MLPs and Node-MLPs (Eq. 8). Following the experimental setup of Graph Normalizing Flows (GNF) (Liu et al., 2019), we test GraphAF on two generic graph datasets: COMMUNITY-SMALL, which is a synthetic data set containing 100 2-community graphs, and EGO-SMALL, which is a set of graphs extracted from Citeseer dataset (Sen et al., 2008). In practice, we use one-hot indicator vectors as node features for R-GCN. We borrow open source scripts from GraphRNN (You et al., 2018b) to generate datasets and evaluate different models. For evaluation, we report the Maximum Mean Discrepancy (MMD) (Gretton et al., 2012) between generated and training graphs using some specific metrics on graphs proposed by You et al. (2018b). The results in Table 4 demonstrate that when applied to generic graphs, GraphAF can still consistently yield comparable or better results compared with GraphRNN and GNF. We give the visualization of generated generic graphs in Appendix D.

Method Penalized logP QED
1st 2nd 3rd Validity 1st 2nd 3rd Validity
ZINC (Dataset) 4.52 4.30 4.23 100.0% 0.948 0.948 0.948 100.0%
JT-VAE (Jin et al., 2018) 5.30 4.93 4.49 100.0% 0.925 0.911 0.910 100.0%

GCPN (You et al., 2018a)
7.98 7.85 7.80 100.0% 0.948 0.947 0.946 100.0%
MRNN111Equal contribution, with order determined by flipping a coin. Work was done during internship at Mila. (Popova et al., 2019) 8.63 6.08 4.73 100.0% 0.844 0.796 0.736 100.0%
GraphAF 12.23 11.29 11.05 100.0% 0.948 0.948 0.947 100.0%
Table 5: Comparison of the top 3 property scores of generated molecules.
11footnotetext: The scores reported here are recalculated based on top 3 molecules presented in the original paper (Popova et al., 2019) using GCPN’s script.
(a) Penalized logP optimization
(b) QED optimization
(c) Constrained property optimization
Figure 2: Molecules generated in property optimization and constrained property optimization tasks. (a) Molecules with high penalized logP scores. (b) Molecules with high QED scores. (c) Two pairs of molecules in constrained property optimization for penalized logP with similarity 0.71(top) and 0.64(bottom).

Property Optimization.

In this task, we aim at generating molecules with desired properties. Specifically, we choose penalized logP and QED as our target property. The former score is logP score penalized by ring size and synthetic accessibility, while the latter one measures the drug-likeness of the molecules. Note that both scores are calculated using empirical prediction models and we adopt the script used in (You et al., 2018a) to make results comparable. To perform this task, we pretrain the GraphAF network for epochs for likelihood modeling, and then apply the RL process described in section 4.4 to fine-tune the network towards desired chemical properties. Detailed reward design and hyper-parameters setting can be found in Appendix C. Following existing works, we report the top-3 scores found by each model.

As shown in Table 5, GraphAF outperforms all baselines by a large margin for penalized logP score and achieves comparable results for QED. This phenomenon indicates that combined with RL process, GraphAF successfully captures the distribution of desired molecules. Note that we re-evaluate the properties of the top-3 molecules found by MolecularRNN, which turn out to be lower than the results reported in the original paper. Figure 2(a) and 2(b) show the molecules with the highest score discovered by our model. More realistic molecules generated by GraphAF with penalized logP score ranging from 5 to 10 are presented in Figure 6 in Appendix E.

One should note that, as defined in Sec 4.4, our RL process is close to the one used in previous work GCPN (You et al., 2018a). Therefore, the good property optimization performance is believed to come from the flexibility of flow. Compared with the GAN model used in GCPN, which is known to suffer from the mode collapse problem, flow is flexible at modeling complex distribution and generating diverse data (as shown in Table 2 and Table 3). This allows GraphAF to explore a variety of molecule structures in the RL process for molecule properties optimization.

Improvement Similarity Success Improvement Similarity Success Improvement Similarity Success
0.0 97.5% 100% 100%
0.2 97.1% 100% 100%
0.4 83.6% 100% 99.88%
0.6 46.4% 100% 96.88%
Table 6: Comparison of results on constrained property optimization.

Constrained Property Optimization.

The goal of the last task is to modify the given molecule to improve specified property with the constraint that the similarity between the original and modified molecule is above a threshold . Following Jin et al. (2018) and You et al. (2018a), we choose to optimize penalized logP for 800 molecules in ZINC250k with the lowest scores and adopt Tanimoto similarity with Morgan fingerprint (Rogers and Hahn, 2010) as the similarity metric.

Similar to the property optimization task, we pretrain GraphAF via density modeling and then fine-tune the model with RL. During generation, we set the initial states as sub-graphs randomly sampled from molecules to be optimized. For evaluation, we report the mean and standard deviation of the highest improvement and the corresponding similarity between the original and modified molecules in Table 6. Experiment results show that GraphAF significantly outperforms all previous approaches and almost always succeeds in improving the target property. Figure 2(c) visualizes two optimization examples, showing that our model is able to improve the penalized logP score by a large margin while maintaining a high similarity between the original and modified molecule.

6 Conclusion

We proposed GraphAF, the first flow-based autoregressive model for generating realistic and diverse molecular graphs. GraphAF is capable to model the complex molecular distribution thanks to the flexibility of normalizing flow, as well as generate novel and 100% valid molecules in empirical experiments. Moreover, the training of GraphAF is very efficient. To optimize the properties of generated molecules, we fine-tuned the generative process with reinforcement learning. Experimental results show that GraphAF outperforms all previous state-of-the-art baselines on the standard tasks. In the future, we plan to train our GraphAF model on larger datasets and also extend it to generate other types of graph structures (e.g., social networks).

7 Acknowledgement

We would like to thank Min Lin, Meng Qu, Andreea Deac, Laurent Dinh, Louis-Pascal A. C. Xhonneux and Vikas Verma for the extremely helpful discussions and comments.


  • G. R. Bickerton, G. V. Paolini, J. Besnard, S. Muresan, and A. L. Hopkins (2012) Quantifying the chemical beauty of drugs. Nature chemistry 4 (2), pp. 90. Cited by: §4.4.
  • N. De Cao and T. Kipf (2018) MolGAN: an implicit generative model for small molecular graphs. arXiv preprint arXiv:1805.11973. Cited by: §1, §2.
  • L. Dinh, J. Sohl-Dickstein, and S. Bengio (2016) Density estimation using real nvp. arXiv preprint arXiv:1605.08803. Cited by: §1, §4.1.
  • D. K. Duvenaud, D. Maclaurin, J. Iparraguirre, R. Bombarell, T. Hirzel, A. Aspuru-Guzik, and R. P. Adams (2015) Convolutional networks on graphs for learning molecular fingerprints. In Advances in neural information processing systems, pp. 2224–2232. Cited by: §3.2.
  • M. Germain, K. Gregor, I. Murray, and H. Larochelle (2015) Made: masked autoencoder for distribution estimation. In International Conference on Machine Learning, pp. 881–889. Cited by: §4.2.
  • J. Gilmer, S. S. Schoenholz, P. F. Riley, O. Vinyals, and G. E. Dahl (2017) Neural message passing for quantum chemistry. In Proceedings of the 34th International Conference on Machine Learning-Volume 70, pp. 1263–1272. Cited by: §3.2.
  • R. Gómez-Bombarelli, J. N. Wei, D. Duvenaud, J. M. Hernández-Lobato, B. Sánchez-Lengeling, D. Sheberla, J. Aguilera-Iparraguirre, T. D. Hirzel, R. P. Adams, and A. Aspuru-Guzik (2018) Automatic chemical design using a data-driven continuous representation of molecules. ACS central science 4 (2), pp. 268–276. Cited by: §5.1.
  • I. Goodfellow, J. Pouget-Abadie, M. Mirza, B. Xu, D. Warde-Farley, S. Ozair, A. Courville, and Y. Bengio (2014) Generative adversarial nets. In Advances in neural information processing systems, pp. 2672–2680. Cited by: §1.
  • A. Gretton, K. M. Borgwardt, M. J. Rasch, B. Schölkopf, and A. Smola (2012) A kernel two-sample test. Journal of Machine Learning Research 13 (Mar), pp. 723–773. Cited by: §5.2.
  • W. Hamilton, Z. Ying, and J. Leskovec (2017) Inductive representation learning on large graphs. In Advances in Neural Information Processing Systems, pp. 1024–1034. Cited by: §3.2.
  • J. Ho, X. Chen, A. Srinivas, Y. Duan, and P. Abbeel (2019) Flow++: improving flow-based generative models with variational dequantization and architecture design. In Proceedings of the 36th International Conference on Machine Learning, External Links: Link Cited by: Appendix A, Appendix A.
  • J. J. Irwin, T. Sterling, M. M. Mysinger, E. S. Bolstad, and R. G. Coleman (2012) ZINC: a free tool to discover chemistry for biology. Journal of chemical information and modeling 52 (7), pp. 1757–1768. Cited by: §1, §4.4, §5.1.
  • W. Jin, R. Barzilay, and T. Jaakkola (2018) Junction tree variational autoencoder for molecular graph generation. arXiv preprint arXiv:1802.04364. Cited by: §1, §2, §5.1, §5.1, §5.2, Table 5.
  • S. Kearnes, K. McCloskey, M. Berndl, V. Pande, and P. Riley (2016) Molecular graph convolutions: moving beyond fingerprints. Journal of computer-aided molecular design 30 (8), pp. 595–608. Cited by: §3.2.
  • D. P. Kingma and J. Ba (2014) Adam: a method for stochastic optimization. In 3nd International Conference on Learning Representations, Cited by: §5.1.
  • D. P. Kingma and M. Welling (2013) Auto-encoding variational bayes. In 2nd International Conference on Learning Representations, Cited by: §1.
  • D. P. Kingma and P. Dhariwal (2018) Glow: generative flow with invertible 1x1 convolutions. In Advances in Neural Information Processing Systems, pp. 10215–10224. Cited by: §1, §4.1.
  • D. P. Kingma, T. Salimans, R. Jozefowicz, X. Chen, I. Sutskever, and M. Welling (2016) Improved variational inference with inverse autoregressive flow. In Advances in neural information processing systems, pp. 4743–4751. Cited by: §1.
  • T. N. Kipf and M. Welling (2016) Semi-supervised classification with graph convolutional networks. arXiv preprint arXiv:1609.02907. Cited by: §3.2.
  • I. Kobyzev, S. Prince, and M. A. Brubaker (2019) Normalizing flows: introduction and ideas. arXiv preprint arXiv:1908.09257. Cited by: §3.1.
  • M. J. Kusner, B. Paige, and J. M. Hernández-Lobato (2017) Grammar variational autoencoder. In Proceedings of the 34th International Conference on Machine Learning-Volume 70, pp. 1945–1954. Cited by: §5.1.
  • G. Landrum (2016) RDKit: open-source cheminformatics software. Cited by: §5.1.
  • J. Liu, A. Kumar, J. Ba, J. Kiros, and K. Swersky (2019) Graph normalizing flows. arXiv preprint arXiv:1905.13177. Cited by: §2, §5.2, Table 4.
  • C. Louizos and M. Welling (2017) Multiplicative normalizing flows for variational bayesian neural networks. In Proceedings of the 34th International Conference on Machine Learning-Volume 70, pp. 2218–2227. Cited by: §1.
  • T. Ma, J. Chen, and C. Xiao (2018) Constrained generation of semantically valid graphs via regularizing variational autoencoders. In Advances in Neural Information Processing Systems, pp. 7113–7124. Cited by: §2.
  • K. Madhawa, K. Ishiguro, K. Nakago, and M. Abe (2019) GraphNVP: an invertible flow model for generating molecular graphs. arXiv preprint arXiv:1905.11600. Cited by: §2, §5.1.
  • D. Neil, M. H. S. Segler, L. Guasch, M. Ahmed, D. Plumbley, M. Sellwood, and N. Brown (2018) Exploring deep recurrent models with reinforcement learning for molecule design. In 6th International Conference on Learning Representations, Workshop Track Proceedings, Cited by: §2.
  • M. Olivecrona, T. Blaschke, O. Engkvist, and H. Chen (2017) Molecular de-novo design through deep reinforcement learning. Journal of cheminformatics 9 (1), pp. 48. Cited by: §2.
  • G. Papamakarios, T. Pavlakou, and I. Murray (2017) Masked autoregressive flow for density estimation. In Advances in Neural Information Processing Systems, pp. 2338–2347. Cited by: §1, §3.1, §4.2.
  • A. Paszke, S. Gross, S. Chintala, G. Chanan, E. Yang, Z. DeVito, Z. Lin, A. Desmaison, L. Antiga, and A. Lerer (2017) Automatic differentiation in pytorch. In NIPS-W, Cited by: §5.1.
  • P. G. Polishchuk, T. I. Madzhidov, and A. Varnek (2013) Estimation of the size of drug-like chemical space based on gdb-17 data. Journal of Computer-Aided Molecular Design 27 (8), pp. 675–679. Cited by: §1.
  • D. Polykovskiy, A. Zhebrak, B. Sanchez-Lengeling, S. Golovanov, O. Tatanov, S. Belyaev, R. Kurbanov, A. Artamonov, V. Aladinskiy, M. Veselov, A. Kadurin, S. Nikolenko, A. Aspuru-Guzik, and A. Zhavoronkov (2018) Molecular Sets (MOSES): A Benchmarking Platform for Molecular Generation Models. arXiv preprint arXiv:1811.12823. Cited by: §5.2.
  • M. Popova, M. Shvets, J. Oliva, and O. Isayev (2019) MolecularRNN: generating realistic molecular graphs with optimized properties. arXiv preprint arXiv:1905.13372. Cited by: §1, §2, §4.1, §4.2, §4.3, §5.1, Table 2, Table 5, §5.2.
  • R. Ramakrishnan, P. O. Dral, M. Rupp, and O. A. von Lilienfeld (2014) Quantum chemistry structures and properties of 134 kilo molecules. Scientific Data 1. Cited by: §5.2.
  • D. J. Rezende and S. Mohamed (2015) Variational inference with normalizing flows. arXiv preprint arXiv:1505.05770. Cited by: §1.
  • D. Rogers and M. Hahn (2010) Extended-connectivity fingerprints. Journal of chemical information and modeling 50, pp. 742–754. Cited by: §5.2.
  • B. Samanta, A. De, N. Ganguly, and M. Gomez-Rodriguez (2018) Designing random graph models using variational autoencoders with applications to chemical design. arXiv preprint arXiv:1802.05283. Cited by: §2.
  • M. Schlichtkrull, T. N. Kipf, P. Bloem, R. Van Den Berg, I. Titov, and M. Welling (2018) Modeling relational data with graph convolutional networks. In European Semantic Web Conference, pp. 593–607. Cited by: §3.2.
  • J. Schulman, F. Wolski, P. Dhariwal, A. Radford, and O. Klimov (2017) Proximal policy optimization algorithms. arXiv preprint arXiv:1707.06347. Cited by: §4.4.
  • K. T. Schütt, F. Arbabzadah, S. Chmiela, K. R. Müller, and A. Tkatchenko (2017) Quantum-chemical insights from deep tensor neural networks. Nature communications 8, pp. 13890. Cited by: §3.2.
  • M. H. Segler, T. Kogej, C. Tyrchan, and M. P. Waller (2017)

    Generating focused molecule libraries for drug discovery with recurrent neural networks

    ACS central science 4 (1), pp. 120–131. Cited by: §2.
  • P. Sen, G. M. Namata, M. Bilgic, L. Getoor, B. Gallagher, and T. Eliassi-Rad (2008) Collective classification in network data. AI Magazine 29 (3), pp. 93–106. External Links: Link Cited by: §5.2.
  • M. Simonovsky and N. Komodakis (2018) Graphvae: towards generation of small graphs using variational autoencoders. In International Conference on Artificial Neural Networks, pp. 412–422. Cited by: §5.1.
  • L. Theis, A. van den Oord, and M. Bethge (2016) A note on the evaluation of generative models. In International Conference on Learning Representations, Note: arXiv:1511.01844 External Links: Link Cited by: Appendix A.
  • A. Van Oord, N. Kalchbrenner, and K. Kavukcuoglu (2016) Pixel recurrent neural networks. In International Conference on Machine Learning, pp. 1747–1756. Cited by: §1.
  • J. You, B. Liu, Z. Ying, V. Pande, and J. Leskovec (2018a) Graph convolutional policy network for goal-directed molecular graph generation. In Advances in Neural Information Processing Systems, pp. 6410–6421. Cited by: §1, §4.1, §4.3, §4.4, §5.1, §5.2, §5.2, §5.2, Table 5.
  • J. You, R. Ying, X. Ren, W. L. Hamilton, and J. Leskovec (2018b) Graphrnn: generating realistic graphs with deep auto-regressive models. arXiv preprint arXiv:1802.08773. Cited by: §2, §4.2, §5.2.

Appendix A Disccusions on Dequantization techniques

The dequantization techniques allow mapping the discrete data into the continuous one by adding a small noise to each dimension. By adding noise from , we can ensure that the range of different categories will not overlap. For example, after dequantization, the value of 1-entry in the one-hot vector lies in while the 0-entry lies in . Therefore, we can map the dequantized continuous data back to the discrete one-hot data by easily performing the operation in the generation process. Theoretically, as shown in Theis et al. (2016); Ho et al. (2019), training a continuous density model on uniform dequantized data can be interpreted as maximizing a lower bound on the log-likelihood for the original discrete data. Mathematically, this statement holds for both image data and binary/categorical data.

Furthermore, as suggested in Ho et al. (2019), instead of adding random uniform noise to each discrete data for dequantization, a more advanced dequantization technique is to treat the noise as a hidden variable and use variational inference to infer the optimum noise added to each discrete data, which we would like to explore in our future work.

Appendix B Parallel Training Algorithm

Input: learning rate, batch size, maximum dependency distance in BFS, Adam hyperparameters , use as the product of elements across dimensions of a tensor

Initial: Parameters of GraphAF (R-GCN, Node-MLP and Edge-MLP)

1:  while  is not converged do
2:     for  do
3:        Sample a molecule from dataset and get the graph size
4:        Convert to with BFS re-ordering
5:        for  do
10:           for  do
15:           end for
16:        end for
18:     end for
20:  end while
Algorithm 1 Parallel Training Algorithm of GraphAF

Appendix C Experiment details

In this section, we elaborate the network architecture and the implementation details of three tasks.

Network architecture.

The network architecture is fixed among all three tasks. More specifically, the R-GCN is implemented with 3 layers and the embedding dimension is set as 128. We use batch normalization before graph pooling to accelerate the convergence and choose sum-pooling as the readout function for graph representations. Both node MLPs and edge MLPs have two fully-connected layers equipped with


Density Modeling and Generation.

To achieve the results in Table 2, we train GraphAF on ZINC250K with a batch size of 32 on 1 Tesla V100 GPU and 32 CPU cores for 10 epochs. We optimize our model with Adam with a fixed learning rate of 0.001.

Property Optimization.

For both property optimization and constrained property optimization, we first pretrain a GraphAF network via the density modeling task for 300 epochs, and then fine-tune the network toward desired molecular distribution through RL process. Following are details about the reward design for property optimization. The reward of each step consists of step-wise validity rewards and the final rewards discounted by a fixed factor . The step-wise validity penalty is fixed as -1. The final reward of a molecule includes both property-targeted reward and chemical validation reward. We adopt the same chemical validation rewards as GCPN. We define property-targeted reward as follows:


is set to 0.97 for QED optimization and 0.9 for penalized logP optimization respectively. We fine-tune the pretrained model for 200 iterations with a fixed batch size of 64 using Adam optimizer. We also adopt a linear learning rate warm-up to stabilize the training. We perform the grid search to determine the optimal hyperparameters according to the chemical scoring performance. The search space is summarised in Table 7.

PARAM Description Search space
Learning rate {0.001, 0.0005, 0.0001}
Coefficient for QED score {2, 3, 4, 5}
Temperature for exponential function {3, 4, 5}
Number of warm up iterations {12, 24, 36}
Table 7: Tuned-parameters for policy gradient and their search space.

Constrained Property Optimization.

We first introduce the way we sample sub-graphs from 800 ZINC molecules. Given a molecule, we first randomly sample a BFS order and then drop the last nodes in BFS order as well as edges induced by these nodes, where is randomly chosen from each time. Finally, we reconstruct the sub-graph from the remaining nodes in the BFS sequence. Note that the final sub-graph is connected due to the nature of BFS order. For reward design, we set it as the improvement of the target score. We fine-tune the pretrained model for 200 iterations with a batch size of 64. We also use Adam with a learning rate of 0.0001 to optimize the model. Finally, each molecule is optimized for 200 times by the tuned model.

Appendix D Visualization of generated generic graphs

We present visualizations of graphs from both the training set and generated graphs by GraphAF in Figure 3 and Figure 4. The visualizations demonstrate that GraphAF has strong ability to model different graph structures in the generic graph datasets.

Appendix E More molecule samples

We present more molecule samples generated by GraphAF in the following pages. Figure 5 presents 50 molecules randomly sampled from multivariate Gaussian, which justify the ability of our model to generate novel, realistic and unique molecules. From Figure 6 we can see that our model is able to generate molecules with high and diverse penalized logP scores ranging from 5 to 10. For constrained property optimization of penalized logP score, as shown by Figure 7, our model can either reduce the ring size, remove the big ring or grow carbon chains from the original molecule, improving the penalized logP score by a large margin.

(a) Graphs from training set
(b) Graphs generated by GraphAF
Figure 3: Visualizations of training graphs and generated graphs of EGO-SMALL.
(a) Graphs from training set
(b) Graphs generated by GraphAF
Figure 4: Visualizations of training graphs and generated graphs of COMMUNITY-SMALL.
Figure 5: 50 molecules sampled from prior.
Figure 6: Molecule samples with high penalized logp score generated by GraphAF.
Figure 7: More results on constrained property optimization for penalized logP score. Numbers beside the arrow denote similarity and improvement of the given molecule pair respectively.