arXiv(opens in a new tab)physics.chem-phOct 2026

Manuscript Offprint

arXiv:2610.03066

Explainable Molecular Structure Inference from GC--MS with Diffusion Models and LLM Reranking

Changlin Liu, Tianyu Yi, Chengchun Liu, Boxuan Zhao, Fanyang Mo

Changlin Liu, Tianyu Yi, Chengchun Liu, Boxuan Zhao, and Fanyang Mo ∗^{*}

ABSTRACT: GC–EI–MS is an important technique for analyzing volatile and semivolatile compounds in complex samples. However, conventional methods rely heavily on reference spectral library matching, limiting their ability to identify compounds absent from these libraries and to infer complete molecular structures directly from fragmentation information. Here, we present DiffGCMS, a spectrum-conditioned discrete graph diffusion model for de novo structure elucidation from GC–EI–MS, and further develop a framework that integrates DiffGCMS with second-stage reasoning by a large language model (LLM). In the first stage, DiffGCMS generates candidate molecular structures from input spectra; in the second stage, the LLM uses mass spectral information to validate, repair, and rerank the candidates and provides interpretable analysis of fragment-ion peaks. This framework can generate plausible molecular structures for compounds absent from reference spectral libraries and provide traceable evidence supporting its decisions. On a test set comprising 13,696 spectra from NIST 20, the generative model achieved Acc@1 and Acc@10 of 6.01% and 15.76%, respectively. On the test subset containing molecules with no more than 10 heavy atoms, LLM-assisted molecular graph repair and reranking increased Acc@1 from 21.28% to 21.95%, Acc@10 from 46.91% to 47.99%, and candidate validity from 91.04% to 100%. These results demonstrate that spectrum-aware postprocessing can correct errors produced by the generative model while providing auditable and traceable explanations for the final ranking.

Gas chromatography–mass spectrometry (GC–MS) is a widely used analytical platform for characterizing volatile and semivolatile compounds in environmental analysis, food safety, forensic science, metabolomics, and industrial quality control. In a typical GC–MS experiment, compounds are first separated by gas chromatography and subsequently ionized; the resulting ions are detected according to their mass-to-charge ratios (m/z) and relative abundances. Electron ionization (EI), typically operated at a standard ionization energy of 70 eV, produces highly reproducible, fragment-rich mass spectra. These characteristics have facilitated the construction of large reference spectral libraries and made gas chromatography–electron ionization mass spectrometry (GC–EI–MS) particularly suitable for routine compound identification across different laboratories and instruments. 1−3^{1-3}

Conventional compound identification by GC–EI–MS relies primarily on spectral similarity algorithms that compare experimentally measured spectra with standard reference spectra. 3−5^{3-5} These methods perform well when the compound of interest is represented in the spectral library. However, identification performance decreases substantially when the analyte is absent from the reference library. More broadly, in silico fragmentation and spectrum prediction can extend mass-spectral identification beyond experimentally measured spectral libraries. In database-search implementations, however, identification remains restricted to the supplied candidate structures. 6−8^{6-8}

De novo molecular generation offers a promising alternative by directly inferring molecular structures from mass spectra without requiring the target structure to be present in a predefined database. Most existing studies in this area have focused on liquid chromatography–tandem mass spectrometry (LC–MS/MS). Models such as Spec2Mol, 9^{9} MassGenie, 10^{10} MSNovelist, 11^{11} MS2Mol, 12^{12} and Mass2SMILES 13^{13} use neural sequence-generation or learned molecular-representation approaches to infer candidate structures from tandem mass spectra and, depending on the method, molecular formulas or predicted fingerprints. Cycle-MS integrates spectrum-to-molecule prediction with forward spectrum reconstruction through cycle-consistency training for de novo structure elucidation from tandem mass spectra. 14^{14} Graph-based approaches such as DiffMS 15^{15} and FlowMS 16^{16} generate candidate molecular structures through iterative diffusion or flow-matching processes under molecular-formula constraints. LC–MS/MS can also exploit precursor-ion information and multiple fragmentation conditions to facilitate the inference of molecular masses or molecular formulas. Consequently, de novo structure elucidation from LC–MS/MS has developed into a relatively active and mature research area.

In contrast, direct de novo molecular generation from GC–EI–MS remains comparatively underexplored. Previous machine-learning studies have focused mainly on forward EI spectrum prediction or database-dependent retrieval and identification. NEIMS 17^{17} and RASSP 18^{18} predict EI mass spectra from molecular structures, whereas DeepEI 19^{19} maps experimental spectra to molecular fingerprints for candidate ranking. Although these approaches improve the coverage or efficiency of spectral-library searching, they do not fully eliminate dependence on candidate databases. SpecTUS 20^{20} represents an important advance: it employs a large encoder–decoder Transformer to translate low-resolution EI mass spectra directly into SMILES representations. The model is first pretrained on millions of synthetic spectra and then fine-tuned on experimental NIST spectra, demonstrating the feasibility of generating molecular structures directly from EI–MS data. Nevertheless, autoregressive SMILES generation may produce chemically implausible structures or structures that lack sufficient support from spectral evidence. Sequence-generation scores do not by themselves provide an explicit peak-by-peak account of how a proposed structure explains the observed EI spectrum.

Here, we present DiffGCMS, a spectrum-conditioned discrete graph diffusion framework for de novo molecular structure elucidation from GC–EI–MS data. The model represents atoms and chemical bonds as categorical variables and iteratively denoises molecular graphs under molecular-formula constraints, enabling the generation of chemically constrained and structurally diverse molecular candidates. To bridge the

Figure

Figure 1. Overall two-stage workflow for molecular structure inference from GC–EI–MS. The query spectrum is encoded as the conditioning vector y, and the molecular formula determines the heavy-atom set X. DiffGCMS progressively denoises the bond-adjacency state from ATA^{T} through AtA^{t} to the predicted clean molecular graph A0A^{0}. Ten sampling runs are performed for each spectrum to generate 10 candidate SMILES. In the second stage, DeepSeek uses bidirectional SMILES–MoleCode conversion to inspect, retain or revise, and rerank the candidates, returning ranked SMILES together with mass-spectral explanations.

gap between generating valid molecules and selecting the true structure best supported by experimental evidence, we further develop a second-stage reasoning framework based on a large language model (LLM). For each query spectrum, DiffGCMS first generates a set of candidate molecular structures. The LLM subsequently evaluates these candidates against molecular-ion and fragment-ion evidence, performs chemistry-rule-guided molecular graph correction when necessary, reranks the candidate set, and provides peak-level explanations for its decisions. By decoupling molecular generation from evidence-based validation, this framework combines the generative capability of discrete diffusion models with the chemical reasoning and interpretability of LLMs, providing a traceable strategy for identifying compounds beyond existing GC–EI–MS spectral libraries. The overall workflow is illustrated in Figure 1.

METHODS

Dataset Collection and Preprocessing. This study used gas chromatography–electron ionization mass spectrometry (GC–EI–MS) data from the NIST 20 Mass Spectral Library. 1^{1} To ensure data quality and compatibility with model input requirements, the raw data were subjected to standardized filtering. A sample was excluded if it met any of the following criteria: (1) missing retention index (RI); (2) molecular weight greater than 600 Da; (3) presence of elements other than C, H, N, O, S, P, F, Cl, Br, I, Si, and B; (4) more than 300 peaks in the mass spectrum; (5) maximum mass-to-charge ratio (m/z) greater than 500; or (6) a corresponding molecular structure that could not be parsed by RDKit (version 2022.09.5) 21^{21} or failed chemical validity checks. After filtering, 273,935 valid GC–EI–MS spectrum–structure pairs were retained.

The molecular structures were then standardized using RDKit, and the SMILES strings were converted to canonical SMILES for molecular identity assignment and dataset partitioning. 22^{22} To prevent data leakage caused by spectra of the same molecule appearing in both the training and test sets, we adopted a molecule-disjoint splitting strategy. Samples were first grouped by canonical SMILES and then divided into training, validation, and test sets at approximate ratios of 90%, 5%, and 5%, respectively.

DiffGCMS: Spectrum-Conditioned Graph Diffusion. DiffGCMS is a spectrum-conditioned discrete graph diffusion model for de novo molecular structure inference from GC–EI–MS. It consists of a spectrum encoder, a condition projection module, and a graph diffusion decoder. The model takes a mass spectral peak sequence and a molecular formula as inputs. The spectrum provides fragment-ion information, whereas the molecular formula determines the number and types of nodes in the molecular graph. Rather than jointly generating atoms and chemical bonds, DiffGCMS fixes the atom set specified by the molecular formula and applies discrete diffusion only to the interatomic connectivity, thereby constraining the generation space to candidate structures consistent with the given formula.

The spectrum encoder is initialized from the pretrained SpecTUS encoder. 20^{20} For each spectral peak, the integer-valued mass-to-charge ratio is converted into an m/z embedding, while the normalized intensity is logarithmically binned and converted into an intensity embedding. The two embeddings are added to form a peak-level input representation. The resulting peak sequence is then processed by a 12-layer Transformer encoder with an embedding dimension of 1024, a feed-forward dimension of 4096, and 16 attention heads, enabling the model to capture global relationships among fragment peaks. The encoder outputs are aggregated by mask-aware mean pooling to obtain a fixed-length spectrum representation. This representation is subsequently passed through a two-layer condition projection module with dimensions of 1024, 4096, and 1024. A SiLU activation function is applied between the two linear layers, producing a 1024-dimensional global spectrum-conditioning vector.

A molecular structure is represented as an undirected graph in which nodes correspond to heavy atoms and edges represent chemical bonds. Node types are determined by the molecular formula, whereas edges are classified into five categories: no bond, single bond, double bond, triple bond, and aromatic bond. The forward diffusion process is applied exclusively to the edge variables. During each training iteration, a diffusion time step is uniformly sampled from 1 to 500, and

A | Spectrum Encoder

B | Graph Decoder

Figure

Figure 2. Architecture of DiffGCMS. (A) The spectrum encoder embeds the mass-to-charge ratio (m/z) and intensity sequences and adds the two embeddings to obtain peak representations. A 12-layer spectrum encoder and a pooling module then produce the global spectrum conditioning vector y. (B) The graph decoder combines the spectrum condition, the heavy-atom types, counts, and structural features determined by the molecular formula, and the noisy bond state A′A'. Four GraphTransformer layers predict probabilities for five bond classes (no bond, single, double, triple, and aromatic). During sampling, the predicted distribution is used to iteratively update the bond state.

the corresponding noisy edge structure is sampled from the ground-truth graph using the cumulative transition matrix. The diffusion process comprises 500 steps and follows a cosine noise schedule, following established discrete diffusion and graph-denoising formulations. 23−25^{23-25} The categorical transition matrix is constructed from the empirical distribution of edge types in the training set. Because no noise is applied to the nodes, the atom types and spectrum-conditioning vector remain unchanged throughout the diffusion process.

The graph diffusion decoder consists of four GraphTransformer layers. 24,26^{24,26} Its inputs include the fixed node types, the noisy edges at the current diffusion step, the spectrum-conditioning vector, the normalized diffusion time, and additional structural and chemical features. These auxiliary features include node valence, formal charge, local ring information, connected-component information, and graph Laplacian spectral features, which enhance the model's awareness of molecular topology and chemical constraints. The node, edge, and global features are first mapped into their respective hidden spaces using multilayer perceptrons and are then jointly updated by the GraphTransformer.

Each GraphTransformer layer comprises a joint node–edge attention module, residual connections, layer normalization, and feed-forward networks. Node attention first models interactions between atoms, after which the current edge features multiplicatively and additively modulate the attention representations, allowing the bond states to directly influence information exchange between nodes. The spectrum condition is injected into the node and edge representations through feature-wise linear modulation, ensuring that every denoising step is guided by the input mass spectrum. Aggregated node and edge representations are also used to update the global features, enabling information exchange among the spectrum, atoms, and chemical bonds. The output layer predicts the probability of each edge type for every pair of atoms in the clean molecular graph. The predicted edge matrix is symmetrized, and its diagonal elements are masked to ensure that the generated structure is an undirected graph without self-loops. The overall model architecture is shown in Figure 2.

During training, the ground-truth edge types in the original molecular graph are used as supervision, and the edge-classification cross-entropy loss is computed only over valid node pairs. Because the adjacency matrix is symmetric, the loss is evaluated only over its upper-triangular entries to avoid counting each undirected edge twice. Neither the node types nor the global conditioning features contribute directly to the training loss. The model is optimized using AdamW together with a OneCycle learning-rate schedule. 27,28^{27,28}

During sampling, the node types and spectrum condition remain fixed, while the initial edge structure is sampled from the empirical marginal distribution of edge types in the training set. Starting from diffusion step 500, the model progressively predicts the edge-type distribution of the clean molecular graph and samples the edge structure at the preceding step using the discrete diffusion posterior. This procedure continues until the complete reverse-denoising process is finished. The resulting discrete graph is converted into a candidate molecular structure using RDKit. For each input spectrum, the sampling procedure is repeated to generate 10 candidate structures for subsequent validation and reranking by the large language model.

Graph-Explicit Candidate Representation with MoleCode. SMILES provides a compact and widely supported serialization for molecular storage and exchange, but it presents a molecular graph as a one-dimensional sequence. 22^{22} Connectivity is therefore implicit: branches are encoded through parentheses, ring closures through paired indices, and bond relationships through syntax whose meaning depends on position. An LLM must reconstruct the underlying adjacency before it can compare structures or evaluate a proposed chemical edit. This extra step is particularly problematic for the present workflow, where candidate validation requires atom-resolved comparisons, localized bond-order corrections, and a traceable record of which structural feature supports a decision. Reconstruction errors can cause the model to misidentify the target atom or bond even when the input SMILES is chemically valid. The MoleCode study found that this representational bottleneck becomes more pronounced for unfamiliar molecules, larger structures, and topology-sensitive operations. 29^{29}

MoleCode addresses this limitation with a training-free, graph-explicit molecular language built from Subgraph, Node, and Edge primitives. Atoms and fragments are represented as typed entities with persistent identifiers, while bonds are stated as explicit relations between nodes. Molecular topology is therefore directly readable and editable in the language context rather than being recovered from sequential syntax. MoleCode also supports deterministic bidirectional conversion with standard formats such as SMILES and MOL, allowing the graph representation to be introduced without changing the underlying chemical structure. In our workflow, all candidate strings generated by DiffGCMS are retained and supplied directly to the large language model, including candidates that fail RDKit chemical validity checks. The original candidate strings remain available to the LLM for inspection and repair. During reasoning, the model uses a SMILES-to-MoleCode conversion tool to obtain explicit molecular graphs for convertible candidates. This graph-explicit interface provides a natural bridge between the graph diffusion generator and the subsequent evidence-aware reasoning stage.

LLM Graph Repair and Spectrum-Aware Reranking. The second stage receives the mass spectral peak list and 10 candidate SMILES generated by DiffGCMS. DeepSeek-V4-Flash is used as the reasoning model in this stage.

The LLM first reads all 10 candidate strings, including chemically invalid candidates, and uses a SMILES-to-MoleCode conversion tool during reasoning to support graph-level inspection. The original strings are retained as inputs for structural repair regardless of their initial RDKit validation outcome. MoleCode records atom-level and bond-level information, including atom identity, hydrogen state, atomic connectivity, and bond order, thereby making the molecular topology and chemical properties implicit in the SMILES syntax explicitly accessible for inspection. 29^{29} This tool-augmented organization is consistent with prior chemistry-agent work showing the value of coupling LLM reasoning to deterministic chemical tools. 30^{30}

Using the candidate strings and available MoleCode representations, the LLM jointly evaluates the chemical plausibility of each candidate and its consistency with the input spectrum by considering the nominal molecular mass, base peak, abundant diagnostic ions, and chemically plausible neutral losses. Based on the substructural information and bond-cleavage patterns reflected by the fragment ions, the model identifies local structural features that are inconsistent with the spectral evidence and further examines the corresponding regions for valence violations, incorrect aromaticity assignments, implausible bond-order patterns, or errors in ring connectivity. For recoverable molecular graph errors, the LLM proposes structural repairs while preserving the heavy-atom composition of the original candidate.

The inspected or repaired candidates are returned as SMILES and subjected to RDKit chemical validity checks, together with checks of molecular connectivity, heavy-atom composition, and graph-to-SMILES round-trip consistency where applicable. For each validated candidate, the LLM integrates molecular-mass consistency, diagnostic-ion matches, plausible bond-cleavage patterns, neutral-loss pathways, and supporting or contradictory evidence to assign a confidence score and rerank the candidate structures accordingly. After reranking, the LLM performs a detailed peak-level interpretability analysis only for the highest-confidence Top-1 candidate, including the likely origins of key fragment ions, the corresponding bond-cleavage pathways, and plausible neutral losses. The complete workflow of tool invocation, molecular graph repair, chemical validation, candidate reranking, and Top-1 peak-level interpretation is illustrated in Figure 3.

Evaluation Metrics. Let NN denote the number of query spectra, Gi∗G_i^* the standardized reference structure for spectrum ii, and G^ij\widehat{G}_{ij} the candidate ranked at position jj. The function c(⋅)c(\cdot) returns the standardized canonical-SMILES identity, f(⋅)f(\cdot) returns a binary Morgan fingerprint, and 1[⋅]\mathbf{1}[\cdot] is the indicator function.31^{31} Acc@k was the fraction of spectra for which the reference structure occurred within the first kk candidates:

Acc@k=1N∑i=1Nmax⁡1≤j≤k1[c(G^ij)=c(Gi∗)].(1)\mathrm{A c c}@k=\frac{1}{N}\sum_{i=1}^{N}\max_{1\leq j\leq k}\mathbf{1}\Big[c(\widehat{G}_{i j})=c(G_{i}^{*})\Big]. \tag{1}

Tanimoto@k was the mean, over spectra, of the highest Morgan-fingerprint Tanimoto similarity within the first k candidates:

Tanimoto@k=1N∑i=1Nmax⁡1≤j≤kT(f(Gi∗),f(G^ij)),(2)\mathrm{Tanimoto}@k=\frac{1}{N}\sum_{i=1}^{N}\max_{1\leq j\leq k}T\Big(f(G_{i}^{*}),f(\widehat{G}_{ij})\Big), \tag{2}

where the Tanimoto coefficient for two binary fingerprint vectors a and b is

T(a,b)=a⊤b∥a∥1+∥b∥1−a⊤b.(3)T(a,b)=\frac{a^{\top}b}{\|a\|_{1}+\|b\|_{1}-a^{\top}b}. \tag{3}

For validity, let MiM_i be the number of generated or postprocessed candidates evaluated for spectrum ii, and let v(G^ij)v(\widehat{G}_{ij}) equal 1 when a candidate passes all chemical checks and 0

Query mass spectrum

Figure

Candidate SMILES

Input order

1C1=COC1
2C1=COCC1
3C1CC1
4CC
......
9C=C
10C1=NOCC1

Reranked candidates

RankCandidate SMILESConfidence
1CC0.86
2C=C0.52
3C1CO10.18
.........
9C1=NOCC10.03
10C1COC10.03

Top-ranked candidate

m/z 30

Proposed molecular-ion assignment:

C2H6+\mathrm{C_2H_6^+}

m/z 31

Possible M+1 contribution:

evaluate relative to M.

Figure 3. MoleCode-enabled LLM graph repair and spectrum-aware reranking. The query EI spectrum and 10 DiffGCMS candidate SMILES are supplied to DeepSeek. For each candidate, the model invokes deterministic SMILES-to-MoleCode conversion, inspects the explicit atom–bond graph, and retains or locally revises the structure using spectral and chemical evidence. Reviewed MoleCode graphs are converted back to SMILES, validated, assigned confidence scores, and reranked. Peak-level interpretation is then reported for the highest-confidence candidate.

otherwise. Validity was calculated as

 Validity =∑i=1N∑j=1Miv(G^ij)∑i=1NMi.(4)\text { Validity } = \frac {\sum_ {i = 1} ^ {N} \sum_ {j = 1} ^ {M _ {i}} v (\widehat {G} _ {i j})}{\sum_ {i = 1} ^ {N} M _ {i}}. \tag {4}

Results were reported for the full test set and for subsets containing no more than 20 or 10 heavy atoms. The heavy-atom subsets quantify how molecular size affects the combinatorial graph search problem and permit a focused evaluation of the more expensive LLM stage.

References (36)