> ## Documentation Index
> Fetch the complete documentation index at: https://docs.priorlabs.ai/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> TabPFN-3 and later versions support up to 1,000,000 rows, subject to feature count and checkpoint/API limits.
> For large datasets, use per-estimator subsampling, e.g. inference_config={"SUBSAMPLE_SAMPLES": 100_000}, in TabPFNClassifier or TabPFNRegressor from tabpfn or tabpfn_client.
> Pass raw pandas DataFrames to fit and predict. Categorical strings/categories, raw text, and missing feature values are handled automatically; no manual integer/one-hot encoding, imputation, scaling, or outlier removal is needed.

# Bayesian Optimization with TabPFN Extensions

> Use TabPFN as a Bayesian optimization surrogate via tabpfn-extensions and compare it against a BoTorch GP and random search on Michalewicz-2.

By
Klemens Flöge[LinkedIn](https://www.linkedin.com/in/klemens-fl%C3%B6ge/)Tuana Çelik[LinkedIn](https://www.linkedin.com/in/tuanacelik/)[X](https://x.com/tuanacelik)

[Open in Colab](https://colab.research.google.com/github/PriorLabs/tabpfn-cookbook/blob/main/notebooks/bayesian_optimization.ipynb)

*Use TabPFN as the surrogate model inside a Bayesian optimization loop.*

This cookbook turns the `tabpfn-extensions` Bayesian optimization example into a step-by-step notebook. We optimize the 2D Michalewicz benchmark and compare TabPFN-driven search against two baselines under the same evaluation budget: BoTorch's Gaussian process with LogEI, the standard choice for this kind of problem, and random search. Along the way we show how `propose_next_point()` uses the predictive distribution from TabPFN to compute Expected Improvement (EI).

A single run tells you very little — the starting design alone can decide the outcome. So we repeat the whole experiment **5 times** with different initial designs and report the mean with a min–max band.

This is a toy example. Michalewicz-2 is a cheap synthetic function in two dimensions, and 5 repeats of 50 evaluations is a small budget. The notebook shows how to put TabPFN into a Bayesian optimization loop; it is not a benchmark, and it is not representative of many real-world or higher-dimensional BO problems. Which method wins depends on the function and its dimension: in our larger benchmark the GP was ahead early on smoother problems such as Hartmann-6.

Relevant resources:

* [`tabpfn-extensions` repository](https://github.com/PriorLabs/tabpfn-extensions)
* [Bayesian optimization example script in `tabpfn-extensions`](https://github.com/PriorLabs/tabpfn-extensions/blob/main/examples/bayesian_optimization/bayesian_optimization.py)
* [`PFNs4BO` paper / reference implementation](https://github.com/automl/PFNs4BO)
* [TabPFN repo](https://github.com/PriorLabs/TabPFN)

## Setup

*Install the full TabPFN package plus the Bayesian optimization extras from `tabpfn-extensions`.*

This example uses the local PyTorch-backed TabPFN implementation, because the acquisition function reads TabPFN's predicted distribution directly. With `tabpfn>=9.0.0` the default model is TabPFN 3.5. The extras pull in BoTorch, which provides the GP baseline and the benchmark function.

```python theme={null}
%pip install -q -U "tabpfn-extensions[bayesian_optimization]" "tabpfn>=9.0.0" matplotlib
```

*TabPFN as the surrogate, BoTorch for the GP baseline and the benchmark objective, and Matplotlib for the comparison plot.*

```python theme={null}
import warnings

# botorch triggers a torch.jit deprecation warning on import; it is harmless here.
warnings.filterwarnings("ignore", category=FutureWarning, message=r".*torch\.jit\.script.*")

import matplotlib.pyplot as plt
import numpy as np
import torch
from botorch.acquisition import LogExpectedImprovement
from botorch.fit import fit_gpytorch_mll
from botorch.models import SingleTaskGP
from botorch.models.transforms import Normalize, Standardize
from botorch.optim import optimize_acqf
from botorch.test_functions import Michalewicz
from gpytorch.mlls import ExactMarginalLogLikelihood

from tabpfn import TabPFNRegressor
from tabpfn_extensions.bayesian_optimization import propose_next_point
```

## The Optimization Problem

Michalewicz-2 is a two-dimensional benchmark with steep, narrow valleys separated by flat plateaus on `[0, π]^2`. After negation its optimum is `1.8013` at about `(2.20, 1.57)`. The plateaus carry almost no signal, so a stationary GP kernel has little to go on early, and random search rarely lands in the right valley.

The TabPFN surrogate predicts a **full bar distribution** over the objective value. `propose_next_point()` computes Expected Improvement exactly on that distribution — no Gaussian assumption — for a large batch of random candidates, then refines the most promising ones by sampling around them with a shrinking Gaussian. That optimizer is gradient-free, so it needs nothing special from the regressor.

Two details worth calling out:

* `negate=True` turns the minimization benchmark into a maximization problem, which is what EI expects; `optimal_value` follows the sign.
* The optimizer searches the unit cube `[0, 1]^2`, but Michalewicz lives on `[0, π]^2`, so every candidate is mapped onto the problem's own bounds before evaluation.

```python theme={null}
N_INIT = 10  # scrambled-Sobol points that every method starts from
N_BO_STEPS = 40  # one objective evaluation per step
N_SEEDS = 5  # independent repeats, each with its own initial design
N_ESTIMATORS = 8  # TabPFN ensemble size
GAP_FLOOR = 1e-4  # the log axis needs a positive floor

DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Device: {DEVICE}")

# EI maximizes the objective, so we negate Michalewicz to turn its optimum into a maximum.
objective = Michalewicz(dim=2, negate=True).to(DEVICE)
LO, HI = objective.bounds[0], objective.bounds[1]
print(f"Objective optimum: {objective.optimal_value:.4f} on {LO.tolist()}..{HI.tolist()}")


def evaluate(unit_x: torch.Tensor) -> torch.Tensor:
    """Evaluate the benchmark on points given in the unit cube."""
    return objective(LO + unit_x * (HI - LO))
```

```console theme={null}
Device: cpu
Objective optimum: 1.8013 on [0.0, 0.0]..[3.141592653589793, 3.141592653589793]
```

*What the optimizers are up against: Michalewicz-2 over its full domain.*

The landscape below is the negated objective, so brighter is better. Almost the whole square is a flat plateau; the optimum (star) sits where two narrow ridges cross.

```python theme={null}
GRID = 200
axis = torch.linspace(0, 1, GRID, device=DEVICE)
gx, gy = torch.meshgrid(axis, axis, indexing="xy")
landscape = evaluate(torch.stack([gx.flatten(), gy.flatten()], dim=-1)).reshape(GRID, GRID).cpu().numpy()
extent = [LO[0].item(), HI[0].item(), LO[1].item(), HI[1].item()]
x_opt = objective.optimizers[0].cpu().numpy()

fig, ax = plt.subplots(figsize=(5.2, 4.4), facecolor="#fcfcfb")
im = ax.imshow(landscape, origin="lower", extent=extent, cmap="viridis", aspect="equal")
ax.scatter(*x_opt, marker="*", s=220, color="white", edgecolor="#0b0b0b", linewidth=0.8, zorder=3)
fig.colorbar(im, ax=ax, shrink=0.85, label="objective (negated Michalewicz)")
ax.set_title("Michalewicz-2", fontsize=11, color="#0b0b0b", loc="left", fontweight="bold", pad=8)
ax.set_xlabel("$x_1$", fontsize=9, color="#52514e")
ax.set_ylabel("$x_2$", fontsize=9, color="#52514e")
ax.tick_params(colors="#898781", labelsize=8, length=3)
fig.tight_layout()
plt.show()
```

![The Optimization Problem](https://raw.githubusercontent.com/PriorLabs/tabpfn-cookbook/main/visuals/bayesian_optimization/plot-01.png)

## Build the TabPFN Surrogate

*An ordinary `TabPFNRegressor` is all it takes.*

Nothing in the loop needs gradients with respect to the inputs, so we use the plain regressor with its full ensemble of 8 estimators. Those are the settings we validated on the continuous BoTorch benchmark suite (eight synthetic functions, 32 seeds, 250 evaluations each): an 8-estimator TabPFN with exact EI and this sampled optimizer had the best mean rank against BoTorch's GP with EI and LogEI at 250 evaluations, while the GP led on the smooth single-basin functions (Branin, Hartmann-3, Rosenbrock-like valleys) early on. Michalewicz is one of the multimodal functions where TabPFN was clearly ahead, by about 7× in mean regret at 50 evaluations, so it is where the difference shows within a notebook-sized budget.

Each repeat gets its own surrogate, seeded with that repeat's index, so the runs are independent. Keep TabPFN on `cpu` or `cuda`; Apple's `mps` backend is an order of magnitude slower here.

```python theme={null}
def make_surrogate(seed: int) -> TabPFNRegressor:
    return TabPFNRegressor(n_estimators=N_ESTIMATORS, device=DEVICE, random_state=seed)
```

## Run Bayesian Optimization

*Seed with a Sobol design, then let each method propose the next evaluation point.*

Each TabPFN iteration fits the surrogate on all observed evaluations so far, scores 2048 random candidates with Expected Improvement in one forward pass, and refines the top 16 by sampling around them for three rounds before returning the next point to evaluate. The GP baseline is BoTorch's `SingleTaskGP` with LogEI, maximized with `optimize_acqf`, in the configuration of Ament et al. (NeurIPS 2023).

We run that loop `N_SEEDS = 5` times. Within a repeat, all three methods start from the **same** `N_INIT` scrambled-Sobol evaluations, so the curves can only diverge once the acquisition strategy takes over. A Sobol sequence is a quasi-random design that covers the search space more evenly than uniform random points; scrambling randomizes it, so each repeat gets a different but still well-spread start. TabPFN takes nearly all of the runtime: one repeat of its loop takes about 9 minutes on 2 laptop CPU threads and about a minute on an L4 GPU, while the GP needs a few seconds. In a real campaign each evaluation of the objective usually costs far more than either.

```python theme={null}
def run_tabpfn(
    init_x: torch.Tensor, init_y: torch.Tensor, seed: int
) -> tuple[torch.Tensor, torch.Tensor]:
    """Run the TabPFN-EI loop from a fixed init and return every evaluated x and y."""
    reg = make_surrogate(seed)
    train_x, train_y = init_x.clone(), init_y.clone()
    for _ in range(N_BO_STEPS):
        next_x = propose_next_point(reg, train_x, train_y)
        train_x = torch.cat([train_x, next_x.unsqueeze(0)])
        train_y = torch.cat([train_y, evaluate(next_x.unsqueeze(0))])
    return train_x, train_y


def run_gp_logei(
    init_x: torch.Tensor, init_y: torch.Tensor, seed: int
) -> tuple[torch.Tensor, torch.Tensor]:
    """BoTorch's GP with LogEI: refit the GP each round, maximize LogEI with L-BFGS-B."""
    dim = init_x.shape[1]
    unit_bounds = torch.stack(
        [torch.zeros(dim, dtype=torch.double), torch.ones(dim, dtype=torch.double)]
    )
    train_x = init_x.double().cpu()
    train_y = init_y.double().cpu().unsqueeze(-1)
    for step in range(N_BO_STEPS):
        gp = SingleTaskGP(  # Matern-5/2 ARD kernel by default
            train_x,
            train_y,
            input_transform=Normalize(d=dim),
            outcome_transform=Standardize(m=1),
        )
        fit_gpytorch_mll(ExactMarginalLogLikelihood(gp.likelihood, gp))
        acqf = LogExpectedImprovement(gp, best_f=train_y.max())
        next_x, _ = optimize_acqf(
            acqf,
            bounds=unit_bounds,
            q=1,
            num_restarts=16,
            raw_samples=512,
            # A fresh candidate draw per step, reproducibly: one seed per (repeat, step).
            options={"seed": 1000 + seed * 100 + step},
        )
        next_y = evaluate(next_x.to(DEVICE).float()).double().cpu().unsqueeze(-1)
        train_x = torch.cat([train_x, next_x])
        train_y = torch.cat([train_y, next_y])
    return train_x.float().to(DEVICE), train_y.squeeze(-1).float().to(DEVICE)


def run_random(init_x: torch.Tensor, init_y: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
    extra = torch.rand(N_BO_STEPS, init_x.shape[1], device=DEVICE)
    return torch.cat([init_x, extra]), torch.cat([init_y, evaluate(extra)])


def gap_to_optimum(y: torch.Tensor) -> np.ndarray:
    """Best-so-far distance to the known optimum — lower is better."""
    best = np.maximum.accumulate(y.detach().cpu().numpy())
    return np.maximum(objective.optimal_value - best, GAP_FLOOR)


RUNNERS = {
    "TabPFN-EI": lambda x, y, seed: run_tabpfn(x, y, seed),
    "GP-LogEI (BoTorch)": lambda x, y, seed: run_gp_logei(x, y, seed),
    "Random search": lambda x, y, seed: run_random(x, y),
}
gaps = {name: [] for name in RUNNERS}
points = {name: [] for name in RUNNERS}  # evaluated x per repeat, in the unit cube

for seed in range(N_SEEDS):
    # One shared scrambled-Sobol init per repeat: every method sees the same start.
    sobol = torch.quasirandom.SobolEngine(objective.dim, scramble=True, seed=seed)
    init_x = sobol.draw(N_INIT).to(DEVICE)
    init_y = evaluate(init_x)

    for name, runner in RUNNERS.items():
        torch.manual_seed(1000 + seed)
        xs, ys = runner(init_x, init_y, seed)
        gaps[name].append(gap_to_optimum(ys))
        points[name].append(xs.detach().cpu().numpy())

    print(
        f"repeat {seed}: "
        + " | ".join(f"{name} gap {gaps[name][-1][-1]:9.4g}" for name in RUNNERS)
    )

gaps = {name: np.array(runs) for name, runs in gaps.items()}  # (N_SEEDS, N_INIT + N_BO_STEPS)
```

```console theme={null}
repeat 0: TabPFN-EI gap 0.0002769 | GP-LogEI (BoTorch) gap    0.5287 | Random search gap    0.6139
repeat 1: TabPFN-EI gap 0.0002273 | GP-LogEI (BoTorch) gap    0.1103 | Random search gap    0.8131
repeat 2: TabPFN-EI gap  0.004078 | GP-LogEI (BoTorch) gap 0.0003413 | Random search gap      0.37
repeat 3: TabPFN-EI gap    0.0001 | GP-LogEI (BoTorch) gap  0.001846 | Random search gap    0.7984
repeat 4: TabPFN-EI gap 0.0001964 | GP-LogEI (BoTorch) gap    0.4384 | Random search gap    0.8819
```

## Compare the Three Methods

*Same objective, same budget, same starting points — only the choice of the next point differs.*

We report the **gap to the optimum** (`optimum - best so far`, the simple regret) on a log axis rather than the raw objective. Lower is better.

```python theme={null}
for name, runs in gaps.items():
    final = runs[:, -1]
    print(
        f"{name:<20} final gap over {N_SEEDS} repeats: "
        f"mean {final.mean():9.4g} | median {np.median(final):9.4g} | best {final.min():9.4g}"
    )
```

```console theme={null}
TabPFN-EI            final gap over 5 repeats: mean 0.0009757 | median 0.0002273 | best    0.0001
GP-LogEI (BoTorch)   final gap over 5 repeats: mean    0.2159 | median    0.1103 | best 0.0003413
Random search        final gap over 5 repeats: mean    0.6954 | median    0.7984 | best      0.37
```

```python theme={null}
evals = np.arange(1, N_INIT + N_BO_STEPS + 1)

fig, ax = plt.subplots(figsize=(7.2, 4.2), facecolor="#fcfcfb")
ax.set_facecolor("#fcfcfb")
ax.set_yscale("log")

# Mean over repeats, band spans min-max across them.
for name, color in [
    ("TabPFN-EI", "#2a78d6"),
    ("GP-LogEI (BoTorch)", "#eb6834"),
    ("Random search", "#1baf7a"),
]:
    runs = gaps[name]
    ax.fill_between(evals, runs.min(0), runs.max(0), color=color, alpha=0.15, lw=0)
    ax.plot(evals, runs.mean(0), color=color, lw=2, label=name)
ax.axvline(N_INIT, color="#898781", lw=1, ls=(0, (2, 3)))

ax.set_title("Michalewicz-2", fontsize=11, color="#0b0b0b", loc="left", fontweight="bold", pad=8)
ax.grid(visible=True, axis="y", color="#e1e0d9", linewidth=0.6)
ax.set_axisbelow(True)
for side in ("top", "right"):
    ax.spines[side].set_visible(False)
for side in ("left", "bottom"):
    ax.spines[side].set_color("#c3c2b7")
ax.tick_params(colors="#898781", labelsize=8, length=3)
ax.set_xlim(1, N_INIT + N_BO_STEPS)
ax.set_xlabel("evaluation", fontsize=9, color="#52514e")
ax.set_ylabel("gap to optimum (log)", fontsize=9, color="#52514e")
ax.legend(frameon=False, fontsize=9.5, labelcolor="#0b0b0b")

fig.suptitle(
    f"Best-so-far gap to optimum — mean over {N_SEEDS} repeats, bands are min-max"
    "   (dotted line: end of shared Sobol init)",
    fontsize=11,
    color="#0b0b0b",
    x=0.02,
    ha="left",
    y=1.02,
)
fig.tight_layout()
plt.show()
```

![Compare the Three Methods](https://raw.githubusercontent.com/PriorLabs/tabpfn-cookbook/main/visuals/bayesian_optimization/plot-02.png)

## Where Each Method Searched

*The same landscape, with every point each method evaluated in one repeat.*

We pick the repeat with TabPFN's median final gap, so the picture is typical rather than its best case. Grey crosses are the shared Sobol start; colored dots are the 40 points each method chose, darker for later ones.

```python theme={null}
rep = int(np.argsort(gaps["TabPFN-EI"][:, -1])[N_SEEDS // 2])
colors = {"TabPFN-EI": "Blues", "GP-LogEI (BoTorch)": "Oranges", "Random search": "Greens"}
scale = (HI - LO).cpu().numpy()
lo = LO.cpu().numpy()

fig, axes = plt.subplots(1, 3, figsize=(12, 4.2), facecolor="#fcfcfb", sharey=True)
for ax, (name, cmap) in zip(axes, colors.items()):
    xs = lo + points[name][rep] * scale
    ax.imshow(landscape, origin="lower", extent=extent, cmap="Greys_r", aspect="equal", alpha=0.55)
    ax.scatter(*xs[:N_INIT].T, marker="x", s=30, color="#52514e", linewidth=1)
    ax.scatter(
        *xs[N_INIT:].T,
        c=np.arange(N_BO_STEPS),
        cmap=cmap,
        vmin=-N_BO_STEPS // 2,
        s=28,
        edgecolor="#0b0b0b",
        linewidth=0.4,
    )
    ax.scatter(*x_opt, marker="*", s=220, color="white", edgecolor="#0b0b0b", linewidth=0.8, zorder=3)
    ax.set_title(
        f"{name} — final gap {gaps[name][rep, -1]:.2g}",
        fontsize=10,
        color="#0b0b0b",
        loc="left",
        fontweight="bold",
    )
    ax.set_xlabel("$x_1$", fontsize=9, color="#52514e")
    ax.tick_params(colors="#898781", labelsize=8, length=3)
axes[0].set_ylabel("$x_2$", fontsize=9, color="#52514e")
fig.suptitle(f"Evaluated points in repeat {rep}", fontsize=11, color="#0b0b0b", x=0.02, ha="left")
fig.tight_layout()
plt.show()
```

![Where Each Method Searched](https://raw.githubusercontent.com/PriorLabs/tabpfn-cookbook/main/visuals/bayesian_optimization/plot-03.png)

## Takeaways

* `tabpfn-extensions` provides the Bayesian optimization loop primitive, `propose_next_point()`, and it works with a plain `TabPFNRegressor`: exact EI on TabPFN's predicted distribution, maximized by a gradient-free sampled optimizer.
* On Michalewicz-2 with 50 evaluations, TabPFN-EI ends with a mean gap of 0.0010 (median 0.0002), against 0.22 for GP-LogEI and 0.70 for random search. TabPFN is ahead of the GP on four of the five repeats; on the fifth the GP gets closer (0.0003 against 0.004). Over 32 repeats the picture holds: TabPFN-EI gets within 1e-3 of the optimum on 20 of 32, GP-LogEI on 6, and the GP stays stuck above 0.1 on 12.
* The picture is function-dependent. In our larger benchmark the GP is ahead early on smooth single-basin functions such as Branin and Hartmann-3 and wins on final precision there; TabPFN leads on multimodal functions like this one and Ackley, and overall from about 100 evaluations on, once its context has grown. Use more evaluations and more repeats for a clean comparison on your own problem.
* For more background, start with the upstream [example](https://github.com/PriorLabs/tabpfn-extensions/blob/main/examples/bayesian_optimization/bayesian_optimization.py) and the [`tabpfn-extensions` repo](https://github.com/PriorLabs/tabpfn-extensions).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.