01 / 13
AI for Materials Science  ·  Lecture 08 (Complete Beginner-to-Research Edition)

Sequence Models, Transformers & Reaction Prediction:
Chemical Language Models, SMILES Augmentation & Attention

Zesheng Liu
Laboratory of Organic Electronics, Linköping University
Modules 08a–08d  |  Pure PyTorch LSTM Language Models, NLL Anomaly Detection & Mini ReactionTransformer
Linköping University Laboratory of Organic Electronics

Lecture 08 roadmap: treating chemistry as a language

From chemical tokenization and autoregressive LSTMs to Encoder–Decoder Reaction Transformers (08a–08d)
PART 1 · MODULE 08a

SMILES Language Models

Chemical regex tokenization, Teacher Forcing, 1st-order Markov Bigram vs. LSTM recurrent memory, and controlling generation diversity with sampling temperature T.

PART 2 · MODULE 08b

Augmentation, NLL & Transfer

5× non-canonical SMILES enumeration, per-token Negative Log-Likelihood (NLL) as an Applicability Domain alarm, and fine-tuning a general LM toward Organic Semiconductors.

PART 3 · MODULE 08c

Mini Reaction Transformer

Template-free reaction prediction as machine translation (Reactants >> Product), Scaled Dot-Product Attention, Positional Encoding, and Cross-Attention inspection.

Autoregressive sequence models unlock both de novo molecular generation and template-free chemical reaction prediction—using the exact same PyTorch engine as modern LLMs.
Linköping University Laboratory of Organic Electronics

Chemical-aware tokenization & Teacher Forcing

Never split SMILES by character—two-letter elements (Cl, Br) and bracketed atoms ([Si]) must stay atomic tokens
Chemical-aware tokenization & Teacher Forcing
Regex tokenization preserves chemical identity, while Teacher Forcing turns a single SMILES sequence of length L into L parallel next-token training steps.
Linköping University Laboratory of Organic Electronics

Why Bigrams fail & why LSTMs succeed on chemical syntax

Closing a 6-membered ring (c1ccccc1) or nested branch requires long-range memory beyond the previous token
Why Bigrams fail & why LSTMs succeed on chemical syntax
An LSTM's recurrent hidden state h_t tracks open rings and parentheses across dozens of tokens—boosting chemical validity from ~11% to >80–90%.
Linköping University Laboratory of Organic Electronics

Controlling creativity: Softmax sampling temperature T

Scaling logits by 1/T navigates the trade-off between safe textbook molecules and novel unexplored structures
Controlling creativity: Softmax sampling temperature T
Low T (0.4) repeats safe training molecules; high T (1.6) breaks SMILES grammar; T ≈ 0.8–1.0 balances high validity with true chemical novelty.
Linköping University Laboratory of Organic Electronics

SMILES augmentation: free 5×–10× dataset multiplication

A single molecular graph has many valid non-canonical SMILES strings—enumerating them prevents string memorization
SMILES augmentation: free 5×–10× dataset multiplication
Training on randomized SMILES acts as graph-equivariant data augmentation, raising both validity and novelty on small chemical datasets.
Linköping University Laboratory of Organic Electronics

Per-token NLL: generative models as anomaly detectors

Computing average Negative Log-Likelihood (masking <pad>!) measures how 'surprised' the model is by a new molecule
Per-token NLL: generative models as anomaly detectors
A trained SMILES language model doubles as an unsupervised Applicability Domain detector—flagging exotic chemistries before you trust downstream predictions.
Linköping University Laboratory of Organic Electronics

Cross-domain transfer learning: general LM → organic semiconductors

Pre-train on 9,500 diverse molecules to learn valence & ring grammar, then fine-tune on a small library of target OSCs
Cross-domain transfer learning: general LM &rarr; organic semiconductors
Transfer learning decouples 'learning chemical grammar' (big general dataset) from 'targeting a materials class' (small specialist dataset).
Linköping University Laboratory of Organic Electronics

Reaction prediction: rule-based templates vs. Seq2Seq translation

Why Molecular Transformer (Schwaller et al., ACS Central Science 2019) revolutionized synthetic chemistry
CLASSICAL · REACTION TEMPLATES

Hand-Coded SMARTS Rules

  • Requires explicit atom-mapped reaction rules (e.g., Suzuki Ar–Br + Ar'–B(OH)2).
  • Brittle: cannot predict novel reaction mechanisms outside the template library.
  • Struggles with subtle regioselectivity and competing functional groups.
MODERN · TRANSFORMER TRANSLATION

Template-Free Seq2Seq

  • Treats reaction prediction as translating Reactant1.Reactant2 → Product.
  • Zero atom-mapping required at inference; handles reagents, solvents & catalysts naturally.
  • Self-attention links distant reacting atoms in O(1) path length (unlike RNN bottlenecks).
By framing synthesis as sequence-to-sequence translation, Transformers learn reaction chemistry directly from patent corpora (USPTO) without hand-coded rules.
Linköping University Laboratory of Organic Electronics

Inside the Transformer: Positional Encoding & Causal Attention

Attention is permutation-equivariant—sinusoidal encodings inject sequence order, and causal masks block future leakage
Inside the Transformer: Positional Encoding &amp; Causal Attention
Scaled Dot-Product Attention softmax(QKᵀ/√d_k + M)V lets every atom dynamically query all other atoms in parallel while preserving autoregressive causality.
Linköping University Laboratory of Organic Electronics

Opening the Reaction Transformer: Cross-Attention & Extrapolation

Visualizing which reactant tokens the decoder attends to when assembling a Suzuki coupling product
Opening the Reaction Transformer: Cross-Attention &amp; Extrapolation
Cross-attention learns chemical reactivity—copying intact aryl scaffolds while dropping leaving groups—yet unseen scaffolds remain the key generalization test.
Linköping University Laboratory of Organic Electronics

Scientific LLMs: Grounded Literature Extraction & RAG

Turning unstructured experimental paragraphs into clean databases (PERLA / NOMAD style) with near-zero hallucination
Scientific LLMs: Grounded Literature Extraction &amp; RAG
Enforcing JSON Schema + verbatim quote verification + physical bounds slashes LLM extraction hallucinations below ~1%, while RAG grounds answers in your lab's papers.
Linköping University Laboratory of Organic Electronics

Tool-Calling Agents & Socratic Project Supervision

Let LLMs orchestrate reasoning—delegate exact chemistry & math to deterministic Python tools, and fight AI sycophancy!
AGENTIC AI FOR MATERIALS

LLM Orchestrator + Scientific Tools

  • Never do stoichiometry in tokens: BPE splits decimals & formulas—call pymatgen / RDKit tools for exact masses, symmetry & descriptors.
  • Closed-loop agents: Plan → Query MP/RAG → Run Python sandbox → Propose next experiment.
  • Always keep a human scientist in the loop before wet-lab synthesis!
SOCRATIC PROJECT CRITIC (LIU 2026)

Defeating Chatbot Sycophancy

  • By default, chatbots praise flawed project ideas (15 samples + deep GNN, or random-split leakage).
  • Flip the prompt: Instruct the AI to act as a Skeptical Examiner asking 1–2 probing questions at a time.
  • Audit 6 pillars: Problem, Data Hygiene, Simple Baseline, Honest Split, Compute Budget & Physical Insight.
The best researchers use AI not to write unverified boilerplate, but as a tireless tool-calling assistant and a ruthless pre-submission reviewer.
Linköping University Laboratory of Organic Electronics

Summary (Take home notes)

  • Tokenize chemically, train autoregressively: Regex tokenization preserves multi-character atoms (Cl, [Si]), and Teacher Forcing trains next-token prediction efficiently.
  • Recurrent memory & temperature control: LSTMs track open rings/branches that Bigrams miss; sampling temperature T ≈ 0.8–1.0 balances validity and novelty.
  • Augment & audit with likelihood: Randomized SMILES boosts generalization, while per-token NLL serves as a built-in Applicability Domain detector.
  • Transfer learning unlocks small domains: Pre-train on large diverse libraries for syntax, then fine-tune on small specialist materials datasets (e.g., OSCs).
  • Attention powers template-free synthesis: Encoder–Decoder Transformers translate reactants directly to products, with interpretable cross-attention maps.
  • Ground scientific LLMs & agents: Combine JSON Schema + quote verification, RAG, deterministic RDKit/Pymatgen tools, and Socratic critical prompting.
Linköping University Laboratory of Organic Electronics

Thanks for your listening

Zesheng Liu  ·  zesheng.liu@liu.se
AI for Materials Science  ·  Lecture 08  |  Next: Hands-on Practice in 08e_exercises.ipynb
Linköping University Laboratory of Organic Electronics