Generative chemistry has a scaling problem and an editing problem, and they are the same problem. As molecules grow from the nine heavy atoms of QM9 to the 20–50+ atoms of real drug candidates, graph-based generators choke on quadratic adjacency matrices and collapsing validity, while sequence models that do scale — character-level SMILES RNNs and fragment-token language models — can only write molecules left to right. This makes the most common activity in medicinal chemistry, swapping one functional group for a similar one somewhere in the middle of a large molecule, awkward at best: autoregressive models must regenerate everything downstream of the edit, and SMILES' non-local syntax invites them to silently rewrite the scaffold they were supposed to preserve. Meanwhile, in natural language processing, an entirely separate literature has solved an isomorphic task: replacing a word in context without breaking the sentence. Bidirectional masked language models, partial-embedding corruption, and multi-operation edit grammars (replace, insert, merge) now generate context-appropriate substitutions at near-human precision.
This proposal brings those two threads together. We will build a bidirectional masked language model over SAFE fragment tokens — the representation that serializes molecules as chemically validated building blocks — and use NLP-style contextual substitution, including embedding dropout and a replace/insert/merge action grammar, to perform in-place molecular editing on drug-sized and larger molecules. The core empirical bet is that the identity-versus-context tension documented in lexical substitution maps directly onto bioisosterism: a full mask invites chemically wild replacements, an uncorrupted fragment invites the model to copy itself, and partial corruption of the fragment embedding should yield the subtle, property-preserving substitutions that lead optimization actually needs.
Core Claim
A bidirectional masked language model trained on SAFE fragment sequences, equipped with embedding dropout and a three-operation edit grammar, can perform localized in-place edits on molecules of 20–100+ heavy atoms with guaranteed topological validity, higher scaffold retention than autoregressive fragment models, and a controllable dial between conservative bioisosteric substitution and creative redesign — a capability no model in the surveyed literature provides. The closest existing systems each lack one half: SAFE setup for generative molecular design tokenizes molecules into validated fragments but decodes strictly left-to-right, so interior substitution requires regenerating or reordering the sequence; BartSmiles: Generative Masked Language Models for Molecular Representations is bidirectional but operates on SMILES subwords without attachment-point semantics and never evaluates controlled token substitution; Fragment-Masked Molecular Optimization inpaints side chains only, holds the Murcko scaffold rigid, and needs rule-based post-processing to fix broken chemistry. None combines a bidirectional fragment grammar, partial-identity corruption, and multi-action editing.
Research Program
The first build is the tokenizer and corpus. SAFE decomposes molecules into fragments from BRICS or RECAP cuts, each carrying explicit attachment points; a drug-sized molecule becomes a short sequence of perhaps 5–15 fragment tokens instead of 50+ atom tokens, which is precisely what keeps the model on the right side of the complexity wall documented in Adversarial Learned Molecular Graph Inference and Generation, where dense adjacency grows from 81 to 2,500 elements between 9 and 50 atoms. We pretrain a RoBERTa-style bidirectional encoder over SAFE sequences from ZINC20 and MOSES-scale corpora, using span-masked denoising in the spirit of BARTSmiles' corruption objective but over fragments rather than subwords.
The second build is the substitution mechanism, and this is where the NLP literature supplies the method. Following BERT-based Lexical Substitution, we corrupt a selected fragment's embedding rather than erasing it entirely. If $h_{\text{frag}}$ is the encoder embedding of the target fragment and $h_{\text{mask}}$ the learned mask embedding, we replace it with
$$\tilde{h} = m \odot h_{\text{frag}} + (1 - m) \odot h_{\text{mask}}, \qquad m_i \sim \text{Bernoulli}(\rho),$$
where $\rho \in [0, 1]$ is a retention rate: $\rho = 0$ recovers full masking and $\rho = 1$ recovers identity (copy bias). Zhou et al. showed this resolves the drift-versus-copy tension for words; we hypothesize it resolves the analogous tension between creative redesign and bioisosteric conservatism for fragments, and that $\rho$ becomes a chemist-facing control knob. Candidates are then sampled from the model's predictions at the corrupted position, conditioned on both flanking fragments simultaneously — something a causal model cannot do — and filtered by the SAFE grammar's built-in valency constraints, so unlike diffusion-based inpainting, validity is guaranteed by construction rather than repaired post hoc, a contrast FMOP itself acknowledges when it must patch unstable motifs with rules.
The third build is the action grammar. Contextualized Perturbation for Textual Adversarial Attack defines replace, insert, and merge over text tokens; each maps onto a standard med-chem operation. Replace is substituent swapping; insert, by placing a mask between two fragments, is spacer-linker insertion — the task 3DLinker and DiffLinker address in coordinate space; merge, masking two adjacent fragments jointly, is ring fusion or macrocycle consolidation. Unifying these under one masked model replaces the current patchwork in which linker design, scaffold decoration, and bioisosteric replacement are separate architectures.
We deliberately keep the model 2D-topological. The surveyed 3D equivariant methods — 3DLinker, DiffLinker, and the geometric diffusion line of — handle coordinates natively but assume rigid fragments and accumulate coordinate error with atom count, as Chen et al. observe in. Our scope is the discrete editing grammar; as an extension we will rank candidate substitutions by post-hoc conformer energy to flag steric clashes, coupling token-space editing to geometric validation without building an equivariant generator.
Baselines
The naive reference point is random fragment substitution: draw a replacement uniformly from the BRICS fragment vocabulary at the edit site. This guarantees validity through the grammar but uses no context, and it calibrates how much of our performance comes from the grammar versus from learned context — exactly the calibration the NLP literature performed when static dictionaries were displaced, with BERT-based Lexical Substitution reaching 56.3% Precision@1 on LS14 where static vector baselines sat in the low teens.
The strongest existing competitor on constrained fragment editing is SAFE paired with an autoregressive LLaMA, from SAFE setup for generative molecular design, which already demonstrates scaffold decoration and linker completion as sequence fill-in-the-blank and reports that a GPT-2 variant moves from nearly 0% validity on 10k MOSES molecules to 100% on the full 1.3M set. We will train it ourselves on our identical corpus with matched parameter count and an equal tuning budget, since no reported result found on Lacuna for SAFE–LLaMA FCD on MOSES. Beating it means higher scaffold-retention and success rates on interior-edit tasks (defined below) at equal validity, specifically on edits in the middle of the fragment sequence where SAFE must reorder or regenerate.
For distribution learning, the strongest number on file is the Graph VQ-Transformer of GVT, which reports an FCD of 0.16 on MOSES alongside 99.89% reconstruction fidelity on ZINC250k; our model beats it on this axis if it posts a lower FCD at comparable validity, novelty, and speed. For phenotypic optimization, FMOP reports a 95.4% in-silico success rate across GDSCv2 cell lines with an average 7.5% IC50 reduction; a conditional variant of our model must exceed both under the same task setup. A serious additional competitor is fine-tuned BARTSmiles itself, retokenized for span infilling — it is the only bidirectionally pretrained molecular language model on file, pretrained on 1.7 billion ZINC20 molecules — and we treat it as a live threat rather than a strawman, running it at matched compute with our SAFE tokenizer ablated in (see below).
Two ablations isolate our key ingredients. First, full-mask versus embedding-dropout substitution at the same edit sites and sample budget, which isolates the partial-identity mechanism; if the dropout knob does not trace a monotone identity–context curve, the central hypothesis fails. Second, a causally masked version of our own architecture, which isolates bidirectionality from every other design choice — same tokenizer, same pretraining, same parameters, unidirectional attention only.
Why not just…?
Why not just use an autoregressive fragment model (SAFE + LLaMA)? This is the closest alternative and we run it head-to-head rather than argue around it. SAFE's own authors note that constrained generation works by placing the editable region at the sequence end and completing left-to-right; an interior substitution in a 100-atom macrocycle forces regeneration of everything downstream, multiplying error opportunities and cost with molecule size, while our edit cost is independent of where the fragment sits. The causal-mask ablation will show how much of any gap is genuinely attributable to bidirectional conditioning. If SAFE–LLaMA matches us on interior edits despite the reordering trick, our claim collapses to "equivalent but tidier," and we will report that honestly.
Why not just use a simple SMILES LSTM? For unconstrained distribution learning, this simple route is genuinely strong: Language models can learn complex molecular distributions shows character RNNs beating graph VAEs by roughly six times on Wasserstein distance for penalized LogP and handling 100+-atom PubChem molecules where graph models fail entirely, and GuacaMol reports a SMILES LSTM matching the best-of-dataset baseline at 77% acceptable compounds. But the SAFE paper documents precisely the failure mode that matters here: SMILES' non-local syntax causes autoregressive models to hallucinate and rewrite scaffolds during constrained tasks. We therefore include a SMILES LSTM on the interior-edit benchmarks, expecting it to lose on scaffold retention while remaining the distribution-learning reference.
Why not just use matched-molecular-pair rules or a bioisostere dictionary? Rule-based transforms guarantee validity and cost nothing, but the lexical-substitution literature is a controlled study of exactly this trade: static dictionaries and static vector neighbors lack coverage and ignore context, which is why contextual models overtook them. The molecular analogue is that a dictionary cannot tell you which of fifty recorded amide replacements fits this scaffold's steric and electronic context. Our random-substitution and dictionary baselines quantify this; if the dictionary matches our model on property-improving substitution success, the learned component is not earning its cost and we would report that the task is easier than believed.
Why not just inpaint with continuous 3D diffusion? DiffLinker and FMOP already do mask-and-fill. Three costs are documented on file: sampling latency, with GVT reporting a 46x speedup over DiGress; chemistry, with FMOP requiring rule-based post-processing for unstable motifs; and scale, with coordinate errors compounding as atom counts grow past 20–50. But this alternative is a real threat on tasks with genuine 3D coupling, and DiffLinker's roughly 94% multi-fragment validity on GEOM versus 3DLinker's roughly 16% shows the 3D approach is maturing fast. Our resolution is scope, not superiority: we compare only on topological graph recovery and edit speed, and leave pocket-aware 3D substitution open, while our conformer-ranking extension tests whether cheap post-hoc geometry screening recovers most of the 3D benefit.
Proposed Experiments
The identity–context curve is the decisive first check. On a benchmark constructed from MOSES molecules by masking one fragment at a time, we sweep $\rho$ from 0 to 1 and measure, per substitution, the Tanimoto similarity and property distance (LogP, QED, molecular weight) between original and replacement, plus scaffold retention. The hypothesis is a monotone curve: $\rho = 0$ produces diverse, sometimes wild candidates; $\rho$ near 1 produces near-copies; the mid-range produces bioisosteres — replacements close enough to preserve pharmacophore-relevant properties, different enough to matter. This is the direct molecular replication of Zhou et al.'s LS07/LS14 finding (51.1% and 56.3% Precision@1), and if the curve is flat or non-monotone the core claim is falsified early and cheaply.
The second check is interior in-place editing versus SAFE–LLaMA and the SMILES LSTM, on MOSES and on the roughly 300,000 largest PubChem molecules used by the RNN-scaling paper, spanning 20 to 100+ heavy atoms. Metrics are validity (grammar-guaranteed, so expected near 100% for all fragment models), scaffold retention rate of unedited regions, success rate at achieving a target property change with a bounded edit budget, and wall-clock cost per edit as a function of edit position and molecule size. The causal-mask ablation runs here too; the prediction is that its degradation grows with distance of the edit site from the sequence end, which would be the cleanest evidence that bidirectionality, not just tokenization, is doing the work.
The third check targets the insert action against the linking literature: on the ZINC double-cut linker benchmark from 3DLinker — which reports 93.75% graph recovery, 98.68% validity, and 0.081 Å RMSD — we evaluate 2D graph recovery and note explicitly that RMSD is outside our scope. The fourth check is conditional optimization on GDSCv2, following FMOP's protocol (95.4% success, 7.5% average IC50 reduction) with a cell-line-conditioned variant of our model, plus the BARTSmiles-fine-tuned competitor at matched compute, which settles whether SAFE-token bidirectionality or merely any large pretrained bidirectional encoder drives the gains. Finally, distribution learning on MOSES with the full metric suite, against GVT's reported FCD of 0.16, establishes that adding edit capability does not cost generative fidelity. Together these experiments either establish contextual fragment substitution as a working editing layer for drug-sized molecules, or localize exactly which ingredient — the tokenizer, the bidirectionality, or the dropout knob — fails to transfer from language to chemistry.
References
- SAFE setup for generative molecular design
- BartSmiles: Generative Masked Language Models for Molecular Representations
- Fragment-Masked Molecular Optimization
- Adversarial Learned Molecular Graph Inference and Generation
- BERT-based Lexical Substitution
- Contextualized Perturbation for Textual Adversarial Attack
- 3DLinker: An E(3) Equivariant Variational Autoencoder for Molecular Linker Design
- Equivariant 3D-Conditional Diffusion Models for Molecular Linker Design
- Geometric-Facilitated Denoising Diffusion Model for 3D Molecule Generation
- Uncertainty-Aware Multi-Objective Reinforcement Learning-Guided Diffusion Models for 3D De Novo Molecular Design
- Graph VQ-Transformer (GVT): Fast and Accurate Molecular Generation via High-Fidelity Discrete Latents
- Language models can learn complex molecular distributions
- GuacaMol: Benchmarking Models for de Novo Molecular Design