ML for Materials Science · Week 14 · Lecture 14

Generative Models and Inverse Design

From "what is the property of this material?" to "which material has this property?": screening, variational autoencoders, diffusion models and language models.
Undergraduate course · 16 weeks
latent space z decode a new crystal x
Recap · lecture 13

Last week the model chose the next experiment. But only from a list we wrote.

1

Closed loop: model → choose → measure → update.

2

Gaussian-process surrogate (lecture 4): a prediction and an error bar for every candidate.

3

Acquisition functions: expected improvement and upper confidence bound trade exploration against exploitation.

4

Bayesian optimization beat random search on the simulated alloy-hardness problem; self-driving labs close the loop with robots.

What it left open

The loop picked the best point from a search space we defined: a composition range, a list of known compounds. It never invented a candidate. Where do genuinely new candidates come from, when the space of possible crystals is astronomically large?

Today

Models that propose materials: screening funnels, variational autoencoders, diffusion models, and language models that read the literature.

Last week: choose well from a list. This week: write the list.
Why questions · answered at the end

Four puzzles for today

WHY 1

A model generates 10 000 "new" crystals. Why does that not mean 10 000 new materials?

WHY 2

We have a good model from material to band gap. Why can't we simply run it backwards to get the material for a target gap?

WHY 3

An autoencoder rebuilds every training structure almost perfectly. Why can it still be a poor generator of new ones?

WHY 4

Why can a large language model give you a confident reference to a paper that does not exist?

The big picture · forward versus inverse design

Inverse design asks the question backwards, and it has many answers

material xcomposition, structure
→
modelweeks 2–12
→
property ŷone answer
target y*e.g. Eg = 3.4 eV
→
?search or generate
→
materials xmany, or none
1

Screening: enumerate known or easy candidates, filter with cheap models first.

2

Optimization: search a space we define (Bayesian optimization, lecture 13).

3

Generation: learn the distribution p(x) of real materials, then sample new x from it, steered toward y*.

Try to invert lecture 1's line

\[ \hat E_g = 0.5875 + 2.5675\,\Delta\chi \;\Rightarrow\; \Delta\chi = \frac{3.4 - 0.5875}{2.5675} = 1.10 \]

The answer is a descriptor value, not a material.

Why inverse is hard

Many compounds have Δχ ≈ 1.1, with very different gaps; most values of a descriptor belong to no stable crystal at all. The inverse is one-to-many and must stay inside the set of real, stable materials.

Route 1 · high-throughput screening

Screening funnel: cheap filters first, costly checks last

bar width ∝ log₁₀(number of candidates) · simulated solid-electrolyte search

Cathodes, same funnel: Ehull → voltage from DFT energies, capacity Q = F/(3.6 M) (LiCoO₂: 274 mAh/g) → Li diffusion with an ML potential → lab.

stagecost per candidate
Ehull, Eg from a DFT databasealready computed (hours each, once)
ML model of conductivitymilliseconds
MD with an ML potential (lecture 12)about a GPU-day
synthesis and impedance testweeks
Two cylindrical lithium-ion battery cells
18650 and 21700 Li-ion cells. Sevenethics, CC0

Why a funnel

MD on all 5000 candidates ≈ 5000 GPU-days, about 14 GPU-years. The funnel spends 100 GPU-days, on the candidates most likely to pass.

Materials example 1 · screening solid electrolytes (simulated)

Does the ML ranking help? Compare with two baselines

candidates sent to MD (in ranked order) good conductors found

The set-up (simulated data)

918 stable, insulating candidates; 114 of them (12.4 %) are good conductors, σion > 1 mS/cm. A ridge model on quadratic features of three descriptors (lecture 2), trained on 150 known compounds outside the pool; MAE 0.39 in log₁₀σion.

rankinghits in top 50hits in top 100
random order6.212.4
most Li first (rule of thumb)1331
ML model4576

What the model learned

Which descriptor combinations go with fast ions: 6 times more hits than random. But it only ranks the list it is given, and it is trustworthy only inside its training range.

Math primer · Gaussians, sampling and the KL divergence

Three tools we need for generative models

1
A 1-D Gaussian and its logarithm:\[ q(z) = \frac{1}{\sqrt{2\pi}\,\sigma}\,e^{-\frac{(z-\mu)^2}{2\sigma^2}}, \quad \ln q(z) = -\ln\sigma - \tfrac12\ln 2\pi - \frac{(z-\mu)^2}{2\sigma^2} \]
Logs turn the product into a sum we can average.
2
Sampling any Gaussian from a standard one:\[ z = \mu + \sigma\,\varepsilon, \qquad \varepsilon \sim \mathcal N(0,1) \]
Shift by μ, stretch by σ: the randomness sits only in ε.
3
Two averages (write z − m = (z − μ) + (μ − m); the cross term averages to 0):\[ \mathbb E[(z-\mu)^2] = \sigma^2, \qquad \mathbb E[(z-m)^2] = \sigma^2 + (\mu - m)^2 \]
The second one is the key step of today's derivation.
\[ \mathrm{KL}(q\,\|\,p) = \mathbb E_{z\sim q}\big[\ln q(z) - \ln p(z)\big] \]
Kullback–Leibler divergence, in nats

Properties

  • KL ≥ 0, and KL = 0 only if q = p.
  • Not symmetric: KL(q‖p) ≠ KL(p‖q), so not a true distance.

Meaning

KL measures how much a distribution q differs from a reference p: the average extra "surprise" when the data come from q but we expected p.

Route 3 · generation · step 1: the autoencoder

Squeeze a material into a short code, then rebuild it

1

Loss: reconstruction error \(\ell = \lVert \mathbf x - \hat{\mathbf x} \rVert^2\), averaged over the training materials. No labels needed.

2

Bottleneck: z has far fewer numbers than x, so the network must keep only what matters. A linear autoencoder with squared loss finds the same subspace as PCA (lecture 7).

3

Generate? Pick a new code z and decode it. But nothing told the network what codes between the training points should mean.

latent space of a plain autoencoder (schematic)
Derivation · step 2: the variational autoencoder (VAE)

Encode each material as a small cloud, and keep all clouds near the origin

1
Encoder outputs a distribution: a mean μ(x) and a spread σ(x), so \(q(z\,|\,\mathbf x) = \mathcal N\big(\mu(\mathbf x), \sigma(\mathbf x)^2\big)\).
A cloud, not a point: nearby codes must decode to similar materials.
2
Reparameterization (primer step 2):\[ z = \mu(\mathbf x) + \sigma(\mathbf x)\,\varepsilon, \qquad \frac{\partial z}{\partial \mu} = 1, \quad \frac{\partial z}{\partial \sigma} = \varepsilon \]
The random draw moves into ε, so backpropagation (lecture 9) reaches μ and σ.
3
Loss = reconstruction + KL to a standard Gaussian prior:\[ L = \underbrace{\lVert \mathbf x - \hat{\mathbf x}(z) \rVert^2}_{\text{rebuild well}} + \underbrace{\mathrm{KL}\big(\mathcal N(\mu,\sigma^2)\,\|\,\mathcal N(0,1)\big)}_{\text{stay near the origin, keep spread}} \]
Two forces: the first pulls codes apart, the second pulls them together.
4
Generate: draw z ~ 𝒩(0, 1) and decode.
The prior now covers the region the decoder was trained on.
latent space of a VAE (schematic)

What the model learned

A smooth map of "material-like" codes: nearby z give similar materials, so we can interpolate and sample. It can only produce variations of what it saw; it knows nothing about stability unless we check.

Derivation · the KL term between two 1-D Gaussians

The KL term in closed form, step by step

1
Difference of logs for q = 𝒩(μ₁, σ₁²), p = 𝒩(μ₂, σ₂²) (primer step 1; the ln 2π cancels):\[ \ln q - \ln p = \ln\frac{\sigma_2}{\sigma_1} - \frac{(z-\mu_1)^2}{2\sigma_1^2} + \frac{(z-\mu_2)^2}{2\sigma_2^2} \]
2
Average over z ~ q (primer step 3):\[ \mathbb E_q[(z-\mu_1)^2] = \sigma_1^2, \qquad \mathbb E_q[(z-\mu_2)^2] = \sigma_1^2 + (\mu_1-\mu_2)^2 \]
Only these two averages are needed; everything else is a constant.
3
Insert:\[ \mathrm{KL}(q\|p) = \ln\frac{\sigma_2}{\sigma_1} + \frac{\sigma_1^2 + (\mu_1-\mu_2)^2}{2\sigma_2^2} - \frac12 \]
4
VAE prior μ₂ = 0, σ₂ = 1 (write μ, σ for the encoder):\[ \mathrm{KL} = \tfrac12\big(\mu^2 + \sigma^2 - 1 - \ln\sigma^2\big) \]

Sanity checks

  • μ = 0, σ = 1: KL = ½(0 + 1 − 1 − 0) = 0. Same distribution.
  • σ → 0: −ln σ² → ∞. A cloud that shrinks to a point is punished: no plain autoencoder.
  • Large μ costs μ²/2: codes far from the origin are pulled back.
  • Dimensionless (nats); d latent dimensions just add d such terms.

What the model learned

The KL term is the price of each code. A VAE pays it only where a distinct code really improves the reconstruction, so the latent space stays compact and filled.

Worked problem 1 · by hand

The price of a code, and one reparameterized sample

1
Encoder gives μ = 1, σ = 0.5.\[ \mathrm{KL} = \tfrac12\big(1 + 0.25 - 1 - \ln 0.25\big) = \tfrac12(0.25 + 1.386) = 0.818 \]
ln 0.25 = −1.386. A Monte Carlo average over 400 000 samples gives 0.818 too.
2
Encoder gives μ = 0, σ = 2.\[ \mathrm{KL} = \tfrac12\big(0 + 4 - 1 - \ln 4\big) = \tfrac12(3 - 1.386) = 0.807 \]
At the same μ = 0, σ = 0.5 would cost 0.318 and σ = 2 costs 0.807: both are penalized, with the minimum at σ = 1 (0.5 of case 1's 0.818 came from its mean).
3
Sample a code for case 1 with ε = −0.8:\[ z = \mu + \sigma\varepsilon = 1 + 0.5\times(-0.8) = 0.6 \]
This z goes into the decoder; the gradient reaches μ (factor 1) and σ (factor ε = −0.8).
encoder spread σ KL to 𝒩(0, 1) (nats)
Route 3 · generation · diffusion models (idea level)

Destroy data with noise, step by step, and learn to undo each step

1
Forward noising (fixed, nothing learned), with a small noise step βt at each of T steps:\[ \mathbf x_t = \sqrt{\bar\alpha_t}\,\mathbf x_0 + \sqrt{1-\bar\alpha_t}\,\boldsymbol\varepsilon, \qquad \bar\alpha_t = \prod_{s\le t}(1-\beta_s) \]
ᾱ falls from 1 (clean data) to almost 0 (pure Gaussian noise).
2
Learn the denoiser: a network \(\hat{\boldsymbol\varepsilon}_\theta(\mathbf x_t, t)\) guesses the noise that was added,\[ L(\theta) = \mathbb E\,\lVert \boldsymbol\varepsilon - \hat{\boldsymbol\varepsilon}_\theta(\mathbf x_t, t)\rVert^2 \]
Plain regression with squared loss, as in lecture 2, on endless self-made examples.
3
Sample: start from pure noise \(\mathbf x_T \sim \mathcal N(0, I)\) and remove a little predicted noise at every step, t = T, …, 1.
Many small, easy steps instead of one impossible jump.

By hand: one forward step and its undo

x₀ = 1.2, ᾱt = 0.5, ε = −0.6:

\[ x_t = \sqrt{0.5}\,(1.2) + \sqrt{0.5}\,(-0.6) = 0.424 \]

A perfect denoiser predicts ε̂ = −0.6, so

\[ \hat x_0 = \frac{x_t - \sqrt{0.5}\,\hat\varepsilon}{\sqrt{0.5}} = \frac{0.424 + 0.424}{0.707} = 1.2 \]

What the model learned

At every noise level, the direction from a noisy point toward real data. Many small steps along it turn noise into realistic samples. Slow: one network call per step (often hundreds of steps).

A 1-D toy · forward noising (simulated two-family data)

Two families of materials melt into one Gaussian

descriptor x (scaled), e.g. volume per atom probability density pt(x)

The toy

Data: two structure families, \(0.5\,\mathcal N(-1, 0.25^2) + 0.5\,\mathcal N(1.2, 0.3^2)\) (simulated). T = 100 steps, β from 0.001 to 0.12. The noised densities are exact.

step tᾱtwhat is left
250.68two peaks, blurred
500.21one lopsided hump
1000.002standard Gaussian

Try it (outside the video)

step t 0
ᾱ = 1.000
Materials example 2 · generating from the toy, against a baseline

Run the steps backwards: the two families come back

gap descriptor x (scaled) probability density
20 000 diffusion samplestrue densitybaseline: one Gaussian

How the samples were made

Start from 20 000 noise values; 100 reverse steps with the exact noise predictor of this toy (it stands in for a trained network). Baseline: one Gaussian fitted to 2000 data points (mean 0.11, sd 1.13), then sampled.

samples in the gap −0.4 < x < 0.5fraction
real data (true density)0.9 %
diffusion model1.1 %
single-Gaussian baseline30.6 %

What the model learned

The shape of the data: both families and the empty gap. It reproduces what it saw; novelty needs steering toward a target, and checking.

Generated crystals · what is generated, and how we check it

A generated crystal is only a candidate until DFT says it is stable

What the model outputs

Lattice L (3 × 3), fractional coordinates F (N × 3), atom types A (N). The generator must respect the invariances of lecture 3: translation, rotation, atom order, and periodicity.

Polyhedral model of the LiCoO2 crystal structure
LiCoO₂ layered structure (CoO₆ octahedra, Li between layers). Ben Mills, public domain
checkhowleft of 1000
validcharge neutral, no atoms closer than ~0.5 Å apart940
uniqueremove generated duplicates (structure matcher)870
novelnot already in the training database610
stablerelax (ML potential, then DFT); Ehull < 25 meV/atom85

Illustrative round numbers, not from a specific paper.

Published generators (examples)

CDVAE (a VAE with a diffusion decoder, 2022), DiffCSP (2023), MatterGen (a diffusion model steered by target properties, 2025). They are judged by the S.U.N. rate: stable, unique and novel.

Stable is still not made

Ehull is a 0 K, DFT number. A stable, novel crystal still needs a synthesis route, and some metastable phases are made every day.

Worked problem 2 · by hand

Do three generated A–B compounds survive the hull?

fraction of B in A₁₋ₓBₓ formation energy (eV/atom)
1

Hull at x = 0.4, between the hull points (1/3, −0.28) and (1/2, −0.40):

\[ -0.28 + (-0.12)\,\frac{0.4 - 1/3}{1/2 - 1/3} = -0.28 - 0.12\times0.4 = -0.328 \]
2

G1 at −0.31: Ehull = −0.31 − (−0.328) = 18 meV/atom < 25: keep.

3

G2 at x = 0.6: hull −0.34, compound −0.29 → 50 meV/atom: reject.

4

G3 at x = 0.9: hull −0.10, compound −0.12 → below the hull by 20 meV/atom: a new stable phase. The hull must be redrawn through it (dashed).

S.U.N. rate of the previous slide

85 / 1000 = 8.5 %, and 85 / 610 = 14 % of the novel ones. A new stable phase also changes Ehull of its neighbours.

Materials example 3 · synthesis recipes mined from papers

The literature is a dataset: turning sentences into recipes

“LiCoO₂ was prepared from Li₂CO₃ and Co₃O₄. The powders were dried at 120 °C, ground, and calcined at 900 °C for 12 h in air.”
Example sentence written for this lecture. Tags: target, precursors, drying, heating step.
1

Find synthesis paragraphs among millions of papers (a text classifier).

2

Tag words by their role: target, precursor, operation, temperature, time (named-entity recognition).

3

Balance the reaction, a check that the tags make chemical sense:

\[ 6\,\text{Li}_2\text{CO}_3 + 4\,\text{Co}_3\text{O}_4 + \text{O}_2 \rightarrow 12\,\text{LiCoO}_2 + 6\,\text{CO}_2 \]

Li 12 = 12, Co 12 = 12, C 6 = 6, O 18 + 16 + 2 = 36 = 24 + 12.

"synthesis temperature"answer
baseline rule: first number before °C120 °C ✗
role tagger: the heating step900 °C ✓
A row of muffle furnaces in a laboratory
Muffle furnaces, where such recipes run. Brammers, CC0

What the data can and cannot say

Text-mined datasets hold order 10⁴ solid-state recipes. They record what was published, mostly successes, so failed recipes are missing.

Large language models as materials-knowledge tools

A language model generates text: plausible is not true

\[ p(\text{next token} \mid \text{all previous tokens}) \]

Useful for

  • summarizing papers; first drafts of code
  • extracting tables from text (last slide)
  • suggesting hypotheses to test

Limits

  • hallucination: invented numbers and references, in a confident tone
  • knowledge stops at the training date
  • arithmetic, units and stoichiometry are not checked

Cite and verify: five rules

  1. Every number gets a primary source (handbook, paper, database entry).
  2. Check that each reference exists and says what is claimed.
  3. Let the model call tools (database query, calculator), not memory.
  4. Score extraction on a hand-checked sample: precision and recall (lecture 5), against a simple rule.
  5. Never put unverified values into a training set.

What the model learned

How materials text reads, not which statements are true. A fluent wrong answer looks just like a right one.

Lab 14 · this week in Colab

A 1-D diffusion model and a KL check in a few lines

import numpy as np
rng = np.random.default_rng(0)
T = 100; beta = np.linspace(1e-3, 0.12, T)
abar = np.cumprod(1 - beta)
x0 = two_families(5000)              # data
t = rng.integers(0, T, 5000)
eps = rng.normal(size=5000)
xt = np.sqrt(abar[t])*x0 + np.sqrt(1-abar[t])*eps
net = train_mlp(inputs=(xt, t), target=eps)  # lab 9
x = rng.normal(size=20000)           # pure noise
for t in reversed(range(T)):
    e = net(x, t)
    x = (x - beta[t]/np.sqrt(1-abar[t])*e) / np.sqrt(1-beta[t])
    if t > 0: x += np.sqrt(beta[t])*rng.normal(size=x.size)
mu, s = 1.0, 0.5
kl = 0.5*(mu**2 + s**2 - 1 - np.log(s**2))  # 0.818

Exercises

  • Check the KL formula against a Monte Carlo average of ln q − ln p.
  • Train the denoiser; compare the generated histogram with the data and with the single-Gaussian baseline (fraction in the gap).
  • Use T = 10 instead of 100. What goes wrong, and why?
  • Screening: filter a provided table by Ehull < 25 meV/atom and Eg > 3 eV, rank with a ridge model, count hits in the top 100 against random order.

Runs in Google Colab on a CPU; the tiny network trains in about a minute. Notebook and data are posted with this lecture.

Answers to the why questions

The four puzzles, solved

1 · 10 000 generated ≠ 10 000 new materials

Each must be valid, unique, novel and stable. In our example only 85 of 1000 survived (8.5 %), and stable at 0 K still needs a synthesis route.

2 · Running the model backwards

The inverse is one-to-many: Eg = 3.4 eV gives Δχ = 1.10, a descriptor shared by many compounds, and most descriptor values match no real crystal.

3 · Perfect autoencoder, poor generator

Its codes form clumps with holes; codes between them were never trained. The VAE's KL term fills and organizes the latent space.

4 · A confident fake reference

A language model generates plausible text, p(next token), not checked facts. Cite and verify every number and reference.

Check your understanding · click a card to reveal

Concept check

Q1. An encoder gives μ = 0.5, σ = 1 for one material. What is its KL term to 𝒩(0, 1)?
½(0.25 + 1 − 1 − ln 1) = 0.125 nats. Only the mean costs anything; the spread already matches the prior.
Q2. A generator reports 99 % valid and 95 % unique structures. Is it a good materials generator?
Not yet. A model that copies its training set scores just as well. Ask for novelty and stability (DFT Ehull): the S.U.N. rate.
Q3. Why is sampling from a diffusion model much slower than from a VAE?
A VAE needs one decoder pass; a diffusion model needs one network call per denoising step, often hundreds.
Q4. A language model gives you a melting point and a DOI. What do you do before using the value?
Check that the DOI exists and reports that value, or cross-check a handbook. Unverified values never go into a training set.
Wrap-up

Summary and next lecture

1
Inverse design asks for materials with a target property. It is one-to-many and must stay inside real, stable materials.
2
Screening funnels: cheap filters first. An ML ranking found 6× more good conductors than random order (simulated).
3
VAE: encode to a cloud, z = μ + σε, loss = reconstruction + ½(μ² + σ² − 1 − ln σ²).
4
Diffusion: add noise step by step, learn to predict it, and remove it from pure noise.
5
Every generated crystal must pass valid, unique, novel, stable (Ehull); text and language models must be cited and verified.

This week

Lab 14: a 1-D diffusion model, the KL check, a small screening funnel. Problem set 5 (weeks 13–14) is due in week 15, together with your project poster and report.

Next lecture · Interpretable and physics-informed ML, and course synthesis

Why did the model predict that? Permutation importance, Shapley values, symbolic regression and the tolerance factor, physical consistency checks, and a map of the whole course: which method to use when, and how each one fails.

References and image credits

Further reading

Reading for this week

  • C. M. Bishop, H. Bishop, Deep Learning: Foundations and Concepts, Springer (2024): chapters on autoencoders, variational autoencoders and diffusion models.
  • K. P. Murphy, Probabilistic Machine Learning: An Introduction, MIT Press (2022): KL divergence and latent-variable models.
  • D. P. Kingma, M. Welling, "Auto-encoding variational Bayes," ICLR (2014).
  • J. Ho, A. Jain, P. Abbeel, "Denoising diffusion probabilistic models," NeurIPS (2020).
  • T. Xie et al., "Crystal diffusion variational autoencoder for periodic material generation," ICLR (2022) (CDVAE).
  • C. Zeni et al., "A generative model for inorganic materials design," Nature (2025) (MatterGen).
  • R. Jiao et al., "Crystal structure prediction by joint equivariant diffusion," NeurIPS (2023) (DiffCSP).
  • O. Kononova et al., "Text-mined dataset of inorganic materials synthesis recipes," Sci. Data 6, 203 (2019).
  • V. Tshitoyan et al., "Unsupervised word embeddings capture latent knowledge from materials science literature," Nature 571, 95 (2019).
  • S. Sandfeld, Materials Data Science, Springer (2024).

Image credits (Wikimedia Commons)

  • 18650 and 21700 lithium-ion cells: Sevenethics, CC0 — File page
  • LiCoO₂ crystal structure, polyhedral model: Ben Mills, public domain — File page
  • Muffle furnaces in a laboratory: Brammers, CC0 — File page

All schematics and plots were drawn for this course. The screening pool, the 1-D two-family data and the generated-crystal counts are simulated or illustrative; the A–B hull is the illustrative system of lecture 1. The example synthesis sentence was written for this lecture.