06-763 / L15

Lecture 15: Bayesian optimization

Week 8, Machine learning and deep learning

Systems and Toolchains for AI Engineers
06-763 / L15

Today

A stirred tank reactor
1
The problem
A reaction, a few expensive experiments
A surrogate with its uncertainty
2
Gen 1 and Bayes
A model that "knows what it does not know"
A Gaussian process and an acquisition function
3
The loop
Explore, exploit, acquisition functions
Bayesian optimization against other optimizers
4
In practice
BoTorch, when to use it, where it is used
Systems and Toolchains for AI Engineers
06-763 / L15

The problem

Systems and Toolchains for AI Engineers
06-763 / L15

The problem, a reaction

A→B→C
  • A raw material A turns into the product we sell, B
  • B keeps reacting into a waste, C
  • Heat speeds up both steps, but the second one more
  • Two knobs: the temperature T, and the time in the tank τ
Systems and Toolchains for AI Engineers
06-763 / L15

The problem, a simple toaster example

Too cold
Bread stays bread

A barely reacts
Little B
Just right
Golden toast

Most of A becomes B
Before it goes further
Too hot
Burnt

B burns into C
Little B again

Somewhere in between is a best temperature. Where?

Systems and Toolchains for AI Engineers
06-763 / L15

The problem, the yield curve

  • Yield: the fraction of A that leaves as B
  • Best: 0.46 at 80 °C, with 10 min in the tank
  • Each point on this curve is one experiment
  • In the lab, nobody sees this curve
Systems and Toolchains for AI Engineers
06-763 / L15

The problem, the same shape in industry

Ethylene oxide

Sketch: ethylene falls, ethylene oxide rises then falls, CO2 rises

Raw material for antifreeze and plastics. On the silver catalyst, over-oxidation burns the product (Pu et al., 2019)

Sugar from wood

Sketch: cellulose falls, glucose rises then falls, waste rises

Acid makes the sugar, then destroys it. Saeman's 1945 model is exactly A → B → C

Drug synthesis

Sketch: reagents fall, the drug rises then falls, impurities rise

The drug is an intermediate. Choosing its reaction conditions is a BO problem (Shields et al., 2021)

Made in the middle of a chain, destroyed by going further.

Systems and Toolchains for AI Engineers
06-763 / L15

The problem, what an experiment costs

hours
per experiment: heat up, reach steady state, sample, analyze
121
experiments for a 1 °C grid from 20 to 140 °C: weeks of lab time
thousands
for a grid over two knobs
10 to 30
the budget a lab can afford

  • A grid that fits the budget is coarse: 6 runs, every 24 °C
  • It misses the peak: 0 of 6 within 10% of the best yield
Systems and Toolchains for AI Engineers
06-763 / L15

Black-box objective

Inputs
T, τ
→
The lab
(or a slow simulation)
→
One noisy number
yield

Black-box objective: a function you can only evaluate. Set the inputs, run the experiment, read one noisy number. No formula, no gradient.

Systems and Toolchains for AI Engineers
06-763 / L15

  • Six experiments each. Green: within 10% of the best yield. Red: wasted
  • Neither strategy learns from the experiments it already ran
Systems and Toolchains for AI Engineers
06-763 / L15

Gen 0 and Gen 1

Systems and Toolchains for AI Engineers
06-763 / L15

Gen 0 and Gen 1, the surrogate

Gen 0: the surrogate model

  • A cheap model replaces an expensive simulator or experiment
  • It predicts. That is all

Surrogate model: a cheap model of the objective, fitted to the evaluations so far.

Systems and Toolchains for AI Engineers
06-763 / L15

Gen 0 and Gen 1, machine learning with intention

Gen 1: the surrogate "knows what it does not know"

  • The surrogate also says how uncertain it is

Bayesian optimization is Gen 1.

Systems and Toolchains for AI Engineers
06-763 / L15

Why "Bayesian"?

Systems and Toolchains for AI Engineers
06-763 / L15

Why "Bayesian", Bayes' rule

posterior

likelihood

prior

Prior, p(f)

What we believe about the yield curve before any experiment

Reactor: "the yield is around 0.25, and changes smoothly over about 20 °C"

Likelihood, p(data | f)

How well a candidate curve f explains the measurements, given the noise (0.01)

Reactor: we measured 0.181 at 50 °C. A curve through 0.18 there fits; a curve through 0.40 does not

Posterior, p(f | data)

What we believe after the experiments: only curves that fit the data remain

Reactor: after 30 and 50 °C, every curve passes near 0.05 and 0.18. At 110 °C, still anything

The unknown is the whole curve, f. Each experiment updates our belief about it.

Systems and Toolchains for AI Engineers
06-763 / L15

Why "Bayesian", a Gaussian process

  • Lecture 14: exact and cheap to update; the posterior is again a GP
  • Smoothness and noise fitted by marginal likelihood

Gaussian process (GP): a prior over functions. After the data, a mean μ(x) and an uncertainty σ(x) at every input.

Systems and Toolchains for AI Engineers
06-763 / L15

Why "Bayesian", the posterior, one experiment at a time

A Gaussian process prior over yield curves, then updated by up to five experiments, with three sample curves
Systems and Toolchains for AI Engineers
06-763 / L15

Why "Bayesian", the decision

Prior
over curves
→
Experiments
→
Posterior
μ(x), σ(x)
→
Decision:
where next?
  • Bayesian statistics: update the belief with data
  • Bayesian decision: choose the next experiment on that belief
  • Both together: Bayesian optimization. "The term Bayesian optimization was coined in the seventies", citing Močkus, Tiesis and Žilinskas (1978) (Shahriari et al., 2016, p. 17)
Systems and Toolchains for AI Engineers
06-763 / L15

The loop

Systems and Toolchains for AI Engineers
06-763 / L15

Bayesian optimization

Bayesian optimization (BO): maximize a black-box objective in few evaluations. Fit a surrogate to every evaluation so far, choose the next input by maximizing an acquisition function, evaluate it, and repeat.

A Gaussian process fitted to two experiments

1. Fit a GP to all data

→
Expected improvement over temperature with its maximum marked

2. Score with an acquisition function, cheap

→
One new experiment at the maximum of the acquisition

3. Run the best candidate

→
The Gaussian process refitted with the new experiment

4. Add it to the data

repeat until the budget is spent
Systems and Toolchains for AI Engineers
06-763 / L15

The loop, terminology

  • Incumbent f*: the best value measured so far. Here 0.474, at experiment 7
  • Budget: the number of experiments we can afford. Here 12
  • Regret: best possible value minus the best found. After 4 experiments: 0.46 − 0.31 = 0.16

The goal: small regret, small budget.

Systems and Toolchains for AI Engineers
06-763 / L15

The loop, step by step

Gaussian process, expected improvement and next experiment at each step of Bayesian optimization on the reactor
Systems and Toolchains for AI Engineers
06-763 / L15

The loop, what it did

30, 50 °C
two old runs
→
54, 61, 72, 87, 81 °C
climbing
→
140 °C
explores: still unsure there
→
80 °C
settled
7
experiments to 98% of the best yield, the two old runs included
0.474
best measured yield, at 80.5 °C (true there: 0.461)
0.462
best possible: 79.5 °C
Systems and Toolchains for AI Engineers
06-763 / L15

Exploration and exploitation

Systems and Toolchains for AI Engineers
06-763 / L15

Exploitation and exploration

Exploitation: run the next experiment where the surrogate predicts a good value (high μ).

Exploration: run it where the surrogate is unsure (high σ).

Systems and Toolchains for AI Engineers
06-763 / L15

Exploration and exploitation, tonight's dinner

Your favorite restaurant

You know it is good. You will never find out if the new place is better

Exploitation

The new place

Could be great, could be awful. You learn something either way

Exploration

A good acquisition function does some of both.

Systems and Toolchains for AI Engineers
06-763 / L15

Exploration and exploitation, the two extremes

Pure exploitation

Keeps sampling next to the best point so far

Can sit on a local optimum forever: it never looks elsewhere

Pure exploration

Samples wherever the band is widest

Learns the whole curve, ignores the goal: close to a careful random search

Every acquisition function is a recipe for the balance, with a knob.

Systems and Toolchains for AI Engineers
06-763 / L15

Exploration and exploitation, one knob

The upper confidence bound mu plus kappa sigma and its maximum, as kappa changes
Systems and Toolchains for AI Engineers
06-763 / L15

Acquisition functions

Systems and Toolchains for AI Engineers
06-763 / L15

Acquisition functions, the z-score

z-score: how many GP standard deviations the predicted yield μ(x) sits above the best so far, f*. z > 0: the GP expects to beat f*. z < 0: it expects to fall short.

  • Reactor, at 60 °C after 3 experiments: μ = 0.242, σ = 0.046, f* = 0.236, so z = (0.242 − 0.236) / 0.046 = 0.13
  • ξ (xi), the margin: the smallest gain that counts. With ξ = 0.01, a temperature counts only if it beats 0.236 by more than 0.01
  • ξ > 0 ignores tiny gains right next to f*, so the search moves away from it: more exploration. The worked example uses ξ = 0
Systems and Toolchains for AI Engineers
06-763 / L15

Acquisition functions, probability of improvement (PI)

Probability of improvement (PI): the probability that the yield at x beats the best so far, f*, by more than ξ.

  • 1. At 60 °C the GP gives a bell of possible yields: mean 0.242, sd 0.046
  • 2. The best yield so far: f* = 0.236
  • 3. PI = the share of the bell above f*: 0.55
  • 4. Same number from z: Φ(z) is the share of a standard bell left of z. Φ(0.13) = 0.55

In short: PI runs the experiment most likely to beat the best so far, however small the gain.

Systems and Toolchains for AI Engineers
06-763 / L15

Acquisition functions, expected improvement (EI)

Expected improvement (EI): the average amount by which the yield at x beats the best so far, counting a miss as zero.

The gain, I(x)

If the yield at x turns out to be f, the gain is f − f*. Below f*, the gain is 0

The average, 𝔼

Average the gain over the GP's bell of possible yields

Exploitation term

How far the mean is above f*, times Φ(z), the chance of beating f*. Large where μ is high

Exploration term

The bell's width σ times φ(z), the bell's height at z. Large where σ is large

Systems and Toolchains for AI Engineers
06-763 / L15

Acquisition functions, LogEI

LogEI: compute log EI directly, with formulas that stay accurate where EI is tiny. Same maximizer as EI: the log does not move the peak.

  • Why: far from the data, EI is so small that the computer rounds it to 0. EI's values "vanish numerically in many regions" (Ament et al., 2023)
  • Top: EI after the 12 experiments. One narrow peak near 80 °C, about 10⁻⁸ high
  • Red: where the computer stores EI as exactly 0. Flat: the optimizer finds no slope to follow
  • Bottom: log EI. A finite number everywhere, sloping up toward 80 °C
  • Both peak at the same temperature: the same next experiment

Systems and Toolchains for AI Engineers
06-763 / L15

Acquisition functions, upper and lower confidence bounds

Upper confidence bound (UCB): an optimistic score, the GP mean plus κ standard deviations. LCB, μ − κσ, is the same idea for minimizing.

  • κ (kappa): how many standard deviations of optimism. UCB scores each temperature by the top of its band, μ + κσ
  • κ = 0: the mean only. Pure exploitation
  • κ = 2: the top of the 95% band. On the reactor: next experiment at 65 °C
  • Large κ: the band wins. Exploration

Systems and Toolchains for AI Engineers
06-763 / L15

Acquisition functions, one GP, three choices

  • The same GP, after three experiments (30, 50, 54 °C)
  • PI 56 °C: closest to the best so far
  • EI 61 °C
  • UCB, κ = 2: 65 °C, the furthest into the unknown

Same data, same GP: the acquisition function alone sets the next experiment.

Systems and Toolchains for AI Engineers
06-763 / L15

Acquisition functions, where the ideas come from

1964
Kushner
Probability of improvement, for a noisy curve

J. Basic Eng.
1970s
Šaltenis, Močkus
Expected improvement; "Bayesian"

Močkus 1975
1998
Jones, Schonlau, Welch
EGO: EI on a kriging model

kriging + EI

J. Global Optim.
2001
Jones
A taxonomy of response-surface methods

which work, which fail

J. Global Optim.
2010
Srinivas et al.
UCB on a GP: GP-UCB

ICML
2012
Snoek et al.
BO for machine learning

hyper­parameters

NeurIPS
2020
BoTorch
On PyTorch; LogEI in 2023

NeurIPS
Systems and Toolchains for AI Engineers
06-763 / L15

Acquisition functions, Donald Jones and EGO

Efficient global optimization (EGO): fit a kriging model (a GP), sample where expected improvement is largest, refit, repeat (Jones, Schonlau and Welch, 1998).

  • Start: a space-filling design, about 10 points per input
  • Fit the kriging model; check it by cross-validation
  • Loop: maximize EI; sample there; refit
  • Stop when EI is below 1% of the best value
  • Kriging: named after Danie Krige, a South African mining engineer who estimated gold grades from samples (NAE)
Systems and Toolchains for AI Engineers
06-763 / L15

Bayesian optimization in BoTorch

Systems and Toolchains for AI Engineers
06-763 / L15

BoTorch

BoTorch: acquisition functions, optimizing them
GPyTorch: Gaussian processes
PyTorch: tensors, automatic differentiation
BoTorch
  • optimize_acqf maximizes the acquisition with L-BFGS-B, a gradient method. PyTorch's automatic differentiation supplies the gradients
  • Docs and tutorials: botorch.org
Systems and Toolchains for AI Engineers
06-763 / L15

BoTorch, the experiment

R = 8.314                     # J/(mol K)


def rate(T, k_ref, E):
    # Arrhenius: rate constant (1/min) at T (degC), relative to 80 degC
    T = T + 273.15
    return k_ref * np.exp(-E / R * (1 / T - 1 / 353.15))


def yield_B(T, tau):
    # steady-state yield of B in the tank, for A -> B -> C
    k1 = rate(T, 0.15, 60e3)      # A -> B
    k2 = rate(T, 0.03, 110e3)     # B -> C: needs more heat
    return k1 * tau / ((1 + k1 * tau) * (1 + k2 * tau))


rng = np.random.default_rng(0)


def run_experiment(T):
    # one experiment per row of T (degC): 10 min in the tank, noise 0.01
    y = yield_B(T.numpy().ravel(), 10.0)
    y = y + 0.01 * rng.standard_normal(T.shape[0])
    return torch.tensor(y).unsqueeze(-1)

Arrhenius' law: heat speeds up each step

Yield of B at steady state. E₂ > E₁: the waste step needs more heat

The "lab": one noisy yield per temperature. The optimizer sees only this

Systems and Toolchains for AI Engineers
06-763 / L15

BoTorch, two old runs

bounds = torch.tensor([[20.0], [140.0]])      # temperature from 20 to 140 degC
torch.manual_seed(0)

# two old runs from the lab notebook
T = torch.tensor([[30.0], [50.0]])
y = run_experiment(T)
Where BO may search: 20 to 140 °C
The starting data: two cold runs. Each row is one experiment
Systems and Toolchains for AI Engineers
06-763 / L15

BoTorch, the loop, the surrogate

for i in range(10):
    # 1. the surrogate: a GP fitted to every experiment so far
    gp = SingleTaskGP(
        T,
        y,
        input_transform=Normalize(d=1),
        outcome_transform=Standardize(m=1),
    )
    mll = ExactMarginalLogLikelihood(gp.likelihood, gp)
    fit_gpytorch_mll(mll)
Ten more experiments: the budget
The GP. Normalize: temperature to [0, 1]. Standardize: yields to mean 0, standard deviation 1
Fit its settings (smoothness, noise) by marginal likelihood, as in Lecture 14
Systems and Toolchains for AI Engineers
06-763 / L15

BoTorch, the loop, acquire and run

    # 2. the acquisition: expected improvement over the best yield so far
    acq = LogExpectedImprovement(gp, best_f=y.max())

    # 3. the next experiment: where the acquisition is largest
    T_next, _ = optimize_acqf(
        acq,
        bounds=bounds,
        q=1,
        num_restarts=10,
        raw_samples=200,
    )

    # 4. run it, and add it to the data
    y_next = run_experiment(T_next)
    T = torch.cat([T, T_next])
    y = torch.cat([y, y_next])
LogEI, with the incumbent: the best yield so far
Maximize it: score 200 random candidates, start 10 gradient searches from the best. q=1: one experiment at a time
The only expensive line: the experiment. Then add it to the data
Systems and Toolchains for AI Engineers
06-763 / L15

BoTorch, what it ran

experiment  1: T =  30.0 C, yield 0.050
experiment  2: T =  50.0 C, yield 0.181
experiment  3: T =  54.4 C, yield 0.236
experiment  4: T =  60.7 C, yield 0.306
experiment  5: T =  71.5 C, yield 0.419
experiment  6: T =  86.9 C, yield 0.430
experiment  7: T =  80.5 C, yield 0.474
experiment  8: T = 140.0 C, yield 0.023
experiment  9: T =  80.0 C, yield 0.454
experiment 10: T =  80.0 C, yield 0.449
experiment 11: T =  80.1 C, yield 0.455
experiment 12: T = 102.5 C, yield 0.219
Climbs from the cold side: 54, 61, 72, 87, 81 °C
Experiment 8: 140 °C, where the GP was still unsure. Yield 0.023: nothing there
Settles at 80 °C, with a check at 102.5 °C
Systems and Toolchains for AI Engineers
06-763 / L15

BoTorch, check the answer

  • Only now do we look at the true curve
  • Best experiment: 80.5 °C, measured 0.474, true 0.461
  • True best: 79.5 °C, 0.462
  • The band is wide between 105 and 135 °C, where BO ran no experiment
Systems and Toolchains for AI Engineers
06-763 / L15

BoTorch, a second knob: the time in the tank

  • The pump sets the flow q, so the time in the tank τ = V / q: from 1 to 30 min
  • The knobs interact: with 30 min, the best temperature drops from 80 to 67 °C, and the best yield rises from 0.46 to 0.55
Systems and Toolchains for AI Engineers
06-763 / L15

BoTorch, comparing optimizers: what to report

Several seeds

BO is random: the noise, the random candidates. One run is one sample

A baseline

Random search at least. Also try a classic optimizer, if possible

Best so far

Against experiments, with its spread across seeds

The budget

Count every experiment, the old runs included

Systems and Toolchains for AI Engineers
06-763 / L15

BoTorch, ten seeds

  • Median over 10 seeds, shaded from the worst to the best seed
  • BO: 98% of the best possible yield in all 10 seeds, after 8 experiments (median)
Systems and Toolchains for AI Engineers
06-763 / L15

When to use it

Systems and Toolchains for AI Engineers
06-763 / L15

When to use it, four optimizers with the same 30 experiments

Bayesian optimization, Nelder-Mead, L-BFGS-B and random search choosing experiments on the two-knob yield map
Systems and Toolchains for AI Engineers
06-763 / L15

When to use it, ten seeds

Where BO ran its experiments, seed 0
10 / 10
Bayesian optimization
reached 98% of the best yield, median 8 experiments
Where L-BFGS-B ran its experiments, seed 0
2 / 10
L-BFGS-B
median 86% after 30 experiments
Where Nelder-Mead ran its experiments, seed 0
0 / 10
Nelder–Mead
stuck near 20% of the best
Where random search ran its experiments, seed 0
0 / 10
Random search
median 93% after 30 experiments

All four: the same reactor, noise, budget of 30 and cold start. Maps: seed 0; star: the best.

Systems and Toolchains for AI Engineers
06-763 / L15

When to use it, why gradient methods stall here

  • Each y is an experiment, with noise 0.01
  • A gradient by finite differences costs an experiment per input
  • Cold side, h = 1.2 °C: true change 0.008, noise in the difference ±0.028
  • Nelder–Mead needs no gradient, but it is local: it shuffles around where it started

Finite differences need cheap, noise-free evaluations. Lab experiments are expensive and noisy.

Systems and Toolchains for AI Engineers
06-763 / L15

When to use it, BO or gradient-based?

  • Gradient-based (Newton, L-BFGS, IPOPT): cheap evaluations, gradients available, up to millions of inputs. A local optimum, fast
  • Bayesian optimization: expensive (minutes to weeks), noisy, no gradients, up to about 20 inputs, tens to hundreds of evaluations
  • Other derivative-free (Nelder–Mead, evolutionary): no gradients, but cheap enough for thousands of evaluations

Choose by the cost of one evaluation, the noise, and the number of inputs.

Systems and Toolchains for AI Engineers
06-763 / L15

Where it is used

Systems and Toolchains for AI Engineers
06-763 / L15

Where it is used, chemistry and materials

Reaction optimization

50 expert chemists and engineers against BO, choosing reaction conditions

"Bayesian optimization outperforms human decision making in both average optimization efficiency (number of experiments) and consistency"

Shields et al., Nature (2021)

A self-driving lab

A mobile robot searching for a better photocatalyst

"operated autonomously over eight days, performing 688 experiments within a ten-variable experimental space, driven by a batched Bayesian search algorithm"

Burger et al., Nature (2020)

Fast-charging batteries

BO with early predictions of battery life

"among 224 candidates in 16 days (compared with over 500 days using exhaustive search without early prediction)"

Attia et al., Nature (2020)

Systems and Toolchains for AI Engineers
06-763 / L15

Where it is used, engineering

Process design

Flowsheet optimization when each unit is an expensive black box

"The black box modules are substituted by metamodels based on a kriging interpolation"

Caballero and Grossmann, AIChE J. (2008)

Engineering design

Wings and other shapes, each evaluated by an expensive simulation

"Surrogate models expedite the search for promising designs by standing in for expensive design evaluations or simulations"

Forrester, Sóbester and Keane (2008)

Controller tuning

An automotive throttle valve, tuned on the test bench

"BO achieves on par or better performance than hand tuning with only around ten experimental evaluations"

Neumann-Brosig et al., IEEE TCST (2020)

Systems and Toolchains for AI Engineers
06-763 / L15

Where it is used, machine learning and beyond

Hyperparameters

Choosing a model's settings, such as the learning rate, when each training run takes hours

Snoek et al. (2012)

AlphaGo

Tuning the Go program's settings, where each test is many games. Win rate against its old self: 50% to 66.5%

Chen et al. (2018)

Online experiments

Facebook tuned the settings of a ranking system and of its server software. Each try is a live test with noisy results

Letham et al. (2019)

Cookies

Google tuned a chocolate chip cookie recipe (sugar, salt, vanilla, chips) by taste tests, in 144 experiments

Solnik et al. (2017)

Anywhere one evaluation is expensive and there is no formula.

Systems and Toolchains for AI Engineers
06-763 / L15

Where it is used, what engineers also need

Constraints

Yield curve with the region above 70 degrees shaded as not allowed

The best yield may need a temperature the reactor cannot take. A second GP learns that limit from the same experiments, and BO proposes only runs likely to respect it

Batches

Expected improvement with four experiments chosen at once

Four reactors: four experiments at once (q=4, qLogEI)

Several objectives

Yield against production rate with the Pareto front in red

Yield and rate: the Pareto front, the best trade-offs (qEHVI)

Several fidelities

A cheap rough model and the lab curve, many cheap points and few lab points

Many cheap, rough runs and a few exact ones: BO picks which, and where

All four are in BoTorch.

Systems and Toolchains for AI Engineers
06-763 / L15

Limitations and trade-offs

What goes wrong
What to do
Many inputs: beyond about 20, the GP needs far more data
Fewer knobs, or methods built for high dimension
Many evaluations: fitting the GP grows as n³
Fine for hundreds. For thousands of cheap runs, use something else
Jumps and cliffs: the kernel assumes smoothness, so the band is wrong
Check the GP against held-out runs; change the kernel
Cold start: with two or three points, the band is not trustworthy
Start from a small, spread-out set of experiments
A noisy incumbent: 0.474 measured, 0.461 true
Repeat the best experiment, or report the GP's best
One run of a random method
Several seeds and a baseline
Systems and Toolchains for AI Engineers
06-763 / L15

Active learning, the same loop, a different goal

Active learning: choose each next experiment to make the model good everywhere, usually where it is most uncertain.

  • The next experiment goes where the band is widest
  • BO (EI), 6 more runs: crowds around 80 °C. The best point, found
  • Active learning, 6 more runs: spread from 20 to 140 °C. A narrow band everywhere
Systems and Toolchains for AI Engineers
06-763 / L15

Recap

When

Where each optimizer fits

Expensive, noisy, no gradients, few inputs

Why "Bayesian"

A GP prior over the curve, updated by every experiment

The loop

fitscorerunadd

Fit, score, run, add

The balance

UCB

Exploit high μ, explore high σ

Acquisition functions

BoTorch

SingleTaskGP: the GP

LogExpectedImprovement: the score

optimize_acqf: the next experiment

Systems and Toolchains for AI Engineers
06-763 / L15

Worked example

l15-bayesian-optimization.ipynb: BoTorch on the reactor, one knob then two

Systems and Toolchains for AI Engineers
06-763 / L15

Before next time

  • Assignment 5, four models of a bioreactor: released today, due Wednesday 10-28
  • Practice module for this session, for participation credit
Systems and Toolchains for AI Engineers

90 minutes of deck, 20 for the notebook. One example all the way: the reactor.

Coffee roasting works too: green, roasted, burnt.

We built the curve from the kinetics only to play the lab and check the answer. The optimizer never sees it.

The curves are sketches of first-order kinetics, A -> B -> C, not data. Saeman's paper is behind the ACS paywall.

From my seminar, as in Lecture 13.

The green diamond: where the uncertainty is largest.

How do you draw one of these random curves from the GP, in practice? Evaluate the GP on a grid of temperatures (here 241 of them). That gives a mean vector mu and a covariance matrix K. Factor K = L L^T (Cholesky). Draw a vector z of standard normal random numbers. The curve is mu + L z. In BoTorch the same thing is gp.posterior(T_grid).rsample().

Play. Prior first: same belief everywhere. Then 30, 50, 110, 80, 65 °C. The sample curves agree where we measured.

Where is Mockus in Shahriari et al. (2016)? The review spells him Močkus, with a caron, and names him only in the reference list. Page 17 of the PDF: "The term Bayesian optimization was coined in the seventies [115]". Reference [115] is J. Močkus, V. Tiesis and A. Žilinskas, "The application of Bayesian methods for seeking the extremum", 1978. The link opens that page.

The four panels are the first pass of the worked example: two old runs, EI peaks at 54 °C, run it, refit.

Step through slowly. Step 6: the jump to 140 °C, where the GP is unsure. After that it never goes back there.

What is kappa, the number on the slider? It is the weight on uncertainty in the upper confidence bound, mu(x) + kappa sigma(x): how many standard deviations of optimism we add to the GP mean. Kappa = 0: the score is just the mean, so the next run goes right next to the best point so far (58 °C). As kappa grows, the uncertainty term takes over and the pick moves to where the band is widest.

Slide κ from 0 up. At 0 it sits next to 54 °C. Around 2 it moves out. At 5 it goes where the band is widest.

What are the Greek letters? Xi (ξ) is the margin. It is in z. In plain terms, the smallest gain that counts: with xi = 0.01, a temperature counts as an improvement only if it beats 0.236 by more than 0.01. A larger xi ignores tiny gains right next to f*, so the search moves away from it. We use xi = 0. Capital and lowercase phi (Φ, φ) are NOT in z. They take z as input in PI and EI: Φ is the standard normal cumulative distribution, φ its density. They are defined on the next two slides.

PI in plain words. At 60 °C the GP does not give one yield. It gives a bell of possible yields, centred at 0.242, spread 0.046. The best yield so far is 0.236. PI is the share of the bell above 0.236: 55%. A 55% chance that 60 °C beats the best so far. Phi(z) is the same number reached through z. Shifting and rescaling the bell to a standard one turns the share above 0.236 into the share left of z = 0.13, and Phi(0.13) = 0.55. The weakness: a point right next to f*, with a narrow bell, gets PI near 1 for a gain of almost nothing. That is why EI weighs each gain by its size.

What is the gain f minus f*? If we ran the experiment at 60 °C and the yield came out f, the gain over the best so far would be f minus f*. If f is below f*, we gain nothing: the gain is 0, not negative. Bottom panel: the gain for every possible yield. Top panel: how likely each yield is. EI averages the gain over the bell: 0.022 at 60 °C. Each card lights up its term in the equation as it appears.

Why LogEI was created. Far from the data, EI is so small that the computer rounds it to exactly 0 (underflow; below about 1e-324 in double precision). Here, after 12 experiments, that happens at 12% of the temperatures (red). Where EI is exactly 0, its slope is 0 too, so the optimizer that follows the slope has no direction. Log EI is about -1000 there instead: a normal number with a slope. The log does not move the peak, so the next experiment is the same. Ament et al. (2023): EI's values "vanish numerically in many regions".

What is kappa exactly, besides the knob? How many standard deviations of optimism. UCB scores each temperature by the top of its band, mu + kappa sigma. Kappa = 2 is the top of the 95% band. What is beta in BoTorch? UpperConfidenceBound(gp, beta) computes mu + sqrt(beta) sigma, so beta = kappa squared: beta = 4 means kappa = 2. Not on this slide on purpose: BoTorch comes later. It is in the notes' BoTorch section.

The figure redraws the idea of the paper's Figs. 8 to 11 on our own function: the prediction alone only refines the local peak near the cluster; EI is largest in the gap. Jones (2001) is the follow-up taxonomy.

Is "automatic differentiation" true for BoTorch? Yes. Checked in the BoTorch 0.18.1 source: optimize_acqf calls gen_candidates_scipy, which runs SciPy's L-BFGS-B, and the gradients come from torch.autograd.grad. The GP is a formula, so the acquisition has exact gradients. Only the experiment itself has none.

Play. Watch Nelder-Mead and L-BFGS-B sit in the cold corner. Random search sprays points everywhere.

BO comes with no guarantee of finding the global optimum. It explores the whole range, which helps it avoid getting stuck, but nothing promises the best point. We do not call it "global".

The Shields et al. quote: the paper spells it "decisionmaking", one word. The slide writes "decision making".

Online experiments, in plain words. Facebook tuned two systems. A ranking system: the order in which items are shown to users. And its server software: the compiler flags, settings of the compiler that change how fast the servers run. Each try is a live test on real traffic, so every result is noisy (Letham et al., 2019).

Constraints, in plain words. The best yield may need a temperature the reactor cannot take, for example a hot spot above its limit. We can only find out by running the experiment. So a second GP learns that limit from the same experiments, and the acquisition is multiplied by the probability of staying within it. BO then proposes only runs likely to be safe.

The 70 °C limit and the rough model are made-up examples on the reactor. The batch is qLogEI on the GP after three experiments. The Pareto front is computed from the kinetics.

What is x_{n+1} = argmax_x sigma(x) doing? It reads: the next experiment is the input where the GP's uncertainty sigma(x) is largest, the widest point of the band. No mean in it at all: active learning does not care where the yield is high, only where the model is unsure.