Multimodal Large Language Models for Inverse Molecular Design with Retrosynthetic Planning

## Abstract

Abstract While large language models (LLMs) have integrated images, adapting them to graphs remains challenging, limiting their applications in materials and drug design. This difficulty stems from the need for coherent autoregressive generation across texts and graphs. To address this, we introduce Llamole, the first multimodal LLM capable of interleaved text and graph generation, enabling molecular inverse design with retrosynthetic planning.
Llamole integrates a base LLM with the Graph Diffusion Transformer and Graph Neural Networks for multi-conditional molecular generation and reaction inference within texts, while the LLM, with enhanced molecular understanding, flexibly controls activation among the different graph modules.
Additionally, Llamole integrates A* search with LLM-based cost functions for efficient retrosynthetic planning. We create benchmarking datasets and conduct extensive experiments to evaluate Llamole against in-context learning and supervised fine-tuning. Llamole significantly outperforms 14 adapted LLMs across 12 metrics for controllable molecular design and retrosynthetic planning.

## 1 Introduction

Figure: Figure 1: Comparison of Controllability: Results are averaged from the best numbers from Table 1.
Refer to caption: x1.png

Large language models (LLMs) are transforming machine learning across many domains (Achiam et al., ). Their success in natural language processing has extended to areas handling not only text but also image and speech data (Dong et al., ; Wu et al., ), thanks to the development of multimodal capabilities. Recently, the potential of LLMs for molecular discovery has been actively explored (Jablonka et al., ). However, LLMs struggle in the chemical domain, exhibiting poor generation quality and planning capability (Guo et al., ). This is due to the unique, graph structures of molecular data, which are challenging for LLMs that typically handle sequential texts.

Inverse molecular design requires LLMs to be controllable for generating molecular structures that meet multi-property and synthesizability requirements (Chen et al., ; Gao et al., ). These requirements can be detailed as questions for LLM input, as shown in Figure 2.
Answering these questions demands a comprehensive understanding of molecular structures and their relationship to properties. However, sequence-based LLMs struggle with this because they are pre-trained or fine-tuned solely on text representations of molecules, e.g., SMILES (Weininger, ).
To illustrate this, we investigate 14 LLMs for molecular generation in Figure 1 across 10K drug and material questions: ten using in-context learning (ICL) and four with supervised fine-tuning (SFT). LLMs generate molecular structures based on the questions, and their properties are obtained through oracles to assess the differences between requirements and generated outputs. Details of the experimental set-ups and results can be found in Section 5. In summary, even the best LLMs perform worse than GraphGA (Gao et al., ), a simple yet effective graph-based method, in designing molecules with satisfactory properties.

Figure: Figure 2: Three LLM-based methods for molecular design. The question outlines requirements for properties, structures, and synthesis, addressed as follows: (a) In-Context Learning and (b) Supervised Fine-Tuning use text-only data for demonstrations and instruction tuning, respectively. (c) The proposed Llamole uses graph-text multimodal data to fine-tune the LLM, integrating parameter-frozen graph models for interleaved text and graph generation with reaction inference.
Refer to caption: x2.png

As illustrated in Figure 2, practical answers for molecular design are more complex than what can be achieved by using graph methods or LLMs alone. The generation begins with a paragraph describing the intended molecule for multi-conditional generation, followed by retrosynthetic planning, detailing each synthesis step—one reaction per paragraph—in reverse order, from the target molecule to purchasable reactants. Thus, multimodal LLMs (MLLMs) are essential, with LLMs handling text generation and graph models managing molecular design.

In this work, we propose the multimodal Large language model for molecular discovery (Llamole). As shown in Figure 2 (c), the model seamlessly integrates LLMs and graph models within a multimodal autoregressive framework, enabling the interleaved generation of text, molecules, and reactions. It predicts the next token across both word and chemical spaces, framed as multi-class prediction tasks for word vocabulary, atom/bond types, and reaction templates. For retrosynthetic planning, Llamole integrates A* search to efficiently identify synthesis pathways for the designed molecule.

To implement Llamole, we augment a base LLM with two pre-trained graph modules: the Graph Diffusion Transformer (Graph DiT) for multi-conditional molecule generation (Liu et al., ) and a GNN for reaction template prediction. The base LLM controls the generation flow using a trigger-query-prediction approach with two sets of trigger tokens for the Graph DiT and GNN, respectively. Upon predicting a trigger token, one or a few query tokens summarize the prior text as vectors, activating the corresponding graph modules and generating molecules or predicting reaction templates. Afterward, the base LLM can resume text generation, aided by a graph encoder that encodes the previously generated molecule. In retrosynthetic planning, the LLM computes heuristics to efficiently assist the A* search in navigating the vast reaction space for multi-step generation.

Our work has several highlights. First, Llamole is the first MLLM for molecular design, capable of interleaved generation of text and graphs. Second, we curated a dataset along with fine-tuning instructions to benchmark complex yet realistic molecular design outcomes, including human conversation. Third, we present compelling experimental results that demonstrate the competitiveness of Llamole against 14 LLMs and GraphGA, as shown in Figure 1. With details in Tables 1 and 2, Llamole improves LLM performance by up to 80.9% across 12 metrics for controllable molecular generation and increases the success rate for retrosynthetic planning from 5.5% to 35%.

## 2 Preliminaries

### 2.1 Autoregressive Language Modeling

Given a sequence of word tokens $W=\{w_{1},w_{2},\dots,w_{L}\}$ of length $L$ from the vocabulary $\mathcal{W}$, LLMs parameterized by $\theta_{1}$ decompose the joint distribution as $p_{\theta_{1}}({W})=\prod_{i=1}^{L}p_{\theta_{1}}(w_{i}|{W}_{<i})$, where $W_{<i}$ represents the tokens preceding the $i$-th position.
These models are optimized by minimizing the negative log-likelihood between their predictions and the empirical data distribution, resulting in:

$$ $\mathcal{L}_{\text{LM}}=\sum_{i}-\log p_{\theta_{1}}(w_{i}|{W}_{<i}).$ (1) $$

### 2.2 Molecular Design with Graph Diffusion Models

Molecular graphs can be modeled through diffusion in discrete spaces (Austin et al., ; Vignac et al., ; Liu et al., ). Given a one-hot encoded data point $\mathbf{x}\in\mathbb{R}^{F}$ with $F$ categories (e.g., a node or an edge), discrete models perform diffusion using a transition matrix $\mathbf{Q}$, where $[\mathbf{Q}^{t}]_{ij}=q(\mathbf{x}^{t}_{j}\mid\mathbf{x}^{t-1}_{i})$ for $i,j\in[1,F]$.
The forward diffusion with $\mathbf{Q}$ is: $q(\mathbf{x}^{t}\mid\mathbf{x}^{t-1})=\operatorname{Cat}(\mathbf{x}_{t};
\mathbf{p}=\mathbf{x}^{t-1}\mathbf{Q}^{t})$, where $\operatorname{Cat}(\mathbf{x};\mathbf{p})$ denotes the categorical distribution over $\mathbf{x}$ with probabilities given by $\mathbf{p}$.
Starting from the original data point $\mathbf{x}=\mathbf{x}^{0}$, we have $q(\mathbf{x}^{t}\mid\mathbf{x}^{0})=\operatorname{Cat}\left(\mathbf{x}^{t};
\mathbf{p}=\mathbf{x}^{0}\bar{\mathbf{Q}}^{t}\right)$, where $\bar{\mathbf{Q}}^{t}=\prod_{i\leq t}\mathbf{Q}^{i}$. The forward diffusion gradually corrupts data points. When the total timestep $T$ is large enough, $q(\mathbf{x}^{T})$ converges to a stationary distribution.
The reverse process samples from $q(\mathbf{x}^{T})$ and gradually removes noise. The posterior distribution $q(\mathbf{x}^{t-1}\mid\mathbf{x}^{t})$ is calculated as $q(\mathbf{x}^{t-1}|\mathbf{x}^{t},\mathbf{x}^{0})\propto\mathbf{x}^{t}(\mathbf
{Q}^{t})^{\top}\odot\mathbf{x}^{0}\bar{\mathbf{Q}}^{t-1}$. Using a denoising model parameterized by $\theta_{2}$, this posterior can be approximated by $p_{\theta_{2}}(\mathbf{x}^{t-1}|\mathbf{x}^{t},\mathbf{x}^{0})$. For inverse molecular design with multi-property constraints, the denoising model can be optimized by minimizing the negative log-likelihood for $\mathbf{x}^{0}$:

$$ $\mathcal{L}_{\text{DM}}=\mathbb{E}_{q(\mathbf{x}^{0})}\mathbb{E}_{q(\mathbf{x} ^{t}\mid\mathbf{x}^{0})}\left[-\log p_{\theta_{2}}\left(\mathbf{x}^{0}\mid c_{ 1},c_{2},\dots,c_{M},\mathbf{c}_{\text{text}},\mathbf{x}^{t}\right)\right],$ (2) $$

where $M$ molecular properties are denoted by $\{c_{i}\}_{i=1}^{M}$, and the text embedding is $\mathbf{c}_{\text{text}}$. These conditions can be handled by Graph DiT (Liu et al., ) without introducing additional predictors for guidance (Ho and Salimans, ).

### 2.3 One-Step Reaction Prediction with Graph Neural Networks

Retrosynthesis needs to predict the reverse of a synthetic reaction, which decomposes chemical products into reactants. A GNN parameterized by $\theta_{3}$ takes the product $G_{\text{product}}$ to predict the label $r\in\mathcal{R}$ in the reaction space $\mathcal{R}$. This label is interpreted as the template and determines the reactants. With the text condition $\mathbf{c}_{\text{text}}$, we minimize the negative log-likelihood of the label distribution $q(r)$:

$$ $\mathcal{L}_{\text{predictor}}=\mathbb{E}_{q(r)}\left[-\log p_{\theta_{3}}(r \mid\mathbf{c}_{\text{text}},G_{\text{product}})\right].$ (3) $$

### 2.4 Retrosynthetic Planning with A* Search

Given molecules from the structure space $\mathcal{G}$, a subset $\mathcal{G}_{\text{avail}}$ represents available molecular structures that can be purchased as building blocks for synthesis. For any target $G_{\text{target}}$, one-step prediction of the reversed reaction may not yield reactants within $\mathcal{G}_{\text{avail}}$. Thus, retrosynthesis typically requires multi-step planning to find pathways from building blocks to the target in reverse order. The search space of chemical reactions can be navigated using A* on an AND-OR tree $\mathcal{T}$, with $G_{\text{target}}$ as the root. Reaction nodes follow an “AND” relation, requiring all child reactants, while molecule nodes follow an “OR” relation, meaning the product can be synthesized by any child reaction (Chen et al., ).

Selection: We select nodes from the frontier $\mathcal{F}(\mathcal{T})$ containing unexplored molecule nodes to expand the tree. Given an oracle cost function $J(\cdot)$, the next node is selected as $G_{\text{next}}=\arg\min_{G\in\mathcal{F}(\mathcal{T})}J(G)$ to minimize the cost. A well-designed $J(\cdot)$ improves search efficiency and aids in global optimality.

Expansion: After selecting $G_{\text{next}}$, a single GNN predictor call can generate many one-step retrosynthesis proposals. The GNN provides top-candidate reaction templates, each linked to different reactants. Thus we can form molecule nodes under the reaction node as an AND-OR stump.

Update and Cost: After expanding $G_{\text{next}}$, the tree becomes $\mathcal{T}^{\prime}$. We update the nodes in $\mathcal{T}^{\prime}$ for the next iteration. A* selects the path that minimizes $J(\cdot)=J_{\text{current}}(\cdot)+J_{\text{heuristic}}(\cdot)$, which includes the cost from the start to the current node $J_{\text{current}}(\cdot)$ and a heuristic estimate of the cost to the goal $J_{\text{heuristic}}(\cdot)$. With the GNN predictor, the negative log-likelihood of the reaction can be used to compute path cost $J_{\text{current}}(\cdot)$ to the leaf molecule node, we design $J_{\text{heuristic}}(\cdot)$ with the LLM in Llamole.

## 3 Llamole: Multimodal Large Language Model for Molecular Discovery

Figure: Figure 3: Overview of Llamole: Trigger tokens (<design> and <retro>) switch active modules from the base LLM to the respective graph component. The subsequent <query> token utilizes output vectors from the LLM to summarize past texts as conditions. Using these, Llamole generates molecules and predicts one-step reactions. Enhanced with a graph encoder and A* search, Llamole efficiently plans synthesis routes through selection and expansion iterations on the AND-OR Tree.
Refer to caption: x3.png

### 3.1 Multimodal Autoregressive Modeling

In molecular discovery, the sequence may include molecular structures $\mathcal{G}$ and retrosynthetic reactions $\mathcal{R}$
with each molecule or reaction tokenized. The sequence $Y=\{y_{1},y_{2},\dots,y_{N}\}$, where $y_{i}\in\mathcal{W}\cup\mathcal{G}\cup\mathcal{R}$, combines these tokens. The sequence is interleaved with tokens in different spaces.
Suppose the molecule appears at position $i$; then, we typically see:

$$ $\ldots,\quad Y_{i}\in\mathcal{G},\quad Y_{i+1:i+L}\in\mathcal{W},\quad Y_{i+L+ 1}\in\mathcal{R},\quad\ldots$ $$

where $L$ is the length of the text following the molecule at position $i$. The sequence starts with text. If position $i$ denotes the first molecule in the sequence, then $Y_{<i}\in\mathcal{W}$; otherwise, $y_{i-1}\in\mathcal{R}$.
To handle non-word tokens, we integrate domain-specific Graph DiT and GNN with the LLM, forming a multimodal LLM, i.e., Llamole. Parameterized by $\Theta$, Llamole unifies the cross-entropy losses from Eqs. 1, 2 and 3 into autoregressive modeling:

$$ $\mathcal{L}_{\text{Llamole}}=\mathcal{L}_{\text{LM}}+\mathcal{L}_{\text{DM}}+ \mathcal{L}_{\text{predictor}}=\sum_{i}-\log p_{\Theta}(y_{i}|Y_{<i}).$ (4) $$

$\mathcal{L}_{\text{DM}}$ interprets ${Y}_{<i}$ as the input conditions, including desirable molecular properties and text conditions $\{c_{i}\}_{i=1}^{M}\cup\{\mathbf{c}_{\text{text}}\}$ for the autoregression of $Y_{i}$ in $\mathcal{G}$.
In $\mathcal{L}_{\text{predictor}}$, ${Y}_{<i}$ represents $G_{\text{product}}$ and $\mathbf{c}_{\text{text}}$.
Here, $G_{\text{product}}$ is generated from previous diffusion models or as intermediate $G\notin\mathcal{G}_{\text{avail}}$ in retrosynthesis. The autoregression for the label $Y_{i}$ is performed in the reaction space $\mathcal{R}$.

We present an overview of multimodal autoregression with Llamole in Figure 3, divided into controllable molecular generation and retrosynthetic planning. The base LLMs perform multiple roles: generating text, controlling the switch of active modules, and providing cost functions for A* search. Augmented with the graph models, the overall parameters in Llamole are $\Theta=\{\theta_{1},\theta_{2},\theta_{3},\phi_{1},\phi_{2},\phi_{3}\}$, where $\phi_{1}$ and $\phi_{2}$ project text into $\mathbf{c}_{\text{text}}$ for the Graph DiT and GNN predictor, respectively. The graph encoder with $\phi_{3}$ projects molecule tokens into the LLM.
Next, we detail the design space of Llamole.

### 3.2 Llamole Design Space

Llamole consists of a base LLM and two pre-trained graph modules: the Graph DiT for molecule generation and the GNN for one-step reaction prediction. The base LLM employs a trigger-query-prediction approach using two sets of special tokens to switch between modules.

Trigger Tokens.
Llamole defines two special trigger tokens to augment the word vocabulary $\mathcal{W}$: <design> for switching between the LLM and Graph DiT, and <retro> for switching between the LLM and GNN predictor. When a trigger token is predicted, Llamole activates the corresponding graph model. After molecule generation or reaction prediction, the active modules revert to the LLM.

Query Tokens.
We introduce another set of special tokens, named query tokens <query> automatically placed after triggers. They use the LLM to query previous tokens and output hidden states as $\mathbf{c}_{\text{hidden}}$. A linear layer is applied: $\mathbf{c}_{\text{text}}=\operatorname{Linear}(\mathbf{c}_{\text{hidden}})$, adjusting the input size for the graph models. We use different query tokens for different triggers. Query tokens allow us to share parameters $\phi_{1}$ and $\phi_{2}$ with $\theta_{1}$, enhancing both efficiency and effectiveness. We can apply ensemble methods by repeating the query tokens multiple times and averaging the $\mathbf{c}_{\text{hidden}}$ values (Dong et al., ).

Besides the special tokens, Llamole enhances molecule understanding with a graph encoder and uses the LLM to provide the cost function in A* search for retrosynthetic planning.

Graph Encoder.
The graph encoder parameterized by $\phi_{3}$ replaces the word encoder in the LLM tokenizer for molecule tokens. The LLM decoder takes molecule embeddings from the graph encoder, along with text embeddings from the tokenizer, into the Transformer layers for next token generation. We use a pre-trained Graph Isomorphism Network (GIN) (Xu et al., ) as the graph encoder, optimized via molecule-text contrastive learning similar to CLIP (Radford et al., ).

A* Cost Function with LLM.
We define $J_{\text{heuristic}}$ as a multi-choice problem, where each choice, assigned a score, represents synthesis complexity, from few to many steps. The LLM estimates the remaining synthesis steps for the leaf molecule node $G\in\mathcal{F}(\mathcal{T})\setminus\mathcal{G}_{\text{avail}}$ in the search tree $\mathcal{T}$. It outputs probabilities for each choice, and $J_{\text{heuristic}}$ is computed as the weighted score by averaging the scores with their probabilities. For $G\in\mathcal{F}(\mathcal{T})\cap\mathcal{G}_{\text{avail}}$, $J_{\text{heuristic}}=0$.

### 3.3 End-to-End Model Fine-Tuning and Generation

Supervised Fine-Tuning.
We use multimodal SFT to connect the base LLM and other graph modules in Llamole (Ouyang et al., ). Specifically, we freeze the parameters for the graph modules ($\theta_{2}$ and $\theta_{3}$) and fine-tune the LLM parameters $\theta_{1}$, the learnable special tokens, and the linear layers for the query tokens ($\phi_{1}$ and $\phi_{2}$). We freeze the parameters of the pre-trained graph encoder ($\phi_{3}$) and add a tunable linear layer between it and the LLM decoder. The optimization can be conducted end-to-end with Eq. 4. The SFT aligns the LLM with domain-specific graph models. To maintain generality in the base LLM, we employ parameter-efficient LoRA (Hu et al., ).

Interleaved Generation.
Given a question as shown in Figure 2, Llamole performs controllable and synthesizable molecular designs, as presented in Figure 3. For the controllable generation, Llamole uses the base LLM to analyze the requirements and switches to the Graph DiT for generating $G_{\text{target}}$ when the trigger is predicted. For the synthesizable generation, Llamole plans synthesis routes for $G_{\text{target}}$.
A* search on the AND-OR tree $\mathcal{T}$ aids in multi-step generation, interleaving molecule and reaction nodes, with $G_{\text{target}}$ as the root. During each selection-expansion iteration, A* selects $G_{\text{next}}=\arg\min_{G\in\mathcal{F}(\mathcal{T})}J(G)$ from the leaf nodes $\mathcal{F}(\mathcal{T})$. The graph encoder embeds molecule tokens into the LLM, which generates reaction conditions until the token <retro> is triggered, activating the GNN predictor. The predictor then predicts the top-50 templates as reaction nodes, along with corresponding reactants as molecule nodes for the next iteration.
A* stops after finding a route from $G_{\text{target}}$ to $\mathcal{G}_{\text{avail}}$ with satisfying all AND-OR constraints, or if it fails after 30 seconds or 300 iterations. Upon success, the text with the corresponding reaction along the route is returned for retrosynthesis; otherwise, the base LLM directly generates texts.

## 4 Benchmarking for Multimodal Molecular Design

Figure: Figure 4: Creation of MolQA and MolPair: MolQA comprises two sets: a training set for ICL and (multimodal) SFT, and a test set for evaluation. MolPair consists of graph-text and reaction-text pairs, with red highlights indicating synthetic complexity, structure, and properties information.
Refer to caption: x4.png

To train Llamole, we need instruction data that provide detailed language supervision and evaluation covering synthetic complexity, drug and material utility, and reaction conditions. However, existing data based on PubChem (Kim et al., ) are only usable for small molecules and lack such details. Thus, we create MolQA, a large-scale graph-text multimodal instruction dataset for systematic LLM benchmarking used in Section 5. We also create MolPair with graph-text and reaction-text pairwise data to pre-train graph modules, as detailed in appendix C. To this end, we first collect multisource molecule data (Figure 4), with details in appendix B. Then we create MolQA and MolPair.

MolQA: Instruction Data Creation.
USPTO reactions include text descriptions. We use Enamine’s 1.3 million small molecules as $\mathcal{G}_{\text{avail}}$. The depth-first search identifies routes from reaction products (i.e. target molecules) to molecules within $\mathcal{G}_{\text{avail}}$, resulting in about 139K routes with lengths ranging from 1 to 10. We sample around 11K routes (750 for materials and 9986 for drugs) for testing and use the rest for instruction tuning. We focus on eight popular properties for benchmarking (i.e, $M=8$ for $\{c_{i}\}_{1}^{M}$ in Eq. 2). They include three drug-related categorical properties (Wu et al., ): (1) HIV virus replication inhibition (HIV), (2) blood-brain barrier permeability (BBBP), and (3) human $\beta$-secretase 1 inhibition (BACE) and five continuous material properties (Thornton et al., ): (4) CO2 permeability, (5) N2 permeability, (6) O2 permeability, (7) fractional free volume (FFV), and (8) thermal conductivity (TC).
Not all target molecules have these properties. To enrich properties and texts, two supervised GNNs predict drug and material properties with confidence scores as in Liu et al. (, ). Only high-confident predictions are selected for annotation. Llama-3-70B then generates descriptions using a template that incorporates these properties with structural and synthesis information from toolkits like RDKit.
There are no polymerization reactions; we consider the monomer structure of the polymer as the synthesis target.
We assemble molecule descriptions, text, and reactions from synthesis routes as answer data. Then Llama-3-70B is prompted to generate questions, resulting in MolQA with the example as shown in Figure 2. Details are in Section B.2.

MolPair: Pairwise Data Creation.
After excluding the target molecules from the instruction data, we use the remaining text-reaction data from USPTO to pre-train the GNN reaction predictor. Similarly, we utilize all other small molecules and polymers to pre-train the Graph DiT and graph encoder. For generalization, we expand beyond the eight properties used in the instruction data. For drug utility, we train another GNN to predict 41 properties, including toxicity, safety, enzyme interaction, absorption, distribution, metabolism, excretion (ADME), and biological activity (Swanson et al., ). For material utility, we consider 14 properties, such as thermal, physical, thermodynamic, permeability, solubility, and dielectric properties. Llama-3-70B generates related texts for these properties, incorporating structural and synthetic information. Finally, there are around 600K graph-text pairs for both small molecules and polymers to support pre-training. Details are in Section B.3.

## 5 Experiment

We conduct a systematic evaluation to demonstrate Llamole’s superior performance in controllable and synthesizable molecular design (RQ1). We investigate Llamole’s performance in controllable molecular generation through ablation and case studies (RQ2). We analyze retrosynthetic performance of LLMs, focusing on error analysis and the efficiency and effectiveness of Llamole (RQ3).

Set-ups:
We include LLM baselines from 7B to 70B, such as Llama, Mistral, Qwen, Granite, and Flan-T5, using either ICL or LoRA-based SFT. The MolQA test set contains 9,986 QA pairs for material design and 750 for drug design. LLMs are prompted with questions to generate responses for texts, molecules, and reactions. For controllability, we evaluate up to 12 metrics across four aspects: (1) chemical validity, (2) similarity to the reference based on Morgan fingerprints (Rogers and Hahn, ), (3) BLEU-4 and ROUGE-L scores against reference texts, and (4) deviation from desired properties. We follow Gao et al. () to use well-trained random forests as the oracle functions for obtaining properties of designed molecules. We focus on three drug-related categorical properties assessed by balanced accuracy (BA) and five continuous material properties assessed by mean absolute error (MAE). For retrosynthesis, we evaluate the success rate of designed molecules against those available in $\mathcal{G}_{\text{avail}}$ from Enamine. Details are in Section D.1.

Table: Table 1: Multi-Conditional Molecular Design with LLMs: Best overall results in each metric are in bold, best baseline results are in italic. Balanced Accuracy (BA) $=\frac{\text{True Positive Rate}+\text{True Negative Rate}}{2}$.

Figure: (a) LLM for Drug (Small Molecule) Design
Refer to caption: x5.png

### 5.1 RQ1: LLMs for Controllable and Synthesizable Molecular Design

Table 1 and Table 2 detail LLM performance in controllability and retrosynthesis success rate. The overall performance rankings are summarized in Figure 5. Our key observations are:

(1) Llamole significantly outperforms other LLMs in text generation, controllable molecule generation, and retrosynthetic planning. Llamole fine-tuned on various 7B-parameter LLMs, as shown in Table 2, results in top-3 rankings, surpassing 70B models that are 10$\times$ larger across all 12 metrics for controllability and planning success. Specifically, Llamole enhances chemical structure validity by 14.6%, structure controllability by 4.4%, and text generation by 11.9%-15.9%. Additionally, Llamole improves property controllability by 32% to 80%. In retrosynthesis, Table 2 indicates Llamole increases the success ratio from 5% to 35% for drugs and to 17.9% for polymers.

(2) SFT improves molecular design but may not always enhance retrosynthesis. According to Figures 5 and 1, SFT enables 7B LLMs to achieve chemical validity, structure, and property control comparable to 70B LLMs with ICL. However, it offers minimal improvement in planning ability for the generated target molecule. A notable example is Llama-3-8B from Table 2, where SFT reduces its retrosynthesis planning success from 5.5% to below 1%. Except for Llama-3-8B, we connect LLM performance with the same baseline but different learning methods in Figure 5. The results show that SFT methods still outperform ICL with the same base 7B models in most cases.

**Table 2: Retrosynthetic Success Rate: Best results are in bold, best baseline results are in italic.**
| In-Context Learning<br>Llama-2-7B<br>Mistral-7B<br>Qwen2-7B<br>Llama-3-8B<br>Flan-T5-XXL<br>Granite-13B<br>Llama-2-13B<br>Mistral-8x7B<br>Llama-2-70B<br>Drug (%)<br>0.1<br>0.2<br>0.0<br>5.5<br>0.4<br>0.6<br>1.2<br>1.6<br>1.0<br>Material (%)<br>0.3<br>0.4<br>0.0<br>4.8<br>0.8<br>1.6<br>1.2<br>1.7<br>0.8 |
| --- |
| Supervised Fine-tuning<br>Llamole<br>Mistral-7B<br>Qwen2-7B<br>Llama-3-8B<br>Llama-3.1-8B<br>Mistral-7B<br>Qwen2-7B<br>Llama-3.1-8B<br>Drug (%)<br>1.5<br>0.2<br>0.6<br>0.8<br>29.9<br>33.7<br>35.1<br>Material (%)<br>0.8<br>0.1<br>0.7<br>0.8<br>14.3<br>17.9<br>17.6 |

(3) Larger models without domain-specific adaptation do not necessarily perform better in molecular designs. We calculate the average Pearson correlation coefficient between model size and molecular design metrics, yielding a value of 0.366, indicating a weak correlation (below 0.5) between size and performance. We also compare LLM performance with GraphGA, which has been shown to be simple yet powerful (Gao et al., ; Liu et al., ). Our observations confirm that GraphGA serves as a strong molecular design baseline, challenging most LLM models with ICL and SFT in generating molecules with precise multi-condition control.

### 5.2 RQ2: Discussion on Controllable Molecular Generation

Figure: Figure 6: Ablation Studies for the Graph DiT Module in Llamole: First, we remove the text conditions from the input, i.e., $\mathbf{c}_{\text{text}}=\emptyset$. Next, we remove both text and property conditions, $\{c_{i}\}_{i}^{M}\cup\mathbf{c}_{\text{text}}$. There are learned embeddings that represent the “null” value for different conditions.
Refer to caption: x7.png

#### 5.2.1 Ablation Studies on LLM and Graph DiT Synergy

We investigate the synergy effect of Graph DiT and LLM in Llamole for molecule controllability.
We first remove text conditions $\mathbf{c}_{\text{text}}$. In this case, Graph DiT uses a learned “null” embedding to represent the dropped condition $\mathbf{c}_{\text{text}}=\emptyset$.
Next, we remove the drug or material property conditions $\{c_{i}\}_{i}^{M}$ associated with the question.
Results in Figure 6 show that text instructions enhance the chemical structure understanding ability of Graph DiT, while Llamole leverages Graph DiT’s capabilities with property inputs to generate molecules with desirable properties.

Figure: Figure 7: Interleaved generation with the base Qwen2-7B: Red indicates positions where molecules and reactions (with templates) are generated, forming three parts. The properties of the designed molecules are obtained from the oracle. Reference and other LLM responses are shown in Figure 9.
Refer to caption: x8.png

#### 5.2.2 Case Studies for Property and Structure Controllability

In Figure 7, Llamole can design a satisfactory molecule that meets both functional and structural constraints. Functionally, the oracle function confirms that the properties of BACE and HIV align with the criteria. Structurally, all key criteria are satisfied, including molecular weight, “two aromatic rings,” and “connected to aliphatic chains.” Llamole also adds details for structure design, such as a carboxyl (\ce-COOH) group and an amino group (\ce-NH2). While the amino group is present in the structure, it is connected to the carbonyl group (\ce-C(=O)-) instead of the carboxyl group. This subtle difference may require precise control based on the text condition. More results are in Section D.3.

### 5.3 RQ3: Discussion on Retrosynthetic Planning

Figure: Figure 8: Error Analysis in Reaction Generation
Refer to caption: x9.png

Retrosynthesis challenges LLMs in two aspects: (1) one-step reaction generation and (2) multi-step planning. Table 2 highlights the weaknesses of LLMs with ICL and SFT in overall planning ability and the promise of Llamole.
We examine the failure reasons in LLMs and the synergy between the GNN and LLMs to avoid them.

#### 5.3.1 One-step Reaction Generation

We conduct error analysis for LLMs in reaction generation. Results in Figure 8 average performance across all LLMs using ICL or SFT methods. We identify five types of errors related to instruction adherence, format compliance, and template matching. We find that LLMs using ICL frequently fail to follow instructions for generating reactions in text format, with a high probability (68.4%) of not producing valid formats and templates. In contrast, LLMs with SFT reduce this probability to 57.6%. However, neither ICL nor SFT guarantees that the templates are correct or match the generated reactions.
In comparison, Llamole avoids these errors by using GNN predictors, which estimate probabilities for over 300K templates derived from USPTO reactions. This enables Llamole to apply templates directly to derive reactions in retrosynthesis, avoiding hallucination.

#### 5.3.2 Multi-step Retrosynthetic Planning

From the success cases in Table 2, we find that 96.40% of 777 success cases in ICL-adapted LLMs and 94.14% of 324 success cases in SFT-adapted LLMs arise from one-step reaction generation. However, not all designed molecules can be synthesized via one-step reactions. Compared to LLMs, Llamole achieves over 10K success cases, with 40.48% resulting from two or more steps.
Figure 7 illustrates a two-step planning case for the designed molecule. The generation interleaves reaction conditions and specific formulas based on the template in both steps.

Table: Table 3: Analysis of $J_{\text{heuristics}}$ and Planning Time on Material Questions

Llamole is influenced by two factors for retrosynthesis: (1) the size of the search space and (2) the quality of the cost $J_{\text{heuristic}}$. The results reported in Table 2 limited the total planning time to 30 seconds (on an A6000 card). We remove this time constraint and report comparisons for material tasks in Table 3. We find that success rates for all base LLMs significantly improve, but this comes at the cost of long inference time.
While there is a trade-off between efficiency and effectiveness, extending response time by a few minutes is often acceptable to improve the success rate of finding synthesis paths for a single designed molecule. In Table 3, we also compare the $J_{\text{heuristics}}$ designed by LLMs (default) with the domain model trained from Chen et al. (). we find that LLMs are competitive with these domain models in providing the cost function for A*, contrasting with previous observations where LLMs struggled with retrosynthetic planning.

## 6 Related Work

Since the emergence of ChatGPT (Achiam et al., ), LLMs (Dubey et al., ) have become foundation models for text-based problems and are revolutionizing domains like vision and speech (Dong et al., ; Wu et al., ). These advancements extend to chemistry, biology, and material sciences, focusing on molecules (Guo et al., ; Jablonka et al., ; Jin et al., ). Prior work explores LLMs in molecular generation, property prediction, and one-step reaction prediction in retrosynthesis (Guo et al., ; Jablonka et al., ). A key lesson is the limitation of LLMs in sequential modeling of molecules (e.g., SMILES or SELFIES) (Guo et al., ). Multimodal LMs have been developed in combination with GNNs (Zhao et al., ; Liu et al., ), but they have not been scaled up to leverage LLMs with at least 7 billion parameters.
Additionally, LLMs struggle with planning tasks (Kambhampati et al., ), which are essential for retrosynthesis. We address these issues using graph-text multimodal LLMs, augmented by A* for efficient planning.

Domain-specific molecular design methods have evolved from sequential models (Segler et al., ) to graph diffusion models (Jo et al., ; Vignac et al., ; Liu et al., ). Studies show that older graph-based methods like GraphGA remain competitive (Gao et al., ). To incorporate property constraints, one can use molecular optimization approaches such as Bayesian optimization or REINFORCE (Gao et al., ), or employ diffusion models with or without predictor guidance (Vignac et al., ; Liu et al., ).
For synthesizable molecular design, prior work has focused on bottom-up methods (Gao et al., ; Sun et al., ). These methods explore a chemical space defined by a discrete action space of reaction templates and purchasable starting materials, which may limit flexibility. Thus, retrosynthesis algorithms (Chen et al., ) are also studied as separate solutions to find synthesis routes for generated molecules in a top-down manner.

## 7 Conclusion

We have presented the first graph-text MLLM, Llamole, for multi-conditional molecular generation and retrosynthetic planning. By integrating a base LLM with specialized graph modules, Llamole interleaved the generation of text, molecular graphs, and reactions, enabling controllable and synthesizable designs. Extensive benchmarking against 14 LLMs revealed their limitations in controlling molecular structures and planning synthesis routes. In contrast, Llamole significantly outperformed these LLMs. These findings underscored the value of multimodal approaches in molecular discovery and highlighted Llamole’s potential to connect text and chemical structures. The new benchmarking dataset also laid the groundwork for future MLLM research in molecular applications.

## Appendix A Additional Details for Llamole

### A.1 Details of Special Tokens

In total, there are nine special tokens divided into three groups. These tokens augment the word vocabulary $\mathcal{W}$, enabling flexible control of the generation flow:

- •
Trigger and Query tokens: <design_start>, <design_body>, <design_end>, <retro_start>, <retro_body>, <retro_end>
- •
Molecule token: <molecule>
- •
Callback tokens: <callback_start>, <callback_end>

The tokens <design_start> and <retro_start> switch between the LLM and the Graph DiT or GNN, respectively. The tokens <design_body> and <retro_body> serve as query tokens, repeated eight times. After tokenization, the LLM takes their embeddings as input and outputs a vector from the last layer. The tokens <design_end> and <retro_end> indicate the end of these switches.

The <molecule> token marks the position of the molecular graph where the graph encoder is applied. In the instruction dataset, the segment “<mol_start>SMILES<mol_end>” denotes the position and identity of the molecule. SMILES will be converted to molecular graphs using RDKit, and this segment will be replaced by the <molecule> token for Llamole inputs.

Finally, callback tokens control the LLM to generate backup results as complements to the specialized graph modules. For instance, if the Graph DiT fails to produce a valid molecule, the base LLM can generate an alternative, regardless of validity.

### A.2 Details of LLM-based A* Heuristics

Llamole models $J_{\text{heuristics}}$ in A* search as a multi-choice problem, filling in information from the molecule node, its parent reaction nodes and siblings using the template below. Parameters such as step, reaction template, and reactants are optional.

Using this question to estimate remaining steps, we input the text into the base LLM and formulate five choices with corresponding scores:

The LLM outputs logits for the next token, which we average for each choice to obtain overall probabilities. The $J_{\text{heuristics}}$ is calculated as the weighted score using these probabilities.

## Appendix B Additional Benchmarking and Datasets Details

We collect small drug molecules from PubChem [Kim et al., ], MoleculeNet [Wu et al., ], ChEMBL [Zdrazil et al., ], and ZINC [Sterling and Irwin, ].
Polymers are macromolecules with one repeating unit called monomers. We collect polymers from PI1M [Ma and Luo, ], the Membrane Society of Australia (MSA) [Thornton et al., ], and others [Liu et al., ].
Additionally, we collect 3.8 million patent chemical reactions with descriptions from USPTO [Lowe, ], spanning from 1976 to 2016.

### B.1 Details of Quality Control

After collecting molecules and polymers from various sources, we deduplicate and merge the label information for identical molecules. We use RDKit to obtain canonical SMILES. For small molecules, we calculate the first 14 characters of the InChIKey as the unique identifier, while for polymers, where the polymerization point is represented by “*”, we use the canonical SMILES directly.

For drug-like small molecules, we apply the following rules to filter out alert structures, known as the Rule of Five (Ro5):

- •
Molecular Weight (MW): Must be $\leq$ 500 Da.
- •
Hydrogen Bond Acceptors (HBA): Must not exceed 10.
- •
Hydrogen Bond Donors (HBD): Must not exceed 5.
- •
LogP: Must be $\leq$ 5, indicating lipophilicity.

A molecule passes the Ro5 test if at least three of these four conditions are met, indicating potential oral bioavailability.

We also apply 15 filter rules from the RDKit package, including the following from the FilterCatalogs Class: BRENK, CHEMBL, CHEMBL_BMS, CHEMBL_Dundee, CHEMBL_Glaxo, CHEMBL_Inpharmatica, CHEMBL_LINT, CHEMBL_MLSMR, CHEMBL_SureChEMBL, NIH, PAINS, PAINS_A, PAINS_B, PAINS_C, and ZINC.

### B.2 Details on the Creation of MolQA

#### B.2.1 Creation of Synthesis Routes

The USPTO has 3.7 million reactions. There are approximately 1.3 million unique product molecules. The purchasable compounds come from the Enamine Building Block (June 2024 version), supplemented with other common ions and starting materials, totaling around 1.3 million. We check each product from USPTO as a target molecule in the retrosynthesis task, exploring whether they can be synthesized using existing USPTO reactions through depth-first search (DFS). Ultimately, we identify about 139K target molecules with synthesis routes, supporting the creation of MolQA.

Since there are no polymerization reactions, we consider only monomer structures by replacing the * point with hydrogen. Among the 139K small molecules with synthesis routes, 2196 fit the monomer structures and serve as target molecules for polymer retrosynthesis. The length of synthesis routes ranges from 1 to 10. For each length of the routes, we split half of the molecules into the testing set, with a maximum of 3000, while the remainder is retained in the training set.

It results in around 11K routes (750 for materials and 9986 for drugs) for testing and 126K target molecules for training.

#### B.2.2 Creation of Property Annotations

We focus on eight benchmarking properties: three drug-related categorical properties [Wu et al., ]—(1) HIV virus replication inhibition (HIV), (2) blood-brain barrier permeability (BBBP), and (3) human $\beta$-secretase 1 inhibition (BACE)—and five continuous material properties [Thornton et al., ]—(4) CO2 permeability (CO2Perm), (5) N2 permeability (N2Perm), (6) O2 permeability (O2Perm), (7) fractional free volume (FFV), and (8) thermal conductivity (TC).

First, we check existing sources for annotations of these properties.
To enrich the label space, we use well-trained GNN models [Liu et al., ] to generate confident pseudo-labels, following the method in [Liu et al., ]. We collect all labeled data to train two supervised multi-task GIN models for drug and material property annotation. The GIN models employ rationalization techniques [Liu et al., ] to split the molecular graph into rationale and environment subgraphs in the latent space, predicting labels from the rationale subgraph. The confidence score is computed by combining the rationale subgraph with various environment subgraphs, using the reciprocal of prediction variance. We annotate properties when prediction confidence exceeds the median threshold.

#### B.2.3 Creation of Text Data for Molecular Description

In addition to property annotations, we consider structural and synthesis information of the molecules using RDKit and heuristic complexity estimation scores. First, for any molecule, we extract the following structural information:

- •
Scaffold: Extracted scaffold from the molecule structure.
- •
Molecular Weight: Calculated using the molecular weight descriptor.
- •
Number of Rings: Total number of rings in the molecule.
- •
Number of Aromatic Rings: Total number of aromatic rings in the molecule.
- •
Number of Aliphatic Rings: Total number of aliphatic rings in the molecule.
- •
Number of Rotatable Bonds: Total number of rotatable bonds in the molecule.
- •
Number of Hydrogen Bond Donors: Total number of hydrogen bond donors.
- •
Number of Hydrogen Bond Acceptors: Total number of hydrogen bond acceptors.

Next, we compute the synthetic accessibility score (SAScore) [Ertl and Schuffenhauer, ] and SCScore [Coley et al., ]. Based on this information, we use the following template:

The pre-defined utility context for the small molecule is as follows:

The pre-defined utility context for the polymer is as follows:

For the property variable, we include the property name with values, as well as the minimum, maximum, and percentile among the labels in the template. We repeat all annotated properties in the property variable. The estimated synthesis complexity scores are included among them.

We also prompt Llama-3-70B to generate short responses of 50-70 words, producing a molecular description for each molecule based on its properties, structures, and synthesis estimation. If a molecule has a description from PubChem [Kim et al., ], we concatenate these descriptions.

The generated texts may not always be meaningful or valid. We can establish filter rules based on patterns observed in poorly generated texts to remove them. We then regenerate texts for these items. After several iterations, we obtain the final text data for molecular utility descriptions, improving overall text quality. We also apply this strategy to other steps that involves prompting LLMs for synthetic data creation.

#### B.2.4 Creation of Question Answering Data

After annotating molecular description texts from Section B.2.3, we combine them with reaction descriptions, including the reaction formula and template from synthesis routes in Section B.2.1. This forms the answer data in a QA data pair.

Next, we prompt Llame-3-70B to generate questions for each answer based on the following template.

The template is applied to any answer with the corresponding structure, property information, and complete answer texts.

### B.3 Details on the Creation of MolPair

MolPair consists of two parts: reaction-text pairs and graph-text pairs.
We curate reaction-text pairs from USPTO [Lowe, ], pairing each reaction with its corresponding description of the reaction conditions. We first deduplicate product molecules in reactions, obtaining input data as the product molecule alongside the reaction condition texts. Next, we extract reaction templates from the reaction formula using rdchiral [Coley et al., ], resulting in approximately 300K templates, which will serve as labels for predictions. Finally, we have approximately 1.6 million training examples.

For the graph-text pairs, we use small molecules and polymers from the multisource collection, excluding those in MolQA. We follow the same pipeline used to create property and text annotations for the MolQA data, focusing on broader properties that describe drug-related utility with 41 small molecule properties [Swanson et al., ]. Besides the three used in MolQA, others include:

- •
Toxicity and Safety: AMES, Carcinogens Lagunin, ClinTox, DILI, Skin Reaction, hERG
- •
Enzyme Interaction: CYP1A2 Veith, CYP2C19 Veith, CYP2C9 Substrate CarbonMangels, CYP2C9 Veith, CYP2D6 Substrate CarbonMangels, CYP2D6 Veith, CYP3A4 Substrate CarbonMangels, CYP3A4 Veith
- •
Absorption, Distribution, Metabolism, and Excretion (ADME): BBB Martins, Bioavailability Ma, Caco2 Wang, Clearance Hepatocyte AZ, Clearance Microsome AZ, HIA Hou, Half Life Obach, Hydration Free Energy FreeSolv, Lipophilicity AstraZeneca, PAMPA NCATS, PPBR AZ, Pgp Broccatelli, Solubility AqSolDB, VDss Lombardo
- •
Stress Response: SR-ARE, SR-ATAD5, SR-HSE, SR-MMP, SR-p53
- •
Nuclear Receptor Interaction: NR-AR-LBD, NR-AR, NR-AhR, NR-Aromatase, NR-ER-LBD, NR-ER, NR-PPAR-gamma

We describe polymeric material utility based on 14 polymer properties collected from Otsuka et al. []:

- •
Thermal Properties: Melting temperature [°C]; Specific heat capacity at constant pressure ($C_{p}$) [cal/(g·°C)]; Specific heat capacity at constant volume ($C_{v}$) [cal/(g·°C)]; Thermal conductivity [W/(m·K)]
- •
Physical & Thermodynamic Properties: Density [g/cm^3]; Fractional Free Volume (dimensionless); Radius of Gyration ($R_{g}$) [nm]
- •
Permeability Properties: Gas diffusion coefficient ($D$) [cm^2/s]; Gas permeability coefficient ($P$) [cm^3 (STP)·cm/(cm^2·s·Pa)]; Oxygen ($\text{O}_{2}$) Gas Permeability (Barrer); Nitrogen ($\text{N}_{2}$) Gas Permeability (Barrer); Carbon Dioxide ($\text{CO}_{2}$) Gas Permeability (Barrer)
- •
Solubility Properties: Gas solubility coefficient ($S$) [cm^3 (STP)·cm/(cm^2·s·Pa)]
- •
Dielectric & Optical Properties: Dielectric constant.

We train two multi-task GIN models based on the rationalization method [Liu et al., ] using all existing labeled data for drug and material property prediction, respectively. We use these models to predict properties for millions of small molecules and polymers, retaining the top ten thousand predictions by confidence score for each property. These are then used to prompt Llama-3-70B to create molecular descriptions, using the same prompt template as in Section B.2.3. Additionally, we apply the same strategy as in Section B.2.3 to annotate labels for the eight studied properties, which can serve as input for pretraining the multi-conditional Graph DiT. Finally, we have approximately 300K graph-text pairs for small molecules and 300K graph-text pairs for polymers.

## Appendix C Additional Pre-training and Fine-tuning Details

We pre-train three graph models including Graph DiT [Liu et al., ] for multi-conditional molecular generation, a GIN-based GNN predictor for reaction template prediction, and a GIN-based graph encoder for molecule understanding [Xu et al., ].

### C.1 Pre-training of Graph Diffusion Transformers

Suppose the node has $F_{V}$ categories and the edge has $F_{E}$ categories (including non-bond). Graph DiT models the node token by concatenating all its edge configurations to other nodes. For each node $\mathbf{x}\in\mathbb{R}^{F}$, we have $F=F_{V}+N_{G}\times F_{E}$, where $N_{G}$ denotes the graph size. This facilitates defining the transition matrix $\mathbf{Q}$ for the joint distribution of nodes and edges [Liu et al., ]. Graph DiT uses Transformer layers, replacing layer normalization with adaptive layer normalization (AdaLN):

$$ $\operatorname{AdaLN}\left(\mathbf{h},\mathbf{c}\right)=\gamma_{\theta}(\mathbf {c})\odot\frac{\mathbf{h}-\mu\left(\mathbf{h}\right)}{\sigma\left(\mathbf{h} \right)}+\beta_{\theta}(\mathbf{c}),$ $$

where $\mathbf{h}$ denotes the hidden state of $\mathbf{x}$ and $\mathbf{c}$ is the vector representing the input conditions.

Given multiple conditions with categorical, continuous properties, and text, Graph DiT uses one-hot encoding for categorical properties and a clustering-based approach with $\operatorname{Linear}\left(\operatorname{Softmax}\left(\operatorname{Linear}(c
)\right)\right)$ to embed continuous condition values $c$. We employ pre-trained SciBERT [Beltagy et al., ] to embed input texts into a 768-dimensional vector by averaging the representations of all text tokens in the sentence, then using a linear layer to adjust the dimension for Graph DiT. For each condition, the model also learns a drop embedding. The drop embedding is used when no values are provided.
Finally, the model sums the representation vectors of different conditions as input for $\mathbf{c}$. In the reverse diffusion process, the denoising model uses predictor-free guidance to sample molecular graphs given multiple conditions.
We pre-train the denoising model with the loss function in Eq. 2 using 600K graph-text pairwise data and the eight properties defined in Section B.3. The model employs the following hyperparameters: depth of 28, hidden size of 1024, 16 heads, and MLP hidden size of 4096. The total model size is around 574 million parameters. We pre-train the model for 45 epochs, which takes approximately one week on a single A100 card.

### C.2 Pre-training of GNNs

We pre-train a three-layer GIN to predict reaction templates among 30,124 labels, using a hidden size of 512. Reaction template prediction is a multi-class classification task.
Given reaction-text pairs from MolPair, we extract the product molecular graph from the reaction formula, using the reaction condition text as input. SciBERT [Beltagy et al., ] is used as the text encoder with frozen parameters. We average the text representations to obtain a sentence-level representation.
The prediction target is the reaction template extracted from the reaction [Coley et al., ]. GIN naturally uses molecular graphs, employing the AdaLN approach as the normalization layer added after each message-passing layer to incorporate text conditions. We pre-train the model for 5 epochs on a single V100 card, with 632 million parameters. This model serves as the reaction predictor to suggest reaction templates for Llamole.

For molecular understanding, we pre-train a five-layer GIN model with a hidden size of 768. SciBERT [Beltagy et al., ] is used as the text encoder with frozen parameters. We average the text representations to obtain a sentence-level representation, while the GIN model uses sum pooling to produce the graph representation. For each graph-text pair from MolPair, we optimize the graph encoder using the CLIP loss [Radford et al., ] for 40 epochs. The CLIP loss consists of two contrastive losses: it first computes the similarity score between graph-text pairs, then contrasts it with all other similarity scores by pairing the graph with other texts and pairing the text with other graphs as negative pairs. The model has around 43 million parameters. The model can be pre-trained on a single V100 card in a few days. This graph encoder will replace the word encoder in the LLM tokenizer module for molecules indicated by the token <molecule> as shown in appendix A.

### C.3 Fine-tuning of Llamole

Llamole is fine-tuned on graph-text multimodal instruction data, freezing the parameters of the Graph DiT, GNN predictor, and graph encoder. It automatically adds eight query tokens to the sequence once the trigger tokens are predicted, allowing the base LLM to continue autoregression and output vectors for all eight query tokens. We average these output vectors as queries for prior generated texts and use them as input text vectors for the subsequent Graph DiT or GNN predictor module via a tunable linear layer. For the <molecule> token, we add a tunable linear layer on top of the token embedding after the graph encoder outputs it. Without loss of generality, we study three variants of Llamole with different base LLMs: Llama-3.1-8B [Dubey et al., ], Mistral-7B [Jiang et al., ], and Qwen2-7B [Yang et al., ]. All LLMs are fine-tuned using LoRA [Hu et al., ] for four epochs, taking approximately two days on a single A100 card.

## Appendix D Additional Experimental Details and Discussions

### D.1 Additional Details on Experimental Set-ups

In Tables 1, 2, 1, 5(a) and 5(b), Llamole is compared with fourteen LLMs with sizes ranging from 7B to 70B, including Llama [Dubey et al., ], Mistral [Jiang et al., ], Qwen [Yang et al., ], Granite [Abdelaziz et al., ], and Flan-T5 [Chung et al., ]. We prefer the instruct version of the model when available.

Using the MolQA training set, previous work can implement these LLMs in two ways: in-context learning (ICL) and text-only supervised fine-tuning (SFT). For ICL, we retrieve five closest QA pairs from the training set based on the average property difference from desired properties. The template used to construct the prompt with demonstrations is:

For SFT, we fine-tune the LLMs with LoRA after converting molecules into SMILES strings.

The MolQA test set contains 9,986 QA pairs for small molecules in drug applications and 750 pairs for polymeric materials. The questions serve as input to prompt the LLMs to generate responses.

For the controllability of multi-conditional molecular generation, we evaluate up to 12 metrics across four aspects: (1) chemical validity, (2) similarity to the truth based on Morgan fingerprints, (3) BLEU-4 and ROUGE-L scores compared to reference texts, and (4) deviation from desired properties. For polymer validity, we further examine whether the generated molecular structures contain at least two polymerization points (“*”). To obtain the properties of the designed structure, we define an oracle function based on well-trained random forests from all annotated molecules, following previous work [Gao et al., , Liu et al., ]. We evaluate three drug-related categorical properties using balanced accuracy (BA) and five continuous material properties using mean absolute error (MAE). As a baseline, we consider GraphGA [Gao et al., ] to reference the performance of LLMs compared to domain-specific methods.

For retrosynthesis, we evaluate the success rate from the designed molecule to those available in $\mathcal{G}_{\text{avail}}$, purchasable from the Enamine Building Block (June 2024 version), supplemented with other common ions and starting materials, totaling around 1.3 million.

#### D.1.1 Set-ups for Figure 1

For Figure 1, we average the balanced accuracy for three drug-related properties and five MAEs for the polymeric material properties. We then select the model with the best performance in each category based on these average metrics. For drug tasks, the best ICL model is Llama-3-8B-ICL, the best SFT model is Mistral-7B-SFT, and the best Llamole variant is based on Qwen2-7B. For material tasks, the best ICL model is Llama-3-70B-ICL, the best SFT model is Llama-3-8B-SFT, and the best Llamole variant is based on Llama-3.1-8B. Their average performance is visualized in Figure 1 in comparison with GraphGA.

#### D.1.2 Extraction of SMILES from LLM Responses

ICL or SFT-based LLMs generate free-form text that includes both natural language and SMILES-represented molecular structures. We need a method to automatically extract SMILES strings from LLM outputs for evaluation. Practically, one can observe generation patterns to summarize rules for regular expressions to accomplish this. In the MolQA training set, the designed molecular structures typically follow the phrase ”the designed molecule is:” as shown in examples Figures 9 and 10. LLMs may not always adhere strictly to this pattern, so we may need to extend this rule to cover more cases. In the future, more sophisticated regular expressions could be developed to extract SMILES strings from text directly. However, these will still need to be combined with additional rules to identify the designed molecules, as LLMs may generate intermediate SMILES strings before and after the designed molecule. Compared to them, Llamole uses <design_start> or <retro_start> to indicate the position of generated molecular structures.

### D.2 Additional Discussion on One-Step Generation

**Table 4: Text Generation for Reaction Conditions: Best results and best baselines are highlighted.**
| In-Context Learning<br>Llama-2-7B<br>Mistral-7B<br>Qwen2-7B<br>Llama-3-8B<br>Llama-3-8B<br>Flan-T5-XXL<br>Granite-13B<br>Llama-2-13B<br>Mistral-8x7B<br>Llama-2-70B<br>Llama-2-70B<br>BLEU-4<br>0.021<br>0.036<br>0.005<br>0.107<br>0.130<br>0.077<br>0.051<br>0.048<br>0.136<br>0.054<br>0.059<br>ROUGE-L<br>0.112<br>0.141<br>0.095<br>0.205<br>0.250<br>0.202<br>0.159<br>0.149<br>0.248<br>0.152<br>0.164 |
| --- |
| Supervised Fine-tuning<br>Llamole<br>Mistral-7B<br>Qwen2-7B<br>Llama-3-8B<br>Llama-3.1-8B<br>Mistral-7B<br>Qwen2-7B<br>Llama-3.1-8B<br>BLEU-4<br>0.085<br>0.141<br>0.114<br>0.111<br>0.049<br>0.074<br>0.085<br>ROUGE-L<br>0.191<br>0.222<br>0.195<br>0.201<br>0.192<br>0.262<br>0.268 |

We further examine the text generation results for reaction conditions. Since the answer represents just one possibility in retrosynthesis, we use the template to retrieve the best-matching reaction condition descriptions as references for Table 4, based on the available templates within the USPTO reaction space. One template may correspond to thousands of reactions, so we limit our search to five items to manage costs while identifying the best matching generated and reference pairs.

The results of generating reaction texts are shown in Table 4, where Llamole achieves the highest ROUGE-L but low BLEU-4 scores. The best ROUGE-L score for Llamole indicates its capacity to understand and maintain the overall structure of the answer after fine-tuning. The lower BLEU-4 scores may result from the A* search nature in Llamole, which explores a vast space (300K) of possible reactions, leading to fewer exact n-gram matches with reference sentences. The many-to-many relationships between products and reactants, along with various conditions for the same reaction, diminish BLEU-4’s effectiveness in evaluating Llamole’s capabilities. Overall, Llamole is not merely memorizing reaction conditions but actively exploring possibilities, yielding more contextually coherent and meaningful outputs.

### D.3 Additional Discussion on Case Studies

Figure: Figure 9: Reference Answer with Generation Results from ICL or SFT Using the base LLM Qwen2-7B. The question is the same as in Figure 7.
Refer to caption: x10.png

Figure: Figure 10: A Case Study for the Small Molecule: We include the reference answer and the generation results from ICL with Llama-3-8B and SFT and Llamole with Llama-3.1-8B.

Figure: Figure 11: A Case Study for the Polymer: We include the reference answer and the generation results from ICL, SFT, and Llamole with Qwen2-7B.
Refer to caption: x12.png

We present case studies for baseline LLMs using the same question as in Figure 7. Results are shown in Figure 7. The reference indicates one possible ground truth for molecular design with retrosynthetic pathways, noting that many alternatives exist. Compared to the reference, results in Figure 7 demonstrate that Llamole designs another molecule with similar structures, properties, and shorter synthesis routes, showcasing its potential for controllability and generating synthesizable molecules.
Using ICL, Qwen2-7B fails to generate meaningful responses, despite indicating it possesses rich knowledge about molecular design. SFT allows Qwen2-7B to more strictly follow instructions, producing meaningful responses. However, text-only generation leads to hallucinations, as the generated templates do not yield expected products in retrosynthetic planning.

Another example based on Llama-3.1/3-8B is provided in Figure 10. The ICL method may copy from the demonstrations to get the SMILES string CC(=O)C=Cc1cc(Cl)ccc1Cl.
It also includes one SMILES string before the designed molecule, such as CN(C)c1ccc(C=NNc2ccc(I)cc2)cc1. However, it does not follow the instruction pattern and is therefore not automatically extracted for evaluation, as illustrated in Section D.1.2.
SFT follows the instructions through fine-tuning, using the pattern ”the designed molecule is:” but generates invalid structures with meaninglessly repeated sentences. In contrast, Llamole generates meaningful and valid molecular structures that generally satisfy the question’s requirements. During text generation for molecular design, Llamole analyzes the question and includes more details about desirable structures, such as “aromatic rings” and “aliphatic chains”. Some functional groups, like hydroxyl, may not be precisely represented in the structure. This indicates a need for enhanced text instruction adherence in Graph DiT.

In addition to small molecules, we present a polymer inverse design case in Figure 11 based on Qwen2-7B. The polymer has polymerization points denoted by “*” in the reference structure. Since polymerization reactions are not considered, we focus on the retrosynthetic routes to the monomer structures by replacing polymerization points with hydrogen atoms. In this case, ICL-based Qwen2-7B fails molecular design due to the same issue as in Figure 9, not following instructions to generate polymer structures. SFT-based Qwen2-7B generates a polymer in SMILES format but invalid in chemical space. In contrast, Llamole successfully generates valid molecular structures through Graph DiT, satisfying the requirements of ”high CO2 permeability and low permeability to N2 and O2,” and suggests a two-step retrosynthetic pathway for the monomer structure.

## Peer Reviews

confidence: 2
contribution: 3
initial_rating: 6
presentation: 2
questions: What is the computational cost and inference time of the proposed methods, compared to GraphGA?
soundness: 3
strengths: 1. The idea proposed in the paper on jointly model texts and molecules with MLLM for inverse molecular deisgn and retrosynthesis planning pipeline is novel. The created dataset could also contribute to the area;
2. From the experiments the proposed framework shows strong performance.
3. The paper is clearly written for readers to understand the proposed method.
summary: This paper propose a multimodal large language model framework to jointly model molecules and texts for drug discovery and retrosynthesis planning tasks, which is motivated by the fact that the joint modeling of texts and molecules remain challenging.  To address this, the framework combines an existing LLM with two pre-trained graph encoders: one for conditional molecule generation and another for predicting reaction templates for retrosynthesis planning. The paper further proposes to apply A* search to ensure the target product could be synthesized from reactants that are purchasabe on the market. To summarize, the goal of this paper is to propose a MLLM-based framework that is able to build a pipeline from drug design to retrosynthesis planning for the discovered molecules. To evaluate the proposed framework, the paper proposes a dataset to benchmark in such task. From the empirical experiments, the paper argues that the proposed framw3ork Llamole outperforms the baselines of ICL or SFT with only LLMs, as well as GraphGA. The paper also justifies their deisgn of the framework based on ablation studies.
weaknesses: The baselines selected in the experiments are mainly LLMs with ICL or SFT. The only baseline with similar purpose is GraphGA. It would be interested to see the comaprisons of more baselines of the combination of existing inverse molecular design [1] and retrosynthesis planning [2,3] methods.

1. Weiss, Tomer, et al. "Guided diffusion for inverse molecular design." Nature Computational Science 3.10 (2023): 873-882.
2. Zeng, Tao, et al. "Developing BioNavi for Hybrid Retrosynthesis Planning." JACS Au 4.7 (2024): 2492-2502.
3. Han, Peng, et al. "Gnn-retro: Retrosynthetic planning with graph neural networks." Proceedings of the AAAI conference on artificial intelligence. Vol. 36. No. 4. 2022

---

confidence: 5
contribution: 3
initial_rating: 6
presentation: 3
questions: I've expressed all my concerns in the weaknesses session.
soundness: 3
strengths: - The paper presents an autoregressive MLLM capable of understanding and generating interleaved text and graphs, which has the potential to be applied to a wide range of molecule-text downstream tasks.
- The authors have collected and processed new datasets, MolQA and MolPair, which allow for more complex molecule-text downstream evaluations. These datasets will be valuable resources for future research in the field if they can be made open-source.
- The experiments in controllable molecule generation are particularly compelling.
- The integration of the A* search algorithm with LLM-based cost functions is a practical and effective approach to retrosynthetic planning
summary: The paper introduces Llamole, a novel multimodal large language model (MLLM) designed for inverse molecular design. It is capable of autoregressive generation of interleaved text and graphs, which is a significant advancement in the field. Llamole integrates a base LLM with a Graph Diffusion Transformer and GNN model to enable molecular generation and molecular inference within textual contexts. Additionally, it incorporates an A* search algorithm with LLM-based cost functions for efficient retrosynthetic planning. The authors have further created benchmarking datasets, MolQA and MolPair, and conducted extensive experiments comparing Llamole against various state-of-the-art LLMs, demonstrating its superiority in controllable molecular design and retrosynthetic planning.
weaknesses: - The framework of this work (Figure 3) is somewhat difficult to understand due to its tight layout and restricted color use. - Rearranging the layout and using a more varied color scheme could improve the clarity of the framework.
- The first claim about this paper's contribution is a bit vague. Although this model is indeed a novel MLLM (Multimodal LLM), there are already some existing MLLMs for molecular generation and understanding. The key innovation of this work lies in the autoregressive generation of interleaved text and graphs with GNN and Graph Diffusion Transformer. This should be emphasized in the introduction and preliminaries to distinguish it from existing work.
- As mentioned above, there are existing MLLM methods tailored for molecule-text related tasks, some of which can be scaled up to 7B or higher parameter levels. These models have made a great contribution to molecule discovery and should be included in the introduction (Figure 1), preliminaries, and experiment sections of this paper.
- This work conducts experiments majorly on the two new datasets proposed in this paper. While the comprehensiveness of the newly proposed datasets is commendable, additional comparisons on existing datasets such as MoleculeNet or USPTO retrosynthesis datasets would lead to better comparison with previous approaches.

---

confidence: 2
contribution: 2
initial_rating: 6
presentation: 3
questions: See above
soundness: 3
strengths: 1. Novel Multimodal Integration: The integration of graph-based models with a base LLM to handle both text and graph data is innovative, addressing the limitations of LLMs in generating coherent molecular structures and enabling interleaved text and graph generation.

2. Efficient Retrosynthetic Planning: The use of A* search combined with LLM-derived cost functions significantly improves the efficiency of retrosynthetic planning, offering a practical solution for synthesizable molecular design.

3. Good Performance: Llamole achieves substantial improvements over baseline methods across multiple metrics, demonstrating its superiority in both molecular design and planning tasks.
summary: The paper introduces Llamole, a novel multimodal large language model (MLLM) designed for inverse molecular design that integrates graph and text generation capabilities for retrosynthetic planning. Llamole combines a base LLM with specialized graph modules (Graph Diffusion Transformer and Graph Neural Networks) to perform multi-conditional molecular generation and reaction inference within a unified framework. The model also incorporates A* search with LLM-based cost functions to enhance retrosynthetic planning efficiency. Extensive experiments demonstrate that Llamole outperforms other adapted LLMs on several benchmarks, establishing its effectiveness in controllable molecular design and retrosynthetic planning.
weaknesses: 1. Theoretical Justification: The paper lacks a strong theoretical explanation for why the Llamole approach works effectively for inverse molecular design. While the empirical results are compelling, a deeper theoretical discussion would enhance the understanding of its effectiveness.

2. Scalability Concerns: The computational cost and scalability of Llamole are not thoroughly discussed. The practicality of deploying such a large-scale multimodal model in real-world scenarios remains unclear, especially given the integration of multiple complex components.

3. Comparative Analysis Gaps: The paper does not compare Llamole with some recent multimodal approaches that also attempt to bridge the gap between graph and text modalities, which would provide a more comprehensive evaluation.

---

confidence: 4
contribution: 3
initial_rating: 6
presentation: 4
questions: Check the Weaknesses
soundness: 4
strengths: - The paper is very well written. The problem statement is well-motivated. The authors did a comprehensive review of prior work on LLMs for Molecule Synthesis.
- The authors proposed the first multi-modal LLM for molecular design. They proposed a novel idea to integrate Graph encoders with pre-trained LLMs and unified cross-entropy loss into the autoregressive modeling of LLMs. 
- They curated a dataset and developed fine-tuning guidelines for benchmarking multimodal molecular design.
- Authors conduct extensive experiments with popular benchmark datasets and compare them with state-of-the-art models to show the effectiveness of their proposed model.
- Authors conduct ablation studies to show the utility of different components of their model.
- Source code is  provided
summary: Summary: In this paper, the authors address an important task of multi-modal molecule design using LLMs. In particular, they have integrated pre-trained Graph Models with pre-trained auto-regressive LLM and fine-tuned them using multi-modal data (Text+Graph) to enable interleaved generate Multi-modal output (text, molecules, and graph). Moreover, they have incorporated retrosynthetic planning during generation, where they integrate A* search to efficiently identify synthesis pathways for the designed molecule.
weaknesses: - Can the model handle any random format of the question, or is the format specified in Fig-2 predetermined? 
- What is the minimum information required by LLMole to generate an appropriate molecular structure?
- To what extent does the information requested in the text match the generated material, and are there any qualitative results available for this?
- For property prediction for Drugs and Materials, Can the model handle unseen datasets for property prediction in drugs and materials? Could the authors provide some insights on this?

Meta-review: This paper proposes a multimodal large language model for inverse molecule design and retrosynthetic analysis. 

The method is well-designed and the experiments are well-executed. The paper also proposes new datasets and benchmarks which are likely to be very useful for future research in this area.

Reviewers pointed out some presentation issues and missing baselines, but the concerns were not critical. 

Overall, this is a very solid work. I recommend acceptance.

Decision: Accept (Poster)