Molecule Generation by Principal Subgraph Mining and Assembling
Abstract
Molecule generation is central to a variety of applications.
Current attention has been paid to approaching the generation task as subgraph prediction and assembling.
Nevertheless, these methods usually rely on hand-crafted or external subgraph construction, and the subgraph assembling depends solely on local arrangement.
In this paper, we define a novel notion, principal subgraph that is closely related to the informative pattern within molecules.
Interestingly, our proposed merge-andupdate subgraph extraction method can automatically discover frequent principal subgraphs from the dataset, while previous methods are incapable of.
Moreover, we develop a two-step subgraph assembling strategy, which first predicts a set of subgraphs in a sequence-wise manner and then assembles all generated subgraphs globally as the final output molecule.
Built upon graph variational auto-encoder, our model is demonstrated to be effective in terms of several evaluation metrics and efficiency, compared with state-of-the-art methods on distribution learning and (constrained) property optimization tasks.
Introduction
Generating chemically valid molecules with desired properties is central to a variety of applications in drug discovery and material science.
In contrast to searching countless potential candidates by expert chemists or pharmacologists, designing generative models that can produce molecules automatically is more efficient and now a prevailing topic in machine learning.
Recently, there have been various works[18, 26, 47, 24, 9, 39, 20] utilizing graphs to characterize the distribution of molecules
[Figure]
[16, 23] marked with their frequencies of occurrence. In general, these graph-based generation methods can be clustered into two categories: the atom level [25, 47, 26, 20] and the subgraph level [18, 19, 46], in terms of what the basic generation unit is.
Compared with the atom-level methods, exploring subgraphs for generating molecules (as illustrated in Figure 1) exhibits three potential benefits.
First, it can capture the regularities of atomic combinations and discover repetitive patterns in molecules, thus more capable of generating realistic molecules.
Second, it is able to reflect chemical properties, since it has been revealed that the chemical properties are closely related to certain substructures (i.e., subgraphs) [31, 20].
Finally, leveraging subgraphs as the building blocks enables efficient training and inference, as the searching time is remarkably reduced by representing a molecule as a set of subgraphs other than atoms.
However, current subgraph-level methods [18, 19, 46] are still suboptimal in two senses.
For one thing, the vocabulary of the molecular fragments is constructed by simple hand-crafted rules [18, 19] or borrowed straightly from external chemical fragment libraries [46], which is unable (at least uncertain) to reveal the frequent patterns existing in the dataset.
For another, the prediction and the assembling of the subgraphs are conducted either autoregressively [19, 46] or according to a pre-defined tree structure [18], both of which are inflexible and defective, since each newly predicted subgraph is only allowed to attach a local set of previous subgraphs during the assembling process.
To address the above two pitfalls, this paper proposes a novel framework: Principal Subgraph Variational Auto-Encoder (PS-VAE).
PS-VAE first creates a vocabulary of molecular fragments from any given dataset, which starts from all distinct atoms and then merges the neighboring fragments as a new one to update the vocabulary.
Interestingly, the fragments derived by such a merge-and-update strategy are actually principal subgraphs which, as a novel concept defined by this paper, represent the frequent and largest repetitive patterns of molecules.
We also theoretically prove that any principal subgraph can be universally covered by our vocabulary.
Moreover, we develop a two-step subgraph assembling strategy, which first sequentially predicts a set of fragments and then assembles all generated subgraphs globally.
This two-step fashion makes our method less permutation-dependent and focus more on global connectivity against traditional methods [18, 19, 46].
We conduct extensive experiments on the ZINC250K [16] and QM9 [6, 37] datasets.
Results demonstrate that our PS-VAE outperforms state-of-the-art models on distribution learning, (constrained) property optimization as well as GuacaMol goal-directed benchmarks [7].
Besides, PS-VAE is efficient and about six times faster than the fastest autoregressive baseline.
Related Work
Molecule Generation.
Regarding the representation of molecules, existing generation models can be divided into two categories: text-based and graph-based methods.
Text-based models [13, 23, 5] usually adopt the Simplified Molecular-Input Line-entry System ([40], SMILES) to describe each molecule, which is simple and efficient.
However, they are not robust because slight perturbations in SMILES could result in significant changes in molecule structure [47, 24].
The graph-based counterparts [9, 39, 20], therefore, have gained increasing attention recently.
Li et al.
[25] proposed a generation model for graphs and demonstrated it performed better than the text-based strategy.
You et al.
[47] used reinforcement learning to generate molecules sequentially under the guidance of mixed rewards in terms of the chemical validity and other property scores.
Popova et al.
[34] proposed MRNN to autoregressively generate nodes and edges.
Shi et al.
[39] designed a flow-based autoregressive model and exploited reinforcement learning for goal-directed generation.
However, these models use atoms as the basic generation unit, leading to long sequences and therefore timeconsuming training process.
On the contrary, our method applies subgraph-level representation, which not only captures chemical properties but also is computationally efficient.
Subgraph-Level Molecule Generation Several works have been developed for subgraph-level generation.
In particular, Jin et al.
[18] suggested generating molecules in the form of junction trees where each node is a ring or edge.
Jin et al.
[19] decomposed molecules into subgraphs by breaking all the bridge bonds.
It used a complex hierarchical model for polymer generation and graph-to-graph translation.
Yang et al.
[46] integrated reinforcement learning with the subgraph vocabulary created from existing chemical fragment libraries.
Different from Jin et al.
[18, 19], Yang et al.
[46] which use manual rules to extract subgraphs or utilize existing libraries, we automatically extract frequent principal subgraphs to better capture the regularities in molecules for subgraph-level decomposition.
Our work also relates to traditional subgraph mining literature [15, 45, 33].
While seeking generic frequent subgraphs is known to be NP-hard [22, 17], our work focuses on finding frequent principal subgraphs by merging two adjacent fragments, which alleviates time complexity to a large extent.
To the best of our knowledge, we are the first to utilize frequent subgraphs in generation tasks
. Our Proposed PS-VAE
This section presents the details of the proposed PS-VAE, consisting of the principal subgraph definition and extraction in Section 3.1 and the two-step generation in Section 3.2.
3.1 Principal Subgraph
A molecule can be represented as a graph G = ⟨V , E⟩ , where V is a set of nodes corresponding to atoms and E is a set of edges corresponding to chemical bonds.
We define a subgraph of G as
S = ⟨ ˜ V , ˜ E⟩ ⊆ G , were ˜ V ⊆ V and ˜ E ⊆ E .
We say subgraph S spatially intersects with subgraph
S ′ if there are certain atoms in a molecule belong to both S and S ′ , denoted as S ∩ S ′ ̸
= ∅ .
Note that if two subgraphs look the same (with the same topology), but they are constructed by different atom instances, they are not spatial intersected.
Similarly, if two subgraphs S and S ′ appear in the same molecule, we call their spatially union subgraph as U = S (cid:83) S ′ , where the nodes of U are the union set of ˜ V and ˜ V ′ , and its edges are the union of ˜ E and ˜ E
′ plus all edges connecting S and S ′ .
A decomposition of a molecule G is derived as a set of non-overlapped subgraphs {S i } ni and the edges connecting them {E ij } n,ni,j , if G =
( (cid:83) ni S i ) (cid:83) ( (cid:83) n,ni,j E ij ) and S i ∩ S j = ∅ for any i ̸
= j .
The frequency of a subgraph occurring in all molecules of a given dataset measures its repeability and epidemicity, which should be an important property.
Formally, we define the frequency of a subgraph
S as c ( S ) =
(cid:80) i
c ( S|G i ) where c ( S|G i ) computes the occurrence of S in a molecule G i .
Without loss of generality, we assume all molecules and subgraphs we discuss are connected.
With the aforementioned notations, we propose a novel and central concept below.
Definition 3.1 (Principal Subgraph) .
We call subgraph S a principal subgraph, if any other subgraph
S ′ that spatially intersects with S in a certain molecule satisfies either S ′ ⊆ S or c ( S ′ )
≤ c ( S ) .
Amongst all subgraphs of the larger frequency, a principal subgraph basically represents the “largest” repetitive pattern in size within the data.
It is desirable to leverage patterns of this kind as the building blocks for molecule generation since those subgraphs with a larger size than them are less frequent/reusable.
We will prove that our designed vocabulary is capable of mining these subgraphs.
Now we introduce the proposed vocabulary construction process.
We call each subgraph of the constructed vocabulary as a fragment .
We generate all fragments via the following stages:
Initialization .
The vocabulary V is initialized with all unique atoms (subgraph with one node).
Merge .
For every two neighboring fragments F and F ′ in the current vocabulary, we merge them by deriving the union F (cid:83) F ′ .
Here, the neighboring fragments of a given fragment F in a molecule is defined as the ones that contain at least one first-order neighbor nodes of a certain node in F .
Update .
We count the frequency of each identical merged subgraph in the last stage.
We choose the most frequent one as a new fragment in the vocabulary V .
Then, we go back to the merge stage until the vocabulary size reaches the predefined number N.[-
-]
1: Input: A set of graphs D and the desired number N of principal subgraphs to learn.
2: Output: A set of principal subgraphs V and the counter C of principal subgraphs.
3: V ← { GraphToSMILES( ⟨{ a } , ∅⟩ ) } ; { Initially, V corre- sponds to all atoms a that appear in D . } 4: N ′ ← max( N, | V | ) ; 5: while | V | < N ′ do 6: C ← EmptyMap() ; { Initialize a counter. } 7: for G in D do 8: for ⟨F i , F j , E ij ⟩ in G do 9: F ← Merge( ⟨F i , F j , E ij ⟩ ) ; { Merge neighboring fragments into a new fragment. } 10: s ← GraphToSMILES( F ) ; { Convert the to SMILES representation. }
[Table]
[Table]
[Table] [Table]
[Table]
( C ) ; { Find the most frequent merged frag- ment. } 15:
F ← SMILESToGraph(s) ; { ConverttheSMILESstring to graph representation .} 16:
V ← V ∪ { s } ; D ′ ← {} ; 17: for G in D do 18:
G ′ ← MergeSubGraph( G , F ) ; { Update the graph representation if possible. } 19:
D ′ ← D ′ ∪ {G ′ } ; 20: end for 21:
D ← D ′ ; 22: end while
[Figure]
Figure 2 illustrates the above processes and Algorithm 1 gives the flowchart.
Notice that Algorithmhas exploited the conversion from molecular subgraph to SMILES [40] to not only ensure the
[Figure]
After training, we can directly sample from the latent space to generate molecules.
uniqueness but also better calculate the occurrence of each merged subgraph by string comparison.
One notable merit is that we always track the decomposition of each molecule at each iteration, which is crucial for the training of the two-step decoder introduced in the next subsection.
More importantly, we have the following theorem to demonstrate the benefit of Algorithm 1.
Theorem 3.2.
The vocabulary V constructed by Algorithm 1 exhibits the following advantages.
(i) Monotonicity :
The frequency of the non-single-atom fragments in V decreases monotonically, namely, ∀F i , F j ∈ V , c ( F i ) ≤ c ( F j ) , if i ≥ j .
(ii) Significance :
Each fragment F in V is a principal subgraph.
(iii) Completeness :
For any principal subgraph S arising in the dataset, there always exits a fragment F in V satisfying S ⊆ F , c ( S )
=
c ( F ) , when V has collected all fragments with frequency no less than c ( S ) .
The conclusion by Theorem 3.2 is interesting and valuable.
It states that our algorithm is able to discover frequent principal subgraphs, and any principal subgraph can be represented (at least contained) by our certain extracted fragment if the size of the vocabulary is sufficiently large.
This is also a meaningful extension to traditional subgraph mining literature [17], in which seeking the most frequent subgraphs is known to be NP-hard.
Algorithm 1 can somehow address this problem efficiently by focusing mainly on finding the most frequent principal subgraphs.
3.2 Two-step Molecule Generation
The molecule generation is modeled as a two-step task: first predicting which fragment should be chosen from the vocabulary created in the last subsection, and then proceeding with how to assemble the predicted fragments.
Although in the first step we predict the fragments in a sequence-wise manner, we globally investigate if every two predicted fragments should be linked in the second step.
This two-step fashion makes our method not only less permutation-dependent and thus more sample-efficient than the generic autoregressive counterparts [25], but also more flexible than the methods [18] that require predefined junction tree or adjacent connections between subgraphs.
We will provide experimental evaluations in Table 4 to justify the benefit of our proposed two-step generation strategy.
Below, we provide the details of the two steps.
What to assemble.
This step is of the VAE style [21].
As shown in Figure 3, we use a GNN to encode a molecular graph G into a latent variable z .
Each node v has a feature vector x v which is the concatenation of three learnable embeddings: its atomic type, fragment type and the generation order of the fragment.
Each edge has a feature vector indicating its bond type.
Specifically, we utilize GIN with edge feature [14] as the backbone GNN network, which computes the k -th layer as follows:
[Equation]
where, h ( k ) v is the hidden activation of node v ( h (0) v = x v ),
e uv is the edge feature between node u and v , N ( v ) returns the neighbors of u , h Θ is a neural network, and ε is a constant.
We implement h Θ as a 2-layer Multi-Layer Perceptron ([10], MLP) with ReLU activation and set ε = 0 .
We obtain the final representations of nodes as h v =
[ h (1) v , . .
, h ( t ) v ] so that it contains the contextual information from 1 -hop to t -hop.
The graph-level representation is given by summation h G = (cid:80) v ∈V h v .
We use h G to obtain the mean µ G and log variance σ G of variational posterior approximation q ( z |G ) through two separate linear layers and use the reparameterization trick [21] to sample from the distribution in the training process.
Given a latent variable z , our model first uses an autoregressive sequence generation model
P ( F i |F <
i , z ) to decode an sequence of graph fragments [ F 1 , . . . , F n ] .
Note that the set of subgraphs into which a molecule is decomposed should not be ordered.
Here, although we violate this law by using the ordered decoder, this issue is practically relieved by data augmentation of random fragment permutations during training, and it is further mitigated by the second step (presented later) where the assembling of the predicted subgraphs is not order-sensitive.
During training, we insert two special tokens “ <start> ” and “ <end> ” indicating the beginning and the end of sequence generation, respectively.
We implement the sequence model via a single layer of GRU [8] and project the latent variable z to the initial state of GRU.
The training objective of this stage is to minimize the log-likelihood L P of the ground truth fragment sequence:
[Equation]
During testing, the generation stops when a “ <end> ” is outputted.
How to assemble.
This step estimates all inter-fragment edges {E ij } non-autoregressively and globally.
Specifically, we use a GNN with the same architecture in the last step but with different parameters to obtain the representations h v of each atom v in all fragments.
Given nodes v and u in two different fragments, we predict their connections as follows:
[Equation]
where H θ is a 3-layer MLP with ReLU activation.
Apart from the types of chemical bonds, we also add a special type “ <none> ” to the edge vocabulary which indicates there is no connection between two nodes.
During training, we predict both P ( e uv ) and P ( e vu ) to let H θ learn the undirected nature of chemical bonds.
We use negative sampling [12] to balance the ratio of “ <none> ” and chemical bonds.
Since only about 2% pairs of nodes has inter-fragment connections, negative sampling significantly improves the computational efficiency and scalability.
The training objective of this stage is to minimize the log-likelihood:
[Equation]
Joining the reconstruction losses of both steps (Eq. 3 and Eq. 5), we arrive at: L rec =
L F + L E .
When considering target property, we jointly train a 2-layer MLP from z to predict the scores of target properties using the MSE loss.
By denoting this extra loss as L prop , the final objective of our
PS-VAE becomes:
[Equation]
where the the KL divergence D KL aligns the distribution of z with the prior distribution N ( 0 , I ) ; α and β balance the trade-off between different losses.
To decode {E ij } in the inference phase, the decoder first assigns all possible inter-fragment connections with a bond type and a corresponding confidence level.
We try to add bonds that have a confidence level higher than δ th = 0 .
5 to the molecule in order of confidence level from high to low.
For each attempt, we perform a valency and a cycle check to reject the connections that will cause violation of valency or form unstable rings which are too small or too large.
Since this procedure may form unconnected graphs, we find the maximal connected component as the final result.
The pseudo code for inference is deferred to Appendix D.
Experiments
Evaluation Tasks We first report the empirical results for the distribution-learning tasks in GuacaMol benchmarks [7] to evaluate if the model can generate realistic and diverse molecules.
Then we validate our model on two common problems and the goal-directed tasks of the GuacaMol benchmarks .
Property Optimization requires generating molecules with optimized properties.
Constrained
Property Optimization concentrates on improving the properties of given molecules with a restricted degree of modification.
GuacaMol Goal-Directed Benchmarks consist of 20 molecular design tasks carefully curated by domain-experts [48, 43, 11].
Baselines We compare our principal subgraph variational auto-encoder ( PS-VAE ) with the following state-of-the-art models.
JT-VAE [18] is a variational auto-encoder that represents molecules as junction trees.
It performs Bayesian optimization on the latent variable for property optimization.
GCPN [47] combines reinforcement learning and graph representation for goal-directed molecular graph generation.
MRNN [34] adopts two RNNs to autoregressively generate atoms and bonds respectively.
It combines policy gradient optimization to generate molecules with desired properties.
GraphAF
[39] is a flow-based autoregressive model which is first pretrained for likelihood modeling and then fine-tuned with reinforcement learning for property optimization. GraphDF [28] is another flow-based autoregressive model but leverages discrete latent variables to better capture the discrete distribution of graphs.
GA [32] adopts genetic algorithms for property optimization and models the selection of the subsequent population with a neural network.
HierVAE [19] extracts fragments by breaking bridge bonds in molecules and uses them as building blocks.
FREED [46] is an RL-based model and uses fragments from existing chemical libraries to construct the subgraph vocabulary.
MARS [44] adopts Markov chain Monte Carlo sampling for generation and is the state-of-the-art approach on the GuacaMol goal-directed benchmarks.
Since our generation model is universally compatible with molecular decomposition of non-overlapping fragments, we also integrate vocabularies from HierVAE and FREED into our two-step generation model, which are abbreviated as H-VAE ∗ and F-VAE ∗ , respectively. We use the ZINC250K [16] dataset for training, which contains 250,000 drug-like molecules up to 38 atoms.
For GuacaMol benchmark, we add extra results on the QM9 [6, 37] dataset, which has 133,014 molecules up to 23 atoms. We choose N = 300 for property optimization and N =for constrained property optimization.
PS-VAE is trained for 6 epochs with a batch size of 32 and a learning rate of 0.001.
We set α = 0 .
1 and initialize β = 0 .
We adopt a warm-up method that increases β by 0 .
every 1000 steps to a maximum of 0 .
More details are in Appendix G.
4.1 Results
GuacaMol Distribution-Learning Benchmarks These benchmarks evaluate four metrics on 10,000 molecules generated by the models.
Since all methods introduce validity check into generation, they can always generate chemically valid molecules.
Uniqueness measures the ratio of unique ones in generated molecules.
Novelty assesses the ability of the models to generate molecules not contained in the training set.
KL Divergence evaluates the closeness between the training set molecules and the generated molecules in terms of the distributions of various physicochemical properties.
Fréchet
ChemNet Distance (FCD) calculates the closeness of the two sets of molecules with respect to their hidden representations in the ChemNet [35].
Each metric is normalized to 0 to 1, and a higher value indicates better performance.
Table 1 shows the results of distribution-learning benchmarks on QM and ZINC250K.
Our model achieves competitive results in all four metrics, which indicates our model can generate realistic molecules and prevent overfitting the training set.
In addition, with the same vocabulary, H-VAE ∗ surpasses HierVAE consistently, confirming the advantage of our two-step generation model over the one used in HierVAE.
Moreover, even sharing the same two-step decoder, PS-VAE is still better than H-VAE ∗ and F-VAE ∗ consistently, which is probably because our constructed vocabulary discovers more meaningful and reusable patterns than H-VAE ∗ and F-VAE ∗ .
We have displayed some molecules sampled from the prior distribution in Appendix L.
[Table]
Property Optimization This task focuses on generating molecules with optimized Penalized logP ([23], PlogP) and QED [4].
PlogP is logP penalized by synthesis accessibility and ring size which has an unbounded range.
QED measures the drug-likeness of molecules with a range of [0 , 1] .
Both properties are calculated by empirical prediction models [42, 4] [Table] and are widely used in previous works [18, 47, 39].
We constrain all models to generate molecules under 60 atoms to prevent them from utilizing the flaw of PlogP by keeping extending the carbon chain [39].
We first train a predictor on the latent space of previously-trained VAE models to simulate the scoring functions, then perform gradient ascending to search for optimized molecules [18, 27].
Hyperparameters can be found in
Appendix G.
Following previous works [18, 47, 39]
[Table]
we generate 10,000 optimized molecules and report the top-3 scores found by each model.
Results in Table 2 show that our model surpasses the baselines consistently.
Note that with the same vocabulary, F-VAE achieves much better results than
FREED, which indicates the superiority of our two-step generation strategy to the one in FREED
[Table] [Table]
Constrained Property Optimization This task refines molecular properties under the constraint that the Tanimoto similarity with Morgan fingerprint [36] is above a threshold δ .
As suggested by previous works [18, 47, 39] [Table] we optimize 800 molecules with the lowest PlogP in the test set of
ZINC250K. Similar to the property optimization task, we perform gradient ascending on the latent variable with a max step of 80.
We collect all latent variables which have better-predicted scores than the previous iteration and decode each of them 5 times, namely up to 400 molecules.
Following Shi et al.
[Table] we initialize the generation with sub-graphs sampled from the original molecules.
Then we choose the highest scoring one from the molecules that meet the similarity constraint.
Tableshows our model can generate molecules with a higher PlogP score under the similarity constraints.
Since our model uses subgraphs as building blocks, the degree of modification tends to be greater than atom-level models, leading to a lower success rate.
Even so, the success rates by our model are still on par with the atom-level counterparts and are the best among all subgraph-level methods.
GuacaMol Goal-Directed Benchmarks To further explore the efficacy of PS-VAE, we provide the results for GuacaMol goal-directed benchmarks [7] in Table 4.
All scores are continuous values between 0 and 1, and the higher, the better.
In order to obtain more discernible results between [Table] different approaches, we conduct experiments on QM9 and ZINC250K which have much less highscoring molecules than ChEMBL [30] to make the tasks more challenging.
Otherwise the majority of the benchmarks are easy to be optimized to the upper bound [1].
We adopt the same optimizing strategy as in the property optimization tasks.
Hyperparameters can be found in Appendix G. Table 4 shows that our model remarkably performs better than H-VAE ∗ and F-VAE ∗ , and thus exhibits the benefit of our subgraph extraction method. The superior of H-VAE ∗ to HierVAE indicates the advantage of our two-step assembling over the sequential sampling strategy
[Table] [Table]
Ranolazine
[Table] Troglitazone
[Table]
4.2 Ablation Study
We conduct an ablation study to further validate the effects of principal subgraphs and the two-step generation approach.
We first downgrade the vocabulary to contain only single atoms.
Then we replace the two-step decoder with a fully autoregressive decoder.
We present the performance on (constrained) property optimization in Table 5 and Table 6.
The direct introduction of the two-step generation approach leads to improvement in property optimization but harms the performance on constrained property optimization.
This is reasonable as separating the generation of atoms and bonds brings in information loss of bonds for the atom-level generation process.
However, the adoption of principal subgraphs as building blocks alleviates this negative effect since the principal subgraphs themselves contain rich bond information.
Therefore, integrating principal subgraphs with our two-step generation approach leads to the best choice in our model design.
Furthermore, we provide the runtime cost of baselines and PS-VAE in Appendix F to demonstrate the improvement in efficiency brought by the principal subgraphs and the two-step generation approach.
[Table] [Table]
Analysis
Principal Subgraph Statistics
We compare the distributions of the vocabulary of JT-VAE, FREED,
HierVAE
[Table]
and the vocabulary constructed by our principal subgraph extraction methods with a size of 100, 300, 500, and 700.
Figure 4 shows the proportion of fragments with different numbers of atoms in the vocabulary and their frequencies of occurrence in the ZINC250K dataset.
The fragments in the vocabulary of JT-VAE mainly contain 5 to 8 atoms with a sharp distribution.
However, starting from fragments with 3 atoms, the frequency of occurrence is already close to zero.
Therefore, the majority of fragments in the vocabulary of JT-VAE are actually not common fragments.
On the contrary, the fragments in the vocabulary of principal subgraphs have a relatively smooth distribution over 4 to 10 atoms.
Moreover, these fragments also have a much higher frequency of occurrence compared to those by JT-VAE.
Vocabularies constructed by our method show similar advantages compared to those of HierVAE and FREED.
We present samples of principal subgraphs in Appendix K.
Principal Subgraph - Property Correlation To analyze the principal subgraph - property correlation and whether our model can discover and utilize the correlation, we present the normalized distribution of generated fragments and Pearson correlation coefficient between the fragments and
Penalized logP (PlogP) in Figure 5.
The curve indicates that some fragments positively correlate with PlogP while some negatively correlate with it.
Compared with the flat distribution under the non-optimization setting, the generated distribution shifts towards the fragments positively correlated with PlogP under the PlogP-optimization setting.
The generation of fragments negatively correlated with PlogP is also suppressed.
Therefore, correlations exist between fragments and PlogP, and our model can accurately discover and utilize these correlations.
Proper Granularity A larger N in the principal subgraph extraction process leads to an increase in the number of atoms in extracted fragments and a decrease in their frequency of occurrence, as illustrated in Figure 6.
These two factors affect model performance in opposite ways.
On the one hand, the entropy of the dataset decreases with more coarse-grained decomposition [29], which benefits model learning [3].
On the other hand, the sparsity problem worsens as the frequency of fragments decreases, which hurts model learning [2].
We propose a quantified method to balance entropy and sparsity.
The entropy of the dataset given a set of fragments V is defined by the sum of the entropy of each fragment normalized by the average number of atoms: H V = − 1 n V (cid:80) F∈ V P ( F ) log P ( F ) , where P ( F ) is the relative frequency of fragment F in the dataset and n V is the average number of atoms of fragments in V . The sparsity of V is defined as the reciprocal of the average frequency of fragments f V normalized by the size of the dataset M : S V = M/f V . Then the entropy - sparsity trade-off ( T ) can be expressed as: T V =
H V + γS V , where γ balances the impacts of entropy and sparsity since the impacts vary across different tasks.
We assume that T V negatively correlates with downstream tasks.
Given a task, we first sample several values of N to calculate their values of
T and then compute the γ that minimize the Pearson correlation coefficient between T and the corresponding performance on the task.
With the proper γ , Pearson correlation coefficients for the first three downstream tasks in this paper are -0.987, -0.999, and -0.707, indicating strong negative correlations.
For example, Figure 6 shows the curve of entropy - sparsity trade-off with a maximum of 3,000 iteration steps for the property optimization task.
From the curve, we choose N = 300 for the property optimization task.
Please refer to Appendix B for more experimental details.  Conclusion We propose an algorithm to automatically discover the regularity in molecules and extract them as principal subgraphs .
With the extracted principle subgraphs at hand, we generate molecules in two phases.
Our model consistently outperforms state-of-the-art models on distribution-learning, (constrained) property optimization, and GuacaMol goal-directed benchmarks, and exhibits higher computational efficiency than certain widely-used baselines.
Our work provides insights into the selection of subgraphs on molecular graph generation and can inspire future search in this direction. Acknowledgments and Disclosure of Funding
This work is jointly supported by the National Natural Science Foundation of China (No.61925601, No.62006137); Guoqiang Research Institute General Project, Tsinghua University (No. 2021GQG1012); Beijing Academy of Artificial Intelligence; and Huawei Noah’s Ark
Lab. Checklist
For all authors... (a) Do the main claims made in the abstract and introduction accurately reflect the paper’s contributions and scope?
[Yes] See abstract and § 1.
(b) Did you describe the limitations of your work?
[Yes] See Appendix J. (c) Did you discuss any potential negative societal impacts of your work?
[N/A] (d) Have you read the ethics review guidelines and ensured that your paper conforms to them?
[Yes] We have read them and ensured that our paper conforms to them.
If you are including theoretical results... (a) Did you state the full set of assumptions of all theoretical results?
[Yes] They are in the Appendix A.1.
(b) Did you include complete proofs of all theoretical results?
[Yes] They are in the Appendix A.1.
If you ran experiments... (a) Did you include the code, data, and instructions needed to reproduce the main experimental results (either in the supplemental material or as a URL)?
[Yes] They are in the supplemental material.
(b) Did you specify all the training details (e g., data splits, hyperparameters, how they were chosen)?
[Yes] They are in § 4 and Appendix G.
(c) Did you report error bars (e.g., with respect to the random seed after running experiments multiple times)?
[Yes] For guacamol benchmarks, they calculate metrics with respect to the global data distribution, making the results insensitive to randomness.
For the optimization tasks, they simulate the real scenario where a bunch of candidates are produced (about 10,000 candidates) and the high-scoring ones (e.g. top-3) are selected for further development, which means the highest scores achieved by each model are relatively stable.
For the constrained optimization tasks (Table 3), we report the error bars to evaluate the robustness of the model, since different input molecules may result in different improvements (d) Did you include the total amount of compute and the type of resources used (e.g., type of GPUs, internal cluster, or cloud provider)?
[Yes] They are in Appendix F. 4.
If you are using existing assets (e.g., code, data, models) or curating/releasing new assets... (a) If your work uses existing assets, did you cite the creators?
[Yes] (b) Did you mention the license of the assets?
[N/A] (c) Did you include any new assets either in the supplemental material or as a URL? [N/A] (d) Did you discuss whether
and how consent was obtained from people whose data you’re using/curating?
[N/A] (e) Did you discuss whether the data you are using/curating contains personally identifiable information or offensive content?
[N/A] 5.
If you used crowdsourcing or conducted research with human subjects... (a) Did you include the full text of instructions given to participants and screenshots, if applicable?
[N/A] (b) Did you describe any potential participant risks, with links to Institutional Review Board (IRB) approvals, if applicable?
[N/A] (c) Did you include the estimated hourly wage paid to participants and the total amount spent on participant compensation?
[N/A]
Theorem A.1. The vocabulary V constructed by Algorithm 1 exhibits the following advantageous properties. (i) Monotonicity :
The frequency of the non-single-atom fragments in V decreases monotonically, namely, ∀F i , F j ∈ V , c ( F i ) ≤ c ( F j ) , if i ≥ j . (ii) Significance : Each fragment F in V is a principal subgraph. (iii) Completeness :
For any principal subgraph S arising in the dataset, there always exists a fragment F in V satisfying S ⊆ F , c ( S )
=
c ( F ) , when V has collected all fragments with frequency no less than c ( S ) .
Proof.
Prior to the proof, we first present a clear observation of the created vocabulary V :
Proposition A.2.
Given any F , F ′ ∈ V , for any their instances arising on an arbitrary molecule during the extraction process, either they are not spatially intersected F ∩ F ′ = ∅ , or they contain each other: F ⊆ F ′ or F ′ ⊆ F .
Now we prove each claim in the above theorem.
(i) Monotonicity .
We prove it by contradiction.
Suppose that there exist F i 1 , F i 2 ∈ V , i 1 > i 2 , and
c ( F i 1 ) >
c ( F i 2 ) .
According to Proposition A.2, we have either F i 1 ⊆
F i 2 or F i 1 ∩ F i 2 = ∅ on each molecular.
If it is the former case, then F i 1 should be firstly extracted and then merged with other fragments to yield F i 2 which means i 1 < i 2 , conflicting with the assumption.
If it is the latter case, since c ( F i 1 ) >
c ( F i 2 ) implying that F i 1 is first extracted, also conflicting with the assumption we set.
Hence, the claim is proved.
(ii) Significance .
It is proved by contradiction as well.
For any fragment F ∈ V on a certain molecule, suppose we have a subgraph S satisfying S ∩ F ̸ = ∅ , c ( S )
>
c ( F ) , and S ⊈ F .
Then we must find two connected nodes v 1 and v 2 , where v 1 belongs to S but not F : v 1 ∈ S , v 1 / ∈ F , and v 2 belongs to both subgraphs: v 2 ∈ S ∩ F .
Let us construct a new subgraph with two nodes S ′
= { v 1 , v 2 , e 12 } where e 12 is the edge connecting v 1 and v 2 .
Obviously, c ( S ′ ) ≥ c ( S ) > c ( F ) , implying that S ′ has been included into the vocabulary V before F is generated.
However, by its definition, S ′ ∩ F ̸ = ∅ ,
S ′
⊈
F , and F ⊈ S which makes a contradiction with Proposition A.2.
Thus, the assumption fails, and the claim is proved.
(iii) Completeness .
Without loss of generality, we suppose S contains at least two nodes.
We choose an arbitrary node from S , then we expand it during the vocabulary conduction via Algorithm 1.
We keep merging this node with the fragments in V to produce F t at each iteration t until the following cases happen: 1) F t = S , which directly leads to the conclusion of the claim; 2) it is the first time we merge the current fragment F t − 1 ⊊ S with an external fragment F ′
⊈
S to yield F t .
Now, we solely discuss the second case.
On one hand, if c ( F t ) > c ( S ) , we can always find a subgraph consisting of two connected nodes from F ′ and F t − 1 , respectively, and this subgraph contains at least one node not in S and has a larger frequency than S , which conflicts with the condition that S is a principal subgraph.
On the other hand, if c ( F t ) < c ( S ) , we can always find a node in S but not in F t − 1 merged with with F t − 1 to generate a fragment with a larger frequency than F ′ , which also conflicts with the implementation rule of Algorithm 1 since F ′ is of the largest frequency among all potential merging choices with F t − 1 .
Hence, we only have c ( F t ) =
c ( S ) , based on which, we can always merge F t with the remaining part of S at later iterations to make F t ⊇ S while keeping c ( F t )
=
c ( S ) .
The proof is concluded.
B Effects of Different Sizes of Vocabulary
In Table 7 and Table 8, we also provide
We observe that the best values of N for the above two tasks are 300 and 500, respectively, both of which are consistent with the optimal points by the trade-off curves in Figure 6 of Section 5.
It suggests that in practice we can tune the value of N by the method proposed in Section 5.
[Table]
[Table]
C Subgraph-Level Decomposition Algorithm
Algorithm 2 presents the pseudo code for the subgraph-level decomposition of molecules.
The algorithm takes the atom-level molecular graph, the vocabulary of principal subgraphs, and their frequencies of occurrence recorded during the principal subgraph extraction process as input.
Then the algorithm iteratively merges the two neighboring principal subgraphs whose union has the highest recorded frequency of occurrence in the vocabulary until all possible unions of two neighboring principal subgraphs are not in the vocabulary.
We provide further illustrations for the mechanism of “MergeSubGraph” as follows.
It takes as input each molecular G and the selected top-1 fragment F .
If G contains F , then we will merge the two adjacent nodes in G that comprise F into a new node F .
Input
Output
G
← G ; while True do freq ← − 1 ; F ← None ; for ⟨F i , F j , E ij ⟩ in G ′ do
F ′ ← Merge( ⟨F i , F j , E ij ⟩ ) ; { Merge neighboring fragments into a new fragment. }
s ← GraphToSMILES( F ′ ) ; { Convert a graph to SMILES representation.
} if s in V and C [ s ] > freq then freq ← C [ s ] ;
F ← F ′ ; end if end for if freq =
=
− 1 then break; else
G ′ ← MergeSubGraph( G ′ , F ) ; { Update the graph representation.
} end if end while
D Inference Algorithm for Bond Completion
Algorithm 3 shows the pseudo code of our inference algorithm.
We first predict the bonds between all possible pairs of atoms in which the two atoms are in different fragments and sort them by the confidence level given by the model from high to low.
Then for each bond with a confidence level higher than the predefined threshold δ th , which is 0.5 in our experiments, we add it into the molecular graph if it passes the valence check and cycle check.
The valence check ensures the given bond will not violate valence rules.
The cycle check ensures the given bond will not form unstable rings with nodes less than 5 or more than 6.
Input: An incomplete molecular graph G composed of fragments where inter-fragment bonds are absent, the predicted bond type for all possible inter-fragment connections B and the map to their confidence level C , the threshold for confidence level δ th
Output: A valid molecular graph G ′
G ′ ← G ;
B ← SortByConfidence( B , C ) ; { Sort the bonds by their confidence level from high to low. } for b uv in B do if C [ b uv ] < δ th then continue; { Discard edges with confidence level lower than the threshold.
} end if if valence _ check(b uv ) and cycle _ check(b uv ) then
G ′ ← AddEdge( G ′ , b uv ) ;{ Add edges that pass valence and cycle check to G ′ } end if end for
G ′ ← MaxConnectedComponent( G ′ )
; { Find the maximal connected component in G ′ }
E Complexity Analysis
Principal Subgraph Extraction
The GraphToSMILES function is implemented with CANGEN [41] algorithm, which tackles the conversion from molecular graph to SMILES with a complexity of O ( n 2 log n ) , where n denotes the number of atoms in a molecule.
The SMILESToGraph function constructs a molecular graph from a given SMILES with O ( n ) complexity.
Particularly for small molecules, the largest number of atoms n is restricted by the molecular weight, hence we can practically assume these two functions have constant running time.
Since the number of two neighboring fragments equals the number of inter-fragment connections in the subgraph-level graph, the complexity is O ( NMe ) , where N is the predefined size of vocabulary, M denotes the number of molecules in the dataset, and e denotes the maximal number of inter-fragment connections in a single molecule.
The number of inter-fragment connections decreases rapidly in the first few iterations, therefore the time cost for each iteration decreases rapidly.
It cost 6 hours to perform 500 iterations on 250,000 molecules in the ZINC250K dataset with 4 CPU cores.
Subgraph-Level Decomposition Given an arbitrary molecule, the worst case is that each iteration adds one atom to one existing fragment until the molecule is finally merged into a single fragment.
In this case, the algorithm runs for | V | iterations.
Therefore, the complexity is O ( | V | ) where V includes all the atoms in the molecule.
F Runtime Cost
We train JT-VAE, GraphAF, and our PS-VAE on a machine with 1 NVIDIA GeForce RTX 2080Ti
GPU and 32 CPU cores to compare their efficiency of training and inference.
All models are trained over a fixed number of epochs ( i.e. 6) and then generate 10,000 molecules.
As shown in Table 9, our model achieves significant improvements in efficiency due to subgraph-based two-step generation.
With principal subgraphs as building blocks, the number of steps required to generate a molecule is significantly decreased compared to the atom-level models like GraphAF.
Moreover, since the two-step generation approach separates the generation of principal subgraphs and the assembling of them into two stages, it formalizes the bond completion as a link prediction task and avoids the exhausting enumeration of all possible combinations adopted by JT-VAE.
Therefore, our model achieves tremendous improvement in computational efficiency over these baselines.
[Table]
G Experiment Details
Model and Training Hyperparameters
We present the choice of model parameters in Tableand training parameters in Table 11.
We represent an atom with three features: atom embedding, fragment embedding and position embedding.
Atom embedding is a trainable vector of size e atom for each type of atoms.
Similarly, fragment embedding is a trainable vector of size e fragment for each type of fragment.
Positions indicate the order of generation of fragments.
For property optimization tasks, we jointly train a 2-layer MLP from the latent variable to predict property scores.
For GuacaMol goal-directed benchmarks, the predictor is trained after the training of the VAE models.
The training loss is represented as L = α ·L rec +(1 − α ) ·L prop + β · D KL where α balances the reconstruction loss and prediction loss.
For β , we adopt a warm-up method that increase it by β stage every fixed number of steps to a maximum of β max .
We found a β higher than 0 .
01 often causes KL vanishing problem and greatly harm the performance.
Our model and the baselines are trained on the ZINC250K dataset with the same train / valid / test split as in Kusner et al.
[Table]
of
[Table]
[Table]
[Figure]
[Table]
max position is set to be
[Table]
[Figure]
[Table]
[Figure]
[Table]
The final representaion of graphs are projected to d G
[Table]
[Figure]
[Table]
[Table]
[Figure]
[Table]
[Figure]
[Table]
Property Optimization We use gradient ascending to search in the continuous space of latent variable.
For simplicity
[Table]
we set a target score and optimize the mean square error between the score given by the predictor and the target score just as in the training process.
The optimization stops if the mean square error does not drop for 3 iterations or it has been iterated to the maxstep .
We normalize the Penalized logP in the training set to [0 , 1] according to the statistics of ZINC250K.
By setting a target value higher than 1 the model is supposed to find molecules with better property than the molecules in the training set.
To acquire the best performance, we perform a grid search with lr ∈ { 0 . 001 , 0 . 01 , 0 . 1 , 1 , 2 } , maxstep ∈ { 20 , 40 , 60 , 80 , 100 } and target ∈ { 1 , 2 , 3 , 4 } .
For optimization of QED, we choose lr = 0 .
01 , maxstep = 100 , target = 2 .
For optimization of
Penalized logP, we choose lr = 0 .
1 , maxstep = 100 , target = 2 .
[Figure]
Constrained Property Optimization We use the same method as property optimization to optimize the latent variable.
We also perform a grid search with lr ∈ { 0 . 1 , 0 . 01 } and target ∈ { 2 , 3 } .
We select lr = 0 .
1 , maxstep = 80 and target = 2 .
For decoding, we first initialize the generation with a submol sampled from the original molecule by teacher forcing.
We follow Shi et al.
[39] to first sample a BFS order of all atoms and then randomly drop out the last m atoms with m up to 5.
We collect all latent variables which have better predicted scores than the previous iteration and decode each of them 5 times, namely up to 400 molecules.
Then we choose the one with the highest property score from the molecules that meet the similarity constraint.
For the baseline GA [1], we adjust the number of iterations to 5 and the size of population to 80, namely traversing up to 400 molecules, for fair comparison.
H Fused Rings Generation
We conduct an additional experiment to validate the ability of PS-VAE to generate molecules with fused rings (cycles with shared edges), because at first thought it seems difficult for PS-VAE to handle these molecules due to the non-overlapping nature of principal subgraphs in a decomposed molecule.
We train atom-level and subgraph-level PS-VAEs on all 4,431 structures consisting of fused rings from ZINC250K. Then we sample 1,000 molecules from the latent space to calculate the proportion of molecules with fused rings.
The results are 94.5% and 97.2% for the atom-level model and the subgraph-level model, respectively.
The experiment demonstrates that the introduction of principal subgraphs as building blocks will not hinder the generation of molecules with fused rings.
I Data Efficiency
Since the principal subgraphs are common subgraphs in the molecular graphs, they should be relatively stable with respect to the scale of training set.
To validate this assumption, we choose subsets of different ratios to the training set for training to observe the trend of the coverage of Top 100 principal subgraphs in the vocabularies as well as the model performance on the average score of the distribution-learning benchmarks.
As illustrated in Figure 9, with a subset above 20% of the training set, the constructed vocabulary covers more than 95% of the top 100 principal subgraphs in the full training set, as well as the model performance on the distribution-learning benchmarks.
[Figure]
J Discussion
Universal Granularity Adaption
The concept and extraction algorithm of principal subgraphs resemble those of subword units [38] in machine translation.
Though subword units are designed for the out-of-vocabulary problem of machine translation, they also improve the translation quality [38].
In this work, we demonstrate the power of principal subgraphs and are curious about whether there is a universal way to adapt atom-level models into subgraph-level counterparts to improve their generation quality.
The key challenge is to find an efficient and expressive way to encode inter-fragment connections into feature vectors.
We leave this for future work.
Searching in Continuous Space In recent years, reinforcement learning (RL) is becoming dominant in the field of optimization of molecular properties [47, 39].
These RL models usually suffer from reward sparsity when applied to multi-objective optimization [20].
However, most scenarios that incorporate molecular property optimization have multi-objective constraints (e.g., drug discovery).
In this work, we show that with principal subgraphs, even a simple searching method like gradient ascending can surpass RL methods on single-objective optimization.
It is possible that with better searching methods in continuous space our model can achieve competitive results on multi-objective optimization.
K Principal Subgraph Samples
We present 50 principal subgraphs found by our extraction algorithm in Figure 10.
L More Molecule Samples
We further present 50 molecules sampled from the prior distribution in Figure 11.